hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
ac7f18198c4b7ebb51428ca0e212c7bff5992afc
746
cpp
C++
Plugins/org.mitk.gui.qt.datamanager/src/berrySingleNodeSelection.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2022-03-03T12:03:32.000Z
2022-03-03T12:03:32.000Z
Plugins/org.mitk.gui.qt.datamanager/src/berrySingleNodeSelection.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2021-12-22T10:19:02.000Z
2021-12-22T10:19:02.000Z
Plugins/org.mitk.gui.qt.datamanager/src/berrySingleNodeSelection.cpp
zhaomengxiao/MITK_lancet
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2020-11-27T09:41:18.000Z
2020-11-27T09:41:18.000Z
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berrySingleNodeSelection.h" #include "mitkDataNode.h" namespace berry { void SingleNodeSelection::SetNode( mitk::DataNode* _SelectedNode ) { m_Node = _SelectedNode; } mitk::DataNode* SingleNodeSelection::GetNode() const { return m_Node; } bool SingleNodeSelection::IsEmpty() const { return ( m_Node == nullptr ); } }
20.722222
78
0.568365
zhaomengxiao
ac806388da5d8e24ed0e5846395902524c11f99a
783
cpp
C++
C_Plus_Plus/Basic/save_image/main.cpp
Asadullah-Dal17/learn-opencv-python
2892e1b253f1c8977662148a8721d8efb7bd63b6
[ "MIT" ]
1
2021-12-12T12:17:03.000Z
2021-12-12T12:17:03.000Z
C_Plus_Plus/Basic/save_image/main.cpp
Asadullah-Dal17/learn-opencv-python
2892e1b253f1c8977662148a8721d8efb7bd63b6
[ "MIT" ]
null
null
null
C_Plus_Plus/Basic/save_image/main.cpp
Asadullah-Dal17/learn-opencv-python
2892e1b253f1c8977662148a8721d8efb7bd63b6
[ "MIT" ]
null
null
null
#include <iostream> #include <opencv2/opencv.hpp> int main(int, char**) { std::string image_path ="C:/Users/Asadullah/Projects/Opencv/Course/coding_pubic/learn-opencv-python/images/shapes_image.png"; std::string saving_path ="C:/Users/Asadullah/Projects/Opencv/Course/coding_pubic/learn-opencv-python/C_Plus_Plus/Basic/save_image/save_image.png"; // std::cout<<test; cv::Mat image; // creating Mat data type for image image = cv::imread(image_path,0); cv::imwrite(saving_path, image); cv::imshow("Images", image); //showing image on screen cv::waitKey(0); // making window wait until key is pressed on keyboard cv::Mat loading_saved = cv::imread(saving_path); cv::imshow("saved_image",loading_saved); cv::waitKey(0); return 0; }
41.210526
150
0.707535
Asadullah-Dal17
ac813c9b719672b1d58e01b342dc9615d3540e0e
640
cpp
C++
src/random.cpp
navkagleb/Random
adb8ea30178582dc77af0b460f3895ca8e4cb641
[ "MIT" ]
1
2021-06-02T15:46:00.000Z
2021-06-02T15:46:00.000Z
src/random.cpp
navkagleb/Random
adb8ea30178582dc77af0b460f3895ca8e4cb641
[ "MIT" ]
null
null
null
src/random.cpp
navkagleb/Random
adb8ea30178582dc77af0b460f3895ca8e4cb641
[ "MIT" ]
null
null
null
#include "random.hpp" namespace ng::random { bool NextBool(float probability) { return _detail::BoolDistribution(std::max(0.0f, std::min(1.0f, probability)))(_detail::GetMersenneTwisterEngine()); } std::string NextString(std::size_t size, char from, char to) { std::string next(size, '\0'); for (auto& character : next) { character = NextIntegral<char>(from, to); } return next; } std::string NextString(std::size_t size, const std::function<char()>& get_random_char) { std::string next(size, '\0'); for (auto& character : next) { character = get_random_char(); } return next; } } // namespace ng::random
21.333333
117
0.673438
navkagleb
ac82131e62f6b39d4c94a6eebe93eeba4ad5e920
8,614
hxx
C++
include/nifty/distributed/distributed_graph.hxx
konopczynski/nifty
dc02ac60febaabfaf9b2ee5a854bb61436ebdc97
[ "MIT" ]
null
null
null
include/nifty/distributed/distributed_graph.hxx
konopczynski/nifty
dc02ac60febaabfaf9b2ee5a854bb61436ebdc97
[ "MIT" ]
null
null
null
include/nifty/distributed/distributed_graph.hxx
konopczynski/nifty
dc02ac60febaabfaf9b2ee5a854bb61436ebdc97
[ "MIT" ]
null
null
null
#pragma once #include <unordered_map> #include <boost/functional/hash.hpp> #include "nifty/distributed/graph_extraction.hxx" namespace nifty { namespace distributed { // A simple directed graph, // that can be constructed from the distributed region graph outputs // We use this instead of the nifty graph api, because we need to support // non-dense node indices class Graph { // private graph typedefs // NodeAdjacency: maps nodes that are adjacent to a given node to the corresponding edge-id typedef std::map<NodeType, EdgeIndexType> NodeAdjacency; // NodeStorage: storage of the adjacency for all nodes typedef std::unordered_map<NodeType, NodeAdjacency> NodeStorage; // EdgeStorage: dense storage of pairs of edges typedef std::vector<EdgeType> EdgeStorage; public: // API: we can construct the graph from blocks that were extracted via `extractGraphFromRoi` // or `mergeSubgraphs` from `region_graph.hxx` Graph(const std::string & blockPath, const int nThreads=1) : nodeMaxId_(0) { loadEdges(blockPath, edges_, 0, nThreads); initGraph(); } // This is a bit weird (constructor with side effects....) // but I don't want the edge id mapping to be part of this class Graph(const std::vector<std::string> & blockPaths, std::vector<EdgeIndexType> & edgeIdsOut, const int nThreads=1) : nodeMaxId_(0) { // load all the edges and edge-id mapping in the blocks // to tmp objects std::vector<EdgeType> edgesTmp; std::vector<EdgeIndexType> edgeIdsTmp; for(const auto & blockPath : blockPaths) { loadEdges(blockPath, edgesTmp, edgesTmp.size(), nThreads); loadEdgeIndices(blockPath, edgeIdsTmp, edgeIdsTmp.size(), nThreads); } // get the indices that would sort the edge uv's // (we need to sort the edge uvs AND the edgeIds in the same manner here) std::vector<std::size_t> indices(edgesTmp.size()); std::iota(indices.begin(), indices.end(), 0); std::sort(indices.begin(), indices.end(), [&](const std::size_t a, const std::size_t b){ return edgesTmp[a] < edgesTmp[b]; }); // copy tmp edges in sorted order edges_.resize(edgesTmp.size()); for(std::size_t ii = 0; ii < edges_.size(); ++ii) { edges_[ii] = edgesTmp[indices[ii]]; } // make edges unique edges_.resize(std::unique(edges_.begin(), edges_.end()) - edges_.begin()); // copy tmp edge ids to the out vector in sorted order edgeIdsOut.resize(edgeIdsTmp.size()); for(std::size_t ii = 0; ii < edgeIdsOut.size(); ++ii) { edgeIdsOut[ii] = edgeIdsTmp[indices[ii]]; } // make edge ids unique edgeIdsOut.resize(std::unique(edgeIdsOut.begin(), edgeIdsOut.end()) - edgeIdsOut.begin()); // init the graph initGraph(); } // non-constructor API // Find edge-id corresponding to the nodes u, v // returns -1 if no such edge exists EdgeIndexType findEdge(NodeType u, NodeType v) const { // find the node iterator auto uIt = nodes_.find(u); // don't find the u node -> return -1 if(uIt == nodes_.end()) { return -1; } // check if v is in the adjacency of u auto vIt = uIt->second.find(v); // v node is not in u's adjacency -> return -1 if(vIt == uIt->second.end()) { return -1; } // otherwise we have found the edge and return the edge id return vIt->second; } // get the node adjacency const NodeAdjacency & nodeAdjacency(const NodeType node) const { return nodes_.at(node); } // extract the subgraph uv-ids (with dense node labels) // as well as inner and outer edges associated with the node list template<class NODE_ARRAY> void extractSubgraphFromNodes(const xt::xexpression<NODE_ARRAY> & nodesExp, const bool allowInvalidNodes, std::vector<EdgeIndexType> & innerEdgesOut, std::vector<EdgeIndexType> & outerEdgesOut) const { const auto & nodes = nodesExp.derived_cast(); // build hash set for fast look-up std::unordered_set<NodeType> nodeSet(nodes.begin(), nodes.end()); // then iterate over the adjacency and extract inner and outer edges for(const NodeType u : nodes) { //const auto & uAdjacency = nodes_.at(u); // we might allow invalid nodes auto adjIt = nodes_.find(u); if(adjIt == nodes_.end()) { if(allowInvalidNodes) { continue; } else { throw std::runtime_error("Invalid node in sub-graph extraction"); } } const auto & uAdjacency = adjIt->second; for(const auto & adj : uAdjacency) { const NodeType v = adj.first; const EdgeIndexType edge = adj.second; // we do the look-up in the node-mapping instead of the node-list, because it's a hash-map // (and thus faster than array lookup) if(nodeSet.find(v) != nodeSet.end()) { // we will encounter inner edges twice, so we only add them for u < v if(u < v) { innerEdgesOut.push_back(edge); } } else { // outer edges occur only once by construction outerEdgesOut.push_back(edge); } } } } // number of nodes and edges std::size_t numberOfNodes() const {return nodes_.size();} std::size_t numberOfEdges() const {return edges_.size();} std::size_t maxNodeId() const {return nodeMaxId_;} // edges are always consecutive std::size_t maxEdgeId() const {return edges_.size() - 1;} const EdgeStorage & edges() const {return edges_;} void nodes(std::set<NodeType> & out) const{ for(auto nodeIt = nodes_.begin(); nodeIt != nodes_.end(); ++nodeIt) { out.insert(nodeIt->first); } } void nodes(std::vector<NodeType> & out) const{ out.clear(); out.resize(numberOfNodes()); std::size_t nodeId = 0; for(auto nodeIt = nodes_.begin(); nodeIt != nodes_.end(); ++nodeIt, ++nodeId) { out[nodeId] = nodeIt->first; } } private: // init the graph from the edges void initGraph() { // iterate over the edges we have NodeType u, v; NodeType maxNode; EdgeIndexType edgeId = 0; for(const auto & edge : edges_) { u = edge.first; v = edge.second; // insert v in the u adjacency auto uIt = nodes_.find(u); if(uIt == nodes_.end()) { // if u is not in the nodes vector yet, insert it nodes_.insert(std::make_pair(u, NodeAdjacency{{v, edgeId}})); } else { uIt->second[v] = edgeId; } // insert u in the v adjacency auto vIt = nodes_.find(v); if(vIt == nodes_.end()) { // if v is not in the nodes vector yet, insert it nodes_.insert(std::make_pair(v, NodeAdjacency{{u, edgeId}})); } else { vIt->second[u] = edgeId; } // increase the edge id ++edgeId; // update the node max id maxNode = std::max(u, v); if(maxNode > nodeMaxId_) { nodeMaxId_ = maxNode; } } } NodeType nodeMaxId_; NodeStorage nodes_; EdgeStorage edges_; }; } }
38.284444
110
0.519039
konopczynski
12bf7201cb974498cd57acd4e1c0b691255d842a
3,274
cpp
C++
Aether Framework/src/Audio/AudioDevice.cpp
WiktorKasjaniuk/Aether-Framework
75b3e064e6ccee81784636aa7cc45b4cae663d46
[ "BSD-3-Clause" ]
null
null
null
Aether Framework/src/Audio/AudioDevice.cpp
WiktorKasjaniuk/Aether-Framework
75b3e064e6ccee81784636aa7cc45b4cae663d46
[ "BSD-3-Clause" ]
null
null
null
Aether Framework/src/Audio/AudioDevice.cpp
WiktorKasjaniuk/Aether-Framework
75b3e064e6ccee81784636aa7cc45b4cae663d46
[ "BSD-3-Clause" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (c) 2021, Wiktor Kasjaniuk // 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. //////////////////////////////////////////////////////////////////////////////////// #include "Audio/AudioDevice.hpp" #include "Audio/Listener.hpp" #include "Audio/Music.hpp" #include "Core/OpenALCalls.hpp" #include "Core/Preprocessor.hpp" #include "System/LogError.hpp" #include <OpenALSoft/al.h> #include <OpenALSoft/alc.h> namespace ae { namespace internal { AudioDevice AudioDevice::s_instance; void AudioDevice::Initialize() { // open default device ALCdevice* device = alcOpenDevice(nullptr); ALCcontext* context = nullptr; // the application will be muted if no device are present at this point // or potentially crash if the default one is turned off after creation if (!device) { AE_WARNING("[Aether] Could not open OpenAL Soft device"); } else { context = alcCreateContext(device, nullptr); bool context_current = alcMakeContextCurrent(context); AE_ASSERT_WARNING(context_current, "[Aether] Could not create and make current OpenAL Soft context"); } // initialize listener Listener.Initialize(); // update s_instance.m_native_device = static_cast<void*>(device); s_instance.m_native_context = static_cast<void*>(context); } void AudioDevice::Terminate() { s_instance.m_is_running = false; Music::s_streaming_thread.join(); alcMakeContextCurrent(NULL); alcDestroyContext(static_cast<ALCcontext*>(s_instance.m_native_context)); alcCloseDevice(static_cast<ALCdevice*>(s_instance.m_native_device)); } bool AudioDevice::IsRunning() { return s_instance.m_is_running; } } }
38.069767
105
0.711057
WiktorKasjaniuk
12c097c0a363d5ddf94e57a6c758a49a938ee077
47
hpp
C++
src/boost_date_time_compiler_config.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_date_time_compiler_config.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_date_time_compiler_config.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/date_time/compiler_config.hpp>
23.5
46
0.829787
miathedev
12c53ba0bf5726820b495f029a641b18b50d04a5
1,638
cpp
C++
12-circle/circle.cpp
skaadin/learning-projects
977efa1eabab038566d57c455e649da8b440c7e9
[ "MIT" ]
143
2016-07-28T06:00:43.000Z
2022-03-30T14:08:50.000Z
12-circle/circle.cpp
skaadin/learning-projects
977efa1eabab038566d57c455e649da8b440c7e9
[ "MIT" ]
3
2017-11-28T10:09:52.000Z
2021-08-30T09:20:41.000Z
12-circle/circle.cpp
skaadin/learning-projects
977efa1eabab038566d57c455e649da8b440c7e9
[ "MIT" ]
24
2016-10-27T02:02:44.000Z
2022-02-06T07:37:07.000Z
#include <iostream> #include <math.h> // M_PI, sqrt class Circle { private: float area; float radius; float diameter; public: Circle(float area = 0, float radius = 0, float diameter = 0) : area{area}, radius{radius}, diameter{diameter} {} static Circle from_radius(float radius) { return Circle(M_PI * (radius * radius), radius, radius * 2); } static Circle from_diameter(float diameter) { float radius = diameter / 2.0; return Circle(M_PI * (radius * radius), radius, diameter); } static Circle from_area(float area) { float diameter = sqrt(area / M_PI); return Circle(area, diameter / 2.0, diameter); } void print() { std::cout << "Circle(area: " << area << ", radius: " << radius << ", diameter: " << diameter << ")" << std::endl; } }; int main() { std::cout << "Pick an option: " << std::endl; std::cout << "1. Area" << std::endl; std::cout << "2. Radius" << std::endl; std::cout << "3. Diameter" << std::endl; int choice; std::cin >> choice; if(!std::cin) { std::cout << "Enter a number!" << std::endl; return 1; } std::cout << "Enter size: "; int size; std::cin >> size; if(!std::cin) { std::cout << "Enter a number!" << std::endl; return 1; } Circle circle; switch(choice) { case 1: circle = Circle::from_area(size); break; case 2: circle = Circle::from_radius(size); break; case 3: circle = Circle::from_diameter(size); break; default: std::cout << "Pick an option from the list!" << std::endl; return 1; } circle.print(); return 0; }
20.734177
64
0.571429
skaadin
12d2e88f92eace73422104e3e939ac717e36ad95
13,726
cpp
C++
TerrainSDK/vtlib/core/PagedLodGrid.cpp
nakijun/vtp
7bd2b2abd3a3f778a32ba30be099cfba9b892922
[ "MIT" ]
4
2019-02-08T13:51:26.000Z
2021-12-07T13:11:06.000Z
TerrainSDK/vtlib/core/PagedLodGrid.cpp
nakijun/vtp
7bd2b2abd3a3f778a32ba30be099cfba9b892922
[ "MIT" ]
null
null
null
TerrainSDK/vtlib/core/PagedLodGrid.cpp
nakijun/vtp
7bd2b2abd3a3f778a32ba30be099cfba9b892922
[ "MIT" ]
7
2017-12-03T10:13:17.000Z
2022-03-29T09:51:18.000Z
// // PagedLodGrid.cpp // // Copyright (c) 2007-2011 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "vtlib/vtlib.h" #include "Structure3d.h" #include "vtdata/LocalCS.h" #include "vtdata/HeightField.h" #include "vtdata/vtLog.h" #include "PagedLodGrid.h" #include <algorithm> // for sort vtPagedStructureLOD::vtPagedStructureLOD() : vtLOD() { m_iNumConstructed = 0; m_bAddedToQueue = false; SetCenter(FPoint3(0, 0, 0)); SetOsgNode(this); } void vtPagedStructureLOD::SetRange(float range) { m_fRange = range; } /** * \param fDistance The distance in meters to check against. * \param bLoad If true, and this cell is within the distance, and it isn't * loaded, then load it. */ bool vtPagedStructureLOD::TestVisible(float fDistance, bool bLoad) { if (fDistance < m_fRange) { // Check if this group has any unbuilt structures if (bLoad && !m_bAddedToQueue && m_iNumConstructed != m_StructureRefs.size() && m_pGrid->m_LoadingEnabled) { AppendToQueue(); m_bAddedToQueue = true; } return true; } return false; } void vtPagedStructureLOD::AppendToQueue() { int count = 0; for (uint i = 0; i < m_StructureRefs.size(); i++) { StructureRef &ref = m_StructureRefs[i]; // Don't queue structures from layers that aren't visible if (ref.pArray->GetEnabled() == false) continue; if (m_pGrid->AddToQueue(this, ref.pArray, ref.iIndex)) count++; } if (count > 0) VTLOG("Added %d buildings to queue.\n", count); // We have just added a lump of structures, sort them by distance m_pGrid->SortQueue(); } void vtPagedStructureLOD::Add(vtStructureArray3d *pArray, int iIndex) { StructureRef ref; ref.pArray = pArray; ref.iIndex = iIndex; m_StructureRefs.push_back(ref); } void vtPagedStructureLOD::Remove(vtStructureArray3d *pArray, int iIndex) { StructureRefVector::iterator it = m_StructureRefs.begin(); while (it != m_StructureRefs.end()) { if (it->pArray == pArray && it->iIndex == iIndex) { vtStructure3d *s3d = it->pArray->GetStructure3d(it->iIndex); if (s3d->IsCreated()) m_iNumConstructed--; it = m_StructureRefs.erase(it); } else it++; } } /////////////////////////////////////////////////////////////////////// // vtPagedStructureLodGrid #define CellIndex(a,b) ((a*m_dim)+b) vtPagedStructureLodGrid::vtPagedStructureLodGrid() { m_pCells = NULL; m_LoadingEnabled = true; m_iLoadCount = 0; } void vtPagedStructureLodGrid::Setup(const FPoint3 &origin, const FPoint3 &size, int iDimension, float fLODDistance, vtHeightField3d *pHF) { m_origin = origin; m_size = size; m_dim = iDimension; m_fLODDistance = fLODDistance; m_step = m_size / (float)m_dim; // wrap with an array of simple LOD nodes m_pCells = (vtPagedStructureLOD **)malloc(m_dim * m_dim * sizeof(vtPagedStructureLOD *)); int a, b; for (a = 0; a < m_dim; a++) { for (b = 0; b < m_dim; b++) { m_pCells[CellIndex(a,b)] = NULL; } } m_pHeightField = pHF; } void vtPagedStructureLodGrid::Cleanup() { // get rid of children first removeChildren(0, getNumChildren()); // free all our pointers to them free(m_pCells); m_pCells = NULL; } void vtPagedStructureLodGrid::AllocateCell(int a, int b) { int i = CellIndex(a,b); m_pCells[i] = new vtPagedStructureLOD; vtString name; name.Format("LOD cell %d %d", a, b); m_pCells[i]->setName(name); m_pCells[i]->SetRange(m_fLODDistance); // determine LOD center FPoint3 lod_center; lod_center.x = m_origin.x + ((m_size.x / m_dim) * (a + 0.5f)); lod_center.y = m_origin.y + (m_size.y / 2.0f); lod_center.z = m_origin.z + ((m_size.z / m_dim) * (b + 0.5f)); if (m_pHeightField) m_pHeightField->FindAltitudeAtPoint(lod_center, lod_center.y); m_pCells[i]->SetCenter(lod_center); // and a radius to give the LOD a bounding sphere, for efficient culling FPoint2 diag(m_size.x / m_dim, m_size.z / m_dim); float diagonal = diag.Length(); float radius = diagonal/2; // Increase it a little, because some structures might visually extend outside // the minimal bounding sphere radius *= 1.6f; m_pCells[i]->setRadius(radius); m_pCells[i]->SetGrid(this); addChild(m_pCells[i]); } osg::Group *vtPagedStructureLodGrid::GetCell(int a, int b) { int i = CellIndex(a, b); return m_pCells[i]; } vtPagedStructureLOD *vtPagedStructureLodGrid::FindPagedCellParent(const FPoint3 &point) { int a, b; DetermineCell(point, a, b); if (a < 0 || a >= m_dim || b < 0 || b >= m_dim) return NULL; const int i = CellIndex(a, b); if (!m_pCells[i]) AllocateCell(a, b); return m_pCells[i]; } osg::Group *vtPagedStructureLodGrid::FindCellParent(const FPoint3 &point) { return FindPagedCellParent(point); } void vtPagedStructureLodGrid::SetDistance(float fLODDistance) { m_fLODDistance = fLODDistance; for (int a = 0; a < m_dim; a++) { for (int b = 0; b < m_dim; b++) { vtPagedStructureLOD *lod = m_pCells[CellIndex(a,b)]; if (lod) lod->SetRange(m_fLODDistance); } } } /** * For a given vtStructure, find the lod group parent for it, using the * structure's earth extents. */ vtPagedStructureLOD *vtPagedStructureLodGrid::FindGroup(vtStructure *str) { DRECT rect; if (str->GetExtents(rect)) { float xmin, xmax, zmin, zmax; m_pHeightField->m_LocalCS.EarthToLocal(rect.left, rect.bottom, xmin, zmin); m_pHeightField->m_LocalCS.EarthToLocal(rect.right, rect.top, xmax, zmax); const FPoint3 mid((xmin+xmax) / 2, 0.0f, (zmin+zmax)/2); return FindPagedCellParent(mid); } return NULL; } bool vtPagedStructureLodGrid::AppendToGrid(vtStructureArray3d *pArray, int iIndex) { // Get 2D extents from the unbuild structure vtStructure *str = pArray->at(iIndex); vtPagedStructureLOD *pGroup = FindGroup(str); if (pGroup) { pGroup->Add(pArray, iIndex); return true; } return false; } void vtPagedStructureLodGrid::RemoveFromGrid(vtStructureArray3d *pArray, int iIndex) { // Get 2D extents from the unbuild structure vtStructure *str = pArray->at(iIndex); vtPagedStructureLOD *pGroup = FindGroup(str); if (pGroup) pGroup->Remove(pArray, iIndex); } vtPagedStructureLOD *vtPagedStructureLodGrid::GetPagedCell(int a, int b) { return m_pCells[CellIndex(a,b)]; } void vtPagedStructureLodGrid::DeconstructCell(vtPagedStructureLOD *pLOD) { int count = 0; StructureRefVector &refs = pLOD->m_StructureRefs; //VTLOG("Deconstruction check on %d structures: ", indices.GetSize()); for (uint i = 0; i < refs.size(); i++) { StructureRef &ref = refs[i]; vtStructure3d *str3d = ref.pArray->GetStructure3d(ref.iIndex); osg::Node *node = str3d->GetContainer(); if (!node) node = str3d->GetGeom(); if (!node) continue; pLOD->removeChild(node); str3d->DeleteNode(); count++; } //VTLOG("%d decon.\n", count); pLOD->m_iNumConstructed = 0; pLOD->m_bAddedToQueue = false; } void vtPagedStructureLodGrid::RemoveCellFromQueue(vtPagedStructureLOD *pLOD) { if (!pLOD->m_bAddedToQueue) return; if (pLOD->m_iNumConstructed == pLOD->m_StructureRefs.size()) return; const StructureRefVector &refs = pLOD->m_StructureRefs; int count = 0; for (uint i = 0; i < refs.size(); i++) { if (RemoveFromQueue(refs[i].pArray, refs[i].iIndex)) count++; } if (count != 0) VTLOG("Dequeued %d of %d.\n", count, refs.size()); pLOD->m_bAddedToQueue = false; } void vtPagedStructureLodGrid::CullFarawayStructures(const FPoint3 &CamPos, int iMaxStructures, float fDistance) { m_iTotalConstructed = 0; for (int a = 0; a < m_dim; a++) { for (int b = 0; b < m_dim; b++) { vtPagedStructureLOD *lod = m_pCells[CellIndex(a,b)]; if (lod) m_iTotalConstructed += lod->getNumChildren(); } } // If we have too many or have items in the queue if (m_iTotalConstructed > iMaxStructures || m_Queue.size() > 0) { //VTLOG("CullFarawayStructures: %d in Queue, ", m_Queue.size()); int total = 0, removed = 0; // Delete/dequeue the ones that are very far FPoint3 center; for (int a = 0; a < m_dim; a++) { for (int b = 0; b < m_dim; b++) { vtPagedStructureLOD *lod = m_pCells[CellIndex(a,b)]; if (!lod) continue; total++; lod->GetCenter(center); float dist = (center - CamPos).Length(); // If very far, delete the structures entirely if (lod->m_iNumConstructed != 0 && m_iTotalConstructed > iMaxStructures && dist > fDistance) DeconstructCell(lod); // If it has fallen out of the frustum, remove them // from the queue if (dist > m_fLODDistance) { RemoveCellFromQueue(lod); removed++; } } } //VTLOG(" %d cells, %d cell removed\n", total, removed); } } bool operator<(const QueueEntry& a, const QueueEntry& b) { // Reverse-sort, to put smallest values (closest points) at the end // of the list so they can be efficiently removed return a.fDistance > b.fDistance; } void vtPagedStructureLodGrid::SortQueue() { vtCamera *cam = vtGetScene()->GetCamera(); FPoint3 CamPos = cam->GetTrans(); FPoint3 CamDir = cam->GetDirection(); // Prioritization is by distance. // We can measure horizontal distance, which is faster. DPoint3 cam_epos, cam_epos2; m_pHeightField->m_LocalCS.LocalToEarth(CamPos, cam_epos); m_pHeightField->m_LocalCS.LocalToEarth(CamPos+CamDir, cam_epos2); DPoint2 cam_pos(cam_epos.x, cam_epos.y); DPoint2 cam_dir(cam_epos2.x - cam_epos.x, cam_epos2.y - cam_epos.y); cam_dir.Normalize(); DPoint2 p; for (uint i = 0; i < m_Queue.size(); i++) { QueueEntry &e = m_Queue[i]; vtStructure *st = e.pStructureArray->at(e.iStructIndex); vtBuilding *bld = st->GetBuilding(); vtStructInstance *inst = st->GetInstance(); if (bld) p = bld->GetOuterFootprint(0).Centroid(); else if (inst) p = inst->GetPoint(); else continue; // Calculate distance DPoint2 diff = p-cam_pos; e.fDistance = (float) diff.Length(); // Is point behind the camera? If so, give it lowest priority if (diff.Dot(cam_dir) < 0) e.fDistance += 1E5; } std::sort(m_Queue.begin(), m_Queue.end()); } void vtPagedStructureLodGrid::ClearQueue(vtStructureArray3d *pArray) { QueueVector::iterator it = m_Queue.begin(); while (it != m_Queue.end()) { if (it->pStructureArray == pArray) it = m_Queue.erase(it); else it++; } } /** * In case the paging grid did not load some structure before (because the * structures were hidden), tell it to check again. * You should call this when a structure layer becomes enabled (un-hidden). */ void vtPagedStructureLodGrid::RefreshPaging(vtStructureArray3d *pArray) { for (uint i = 0; i < pArray->size(); i++) { // Get 2D extents from the unbuild structure vtStructure *str = pArray->at(i); vtPagedStructureLOD *pGroup = FindGroup(str); if (pGroup) pGroup->m_bAddedToQueue = false; } } void vtPagedStructureLodGrid::DoPaging(const FPoint3 &CamPos, int iMaxStructures, float fDeleteDistance) { static float last_cull = 0.0f, last_load = 0.0f, last_prioritize = 0.0f; float current = vtGetTime(); if (current - last_prioritize > 1.0f) { // Do a re-priortization every 1 second. SortQueue(); last_prioritize = current; } else if (current - last_cull > 0.25f) { // Do a paging cleanup pass every 1/4 of a second // Unload/unqueue anything excessive CullFarawayStructures(CamPos, iMaxStructures, fDeleteDistance); last_cull = current; } else if (current - last_load > 0.01f && !m_Queue.empty()) { // Do loading every other available frame last_load = current; // Check if the camera is not moving; if so, construct more. int construct; static FPoint3 last_campos; if (CamPos == last_campos) construct = 5; else construct = 1; for (int i = 0; i < construct && m_Queue.size() > 0; i++) { // Gradually load anything that needs loading const QueueEntry &e = m_Queue.back(); ConstructByIndex(e.pLOD, e.pStructureArray, e.iStructIndex); m_Queue.pop_back(); } last_campos = CamPos; } } void vtPagedStructureLodGrid::ConstructByIndex(vtPagedStructureLOD *pLOD, vtStructureArray3d *pArray, uint iStructIndex) { bool bSuccess = pArray->ConstructStructure(iStructIndex); if (bSuccess) { vtStructure3d *str3d = pArray->GetStructure3d(iStructIndex); vtTransform *pTrans = str3d->GetContainer(); if (pTrans) pLOD->addChild(pTrans); else { vtGeode *pGeode = str3d->GetGeom(); if (pGeode) pLOD->addChild(pGeode); } pLOD->m_iNumConstructed ++; // Keep track of overall number of loads m_iLoadCount++; } else { VTLOG("Error: couldn't construct index %d\n", iStructIndex); vtStructInstance *si = pArray->GetInstance(iStructIndex); if (si) { const char *fname = si->GetValueString("filename", true); VTLOG("\tinstance fname: '%s'\n", fname ? fname : "null"); } } } bool vtPagedStructureLodGrid::AddToQueue(vtPagedStructureLOD *pLOD, vtStructureArray3d *pArray, int iIndex) { // Check if it's already built vtStructure3d *str3d = pArray->GetStructure3d(iIndex); if (str3d && str3d->IsCreated()) return false; // Check if it's already in the queue for (QueueVector::iterator it = m_Queue.begin(); it != m_Queue.end(); it++) { if (it->pStructureArray == pArray && it->iStructIndex == iIndex) return false; } // If not, add it QueueEntry e; e.pLOD = pLOD; e.pStructureArray = pArray; e.iStructIndex = iIndex; e.fDistance = 1E9; m_Queue.push_back(e); return true; } bool vtPagedStructureLodGrid::RemoveFromQueue(vtStructureArray3d *pArray, int iIndex) { // Check if it's in the queue for (QueueVector::iterator it = m_Queue.begin(); it != m_Queue.end(); it++) { if (it->pStructureArray == pArray && it->iStructIndex == iIndex) { m_Queue.erase(it); return true; } } return false; }
24.598566
90
0.683375
nakijun
12d3cf11cb874027db4ecfaead2fb54d13967e27
16,970
cpp
C++
src/xray/editor/world/sources/sound_object_cook.cpp
ixray-team/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
3
2021-10-30T09:36:14.000Z
2022-03-26T17:00:06.000Z
src/xray/editor/world/sources/sound_object_cook.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
null
null
null
src/xray/editor/world/sources/sound_object_cook.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:08.000Z
2022-03-26T17:00:08.000Z
//////////////////////////////////////////////////////////////////////////// // Created : 21.12.2009 // Author : Evgeniy Obertyukh // Copyright (C) GSC Game World - 2009 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #pragma managed(push) #pragma unmanaged #include <xray/resources.h> #include <xray/resources_cook_classes.h> #include <xray/resources_fs.h> #include <xray/fs_path_string.h> #pragma managed(pop) #include "memory.h" //#include <conio.h> #pragma managed(push) #pragma unmanaged #include <xray/core/sources/resources_manager.h> #include <xray/core/sources/resources_managed_allocator.h> #pragma managed(pop) #include "sound_object_cook.h" #include "raw_file_property_struct.h" #include "sound_editor.h" #pragma managed(push) #pragma unmanaged #include <xray/fs_utils.h> #include <xray/linkage_helper.h> #pragma managed(pop) DECLARE_LINKAGE_ID(resources_test) using namespace System; using namespace System::IO; using namespace System::Diagnostics; using namespace System::Windows::Forms; using xray::editor::raw_file_property_struct; using xray::editor::sound_editor; using xray::editor::unmanaged_string; using xray::resources::fs_iterator; #pragma message(XRAY_TODO("fix cooks")) #if 0 // commented by Lain namespace xray { namespace resources { static void make_sound_options (fs::path_string& file_path); static void encode_sound_file ( fs::path_string &end_file_path, int bits_per_sample, int number_of_chanels, int samples_per_second, int output_bitrate ); //ogg_resource class sound_object_resource::sound_object_resource(pcbyte data_raw) { XRAY_UNREFERENCED_PARAMETER(data_raw); m_options_resource_ptr = NULL; } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ogg_sound_cook_wrapper::ogg_sound_cook_wrapper () : cook( ogg_sound_wrapper_class, flag_process|flag_generate_if_no_file|flag_translate_query, threading::current_thread_id()/*use_cooker_thread_id*/) {} void ogg_sound_cook_wrapper::translate_query ( resources::query_result& result ) { //prepare paths fs::path_string old_path (result.get_requested_path()); fs::path_string root_path; fs::path_string* resource_path = MT_NEW(fs::path_string); pcstr find_str = strstr(old_path.c_str(), "sounds"); root_path.append (old_path.begin(), find_str+6); resource_path->append (find_str+23, old_path.end()); resources::query_fs_iterator( root_path.c_str(), boost::bind(&ogg_sound_cook_wrapper::on_fs_iterator_ready, this, resource_path, &result, _1), result.get_user_allocator() ); } void ogg_sound_cook_wrapper::on_fs_iterator_ready (fs::path_string* resource_path, query_result_for_cook* parent, xray::resources::fs_iterator fs_it) { // // if converted ogg isn't exists -> convert it and options // fs::path_string converted_path; converted_path.append ("converted_local/"); converted_path.append (resource_path->c_str()); converted_path.append (".ogg"); fs_iterator fs_it_converted = fs_it.find_child(converted_path.c_str()); if(fs_it_converted.is_end()) { request_convertion (resource_path, parent); MT_DELETE (resource_path); return; } // // if converted ogg is old or source options younger than converted ogg -> convert ogg and options // fs::path_string source_path; source_path.append ("sources/"); source_path.append (resource_path->c_str()); source_path.append (".wav"); fs_iterator fs_it_source = fs_it.find_child(source_path.c_str()); fs::path_string source_options_path; source_options_path.append ("sources/"); source_options_path.append (resource_path->c_str()); source_options_path.append (".options"); fs_iterator fs_it_source_options = fs_it.find_child(source_options_path.c_str()); fs::path_info source_info; fs::path_info converted_info; fs::path_info source_options_info; fs::path_string source_absolute_path; fs::path_string converted_absolute_path; fs::path_string source_options_absolute_path; fs_it_source.get_disk_path (source_absolute_path); fs_it_converted.get_disk_path (converted_absolute_path); fs_it_source_options.get_disk_path (source_options_absolute_path); fs::get_path_info (&source_info, source_absolute_path.c_str()); fs::get_path_info (&converted_info, converted_absolute_path.c_str()); fs::get_path_info (&source_options_info, source_options_absolute_path.c_str()); if( source_info.file_last_modify_time > converted_info.file_last_modify_time || source_options_info.file_last_modify_time > converted_info.file_last_modify_time) { request_convertion (resource_path, parent); MT_DELETE (resource_path); return; } // // if converted options isn't exists -> convert it // fs::path_string converted_options_path; converted_options_path.append ("converted_local/"); converted_options_path.append (resource_path->c_str()); converted_options_path.append (".options"); xray::resources::fs_iterator fs_it_converted_options = fs_it.find_child(converted_options_path.c_str()); if(fs_it_converted_options.is_end()) { request_convertion_options (resource_path, parent); MT_DELETE (resource_path); return; } // // if converted options is old -> convert it // fs::path_info converted_options_info; fs::path_string converted_options_absolute_path; fs_it_converted_options.get_disk_path (converted_options_absolute_path); fs::get_path_info (&converted_options_info, converted_options_absolute_path.c_str()); if( converted_options_info.file_last_modify_time < converted_info.file_last_modify_time) { request_convertion_options (resource_path, parent); MT_DELETE (resource_path); return; } // // otherwise request sound // query_resource( parent->get_requested_path(), ogg_sound_class, boost::bind(&ogg_sound_cook_wrapper::sound_loaded, this, _1), &memory::g_mt_allocator, 0, parent ); MT_DELETE (resource_path); } void ogg_sound_cook_wrapper::request_convertion (fs::path_string* resource_path, query_result_for_cook* parent) { //prepare paths fs::path_string ogg_path; fs::path_string tga_path; ogg_path.append ("resources/sounds/converted_local/"); ogg_path.append (resource_path->c_str()); ogg_path.append (".ogg"); query_resource( ogg_path.c_str(), ogg_converter_class, boost::bind(&ogg_sound_cook_wrapper::on_sound_converted, this, false, _1), &memory::g_mt_allocator, 0, parent ); } void ogg_sound_cook_wrapper::request_convertion_options (fs::path_string* resource_path, query_result_for_cook* parent) { //prepare paths fs::path_string ogg_path; fs::path_string tga_path; ogg_path.append ("resources/sounds/converted_local/"); ogg_path.append (resource_path->c_str()); ogg_path.append (".options"); query_resource( ogg_path.c_str(), ogg_options_converter_class, boost::bind(&ogg_sound_cook_wrapper::on_sound_converted, this, true, _1), &memory::g_mt_allocator, 0, parent ); } void ogg_sound_cook_wrapper::on_sound_converted (bool is_options_complete, resources::queries_result& result) { resources::query_result_for_cook * const parent = result.get_parent_query(); if(is_options_complete) { query_resource( parent->get_requested_path(), ogg_sound_class, boost::bind(&ogg_sound_cook_wrapper::sound_loaded, this, _1), &memory::g_mt_allocator, 0, parent ); } else { fs::path_string old_path (result[0].get_requested_path()); fs::path_string resource_path; pcstr find_str = strstr(old_path.c_str(), "converted_local"); resource_path.append (find_str+16, old_path.end()-4); request_convertion_options (&resource_path, parent); } } void ogg_sound_cook_wrapper::sound_loaded (queries_result& result) { query_result_for_cook * const parent = result.get_parent_query(); if(result.is_failed()) { parent->finish_translated_query (result_error); return; } parent->set_unmanaged_resource (result[0].get_unmanaged_resource().get()); parent->finish_translated_query (result_dont_reuse); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// //ogg_sound_cook class ogg_sound_cook::ogg_sound_cook () : cook( ogg_sound_class, cook::flag_translate_query, use_cooker_thread_id) {} void ogg_sound_cook::translate_query (query_result& parent) { pstr request_ogg = 0; STR_JOINA ( request_ogg, parent.get_requested_path(), ".ogg" ); pstr request_options = 0; STR_JOINA ( request_options, parent.get_requested_path(), ".options" ); request arr[] = { { request_ogg, ogg_class }, { request_options, config_lua_class }, }; query_resources (arr, 2, boost::bind(&ogg_sound_cook::on_sub_resources_loaded, this, _1), parent.get_user_allocator(), 0, &parent); } void ogg_sound_cook::on_sub_resources_loaded (queries_result & result) { query_result_for_cook * const parent = result.get_parent_query(); unmanaged_resource_ptr ogg_res; if ( result[0].is_success() && result[1].is_success() ) { ogg_res = result[0].get_unmanaged_resource(); static_cast_checked<sound_object_resource*>( ogg_res.get()) -> m_options_resource_ptr = (result[1].get_unmanaged_resource()); } else { parent->finish_translated_query (result_error); return; } parent->set_unmanaged_resource (ogg_res.get()); parent->finish_translated_query (result_reuse_unmanaged); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ogg_cook::ogg_cook() : cook(ogg_class, flag_process|flag_generate_if_no_file) {} cook::result_enum ogg_cook::process (query_result_for_cook& query, u32& final_managed_resource_size) { XRAY_UNREFERENCED_PARAMETER ( final_managed_resource_size ); sound_object_resource * out = NULL; if (!query.is_success()) return result_error; mutable_buffer data = query.get_file_data(); pcbyte data_raw = (pcbyte)data.data(); out = MT_NEW(sound_object_resource)(data_raw); query.set_unmanaged_resource (out); return result_reuse_unmanaged; } void ogg_cook::delete_unmanaged (unmanaged_resource* res) { MT_DELETE (res); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// static void encode_sound_file ( fs::path_string &end_file_path, int bits_per_sample, int number_of_chanels, int samples_per_second, int output_bitrate ); ogg_converter::ogg_converter() : cook(ogg_converter_class, flag_process|flag_generate_if_no_file) {} cook::result_enum ogg_converter::process(query_result_for_cook& query, u32& final_managed_resource_size) { XRAY_UNREFERENCED_PARAMETER ( final_managed_resource_size ); //prepare paths fs::path_string dest_path (query.get_requested_path()); fs::path_string source_options_path; pcstr find_str = strstr(dest_path.c_str(), "converted_local"); source_options_path.append (dest_path.begin(), find_str); source_options_path.append ("sources"); source_options_path.append (find_str+15, dest_path.end()-4); source_options_path.append (".options"); fs::path_string disk_path; CURE_ASSERT (query.select_disk_path_from_request_path(& disk_path), return result_error); query_resource ( source_options_path.c_str(), config_lua_class, boost::bind(&ogg_converter::on_raw_properties_loaded, this, _1), & memory::g_mt_allocator, 0, & query); return result_postponed; } void ogg_converter::on_raw_properties_loaded (queries_result& result) { query_result_for_cook * const parent = result.get_parent_query(); if ( result.is_failed() ) { parent->finish_postponed (result_error); return; } configs::lua_config_ptr config = static_cast_intrusive_ptr<configs::lua_config_ptr>(result[0].get_unmanaged_resource()); configs::lua_config_value const& config_root = config->get_root(); configs::lua_config_value value = config_root["options"]; fs::path_string disk_path; CURE_ASSERT (parent->select_disk_path_from_request_path(&disk_path), parent->finish_postponed(result_error)); encode_sound_file( disk_path, value["bits_per_sample"], value["number_of_chanels"], value["samples_per_second"], value["output_bitrate"] ); parent->finish_postponed (result_dont_reuse); } static void encode_sound_file( fs::path_string &end_file_path, int bits_per_sample, int number_of_chanels, int samples_per_second, int output_bitrate) { //make path's fs::path_string src_file_path; char* sources_offset = strstr(end_file_path.c_str(), "converted_local"); src_file_path.append (end_file_path.begin(), sources_offset); src_file_path.append ("sources"); src_file_path.append (sources_offset+15, end_file_path.end()); src_file_path.set_length(src_file_path.length()-4); src_file_path.append (".wav"); //if destination directory is not exists -> make it fs::path_string dir; dir = end_file_path; dir.set_length(dir.rfind('/')); if(fs::get_path_info(NULL, dir.c_str()) == fs::path_info::type_nothing) { fs::make_dir_r(dir.c_str()); } STARTUPINFO si; ZeroMemory ( &si, sizeof(si) ); si.cb = sizeof(STARTUPINFO); si.wShowWindow = 0; si.dwFlags = STARTF_USESHOWWINDOW; PROCESS_INFORMATION pi; ZeroMemory ( &pi, sizeof(pi) ); char buf[12]; fixed_string512 cl_args; cl_args += "oggenc.exe"; cl_args += " -B "; _itoa_s(bits_per_sample, buf, 10); cl_args += buf; cl_args += " -C "; _itoa_s(number_of_chanels, buf, 10); cl_args += buf; cl_args += " -R "; _itoa_s(samples_per_second, buf, 10); cl_args += buf; cl_args += " -b "; _itoa_s(output_bitrate, buf, 10); cl_args += buf; cl_args += " -o \""; cl_args += end_file_path.c_str(); cl_args += "\" \""; cl_args += src_file_path.c_str(); cl_args += "\""; if(CreateProcess(NULL,cl_args.c_str(),NULL, NULL, FALSE,0, NULL, NULL, &si, &pi)) WaitForSingleObject(pi.hProcess, INFINITE); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// static void make_sound_options(fs::path_string& end_file_path); ogg_options_converter::ogg_options_converter() : cook(ogg_options_converter_class, flag_process|flag_generate_if_no_file) {} cook::result_enum ogg_options_converter::process(query_result_for_cook& query, u32& final_managed_resource_size) { XRAY_UNREFERENCED_PARAMETER ( final_managed_resource_size ); //if no requested file fs::path_string disk_path; if(query.select_disk_path_from_request_path(& disk_path)) make_sound_options (disk_path); return result_dont_reuse; } static void make_sound_options(fs::path_string& end_file_path) { //make path's fs::path_string file_path; file_path = end_file_path; file_path.set_length (file_path.length()-8); file_path.append (".ogg"); STARTUPINFO si; ZeroMemory ( &si, sizeof(si) ); si.cb = sizeof(STARTUPINFO); si.wShowWindow = 0; si.dwFlags = STARTF_USESHOWWINDOW; PROCESS_INFORMATION pi; ZeroMemory ( &pi, sizeof(pi) ); fixed_string512 cl_args; cl_args += "xray_rms_generator-debug.exe"; cl_args += " -o=\""; cl_args += end_file_path.c_str(); cl_args += "\" -i=\""; cl_args += file_path.c_str(); cl_args += "\""; if(CreateProcess(NULL, cl_args.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) WaitForSingleObject(pi.hProcess, INFINITE); } }//namespace resources }//namespace xray #endif // #if 0 // commented by Lain
30.521583
154
0.652858
ixray-team
12d713f4f1018305d22d3ca9d75f1b702414b0b2
7,430
cpp
C++
game.cpp
block8437/GameEngine
e4b452c33781566e55e9339efee9441ddb924f58
[ "MIT" ]
null
null
null
game.cpp
block8437/GameEngine
e4b452c33781566e55e9339efee9441ddb924f58
[ "MIT" ]
1
2017-04-05T00:58:21.000Z
2017-04-05T00:58:21.000Z
game.cpp
block8437/GameEngine
e4b452c33781566e55e9339efee9441ddb924f58
[ "MIT" ]
null
null
null
#include <GL/glew.h> #include "game.h" namespace GameEngine { Game gameObject; GameContactListener myContactListenerInstance; void _display_redirect() { gameObject.display(); } void _reshape_redirect(GLsizei width, GLsizei height) { gameObject.reshape(width, height); } void _exit_redirect() { gameObject.onExit(); } void _timer_redirect(int value) { gameObject.timer(value); } void _keyboardUp_redirect(unsigned char key, int x, int y) { gameObject.keyboardUp(key, x, y); } void _keyboardDown_redirect(unsigned char key, int x, int y) { gameObject.keyboardDown(key, x, y); } void _specialKeys_redirect(int key, int x, int y) { gameObject.specialKeys(key, x, y); } void _mouse_redirect(int button, int state, int x, int y) { gameObject.mouse(button, state, x, y); } Game::Game() { } Game::Game(char* _title, int width, int height, int _argc, char** _argv) { title = _title; originalWindowWidth = width; originalWindowHeight = height; windowWidth = originalWindowWidth; windowHeight = originalWindowHeight; windowPosX = 50; windowPosY = 50; argc = _argc; argv = _argv; refreshMillis = 15.0f; base_time = 0; fps = 0; frames = 0; fullScreenMode = false; } void Game::initGL() { keys[0] = false; keys[1] = false; keys[2] = false; keys[3] = false; glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_ALPHA | GLUT_STENCIL); glutInitWindowSize(windowWidth, windowHeight); glutInitWindowPosition(windowPosX, windowPosY); glutCreateWindow(title); glutDisplayFunc(_display_redirect); glutReshapeFunc(_reshape_redirect); glutTimerFunc(0, _timer_redirect, 0); glutSpecialFunc(_specialKeys_redirect); glutKeyboardUpFunc(_keyboardUp_redirect); glutKeyboardFunc(_keyboardDown_redirect); printf("*** Initializing GL Version: %s\n", (const char*)glGetString(GL_VERSION)); if(fullScreenMode) glutFullScreen(); glutMouseFunc(_mouse_redirect); B2_NOT_USED(argc); B2_NOT_USED(argv); } void Game::begin() { universe.getWorld()->SetContactListener(&myContactListenerInstance); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glOrtho(0.0f,windowWidth,0.0f,windowHeight,0.0f,1.0f); glClearColor(0.0, 0.0, 0.0, 0.0); GLenum error = glGetError(); if(error != GL_NO_ERROR) { printf( "***Error initializing OpenGL! %s\n", gluErrorString( error ) ); exit(0); } GLint GlewInitResult = glewInit(); if (GLEW_OK != GlewInitResult) { printf("***Error initializing GLEW! %s\n",glewGetErrorString(GlewInitResult)); exit(EXIT_FAILURE); } setShader("light","","light.glsl"); light = Light(&universe, 400, 100, 1.0, 1.0f, 0.0f, windowWidth, windowHeight, getShader("light")); glutMainLoop(); } void Game::initGame() { loadLevel("level1.json", &universe, windowWidth, windowHeight); PlayerObject* player = new PlayerObject(universe.getSpritesheet("playersprites"), 2.0f, 50.0f, 300.0f, universe.getWorld(), 640, 480); universe.setActivatePlayer(player); } void Game::keyboardDown(unsigned char key, int x, int y) { switch (key) { case 'd': keys[3] = true; break; case 'a': keys[2] = true; break; case 'w': keys[0] = true; break; case 's': keys[1] = true; break; case 27: // ESC key exit(0); break; } } void Game::keyboardUp(unsigned char key, int x, int y) { switch (key) { case 'd': keys[3] = false; break; case 'a': keys[2] = false; break; case 'w': keys[0] = false; break; case 's': keys[1] = false; break; } } void Game::specialKeys(int key, int x, int y) { switch (key) { case GLUT_KEY_F1: fullScreenMode = !fullScreenMode; if (fullScreenMode) { originalWindowWidth = windowWidth; originalWindowHeight = windowHeight; windowPosX = glutGet(GLUT_WINDOW_X); windowPosY = glutGet(GLUT_WINDOW_Y); windowWidth = glutGet(GLUT_WINDOW_WIDTH); windowHeight = glutGet(GLUT_WINDOW_HEIGHT); reshape(windowWidth, windowHeight); glutFullScreen(); } else { windowWidth = originalWindowWidth; windowHeight = originalWindowHeight; glutReshapeWindow(windowWidth, windowHeight); glutPositionWindow(windowPosX, windowPosX); } break; } } void Game::mouse(int button, int state, int x, int y) { if(!state) { //addMoreBlocks(x, windowHeight - y); printf("Mouse clicked %d (%d,%d)\n", state, x, y); } } void Game::timer(int value) { glutPostRedisplay(); glutTimerFunc(refreshMillis, _timer_redirect, 0); } void Game::display() { frames++; calculateFrameRate(); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); light.render(); universe.render(); universe.update(keys[0], keys[1], keys[2], keys[3]); glutSwapBuffers(); } void Game::reshape(GLsizei width, GLsizei height) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); windowWidth = width; windowHeight = height; glOrtho(0.0f,windowWidth,0.0f,windowHeight,0.0f,1.0f); glViewport(0, 0, width, height); } void Game::calculateFrameRate() { int time = glutGet(GLUT_ELAPSED_TIME); if ((time - base_time) > 1000.0) { fps = frames*1000.0/(time - base_time); base_time = time; frames = 0; } } float Game::getFrameRate() { return fps; } void Game::onExit() { universe.clean(); } void Game::setShader(std::string name, const char* vertex_file, const char* fragment_file) { bool use_vert = vertex_file != "" ? true : false; bool use_frag = fragment_file != "" ? true : false; GLuint program = glCreateProgram(); programMap[name] = program; if(use_vert && use_frag) { vertexMap[name] = glCreateShader(GL_VERTEX_SHADER); fragmentMap[name] = glCreateShader(GL_FRAGMENT_SHADER); std::string vss = get_file_contents(vertex_file); std::string fss = get_file_contents(fragment_file); const char* vv = vss.c_str(); const char* ff = fss.c_str(); glShaderSource(vertexMap[name], 1, &vv, NULL); glShaderSource(fragmentMap[name], 1, &ff, NULL); glCompileShader(vertexMap[name]); glCompileShader(fragmentMap[name]); glAttachShader(programMap[name], vertexMap[name]); glAttachShader(programMap[name], fragmentMap[name]); } else { if(use_vert && !use_frag) { vertexMap[name] = glCreateShader(GL_VERTEX_SHADER); std::string vss = get_file_contents(vertex_file); const char* vv = vss.c_str(); glShaderSource(vertexMap[name], 1, &vv, NULL); glCompileShader(vertexMap[name]); glAttachShader(programMap[name], vertexMap[name]); } else { if(!use_vert && use_frag) { fragmentMap[name] = glCreateShader(GL_FRAGMENT_SHADER); std::string fss = get_file_contents(fragment_file); const char* ff = fss.c_str(); glShaderSource(fragmentMap[name], 1, &ff, NULL); glCompileShader(fragmentMap[name]); glAttachShader(programMap[name], fragmentMap[name]); } else return; // no shader!! } } glLinkProgram(programMap[name]); glValidateProgram(programMap[name]); printf("*** Shader Program '%s' initialized!\n", name.c_str()); } GLuint Game::getShader(std::string name) { return programMap[name]; } Game* NewGame(char* title, int windowWidth, int windowHeight, int argc, char** argv) { gameObject = Game(title, windowWidth, windowHeight, argc, argv); return &gameObject; } }
24.045307
136
0.673351
block8437
12d788c3b34c43755b41891974e020fe89b4e04d
3,497
cpp
C++
lotus/src/scene/SceneManager.cpp
mayant15/lotus
6b01b6bc204c66f3f22c5d3ad59dc08312f1ad20
[ "MIT" ]
6
2020-11-13T14:02:02.000Z
2021-11-30T14:26:50.000Z
lotus/src/scene/SceneManager.cpp
sps1112/lotus
28c048b04a2f30cc1620f7fd10279038c101bd48
[ "MIT" ]
1
2020-07-16T10:51:56.000Z
2020-07-16T10:51:56.000Z
lotus/src/scene/SceneManager.cpp
sps1112/lotus
28c048b04a2f30cc1620f7fd10279038c101bd48
[ "MIT" ]
3
2020-07-13T11:36:29.000Z
2020-10-20T09:13:32.000Z
#include <lotus/scene/SceneManager.h> #include <lotus/ecs/ComponentRegistry.h> #include <lotus/debug.h> #include <lotus/filesystem.h> #include <stdexcept> #include <lotus/ecs/EventManager.h> namespace Lotus::SceneManager { SRef<Scene> currentScene; SRef<Scene> GetCurrentScene() { return currentScene; } inline void attachComponents(Entity entity, const nlohmann::json& info) { auto reg = currentScene->GetRegistry(); auto id = (EntityID) entity; // TODO: Transform should be created first. Right now, component create events are non-immediate, so they're // called only after all components are attached. While that works for now, we should really have some sort of // strict order here. // if (info.contains("CTransform")) // { // // Add a transform first as other components might depend on it // auto entity = CreateEntity(); // CTransform transform; // from_json(entityInfo.at("CTransform"), transform); // entity.AddComponent<CTransform>(transform); // } if (!info.contains("CDisplayName")) { entity.AddComponent<CDisplayName>("Entity " + std::to_string((unsigned int) id)); } for (auto& comp : info.items()) { if (comp.key() != "Prefab") { auto info = GetComponentInfo(comp.key()); info.assignFn(id, *reg, comp.value()); } } } void LoadScene(const std::string& relpath) { currentScene = std::make_shared<Scene>(); currentScene->detail.path = relpath; auto fullpath = ExpandPath(relpath); std::ifstream infile (fullpath); nlohmann::json data; infile >> data; // if (!data.is_array()) if (!data.contains("components")) { throw std::runtime_error { "Invalid scene format" }; } // for (auto& entityInfo : data) for (auto& entityInfo : data["components"]) { if (entityInfo.contains("Prefab")) { auto entity = currentScene->CreateEntity(ExpandPath(entityInfo.at("Prefab").get<std::string>())); attachComponents(entity, entityInfo); } else { auto entity = currentScene->CreateEntity(); attachComponents(entity, entityInfo); } } // TODO: Generate the scene tree EventManager::Get().Dispatch(SceneLoadEvent { currentScene.get() }); } void OnSimulationBegin(const SimulationBeginEvent& event) { // Save a snapshot of the scene } void OnSimulationEnd(const SimulationEndEvent& event) { // Restore the scene with snapshot } void SaveScene() { // TODO: Save changes to disk. I'll probably need to fix the serialization thing once and for all // TODO: The above is done, sort of. Save prefab information too. LOG_INFO("Saving scene..."); auto* reg = currentScene->GetRegistry(); OutputArchive archive { reg }; // Save all components SerializeComponents(archive); // Dump to file archive.DumpToFile(Lotus::ExpandPath(currentScene->detail.path)); LOG_INFO("Saved!"); } }
30.408696
120
0.560766
mayant15
12d87943a99b04bdf0c3a0c6421bb9d224ba0234
356
cpp
C++
HackerRank/Recursion/reverse_string.cpp
nullpointxr/HackerRankSolutions
052c9ab66bfd66268b81d8e7888c3d7504ab988f
[ "Apache-2.0" ]
1
2020-10-25T16:12:09.000Z
2020-10-25T16:12:09.000Z
HackerRank/Recursion/reverse_string.cpp
abhishek-sankar/Competitive-Coding-Solutions
052c9ab66bfd66268b81d8e7888c3d7504ab988f
[ "Apache-2.0" ]
3
2020-11-12T05:44:24.000Z
2021-04-05T08:09:01.000Z
HackerRank/Recursion/reverse_string.cpp
nullpointxr/HackerRankSolutions
052c9ab66bfd66268b81d8e7888c3d7504ab988f
[ "Apache-2.0" ]
null
null
null
#include<bits/stdc++.h> using namespace std; string reverse(string name){ // 3 steps // one step simpler? // My function CAN // how will I use the function which can do 1 step simpler to solve present problem? // Base case: if(name.length()<=1) return name; return reverse(name.substr(1))+name[0]; } int main(){ cout<<reverse("kehsihbA")<<endl; }
23.733333
85
0.685393
nullpointxr
12db14f05af5c98a3b912e29cda983f9834fbab6
629
hpp
C++
public/sketch/application.hpp
vladislavmarkov/sketch
5afed3edd0245942ed2010df1d092fc7d1ed8610
[ "MIT" ]
null
null
null
public/sketch/application.hpp
vladislavmarkov/sketch
5afed3edd0245942ed2010df1d092fc7d1ed8610
[ "MIT" ]
null
null
null
public/sketch/application.hpp
vladislavmarkov/sketch
5afed3edd0245942ed2010df1d092fc7d1ed8610
[ "MIT" ]
null
null
null
#pragma once #ifndef SK_APPLICATION_HPP #define SK_APPLICATION_HPP #include <sketch/window.hpp> namespace sk { class application_t final { std::vector<window_t> _windows; bool _running = {true}; public: application_t& operator=(const application_t&) = delete; application_t& operator=(application_t&&) = delete; application_t(const application_t&) = delete; application_t(application_t&&) = delete; application_t(); ~application_t(); void add(window_t&&); int run(); void quit(); bool is_running() const; }; } #endif // SK_APPLICATION_HPP
20.966667
60
0.655008
vladislavmarkov
12e1de9878cc3d4aa88a9cb99bb560e034b69a85
1,663
cpp
C++
perception_oru-port-kinetic/graph_map/src/template/template_reg_type.cpp
lllray/ndt-loam
331867941e0764b40e1a980dd85d2174f861e9c8
[ "BSD-3-Clause" ]
1
2020-11-14T08:21:13.000Z
2020-11-14T08:21:13.000Z
perception_oru-port-kinetic/graph_map/src/template/template_reg_type.cpp
lllray/ndt-loam
331867941e0764b40e1a980dd85d2174f861e9c8
[ "BSD-3-Clause" ]
1
2021-07-28T04:47:56.000Z
2021-07-28T04:47:56.000Z
perception_oru-port-kinetic/graph_map/src/template/template_reg_type.cpp
lllray/ndt-loam
331867941e0764b40e1a980dd85d2174f861e9c8
[ "BSD-3-Clause" ]
2
2020-12-18T11:25:53.000Z
2022-02-19T12:59:59.000Z
#include "graph_map/template/template_reg_type.h" namespace perception_oru{ namespace libgraphMap{ TemplateRegType::TemplateRegType(const Affine3d &sensor_pose,RegParamPtr paramptr):registrationType(sensor_pose,paramptr){ TemplateRegTypeParamPtr param = boost::dynamic_pointer_cast< TemplateRegTypeParam >(paramptr);//Should not be NULL if(param!=NULL){ //Transfer all parameters from param to this class cout<<"Created registration type for template"<<endl; } else cerr<<"ndtd2d registrator has NULL parameters"<<endl; } TemplateRegType::~TemplateRegType(){} bool TemplateRegType::Register(MapTypePtr maptype, Eigen::Affine3d &Tnow, pcl::PointCloud<pcl::PointXYZ> &cloud, Matrix6d cov) { if(!enableRegistration_||!maptype->Initialized()){ cout<<"Registration disabled - motion based on odometry"<<endl; return false; } else{ TemplateMapTypePtr MapPtr = boost::dynamic_pointer_cast< TemplateMapType >(maptype); //Perform registration based on prediction "Tinit", your map "MapPtr" and the "cloud" cout<<"please fill in code for registration- uintil then, registration is disabled"<<endl; } return false;//remove this when registration code has been implemented } /* ----------- Parameters ------------*/ TemplateRegTypeParam::~TemplateRegTypeParam(){} TemplateRegTypeParam::TemplateRegTypeParam():registrationParameters(){ } void TemplateRegTypeParam::GetParametersFromRos(){ registrationParameters::GetParametersFromRos(); ros::NodeHandle nh("~");//base class parameters nh.param<std::string>("super_important_parameter",super_important_parameter_,"default string"); } } }//end namespace
30.236364
128
0.753458
lllray
12e6c2e4c800db0f43c8e684214f56283e2a5c1b
84
hpp
C++
tests/wf/operators/shift_equal_continuation.hpp
GuillaumeDua/CppShelf
fc559010a5e38cecfd1967ebbbba21fd4b38e5ee
[ "MIT" ]
3
2021-12-09T20:02:51.000Z
2022-03-23T09:22:58.000Z
tests/wf/operators/shift_equal_continuation.hpp
GuillaumeDua/CppShelf
fc559010a5e38cecfd1967ebbbba21fd4b38e5ee
[ "MIT" ]
31
2021-08-11T16:14:43.000Z
2022-03-31T11:45:24.000Z
tests/wf/operators/shift_equal_continuation.hpp
GuillaumeDua/CppShelf
fc559010a5e38cecfd1967ebbbba21fd4b38e5ee
[ "MIT" ]
null
null
null
#pragma once #include <csl/wf.hpp> namespace test::wf::operators::shift_equal { }
12
44
0.714286
GuillaumeDua
12e704d2048d8696df6c3977c76a7d017c261b4e
1,740
cpp
C++
graphs/prims.cpp
sumanbanerjee1/Algorithms-and-data-structures
0bc61036c398bd3cea5f7ddf80535520de3a33fa
[ "Apache-2.0" ]
null
null
null
graphs/prims.cpp
sumanbanerjee1/Algorithms-and-data-structures
0bc61036c398bd3cea5f7ddf80535520de3a33fa
[ "Apache-2.0" ]
null
null
null
graphs/prims.cpp
sumanbanerjee1/Algorithms-and-data-structures
0bc61036c398bd3cea5f7ddf80535520de3a33fa
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<bits/stdc++.h> # define inf INT_MAX using namespace std; typedef pair<int,int> iPair; class Graph{ int v; list< pair<int,int> > *adj; public: Graph(int vert) { v=vert; adj = new list< pair<int,int> > [vert]; } void addEdge(int u,int v,int w) { adj[u].push_back(make_pair(w,v)); adj[v].push_back(make_pair(w,u)); } void disp() { for(int i=0;i<v;i++) { cout<<i<<"->"; list < pair<int,int> > :: iterator j; for(j = adj[i].begin();j!=adj[i].end();j++) cout<<"("<<(*j).second<<","<<(*j).first<<")->"; cout<<endl; } } long int prims(int s) { priority_queue <iPair , vector<iPair>, greater<iPair> > pq; vector<int> dist(v,inf); dist[s]=0; pq.push(make_pair(0,s)); vector<bool> inMST(v,false); inMST[s] = true; vector<int> parent(v,-1); while(!pq.empty()) { int u=pq.top().second; pq.pop(); inMST[u] = true; for(list< pair<int,int> > :: iterator j = adj[u].begin(); j!=adj[u].end(); j++) { int node = (*j).second; if(inMST[node]==false and dist[node]>(*j).first) { dist[node] = (*j).first; pq.push(make_pair(dist[node],node)); parent[node] = u; } } } long int sum=0; for(int i=0;i<v;i++) sum+= dist[i]; return sum; } }; int main() { Graph *g = new Graph(9); g->addEdge(0, 1, 4); g->addEdge(0, 7, 8); g->addEdge(1, 2, 8); g->addEdge(1, 7, 11); g->addEdge(2, 3, 7); g->addEdge(2, 8, 2); g->addEdge(2, 5, 4); g->addEdge(3, 4, 9); g->addEdge(3, 5, 14); g->addEdge(4, 5, 10); g->addEdge(5, 6, 2); g->addEdge(6, 7, 1); g->addEdge(6, 8, 6); g->addEdge(7, 8, 7); //g->disp(); cout<<g->prims(0); return 1; }
16.571429
82
0.518966
sumanbanerjee1
12ebbe81215360c5ec694657e40dc4aa19622a20
9,527
cpp
C++
test/OpenDDLExportTest.cpp
lerppana/openddl-parser
a9bc8a5dee880d546136e33a5977d7a0a28eaa20
[ "MIT" ]
24
2015-02-08T23:16:05.000Z
2021-07-15T07:31:08.000Z
test/OpenDDLExportTest.cpp
lerppana/openddl-parser
a9bc8a5dee880d546136e33a5977d7a0a28eaa20
[ "MIT" ]
64
2015-01-28T21:42:06.000Z
2021-11-01T07:49:24.000Z
test/OpenDDLExportTest.cpp
lerppana/openddl-parser
a9bc8a5dee880d546136e33a5977d7a0a28eaa20
[ "MIT" ]
10
2015-11-17T09:18:57.000Z
2021-10-06T18:59:05.000Z
/*----------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2014-2020 Kim Kulling 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 "gtest/gtest.h" #include "UnitTestCommon.h" #include <openddlparser/DDLNode.h> #include <openddlparser/OpenDDLExport.h> #include <openddlparser/Value.h> BEGIN_ODDLPARSER_NS class OpenDDLExportMock : public OpenDDLExport { public: OpenDDLExportMock() : OpenDDLExport() { // empty } virtual ~OpenDDLExportMock() { // empty } virtual bool writeNodeHeaderTester(DDLNode *node, std::string &statement) { return writeNodeHeader(node, statement); } virtual bool writePropertiesTester(DDLNode *node, std::string &statement) { return writeProperties(node, statement); } virtual bool writeValueTypeTester(Value::ValueType type, size_t numItems, std::string &statement) { return writeValueType(type, numItems, statement); } virtual bool writeValueTester(Value *val, std::string &statement) { return writeValue(val, statement); } virtual bool writeValueArrayTester(DataArrayList *al, std::string &statement) { return writeValueArray(al, statement); } }; class OpenDDLExportTest : public testing::Test { public: DDLNode *m_root; protected: void SetUp() override { m_root = createNodeHierarchy(); } void TearDown() override { delete m_root; m_root = nullptr; } DDLNode *createNodeHierarchy() { DDLNode *root = DDLNode::create("test", "root"); for (uint32 i = 0; i < 10; i++) { DDLNode *node(DDLNode::create("test", "child")); node->attachParent(root); } return root; } Property *createProperties(size_t numProps) { if (0 == numProps) { return nullptr; } Property *prop(nullptr), *first(nullptr), *prev(nullptr); for (size_t i = 0; i < numProps; i++) { static const size_t Size = 256; char buffer[Size]; ::memset(buffer, 0, Size); sprintf(buffer, "id.%d", static_cast<int>(i)); Text *id = new Text(buffer, strlen(buffer)); Value *v = ValueAllocator::allocPrimData(Value::ValueType::ddl_int32); v->setInt32(static_cast<int>(i)); prop = new Property(id); prop->m_value = v; if (nullptr == first) { first = prop; } if (nullptr != prev) { prev->m_next = prop; } prev = prop; } return first; } }; TEST_F(OpenDDLExportTest, createTest) { bool ok(true); try { OpenDDLExport myExport; } catch (...) { ok = false; } EXPECT_TRUE(ok); } TEST_F(OpenDDLExportTest, handleNodeTest) { OpenDDLExport myExport; bool success(true); success = myExport.handleNode(m_root); EXPECT_TRUE(success); } TEST_F(OpenDDLExportTest, writeNodeHeaderTest) { OpenDDLExportMock myExport; bool ok(true); std::string statement; ok = myExport.writeNodeHeaderTester(nullptr, statement); EXPECT_FALSE(ok); DDLNode *node(DDLNode::create("test", "")); node->attachParent(m_root); ok = myExport.writeNodeHeaderTester(node, statement); EXPECT_TRUE(ok); EXPECT_EQ("test", statement); statement.clear(); ok = myExport.writeNodeHeaderTester(m_root, statement); EXPECT_TRUE(ok); EXPECT_EQ("test $root", statement); } TEST_F(OpenDDLExportTest, writeBoolTest) { OpenDDLExportMock myExport; Value *v = ValueAllocator::allocPrimData(Value::ValueType::ddl_bool); v->setBool(true); std::string statement; bool ok(true); ok = myExport.writeValueTester(v, statement); EXPECT_TRUE(ok); EXPECT_EQ("true", statement); v->setBool(false); statement.clear(); ok = myExport.writeValueTester(v, statement); EXPECT_TRUE(ok); EXPECT_EQ("false", statement); ValueAllocator::releasePrimData(&v); } TEST_F(OpenDDLExportTest, writeIntegerTest) { OpenDDLExportMock myExport; Value *v = ValueAllocator::allocPrimData(Value::ValueType::ddl_int8); v->setInt8(10); bool ok(true); std::string statement; ok = myExport.writeValueTester(v, statement); EXPECT_TRUE(ok); EXPECT_EQ("10", statement); ValueAllocator::releasePrimData(&v); statement.clear(); v = ValueAllocator::allocPrimData(Value::ValueType::ddl_int16); v->setInt16(655); ok = myExport.writeValueTester(v, statement); EXPECT_TRUE(ok); EXPECT_EQ("655", statement); ValueAllocator::releasePrimData(&v); statement.clear(); v = ValueAllocator::allocPrimData(Value::ValueType::ddl_int32); v->setInt32(65501); ok = myExport.writeValueTester(v, statement); EXPECT_TRUE(ok); EXPECT_EQ("65501", statement); ValueAllocator::releasePrimData(&v); statement.clear(); v = ValueAllocator::allocPrimData(Value::ValueType::ddl_int64); v->setInt64(65502); ok = myExport.writeValueTester(v, statement); EXPECT_TRUE(ok); EXPECT_EQ("65502", statement); ValueAllocator::releasePrimData(&v); } TEST_F(OpenDDLExportTest, writeFloatTest) { OpenDDLExportMock myExport; Value *v = ValueAllocator::allocPrimData(Value::ValueType::ddl_float); v->setFloat(1.1f); bool ok(true); std::string statement; ok = myExport.writeValueTester(v, statement); EXPECT_TRUE(ok); EXPECT_EQ("1.1", statement); ValueAllocator::releasePrimData(&v); } TEST_F(OpenDDLExportTest, writeStringTest) { OpenDDLExportMock myExport; char tempString[] = "huhu"; Value *v = ValueAllocator::allocPrimData(Value::ValueType::ddl_string, sizeof(tempString)); v->setString(tempString); bool ok(true); std::string statement; ok = myExport.writeValueTester(v, statement); EXPECT_TRUE(ok); EXPECT_EQ("\"huhu\"", statement); ValueAllocator::releasePrimData(&v); } TEST_F(OpenDDLExportTest, writeValueTypeTest) { OpenDDLExportMock myExporter; bool ok(true); std::string statement; ok = myExporter.writeValueTypeTester(Value::ValueType::ddl_types_max, 1, statement); EXPECT_FALSE(ok); EXPECT_TRUE(statement.empty()); Value *v_int32 = ValueAllocator::allocPrimData(Value::ValueType::ddl_int32); ok = myExporter.writeValueTypeTester(v_int32->m_type, 1, statement); EXPECT_TRUE(ok); EXPECT_EQ("int32", statement); statement.clear(); delete v_int32; Value *v_int32_array = ValueAllocator::allocPrimData(Value::ValueType::ddl_int32); ok = myExporter.writeValueTypeTester(v_int32_array->m_type, 10, statement); EXPECT_TRUE(ok); EXPECT_EQ("int32[10]", statement); delete v_int32_array; } TEST_F(OpenDDLExportTest, writePropertiesTest) { OpenDDLExportMock myExporter; bool ok(true); std::string statement; ok = myExporter.writePropertiesTester(nullptr, statement); EXPECT_FALSE(ok); Property *prop(createProperties(1)); m_root->setProperties(prop); ok = myExporter.writePropertiesTester(m_root, statement); EXPECT_TRUE(ok); EXPECT_EQ("(id.0 = 0)", statement); statement.clear(); Property *prop2(createProperties(2)); m_root->setProperties(prop2); ok = myExporter.writePropertiesTester(m_root, statement); EXPECT_TRUE(ok); EXPECT_EQ("(id.0 = 0, id.1 = 1)", statement); } TEST_F(OpenDDLExportTest, writeValueArrayTest) { OpenDDLExportMock myExporter; bool ok(true); std::string statement; ok = myExporter.writeValueArrayTester(nullptr, statement); EXPECT_FALSE(ok); EXPECT_TRUE(statement.empty()); char token[] = "float[ 3 ]\n" "{\n" " {1, 2, 3}\n" "}\n"; size_t len(0); char *end = findEnd(token, len); DataArrayList *dataArrayList = nullptr; Value::ValueType type; char *in = OpenDDLParser::parsePrimitiveDataType(token, end, type, len); ASSERT_EQ(Value::ValueType::ddl_float, type); ASSERT_EQ(3U, len); in = OpenDDLParser::parseDataArrayList(in, end, type, &dataArrayList); ASSERT_FALSE(nullptr == dataArrayList); ok = myExporter.writeValueArrayTester(dataArrayList, statement); EXPECT_TRUE(ok); EXPECT_EQ("{ 1, 2, 3 }", statement); delete dataArrayList; } END_ODDLPARSER_NS
30.4377
103
0.65771
lerppana
12eea4cf8d075f0f2846a72b60c340db33b652de
4,856
cpp
C++
files/soko1/qutim_0.1.1/protocol/oscar/icq/multiplesending.cpp
truebsdorg/truebsdorg.github.io
8663d8f6fae3b1bb1e2fb29614677f2863521951
[ "BSD-4-Clause-UC" ]
null
null
null
files/soko1/qutim_0.1.1/protocol/oscar/icq/multiplesending.cpp
truebsdorg/truebsdorg.github.io
8663d8f6fae3b1bb1e2fb29614677f2863521951
[ "BSD-4-Clause-UC" ]
null
null
null
files/soko1/qutim_0.1.1/protocol/oscar/icq/multiplesending.cpp
truebsdorg/truebsdorg.github.io
8663d8f6fae3b1bb1e2fb29614677f2863521951
[ "BSD-4-Clause-UC" ]
null
null
null
/* multipleSending Copyright (c) 2008 by Rustam Chakin <[email protected]> *************************************************************************** * * * 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. * * * *************************************************************************** */ #include "treegroupitem.h" #include "treebuddyitem.h" #include "icqmessage.h" #include "multiplesending.h" multipleSending::multipleSending(QWidget *parent) : QWidget(parent) { ui.setupUi(this); setWindowTitle(tr("Send multiple")); setWindowIcon(QIcon(":/icons/crystal_project/multiple.png")); move(desktopCenter()); ui.contactListWidget->header()->hide(); QList<int> listSize; listSize.append(408); listSize.append(156); ui.splitter->setSizes(listSize); sendTimer = new QTimer(this); connect(sendTimer, SIGNAL(timeout()), this, SLOT(sendMessage())); } multipleSending::~multipleSending() { } void multipleSending::rellocateDialogToCenter(QWidget *widget) { QDesktopWidget desktop; // Get current screen num int curScreen = desktop.screenNumber(widget); // Get available geometry of the screen QRect screenGeom = desktop.availableGeometry(curScreen); // Let's calculate point to move dialog QPoint moveTo(screenGeom.left(), screenGeom.top()); moveTo.setX(moveTo.x() + screenGeom.width() / 2); moveTo.setY(moveTo.y() + screenGeom.height() / 2); moveTo.setX(moveTo.x() - this->size().width() / 2); moveTo.setY(moveTo.y() - this->size().height() / 2); this->move(moveTo); } void multipleSending::setTreeModel(const QString &uin, const QHash<quint16, treeGroupItem *> *groupList, const QHash<QString, treeBuddyItem *> *buddyList) { rootItem = new QTreeWidgetItem(ui.contactListWidget); rootItem->setText(0, uin); rootItem->setFlags(rootItem->flags() | Qt::ItemIsUserCheckable); rootItem->setCheckState(0, Qt::Unchecked); foreach(treeGroupItem *getgroup, *groupList) { QTreeWidgetItem *group = new QTreeWidgetItem(rootItem); group->setText(0,getgroup->name); group->setFlags(group->flags() | Qt::ItemIsUserCheckable); group->setCheckState(0, Qt::Unchecked); foreach(treeBuddyItem *getbuddy, *buddyList) { if ( getbuddy->groupName == getgroup->name) { QTreeWidgetItem *buddy = new QTreeWidgetItem(group); buddy->setText(0,getbuddy->getName()); buddy->setIcon(0, getbuddy->icon(0)); buddy->setFlags(buddy->flags() | Qt::ItemIsUserCheckable); buddy->setCheckState(0, Qt::Unchecked); buddy->setToolTip(0,getbuddy->getUin()); } } if ( group->childCount() ) group->setExpanded(true); } if ( rootItem->childCount() ) rootItem->setExpanded(true); } void multipleSending::on_contactListWidget_itemChanged(QTreeWidgetItem *item, int ) { if ( item->childCount() ) { Qt::CheckState checkState = item->checkState(0); for ( int i = 0; i < item->childCount(); i++) { item->child(i)->setCheckState(0,checkState); } } } QPoint multipleSending::desktopCenter() { QDesktopWidget desktop; return QPoint(desktop.width() / 2 - size().width() / 2, desktop.height() / 2 - size().height() / 2); } void multipleSending::on_sendButton_clicked() { if ( !ui.messageEdit->toPlainText().isEmpty()) { ui.sendButton->setEnabled(false); ui.stopButton->setEnabled(true); for( int i = 0; i < rootItem->childCount(); i++) { QTreeWidgetItem *group = rootItem->child(i); for ( int j = 0; j < group->childCount(); j++) { if ( !group->child(j)->toolTip(0).isEmpty() && group->child(j)->checkState(0)) sendToList<<group->child(j)->toolTip(0); } } barInterval = sendToList.count(); if (barInterval) { sendMessage(); } else on_stopButton_clicked(); } } void multipleSending::on_stopButton_clicked() { ui.sendButton->setEnabled(true); ui.stopButton->setEnabled(false); sendToList.clear(); sendTimer->stop(); ui.progressBar->setValue(0); } void multipleSending::sendMessage() { if ( !ui.messageEdit->toPlainText().isEmpty()) { if ( sendToList.count() ) { messageFormat msg; msg.date = QDateTime::currentDateTime(); msg.fromUin = sendToList.at(0); msg.message = ui.messageEdit->toPlainText(); emit sendMessageToContact(msg); sendToList.removeAt(0); sendTimer->start(2000); ui.progressBar->setValue(ui.progressBar->value() + 100 / barInterval ); if ( !sendToList.count() ) on_stopButton_clicked(); } else on_stopButton_clicked(); } else on_stopButton_clicked(); }
27.280899
154
0.644563
truebsdorg
12f00818638db4fb4442d04bef80cc851d808e1c
1,926
cpp
C++
Game/ui/documentmenu.cpp
da3m0nsec/OpenGothic
af30c52309cb84ff338d42554610679e0e245f91
[ "MIT" ]
null
null
null
Game/ui/documentmenu.cpp
da3m0nsec/OpenGothic
af30c52309cb84ff338d42554610679e0e245f91
[ "MIT" ]
null
null
null
Game/ui/documentmenu.cpp
da3m0nsec/OpenGothic
af30c52309cb84ff338d42554610679e0e245f91
[ "MIT" ]
null
null
null
#include "documentmenu.h" #include "utils/gthfont.h" #include "gothic.h" using namespace Tempest; DocumentMenu::DocumentMenu(Gothic& gothic) :gothic(gothic) { } void DocumentMenu::show(const DocumentMenu::Show &doc) { document = doc; active = true; update(); } void DocumentMenu::close() { if(!active) return; active=false; if(auto pl = gothic.player()) pl->setInteraction(nullptr); } void DocumentMenu::keyDownEvent(KeyEvent &e) { if(!active){ e.ignore(); return; } if(e.key!=Event::K_ESCAPE){ e.ignore(); return; } close(); } void DocumentMenu::keyUpEvent(KeyEvent&) { } void DocumentMenu::paintEvent(PaintEvent &e) { if(!active) return; float mw = 0, mh = 0; for(auto& i:document.pages){ auto back = Resources::loadTexture((i.flg&F_Backgr) ? i.img : document.img); if(!back) continue; mw += float(back->w()); mh = std::max(mh,float(back->h())); } float k = std::min(1.f,float(800+document.margins.xMargin())/std::max(mw,1.f)); int x=(w()-int(k*mw))/2, y = (h()-int(mh))/2; Painter p(e); for(auto& i:document.pages){ const GthFont* fnt = nullptr; if(i.flg&F_Font) fnt = &Resources::font(i.font.c_str()); else fnt = &Resources::font(document.font.c_str()); if(fnt==nullptr) fnt = &Resources::font(); auto back = Resources::loadTexture((i.flg&F_Backgr) ? i.img : document.img); if(!back) continue; auto& mgr = (i.flg&F_Margin) ? i.margins : document.margins; const int w = int(k*float(back->w())); p.setBrush(*back); p.drawRect(x,y,w,back->h(), 0,0,back->w(),back->h()); p.setBrush(Color(0.04f,0.04f,0.04f,1)); fnt->drawText(p,x+mgr.left, y+mgr.top, w - mgr.xMargin(), back->h() - mgr.yMargin(), i.text, Tempest::AlignLeft); x+=w; } }
21.640449
81
0.573209
da3m0nsec
12f31d7d66104c07eb40b842fac64512ce7d4837
1,017
cpp
C++
Engine/src/DebugPass.cpp
Swizzman/DV1573_Stort_Spel
77ed6524988b0b501d9b556c487a36d929a20313
[ "MIT" ]
3
2022-01-29T12:05:53.000Z
2022-02-20T16:00:26.000Z
Engine/src/DebugPass.cpp
Swizzman/Homehearth
77ed6524988b0b501d9b556c487a36d929a20313
[ "MIT" ]
null
null
null
Engine/src/DebugPass.cpp
Swizzman/Homehearth
77ed6524988b0b501d9b556c487a36d929a20313
[ "MIT" ]
null
null
null
#include "EnginePCH.h" #include "BasePass.h" void DebugPass::PreRender(Camera* pCam, ID3D11DeviceContext* pDeviceContext) { DC->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); DC->IASetInputLayout(PM->m_defaultInputLayout.Get()); DC->VSSetShader(PM->m_defaultVertexShader.Get(), nullptr, 0); DC->PSSetShader(PM->m_debugPixelShader.Get(), nullptr, 0); DC->VSSetConstantBuffers(1, 1, pCam->m_viewConstantBuffer.GetAddressOf()); DC->RSSetViewports(1, &PM->m_viewport); DC->RSSetState(PM->m_rasterStateWireframe.Get()); DC->OMSetRenderTargets(1, PM->m_backBuffer.GetAddressOf(), PM->m_debugDepthStencilView.Get()); //DC->OMSetDepthStencilState(PM->m_depthStencilStateEqualAndDisableDepthWrite.Get(), 0); } void DebugPass::Render(Scene* pScene) { pScene->RenderDebug(); } void DebugPass::PostRender(ID3D11DeviceContext* pDeviceContext) { // Cleanup. //ID3D11ShaderResourceView* nullSRV[] = { nullptr }; //DC->PSSetShaderResources(0, 1, nullSRV); }
31.78125
98
0.73648
Swizzman
12f9ed1bfd569b99c78754fff91318080f6565de
1,115
cc
C++
day06/main.cc
HappyCerberus/moderncpp-aoc-2021
0973201f2e1c2c6c2900162e3829a68477818ced
[ "MIT" ]
20
2021-12-04T04:53:22.000Z
2022-02-24T23:37:31.000Z
day06/main.cc
HappyCerberus/moderncpp-aoc-2021
0973201f2e1c2c6c2900162e3829a68477818ced
[ "MIT" ]
null
null
null
day06/main.cc
HappyCerberus/moderncpp-aoc-2021
0973201f2e1c2c6c2900162e3829a68477818ced
[ "MIT" ]
1
2022-01-04T22:12:05.000Z
2022-01-04T22:12:05.000Z
#include "lanternfish.h" #include <fstream> #include <iostream> #include <string> int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << "This program expects one parameter that is the input file to read.\n"; return 1; } std::ifstream input(argv[1]); if (!input.is_open()) { std::cerr << "Failed to open file.\n"; return 1; } std::string starting_pop; if (!getline(input, starting_pop)) throw std::runtime_error("Failed to read input."); constexpr const uint32_t days_part1 = 80; { Population pop; init_population(pop, starting_pop); for (uint32_t i = 0; i < days_part1; i++) simulate_day(pop); std::cout << "Simulated population size of lanternfish after " << days_part1 << " is " << total_pop_count(pop) << "\n"; } constexpr const uint32_t days_part2 = 256; { Population pop; init_population(pop, starting_pop); for (uint32_t i = 0; i < days_part2; i++) simulate_day(pop); std::cout << "Simulated population size of lanternfish after " << days_part2 << " is " << total_pop_count(pop) << "\n"; } return 0; }
27.875
123
0.636771
HappyCerberus
12fe5a69ec6ca62a21385ca1c1c89d205758bd44
7,569
cpp
C++
Samples/RnD/DDGI/SVGFPass.cpp
guoxx/DDGI
cc8b6b8194ff4473cdf21f72754a103cd6f8526d
[ "BSD-3-Clause" ]
15
2019-11-12T21:45:58.000Z
2022-02-08T07:07:06.000Z
Samples/RnD/DDGI/SVGFPass.cpp
guoxx/DDGI
cc8b6b8194ff4473cdf21f72754a103cd6f8526d
[ "BSD-3-Clause" ]
1
2020-01-16T07:21:23.000Z
2020-02-07T02:39:27.000Z
Samples/RnD/DDGI/SVGFPass.cpp
guoxx/DDGI
cc8b6b8194ff4473cdf21f72754a103cd6f8526d
[ "BSD-3-Clause" ]
3
2020-05-16T12:35:34.000Z
2022-01-23T07:30:47.000Z
#include "SVGFPass.h" using namespace Falcor; SVGFPass::SharedPtr SVGFPass::create(uint32_t width, uint32_t height) { return std::make_shared<SVGFPass>(width, height); } SVGFPass::SVGFPass(uint32_t width, uint32_t height) : mAtrousIterations(4), mFeedbackTap(1), mAtrousRadius(2), mAlpha(0.15f), mMomentsAlpha(0.2f), mPhiColor(10.0f), mPhiNormal(128.0f), mEnableTemporalReprojection(true), mEnableSpatialVarianceEstimation(true) { Fbo::Desc reprojFboDesc; reprojFboDesc.setColorTarget(0, ResourceFormat::RGBA16Float); // Input signal, variance reprojFboDesc.setColorTarget(1, ResourceFormat::RG16Float); // 1st and 2nd Moments reprojFboDesc.setColorTarget(2, ResourceFormat::R16Float); // History length mCurrReprojFbo = FboHelper::create2D(width, height, reprojFboDesc); mPrevReprojFbo = FboHelper::create2D(width, height, reprojFboDesc); Fbo::Desc atrousFboDesc; atrousFboDesc.setColorTarget(0, ResourceFormat::RGBA16Float); // Input signal, variance mOutputFbo = FboHelper::create2D(width, height, atrousFboDesc); mLastFilteredFbo = FboHelper::create2D(width, height, atrousFboDesc); mAtrousPingFbo = FboHelper::create2D(width, height, atrousFboDesc); mAtrousPongFbo = FboHelper::create2D(width, height, atrousFboDesc); mPrevLinearZTexture = Texture::create2D(width, height, ResourceFormat::RGBA32Float, 1, 1, nullptr, ResourceBindFlags::ShaderResource | ResourceBindFlags::RenderTarget); mReprojectionPass = FullScreenPass::create("SVGF_Reprojection.slang"); mReprojectionVars = GraphicsVars::create(mReprojectionPass->getProgram()->getReflector()); mReprojectionState = GraphicsState::create(); mVarianceEstimationPass = FullScreenPass::create("SVGF_VarianceEstimation.slang"); mVarianceEstimationVars = GraphicsVars::create(mVarianceEstimationPass->getProgram()->getReflector()); mVarianceEstimationState = GraphicsState::create(); mAtrousPass = FullScreenPass::create("SVGF_Atrous.slang"); mAtrousPass->getProgram()->addDefine("ATROUS_RADIUS", std::to_string(mAtrousRadius)); mAtrousVars = GraphicsVars::create(mAtrousPass->getProgram()->getReflector()); mAtrousState = GraphicsState::create(); } SVGFPass::~SVGFPass() { } Texture::SharedPtr SVGFPass::Execute( RenderContext* renderContext, Texture::SharedPtr inputSignal, Texture::SharedPtr motionVec, Texture::SharedPtr linearZ, Texture::SharedPtr normalDepth) { GPU_EVENT(renderContext, "SVGF"); mGBufferInput.inputSignal = inputSignal; mGBufferInput.linearZ = linearZ; mGBufferInput.motionVec = motionVec; mGBufferInput.compactNormalDepth = normalDepth; TemporalReprojection(renderContext); SpatialVarianceEstimation(renderContext); for (uint32_t i = 0; i < mAtrousIterations; ++i) { Fbo::SharedPtr output = (i == mAtrousIterations - 1) ? mOutputFbo : mAtrousPongFbo; AtrousFilter(renderContext, i, mAtrousPingFbo, output); if (i == std::min(mFeedbackTap, mAtrousIterations-1)) { renderContext->blit(output->getColorTexture(0)->getSRV(), mLastFilteredFbo->getColorTexture(0)->getRTV(), uvec4(-1), uvec4(-1), Sampler::Filter::Point); } std::swap(mAtrousPingFbo, mAtrousPongFbo); } std::swap(mCurrReprojFbo, mPrevReprojFbo); renderContext->blit(mGBufferInput.linearZ->getSRV(), mPrevLinearZTexture->getRTV(), uvec4(-1), uvec4(-1), Sampler::Filter::Point); return mOutputFbo->getColorTexture(0); } void SVGFPass::TemporalReprojection(RenderContext* renderContext) { GPU_EVENT(renderContext, "TemporalReprojection"); mReprojectionVars->setTexture("gInputSignal", mGBufferInput.inputSignal); mReprojectionVars->setTexture("gLinearZ", mGBufferInput.linearZ); mReprojectionVars->setTexture("gMotion", mGBufferInput.motionVec); mReprojectionVars->setTexture("gPrevLinearZ", mPrevLinearZTexture); mReprojectionVars->setTexture("gPrevInputSignal", mLastFilteredFbo->getColorTexture(0)); mReprojectionVars->setTexture("gPrevMoments", mPrevReprojFbo->getColorTexture(1)); mReprojectionVars->setTexture("gHistoryLength", mPrevReprojFbo->getColorTexture(2)); mReprojectionVars["PerPassCB"]["gAlpha"] = mAlpha; mReprojectionVars["PerPassCB"]["gMomentsAlpha"] = mMomentsAlpha; mReprojectionVars["PerPassCB"]["gEnableTemporalReprojection"] = mEnableTemporalReprojection; mReprojectionState->setFbo(mCurrReprojFbo); renderContext->pushGraphicsState(mReprojectionState); renderContext->pushGraphicsVars(mReprojectionVars); mReprojectionPass->execute(renderContext); renderContext->popGraphicsVars(); renderContext->popGraphicsState(); } void SVGFPass::SpatialVarianceEstimation(RenderContext* renderContext) { GPU_EVENT(renderContext, "SpatialVarianceEstimation"); mVarianceEstimationVars->setTexture("gCompactNormDepth", mGBufferInput.compactNormalDepth); mVarianceEstimationVars->setTexture("gInputSignal", mCurrReprojFbo->getColorTexture(0)); mVarianceEstimationVars->setTexture("gMoments", mCurrReprojFbo->getColorTexture(1)); mVarianceEstimationVars->setTexture("gHistoryLength", mCurrReprojFbo->getColorTexture(2)); mVarianceEstimationVars["PerPassCB"]["gPhiColor"] = mPhiColor; mVarianceEstimationVars["PerPassCB"]["gPhiNormal"] = mPhiNormal; mVarianceEstimationVars["PerPassCB"]["gEnableSpatialVarianceEstimation"] = mEnableSpatialVarianceEstimation; mVarianceEstimationState->setFbo(mAtrousPingFbo); renderContext->pushGraphicsState(mVarianceEstimationState); renderContext->pushGraphicsVars(mVarianceEstimationVars); mVarianceEstimationPass->execute(renderContext); renderContext->popGraphicsVars(); renderContext->popGraphicsState(); } void SVGFPass::AtrousFilter(RenderContext* renderContext, uint32_t iteration, Fbo::SharedPtr input, Fbo::SharedPtr output) { GPU_EVENT(renderContext, "AtrousFilter"); mAtrousVars->setTexture("gCompactNormDepth", mGBufferInput.compactNormalDepth); mAtrousVars->setTexture("gInputSignal", input->getColorTexture(0)); mAtrousVars["PerPassCB"]["gStepSize"] = 1u << iteration; mAtrousVars["PerPassCB"]["gPhiColor"] = mPhiColor; mAtrousVars["PerPassCB"]["gPhiNormal"] = mPhiNormal; mAtrousState->setFbo(output); renderContext->pushGraphicsState(mAtrousState); renderContext->pushGraphicsVars(mAtrousVars); mAtrousPass->execute(renderContext); renderContext->popGraphicsVars(); renderContext->popGraphicsState(); } void SVGFPass::RenderGui(Gui* gui, const char* group) { if (gui->beginGroup(group)) { gui->addCheckBox("Temporal Reprojection", mEnableTemporalReprojection); gui->addCheckBox("Spatial Variance Estimation", mEnableSpatialVarianceEstimation); gui->addFloatSlider("Color Alpha", mAlpha, 0.0f, 1.0f); gui->addFloatSlider("Moments Alpha", mMomentsAlpha, 0.0f, 1.0f); gui->addFloatSlider("Phi Color", mPhiColor, 0.0f, 64.0f); gui->addFloatSlider("Phi Normal", mPhiNormal, 1.0f, 256.0f); gui->addIntSlider("Atrous Iterations", *reinterpret_cast<int32_t*>(&mAtrousIterations), 1, 5); gui->addIntSlider("Feedback Tap", *reinterpret_cast<int32_t*>(&mFeedbackTap), 1, 5); if (gui->addIntSlider("Atrous Radius", *reinterpret_cast<int32_t*>(&mAtrousRadius), 1, 2)) { mAtrousPass->getProgram()->addDefine("ATROUS_RADIUS", std::to_string(mAtrousRadius)); } gui->endGroup(); } }
41.81768
172
0.742767
guoxx
420584dddf7ea9ffe6fa2caa0c549145b39c5be7
1,011
hpp
C++
Engine/Code/Engine/Renderer/SpriteAnimDefinition.hpp
sam830917/TenNenDemon
a5f60007b73cccc6af8675c7f3dec597008dfdb4
[ "MIT" ]
null
null
null
Engine/Code/Engine/Renderer/SpriteAnimDefinition.hpp
sam830917/TenNenDemon
a5f60007b73cccc6af8675c7f3dec597008dfdb4
[ "MIT" ]
null
null
null
Engine/Code/Engine/Renderer/SpriteAnimDefinition.hpp
sam830917/TenNenDemon
a5f60007b73cccc6af8675c7f3dec597008dfdb4
[ "MIT" ]
null
null
null
#pragma once #include "SpriteSheet.hpp" enum class SpriteAnimPlaybackType { ONCE, // for 5-frame anim, plays 0,1,2,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4... LOOP, // for 5-frame anim, plays 0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0... PINGPONG // for 5-frame anim, plays 0,1,2,3,4,3,2,1,0,1,2,3,4,3,2,1,0,1,2,3,4,3,2,1,0,1... }; class SpriteAnimDefinition { public: SpriteAnimDefinition( const SpriteSheet& sheet, int startSpriteIndex, int endSpriteIndex, float durationSeconds, SpriteAnimPlaybackType playbackType = SpriteAnimPlaybackType::LOOP ); SpriteAnimDefinition( const SpriteSheet& sheet, const std::vector<int>& spriteIndexs, float durationSeconds, SpriteAnimPlaybackType playbackType = SpriteAnimPlaybackType::LOOP ); const SpriteDefinition& GetSpriteDefAtTime( float seconds ) const; private: const SpriteSheet& m_spriteSheet; float m_durationSeconds = 1.f; SpriteAnimPlaybackType m_playbackType = SpriteAnimPlaybackType::LOOP; std::vector<int> m_spriteIndexes; };
37.444444
94
0.740851
sam830917
42075bf31ee80b30fb7175f179f7b56b5a476549
339
cpp
C++
src/xgdial.cpp
msperl/Period
da4b4364e8228852cc2b82639470dab0b3579055
[ "MIT" ]
1
2019-12-10T20:13:11.000Z
2019-12-10T20:13:11.000Z
src/xgdial.cpp
msperl/Period
da4b4364e8228852cc2b82639470dab0b3579055
[ "MIT" ]
null
null
null
src/xgdial.cpp
msperl/Period
da4b4364e8228852cc2b82639470dab0b3579055
[ "MIT" ]
null
null
null
/* * Program: Period98 * * File: xgdial.h * Purpose: Implementation-file for * ? * Author: Martin Sperl * Created: 1996 * Copyright: (c) 1996-1998, Martin Sperl */ #include "xgdial.h" Bool myDialogBox::OnClose(void) { int result=wxDialogBox::OnClose(); Show(FALSE); return result; }
16.95
43
0.587021
msperl
420b724ad3961986b054359d68284129eee05771
645
cpp
C++
test/linux/router/service.cpp
justinc1/IncludeOS
2ce07b04e7a35c8d96e773f041db32a4593ca3d0
[ "Apache-2.0" ]
null
null
null
test/linux/router/service.cpp
justinc1/IncludeOS
2ce07b04e7a35c8d96e773f041db32a4593ca3d0
[ "Apache-2.0" ]
null
null
null
test/linux/router/service.cpp
justinc1/IncludeOS
2ce07b04e7a35c8d96e773f041db32a4593ca3d0
[ "Apache-2.0" ]
null
null
null
#include <service> #include "async_device.hpp" static std::unique_ptr<Async_device> dev2; void Service::start() { extern void create_network_device(int N, const char* route, const char* ip); create_network_device(0, "10.0.0.0/24", "10.0.0.1"); // Get the first IP stack configured from config.json auto& inet = net::Super_stack::get<net::IP4>(0); inet.network_config({10,0,0,42}, {255,255,255,0}, {10,0,0,1}); dev2 = std::make_unique<Async_device> (1500); dev2->set_transmit( [] (net::Packet_ptr) { printf("Inside network dropping packet\n"); }); extern void register_plugin_nacl(); register_plugin_nacl(); }
28.043478
78
0.683721
justinc1
420c3c03afaad46519b0bd79063348d7c72dbb6a
10,468
cpp
C++
opcodes/dxil/dxil_compute.cpp
HansKristian-Work/DXIL2SPIRV
ea9ac33ae88c9efb0f864d473eb22c3c04d166a5
[ "MIT" ]
5
2019-11-07T13:14:56.000Z
2019-12-09T20:01:47.000Z
opcodes/dxil/dxil_compute.cpp
HansKristian-Work/DXIL2SPIRV
ea9ac33ae88c9efb0f864d473eb22c3c04d166a5
[ "MIT" ]
null
null
null
opcodes/dxil/dxil_compute.cpp
HansKristian-Work/DXIL2SPIRV
ea9ac33ae88c9efb0f864d473eb22c3c04d166a5
[ "MIT" ]
null
null
null
/* Copyright (c) 2019-2022 Hans-Kristian Arntzen for Valve Corporation * * SPDX-License-Identifier: MIT * * 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 "dxil_compute.hpp" #include "dxil_common.hpp" #include "opcodes/converter_impl.hpp" #include "spirv_module.hpp" namespace dxil_spv { bool emit_barrier_instruction(Converter::Impl &impl, const llvm::CallInst *instruction) { auto &builder = impl.builder(); uint32_t operation; if (!get_constant_operand(instruction, 1, &operation)) return false; // Match DXC SPIR-V output here. Operation *op = nullptr; switch (static_cast<DXIL::BarrierMode>(operation)) { case DXIL::BarrierMode::DeviceMemoryBarrierWithGroupSync: op = impl.allocate(spv::OpControlBarrier); op->add_id(builder.makeUintConstant(spv::ScopeWorkgroup)); op->add_id(builder.makeUintConstant(spv::ScopeDevice)); op->add_id( builder.makeUintConstant(spv::MemorySemanticsImageMemoryMask | spv::MemorySemanticsUniformMemoryMask | spv::MemorySemanticsAcquireReleaseMask)); break; case DXIL::BarrierMode::GroupMemoryBarrierWithGroupSync: op = impl.allocate(spv::OpControlBarrier); op->add_id(builder.makeUintConstant(spv::ScopeWorkgroup)); op->add_id(builder.makeUintConstant(spv::ScopeWorkgroup)); op->add_id( builder.makeUintConstant(spv::MemorySemanticsWorkgroupMemoryMask | spv::MemorySemanticsAcquireReleaseMask)); break; case DXIL::BarrierMode::AllMemoryBarrierWithGroupSync: op = impl.allocate(spv::OpControlBarrier); op->add_id(builder.makeUintConstant(spv::ScopeWorkgroup)); op->add_id(builder.makeUintConstant(spv::ScopeDevice)); op->add_id( builder.makeUintConstant(spv::MemorySemanticsWorkgroupMemoryMask | spv::MemorySemanticsImageMemoryMask | spv::MemorySemanticsUniformMemoryMask | spv::MemorySemanticsAcquireReleaseMask)); break; case DXIL::BarrierMode::DeviceMemoryBarrier: op = impl.allocate(spv::OpMemoryBarrier); op->add_id(builder.makeUintConstant(spv::ScopeDevice)); op->add_id( builder.makeUintConstant(spv::MemorySemanticsImageMemoryMask | spv::MemorySemanticsUniformMemoryMask | spv::MemorySemanticsAcquireReleaseMask)); break; case DXIL::BarrierMode::GroupMemoryBarrier: op = impl.allocate(spv::OpMemoryBarrier); op->add_id(builder.makeUintConstant(spv::ScopeWorkgroup)); op->add_id( builder.makeUintConstant(spv::MemorySemanticsWorkgroupMemoryMask | spv::MemorySemanticsAcquireReleaseMask)); break; case DXIL::BarrierMode::AllMemoryBarrier: op = impl.allocate(spv::OpMemoryBarrier); op->add_id(builder.makeUintConstant(spv::ScopeDevice)); op->add_id( builder.makeUintConstant(spv::MemorySemanticsWorkgroupMemoryMask | spv::MemorySemanticsImageMemoryMask | spv::MemorySemanticsUniformMemoryMask | spv::MemorySemanticsAcquireReleaseMask)); break; default: return false; } impl.add(op); return true; } static bool emit_thread_2d_quad_fixup_instruction(spv::BuiltIn builtin, Converter::Impl &impl, const llvm::CallInst *instruction, uint32_t component) { // We have to compute everything from scratch. Sigh ... <_> auto &builder = impl.builder(); spv::Id local_thread_id = impl.spirv_module.get_builtin_shader_input(spv::BuiltInLocalInvocationId); { auto *load_op = impl.allocate(spv::OpLoad, builder.makeVectorType(builder.makeUintType(32), 3)); load_op->add_id(local_thread_id); impl.add(load_op); local_thread_id = load_op->id; } spv::Id comp_ids[3] = {}; const bool require[3] = { true, component >= 1 || builtin == spv::BuiltInLocalInvocationIndex, builtin == spv::BuiltInLocalInvocationIndex }; for (unsigned i = 0; i < 3; i++) { if (require[i]) { auto *extract_op = impl.allocate(spv::OpCompositeExtract, builder.makeUintType(32)); extract_op->add_id(local_thread_id); extract_op->add_literal(i); impl.add(extract_op); comp_ids[i] = extract_op->id; } } if (require[1]) { // Y * 2 + ((X >> 1) & 1). auto *x_part = impl.allocate(spv::OpBitFieldUExtract, builder.makeUintType(32)); x_part->add_id(comp_ids[0]); x_part->add_id(builder.makeUintConstant(1)); x_part->add_id(builder.makeUintConstant(1)); impl.add(x_part); auto *y_part = impl.allocate(spv::OpIMul, builder.makeUintType(32)); y_part->add_id(comp_ids[1]); y_part->add_id(builder.makeUintConstant(2)); impl.add(y_part); auto *add_part = impl.allocate(spv::OpIAdd, builder.makeUintType(32)); add_part->add_id(x_part->id); add_part->add_id(y_part->id); impl.add(add_part); comp_ids[1] = add_part->id; } { // Reconstruct X. In a group of 4 threads, we should see [0, 1, 0, 1], but for different Ys. auto *and_op = impl.allocate(spv::OpBitwiseAnd, builder.makeUintType(32)); and_op->add_id(comp_ids[0]); and_op->add_id(builder.makeUintConstant(1)); impl.add(and_op); auto *shift_down = impl.allocate(spv::OpShiftRightLogical, builder.makeUintType(32)); shift_down->add_id(comp_ids[0]); shift_down->add_id(builder.makeUintConstant(2)); impl.add(shift_down); auto *shift_up = impl.allocate(spv::OpShiftLeftLogical, builder.makeUintType(32)); shift_up->add_id(shift_down->id); shift_up->add_id(builder.makeUintConstant(1)); impl.add(shift_up); auto *or_op = impl.allocate(spv::OpBitwiseOr, builder.makeUintType(32)); or_op->add_id(and_op->id); or_op->add_id(shift_up->id); impl.add(or_op); comp_ids[0] = or_op->id; } // Reconstruct the flattened index. if (builtin == spv::BuiltInLocalInvocationIndex) { auto *y_base_op = impl.allocate(spv::OpIMul, builder.makeUintType(32)); y_base_op->add_id(comp_ids[1]); y_base_op->add_id(builder.makeUintConstant(impl.execution_mode_meta.workgroup_threads[0] / 2)); impl.add(y_base_op); auto *z_base_op = impl.allocate(spv::OpIMul, builder.makeUintType(32)); z_base_op->add_id(comp_ids[2]); z_base_op->add_id(builder.makeUintConstant( impl.execution_mode_meta.workgroup_threads[0] * impl.execution_mode_meta.workgroup_threads[1])); impl.add(z_base_op); auto *add_op = impl.allocate(spv::OpIAdd, builder.makeUintType(32)); add_op->add_id(y_base_op->id); add_op->add_id(z_base_op->id); impl.add(add_op); auto *final_add_op = impl.allocate(spv::OpIAdd, instruction); final_add_op->add_id(add_op->id); final_add_op->add_id(comp_ids[0]); impl.add(final_add_op); } else if (builtin == spv::BuiltInLocalInvocationId) { impl.rewrite_value(instruction, comp_ids[component]); } else { spv::Id wg_id = impl.spirv_module.get_builtin_shader_input(spv::BuiltInWorkgroupId); auto *ptr_wg = impl.allocate(spv::OpAccessChain, builder.makePointer(spv::StorageClassInput, builder.makeUintType(32))); ptr_wg->add_id(wg_id); ptr_wg->add_id(builder.makeUintConstant(component)); impl.add(ptr_wg); auto *load_wg = impl.allocate(spv::OpLoad, builder.makeUintType(32)); load_wg->add_id(ptr_wg->id); impl.add(load_wg); auto *base_thread = impl.allocate(spv::OpIMul, builder.makeUintType(32)); base_thread->add_id(load_wg->id); if (component == 0) base_thread->add_id(builder.makeUintConstant(impl.execution_mode_meta.workgroup_threads[component] / 2)); else // if (component == 1) base_thread->add_id(builder.makeUintConstant(impl.execution_mode_meta.workgroup_threads[component] * 2)); impl.add(base_thread); auto *final_add = impl.allocate(spv::OpIAdd, instruction); final_add->add_id(base_thread->id); final_add->add_id(comp_ids[component]); impl.add(final_add); } return true; } bool emit_thread_id_load_instruction(spv::BuiltIn builtin, Converter::Impl &impl, const llvm::CallInst *instruction) { // This appears to always be constant, not unlike all other input loading instructions. // Any attempt to dynamically index forces alloca. uint32_t component = 0; if (builtin != spv::BuiltInLocalInvocationIndex && !get_constant_operand(instruction, 1, &component)) return false; // Querying Z component for ThreadId or ThreadIdInGroup doesn't change with 2D quad fixup, just use normal path. // Need to consider ThreadId.xy, ThreadIdInGroup.xy and FlattenedThreadIdInGroup. if (builtin != spv::BuiltInWorkgroupId && impl.execution_mode_meta.synthesize_2d_quad_dispatch && component <= 1) return emit_thread_2d_quad_fixup_instruction(builtin, impl, instruction, component); // Awkward NVIDIA workaround. If loading LocalInvocationId, check if we can return constant 0. // This is key to avoid some particular shader compiler bugs. if (builtin == spv::BuiltInLocalInvocationId) { if (component <= 2 && impl.execution_mode_meta.workgroup_threads[component] == 1) { spv::Id const_zero = impl.builder().makeUintConstant(0); impl.rewrite_value(instruction, const_zero); return true; } } spv::Id var_id = impl.spirv_module.get_builtin_shader_input(builtin); if (builtin != spv::BuiltInLocalInvocationIndex) { Operation *op = impl.allocate(spv::OpAccessChain, impl.builder().makePointer(spv::StorageClassInput, impl.get_type_id(instruction->getType()))); op->add_id(var_id); op->add_id(impl.get_id_for_value(instruction->getOperand(1))); impl.add(op); var_id = op->id; } Operation *op = impl.allocate(spv::OpLoad, instruction); op->add_id(var_id); impl.add(op); return true; } } // namespace dxil_spv
36.729825
116
0.734142
HansKristian-Work
4210c2aaf8f2187a480a4b39fb5310b42836d22a
772
hpp
C++
pal/src/include/pal/handleapi.hpp
Taritsyn/ChakraCore
b6042191545a823fcf9d53df2b09d160d5808f51
[ "MIT" ]
8,664
2016-01-13T17:33:19.000Z
2019-05-06T19:55:36.000Z
pal/src/include/pal/handleapi.hpp
Taritsyn/ChakraCore
b6042191545a823fcf9d53df2b09d160d5808f51
[ "MIT" ]
5,058
2016-01-13T17:57:02.000Z
2019-05-04T15:41:54.000Z
pal/src/include/pal/handleapi.hpp
Taritsyn/ChakraCore
b6042191545a823fcf9d53df2b09d160d5808f51
[ "MIT" ]
1,367
2016-01-13T17:54:57.000Z
2019-04-29T18:16:27.000Z
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // /*++ Module Name: handleapi.hpp Abstract: Declaration of the handle management APIs --*/ #ifndef _HANDLEAPI_HPP #define _HANDLEAPI_HPP #include "corunix.hpp" namespace CorUnix { PAL_ERROR InternalDuplicateHandle( CPalThread *pThread, HANDLE hSourceProcess, HANDLE hSource, HANDLE hTargetProcess, LPHANDLE phDuplicate, DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwOptions ); PAL_ERROR InternalCloseHandle( CPalThread *pThread, HANDLE hObject ); } #endif // _HANDLEAPI_HPP
15.44
102
0.65544
Taritsyn
4210f672c013214c16e1dc820db8b5711539fa04
1,288
hpp
C++
typed_python/PyPythonObjectOfTypeInstance.hpp
npang1/nativepython
df311a5614a9660c15a8183b2dc606ff3e4600df
[ "Apache-2.0" ]
null
null
null
typed_python/PyPythonObjectOfTypeInstance.hpp
npang1/nativepython
df311a5614a9660c15a8183b2dc606ff3e4600df
[ "Apache-2.0" ]
null
null
null
typed_python/PyPythonObjectOfTypeInstance.hpp
npang1/nativepython
df311a5614a9660c15a8183b2dc606ff3e4600df
[ "Apache-2.0" ]
null
null
null
#pragma once #include "PyInstance.hpp" class PyPythonObjectOfTypeInstance : public PyInstance { public: typedef PythonObjectOfType modeled_type; static void copyConstructFromPythonInstanceConcrete(PythonObjectOfType* eltType, instance_ptr tgt, PyObject* pyRepresentation, bool isExplicit) { int isinst = PyObject_IsInstance(pyRepresentation, (PyObject*)eltType->pyType()); if (isinst == -1) { isinst = 0; PyErr_Clear(); } if (!isinst) { throw std::logic_error("Object of type " + std::string(pyRepresentation->ob_type->tp_name) + " is not an instance of " + ((PythonObjectOfType*)eltType)->pyType()->tp_name); } Py_INCREF(pyRepresentation); ((PyObject**)tgt)[0] = pyRepresentation; return; } static bool pyValCouldBeOfTypeConcrete(modeled_type* type, PyObject* pyRepresentation) { int isinst = PyObject_IsInstance(pyRepresentation, (PyObject*)type->pyType()); if (isinst == -1) { isinst = 0; PyErr_Clear(); } return isinst > 0; } static PyObject* extractPythonObjectConcrete(PythonObjectOfType* valueType, instance_ptr data) { return incref(*(PyObject**)data); } };
30.666667
149
0.63587
npang1
4216d37a7ec815a46ba620348eafdf13133dc2ef
2,103
cpp
C++
codes/HDU/hdu5402.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/HDU/hdu5402.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/HDU/hdu5402.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 105; const int dir[2][4][2] = { {{0, -1}, {-1, 0}, {1, 0}, {0, 1}}, {{-1, 0}, {0, 1}, {0, -1}, {1, 0}} }; const char sig[2][5] = {"LUDR", "URLD"}; int N, M, A[maxn][maxn], V[maxn][maxn]; char str[maxn * maxn]; int build (const int d[4][2], const char* t) { int x = 1, y = 1, n = 0; V[1][1] = 1; while (true) { bool flag = true; for (int i = 0; i < 4 && flag; i++) { int p = x + d[i][0]; int q = y + d[i][1]; if (p <= 0 || p > N || q <= 0 || q > M || V[p][q]) continue; str[n++] = t[i]; V[p][q] = 1; x = p, y = q, flag = false; } if (flag) break; } str[n] = '\0'; if (x == N && y == M) return n; return 0; } void build2 (const int d[4][2], const char* t, int& x, int &y, int& n, int l, int r) { V[x][y] = 1; while (true) { // printf("%d %d\n", x, y); bool flag = true; for (int i = 0; i < 4 && flag; i++) { int p = x + d[i][0]; int q = y + d[i][1]; if (p <= 0 || p > N || q <= l || q > r || V[p][q]) continue; str[n++] = t[i]; V[p][q] = 1; x = p, y = q, flag = false; } if (flag) break;; } // printf("end:%d %d\n", x, y); } int main () { while (scanf("%d%d", &N, &M) == 2) { memset(V, 0, sizeof(V)); int k = 1e4 + 5, rx, ry, s = 0; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { scanf("%d", &A[i][j]); s += A[i][j]; if (A[i][j] < k && ((i+j)&1)) { k = A[i][j]; rx = i, ry = j; } } } int end = N * M - 1; if ((N&1) == 0 && (M&1) == 0) { s -= k; int x = 1, y = 1, n = 0; memset(V, 0, sizeof(V)); V[rx][ry] = 1; for (int i = 1; i <= M; i += 2) { if (i == ry || i + 1 == ry) build2(dir[1], sig[1], x, y, n, y - 1, y + 1); else build2(dir[0], sig[0], x, y, n, y - 1, y + 1); y++; str[n++] = 'R'; } str[n-1] = '\0'; } else { memset(V, 0, sizeof(V)); int n = build(dir[0], sig[0]); if (n != end) { memset(V, 0, sizeof(V)); int n = build(dir[1], sig[1]); } } printf("%d\n%s\n", s, str); } return 0; }
21.03
100
0.406087
JeraKrs
421c63e7851ba31fb469dacf5023e6b3a74f3ca8
3,790
cpp
C++
RegionGrowingColor/prova.cpp
OttoBismark/DigitalImageProcessing
83ecbe64efe8acb6ce6aea020125b2eba2569f30
[ "MIT" ]
null
null
null
RegionGrowingColor/prova.cpp
OttoBismark/DigitalImageProcessing
83ecbe64efe8acb6ce6aea020125b2eba2569f30
[ "MIT" ]
null
null
null
RegionGrowingColor/prova.cpp
OttoBismark/DigitalImageProcessing
83ecbe64efe8acb6ce6aea020125b2eba2569f30
[ "MIT" ]
null
null
null
/* Region Growing a colori */ #include <cstdlib> #include <opencv/cv.h> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/video/video.hpp> #include <iostream> #include <stdio.h> #include <opencv2/core/core.hpp> #include <math.h> #include <unistd.h> #include <vector> #include <iterator> using namespace std; using namespace cv; void regionGrowingColorIterative(Mat img, vector<Point> vecPoint, Vec3b pixel, int T, Mat mask, Mat toModify) { while(!vecPoint.empty()) { Point P = vecPoint.back(); int x = P.x; int y = P.y; vecPoint.pop_back(); for(int i=-1; i<=1; i++) { for(int j=-1; j<=1; j++) { if((x+i>=0) && (x+i<img.rows)) { if((y+j>=0) && (y+j<img.cols)) { int dist = sqrt(pow(pixel.val[0]-img.at<Vec3b>(x+i,y+j).val[0],2)+ pow(pixel.val[1]-img.at<Vec3b>(x+i,y+j).val[1],2)+ pow(pixel.val[2]-img.at<Vec3b>(x+i,y+j).val[2],2)); if(dist < T && mask.at<uchar>(x+i,y+j)==0) { mask.at<uchar>(x+i,y+j) = 1; toModify.at<Vec3b>(x+i,y+j) = pixel; vecPoint.push_back(Point(x+i,y+j)); } } } } } } } void regionGrowingColor(Mat img,int x, int y, Vec3b pixel, int T, Mat mask, Mat toModify) { for(int i=-1; i<=1; i++) { for(int j=-1; j<=1; j++) { if((x+i>=0) && (x+i<img.rows)) { if((y+j>=0) && (y+j<img.cols)) { int dist = sqrt(pow(pixel.val[0]-img.at<Vec3b>(x+i,y+j).val[0],2)+ pow(pixel.val[1]-img.at<Vec3b>(x+i,y+j).val[1],2)+ pow(pixel.val[2]-img.at<Vec3b>(x+i,y+j).val[2],2)); if(dist < T && mask.at<uchar>(x+i,y+j)==0) { mask.at<uchar>(x+i,y+j) = 1; toModify.at<Vec3b>(x+i,y+j) = pixel; regionGrowingColor(img,x+i,y+j,pixel,T,mask,toModify); } } } } } } int main(int argc, char **argv) { if(argv[1] == nullptr && argv[2] == nullptr) { cerr << "Inserire due argomenti da passare al main" << endl; exit(-1); } Mat image = imread(argv[1], 1); Mat outputImage = Mat::zeros(image.size(),image.type()); Mat mask = Mat::zeros(image.size(),image.type()); int xPixel,yPixel,range=10; Vec3b pixel; vector<Point> vecPoint; if(!image.data) { cout << "Impossibile leggere l'immagine!\n" << endl; exit(0); } for(int i=0; i<atoi(argv[2]); i++) { xPixel = rand()%image.rows; yPixel = rand()%image.cols; if(mask.at<uchar>(xPixel,yPixel) == 0) { mask.at<uchar>(xPixel,yPixel) = 1; outputImage.at<Vec3b>(xPixel,yPixel) = image.at<Vec3b>(xPixel,yPixel); pixel = image.at<Vec3b>(xPixel,yPixel); vecPoint.clear(); vecPoint.push_back(Point(xPixel,yPixel)); //regionGrowingColor(image,xPixel,yPixel,pixel,range,mask,outputImage); regionGrowingColorIterative(image,vecPoint,pixel,range,mask,outputImage); } else { i--; } } namedWindow("Original",0); imshow("Original",image); namedWindow("RegionGrowing",0); imshow("RegionGrowing",outputImage); waitKey(); return 0; }
28.712121
109
0.466755
OttoBismark
421ec7da40ccd4ce7e985263c3617f6c3beafa54
1,670
hpp
C++
lib/models/customer.hpp
lacriment/Hayyam
488f274944df61562e19b02145a6fdbcf7dc88b1
[ "MIT" ]
2
2016-05-03T07:38:34.000Z
2020-12-13T22:31:32.000Z
lib/models/customer.hpp
lacriment/Hayyam
488f274944df61562e19b02145a6fdbcf7dc88b1
[ "MIT" ]
null
null
null
lib/models/customer.hpp
lacriment/Hayyam
488f274944df61562e19b02145a6fdbcf7dc88b1
[ "MIT" ]
null
null
null
#ifndef CUSTOMER_HPP #define CUSTOMER_HPP #include <QObject> #include <QString> #include "city.hpp" class Customer : public QObject { Q_OBJECT private: int m_Id; QString m_tc; QString m_name; QString m_surname; QString m_phone; City *m_city; QString m_address; public: explicit Customer(QObject *parent = 0); Q_PROPERTY(int id READ getId WRITE setId NOTIFY idChanged) Q_PROPERTY(QString tc READ getTc WRITE setTc NOTIFY tcChanged) Q_PROPERTY(QString name READ getName WRITE setName NOTIFY nameChanged) Q_PROPERTY(QString surname READ getSurname WRITE setSurname NOTIFY surnameChanged) Q_PROPERTY(QString phone READ getPhone WRITE setPhone NOTIFY phoneChanged) Q_PROPERTY(City* city READ getCity WRITE setCity NOTIFY cityChanged) Q_PROPERTY(QString address READ getAddress WRITE setAddress NOTIFY addressChanged) int getId() const; QString getTc() const; QString getName() const; QString getSurname() const; QString getPhone() const; City *getCity() const; QString getAddress() const; signals: void idChanged(int newId); void tcChanged(QString newTc); void nameChanged(QString newName); void surnameChanged(QString newSurname); void phoneChanged(QString newPhone); void cityChanged(City *newCity); void addressChanged(QString newAddress); public slots: void setId(int value); void setTc(const QString &value); void setName(const QString &value); void setSurname(const QString &value); void setPhone(const QString &value); void setCity(City *city); void setAddress(const QString &value); }; #endif // CUSTOMER_HPP
27.377049
86
0.731138
lacriment
422465eb7bab342d3f42586d18b9683dfdefef45
1,706
cpp
C++
src/providers/mpi/connection.cpp
PeterJGeorg/pmr
e3022da0027313f947b0778188fad1a863fd7dbf
[ "Apache-2.0" ]
6
2017-01-31T10:39:36.000Z
2020-08-15T12:40:21.000Z
src/providers/mpi/connection.cpp
pjgeorg/pMR
e3022da0027313f947b0778188fad1a863fd7dbf
[ "Apache-2.0" ]
null
null
null
src/providers/mpi/connection.cpp
pjgeorg/pMR
e3022da0027313f947b0778188fad1a863fd7dbf
[ "Apache-2.0" ]
null
null
null
// Copyright 2016 Peter Georg // // 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 "connection.hpp" #include "../../backends/backend.hpp" #include "../../backends/mpi/target.hpp" #include "../../backends/mpi/threadsupport.hpp" pMR::MPI::Connection::Connection(Target const &target) : mCommunicator{target.getMPICommunicator()} , mTargetRank{target.getTargetRank()} , mThreadLevel{Backend::ThreadSupport().getLevel()} { mSendTag = {static_cast<int>(reinterpret_cast<std::intptr_t>(this) % #ifdef MPI_TAG_NARROW std::numeric_limits<std::uint16_t>::max())}; #else std::numeric_limits<int>::max())}; #endif // MPI_TAG_NARROW // Exchange a (hopefully) unique message tag with remote Backend::exchange(target, mSendTag, mRecvTag); } MPI_Comm pMR::MPI::Connection::getCommunicator() const { return {mCommunicator}; } int pMR::MPI::Connection::getTargetRank() const { return {mTargetRank}; } int pMR::MPI::Connection::getSendTag() const { return {mSendTag}; } int pMR::MPI::Connection::getRecvTag() const { return {mRecvTag}; } enum pMR::ThreadLevel pMR::MPI::Connection::getThreadLevel() const { return {mThreadLevel}; }
28.433333
76
0.708675
PeterJGeorg
4228967ffd0e8e7f8735a54c212d0a7bffced7e9
64
cpp
C++
3DEngine/Physics/OBB.cpp
EricDDK/3DEngineEEE
cf7832e69ba03111d54093b1f797eaabab3455e1
[ "MIT" ]
5
2019-07-23T03:21:04.000Z
2020-08-28T09:09:08.000Z
3DEngine/Physics/OBB.cpp
EricDDK/3DEngineEEE
cf7832e69ba03111d54093b1f797eaabab3455e1
[ "MIT" ]
null
null
null
3DEngine/Physics/OBB.cpp
EricDDK/3DEngineEEE
cf7832e69ba03111d54093b1f797eaabab3455e1
[ "MIT" ]
3
2019-07-25T01:36:02.000Z
2020-02-15T08:11:19.000Z
#include "OBB.h" ENGINE_NAMESPACE_START ENGINE_NAMESPACE_END
9.142857
22
0.828125
EricDDK
422d7cfc53b6ef303711742d998a759c59689269
2,935
cpp
C++
src/Canvas/NumberPadCanvas.cpp
RobinSinghNanda/Home-assistant-display
6f59104012c0956b54d4b55e190aa89941c2c1af
[ "MIT" ]
2
2020-10-23T19:53:56.000Z
2020-11-06T08:59:48.000Z
src/Canvas/NumberPadCanvas.cpp
RobinSinghNanda/Home-assistant-display
6f59104012c0956b54d4b55e190aa89941c2c1af
[ "MIT" ]
null
null
null
src/Canvas/NumberPadCanvas.cpp
RobinSinghNanda/Home-assistant-display
6f59104012c0956b54d4b55e190aa89941c2c1af
[ "MIT" ]
null
null
null
#include "NumberPadCanvas.hpp" NumberPadCanvas::NumberPadCanvas(Canvas * canvas, uint16_t id) : Canvas(canvas, id) { for (uint8_t i=0;i<12;i++) { char text[10]; snprintf(text, sizeof(text), "%d", i+1); numberButtonsCanvas[i] = new TextCanvas(this, i); numberButtonsCanvas[i]->setText(text); numberButtonsCanvas[i]->onTouch([i, this](Canvas* canvas, TouchEvent event, TouchEventData)->bool{ if (isEventLosely(event, TouchEvent::TouchActionPressed)) { if ((i < 9 && !this->isNumbersDisabled()) || (i == 9 && !this->isLeftButtonDisabled()) || (i == 11 && !this->isRightButtonDisabled()) || (i == 10 && !this->isNumbersDisabled())) { canvas->setBgColor(this->pressedColor); } } else if (isEventLosely(event, TouchEvent::TouchActionTapped)) { canvas->setBgColor(this->bgColor); if (i<9) { if (this->isNumbersDisabled()) { return false; } return pressCallback(this, i+1); } else if (i == 9) { if (this->isLeftButtonDisabled()) { return false; } return pressCallback(this, 10); } else if (i == 10) { if (this->isNumbersDisabled()) { return false; } return pressCallback(this, 0); } else { if (this->isRightButtonDisabled()) { return false; } return pressCallback(this, 11); } } else { canvas->setBgColor(this->bgColor); return false; } return false; }); } numberButtonsCanvas[9]->setText(""); numberButtonsCanvas[10]->setText("0"); numberButtonsCanvas[11]->setText(""); pressCallback = [](NumberPadCanvas*, uint8_t)->bool{return false;}; } void NumberPadCanvas::resetLayout() { uint16_t size = (this->width/3>this->height/4)?this->height/4:this->width/3; uint16_t xOffset = getButtonX(); uint16_t yOffset = getButtonY(); for (uint8_t i=0;i<12;i++) { numberButtonsCanvas[i]->setWidth(size); numberButtonsCanvas[i]->setHeight(size); numberButtonsCanvas[i]->setHAlign(ALIGN_CENTER); numberButtonsCanvas[i]->setVAlign(ALIGN_MIDDLE); uint8_t gridX = ((i)%3)*size; uint8_t gridY = ((i)/3)*size; numberButtonsCanvas[i]->setX(xOffset + gridX); numberButtonsCanvas[i]->setY(yOffset + gridY); } }
43.80597
106
0.479727
RobinSinghNanda
422f0cadcc4cba747dcf7969fa31b9c9316afcd1
2,286
cpp
C++
monad_test.cpp
XzoRit/cpp_monad
9777f14d38c0df62cdaecfb286ae4d2f52777927
[ "BSL-1.0" ]
null
null
null
monad_test.cpp
XzoRit/cpp_monad
9777f14d38c0df62cdaecfb286ae4d2f52777927
[ "BSL-1.0" ]
null
null
null
monad_test.cpp
XzoRit/cpp_monad
9777f14d38c0df62cdaecfb286ae4d2f52777927
[ "BSL-1.0" ]
null
null
null
#include "monad.hpp" #include <boost/test/unit_test.hpp> #include <cctype> #include <iostream> #include <variant> namespace std { ostream& boost_test_print_type(ostream& ostr, monostate const& right) { ostr << "monostate"; return ostr; } } struct init { init() { BOOST_TEST_MESSAGE("init"); } ~init() { BOOST_TEST_MESSAGE("~init"); } }; using namespace std; string str_toupper(string a) { transform( a.begin(), a.end(), a.begin(), [](unsigned char c) { return toupper(c); }); return a; } BOOST_AUTO_TEST_SUITE(monad) BOOST_FIXTURE_TEST_CASE(monad_lazy_value, init) { using namespace monad; const auto a = lazy_value{ []() { return 2374; } }; BOOST_TEST(a() == 2374); BOOST_TEST(a() == 2374); } BOOST_FIXTURE_TEST_CASE(monad_io_monostate, init) { const auto a = monad::io::make_action([]() { return monostate{}; }); BOOST_TEST(a() == monostate{}); } BOOST_FIXTURE_TEST_CASE(monad_io_bind, init) { const auto a = monad::io::make_action([]() { return 1; }) .bind([](const auto& a) { return monad::io::make_action([a]() { return a + 2; }); }) .bind([](const auto& a) { return monad::io::make_action([a]() { return a + 3; }); }); BOOST_TEST(a() == 6); const auto b = monad::io::make_action([]() { return string{ "1" }; }) | [](const auto& a) { return monad::io::make_action([a]() { return a + "2"; }); } | [](const auto& a) { return monad::io::make_action([a]() { return a + "3"; }); }; BOOST_TEST(b() == "123"); } BOOST_FIXTURE_TEST_CASE(monad_io_fmap, init) { const auto a = monad::io::make_action([]() { return string{ "a" }; }) .fmap([](const auto& a) { return a + "b"; }) .fmap([](const auto& a) { return a + "c"; }) .fmap(str_toupper); BOOST_TEST(a() == "ABC"); const auto b = monad::io::make_action([]() { return string{ "a" }; }) > [](const auto& a) { return a + "b"; } > [](const auto& a) { return a + "c"; } > str_toupper; BOOST_TEST(b() == "ABC"); } BOOST_FIXTURE_TEST_CASE(monad_io_pure, init) { const auto a = monad::io::pure(string{ "abc" }); BOOST_TEST(a() == "abc"); } BOOST_AUTO_TEST_SUITE_END()
23.326531
96
0.561242
XzoRit
4231df6f009026d47fff53a263e67666fce71ee6
3,125
cpp
C++
lang/codeGen/types/CodeGenArrayComplexType.cpp
zippy1978/stark
62607d606fc5fe1addea4bd433b4d8dba9d4f3b1
[ "MIT" ]
null
null
null
lang/codeGen/types/CodeGenArrayComplexType.cpp
zippy1978/stark
62607d606fc5fe1addea4bd433b4d8dba9d4f3b1
[ "MIT" ]
null
null
null
lang/codeGen/types/CodeGenArrayComplexType.cpp
zippy1978/stark
62607d606fc5fe1addea4bd433b4d8dba9d4f3b1
[ "MIT" ]
null
null
null
#include <vector> #include <llvm/IR/Constant.h> #include <llvm/IR/IRBuilder.h> #include "../CodeGenFileContext.h" #include "CodeGenComplexType.h" using namespace llvm; using namespace std; namespace stark { CodeGenArrayComplexType::CodeGenArrayComplexType(std::string typeName, CodeGenFileContext *context) : CodeGenComplexType(formatv("array.{0}", typeName), context, true) { Type *t = context->getType(typeName); addMember("elements", typeName, t->getPointerTo()); addMember("len", "int", context->getPrimaryType("int")->getType()); } void CodeGenArrayComplexType::defineConstructor() { // Array constructor is not supported } Value *CodeGenArrayComplexType::createDefaultValue() { std::vector<Value *> values; return create(values); } Value *CodeGenArrayComplexType::create(std::vector<Value *> values) { // Get array element type Type *elementType = this->members[0]->type->getPointerElementType(); IRBuilder<> Builder(context->getLlvmContext()); Builder.SetInsertPoint(context->getCurrentBlock()); // Alloc inner array // If element type is a complex type : it is a pointer Type *innerArrayType = ArrayType::get(elementType, values.size()); Value* innerArrayAllocSize = ConstantExpr::getSizeOf(innerArrayType); Value *innerArrayAlloc = context->createMemoryAllocation(innerArrayType, innerArrayAllocSize, context->getCurrentBlock()); // Initialize inner array with elements // TODO : there is probably a way to write the whole content in a single instruction !!! long index = 0; for (auto it = values.begin(); it != values.end(); it++) { std::vector<llvm::Value *> indices; indices.push_back(ConstantInt::get(context->getLlvmContext(), APInt(32, 0, true))); indices.push_back(ConstantInt::get(context->getLlvmContext(), APInt(32, index, true))); Value *elementVarValue = Builder.CreateInBoundsGEP(innerArrayAlloc, indices, "elementptr"); Builder.CreateStore(*it, elementVarValue); index++; } // Create array Type *arrayType = context->getArrayComplexType(context->getTypeName(elementType))->getType(); Constant* arrayAllocSize = ConstantExpr::getSizeOf(arrayType); Value *arrayAlloc = context->createMemoryAllocation(arrayType, arrayAllocSize, context->getCurrentBlock()); // Set len member Value *lenMember = Builder.CreateStructGEP(arrayAlloc, 1, "arrayleninit"); Builder.CreateStore(ConstantInt::get(context->getPrimaryType("int")->getType(), values.size(), true), lenMember); // Set elements member with inner array Value *elementsMemberPointer = Builder.CreateStructGEP(arrayAlloc, 0, "arrayeleminit"); Builder.CreateStore(new BitCastInst(innerArrayAlloc, elementType->getPointerTo(), "", context->getCurrentBlock()), elementsMemberPointer); // Return new instance return arrayAlloc; } } // namespace stark
40.584416
171
0.67104
zippy1978
423537413507863635dc62c08b62af1a6dd04a29
1,219
cpp
C++
test/cpp/misc_tests/url-1.cpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
5
2015-09-15T16:24:14.000Z
2021-08-12T11:05:55.000Z
test/cpp/misc_tests/url-1.cpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
null
null
null
test/cpp/misc_tests/url-1.cpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
3
2016-11-17T04:38:38.000Z
2021-04-10T17:23:52.000Z
// // Copyright (c) 2008 João Abecasis // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <saga/saga.hpp> #include <iostream> int main() { saga::url u1("http://example.com"), u2 = u1, u3; std::cout << "u1: " << u1 << std::endl; std::cout << "u2: " << u2 << std::endl; std::cout << "u3: " << u3 << std::endl; std::cout << "Resetting u2." << std::endl; u2 = "condor://localhost"; std::cout << "u1: " << u1 << std::endl; std::cout << "u2: " << u2 << std::endl; std::cout << "u3: " << u3 << std::endl; std::cout << "u1.get_host(): " << u1.get_host() << std::endl; std::cout << "u2.get_host(): " << u2.get_host() << std::endl; std::cout << "u3.get_host(): " << u3.get_host() << std::endl; std::cout << "Resetting all hosts to localhost." << std::endl; u1.set_host("localhost"); u2.set_host("localhost"); u3.set_host("localhost"); std::cout << "u1.get_host(): " << u1.get_host() << std::endl; std::cout << "u2.get_host(): " << u2.get_host() << std::endl; std::cout << "u3.get_host(): " << u3.get_host() << std::endl; }
29.731707
80
0.546349
saga-project
4237709d2596784d4f7ba3af9705c389b7d0c391
1,375
cpp
C++
src/ui/main.cpp
mario-martinez-proyecto1/arbol-b
832371749cfa192f3b32873b0a55e99936f5ab6a
[ "MIT" ]
null
null
null
src/ui/main.cpp
mario-martinez-proyecto1/arbol-b
832371749cfa192f3b32873b0a55e99936f5ab6a
[ "MIT" ]
null
null
null
src/ui/main.cpp
mario-martinez-proyecto1/arbol-b
832371749cfa192f3b32873b0a55e99936f5ab6a
[ "MIT" ]
null
null
null
#include <iostream> #include "../tl/Gestor.h" #include "utilitario/Validar.h" Gestor gestor; Validar validar; using namespace std; void menu(); void procesarMenu(int &, bool &); int ingresarNum(string); int main() { menu(); return 0; } void menu() { bool salir; string valor; int opcion = 0; do { cout << "\nMenú Árbol\n\nElija una opción\n" << "01 Agregar elemento\n" << "02 Buscar elemento\n" << "03 Número primo menor que ...\n" << "04 Salir\n"; cin >> valor; opcion = validar.ingresarInt(valor); procesarMenu(opcion, salir); } while (!salir); } void procesarMenu(int & pOpcion, bool & salir) { switch (pOpcion) { case 1: // addValores(); break; case 2: // buscarValores(); break; case 3: // nPrimoMenorQue(); break; case 4: salir = true; break; default: cout << "Opción inválida\n"; } } int ingresarNum(string msg){ int num; string valor; do { cout << msg << endl; cin >> valor; num = validar.ingresarInt(valor); if (num == -1){ cout << "El valor ingresado es incorrecto\nVuelva a intentarlo\n"; } } while (num == -1); return num; }
22.540984
78
0.506182
mario-martinez-proyecto1
423b4bfc1e4fa564a57f5197c188b4c0856bd2ce
947
cpp
C++
SmallestGoodBase.cpp
yplusplus/LeetCode
122bd31b291af1e97ee4e9349a8e65bba6e04c96
[ "MIT" ]
3
2017-11-27T03:01:50.000Z
2021-03-13T08:14:00.000Z
SmallestGoodBase.cpp
yplusplus/LeetCode
122bd31b291af1e97ee4e9349a8e65bba6e04c96
[ "MIT" ]
null
null
null
SmallestGoodBase.cpp
yplusplus/LeetCode
122bd31b291af1e97ee4e9349a8e65bba6e04c96
[ "MIT" ]
null
null
null
// log * log * log class Solution { public: unsigned long long calc(int d, int k) {; unsigned long long x = 1; unsigned long long sum = 0; for (int i = 0; i < d; i++) { sum += x; x *= k; } return sum; } string smallestGoodBase(string n) { unsigned long long m = stoull(n); for (int d = 62; d >= 2; d--) { if ((1 << d) - 1 <= m) { int L = 2, R = pow(m, 1.0 / (d - 1)) + 1.0; while (L <= R) { int mid = (L + R) / 2; long long x = calc(d, mid); if (x == m) { return to_string(mid); } else if (x > m) { R = mid - 1; } else { L = mid + 1; } } } } return to_string(m - 1); } };
28.69697
59
0.317846
yplusplus
423e5287e968b03a7a40b8153df367c9f0f61624
2,306
cpp
C++
tests/hull/hullTest.cpp
Yattabyte/TestProject
21a1e047dd03f90087e2738c7d90545a067e8375
[ "BSD-3-Clause" ]
1
2020-03-02T21:56:42.000Z
2020-03-02T21:56:42.000Z
tests/hull/hullTest.cpp
Yattabyte/TestProject
21a1e047dd03f90087e2738c7d90545a067e8375
[ "BSD-3-Clause" ]
null
null
null
tests/hull/hullTest.cpp
Yattabyte/TestProject
21a1e047dd03f90087e2738c7d90545a067e8375
[ "BSD-3-Clause" ]
null
null
null
#include "hull.hpp" #include <cassert> #include <iostream> #include <limits> #include <string> ////////////////////////////////////////////////////////////////////// /// Use the shared mini namespace using namespace mini; // Constant variables for this test constexpr auto scale(10.0F); constexpr auto pointCount(16384ULL); constexpr auto seed(1234567890U); void cloudTest(const std::vector<vec3>& pointCloud); void hullTest(const std::vector<vec3>& pointCloud); int main() { // Generate a point cloud given the above variables std::cout << "Generating point cloud given:\n" << "\t-scale: " << std::to_string(scale) << "\n" << "\t-count: " << std::to_string(pointCount) << "\n" << "\t-seed: " << std::to_string(seed) << std::endl; const auto pointCloud(Hull::generate_point_cloud(scale, pointCount, seed)); // Test the point cloud for accuracy cloudTest(pointCloud); // Test the convex hull for accuracy hullTest(pointCloud); exit(0); } void cloudTest(const std::vector<vec3>& pointCloud) { // Ensure number of points match assert(pointCloud.size() == pointCount); // Ensure scale is accurate vec3 max(std::numeric_limits<float>::min()); vec3 min(std::numeric_limits<float>::max()); for (const auto& point : pointCloud) { if (max.x() < point.x()) max.x() = point.x(); if (max.y() < point.y()) max.y() = point.y(); if (max.z() < point.z()) max.z() = point.z(); if (min.x() > point.x()) min.x() = point.x(); if (min.y() > point.y()) min.y() = point.y(); if (min.z() > point.z()) min.z() = point.z(); } [[maybe_unused]] const auto delta = max - min; assert(ceilf((delta.x() + delta.y() + delta.z()) / 6.0F) == ceilf(scale)); // Ensure deterministic point cloud assert( pointCloud[0].x() == 2.37589645F && pointCloud[0].y() == -3.18982124F && pointCloud[0].z() == 1.83247185F); } void hullTest(const std::vector<vec3>& pointCloud) { // Attempt to generate a convex hull [[maybe_unused]] const auto convexHull( Hull::generate_convex_hull(pointCloud)); // Ensure we have actually have a hull assert(!convexHull.empty()); }
31.589041
80
0.573287
Yattabyte
4244bf1064c76dbcfe7a5c0983dc66ab07321ab2
1,247
cc
C++
Codeforces/311 Division 2/Problem A/A.cc
VastoLorde95/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
170
2017-07-25T14:47:29.000Z
2022-01-26T19:16:31.000Z
Codeforces/311 Division 2/Problem A/A.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
null
null
null
Codeforces/311 Division 2/Problem A/A.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
55
2017-07-28T06:17:33.000Z
2021-10-31T03:06:22.000Z
#include<cstdio> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<map> #include<set> #include<vector> #include<utility> #include<queue> #include<stack> #define sd(x) scanf("%d",&x) #define sd2(x,y) scanf("%d%d",&x,&y) #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define fi first #define se second #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define LET(x, a) __typeof(a) x(a) #define foreach(it, v) for(LET(it, v.begin()); it != v.end(); it++) #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define __ freopen("input.txt", "r", stdin);freopen("output.txt", "w", stdout); #define tr(x) cout<<x<<endl; #define tr2(x,y) cout<<x<<" "<<y<<endl; #define tr3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl; #define tr4(w,x,y,z) cout<<w<<" "<<x<<" "<<y<<" "<<z<<endl; using namespace std; int n; int x1, x2, x3, x4, x5, x6; int main(){ cin >> n; sd2(x1,x2); sd2(x3,x4); sd2(x5,x6); int a = x1, b = x3, c = x5; n -= (x1+x3+x5); if(n >= x2-x1){ n -= x2-x1; a = x2; } else{ a += n; n = 0; } if(n >= x4-x3){ n -= x4-x3; b = x4; } else{ b += n; n = 0; } if(n >= x6-x5){ n -= x6-x5; c = x6; } else{ c += n; n = 0; } tr3(a,b,c); return 0; }
17.082192
79
0.55413
VastoLorde95
424a1938b3dfb575afc3d89a653c01ec8e2da0c7
748
cpp
C++
2265/9284084_AC_0MS_956K.cpp
vandreas19/POJ_sol
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
18
2017-08-14T07:34:42.000Z
2022-01-29T14:20:29.000Z
2265/9284084_AC_0MS_956K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
null
null
null
2265/9284084_AC_0MS_956K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
14
2016-12-21T23:37:22.000Z
2021-07-24T09:38:57.000Z
#define _CRT_SECURE_NO_WARNINGS #include<cstdio> const int ID_MAX=100000; int x[ID_MAX]={0},y[ID_MAX]={0}; int main(){ for(int id=0;id+1<ID_MAX;id++){ if(x[id]>=0 && x[id]+y[id]<0){ x[id+1]=x[id]+1; y[id+1]=y[id]; } else if(y[id]<=0 && x[id]+y[id]>=0){ x[id+1]=x[id]; y[id+1]=y[id]+1; } else if(x[id]>0 && y[id]>0){ x[id+1]=x[id]-1; y[id+1]=y[id]+1; } else if(x[id]<=0 && x[id]+y[id]>0){ x[id+1]=x[id]-1; y[id+1]=y[id]; } else if(y[id]>0 && x[id]+y[id]<=0){ x[id+1]=x[id]; y[id+1]=y[id]-1; } else if(x[id]<0 && y[id]<=0){ x[id+1]=x[id]+1; y[id+1]=y[id]-1; } } int id; while(scanf("%d",&id)!=EOF) printf("%d %d\n",x[id-1],y[id-1]); return 0; }
19.684211
39
0.450535
vandreas19
424b3a4833b296d05cea1a528f1ec30ad7101f12
1,241
cpp
C++
UVA/11462 - Age Sort.cpp
Mhmd-Hisham/Problem-Solving
7ce0955b697e735c5ccb37347d9bec83e57339b5
[ "MIT" ]
null
null
null
UVA/11462 - Age Sort.cpp
Mhmd-Hisham/Problem-Solving
7ce0955b697e735c5ccb37347d9bec83e57339b5
[ "MIT" ]
null
null
null
UVA/11462 - Age Sort.cpp
Mhmd-Hisham/Problem-Solving
7ce0955b697e735c5ccb37347d9bec83e57339b5
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> /* Problem: 11462 - Age Sort Link : https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2457 Solution by: Mohamed Hisham El-Banna Gmail : [email protected] Github : www.github.com/Mhmd-Hisham LinkedIn: www.linkedin.com/in/Mhmd-Hisham */ using namespace std; int N, age, age_freq[2000002]; set<int> ages; set<int> ::iterator it; int main () { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); while ( cin >> N && N ){ int left = N; // numbers left to print for (int i = 0; i < N; i++){ cin >> age; age_freq[age]++; ages.insert(age); } it = ages.begin(); while (it != ages.end()){ while (age_freq[*it]){ cout << *it; cout << ( (left == 1)? "" : " "); age_freq[*it]--; left--; } it++; } cout << '\n'; ages.clear(); } return 0; } /* Sample input:- ----------------- 5 3 4 2 1 5 5 2 3 2 3 1 0 Sample output:- ----------------- 1 2 3 4 5 1 2 2 3 3 Resources:- ------------- Explanation: --------------- */
17.478873
109
0.475423
Mhmd-Hisham
42521aa4b8951f72b588c6847e0e199be7d2a4bb
1,169
cc
C++
src/rocksdb2/util/concurrent_arena.cc
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
5
2019-01-23T04:36:03.000Z
2020-02-04T07:10:39.000Z
src/rocksdb2/util/concurrent_arena.cc
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
null
null
null
src/rocksdb2/util/concurrent_arena.cc
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
2
2019-05-14T07:26:59.000Z
2020-06-15T07:25:01.000Z
//此源码被清华学神尹成大魔王专业翻译分析并修改 //尹成QQ77025077 //尹成微信18510341407 //尹成所在QQ群721929980 //尹成邮箱 [email protected] //尹成毕业于清华大学,微软区块链领域全球最有价值专家 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 //版权所有(c)2011至今,Facebook,Inc.保留所有权利。 //此源代码在两个gplv2下都获得了许可(在 //复制根目录中的文件)和Apache2.0许可证 //(在根目录的license.apache文件中找到)。 // //版权所有(c)2011 LevelDB作者。版权所有。 //此源代码的使用受可以 //在许可证文件中找到。有关参与者的名称,请参阅作者文件。 #include "util/concurrent_arena.h" #include <thread> #include "port/port.h" #include "util/random.h" namespace rocksdb { #ifdef ROCKSDB_SUPPORT_THREAD_LOCAL __thread size_t ConcurrentArena::tls_cpuid = 0; #endif ConcurrentArena::ConcurrentArena(size_t block_size, AllocTracker* tracker, size_t huge_page_size) : shard_block_size_(block_size / 8), shards_(), arena_(block_size, tracker, huge_page_size) { Fixup(); } ConcurrentArena::Shard* ConcurrentArena::Repick() { auto shard_and_index = shards_.AccessElementAndIndex(); #ifdef ROCKSDB_SUPPORT_THREAD_LOCAL //即使我们是CPU 0,也要使用非零的tls_cpuid,这样我们就可以告诉我们 //重选 tls_cpuid = shard_and_index.second | shards_.Size(); #endif return shard_and_index.first; } } //命名空间rocksdb
24.354167
74
0.753636
yinchengtsinghua
425ad57f0ec487f910bb9d842de40c70bfe72c4e
9,890
cpp
C++
TRANSmission/Intermediate/Build/Win64/UE4Editor/Inc/TRANSmission/Vibrator.gen.cpp
daff0111/GGJ2018
2d14edb4f1ba6a281985c758961939294cdeda9a
[ "MIT" ]
null
null
null
TRANSmission/Intermediate/Build/Win64/UE4Editor/Inc/TRANSmission/Vibrator.gen.cpp
daff0111/GGJ2018
2d14edb4f1ba6a281985c758961939294cdeda9a
[ "MIT" ]
null
null
null
TRANSmission/Intermediate/Build/Win64/UE4Editor/Inc/TRANSmission/Vibrator.gen.cpp
daff0111/GGJ2018
2d14edb4f1ba6a281985c758961939294cdeda9a
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "GeneratedCppIncludes.h" #include "Vibrator.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeVibrator() {} // Cross Module References TRANSMISSION_API UEnum* Z_Construct_UEnum_TRANSmission_EController(); UPackage* Z_Construct_UPackage__Script_TRANSmission(); TRANSMISSION_API UEnum* Z_Construct_UEnum_TRANSmission_EMorseInput(); TRANSMISSION_API UClass* Z_Construct_UClass_AVibrator_NoRegister(); TRANSMISSION_API UClass* Z_Construct_UClass_AVibrator(); ENGINE_API UClass* Z_Construct_UClass_AActor(); ENGINE_API UClass* Z_Construct_UClass_UForceFeedbackEffect_NoRegister(); // End Cross Module References static UEnum* EController_StaticEnum() { static UEnum* Singleton = nullptr; if (!Singleton) { Singleton = GetStaticEnum(Z_Construct_UEnum_TRANSmission_EController, Z_Construct_UPackage__Script_TRANSmission(), TEXT("EController")); } return Singleton; } static FCompiledInDeferEnum Z_CompiledInDeferEnum_UEnum_EController(EController_StaticEnum, TEXT("/Script/TRANSmission"), TEXT("EController"), false, nullptr, nullptr); uint32 Get_Z_Construct_UEnum_TRANSmission_EController_CRC() { return 4001267138U; } UEnum* Z_Construct_UEnum_TRANSmission_EController() { #if WITH_HOT_RELOAD UPackage* Outer = Z_Construct_UPackage__Script_TRANSmission(); static UEnum* ReturnEnum = FindExistingEnumIfHotReloadOrDynamic(Outer, TEXT("EController"), 0, Get_Z_Construct_UEnum_TRANSmission_EController_CRC(), false); #else static UEnum* ReturnEnum = nullptr; #endif // WITH_HOT_RELOAD if (!ReturnEnum) { static const UE4CodeGen_Private::FEnumeratorParam Enumerators[] = { { "EController::Player1", (int64)EController::Player1 }, { "EController::Player2", (int64)EController::Player2 }, }; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Enum_MetaDataParams[] = { { "BlueprintType", "true" }, { "ModuleRelativePath", "Vibrator.h" }, }; #endif static const UE4CodeGen_Private::FEnumParams EnumParams = { (UObject*(*)())Z_Construct_UPackage__Script_TRANSmission, UE4CodeGen_Private::EDynamicType::NotDynamic, "EController", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (uint8)UEnum::ECppForm::EnumClass, "EController", Enumerators, ARRAY_COUNT(Enumerators), METADATA_PARAMS(Enum_MetaDataParams, ARRAY_COUNT(Enum_MetaDataParams)) }; UE4CodeGen_Private::ConstructUEnum(ReturnEnum, EnumParams); } return ReturnEnum; } static UEnum* EMorseInput_StaticEnum() { static UEnum* Singleton = nullptr; if (!Singleton) { Singleton = GetStaticEnum(Z_Construct_UEnum_TRANSmission_EMorseInput, Z_Construct_UPackage__Script_TRANSmission(), TEXT("EMorseInput")); } return Singleton; } static FCompiledInDeferEnum Z_CompiledInDeferEnum_UEnum_EMorseInput(EMorseInput_StaticEnum, TEXT("/Script/TRANSmission"), TEXT("EMorseInput"), false, nullptr, nullptr); uint32 Get_Z_Construct_UEnum_TRANSmission_EMorseInput_CRC() { return 797329059U; } UEnum* Z_Construct_UEnum_TRANSmission_EMorseInput() { #if WITH_HOT_RELOAD UPackage* Outer = Z_Construct_UPackage__Script_TRANSmission(); static UEnum* ReturnEnum = FindExistingEnumIfHotReloadOrDynamic(Outer, TEXT("EMorseInput"), 0, Get_Z_Construct_UEnum_TRANSmission_EMorseInput_CRC(), false); #else static UEnum* ReturnEnum = nullptr; #endif // WITH_HOT_RELOAD if (!ReturnEnum) { static const UE4CodeGen_Private::FEnumeratorParam Enumerators[] = { { "EMorseInput::A", (int64)EMorseInput::A }, { "EMorseInput::B", (int64)EMorseInput::B }, { "EMorseInput::X", (int64)EMorseInput::X }, { "EMorseInput::Y", (int64)EMorseInput::Y }, { "EMorseInput::S", (int64)EMorseInput::S }, { "EMorseInput::U", (int64)EMorseInput::U }, { "EMorseInput::C", (int64)EMorseInput::C }, }; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Enum_MetaDataParams[] = { { "BlueprintType", "true" }, { "ModuleRelativePath", "Vibrator.h" }, }; #endif static const UE4CodeGen_Private::FEnumParams EnumParams = { (UObject*(*)())Z_Construct_UPackage__Script_TRANSmission, UE4CodeGen_Private::EDynamicType::NotDynamic, "EMorseInput", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (uint8)UEnum::ECppForm::EnumClass, "EMorseInput", Enumerators, ARRAY_COUNT(Enumerators), METADATA_PARAMS(Enum_MetaDataParams, ARRAY_COUNT(Enum_MetaDataParams)) }; UE4CodeGen_Private::ConstructUEnum(ReturnEnum, EnumParams); } return ReturnEnum; } void AVibrator::StaticRegisterNativesAVibrator() { } UClass* Z_Construct_UClass_AVibrator_NoRegister() { return AVibrator::StaticClass(); } UClass* Z_Construct_UClass_AVibrator() { static UClass* OuterClass = nullptr; if (!OuterClass) { static UObject* (*const DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_AActor, (UObject* (*)())Z_Construct_UPackage__Script_TRANSmission, }; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[] = { { "IncludePath", "Vibrator.h" }, { "ModuleRelativePath", "Vibrator.h" }, }; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_DashHapticFeedback_MetaData[] = { { "Category", "Vibrator" }, { "ModuleRelativePath", "Vibrator.h" }, }; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_DashHapticFeedback = { UE4CodeGen_Private::EPropertyClass::Object, "DashHapticFeedback", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000005, 1, nullptr, STRUCT_OFFSET(AVibrator, DashHapticFeedback), Z_Construct_UClass_UForceFeedbackEffect_NoRegister, METADATA_PARAMS(NewProp_DashHapticFeedback_MetaData, ARRAY_COUNT(NewProp_DashHapticFeedback_MetaData)) }; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_DotHapticFeedback_MetaData[] = { { "Category", "Vibrator" }, { "ModuleRelativePath", "Vibrator.h" }, }; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_DotHapticFeedback = { UE4CodeGen_Private::EPropertyClass::Object, "DotHapticFeedback", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000005, 1, nullptr, STRUCT_OFFSET(AVibrator, DotHapticFeedback), Z_Construct_UClass_UForceFeedbackEffect_NoRegister, METADATA_PARAMS(NewProp_DotHapticFeedback_MetaData, ARRAY_COUNT(NewProp_DotHapticFeedback_MetaData)) }; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_SignalToPlay_MetaData[] = { { "Category", "Vibrator" }, { "ModuleRelativePath", "Vibrator.h" }, }; #endif static const UE4CodeGen_Private::FEnumPropertyParams NewProp_SignalToPlay = { UE4CodeGen_Private::EPropertyClass::Enum, "SignalToPlay", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000005, 1, nullptr, STRUCT_OFFSET(AVibrator, SignalToPlay), Z_Construct_UEnum_TRANSmission_EMorseInput, METADATA_PARAMS(NewProp_SignalToPlay_MetaData, ARRAY_COUNT(NewProp_SignalToPlay_MetaData)) }; static const UE4CodeGen_Private::FBytePropertyParams NewProp_SignalToPlay_Underlying = { UE4CodeGen_Private::EPropertyClass::Byte, "UnderlyingType", RF_Public|RF_Transient|RF_MarkAsNative, 0x0000000000000000, 1, nullptr, 0, nullptr, METADATA_PARAMS(nullptr, 0) }; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_PlaySignal_MetaData[] = { { "Category", "Vibrator" }, { "ModuleRelativePath", "Vibrator.h" }, { "ToolTip", "Test" }, }; #endif auto NewProp_PlaySignal_SetBit = [](void* Obj){ ((AVibrator*)Obj)->PlaySignal = 1; }; static const UE4CodeGen_Private::FBoolPropertyParams NewProp_PlaySignal = { UE4CodeGen_Private::EPropertyClass::Bool, "PlaySignal", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000005, 1, nullptr, sizeof(bool), UE4CodeGen_Private::ENativeBool::Native, sizeof(AVibrator), &UE4CodeGen_Private::TBoolSetBitWrapper<decltype(NewProp_PlaySignal_SetBit)>::SetBit, METADATA_PARAMS(NewProp_PlaySignal_MetaData, ARRAY_COUNT(NewProp_PlaySignal_MetaData)) }; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_DashHapticFeedback, (const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_DotHapticFeedback, (const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_SignalToPlay, (const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_SignalToPlay_Underlying, (const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_PlaySignal, }; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo = { TCppClassTypeTraits<AVibrator>::IsAbstract, }; static const UE4CodeGen_Private::FClassParams ClassParams = { &AVibrator::StaticClass, DependentSingletons, ARRAY_COUNT(DependentSingletons), 0x00900080u, nullptr, 0, PropPointers, ARRAY_COUNT(PropPointers), nullptr, &StaticCppClassTypeInfo, nullptr, 0, METADATA_PARAMS(Class_MetaDataParams, ARRAY_COUNT(Class_MetaDataParams)) }; UE4CodeGen_Private::ConstructUClass(OuterClass, ClassParams); } return OuterClass; } IMPLEMENT_CLASS(AVibrator, 3214353239); static FCompiledInDefer Z_CompiledInDefer_UClass_AVibrator(Z_Construct_UClass_AVibrator, &AVibrator::StaticClass, TEXT("/Script/TRANSmission"), TEXT("AVibrator"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(AVibrator); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
47.548077
456
0.768959
daff0111
425c44c6ab3335b2a34784926aa7d93aff2771dd
189
cc
C++
lib/seadsa/Debug.cc
wenhuizhang/sea-dsa
098a945af596d29940421219741bea727778bfb5
[ "BSD-3-Clause" ]
2
2021-10-08T00:50:26.000Z
2021-12-17T07:18:15.000Z
lib/seadsa/Debug.cc
wenhuizhang/sea-dsa
098a945af596d29940421219741bea727778bfb5
[ "BSD-3-Clause" ]
1
2021-09-29T07:21:20.000Z
2021-09-29T07:21:20.000Z
lib/seadsa/Debug.cc
wenhuizhang/sea-dsa
098a945af596d29940421219741bea727778bfb5
[ "BSD-3-Clause" ]
1
2021-10-12T09:02:40.000Z
2021-10-12T09:02:40.000Z
#include <seadsa/support/Debug.h> std::set<std::string> seadsa::SeaDsaLog; void seadsa::SeaDsaEnableLog (std::string x) { if (x.empty()) return; seadsa::SeaDsaLog.insert (x); }
13.5
46
0.671958
wenhuizhang
4263fd30955386762c18b28f158d1a0ba1ab0767
647
cpp
C++
chapter_05/ComputeMean.cpp
Kevin-Oudai/my_cpp_solutions
a0f5f533ee4825f5b2d88cacc936d80276062ca4
[ "MIT" ]
null
null
null
chapter_05/ComputeMean.cpp
Kevin-Oudai/my_cpp_solutions
a0f5f533ee4825f5b2d88cacc936d80276062ca4
[ "MIT" ]
31
2021-05-14T03:37:24.000Z
2022-03-13T17:38:32.000Z
chapter_05/ComputeMean.cpp
Kevin-Oudai/my_cpp_solutions
a0f5f533ee4825f5b2d88cacc936d80276062ca4
[ "MIT" ]
null
null
null
// Exercise 5.47 - Statistics: Compute mean and standard deviation #include <iostream> #include <cmath> int main() { std::cout << "Enter ten numbers: "; int count = 0; double num, sum = 0.0, squareSum, sumSquare = 0, mean, deviation; while (count < 10) { std::cin >> num; sum += num; sumSquare += std::pow(num, 2); count++; } mean = sum / 10.0; squareSum = std::pow(sum, 2); deviation = std::sqrt((sumSquare - (squareSum / 10)) / 9); std::cout << "The mean is " << mean << std::endl; std::cout << "The standard deviation is " << deviation << std::endl; return 0; }
25.88
72
0.554869
Kevin-Oudai
426414a602d2273e98bb37e0867cc6d70faec56d
3,812
cpp
C++
Final_Project/gl_common_ext/SkyBox.cpp
Guarionex/HCI-557-CG
a84fdb3a1440992cc1cc973f4360f232f94d2025
[ "MIT" ]
null
null
null
Final_Project/gl_common_ext/SkyBox.cpp
Guarionex/HCI-557-CG
a84fdb3a1440992cc1cc973f4360f232f94d2025
[ "MIT" ]
null
null
null
Final_Project/gl_common_ext/SkyBox.cpp
Guarionex/HCI-557-CG
a84fdb3a1440992cc1cc973f4360f232f94d2025
[ "MIT" ]
null
null
null
#include "SkyBox.h" #include <iostream> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include "ShaderProgram.h" using namespace cs557; SkyBox::SkyBox(string left, string right, string up, string down, string front, string back, ShaderFiles skybox_shader_files) { vector<string> faces { left, right, up, down, front, back }; skyBox_program = LoadAndCreateShaderProgram(skybox_shader_files.vertex_shader, skybox_shader_files.fragment_shader); cubemapTexture = loadCubemap(faces); createCube(); } SkyBox::SkyBox() { } unsigned int SkyBox::loadCubemap(vector<std::string> faces) { unsigned int textureID; glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_CUBE_MAP, textureID); int width, height, nrChannels; for (unsigned int i = 0; i < faces.size(); i++) { unsigned char *data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data ); stbi_image_free(data); } else { std::cout << "Cubemap texture failed to load at path: " << faces[i] << std::endl; stbi_image_free(data); } } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); return textureID; } void SkyBox::createCube() { float skyboxVertices[] = { -100.0f, 100.0f, -100.0f, -100.0f, -100.0f, -100.0f, 100.0f, -100.0f, -100.0f, 100.0f, -100.0f, -100.0f, 100.0f, 100.0f, -100.0f, -100.0f, 100.0f, -100.0f, -100.0f, -100.0f, 100.0f, -100.0f, -100.0f, -100.0f, -100.0f, 100.0f, -100.0f, -100.0f, 100.0f, -100.0f, -100.0f, 100.0f, 100.0f, -100.0f, -100.0f, 100.0f, 100.0f, -100.0f, -100.0f, 100.0f, -100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, -100.0f, 100.0f, -100.0f, -100.0f, -100.0f, -100.0f, 100.0f, -100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, -100.0f, 100.0f, -100.0f, -100.0f, 100.0f, -100.0f, 100.0f, -100.0f, 100.0f, 100.0f, -100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, 100.0f, -100.0f, 100.0f, 100.0f, -100.0f, 100.0f, -100.0f, -100.0f, -100.0f, -100.0f, -100.0f, -100.0f, 100.0f, 100.0f, -100.0f, -100.0f, 100.0f, -100.0f, -100.0f, -100.0f, -100.0f, 100.0f, 100.0f, -100.0f, 100.0f }; glGenVertexArrays(1, &sky_VAO); glBindVertexArray(sky_VAO); glGenBuffers(1, &sky_VBO); glBindBuffer(GL_ARRAY_BUFFER, sky_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), skyboxVertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); skyBoxViewMatrixLocation = glGetUniformLocation(skyBox_program, "view"); skyBoxProjMatrixLocation = glGetUniformLocation(skyBox_program, "projection"); } void SkyBox::Draw(mat4 projectionMatrix, mat4 viewMatrix) { glDepthFunc(GL_LEQUAL); glUseProgram(skyBox_program); mat4 skyBoxView = mat4(mat3(viewMatrix)); glUniform1i(glGetUniformLocation(skyBox_program, "skybox"), 0); glUniformMatrix4fv(skyBoxViewMatrixLocation, 1, GL_FALSE, &skyBoxView[0][0]); glUniformMatrix4fv(skyBoxProjMatrixLocation, 1, GL_FALSE, &projectionMatrix[0][0]); glBindVertexArray(sky_VAO); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); glUseProgram(0); glDepthFunc(GL_LESS); } unsigned SkyBox::GetCubeMap() const { return cubemapTexture; }
26.289655
125
0.705666
Guarionex
42670b3adde45ea4712819604d9f4ffe20d97c8c
1,918
cpp
C++
Leet Code/Word Break II.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
51
2020-02-24T11:14:00.000Z
2022-03-24T09:32:18.000Z
Leet Code/Word Break II.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
3
2020-10-02T08:16:09.000Z
2021-04-17T16:32:38.000Z
Leet Code/Word Break II.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
18
2020-04-24T15:33:36.000Z
2022-03-24T09:32:20.000Z
/* Leet Code */ /* Title - Word Break II */ /* Created By - Akash Modak */ /* Date - 30/7/2020 */ // Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. // Note: // The same word in the dictionary may be reused multiple times in the segmentation. // You may assume the dictionary does not contain duplicate words. // Example 1: // Input: // s = "catsanddog" // wordDict = ["cat", "cats", "and", "sand", "dog"] // Output: // [ // "cats and dog", // "cat sand dog" // ] // Example 2: // Input: // s = "pineapplepenapple" // wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] // Output: // [ // "pine apple pen apple", // "pineapple pen apple", // "pine applepen apple" // ] // Explanation: Note that you are allowed to reuse a dictionary word. // Example 3: // Input: // s = "catsandog" // wordDict = ["cats", "dog", "sand", "and", "cat"] // Output: // [] class Solution { public: unordered_map<string, vector<string>> dp; vector<string> util(string s, vector<string>& wordDict){ if(s.empty()) return {""}; if(dp.find(s)!=dp.end()) return dp[s]; vector<string>sub,whole; for(string word : wordDict){ string igot = s.substr(0,word.length()); if(igot != word){ continue ; }else{ sub = util(s.substr(word.length()) , wordDict); } for(string ans : sub){ string space = ans.length()==0 ? "" : " "; whole.push_back(word+space+ans); } } return dp[s] = whole; } vector<string> wordBreak(string s, vector<string>& wordDict) { dp.clear(); return util(s,wordDict); } };
24.909091
214
0.55318
Shubhrmcf07
4269616c992300e60e21a3675c0f8141b9005ac5
1,371
cpp
C++
Source/Urho3D/Urho2D/Urho2D.cpp
1vanK/Dviglo
468a61e6d9a87cf7d998312c1261aaa83b37ff3c
[ "MIT" ]
null
null
null
Source/Urho3D/Urho2D/Urho2D.cpp
1vanK/Dviglo
468a61e6d9a87cf7d998312c1261aaa83b37ff3c
[ "MIT" ]
1
2021-04-17T22:38:25.000Z
2021-04-18T00:43:15.000Z
Source/Urho3D/Urho2D/Urho2D.cpp
1vanK/Dviglo
468a61e6d9a87cf7d998312c1261aaa83b37ff3c
[ "MIT" ]
null
null
null
// Copyright (c) 2008-2021 the Urho3D project // Copyright (c) 2021 проект Dviglo // Лицензия: MIT #include "../Precompiled.h" #include "../Core/Context.h" #include "../Urho2D/StretchableSprite2D.h" #include "../Urho2D/AnimatedSprite2D.h" #include "../Urho2D/AnimationSet2D.h" #include "../Urho2D/ParticleEffect2D.h" #include "../Urho2D/ParticleEmitter2D.h" #include "../Urho2D/Renderer2D.h" #include "../Urho2D/Sprite2D.h" #include "../Urho2D/SpriteSheet2D.h" #include "../Urho2D/TileMap2D.h" #include "../Urho2D/TileMapLayer2D.h" #include "../Urho2D/TmxFile2D.h" #include "../Urho2D/Urho2D.h" #include "../DebugNew.h" namespace Dviglo { const char* URHO2D_CATEGORY = "Urho2D"; void RegisterUrho2DLibrary(Context* context) { Renderer2D::RegisterObject(context); Sprite2D::RegisterObject(context); SpriteSheet2D::RegisterObject(context); // Must register objects from base to derived order Drawable2D::RegisterObject(context); StaticSprite2D::RegisterObject(context); StretchableSprite2D::RegisterObject(context); AnimationSet2D::RegisterObject(context); AnimatedSprite2D::RegisterObject(context); ParticleEffect2D::RegisterObject(context); ParticleEmitter2D::RegisterObject(context); TmxFile2D::RegisterObject(context); TileMap2D::RegisterObject(context); TileMapLayer2D::RegisterObject(context); } }
25.867925
55
0.737418
1vanK
f119e3f1a982e20ceda42c3237315147eded3850
2,960
hpp
C++
sc-memory/wrap/sc_stream.hpp
AbaevTM/json-parser-sc-machine
8ebe4fdc7be9076e23dd70de92761a8421a81d76
[ "MIT" ]
null
null
null
sc-memory/wrap/sc_stream.hpp
AbaevTM/json-parser-sc-machine
8ebe4fdc7be9076e23dd70de92761a8421a81d76
[ "MIT" ]
2
2016-05-19T11:54:58.000Z
2016-05-19T12:31:25.000Z
sc-memory/wrap/sc_stream.hpp
AbaevTM/json-parser-sc-machine
8ebe4fdc7be9076e23dd70de92761a8421a81d76
[ "MIT" ]
null
null
null
/* * This source file is part of an OSTIS project. For the latest info, see http://ostis.net * Distributed under the MIT License * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ #pragma once extern "C" { #include "sc_memory_headers.h" } #include "sc_types.hpp" #include "sc_utils.hpp" namespace sc { class IStream { public: _SC_EXTERN virtual bool isValid() const = 0; _SC_EXTERN virtual bool read(sc_char * buff, sc_uint32 buffLen, sc_uint32 & readBytes) const = 0; _SC_EXTERN virtual bool write(sc_char * data, sc_uint32 dataLen, sc_uint32 & writtenBytes) = 0; _SC_EXTERN virtual bool seek(sc_stream_seek_origin origin, sc_uint32 offset) = 0; //! Check if current position at the end of file _SC_EXTERN virtual bool eof() const = 0; //! Returns lenght of stream in bytes _SC_EXTERN virtual sc_uint32 size() const = 0; //! Returns current position of stream _SC_EXTERN virtual sc_uint32 pos() const = 0; //! Check if stream has a specified flag _SC_EXTERN virtual bool hasFlag(sc_uint8 flag) = 0; }; class Stream : public IStream { friend class MemoryContext; public: _SC_EXTERN explicit Stream(); _SC_EXTERN explicit Stream(sc_stream * stream); _SC_EXTERN explicit Stream(std::string const & fileName, sc_uint8 flags); _SC_EXTERN explicit Stream(sc_char * buffer, sc_uint32 bufferSize, sc_uint8 flags); _SC_EXTERN explicit Stream(sc_char const * buffer, sc_uint32 bufferSize, sc_uint8 flags); _SC_EXTERN ~Stream(); _SC_EXTERN void reset(); _SC_EXTERN bool isValid() const; _SC_EXTERN bool read(sc_char * buff, sc_uint32 buffLen, sc_uint32 & readBytes) const; _SC_EXTERN bool write(sc_char * data, sc_uint32 dataLen, sc_uint32 & writtenBytes); _SC_EXTERN bool seek(sc_stream_seek_origin origin, sc_uint32 offset); //! Check if current position at the end of file _SC_EXTERN bool eof() const; //! Returns lenght of stream in bytes _SC_EXTERN sc_uint32 size() const; //! Returns current position of stream _SC_EXTERN sc_uint32 pos() const; //! Check if stream has a specified flag _SC_EXTERN bool hasFlag(sc_uint8 flag); protected: //! Init with new stream object. Used by MemoryContext::getLinkContent void init(sc_stream * stream); protected: sc_stream * mStream; }; class StreamMemory : public IStream { public: _SC_EXTERN explicit StreamMemory(MemoryBufferPtr const & buff); _SC_EXTERN virtual ~StreamMemory(); _SC_EXTERN bool isValid() const; _SC_EXTERN bool read(sc_char * buff, sc_uint32 buffLen, sc_uint32 & readBytes) const; _SC_EXTERN bool write(sc_char * data, sc_uint32 dataLen, sc_uint32 & writtenBytes); _SC_EXTERN bool seek(sc_stream_seek_origin origin, sc_uint32 offset); _SC_EXTERN bool eof() const; _SC_EXTERN sc_uint32 size() const; _SC_EXTERN sc_uint32 pos() const; _SC_EXTERN bool hasFlag(sc_uint8 flag); private: MemoryBufferPtr mBuffer; mutable sc_uint32 mPos; }; SHARED_PTR_TYPE(IStream) }
26.19469
98
0.753378
AbaevTM
f11a018f0c555085ba4418b893b7a855262dca93
24,586
cpp
C++
EU4ToVic2Tests/MapperTests/IdeaEffectsMapperTests.cpp
Clonefusion/EU4toVic2
d39157b8317152da4ca138a69d78b6335bb27eb3
[ "MIT" ]
2
2020-01-02T16:07:51.000Z
2020-01-12T17:55:13.000Z
EU4ToVic2Tests/MapperTests/IdeaEffectsMapperTests.cpp
Clonefusion/EU4toVic2
d39157b8317152da4ca138a69d78b6335bb27eb3
[ "MIT" ]
3
2020-01-12T19:44:56.000Z
2020-01-17T05:40:41.000Z
EU4ToVic2Tests/MapperTests/IdeaEffectsMapperTests.cpp
Clonefusion/EU4toVic2
d39157b8317152da4ca138a69d78b6335bb27eb3
[ "MIT" ]
1
2020-01-12T17:55:40.000Z
2020-01-12T17:55:40.000Z
/*Copyright (c) 2019 The Paradox Game Converters Project 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 "gtest/gtest.h" #include "../EU4toV2/Source/Mappers/Ideas/IdeaEffectMapper.h" #include <sstream> TEST(Mappers_IdeaEffectMapperTests, getEnforceFromIdeaReturnsEmptyForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getEnforceFromIdea("missingIdea", 1); ASSERT_EQ(investment, ""); } TEST(Mappers_IdeaEffectMapperTests, getEnforceFromIdeaDefaultsToEmpty) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getEnforceFromIdea("specifiedIdea", 1), ""); } TEST(Mappers_IdeaEffectMapperTests, getEnforceFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tenforce = absolute_monarchy"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getEnforceFromIdea("specifiedIdea", 7), "absolute_monarchy"); } TEST(Mappers_IdeaEffectMapperTests, getEnforceFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tenforce = absolute_monarchy"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getEnforceFromIdea("specifiedIdea", 4), ""); } TEST(Mappers_IdeaEffectMapperTests, getArmyFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getArmyFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getArmyFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getArmyFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getArmyFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tarmy = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getArmyFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getArmyFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tarmy = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getArmyFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getNavyFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getNavyFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getNavyFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getNavyFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getNavyFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tnavy = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getNavyFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getNavyFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tnavy = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getNavyFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getCommerceFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getCommerceFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getCommerceFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getCommerceFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getCommerceFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tcommerce = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getCommerceFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getCommerceFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tcommerce = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getCommerceFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getCultureFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getCultureFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getCultureFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getCultureFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getCultureFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tculture = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getCultureFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getCultureFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tculture = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getCultureFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getIndustryFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getIndustryFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getIndustryFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getIndustryFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getIndustryFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tindustry = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getIndustryFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getIndustryFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tindustry = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getIndustryFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getLibertyFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getLibertyFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getLibertyFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getLibertyFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getLibertyFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tliberty = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getLibertyFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getLibertyFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tliberty = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getLibertyFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getEqualityFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getEqualityFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getEqualityFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getEqualityFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getEqualityFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tequality = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getEqualityFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getEqualityFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tequality = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getEqualityFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getOrderFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getOrderFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getOrderFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getOrderFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getOrderFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\torder = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getOrderFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getOrderFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\torder = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getOrderFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getLiteracyFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getLiteracyFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getLiteracyFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getLiteracyFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getLiteracyFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tliteracy = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getLiteracyFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getLiteracyFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tliteracy = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getLiteracyFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getLiberalFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getLiberalFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getLiberalFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getLiberalFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getLiberalFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tliberal = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getLiberalFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getLiberalFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tliberal = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getLiberalFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getReactionaryFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getReactionaryFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getReactionaryFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getReactionaryFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getReactionaryFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\treactionary = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getReactionaryFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getReactionaryFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\treactionary = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getReactionaryFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getSlaveryFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getSlaveryFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getSlaveryFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getSlaveryFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getSlaveryFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tslavery = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getSlaveryFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getSlaveryFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tslavery = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getSlaveryFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getUpper_house_compositionFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getUpper_house_compositionFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getUpper_house_compositionFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getUpper_house_compositionFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getUpper_house_compositionFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tupper_house_composition = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getUpper_house_compositionFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getUpper_house_compositionFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tupper_house_composition = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getUpper_house_compositionFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getVote_franchiseFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getVote_franchiseFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getVote_franchiseFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getVote_franchiseFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getVote_franchiseFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tvote_franchise = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getVote_franchiseFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getVote_franchiseFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tvote_franchise = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getVote_franchiseFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getVoting_systemFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getVoting_systemFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getVoting_systemFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getVoting_systemFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getVoting_systemFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tvoting_system = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getVoting_systemFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getVoting_systemFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tvoting_system = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getVoting_systemFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getPublic_meetingsFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getPublic_meetingsFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getPublic_meetingsFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getPublic_meetingsFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getPublic_meetingsFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tpublic_meetings = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getPublic_meetingsFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getPublic_meetingsFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tpublic_meetings = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getPublic_meetingsFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getPress_rightsFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getPress_rightsFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getPress_rightsFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getPress_rightsFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getPress_rightsFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tpress_rights = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getPress_rightsFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getPress_rightsFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tpress_rights = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getPress_rightsFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getTrade_unionsFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getTrade_unionsFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getTrade_unionsFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getTrade_unionsFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getTrade_unionsFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\ttrade_unions = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getTrade_unionsFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getTrade_unionsFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\ttrade_unions = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getTrade_unionsFromIdea("specifiedIdea", 4), 5); } TEST(Mappers_IdeaEffectMapperTests, getPolitical_partiesFromIdeaReturnsFiveForMissingIdea) { std::stringstream input; mappers::IdeaEffectMapper theMapper(input, input); auto investment = theMapper.getPolitical_partiesFromIdea("missingIdea", 1); ASSERT_EQ(investment, 5); } TEST(Mappers_IdeaEffectMapperTests, getPolitical_partiesFromIdeaDefaultsToFive) { std::stringstream input; input << "specifiedIdea ={\n"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getPolitical_partiesFromIdea("specifiedIdea", 1), 5); } TEST(Mappers_IdeaEffectMapperTests, getPolitical_partiesFromIdeaCanBeSetForCompletedIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tpolitical_parties = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getPolitical_partiesFromIdea("specifiedIdea", 7), 1); } TEST(Mappers_IdeaEffectMapperTests, getPolitical_partiesFromIdeaCannotBeSetForIncompleteIdea) { std::stringstream input; input << "specifiedIdea ={\n"; input << "\tpolitical_parties = 1"; input << "}"; mappers::IdeaEffectMapper theMapper(input, input); ASSERT_EQ(theMapper.getArmyFromIdea("specifiedIdea", 4), 5); }
26.465016
99
0.770194
Clonefusion
f120f54376574b04555e03aced6de9a09795958b
151
cpp
C++
Cpp_primer_5th/code_part3/prog3_14.cpp
Links789/Cpp_primer_5th
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
[ "MIT" ]
null
null
null
Cpp_primer_5th/code_part3/prog3_14.cpp
Links789/Cpp_primer_5th
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
[ "MIT" ]
null
null
null
Cpp_primer_5th/code_part3/prog3_14.cpp
Links789/Cpp_primer_5th
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main(){ int n; vector<int> text; while(cin >> n) text.push_back(n); return 0; }
10.785714
20
0.655629
Links789
f1215ca40d4a6d21eafb106a07b2584254f51045
528
hpp
C++
wrapStringVector.hpp
LAGonauta/Alure-C-Interface
d6eb94a0bedd68ee076b084b6736dfee8ff95d0e
[ "Zlib" ]
1
2019-07-19T03:37:33.000Z
2019-07-19T03:37:33.000Z
wrapStringVector.hpp
LAGonauta/Alure-C-Interface
d6eb94a0bedd68ee076b084b6736dfee8ff95d0e
[ "Zlib" ]
null
null
null
wrapStringVector.hpp
LAGonauta/Alure-C-Interface
d6eb94a0bedd68ee076b084b6736dfee8ff95d0e
[ "Zlib" ]
null
null
null
#include <vector> #include "common.h" #ifndef __WRAPSTRINGVECTOR_H__ #define __WRAPSTRINGVECTOR_H__ #ifdef __cplusplus extern "C" { #endif DLL_PUBLIC wrapStringVector_t* wrapStringVector_create(std::vector<wrapString_t*> vector); DLL_PUBLIC void wrapStringVector_destroy(wrapStringVector_t* dm); DLL_PUBLIC uint64_t wrapStringVector_getSize(wrapStringVector_t* dm); DLL_PUBLIC wrapString_t* wrapStringVector_getAt(wrapStringVector_t* dm, uint64_t position); #ifdef __cplusplus } #endif #endif /* __WRAPSTRINGVECTOR_H__ */
22.956522
91
0.827652
LAGonauta
f1255f51472524661b626032a25cffd65da87655
697
cpp
C++
src/historypanel.cpp
SilangQuan/Pixer
2291ce1a32463510a9ac4b1444fb483180cfbe83
[ "MIT" ]
99
2015-01-14T01:10:37.000Z
2021-07-29T07:30:14.000Z
src/historypanel.cpp
sahwar/Pixer
2291ce1a32463510a9ac4b1444fb483180cfbe83
[ "MIT" ]
1
2019-08-07T13:06:31.000Z
2019-08-07T13:06:31.000Z
src/historypanel.cpp
sahwar/Pixer
2291ce1a32463510a9ac4b1444fb483180cfbe83
[ "MIT" ]
22
2015-01-19T14:53:22.000Z
2021-08-18T04:38:12.000Z
#include "historypanel.h" HistoryPanel::HistoryPanel(QUndoStack *stack,QWidget *parent) : QDockWidget(parent), undoView(stack) { this->setFeatures(QDockWidget::DockWidgetFloatable | \ QDockWidget::DockWidgetMovable | \ QDockWidget::DockWidgetClosable); this->setAttribute(Qt::WA_QuitOnClose, false); undoView.setBackgroundRole(QPalette::Dark); undoView.setFrameShape(QFrame::NoFrame); this->setWidget(&undoView); connect(&undoView, SIGNAL(pressed(const QModelIndex &)), this, SLOT(itemClickedSlot(const QModelIndex &))); } HistoryPanel::~HistoryPanel() { } void HistoryPanel::itemClickedSlot(const QModelIndex &index) { qDebug() << "itemClickedSlot"; emit historyTriggered(); }
24.034483
108
0.764706
SilangQuan
f12c9971493d54340d32f72eca1df09d36601c94
16,931
inl
C++
tmp/cohash-read-only/include/thrust/detail/device/cuda/reduce.inl
ismagarcia/cohash
d20c7489456c8df033f4fe86f459f1901e01114c
[ "Apache-2.0" ]
1
2022-02-25T08:14:55.000Z
2022-02-25T08:14:55.000Z
tmp/cohash-read-only/include/thrust/detail/device/cuda/reduce.inl
ismagarcia/cohash
d20c7489456c8df033f4fe86f459f1901e01114c
[ "Apache-2.0" ]
null
null
null
tmp/cohash-read-only/include/thrust/detail/device/cuda/reduce.inl
ismagarcia/cohash
d20c7489456c8df033f4fe86f459f1901e01114c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2008-2010 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file reduce.inl * \brief Inline file for reduce.h */ // do not attempt to compile this file with any other compiler #if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC // to configure launch parameters #include <thrust/detail/device/cuda/arch.h> #include <thrust/detail/type_traits.h> #include <thrust/detail/raw_buffer.h> #include <thrust/detail/device/cuda/block/reduce.h> #include <thrust/detail/device/cuda/extern_shared_ptr.h> #include <thrust/detail/device/cuda/dispatch/reduce.h> #include <thrust/iterator/transform_iterator.h> #include <thrust/functional.h> #include <thrust/detail/device/cuda/synchronize.h> namespace thrust { namespace detail { namespace device { namespace cuda { namespace detail { /* * Reduce a vector of n elements using binary_op() * * The order of reduction is not defined, so binary_op() should * be a commutative (and associative) operator such as * (integer) addition. Since floating point operations * do not completely satisfy these criteria, the result is * generally not the same as a consecutive reduction of * the elements. * * Uses the same pattern as reduce6() in the CUDA SDK * */ template<typename InputIterator, typename OutputType, typename BinaryFunction, typename SharedArray> __device__ void reduce_n_device(InputIterator input, const unsigned int n, OutputType * block_results, BinaryFunction binary_op, SharedArray shared_array) { // perform one level of reduction, writing per-block results to // global memory for subsequent processing (e.g. second level reduction) const unsigned int grid_size = blockDim.x * gridDim.x; unsigned int i = blockDim.x * blockIdx.x + threadIdx.x; // advance input input += i; if (i < n) { // initialize local sum OutputType sum = thrust::detail::device::dereference(input); i += grid_size; input += grid_size; // accumulate local sum while (i < n) { OutputType val = thrust::detail::device::dereference(input); sum = binary_op(sum, val); i += grid_size; input += grid_size; } // copy local sum to shared memory shared_array[threadIdx.x] = sum; } __syncthreads(); // compute reduction across block thrust::detail::device::cuda::block::reduce_n(shared_array, min(n - blockDim.x * blockIdx.x, blockDim.x), binary_op); // write result for this block to global mem if (threadIdx.x == 0) block_results[blockIdx.x] = shared_array[threadIdx.x]; } // end reduce_n_device() template<typename InputIterator, typename OutputType, typename BinaryFunction> __global__ void reduce_n_smem(InputIterator input, const unsigned int n, OutputType * block_results, BinaryFunction binary_op) { thrust::detail::device::cuda::extern_shared_ptr<OutputType> shared_ptr; OutputType *shared_array = shared_ptr; reduce_n_device(input, n, block_results, binary_op, shared_array); } // end reduce_n_kernel() template<typename InputIterator, typename OutputType, typename BinaryFunction> __global__ void reduce_n_gmem(InputIterator input, const unsigned int n, OutputType * block_results, OutputType * shared_array, BinaryFunction binary_op) { reduce_n_device(input, n, block_results, binary_op, shared_array + blockDim.x * blockIdx.x); } // end reduce_n_kernel() template <typename InputType, typename OutputType, typename BinaryFunction, typename WideType> struct wide_unary_op : public thrust::unary_function<WideType,OutputType> { BinaryFunction binary_op; __host__ __device__ wide_unary_op(BinaryFunction binary_op) : binary_op(binary_op) {} __host__ __device__ OutputType operator()(WideType x) { WideType mask = ((WideType) 1 << (8 * sizeof(InputType))) - 1; OutputType sum = static_cast<InputType>(x & mask); for(unsigned int n = 1; n < sizeof(WideType) / sizeof(InputType); n++) sum = binary_op(sum, static_cast<InputType>( (x >> (8 * n * sizeof(InputType))) & mask ) ); return sum; } }; #if THRUST_HOST_COMPILER == THRUST_HOST_COMPILER_MSVC // temporarily disable 'possible loss of data' warnings on MSVC #pragma warning(push) #pragma warning(disable : 4244 4267) #endif template<typename RandomAccessIterator1, typename SizeType1, typename SizeType2, typename BinaryFunction, typename RandomAccessIterator2> void unordered_blocked_reduce_n(RandomAccessIterator1 first, SizeType1 n, SizeType2 num_blocks, BinaryFunction binary_op, RandomAccessIterator2 result, thrust::detail::true_type) // reduce in shared memory { typedef typename thrust::iterator_value<RandomAccessIterator2>::type OutputType; // determine launch parameters const size_t smem_per_thread = sizeof(OutputType); const size_t block_size = thrust::detail::device::cuda::arch::max_blocksize_with_highest_occupancy(reduce_n_smem<RandomAccessIterator1, OutputType, BinaryFunction>, smem_per_thread); const size_t smem_size = block_size * smem_per_thread; // reduce input to per-block sums reduce_n_smem<<<num_blocks, block_size, smem_size>>>(first, n, thrust::raw_pointer_cast(&*result), binary_op); synchronize_if_enabled("reduce_n_smem"); } // end unordered_blocked_reduce_n() template<typename RandomAccessIterator1, typename SizeType1, typename SizeType2, typename BinaryFunction, typename RandomAccessIterator2> void unordered_blocked_reduce_n(RandomAccessIterator1 first, SizeType1 n, SizeType2 num_blocks, BinaryFunction binary_op, RandomAccessIterator2 result, thrust::detail::false_type) // reduce in global memory { typedef typename thrust::iterator_value<RandomAccessIterator2>::type OutputType; const size_t block_size = thrust::detail::device::cuda::arch::max_blocksize_with_highest_occupancy(reduce_n_gmem<RandomAccessIterator1, OutputType, BinaryFunction>, 0); // allocate storage for shared array thrust::detail::raw_cuda_device_buffer<OutputType> shared_array(block_size * num_blocks); // reduce input to per-block sums detail::reduce_n_gmem<<<num_blocks, block_size>>>(first, n, raw_pointer_cast(&*result), raw_pointer_cast(&shared_array[0]), binary_op); synchronize_if_enabled("reduce_n_gmem"); } // end unordered_blocked_reduce_n() template<typename Iterator, typename InputType = typename thrust::iterator_value<Iterator>::type> struct use_wide_reduction : thrust::detail::integral_constant< bool, thrust::detail::is_pod<InputType>::value && thrust::detail::is_trivial_iterator<Iterator>::value && (sizeof(InputType) == 1 || sizeof(InputType) == 2) > {}; } // end namespace detail #if THRUST_HOST_COMPILER == THRUST_HOST_COMPILER_MSVC // reenable 'possible loss of data' warnings #pragma warning(pop) #endif template<typename RandomAccessIterator, typename SizeType, typename OutputType, typename BinaryFunction> SizeType get_unordered_blocked_wide_reduce_n_schedule(RandomAccessIterator first, SizeType n, OutputType init, BinaryFunction binary_op) { // "wide" reduction for small types like char, short, etc. typedef typename thrust::iterator_traits<RandomAccessIterator>::value_type InputType; typedef unsigned int WideType; const size_t input_type_per_wide_type = sizeof(WideType) / sizeof(InputType); const size_t n_wide = n / input_type_per_wide_type; thrust::device_ptr<const WideType> wide_first = thrust::device_pointer_cast(reinterpret_cast<const WideType *>(thrust::raw_pointer_cast(&*first))); thrust::transform_iterator< detail::wide_unary_op<InputType,OutputType,BinaryFunction,WideType>, thrust::device_ptr<const WideType> > xfrm_wide_first = thrust::make_transform_iterator(wide_first, detail::wide_unary_op<InputType,OutputType,BinaryFunction,WideType>(binary_op)); const size_t num_blocks_from_wide_part = thrust::detail::device::cuda::get_unordered_blocked_standard_reduce_n_schedule(xfrm_wide_first, n_wide, init, binary_op); // add one block to reduce the tail (if there is one) RandomAccessIterator tail_first = first + n_wide * input_type_per_wide_type; const size_t n_tail = n - (tail_first - first); return num_blocks_from_wide_part + ((n_tail > 0) ? 1 : 0); } template<typename RandomAccessIterator, typename SizeType, typename OutputType, typename BinaryFunction> SizeType get_unordered_blocked_standard_reduce_n_schedule(RandomAccessIterator first, SizeType n, OutputType init, BinaryFunction binary_op) { // decide whether or not we will use smem size_t smem_per_thread = 0; if(sizeof(OutputType) <= 64) { smem_per_thread = sizeof(OutputType); } // choose block_size size_t block_size = 0; if(smem_per_thread > 0) { block_size = thrust::detail::device::cuda::arch::max_blocksize_with_highest_occupancy(detail::reduce_n_smem<RandomAccessIterator, OutputType, BinaryFunction>, smem_per_thread); } else { block_size = thrust::detail::device::cuda::arch::max_blocksize_with_highest_occupancy(detail::reduce_n_gmem<RandomAccessIterator, OutputType, BinaryFunction>, smem_per_thread); } const size_t smem_size = block_size * smem_per_thread; // choose the maximum number of blocks we can launch size_t max_blocks = 0; if(smem_per_thread > 0) { max_blocks = thrust::detail::device::cuda::arch::max_active_blocks(detail::reduce_n_smem<RandomAccessIterator, OutputType, BinaryFunction>, block_size, smem_size); } else { max_blocks = thrust::detail::device::cuda::arch::max_active_blocks(detail::reduce_n_gmem<RandomAccessIterator, OutputType, BinaryFunction>, block_size, smem_size); } // finalize the number of blocks to launch const size_t num_blocks = std::min<size_t>(max_blocks, (n + (block_size - 1)) / block_size); return num_blocks; } // TODO add runtime switch for SizeType vs. unsigned int // TODO use closure approach to handle large iterators & functors (i.e. sum > 256 bytes) template<typename RandomAccessIterator1, typename SizeType1, typename SizeType2, typename BinaryFunction, typename RandomAccessIterator2> void unordered_blocked_wide_reduce_n(RandomAccessIterator1 first, SizeType1 n, SizeType2 num_blocks, BinaryFunction binary_op, RandomAccessIterator2 result) { // XXX this implementation is incredibly ugly // if we only received one output block, use the standard reduction if(num_blocks < 2) { thrust::detail::device::cuda::unordered_blocked_standard_reduce_n(first, n, num_blocks, binary_op, result); } // end if else { // break the reduction into a "wide" body and the "tail" // this assumes we have at least two output blocks to work with // "wide" reduction for small types like char, short, etc. typedef typename thrust::iterator_traits<RandomAccessIterator1>::value_type InputType; typedef typename thrust::iterator_traits<RandomAccessIterator2>::value_type OutputType; typedef unsigned int WideType; // note: this assumes that InputIterator is a InputType * and can be reinterpret_casted to WideType * // TODO use simple threshold and ensure alignment of wide_first // process first part const size_t input_type_per_wide_type = sizeof(WideType) / sizeof(InputType); const size_t n_wide = n / input_type_per_wide_type; thrust::device_ptr<const WideType> wide_first(reinterpret_cast<const WideType *>(thrust::raw_pointer_cast(&*first))); thrust::transform_iterator< detail::wide_unary_op<InputType,OutputType,BinaryFunction,WideType>, thrust::device_ptr<const WideType> > xfrm_wide_first = thrust::make_transform_iterator(wide_first, detail::wide_unary_op<InputType,OutputType,BinaryFunction,WideType>(binary_op)); // compute where the tail is RandomAccessIterator1 tail_first = first + n_wide * input_type_per_wide_type; const size_t n_tail = n - (tail_first - first); // count the number of results to produce from the widened input size_t num_wide_results = num_blocks; // reserve one of the results for the tail, if there is one if(n_tail > 0) { --num_wide_results; } // process the wide body thrust::detail::device::cuda::unordered_blocked_standard_reduce_n(xfrm_wide_first, n_wide, num_wide_results, binary_op, result); // process tail thrust::detail::device::cuda::unordered_blocked_standard_reduce_n(tail_first, n_tail, (size_t)1u, binary_op, result + num_wide_results); } // end else } // end unordered_blocked_wide_reduce_n() template<typename RandomAccessIterator1, typename SizeType1, typename SizeType2, typename BinaryFunction, typename RandomAccessIterator2> void unordered_blocked_standard_reduce_n(RandomAccessIterator1 first, SizeType1 n, SizeType2 num_blocks, BinaryFunction binary_op, RandomAccessIterator2 result) { typedef typename thrust::iterator_value<RandomAccessIterator2>::type OutputType; // handle zero length input or output if(n == 0 || num_blocks == 0) return; // whether to perform blockwise reductions in shared memory or global memory thrust::detail::integral_constant<bool, sizeof(OutputType) <= 64> use_smem; return detail::unordered_blocked_reduce_n(first, n, num_blocks, binary_op, result, use_smem); } // end unordered_standard_blocked_reduce_n() template<typename RandomAccessIterator1, typename SizeType1, typename SizeType2, typename BinaryFunction, typename RandomAccessIterator2> void unordered_blocked_reduce_n(RandomAccessIterator1 first, SizeType1 n, SizeType2 num_blocks, BinaryFunction binary_op, RandomAccessIterator2 result) { // dispatch on whether or not to use a wide reduction return thrust::detail::device::cuda::dispatch::unordered_blocked_reduce_n(first, n, num_blocks, binary_op, result, typename detail::use_wide_reduction<RandomAccessIterator1>::type()); } // end unordered_blocked_reduce_n() template<typename RandomAccessIterator, typename SizeType, typename OutputType, typename BinaryFunction> SizeType get_unordered_blocked_reduce_n_schedule(RandomAccessIterator first, SizeType n, OutputType init, BinaryFunction binary_op) { // dispatch on whether or not to use the wide reduction return thrust::detail::device::cuda::dispatch::get_unordered_blocked_reduce_n_schedule(first, n, init, binary_op, typename detail::use_wide_reduction<RandomAccessIterator>::type()); } } // end namespace cuda } // end namespace device } // end namespace detail } // end namespace thrust #endif // THRUST_DEVICE_COMPILER != THRUST_DEVICE_COMPILER_NVCC
36.967249
184
0.677396
ismagarcia
f133403a74e5e48ac921b67904eee315e55ce2ce
362
cpp
C++
addons/ofxKinectForWindows2/exampleBodyIndexShader/src/main.cpp
syeminpark/openFrame
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
[ "MIT" ]
145
2015-02-14T09:32:04.000Z
2022-01-21T21:17:27.000Z
addons/ofxKinectForWindows2/exampleBodyIndexShader/src/main.cpp
syeminpark/openFrame
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
[ "MIT" ]
80
2015-01-01T03:28:49.000Z
2021-04-03T09:08:54.000Z
addons/ofxKinectForWindows2/exampleBodyIndexShader/src/main.cpp
syeminpark/openFrame
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
[ "MIT" ]
74
2015-01-11T16:23:57.000Z
2021-12-22T07:16:13.000Z
#include "ofMain.h" #include "ofApp.h" //-------------------------------------------------------------- int main(){ #ifdef USE_PROGRAMMABLE_PIPELINE ofGLWindowSettings settings; settings.setGLVersion(4,3); settings.width = 1024; settings.height = 768; ofCreateWindow(settings); #else ofSetupOpenGL(1024, 768, OF_WINDOW); #endif ofRunApp(new ofApp()); }
20.111111
64
0.61326
syeminpark
f133d2a074c29505599e68d75668d881a126e20e
530
cpp
C++
C++/BehaviorTreesLib/Action.cpp
JuanFerrer/behavior-trees
43cc40c8bce4e3b9737bbd5bcd98a50948b91fc9
[ "MIT" ]
3
2019-10-20T18:46:08.000Z
2022-02-12T20:39:53.000Z
C++/BehaviorTreesLib/Action.cpp
JuanFerrer/behavior-trees
43cc40c8bce4e3b9737bbd5bcd98a50948b91fc9
[ "MIT" ]
null
null
null
C++/BehaviorTreesLib/Action.cpp
JuanFerrer/behavior-trees
43cc40c8bce4e3b9737bbd5bcd98a50948b91fc9
[ "MIT" ]
1
2021-04-12T09:00:07.000Z
2021-04-12T09:00:07.000Z
#include "Action.h" namespace fluentBehaviorTree { Node * Action::copy() { Action* newNode = new Action(this->getName(), this->mAction); return newNode; } //Action::Action(std::string name, EStatus(*f)()) Action::Action(std::string name, std::function<EStatus()> f) { this->setName(name); mAction = f; } // Return result of action EStatus Action::tickNode() { try { this->setResult(mAction()); } catch (std::exception& e) { this->setResult(EStatus::ERROR); } return this->getResult(); } }
17.096774
63
0.637736
JuanFerrer
f133d7087112d40f2ca9b96a2d04587509da3332
8,609
cxx
C++
client/mock_sdl.cxx
Drako/MPSnake
a22bd7156f79f9824ce689c54ac4a7ef085efd08
[ "MIT" ]
null
null
null
client/mock_sdl.cxx
Drako/MPSnake
a22bd7156f79f9824ce689c54ac4a7ef085efd08
[ "MIT" ]
null
null
null
client/mock_sdl.cxx
Drako/MPSnake
a22bd7156f79f9824ce689c54ac4a7ef085efd08
[ "MIT" ]
null
null
null
#include "mock_sdl.hxx" #include "native.hxx" #include "default_colors.hxx" #include <cassert> #include <filesystem> struct SDL_Window { char const * title; int x, y, w, h; std::uint32_t flags; SDL_DisplayMode mode; }; namespace snake::client { template <MockPolicy policy> int MockSDL<policy>::getCallCount(Mock mock) const { auto const it = m_callCounts.find(mock); return it == m_callCounts.end() ? 0 : it->second; } template <MockPolicy policy> int MockSDL<policy>::init(std::uint32_t features) { ++m_callCounts[Mock::Init]; auto const & impl = getMock<Mock::Init>().impl; if (impl) return impl(features); else if constexpr (policy == MockPolicy::Stub) return 0; else return ActualSDL::init(features); } template <MockPolicy policy> void MockSDL<policy>::quit() { ++m_callCounts[Mock::Quit]; auto const & impl = getMock<Mock::Quit>().impl; if (impl) impl(); else if constexpr (policy == MockPolicy::CallOriginal) ActualSDL::quit(); } template <MockPolicy policy> char const * MockSDL<policy>::getError() { ++m_callCounts[Mock::GetError]; auto const & impl = getMock<Mock::GetError>().impl; if (impl) return impl(); else if constexpr (policy == MockPolicy::Stub) return ""; else return ActualSDL::getError(); } template <MockPolicy policy> std::uint32_t MockSDL<policy>::wasInit(std::uint32_t features) { ++m_callCounts[Mock::WasInit]; auto const & impl = getMock<Mock::WasInit>().impl; if (impl) return impl(features); else if constexpr (policy == MockPolicy::Stub) return features; else return ActualSDL::wasInit(features); } template <MockPolicy policy> SDL_Window * MockSDL<policy>::createWindow(char const * title, int x, int y, int w, int h, std::uint32_t flags) { ++m_callCounts[Mock::CreateWindow]; auto const & impl = getMock<Mock::CreateWindow>().impl; if (impl) return impl(title, x, y, w, h, flags); else if constexpr (policy == MockPolicy::Stub) return new SDL_Window{title, x, y, w, h, flags}; else return ActualSDL::createWindow(title, x, y, w, h, flags); } template <MockPolicy policy> void MockSDL<policy>::destroyWindow(SDL_Window * window) { ++m_callCounts[Mock::DestroyWindow]; auto const & impl = getMock<Mock::DestroyWindow>().impl; if (impl) impl(window); else if constexpr (policy == MockPolicy::Stub) delete window; else ActualSDL::destroyWindow(window); } template <MockPolicy policy> int MockSDL<policy>::setWindowDisplayMode(SDL_Window * window, SDL_DisplayMode const * mode) { ++m_callCounts[Mock::SetWindowDisplayMode]; auto const & impl = getMock<Mock::SetWindowDisplayMode>().impl; if (impl) return impl(window, mode); else if constexpr (policy == MockPolicy::Stub) { assert(window != nullptr); assert(mode != nullptr); window->mode = *mode; return 0; } else return ActualSDL::setWindowDisplayMode(window, mode); } template <MockPolicy policy> int MockSDL<policy>::getWindowDisplayMode(SDL_Window * window, SDL_DisplayMode * mode) { ++m_callCounts[Mock::GetWindowDisplayMode]; auto const & impl = getMock<Mock::GetWindowDisplayMode>().impl; if (impl) return impl(window, mode); else if constexpr (policy == MockPolicy::Stub) { assert(window != nullptr); assert(mode != nullptr); *mode = window->mode; return 0; } else return ActualSDL::getWindowDisplayMode(window, mode); } template <MockPolicy policy> int MockSDL<policy>::pollEvent(SDL_Event * event) { ++m_callCounts[Mock::PollEvent]; auto const & impl = getMock<Mock::PollEvent>().impl; if (impl) return impl(event); else if constexpr (policy == MockPolicy::Stub) { assert(event != nullptr); return 0; } else return ActualSDL::pollEvent(event); } template <MockPolicy policy> int MockSDL<policy>::pushEvent(SDL_Event * event) { ++m_callCounts[Mock::PushEvent]; auto const & impl = getMock<Mock::PushEvent>().impl; if (impl) return impl(event); else if constexpr (policy == MockPolicy::Stub) { assert(event != nullptr); return 0; } else return ActualSDL::pushEvent(event); } template <MockPolicy policy> void MockSDL<policy>::useEventQueue(std::deque<SDL_Event> & queue) { mockFunction<Mock::PushEvent>([&queue](SDL_Event * event) { assert(event != nullptr); queue.push_back(*event); return 1; }); mockFunction<Mock::PollEvent>([&queue](SDL_Event * event) { assert(event != nullptr); if (queue.empty()) return 0; else { *event = queue.front(); queue.pop_front(); return 1; } }); } SDL_Event event_helpers::makeQuitEvent(std::uint32_t timestamp) { SDL_Event result{}; result.quit = SDL_QuitEvent{SDL_QUIT, timestamp}; return result; } template <MockPolicy policy> SDL_Surface * MockSDL<policy>::getWindowSurface(SDL_Window * window) { ++m_callCounts[Mock::GetWindowSurface]; auto const & impl = getMock<Mock::GetWindowSurface>().impl; if (impl) return impl(window); else if constexpr (policy == MockPolicy::Stub) { assert(window != nullptr); return nullptr; } else return ActualSDL::getWindowSurface(window); } template <MockPolicy policy> void MockSDL<policy>::freeSurface(SDL_Surface * surface) { ++m_callCounts[Mock::FreeSurface]; auto const & impl = getMock<Mock::FreeSurface>().impl; if (impl) impl(surface); else if constexpr (policy == MockPolicy::Stub) delete surface; else ActualSDL::freeSurface(surface); } template <MockPolicy policy> int MockSDL<policy>::fillRect(SDL_Surface * destination, SDL_Rect const * rect, std::uint32_t color) { ++m_callCounts[Mock::FillRect]; auto const & impl = getMock<Mock::FillRect>().impl; if (impl) return impl(destination, rect, color); else if constexpr (policy == MockPolicy::Stub) return 0; else return ActualSDL::fillRect(destination, rect, color); } template <MockPolicy policy> uint32_t MockSDL<policy>::mapRGBA(SDL_PixelFormat const * format, std::uint8_t r, std::uint8_t g, std::uint8_t b, std::uint8_t a) { ++m_callCounts[Mock::MapRGBA]; auto const & impl = getMock<Mock::MapRGBA>().impl; if (impl) return impl(format, r, g, b, a); else if constexpr (policy == MockPolicy::Stub) return colors::colorToRGBA({r, g, b, a}); else return ActualSDL::mapRGBA(format, r, g, b, a); } template <MockPolicy policy> int MockSDL<policy>::updateWindowSurface(SDL_Window * window) { ++m_callCounts[Mock::UpdateWindowSurface]; auto const & impl = getMock<Mock::UpdateWindowSurface>().impl; if (impl) return impl(window); else if constexpr (policy == MockPolicy::Stub) return 0; else return ActualSDL::updateWindowSurface(window); } template <MockPolicy policy> std::string MockSDL<policy>::getBasePath() { ++m_callCounts[Mock::GetBasePath]; auto const & impl = getMock<Mock::GetBasePath>().impl; if (impl) return impl(); else if constexpr (policy == MockPolicy::Stub) return native::getExePath().parent_path(); else return ActualSDL::getBasePath(); } template <MockPolicy policy> std::string MockSDL<policy>::getPrefPath(char const * organizationName, char const * applicationName) { ++m_callCounts[Mock::GetPrefPath]; auto const & impl = getMock<Mock::GetPrefPath>().impl; if (impl) return impl(organizationName, applicationName); else if constexpr (policy == MockPolicy::Stub) return std::filesystem::temp_directory_path(); else return ActualSDL::getPrefPath(organizationName, applicationName); } template <MockPolicy policy> SDL_Surface * MockSDL<policy>::createRGBSurfaceWithFormat(std::uint32_t flags, int width, int height, int depth, std::uint32_t format) { ++m_callCounts[Mock::CreateRGBSurfaceWithFormat]; auto const & impl = getMock<Mock::CreateRGBSurfaceWithFormat>().impl; if (impl) return impl(flags, width, height, depth, format); else if constexpr (policy == MockPolicy::Stub) return new SDL_Surface{flags, nullptr, width, height}; else return ActualSDL::createRGBSurfaceWithFormat(flags, width, height, depth, format); } template class MockSDL<MockPolicy::Stub>; template class MockSDL<MockPolicy::CallOriginal>; }
31.305455
114
0.663956
Drako
f1363e9b219963d000f28531bfbc954a6c2e19c6
981
cpp
C++
240_Search a 2D Matrix II.cpp
anubhavnandan/leetCode
2cb9511b2c37b80f3ee57b3932d1dc9e7be9994f
[ "Apache-2.0" ]
1
2021-09-30T10:02:35.000Z
2021-09-30T10:02:35.000Z
240_Search a 2D Matrix II.cpp
anubhavnandan/leetCode
2cb9511b2c37b80f3ee57b3932d1dc9e7be9994f
[ "Apache-2.0" ]
null
null
null
240_Search a 2D Matrix II.cpp
anubhavnandan/leetCode
2cb9511b2c37b80f3ee57b3932d1dc9e7be9994f
[ "Apache-2.0" ]
null
null
null
//C++ 11 #include<iostream> #include<vector> using namespace std; class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int row=-1,col=-1; for(int i=0; i<matrix.size(); i++){ for(int j=0; j<matrix[i].size(); j++){ if(i==j){ if(target==matrix[i][j]) return true; else if(target<matrix[i][j] && i>0 && j>0){ row=i-1; col=j-1; break; } } } } if(row!=-1 && col!=-1){ for(int i=row; i<matrix.size(); i++){ if(target==matrix[i][col]) return true; } for(int j=col; j<matrix[row].size(); j++){ if(target==matrix[row][j]) return true; } } return false; } }; int main(){ vector<vector<int>> V = {{1,4},{2,5}}; //{{1,4,7,11,15},{2,5,8,12,19},{3,6,9,16,22},{10,13,14,17,24},{18,21,23,26,30}}; Solution Obj; cout<<Obj.searchMatrix(V,2); return 0; }
22.295455
80
0.474006
anubhavnandan
f1368af0b8f2b7466ea7f18c8e33951f47157d5a
391
hpp
C++
utils/parameters_utils_t.hpp
dioptra-io/diamond-miner-cpp
8f41e3211bdbdc96eecd57f6fb3c459b0350d3e5
[ "MIT" ]
null
null
null
utils/parameters_utils_t.hpp
dioptra-io/diamond-miner-cpp
8f41e3211bdbdc96eecd57f6fb3c459b0350d3e5
[ "MIT" ]
null
null
null
utils/parameters_utils_t.hpp
dioptra-io/diamond-miner-cpp
8f41e3211bdbdc96eecd57f6fb3c459b0350d3e5
[ "MIT" ]
1
2020-11-03T14:51:43.000Z
2020-11-03T14:51:43.000Z
// // Created by System Administrator on 2019-08-02. // #ifndef HEARTBEAT_PARAMETERS_UTILS_T_HPP #define HEARTBEAT_PARAMETERS_UTILS_T_HPP #include <cstdint> namespace utils{ extern uint16_t default_sport; extern uint16_t default_dport; extern uint32_t default_dst_ip; extern int default_1_round_flows; extern int max_ttl; } #endif //HEARTBEAT_PARAMETERS_UTILS_T_HPP
19.55
49
0.785166
dioptra-io
f138c5e88387d953e4170e678fab7166a67c5055
4,516
cpp
C++
firmware/src/SSRPump.cpp
solderdev/silvia
a1c5f255054849306b8383e0a98fb7322a7b625f
[ "MIT" ]
1
2020-12-03T20:26:48.000Z
2020-12-03T20:26:48.000Z
firmware/src/SSRPump.cpp
solderdev/silvia
a1c5f255054849306b8383e0a98fb7322a7b625f
[ "MIT" ]
null
null
null
firmware/src/SSRPump.cpp
solderdev/silvia
a1c5f255054849306b8383e0a98fb7322a7b625f
[ "MIT" ]
null
null
null
#include "SSRPump.hpp" #include "helpers.hpp" static void timer_callback(void); static SSRPump *instance = nullptr; SSRPump::SSRPump(uint8_t ctrl_pin, int32_t timer_id, uint32_t timer_period_us) : SSR(ctrl_pin), timer_pwm_(nullptr), pwm_percent_(PWM_0_PERCENT), time_on_(0) { if (instance) { Serial.println("ERROR: more than one pumps generated"); ESP.restart(); return; } timer_pwm_ = timerBegin(timer_id, 80, true); timerAttachInterrupt(timer_pwm_, &timer_callback, true); timerAlarmWrite(timer_pwm_, timer_period_us, true); timerAlarmEnable(timer_pwm_); instance = this; } SSRPump* SSRPump::getInstance() { return instance; } void SSRPump::setPWM(uint8_t percent) { if (!enabled_ || timer_pwm_ == nullptr) return; if (percent < 5) { if (pwm_percent_ != PWM_0_PERCENT && systime_ms() - time_on_ > 3000) { // if (SHOT_getState() != SHOT_PAUSE) // PID_override(0.0f, PID_OVERRIDE_CNT); } pwm_percent_ = PWM_0_PERCENT; } else { if (pwm_percent_ == PWM_0_PERCENT) time_on_ = systime_ms(); if (percent < 15) pwm_percent_ = PWM_10_PERCENT; else if (percent < 25) pwm_percent_ = PWM_20_PERCENT; else if (percent < 35) pwm_percent_ = PWM_30_PERCENT; else if (percent < 45) pwm_percent_ = PWM_40_PERCENT; else if (percent < 55) pwm_percent_ = PWM_50_PERCENT; else if (percent < 65) pwm_percent_ = PWM_60_PERCENT; else if (percent < 75) pwm_percent_ = PWM_70_PERCENT; else if (percent < 85) pwm_percent_ = PWM_80_PERCENT; else if (percent < 95) pwm_percent_ = PWM_90_PERCENT; else if (percent <= 100) pwm_percent_ = PWM_100_PERCENT; else { Serial.print("SSRPump: pump pwm percent not valid! "); Serial.println(percent); pwm_percent_ = PWM_0_PERCENT; return; } } } PWM_Percent_t IRAM_ATTR SSRPump::getPWM() { return pwm_percent_; } static void IRAM_ATTR timer_callback(void) { static uint32_t pwm_period_counter_ = 0; // elapsed periods if (instance == nullptr) return; if (!instance->isEnabled()) { pwm_period_counter_ = 0; instance->off(); return; } // called every 20ms == full sine period switch (instance->getPWM()) { case PWM_0_PERCENT: instance->off(); pwm_period_counter_ = 0; break; case PWM_10_PERCENT: if (pwm_period_counter_ == 0) instance->on(); else instance->off(); if (++pwm_period_counter_ >= 10) pwm_period_counter_ = 0; break; case PWM_20_PERCENT: if (pwm_period_counter_ == 0) instance->on(); else instance->off(); if (++pwm_period_counter_ >= 5) pwm_period_counter_ = 0; break; case PWM_30_PERCENT: if (pwm_period_counter_ == 0) instance->on(); else instance->off(); if (++pwm_period_counter_ >= 3) pwm_period_counter_ = 0; break; case PWM_40_PERCENT: if (pwm_period_counter_ == 0 || pwm_period_counter_ == 2) instance->on(); else instance->off(); if (++pwm_period_counter_ >= 5) pwm_period_counter_ = 0; break; case PWM_50_PERCENT: if (pwm_period_counter_ == 0) instance->on(); else instance->off(); if (++pwm_period_counter_ >= 2) pwm_period_counter_ = 0; break; case PWM_60_PERCENT: if (pwm_period_counter_ == 0 || pwm_period_counter_ == 1 || pwm_period_counter_ == 3) instance->on(); else instance->off(); if (++pwm_period_counter_ >= 5) pwm_period_counter_ = 0; break; case PWM_70_PERCENT: if (pwm_period_counter_ == 3 || pwm_period_counter_ == 6 || pwm_period_counter_ == 9) instance->off(); else instance->on(); if (++pwm_period_counter_ >= 10) pwm_period_counter_ = 0; break; case PWM_80_PERCENT: if (pwm_period_counter_ < 4) instance->on(); else instance->off(); if (++pwm_period_counter_ >= 5) pwm_period_counter_ = 0; break; case PWM_90_PERCENT: if (pwm_period_counter_ < 9) instance->on(); else instance->off(); if (++pwm_period_counter_ >= 10) pwm_period_counter_ = 0; break; case PWM_100_PERCENT: instance->on(); pwm_period_counter_ = 0; break; default: instance->off(); } }
24.021277
95
0.608725
solderdev
f13b47a006cdb1e6a82dc982ad4580ebb457e364
5,850
cc
C++
src/s3_driver.cc
h5s3/h5s3
abe0ac2e82f04f9f550ae3760fc312e9e37dc84b
[ "Apache-2.0" ]
18
2018-01-31T02:47:39.000Z
2021-03-13T15:17:45.000Z
src/s3_driver.cc
h5s3/h5s3
abe0ac2e82f04f9f550ae3760fc312e9e37dc84b
[ "Apache-2.0" ]
2
2017-12-03T08:05:40.000Z
2018-06-13T22:05:37.000Z
src/s3_driver.cc
h5s3/h5s3
abe0ac2e82f04f9f550ae3760fc312e9e37dc84b
[ "Apache-2.0" ]
null
null
null
#include <cassert> #include <regex> #include "h5s3/private/s3_driver.h" namespace h5s3::s3_driver { const char* s3_kv_store::name = "h5s3"; s3_kv_store::s3_kv_store(const std::string& host, bool use_tls, const std::string& bucket, const std::string& path, const std::string& access_key, const std::string& secret_key, const std::string& region, const std::size_t page_size) : m_host(host), m_use_tls(use_tls), m_bucket(bucket), m_path(path), m_notary(region, access_key, secret_key), m_allocated_pages(0), m_page_size(page_size) { try { std::string result = s3::get_object(m_notary, m_bucket, path + "/.meta", m_host, m_use_tls); std::regex metadata_regex("page_size=([0-9]+)\n" "allocated_pages=([0-9]+)\n" "invalid_pages=\\{(([0-9]+ )*[0-9]*)\\}\n"); std::smatch match; if (!std::regex_match(result, match, metadata_regex)) { std::stringstream s; s << "failed to parse metadata from .meta file:\n" << result; throw std::runtime_error(s.str()); } { std::size_t metadata_page_size; std::stringstream s(match[1].str()); s >> metadata_page_size; if (m_page_size != 0 && metadata_page_size != m_page_size) { std::stringstream s; s << "passed page size does not match existing page size: " << m_page_size << " != " << metadata_page_size; throw std::runtime_error(s.str()); } m_page_size = metadata_page_size; } { std::stringstream s(match[2].str()); s >> m_allocated_pages; } { std::stringstream s(match[3].str()); page::id page_id; while (s >> page_id) { m_invalid_pages.insert(page_id); } } } catch (const curl::http_error& e) { if (e.code != 404) { throw; } } } s3_kv_store s3_kv_store::from_params(const std::string_view& uri_view, unsigned int, // TODO: Use this? std::size_t page_size, const char* access_key, const char* secret_key, const char* region, const char* host, bool use_tls) { std::string uri(uri_view); std::regex url_regex("s3://(.+)/(.+)"); std::smatch match; if (!std::regex_match(uri, match, url_regex)) { throw std::runtime_error(uri); } std::string bucket = match[1].str(); std::string path = match[2].str(); // Trim trailing slashes. while (path.back() == '/') { path.pop_back(); } // TODO: Allow anonymous usage without either key. // TODO: Validate that these are valid keys if possible. if (!access_key) { throw std::runtime_error("Access Key is Required."); } if (!secret_key) { throw std::runtime_error("Secret Key is Required."); } if (!region) { region = "us-east-1"; } if (!page_size) { using utils::operator""_MB; page_size = 2_MB; } std::string host_string; if (!host) { host_string = s3::default_host; } else { host_string = host; } return {host, use_tls, bucket, path, access_key, secret_key, region, page_size}; } void s3_kv_store::max_page(page::id max_page) { for (page::id page_id = max_page + 1; page_id < m_allocated_pages; ++page_id) { m_invalid_pages.insert(page_id); } m_allocated_pages = max_page + 1; } void s3_kv_store::read(page::id page_id, utils::out_buffer& out) const { assert(out.size() == m_page_size); if (page_id > max_page() || m_invalid_pages.find(page_id) != m_invalid_pages.end()) { std::memset(out.data(), 0, m_page_size); } std::string keyname(m_path + "/" + std::to_string(page_id)); try { std::size_t size = s3::get_object(out, m_notary, m_bucket, keyname, m_host, m_use_tls); if (size != m_page_size) { throw std::runtime_error("page was smaller than the page_size"); } return; } catch (const curl::http_error& e) { if (e.code != 404) { throw; } } std::memset(out.data(), 0, m_page_size); } void s3_kv_store::write(page::id page_id, const std::string_view& data) { std::string keyname(m_path + "/" + std::to_string(page_id)); s3::set_object(m_notary, m_bucket, keyname, data, m_host, m_use_tls); m_allocated_pages = std::max(m_allocated_pages, page_id + 1); m_invalid_pages.erase(page_id); } void s3_kv_store::flush() { std::stringstream formatter; formatter << "page_size=" << m_page_size << '\n' << "allocated_pages" << m_allocated_pages << '\n' << "invalid_pages={"; for (page::id page_id : m_invalid_pages) { formatter << page_id << ','; } if (m_invalid_pages.size()) { // consume the trailing comma formatter.get(); } formatter << "}\n"; s3::set_object(m_notary, m_bucket, m_path + "/.meta", formatter.str(), m_host, m_use_tls); } } // namespace h5s3::s3_driver // declare storage for the static member m_class in this TU template<> H5FD_class_t h5s3::s3_driver::s3_driver::m_class{};
30.46875
90
0.524786
h5s3
f1402f69ee26471fd5e5f671470bf25e21306cbf
1,082
hpp
C++
arduino/libraries/LovyanGFX/src/LovyanGFX.hpp
Mchaney3/AXSResearch
6843b833a95010014bb3113ca59dda3b5e1c3663
[ "Unlicense" ]
null
null
null
arduino/libraries/LovyanGFX/src/LovyanGFX.hpp
Mchaney3/AXSResearch
6843b833a95010014bb3113ca59dda3b5e1c3663
[ "Unlicense" ]
null
null
null
arduino/libraries/LovyanGFX/src/LovyanGFX.hpp
Mchaney3/AXSResearch
6843b833a95010014bb3113ca59dda3b5e1c3663
[ "Unlicense" ]
null
null
null
/*----------------------------------------------------------------------------/ Lovyan GFX library - LCD graphics library . support platform: ESP32 (SPI/I2S) with Arduino/ESP-IDF ATSAMD51 (SPI) with Arduino Original Source: https://github.com/lovyan03/LovyanGFX/ Licence: [BSD](https://github.com/lovyan03/LovyanGFX/blob/master/license.txt) Author: [lovyan03](https://twitter.com/lovyan03) Contributors: [ciniml](https://github.com/ciniml) [mongonta0716](https://github.com/mongonta0716) [tobozo](https://github.com/tobozo) /----------------------------------------------------------------------------*/ #ifndef LOVYANGFX_HPP_ #define LOVYANGFX_HPP_ #ifdef setFont #undef setFont #endif #if __has_include("lgfx/v1_init.hpp") && ( defined ( LGFX_USE_V1 ) || !__has_include("lgfx/v0_init.hpp") ) #include "lgfx/v1_init.hpp" #if defined ( LGFX_AUTODETECT ) #include "LGFX_AUTODETECT.hpp" #endif #else // if defined ( LGFX_USE_V0 ) #if __has_include("lgfx/v0_init.hpp") #include "lgfx/v0_init.hpp" #endif #endif #endif
22.541667
106
0.601664
Mchaney3
f14c0c480f4ef7280d98c05f6d35414e04452e82
3,443
cpp
C++
src/lib/ecp.cpp
peterbygrave/libecpint
2d40bce92f229c9a477e618c6008c0622e241d48
[ "MIT" ]
1
2020-08-31T13:44:12.000Z
2020-08-31T13:44:12.000Z
src/lib/ecp.cpp
peterbygrave/libecpint
2d40bce92f229c9a477e618c6008c0622e241d48
[ "MIT" ]
null
null
null
src/lib/ecp.cpp
peterbygrave/libecpint
2d40bce92f229c9a477e618c6008c0622e241d48
[ "MIT" ]
2
2020-03-25T09:23:24.000Z
2020-08-31T14:29:29.000Z
/* * Copyright (c) 2017 Robert Shaw * This file is a part of Libecpint. * * 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 "ecp.hpp" #include <cmath> #include <iostream> #include <algorithm> namespace libecpint { // GaussianECP constructor and copy constructor GaussianECP::GaussianECP() : n(0), l(0), a(0), d(0) {} GaussianECP::GaussianECP(int _n, int _l, double _a, double _d) : n(_n-2), l(_l), a(_a), d(_d) {} GaussianECP::GaussianECP(const GaussianECP& other) : n(other.n), l(other.l), a(other.a), d(other.d) {} // class ECP ECP::ECP() : N(0), L(-1), nCore(0) { center_[0] = center_[1] = center_[2] = 0.0; } ECP::ECP(const double *_center) : N(0), L(-1), nCore(0) { center_[0] = _center[0]; center_[1] = _center[1]; center_[2] = _center[2]; } ECP::ECP(const ECP &other) { gaussians = other.gaussians; N = other.N; L = other.L; nCore = other.nCore; center_ = other.center_; } void ECP::addPrimitive(int n, int l, double a, double d, bool needSort) { GaussianECP newEcp(n, l, a, d); gaussians.push_back(newEcp); N++; L = l > L ? l : L; if (needSort) sort(); } void ECP::sort() { std::sort(gaussians.begin(), gaussians.end(), [&] (const GaussianECP& g1, const GaussianECP& g2) {return (g1.l < g2.l);}); } bool ECP::noType1() const { bool zero = true; for (auto& g : gaussians) if (g.l == L && fabs(g.d) > 1e-12) zero = false; return zero; } // Evaluate U_l(r), assuming that gaussians sorted by angular momentum double ECP::evaluate(double r, int l) { double value = 0.0; int am = 0; double r2 = r*r; for (int i = 0; i < N; i++) { if (gaussians[i].l == l) // Only evaluate if in correct shell value += pow(r, gaussians[i].n) * gaussians[i].d * exp(-gaussians[i].a * r2); } return value; } void ECP::setPos(double x, double y, double z) { center_[0] = x; center_[1] = y; center_[2] = z; } ECPBasis::ECPBasis() : N(0), maxL(-1) {} void ECPBasis::addECP(ECP &U, int atom) { basis.push_back(U); atomList.push_back(atom); N++; maxL = U.getL() > maxL ? U.getL() : maxL; } ECP& ECPBasis::getECP(int i) { return basis[i]; } int ECPBasis::getECPCore(int q) { int core = 0; auto it = core_electrons.find(q); if (it != core_electrons.end()) core = it->second; return core; } }
30.201754
103
0.637816
peterbygrave
f1550eb2c5d62e06ae8ab1c834700832abcaba7f
1,399
cpp
C++
Hard/Maximize Palindrome Length From Subsequences.cpp
hunt-s7/LeetCode-Problems
5235896710bff8a05985c45f261d3462e3b8bf2e
[ "MIT" ]
null
null
null
Hard/Maximize Palindrome Length From Subsequences.cpp
hunt-s7/LeetCode-Problems
5235896710bff8a05985c45f261d3462e3b8bf2e
[ "MIT" ]
null
null
null
Hard/Maximize Palindrome Length From Subsequences.cpp
hunt-s7/LeetCode-Problems
5235896710bff8a05985c45f261d3462e3b8bf2e
[ "MIT" ]
4
2020-11-30T04:38:58.000Z
2021-10-05T15:25:38.000Z
class Solution { public: int ans(string w1, string w2){ string s=w1+w2; string t=s; reverse(t.begin(),t.end()); int n=(int)s.size(); int dp[n+1][n+1]; memset(dp,0,sizeof(dp)); int f=0; for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(s[i-1]==t[j-1]){ dp[i][j]=1+dp[i-1][j-1]; } else{ dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } } return dp[n][n]; } int longestPalindrome(string w1, string w2) { int m=0,mr=0; vector<bool> v(26,0); for(int i=0;i<w1.size();i++){ if(v[w1[i]-'a']){ continue; } v[w1[i]-'a']=1; for(int j=w2.size()-1;j>=0;j--){ if(w1[i]==w2[j]){ if(mr>j){ break; } if(m>(w1.size()-i+1+j)){ break; } // v[i]=1; m=max(m,ans(w1.substr(i,w1.size()-i),w2.substr(0,j+1))); mr=j; break; } } } return m; } };
26.396226
77
0.2802
hunt-s7
f1560e367521bbc28fd25bdd19ec1abf439c67ae
779
hpp
C++
include/lol/def/LolGameSettingsLoginSession.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
1
2020-07-22T11:14:55.000Z
2020-07-22T11:14:55.000Z
include/lol/def/LolGameSettingsLoginSession.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
null
null
null
include/lol/def/LolGameSettingsLoginSession.hpp
Maufeat/LeagueAPI
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
[ "BSD-3-Clause" ]
4
2018-12-01T22:48:21.000Z
2020-07-22T11:14:56.000Z
#pragma once #include "../base_def.hpp" #include "LolGameSettingsLoginSessionStates.hpp" namespace lol { struct LolGameSettingsLoginSession { LolGameSettingsLoginSessionStates state; uint64_t summonerId; uint64_t accountId; json gasToken; }; inline void to_json(json& j, const LolGameSettingsLoginSession& v) { j["state"] = v.state; j["summonerId"] = v.summonerId; j["accountId"] = v.accountId; j["gasToken"] = v.gasToken; } inline void from_json(const json& j, LolGameSettingsLoginSession& v) { v.state = j.at("state").get<LolGameSettingsLoginSessionStates>(); v.summonerId = j.at("summonerId").get<uint64_t>(); v.accountId = j.at("accountId").get<uint64_t>(); v.gasToken = j.at("gasToken").get<json>(); } }
33.869565
72
0.680359
Maufeat
f15704af65edf9cb9856d1dc391a1b14924bc61f
3,808
cc
C++
mds/apfPM.cc
Thomas-Ulrich/core
1c7bc7ff994c3570ab22b96d37be0c4c993e5940
[ "BSD-3-Clause" ]
138
2015-01-05T15:50:20.000Z
2022-02-25T01:09:58.000Z
mds/apfPM.cc
Thomas-Ulrich/core
1c7bc7ff994c3570ab22b96d37be0c4c993e5940
[ "BSD-3-Clause" ]
337
2015-08-07T18:24:58.000Z
2022-03-31T14:39:03.000Z
mds/apfPM.cc
Thomas-Ulrich/core
1c7bc7ff994c3570ab22b96d37be0c4c993e5940
[ "BSD-3-Clause" ]
70
2015-01-17T00:58:41.000Z
2022-02-13T04:58:20.000Z
/****************************************************************************** Copyright 2014 Scientific Computation Research Center, Rensselaer Polytechnic Institute. All rights reserved. This work is open source software, licensed under the terms of the BSD license as described in the LICENSE file in the top-level directory. *******************************************************************************/ #include <PCU.h> #include "apfPM.h" #include <apf.h> #include <pcu_util.h> namespace apf { // the following three functions are for exclusive use by pumi_mesh_loadAll // the last arg "owner" is used only if a new pmodel entity is created PME* getPMent(PM& ps, apf::Parts const& pids, int owner) { APF_ITERATE(PM, ps, it) { bool equal=true; APF_ITERATE(Parts,pids,pit) { bool found=false; for (size_t i = 0; i < (*it).ids.size(); ++i) if ((*it).ids[i]==*pit) found=true; if (!found) { equal=false; break; } } if (equal) { PME& p = const_cast<PME&>(*it); ++(p.refs); return &p; } } static int pme_id=ps.size(); PME *pme = new PME(pme_id++, pids, owner); ps.insert(*pme); ++(pme->refs); return pme; } // the partition classification of mesh entities has to be updated separately void deletePM(PM& ps) { APF_ITERATE(PM, ps, it) ps.erase(*it); } void deletePMent(PM& ps, PME* p) { ps.erase(*p); } typedef std::map<int,size_t> CountMap; PME* getPME(PM& ps, apf::Parts const& ids) { PME const& cp = *(ps.insert(PME(ps.size(), ids, -1)).first); /* always annoyed by this flaw in std::set */ PME& p = const_cast<PME&>(cp); ++(p.refs); return &p; } void putPME(PM& ps, PME* p) { --(p->refs); if (!(p->refs)) ps.erase(*p); } static void getAdjacentParts(apf::Mesh* m, PM& ps, apf::Parts& ids) { APF_ITERATE(PM, ps, it) { std::vector<int> const& rp = it->ids; ids.insert(rp.begin(), rp.end()); } ids.erase(m->getId()); } static void getCountMap(apf::Mesh* m, PM& ps, CountMap& mp) { apf::Parts peers; size_t n; getAdjacentParts(m, ps, peers); n = m->count(m->getDimension()); PCU_Comm_Begin(); APF_ITERATE(apf::Parts, peers, it) PCU_COMM_PACK(*it, n); PCU_Comm_Send(); mp[m->getId()] = n; while (PCU_Comm_Listen()) { PCU_COMM_UNPACK(n); mp[PCU_Comm_Sender()] = n; } } static void setOwners(PM& ps, CountMap& mp) { APF_ITERATE(PM, ps, it) { PME const& cp = *it; PME& p = const_cast<PME&>(cp); /* again with the silly */ std::vector<int> const& ids = p.ids; PCU_ALWAYS_ASSERT(ids.size()); int owner = ids[0]; // PCU_ALWAYS_ASSERT(mp.count(owner)); // seol - this doesn't work for ghost copy for (size_t i = 1; i < ids.size(); ++i) { // PCU_ALWAYS_ASSERT(mp.count(ids[i])); // seol - this doesn't work for ghost copy if (mp[ids[i]] < mp[owner]) owner = ids[i]; } p.owner = owner; } } void updateOwners(apf::Mesh* m, PM& ps) { CountMap mp; getCountMap(m, ps, mp); setOwners(ps, mp); } void remapPM(PM& pm, int (*map)(int, void*), void* user) { APF_ITERATE(PM, pm, it) { PME const& cp = *it; PME& p = const_cast<PME&>(cp); /* yep */ p.owner = map(p.owner, user); std::vector<int>& ids = p.ids; /* note: we can only do this because operator<(std::vector<T>...) uses lexicographical comparison, and so for vectors A and B, A < B does not change if all the elements of A and B are multiplied or divided by a constant factor, so long as the resulting ids are also unique. any map which changes the results of lexicographical comparison breaks the ordering of PME's in the PM. */ for (size_t i = 0; i < ids.size(); ++i) ids[i] = map(ids[i], user); } } }
24.254777
88
0.581408
Thomas-Ulrich
f160b5fd8f6455f5ca65f73e02002c2a311c3f84
6,406
cpp
C++
Source/SkyEngine/src/Components/Transform.cpp
SilangQuan/PixelLab
06c5c1fcf6b07c859179f5925dc642f43b38c676
[ "MIT" ]
null
null
null
Source/SkyEngine/src/Components/Transform.cpp
SilangQuan/PixelLab
06c5c1fcf6b07c859179f5925dc642f43b38c676
[ "MIT" ]
null
null
null
Source/SkyEngine/src/Components/Transform.cpp
SilangQuan/PixelLab
06c5c1fcf6b07c859179f5925dc642f43b38c676
[ "MIT" ]
null
null
null
#include "Components/Transform.h" #include "Log/Log.h" Transform::Transform() { isDirty = true; position = Vector3::zero; rotation = Quaternion::identity; scale = Vector3::one; gameObject = NULL; } Transform::Transform(const Vector3& _position, const Quaternion& _rotation, const Vector3& _scale) :position(_position),rotation(_rotation), scale(_scale), isDirty(true) { gameObject = NULL; } Transform::~Transform() { } void Transform::AttachToGameObject(GameObject* _gameObject) { gameObject = _gameObject; } GameObject* Transform::GetGameObject() { return gameObject; } Matrix4x4 Transform::GetLocalToWorldMatrix() { if (isDirty) { Matrix4x4 transMatrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, position.x, position.y, position.z, 1); Matrix4x4 scaleMatrix(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1); localToWorldMatrix = transMatrix * rotation.GetRotMatrix() * scaleMatrix; isDirty = false; } return localToWorldMatrix; } void Transform::Translate(const Vector3 &delta) { position.x += delta.x; position.y += delta.y; position.z += delta.z; isDirty = true; /* Matrix4x4 mInv(1, 0, 0, -delta.x, 0, 1, 0, -delta.y, 0, 0, 1, -delta.z, 0, 0, 0, 1);*/ } void Transform::RotateAxis(Vector3 axis, float _rotation) { rotation = rotation * Quaternion(0.01f, 0.02f, 0, 1); isDirty = true; } void Transform::Rotate(float xRot, float yRot, float zRot) { rotation = rotation * Quaternion::Euler(xRot, yRot, zRot); isDirty = true; } Vector3 Transform::GetForward() { return rotation * Vector3::forward; } Vector3 Transform::GetRight() { return rotation * Vector3::right; } Vector3 Transform::GetUp() { return rotation * Vector3::up; } void Transform::SetDirty(bool inIsDirty) { isDirty = inIsDirty; } void MatrixToQuaternion(const Matrix3& kRot, Quaternion& q) { // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes // article "Quaternionf Calculus and Fast Animation". float fTrace = kRot.Get(0, 0) + kRot.Get(1, 1) + kRot.Get(2, 2); float fRoot; if (fTrace > 0.0f) { // |w| > 1/2, may as well choose w > 1/2 fRoot = std::sqrt(fTrace + 1.0f); // 2w q.w = 0.5f * fRoot; fRoot = 0.5f / fRoot; // 1/(4w) q.x = (kRot.Get(2, 1) - kRot.Get(1, 2)) * fRoot; q.y = (kRot.Get(0, 2) - kRot.Get(2, 0)) * fRoot; q.z = (kRot.Get(1, 0) - kRot.Get(0, 1)) * fRoot; } else { // |w| <= 1/2 int s_iNext[3] = { 1, 2, 0 }; int i = 0; if (kRot.Get(1, 1) > kRot.Get(0, 0)) i = 1; if (kRot.Get(2, 2) > kRot.Get(i, i)) i = 2; int j = s_iNext[i]; int k = s_iNext[j]; fRoot = std::sqrt(kRot.Get(i, i) - kRot.Get(j, j) - kRot.Get(k, k) + 1.0f); float* apkQuat[3] = { &q.x, &q.y, &q.z }; //Assert(fRoot >= Vector3f::epsilon); *apkQuat[i] = 0.5f * fRoot; fRoot = 0.5f / fRoot; q.w = (kRot.Get(k, j) - kRot.Get(j, k)) * fRoot; *apkQuat[j] = (kRot.Get(j, i) + kRot.Get(i, j)) * fRoot; *apkQuat[k] = (kRot.Get(k, i) + kRot.Get(i, k)) * fRoot; } q = Quaternion::Normalize(q); } bool LookRotationToQuaternion(const Vector3& viewVec, const Vector3& upVec, Quaternion* res) { Matrix3 m; if (!Matrix3::LookRotationToMatrix(viewVec, upVec, &m)) return false; MatrixToQuaternion(m, *res); return true; } void Transform :: LookAt(const Vector3& targetPosition, const Vector3& worldUp) { Vector3 forward = targetPosition - position; Quaternion q = Quaternion::identity; if (LookRotationToQuaternion(forward, worldUp, &q)) { rotation = q; isDirty = true; } else { //float mag = forward.magnitude(); //if (mag > Mathf::EPSILON) //{ // Matrix3 m; // m.SetFromToRotation(Vector3::zAxis, forward / mag); // MatrixToQuaternion(m, q); // rotation = q; // isDirty = true; //} } } Matrix4x4 Transform::FPSView(const Vector3& eye, Quaternion rotation) { Matrix4x4 rotMatrix = rotation.GetRotMatrix().transpose(); Vector3 x(rotMatrix[0], rotMatrix[4], rotMatrix[8]); Vector3 y(rotMatrix[1], rotMatrix[5], rotMatrix[9]); Vector3 z(-rotMatrix[2], -rotMatrix[6], -rotMatrix[10]); Matrix4x4 result; result[0] = x.x; result[4] = x.y; result[8] = x.z; result[12] = -Vector3::Dot(x, eye); result[1] = y.x; result[5] = y.y; result[9] = y.z; result[13] = -Vector3::Dot(y, eye); result[2] = z.x; result[6] = z.y; result[10] = z.z; result[14] = -Vector3::Dot(z, eye); result[3] = result[7] = result[11] = 0.0f; result[15] = 1.0f; return result; } Matrix4x4 Transform::Perspective(float fovy, float aspect, float zNear, float zFar) { float tanHalfFovy = tan(Mathf::Deg2Rad * fovy / 2); Matrix4x4 result(0.0f); result[0 * 4 + 0] = 1.0f / (aspect * tanHalfFovy); result[1 * 4 + 1] = 1.0f / (tanHalfFovy); result[2 * 4 + 3] = -1.0f; result[2 * 4 + 2] = -(zFar + zNear) / (zFar - zNear); result[3 * 4 + 2] = -(2.0f * zFar * zNear) / (zFar - zNear); return result; } Matrix4x4 Transform::Frustum(float l, float r, float b, float t, float zNear, float zFar) { Matrix4x4 result(0.0f); result[0] = 2 * zNear / (r - l); result[8] = (r + l) / (r - l); result[5] = 2 * zNear / (t - b); result[9] = (t + b) / (t - b); result[10] = -(zFar + zNear) / (zFar - zNear); result[14] = -(2 * zFar * zNear) / (zFar - zNear); result[11] = -1; result[15] = 0; return result; } Matrix4x4 Transform::OrthoFrustum(float l, float r, float b, float t, float zNear, float zFar) { Matrix4x4 result(0.0f); result[0] = 2 / (r - l); result[5] = 2 / (t - b); result[10] = -2 / (zFar - zNear); result[15] = 1; //result[12] = -(r + l) / (r - l); //result[13] = -(t + b) / (t - b); result[14] = -(zFar + zNear) / (zFar - zNear); return result; } Vector3 Transform::TranslateToNDC(const Vector4& clipVector) { float inveW = 1.0f / clipVector.w; return Vector3(clipVector.x * inveW, clipVector.y * inveW, clipVector.z * inveW); } void Transform::TranslateToScreenCoord(const int screenWidth, const int screenHeight, Vector3& ndcCoord) { int w = screenWidth; int h = screenHeight; ndcCoord.x = 0.5f * w + 0.5f *ndcCoord.x * w; ndcCoord.y = 0.5f * h + 0.5f *ndcCoord.y * h; } void Transform::Scale(const Vector3 &_scale) { scale = _scale; isDirty = true; } /* int Transform::CheckCvv(const Vector3& vec) { float w = v->w; int check = 0; if (v->z < 0.0f) check |= 1; if (v->z > w) check |= 2; if (v->x < -w) check |= 4; if (v->x > w) check |= 8; if (v->y < -w) check |= 16; if (v->y > w) check |= 32; return check; } */
22.320557
104
0.622697
SilangQuan
f1612d8dc9bb9598c66fb44659837df1b056c88a
17,620
hpp
C++
src/nark/fstring.hpp
rockeet/nark-bone
11263ff5a192c85e4a2776aac1096d01138483d2
[ "BSD-3-Clause" ]
18
2015-02-12T04:41:22.000Z
2018-08-22T07:44:13.000Z
src/nark/fstring.hpp
rockeet/nark-bone
11263ff5a192c85e4a2776aac1096d01138483d2
[ "BSD-3-Clause" ]
null
null
null
src/nark/fstring.hpp
rockeet/nark-bone
11263ff5a192c85e4a2776aac1096d01138483d2
[ "BSD-3-Clause" ]
13
2015-05-24T12:24:46.000Z
2021-01-05T10:59:40.000Z
#ifndef __nark_fstring_hpp__ #define __nark_fstring_hpp__ #include <assert.h> #include <stddef.h> #include <string.h> #include <iterator> #include <string> #include <iosfwd> #include <utility> #include <algorithm> #include <string.h> #include "config.hpp" #include "stdtypes.hpp" #include "util/throw.hpp" #include "bits_rotate.hpp" //#include <boost/static_assert.hpp> #include <boost/utility/enable_if.hpp> namespace nark { #if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__clang__) #define HSM_FORCE_INLINE __attribute__((always_inline)) #elif defined(_MSC_VER) #define HSM_FORCE_INLINE __forceinline #else #define HSM_FORCE_INLINE inline #endif // Why name it SP_ALIGN? It is: String Pool/Pointer Align // // to disable align, define SP_ALIGN as 0 // otherwise, it will guess and use the best alignment #ifdef SP_ALIGN #if SP_ALIGN == 0 #undef SP_ALIGN #define SP_ALIGN 1 #endif #elif defined(NARK_WORD_BITS) #if 64 == NARK_WORD_BITS #define SP_ALIGN 8 #elif 32 == NARK_WORD_BITS #define SP_ALIGN 4 #else #error NARK_WORD_BITS is invalid #endif #else #error NARK_WORD_BITS is not defined #endif #if SP_ALIGN == 4 // typedef uint32_t align_type; typedef unsigned align_type; typedef size_t HSM_HashTp; #elif SP_ALIGN == 8 // typedef uint64_t align_type; typedef unsigned long long align_type; typedef unsigned long long HSM_HashTp; #elif SP_ALIGN == 1 typedef unsigned char align_type; typedef size_t HSM_HashTp; #else #error "SP_ALIGN defined but is not 0, 1, 4 or 8" #endif #if SP_ALIGN == 4 && UINT_MAX != 0xFFFFFFFF #error "sizeof(unsigned) must be 4" #elif SP_ALIGN == 8 && ULLONG_MAX != 0xFFFFFFFFFFFFFFFFull #error "sizeof(unsigned long long) must be 8" #endif BOOST_STATIC_ASSERT(sizeof(align_type) == SP_ALIGN); #if SP_ALIGN == 1 #define LOAD_OFFSET(x) size_t(x) #define SAVE_OFFSET(x) LinkTp(x) #define IF_SP_ALIGN(Then, Else) Else #else // on 64 bit system, make it to support larger strpool, up to 8*4G = 32G #define LOAD_OFFSET(x) (size_t(x) * SP_ALIGN) #define SAVE_OFFSET(x) LinkTp((x) / SP_ALIGN) #define IF_SP_ALIGN(Then, Else) Then #endif inline size_t nark_fstrlen(const char* s) { return strlen(s); } inline size_t nark_fstrlen(const uint16_t* s) { size_t n = 0; while (s[n]) ++n; return n; } #ifdef _MSC_VER NARK_DLL_EXPORT char* nark_fstrstr(const char* haystack, size_t haystack_len , const char* needle , size_t needle_len); #else inline char* nark_fstrstr(const char* haystack, size_t haystack_len , const char* needle , size_t needle_len) { return (char*)memmem(haystack, haystack_len, needle, needle_len); } #endif NARK_DLL_EXPORT uint16_t* nark_fstrstr(const uint16_t* haystack, size_t haystack_len , const uint16_t* needle , size_t needle_len); template<class Char> struct nark_get_uchar_type; template<>struct nark_get_uchar_type<char>{typedef unsigned char type;}; template<>struct nark_get_uchar_type<uint16_t>{typedef uint16_t type;}; // Fast String: shallow copy, simple, just has char* and length // May be short name of: Febird String template<class Char> struct basic_fstring { // BOOST_STATIC_ASSERT(sizeof(Char) <= 2); typedef std::basic_string<Char> std_string; const Char* p; ptrdiff_t n; basic_fstring() : p(NULL), n(0) {} basic_fstring(const std_string& x) : p(x.data()), n(x.size()) {} #ifdef NDEBUG // let compiler compute strlen(string literal) at compilation time basic_fstring(const Char* x) : p(x), n(nark_fstrlen(x)) {} #else basic_fstring(const Char* x) { assert(NULL != x); p = x; n = nark_fstrlen(x); } #endif basic_fstring(const Char* x, ptrdiff_t l) : p(x), n(l ) { assert(l >= 0); } basic_fstring(const Char* x, const Char* y) : p(x), n(y-x) { assert(y >= x); } #define fstring_enable_if_same_size(C) typename boost::enable_if_c<sizeof(C)==sizeof(Char)>::type* = NULL template<class C> basic_fstring(const C* x, fstring_enable_if_same_size(C)) { assert(NULL != x); p = (const Char*)x; n = nark_fstrlen((const Char*)x); } template<class C> basic_fstring(const C* x, ptrdiff_t l, fstring_enable_if_same_size(C)) : p((const Char*)x), n(l ) { assert(l >= 0); } template<class C> basic_fstring(const C* x, const C* y, fstring_enable_if_same_size(C)) : p((const Char*)x), n(y-x) { assert(y >= x); } #undef fstring_enable_if_same_size basic_fstring(const std::pair<Char*, Char*>& rng) : p(rng.first), n(rng.second - rng.first) { assert(n >= 0); } basic_fstring(const std::pair<const Char*, const Char*>& rng) : p(rng.first), n(rng.second - rng.first) { assert(n >= 0); } template<class CharVec> basic_fstring(const CharVec& chvec, typename CharVec::const_iterator** =NULL) { BOOST_STATIC_ASSERT(sizeof(*chvec.begin()) == sizeof(Char)); p = (const Char*)&*chvec.begin(); n = chvec.size(); #if !defined(NDEBUG) && 0 if (chvec.size() > 1) { assert(&chvec[0]+1 == &chvec[1]); assert(&chvec[0]+n-1 == &chvec[n-1]); } #endif } const std::pair<const Char*, const Char*> range() const { return std::make_pair(p, p+n); } typedef ptrdiff_t difference_type; typedef size_t size_type; typedef const Char value_type; typedef const Char &reference, &const_reference; typedef const Char *iterator, *const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator, const_reverse_iterator; typedef typename nark_get_uchar_type<Char>::type uc_t; iterator begin() const { return p; } iterator cbegin() const { return p; } iterator end() const { return p + n; } iterator cend() const { return p + n; } reverse_iterator rbegin() const { return reverse_iterator(p + n); } reverse_iterator crbegin() const { return reverse_iterator(p + n); } reverse_iterator rend() const { return reverse_iterator(p); } reverse_iterator crend() const { return reverse_iterator(p); } uc_t ende(ptrdiff_t off) const { assert(off <= n); assert(off >= 1); return p[n-off]; } std_string str() const { assert(0==n || (p && n) ); return std_string(p, n); } const Char* c_str() const { assert(p && '\0' == p[n]); return p; } const Char* data() const { return p; } const uc_t* udata() const { return (const uc_t*)p; } size_t size() const { return n; } int ilen() const { return (int)n; } // for printf: "%.*s" uc_t operator[](ptrdiff_t i)const{assert(i>=0);assert(i<n);assert(p);return p[i];} uc_t uch(ptrdiff_t i)const{assert(i>=0);assert(i<n);assert(p);return p[i];} bool empty() const { return 0 == n; } void chomp(); void trim(); basic_fstring substr(size_t pos, size_t len) const { assert(pos <= size()); assert(len <= size()); // if (pos > size()) { // similar with std::basic_string::substr // THROW_STD(out_of_range, "size()=%zd pos=%zd", size(), pos); // } if (pos + len > size()) len = size() - pos; return basic_fstring(p+pos, len); } basic_fstring substr(size_t pos) const { assert(pos <= size()); // if (pos > size()) { // similar with std::basic_string::substr // THROW_STD(out_of_range, "size()=%zd pos=%zd", size(), pos); // } return basic_fstring(p+pos, n-pos); } basic_fstring substrBegEnd(size_t Beg, size_t End) const { assert(Beg <= End); assert(End <= size()); // if (End > size()) { // similar with std::basic_string::substr // THROW_STD(out_of_range, "size()=%zd End=%zd", size(), End); // } return basic_fstring(p+Beg, End-Beg); } bool match_at(ptrdiff_t pos, Char ch) const { assert(pos >= 0); assert(pos <= n); return pos < n && p[pos] == ch; } bool match_at(ptrdiff_t pos, basic_fstring needle) const { assert(pos >= 0); assert(pos <= n); if (pos + needle.n > n) return false; return memcmp(p + pos, needle.p, sizeof(Char) * needle.size()) == 0; } const Char* strstr(basic_fstring needle) const { assert(needle.n > 0); return this->strstr(0, needle); } const Char* strstr(ptrdiff_t pos, basic_fstring needle) const { assert(pos >= 0); assert(pos <= n); assert(needle.n > 0); if (pos + needle.n > n) return NULL; return nark_fstrstr(p, n, needle.p, needle.n); } bool startsWith(basic_fstring x) const { assert(x.n > 0); if (x.n > n) return false; return memcmp(p, x.p, sizeof(Char)*x.n) == 0; } bool endsWith(basic_fstring x) const { assert(x.n > 0); if (x.n > n) return false; return memcmp(p+n - x.n, x.p, sizeof(Char)*x.n) == 0; } size_t commonPrefixLen(basic_fstring y) const { size_t minlen = n < y.n ? n : y.n; for (size_t i = 0; i < minlen; ++i) if (p[i] != y.p[i]) return i; return minlen; } template<class Vec> size_t split(const Char delim, Vec* F, size_t max_fields = ~size_t(0)) const { // assert(n >= 0); F->resize(0); if (' ' == delim) { // same as awk, skip first blank field, and skip dup blanks const Char *col = p, *End = p + n; while (col < End && isspace((unsigned char)(*col))) ++col; // skip first blank field while (col < End && F->size()+1 < max_fields) { const Char* next = col; while (next < End && !isspace((unsigned char)(*next))) ++next; F->push_back(typename Vec::value_type(col, next)); while (next < End && isspace(*next)) ++next; // skip blanks col = next; } if (col < End) F->push_back(typename Vec::value_type(col, End)); } else { const Char *col = p, *End = p + n; while (col <= End && F->size()+1 < max_fields) { const Char* next = col; while (next < End && delim != *next) ++next; F->push_back(typename Vec::value_type(col, next)); col = next + 1; } if (col <= End) F->push_back(typename Vec::value_type(col, End)); } return F->size(); } /// split into fields template<class Vec> size_t split(const Char* delims, Vec* F, size_t max_fields = ~size_t(0)) { assert(n >= 0); size_t dlen = nark_fstrlen(delims); if (0 == dlen) // empty delims redirect to blank delim return split(' ', F); if (1 == dlen) return split(delims[0], F); F->resize(0); const Char *col = p, *End = p + n; while (col <= End && F->size()+1 < max_fields) { const Char* next = nark_fstrstr(col, End-col, delims, dlen); if (NULL == next) next = End; F->push_back(typename Vec::value_type(col, next)); col = next + dlen; } if (col <= End) F->push_back(typename Vec::value_type(col, End)); return F->size(); } }; template<class DataIO, class Char> void DataIO_saveObject(DataIO& dio, basic_fstring<Char> s) { dio << typename DataIO::my_var_uint64_t(s.n); dio.ensureWrite(s.p, sizeof(Char) * s.n); } typedef basic_fstring<char> fstring; typedef basic_fstring<uint16_t> fstring16; template<class Char> struct char_to_fstring; template<> struct char_to_fstring<char> { typedef fstring type; }; template<> struct char_to_fstring<unsigned char> { typedef fstring type; }; template<> struct char_to_fstring<uint16_t> { typedef fstring16 type; }; NARK_DLL_EXPORT std::string operator+(fstring x, fstring y); inline std::string operator+(fstring x, const char* y) {return x+fstring(y);} inline std::string operator+(const char* x, fstring y) {return fstring(x)+y;} #if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L inline std::string operator+(std::string&& x, fstring y) { return x.append( y.p, y.n); } inline std::string operator+(fstring x, std::string&& y) { return y.insert(0, x.p, x.n); } #endif NARK_DLL_EXPORT bool operator==(fstring x, fstring y); NARK_DLL_EXPORT bool operator!=(fstring x, fstring y); NARK_DLL_EXPORT bool operator<(fstring x, fstring y); NARK_DLL_EXPORT bool operator>(fstring x, fstring y); NARK_DLL_EXPORT bool operator<=(fstring x, fstring y); NARK_DLL_EXPORT bool operator>=(fstring x, fstring y); NARK_DLL_EXPORT std::ostream& operator<<(std::ostream& os, fstring s); // fstring16 NARK_DLL_EXPORT bool operator==(fstring16 x, fstring16 y); NARK_DLL_EXPORT bool operator!=(fstring16 x, fstring16 y); NARK_DLL_EXPORT bool operator<(fstring16 x, fstring16 y); NARK_DLL_EXPORT bool operator>(fstring16 x, fstring16 y); NARK_DLL_EXPORT bool operator<=(fstring16 x, fstring16 y); NARK_DLL_EXPORT bool operator>=(fstring16 x, fstring16 y); //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// struct fstring_func { // 3-way compare class prefix_compare3 { ptrdiff_t plen; public: int operator()(fstring x, fstring y) const { using namespace std; const ptrdiff_t lmin = min(x.n, y.n); const ptrdiff_t clen = min(lmin, plen); for (ptrdiff_t i = 0; i < clen; ++i) if (x.p[i] != y.p[i]) // char diff doesn't exceed INT_MAX return (unsigned char)x.p[i] - (unsigned char)y.p[i]; if (plen < lmin) return 0; // all prefix are same else return int(x.n - y.n); // length diff couldn't exceed INT_MAX } prefix_compare3(ptrdiff_t prelen) : plen(prelen) {} }; // 3-way compare class compare3 { public: int operator()(fstring x, fstring y) const { using namespace std; int ret = memcmp(x.p, y.p, min(x.n, y.n)); if (ret != 0) return ret; return int(x.n - y.n); // length diff couldn't exceed INT_MAX } }; struct less_unalign { bool operator()(const fstring& x, const fstring& y) const { int ret = memcmp(x.p, y.p, x.n < y.n ? x.n : y.n); if (ret != 0) return ret < 0; else return x.n < y.n; } }; struct hash_unalign { HSM_FORCE_INLINE HSM_HashTp operator()(const fstring k) const { HSM_HashTp h = 2134173 + k.n * 31; for (ptrdiff_t i = 0; i < k.n; ++i) h = BitsRotateLeft(h, 5) + h + k.p[i]; return h; } }; struct equal_unalign { bool operator()(const fstring x, const fstring y) const { return x.n == y.n && memcmp(x.p, y.p, x.n) == 0; } }; static size_t align_to(size_t x) { return (x + SP_ALIGN-1) & ~(intptr_t)(SP_ALIGN-1); } #if SP_ALIGN != 1 struct less_align { HSM_FORCE_INLINE bool operator()(const fstring& x, const fstring& y) const { ptrdiff_t n = x.n < y.n ? x.n : y.n; ptrdiff_t c = n - (SP_ALIGN-1); ptrdiff_t i = 0; for (; i < c; i += SP_ALIGN) if (*reinterpret_cast<const align_type*>(x.p + i) != *reinterpret_cast<const align_type*>(y.p + i)) break; for (; i < n; ++i) if (x.p[i] != y.p[i]) return (unsigned char)x.p[i] < (unsigned char)y.p[i]; return x.n < y.n; } }; struct Less { HSM_FORCE_INLINE bool operator()(const fstring& x, const fstring& y) const { if (((intptr_t(x.p) | intptr_t(y.p)) & (SP_ALIGN-1)) == 0) return less_align()(x, y); else return less_unalign()(x, y); } }; struct hash_align { HSM_FORCE_INLINE HSM_HashTp operator()(const fstring k) const { BOOST_STATIC_ASSERT(SP_ALIGN <= sizeof(HSM_HashTp)); HSM_HashTp h = 2134173 + k.n * 31; ptrdiff_t c = k.n - (SP_ALIGN-1); ptrdiff_t i = 0; for (; i < c; i += SP_ALIGN) h = BitsRotateLeft(h, 5) + h + *reinterpret_cast<const align_type*>(k.p + i); for (; i < k.n; ++i) h = BitsRotateLeft(h, 5) + h + k.p[i]; return h; } }; // make it easier to enable or disable X86 judgment #if 1 && ( \ defined(__i386__) || defined(__i386) || defined(_M_IX86) || \ defined(__X86__) || defined(_X86_) || \ defined(__THW_INTEL__) || defined(__I86__) || \ defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) \ ) // don't care pointer align, overhead of x86 align fault is slightly enough typedef hash_align hash; #else struct hash { // align or not align HSM_FORCE_INLINE HSM_HashTp operator()(const fstring k) const { HSM_HashTp h = 2134173 + k.n * 31; ptrdiff_t c = k.n - (SP_ALIGN-1); ptrdiff_t i = 0; if ((intptr_t(k.p) & (SP_ALIGN-1)) == 0) { // aligned for (; i < c; i += SP_ALIGN) h = BitsRotateLeft(h, 5) + h + *reinterpret_cast<const align_type*>(k.p + i); } else { // not aligned for (; i < c; i += SP_ALIGN) { align_type word; // compiler could generate unaligned load instruction // for fixed size(SP_ALIGN) object, word may be a register memcpy(&word, k.p + i, SP_ALIGN); h = BitsRotateLeft(h, 5) + h + word; } } for (; i < k.n; ++i) h = BitsRotateLeft(h, 5) + h + k.p[i]; return h; } }; #endif // X86 struct equal_align { HSM_FORCE_INLINE bool operator()(const fstring x, const fstring y) const { if (nark_unlikely(x.n != y.n)) return false; ptrdiff_t c = x.n - (SP_ALIGN-1); ptrdiff_t i = 0; for (; i < c; i += SP_ALIGN) if (*reinterpret_cast<const align_type*>(x.p + i) != *reinterpret_cast<const align_type*>(y.p + i)) return false; for (; i < x.n; ++i) if (x.p[i] != y.p[i]) return false; return true; } }; struct equal { // align or not align HSM_FORCE_INLINE bool operator()(const fstring x, const fstring y) const { if (nark_unlikely(x.n != y.n)) return false; if (((intptr_t(x.p) | intptr_t(y.p)) & (SP_ALIGN-1)) == 0) { ptrdiff_t c = x.n - (SP_ALIGN-1); ptrdiff_t i = 0; for (; i < c; i += SP_ALIGN) if (*reinterpret_cast<const align_type*>(x.p + i) != *reinterpret_cast<const align_type*>(y.p + i)) return false; for (; i < x.n; ++i) if (x.p[i] != y.p[i]) return false; return true; } else return memcmp(x.p, y.p, x.n) == 0; } }; #else typedef less_unalign less_align; typedef hash_unalign hash_align; typedef equal_unalign equal_align; typedef less_unalign Less; typedef hash_unalign hash; typedef equal_unalign equal; #endif // SP_ALIGN }; NARK_DLL_EXPORT extern unsigned char gtab_ascii_tolower[256]; NARK_DLL_EXPORT extern unsigned char gtab_ascii_tolower[256]; } // namespace nark #endif // __nark_fstring_hpp__
31.862568
153
0.651305
rockeet
f162a01105bc84fa0207b807e0fcaf2c1502226c
4,019
cpp
C++
297-serialize-and-deserialize-binary-tree/serialize-and-deserialize-binary-tree.cpp
nagestx/MyLeetCode
ef2a98b48485a0cebc442bbbbdb2690ba51484e1
[ "MIT" ]
3
2018-12-15T14:07:12.000Z
2020-07-19T23:18:09.000Z
297-serialize-and-deserialize-binary-tree/serialize-and-deserialize-binary-tree.cpp
yangyangu/MyLeetCode
ef2a98b48485a0cebc442bbbbdb2690ba51484e1
[ "MIT" ]
null
null
null
297-serialize-and-deserialize-binary-tree/serialize-and-deserialize-binary-tree.cpp
yangyangu/MyLeetCode
ef2a98b48485a0cebc442bbbbdb2690ba51484e1
[ "MIT" ]
null
null
null
// Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. // // Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. // // Example:  // // // You may serialize the following tree: // // 1 // / \ // 2 3 // / \ // 4 5 // // as "[1,2,3,null,null,4,5]" // // // Clarification: The above format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. // // Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless. // class Codec { private: int str2int(string str){ int res = 0; if(str[0] == '-'){ for(int i = 1; i < str.size(); ++ i){ res = 10 * res + (str[i] - '0'); } res *= -1; }else{ for(int i = 0; i < str.size(); ++ i){ res = 10 * res + (str[i] - '0'); } } return res; } vector<string> split(string &str, char ch){ vector<string> res; string tmp; for(auto &s: str){ if(s != ch){ tmp += s; }else{ res.push_back(tmp); tmp.clear(); } } if(!tmp.empty()) res.push_back(tmp); return res; } public: // Encodes a tree to a single string. string serialize(TreeNode* root) { string null = "null"; if(!root) return "[" + null + "]"; string res; vector<string> r; queue<TreeNode*> que; que.push(root); while(!que.empty()){ queue<TreeNode*> p; while(!que.empty()){ auto top = que.front(); que.pop(); if(top){ r.push_back(to_string(top->val)); p.push(top->left); p.push(top->right); }else{ r.push_back(null); } } while(!p.empty()){ que.push(p.front()); p.pop(); } } res += "["; for(int i = 0; i < r.size(); ++ i){ res += r[i]; if(i < r.size() - 1) res += ","; } res += "]"; return res; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { if(data.empty() || data == "[null]") return nullptr; string str(data.begin() + 1, data.end() - 1); auto arr = split(str, ','); size_t size = arr.size(); TreeNode * root = new TreeNode(str2int(arr[0])); queue<TreeNode*> que; que.push(root); for(size_t i = 1; i < size;){ auto top = que.front(); que.pop(); if(top){ if(arr[i] != "null") top->left = new TreeNode(str2int(arr[i])); else top->left = nullptr; ++ i; if(i < size){ if(arr[i] != "null") top->right = new TreeNode(str2int(arr[i])); else top->right = nullptr; ++ i; } if(top->left) que.push(top->left); if(top->right) que.push(top->right); } } return root; } };
30.679389
297
0.458821
nagestx
f16d41e4d89e0b34a2a6424646cfe4b73a80f668
1,066
cpp
C++
src/test.feature.cpp
prinsij/RogueReborn
20e6ba4d2e61a47283747ba207a758e604fa89d9
[ "BSD-3-Clause" ]
null
null
null
src/test.feature.cpp
prinsij/RogueReborn
20e6ba4d2e61a47283747ba207a758e604fa89d9
[ "BSD-3-Clause" ]
null
null
null
src/test.feature.cpp
prinsij/RogueReborn
20e6ba4d2e61a47283747ba207a758e604fa89d9
[ "BSD-3-Clause" ]
null
null
null
/** * @file test.feature.cpp * @author Team Rogue++ * @date December 08, 2016 * * @brief Member definitions for the FeatureTest class */ #include <exception> #include <iostream> #include <string> #include <vector> #include "include/feature.h" #include "test.testable.h" /** * @brief Tests the Feature class. */ class FeatureTest : public Testable { public: FeatureTest(){} void test(){ comment("Commencing Feature tests..."); try { Feature feature = Feature('~', Coord(0,0), false, TCODColor::white); assert(true, "Created Feature"); } catch (const std::exception& e) { assert(false, "Failure creating Feature"); } Feature feature = Feature('~', Coord(0,0), false, TCODColor::white); assert(feature.getSymbol() == '~', "Feature Symbol Check"); assert(!feature.getVisible(), "Feature Visible Check"); feature.setVisible(true); assert(feature.getVisible(), "Feature Visible Check"); assert(feature.getLocation() == Coord(0,0), "Feature Location Check"); comment("Finished Feature tests."); } };
24.227273
73
0.659475
prinsij
f16ec3dc35ce3fb4a90566bce1bbd9d355b2f750
9,392
cpp
C++
src/tests/spec.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
src/tests/spec.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
src/tests/spec.cpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
null
null
null
#include "../thirdparty/catch2/catch.hpp" #include <iostream> #include "../elona/spec.hpp" using namespace std::literals::string_literals; using namespace elona; class TestSpec : public spec::Object { public: TestSpec() : spec::Object("test") { } }; namespace { TestSpec load(const std::string& str) { TestSpec def; std::stringstream ss(str); REQUIRE_NOTHROW(def.load(ss, "spec_test.hcl", "spec_test")); return def; } bool load_fails(const std::string& str) { TestSpec def; std::stringstream ss(str); try { def.load(ss, "spec_test.hcl", "spec_test"); } catch (...) { return true; } return false; } } // namespace TEST_CASE("Test invalid spec format", "[Spec: Definition]") { REQUIRE(load_fails(R"( blah = 4 )")); } TEST_CASE("Test invalid spec object name", "[Spec: Definition]") { REQUIRE(load_fails(R"( config {} )")); } TEST_CASE("Test loading blank spec", "[Spec: Definition]") { REQUIRE_FALSE(load_fails(R"( test {} )")); } TEST_CASE("testining boolean config value", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = true } )"); REQUIRE(def.is<spec::BoolDef>("spec_test.foo")); REQUIRE(def.get_default("spec_test.foo").is<bool>()); REQUIRE(def.get_default("spec_test.foo").as<bool>() == true); } TEST_CASE("testining integer config value", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { default = 42 min = 0 max = 0 } } )"); REQUIRE(def.is<spec::IntDef>("spec_test.foo")); REQUIRE(def.get_default("spec_test.foo").is<int>()); REQUIRE(def.get_default("spec_test.foo").as<int>() == 42); } TEST_CASE("testining bare integer", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = 42 } )")); } TEST_CASE("testining integer without min", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = 42 max = 100 } )")); } TEST_CASE("testining integer without max", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = 42 min = 0 } )")); } TEST_CASE("testining string config value", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = "bar" } )"); REQUIRE(def.is<spec::StringDef>("spec_test.foo")); REQUIRE(def.get_default("spec_test.foo").is<std::string>()); REQUIRE(def.get_default("spec_test.foo").as<std::string>() == "bar"); } TEST_CASE("testining list config value", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = ["bar", "baz", "quux"] } )"); REQUIRE(def.is<spec::ListDef>("spec_test.foo")); REQUIRE(def.get_default("spec_test.foo").is<hcl::List>()); auto list = def.get_default("spec_test.foo").as<hcl::List>(); REQUIRE(list.at(0).as<std::string>() == "bar"); REQUIRE(list.at(1).as<std::string>() == "baz"); REQUIRE(list.at(2).as<std::string>() == "quux"); } TEST_CASE("testining enum config value", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { type = "enum" variants = ["bar", "baz", "quux"] default = "baz" } } )"); REQUIRE(def.is<spec::EnumDef>("spec_test.foo")); REQUIRE(def.get_default("spec_test.foo").is<std::string>()); REQUIRE(def.get_default("spec_test.foo").as<std::string>() == "baz"); } TEST_CASE("Test not providing enum variants", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = { type = "enum" default = "baz" } } )")); } TEST_CASE("Test not providing enum default", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = { type = "enum" variants = ["bar", "baz", "quux"] } } )")); } TEST_CASE("Test providing non-existent enum default", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = { type = "enum" variants = ["bar", "baz", "quux"] default = "hoge" } } )")); } TEST_CASE("Test providing non-string enum variant", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = { type = "enum" variants = ["bar", "baz", 42] default = "bar" } } )")); } TEST_CASE( "Test providing non-string default value in enum", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = { type = "enum" variants = ["bar", "baz", "quux"] default = 42 } } )")); } TEST_CASE("Test providing non-list variants in enum", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = { type = "enum" variants = 42 default = "foo" } } )")); } TEST_CASE("testining runtime enum config value", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { type = "runtime_enum" } bar = "baz" } )"); REQUIRE(def.is<spec::EnumDef>("spec_test.foo")); REQUIRE(def.get_default("spec_test.foo").is<std::string>()); REQUIRE( def.get_default("spec_test.foo").as<std::string>() == "__unknown__"); REQUIRE(def.get_variants("spec_test.foo").size() == 1); REQUIRE_NOTHROW( def.inject_enum("spec_test.foo", {"foo", "bar", "baz"}, "baz")); REQUIRE(def.get_default("spec_test.foo").is<std::string>()); REQUIRE(def.get_default("spec_test.foo").as<std::string>() == "baz"); auto variants = def.get_variants("spec_test.foo"); REQUIRE(variants.size() == 4); REQUIRE(variants.at(0) == "__unknown__"); REQUIRE(variants.at(1) == "foo"); REQUIRE(variants.at(2) == "bar"); REQUIRE(variants.at(3) == "baz"); REQUIRE_THROWS( def.inject_enum("spec_test.bar", {"foo", "bar", "baz"}, "bar")); } TEST_CASE( "Test providing invalid default index in injected enum", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { type = "runtime_enum" } } )"); REQUIRE_THROWS( def.inject_enum("spec_test.foo", {"foo", "bar", "baz"}, "asdfg")); REQUIRE_THROWS(def.inject_enum("spec_test.foo", {"foo", "bar", "baz"}, "")); } TEST_CASE("Test error when injecting non-runtime enum", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { type = "enum" variants = ["foo", "bar", "baz"] default = "bar" } } )"); REQUIRE_THROWS(def.inject_enum("spec_test.foo", {"quux"}, "quux")); } TEST_CASE("testining config section", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { type = "section" options = { bar = false baz = "quux" } } } )"); REQUIRE_THROWS(def.get_default("spec_test.foo")); } TEST_CASE("testining config section with no options", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = { type = "section" } } )")); } TEST_CASE("testining config section with invalid options", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = { type = "section" options = "foo" } } )")); } TEST_CASE("testining invalid type", "[Spec: Definition]") { REQUIRE(load_fails(R"( test { foo = { type = "bar" default = 42 } } )")); } TEST_CASE("Test get_variants", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { type = "enum" variants = ["bar", "baz", "quux"] default = "baz" } hoge = "piyo" } )"); auto variants = def.get_variants("spec_test.foo"); REQUIRE(variants.size() == 3); REQUIRE(variants.at(0) == "bar"); REQUIRE(variants.at(1) == "baz"); REQUIRE(variants.at(2) == "quux"); REQUIRE_THROWS(def.get_variants("spec_test.hoge")); } TEST_CASE("Test get_children", "[Spec: Definition]") { TestSpec def = load(R"( test { foo { type = "section" options = { bar = false baz = "quux" hoge = "fuga" piyo = true } } } )"); auto children = def.get_children("spec_test.foo"); REQUIRE(children.size() == 4); REQUIRE(children.at(0) == "bar"); REQUIRE(children.at(1) == "baz"); REQUIRE(children.at(2) == "hoge"); REQUIRE(children.at(3) == "piyo"); REQUIRE_THROWS(def.get_children("spec_test.hoge")); } TEST_CASE("Test get_max/get_min (integer)", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { default = 42 min = 0 max = 100 } hoge = "piyo" } )"); REQUIRE(def.get_min("spec_test.foo") == 0); REQUIRE(def.get_max("spec_test.foo") == 100); REQUIRE_THROWS(def.get_min("spec_test.hoge")); REQUIRE_THROWS(def.get_max("spec_test.hoge")); } TEST_CASE("Test get_max/get_min (enum)", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { type = "enum" variants = ["bar", "baz", "quux"] default = "baz" } } )"); REQUIRE(def.get_min("spec_test.foo") == 0); REQUIRE(def.get_max("spec_test.foo") == 2); } TEST_CASE("testinition with extended syntax", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = { default = "bar" } } )"); REQUIRE(def.get_default("spec_test.foo").is<std::string>()); REQUIRE(def.get_default("spec_test.foo").as<std::string>() == "bar"); } TEST_CASE("Test exists", "[Spec: Definition]") { TestSpec def = load(R"( test { foo = "bar" } )"); REQUIRE(def.exists("spec_test.foo") == true); REQUIRE(def.exists("spec_test.baz") == false); }
19.689727
80
0.569101
XrosFade
f170413e9e63a0f8a01a12645f5ba620ebfe83b1
1,314
cpp
C++
tested/make_training_set/src/make_training_set.cpp
songdaegeun/school-zone-enforcement-system
b5680909fd5a348575563534428d2117f8dc2e3f
[ "MIT" ]
null
null
null
tested/make_training_set/src/make_training_set.cpp
songdaegeun/school-zone-enforcement-system
b5680909fd5a348575563534428d2117f8dc2e3f
[ "MIT" ]
null
null
null
tested/make_training_set/src/make_training_set.cpp
songdaegeun/school-zone-enforcement-system
b5680909fd5a348575563534428d2117f8dc2e3f
[ "MIT" ]
null
null
null
#include <ros/ros.h> #include <image_transport/image_transport.h> //package.xml에 추가. 이미지데이터를 받고 보내기위해 사용. #include <cv_bridge/cv_bridge.h> //package.xml에 추가 #include <sensor_msgs/image_encodings.h> //package.xml에 추가. cv_bridge::CvImagePtr에 값을 대입하기 위한 인자로 사용된다. #include <opencv2/imgproc/imgproc.hpp> //OpenCV's image processing를 사용하기위해 필요하다. #include <opencv2/highgui/highgui.hpp> //OpenCV's GUI modules를 사용하기위해 필요하다. (cv::namedWindow(OPENCV_WINDOW);) int count=1; class ImageConverter { ros::NodeHandle nh_; image_transport::ImageTransport it_; image_transport::Subscriber image_sub_; cv_bridge::CvImagePtr cv_ptr; cv::Mat img; public: ImageConverter(): it_(nh_) //it_에 nh_을 대입한다. { image_sub_ = it_.subscribe("/camera/color/image_raw", 1, &ImageConverter::imageCb, this); } void imageCb(const sensor_msgs::ImageConstPtr& msg) { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); img=cv_ptr->image; char buff[256]; sprintf(buff,"/home/sdg/catkin_ws/src/make_training_set/dataset/num%d.jpg",count); cv::imwrite(buff,img); count++; } }; int main(int argc, char** argv) { ros::init(argc, argv, "make_training_set"); ImageConverter ic; ros::spin(); return 0; }
30.55814
115
0.681887
songdaegeun
f178d496f3db84c78105b0501e91a10aef1f8576
404
cpp
C++
GotW/GotW1.cpp
straceX/GotW
c8df762586584065c78c64a060a1e67410c59649
[ "Apache-2.0" ]
null
null
null
GotW/GotW1.cpp
straceX/GotW
c8df762586584065c78c64a060a1e67410c59649
[ "Apache-2.0" ]
null
null
null
GotW/GotW1.cpp
straceX/GotW
c8df762586584065c78c64a060a1e67410c59649
[ "Apache-2.0" ]
null
null
null
/* g++ GotW1.cpp -omain -std=c++11 */ #include <iostream> int main() { int ival1 = 13; int ival2{14}; // C++11 int ival3(15); int ival4; int ival5(); // it's a function declaration std::cout << ival1 <<std::endl; std::cout << ival2 <<std::endl; std::cout << ival3 <<std::endl; std::cout << ival4 <<std::endl; std::cout << ival5 <<std::endl; return 0; }
16.833333
47
0.534653
straceX
f17b283c2d2aa63ae9ed1fe0cd097f0cebde5804
6,172
cpp
C++
src/rpc_insert.cpp
ashcharles/openset
51dc29b9dffdb745a24e01a9e4d86c79d2ff20d6
[ "MIT" ]
null
null
null
src/rpc_insert.cpp
ashcharles/openset
51dc29b9dffdb745a24e01a9e4d86c79d2ff20d6
[ "MIT" ]
null
null
null
src/rpc_insert.cpp
ashcharles/openset
51dc29b9dffdb745a24e01a9e4d86c79d2ff20d6
[ "MIT" ]
null
null
null
#include <cinttypes> #include <regex> #include <thread> #include <random> #include "common.h" #include "rpc_global.h" #include "rpc_insert.h" #include "cjson/cjson.h" #include "str/strtools.h" #include "sba/sba.h" #include "oloop_insert.h" #include "asyncpool.h" #include "sentinel.h" #include "sidelog.h" #include "database.h" #include "result.h" #include "table.h" #include "tablepartitioned.h" #include "errors.h" #include "internoderouter.h" #include "http_serve.h" using namespace std; using namespace openset::comms; using namespace openset::async; using namespace openset::comms; using namespace openset::db; using namespace openset::result; void RpcInsert::insertRetry(const openset::web::MessagePtr& message, const RpcMapping& matches, const int retryCount) { const auto database = openset::globals::database; const auto partitions = openset::globals::async; const auto request = message->getJSON(); const auto tableName = matches.find("table"s)->second; const auto isFork = message->getParamBool("fork"); /* const auto relayString = message->getParamString("relay"); const auto relayParts = split(relayString, ':'); std::unordered_set<int64_t> alreadyRelayed; alreadyRelayed.insert(openset::globals::running->nodeId); for (const auto &relay : relayParts) { alreadyRelayed.insert(stoll(relay)); } if (!partitions->getPartitionMax()) { RpcError( openset::errors::Error{ openset::errors::errorClass_e::insert, openset::errors::errorCode_e::route_error, "node not initialized" }, message); return; } */ auto table = database->getTable(tableName); if (!table || table->deleted) { RpcError( openset::errors::Error{ openset::errors::errorClass_e::insert, openset::errors::errorCode_e::general_error, "missing or invalid table name" }, message); return; } //auto clusterErrors = false; const auto startTime = Now(); // a cluster error (missing partition, etc), or a map changed happened // during this insert, then re-insert if (openset::globals::sentinel->wasDuringMapChange(startTime - 500, startTime)) { const auto backOff = (retryCount * retryCount) * 20; ThreadSleep(backOff < 10000 ? backOff : 10000); insertRetry(message, matches, retryCount + 1); return; } auto rows = request.getNodes(); Logger::get().info("Inserting " + to_string(rows.size()) + " events."); // vectors go gather locally inserted, or remotely distributed events from this set //std::unordered_map<int, std::vector<char*>> localGather; //std::unordered_map<int64_t, std::vector<char*>> remoteGather; SideLog::getSideLog().lock(); for (auto row : rows) { const auto personNode = row->xPath("/id"); if (!personNode || (personNode->type() != cjson::Types_e::INT && personNode->type() != cjson::Types_e::STR)) continue; // straight up numeric ID nodes don't need hashing, actually hashing would be very bad. // We can use numeric IDs (i.e. a customer id) directly. int64_t uuid = 0; if (personNode->type() == cjson::Types_e::STR) { auto uuString = personNode->getString(); toLower(uuString); if (uuString.length()) uuid = MakeHash(uuString); } else uuid = personNode->getInt(); const auto destination = cast<int32_t>((std::abs(uuid) % 13337) % partitions->getPartitionMax()); int64_t len; SideLog::getSideLog().add(table.get(), destination, cjson::stringifyCstr(row, len)); } SideLog::getSideLog().unlock(); const auto localEndTime = Now(); if (!isFork && openset::globals::mapper->countActiveRoutes() > 1) { if (openset::globals::sentinel->wasDuringMapChange(startTime, localEndTime)) ThreadSleep(1000); const auto method = message->getMethod(); const auto path = message->getPath(); auto newParams = message->getQuery(); newParams.emplace("fork", "true"); const auto payloadLength = message->getPayloadLength(); const auto payload = static_cast<char*>(PoolMem::getPool().getPtr(payloadLength)); memcpy(payload, message->getPayload(), payloadLength); std::thread t([=](){ while (true) { auto result = openset::globals::mapper->dispatchCluster( method, path, newParams, payload, payloadLength, false); const auto isGood = !result.routeError; openset::globals::mapper->releaseResponses(result); if (isGood) break; } PoolMem::getPool().freePtr(payload); }); t.detach(); } cjson response; response.set("message", "yummy"); // broadcast active nodes to caller - they may round-robin to these auto routesList = response.setArray("routes"); { csLock lock(openset::globals::mapper->cs); auto routes = openset::globals::mapper->routes; for (const auto &r : routes) { if (r.first == globals::running->nodeId) // fix for broadcast bug shouting local host and port routesList->push(globals::running->hostExternal + ":" + to_string(globals::running->portExternal)); else routesList->push(r.second.first + ":" + to_string(r.second.second)); } } message->reply(http::StatusCode::success_ok, response); } void RpcInsert::insert(const openset::web::MessagePtr& message, const RpcMapping& matches) { insertRetry(message, matches, 1); }
31.489796
118
0.585386
ashcharles
f184cb107e9537b5c4396f7ecc52e3025c1cbf84
16,373
cpp
C++
template/src/Wrapper_py/Tools/Algo/Matrix/Sparse_matrix/Sparse_matrix.cpp
aff3ct/py_aff3ct
8afb7e6b1db1b621db0ae4153b29a2e848e09fcf
[ "MIT" ]
15
2021-01-24T11:59:04.000Z
2022-03-23T07:23:44.000Z
template/src/Wrapper_py/Tools/Algo/Matrix/Sparse_matrix/Sparse_matrix.cpp
aff3ct/py_aff3ct
8afb7e6b1db1b621db0ae4153b29a2e848e09fcf
[ "MIT" ]
8
2021-05-24T18:22:45.000Z
2022-03-11T09:48:05.000Z
template/src/Wrapper_py/Tools/Algo/Matrix/Sparse_matrix/Sparse_matrix.cpp
aff3ct/py_aff3ct
8afb7e6b1db1b621db0ae4153b29a2e848e09fcf
[ "MIT" ]
4
2021-01-26T19:18:21.000Z
2021-12-07T17:02:34.000Z
#include <sstream> #include "Wrapper_py/Tools/Algo/Matrix/Sparse_matrix/Sparse_matrix.hpp" namespace py = pybind11; using namespace py::literals; using namespace aff3ct; using namespace aff3ct::module; using namespace aff3ct::tools; using namespace aff3ct::wrapper; Wrapper_Sparse_matrix ::Wrapper_Sparse_matrix(py::module_& scope) : Wrapper_py(), py::class_<aff3ct::tools::Sparse_matrix>(scope, "array") { py::module_ alist = scope.def_submodule("alist"); alist.def("read", [](const std::string& path){ std::filebuf fb; if (fb.open (path,std::ios::in)) { std::istream stream(&fb); aff3ct::tools::Sparse_matrix ret = aff3ct::tools::AList::read(stream); return ret; } else { std::stringstream message; message << "Can't open '" + path + "' file."; throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str()); } }, py::return_value_policy::copy); py::module_ qc = scope.def_submodule("qc"); qc.def("read", [](const std::string& path){ std::filebuf fb; if (fb.open (path,std::ios::in)) { std::istream stream(&fb); aff3ct::tools::Sparse_matrix ret = aff3ct::tools::QC::read(stream); return ret; } else { std::stringstream message; message << "Can't open '" + path + "' file."; throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str()); } }, py::return_value_policy::copy); scope.def("eye", [](const size_t &size, const int64_t &d){ aff3ct::tools::Sparse_matrix * H = new aff3ct::tools::Sparse_matrix(size, size); for (size_t i = 0; i<size; i++) if (i-d >= 0 && i-d < size) H->add_connection(i-d,i); return H; }, py::return_value_policy::take_ownership); scope.def("ones", [](py::tuple& shape){ if (shape.size() != 2 ) { std::stringstream message; message << "the created array should be 2-dimensional, but " << shape.size() << " indexes were given."; throw py::index_error(message.str()); } int n_rows; try { n_rows = shape[0].cast<size_t>(); } catch(...) { std::stringstream message; message << "shape should be a positive integer vector."; throw py::index_error(message.str()); } int n_cols; try { n_cols = shape[1].cast<size_t>(); } catch(...) { std::stringstream message; message << "shape should be a positive integer vector."; throw py::index_error(message.str()); } aff3ct::tools::Sparse_matrix * H = new aff3ct::tools::Sparse_matrix(n_rows, n_cols); for (size_t i = 0; i<n_rows; i++) for (size_t j = 0; j<n_cols; j++) H->add_connection(i,j); return H; }, py::return_value_policy::take_ownership); scope.def("zeros", [](py::tuple& shape){ if (shape.size() != 2 ) { std::stringstream message; message << "the created array should be 2-dimensional, but " << shape.size() << " indexes were given."; throw py::index_error(message.str()); } int n_rows; try { n_rows = shape[0].cast<size_t>(); } catch(...) { std::stringstream message; message << "shape should be a positive integer vector."; throw py::index_error(message.str()); } int n_cols; try { n_cols = shape[1].cast<size_t>(); } catch(...) { std::stringstream message; message << "shape should be a positive integer vector."; throw py::index_error(message.str()); } aff3ct::tools::Sparse_matrix * H = new aff3ct::tools::Sparse_matrix(n_rows, n_cols); return H; }, py::return_value_policy::take_ownership); scope.def("concatenate", [](py::tuple& arrays, size_t axis){ aff3ct::tools::Sparse_matrix* H; try { H = new aff3ct::tools::Sparse_matrix(arrays[0].cast<aff3ct::tools::Sparse_matrix>()); } catch(...) { std::stringstream message; message << "Item 0 of 'arrays' tuple cannot be casted into a py_aff3ct.tools.sparse_matrix.array."; throw py::value_error(message.str()); } size_t n_rows = H->get_n_rows(); size_t n_cols = H->get_n_cols(); if (axis == 0) { for (size_t i =1; i<arrays.size(); i++) { aff3ct::tools::Sparse_matrix* H_; try { H_ = arrays[i].cast<aff3ct::tools::Sparse_matrix*>(); } catch(...) { std::stringstream message; message << "Item " << i << " of 'arrays' tuple cannot be casted into a py_aff3ct.tools.sparse_matrix.array."; throw py::value_error(message.str()); } int old_n_rows = n_rows; n_rows += H_->get_n_rows(); if (H_->get_n_cols() != n_cols) { std::stringstream message; message << "all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index " << i << " has size " << H_->get_n_cols() << " and the array at index " << i - 1 << " has size " << n_cols << "."; throw py::value_error(message.str()); } H->self_resize(n_rows, n_cols, aff3ct::tools::Matrix::Origin::TOP_LEFT); for (size_t i = 0; i < H_->get_n_rows(); i++) for (size_t j = 0; j < H_->get_n_cols(); j++) if(H_->at(i,j) && !H->at(old_n_rows+i,j)) H->add_connection(old_n_rows+i,j); else if(!H_->at(i,j) && H->at(old_n_rows+i,j)) H->rm_connection(old_n_rows+i,j); } } else if (axis == 1) { for (size_t i =1; i<arrays.size(); i++) { aff3ct::tools::Sparse_matrix* H_; try { H_ = arrays[i].cast<aff3ct::tools::Sparse_matrix*>(); } catch(...) { std::stringstream message; message << "Item " << i << " of 'arrays' tuple cannot be casted into a py_aff3ct.tools.sparse_matrix.array."; throw py::value_error(message.str()); } int old_n_cols = n_cols; n_cols += H_->get_n_cols(); if (H_->get_n_rows() != n_rows) { std::stringstream message; message << "all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index " << i << " has size " << H_->get_n_rows() << " and the array at index " << i - 1 << " has size " << n_rows << "."; throw py::value_error(message.str()); } H->self_resize(n_rows, n_cols, aff3ct::tools::Matrix::Origin::TOP_LEFT); for (size_t i = 0; i < H_->get_n_rows(); i++) for (size_t j = 0; j < H_->get_n_cols(); j++) if(H_->at(i,j) && !H->at(i,old_n_cols + j)) H->add_connection(i,old_n_cols + j); else if(!H_->at(i,j) && H->at(i,old_n_cols + j)) H->rm_connection(i,old_n_cols + j); } } return H; }, "arrays"_a, "axis"_a=0, py::return_value_policy::take_ownership); } void Wrapper_Sparse_matrix ::definitions() { this->def(py::init<const size_t, const size_t>(),"n_rows"_a = 0, "n_cols"_a = 1, R"pbdoc()pbdoc", py::return_value_policy::take_ownership); this->def(py::init([](py::array_t<bool> &array){ if (array.ndim() == 2) { size_t n_rows = array.shape(0); size_t n_cols = array.shape(1); tools::Sparse_matrix* ret_spm = new tools::Sparse_matrix(n_rows,n_cols); for (size_t i = 0; i < n_rows ; ++i) for (size_t j = 0; j < n_cols ; ++j) if(array.at(i,j)) ret_spm->add_connection(i,j); return ret_spm; } else { throw std::runtime_error("Sparse_Matrix can only be built from a 2-dimensional boolean array."); } }), "array"_a = 1, R"pbdoc()pbdoc", py::return_value_policy::take_ownership); this->def("full", [](aff3ct::tools::Sparse_matrix& self) { auto arr = py::array_t<bool, py::array::c_style>({ self.get_n_rows(), self.get_n_cols() }); auto f_arr = arr.mutable_unchecked<2>(); for (size_t i = 0; i<self.get_n_rows(); i++ ) for (size_t j = 0; j<self.get_n_cols(); j++ ) f_arr(i,j) = self.at(i,j); return arr; },py::return_value_policy::copy); this->def("__getitem__", [](const aff3ct::tools::Sparse_matrix& self, const size_t& index) { aff3ct::tools::Sparse_matrix* ret_spm = new aff3ct::tools::Sparse_matrix(1, self.get_n_cols()); for (size_t j = 0; j < self.get_n_cols(); ++j) if (self.at(index, j)) ret_spm->add_connection(0,j); return ret_spm; }, py::return_value_policy::take_ownership); this->def("__getitem__", [](const aff3ct::tools::Sparse_matrix& self, const py::tuple& index) { if (index.size() < 1 ) { std::stringstream message; message << "too few indices for array: array is 2-dimensional, but " << index.size() << " were indexed."; throw py::index_error(message.str()); } if (index.size() > 2 ) { std::stringstream message; message << "too many indices for array: array is 2-dimensional, but " << index.size() << " were indexed."; throw py::index_error(message.str()); } py::slice si = Wrapper_Sparse_matrix::get_slice(index[0], self.get_n_rows()); size_t starti = 0, stopi = 0, stepi = 0, slicelengthi = 0; if (!si.compute(self.get_n_rows(), &starti, &stopi, &stepi, &slicelengthi)) throw py::error_already_set(); py::slice sj; if (index.size() == 1) sj = py::slice(0, self.get_n_cols(),1); else sj = Wrapper_Sparse_matrix::get_slice(index[1], self.get_n_rows()); size_t startj = 0, stopj = 0, stepj = 0, slicelengthj = 0; if (!sj.compute(self.get_n_cols(), &startj, &stopj, &stepj, &slicelengthj)) throw py::error_already_set(); aff3ct::tools::Sparse_matrix* ret_spm = new aff3ct::tools::Sparse_matrix(slicelengthi, slicelengthj); size_t read_i = starti; for (size_t i = 0; i < slicelengthi; ++i) { size_t read_j = startj; for (size_t j = 0; j < slicelengthj; ++j) { if (self.at(read_i, read_j)) ret_spm->add_connection(i,j); read_j += stepj; } read_i += stepi; } return ret_spm; }, py::return_value_policy::take_ownership); this->def("__setitem__", [](aff3ct::tools::Sparse_matrix& self, const size_t& index, const aff3ct::tools::Sparse_matrix& value) { for (size_t j = 0; j < self.get_n_cols(); ++j) { if (value.at(0,j) && !self.at(index, j)) self.add_connection(index, j); else if (!value.at(0,j) && self.at(index, j)) self.rm_connection(index, j); } }); this->def("__setitem__", [](aff3ct::tools::Sparse_matrix& self, const py::tuple& index, const aff3ct::tools::Sparse_matrix& value) { if (index.size() < 1 ) { std::stringstream message; message << "too few indices for array: array is 2-dimensional, but " << index.size() << " were indexed."; throw py::index_error(message.str()); } if (index.size() > 2 ) { std::stringstream message; message << "too many indices for array: array is 2-dimensional, but " << index.size() << " were indexed."; throw py::index_error(message.str()); } py::slice si = Wrapper_Sparse_matrix::get_slice(index[0], self.get_n_rows()); size_t starti = 0, stopi = 0, stepi = 0, slicelengthi = 0; if (!si.compute(self.get_n_rows(), &starti, &stopi, &stepi, &slicelengthi)) throw py::error_already_set(); py::slice sj; if (index.size() == 1) sj = py::slice(0, self.get_n_cols(),1); else sj = Wrapper_Sparse_matrix::get_slice(index[1], self.get_n_rows()); size_t startj = 0, stopj = 0, stepj = 0, slicelengthj = 0; if (!sj.compute(self.get_n_cols(), &startj, &stopj, &stepj, &slicelengthj)) throw py::error_already_set(); if (value.get_n_rows() != slicelengthi || value.get_n_cols() != slicelengthj) { std::stringstream message; message << " could not broadcast input array from shape (" << value.get_n_rows() << "," << value.get_n_cols() <<") into shape (" << slicelengthi << "," << slicelengthj << ")."; throw py::index_error(message.str()); } size_t write_i = starti; for (size_t i = 0; i < slicelengthi; ++i) { size_t write_j = startj; for (size_t j = 0; j < slicelengthj; ++j) { if (value.at(i,j)) { if(!self.at(write_i, write_j)) self.add_connection(write_i, write_j); } else { if(self.at(write_i, write_j)) self.rm_connection(write_i, write_j); } write_j += stepj; } write_i += stepi; } }); this->def("__setitem__", [](aff3ct::tools::Sparse_matrix& self, const py::tuple& index, const py::array_t<bool>& value) { if (index.size() < 1 ) { std::stringstream message; message << "too few indices for array: array is 2-dimensional, but " << index.size() << " were indexed."; throw py::index_error(message.str()); } if (index.size() > 2 ) { std::stringstream message; message << "too many indices for array: array is 2-dimensional, but " << index.size() << " were indexed."; throw py::index_error(message.str()); } py::slice si = Wrapper_Sparse_matrix::get_slice(index[0], self.get_n_rows()); size_t starti = 0, stopi = 0, stepi = 0, slicelengthi = 0; if (!si.compute(self.get_n_rows(), &starti, &stopi, &stepi, &slicelengthi)) throw py::error_already_set(); py::slice sj; if (index.size() == 1) sj = py::slice(0, self.get_n_cols(),1); else sj = Wrapper_Sparse_matrix::get_slice(index[1], self.get_n_rows()); size_t startj = 0, stopj = 0, stepj = 0, slicelengthj = 0; if (!sj.compute(self.get_n_cols(), &startj, &stopj, &stepj, &slicelengthj)) throw py::error_already_set(); if (value.shape(0) != slicelengthi || value.shape(1) != slicelengthj) { std::stringstream message; message << " could not broadcast input array from shape (" << value.shape(0) << "," << value.shape(1) <<") into shape (" << slicelengthi << "," << slicelengthj << ")."; throw py::index_error(message.str()); } size_t write_i = starti; for (size_t i = 0; i < slicelengthi; ++i) { size_t write_j = startj; for (size_t j = 0; j < slicelengthj; ++j) { if (value.at(i,j)) { if(!self.at(write_i, write_j)) self.add_connection(write_i, write_j); } else { if(self.at(write_i, write_j)) self.rm_connection(write_i, write_j); } write_j += stepj; } write_i += stepi; } }); this->def("__setitem__", [](aff3ct::tools::Sparse_matrix& self, const py::tuple& index, const bool& value) { if (index.size() < 1 ) { std::stringstream message; message << "too few indices for array: array is 2-dimensional, but " << index.size() << " were indexed."; throw py::index_error(message.str()); } if (index.size() > 2 ) { std::stringstream message; message << "too many indices for array: array is 2-dimensional, but " << index.size() << " were indexed."; throw py::index_error(message.str()); } py::slice si = Wrapper_Sparse_matrix::get_slice(index[0], self.get_n_rows()); size_t starti = 0, stopi = 0, stepi = 0, slicelengthi = 0; if (!si.compute(self.get_n_rows(), &starti, &stopi, &stepi, &slicelengthi)) throw py::error_already_set(); py::slice sj; if (index.size() == 1) sj = py::slice(0, self.get_n_cols(),1); else sj = Wrapper_Sparse_matrix::get_slice(index[1], self.get_n_rows()); size_t startj = 0, stopj = 0, stepj = 0, slicelengthj = 0; if (!sj.compute(self.get_n_cols(), &startj, &stopj, &stepj, &slicelengthj)) throw py::error_already_set(); size_t write_i = starti; for (size_t i = 0; i < slicelengthi; ++i) { size_t write_j = startj; for (size_t j = 0; j < slicelengthj; ++j) { if (value) { if(!self.at(write_i, write_j)) self.add_connection(write_i, write_j); } else { if(self.at(write_i, write_j)) self.rm_connection(write_i, write_j); } write_j += stepj; } write_i += stepi; } }); this->def("__str__",[](aff3ct::tools::Sparse_matrix& self){ std::stringstream message; message << "Sparse_matrix of size " << self.get_n_rows() << "x" << self.get_n_cols()<<".\nConnections:\n"; for (size_t i = 0; i < self.get_n_rows(); ++i) for (size_t j = 0; j < self.get_n_cols(); ++j) if (self.at(i,j)) message << "\t(" << i <<","<< j <<")\n"; return message.str(); }); this->def("transpose",[](const aff3ct::tools::Sparse_matrix& self){ return self.transpose(); }); this->def_property_readonly("shape", [](const aff3ct::tools::Sparse_matrix& self){ return py::make_tuple(self.get_n_rows(),self.get_n_cols()); }); } py::slice Wrapper_Sparse_matrix ::get_slice(const py::object& obj, const size_t len) { if (py::isinstance<py::int_>(obj)) { int i_sj = obj.cast<int>(); size_t ui_sj; if ( i_sj < 0 ) ui_sj = len - (abs(i_sj) % len); else ui_sj = i_sj % len; py::slice sjj = py::slice(ui_sj, ui_sj+1, 1); return sjj; } else if(py::isinstance<py::slice>(obj)) { return py::slice(obj); } else { throw std::runtime_error("Sparse_Matrix only accepts integer or slice indexing."); } }
30.776316
253
0.62658
aff3ct
f18661d5b42ddec21ee89bb630335b003b927da0
557
cpp
C++
main.cpp
autch/piemu
bf15030757c49325c155a853871aee45b616717a
[ "Zlib" ]
10
2017-07-04T03:05:42.000Z
2022-01-20T17:37:06.000Z
main.cpp
autch/piemu
bf15030757c49325c155a853871aee45b616717a
[ "Zlib" ]
2
2020-06-29T13:32:15.000Z
2021-12-22T23:04:43.000Z
main.cpp
autch/piemu
bf15030757c49325c155a853871aee45b616717a
[ "Zlib" ]
5
2021-08-28T02:21:56.000Z
2022-01-16T21:39:16.000Z
/** @file main.c * Entry point of p/emu */ #include <SDL.h> #include <SDL_thread.h> int main_event_loop(void); #ifdef __linux__ int main(int argc, char** argv) #else int SDL_main(int argc, char** argv) #endif { SDL_Init(SDL_INIT_EVERYTHING); SDL_SetVideoMode(128 * 2, 88 * 2, 32, SDL_HWSURFACE); main_event_loop(); SDL_Quit(); return 0; } int main_event_loop(void) { SDL_Event event; while(1) { while(SDL_WaitEvent(&event)) { switch(event.type) { case SDL_QUIT: return 0; } } } return 0; }
12.953488
55
0.624776
autch
f18c14013c9b6cd736a3fed6920eb508781f94dc
1,189
hpp
C++
lib/crypto/crypto_AES.hpp
Pcornat/BenLib
5ec30f5eb0bbf827d4d3fd00c8cca1064109fb4c
[ "MIT" ]
null
null
null
lib/crypto/crypto_AES.hpp
Pcornat/BenLib
5ec30f5eb0bbf827d4d3fd00c8cca1064109fb4c
[ "MIT" ]
null
null
null
lib/crypto/crypto_AES.hpp
Pcornat/BenLib
5ec30f5eb0bbf827d4d3fd00c8cca1064109fb4c
[ "MIT" ]
null
null
null
/* ** BENSUPERPC PROJECT, 2020 ** Crypto ** Source: https://stackoverflow.com/questions/178265/what-is-the-most-hard-to-understand-piece-of-c-code-you-know https://cs.uwaterloo.ca/~m32rober/rsqrt.pdf https://github.com/bavlayan/Encrypt-Decrypt-with-OpenSSL---RSA https://stackoverflow.com/a/5580881/10152334 ** crypto.cpp */ #ifndef CRYPTO_AES_HPP_ #define CRYPTO_AES_HPP_ // For AES #include <openssl/aes.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/rand.h> #include <string.h> #define BUFFSIZE 16384 namespace my { namespace crypto { int Decrypt_AES(unsigned char *ciphertext, int ciphertext_len, unsigned char *aad, int aad_len, unsigned char *tag, unsigned char *key, unsigned char *iv, unsigned char *plaintext); int Encrypt_AES(unsigned char *plaintext, int plaintext_len, unsigned char *aad, int aad_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext, unsigned char *tag); int Rand_Key_AES(unsigned char *key); int Rand_IV_AES(unsigned char *iv); __attribute__((__noreturn__)) void handleErrors(); } // namespace crypto } // namespace my // https://www.quora.com/How-can-I-get-the-MD5-or-SHA-hash-of-a-file-in-C #endif
27.651163
159
0.751051
Pcornat
f197bf6ee3216d0ade2497e1f115756a814b2b9b
3,473
cpp
C++
STM_SW/test_mbed/src/main.cpp
chris3069/BLDC_Project
69f6b7ed810d091dd430d93554056e34af130d2d
[ "BSL-1.0" ]
null
null
null
STM_SW/test_mbed/src/main.cpp
chris3069/BLDC_Project
69f6b7ed810d091dd430d93554056e34af130d2d
[ "BSL-1.0" ]
null
null
null
STM_SW/test_mbed/src/main.cpp
chris3069/BLDC_Project
69f6b7ed810d091dd430d93554056e34af130d2d
[ "BSL-1.0" ]
null
null
null
#include <mbed.h> // #include "encoder_implementation/own_rotary.hpp" #include "motor_implementation/own_open_loop/open_loop.hpp" #include "motor_implementation/closed_loop/closed_loop.hpp" class Encoder { public: Encoder(); ~Encoder(); int32_t get_rotary_angle(void); void reset_rotary_angle(void); private: void rise_A(void); void rise_B(void); void fall_A(void); void fall_B(void); private: InterruptIn rotary_encoderA; InterruptIn rotary_encoderB; // Timeout synchronous_rpm; volatile int32_t m_rotary_angle; volatile bool voltage_level_a; volatile bool voltage_level_b; // _interrupt.rise(callback(this, &Encoder::change_angle)); }; void Encoder::rise_A(void) { voltage_level_a = 1; if (voltage_level_b == 1) { m_rotary_angle = m_rotary_angle +1; } else { --m_rotary_angle; } } void Encoder::fall_A(void) { voltage_level_a = 0; if (voltage_level_b == 1) { // --Encoder::rotary_angle; --m_rotary_angle; } else { ++m_rotary_angle; } } void Encoder::rise_B(void) { voltage_level_b = 1; if (voltage_level_a == 1) { --m_rotary_angle; } else { ++m_rotary_angle; } } void Encoder::fall_B(void) { voltage_level_b = 0; if (voltage_level_a == 1) { ++m_rotary_angle; } else { --m_rotary_angle; } } int32_t Encoder::get_rotary_angle(void) { return this->m_rotary_angle; } void Encoder::reset_rotary_angle(void) { m_rotary_angle = 0; } Encoder::Encoder() :rotary_encoderA(D12), rotary_encoderB(PA_11), m_rotary_angle(0) { rotary_encoderA.rise(callback(this, &Encoder::rise_A)); rotary_encoderA.fall(callback(this, &Encoder::fall_A)); rotary_encoderB.rise(callback(this, &Encoder::rise_B)); rotary_encoderB.fall(callback(this, &Encoder::fall_B)); } #define MAXIMUM_BUFFER_SIZE 32 Motor_Implementation *MotorControl; // Encoder *Rotary_Encoder; InterruptIn button_stop(D7); // Stop Taster, Falling Edge glaub ich InterruptIn button_start(D8); // Start Taster, Falling Edge bool stop_motor = 0; void start_button_press(void) { // delete MotorControl; // if (button_start.read() == 0) // { // MotorControl = new Own_Closed_Loop(); // } // else // { // MotorControl = new Own_Open_Loop(); // } // MotorControl->start_motor_control(); } void stop_button_press(void) { stop_motor = 1; } // Create a BufferedSerial object with a default baud rate. static BufferedSerial serial_port(USBTX, USBRX); int main() { // Set desired properties (9600-8-N-1). serial_port.set_baud(9600); serial_port.set_format( /* bits */ 8, /* parity */ BufferedSerial::None, /* stop bit */ 1 ); char buf[MAXIMUM_BUFFER_SIZE] = {0}; // button_start.fall(&start_button_press); button_stop.fall(&stop_button_press); Encoder Rotary_Encoder; // MotorControl = new Own_Closed_Loop(); if (button_start.read() == 0) { MotorControl = new Own_Closed_Loop(); } else { MotorControl = new Own_Open_Loop(); } // serial_port.write(buf, periodlength); while(1) { if (stop_motor == 1) { Rotary_Encoder.reset_rotary_angle(); stop_motor = 0; } int32_t rotary_angle = Rotary_Encoder.get_rotary_angle(); MotorControl->control_motor(rotary_angle); // serial_port.write(buf, periodlength); // put your main code here, to run repeatedly: ThisThread::sleep_for(20); } }
18.875
68
0.669738
chris3069
f1980c0fbbaf792c3ca69e0114e61712dfea79de
3,825
cpp
C++
main.cpp
vicrucann/ParallelTransportFrame
3357b15725a3d953ae740d069d44a2595d6a2d81
[ "MIT" ]
3
2019-04-08T05:13:00.000Z
2020-01-02T05:40:03.000Z
main.cpp
vicrucann/ParallelTransportFrame
3357b15725a3d953ae740d069d44a2595d6a2d81
[ "MIT" ]
null
null
null
main.cpp
vicrucann/ParallelTransportFrame
3357b15725a3d953ae740d069d44a2595d6a2d81
[ "MIT" ]
2
2018-07-06T05:22:01.000Z
2021-12-26T12:45:34.000Z
#include <iostream> #include <stdio.h> #ifdef _WIN32 #include <Windows.h> #endif #include <osgViewer/Viewer> #include <osg/Node> #include <osg/ShapeDrawable> #include <osgDB/WriteFile> #include <osgGA/EventHandler> #include <osg/Switch> #include "libPTFTube/PTFTube.h" const int OSG_WIDTH = 900; const int OSG_HEIGHT = 900; osg::Node* createReferenceShape() { osg::Cylinder* cylinder = new osg::Cylinder(osg::Vec3( 0.f, 0.f, 0.f ), 0.5f, 2.f); osg::ShapeDrawable* sd = new osg::ShapeDrawable( cylinder ); sd->setColor( osg::Vec4( 0.8f, 0.5f, 0.2f, 1.f ) ); osg::Geode* geode = new osg::Geode; geode->addDrawable(sd); geode->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::ON); return geode; } std::vector<osg::Vec3f> createLinePoints3d() { std::vector<osg::Vec3f> points3d; int angle = 0; float z=0.f; float pi = 3.141592f; for (angle; angle<=360*2; angle+=10, z+=0.3f){ float rad = angle*pi/180.f; float dx=0, dy=0, dz=0; dx = std::sin(rad)*2.f; dy = std::cos(rad)*4.f; dz = z; points3d.push_back(osg::Vec3f(dx,dy,dz)); } return points3d; } class Switch : public osg::Switch { public: Switch(const PTFTube& extrusion) : osg::Switch() { osg::ref_ptr<osg::Node> path = extrusion.generatePath(); osg::ref_ptr<osg::Node> mesh = extrusion.generateTriMesh(); osg::ref_ptr<osg::Node> slices = extrusion.generateFrameSlices(1.f); osg::ref_ptr<osg::Node> wire = extrusion.generateWireFrame(); this->addChild(path.get(), false); this->addChild(wire.get(), false); this->addChild(slices.get(), false); this->addChild(mesh.get(), true); } }; class EventHandler : public osgGA::GUIEventHandler { public: EventHandler(Switch* all) : osgGA::GUIEventHandler() , m_root(all) { } virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { unsigned int index = 3; switch (ea.getEventType()){ case (osgGA::GUIEventAdapter::KEYUP): switch (ea.getKey()){ case '0': std::cout << "Original path display.\n"; index = 0; break; case '1': std::cout << "Wire frame display.\n"; index = 1; break; case '2': std::cout << "Frame slice display.\n"; index = 2; break; case '3': std::cout << "Triangular mesh display.\n"; index = 3; break; default: for (unsigned int i=0; i<m_root->getNumChildren(); ++i){ if (m_root->getValue(i)) index = i; } break; } for (unsigned int i=0; i< m_root->getNumChildren(); ++i){ if (i == index) m_root->setValue(i, true); else m_root->setValue(i, false); } default: break; } return false; } private: osg::observer_ptr<Switch> m_root; }; int main(int, char**) { #ifdef _WIN32 ::SetProcessDPIAware(); #endif osgViewer::Viewer viewer; viewer.setUpViewInWindow(100,100,OSG_WIDTH, OSG_HEIGHT); osg::ref_ptr<osg::Group> root = new osg::Group(); // root->addChild(createReferenceShape()); PTFTube extrusion(createLinePoints3d(), 0.5, 5); extrusion.build(); Switch* geometries = new Switch(extrusion); root->addChild(geometries); viewer.setSceneData(root.get()); EventHandler* EH = new EventHandler(geometries); viewer.addEventHandler(EH); return viewer.run(); }
26.020408
87
0.55268
vicrucann
1af5e2ad3934fffc83afe5deeeef978bf8aaa137
28
cc
C++
src/tests/test_event_chain.cc
AndreyGFranca/mcec
3033b85068c1bfe45b07597b96fa810872030bf1
[ "Apache-2.0" ]
null
null
null
src/tests/test_event_chain.cc
AndreyGFranca/mcec
3033b85068c1bfe45b07597b96fa810872030bf1
[ "Apache-2.0" ]
null
null
null
src/tests/test_event_chain.cc
AndreyGFranca/mcec
3033b85068c1bfe45b07597b96fa810872030bf1
[ "Apache-2.0" ]
null
null
null
#include "../EventChain.h"
9.333333
26
0.642857
AndreyGFranca
1afab343c93e5de1f73a6dbfd41cdfe39584c228
425
hpp
C++
library/ATF/__dummy_block.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/__dummy_block.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/__dummy_block.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <_dummy_position.hpp> START_ATF_NAMESPACE struct __dummy_block { char *pszBlockName; int nSubDummyNum; _dummy_position *pSubDummy[32]; public: __dummy_block(); void ctor___dummy_block(); }; END_ATF_NAMESPACE
22.368421
108
0.689412
lemkova
1afc4ec5b99ad983400a0ba147a1929f1774be8b
2,401
hpp
C++
rest_rpc/rest_rpc/base/log.hpp
emogua/CGAssistant
f3ded85a8336bcc03fd1a3d370880cdeedaa570f
[ "MIT" ]
39
2019-03-26T08:03:44.000Z
2022-02-13T09:06:48.000Z
rest_rpc/rest_rpc/base/log.hpp
emogua/CGAssistant
f3ded85a8336bcc03fd1a3d370880cdeedaa570f
[ "MIT" ]
10
2019-04-08T22:18:10.000Z
2021-10-04T04:11:00.000Z
rest_rpc/rest_rpc/base/log.hpp
emogua/CGAssistant
f3ded85a8336bcc03fd1a3d370880cdeedaa570f
[ "MIT" ]
26
2019-03-26T08:13:42.000Z
2022-03-15T04:51:39.000Z
#pragma once #include <spdlog/spdlog.h> namespace timax { class log { public: static log& get() { static log _log; return _log; } bool init(const std::string& file_name) { try { log_ = spdlog::rotating_logger_mt("logger", file_name, 1024 * 1024 * 50, 2); console_log_ = spdlog::stdout_logger_mt("console"); } catch (std::exception&) { return false; } catch (...) { return false; } return true; } std::shared_ptr<spdlog::logger> get_log() { return log_; } std::shared_ptr<spdlog::logger> get_console_log() { return console_log_; } private: log() = default; log(const log&) = delete; log(log&&) = delete; std::shared_ptr<spdlog::logger> log_; std::shared_ptr<spdlog::logger> console_log_; }; template<typename... Args> static inline void SPD_LOG_TRACE(const char* fmt, const Args&... args) { log::get().get_log()->trace(fmt, args...); } template<typename... Args> static inline void SPD_LOG_INFO(const char* fmt, const Args&... args) { log::get().get_log()->info(fmt, args...); } //template<typename... Args> //static inline void SPD_LOG_NOTICE(const char* fmt, const Args&... args) //{ // log::get().get_log()->notice(fmt, args...); //} template<typename... Args> static inline void SPD_LOG_WARN(const char* fmt, const Args&... args) { log::get().get_log()->warn(fmt, args...); } template<typename... Args> static inline void SPD_LOG_ERROR(const char* fmt, const Args&... args) { log::get().get_log()->error(fmt, args...); } template<typename... Args> static inline void SPD_LOG_CRITICAL(const char* fmt, const Args&... args) { log::get().get_log()->critical(fmt, args...); } //template<typename... Args> //static inline void SPD_LOG_ALERT(const char* fmt, const Args&... args) //{ // log::get().get_log()->alert(fmt, args...); //} //template<typename... Args> //static inline void SPD_LOG_EMERG(const char* fmt, const Args&... args) //{ // log::get().get_log()->emerg(fmt, args...); //} template<typename... Args> static inline void SPD_LOG_DEBUG(const char* fmt, const Args&... args) { #ifdef NDEBUG #else log::get().get_log()->set_level(spdlog::level::debug); log::get().get_log()->debug(fmt, args...); log::get().get_console_log()->set_level(spdlog::level::debug); log::get().get_console_log()->debug(fmt, args...); #endif } }
21.061404
80
0.63307
emogua
1afee429b5d65373d88f8a49dce90955d4c0967d
2,024
cpp
C++
src/Emulators/nestopiaue/core/input/NstInpPokkunMoguraa.cpp
slajerek/RetroDebugger
e761e4f9efd103a05e65ef283423b142fa4324c7
[ "Apache-2.0", "MIT" ]
34
2021-05-29T07:04:17.000Z
2022-03-10T20:16:03.000Z
src/Emulators/nestopiaue/core/input/NstInpPokkunMoguraa.cpp
slajerek/RetroDebugger
e761e4f9efd103a05e65ef283423b142fa4324c7
[ "Apache-2.0", "MIT" ]
6
2021-12-25T13:05:21.000Z
2022-01-19T17:35:17.000Z
src/Emulators/nestopiaue/core/input/NstInpPokkunMoguraa.cpp
slajerek/RetroDebugger
e761e4f9efd103a05e65ef283423b142fa4324c7
[ "Apache-2.0", "MIT" ]
6
2021-12-24T18:37:41.000Z
2022-02-06T23:06:02.000Z
//////////////////////////////////////////////////////////////////////////////////////// // // Nestopia - NES/Famicom emulator written in C++ // // Copyright (C) 2003-2008 Martin Freij // // This file is part of Nestopia. // // Nestopia 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. // // Nestopia 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 Nestopia; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //////////////////////////////////////////////////////////////////////////////////////// #include "NstInpDevice.hpp" #include "NstInpPokkunMoguraa.hpp" namespace Nes { namespace Core { namespace Input { #ifdef NST_MSVC_OPTIMIZE #pragma optimize("s", on) #endif PokkunMoguraa::PokkunMoguraa(const Cpu& c) : Device(c,Api::Input::POKKUNMOGURAA) { PokkunMoguraa::Reset(); } void PokkunMoguraa::Reset() { state = 0x1E; } void PokkunMoguraa::SaveState(State::Saver& saver,const byte id) const { saver.Begin( AsciiId<'P','M'>::R(0,0,id) ).End(); } #ifdef NST_MSVC_OPTIMIZE #pragma optimize("", on) #endif void PokkunMoguraa::Poke(const uint data) { if (input) { Controllers::PokkunMoguraa::callback( input->pokkunMoguraa, ~data & 0x7 ); state = ~input->pokkunMoguraa.buttons & 0x1E; } else { state = 0x1E; } } uint PokkunMoguraa::Peek(const uint port) { return port ? state : 0; } } } }
25.948718
89
0.585968
slajerek
210474d24dfa9b30f862bc59e3d3dfcb4995fb91
2,771
cpp
C++
app/src/main/cpp/Bullet.cpp
KoreanGinseng/2d_shooting_game_for_android
be21b4f4bbf8326c834f2148f6ab6337fd2c0518
[ "MIT" ]
null
null
null
app/src/main/cpp/Bullet.cpp
KoreanGinseng/2d_shooting_game_for_android
be21b4f4bbf8326c834f2148f6ab6337fd2c0518
[ "MIT" ]
null
null
null
app/src/main/cpp/Bullet.cpp
KoreanGinseng/2d_shooting_game_for_android
be21b4f4bbf8326c834f2148f6ab6337fd2c0518
[ "MIT" ]
null
null
null
/******************************************************************************/ /*! @file Bullet.cpp @brief 弾クラス実装ファイル *******************************************************************************/ #include "Bullet.h" #include <DxLib.h> using namespace Shooting2D; /******************************************************************************/ /*! コンストラクタ *******************************************************************************/ CBullet::CBullet() : CGameObject() , m_SpeedX(0.0f) , m_SpeedY(0.0f) , m_Angle(0.0f) , m_Image(-1) { } /******************************************************************************/ /*! デストラクタ *******************************************************************************/ CBullet::~CBullet() { } /******************************************************************************/ /*! 弾の初期化 @param[in] px 初期位置X @param[in] py 初期位置Y @param[in] sx スピードX @param[in] sy スピードY @param[in] iw 画像幅 @param[in] ih 画像高さ @param[in] img 画像ID @return 成功 k_Success, 失敗 それ以外 *******************************************************************************/ MyS32 CBullet::Initialize(MyFloat px, MyFloat py, MyFloat sx, MyFloat sy, MyS32 iw, MyS32 ih, MyInt img) { m_bShow = true; m_PosX = px; m_PosY = py; m_SpeedX = sx; m_SpeedY = sy; m_Angle = atan2f(sy, sx) + ToRadian(90); m_Width = iw; m_Height = ih; m_Image = img; m_Radius = 4; return k_Success; } /******************************************************************************/ /*! 弾の更新 @return 成功 k_Success, 失敗 それ以外 *******************************************************************************/ MyS32 CBullet::Update() { // 非表示のため動作なし if (!m_bShow) { return k_Success; } // 速度で等速移動 m_PosX += m_SpeedX; m_PosY += m_SpeedY; // 画面外で消去 if (m_PosX < -m_Width || m_PosY < -m_Height || m_PosX > k_SceneWidth + m_Width || m_PosY > k_SceneHeight + m_Height) { m_bShow = false; } return k_Success; } /******************************************************************************/ /*! 弾の描画 @return 成功 k_Success, 失敗 それ以外 *******************************************************************************/ MyS32 CBullet::Draw() { // 非表示のため描画なし if (!m_bShow) { return k_Success; } MyInt drawPosX = k_SceneOffsetX + m_PosX + k_BulletDrawOffsetX; MyInt drawPosY = k_SceneOffsetY + m_PosY + k_BulletDrawOffsetY; DxLib::DrawRotaGraph(drawPosX, drawPosY, 1.0f, m_Angle, m_Image, true); #ifdef MY_DEBUG DxLib::DrawCircle(m_PosX, m_PosY, m_Radius, DxLib::GetColor(0, 0, 0)); #endif //MY_DEBUG return k_Success; }
29.478723
104
0.381451
KoreanGinseng
2105620576082643d5af067788e47a9e9b9caba9
2,367
cpp
C++
Opal Prospect/OpenGL/TextureAtlasController.cpp
swbengs/OpalProspect
5f77dd07c1bb4197673589ac3f42546a4d0329b3
[ "MIT" ]
2
2018-06-06T02:01:08.000Z
2020-07-25T18:10:32.000Z
Opal Prospect/OpenGL/TextureAtlasController.cpp
swbengs/OpalProspect
5f77dd07c1bb4197673589ac3f42546a4d0329b3
[ "MIT" ]
10
2018-07-27T01:56:45.000Z
2019-02-23T01:49:36.000Z
Opal Prospect/OpenGL/TextureAtlasController.cpp
swbengs/OpalProspect
5f77dd07c1bb4197673589ac3f42546a4d0329b3
[ "MIT" ]
null
null
null
#include "TextureAtlasController.hpp" /* MIT License Copyright (c) 2018 Scott Bengs 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. */ TextureAtlasController::TextureAtlasController() { index_size = 0; } void TextureAtlasController::addAtlas(TextureAtlas& atlas) { atlases.push_back(atlas); if (getSize() == 1) { starts.push_back(0); //number of textures in the atlas * index size //so for example, using rectangles you need 24 bytes per texture * atlas size //24 = 6 index * 4 bytes each(unsigned int) } else { unsigned int total = 0; for (unsigned int n = 0; n < getSize()-1; n++) { total += total + atlases.at(n).getAtlasSize(); } starts.push_back(total * getIndexSize()); } } TextureAtlas& TextureAtlasController::modifyAtlas(unsigned int index) { return atlases.at(index); } //gets const TextureAtlas& TextureAtlasController::getAtlas(unsigned int index) { return atlases.at(index); } unsigned int TextureAtlasController::getAtlasStart(unsigned int index) const { return starts.at(index); } unsigned int TextureAtlasController::getIndexSize() const { return index_size; } unsigned int TextureAtlasController::getSize() const { return atlases.size(); } //sets void TextureAtlasController::setIndexSize(unsigned int size) { index_size = size; }
28.178571
85
0.73215
swbengs
210a6386dbb89d43f1738b76a6cc3b55bac54390
1,170
cpp
C++
src/sense-hat-sim.cpp
partouf/cpp-sense-hat
d0f4750d1d432fae1bc4793c8d161d6374ed1d9e
[ "MIT" ]
4
2016-08-22T21:06:46.000Z
2021-02-28T02:06:52.000Z
src/sense-hat-sim.cpp
partouf/cpp-sense-hat
d0f4750d1d432fae1bc4793c8d161d6374ed1d9e
[ "MIT" ]
null
null
null
src/sense-hat-sim.cpp
partouf/cpp-sense-hat
d0f4750d1d432fae1bc4793c8d161d6374ed1d9e
[ "MIT" ]
null
null
null
#include "sense-hat-sim.h" #include <memory> SenseHAT::ISenseHAT *HATInstance = nullptr; SenseHAT::SenseHATSim::SenseHATSim() : ISenseHAT() { LEDMatrix = std::make_unique<SenseHAT::SenseHATLedMatrixSim>(); } double SenseHAT::SenseHATSim::get_humidity() { return 0.0; } double SenseHAT::SenseHATSim::get_pressure() { return 0.0; } SenseHAT::d3 SenseHAT::SenseHATSim::get_gyro() { return{ 0, 0, 0, true }; } SenseHAT::d3 SenseHAT::SenseHATSim::get_accel() { return{ 0, 0, 0, true }; } SenseHAT::d3 SenseHAT::SenseHATSim::get_magno() { return{ 0, 0, 0, true }; } SenseHAT::ISenseHAT * SenseHAT::SenseHATSim::Instance() { if (HATInstance == nullptr) { HATInstance = new SenseHAT::SenseHATSim(); } return HATInstance; } SenseHAT::d3 SenseHAT::SenseHATSim::get_temperature() { return {0,0,0,true}; } SenseHAT::SenseHATLedMatrixSim::SenseHATLedMatrixSim() : ISenseHATLEDMatrix() { } void SenseHAT::SenseHATLedMatrixSim::Clear() { } void SenseHAT::SenseHATLedMatrixSim::SetPixel(int x, int y, uint8_t r, uint8_t g, uint8_t b) { } void SenseHAT::SenseHATLedMatrixSim::SetFromRgbaMatrix(const SenseHATColor_t matrix[8][8]) { }
17.727273
92
0.702564
partouf
210b0a849964627fdfa84cf20b6d61a947dd059e
185
hpp
C++
src/agl/glsl/function/geometric/normalize.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
src/agl/glsl/function/geometric/normalize.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
src/agl/glsl/function/geometric/normalize.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
#pragma once #include "length.hpp" #include "agl/glsl/vec/vec.hpp" namespace agl { template<std::size_t N> Vec<float, N> normalize(Vec<float, N> v) { return v / length(v); } }
12.333333
42
0.654054
the-last-willy
2111129de076626ac8aaf1ebd0cf388996581daf
809
cpp
C++
node_modules/lzz-gyp/lzz-source/smtc_TypeParam.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
3
2019-09-18T16:44:33.000Z
2021-03-29T13:45:27.000Z
node_modules/lzz-gyp/lzz-source/smtc_TypeParam.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
null
null
null
node_modules/lzz-gyp/lzz-source/smtc_TypeParam.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
2
2019-03-29T01:06:38.000Z
2019-09-18T16:44:34.000Z
// smtc_TypeParam.cpp // #include "smtc_TypeParam.h" #ifndef LZZ_ENABLE_INLINE #include "smtc_TypeParam.inl" #endif // semantic #include "smtc_NameToString.h" // util #include "util_AppendWithSpace.h" #define LZZ_INLINE inline namespace smtc { TypeParam::TypeParam (NamePtr const & name, CvType const & def_type) : Param (name), m_def_type (def_type) {} } namespace smtc { TypeParam::~ TypeParam () {} } namespace smtc { util::String TypeParam::toString (bool is_decl) const { using namespace util; String str = "typename"; appendWithSpace (str, nameToString (getName ())); if (is_decl && m_def_type.isSet ()) { appendWithSpace (str, '='); appendWithSpace (str, m_def_type.toString ()); } return str; } } #undef LZZ_INLINE
19.731707
70
0.657602
SuperDizor
211e7f65be16fae090457534fa702e196d5f8188
829
cpp
C++
Ejercicios/ProyectoFinal_GestorArchivosMAR/login.cpp
Maldanar201/LenguajeProgramacion1
5a53c51077c0e41deff8daf40dbe6f0778b41f9c
[ "MIT" ]
null
null
null
Ejercicios/ProyectoFinal_GestorArchivosMAR/login.cpp
Maldanar201/LenguajeProgramacion1
5a53c51077c0e41deff8daf40dbe6f0778b41f9c
[ "MIT" ]
null
null
null
Ejercicios/ProyectoFinal_GestorArchivosMAR/login.cpp
Maldanar201/LenguajeProgramacion1
5a53c51077c0e41deff8daf40dbe6f0778b41f9c
[ "MIT" ]
null
null
null
#include <iostream> #include <stdlib.h> #include <fstream> #include <string.h> #include <ctime> using namespace std; // seguridad para iniciar el sistema bool login() { setlocale(LC_CTYPE,"spanish"); string usuario = ""; string password = ""; bool acceso = false; int intentos = 0; while(intentos <= 3) { system("cls"); if(intentos == 3) { cout << " NO SE PUDO VALIDAR SU PASSWORD, "<< endl; cout << " Por favor pongase en contacto con el,"<<endl; cout << " administrador del systema " << endl; return false; } cout << " Ingrese su Usuario : "; cin >> usuario; cout << " Ingrese su clave : "; cin >> password; if(usuario == "admin" && password == "admin") { system("cls"); return true; } intentos++; } }
18.021739
59
0.557298
Maldanar201
2123419ecedb22992456a7c3cf3caf7672cc90ba
526
cpp
C++
src/models/piece.cpp
0xkalvin/chess
3a71fb04c3d6ec9d1a0d27fba320090c8ee7ce52
[ "MIT" ]
1
2021-07-24T06:36:25.000Z
2021-07-24T06:36:25.000Z
src/models/piece.cpp
0xkalvin/chess
3a71fb04c3d6ec9d1a0d27fba320090c8ee7ce52
[ "MIT" ]
9
2019-07-04T02:35:34.000Z
2019-07-09T03:00:21.000Z
src/models/piece.cpp
0xkalvin/chess
3a71fb04c3d6ec9d1a0d27fba320090c8ee7ce52
[ "MIT" ]
null
null
null
#include "piece.h" Piece::Piece(char s, int v, bool white, int q){ this->symbol = s; this->value = v; this->white = white; this->quantity = this->alive = q; this->moved = false; } Piece::~Piece(){} char Piece::getSymbol(){ return this->symbol; } int Piece::getValue(){ return this->value; } bool Piece::isWhite(){ return this->white; } int Piece::getQuantity(){ return this->quantity; } void Piece::captured(){ this->alive--; } int Piece::getAlive(){ return this->alive; }
14.216216
47
0.60076
0xkalvin
2124fe39abdaac1984e9e6d4fc09a80fe0af8725
790
cpp
C++
CompileToCppVariable.cpp
ShaiRoitman/CompileToCppVar
6f5da9231d8594ce7b07e73a14f2b182de7608f6
[ "MIT" ]
null
null
null
CompileToCppVariable.cpp
ShaiRoitman/CompileToCppVar
6f5da9231d8594ce7b07e73a14f2b182de7608f6
[ "MIT" ]
null
null
null
CompileToCppVariable.cpp
ShaiRoitman/CompileToCppVar
6f5da9231d8594ce7b07e73a14f2b182de7608f6
[ "MIT" ]
null
null
null
#include "stdio.h" int main(int argc, char* argv[]) { if ( argc <= 1) { printf("CompileToCppVariable <Filename> [VariableName]\n"); return 1; } if ( argc > 2) { printf ("const char %s[] = {\n", argv[2]); } FILE* fp = fopen(argv[1],"rb"); if (fp == NULL) { printf ("Could not open file %s\n", argv[1]); return 2; } fseek(fp,0,SEEK_END); long size = ftell(fp); unsigned char* buffer = new unsigned char[size]; fseek(fp,0,SEEK_SET); fread(buffer,sizeof(char),size,fp); for (long i = 0 ; i < size ; i++) { printf("0x%02hhx,",buffer[i]); if ((i % 20)==19) { printf("\n"); } } printf ("0x%02hhx\n",(const unsigned char)(0)); if ( argc > 2) { printf ("};\n"); } fclose(fp); return 0; }
15.490196
62
0.516456
ShaiRoitman
2125e54de619aa2bfdbd0f8403008d8517f92445
1,002
cpp
C++
src/WindowManager.cpp
ToxicFrazzles/MultiPaddle
1650280d99e350255c6fdadcf14b02b872379748
[ "CC0-1.0" ]
null
null
null
src/WindowManager.cpp
ToxicFrazzles/MultiPaddle
1650280d99e350255c6fdadcf14b02b872379748
[ "CC0-1.0" ]
null
null
null
src/WindowManager.cpp
ToxicFrazzles/MultiPaddle
1650280d99e350255c6fdadcf14b02b872379748
[ "CC0-1.0" ]
null
null
null
#include "MultiPaddle/WindowManager.h" WindowManager::WindowManager(const char* windowTitle) { if(SDL_Init(SDL_INIT_VIDEO) < 0){ std::cerr << "Could not initialise sdl2: " << SDL_GetError() << std::endl; return; } window = SDL_CreateWindow( windowTitle, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); if(window == nullptr){ std::cerr << "Could not create window: " << SDL_GetError() << std::endl; return; } this->screenSurface = SDL_GetWindowSurface(window); this->sdlRenderer = SDL_CreateRenderer(window, -1, 0); this->ready = true; } bool WindowManager::isReady() const { return this->ready; } SDL_Renderer * WindowManager::getRenderer() { return this->sdlRenderer; } int WindowManager::handleEvents() { SDL_Event event; SDL_WaitEventTimeout(&event, 10); switch(event.type){ case SDL_QUIT: SDL_Quit(); return 1; default: ; // std::cout << "Event Type: " << event.type << std::endl; } return 0; }
22.266667
76
0.697605
ToxicFrazzles
2127fbdf3c872ac273b82f3bc0a60356869d7b94
3,422
cpp
C++
src/SinkRecord.cpp
rgmyr/FLASHcodeStellarCores
32b14d2e991a92d9146f4e0d939a444e8adcd163
[ "MIT" ]
null
null
null
src/SinkRecord.cpp
rgmyr/FLASHcodeStellarCores
32b14d2e991a92d9146f4e0d939a444e8adcd163
[ "MIT" ]
null
null
null
src/SinkRecord.cpp
rgmyr/FLASHcodeStellarCores
32b14d2e991a92d9146f4e0d939a444e8adcd163
[ "MIT" ]
null
null
null
/* * The Sink Record class reads, prints, and writes information related to sink data * read directly from the checkpoint files. The ctor should be passed a filename. */ #include "RossGlobals.h" #include "HDFIO.h" #include "Sink.hpp" #include "SinkRecord.hpp" #include <iostream> using std::cout; using std::endl; SinkRecord::SinkRecord(const std::string fname): Filename(fname), has_been_allocated(false) { resetFromFile(); } void SinkRecord::resetFromFile() { InOut.open(Filename, 'r'); data_dims = InOut.getDims("sink particle data"); data_size = InOut.getSize("sink particle data"); num_sinks = data_dims[0]; num_attributes = data_dims[1]; // Probably superfluous, but these should always be the same? assert( (num_sinks*num_attributes) == data_size ); cout << "Sink Data dimensions: "; print_container( data_dims ); cout << "Data size: " << data_size << endl; // Global function sets global var: HDFDataType CheckMachineForLittleBigEndianNumerics(); if (has_been_allocated) { delete [] DataPointer; } DataPointer = new float[data_size]; has_been_allocated = true; InOut.read(DataPointer, "sink particle data", ::HDFDataType); InOut.close(); unsigned int i; for (i = 0; i < num_sinks; i++) { // call Sink ctor and push onto mySinks mySinks.push_back( Sink( &DataPointer[i*num_attributes] ) ); } // sorts the sinks by formation times, so they always have the same ID std::sort( mySinks.begin(), mySinks.end() ); // give the sinks a unique int ID from sorted order for (i = 0; i < num_sinks; i++) { mySinks[i].setID(i); } } float SinkRecord::getAttribute(const unsigned int sink_id, const unsigned int attr_id) const { if (attr_id >= num_attributes) { cout << "Warning: attribute index must be less than the number of attributes" << " to avoid errors" << endl << "You passed: " << attr_id << endl << "Number of attributes: " << num_attributes << endl; return 1; } else if (sink_id >= num_sinks) { cout << "Error --> passed sink_id: " << sink_id << " with num_sinks: " << num_sinks << endl; return 1; } else { return this->DataPointer[sink_id * num_attributes + attr_id]; } } // For writing meta info to file adjacent to extracted datasets // -- might not need this, just run everything from one main and // give reference to SinkRecord to CoreAnalyzer? void WriteSinkRecord(const int sink_id, const std::string outfile_name) { } void SinkRecord::writeAllScripts() const { cout << "SinkRecord::writeAllScripts() called..." << endl << endl; std::string baseDir("/data1/r900-1/rossm/QuickFlash-1.0.0/core_code"); std::vector< Sink >::const_iterator it; for (it = mySinks.begin(); it != mySinks.end(); ++it) { int chk_num = 66; // needs to be more general it->writeExtractorScript(baseDir, chk_num, Filename); } } void SinkRecord::printAllData(void) { for (int i = 0; i < data_size; i++) { cout << DataPointer[i] << endl; if (i % (num_attributes-1) == 0){ cout << endl; } } } void SinkRecord::printAllSinks(void) { cout << endl; std::vector< Sink >::iterator it; for (it = mySinks.begin(); it != mySinks.end(); ++it) { it->printMe(); } }
27.596774
92
0.630333
rgmyr
213e85ee0ff56ef4f0fcfa43aa93573e4a46321c
229
cpp
C++
_tempalte/main.cpp
5ooo/LeetCode
5f250cd38696f581e5c891b8977f6c27eea26ffa
[ "MIT" ]
null
null
null
_tempalte/main.cpp
5ooo/LeetCode
5f250cd38696f581e5c891b8977f6c27eea26ffa
[ "MIT" ]
null
null
null
_tempalte/main.cpp
5ooo/LeetCode
5f250cd38696f581e5c891b8977f6c27eea26ffa
[ "MIT" ]
null
null
null
#include <stdio.h> #include <algorithm> #include <iostream> #include <vector> #include <stack> #include <map> #include <utility> using namespace std; class Solution { public: }; int main() { Solution s; return 0; }
9.956522
20
0.663755
5ooo
213f686c659be9ddcbabed25563e8468288e3adf
38,954
cpp
C++
PVGroups.cpp
nardinan/vulture
d4be5b028d9fab4c0d23797ceb95d22f5a33cb75
[ "FTL" ]
null
null
null
PVGroups.cpp
nardinan/vulture
d4be5b028d9fab4c0d23797ceb95d22f5a33cb75
[ "FTL" ]
null
null
null
PVGroups.cpp
nardinan/vulture
d4be5b028d9fab4c0d23797ceb95d22f5a33cb75
[ "FTL" ]
null
null
null
/* PSYCHO GAMES(C) STUDIOS - 2007 www.psychogames.net * Project: Vulture(c) * Author : Andrea Nardinocchi * eMail : [email protected] * * 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "PVGroups.h" int PVgroup::build(char *string) { if (infos.player->logics.hascategory("GROUP") != 0) { if (groups.hasvalue(string) != 0) { if (groups.addvalue(string, 1) > 0) LOG_ERROR("Unable to add GROUP->%s Logic", message); else { if (infos.player->logics.addcategory("GROUP") > 0) LOG_ERROR("Unable to add GROUP Category"); else { if (infos.player->logics.addvalue("GROUP", "Admin", 1) > 0) LOG_ERROR("Unable to add GROUP->Admin Logic"); else if (infos.player->logics.addvalue("GROUP", "Capo", 2) > 0) LOG_ERROR("Unable to add GROUP->Rule Logic"); else if (infos.player->logics.addvalue("GROUP", string, 3) > 0) LOG_ERROR("Unable to add GROUP->Name Logic"); else if (infos.player->pvsend(pvulture.server, "[reset][green]hai fondato il gruppo \"%s\"[n]", string) > 0) return 1; } } } else if (infos.player->pvsend(pvulture.server, "[reset]esiste gia' un'altro gruppo con lo stesso nome![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]fai gia' parte di un gruppo![n]") > 0) return 1; return 0; } int PVgroup::add(char *string) { Cmob *mob = NULL; Cplayer *player = NULL; char *charactername = NULL; if (string) { if ((player = pvulture.characters.getplayer(string, infos.player->position))) { if (infos.player->getID() != player->getID()) { if (player->logics.hascategory("GROUP") != 0) { if (player->logics.addcategory("GROUP") > 0) LOG_ERROR("Unable to add GROUP Category"); else { if (player->logics.addvalue("GROUP", infos.player->logics.getvalue("GROUP", 3), 3) > 0) LOG_ERROR("Unable to add GROUP->Name Logic"); else if (player->logics.addvalue("GROUP", "Membro", 2) > 0) LOG_ERROR("Unable to add GROUP->Rule Logic"); else { if (player->pvsend(pvulture.server, "[reset][n][green]sei ora membro del gruppo \"%s\"[n]", infos.player->logics.getvalue("GROUP", 3)) > 0) return 1; if (infos.player->pvsend(pvulture.server, "[reset][green]%s e' ora un membro del tuo gruppo[n]", charactername = pvulture.characters.gettargetname(player, infos.player)) > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } if (player->spvsend(pvulture.server, sshell) > 0) return 1; } } } else if (infos.player->pvsend(pvulture.server, "[reset]fa gia' parte di un'altro gruppo[n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset][reset]stai parlando di te stess%s![n]", (infos.player->getsex() != MALE) ? "a" : "o") > 0) return 1; } else if ((mob = pvulture.characters.getmob(string, infos.player->position))) { if (mob->logics.hascategory("GROUP") != 0) { if (mob->logics.addcategory("GROUP") > 0) LOG_ERROR("Unable to add GROUP Category"); else { if (mob->logics.addvalue("GROUP", infos.player->logics.getvalue("GROUP", 3), 3) > 0) LOG_ERROR("Unable to add GROUP->Name Logic"); else if (mob->logics.addvalue("GROUP", "Membro", 2) > 0) LOG_ERROR("Unable to add GROUP->Rule Logic"); else if (infos.player->pvsend(pvulture.server, "[reset][green]%s e' ora un membro del tuo gruppo[n]", charactername = pvulture.characters.gettargetname(mob, infos.player)) > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } } } else if (infos.player->pvsend(pvulture.server, "[reset]fa gia' parte di un'altro gruppo[n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non vedi nessuno con quel nome qui![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un nome![n]") > 0) return 1; return 0; } int PVgroup::rule(char *string) { Cmob *mob = NULL; Cplayer *player = NULL; int value = 0; char *message = NULL, *pointer = NULL, *rule = NULL; if (string) { if ((message = (char *) pvmalloc(strlen(string) + 1))) { strcpy(message, string); message[strlen(string)] = '\0'; if ((pointer = strchr(message, ':'))) { for (rule = pointer + 1; *rule == ' '; rule++); do { *pointer-- = '\0'; } while ((pointer > message) && (*pointer == ' ')); if ((strlen(rule) > 0) && (strlen(message) > 0)) { if ((player = pvulture.characters.getplayer(message, infos.player->position))) { value = this->rule(player, rule); } else if ((mob = pvulture.characters.getmob(message, infos.player->position))) { value = this->rule(mob, rule); } else if (infos.player->pvsend(pvulture.server, "[reset]non vedi nessuno con quel nome qui![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare almeno un ruolo[n]") > 0) return 1; } else { value = this->rule(infos.player, message); } } else return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare almeno un ruolo[n]") > 0) return 1; if (message) { pvfree(message); message = NULL; } return value; } int PVgroup::rule(Cplayer *player, char *string) { char *charactername = NULL; if (player->getID() != infos.player->getID()) { if ((player->logics.hascategory("GROUP") == 0) || (player->logics.hasvalue("GROUP", infos.player->logics.getvalue("GROUP", 3)) == 0)) { if (player->logics.delvalue("GROUP", 2) > 0) LOG_ERROR("Unable to delete GROUP->Rule Logic"); if (player->logics.addvalue("GROUP", string, 2) > 0) LOG_ERROR("Unable to add GROUP RULE->Rule Logic"); else { if (player->pvsend(pvulture.server, "[reset][n][green]sei ora nel gruppo con il ruolo di \"%s\"[n]", string) > 0) return 1; if (infos.player->pvsend(pvulture.server, "[reset][green]%s ora ha il ruolo di \"%s\"[n]", charactername = pvulture.characters.gettargetname(player, infos.player), string) > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } if (player->spvsend(pvulture.server, sshell) > 0) return 1; } } else if (infos.player->pvsend(pvulture.server, "[reset]non fa parte del tuo gruppo![n]") > 0) return 1; } else { if (infos.player->logics.delvalue("GROUP", 2) > 0) LOG_ERROR("Unable to delete GROUP->Rule Logic"); if (infos.player->logics.addvalue("GROUP", string, 2) > 0) LOG_ERROR("Unable to add GROUP->Rule Logic"); else if (infos.player->pvsend(pvulture.server, "[reset][green]hai modificato il tuo ruolo in \"%s\"[n]", message) > 0) return 1; } return 0; } int PVgroup::rule(Cmob *mob, char *string) { char *charactername = NULL; if ((mob->logics.hascategory("GROUP") == 0) || (mob->logics.hasvalue("GROUP", infos.player->logics.getvalue("GROUP", 3)) == 0)) { if (mob->logics.delvalue("GROUP", 2) > 0) LOG_ERROR("Unable to delete GROUP->Rule Logic"); if (mob->logics.addvalue("GROUP", string, 2) > 0) LOG_ERROR("Unable to add GROUP->Rule Logic"); else { if (infos.player->pvsend(pvulture.server, "[reset][green]%s ora ha il ruolo di \"%s\"[n]", charactername = pvulture.characters.gettargetname(mob, infos.player), string) > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } } } else if (infos.player->pvsend(pvulture.server, "[reset]non fa parte del tuo gruppo![n]") > 0) return 1; return 0; } int PVgroup::exit(void) { if (infos.player->logics.hasvalue("GROUP", "Admin") != 0) { if (infos.player->logics.delcategory("GROUP") > 0) LOG_ERROR("Unable to delete GROUP Category"); else if (infos.player->pvsend(pvulture.server, "[reset][red]hai abbandonato il gruppo[n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]prima di abbandonare devi cedere il trono, o sciogliere direttamente il gruppo[n]") > 0) return 1; return 0; } int PVgroup::kick(char *string) { Cmob *mob = NULL; Cplayer *player = NULL; int value = 0; char *charactername = string; if ((player = pvulture.characters.getplayer(charactername, infos.player->position))) { value = kick(player); } else if ((mob = pvulture.characters.getmob(charactername, infos.player->position))) { value = kick(mob); } else if (infos.player->pvsend(pvulture.server, "[reset]non vedi nessuno con quel nome qui![n]") > 0) return 1; return value; } int PVgroup::kick(Cplayer *player) { char *charactername = NULL; if (player->getID() != infos.player->getID()) { if (player->logics.hasvalue("GROUP", infos.player->logics.getvalue("GROUP", 3)) == 0) { if ((player->logics.hasvalue("GROUP", "Admin") != 0) && ((player->logics.hasvalue("GROUP", "Moderator") != 0) || (infos.player->logics.hasvalue("GROUP", "Moderator") != 0))) { if (player->logics.delcategory("GROUP") > 0) LOG_ERROR("Unable to delete GROUP Category"); else { if (infos.player->pvsend(pvulture.server, "[reset][blue]%s non fa piu' parte del tuo gruppo[n]", charactername = pvulture.characters.gettargetname(player, infos.player)) > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } if (player->pvsend(pvulture.server, "[reset][n][blue]sei stato cacciato dal gruppo da %s[n]", charactername = pvulture.characters.gettargetname(infos.player, player)) > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } if (player->spvsend(pvulture.server, sshell) > 0) return 1; } } else if (infos.player->pvsend(pvulture.server, "[reset]non hai sufficienti privilegi![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]%s non fa parte del tuo gruppo![n]", (player->getsex() != MALE) ? "lei" : "lui") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset][reset]stai parlando di te stess%s![n]", (infos.player->getsex() != MALE) ? "a" : "o") > 0) return 1; return 0; } int PVgroup::kick(Cmob *mob) { char *charactername = NULL; if (mob->logics.hasvalue("GROUP", infos.player->logics.getvalue("GROUP", 3)) == 0) { if ((mob->logics.hasvalue("GROUP", "Moderator") != 0) || (infos.player->logics.hasvalue("GROUP", "Moderator") != 0)) { if (mob->logics.delcategory("GROUP") > 0) LOG_ERROR("Unable to delete GROUP Category"); else { if (infos.player->pvsend(pvulture.server, "[reset][blue]%s non fa piu' parte del tuo gruppo[n]", charactername = pvulture.characters.gettargetname(mob, infos.player)) > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } } } else if (infos.player->pvsend(pvulture.server, "[reset]non hai sufficienti privilegi![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]%s non fa parte del tuo gruppo![n]", (mob->getsex() != MALE) ? "lei" : "lui") > 0) return 1; return 0; } int PVgroup::transfer(char *string) { Cplayer *player = NULL; char *charactername = string; if ((player = pvulture.characters.getplayer(charactername, infos.player->position))) { if (player->getID() != infos.player->getID()) { if ((player->logics.hascategory("GROUP") == 0) && (compare.vcmpcase(infos.player->logics.getvalue("GROUP", 3), player->logics.getvalue("GROUP", 3)) == 0)) { player->logics.delvalue("GROUP", "Moderator"); player->logics.delvalue("GROUP", "User"); if ((player->logics.addvalue("GROUP", "Admin", 1) > 0) || (player->logics.delvalue("GROUP", 2) > 0) || (player->logics.addvalue("GROUP", "Capitano", 2) > 0)) LOG_ERROR("Unable to add GROUP->Rule Logic"); else if ((infos.player->logics.delvalue("GROUP", "Admin") > 0) || (infos.player->logics.addvalue("GROUP", "User", 1) > 0) || (infos.player->logics.delvalue("GROUP", 2) > 0) || (infos.player->logics.addvalue("GROUP", "Membro", 2) > 0)) LOG_ERROR("Unable to add GROUP->Rule Logic"); else { if (player->pvsend(pvulture.server, "[reset][n][blue]sei diventat%s l'admin del gruppo![n]", (player->getsex() != MALE) ? "a" : "o") > 0) return 1; if (infos.player->pvsend(pvulture.server, "[reset][blue]hai ceduto la tua carica di admin a %s[n]", charactername = pvulture.characters.gettargetname(player, infos.player)) > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } if (player->spvsend(pvulture.server, sshell) > 0) return 1; } } else if (infos.player->pvsend(pvulture.server, "[reset]stai parlando di te stess%s![n]", (infos.player->getsex() != MALE) ? "a" : "o") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non fa parte del tuo stesso gruppo![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non vedi nessuno con quel nome qui![n]") > 0) return 1; return 0; } int PVgroup::moderator(char *string) { Cmob *mob = NULL; Cplayer *player = NULL; int value = 0; if ((player = pvulture.characters.getplayer(string, infos.player->position))) { value = moderator(player); } else if ((mob = pvulture.characters.getmob(string, infos.player->position))) { value = moderator(mob); } else if (infos.player->pvsend(pvulture.server, "[reset]non vedi nessuno con quel nome qui![n]") > 0) return 1; return value; } int PVgroup::moderator(Cplayer *player) { char *charactername = NULL; if (player->getID() != infos.player->getID()) { if ((player->logics.hascategory("GROUP") == 0) && (compare.vcmpcase(infos.player->logics.getvalue("GROUP", 3), player->logics.getvalue("GROUP", 3)) == 0)) { if (player->logics.hasvalue("GROUP", "Moderator") != 0) { player->logics.delvalue("GROUP", "User"); if ((player->logics.addvalue("GROUP", "Moderator", 1) > 0) || (player->logics.delvalue("GROUP", 2) > 0) || (player->logics.addvalue("GROUP", "Vice", 2) > 0)) LOG_ERROR("Unable to add/remove GROUP->Rule Logic"); else { if (infos.player->pvsend(pvulture.server, "[reset][blue]%s e' ora un vice[n]", charactername = pvulture.characters.gettargetname(player, infos.player)) > 0) return 1; if (player->pvsend(pvulture.server, "[reset][n][blue]sei diventat%s vice del gruppo![n]", (player->getsex() != MALE) ? "a una" : "o un") > 0) return 1; if (player->spvsend(pvulture.server, sshell) > 0) return 1; } } else { player->logics.delvalue("GROUP", "Moderator"); if ((player->logics.addvalue("GROUP", "User", 1) > 0) || (player->logics.delvalue("GROUP", 2) > 0) || (player->logics.addvalue("GROUP", "Membro", 2) > 0)) LOG_ERROR("Unable to add/remove GROUP->Rule Logic"); else { if (infos.player->pvsend(pvulture.server, "[reset][blue]%s non e' piu' %s vice[n]", charactername = pvulture.characters.gettargetname(player, infos.player), (player->getsex() != MALE) ? "una" : "un") > 0) return 1; if (player->pvsend(pvulture.server, "[reset][n][blue]l'incarico di vice ti e' stato tolto![n]") > 0) return 1; if (player->spvsend(pvulture.server, sshell) > 0) return 1; } } } else if (infos.player->pvsend(pvulture.server, "[reset]non fa parte del tuo stesso gruppo![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]stai parlando di te stess%s![n]", (infos.player->getsex() != MALE) ? "a" : "o") > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } return 0; } int PVgroup::moderator(Cmob *mob) { char *charactername = NULL; if ((mob->logics.hascategory("GROUP") == 0) && (compare.vcmpcase(infos.player->logics.getvalue("GROUP", 3), mob->logics.getvalue("GROUP", 3)) == 0)) { if (mob->logics.hasvalue("GROUP", "Moderator") != 0) { mob->logics.delvalue("GROUP", "User"); if ((mob->logics.addvalue("GROUP", "Moderator", 1) > 0) || (mob->logics.delvalue("GROUP", 2) > 0) || (mob->logics.addvalue("GROUP", "Vice", 2) > 0)) LOG_ERROR("Unable to add/remove GROUP->Rule Logic"); else if (infos.player->pvsend(pvulture.server, "[reset][blue]%s e' ora %s vice[n]", charactername = pvulture.characters.gettargetname(mob, infos.player), (mob->getsex() != MALE) ? "una" : "un") > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } } else { mob->logics.delvalue("GROUP", "Moderator"); if ((mob->logics.addvalue("GROUP", "User", 1) > 0) || (mob->logics.delvalue("GROUP", 2) > 0) || (mob->logics.addvalue("GROUP", "Membro", 2) > 0)) LOG_ERROR("Unable to add/remove GROUP->Rule Logic"); else if (infos.player->pvsend(pvulture.server, "[reset][blue]%s non e' piu' %s vice[n]", charactername = pvulture.characters.gettargetname(mob, infos.player), (mob->getsex() != MALE) ? "una" : "un") > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } } } else if (infos.player->pvsend(pvulture.server, "[reset]non fa parte del tuo stesso gruppo![n]") > 0) return 1; return 0; } int PVgroup::bounce(char *string) { Cmob *mob = NULL; Cplayer *player = NULL; if ((player = pvulture.characters.getplayer(string)) && (player->position)) { if (infos.player->getID() != player->getID()) { if ((player->logics.hascategory("GROUP") == 0) && (compare.vcmpcase(player->logics.getvalue("GROUP", 3), infos.player->logics.getvalue("GROUP", 3)) == 0)) { if ((infos.player->position->getID() != player->position->getID()) || (infos.player->position->getzoneID() != player->position->getzoneID())) { if (infos.player->position->getplayer(infos.player->getID())) { if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1; } if (infos.player->pvsend(pvulture.server, "[reset][green]ti muovi presso %s[n]", string) > 0) return 1; if (infos.player->logics.hasvalue("STATUS", "Hide") != 0) { if (spvsend(pvulture.server, infos.player->position, "[reset][n][yellow]$name scompare in una nuvola di fumo[n]", (Ccharacter *) infos.player) > 0) return 1; if (spvsend(pvulture.server, player->position, "[reset][n][yellow]$name appare da una nuvola di fumo[n]", (Ccharacter *) infos.player) > 0) return 1; if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1; if (player->position->spvsend(pvulture.server, sshell) > 0) return 1; } if (player->position->addplayer(infos.player) > 0) return 1; if (environmentcommands.lookenvironment() > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]si trova proprio qui![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non fa parte del tuo gruppo![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset][reset]stai parlando di te stess%s![n]", (infos.player->getsex() != MALE) ? "a" : "o") > 0) return 1; } else if ((mob = pvulture.characters.getmob(message)) && (mob->position)) { if ((mob->logics.hascategory("GROUP") == 0) && (compare.vcmpcase(mob->logics.getvalue("GROUP", 3), infos.player->logics.getvalue("GROUP", 3)) == 0)) { if ((infos.player->position->getID() != mob->position->getID()) || (infos.player->position->getzoneID() != mob->position->getzoneID())) { if (infos.player->position->getplayer(infos.player->getID())) { if (infos.player->position->delplayer(infos.player->getID()) > 0) return 1; } if (infos.player->pvsend(pvulture.server, "[reset][green]ti muovi presso %s[n]", string) > 0) return 1; if (infos.player->logics.hasvalue("STATUS", "Hide") != 0) { if (spvsend(pvulture.server, infos.player->position, "[reset][n][yellow]$name scompare in una nuvola di fumo[n]", (Ccharacter *) infos.player) > 0) return 1; if (spvsend(pvulture.server, player->position, "[reset][n][yellow]$name appare da una nuvola di fumo[n]", (Ccharacter *) infos.player) > 0) return 1; if (infos.player->position->spvsend(pvulture.server, sshell) > 0) return 1; if (mob->position->spvsend(pvulture.server, sshell) > 0) return 1; } if (mob->position->addplayer(infos.player) > 0) return 1; if (environmentcommands.lookenvironment() > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]si trova proprio qui![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non fa parte del tuo gruppo![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non c'e' nessuno con quel nome in questo mondo![n]") > 0) return 1; return 0; } int PVgroup::chat(char *string) { playerslist *player = pvulture.characters.gamecharacters.playersroot; char *groupname = infos.player->logics.getvalue("GROUP", 3), *charactername = NULL, *emoticon = NULL, *message = NULL; if ((message = (char *) pvmalloc(strlen(string) + 1))) { strcpy(message, string); message[strlen(string)] = '\0'; emoticon = getemoticon(&message); if (message) { while (player) { if ((infos.player->getID() != player->player->getID()) && (player->player->logics.hasvalue("GROUP", groupname) == 0)) { if (player->player->pvsend(pvulture.server, "[n][reset][blue]%s vi dice %s: \"%s\"[reset][n]", charactername = pvulture.characters.gettargetname(infos.player, player->player), (emoticon) ? emoticon : "", message) > 0) return 1; if (player->player->spvsend(pvulture.server, sshell) > 0) return 1; if (charactername) { pvfree(charactername); charactername = NULL; } } player = player->next; } if (infos.player->pvsend(pvulture.server, "[reset][blue]dici al tuo gruppo %s: \"%s\"[reset][n]", (emoticon) ? emoticon : "", message) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un messaggio![n]") > 0) return 1; } else return 1; if (emoticon) { pvfree(emoticon); emoticon = NULL; } if (message) { pvfree(message); message = NULL; } return 0; } int PVgroup::list(void) { mobslist *mob = pvulture.characters.gamecharacters.mobsroot; playerslist *player = pvulture.characters.gamecharacters.playersroot; char *groupname = infos.player->logics.getvalue("GROUP", 3); if (infos.player->pvsend(pvulture.server, "membri del gruppo \"[bold]%s[reset]\" ora collegati:[n]", groupname) > 0) return 1; while (player) { if ((player->player->getID() != infos.player->getID()) && (player->player->logics.hasvalue("GROUP", groupname) == 0)) { if (player->player->logics.hasvalue("STATUS", "Password") != 0) { if (infos.player->pvsend(pvulture.server, "\t[reset][green](online)[reset]%s(%d) %s[n]", ((player->player->logics.hasvalue("GROUP", "Admin") != 0) ? ((player->player->logics.hasvalue("GROUP", "Moderator") != 0) ? "" : "[yellow]") : "[green]"), player->player->getID(), pvulture.characters.getsimplename(player->player)) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "\t[reset][yellow](passwd)[reset]%s(%d) %s[n]", ((player->player->logics.hasvalue("GROUP", "Admin") != 0) ? ((player->player->logics.hasvalue("GROUP", "Moderator") != 0) ? "" : "[yellow]") : "[green]"), player->player->getID(), pvulture.characters.getsimplename(player->player)) > 0) return 1; } player = player->next; } while (mob) { if (mob->mob->logics.hasvalue("GROUP", groupname) == 0) if (infos.player->pvsend(pvulture.server, "\t[reset][green](online)[reset]%s(%d) %s[n]", (infos.player->logics.hasvalue("GROUP", "Moderator") != 0) ? "" : "[yellow]", mob->mob->getID(), pvulture.characters.getsimplename(mob->mob)) > 0) return 1; mob = mob->next; } return 0; } int PVgroup::destroy(void) { mobslist *mob = pvulture.characters.gamecharacters.mobsroot; playerslist *player = pvulture.characters.gamecharacters.playersroot; char *groupname = infos.player->logics.getvalue("GROUP", 3); if (groups.delvalue(groupname) > 0) LOG_ERROR("Unable to delete GROUPS->%s Logic", groupname); while (player) { if ((infos.player->getID() != player->player->getID()) && (player->player->logics.hasvalue("GROUP", groupname) == 0)) { if (player->player->logics.delcategory("GROUP") > 0) LOG_ERROR("Unable to delete GROUP Category"); if (player->player->pvsend(pvulture.server, "[n][blue]Il tuo gruppo e' stato sciolto![n]") > 0) return 1; if (player->player->spvsend(pvulture.server, sshell) > 0) return 1; } player = player->next; } while (mob) { if (mob->mob->logics.hasvalue("GROUP", groupname) == 0) { if (player->player->logics.delcategory("GROUP") > 0) LOG_ERROR("Unable to delete GROUP Category"); } mob = mob->next; } if (infos.player->logics.delcategory("GROUP") > 0) LOG_ERROR("Unable to delete GROUP Category"); return 0; } int PVgroup::information(void) { mobslist *mob = pvulture.characters.gamecharacters.mobsroot; playerslist *player = pvulture.characters.gamecharacters.playersroot; int index = 0; char *groupname = infos.player->logics.getvalue("GROUP", 3); while (player) { if (player->player->logics.hasvalue("GROUP", groupname) == 0) index++; player = player->next; } while (mob) { if (mob->mob->logics.hasvalue("GROUP", groupname) == 0) index++; mob = mob->next; } if (infos.player->pvsend(pvulture.server, "[reset]fai parte del gruppo [blue]\"[bold]%s[reset][blue]\"[reset]", infos.player->logics.getvalue("GROUP", 3)) > 0) return 1; if (compare.vcmpcase(infos.player->logics.getvalue("GROUP", 1), "Admin") == 0) { if (infos.player->pvsend(pvulture.server, " (di cui sei [green]il capo[reset]) ") > 0) return 1; } else if (compare.vcmpcase(infos.player->logics.getvalue("GROUP", 1), "Moderator") == 0) { if (infos.player->pvsend(pvulture.server, " (di cui sei [yellow]un vice[reset]) ") > 0) return 1; } if (infos.player->pvsend(pvulture.server, "che conta %d membri![n]\t[reset]il tuo ruolo e' [blue]\"[bold]%s[reset][blue]\"[reset][n]", index, infos.player->logics.getvalue("GROUP", 2)) > 0) return 1; return 0; } PVgroup groupcommands; int group(void) { char *message = NULL, *command = NULL, *subcommand = NULL; if ((message = (char *) pvmalloc(strlen(infos.message) + 1))) { strcpy(message, infos.message); message[strlen(infos.message)] = '\0'; if ((command = strings.vpop(&message)) && (subcommand = strings.vpop(&message))) { if (compare.vcmpcase(subcommand, CSTRSIZE("crea")) == 0) { if (message) { if (groupcommands.build(message) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un nome![n]") > 0) return 1; } else if (infos.player->logics.hascategory("GROUP") == 0) { if (compare.vcmpcase(subcommand, CSTRSIZE("abbandona")) == 0) { if (groupcommands.exit() > 0) return 1; } else if (compare.vcmpcase(subcommand, CSTRSIZE("lista")) == 0) { if (groupcommands.list() > 0) return 1; } else if (compare.vcmpcase(subcommand, CSTRSIZE("info")) == 0) { if (groupcommands.information() > 0) return 1; } else if (compare.vcmpcase(subcommand, CSTRSIZE("di")) == 0) { if (message) { if (groupcommands.chat(message) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un messaggio![n]") > 0) return 1; } else if ((infos.player->logics.hasvalue("GROUP", "Admin") == 0) || (infos.player->logics.hasvalue("GROUP", "Moderator") == 0)) { if (compare.vcmpcase(subcommand, CSTRSIZE("caccia")) == 0) { if (message) { if (groupcommands.kick(message) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un nome![n]") > 0) return 1; } else if (compare.vcmpcase(subcommand, CSTRSIZE("aggiungi")) == 0) { if (message) { if (groupcommands.add(message) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un nome![n]") > 0) return 1; } else if (infos.player->logics.hasvalue("GROUP", "Admin") == 0) { if (compare.vcmpcase(subcommand, CSTRSIZE("ruolo")) == 0) { if (message) { if (groupcommands.rule(message) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un ruolo![n]") > 0) return 1; } else if (compare.vcmpcase(subcommand, CSTRSIZE("moderatore")) == 0) { if (message) { if (groupcommands.moderator(message) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un nome![n]") > 0) return 1; } else if (compare.vcmpcase(subcommand, CSTRSIZE("cedi")) == 0) { if (message) { if (groupcommands.transfer(message) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un nome![n]") > 0) return 1; } else if (compare.vcmpcase(subcommand, CSTRSIZE("vai")) == 0) { if (message) { if (groupcommands.bounce(message) > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]e' necessario specificare un nome![n]") > 0) return 1; } else if (compare.vcmpcase(subcommand, CSTRSIZE("sciogli")) == 0) { if (groupcommands.destroy() > 0) return 1; if (infos.player->pvsend(pvulture.server, "[reset][green]hai sciolto il tuo gruppo![n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non esiste quel comando[n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non esiste quel comando[n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non esiste quel comando[n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]non esiste quel comando[n]") > 0) return 1; } else if (infos.player->pvsend(pvulture.server, "[reset]prego?[n]") > 0) return 1; } else return 1; if (subcommand) { pvfree(subcommand); subcommand = NULL; } if (command) { pvfree(command); command = NULL; } if (message) { pvfree(message); message = NULL; } return 0; }
54.178025
193
0.507753
nardinan
21462d66e49eaeaa64b3b399bc64b9b1e175fbd7
28,371
cpp
C++
src/cui/EntisGLS/EntisGLS.cpp
MaiReo/crass
11579527090faecab27f98b1e221172822928f57
[ "BSD-3-Clause" ]
1
2021-07-21T00:58:45.000Z
2021-07-21T00:58:45.000Z
src/cui/EntisGLS/EntisGLS.cpp
MaiReo/crass
11579527090faecab27f98b1e221172822928f57
[ "BSD-3-Clause" ]
null
null
null
src/cui/EntisGLS/EntisGLS.cpp
MaiReo/crass
11579527090faecab27f98b1e221172822928f57
[ "BSD-3-Clause" ]
null
null
null
#include <windows.h> #include <tchar.h> #include <crass_types.h> #include <acui.h> #include <cui.h> #include <package.h> #include <resource.h> #include <cui_error.h> #include <stdio.h> #include <crass/locale.h> #include <utility.h> #include <vector> #include <string> #include <xerisa.h> /* 【game参数游戏支持列表】 ·ドS姉とボクの放尿関係 game=ane ·要!エプロン着用 体验版 game=ApronedOnly ·いろは ~秋の夕日に影ふみを~ 体験版 game=rural ·Alea -アレア- 紅き月を遙かに望み 体験版 game=Alea ·donor[ドナー] 体験版 game=donor ·絶対女子寮域!体験版 game=aftrial ·淫乳ファミレス ~深夜の母乳サービスはいかが? game=fami ·隣り妻2 ~淫惑の閨房~ 体験版 game=NWives2 ·アメサラサ ~雨と不思議な君に、恋をする 体験版 game=ame Chanter(シャンテ) -キミの歌がとどいたら-.rar [081205]ヨスガノソラ 搜索密码: C源码 00405060 /$ 83EC 10 SUB ESP,10 ; dec 00405063 |. 53 PUSH EBX 00405064 |. 55 PUSH EBP 00405065 |. 8BE9 MOV EBP,ECX ; cxt0 00405067 |. 56 PUSH ESI 00405068 |. 57 PUSH EDI 00405069 |. 8B4D 14 MOV ECX,DWORD PTR SS:[EBP+14] ; (0)i? 0040506C |. 8D41 01 LEA EAX,DWORD PTR DS:[ECX+1] ; ++i 0040506F |. 8945 14 MOV DWORD PTR SS:[EBP+14],EAX 00405072 |. 8B5D 0C MOV EBX,DWORD PTR SS:[EBP+C] ; (0x20)ERISADecodeContextLength 00405075 |. 8B55 08 MOV EDX,DWORD PTR SS:[EBP+8] ; 113fa90? ERISADecodeContext 00405078 |. 3BC3 CMP EAX,EBX ; orig_i VS ERISADecodeContextLength 0040507A |. 895C24 18 MOV DWORD PTR SS:[ESP+18],EBX ; save ERISADecodeContextLength 0040507E |. 895424 1C MOV DWORD PTR SS:[ESP+1C],EDX ; ERISADecodeContext <-- 查看这个buffer 00405082 |. 7C 07 JL SHORT noa32c.0040508B 00405084 |. C745 14 00000>MOV DWORD PTR SS:[EBP+14],0 ; i = 0 0040508B |> 8D7D 58 LEA EDI,DWORD PTR SS:[EBP+58] ; array32_1 0040508E |. BA A8FFFFFF MOV EDX,-58 ; -58 <---关键字 00405093 |. 8BC7 MOV EAX,EDI ; array32_1 00405095 |. 2BD5 SUB EDX,EBP ; -58 - obj 00405097 |> C640 C0 00 /MOV BYTE PTR DS:[EAX-40],0 ; memset(array32_0, 0, 32) 0040509B |. C600 00 |MOV BYTE PTR DS:[EAX],0 ; memset(array32_1, 0, 32) 汇编: ERIBshfBuffer@@DecodeBuffer PROC NEAR32 SYSCALL USES ebx esi edi mov ebx, ecx ASSUME ebx:PTR ERIBshfBuffer ; ; 復号の準備 ; mov eax, [ebx].m_dwPassOffset mov esi, eax ; esi = iPos inc eax xor edx, edx .IF eax >= [ebx].m_strPassword.m_nLength xor eax, eax .ENDIF mov [ebx].m_dwPassOffset, eax ; xor ecx, ecx .REPEAT mov DWORD PTR [ebx].m_bufBSHF[ecx], edx mov DWORD PTR [ebx].m_maskBSHF[ecx], edx add ecx, 4 .UNTIL ecx >= 32 ; ; 暗号を復号 ; xor edi, edi ; edi = iBit mov edx, [ebx].m_strPassword.m_pszString 《---密码 push ebp mov ebp, 256 .REPEAT movzx eax, BYTE PTR [edx + esi] inc esi add edi, eax cmp esi, [ebx].m_strPassword.m_nLength sbb edx, edx and edi, 0FFH mov eax, edi mov ecx, edi shr eax, 3 and esi, edx mov dl, 80H and ecx, 07H shr dl, cl ; .WHILE [ebx].m_maskBSHF[eax] == 0FFH inc eax add edi, 8 and eax, 1FH 《-- 关键指令 and edi, 0FFH .ENDW 断点挺直后,搜索内存,关键字key=,然后dump这段内存,保存的就是xml数据 */ /* exe内藏加密资源型密码分析用: M:\Program Files\highsox\愨懳彈巕椌堟両 懱尡斉 exe内藏加密资源型密码测试用: Q:\Program Files\highsox\SpycyTrial exe加壳,密码未知: Q:\[unpack]\[noa](18禁ゲーム)すぺ~す☆とらぶる */ using namespace std; using std::vector; static int debug; static int EntisGLS_locale_id; static const TCHAR *simplified_chinese_strings[] = { _T("%s: crc校验失败(0x%08x), 应该是0x%08x.\n"), _T("%s: 指定的exe文件不存在, 请在exe=的后面用\"\"把路径信息括起来.\n"), }; static const TCHAR *traditional_chinese_strings[] = { _T("%s: crc校驗失敗(0x%08x), 應該是0x%08x.\n"), _T("%s: 指定的exe文件不存在, 請在exe=的後面用\"\"把路徑信息括起來.\n"), }; static const TCHAR *japanese_strings[] = { _T("%s: crcチェック失敗(0x%08x)、もとい0x%08x。\n"), _T("%s: 指定されたexeファイルは存在しません、exe=の後に\"\"でパスメッセージを括ってください。\n"), }; static const TCHAR *default_strings[] = { _T("%s: crc error(0x%08x), shoule be 0x%08x.\n"), _T("%s: the exe file specified doesn't exist, please add \"\" pair to surond the path information behind exe=.\n"), }; static struct locale_configuration EntisGLS_locale_configurations[4] = { { 936, simplified_chinese_strings, 2 }, { 950, traditional_chinese_strings, 2 }, { 932, japanese_strings, 2 }, { 0, default_strings, 2 }, }; /* 接口数据结构: 表示cui插件的一般信息 */ struct acui_information EntisGLS_cui_information = { _T("Leshade Entis, Entis-soft."), /* copyright */ _T("Entis Generalized Library Set version 3"), /* system */ _T(".noa .dat .arc"), /* package */ _T("0.5.0"), /* revision */ _T("痴漢公賊"), /* author */ _T("2009-5-2 17:08"), /* date */ NULL, /* notion */ ACUI_ATTRIBUTE_LEVEL_DEVELOP }; /* 所有的封包特定的数据结构都要放在这个#pragma段里 */ #pragma pack (1) typedef struct { s8 header_code[8]; // "Entis\x1a\x00\x00" /* erisafile.h: fidArchive = 0x02000400, fidRasterizedImage = 0x03000100, fidEGL3DSurface = 0x03001100, fidEGL3DModel = 0x03001200, fidUndefinedEMC = -1 */ u32 file_id; u32 reserved; // 0 s8 format_desc[40]; u32 record_len_lo; u32 record_len_hi; } noa_header_t; typedef struct { s8 dir_record_code[8]; // "DirEntry" u32 dir_record_len_lo; u32 dir_record_len_hi; //u32 index_entries; // 包含在dir_record_len } noa_dir_record_t; typedef struct { u32 data_len_lo; // 原始长度 u32 data_len_hi; /* erisafile.h: attrNormal = 0x00000000, attrReadOnly = 0x00000001, attrHidden = 0x00000002, attrSystem = 0x00000004, attrDirectory = 0x00000010, attrEndOfDirectory = 0x00000020, attrNextDirectory = 0x00000040 */ u32 attribute; /* erisafile.h: etRaw = 0x00000000, // /raw etERISACode = 0x80000010, // default or /r etBSHFCrypt = 0x40000000, // /bshf etERISACrypt = 0xC0000010 */ u32 encode_type; u32 data_offset_lo; // 相对于目录项 u32 data_offset_hi; u8 second; u8 minute; u8 hour; u8 week; u8 day; u8 month; u16 year; u32 extra_info_len; u8 *extra_info; u32 name_len; u8 *name; } noa_dir_record_info_t; typedef struct { s8 file_record_code[8]; // "filedata" u32 file_record_len_lo; u32 file_record_len_hi; } noa_file_record_t; #pragma pack () typedef struct { char path[MAX_PATH]; u64 offset; u64 length; u32 extra_info_len; u8 *extra_info; u32 encode_type; u32 attr; } my_noa_entry_t; struct game_key_sub_table { char path[32]; // 封包名 char password[256]; }; struct game_key_table { char caption[128]; // 游戏名 unsigned int number; struct game_key_sub_table sub_table[32]; }; static struct game_key_table default_key_table = { "default", 1, { { "", " " }, } }; // 对于exe不能提取的游戏(比如exe加壳),使用game参数 static struct game_key_table game_key_table_list[] = { #if 0 /* 要!エプロン着用 体验版(临时用) */ { "ApronedOnly", 1, { { "ContainerB.noa", "7DQ1Xm7ZahIv1ZwlFgyMTMryKC6OP9V6cAgL64WD5JLyvmeEyqTSA5rUbRigOtebnnK4MuOptwsbOf4K8UBDH4kpAUOQgB71Qr1qxtHGxQl8KZKj6WIYWpPh0G3JOJat" } } }, /* Alea -アレア- 紅き月を遙かに望み 体験版(临时用) */ { "Alea", 1, { { "Data2.noa", "faTSgh75PfbZHctOvW3hHphnA7LEaa8gm5qMcI5Bn4eZa3bzbRwA8E4CnNocr2pG16KMdhSyZSiRJ1b27ECw2RSsIyfxsgFyworNlq6q7qYnqZ9SO2cnQws4hFGjb9Dl" } } }, /* donor[ドナー] 体験版(临时用) */ { "donor", 2, { { "data1.noa", "vfhvbqwydyqgbpv6teq" }, { "data3.noa", "vdsygo3423byfwo" } } }, /* 絶対女子寮域!体験版(临时用) */ { "aftrial", 1, { "ContainerB.noa", "XFwcnU1Qn3mUICUv" "pw1KgEuc9eVRZWQz" "DtKgf9dSQSNcnB6O" "YvntbzwULCU81Lvx" "WLJFX64NvGPKMUPx" "lKrUVJaNHCzfdkCQ" "wXYp7rI6fsi4T1nV" "4rg75JoiXnTbkQFM" } }, /* ドS姉とボクの放尿関係(临时用) */ { "ane", 2, { { "d02.dat", "vwerc7s65r21bnfu" }, { "d03.dat", "ctfvgbhnj67y8u" } } }, { "SpaceTrouble", 1, #if 0 { "PtOJsyBhKoZHH4Lm" "9trW0EAhVWc5ufMR" "Xl7MoYsnOHfhRyRN" "n4ka4q9SddgGCVL2" "tPbIrLLTgejeSbnA" "UYVYYUY2YV12YVU9" "IF09IV32IV31NV12" "RAW8DXT1DXT2DXT3" "DXT4DXT5NVHSNVHU" "NVCSNVBF" "Z062D9322446GM" } #endif }, /* 淫乳ファミレス~深夜の母乳サービスはいかが?(临时用) */ { "fami", 2, { { "d01.dat", "vdiu$43AfUCfh9aksf" }, { "d03.dat", "gaivnwq7365e021gf" }, } }, /* 隣り妻2 体験版(临时用) */ { "NWives2", 2, { { "Data6.noa", "ahyohsimohfaish1ao6ohh6edoh1yeezooDooj4Eabie0Aik4neeJohl0doo6fie2Iedao4poh9ahMoothohm3ba5LieC2beeba3hiyu1wit2fachae2Eecheed5kahc" }, { "Data7.noa", "fee4Thaixuol2siema2azeiha7Quek2Egh5soov1soich1haeShu2Vuashai6ba1Gejei0eonooz0cooliciexoh1WohmaBaemaezieraibeevohjeceiT5eecogh1eo" }, } }, /* アメサラサ ~雨と不思議な君に、恋をする 体験版(临时用) */ { "ame", 1, { { "system.noa", "lipsync" } } }, /* いろは ~秋の夕日に影ふみを~ 体験版(临时用) */ { "rural", 2, { { "scenario.noa", "0XT9ORIT0WlIl7U16yjKxTCyUOYZoN1cL7FxrBTiuvi0EY50b7Pu8uvLVlX0opOU5ash97Bkkqq" }, { "graphics02.noa", "2o3bZEwqb9JMfkU4CYv2BaAD2sSdyUxtiAR4IQWG8UP6EmWkN0JcA9nmV6MAHH3AspaGBUqib3i" } } }, #endif /* 终止项 */ { "", 0, } }; /* 包含运行时需要的所有可能的tbl */ static vector<struct game_key_table> runtime_game_key_table; static struct game_key_sub_table *cur_sub_table; //static BYTE BshfCode[512]; //static DWORD BshfCodePos; //static DWORD BshfCodeLen; static u32 ERISACrc(BYTE *data, DWORD data_len) { BYTE crc[4] = { 0, 0, 0, 0 }; for (DWORD i = 0; i < data_len; ++i) crc[i & 3] ^= data[i]; return crc[0] | (crc[1] << 8) | (crc[2] << 16) | (crc[3] << 24); } #if 0 static void ERIBshfDecodeInit(const char *password) { int len; if (!password) password = " "; len = strlen(password); strcpy((char *)BshfCode, password); if (len < 32) { BshfCode[len++] = 0x1b; for (DWORD i = len; i < 32; ++i) BshfCode[i] = BshfCode[i - 1] + BshfCode[i % len]; len = 32; } BshfCodeLen = len; BshfCodePos = 0; if (debug) { printf("Dump BshfCode (%d bytes)\n", len); printf("Use password: \"%s\"\n", password); for (DWORD i = 0; i < len; ++i) printf("0x%02x ", BshfCode[i]); printf("\n"); } } static int __ERIBshfDecode(BYTE *BSHF_dst, DWORD BSHF_dst_len, BYTE *BSHF_src, DWORD BSHF_src_len) { DWORD act_BSHF_dst_len = 0; u32 crc = *(u32 *)&BSHF_src[BSHF_src_len - 4]; for (DWORD i = 0; i < BSHF_src_len / 32; ++i) { BYTE BSHF_mask[32]; BYTE BSHF_buf[32]; BYTE bit = 0; BYTE cur = i; memset(BSHF_mask, 0, sizeof(BSHF_mask)); memset(BSHF_buf, 0, sizeof(BSHF_buf)); for (DWORD k = 0; k < 256; ++k) { bit += BshfCode[cur++ % BshfCodeLen]; BYTE mask = 0x80 >> (bit & 7); while (BSHF_mask[bit / 8] == 0xff) bit += 8; while (BSHF_mask[bit / 8] & mask) { ++bit; mask >>= 1; if (!mask) { bit += 8; mask = 0x80; } } BSHF_mask[bit / 8] |= mask; if (BSHF_src[k / 8] & (0x80 >> (k & 7))) BSHF_buf[bit / 8] |= mask; } BSHF_src += 32; for (k = 0; k < 32; ++k) { BSHF_dst[act_BSHF_dst_len++] = BSHF_buf[k]; if (act_BSHF_dst_len >= BSHF_dst_len) goto out; } } out: return ERISACrc(BSHF_dst, act_BSHF_dst_len, crc); } #endif #if 1 static int ERIBSHFDecode(BYTE *dec, DWORD dec_len, BYTE *enc, DWORD enc_len, char *pwd) { EMemoryFile DEC; DEC.Open(enc, enc_len); ESLFileObject *file = DEC.Duplicate(); ERISADecodeContext BSHF(dec_len); BSHF.AttachInputFile(file); BSHF.PrepareToDecodeBSHFCode(pwd); EStreamBuffer buf; BYTE *ptrBuf = (BYTE *)buf.PutBuffer(dec_len); int ret = BSHF.DecodeBSHFCodeBytes((SBYTE *)ptrBuf, dec_len); if (ret > 0) memcpy(dec, ptrBuf, dec_len); delete file; return ret; } #else static int ERIBshfDecode(BYTE *BSHF_dst, DWORD BSHF_dst_len, BYTE *BSHF_src, DWORD BSHF_src_len) { int ret = __ERIBshfDecode(BSHF_dst, BSHF_dst_len, BSHF_src, BSHF_src_len); if (!ret) { for (DWORD i = 0; i < runtime_game_key_table.size(); ++i) { struct game_key_table &tbl = runtime_game_key_table[i]; for (DWORD k = 0; k < tbl.number; ++k) { if (cur_sub_table && cur_sub_table == &tbl.sub_table[k]) continue; ERIBshfDecodeInit(tbl.sub_table[k].password); ret = __ERIBshfDecode(BSHF_dst, BSHF_dst_len, BSHF_src, BSHF_src_len); if (ret) { cur_sub_table = &tbl.sub_table[k]; return 1; } } } } cur_sub_table = default_key_table.sub_table; return ret; } #endif static void parse_xml_data(char *xml_cfg) { string xml = xml_cfg; string::size_type begin, end; char game[256] = "no_name"; int game_name_len = strlen(game); struct game_key_table entry; unsigned int &i = entry.number; begin = xml.find("<display caption=\"", 0); if (begin != string::npos) { begin += strlen("<display caption=\""); end = xml.find("\"", begin); if (end == string::npos) return; memcpy(game, &xml[begin], end - begin); game_name_len = end - begin; } begin = 0; i = 0; while ((begin = xml.find("<archive ", begin)) != string::npos) { end = xml.find("/>", begin); if (end == string::npos) break; string::size_type path = xml.find("path=", begin); if (path == string::npos || path >= end) break; string::size_type key = xml.find("key=", begin); if (key == string::npos || key >= end) { begin = end + 2; continue; } memset(entry.sub_table[i].password, 0, sizeof(entry.sub_table[i].password)); memcpy(entry.sub_table[i].password, &xml[key + 5] /* "key=\"" */, end - key - 5 /* "key=\"" */ - 1 /* "\"" */); memset(entry.sub_table[i].path, 0, sizeof(entry.sub_table[i].path)); string::size_type dim; dim = xml.rfind("\\", key - 1); if (dim == string::npos || dim <= path) dim = path + 6 /* "path=\"" */; else ++dim; // 通常情况,xml里会对加密的noa所在光盘和硬盘上不同的位置有 // 2组key,内容都一样,所以这里进行检查,不加入重复的key。 for (DWORD k = 0; k < i; ++k) { if (!strcmp(entry.sub_table[k].path, &xml[dim])) goto not_insert; } memcpy(entry.sub_table[i].path, &xml[dim], key - 1 /* " " */ - dim - 1 /* "\"" */); not_insert: begin = end + 2; ++i; } if (i) { game[game_name_len] = 0; strcpy(entry.caption, game); runtime_game_key_table.push_back(entry); } } static int load_exe_xml(const char *exe_file) { if (!exe_file) return 0; HMODULE exe = LoadLibraryA(exe_file); if ((DWORD)exe > 31) { HRSRC code = FindResourceA(exe, "IDR_COTOMI", (const char *)RT_RCDATA); if (code) { DWORD sz = SizeofResource(exe, code); HGLOBAL hsrc = LoadResource(exe, code); if (hsrc) { LPVOID cipher = LockResource(hsrc); if (cipher) { EMemoryFile xml; xml.Open(cipher, sz); ERISADecodeContext ERISA(0x10000); ESLFileObject *dup = xml.Duplicate(); ERISA.AttachInputFile(dup); ERISA.PrepareToDecodeERISANCode(); EStreamBuffer buf; BYTE *ptrBuf = (BYTE *)buf.PutBuffer(0x10000); unsigned int Result = ERISA.DecodeERISANCodeBytes((SBYTE *)ptrBuf, 0x10000); if (debug) MySaveFile(_T("exe.xml"), ptrBuf, Result); parse_xml_data((char *)ptrBuf); delete dup; return runtime_game_key_table.size(); } FreeResource(hsrc); } } FreeLibrary(exe); } else { TCHAR exe_path[MAX_PATH]; acp2unicode(exe_file, -1, exe_path, MAX_PATH); locale_app_printf(EntisGLS_locale_id, 1, exe_path); } return 0; } /********************* noa *********************/ /* 封包匹配回调函数 */ static int EntisGLS_noa_match(struct package *pkg) { noa_header_t noa_header; if (pkg->pio->open(pkg, IO_READONLY)) return -CUI_EOPEN; if (pkg->pio->read(pkg, &noa_header, sizeof(noa_header))) { pkg->pio->close(pkg); return -CUI_EREAD; } if (memcmp(noa_header.header_code, "Entis\x1a\x00\x00", 8) || noa_header.file_id != 0x02000400 || noa_header.reserved) { pkg->pio->close(pkg); return -CUI_EMATCH; } //BshfCodePos = 0; return 0; } static int noa_dir_record_process(struct package *pkg, vector<my_noa_entry_t> &my_noa_index, char *path_name) { u64 base_offset; pkg->pio->locate64(pkg, (u32 *)&base_offset, ((u32 *)&base_offset) + 1); noa_dir_record_t dir_rec; if (pkg->pio->read(pkg, &dir_rec, sizeof(dir_rec))) return -CUI_EREAD; if (strncmp(dir_rec.dir_record_code, "DirEntry", sizeof(dir_rec.dir_record_code))) return -CUI_EMATCH; BYTE *dir_rec_info = new BYTE[dir_rec.dir_record_len_lo]; if (!dir_rec_info) return -CUI_EMEM; if (pkg->pio->read(pkg, dir_rec_info, dir_rec.dir_record_len_lo)) { delete [] dir_rec_info; return -CUI_EREAD; } BYTE *p_dir = dir_rec_info; u32 index_entries = *(u32 *)p_dir; p_dir += 4; int ret = 0; for (DWORD i = 0; i < index_entries; ++i) { my_noa_entry_t entry; entry.length = *(u64 *)p_dir; p_dir += 8; u32 attr = *(u32 *)p_dir; p_dir += 4; entry.attr = attr; entry.encode_type = *(u32 *)p_dir; p_dir += 4; entry.offset = *(u64 *)p_dir + base_offset; p_dir += 16; // bypass filetime entry.extra_info_len = *(u32 *)p_dir; p_dir += 4; if (entry.extra_info_len) { entry.extra_info = new BYTE[entry.extra_info_len]; if (!entry.extra_info) break; } else entry.extra_info = NULL; p_dir += entry.extra_info_len; sprintf(entry.path, "%s\\%s", path_name, (char *)p_dir + 4); p_dir += 4 + *(u32 *)p_dir; my_noa_index.push_back(entry); if (attr == 0x00000010) { // attrDirectory noa_file_record_t file_rec; // 目录项也是个filedata if (pkg->pio->readvec64(pkg, &file_rec, sizeof(file_rec), 0, (u32)entry.offset, (u32)(entry.offset >> 32), IO_SEEK_SET)) { ret = -CUI_EREADVEC; break; } ret = noa_dir_record_process(pkg, my_noa_index, entry.path); if (ret) break; } else if (attr == 0x00000020) { // attrEndOfDirectory printf("attrEndOfDirectory!!\n");exit(0); } else if (attr == 0x00000040) { // attrNextDirectory printf("attrNextDirectory!!\n");exit(0); } } delete [] dir_rec_info; return ret; } /* 封包索引目录提取函数 */ static int EntisGLS_noa_extract_directory(struct package *pkg, struct package_directory *pkg_dir) { vector<my_noa_entry_t> my_noa_index; int ret; my_noa_entry_t root_dir; memset(&root_dir, 0, sizeof(root_dir)); root_dir.attr = 0x00000010; my_noa_index.push_back(root_dir); ret = noa_dir_record_process(pkg, my_noa_index, "."); if (ret) return ret; DWORD index_entries = 0; for (DWORD i = 0; i < my_noa_index.size(); ++i) { // printf("%d %s %x %x %x\n", i, my_noa_index[i].path, // my_noa_index[i].attr, my_noa_index[i].offset, // (u32)my_noa_index[i].length); if (my_noa_index[i].attr != 0x00000010 && my_noa_index[i].attr != 0x00000020 && my_noa_index[i].attr != 0x00000040) ++index_entries; } my_noa_entry_t *index = new my_noa_entry_t[index_entries]; if (!index) return -CUI_EMEM; DWORD k = 0; for (i = 0; i < my_noa_index.size(); ++i) { if (my_noa_index[i].attr == 0x00000010) { // attrDirectory if (my_noa_index[i].extra_info) delete [] my_noa_index[i].extra_info; } else if (my_noa_index[i].attr == 0x00000020) { // attrEndOfDirectory if (my_noa_index[i].extra_info) delete [] my_noa_index[i].extra_info; printf("attrEndOfDirectory!!\n");exit(0); } else if (my_noa_index[i].attr == 0x00000040) { // attrNextDirectory if (my_noa_index[i].extra_info) delete [] my_noa_index[i].extra_info; printf("attrNextDirectory!!\n");exit(0); } else index[k++] = my_noa_index[i]; } pkg_dir->index_entries = index_entries; pkg_dir->directory = index; pkg_dir->directory_length = index_entries * sizeof(my_noa_entry_t); pkg_dir->index_entry_length = sizeof(my_noa_entry_t); pkg_dir->flags = PKG_DIR_FLAG_SKIP0; return 0; } /* 封包索引项解析函数 */ static int EntisGLS_noa_parse_resource_info(struct package *pkg, struct package_resource *pkg_res) { my_noa_entry_t *my_noa_entry; my_noa_entry = (my_noa_entry_t *)pkg_res->actual_index_entry; strcpy(pkg_res->name, my_noa_entry->path); pkg_res->name_length = -1; /* -1表示名称以NULL结尾 */ pkg_res->raw_data_length = (u32)my_noa_entry->length; pkg_res->actual_data_length = (u32)my_noa_entry->length; pkg_res->offset = (u32)my_noa_entry->offset; return 0; } /* 封包资源提取函数 */ static int EntisGLS_noa_extract_resource(struct package *pkg, struct package_resource *pkg_res) { my_noa_entry_t *my_noa_entry = (my_noa_entry_t *)pkg_res->actual_index_entry; noa_file_record_t file_rec; u64 offset = my_noa_entry->offset; if (pkg->pio->readvec64(pkg, &file_rec, sizeof(file_rec), 0, (u32)offset, (u32)(offset >> 32), IO_SEEK_SET)) return -CUI_EREADVEC; u64 raw_len = (u64)file_rec.file_record_len_lo | ((u64)file_rec.file_record_len_hi << 32); BYTE *raw = new BYTE[(u32)raw_len]; if (!raw) return -CUI_EMEM; offset += sizeof(file_rec); if (pkg->pio->readvec64(pkg, raw, (u32)raw_len, (u32)(raw_len >> 32), (u32)offset, (u32)(offset >> 32), IO_SEEK_SET)) { delete [] raw; return -CUI_EREADVEC; } pkg_res->raw_data_length = raw_len; pkg_res->actual_data_length = my_noa_entry->length; if (my_noa_entry->encode_type == 0x00000000) // etRaw pkg_res->raw_data = raw; else if (my_noa_entry->encode_type == 0x80000010) { // etERISACode EMemoryFile dec; dec.Open(raw, pkg_res->raw_data_length); ERISADecodeContext ERISA(pkg_res->actual_data_length); ESLFileObject *dup = dec.Duplicate(); ERISA.AttachInputFile(dup); ERISA.PrepareToDecodeERISANCode(); EStreamBuffer buf; BYTE *ptrBuf = (BYTE *)buf.PutBuffer(pkg_res->actual_data_length); pkg_res->actual_data_length = ERISA.DecodeERISANCodeBytes((SBYTE *)ptrBuf, pkg_res->actual_data_length); BYTE *act = new BYTE[pkg_res->actual_data_length]; if (!act) { delete [] raw; return -CUI_EMEM; } memcpy(act, ptrBuf, pkg_res->actual_data_length); delete dup; pkg_res->raw_data = raw; pkg_res->actual_data = act; } else if (my_noa_entry->encode_type == 0x40000000) { // etBSHFCrypt #if 1 BYTE *act = new BYTE[pkg_res->actual_data_length]; if (!act) { delete [] raw; return -CUI_EMEM; } char pkg_name[MAX_PATH]; unicode2acp(pkg_name, MAX_PATH, pkg->name, -1); for (DWORD i = 0; i < runtime_game_key_table.size(); ++i) { struct game_key_table &tbl = runtime_game_key_table[i]; for (DWORD k = 0; k < tbl.number; ++k) { if (tbl.sub_table[k].path[0] && strcmpi(pkg_name, tbl.sub_table[k].path)) continue; if (!pkg_res->index_number && debug) { printf("%s: using password \"%s\"", pkg_name, tbl.sub_table[k].password); if (tbl.sub_table[k].path[0]) printf(" for %s\n\n", tbl.sub_table[k].path); } int act_len = ERIBSHFDecode(act, pkg_res->actual_data_length, raw, pkg_res->raw_data_length-4, tbl.sub_table[k].password); if (act_len <= 0) { delete [] act; delete [] raw; return -CUI_EUNCOMPR; } u32 crc = *(u32 *)&raw[pkg_res->raw_data_length-4]; u32 act_crc = ERISACrc(act, act_len); if (crc != act_crc) { WCHAR res_name[MAX_PATH]; acp2unicode(pkg_res->name, -1, res_name, MAX_PATH); locale_app_printf(EntisGLS_locale_id, 0, res_name, crc, act_crc); delete [] act; delete [] raw; return -CUI_EMATCH; } else { pkg_res->actual_data_length = act_len; goto out; } } } out: pkg_res->raw_data = raw; pkg_res->actual_data = act; #else BYTE *dec = new BYTE[pkg_res->actual_data_length]; if (!dec) { delete [] raw; return -CUI_EMEM; } if (!ERIBshfDecode(dec, pkg_res->actual_data_length, raw, raw_len)) { printf("%s: crc不正确, 可能是文件损坏或者需要指定正确的exe/game/pwd参数提供密码.\n", pkg_res->name); printf("%s: crc is incorrect, maybe the data is corrupt or need correct parameter exe/game/pwd to provide the password.\n", pkg_res->name); delete [] dec; delete [] raw; return -CUI_EMATCH; } delete [] raw; pkg_res->actual_data = dec; #endif } else if (my_noa_entry->encode_type == 0xC0000010) { // etERISACrypt printf("unsupport type etERISACrypt\n"); pkg_res->raw_data = raw; } else { printf("unsupport type unknown\n"); pkg_res->raw_data = raw; } return 0; } /* 资源保存函数 */ static int EntisGLS_noa_save_resource(struct resource *res, struct package_resource *pkg_res) { if (res->rio->create(res)) return -CUI_ECREATE; if (pkg_res->actual_data && pkg_res->actual_data_length) { if (res->rio->write(res, pkg_res->actual_data, pkg_res->actual_data_length)) { res->rio->close(res); return -CUI_EWRITE; } } else if (pkg_res->raw_data && pkg_res->raw_data_length) { if (res->rio->write(res, pkg_res->raw_data, pkg_res->raw_data_length)) { res->rio->close(res); return -CUI_EWRITE; } } res->rio->close(res); return 0; } /* 封包资源释放函数 */ static void EntisGLS_noa_release_resource(struct package *pkg, struct package_resource *pkg_res) { if (pkg_res->actual_data) { delete [] pkg_res->actual_data; pkg_res->actual_data = NULL; } if (pkg_res->raw_data) { delete [] pkg_res->raw_data; pkg_res->raw_data = NULL; } } /* 封包卸载函数 */ static void EntisGLS_noa_release(struct package *pkg, struct package_directory *pkg_dir) { if (pkg_dir->directory) { my_noa_entry_t *index = (my_noa_entry_t *)pkg_dir->directory; for (DWORD i = 0; i < pkg_dir->index_entries; ++i) delete [] index[i].extra_info; delete [] pkg_dir->directory; pkg_dir->directory = NULL; } pkg->pio->close(pkg); } /* 封包处理回调函数集合 */ static cui_ext_operation EntisGLS_noa_operation = { EntisGLS_noa_match, /* match */ EntisGLS_noa_extract_directory, /* extract_directory */ EntisGLS_noa_parse_resource_info, /* parse_resource_info */ EntisGLS_noa_extract_resource, /* extract_resource */ EntisGLS_noa_save_resource, /* save_resource */ EntisGLS_noa_release_resource, /* release_resource */ EntisGLS_noa_release /* release */ }; /* 接口函数: 向cui_core注册支持的封包类型 */ int CALLBACK EntisGLS_register_cui(struct cui_register_callback *callback) { if (callback->add_extension(callback->cui, _T(".noa"), NULL, _T("ERISA-Archive file(乃亞アーカイバ)"), &EntisGLS_noa_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_DIR | CUI_EXT_FLAG_RES | CUI_EXT_FLAG_RECURSION)) return -1; if (callback->add_extension(callback->cui, _T(".dat"), NULL, _T("ERISA-Archive file(乃亞アーカイバ)"), &EntisGLS_noa_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_DIR | CUI_EXT_FLAG_RES | CUI_EXT_FLAG_RECURSION)) return -1; if (callback->add_extension(callback->cui, _T(".arc"), NULL, _T("ERISA-Archive file(乃亞アーカイバ)"), &EntisGLS_noa_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_DIR | CUI_EXT_FLAG_RES | CUI_EXT_FLAG_RECURSION)) return -1; #if 0 if (callback->add_extension(callback->cui, _T(".eri"), NULL, _T("Entis Rasterized Image - 1(エリちゃん)"), &EntisGLS_eri_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_RES)) return -1; if (callback->add_extension(callback->cui, _T(".mio"), NULL, _T("Music Interleaved and Orthogonal transformaed(ミーオ)"), &EntisGLS_mio_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_RES)) return -1; if (callback->add_extension(callback->cui, _T(".csx"), NULL, _T("Cotopha Image file"), &EntisGLS_csx_operation, CUI_EXT_FLAG_PKG | CUI_EXT_FLAG_RES)) return -1; #endif EntisGLS_locale_id = locale_app_register(EntisGLS_locale_configurations, 3); debug = !!(unsigned long)get_options("debug"); const char *exe = get_options("exe"); const char *game = get_options("game"); if (!load_exe_xml(exe) && game) { for (DWORD i = 0; game_key_table_list[i].caption[0]; ++i) { if (!strcmpi(game_key_table_list[i].caption, game)) break; } if (game_key_table_list[i].caption[0]) runtime_game_key_table.push_back(game_key_table_list[i]); } const char *password = get_options("pwd"); if (!runtime_game_key_table.size() && password) { struct game_key_table pwd_game; strcpy(pwd_game.caption, "password"); pwd_game.number = 1; strcpy(pwd_game.sub_table[0].password, password); strcpy(pwd_game.sub_table[0].path, ""); runtime_game_key_table.push_back(pwd_game); } else runtime_game_key_table.push_back(default_key_table); //ERIBshfDecodeInit(password); if (debug) { printf("Dump key ring (%d):\n", runtime_game_key_table.size()); for (DWORD i = 0; i < runtime_game_key_table.size(); ++i) { printf("%2d) game \"%s\" (%d)\n", i, runtime_game_key_table[i].caption, runtime_game_key_table[i].number); for (DWORD k = 0; k < runtime_game_key_table[i].number; ++k) { printf("\t%2d> path \"%s\", password \"%s\"\n", k, runtime_game_key_table[i].sub_table[k].path, runtime_game_key_table[i].sub_table[k].password); } } } return 0; } }
25.675113
142
0.65715
MaiReo
2152ab9673f96e552f74c04242c24df2224dd22c
4,692
cpp
C++
export/windows/obj/src/lime/graphics/opengl/ext/EXT_texture_type_2_10_10_10_REV.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
export/windows/obj/src/lime/graphics/opengl/ext/EXT_texture_type_2_10_10_10_REV.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
export/windows/obj/src/lime/graphics/opengl/ext/EXT_texture_type_2_10_10_10_REV.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
// Generated by Haxe 3.4.7 #include <hxcpp.h> #ifndef INCLUDED_lime_graphics_opengl_ext_EXT_texture_type_2_10_10_10_REV #include <lime/graphics/opengl/ext/EXT_texture_type_2_10_10_10_REV.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_d9ba4fd59f8a4b9b_9_new,"lime.graphics.opengl.ext.EXT_texture_type_2_10_10_10_REV","new",0x9147d7a3,"lime.graphics.opengl.ext.EXT_texture_type_2_10_10_10_REV.new","lime/graphics/opengl/ext/EXT_texture_type_2_10_10_10_REV.hx",9,0x0a1a4a4f) namespace lime{ namespace graphics{ namespace opengl{ namespace ext{ void EXT_texture_type_2_10_10_10_REV_obj::__construct(){ HX_STACKFRAME(&_hx_pos_d9ba4fd59f8a4b9b_9_new) HXDLIN( 9) this->UNSIGNED_INT_2_10_10_10_REV_EXT = (int)33640; } Dynamic EXT_texture_type_2_10_10_10_REV_obj::__CreateEmpty() { return new EXT_texture_type_2_10_10_10_REV_obj; } void *EXT_texture_type_2_10_10_10_REV_obj::_hx_vtable = 0; Dynamic EXT_texture_type_2_10_10_10_REV_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< EXT_texture_type_2_10_10_10_REV_obj > _hx_result = new EXT_texture_type_2_10_10_10_REV_obj(); _hx_result->__construct(); return _hx_result; } bool EXT_texture_type_2_10_10_10_REV_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x6d989885; } EXT_texture_type_2_10_10_10_REV_obj::EXT_texture_type_2_10_10_10_REV_obj() { } hx::Val EXT_texture_type_2_10_10_10_REV_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 31: if (HX_FIELD_EQ(inName,"UNSIGNED_INT_2_10_10_10_REV_EXT") ) { return hx::Val( UNSIGNED_INT_2_10_10_10_REV_EXT ); } } return super::__Field(inName,inCallProp); } hx::Val EXT_texture_type_2_10_10_10_REV_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 31: if (HX_FIELD_EQ(inName,"UNSIGNED_INT_2_10_10_10_REV_EXT") ) { UNSIGNED_INT_2_10_10_10_REV_EXT=inValue.Cast< int >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void EXT_texture_type_2_10_10_10_REV_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_HCSTRING("UNSIGNED_INT_2_10_10_10_REV_EXT","\x8c","\x7b","\xc3","\x89")); super::__GetFields(outFields); }; #if HXCPP_SCRIPTABLE static hx::StorageInfo EXT_texture_type_2_10_10_10_REV_obj_sMemberStorageInfo[] = { {hx::fsInt,(int)offsetof(EXT_texture_type_2_10_10_10_REV_obj,UNSIGNED_INT_2_10_10_10_REV_EXT),HX_HCSTRING("UNSIGNED_INT_2_10_10_10_REV_EXT","\x8c","\x7b","\xc3","\x89")}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo *EXT_texture_type_2_10_10_10_REV_obj_sStaticStorageInfo = 0; #endif static ::String EXT_texture_type_2_10_10_10_REV_obj_sMemberFields[] = { HX_HCSTRING("UNSIGNED_INT_2_10_10_10_REV_EXT","\x8c","\x7b","\xc3","\x89"), ::String(null()) }; static void EXT_texture_type_2_10_10_10_REV_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(EXT_texture_type_2_10_10_10_REV_obj::__mClass,"__mClass"); }; #ifdef HXCPP_VISIT_ALLOCS static void EXT_texture_type_2_10_10_10_REV_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(EXT_texture_type_2_10_10_10_REV_obj::__mClass,"__mClass"); }; #endif hx::Class EXT_texture_type_2_10_10_10_REV_obj::__mClass; void EXT_texture_type_2_10_10_10_REV_obj::__register() { hx::Object *dummy = new EXT_texture_type_2_10_10_10_REV_obj; EXT_texture_type_2_10_10_10_REV_obj::_hx_vtable = *(void **)dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("lime.graphics.opengl.ext.EXT_texture_type_2_10_10_10_REV","\x31","\xca","\xbc","\x3c"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mMarkFunc = EXT_texture_type_2_10_10_10_REV_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(EXT_texture_type_2_10_10_10_REV_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< EXT_texture_type_2_10_10_10_REV_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = EXT_texture_type_2_10_10_10_REV_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = EXT_texture_type_2_10_10_10_REV_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = EXT_texture_type_2_10_10_10_REV_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace lime } // end namespace graphics } // end namespace opengl } // end namespace ext
39.428571
267
0.808184
seanbashaw
21567baf916fa34ae5e2c1f7b4af21b5ab57ddb6
5,356
cc
C++
Grove_Sensoren/Grove Serial Camera Kit - 815001001/CompactC/Webcam/WEB_CAM.cc
frankyhub/Calliope
335f0ef5ca9bcf57e14166319501ec9086bc09bf
[ "MIT" ]
null
null
null
Grove_Sensoren/Grove Serial Camera Kit - 815001001/CompactC/Webcam/WEB_CAM.cc
frankyhub/Calliope
335f0ef5ca9bcf57e14166319501ec9086bc09bf
[ "MIT" ]
null
null
null
Grove_Sensoren/Grove Serial Camera Kit - 815001001/CompactC/Webcam/WEB_CAM.cc
frankyhub/Calliope
335f0ef5ca9bcf57e14166319501ec9086bc09bf
[ "MIT" ]
null
null
null
/******************************************************************************* Project Name: WEB_CAM.cprj Required Libs's: IntFunc_lib.cc Files: CAMERA_CJ_OV528.cc, SD.Lib.cc Writer: CCPRO-TEAM Date: 10.05.2015 Function: Demonstrates the Grove Camera_CJ_OV528 with Webserver ------------------------------------------------------------------------------ AVR32 Serie: ------------ Required the C-Control PRO AVR32-Bit UNIT Conrad BN: 192573 Applicationboard Conrad BN: 192587 Or Mainboard Conrad BN: 192702 Connection: ----------- - Connect the sensor red wire to +5V (AVR32) the Camers dosn't work with 3,3V! - Connect the sensor black wire to GND - Connect the sensor yellow wire (UART-RxD) P37 - Connect the sensor white wire (UART-TxD) P36 HTTP-Webserver: --------------- http://localhost Copy the "Webroot" files to the microSD-Card (main directory) Start the program with F10 (or the yellow flash icon) for debug outputs! ------------------------------------------------------------------------------ Note: ----- Source: http://www.seeedstudio.com/depot/Grove-Serial-Camera-Kit-p-1608.html Grove - Serial Camera Kit includes one control board and two interchangeble lenses, one is standard lens and the other is wide-angle lens. To make it more fun and playable, lenses of two specs are shipped in this kit. The standard one is for common photo shots and the wide-angle one is specially suitable for monitoring projects. Specifications: --------------- * Input Voltage: 5V * Pixel: 300,000 * Resolution: 640*480, 320*240, 160*120 * Uart Baud Rate: 9600~115200 * Communication: RS485 and RS232 * Photo JPEG compression, high, medium and low grades Optional * AGC * Auto Exposure Event Control * Automatic White Balance Control * Focus adjustable *******************************************************************************/ // Only for the C-Control PRO AVR32 #ifdef AVR32 // Webserver user variables #define WEB_VAR_CNT 1 // Webserver byte webmem[WEB_BUF(WEB_VAR_CNT)]; byte ip_info[6]; int cmd; // Str_Printf char text[80]; /*------------------------------------------------------------------------------ Main loop ------------------------------------------------------------------------------*/ void main(void) { // Webserver request variable byte req_id; int counter; counter=0; cmd=0; // Live LED init Port_Attribute(PORT_LED2, PORT_ATTR_OUTPUT | PORT_ATTR_INIT_LOW); // SD WRITE LED Port_Attribute(PORT_LED1,PORT_ATTR_OUTPUT|PORT_ATTR_DRIVE_MIN); Port_WriteBit(PORT_LED1,0); // SD and Camera initialize Msg_WriteText("Camera initialize...\r"); SD_INIT(); CAMERA_INIT(); CAMERA_SIZE_BAUD_FRAM(); // HTTP Webserver debug output ETH_GetIPInfo(EI_IP_ADDR, ip_info); Str_Printf(text, "IP-Adresse: %d.%d.%d.%d\r", ip_info[0],ip_info[1],ip_info[2],ip_info[3]); Msg_WriteText(text); ETH_GetIPInfo(EI_NETMASK, ip_info); Str_Printf(text, "IP-Netmask: %d.%d.%d.%d\r", ip_info[0],ip_info[1],ip_info[2],ip_info[3]); Msg_WriteText(text); ETH_GetIPInfo(EI_GATEWAY, ip_info); Str_Printf(text, "IP-Gateway: %d.%d.%d.%d\r", ip_info[0],ip_info[1],ip_info[2],ip_info[3]); Msg_WriteText(text); // Start the HTTP Websever as port 80 WEB_StartServer(80, webmem, WEB_VAR_CNT, 0); // Set the HTTP Webserver variables WEB_SetDynVar(0, cmd, DYN_INT, DYN_CGIVAR, 0); // Here start the endless loop while(1) { // Received the request variable req_id=WEB_GetRequest(); if(req_id!=0) { Str_Printf(text, "req_id:%d hash:%x cmd:%d\r", req_id, WEB_GetFileHash(req_id), cmd); Msg_WriteText(text); if(cmd==1) { // Save the Camera Picture SNAP(); } // Clear the request variable and send infomation to Website cmd=0; WEB_ReleaseRequest(req_id); } // Toggle "Live LED" if(counter==1000) { Port_ToggleBit(PORT_LED2); counter=0; } counter++; } } /*------------------------------------------------------------------------------ SNAP PIC ------------------------------------------------------------------------------*/ void SNAP(void) { // Save the Camera Picture SD_OPEN_FILE("bild.jpg"); GET_PIC(); CAMERA_SAVE_PIC(); } #else #error "Only C-Control PRO AVR32-Bit" #endif /******************************************************************************* * Info ******************************************************************************* * Changelog: * - * ******************************************************************************* * Bugs, feedback, questions and modifications can be posted on the * C-Control Forum on http://www.c-control.de * Of course you can also write us an e-mail to: [email protected] * We publish updates from time to time on www.c-control.de! /******************************************************************************/ // EOF
29.921788
98
0.510456
frankyhub