hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
13d5ebf1966fb98094358874f434b429b88f6306
1,316
cpp
C++
luogu/P1160.cpp
delphi122/knowledge_planet
e86cb8f9aa47ef8918cde0e814984a6535023c21
[ "Apache-2.0" ]
1
2020-07-24T03:07:08.000Z
2020-07-24T03:07:08.000Z
luogu/P1160.cpp
delphi122/knowledge_planet
e86cb8f9aa47ef8918cde0e814984a6535023c21
[ "Apache-2.0" ]
null
null
null
luogu/P1160.cpp
delphi122/knowledge_planet
e86cb8f9aa47ef8918cde0e814984a6535023c21
[ "Apache-2.0" ]
null
null
null
// // Created by yangtao on 20-5-29. // #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <map> using namespace std; struct Node { Node *left, *right; int no; }; map<int, Node*> s; int n,m; Node *h , *p; int main() { cin >> n; h = new Node; Node *t = new Node; t->no = 1; h->right = t; t->left = h; s[1] = t; for(int i = 2; i <= n; i++) { Node *node = new Node; node->no = i; int k, q; scanf("%d%d", &k, &q); p = h->right; s[i] = node; p = s[k]; if(q == 0) { node->left = p->left; node->right = p; p->left->right = node; p->left = node; } else { node->right = p->right; node->left = p; p->right = node; if(node->right) node->right->left = node; } } cin >> m; for(int i = 0 ; i < m; i++) { int q; scanf("%d", &q); if(s.find(q) == s.end()) continue; p = s[q]; s.erase(q); p->left->right = p->right; if(p->right) { p->right->left = p->left; } } p = h->right; while(p) { printf("%d ", p->no); p = p->right; } return 0; }
18.535211
42
0.395137
delphi122
13dfc95fad116c2c0a698cf25fcdf84da2d814e9
2,902
cpp
C++
src/libcore/src/ccmrt/system/SocketTagger.cpp
sparkoss/ccm
9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d
[ "Apache-2.0" ]
6
2018-05-08T10:08:21.000Z
2021-11-13T13:22:58.000Z
src/libcore/src/ccmrt/system/SocketTagger.cpp
sparkoss/ccm
9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d
[ "Apache-2.0" ]
1
2018-05-08T10:20:17.000Z
2018-07-23T05:19:19.000Z
src/libcore/src/ccmrt/system/SocketTagger.cpp
sparkoss/ccm
9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d
[ "Apache-2.0" ]
4
2018-03-13T06:21:11.000Z
2021-06-19T02:48:07.000Z
//========================================================================= // Copyright (C) 2018 The C++ Component Model(CCM) Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "ccmrt/system/SocketTagger.h" #include "ccm.io.IFileDescriptor.h" #include <ccmlogger.h> using ccm::io::IFileDescriptor; namespace ccmrt { namespace system { CCM_INTERFACE_IMPL_1(SocketTagger, SyncObject, ISocketTagger); AutoPtr<ISocketTagger> SocketTagger::GetOrSet( /* [in] */ ISocketTagger* tagger) { class _SocketTagger : public SocketTagger { public: ECode Tag( /* [in] */ IFileDescriptor* socketDescriptor) override { return NOERROR; } ECode Untag( /* [in] */ IFileDescriptor* socketDescriptor) override { return NOERROR; } }; static AutoPtr<ISocketTagger> sTagger = new _SocketTagger(); if (tagger != nullptr) { sTagger = tagger; } return sTagger; } ECode SocketTagger::Tag( /* [in] */ ISocket* socket) { Boolean closed; if (socket->IsClosed(&closed), !closed) { AutoPtr<IFileDescriptor> fd; socket->GetFileDescriptor(&fd); return Tag(fd); } return NOERROR; } ECode SocketTagger::Untag( /* [in] */ ISocket* socket) { Boolean closed; if (socket->IsClosed(&closed), !closed) { AutoPtr<IFileDescriptor> fd; socket->GetFileDescriptor(&fd); return Untag(fd); } return NOERROR; } ECode SocketTagger::Tag( /* [in] */ IDatagramSocket* socket) { Boolean closed; if (socket->IsClosed(&closed), !closed) { AutoPtr<IFileDescriptor> fd; socket->GetFileDescriptor(&fd); return Tag(fd); } return NOERROR; } ECode SocketTagger::Untag( /* [in] */ IDatagramSocket* socket) { Boolean closed; if (socket->IsClosed(&closed), !closed) { AutoPtr<IFileDescriptor> fd; socket->GetFileDescriptor(&fd); return Untag(fd); } return NOERROR; } ECode SocketTagger::Set( /* [in] */ ISocketTagger* tagger) { if (tagger == nullptr) { Logger::E("SocketTagger", "tagger == null"); return ccm::core::E_NULL_POINTER_EXCEPTION; } GetOrSet(tagger); return NOERROR; } } }
25.017241
75
0.599931
sparkoss
13e09d8dc5005b4bf52881df046f474e42469bf2
1,595
cpp
C++
src/tuning/coefficients.cpp
pyxis-roc/sass-math
0d6d4413e89101366c5b49d62c466e0567bef735
[ "MIT" ]
null
null
null
src/tuning/coefficients.cpp
pyxis-roc/sass-math
0d6d4413e89101366c5b49d62c466e0567bef735
[ "MIT" ]
1
2021-09-23T17:46:24.000Z
2021-09-23T17:46:24.000Z
src/tuning/coefficients.cpp
pyxis-roc/sass-math
0d6d4413e89101366c5b49d62c466e0567bef735
[ "MIT" ]
null
null
null
#include "coefficients.hpp" #include "bias.hpp" #include <cstddef> enum direction { DOWN, UP, UNKNOWN }; std::tuple<uint64_t, std::array<uint32_t, 3>, counters> coefficient_search(const eval_t<uint64_t, const std::array<uint32_t, 3> &> &eval, const std::array<bool, 3> &negated, const std::array<uint32_t, 3> &initial) { counters count; uint64_t bias; std::array<uint32_t, 3> coefficients = initial; const auto bias_eval = [&coefficients, &eval](uint64_t bias) -> counters { return eval(bias, coefficients); }; std::array<direction, 3> directions = {UNKNOWN, UNKNOWN, UNKNOWN}; while (true) { std::tie(bias, count) = bias_search(bias_eval); if (count.regions() == 0u) break; if (count.regions() > 3u) break; std::size_t edit = count.regions() - 1u; direction dir = (count.last() == counters::NEGATIVE) ? UP : DOWN; if (negated[edit]) dir = (dir == DOWN) ? UP : DOWN; if (directions[edit] == UNKNOWN) { directions[edit] = dir; } else if (directions[edit] != dir) { if (++edit > 2u) break; } if (directions[edit] == DOWN) coefficients[edit]--; else coefficients[edit]++; // UP is arbitrary for UNKNOWN case for (std::size_t i = 0; i < edit; i++) { directions[i] = UNKNOWN; } } return std::make_tuple(bias, coefficients, count); }
23.115942
81
0.530408
pyxis-roc
13e1b4b357987a32394e5473d995d91316e7bb90
1,197
cpp
C++
Aphelion/Src/Aphelion/Renderer/old/Renderer.cpp
antjowie/AphelionWeb
e616806844bb06914b32395b2e4998ac518b3773
[ "MIT" ]
null
null
null
Aphelion/Src/Aphelion/Renderer/old/Renderer.cpp
antjowie/AphelionWeb
e616806844bb06914b32395b2e4998ac518b3773
[ "MIT" ]
null
null
null
Aphelion/Src/Aphelion/Renderer/old/Renderer.cpp
antjowie/AphelionWeb
e616806844bb06914b32395b2e4998ac518b3773
[ "MIT" ]
null
null
null
#include "Aphelion/Renderer/Renderer.h" #include <glm/gtc/type_ptr.hpp> #include "Aphelion/Renderer/RenderCommand.h" #include "Aphelion/Renderer/Renderer2D.h" namespace ap { struct RendererData { // PerspectiveCamera camera; glm::mat4 view; glm::mat4 projection; }; static RendererData data; void Renderer::Init() { RenderCommand::Init(); Renderer2D::Init(); } void Renderer::Deinit() { Renderer2D::Deinit(); } void Renderer::OnWindowResize(uint32_t width, uint32_t height) { RenderCommand::SetViewport(0, 0, width, height); } void Renderer::BeginScene(const PerspectiveCamera& camera) { data.view = camera.GetViewMatrix(); data.projection = camera.GetProjectionMatrix(); } void Renderer::EndScene() {} void Renderer::Submit(const ShaderRef& shader, const VertexArrayRef& vertexArray, const glm::mat4& transform) { // shader->Bind(); shader->SetMat4("aTransform", glm::value_ptr(transform)); shader->SetMat4("aVP", glm::value_ptr(data.projection * data.view)); vertexArray->Bind(); RenderCommand::DrawIndexed(vertexArray, vertexArray->GetIndexBuffer()->GetCount()); } } // namespace ap
25.468085
72
0.687552
antjowie
13e675b8faae7b8ca0101fe15d29d0b5e109a50d
1,937
cpp
C++
Real-Time Corruptor/BizHawk_RTC/waterbox/pcfx/input/mouse.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
45
2017-07-24T05:31:06.000Z
2019-03-29T12:23:57.000Z
Real-Time Corruptor/BizHawk_RTC/waterbox/pcfx/input/mouse.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
7
2019-01-14T14:46:46.000Z
2019-01-25T20:57:05.000Z
Real-Time Corruptor/BizHawk_RTC/waterbox/pcfx/input/mouse.cpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
10
2017-07-24T02:11:43.000Z
2018-12-27T20:49:37.000Z
/******************************************************************************/ /* Mednafen NEC PC-FX Emulation Module */ /******************************************************************************/ /* mouse.cpp: ** Copyright (C) 2007-2016 Mednafen Team ** ** This program is free software; you can redistribute it and/or ** modify it under the terms of the GNU General Public License ** as published by the Free Software Foundation; either version 2 ** of the License, or (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software Foundation, Inc., ** 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "../pcfx.h" #include "../input.h" #include "mouse.h" namespace MDFN_IEN_PCFX { class PCFX_Input_Mouse : public PCFX_Input_Device { public: PCFX_Input_Mouse(int which) { dx = 0; dy = 0; button = 0; } virtual ~PCFX_Input_Mouse() override { } virtual uint32 ReadTransferTime(void) override { return (1536); } virtual uint32 WriteTransferTime(void) override { return (1536); } virtual uint32 Read(void) override { return FX_SIG_MOUSE << 28 | button << 16 | dx << 8 | dy; } virtual void Write(uint32 data) override { } virtual void Power(void) override { button = 0; dx = 0; dy = 0; } virtual void Frame(uint32_t data) override { dx = data; dy = data >> 8; button = data >> 16 & 3; } private: int8 dx, dy; // 76543210 // ......RL uint8 button; }; PCFX_Input_Device *PCFXINPUT_MakeMouse(int which) { return new PCFX_Input_Mouse(which); } }
21.764045
80
0.620031
redscientistlabs
13e74812db5607c4ddf8cda57e390643adb2baba
1,646
cpp
C++
XBT/misc/xcc_z.cpp
3evils/pub
3f0f8e39e6297657ca7e088c0e3250f5c52c9e70
[ "WTFPL" ]
null
null
null
XBT/misc/xcc_z.cpp
3evils/pub
3f0f8e39e6297657ca7e088c0e3250f5c52c9e70
[ "WTFPL" ]
null
null
null
XBT/misc/xcc_z.cpp
3evils/pub
3f0f8e39e6297657ca7e088c0e3250f5c52c9e70
[ "WTFPL" ]
null
null
null
#include "xbt/xcc_z.h" #include <cstdio> #include <string.h> #include <zlib.h> #include "stream_int.h" shared_data xcc_z::gunzip(data_ref s) { if (s.size() < 18) return shared_data(); shared_data d(read_int_le(4, s.end() - 4)); z_stream stream; stream.zalloc = NULL; stream.zfree = NULL; stream.opaque = NULL; stream.next_in = const_cast<unsigned char*>(s.begin()) + 10; stream.avail_in = s.size() - 18; stream.next_out = d.data(); stream.avail_out = d.size(); return stream.next_out && Z_OK == inflateInit2(&stream, -MAX_WBITS) && Z_STREAM_END == inflate(&stream, Z_FINISH) && Z_OK == inflateEnd(&stream) ? d : shared_data(); } shared_data xcc_z::gzip(data_ref s) { unsigned long cb_d = s.size() + (s.size() + 999) / 1000 + 12; shared_data d(10 + cb_d + 8); unsigned char* w = d.data(); *w++ = 0x1f; *w++ = 0x8b; *w++ = Z_DEFLATED; *w++ = 0; *w++ = 0; *w++ = 0; *w++ = 0; *w++ = 0; *w++ = 0; *w++ = 3; { z_stream stream; stream.zalloc = NULL; stream.zfree = NULL; stream.opaque = NULL; deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -MAX_WBITS, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY); stream.next_in = const_cast<unsigned char*>(s.begin()); stream.avail_in = s.size(); stream.next_out = w; stream.avail_out = cb_d; deflate(&stream, Z_FINISH); deflateEnd(&stream); w = stream.next_out; } w = write_int_le(4, w, crc32(crc32(0, NULL, 0), s.data(), s.size())); w = write_int_le(4, w, s.size()); return d.substr(0, w - d.data()); } /* void xcc_z::gzip_out(data_ref s) { gzFile f = gzdopen(fileno(stdout), "wb"); gzwrite(f, s.data(), s.size()); gzflush(f, Z_FINISH); } */
23.183099
106
0.631835
3evils
13e7a9f37a885b46be168375bc57e9bd92706076
1,724
hxx
C++
opencascade/GeomToStep_MakeAxis2Placement2d.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
opencascade/GeomToStep_MakeAxis2Placement2d.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
opencascade/GeomToStep_MakeAxis2Placement2d.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
// Created on: 1994-08-26 // Created by: Frederic MAUPAS // Copyright (c) 1994-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _GeomToStep_MakeAxis2Placement2d_HeaderFile #define _GeomToStep_MakeAxis2Placement2d_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <GeomToStep_Root.hxx> class StepGeom_Axis2Placement2d; class gp_Ax2; class gp_Ax22d; //! This class implements the mapping between classes //! Axis2Placement from Geom and Ax2, Ax22d from gp, and the class //! Axis2Placement2d from StepGeom which describes an //! axis2_placement_2d from Prostep. class GeomToStep_MakeAxis2Placement2d : public GeomToStep_Root { public: DEFINE_STANDARD_ALLOC Standard_EXPORT GeomToStep_MakeAxis2Placement2d(const gp_Ax2& A); Standard_EXPORT GeomToStep_MakeAxis2Placement2d(const gp_Ax22d& A); Standard_EXPORT const Handle(StepGeom_Axis2Placement2d)& Value() const; protected: private: Handle(StepGeom_Axis2Placement2d) theAxis2Placement2d; }; #endif // _GeomToStep_MakeAxis2Placement2d_HeaderFile
23.944444
81
0.792343
mgreminger
13e8893ce8fad6e8dc2b712daacb3fd0c77947c7
31,390
cpp
C++
neo/tools/kademlia/kademlia/Indexed.cpp
vic3t3chn0/OpenKrown
201c8fb6895cb0439e39c984d2fbc2c2eaf185b4
[ "MIT" ]
1
2018-11-07T22:44:23.000Z
2018-11-07T22:44:23.000Z
neo/tools/kademlia/kademlia/Indexed.cpp
vic3t3chn0/OpenKrown
201c8fb6895cb0439e39c984d2fbc2c2eaf185b4
[ "MIT" ]
null
null
null
neo/tools/kademlia/kademlia/Indexed.cpp
vic3t3chn0/OpenKrown
201c8fb6895cb0439e39c984d2fbc2c2eaf185b4
[ "MIT" ]
null
null
null
// // This file is part of the aMule Project. // // Copyright (c) 2004-2011 Angel Vidal ( kry@amule.org ) // Copyright (c) 2004-2011 aMule Team ( admin@amule.org / http://www.amule.org ) // Copyright (c) 2003-2011 Barry Dunne (http://www.emule-project.net) // // Any parts of this program derived from the xMule, lMule or eMule project, // or contributed by third-party developers are copyrighted by their // respective authors. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA // // Note To Mods // /* Please do not change anything here and release it.. There is going to be a new forum created just for the Kademlia side of the client.. If you feel there is an error or a way to improve something, please post it in the forum first and let us look at it.. If it is a real improvement, it will be added to the offical client.. Changing something without knowing what all it does can cause great harm to the network if released in mass form.. Any mod that changes anything within the Kademlia side will not be allowed to advertise there client on the eMule forum.. */ #include "Indexed.h" #include <protocol/Protocols.h> #include <protocol/ed2k/Constants.h> #include <protocol/kad/Constants.h> #include <protocol/kad/Client2Client/UDP.h> #include <protocol/kad2/Client2Client/UDP.h> #include <common/Macros.h> #include <tags/FileTags.h> #include "../routing/Contact.h" #include "../net/KademliaUDPListener.h" #include "../utils/KadUDPKey.h" #include "../../CFile.h" #include "../../MemFile.h" #include "../../Preferences.h" #include "../../Logger.h" //////////////////////////////////////// using namespace Kademlia; //////////////////////////////////////// wxString CIndexed::m_kfilename; wxString CIndexed::m_sfilename; wxString CIndexed::m_loadfilename; CIndexed::CIndexed() { m_sfilename = thePrefs::GetConfigDir() + wxT("src_index.dat"); m_kfilename = thePrefs::GetConfigDir() + wxT("key_index.dat"); m_loadfilename = thePrefs::GetConfigDir() + wxT("load_index.dat"); m_lastClean = time(NULL) + (60*30); m_totalIndexSource = 0; m_totalIndexKeyword = 0; m_totalIndexNotes = 0; m_totalIndexLoad = 0; ReadFile(); } void CIndexed::ReadFile() { try { uint32_t totalLoad = 0; uint32_t totalSource = 0; uint32_t totalKeyword = 0; CFile load_file; if (CPath::FileExists(m_loadfilename) && load_file.Open(m_loadfilename, CFile::read)) { uint32_t version = load_file.ReadUInt32(); if (version < 2) { /*time_t savetime =*/ load_file.ReadUInt32(); // Savetime is unused now uint32_t numLoad = load_file.ReadUInt32(); while (numLoad) { CUInt128 keyID = load_file.ReadUInt128(); if (AddLoad(keyID, load_file.ReadUInt32())) { totalLoad++; } numLoad--; } } load_file.Close(); } CFile k_file; if (CPath::FileExists(m_kfilename) && k_file.Open(m_kfilename, CFile::read)) { uint32_t version = k_file.ReadUInt32(); if (version < 4) { time_t savetime = k_file.ReadUInt32(); if (savetime > time(NULL)) { CUInt128 id = k_file.ReadUInt128(); if (Kademlia::CKademlia::GetPrefs()->GetKadID() == id) { uint32_t numKeys = k_file.ReadUInt32(); while (numKeys) { CUInt128 keyID = k_file.ReadUInt128(); uint32_t numSource = k_file.ReadUInt32(); while (numSource) { CUInt128 sourceID = k_file.ReadUInt128(); uint32_t numName = k_file.ReadUInt32(); while (numName) { Kademlia::CKeyEntry* toAdd = new Kademlia::CKeyEntry(); toAdd->m_uKeyID = keyID; toAdd->m_uSourceID = sourceID; toAdd->m_bSource = false; toAdd->m_tLifeTime = k_file.ReadUInt32(); if (version >= 3) { toAdd->ReadPublishTrackingDataFromFile(&k_file); } uint32_t tagList = k_file.ReadUInt8(); while (tagList) { CTag* tag = k_file.ReadTag(); if (tag) { if (!tag->GetName().Cmp(TAG_FILENAME)) { if (toAdd->GetCommonFileName().IsEmpty()) { toAdd->SetFileName(tag->GetStr()); } delete tag; } else if (!tag->GetName().Cmp(TAG_FILESIZE)) { if (tag->IsBsob() && (tag->GetBsobSize() == 8)) { // We've previously wrongly saved BSOB uint64s to key_index.dat, // so we'll have to handle those here as well. Too bad ... toAdd->m_uSize = PeekUInt64(tag->GetBsob()); } else { toAdd->m_uSize = tag->GetInt(); } delete tag; } else if (!tag->GetName().Cmp(TAG_SOURCEIP)) { toAdd->m_uIP = tag->GetInt(); toAdd->AddTag(tag); } else if (!tag->GetName().Cmp(TAG_SOURCEPORT)) { toAdd->m_uTCPport = tag->GetInt(); toAdd->AddTag(tag); } else if (!tag->GetName().Cmp(TAG_SOURCEUPORT)) { toAdd->m_uUDPport = tag->GetInt(); toAdd->AddTag(tag); } else { toAdd->AddTag(tag); } } tagList--; } uint8_t load; if (AddKeyword(keyID, sourceID, toAdd, load)) { totalKeyword++; } else { delete toAdd; } numName--; } numSource--; } numKeys--; } } } } k_file.Close(); } CFile s_file; if (CPath::FileExists(m_sfilename) && s_file.Open(m_sfilename, CFile::read)) { uint32_t version = s_file.ReadUInt32(); if (version < 3) { time_t savetime = s_file.ReadUInt32(); if (savetime > time(NULL)) { uint32_t numKeys = s_file.ReadUInt32(); while (numKeys) { CUInt128 keyID = s_file.ReadUInt128(); uint32_t numSource = s_file.ReadUInt32(); while (numSource) { CUInt128 sourceID = s_file.ReadUInt128(); uint32_t numName = s_file.ReadUInt32(); while (numName) { Kademlia::CEntry* toAdd = new Kademlia::CEntry(); toAdd->m_bSource = true; toAdd->m_tLifeTime = s_file.ReadUInt32(); uint32_t tagList = s_file.ReadUInt8(); while (tagList) { CTag* tag = s_file.ReadTag(); if (tag) { if (!tag->GetName().Cmp(TAG_SOURCEIP)) { toAdd->m_uIP = tag->GetInt(); toAdd->AddTag(tag); } else if (!tag->GetName().Cmp(TAG_SOURCEPORT)) { toAdd->m_uTCPport = tag->GetInt(); toAdd->AddTag(tag); } else if (!tag->GetName().Cmp(TAG_SOURCEUPORT)) { toAdd->m_uUDPport = tag->GetInt(); toAdd->AddTag(tag); } else { toAdd->AddTag(tag); } } tagList--; } toAdd->m_uKeyID = keyID; toAdd->m_uSourceID = sourceID; uint8_t load; if (AddSources(keyID, sourceID, toAdd, load)) { totalSource++; } else { delete toAdd; } numName--; } numSource--; } numKeys--; } } } s_file.Close(); } m_totalIndexSource = totalSource; m_totalIndexKeyword = totalKeyword; m_totalIndexLoad = totalLoad; AddDebugLogLineN(logKadIndex, CFormat(wxT("Read %u source, %u keyword, and %u load entries")) % totalSource % totalKeyword % totalLoad); } catch (const CSafeIOException& err) { AddDebugLogLineC(logKadIndex, wxT("CSafeIOException in CIndexed::readFile: ") + err.what()); } catch (const CInvalidPacket& err) { AddDebugLogLineC(logKadIndex, wxT("CInvalidPacket Exception in CIndexed::readFile: ") + err.what()); } catch (const wxString& e) { AddDebugLogLineC(logKadIndex, wxT("Exception in CIndexed::readFile: ") + e); } } CIndexed::~CIndexed() { try { time_t now = time(NULL); uint32_t s_total = 0; uint32_t k_total = 0; uint32_t l_total = 0; CFile load_file; if (load_file.Open(m_loadfilename, CFile::write)) { load_file.WriteUInt32(1); // version load_file.WriteUInt32(now); wxASSERT(m_Load_map.size() < 0xFFFFFFFF); load_file.WriteUInt32((uint32_t)m_Load_map.size()); for (LoadMap::iterator it = m_Load_map.begin(); it != m_Load_map.end(); ++it ) { Load* load = it->second; wxASSERT(load); if (load) { load_file.WriteUInt128(load->keyID); load_file.WriteUInt32(load->time); l_total++; delete load; } } load_file.Close(); } CFile s_file; if (s_file.Open(m_sfilename, CFile::write)) { s_file.WriteUInt32(2); // version s_file.WriteUInt32(now + KADEMLIAREPUBLISHTIMES); wxASSERT(m_Sources_map.size() < 0xFFFFFFFF); s_file.WriteUInt32((uint32_t)m_Sources_map.size()); for (SrcHashMap::iterator itSrcHash = m_Sources_map.begin(); itSrcHash != m_Sources_map.end(); ++itSrcHash ) { SrcHash* currSrcHash = itSrcHash->second; s_file.WriteUInt128(currSrcHash->keyID); CKadSourcePtrList& KeyHashSrcMap = currSrcHash->m_Source_map; wxASSERT(KeyHashSrcMap.size() < 0xFFFFFFFF); s_file.WriteUInt32((uint32_t)KeyHashSrcMap.size()); for (CKadSourcePtrList::iterator itSource = KeyHashSrcMap.begin(); itSource != KeyHashSrcMap.end(); ++itSource) { Source* currSource = *itSource; s_file.WriteUInt128(currSource->sourceID); CKadEntryPtrList& SrcEntryList = currSource->entryList; wxASSERT(SrcEntryList.size() < 0xFFFFFFFF); s_file.WriteUInt32((uint32_t)SrcEntryList.size()); for (CKadEntryPtrList::iterator itEntry = SrcEntryList.begin(); itEntry != SrcEntryList.end(); ++itEntry) { Kademlia::CEntry* currName = *itEntry; s_file.WriteUInt32(currName->m_tLifeTime); currName->WriteTagList(&s_file); delete currName; s_total++; } delete currSource; } delete currSrcHash; } s_file.Close(); } CFile k_file; if (k_file.Open(m_kfilename, CFile::write)) { k_file.WriteUInt32(3); // version k_file.WriteUInt32(now + KADEMLIAREPUBLISHTIMEK); k_file.WriteUInt128(Kademlia::CKademlia::GetPrefs()->GetKadID()); wxASSERT(m_Keyword_map.size() < 0xFFFFFFFF); k_file.WriteUInt32((uint32_t)m_Keyword_map.size()); for (KeyHashMap::iterator itKeyHash = m_Keyword_map.begin(); itKeyHash != m_Keyword_map.end(); ++itKeyHash ) { KeyHash* currKeyHash = itKeyHash->second; k_file.WriteUInt128(currKeyHash->keyID); CSourceKeyMap& KeyHashSrcMap = currKeyHash->m_Source_map; wxASSERT(KeyHashSrcMap.size() < 0xFFFFFFFF); k_file.WriteUInt32((uint32_t)KeyHashSrcMap.size()); for (CSourceKeyMap::iterator itSource = KeyHashSrcMap.begin(); itSource != KeyHashSrcMap.end(); ++itSource ) { Source* currSource = itSource->second; k_file.WriteUInt128(currSource->sourceID); CKadEntryPtrList& SrcEntryList = currSource->entryList; wxASSERT(SrcEntryList.size() < 0xFFFFFFFF); k_file.WriteUInt32((uint32_t)SrcEntryList.size()); for (CKadEntryPtrList::iterator itEntry = SrcEntryList.begin(); itEntry != SrcEntryList.end(); ++itEntry) { Kademlia::CKeyEntry* currName = static_cast<Kademlia::CKeyEntry*>(*itEntry); wxASSERT(currName->IsKeyEntry()); k_file.WriteUInt32(currName->m_tLifeTime); currName->WritePublishTrackingDataToFile(&k_file); currName->WriteTagList(&k_file); currName->DirtyDeletePublishData(); delete currName; k_total++; } delete currSource; } CKeyEntry::ResetGlobalTrackingMap(); delete currKeyHash; } k_file.Close(); } AddDebugLogLineN(logKadIndex, CFormat(wxT("Wrote %u source, %u keyword, and %u load entries")) % s_total % k_total % l_total); for (SrcHashMap::iterator itNoteHash = m_Notes_map.begin(); itNoteHash != m_Notes_map.end(); ++itNoteHash) { SrcHash* currNoteHash = itNoteHash->second; CKadSourcePtrList& KeyHashNoteMap = currNoteHash->m_Source_map; for (CKadSourcePtrList::iterator itNote = KeyHashNoteMap.begin(); itNote != KeyHashNoteMap.end(); ++itNote) { Source* currNote = *itNote; CKadEntryPtrList& NoteEntryList = currNote->entryList; for (CKadEntryPtrList::iterator itNoteEntry = NoteEntryList.begin(); itNoteEntry != NoteEntryList.end(); ++itNoteEntry) { delete *itNoteEntry; } delete currNote; } delete currNoteHash; } m_Notes_map.clear(); } catch (const CSafeIOException& err) { AddDebugLogLineC(logKadIndex, wxT("CSafeIOException in CIndexed::~CIndexed: ") + err.what()); } catch (const CInvalidPacket& err) { AddDebugLogLineC(logKadIndex, wxT("CInvalidPacket Exception in CIndexed::~CIndexed: ") + err.what()); } catch (const wxString& e) { AddDebugLogLineC(logKadIndex, wxT("Exception in CIndexed::~CIndexed: ") + e); } } void CIndexed::Clean() { time_t tNow = time(NULL); if (m_lastClean > tNow) { return; } uint32_t k_Removed = 0; uint32_t s_Removed = 0; uint32_t s_Total = 0; uint32_t k_Total = 0; KeyHashMap::iterator itKeyHash = m_Keyword_map.begin(); while (itKeyHash != m_Keyword_map.end()) { KeyHashMap::iterator curr_itKeyHash = itKeyHash++; // Don't change this to a ++it! KeyHash* currKeyHash = curr_itKeyHash->second; for (CSourceKeyMap::iterator itSource = currKeyHash->m_Source_map.begin(); itSource != currKeyHash->m_Source_map.end(); ) { CSourceKeyMap::iterator curr_itSource = itSource++; // Don't change this to a ++it! Source* currSource = curr_itSource->second; CKadEntryPtrList::iterator itEntry = currSource->entryList.begin(); while (itEntry != currSource->entryList.end()) { k_Total++; Kademlia::CKeyEntry* currName = static_cast<Kademlia::CKeyEntry*>(*itEntry); wxASSERT(currName->IsKeyEntry()); if (!currName->m_bSource && currName->m_tLifeTime < tNow) { k_Removed++; itEntry = currSource->entryList.erase(itEntry); delete currName; continue; } else if (currName->m_bSource) { wxFAIL; } else { currName->CleanUpTrackedPublishers(); // intern cleanup } ++itEntry; } if (currSource->entryList.empty()) { currKeyHash->m_Source_map.erase(curr_itSource); delete currSource; } } if (currKeyHash->m_Source_map.empty()) { m_Keyword_map.erase(curr_itKeyHash); delete currKeyHash; } } SrcHashMap::iterator itSrcHash = m_Sources_map.begin(); while (itSrcHash != m_Sources_map.end()) { SrcHashMap::iterator curr_itSrcHash = itSrcHash++; // Don't change this to a ++it! SrcHash* currSrcHash = curr_itSrcHash->second; CKadSourcePtrList::iterator itSource = currSrcHash->m_Source_map.begin(); while (itSource != currSrcHash->m_Source_map.end()) { Source* currSource = *itSource; CKadEntryPtrList::iterator itEntry = currSource->entryList.begin(); while (itEntry != currSource->entryList.end()) { s_Total++; Kademlia::CEntry* currName = *itEntry; if (currName->m_tLifeTime < tNow) { s_Removed++; itEntry = currSource->entryList.erase(itEntry); delete currName; } else { ++itEntry; } } if (currSource->entryList.empty()) { itSource = currSrcHash->m_Source_map.erase(itSource); delete currSource; } else { ++itSource; } } if (currSrcHash->m_Source_map.empty()) { m_Sources_map.erase(curr_itSrcHash); delete currSrcHash; } } m_totalIndexSource = s_Total - s_Removed; m_totalIndexKeyword = k_Total - k_Removed; AddDebugLogLineN(logKadIndex, CFormat(wxT("Removed %u keyword out of %u and %u source out of %u")) % k_Removed % k_Total % s_Removed % s_Total); m_lastClean = tNow + MIN2S(30); } bool CIndexed::AddKeyword(const CUInt128& keyID, const CUInt128& sourceID, Kademlia::CKeyEntry* entry, uint8_t& load) { if (!entry) { return false; } wxCHECK(entry->IsKeyEntry(), false); if (m_totalIndexKeyword > KADEMLIAMAXENTRIES) { load = 100; return false; } if (entry->m_uSize == 0 || entry->GetCommonFileName().IsEmpty() || entry->GetTagCount() == 0 || entry->m_tLifeTime < time(NULL)) { return false; } KeyHashMap::iterator itKeyHash = m_Keyword_map.find(keyID); KeyHash* currKeyHash = NULL; if (itKeyHash == m_Keyword_map.end()) { Source* currSource = new Source; currSource->sourceID = sourceID; entry->MergeIPsAndFilenames(NULL); // IpTracking init currSource->entryList.push_front(entry); currKeyHash = new KeyHash; currKeyHash->keyID = keyID; currKeyHash->m_Source_map[currSource->sourceID] = currSource; m_Keyword_map[currKeyHash->keyID] = currKeyHash; load = 1; m_totalIndexKeyword++; return true; } else { currKeyHash = itKeyHash->second; size_t indexTotal = currKeyHash->m_Source_map.size(); if (indexTotal > KADEMLIAMAXINDEX) { load = 100; //Too many entries for this Keyword.. return false; } Source* currSource = NULL; CSourceKeyMap::iterator itSource = currKeyHash->m_Source_map.find(sourceID); if (itSource != currKeyHash->m_Source_map.end()) { currSource = itSource->second; if (!currSource->entryList.empty()) { if (indexTotal > KADEMLIAMAXINDEX - 5000) { load = 100; //We are in a hot node.. If we continued to update all the publishes //while this index is full, popular files will be the only thing you index. return false; } // also check for size match CKeyEntry *oldEntry = NULL; for (CKadEntryPtrList::iterator itEntry = currSource->entryList.begin(); itEntry != currSource->entryList.end(); ++itEntry) { CKeyEntry *currEntry = static_cast<Kademlia::CKeyEntry*>(*itEntry); wxASSERT(currEntry->IsKeyEntry()); if (currEntry->m_uSize == entry->m_uSize) { oldEntry = currEntry; currSource->entryList.erase(itEntry); break; } } entry->MergeIPsAndFilenames(oldEntry); // oldEntry can be NULL, that's ok and we still need to do this call in this case if (oldEntry == NULL) { m_totalIndexKeyword++; AddDebugLogLineN(logKadIndex, wxT("Multiple sizes published for file ") + entry->m_uSourceID.ToHexString()); } delete oldEntry; oldEntry = NULL; } else { m_totalIndexKeyword++; entry->MergeIPsAndFilenames(NULL); // IpTracking init } load = (uint8_t)((indexTotal * 100) / KADEMLIAMAXINDEX); currSource->entryList.push_front(entry); return true; } else { currSource = new Source; currSource->sourceID = sourceID; entry->MergeIPsAndFilenames(NULL); // IpTracking init currSource->entryList.push_front(entry); currKeyHash->m_Source_map[currSource->sourceID] = currSource; m_totalIndexKeyword++; load = (indexTotal * 100) / KADEMLIAMAXINDEX; return true; } } } bool CIndexed::AddSources(const CUInt128& keyID, const CUInt128& sourceID, Kademlia::CEntry* entry, uint8_t& load) { if (!entry) { return false; } if( entry->m_uIP == 0 || entry->m_uTCPport == 0 || entry->m_uUDPport == 0 || entry->GetTagCount() == 0 || entry->m_tLifeTime < time(NULL)) { return false; } SrcHash* currSrcHash = NULL; SrcHashMap::iterator itSrcHash = m_Sources_map.find(keyID); if (itSrcHash == m_Sources_map.end()) { Source* currSource = new Source; currSource->sourceID = sourceID; currSource->entryList.push_front(entry); currSrcHash = new SrcHash; currSrcHash->keyID = keyID; currSrcHash->m_Source_map.push_front(currSource); m_Sources_map[currSrcHash->keyID] = currSrcHash; m_totalIndexSource++; load = 1; return true; } else { currSrcHash = itSrcHash->second; size_t size = currSrcHash->m_Source_map.size(); for (CKadSourcePtrList::iterator itSource = currSrcHash->m_Source_map.begin(); itSource != currSrcHash->m_Source_map.end(); ++itSource) { Source* currSource = *itSource; if (!currSource->entryList.empty()) { CEntry* currEntry = currSource->entryList.front(); wxASSERT(currEntry != NULL); if (currEntry->m_uIP == entry->m_uIP && (currEntry->m_uTCPport == entry->m_uTCPport || currEntry->m_uUDPport == entry->m_uUDPport)) { CEntry* currName = currSource->entryList.front(); currSource->entryList.pop_front(); delete currName; currSource->entryList.push_front(entry); load = (size * 100) / KADEMLIAMAXSOURCEPERFILE; return true; } } else { //This should never happen! currSource->entryList.push_front(entry); wxFAIL; load = (size * 100) / KADEMLIAMAXSOURCEPERFILE; return true; } } if (size > KADEMLIAMAXSOURCEPERFILE) { Source* currSource = currSrcHash->m_Source_map.back(); currSrcHash->m_Source_map.pop_back(); wxASSERT(currSource != NULL); Kademlia::CEntry* currName = currSource->entryList.back(); currSource->entryList.pop_back(); wxASSERT(currName != NULL); delete currName; currSource->sourceID = sourceID; currSource->entryList.push_front(entry); currSrcHash->m_Source_map.push_front(currSource); load = 100; return true; } else { Source* currSource = new Source; currSource->sourceID = sourceID; currSource->entryList.push_front(entry); currSrcHash->m_Source_map.push_front(currSource); m_totalIndexSource++; load = (size * 100) / KADEMLIAMAXSOURCEPERFILE; return true; } } return false; } bool CIndexed::AddNotes(const CUInt128& keyID, const CUInt128& sourceID, Kademlia::CEntry* entry, uint8_t& load) { if (!entry) { return false; } if (entry->m_uIP == 0 || entry->GetTagCount() == 0) { return false; } SrcHash* currNoteHash = NULL; SrcHashMap::iterator itNoteHash = m_Notes_map.find(keyID); if (itNoteHash == m_Notes_map.end()) { Source* currNote = new Source; currNote->sourceID = sourceID; currNote->entryList.push_front(entry); currNoteHash = new SrcHash; currNoteHash->keyID = keyID; currNoteHash->m_Source_map.push_front(currNote); m_Notes_map[currNoteHash->keyID] = currNoteHash; load = 1; m_totalIndexNotes++; return true; } else { currNoteHash = itNoteHash->second; size_t size = currNoteHash->m_Source_map.size(); for (CKadSourcePtrList::iterator itSource = currNoteHash->m_Source_map.begin(); itSource != currNoteHash->m_Source_map.end(); ++itSource) { Source* currNote = *itSource; if (!currNote->entryList.empty()) { CEntry* currEntry = currNote->entryList.front(); wxASSERT(currEntry!=NULL); if (currEntry->m_uIP == entry->m_uIP || currEntry->m_uSourceID == entry->m_uSourceID) { CEntry* currName = currNote->entryList.front(); currNote->entryList.pop_front(); delete currName; currNote->entryList.push_front(entry); load = (size * 100) / KADEMLIAMAXNOTESPERFILE; return true; } } else { //This should never happen! currNote->entryList.push_front(entry); wxFAIL; load = (size * 100) / KADEMLIAMAXNOTESPERFILE; m_totalIndexNotes++; return true; } } if (size > KADEMLIAMAXNOTESPERFILE) { Source* currNote = currNoteHash->m_Source_map.back(); currNoteHash->m_Source_map.pop_back(); wxASSERT(currNote != NULL); CEntry* currName = currNote->entryList.back(); currNote->entryList.pop_back(); wxASSERT(currName != NULL); delete currName; currNote->sourceID = sourceID; currNote->entryList.push_front(entry); currNoteHash->m_Source_map.push_front(currNote); load = 100; return true; } else { Source* currNote = new Source; currNote->sourceID = sourceID; currNote->entryList.push_front(entry); currNoteHash->m_Source_map.push_front(currNote); load = (size * 100) / KADEMLIAMAXNOTESPERFILE; m_totalIndexNotes++; return true; } } } bool CIndexed::AddLoad(const CUInt128& keyID, uint32_t timet) { Load* load = NULL; if ((uint32_t)time(NULL) > timet) { return false; } LoadMap::iterator it = m_Load_map.find(keyID); if (it != m_Load_map.end()) { wxFAIL; return false; } load = new Load(); load->keyID = keyID; load->time = timet; m_Load_map[load->keyID] = load; m_totalIndexLoad++; return true; } void CIndexed::SendValidKeywordResult(const CUInt128& keyID, const SSearchTerm* pSearchTerms, uint32_t ip, uint16_t port, bool oldClient, uint16_t startPosition, const CKadUDPKey& senderKey) { KeyHash* currKeyHash = NULL; KeyHashMap::iterator itKeyHash = m_Keyword_map.find(keyID); if (itKeyHash != m_Keyword_map.end()) { currKeyHash = itKeyHash->second; CMemFile packetdata(1024 * 50); packetdata.WriteUInt128(Kademlia::CKademlia::GetPrefs()->GetKadID()); packetdata.WriteUInt128(keyID); packetdata.WriteUInt16(50); const uint16_t maxResults = 300; int count = 0 - startPosition; // we do 2 loops: In the first one we ignore all results which have a trustvalue below 1 // in the second one we then also consider those. That way we make sure our 300 max results are not full // of spam entries. We could also sort by trustvalue, but we would risk to only send popular files this way // on very hot keywords bool onlyTrusted = true; DEBUG_ONLY( uint32_t dbgResultsTrusted = 0; ) DEBUG_ONLY( uint32_t dbgResultsUntrusted = 0; ) do { for (CSourceKeyMap::iterator itSource = currKeyHash->m_Source_map.begin(); itSource != currKeyHash->m_Source_map.end(); ++itSource) { Source* currSource = itSource->second; for (CKadEntryPtrList::iterator itEntry = currSource->entryList.begin(); itEntry != currSource->entryList.end(); ++itEntry) { Kademlia::CKeyEntry* currName = static_cast<Kademlia::CKeyEntry*>(*itEntry); wxASSERT(currName->IsKeyEntry()); if ((onlyTrusted ^ (currName->GetTrustValue() < 1.0)) && (!pSearchTerms || currName->SearchTermsMatch(pSearchTerms))) { if (count < 0) { count++; } else if ((uint16_t)count < maxResults) { if (!oldClient || currName->m_uSize <= OLD_MAX_FILE_SIZE) { count++; #ifdef __DEBUG__ if (onlyTrusted) { dbgResultsTrusted++; } else { dbgResultsUntrusted++; } #endif packetdata.WriteUInt128(currName->m_uSourceID); currName->WriteTagListWithPublishInfo(&packetdata); if (count % 50 == 0) { DebugSend(Kad2SearchRes, ip, port); CKademlia::GetUDPListener()->SendPacket(packetdata, KADEMLIA2_SEARCH_RES, ip, port, senderKey, NULL); // Reset the packet, keeping the header (Kad id, key id, number of entries) packetdata.SetLength(16 + 16 + 2); } } } else { itSource = currKeyHash->m_Source_map.end(); --itSource; break; } } } } if (onlyTrusted && count < (int)maxResults) { onlyTrusted = false; } else { break; } } while (!onlyTrusted); AddDebugLogLineN(logKadIndex, CFormat(wxT("Kad keyword search result request: Sent %u trusted and %u untrusted results")) % dbgResultsTrusted % dbgResultsUntrusted); if (count > 0) { uint16_t countLeft = (uint16_t)count % 50; if (countLeft) { packetdata.Seek(16 + 16); packetdata.WriteUInt16(countLeft); DebugSend(Kad2SearchRes, ip, port); CKademlia::GetUDPListener()->SendPacket(packetdata, KADEMLIA2_SEARCH_RES, ip, port, senderKey, NULL); } } } Clean(); } void CIndexed::SendValidSourceResult(const CUInt128& keyID, uint32_t ip, uint16_t port, uint16_t startPosition, uint64_t fileSize, const CKadUDPKey& senderKey) { SrcHash* currSrcHash = NULL; SrcHashMap::iterator itSrcHash = m_Sources_map.find(keyID); if (itSrcHash != m_Sources_map.end()) { currSrcHash = itSrcHash->second; CMemFile packetdata(1024*50); packetdata.WriteUInt128(Kademlia::CKademlia::GetPrefs()->GetKadID()); packetdata.WriteUInt128(keyID); packetdata.WriteUInt16(50); uint16_t maxResults = 300; int count = 0 - startPosition; for (CKadSourcePtrList::iterator itSource = currSrcHash->m_Source_map.begin(); itSource != currSrcHash->m_Source_map.end(); ++itSource) { Source* currSource = *itSource; if (!currSource->entryList.empty()) { Kademlia::CEntry* currName = currSource->entryList.front(); if (count < 0) { count++; } else if (count < maxResults) { if (!fileSize || !currName->m_uSize || currName->m_uSize == fileSize) { packetdata.WriteUInt128(currName->m_uSourceID); currName->WriteTagList(&packetdata); count++; if (count % 50 == 0) { DebugSend(Kad2SearchRes, ip, port); CKademlia::GetUDPListener()->SendPacket(packetdata, KADEMLIA2_SEARCH_RES, ip, port, senderKey, NULL); // Reset the packet, keeping the header (Kad id, key id, number of entries) packetdata.SetLength(16 + 16 + 2); } } } else { break; } } } if (count > 0) { uint16_t countLeft = (uint16_t)count % 50; if (countLeft) { packetdata.Seek(16 + 16); packetdata.WriteUInt16(countLeft); DebugSend(Kad2SearchRes, ip, port); CKademlia::GetUDPListener()->SendPacket(packetdata, KADEMLIA2_SEARCH_RES, ip, port, senderKey, NULL); } } } Clean(); } void CIndexed::SendValidNoteResult(const CUInt128& keyID, uint32_t ip, uint16_t port, uint64_t fileSize, const CKadUDPKey& senderKey) { SrcHash* currNoteHash = NULL; SrcHashMap::iterator itNote = m_Notes_map.find(keyID); if (itNote != m_Notes_map.end()) { currNoteHash = itNote->second; CMemFile packetdata(1024*50); packetdata.WriteUInt128(Kademlia::CKademlia::GetPrefs()->GetKadID()); packetdata.WriteUInt128(keyID); packetdata.WriteUInt16(50); uint16_t maxResults = 150; uint16_t count = 0; for (CKadSourcePtrList::iterator itSource = currNoteHash->m_Source_map.begin(); itSource != currNoteHash->m_Source_map.end(); ++itSource ) { Source* currNote = *itSource; if (!currNote->entryList.empty()) { Kademlia::CEntry* currName = currNote->entryList.front(); if (count < maxResults) { if (!fileSize || !currName->m_uSize || fileSize == currName->m_uSize) { packetdata.WriteUInt128(currName->m_uSourceID); currName->WriteTagList(&packetdata); count++; if (count % 50 == 0) { DebugSend(Kad2SearchRes, ip, port); CKademlia::GetUDPListener()->SendPacket(packetdata, KADEMLIA2_SEARCH_RES, ip, port, senderKey, NULL); // Reset the packet, keeping the header (Kad id, key id, number of entries) packetdata.SetLength(16 + 16 + 2); } } } else { break; } } } uint16_t countLeft = count % 50; if (countLeft) { packetdata.Seek(16 + 16); packetdata.WriteUInt16(countLeft); DebugSend(Kad2SearchRes, ip, port); CKademlia::GetUDPListener()->SendPacket(packetdata, KADEMLIA2_SEARCH_RES, ip, port, senderKey, NULL); } } } bool CIndexed::SendStoreRequest(const CUInt128& keyID) { Load* load = NULL; LoadMap::iterator it = m_Load_map.find(keyID); if (it != m_Load_map.end()) { load = it->second; if (load->time < (uint32_t)time(NULL)) { m_Load_map.erase(it); m_totalIndexLoad--; delete load; return true; } return false; } return true; } SSearchTerm::SSearchTerm() : type(AND), tag(NULL), astr(NULL), left(NULL), right(NULL) {} SSearchTerm::~SSearchTerm() { if (type == String) { delete astr; } delete tag; } // File_checked_for_headers
33.287381
190
0.668079
vic3t3chn0
13ebdf2f3e672f167ff22ecfc1c9a8f60095ad12
6,197
cpp
C++
problems/atcoder/abc223/f---parenthesis-checking/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
7
2020-10-15T22:37:10.000Z
2022-02-26T17:23:49.000Z
problems/atcoder/abc223/f---parenthesis-checking/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
problems/atcoder/abc223/f---parenthesis-checking/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #ifdef LOCAL #include "code/formatting.hpp" #else #define debug(...) (void)0 #endif using namespace std; template <typename Node> struct segtree { vector<Node> node; vector<array<int, 2>> range; vector<int> where; segtree() = default; segtree(int L, int R, Node init) { assign(L, R, init); } template <typename T> segtree(int L, int R, const vector<T>& arr, int s = 0) { assign(L, R, arr, s); } void assign(int L, int R, Node init) { int N = R - L; node.assign(2 * N, init); range.resize(2 * N); where.resize(N); int Q = 1 << (N > 1 ? 8 * sizeof(N) - __builtin_clz(N - 1) : 0); for (int i = 0; i < N; i++) { range[i + N] = {L + i, L + i + 1}; } rotate(begin(range) + N, begin(range) + (3 * N - Q), end(range)); for (int i = 0; i < N; i++) { where[range[i + N][0] - L] = i + N; } for (int u = N - 1; u >= 1; u--) { range[u] = {range[u << 1][0], range[u << 1 | 1][1]}; pushup(u); } } template <typename T> void assign(int L, int R, const vector<T>& arr, int s = 0) { int N = R - L; node.resize(2 * N); range.resize(2 * N); where.resize(N); int Q = 1 << (N > 1 ? 8 * sizeof(N) - __builtin_clz(N - 1) : 0); for (int i = 0; i < N; i++) { range[i + N] = {L + i, L + i + 1}; node[i + N] = Node(arr[L + i - s]); } rotate(begin(range) + N, begin(range) + (3 * N - Q), end(range)); rotate(begin(node) + N, begin(node) + (3 * N - Q), end(node)); for (int i = 0; i < N; i++) { where[range[i + N][0] - L] = i + N; } for (int u = N - 1; u >= 1; u--) { range[u] = {range[u << 1][0], range[u << 1 | 1][1]}; pushup(u); } } auto query_point(int i) const { assert(range[1][0] <= i && i < range[1][1]); int u = where[i - range[1][0]]; return node[u]; } template <typename Update> void update_point(int i, Update&& update) { assert(range[1][0] <= i && i < range[1][1]); int u = where[i - range[1][0]]; apply(u, update); while ((u >>= 1) >= 1) { pushup(u); } } auto query_range(int L, int R) const { assert(range[1][0] <= L && R <= range[1][1]); return query_range(1, L, R); } auto query_all() const { return node[1]; } // Find first i>=k such that fn([L,i]) holds, or R otherwise // Fn is F F F F T T T T ... template <typename Fn> int prefix_binary_search(int k, Fn&& fn) { auto [L, R] = range[1]; Node ans; int i = 1, N = R - L; while (i < N) { Node v = combine(ans, node[i << 1]); if (range[i << 1][1] <= k || !fn(v)) { ans = move(v); i = i << 1 | 1; } else { i = i << 1; } } Node v = combine(ans, node[i]); return range[i][0] + !fn(v); } // Find last i<=k such that fn([i,R)) holds, or L-1 otherwise // Fn is T T T T F F F F ... template <typename Fn> int suffix_binary_search(int k, Fn&& fn) { auto [L, R] = range[1]; Node ans; int i = 1, N = R - L; while (i < N) { Node v = combine(node[i << 1 | 1], ans); if (k < range[i << 1][1] || !fn(v)) { ans = move(v); i = i << 1; } else { i = i << 1 | 1; } } Node v = combine(ans, node[i]); return range[i][0] - !fn(v); } template <typename Fn> int prefix_binary_search(Fn&& fn) { return prefix_binary_search(range[1][0], forward<Fn>(fn)); } template <typename Fn> int suffix_binary_search(Fn&& fn) { return suffix_binary_search(range[1][1] - 1, forward<Fn>(fn)); } private: static Node combine(const Node& x, const Node& y) { Node ans; ans.pushup(x, y); return ans; } template <typename Update> void apply(int u, Update&& update) { if constexpr (Node::RANGES) { node[u].apply(update, 1); } else { node[u].apply(update); } } void pushup(int u) { node[u].pushup(node[u << 1], node[u << 1 | 1]); // } auto query_range(int u, int L, int R) const { if (L <= range[u][0] && range[u][1] <= R) { return node[u]; } int m = range[u << 1][1]; if (R <= m) { return query_range(u << 1, L, R); } else if (m <= L) { return query_range(u << 1 | 1, L, R); } else { return combine(query_range(u << 1, L, m), query_range(u << 1 | 1, m, R)); } } }; struct segnode { static constexpr bool LAZY = false, RANGES = false, REVERSE = false; int side = 0; // +1 for (, -1 for ) int minprefix = 0; // should be 0 segnode() = default; segnode(int side) : side(side), minprefix(side) { assert(side == +1 || side == -1); } void pushup(const segnode& lhs, const segnode& rhs) { side = lhs.side + rhs.side; minprefix = min(lhs.minprefix, lhs.side + rhs.minprefix); } void apply(int set) { side = minprefix = set; } }; int main() { ios::sync_with_stdio(false), cin.tie(nullptr); int N, Q; cin >> N >> Q; string s; cin >> s; vector<int> side(N); for (int i = 0; i < N; i++) { side[i] = s[i] == '(' ? +1 : -1; } segtree<segnode> st(0, N, side); while (Q--) { int type, l, r; cin >> type >> l >> r, l--, r--; if (type == 1 && side[l] != side[r]) { st.update_point(l, side[r]); st.update_point(r, side[l]); swap(side[l], side[r]); } else if (type == 2) { auto ans = st.query_range(l, r + 1); if (ans.side == 0 && ans.minprefix == 0) { cout << "Yes\n"; } else { cout << "No\n"; } } } return 0; }
28.168182
89
0.442472
brunodccarvalho
13ecd5ac0467a2bd894fd528634b6765d069cc69
808
cpp
C++
Algorithms/Bit Manipulation/Integer_is_Palindrome.cpp
Praggya17/HacktoberFestContribute
098cb1012f1f2ed6ca6b3544a7b962b6c49e2643
[ "MIT" ]
98
2018-10-09T15:42:41.000Z
2021-10-04T15:25:44.000Z
Algorithms/Bit Manipulation/Integer_is_Palindrome.cpp
Praggya17/HacktoberFestContribute
098cb1012f1f2ed6ca6b3544a7b962b6c49e2643
[ "MIT" ]
141
2018-10-06T16:55:20.000Z
2021-10-31T18:25:35.000Z
Algorithms/Bit Manipulation/Integer_is_Palindrome.cpp
Praggya17/HacktoberFestContribute
098cb1012f1f2ed6ca6b3544a7b962b6c49e2643
[ "MIT" ]
885
2018-10-06T17:14:44.000Z
2022-01-29T03:16:21.000Z
#include<iostream> #include<cmath> using namespace std; //avoids the space complexity of O(n) by directly extracting the digits from the input. bool IsPalindromeNumber(int x) { if (x <= 0) { return x == 0; } const int num_digits = static_cast<int>(floor(log10(x))) + 1; int msd_mask = static_cast<int>(pow(10, num_digits - 1)); for (int i = 0; i < (num_digits / 2); ++i) { if (x / msd_mask != x % 10) { //checks MSB != LSB returns false return false; } x %= msd_mask; // Remove the most significant digit of x. x /= 10; // Remove the least significant digit of x. msd_mask /= 100; } return true; } int main(int argc, char const *argv[]) { int n; cin>>n; if(IsPalindromeNumber(n)) cout<<"Palindrome"; else cout<<"Not Palindrome"; return 0; }
25.25
87
0.621287
Praggya17
13ece53dcd03ee60dbe799a719c17a4825ba634d
8,407
hpp
C++
svntrunk/src/untabbed/BlueMatter/analysis/include/DataReceiverSnapshotDumper.hpp
Bhaskers-Blu-Org1/BlueMatter
1ab2c41af870c19e2e1b1095edd1d5c85eeb9b5e
[ "BSD-2-Clause" ]
7
2020-02-25T15:46:18.000Z
2022-02-25T07:04:47.000Z
svntrunk/src/untabbed/BlueMatter/analysis/include/DataReceiverSnapshotDumper.hpp
IBM/BlueMatter
5243c0ef119e599fc3e9b7c4213ecfe837de59f3
[ "BSD-2-Clause" ]
null
null
null
svntrunk/src/untabbed/BlueMatter/analysis/include/DataReceiverSnapshotDumper.hpp
IBM/BlueMatter
5243c0ef119e599fc3e9b7c4213ecfe837de59f3
[ "BSD-2-Clause" ]
5
2019-06-06T16:30:21.000Z
2020-11-16T19:43:01.000Z
/* Copyright 2001, 2019 IBM Corporation * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DATARECEIVERSNAPSHOTDUMPER_HPP #define DATARECEIVERSNAPSHOTDUMPER_HPP #include <ostream> #include <fstream> #include <BlueMatter/DataReceiver.hpp> #include <BlueMatter/ExternalDatagram.hpp> // #define STEADY_SHOT using namespace std; struct XYZShort{ unsigned short mX; unsigned short mY; unsigned short mZ; }; class DataReceiverSnapshotDumper : public DataReceiver { public: ofstream mStream; FILE *mFile; char mBMTFileName[256]; char mPDBFileName[256]; int mNNonWaterAtoms; int mNWaters; int mDoAppend; int mStartIndex; int mEndIndex; int mNoWaters; #ifdef STEADY_SHOT XYZ FirstOrigin; int FirstFrame; #endif XYZShort *mpShortPos; void setParams(char *BMTFileName, char *PDBFileName, int NNonWaterAtoms, int NWaters, int DoAppend=0, int NoWaters=0) { strcpy(mBMTFileName, BMTFileName); strcpy(mPDBFileName, PDBFileName); mNNonWaterAtoms = NNonWaterAtoms; mNWaters = NWaters; mDoAppend = DoAppend; mNoWaters = NoWaters; mStartIndex = 0; mEndIndex = NNonWaterAtoms + 3 * NWaters - 1; if (NoWaters) mEndIndex = NNonWaterAtoms - 1; } virtual void init() { char buff[1024]; mpShortPos = NULL; if (!mDoAppend) { mStream.open(mBMTFileName); if (!mStream.is_open()) { cerr << "SSD output file " << mBMTFileName << " could not be open." << endl; exit(-1); } mStream << "SSD" << endl; mStream << "VERSION 1.00" << endl; mStream << "STRUCTURE " << mPDBFileName << endl; mStream << "BONDS NULL" << endl; mStream << "NUMNONWATERATOMS " << mNNonWaterAtoms << endl; mStream << "NUMWATERS " << mNWaters << endl; mStream << "NOWATERS " << mNoWaters << endl; mStream << "STARTINDEX " << mStartIndex << endl; mStream << "ENDINDEX " << mEndIndex << endl; mStream << "SNAPSHOTFORMAT nsites* double px,py,pz,vx,vy,vz" << endl; mStream.close(); } mFile = fopen(mBMTFileName, "ab"); if (!mFile) { cerr << "BMT output file " << mBMTFileName << " could not be open for binary write/append." << endl; exit(-1); } } virtual void final() { if (fclose(mFile)) { cerr << "Error on closing " << mBMTFileName << endl; } if (mpShortPos) delete [] mpShortPos; } void FrameCenter(tSiteData *full_ps, int Start, int End, XYZ &cen) { tSiteData *ps = &full_ps[Start]; cen.Zero(); for (int i=Start; i<=End; i++) { XYZ s = ps->mPosition; cen = cen + s; ps++; } double N = 1.0 / (Start - End); cen = N * cen; return; } void findBox(tSiteData *full_ps, int Start, int End, XYZ &origin, XYZ &span, double &MaxSpan) { XYZ LL, UR; tSiteData *ps = &full_ps[Start]; LL.mX = LL.mY = LL.mZ = 1.0E20; UR.mX = UR.mY = UR.mZ = -1.0E20; for (int i=Start; i<=End; i++) { XYZ s = ps->mPosition; if (s.mX < LL.mX) LL.mX = s.mX; if (s.mX > UR.mX) UR.mX = s.mX; if (s.mY < LL.mY) LL.mY = s.mY; if (s.mY > UR.mY) UR.mY = s.mY; if (s.mZ < LL.mZ) LL.mZ = s.mZ; if (s.mZ > UR.mZ) UR.mZ = s.mZ; ps++; } origin = LL; span = UR - LL; MaxSpan = span.mX; if (span.mY > MaxSpan) MaxSpan = span.mY; if (span.mZ > MaxSpan) MaxSpan = span.mZ; } void simplifySites(tSiteData *full_ps, XYZShort *psp, int Start, int End, XYZ &origin, double factor) { tSiteData *ps = &full_ps[Start]; for (int i=Start; i<=End; i++) { XYZ p = ps->mPosition; p -= origin; psp->mX = p.mX*factor; psp->mY = p.mY*factor; psp->mZ = p.mZ*factor; ps++; psp++; } } virtual void sites(Frame *f) { static char fname[512]; int NumToWrite; int NumWritten; unsigned CurrentStep = f->mOuterTimeStep; tSiteData *ps= f->mSiteData.getArray(); int NSites = f->mSiteData.getSize(); XYZ cen; // CenterFrame(ps,mStartIndex,mEndIndex); #if 1 for (int i=0; i<NSites; i++) { int site = i+1; fwrite(&CurrentStep, sizeof(int), 1, mFile); fwrite(&site, sizeof(int), 1, mFile); fwrite(&ps->mPosition, sizeof(double), 3, mFile); fwrite(&ps->mVelocity, sizeof(double), 3, mFile); ps++; } #endif #if 0 for (int i=0; i<NSites; i++) { XYZ &p = ps->mPosition; XYZ &v = ps->mVelocity; fprintf(mFile,"%10d %6d %12.8f %12.8f %12.8f %12.8f %12.8 %12.8 /n", CurrentStep,i+1,p.mX,p.mY,p.mZ,v.mX,v.mY,v.mZ); ps++; } #endif } #if 0 virtual void udfs(Frame *f) { tEnergySumAccumulator *pesa = &f->mEnergyInfo.mEnergySumAccumulator; pesa->mBondEnergy = f->mUDFs[ UDF_Binding::StdHarmonicBondForce_Code ].getSum(); pesa->mAngleEnergy = f->mUDFs[ UDF_Binding::StdHarmonicAngleForce_Code ].getSum(); pesa->mUBEnergy = f->mUDFs[ UDF_Binding::UreyBradleyForce_Code ].getSum(); pesa->mTorsionEnergy = f->mUDFs[ UDF_Binding::SwopeTorsionForce_Code ].getSum() + f->mUDFs[ UDF_Binding::OPLSTorsionForce_Code ].getSum(); pesa->mImproperEnergy = f->mUDFs[ UDF_Binding::OPLSImproperForce_Code ].getSum() + f->mUDFs[ UDF_Binding::ImproperDihedralForce_Code ].getSum() ; pesa->mChargeEnergy = f->mUDFs[ UDF_Binding::StdChargeForce_Code ].getSum(); pesa->mLennardJonesEnergy = f->mUDFs[ UDF_Binding::LennardJonesForce_Code ].getSum(); pesa->mKineticEnergy = f->mUDFs[ UDF_Binding::KineticEnergy_Code ].getSum(); pesa->mWaterEnergy = f->mUDFs[ UDF_Binding::TIP3PForce_Code ].getSum(); f->mEnergyInfo.mEnergySums.mIntraE = pesa->mBondEnergy + pesa->mAngleEnergy + pesa->mUBEnergy + pesa->mTorsionEnergy + pesa->mImproperEnergy + pesa->mWaterEnergy; f->mEnergyInfo.mEnergySums.mInterE = pesa->mChargeEnergy + pesa->mLennardJonesEnergy; if (f->mNSites > 0) f->mEnergyInfo.mEnergySums.mTemp = f->mEnergyInfo.mEnergySumAccumulator.mKineticEnergy/1.5/f->mNSites/SciConst::KBoltzmann_IU; else f->mEnergyInfo.mEnergySums.mTemp = 0; f->mEnergyInfo.mEnergySums.mTotalE = f->mEnergyInfo.mEnergySums.mInterE + f->mEnergyInfo.mEnergySums.mIntraE + pesa->mKineticEnergy; pesa->mFullTimeStep = f->mFullTimeStep; ReportTotalEnergy(&f->mEnergyInfo); } #endif }; #endif
31.02214
144
0.587725
Bhaskers-Blu-Org1
13eee5b68494bb7e016ac2fb5179230f25e60262
2,032
hpp
C++
lib/lvd/read_bin_sst.hpp
vdods/lvd
864eaa25bdaddfc0dc7e788e693ebae3b42597be
[ "Apache-2.0" ]
null
null
null
lib/lvd/read_bin_sst.hpp
vdods/lvd
864eaa25bdaddfc0dc7e788e693ebae3b42597be
[ "Apache-2.0" ]
null
null
null
lib/lvd/read_bin_sst.hpp
vdods/lvd
864eaa25bdaddfc0dc7e788e693ebae3b42597be
[ "Apache-2.0" ]
null
null
null
// 2021.01.22 - Copyright Victor Dods - Licensed under Apache 2.0 #pragma once #include "lvd/read_bin_type.hpp" #include "lvd/sst/SV_t.hpp" namespace lvd { template <typename S_, typename C_, auto... Params_> struct ReadInPlace_t<sst::SV_t<S_,C_>,BinEncoding_t<Params_...>> { template <typename CharT_, typename Traits_> std::basic_istream<CharT_,Traits_> &operator() (std::basic_istream<CharT_,Traits_> &in, BinEncoding_t<Params_...> const &enc, sst::SV_t<S_,C_> &dest_val) const { if constexpr (enc.type_encoding() == TypeEncoding::INCLUDED) in >> enc.with_demoted_type_encoding().in(type_of(dest_val)); // This will throw if the type doesn't match. // The type is already known at this point. auto inner_enc = enc.with_demoted_type_encoding(); // Use assign-move so that the validity check is done automatically. dest_val = inner_enc.template read<C_>(in); return in; } }; // SV_t<S_,C_> is not in general default-constructible, so ReadValue_t has to be specialized. template <typename S_, typename C_, typename Encoding_> struct ReadValue_t<sst::SV_t<S_,C_>,Encoding_> { template <typename CharT_, typename Traits_> sst::SV_t<S_,C_> operator() (std::basic_istream<CharT_,Traits_> &in, Encoding_ const &enc) const { if constexpr (enc.type_encoding() == TypeEncoding::INCLUDED) in >> enc.with_demoted_type_encoding().in(ty<sst::SV_t<S_,C_>>); // This will throw if the type doesn't match. // The type is already known at this point. auto inner_enc = enc.with_demoted_type_encoding(); auto retval = sst::SV_t<S_,C_>{sst::no_check}; retval = inner_enc.template read<C_>(in); return retval; // auto retval = sst::SV_t<S_,C_>{sst::no_check, inner_enc.template read<C_>(in)}; // retval->template check<check_policy_for__ctor_move_C(S_{})>(); // return retval; // return sst::SV_t<S_,C_>{inner_enc.template read<C_>(in)}; } }; } // end namespace lvd
42.333333
165
0.676181
vdods
13ef330ec6e6ab4c815925600bf316db4bc65ede
7,254
cpp
C++
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/modules/v8/V8RsaKeyAlgorithm.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/modules/v8/V8RsaKeyAlgorithm.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/External/node/elastos/external/chromium_org/third_party/WebKit/Source/modules/modules_gyp/bindings/modules/v8/V8RsaKeyAlgorithm.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
// Copyright 2014 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. // This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY! #include "config.h" #include "V8RsaKeyAlgorithm.h" #include "bindings/v8/ExceptionState.h" #include "bindings/v8/V8DOMConfiguration.h" #include "bindings/v8/V8HiddenValue.h" #include "bindings/v8/V8ObjectConstructor.h" #include "bindings/v8/custom/V8Uint8ArrayCustom.h" #include "core/dom/ContextFeatures.h" #include "core/dom/Document.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/TraceEvent.h" #include "wtf/GetPtr.h" #include "wtf/RefPtr.h" namespace WebCore { static void initializeScriptWrappableForInterface(RsaKeyAlgorithm* object) { if (ScriptWrappable::wrapperCanBeStoredInObject(object)) ScriptWrappable::fromObject(object)->setTypeInfo(&V8RsaKeyAlgorithm::wrapperTypeInfo); else ASSERT_NOT_REACHED(); } } // namespace WebCore void webCoreInitializeScriptWrappableForInterface(WebCore::RsaKeyAlgorithm* object) { WebCore::initializeScriptWrappableForInterface(object); } namespace WebCore { const WrapperTypeInfo V8RsaKeyAlgorithm::wrapperTypeInfo = { gin::kEmbedderBlink, V8RsaKeyAlgorithm::domTemplate, V8RsaKeyAlgorithm::derefObject, 0, 0, 0, V8RsaKeyAlgorithm::installPerContextEnabledMethods, &V8KeyAlgorithm::wrapperTypeInfo, WrapperTypeObjectPrototype, GarbageCollectedObject }; namespace RsaKeyAlgorithmV8Internal { template <typename T> void V8_USE(T) { } static void modulusLengthAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); RsaKeyAlgorithm* impl = V8RsaKeyAlgorithm::toNative(holder); v8SetReturnValueUnsigned(info, impl->modulusLength()); } static void modulusLengthAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); RsaKeyAlgorithmV8Internal::modulusLengthAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void publicExponentAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); RsaKeyAlgorithm* impl = V8RsaKeyAlgorithm::toNative(holder); RefPtr<Uint8Array> result(impl->publicExponent()); if (result && DOMDataStore::setReturnValueFromWrapper<V8Uint8Array>(info.GetReturnValue(), result.get())) return; v8::Handle<v8::Value> wrapper = toV8(result.get(), holder, info.GetIsolate()); if (!wrapper.IsEmpty()) { V8HiddenValue::setHiddenValue(info.GetIsolate(), holder, v8AtomicString(info.GetIsolate(), "publicExponent"), wrapper); v8SetReturnValue(info, wrapper); } } static void publicExponentAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); RsaKeyAlgorithmV8Internal::publicExponentAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } } // namespace RsaKeyAlgorithmV8Internal static const V8DOMConfiguration::AttributeConfiguration V8RsaKeyAlgorithmAttributes[] = { {"modulusLength", RsaKeyAlgorithmV8Internal::modulusLengthAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"publicExponent", RsaKeyAlgorithmV8Internal::publicExponentAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, }; static void configureV8RsaKeyAlgorithmTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) { functionTemplate->ReadOnlyPrototype(); v8::Local<v8::Signature> defaultSignature; defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "RsaKeyAlgorithm", V8KeyAlgorithm::domTemplate(isolate), V8RsaKeyAlgorithm::internalFieldCount, V8RsaKeyAlgorithmAttributes, WTF_ARRAY_LENGTH(V8RsaKeyAlgorithmAttributes), 0, 0, 0, 0, isolate); v8::Local<v8::ObjectTemplate> instanceTemplate ALLOW_UNUSED = functionTemplate->InstanceTemplate(); v8::Local<v8::ObjectTemplate> prototypeTemplate ALLOW_UNUSED = functionTemplate->PrototypeTemplate(); // Custom toString template functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate()); } v8::Handle<v8::FunctionTemplate> V8RsaKeyAlgorithm::domTemplate(v8::Isolate* isolate) { return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), configureV8RsaKeyAlgorithmTemplate); } bool V8RsaKeyAlgorithm::hasInstance(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value); } v8::Handle<v8::Object> V8RsaKeyAlgorithm::findInstanceInPrototypeChain(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value); } RsaKeyAlgorithm* V8RsaKeyAlgorithm::toNativeWithTypeCheck(v8::Isolate* isolate, v8::Handle<v8::Value> value) { return hasInstance(value, isolate) ? fromInternalPointer(v8::Handle<v8::Object>::Cast(value)->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex)) : 0; } v8::Handle<v8::Object> wrap(RsaKeyAlgorithm* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { ASSERT(impl); ASSERT(!DOMDataStore::containsWrapper<V8RsaKeyAlgorithm>(impl, isolate)); return V8RsaKeyAlgorithm::createWrapper(impl, creationContext, isolate); } v8::Handle<v8::Object> V8RsaKeyAlgorithm::createWrapper(RawPtr<RsaKeyAlgorithm> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { ASSERT(impl); ASSERT(!DOMDataStore::containsWrapper<V8RsaKeyAlgorithm>(impl.get(), isolate)); if (ScriptWrappable::wrapperCanBeStoredInObject(impl.get())) { const WrapperTypeInfo* actualInfo = ScriptWrappable::fromObject(impl.get())->typeInfo(); // Might be a XXXConstructor::wrapperTypeInfo instead of an XXX::wrapperTypeInfo. These will both have // the same object de-ref functions, though, so use that as the basis of the check. RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(actualInfo->derefObjectFunction == wrapperTypeInfo.derefObjectFunction); } v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &wrapperTypeInfo, toInternalPointer(impl.get()), isolate); if (UNLIKELY(wrapper.IsEmpty())) return wrapper; installPerContextEnabledProperties(wrapper, impl.get(), isolate); V8DOMWrapper::associateObjectWithWrapper<V8RsaKeyAlgorithm>(impl, &wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Independent); return wrapper; } void V8RsaKeyAlgorithm::derefObject(void* object) { } template<> v8::Handle<v8::Value> toV8NoInline(RsaKeyAlgorithm* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { return toV8(impl, creationContext, isolate); } } // namespace WebCore
44.503067
294
0.76992
jingcao80
13ef68cf771eba81d2e52f13c77016214561199b
289
cpp
C++
test/util/value_unittest.cpp
kilasuelika/FastAD
dd070c608c18f5391f2ac68dca4f9db223a33eca
[ "MIT" ]
50
2019-11-28T22:25:01.000Z
2022-02-20T03:55:19.000Z
test/util/value_unittest.cpp
kilasuelika/FastAD
dd070c608c18f5391f2ac68dca4f9db223a33eca
[ "MIT" ]
25
2019-11-28T20:44:12.000Z
2021-10-30T00:14:39.000Z
test/util/value_unittest.cpp
kilasuelika/FastAD
dd070c608c18f5391f2ac68dca4f9db223a33eca
[ "MIT" ]
2
2021-02-26T11:14:56.000Z
2021-07-07T06:40:18.000Z
#include <gtest/gtest.h> #include <fastad_bits/util/value.hpp> namespace ad { namespace util { struct value_fixture : ::testing::Test { protected: }; TEST_F(value_fixture, ones_scl) { double x = 0.; ones(x); EXPECT_DOUBLE_EQ(x, 1.); } } // namespace util } // namespace ad
13.761905
38
0.66782
kilasuelika
13f881af771c0ff5217d500c55aa2555898004de
1,562
cc
C++
sdk/c/api/create_peerconnection_factory.cc
raghuhit/webrtc-1
5b534b6458ab14cbe62a2bbb642e8a3536dfd5e2
[ "Apache-2.0", "BSD-3-Clause" ]
99
2019-09-30T11:42:30.000Z
2021-12-24T04:41:10.000Z
sdk/c/api/create_peerconnection_factory.cc
raghuhit/webrtc-1
5b534b6458ab14cbe62a2bbb642e8a3536dfd5e2
[ "Apache-2.0", "BSD-3-Clause" ]
23
2020-03-27T00:59:45.000Z
2022-03-28T15:31:09.000Z
sdk/c/api/create_peerconnection_factory.cc
raghuhit/webrtc-1
5b534b6458ab14cbe62a2bbb642e8a3536dfd5e2
[ "Apache-2.0", "BSD-3-Clause" ]
26
2019-11-23T15:36:12.000Z
2022-03-15T15:37:01.000Z
/* * Copyright 2019 pixiv Inc. All Rights Reserved. * * Use of this source code is governed by a license that can be * found in the LICENSE.pixiv file in the root of the source tree. */ #include "api/create_peerconnection_factory.h" #include "api/video_codecs/video_decoder_factory.h" #include "api/video_codecs/video_encoder_factory.h" #include "sdk/c/api/create_peerconnection_factory.h" extern "C" WebrtcPeerConnectionFactoryInterface* webrtcCreatePeerConnectionFactory( RtcThread* network_thread, RtcThread* worker_thread, RtcThread* signaling_thread, WebrtcAudioDeviceModule* default_adm, WebrtcAudioEncoderFactory* audio_encoder_factory, WebrtcAudioDecoderFactory* audio_decoder_factory, WebrtcVideoEncoderFactory* video_encoder_factory, WebrtcVideoDecoderFactory* video_decoder_factory, WebrtcAudioMixer* audio_mixer, WebrtcAudioProcessing* audio_processing) { return rtc::ToC( webrtc::CreatePeerConnectionFactory( rtc::ToCplusplus(network_thread), rtc::ToCplusplus(worker_thread), rtc::ToCplusplus(signaling_thread), rtc::ToCplusplus(default_adm), rtc::ToCplusplus(audio_encoder_factory), rtc::ToCplusplus(audio_decoder_factory), std::unique_ptr<webrtc::VideoEncoderFactory>( rtc::ToCplusplus(video_encoder_factory)), std::unique_ptr<webrtc::VideoDecoderFactory>( rtc::ToCplusplus(video_decoder_factory)), rtc::ToCplusplus(audio_mixer), rtc::ToCplusplus(audio_processing)) .release()); }
41.105263
76
0.748399
raghuhit
13f8d4395f87c200509cc96244fb15e27b32bda2
65,787
cpp
C++
com/netfx/src/clr/jit/il/emitrisc.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/netfx/src/clr/jit/il/emitrisc.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/netfx/src/clr/jit/il/emitrisc.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX emitRISC.cpp XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #include "jitpch.h" #pragma hdrstop #include "alloc.h" #include "instr.h" #include "target.h" #include "emit.h" /*****************************************************************************/ #if TGT_RISC /***************************************************************************** * * Call the specified function pointer for each epilog block in the current * method with the epilog's relative code offset. Returns the sum of the * values returned by the callback. */ #if TRACK_GC_REFS size_t emitter::emitGenEpilogLst(size_t (*fp)(void *, unsigned), void *cp) { #error GC ref tracking NYI for RISC targets } #endif /*****************************************************************************/ #if EMIT_USE_LIT_POOLS /***************************************************************************** * * Allocate an instruction descriptor for an instruction that references * a literal pool entry. */ emitter::instrDesc* emitter::emitNewInstrLPR(size_t size, gtCallTypes typ, void * hnd) { instrDescLPR * ld = emitAllocInstrLPR(size); /* Fill in the instruction descriptor */ ld->idInsFmt = IF_RWR_LIT; ld->idIns = LIT_POOL_LOAD_INS; ld->idAddr.iiaMembHnd = hnd; ld->idInfo.idSmallCns = typ; /* Make sure the type was stored properly */ assert(emitGetInsLPRtyp(ld) == typ); /* Record the instruction's IG and offset within it */ ld->idlIG = emitCurIG; ld->idlOffs = emitCurIGsize; /* Assume this is not a direct call sequence for now */ #if SMALL_DIRECT_CALLS ld->idlCall = NULL; #endif /* Add the instruction to this IG's litpool ref list */ ld->idlNext = emitLPRlistIG; emitLPRlistIG = ld; return ld; } /***************************************************************************** * * When we're finished creating an instruction group, this routine is called * to perform any literal pool-related work for the current IG. */ void emitter::emitRecIGlitPoolRefs(insGroup *ig) { /* Update the total estimate of literal pool entries */ emitEstLPwords += emitCurIG->igLPuseCntW; emitEstLPlongs += emitCurIG->igLPuseCntL; emitEstLPaddrs += emitCurIG->igLPuseCntA; /* Does this IG have any instructions referencing the literal pool? */ if (emitLPRlistIG) { /* Move all LP referencing instructions to a global list */ instrDescLPR * list = NULL; instrDescLPR * last = NULL; do { size_t offs; instrDescLPR * oldI; instrDescLPR * newI; /* Grab the next instruction and remove it from the list */ oldI = emitLPRlistIG; emitLPRlistIG = oldI->idlNext; /* Figure out the address of where the instruction got copied */ offs = (BYTE*)oldI - emitCurIGfreeBase; newI = (instrDescLPR*)(ig->igData + offs); #if USE_LCL_EMIT_BUFF assert((oldI == newI) == emitLclBuffDst); #endif assert(newI->idlIG == ig); assert(newI->idIns == oldI->idIns); assert(newI->idlNext == oldI->idlNext); /* Update the "call" field if non-NULL */ if (newI->idlCall) { unsigned diff = (BYTE*)newI->idlCall - emitCurIGfreeBase; newI->idlCall = (instrDescLPR*)(ig->igData + diff); } /* Append the new instruction to the list */ newI->idlNext = list; list = newI; if (!last) last = newI; } while (emitLPRlistIG); /* Add the instruction(s) from this IG to the global list */ if (emitCurIG == emitPrologIG) { /* We're in the prolog, insert in front of the list */ last->idlNext = emitLPRlist; emitLPRlist = list; if (!emitLPRlast) emitLPRlast = last; } else { /* Append at the end of the current list */ if (emitLPRlist) emitLPRlast->idlNext = list; else emitLPRlist = list; last->idlNext = NULL; emitLPRlast = last; } } assert(emitLPRlistIG == NULL); } /***************************************************************************** * * Append a literal pool after the specified instruction group. Return its * estimated size. */ size_t emitter::emitAddLitPool(insGroup * ig, bool skip, unsigned wordCnt, short * * nxtLPptrW, unsigned longCnt, long * * nxtLPptrL, unsigned addrCnt, LPaddrDesc**nxtAPptrL) { litPool * lp; size_t sz; /* Allocate a pool descriptor and append it to the list */ lp = (litPool*)emitGetMem(sizeof(*lp)); if (emitLitPoolLast) emitLitPoolLast->lpNext = lp; else emitLitPoolList = lp; emitLitPoolLast = lp; lp->lpNext = 0; emitTotLPcount++; #ifdef DEBUG lp->lpNum = emitTotLPcount; #endif /* If there are longs/addrs, we need at least one word for alignment */ /* but only for sh3? */ #if !TGT_ARM if ((longCnt || addrCnt) && !wordCnt) wordCnt++; #endif // TGT_ARM /* Remember which group the pool belongs to */ lp->lpIG = ig; /* There are no references yet */ #if SCHEDULER lp->lpRefs = NULL; #endif /* Conservative size estimate: assume the pool will be completely filled */ sz = wordCnt * 2 + longCnt * 4 + addrCnt * 4; /* Do we need to jump over the literal pool? */ lp->lpJumpIt = skip; if (skip) { size_t jmpSize; /* Estimate what size jump we'll have to use */ #if JMP_SIZE_MIDDL lp->lpJumpMedium = false; #endif if (sz < JMP_DIST_SMALL_MAX_POS) { lp->lpJumpSmall = true; jmpSize = JMP_SIZE_SMALL; } #if JMP_SIZE_MIDDL else if (sz < JMP_DIST_MIDDL_MAX_POS) { lp->lpJumpMedium = true; jmpSize = JMP_SIZE_MIDDL; } #endif else { lp->lpJumpSmall = false; jmpSize = JMP_SIZE_LARGE; /* This one really hurts - the jump will need to use the LP */ longCnt++; sz += 4; } /* Add the jump size to the total size estimate */ sz += jmpSize; } /* Grab the appropriate space in the tables */ lp->lpWordTab = lp->lpWordNxt = *nxtLPptrW; *nxtLPptrW += wordCnt; #ifdef DEBUG lp->lpWordMax = wordCnt; #endif lp->lpWordCnt = 0; lp->lpLongTab = lp->lpLongNxt = *nxtLPptrL; *nxtLPptrL += longCnt; #ifdef DEBUG lp->lpLongMax = longCnt; #endif lp->lpLongCnt = 0; lp->lpAddrTab = lp->lpAddrNxt = *nxtAPptrL; *nxtAPptrL += addrCnt; #ifdef DEBUG lp->lpAddrMax = addrCnt; #endif lp->lpAddrCnt = 0; /* Record the size estimate and add it to the group's size */ lp->lpSize = 0; lp->lpSizeEst = sz; ig->igSize += sz; return sz; } /***************************************************************************** * * Find an existing literal pool entry that matches the given one. Returns * the offset of the entry (or -1 in case one wasn't found). */ int emitter::emitGetLitPoolEntry(void * table, unsigned count, void * value, size_t size) { BYTE * entry = (BYTE*)table; /* ISSUE: Using linear search here - brilliant!!! */ while (count--) { if (!memcmp(entry, value, size)) { /* Match found, return offset from base of table */ return (BYTE *)entry - (BYTE*)table; } entry += size; } return -1; } /***************************************************************************** * * Add an entry for the instruction's operand to the specified literal pool; * if 'issue' is non-zero, the actual final offset of the entry (relative * to the method beginning) is returned. */ size_t emitter::emitAddLitPoolEntry(litPool *lp, instrDesc *id, bool issue) { int offs; unsigned base; int val; size_t size = emitDecodeSize(id->idOpSize); assert(size == 2 || size == 4); assert(lp); assert(id->idInsFmt == IF_RWR_LIT); /* Get the base offset of the pool (valid only when 'issue' is true) */ base = lp->lpOffs; /* Try to reuse an existing entry */ if (emitGetInsLPRtyp(id) == CT_INTCNS) { int val = id->idAddr.iiaCns; //printf ("adding lit pool %d with issue %d\n", val, issue); if (size == 2) { /* Search the word table for a match */ offs = emitGetLitPoolEntry(lp->lpWordTab, lp->lpWordCnt, &val, size); if (offs != -1) { if (issue) { /* Do we have any padding? */ if (lp->lpPadding) { /* We must be using the first word for padding */ assert(lp->lpPadFake == false); /* Have we matched the padding word itself? */ if (!offs) return base; } /* Add the long and address sections sizes to the offset */ return base + offs + lp->lpLongCnt * sizeof(int) + lp->lpAddrCnt * sizeof(void*); } return 0; } /* Search the long table for a match as well */ offs = emitGetLitPoolEntry(lp->lpLongTab, lp->lpLongCnt*2, &val, size); if (offs != -1) goto FOUND_LONG; /* No match among the existing entries, append a new entry */ #ifdef DEBUG assert(lp->lpWordCnt < lp->lpWordMax); #endif *lp->lpWordNxt++ = (short)val; lp->lpWordCnt++; } else { /* Search the long table for a match */ offs = emitGetLitPoolEntry(lp->lpLongTab, lp->lpLongCnt, &val, size); if (offs != -1) { if (issue) { FOUND_LONG: /* Add padding, if necessary */ if (lp->lpPadding) base += 2; /* long/addr entries must always be aligned */ assert(((base + offs) & 3) == 0 || issue == false || size < sizeof(int)); /* Return the offset of the entry */ return base + offs; } return 0; } /* No match among the existing entries, append a new entry */ #ifdef DEBUG assert(lp->lpLongCnt < lp->lpLongMax); #endif *lp->lpLongNxt++ = val; lp->lpLongCnt++; } } else { LPaddrDesc val; /* Create an entry for the lookup */ memset(&val, 0, sizeof(val)); val.lpaTyp = emitGetInsLPRtyp(id); val.lpaHnd = id->idAddr.iiaMethHnd; // printf("Adding [%d] addr entry [%02X,%08X]\n", issue+1, val.lpaTyp, val.lpaHnd); /* Search both the addr table for a match */ offs = emitGetLitPoolEntry(lp->lpAddrTab, lp->lpAddrCnt , &val, sizeof(val)); if (offs != -1) { if (issue) { /* Add padding, if necessary */ if (base & 3) { assert(lp->lpPadding); base += 2; } else { assert(lp->lpPadding == false && lp->lpPadFake == false); } // the offs returned is the offset into the address table, which // is not the same as the offset into the litpool, since the // address table contains structures, not simple 32-bit addresses offs = offs * sizeof(void*) / sizeof(val); /* Return the offset of the entry */ //return base + offs + lp->lpLongCnt * sizeof(int) + lp->lpAddrCnt * sizeof(void*); return base + lp->lpLongCnt * sizeof(long) + offs; } return 0; } /* No match among the existing entries, append a new entry */ #ifdef DEBUG assert(lp->lpAddrCnt < lp->lpAddrMax); #endif *lp->lpAddrNxt++ = val; lp->lpAddrCnt++; } /* If we get here it means that we've just added a new entry to the pool. We better not be issuing an instruction since all entries are supposed to have been added by that time. */ assert(issue == false); return 0; } /***************************************************************************** * * Compute a conservative estimate of the size of each literal pool. */ void emitter::emitEstimateLitPools() { emitTotLPcount = 0; #ifdef DEBUG unsigned words = 0; unsigned longs = 0; unsigned addrs = 0; #endif /* Does it look like we might need to create a constant pool? */ if (emitEstLPwords || emitEstLPlongs || emitEstLPaddrs) { size_t curOffs; insGroup * tempIG; insGroup * nextIG; insGroup * lastIG = NULL; insGroup * bestIG = NULL; unsigned bestWc = 0; unsigned bestLc = 0; unsigned bestAc = 0; unsigned bestSz; unsigned prevWc = 0; unsigned prevLc = 0; unsigned prevAc = 0; unsigned prevSz; unsigned bestMx = UINT_MAX; unsigned need_bestmx = false; unsigned need_bestmxw = false; unsigned begOfsW = 0; unsigned begOfsL = 0; unsigned wordCnt = 0; unsigned longCnt = 0; unsigned addrCnt = 0; unsigned litSize = 0; unsigned endOffs; unsigned maxOffs = UINT_MAX; bool doneIG = false; bool skipIG = false; short * LPtabW = NULL; short * LPnxtW = NULL; long * LPtabL = NULL; long * LPnxtL = NULL; LPaddrDesc * LPtabA = NULL; LPaddrDesc * LPnxtA = NULL; /* If the total estimated size of the entire method is less than the max. distance for "medium" jumps, decrement the "long" literal pool use counts for each jump marked as long. */ #if !TGT_ARM if (emitCurCodeOffset < -min(JMP_DIST_SMALL_MAX_NEG, JCC_DIST_MIDDL_MAX_NEG) && emitCurCodeOffset < min(JMP_DIST_SMALL_MAX_POS, JCC_DIST_MIDDL_MAX_POS)) { instrDescJmp * jmp; for (jmp = emitJumpList; jmp; jmp = jmp->idjNext) { insGroup * jmpIG; if (jmp->idInsFmt == IF_JMP_TAB) continue; #if TGT_MIPSFP assert( (jmp->idInsFmt == IF_LABEL) || (jmp->idInsFmt == IF_JR) || (jmp->idInsFmt == IF_JR_R) || (jmp->idInsFmt == IF_RR_O) || (jmp->idInsFmt == IF_R_O) || (jmp->idInsFmt == IF_O)); #elif TGT_MIPS32 assert( (jmp->idInsFmt == IF_LABEL) || (jmp->idInsFmt == IF_JR) || (jmp->idInsFmt == IF_JR_R) || (jmp->idInsFmt == IF_RR_O) || (jmp->idInsFmt == IF_R_O)); #else assert(jmp->idInsFmt == IF_LABEL); #endif /* Get the group the jump is in */ jmpIG = jmp->idjIG; /* Decrease the "long" litpool count of the group */ assert(jmpIG->igLPuseCntL > 0); jmpIG->igLPuseCntL--; emitEstLPlongs--; } #if TGT_SH3 all_jumps_shortened = 1; #endif /* Are there any litpool users left? */ if (!emitEstLPwords && !emitEstLPlongs && !emitEstLPaddrs) goto DONE_LP; } else { #if TGT_SH3 all_jumps_shortened = 0; #endif } #endif //TGT_ARM #ifdef DEBUG if (verbose) { printf("\nInstruction list before literal pools are added:\n\n"); emitDispIGlist(false); } /* Make sure our estimates were accurate */ unsigned wordChk; unsigned longChk; unsigned addrChk; for (wordChk = longChk = addrChk = 0, tempIG = emitIGlist; tempIG; tempIG = tempIG->igNext) { wordChk += tempIG->igLPuseCntW; longChk += tempIG->igLPuseCntL; addrChk += tempIG->igLPuseCntA; emitEstLPwords+=2; emitEstLPlongs+=2; // @TODO [REVISIT] [04/16/01] []: // any lit pool can add a word for alignment. // also can add a long for a jump over the litpool. // here we pray there is not an avg of more than two lit pool per instr group. } assert(wordChk <= emitEstLPwords); assert(longChk <= emitEstLPlongs); assert(addrChk <= emitEstLPaddrs); #else for (tempIG = emitIGlist; tempIG; tempIG = tempIG->igNext) { emitEstLPwords+=2; emitEstLPlongs+=2; } #endif /* Allocate the arrays of the literal pool word/long entries */ LPtabW = LPnxtW = (short *)emitGetMem(roundUp(emitEstLPwords * sizeof(*LPtabW))); LPtabL = LPnxtL = (long *)emitGetMem( emitEstLPlongs * sizeof(*LPtabL) ); LPtabA = LPnxtA = (LPaddrDesc*)emitGetMem( emitEstLPaddrs * sizeof(*LPtabA) ); /* We have not created any actual lit pools yet */ emitLitPoolList = emitLitPoolLast = NULL; /* Walk the group list, looking for lit pool use */ for (tempIG = emitIGlist, curOffs = litSize = bestSz = 0;;) { assert(lastIG == NULL || lastIG->igNext == tempIG); /* Record the (possibly) updated group offset */ tempIG->igOffs = curOffs; /* Get hold of the next group */ nextIG = tempIG->igNext; /* Compute the offset of the group's end */ endOffs = tempIG->igOffs + tempIG->igSize; //printf("\nConsider IG #%02u at %04X\n", tempIG->igNum, tempIG->igOffs); //printf("bestsz is %x\n", bestSz); /* Is the end of this group too far? */ int nextLitSize = tempIG->igLPuseCntW * 2 + tempIG->igLPuseCntL * sizeof(int ) + tempIG->igLPuseCntA * sizeof(void*); if (endOffs + litSize + nextLitSize > maxOffs) //if (endOffs + litSize > maxOffs) { size_t offsAdj; /* We must place a literal pool before this group */ if (!bestIG) { // Ouch - we'll have to jump over the literal pool // since we have to place it here and there were // no good places to put earlier. For now, we'll // just set a flag on the liter pool (and bump its // size), and we'll issue the jump just before we // write out the literal pool contents. skipIG = true; bestIG = lastIG; ALL_LP: bestWc = wordCnt; bestLc = longCnt; bestAc = addrCnt; bestSz = litSize; bestMx = UINT_MAX; //printf ("had to split %d %d %d %x!\n", bestWc, bestLc, bestAc, litSize); } assert(bestIG && ((bestIG->igFlags & IGF_END_NOREACH) || skipIG)); /* Append an LP right after "bestIG" */ //printf("lit placed after IG #%02u at %04X uses : WLA %d %d %d : maxOffs was %X\n", bestIG->igNum, bestIG->igOffs, bestWc, bestLc, bestAc, maxOffs); //printf("lit size (bestsz) was %x, litsize+endoffs = %x endoffs = %x\n", bestSz, bestSz+bestIG->igOffs+bestIG->igSize, bestIG->igOffs+bestIG->igSize); //printf("lit uses lpnxtW : %x\t lpnxtL : %x\t lpnxtA : %x\n", LPnxtW, LPnxtL, LPnxtA); offsAdj = emitAddLitPool(bestIG, skipIG, bestWc, &LPnxtW, bestLc, &LPnxtL, bestAc, &LPnxtA); // Do we need to skip over the literal pool? if (skipIG) { /* Reset the flag */ skipIG = false; /* Update this group's and the current offset */ tempIG->igOffs += offsAdj; } else { /* Update the intervening group offsets */ while (bestIG != tempIG) { bestIG = bestIG->igNext; bestIG->igOffs += offsAdj; } } /* Update the total code size */ emitCurCodeOffset += offsAdj; /* Update the current offset */ curOffs += offsAdj; /* Update the outstanding/"best" LP ref values */ wordCnt -= bestWc; bestWc = 0; longCnt -= bestLc; bestLc = 0; addrCnt -= bestAc; bestAc = 0; litSize -= bestSz; bestSz = 0; /* if we've unloaded some litpool entries on bestIG but still */ /* need to put more before the current IG, then need a skip and loop back */ if (endOffs + litSize + nextLitSize > bestMx) { skipIG = true; bestIG = lastIG; goto ALL_LP; } maxOffs = bestMx; bestMx = UINT_MAX; /* We've used up our "best" IG */ bestIG = NULL; if (doneIG) goto DONE_LP; } #ifdef DEBUG //printf("IG #%02u at %04X uses : WLA %d %d %d words %d longs %d\n", tempIG->igNum, tempIG->igOffs, tempIG->igLPuseCntW, tempIG->igLPuseCntL, tempIG->igLPuseCntA, wordCnt, longCnt); //printf("IG #%02u at %04X uses : WLA %d %d %d maxoffs %x bestMx %x\n", tempIG->igNum, tempIG->igOffs, tempIG->igLPuseCntW, tempIG->igLPuseCntL, tempIG->igLPuseCntA, maxOffs, bestMx); //printf("litsize : %x\n", litSize); words += tempIG->igLPuseCntW; longs += tempIG->igLPuseCntL; addrs += tempIG->igLPuseCntA; #endif /* Does this group need any LP entries? */ prevWc = wordCnt; prevLc = longCnt; prevAc = addrCnt; prevSz = litSize; if (tempIG->igLPuseCntW) { if (!wordCnt || !bestWc || need_bestmx || need_bestmxw) { unsigned tmpOffs; /* This is the first "word" LP use */ tmpOffs = tempIG->igOffs; #if SCHEDULER if (!emitComp->opts.compSchedCode) #endif tmpOffs += tempIG->igLPuse1stW; /* Figure out the farthest acceptable offset */ tmpOffs += LIT_POOL_MAX_OFFS_WORD - 2*INSTRUCTION_SIZE; /* Update the max. offset */ if (!wordCnt) { if (maxOffs > tmpOffs) maxOffs = tmpOffs; } if (need_bestmx || need_bestmxw) //else { if (bestMx > tmpOffs) bestMx = tmpOffs; need_bestmx = false; need_bestmxw = false; } } wordCnt += tempIG->igLPuseCntW; litSize += tempIG->igLPuseCntW * 2; //bestSz += tempIG->igLPuseCntW * 2; } if (tempIG->igLPuseCntL || tempIG->igLPuseCntA) { if ((!longCnt && !addrCnt) || (!bestLc && !bestAc) || need_bestmx) { unsigned tmpOffs; /* This is the first long/addr LP use */ tmpOffs = tempIG->igOffs; int firstuse = INT_MAX; if (tempIG->igLPuseCntL) firstuse = tempIG->igLPuse1stL; if (tempIG->igLPuseCntA) firstuse = min (firstuse, tempIG->igLPuse1stA); #if SCHEDULER if (!emitComp->opts.compSchedCode) #endif tmpOffs += firstuse; /* Figure out the farthest acceptable offset */ tmpOffs += LIT_POOL_MAX_OFFS_LONG - 2*INSTRUCTION_SIZE; /* Update the max. offset */ if (!longCnt && !addrCnt) { if (maxOffs > tmpOffs) maxOffs = tmpOffs; } if (need_bestmx) { if (bestMx > tmpOffs) bestMx = tmpOffs; need_bestmx = false; } } longCnt += tempIG->igLPuseCntL; litSize += tempIG->igLPuseCntL * sizeof(int ); //bestSz += tempIG->igLPuseCntL * sizeof(int ); addrCnt += tempIG->igLPuseCntA; litSize += tempIG->igLPuseCntA * sizeof(void*); //bestSz += tempIG->igLPuseCntA * sizeof(void*); } /* Is the end of this group unreachable? */ if (tempIG->igFlags & IGF_END_NOREACH) { /* Looks like the best candidate so far */ bestIG = tempIG; /* Remember how much we can cram into the best candidate */ bestWc = wordCnt; bestLc = longCnt; bestAc = addrCnt; //bestSz = 0; bestSz = litSize; bestMx = UINT_MAX; need_bestmx = true; need_bestmxw = true; } /* Is this the last group? */ //printf("IG #%02u at %04X uses : WLA %d %d %d maxoffs %x bestMx %x\n", tempIG->igNum, tempIG->igOffs, tempIG->igLPuseCntW, tempIG->igLPuseCntL, tempIG->igLPuseCntA, maxOffs, bestMx); if (!nextIG) { assert(bestIG == tempIG); /* Is there any need for a literal pool? */ if (wordCnt || longCnt || addrCnt) { /* Prevent endless looping */ if (doneIG) break; doneIG = true; bestWc = wordCnt; bestLc = longCnt; bestAc = addrCnt; bestSz = litSize; goto ALL_LP; } /* We're all done */ break; } /* Update the current offset and continue with the next group */ curOffs += tempIG->igSize; lastIG = tempIG; tempIG = nextIG; } DONE_LP:; #ifdef DEBUG if (verbose) { printf("Est word need = %3u, alloc = %3u, used = %3u\n", emitEstLPwords, words, LPnxtW - LPtabW); printf("Est long need = %3u, alloc = %3u, used = %3u\n", emitEstLPlongs, longs, LPnxtL - LPtabL); printf("Est addr need = %3u, alloc = %3u, used = %3u\n", emitEstLPaddrs, addrs, LPnxtA - LPtabA); } #endif #ifdef DEBUG if (verbose) { printf("\nInstruction list after literal pools have been added:\n\n"); emitDispIGlist(false); } assert(words <= emitEstLPwords && emitEstLPwords + LPtabW >= LPnxtW); assert(longs <= emitEstLPlongs && emitEstLPlongs + LPtabL >= LPnxtL); assert(addrs <= emitEstLPaddrs && emitEstLPaddrs + LPtabA >= LPnxtA); #endif } /* Make sure all the IG offsets are up-to-date */ emitCheckIGoffsets(); } /***************************************************************************** * * Finalize the size and contents of each literal pool. */ void emitter::emitFinalizeLitPools() { litPool * curLP; insGroup * litIG; instrDescLPR* lprID; insGroup * thisIG; size_t offsIG; /* Do we have any literal pools? */ if (!emitTotLPcount) return; #ifdef DEBUG if (verbose) { printf("\nInstruction list before final literal pool allocation:\n\n"); emitDispIGlist(false); } emitCheckIGoffsets(); #endif #if SMALL_DIRECT_CALLS /* Do we already know where the code for this method will end up? */ if (emitLPmethodAddr) emitShrinkShortCalls(); #endif /* Get hold of the first literal pool and its group */ curLP = emitLitPoolList; assert(curLP); litIG = curLP->lpIG; lprID = emitLPRlist; /* Walk the instruction groups to create the literal pool contents */ for (thisIG = emitIGlist, offsIG = 0; thisIG; thisIG = thisIG->igNext) { thisIG->igOffs = offsIG; /* Does this group have any lit pool entries? */ if (thisIG->igLPuseCntW || thisIG->igLPuseCntL || thisIG->igLPuseCntA) { /* Walk the list of instructions that reference the literal pool */ #ifdef DEBUG unsigned wc = 0; unsigned lc = 0; unsigned ac = 0; #endif do { #if TGT_SH3 #ifdef DEBUG emitDispIns(lprID, false, true, false, 0); #endif // maybe this was because of a jmp instruction if (lprID->idlIG != thisIG) { unsigned cnt = thisIG->igInsCnt; BYTE * ins = thisIG->igData; instrDesc* id; #ifdef DEBUG _flushall(); #endif do { instrDesc * id = (instrDesc *)ins; //emitDispIns(id, false, true, false, 0); if (id->idInsFmt == IF_LABEL) { /* Is the jump "very long" ? */ if (((instrDescJmp*)lprID)->idjShort == false && ((instrDescJmp*)lprID)->idjMiddle == false) { /* Add a label entry to the current LP */ #ifdef DEBUG lc++; #endif } } ins += emitSizeOfInsDsc(id); } while (--cnt); break; thisIG = thisIG->igNext; while (!(thisIG->igLPuseCntW || thisIG->igLPuseCntL || thisIG->igLPuseCntA)) thisIG = thisIG->igNext; continue; } #endif assert(lprID && lprID->idlIG == thisIG); switch (lprID->idInsFmt) { case IF_RWR_LIT: #ifdef DEBUG /* Just to make sure the counts agree */ if (emitGetInsLPRtyp(lprID) == CT_INTCNS) { if (emitDecodeSize(lprID->idOpSize) == 2) wc++; else lc++; } else { ac++; } #endif #if SMALL_DIRECT_CALLS /* Ignore calls that have been made direct */ if (lprID->idIns == DIRECT_CALL_INS) break; #endif /* Add an entry for the operand to the current LP */ emitAddLitPoolEntry(curLP, lprID, false); break; case IF_LABEL: /* Is the jump "very long" ? */ if (((instrDescJmp*)lprID)->idjShort == false && ((instrDescJmp*)lprID)->idjMiddle == false) { /* Add a label entry to the current LP */ #ifdef DEBUG lc++; #endif assert(!"add long jump label address to litpool"); } break; #ifdef DEBUG default: assert(!"unexpected instruction in LP list"); #endif } lprID = lprID->idlNext; } while (lprID && lprID->idlIG == thisIG); #ifdef DEBUG assert(thisIG->igLPuseCntW == wc); //assert(thisIG->igLPuseCntL == lc); assert(thisIG->igLPuseCntA == ac); #endif } /* Is the current literal pool supposed to go after this group? */ if (litIG == thisIG) { unsigned begOffs; unsigned jmpSize; unsigned wordCnt; unsigned longCnt; unsigned addrCnt; assert(curLP && curLP->lpIG == thisIG); /* Subtract the estimated pool size from the group's size */ thisIG->igSize -= curLP->lpSizeEst; assert((int)thisIG->igSize >= 0); /* Compute the starting offset of the pool */ begOffs = offsIG + thisIG->igSize; /* Adjust by the size of the "skip over LP" jump, if present */ jmpSize = 0; if (curLP->lpJumpIt) { jmpSize = emitLPjumpOverSize(curLP); begOffs += jmpSize; } /* Get hold of the counts */ wordCnt = curLP->lpWordCnt; longCnt = curLP->lpLongCnt; addrCnt = curLP->lpAddrCnt; /* Do we need to align the first long/addr? */ curLP->lpPadding = curLP->lpPadFake = false; if ((begOffs & 3) && (longCnt || addrCnt)) { /* We'll definitely need one word of padding */ curLP->lpPadding = true; /* Do we have any word-sized entries? */ if (!wordCnt) { /* No, we'll have to pad by adding a "fake" word */ curLP->lpPadFake = true; wordCnt++; } } /* Compute the final (accurate) size */ curLP->lpSize = wordCnt * 2 + longCnt * 4 + addrCnt * 4; /* Make sure the original estimate wasn't too low */ assert(curLP->lpSize <= curLP->lpSizeEst); /* Record the pool's offset within the method */ curLP->lpOffs = begOffs; /* Add the actual size to the group's size */ thisIG->igSize += curLP->lpSize + jmpSize; /* Move to the next literal pool, if any */ curLP = curLP->lpNext; litIG = curLP ? curLP->lpIG : NULL; } offsIG += thisIG->igSize; } /* We should have processed all the literal pools */ assert(curLP == NULL); assert(litIG == NULL); assert(lprID == NULL); /* Update the total code size of the method */ emitTotalCodeSize = offsIG; /* Make sure all the IG offsets are up-to-date */ emitCheckIGoffsets(); } /*****************************************************************************/ #if SMALL_DIRECT_CALLS /***************************************************************************** * * Convert as many calls as possible into the direct pc-relative variety. */ void emitter::emitShrinkShortCalls() { litPool * curLP; insGroup * litIG; unsigned litIN; instrDescLPR* lprID; size_t ofAdj; bool shrnk; bool swapf; /* Do we have any candidate calls at all? */ #ifndef TGT_SH3 if (!emitTotDCcount) return; #endif /* This is to make recursive calls find their target address */ emitCodeBlock = emitLPmethodAddr; /* Get hold of the first literal pool and the group it belongs to */ curLP = emitLitPoolList; assert(curLP); litIG = curLP->lpIG; litIN = litIG->igNum; /* Remember whether we shrank any calls at all */ shrnk = false; /* Remember whether to swap any calls to fill branch-delay slots */ swapf = false; #if TGT_SH3 shrnk = true; // always need to do delay slots on sh3 swapf = true; #endif /* Walk the list of instructions that reference the literal pool */ for (lprID = emitLPRlist; lprID; lprID = lprID->idlNext) { instrDesc * nxtID; BYTE * srcAddr; BYTE * dstAddr; int difAddr; /* Does this instruction reference a new literal pool? */ while (lprID->idlIG->igNum > litIN) { /* Move to the next literal pool */ curLP = curLP->lpNext; assert(curLP); litIG = curLP->lpIG; litIN = litIG->igNum; } /* We're only interested in direct-via-register call sequences */ if (lprID->idInsFmt != IF_RWR_LIT) continue; if (lprID->idIns != LIT_POOL_LOAD_INS) continue; if (lprID->idlCall == NULL) continue; switch (emitGetInsLPRtyp(lprID)) { case CT_DESCR: #if defined(BIRCH_SP2) && TGT_SH3 case CT_RELOCP: #endif case CT_USER_FUNC: break; default: continue; } /* Here we have a direct call via a register */ nxtID = lprID->idlCall; assert(nxtID->idIns == INDIRECT_CALL_INS); assert(nxtID->idRegGet() == lprID->idRegGet()); /* Assume the call will not be short */ lprID->idlCall = NULL; /* Compute the address from where the call will originate */ srcAddr = emitDirectCallBase(emitCodeBlock + litIG-> igOffs + lprID->idlOffs); /* Ask for the address of the target and see how far it is */ #if defined(BIRCH_SP2) && TGT_SH3 if (~0 != (unsigned) nxtID->idAddr.iiaMethHnd) { OptPEReader *oper = &((OptJitInfo*)emitComp->info.compCompHnd)->m_PER; dstAddr = (BYTE *)oper->m_rgFtnInfo[(unsigned)nxtID->idAddr.iiaMethHnd].m_pNative; } else dstAddr = 0; #else # ifdef BIRCH_SP2 assert (0); // you need to guarantee iiaMethHnd if you want this to work <tanj> # endif dstAddr = emitMethodAddr(lprID); #endif /* If the target address isn't known, there isn't much we can do */ if (!dstAddr) continue; // printf("Direct call: %08X -> %08X , dist = %d\n", srcAddr, dstAddr, dstAddr - srcAddr); /* Compute the distance and see if it's in range */ difAddr = dstAddr - srcAddr; if (difAddr < CALL_DIST_MAX_NEG) continue; if (difAddr > CALL_DIST_MAX_POS) continue; /* The call can be made short */ lprID->idlCall = nxtID; /* Change the load-address instruction to a direct call */ lprID->idIns = DIRECT_CALL_INS; /* The indirect call instruction won't generate any code */ nxtID->idIns = INS_ignore; /* Update the group's size [ISSUE: may have to use nxtID's group] */ lprID->idlIG->igSize -= INSTRUCTION_SIZE; /* Remember that we've shrunk at least one call */ shrnk = true; /* Is there a "nop" filling the branch-delay slot? */ if (Compiler::instBranchDelay(DIRECT_CALL_INS)) { instrDesc * nopID; /* Get hold of the instruction that follows the call */ nopID = (instrDesc*)((BYTE*)nxtID + emitSizeOfInsDsc(nxtID)); /* Do we have a (branch-delay) nop? */ if (nopID->idIns == INS_nop) { /* We'll get rid of the nop later (see next loop below) */ lprID->idSwap = true; swapf = true; } } } /* We should have processed all the literal pools */ // maybe there are lit pools after this that are now empty // (could have been used by jumps that are now long) //assert(curLP->lpNext == NULL); //assert(lprID == NULL); /* Did we manage to shrink any calls? */ if (shrnk) { insGroup * thisIG; size_t offsIG; for (thisIG = emitIGlist, offsIG = 0; thisIG; thisIG = thisIG->igNext) { instrDesc * id; int cnt; /* Update the group's offset */ thisIG->igOffs = offsIG; /* Does this group have any address entries? */ if (!thisIG->igLPuseCntA) goto NXT_IG; /* Did we find any branch-delay slots that can be eliminated? */ if (!swapf) goto NXT_IG; /* Walk the instructions of the group, looking for the following sequence: <any_ins> direct_call nop If we find it, we swap the first instruction with the call and zap the nop. */ id = (instrDesc *)thisIG->igData; cnt = thisIG->igInsCnt - 2; while (cnt > 0) { instrDesc * nd; /* Get hold of the instruction that follows */ nd = (instrDesc*)((BYTE*)id + emitSizeOfInsDsc(id)); /* Is the following instruction a direct call? */ if (nd->idIns == DIRECT_CALL_INS && nd->idSwap) { instrDesc * n1; instrDesc * n2; /* Skip over the indirect call */ n1 = (instrDesc*)((BYTE*)nd + emitSizeOfInsDsc(nd)); assert(n1->idIns == INS_ignore); /* Get hold of the "nop" that is known to follow */ n2 = (instrDesc*)((BYTE*)n1 + emitSizeOfInsDsc(n1)); assert(n2->idIns == INS_nop); /* The call was marked as "swapped" only temporarily */ nd->idSwap = false; /* Are we scheduling "for real" ? */ #if SCHEDULER if (emitComp->opts.compSchedCode) { /* Move the "nop" into the branch-delay slot */ n1->idIns = INS_nop; n2->idIns = INS_ignore; } else #endif { if (!emitInsDepends(nd, id)) { /* Swap the call with the previous instruction */ id->idSwap = true; /* Zap the branch-delay slot (the "nop") */ n2->idIns = INS_ignore; /* Update the group's size */ thisIG->igSize -= INSTRUCTION_SIZE; } } } #if TGT_SH3 else if (nd->idIns == INS_jsr) { instrDesc * nop; nop = (instrDesc*)((BYTE*)nd + emitSizeOfInsDsc(nd)); assert(nop->idIns == INS_nop); if (!emitInsDepends(nd, id)) { /* Swap the call with the previous instruction */ id->idSwap = true; /* Zap the branch-delay slot (the "nop") */ nop->idIns = INS_ignore; /* Update the group's size */ thisIG->igSize -= INSTRUCTION_SIZE; } } #endif /* Continue with the next instruction */ id = nd; cnt--; } NXT_IG: /* Update the running offset */ offsIG += thisIG->igSize; } assert(emitTotalCodeSize); emitTotalCodeSize = offsIG; } /* Make sure all the IG offsets are up-to-date */ emitCheckIGoffsets(); } /*****************************************************************************/ #endif//SMALL_DIRECT_CALLS /***************************************************************************** * * Output the contents of the next literal pool. */ BYTE * emitter::emitOutputLitPool(litPool *lp, BYTE *cp) { unsigned wordCnt = lp->lpWordCnt; short * wordPtr = lp->lpWordTab; unsigned longCnt = lp->lpLongCnt; long * longPtr = lp->lpLongTab; unsigned addrCnt = lp->lpAddrCnt; LPaddrDesc * addrPtr = lp->lpAddrTab; size_t curOffs; /* Bail of no entry ended up being used in this pool */ if ((wordCnt|longCnt|addrCnt) == 0) return cp; /* Compute the current code offset */ curOffs = emitCurCodeOffs(cp); /* Do we need to jump over the literal pool? */ if (lp->lpJumpIt) { /* Reserve space for the jump over the pool */ curOffs += emitLPjumpOverSize(lp); } #if SCHEDULER bool addPad = false; /* Has the offset of this LP changed? */ if (lp->lpOffs != curOffs) { LPcrefDesc * ref; size_t oldOffs = lp->lpOffs; size_t tmpOffs = curOffs; assert(emitComp->opts.compSchedCode); /* Has the literal pool moved by an unaligned amount? */ if ((curOffs - oldOffs) & 2) { /* Did we originally think we would need padding? */ if (lp->lpPadding) { /* OK, we thought we'd need padding but with the new LP position that's not the case any more. If the padding value is an unused one, simply get rid of it; if it contains a real word entry, we'll have to add padding in front of the LP to keep things aligned, as moving the initial word entry is too difficult at this point. */ if (lp->lpPadFake) { /* Padding no longer needed, just get rid of it */ lp->lpPadding = lp->lpPadFake = false; } else { /* This is the unfortunate scenario described above; we thought we'd need padding and we achieved this by sticking the first word entry in front of all the dword entries. It's simply too hard to move that initial word someplace else at this point, so instead we just add another pad word. Sigh. */ ADD_PAD: /* Come here to add a pad word in front of the LP */ addPad = true; lp->lpSize += 2; /* Update the offset and see if it's still different */ curOffs += 2; if (curOffs == oldOffs) goto DONE_MOVE; } } else { /* There is currently no padding. If there are any entries that need to be aligned, we'll have to add padding now, lest they end up mis-aligned. */ assert((oldOffs & 2) == 0); assert((curOffs & 2) != 0); if (longCnt || addrCnt) { lp->lpPadding = lp->lpPadFake = true; /* Does the padding take up all the savings? */ if (oldOffs == curOffs + sizeof(short)) { /* Nothing really changed, no need to patch */ goto NO_PATCH; } tmpOffs += sizeof(short); } } } /* Patch all issued instructions that reference this LP */ for (ref = lp->lpRefs; ref; ref = ref->lpcNext) emitPatchLPref(ref->lpcAddr, oldOffs, tmpOffs); NO_PATCH: /* Update the offset of the LP */ lp->lpOffs = curOffs; assert(oldOffs != curOffs); } DONE_MOVE: #else assert(lp->lpOffs == curOffs); #endif /* Do we need to jump over the literal pool? */ if (lp->lpJumpIt) { #ifdef DEBUG /* Remember the code offset so that we can verify the jump size */ unsigned jo = emitCurCodeOffs(cp); #endif /* Skip over the literal pool */ #ifdef DEBUG emitDispIG = lp->lpIG->igNext; // for instruction display purposes #endif #if TGT_SH3 if (lp->lpJumpSmall) { cp += emitOutputWord(cp, 0x0009); } #endif cp = emitOutputFwdJmp(cp, lp->lpSize, lp->lpJumpSmall, lp->lpJumpMedium); /* Make sure the issued jump had the expected size */ #ifdef DEBUG assert(jo + emitLPjumpOverSize(lp) == emitCurCodeOffs(cp)); #endif } #ifdef DEBUG if (disAsm) printf("\n; Literal pool %02u:\n", lp->lpNum); #endif #ifdef DEBUG unsigned lpBaseOffs = emitCurCodeOffs(cp); #endif #if SCHEDULER /* Do we need to insert additional padding? */ if (addPad) { /* This can only happen when the scheduler is enabled */ assert(emitComp->opts.compSchedCode); #ifdef DEBUG if (disAsm) { emitDispInsOffs(emitCurCodeOffs(cp), dspGCtbls); printf(EMIT_DSP_INS_NAME "0 ; pool alignment (due to scheduling)\n", ".data.w"); } #endif cp += emitOutputWord(cp, 0); } #endif /* Output the contents of the literal pool */ if (lp->lpPadding) { #ifdef DEBUG if (disAsm) emitDispInsOffs(emitCurCodeOffs(cp), dspGCtbls); #endif /* Are we padding with the first word entry? */ if (lp->lpPadFake) { #if ! SCHEDULER assert(wordCnt == 0); #endif #ifdef DEBUG if (disAsm) printf(EMIT_DSP_INS_NAME "0 ; pool alignment\n", ".data.w"); #endif cp += emitOutputWord(cp, 0); } else { assert(wordCnt != 0); #ifdef DEBUG if (disAsm) printf(EMIT_DSP_INS_NAME "%d\n", ".data.w", *wordPtr); #endif cp += emitOutputWord(cp, *wordPtr); wordPtr++; wordCnt--; } } /* Output any long entries */ while (longCnt) { int val = *longPtr; #ifdef DEBUG if (disAsm) { emitDispInsOffs(emitCurCodeOffs(cp), dspGCtbls); printf(EMIT_DSP_INS_NAME "%d\n", ".data.l", val); } #endif assert(longPtr < lp->lpLongNxt); cp += emitOutputLong(cp, val); longPtr++; longCnt--; } /* Output any addr entries */ while (addrCnt) { gtCallTypes addrTyp = addrPtr->lpaTyp; void * addrHnd = addrPtr->lpaHnd; void * addr; /* What kind of an address do we have here? */ switch (addrTyp) { InfoAccessType accessType = IAT_VALUE; #ifdef BIRCH_SP2 case CT_RELOCP: addr = (BYTE*)addrHnd; // record that this addr must be in the .reloc section emitCmpHandle->recordRelocation((void**)cp, IMAGE_REL_BASED_HIGHLOW); break; #endif case CT_CLSVAR: addr = (BYTE *)emitComp->eeGetFieldAddress(addrHnd); if (!addr) NO_WAY("could not obtain address of static field"); break; case CT_HELPER: assert(!"ToDo"); break; case CT_DESCR: addr = (BYTE*)emitComp->eeGetMethodEntryPoint((CORINFO_METHOD_HANDLE)addrHnd, &accessType); assert(accessType == IAT_PVALUE); break; case CT_INDIRECT: assert(!"this should never happen"); case CT_USER_FUNC: if (emitComp->eeIsOurMethod((CORINFO_METHOD_HANDLE)addrHnd)) { /* Directly recursive call */ addr = emitCodeBlock; } else { addr = (BYTE*)emitComp->eeGetMethodPointer((CORINFO_METHOD_HANDLE)addrHnd, &accessType); assert(accessType == IAT_VALUE); } break; default: assert(!"unexpected call type"); } #ifdef DEBUG if (disAsm) { emitDispInsOffs(emitCurCodeOffs(cp), dspGCtbls); printf(EMIT_DSP_INS_NAME, ".data.l"); printf("0x%08X ; ", addr); if (addrTyp == CT_CLSVAR) { printf("&"); emitDispClsVar((CORINFO_FIELD_HANDLE) addrHnd, 0); } else { const char * methodName; const char * className; printf("&"); methodName = emitComp->eeGetMethodName((CORINFO_METHOD_HANDLE) addrHnd, &className); if (className == NULL) printf("'%s'", methodName); else printf("'%s.%s'", className, methodName); } printf("\n"); } #endif assert(addrPtr < lp->lpAddrNxt); cp += emitOutputLong(cp, (int)addr); addrPtr++; addrCnt--; } /* Output any word entries that may remain */ while (wordCnt) { int val = *wordPtr; #ifdef DEBUG if (disAsm) { emitDispInsOffs(emitCurCodeOffs(cp), dspGCtbls); printf(EMIT_DSP_INS_NAME "%d\n", ".data.w", val); } #endif assert(wordPtr < lp->lpWordNxt); cp += emitOutputWord(cp, val); wordPtr++; wordCnt--; } /* Make sure we've generated the exact right number of entries */ assert(wordPtr == lp->lpWordNxt); assert(longPtr == lp->lpLongNxt); assert(addrPtr == lp->lpAddrNxt); /* Make sure the size matches our expectations */ assert(lpBaseOffs + lp->lpSize == emitCurCodeOffs(cp)); return cp; } /*****************************************************************************/ #if SCHEDULER /***************************************************************************** * * Record a reference to a literal pool entry so that the distance can be * updated if the literal pool moves due to scheduling. */ struct LPcrefDesc { LPcrefDesc * lpcNext; // next ref to this literal pool void * lpcAddr; // address of reference }; void emitter::emitRecordLPref(litPool *lp, BYTE *dst) { LPcrefDesc * ref; assert(emitComp->opts.compSchedCode); /* Allocate a reference descriptor and add it to the list */ ref = (LPcrefDesc *)emitGetMem(sizeof(*ref)); ref->lpcAddr = dst; ref->lpcNext = lp->lpRefs; lp->lpRefs = ref; } /*****************************************************************************/ #endif//SCHEDULER /*****************************************************************************/ #endif//EMIT_USE_LIT_POOLS /*****************************************************************************/ /***************************************************************************** * * Return the allocated size (in bytes) of the given instruction descriptor. */ size_t emitter::emitSizeOfInsDsc(instrDesc *id) { if (emitIsTinyInsDsc(id)) return TINY_IDSC_SIZE; if (emitIsScnsInsDsc(id)) { return id->idInfo.idLargeCns ? sizeof(instrBaseCns) : SCNS_IDSC_SIZE; } assert((unsigned)id->idInsFmt < emitFmtCount); switch (emitFmtToOps[id->idInsFmt]) { case ID_OP_NONE: break; case ID_OP_JMP: return sizeof(instrDescJmp); case ID_OP_CNS: return emitSizeOfInsDsc((instrDescCns *)id); case ID_OP_DSP: return emitSizeOfInsDsc((instrDescDsp *)id); case ID_OP_DC: return emitSizeOfInsDsc((instrDescDspCns*)id); case ID_OP_SCNS: break; case ID_OP_CALL: if (id->idInfo.idLargeCall) { /* Must be a "fat" indirect call descriptor */ return sizeof(instrDescCIGCA); } assert(id->idInfo.idLargeCns == false); assert(id->idInfo.idLargeDsp == false); break; case ID_OP_SPEC: #if EMIT_USE_LIT_POOLS switch (id->idInsFmt) { case IF_RWR_LIT: return sizeof(instrDescLPR); } #endif // EMIT_USE_LIT_POOLS assert(!"unexpected 'special' format"); default: assert(!"unexpected instruction descriptor format"); } return sizeof(instrDesc); } /*****************************************************************************/ #ifdef DEBUG /***************************************************************************** * * Return a string that represents the given register. */ const char * emitter::emitRegName(emitRegs reg, int size, bool varName) { static char rb[128]; assert(reg < SR_COUNT); // CONSIDER: Make the following work just using a code offset const char * rn = emitComp->compRegVarName((regNumber)reg, varName); // assert(size == EA_GCREF || size == EA_BYREF || size == EA_4BYTE); return rn; } /***************************************************************************** * * Display a static data member reference. */ void emitter::emitDispClsVar(CORINFO_FIELD_HANDLE hand, int offs, bool reloc) { if (varNames) { const char * clsn; const char * memn; memn = emitComp->eeGetFieldName(hand, &clsn); printf("'%s.%s", clsn, memn); if (offs) printf("%+d", offs); printf("'"); } else { printf("classVar[%08X]", hand); } } /***************************************************************************** * * Display a stack frame reference. */ void emitter::emitDispFrameRef(int varx, int offs, int disp, bool asmfm) { int addr; bool bEBP; assert(emitComp->lvaDoneFrameLayout); addr = emitComp->lvaFrameAddress(varx, &bEBP) + disp; assert((int)addr >= 0); printf("@(%u,%s)", addr, bEBP ? "fp" : "sp"); if (varx >= 0 && varNames) { Compiler::LclVarDsc*varDsc; const char * varName; assert((unsigned)varx < emitComp->lvaCount); varDsc = emitComp->lvaTable + varx; varName = emitComp->compLocalVarName(varx, offs); if (varName) { printf("'%s", varName); if (disp < 0) printf("-%d", -disp); else if (disp > 0) printf("+%d", +disp); printf("'"); } } } /***************************************************************************** * * Display an indirection (possibly auto-inc/dec). */ void emitter::emitDispIndAddr(emitRegs base, bool dest, bool autox, int disp) { if (dest) { printf("@%s%s", autox ? "-" : "", emitRegName(base)); } else { printf("@%s%s", emitRegName(base), autox ? "+" : ""); } } #endif // DEBUG #endif//TGT_RISC /*****************************************************************************/
28.740498
196
0.449116
npocmaka
13f93bd985dd4c99bafd0fe35e35194fe71313b3
6,453
cpp
C++
src/core/test/test_hpcp.cpp
jmaldon1/Musher
58f4c8bde4c314821f15bce27555896a00935c1c
[ "MIT" ]
4
2019-11-11T22:57:33.000Z
2020-11-30T03:12:44.000Z
src/core/test/test_hpcp.cpp
jmaldon1/Musher
58f4c8bde4c314821f15bce27555896a00935c1c
[ "MIT" ]
null
null
null
src/core/test/test_hpcp.cpp
jmaldon1/Musher
58f4c8bde4c314821f15bce27555896a00935c1c
[ "MIT" ]
1
2019-11-13T16:45:30.000Z
2019-11-13T16:45:30.000Z
#include <cmath> #include "src/core/hpcp.h" #include "src/core/test/gtest_extras.h" using namespace musher::core; /** * @brief Test Zero inputs * */ TEST(HPCP, TestZeros) { std::vector<double> actual_hpcp; std::vector<double> frequencies(10); std::vector<double> magnitudes(10); actual_hpcp = HPCP(frequencies, magnitudes); std::vector<double> expected_hpcp(12); EXPECT_VEC_EQ(actual_hpcp, expected_hpcp); } /** * @brief Test submediant position * @details Make sure that the submediant of a key based on 440 is in the * correct location (submediant was randomly selected from all the tones) * */ TEST(HPCP, SubmediantPosition) { std::vector<double> actual_hpcp; int tonic = 440; double submediant = tonic * std::pow(2, (9. / 12.)); std::vector<double> submediant_freqs = { submediant }; std::vector<double> magnitudes = { 1 }; actual_hpcp = HPCP(submediant_freqs, magnitudes); std::vector<double> expected_hpcp = { 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0. }; EXPECT_VEC_EQ(actual_hpcp, expected_hpcp); } /** * @brief Test harmonics * */ TEST(HPCP, Harmonics) { std::vector<double> actual_hpcp; double tone = 100.; std::vector<double> frequencies = { tone, tone * 2, tone * 3, tone * 4 }; std::vector<double> magnitudes(4, 1.); int harmonics = 3; bool band_preset = false; double min_frequency = 50.0; double max_frequency = 500.0; actual_hpcp = HPCP(frequencies, magnitudes, 12, 440.0, harmonics, band_preset, 500.0, min_frequency, max_frequency, "squared cosine", 1.0, false); std::vector<double> expected_hpcp = { 0., 0., 0., 0.1340538263, 0., 0.2476127148, 0., 0., 0., 0., 1., 0. }; EXPECT_VEC_NEAR(actual_hpcp, expected_hpcp, 1e-4); } /** * @brief Test max shifted * @details Tests whether a HPCP reading with only the dominant semitone * activated is correctly shifted so that the dominant is at the position 0 * */ TEST(HPCP, MaxShifted) { std::vector<double> actual_hpcp; int tonic = 440; double dominant = tonic * std::pow(2, (7. / 12.)); std::vector<double> dominant_freqs = { dominant }; std::vector<double> magnitudes = { 1 }; bool max_shifted = true; actual_hpcp = HPCP(dominant_freqs, magnitudes, 12, 440.0, 0, true, 500.0, 40.0, 5000.0, "squared cosine", 1.0, max_shifted); std::vector<double> expected_hpcp = { 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0. }; EXPECT_VEC_EQ(actual_hpcp, expected_hpcp); } /** * @brief Test low frequency * */ TEST(HPCP, LowFrequency) { std::vector<double> actual_hpcp; std::vector<double> frequencies = { 99 }; std::vector<double> magnitudes = { 1 }; double min_frequency = 100.0; double max_frequency = 1000.0; actual_hpcp = HPCP(frequencies, magnitudes, 12, 440.0, 0, true, 500.0, min_frequency, max_frequency, "squared cosine", 1.0, false); std::vector<double> expected_hpcp = { 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0. }; EXPECT_VEC_EQ(actual_hpcp, expected_hpcp); } /** * @brief Test high frequency * */ TEST(HPCP, HighFrequency) { std::vector<double> actual_hpcp; std::vector<double> frequencies = { 1001 }; std::vector<double> magnitudes = { 1 }; double min_frequency = 100.0; double max_frequency = 1000.0; actual_hpcp = HPCP(frequencies, magnitudes, 12, 440.0, 0, true, 500.0, min_frequency, max_frequency, "squared cosine", 1.0, false); std::vector<double> expected_hpcp = { 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0. }; EXPECT_VEC_EQ(actual_hpcp, expected_hpcp); } /** * @brief Test too small min range error * */ TEST(HPCP, TooSmallMinRangeError) { std::vector<double> actual_hpcp; std::vector<double> frequencies = {}; std::vector<double> magnitudes = {}; double band_split_frequency = 200.0; double min_frequency = 1.0; EXPECT_THROW( { try { actual_hpcp = HPCP(frequencies, magnitudes, 12, 440.0, 0, true, band_split_frequency, min_frequency, 1000.0, "squared cosine", 1.0, false); } catch (const std::runtime_error& e) { /* This tests if the error message is equal */ EXPECT_STREQ("HPCP: Low band frequency range too small", e.what()); throw; } }, std::runtime_error); } /** * @brief Test too small max range error * */ TEST(HPCP, TooSmallMaxRangeError) { std::vector<double> actual_hpcp; std::vector<double> frequencies = {}; std::vector<double> magnitudes = {}; double band_split_frequency = 1000.0; double max_frequency = 1199.0; EXPECT_THROW( { try { actual_hpcp = HPCP(frequencies, magnitudes, 12, 440.0, 0, true, band_split_frequency, 40.0, max_frequency, "squared cosine", 1.0, false); } catch (const std::runtime_error& e) { /* This tests if the error message is equal */ EXPECT_STREQ("HPCP: High band frequency range too small", e.what()); throw; } }, std::runtime_error); } /** * @brief Test too close min max range error * */ TEST(HPCP, TooCloseMinMaxRange) { std::vector<double> actual_hpcp; std::vector<double> frequencies = {}; std::vector<double> magnitudes = {}; bool band_present = false; double min_frequency = 1.0; double max_frequency = 200.0; EXPECT_THROW( { try { actual_hpcp = HPCP(frequencies, magnitudes, 12, 440.0, 0, band_present, 1000.0, min_frequency, max_frequency, "squared cosine", 1.0, false); } catch (const std::runtime_error& e) { /* This tests if the error message is equal */ EXPECT_STREQ("HPCP: Minimum and maximum frequencies are too close", e.what()); throw; } }, std::runtime_error); } /** * @brief Test size not a multiple of 12. * */ TEST(HPCP, SizeNotMultipleOf12) { std::vector<double> actual_hpcp; std::vector<double> frequencies = {}; std::vector<double> magnitudes = {}; int size = 13; EXPECT_THROW( { try { actual_hpcp = HPCP(frequencies, magnitudes, size, 440.0, 0, true, 500.0, 40.0, 5000.0, "squared cosine", 1.0, false); } catch (const std::runtime_error& e) { /* This tests if the error message is equal */ EXPECT_STREQ("HPCP: The size parameter is not a multiple of 12.", e.what()); throw; } }, std::runtime_error); }
30.875598
120
0.6256
jmaldon1
13f970f9e06d8715544b79edbf4236de15b002d6
3,829
cpp
C++
src/Util/FFT.cpp
roman-ellerbrock/QuTree
28c5b4eddf20e41cd015a03d33f31693eff17839
[ "MIT" ]
6
2020-04-24T09:58:23.000Z
2022-02-06T03:40:55.000Z
src/Util/FFT.cpp
roman-ellerbrock/QuTree
28c5b4eddf20e41cd015a03d33f31693eff17839
[ "MIT" ]
1
2020-06-18T11:33:14.000Z
2020-06-18T11:35:23.000Z
src/Util/FFT.cpp
roman-ellerbrock/QuTree
28c5b4eddf20e41cd015a03d33f31693eff17839
[ "MIT" ]
1
2020-12-26T15:23:21.000Z
2020-12-26T15:23:21.000Z
#include "Util/FFT.h" size_t FFT::getGoodSize(size_t size) { //check if size is a power of 2 size_t mod = size % 2; if(mod == 0) return size; //get the next bigger power of 2 size_t potens = 0; while(size > 0) { size = size/2; potens++; } return pow(2,potens); } Tensorcd FFT::reverseOrder(const Tensorcd& in) { //get the next best size for fft const TensorShape& dim = in.shape(); size_t size = dim.lastBefore(); size_t states = dim.lastDimension(); size_t N = getGoodSize(size); //build the output tensor withe the new sizes vector<size_t> d; d.push_back(N); d.push_back(dim.lastDimension()); TensorShape newdim(d); Tensorcd out(newdim); for(size_t n = 0; n < states; n++) for(size_t i = 0; i < size; i++) out[n*size + i] = in[n*size + i]; complex<double> tmp; //reverse the order for(size_t n = 0; n < states; n++) { size_t j = 1; for(size_t i = 1; i <= size; i++) { if(j > i) { tmp = out[n*size + j-1]; out[n*size + j-1] = out[n*size + i-1]; out[n*size + i-1] = tmp; } size_t m = size/2; while((m >= 2) && (j > m)) { j -= m; m /= 2; } j += m; } } return out; } Tensorcd FFT::generalFFT(const Tensorcd& in, const int sign) { //get sizes for fft const TensorShape& dim = in.shape(); size_t size = dim.lastBefore(); size_t states = dim.lastDimension(); //get primefactors vector<size_t> primefactors = primeFactorization(size); size_t numberOfFactors = primefactors.size(); //make a factor 2 fft if possible if(primefactors[numberOfFactors-1] == 2) return factor2FFT(in, sign); //otherwise perform dft return dft(in, sign); } Tensorcd FFT::dft(const Tensorcd& in, const int sign) { //get sizes for dft const TensorShape& dim = in.shape(); size_t size = dim.lastBefore(); size_t states = dim.lastDimension(); //otherwise perform dft vector<size_t> d; d.push_back(size); d.push_back(states); TensorShape newdim(d); Tensorcd out(newdim); for(size_t k = 0; k < states; k++) { for(size_t i = 0; i < size; i++) { double angle = (2.*M_PI*i*sign)/(1.*size); complex<double> factor(cos(angle),sin(angle)); complex<double> w(1/sqrt(1.*size),0.); for(size_t j = 0; j < size; j++) { out[k*size + i] += w*in[k*size + j]; w *= factor; } } } return out; } Tensorcd FFT::factor2FFT(const Tensorcd& in, const int sign) { Tensorcd out = reverseOrder(in); danielsonLanczosAlgorithm(out, sign); return out; } void FFT::danielsonLanczosAlgorithm(Tensorcd& in, const int sign) { //get sizes for fft const TensorShape& dim = in.shape(); size_t size = dim.lastBefore(); size_t states = dim.lastDimension(); //save some intermediat results complex<double> tmp(0., 0.); //Transform each vector seperadly for(size_t n = 0; n < states; n++) { //Recursion size_t mmax = 1; while(mmax < size) { size_t j = 0; size_t step = 2*mmax; //prefector for exponent double angle = M_PI/(1.*sign*mmax); complex<double> factor(-2.*pow(sin(0.5*angle),2), sin(angle)); //transformation factor complex<double> w(1., 0.); //go throug all partitions of the vector for(size_t m = 0; m < mmax; m++) { for(size_t i = m; i < size; i += step) { //Davidson-Lanczos-Formula j = i + mmax; tmp = w*in[n*size + j]; in[n*size + j] = in[n*size + i] - tmp; in[n*size + i] = in[n*size + i] + tmp; } w = w*factor + w; } mmax = step; } } in *= 1./sqrt(size); } vector<size_t> FFT::primeFactorization(size_t number) const { vector<size_t> primefactors; if(number == 1) primefactors.push_back(1); size_t inter = number; for(size_t i = 2; i <= number; i++) { while(inter % i == 0) { inter /= i; primefactors.push_back(i); } if(inter == 1) break; } return primefactors; }
19.338384
65
0.610603
roman-ellerbrock
13f9b9c95378bbe1493c2d354ced7beb239f557b
849
cpp
C++
src/html/Extensions.cpp
daotranminh/findscholarships-new
ac7d5e69d9e1c6d971dfbe25658507a0c0fb0081
[ "Apache-1.1" ]
null
null
null
src/html/Extensions.cpp
daotranminh/findscholarships-new
ac7d5e69d9e1c6d971dfbe25658507a0c0fb0081
[ "Apache-1.1" ]
null
null
null
src/html/Extensions.cpp
daotranminh/findscholarships-new
ac7d5e69d9e1c6d971dfbe25658507a0c0fb0081
[ "Apache-1.1" ]
null
null
null
#include <cstring> #include "html/Extensions.h" using namespace std; using namespace htmlcxx; Extensions::Extensions(const string &exts) { const char *begin = exts.c_str(); while (*begin) { while (*begin == ' ') ++begin; if (*begin == 0) break; const char *end = begin + 1; while (*end && *end != ' ') ++end; insert(ci_string(begin, end)); begin = end; } } bool Extensions::check(const string &url) { const char *slash; const char *dot; const char *question; question = strchr(url.c_str(), '?'); if (question) return false; slash = strrchr(url.c_str(), '/'); dot = strrchr(url.c_str(), '.'); if (slash >= dot) return false; ci_string ext(dot); return mExts.find(ext) != mExts.end(); }
19.744186
42
0.532391
daotranminh
13fd6dd53c6d8715ff98c0f9281b50183c984c3f
2,175
cc
C++
Geometry/HGCalGeometry/plugins/HGCalGeometryESProducer.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
1
2019-08-09T08:42:11.000Z
2019-08-09T08:42:11.000Z
Geometry/HGCalGeometry/plugins/HGCalGeometryESProducer.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
null
null
null
Geometry/HGCalGeometry/plugins/HGCalGeometryESProducer.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
1
2019-04-03T19:23:27.000Z
2019-04-03T19:23:27.000Z
// -*- C++ -*- // // Package: HGCalGeometry // Class: HGCalGeometryESProducer // /**\class HGCalGeometryESProducer HGCalGeometryESProducer.h Description: <one line class summary> Implementation: <Notes on implementation> */ // // Original Author: Sunanda Banerjee // // // system include files #include <memory> // user include files #include "FWCore/Framework/interface/ModuleFactory.h" #include "FWCore/Framework/interface/ESProducer.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "Geometry/CaloGeometry/interface/CaloSubdetectorGeometry.h" #include "Geometry/CaloTopology/interface/HGCalTopology.h" #include "Geometry/HGCalGeometry/interface/HGCalGeometry.h" #include "Geometry/HGCalGeometry/interface/HGCalGeometryLoader.h" //#define EDM_ML_DEBUG // // class decleration // class HGCalGeometryESProducer : public edm::ESProducer { public: HGCalGeometryESProducer( const edm::ParameterSet& iP ); ~HGCalGeometryESProducer() override ; using ReturnType = std::unique_ptr<HGCalGeometry>; ReturnType produce(const IdealGeometryRecord&); private: // ----------member data --------------------------- std::string name_; }; HGCalGeometryESProducer::HGCalGeometryESProducer(const edm::ParameterSet& iConfig) { name_ = iConfig.getUntrackedParameter<std::string>("Name"); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "Constructing HGCalGeometry for " << name_; #endif setWhatProduced(this, name_); } HGCalGeometryESProducer::~HGCalGeometryESProducer() { } // // member functions // // ------------ method called to produce the data ------------ HGCalGeometryESProducer::ReturnType HGCalGeometryESProducer::produce(const IdealGeometryRecord& iRecord ) { edm::ESHandle<HGCalTopology> topo; iRecord.get(name_,topo); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "Create HGCalGeometry (*topo) with " << topo.isValid(); #endif HGCalGeometryLoader builder; return ReturnType(builder.build(*topo)); } DEFINE_FWK_EVENTSETUP_MODULE(HGCalGeometryESProducer);
24.715909
84
0.736552
bisnupriyasahu
13fdb6162e5ceee227f032a1121f7d934275675b
3,682
cpp
C++
logdevice/common/StatsCollectionThread.cpp
Ikhbar-Kebaa/LogDevice
d69d706fb81d665eb94ee844aab94ff4951c9731
[ "BSD-3-Clause" ]
1
2019-01-17T18:53:25.000Z
2019-01-17T18:53:25.000Z
logdevice/common/StatsCollectionThread.cpp
abhishekg785/LogDevice
060da71ef84b61f3371115ed352a7ee7b07ba9e2
[ "BSD-3-Clause" ]
null
null
null
logdevice/common/StatsCollectionThread.cpp
abhishekg785/LogDevice
060da71ef84b61f3371115ed352a7ee7b07ba9e2
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "logdevice/common/StatsCollectionThread.h" #include <folly/Optional.h> #include "logdevice/common/ThreadID.h" #include "logdevice/common/configuration/ServerConfig.h" #include "logdevice/common/debug.h" #include "logdevice/common/plugin/PluginRegistry.h" #include "logdevice/common/plugin/StatsPublisherFactory.h" #include "logdevice/common/settings/Settings.h" #include "logdevice/common/settings/UpdateableSettings.h" #include "logdevice/common/stats/Stats.h" namespace facebook { namespace logdevice { StatsCollectionThread::StatsCollectionThread( const StatsHolder* source, std::chrono::seconds interval, std::unique_ptr<StatsPublisher> publisher) : source_stats_(source), interval_(interval), publisher_(std::move(publisher)), thread_(std::bind(&StatsCollectionThread::mainLoop, this)) { ld_debug("Stats Collection Thread Started..."); } StatsCollectionThread::~StatsCollectionThread() { shutDown(); thread_.join(); } namespace { struct StatsSnapshot { Stats stats; std::chrono::steady_clock::time_point when; }; } // namespace void StatsCollectionThread::mainLoop() { ThreadID::set(ThreadID::Type::UTILITY, "ld:stats"); folly::Optional<StatsSnapshot> previous; while (true) { using namespace std::chrono; const auto now = steady_clock::now(); const auto next_tick = now + interval_; StatsSnapshot current = {source_stats_->aggregate(), now}; ld_debug("Publishing Stats..."); if (previous.hasValue()) { publisher_->publish( current.stats, previous.value().stats, duration_cast<milliseconds>(now - previous.value().when)); } previous.assign(std::move(current)); { std::unique_lock<std::mutex> lock(mutex_); if (stop_) { break; } if (next_tick > steady_clock::now()) { cv_.wait_until(lock, next_tick, [this]() { return stop_; }); } // NOTE: even if we got woken up by shutDown(), we still aggregate and // push once more so we don't lose data from the partial interval } } } std::unique_ptr<StatsCollectionThread> StatsCollectionThread::maybeCreate( const UpdateableSettings<Settings>& settings, std::shared_ptr<ServerConfig> config, std::shared_ptr<PluginRegistry> plugin_registry, StatsPublisherScope scope, int num_shards, const StatsHolder* source) { ld_check(settings.get()); ld_check(config); ld_check(plugin_registry); auto stats_collection_interval = settings->stats_collection_interval; if (stats_collection_interval.count() <= 0) { return nullptr; } auto factory = plugin_registry->getSinglePlugin<StatsPublisherFactory>( PluginType::STATS_PUBLISHER_FACTORY); if (!factory) { return nullptr; } auto stats_publisher = (*factory)(scope, settings, num_shards); if (!stats_publisher) { return nullptr; } auto rollup_entity = config->getClusterName(); stats_publisher->addRollupEntity(rollup_entity); if (scope == StatsPublisherScope::CLIENT) { // This is here for backward compatibility with our tooling. The // <tier>.client entity space is deprecated and all new tooling should // be using the tier name without suffix stats_publisher->addRollupEntity(rollup_entity + ".client"); } return std::make_unique<StatsCollectionThread>( source, stats_collection_interval, std::move(stats_publisher)); } }} // namespace facebook::logdevice
31.741379
76
0.713199
Ikhbar-Kebaa
cd01666b015f09342ebcbf8785b5fd5dc556b85b
11,892
cpp
C++
lib/Conversion/VectorConversions/VectorToLLVM.cpp
tjingrant/mlir
afc96480af33cca63556dd209dc60bc6c2eec6fd
[ "Apache-2.0" ]
1
2020-04-01T10:28:07.000Z
2020-04-01T10:28:07.000Z
lib/Conversion/VectorConversions/VectorToLLVM.cpp
tjingrant/mlir
afc96480af33cca63556dd209dc60bc6c2eec6fd
[ "Apache-2.0" ]
1
2018-04-02T23:42:30.000Z
2018-05-03T23:12:23.000Z
lib/Conversion/VectorConversions/VectorToLLVM.cpp
tjingrant/mlir
afc96480af33cca63556dd209dc60bc6c2eec6fd
[ "Apache-2.0" ]
null
null
null
//===- VectorToLLVM.cpp - Conversion from Vector to the LLVM dialect ------===// // // Copyright 2019 The MLIR Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================= #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVM.h" #include "mlir/Conversion/StandardToLLVM/ConvertStandardToLLVMPass.h" #include "mlir/Conversion/VectorConversions/VectorConversions.h" #include "mlir/Dialect/LLVMIR/LLVMDialect.h" #include "mlir/Dialect/VectorOps/VectorOps.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/Builders.h" #include "mlir/IR/MLIRContext.h" #include "mlir/IR/Module.h" #include "mlir/IR/Operation.h" #include "mlir/IR/PatternMatch.h" #include "mlir/IR/StandardTypes.h" #include "mlir/IR/Types.h" #include "mlir/Pass/Pass.h" #include "mlir/Pass/PassManager.h" #include "mlir/Transforms/DialectConversion.h" #include "mlir/Transforms/Passes.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Module.h" #include "llvm/IR/Type.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/ErrorHandling.h" using namespace mlir; template <typename T> static LLVM::LLVMType getPtrToElementType(T containerType, LLVMTypeConverter &lowering) { return lowering.convertType(containerType.getElementType()) .template cast<LLVM::LLVMType>() .getPointerTo(); } class VectorExtractElementOpConversion : public LLVMOpLowering { public: explicit VectorExtractElementOpConversion(MLIRContext *context, LLVMTypeConverter &typeConverter) : LLVMOpLowering(vector::VectorExtractElementOp::getOperationName(), context, typeConverter) {} PatternMatchResult matchAndRewrite(Operation *op, ArrayRef<Value *> operands, ConversionPatternRewriter &rewriter) const override { auto loc = op->getLoc(); auto adaptor = vector::VectorExtractElementOpOperandAdaptor(operands); auto extractOp = cast<vector::VectorExtractElementOp>(op); auto vectorType = extractOp.vector()->getType().cast<VectorType>(); auto resultType = extractOp.getResult()->getType(); auto llvmResultType = lowering.convertType(resultType); auto positionArrayAttr = extractOp.position(); // One-shot extraction of vector from array (only requires extractvalue). if (resultType.isa<VectorType>()) { Value *extracted = rewriter.create<LLVM::ExtractValueOp>( loc, llvmResultType, adaptor.vector(), positionArrayAttr); rewriter.replaceOp(op, extracted); return matchSuccess(); } // Potential extraction of 1-D vector from struct. auto *context = op->getContext(); Value *extracted = adaptor.vector(); auto positionAttrs = positionArrayAttr.getValue(); auto i32Type = rewriter.getIntegerType(32); if (positionAttrs.size() > 1) { auto nDVectorType = vectorType; auto oneDVectorType = VectorType::get(nDVectorType.getShape().take_back(), nDVectorType.getElementType()); auto nMinusOnePositionAttrs = ArrayAttr::get(positionAttrs.drop_back(), context); extracted = rewriter.create<LLVM::ExtractValueOp>( loc, lowering.convertType(oneDVectorType), extracted, nMinusOnePositionAttrs); } // Remaining extraction of element from 1-D LLVM vector auto position = positionAttrs.back().cast<IntegerAttr>(); auto constant = rewriter.create<LLVM::ConstantOp>( loc, lowering.convertType(i32Type), position); extracted = rewriter.create<LLVM::ExtractElementOp>(loc, extracted, constant); rewriter.replaceOp(op, extracted); return matchSuccess(); } }; class VectorOuterProductOpConversion : public LLVMOpLowering { public: explicit VectorOuterProductOpConversion(MLIRContext *context, LLVMTypeConverter &typeConverter) : LLVMOpLowering(vector::VectorOuterProductOp::getOperationName(), context, typeConverter) {} PatternMatchResult matchAndRewrite(Operation *op, ArrayRef<Value *> operands, ConversionPatternRewriter &rewriter) const override { auto loc = op->getLoc(); auto adaptor = vector::VectorOuterProductOpOperandAdaptor(operands); auto *ctx = op->getContext(); auto vLHS = adaptor.lhs()->getType().cast<LLVM::LLVMType>(); auto vRHS = adaptor.rhs()->getType().cast<LLVM::LLVMType>(); auto rankLHS = vLHS.getUnderlyingType()->getVectorNumElements(); auto rankRHS = vRHS.getUnderlyingType()->getVectorNumElements(); auto llvmArrayOfVectType = lowering.convertType( cast<vector::VectorOuterProductOp>(op).getResult()->getType()); Value *desc = rewriter.create<LLVM::UndefOp>(loc, llvmArrayOfVectType); Value *a = adaptor.lhs(), *b = adaptor.rhs(); Value *acc = adaptor.acc().empty() ? nullptr : adaptor.acc().front(); SmallVector<Value *, 8> lhs, accs; lhs.reserve(rankLHS); accs.reserve(rankLHS); for (unsigned d = 0, e = rankLHS; d < e; ++d) { // shufflevector explicitly requires i32. auto attr = rewriter.getI32IntegerAttr(d); SmallVector<Attribute, 4> bcastAttr(rankRHS, attr); auto bcastArrayAttr = ArrayAttr::get(bcastAttr, ctx); Value *aD = nullptr, *accD = nullptr; // 1. Broadcast the element a[d] into vector aD. aD = rewriter.create<LLVM::ShuffleVectorOp>(loc, a, a, bcastArrayAttr); // 2. If acc is present, extract 1-d vector acc[d] into accD. if (acc) accD = rewriter.create<LLVM::ExtractValueOp>( loc, vRHS, acc, rewriter.getI64ArrayAttr(d)); // 3. Compute aD outer b (plus accD, if relevant). Value *aOuterbD = accD ? rewriter.create<LLVM::FMulAddOp>(loc, vRHS, aD, b, accD) .getResult() : rewriter.create<LLVM::FMulOp>(loc, aD, b).getResult(); // 4. Insert as value `d` in the descriptor. desc = rewriter.create<LLVM::InsertValueOp>(loc, llvmArrayOfVectType, desc, aOuterbD, rewriter.getI64ArrayAttr(d)); } rewriter.replaceOp(op, desc); return matchSuccess(); } }; class VectorTypeCastOpConversion : public LLVMOpLowering { public: explicit VectorTypeCastOpConversion(MLIRContext *context, LLVMTypeConverter &typeConverter) : LLVMOpLowering(vector::VectorTypeCastOp::getOperationName(), context, typeConverter) {} PatternMatchResult matchAndRewrite(Operation *op, ArrayRef<Value *> operands, ConversionPatternRewriter &rewriter) const override { auto loc = op->getLoc(); vector::VectorTypeCastOp castOp = cast<vector::VectorTypeCastOp>(op); MemRefType sourceMemRefType = castOp.getOperand()->getType().cast<MemRefType>(); MemRefType targetMemRefType = castOp.getResult()->getType().cast<MemRefType>(); // Only static shape casts supported atm. if (!sourceMemRefType.hasStaticShape() || !targetMemRefType.hasStaticShape()) return matchFailure(); auto llvmSourceDescriptorTy = operands[0]->getType().dyn_cast<LLVM::LLVMType>(); if (!llvmSourceDescriptorTy || !llvmSourceDescriptorTy.isStructTy()) return matchFailure(); MemRefDescriptor sourceMemRef(operands[0]); auto llvmTargetDescriptorTy = lowering.convertType(targetMemRefType) .dyn_cast_or_null<LLVM::LLVMType>(); if (!llvmTargetDescriptorTy || !llvmTargetDescriptorTy.isStructTy()) return matchFailure(); int64_t offset; SmallVector<int64_t, 4> strides; auto successStrides = getStridesAndOffset(sourceMemRefType, strides, offset); bool isContiguous = (strides.back() == 1); if (isContiguous) { auto sizes = sourceMemRefType.getShape(); for (int index = 0, e = strides.size() - 2; index < e; ++index) { if (strides[index] != strides[index + 1] * sizes[index + 1]) { isContiguous = false; break; } } } // Only contiguous source tensors supported atm. if (failed(successStrides) || !isContiguous) return matchFailure(); auto int64Ty = LLVM::LLVMType::getInt64Ty(lowering.getDialect()); // Create descriptor. auto desc = MemRefDescriptor::undef(rewriter, loc, llvmTargetDescriptorTy); Type llvmTargetElementTy = desc.getElementType(); // Set allocated ptr. Value *allocated = sourceMemRef.allocatedPtr(rewriter, loc); allocated = rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, allocated); desc.setAllocatedPtr(rewriter, loc, allocated); // Set aligned ptr. Value *ptr = sourceMemRef.alignedPtr(rewriter, loc); ptr = rewriter.create<LLVM::BitcastOp>(loc, llvmTargetElementTy, ptr); desc.setAlignedPtr(rewriter, loc, ptr); // Fill offset 0. auto attr = rewriter.getIntegerAttr(rewriter.getIndexType(), 0); auto zero = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, attr); desc.setOffset(rewriter, loc, zero); // Fill size and stride descriptors in memref. for (auto indexedSize : llvm::enumerate(targetMemRefType.getShape())) { int64_t index = indexedSize.index(); auto sizeAttr = rewriter.getIntegerAttr(rewriter.getIndexType(), indexedSize.value()); auto size = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, sizeAttr); desc.setSize(rewriter, loc, index, size); auto strideAttr = rewriter.getIntegerAttr(rewriter.getIndexType(), strides[index]); auto stride = rewriter.create<LLVM::ConstantOp>(loc, int64Ty, strideAttr); desc.setStride(rewriter, loc, index, stride); } rewriter.replaceOp(op, {desc}); return matchSuccess(); } }; /// Populate the given list with patterns that convert from Vector to LLVM. void mlir::populateVectorToLLVMConversionPatterns( LLVMTypeConverter &converter, OwningRewritePatternList &patterns) { patterns.insert<VectorExtractElementOpConversion, VectorOuterProductOpConversion, VectorTypeCastOpConversion>( converter.getDialect()->getContext(), converter); } namespace { struct LowerVectorToLLVMPass : public ModulePass<LowerVectorToLLVMPass> { void runOnModule() override; }; } // namespace void LowerVectorToLLVMPass::runOnModule() { // Convert to the LLVM IR dialect using the converter defined above. OwningRewritePatternList patterns; LLVMTypeConverter converter(&getContext()); populateVectorToLLVMConversionPatterns(converter, patterns); populateStdToLLVMConversionPatterns(converter, patterns); ConversionTarget target(getContext()); target.addLegalDialect<LLVM::LLVMDialect>(); target.addDynamicallyLegalOp<FuncOp>( [&](FuncOp op) { return converter.isSignatureLegal(op.getType()); }); if (failed( applyPartialConversion(getModule(), target, patterns, &converter))) { signalPassFailure(); } } OpPassBase<ModuleOp> *mlir::createLowerVectorToLLVMPass() { return new LowerVectorToLLVMPass(); } static PassRegistration<LowerVectorToLLVMPass> pass("convert-vector-to-llvm", "Lower the operations from the vector dialect into the LLVM dialect");
41.873239
80
0.68113
tjingrant
cd01d8ee25017283708d0f56c5cbef66b5d03e83
430
cpp
C++
Programming Basics with C++ - September 2018/02. Lesson/Birthday/Birthday.cpp
Kazalev/SoftUni-ProgrammingBasics-CPlusPlus
115f2618a370443be533b9958121aecca54f4649
[ "MIT" ]
3
2019-07-17T10:11:31.000Z
2020-01-09T18:04:47.000Z
Programming Basics with C++ - September 2018/02. Lesson/Birthday/Birthday.cpp
Kazalev/SoftUni-ProgrammingBasics-CPlusPlus
115f2618a370443be533b9958121aecca54f4649
[ "MIT" ]
null
null
null
Programming Basics with C++ - September 2018/02. Lesson/Birthday/Birthday.cpp
Kazalev/SoftUni-ProgrammingBasics-CPlusPlus
115f2618a370443be533b9958121aecca54f4649
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> using namespace std; int main() { int length, width, height; double percent; cin >> length >> width >> height >> percent; int volume = length * width * height; double liters = volume * 0.001; percent = percent * 0.01; double realLeaters = liters * (1-percent); cout.setf(ios::fixed); cout.precision(3); cout << realLeaters << endl; return 0; }
19.545455
48
0.611628
Kazalev
cd0309415258a6c4b4b89ac6406766474c5c26e2
2,594
cpp
C++
tests/objects_door.cpp
jd28/libnw
15bcb23cf3ef221296b026ad8ce2909044282f2b
[ "MIT" ]
null
null
null
tests/objects_door.cpp
jd28/libnw
15bcb23cf3ef221296b026ad8ce2909044282f2b
[ "MIT" ]
null
null
null
tests/objects_door.cpp
jd28/libnw
15bcb23cf3ef221296b026ad8ce2909044282f2b
[ "MIT" ]
null
null
null
#include <catch2/catch.hpp> #include <nlohmann/json.hpp> #include <nw/kernel/Kernel.hpp> #include <nw/objects/Door.hpp> #include <nw/serialization/Archives.hpp> #include <filesystem> #include <fstream> namespace fs = std::filesystem; TEST_CASE("door: from_gff", "[objects]") { auto door = nw::kernel::objects().load(fs::path("test_data/user/development/door_ttr_002.utd")); auto d = door.get<nw::Door>(); auto common = door.get<nw::Common>(); auto lock = door.get<nw::Lock>(); REQUIRE(common->resref == "door_ttr_002"); REQUIRE(d->appearance == 0); REQUIRE(!d->plot); REQUIRE(!lock->locked); door.destruct(); } TEST_CASE("door: to_json", "[objects]") { auto door = nw::kernel::objects().load(fs::path("test_data/user/development/door_ttr_002.utd")); nlohmann::json j; nw::kernel::objects().serialize(door, j, nw::SerializationProfile::blueprint); auto door2 = nw::kernel::objects().deserialize(nw::ObjectType::door, j, nw::SerializationProfile::blueprint); REQUIRE(door2.is_alive()); nlohmann::json j2; nw::kernel::objects().serialize(door, j2, nw::SerializationProfile::blueprint); REQUIRE(j == j2); std::ofstream f{"tmp/door_ttr_002.utd.json"}; f << std::setw(4) << j; } TEST_CASE("door: gff round trip", "[ojbects]") { nw::GffInputArchive g("test_data/user/development/door_ttr_002.utd"); REQUIRE(g.valid()); auto door = nw::kernel::objects().load(fs::path("test_data/user/development/door_ttr_002.utd")); nw::GffOutputArchive oa = nw::kernel::objects().serialize(door, nw::SerializationProfile::blueprint); oa.write_to("tmp/door_ttr_002.utd"); nw::GffInputArchive g2("tmp/door_ttr_002.utd"); REQUIRE(g2.valid()); REQUIRE(nw::gff_to_gffjson(g) == nw::gff_to_gffjson(g2)); REQUIRE(oa.header.struct_offset == g.head_->struct_offset); REQUIRE(oa.header.struct_count == g.head_->struct_count); REQUIRE(oa.header.field_offset == g.head_->field_offset); REQUIRE(oa.header.field_count == g.head_->field_count); REQUIRE(oa.header.label_offset == g.head_->label_offset); REQUIRE(oa.header.label_count == g.head_->label_count); REQUIRE(oa.header.field_data_offset == g.head_->field_data_offset); REQUIRE(oa.header.field_data_count == g.head_->field_data_count); REQUIRE(oa.header.field_idx_offset == g.head_->field_idx_offset); REQUIRE(oa.header.field_idx_count == g.head_->field_idx_count); REQUIRE(oa.header.list_idx_offset == g.head_->list_idx_offset); REQUIRE(oa.header.list_idx_count == g.head_->list_idx_count); }
34.586667
105
0.690439
jd28
cd03949f8c99ca25e87497907d0b0cc8ae846853
3,265
hpp
C++
opencamlib/src/algo/batchpushcutter_py.hpp
JohnyEngine/CNC
e4c77250ab2b749d3014022cbb5eb9924e939993
[ "Apache-2.0" ]
null
null
null
opencamlib/src/algo/batchpushcutter_py.hpp
JohnyEngine/CNC
e4c77250ab2b749d3014022cbb5eb9924e939993
[ "Apache-2.0" ]
null
null
null
opencamlib/src/algo/batchpushcutter_py.hpp
JohnyEngine/CNC
e4c77250ab2b749d3014022cbb5eb9924e939993
[ "Apache-2.0" ]
null
null
null
/* $Id$ * * Copyright 2010 Anders Wallin (anders.e.e.wallin "at" gmail.com) * * This file is part of OpenCAMlib. * * OpenCAMlib is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenCAMlib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenCAMlib. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BPC_PY_H #define BPC_PY_H #include <boost/python.hpp> #include "batchpushcutter.hpp" #include "fiber_py.hpp" namespace ocl { /// \brief python wrapper for batchpushcutter class BatchPushCutter_py : public BatchPushCutter { public: BatchPushCutter_py() : BatchPushCutter() {} /// return CL-points to Python boost::python::list getCLPoints() const { boost::python::list plist; BOOST_FOREACH(Fiber f, *fibers) { BOOST_FOREACH( Interval i, f.ints ) { if ( !i.empty() ) { Point tmp = f.point(i.lower); CLPoint p1 = CLPoint( tmp.x, tmp.y, tmp.z ); p1.cc = new CCPoint(i.lower_cc); tmp = f.point(i.upper); CLPoint p2 = CLPoint( tmp.x, tmp.y, tmp.z ); p2.cc = new CCPoint(i.upper_cc); plist.append(p1); plist.append(p2); } } } return plist; }; /// return triangles under cutter to Python. Not for CAM-algorithms, /// more for visualization and demonstration. boost::python::list getOverlapTriangles(Fiber& f) { boost::python::list trilist; std::list<Triangle> *overlap_triangles = new std::list<Triangle>(); //int plane = 3; // XY-plane //Bbox bb; //FIXME //KDNode2::search_kdtree( overlap_triangles, bb, root, plane); CLPoint cl; if (x_direction) { cl.x = 0; cl.y = f.p1.y; cl.z = f.p1.z; } else if (y_direction) { cl.x = f.p1.x; cl.y = 0; cl.z = f.p1.z; } else { assert(0); } overlap_triangles = root->search_cutter_overlap(cutter, &cl); BOOST_FOREACH(Triangle t, *overlap_triangles) { trilist.append(t); } delete overlap_triangles; return trilist; }; /// return list of Fibers to python boost::python::list getFibers_py() const { boost::python::list flist; BOOST_FOREACH(Fiber f, *fibers) { flist.append( Fiber_py(f) ); } return flist; }; }; } // end namespace #endif
33.316327
79
0.533538
JohnyEngine
cd042792d841272a5d5945ddbbc1e1496d55b8a5
20,479
cpp
C++
services/updater_binary/update_image_block.cpp
openharmony-gitee-mirror/update_updater
72393623a6aa9d08346da98433bb3bdbe5f07120
[ "Apache-2.0" ]
null
null
null
services/updater_binary/update_image_block.cpp
openharmony-gitee-mirror/update_updater
72393623a6aa9d08346da98433bb3bdbe5f07120
[ "Apache-2.0" ]
null
null
null
services/updater_binary/update_image_block.cpp
openharmony-gitee-mirror/update_updater
72393623a6aa9d08346da98433bb3bdbe5f07120
[ "Apache-2.0" ]
1
2021-09-13T12:07:24.000Z
2021-09-13T12:07:24.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "update_image_block.h" #include <cerrno> #include <fcntl.h> #include <pthread.h> #include <sstream> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "applypatch/block_set.h" #include "applypatch/store.h" #include "applypatch/transfer_manager.h" #include "applypatch/partition_record.h" #include "fs_manager/mount.h" #include "log/log.h" #include "utils.h" using namespace uscript; using namespace hpackage; using namespace updater; namespace updater { constexpr int32_t SHA_CHECK_SECOND = 2; constexpr int32_t SHA_CHECK_PARAMS = 3; static int ExtractNewData(const PkgBuffer &buffer, size_t size, size_t start, bool isFinish, const void* context) { void *p = const_cast<void *>(context); WriterThreadInfo *info = static_cast<WriterThreadInfo *>(p); uint8_t *addr = buffer.buffer; while (size > 0) { pthread_mutex_lock(&info->mutex); while (info->writer == nullptr) { if (!info->readyToWrite) { LOG(WARNING) << "writer is not ready to write."; pthread_mutex_unlock(&info->mutex); return hpackage::PKG_INVALID_STREAM; } pthread_cond_wait(&info->cond, &info->mutex); } pthread_mutex_unlock(&info->mutex); size_t toWrite = std::min(size, info->writer->GetBlocksSize() - info->writer->GetTotalWritten()); // No more data to write. UPDATER_CHECK_ONLY_RETURN(toWrite != 0, break); bool ret = info->writer->Write(const_cast<uint8_t *>(addr), toWrite, WRITE_BLOCK, ""); std::ostringstream logMessage; logMessage << "Write " << toWrite << " byte(s) failed"; UPDATER_ERROR_CHECK(ret == true, logMessage.str(), return hpackage::PKG_INVALID_STREAM); size -= toWrite; addr += toWrite; if (info->writer->IsWriteDone()) { pthread_mutex_lock(&info->mutex); info->writer.reset(); pthread_cond_broadcast(&info->cond); pthread_mutex_unlock(&info->mutex); } } return hpackage::PKG_SUCCESS; } void* UnpackNewData(void *arg) { WriterThreadInfo *info = static_cast<WriterThreadInfo *>(arg); hpackage::PkgManager::StreamPtr stream = nullptr; TransferManagerPtr tm = TransferManager::GetTransferManagerInstance(); if (info->newPatch.empty()) { LOG(ERROR) << "new patch file name is empty. thread quit."; pthread_mutex_lock(&info->mutex); info->readyToWrite = false; if (info->writer != nullptr) { pthread_cond_broadcast(&info->cond); } pthread_mutex_unlock(&info->mutex); return nullptr; } LOG(DEBUG) << "new patch file name: " << info->newPatch; auto env = tm->GetGlobalParams()->env; const FileInfo *file = env->GetPkgManager()->GetFileInfo(info->newPatch); if (file == nullptr) { LOG(ERROR) << "Cannot get file info of :" << info->newPatch; pthread_mutex_lock(&info->mutex); info->readyToWrite = false; if (info->writer != nullptr) { pthread_cond_broadcast(&info->cond); } pthread_mutex_unlock(&info->mutex); return nullptr; } LOG(DEBUG) << info->newPatch << " info: size " << file->packedSize << " unpacked size " << file->unpackedSize << " name " << file->identity; int32_t ret = env->GetPkgManager()->CreatePkgStream(stream, info->newPatch, ExtractNewData, info); if (ret != hpackage::PKG_SUCCESS || stream == nullptr) { LOG(ERROR) << "Cannot extract " << info->newPatch << " from package."; pthread_mutex_lock(&info->mutex); info->readyToWrite = false; if (info->writer != nullptr) { pthread_cond_broadcast(&info->cond); } pthread_mutex_unlock(&info->mutex); return nullptr; } ret = env->GetPkgManager()->ExtractFile(info->newPatch, stream); env->GetPkgManager()->ClosePkgStream(stream); pthread_mutex_lock(&info->mutex); LOG(DEBUG) << "new data writer ending..."; // extract new data done. // tell command. info->readyToWrite = false; UPDATER_WARING_CHECK (info->writer == nullptr, "writer is null", pthread_cond_broadcast(&info->cond)); pthread_mutex_unlock(&info->mutex); return nullptr; } static int32_t ReturnAndPushParam(int32_t returnValue, uscript::UScriptContext &context) { context.PushParam(returnValue); return returnValue; } struct UpdateBlockInfo { std::string partitionName; std::string transferName; std::string newDataName; std::string patchDataName; std::string devPath; }; static int32_t GetUpdateBlockInfo(struct UpdateBlockInfo &infos, uscript::UScriptEnv &env, uscript::UScriptContext &context) { UPDATER_ERROR_CHECK(context.GetParamCount() == 4, "Invalid param", return ReturnAndPushParam(USCRIPT_INVALID_PARAM, context)); // Get partition Name first. // Use partition name as zip file name. ${partition name}.zip // load ${partition name}.zip from updater package. // Try to unzip ${partition name}.zip, extract transfer.list, net.dat, patch.dat size_t pos = 0; int32_t ret = context.GetParam(pos++, infos.partitionName); UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Error to get param 1", return ret); ret = context.GetParam(pos++, infos.transferName); UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Error to get param 2", return ret); ret = context.GetParam(pos++, infos.newDataName); UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Error to get param 3", return ret); ret = context.GetParam(pos++, infos.patchDataName); UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Error to get param 4", return ret); LOG(INFO) << "ExecuteUpdateBlock::updating " << infos.partitionName << " ..."; infos.devPath = GetBlockDeviceByMountPoint(infos.partitionName); LOG(INFO) << "ExecuteUpdateBlock::updating dev path : " << infos.devPath; UPDATER_ERROR_CHECK(!infos.devPath.empty(), "cannot get block device of partition", return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context)); return USCRIPT_SUCCESS; } static int32_t ExecuteTransferCommand(int fd, const std::vector<std::string> &lines, uscript::UScriptEnv &env, uscript::UScriptContext &context, const std::string &partitionName) { TransferManagerPtr tm = TransferManager::GetTransferManagerInstance(); auto globalParams = tm->GetGlobalParams(); auto writerThreadInfo = globalParams->writerThreadInfo.get(); globalParams->storeBase = "/data/updater/update_tmp"; globalParams->retryFile = std::string("/data/updater") + partitionName + "_retry"; LOG(INFO) << "Store base path is " << globalParams->storeBase; int32_t ret = Store::CreateNewSpace(globalParams->storeBase, !globalParams->env->IsRetry()); UPDATER_ERROR_CHECK(ret != -1, "Error to create new store space", return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context)); globalParams->storeCreated = ret; UPDATER_CHECK_ONLY_RETURN(tm->CommandsParser(fd, lines), return USCRIPT_ERROR_EXECUTE); pthread_mutex_lock(&writerThreadInfo->mutex); if (writerThreadInfo->readyToWrite) { LOG(WARNING) << "New data writer thread is still available..."; } writerThreadInfo->readyToWrite = false; pthread_cond_broadcast(&writerThreadInfo->cond); pthread_mutex_unlock(&writerThreadInfo->mutex); ret = pthread_join(globalParams->thread, nullptr); std::ostringstream logMessage; logMessage << "pthread join returned with " << strerror(ret); UPDATER_WARNING_CHECK_NOT_RETURN(ret == 0, logMessage.str()); if (globalParams->storeCreated != -1) { Store::DoFreeSpace(globalParams->storeBase); } return USCRIPT_SUCCESS; } static int InitThread(struct UpdateBlockInfo &infos, uscript::UScriptEnv &env, uscript::UScriptContext &context) { TransferManagerPtr tm = TransferManager::GetTransferManagerInstance(); auto globalParams = tm->GetGlobalParams(); auto writerThreadInfo = globalParams->writerThreadInfo.get(); writerThreadInfo->readyToWrite = true; pthread_mutex_init(&writerThreadInfo->mutex, nullptr); pthread_cond_init(&writerThreadInfo->cond, nullptr); pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); writerThreadInfo->newPatch = infos.newDataName; int error = pthread_create(&globalParams->thread, &attr, UnpackNewData, writerThreadInfo); return error; } static int32_t ExtractDiffPackageAndLoad(const UpdateBlockInfo &infos, uscript::UScriptEnv &env, uscript::UScriptContext &context) { hpackage::PkgManager::StreamPtr outStream = nullptr; LOG(DEBUG) << "partitionName is " << infos.partitionName; const FileInfo *info = env.GetPkgManager()->GetFileInfo(infos.partitionName); UPDATER_ERROR_CHECK(info != nullptr, "Error to get file info", return USCRIPT_ERROR_EXECUTE); std::string diffPackage = std::string("/data/updater") + infos.partitionName; int32_t ret = env.GetPkgManager()->CreatePkgStream(outStream, diffPackage, info->unpackedSize, PkgStream::PkgStreamType_Write); UPDATER_ERROR_CHECK(outStream != nullptr, "Error to create output stream", return USCRIPT_ERROR_EXECUTE); ret = env.GetPkgManager()->ExtractFile(infos.partitionName, outStream); UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Error to extract file", env.GetPkgManager()->ClosePkgStream(outStream); return USCRIPT_ERROR_EXECUTE); env.GetPkgManager()->ClosePkgStream(outStream); std::string diffPackageZip = diffPackage + ".zip"; rename(diffPackage.c_str(), diffPackageZip.c_str()); LOG(DEBUG) << "Rename " << diffPackage << " to zip\nExtract " << diffPackage << " done\nReload " << diffPackageZip; std::vector<std::string> diffPackageComponents; ret = env.GetPkgManager()->LoadPackage(diffPackageZip, updater::utils::GetCertName(), diffPackageComponents); UPDATER_ERROR_CHECK(diffPackageComponents.size() >= 1, "Diff package is empty", return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context)); return USCRIPT_SUCCESS; } static int32_t DoExecuteUpdateBlock(UpdateBlockInfo &infos, uscript::UScriptEnv &env, hpackage::PkgManager::StreamPtr &outStream, const std::vector<std::string> &lines, uscript::UScriptContext &context) { int fd = open(infos.devPath.c_str(), O_RDWR | O_LARGEFILE); UPDATER_ERROR_CHECK (fd != -1, "Failed to open block", env.GetPkgManager()->ClosePkgStream(outStream); return USCRIPT_ERROR_EXECUTE); int32_t ret = ExecuteTransferCommand(fd, lines, env, context, infos.partitionName); fsync(fd); close(fd); fd = -1; env.GetPkgManager()->ClosePkgStream(outStream); if (ret == USCRIPT_SUCCESS) { PartitionRecord::GetInstance().RecordPartitionUpdateStatus(infos.partitionName, true); } return ret; } static int32_t ExecuteUpdateBlock(uscript::UScriptEnv &env, uscript::UScriptContext &context) { UpdateBlockInfo infos {}; UPDATER_CHECK_ONLY_RETURN(!GetUpdateBlockInfo(infos, env, context), return USCRIPT_ERROR_EXECUTE); UPDATER_ERROR_CHECK(env.GetPkgManager() != nullptr, "Error to get pkg manager", return USCRIPT_ERROR_EXECUTE); if (env.IsRetry()) { LOG(DEBUG) << "Retry updater, check if current partition updatered already during last time"; bool isUpdated = PartitionRecord::GetInstance().IsPartitionUpdated(infos.partitionName); if (isUpdated) { LOG(INFO) << infos.partitionName << " already updated, skip"; return USCRIPT_SUCCESS; } } int32_t ret = ExtractDiffPackageAndLoad(infos, env, context); UPDATER_CHECK_ONLY_RETURN(ret == USCRIPT_SUCCESS, return USCRIPT_ERROR_EXECUTE); const FileInfo *info = env.GetPkgManager()->GetFileInfo(infos.transferName); hpackage::PkgManager::StreamPtr outStream = nullptr; ret = env.GetPkgManager()->CreatePkgStream(outStream, infos.transferName, info->unpackedSize, PkgStream::PkgStreamType_MemoryMap); ret = env.GetPkgManager()->ExtractFile(infos.transferName, outStream); uint8_t *transferListBuffer = nullptr; size_t transferListSize = 0; ret = outStream->GetBuffer(transferListBuffer, transferListSize); TransferManagerPtr tm = TransferManager::GetTransferManagerInstance(); auto globalParams = tm->GetGlobalParams(); /* Save Script Env to transfer manager */ globalParams->env = &env; std::vector<std::string> lines = updater::utils::SplitString(std::string(reinterpret_cast<const char*>(transferListBuffer)), "\n"); LOG(INFO) << "Ready to start a thread to handle new data processing"; UPDATER_ERROR_CHECK (InitThread(infos, env, context) == 0, "Failed to create pthread", env.GetPkgManager()->ClosePkgStream(outStream); return USCRIPT_ERROR_EXECUTE); LOG(DEBUG) << "Start unpack new data thread done. Get patch data: " << infos.patchDataName; info = env.GetPkgManager()->GetFileInfo(infos.patchDataName); // Close stream opened before. env.GetPkgManager()->ClosePkgStream(outStream); ret = env.GetPkgManager()->CreatePkgStream(outStream, infos.patchDataName, info->unpackedSize, PkgStream::PkgStreamType_MemoryMap); UPDATER_ERROR_CHECK(outStream != nullptr, "Error to create output stream", return USCRIPT_ERROR_EXECUTE); ret = env.GetPkgManager()->ExtractFile(infos.patchDataName, outStream); UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Error to extract file", env.GetPkgManager()->ClosePkgStream(outStream); return USCRIPT_ERROR_EXECUTE); outStream->GetBuffer(globalParams->patchDataBuffer, globalParams->patchDataSize); LOG(DEBUG) << "Patch data size is: " << globalParams->patchDataSize; ret = DoExecuteUpdateBlock(infos, env, outStream, lines, context); TransferManager::ReleaseTransferManagerInstance(tm); return ret; } int32_t UScriptInstructionBlockUpdate::Execute(uscript::UScriptEnv &env, uscript::UScriptContext &context) { int32_t result = ExecuteUpdateBlock(env, context); context.PushParam(result); return result; } int32_t UScriptInstructionBlockCheck::Execute(uscript::UScriptEnv &env, uscript::UScriptContext &context) { UPDATER_ERROR_CHECK(context.GetParamCount() == 1, "Invalid param", return ReturnAndPushParam(USCRIPT_INVALID_PARAM, context)); UPDATER_CHECK_ONLY_RETURN(!env.IsRetry(), return ReturnAndPushParam(USCRIPT_SUCCESS, context)); std::string partitionName; int32_t ret = context.GetParam(0, partitionName); UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Failed to get param", return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context)); auto devPath = GetBlockDeviceByMountPoint(partitionName); LOG(INFO) << "UScriptInstructionBlockCheck::dev path : " << devPath; UPDATER_ERROR_CHECK(!devPath.empty(), "cannot get block device of partition", return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context)); int fd = open(devPath.c_str(), O_RDWR | O_LARGEFILE); UPDATER_ERROR_CHECK(fd != -1, "Failed to open file", return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context)); std::vector<uint8_t> block_buff(H_BLOCK_SIZE); BlockSet blk0(std::vector<BlockPair> {BlockPair{0, 1}}); size_t pos = 0; std::vector<BlockPair>::iterator it = blk0.Begin(); for (; it != blk0.End(); ++it) { LOG(INFO) << "BlockSet::ReadDataFromBlock lseek64"; ret = lseek64(fd, static_cast<off64_t>(it->first * H_BLOCK_SIZE), SEEK_SET); UPDATER_ERROR_CHECK(ret != -1, "Failed to seek", return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context)); size_t size = (it->second - it->first) * H_BLOCK_SIZE; LOG(INFO) << "BlockSet::ReadDataFromBlock Read " << size << " from block"; UPDATER_ERROR_CHECK(utils::ReadFully(fd, block_buff.data() + pos, size), "Failed to read", return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context)); pos += size; } time_t mountTime = *reinterpret_cast<uint32_t *>(&block_buff[0x400 + 0x2C]); uint16_t mountCount = *reinterpret_cast<uint16_t *>(&block_buff[0x400 + 0x34]); if (mountCount > 0) { std::ostringstream ostr; ostr << "Device was remounted R/W " << mountCount << "times\nLast remount happened on " << ctime(&mountTime) << std::endl; std::string message = ostr.str(); env.PostMessage("ui_log", message); } LOG(INFO) << "UScriptInstructionBlockCheck::Execute Success"; context.PushParam(USCRIPT_SUCCESS); return USCRIPT_SUCCESS; } int32_t UScriptInstructionShaCheck::Execute(uscript::UScriptEnv &env, uscript::UScriptContext &context) { UPDATER_ERROR_CHECK(context.GetParamCount() == SHA_CHECK_PARAMS, "Invalid param", return ReturnAndPushParam(USCRIPT_INVALID_PARAM, context)); UPDATER_CHECK_ONLY_RETURN(!env.IsRetry(), return ReturnAndPushParam(USCRIPT_SUCCESS, context)); std::string partitionName; int32_t ret = context.GetParam(0, partitionName); UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Failed to get param", return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context)); std::string blockPairs; ret = context.GetParam(1, blockPairs); UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Failed to get param", return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context)); std::string contrastSha; ret = context.GetParam(SHA_CHECK_SECOND, contrastSha); UPDATER_ERROR_CHECK(ret == USCRIPT_SUCCESS, "Failed to get param", return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context)); auto devPath = GetBlockDeviceByMountPoint(partitionName); LOG(INFO) << "UScriptInstructionShaCheck::dev path : " << devPath; UPDATER_ERROR_CHECK(!devPath.empty(), "cannot get block device of partition", return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context)); int fd = open(devPath.c_str(), O_RDWR | O_LARGEFILE); UPDATER_ERROR_CHECK(fd != -1, "Failed to open file", return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context)); BlockSet blk; blk.ParserAndInsert(blockPairs); std::vector<uint8_t> block_buff(H_BLOCK_SIZE); SHA256_CTX ctx; SHA256_Init(&ctx); std::vector<BlockPair>::iterator it = blk.Begin(); for (; it != blk.End(); ++it) { ret = lseek64(fd, static_cast<off64_t>(it->first * H_BLOCK_SIZE), SEEK_SET); UPDATER_ERROR_CHECK(ret != -1, "Failed to seek", return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context)); for (size_t i = it->first; i < it->second; ++i) { UPDATER_ERROR_CHECK(utils::ReadFully(fd, block_buff.data(), H_BLOCK_SIZE), "Failed to read", return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context)); SHA256_Update(&ctx, block_buff.data(), H_BLOCK_SIZE); } } uint8_t digest[SHA256_DIGEST_LENGTH]; SHA256_Final(digest, &ctx); std::string resultSha = utils::ConvertSha256Hex(digest, SHA256_DIGEST_LENGTH); UPDATER_ERROR_CHECK(resultSha == contrastSha, "Different sha256, cannot continue", return ReturnAndPushParam(USCRIPT_ERROR_EXECUTE, context)); LOG(INFO) << "UScriptInstructionShaCheck::Execute Success"; context.PushParam(USCRIPT_SUCCESS); return USCRIPT_SUCCESS; } }
48.07277
121
0.68558
openharmony-gitee-mirror
cd08ac7c2192da17a509a33caa837d1693ac8926
1,533
hpp
C++
includecpp/network.hpp
willst/libcaer
ff0e741fcfc0b59a41f87679d59620e3cc3b3a7e
[ "BSD-2-Clause" ]
1
2018-12-05T16:42:26.000Z
2018-12-05T16:42:26.000Z
includecpp/network.hpp
willst/libcaer
ff0e741fcfc0b59a41f87679d59620e3cc3b3a7e
[ "BSD-2-Clause" ]
null
null
null
includecpp/network.hpp
willst/libcaer
ff0e741fcfc0b59a41f87679d59620e3cc3b3a7e
[ "BSD-2-Clause" ]
null
null
null
#ifndef LIBCAER_NETWORK_HPP_ #define LIBCAER_NETWORK_HPP_ #include "libcaer.hpp" #include <libcaer/network.h> namespace libcaer { namespace network { class AEDAT3NetworkHeader : private aedat3_network_header { public: AEDAT3NetworkHeader() { magicNumber = AEDAT3_NETWORK_MAGIC_NUMBER; sequenceNumber = 0; versionNumber = AEDAT3_NETWORK_VERSION; formatNumber = 0; sourceID = 0; } AEDAT3NetworkHeader(const uint8_t *h) { struct aedat3_network_header header = caerParseNetworkHeader(h); magicNumber = header.magicNumber; sequenceNumber = header.sequenceNumber; versionNumber = header.versionNumber; formatNumber = header.formatNumber; sourceID = header.sourceID; } int64_t getMagicNumber() const noexcept { return (magicNumber); } bool checkMagicNumber() const noexcept { return (magicNumber == AEDAT3_NETWORK_MAGIC_NUMBER); } int64_t getSequenceNumber() const noexcept { return (sequenceNumber); } void incrementSequenceNumber() noexcept { sequenceNumber++; } int8_t getVersionNumber() const noexcept { return (versionNumber); } bool checkVersionNumber() const noexcept { return (versionNumber == AEDAT3_NETWORK_VERSION); } int8_t getFormatNumber() const noexcept { return (formatNumber); } void setFormatNumber(int8_t format) noexcept { formatNumber = format; } int16_t getSourceID() const noexcept { return (sourceID); } void setSourceID(int16_t source) noexcept { sourceID = source; } }; } } #endif /* LIBCAER_NETWORK_HPP_ */
20.716216
66
0.741683
willst
cd08d9dda3d2b4a463ae745a2ec9ff6d3b42c633
18,190
cpp
C++
src/certificate/Certificate.cpp
LabSEC/libcryptosec
e53030ec32b52b6abeaa973a9f0bfba0eb2c2440
[ "BSD-3-Clause" ]
22
2015-08-26T16:40:59.000Z
2022-02-22T19:52:55.000Z
src/certificate/Certificate.cpp
LabSEC/Libcryptosec
e53030ec32b52b6abeaa973a9f0bfba0eb2c2440
[ "BSD-3-Clause" ]
14
2015-09-01T00:39:22.000Z
2018-12-17T16:24:28.000Z
src/certificate/Certificate.cpp
LabSEC/Libcryptosec
e53030ec32b52b6abeaa973a9f0bfba0eb2c2440
[ "BSD-3-Clause" ]
22
2015-08-31T19:17:37.000Z
2021-01-04T13:38:35.000Z
#include <libcryptosec/certificate/Certificate.h> Certificate::Certificate(X509 *cert) { this->cert = cert; } Certificate::Certificate(std::string pemEncoded) throw (EncodeException) { BIO *buffer; buffer = BIO_new(BIO_s_mem()); if (buffer == NULL) { throw EncodeException(EncodeException::BUFFER_CREATING, "Certificate::Certificate"); } if ((unsigned int)(BIO_write(buffer, pemEncoded.c_str(), pemEncoded.size())) != pemEncoded.size()) { BIO_free(buffer); throw EncodeException(EncodeException::BUFFER_WRITING, "Certificate::Certificate"); } this->cert = PEM_read_bio_X509(buffer, NULL, NULL, NULL); if (this->cert == NULL) { BIO_free(buffer); throw EncodeException(EncodeException::PEM_DECODE, "Certificate::Certificate"); } BIO_free(buffer); } Certificate::Certificate(ByteArray &derEncoded) throw (EncodeException) { BIO *buffer; buffer = BIO_new(BIO_s_mem()); if (buffer == NULL) { throw EncodeException(EncodeException::BUFFER_CREATING, "Certificate::Certificate"); } if ((unsigned int)(BIO_write(buffer, derEncoded.getDataPointer(), derEncoded.size())) != derEncoded.size()) { BIO_free(buffer); throw EncodeException(EncodeException::BUFFER_WRITING, "Certificate::Certificate"); } this->cert = d2i_X509_bio(buffer, NULL); /* TODO: will the second parameter work fine ? */ if (this->cert == NULL) { BIO_free(buffer); throw EncodeException(EncodeException::DER_DECODE, "Certificate::Certificate"); } BIO_free(buffer); } Certificate::Certificate(const Certificate& cert) { this->cert = X509_dup(cert.getX509()); } Certificate::~Certificate() { X509_free(this->cert); this->cert = NULL; } std::string Certificate::getXmlEncoded() { return this->getXmlEncoded(""); } std::string Certificate::getXmlEncoded(std::string tab) { std::string ret, string; ByteArray data; char temp[15]; long value; std::vector<Extension *> extensions; unsigned int i; ret = "<?xml version=\"1.0\"?>\n"; ret += "<certificate>\n"; ret += "\t<tbsCertificate>\n"; try /* version */ { value = this->getVersion(); sprintf(temp, "%d", (int)value); string = temp; ret += "\t\t<version>" + string + "</version>\n"; } catch (...) { } try /* Serial Number */ { value = this->getSerialNumber(); sprintf(temp, "%d", (int)value); string = temp; ret += "\t\t<serialNumber>" + string + "</serialNumber>\n"; } catch (...) { } string = OBJ_nid2ln(OBJ_obj2nid(this->cert->sig_alg->algorithm)); ret += "\t\t<signature>" + string + "</signature>\n"; ret += "\t\t<issuer>\n"; try { ret += (this->getIssuer()).getXmlEncoded("\t\t\t"); } catch (...) { } ret += "\t\t</issuer>\n"; ret += "\t\t<validity>\n"; try { ret += "\t\t\t<notBefore>" + ((this->getNotBefore()).getXmlEncoded()) + "</notBefore>\n"; } catch (...) { } try { ret += "\t\t\t<notAfter>" + ((this->getNotAfter()).getXmlEncoded()) + "</notAfter>\n"; } catch (...) { } ret += "\t\t</validity>\n"; ret += "\t\t<subject>\n"; try { ret += (this->getSubject()).getXmlEncoded("\t\t\t"); } catch (...) { } ret += "\t\t</subject>\n"; ret += "\t\t<subjectPublicKeyInfo>\n"; string = OBJ_nid2ln(OBJ_obj2nid(this->cert->cert_info->key->algor->algorithm)); ret += "\t\t\t<algorithm>" + string + "</algorithm>\n"; data = ByteArray(this->cert->cert_info->key->public_key->data, this->cert->cert_info->key->public_key->length); string = Base64::encode(data); ret += "\t\t\t<subjectPublicKey>" + string + "</subjectPublicKey>\n"; ret += "\t\t</subjectPublicKeyInfo>\n"; if (this->cert->cert_info->issuerUID) { data = ByteArray(this->cert->cert_info->issuerUID->data, this->cert->cert_info->issuerUID->length); string = Base64::encode(data); ret += "\t\t<issuerUniqueID>" + string + "</issuerUniqueID>\n"; } if (this->cert->cert_info->subjectUID) { data = ByteArray(this->cert->cert_info->subjectUID->data, this->cert->cert_info->subjectUID->length); string = Base64::encode(data); ret += "\t\t<subjectUniqueID>" + string + "</subjectUniqueID>\n"; } ret += "\t\t<extensions>\n"; extensions = this->getExtensions(); for (i=0;i<extensions.size();i++) { ret += extensions.at(i)->getXmlEncoded("\t\t\t"); delete extensions.at(i); } ret += "\t\t</extensions>\n"; ret += "\t</tbsCertificate>\n"; ret += "\t<signatureAlgorithm>\n"; string = OBJ_nid2ln(OBJ_obj2nid(this->cert->sig_alg->algorithm)); ret += "\t\t<algorithm>" + string + "</algorithm>\n"; ret += "\t</signatureAlgorithm>\n"; data = ByteArray(this->cert->signature->data, this->cert->signature->length); string = Base64::encode(data); ret += "\t<signatureValue>" + string + "</signatureValue>\n"; ret += "</certificate>\n"; return ret; } std::string Certificate::toXml(std::string tab) { std::string ret, string; ByteArray data; char temp[15]; long value; std::vector<Extension *> extensions; unsigned int i; ret = "<?xml version=\"1.0\"?>\n"; ret += "<certificate>\n"; ret += "\t<tbsCertificate>\n"; try /* version */ { value = this->getVersion(); sprintf(temp, "%d", (int)value); string = temp; ret += "\t\t<version>" + string + "</version>\n"; } catch (...) { } try /* Serial Number */ { ret += "\t\t<serialNumber>" + this->getSerialNumberBigInt().toDec() + "</serialNumber>\n"; } catch (...) { } string = OBJ_nid2ln(OBJ_obj2nid(this->cert->sig_alg->algorithm)); ret += "\t\t<signature>" + string + "</signature>\n"; ret += "\t\t<issuer>\n"; try { ret += (this->getIssuer()).getXmlEncoded("\t\t\t"); } catch (...) { } ret += "\t\t</issuer>\n"; ret += "\t\t<validity>\n"; try { ret += "\t\t\t<notBefore>" + ((this->getNotBefore()).getXmlEncoded()) + "</notBefore>\n"; } catch (...) { } try { ret += "\t\t\t<notAfter>" + ((this->getNotAfter()).getXmlEncoded()) + "</notAfter>\n"; } catch (...) { } ret += "\t\t</validity>\n"; ret += "\t\t<subject>\n"; try { ret += (this->getSubject()).getXmlEncoded("\t\t\t"); } catch (...) { } ret += "\t\t</subject>\n"; ret += "\t\t<subjectPublicKeyInfo>\n"; string = OBJ_nid2ln(OBJ_obj2nid(this->cert->cert_info->key->algor->algorithm)); ret += "\t\t\t<algorithm>" + string + "</algorithm>\n"; data = ByteArray(this->cert->cert_info->key->public_key->data, this->cert->cert_info->key->public_key->length); string = Base64::encode(data); ret += "\t\t\t<subjectPublicKey>" + string + "</subjectPublicKey>\n"; ret += "\t\t</subjectPublicKeyInfo>\n"; if (this->cert->cert_info->issuerUID) { data = ByteArray(this->cert->cert_info->issuerUID->data, this->cert->cert_info->issuerUID->length); string = Base64::encode(data); ret += "\t\t<issuerUniqueID>" + string + "</issuerUniqueID>\n"; } if (this->cert->cert_info->subjectUID) { data = ByteArray(this->cert->cert_info->subjectUID->data, this->cert->cert_info->subjectUID->length); string = Base64::encode(data); ret += "\t\t<subjectUniqueID>" + string + "</subjectUniqueID>\n"; } ret += "\t\t<extensions>\n"; extensions = this->getExtensions(); for (i=0;i<extensions.size();i++) { ret += extensions.at(i)->toXml("\t\t\t"); delete extensions.at(i); } ret += "\t\t</extensions>\n"; ret += "\t</tbsCertificate>\n"; ret += "\t<signatureAlgorithm>\n"; string = OBJ_nid2ln(OBJ_obj2nid(this->cert->sig_alg->algorithm)); ret += "\t\t<algorithm>" + string + "</algorithm>\n"; ret += "\t</signatureAlgorithm>\n"; data = ByteArray(this->cert->signature->data, this->cert->signature->length); string = Base64::encode(data); ret += "\t<signatureValue>" + string + "</signatureValue>\n"; ret += "</certificate>\n"; return ret; } std::string Certificate::getPemEncoded() const throw (EncodeException) { BIO *buffer; int ndata, wrote; std::string ret; ByteArray *retTemp; unsigned char *data; buffer = BIO_new(BIO_s_mem()); if (buffer == NULL) { throw EncodeException(EncodeException::BUFFER_CREATING, "Certificate::getPemEncoded"); } wrote = PEM_write_bio_X509(buffer, this->cert); if (!wrote) { BIO_free(buffer); throw EncodeException(EncodeException::PEM_ENCODE, "Certificate::getPemEncoded"); } ndata = BIO_get_mem_data(buffer, &data); if (ndata <= 0) { BIO_free(buffer); throw EncodeException(EncodeException::BUFFER_READING, "Certificate::getPemEncoded"); } retTemp = new ByteArray(data, ndata); ret = retTemp->toString(); delete retTemp; BIO_free(buffer); return ret; } ByteArray Certificate::getDerEncoded() const throw (EncodeException) { BIO *buffer; int ndata, wrote; ByteArray ret; unsigned char *data; buffer = BIO_new(BIO_s_mem()); if (buffer == NULL) { throw EncodeException(EncodeException::BUFFER_CREATING, "Certificate::getDerEncoded"); } wrote = i2d_X509_bio(buffer, this->cert); if (!wrote) { BIO_free(buffer); throw EncodeException(EncodeException::DER_ENCODE, "Certificate::getDerEncoded"); } ndata = BIO_get_mem_data(buffer, &data); if (ndata <= 0) { BIO_free(buffer); throw EncodeException(EncodeException::BUFFER_READING, "Certificate::getDerEncoded"); } ret = ByteArray(data, ndata); BIO_free(buffer); return ret; } long int Certificate::getSerialNumber() throw (CertificationException) { ASN1_INTEGER *asn1Int; long ret; if (this->cert == NULL) { throw CertificationException(CertificationException::INVALID_CERTIFICATE, "Certificate::getSerialNumber"); } /* Here, we have a problem!!! the return value -1 can be error and a valid value. */ asn1Int = X509_get_serialNumber(this->cert); if (asn1Int == NULL) { throw CertificationException(CertificationException::SET_NO_VALUE, "Certificate::getSerialNumber"); } if (asn1Int->data == NULL) { throw CertificationException(CertificationException::INTERNAL_ERROR, "Certificate::getSerialNumber"); } ret = ASN1_INTEGER_get(asn1Int); if (ret < 0L) { throw CertificationException(CertificationException::INTERNAL_ERROR, "Certificate::getSerialNumber"); } return ret; } BigInteger Certificate::getSerialNumberBigInt() throw (CertificationException) { ASN1_INTEGER *asn1Int; BigInteger ret; if (this->cert == NULL) { throw CertificationException(CertificationException::INVALID_CERTIFICATE, "Certificate::getSerialNumberBytes"); } /* Here, we have a problem!!! the return value -1 can be error and a valid value. */ asn1Int = X509_get_serialNumber(this->cert); if (asn1Int == NULL) { throw CertificationException(CertificationException::SET_NO_VALUE, "Certificate::getSerialNumberBytes"); } if (asn1Int->data == NULL) { throw CertificationException(CertificationException::INTERNAL_ERROR, "Certificate::getSerialNumberBytes"); } ret = BigInteger(asn1Int); return ret; } MessageDigest::Algorithm Certificate::getMessageDigestAlgorithm() throw (MessageDigestException) { MessageDigest::Algorithm ret; ret = MessageDigest::getMessageDigest(OBJ_obj2nid(this->cert->sig_alg->algorithm)); return ret; } PublicKey* Certificate::getPublicKey() throw (CertificationException, AsymmetricKeyException) { EVP_PKEY *key; PublicKey *ret; if (this->cert == NULL) { throw CertificationException(CertificationException::INVALID_CERTIFICATE, "Certificate::getPublicKey"); } key = X509_get_pubkey(this->cert); if (key == NULL) { throw CertificationException(CertificationException::SET_NO_VALUE, "Certificate::getPublicKey"); } try { ret = new PublicKey(key); } catch (...) { EVP_PKEY_free(key); throw; } return ret; } ByteArray Certificate::getPublicKeyInfo() throw (CertificationException) { ByteArray ret; unsigned int size; ASN1_BIT_STRING *temp; if (!this->cert->cert_info->key) { throw CertificationException(CertificationException::SET_NO_VALUE, "Certificate::getPublicKeyInfo"); } temp = this->cert->cert_info->key->public_key; ret = ByteArray(EVP_MAX_MD_SIZE); EVP_Digest(temp->data, temp->length, ret.getDataPointer(), &size, EVP_sha1(), NULL); ret = ByteArray(ret.getDataPointer(), size); return ret; } long Certificate::getVersion() throw (CertificationException) { long ret; /* Here, we have a problem!!! the return value 0 can be error and a valid value. */ if (this->cert == NULL) { throw CertificationException(CertificationException::INVALID_CERTIFICATE, "Certificate::getVersion"); } ret = X509_get_version(this->cert); if (ret < 0 || ret > 2) { throw CertificationException(CertificationException::SET_NO_VALUE, "Certificate::getVersion"); } return ret; } DateTime Certificate::getNotBefore() { ASN1_TIME *asn1Time; asn1Time = X509_get_notBefore(this->cert); return DateTime(asn1Time); } DateTime Certificate::getNotAfter() { ASN1_TIME *asn1Time; asn1Time = X509_get_notAfter(this->cert); return DateTime(asn1Time); } RDNSequence Certificate::getIssuer() { RDNSequence name; if (this->cert) { name = RDNSequence(X509_get_issuer_name(this->cert)); } return name; } RDNSequence Certificate::getSubject() { RDNSequence name; if (this->cert) { name = RDNSequence(X509_get_subject_name(this->cert)); } return name; } std::vector<Extension*> Certificate::getExtension(Extension::Name extensionName) { int next, i; X509_EXTENSION *ext; std::vector<Extension *> ret; Extension *oneExt; next = X509_get_ext_count(this->cert); for (i=0;i<next;i++) { ext = X509_get_ext(this->cert, i); if (Extension::getName(ext) == extensionName) { switch (Extension::getName(ext)) { case Extension::KEY_USAGE: oneExt = new KeyUsageExtension(ext); break; case Extension::EXTENDED_KEY_USAGE: oneExt = new ExtendedKeyUsageExtension(ext); break; case Extension::AUTHORITY_KEY_IDENTIFIER: oneExt = new AuthorityKeyIdentifierExtension(ext); break; case Extension::CRL_DISTRIBUTION_POINTS: oneExt = new CRLDistributionPointsExtension(ext); break; case Extension::AUTHORITY_INFORMATION_ACCESS: oneExt = new AuthorityInformationAccessExtension(ext); break; case Extension::BASIC_CONSTRAINTS: oneExt = new BasicConstraintsExtension(ext); break; case Extension::CERTIFICATE_POLICIES: oneExt = new CertificatePoliciesExtension(ext); break; case Extension::ISSUER_ALTERNATIVE_NAME: oneExt = new IssuerAlternativeNameExtension(ext); break; case Extension::SUBJECT_ALTERNATIVE_NAME: oneExt = new SubjectAlternativeNameExtension(ext); break; case Extension::SUBJECT_INFORMATION_ACCESS: oneExt = new SubjectInformationAccessExtension(ext); break; case Extension::SUBJECT_KEY_IDENTIFIER: oneExt = new SubjectKeyIdentifierExtension(ext); break; default: oneExt = new Extension(ext); break; } ret.push_back(oneExt); } } return ret; } std::vector<Extension*> Certificate::getExtensions() { int next, i; X509_EXTENSION *ext; std::vector<Extension *> ret; Extension *oneExt; next = X509_get_ext_count(this->cert); for (i=0;i<next;i++) { ext = X509_get_ext(this->cert, i); switch (Extension::getName(ext)) { case Extension::KEY_USAGE: oneExt = new KeyUsageExtension(ext); break; case Extension::EXTENDED_KEY_USAGE: oneExt = new ExtendedKeyUsageExtension(ext); break; case Extension::AUTHORITY_KEY_IDENTIFIER: oneExt = new AuthorityKeyIdentifierExtension(ext); break; case Extension::CRL_DISTRIBUTION_POINTS: oneExt = new CRLDistributionPointsExtension(ext); break; case Extension::AUTHORITY_INFORMATION_ACCESS: oneExt = new AuthorityInformationAccessExtension(ext); break; case Extension::BASIC_CONSTRAINTS: oneExt = new BasicConstraintsExtension(ext); break; case Extension::CERTIFICATE_POLICIES: oneExt = new CertificatePoliciesExtension(ext); break; case Extension::ISSUER_ALTERNATIVE_NAME: oneExt = new IssuerAlternativeNameExtension(ext); break; case Extension::SUBJECT_ALTERNATIVE_NAME: oneExt = new SubjectAlternativeNameExtension(ext); break; case Extension::SUBJECT_INFORMATION_ACCESS: oneExt = new SubjectInformationAccessExtension(ext); break; case Extension::SUBJECT_KEY_IDENTIFIER: oneExt = new SubjectKeyIdentifierExtension(ext); break; default: oneExt = new Extension(ext); break; } ret.push_back(oneExt); } return ret; } std::vector<Extension *> Certificate::getUnknownExtensions() { int next, i; X509_EXTENSION *ext; std::vector<Extension *> ret; Extension *oneExt; next = X509_get_ext_count(this->cert); for (i=0;i<next;i++) { ext = X509_get_ext(this->cert, i); switch (Extension::getName(ext)) { case Extension::UNKNOWN: oneExt = new Extension(ext); ret.push_back(oneExt); default: break; } } return ret; } ByteArray Certificate::getFingerPrint(MessageDigest::Algorithm algorithm) const throw (CertificationException, EncodeException, MessageDigestException) { ByteArray ret, derEncoded; MessageDigest messageDigest; derEncoded = this->getDerEncoded(); messageDigest.init(algorithm); ret = messageDigest.doFinal(derEncoded); return ret; } bool Certificate::verify(PublicKey &publicKey) { int ok; ok = X509_verify(this->cert, publicKey.getEvpPkey()); return (ok == 1); } X509* Certificate::getX509() const { return this->cert; } CertificateRequest Certificate::getNewCertificateRequest(PrivateKey &privateKey, MessageDigest::Algorithm algorithm) throw (CertificationException) { X509_REQ* req = NULL; req = X509_to_X509_REQ(this->cert, privateKey.getEvpPkey(), MessageDigest::getMessageDigest(algorithm)); if (!req) { throw CertificationException(CertificationException::INTERNAL_ERROR, "Certificate::getNewCertificateRequest"); } return CertificateRequest(req); } Certificate& Certificate::operator =(const Certificate& value) { if (this->cert) { X509_free(this->cert); } this->cert = X509_dup(value.getX509()); return (*this); } bool Certificate::operator ==(const Certificate& value) { return X509_cmp(this->cert, value.getX509()) == 0; } bool Certificate::operator !=(const Certificate& value) { return !this->operator==(value); }
26.060172
116
0.682298
LabSEC
cd0a9c8f5c6686ce499698e14c2e430ff23128bb
4,749
cpp
C++
tests/OptionalMemorySafetyTest.cpp
jtojnar/aws-crt-cpp
799b83cf352b173abf11d722633f330596a1f4a4
[ "Apache-2.0" ]
53
2019-01-03T22:10:43.000Z
2022-01-11T17:00:42.000Z
tests/OptionalMemorySafetyTest.cpp
jtojnar/aws-crt-cpp
799b83cf352b173abf11d722633f330596a1f4a4
[ "Apache-2.0" ]
65
2019-03-16T01:09:12.000Z
2022-02-28T19:02:59.000Z
tests/OptionalMemorySafetyTest.cpp
jtojnar/aws-crt-cpp
799b83cf352b173abf11d722633f330596a1f4a4
[ "Apache-2.0" ]
37
2019-04-03T19:15:14.000Z
2022-03-10T03:09:07.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/crt/Api.h> #include <aws/crt/Optional.h> #include <aws/testing/aws_test_harness.h> const char *s_test_str = "This is a string, that should be long enough to avoid small string optimizations"; static int s_OptionalCopySafety(struct aws_allocator *allocator, void *ctx) { (void)ctx; { Aws::Crt::ApiHandle apiHandle(allocator); Aws::Crt::Optional<Aws::Crt::String> str1(s_test_str); Aws::Crt::Optional<Aws::Crt::String> strCpyAssigned = str1; Aws::Crt::Optional<Aws::Crt::String> strCpyConstructedOptional(strCpyAssigned); Aws::Crt::Optional<Aws::Crt::String> strCpyConstructedValue(*strCpyAssigned); // now force data access just to check there's not a segfault hiding somewhere. ASSERT_STR_EQUALS(s_test_str, str1->c_str()); ASSERT_STR_EQUALS(s_test_str, strCpyAssigned->c_str()); ASSERT_STR_EQUALS(s_test_str, strCpyConstructedOptional->c_str()); ASSERT_STR_EQUALS(s_test_str, strCpyConstructedValue->c_str()); } return AWS_OP_SUCCESS; } AWS_TEST_CASE(OptionalCopySafety, s_OptionalCopySafety) static int s_OptionalMoveSafety(struct aws_allocator *allocator, void *ctx) { (void)ctx; { Aws::Crt::ApiHandle apiHandle(allocator); Aws::Crt::Optional<Aws::Crt::String> str1(s_test_str); Aws::Crt::Optional<Aws::Crt::String> strMoveAssigned = std::move(str1); ASSERT_STR_EQUALS(s_test_str, strMoveAssigned->c_str()); Aws::Crt::Optional<Aws::Crt::String> strMoveValueAssigned = std::move(*strMoveAssigned); ASSERT_STR_EQUALS(s_test_str, strMoveValueAssigned->c_str()); Aws::Crt::Optional<Aws::Crt::String> strMoveConstructed(std::move(strMoveValueAssigned)); ASSERT_STR_EQUALS(s_test_str, strMoveConstructed->c_str()); Aws::Crt::Optional<Aws::Crt::String> strMoveValueConstructed(std::move(*strMoveConstructed)); ASSERT_STR_EQUALS(s_test_str, strMoveValueConstructed->c_str()); } return AWS_OP_SUCCESS; } AWS_TEST_CASE(OptionalMoveSafety, s_OptionalMoveSafety) class CopyMoveTester { public: CopyMoveTester() : m_copied(false), m_moved(false) {} CopyMoveTester(const CopyMoveTester &) : m_copied(true), m_moved(false) {} CopyMoveTester(CopyMoveTester &&) : m_copied(false), m_moved(true) {} CopyMoveTester &operator=(const CopyMoveTester &) { m_copied = true; m_moved = false; return *this; } CopyMoveTester &operator=(CopyMoveTester &&) { m_copied = false; m_moved = true; return *this; } ~CopyMoveTester() {} bool m_copied; bool m_moved; }; static int s_OptionalCopyAndMoveSemantics(struct aws_allocator *allocator, void *ctx) { (void)ctx; { Aws::Crt::ApiHandle apiHandle(allocator); CopyMoveTester initialItem; ASSERT_FALSE(initialItem.m_copied); ASSERT_FALSE(initialItem.m_moved); Aws::Crt::Optional<CopyMoveTester> copyConstructedValue(initialItem); ASSERT_TRUE(copyConstructedValue->m_copied); ASSERT_FALSE(copyConstructedValue->m_moved); Aws::Crt::Optional<CopyMoveTester> copyConstructedOptional(copyConstructedValue); ASSERT_TRUE(copyConstructedOptional->m_copied); ASSERT_FALSE(copyConstructedOptional->m_moved); Aws::Crt::Optional<CopyMoveTester> copyAssignedValue = initialItem; ASSERT_TRUE(copyAssignedValue->m_copied); ASSERT_FALSE(copyAssignedValue->m_moved); Aws::Crt::Optional<CopyMoveTester> copyAssignedOptional = copyConstructedOptional; ASSERT_TRUE(copyAssignedOptional->m_copied); ASSERT_FALSE(copyAssignedOptional->m_moved); Aws::Crt::Optional<CopyMoveTester> moveConstructedValue(std::move(initialItem)); ASSERT_FALSE(moveConstructedValue->m_copied); ASSERT_TRUE(moveConstructedValue->m_moved); Aws::Crt::Optional<CopyMoveTester> moveConstructedOptional(std::move(moveConstructedValue)); ASSERT_FALSE(moveConstructedOptional->m_copied); ASSERT_TRUE(moveConstructedOptional->m_moved); Aws::Crt::Optional<CopyMoveTester> moveAssignedValue = std::move(*moveConstructedOptional); ASSERT_FALSE(moveAssignedValue->m_copied); ASSERT_TRUE(moveAssignedValue->m_moved); Aws::Crt::Optional<CopyMoveTester> moveAssignedOptional = std::move(moveAssignedValue); ASSERT_FALSE(moveAssignedOptional->m_copied); ASSERT_TRUE(moveAssignedOptional->m_moved); } return AWS_OP_SUCCESS; } AWS_TEST_CASE(OptionalCopyAndMoveSemantics, s_OptionalCopyAndMoveSemantics)
35.977273
108
0.71236
jtojnar
cd0b536e305307c3d3c26556015131863c3b4d2f
2,156
cpp
C++
leetcode/problems/medium/918-maximum-sum-circular-subarray.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/medium/918-maximum-sum-circular-subarray.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/medium/918-maximum-sum-circular-subarray.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Maximum Sum Circular Subarray Given a circular array C of integers represented by A, find the maximum possible sum of a non-empty subarray of C. Here, a circular array means the end of the array connects to the beginning of the array. (Formally, C[i] = A[i] when 0 <= i < A.length, and C[i+A.length] = C[i] when i >= 0.) Also, a subarray may only include each element of the fixed buffer A at most once. (Formally, for a subarray C[i], C[i+1], ..., C[j], there does not exist i <= k1, k2 <= j with k1 % A.length = k2 % A.length.) Example 1: Input: [1,-2,3,-2] Output: 3 Explanation: Subarray [3] has maximum sum 3 Example 2: Input: [5,-3,5] Output: 10 Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10 Example 3: Input: [3,-1,2,-1] Output: 4 Explanation: Subarray [2,-1,3] has maximum sum 2 + (-1) + 3 = 4 Example 4: Input: [3,-2,2,-3] Output: 3 Explanation: Subarray [3] and [3,-2,2] both have maximum sum 3 Example 5: Input: [-2,-3,-1] Output: -1 Explanation: Subarray [-1] has maximum sum -1 Note: -30000 <= A[i] <= 30000 1 <= A.length <= 30000 */ class Solution { public: int maxSubarraySumCircular(vector<int>& A) { int total_sum = 0, global_max = INT_MIN, global_min = INT_MAX, local_min = 0, local_max = 0; // kadane's algorithm for (int a : A) { local_max = max(a, local_max + a); global_max = max(global_max, local_max); local_min = min(a, local_min + a); global_min = min(global_min, local_min); total_sum += a; } // case 1: max subarray is not circular // ______________________________ // | | Max subarray| | // 0 --------------------------- N-1 // case 2: max subarray is circular // _____________________________ // | | Max su|barray| | // 0 -----------|N-1------------ 2N-1 // which is equal to // ______________________________ // | max | Min subarray| subarray| // 0 --------------------------- N-1 // max(the max subarray sum, the total sum - the min subarray sum) return global_max > 0 ? max(global_max, total_sum - global_min) : global_max; } };
28.746667
209
0.600186
wingkwong
cd0c3a8cc403b314828878a87f5691eb2244b298
27,488
cpp
C++
src/align.cpp
ezracb/librealsense
c595bc426e1b258c7af1625cabb8e9ccb9335a8b
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
src/align.cpp
ezracb/librealsense
c595bc426e1b258c7af1625cabb8e9ccb9335a8b
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
src/align.cpp
ezracb/librealsense
c595bc426e1b258c7af1625cabb8e9ccb9335a8b
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2015 Intel Corporation. All Rights Reserved. #include "../include/librealsense2/rs.hpp" #include "../include/librealsense2/rsutil.h" #include "core/video.h" #include "align.h" #include "archive.h" #include "context.h" #include "environment.h" namespace librealsense { template<class MAP_DEPTH> void deproject_depth(float * points, const rs2_intrinsics & intrin, const uint16_t * depth, MAP_DEPTH map_depth) { for (int y = 0; y<intrin.height; ++y) { for (int x = 0; x<intrin.width; ++x) { const float pixel[] = { (float)x, (float)y }; rs2_deproject_pixel_to_point(points, &intrin, pixel, map_depth(*depth++)); points += 3; } } } const float3 * depth_to_points(uint8_t* image, const rs2_intrinsics &depth_intrinsics, const uint16_t * depth_image, float depth_scale) { deproject_depth(reinterpret_cast<float *>(image), depth_intrinsics, depth_image, [depth_scale](uint16_t z) { return depth_scale * z; }); return reinterpret_cast<float3 *>(image); } float3 transform(const rs2_extrinsics *extrin, const float3 &point) { float3 p = {}; rs2_transform_point_to_point(&p.x, extrin, &point.x); return p; } float2 project(const rs2_intrinsics *intrin, const float3 & point) { float2 pixel = {}; rs2_project_point_to_pixel(&pixel.x, intrin, &point.x); return pixel; } float2 pixel_to_texcoord(const rs2_intrinsics *intrin, const float2 & pixel) { return{ (pixel.x + 0.5f) / intrin->width, (pixel.y + 0.5f) / intrin->height }; } float2 project_to_texcoord(const rs2_intrinsics *intrin, const float3 & point) { return pixel_to_texcoord(intrin, project(intrin, point)); } void processing_block::set_processing_callback(frame_processor_callback_ptr callback) { std::lock_guard<std::mutex> lock(_mutex); _callback = callback; } void processing_block::set_output_callback(frame_callback_ptr callback) { _source.set_callback(callback); } processing_block::processing_block() : _source_wrapper(_source) { _source.init(std::make_shared<metadata_parser_map>()); } void processing_block::invoke(frame_holder f) { auto callback = _source.begin_callback(); try { if (_callback) { frame_interface* ptr = nullptr; std::swap(f.frame, ptr); _callback->on_frame((rs2_frame*)ptr, _source_wrapper.get_c_wrapper()); } } catch(...) { LOG_ERROR("Exception was thrown during user processing callback!"); } } void synthetic_source::frame_ready(frame_holder result) { _actual_source.invoke_callback(std::move(result)); } frame_interface* synthetic_source::allocate_points(std::shared_ptr<stream_profile_interface> stream, frame_interface* original) { auto vid_stream = dynamic_cast<video_stream_profile_interface*>(stream.get()); if (vid_stream) { frame_additional_data data{}; data.frame_number = original->get_frame_number(); data.timestamp = original->get_frame_timestamp(); data.timestamp_domain = original->get_frame_timestamp_domain(); data.metadata_size = 0; data.system_time = _actual_source.get_time(); auto res = _actual_source.alloc_frame(RS2_EXTENSION_POINTS, vid_stream->get_width() * vid_stream->get_height() * sizeof(float) * 5, data, true); if (!res) throw wrong_api_call_sequence_exception("Out of frame resources!"); res->set_sensor(original->get_sensor()); res->set_stream(stream); return res; } return nullptr; } frame_interface* synthetic_source::allocate_video_frame(std::shared_ptr<stream_profile_interface> stream, frame_interface* original, int new_bpp, int new_width, int new_height, int new_stride, rs2_extension frame_type) { video_frame* vf = nullptr; if (new_bpp == 0 || (new_width == 0 && new_stride == 0) || new_height == 0) { // If the user wants to delegate width, height and etc to original frame, it must be a video frame if (!rs2_is_frame_extendable_to((rs2_frame*)original, RS2_EXTENSION_VIDEO_FRAME, nullptr)) { throw std::runtime_error("If original frame is not video frame, you must specify new bpp, width/stide and height!"); } vf = static_cast<video_frame*>(original); } frame_additional_data data{}; data.frame_number = original->get_frame_number(); data.timestamp = original->get_frame_timestamp(); data.timestamp_domain = original->get_frame_timestamp_domain(); data.metadata_size = 0; data.system_time = _actual_source.get_time(); auto width = new_width; auto height = new_height; auto bpp = new_bpp * 8; auto stride = new_stride; if (bpp == 0) { bpp = vf->get_bpp(); } if (width == 0 && stride == 0) { width = vf->get_width(); stride = width * bpp / 8; } else if (width == 0) { width = stride * 8 / bpp; } else if (stride == 0) { stride = width * bpp / 8; } if (height == 0) { height = vf->get_height(); } auto res = _actual_source.alloc_frame(frame_type, stride * height, data, true); if (!res) throw wrong_api_call_sequence_exception("Out of frame resources!"); vf = static_cast<video_frame*>(res); vf->assign(width, height, stride, bpp); vf->set_sensor(original->get_sensor()); res->set_stream(stream); if (frame_type == RS2_EXTENSION_DEPTH_FRAME) { original->acquire(); (dynamic_cast<depth_frame*>(res))->set_original(original); } return res; } int get_embeded_frames_size(frame_interface* f) { if (f == nullptr) return 0; if (auto c = dynamic_cast<composite_frame*>(f)) return static_cast<int>(c->get_embedded_frames_count()); return 1; } void copy_frames(frame_holder from, frame_interface**& target) { if (auto comp = dynamic_cast<composite_frame*>(from.frame)) { auto frame_buff = comp->get_frames(); for (size_t i = 0; i < comp->get_embedded_frames_count(); i++) { std::swap(*target, frame_buff[i]); target++; } from.frame->disable_continuation(); } else { *target = nullptr; // "move" the frame ref into target std::swap(*target, from.frame); target++; } } frame_interface* synthetic_source::allocate_composite_frame(std::vector<frame_holder> holders) { frame_additional_data d {}; auto req_size = 0; for (auto&& f : holders) req_size += get_embeded_frames_size(f.frame); auto res = _actual_source.alloc_frame(RS2_EXTENSION_COMPOSITE_FRAME, req_size * sizeof(rs2_frame*), d, true); if (!res) return nullptr; auto cf = static_cast<composite_frame*>(res); auto frames = cf->get_frames(); for (auto&& f : holders) copy_frames(std::move(f), frames); frames -= req_size; auto releaser = [frames, req_size]() { for (auto i = 0; i < req_size; i++) { frames[i]->release(); frames[i] = nullptr; } }; frame_continuation release_frames(releaser, nullptr); cf->attach_continuation(std::move(release_frames)); cf->set_stream(cf->first()->get_stream()); return res; } pointcloud::pointcloud() :_depth_intrinsics_ptr(nullptr), _depth_units_ptr(nullptr), _mapped_intrinsics_ptr(nullptr), _extrinsics_ptr(nullptr), _mapped(nullptr), _depth_stream_uid(0) { auto on_frame = [this](rs2::frame f, const rs2::frame_source& source) { auto inspect_depth_frame = [this](const rs2::frame& depth) { auto depth_frame = (frame_interface*)depth.get(); std::lock_guard<std::mutex> lock(_mutex); if (!_stream.get() || _depth_stream_uid != depth_frame->get_stream()->get_unique_id()) { _stream = depth_frame->get_stream()->clone(); _depth_stream_uid = depth_frame->get_stream()->get_unique_id(); environment::get_instance().get_extrinsics_graph().register_same_extrinsics(*_stream, *depth_frame->get_stream()); _depth_intrinsics_ptr = nullptr; _depth_units_ptr = nullptr; } bool found_depth_intrinsics = false; bool found_depth_units = false; if (!_depth_intrinsics_ptr) { auto stream_profile = depth_frame->get_stream(); if (auto video = dynamic_cast<video_stream_profile_interface*>(stream_profile.get())) { _depth_intrinsics = video->get_intrinsics(); _depth_intrinsics_ptr = &_depth_intrinsics; found_depth_intrinsics = true; } } if (!_depth_units_ptr) { auto sensor = depth_frame->get_sensor(); _depth_units = sensor->get_option(RS2_OPTION_DEPTH_UNITS).query(); _depth_units_ptr = &_depth_units; found_depth_units = true; } if (found_depth_units != found_depth_intrinsics) { throw wrong_api_call_sequence_exception("Received depth frame that doesn't provide either intrinsics or depth units!"); } }; auto inspect_other_frame = [this](const rs2::frame& other) { auto other_frame = (frame_interface*)other.get(); std::lock_guard<std::mutex> lock(_mutex); if (_mapped.get() != other_frame->get_stream().get()) { _mapped = other_frame->get_stream(); _mapped_intrinsics_ptr = nullptr; _extrinsics_ptr = nullptr; } if (!_mapped_intrinsics_ptr) { if (auto video = dynamic_cast<video_stream_profile_interface*>(_mapped.get())) { _mapped_intrinsics = video->get_intrinsics(); _mapped_intrinsics_ptr = &_mapped_intrinsics; } } if (_stream && !_extrinsics_ptr) { if ( environment::get_instance().get_extrinsics_graph().try_fetch_extrinsics( *_stream, *other_frame->get_stream(), &_extrinsics )) { _extrinsics_ptr = &_extrinsics; } } }; auto process_depth_frame = [this](const rs2::depth_frame& depth) { frame_holder res = get_source().allocate_points(_stream, (frame_interface*)depth.get()); auto pframe = (points*)(res.frame); auto depth_data = (const uint16_t*)depth.get_data(); //auto original_depth = ((depth_frame*)depth.get())->get_original_depth(); //if (original_depth) depth_data = (const uint16_t*)original_depth->get_frame_data(); auto points = depth_to_points((uint8_t*)pframe->get_vertices(), *_depth_intrinsics_ptr, depth_data, *_depth_units_ptr); auto vid_frame = depth.as<rs2::video_frame>(); float2* tex_ptr = pframe->get_texture_coordinates(); rs2_intrinsics mapped_intr; rs2_extrinsics extr; bool map_texture = false; { std::lock_guard<std::mutex> lock(_mutex); if (_extrinsics_ptr && _mapped_intrinsics_ptr) { mapped_intr = *_mapped_intrinsics_ptr; extr = *_extrinsics_ptr; map_texture = true; } } if (map_texture) { for (int y = 0; y < vid_frame.get_height(); ++y) { for (int x = 0; x < vid_frame.get_width(); ++x) { if (points->z) { auto trans = transform(&extr, *points); auto tex_xy = project_to_texcoord(&mapped_intr, trans); *tex_ptr = tex_xy; } else { *tex_ptr = { 0.f, 0.f }; } ++points; ++tex_ptr; } } } get_source().frame_ready(std::move(res)); }; if (auto composite = f.as<rs2::frameset>()) { auto depth = composite.first_or_default(RS2_STREAM_DEPTH); if (depth) { inspect_depth_frame(depth); process_depth_frame(depth); } else { composite.foreach(inspect_other_frame); } } else { if (f.get_profile().stream_type() == RS2_STREAM_DEPTH) { inspect_depth_frame(f); process_depth_frame(f); } else { inspect_other_frame(f); } } }; auto callback = new rs2::frame_processor_callback<decltype(on_frame)>(on_frame); processing_block::set_processing_callback(std::shared_ptr<rs2_frame_processor_callback>(callback)); } //void colorize::set_color_map(rs2_color_map cm) //{ // std::lock_guard<std::mutex> lock(_mutex); // switch(cm) // { // case RS2_COLOR_MAP_CLASSIC: // _cm = &classic; // break; // case RS2_COLOR_MAP_JET: // _cm = &jet; // break; // case RS2_COLOR_MAP_HSV: // _cm = &hsv; // break; // default: // _cm = &classic; // } //} //void colorize::histogram_equalization(bool enable) //{ // std::lock_guard<std::mutex> lock(_mutex); // _equalize = enable; //} //colorize::colorize(std::shared_ptr<uvc::time_service> ts) // : processing_block(RS2_EXTENSION_VIDEO_FRAME, ts), _cm(&classic), _equalize(true) //{ // auto on_frame = [this](std::vector<rs2::frame> frames, const rs2::frame_source& source) // { // std::lock_guard<std::mutex> lock(_mutex); // for (auto&& f : frames) // { // if (f.get_stream_type() == RS2_STREAM_DEPTH) // { // const auto max_depth = 0x10000; // static uint32_t histogram[max_depth]; // memset(histogram, 0, sizeof(histogram)); // auto vf = f.as<video_frame>(); // auto width = vf.get_width(); // auto height = vf.get_height(); // auto depth_image = vf.get_frame_data(); // for (auto i = 0; i < width*height; ++i) ++histogram[depth_image[i]]; // for (auto i = 2; i < max_depth; ++i) histogram[i] += histogram[i - 1]; // Build a cumulative histogram for the indices in [1,0xFFFF] // for (auto i = 0; i < width*height; ++i) // { // auto d = depth_image[i]; // //if (d) // //{ // // auto f = histogram[d] / (float)histogram[0xFFFF]; // 0-255 based on histogram location // // auto c = map.get(f); // // rgb_image[i * 3 + 0] = c.x; // // rgb_image[i * 3 + 1] = c.y; // // rgb_image[i * 3 + 2] = c.z; // //} // //else // //{ // // rgb_image[i * 3 + 0] = 0; // // rgb_image[i * 3 + 1] = 0; // // rgb_image[i * 3 + 2] = 0; // //} // } // } // } // }; // auto callback = new rs2::frame_processor_callback<decltype(on_frame)>(on_frame); // set_processing_callback(std::shared_ptr<rs2_frame_processor_callback>(callback)); //} template<class GET_DEPTH, class TRANSFER_PIXEL> void align_images(const rs2_intrinsics & depth_intrin, const rs2_extrinsics & depth_to_other, const rs2_intrinsics & other_intrin, GET_DEPTH get_depth, TRANSFER_PIXEL transfer_pixel) { // Iterate over the pixels of the depth image #pragma omp parallel for schedule(dynamic) for (int depth_y = 0; depth_y < depth_intrin.height; ++depth_y) { int depth_pixel_index = depth_y * depth_intrin.width; for (int depth_x = 0; depth_x < depth_intrin.width; ++depth_x, ++depth_pixel_index) { // Skip over depth pixels with the value of zero, we have no depth data so we will not write anything into our aligned images if (float depth = get_depth(depth_pixel_index)) { // Map the top-left corner of the depth pixel onto the other image float depth_pixel[2] = { depth_x - 0.5f, depth_y - 0.5f }, depth_point[3], other_point[3], other_pixel[2]; rs2_deproject_pixel_to_point(depth_point, &depth_intrin, depth_pixel, depth); rs2_transform_point_to_point(other_point, &depth_to_other, depth_point); rs2_project_point_to_pixel(other_pixel, &other_intrin, other_point); const int other_x0 = static_cast<int>(other_pixel[0] + 0.5f); const int other_y0 = static_cast<int>(other_pixel[1] + 0.5f); // Map the bottom-right corner of the depth pixel onto the other image depth_pixel[0] = depth_x + 0.5f; depth_pixel[1] = depth_y + 0.5f; rs2_deproject_pixel_to_point(depth_point, &depth_intrin, depth_pixel, depth); rs2_transform_point_to_point(other_point, &depth_to_other, depth_point); rs2_project_point_to_pixel(other_pixel, &other_intrin, other_point); const int other_x1 = static_cast<int>(other_pixel[0] + 0.5f); const int other_y1 = static_cast<int>(other_pixel[1] + 0.5f); if (other_x0 < 0 || other_y0 < 0 || other_x1 >= other_intrin.width || other_y1 >= other_intrin.height) continue; // Transfer between the depth pixels and the pixels inside the rectangle on the other image for (int y = other_y0; y <= other_y1; ++y) { for (int x = other_x0; x <= other_x1; ++x) { transfer_pixel(depth_pixel_index, y * other_intrin.width + x); } } } } } } align::align(rs2_stream to_stream) : _depth_intrinsics_ptr(nullptr), _depth_units_ptr(nullptr), _other_intrinsics_ptr(nullptr), _depth_to_other_extrinsics_ptr(nullptr), _other_bytes_per_pixel_ptr(nullptr), _other_stream_type(to_stream) { auto on_frame = [this](rs2::frame f, const rs2::frame_source& source) { auto inspect_depth_frame = [this, &source](const rs2::frame& depth, const rs2::frame& other) { auto depth_frame = (frame_interface*)depth.get(); std::lock_guard<std::mutex> lock(_mutex); bool found_depth_intrinsics = false; bool found_depth_units = false; if (!_depth_intrinsics_ptr) { auto stream_profile = depth_frame->get_stream(); if (auto video = dynamic_cast<video_stream_profile_interface*>(stream_profile.get())) { _depth_intrinsics = video->get_intrinsics(); _depth_intrinsics_ptr = &_depth_intrinsics; found_depth_intrinsics = true; } } if (!_depth_units_ptr) { auto sensor = depth_frame->get_sensor(); _depth_units = sensor->get_option(RS2_OPTION_DEPTH_UNITS).query(); _depth_units_ptr = &_depth_units; found_depth_units = true; } if (found_depth_units != found_depth_intrinsics) { throw wrong_api_call_sequence_exception("Received depth frame that doesn't provide either intrinsics or depth units!"); } if (!_depth_stream_profile.get()) { _depth_stream_profile = depth_frame->get_stream(); environment::get_instance().get_extrinsics_graph().register_same_extrinsics(*_depth_stream_profile, *depth_frame->get_stream()); auto vid_frame = depth.as<rs2::video_frame>(); _width = vid_frame.get_width(); _height = vid_frame.get_height(); } if (!_depth_to_other_extrinsics_ptr && _depth_stream_profile && _other_stream_profile) { environment::get_instance().get_extrinsics_graph().try_fetch_extrinsics(*_depth_stream_profile, *_other_stream_profile, &_depth_to_other_extrinsics); _depth_to_other_extrinsics_ptr = &_depth_to_other_extrinsics; } if (_depth_intrinsics_ptr && _depth_units_ptr && _depth_stream_profile && _other_bytes_per_pixel_ptr && _depth_to_other_extrinsics_ptr && _other_intrinsics_ptr && _other_stream_profile && other) { std::vector<frame_holder> frames(2); auto other_frame = (frame_interface*)other.get(); other_frame->acquire(); frames[0] = frame_holder{ other_frame }; frame_holder out_frame = get_source().allocate_video_frame(_depth_stream_profile, depth_frame, _other_bytes_per_pixel / 8, _other_intrinsics.width, _other_intrinsics.height, 0, RS2_EXTENSION_DEPTH_FRAME); auto p_out_frame = reinterpret_cast<uint16_t*>(((frame*)(out_frame.frame))->data.data()); memset(p_out_frame, _depth_stream_profile->get_format() == RS2_FORMAT_DISPARITY16 ? 0xFF : 0x00, _other_intrinsics.height * _other_intrinsics.width * sizeof(uint16_t)); auto p_depth_frame = reinterpret_cast<const uint16_t*>(((frame*)(depth_frame))->get_frame_data()); align_images(*_depth_intrinsics_ptr, *_depth_to_other_extrinsics_ptr, *_other_intrinsics_ptr, [p_depth_frame, this](int z_pixel_index) { return _depth_units * p_depth_frame[z_pixel_index]; }, [p_out_frame, p_depth_frame/*, p_out_other_frame, other_bytes_per_pixel*/](int z_pixel_index, int other_pixel_index) { p_out_frame[other_pixel_index] = p_out_frame[other_pixel_index] ? std::min( (int)(p_out_frame[other_pixel_index]), (int)(p_depth_frame[z_pixel_index]) ) : p_depth_frame[z_pixel_index]; }); frames[1] = std::move(out_frame); auto composite = get_source().allocate_composite_frame(std::move(frames)); get_source().frame_ready(std::move(composite)); } }; auto inspect_other_frame = [this, &source](const rs2::frame& other) { auto other_frame = (frame_interface*)other.get(); std::lock_guard<std::mutex> lock(_mutex); if (_other_stream_type != other_frame->get_stream()->get_stream_type()) return; if (!_other_stream_profile.get()) { _other_stream_profile = other_frame->get_stream(); } if (!_other_bytes_per_pixel_ptr) { auto vid_frame = other.as<rs2::video_frame>(); _other_bytes_per_pixel = vid_frame.get_bytes_per_pixel(); _other_bytes_per_pixel_ptr = &_other_bytes_per_pixel; } if (!_other_intrinsics_ptr) { if (auto video = dynamic_cast<video_stream_profile_interface*>(_other_stream_profile.get())) { _other_intrinsics = video->get_intrinsics(); _other_intrinsics_ptr = &_other_intrinsics; } } //source.frame_ready(other); }; if (auto composite = f.as<rs2::frameset>()) { auto depth = composite.first_or_default(RS2_STREAM_DEPTH); auto other = composite.first_or_default(_other_stream_type); if (other) { inspect_other_frame(other); } if (depth) { inspect_depth_frame(depth, other); } } }; auto callback = new rs2::frame_processor_callback<decltype(on_frame)>(on_frame); processing_block::set_processing_callback(std::shared_ptr<rs2_frame_processor_callback>(callback)); } }
41.46003
188
0.524993
ezracb
cd0dfb65ec82c65ba4e4af4650cae6ed709900a3
34
cpp
C++
libwx/src/Maps/MapControlBaseTpl.cpp
EnjoMitch/EnjoLib
321167146657cba1497a9d3b4ffd71430f9b24b3
[ "BSD-3-Clause" ]
3
2021-06-14T15:36:46.000Z
2022-02-28T15:16:08.000Z
libwx/src/Maps/MapControlBaseTpl.cpp
EnjoMitch/EnjoLib
321167146657cba1497a9d3b4ffd71430f9b24b3
[ "BSD-3-Clause" ]
1
2021-07-17T07:52:15.000Z
2021-07-17T07:52:15.000Z
libwx/src/Maps/MapControlBaseTpl.cpp
EnjoMitch/EnjoLib
321167146657cba1497a9d3b4ffd71430f9b24b3
[ "BSD-3-Clause" ]
3
2021-07-12T14:52:38.000Z
2021-11-28T17:10:33.000Z
#include "MapControlBaseTpl.hpp"
11.333333
32
0.794118
EnjoMitch
cd110ba1a1a3db65d78b2c090a63cd54c1bd7781
1,158
cpp
C++
BZOJ/1193/std.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
BZOJ/1193/std.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
BZOJ/1193/std.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <cstring> #include <cstdio> #include <cstdlib> #include <queue> using namespace std; int x,y,fx[10][3],dis[105][105]; struct Point { int x,y; }; void bfs() { memset(dis,-1,sizeof(dis)); dis[x][y]=0; fx[1][1]=fx[2][1]=1,fx[3][1]=fx[4][1]=-1,fx[5][1]=fx[6][1]=2,fx[7][1]=fx[8][1]=-2; fx[1][2]=fx[3][2]=2,fx[2][2]=fx[4][2]=-2,fx[5][2]=fx[7][2]=1,fx[6][2]=fx[8][2]=-1; queue<Point> q; Point p; p.x=x,p.y=y; q.push(p); while (!q.empty()) { Point x; x=q.front(); q.pop(); for (int i=1;i<=8;i++) { int nowx=x.x+fx[i][1],nowy=x.y+fx[i][2]; if (nowx<0||nowy<0||nowx>100||nowy>100) continue; if (dis[nowx][nowy]!=-1) continue; dis[nowx][nowy]=dis[x.x][x.y]+1; Point X; X.x=nowx,X.y=nowy; q.push(X); if (nowx==50&&nowy==50) return; } } } int main() { freopen("code.in","r",stdin);freopen("std.out","w",stdout); int xp,yp,xs,ys; scanf("%d%d%d%d",&xp,&yp,&xs,&ys); x=abs(xs-xp),y=abs(ys-yp); int ans=0; while (x+y>=50) { if (x<y) swap(x,y); if (x-4>=y*2) x-=4; else x-=4,y-=2; ans+=2; } x+=50,y+=50; bfs(); printf("%d\n",ans+dis[50][50]); return 0; }
18.983607
83
0.535406
sjj118
99827a5bc2aa5751e7be0c468986baae5c8f4303
417
cpp
C++
Dataset/Leetcode/train/69/678.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/69/678.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/69/678.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: int XXX(int x) { long long int ans = x; long long int square= 0; while(ans){ long long int temp = ans/2; square= temp*temp; ans = temp; if(square<= x){ break; } } while(square<= x){ ans++; square= ans*ans; } return ans-1; } };
18.954545
39
0.386091
kkcookies99
99832a30287b84907193b5279b1fbf5a94ab9c12
3,138
hh
C++
src/c++/include/xml/XmlWriter.hh
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
13
2018-02-09T22:59:39.000Z
2021-11-29T06:33:22.000Z
src/c++/include/xml/XmlWriter.hh
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
17
2018-01-26T11:36:07.000Z
2022-02-03T18:48:43.000Z
src/c++/include/xml/XmlWriter.hh
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
4
2018-10-19T20:00:00.000Z
2020-10-29T14:44:06.000Z
/** ** Isaac Genome Alignment Software ** Copyright (c) 2010-2017 Illumina, Inc. ** All rights reserved. ** ** This software is provided under the terms and conditions of the ** GNU GENERAL PUBLIC LICENSE Version 3 ** ** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3 ** along with this program. If not, see ** <https://github.com/illumina/licenses/>. ** ** \file XmlWriter.hh ** ** Helper classes for composing xml ** ** \author Roman Petrovski **/ #ifndef iSAAC_XML_XML_WRITER_HH #define iSAAC_XML_XML_WRITER_HH #include <libxml/xmlwriter.h> #include <iostream> #include <boost/noncopyable.hpp> #include "common/Debug.hh" #include "common/Exceptions.hh" namespace isaac { namespace xml { class XmlWriterException : public common::IsaacException { public: XmlWriterException(const std::string &message) : common::IsaacException(message) { } }; class XmlWriter: boost::noncopyable { std::ostream &os_; xmlTextWriterPtr xmlWriter_; static int xmlOutputWriteCallback(void * context, const char * buffer, int len); public: explicit XmlWriter(std::ostream &os); ~XmlWriter(); void close(); XmlWriter &startElement(const char *name); XmlWriter &startElement(const std::string &name) {return startElement(name.c_str());} XmlWriter &endElement(); XmlWriter &writeText(const char *text); template <typename T> XmlWriter &writeElement(const char *name, const T& value) { return (startElement(name) << value).endElement(); } template <typename T> XmlWriter &writeElement(const std::string &name, const T& value) { return writeElement(name.c_str(), value); } template <typename T> XmlWriter &writeAttribute(const char *name, const T& value) { const std::string strValue = boost::lexical_cast<std::string>(value); const int written = xmlTextWriterWriteAttribute(xmlWriter_, BAD_CAST name, BAD_CAST strValue.c_str()); if (-1 == written) { BOOST_THROW_EXCEPTION(XmlWriterException( std::string("xmlTextWriterWriteAttribute returned -1 for attribute name: ") + name + " value: " + strValue)); } return *this; } template <typename T> XmlWriter &operator <<(const T&t) { return writeText(boost::lexical_cast<std::string>(t).c_str()); } struct BlockMacroSupport { bool set_; BlockMacroSupport() : set_(true){} void reset () {set_ = false;}; operator bool() const {return set_;} }; // This is to allow macro ISAAC_XML_WRITER_ELEMENT_BLOCK to work operator BlockMacroSupport() const {return BlockMacroSupport();} }; /** * \brief Macro for controling xml element scope. Automatically closes the element at the end of the block */ #define ISAAC_XML_WRITER_ELEMENT_BLOCK(writer, name) for(xml::XmlWriter::BlockMacroSupport iSaacElementBlockVariable = writer.startElement(name); iSaacElementBlockVariable; iSaacElementBlockVariable.reset(), writer.endElement()) } // namespace xml } // namespace isaac #endif // #ifndef iSAAC_XML_XML_WRITER_HH
29.055556
228
0.689611
Illumina
9983945023649b0aa66452dfe0bf3f3805212be4
1,753
cpp
C++
app/plugins/widgets/PaintField.cpp
adius/FeetJ
aca8ffc72911440eb8341a953ad833f3c7115554
[ "MIT" ]
1
2021-12-20T16:50:25.000Z
2021-12-20T16:50:25.000Z
app/plugins/widgets/PaintField.cpp
adius/FeetJ
aca8ffc72911440eb8341a953ad833f3c7115554
[ "MIT" ]
null
null
null
app/plugins/widgets/PaintField.cpp
adius/FeetJ
aca8ffc72911440eb8341a953ad833f3c7115554
[ "MIT" ]
null
null
null
#include "PaintField.h" #include <QPainter> //We need to register this Type in MTQ MTQ_QML_REGISTER_PLUGIN(PaintField) //Constructor PaintField::PaintField(QQuickItem *) { setHeight(600); setWidth(600); setStrokeHue(0); setBackgroundBrightness(255); } void PaintField::paint(QPainter *painter) { painter->setRenderHint(QPainter::Antialiasing); QRect rect(4, 4, width() - 8, height() - 8); painter->fillRect(rect, m_bgColor); for (int strokeI = 0; strokeI < m_strokes.size(); strokeI++) { painter->setPen(QPen(QBrush(m_strokeColors.at(strokeI)),4)); if (m_strokes.at(strokeI).size() == 1) painter->drawPoint(m_strokes.at(strokeI).at(0)); else if (m_strokes.at(strokeI).size() > 1) { for (int i = 0; i < m_strokes.at(strokeI).size() - 1; i++) { painter->drawLine(m_strokes.at(strokeI).at(i), m_strokes.at(strokeI).at(i+1)); } } } } qreal PaintField::strokeHue() const { return m_strokeHue; } void PaintField::setStrokeHue(const qreal hue) { m_strokeHue = hue; } int PaintField::backgroundBrightness() const { return m_backgroundBrightness; } void PaintField::setBackgroundBrightness(const int brightness) { m_backgroundBrightness = brightness; m_bgColor = QColor().fromHsv(1, 0, brightness); update(); } void PaintField::processContactDown(mtq::ContactEvent *event) { m_strokes.push_back(QVector<QPointF>()); m_strokeColors.push_back(QColor().fromHsvF(m_strokeHue, 1, 1)); QPointF center = event->mappedCenter(); m_strokes.last().push_back(center); update(); } void PaintField::processContactMove(mtq::ContactEvent *event) { QPointF center = event->mappedCenter(); m_strokes.last().push_back(center); update(); } void PaintField::processContactUp(mtq::ContactEvent *event) { update(); }
22.189873
64
0.716486
adius
9984e749e2f41d874e6787cb43c5058f88b99898
2,747
cc
C++
llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/27_io/basic_istream/getline/wchar_t/2.cc
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
1
2016-04-09T02:58:13.000Z
2016-04-09T02:58:13.000Z
llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/27_io/basic_istream/getline/wchar_t/2.cc
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
llvm-gcc-4.2-2.9/libstdc++-v3/testsuite/27_io/basic_istream/getline/wchar_t/2.cc
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
// Copyright (C) 2004 Free Software Foundation // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 2, 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 General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. // 27.6.1.3 unformatted input functions #include <cwchar> // for wcslen #include <istream> #include <sstream> #include <testsuite_hooks.h> // [patch] bits/istream.tcc - getline(char_type*,streamsize,char_type) // http://gcc.gnu.org/ml/libstdc++/2000-07/msg00003.html void test05() { const wchar_t* charray = L"\n" L"a\n" L"aa\n" L"aaa\n" L"aaaa\n" L"aaaaa\n" L"aaaaaa\n" L"aaaaaaa\n" L"aaaaaaaa\n" L"aaaaaaaaa\n" L"aaaaaaaaaa\n" L"aaaaaaaaaaa\n" L"aaaaaaaaaaaa\n" L"aaaaaaaaaaaaa\n" L"aaaaaaaaaaaaaa\n"; bool test __attribute__((unused)) = true; const std::streamsize it = 5; std::streamsize br = 0; wchar_t tmp[it]; std::wstringbuf sb(charray, std::ios_base::in); std::wistream ifs(&sb); std::streamsize blen = std::wcslen(charray); VERIFY(!(!ifs)); while(ifs.getline(tmp, it) || ifs.gcount()) { br += ifs.gcount(); if(ifs.eof()) { // Just sanity checks to make sure we've extracted the same // number of chars that were in the streambuf VERIFY( br == blen ); // Also, we should only set the failbit if we could // _extract_ no chars from the stream, i.e. the first read // returned EOF. VERIFY( ifs.fail() && ifs.gcount() == 0 ); } else if(ifs.fail()) { // delimiter not read // // either // -> extracted no characters // or // -> n - 1 characters are stored ifs.clear(ifs.rdstate() & ~std::ios::failbit); VERIFY( (ifs.gcount() == 0) || (std::wcslen(tmp) == it - 1) ); VERIFY( !(!ifs) ); continue; } else { // delimiter was read. // // -> wcslen(__s) < n - 1 // -> delimiter was seen -> gcount() > wcslen(__s) VERIFY( ifs.gcount() == static_cast<std::streamsize>(std::wcslen(tmp) + 1) ); continue; } } } int main() { test05(); return 0; }
27.47
79
0.620313
vidkidz
9986cefe6251c6c099a5a6d74636638750c6475b
1,101
cc
C++
EvtGenBase/EvtPropBreitWigner.cc
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
EvtGenBase/EvtPropBreitWigner.cc
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
EvtGenBase/EvtPropBreitWigner.cc
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
#include "Experiment/Experiment.hh" /******************************************************************************* * Project: BaBar detector at the SLAC PEP-II B-factory * Package: EvtGenBase * File: $Id: EvtPropBreitWigner.cc 427 2010-01-14 13:25:53Z stroili $ * Author: Alexei Dvoretskii, dvoretsk@slac.stanford.edu, 2001-2002 * * Copyright (C) 2002 Caltech *******************************************************************************/ #include <math.h> #include "EvtGenBase/EvtConst.hh" #include "EvtGenBase/EvtPropBreitWigner.hh" EvtPropBreitWigner::EvtPropBreitWigner(double m0, double g0) : EvtPropagator(m0,g0) {} EvtPropBreitWigner::EvtPropBreitWigner(const EvtPropBreitWigner& other) : EvtPropagator(other) {} EvtPropBreitWigner::~EvtPropBreitWigner() {} EvtAmplitude<EvtPoint1D>* EvtPropBreitWigner::clone() const { return new EvtPropBreitWigner(*this); } EvtComplex EvtPropBreitWigner::amplitude(const EvtPoint1D& x) const { double m = x.value(); EvtComplex value = sqrt(_g0/EvtConst::twoPi)/(m-_m0-EvtComplex(0.0,_g0/2.)); return value; }
26.214286
81
0.630336
brownd1978
9987109a9171472654a7e6be81e326619c361621
439
cpp
C++
src/search-a-2d-matrix.cpp
Liuchang0812/leetcode
d71f87b0035e661d0009f4382b39c4787c355f89
[ "MIT" ]
9
2015-09-09T20:28:31.000Z
2019-05-15T09:13:07.000Z
src/search-a-2d-matrix.cpp
liuchang0812/leetcode
d71f87b0035e661d0009f4382b39c4787c355f89
[ "MIT" ]
1
2015-02-25T13:10:09.000Z
2015-02-25T13:10:09.000Z
src/search-a-2d-matrix.cpp
liuchang0812/leetcode
d71f87b0035e661d0009f4382b39c4787c355f89
[ "MIT" ]
1
2016-08-31T19:14:52.000Z
2016-08-31T19:14:52.000Z
class Solution { public: bool searchMatrix(vector<vector<int> > &matrix, int target) { int posx = 0, posy = 0; int n = matrix.size(); int m = matrix[0].size(); do { if (matrix[posx][posy] == target) return true; if (posx + 1 < n && matrix[posx+1][posy] <= target) posx ++; else posy++; } while (posx < n && posy < m); return false; } };
27.4375
72
0.473804
Liuchang0812
99872690557531ff5706528de551053c5cf13fd3
32,319
hpp
C++
api/vpl/preview/video_param.hpp
alexelizarov/oneVPL
cdf7444dc971544d148c51e0d93a2df1bb55dda7
[ "MIT" ]
null
null
null
api/vpl/preview/video_param.hpp
alexelizarov/oneVPL
cdf7444dc971544d148c51e0d93a2df1bb55dda7
[ "MIT" ]
null
null
null
api/vpl/preview/video_param.hpp
alexelizarov/oneVPL
cdf7444dc971544d148c51e0d93a2df1bb55dda7
[ "MIT" ]
1
2021-06-17T07:38:18.000Z
2021-06-17T07:38:18.000Z
/*############################################################################ # Copyright Intel Corporation # # SPDX-License-Identifier: MIT ############################################################################*/ #pragma once #include <algorithm> #include <iostream> #include <utility> #include <tuple> #include "vpl/preview/detail/string_helpers.hpp" namespace oneapi { namespace vpl { #define DECLARE_MEMBER_ACCESS(father, type, name) \ /*! @brief Returns name value. */ \ /*! @return name value. */ \ type get_##name() const { \ return param_.name; \ } \ /*! @brief Sets name value. */ \ /*! @param[in] name Value. */ \ /*! @return Reference to the instance. */ \ father &set_##name(type name) { \ param_.name = name; \ return *this; \ } #define DECLARE_INNER_MEMBER_ACCESS(father, type, parent, name) \ /*! @brief Returns name value. */ \ /*! @return name value. */ \ type get_##name() const { \ return param_.parent.name; \ } \ /*! @brief Sets name value. */ \ /*! @param[in] name Value. */ \ /*! @return Reference to the instance. */ \ father &set_##name(type name) { \ param_.parent.name = name; \ return *this; \ } #define DECLARE_INNER_MEMBER_ARRAY_ACCESS(father, type, size, parent, name) \ /*! @brief Returns name value. */ \ /*! @return name value. */ \ auto get_##name() const { \ return param_.parent.name; \ } \ /*! @brief Sets name value. */ \ /*! @param[in] name Value. */ \ /*! @return Reference to the instance. */ \ father &set_##name(type name[size]) { \ std::copy(name, name + size, param_.parent.name); \ return *this; \ } /// @brief Holds general video params applicable for all kind of sessions. class video_param { public: /// @brief Constructs params and initialize them with default values. video_param() : param_() {} video_param(const video_param &param) : param_(param.param_) { clear_extension_buffers(); } video_param& operator=(const video_param& other){ param_ = other.param_; clear_extension_buffers(); return *this; } /// @brief Dtor virtual ~video_param() { param_ = {}; } public: /// @brief Returns pointer to raw data /// @return Pointer to raw data mfxVideoParam *getMfx() { return &param_; } public: DECLARE_MEMBER_ACCESS(video_param, uint32_t, AllocId) DECLARE_MEMBER_ACCESS(video_param, uint16_t, AsyncDepth) DECLARE_MEMBER_ACCESS(video_param, uint16_t, Protected) /// @brief Returns i/o memory pattern value. /// @return i/o memory pattern value. io_pattern get_IOPattern() const { return (io_pattern)param_.IOPattern; } /// @brief Sets i/o memory pattern value. /// @param[in] IOPattern i/o memory pattern. /// @return Reference to this object video_param &set_IOPattern(io_pattern IOPattern) { param_.IOPattern = (uint32_t)IOPattern; return *this; } /// @brief Attaches extension buffers to the video params /// @param[in] buffer Array of extension buffers /// @param[in] num Number of extension buffers /// @return Reference to this object video_param &set_extension_buffers(mfxExtBuffer **buffer, uint16_t num) { param_.ExtParam = buffer; param_.NumExtParam = num; return *this; } /// @brief Clear extension buffers from the video params /// @param[in] buffer Array of extension buffers /// @param[in] num Number of extension buffers /// @return Reference to this object video_param &clear_extension_buffers() { param_.ExtParam = nullptr; param_.NumExtParam = 0; return *this; } /// @brief Friend operator to print out state of the class in human readable form. /// @param[inout] out Reference to the stream to write. /// @param[in] p Referebce to the video_param instance to dump the state. /// @return Reference to the stream. friend std::ostream &operator<<(std::ostream &out, const video_param &p); protected: /// @brief Raw data mfxVideoParam param_; }; inline std::ostream &operator<<(std::ostream &out, const video_param &p) { out << "Base:" << std::endl; out << detail::space(detail::INTENT, out, "AllocId = ") << p.param_.AllocId << std::endl; out << detail::space(detail::INTENT, out, "AsyncDepth = ") << detail::NotSpecifyed0(p.param_.AsyncDepth) << std::endl; out << detail::space(detail::INTENT, out, "Protected = ") << p.param_.Protected << std::endl; out << detail::space(detail::INTENT, out, "IOPattern = ") << detail::IOPattern2String(p.param_.IOPattern) << std::endl; return out; } class codec_video_param; class vpp_video_param; /// @brief Holds general frame related params. class frame_info { public: /// @brief Default ctor. frame_info() : param_() {} /// @brief Copy ctor. /// @param[in] other another object to use as data source frame_info(const frame_info &other) { param_ = other.param_; } /// @brief Constructs object from the raw data. /// @param[in] other another object to use as data source explicit frame_info(const mfxFrameInfo &other) { param_ = other; } /// @brief Copy operator. /// @param[in] other another object to use as data source /// @returns Reference to this object frame_info &operator=(const frame_info &other) { param_ = other.param_; return *this; } DECLARE_MEMBER_ACCESS(frame_info, uint16_t, BitDepthLuma) DECLARE_MEMBER_ACCESS(frame_info, uint16_t, BitDepthChroma) DECLARE_MEMBER_ACCESS(frame_info, uint16_t, Shift) DECLARE_MEMBER_ACCESS(frame_info, mfxFrameId, FrameId) /// @brief Returns color format fourCC value. /// @return color format fourCC value. color_format_fourcc get_FourCC() const { return (color_format_fourcc)param_.FourCC; } /// @brief Sets color format fourCC value. /// @param[in] FourCC color format fourCC. /// @return Reference to this object frame_info &set_FourCC(color_format_fourcc FourCC) { param_.FourCC = (uint32_t)FourCC; return *this; } /// @todo below group valid for formats != P8 /// @brief Returns frame size. /// @return Pair of width and height. auto get_frame_size() const { return std::pair(param_.Width, param_.Height); } /// @brief Sets frame size value. /// @param[in] size pair of width and height. /// @return Reference to this object frame_info &set_frame_size(std::pair<uint32_t, uint32_t> size) { param_.Width = std::get<0>(size); param_.Height = std::get<1>(size); return *this; } /// @brief Returns ROI. /// @return Two pairs: pair of left corner and pair of size. auto get_ROI() const { return std::pair(std::pair(param_.CropX, param_.CropY), std::pair(param_.CropW, param_.CropH)); } /// @brief Sets ROI. /// @param[in] roi Two pairs: pair of left corner and pair of size. /// @return Reference to this object frame_info &set_ROI( std::pair<std::pair<uint16_t, uint16_t>, std::pair<uint16_t, uint16_t>> roi) { param_.CropX = std::get<0>(std::get<0>(roi)); param_.CropY = std::get<1>(std::get<0>(roi)); param_.CropW = std::get<0>(std::get<1>(roi)); param_.CropH = std::get<1>(std::get<1>(roi)); return *this; } /// @todo below method is valid for P8 format only DECLARE_MEMBER_ACCESS(frame_info, uint64_t, BufferSize) /// @brief Returns frame rate value. /// @return Pair of numerator and denominator. auto get_frame_rate() const { return std::pair(param_.FrameRateExtN, param_.FrameRateExtD); } /// @brief Sets frame rate value. /// @param[in] rate pair of numerator and denominator. /// @return Reference to this object frame_info &set_frame_rate(std::pair<uint32_t, uint32_t> rate) { param_.FrameRateExtN = std::get<0>(rate); param_.FrameRateExtD = std::get<1>(rate); return *this; } /// @brief Returns aspect ratio. /// @return Pair of width and height of aspect ratio. auto get_aspect_ratio() const { return std::pair(param_.AspectRatioW, param_.AspectRatioH); } /// @brief Sets aspect ratio. /// @param[in] ratio pair of width and height of aspect ratio. /// @return Reference to this object frame_info &set_aspect_ratio(std::pair<uint32_t, uint32_t> ratio) { param_.AspectRatioW = std::get<0>(ratio); param_.AspectRatioH = std::get<1>(ratio); return *this; } /// @brief Returns picture structure value. /// @return picture structure value. pic_struct get_PicStruct() const { return (pic_struct)param_.PicStruct; } /// @brief Sets picture structure value. /// @param[in] PicStruct picture structure. /// @return Reference to this object frame_info &set_PicStruct(pic_struct PicStruct) { param_.PicStruct = (uint16_t)PicStruct; return *this; } /// @brief Returns chroma format value. /// @return chroma format value. chroma_format_idc get_ChromaFormat() const { return (chroma_format_idc)param_.ChromaFormat; } /// @brief Sets chroma format value. /// @param[in] ChromaFormat chroma format. /// @return Reference to this object frame_info &set_ChromaFormat(chroma_format_idc ChromaFormat) { param_.ChromaFormat = (uint32_t)ChromaFormat; return *this; } /// @brief Friend class friend class codec_video_param; /// @brief Friend class friend class vpp_video_param; /// @brief Friend operator to print out state of the class in human readable form. /// @param[inout] out Reference to the stream to write. /// @param[in] p Reference to the codec_video_param instance to dump the state. /// @return Reference to the stream. friend std::ostream &operator<<(std::ostream &out, const codec_video_param &p); /// @brief Friend operator to print out state of the class in human readable form. /// @param[inout] out Reference to the stream to write. /// @param[in] v Reference to the vpp_video_param instance to dump the state. /// @return Reference to the stream. friend std::ostream &operator<<(std::ostream &out, const vpp_video_param &v); /// @brief Friend operator to print out state of the class in human readable form. /// @param[inout] out Reference to the stream to write. /// @param[in] f Reference to the frame_info instance to dump the state. /// @return Reference to the stream. friend std::ostream &operator<<(std::ostream &out, const frame_info &f); /// @brief Provides raw data. /// @return Raw data. mfxFrameInfo operator()() const { return param_; } protected: /// @brief Raw data mfxFrameInfo param_; }; inline std::ostream &operator<<(std::ostream &out, const frame_info &f) { out << detail::space(detail::INTENT, out, "BitDepthLuma = ") << f.param_.BitDepthLuma << std::endl; out << detail::space(detail::INTENT, out, "BitDepthChroma = ") << f.param_.BitDepthChroma << std::endl; out << detail::space(detail::INTENT, out, "Shift = ") << detail::NotSpecifyed0(f.param_.Shift) << std::endl; out << detail::space(detail::INTENT, out, "Color Format = ") << detail::FourCC2String(f.param_.FourCC) << std::endl; if (f.param_.FourCC == MFX_FOURCC_P8) { out << detail::space(detail::INTENT, out, "BufferSize = ") << f.param_.BufferSize << std::endl; } else { out << detail::space(detail::INTENT, out, "Size [W,H] = [") << f.param_.Width << "," << f.param_.Height << "]" << std::endl; out << detail::space(detail::INTENT, out, "ROI [X,Y,W,H] = [") << f.param_.CropX << "," << f.param_.CropY << "," << f.param_.CropW << "," << f.param_.CropH << "]" << std::endl; } out << detail::space(detail::INTENT, out, "FrameRate [N:D]= ") << detail::NotSpecifyed0(f.param_.FrameRateExtN) << ":" << detail::NotSpecifyed0(f.param_.FrameRateExtD) << std::endl; if (0 == f.param_.AspectRatioW && 0 == f.param_.AspectRatioH) { out << detail::space(detail::INTENT, out, "AspecRato [W,H]= [") << "Unset" << "]" << std::endl; } else { out << detail::space(detail::INTENT, out, "AspecRato [W,H]= [") << f.param_.AspectRatioW << "," << f.param_.AspectRatioH << "]" << std::endl; } out << detail::space(detail::INTENT, out, "PicStruct = ") << detail::PicStruct2String(f.param_.PicStruct) << std::endl; out << detail::space(detail::INTENT, out, "ChromaFormat = ") << detail::ChromaFormat2String(f.param_.ChromaFormat) << std::endl; return out; } /// @brief Holds general frame related params. class frame_data { public: /// @brief Default ctor. frame_data() : param_() {} /// @brief Copy ctor. /// @param[in] other another object to use as data source frame_data(const frame_data &other) { param_ = other.param_; } /// @brief Constructs object from the raw data. /// @param[in] other another object to use as data source explicit frame_data(const mfxFrameData &other) { param_ = other; } /// @brief Copy operator. /// @param[in] other another object to use as data source /// @return Reference to this object frame_data &operator=(const frame_data &other) { param_ = other.param_; return *this; } DECLARE_MEMBER_ACCESS(frame_data, uint16_t, MemType) /// @brief Returns pitch value. /// @return Pitch value. uint32_t get_pitch() const { return ((uint32_t)param_.PitchHigh << 16) | (uint32_t)(uint32_t)param_.PitchLow; } /// @brief Sets pitch value. /// @param[in] pitch Pitch. void set_pitch(uint32_t pitch) { param_.PitchHigh = (uint16_t)(pitch >> 16); param_.PitchLow = (uint16_t)(pitch & 0xFFFF); } DECLARE_MEMBER_ACCESS(frame_data, uint64_t, TimeStamp) DECLARE_MEMBER_ACCESS(frame_data, uint32_t, FrameOrder) DECLARE_MEMBER_ACCESS(frame_data, uint16_t, Locked) DECLARE_MEMBER_ACCESS(frame_data, uint16_t, Corrupted) DECLARE_MEMBER_ACCESS(frame_data, uint16_t, DataFlag) /// @brief Gets pointer for formats with 1 plane. /// @return Pointer for formats with 1 plane. auto get_plane_ptrs_1() const { return param_.R; } /// @brief Gets pointer for formats with 1 plane (BGRA). /// @return Pointer for formats with 1 plane (BGRA). auto get_plane_ptrs_1_BGRA() const { return param_.B; } /// @brief Gets pointer for formats with 2 planes. /// @return Pointers for formats with 2 planes. Pointers for planes layout is: Y, UV. auto get_plane_ptrs_2() const { return std::pair(param_.R, param_.G); } /// @brief Gets pointer for formats with 3 planes. /// @return Pointers for formats with 3 planes. Pointers for planes layout is: R, G, B or Y, U, V. auto get_plane_ptrs_3() const { return std::make_tuple(param_.R, param_.G, param_.B); } /// @brief Gets pointer for formats with 4 planes. /// @return Pointers for formats with 4 planes. Pointers for planes layout is: R, G, B, A. auto get_plane_ptrs_4() const { return std::make_tuple(param_.R, param_.G, param_.B, param_.A); } /// @brief Friend operator to print out state of the class in human readable form. /// @param[inout] out Reference to the stream to write. /// @param[in] f Reference to the frame_data instance to dump the state. /// @return Reference to the stream. friend std::ostream &operator<<(std::ostream &out, const frame_data &f); protected: /// @brief Raw data mfxFrameData param_; }; inline std::ostream &operator<<(std::ostream &out, const frame_data &f) { out << detail::space(detail::INTENT, out, "MemType = ") << detail::MemType2String(f.param_.MemType) << std::endl; out << detail::space(detail::INTENT, out, "PitchHigh = ") << f.param_.PitchHigh << std::endl; out << detail::space(detail::INTENT, out, "PitchLow = ") << f.param_.PitchLow << std::endl; out << detail::space(detail::INTENT, out, "TimeStamp = ") << detail::TimeStamp2String(static_cast<uint64_t>(f.param_.TimeStamp)) << std::endl; out << detail::space(detail::INTENT, out, "FrameOrder = ") << f.param_.FrameOrder << std::endl; out << detail::space(detail::INTENT, out, "Locked = ") << f.param_.Locked << std::endl; out << detail::space(detail::INTENT, out, "Corrupted = ") << detail::Corruption2String(f.param_.Corrupted) << std::endl; out << detail::space(detail::INTENT, out, "DataFlag = ") << detail::TimeStamp2String(f.param_.DataFlag) << std::endl; return out; } /// @brief Holds general codec-specific params applicable for any decoder and encoder. class codec_video_param : public video_param { protected: /// @brief Constructs params and initialize them with default values. codec_video_param() : video_param() {} codec_video_param(const codec_video_param &param) : video_param(param) {} codec_video_param& operator=(const codec_video_param &param){ video_param::operator=(param); return *this; } public: DECLARE_INNER_MEMBER_ACCESS(codec_video_param, uint16_t, mfx, LowPower); DECLARE_INNER_MEMBER_ACCESS(codec_video_param, uint16_t, mfx, BRCParamMultiplier); /// @brief Returns codec fourCC value. /// @return codec fourCC value. codec_format_fourcc get_CodecId() const { return (codec_format_fourcc)param_.mfx.CodecId; } /// @brief Sets codec fourCC value. /// @param[in] CodecID codec fourCC. /// @return Reference to this object codec_video_param &set_CodecId(codec_format_fourcc CodecID) { param_.mfx.CodecId = (uint32_t)CodecID; return *this; } DECLARE_INNER_MEMBER_ACCESS(codec_video_param, uint16_t, mfx, CodecProfile); DECLARE_INNER_MEMBER_ACCESS(codec_video_param, uint16_t, mfx, CodecLevel); DECLARE_INNER_MEMBER_ACCESS(codec_video_param, uint16_t, mfx, NumThread); /// @brief Returns frame_info value. /// @return frame info value. frame_info get_frame_info() const { return frame_info(param_.mfx.FrameInfo); } /// @brief Sets name value. /// @param[in] name Value. /// @return Reference to this object codec_video_param &set_frame_info(frame_info name) { param_.mfx.FrameInfo = name(); return *this; } /// Friend operator to print out state of the class in human readable form. friend std::ostream &operator<<(std::ostream &out, const codec_video_param &p); }; inline std::ostream &operator<<(std::ostream &out, const codec_video_param &p) { const video_param &v = dynamic_cast<const video_param &>(p); out << v; out << "Codec:" << std::endl; out << detail::space(detail::INTENT, out, "LowPower = ") << detail::TriState2String(p.param_.mfx.LowPower) << std::endl; out << detail::space(detail::INTENT, out, "BRCParamMultiplier = ") << p.param_.mfx.BRCParamMultiplier << std::endl; out << detail::space(detail::INTENT, out, "CodecId = ") << detail::FourCC2String(p.param_.mfx.CodecId) << std::endl; out << detail::space(detail::INTENT, out, "CodecProfile = ") << p.param_.mfx.CodecProfile << std::endl; out << detail::space(detail::INTENT, out, "CodecLevel = ") << p.param_.mfx.CodecLevel << std::endl; out << detail::space(detail::INTENT, out, "NumThread = ") << p.param_.mfx.NumThread << std::endl; out << "FrameInfo:" << std::endl; out << frame_info(p.param_.mfx.FrameInfo) << std::endl; return out; } /// @brief Holds encoder specific params. class encoder_video_param : public codec_video_param { public: /// @brief Constructs params and initialize them with default values. encoder_video_param() : codec_video_param() {} /// @brief Returns TargetUsage value. /// @return TargetUsage Target Usage value. target_usage get_TargetUsage() const { return (target_usage)param_.mfx.TargetUsage; } /// @brief Sets Target Usage value. /// @param[in] TargetUsage Target Usage. /// @return Reference to this object encoder_video_param &set_TargetUsage(target_usage TargetUsage) { param_.mfx.CodecId = (uint32_t)TargetUsage; return *this; } DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, GopPicSize); DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint32_t, mfx, GopRefDist); DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, GopOptFlag); DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, IdrInterval); /// @brief Returns rate control method value. /// @return rate control method value. rate_control_method get_RateControlMethod() const { return (rate_control_method)param_.mfx.RateControlMethod; } /// @brief Sets rate control method value. /// @param[in] RateControlMethod rate control method. /// @return Reference to this object encoder_video_param &set_RateControlMethod(rate_control_method RateControlMethod) { param_.mfx.RateControlMethod = (uint32_t)RateControlMethod; return *this; } DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, InitialDelayInKB); DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, QPI); DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, Accuracy); DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, BufferSizeInKB); DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, TargetKbps); DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, QPP); DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, ICQQuality); DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, MaxKbps); DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, QPB); DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, Convergence); DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, NumSlice); DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, NumRefFrame); DECLARE_INNER_MEMBER_ACCESS(encoder_video_param, uint16_t, mfx, EncodedOrder); /// @brief Friend operator to print out state of the class in human readable form. /// @param[inout] out Reference to the stream to write. /// @param[in] e Reference to the encoder_video_param instance to dump the state. /// @return Reference to the stream. friend std::ostream &operator<<(std::ostream &out, const encoder_video_param &e); }; inline std::ostream &operator<<(std::ostream &out, const encoder_video_param &e) { const codec_video_param &c = dynamic_cast<const codec_video_param &>(e); out << c; out << "Encoder:" << std::endl; out << detail::space(detail::INTENT, out, "TargetUsage = ") << detail::NotSpecifyed0(e.param_.mfx.TargetUsage) << std::endl; out << detail::space(detail::INTENT, out, "GopPicSize = ") << detail::NotSpecifyed0(e.param_.mfx.GopPicSize) << std::endl; out << detail::space(detail::INTENT, out, "GopRefDist = ") << detail::NotSpecifyed0(e.param_.mfx.GopRefDist) << std::endl; out << detail::space(detail::INTENT, out, "GopOptFlag = ") << detail::GopOptFlag2String(e.param_.mfx.GopOptFlag) << std::endl; out << detail::space(detail::INTENT, out, "IdrInterval = ") << e.param_.mfx.IdrInterval << std::endl; out << detail::space(detail::INTENT, out, "RateControlMethod = ") << detail::RateControlMethod2String(e.param_.mfx.RateControlMethod) << std::endl; out << detail::space(detail::INTENT, out, "InitialDelayInKB = ") << e.param_.mfx.InitialDelayInKB << std::endl; out << detail::space(detail::INTENT, out, "QPI = ") << e.param_.mfx.QPI << std::endl; out << detail::space(detail::INTENT, out, "Accuracy = ") << e.param_.mfx.Accuracy << std::endl; out << detail::space(detail::INTENT, out, "BufferSizeInKB = ") << e.param_.mfx.BufferSizeInKB << std::endl; out << detail::space(detail::INTENT, out, "TargetKbps = ") << e.param_.mfx.TargetKbps << std::endl; out << detail::space(detail::INTENT, out, "QPP = ") << e.param_.mfx.QPP << std::endl; out << detail::space(detail::INTENT, out, "ICQQuality = ") << e.param_.mfx.ICQQuality << std::endl; out << detail::space(detail::INTENT, out, "MaxKbps = ") << e.param_.mfx.MaxKbps << std::endl; out << detail::space(detail::INTENT, out, "QPB = ") << e.param_.mfx.QPB << std::endl; out << detail::space(detail::INTENT, out, "Convergence = ") << e.param_.mfx.Convergence << std::endl; out << detail::space(detail::INTENT, out, "NumSlice = ") << detail::NotSpecifyed0(e.param_.mfx.NumSlice) << std::endl; out << detail::space(detail::INTENT, out, "NumRefFrame = ") << detail::NotSpecifyed0(e.param_.mfx.NumRefFrame) << std::endl; out << detail::space(detail::INTENT, out, "EncodedOrder = ") << detail::Boolean2String(e.param_.mfx.EncodedOrder) << std::endl; return out; } /// @brief Holds decoder specific params. class decoder_video_param : public codec_video_param { public: /// @brief Constructs params and initialize them with default values. decoder_video_param() : codec_video_param() {} explicit decoder_video_param(const codec_video_param &other) : codec_video_param(other) {} DECLARE_INNER_MEMBER_ACCESS(decoder_video_param, uint16_t, mfx, DecodedOrder); DECLARE_INNER_MEMBER_ACCESS(decoder_video_param, uint16_t, mfx, ExtendedPicStruct); DECLARE_INNER_MEMBER_ACCESS(decoder_video_param, uint32_t, mfx, TimeStampCalc); DECLARE_INNER_MEMBER_ACCESS(decoder_video_param, uint16_t, mfx, SliceGroupsPresent); DECLARE_INNER_MEMBER_ACCESS(decoder_video_param, uint16_t, mfx, MaxDecFrameBuffering); DECLARE_INNER_MEMBER_ACCESS(decoder_video_param, uint16_t, mfx, EnableReallocRequest); /// @brief Friend operator to print out state of the class in human readable form. /// @param[inout] out Reference to the stream to write. /// @param[in] d Reference to the decoder_video_param instance to dump the state. /// @return Reference to the stream. friend std::ostream &operator<<(std::ostream &out, const decoder_video_param &d); }; inline std::ostream &operator<<(std::ostream &out, const decoder_video_param &d) { const codec_video_param &c = dynamic_cast<const codec_video_param &>(d); out << c; out << "Decoder:" << std::endl; out << detail::space(detail::INTENT, out, "DecodedOrder = ") << detail::Boolean2String(d.param_.mfx.DecodedOrder) << std::endl; out << detail::space(detail::INTENT, out, "ExtendedPicStruct = ") << detail::PicStruct2String(d.param_.mfx.ExtendedPicStruct) << std::endl; out << detail::space(detail::INTENT, out, "TimeStampCalc = ") << detail::TimeStampCalc2String(d.param_.mfx.TimeStampCalc) << std::endl; out << detail::space(detail::INTENT, out, "SliceGroupsPresent = ") << detail::Boolean2String(d.param_.mfx.SliceGroupsPresent) << std::endl; out << detail::space(detail::INTENT, out, "MaxDecFrameBuffering = ") << detail::NotSpecifyed0(d.param_.mfx.MaxDecFrameBuffering) << std::endl; out << detail::space(detail::INTENT, out, "EnableReallocRequest = ") << detail::TriState2String(d.param_.mfx.EnableReallocRequest) << std::endl; return out; } /// @brief Holds JPEG decoder specific params. class jpeg_decoder_video_param : public codec_video_param { public: /// @brief Constructs params and initialize them with default values. jpeg_decoder_video_param() : codec_video_param() {} DECLARE_INNER_MEMBER_ACCESS(jpeg_decoder_video_param, uint16_t, mfx, JPEGChromaFormat); DECLARE_INNER_MEMBER_ACCESS(jpeg_decoder_video_param, uint16_t, mfx, Rotation); DECLARE_INNER_MEMBER_ACCESS(jpeg_decoder_video_param, uint32_t, mfx, JPEGColorFormat); DECLARE_INNER_MEMBER_ACCESS(jpeg_decoder_video_param, uint16_t, mfx, InterleavedDec); DECLARE_INNER_MEMBER_ARRAY_ACCESS(jpeg_decoder_video_param, uint8_t, 4, mfx, SamplingFactorH); DECLARE_INNER_MEMBER_ARRAY_ACCESS(jpeg_decoder_video_param, uint8_t, 4, mfx, SamplingFactorV); }; /// @brief Holds JPEG encoder specific params. class jpeg_encoder_video_param : public codec_video_param { public: /// @brief Constructs params and initialize them with default values. jpeg_encoder_video_param() : codec_video_param() {} DECLARE_INNER_MEMBER_ACCESS(jpeg_encoder_video_param, uint16_t, mfx, Interleaved); DECLARE_INNER_MEMBER_ACCESS(jpeg_encoder_video_param, uint16_t, mfx, Quality); DECLARE_INNER_MEMBER_ACCESS(jpeg_encoder_video_param, uint32_t, mfx, RestartInterval); }; /// @brief Holds VPP specific params. class vpp_video_param : public video_param { public: /// @brief Constructs params and initialize them with default values. vpp_video_param() : video_param() {} public: /// @brief Returns frame_info in value. /// @return frame info in value. frame_info get_in_frame_info() const { return frame_info(param_.vpp.In); } /// @brief Sets name value. /// @param[in] name Value. /// @return Reference to this object vpp_video_param &set_in_frame_info(frame_info name) { param_.vpp.In = name(); return *this; } /// @brief Returns frame_info out value. /// @return frame info out value. frame_info get_out_frame_info() const { return frame_info(param_.vpp.Out); } /// @brief Sets name value. /// @param[in] name Value. /// @return Reference to this object vpp_video_param &set_out_frame_info(frame_info name) { param_.vpp.Out = name(); return *this; } /// @brief Friend operator to print out state of the class in human readable form. /// @param[inout] out Reference to the stream to write. /// @param[in] v Reference to the vpp_video_param instance to dump the state. /// @return Reference to the stream. friend std::ostream &operator<<(std::ostream &out, const vpp_video_param &v); }; inline std::ostream &operator<<(std::ostream &out, const vpp_video_param &vpp) { const video_param &v = dynamic_cast<const video_param &>(vpp); out << v; out << "Input FrameInfo:" << std::endl; out << frame_info(vpp.param_.vpp.In) << std::endl; out << "Output FrameInfo:" << std::endl; out << frame_info(vpp.param_.vpp.Out) << std::endl; return out; } } // namespace vpl } // namespace oneapi
41.328645
102
0.632569
alexelizarov
998cfa7472303ff35f565a6656b07a34a17b5074
1,827
cpp
C++
codejam/2019_1a_a.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
1
2020-04-04T14:56:12.000Z
2020-04-04T14:56:12.000Z
codejam/2019_1a_a.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
codejam/2019_1a_a.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int g[20][20]; // once you feel prob is high, random. void solve() { int n,m; cin >> n >> m; const int TRY = 100*(n+m); const int JUMP = 25; for (int _ = 0; _ < TRY; _++) { vector<int> a(n*m); iota(a.begin(), a.end(), 0); vector<pair<int, int>> res; auto take = [&](int step, int i){ int x = a[i]; g[x/m][x%m] = step; res.emplace_back(x/m, x%m); swap(a[i], a[a.size()-1]); a.pop_back(); return x; }; int k = rng() % a.size(); int now = take(0, k); for (int s = 1; s < n*m; s++) { for (int _ = 0; _ < JUMP; _++) { int k = rng() % a.size(); int nxt = a[k]; if (now%m == nxt%m) continue; if (now/m == nxt/m) continue; if (now%m + now/m == nxt%m + nxt/m) continue; if (now%m - now/m == nxt%m - nxt/m) continue; now = take(s, k); goto next_step; } goto one_fail; next_step:; } // success cout << "POSSIBLE\n"; for (auto& _: res) { cout << _.first+1 << ' ' << _.second+1 << '\n'; } //for (int i = 0; i < n; i++) { // for (int j = 0; j < m; j++) { // cout << g[i][j]+1 << ' '; // }cout << '\n'; //} return; one_fail:; } cout << "IMPOSSIBLE\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int T; cin >> T; for (int t = 1; t <= T; t++) { cout << "Case #" << t << ": "; solve(); //cout << "\n"; } fflush(stdout); }
27.268657
68
0.394636
sogapalag
998da34d0c8cdf16ac0d6f1a9b3374c032658b49
9,678
cpp
C++
bs_mesh/src/mpi_mesh_grdecl.cpp
bs-eagle/bs-eagle
b1017a4f6ac2dcafba2deafec84052ddde792671
[ "BSD-3-Clause" ]
7
2015-07-16T22:30:36.000Z
2020-02-06T10:16:42.000Z
bs_mesh/src/mpi_mesh_grdecl.cpp
bs-eagle/bs-eagle
b1017a4f6ac2dcafba2deafec84052ddde792671
[ "BSD-3-Clause" ]
null
null
null
bs_mesh/src/mpi_mesh_grdecl.cpp
bs-eagle/bs-eagle
b1017a4f6ac2dcafba2deafec84052ddde792671
[ "BSD-3-Clause" ]
3
2017-01-05T20:06:28.000Z
2021-12-20T16:19:10.000Z
/** \file mpi_mesh_grdecl.cpp \brief This file implement class for decompose main mesh among processes \author Iskhakov Ruslan \date 2008-10-14*/ #include "mpi_mesh_grdecl.h" #ifdef _MPI_MY namespace blue_sky { //! default constructor mpi_mesh_grdecl::mpi_mesh_grdecl(bs_type_ctor_param) { } mpi_mesh_grdecl::mpi_mesh_grdecl(const mpi_mesh_grdecl& src) { *this = src; } int mpi_mesh_grdecl::par_distribution() { return 0; } int mpi_mesh_grdecl::print_debug_info() { printf("numprocs=%d,myid = %d\n",numprocs,myid); fflush(0); printf("lx=%d, ly=%d, lz=%d\n",lx,ly,lz); fflush(0); printf("start_x=%d, start_y=%d, start_z=%d\n",i_start,j_start,k_start); fflush(0); printf("end_x=%d, end_y=%d, end_z=%d\n",i_end,j_end,k_end); fflush(0); return 0; } int mpi_mesh_grdecl::par_fileOpen_cube_hdf5(const char* file_name) { hid_t file_id, dset_id = 0; //file and dataset identifiers int cut_dir, n_layers; hid_t filespace = 0, memspace=0; //file and memory dataspace identifiers hsize_t dims_memory; // dataset dimensions //hyperslab selection parameters hsize_t stride[1]; hsize_t block[1]; hsize_t count[1]; hsize_t start[1] = {0}; //bounds for hyperslab selection i_start=0, j_start=0, k_start=0, i_end=0, j_end=0, k_end=0; file_id = open_file_mpi_hdf5(file_name); // open file if (file_id < 0 ) return -1; //! read initial_data int initial_data[3]; dims_memory = 3; count[0] = 3; stride[0] = 1; block[0] = 1; mpi_hdf5_read_dataset ("/grid/initial_data", file_id, dims_memory, stride, block, count, TYPE_INT, initial_data, 0, nx, ny, i_start, j_start, k_start, i_end, j_end, k_end, 1); nx = initial_data[0]; ny = initial_data[1]; nz = initial_data[2]; if (!myid) printf("nx %d, ny %d, nz %d\n", nx, ny, nz); //! make 1D-decomposition if (nx <= ny) cut_dir = CUT_DIR_X; else cut_dir = CUT_DIR_Y; //cut_dir = CUT_DIR_Z; if (!myid) printf("cut_dir %d\n", cut_dir); // at first, init as full i_start = 0; j_start = 0; k_start = 0; i_end = nx - 1; j_end = ny - 1; k_end = nz - 1; if (cut_dir == CUT_DIR_X) { i_start = (int) (myid) * ((double) nx / numprocs); i_end = (int) (myid + 1) * ((double) nx / numprocs) - 1; n_layers = nx; } else if (cut_dir == CUT_DIR_Y) { j_start = (int) myid * ((double) ny / numprocs); j_end = (int) (myid + 1) * ((double) ny / numprocs) - 1; n_layers = ny; } else if (cut_dir == CUT_DIR_Z) { k_start = (int) myid * ((double) nz / numprocs); k_end = (int) (myid + 1) * ((double) nz / numprocs) - 1; n_layers = nz; } if (n_layers < numprocs) { printf("Error: n_procs %d > nx %d!\n", numprocs, nx); return -1; } printf ("BOUND_INDEXES : [%d, %d] , [%d, %d] , [%d, %d]\n", i_start, i_end, j_start, j_end, k_start, k_end); if ((i_end < i_start) || (j_end < j_start) || (k_end < k_start)) { printf("Wrong decomp!\n"); return -1; } /* //! make 1D-decomposition if (nx <= ny) cut_dir = CUT_DIR_X; else cut_dir = CUT_DIR_Y; if (!myid) {printf("cut_dir %d\n", cut_dir); fflush(0);} // at first, init as full i_start = 0; j_start = 0; k_start = 0; i_end = nx - 1; j_end = ny - 1; k_end = nz - 1; if (cut_dir == CUT_DIR_X) { i_start = (int) myid * ((double) nx / numprocs); i_end = (int) (myid + 1) * ((double) nx / numprocs) - 1; n_layers = nx; } else if (cut_dir == CUT_DIR_Y) { j_start = (int) myid * ((double) ny / numprocs); j_end = (int) (myid + 1) * ((double) ny / numprocs) - 1; n_layers = ny; } // else if (cut_dir == CUT_DIR_Z) { k_start = (int) mpi_rank * ((double) nz / mpi_size); k_end = (int) (mpi_rank + 1) * ((double) nz / mpi_size) - 1; n_layers = nz; } if (n_layers < numprocs) { printf("Error: n_procs %d > nx %d!\n", numprocs, nx); return -1; } printf ("BOUND_INDEXES : [%d, %d] , [%d, %d] , [%d, %d]\n", i_start, i_end, j_start, j_end, k_start, k_end); //share between process by equal part of active cells (begin) #ifdef _WIN32 mesh_grdecl::fileOpen_cube_hdf5(file_name,i_start, j_start, k_start, i_end, j_end,k_end); //#elif UNIX //hdf5-parallel only in UNIX-like system //put misha direction he #endif printf("mesh_zcorn_number = %d\n",zcorn_array.size()); return true; */ return 0; } void mpi_mesh_grdecl::set_mpi_comm(MPI_Comm acomm) { mpi_comm = acomm; MPI_Comm_size(mpi_comm, &numprocs); MPI_Comm_rank(mpi_comm, &myid); } int mpi_mesh_grdecl::open_file_mpi_hdf5(const char *file_name) { //Set up file access property list with parallel I/O access hid_t plist_id = H5Pcreate(H5P_FILE_ACCESS); // Creates a new property as an instance of a property li_startt class. //Each process of the MPI communicator creates an access template and sets i_end up wi_endh MPI parallel access information. Thi_start i_start2 done wi_endh the H5Pcreate call to obtain the file access property li_startt and the H5Pset_fapl_mpio call to set up parallel I/O access. H5Pset_fapl_mpio(plist_id, mpi_comm, mpi_info); // Open a new file and release property list identifier hid_t file_id = H5Fopen (file_name, H5F_ACC_RDONLY, H5P_DEFAULT); // H5F_ACC_RDONLY - Allow read-only access to file. if (file_id < 0) { printf("Error: Can't open file %s!\n", file_name); return -1; } H5Pclose (plist_id); return file_id; } int mpi_mesh_grdecl::mpi_hdf5_read_dataset (const char* dset_title, hid_t file_id, hsize_t dims_memory, hsize_t *stride, hsize_t *block, hsize_t *count, const int datatype, int *data_int, float *data_float, const int nx, const int ny, const int i_start2, const int j_start, const int k_start, const int i_end, const int j_end, const int k_end, int mode) { herr_t status; int rank = 1; // read 1-dimensional array hid_t filespace, memspace; // file and memory dataspace identifiers int k; float *data_float_ptr = data_float; int *data_int_ptr = data_int; hid_t dset_id; hsize_t start[1]; if (datatype != TYPE_FLOAT && datatype != TYPE_INT) { printf("Error: wrong type!\n"); return -1; } dset_id = open_dataset(rank, &dims_memory, file_id, dset_title); if (dset_id < 0) return -1; //cant' open dataset! filespace = H5Dget_space(dset_id); memspace = H5Screate_simple(rank, &dims_memory, NULL); hid_t plist_id = H5Pcreate(H5P_DATASET_XFER); H5Pset_dxpl_mpio(plist_id, H5FD_MPIO_INDEPENDENT); if (mode) // for 1 pass read { if (mode == 1)// initial_data start[0] = 0; else if (mode == 2)// coord start[0] = (i_start + j_start * (nx + 1)) * 6; H5Sselect_hyperslab(filespace, H5S_SELECT_SET, start, stride, count, block); if (datatype == TYPE_FLOAT) status = H5Dread(dset_id, H5T_NATIVE_FLOAT, memspace, filespace, plist_id, data_float); else if (datatype == TYPE_INT) status = H5Dread(dset_id, H5T_NATIVE_INT, memspace, filespace, plist_id, data_int); } else // multi pass read { for (k = 0; k < k_end - k_start + 1; k++) { start[0] = i_start + j_start * nx + (k + k_start) * nx * ny; H5Sselect_hyperslab(filespace, H5S_SELECT_SET, start, stride, count, block); if (datatype == TYPE_FLOAT) status = H5Dread(dset_id, H5T_NATIVE_FLOAT, memspace, filespace, plist_id, data_float_ptr); else if (datatype == TYPE_INT) status = H5Dread(dset_id, H5T_NATIVE_INT, memspace, filespace, plist_id, data_int_ptr); if (status < 0) { printf("Error: Dataset read error!\n"); return -1; } data_int_ptr = data_int_ptr + dims_memory; data_float_ptr = data_float_ptr + dims_memory; } } //release resources H5Dclose(dset_id); H5Sclose(filespace); H5Sclose(memspace); H5Pclose(plist_id); return 0; } int mpi_mesh_grdecl::open_dataset(int rank, hsize_t dims_memory[], hid_t file_id, const char* dset_title) { hid_t filespace = H5Screate_simple(rank, dims_memory, NULL); //Open the dataset and close filespace hid_t dset_id = H5Dopen(file_id, dset_title); if (dset_id < 0)// check if file has been opened { printf("Error: Can't open dataset %s!\n", dset_title); return -1; } H5Sclose(filespace); return dset_id; } BLUE_SKY_TYPE_IMPL_T_EXT(1 , (mpi_mesh_grdecl<base_strategy_fif>) , 1, (objbase), "mpi_mesh_grdecl<float, int,float>", "MPI mesh_grdecl class", "MPI mesh ecllipse class", false); BLUE_SKY_TYPE_IMPL_T_EXT(1 , (mpi_mesh_grdecl<base_strategy_did>) , 1, (objbase), "mpi_mesh_grdecl<double, int,double>", "MPI mesh ecllipse class", "MPI mesh ecllipse class", false); BLUE_SKY_TYPE_STD_CREATE_T_DEF(mpi_mesh_grdecl, (class)); BLUE_SKY_TYPE_STD_COPY_T_DEF(mpi_mesh_grdecl, (class)); }; //namespace blue_sky #endif //_MPI_MY
30.920128
285
0.599917
bs-eagle
998e041b4883ee11c6ee796bd4f582a31b7c617e
278
hpp
C++
src/core/game-states/cinematic-state.hpp
guillaume-haerinck/imac-tower-defense
365a32642ea0d3ad8b2b7d63347d585c44d9f670
[ "MIT" ]
44
2019-06-06T21:33:30.000Z
2022-03-26T06:18:23.000Z
src/core/game-states/cinematic-state.hpp
guillaume-haerinck/imac-tower-defense
365a32642ea0d3ad8b2b7d63347d585c44d9f670
[ "MIT" ]
1
2019-09-27T12:04:52.000Z
2019-09-29T13:30:42.000Z
src/core/game-states/cinematic-state.hpp
guillaume-haerinck/imac-tower-defense
365a32642ea0d3ad8b2b7d63347d585c44d9f670
[ "MIT" ]
8
2019-07-26T16:44:26.000Z
2020-11-24T17:56:18.000Z
#pragma once #include "i-game-state.hpp" class Game; // Forward declaration class CinematicState : public IGameState { public: CinematicState(Game& game); virtual ~CinematicState(); void enter() override; void update(float deltatime) override; void exit() override; };
17.375
42
0.741007
guillaume-haerinck
998ef2272096e1f01bcdf770cbf9fbc0511898f0
15,127
cpp
C++
GameEngine/CoreEngine/CoreEngine/src/ShadingOperation.cpp
mettaursp/SuddenlyGames
e2ff1c2771d4ca54824650e4f1a33a527536ca61
[ "Apache-2.0" ]
1
2021-01-17T13:05:20.000Z
2021-01-17T13:05:20.000Z
GameEngine/CoreEngine/CoreEngine/src/ShadingOperation.cpp
suddenly-games/SuddenlyGames
e2ff1c2771d4ca54824650e4f1a33a527536ca61
[ "Apache-2.0" ]
null
null
null
GameEngine/CoreEngine/CoreEngine/src/ShadingOperation.cpp
suddenly-games/SuddenlyGames
e2ff1c2771d4ca54824650e4f1a33a527536ca61
[ "Apache-2.0" ]
null
null
null
#include "ShadingOperation.h" extern "C" { #include <math.h> } #include "Graphics.h" #include "Textures.h" #include "Light.h" #include "FrameBuffer.h" namespace GraphicsEngine { void ShadingOperation::Initialize() { auto shadowCamera = Engine::Create<Camera>(); auto shadowScene = Engine::Create<Scene>(); shadowCamera->SetParent(This.lock()); shadowScene->SetParent(This.lock()); ShadowCamera = shadowCamera; ShadowScene = shadowScene; shadowScene->CurrentCamera = ShadowCamera; int width = 2048; int height = 2048; auto rightMap = FrameBuffer::Create(width, height, Textures::Create(width, height, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_FLOAT, GL_R32F, GL_RED)); auto leftMap = FrameBuffer::Create(width, height, Textures::Create(width, height, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_FLOAT, GL_R32F, GL_RED)); auto topMap = FrameBuffer::Create(width, height, Textures::Create(width, height, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_FLOAT, GL_R32F, GL_RED)); auto bottomMap = FrameBuffer::Create(width, height, Textures::Create(width, height, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_FLOAT, GL_R32F, GL_RED)); auto frontMap = FrameBuffer::Create(width, height, Textures::Create(width, height, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_FLOAT, GL_R32F, GL_RED)); auto backMap = FrameBuffer::Create(width, height, Textures::Create(width, height, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_FLOAT, GL_R32F, GL_RED)); auto parent = This.lock(); rightMap->SetParent(parent); leftMap->SetParent(parent); topMap->SetParent(parent); bottomMap->SetParent(parent); frontMap->SetParent(parent); backMap->SetParent(parent); RightMap = rightMap; LeftMap = leftMap; TopMap = topMap; BottomMap = bottomMap; FrontMap = frontMap; BackMap = backMap; } void ShadingOperation::Update(float) { if (CurrentScene.expired()) return; CurrentScene.lock()->RefreshWatches(); } void ShadingOperation::Render() { if (CurrentCamera.expired() || CurrentScene.expired()) return; glEnable(GL_BLEND); CheckGLErrors(); glEnable(GL_DEPTH_TEST); CheckGLErrors(); glDepthMask(GL_FALSE); CheckGLErrors(); glBlendFunc(GL_SRC_ALPHA, GL_ONE); CheckGLErrors(); Programs::PhongOutput->Use(); Programs::PhongOutput->SetInputBuffer(SceneBuffer.lock()); Programs::PhongOutput->resolution.Set(Resolution); Programs::PhongOutput->shadowsEnabled.Set(false); Programs::PhongOutput->shadowLeft.Set(LeftMap.lock()->GetTexture(), 8); Programs::PhongOutput->shadowRight.Set(RightMap.lock()->GetTexture(), 9); Programs::PhongOutput->shadowFront.Set(FrontMap.lock()->GetTexture(), 10); Programs::PhongOutput->shadowBack.Set(BackMap.lock()->GetTexture(), 11); Programs::PhongOutput->shadowTop.Set(TopMap.lock()->GetTexture(), 12); Programs::PhongOutput->shadowBottom.Set(BottomMap.lock()->GetTexture(), 13); auto currentCamera = CurrentCamera.lock(); if (GlobalLight.expired()) { Programs::PhongOutput->lightBrightness.Set(1); Programs::PhongOutput->attenuation.Set(1, 0, 0); Programs::PhongOutput->lightPosition.Set(0, 0, 0); Programs::PhongOutput->lightDirection.Set(-currentCamera->GetTransformationInverse().UpVector()); Programs::PhongOutput->lightDiffuse.Set(0.5f, 0.5f, 0.5f); Programs::PhongOutput->lightSpecular.Set(1, 1, 1); Programs::PhongOutput->lightAmbient.Set(0.5f, 0.5f, 0.5f); Programs::PhongOutput->spotlightAngles.Set(0, 0); Programs::PhongOutput->spotlightFalloff.Set(0); Programs::PhongOutput->lightType.Set(0); } else { auto globalLight = GlobalLight.lock(); Programs::PhongOutput->lightBrightness.Set(globalLight->Brightness); Programs::PhongOutput->attenuation.Set(globalLight->Attenuation); Programs::PhongOutput->lightPosition.Set(globalLight->Position); Programs::PhongOutput->lightDirection.Set(currentCamera->GetTransformationInverse() * -globalLight->Direction); Programs::PhongOutput->lightDiffuse.Set(globalLight->Diffuse); Programs::PhongOutput->lightSpecular.Set(globalLight->Specular); Programs::PhongOutput->lightAmbient.Set(globalLight->Ambient); Programs::PhongOutput->spotlightAngles.Set(globalLight->InnerRadius, globalLight->OuterRadius); Programs::PhongOutput->spotlightFalloff.Set(globalLight->SpotlightFalloff); Programs::PhongOutput->lightType.Set(globalLight->Type); } Programs::PhongOutput->transform.Set(Matrix3().Scale(1, 1, 1)); Programs::PhongOutput->CoreMeshes.Square->Draw(); glEnable(GL_STENCIL_TEST); CheckGLErrors(); glDepthFunc(GL_GEQUAL); CheckGLErrors(); auto currentScene = CurrentScene.lock(); for (int i = 0; i < currentScene->GetLights(); ++i) { std::shared_ptr<Light> light = currentScene->GetLight(i); if (!light->Enabled || light->AreShadowsEnabled()) continue; if (currentCamera->GetFrustum().Intersects(light->GetBoundingBox()) == Enum::IntersectionType::Outside) continue; Draw(light); } glBlendFunc(GL_SRC_ALPHA, GL_ONE); CheckGLErrors(); for (int i = 0; i < currentScene->GetLights(); ++i) { std::shared_ptr<Light> light = currentScene->GetLight(i); if (!light->Enabled || !light->AreShadowsEnabled()) continue; if (currentCamera->GetFrustum().Intersects(light->GetBoundingBox()) == Enum::IntersectionType::Outside) continue; glDisable(GL_BLEND); CheckGLErrors(); glDepthMask(GL_TRUE); CheckGLErrors(); glDisable(GL_STENCIL_TEST); CheckGLErrors(); glEnable(GL_DEPTH_TEST); CheckGLErrors(); glDepthFunc(GL_LEQUAL); CheckGLErrors(); glCullFace(GL_FRONT); CheckGLErrors(); Programs::DepthTrace->Use(); DrawShadows(light, i); glCullFace(GL_BACK); CheckGLErrors(); glEnable(GL_BLEND); CheckGLErrors(); glEnable(GL_DEPTH_TEST); CheckGLErrors(); glDepthMask(GL_FALSE); CheckGLErrors(); glEnable(GL_STENCIL_TEST); CheckGLErrors(); glDepthFunc(GL_GEQUAL); CheckGLErrors(); Programs::PhongOutput->Use(); LightBuffer.lock()->DrawTo(); Draw(light); } glDepthMask(GL_TRUE); CheckGLErrors(); glDisable(GL_STENCIL_TEST); CheckGLErrors(); //glEnable(GL_DEPTH_TEST); CheckGLErrors(); glDepthFunc(GL_LEQUAL); CheckGLErrors(); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); CheckGLErrors(); } void ShadingOperation::Draw(const std::shared_ptr<Light>& light) { auto currentCamera = CurrentCamera.lock(); Programs::PhongOutput->lightBrightness.Set(light->Brightness); Programs::PhongOutput->cameraTransform.Set(light->GetShadowMapInverseTransformation() * currentCamera->GetTransformation()); Programs::PhongOutput->attenuation.Set(light->Attenuation); Programs::PhongOutput->lightPosition.Set(currentCamera->GetTransformationInverse() * light->Position); Programs::PhongOutput->lightDirection.Set(currentCamera->GetTransformationInverse() * -light->Direction); Programs::PhongOutput->lightDiffuse.Set(light->Diffuse); Programs::PhongOutput->lightSpecular.Set(light->Specular); Programs::PhongOutput->lightAmbient.Set(light->Ambient); Programs::PhongOutput->spotlightAngles.Set(cosf(light->InnerRadius), cosf(light->OuterRadius)); Programs::PhongOutput->spotlightFalloff.Set(light->SpotlightFalloff); Programs::PhongOutput->lightType.Set(light->Type); const Mesh* mesh = nullptr; const Mesh* stencilMesh = nullptr; float lightRadius = 0; Matrix3 transform; if (light->Type == Enum::LightType::Directional) { transform = Matrix3().Scale(1, 1, 1); Programs::PhongOutput->shadowsEnabled.Set(false); Programs::PhongOutput->transform.Set(transform); mesh = Programs::PhongOutput->CoreMeshes.Square; stencilMesh = Programs::PhongOutputStencil->CoreMeshes.Square; } else { Dimensions shadowMapSize = light->GetShadowMapSize(); Programs::PhongOutput->shadowsEnabled.Set(light->AreShadowsEnabled()); Programs::PhongOutput->shadowDebugView.Set(light->ShadowDebugView); if (light->AreShadowsEnabled()) Programs::PhongOutput->shadowScale.Set(float(shadowMapSize.Width) / 2048, float(shadowMapSize.Height) / 2048); lightRadius = light->GetRadius(); Programs::PhongOutput->maxRadius.Set(lightRadius); lightRadius *= 1.1f; if (light->Type == Enum::LightType::Spot && light->OuterRadius <= PI / 2 + 0.001f) { Matrix3 rotation; float direction = 1; if (light->Direction == Vector3(0, -1, 0)) rotation = Matrix3().RotatePitch(PI);//direction = -1; else if (light->Direction != Vector3(0, 1, 0)) rotation = Matrix3().RotateYaw(atan2f(light->Direction.X, -light->Direction.Z)) * Matrix3().RotatePitch(-acosf(light->Direction.Y)); transform = currentCamera->GetProjection() * Matrix3().Translate(light->Position) * Matrix3().Scale(-lightRadius, lightRadius, lightRadius) * rotation; Programs::PhongOutput->transform.Set(transform); if (light->OuterRadius <= PI / 4 + 0.001f) { mesh = Programs::PhongOutput->CoreMeshes.Cone; stencilMesh = Programs::PhongOutputStencil->CoreMeshes.Cone; } else { mesh = Programs::PhongOutput->CoreMeshes.HalfBoundingVolume; stencilMesh = Programs::PhongOutputStencil->CoreMeshes.HalfBoundingVolume; } } else { transform = currentCamera->GetProjectionMatrix() * Matrix3().Translate( currentCamera->GetTransformationInverse() * light->Position ) * Matrix3().Scale(-lightRadius, lightRadius, lightRadius); Programs::PhongOutput->transform.Set(transform); mesh = Programs::PhongOutput->CoreMeshes.BoundingVolume; stencilMesh = Programs::PhongOutputStencil->CoreMeshes.BoundingVolume; } } glStencilMask(0xFF); CheckGLErrors(); glStencilFunc(GL_ALWAYS, 1, 0xFF); CheckGLErrors(); glStencilOp(GL_ZERO, GL_ZERO, GL_REPLACE); CheckGLErrors(); Programs::PhongOutputStencil->Use(); Programs::PhongOutputStencil->transform.Set(transform); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); CheckGLErrors(); stencilMesh->Draw(); glStencilFunc(GL_EQUAL, 1, 0xFF); CheckGLErrors(); glStencilOp(GL_ZERO, GL_ZERO, GL_REPLACE); CheckGLErrors(); Programs::PhongOutputStencil->transform.Set(transform * Matrix3().Scale(-1, 1, 1)); glDepthFunc(GL_LEQUAL); CheckGLErrors(); stencilMesh->Draw(); Programs::PhongOutput->Use(); glStencilMask(0x00); CheckGLErrors(); glStencilFunc(GL_EQUAL, 1, 0xFF); CheckGLErrors(); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); CheckGLErrors(); glDepthFunc(GL_GEQUAL); CheckGLErrors(); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); CheckGLErrors(); mesh->Draw(); } void ShadingOperation::DrawShadows(const std::shared_ptr<Light>& light, int index) { float lightRadius = light->GetRadius() * 1.1f; Matrix3 backPanelTransform = Matrix3(0, 0, -lightRadius + 0.01f) * Matrix3().Scale(lightRadius, lightRadius, 0); //Matrix3 base = Matrix3().ExtractRotation(CurrentCamera->GetTransformation(), light->Position); Dimensions bufferSize = light->GetShadowMapSize(); const AabbTree& watch = CurrentScene.lock()->GetWatched(index); auto shadowCamera = ShadowCamera.lock(); shadowCamera->SetProperties(0.5f * PI, 1, 1e-1f, lightRadius); if (light->Type != Enum::LightType::Spot || light->OuterRadius > PI / 4 + 0.001f) { RightMap.lock()->DrawTo(0, 0, bufferSize.Width, bufferSize.Height); Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shadowCamera->SetTransformation(light->GetShadowMapTransformation() * Matrix3(Vector3(), Vector3(0, 0, 1), Vector3(0, 1, 0), Vector3(-1, 0, 0))); Scene::Draw(watch, false, shadowCamera); Programs::DepthTrace->transform.Set(shadowCamera->GetProjectionMatrix() * backPanelTransform); Programs::DepthTrace->objectTransform.Set(shadowCamera->GetTransformation() * backPanelTransform); Programs::DepthTrace->CoreMeshes.Cube->Draw(); } if (light->Type != Enum::LightType::Spot || light->OuterRadius > PI / 4 + 0.001f) { LeftMap.lock()->DrawTo(0, 0, bufferSize.Width, bufferSize.Height); Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shadowCamera->SetTransformation(light->GetShadowMapTransformation() * Matrix3(Vector3(), Vector3(0, 0, -1), Vector3(0, 1, 0), Vector3(1, 0, 0))); Scene::Draw(watch, false, shadowCamera); Programs::DepthTrace->transform.Set(shadowCamera->GetProjectionMatrix() * backPanelTransform); Programs::DepthTrace->objectTransform.Set(shadowCamera->GetTransformation() * backPanelTransform); Programs::DepthTrace->CoreMeshes.Cube->Draw(); } if (light->Type != Enum::LightType::Spot || light->OuterRadius > PI / 4 + 0.001f) { FrontMap.lock()->DrawTo(0, 0, bufferSize.Width, bufferSize.Height); Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shadowCamera->SetTransformation(light->GetShadowMapTransformation() * Matrix3(Vector3(), Vector3(1, 0, 0), Vector3(0, 1, 0), Vector3(0, 0, 1))); Scene::Draw(watch, false, shadowCamera); Programs::DepthTrace->transform.Set(shadowCamera->GetProjectionMatrix() * backPanelTransform); Programs::DepthTrace->objectTransform.Set(shadowCamera->GetTransformation() * backPanelTransform); Programs::DepthTrace->CoreMeshes.Cube->Draw(); } if (light->Type != Enum::LightType::Spot || light->OuterRadius > PI / 4 + 0.001f) { BackMap.lock()->DrawTo(0, 0, bufferSize.Width, bufferSize.Height); Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shadowCamera->SetTransformation(light->GetShadowMapTransformation() * Matrix3(Vector3(), Vector3(-1, 0, 0), Vector3(0, 1, 0), Vector3(0, 0, -1))); Scene::Draw(watch, false, shadowCamera); Programs::DepthTrace->transform.Set(shadowCamera->GetProjectionMatrix() * backPanelTransform); Programs::DepthTrace->objectTransform.Set(shadowCamera->GetTransformation() * backPanelTransform); Programs::DepthTrace->CoreMeshes.Cube->Draw(); } //if (light->Type != Enum::LightType::Spot || light->OuterRadius <= PI / 4 + 0.001f) { TopMap.lock()->DrawTo(0, 0, bufferSize.Width, bufferSize.Height); Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shadowCamera->SetTransformation(light->GetShadowMapTransformation() * Matrix3(Vector3(), Vector3(1, 0, 0), Vector3(0, 0, 1), Vector3(0, -1, 0))); Scene::Draw(watch, false, shadowCamera); Programs::DepthTrace->transform.Set(shadowCamera->GetProjectionMatrix() * backPanelTransform); Programs::DepthTrace->objectTransform.Set(shadowCamera->GetTransformation() * backPanelTransform); Programs::DepthTrace->CoreMeshes.Cube->Draw(); } if (light->Type != Enum::LightType::Spot || light->OuterRadius > 3 * PI / 4 + 0.001f) { BottomMap.lock()->DrawTo(0, 0, bufferSize.Width, bufferSize.Height); Graphics::ClearScreen(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shadowCamera->SetTransformation(light->GetShadowMapTransformation() * Matrix3(Vector3(), Vector3(1, 0, 0), Vector3(0, 0, -1), Vector3(0, 1, 0))); Scene::Draw(watch, false, shadowCamera); Programs::DepthTrace->transform.Set(shadowCamera->GetProjectionMatrix() * backPanelTransform); Programs::DepthTrace->objectTransform.Set(shadowCamera->GetTransformation() * backPanelTransform); Programs::DepthTrace->CoreMeshes.Cube->Draw(); } } }
36.627119
155
0.728763
mettaursp
998f59d8ff627006e43f0c806056bc361bbe6e56
33,660
hpp
C++
Tests/wrappers.hpp
adam-morrison/Comparing_Filters
8287cae15a64cffd5e5885516dc547f7b01621a7
[ "Apache-2.0" ]
null
null
null
Tests/wrappers.hpp
adam-morrison/Comparing_Filters
8287cae15a64cffd5e5885516dc547f7b01621a7
[ "Apache-2.0" ]
null
null
null
Tests/wrappers.hpp
adam-morrison/Comparing_Filters
8287cae15a64cffd5e5885516dc547f7b01621a7
[ "Apache-2.0" ]
null
null
null
/* Taken from * https://github.com/FastFilter/fastfilter_cpp * */ #ifndef FILTERS_WRAPPERS_HPP #define FILTERS_WRAPPERS_HPP #include <climits> #include <iomanip> #include <iostream> #include <map> #include <random> #include <set> #include <stdexcept> #include <stdio.h> #include <vector> #include "../Bloom_Filter/bloom.hpp" #include "../PD_Filter/dict.hpp" #include "TPD_Filter/T_dict.hpp" //#include "../TPD_Filter/pd512_wrapper.hpp" //#include "dict512.hpp" #include "TPD_Filter/dict512.hpp" #include "d512/att_d512.hpp" #include "d512/twoChoicer.hpp" // #include "../cuckoo/cuckoofilter.h" #include "../cuckoofilter/src/cuckoofilter.h" //#include "../morton/compressed_cuckoo_filter.h" #include "../Bloom_Filter/simd-block-fixed-fpp.h" #include "../Bloom_Filter/simd-block.h" #include "../morton/morton_sample_configs.h" //#include "xorfilter.h" //#include "../xorfilter/xorfilter_2.h" //#include "../xorfilter/xorfilter_2n.h" //#include "../xorfilter/xorfilter_10bit.h" //#include "../xorfilter/xorfilter_10_666bit.h" //#include "../xorfilter/xorfilter_13bit.h" //#include "../xorfilter/xorfilter_plus.h" //#include "../xorfilter/xorfilter_singleheader.h" //#include "../xorfilter/xor_fuse_filter.h" #define CONTAIN_ATTRIBUTES __attribute__((noinline)) enum filter_id { BF, CF, CF_ss, MF, SIMD, pd_id, tpd_id, d512, att_d512_id, twoChoicer_id }; template <typename Table> struct FilterAPI { }; template <typename ItemType, size_t bits_per_item, template <size_t> class TableType, typename HashFamily> struct FilterAPI<cuckoofilter::CuckooFilter<ItemType, bits_per_item, TableType, HashFamily>> { using Table = cuckoofilter::CuckooFilter<ItemType, bits_per_item, TableType, HashFamily>; static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); } static void Add(uint64_t key, Table *table) { if (table->Add(key) != cuckoofilter::Ok) { std::cerr << "Cuckoo filter is too full. Inertion of the element (" << key << ") failed.\n"; get_info(table); throw logic_error("The filter is too small to hold all of the elements"); } } static void AddAll(const vector<ItemType> keys, const size_t start, const size_t end, Table *table) { for (int i = start; i < end; ++i) { if (table->Add(keys[i]) != cuckoofilter::Ok) { std::cerr << "Cuckoo filter is too full. Inertion of the element (" << keys[i] << ") failed.\n"; get_info(table); throw logic_error("The filter is too small to hold all of the elements"); } } } static void AddAll(const std::vector<ItemType> keys, Table *table) { for (int i = 0; i < keys.size(); ++i) { if (table->Add(keys[i]) != cuckoofilter::Ok) { std::cerr << "Cuckoo filter is too full. Inertion of the element (" << keys[i] << ") failed.\n"; // std::cerr << "Load before insertion is: " << ; get_info(table); throw logic_error("The filter is too small to hold all of the elements"); } } // table->AddAll(keys, 0, keys.size()); } static void Remove(uint64_t key, Table *table) { table->Delete(key); } CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) { return (0 == table->Contain(key)); } static string get_name(Table *table) { auto ss = table->Info(); std::string temp = "PackedHashtable"; if (ss.find(temp)!= std::string::npos){ return "CF-ss"; } return "Cuckoo"; } static auto get_info(const Table *table) ->std::stringstream { std::string state = table->Info(); std::stringstream ss; ss << state; return ss; // std::cout << state << std::endl; } static auto get_ID(Table *table) -> filter_id { return CF; } }; template < class TableType, typename spareItemType, typename itemType> struct FilterAPI<att_d512<TableType, spareItemType, itemType>> { using Table = att_d512<TableType, spareItemType, itemType, 8, 51, 50>; // using Table = dict512<TableType, spareItemType, itemType>; static Table ConstructFromAddCount(size_t add_count) { return Table(add_count, .955, .5); } static void Add(itemType key, Table *table) { // assert(table->case_validate()); table->insert(key); // assert(table->case_validate()); } static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table) { for (int i = start; i < end; ++i) { table->insert(keys[i]); } } static void AddAll(const std::vector<itemType> keys, Table *table) { for (int i = 0; i < keys.size(); ++i) { table->insert(keys[i]); } } static void Remove(itemType key, Table *table) { // std::cout << "Remove in Wrapper!" << std::endl; table->remove(key); } CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table) { return table->lookup(key); } static string get_name(Table *table) { return table->get_name(); } static auto get_info(Table *table) ->std::stringstream { return table->get_extended_info(); } static auto get_ID(Table *table) -> filter_id { return att_d512_id; } }; template <typename itemType> struct FilterAPI<twoChoicer<itemType>> { using Table = twoChoicer<itemType, 8, 51, 50>; // using Table = dict512<TableType, spareItemType, itemType>; static Table ConstructFromAddCount(size_t add_count) { return Table(add_count, .9, .5); } static void Add(itemType key, Table *table) { // assert(table->case_validate()); table->insert(key); // assert(table->case_validate()); } static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table) { for (int i = start; i < end; ++i) { table->insert(keys[i]); } } static void AddAll(const std::vector<itemType> keys, Table *table) { for (int i = 0; i < keys.size(); ++i) { table->insert(keys[i]); } } static void Remove(itemType key, Table *table) { table->remove(key); } CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table) { return table->lookup(key); } static string get_name(Table *table) { return table->get_name(); } static auto get_info(Table *table) ->std::stringstream { return table->get_extended_info(); } static auto get_ID(Table *table) -> filter_id { return twoChoicer_id; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// template <typename ItemType, size_t bits_per_item, bool branchless, typename HashFamily> struct FilterAPI<bloomfilter::bloom<ItemType, bits_per_item, branchless, HashFamily>> { using Table = bloomfilter::bloom<ItemType, bits_per_item, branchless, HashFamily>; static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); } static void Add(uint64_t key, Table *table) { table->Add(key); } static void AddAll(const std::vector<ItemType> keys, const size_t start, const size_t end, Table *table) { table->AddAll(keys, start, end); } static void AddAll(const std::vector<ItemType> keys, Table *table) { table->AddAll(keys, 0, keys.size()); } static void Remove(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } static string get_name(Table *table) { return "Bloom"; } static auto get_info(Table *table) ->std::stringstream { assert(false); std::stringstream ss; return ss; } CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) { return (0 == table->Contain(key)); } static auto get_ID(Table *table) -> filter_id { return BF; } }; template <> struct FilterAPI<SimdBlockFilter<>> { using Table = SimdBlockFilter<>; static Table ConstructFromAddCount(size_t add_count) { Table ans(ceil(log2(add_count * 8.0 / CHAR_BIT))); return ans; } static void Add(uint64_t key, Table *table) { table->Add(key); } static void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end, Table *table) { for (int i = start; i < end; ++i) { table->Add(keys[i]); } } static void AddAll(const std::vector<uint64_t> keys, Table *table) { AddAll(keys, 0, keys.size(), table); /* for (int i = 0; i < keys.size(); ++i) { table->Add(keys[i]); }*/ } static bool Contain(uint64_t key, const Table *table) { return table->Find(key); } static void Remove(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } static string get_name(Table *table) { return "SimdBlockFilter"; } static auto get_info(Table *table) ->std::stringstream { assert(false); std::stringstream ss; return ss; } static auto get_ID(Table *table) -> filter_id { return SIMD; } }; class MortonFilter { using mf7_6 = CompressedCuckoo::Morton7_6; mf7_6 *filter; size_t size; public: MortonFilter(const size_t size) { // filter = new CompressedCuckoo::Morton3_8((size_t) (size / 0.95) + 64); // filter = new CompressedCuckoo::Morton3_8((size_t) (2.1 * size) + 64); filter = new mf7_6((size_t)(size / 0.95) + 64); this->size = size; } ~MortonFilter() { delete filter; } void Add(uint64_t key) { filter->insert(key); } void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end) { size_t size = end - start; ::std::vector<uint64_t> k(size); ::std::vector<bool> status(size); for (size_t i = start; i < end; i++) { k[i - start] = keys[i]; } // TODO return value and status is ignored currently filter->insert_many(k, status, size); } void AddAll(const std::vector<uint64_t> keys) { AddAll(keys, 0, keys.size()); } inline bool Contain(uint64_t &item) { return filter->likely_contains(item); }; size_t SizeInBytes() const { // according to morton_sample_configs.h: // Morton3_8 - 3-slot buckets with 8-bit fingerprints: 11.7 bits/item // (load factor = 0.95) // so in theory we could just hardcode the size here, // and don't measure it // return (size_t)((size * 11.7) / 8); return filter->SizeInBytes(); } }; template <> struct FilterAPI<MortonFilter> { using Table = MortonFilter; static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); } static void Add(uint64_t key, Table *table) { table->Add(key); } static void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end, Table *table) { for (int i = start; i < end; ++i) { table->Add(keys[i]); } // table->AddAll(keys, start, end); } static void AddAll(const std::vector<uint64_t> keys, Table *table) { for (unsigned long key : keys) { table->Add(key); } } static void Remove(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, Table *table) { return table->Contain(key); } static string get_name(Table *table) { return "Morton"; } static auto get_info(Table *table) ->std::stringstream { assert(false); std::stringstream ss; return ss; } static auto get_ID(Table *table) -> filter_id { return MF; } }; //template<typename itemType, size_t bits_per_item,brancless, Hashfam> //template<typename itemType, size_t bits_per_item, bool branchless, typename HashFamily> //template<typename itemType, template<typename> class TableType> //template<template<typename> class TableType, typename itemType, size_t bits_per_item> //struct FilterAPI<dict<PD, TableType, itemType, bits_per_item>> { template <template <typename> class TableType, typename itemType, typename spareItemType> struct FilterAPI<dict<PD, TableType, itemType, spareItemType>> { // using Table = dict<PD, hash_table<uint32_t>, itemType, bits_per_item, branchless, HashFamily>; using Table = dict<PD, TableType, itemType, spareItemType>; static Table ConstructFromAddCount(size_t add_count, size_t bits_per_item) { return Table(add_count, bits_per_item, .95, .5); } static void Add(itemType key, Table *table) { table->insert(key); } static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table) { for (int i = start; i < end; ++i) { table->insert(keys[i]); } } static void AddAll(const std::vector<itemType> keys, Table *table) { for (int i = 0; i < keys.size(); ++i) { table->insert(keys[i]); } } static void Remove(itemType key, Table *table) { table->remove(key); } CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table) { return table->lookup(key); } static string get_name(Table *table) { return "PD"; } static auto get_info(Table *table) ->std::stringstream { assert(false); std::stringstream ss; return ss; } static auto get_ID(Table *table) -> filter_id { return pd_id; } }; /* template<class temp_PD, template<typename> class TableType, typename itemType, typename spareItemType> struct FilterAPI<dict<temp_PD, TableType, itemType, spareItemType>> { using Table = dict<temp_PD, TableType, itemType, spareItemType>; static Table ConstructFromAddCount(size_t add_count, size_t bits_per_item) { return Table(add_count, bits_per_item, .95, .5); } static void Add(itemType key, Table *table) { table->insert(key); } static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table) { for (int i = start; i < end; ++i) { table->insert(keys[i]); } } static void AddAll(const std::vector<itemType> keys, Table *table) { for (int i = 0; i < keys.size(); ++i) { table->insert(keys[i]); } } static void Remove(itemType key, Table *table) { table->remove(key); } CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table) { return table->lookup(key); } static string get_name() { // string res = "TPD"; // res += sizeof() return "TPD"; } }; */ /* template<template<typename, size_t, size_t> class temp_PD, typename slot_type, size_t bits_per_item, size_t max_capacity, typename itemType, template<typename> class TableType, typename spareItemType> struct FilterAPI<dict<temp_PD<slot_type, bits_per_item, max_capacity>, TableType, itemType, spareItemType>> { // using Table = dict<PD, hash_table<uint32_t>, itemType, bits_per_item, branchless, HashFamily>; using Table = dict<TPD_name::TPD<slot_type, bits_per_item, max_capacity>, TableType, itemType, spareItemType>; static Table ConstructFromAddCount(size_t add_count) { return Table(add_count, bits_per_item, .95, .5, max_capacity); } static void Add(itemType key, Table *table) { table->insert(key); } static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table) { for (int i = start; i < end; ++i) { table->insert(keys[i]); } } static void AddAll(const std::vector<itemType> keys, Table *table) { for (int i = 0; i < keys.size(); ++i) { table->insert(keys[i]); } } static void Remove(itemType key, Table *table) { table->remove(key); } CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table) { return table->lookup(key); } static string get_name() { // string res = "TPD"; // res += sizeof() return "TPD"; } }; */ //<slot_type, bits_per_item, max_capacity> template < class temp_PD, typename slot_type, size_t bits_per_item, size_t max_capacity, typename itemType, class TableType, typename spareItemType> struct FilterAPI< T_dict<temp_PD, slot_type, bits_per_item, max_capacity, TableType, spareItemType, itemType>> { // using Table = T_dict<TPD_name::TPD<slot_type,bits_per_item, max_capacity>, slot_type, bits_per_item, max_capacity, TableType, spareItemType, itemType>; using Table = T_dict<temp_PD, slot_type, bits_per_item, max_capacity, TableType, spareItemType, itemType>; static Table ConstructFromAddCount(size_t add_count) { return Table(add_count, .95, .5); } static void Add(itemType key, Table *table) { table->insert(key); } static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table) { for (int i = start; i < end; ++i) { table->insert(keys[i]); } } static void AddAll(const std::vector<itemType> keys, Table *table) { for (int i = 0; i < keys.size(); ++i) { table->insert(keys[i]); } } static void Remove(itemType key, Table *table) { table->remove(key); } CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table) { return table->lookup(key); } static string get_name(Table *table) { return table->get_name(); } static auto get_info(Table *table) ->std::stringstream { table->get_dynamic_info(); std::stringstream ss; return ss; } static auto get_ID(Table *table) -> filter_id { return tpd_id; } }; template < class TableType, typename spareItemType, typename itemType> struct FilterAPI< dict512<TableType, spareItemType, itemType>> { using Table = dict512<TableType, spareItemType, itemType, 8, 51, 50>; // using Table = dict512<TableType, spareItemType, itemType>; static Table ConstructFromAddCount(size_t add_count) { return Table(add_count, 1, .5); } static void Add(itemType key, Table *table) { table->insert(key); } static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table) { for (int i = start; i < end; ++i) { table->insert(keys[i]); } } static void AddAll(const std::vector<itemType> keys, Table *table) { for (int i = 0; i < keys.size(); ++i) { table->insert(keys[i]); } } static void Remove(itemType key, Table *table) { table->remove(key); } CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table) { return table->lookup(key); } static string get_name(Table *table) { return table->get_name(); } static auto get_info(Table *table) ->std::stringstream { table->get_dynamic_info(); std::stringstream ss; return ss; } static auto get_ID(Table *table) -> filter_id { return d512; } }; /**Before changing first argument in T_dict template argument*/ /* template< template<typename, size_t, size_t> class temp_PD, typename slot_type, size_t bits_per_item, size_t max_capacity, typename itemType, template<typename> class TableType, typename spareItemType > struct FilterAPI< T_dict<temp_PD, slot_type, bits_per_item, max_capacity, TableType, spareItemType, itemType> > { using Table = T_dict<TPD_name::TPD, slot_type, bits_per_item, max_capacity, TableType, spareItemType, itemType>; static Table ConstructFromAddCount(size_t add_count) { return Table(add_count, .95, .5); } static void Add(itemType key, Table *table) { table->insert(key); } static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, Table *table) { for (int i = start; i < end; ++i) { table->insert(keys[i]); } } static void AddAll(const std::vector<itemType> keys, Table *table) { for (int i = 0; i < keys.size(); ++i) { table->insert(keys[i]); } } static void Remove(itemType key, Table *table) { table->remove(key); } CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table) { return table->lookup(key); } static string get_name() { // string res = "TPD"; // res += sizeof() return "T_dict"; } }; */ /* #ifdef __AVX2__ template<typename HashFamily> struct FilterAPI<SimdBlockFilter<HashFamily>> { using Table = SimdBlockFilter<HashFamily>; static Table ConstructFromAddCount(size_t add_count) { Table ans(ceil(log2(add_count * 8.0 / CHAR_BIT))); return ans; } static void Add(uint64_t key, Table *table) { table->Add(key); } static void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end, Table *table) { throw std::runtime_error("Unsupported"); } static void AddAll(const vector<uint64_t> keys, Table *table) { throw std::runtime_error("Unsupported"); } static void Remove(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) { return table->Find(key); } static string get_name() { return "SimdBlockFilter"; } }; template<typename HashFamily> struct FilterAPI<SimdBlockFilterFixed64<HashFamily>> { using Table = SimdBlockFilterFixed64<HashFamily>; static Table ConstructFromAddCount(size_t add_count) { Table ans(ceil(add_count * 8.0 / CHAR_BIT)); return ans; } static void Add(uint64_t key, Table *table) { table->Add(key); } static void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end, Table *table) { throw std::runtime_error("Unsupported"); } static void AddAll(const vector<uint64_t> keys, Table *table) { throw std::runtime_error("Unsupported"); } static void Remove(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) { return table->Find(key); } static string get_name() { return "SimdBlockFilterFixed64"; } }; */ /* template <typename HashFamily> struct FilterAPI<SimdBlockFilterFixed16<HashFamily>> { using Table = SimdBlockFilterFixed16<HashFamily>; static Table ConstructFromAddCount(size_t add_count) { Table ans(ceil(add_count * 8.0 / CHAR_BIT)); return ans; } static void Add(uint64_t key, Table* table) { table->Add(key); } static void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end, Table* table) { throw std::runtime_error("Unsupported"); } static void Remove(uint64_t key, Table * table) { throw std::runtime_error("Unsupported"); } CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table * table) { return table->Find(key); } }; */ /* template<typename HashFamily> struct FilterAPI<SimdBlockFilterFixed<HashFamily>> { using Table = SimdBlockFilterFixed<HashFamily>; static Table ConstructFromAddCount(size_t add_count) { Table ans(ceil(add_count * 8.0 / CHAR_BIT)); return ans; } static void Add(uint64_t key, Table *table) { table->Add(key); } static void AddAll(const vector<uint64_t> keys, const size_t start, const size_t end, Table *table) { table->AddAll(keys, start, end); } static void AddAll(const vector<uint64_t> keys, Table *table) { table->AddAll(keys, 0, keys.size()); } static void Remove(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) { return table->Find(key); } static string get_name() { return "SimdBlockFilterFixed"; } }; #endif */ /* template<typename itemType> struct FilterAPI<set<itemType>> { // using Table = dict<PD, hash_table<uint32_t>, itemType, bits_per_item, branchless, HashFamily>; // using Table = set<itemType>; static set<itemType> ConstructFromAddCount(size_t add_count) { return set<itemType>(); } static void Add(itemType key, set<itemType> *table) { table->insert(key); } static void AddAll(const std::vector<itemType> keys, const size_t start, const size_t end, set<itemType> *table) { table->insert(keys); // for (int i = start; i < end; ++i) { // table->insert(keys[i]); // } } static void AddAll(const std::vector<itemType> keys, Table *table) { table->insert(keys); // for (int i = 0; i < keys.size(); ++i) { // table->insert(keys[i]); // } } static void Remove(itemType key, Table *table) { table->remove(key); } CONTAIN_ATTRIBUTES static bool Contain(itemType key, const Table *table) { return table->lookup(key); } static string get_name() { return "std::set"; } }; */ //typedef struct FilterAPI<bloomfilter::bloom<uint64_t, 8, false, HashUtil>> filter_api_bloom; /* template<typename itemType, typename FingerprintType, typename HashFamily> struct FilterAPI<xorfilter::XorFilter<itemType, FingerprintType, HashFamily>> { using Table = xorfilter::XorFilter<itemType, FingerprintType, HashFamily>; static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); } static void Add(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) { table->AddAll(keys, start, end); } static void AddAll(const std::vector<itemType> keys, Table *table) { table->AddAll(keys, 0, keys.size()); } static void Remove(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) { return (0 == table->Contain(key)); } }; template<typename itemType, typename FingerprintType, typename FingerprintStorageType, typename HashFamily> struct FilterAPI<xorfilter2::XorFilter2<itemType, FingerprintType, FingerprintStorageType, HashFamily>> { using Table = xorfilter2::XorFilter2<itemType, FingerprintType, FingerprintStorageType, HashFamily>; static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); } static void Add(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) { table->AddAll(keys, start, end); } static void AddAll(const std::vector<itemType> keys, Table *table) { table->AddAll(keys, 0, keys.size()); } static void Remove(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) { return (0 == table->Contain(key)); } }; template<typename itemType, typename HashFamily> struct FilterAPI<xorfilter::XorFilter10<itemType, HashFamily>> { using Table = xorfilter::XorFilter10<itemType, HashFamily>; static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); } static void Add(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) { table->AddAll(keys, start, end); } static void AddAll(const std::vector<itemType> keys, Table *table) { table->AddAll(keys, 0, keys.size()); } static void Remove(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) { return (0 == table->Contain(key)); } }; template<typename itemType, typename HashFamily> struct FilterAPI<xorfilter::XorFilter13<itemType, HashFamily>> { using Table = xorfilter::XorFilter13<itemType, HashFamily>; static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); } static void Add(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) { table->AddAll(keys, start, end); } static void AddAll(const std::vector<itemType> keys, Table *table) { table->AddAll(keys, 0, keys.size()); } static void Remove(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) { return (0 == table->Contain(key)); } }; template<typename itemType, typename HashFamily> struct FilterAPI<xorfilter::XorFilter10_666<itemType, HashFamily>> { using Table = xorfilter::XorFilter10_666<itemType, HashFamily>; static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); } static void Add(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) { table->AddAll(keys, start, end); } static void AddAll(const std::vector<itemType> keys, Table *table) { table->AddAll(keys, 0, keys.size()); } static void Remove(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) { return (0 == table->Contain(key)); } }; template<typename itemType, typename FingerprintType, typename FingerprintStorageType, typename HashFamily> struct FilterAPI<xorfilter2n::XorFilter2n<itemType, FingerprintType, FingerprintStorageType, HashFamily>> { using Table = xorfilter2n::XorFilter2n<itemType, FingerprintType, FingerprintStorageType, HashFamily>; static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); } static void Add(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) { table->AddAll(keys, start, end); } static void AddAll(const std::vector<itemType> keys, Table *table) { table->AddAll(keys, 0, keys.size()); } static void Remove(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) { return (0 == table->Contain(key)); } }; template<typename itemType, typename FingerprintType, typename HashFamily> struct FilterAPI<xorfilter_plus::XorFilterPlus<itemType, FingerprintType, HashFamily>> { using Table = xorfilter_plus::XorFilterPlus<itemType, FingerprintType, HashFamily>; static Table ConstructFromAddCount(size_t add_count) { return Table(add_count); } static void Add(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } static void AddAll(const vector<itemType> keys, const size_t start, const size_t end, Table *table) { table->AddAll(keys, start, end); } static void AddAll(const std::vector<itemType> keys, Table *table) { table->AddAll(keys, 0, keys.size()); } static void Remove(uint64_t key, Table *table) { throw std::runtime_error("Unsupported"); } CONTAIN_ATTRIBUTES static bool Contain(uint64_t key, const Table *table) { return (0 == table->Contain(key)); } }; */ #endif //FILTERS_WRAPPERS_HPP
27.29927
161
0.618865
adam-morrison
99910c69455a3106a0c62249ca7f102d28dbefb7
26,359
cpp
C++
be/test/formats/parquet/parquet_schema_test.cpp
stephen-shelby/starrocks
67932670efddbc8c56e2aaf5d3758724dcb44b0a
[ "Zlib", "PSF-2.0", "BSD-2-Clause", "Apache-2.0", "ECL-2.0", "BSD-3-Clause-Clear" ]
1
2022-03-08T09:13:32.000Z
2022-03-08T09:13:32.000Z
be/test/formats/parquet/parquet_schema_test.cpp
stephen-shelby/starrocks
67932670efddbc8c56e2aaf5d3758724dcb44b0a
[ "Zlib", "PSF-2.0", "BSD-2-Clause", "Apache-2.0", "ECL-2.0", "BSD-3-Clause-Clear" ]
null
null
null
be/test/formats/parquet/parquet_schema_test.cpp
stephen-shelby/starrocks
67932670efddbc8c56e2aaf5d3758724dcb44b0a
[ "Zlib", "PSF-2.0", "BSD-2-Clause", "Apache-2.0", "ECL-2.0", "BSD-3-Clause-Clear" ]
null
null
null
// This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited. #include <gtest/gtest.h> #include <iostream> #include <vector> #include "formats/parquet/schema.h" namespace starrocks::parquet { class ParquetSchemaTest : public testing::Test { public: ParquetSchemaTest() {} virtual ~ParquetSchemaTest() {} }; TEST_F(ParquetSchemaTest, EmptySchema) { std::vector<tparquet::SchemaElement> t_schemas; SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_FALSE(st.ok()); } TEST_F(ParquetSchemaTest, OnlyRoot) { std::vector<tparquet::SchemaElement> t_schemas; t_schemas.resize(1); { auto& t_schema = t_schemas[0]; t_schema.name = "hive-schema"; t_schema.__set_num_children(0); } SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_FALSE(st.ok()); } TEST_F(ParquetSchemaTest, OnlyLeafType) { std::vector<tparquet::SchemaElement> t_schemas; t_schemas.resize(3); // Root { auto& t_schema = t_schemas[0]; t_schema.name = "hive-schema"; t_schema.__set_num_children(2); } // INT32 { auto& t_schema = t_schemas[1]; t_schema.__set_type(tparquet::Type::INT32); t_schema.name = "col1"; t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); } // BYTE_ARRAY { auto& t_schema = t_schemas[2]; t_schema.__set_type(tparquet::Type::BYTE_ARRAY); t_schema.name = "col2"; t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REQUIRED); } SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_TRUE(st.ok()); { auto idx = desc.get_column_index("col1"); ASSERT_EQ(0, idx); auto field = desc.get_stored_column_by_idx(0); ASSERT_STREQ("col1", field->name.c_str()); ASSERT_EQ(0, field->physical_column_index); ASSERT_EQ(1, field->max_def_level()); ASSERT_EQ(0, field->max_rep_level()); ASSERT_EQ(true, field->is_nullable); } { auto idx = desc.get_column_index("col2"); ASSERT_EQ(1, idx); auto field = desc.get_stored_column_by_idx(1); ASSERT_STREQ("col2", field->name.c_str()); ASSERT_EQ(1, field->physical_column_index); ASSERT_EQ(0, field->max_def_level()); ASSERT_EQ(0, field->max_rep_level()); ASSERT_EQ(false, field->is_nullable); } LOG(INFO) << desc.debug_string(); } TEST_F(ParquetSchemaTest, NestedType) { std::vector<tparquet::SchemaElement> t_schemas; t_schemas.resize(8); // Root { auto& t_schema = t_schemas[0]; t_schema.name = "hive-schema"; t_schema.__set_num_children(3); } // col1: INT32 { auto& t_schema = t_schemas[1]; t_schema.__set_type(tparquet::Type::INT32); t_schema.name = "col1"; t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); } // col2: LIST(BYTE_ARRAY) { int idx_base = 2; // level-1 { auto& t_schema = t_schemas[idx_base + 0]; t_schema.name = "col2"; t_schema.__set_num_children(1); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); t_schema.__set_converted_type(tparquet::ConvertedType::LIST); } // level-2 { auto& t_schema = t_schemas[idx_base + 1]; t_schema.name = "list"; t_schema.__set_num_children(1); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REPEATED); } // level-3 { auto& t_schema = t_schemas[idx_base + 2]; t_schema.__set_type(tparquet::Type::BYTE_ARRAY); t_schema.name = "element"; t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); } } // col3: STRUCT{ a: INT32, b: BYTE_ARRAY} { int idx_base = 5; { auto& t_schema = t_schemas[idx_base + 0]; t_schema.name = "col3"; t_schema.__set_num_children(2); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); } // field-a { auto& t_schema = t_schemas[idx_base + 1]; t_schema.__set_type(tparquet::Type::INT32); t_schema.name = "a"; t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); } // field-b { auto& t_schema = t_schemas[idx_base + 2]; t_schema.__set_type(tparquet::Type::BYTE_ARRAY); t_schema.name = "b"; t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REQUIRED); } } SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_TRUE(st.ok()); // Check col2 { auto field = desc.resolve_by_name("col2"); ASSERT_EQ(TYPE_ARRAY, field->type.type); ASSERT_EQ(2, field->max_def_level()); ASSERT_EQ(1, field->max_rep_level()); ASSERT_EQ(0, field->level_info.immediate_repeated_ancestor_def_level); ASSERT_EQ(true, field->is_nullable); auto child = &field->children[0]; ASSERT_EQ(3, child->max_def_level()); ASSERT_EQ(1, child->max_rep_level()); ASSERT_EQ(2, child->level_info.immediate_repeated_ancestor_def_level); ASSERT_EQ(1, child->physical_column_index); ASSERT_EQ(true, child->is_nullable); } // Check col3 { auto field = desc.resolve_by_name("col3"); ASSERT_EQ(TYPE_STRUCT, field->type.type); ASSERT_EQ(1, field->max_def_level()); ASSERT_EQ(0, field->max_rep_level()); ASSERT_EQ(true, field->is_nullable); auto child_a = &field->children[0]; ASSERT_EQ(2, child_a->max_def_level()); ASSERT_EQ(0, child_a->max_rep_level()); ASSERT_EQ(2, child_a->physical_column_index); ASSERT_EQ(true, child_a->is_nullable); auto child_b = &field->children[1]; ASSERT_EQ(1, child_b->max_def_level()); ASSERT_EQ(0, child_b->max_rep_level()); ASSERT_EQ(3, child_b->physical_column_index); ASSERT_EQ(false, child_b->is_nullable); } LOG(INFO) << desc.debug_string(); } TEST_F(ParquetSchemaTest, InvalidCase1) { std::vector<tparquet::SchemaElement> t_schemas; t_schemas.resize(3); // Root { auto& t_schema = t_schemas[0]; t_schema.name = "hive-schema"; t_schema.__set_num_children(1); } // INT32 { auto& t_schema = t_schemas[1]; t_schema.__set_type(tparquet::Type::INT32); t_schema.name = "col1"; t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); } // BYTE_ARRAY { auto& t_schema = t_schemas[2]; t_schema.__set_type(tparquet::Type::BYTE_ARRAY); t_schema.name = "col2"; t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REQUIRED); } SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_FALSE(st.ok()); } TEST_F(ParquetSchemaTest, InvalidCase2) { std::vector<tparquet::SchemaElement> t_schemas; t_schemas.resize(3); // Root { auto& t_schema = t_schemas[0]; t_schema.name = "hive-schema"; t_schema.__set_num_children(3); } // INT32 { auto& t_schema = t_schemas[1]; t_schema.__set_type(tparquet::Type::INT32); t_schema.name = "col1"; t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); } // BYTE_ARRAY { auto& t_schema = t_schemas[2]; t_schema.__set_type(tparquet::Type::BYTE_ARRAY); t_schema.name = "col2"; t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REQUIRED); } SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_FALSE(st.ok()); } TEST_F(ParquetSchemaTest, InvalidList1) { std::vector<tparquet::SchemaElement> t_schemas; t_schemas.resize(2); // Root { auto& t_schema = t_schemas[0]; t_schema.name = "hive-schema"; t_schema.__set_num_children(1); } // Col1: Array { int idx_base = 1; // level-1 { auto& t_schema = t_schemas[idx_base + 0]; t_schema.name = "col2"; t_schema.__set_num_children(1); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REPEATED); t_schema.__set_converted_type(tparquet::ConvertedType::LIST); } } SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_FALSE(st.ok()); } TEST_F(ParquetSchemaTest, InvalidList2) { std::vector<tparquet::SchemaElement> t_schemas; t_schemas.resize(2); // Root { auto& t_schema = t_schemas[0]; t_schema.name = "hive-schema"; t_schema.__set_num_children(1); } // Col1: Array { int idx_base = 1; // level-1 { auto& t_schema = t_schemas[idx_base + 0]; t_schema.name = "col2"; t_schema.__set_num_children(2); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); t_schema.__set_converted_type(tparquet::ConvertedType::LIST); } } SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_FALSE(st.ok()); } TEST_F(ParquetSchemaTest, InvalidList3) { std::vector<tparquet::SchemaElement> t_schemas; t_schemas.resize(2); // Root { auto& t_schema = t_schemas[0]; t_schema.name = "hive-schema"; t_schema.__set_num_children(1); } // Col1: Array { int idx_base = 1; // level-1 { auto& t_schema = t_schemas[idx_base + 0]; t_schema.name = "col2"; t_schema.__set_num_children(1); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); t_schema.__set_converted_type(tparquet::ConvertedType::LIST); } } SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_FALSE(st.ok()); } TEST_F(ParquetSchemaTest, InvalidList4) { std::vector<tparquet::SchemaElement> t_schemas; t_schemas.resize(3); // Root { auto& t_schema = t_schemas[0]; t_schema.name = "hive-schema"; t_schema.__set_num_children(1); } // Col1: Array { int idx_base = 1; // level-1 { auto& t_schema = t_schemas[idx_base + 0]; t_schema.name = "col2"; t_schema.__set_num_children(1); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); t_schema.__set_converted_type(tparquet::ConvertedType::LIST); } // level-2 { auto& t_schema = t_schemas[idx_base + 1]; t_schema.name = "list"; t_schema.__set_num_children(1); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); } } SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_FALSE(st.ok()); } TEST_F(ParquetSchemaTest, SimpleArray) { std::vector<tparquet::SchemaElement> t_schemas; t_schemas.resize(2); // Root { auto& t_schema = t_schemas[0]; t_schema.name = "hive-schema"; t_schema.__set_num_children(1); } // Col1: Array { int idx_base = 1; // level-1 { auto& t_schema = t_schemas[idx_base + 0]; t_schema.name = "col2"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REPEATED); } } SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_TRUE(st.ok()); { auto field = desc.resolve_by_name("col2"); ASSERT_EQ(TYPE_ARRAY, field->type.type); ASSERT_EQ(1, field->max_def_level()); ASSERT_EQ(1, field->max_rep_level()); ASSERT_EQ(false, field->is_nullable); ASSERT_EQ(0, field->level_info.immediate_repeated_ancestor_def_level); auto child = &field->children[0]; ASSERT_EQ(1, child->max_def_level()); ASSERT_EQ(1, child->max_rep_level()); ASSERT_EQ(false, child->is_nullable); ASSERT_EQ(1, child->level_info.immediate_repeated_ancestor_def_level); ASSERT_EQ(0, child->physical_column_index); } } TEST_F(ParquetSchemaTest, TwoLevelArray) { std::vector<tparquet::SchemaElement> t_schemas; t_schemas.resize(3); // Root { auto& t_schema = t_schemas[0]; t_schema.name = "hive-schema"; t_schema.__set_num_children(1); } // Col1: Array { int idx_base = 1; // level-1 { auto& t_schema = t_schemas[idx_base + 0]; t_schema.name = "col2"; t_schema.__set_num_children(1); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); t_schema.__set_converted_type(tparquet::ConvertedType::LIST); } // level-2 { auto& t_schema = t_schemas[idx_base + 1]; t_schema.name = "field"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REPEATED); } } SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_TRUE(st.ok()); { auto field = desc.resolve_by_name("col2"); ASSERT_EQ(TYPE_ARRAY, field->type.type); ASSERT_EQ(2, field->max_def_level()); ASSERT_EQ(1, field->max_rep_level()); ASSERT_EQ(true, field->is_nullable); ASSERT_EQ(0, field->level_info.immediate_repeated_ancestor_def_level); auto child = &field->children[0]; ASSERT_EQ(2, child->max_def_level()); ASSERT_EQ(1, child->max_rep_level()); ASSERT_EQ(false, child->is_nullable); ASSERT_EQ(2, child->level_info.immediate_repeated_ancestor_def_level); ASSERT_EQ(0, child->physical_column_index); } } TEST_F(ParquetSchemaTest, MapNormal) { std::vector<tparquet::SchemaElement> t_schemas; t_schemas.resize(5); // Root { auto& t_schema = t_schemas[0]; t_schema.name = "hive-schema"; t_schema.__set_num_children(1); } // Col1: Array { int idx_base = 1; // level-1 { auto& t_schema = t_schemas[idx_base + 0]; t_schema.name = "col2"; t_schema.__set_num_children(1); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); t_schema.__set_converted_type(tparquet::ConvertedType::MAP); } // level-2 { auto& t_schema = t_schemas[idx_base + 1]; t_schema.name = "key_value"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(2); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REPEATED); } // key { auto& t_schema = t_schemas[idx_base + 2]; t_schema.name = "key"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REQUIRED); } // value { auto& t_schema = t_schemas[idx_base + 3]; t_schema.name = "value"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); } } SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_TRUE(st.ok()); { auto field = desc.resolve_by_name("col2"); ASSERT_EQ(TYPE_MAP, field->type.type); ASSERT_EQ(2, field->max_def_level()); ASSERT_EQ(1, field->max_rep_level()); ASSERT_EQ(true, field->is_nullable); ASSERT_EQ(0, field->level_info.immediate_repeated_ancestor_def_level); auto key_value = &field->children[0]; ASSERT_EQ(2, key_value->max_def_level()); ASSERT_EQ(1, key_value->max_rep_level()); ASSERT_EQ(false, key_value->is_nullable); ASSERT_EQ(2, key_value->level_info.immediate_repeated_ancestor_def_level); } } TEST_F(ParquetSchemaTest, InvalidMap1) { std::vector<tparquet::SchemaElement> t_schemas; t_schemas.resize(3); // Root { auto& t_schema = t_schemas[0]; t_schema.name = "hive-schema"; t_schema.__set_num_children(1); } // Col1: Array { int idx_base = 1; // level-1 { auto& t_schema = t_schemas[idx_base + 0]; t_schema.name = "col2"; t_schema.__set_num_children(1); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); t_schema.__set_converted_type(tparquet::ConvertedType::MAP); } // level-2 { auto& t_schema = t_schemas[idx_base + 1]; t_schema.name = "key_value"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(2); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REPEATED); } } SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_FALSE(st.ok()); } TEST_F(ParquetSchemaTest, InvalidMap2) { std::vector<tparquet::SchemaElement> t_schemas; t_schemas.resize(4); // Root { auto& t_schema = t_schemas[0]; t_schema.name = "hive-schema"; t_schema.__set_num_children(1); } // Col1: Array { int idx_base = 1; // level-1 { auto& t_schema = t_schemas[idx_base + 0]; t_schema.name = "col2"; t_schema.__set_num_children(2); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); t_schema.__set_converted_type(tparquet::ConvertedType::MAP); } // key { auto& t_schema = t_schemas[idx_base + 1]; t_schema.name = "key"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REQUIRED); } // value { auto& t_schema = t_schemas[idx_base + 2]; t_schema.name = "value"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); } } SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_FALSE(st.ok()); } TEST_F(ParquetSchemaTest, InvalidMap3) { std::vector<tparquet::SchemaElement> t_schemas; t_schemas.resize(4); // Root { auto& t_schema = t_schemas[0]; t_schema.name = "hive-schema"; t_schema.__set_num_children(1); } // Col1: Array { int idx_base = 1; // level-1 { auto& t_schema = t_schemas[idx_base + 0]; t_schema.name = "col2"; t_schema.__set_num_children(2); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REPEATED); t_schema.__set_converted_type(tparquet::ConvertedType::MAP); } // key { auto& t_schema = t_schemas[idx_base + 1]; t_schema.name = "key"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REQUIRED); } // value { auto& t_schema = t_schemas[idx_base + 2]; t_schema.name = "value"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); } } SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_FALSE(st.ok()); } TEST_F(ParquetSchemaTest, InvalidMap4) { std::vector<tparquet::SchemaElement> t_schemas; t_schemas.resize(5); // Root { auto& t_schema = t_schemas[0]; t_schema.name = "hive-schema"; t_schema.__set_num_children(1); } // Col1: Array { int idx_base = 1; // level-1 { auto& t_schema = t_schemas[idx_base + 0]; t_schema.name = "col2"; t_schema.__set_num_children(1); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); t_schema.__set_converted_type(tparquet::ConvertedType::MAP); } // level-2 { auto& t_schema = t_schemas[idx_base + 1]; t_schema.name = "key_value"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(2); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); } // key { auto& t_schema = t_schemas[idx_base + 2]; t_schema.name = "key"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REQUIRED); } // value { auto& t_schema = t_schemas[idx_base + 3]; t_schema.name = "value"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); } } SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_FALSE(st.ok()); } TEST_F(ParquetSchemaTest, InvalidMap5) { std::vector<tparquet::SchemaElement> t_schemas; t_schemas.resize(5); // Root { auto& t_schema = t_schemas[0]; t_schema.name = "hive-schema"; t_schema.__set_num_children(1); } // Col1: Array { int idx_base = 1; // level-1 { auto& t_schema = t_schemas[idx_base + 0]; t_schema.name = "col2"; t_schema.__set_num_children(1); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); t_schema.__set_converted_type(tparquet::ConvertedType::MAP); } // level-2 { auto& t_schema = t_schemas[idx_base + 1]; t_schema.name = "key_value"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(2); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REPEATED); } // key { auto& t_schema = t_schemas[idx_base + 2]; t_schema.name = "key"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); } // value { auto& t_schema = t_schemas[idx_base + 3]; t_schema.name = "value"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); } } SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_FALSE(st.ok()); } TEST_F(ParquetSchemaTest, InvalidMap6) { std::vector<tparquet::SchemaElement> t_schemas; t_schemas.resize(6); // Root { auto& t_schema = t_schemas[0]; t_schema.name = "hive-schema"; t_schema.__set_num_children(1); } // Col1: Array { int idx_base = 1; // level-1 { auto& t_schema = t_schemas[idx_base + 0]; t_schema.name = "col2"; t_schema.__set_num_children(1); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); t_schema.__set_converted_type(tparquet::ConvertedType::MAP); } // level-2 { auto& t_schema = t_schemas[idx_base + 1]; t_schema.name = "key_value"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(3); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::REPEATED); } // key { auto& t_schema = t_schemas[idx_base + 2]; t_schema.name = "key"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); } // value { auto& t_schema = t_schemas[idx_base + 3]; t_schema.name = "value"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); } // value3 { auto& t_schema = t_schemas[idx_base + 4]; t_schema.name = "value2"; t_schema.__set_type(tparquet::Type::INT32); t_schema.__set_num_children(0); t_schema.__set_repetition_type(tparquet::FieldRepetitionType::OPTIONAL); } } SchemaDescriptor desc; auto st = desc.from_thrift(t_schemas); ASSERT_FALSE(st.ok()); } } // namespace starrocks::parquet
30.193585
98
0.600668
stephen-shelby
99914571040c060f7a15a05e545a1a5ba8dfd966
6,763
cpp
C++
tests/auto/plugins/WebQueryTest/tst_webquery.cpp
Skycoder42/QtAutoUpdater
5df052961cec1e47acfdb770599ad9669d720f80
[ "BSD-3-Clause" ]
594
2015-12-31T12:39:23.000Z
2022-03-31T16:09:46.000Z
tests/auto/plugins/WebQueryTest/tst_webquery.cpp
Skycoder42/QtAutoUpdater
5df052961cec1e47acfdb770599ad9669d720f80
[ "BSD-3-Clause" ]
35
2016-05-06T22:59:07.000Z
2021-09-23T01:20:20.000Z
tests/auto/plugins/WebQueryTest/tst_webquery.cpp
Skycoder42/QtAutoUpdater
5df052961cec1e47acfdb770599ad9669d720f80
[ "BSD-3-Clause" ]
158
2016-03-27T04:12:46.000Z
2022-03-27T10:58:56.000Z
class WebQueryTest; #define TEST_FRIEND WebQueryTest; #include <plugintest.h> #include <QtGui/QGuiApplication> #include "updaterserver.h" using namespace QtAutoUpdater; class WebQueryTest : public PluginTest { Q_OBJECT protected: bool init() override; bool cleanup() override; QString backend() const override; QVariantMap config() override; QVariantMap performConfig() override; QList<UpdateInfo> createInfos(const QVersionNumber &versionFrom, const QVersionNumber &versionTo) override; bool simulateInstall(const QVersionNumber &version) override; bool prepareUpdate(const QVersionNumber &version) override; bool canAbort(bool hard) const override; bool cancelState() const override; private Q_SLOTS: void testSpecialUpdates_data(); void testSpecialUpdates(); private: UpdaterServer *_server = nullptr; QString _parser = QStringLiteral("auto"); bool _autoQuery = true; }; bool WebQueryTest::init() { TEST_WRAP_BEGIN _server = new UpdaterServer{this}; QVERIFY(_server->create()); TEST_WRAP_END } bool WebQueryTest::cleanup() { _server->deleteLater(); _server = nullptr; return true; } QString WebQueryTest::backend() const { return QStringLiteral("webquery"); } QVariantMap WebQueryTest::config() { return { {QStringLiteral("check/url"), _server->checkUrl()}, {QStringLiteral("check/autoQuery"), _autoQuery}, {QStringLiteral("check/parser"), _parser}, #ifdef Q_OS_WIN {QStringLiteral("install/tool"), QStringLiteral("python")}, #else {QStringLiteral("install/tool"), QStringLiteral("python3")}, #endif {QStringLiteral("install/parallel"), true}, {QStringLiteral("install/arguments"), QStringList { QStringLiteral(SRCDIR "installer.py"), _server->installUrl().toString(QUrl::FullyEncoded) }}, {QStringLiteral("install/addDataArgs"), true}, {QStringLiteral("install/runAsAdmin"), false} }; } QVariantMap WebQueryTest::performConfig() { return { {QStringLiteral("check/url"), _server->checkUrl()}, {QStringLiteral("check/autoQuery"), _autoQuery}, {QStringLiteral("check/parser"), _parser}, {QStringLiteral("install/download"), true}, {QStringLiteral("install/downloadUrl"), _server->downloadUrl()}, #ifdef Q_OS_WIN {QStringLiteral("install/tool"), QStringLiteral("python")}, #else {QStringLiteral("install/tool"), QStringLiteral("python3")}, #endif {QStringLiteral("install/parallel"), true}, {QStringLiteral("install/arguments"), QStringList { QStringLiteral("%{downloadPath}"), _server->installUrl().toString(QUrl::FullyEncoded) }}, {QStringLiteral("install/addDataArgs"), true}, {QStringLiteral("install/runAsAdmin"), false} }; } QList<UpdateInfo> WebQueryTest::createInfos(const QVersionNumber &versionFrom, const QVersionNumber &versionTo) { if (versionTo > versionFrom) { if (_parser == QStringLiteral("version")) { return { { QCoreApplication::applicationName(), QGuiApplication::applicationDisplayName(), versionTo } }; } else { return { { QStringLiteral("test-update"), QStringLiteral("test-update"), versionTo, { {QStringLiteral("arguments"), QStringList { QVariant{true}.toString(), versionTo.toString() }}, {QStringLiteral("eulas"), QVariantList { QStringLiteral("EULA 1"), QVariantMap { {QStringLiteral("text"), QStringLiteral("EULA 2")}, {QStringLiteral("required"), true}, }, QVariantMap { {QStringLiteral("text"), QStringLiteral("EULA 3")}, {QStringLiteral("required"), false}, } }} } } }; } } else return {}; } bool WebQueryTest::simulateInstall(const QVersionNumber &version) { QCoreApplication::setApplicationVersion(version.toString()); return true; } bool WebQueryTest::prepareUpdate(const QVersionNumber &version) { if (_parser == QStringLiteral("version")) { _server->setUpdateInfo(version > QVersionNumber::fromString(QCoreApplication::applicationVersion()) ? version : QVersionNumber{}); } else { _server->setUpdateInfo(createInfos(QVersionNumber::fromString(QCoreApplication::applicationVersion()), version)); } QUrlQuery query; if (_autoQuery) { query.addQueryItem(QStringLiteral("name"), QCoreApplication::applicationName()); query.addQueryItem(QStringLiteral("version"), QCoreApplication::applicationVersion()); query.addQueryItem(QStringLiteral("domain"), QCoreApplication::organizationDomain()); query.addQueryItem(QStringLiteral("abi"), QSysInfo::buildAbi()); query.addQueryItem(QStringLiteral("kernel-type"), QSysInfo::kernelType()); query.addQueryItem(QStringLiteral("kernel-version"), QSysInfo::kernelVersion()); query.addQueryItem(QStringLiteral("os-type"), QSysInfo::productType()); query.addQueryItem(QStringLiteral("os-version"), QSysInfo::productVersion()); } _server->setQuery(query); return true; } bool WebQueryTest::canAbort(bool hard) const { Q_UNUSED(hard) return true; } bool WebQueryTest::cancelState() const { return false; } void WebQueryTest::testSpecialUpdates_data() { QTest::addColumn<QVersionNumber>("installedVersion"); QTest::addColumn<QVersionNumber>("updateVersion"); QTest::addColumn<int>("abortLevel"); QTest::addColumn<bool>("success"); QTest::addColumn<bool>("simpleVersion"); QTest::addColumn<bool>("noQuery"); QTest::newRow("complexVersion.noUpdates") << QVersionNumber(1, 0, 0) << QVersionNumber(1, 0, 0) << 0 << true << false << false; QTest::newRow("complexVersion.simpleUpdate") << QVersionNumber(1, 0, 0) << QVersionNumber(1, 1, 0) << 0 << true << false << false; QTest::newRow("simpleVersion.noUpdates") << QVersionNumber(1, 0, 0) << QVersionNumber(1, 0, 0) << 0 << true << true << false; QTest::newRow("simpleVersion.simpleUpdate") << QVersionNumber(1, 0, 0) << QVersionNumber(1, 1, 0) << 0 << true << true << false; QTest::newRow("noQuery.noUpdates") << QVersionNumber(1, 0, 0) << QVersionNumber(1, 0, 0) << 0 << true << false << true; QTest::newRow("noQuery.simpleUpdate") << QVersionNumber(1, 0, 0) << QVersionNumber(1, 1, 0) << 0 << true << false << true; } void WebQueryTest::testSpecialUpdates() { QFETCH(bool, simpleVersion); QFETCH(bool, noQuery); _parser = simpleVersion ? QStringLiteral("version") : QStringLiteral("json"); _autoQuery = !noQuery; testUpdateCheck(); } QTEST_GUILESS_MAIN(WebQueryTest) #include "tst_webquery.moc"
26.731225
111
0.672039
Skycoder42
999157079c666c2c112dc53855a6a9e29a8bf841
4,341
cpp
C++
carlsim/monitor/neuron_monitor.cpp
saw368/CARLsim5
ba359f87e52f30341ea8332ed8f3e5af846c2687
[ "MIT" ]
18
2020-07-21T00:30:51.000Z
2022-01-14T20:21:56.000Z
carlsim/monitor/neuron_monitor.cpp
saw368/CARLsim5
ba359f87e52f30341ea8332ed8f3e5af846c2687
[ "MIT" ]
17
2020-08-19T15:27:56.000Z
2022-02-26T12:18:11.000Z
carlsim/monitor/neuron_monitor.cpp
saw368/CARLsim5
ba359f87e52f30341ea8332ed8f3e5af846c2687
[ "MIT" ]
11
2020-07-28T21:17:05.000Z
2022-03-07T20:30:13.000Z
/* * Copyright (c) 2016 Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. The names of its contributors may not 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. * * *********************************************************************************************** * * CARLsim * created by: (MDR) Micah Richert, (JN) Jayram M. Nageswaran * maintained by: * (MA) Mike Avery <averym@uci.edu> * (MB) Michael Beyeler <mbeyeler@uci.edu>, * (KDC) Kristofor Carlson <kdcarlso@uci.edu> * (TSC) Ting-Shuo Chou <tingshuc@uci.edu> * (HK) Hirak J Kashyap <kashyaph@uci.edu> * * CARLsim v1.0: JM, MDR * CARLsim v2.0/v2.1/v2.2: JM, MDR, MA, MB, KDC * CARLsim3: MB, KDC, TSC * CARLsim4: TSC, HK * CARLsim5: HK, JX, KC * * CARLsim available from http://socsci.uci.edu/~jkrichma/CARLsim/ * Ver 05/24/2017 */ #include <neuron_monitor.h> #include <neuron_monitor_core.h> // NeuronMonitor private implementation #include <user_errors.h> // fancy user error messages #include <sstream> // std::stringstream #include <algorithm> // std::transform // we aren't using namespace std so pay attention! NeuronMonitor::NeuronMonitor(NeuronMonitorCore* neuronMonitorCorePtr){ // make sure the pointer is NULL neuronMonitorCorePtr_ = neuronMonitorCorePtr; } NeuronMonitor::~NeuronMonitor() { delete neuronMonitorCorePtr_; } void NeuronMonitor::clear(){ std::string funcName = "clear()"; UserErrors::assertTrue(!isRecording(), UserErrors::CANNOT_BE_ON, funcName, "Recording"); neuronMonitorCorePtr_->clear(); } bool NeuronMonitor::isRecording(){ return neuronMonitorCorePtr_->isRecording(); } void NeuronMonitor::startRecording() { std::string funcName = "startRecording()"; UserErrors::assertTrue(!isRecording(), UserErrors::CANNOT_BE_ON, funcName, "Recording"); neuronMonitorCorePtr_->startRecording(); } void NeuronMonitor::stopRecording(){ std::string funcName = "stopRecording()"; UserErrors::assertTrue(isRecording(), UserErrors::MUST_BE_ON, funcName, "Recording"); neuronMonitorCorePtr_->stopRecording(); } void NeuronMonitor::setLogFile(const std::string& fileName) { std::string funcName = "setLogFile"; FILE* fid; std::string fileNameLower = fileName; std::transform(fileNameLower.begin(), fileNameLower.end(), fileNameLower.begin(), ::tolower); if (fileNameLower == "null") { // user does not want a binary created fid = NULL; } else { fid = fopen(fileName.c_str(),"wb"); //printf("%s\n", fileName.c_str()); if (fid==NULL) { // default case: print error and exit std::string fileError = " Double-check file permissions and make sure directory exists."; UserErrors::assertTrue(false, UserErrors::FILE_CANNOT_OPEN, funcName, fileName, fileError); } } // tell new file id to core object neuronMonitorCorePtr_->setNeuronFileId(fid); } void NeuronMonitor::print() { std::string funcName = "print()"; UserErrors::assertTrue(!isRecording(), UserErrors::CANNOT_BE_ON, funcName, "Recording"); neuronMonitorCorePtr_->print(); }
35.008065
99
0.728634
saw368
9991b56b62a55e134f4e51bad4c8017ebe807f11
764
hpp
C++
src/debug/TextMesh.hpp
bferan/lucent
b19163df12739ffc513110d927e92f98c0b54321
[ "MIT" ]
1
2021-11-12T08:42:43.000Z
2021-11-12T08:42:43.000Z
src/debug/TextMesh.hpp
bferan/lucent
b19163df12739ffc513110d927e92f98c0b54321
[ "MIT" ]
null
null
null
src/debug/TextMesh.hpp
bferan/lucent
b19163df12739ffc513110d927e92f98c0b54321
[ "MIT" ]
null
null
null
#pragma once #include "device/Device.hpp" #include "debug/Font.hpp" #include "rendering/Mesh.hpp" namespace lucent { class TextMesh { public: TextMesh(Device* device, const Font& font); void SetScreenSize(uint32 width, uint32 height); float Draw(const std::string& str, float x, float y, Color color = Color::White()); float Draw(char c, float screenX, float screenY, Color color = Color::White()); void Clear(); void Upload(); void Render(Context& context); private: const Font& m_Font; bool m_Dirty; std::vector<Mesh::Vertex> m_Vertices; std::vector<uint32> m_Indices; Device* m_Device; Buffer* m_VertexBuffer; Buffer* m_IndexBuffer; uint32 m_ScreenWidth; uint32 m_ScreenHeight; }; }
17.767442
87
0.67801
bferan
999555c38ab2089f6515280071f0e9c1d48743f1
3,139
cpp
C++
src/test/test_disparities.cpp
ShnitzelKiller/Reverse-Engineering-Carpentry
585b5ff053c7e3bf286b663a584bc83687691bd6
[ "MIT" ]
3
2021-09-08T07:28:13.000Z
2022-03-02T21:12:40.000Z
src/test/test_disparities.cpp
ShnitzelKiller/Reverse-Engineering-Carpentry
585b5ff053c7e3bf286b663a584bc83687691bd6
[ "MIT" ]
1
2021-09-21T14:40:55.000Z
2021-09-26T01:19:38.000Z
src/test/test_disparities.cpp
ShnitzelKiller/Reverse-Engineering-Carpentry
585b5ff053c7e3bf286b663a584bc83687691bd6
[ "MIT" ]
null
null
null
// // Created by James Noeckel on 10/13/20. // #include "reconstruction/ReconstructionData.h" #include <opencv2/opencv.hpp> using namespace Eigen; void saveEpipolarLines(ReconstructionData &reconstruction) { for (auto &pair : reconstruction.images) { Vector3d origin1 = pair.second.origin(); double minL2 = std::numeric_limits<double>::max(); int matchImgInd = -1; for (const auto &pair2 : reconstruction.images) { if (pair.first != pair2.first) { Vector3d origin2 = pair2.second.origin(); double L2 = (origin1 - origin2).squaredNorm(); if (L2 < minL2) { minL2 = L2; matchImgInd = pair2.first; } } } Vector3d center(0, 0, 0); Vector2d midpoint1 = reconstruction.project(center.transpose(), pair.first).transpose(); Vector2d midpoint2 = reconstruction.project(center.transpose(), matchImgInd).transpose(); // Vector2d midpoint1 = reconstruction.resolution(pair.first) * 0.5; // Vector2d midpoint2 = reconstruction.resolution(matchImgInd) * 0.5; Vector2d epipolarLine1 = reconstruction.epipolar_line(midpoint1.y(), midpoint1.x(), pair.first, matchImgInd); Vector2d epipolarLine2 = reconstruction.epipolar_line(midpoint2.y(), midpoint2.x(), matchImgInd, pair.first); Vector2d startpoint1 = midpoint1 - epipolarLine1 * midpoint1.x(); Vector2d otherpoint1 = midpoint1 + epipolarLine1 * midpoint1.x(); Vector2d startpoint2 = midpoint2 - epipolarLine2 * midpoint2.x(); Vector2d otherpoint2 = midpoint2 + epipolarLine2 * midpoint2.x(); cv::Mat img1 = pair.second.getImage().clone(); cv::line(img1, cv::Point(startpoint1.x(), startpoint1.y()), cv::Point(otherpoint1.x(), otherpoint1.y()), cv::Scalar(255, 100, 255), 2); cv::circle(img1, cv::Point(midpoint1.x(), midpoint1.y()), 2, cv::Scalar(0, 0, 255), CV_FILLED); cv::imwrite("image_" + std::to_string(pair.first) + "_" + std::to_string(matchImgInd) + "_" + std::to_string(pair.first) + ".png", img1); cv::Mat img2 = reconstruction.images[matchImgInd].getImage().clone(); cv::line(img2, cv::Point(startpoint2.x(), startpoint2.y()), cv::Point(otherpoint2.x(), otherpoint2.y()), cv::Scalar(255, 100, 255), 2); cv::circle(img2, cv::Point(midpoint2.x(), midpoint2.y()), 2, cv::Scalar(0, 0, 255), CV_FILLED); cv::imwrite("image_" + std::to_string(pair.first) + "_" + std::to_string(matchImgInd) + "_" + std::to_string(matchImgInd) + ".png", img2); } } int main(int argc, char **argv) { ReconstructionData reconstruction; if (!reconstruction.load_bundler_file("../data/bench/alignment_complete3/complete3.out")) { std::cout << "failed to load reconstruction" << std::endl; return 1; } //saveEpipolarLines(reconstruction); reconstruction.setImageScale(0.25); saveEpipolarLines(reconstruction); return 0; }
53.20339
146
0.61389
ShnitzelKiller
9995d7412215e44378c5f1451048c16bd9d684b7
44,406
cpp
C++
external/Angle/Project/samples/Asteroids/Asteroids.cpp
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
1,968
2018-12-30T21:14:22.000Z
2022-03-31T23:48:16.000Z
external/Angle/Project/samples/Asteroids/Asteroids.cpp
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
303
2019-01-02T19:36:43.000Z
2022-03-31T23:52:45.000Z
external/Angle/Project/samples/Asteroids/Asteroids.cpp
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
254
2019-01-02T19:05:52.000Z
2022-03-30T06:32:28.000Z
#include "pch.h" #include "Asteroids.h" #include "BasicTimer.h" #define STRINGIFY(str) #str #define PLAYER_ACCELERATION 100.0f #define TURN_SPEED 200.0f #define MAX_ASTEROIDS 32 #define MAX_FALLOUT_PER_ASTEROID 20 #define FALLOUT_INITIAL_VEL 500.0f #define BULLET_SPEED 300.0f #define DESTROYED_ASTEROID_SPEED 100.0f #define REGULAR_WEAPON_COOLDOWN 0.2f #define SPREAD_WEAPON_COOLDOWN 0.5f #define LASER_WEAPON_COOLDOWN 2.0f #define THRUST_OUTPUT_RATE 5 #define MAX_THRUST_PARTICLES 200 #define LASER_LIFETIME 4.0f #define PLAYER_STATE_W 0x1 #define PLAYER_STATE_A 0x2 #define PLAYER_STATE_S 0x4 #define PLAYER_STATE_D 0x8 #define PLAYER_STATE_SPACE 0x10 #define RENDER_TARGET_WIDTH 1024 #define RENDER_TARGET_HEIGHT 512 using namespace Windows::ApplicationModel; using namespace Windows::ApplicationModel::Core; using namespace Windows::ApplicationModel::Activation; using namespace Windows::UI::Core; using namespace Windows::System; using namespace Windows::Foundation; using namespace Windows::Graphics::Display; using namespace concurrency; using namespace DirectX; Asteroids::Asteroids() : m_playerState(0), m_regularWeaponTimer(0), m_spreadWeaponTimer(0), m_laserWeaponTimer(0), m_weapon(Weapon::Regular), m_asteroidRespawnTime(10), m_windowClosed(false), m_windowVisible(false) { } void Asteroids::Initialize(CoreApplicationView^ applicationView) { applicationView->Activated += ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &Asteroids::OnActivated); CoreApplication::Suspending += ref new EventHandler<SuspendingEventArgs^>(this, &Asteroids::OnSuspending); CoreApplication::Resuming += ref new EventHandler<Platform::Object^>(this, &Asteroids::OnResuming); //m_renderer = ref new CubeRenderer(); m_player.m_scale = glm::vec2(40); for(int i = 0; i < MAX_ASTEROIDS; ++i) { GameObject asteroid; asteroid.m_pos.x = static_cast<float>(rand() % 10000); asteroid.m_pos.y = static_cast<float>(rand() % 10000); asteroid.m_angle = (rand() % 1000) / 10.0f - 50; asteroid.m_omega = (rand() % 1000) / 10.0f - 50; asteroid.m_vel.x = (rand() % 1000) / 10.0f - 50; asteroid.m_vel.y = (rand() % 1000) / 10.0f - 50; asteroid.m_scale.x = (rand() % 1000) / 20.0f + 50; asteroid.m_scale.y = asteroid.m_scale.x;//(rand() % 1000) / 10.0f - 50; asteroid.m_lives = 2; m_asteroids.push_back(asteroid); } m_rocketThrust.m_emissionRate = THRUST_OUTPUT_RATE; m_rocketThrust.m_maxParticles = MAX_THRUST_PARTICLES; m_rocketThrust.m_emissionTimer = 0; } void Asteroids::SetWindow(CoreWindow^ window) { window->SizeChanged += ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &Asteroids::OnWindowSizeChanged); window->VisibilityChanged += ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &Asteroids::OnVisibilityChanged); window->Closed += ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &Asteroids::OnWindowClosed); window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0); window->PointerPressed += ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &Asteroids::OnPointerPressed); window->PointerMoved += ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &Asteroids::OnPointerMoved); window->KeyDown += ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &Asteroids::OnKeyDown); window->KeyUp += ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &Asteroids::OnKeyUp); //m_renderer->Initialize(CoreWindow::GetForCurrentThread()); m_orientation = DisplayProperties::CurrentOrientation; m_windowBounds = window->Bounds; esInitContext ( &m_esContext ); m_esContext.hWnd.window = CoreWindow::GetForCurrentThread(); esCreateWindow ( &m_esContext, TEXT("Simple Instancing"), 320, 240, ES_WINDOW_RGB ); const char *vs = STRINGIFY( attribute vec3 a_position; attribute vec4 a_color; varying vec4 v_color; uniform mat4 u_mvp; void main(void) { v_color = a_color; v_color.rgb *= a_color.a; gl_Position = u_mvp * vec4(a_position, 1); } ); const char *fs = STRINGIFY( precision mediump float; varying vec4 v_color; void main(void) { gl_FragColor = v_color; } ); m_drawProgram = esLoadProgram(vs, fs); m_uMvpDraw = glGetUniformLocation(m_drawProgram, "u_mvp"); m_aPositionDraw = glGetAttribLocation(m_drawProgram, "a_position"); m_aColorDraw = glGetAttribLocation(m_drawProgram, "a_color"); vs = STRINGIFY( attribute vec2 a_position; varying vec2 v_uv; void main(void) { gl_Position = vec4(a_position, 0, 1); v_uv = a_position * 0.5 + 0.5; } ); fs = STRINGIFY( precision mediump float; varying vec2 v_uv; uniform sampler2D u_texture; uniform vec2 u_offset; void main(void) { vec4 color; const int radius = 1; const float gaussianOffset = 1.4; int divisor = 0; for(int i = -radius; i <= radius; ++i) { vec2 uv = v_uv + u_offset * float(i) * gaussianOffset; color += texture2D(u_texture, uv); ++divisor; } gl_FragColor = color / float(divisor); } ); m_blurProgram = esLoadProgram(vs, fs); m_uTextureBlur = glGetUniformLocation(m_blurProgram, "u_texture"); m_uOffsetBlur = glGetUniformLocation(m_blurProgram, "u_offset"); m_aPositionBlur = glGetAttribLocation(m_blurProgram, "a_position"); fs = STRINGIFY( precision mediump float; varying vec2 v_uv; uniform sampler2D u_texture; void main(void) { gl_FragColor = texture2D(u_texture, v_uv); } ); m_texturePassThruProgram = esLoadProgram(vs, fs); m_uTextureTexturePassThru = glGetUniformLocation(m_texturePassThruProgram, "u_texture"); m_aPositionTexturePassThru = glGetAttribLocation(m_texturePassThruProgram, "a_position"); fs = STRINGIFY( precision mediump float; varying vec2 v_uv; uniform sampler2D u_texture[4]; void main(void) { vec4 color; for(int i = 0; i < 4; ++i) color += texture2D(u_texture[i], v_uv); const float bloomPower = 3.0; gl_FragColor.r = (color.r + (max(color.g - 1.0, 0.0) + max(color.b - 1.0, 0.0)) * 0.5 * bloomPower) * color.a; gl_FragColor.g = (color.g + (max(color.r - 1.0, 0.0) + max(color.b - 1.0, 0.0)) * 0.5 * bloomPower) * color.a; gl_FragColor.b = (color.b + (max(color.r - 1.0, 0.0) + max(color.g - 1.0, 0.0)) * 0.5 * bloomPower) * color.a; gl_FragColor.a = color.a; } ); m_bloomProgram = esLoadProgram(vs, fs); for(int i = 0; i < 4; ++i) { char buffer[] = "u_texture[0]"; sprintf(buffer, "u_texture[%i]", i); m_uTextureBloom[i] = glGetUniformLocation(m_bloomProgram, buffer); } m_aPositionBloom = glGetAttribLocation(m_bloomProgram, "a_position"); //setup the FBO CreateFBO(); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } void Asteroids::Load(Platform::String^ entryPoint) { } void Asteroids::Run() { BasicTimer^ timer = ref new BasicTimer(); while (!m_windowClosed) { if (m_windowVisible) { timer->Update(); CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent); Update(); Draw(); //m_renderer->Update(timer->Total, timer->Delta); //m_renderer->Render(); //m_renderer->Present(); // This call is synchronized to the display frame rate. } else { CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending); } } } void Asteroids::Uninitialize() { } void Asteroids::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args) { //m_renderer->UpdateForWindowSizeChange(); if (sender->Bounds.Width != m_windowBounds.Width || sender->Bounds.Height != m_windowBounds.Height || m_orientation != DisplayProperties::CurrentOrientation) { // Internally calls DX11's version of flush glFlush(); // Store the window bounds so the next time we get a SizeChanged event we can // avoid rebuilding everything if the size is identical. m_windowBounds = sender->Bounds; // Calculate the necessary swap chain and render target size in pixels. float windowWidth = ConvertDipsToPixels(m_windowBounds.Width); float windowHeight = ConvertDipsToPixels(m_windowBounds.Height); // The width and height of the swap chain must be based on the window's // landscape-oriented width and height. If the window is in a portrait // orientation, the dimensions must be reversed. m_orientation = DisplayProperties::CurrentOrientation; bool swapDimensions = m_orientation == DisplayOrientations::Portrait || m_orientation == DisplayOrientations::PortraitFlipped; m_renderTargetSize.Width = swapDimensions ? windowHeight : windowWidth; m_renderTargetSize.Height = swapDimensions ? windowWidth : windowHeight; // Actually resize the underlying swapchain //esResizeWindow(&m_esContext, static_cast<UINT>(m_renderTargetSize.Width), static_cast<UINT>(m_renderTargetSize.Height)); glViewport(0, 0, static_cast<UINT>(m_renderTargetSize.Width), static_cast<UINT>(m_renderTargetSize.Height)); // Recreate the FBO with the new dimensions glDeleteFramebuffers(8, m_offscreenFBO); glDeleteTextures(8, m_offscreenTex); //setup the FBO CreateFBO(); } } void Asteroids::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args) { m_windowVisible = args->Visible; } void Asteroids::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args) { m_windowClosed = true; glDeleteProgram(m_drawProgram); glDeleteProgram(m_blurProgram); glDeleteProgram(m_texturePassThruProgram); glDeleteProgram(m_bloomProgram); glDeleteTextures(8, m_offscreenTex); glDeleteFramebuffers(8, m_offscreenFBO); } void Asteroids::OnPointerPressed(CoreWindow^ sender, PointerEventArgs^ args) { // Insert your code here. } void Asteroids::OnPointerMoved(CoreWindow^ sender, PointerEventArgs^ args) { // Insert your code here. } void Asteroids::OnKeyDown(CoreWindow^ sender, KeyEventArgs ^args) { switch(args->VirtualKey) { case VirtualKey::W: case VirtualKey::Up: m_playerState |= PLAYER_STATE_W; break; case VirtualKey::S: case VirtualKey::Down: m_playerState |= PLAYER_STATE_S; break; case VirtualKey::A: case VirtualKey::Left: m_playerState |= PLAYER_STATE_A; break; case VirtualKey::D: case VirtualKey::Right: m_playerState |= PLAYER_STATE_D; break; case VirtualKey::Space: m_playerState |= PLAYER_STATE_SPACE; break; case VirtualKey::Number1: m_weapon = Weapon::Regular; break; case VirtualKey::Number2: m_weapon = Weapon::Spread; break; case VirtualKey::Number3: m_weapon = Weapon::LaserWeapon; break; } } void Asteroids::OnKeyUp(CoreWindow^ sender, KeyEventArgs ^args) { switch(args->VirtualKey) { case VirtualKey::W: case VirtualKey::Up: m_playerState &= ~PLAYER_STATE_W; break; case VirtualKey::S: case VirtualKey::Down: m_playerState &= ~PLAYER_STATE_S; break; case VirtualKey::A: case VirtualKey::Left: m_playerState &= ~PLAYER_STATE_A; break; case VirtualKey::D: case VirtualKey::Right: m_playerState &= ~PLAYER_STATE_D; break; case VirtualKey::Space: m_playerState &= ~PLAYER_STATE_SPACE; break; } } float Asteroids::ConvertDipsToPixels(float dips) { static const float dipsPerInch = 96.0f; return floor(dips * DisplayProperties::LogicalDpi / dipsPerInch + 0.5f); // Round to nearest integer. } void Asteroids::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args) { CoreWindow::GetForCurrentThread()->Activate(); } void Asteroids::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args) { // Save app state asynchronously after requesting a deferral. Holding a deferral // indicates that the application is busy performing suspending operations. Be // aware that a deferral may not be held indefinitely. After about five seconds, // the app will be forced to exit. SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral(); create_task([this, deferral]() { // Insert your code here. deferral->Complete(); }); } void Asteroids::OnResuming(Platform::Object^ sender, Platform::Object^ args) { // Restore any data or state that was unloaded on suspend. By default, data // and state are persisted when resuming from suspend. Note that this event // does not occur if the app was previously terminated. } Asteroids::GameObject::GameObject(void) : m_angle(0), m_omega(0), m_scale(1, 1), m_lives(1), m_lifeTime(0.2f) { } void Asteroids::GameObject::Update(float dt) { //do semi-implicit euler m_vel += m_acc * dt; m_pos += m_vel * dt; m_angle += m_omega * dt; m_lifeTime -= dt; } glm::mat4 Asteroids::GameObject::TransformMatrix(void) const { return glm::translate(glm::vec3(m_pos, 0)) * glm::rotate(m_angle, glm::vec3(0, 0, 1)) * glm::scale(glm::vec3(m_scale, 0)); } static float MagnitudeSquared(float x, float y) { return x * x + y * y; } static float MagnitudeSquared(const glm::vec2 &v) { return MagnitudeSquared(v.x, v.y); } void Asteroids::Update() { const float dt = 1.0f / 60; //handle input float radians = glm::radians(m_player.m_angle); if((m_playerState & PLAYER_STATE_W) && !(m_playerState & PLAYER_STATE_S)) m_player.m_acc = glm::vec2(cos(radians), sin(radians)) * PLAYER_ACCELERATION; if((m_playerState & PLAYER_STATE_S) && !(m_playerState &PLAYER_STATE_W)) m_player.m_acc = glm::vec2(cos(radians), sin(radians)) * -PLAYER_ACCELERATION; else if(!(m_playerState & PLAYER_STATE_S) && !(m_playerState &PLAYER_STATE_W)) m_player.m_acc = glm::vec2(); if(m_playerState & PLAYER_STATE_A) m_player.m_omega = TURN_SPEED; if(m_playerState & PLAYER_STATE_D) m_player.m_omega = -TURN_SPEED; if(!(m_playerState & PLAYER_STATE_A) && !(m_playerState & PLAYER_STATE_D)) m_player.m_omega = 0; m_regularWeaponTimer -= dt; m_spreadWeaponTimer -= dt; m_laserWeaponTimer -= dt; if(m_playerState & PLAYER_STATE_SPACE) FireBullet(); //move everything around m_player.Update(dt); GameObjectIter end = m_asteroids.end(); for(GameObjectIter it = m_asteroids.begin(); it != end; ++it) it->Update(dt); end = m_bullets.end(); for(GameObjectIter it = m_bullets.begin(); it != end; ++it) it->Update(dt); end = m_asteroidFallout.end(); for(GameObjectIter it = m_asteroidFallout.begin(); it != end; ++it) it->Update(dt); //update the thrust particles end = m_rocketThrustParticles.end(); for(GameObjectIter it = m_rocketThrustParticles.begin(); it != end;) { it->Update(dt); if(it->m_lifeTime <= 0) { it = m_rocketThrustParticles.erase(it); end = m_rocketThrustParticles.end(); } else ++it; } if(m_rocketThrustParticles.size() < MAX_THRUST_PARTICLES) { --m_rocketThrust.m_emissionTimer; if(m_rocketThrust.m_emissionTimer <= 0) { GameObject particle; particle.m_color = glm::vec4(1, 0.4f, 0, 1); particle.m_lifeTime = (rand() % 1000) / 3000.0f + 0.1f; float radians = glm::radians(m_player.m_angle); glm::vec2 rearEnd = m_player.m_pos - glm::vec2(cos(radians), sin(radians)) * m_player.m_scale.x * 0.5f; particle.m_pos = rearEnd; radians = glm::radians(m_player.m_angle + (rand() % 6000) / 200.0f - 15); float velScale; if(m_playerState & PLAYER_STATE_W) velScale = (rand() % 1000) / 50.0f + 200.0f; else if(m_playerState & PLAYER_STATE_S) velScale = -((rand() % 1000) / 50.0f + 200.0f); else velScale = (rand() % 1000) / 50.0f + 50.0f; particle.m_vel = m_player.m_vel + -glm::vec2(cos(radians), sin(radians)) * velScale; particle.m_scale = glm::vec2(5); particle.m_omega = (rand() % 1000) / 5.0f - 100; m_rocketThrustParticles.push_back(particle); if(m_rocketThrustParticles.size() == MAX_THRUST_PARTICLES) m_rocketThrust.m_emissionTimer = THRUST_OUTPUT_RATE; } } //update the lasers for(LaserIter it = m_lasers.begin(); it != m_lasers.end();) { it->m_lifeTime -= dt; if(it->m_lifeTime <= 0) it = m_lasers.erase(it); else ++it; } //wrap player and asteroids to the other side of the universe if out of bounds WrapAround(m_player); end = m_asteroids.end(); for(GameObjectIter it = m_asteroids.begin(); it != end; ++it) WrapAround(*it); //collide the asteroids and bullets using circles end = m_bullets.end(); for(GameObjectIter it = m_bullets.begin(); it != end; ) { GameObjectIter end2 = m_asteroids.end(); for(GameObjectIter it2 = m_asteroids.begin(); it2 != end2;) { float radius1 = MagnitudeSquared(it->m_scale * 0.5f); float radius2 = MagnitudeSquared(it2->m_scale * 0.5f); float distance = MagnitudeSquared(it->m_pos - it2->m_pos); //they've collided so delete them if(radius1 + radius2 > distance) { it = m_bullets.erase(it); end = m_bullets.end(); //split the asteroid into 4 smaller ones if(it2->m_lives == 2) { int position = it2 - m_asteroids.begin(); GameObject asteroid; float radians = glm::radians(glm::radians(it2->m_angle + 45)); glm::vec2 vel = it2->m_vel; glm::vec2 pos = it2->m_pos; glm::vec2 dir1(cos(radians), sin(radians)); glm::vec2 dir2(dir1.y, -dir1.x); float scale = it2->m_scale.x; float angle = it2->m_angle; float omega = it2->m_omega; asteroid.m_scale.x = asteroid.m_scale.y = scale * 0.5f; asteroid.m_pos = pos + dir1 * scale * 0.25f; asteroid.m_angle = angle; asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50; asteroid.m_vel = vel + dir1 * DESTROYED_ASTEROID_SPEED; m_asteroids.push_back(asteroid); asteroid.m_pos = pos - dir1 * scale * 0.25f; asteroid.m_angle = angle; asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50; asteroid.m_vel = vel - dir1 * DESTROYED_ASTEROID_SPEED; m_asteroids.push_back(asteroid); asteroid.m_pos = pos + dir2 * scale * 0.25f; asteroid.m_angle = angle; asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50; asteroid.m_vel = vel + dir2 * DESTROYED_ASTEROID_SPEED; m_asteroids.push_back(asteroid); asteroid.m_pos = pos - dir2 * scale * 0.25f; asteroid.m_angle = angle; asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50; asteroid.m_vel = vel - dir2 * DESTROYED_ASTEROID_SPEED; m_asteroids.push_back(asteroid); it2 = m_asteroids.begin() + position; } else { GameObject fallout; fallout.m_pos = it2->m_pos; fallout.m_scale = glm::vec2(5); for(int i = 0; i < MAX_FALLOUT_PER_ASTEROID; ++i) { fallout.m_angle = static_cast<float>(rand() % 10000); fallout.m_omega = (rand() % 1000) - 500.0f; float radians = glm::radians(static_cast<float>(rand() % 10000)); fallout.m_vel = it2->m_vel + glm::vec2(cos(radians), sin(radians)) * (rand() % 100 + FALLOUT_INITIAL_VEL); m_asteroidFallout.push_back(fallout); } } it2 = m_asteroids.erase(it2); end2 = m_asteroids.end(); if(it == end) break; } else ++it2; } if(it != end) ++it; } //collide asteroid fallout and asteroids end = m_asteroidFallout.end(); for(GameObjectIter it = m_asteroidFallout.begin(); it != end; ) { if(it->m_lifeTime <= 0) { it = m_asteroidFallout.erase(it); end = m_asteroidFallout.end(); continue; } GameObjectIter end2 = m_asteroids.end(); for(GameObjectIter it2 = m_asteroids.begin(); it2 != end2;) { float radius1 = MagnitudeSquared(it->m_scale * 0.5f); float radius2 = MagnitudeSquared(it2->m_scale * 0.5f); float distance = MagnitudeSquared(it->m_pos - it2->m_pos); //they've collided so delete them if(radius1 + radius2 > distance) { it = m_asteroidFallout.erase(it); end = m_asteroidFallout.end(); //split the asteroid into 4 smaller ones if(it2->m_lives == 2) { int position = it2 - m_asteroids.begin(); GameObject asteroid; float radians = glm::radians(glm::radians(it2->m_angle + 45)); glm::vec2 vel = it2->m_vel; glm::vec2 pos = it2->m_pos; glm::vec2 dir1(cos(radians), sin(radians)); glm::vec2 dir2(dir1.y, -dir1.x); float scale = it2->m_scale.x; float angle = it2->m_angle; float omega = it2->m_omega; asteroid.m_scale.x = asteroid.m_scale.y = scale * 0.5f; asteroid.m_pos = pos + dir1 * scale * 0.25f; asteroid.m_angle = angle; asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50; asteroid.m_vel = vel + dir1 * DESTROYED_ASTEROID_SPEED; m_asteroids.push_back(asteroid); asteroid.m_pos = pos - dir1 * scale * 0.25f; asteroid.m_angle = angle; asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50; asteroid.m_vel = vel - dir1 * DESTROYED_ASTEROID_SPEED; m_asteroids.push_back(asteroid); asteroid.m_pos = pos + dir2 * scale * 0.25f; asteroid.m_angle = angle; asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50; asteroid.m_vel = vel + dir2 * DESTROYED_ASTEROID_SPEED; m_asteroids.push_back(asteroid); asteroid.m_pos = pos - dir2 * scale * 0.25f; asteroid.m_angle = angle; asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50; asteroid.m_vel = vel - dir2 * DESTROYED_ASTEROID_SPEED; m_asteroids.push_back(asteroid); it2 = m_asteroids.begin() + position; } else { int index = it - m_asteroidFallout.begin(); GameObject fallout; fallout.m_pos = it2->m_pos; fallout.m_scale = glm::vec2(5); for(int i = 0; i < MAX_FALLOUT_PER_ASTEROID; ++i) { fallout.m_angle = static_cast<float>(rand() % 10000); fallout.m_omega = (rand() % 1000) - 500.0f; float radians = glm::radians(static_cast<float>(rand() % 10000)); fallout.m_vel = it2->m_vel + glm::vec2(cos(radians), sin(radians)) * (rand() % 100 + FALLOUT_INITIAL_VEL); m_asteroidFallout.push_back(fallout); } it = m_asteroidFallout.begin() + index; end = m_asteroidFallout.end(); } it2 = m_asteroids.erase(it2); end2 = m_asteroids.end(); if(it == end) break; } else ++it2; } if(it != end) ++it; } //collide the asteroids and lasers for(LaserIter it = m_lasers.begin(); it != m_lasers.end(); ++it) { if(!it->m_lethal) continue; for(GameObjectIter it2 = m_asteroids.begin(); it2 != m_asteroids.end();) { //project asteroid to laser direction glm::vec2 projectedPos = it->m_pos + glm::dot(it2->m_pos - it->m_pos, it->m_dir) / MagnitudeSquared(it->m_dir) * it->m_dir; if(it2->m_scale.x > glm::length(it2->m_pos - projectedPos) && glm::dot(projectedPos - it->m_pos, it->m_dir) >= 0) { //split the asteroid into 4 smaller ones if(it2->m_lives == 2) { int position = it2 - m_asteroids.begin(); GameObject asteroid; float radians = glm::radians(glm::radians(it2->m_angle + 45)); glm::vec2 vel = it2->m_vel; glm::vec2 pos = it2->m_pos; glm::vec2 dir1(cos(radians), sin(radians)); glm::vec2 dir2(dir1.y, -dir1.x); float scale = it2->m_scale.x; float angle = it2->m_angle; float omega = it2->m_omega; asteroid.m_scale.x = asteroid.m_scale.y = scale * 0.5f; asteroid.m_pos = pos + dir1 * scale * 0.25f; asteroid.m_angle = angle; asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50; asteroid.m_vel = vel + dir1 * DESTROYED_ASTEROID_SPEED; m_asteroids.push_back(asteroid); asteroid.m_pos = pos - dir1 * scale * 0.25f; asteroid.m_angle = angle; asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50; asteroid.m_vel = vel - dir1 * DESTROYED_ASTEROID_SPEED; m_asteroids.push_back(asteroid); asteroid.m_pos = pos + dir2 * scale * 0.25f; asteroid.m_angle = angle; asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50; asteroid.m_vel = vel + dir2 * DESTROYED_ASTEROID_SPEED; m_asteroids.push_back(asteroid); asteroid.m_pos = pos - dir2 * scale * 0.25f; asteroid.m_angle = angle; asteroid.m_omega = omega + (rand() % 1000) / 10.0f - 50; asteroid.m_vel = vel - dir2 * DESTROYED_ASTEROID_SPEED; m_asteroids.push_back(asteroid); it2 = m_asteroids.begin() + position; } else { GameObject fallout; fallout.m_pos = it2->m_pos; fallout.m_scale = glm::vec2(5); for(int i = 0; i < MAX_FALLOUT_PER_ASTEROID; ++i) { fallout.m_angle = static_cast<float>(rand() % 10000); fallout.m_omega = (rand() % 1000) - 500.0f; float radians = glm::radians(static_cast<float>(rand() % 10000)); fallout.m_vel = it2->m_vel + glm::vec2(cos(radians), sin(radians)) * (rand() % 100 + FALLOUT_INITIAL_VEL); m_asteroidFallout.push_back(fallout); } } it2 = m_asteroids.erase(it2); } else ++it2; } it->m_lethal = false; } //keep the asteroids coming when the universe runs low if(m_asteroids.size() < MAX_ASTEROIDS) { --m_asteroidRespawnTime; if(m_asteroidRespawnTime <= 0) { for(unsigned i = m_asteroids.size(); i < MAX_ASTEROIDS; ++i) { GameObject asteroid; asteroid.m_pos.x = static_cast<float>(rand() % 10000); asteroid.m_pos.y = static_cast<float>(rand() % 10000); asteroid.m_angle = (rand() % 1000) / 10.0f - 50; asteroid.m_omega = (rand() % 1000) / 10.0f - 50; asteroid.m_vel.x = (rand() % 1000) / 10.0f - 50; asteroid.m_vel.y = (rand() % 1000) / 10.0f - 50; asteroid.m_scale = glm::vec2((rand() % 1000) / 20.0f + 50); asteroid.m_lives = 2; m_asteroids.push_back(asteroid); } m_asteroidRespawnTime = 30; } } } void Asteroids::Draw() { glUseProgram(m_drawProgram); CoreWindow ^window = CoreWindow::GetForCurrentThread(); float halfWindowWidth = window->Bounds.Width * 0.5f; float halfWindowHeight = window->Bounds.Height * 0.5f; glm::mat4 ortho = glm::ortho(-halfWindowWidth, halfWindowWidth, -halfWindowHeight, halfWindowHeight, -1.0f, 1.0f); glUniformMatrix4fv(m_uMvpDraw, 1, GL_FALSE, &ortho[0][0]); DrawPlayer(); DrawAsteroids(); DrawBullets(); DrawRocket(); const int stride = sizeof(glm::vec3) + sizeof(glm::vec4); glEnableVertexAttribArray(m_aPositionDraw); glEnableVertexAttribArray(m_aColorDraw); glVertexAttribPointer(m_aPositionDraw, 3, GL_FLOAT, GL_FALSE, stride, &m_vertexBuffer[0]); glVertexAttribPointer(m_aColorDraw, 4, GL_FLOAT, GL_FALSE, stride, &m_vertexBuffer[3]); bool swapDimensions = m_orientation == Windows::Graphics::Display::DisplayOrientations::Portrait || m_orientation == Windows::Graphics::Display::DisplayOrientations::PortraitFlipped; for(int i = 0; i < 4; ++i) { if(swapDimensions) glViewport(0, 0, RENDER_TARGET_HEIGHT >> i, RENDER_TARGET_WIDTH >> i); else glViewport(0, 0, RENDER_TARGET_WIDTH >> i, RENDER_TARGET_HEIGHT >> i); glBindFramebuffer(GL_FRAMEBUFFER, m_offscreenFBO[i]); glClear(GL_COLOR_BUFFER_BIT); glDrawArrays(GL_LINES, 0, m_vertexBuffer.size() / 7); } m_vertexBuffer.clear(); DrawLasers(); if(m_lasers.size()) { glVertexAttribPointer(m_aPositionDraw, 3, GL_FLOAT, GL_FALSE, stride, &m_vertexBuffer[0]); glVertexAttribPointer(m_aColorDraw, 4, GL_FLOAT, GL_FALSE, stride, &m_vertexBuffer[3]); for(int i = 0; i < 4; ++i) { if(swapDimensions) glViewport(0, 0, RENDER_TARGET_HEIGHT >> i, RENDER_TARGET_WIDTH >> i); else glViewport(0, 0, RENDER_TARGET_WIDTH >> i, RENDER_TARGET_HEIGHT >> i); glBindFramebuffer(GL_FRAMEBUFFER, m_offscreenFBO[i]); glDrawArrays(GL_TRIANGLES, 0, m_vertexBuffer.size() / 7); } } m_vertexBuffer.clear(); glDisableVertexAttribArray(m_aPositionDraw); glDisableVertexAttribArray(m_aColorDraw); float fullScreen[] = { -1, 1, -1, -1, 1, 1, 1, -1 }; glDisable(GL_BLEND); glUseProgram(m_blurProgram); glActiveTexture(GL_TEXTURE0); glUniform1i(m_uTextureBlur, 0); glEnableVertexAttribArray(m_aPositionBlur); glVertexAttribPointer(m_aPositionBlur, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), fullScreen); for(int i = 0; i < 4; ++i) { int width = (swapDimensions) ? RENDER_TARGET_HEIGHT >> i : RENDER_TARGET_WIDTH >> i; int height = (swapDimensions) ? RENDER_TARGET_WIDTH >> i : RENDER_TARGET_HEIGHT >> i; glViewport(0, 0, width, height); glBindFramebuffer(GL_FRAMEBUFFER, m_offscreenFBO[i + 4]); glBindTexture(GL_TEXTURE_2D, m_offscreenTex[i]); glm::vec2 horiOffset(1.0f / width, 0.0f); glUniform2f(m_uOffsetBlur, horiOffset.x, horiOffset.y); glClear(GL_COLOR_BUFFER_BIT); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindFramebuffer(GL_FRAMEBUFFER, m_offscreenFBO[i]); glBindTexture(GL_TEXTURE_2D, m_offscreenTex[i + 4]); glm::vec2 vertOffset = glm::vec2(0.0f, 1.0f / height); glUniform2f(m_uOffsetBlur, vertOffset.x, vertOffset.y); glClear(GL_COLOR_BUFFER_BIT); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } glDisableVertexAttribArray(m_aPositionBlur); glEnable(GL_BLEND); glViewport(0, 0, static_cast<int>(ConvertDipsToPixels(window->Bounds.Width)), static_cast<int>(ConvertDipsToPixels(window->Bounds.Height))); glBindFramebuffer(GL_FRAMEBUFFER, 0); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(m_bloomProgram); for(int i = 0; i < 4; ++i) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, m_offscreenTex[i]); glUniform1i(m_uTextureBloom[i], i); } glUniform1i(m_uTextureTexturePassThru, 0); glEnableVertexAttribArray(m_aPositionBloom); glVertexAttribPointer(m_aPositionBloom, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), fullScreen); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableVertexAttribArray(m_aPositionBloom); eglSwapBuffers(m_esContext.eglDisplay, m_esContext.eglSurface); } void Asteroids::WrapAround(GameObject &object) { CoreWindow ^window = CoreWindow::GetForCurrentThread(); float halfWindowWidth = window->Bounds.Width * 0.5f; float halfWindowHeight = window->Bounds.Height * 0.5f; if(object.m_pos.x - object.m_scale.x > halfWindowWidth) object.m_pos.x = -halfWindowWidth - object.m_scale.x * 0.5f; if(object.m_pos.x + object.m_scale.x < -halfWindowWidth) object.m_pos.x = halfWindowWidth + object.m_scale.x * 0.5f; if(object.m_pos.y - object.m_scale.y > halfWindowHeight) object.m_pos.y = -halfWindowHeight - object.m_scale.y * 0.5f; if(object.m_pos.y + object.m_scale.y < -halfWindowHeight) object.m_pos.y = halfWindowHeight + object.m_scale.y * 0.5f; } void Asteroids::FireBullet() { if(m_weapon == Weapon::Regular) { if(m_regularWeaponTimer <= 0) { GameObject bullet; float radians = glm::radians(m_player.m_angle); glm::vec2 dir(cos(radians), sin(radians)); bullet.m_pos = m_player.m_pos + dir * m_player.m_scale.x * 0.5f; bullet.m_scale = glm::vec2(10, 10); bullet.m_angle = m_player.m_angle; bullet.m_vel = dir * BULLET_SPEED + m_player.m_vel; m_bullets.push_back(bullet); m_regularWeaponTimer = REGULAR_WEAPON_COOLDOWN; } } else if(m_weapon == Weapon::Spread) { if(m_spreadWeaponTimer <= 0) { GameObject bullet; bullet.m_scale = glm::vec2(10, 10); bullet.m_angle = m_player.m_angle; for(int i = -2; i <= 2; ++i) { float radians = glm::radians(m_player.m_angle + i * 10); glm::vec2 dir(cos(radians), sin(radians)); bullet.m_vel = dir * BULLET_SPEED + m_player.m_vel; bullet.m_pos = m_player.m_pos + dir * m_player.m_scale.x * 0.5f; m_bullets.push_back(bullet); } m_spreadWeaponTimer = SPREAD_WEAPON_COOLDOWN; } } else if(m_weapon == Weapon::LaserWeapon) { if(m_laserWeaponTimer <= 0) { Laser laser; laser.m_lifeTime = 2; float radians = glm::radians(m_player.m_angle); laser.m_dir = glm::vec2(cos(radians), sin(radians)); laser.m_pos = m_player.m_pos + laser.m_dir * m_player.m_scale * 0.5f; laser.m_lethal = true; m_lasers.push_back(laser); m_laserWeaponTimer = LASER_WEAPON_COOLDOWN; } } } void Asteroids::RemoveOutOfBoundsBullets() { CoreWindow ^window = CoreWindow::GetForCurrentThread(); float halfWindowWidth = window->Bounds.Width * 0.5f; float halfWindowHeight = window->Bounds.Height * 0.5f; GameObjectIter end = m_bullets.end(); for(GameObjectIter it = m_bullets.begin(); it != end;) { if(it->m_pos.x - it->m_scale.x > halfWindowWidth || it->m_pos.x + it->m_scale.x < halfWindowWidth || it->m_pos.y - it->m_scale.y > halfWindowHeight || it->m_pos.y + it->m_scale.y < halfWindowHeight) it = m_bullets.erase(it); else ++it; } } static void FillVertexBuffer(std::vector<float> &buffer, const glm::vec3 &position, const glm::vec4 &color) { buffer.insert(buffer.end(), &position.x, &position.x + 3); buffer.insert(buffer.end(), &color.x, &color.x + 4); } void Asteroids::DrawPlayer(void) { glm::mat4 transform = m_player.TransformMatrix(); glm::vec4 verts[] = { glm::vec4(0.5f, 0, 0, 1), glm::vec4(-0.5f, 0.3f, 0, 1), glm::vec4(-0.5f, 0.3f, 0, 1), glm::vec4(-0.2f, 0, 0, 1), glm::vec4(-0.2f, 0, 0, 1), glm::vec4(-0.5f, -0.3f, 0, 1), glm::vec4(-0.5f, -0.3f, 0, 1), glm::vec4(0.5f, 0, 0, 1), }; for(int i = 0; i < sizeof(verts) / sizeof(*verts); ++i) FillVertexBuffer(m_vertexBuffer, glm::vec3(transform * verts[i]), glm::vec4(0, 1, 0, 1)); } void Asteroids::DrawAsteroids(void) { glm::vec4 verts[] = { glm::vec4(0.5f, 0.5f, 0, 1), glm::vec4(-0.5f, 0.5f, 0, 1), glm::vec4(-0.5f, 0.5f, 0, 1), glm::vec4(-0.5f, -0.5f, 0, 1), glm::vec4(-0.5f, -0.5f, 0, 1), glm::vec4(0.5f, -0.5f, 0, 1), glm::vec4(0.5f, -0.5f, 0, 1), glm::vec4(0.5f, 0.5f, 0, 1), }; GameObjectIter end = m_asteroids.end(); for(GameObjectIter it = m_asteroids.begin(); it != end; ++it) { glm::mat4 transform = it->TransformMatrix(); for(int i = 0; i < sizeof(verts) / sizeof(*verts); ++i) FillVertexBuffer(m_vertexBuffer, glm::vec3(transform * verts[i]), glm::vec4(1, 0, 0, 1)); } end = m_asteroidFallout.end(); for(GameObjectIter it = m_asteroidFallout.begin(); it != end; ++it) { glm::mat4 transform = it->TransformMatrix(); for(int i = 0; i < sizeof(verts) / sizeof(*verts); ++i) FillVertexBuffer(m_vertexBuffer, glm::vec3(transform * verts[i]), glm::vec4(1, 0.7f, 0, 1)); } } void Asteroids::DrawBullets(void) { glm::vec4 verts[] = { glm::vec4(0.5f, 0, 0, 1), glm::vec4(-0.5f, 0.5f, 0, 1), glm::vec4(-0.5f, 0.5f, 0, 1), glm::vec4(-0.5f, -0.5f, 0, 1), glm::vec4(-0.5f, -0.5f, 0, 1), glm::vec4(0.5f, 0, 0, 1), }; GameObjectIter end = m_bullets.end(); for(GameObjectIter it = m_bullets.begin(); it != end; ++it) { glm::mat4 transform = it->TransformMatrix(); for(int i = 0; i < sizeof(verts) / sizeof(*verts); ++i) FillVertexBuffer(m_vertexBuffer, glm::vec3(transform * verts[i]), glm::vec4(0, 0.5f, 1, 1)); } } void Asteroids::DrawRocket(void) { glm::vec4 verts[] = { glm::vec4(0.5f, 0, 0, 1), glm::vec4(-0.5f, 0.5f, 0, 1), glm::vec4(-0.5f, 0.5f, 0, 1), glm::vec4(-0.5f, -0.5f, 0, 1), glm::vec4(-0.5f, -0.5f, 0, 1), glm::vec4(0.5f, 0, 0, 1), }; GameObjectIter end = m_rocketThrustParticles.end(); for(GameObjectIter it = m_rocketThrustParticles.begin(); it != end; ++it) { glm::mat4 transform = it->TransformMatrix(); for(int i = 0; i < sizeof(verts) / sizeof(*verts); ++i) FillVertexBuffer(m_vertexBuffer, glm::vec3(transform * verts[i]), it->m_color); } } void Asteroids::DrawLasers(void) { for(LaserIter it = m_lasers.begin(); it != m_lasers.end(); ++it) { glm::vec2 dir2(it->m_dir.y, -it->m_dir.x); glm::vec2 lowerRight(it->m_pos + dir2 * 10.0f); glm::vec2 upperRight(it->m_pos - dir2 * 10.0f); glm::vec2 lowerLeft(lowerRight + it->m_dir * 100000.0f); glm::vec2 upperLeft(upperRight + it->m_dir * 100000.0f); float alpha = 1; if(it->m_lifeTime < 1) alpha = it->m_lifeTime; FillVertexBuffer(m_vertexBuffer, glm::vec3(lowerRight, 0), glm::vec4(0, 1, 1, alpha)); FillVertexBuffer(m_vertexBuffer, glm::vec3(upperRight, 0), glm::vec4(0, 1, 1, alpha)); FillVertexBuffer(m_vertexBuffer, glm::vec3(lowerLeft, 0), glm::vec4(0, 1, 1, alpha)); FillVertexBuffer(m_vertexBuffer, glm::vec3(upperRight, 0), glm::vec4(0, 1, 1, alpha)); FillVertexBuffer(m_vertexBuffer, glm::vec3(upperLeft, 0), glm::vec4(0, 1, 1, alpha)); FillVertexBuffer(m_vertexBuffer, glm::vec3(lowerLeft, 0), glm::vec4(0, 1, 1, alpha)); } } void Asteroids::CreateFBO(void) { bool swapDimensions = m_orientation == DisplayOrientations::Portrait || m_orientation == DisplayOrientations::PortraitFlipped; glGenFramebuffers(8, m_offscreenFBO); glGenTextures(8, m_offscreenTex); for(int i = 0; i < 4; ++i) { int width = (swapDimensions) ? RENDER_TARGET_HEIGHT >> i : RENDER_TARGET_WIDTH >> i; int height = (swapDimensions) ? RENDER_TARGET_WIDTH >> i : RENDER_TARGET_HEIGHT >> i; glBindFramebuffer(GL_FRAMEBUFFER, m_offscreenFBO[i]); glBindTexture(GL_TEXTURE_2D, m_offscreenTex[i]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_offscreenTex[i], 0); if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) throw FBOIncompleteException(); glBindFramebuffer(GL_FRAMEBUFFER, m_offscreenFBO[i + 4]); glBindTexture(GL_TEXTURE_2D, m_offscreenTex[i + 4]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_offscreenTex[i + 4], 0); if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) throw FBOIncompleteException(); } glBindTexture(GL_TEXTURE_2D, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); } IFrameworkView^ Direct3DApplicationSource::CreateView() { return ref new Asteroids(); } [Platform::MTAThread] int main(Platform::Array<Platform::String^>^) { auto direct3DApplicationSource = ref new Direct3DApplicationSource(); CoreApplication::Run(direct3DApplicationSource); return 0; }
37.473418
144
0.596744
agramonte
9995e36c1017e036a5b84650d2593e276195d63f
19,392
cpp
C++
src-plugins/v3dView/v3dViewFiberInteractor.cpp
gpasquie/medInria-public
1efa82292698695f6ee69fe00114aabce5431246
[ "BSD-4-Clause" ]
null
null
null
src-plugins/v3dView/v3dViewFiberInteractor.cpp
gpasquie/medInria-public
1efa82292698695f6ee69fe00114aabce5431246
[ "BSD-4-Clause" ]
null
null
null
src-plugins/v3dView/v3dViewFiberInteractor.cpp
gpasquie/medInria-public
1efa82292698695f6ee69fe00114aabce5431246
[ "BSD-4-Clause" ]
null
null
null
/*========================================================================= medInria Copyright (c) INRIA 2013. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include "v3dViewFiberInteractor.h" #include <dtkCore/dtkAbstractData.h> #include <dtkCore/dtkAbstractDataFactory.h> #include <dtkCore/dtkAbstractView.h> #include <dtkCore/dtkAbstractViewFactory.h> #include <medMessageController.h> #include <vtkSmartPointer.h> #include <vtkPolyData.h> #include <vtkFiberDataSetManager.h> #include <vtkImageView.h> #include <vtkImageView2D.h> #include <vtkImageView3D.h> #include <vtkLimitFibersToVOI.h> #include <vtkPointData.h> #include <vtkLookupTableManager.h> #include <vtkFiberDataSet.h> #include <vtkMatrix4x4.h> #include <vtkLimitFibersToROI.h> #include <vtkIsosurfaceManager.h> #include <itkImage.h> #include <itkImageToVTKImageFilter.h> #include <itkFiberBundleStatisticsCalculator.h> #include "v3dView.h" #include "medVtkView.h" #include <QInputDialog> #include <QColorDialog> class v3dViewFiberInteractorPrivate { public: dtkAbstractData *data; v3dView *view; dtkAbstractData *projectionData; vtkFiberDataSetManager *manager; vtkIsosurfaceManager *roiManager; vtkSmartPointer<vtkFiberDataSet> dataset; QMap<QString, double> meanFAList; QMap<QString, double> minFAList; QMap<QString, double> maxFAList; QMap<QString, double> varFAList; QMap<QString, double> meanADCList; QMap<QString, double> minADCList; QMap<QString, double> maxADCList; QMap<QString, double> varADCList; QMap<QString, double> meanLengthList; QMap<QString, double> minLengthList; QMap<QString, double> maxLengthList; QMap<QString, double> varLengthList; }; v3dViewFiberInteractor::v3dViewFiberInteractor(): medAbstractVtkViewInteractor(), d(new v3dViewFiberInteractorPrivate) { d->data = 0; d->dataset = 0; d->view = 0; d->manager = vtkFiberDataSetManager::New(); d->manager->SetHelpMessageVisibility(0); d->roiManager = vtkIsosurfaceManager::New(); // d->manager->SetBoxWidget (0); vtkLookupTable* lut = vtkLookupTableManager::GetSpectrumLookupTable(); d->manager->SetLookupTable(lut); lut->Delete(); } v3dViewFiberInteractor::~v3dViewFiberInteractor() { this->disable(); d->manager->Delete(); d->roiManager->Delete(); delete d; d = 0; } QString v3dViewFiberInteractor::description() const { return tr("Interactor to help visualising Fibers"); } QString v3dViewFiberInteractor::identifier() const { return "v3dViewFiberInteractor"; } QStringList v3dViewFiberInteractor::handled() const { return QStringList () << v3dView::s_identifier() << medVtkView::s_identifier(); } bool v3dViewFiberInteractor::isDataTypeHandled(QString dataType) const { if (dataType == "v3dDataFibers") return true; return false; } bool v3dViewFiberInteractor::registered() { return dtkAbstractViewFactory::instance()->registerViewInteractorType("v3dViewFiberInteractor", QStringList () << v3dView::s_identifier() << medVtkView::s_identifier(), createV3dViewFiberInteractor); } void v3dViewFiberInteractor::setData(dtkAbstractData *data) { if (!data) return; if (data->identifier()=="v3dDataFibers") { if (vtkFiberDataSet *dataset = static_cast<vtkFiberDataSet *>(data->data())) { d->dataset = dataset; d->manager->SetInput (d->dataset); if (!data->hasMetaData("BundleList")) data->addMetaData("BundleList", QStringList()); if (!data->hasMetaData("BundleColorList")) data->addMetaData("BundleColorList", QStringList()); // add bundles to 2d vtkFiberDataSet::vtkFiberBundleListType bundles = d->dataset->GetBundleList(); vtkFiberDataSet::vtkFiberBundleListType::iterator it = bundles.begin(); while (it!=bundles.end()) { if (d->view) d->view->renderer2d()->AddActor( d->manager->GetBundleActor ((*it).first )); ++it; } this->clearStatistics(); d->data = data; } } } dtkAbstractData *v3dViewFiberInteractor::data() { return d->data; } void v3dViewFiberInteractor::setView(dtkAbstractView *view) { if (v3dView *v3dview = qobject_cast<v3dView*>(view) ) { d->view = v3dview; d->manager->SetRenderer( d->view->renderer3d() ); d->manager->SetRenderWindowInteractor( d->view->interactor() ); d->view->renderer2d()->AddActor( d->manager->GetOutput() ); d->roiManager->SetRenderWindowInteractor( d->view->interactor() ); } } dtkAbstractView *v3dViewFiberInteractor::view() { return d->view; } void v3dViewFiberInteractor::enable() { if (this->enabled()) return; if (d->view) { d->manager->Enable(); d->roiManager->Enable(); if (d->dataset) { vtkFiberDataSet::vtkFiberBundleListType bundles = d->dataset->GetBundleList(); vtkFiberDataSet::vtkFiberBundleListType::iterator it = bundles.begin(); while (it!=bundles.end()) { if (d->view) d->view->renderer2d()->AddActor( d->manager->GetBundleActor ((*it).first )); ++it; } } } dtkAbstractViewInteractor::enable(); } void v3dViewFiberInteractor::disable() { if (!this->enabled()) return; if (d->view) { d->manager->Disable(); d->roiManager->Disable(); if (d->dataset) { vtkFiberDataSet::vtkFiberBundleListType bundles = d->dataset->GetBundleList(); vtkFiberDataSet::vtkFiberBundleListType::iterator it = bundles.begin(); while (it!=bundles.end()) { if (d->view) d->view->renderer2d()->RemoveActor( d->manager->GetBundleActor ((*it).first )); ++it; } } } dtkAbstractViewInteractor::disable(); } void v3dViewFiberInteractor::setVisibility(bool visible) { d->manager->SetVisibility(visible); } void v3dViewFiberInteractor::setBoxVisibility(bool visible) { if (d->view && d->view->property("Orientation") != "3D") { medMessageController::instance()->showError("View must be in 3D mode to activate the bundling box", 3000); d->manager->SetBoxWidget(false); return; } d->manager->SetBoxWidget(visible); d->view->update(); } void v3dViewFiberInteractor::setRenderingMode(RenderingMode mode) { switch(mode) { case v3dViewFiberInteractor::Lines: d->manager->SetRenderingModeToPolyLines(); break; case v3dViewFiberInteractor::Ribbons: d->manager->SetRenderingModeToRibbons(); break; case v3dViewFiberInteractor::Tubes: d->manager->SetRenderingModeToTubes(); break; default: qDebug() << "v3dViewFiberInteractor: unknown rendering mode"; } d->view->update(); } void v3dViewFiberInteractor::activateGPU(bool activate) { if (activate) { vtkFibersManager::UseHardwareShadersOn(); d->manager->ChangeMapperToUseHardwareShaders(); } else { vtkFibersManager::UseHardwareShadersOff(); d->manager->ChangeMapperToDefault(); } d->view->update(); } void v3dViewFiberInteractor::setColorMode(ColorMode mode) { switch(mode) { case v3dViewFiberInteractor::Local: d->manager->SetColorModeToLocalFiberOrientation(); break; case v3dViewFiberInteractor::Global: d->manager->SetColorModelToGlobalFiberOrientation(); break; case v3dViewFiberInteractor::FA: d->manager->SetColorModeToLocalFiberOrientation(); for (int i=0; i<d->manager->GetNumberOfPointArrays(); i++) { if (d->manager->GetPointArrayName (i)) { if (strcmp ( d->manager->GetPointArrayName (i), "FA")==0) { d->manager->SetColorModeToPointArray (i); break; } } } break; default: qDebug() << "v3dViewFiberInteractor: unknown color mode"; } d->view->update(); } void v3dViewFiberInteractor::setBoxBooleanOperation(BooleanOperation op) { switch(op) { case v3dViewFiberInteractor::Plus: d->manager->GetVOILimiter()->SetBooleanOperationToAND(); break; case v3dViewFiberInteractor::Minus: d->manager->GetVOILimiter()->SetBooleanOperationToNOT(); break; default: qDebug() << "v3dViewFiberInteractor: Unknown boolean operations"; } d->manager->GetVOILimiter()->Modified(); d->view->update(); } void v3dViewFiberInteractor::tagSelection() { d->manager->SwapInputOutput(); d->view->update(); } void v3dViewFiberInteractor::resetSelection() { d->manager->Reset(); d->view->update(); } void v3dViewFiberInteractor::validateSelection(const QString &name, const QColor &color) { if (!d->data) return; double color_d[3] = {(double)color.red()/255.0, (double)color.green()/255.0, (double)color.blue()/255.0}; d->manager->Validate (name.toAscii().constData(), color_d); d->view->renderer2d()->AddActor (d->manager->GetBundleActor(name.toAscii().constData())); d->data->addMetaData("BundleList", name); d->data->addMetaData("BundleColorList", color.name()); // reset to initial navigation state d->manager->Reset(); d->view->update(); } void v3dViewFiberInteractor::computeBundleFAStatistics (const QString &name, double &mean, double &min, double &max, double &var) { itk::FiberBundleStatisticsCalculator::Pointer statCalculator = itk::FiberBundleStatisticsCalculator::New(); statCalculator->SetInput (d->dataset->GetBundle (name.toAscii().constData()).Bundle); try { statCalculator->Compute(); } catch(itk::ExceptionObject &e) { qDebug() << e.GetDescription(); mean = 0.0; min = 0.0; max = 0.0; var = 0.0; return; } statCalculator->GetFAStatistics(mean, min, max, var); } void v3dViewFiberInteractor::bundleFAStatistics(const QString &name, double &mean, double &min, double &max, double &var) { if (!d->meanFAList.contains(name)) { this->computeBundleFAStatistics(name, mean, min, max, var); d->meanFAList[name] = mean; d->minFAList[name] = min; d->maxFAList[name] = max; d->varFAList[name] = var; } else { mean = d->meanFAList[name]; min = d->minFAList[name]; max = d->maxFAList[name]; var = d->varFAList[name]; } } void v3dViewFiberInteractor::computeBundleADCStatistics (const QString &name, double &mean, double &min, double &max, double &var) { itk::FiberBundleStatisticsCalculator::Pointer statCalculator = itk::FiberBundleStatisticsCalculator::New(); statCalculator->SetInput (d->dataset->GetBundle (name.toAscii().constData()).Bundle); try { statCalculator->Compute(); } catch(itk::ExceptionObject &e) { qDebug() << e.GetDescription(); mean = 0.0; min = 0.0; max = 0.0; var = 0.0; return; } statCalculator->GetADCStatistics(mean, min, max, var); } void v3dViewFiberInteractor::bundleADCStatistics(const QString &name, double &mean, double &min, double &max, double &var) { if (!d->meanADCList.contains(name)) { this->computeBundleADCStatistics(name, mean, min, max, var); d->meanADCList[name] = mean; d->minADCList[name] = min; d->maxADCList[name] = max; d->varADCList[name] = var; } else { mean = d->meanADCList[name]; min = d->minADCList[name]; max = d->maxADCList[name]; var = d->varADCList[name]; } } void v3dViewFiberInteractor::computeBundleLengthStatistics (const QString &name, double &mean, double &min, double &max, double &var) { itk::FiberBundleStatisticsCalculator::Pointer statCalculator = itk::FiberBundleStatisticsCalculator::New(); statCalculator->SetInput (d->dataset->GetBundle (name.toAscii().constData()).Bundle); try { statCalculator->Compute(); } catch(itk::ExceptionObject &e) { qDebug() << e.GetDescription(); mean = 0.0; min = 0.0; max = 0.0; var = 0.0; return; } statCalculator->GetLengthStatistics(mean, min, max, var); } void v3dViewFiberInteractor::bundleLengthStatistics(const QString &name, double &mean, double &min, double &max, double &var) { if (!d->meanLengthList.contains(name)) { this->computeBundleLengthStatistics(name, mean, min, max, var); d->meanLengthList[name] = mean; d->minLengthList[name] = min; d->maxLengthList[name] = max; d->varLengthList[name] = var; } else { mean = d->meanLengthList[name]; min = d->minLengthList[name]; max = d->maxLengthList[name]; var = d->varLengthList[name]; } } void v3dViewFiberInteractor::clearStatistics(void) { d->meanFAList.clear(); d->minFAList.clear(); d->maxFAList.clear(); d->varFAList.clear(); d->meanADCList.clear(); d->minADCList.clear(); d->maxADCList.clear(); d->varADCList.clear(); d->meanLengthList.clear(); d->minLengthList.clear(); d->maxLengthList.clear(); d->varLengthList.clear(); } void v3dViewFiberInteractor::setProjection(const QString& value) { if (!d->view) return; if (value=="true") { d->view->view2d()->AddDataSet( d->manager->GetCallbackOutput() ); } } void v3dViewFiberInteractor::setRadius (int value) { d->manager->SetRadius (value); if (d->view) d->view->update(); } void v3dViewFiberInteractor::setROI(dtkAbstractData *data) { if (!data) return; if (data->identifier()!="itkDataImageUChar3") return; typedef itk::Image<unsigned char, 3> ROIType; ROIType::Pointer roiImage = static_cast<ROIType*>(data->data()); if (!roiImage.IsNull()) { itk::ImageToVTKImageFilter<ROIType>::Pointer converter = itk::ImageToVTKImageFilter<ROIType>::New(); converter->SetReferenceCount(2); converter->SetInput(roiImage); converter->Update(); ROIType::DirectionType directions = roiImage->GetDirection(); vtkMatrix4x4 *matrix = vtkMatrix4x4::New(); matrix->Identity(); for (int i=0; i<3; i++) for (int j=0; j<3; j++) matrix->SetElement (i, j, directions (i,j)); d->manager->Reset(); d->manager->GetROILimiter()->SetMaskImage (converter->GetOutput()); d->manager->GetROILimiter()->SetDirectionMatrix (matrix); ROIType::PointType origin = roiImage->GetOrigin(); vtkMatrix4x4 *matrix2 = vtkMatrix4x4::New(); matrix2->Identity(); for (int i=0; i<3; i++) for (int j=0; j<3; j++) matrix2->SetElement (i, j, directions (i,j)); double v_origin[4], v_origin2[4]; for (int i=0; i<3; i++) v_origin[i] = origin[i]; v_origin[3] = 1.0; matrix->MultiplyPoint (v_origin, v_origin2); for (int i=0; i<3; i++) matrix2->SetElement (i, 3, v_origin[i]-v_origin2[i]); d->roiManager->SetInput (converter->GetOutput()); d->roiManager->SetDirectionMatrix (matrix2); // d->manager->GetROILimiter()->Update(); d->roiManager->GenerateData(); matrix->Delete(); matrix2->Delete(); } else { d->manager->GetROILimiter()->SetMaskImage (0); d->manager->GetROILimiter()->SetDirectionMatrix (0); d->roiManager->ResetData(); } d->view->update(); } void v3dViewFiberInteractor::setRoiBoolean(int roi, int meaning) { d->manager->GetROILimiter()->SetBooleanOperation (roi, meaning); d->view->update(); } int v3dViewFiberInteractor::roiBoolean(int roi) { return d->manager->GetROILimiter()->GetBooleanOperationVector()[roi+1]; } void v3dViewFiberInteractor::setBundleVisibility(const QString &name, bool visibility) { d->manager->SetBundleVisibility(name.toAscii().constData(), (int)visibility); d->view->update(); } bool v3dViewFiberInteractor::bundleVisibility(const QString &name) const { return d->manager->GetBundleVisibility(name.toAscii().constData()); } void v3dViewFiberInteractor::setAllBundlesVisibility(bool visibility) { if (visibility) d->manager->ShowAllBundles(); else d->manager->HideAllBundles(); d->view->update(); } void v3dViewFiberInteractor::setOpacity(dtkAbstractData * /*data*/, double /*opacity*/) { } double v3dViewFiberInteractor::opacity(dtkAbstractData * /*data*/) const { //TODO return 100; } void v3dViewFiberInteractor::setVisible(dtkAbstractData * /*data*/, bool /*visible*/) { //TODO } bool v3dViewFiberInteractor::isVisible(dtkAbstractData * /*data*/) const { //TODO return true; } // ///////////////////////////////////////////////////////////////// // Type instantiation // ///////////////////////////////////////////////////////////////// dtkAbstractViewInteractor *createV3dViewFiberInteractor() { return new v3dViewFiberInteractor; }
29.248869
146
0.569565
gpasquie
9995eeacaf1d87cdb211400fd56c8653626272fd
28,059
cpp
C++
cpp-projects/base/files/assimp_loader.cpp
FlorianLance/toolbox
87882a14ec86852d90527c81475b451b9f6e12cf
[ "MIT" ]
null
null
null
cpp-projects/base/files/assimp_loader.cpp
FlorianLance/toolbox
87882a14ec86852d90527c81475b451b9f6e12cf
[ "MIT" ]
null
null
null
cpp-projects/base/files/assimp_loader.cpp
FlorianLance/toolbox
87882a14ec86852d90527c81475b451b9f6e12cf
[ "MIT" ]
1
2021-07-06T14:47:41.000Z
2021-07-06T14:47:41.000Z
/******************************************************************************* ** Toolbox-base ** ** MIT License ** ** Copyright (c) [2018] [Florian Lance] ** ** ** ** Permission is hereby granted, free of charge, to any person obtaining a ** ** copy of this software and associated documentation files (the "Software"), ** ** to deal in the Software without restriction, including without limitation ** ** the rights to use, copy, modify, merge, publish, distribute, sublicense, ** ** and/or sell copies of the Software, and to permit persons to whom the ** ** Software is furnished to do so, subject to the following conditions: ** ** ** ** The above copyright notice and this permission notice shall be included in ** ** all copies or substantial portions of the Software. ** ** ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ** ** THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ** ** FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ** ** DEALINGS IN THE SOFTWARE. ** ** ** ********************************************************************************/ #include "assimp_loader.hpp" // std #include <filesystem> #include <algorithm> // assimp #include <assimp/Importer.hpp> #include <assimp/postprocess.h> using namespace tool::geo; using namespace tool::files; //Texture2D *AiLoader::read_texture(Model *model, aiMaterial *mat, aiTextureType type, unsigned int index){ // // ai data // aiString path; // receives the path to the texture. If the texture is embedded, receives a '*' followed by the id of the texture // // (for the textures stored in the corresponding scene) which can be converted to an int using a function like atoi. NULL is a valid value // aiTextureMapping mapping; // texture mapping, NULL is allowed as value // unsigned int uvIndex; // uv index of the texture (NULL is valid value) // ai_real blend; // blend factor for the texture // aiTextureOp operation; // texture operation to be performed between this texture and the previous texture // aiTextureMapMode mapMode[3];// mapping modes to be used for the texture, the parameter may be NULL but if it is a valid pointer it MUST // // point to an array of 3 aiTextureMapMode's (one for each axis: UVW order (=XYZ)). // mat->GetTexture(type, index, &path, &mapping, &uvIndex, &blend, &operation, &mapMode[0]); // // auto wrapping = read_texture_property<int>(MatP::text_mapping, aiMat, texturesPerType.first, ii).value(); // // auto uvwSource = read_texture_property<int>(MatP::text_uvw_source, aiMat, texturesPerType.first, ii).value(); // // auto mappingModeU = read_texture_property<int>(MatP::text_mapping_mode_u, aiMat, texturesPerType.first, ii).value(); // // auto mappingModeV = read_texture_property<int>(MatP::text_mapping_mode_v, aiMat, texturesPerType.first, ii).value(); // // auto flags = read_texture_property<int>(MatP::text_flags, aiMat, texturesPerType.first, ii).value(); // // auto texmapAxis = read_texture_property<aiVector3D>(MatP::text_texmap_axis, aiMat, texturesPerType.first, ii).value(); // // auto blend = read_texture_property<float>(MatP::text_blend, aiMat, texturesPerType.first, ii).value(); // // find texture // namespace fs = std::filesystem; // const std::string aiPath = path.C_Str(); // if(aiPath.length() > 0){ // if(aiPath[0] == '*'){ // std::cout << "[ASSIMP_LOADER] Embedded texture detected, not managed yet\n"; // return nullptr; // } // } // fs::path texturePath = aiPath; // if(!fs::exists(texturePath)){ // check if full path exist // fs::path dirPath = model->directory; // std_v1<fs::path> pathsToTest; // pathsToTest.emplace_back(dirPath / texturePath.filename()); // pathsToTest.emplace_back(dirPath / "texture" / texturePath.filename()); // pathsToTest.emplace_back(dirPath / "textures" / texturePath.filename()); // pathsToTest.emplace_back(dirPath / ".." / "texture" / texturePath.filename()); // pathsToTest.emplace_back(dirPath / ".." / "textures" / texturePath.filename()); // bool found = false; // for(const auto &pathToTest : pathsToTest){ // if(fs::exists(pathToTest)){ // found = true; // texturePath = pathToTest; // break; // } // } // if(!found){ // std::cerr << "[ASSIMP_LOADER] Cannot find texture " << texturePath.filename() << "\n"; // return nullptr; // } // } // std::string foundPath = texturePath.u8string(); // auto textures = &model->m_textures; // if(textures->count(foundPath) == 0){ // // load texture // Texture2D texture(foundPath); // // type // texture.type = get_texture_type(type); // // mapping // texture.mapping = get_texture_mapping(mapping); // // operation // texture.operation = get_texture_operation(operation); // // mapMode // texture.mapMode = Pt3<TexMapMode>{get_texture_map_mode(mapMode[0]),get_texture_map_mode(mapMode[1]),get_texture_map_mode(mapMode[2])}; // // add texture to model // (*textures)[foundPath] = std::move(texture); // } // return &(*textures)[foundPath]; //} std::shared_ptr<Model> AiLoader::load_model(std::string path, bool verbose){ if(verbose){ std::cout << "[ASSIMP_LOADER] Load model with path: " << path << "\n"; } namespace fs = std::filesystem; fs::path pathModel = path; if(!fs::exists(pathModel)){ // throw std::runtime_error("[ASSIMP_LOADER] Path " + path + " doesn't exists, cannot load model.\n"); std::cerr << "[ASSIMP_LOADER] Path " << path << " doesn't exists, cannot load model.\n"; return nullptr; } // read from assimp Assimp::Importer import; const aiScene *scene = import.ReadFile(path, aiProcess_Triangulate); // aiProcess_EmbedTextures / aiProcess_FlipUVs if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode){ std::cerr << "[ASSIMP_LOADER] " << import.GetErrorString() << "\n"; return nullptr; } // create model auto model = std::make_shared<Model>(); model->directory = pathModel.parent_path().string(); model->name = scene->mRootNode->mName.C_Str(); if(verbose){ std::cout << "[ASSIMP_LOADER] Model name: " << model->name << "\n"; } // retrieve global inverse transform model->globalInverseTr = scene->mRootNode->mTransformation; model->globalInverseTr.Inverse(); auto m = scene->mRootNode->mTransformation; m.Inverse(); model->globalInverseTr2 = geo::Mat4f{ m.a1,m.a2,m.a3,m.a4, m.b1,m.b2,m.b3,m.b4, m.c1,m.c2,m.c3,m.c4, m.d1,m.d2,m.d3,m.d4, }; // aiVector3t<float> aiTr,aiRot,aiSc; // m_GlobalInverseTransform.Decompose(aiSc,aiRot,aiTr); // auto r = geo::Pt3f{aiRot.x,aiRot.y,aiRot.z}; // model->globalInverseTr = geo::Mat4f::transform( // geo::Pt3f{aiSc.x,aiSc.y,aiSc.z}, // geo::Pt3f{rad_2_deg(r.x()),rad_2_deg(r.y()),rad_2_deg(r.z())}, // geo::Pt3f{aiTr.x,aiTr.y,aiTr.z} // ); // std::cout << "GLOBAL INVERSE:\n " <<geo::Pt3f{aiSc.x,aiSc.y,aiSc.z} << " " << geo::Pt3f{rad_2_deg(r.x()),rad_2_deg(r.y()),rad_2_deg(r.z())} << " "<< geo::Pt3f{aiTr.x,aiTr.y,aiTr.z} << "\n"; // // read embedded textures // EMBEDDED // if(scene->HasTextures()){ // for(size_t ii = 0; ii < scene->mNumTextures; ++ii){ // auto aiTexture = scene->mTextures[ii]; // std::string file = aiTexture->mFilename.C_Str(); // std::cout << "embedded texture " << ii << " " << file << " " << aiTexture->mWidth << " " << aiTexture->mHeight << "\n"; // for(size_t jj = 0; jj < aiTexture->mWidth * aiTexture->mHeight; ++jj){ // aiTexture->pcData->r; // aiTexture->pcData->g; // aiTexture->pcData->b; // aiTexture->pcData->a; // } // } // } // retrieve materials if(scene->HasMaterials()){ if(verbose){ std::cout << "[ASSIMP_LOADER] Load materials: " << scene->mNumMaterials << "\n"; } for(size_t ii = 0; ii < scene->mNumMaterials; ++ii){ read_material(model.get(), scene->mMaterials[ii]); } } // retrieve meshes if(scene->HasMeshes()){ if(verbose){ std::cout << "[ASSIMP_LOADER] Load meshes: " << scene->mNumMeshes << "\n"; } for(size_t ii = 0; ii < scene->mNumMeshes; ++ii){ if(verbose){ std::cout << "[ASSIMP_LOADER] Mesh: " << scene->mMeshes[ii]->mName.C_Str() << "\n"; } read_mesh(model.get(), scene->mMeshes[ii]); } } // retrieve animations if(scene->HasAnimations()){ if(verbose){ std::cout << "[ASSIMP_LOADER] Load animations: " << scene->mNumAnimations << "\n"; } for(size_t ii = 0; ii < scene->mNumAnimations; ++ii){ if(verbose){ std::cout << "[ASSIMP_LOADER] Animation: " << scene->mAnimations[ii]->mName.C_Str() << "\n"; } auto assimpAnimation = scene->mAnimations[ii]; graphics::Animation animation; animation.duration = assimpAnimation->mDuration; animation.ticksPerSecond = assimpAnimation->mTicksPerSecond; animation.name = assimpAnimation->mName.C_Str(); for(size_t jj = 0; jj < assimpAnimation->mNumChannels; ++jj){ auto assimpChannel = assimpAnimation->mChannels[jj]; const std::string affectedNodeName = assimpChannel->mNodeName.C_Str(); tool::graphics::AnimationKeys keys; keys.positionTimes.resize(assimpChannel->mNumPositionKeys); keys.positionKeys.resize(assimpChannel->mNumPositionKeys); for(size_t kk = 0; kk < keys.positionTimes.size(); ++kk){ auto &key = assimpChannel->mPositionKeys[kk]; keys.positionTimes[kk] = key.mTime; keys.positionKeys[kk] = {key.mValue.x,key.mValue.y,key.mValue.z}; } keys.rotationTimes.resize(assimpChannel->mNumRotationKeys); keys.rotationKeys.resize(assimpChannel->mNumRotationKeys); for(size_t kk = 0; kk < keys.rotationTimes.size(); ++kk){ auto &key = assimpChannel->mRotationKeys[kk]; keys.rotationTimes[kk] = key.mTime; keys.rotationKeys[kk] = {key.mValue.x,key.mValue.y,key.mValue.z, key.mValue.w}; } keys.scalingTimes.resize(assimpChannel->mNumScalingKeys); keys.scalingKeys.resize(assimpChannel->mNumScalingKeys); for(size_t kk = 0; kk < keys.scalingTimes.size(); ++kk){ auto &key = assimpChannel->mScalingKeys[kk]; keys.scalingTimes[kk] = key.mTime; keys.scalingKeys[kk] = {key.mValue.x,key.mValue.y,key.mValue.z}; } model->animationsKeys[animation.name][affectedNodeName] = std::move(keys); } model->animations.emplace_back(std::move(animation)); } } // bones read_bones_hierarchy(&model->bonesHierachy, scene->mRootNode); return model; } void AiLoader::read_mesh(Model *model, aiMesh *aiMesh){ bool verbose = false; auto gmesh = std::make_shared<GMesh>(); gmesh->name = aiMesh->mName.C_Str(); gmesh->material = &model->m_materials[aiMesh->mMaterialIndex]; Mesh *mesh = &gmesh->mesh; bool hasPoints = aiMesh->mPrimitiveTypes & aiPrimitiveType::aiPrimitiveType_POINT; bool hasLines = aiMesh->mPrimitiveTypes & aiPrimitiveType::aiPrimitiveType_LINE; bool hasTriangles = aiMesh->mPrimitiveTypes & aiPrimitiveType::aiPrimitiveType_TRIANGLE; bool hasPolygons = aiMesh->mPrimitiveTypes & aiPrimitiveType::aiPrimitiveType_POLYGON; // process vertex positions, normals and texture coordinates mesh->vertices.reserve(aiMesh->mNumVertices); if(aiMesh->HasNormals()){ mesh->normals.reserve(aiMesh->mNumVertices); } if(aiMesh->HasTextureCoords(0)){ mesh->tCoords.reserve(aiMesh->mNumVertices); }else{ mesh->tCoords.resize(aiMesh->mNumVertices); std::fill(std::begin(mesh->tCoords), std::end(mesh->tCoords), Pt2f{0.f,0.f}); } if(aiMesh->HasTangentsAndBitangents()){ mesh->tangents.resize(aiMesh->mNumVertices); } if(aiMesh->HasVertexColors(0)){ mesh->colors.reserve(aiMesh->mNumVertices); } if(aiMesh->HasBones()){ mesh->bones.resize(aiMesh->mNumVertices); } for(unsigned int ii = 0; ii < aiMesh->mNumVertices; ii++){ // position mesh->vertices.emplace_back(Pt3f{aiMesh->mVertices[ii].x, aiMesh->mVertices[ii].y, aiMesh->mVertices[ii].z}); // normal if(aiMesh->HasNormals()){ mesh->normals.emplace_back(Vec3f{aiMesh->mNormals[ii].x, aiMesh->mNormals[ii].y, aiMesh->mNormals[ii].z}); } // uv // aiMesh->GetNumUVChannels() if(aiMesh->HasTextureCoords(0)){ mesh->tCoords.emplace_back(Pt2f{aiMesh->mTextureCoords[0][ii].x, aiMesh->mTextureCoords[0][ii].y}); } // tangents if(aiMesh->HasTangentsAndBitangents()){ mesh->tangents.emplace_back(Pt4f{aiMesh->mTangents->x,aiMesh->mTangents->y,aiMesh->mTangents->z,1.f}); } // colors // aiMesh->GetNumColorChannels() if(aiMesh->HasVertexColors(0)){ mesh->colors.emplace_back(Pt4f{ aiMesh->mColors[0][ii].r, aiMesh->mColors[0][ii].g, aiMesh->mColors[0][ii].b, aiMesh->mColors[0][ii].a }); } // aiMesh->mBitangents // aiMesh->mMethod // aiMesh->mAnimMeshes } // process indices if(hasTriangles && !hasPoints && !hasLines && !hasPolygons){ mesh->triIds.reserve(aiMesh->mNumFaces); for(unsigned int ii = 0; ii < aiMesh->mNumFaces; ii++){ aiFace face = aiMesh->mFaces[ii]; mesh->triIds.emplace_back(TriIds{face.mIndices[0], face.mIndices[1], face.mIndices[2]}); } }else{ std::cerr << "[ASSIMP_LOADER] Face format not managed.\n"; } // compute normals if necessary if(!aiMesh->HasNormals()){ mesh->generate_normals(); } // generate tangents if necessary if(!aiMesh->HasTangentsAndBitangents() && (mesh->normals.size() > 0) && aiMesh->HasTextureCoords(0)){ mesh->generate_tangents(); } // if(mesh->tangents.size() != mesh->vertices.size()){ // std::cout << "[ASSIMP_LOADER] Invalid tangents. Recomputing.\n"; // mesh->generate_tangents(); // } // bones if(aiMesh->HasBones()){ // for (uint i = 0 ; i < pMesh->mNumBones ; i++) { // uint BoneIndex = 0; // string BoneName(pMesh->mBones[i]->mName.data); // if (m_BoneMapping.find(BoneName) == m_BoneMapping.end()) { // BoneIndex = m_NumBones; // m_NumBones++; // BoneInfo bi; // m_BoneInfo.push_back(bi); // } // else { // BoneIndex = m_BoneMapping[BoneName]; // } // m_BoneMapping[BoneName] = BoneIndex; // m_BoneInfo[BoneIndex].BoneOffset = pMesh->mBones[i]->mOffsetMatrix; // for (uint j = 0 ; j < pMesh->mBones[i]->mNumWeights ; j++) { // uint VertexID = m_Entries[MeshIndex].BaseVertex + pMesh->mBones[i]->mWeights[j].mVertexId; // float Weight = pMesh->mBones[i]->mWeights[j].mWeight; // Bones[VertexID].AddBoneData(BoneIndex, Weight); // } // } if(verbose){ std::cout << "Num bones: " << aiMesh->mNumBones << "\n"; } for(size_t ii = 0; ii < aiMesh->mNumBones; ++ii){ unsigned int boneIndex = 0; auto bone = aiMesh->mBones[ii]; std::string boneName(bone->mName.C_Str()); if(verbose){ std::cout << "Bone: " << boneName << "\n"; } if(model->bonesMapping.count(boneName) == 0){ boneIndex = static_cast<unsigned int>(model->bonesMapping.size()); model->bonesInfo.emplace_back(graphics::BoneInfo{}); // model->bonesMapping[boneName] = boneIndex; if(verbose){ std::cout << "Add bone in mapping, current index: " << boneIndex << " " << model->bonesMapping.size() << "\n"; } }else{ boneIndex = model->bonesMapping[boneName]; if(verbose){ std::cout << "Bone already in mapping at index: " << boneIndex << "\n"; } } model->bonesMapping[boneName] = boneIndex; model->bonesInfo[boneIndex].offset = bone->mOffsetMatrix; // model->bonesInfo[boneIndex].offset = geo::Mat4f // { // m.a1,m.a2,m.a3,m.a4, // m.b1,m.b2,m.b3,m.b4, // m.c1,m.c2,m.c3,m.c4, // m.d1,m.d2,m.d3,m.d4, // }; // // bone offset // // # decompose // aiVector3t<float> aiTr,aiRot,aiSc; // bone->mOffsetMatrix.Decompose(aiSc,aiRot,aiTr); // // # create offset transform // auto r = geo::Pt3f{aiRot.x,aiRot.y,aiRot.z}; // model->bonesInfo[boneIndex].offset = geo::Mat4f::transform( // geo::Pt3f{aiSc.x,aiSc.y,aiSc.z}, // geo::Pt3f{rad_2_deg(r.x()),rad_2_deg(r.y()),rad_2_deg(r.z())}, //// geo::Pt3f{(r.x()),(r.y()),(r.z())}, // geo::Pt3f{aiTr.x,aiTr.y,aiTr.z} // ); if(verbose){ std::cout << "Num weights: " << bone->mNumWeights << "\n"; } for (size_t jj = 0 ; jj < bone->mNumWeights; jj++) { unsigned int VertexId = bone->mWeights[jj].mVertexId; float Weight = bone->mWeights[jj].mWeight; mesh->bones[VertexId].add_bone_data(boneIndex, Weight); } } } model->gmeshes.emplace_back(std::move(gmesh)); } void AiLoader::read_material(Model *model, aiMaterial *aiMat){ using MatP = Material::Property; // read properties Material material; // # str material.name = to_string(read_property<aiString>(MatP::name, aiMat)); // # int material.backfaceCulling = read_property<int>(MatP::twosided, aiMat).value() != 0; material.wireframe = read_property<int>(MatP::enable_wireframe, aiMat).value() != 0; // # float material.opacity = read_property<float>(MatP::opacity, aiMat).value(); material.shininess = read_property<float>(MatP::shininess, aiMat).value(); material.shininessStrength = read_property<float>(MatP::shininess_strength, aiMat).value(); material.refraction = read_property<float>(MatP::refacti, aiMat).value(); material.reflectivity = read_property<float>(MatP::reflectivity, aiMat).value(); // # point3f material.ambiantColor = to_color(read_property<aiColor3D>(MatP::color_ambient, aiMat)); material.diffuseColor = to_color(read_property<aiColor3D>(MatP::color_diffuse, aiMat)); material.specularColor = to_color(read_property<aiColor3D>(MatP::color_specular, aiMat)); material.emissiveColor = to_color(read_property<aiColor3D>(MatP::color_emissive, aiMat)); material.transparentColor = to_color(read_property<aiColor3D>(MatP::color_transparent, aiMat)); material.reflectiveColor = to_color(read_property<aiColor3D>(MatP::color_reflective, aiMat)); // mat.mNumAllocated; // mat.mNumProperties; // read textures for(const auto &type : textureTypes.data){ for(unsigned int ii = 0; ii < aiMat->GetTextureCount(std::get<1>(type)); ++ii){ // ai data aiString path; // receives the path to the texture. If the texture is embedded, receives a '*' followed by the id of the texture // (for the textures stored in the corresponding scene) which can be converted to an int using a function like atoi. NULL is a valid value aiTextureMapping mapping = aiTextureMapping_UV; // texture mapping, NULL is allowed as value unsigned int uvIndex; // uv index of the texture (NULL is valid value) ai_real blend; // blend factor for the texture aiTextureOp operation = aiTextureOp_Multiply;// texture operation to be performed between this texture and the previous texture aiTextureMapMode mapMode[3];// mapping modes to be used for the texture, the parameter may be NULL but if it is a valid pointer it MUST aiMat->GetTexture(std::get<1>(type), ii, &path, &mapping, &uvIndex, &blend, &operation, &mapMode[0]); if(auto pathTexture = retrieve_texture_path(model, path); pathTexture.has_value()){ Texture2D *texture = nullptr; if(model->m_textures.count(pathTexture.value()) == 0){ // add texture model->m_textures[pathTexture.value()] = Texture2D(pathTexture.value()); } texture = &model->m_textures[pathTexture.value()]; TextureInfo textureInfo; textureInfo.texture = texture; textureInfo.options.type = std::get<0>(type); textureInfo.options.mapping = get_texture_mapping(mapping); textureInfo.options.operation = get_texture_operation(operation); textureInfo.options.mapMode = Pt3<TextureMapMode>{ get_texture_map_mode(mapMode[0]), get_texture_map_mode(mapMode[1]), get_texture_map_mode(mapMode[2]) }; // others textures info auto wrapping = read_texture_property<int>(MatP::text_mapping, aiMat, textureInfo.options.type, ii).value(); auto uvwSource = read_texture_property<int>(MatP::text_uvw_source, aiMat, textureInfo.options.type, ii).value(); auto mappingModeU = read_texture_property<int>(MatP::text_mapping_mode_u, aiMat, textureInfo.options.type, ii).value(); auto mappingModeV = read_texture_property<int>(MatP::text_mapping_mode_v, aiMat, textureInfo.options.type, ii).value(); auto flags = read_texture_property<int>(MatP::text_flags, aiMat, textureInfo.options.type, ii).value(); auto texmapAxis = read_texture_property<aiVector3D>(MatP::text_texmap_axis, aiMat, textureInfo.options.type, ii).value(); auto blend = read_texture_property<float>(MatP::text_blend, aiMat, textureInfo.options.type, ii).value(); static_cast<void>(wrapping); static_cast<void>(uvwSource); static_cast<void>(mappingModeU); static_cast<void>(mappingModeV); static_cast<void>(flags); static_cast<void>(texmapAxis); static_cast<void>(blend); // name,twosided,shading_model,enable_wireframe,blend_func,opacity, bumpscaling, shininess, reflectivity, // shininess_strength, refacti, color_diffuse, color_ambient, color_specular, color_emissive, color_transparent, // color_reflective, global_background_image, // text_blend, text_mapping, text_operation, text_uvw_source, // text_mapping_mode_u, text_mapping_mode_v, // text_texmap_axis, text_flags, // add infos material.texturesInfo[textureInfo.options.type].emplace_back(std::move(textureInfo)); } } } model->m_materials.emplace_back(std::move(material)); } std::optional<std::string> AiLoader::retrieve_texture_path(Model *model, const aiString &aiPath){ const std::string path = aiPath.C_Str(); if(path.length() > 0){ if(path[0] == '*'){ std::cout << "[ASSIMP_LOADER] Embedded texture detected, not managed yet\n"; return {}; } } namespace fs = std::filesystem; fs::path texturePath = path; std::error_code code; if(!fs::exists(texturePath,code)){ // check if full path exist fs::path dirPath = model->directory; std_v1<fs::path> pathsToTest; pathsToTest.emplace_back(dirPath / texturePath.filename()); pathsToTest.emplace_back(dirPath / "texture" / texturePath.filename()); pathsToTest.emplace_back(dirPath / "textures" / texturePath.filename()); pathsToTest.emplace_back(dirPath / ".." / "texture" / texturePath.filename()); pathsToTest.emplace_back(dirPath / ".." / "textures" / texturePath.filename()); bool found = false; for(const auto &pathToTest : pathsToTest){ if(fs::exists(pathToTest)){ found = true; texturePath = pathToTest; break; } } if(!found){ std::cerr << "[ASSIMP_LOADER] Cannot find texture " << texturePath.filename() << "\n"; return {}; } } // found path return texturePath.string(); } void AiLoader::read_bones_hierarchy(tool::graphics::BonesHierarchy *bones, aiNode *node){ bones->boneName = node->mName.C_Str(); // set transform // const auto &m = node->mTransformation; // aiVector3t<float> aiTr,aiRot,aiSc; // node->mTransformation.Decompose(aiSc,aiRot,aiTr); // auto r = geo::Pt3f{aiRot.x,aiRot.y,aiRot.z}; // bones->tr = geo::Mat4f::transform( // geo::Pt3f{aiSc.x,aiSc.y,aiSc.z}, // geo::Pt3f{rad_2_deg(r.x()),rad_2_deg(r.y()),rad_2_deg(r.z())}, //// geo::Pt3f{(r.x()),(r.y()),(r.z())}, // geo::Pt3f{aiTr.x,aiTr.y,aiTr.z} // ); bones->tr = node->mTransformation; // const auto &m = node->mTransformation;//.Transpose(); // bones->tr = geo::Mat4f // { // m.a1,m.a2,m.a3,m.a4, // m.b1,m.b2,m.b3,m.b4, // m.c1,m.c2,m.c3,m.c4, // m.d1,m.d2,m.d3,m.d4, // }; // std::cout << "TR: " << geo::Pt3f{aiSc.x,aiSc.y,aiSc.z} << " " << geo::Pt3f{rad_2_deg(r.x()),rad_2_deg(r.y()),rad_2_deg(r.z())} << " " << geo::Pt3f{aiTr.x,aiTr.y,aiTr.z} << "\n"; for(size_t ii = 0; ii < node->mNumChildren; ++ii){ graphics::BonesHierarchy bh; read_bones_hierarchy(&bh, node->mChildren[ii]); bones->children.emplace_back(std::move(bh)); } }
41.202643
197
0.572544
FlorianLance
999825db590c44fa8bd30f1ba9d1112b526bc9e3
4,292
cpp
C++
tools/ecrecover.cpp
beerriot/concord
b03ccf01963bd072915020bb954a7afdb3074d79
[ "Apache-2.0" ]
null
null
null
tools/ecrecover.cpp
beerriot/concord
b03ccf01963bd072915020bb954a7afdb3074d79
[ "Apache-2.0" ]
null
null
null
tools/ecrecover.cpp
beerriot/concord
b03ccf01963bd072915020bb954a7afdb3074d79
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2018-2019 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #include "utils/concord_eth_hash.hpp" #include "utils/concord_eth_sign.hpp" #include "utils/concord_utils.hpp" #include "utils/rlp.hpp" using namespace std; using concord::utils::dehex; using concord::utils::EthSign; using concord::utils::RLPBuilder; using concord::utils::RLPParser; std::vector<uint8_t> next_part(RLPParser &parser, const char *label) { if (parser.at_end()) { cerr << "Transaction too short: missing " << label << endl; exit(-1); } return parser.next(); } std::string addr_to_string(evm_address a) { static const char hexes[] = "0123456789abcdef"; std::string out; for (size_t i = 0; i < sizeof(evm_address); i++) { out.append(hexes + (a.bytes[i] >> 4), 1) .append(hexes + (a.bytes[i] & 0x0f), 1); } return out; } uint64_t uint_from_vector(std::vector<uint8_t> v, const char *label) { if (v.size() > 8) { cerr << label << " > uint64_t\n" << endl; exit(-1); } uint64_t u = 0; for (size_t i = 0; i < v.size(); i++) { u = u << 8; u += v[i]; } return u; } int main(int argc, char **argv) { if (argc != 2) { cerr << "Usage: ecrecover <signed transaction hex>" << endl; return -1; } string tx_s(argv[1]); vector<uint8_t> tx = dehex(tx_s); // Decode RLP RLPParser tx_envelope_p = RLPParser(tx); std::vector<uint8_t> tx_envelope = tx_envelope_p.next(); if (!tx_envelope_p.at_end()) { cerr << "Warning: There are more bytes here than one transaction\n"; } RLPParser tx_parts_p = RLPParser(tx_envelope); std::vector<uint8_t> nonce_v = next_part(tx_parts_p, "nonce"); std::vector<uint8_t> gasPrice_v = next_part(tx_parts_p, "gas price"); std::vector<uint8_t> gas_v = next_part(tx_parts_p, "start gas"); std::vector<uint8_t> to = next_part(tx_parts_p, "to address"); std::vector<uint8_t> value_v = next_part(tx_parts_p, "value"); std::vector<uint8_t> data = next_part(tx_parts_p, "data"); std::vector<uint8_t> v = next_part(tx_parts_p, "signature V"); std::vector<uint8_t> r_v = next_part(tx_parts_p, "signature R"); std::vector<uint8_t> s_v = next_part(tx_parts_p, "signature S"); uint64_t nonce = uint_from_vector(nonce_v, "nonce"); uint64_t gasPrice = uint_from_vector(gasPrice_v, "gas price"); uint64_t gas = uint_from_vector(gas_v, "start gas"); uint64_t value = uint_from_vector(value_v, "value"); if (r_v.size() != sizeof(evm_uint256be)) { cout << "Signature R is too short (" << r_v.size() << ")" << endl; return -1; } evm_uint256be r; std::copy(r_v.begin(), r_v.end(), r.bytes); if (s_v.size() != sizeof(evm_uint256be)) { cout << "Signature S is too short (" << s_v.size() << ")" << endl; return -1; } evm_uint256be s; std::copy(s_v.begin(), s_v.end(), s.bytes); // Figure out non-signed V if (v.size() < 1) { cerr << "Signature V is empty\n" << endl; return -1; } uint64_t chainID = uint_from_vector(v, "chain ID"); uint8_t actualV; if (chainID < 37) { cerr << "Non-EIP-155 signature V value" << endl; return -1; } if (chainID % 2) { actualV = 0; chainID = (chainID - 35) / 2; } else { actualV = 1; chainID = (chainID - 36) / 2; } // Re-encode RLP RLPBuilder unsignedTX_b; unsignedTX_b.start_list(); std::vector<uint8_t> empty; unsignedTX_b.add(empty); // S unsignedTX_b.add(empty); // R unsignedTX_b.add(chainID); // V unsignedTX_b.add(data); if (value == 0) { // signing hash expects 0x80 here, not 0x00 unsignedTX_b.add(empty); } else { unsignedTX_b.add(value); } unsignedTX_b.add(to); if (gas == 0) { unsignedTX_b.add(empty); } else { unsignedTX_b.add(gas); } if (gasPrice == 0) { unsignedTX_b.add(empty); } else { unsignedTX_b.add(gasPrice); } if (nonce == 0) { unsignedTX_b.add(empty); } else { unsignedTX_b.add(nonce); } std::vector<uint8_t> unsignedTX = unsignedTX_b.build(); // Recover Address evm_uint256be unsignedTX_h = concord::utils::eth_hash::keccak_hash(unsignedTX); EthSign verifier; evm_address from = verifier.ecrecover(unsignedTX_h, actualV, r, s); cout << "Recovered: " << addr_to_string(from) << endl; return 0; }
26.012121
72
0.637931
beerriot
99a21be2f932532a41fbb2c1246ed158ffdd676b
2,787
cpp
C++
qtchat/bustx/main.cpp
ericosur/myqt
e96f77f99442c44e51a1dbe1ee93edfa09b3db0f
[ "MIT" ]
null
null
null
qtchat/bustx/main.cpp
ericosur/myqt
e96f77f99442c44e51a1dbe1ee93edfa09b3db0f
[ "MIT" ]
null
null
null
qtchat/bustx/main.cpp
ericosur/myqt
e96f77f99442c44e51a1dbe1ee93edfa09b3db0f
[ "MIT" ]
null
null
null
#include <QtCore> #include <QDebug> #include <QCoreApplication> #include <iostream> #include <unistd.h> #include "dbusutil.h" using namespace std; ENUM_BUS g_session_bus = USE_SYSTEM_BUS; void msgHandler(QtMsgType type, const QMessageLogContext& ctx, const QString& msg) { Q_UNUSED(ctx); const char symbols[] = { 'I', 'E', '!', 'X' }; QString output = QString("[%1] %2").arg( symbols[type] ).arg( msg ); std::cerr << output.toStdString() << std::endl; if( type == QtFatalMsg ) abort(); } void usage() { cout << "bustx - send two kinds of signals to dbus" << endl << "options:" << endl << "\t-c send COMMAND signal" << endl << "\t-m send MESSAGE signal" << endl << "\t-h this usage" << endl << "\t-n assign name of sender" << endl << "\t-s use session bus" << endl << endl << "option -c will override -s and -m" << endl; } void process_args(int argc, char* argv[]) { int c; const size_t MAX_CMD_LEN = 64; char cmd[MAX_CMD_LEN]; char sender[MAX_CMD_LEN]; bool has_sender = false; bool has_message = false; while (true) { c = getopt(argc, argv, "hc:m:n:sy"); if (c == -1) break; switch (c) { case 'h': case '?': usage(); return; case 'c': memset(cmd, 0, MAX_CMD_LEN); strncpy(cmd, optarg, qMin(MAX_CMD_LEN, strlen(optarg))); send_dbus_signal_to_command(cmd); return; case 'm': has_message = true; memset(cmd, 0, MAX_CMD_LEN); strncpy(cmd, optarg, qMin(MAX_CMD_LEN, strlen(optarg))); break; case 'n': has_sender = true; memset(sender, 0, MAX_CMD_LEN); strncpy(sender, optarg, qMin(MAX_CMD_LEN, strlen(optarg))); break; case 's': g_session_bus = USE_SESSION_BUS; printf("use session bus"); break; case 'y': g_session_bus = USE_SYSTEM_BUS; printf("use system bus"); break; default: break; } } if (has_message) { send_dbus_signal_to_message( cmd, (has_sender ? sender : argv[0]) ); } if (argc > optind) { for (int i = optind; i < argc; i++) { send_dbus_signal_to_message( argv[i], (has_sender ? sender : argv[0]) ); } } } int main(int argc, char *argv[]) { Q_UNUSED(argc); Q_UNUSED(argv); //qInstallMessageHandler(msgHandler); //QCoreApplication app(argc, argv); if (argc == 1) { usage(); return 0; } process_args(argc, argv); return 0; }
24.883929
82
0.519555
ericosur
99a2e0a90e4dd2ff7f515862951c93847489be92
2,323
hpp
C++
include/expressions/diff_expr.hpp
miceks/gem
08321fd35f8e3338f70bf9364448c8e77735ed2d
[ "MIT" ]
null
null
null
include/expressions/diff_expr.hpp
miceks/gem
08321fd35f8e3338f70bf9364448c8e77735ed2d
[ "MIT" ]
null
null
null
include/expressions/diff_expr.hpp
miceks/gem
08321fd35f8e3338f70bf9364448c8e77735ed2d
[ "MIT" ]
null
null
null
#pragma once namespace gem::expr { // Expression produced by the - operator template <typename LHS, typename RHS> class diff_expr { LHS const& m_lhs_expr; RHS const& m_rhs_expr; public: using result_type = gem::meta::sum<typename LHS::result_type, typename RHS::result_type>::type; constexpr diff_expr(LHS const& lhs, RHS const& rhs) : m_lhs_expr(lhs), m_rhs_expr(rhs) { } template <std::size_t I> auto constexpr subscript() const { // Find which indices in sub expressions map to index I using index_mapping = gem::meta::sum_sub_indices<I, result_type, typename LHS::result_type, typename RHS::result_type>; // Only rhs contributes a term. if constexpr(index_mapping::I1 == LHS::result_type::size) { return -m_rhs_expr. template subscript<index_mapping::I2>(); } // Only lhs contributes a term. else if constexpr(index_mapping::I2 == RHS::result_type::size) { return m_lhs_expr. template subscript<index_mapping::I1>(); } // Both rhs and lhs contribute a term each. else { return m_lhs_expr. template subscript<index_mapping::I1>() - m_rhs_expr. template subscript<index_mapping::I2>(); } } }; } // namespace gem::expr namespace gem { // Difference of two expressions template <expression LHS, expression RHS> auto constexpr operator - (LHS const& lhs, RHS const& rhs) { return expr::diff_expr<LHS, RHS>(lhs, rhs); } // Difference of scalar and expression template <expression RHS> auto constexpr operator - (mvec<blade<0,0,0>> const& lhs, RHS const& rhs) { return expr::diff_expr(lhs, rhs); } // Difference of expression and scalar template <expression LHS> auto constexpr operator - (LHS const& lhs, mvec<blade<0,0,0>> const& rhs) { return expr::diff_expr(lhs, rhs); } } // namespace gem
29.782051
77
0.541972
miceks
99a40a86a403ac0161f90871abbcd7aee58efe86
1,170
cpp
C++
src/Scene/Model/MenuModelManager.cpp
krusagiz/SDL-OpenGL-Game-Framework
f96dc4f2fccf2b9d7fda4b7403be54d025b9b2c7
[ "MIT" ]
null
null
null
src/Scene/Model/MenuModelManager.cpp
krusagiz/SDL-OpenGL-Game-Framework
f96dc4f2fccf2b9d7fda4b7403be54d025b9b2c7
[ "MIT" ]
null
null
null
src/Scene/Model/MenuModelManager.cpp
krusagiz/SDL-OpenGL-Game-Framework
f96dc4f2fccf2b9d7fda4b7403be54d025b9b2c7
[ "MIT" ]
null
null
null
#include "MenuModelManager.hpp" #include <cmath> #include "../../ui/UiManager.hpp" MenuModelManager::MenuModelManager() : ModelManager(64) { // } void MenuModelManager::updateOneTick() { // } void MenuModelManager::draw(UiManager &uiManager) { uiManager.setColorMask({1,1,1}); uiManager.setObjectScale(1 + .8f*sin(modelTick*.01618f +.8f)); uiManager.drawSprite(-3 + sin(modelTick*.01f +.8f), .5f*cos(modelTick*.01f +.8f), SPRITE_ID_TEX1); uiManager.setObjectScale(1 + .2f*sin(modelTick*.01618f)); uiManager.drawSprite(.5f*cos(modelTick*.01f +.4f), 1 - sin(modelTick*.01f +.4f), SPRITE_ID_GEOM); uiManager.setObjectScale(1); uiManager.drawSprite(3 + sin(modelTick*.01f), .5f*cos(modelTick*.01f), SPRITE_ID_TEX1); uiManager.setObjectScale(3, 1); uiManager.drawSprite(3 + sin(modelTick*.01f +.3f), 3 + .5f*cos(modelTick*.01f +.3f), SPRITE_ID_TEX2); uiManager.setObjectScale(1); uiManager.drawSprite(-3 + sin(modelTick*.01f), 1 + .5f*cos(modelTick*.01f), SPRITE_ID_TEX3); uiManager.setObjectScale(1); uiManager.drawSprite(-3 + sin(modelTick*.015f), -2 + cos(modelTick*.015f), SPRITE_ID_TEX4); }
31.621622
105
0.68547
krusagiz
99a4913fa33c824bec8d78bb7283b51536954b6c
5,738
hpp
C++
L7/Common/Headers/GpProtoHeaders.hpp
ITBear/GpNetwork
65b28ee8ed16e47efd8f8991cd8942c8a517c45e
[ "Apache-2.0" ]
null
null
null
L7/Common/Headers/GpProtoHeaders.hpp
ITBear/GpNetwork
65b28ee8ed16e47efd8f8991cd8942c8a517c45e
[ "Apache-2.0" ]
null
null
null
L7/Common/Headers/GpProtoHeaders.hpp
ITBear/GpNetwork
65b28ee8ed16e47efd8f8991cd8942c8a517c45e
[ "Apache-2.0" ]
null
null
null
#pragma once #include "GpProtoHeaderValue.hpp" #include "../Enums/GpEnums.hpp" namespace GPlatform { class GPNETWORK_API GpProtoHeaders: public GpTypeStructBase { public: CLASS_DECLARE_DEFAULTS(GpProtoHeaders) TYPE_STRUCT_DECLARE("88a01e4e-9105-4cd5-9990-4578ebb14b51"_sv) public: explicit GpProtoHeaders (void) noexcept; GpProtoHeaders (const GpProtoHeaders& aHeaders); GpProtoHeaders (GpProtoHeaders&& aHeaders) noexcept; virtual ~GpProtoHeaders (void) noexcept override; void Set (const GpProtoHeaders& aHeaders); void Set (GpProtoHeaders&& aHeaders) noexcept; void Clear (void); GpProtoHeaderValue::C::MapStr::SP& Headers (void) noexcept {return headers;} const GpProtoHeaderValue::C::MapStr::SP& Headers (void) const noexcept {return headers;} GpProtoHeaders& Replace (std::string aName, std::string_view aValue); GpProtoHeaders& Replace (std::string aName, std::string&& aValue); GpProtoHeaders& Replace (std::string aName, const u_int_64 aValue); GpProtoHeaders& Add (std::string aName, std::string_view aValue); GpProtoHeaders& Add (std::string aName, std::string&& aValue); GpProtoHeaders& Add (std::string aName, const u_int_64 aValue); protected: template<typename T, typename V> GpProtoHeaders& Replace (const typename T::EnumT aType, std::string_view aValue); template<typename T, typename V> GpProtoHeaders& Replace (const typename T::EnumT aType, std::string&& aValue); template<typename T, typename V> GpProtoHeaders& Replace (const typename T::EnumT aType, const u_int_64 aValue); template<typename T, typename V> GpProtoHeaders& Add (const typename T::EnumT aType, std::string_view aValue); template<typename T, typename V> GpProtoHeaders& Add (const typename T::EnumT aType, std::string&& aValue); template<typename T, typename V> GpProtoHeaders& Add (const typename T::EnumT aType, const u_int_64 aValue); private: GpProtoHeaderValue::C::MapStr::SP headers; public: static const GpArray<std::string, GpContentType::SCount().As<size_t>()> sContentType; static const GpArray<std::string, GpCharset::SCount().As<size_t>()> sCharset; }; template<typename T, typename V> GpProtoHeaders& GpProtoHeaders::Replace ( const typename T::EnumT aType, std::string_view aValue ) { return Replace<T, V>(aType, std::string(aValue)); } template<typename T, typename V> GpProtoHeaders& GpProtoHeaders::Replace ( const typename T::EnumT aType, std::string&& aValue ) { const std::string& headerName = V::sHeadersNames.at(size_t(aType)); headers[headerName] = MakeSP<GpProtoHeaderValue>(std::move(aValue)); return *this; } template<typename T, typename V> GpProtoHeaders& GpProtoHeaders::Replace ( const typename T::EnumT aType, const u_int_64 aValue) { return Replace<T, V>(aType, StrOps::SFromUI64(aValue)); } template<typename T, typename V> GpProtoHeaders& GpProtoHeaders::Add ( const typename T::EnumT aType, std::string_view aValue ) { return Add<T, V>(aType, std::string(aValue)); } template<typename T, typename V> GpProtoHeaders& GpProtoHeaders::Add ( const typename T::EnumT aType, std::string&& aValue ) { const std::string& headerName = V::sHeadersNames.at(size_t(aType)); auto iter = headers.find(headerName); if (iter == headers.end()) { return Replace<T, V>(aType, std::move(aValue)); } else { iter->second->elements.emplace_back(std::move(aValue)); } return *this; } template<typename T, typename V> GpProtoHeaders& GpProtoHeaders::Add ( const typename T::EnumT aType, const u_int_64 aValue ) { return Add<T, V>(aType, StrOps::SFromUI64(aValue)); } }//namespace GPlatform
40.125874
104
0.467585
ITBear
99a5be3d0bb725a723cd52bc36fbae911f0f21f9
3,991
cpp
C++
Advanced C++ Course/Benjamin Rutan HW 1 Submission/1.5/1.5/Line.cpp
BRutan/Cpp
8acbc6c341f49d6d83168ccd5ba49bd6824214f9
[ "MIT" ]
null
null
null
Advanced C++ Course/Benjamin Rutan HW 1 Submission/1.5/1.5/Line.cpp
BRutan/Cpp
8acbc6c341f49d6d83168ccd5ba49bd6824214f9
[ "MIT" ]
null
null
null
Advanced C++ Course/Benjamin Rutan HW 1 Submission/1.5/1.5/Line.cpp
BRutan/Cpp
8acbc6c341f49d6d83168ccd5ba49bd6824214f9
[ "MIT" ]
null
null
null
/* Line.cpp (exercise 1.5.5) Description: * Declare Line class that represents a line in 2-D Euclidean space. State Variables/Objects: *Point p1, p2: Points in 2-D Euclidean space. Member Functions: *Line(): Default constructor (allocates memory for both state Point objects, sets their states to (0,0)). *Line(const Point&, const Point&): Overloaded constructor (allocates memory for both state Point objects, sets their states to (0,0)). *Line(const Line&): Copy constructor (allocates memory for both state Point objects, sets their states to passed Line's point's states). *~Line(): Destructor (frees memory previously allocated by constructor). // Accessors: *Point P1() const: Return copy of P1 Point Object. *Point P2() const: Return copy of P2 Point Object. // Mutators: *void P1(const Point&): Change P1's state to state of passed Point object. *void P2(const Point&): Change P2's state to state of passed Point object. // Misc. Methods: *double Length() const: Return length of line. *void Draw() const: Draw calling Line object. *string ToString() const: Return string description of Length object's state ("Line((P1_X(), P1_Y()), (P2_X(), P2_Y()))"). */ #include <iostream> #include <string> #include <sstream> #include "IODevice.hpp" #include "Line.hpp" #include "Shape.hpp" //////////////////////////////// // Constructors/Destructor: //////////////////////////////// Line::Line() noexcept : p1(), p2(), Shape() /* Default constructor. */ { } Line::Line(const Point &p1_in, const Point &p2_in) noexcept : p1(p1_in), p2(p2_in), Shape() /* Overloaded constructor (parameters reference existing point objects). */ { } Line::Line(const Line &line_in) noexcept : p1(line_in.p1), p2(line_in.p2), Shape(line_in) /* Copy constructor. */ { } Line::~Line() noexcept /* Destructor. */ { } //////////////////////////////// // Accessors: //////////////////////////////// Point Line::P1() const noexcept /* Return P1. */ { return p1; } Point Line::P2() const noexcept /* Return P2. */ { return p2; } //////////////////////////////// // Mutators: //////////////////////////////// void Line::P1(const Point &point_in) noexcept /* Set state of P1 by using assignment operator with point_in. */ { p1 = point_in; } void Line::P2(const Point &point_in) noexcept /* Set state of P2 by using assignment operator with point_in. */ { p2 = point_in; } //////////////////////////////// // Misc. methods: //////////////////////////////// double Line::Length() const noexcept /* Return euclidean distance between P1 and P2. */ { return (p1.Distance(p2)); } void Line::Draw() const noexcept /* Draw current Line object. */ { std::cout << "Line has been drawn. " << std::endl; } void Line::display(const IODevice &in) const noexcept /* Display Circle object on passed input-output device. */ { in << *this; } std::string Line::ToString() const noexcept /* Return description of Line object's state ("Line((P1_X(), P1_Y()), (P2_X(), P2_Y()))") */ { std::stringstream ss; // Append the base Shape object description to Line object description: std::string s = Shape::ToString(); ss << "Line({" << p1.X() << ", " << p1.Y() << "},{" << p2.X() << ", " << p2.Y() << "}) " << s; return ss.str(); } ////////////////////////////////////// // Overloaded Operators: ////////////////////////////////////// // Member operators: Line& Line::operator=(const Line& line_in) noexcept /* Assignment operator. */ { // Preclude self-assignment (check if passed line has the same memory address): if (this != &line_in) { p1 = line_in.p1; p2 = line_in.p2; // Copy passed Line object's base state: Shape::operator=(line_in); } return *this; } // Global operators: std::ostream& operator<<(std::ostream& os, const Line& line_in) noexcept /* Overloaded ostream operator. */ { os << "Line((" << line_in.p1.X() << ", " << line_in.p1.Y() << "),(" << line_in.p2.X() << ", " << line_in.p2.Y() << "))"; return os; }
34.111111
168
0.604861
BRutan
99a858f595f29c0242f3f3d56ae313bcf004f4e0
4,865
cc
C++
third_party/blink/renderer/core/html/anchor_element_metrics_sender.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
third_party/blink/renderer/core/html/anchor_element_metrics_sender.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
third_party/blink/renderer/core/html/anchor_element_metrics_sender.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/html/anchor_element_metrics_sender.h" #include "base/metrics/histogram_macros.h" #include "third_party/blink/public/common/browser_interface_broker_proxy.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/html/anchor_element_metrics.h" #include "third_party/blink/renderer/core/html/html_anchor_element.h" #include "ui/gfx/geometry/mojom/geometry.mojom-shared.h" namespace blink { namespace { // Returns true if |anchor_element| should be discarded, and not used for // navigation prediction. bool ShouldDiscardAnchorElement(const HTMLAnchorElement& anchor_element) { Frame* frame = anchor_element.GetDocument().GetFrame(); auto* local_frame = DynamicTo<LocalFrame>(frame); if (!local_frame) return true; return local_frame->IsAdSubframe(); } } // namespace // static const char AnchorElementMetricsSender::kSupplementName[] = "DocumentAnchorElementMetricsSender"; AnchorElementMetricsSender::~AnchorElementMetricsSender() = default; // static AnchorElementMetricsSender* AnchorElementMetricsSender::From( Document& document) { DCHECK(HasAnchorElementMetricsSender(document)); AnchorElementMetricsSender* sender = Supplement<Document>::From<AnchorElementMetricsSender>(document); if (!sender) { sender = MakeGarbageCollected<AnchorElementMetricsSender>(document); ProvideTo(document, sender); } return sender; } // static bool AnchorElementMetricsSender::HasAnchorElementMetricsSender( Document& document) { bool is_feature_enabled = base::FeatureList::IsEnabled(features::kNavigationPredictor); const KURL& url = document.BaseURL(); return is_feature_enabled && !document.ParentDocument() && url.IsValid() && url.ProtocolIsInHTTPFamily(); } void AnchorElementMetricsSender::SendClickedAnchorMetricsToBrowser( mojom::blink::AnchorElementMetricsPtr metric) { if (!AssociateInterface()) return; metrics_host_->ReportAnchorElementMetricsOnClick(std::move(metric)); } void AnchorElementMetricsSender::SendAnchorMetricsVectorToBrowser( Vector<mojom::blink::AnchorElementMetricsPtr> metrics, const IntSize& viewport_size) { if (!AssociateInterface()) return; metrics_host_->ReportAnchorElementMetricsOnLoad(std::move(metrics), gfx::Size(viewport_size)); has_onload_report_sent_ = true; anchor_elements_.clear(); } void AnchorElementMetricsSender::AddAnchorElement(HTMLAnchorElement& element) { if (has_onload_report_sent_) return; bool is_ad_frame_element = ShouldDiscardAnchorElement(element); // We ignore anchor elements that are in ad frames. if (is_ad_frame_element) return; anchor_elements_.insert(&element); } const HeapHashSet<Member<HTMLAnchorElement>>& AnchorElementMetricsSender::GetAnchorElements() const { return anchor_elements_; } void AnchorElementMetricsSender::Trace(Visitor* visitor) const { visitor->Trace(anchor_elements_); visitor->Trace(metrics_host_); Supplement<Document>::Trace(visitor); } bool AnchorElementMetricsSender::AssociateInterface() { if (metrics_host_.is_bound()) return true; Document* document = GetSupplementable(); // Unable to associate since no frame is attached. if (!document->GetFrame()) return false; document->GetFrame()->GetBrowserInterfaceBroker().GetInterface( metrics_host_.BindNewPipeAndPassReceiver( document->GetExecutionContext()->GetTaskRunner( TaskType::kInternalDefault))); return true; } AnchorElementMetricsSender::AnchorElementMetricsSender(Document& document) : Supplement<Document>(document), metrics_host_(document.GetExecutionContext()) { DCHECK(!document.ParentDocument()); } void AnchorElementMetricsSender::DidFinishLifecycleUpdate( const LocalFrameView& local_frame_view) { // Check that layout is stable. If it is, we can perform the onload update and // stop observing future events. Document* document = local_frame_view.GetFrame().GetDocument(); if (document->Lifecycle().GetState() < DocumentLifecycle::kAfterPerformLayout) { return; } // Stop listening to updates, as the onload report can be sent now. document->View()->UnregisterFromLifecycleNotifications(this); // Send onload report. AnchorElementMetrics::MaybeReportViewportMetricsOnLoad(*document); } } // namespace blink
32.871622
80
0.764851
mghgroup
99a9fe05108b7f6744f3b903c9983d67caf2f920
157
hpp
C++
BBB_GPIO/utils.hpp
felipegarcia99/beagleboneblack-gpio-cpp-api
e6169957fe8da0dfb87381ee4c1a12941c1f02be
[ "MIT" ]
1
2021-09-09T10:10:43.000Z
2021-09-09T10:10:43.000Z
BBB_GPIO/utils.hpp
felipegarcia99/beagleboneblack-gpio-cpp-api
e6169957fe8da0dfb87381ee4c1a12941c1f02be
[ "MIT" ]
null
null
null
BBB_GPIO/utils.hpp
felipegarcia99/beagleboneblack-gpio-cpp-api
e6169957fe8da0dfb87381ee4c1a12941c1f02be
[ "MIT" ]
null
null
null
#include <signal.h> // our new library extern volatile sig_atomic_t flag; void delay(float time); void defining_sigaction(); void my_handler(int signal);
22.428571
40
0.764331
felipegarcia99
99aa1ef128ad211443b5fa17f3aa39f9036020a7
80,205
cpp
C++
Libs/Mesh/meshFIM.cpp
ajensen1234/ShapeWorks
fb308c8c38ad0e00c7f62aa7221e00e72140d909
[ "MIT" ]
40
2019-07-26T18:02:13.000Z
2022-03-28T07:24:23.000Z
Libs/Mesh/meshFIM.cpp
ajensen1234/ShapeWorks
fb308c8c38ad0e00c7f62aa7221e00e72140d909
[ "MIT" ]
1,359
2019-06-20T17:17:53.000Z
2022-03-31T05:42:29.000Z
Libs/Mesh/meshFIM.cpp
ajensen1234/ShapeWorks
fb308c8c38ad0e00c7f62aa7221e00e72140d909
[ "MIT" ]
13
2019-12-06T01:31:48.000Z
2022-02-24T04:34:23.000Z
#include "meshFIM.h" #include "Vec.h" #include <math.h> #include <sstream> #include <fstream> #include <stdio.h> //#include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> //#include <termios.h> #define NB_ENABLE 0 #define NB_DISABLE 1 #ifndef PI #define PI 3.1415927 #endif #ifndef MIN #define MIN(a,b) (((a)<(b))?(a):(b)) #endif #ifndef MAX #define MAX(a,b) (((a)>(b))?(a):(b)) #endif #define LARGENUM 10000000.0 #define EPS 1e-6 typedef std::pair<unsigned int, float> gDistPair; void meshFIM::need_kdtree() { if (!kd) { kd = new KDtree(m_meshPtr->vertices); } if (maxEdgeLength == 0.0) { need_maxedgelength(); } } void meshFIM::need_oneringfaces() { if (vertOneringFaces.empty()) { vertOneringFaces.resize(m_meshPtr->vertices.size()); for (int i = 0; i < m_meshPtr->vertices.size(); i++) { vertOneringFaces[i] = GetOneRing(i); } } } void meshFIM::need_speed() { need_abs_curvatures(); int nf = m_meshPtr->faces.size(); for (int i = 0; i < nf; i++) { TriMesh::Face f = m_meshPtr->faces[i]; float speedInv = 0; switch (speedType) { case CURVATURE: speedInv = (abs_curv[f[0]] + abs_curv[f[1]] + abs_curv[f[2]]) / 3.0; break; case ONE: speedInv = 1.0; break; } speedInvVector.push_back(speedInv); } } void meshFIM::need_abs_curvatures() { m_meshPtr->need_curvatures(); if (abs_curv.size() == m_meshPtr->vertices.size()) return; abs_curv.clear(); //compute rms curvature and max/min for (int i = 0; i < m_meshPtr->vertices.size(); i++) { float crv1 = m_meshPtr->curv1[i]; float crv2 = m_meshPtr->curv2[i]; float abs_c = (fabs(crv1) + fabs(crv2)) / 2.0 + 1.0; abs_curv.push_back(abs_c); } std::vector<float> abs_curv_mean; float max_abs = -9e99; float min_abs = 9e99; for (int i = 0; i < abs_curv.size(); i++) { float abs_c = abs_curv[i]; if (abs_c > max_abs) { max_abs = abs_c; } if (abs_c < min_abs) { min_abs = abs_c; } } for (int i = 0; i < abs_curv.size(); i++) { abs_curv[i] /= max_abs; abs_curv[i] = sqrt(abs_curv[i]); } } //compute the edge length void meshFIM::need_edge_lengths() { if (m_meshPtr->faces.empty()) { std::cerr << "No faces to compute face edges!!!\n"; throw(1); } int numFaces = m_meshPtr->faces.size(); for (int i = 0; i < numFaces; i++) { TriMesh::Face f = m_meshPtr->faces[i]; vec3 edge01 = ( vec3) (m_meshPtr->vertices[f[1]] - m_meshPtr->vertices[f[0]]); vec3 edge12 = ( vec3) (m_meshPtr->vertices[f[2]] - m_meshPtr->vertices[f[1]]); vec3 edge20 = ( vec3) (m_meshPtr->vertices[f[0]] - m_meshPtr->vertices[f[2]]); vec3 edgeLengths; edgeLengths[0] = sqrt(edge01[0] * edge01[0] + edge01[1] * edge01[1] + edge01[2] * edge01[2]); edgeLengths[1] = sqrt(edge12[0] * edge12[0] + edge12[1] * edge12[1] + edge12[2] * edge12[2]); edgeLengths[2] = sqrt(edge20[0] * edge20[0] + edge20[1] * edge20[1] + edge20[2] * edge20[2]); edgeLengthsVector.push_back(edgeLengths); } } void meshFIM::SetMesh(TriMesh *mesh) { m_meshPtr = mesh; this->geodesicMap.resize(m_meshPtr->vertices.size()); // orient the mesh for consistent vertex ordering... orient(m_meshPtr);// Manasi // have to recompute the normals and other attributes required for rendering if (!m_meshPtr->normals.empty()) m_meshPtr->normals.clear();// Manasi m_meshPtr->need_normals();// Manasi if (!m_meshPtr->adjacentfaces.empty()) m_meshPtr->adjacentfaces.clear();// Manasi m_meshPtr->need_adjacentfaces();// Manasi if (!m_meshPtr->across_edge.empty()) m_meshPtr->across_edge.clear();// Manasi m_meshPtr->need_across_edge();// Manasi if (!m_meshPtr->tstrips.empty()) m_meshPtr->tstrips.clear();// Manasi m_meshPtr->need_tstrips();// Manasi need_edge_lengths(); m_meshPtr->need_curvatures(); need_speed(); } void meshFIM::InitializeLabels() { if (!m_meshPtr) { std::cerr << "Label-vector size unknown, please set the mesh first..." << std::endl; throw(1); } else { // initialize all labels to 'Far' int nv = m_meshPtr->vertices.size(); if (m_Label.size() != nv) m_Label.resize(nv); for (int l = 0; l < nv; l++) { m_Label[l] = FarPoint; } // if seeed-points are present, treat them differently if (!m_SeedPoints.empty()) { for (int s = 0; s < m_SeedPoints.size(); s++) { m_Label[m_SeedPoints[s]] = SeedPoint;//m_Label[s] = LabelType::SeedPoint; } } } } void meshFIM::InitializeActivePoints() { if (!m_SeedPoints.empty()) { int ns = m_SeedPoints.size(); std::vector<index> nb; for (int s = 0; s < ns; s++) { nb = m_meshPtr->neighbors[m_SeedPoints[s]]; for (int i = 0; i < nb.size(); i++) { if (m_Label[nb[i]] != SeedPoint) { m_ActivePoints.push_back(nb[i]); m_Label[nb[i]] = ActivePoint; } } } } } float meshFIM::PointLength(point v) { float length = 0; for (int i = 0; i < 3; i++) { length += v[i] * v[i]; } return sqrt(length); } // FIM: check angle for at a given vertex, for a given face bool meshFIM::IsNonObtuse(int v, TriMesh::Face f) { int iV = f.indexof(v); point A = m_meshPtr->vertices[v]; point B = m_meshPtr->vertices[f[(iV + 1) % 3]]; point C = m_meshPtr->vertices[f[(iV + 2) % 3]]; float a = trimesh::dist(B, C); float b = trimesh::dist(A, C); float c = trimesh::dist(A, B); float angA = 0.0; /* = acos( (b*b + c*c - a*a) / (2*b*c) )*/ if ((a > 0) && (b > 0) && (c > 0))// Manasi stack overflow {// Manasi stack overflow angA = acos((b * b + c * c - a * a) / (2 * b * c));// Manasi stack overflow }// Manasi stack overflow return (angA < M_PI / 2.0f); } // FIM: given a vertex, find an all-acute neighborhood of faces void meshFIM::SplitFace(std::vector<TriMesh::Face> &acFaces, int v, TriMesh::Face cf, int nfAdj/*, int currentVert*/) { // get all the four vertices in order /* v1 v4 +-------+ \ . \ \ . \ \ . \ +-------+ v2 v3 */ int iV = cf.indexof(v); // get index of v in terms of cf int v1 = v; int v2 = cf[(iV + 1) % 3]; int v4 = cf[(iV + 2) % 3]; iV = m_meshPtr->faces[nfAdj].indexof(v2); // get index of v in terms of adjacent face int v3 = m_meshPtr->faces[nfAdj][(iV + 1) % 3]; // create faces (v1,v3,v4) and (v1,v2,v3), check angle at v1 TriMesh::Face f11(v1, v3, v4); TriMesh::Face f22(v1, v2, v3); std::vector<TriMesh::Face> f1f2; f1f2.push_back(f11); f1f2.push_back(f22); for (int i = 0; i < f1f2.size(); i++) { TriMesh::Face face = f1f2[i]; if (IsNonObtuse(v, face)) { acFaces.push_back(face); } else { int nfAdj_new = m_meshPtr->across_edge[nfAdj][m_meshPtr->faces[nfAdj].indexof(v2)]; if (nfAdj_new > -1) { SplitFace(acFaces, v, face, nfAdj_new/*, currentVert*/); } else { //printf("NO cross edge!!! Maybe a hole!!\n"); } } } } std::vector<TriMesh::Face> meshFIM::GetOneRing(int v/*, int currentVert*/) { if (m_meshPtr->across_edge.empty()) m_meshPtr->need_across_edge(); // variables required std::vector<TriMesh::Face> oneRingFaces; std::vector<TriMesh::Face> t_faces; // get adjacent faces int naf = m_meshPtr->adjacentfaces[v].size(); if (!naf) { std::cout << "vertex " << v << " has 0 adjacent faces..." << std::endl; } else { for (int af = 0; af < naf; af++) { TriMesh::Face cf = m_meshPtr->faces[m_meshPtr->adjacentfaces[v][af]]; t_faces.clear(); if (IsNonObtuse(v, cf))// check angle: if non-obtuse, return existing face { t_faces.push_back(cf); } else { //t_faces.push_back(cf); int nfae = m_meshPtr->across_edge[m_meshPtr->adjacentfaces[v][af]][cf.indexof(v)]; if (nfae > -1) { SplitFace(t_faces, v, cf, nfae/*,currentVert*/);// if obtuse, split face till we get all acute angles } else { //printf("NO cross edge!!! Maybe a hole!!\n"); } } for (int tf = 0; tf < t_faces.size(); tf++) { oneRingFaces.push_back(t_faces[tf]); } } } return oneRingFaces; } float meshFIM::LocalSolver(index vet, TriMesh::Face triangle, index currentVert) { float a, b, delta, cosA, lamda1, lamda2, TC1, TC2; float TAB, TA, TB, TC; int A, B, C; float squareAB; float LenAB, LenBC, LenAC, LenCD, LenAD; float EdgeTA, EdgeTB; float speedInv; switch (speedType) { case CURVATURE: speedInv = (abs_curv[triangle[0]] + abs_curv[triangle[1]] + abs_curv[triangle[2]]) / 3.0; break; case ONE: default: speedInv = 1.0; break; } float speedI; if (speedType == CURVATURE) { speedI = 100 * speedInv; } else { speedI = speedInv; } C = triangle.indexof(vet); A = (C + 1) % 3; B = (A + 1) % 3; TC1 = LARGENUM; TC2 = LARGENUM; TA = this->geodesic[triangle[A]]; TB = this->geodesic[triangle[B]]; TC = this->geodesic[triangle[C]]; TAB = TB - TA; vec3 edge01 = ( vec3) (m_meshPtr->vertices[triangle[1]] - m_meshPtr->vertices[triangle[0]]); vec3 edge12 = ( vec3) (m_meshPtr->vertices[triangle[2]] - m_meshPtr->vertices[triangle[1]]); vec3 edge20 = ( vec3) (m_meshPtr->vertices[triangle[0]] - m_meshPtr->vertices[triangle[2]]); vec3 edgeLengths; edgeLengths[0] = sqrt(edge01[0] * edge01[0] + edge01[1] * edge01[1] + edge01[2] * edge01[2]); edgeLengths[1] = sqrt(edge12[0] * edge12[0] + edge12[1] * edge12[1] + edge12[2] * edge12[2]); edgeLengths[2] = sqrt(edge20[0] * edge20[0] + edge20[1] * edge20[1] + edge20[2] * edge20[2]); LenAB = edgeLengths[A]; LenBC = edgeLengths[B]; LenAC = edgeLengths[C]; a = (speedI * speedI * LenAB * LenAB - TAB * TAB) * LenAB * LenAB; EdgeTA = TA /*oldValues1 */ + LenAC /*s_triMem[tx*TRIMEMLENGTH + 0]*/ * speedI; EdgeTB = TB /*oldValues2*/ + LenBC /*s_triMem[tx*TRIMEMLENGTH + 2]*/ * speedI; if (a > 0) { cosA = (LenAC * LenAC + LenAB * LenAB - LenBC * LenBC) / (2 * LenAC * LenAB); b = 2 * LenAB * LenAC * cosA * (TAB * TAB - speedI * speedI * LenAB * LenAB); delta = 4 * LenAC * LenAC * a * TAB * TAB * (1 - cosA * cosA); lamda1 = (-b + sqrt(delta)) / (2 * a); lamda2 = (-b - sqrt(delta)) / (2 * a); if (lamda1 >= 0 && lamda1 <= 1) { LenAD = lamda1 * LenAB; LenCD = sqrt(LenAC * LenAC + LenAD * LenAD - 2 * LenAC * LenAD * cosA); TC1 = lamda1 * TAB + TA + LenCD * speedI; } if (lamda2 >= 0 && lamda2 <= 1) { LenAD = lamda2 * LenAB; LenCD = sqrt(LenAC * LenAC + LenAD * LenAD - 2 * LenAC * LenAD * cosA); TC2 = lamda2 * TAB + TA + LenCD * speedI; } TC = MIN(TC, MIN(TC2, MIN(TC1, MIN(EdgeTA, EdgeTB)))); } else { TC = MIN(TC, MIN(EdgeTA, EdgeTB)); } return TC; } float meshFIM::Upwind(index currentVert,index vet) { float result=LARGENUM; float tmp; std::vector<TriMesh::Face> neighborFaces = this->GetOneRing(vet/*, currentVert*/); // WAS THIS LINE BELOW ON Nov17 - Change Back when GetOneRing works for speed! //vector<TriMesh::Face> neighborFaces = m_meshPtr->vertOneringFaces[vet]; //vector<int> neighborFaces = m_meshPtr->adjacentfaces[vet]; int i; for (i = 0; i < neighborFaces.size(); i++) { tmp = LocalSolver(vet, neighborFaces[i], currentVert); //tmp = LocalSolver(vet, m_meshPtr->faces[neighborFaces[i]], currentVert); NumComputation++; result = MIN(result,tmp ); //m_meshPtr->vertT[currentVert][vet] = result; } return result; } // FIM: initialize attributes void meshFIM::InitializeAttributes(int currentVert, std::vector<int> seeds = std::vector<int>()) { for (int v = 0; v < m_meshPtr->vertices.size(); v++) { this->geodesic.push_back(LARGENUM); } // initialize seed points if present... for (int s = 0; s < seeds.size(); s++) { this->geodesic[seeds[s]] = 0; } // pre-compute faces, normals, and other per-vertex properties that may be needed m_meshPtr->need_neighbors(); m_meshPtr->need_normals(); m_meshPtr->need_adjacentfaces(); m_meshPtr->need_across_edge(); m_meshPtr->need_faces(); } // FIM: Remove data lingering from computation void meshFIM::CleanupAttributes() { this->geodesic.clear(); } void meshFIM::GenerateReducedData() { std::list<index>::iterator iter = m_ActivePoints.begin(); float oldT1, newT1, oldT2, newT2; index tmpIndex1, tmpIndex2; std::vector<int> nb; NumComputation = 0; double total_duration = 0; clock_t starttime, endtime; starttime = clock(); char c; int i = 0; for (int currentVert = 0; currentVert < m_meshPtr->vertices.size(); currentVert++) { std::vector<int> seedPointList(1, currentVert); SetSeedPoint(seedPointList); this->InitializeAttributes(currentVert, m_SeedPoints); InitializeLabels(); InitializeActivePoints(); while (!m_ActivePoints.empty()) { iter = m_ActivePoints.begin(); while (iter != m_ActivePoints.end()) { tmpIndex1 = *iter; nb = m_meshPtr->neighbors[tmpIndex1]; oldT1 = this->geodesic[tmpIndex1]; newT1 = Upwind(currentVert, tmpIndex1); if (abs(oldT1 - newT1) < _EPS) //if converges { if (oldT1 > newT1) { this->geodesic[tmpIndex1] = newT1; } if (this->geodesic[tmpIndex1] < m_StopDistance) { for (i = 0; i < nb.size(); i++) { tmpIndex2 = nb[i]; if (m_Label[tmpIndex2] == AlivePoint || m_Label[tmpIndex2] == FarPoint) { oldT2 = this->geodesic[tmpIndex2]; newT2 = Upwind(currentVert, tmpIndex2); if (oldT2 > newT2) { this->geodesic[tmpIndex2] = newT2; if (m_Label[tmpIndex2] != ActivePoint) { m_ActivePoints.insert(iter, tmpIndex2); m_Label[tmpIndex2] = ActivePoint; } } } } } iter = m_ActivePoints.erase(iter); m_Label[tmpIndex1] = AlivePoint; } else // if not converge { if (newT1 < oldT1) { this->geodesic[tmpIndex1] = newT1; } iter++; } } } // Loop Through And Copy Only Values < than m_StopDistance int nv = m_meshPtr->vertices.size(); for (int v = 0; v < currentVert; v++) { if ((this->geodesic[v] <= m_StopDistance) && (this->geodesic[v] > 0)) { //m_meshPtr->geoMap[currentVert][v] = m_meshPtr->geodesic[v]; //(*(m_meshPtr->dMap))[currentVert].push_back(m_meshPtr->geodesic[v]); //(*(m_meshPtr->iMap))[currentVert].push_back(v); (this->geodesicMap[currentVert])[v] = this->geodesic[v]; } } // Now Erase the duplicate data this->CleanupAttributes(); endtime = clock(); total_duration = ( double) (endtime - starttime) / CLOCKS_PER_SEC; float percent = (currentVert + 1) / ( float) m_meshPtr->vertices.size(); double total_time = total_duration / percent; double time_left = total_time - total_duration; int hours = ( int) (time_left / (60 * 60)); int minutes = ( int) ((time_left - hours * 60 * 60) / 60); int seconds = ( int) (time_left - hours * 60 * 60 - minutes * 60); int count = (this->geodesicMap[currentVert]).size(); } } // SHIREEN - modified the loading to control the generation of geo files (till we add the geo repulsion stuff) void meshFIM::loadGeodesicFile(TriMesh *mesh, const char *geoFileName) { // cout << "Looking for file: " << geoFileName << " ... " << flush; std::ifstream infile(geoFileName, std::ios::binary); if (!infile.is_open()) { if(GENERATE_GEO_FILES == 1) { // cout << "File Not Found, will generate the geo file now ..." << endl; int numVert = mesh->vertices.size(); this->geodesicMap.resize(numVert); this->computeFIM(mesh,geoFileName); } // else // cout << "File Not Found and geo file generation is DISABLED ..." << endl; } else { int numVert = mesh->vertices.size(); //mesh->geoMap.resize(numVert); //mesh->geoIndex.resize(numVert); this->geodesicMap.resize(numVert); // read stop distance float distance; infile.read(reinterpret_cast<char *>(&distance), sizeof(float)); this->SetStopDistance(distance); // loop over vertices for (int i = 0; i < numVert; i++) { // read map size for vertex unsigned int dLength; infile.read( reinterpret_cast<char *>(&dLength), sizeof(unsigned int) ); // read key and distance pair for (int j = 0; j < dLength; j++) { unsigned int index; infile.read( reinterpret_cast<char *>(&index), sizeof(unsigned int) ); float dist; infile.read( reinterpret_cast<char *>(&dist), sizeof(float) ); (this->geodesicMap[i])[index] = dist; } } infile.close(); } } // end SHIREEN //Praful void meshFIM::computeCoordXFiles(TriMesh *mesh, const char *vertT_filename) { unsigned int numVert = mesh->vertices.size(); this->SetMesh(mesh); std::ofstream outfile(vertT_filename, std::ios::binary); std::cout << "# vertices in mesh: " << numVert << std::endl; outfile.write( reinterpret_cast<char *>(&numVert), sizeof(unsigned int) ); // loop over each vertex for (int i = 0; i < numVert; i++) { float coordVal = mesh->vertices[i][0]; outfile.write( reinterpret_cast<char *>(&coordVal), sizeof(float) ); } outfile.close(); } void meshFIM::computeCoordYFiles(TriMesh *mesh, const char *vertT_filename) { unsigned int numVert = mesh->vertices.size(); this->SetMesh(mesh); std::ofstream outfile(vertT_filename, std::ios::binary); std::cout << "# vertices in mesh: " << numVert << std::endl; outfile.write( reinterpret_cast<char *>(&numVert), sizeof(unsigned int) ); // loop over each vertex for (int i = 0; i < numVert; i++) { float coordVal = mesh->vertices[i][1]; outfile.write( reinterpret_cast<char *>(&coordVal), sizeof(float) ); } outfile.close(); } void meshFIM::computeCoordZFiles(TriMesh *mesh, const char *vertT_filename) { unsigned int numVert = mesh->vertices.size(); this->SetMesh(mesh); std::ofstream outfile(vertT_filename, std::ios::binary); std::cout << "# vertices in mesh: " << numVert << std::endl; outfile.write( reinterpret_cast<char *>(&numVert), sizeof(unsigned int) ); // loop over each vertex for (int i = 0; i < numVert; i++) { float coordVal = mesh->vertices[i][2]; outfile.write( reinterpret_cast<char *>(&coordVal), sizeof(float) ); } outfile.close(); } void meshFIM::computeCurvFiles(TriMesh *mesh, const char *vertT_filename) { unsigned int numVert = mesh->vertices.size(); this->SetMesh(mesh); std::ofstream outfile(vertT_filename, std::ios::binary); std::cout << "# vertices in mesh: " << numVert << std::endl; outfile.write( reinterpret_cast<char *>(&numVert), sizeof(unsigned int) ); // loop over each vertex for (int i = 0; i < numVert; i++) { float absCurvVal = this->abs_curv[i]; outfile.write( reinterpret_cast<char *>(&absCurvVal), sizeof(float) ); } outfile.close(); } //end Praful void meshFIM::computeFIM(TriMesh *mesh, const char *vertT_filename) { std::cout << "Trying to load: " << vertT_filename << std::endl; // FILE* vertTFile = fopen(vertT_filename, "r+"); std::ifstream infile(vertT_filename, std::ios::binary); unsigned int numVert = mesh->vertices.size(); //(mesh->dMap)->resize(numVert); //(mesh->iMap)->resize(numVert); this->geodesicMap.resize(numVert); this->SetMesh(mesh); if (!infile.is_open()) { //vertTFile = fopen(vertT_filename, "w+"); // ofstream outfile(vertT_filename, std::ios::binary); std::ofstream outfile(vertT_filename, std::ofstream::out); std::cout << "No vertT file!!!\n Writing..." << std::endl; std::cout << "stop distance = " << this->GetStopDistance() << std::endl; std::cout << "# vertices in mesh: " << numVert << std::endl; this->GenerateReducedData(); // write stop distance float dStop = this->GetStopDistance(); // outfile.write( reinterpret_cast<char *>(&dStop), sizeof(float) ); // loop over each vertex for (int i = 0; i < numVert; i++) { // write map size for vertex unsigned int dLength = this->geodesicMap[i].size(); // outfile.write( reinterpret_cast<char *>(&dLength), sizeof(unsigned int) ); // write key and distance pair for (std::map<unsigned int,float>::iterator it= this->geodesicMap[i].begin(); it != this->geodesicMap[i].end(); it++) { unsigned int index = (*it).first; // outfile.write( reinterpret_cast<char *>(&index), sizeof(unsigned int) ); float dist = (*it).second; // outfile.write( reinterpret_cast<char *>(&dist), sizeof(float) ); outfile << i << " " << index << " " << dist << std::endl; } } //// First Line In File Is Stop Distance //outfile << this->GetStopDistance() * s << endl; //// Loop Over Each Vertex //for (int i = 0; i < numVert; i++) //{ // std::map<unsigned int,unsigned int>::iterator mIter; // // for(mIter = mesh->geodesicMap[i].begin(); mIter != mesh->geodesicMap[i].end(); mIter++) // { // outfile << (*mIter).first << " " << (*mIter).second << " "; // } // outfile << endl; //} outfile.close(); } else { // read stop distance float distance; infile.read(reinterpret_cast<char *>(&distance), sizeof(float)); this->SetStopDistance(distance); // loop over vertices for (int i = 0; i < numVert; i++) { // read map size for vertex unsigned int dLength; infile.read( reinterpret_cast<char *>(&dLength), sizeof(unsigned int) ); // read key and distance pair for (int j = 0; j < dLength; j++) { unsigned int index; infile.read( reinterpret_cast<char *>(&index), sizeof(unsigned int) ); float dist; infile.read( reinterpret_cast<char *>(&dist), sizeof(float) ); (this->geodesicMap[i])[index] = dist; } } //unsigned int vertex; //unsigned int distance; //string line; //// First Line In File Is Stop Distance //getline(infile, line); //stringstream str(line); //str >> distance; // //this->SetStopDistance((float)distance/(float)s); // cout << "Loading " << vertT_filename << endl; //for(int i=0; i < numVert; i++){ // // string line; // getline(infile, line); // stringstream str(line); // // str >> vertex >> distance; // while(!str.eof()) // { // //mesh->geoMap[i].push_back(distance); // //mesh->geoIndex[i].push_back(vertex); // (mesh->geodesicMap[i])[vertex] = distance; // str >> vertex >> distance; // } // //printf("\r \r"); // //printf("progress %.1f%%", (i+1.0f)/(numVert)*100); // //fflush(stdout); // //} //cout << endl; infile.close(); } } void meshFIM::physicalPointToXYZ(point x, VoxelIndexType *imageX, float imageOrigin[3], float imageSpacing[3]) { imageX[0] = static_cast<VoxelIndexType> ((x[0] - imageOrigin[0]) / imageSpacing[0]); imageX[1] = static_cast<VoxelIndexType> ((x[1] - imageOrigin[1]) / imageSpacing[1]); imageX[2] = static_cast<VoxelIndexType> ((x[2] - imageOrigin[2]) / imageSpacing[2]); } meshFIM::VoxelIndexType meshFIM::indexToLinearIndex(VoxelIndexType *imageX, int imageSize[3]) { VoxelIndexType linearIndX = imageX[0] + imageX[1] * imageSize[0] + imageX[2] * imageSize[0] * imageSize[1]; return linearIndX; } meshFIM::VoxelIndexType meshFIM::physicalPointToLinearIndex(point x) { VoxelIndexType imageX[3]; this->physicalPointToXYZ(x, imageX, this->imageOrigin, this->imageSpacing); VoxelIndexType linearIndX = this->indexToLinearIndex(imageX, this->imageSize); return linearIndX; } meshFIM::VoxelIndexType meshFIM::physicalPointToLinearIndex(point x, float imageOrigin[3], float imageSpacing[3], int imageSize[3]) { VoxelIndexType imageX[3]; this->physicalPointToXYZ(x, imageX, imageOrigin, imageSpacing); VoxelIndexType linearIndX = this->indexToLinearIndex(imageX, imageSize); return linearIndX; } /* Prateep * http://www.geometrictools.com/Documentation/DistancePoint3Triangle3.pdf * ^t * \ | * \reg2| * \ | * \ | * \ | * \| * *P2 * |\ * | \ * reg3 | \ reg1 * | \ * |reg0\ * | \ * | \ P1 * -------*-------*------->s * |P0 \ * reg4 | reg5 \ reg6 */ double meshFIM::pointTriangleDistance(point P, TriMesh::Face face, point &PP) { // rewrite vertices in normal form point B = m_meshPtr->vertices[face[0]]; point E0 = m_meshPtr->vertices[face[1]] - B; point E1 = m_meshPtr->vertices[face[2]] - B; point D = B - P; float a = E0 DOT E0; float b = E0 DOT E1; float c = E1 DOT E1; float d = E0 DOT D; float e = E1 DOT D; float f = D DOT D; float det = a * c - b * b; float s = b * e - c * d; float t = b * d - a * e; float distSqr = 0.0f; if (s + t <= det) { if (s < 0) { if (t < 0) { // region 4 if (d < 0) { t = 0; if (-d >= a) { s = 1.0; distSqr = a + 2.0f * d + f; } else { s = -d / a; distSqr = d * s + f; } } else { s = 0.0f; if (e >= 0.0f) { t = 0.0f; distSqr = f; } else { if (-e >= c) { t = 1.0f; distSqr = c + 2.0f * e + f; } else { t = -e / c; distSqr = e * t + f; } } } // end of region 4 } else { // region 3 s = 0.0f; if (e >= 0.0f) { t = 0.0f; distSqr = f; } else { if (-e >= c) { t = 1.0f; distSqr = c + 2.0f * e + f; } else { t = -e / c; distSqr = e * t + f; } } } // end of region 3 } else { if (t < 0.0f) { // region 5 t = 0.0f; if (d >= 0.0f) { s = 0.0f; distSqr = f; } else { if (-d >= a) { s = 1.0f; distSqr = a + 2 * d + f; } else { s = -d / a; distSqr = d * s + f; } } // end of region 5 } else { // region 0 float invDet = 1.0f / det; s *= invDet; t *= invDet; distSqr = s * (a * s + b * t + 2 * d) + t * (b * s + c * t + 2 * e) + f; // end of region 0 } } } else { if (s < 0.0f) { // region 2 float tmp0 = b + d; float tmp1 = c + e; if (tmp1 > tmp0) { float numer = tmp1 - tmp0; float denom = a - 2 * b + c; if (numer >= denom) { s = 1.0f; t = 0.0f; distSqr = a + 2 * d + f; } else { s = numer / denom; t = 1.0 - s; distSqr = s * (a * s + b * t + 2 * d) + t * (b * s + c * t + 2 * e) + f; } } else { s = 0.0f; if (tmp1 <= 0.0f) { t = 1.0f; distSqr = c + 2 * e + f; } else { if (e >= 0.0f) { t = 0.0f; distSqr = f; } else { t = -e / c; distSqr = e * t + f; } } } // end of region 2 } else { if (t < 0) { // region 6 float tmp0 = b + e; float tmp1 = a + d; if (tmp1 > tmp0) { float numer = tmp1 - tmp0; float denom = a - 2 * b + c; if (numer >= denom) { t = 1.0f; s = 0.0f; distSqr = c + 2 * e + f; } else { t = numer / denom; s = 1.0 - t; distSqr = s * (a * s + b * t + 2 * d) + t * (b * s + c * t + 2 * e) + f; } } else { t = 0.0f; if (tmp1 <= 0.0f) { s = 1.0f; distSqr = a + 2 * d + f; } else { if (d >= 0.0f) { s = 0.0f; distSqr = f; } else { s = -d / a; distSqr = d * s + f; } } } // end of region 6 } else { // region 1 float numer = c + e - b - d; if (numer <= 0) { s = 0.0f; t = 1.0f; distSqr = c + 2 * e + f; } else { float denom = a - 2 * b + c; if (numer >= denom) { s = 1.0f; t = 0.0f; distSqr = a + 2 * d + f; } else { s = numer / denom; t = 1.0f - s; distSqr = s * (a * s + b * t + 2 * d) + t * (b * s + c * t + 2 * e) + f; } } // end of region 1 } } } if (distSqr < 0.0f) distSqr = 0.0f; float dist = std::sqrt(distSqr); PP = B + s * E0 + t * E1; return dist; } vec3 meshFIM::ComputeBarycentricCoordinates(point p, TriMesh::Face f) { vec3 bCoords; bCoords.clear(); point a, b, c; a = m_meshPtr->vertices[f[0]]; b = m_meshPtr->vertices[f[1]]; c = m_meshPtr->vertices[f[2]]; point n = (b - a) CROSS(c - a); normalize(n); float area = ((b - a) CROSS(c - a)) DOT n; float inv_area = 1.0f / (area + EPS); // shireen bCoords[0] = (((c - b) CROSS(p - b)) DOT n) * inv_area; // * areaInvPerTri[f];map <face, double> didnot work bCoords[1] = (((a - c) CROSS(p - c)) DOT n) * inv_area; // * areaInvPerTri[f];map <face, double> didnot work bCoords[2] = (((b - a) CROSS(p - a)) DOT n) * inv_area; // * areaInvPerTri[f];map <face, double> didnot work float sum = bCoords.sum(); bCoords[0] /= sum; bCoords[1] /= sum; bCoords[2] /= sum; return bCoords; } void meshFIM::need_maxedgelength() { this->need_edge_lengths(); for (int f = 0; f < m_meshPtr->faces.size(); f++) { for (int d = 0; d < 3; d++) { if (this->edgeLengthsVector[f][d] >= maxEdgeLength) { maxEdgeLength = this->edgeLengthsVector[f][d]; } } } } int meshFIM::FindNearestVertex(point pt) { //std::cerr << "FindNearestVertexA\n"; if (!kd) { kd = new KDtree(m_meshPtr->vertices); } //std::cerr << "FindNearestVertexB\n"; if (maxEdgeLength == 0.0) { need_maxedgelength(); } //std::cerr << "FindNearestVertexC\n"; const float *match = kd->closest_to_pt(pt, 100000.0 * maxEdgeLength * maxEdgeLength); // SHIREEN - enlargen the neighborhood size for kdtree to find a match int imatch = 0; if (!match) { std::cout << "failed to find vertex within " << maxEdgeLength << " for point " << pt << ". using vertex 0" << std::endl; return imatch; } //std::cerr << "FindNearestVertexD\n"; imatch = (match - (const float *) & (m_meshPtr->vertices[0][0])) / 3; return imatch; } int meshFIM::GetTriangleInfoForPoint(point x, TriMesh::Face &triangleX, float &alphaX, float &betaX, float &gammaX) { int faceID; //std::cerr << "GetTriangleInfoForPoint\n"; if (this->faceIndexMap.size() > 0) // there is a generated face index map so used it { std::cerr << "Doing face index stuff\n"; // Physical point to Image Index VoxelIndexType linearIndX = this->physicalPointToLinearIndex(x); // collect face indices for this voxel std::map<VoxelIndexType, std::vector<int> >::iterator it = this->faceIndexMap.find(linearIndX); if (it != this->faceIndexMap.end()) // see if the linearIndX already exist in the face index map { // std::cout << "WOW, fids will be used ... \n" ; std::vector<int> faceList = this->faceIndexMap[linearIndX]; double minDist = LARGENUM; int winnerIndex; for (std::vector<int>::iterator it = faceList.begin(); it != faceList.end(); ++it) { triangleX = m_meshPtr->faces[(*it)]; // project the point onto the plane of the current triangle point projPoint; double dist = this->pointTriangleDistance(x, triangleX, projPoint); if (dist < minDist) { minDist = dist; winnerIndex = (*it); } } triangleX = m_meshPtr->faces[winnerIndex]; faceID = winnerIndex; point projPoint; double dist = this->pointTriangleDistance(x, triangleX, projPoint); vec3 barycentric = this->ComputeBarycentricCoordinates(projPoint, triangleX); alphaX = barycentric[0]; betaX = barycentric[1]; gammaX = barycentric[2]; return faceID; } } #if SHOW_WARNING std::cerr << "warning: using kdtree for triangle info because there is no face index map !!! ...\n"; #endif //std::cerr << "warning: using kdtree for triangle info because there is no face index map !!! ...\n"; // get vertex closest to first point - x int vertX = this->FindNearestVertex(x); //std::cerr << "FindNearestVertex finished\n"; unsigned int fNumber; // scan all adjacent faces to see which face (f) includes point x triangleX = m_meshPtr->faces[m_meshPtr->adjacentfaces[vertX][0]]; faceID = m_meshPtr->adjacentfaces[vertX][0]; for (fNumber = 0; fNumber < m_meshPtr->adjacentfaces[vertX].size(); fNumber++) { // check if face contains x and store barycentric coordinates for x in face f triangleX = m_meshPtr->faces[m_meshPtr->adjacentfaces[vertX][fNumber]]; faceID = m_meshPtr->adjacentfaces[vertX][fNumber]; vec3 barycentric = this->ComputeBarycentricCoordinates(x, triangleX); alphaX = barycentric[0]; betaX = barycentric[1]; gammaX = barycentric[2]; if (((barycentric[0] >= 0) && (barycentric[0] <= 1)) && ((barycentric[1] >= 0) && (barycentric[1] <= 1)) && ((barycentric[2] >= 0) && (barycentric[2] <= 1))) { fNumber = m_meshPtr->adjacentfaces[vertX].size(); } } if (alphaX < 0.0 || betaX < 0.0f || gammaX < 0.0f) { int t = 0; } return faceID; } float meshFIM::GetVirtualSource(vnl_vector<float> baryCoord, vnl_matrix<float> X, vnl_vector<float> ds, vnl_vector< float > &x0) { // vcl_cout<<"X:"<<std::endl<<X.extract(2,3,0,0); // vcl_cout<<"ds: "<<ds<<std::endl; vgl_homg_point_2d<float> centre1(X(0, 0), X(1, 0), 1); vgl_homg_point_2d<float> centre2(X(0, 1), X(1, 1), 1); vgl_homg_point_2d<float> centre3(X(0, 2), X(1, 2), 1); vgl_conic<float> circle1(centre1, ds[0], ds[0], 0.0f); vgl_conic<float> circle2(centre2, ds[1], ds[1], 0.0f); vgl_conic<float> circle3(centre3, ds[2], ds[2], 0.0f); // vcl_cout<<"Circle1: "<<circle1<<std::endl; // vcl_cout<<"Circle2: "<<circle2<<std::endl; // vcl_cout<<"Circle3: "<<circle3<<std::endl; vcl_list<vgl_homg_point_2d<float> > pts1; pts1 = vgl_homg_operators_2d<float>::intersection(circle1, circle2); int n1 = ( int) (pts1.size()); vcl_list<vgl_homg_point_2d<float> > pts2; pts2 = vgl_homg_operators_2d<float>::intersection(circle2, circle3); int n2 = ( int) (pts2.size()); vcl_list<vgl_homg_point_2d<float> > pts3; pts3 = vgl_homg_operators_2d<float>::intersection(circle1, circle3); int n3 = ( int) (pts3.size()); int n = n1 + n2 + n3; // std::cout<<"n= "<<n<<std::endl; if (n == 0) { x0 = vnl_vector<float>(2, -1.0f); return -1.0f; } else { vnl_matrix< float > xinit(2, n, 0); int i = 0; typedef vcl_list< vgl_homg_point_2d < float > > container; vgl_homg_point_2d<float> temp; for (container::iterator p = pts1.begin(); p != pts1.end(); p++) { // std::cout<<"n1 = "<<n1<<std::endl; temp = *p; if (!std::isfinite(temp.x()) || !std::isfinite(temp.y()) || !std::isfinite(temp.w())) continue; // std::cout<<"x: "<<temp.x()<<" y: "<<temp.y()<<" w: "<<temp.w()<<std::endl; xinit(0, i) = temp.x() / temp.w(); xinit(1, i) = temp.y() / temp.w(); // vcl_cout<<"i= "<<i<<" xinit(i)="<<xinit.get_column(i)<<std::endl; i++; } for (container::iterator p = pts2.begin(); p != pts2.end(); p++) { // std::cout<<"n2 = "<<n2<<std::endl; temp = *p; if (!std::isfinite(temp.x()) || !std::isfinite(temp.y()) || !std::isfinite(temp.w())) continue; // std::cout<<"x: "<<temp.x()<<" y: "<<temp.y()<<" w: "<<temp.w()<<std::endl; xinit(0, i) = temp.x() / temp.w(); xinit(1, i) = temp.y() / temp.w(); // vcl_cout<<"i= "<<i<<" xinit(i)="<<xinit.get_column(i)<<std::endl; i++; } for (container::iterator p = pts3.begin(); p != pts3.end(); p++) { // std::cout<<"n3 = "<<n3<<std::endl; temp = *p; if (!std::isfinite(temp.x()) || !std::isfinite(temp.y()) || !std::isfinite(temp.w())) continue; // std::cout<<"x: "<<temp.x()<<" y: "<<temp.y()<<" w: "<<temp.w()<<std::endl; xinit(0, i) = temp.x() / temp.w(); xinit(1, i) = temp.y() / temp.w(); // vcl_cout<<"i= "<<i<<" xinit(i)="<<xinit.get_column(i)<<std::endl; i++; } if (i == 0) { x0 = vnl_vector<float>(2, -1.0f); return -1.0f; } // vcl_cout<<"xinit:"<<std::endl<<xinit.extract(2,n,0,0)<<std::endl; // vcl_cout<<"xinit:"<<std::endl<<xinit.extract(2,i,0,0)<<std::endl; double minE = 10000000000.0; int flag = 0; int winner = -1; for (int i1 = 0; i1 < i; i1++) { double energy = 0.0; vnl_vector<float> pt = xinit.get_column(i1); // vcl_cout<<"pt= "<<pt<<std::endl; for (int j = 0; j < 3; j++) { vnl_vector<float> tmp1 = pt - X.get_column(j); float residual = std::abs(tmp1.squared_magnitude() - ds[j] * ds[j]); //write the dot product in place of tmp1.*tmp1 energy += ( double) (residual * baryCoord[j]); // float residual = tmp1.squared_magnitude() - ds[j]*ds[j]; //write the dot product in place of tmp1.*tmp1 // energy += (double)(residual*residual*baryCoord[j]); } // std::cout<<"Energy: "<<energy<<std::endl; if (flag == 0) { minE = energy; winner = i1; flag = 1; } else { if (energy < minE) { minE = energy; winner = i1; } } } // std::cout<<winner<<std::endl; x0 = xinit.get_column(winner); // vcl_cout<<"x0: "<<x0<<std::endl; return 1.0f; } } namespace { /* Praful */ float ComputeGradient(vnl_vector<float> x0, vnl_vector<float> baryCoord, vnl_matrix<float> X, vnl_vector<float> ds, vnl_vector<float> &G) { G = vnl_vector<float>(2, 0.0f); for (int k = 0; k < 2; k++) { for (int ii = 0; ii < 3; ii++) { vnl_vector<float> xi = X.get_column(ii); vnl_vector<float> tmp = x0 - xi; float residual = dot_product(tmp, tmp) - ds[ii] * ds[ii]; G[k] += 4 * baryCoord[ii] * residual * tmp[k]; } } return 1.0f; } /* Praful */ float ComputeHessian(vnl_vector<float> x0, vnl_vector<float> baryCoord, vnl_matrix<float> X, vnl_vector<float> ds, vnl_matrix<float> &H) { H = vnl_matrix<float>(2, 2, 0.0f); for (int k = 0; k < 2; k++) { for (int kp = 0; kp < 2; kp++) { for (int ii = 0; ii < 3; ii++) { vnl_vector<float> xi = X.get_column(ii); vnl_vector<float> tmp = x0 - xi; float residual = dot_product(tmp, tmp) - ds[ii] * ds[ii]; if (k == kp) { H(k, k) += 4 * baryCoord[ii] * (residual + 2 * tmp[k] * tmp[k]); } else { H(k, kp) += 8 * baryCoord[ii] * tmp[k] * tmp[kp]; } } } } return 1.0f; } } float meshFIM::ComputeThreePointApproximatedGeodesic(vnl_vector<float> x, vnl_vector<float> baryCoord, vnl_matrix<float> X, vnl_vector<float> ds, char *method) { float geo_approx = -1.0f; vnl_vector<float> x0; // std::cout<<"check4"<<std::endl; float n = this->GetVirtualSource(baryCoord, X, ds, x0); // std::cout<<"check5"<<std::endl; char check2[] = "Bary"; if (n == -1.0f || strcmp(method, check2) == 0) { // std::cout<<"Using Bary..."<<std::endl; geo_approx = dot_product(baryCoord, ds); } else { char check1[] = "Newton"; if (strcmp(method, check1) == 0) //Newton method { // std::cout<<"Using Newton iterations..."<<std::endl; // vcl_cout<<"Initial x0= "<<x0<<std::endl; float eta = 1.0f; for (int iter = 0; iter < 10; iter++) { vnl_matrix<float> H; vnl_vector<float> G; ComputeGradient(x0, baryCoord, X, ds, G); ComputeHessian(x0, baryCoord, X, ds, H); vnl_matrix<float> Hinv = vnl_matrix_inverse<float>(H); x0 -= eta * Hinv * G; } // vcl_cout<<"Final x0= "<<x0<<std::endl; } else //LM method { // std::cout<<"LM..coming soon.."<<std::endl; // std::cout<<"Using LM..."<<std::endl; float v = 2.0f; float eps1 = 0.000001f; float eps2 = 0.000001f; float tau = 0.001f; int m = 3; int n = 2; float k = 0.0f; float kmax = 10.0f; // computing Jacobian // vcl_cout<<"x0: "<<std::endl<<x0<<std::endl; // vcl_cout<<"baryCoord: "<<std::endl<<baryCoord<<std::endl; vnl_matrix<float> J(m, n, 0.0f); for (int i = 0; i < m; i++) { vnl_vector<float> xi = X.get_column(i); // vcl_cout<<"xi: "<<std::endl<<xi<<std::endl; for (int j = 0; j < n; j++) { J(i, j) = 2.0f * ( float) (std::sqrt(baryCoord[i])) * (x0[j] - xi[j]); } } // vcl_cout<<"J: "<<std::endl<<J.extract(m,n,0,0)<<std::endl; // computing function values given the current guess vnl_vector<float> f(m, 0.0f); for (int i = 0; i < m; i++) { vnl_vector<float> xi = X.get_column(i); float di = ds[i]; vnl_vector<float> x0_m_xi; x0_m_xi = x0 - xi; float r_i = dot_product(x0_m_xi, x0_m_xi) - di * di; f[i] = ( float) (std::sqrt(baryCoord[i])) * r_i; } float F; F = dot_product(f, f); F = 0.5f * F; vnl_matrix<float> A(n, n, 0.0f); A = J.transpose() * J; vnl_vector<float> g(n, 0.0f); g = J.transpose() * f; vnl_vector<float> diagA = A.get_diagonal(); float max_diagA = diagA.max_value(); float mu = tau * max_diagA; float norm_g = g.two_norm(); vnl_matrix<float> muId(n, n, 0.0f); vnl_matrix<float> A_mu(n, n, 0.0f); vnl_matrix<float> A_mu_inv; vnl_vector<float> hlm(n, 0.0f); vnl_vector<float> xnew(n, 0.0f); vnl_vector<float> fnew(m, 0.0f); float Fnew = 0.0f, delta_L = 0.0f, rho = 0.0f; // std::cout<<"****************"<<std::endl; bool found = norm_g <= eps1; while (!found && k < kmax) { k = k + 1.0f; muId.set_identity(); muId = mu * muId; A_mu = A + muId; // std::cout<<"check4"<<std::endl; // vcl_cout<<"A: "<<std::endl<<A.extract(n,n,0,0)<<std::endl; // std::cout<<"mu: "<<mu<<std::endl; // vcl_cout<<"A_mu: "<<std::endl<<A_mu.extract(n,n,0,0)<<std::endl; A_mu_inv = vnl_matrix_inverse<float>(A_mu); // std::cout<<"check51"<<std::endl; // vcl_cout<<"A_mu_inv: "<<std::endl<<A_mu_inv.extract(n,n,0,0)<<std::endl; A_mu_inv = -1.0f * A_mu_inv; // vcl_cout<<"A_mu_inv: "<<std::endl<<A_mu_inv.extract(n,n,0,0)<<std::endl; hlm = A_mu_inv * g; float norm_hlm = hlm.two_norm(); float norm_x0 = x0.two_norm(); if (norm_hlm <= (eps1 * (norm_x0 + eps2))) { found = true; } else { xnew = x0 + hlm; for (int i = 0; i < m; i++) { vnl_vector<float> xi = X.get_column(i); float di = ds[i]; vnl_vector<float> x_m_xi; x_m_xi = xnew - xi; float r_i = dot_product(x_m_xi, x_m_xi) - di * di; fnew[i] = ( float) (std::sqrt(baryCoord[i])) * r_i; } Fnew = dot_product(fnew, fnew); Fnew = 0.5f * Fnew; delta_L = 0.5f * dot_product(hlm, (mu * hlm - g)); rho = (F - Fnew) / delta_L; if (rho > 0.0f) { x0 = xnew; // computing Jacobian for (int i = 0; i < m; i++) { vnl_vector<float> xi = X.get_column(i); for (int j = 0; j < n; j++) { J(i, j) = 2.0f * ( float) (std::sqrt(baryCoord[i])) * (x0[j] - xi[j]); } } // computing function values given the current guess for (int i = 0; i < m; i++) { vnl_vector<float> xi = X.get_column(i); float di = ds[i]; vnl_vector<float> x0_m_xi; x0_m_xi = x0 - xi; float r_i = dot_product(x0_m_xi, x0_m_xi) - di * di; f[i] = ( float) (std::sqrt(baryCoord[i])) * r_i; } F = dot_product(f, f); F = 0.5f * F; A = J.transpose() * J; g = J.transpose() * f; norm_g = g.two_norm(); found = norm_g <= eps1; // std::cout<<"=================="<<std::endl; // std::cout<<"mu= "<<mu<<std::endl; // std::cout<<"=================="<<std::endl; float cmp1 = 1.0f - (2.0f * rho - 1.0f) * (2.0f * rho - 1.0f) * (2.0f * rho - 1.0f); if (0.3f > cmp1) { mu = mu * 0.3f; } else { mu = mu * cmp1; } // std::cout<<"=================="<<std::endl; // std::cout<<"cmp1= "<<cmp1<<" mu= "<<mu<<std::endl; // std::cout<<"=================="<<std::endl; v = 2.0f; } else { mu = mu * v; v = 2.0f * v; } } } // vcl_cout<<x0<<std::endl; } geo_approx = (x0 - x).two_norm(); } //end else xinit not empty // std::cout<<"Returning geo_approx..."<<geo_approx<<std::endl; return geo_approx; } float meshFIM::ComputeCanonicalForm(point s, vnl_vector<float> &x, vnl_matrix<float> &X)//, Face S) { TriMesh::Face S; float alpS, betS, gamS; GetTriangleInfoForPoint(s, S, alpS, betS, gamS); vnl_matrix<float> S_(3, 3); vnl_vector<float> muS(3, 0); for (int i = 0; i < 3; i++) { point vertex = m_meshPtr->vertices[S[i]]; for (int j = 0; j < 3; j++) S_(i, j) = ( float) (vertex[j]); } // std::cout<<"*****************"<<std::endl; // vcl_cout<<"Face: "<<std::endl<<S_.extract(3,3,0,0)<<std::endl; // std::cout<<"*****************"<<std::endl; S_ = S_.transpose(); // std::cout<<"*****************"<<std::endl; // vcl_cout<<"Transposed: "<<std::endl<<S_.extract(3,3,0,0)<<std::endl; // std::cout<<"*****************"<<std::endl; for (int r = 0; r < 3; r++) { for (int c = 0; c < 3; c++) muS[r] += S_(r, c); muS[r] /= 3.0f; } // std::cout<<"*****************"<<std::endl; // vcl_cout<<"muS: "<<std::endl<<muS<<std::endl; // std::cout<<"*****************"<<std::endl; // Scent = S - muS vnl_matrix<float> Scent(3, 3); for (int r = 0; r < 3; r++) { for (int c = 0; c < 3; c++) Scent(r, c) = S_(r, c) - muS[r]; } // vcl_cout<<"Scent: "<<Scent.extract(3,3,0,0)<<std::endl; vnl_svd<float> svd(Scent); // bool vld_svd = vnl_svd<float>::valid(); // std::cout<<"Valid SVD? "<<vld_svd<<std::endl; // std::cout<<"checkpoint SVD"<<std::endl; // vnl_diag_matrix<point::value_type> W_ = svd.W(); vnl_matrix<float> U_ = svd.U(); // vcl_cout<<"U_: "<<U_.extract(3,2,0,0)<<std::endl; // std::cout<<"check32"<<std::endl; // vnl_matrix<point::value_type> V_ = svd.V(); /* top 2 eigen vectors */ vnl_matrix<float> U(3, 2); for (int r = 0; r < 3; r++) { for (int c = 0; c < 2; c++) U(r, c) = U_(r, c); } // std::cout<<"............................"<<std::endl; // vcl_cout<<"U: "<<U.extract(2,3,0,0)<<std::endl; // std::cout<<"............................"<<std::endl; /*vnl_matrix<point::value_type>*/ X = U.transpose() * Scent; vnl_vector<float> sCent(3); for (int c = 0; c < 3; c++) sCent[c] = s[c] - muS[c]; /*vnl_vector<point::value_type>*/ x = U.transpose() * sCent; // std::cout<<"-----------------------------"<<std::endl; // vcl_cout<<x<<std::endl; // std::cout<<"-----------------------------"<<std::endl; return 1.0f; // printing for debugging // std::cout<<std::endl<<std::endl<<"Canonical form computed..."<<std::endl; // vcl_cerr<<x; // std::cout<<std::endl; // vcl_cerr<<X.extract(2,3,0,0); } float meshFIM::GetGeodesicDistance(int v1, int v2) { float gDist = 0.000001f; if (v1 == v2) return gDist; int vert = v1; int key = v2; if (v2 > v1) { vert = v2; key = v1; } std::map<unsigned int, float>::iterator geoIter = this->geodesicMap[vert].find(key); if (geoIter != this->geodesicMap[vert].end()) { gDist = geoIter->second; } else { gDist = LARGENUM; } return gDist; } float meshFIM::GetBronsteinGeodesicDistance(TriMesh::Face Sa, TriMesh::Face Sb, vnl_vector <float> baryCoord_a, vnl_vector <float> baryCoord_b, char *method) { point a; a.clear(); point b; b.clear(); for (int d1 = 0; d1 < 3; d1++) { a[d1] = 0.0; b[d1] = 0.0; for (int d2 = 0; d2 < 3; d2++) { point vt = m_meshPtr->vertices[Sa[d2]]; a[d1] += baryCoord_a[d2] * vt[d1]; point vt2 = m_meshPtr->vertices[Sb[d2]]; b[d1] += baryCoord_b[d2] * vt2[d1]; } } float alp_a, alp_b, bet_a, bet_b, gam_a, gam_b; alp_a = baryCoord_a[0]; bet_a = baryCoord_a[1]; gam_a = baryCoord_a[2]; alp_b = baryCoord_b[0]; bet_b = baryCoord_b[1]; gam_b = baryCoord_b[2]; if (alp_a < 0.000001f) { alp_a = 0.000001f; } if (bet_a < 0.000001f) { bet_a = 0.000001f; } if (gam_a < 0.000001f) { gam_a = 0.000001f; } if (alp_b < 0.000001f) { alp_b = 0.000001f; } if (bet_b < 0.000001f) { bet_b = 0.000001f; } if (gam_b < 0.000001f) { gam_b = 0.000001f; } alp_a /= (alp_a + bet_a + gam_a); bet_a /= (alp_a + bet_a + gam_a); gam_a /= (alp_a + bet_a + gam_a); alp_b /= (alp_b + bet_b + gam_b); bet_b /= (alp_b + bet_b + gam_b); gam_b /= (alp_b + bet_b + gam_b); baryCoord_a[0] = alp_a; baryCoord_a[1] = bet_a; baryCoord_a[2] = gam_a; baryCoord_b[0] = alp_b; baryCoord_b[1] = bet_b; baryCoord_b[2] = gam_b; vnl_vector<float> xA(2); vnl_vector<float> xB(2); vnl_matrix<float> Xa(2, 3); vnl_matrix<float> Xb(2, 3); if (baryCoord_a.max_value() > 1.0f || baryCoord_a.min_value() < 0.0f || baryCoord_b.max_value() > 1.0f || baryCoord_b.min_value() < 0.0f) { std::cerr << "incorrect barycentric coordinates...!!" << std::endl; std::cerr << "baryCoord_a: " << baryCoord_a << std::endl; std::cerr << "baryCoord_b: " << baryCoord_b << std::endl; return EXIT_FAILURE; } ComputeCanonicalForm(a, xA, Xa); ComputeCanonicalForm(b, xB, Xb); vnl_matrix<float> dA_2_B(3, 3); bool tooFar = false; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { dA_2_B(i, j) = this->GetGeodesicDistance(Sa[i], Sb[j]); // SHIREEN: if triangles are too far, don't bother to complete if (dA_2_B(i, j) == LARGENUM) { tooFar = true; break; } } if (tooFar) break; } if (tooFar) return LARGENUM; vnl_vector<float> geo_approx_2_B(3); for (int vertB_id = 0; vertB_id < 3; vertB_id++) geo_approx_2_B[vertB_id] = ComputeThreePointApproximatedGeodesic(xA, baryCoord_a, Xa, dA_2_B.get_column(vertB_id), method); float dGeo_a_2_b = 0.0f; dGeo_a_2_b = ComputeThreePointApproximatedGeodesic(xB, baryCoord_b, Xb, geo_approx_2_B, method); return dGeo_a_2_b; } // Praful - compute distance to landmarks based on geodesic approximation with given triangle info void meshFIM::ComputeDistanceToLandmarksGivenTriangleInfo(TriMesh *mesh, const char *infilename , const char *outfilename) { // initialize the geodesic map to hold the geodesics from the triangle vertices of the given landmark to all other mesh vertices SetStopDistance(1e7); int numVert = mesh->vertices.size(); this->geodesicMap.resize(numVert); SetMesh(mesh); std::ifstream pointsFile(infilename); std::ofstream outfile(outfilename); if (!pointsFile) { std::cerr << "points file not found: " << infilename << std::endl; } int count = 0; while(pointsFile) { point tmpPt; tmpPt.clear(); vnl_vector<float> baryCoords(3, 0.0); int faceId; for (int d=0; d<3; d++) pointsFile >> tmpPt[d]; if (!pointsFile) { count--; break; } pointsFile >> faceId; if (!pointsFile) { count--; break; } for (int d=0; d<3; d++) pointsFile >> baryCoords[d]; if (!pointsFile) { count--; break; } TriMesh::Face triangleX = mesh->faces[faceId]; std::vector<int> vertexIdlist; vertexIdlist.clear(); vertexIdlist.push_back(triangleX[0]); vertexIdlist.push_back(triangleX[1]); vertexIdlist.push_back(triangleX[2]); // update the geodesic map with geodesic distances from each triangle vertex to all other mesh vertices UpdateGeodesicMapWithDistancesFromVertices(vertexIdlist); std::cout << "Point# " << count++ << " fid: " << faceId << " baryCoords: " << baryCoords[0] << " " << baryCoords[1] << " " << baryCoords[2] << std::endl; for (int i = 0; i < numVert; i++) { // std::cout << "Vertex: " << i << std::endl; point curVertex = mesh->vertices[i]; TriMesh::Face vertFace = mesh->faces[mesh->adjacentfaces[i][0]]; vec3 barycentric = this->ComputeBarycentricCoordinates(curVertex, vertFace); vnl_vector<float> baryVert(3, 0.0); for (int d = 0; d < 3; d++) baryVert[d] = barycentric[d]; float distToLandmark = this->GetBronsteinGeodesicDistance(triangleX, vertFace, baryCoords, baryVert, (char*) "LM"); outfile << distToLandmark << " "; } outfile << std::endl; } std::cout << "Total number of points: " << count+1 << std::endl; pointsFile.close(); outfile.close(); } /* Praful */ float meshFIM::GetBronsteinGeodesicDistance(point a, point b, char *method)//, Face Sa, Face Sb, vnl_vector <float> baryCoord_a, vnl_vector <float> baryCoord_b) { TriMesh::Face Sa, Sb; vnl_vector <float> baryCoord_a(3), baryCoord_b(3); float alp_a, alp_b, bet_a, bet_b, gam_a, gam_b; GetTriangleInfoForPoint(a, Sa, alp_a, bet_a, gam_a); GetTriangleInfoForPoint(b, Sb, alp_b, bet_b, gam_b); float dGeo_a_2_b = GetBronsteinGeodesicDistance(Sa, Sb, baryCoord_a, baryCoord_b, method); return dGeo_a_2_b; } // SHIREEN - compute distance to landmarks based on geodesic approximation void meshFIM::ComputeDistanceToLandmark(TriMesh *mesh, point landmark, bool apply_log, const char *outfilename) { // initialize the geodesic map to hold the geodesics from the triangle vertices of the given landmark to all other mesh vertices int numVert = mesh->vertices.size(); this->geodesicMap.resize(numVert); SetMesh(mesh); // get which triangle the given landmark should belong to TriMesh::Face triangleX; float alphaX, betaX, gammaX; int faceId = this->GetTriangleInfoForPoint(landmark, triangleX, alphaX, betaX, gammaX); std::vector<int> vertexIdlist; vertexIdlist.clear(); vertexIdlist.push_back(triangleX[0]); vertexIdlist.push_back(triangleX[1]); vertexIdlist.push_back(triangleX[2]); // update the geodesic map with geodesic distances from each triangle vertex to all other mesh vertices UpdateGeodesicMapWithDistancesFromVertices(vertexIdlist); // now start approximating the geodesics to the given landmarks based on the geodesics to its triangle vertices // write out distance to curve std::ofstream outfile(outfilename, std::ios::binary); // write numVertices to facilitate reading later outfile.write( reinterpret_cast<char *>(&numVert), sizeof(unsigned int) ); //std::cout << "vertices (" << numVert << "): "; // loop over each vertex for (int i = 0; i < numVert; i++) { //if ((i % 50) == 0) // std::cout << std::endl; //std::cout << i << ", "; point curVertex = mesh->vertices[i]; float distToLandmark = this->GetBronsteinGeodesicDistance(landmark, curVertex, (char*) "LM"); distToLandmark += 0.00001f; if (apply_log) distToLandmark = std::log(distToLandmark); // write distance to curve outfile.write( reinterpret_cast<char *>(&distToLandmark), sizeof(float) ); } //std::cout << std::endl; outfile.close(); } void meshFIM::UpdateGeodesicMapWithDistancesFromVertices(std::vector<int> vertexIdlist) { std::list<index>::iterator iter = m_ActivePoints.begin(); float oldT1 , newT1, oldT2, newT2; index tmpIndex1, tmpIndex2; std::vector<int> nb; int i = 0; for (int ii = 0 ; ii < vertexIdlist.size(); ii++) { int currentVert = vertexIdlist[ii]; std::vector<int> seedPointList(1, currentVert); SetSeedPoint(seedPointList); this->InitializeAttributes(currentVert, m_SeedPoints); InitializeLabels(); InitializeActivePoints(); // to enable computing geodesic from the current vertex to all mesh vertices SetStopDistance(LARGENUM); while (!m_ActivePoints.empty()) { //printf("Size of Activelist is: %d \n", m_ActivePoints.size()); iter = m_ActivePoints.begin(); while(iter != m_ActivePoints.end()) { tmpIndex1 = *iter; nb = m_meshPtr->neighbors[tmpIndex1]; oldT1 = this->geodesic[tmpIndex1]; newT1 = Upwind(currentVert,tmpIndex1); if (abs(oldT1-newT1)<_EPS) //if converges { if (oldT1>newT1){ this->geodesic[tmpIndex1] = newT1; } if(this->geodesic[tmpIndex1] < m_StopDistance) { for (i=0;i<nb.size();i++) { tmpIndex2 = nb[i]; if (m_Label[tmpIndex2]==AlivePoint || m_Label[tmpIndex2]==FarPoint) { oldT2 = this->geodesic[tmpIndex2]; newT2 = Upwind(currentVert,tmpIndex2); if (oldT2>newT2) { this->geodesic[tmpIndex2] = newT2; if (m_Label[tmpIndex2]!=ActivePoint) { m_ActivePoints.insert(iter, tmpIndex2); //iter++; m_Label[tmpIndex2] = ActivePoint; } } } } } iter = m_ActivePoints.erase(iter); m_Label[tmpIndex1] = AlivePoint; } else // if not converge { if(newT1 < oldT1){ this->geodesic[tmpIndex1] = newT1; } iter++; } } } // Loop Through And Copy Only Values < than int nv = m_meshPtr->vertices.size(); for(int v = 0; v < nv; v++){ if ((this->geodesic[v] <= m_StopDistance) && (this->geodesic[v] > 0)) { int v1 = currentVert; int v2 = v; int vert = v1; int key = v2; if (v2 > v1) { vert = v2; key = v1; } //(m_meshPtr->geodesicMap[currentVert])[v] = m_meshPtr->geodesic[v]; (this->geodesicMap[vert])[key] = this->geodesic[v]; } } // Now Erase the duplicate data this->CleanupAttributes(); } } // end SHIREEN // SHIREEN - compute distance to curve based on geodesic approximation void meshFIM::ComputeDistanceToCurve(TriMesh *mesh, std::vector< point > curvePoints, const char *outfilename) { // initialize the geodesic map to hold the geodesics from the triangle vertices of the given landmark to all other mesh vertices int numVert = mesh->vertices.size(); this->geodesicMap.resize(numVert); SetMesh(mesh); // get which triangle the given landmark should belong to TriMesh::Face triangleX; float alphaX, betaX, gammaX; std::vector<int> vertexIdlist; vertexIdlist.clear(); for (int pIndex = 0; pIndex < curvePoints.size(); pIndex++) { int faceId = this->GetTriangleInfoForPoint(curvePoints[pIndex], triangleX, alphaX, betaX, gammaX); vertexIdlist.push_back(triangleX[0]); vertexIdlist.push_back(triangleX[1]); vertexIdlist.push_back(triangleX[2]); } // update the geodesic map with geodesic distances from each triangle vertex of each curve point to all other mesh vertices UpdateGeodesicMapWithDistancesFromVertices(vertexIdlist); // now start approximating the geodesics to the given curve points based on the geodesics to its triangle vertices // write out distance to curve std::ofstream outfile(outfilename, std::ios::binary); // write numVertices to facilitate reading later outfile.write( reinterpret_cast<char *>(&numVert), sizeof(unsigned int) ); //std::cout << "vertices (" << numVert << "): "; // loop over each vertex for (int i = 0; i < numVert; i++) { float distToCurve = 1e20; point curVertex = mesh->vertices[i]; for (int pIndex = 0; pIndex < curvePoints.size(); pIndex++) { point landmark = curvePoints[pIndex]; float curDist = this->GetBronsteinGeodesicDistance(landmark, curVertex, (char*) "LM"); if (curDist < distToCurve) distToCurve = curDist; } distToCurve += 0.00001f; // write distance to curve outfile.write( reinterpret_cast<char *>(&distToCurve), sizeof(float) ); } //std::cout << std::endl; outfile.close(); } // end SHIREEN int meshFIM::GetVertexInfoForPoint(point x) { int vertX; TriMesh::Face triangleX; float alphaX, betaX, gammaX; if (this->faceIndexMap.size() > 0) // there is a generated face index map so used it { //std::cout << "WOW, fids will be used ... \n" ; // Physical point to Image Index VoxelIndexType linearIndX = this->physicalPointToLinearIndex(x); // collect face indices for this voxel std::map<VoxelIndexType, std::vector<int> >::iterator it = this->faceIndexMap.find(linearIndX); if (it != this->faceIndexMap.end()) { std::vector<int> faceList = this->faceIndexMap[linearIndX]; double minDist = LARGENUM; int winnerIndex; for (std::vector<int>::iterator it = faceList.begin(); it != faceList.end(); ++it) { triangleX = m_meshPtr->faces[(*it)]; // project the point onto the plane of the current triangle point projPoint; double dist = this->pointTriangleDistance(x, triangleX, projPoint); if (dist < minDist) { minDist = dist; winnerIndex = (*it); } } triangleX = m_meshPtr->faces[winnerIndex]; point projPoint; double dist = this->pointTriangleDistance(x, triangleX, projPoint); vec3 barycentric = this->ComputeBarycentricCoordinates(projPoint, triangleX); alphaX = barycentric[0]; betaX = barycentric[1]; gammaX = barycentric[2]; // get vertex closest to first point - x vertX = this->FindNearestVertex(projPoint); } else //kdtree based { #if SHOW_WARNING std::cout << "warning: using kdtree for triangle info because voxel index " << linearIndX << " is not found in the face index map !!! ...\n"; #endif // get vertex closest to first point - x vertX = this->FindNearestVertex(x); // scan all adjacent faces to see which face (f) includes point x triangleX = m_meshPtr->faces[m_meshPtr->adjacentfaces[vertX][0]]; for (unsigned int fNumber = 0; fNumber < m_meshPtr->adjacentfaces[vertX].size(); fNumber++) { // check if face contains x and store barycentric coordinates for x in face f triangleX = m_meshPtr->faces[m_meshPtr->adjacentfaces[vertX][fNumber]]; vec3 barycentric = this->ComputeBarycentricCoordinates(x, triangleX); alphaX = barycentric[0]; betaX = barycentric[1]; gammaX = barycentric[2]; if (((barycentric[0] >= 0) && (barycentric[0] <= 1)) && ((barycentric[1] >= 0) && (barycentric[1] <= 1)) && ((barycentric[2] >= 0) && (barycentric[2] <= 1))) { fNumber = m_meshPtr->adjacentfaces[vertX].size(); } } } } else { #if SHOW_WARNING std::cout << "warning: using kdtree for triangle info because there is no face index map !!! ...\n"; #endif // get vertex closest to first point - x vertX = this->FindNearestVertex(x); // scan all adjacent faces to see which face (f) includes point x triangleX = m_meshPtr->faces[m_meshPtr->adjacentfaces[vertX][0]]; for (unsigned int fNumber = 0; fNumber < m_meshPtr->adjacentfaces[vertX].size(); fNumber++) { // check if face contains x and store barycentric coordinates for x in face f triangleX = m_meshPtr->faces[m_meshPtr->adjacentfaces[vertX][fNumber]]; vec3 barycentric = this->ComputeBarycentricCoordinates(x, triangleX); alphaX = barycentric[0]; betaX = barycentric[1]; gammaX = barycentric[2]; if (((barycentric[0] >= 0) && (barycentric[0] <= 1)) && ((barycentric[1] >= 0) && (barycentric[1] <= 1)) && ((barycentric[2] >= 0) && (barycentric[2] <= 1))) { fNumber = m_meshPtr->adjacentfaces[vertX].size(); } } } return vertX; } // SHIREEN - computing geo distance on the fly for fuzzy geodesics std::vector<float> meshFIM::ComputeDistanceToCurve(TriMesh *mesh, std::vector< point > curvePoints) { int numVert = mesh->vertices.size(); this->geodesicMap.resize(numVert); SetMesh(mesh); std::list<index>::iterator iter = m_ActivePoints.begin(); float oldT1 , newT1, oldT2, newT2; index tmpIndex1, tmpIndex2; std::vector<int> nb; NumComputation = 0; double total_duration = 0; char c; int i=0; std::vector<int> seedPointList; for (int pIndex = 0; pIndex < curvePoints.size(); pIndex++) { // SHIREEN seedPointList.push_back(this->GetVertexInfoForPoint(curvePoints[pIndex]) ); //seedPointList.push_back( mesh->FindNearestVertex(curvePoints[pIndex]) ); // end SHIREEN } SetSeedPoint(seedPointList); this->InitializeAttributes(0, m_SeedPoints); InitializeLabels(); InitializeActivePoints(); SetStopDistance(LARGENUM); while (!m_ActivePoints.empty()) { //printf("Size of Activelist is: %d \n", m_ActivePoints.size()); iter = m_ActivePoints.begin(); while(iter != m_ActivePoints.end()) { tmpIndex1 = *iter; nb = m_meshPtr->neighbors[tmpIndex1]; oldT1 = this->geodesic[tmpIndex1]; newT1 = Upwind(0,tmpIndex1); if (abs(oldT1-newT1)<_EPS) //if converges { if (oldT1>newT1) { this->geodesic[tmpIndex1] = newT1; } if(this->geodesic[tmpIndex1] < m_StopDistance) { for (i=0;i<nb.size();i++) { tmpIndex2 = nb[i]; if (m_Label[tmpIndex2]==AlivePoint || m_Label[tmpIndex2]==FarPoint) { oldT2 = this->geodesic[tmpIndex2]; newT2 = Upwind(0,tmpIndex2); if (oldT2>newT2) { this->geodesic[tmpIndex2] = newT2; if (m_Label[tmpIndex2]!=ActivePoint) { m_ActivePoints.insert(iter, tmpIndex2); m_Label[tmpIndex2] = ActivePoint; } } } } } iter = m_ActivePoints.erase(iter); m_Label[tmpIndex1] = AlivePoint; } else // if not converge { if(newT1 < oldT1) { this->geodesic[tmpIndex1] = newT1; } iter++; } } } std::vector<float> geodesics;geodesics.clear(); // loop over each vertex for (int i = 0; i < numVert; i++) { geodesics.push_back(this->geodesic[i] + 0.0001f); } // Now Erase the duplicate data this->CleanupAttributes(); return geodesics; } void meshFIM::WriteFeaFile(TriMesh *mesh, char* outfilename) { int numVert = mesh->vertices.size(); // write out distance to curve std::ofstream outfile(outfilename, std::ios::binary); // write numVertices to facilitate reading later outfile.write( reinterpret_cast<char *>(&numVert), sizeof(unsigned int) ); // loop over each vertex for (int i = 0; i < numVert; i++) { // write distance to curve float distToCurve; distToCurve = this->geodesic[i] + 0.0001f; outfile.write( reinterpret_cast<char *>(&distToCurve), sizeof(float) ); } outfile.close(); } void meshFIM::WriteFeaFile(std::vector<float> fea, char* outfilename) { int numVert = fea.size(); // write out distance to curve std::ofstream outfile(outfilename, std::ios::binary); // write numVertices to facilitate reading later outfile.write( reinterpret_cast<char *>(&numVert), sizeof(unsigned int) ); // loop over each vertex for (int i = 0; i < numVert; i++) { // write distance to curve float distToCurve; distToCurve = fea[i]; outfile.write( reinterpret_cast<char *>(&distToCurve), sizeof(float) ); } outfile.close(); } // end SHIREEN /* Praful */ void meshFIM::GetFeatureValues(point x, std::vector<float> &vals) { float alphaX, betaX, gammaX; TriMesh::Face triangleX; GetTriangleInfoForPoint(x, triangleX, alphaX, betaX, gammaX); if (alphaX < 0.000001f) alphaX = 0.000001f; if (betaX < 0.000001f) betaX = 0.000001f; if (gammaX < 0.000001f) gammaX = 0.000001f; alphaX /= (alphaX + betaX + gammaX); betaX /= (alphaX + betaX + gammaX); gammaX /= (alphaX + betaX + gammaX); vals.resize(this->features.size()); for (unsigned int i = 0; i < this->features.size(); i++) { float f0 = this->features[i][triangleX[0]]; float f1 = this->features[i][triangleX[1]]; float f2 = this->features[i][triangleX[2]]; vals[i] = (alphaX * f0) + (betaX * f1) + (gammaX * f2); } } /* Prateep */ void meshFIM::ReadFaceIndexMap(const char *infilename) { std::ifstream infile(infilename); if (!infile.is_open()) { std::cout << "File Not Found:" << infilename << std::endl; } else { std::cout << "reading face indices from " << infilename << std::endl; // map<VoxelIndexType, set<int> > tmpFaceIndexMap; std::string line; while (infile) { getline(infile, line); std::stringstream ss(line); VoxelIndexType index; char delim; ss >> index >> delim; int fid; while (ss >> fid) { this->faceIndexMap[index].push_back(fid); // tmpFaceIndexMap[index].insert(fid); } } // if(tmpFaceIndexMap.size() != 0 ) // { // this->faceIndexMap = tmpFaceIndexMap; // } // tmpFaceIndexMap.clear(); // clear memory infile.close(); } } void meshFIM::ReadFeatureFromFile(const char *infilename) { std::ifstream infile(infilename, std::ios::binary); if (!infile.is_open()) { std::cerr << "File Not Found: " << infilename << std::endl; throw(1); } else { // read # vertices unsigned int numVert; infile.read(reinterpret_cast<char *>(&numVert), sizeof(unsigned int)); if (numVert != m_meshPtr->vertices.size()) { std::cerr << "size of feature vector does not match # vertices in mesh" << std::endl; throw(1); } else { // std::cout << "reading feature from file " << infilename << std::endl; std::vector< float > tmpFeatureVec; // loop over vertices for (int i = 0; i < numVert; i++) { // read feature value float value; infile.read(reinterpret_cast<char *>(&value), sizeof(float)); tmpFeatureVec.push_back(value); } this->features.push_back(tmpFeatureVec); } infile.close(); } } /* Praful */ void meshFIM::ReadFeatureGradientFromFile(const char *infilename) { std::ifstream infile(infilename); if (!infile.is_open()) { std::cerr << "File Not Found" << std::endl; throw(1);//exit(1); } else { // read # vertices unsigned int numVert; infile.read(reinterpret_cast<char *>(&numVert), sizeof(unsigned int)); if (numVert != m_meshPtr->vertices.size()) { std::cerr << "size of feature vector does not match # vertices in mesh" << std::endl; throw(1); //exit(1); } else { // std::cout << "reading feature gradient from file " << infilename << std::endl; std::vector<point> tempFeatureGradVec; // loop over vertices for (int i = 0; i < numVert; i++) { // read feature gradient point val; float value; for (int j = 0; j < 3; j++) { infile.read(reinterpret_cast<char *>(&value), sizeof(float)); val[j] = ( float) value; } tempFeatureGradVec.push_back(val); } this->featureGradients.push_back(tempFeatureGradVec); } infile.close(); } } /* Praful */ point meshFIM::ComputeFeatureDerivative(int v, int nFeature = 0) { if (featureGradients.size() > 0) return featureGradients[nFeature][v]; else { point df; df.clear(); df[0] = 0.0f; df[1] = 0.0f; df[2] = 0.0f; // feature value at v float valueV = this->features[nFeature][v]; point ptV = m_meshPtr->vertices[v]; // iterate over neighbors of v to compute derivative as central difference for (unsigned int n = 0; n < m_meshPtr->neighbors[v].size(); n++) { int indexN = m_meshPtr->neighbors[v][n]; float valueN = this->features[nFeature][indexN]; point ptN = m_meshPtr->vertices[indexN]; float valueDiff = valueN - valueV; point ptDiff = ptN - ptV; df[0] = df[0] + valueDiff / (ptDiff[0] + 0.0001f); df[1] = df[1] + valueDiff / (ptDiff[1] + 0.0001f); df[2] = df[2] + valueDiff / (ptDiff[2] + 0.0001f); } df[0] = df[0] / ( float) (m_meshPtr->neighbors[v].size()); df[1] = df[1] / ( float) (m_meshPtr->neighbors[v].size()); df[2] = df[2] / ( float) (m_meshPtr->neighbors[v].size()); return df; } } /* Prateep -- updated Praful */ point meshFIM::GetFeatureDerivative(point p, int fIndex = 0) { point dP; dP.clear(); dP[0] = 0.0f; dP[1] = 0.0f; dP[2] = 0.0f; float alphaP, betaP, gammaP; TriMesh::Face triangleP; GetTriangleInfoForPoint(p, triangleP, alphaP, betaP, gammaP); if (alphaP < 0.000001f) alphaP = 0.000001f; if (betaP < 0.000001f) betaP = 0.000001f; if (gammaP < 0.000001f) gammaP = 0.000001f; alphaP /= (alphaP + betaP + gammaP); betaP /= (alphaP + betaP + gammaP); gammaP /= (alphaP + betaP + gammaP); // compute derivative at 3 vertices (A,B,C) int A = triangleP[0]; int B = triangleP[1]; int C = triangleP[2]; // // Get derivatives of Barycentric coordinates // vec fNorm = GetFaceNormal(triangleP); // float mag = fNorm DOT fNorm; // mag = std::sqrt(mag); // fNorm[0] /= mag; // fNorm[1] /= mag; // fNorm[2] /= mag; // float fArea = GetFaceArea(triangleP); // vec v0 = this->vertices[triangleP.v[0]]; // vec v1 = this->vertices[triangleP.v[1]]; // vec v2 = this->vertices[triangleP.v[2]]; // vec dAlpha = GetGradientBaryCentricCoord(fNorm, v2-v1, fArea); // vec dBeta = GetGradientBaryCentricCoord(fNorm, v0-v2, fArea); // vec dGamma = GetGradientBaryCentricCoord(fNorm, v1-v0, fArea); point dA = ComputeFeatureDerivative(A, fIndex); point dB = ComputeFeatureDerivative(B, fIndex); point dC = ComputeFeatureDerivative(C, fIndex); // float f0 = this->features[fIndex][A]; // float f1 = this->features[fIndex][B]; // float f2 = this->features[fIndex][C]; // interpolate dP[0] = (alphaP * dA[0]) + (betaP * dB[0]) + (gammaP * dC[0]);// + ( dAlpha[0] * f0 ) + ( dBeta[0] * f1 ) + ( dGamma[0] * f2 ); dP[1] = (alphaP * dA[1]) + (betaP * dB[1]) + (gammaP * dC[1]);// + ( dAlpha[1] * f0 ) + ( dBeta[1] * f1 ) + ( dGamma[1] * f2 ); dP[2] = (alphaP * dA[2]) + (betaP * dB[2]) + (gammaP * dC[2]);// + ( dAlpha[2] * f0 ) + ( dBeta[2] * f1 ) + ( dGamma[2] * f2 ); return dP; }
31.802141
161
0.54034
ajensen1234
99aadc94c20aa96fec0056556828f140150c470b
294
hpp
C++
jet-sdk-csgo/src/i_client_leaf_system.hpp
bruhmoment21/csgo-imgui-sdk
f299375d4786b029b800800cde9a3404aa66e0e5
[ "MIT" ]
57
2020-07-04T16:32:12.000Z
2022-03-03T20:18:33.000Z
jet-sdk-csgo/src/i_client_leaf_system.hpp
bruhmoment21/csgo-imgui-sdk
f299375d4786b029b800800cde9a3404aa66e0e5
[ "MIT" ]
9
2021-03-15T08:48:17.000Z
2021-12-18T15:34:12.000Z
jet-sdk-csgo/src/i_client_leaf_system.hpp
bruhmoment21/csgo-imgui-sdk
f299375d4786b029b800800cde9a3404aa66e0e5
[ "MIT" ]
21
2020-07-21T15:33:05.000Z
2022-03-04T23:19:11.000Z
#pragma once #include "utilities.hpp" class i_client_leaf_system { public: void create_renderable_handle(void* obj) { return utilities::call_virtual< void, 0, std::uintptr_t, bool, int, int, std::uint32_t >(this, reinterpret_cast<std::uintptr_t>(obj) + 4, false, 0, -1, 0xFFFFFFFF); } };
24.5
166
0.72449
bruhmoment21
99ab0539d47cd5450c5ce19ab5dc1409fc7e40fb
1,597
cpp
C++
source/init_coreload_postparse.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
source/init_coreload_postparse.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
source/init_coreload_postparse.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
/* This file is part of Cloudy and is copyright (C)1978-2019 by Gary J. Ferland and * others. For conditions of distribution and use see copyright notice in license.txt */ /*InitCoreloadPostparse initialization at start, called from cloudy * after parser one time per core load */ #include "cddefines.h" #include "init.h" #include "dense.h" #include "iso.h" #include "species.h" /*InitCoreloadPostparse initialization at start, called from cloudy * after parser, one time per core load */ void InitCoreloadPostparse( void ) { static int nCalled = 0; DEBUG_ENTRY( "InitCoreloadPostparse()" ); /* only do this once per coreload */ if( nCalled > 0 ) { return; } /* this is first call, increment the nCalled counter so we never do this again */ ++nCalled; for( long ipISO=ipH_LIKE; ipISO<NISO; ++ipISO ) { for( long nelem=ipISO; nelem<LIMELM; ++nelem) { /* only grab core for elements that are turned on */ if( nelem < 2 || dense.lgElmtOn[nelem] ) { iso_update_num_levels( ipISO, nelem ); ASSERT( iso_sp[ipISO][nelem].numLevels_max > 0 ); iso_ctrl.nLyman_alloc[ipISO] = iso_ctrl.nLyman[ipISO]; iso_ctrl.nLyman_max[ipISO] = iso_ctrl.nLyman[ipISO]; // resolved and collapsed levels long numLevels = iso_sp[ipISO][nelem].numLevels_max; // "extra" Lyman lines numLevels += iso_ctrl.nLyman_alloc[ipISO] - 2; // satellite lines (one for doubly-excited continuum) if( iso_ctrl.lgDielRecom[ipISO] ) numLevels += 1; iso_sp[ipISO][nelem].st.init( makeChemical( nelem, nelem-ipISO ).c_str(), numLevels ); } } } return; }
29.574074
90
0.694427
cloudy-astrophysics
99ac4e1e4f75516d96208cc00d44d6941c66dd08
8,167
cpp
C++
pse/TGUI-0.7.7/tests/Widgets/Label.cpp
ValtoLibraries/PUtils
f30ebf21416654743ad2a05b14974acd27257da8
[ "MIT" ]
null
null
null
pse/TGUI-0.7.7/tests/Widgets/Label.cpp
ValtoLibraries/PUtils
f30ebf21416654743ad2a05b14974acd27257da8
[ "MIT" ]
null
null
null
pse/TGUI-0.7.7/tests/Widgets/Label.cpp
ValtoLibraries/PUtils
f30ebf21416654743ad2a05b14974acd27257da8
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // TGUI - Texus's Graphical User Interface // Copyright (C) 2012-2017 Bruno Van de Velde (vdv_b@tgui.eu) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "../Tests.hpp" #include <TGUI/Widgets/Label.hpp> TEST_CASE("[Label]") { tgui::Label::Ptr label = std::make_shared<tgui::Label>(); label->setFont("resources/DroidSansArmenian.ttf"); SECTION("Signals") { REQUIRE_NOTHROW(label->connect("DoubleClicked", [](){})); REQUIRE_NOTHROW(label->connect("DoubleClicked", [](sf::String){})); } SECTION("WidgetType") { REQUIRE(label->getWidgetType() == "Label"); } SECTION("Text") { REQUIRE(label->getText() == ""); label->setText("SomeText"); REQUIRE(label->getText() == "SomeText"); } SECTION("TextStyle") { REQUIRE(label->getTextStyle() == sf::Text::Regular); label->setTextStyle(sf::Text::Bold | sf::Text::Italic); REQUIRE(label->getTextStyle() == (sf::Text::Bold | sf::Text::Italic)); } SECTION("TextSize") { label->setTextSize(25); REQUIRE(label->getTextSize() == 25); } SECTION("Alignment") { REQUIRE(label->getHorizontalAlignment() == tgui::Label::HorizontalAlignment::Left); REQUIRE(label->getVerticalAlignment() == tgui::Label::VerticalAlignment::Top); label->setHorizontalAlignment(tgui::Label::HorizontalAlignment::Center); REQUIRE(label->getHorizontalAlignment() == tgui::Label::HorizontalAlignment::Center); REQUIRE(label->getVerticalAlignment() == tgui::Label::VerticalAlignment::Top); label->setHorizontalAlignment(tgui::Label::HorizontalAlignment::Right); REQUIRE(label->getHorizontalAlignment() == tgui::Label::HorizontalAlignment::Right); label->setHorizontalAlignment(tgui::Label::HorizontalAlignment::Left); REQUIRE(label->getHorizontalAlignment() == tgui::Label::HorizontalAlignment::Left); label->setVerticalAlignment(tgui::Label::VerticalAlignment::Center); REQUIRE(label->getHorizontalAlignment() == tgui::Label::HorizontalAlignment::Left); REQUIRE(label->getVerticalAlignment() == tgui::Label::VerticalAlignment::Center); label->setVerticalAlignment(tgui::Label::VerticalAlignment::Bottom); REQUIRE(label->getVerticalAlignment() == tgui::Label::VerticalAlignment::Bottom); label->setVerticalAlignment(tgui::Label::VerticalAlignment::Top); REQUIRE(label->getVerticalAlignment() == tgui::Label::VerticalAlignment::Top); } SECTION("AutoSize") { REQUIRE(label->getAutoSize()); label->setAutoSize(false); REQUIRE(!label->getAutoSize()); label->setAutoSize(true); REQUIRE(label->getAutoSize()); label->setSize(200, 100); REQUIRE(!label->getAutoSize()); } SECTION("MaximumTextWidth") { REQUIRE(label->getMaximumTextWidth() == 0); label->setMaximumTextWidth(300); REQUIRE(label->getMaximumTextWidth() == 300); } SECTION("Renderer") { auto renderer = label->getRenderer(); SECTION("set serialized property") { REQUIRE_NOTHROW(renderer->setProperty("TextColor", "rgb(100, 50, 150)")); REQUIRE_NOTHROW(renderer->setProperty("BackgroundColor", "rgb(150, 100, 50)")); REQUIRE_NOTHROW(renderer->setProperty("BorderColor", "rgb(50, 150, 100)")); REQUIRE_NOTHROW(renderer->setProperty("Borders", "(1, 2, 3, 4)")); REQUIRE_NOTHROW(renderer->setProperty("Padding", "(5, 6, 7, 8)")); } SECTION("set object property") { REQUIRE_NOTHROW(renderer->setProperty("TextColor", sf::Color{100, 50, 150})); REQUIRE_NOTHROW(renderer->setProperty("BackgroundColor", sf::Color{150, 100, 50})); REQUIRE_NOTHROW(renderer->setProperty("BorderColor", sf::Color{50, 150, 100})); REQUIRE_NOTHROW(renderer->setProperty("Borders", tgui::Borders{1, 2, 3, 4})); REQUIRE_NOTHROW(renderer->setProperty("Padding", tgui::Borders{5, 6, 7, 8})); } SECTION("functions") { renderer->setTextColor({100, 50, 150}); renderer->setBackgroundColor({150, 100, 50}); renderer->setBorderColor({50, 150, 100}); renderer->setBorders({1, 2, 3, 4}); renderer->setPadding({5, 6, 7, 8}); SECTION("getPropertyValuePairs") { auto pairs = renderer->getPropertyValuePairs(); REQUIRE(pairs.size() == 5); REQUIRE(pairs["TextColor"].getColor() == sf::Color(100, 50, 150)); REQUIRE(pairs["BackgroundColor"].getColor() == sf::Color(150, 100, 50)); REQUIRE(pairs["BorderColor"].getColor() == sf::Color(50, 150, 100)); REQUIRE(pairs["Borders"].getBorders() == tgui::Borders(1, 2, 3, 4)); REQUIRE(pairs["Padding"].getBorders() == tgui::Borders(5, 6, 7, 8)); } } REQUIRE(renderer->getProperty("TextColor").getColor() == sf::Color(100, 50, 150)); REQUIRE(renderer->getProperty("BackgroundColor").getColor() == sf::Color(150, 100, 50)); REQUIRE(renderer->getProperty("BorderColor").getColor() == sf::Color(50, 150, 100)); REQUIRE(renderer->getProperty("Borders").getBorders() == tgui::Borders(1, 2, 3, 4)); REQUIRE(renderer->getProperty("Padding").getBorders() == tgui::Borders(5, 6, 7, 8)); } SECTION("Saving and loading from file") { REQUIRE_NOTHROW(label = std::make_shared<tgui::Theme>()->load("Label")); auto theme = std::make_shared<tgui::Theme>("resources/Black.txt"); REQUIRE_NOTHROW(label = theme->load("Label")); REQUIRE(label->getPrimaryLoadingParameter() == "resources/Black.txt"); REQUIRE(label->getSecondaryLoadingParameter() == "label"); auto parent = std::make_shared<tgui::GuiContainer>(); parent->add(label); label->setOpacity(0.8f); label->setText("SomeText"); label->setTextSize(25); label->setTextStyle(sf::Text::Bold | sf::Text::Italic); label->setHorizontalAlignment(tgui::Label::HorizontalAlignment::Center); label->setVerticalAlignment(tgui::Label::VerticalAlignment::Bottom); label->setMaximumTextWidth(300); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileLabel1.txt")); parent->removeAllWidgets(); REQUIRE_NOTHROW(parent->loadWidgetsFromFile("WidgetFileLabel1.txt")); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileLabel2.txt")); REQUIRE(compareFiles("WidgetFileLabel1.txt", "WidgetFileLabel2.txt")); SECTION("Copying widget") { tgui::Label temp; temp = *label; parent->removeAllWidgets(); parent->add(tgui::Label::copy(std::make_shared<tgui::Label>(temp))); REQUIRE_NOTHROW(parent->saveWidgetsToFile("WidgetFileLabel2.txt")); REQUIRE(compareFiles("WidgetFileLabel1.txt", "WidgetFileLabel2.txt")); } } }
44.873626
129
0.615281
ValtoLibraries
99ad54256be68e91bdc74060961a9ae87330de64
3,302
cpp
C++
benchmarks/linear_algebra/cg/dump_matlab_matrix.cpp
akmaru/tiramisu
8ca4173547b6d12cff10575ef0dc48cf93f7f414
[ "MIT" ]
23
2017-05-03T13:06:34.000Z
2018-06-07T07:12:43.000Z
benchmarks/linear_algebra/cg/dump_matlab_matrix.cpp
akmaru/tiramisu
8ca4173547b6d12cff10575ef0dc48cf93f7f414
[ "MIT" ]
2
2017-04-25T08:59:09.000Z
2017-05-11T16:41:55.000Z
benchmarks/linear_algebra/cg/dump_matlab_matrix.cpp
akmaru/tiramisu
8ca4173547b6d12cff10575ef0dc48cf93f7f414
[ "MIT" ]
13
2017-07-03T15:24:53.000Z
2022-03-05T14:57:10.000Z
//@HEADER // ************************************************************************ // // HPCCG: Simple Conjugate Gradient Benchmark Code // Copyright (2006) Sandia Corporation // // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive // license for use of this work by or on behalf of the U.S. Government. // // BSD 3-Clause License // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Michael A. Heroux (maherou@sandia.gov) // // ************************************************************************ //@HEADER ///////////////////////////////////////////////////////////////////////// // Routine to dump matrix in row, col, val format for analysis with Matlab // Writes to mat.dat // NOTE: THIS CODE ONLY WORKS ON SINGLE PROCESSOR RUNS // Read into matlab using: // load mat.dat // A=spconvert(mat); // A - known matrix ///////////////////////////////////////////////////////////////////////// #include <cstdio> #include "dump_matlab_matrix.hpp" int dump_matlab_matrix( HPC_Sparse_Matrix *A, int rank) { const int nrow = A->local_nrow; int start_row = nrow*rank; // Each processor gets a section of a chimney stack domain FILE * handle = 0; if (rank==0) handle = fopen("mat0.dat", "w"); else if (rank==1) handle = fopen("mat1.dat", "w"); else if (rank==2) handle = fopen("mat2.dat", "w"); else if (rank==3) handle = fopen("mat3.dat", "w"); else return(0); for (int i=0; i< nrow; i++) { const double * const cur_vals = A->ptr_to_vals_in_row[i]; const int * const cur_inds = A->ptr_to_inds_in_row[i]; const int cur_nnz = A->nnz_in_row[i]; for (int j=0; j< cur_nnz; j++) fprintf(handle, " %d %d %22.16e\n",start_row+i+1,cur_inds[j]+1,cur_vals[j]); } fclose(handle); return(0); }
39.783133
113
0.640218
akmaru
99afaae66e1b76aaee0613a2ad2acbc24b794242
5,005
hxx
C++
opencascade/IFSelect_SelectSignature.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
opencascade/IFSelect_SelectSignature.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
opencascade/IFSelect_SelectSignature.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
// Created on: 1994-04-21 // Created by: Christian CAILLET // Copyright (c) 1994-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IFSelect_SelectSignature_HeaderFile #define _IFSelect_SelectSignature_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TCollection_AsciiString.hxx> #include <Standard_Integer.hxx> #include <TColStd_SequenceOfAsciiString.hxx> #include <TColStd_SequenceOfInteger.hxx> #include <IFSelect_SelectExtract.hxx> #include <Standard_CString.hxx> #include <Standard_Boolean.hxx> class IFSelect_Signature; class IFSelect_SignCounter; class Standard_Transient; class Interface_Graph; class Interface_InterfaceModel; class IFSelect_SelectSignature; DEFINE_STANDARD_HANDLE(IFSelect_SelectSignature, IFSelect_SelectExtract) //! A SelectSignature sorts the Entities on a Signature Matching. //! The signature to match is given at creation time. Also, the //! required match is given at creation time : exact (IsEqual) or //! contains (the Type's Name must contain the criterium Text) //! //! Remark that no more interpretation is done, it is an //! alpha-numeric signature : for instance, DynamicType is matched //! as such, super-types are not considered //! //! Also, numeric (integer) comparisons are supported : an item //! can be <val ou <=val or >val or >=val , val being an Integer //! //! A SelectSignature may also be created from a SignCounter, //! which then just gives its LastValue as SignatureValue class IFSelect_SelectSignature : public IFSelect_SelectExtract { public: //! Creates a SelectSignature with its Signature and its Text to //! Match. //! <exact> if True requires exact match, //! if False requires <signtext> to be contained in the Signature //! of the entity (default is "exact") Standard_EXPORT IFSelect_SelectSignature(const Handle(IFSelect_Signature)& matcher, const Standard_CString signtext, const Standard_Boolean exact = Standard_True); //! As above with an AsciiString Standard_EXPORT IFSelect_SelectSignature(const Handle(IFSelect_Signature)& matcher, const TCollection_AsciiString& signtext, const Standard_Boolean exact = Standard_True); //! Creates a SelectSignature with a Counter, more precisely a //! SelectSignature. Which is used here to just give a Signature //! Value (by SignOnly Mode) //! Matching is the default provided by the class Signature Standard_EXPORT IFSelect_SelectSignature(const Handle(IFSelect_SignCounter)& matcher, const Standard_CString signtext, const Standard_Boolean exact = Standard_True); //! Returns the used Signature, then it is possible to access it, //! modify it as required. Can be null, hence see Counter Standard_EXPORT Handle(IFSelect_Signature) Signature() const; //! Returns the used SignCounter. Can be used as alternative for //! Signature Standard_EXPORT Handle(IFSelect_SignCounter) Counter() const; //! Returns True for an Entity (model->Value(num)) of which the //! signature matches the text given as creation time //! May also work with a Counter from the Graph Standard_EXPORT virtual Standard_Boolean SortInGraph (const Standard_Integer rank, const Handle(Standard_Transient)& ent, const Interface_Graph& G) const Standard_OVERRIDE; //! Not called, defined only to remove a deferred method here Standard_EXPORT Standard_Boolean Sort (const Standard_Integer rank, const Handle(Standard_Transient)& ent, const Handle(Interface_InterfaceModel)& model) const Standard_OVERRIDE; //! Returns Text used to Sort Entity on its Signature or SignCounter Standard_EXPORT const TCollection_AsciiString& SignatureText() const; //! Returns True if match must be exact Standard_EXPORT Standard_Boolean IsExact() const; //! Returns a text defining the criterium. //! (it refers to the text and exact flag to be matched, and is //! qualified by the Name provided by the Signature) Standard_EXPORT TCollection_AsciiString ExtractLabel() const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(IFSelect_SelectSignature,IFSelect_SelectExtract) protected: private: Handle(IFSelect_Signature) thematcher; Handle(IFSelect_SignCounter) thecounter; TCollection_AsciiString thesigntext; Standard_Integer theexact; TColStd_SequenceOfAsciiString thesignlist; TColStd_SequenceOfInteger thesignmode; }; #endif // _IFSelect_SelectSignature_HeaderFile
37.631579
180
0.783017
mgreminger
99b0a02606783ea16114881450000304af19e5e8
30,975
hpp
C++
public/anton/array.hpp
kociap/atl
a7dc9b35c14453040db82dbbeca3c305bb25c66e
[ "MIT" ]
null
null
null
public/anton/array.hpp
kociap/atl
a7dc9b35c14453040db82dbbeca3c305bb25c66e
[ "MIT" ]
null
null
null
public/anton/array.hpp
kociap/atl
a7dc9b35c14453040db82dbbeca3c305bb25c66e
[ "MIT" ]
null
null
null
#pragma once #include <anton/allocator.hpp> #include <anton/assert.hpp> #include <anton/iterators.hpp> #include <anton/math/math.hpp> #include <anton/memory.hpp> #include <anton/swap.hpp> #include <anton/tags.hpp> #include <anton/type_traits.hpp> #include <anton/utility.hpp> namespace anton { #define ANTON_ARRAY_MIN_ALLOCATION_SIZE ((i64)64) template<typename T, typename Allocator = Allocator> struct Array { public: using value_type = T; using allocator_type = Allocator; using size_type = i64; using difference_type = i64; using iterator = T*; using const_iterator = T const*; Array(); explicit Array(allocator_type const& allocator); // Construct an array with n default constructed elements explicit Array(size_type n); // Construct an array with n default constructed elements explicit Array(size_type n, allocator_type const& allocator); // Construct an array with n copies of value explicit Array(size_type n, value_type const& value); // Construct an array with n copies of value explicit Array(size_type n, value_type const& value, allocator_type const& allocator); // Construct an array with capacity to fit at least n elements explicit Array(Reserve_Tag, size_type n); // Construct an array with capacity to fit at least n elements explicit Array(Reserve_Tag, size_type n, allocator_type const& allocator); // Copies the allocator Array(Array const& other); Array(Array const& other, allocator_type const& allocator); // Moves the allocator Array(Array&& other); Array(Array&& other, allocator_type const& allocator); template<typename Input_Iterator> Array(Range_Construct_Tag, Input_Iterator first, Input_Iterator last); template<typename... Args> Array(Variadic_Construct_Tag, Args&&...); ~Array(); Array& operator=(Array const& other); Array& operator=(Array&& other); [[nodiscard]] T& operator[](size_type); [[nodiscard]] T const& operator[](size_type) const; // back // Accesses the last element of the array. The behaviour is undefined when the array is empty. // [[nodiscard]] T& back(); [[nodiscard]] T const& back() const; [[nodiscard]] T* data(); [[nodiscard]] T const* data() const; [[nodiscard]] iterator begin(); [[nodiscard]] iterator end(); [[nodiscard]] const_iterator begin() const; [[nodiscard]] const_iterator end() const; [[nodiscard]] const_iterator cbegin() const; [[nodiscard]] const_iterator cend() const; // size // The number of elements contained in the array. // [[nodiscard]] size_type size() const; // size_bytes // The size of all the elements contained in the array in bytes. // Equivalent to 'sizeof(T) * size()'. // [[nodiscard]] size_type size_bytes() const; [[nodiscard]] size_type capacity() const; [[nodiscard]] allocator_type& get_allocator(); [[nodiscard]] allocator_type const& get_allocator() const; // resize // Resizes the array allocating additional memory if n is greater than capacity. // If n is greater than size, the new elements are default constructed. // If n is less than size, the excess elements are destroyed. // void resize(size_type n); // resize // Resizes the array allocating additional memory if n is greater than capacity. // If n is greater than size, the new elements are copy constructed from v. // If n is less than size, the excess elements are destroyed. // void resize(size_type n, value_type const& v); // ensure_capacity // Allocates enough memory to fit requested_capacity elements of type T. // Does nothing if requested_capacity is less than capacity(). // void ensure_capacity(size_type requested_capacity); // set_capacity // Sets the capacity to exactly match n. // If n is not equal capacity, contents are reallocated. // void set_capacity(size_type n); // force_size // Changes the size of the array to n. Useful in situations when the user // writes to the array via external means. // void force_size(size_type n); template<typename Input_Iterator> void assign(Input_Iterator first, Input_Iterator last); // insert // Constructs an object directly into array at position avoiding copies or moves. // position must be a valid iterator. // // Returns: iterator to the inserted element. // template<typename... Args> iterator insert(Variadic_Construct_Tag, const_iterator position, Args&&... args); // insert // Constructs an object directly into array at position avoiding copies or moves. // position must be an index greater than or equal 0 and less than or equal size. // // Returns: iterator to the inserted element. // template<typename... Args> iterator insert(Variadic_Construct_Tag, size_type position, Args&&... args); // insert // Insert a range of elements into array at position. // position must be a valid iterator. // // Returns: iterator to the first of the inserted elements. // template<typename Input_Iterator> iterator insert(const_iterator position, Input_Iterator first, Input_Iterator last); // insert // Insert a range of elements into array at position. // position must be an index greater than or equal 0 and less than or equal size. // // Returns: iterator to the first of the inserted elements. // template<typename Input_Iterator> iterator insert(size_type position, Input_Iterator first, Input_Iterator last); // insert_unsorted // Inserts an element into array by moving the object at position to the end of the array // and then copying value into position. // position must be a valid iterator. // // Returns: // Iterator to the inserted element. // iterator insert_unsorted(const_iterator position, value_type const& value); iterator insert_unsorted(const_iterator position, value_type&& value); // insert_unsorted // Inserts an element into array by moving the object at position to the end of the array // and then copying value into position. // position must be an index greater than or equal 0 and less than or equal size. // // Returns: // Iterator to the inserted element. // iterator insert_unsorted(size_type position, value_type const& value); iterator insert_unsorted(size_type position, value_type&& value); T& push_back(value_type const&); T& push_back(value_type&&); template<typename... Args> T& emplace_back(Args&&... args); iterator erase(const_iterator first, const_iterator last); void erase_unsorted(size_type index); void erase_unsorted_unchecked(size_type index); iterator erase_unsorted(const_iterator first); // iterator erase_unsorted(const_iterator first, const_iterator last); void pop_back(); void clear(); // swap // Exchanges the contents of the two arrays without copying, // moving or swapping the individual elements. // Exchanges the allocators. // // Parameters: // lhs, rhs - the containers to exchange the contents of. // // Complexity: // Constant. // friend void swap(Array& lhs, Array& rhs) { // We do not follow the C++ Standard in its complex ways to swap containers // and always swap both the allocator and the memory since it is a common expectation // of the users, is much faster than copying all the elements and does not break // the container or put it in an invalid state. using anton::swap; swap(lhs._allocator, rhs._allocator); swap(lhs._capacity, rhs._capacity); swap(lhs._size, rhs._size); swap(lhs._data, rhs._data); } private: Allocator _allocator; size_type _capacity = 0; size_type _size = 0; T* _data = nullptr; T* allocate(size_type); void deallocate(void*, size_type); }; } // namespace anton namespace anton { template<typename T, typename Allocator> Array<T, Allocator>::Array(): _allocator() {} template<typename T, typename Allocator> Array<T, Allocator>::Array(allocator_type const& allocator): _allocator(allocator) {} template<typename T, typename Allocator> Array<T, Allocator>::Array(size_type const n): Array(n, allocator_type()) {} template<typename T, typename Allocator> Array<T, Allocator>::Array(size_type const n, allocator_type const& allocator): _allocator(allocator) { _capacity = math::max(ANTON_ARRAY_MIN_ALLOCATION_SIZE, n); _data = allocate(_capacity); anton::uninitialized_default_construct_n(_data, n); _size = n; } template<typename T, typename Allocator> Array<T, Allocator>::Array(size_type n, value_type const& value): Array(n, value, allocator_type()) {} template<typename T, typename Allocator> Array<T, Allocator>::Array(size_type n, value_type const& value, allocator_type const& allocator) { _capacity = math::max(ANTON_ARRAY_MIN_ALLOCATION_SIZE, n); _data = allocate(_capacity); anton::uninitialized_fill_n(_data, n, value); _size = n; } template<typename T, typename Allocator> Array<T, Allocator>::Array(Reserve_Tag, size_type const n): Array(reserve, n, allocator_type()) {} template<typename T, typename Allocator> Array<T, Allocator>::Array(Reserve_Tag, size_type const n, allocator_type const& allocator): _allocator(allocator) { _capacity = math::max(ANTON_ARRAY_MIN_ALLOCATION_SIZE, n); _data = allocate(_capacity); } template<typename T, typename Allocator> Array<T, Allocator>::Array(Array const& other): _allocator(other._allocator), _capacity(other._capacity) { if(_capacity > 0) { _data = allocate(_capacity); anton::uninitialized_copy_n(other._data, other._size, _data); _size = other._size; } } template<typename T, typename Allocator> Array<T, Allocator>::Array(Array&& other): _allocator(ANTON_MOV(other._allocator)), _capacity(other._capacity), _size(other._size), _data(other._data) { other._data = nullptr; other._capacity = 0; other._size = 0; } template<typename T, typename Allocator> template<typename Input_Iterator> Array<T, Allocator>::Array(Range_Construct_Tag, Input_Iterator first, Input_Iterator last) { // TODO: Use distance? size_type const count = last - first; _capacity = math::max(ANTON_ARRAY_MIN_ALLOCATION_SIZE, count); _data = allocate(_capacity); anton::uninitialized_copy(first, last, _data); _size = count; } template<typename T, typename Allocator> template<typename... Args> Array<T, Allocator>::Array(Variadic_Construct_Tag, Args&&... args) { _capacity = math::max(ANTON_ARRAY_MIN_ALLOCATION_SIZE, static_cast<size_type>(sizeof...(Args))); _data = allocate(_capacity); anton::uninitialized_variadic_construct(_data, ANTON_FWD(args)...); _size = static_cast<size_type>(sizeof...(Args)); } template<typename T, typename Allocator> Array<T, Allocator>::~Array() { anton::destruct_n(_data, _size); deallocate(_data, _capacity); } template<typename T, typename Allocator> Array<T, Allocator>& Array<T, Allocator>::operator=(Array const& other) { anton::destruct_n(_data, _size); deallocate(_data, _capacity); _capacity = other._capacity; _size = other._size; _allocator = other._allocator; if(_capacity > 0) { _data = allocate(_capacity); anton::uninitialized_copy_n(other._data, other._size, _data); } return *this; } template<typename T, typename Allocator> Array<T, Allocator>& Array<T, Allocator>::operator=(Array&& other) { swap(*this, other); return *this; } template<typename T, typename Allocator> auto Array<T, Allocator>::operator[](size_type index) -> T& { if constexpr(ANTON_ITERATOR_DEBUG) { ANTON_FAIL(index < _size && index >= 0, u8"index out of bounds"); } return _data[index]; } template<typename T, typename Allocator> auto Array<T, Allocator>::operator[](size_type index) const -> T const& { if constexpr(ANTON_ITERATOR_DEBUG) { ANTON_FAIL(index < _size && index >= 0, u8"index out of bounds"); } return _data[index]; } template<typename T, typename Allocator> auto Array<T, Allocator>::back() -> T& { if constexpr(ANTON_ITERATOR_DEBUG) { ANTON_FAIL(_size > 0, u8"attempting to call back() on empty Array"); } return _data[_size - 1]; } template<typename T, typename Allocator> auto Array<T, Allocator>::back() const -> T const& { if constexpr(ANTON_ITERATOR_DEBUG) { ANTON_FAIL(_size > 0, u8"attempting to call back() on empty Array"); } return _data[_size - 1]; } template<typename T, typename Allocator> auto Array<T, Allocator>::data() -> T* { return _data; } template<typename T, typename Allocator> auto Array<T, Allocator>::data() const -> T const* { return _data; } template<typename T, typename Allocator> auto Array<T, Allocator>::begin() -> iterator { return _data; } template<typename T, typename Allocator> auto Array<T, Allocator>::end() -> iterator { return _data + _size; } template<typename T, typename Allocator> auto Array<T, Allocator>::begin() const -> const_iterator { return _data; } template<typename T, typename Allocator> auto Array<T, Allocator>::end() const -> const_iterator { return _data + _size; } template<typename T, typename Allocator> auto Array<T, Allocator>::cbegin() const -> const_iterator { return _data; } template<typename T, typename Allocator> auto Array<T, Allocator>::cend() const -> const_iterator { return _data + _size; } template<typename T, typename Allocator> auto Array<T, Allocator>::size() const -> size_type { return _size; } template<typename T, typename Allocator> auto Array<T, Allocator>::size_bytes() const -> size_type { return _size * sizeof(T); } template<typename T, typename Allocator> auto Array<T, Allocator>::capacity() const -> size_type { return _capacity; } template<typename T, typename Allocator> auto Array<T, Allocator>::get_allocator() -> allocator_type& { return _allocator; } template<typename T, typename Allocator> auto Array<T, Allocator>::get_allocator() const -> allocator_type const& { return _allocator; } template<typename T, typename Allocator> void Array<T, Allocator>::resize(size_type n, value_type const& value) { ensure_capacity(n); if(n > _size) { anton::uninitialized_fill(_data + _size, _data + n, value); } else { anton::destruct(_data + n, _data + _size); } _size = n; } template<typename T, typename Allocator> void Array<T, Allocator>::resize(size_type n) { ensure_capacity(n); if(n > _size) { anton::uninitialized_default_construct(_data + _size, _data + n); } else { anton::destruct(_data + n, _data + _size); } _size = n; } template<typename T, typename Allocator> void Array<T, Allocator>::ensure_capacity(size_type requested_capacity) { if(requested_capacity > _capacity) { size_type new_capacity = (_capacity > 0 ? _capacity : ANTON_ARRAY_MIN_ALLOCATION_SIZE); while(new_capacity < requested_capacity) { new_capacity *= 2; } T* new_data = allocate(new_capacity); if constexpr(is_move_constructible<T>) { uninitialized_move(_data, _data + _size, new_data); } else { uninitialized_copy(_data, _data + _size, new_data); } anton::destruct_n(_data, _size); deallocate(_data, _capacity); _data = new_data; _capacity = new_capacity; } } template<typename T, typename Allocator> void Array<T, Allocator>::set_capacity(size_type new_capacity) { ANTON_ASSERT(new_capacity >= 0, "capacity must be greater than or equal 0"); if(new_capacity != _capacity) { i64 const new_size = math::min(new_capacity, _size); T* new_data = nullptr; if(new_capacity > 0) { new_data = allocate(new_capacity); } if constexpr(is_move_constructible<T>) { anton::uninitialized_move_n(_data, new_size, new_data); } else { anton::uninitialized_copy_n(_data, new_size, new_data); } anton::destruct_n(_data, _size); deallocate(_data, _capacity); _data = new_data; _capacity = new_capacity; _size = new_size; } } template<typename T, typename Allocator> void Array<T, Allocator>::force_size(size_type n) { ANTON_ASSERT(n <= _capacity, u8"requested size is greater than capacity"); _size = n; } template<typename T, typename Allocator> template<typename Input_Iterator> void Array<T, Allocator>::assign(Input_Iterator first, Input_Iterator last) { anton::destruct_n(_data, _size); ensure_capacity(last - first); anton::uninitialized_copy(first, last, _data); _size = last - first; } template<typename T, typename Allocator> template<typename... Args> auto Array<T, Allocator>::insert(Variadic_Construct_Tag, const_iterator position, Args&&... args) -> iterator { size_type const offset = static_cast<size_type>(position - begin()); return insert(variadic_construct, offset, ANTON_FWD(args)...); } template<typename T, typename Allocator> template<typename... Args> auto Array<T, Allocator>::insert(Variadic_Construct_Tag, size_type const position, Args&&... args) -> iterator { if constexpr(ANTON_ITERATOR_DEBUG) { ANTON_FAIL(position >= 0 && position <= _size, u8"index out of bounds"); } if(_size == _capacity || position != _size) { if(_size != _capacity) { anton::uninitialized_move_n(_data + _size - 1, 1, _data + _size); anton::move_backward(_data + position, _data + _size - 1, _data + _size); anton::construct(_data + position, ANTON_FWD(args)...); _size += 1; } else { i64 const new_capacity = (_capacity > 0 ? _capacity * 2 : ANTON_ARRAY_MIN_ALLOCATION_SIZE); T* const new_data = allocate(new_capacity); i64 moved = 0; anton::uninitialized_move(_data, _data + position, new_data); moved = position; anton::construct(new_data + position, ANTON_FWD(args)...); moved += 1; anton::uninitialized_move(_data + position, _data + _size, new_data + moved); anton::destruct_n(_data, _size); deallocate(_data, _capacity); _capacity = new_capacity; _data = new_data; _size += 1; } } else { // Quick path when position points to end and we have room for one more element. anton::construct(_data + _size, ANTON_FWD(args)...); _size += 1; } return _data + position; } template<typename T, typename Allocator> template<typename Input_Iterator> auto Array<T, Allocator>::insert(const_iterator position, Input_Iterator first, Input_Iterator last) -> iterator { size_type const offset = static_cast<size_type>(position - begin()); return insert(offset, first, last); } template<typename T, typename Allocator> template<typename Input_Iterator> auto Array<T, Allocator>::insert(size_type position, Input_Iterator first, Input_Iterator last) -> iterator { if constexpr(ANTON_ITERATOR_DEBUG) { ANTON_FAIL(position >= 0 && position <= _size, u8"index out of bounds"); } // TODO: Distance and actual support for input iterators. if(first != last) { i64 const new_elems = last - first; ANTON_ASSERT(new_elems > 0, "the difference of first and last must be greater than 0"); if(_size + new_elems <= _capacity && position == _size) { // Quick path when position points to end and we have room for new_elems elements. anton::uninitialized_copy(first, last, _data + _size); _size += new_elems; } else { if(_size + new_elems <= _capacity) { // total number of elements we want to move i64 const total_elems = _size - position; // when new_elems < total_elems, we have to unititialized_move min(total_elems, new_elems) // and move_backward the rest because the target range will overlap the source range i64 const elems_outside = math::min(total_elems, new_elems); i64 const elems_inside = total_elems - elems_outside; // we move the 'outside' elements to _size unless position + new_elems is greater than _size i64 const target_offset = math::max(position + new_elems, _size); anton::uninitialized_move_n(_data + position + elems_inside, elems_outside, _data + target_offset); anton::move_backward(_data + position, _data + position + elems_inside, _data + position + new_elems + elems_inside); // we always have to destruct at most total_elems and at least new_elems // if we attempt to destruct more than total_elems, we will call destruct on uninitialized memory anton::destruct_n(_data + position, elems_outside); anton::uninitialized_copy(first, last, _data + position); _size += new_elems; } else { i64 new_capacity = (_capacity > 0 ? _capacity : ANTON_ARRAY_MIN_ALLOCATION_SIZE); while(new_capacity <= _size + new_elems) { new_capacity *= 2; } T* const new_data = allocate(new_capacity); i64 moved = 0; anton::uninitialized_move(_data, _data + position, new_data); moved = position; anton::uninitialized_copy(first, last, new_data + moved); moved += new_elems; anton::uninitialized_move(_data + position, _data + _size, new_data + moved); anton::destruct_n(_data, _size); deallocate(_data, _capacity); _capacity = new_capacity; _data = new_data; _size += new_elems; } } } return _data + position; } template<typename T, typename Allocator> auto Array<T, Allocator>::insert_unsorted(const_iterator position, value_type const& value) -> iterator { size_type const offset = static_cast<size_type>(position - begin()); return insert_unsorted(offset, value); } template<typename T, typename Allocator> auto Array<T, Allocator>::insert_unsorted(const_iterator position, value_type&& value) -> iterator { size_type const offset = static_cast<size_type>(position - begin()); return insert_unsorted(offset, ANTON_MOV(value)); } template<typename T, typename Allocator> auto Array<T, Allocator>::insert_unsorted(size_type position, value_type const& value) -> iterator { if constexpr(ANTON_ITERATOR_DEBUG) { ANTON_FAIL(position >= 0 && position <= _size, u8"index out of bounds"); } ensure_capacity(_size + 1); T* elem_ptr = _data + position; if(position == _size) { anton::construct(elem_ptr, value); } else { if constexpr(is_move_constructible<T>) { anton::construct(_data + _size, ANTON_MOV(*elem_ptr)); } else { anton::construct(_data + _size, *elem_ptr); } anton::destruct(elem_ptr); anton::construct(elem_ptr, value); } ++_size; return elem_ptr; } template<typename T, typename Allocator> auto Array<T, Allocator>::insert_unsorted(size_type position, value_type&& value) -> iterator { if constexpr(ANTON_ITERATOR_DEBUG) { ANTON_FAIL(position >= 0 && position <= _size, u8"index out of bounds"); } ensure_capacity(_size + 1); T* elem_ptr = _data + position; if(position == _size) { anton::construct(elem_ptr, ANTON_MOV(value)); } else { if constexpr(is_move_constructible<T>) { anton::construct(_data + _size, ANTON_MOV(*elem_ptr)); } else { anton::construct(_data + _size, *elem_ptr); } anton::destruct(elem_ptr); anton::construct(elem_ptr, ANTON_MOV(value)); } ++_size; return elem_ptr; } template<typename T, typename Allocator> auto Array<T, Allocator>::push_back(value_type const& value) -> T& { ensure_capacity(_size + 1); T* const element = _data + _size; anton::construct(element, value); ++_size; return *element; } template<typename T, typename Allocator> auto Array<T, Allocator>::push_back(value_type&& value) -> T& { ensure_capacity(_size + 1); T* const element = _data + _size; anton::construct(element, ANTON_MOV(value)); ++_size; return *element; } template<typename T, typename Allocator> template<typename... Args> auto Array<T, Allocator>::emplace_back(Args&&... args) -> T& { ensure_capacity(_size + 1); T* const element = _data + _size; anton::construct(element, ANTON_FWD(args)...); ++_size; return *element; } template<typename T, typename Allocator> void Array<T, Allocator>::erase_unsorted(size_type index) { if constexpr(ANTON_ITERATOR_DEBUG) { ANTON_FAIL(index <= size && index >= 0, u8"index out of bounds"); } erase_unsorted_unchecked(index); } template<typename T, typename Allocator> void Array<T, Allocator>::erase_unsorted_unchecked(size_type index) { T* const element = _data + index; T* const last_element = _data + _size - 1; if(element != last_element) { // Prevent self assignment *element = ANTON_MOV(*last_element); } anton::destruct(last_element); --_size; } template<typename T, typename Allocator> auto Array<T, Allocator>::erase_unsorted(const_iterator iter) -> iterator { if constexpr(ANTON_ITERATOR_DEBUG) { ANTON_FAIL(iter - _data >= 0 && iter - _data <= _size, "iterator out of bounds"); } T* const position = const_cast<T*>(iter); T* const last_element = _data + _size - 1; if(position != last_element) { *position = ANTON_MOV(*last_element); } anton::destruct(last_element); --_size; return position; } // template <typename T, typename Allocator> // auto Array<T, Allocator>::erase_unsorted(const_iterator first, const_iterator last) -> iterator { // #if ANTON_ITERATOR_DEBUG // #endif // ANTON_ITERATOR_DEBUG // if (first != last) { // auto first_last_elems = last - first; // auto last_end_elems = end() - last; // auto elems_till_end = math::min(first_last_elems, last_end_elems); // move(end() - elems_till_end, end(), first); // destruct(end() - elems_till_end, end()); // _size -= first_last_elems; // } // return first; // } template<typename T, typename Allocator> auto Array<T, Allocator>::erase(const_iterator first, const_iterator last) -> iterator { if constexpr(ANTON_ITERATOR_DEBUG) { ANTON_FAIL(first - _data >= 0 && first - _data <= _size, "iterator out of bounds"); ANTON_FAIL(last - _data >= 0 && last - _data <= _size, "iterator out of bounds"); } if(first != last) { iterator pos = anton::move(const_cast<value_type*>(last), end(), const_cast<value_type*>(first)); anton::destruct(pos, end()); _size -= last - first; } return const_cast<value_type*>(first); } template<typename T, typename Allocator> void Array<T, Allocator>::pop_back() { ANTON_VERIFY(_size > 0, u8"pop_back called on an empty Array"); anton::destruct(_data + _size - 1); --_size; } template<typename T, typename Allocator> void Array<T, Allocator>::clear() { anton::destruct(_data, _data + _size); _size = 0; } template<typename T, typename Allocator> T* Array<T, Allocator>::allocate(size_type const size) { void* mem = _allocator.allocate(size * static_cast<isize>(sizeof(T)), static_cast<isize>(alignof(T))); return static_cast<T*>(mem); } template<typename T, typename Allocator> void Array<T, Allocator>::deallocate(void* mem, size_type const size) { _allocator.deallocate(mem, size * static_cast<isize>(sizeof(T)), static_cast<isize>(alignof(T))); } } // namespace anton
38.478261
156
0.610944
kociap
99b1a3dab92ede92281a6a4427483a1efb0db7bd
802
cpp
C++
Src/MatchScript/MatchScript_Console/main.cpp
jjuiddong/TemplateMatch-Script
5b43b62851ba73f7aa05e24d6e1dee7d0fbeadfd
[ "MIT" ]
null
null
null
Src/MatchScript/MatchScript_Console/main.cpp
jjuiddong/TemplateMatch-Script
5b43b62851ba73f7aa05e24d6e1dee7d0fbeadfd
[ "MIT" ]
null
null
null
Src/MatchScript/MatchScript_Console/main.cpp
jjuiddong/TemplateMatch-Script
5b43b62851ba73f7aa05e24d6e1dee7d0fbeadfd
[ "MIT" ]
null
null
null
#include "stdafx.h" using namespace std; using namespace cv; using namespace cvproc; using namespace cvproc::imagematch; void main() { cMatchManager mng; mng.Init("match-script.txt", "@test"); cMatchResult *result = mng.m_sharedData.AllocMatchResult(); list<string> exts; exts.push_back("jpg"); exts.push_back("png"); list <string> out; CollectFiles(exts, "./image/", out); out.sort(); for each (auto &str in out) { Mat img = imread(str); result->Init(&mng.m_matchScript, img, "", (sParseTree*)mng.m_matchScript.FindTreeLabel("@test"), true, true); mng.Match(*result); cout << "image=" << str << ", result = " << result->m_resultStr << endl; } mng.m_sharedData.FreeMatchResult(result); cout << endl << endl << "press key down to exit program" << endl; getchar(); }
20.564103
74
0.668329
jjuiddong
99b249080f28590a7fd251531bfd8d976e60881a
129
cpp
C++
boards/px4/io-v2/src/timer_config.cpp
Diksha-agg/Firmware_val
1efc1ba06997d19df3ed9bd927cfb24401b0fe03
[ "BSD-3-Clause" ]
null
null
null
boards/px4/io-v2/src/timer_config.cpp
Diksha-agg/Firmware_val
1efc1ba06997d19df3ed9bd927cfb24401b0fe03
[ "BSD-3-Clause" ]
null
null
null
boards/px4/io-v2/src/timer_config.cpp
Diksha-agg/Firmware_val
1efc1ba06997d19df3ed9bd927cfb24401b0fe03
[ "BSD-3-Clause" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:4bee13f1ae0dfeeb63f8afbdabf2f2c704da45573edd3063e914ae9149cba03c size 2868
32.25
75
0.883721
Diksha-agg
99b721b83ca5028f1440627b0d71712eff9ab18b
964
cpp
C++
src/abstraction/Semaphore.cpp
lythaniel/YapiBot
724d763fc675a984c110da396ae2803a4b847100
[ "MIT" ]
2
2018-05-28T16:00:52.000Z
2019-01-21T17:36:29.000Z
src/abstraction/Semaphore.cpp
lythaniel/YapiBot
724d763fc675a984c110da396ae2803a4b847100
[ "MIT" ]
null
null
null
src/abstraction/Semaphore.cpp
lythaniel/YapiBot
724d763fc675a984c110da396ae2803a4b847100
[ "MIT" ]
null
null
null
/* * Semaphore.cpp * * Copyright (C) 2016 Cyrille Potereau * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #include "Semaphore.h" #include <time.h> CSemaphore::CSemaphore (int32_t maxcount) : m_MaxCnt(maxcount) { sem_init (&m_Sem, 0, 0); } CSemaphore::~CSemaphore () { sem_destroy(&m_Sem); } bool CSemaphore::wait(int32_t timeout) { int32_t ret; if(timeout == SEM_TIMEOUT_DONTWAIT) { ret = sem_trywait(&m_Sem); } else if (timeout == SEM_TIMEOUT_FOREVER) { ret = sem_wait(&m_Sem); } else { timespec t; clock_gettime(CLOCK_REALTIME,&t); t.tv_sec += timeout/1000; t.tv_nsec += (timeout % 1000) * 1000000; ret = sem_timedwait(&m_Sem, &t); } return (ret == 0); } void CSemaphore::post(void) { if (m_MaxCnt > 0) { int32_t val; sem_getvalue(&m_Sem, &val); if (val < m_MaxCnt) { sem_post(&m_Sem); } } else { sem_post(&m_Sem); } }
14.606061
64
0.650415
lythaniel
99b8ad046d44d39e3334f4f0ab67279f33c735f0
965
cpp
C++
src/train/Trainer.cpp
yxtj/FAB
f483672e13ea96a3f1da450c9655b1fc239233b1
[ "MIT" ]
null
null
null
src/train/Trainer.cpp
yxtj/FAB
f483672e13ea96a3f1da450c9655b1fc239233b1
[ "MIT" ]
null
null
null
src/train/Trainer.cpp
yxtj/FAB
f483672e13ea96a3f1da450c9655b1fc239233b1
[ "MIT" ]
null
null
null
#include "Trainer.h" using namespace std; void Trainer::bindModel(Model* pm){ this->pm = pm; } void Trainer::bindDataset(const DataHolder* pd){ this->pd = pd; } void Trainer::prepare() { } void Trainer::ready() { } void Trainer::initBasic(const std::vector<std::string>& param) { this->param = param; } std::vector<std::string> Trainer::getParam() const { return param; } bool Trainer::needAveragedDelta() const { return true; } double Trainer::loss(const size_t topn) const { double res = 0; size_t n = topn == 0 ? pd->size() : topn; for(size_t i = 0; i < n; ++i){ res += pm->loss(pd->get(i)); } return res / static_cast<double>(n); } Trainer::DeltaResult Trainer::batchDelta(std::atomic<bool>& cond, const size_t start, const size_t cnt, const bool avg, const double slow) { return batchDelta(cond, start, cnt, avg); } void Trainer::applyDelta(const vector<double>& delta, const double factor) { pm->accumulateParameter(delta, factor); }
17.87037
74
0.682902
yxtj
99ba44ecdc17c0885d37e06cbddc6a3179528b70
1,563
cpp
C++
src/hikogui/widgets/momentary_button_widget.cpp
clayne/ttauri
9820409a7df5028ad39448ddd00830e843a2e6ac
[ "BSL-1.0" ]
null
null
null
src/hikogui/widgets/momentary_button_widget.cpp
clayne/ttauri
9820409a7df5028ad39448ddd00830e843a2e6ac
[ "BSL-1.0" ]
null
null
null
src/hikogui/widgets/momentary_button_widget.cpp
clayne/ttauri
9820409a7df5028ad39448ddd00830e843a2e6ac
[ "BSL-1.0" ]
null
null
null
// Copyright Take Vos 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #include "momentary_button_widget.hpp" namespace hi::inline v1 { widget_constraints const &momentary_button_widget::set_constraints() noexcept { _layout = {}; // On left side a check mark, on right side short-cut. Around the label extra margin. hilet extra_size = extent2{theme().margin * 2.0f, theme().margin * 2.0f}; _constraints = set_constraints_button() + extra_size; _constraints.margins = theme().margin; return _constraints; } void momentary_button_widget::set_layout(widget_layout const &layout) noexcept { if (compare_store(_layout, layout)) { _label_rectangle = aarectangle{theme().margin, 0.0f, layout.width() - theme().margin * 2.0f, layout.height()}; } set_layout_button(layout); } void momentary_button_widget::draw(draw_context const &context) noexcept { if (*mode > widget_mode::invisible and overlaps(context, layout())) { draw_label_button(context); draw_button(context); } } void momentary_button_widget::draw_label_button(draw_context const &context) noexcept { // Move the border of the button in the middle of a pixel. context.draw_box( layout(), layout().rectangle(), background_color(), focus_color(), theme().border_width, border_side::inside, corner_radii{theme().rounding_radius}); } } // namespace hi::inline v1
31.26
118
0.699296
clayne
99c1cfd3e2777ed3effb672764fabcd8db517c87
1,513
hpp
C++
test/unit/module/real/core/maxmag/diff/maxmag.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
test/unit/module/real/core/maxmag/diff/maxmag.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
test/unit/module/real/core/maxmag/diff/maxmag.hpp
orao/eve
a8bdc6a9cab06d905e8749354cde63776ab76846
[ "MIT" ]
null
null
null
//================================================================================================== /** EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #include <eve/function/diff/maxmag.hpp> #include <type_traits> TTS_CASE_TPL("Check diff(maxmag) return type", EVE_TYPE) { if constexpr(eve::floating_value<T>) { TTS_EXPR_IS(eve::diff_nth<2>(eve::maxmag)(T(), T()), T); TTS_EXPR_IS(eve::diff_nth<1>(eve::maxmag)(T(), T()), T); } else { TTS_PASS("Unsupported type"); } } TTS_CASE_TPL("Check eve::diff(eve::maxmag) behavior", EVE_TYPE) { if constexpr(eve::floating_value<T>) { TTS_EQUAL(eve::diff_1st(eve::maxmag)(T{2},T{-3}), T(0)); TTS_EQUAL(eve::diff_2nd(eve::maxmag)(T{2},T{-3}), T(1)); TTS_EQUAL(eve::diff_1st(eve::maxmag)(T{-4},T{3}), T(1)); TTS_EQUAL(eve::diff_2nd(eve::maxmag)(T{-4},T{3}), T(0)); using v_t = eve::element_type_t<T>; TTS_EQUAL(eve::diff_1st(eve::maxmag)(T(1), T(2), T(3), T(4), T(5)),T(0)); TTS_EQUAL(eve::diff_3rd(eve::maxmag)(T(1), T(2), T(10), T(4), T(5)),T(1)); TTS_EQUAL(eve::diff_nth<3>(eve::maxmag)(T(1), T(2), T(3), T(4), T(5)),T(0)); TTS_EQUAL(eve::diff_nth<6>(eve::maxmag)(T(1), T(2), T(3), T(4), T(5)),T(0)); TTS_EQUAL(eve::diff_nth<4>(eve::maxmag)(v_t(1), T(3), T(3), T(7), T(5)),T(1)); } else { TTS_PASS("Unsupported type"); } }
34.386364
100
0.519498
orao
99c5226676409519adf175cd79556a8a9436fb1e
3,093
cc
C++
src/mpc/test/mpc_flow_reactive_transport.cc
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
37
2017-04-26T16:27:07.000Z
2022-03-01T07:38:57.000Z
src/mpc/test/mpc_flow_reactive_transport.cc
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
494
2016-09-14T02:31:13.000Z
2022-03-13T18:57:05.000Z
src/mpc/test/mpc_flow_reactive_transport.cc
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
43
2016-09-26T17:58:40.000Z
2022-03-25T02:29:59.000Z
#include <iostream> #include "stdlib.h" #include "math.h" #include "UnitTest++.h" #include <Epetra_MpiComm.h> #include "Epetra_SerialComm.h" #include "Teuchos_ParameterList.hpp" #include "Teuchos_ParameterXMLFileReader.hpp" #include "CycleDriver.hh" #include "eos_registration.hh" #include "Mesh.hh" #include "MeshFactory.hh" #include "mpc_pks_registration.hh" #include "PK_Factory.hh" #include "PK.hh" #include "pks_flow_registration.hh" #include "pks_transport_registration.hh" #include "pks_chemistry_registration.hh" #include "State.hh" TEST(MPC_DRIVER_FLOW_REACTIVE_TRANSPORT) { using namespace Amanzi; using namespace Amanzi::AmanziMesh; using namespace Amanzi::AmanziGeometry; auto comm = Amanzi::getDefaultComm(); // read the main parameter list std::string xmlInFileName = "test/mpc_flow_reactive_transport.xml"; Teuchos::ParameterXMLFileReader xmlreader(xmlInFileName); Teuchos::ParameterList plist = xmlreader.getParameters(); // For now create one geometric model from all the regions in the spec Teuchos::ParameterList region_list = plist.get<Teuchos::ParameterList>("regions"); Teuchos::RCP<Amanzi::AmanziGeometry::GeometricModel> gm = Teuchos::rcp(new Amanzi::AmanziGeometry::GeometricModel(3, region_list, *comm)); // create mesh Preference pref; pref.clear(); pref.push_back(Framework::MSTK); pref.push_back(Framework::STK); MeshFactory meshfactory(comm,gm); meshfactory.set_preference(pref); Teuchos::RCP<Mesh> mesh = meshfactory.create(0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 100, 1, 1); AMANZI_ASSERT(!mesh.is_null()); // create dummy observation data object double avg1, avg2; Amanzi::ObservationData obs_data; Teuchos::RCP<Teuchos::ParameterList> glist = Teuchos::rcp(new Teuchos::ParameterList(plist)); Teuchos::ParameterList state_plist = glist->sublist("state"); Teuchos::RCP<Amanzi::State> S = Teuchos::rcp(new Amanzi::State(state_plist)); S->RegisterMesh("domain", mesh); { Amanzi::CycleDriver cycle_driver(glist, S, comm, obs_data); try { cycle_driver.Go(); S->GetFieldData("pressure")->MeanValue(&avg1); } catch (...) { CHECK(false); } // check observations std::vector<std::string> labels = obs_data.observationLabels(); std::vector<ObservationData::DataQuadruple> tmp = obs_data[labels[0]]; for (int k = 1; k < tmp.size(); ++k) { CHECK_CLOSE(tmp[k].value, -0.0006, 1.0e-5); } tmp = obs_data[labels[1]]; for (int k = 1; k < tmp.size(); ++k) { CHECK_CLOSE(tmp[k].value, -0.0002, 1.0e-5); } } // restart simulation and compare results glist->sublist("cycle driver").sublist("restart").set<std::string>("file name", "chk_frt00005.h5"); S = Teuchos::null; avg2 = 0.; S = Teuchos::rcp(new Amanzi::State(state_plist)); S->RegisterMesh("domain", mesh); { Amanzi::CycleDriver cycle_driver(glist, S, comm, obs_data); try { cycle_driver.Go(); S->GetFieldData("pressure")->MeanValue(&avg2); } catch (...) { CHECK(false); } } CHECK_CLOSE(avg1, avg2, 1e-5 * avg1); }
29.457143
101
0.692208
fmyuan
99c8eaf7c16791f13dee016aff3c4348574d4d0c
12,975
cpp
C++
test/ReaderTest.cpp
semirpuskarevic/serialization
f911bf5f3c04629f61fe3f3f805eebb3fd5b458a
[ "BSL-1.0" ]
null
null
null
test/ReaderTest.cpp
semirpuskarevic/serialization
f911bf5f3c04629f61fe3f3f805eebb3fd5b458a
[ "BSL-1.0" ]
null
null
null
test/ReaderTest.cpp
semirpuskarevic/serialization
f911bf5f3c04629f61fe3f3f805eebb3fd5b458a
[ "BSL-1.0" ]
null
null
null
#include <date.h> #include <gmock/gmock.h> #include <boost/asio/buffer.hpp> #include <reader.hpp> #include <writer.hpp> #include "SerializationTestTypes.hpp" using namespace testing; using namespace detail; using namespace date; using namespace std::chrono; namespace asio = boost::asio; template <size_t N> class ReaderBase : public Test { protected: constexpr static auto arr_size = N; ReaderBase() : buf_{asio::buffer(main_buf_)}, writer_{buf_}, reader_{buf_} {} private: std::array<char, arr_size> main_buf_; protected: asio::mutable_buffer buf_; writer writer_; reader reader_; }; class ReaderTest : public ReaderBase<10u> { protected: ReaderTest() { writer_(fourByteNum); writer_(twoByteNum); } int32_t fourByteNum = 5; uint16_t twoByteNum = 15; }; TEST_F(ReaderTest, ReadsIntegralValueAfterWrite) { int32_t readFourByteNum; reader_(readFourByteNum); ASSERT_THAT(readFourByteNum, Eq(fourByteNum)); } TEST_F(ReaderTest, ReadsTwoConsecutiveIntegralValuesAfterWrite) { int32_t readFourByteNum; reader_(readFourByteNum); uint16_t readTwoByteNum; reader_(readTwoByteNum); ASSERT_THAT(readTwoByteNum, Eq(twoByteNum)); } template <typename T> class IntegralTypeReader : public ReaderBase<1024u> { protected: IntegralTypeReader() { writer_(num); } T num{5}; }; using MyIntegralTypes = ::testing::Types<char, int8_t, int16_t, int64_t, uint8_t, uint32_t, uint64_t>; TYPED_TEST_CASE(IntegralTypeReader, MyIntegralTypes); TYPED_TEST(IntegralTypeReader, ReadssVariousIntegralTypes) { TypeParam readNum; this->reader_(readNum); ASSERT_THAT(readNum, Eq(this->num)); } class BooleanTypeReader : public ReaderBase<4u> { protected: BooleanTypeReader() { writer_(true); writer_(false); } }; TEST_F(BooleanTypeReader, ReadsBooleanValuesAfterWrite) { bool trueValueRead; bool falseValueRead; reader_(trueValueRead); reader_(falseValueRead); ASSERT_TRUE(trueValueRead); ASSERT_FALSE(falseValueRead); } class FloatingPointTypeReader : public ReaderBase<14u> { protected: FloatingPointTypeReader() { writer_(e); writer_(ePrecise); } float e = 2.718281; double ePrecise = 2.718281828459; }; TEST_F(FloatingPointTypeReader, ReadsFloatValueAfterWrite) { float eRead; reader_(eRead); ASSERT_THAT(eRead, Eq(e)); } TEST_F(FloatingPointTypeReader, ReadsDoubleValueAfterWrite) { float eRead; reader_(eRead); double ePreciseRead; reader_(ePreciseRead); ASSERT_THAT(ePreciseRead, ePrecise); } class EnumTypeReader : public ReaderBase<8u> { protected: enum class CharEnum : char { A = 'A', B = 'B', C = 'C' }; enum class UInt32Enum : uint32_t { X, Y }; EnumTypeReader() { writer_(CharEnum::B); writer_(UInt32Enum::X); } }; TEST_F(EnumTypeReader, ReadsCharEnumValueAfterWrite) { CharEnum readValue; reader_(readValue); ASSERT_THAT(readValue, Eq(CharEnum::B)); } TEST_F(EnumTypeReader, ReadsMultipleEnumValuesAfterWrite) { CharEnum readFirst; reader_(readFirst); UInt32Enum readSecond; reader_(readSecond); ASSERT_THAT(readSecond, Eq(UInt32Enum::X)); } class IntegralConstantReader : public ReaderBase<32u> { protected: using IntConstUInt16 = std::integral_constant<uint16_t, 0xf001>; using IntConstUInt32 = std::integral_constant<uint32_t, 0xf0010203>; IntegralConstantReader() { writer_(uint16Member); writer_(regularNum); writer_(uint32Member); writer_(regularNum); } IntConstUInt16 uint16Member; int32_t regularNum = 5; IntConstUInt32 uint32Member; }; TEST_F(IntegralConstantReader, ReadsUInt16IntegralConstantValueAfterWrite) { IntConstUInt16 readUint16Member; reader_(readUint16Member); int32_t readRegularNum; reader_(readRegularNum); ASSERT_THAT(readRegularNum, Eq(5)); } TEST_F(IntegralConstantReader, ReadsMultipleIntegralConstantValuesAfterWrite) { IntConstUInt16 readUint16Member; reader_(readUint16Member); int32_t readRegularNum; reader_(readRegularNum); IntConstUInt32 readUint32Member; reader_(readUint32Member); int32_t readSedondRegularNum; reader_(readSedondRegularNum); ASSERT_THAT(readSedondRegularNum, Eq(5)); } TEST_F(IntegralConstantReader, ConfirmsThatExceptionIsGeneratedWhenConstValueDoesNotMatchReadValue) { std::integral_constant<uint16_t, 0xf002> differentConstValue; ASSERT_THROW(reader_(differentConstValue), std::domain_error); } class StringReader : public ReaderBase<20u> { protected: StringReader() { writer_("ABC"); writer_("12345"); } }; TEST_F(StringReader, ReadsStringValueAfterWrite) { std::string readWord; reader_(readWord); ASSERT_THAT(readWord, Eq("ABC")); } TEST_F(StringReader, ReadsConsecutiveStringValuesAfterWrite) { std::string firstWord; reader_(firstWord); std::string secondWord; reader_(secondWord); ASSERT_THAT(secondWord, Eq("12345")); } class VectorReader : public ReaderBase<50u> { protected: VectorReader() { writer_(numbers); writer_(words); } std::vector<int32_t> numbers{1, 5, 10, 15}; std::vector<std::string> words{"A", "AB", "ABC"}; }; TEST_F(VectorReader, ReadsVectorOfIntegralValuesAfterWrite) { std::vector<int32_t> readNumbers; reader_(readNumbers); ASSERT_THAT(readNumbers, Eq(numbers)); } TEST_F(VectorReader, ReadsConsecutiveVectorsOfDifferentTypeslAfterWrite) { std::vector<int32_t> readNumbers; reader_(readNumbers); std::vector<std::string> readWords; reader_(readWords); ASSERT_THAT(readWords, Eq(words)); } class DateTimeReader : public ReaderBase<15u> { protected: DateTimeReader() { writer_(microsecDateTime); } sys_time<microseconds> microsecDateTime{sys_days(2016_y / 05 / 01) + hours{5} + minutes{15} + seconds{0} + microseconds{123456}}; }; TEST_F(DateTimeReader, ReadsTimePointWithMicrosecondsAfterWrite) { sys_time<microseconds> microsecDateTimeRead; reader_(microsecDateTimeRead); ASSERT_THAT(microsecDateTimeRead, Eq(microsecDateTime)); } class UnorderedMapReader : public ReaderBase<50u> { protected: UnorderedMapReader() { writer_(elements); writer_(numElements); } std::unordered_map<int32_t, std::string> elements{ {1, "A"}, {2, "B"}, {3, "AB"}}; std::unordered_map<int16_t, uint32_t> numElements{{1, 5}, {2, 10}, {3, 15}}; }; TEST_F(UnorderedMapReader, ReadsUnorderedMapValueAfterWrite) { std::unordered_map<int32_t, std::string> readElements; reader_(readElements); ASSERT_THAT(readElements, Eq(elements)); } TEST_F(UnorderedMapReader, ReadsMultipleUnorderedMapValuesAfterWrite) { std::unordered_map<int32_t, std::string> readElements; reader_(readElements); std::unordered_map<int16_t, uint32_t> readNumElements; reader_(readNumElements); ASSERT_THAT(readNumElements, Eq(numElements)); } class SimpleFusionSequenceReader : public ReaderBase<20u> { protected: SimpleFusionSequenceReader() { writer_(header); } SerializationTestTypes::header_t header = { {}, 1, SerializationTestTypes::msg_type_t::B}; }; TEST_F(SimpleFusionSequenceReader, ReadsSequenceValuesAfterWrite) { SerializationTestTypes::header_t readHeader; reader_(readHeader); ASSERT_THAT(readHeader.version, Eq(header.version)); ASSERT_THAT(readHeader.msg_type, Eq(header.msg_type)); ASSERT_THAT(readHeader.seq_num, Eq(header.seq_num)); } class NestedFusionSequenceReader : public ReaderBase<30u> { protected: NestedFusionSequenceReader() { writer_(msg); } SerializationTestTypes::some_message_t msg = {{"12"}, {{"AB", "C"}}}; }; TEST_F(NestedFusionSequenceReader, ReadsNestedFusionSequenceValueAfterWrite) { SerializationTestTypes::some_message_t readMsg; reader_(readMsg); ASSERT_THAT(readMsg.id, Eq(msg.id)); ASSERT_THAT(readMsg.properties.value, Eq(msg.properties.value)); } class OptionalFieldReader : public ReaderBase<10u> { protected: OptionalFieldReader() { writer_(optFieldsMask); writer_(optIntField); writer_(optMsg); writer_(description); } SerializationTestTypes::opt_fields optFieldsMask; SerializationTestTypes::opt_int32_field optIntField = 5; SerializationTestTypes::opt_msg_type_t optMsg; SerializationTestTypes::opt_string_t description = {"AB"}; }; TEST_F(OptionalFieldReader, ReadsOptionalFieldSetAndOptionalValueAfterWrite) { SerializationTestTypes::opt_fields readOptFieldsMask; reader_(readOptFieldsMask); SerializationTestTypes::opt_int32_field readOptIntField; reader_(readOptIntField); ASSERT_THAT(*readOptIntField, Eq(*optIntField)); } TEST_F(OptionalFieldReader, ReadsNonSetOptionalFieldValueAfterWrite) { SerializationTestTypes::opt_fields readOptFieldsMask; reader_(readOptFieldsMask); SerializationTestTypes::opt_int32_field readOptIntField; reader_(readOptIntField); SerializationTestTypes::opt_msg_type_t readOptMsg; reader_(readOptMsg); ASSERT_FALSE(readOptMsg); } TEST_F(OptionalFieldReader, ReadsOptionalFieldValueAfterNonSetValueAfterWrite) { SerializationTestTypes::opt_fields readOptFieldsMask; reader_(readOptFieldsMask); SerializationTestTypes::opt_int32_field readOptIntField; reader_(readOptIntField); SerializationTestTypes::opt_msg_type_t readOptMsg; reader_(readOptMsg); SerializationTestTypes::opt_string_t readDescription; reader_(readDescription); ASSERT_THAT(*readDescription, Eq(description)); } TEST_F(OptionalFieldReader, ConfirmsThatExceptionIsGeneratedWhenFieldIsReadBeforeFieldSet) { SerializationTestTypes::opt_int32_field readOptIntField; ASSERT_THROW(reader_(readOptIntField), std::domain_error); } TEST_F(ReaderTest, ReadsIntegralValueWithReadFunction) { auto readFourByteNum = read<int32_t>(buf_); auto readTwoByteNum = read<uint16_t>(readFourByteNum.second); ASSERT_THAT(readFourByteNum.first, Eq(fourByteNum)); ASSERT_THAT(readTwoByteNum.first, Eq(twoByteNum)); } TEST_F(EnumTypeReader, ReadsMultipleEnumValuesWithReadFunction) { auto readFirst = read<CharEnum>(buf_); auto readSecond = read<UInt32Enum>(readFirst.second); ASSERT_THAT(readFirst.first, Eq(CharEnum::B)); ASSERT_THAT(readSecond.first, Eq(UInt32Enum::X)); } TEST_F(IntegralConstantReader, ReadsMultipleIntegralConstantValuesWithReadFunction) { auto readUint16Member = read<IntConstUInt16>(buf_); auto readRegularNum = read<int32_t>(readUint16Member.second); auto readUint32Member = read<IntConstUInt32>(readRegularNum.second); auto readSedondRegularNum = read<int32_t>(readUint32Member.second); ASSERT_THAT(readSedondRegularNum.first, Eq(5)); } TEST_F(StringReader, ReadsConsecutiveStringValuesWithReadFunction) { auto firstWord = read<std::string>(buf_); auto secondWord = read<std::string>(firstWord.second); ASSERT_THAT(secondWord.first, Eq("12345")); } TEST_F(VectorReader, ReadsConsecutiveVectorsOfDifferentTypesWithReadFunction) { auto readNumbes = read<std::vector<int32_t>>(buf_); auto readWords = read<std::vector<std::string>>(readNumbes.second); ASSERT_THAT(readWords.first, Eq(words)); } TEST_F(UnorderedMapReader, ReadsMultipleUnorderedMapValuesWithReadFunction) { auto readElements = read<std::unordered_map<int32_t, std::string>>(buf_); auto readNumElements = read<std::unordered_map<int16_t, uint32_t>>(readElements.second); ASSERT_THAT(readNumElements.first, Eq(numElements)); } TEST_F(NestedFusionSequenceReader, ReadsNestedFusionSequenceValueWithReadFunction) { auto readMsg = read<SerializationTestTypes::some_message_t>(buf_); ASSERT_THAT(readMsg.first.id, Eq(msg.id)); ASSERT_THAT(readMsg.first.properties.value, Eq(msg.properties.value)); } TEST_F( OptionalFieldReader, ConfirmsThatExceptionIsGeneratedWhenReadingOptionalFieldsWithReadFunction) { auto readOptFieldsMask = read<SerializationTestTypes::opt_fields>(buf_); ASSERT_THROW( read<SerializationTestTypes::opt_int32_field>(readOptFieldsMask.second), std::domain_error); } class FusionSequenceWithOptionalFieldReader : public ReaderBase<50u> { protected: FusionSequenceWithOptionalFieldReader() { writer_(msg); } SerializationTestTypes::msg_with_opt_fields_t msg = { {{"A", "B", "AB"}}, {}, {5}, {}}; }; TEST_F(FusionSequenceWithOptionalFieldReader, ReadOptionalFieldsAsPartOfFusionSequenceWithReadFunction) { auto readMsg = read<SerializationTestTypes::msg_with_opt_fields_t>(buf_); ASSERT_THAT(readMsg.first.properties.value, Eq(msg.properties.value)); ASSERT_THAT(readMsg.first.number, Eq(5)); }
29.896313
80
0.734489
semirpuskarevic
99cbbec5ad5e7ce2bd29ba687b8276193507324b
997
cpp
C++
Cplus/PathWithMinimumEffort.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
1
2018-01-22T12:06:28.000Z
2018-01-22T12:06:28.000Z
Cplus/PathWithMinimumEffort.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
Cplus/PathWithMinimumEffort.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
#include <climits> #include <cmath> #include <queue> #include <vector> using namespace std; class Solution { public: int minimumEffortPath(vector<vector<int>> &heights) { int M = heights.size(), N = heights[0].size(); priority_queue<pair<int, int>> q; //{effort,position} vector<vector<int>> seen(M, vector<int>(N, INT_MAX)); seen[0][0] = 0; q.push({0, 0}); while (!q.empty()) { int x = q.top().second / N, y = q.top().second % N; int effort = -q.top().first; q.pop(); if (x == M - 1 && y == N - 1) return effort; //board dfs direction int path[5] = {-1, 0, 1, 0, -1}; for (int i = 0; i < 4; ++i) { int dx = x + path[i], dy = y + path[i + 1]; if (dx < 0 || dx >= M || dy < 0 || dy >= N) continue; int curEffort = abs(heights[x][y] - heights[dx][dy]); curEffort = max(curEffort, effort); if (curEffort < seen[dx][dy]) { seen[dx][dy] = curEffort; q.push({-curEffort, dx * N + dy}); } } } return -1; } };
23.738095
57
0.535607
JumHorn
99cc05d8f903917c17d9241b307bff4a11c42acc
5,810
cc
C++
sdk/c/api/media_stream_interface.cc
raghuhit/webrtc-1
5b534b6458ab14cbe62a2bbb642e8a3536dfd5e2
[ "Apache-2.0", "BSD-3-Clause" ]
99
2019-09-30T11:42:30.000Z
2021-12-24T04:41:10.000Z
sdk/c/api/media_stream_interface.cc
raghuhit/webrtc-1
5b534b6458ab14cbe62a2bbb642e8a3536dfd5e2
[ "Apache-2.0", "BSD-3-Clause" ]
23
2020-03-27T00:59:45.000Z
2022-03-28T15:31:09.000Z
sdk/c/api/media_stream_interface.cc
raghuhit/webrtc-1
5b534b6458ab14cbe62a2bbb642e8a3536dfd5e2
[ "Apache-2.0", "BSD-3-Clause" ]
26
2019-11-23T15:36:12.000Z
2022-03-15T15:37:01.000Z
/* * Copyright 2019 pixiv Inc. All Rights Reserved. * * Use of this source code is governed by a license that can be * found in the LICENSE.pixiv file in the root of the source tree. */ #include "api/media_stream_interface.h" #include "rtc_base/ref_counted_object.h" #include "sdk/c/api/media_stream_interface.h" namespace webrtc { class DelegatingAudioSourceInterface : public AudioSourceInterface { public: DelegatingAudioSourceInterface( void* context, const struct AudioSourceInterfaceFunctions* functions) { context_ = context; functions_ = functions; } ~DelegatingAudioSourceInterface() { functions_->on_destruction(context_); } void RegisterObserver(ObserverInterface* observer) { functions_->register_observer(context_, rtc::ToC(observer)); } void UnregisterObserver(ObserverInterface* observer) { functions_->unregister_observer(context_, rtc::ToC(observer)); } void AddSink(AudioTrackSinkInterface* sink) { functions_->add_sink(context_, rtc::ToC(sink)); } void RemoveSink(AudioTrackSinkInterface* sink) { functions_->remove_sink(context_, rtc::ToC(sink)); } SourceState state() const { return static_cast<SourceState>(functions_->state(context_)); } bool remote() const { return functions_->remote(context_); } private: void* context_; const struct AudioSourceInterfaceFunctions* functions_; }; } extern "C" WebrtcMediaSourceInterface* webrtcAudioSourceInterfaceToWebrtcMediaSourceInterface( WebrtcAudioSourceInterface* source) { return rtc::ToC( static_cast<webrtc::MediaSourceInterface*>(rtc::ToCplusplus(source))); } extern "C" void webrtcAudioTrackInterfaceAddSink( WebrtcAudioTrackInterface* track, WebrtcAudioTrackSinkInterface* sink) { rtc::ToCplusplus(track)->AddSink(rtc::ToCplusplus(sink)); } extern "C" WebrtcMediaStreamTrackInterface* webrtcAudioTrackInterfaceToWebrtcMediaStreamTrackInterface( WebrtcAudioTrackInterface* track) { return rtc::ToC( static_cast<webrtc::MediaStreamTrackInterface*>(rtc::ToCplusplus(track))); } extern "C" void webrtcAudioTrackSinkInterfaceOnData( WebrtcAudioTrackSinkInterface* sink, const void* audio_data, int bits_per_sample, int sample_rate, size_t number_of_channels, size_t number_of_frames) { rtc::ToCplusplus(sink)->OnData(audio_data, bits_per_sample, sample_rate, number_of_channels, number_of_frames); } extern "C" void webrtcMediaSourceInterfaceRelease( const WebrtcMediaSourceInterface* source) { rtc::ToCplusplus(source)->Release(); } extern "C" WebrtcVideoTrackSourceInterface* webrtcMediaSourceInterfaceToWebrtcVideoTrackSourceInterface( WebrtcMediaSourceInterface* source) { return rtc::ToC(static_cast<webrtc::VideoTrackSourceInterface*>( rtc::ToCplusplus(source))); } extern "C" void webrtcMediaStreamInterfaceRelease( const WebrtcMediaStreamInterface* stream) { rtc::ToCplusplus(stream)->Release(); } extern "C" RtcString* webrtcMediaStreamTrackInterfaceId( const WebrtcMediaStreamTrackInterface* track) { return rtc::ToC(new auto(rtc::ToCplusplus(track)->id())); } extern "C" void webrtcMediaStreamTrackInterfaceRelease( const WebrtcMediaStreamTrackInterface* track) { rtc::ToCplusplus(track)->Release(); } extern "C" const char* webrtcMediaStreamTrackInterfaceKAudioKind() { return webrtc::MediaStreamTrackInterface::kAudioKind; } extern "C" const char* webrtcMediaStreamTrackInterfaceKind( const WebrtcMediaStreamTrackInterface* track) { auto kind = rtc::ToCplusplus(track)->kind(); if (kind == webrtc::MediaStreamTrackInterface::kAudioKind) { return webrtc::MediaStreamTrackInterface::kAudioKind; } if (kind == webrtc::MediaStreamTrackInterface::kVideoKind) { return webrtc::MediaStreamTrackInterface::kVideoKind; } RTC_NOTREACHED(); return nullptr; } extern "C" const char* webrtcMediaStreamTrackInterfaceKVideoKind() { return webrtc::MediaStreamTrackInterface::kVideoKind; } extern "C" WebrtcAudioTrackInterface* webrtcMediaStreamTrackInterfaceToWebrtcAudioTrackInterface( WebrtcMediaStreamTrackInterface* track) { return rtc::ToC( static_cast<webrtc::AudioTrackInterface*>(rtc::ToCplusplus(track))); } extern "C" WebrtcVideoTrackInterface* webrtcMediaStreamTrackInterfaceToWebrtcVideoTrackInterface( WebrtcMediaStreamTrackInterface* track) { return rtc::ToC( static_cast<webrtc::VideoTrackInterface*>(rtc::ToCplusplus(track))); } extern "C" WebrtcAudioSourceInterface* webrtcNewAudioSourceInterface( void* context, const struct AudioSourceInterfaceFunctions* functions) { auto source = new rtc::RefCountedObject<webrtc::DelegatingAudioSourceInterface>( context, functions); source->AddRef(); return rtc::ToC(static_cast<webrtc::AudioSourceInterface*>(source)); } extern "C" void webrtcVideoTrackInterfaceAddOrUpdateSink( WebrtcVideoTrackInterface* track, RtcVideoSinkInterface* sink, const struct RtcVideoSinkWants* cwants) { rtc::VideoSinkWants wants; wants.rotation_applied = cwants->rotation_applied; wants.black_frames = cwants->black_frames; wants.max_pixel_count = cwants->max_pixel_count; wants.max_framerate_fps = cwants->max_framerate_fps; if (cwants->has_target_pixel_count) { wants.target_pixel_count = cwants->target_pixel_count; } return rtc::ToCplusplus(track)->AddOrUpdateSink(rtc::ToCplusplus(sink), wants); } extern "C" WebrtcMediaStreamTrackInterface* webrtcVideoTrackInterfaceToWebrtcMediaStreamTrackInterface( WebrtcVideoTrackInterface* track) { return rtc::ToC( static_cast<webrtc::MediaStreamTrackInterface*>(rtc::ToCplusplus(track))); }
30.904255
80
0.754217
raghuhit
99ce60775ebc950d1219773204d34f11e23551d3
4,252
cpp
C++
src/global/operator_factory.cpp
ViewFaceCore/TenniS
c1d21a71c1cd025ddbbe29924c8b3296b3520fc0
[ "BSD-2-Clause" ]
null
null
null
src/global/operator_factory.cpp
ViewFaceCore/TenniS
c1d21a71c1cd025ddbbe29924c8b3296b3520fc0
[ "BSD-2-Clause" ]
null
null
null
src/global/operator_factory.cpp
ViewFaceCore/TenniS
c1d21a71c1cd025ddbbe29924c8b3296b3520fc0
[ "BSD-2-Clause" ]
null
null
null
// // Created by kier on 2018/6/29. // #include "global/operator_factory.h" #include <map> #include <global/operator_factory.h> #include "global/memory_device.h" namespace ts { using Name = std::pair<DeviceType, std::string>; template<typename K, typename V> using map = std::map<K, V>; static map<Name, OperatorCreator::function> &MapNameCreator() { static map<Name, OperatorCreator::function> map_name_creator; return map_name_creator; }; OperatorCreator::function OperatorCreator::Query(const DeviceType &device_type, const std::string &operator_name) TS_NOEXCEPT { auto &map_name_creator = MapNameCreator(); Name device_operator_name = std::make_pair(device_type, operator_name); auto name_creator = map_name_creator.find(device_operator_name); if (name_creator != map_name_creator.end()) { return name_creator->second; } return OperatorCreator::function(nullptr); } void OperatorCreator::Register(const DeviceType &device_type, const std::string &operator_name, const OperatorCreator::function &operator_creator) TS_NOEXCEPT { auto &map_name_creator = MapNameCreator(); Name device_operator_name = std::make_pair(device_type, operator_name); map_name_creator[device_operator_name] = operator_creator; } const OperatorCreator::CreatorFucMap OperatorCreator::GetCreatorFucMap(){ auto map_name_creator = MapNameCreator(); return std::move(map_name_creator); } void OperatorCreator::flush(const OperatorCreator::CreatorFucMap& creator_map){ auto &map_name_creator = MapNameCreator(); map_name_creator.clear(); for(auto it=creator_map.begin(); it!=creator_map.end(); ++it){ map_name_creator[it->first] = it->second; } } void OperatorCreator::Clear() { auto &map_name_creator = MapNameCreator(); map_name_creator.clear(); } static OperatorCreator::function TalentQuery(const DeviceType &device_type, const std::string &operator_name, bool strict) { // step 1: check in strict mode auto creator = OperatorCreator::Query(device_type, operator_name); if (strict) return creator; if (creator == nullptr) { // step 2.x: try find operator on memory device, if computing device failed auto memory_device = ComputingMemory::Query(device_type); creator = OperatorCreator::Query(memory_device, operator_name); } if (creator == nullptr) { // step 2.y: try find operator on CPU version if (device_type != CPU) { creator = OperatorCreator::Query(CPU, operator_name); } } return creator; } Operator::shared OperatorCreator::CreateNoException(const DeviceType &device_type, const std::string &operator_name, bool strict) TS_NOEXCEPT { auto creator = TalentQuery(device_type, operator_name, strict); if (!creator) return nullptr; return creator(); } OperatorCreator::function OperatorCreator::Query(const DeviceType &device_type, const std::string &operator_name, bool strict) TS_NOEXCEPT { return TalentQuery(device_type, operator_name, strict); } Operator::shared OperatorCreator::Create(const DeviceType &device_type, const std::string &operator_name, bool strict) { auto op = CreateNoException(device_type, operator_name, strict); if (op == nullptr) throw OperatorNotFoundException(device_type, operator_name); return op; } std::set<std::pair<std::string, std::string>> OperatorCreator::AllKeys() TS_NOEXCEPT { auto &map_name_creator = MapNameCreator(); std::set<std::pair<std::string, std::string>> set_name; for (auto &name : map_name_creator) { auto &pair = name.first; set_name.insert(std::make_pair(pair.first.std(), pair.second)); } return set_name; } }
37.964286
120
0.634995
ViewFaceCore
99ce72cc34e49c642c23bab57fcbedcd0b594c0d
11,612
cc
C++
diplomacy_research/proto/tensorflow_serving/apis/prediction_service.grpc.pb.cc
wwongkamjan/dipnet_press
787263c1b9484698904f525c8d78d0e333e1c0d9
[ "MIT" ]
39
2019-09-06T13:42:24.000Z
2022-03-18T18:38:43.000Z
diplomacy_research/proto/tensorflow_serving/apis/prediction_service.grpc.pb.cc
wwongkamjan/dipnet_press
787263c1b9484698904f525c8d78d0e333e1c0d9
[ "MIT" ]
9
2019-09-19T22:35:32.000Z
2022-02-24T18:04:57.000Z
diplomacy_research/proto/tensorflow_serving/apis/prediction_service.grpc.pb.cc
wwongkamjan/dipnet_press
787263c1b9484698904f525c8d78d0e333e1c0d9
[ "MIT" ]
8
2019-10-16T21:09:14.000Z
2022-02-23T05:20:37.000Z
// Generated by the gRPC C++ plugin. // If you make any local change, they will be lost. // source: tensorflow_serving/apis/prediction_service.proto #include "tensorflow_serving/apis/prediction_service.pb.h" #include "tensorflow_serving/apis/prediction_service.grpc.pb.h" #include <grpcpp/impl/codegen/async_stream.h> #include <grpcpp/impl/codegen/async_unary_call.h> #include <grpcpp/impl/codegen/channel_interface.h> #include <grpcpp/impl/codegen/client_unary_call.h> #include <grpcpp/impl/codegen/method_handler_impl.h> #include <grpcpp/impl/codegen/rpc_service_method.h> #include <grpcpp/impl/codegen/service_type.h> #include <grpcpp/impl/codegen/sync_stream.h> namespace tensorflow { namespace serving { static const char* PredictionService_method_names[] = { "/tensorflow.serving.PredictionService/Classify", "/tensorflow.serving.PredictionService/Regress", "/tensorflow.serving.PredictionService/Predict", "/tensorflow.serving.PredictionService/MultiInference", "/tensorflow.serving.PredictionService/GetModelMetadata", }; std::unique_ptr< PredictionService::Stub> PredictionService::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options) { (void)options; std::unique_ptr< PredictionService::Stub> stub(new PredictionService::Stub(channel)); return stub; } PredictionService::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) : channel_(channel), rpcmethod_Classify_(PredictionService_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_Regress_(PredictionService_method_names[1], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_Predict_(PredictionService_method_names[2], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_MultiInference_(PredictionService_method_names[3], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_GetModelMetadata_(PredictionService_method_names[4], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) {} ::grpc::Status PredictionService::Stub::Classify(::grpc::ClientContext* context, const ::tensorflow::serving::ClassificationRequest& request, ::tensorflow::serving::ClassificationResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Classify_, context, request, response); } ::grpc::ClientAsyncResponseReader< ::tensorflow::serving::ClassificationResponse>* PredictionService::Stub::AsyncClassifyRaw(::grpc::ClientContext* context, const ::tensorflow::serving::ClassificationRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::ClassificationResponse>::Create(channel_.get(), cq, rpcmethod_Classify_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::tensorflow::serving::ClassificationResponse>* PredictionService::Stub::PrepareAsyncClassifyRaw(::grpc::ClientContext* context, const ::tensorflow::serving::ClassificationRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::ClassificationResponse>::Create(channel_.get(), cq, rpcmethod_Classify_, context, request, false); } ::grpc::Status PredictionService::Stub::Regress(::grpc::ClientContext* context, const ::tensorflow::serving::RegressionRequest& request, ::tensorflow::serving::RegressionResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Regress_, context, request, response); } ::grpc::ClientAsyncResponseReader< ::tensorflow::serving::RegressionResponse>* PredictionService::Stub::AsyncRegressRaw(::grpc::ClientContext* context, const ::tensorflow::serving::RegressionRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::RegressionResponse>::Create(channel_.get(), cq, rpcmethod_Regress_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::tensorflow::serving::RegressionResponse>* PredictionService::Stub::PrepareAsyncRegressRaw(::grpc::ClientContext* context, const ::tensorflow::serving::RegressionRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::RegressionResponse>::Create(channel_.get(), cq, rpcmethod_Regress_, context, request, false); } ::grpc::Status PredictionService::Stub::Predict(::grpc::ClientContext* context, const ::tensorflow::serving::PredictRequest& request, ::tensorflow::serving::PredictResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Predict_, context, request, response); } ::grpc::ClientAsyncResponseReader< ::tensorflow::serving::PredictResponse>* PredictionService::Stub::AsyncPredictRaw(::grpc::ClientContext* context, const ::tensorflow::serving::PredictRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::PredictResponse>::Create(channel_.get(), cq, rpcmethod_Predict_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::tensorflow::serving::PredictResponse>* PredictionService::Stub::PrepareAsyncPredictRaw(::grpc::ClientContext* context, const ::tensorflow::serving::PredictRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::PredictResponse>::Create(channel_.get(), cq, rpcmethod_Predict_, context, request, false); } ::grpc::Status PredictionService::Stub::MultiInference(::grpc::ClientContext* context, const ::tensorflow::serving::MultiInferenceRequest& request, ::tensorflow::serving::MultiInferenceResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_MultiInference_, context, request, response); } ::grpc::ClientAsyncResponseReader< ::tensorflow::serving::MultiInferenceResponse>* PredictionService::Stub::AsyncMultiInferenceRaw(::grpc::ClientContext* context, const ::tensorflow::serving::MultiInferenceRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::MultiInferenceResponse>::Create(channel_.get(), cq, rpcmethod_MultiInference_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::tensorflow::serving::MultiInferenceResponse>* PredictionService::Stub::PrepareAsyncMultiInferenceRaw(::grpc::ClientContext* context, const ::tensorflow::serving::MultiInferenceRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::MultiInferenceResponse>::Create(channel_.get(), cq, rpcmethod_MultiInference_, context, request, false); } ::grpc::Status PredictionService::Stub::GetModelMetadata(::grpc::ClientContext* context, const ::tensorflow::serving::GetModelMetadataRequest& request, ::tensorflow::serving::GetModelMetadataResponse* response) { return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_GetModelMetadata_, context, request, response); } ::grpc::ClientAsyncResponseReader< ::tensorflow::serving::GetModelMetadataResponse>* PredictionService::Stub::AsyncGetModelMetadataRaw(::grpc::ClientContext* context, const ::tensorflow::serving::GetModelMetadataRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::GetModelMetadataResponse>::Create(channel_.get(), cq, rpcmethod_GetModelMetadata_, context, request, true); } ::grpc::ClientAsyncResponseReader< ::tensorflow::serving::GetModelMetadataResponse>* PredictionService::Stub::PrepareAsyncGetModelMetadataRaw(::grpc::ClientContext* context, const ::tensorflow::serving::GetModelMetadataRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderFactory< ::tensorflow::serving::GetModelMetadataResponse>::Create(channel_.get(), cq, rpcmethod_GetModelMetadata_, context, request, false); } PredictionService::Service::Service() { AddMethod(new ::grpc::internal::RpcServiceMethod( PredictionService_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< PredictionService::Service, ::tensorflow::serving::ClassificationRequest, ::tensorflow::serving::ClassificationResponse>( std::mem_fn(&PredictionService::Service::Classify), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( PredictionService_method_names[1], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< PredictionService::Service, ::tensorflow::serving::RegressionRequest, ::tensorflow::serving::RegressionResponse>( std::mem_fn(&PredictionService::Service::Regress), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( PredictionService_method_names[2], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< PredictionService::Service, ::tensorflow::serving::PredictRequest, ::tensorflow::serving::PredictResponse>( std::mem_fn(&PredictionService::Service::Predict), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( PredictionService_method_names[3], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< PredictionService::Service, ::tensorflow::serving::MultiInferenceRequest, ::tensorflow::serving::MultiInferenceResponse>( std::mem_fn(&PredictionService::Service::MultiInference), this))); AddMethod(new ::grpc::internal::RpcServiceMethod( PredictionService_method_names[4], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< PredictionService::Service, ::tensorflow::serving::GetModelMetadataRequest, ::tensorflow::serving::GetModelMetadataResponse>( std::mem_fn(&PredictionService::Service::GetModelMetadata), this))); } PredictionService::Service::~Service() { } ::grpc::Status PredictionService::Service::Classify(::grpc::ServerContext* context, const ::tensorflow::serving::ClassificationRequest* request, ::tensorflow::serving::ClassificationResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status PredictionService::Service::Regress(::grpc::ServerContext* context, const ::tensorflow::serving::RegressionRequest* request, ::tensorflow::serving::RegressionResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status PredictionService::Service::Predict(::grpc::ServerContext* context, const ::tensorflow::serving::PredictRequest* request, ::tensorflow::serving::PredictResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status PredictionService::Service::MultiInference(::grpc::ServerContext* context, const ::tensorflow::serving::MultiInferenceRequest* request, ::tensorflow::serving::MultiInferenceResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status PredictionService::Service::GetModelMetadata(::grpc::ServerContext* context, const ::tensorflow::serving::GetModelMetadataRequest* request, ::tensorflow::serving::GetModelMetadataResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } } // namespace tensorflow } // namespace serving
67.906433
267
0.775319
wwongkamjan
99cf8f6cd7dd98f2362504cfdddc4dd92cad37df
13,045
cpp
C++
src/IsingMCMC.cpp
liyufan1994/CS205ParallelCipher
121e800dad149c7019d80d8d6fc4e0490b9df803
[ "MIT" ]
null
null
null
src/IsingMCMC.cpp
liyufan1994/CS205ParallelCipher
121e800dad149c7019d80d8d6fc4e0490b9df803
[ "MIT" ]
null
null
null
src/IsingMCMC.cpp
liyufan1994/CS205ParallelCipher
121e800dad149c7019d80d8d6fc4e0490b9df803
[ "MIT" ]
null
null
null
#include <iostream> #include <math.h> #include <random> #include <vector> #include <fstream> #include <map> #include <string> #include <algorithm> #include <mpi.h> #include <omp.h> #include "Randomize.h" #include "Ising.h" #include "ArrayUtilities.h" /* * * This function runs totalS number of parallel chains each on a temperature level defined in temps. * Each MPI process is responsible for 1 or more chains in the pool. * Each chain is run iterNum number of iterations where each iteration consists of T number of steps * The chains communicates via MPI send and receive. temperedChains outputs result in the result array. * * Function Arguments: * iterNum: number of iterations * totalS: total number of parallel chains (each core may run more than one chain) * Nd: dimension of state space * T: number of steps each iteration * rank: rank of current MPI process * size: number of concurrent MPI processes * * */ void temperedChainsIsing(int iterNum, int totalS, int Nd, int T, double *temps, int rank, int size, int kernel) { // Each MPI process is assigned S chains to run int S=totalS/size; if (rank==size-1) { S=totalS/size+totalS%size; } // Each MPI process stores results in partialresult array of S columns and iterNum rows int **partialresult; create2Dmemory(partialresult,iterNum,S); // Each MPI process has a different seed srand(unsigned(time(0))+rank); // Each chain creates a new starting state from uniform sampling int ***xs; create3Dmemory(xs, S, Nd,Nd); for (int chains=0; chains<S; ++chains) { for (int i=0; i<Nd; ++i) { for (int j=0;j<Nd; ++j) { if (unifrnd(0,1)<0.5) xs[chains][i][j]=1; else{ xs[chains][i][j]=0; } } } } /* Define variables used in the loop */ int exchangetimes=0; // total number of exchange that occur double originallog; // store value of log target in prev step double proplog; // store value of log target of the proposal int glbc1; // global idx of chain 1 to exchange int glbc2; // global idx of chain 2 to exchange int rank1; // processor that runs chain 1 int rank2; // processor that runs chain 2 int c1; // local idx of chain 1 to exchange int c2; // local idx of chain 2 to exchange double coin; // store value of coin toss double accpt; // store value of acceptance ratio for (int iter=0; iter<iterNum; ++iter){ for (int chains=0; chains<S; ++chains) { if (kernel==0) { oneChainIsing(xs[chains], T, Nd, temps[chains+rank*S]); } else { oneChainIsingChess(xs[chains], T, Nd, temps[chains+rank*S]); } partialresult[iter][chains]=t(xs[chains],Nd); } // Global index of the two chain to exchange positions glbc1=iterNum % totalS; glbc2=(iterNum+1) % totalS; if (totalS==1) { glbc1=0; glbc2=0; } // Which processors these two indexes belong to rank1=glbc1/S; rank2=glbc2/S; // Current process is not involved in exchange if ((rank1!=rank)&&(rank2!=rank)) { continue; } // Both indexes to exchange belong to current process else if (rank1==rank2){ // Convert global indexes to local indexes c1=glbc1%S; c2=glbc2%S; // Compute acceptance ratio originallog=logtargetIsing(xs[c1],Nd,temps[c1])+logtargetIsing(xs[c2],Nd,temps[c2]); proplog=logtargetIsing(xs[c1],Nd,temps[c2])+logtargetIsing(xs[c2],Nd,temps[c1]); accpt=exp(proplog-originallog); // Determine if accept by toss a random coin coin=unifrnd(0,1); if (coin<accpt){ // We indeed accept the proposal int **imp; imp=xs[c1]; xs[c1]=xs[c2]; xs[c2]=imp; exchangetimes+=1; } } // Indexes to exchange occur on two different processes else { if (rank == rank1){ int c1=glbc1%S; double logtgtc1c1=logtargetIsing(xs[c1],Nd,temps[glbc1]); double logtgtc1c2=logtargetIsing(xs[c1],Nd,temps[glbc2]); int **xsc2; create2Dmemory(xsc2,Nd,Nd); int xsc21D[Nd*Nd]; MPI_Recv(xsc21D,Nd*Nd,MPI_INT,rank2,0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); conv1Dto2D(xsc21D, xsc2, Nd, Nd); double logtgtc2c2=logtargetIsing(xsc2,Nd,temps[glbc2]); double logtgtc2c1=logtargetIsing(xsc2,Nd,temps[glbc1]); originallog=logtgtc1c1+logtgtc2c2; proplog=logtgtc1c2+logtgtc2c1; accpt=exp(proplog-originallog); coin=unifrnd(0,1); if (coin<accpt){ // We indeed accept the proposal, notify the other chain int accptstatus=1; MPI_Send(&accptstatus,1,MPI_INT,rank2,0,MPI_COMM_WORLD); int xsc11D[Nd*Nd]; conv2Dto1D(xs[c1],xsc11D,Nd,Nd); MPI_Send(xsc11D,Nd*Nd,MPI_INT,rank2,0,MPI_COMM_WORLD); deepcopy2Darray(xsc2,xs[c1], Nd, Nd); exchangetimes+=1; } else { int accptstatus=0; MPI_Send(&accptstatus,1,MPI_INT,rank2,0,MPI_COMM_WORLD); } } else { int c2=glbc2%S; int accptstatus; int xsc21D[Nd*Nd]; conv2Dto1D(xs[c2],xsc21D,Nd,Nd); MPI_Send(xsc21D,Nd*Nd,MPI_INT,rank1,0,MPI_COMM_WORLD); MPI_Recv(&accptstatus,1,MPI_INT,rank1,0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); if (accptstatus==1) { int **xsc1; create2Dmemory(xsc1,Nd,Nd); int xsc11D[Nd*Nd]; MPI_Recv(xsc11D,Nd*Nd,MPI_INT,rank1,0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); conv1Dto2D(xsc11D,xsc1,Nd,Nd); deepcopy2Darray(xsc1,xs[c2], Nd,Nd); exchangetimes+=1; } } } } print2Darray(partialresult,iterNum,S,"output"+std::to_string(rank)+".txt"); free3Dmemory(xs, S, Nd,Nd); } /* * This function takes the Markov chain T steps forward. The parallelization used is * the strip partitioning. * * Function Argument: * x: pointer to the starting state; * T: number fo steps * Nd: side length of the Ising lattice * temp: temperature of the Ising lattice * * */ void oneChainIsing(int **x, int T, int Nd, double temp) { #pragma omp parallel shared(x) { //int numthreads=2; //for (int threadid=0; threadid<numthreads; ++threadid) //{ for (int t=0; t<T; ++t) { int threadid = omp_get_thread_num(); int numthreads = omp_get_num_threads(); if (Nd/numthreads<=1) { throw "Too many threads! One thread must have at least 2 rows"; } // Partition the matrix in strips int low = Nd*threadid/numthreads; int high=Nd*(threadid+1)/numthreads; if (high>Nd) { high=Nd; } // The schedule now is to update everything except the last row for(int i=low; i<high-1; ++i) { for(int j=0; j<Nd; ++j) { int leftj=j-1; int rightj=j+1; if (j==0) { leftj=Nd-1; } else if (j==(Nd-1)) { rightj=0; } int upi=i-1; int downi=i+1; if (i==0) { upi=Nd-1; }else if (i==Nd-1) { downi=0; } double s=x[upi][j]+x[downi][j]+x[i][leftj]+x[i][rightj]; double cond_p=exp(temp*s)/(exp(temp*s)+exp(-temp*s)); if (unifrnd(0,1)<cond_p) { x[i][j]=1; } else{ x[i][j]=0; } } } // put a barrier here go ensure all threads update the last row on new values from neighboring regions #pragma omp barrier int i=high-1; for (int j=0;j<Nd;++j) { int leftj=j-1; int rightj=j+1; if (j==0) { leftj=Nd-1; } else if (j==(Nd-1)) { rightj=0; } int upi=i-1; int downi=i+1; if (i==0) { upi=Nd-1; }else if (i==Nd-1) { downi=0; } double s=x[upi][j]+x[downi][j]+x[i][leftj]+x[i][rightj]; double cond_p=exp(temp*s)/(exp(temp*s)+exp(-temp*s)); if (unifrnd(0,1)<cond_p) { x[i][j]=1; } else{ x[i][j]=0; } } // Put a barrier here to ensure iteration is synchronized each step #pragma omp barrier } //} } } void oneChainIsingChess(int **x, int T, int Nd, double temp) { // We specify that the chess board starts first row with white // Update all white cells #pragma omp parallel for for (int i=0; i<Nd; ++i) { int jst=0; if (i%2==1) { jst=1; } int upi=i-1; int downi=i+1; if (i==0) { upi=Nd-1; }else if (i==Nd-1) { downi=0; } for (int j=jst; j<Nd; j=j+2) { int leftj=j-1; int rightj=j+1; if (j==0) { leftj=Nd-1; } else if (j==(Nd-1)) { rightj=0; } double s=x[upi][j]+x[downi][j]+x[i][leftj]+x[i][rightj]; double cond_p=exp(temp*s)/(exp(temp*s)+exp(-temp*s)); if (unifrnd(0,1)<cond_p) { x[i][j]=1; } else{ x[i][j]=0; } } } // Update all black cells #pragma omp parallel for for (int i=0; i<Nd; ++i) { int jst=1; if (i%2==1) { jst=0; } int upi=i-1; int downi=i+1; if (i==0) { upi=Nd-1; }else if (i==Nd-1) { downi=0; } for (int j=jst; j<Nd; j=j+2) { int leftj=j-1; int rightj=j+1; if (j==0) { leftj=Nd-1; } else if (j==(Nd-1)) { rightj=0; } double s=x[upi][j]+x[downi][j]+x[i][leftj]+x[i][rightj]; double cond_p=exp(temp*s)/(exp(temp*s)+exp(-temp*s)); if (unifrnd(0,1)<cond_p) { x[i][j]=1; } else{ x[i][j]=0; } } } } double t(int **x, int Nd) { double result=0; #pragma omp parallel for reduction(+:result) for(int i=0; i<Nd; ++i) { for(int j=0; j<Nd; ++j) { int leftj=j-1; int rightj=j+1; if (j==0) { leftj=Nd-1; } else if (j==(Nd-1)) { rightj=0; } int upi=i-1; int downi=i+1; if (i==0) { upi=Nd-1; }else if (i==Nd-1) { downi=0; } result+=x[i][j]*(x[upi][j]+x[downi][j]+x[i][leftj]+x[i][rightj]); } } return 0.5*result; } double logtargetIsing(int **x, int Nd,double temp) { double result=0; result=t(x,Nd); result=exp(temp*result); return result; }
26.247485
118
0.448601
liyufan1994
99d1c09b18dc0668ca38708dca14ad70117ef015
15,206
cpp
C++
Carthage/Checkouts/realm-cocoa/Realm/ObjectStore/tests/sync/permission.cpp
adventam10/Pokedex
26975844cd1ef74878064a92161470b1bbc10f84
[ "MIT" ]
null
null
null
Carthage/Checkouts/realm-cocoa/Realm/ObjectStore/tests/sync/permission.cpp
adventam10/Pokedex
26975844cd1ef74878064a92161470b1bbc10f84
[ "MIT" ]
null
null
null
Carthage/Checkouts/realm-cocoa/Realm/ObjectStore/tests/sync/permission.cpp
adventam10/Pokedex
26975844cd1ef74878064a92161470b1bbc10f84
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////// // // Copyright 2017 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #include "object.hpp" #include "impl/object_accessor_impl.hpp" #include "object_schema.hpp" #include "object_store.hpp" #include "property.hpp" #include "schema.hpp" #include "sync/sync_permission.hpp" #include "sync_test_utils.hpp" #include "util/test_file.hpp" #include "util/test_utils.hpp" #include <unistd.h> using namespace realm; TEST_CASE("`Permission` class", "[sync]") { SECTION("paths_are_equivalent() properly returns true") { // Identical paths and identical users for tilde-paths. CHECK(Permission::paths_are_equivalent("/~/foo", "/~/foo", "user1", "user1")); // Identical paths for non-tilde paths. CHECK(Permission::paths_are_equivalent("/user2/foo", "/user2/foo", "user1", "user1")); CHECK(Permission::paths_are_equivalent("/user2/foo", "/user2/foo", "user1", "user2")); // First path can be turned into second path. CHECK(Permission::paths_are_equivalent("/~/foo", "/user1/foo", "user1", "user2")); // Second path can be turned into first path. CHECK(Permission::paths_are_equivalent("/user1/foo", "/~/foo", "user2", "user1")); } SECTION("paths_are_equivalent() properly returns false") { // Different tilde-paths. CHECK(!Permission::paths_are_equivalent("/~/foo", "/~/bar", "user1", "user1")); // Different non-tilde paths. CHECK(!Permission::paths_are_equivalent("/user1/foo", "/user2/bar", "user1", "user1")); // Identical paths and different users for tilde-paths. CHECK(!Permission::paths_are_equivalent("/~/foo", "/~/foo", "user1", "user2")); // First path cannot be turned into second path. CHECK(!Permission::paths_are_equivalent("/~/foo", "/user1/foo", "user2", "user2")); // Second path cannot be turned into first path. CHECK(!Permission::paths_are_equivalent("/user1/foo", "/~/foo", "user2", "user2")); } } constexpr const char* result_sets_type_name = "__ResultSets"; static void update_schema(Group& group, Property matches_property) { Schema current_schema; std::string table_name = ObjectStore::table_name_for_object_type(result_sets_type_name); if (group.has_table(table_name)) current_schema = {ObjectSchema{group, result_sets_type_name}}; Schema desired_schema({ ObjectSchema(result_sets_type_name, { {"name", PropertyType::String}, {"matches_property", PropertyType::String}, {"query", PropertyType::String}, {"status", PropertyType::Int}, {"error_message", PropertyType::String}, {"query_parse_counter", PropertyType::Int}, std::move(matches_property) }) }); auto required_changes = current_schema.compare(desired_schema); if (!required_changes.empty()) ObjectStore::apply_additive_changes(group, required_changes, true); } static void subscribe_to_all(std::shared_ptr<Realm> const& r) { using namespace std::string_literals; r->begin_transaction(); update_schema(r->read_group(), Property("object_matches", PropertyType::Object|PropertyType::Array, "object")); ObjectSchema schema{r->read_group(), result_sets_type_name}; CppContext context; auto obj = Object::create<util::Any>(context, r, schema, AnyDict{ {"name", ""s}, {"matches_property", "object_matches"s}, {"query", "TRUEPREDICATE"s}, {"status", int64_t(0)}, {"error_message", ""s}, {"query_parse_counter", int64_t(0)}, {"matches_count", int64_t(0)}, {"created_at", Timestamp(0, 0)}, {"updated_at", Timestamp(0, 0)}, {"expires_at", Timestamp()}, {"time_to_live", {}}, }); r->commit_transaction(); while (any_cast<int64_t>(obj.get_property_value<util::Any>(context, "status")) != 1) { wait_for_download(*r); r->refresh(); } } TEST_CASE("Object-level Permissions") { TestSyncManager init_sync_manager; SyncServer server{StartImmediately{false}}; SyncTestFile config{server, "default"}; config.cache = false; config.automatic_change_notifications = false; config.schema = Schema{ {"object", { {"value", PropertyType::Int} }}, }; auto create_object = [](auto&& r) -> Table& { r->begin_transaction(); auto& table = *r->read_group().get_table("class_object"); sync::create_object(r->read_group(), table); r->commit_transaction(); return table; }; SECTION("Non-sync Realms") { SECTION("permit all operations") { config.sync_config = nullptr; auto r = Realm::get_shared_realm(config); auto& table = create_object(r); CHECK(r->get_privileges() == ComputedPrivileges::AllRealm); CHECK(r->get_privileges("object") == ComputedPrivileges::AllClass); CHECK(r->get_privileges(table[0]) == ComputedPrivileges::AllObject); } } SECTION("Full sync Realms") { SECTION("permit all operations") { auto r = Realm::get_shared_realm(config); auto& table = create_object(r); CHECK(r->get_privileges() == ComputedPrivileges::AllRealm); CHECK(r->get_privileges("object") == ComputedPrivileges::AllClass); CHECK(r->get_privileges(table[0]) == ComputedPrivileges::AllObject); } } SECTION("Query-based sync Realms") { SECTION("permit all operations prior to first sync") { config.sync_config->is_partial = true; auto r = Realm::get_shared_realm(config); auto& table = create_object(r); CHECK(r->get_privileges() == ComputedPrivileges::AllRealm); CHECK(r->get_privileges("object") == ComputedPrivileges::AllClass); CHECK(r->get_privileges(table[0]) == ComputedPrivileges::AllObject); } SECTION("continue to permit all operations after syncing locally-created data") { config.sync_config->is_partial = true; auto r = Realm::get_shared_realm(config); auto& table = create_object(r); server.start(); wait_for_upload(*r); wait_for_download(*r); CHECK(r->get_privileges() == ComputedPrivileges::AllRealm); CHECK(r->get_privileges("object") == ComputedPrivileges::AllClass); CHECK(r->get_privileges(table[0]) == ComputedPrivileges::AllObject); } SECTION("permit all operations on a downloaded Realm created as a Full Realm when logged in as an admin") { server.start(); { auto r = Realm::get_shared_realm(config); create_object(r); wait_for_upload(*r); } SyncTestFile config2{server, "default", true}; config2.automatic_change_notifications = false; auto r = Realm::get_shared_realm(config2); wait_for_download(*r); subscribe_to_all(r); CHECK(r->get_privileges() == ComputedPrivileges::AllRealm); CHECK(r->get_privileges("object") == ComputedPrivileges::AllClass); CHECK(r->get_privileges(r->read_group().get_table("class_object")->get(0)) == ComputedPrivileges::AllObject); } SECTION("permit nothing on pre-existing types in a downloaded Realm created as a Full Realm") { server.start(); { auto r = Realm::get_shared_realm(config); create_object(r); wait_for_upload(*r); } SyncTestFile config2{server, "default", true}; config2.automatic_change_notifications = false; config2.sync_config->user->set_is_admin(false); auto r = Realm::get_shared_realm(config2); wait_for_download(*r); subscribe_to_all(r); // should have no objects as we don't have read permission CHECK(r->read_group().get_table("class_object")->size() == 0); CHECK(r->get_privileges() == ComputedPrivileges::AllRealm); CHECK(r->get_privileges("object") == ComputedPrivileges::None); } SECTION("automatically add newly created users to 'everyone'") { using namespace std::string_literals; config.schema = Schema{ {"__User", { {"id", PropertyType::String, Property::IsPrimary{true}} }}, }; config.sync_config->is_partial = true; auto r = Realm::get_shared_realm(config); r->begin_transaction(); CppContext c; auto user = Object::create<util::Any>(c, r, *r->schema().find("__User"), AnyDict{{"id", "test user"s}}); auto role_table = r->read_group().get_table("class___Role"); REQUIRE(role_table); size_t ndx = role_table->find_first_string(role_table->get_column_index("name"), "everyone"); REQUIRE(ndx != npos); REQUIRE(role_table->get_linklist(role_table->get_column_index("members"), ndx)->find(user.row().get_index()) != npos); r->commit_transaction(); } SECTION("automatically create private roles for newly-created users") { using namespace std::string_literals; config.schema = Schema{ {"__User", { {"id", PropertyType::String, Property::IsPrimary{true}} }}, }; config.sync_config->is_partial = true; auto r = Realm::get_shared_realm(config); r->begin_transaction(); auto validate_user_role = [](const Object& user) { auto user_table = user.row().get_table(); REQUIRE(user_table); size_t ndx = user.row().get_link(user_table->get_column_index("role")); REQUIRE(ndx != npos); auto role_table = user.realm()->read_group().get_table("class___Role"); REQUIRE(role_table); auto members = role_table->get_linklist(role_table->get_column_index("members"), ndx); REQUIRE(members->size() == 1); REQUIRE(members->find(user.row().get_index()) != npos); }; SECTION("logged-in user") { auto user_table = r->read_group().get_table("class___User"); REQUIRE(user_table); REQUIRE(user_table->size() == 1); validate_user_role(Object(r, "__User", 0)); } SECTION("manually created user") { CppContext c; auto user = Object::create<util::Any>(c, r, *r->schema().find("__User"), AnyDict{{"id", "test user"s}}); validate_user_role(user); } r->commit_transaction(); } } SECTION("schema change error reporting") { config.sync_config->is_partial = true; // Create the Realm with an admin user server.start(); { auto r = Realm::get_shared_realm(config); create_object(r); // FIXME: required due to https://github.com/realm/realm-sync/issues/2071 wait_for_upload(*r); wait_for_download(*r); // Revoke modifySchema permission for all users r->begin_transaction(); TableRef permission_table = r->read_group().get_table("class___Permission"); size_t col = permission_table->get_column_index("canModifySchema"); for (size_t i = 0; i < permission_table->size(); ++i) permission_table->set_bool(col, i, false); r->commit_transaction(); wait_for_upload(*r); } SyncTestFile nonadmin{server, "default", true, "user2"}; nonadmin.automatic_change_notifications = false; nonadmin.sync_config->user->set_is_admin(false); auto bind_session_handler = nonadmin.sync_config->bind_session_handler; nonadmin.sync_config->bind_session_handler = [](auto, auto, auto) { }; auto log_in = [&](auto& realm) { auto session = SyncManager::shared().get_session(nonadmin.path, *nonadmin.sync_config); bind_session_handler("", *nonadmin.sync_config, session); wait_for_upload(realm); wait_for_download(realm); }; SECTION("reverted column insertion") { nonadmin.schema = Schema{ {"object", { {"value", PropertyType::Int}, {"value 2", PropertyType::Int} }}, }; auto r = Realm::get_shared_realm(nonadmin); r->invalidate(); SECTION("no active read transaction") { log_in(*r); REQUIRE_THROWS_WITH(r->read_group(), Catch::Matchers::Contains("Property 'object.value 2' has been removed.")); } SECTION("notify()") { r->read_group(); log_in(*r); REQUIRE_THROWS_WITH(r->notify(), Catch::Matchers::Contains("Property 'object.value 2' has been removed.")); } SECTION("refresh()") { r->read_group(); log_in(*r); REQUIRE_THROWS_WITH(r->refresh(), Catch::Matchers::Contains("Property 'object.value 2' has been removed.")); } SECTION("begin_transaction()") { r->read_group(); log_in(*r); REQUIRE_THROWS_WITH(r->begin_transaction(), Catch::Matchers::Contains("Property 'object.value 2' has been removed.")); } } SECTION("reverted table insertion") { nonadmin.schema = Schema{ {"object", { {"value", PropertyType::Int}, }}, {"object 2", { {"value", PropertyType::Int}, }}, }; auto r = Realm::get_shared_realm(nonadmin); r->read_group(); log_in(*r); REQUIRE_THROWS_WITH(r->notify(), Catch::Matchers::Contains("Class 'object 2' has been removed.")); } } }
39.496104
130
0.573721
adventam10
99d35cf25589afde95af64647c8d75a1378f4b5f
907
cpp
C++
LeetCode/897_Increasing_Order_Search_Tree.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
null
null
null
LeetCode/897_Increasing_Order_Search_Tree.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
null
null
null
LeetCode/897_Increasing_Order_Search_Tree.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> v; void dfs(TreeNode* root) { if (root->left) { dfs(root->left); } v.push_back(root->val); if (root->right) { dfs(root->right); } } TreeNode* increasingBST(TreeNode* root) { dfs(root); TreeNode* node = new TreeNode(v[0]); TreeNode* s = node; for (int i = 1; i < v.size(); i++) { node->right = new TreeNode(v[i]); node = node->right; } return s; } };
26.676471
93
0.496141
sungmen
99d3be8c9bf582acbefe0fb98fc8bac2a2e749b1
12,451
cpp
C++
5_System_Processes.cpp
yangminglong/FUGU-ARDUINO-MPPT-FIRMWARE
1a378a2248a636569f5e6a19b14b9bd3b34f4106
[ "CC0-1.0" ]
null
null
null
5_System_Processes.cpp
yangminglong/FUGU-ARDUINO-MPPT-FIRMWARE
1a378a2248a636569f5e6a19b14b9bd3b34f4106
[ "CC0-1.0" ]
null
null
null
5_System_Processes.cpp
yangminglong/FUGU-ARDUINO-MPPT-FIRMWARE
1a378a2248a636569f5e6a19b14b9bd3b34f4106
[ "CC0-1.0" ]
null
null
null
#include "5_System_Processes.h" #include "defines.h" #include <EEPROM.h> #include "Preferences.h" #include "nvs.h" #include "nvs_flash.h" #include "esp32-hal-log.h" const char * my_nvs_errors[] = { "OTHER", "NOT_INITIALIZED", "NOT_FOUND", "TYPE_MISMATCH", "READ_ONLY", "NOT_ENOUGH_SPACE", "INVALID_NAME", "INVALID_HANDLE", "REMOVE_FAILED", "KEY_TOO_LONG", "PAGE_FULL", "INVALID_STATE", "INVALID_LENGTH"}; #define my_nvs_error(e) (((e)>ESP_ERR_NVS_BASE)? my_nvs_errors[(e)&~(ESP_ERR_NVS_BASE)]: my_nvs_errors[0]) class MyPreferences : public Preferences { public: MyPreferences() : Preferences() {} size_t myPutChar(const char* key, int8_t value){ if(!_started || !key || _readOnly){ return 0; } esp_err_t err = nvs_set_i8(_handle, key, value); if(err){ log_e("nvs_set_i8 fail: %s %s", key, my_nvs_error(err)); return 0; } return 1; } size_t myPutUChar(const char* key, uint8_t value){ if(!_started || !key || _readOnly){ return 0; } esp_err_t err = nvs_set_u8(_handle, key, value); if(err){ log_e("nvs_set_u8 fail: %s %s", key, my_nvs_error(err)); return 0; } return 1; } size_t myPutShort(const char* key, int16_t value){ if(!_started || !key || _readOnly){ return 0; } esp_err_t err = nvs_set_i16(_handle, key, value); if(err){ log_e("nvs_set_i16 fail: %s %s", key, my_nvs_error(err)); return 0; } return 2; } size_t myPutUShort(const char* key, uint16_t value){ if(!_started || !key || _readOnly){ return 0; } esp_err_t err = nvs_set_u16(_handle, key, value); if(err){ log_e("nvs_set_u16 fail: %s %s", key, my_nvs_error(err)); return 0; } return 2; } size_t myPutInt(const char* key, int32_t value){ if(!_started || !key || _readOnly){ return 0; } esp_err_t err = nvs_set_i32(_handle, key, value); if(err){ log_e("nvs_set_i32 fail: %s %s", key, my_nvs_error(err)); return 0; } return 4; } size_t myPutUInt(const char* key, uint32_t value){ if(!_started || !key || _readOnly){ return 0; } esp_err_t err = nvs_set_u32(_handle, key, value); if(err){ log_e("nvs_set_u32 fail: %s %s", key, my_nvs_error(err)); return 0; } return 4; } size_t myPutLong(const char* key, int32_t value){ return myPutInt(key, value); } size_t myPutULong(const char* key, uint32_t value){ return myPutUInt(key, value); } size_t myPutLong64(const char* key, int64_t value){ if(!_started || !key || _readOnly){ return 0; } esp_err_t err = nvs_set_i64(_handle, key, value); if(err){ log_e("nvs_set_i64 fail: %s %s", key, my_nvs_error(err)); return 0; } return 8; } size_t myPutULong64(const char* key, uint64_t value){ if(!_started || !key || _readOnly){ return 0; } esp_err_t err = nvs_set_u64(_handle, key, value); if(err){ log_e("nvs_set_u64 fail: %s %s", key, my_nvs_error(err)); return 0; } return 8; } size_t myPutFloat(const char* key, const float_t value){ return myPutBytes(key, (void*)&value, sizeof(float_t)); } size_t myPutDouble(const char* key, const double_t value){ return myPutBytes(key, (void*)&value, sizeof(double_t)); } size_t myPutBool(const char* key, const bool value){ return myPutUChar(key, (uint8_t) (value ? 1 : 0)); } size_t myPutString(const char* key, const char* value){ if(!_started || !key || !value || _readOnly){ return 0; } esp_err_t err = nvs_set_str(_handle, key, value); if(err){ log_e("nvs_set_str fail: %s %s", key, my_nvs_error(err)); return 0; } return strlen(value); } size_t myPutString(const char* key, const String value){ return myPutString(key, value.c_str()); } size_t myPutBytes(const char* key, const void* value, size_t len){ if(!_started || !key || !value || !len || _readOnly){ return 0; } esp_err_t err = nvs_set_blob(_handle, key, value, len); if(err){ log_e("nvs_set_blob fail: %s %s", key, my_nvs_error(err)); return 0; } return len; } void myCommit() { esp_err_t err = nvs_commit(_handle); if(err){ log_e("nvs_commit fail: %s", my_nvs_error(err)); return ; } } }; void resetVariables(){ secondsElapsed = 0; energySavings = 0; daysRunning = 0; timeOn = 0; } void System_Processes(){ ///////////////// FAN COOLING ///////////////// if(enableFan==true){ if(enableDynamicCooling==false){ //STATIC PWM COOLING MODE (2-PIN FAN - no need for hysteresis, temp data only refreshes after 'avgCountTS' or every 500 loop cycles) if(overrideFan==true){fanStatus=true;} //Force on fan else if(temperature>=temperatureFan){fanStatus=1;} //Turn on fan when set fan temp reached else if(temperature<temperatureFan){fanStatus=0;} //Turn off fan when set fan temp reached digitalWrite(FAN,fanStatus); //Send a digital signal to the fan MOSFET } else{} //DYNAMIC PWM COOLING MODE (3-PIN FAN - coming soon) } else{digitalWrite(FAN,LOW);} //Fan Disabled //////////// LOOP TIME STOPWATCH //////////// loopTimeStart = micros(); //Record Start Time loopTime = (loopTimeStart-loopTimeEnd)/1000.000; //Compute Loop Cycle Speed (mS) loopTimeEnd = micros(); //Record End Time ///////////// AUTO DATA RESET ///////////// if(telemCounterReset==0){} //Never Reset else if(telemCounterReset==1 && daysRunning>1) { resetVariables(); } //Daily Reset else if(telemCounterReset==2 && daysRunning>7) { resetVariables(); } //Weekly Reset else if(telemCounterReset==3 && daysRunning>30) { resetVariables(); } //Monthly Reset else if(telemCounterReset==4 && daysRunning>365){ resetVariables(); } //Yearly Reset ///////////// LOW POWER MODE ///////////// if(lowPowerMode==1){} else{} } MyPreferences prefe; void setupPreferences() { prefe.begin("MPPT"); } void loadSettings() { flashMemLoad = prefe.getBool("flashMemLoad", 1); MPPT_Mode = prefe.getBool("MPPT_Mode", 1); output_Mode = prefe.getBool("output_Mode", 1); enableFan = prefe.getBool("enableFan", 1); enableWiFi = prefe.getBool("enableWiFi", 1); temperatureFan = prefe.getInt("temperatureFan", 60); temperatureMax = prefe.getInt("temperatureMax", 90); backlightSleepMode = prefe.getInt("backlightSleepMode", 0); voltageBatteryMax = prefe.getFloat("voltageBatteryMax", 25.5); voltageBatteryMin = prefe.getFloat("voltageBatteryMin", 20); currentChargingMax = prefe.getFloat("currentChargingMax", 50); // MPPT_Mode = EEPROM.read(0); // Load saved charging mode setting // output_Mode = EEPROM.read(12); // Load saved charging mode setting // voltageBatteryMax = EEPROM.read(1)+(EEPROM.read(2)*.01); // Load saved maximum battery voltage setting // voltageBatteryMin = EEPROM.read(3)+(EEPROM.read(4)*.01); // Load saved minimum battery voltage setting // currentChargingMax = EEPROM.read(5)+(EEPROM.read(6)*.01); // Load saved charging current setting // enableFan = EEPROM.read(7); // Load saved fan enable settings // temperatureFan = EEPROM.read(8); // Load saved fan temperature settings // temperatureMax = EEPROM.read(9); // Load saved shutdown temperature settings // enableWiFi = EEPROM.read(10); // Load saved WiFi enable settings // flashMemLoad = EEPROM.read(11); // Load saved flash memory autoload feature // backlightSleepMode = EEPROM.read(13); // Load saved lcd backlight sleep timer } void saveSettings() { prefe.myPutBool("MPPT_Mode", MPPT_Mode); prefe.myPutBool("output_Mode", output_Mode); prefe.myPutBool("enableFan", enableFan); prefe.myPutBool("enableWiFi", enableWiFi); prefe.myPutInt("temperatureFan", temperatureFan); prefe.myPutInt("temperatureMax", temperatureMax); prefe.myPutInt("backlightSleepMode", backlightSleepMode); prefe.myPutFloat("voltageBatteryMax", voltageBatteryMax); prefe.myPutFloat("voltageBatteryMin", voltageBatteryMin); prefe.myPutFloat("currentChargingMax", currentChargingMax); prefe.myCommit(); // // EEPROM.write(0,MPPT_Mode); //STORE: Algorithm // EEPROM.write(12,output_Mode); //STORE: Charge/PSU Mode Selection // conv1 = voltageBatteryMax*100; //STORE: Maximum Battery Voltage (gets whole number) // conv2 = conv1%100; //STORE: Maximum Battery Voltage (gets decimal number and converts to a whole number) // EEPROM.write(1,voltageBatteryMax); // EEPROM.write(2,conv2); // conv1 = voltageBatteryMin*100; //STORE: Minimum Battery Voltage (gets whole number) // conv2 = conv1%100; //STORE: Minimum Battery Voltage (gets decimal number and converts to a whole number) // EEPROM.write(3,voltageBatteryMin); // EEPROM.write(4,conv2); // conv1 = currentChargingMax*100; //STORE: Charging Current // conv2 = conv1%100; // EEPROM.write(5,currentChargingMax); // EEPROM.write(6,conv2); // EEPROM.write(7,enableFan); //STORE: Fan Enable // EEPROM.write(8,temperatureFan); //STORE: Fan Temp // EEPROM.write(9,temperatureMax); //STORE: Shutdown Temp // EEPROM.write(10,enableWiFi); //STORE: Enable WiFi // //EEPROM.write(11,flashMemLoad); //STORE: Enable autoload (must be excluded from bulk save, uncomment under discretion) // EEPROM.write(13,backlightSleepMode); //STORE: LCD backlight sleep timer // EEPROM.commit(); //Saves setting changes to flash memory } void factoryReset(){ prefe.myPutBool("flashMemLoad", 1); prefe.myPutBool("MPPT_Mode", 1); prefe.myPutBool("output_Mode", 1); prefe.myPutBool("enableFan", 1); prefe.myPutBool("enableWiFi", 1); prefe.myPutInt("temperatureFan", 60); prefe.myPutInt("temperatureMax", 90); prefe.myPutInt("backlightSleepMode", 0); prefe.myPutFloat("voltageBatteryMax", 25.5); prefe.myPutFloat("voltageBatteryMin", 20); prefe.myPutFloat("currentChargingMax", 50); prefe.myCommit(); // EEPROM.write(0,1); //STORE: Charging Algorithm (1 = MPPT Mode) // EEPROM.write(12,1); //STORE: Charger/PSU Mode Selection (1 = Charger Mode) // EEPROM.write(1,12); //STORE: Max Battery Voltage (whole) // EEPROM.write(2,0); //STORE: Max Battery Voltage (decimal) // EEPROM.write(3,9); //STORE: Min Battery Voltage (whole) // EEPROM.write(4,0); //STORE: Min Battery Voltage (decimal) // EEPROM.write(5,30); //STORE: Charging Current (whole) // EEPROM.write(6,0); //STORE: Charging Current (decimal) // EEPROM.write(7,1); //STORE: Fan Enable (Bool) // EEPROM.write(8,60); //STORE: Fan Temp (Integer) // EEPROM.write(9,90); //STORE: Shutdown Temp (Integer) // EEPROM.write(10,1); //STORE: Enable WiFi (Boolean) // EEPROM.write(11,1); //STORE: Enable autoload (on by default) // // EEPROM.write(13,0); //STORE: LCD backlight sleep timer (default: 0 = never) // EEPROM.commit(); loadSettings(); } void saveAutoloadSettings(){ // EEPROM.write(11,flashMemLoad); //STORE: Enable autoload // EEPROM.commit(); //Saves setting changes to flash memory prefe.putBool("flashMemLoad", flashMemLoad); } void initializeFlashAutoload() { if(disableFlashAutoLoad==0){ flashMemLoad = prefe.getBool("flashMemLoad", false); // flashMemLoad = EEPROM.read(11); //Load saved autoload (must be excluded from bulk save, uncomment under discretion) if(flashMemLoad==1){loadSettings();} //Load stored settings from flash memory } }
38.076453
239
0.609188
yangminglong
99d5de8c314b656a1a4c73cee84f77e2ea1fc44d
1,103
cpp
C++
src/invoiceutil.cpp
DNotesCoin/DNotes2.0
5dbf99d34ecd2a939fc5306525c3b197243259ba
[ "MIT" ]
4
2018-05-13T07:40:59.000Z
2019-05-27T20:05:19.000Z
src/invoiceutil.cpp
DNotesCoin/DNotes2.0
5dbf99d34ecd2a939fc5306525c3b197243259ba
[ "MIT" ]
3
2018-05-17T20:31:06.000Z
2019-06-04T14:05:29.000Z
src/invoiceutil.cpp
DNotesCoin/DNotes2.0
5dbf99d34ecd2a939fc5306525c3b197243259ba
[ "MIT" ]
5
2018-01-09T17:54:22.000Z
2018-11-02T14:53:52.000Z
#include "util.h" #include "invoiceutil.h" namespace InvoiceUtil { bool validateInvoiceNumber(std::string input) { int size = input.size(); if(size > 32) { return false; } for(int idx=0; idx < size; ++idx) { int ch = input.at(idx); if(((ch >= '0' && ch<='9') || (ch >= 'a' && ch<='z') || (ch >= 'A' && ch<='Z') || (ch == '-'))) { // Alphanumeric or - } else { return false; } } return true; } void parseInvoiceNumberAndAddress(std::string input, std::string& outAddress, std::string& outInvoiceNumber) { size_t plusIndex = input.find('+'); if(plusIndex == string::npos) { //no + outAddress = input; outInvoiceNumber = ""; } else { //+ outAddress = input.substr(0, plusIndex); outInvoiceNumber = input.substr(plusIndex + 1, input.size()); } } }
22.510204
112
0.426111
DNotesCoin
99d81f202ad5ab104644196d68071adc5887203f
656
cpp
C++
cpp03/ex01/main.cpp
ndeana-21/cpp
98932eab0c1d57a715b6deb76c7a294c1e86f2fd
[ "MIT" ]
null
null
null
cpp03/ex01/main.cpp
ndeana-21/cpp
98932eab0c1d57a715b6deb76c7a294c1e86f2fd
[ "MIT" ]
null
null
null
cpp03/ex01/main.cpp
ndeana-21/cpp
98932eab0c1d57a715b6deb76c7a294c1e86f2fd
[ "MIT" ]
null
null
null
#include "FragTrap.hpp" #include "ScavTrap.hpp" int main() { FragTrap frag_trap; FragTrap R2D2("R2D2"); FragTrap test("BMO"); FragTrap BMO(test); FragTrap test2("C-3PO"); FragTrap C_3PO = test2; frag_trap.rangeAttack("Blue bird"); frag_trap.meleeAttack("Handsome Jack"); frag_trap.takeDamage(42); frag_trap.takeDamage(1); frag_trap.beRepaired(42); frag_trap.takeDamage(200); for (int i=0; i < 5; i++) { BMO.vaulthunter_dot_exe("Jake the Dog"); C_3PO.vaulthunter_dot_exe("Jar Jar Binks"); R2D2.vaulthunter_dot_exe("Yoda"); } ScavTrap scav_trap("Happy"); for (int i=0; i < 5; i++) scav_trap.challengeNewcomer("Jojo"); return 0; }
21.866667
45
0.70122
ndeana-21
99d8a42491a74a0869673477a0ea7f08463d2c6c
4,381
hpp
C++
dakota-6.3.0.Windows.x86/include/Teuchos_Flops.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
null
null
null
dakota-6.3.0.Windows.x86/include/Teuchos_Flops.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
null
null
null
dakota-6.3.0.Windows.x86/include/Teuchos_Flops.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
1
2022-03-18T14:13:14.000Z
2022-03-18T14:13:14.000Z
// @HEADER // *********************************************************************** // // Teuchos: Common Tools Package // Copyright (2004) Sandia Corporation // // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive // license for use of this work by or on behalf of the U.S. Government. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact Michael A. Heroux (maherou@sandia.gov) // // *********************************************************************** // @HEADER // Kris // 07.08.03 -- Move into Teuchos package/namespace #ifndef TEUCHOS_FLOPS_HPP #define TEUCHOS_FLOPS_HPP /*! \file Teuchos_Flops.hpp \brief Object for providing basic support and consistent interfaces for counting/reporting floating-point operations performed in Teuchos computational classes. */ /*! \class Teuchos::Flops \brief The Teuchos Floating Point Operations Class. The Teuchos_Flops class provides basic support and consistent interfaces for counting and reporting floating point operations performed in the Teuchos computational classes. All classes based on the Teuchos::CompObject can count flops by the user creating an Teuchos::Flops object and calling the SetFlopCounter() method for an Teuchos_CompObject. */ namespace Teuchos { class Flops { public: //! @name Constructor/Destructor. //@{ //! Default Constructor. /*! Creates a Flops instance. This instance can be queried for the number of floating point operations performed for the associated \e this object. */ Flops(); //! Copy Constructor. /*! Makes an exact copy of an existing Flops instance. */ Flops(const Flops &flops); //! Destructor. /*! Completely deletes a Flops object. */ virtual ~Flops(); //@} //! @name Accessor methods. //@{ //! Returns the number of floating point operations with \e this object and resets the count. double flops() const { return flops_; } //@} //! @name Reset methods. //@{ //! Resets the number of floating point operations to zero for \e this multi-std::vector. void resetFlops() {flops_ = 0.0;} //@} friend class CompObject; protected: mutable double flops_; //! @name Updating methods. //@{ //! Increment Flop count for \e this object from an int void updateFlops(int addflops) const {flops_ += (double) addflops; } //! Increment Flop count for \e this object from a long int void updateFlops(long int addflops) const {flops_ += (double) addflops; } //! Increment Flop count for \e this object from a double void updateFlops(double addflops) const {flops_ += (double) addflops; } //! Increment Flop count for \e this object from a float void updateFlops(float addflops) const {flops_ += (double) addflops; } //@} private: }; // #include "Teuchos_Flops.cpp" } // namespace Teuchos #endif // end of TEUCHOS_FLOPS_HPP
31.517986
98
0.695275
seakers
99da0b48ecf0c84d690b8233dc02c4d640dde780
3,494
cpp
C++
CodeReview/src/overlays/CodeReviewCommentOverlay.cpp
dimitar-asenov/Envision
1ab5c846fca502b7fe73ae4aff59e8746248446c
[ "BSD-3-Clause" ]
75
2015-01-18T13:29:43.000Z
2022-01-14T08:02:01.000Z
CodeReview/src/overlays/CodeReviewCommentOverlay.cpp
dimitar-asenov/Envision
1ab5c846fca502b7fe73ae4aff59e8746248446c
[ "BSD-3-Clause" ]
364
2015-01-06T10:20:21.000Z
2018-12-17T20:12:28.000Z
CodeReview/src/overlays/CodeReviewCommentOverlay.cpp
dimitar-asenov/Envision
1ab5c846fca502b7fe73ae4aff59e8746248446c
[ "BSD-3-Clause" ]
14
2015-01-09T00:44:24.000Z
2022-02-22T15:01:44.000Z
/*********************************************************************************************************************** ** ** Copyright (c) 2015 ETH Zurich ** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "CodeReviewCommentOverlay.h" #include "VisualizationBase/src/declarative/GridLayoutFormElement.h" #include "VisualizationBase/src/declarative/DeclarativeItem.hpp" #include "VisualizationBase/src/items/Item.h" #include "VisualizationBase/src/VisualizationManager.h" #include "../handlers/HCodeReviewOverlay.h" namespace CodeReview { DEFINE_ITEM_COMMON(CodeReviewCommentOverlay, "item") CodeReviewCommentOverlay::CodeReviewCommentOverlay(Visualization::Item* associatedItem, NodeReviews* nodeReviews, const StyleType* style) : Super{{associatedItem}, style}, nodeReviews_{nodeReviews} { setAcceptedMouseButtons(Qt::AllButtons); setItemCategory(Visualization::Scene::MenuItemCategory); offsetItemLocal_ = QPoint{nodeReviews->offsetX(), nodeReviews->offsetY()}; } void CodeReviewCommentOverlay::updateGeometry(int availableWidth, int availableHeight) { Super::updateGeometry(availableWidth, availableHeight); setPos(associatedItem()->mapToScene(offsetItemLocal_)); setScale(1.0/Visualization::VisualizationManager::instance().mainScene()->mainViewScalingFactor()); } void CodeReviewCommentOverlay::initializeForms() { auto container = (new Visualization::GridLayoutFormElement{}) ->setTopMargin(10) ->put(0, 0, item(&I::nodeReviewsItem_, [](I* v) {return v->nodeReviews_;})); addForm(container); } void CodeReviewCommentOverlay::updateOffsetItemLocal(QPointF scenePos) { offsetItemLocal_ = CodeReviewCommentOverlay::associatedItem()->mapFromScene(scenePos); nodeReviews_->beginModification("edit node"); nodeReviews_->setOffsetX(offsetItemLocal_.x()); nodeReviews_->setOffsetY(offsetItemLocal_.y()); nodeReviews_->endModification(); } }
44.227848
120
0.728105
dimitar-asenov
99dc5f6a79eaab8bcd489fc3fb5da4268b34b113
1,420
cpp
C++
src/ExecuteConfigSection.cpp
babetoduarte/EF5
5e469f288bce82259e85d26a3f30f7dc260547fb
[ "Unlicense" ]
20
2016-09-20T15:19:54.000Z
2021-09-04T21:53:30.000Z
src/ExecuteConfigSection.cpp
chrimerss/EF5
c97ed83ead8fd764f7c94731fd5bf74761a0bb3d
[ "Unlicense" ]
10
2016-09-20T17:13:00.000Z
2022-03-20T12:53:37.000Z
src/ExecuteConfigSection.cpp
chrimerss/EF5
c97ed83ead8fd764f7c94731fd5bf74761a0bb3d
[ "Unlicense" ]
20
2016-12-01T21:41:40.000Z
2021-08-07T06:11:43.000Z
#include "ExecuteConfigSection.h" #include "Messages.h" #include <cstdio> #include <cstring> ExecuteConfigSection *g_executeConfig = NULL; ExecuteConfigSection::ExecuteConfigSection() {} ExecuteConfigSection::~ExecuteConfigSection() {} CONFIG_SEC_RET ExecuteConfigSection::ProcessKeyValue(char *name, char *value) { if (strcasecmp(name, "task") == 0) { TOLOWER(value); std::map<std::string, TaskConfigSection *>::iterator itr = g_taskConfigs.find(value); if (itr == g_taskConfigs.end()) { ERROR_LOGF("Unknown task \"%s\"!", value); return INVALID_RESULT; } tasks.push_back(itr->second); } else if (strcasecmp(name, "ensembletask") == 0) { TOLOWER(value); std::map<std::string, EnsTaskConfigSection *>::iterator itr = g_ensTaskConfigs.find(value); if (itr == g_ensTaskConfigs.end()) { ERROR_LOGF("Unknown ensemble task \"%s\"!", value); return INVALID_RESULT; } ensTasks.push_back(itr->second); } else { return INVALID_RESULT; } return VALID_RESULT; } CONFIG_SEC_RET ExecuteConfigSection::ValidateSection() { if (tasks.size() == 0) { ERROR_LOG("No tasks were defined!"); return INVALID_RESULT; } return VALID_RESULT; } std::vector<TaskConfigSection *> *ExecuteConfigSection::GetTasks() { return &tasks; } std::vector<EnsTaskConfigSection *> *ExecuteConfigSection::GetEnsTasks() { return &ensTasks; }
26.296296
79
0.685211
babetoduarte
99dd784f7e94f145e783decf496e821a74d8fc28
3,990
hpp
C++
src/solvers/gecode/inspectors/dot.hpp
Patstrom/disUnison
94731ad37cefa9dc3b6472de3adea8a8d5f0a44b
[ "BSD-3-Clause" ]
6
2018-03-01T19:12:07.000Z
2018-09-10T15:52:14.000Z
src/solvers/gecode/inspectors/dot.hpp
Patstrom/disUnison
94731ad37cefa9dc3b6472de3adea8a8d5f0a44b
[ "BSD-3-Clause" ]
56
2018-02-26T16:44:15.000Z
2019-02-23T17:07:32.000Z
src/solvers/gecode/inspectors/dot.hpp
Patstrom/disUnison
94731ad37cefa9dc3b6472de3adea8a8d5f0a44b
[ "BSD-3-Clause" ]
null
null
null
/* * Main authors: * Roberto Castaneda Lozano <roberto.castaneda@ri.se> * * This file is part of Unison, see http://unison-code.github.io * * Copyright (c) 2016, RISE SICS AB * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef __DOT__ #define __DOT__ #include <tuple> #include <vector> #include <map> #include <QtGui> #include <graphviz/gvc.h> using namespace std; typedef QString NodeId; typedef tuple<NodeId, NodeId, int> EdgeId; EdgeId edgeId(const NodeId& source, const NodeId& target, int instance = 0); EdgeId edgeId(int source, int target, int instance = 0); #define POSITION(l) (l->pos) #define BB(g) (GD_bb(g)) #define NDNAME(n) (agnameof(n)) #define NDCOORD(n) (ND_coord(n)) #define NDHEIGHT(n) (ND_height(n)) #define NDWIDTH(n) (ND_width(n)) #define EDLABEL(e) (ED_label(e)) #define EDTAILNAME(e) (NDNAME(agtail(e))) #define EDHEADNAME(e) (NDNAME(aghead(e))) #define EDSPLLIST(e) (ED_spl(e)->list) class DotNode { public: NodeId name; QPointF topLeftPos; double width, height; QRectF rect; vector<QRectF> rects; }; class DotEdge { public: EdgeId key; QPointF topLeftPos; double width, height; QPainterPath path; QPainterPath arrow; }; class Dot { public: static const double DPI; static const double DOT2QT; Dot(); ~Dot(); void setGlobalGraphAttribute(const QString &attr, const QString &val); void setGlobalNodeAttribute(const QString &attr, const QString &val); void setGlobalEdgeAttribute(const QString &attr, const QString &val); void insert(const NodeId& name); void insert(const EdgeId& key); void setEdgeAttribute(EdgeId key, const QString &attr, const QString &val); void setNodeSize(const NodeId &name, double w, double h); void setNodeAttribute(const NodeId &name, const QString &attr, const QString &val); void draw(void); void dump(FILE * file); QRectF box() const; vector<DotNode> getNodes() const; vector<DotEdge> getEdges() const; QPainterPath drawArrow(QLineF line) const; private: GVC_t * context; Agraph_t *graph; map<NodeId, Agnode_t*> nodes; map<EdgeId, Agedge_t*> edges; static void gvSet(void *object, QString attr, QString value) { agsafeset(object, const_cast<char *>(qPrintable(attr)), const_cast<char *>(qPrintable(value)), const_cast<char *>(qPrintable(value))); } Agnode_t * gvNode(NodeId node) { return agnode(graph, const_cast<char *>(qPrintable(node)),1); } }; #endif
31.171875
80
0.721053
Patstrom
99dd8a64c549d0787a2576d47c4af8c629f25be4
3,422
cpp
C++
concurrencpp/src/threads/thread_group.cpp
HungMingWu/concurrencpp
eb4ed8fb6cd8510925738868cf57bed882005b4b
[ "MIT" ]
null
null
null
concurrencpp/src/threads/thread_group.cpp
HungMingWu/concurrencpp
eb4ed8fb6cd8510925738868cf57bed882005b4b
[ "MIT" ]
null
null
null
concurrencpp/src/threads/thread_group.cpp
HungMingWu/concurrencpp
eb4ed8fb6cd8510925738868cf57bed882005b4b
[ "MIT" ]
null
null
null
#include "thread_group.h" #include <algorithm> #include <cassert> namespace concurrencpp::details { class thread_group_worker { private: task m_task; std::thread m_thread; thread_group& m_parent_pool; typename std::list<thread_group_worker>::iterator m_self_it; void execute_and_retire(); public: thread_group_worker(task& function, thread_group& parent_pool) noexcept; ~thread_group_worker() noexcept; std::thread::id get_id() const noexcept; std::thread::id start(std::list<thread_group_worker>::iterator self_it); }; } using concurrencpp::task; using concurrencpp::details::thread_group; using concurrencpp::details::thread_group_worker; using concurrencpp::details::thread_pool_listener_base; using listener_ptr = std::shared_ptr<thread_pool_listener_base>; thread_group_worker::thread_group_worker(task& function, thread_group& parent_pool) noexcept : m_task(std::move(function)), m_parent_pool(parent_pool) {} thread_group_worker::~thread_group_worker() noexcept { m_thread.join(); } void thread_group_worker::execute_and_retire() { m_task(); m_task.clear(); m_parent_pool.retire_worker(m_self_it); } std::thread::id thread_group_worker::get_id() const noexcept { return m_thread.get_id(); } std::thread::id thread_group_worker::start(std::list<thread_group_worker>::iterator self_it) { m_self_it = self_it; m_thread = std::thread([this] { execute_and_retire(); }); return m_thread.get_id(); } thread_group::thread_group(listener_ptr listener) : m_listener(std::move(listener)) {} thread_group::~thread_group() noexcept { wait_all(); assert(m_workers.empty()); clear_last_retired(std::move(m_last_retired)); } std::thread::id thread_group::enqueue(task callable) { std::unique_lock<decltype(m_lock)> lock(m_lock); auto& new_worker = m_workers.emplace_back(callable, *this); auto worker_it = std::prev(m_workers.end()); const auto id = new_worker.start(worker_it); const auto& listener = get_listener(); if (static_cast<bool>(listener)) { listener->on_thread_created(id); } return id; } void concurrencpp::details::thread_group::wait_all() { std::unique_lock<decltype(m_lock)> lock(m_lock); m_condition.wait(lock, [this] { return m_workers.empty(); }); } bool concurrencpp::details::thread_group::wait_all(std::chrono::milliseconds ms) { std::unique_lock<decltype(m_lock)> lock(m_lock); return m_condition.wait_for(lock, ms, [this] { return m_workers.empty(); }); } const listener_ptr& thread_group::get_listener() const noexcept { return m_listener; } void thread_group::clear_last_retired(std::list<thread_group_worker> last_retired) { if (last_retired.empty()) { return; } assert(last_retired.size() == 1); const auto thread_id = last_retired.front().get_id(); last_retired.clear(); const auto& listener = get_listener(); if (static_cast<bool>(listener)) { listener->on_thread_destroyed(thread_id); } } void thread_group::retire_worker(std::list<thread_group_worker>::iterator it) { std::list<thread_group_worker> last_retired; const auto id = it->get_id(); std::unique_lock<decltype(m_lock)> lock(m_lock); last_retired = std::move(m_last_retired); m_last_retired.splice(m_last_retired.begin(), m_workers, it); lock.unlock(); m_condition.notify_one(); const auto& listener = get_listener(); if (static_cast<bool>(listener)) { listener->on_thread_idling(id); } clear_last_retired(std::move(last_retired)); }
26.527132
94
0.753945
HungMingWu
99e354a0e578822703b25cedd9a6d9bc2a85e45d
91,661
cpp
C++
src/observer/sql/executor/tuple.cpp
watchpoints/miniob
3ad8dffc8f55ce66626472763bd13c4ad5205254
[ "Apache-2.0" ]
null
null
null
src/observer/sql/executor/tuple.cpp
watchpoints/miniob
3ad8dffc8f55ce66626472763bd13c4ad5205254
[ "Apache-2.0" ]
null
null
null
src/observer/sql/executor/tuple.cpp
watchpoints/miniob
3ad8dffc8f55ce66626472763bd13c4ad5205254
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2021 Xie Meiyi(xiemeiyi@hust.edu.cn) and OceanBase and/or its affiliates. All rights reserved. miniob is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. */ // // Created by Wangyunlai on 2021/5/14. // #include "sql/executor/tuple.h" #include "storage/common/table.h" #include "common/log/log.h" #include <stdio.h> #include <stdlib.h> #include <algorithm> Tuple::Tuple(const Tuple &other) { LOG_PANIC("Copy constructor of tuple is not supported"); exit(1); } Tuple::Tuple(Tuple &&other) noexcept : values_(std::move(other.values_)) { selectComareIndex = -1; } Tuple &Tuple::operator=(Tuple &&other) noexcept { if (&other == this) { return *this; } values_.clear(); values_.swap(other.values_); return *this; } Tuple::~Tuple() { } // add (Value && value) void Tuple::add(TupleValue *value) { values_.emplace_back(value); } void Tuple::add(const std::shared_ptr<TupleValue> &other) { values_.emplace_back(other); } void Tuple::add(int value) { add(new IntValue(value, 0)); } void Tuple::add_null_value() { add(new NullValue()); } void Tuple::add(float value) { add(new FloatValue(value, 0)); } //按照列的名字,添加 values void Tuple::add(const char *s, int len) { add(new StringValue(s, len, 0)); } void Tuple::add_text(const char *s, int len) { add(new TextValue(s, len, 0)); } void Tuple::add_date(int value) { add(new DateValue(value, 0)); } //////////////////////////////////////////////////////////////////////////////// std::string TupleField::to_string() const { return std::string(table_name_) + "." + field_name_ + std::to_string(type_); } //////////////////////////////////////////////////////////////////////////////// void TupleSchema::from_table(const Table *table, TupleSchema &schema) { const char *table_name = table->name(); //表名字 const TableMeta &table_meta = table->table_meta(); //表结构 const int field_num = table_meta.field_num(); //字段个数 for (int i = 0; i < field_num; i++) { const FieldMeta *field_meta = table_meta.field(i); if (field_meta->visible()) { schema.add(field_meta->type(), table_name, field_meta->name(), field_meta->nullable()); } } } void TupleSchema::add(AttrType type, const char *table_name, const char *field_name, int nullable) { fields_.emplace_back(type, table_name, field_name, nullable); } void TupleSchema::add(AttrType type, const char *table_name, const char *field_name) { fields_.emplace_back(type, table_name, field_name); } void TupleSchema::add(AttrType type, const char *table_name, const char *field_name, bool visible) { fields_.emplace_back(type, table_name, field_name, visible); } void TupleSchema::add_if_not_exists(AttrType type, const char *table_name, const char *field_name) { for (const auto &field : fields_) { if (0 == strcmp(field.table_name(), table_name) && 0 == strcmp(field.field_name(), field_name)) { LOG_INFO(">>>>>>>>>>add_if_exists. %s.%s", table_name, field_name); return; } } LOG_INFO("add_if_not_exists. %s.%s", table_name, field_name); add(type, table_name, field_name); } void TupleSchema::add_if_not_exists1(AttrType type, const char *table_name, const char *field_name, int nullable) { for (const auto &field : fields_) { if (0 == strcmp(field.table_name(), table_name) && 0 == strcmp(field.field_name(), field_name)) { LOG_INFO(">>>>>>>>>>add_if_exists. %s.%s", table_name, field_name); return; } } // LOG_INFO("add_if_not_exists. %s.%s", table_name, field_name); add(type, table_name, field_name, nullable); } void TupleSchema::add_if_not_exists(AttrType type, const char *table_name, const char *field_name, FunctionType ftype) { //判断列是否存在 for (const auto &field : fields_) { if (0 == strcmp(field.table_name(), table_name) && 0 == strcmp(field.field_name(), field_name) && ftype == field.get_function_type()) { LOG_INFO(">>>>>>>>>>add_if_exists. %s.%s", table_name, field_name); return; } } LOG_INFO("add_if_not_exists. %s.%s", table_name, field_name); add(type, table_name, field_name, ftype); } void TupleSchema::append(const TupleSchema &other) { fields_.reserve(fields_.size() + other.fields_.size()); for (const auto &field : other.fields_) { fields_.emplace_back(field); } } int TupleSchema::index_of_field(const char *table_name, const char *field_name) const { const int size = fields_.size(); for (int i = 0; i < size; i++) { const TupleField &field = fields_[i]; if (0 == strcmp(field.table_name(), table_name) && 0 == strcmp(field.field_name(), field_name)) { return i; } } return -1; } //列信息: fields_:(type_ = INTS, table_name_ = "t1", field_name_ = "id") void TupleSchema::print(std::ostream &os) const { if (fields_.empty()) { os << "No schema"; return; } // 判断有多张表还是只有一张表 //并不使用 table_names的数据 std::set<std::string> table_names; for (const auto &field : fields_) { table_names.insert(field.table_name()); } //单表逻辑 if (table_names.size() == 1) { //遍历n-1个元素. for (std::vector<TupleField>::const_iterator iter = fields_.begin(), end = --fields_.end(); iter != end; ++iter) { //如果多个表:添加表名t.id if (table_names.size() > 1 || realTabeNumber > 1) { os << iter->table_name() << "."; } if (FunctionType::FUN_COUNT_ALL == iter->get_function_type()) { //count(1) //if (0 == strcmp("*", iter->field_name())) //{ //os << "count(*)" // << " | "; //} //else //{ os << "count(" << iter->field_name_count_number() << ")" << " | "; //} } if (FunctionType::FUN_COUNT_ALL_ALl == iter->get_function_type()) { //count(*) os << "count(*)" << " | "; } else if (iter->get_function_type() == FunctionType::FUN_COUNT) { os << "count(" << iter->field_name() << ")" << " | "; } else if (iter->get_function_type() == FunctionType::FUN_MAX) { os << "max(" << iter->field_name() << ")" << " | "; } else if (iter->get_function_type() == FunctionType::FUN_MIN) { os << "min(" << iter->field_name() << ")" << " | "; } else if (iter->get_function_type() == FunctionType::FUN_AVG) { os << "avg(" << iter->field_name() << ")" << " | "; } else { //正常情况 os << iter->field_name() << " | "; } } //last col //visible if (table_names.size() > 1 || realTabeNumber > 1) { os << fields_.back().table_name() << "."; } //id ---- 最后一个列,后面没有 |,只有名字 if (FunctionType::FUN_COUNT_ALL_ALl == fields_.back().get_function_type()) { //count(*) os << "count(*)" << std::endl; } else if (fields_.back().get_function_type() == FunctionType::FUN_COUNT_ALL) { //os << "count(*)" << std::endl; //select count(*) from t; //if (0 == strcmp("*", fields_.back().field_name())) //{ //os << "count(*)" << std::endl; //} //else //{ os << "count(" << fields_.back().field_name_count_number() << ")" << std::endl; //} } else if (fields_.back().get_function_type() == FunctionType::FUN_COUNT) { os << "count(" << fields_.back().field_name() << ")" << std::endl; } else if (fields_.back().get_function_type() == FunctionType::FUN_MAX) { os << "max(" << fields_.back().field_name() << ")" << std::endl; } else if (fields_.back().get_function_type() == FunctionType::FUN_MIN) { os << "min(" << fields_.back().field_name() << ")" << std::endl; } else if (fields_.back().get_function_type() == FunctionType::FUN_AVG) { os << "avg(" << fields_.back().field_name() << ")" << std::endl; } //bug1 else if ->if else { //正常情况 os << fields_.back().field_name() << std::endl; } //单表 列逻辑 ///////////////////////////////////////// end } else { //多表逻辑///////////////////////////////////////// 开始 //https://github.com/oceanbase/miniob/blob/main/src/observer/sql/executor/tuple.cpp#123 LOG_INFO(" join query cols >>>>>>>>>>>>>>"); //删除不显示的列 /** std::vector<TupleField> tuplefields; for (std::vector<TupleField>::const_iterator iter = fields_.begin(), end =fields_.end(); iter != end; ++iter) { tuplefields.push_back(*iter); } for (std::vector<TupleField>::iterator iter = tuplefields.begin(), end =tuplefields.end(); iter != end; ) { if( false ==iter->visible()){ iter = tuplefields.erase(iter); }else{ iter++; } }**/ for (std::vector<TupleField>::const_iterator iter = fields_.begin(), end = --fields_.end(); iter != end; ++iter) { if (FunctionType::FUN_COUNT_ALL == iter->get_function_type()) { //count(1) os << "count(" << iter->field_name_count_number() << ")" << " | "; } else if (FunctionType::FUN_COUNT_ALL_ALl == iter->get_function_type()) { //count(*) os << "count(*)" << " | "; } else if (iter->get_function_type() == FunctionType::FUN_COUNT) { os << "count("; if (table_names.size() > 1) { os << iter->table_name() << "."; } os << iter->field_name() << ")" << " | "; } else if (iter->get_function_type() == FunctionType::FUN_MAX) { os << "max("; if (table_names.size() > 1) { os << iter->table_name() << "."; } os << iter->field_name() << ")" << " | "; } else if (iter->get_function_type() == FunctionType::FUN_MIN) { os << "min("; if (table_names.size() > 1) { os << iter->table_name() << "."; } os << iter->field_name() << ")" << " | "; } else if (iter->get_function_type() == FunctionType::FUN_AVG) { os << "avg("; if (table_names.size() > 1) { os << iter->table_name() << "."; } os << iter->field_name() << ")" << " | "; } else { //正常情况 if (table_names.size() > 1) { os << iter->table_name() << "."; } os << iter->field_name() << " | "; } } //最后一列:显示 if (FunctionType::FUN_COUNT_ALL == fields_.back().get_function_type()) { //count(1) os << "count(" << fields_.back().field_name_count_number() << ")" << std::endl; } else if (FunctionType::FUN_COUNT_ALL_ALl == fields_.back().get_function_type()) { //count(*) os << "count(*)" << std::endl; } else if (fields_.back().get_function_type() == FunctionType::FUN_COUNT) { os << "count("; if (table_names.size() > 1) { os << fields_.back().table_name() << "."; } os << fields_.back().field_name() << ")" << std::endl; } else if (fields_.back().get_function_type() == FunctionType::FUN_MAX) { os << "max("; if (table_names.size() > 1) { os << fields_.back().table_name() << "."; } os << fields_.back().field_name() << ")" << std::endl; } else if (fields_.back().get_function_type() == FunctionType::FUN_MIN) { os << "min("; if (table_names.size() > 1) { os << fields_.back().table_name() << "."; } os << fields_.back().field_name() << ")" << std::endl; } else if (fields_.back().get_function_type() == FunctionType::FUN_AVG) { os << "avg("; if (table_names.size() > 1) { os << fields_.back().table_name() << "."; } os << fields_.back().field_name() << ")" << std::endl; } else { //正常情况,普通的字 if (table_names.size() > 1) { os << fields_.back().table_name() << "."; } os << fields_.back().field_name() << std::endl; } ///////////////////////////end,多表逻辑////////////////////////////end } } ///////////////////////////////////////////////////////////////////////////// TupleSet::TupleSet(TupleSet &&other) : tuples_(std::move(other.tuples_)), schema_(other.schema_) { other.schema_.clear(); realTabeNumber = other.realTabeNumber; //push_back(std::move(TupleSet)) old_schema = other.old_schema; commonIndex = other.commonIndex; select_table_type = other.select_table_type; dp = other.dp; } TupleSet &TupleSet::operator=(TupleSet &&other) { if (this == &other) { return *this; } schema_.clear(); schema_.append(other.schema_); other.schema_.clear(); realTabeNumber = -1; tuples_.clear(); //swap 交换 tuples_.swap(other.tuples_); return *this; } void TupleSet::add(Tuple &&tuple) { tuples_.emplace_back(std::move(tuple)); } void TupleSet::clear() { tuples_.clear(); schema_.clear(); old_schema.clear(); dp.clear(); } //print shows void TupleSet::print(std::ostream &os) { //列信息: (type_ = INTS, table_name_ = "t1", field_name_ = "id") if (schema_.fields().empty()) { LOG_WARN("Got empty schema"); return; } if (realTabeNumber > 1) { schema_.realTabeNumber = realTabeNumber; } else { schema_.realTabeNumber = -1; } schema_.print(os); //打印 列字段 (已经考虑到多个表) // 判断有多张表还是只有一张表 std::set<std::string> table_names; for (const auto &field : schema_.fields()) { table_names.insert(field.table_name()); } //一个表: if (table_names.size() == 1) { //分组 group-by if (ptr_group_selects && ptr_group_selects->attr_group_num > 0) { print_group_by(os); return; } //单表聚合:只有一行 if (true == avg_print(os)) { LOG_INFO("this is avg query >>>>>>>>>>>>>>>>>> "); return; } //排序 order-by int order_by_num = -1; RelAttr *ptr_attr_order_by = nullptr; if (ptr_group_selects && ptr_group_selects->attr_order_num > 0) { order_by_num = ptr_group_selects->attr_order_num; ptr_attr_order_by = ptr_group_selects->attr_order_by; } int group_by_num = -1; RelAttr *ptr_attr_group_by = nullptr; if (ptr_group_selects && ptr_group_selects->attr_group_num > 0) { group_by_num = ptr_group_selects->attr_group_num; ptr_attr_group_by = ptr_group_selects->attr_group_by; } if (order_by_num > 0) { //order by //std::vector<Tuple> tuples_; //一个表头信息 //TupleSchema schema_; //一个表内容信息 //SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME; std::vector<int> order_index; order_index.clear(); const std::vector<TupleField> &fields = schema_.fields(); int index = 0; for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end(); iter != end; ++iter) { //SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME; for (int cols = 0; cols < order_by_num; cols++) { if (0 == strcmp(iter->field_name(), ptr_attr_order_by[cols].attribute_name)) { order_index.push_back(index); LOG_INFO("题目:排序 >>>>>> index=%d,cols=%d,name=%s", index, cols, ptr_attr_order_by[cols].attribute_name); } } index++; } if (order_by_num != order_index.size()) { LOG_INFO("排序 order-by 失败 order_by_num != order_index.size()"); return; } LOG_INFO("排序 order-by 开始排序 order_index=%d", order_by_num); auto sortRuleLambda = [=](const Tuple &s1, const Tuple &s2) -> bool { //std::vector<std::shared_ptr<TupleValue>> values_; std::vector<std::shared_ptr<TupleValue>> sp1; std::vector<std::shared_ptr<TupleValue>> sp2; //根据位置--查找value for (int i = 0; i < order_index.size(); i++) { sp1.push_back(s1.get_pointer(order_index[i])); sp2.push_back(s2.get_pointer(order_index[i])); } //多个字段如何比较呀? for (int op_index = 0; op_index < order_index.size(); op_index++) { int op_comp = 0; std::shared_ptr<TupleValue> sp_1 = sp1[op_index]; std::shared_ptr<TupleValue> sp_2 = sp2[op_index]; if (sp_1 && sp_2) { op_comp = sp_1->compare(*sp_2); } //不相等才比较 ,相等下一个 if (op_comp != 0) { int index_order = order_index.size() - op_index - 1; if (CompOp::ORDER_ASC == ptr_attr_order_by[index_order].is_asc) { LOG_INFO("排序 order-by ORDER_ASC op_index=%d, order_index=%d,name=%s", op_index, order_by_num, ptr_attr_order_by[index_order].attribute_name); return op_comp < 0; //true } else if (CompOp::ORDER_DESC == ptr_attr_order_by[index_order].is_asc) { LOG_INFO("排序 order-by ORDER_DESC op_index=%d,order_index=%d,name=%s", op_index, order_by_num, ptr_attr_order_by[index_order].attribute_name); return op_comp > 0; //true } else { LOG_INFO("排序 order-by err err err err order_index=%d,name=%s", order_by_num, ptr_attr_order_by[index_order].attribute_name); } } } ////多个字段如何比较呀? //为什么std::sort比较函数在参数相等时返回false? return false; }; if (tuples_.size() > 0) { std::sort(tuples_.begin(), tuples_.end(), sortRuleLambda); } } //rows cols for (const Tuple &item : tuples_) { //第n-1列 const std::vector<std::shared_ptr<TupleValue>> &values = item.values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = --values.end(); iter != end; ++iter) { (*iter)->to_string(os); os << " | "; } //最后一列 values.back()->to_string(os); os << std::endl; //1 | 2 | 3 } } else if (table_names.size() == 2) { ////多表操作///////////////////////////////////// //笛卡尔积算法描述 if (tuples1_.size() == 0 || tuples2_.size() == 0) { return; } //t1.rows[i][j] //t2.rows[i][j] for (const Tuple &item_left : tuples1_) { std::shared_ptr<TupleValue> sp1; int col1 = 0; std::stringstream os_left; { //std::vector<std::shared_ptr<TupleValue>> values_; 每一行 多个字段 const std::vector<std::shared_ptr<TupleValue>> &values = item_left.values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { if (is_join == true && joins_index == col1) { sp1 = *iter; cout << ">>>>>>>>>>>>>join select " << endl; } (*iter)->to_string(os_left); os_left << " | "; col1++; } } //b表的多行 tuples_right 多行 for (const Tuple &item_right : tuples2_) { std::shared_ptr<TupleValue> sp2; int col2 = 0; std::stringstream os_right; { const std::vector<std::shared_ptr<TupleValue>> &values = item_right.values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = --values.end(); iter != end; ++iter) { //笛卡尔积:查询条件 if (is_join == true && joins_index == col2) { sp2 = *iter; cout << ">>>>>>>>>>>>>join select " << endl; } (*iter)->to_string(os_right); os_right << " | "; col2++; } //小王疑问:为啥还有最后行 不是上面遍历完毕了吗? values.back()->to_string(os_right); os_right << std::endl; } //多表:join查询 if (is_join == true) { LOG_INFO(" two table join select "); if (sp1 && sp2 && 0 == sp1->compare(*sp2)) { os << os_left.str(); os << os_right.str(); } else { LOG_INFO(" not equal "); } } else { os << os_left.str(); os << os_right.str(); } } } } else { LOG_INFO(" no support three table query "); } } void TupleSet::set_schema(const TupleSchema &schema) { schema_ = schema; } const TupleSchema &TupleSet::get_schema() const { return schema_; } bool TupleSet::is_empty() const { return tuples_.empty(); } int TupleSet::size() const { return tuples_.size(); } const Tuple &TupleSet::get(int index) const { return tuples_[index]; } const std::vector<Tuple> &TupleSet::tuples() const { return tuples_; } ///////////////////////////////////////////////////////////////////////////// TupleRecordConverter::TupleRecordConverter(Table *table, TupleSet &tuple_set) : table_(table), tuple_set_(tuple_set) { } //record:value 开始地址 //record --->显示 void TupleRecordConverter::add_record(const char *record) { const TupleSchema &schema = tuple_set_.schema(); //查询条件的表信息 可能全部列 可能部分 Tuple tuple; const TableMeta &table_meta = table_->table_meta(); for (const TupleField &field : schema.fields()) { const FieldMeta *field_meta = table_meta.field(field.field_name()); assert(field_meta != nullptr); int null_able = field_meta->nullable(); switch (field_meta->type()) { case INTS: { if (null_able == 1) { const char *s = record + field_meta->offset(); if (0 == strcmp(s, "999")) { tuple.add_null_value(); } else { int value = *(int *)(record + field_meta->offset()); //LOG_INFO(" tuple add int =%d ", value); tuple.add(value); } } else { int value = *(int *)(record + field_meta->offset()); // LOG_INFO(" tuple add int =%d ", value); tuple.add(value); } } break; case FLOATS: { if (null_able == 1) { //memset 改为 const char *s = record + field_meta->offset(); if (0 == strcmp(s, "999")) { //LOG_INFO("99999 FLOATS"); tuple.add_null_value(); } else { float value = *(float *)(record + field_meta->offset()); //LOG_INFO(" tuple add float =%d ", value); tuple.add(value); } } else { float value = *(float *)(record + field_meta->offset()); LOG_INFO(" tuple add float =%d ", value); tuple.add(value); } } break; case CHARS: { if (null_able == 1) { //memset 改为 const char *s = record + field_meta->offset(); if (0 == strcmp(s, "999")) { //LOG_INFO("99999 FLOATS"); tuple.add_null_value(); } else { const char *s = record + field_meta->offset(); // 现在当做Cstring来处理 // LOG_INFO(" tuple add string =%s ", s); tuple.add(s, strlen(s)); } } else { const char *s = record + field_meta->offset(); // 现在当做Cstring来处理 LOG_INFO(" tuple add string =%s ", s); tuple.add(s, strlen(s)); } } break; case DATES: { if (null_able == 1) { //memset memcpy const char *s = record + field_meta->offset(); if (0 == strcmp(s, "999")) { // LOG_INFO("99999 FLOATS"); tuple.add_null_value(); } else { int value = *(int *)(record + field_meta->offset()); // LOG_INFO(" tuple.add_date=%d ", value); tuple.add_date(value); } } else { int value = *(int *)(record + field_meta->offset()); // LOG_INFO(" tuple.add_date=%d ", value); tuple.add_date(value); } } break; case TEXTS: { if (null_able == 1) { //memset 改为 const char *s = record + field_meta->offset(); if (0 == strcmp(s, "999")) { //LOG_INFO("99999 FLOATS"); tuple.add_null_value(); } else { const char *s = record + field_meta->offset(); // 现在当做Cstring来处理 // LOG_INFO(" tuple add string =%s ", s); int key = *(int *)s; if (table()->pTextMap.count(key) == 1) { s = table()->pTextMap[key]; LOG_INFO(" 题目 超长文本 >>>>>>>>>>>> key=%d,value=%s ", key, s); } else { LOG_INFO(" 题目 超长文本 失败 失败 失败 失败 =%s ", s); } tuple.add_text(s, strlen(s)); } } else { const char *s = record + field_meta->offset(); // 现在当做Cstring来处理 int key = *(int *)s; if (table()->pTextMap.count(key) == 1) { s = table()->pTextMap[key]; LOG_INFO(" 题目 超长文本 >>>>>>>>>>>> key=%d,value=%s ", key, s); } else { LOG_INFO(" 题目 超长文本 失败 失败 失败 失败 key=%d,value=%s ", key, s); } tuple.add(s, strlen(s)); } } break; default: { LOG_PANIC("Unsupported field type. type=%d", field_meta->type()); } } } tuple_set_.add(std::move(tuple)); } //聚合 void TupleSchema::from_table_first(const Table *table, TupleSchema &schema, FunctionType functiontype) { const char *table_name = table->name(); //表名字 const TableMeta &table_meta = table->table_meta(); //表结构 //const int field_num = table_meta.field_num(); //字段个数 const FieldMeta *field_meta = table_meta.field(1); if (field_meta && field_meta->visible()) { schema.add(field_meta->type(), table_name, field_meta->name(), functiontype, field_meta->nullable()); } } void TupleSchema::add(AttrType type, const char *table_name, const char *field_name, FunctionType functiontype) { fields_.emplace_back(type, table_name, field_name, functiontype); } void TupleSchema::add(AttrType type, const char *table_name, const char *field_name, FunctionType functiontype, int nullable) { fields_.emplace_back(type, table_name, field_name, functiontype, nullable); } bool TupleSet::avg_print(std::ostream &os) const { //步骤 //1. 遍历 属性 //2. 根据不同属性函数,做不同的计算. //3. 返回是存在聚合 bool isWindows = false; const std::vector<TupleField> &fields = schema_.fields(); int count = fields.size(); int index = 0; //遍历n个元素. for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end(); iter != end; ++iter) { FunctionType window_function = iter->get_function_type(); if (FunctionType::FUN_COUNT_ALL_ALl == window_function || FunctionType::FUN_COUNT_ALL == window_function || FunctionType::FUN_COUNT == window_function) { isWindows = true; int count = 0; //count(*) if (FunctionType::FUN_COUNT_ALL_ALl == window_function || FunctionType::FUN_COUNT_ALL == window_function) { count = tuples_.size(); } else { //rows count(id) //字段值是NULL时,比较特殊,不需要统计在内。如果是AVG,不会增加统计行数,也不需要默认值。 for (const Tuple &item : tuples_) { int colIndex = 0; bool null_able = true; //cols const std::vector<std::shared_ptr<TupleValue>> &values = item.values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { if (colIndex == index) { std::shared_ptr<TupleValue> temp = *iter; if (AttrType::NULLVALUES == temp->get_type()) { null_able = false; } break; } colIndex++; } if (true == null_able) { count++; } } } //end else os << count; } else if (FunctionType::FUN_MAX == window_function) { //属性值类型 typedef enum { UNDEFINED, CHARS, INTS, FLOATS,DATES } AttrType; isWindows = true; std::shared_ptr<TupleValue> maxValue; if (0 == tuples_.size()) { return true; } for (const Tuple &item : tuples_) { int colIndex = 0; //第n-1列 const std::vector<std::shared_ptr<TupleValue>> &values = item.values(); if (0 == values.size()) { continue; } for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { //(*iter)->to_string(os); if (colIndex == index) { std::shared_ptr<TupleValue> temp = *iter; //if (AttrType::NULLVALUES == temp->get_type()) //{ //不处理 //} //else { if (nullptr == maxValue) { maxValue = temp; } else { if (maxValue->compare(*temp) < 0) { maxValue = temp; } } } break; //get } colIndex++; } } //end maxValue->to_string(os); } else if (FunctionType::FUN_MIN == window_function) { //属性值类型 typedef enum { UNDEFINED, CHARS, INTS, FLOATS,DATES } AttrType; isWindows = true; std::shared_ptr<TupleValue> minValue; if (0 == tuples_.size()) { return true; } for (const Tuple &item : tuples_) { int colIndex = 0; //列 const std::vector<std::shared_ptr<TupleValue>> &values = item.values(); if (0 == values.size()) { continue; } for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { //(*iter)->to_string(os); if (colIndex == index) { std::shared_ptr<TupleValue> temp = *iter; //if (AttrType::NULLVALUES == temp->get_type()) //{ //不处理 //} //else { if (nullptr == minValue) { minValue = *iter; } else { std::shared_ptr<TupleValue> temp = *iter; if (minValue->compare(*temp) > 0) { minValue = temp; } } } break; //get } colIndex++; } } //end minValue->to_string(os); } else if (FunctionType::FUN_AVG == window_function) { //属性值类型 typedef enum { UNDEFINED, CHARS, INTS, FLOATS,DATES } AttrType; isWindows = true; std::shared_ptr<TupleValue> sumValue; int count = 0; bool exits_null_value = false; if (0 == tuples_.size()) { return true; } for (const Tuple &item : tuples_) { int colIndex = 0; bool null_able = true; //第n列 const std::vector<std::shared_ptr<TupleValue>> &values = item.values(); if (0 == values.size()) { continue; } for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { //(*iter)->to_string(os); if (colIndex == index) { std::shared_ptr<TupleValue> temp = *iter; if (AttrType::NULLVALUES == temp->get_type()) { //不处理 null_able = false; exits_null_value = true; } else { if (nullptr == sumValue) { sumValue = temp; } else { sumValue->add_value(*temp); } } break; //get } colIndex++; } if (true == null_able) { count++; } } //end //防溢出求平均算法 if (0 == count) { if (exits_null_value == true) { os << "NULL"; os << std::endl; } return true; //是聚合运算 } sumValue->to_avg(count, os); } //聚合函数显示 if (FunctionType::FUN_AVG == window_function || FunctionType::FUN_COUNT == window_function || FunctionType::FUN_COUNT_ALL == window_function || FunctionType::FUN_COUNT_ALL_ALl == window_function || FunctionType::FUN_MIN == window_function || FunctionType::FUN_MAX == window_function) { if (index == count - 1) { //os << result.c_str(); os << std::endl; } else { //os << result.c_str(); os << " | "; } } index++; } //const std::vector<TupleField> &fields = schema_.fields(); return isWindows; } void TupleSchema::add_if_not_exists_visible(AttrType type, const char *table_name, const char *field_name, bool visible) { for (const auto &field : fields_) { if (0 == strcmp(field.table_name(), table_name) && 0 == strcmp(field.field_name(), field_name)) { LOG_INFO(">>>>>>>>>>add_if_exists. %s.%s", table_name, field_name); return; } } add(type, table_name, field_name, visible); } //2个表的join操作 void TupleSet::print_two(std::ostream &os) { //列信息: (type_ = INTS, table_name_ = "t1", field_name_ = "id") if (schema_.fields().empty()) { LOG_WARN("Got empty schema"); return; } if (old_schema.get_size() > 0) { old_schema.realTabeNumber = 2; //修改old_schema成员变量, 去掉const函数 old_schema.print(os); // 原始查询条件 //select t2.age from t1 ,t2 where t1.age=21; } else { schema_.print(os); //打印 列字段 (已经考虑到多个表) } // 判断有多张表还是只有一张表 std::set<std::string> table_names; for (const auto &field : schema_.fields()) { table_names.insert(field.table_name()); } if (2 != table_names.size()) { return; } ////多表操作///////////////////////////////////// //笛卡尔积算法描述 if (tuples1_.size() == 0 || tuples2_.size() == 0) { return; } //select t1.age,t2.age from t1 ,t2 where t1.id =t2.id; //[id(隐藏),age] [age,id(隐藏)) std::map<int, bool> leftVisibleMap; leftVisibleMap.clear(); int index1 = 0; int count1 = schema1_.get_size() - 1; for (const auto &field : schema1_.fields()) { if (false == field.visible()) { if (index1 == count1) { leftVisibleMap[index1] = true; //最后一个字段 } else { leftVisibleMap[index1] = false; } } index1++; } std::map<int, bool> rightVisibleMap; rightVisibleMap.clear(); int index2 = 0; int count2 = schema2_.get_size() - 1; for (const auto &field : schema2_.fields()) { if (false == field.visible()) { if (index2 == count2) { rightVisibleMap[index2] = true; } else { rightVisibleMap[index2] = false; } } index2++; } order_by_two(); //t1.rows[i][j] //t2.rows[i][j] //item_left 一行记录 //第一个表内容 for (const Tuple &item_left : tuples1_) { std::shared_ptr<TupleValue> sp1; vector<std::shared_ptr<TupleValue>> left(dp.size()); //多个过滤条件 //几个过滤条件 //select t1.age,t1.id ,t2.id,t2.age from t1,t2 where t1.id=t2.id and t1.age =t2.age; int col1 = 0; std::stringstream os_left; //第一个表的 全部行 std::stringstream os_left1; std::stringstream os_left2; { //std::vector<std::shared_ptr<TupleValue>> values_; 每一行 多个字段 const std::vector<std::shared_ptr<TupleValue>> &values = item_left.values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { if (is_join == true && joins_index == col1) { sp1 = *iter; cout << ">>>>>>>>>>>>>join select " << endl; } if (is_join == true) { for (int i = 0; i < dp.size(); i++) { if (col1 == dp[i][0].m_index) { left[i] = *iter; cout << "left " << col1 << endl; } } } //一个表:是否隐藏 if (leftVisibleMap.size() > 0 && leftVisibleMap.count(col1) == 1) { } else { if (b_not_know == true && col1 == 1) { (*iter)->to_string(os_left1); LOG_INFO("11111111111111111 left="); } else { (*iter)->to_string(os_left); os_left << " | "; } } col1++; } } //b表的多行 tuples_right 多行 //第2个表内容 for (const Tuple &item_right : tuples2_) { std::shared_ptr<TupleValue> sp2; vector<std::shared_ptr<TupleValue>> right(dp.size()); right.clear(); int col2 = 0; std::stringstream os_right; //第二个表:一行记录 { const std::vector<std::shared_ptr<TupleValue>> &values = item_right.values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { //笛卡尔积:查询条件 if (is_join == true && joins_index == col2) { sp2 = *iter; } if (is_join == true) { for (int ri = 0; ri < dp.size(); ri++) { if (col2 == dp[ri][1].m_index) { right[ri] = *iter; cout << "right " << col2 << endl; } } } //判断是否最后一行 if (col2 == values.size() - 1) { //一个表:是否隐藏 if (rightVisibleMap.size() > 0 && rightVisibleMap.count(col2) == 1) { //隐藏 什么都不操作 } else { if (b_not_know == true) { (*iter)->to_string(os_right); os_right << " | "; os_right << os_left1.str(); os_right << std::endl; } else { (*iter)->to_string(os_right); os_right << std::endl; } } } else { if (rightVisibleMap.size() > 0 && rightVisibleMap.count(col2) == 1) { //隐藏 什么都不操作 } else if (rightVisibleMap.size() > 0 && rightVisibleMap.count(col2) == 0) { //自己不隐藏,下一行隐藏,下一行是最后一行 ////age(当前),id(隐藏) int next = col2 + 1; if (rightVisibleMap.count(next) == 1 && true == rightVisibleMap[next]) { (*iter)->to_string(os_right); os_right << std::endl; } } else { (*iter)->to_string(os_right); os_right << " | "; } } col2++; } } //多表:有join条件 if (is_join == true) { LOG_INFO(" two table join select "); bool b_equal = false; //符合条件 //join条件全部相等 for (int i = 0; i < dp.size(); i++) { CompOp two_comp = dp[i][0].comp; std::stringstream s1; std::stringstream s2; left[i]->to_string(s1); right[i]->to_string(s2); std::cout << " >>>>>>> left:" << s1.str() << "right:" << s2.str() << std::endl; //"==" if (two_comp == EQUAL_TO) { if (left[i] && right[i] && 0 == left[i]->compare(*right[i])) { b_equal = true; } } else if (two_comp == GREAT_EQUAL) { // ">=" t1.id >=t2.id if (left[i] && right[i] && left[i]->compare(*right[i]) >= 0) { b_equal = true; } } else if (two_comp == GREAT_THAN) { // ">" if (left[i] && right[i] && left[i]->compare(*right[i]) > 0) { b_equal = true; } } else if (two_comp == LESS_EQUAL) { // "<=" if (left[i] && right[i] && left[i]->compare(*right[i]) <= 0) { b_equal = true; } } else if (two_comp == LESS_THAN) { // "<" if (left[i] && right[i] && left[i]->compare(*right[i]) < 0) { b_equal = true; } } } if (true == b_equal) { //sql: 1笛卡尔积 2 排序 3 分组 4 输出 //题目:order_by if (ptr_group_selects && ptr_group_selects->attr_order_num > 0) { join_table_for_order_by(item_left, item_right); } else if (ptr_group_selects && ptr_group_selects->attr_group_num > 0) { join_table_for_group_by(item_left, item_right); //这里不输出,哪里输出呀 } else { os << os_left.str(); os << os_right.str(); } } } else { //没有join条件 os << os_left.str(); os << os_right.str(); } } } //题目:order_by if (ptr_group_selects && ptr_group_selects->attr_order_num > 0) { sort_table_for_order_by(); std::stringstream ss; join_tuples_to_print(ss); os << ss.str(); } else if (ptr_group_selects && ptr_group_selects->attr_group_num > 0) { //步骤:排序 分组 统计 //2个表合成一个表了. print_two_table_group_by(os); } } //聚合 void TupleSchema::from_table_first_count_number(const Table *table, TupleSchema &schema, FunctionType functiontype, const char *field_name_count_number) { const char *table_name = table->name(); //表名字 const TableMeta &table_meta = table->table_meta(); //表结构 //const int field_num = table_meta.field_num(); //字段个数 const FieldMeta *field_meta = table_meta.field(1); if (field_meta && field_meta->visible()) { // schema.add(field_meta->type(), table_name, field_meta->name(), functiontype); schema.add_number(field_meta->type(), table_name, field_meta->name(), functiontype, field_name_count_number, field_meta->nullable()); } } void TupleSchema::add_number(AttrType type, const char *table_name, const char *field_name, FunctionType functiontype, const char *field_name_count_number, int nullable) { TupleField temp(type, table_name, field_name, functiontype); temp.field_name_count_number_ = field_name_count_number; fields_.push_back(temp); //fields_.emplace_back(std::move(temp)); //fields_.emplace_back(type, table_name, field_name, functiontype); } //至少3个表 void TupleSet::print_multi_table(std::ostream &os) { if (schema_.fields().empty()) { LOG_WARN(" print_multi_table Got empty schema"); return; } schema_.print(os); // 如果显示列有问题 请在看这里 多个表合并一个表 // 判断有多张表还是只有一张表 std::set<std::string> table_names; for (const auto &field : schema_.fields()) { table_names.insert(field.table_name()); } if (3 != table_names.size()) { return; } ////多表操作///////////////////////////////////// //笛卡尔积算法描述 if (tuples1_.size() == 0 || tuples2_.size() == 0 || tuples3_.size() == 0) { return; } //三次循环 for (Tuple &item_1 : tuples1_) { std::stringstream os_tuples_1; //node1 os_tuples_1.clear(); // std::shared_ptr<TupleValue> sp1; item_1.sp1.reset(); item_1.selectComareIndex = commonIndex; //比较字段位置 item_1.head_table_row_string(os_tuples_1, 1); for (Tuple &item_2 : tuples2_) { std::stringstream os_tuples_2; //node2 os_tuples_2.clear(); item_2.sp2.reset(); item_2.selectComareIndex = commonIndex; //比较字段位置 item_2.head_table_row_string(os_tuples_2, 2); std::stringstream os_tuples_1_2; os_tuples_1_2.clear(); if (select_table_type == 2) { LOG_WARN(" >>>>>>>>>>>>>>>>>> select_table_type =2"); if (item_1.sp1 && item_2.sp2 && 0 == item_1.sp1->compare(*item_2.sp2)) { os_tuples_1_2 << os_tuples_1.str(); os_tuples_1_2 << os_tuples_2.str(); LOG_WARN(" >>>>>>>>>>>>>>>>>> 相等 select_table_type =2"); } else { LOG_WARN(" >>>>>>>>>>>>>>>>>> 不相等 select_table_type =2"); } } else { os_tuples_1_2 << os_tuples_1.str(); os_tuples_1_2 << os_tuples_2.str(); } for (Tuple &item_3 : tuples3_) { std::stringstream os_tuples_3; //node3 os_tuples_3.clear(); item_3.sp3.reset(); item_3.selectComareIndex = commonIndex; //比较字段位置 item_3.tail_table_row_string(os_tuples_3, 3); //多表:有join条件 //select * from t1,t2,t3; if (false == is_join) { //没有join条件 os << os_tuples_1_2.str(); os << os_tuples_3.str(); } else { //select_table_type //0 查询无过滤条件 //1 三表完全过滤 //2表过滤 //a ok b ok c (no) //3 //a (no) b ok c ok ////a (no) b ok c ok if (select_table_type == 1) { bool b_equal = true; if (item_1.sp1 && item_2.sp2 && 0 == item_1.sp1->compare(*item_2.sp2)) { } else { b_equal = false; } if (item_1.sp1 && item_3.sp3 && 0 == item_1.sp1->compare(*item_3.sp3)) { } else { b_equal = false; } if (true == b_equal) { os << os_tuples_1_2.str(); os << os_tuples_3.str(); } //end if 1 } else if (select_table_type == 2) { //2表过滤 //a ok b ok c (no) //组合完毕---过滤 bool b_equal = true; if (item_1.sp1 && item_2.sp2 && 0 == item_1.sp1->compare(*item_2.sp2)) { } else { b_equal = false; } if (true == b_equal) { os << os_tuples_1_2.str(); os << os_tuples_3.str(); } } //end select_table_type == 2 else if (select_table_type == 3) { //3 //a (no) b ok c ok bool b_equal = true; //组合完毕---过滤 if (item_2.sp2 && item_3.sp3 && 0 == item_2.sp2->compare(*item_3.sp3)) { } else { b_equal = false; } if (true == b_equal) { os << os_tuples_1_2.str(); os << os_tuples_3.str(); } ////end select_table_type == 3 } else if (4 == select_table_type) { //a (ok) b (no) c ok //组合完毕---过滤 bool b_equal = true; if (item_1.sp1 && item_3.sp3 && 0 == item_1.sp1->compare(*item_3.sp3)) { } else { b_equal = false; } if (true == b_equal) { os << os_tuples_1_2.str(); os << os_tuples_3.str(); } } } //end else } } } } void Tuple::head_table_row_string(std::ostream &os) { const std::vector<std::shared_ptr<TupleValue>> &values = this->values(); //int cols =0; for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { (*iter)->to_string(os); os << " | "; //if(cols ==selectComareIndex) //{ // sp1 = *iter; //} //cols++; } } void Tuple::tail_table_row_string(std::ostream &os) { size_t col2 = 0; const std::vector<std::shared_ptr<TupleValue>> &values = this->values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { //判断是否最后一行 if (col2 == values.size() - 1) { (*iter)->to_string(os); os << std::endl; } else { (*iter)->to_string(os); os << " | "; } col2++; } } void Tuple::head_table_row_string(std::ostream &os, int type) { const std::vector<std::shared_ptr<TupleValue>> &values = this->values(); int cols = 0; for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { (*iter)->to_string(os); os << " | "; //如果多个查询条件,考虑 需要更多考虑 if (cols == selectComareIndex) { if (1 == type) { sp1 = *iter; } else if (2 == type) { sp2 = *iter; } else if (3 == type) { sp3 = *iter; } } cols++; } } void Tuple::tail_table_row_string(std::ostream &os, int type) { size_t col2 = 0; const std::vector<std::shared_ptr<TupleValue>> &values = this->values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { //判断是否最后一行 if (col2 == values.size() - 1) { (*iter)->to_string(os); os << std::endl; } else { (*iter)->to_string(os); os << " | "; } //如果多个查询条件,考虑 需要更多考虑 if (col2 == selectComareIndex) { if (1 == type) { sp1 = *iter; } else if (2 == type) { sp2 = *iter; } else if (3 == type) { sp3 = *iter; } } col2++; } } void TupleSet::order_by_two() { if (nullptr == ptr_group_selects || ptr_group_selects->attr_order_num < 0) { LOG_INFO("不需要 order by"); return; } //步骤01 每个表分开计算 std::vector<RelAttr> attr_order_by1; std::vector<RelAttr> attr_order_by2; for (int i = ptr_group_selects->attr_order_num - 1; i >= 0; i--) { const std::vector<TupleField> &fields = schema1_.fields(); for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end(); iter != end; ++iter) { if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_order_by[i].attribute_name) && 0 == strcmp(iter->table_name(), ptr_group_selects->attr_order_by[i].relation_name)) { attr_order_by1.push_back(ptr_group_selects->attr_order_by[i]); } } } for (int i = ptr_group_selects->attr_order_num - 1; i >= 0; i--) { const std::vector<TupleField> &fields2 = schema2_.fields(); for (std::vector<TupleField>::const_iterator iter2 = fields2.begin(), end = fields2.end(); iter2 != end; ++iter2) { if (0 == strcmp(iter2->field_name(), ptr_group_selects->attr_order_by[i].attribute_name) && 0 == strcmp(iter2->table_name(), ptr_group_selects->attr_order_by[i].relation_name)) { attr_order_by2.push_back(ptr_group_selects->attr_order_by[i]); } } } if (attr_order_by1.size() == 0 && attr_order_by2.size() == 0) { LOG_INFO(" 失败 "); return; } //步骤2:统计排序关键字 在rows中的位置 std::vector<int> order_index1; order_index1.clear(); std::vector<int> order_index2; order_index2.clear(); std::map<int, int> value_key1; //index-key std::map<int, int> value_key2; //index-key //key --->index for (int cols = 0; cols < attr_order_by1.size(); cols++) { const std::vector<TupleField> &fields = schema1_.fields(); int index1 = 0; for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end(); iter != end; ++iter) { if (0 == strcmp(iter->field_name(), attr_order_by1[cols].attribute_name)) { order_index1.push_back(index1); value_key1[index1] = cols; LOG_INFO("题目:排序 >>>>>> cols=%d,index1=%d,name=%s", cols, index1, attr_order_by1[cols].attribute_name); } index1++; } } //key --->index for (int cols = 0; cols < attr_order_by2.size(); cols++) { const std::vector<TupleField> &fields = schema2_.fields(); int index2 = 0; for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end(); iter != end; ++iter) { if (0 == strcmp(iter->field_name(), attr_order_by2[cols].attribute_name)) { order_index2.push_back(index2); value_key2[index2] = cols; LOG_INFO("题目:排序 >>>>>> cols=%d,index2=%d,name=%s", cols, index2, attr_order_by2[cols].attribute_name); } index2++; } } //03 开始排序 if (order_index1.size() > 0) { LOG_INFO("排序 order-by1 开始排序 order_index=%d", order_index1.size()); auto sortRuleLambda1 = [=](const Tuple &s1, const Tuple &s2) -> bool { //std::vector<std::shared_ptr<TupleValue>> values_; std::vector<std::shared_ptr<TupleValue>> sp1; std::vector<std::shared_ptr<TupleValue>> sp2; //根据位置--查找value for (int i = 0; i < order_index1.size(); i++) { sp1.push_back(s1.get_pointer(order_index1[i])); sp2.push_back(s2.get_pointer(order_index1[i])); } //多个字段如何比较呀? for (int op_index = 0; op_index < order_index1.size(); op_index++) { int op_comp = 0; std::shared_ptr<TupleValue> sp_1 = sp1[op_index]; std::shared_ptr<TupleValue> sp_2 = sp2[op_index]; if (sp_1 && sp_2) { op_comp = sp_1->compare(*sp_2); } //不相等才比较 ,相等下一个 if (op_comp != 0) { int index_order = value_key1.at(order_index1[op_index]); if (CompOp::ORDER_ASC == attr_order_by1[index_order].is_asc) { LOG_INFO("排序 order-by ORDER_ASC op_index=%d, order_index=%d,name=%s", op_index, order_index1.size(), attr_order_by1[index_order].attribute_name); return op_comp < 0; //true } else if (CompOp::ORDER_DESC == attr_order_by1[index_order].is_asc) { LOG_INFO("排序 order-by ORDER_DESC op_index=%d, order_index=%d,name=%s", op_index, order_index1.size(), attr_order_by1[index_order].attribute_name); return op_comp > 0; //true } else { LOG_INFO("排序 order-by err order op_index=%d, order_index=%d,name=%s", op_index, order_index1.size(), attr_order_by1[index_order].attribute_name); } } } ////多个字段如何比较呀? //为什么std::sort比较函数在参数相等时返回false? return false; }; if (tuples1_.size() > 0) { std::sort(tuples1_.begin(), tuples1_.end(), sortRuleLambda1); } } //03 开始排序 if (order_index2.size() > 0) { LOG_INFO("排序 order-by2 开始排序 order_index=%d", order_index2.size()); auto sortRuleLambda2 = [=](const Tuple &s1, const Tuple &s2) -> bool { //std::vector<std::shared_ptr<TupleValue>> values_; std::vector<std::shared_ptr<TupleValue>> sp1; std::vector<std::shared_ptr<TupleValue>> sp2; //根据位置--查找value for (int i = 0; i < order_index2.size(); i++) { sp1.push_back(s1.get_pointer(order_index2[i])); sp2.push_back(s2.get_pointer(order_index2[i])); } //多个字段如何比较呀? for (int op_index = 0; op_index < order_index2.size(); op_index++) { int op_comp = 0; std::shared_ptr<TupleValue> sp_1 = sp1[op_index]; std::shared_ptr<TupleValue> sp_2 = sp2[op_index]; if (sp_1 && sp_2) { op_comp = sp_1->compare(*sp_2); } //不相等才比较 ,相等下一个 if (op_comp != 0) { //int index_order = order_index2.size() - op_index - 1; int index_order = value_key2.at(order_index2[op_index]); if (CompOp::ORDER_ASC == attr_order_by2[index_order].is_asc) { LOG_INFO("排序 order-by ORDER_ASC op_index=%d, order_index=%d,name=%s", op_index, order_index2.size(), attr_order_by2[index_order].attribute_name); return op_comp < 0; //true } else if (CompOp::ORDER_DESC == attr_order_by2[index_order].is_asc) { LOG_INFO("排序 order-by ORDER_DESC op_index=%d, order_index=%d,name=%s", op_index, order_index2.size(), attr_order_by2[index_order].attribute_name); return op_comp > 0; //true } else { LOG_INFO("排序 order-by err order op_index=%d, order_index=%d,name=%s", op_index, order_index2.size(), attr_order_by2[index_order].attribute_name); } } } ////多个字段如何比较呀? //为什么std::sort比较函数在参数相等时返回false? return false; }; if (tuples2_.size() > 0) { std::sort(tuples2_.begin(), tuples2_.end(), sortRuleLambda2); } } } void TupleSet::join_table_for_order_by(const Tuple &item_left, const Tuple &item_right) { Tuple merge; const std::vector<std::shared_ptr<TupleValue>> &values_left = item_left.values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_left.begin(), end = values_left.end(); iter != end; ++iter) { merge.add(*iter); } const std::vector<std::shared_ptr<TupleValue>> &values_right = item_right.values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_right.begin(), end = values_right.end(); iter != end; ++iter) { merge.add(*iter); } join_tuples.push_back(std::move(merge)); } void TupleSet::join_table_for_group_by(const Tuple &item_left, const Tuple &item_right) { //对Tuple深度拷贝,不能= Tuple merge; const std::vector<std::shared_ptr<TupleValue>> &values_left = item_left.values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_left.begin(), end = values_left.end(); iter != end; ++iter) { merge.add(*iter); } const std::vector<std::shared_ptr<TupleValue>> &values_right = item_right.values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_right.begin(), end = values_right.end(); iter != end; ++iter) { merge.add(*iter); } join_tuples_group.push_back(std::move(merge)); } void TupleSet::sort_table_for_order_by() { //依赖数据结构: //std::vector<Tuple> join_tuples; 数据 // Selects* ptr_group_selects =nullptr; 排序条件 // TupleSchema schema_; 有可能是old //if (old_schema.get_size() > 0) //排序 order-by int order_by_num = -1; RelAttr *ptr_attr_order_by = nullptr; if (ptr_group_selects && ptr_group_selects->attr_order_num > 0) { order_by_num = ptr_group_selects->attr_order_num; ptr_attr_order_by = ptr_group_selects->attr_order_by; } if (order_by_num > 0) { //order by //std::vector<Tuple> tuples_; //一个表头信息 //TupleSchema schema_; //一个表内容信息 //SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME; //key ---index //index ---key std::vector<int> key_value; std::map<int, int> value_key; key_value.clear(); value_key.clear(); for (int i = ptr_group_selects->attr_order_num - 1; i >= 0; i--) { const std::vector<TupleField> &fields = schema_.fields(); //决定了value 顺序 int index = 0; for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end(); iter != end; ++iter) { if (ptr_group_selects->attr_order_by[i].relation_name) { if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_order_by[i].attribute_name) && 0 == strcmp(iter->table_name(), ptr_group_selects->attr_order_by[i].relation_name)) { key_value.push_back(index); value_key[index] = i; LOG_INFO(" >>>>>order-by index=%d,table_name=%s,attribute_name=%s", index, iter->table_name(), iter->field_name()); break; } } else { if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_order_by[i].attribute_name)) { key_value.push_back(index); value_key[index] = i; LOG_INFO(" >>>>>order-by index=%d,table_name=%s,attribute_name=%s", index, iter->table_name(), iter->field_name()); break; } } index++; } } if (order_by_num != key_value.size()) { LOG_INFO("排序 order-by 失败 order_by_num != order_index.size()"); return; } auto sortRuleLambda = [=](const Tuple &s1, const Tuple &s2) -> bool { std::vector<std::shared_ptr<TupleValue>> sp1; std::vector<std::shared_ptr<TupleValue>> sp2; //key -value //SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME; // 排序数据 for (int i = 0; i < key_value.size(); i++) { sp1.push_back(s1.get_pointer(key_value[i])); sp2.push_back(s2.get_pointer(key_value[i])); //字段:ID, SCORE, NAME; //字段之间顺序 //key_value[i]--对应rows的位置 //rows 对应的值 // i //i -value---key-id } //字段之间顺序 for (int op_index = 0; op_index < key_value.size(); op_index++) { int op_comp = 0; std::shared_ptr<TupleValue> sp_1 = sp1[op_index]; std::shared_ptr<TupleValue> sp_2 = sp2[op_index]; if (sp_1 && sp_2) { op_comp = sp_1->compare(*sp_2); } //不相等才比较 ,相等下一个 if (op_comp != 0) { int index_order = value_key.at(key_value[op_index]); if (CompOp::ORDER_ASC == ptr_attr_order_by[index_order].is_asc) { LOG_INFO("排序 order-by ORDER_ASC value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_order_by[index_order].attribute_name); return op_comp < 0; //true } else if (CompOp::ORDER_DESC == ptr_attr_order_by[index_order].is_asc) { LOG_INFO("排序 order-by ORDER_DESC value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_order_by[index_order].attribute_name); return op_comp > 0; //true } else { LOG_INFO("排序 order-by err..... value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_order_by[index_order].attribute_name); } } } ////多个字段如何比较呀? //为什么std::sort比较函数在参数相等时返回false? return false; }; if (join_tuples.size() > 0) { std::sort(join_tuples.begin(), join_tuples.end(), sortRuleLambda); } } } void TupleSet::join_tuples_to_print(std::ostream &os) { os.clear(); for (const Tuple &item : join_tuples) { //第n-1列 const std::vector<std::shared_ptr<TupleValue>> &values = item.values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = --values.end(); iter != end; ++iter) { (*iter)->to_string(os); os << " | "; } //最后一列 values.back()->to_string(os); os << std::endl; } } void TupleSet::sort_table_for_group_by(std::vector<int> &key_value, std::map<int, int> &value_key) { //依赖数据结构: // std::vector<Tuple> tuples_; //一个表头信息 // TupleSchema schema_; //一个表内容信息 // Selects* ptr_group_selects =nullptr; 排序条件 //排序 order-by int group_by_num = -1; RelAttr *ptr_attr_group_by = nullptr; if (ptr_group_selects && ptr_group_selects->attr_group_num > 0) { group_by_num = ptr_group_selects->attr_group_num; ptr_attr_group_by = ptr_group_selects->attr_group_by; } if (group_by_num > 0) { //SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME; //SELECT ID, AVG(SCORE) FROM T_GROUP_BY GROUP BY ID; //key ---index //index ---key //std::vector<int> key_value; //std::map<int, int> value_key; key_value.clear(); value_key.clear(); for (int i = ptr_group_selects->attr_group_num - 1; i >= 0; i--) { const std::vector<TupleField> &fields = schema_.fields(); //决定了value 顺序 int index = 0; for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end(); iter != end; ++iter) { //有表名 if (ptr_group_selects->attr_group_by[i].relation_name) { if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_group_by[i].attribute_name) && 0 == strcmp(iter->table_name(), ptr_group_selects->attr_group_by[i].relation_name)) { key_value.push_back(index); value_key[index] = i; LOG_INFO(" >>>>>order-by index=%d,table_name=%s,attribute_name=%s", index, iter->table_name(), iter->field_name()); break; } } else { //无表名 if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_group_by[i].attribute_name)) { key_value.push_back(index); value_key[index] = i; LOG_INFO(" >>>>>order-by index=%d,table_name=%s,attribute_name=%s", index, iter->table_name(), iter->field_name()); break; } } index++; } } if (group_by_num != key_value.size()) { LOG_INFO("排序 order-by 失败 order_by_num != order_index.size()"); return; } auto sortRuleLambda = [=](const Tuple &s1, const Tuple &s2) -> bool { std::vector<std::shared_ptr<TupleValue>> sp1; std::vector<std::shared_ptr<TupleValue>> sp2; //key -value //SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME; // 排序数据 for (int i = 0; i < key_value.size(); i++) { sp1.push_back(s1.get_pointer(key_value[i])); sp2.push_back(s2.get_pointer(key_value[i])); //字段:ID, SCORE, NAME; //字段之间顺序 //key_value[i]--对应rows的位置 //rows 对应的值 // i //i -value---key-id } //字段之间顺序 for (int op_index = 0; op_index < key_value.size(); op_index++) { int op_comp = 0; std::shared_ptr<TupleValue> sp_1 = sp1[op_index]; std::shared_ptr<TupleValue> sp_2 = sp2[op_index]; if (sp_1 && sp_2) { op_comp = sp_1->compare(*sp_2); } //不相等才比较 ,相等下一个 if (op_comp != 0) { int index_order = value_key.at(key_value[op_index]); if (CompOp::ORDER_ASC == ptr_attr_group_by[index_order].is_asc) { LOG_INFO("排序 order-by ORDER_ASC value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_group_by[index_order].attribute_name); return op_comp < 0; //true } else if (CompOp::ORDER_DESC == ptr_attr_group_by[index_order].is_asc) { LOG_INFO("排序 order-by ORDER_DESC value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_group_by[index_order].attribute_name); return op_comp > 0; //true } else { LOG_INFO("排序 order-by err..... value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_group_by[index_order].attribute_name); } } } ////多个字段如何比较呀? //为什么std::sort比较函数在参数相等时返回false? return false; }; if (tuples_.size() > 0) { std::sort(tuples_.begin(), tuples_.end(), sortRuleLambda); } } } void TupleSet::sort_two_table_for_group_by(std::vector<int> &key_value, std::map<int, int> &value_key) { //依赖数据结构: // std::vector<Tuple> tuples_; //一个表头信息 // TupleSchema schema_; //一个表内容信息 // Selects* ptr_group_selects =nullptr; 排序条件 //排序 order-by LOG_INFO("sort_two_table_for_group_by begin"); int group_by_num = -1; RelAttr *ptr_attr_group_by = nullptr; if (ptr_group_selects && ptr_group_selects->attr_group_num > 0) { group_by_num = ptr_group_selects->attr_group_num; ptr_attr_group_by = ptr_group_selects->attr_group_by; } if (group_by_num > 0) { //SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME; //SELECT ID, AVG(SCORE) FROM T_GROUP_BY GROUP BY ID; //key ---index //index ---key //std::vector<int> key_value; //std::map<int, int> value_key; key_value.clear(); value_key.clear(); // schema_ 这是2个表的 汇总,注意观察是否正确 for (int i = ptr_group_selects->attr_group_num - 1; i >= 0; i--) { //const std::vector<TupleField> &fields = schema_.fields(); //决定了value 顺序 const std::vector<TupleField> &fields = old_schema.fields(); //决定了value 顺序 int index = 0; for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end(); iter != end; ++iter) { //有表名 if (ptr_group_selects->attr_group_by[i].relation_name) { if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_group_by[i].attribute_name) && 0 == strcmp(iter->table_name(), ptr_group_selects->attr_group_by[i].relation_name)) { key_value.push_back(index); value_key[index] = i; LOG_INFO(" >>>>>order-by index=%d,table_name=%s,attribute_name=%s", index, iter->table_name(), iter->field_name()); break; } } else { //无表名 if (0 == strcmp(iter->field_name(), ptr_group_selects->attr_group_by[i].attribute_name)) { key_value.push_back(index); value_key[index] = i; LOG_INFO(" >>>>>order-by index=%d,table_name=%s,attribute_name=%s", index, iter->table_name(), iter->field_name()); break; } } index++; } } if (group_by_num != key_value.size()) { LOG_INFO("sort_two_table_for_group_by 失败 order_by_num != order_index.size()"); return; } auto sortRuleLambda = [=](const Tuple &s1, const Tuple &s2) -> bool { std::vector<std::shared_ptr<TupleValue>> sp1; std::vector<std::shared_ptr<TupleValue>> sp2; //key -value //SELECT * FROM T_ORDER_BY ORDER BY ID, SCORE, NAME; // 排序数据 for (int i = 0; i < key_value.size(); i++) { sp1.push_back(s1.get_pointer(key_value[i])); sp2.push_back(s2.get_pointer(key_value[i])); //字段:ID, SCORE, NAME; //字段之间顺序 //key_value[i]--对应rows的位置 //rows 对应的值 // i //i -value---key-id } //字段之间顺序 for (int op_index = 0; op_index < key_value.size(); op_index++) { int op_comp = 0; std::shared_ptr<TupleValue> sp_1 = sp1[op_index]; std::shared_ptr<TupleValue> sp_2 = sp2[op_index]; if (sp_1 && sp_2) { op_comp = sp_1->compare(*sp_2); } //不相等才比较 ,相等下一个 if (op_comp != 0) { int index_order = value_key.at(key_value[op_index]); if (CompOp::ORDER_ASC == ptr_attr_group_by[index_order].is_asc) { LOG_INFO("排序 order-by ORDER_ASC value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_group_by[index_order].attribute_name); return op_comp < 0; //true } else if (CompOp::ORDER_DESC == ptr_attr_group_by[index_order].is_asc) { LOG_INFO("排序 order-by ORDER_DESC value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_group_by[index_order].attribute_name); return op_comp > 0; //true } else { LOG_INFO("排序 order-by err..... value=%d, key=%d,name=%s", key_value[op_index], index_order, ptr_attr_group_by[index_order].attribute_name); } } } ////多个字段如何比较呀? //为什么std::sort比较函数在参数相等时返回false? return false; }; if (join_tuples_group.size() > 0) { std::sort(join_tuples_group.begin(), join_tuples_group.end(), sortRuleLambda); } } } //排序 分组 统计 -汇总--返回 //参数写死,新增一个参数要新增一个函数. bool TupleSet::print_group_by(std::ostream &os) { //步骤:单表排序 std::vector<int> key_value; std::map<int, int> value_key; sort_table_for_group_by(key_value, value_key); if (key_value.size() <= 0 || tuples_.size() <= 0) { LOG_INFO("分组 失败,无记录"); return false; } //步骤:相同的为一组 //const int cols = schema_.size(); std::vector<std::shared_ptr<TupleValue>> sp_last; //分组条件 std::vector<std::shared_ptr<TupleValue>> sp_cur; //分组条件 std::vector<Tuple> group_tuples; //对原始数据tuples_分成不同的组 std::vector<vector<string>> output; //汇总分组统计结果 //初始化 默认第一个行记录 for (int i = 0; i < key_value.size(); i++) { sp_last.push_back(tuples_[0].get_pointer(key_value[i])); } //rows for (const Tuple &item : tuples_) { //cols sp_cur.clear(); //const std::vector<std::shared_ptr<TupleValue>> &values = item.values(); for (int i = 0; i < key_value.size(); i++) { sp_cur.push_back(item.get_pointer(key_value[i])); } bool is_group = true; for (int i = 0; i < key_value.size(); i++) { if (sp_last[i] && sp_cur[i] && 0 == sp_last[i]->compare(*sp_cur[i])) { //符合预期 } else { is_group = false; } } //相同就汇总 if (true == is_group) { LOG_INFO("同一个分组 ....add"); //constructor of tuple is not supported //emplace_back //深度拷贝一行数据 Tuple temp; const std::vector<std::shared_ptr<TupleValue>> &values_copy = item.values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_copy.begin(), end = values_copy.end(); iter != end; ++iter) { temp.add(*iter); } group_tuples.emplace_back(std::move(temp)); } else { LOG_INFO("新的分组 ............."); //不相同就统计 //统计 count_group_data(group_tuples, output); //新的一组 group_tuples.clear(); group_tuples.resize(0); Tuple temp; const std::vector<std::shared_ptr<TupleValue>> &values_copy = item.values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_copy.begin(), end = values_copy.end(); iter != end; ++iter) { temp.add(*iter); } group_tuples.emplace_back(std::move(temp)); // //新的分组条件 sp_last = sp_cur; } } //end data //最后一个分组 if (group_tuples.size() > 0) { count_group_data(group_tuples, output); } //步骤:输出 if (output.size() == 0) { LOG_INFO(" 题目 分组group-by 失败,没有任何记录"); } for (int rows = 0; rows < output.size(); rows++) { int cols = output[rows].size() - 1; for (int i = 0; i <= cols; i++) { //最后一行 if (i == cols) { os << output[rows][i]; os << std::endl; } else { os << output[rows][i]; os << " | "; } } } return true; } //统计 void TupleSet::count_group_data(std::vector<Tuple> &group_tuples, std::vector<vector<string>> &output) { if (group_tuples.size() == 0) { LOG_INFO("group_tuples is 0"); } LOG_INFO("count_group_data group_tuples.size=%d ", group_tuples.size()); vector<string> total; //根据schema产生一行记录 const std::vector<TupleField> &fields = schema_.fields(); int cols = 0; //遍历n个元素. for (std::vector<TupleField>::const_iterator iter = fields.begin(), end = fields.end(); iter != end; ++iter) { FunctionType window_function = iter->get_function_type(); if (FunctionType::FUN_COUNT_ALL_ALl == window_function || FunctionType::FUN_COUNT_ALL == window_function || FunctionType::FUN_COUNT == window_function) { //rows std::set<std::shared_ptr<TupleValue>> count; count.clear(); for (const Tuple &item : group_tuples) { const std::vector<std::shared_ptr<TupleValue>> &values = item.values(); int colIndex = 0; //cols for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { //(*iter)->to_string(os); if (colIndex == cols) { //std::shared_ptr<TupleValue> temp = *iter; count.insert(*iter); break; } colIndex++; } } std::stringstream ss; ss << count.size(); total.push_back(ss.str()); } else if (FunctionType::FUN_MAX == window_function) { std::shared_ptr<TupleValue> maxValue; //rows for (const Tuple &item : group_tuples) { const std::vector<std::shared_ptr<TupleValue>> &values = item.values(); if (0 == values.size()) { continue; } int colIndex = 0; //cols for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { //(*iter)->to_string(os); if (colIndex == cols) { std::shared_ptr<TupleValue> temp = *iter; if (nullptr == maxValue) { maxValue = temp; } else { if (maxValue->compare(*temp) < 0) { maxValue = temp; } } break; } colIndex++; } } std::stringstream ss; maxValue->to_string(ss); total.push_back(ss.str()); } else if (FunctionType::FUN_MIN == window_function) { std::shared_ptr<TupleValue> minValue; for (const Tuple &item : group_tuples) { int colIndex = 0; //列 const std::vector<std::shared_ptr<TupleValue>> &values = item.values(); if (0 == values.size()) { continue; } for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { if (colIndex == cols) { std::shared_ptr<TupleValue> temp = *iter; { if (nullptr == minValue) { minValue = *iter; } else { std::shared_ptr<TupleValue> temp = *iter; if (minValue->compare(*temp) > 0) { minValue = temp; } } } break; //get } colIndex++; } } //end std::stringstream ss; minValue->to_string(ss); total.push_back(ss.str()); } else if (FunctionType::FUN_AVG == window_function) { std::shared_ptr<TupleValue> sumValue; int count = 0; bool exits_null_value = false; for (const Tuple &item : group_tuples) { int colIndex = 0; bool null_able = true; //第n列 const std::vector<std::shared_ptr<TupleValue>> &values = item.values(); if (0 == values.size()) { continue; } for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { //(*iter)->to_string(os); if (colIndex == cols) { std::shared_ptr<TupleValue> temp = *iter; if (AttrType::NULLVALUES == temp->get_type()) { //不处理 null_able = false; exits_null_value = true; } else { if (nullptr == sumValue) { sumValue = temp; } else { sumValue->add_value(*temp); } } break; //get } colIndex++; } if (true == null_able) { count++; } } //end //防溢出求平均算法 if (0 == count) { if (exits_null_value == true) { total.push_back("NULL"); } } std::stringstream ss; sumValue->to_avg(count, ss); total.push_back(ss.str()); } else if (FunctionType::FUN_NO == window_function) { LOG_INFO(">>>>>>FunctionType::FUN_NO =%s ", iter->field_name()); std::shared_ptr<TupleValue> itemValue; //只读取其中的一行 if (group_tuples.size() > 0) { //第n列 int colIndex = 0; const std::vector<std::shared_ptr<TupleValue>> &values = group_tuples[0].values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { //(*iter)->to_string(os); if (colIndex == cols) { itemValue = *iter; break; //get } colIndex++; } std::stringstream ss; itemValue->to_string(ss); total.push_back(ss.str()); } } else { LOG_INFO(">>>>>>errrrrrrrrrrrr=%s ", iter->field_name()); } cols++; } //const std::vector<TupleField> &fields = schema_.fields(); output.push_back(total); } //代码重复:前期设计不合适导致,2个一样的逻辑 //需要优化 void TupleSet::count_two_table_group_data(std::vector<Tuple> &group_tuples, std::vector<vector<string>> &output) { if (group_tuples.size() == 0) { LOG_INFO("count_two_table_group_data is 0"); } LOG_INFO("count_two_table_group_data group_tuples.size=%d ", group_tuples.size()); vector<string> total; //根据schema产生一行记录 const std::vector<TupleField> &fields = old_schema.fields(); int cols = 0; //遍历n个元素. for (std::vector<TupleField>::const_iterator field_iter = fields.begin(), end = fields.end(); field_iter != end; ++field_iter) { if (false == field_iter->visible()) { LOG_INFO(">>>>> group by 不可见字段 index =%d,name =%s ", cols, field_iter->field_name()); cols++; continue; } FunctionType window_function = field_iter->get_function_type(); if (FunctionType::FUN_COUNT_ALL_ALl == window_function || FunctionType::FUN_COUNT_ALL == window_function || FunctionType::FUN_COUNT == window_function) { //rows std::set<std::shared_ptr<TupleValue>> count; count.clear(); for (const Tuple &item : group_tuples) { const std::vector<std::shared_ptr<TupleValue>> &values = item.values(); int colIndex = 0; //cols for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { //(*iter)->to_string(os); if (colIndex == cols) { //std::shared_ptr<TupleValue> temp = *iter; count.insert(*iter); break; } colIndex++; } } std::stringstream ss; ss << count.size(); total.push_back(ss.str()); LOG_INFO(">>>>> group by count index =%d,name =%s,value =%d ", cols, field_iter->field_name(), count.size()); } else if (FunctionType::FUN_MAX == window_function) { std::shared_ptr<TupleValue> maxValue; //rows for (const Tuple &item : group_tuples) { const std::vector<std::shared_ptr<TupleValue>> &values = item.values(); if (0 == values.size()) { continue; } int colIndex = 0; //cols for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { //(*iter)->to_string(os); if (colIndex == cols) { std::shared_ptr<TupleValue> temp = *iter; if (nullptr == maxValue) { maxValue = temp; } else { if (maxValue->compare(*temp) < 0) { maxValue = temp; } } break; } colIndex++; } } std::stringstream ss; maxValue->to_string(ss); total.push_back(ss.str()); LOG_INFO(">>>>> group by max index =%d,name =%s,value =%s ", cols, field_iter->field_name(), maxValue->print_string().c_str()); } else if (FunctionType::FUN_MIN == window_function) { std::shared_ptr<TupleValue> minValue; for (const Tuple &item : group_tuples) { int colIndex = 0; //列 const std::vector<std::shared_ptr<TupleValue>> &values = item.values(); if (0 == values.size()) { continue; } for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { if (colIndex == cols) { std::shared_ptr<TupleValue> temp = *iter; { if (nullptr == minValue) { minValue = *iter; } else { std::shared_ptr<TupleValue> temp = *iter; if (minValue->compare(*temp) > 0) { minValue = temp; } } } break; //get } colIndex++; } } //end std::stringstream ss; minValue->to_string(ss); total.push_back(ss.str()); LOG_INFO(">>>>> group by min index =%d,name =%s,value =%s ", cols, field_iter->field_name(), minValue->print_string().c_str()); } else if (FunctionType::FUN_AVG == window_function) { std::shared_ptr<TupleValue> sumValue; int count = 0; for (const Tuple &item : group_tuples) { int colIndex = 0; //第n列 const std::vector<std::shared_ptr<TupleValue>> &values = item.values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { //(*iter)->to_string(os); if (colIndex == cols) { std::shared_ptr<TupleValue> temp = *iter; if (nullptr == sumValue) { sumValue = temp; } else { sumValue->add_value(*temp); } break; //get } colIndex++; } count++; } //end //防溢出求平均算法 LOG_INFO(">>>>> group by >>>>>>>>>>>>>>>>>>>>>>> ", count); if (0 == count) { total.push_back("NULL"); } else { std::stringstream ss; sumValue->to_avg(count, ss); total.push_back(ss.str()); LOG_INFO(">>>>> group by avg index =%d,name =%s ", cols, field_iter->field_name()); } } else if (FunctionType::FUN_NO == window_function) { LOG_INFO(">>>>>> FunctionType::FUN_NO =%s ", field_iter->field_name()); std::shared_ptr<TupleValue> itemValue; //只读取其中的一行 if (group_tuples.size() > 0) { //第n列 int colIndex = 0; const std::vector<std::shared_ptr<TupleValue>> &values = group_tuples[0].values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values.begin(), end = values.end(); iter != end; ++iter) { //(*iter)->to_string(os); if (colIndex == cols) { itemValue = *iter; // break; //get } colIndex++; } std::stringstream ss; itemValue->to_string(ss); total.push_back(ss.str()); LOG_INFO(">>>>> group by index =%d,name =%s,value =%s ", cols, field_iter->field_name(), itemValue->print_string().c_str()); } } else { LOG_INFO(">>>>>>errrrrrrrrrrrr=%s ", field_iter->field_name()); } cols++; } //const std::vector<TupleField> &fields = schema_.fields(); output.push_back(total); } //排序 分组 统计 -汇总--返回 //参数写死,新增一个参数要新增一个函数. bool TupleSet::print_two_table_group_by(std::ostream &os) { //步骤:单表排序 std::vector<int> key_value; std::map<int, int> value_key; sort_two_table_for_group_by(key_value, value_key); if (key_value.size() <= 0 || join_tuples_group.size() <= 0) { LOG_INFO("分组 失败,无记录"); return false; } //步骤:相同的为一组 //const int cols = schema_.size(); std::vector<std::shared_ptr<TupleValue>> sp_last; //分组条件 std::vector<std::shared_ptr<TupleValue>> sp_cur; //分组条件 std::vector<Tuple> onece_group_tuples; //对原始数据tuples_分成不同的组 std::vector<vector<string>> output; //汇总分组统计结果 output.clear(); onece_group_tuples.clear(); //初始化 默认第一个行记录 //std::vector<Tuple> join_tuples_group; //sql:1 笛卡尔积 2 过滤 3 排序 4 分组 5 显示。 //tuples_ for (int i = 0; i < key_value.size(); i++) { sp_last.push_back(join_tuples_group[0].get_pointer(key_value[i])); } //rows for (const Tuple &item : join_tuples_group) { //cols sp_cur.clear(); //const std::vector<std::shared_ptr<TupleValue>> &values = item.values(); for (int i = 0; i < key_value.size(); i++) { sp_cur.push_back(item.get_pointer(key_value[i])); } bool is_group = true; for (int i = 0; i < key_value.size(); i++) { if (sp_last[i] && sp_cur[i] && 0 == sp_last[i]->compare(*sp_cur[i])) { //符合预期 } else { is_group = false; } } //相同就汇总 if (true == is_group) { LOG_INFO("同一个分组 ....add"); //constructor of tuple is not supported //emplace_back //深度拷贝一行数据 Tuple temp; const std::vector<std::shared_ptr<TupleValue>> &values_copy = item.values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_copy.begin(), end = values_copy.end(); iter != end; ++iter) { temp.add(*iter); } onece_group_tuples.push_back(std::move(temp)); } else { LOG_INFO("新的分组 ............."); //不相同就统计 //统计 //count_group_data(group_tuples, output); count_two_table_group_data(onece_group_tuples, output); //新的一组 onece_group_tuples.clear(); onece_group_tuples.resize(0); onece_group_tuples.reserve(0); Tuple temp; const std::vector<std::shared_ptr<TupleValue>> &values_copy = item.values(); for (std::vector<std::shared_ptr<TupleValue>>::const_iterator iter = values_copy.begin(), end = values_copy.end(); iter != end; ++iter) { temp.add(*iter); } onece_group_tuples.push_back(std::move(temp)); // //新的分组条件 sp_last = sp_cur; } } //end data //最后一个分组 if (onece_group_tuples.size() > 0) { count_two_table_group_data(onece_group_tuples, output); } //步骤:输出 if (output.size() == 0) { LOG_INFO(" 题目 分组group-by 失败,没有任何记录"); } for (int rows = 0; rows < output.size(); rows++) { int cols = output[rows].size() - 1; for (int i = 0; i <= cols; i++) { //最后一行 if (i == cols) { os << output[rows][i]; os << std::endl; } else { os << output[rows][i]; os << " | "; } } } return true; }
27.525826
169
0.527694
watchpoints
99e68d7a8237969ce37e075a3c52a118ab548c78
3,777
cxx
C++
main/svx/source/sdr/contact/viewobjectcontactofgroup.cxx
Alan-love/openoffice
09be380f1ebba053dbf269468ff884f5d26ce1e4
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/svx/source/sdr/contact/viewobjectcontactofgroup.cxx
Alan-love/openoffice
09be380f1ebba053dbf269468ff884f5d26ce1e4
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/svx/source/sdr/contact/viewobjectcontactofgroup.cxx
Alan-love/openoffice
09be380f1ebba053dbf269468ff884f5d26ce1e4
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <svx/sdr/contact/viewobjectcontactofgroup.hxx> #include <svx/sdr/contact/displayinfo.hxx> #include <svx/sdr/contact/objectcontact.hxx> #include <basegfx/numeric/ftools.hxx> #include <drawinglayer/primitive2d/groupprimitive2d.hxx> #include <basegfx/tools/canvastools.hxx> #include <svx/sdr/contact/viewcontact.hxx> ////////////////////////////////////////////////////////////////////////////// using namespace com::sun::star; ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace contact { ViewObjectContactOfGroup::ViewObjectContactOfGroup(ObjectContact& rObjectContact, ViewContact& rViewContact) : ViewObjectContactOfSdrObj(rObjectContact, rViewContact) { } ViewObjectContactOfGroup::~ViewObjectContactOfGroup() { } drawinglayer::primitive2d::Primitive2DSequence ViewObjectContactOfGroup::getPrimitive2DSequenceHierarchy(DisplayInfo& rDisplayInfo) const { drawinglayer::primitive2d::Primitive2DSequence xRetval; // check model-view visibility if(isPrimitiveVisible(rDisplayInfo)) { const sal_uInt32 nSubHierarchyCount(GetViewContact().GetObjectCount()); if(nSubHierarchyCount) { const sal_Bool bDoGhostedDisplaying( GetObjectContact().DoVisualizeEnteredGroup() && !GetObjectContact().isOutputToPrinter() && GetObjectContact().getActiveViewContact() == &GetViewContact()); if(bDoGhostedDisplaying) { rDisplayInfo.ClearGhostedDrawMode(); } // create object hierarchy xRetval = getPrimitive2DSequenceSubHierarchy(rDisplayInfo); if(xRetval.hasElements()) { // get ranges const drawinglayer::geometry::ViewInformation2D& rViewInformation2D(GetObjectContact().getViewInformation2D()); const ::basegfx::B2DRange aObjectRange(drawinglayer::primitive2d::getB2DRangeFromPrimitive2DSequence(xRetval, rViewInformation2D)); const basegfx::B2DRange aViewRange(rViewInformation2D.getViewport()); // check geometrical visibility if(!aViewRange.isEmpty() && !aViewRange.overlaps(aObjectRange)) { // not visible, release xRetval.realloc(0); } } if(bDoGhostedDisplaying) { rDisplayInfo.SetGhostedDrawMode(); } } else { // draw replacement object for group. This will use ViewContactOfGroup::createViewIndependentPrimitive2DSequence // which creates the replacement primitives for an empty group xRetval = ViewObjectContactOfSdrObj::getPrimitive2DSequenceHierarchy(rDisplayInfo); } } return xRetval; } } // end of namespace contact } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof
33.723214
139
0.670638
Alan-love
99e885ebda86f7efb00e57cea9fe67418be22686
3,680
cpp
C++
LeetCode/C++/221. Maximal Square.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-18T05:14:28.000Z
2022-03-08T07:00:08.000Z
LeetCode/C++/221. Maximal Square.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
LeetCode/C++/221. Maximal Square.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
//Approach #1 Brute Force [Accepted] //Runtime: 24 ms, faster than 33.17% of C++ online submissions for Maximal Square. //Memory Usage: 8.2 MB, less than 100.00% of C++ online submissions for Maximal Square. //time: O((mn)^2), space: O(1) class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { int m = matrix.size(); if(m == 0) return 0; int n = matrix[0].size(); int maxslen = 0; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(matrix[i][j] == '0') continue; int slen = 1; bool valid = true; while(slen + i < m && slen + j < n && valid){ for(int k = j; k <= j + slen; k++){ //i+slen: examine the (possible) last row of the square if(matrix[i+slen][k] != '1'){ valid = false; break; } } for(int k = i; k <= i + slen; k++){ //j+slen: examine the (possible) last col of the square if(matrix[k][j+slen] != '1'){ valid = false; break; } } if(valid){ slen++; } } maxslen = max(maxslen, slen); } } return maxslen * maxslen; } }; //Approach #2 (Dynamic Programming) [Accepted] //Runtime: 24 ms, faster than 33.17% of C++ online submissions for Maximal Square. //Memory Usage: 8.7 MB, less than 100.00% of C++ online submissions for Maximal Square. //time: O(mn), space: O(mn) class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { int m = matrix.size(); if(m == 0) return 0; int n = matrix[0].size(); int maxslen = 0; vector<vector<int>> dp(m+1, vector(n+1, 0)); for(int i = 1; i <= m; i++){ for(int j = 1; j <= n; j++){ if(matrix[i-1][j-1] == '0') continue; //check top, left and top-left dp[i][j] = min({dp[i-1][j], dp[i][j-1], dp[i-1][j-1]}) + 1; maxslen = max(maxslen, dp[i][j]); } } return maxslen * maxslen; } }; //DP, O(n) space //Runtime: 20 ms, faster than 77.64% of C++ online submissions for Maximal Square. //Memory Usage: 8.6 MB, less than 100.00% of C++ online submissions for Maximal Square. //time: O(mn), space: O(n) class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { int m = matrix.size(); if(m == 0) return 0; int n = matrix[0].size(); int maxslen = 0; vector<int> dp(n+1, 0); int prev = 0; //top-left for(int i = 1; i <= m; i++){ for(int j = 1; j <= n; j++){ /* dp[j] of previous row it will be used as 'prev' in next j, at that time, it means the dp value of top-left corner */ int tmp = dp[j]; if(matrix[i-1][j-1] == '0'){ dp[j] = 0; }else{ //check top, left and top-left dp[j] = min({dp[j], dp[j-1], prev}) + 1; maxslen = max(maxslen, dp[j]); } prev = tmp; } } return maxslen * maxslen; } };
32.857143
87
0.416033
shreejitverma
99e97479fb174c208fe45f7df3dffd7c6b944cd5
6,657
cpp
C++
Game/Client/CEGUIFalagardEx/FalChatChannel.cpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Game/Client/CEGUIFalagardEx/FalChatChannel.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Game/Client/CEGUIFalagardEx/FalChatChannel.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
#include "FalChatChannel.h" #include "CEGUIPropertyHelper.h" #include "falagard/CEGUIFalWidgetLookManager.h" #include "falagard/CEGUIFalWidgetLookFeel.h" // Start of CEGUI namespace section namespace CEGUI { //=================================================================================== // // FalagardChatChannel // //=================================================================================== const utf8 FalagardChatChannel::WidgetTypeName[] = "Falagard/ChatChannel"; FalagardChatChannelProperties::ItemSize FalagardChatChannel::d_itemSizeProperty; FalagardChatChannelProperties::AnchorPosition FalagardChatChannel::d_anchorPositionProperty; FalagardChatChannelProperties::HoverChannelBkg FalagardChatChannel::d_hoverChannelBkgProperty; FalagardChatChannelProperties::HoverChannel FalagardChatChannel::d_hoverChannelProperty; FalagardChatChannelProperties::HoverChannelName FalagardChatChannel::d_hoverChannelNameProperty; FalagardChatChannel::FalagardChatChannel(const String& type, const String& name) : Window(type, name), d_itemSize(0.0, 0.0), d_anchorPosition(0.0, 0.0), d_hoverChannelBkg(0), d_hoverChannel(-1), d_lastHoverChannel(-1), d_pushed(false) { addChatChannelProperties(); setAlwaysOnTop(true); } FalagardChatChannel::~FalagardChatChannel() { } void FalagardChatChannel::addChatChannelProperties(void) { CEGUI_START_ADD_STATICPROPERTY( FalagardChatChannel ) CEGUI_ADD_STATICPROPERTY( &d_itemSizeProperty ); CEGUI_ADD_STATICPROPERTY( &d_anchorPositionProperty ); CEGUI_ADD_STATICPROPERTY( &d_hoverChannelBkgProperty ); CEGUI_ADD_STATICPROPERTY( &d_hoverChannelProperty ); CEGUI_ADD_STATICPROPERTY( &d_hoverChannelNameProperty ); CEGUI_END_ADD_STATICPROPERTY } void FalagardChatChannel::onMouseMove(MouseEventArgs& e) { // base class processing Window::onMouseMove(e); updateInternalState(e.position); e.handled = true; } void FalagardChatChannel::updateInternalState(const Point& ptMouse) { Point pt(ptMouse); pt.d_x -= windowToScreenX(0); pt.d_y -= windowToScreenY(0); Rect absarea(getPixelRect()); absarea.offset(Point(-absarea.d_left, -absarea.d_top)); if(absarea.isPointInRect(pt)) { float fItemHeight = absarea.getHeight()/(int)d_allChannel.size(); d_hoverChannel = (int)(pt.d_y/fItemHeight); if(d_lastHoverChannel != d_hoverChannel) { requestRedraw(); d_lastHoverChannel = d_hoverChannel; } } } void FalagardChatChannel::onMouseButtonDown(MouseEventArgs& e) { // default processing Window::onMouseButtonDown(e); if (e.button == LeftButton) { if (captureInput()) { d_pushed = true; updateInternalState(e.position); requestRedraw(); } // event was handled by us. e.handled = true; } } void FalagardChatChannel::onMouseButtonUp(MouseEventArgs& e) { // default processing Window::onMouseButtonUp(e); if (e.button == LeftButton) { releaseInput(); // event was handled by us. e.handled = true; } } void FalagardChatChannel::onMouseLeaves(MouseEventArgs& e) { // base class processing Window::onMouseLeaves(e); d_hoverChannel = -1; d_lastHoverChannel = -1; requestRedraw(); } void FalagardChatChannel::populateRenderCache(void) { // get WidgetLookFeel for the assigned look. const WidgetLookFeel& wlf = WidgetLookManager::getSingleton().getWidgetLook(d_lookName); // try and get imagery for our current state const StateImagery* imagery = &wlf.getStateImagery("Frame"); // peform the rendering operation. imagery->render(*this); const Rect rectIconSize(wlf.getNamedArea("IconSize").getArea().getPixelRect(*this)); const FontBase* font = getFont(); Rect absarea(getPixelRect()); absarea.offset(Point(-absarea.d_left, -absarea.d_top)); ColourRect final_cols(colour(1.0f, 1.0f, 1.0f)); float fItemHeight = absarea.getHeight()/(int)d_allChannel.size(); for(int i=0; i<(int)d_allChannel.size(); i++) { ChannelItem& theChannel = d_allChannel[i]; Rect rectIcon(rectIconSize); rectIcon.offset(Point(0, (fItemHeight-rectIconSize.getHeight())/2 + fItemHeight*i)); d_renderCache.cacheImage( *theChannel.d_headIcon, rectIcon, 0.0f, final_cols); Rect rectText(absarea.d_left, fItemHeight*i, absarea.d_right, fItemHeight*(i+1)); rectText.d_left += rectIcon.getWidth()+2; if(d_hoverChannelBkg && d_hoverChannel == i) { d_renderCache.cacheImage( *d_hoverChannelBkg, rectText, 0.0f, ColourRect(0xFFFF0000, 0xFFFF0000, 0xFFFF0000, 0xFFFF0000)); } d_renderCache.cacheText(this, theChannel.d_strName, font, (TextFormatting)WordWrapLeftAligned, rectText, 0.0f, final_cols); } } void FalagardChatChannel::resizeSelf(void) { float fTotalHeight = d_itemSize.d_height * (int)d_allChannel.size(); setSize(Absolute,Size(d_itemSize.d_width, fTotalHeight)); float fParentHeight = d_parent->getPixelRect().getHeight(); if(d_parent->getPixelRect().getWidth() < 1024) fParentHeight += 51; setPosition(Absolute,Point(d_anchorPosition.d_x, fParentHeight - d_anchorPosition.d_y - fTotalHeight)); } void FalagardChatChannel::clearAllChannel(void) { d_allChannel.clear(); resizeSelf(); } void FalagardChatChannel::addChannel(const String& strType, const String& strIconName, const String& strName) { ChannelItem newChannel; newChannel.d_strType = strType; newChannel.d_headIcon = PropertyHelper::stringToImage(strIconName); if(!newChannel.d_headIcon) return; newChannel.d_strName = strName; d_allChannel.push_back(newChannel); resizeSelf(); } String FalagardChatChannel::getHoverChannel(void) const { if(d_hoverChannel >= 0 && d_hoverChannel < (int)d_allChannel.size()) { return d_allChannel[d_hoverChannel].d_strType; } return String(""); } String FalagardChatChannel::getHoverChannelName(void) const { if(d_hoverChannel >= 0 && d_hoverChannel < (int)d_allChannel.size()) { return d_allChannel[d_hoverChannel].d_strName; } return String(""); } ////////////////////////////////////////////////////////////////////////// /************************************************************************* Factory Methods *************************************************************************/ ////////////////////////////////////////////////////////////////////////// Window* FalagardChatChannelFactory::createWindow(const String& name) { return new FalagardChatChannel(d_type, name); } void FalagardChatChannelFactory::destroyWindow(Window* window) { delete window; } }
28.570815
110
0.680787
hackerlank
99e9bfed3ca0114396d42df21472a9a422505ccc
3,922
cpp
C++
source/hougfx/test/hou/gfx/test_graphics_state.cpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
2
2018-04-12T20:59:20.000Z
2018-07-26T16:04:07.000Z
source/hougfx/test/hou/gfx/test_graphics_state.cpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
source/hougfx/test/hou/gfx/test_graphics_state.cpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
// Houzi Game Engine // Copyright (c) 2018 Davide Corradi // Licensed under the MIT license. #include "hou/gfx/test_gfx_base.hpp" #include "hou/gfx/graphics_state.hpp" using namespace hou; using namespace testing; namespace hou { class test_graphics_state : public test_gfx_base { public: static std::vector<blending_factor> blending_factors; static std::vector<blending_equation> blending_equations; }; std::vector<blending_factor> test_graphics_state::blending_factors{ blending_factor::zero, blending_factor::one, blending_factor::src_color, blending_factor::one_minus_src_color, blending_factor::dst_color, blending_factor::one_minus_dst_color, blending_factor::src_alpha, blending_factor::one_minus_src_alpha, blending_factor::dst_alpha, blending_factor::one_minus_dst_alpha, blending_factor::constant_color, blending_factor::one_minus_constant_color, blending_factor::constant_alpha, blending_factor::one_minus_constant_alpha, }; std::vector<blending_equation> test_graphics_state::blending_equations{ blending_equation::add, blending_equation::subtract, blending_equation::reverse_subtract, blending_equation::min, blending_equation::max, }; } // namespace hou TEST_F(test_graphics_state, set_vsync_mode) { EXPECT_EQ(vsync_mode::enabled, get_vsync_mode()); EXPECT_TRUE(set_vsync_mode(vsync_mode::disabled)); EXPECT_EQ(vsync_mode::disabled, get_vsync_mode()); if(set_vsync_mode(vsync_mode::adaptive)) { EXPECT_EQ(vsync_mode::adaptive, get_vsync_mode()); } EXPECT_TRUE(set_vsync_mode(vsync_mode::enabled)); EXPECT_EQ(vsync_mode::enabled, get_vsync_mode()); } TEST_F(test_graphics_state, multisampling_enabled) { EXPECT_TRUE(is_multisampling_enabled()); set_multisampling_enabled(true); EXPECT_TRUE(is_multisampling_enabled()); set_multisampling_enabled(false); EXPECT_FALSE(is_multisampling_enabled()); set_multisampling_enabled(false); EXPECT_FALSE(is_multisampling_enabled()); set_multisampling_enabled(true); EXPECT_TRUE(is_multisampling_enabled()); } TEST_F(test_graphics_state, blending_enabled) { EXPECT_TRUE(is_blending_enabled()); set_blending_enabled(true); EXPECT_TRUE(is_blending_enabled()); set_blending_enabled(false); EXPECT_FALSE(is_blending_enabled()); set_blending_enabled(false); EXPECT_FALSE(is_blending_enabled()); set_blending_enabled(true); EXPECT_TRUE(is_blending_enabled()); } TEST_F(test_graphics_state, source_blending_factor) { blending_factor dst_factor = get_destination_blending_factor(); EXPECT_EQ(blending_factor::src_alpha, get_source_blending_factor()); for(auto f : blending_factors) { set_source_blending_factor(f); EXPECT_EQ(f, get_source_blending_factor()); EXPECT_EQ(dst_factor, get_destination_blending_factor()); } set_source_blending_factor(blending_factor::src_alpha); } TEST_F(test_graphics_state, destination_blending_factor) { blending_factor src_factor = get_source_blending_factor(); EXPECT_EQ( blending_factor::one_minus_src_alpha, get_destination_blending_factor()); for(auto f : blending_factors) { set_destination_blending_factor(f); EXPECT_EQ(f, get_destination_blending_factor()); EXPECT_EQ(src_factor, get_source_blending_factor()); } set_destination_blending_factor(blending_factor::one_minus_src_alpha); } TEST_F(test_graphics_state, blending_equation) { EXPECT_EQ(blending_equation::add, get_blending_equation()); for(auto e : blending_equations) { set_blending_equation(e); EXPECT_EQ(e, get_blending_equation()); } set_blending_equation(blending_equation::add); } TEST_F(test_graphics_state, blending_color) { EXPECT_EQ(color::transparent(), get_blending_color()); set_blending_color(color::red()); EXPECT_EQ(color::red(), get_blending_color()); set_blending_color(color::transparent()); EXPECT_EQ(color::transparent(), get_blending_color()); }
25.633987
77
0.789393
DavideCorradiDev
99ebaad6690973f182110c0ee4954177857a8d84
3,899
cpp
C++
src/duyebase/system/duye_epoll.cpp
tencupofkaiwater/duye
72257379f91e7a0db5ffefbb7e7a74dc0a255f67
[ "Unlicense" ]
null
null
null
src/duyebase/system/duye_epoll.cpp
tencupofkaiwater/duye
72257379f91e7a0db5ffefbb7e7a74dc0a255f67
[ "Unlicense" ]
null
null
null
src/duyebase/system/duye_epoll.cpp
tencupofkaiwater/duye
72257379f91e7a0db5ffefbb7e7a74dc0a255f67
[ "Unlicense" ]
null
null
null
/************************************************************************************ ** * @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved. * *************************************************************************************/ /** * @file duye_epoll.cpp * @version * @brief * @author duye * @date 2016-03-29 * @note * * 1. 2016-03-29 duye Created this file */ #include <unistd.h> #include <string.h> #include <stdlib.h> #include <duye_sys.h> #include <duye_epoll.h> namespace duye { static const int8* DUYE_LOG_PREFIX = "duye.system.epoll"; Epoll::Epoll() : m_epollfd(-1) , m_maxEvents(0) , m_sysEvents(NULL) { m_error.setPrefix(DUYE_LOG_PREFIX); } Epoll::~Epoll() { close(); } bool Epoll::open(const uint32 maxEvents) { close(); m_maxEvents = maxEvents; m_epollfd = epoll_create(m_maxEvents); if (m_epollfd == -1) { ERROR_DUYE_LOG("%s:%d > epoll_create failed \n", __FILE__, __LINE__); return false; } m_sysEvents = (struct epoll_event*)calloc(m_maxEvents, sizeof(struct epoll_event)); if (m_sysEvents == NULL) { ERROR_DUYE_LOG("%s:%d > calloc return NULL \n", __FILE__, __LINE__); return false; } return true; } bool Epoll::close() { m_maxEvents = 0; if (m_epollfd != -1) { ::close(m_epollfd); m_epollfd = -1; } if (m_sysEvents != NULL) { free(m_sysEvents); m_sysEvents = NULL; } return true; } bool Epoll::addfd(const int32 fd, const uint32 epollMode) { if (m_epollfd == -1) { ERROR_DUYE_LOG("%s:%d > m_epollfd == -1", __FILE__, __LINE__); return false; } struct epoll_event epollEvent; bzero(&epollEvent, sizeof(struct epoll_event)); epollEvent.data.fd = fd; epollEvent.events = epollMode; int32 ret = epoll_ctl(m_epollfd, EPOLL_CTL_ADD, fd, &epollEvent); if (ret != 0) { ERROR_DUYE_LOG("[%s:%d] epoll_ctl() return = %d", __FILE__, __LINE__, ret); return false; } return true; } bool Epoll::modfd(const int32 fd, const uint32 epollMode) { if (m_epollfd == -1) { ERROR_DUYE_LOG("[%s:%d] m_epollfd == -1", __FILE__, __LINE__); return false; } struct epoll_event epollEvent; bzero(&epollEvent, sizeof(struct epoll_event)); epollEvent.data.fd = fd; epollEvent.events = epollMode; return epoll_ctl(m_epollfd, EPOLL_CTL_MOD, fd, &epollEvent) == 0 ? true : false; } bool Epoll::delfd(const int32 fd) { if (m_epollfd == -1) { ERROR_DUYE_LOG("[%s:%d] m_epollfd == -1", __FILE__, __LINE__); return false; } return epoll_ctl(m_epollfd, EPOLL_CTL_DEL, fd, NULL) == 0 ? true : false; } bool Epoll::wait(Epoll::EventList& eventList, const uint32 timeout) { if (m_epollfd == -1) { ERROR_DUYE_LOG("[%s:%d] m_epollfd == -1", __FILE__, __LINE__); return false; } int32 event_count = epoll_wait(m_epollfd, m_sysEvents, m_maxEvents, timeout); if (event_count <= 0) { return false; } for (uint32 i = 0; i < (uint32)event_count; i++) { if ((m_sysEvents[i].events & EPOLLERR) || (m_sysEvents[i].events & EPOLLHUP)) { ERROR_DUYE_LOG("[%s:%d] epoll error, close fd \n", __FILE__, __LINE__); delfd(m_sysEvents[i].data.fd); eventList.push_back(EpollEvent(m_sysEvents[i].data.fd, ERROR_FD)); continue; } else if (m_sysEvents[i].events & EPOLLIN) { eventList.push_back(EpollEvent(m_sysEvents[i].data.fd, RECV_FD)); } else if (m_sysEvents[i].events & EPOLLOUT) { eventList.push_back(EpollEvent(m_sysEvents[i].data.fd, SEND_FD)); } else { eventList.push_back(EpollEvent(m_sysEvents[i].data.fd, RECV_UN)); } } return true; } uint8* Epoll::error() { return m_error.error; } }
22.80117
87
0.583483
tencupofkaiwater
99ec5621b29c28164ae9d39445151b0e1ca0c522
1,593
cpp
C++
tests/test-uart.cpp
uav-router/uav_router
8accab304fdef749009309c60d2211db5b1793ba
[ "MIT" ]
null
null
null
tests/test-uart.cpp
uav-router/uav_router
8accab304fdef749009309c60d2211db5b1793ba
[ "MIT" ]
null
null
null
tests/test-uart.cpp
uav-router/uav_router
8accab304fdef749009309c60d2211db5b1793ba
[ "MIT" ]
null
null
null
#include "log.h" #include "ioloop.h" #include <memory> #include <iostream> void test() { auto loop = IOLoop::loop(); error_c ec = loop->handle_CtrlC(); if (ec) { std::cout<<"Ctrl-C handler error "<<ec<<std::endl; return; } auto uart = loop->uart("UartEndpoint"); { std::shared_ptr<Client> endpoint; uart->on_connect([&endpoint](std::shared_ptr<Client> cli, std::string name){ endpoint = cli; endpoint->on_close([name, &endpoint](){ std::cout<<"Close "<<name<<std::endl; //endpoint.reset(); }); endpoint->on_read([name](void* buf, int len){ std::cout<<"UART "<<name<<" ("<<len<<"): "; const char* hex = "0123456789ABCDEF"; uint8_t *arr = (uint8_t*)buf; for (int i = len; i; i--) { uint8_t b = *arr++; std::cout<<hex[(b>>4) & 0x0F]; std::cout<<hex[b & 0x0F]<<' '; } std::cout<<std::endl; }); endpoint->on_error([](const error_c& ec) { std::cout<<"UART cli error:"<<ec<<std::endl; }); std::cout<<"Connect to "<<name<<std::endl; }); uart->on_error([](const error_c& ec) { std::cout<<"UART error:"<<ec<<std::endl; }); uart->init("/dev/ttyUSB0",115200); loop->run(); } } int main() { Log::init(); Log::set_level(Log::Level::DEBUG,{"ioloop","uart"}); test(); return 0; }
31.235294
84
0.456372
uav-router
99f1d818541abfe201b61038d2e5d577c9006182
556
cpp
C++
pg_answer/259350e26d1d4c748446c198c9f3ca00.cpp
Guyutongxue/Introduction_to_Computation
062f688fe3ffb8e29cfaf139223e4994edbf64d6
[ "WTFPL" ]
8
2019-10-09T14:33:42.000Z
2020-12-03T00:49:29.000Z
pg_answer/259350e26d1d4c748446c198c9f3ca00.cpp
Guyutongxue/Introduction_to_Computation
062f688fe3ffb8e29cfaf139223e4994edbf64d6
[ "WTFPL" ]
null
null
null
pg_answer/259350e26d1d4c748446c198c9f3ca00.cpp
Guyutongxue/Introduction_to_Computation
062f688fe3ffb8e29cfaf139223e4994edbf64d6
[ "WTFPL" ]
null
null
null
#include <iostream> int main() { int k; while (std::cin >> k, k) { for (int m{k + 1}; true; m++) { int pos{0}; int n{k * 2}; bool hasGood{false}; for (int i{1}; i <= k; i++) { pos = (pos + m - 1) % n; if (pos < k) { hasGood = true; break; } n--; } if (!hasGood) { std::cout << m << std::endl; break; } } } }
23.166667
44
0.276978
Guyutongxue
99f2101a5f0ad596c7d346eb05aad904b7802921
388
hpp
C++
GLFramework/Game/Materials/EmissiveMaterial.hpp
Illation/GLFramework
2b9d3d67d4e951e2ff5ace0241750a438d6e743f
[ "MIT" ]
39
2016-03-23T00:39:46.000Z
2022-02-07T21:26:05.000Z
GLFramework/Game/Materials/EmissiveMaterial.hpp
Illation/GLFramework
2b9d3d67d4e951e2ff5ace0241750a438d6e743f
[ "MIT" ]
1
2016-03-24T14:39:45.000Z
2016-03-24T17:34:39.000Z
GLFramework/Game/Materials/EmissiveMaterial.hpp
Illation/GLFramework
2b9d3d67d4e951e2ff5ace0241750a438d6e743f
[ "MIT" ]
3
2016-08-15T01:27:13.000Z
2021-12-29T01:37:51.000Z
#pragma once #include "../../Graphics/Material.hpp" class EmissiveMaterial : public Material { public: EmissiveMaterial(glm::vec3 col = glm::vec3(1, 1, 1)); ~EmissiveMaterial(); void SetCol(glm::vec3 col) { m_Color = col; } private: void LoadTextures(); void AccessShaderAttributes(); void UploadDerivedVariables(); private: //Parameters GLint m_uCol; glm::vec3 m_Color; };
16.869565
54
0.71134
Illation