hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
636cd41bc1e72bf99ab64fb7a368b8d51bc9edd8
1,863
cpp
C++
Tuniac1/NFN_Exporter/NumberedFileExporter.cpp
Harteex/Tuniac
dac98a68c1b801b7fc82874aad16cc8adcabb606
[ "BSD-3-Clause" ]
3
2022-01-05T08:47:51.000Z
2022-01-06T12:42:18.000Z
Tuniac1/NFN_Exporter/NumberedFileExporter.cpp
Harteex/Tuniac
dac98a68c1b801b7fc82874aad16cc8adcabb606
[ "BSD-3-Clause" ]
null
null
null
Tuniac1/NFN_Exporter/NumberedFileExporter.cpp
Harteex/Tuniac
dac98a68c1b801b7fc82874aad16cc8adcabb606
[ "BSD-3-Clause" ]
1
2022-01-06T16:12:58.000Z
2022-01-06T16:12:58.000Z
#include "StdAfx.h" #include "NumberedFileExporter.h" CNumberedFileExporter::CNumberedFileExporter(void) { } CNumberedFileExporter::~CNumberedFileExporter(void) { } LPTSTR CNumberedFileExporter::GetName(void) { return TEXT("Numbered File Exporter"); } void CNumberedFileExporter::Destory(void) { delete this; } unsigned long CNumberedFileExporter::GetNumExtensions(void) { return 1; } LPTSTR CNumberedFileExporter::SupportedExtension(unsigned long ulExtentionNum) { return TEXT("NFN"); } bool CNumberedFileExporter::CanHandle(LPTSTR szSource) { TCHAR * pLastDigits = szSource + (wcsnlen_s(szSource, MAX_PATH)-3); if(StrStrI(pLastDigits, TEXT("NFN"))) return true; return false; } bool CNumberedFileExporter::BeginExport(LPTSTR szSource, unsigned long ulNumItems) { if (IDNO == MessageBox(NULL, TEXT("Warning: NFN_Exporter plugin creates a copy of the selected files. Eg it duplicates the files! \n\nDo you want to continue?"), TEXT("NFN_Exporter"), MB_YESNO | MB_ICONWARNING)) return false; StringCchCopy(m_szExportFolder, MAX_PATH, szSource); if(GetFileAttributes(m_szExportFolder) == INVALID_FILE_ATTRIBUTES) { // folder doesn't exist, create it. CreateDirectory(m_szExportFolder, NULL); } m_ulCurrentFileIndex = 1; return true; } bool CNumberedFileExporter::ExportEntry(LibraryEntry & libraryEntry) { TCHAR m_szTempFile[MAX_PATH]; StringCchCopy(m_szTempFile, MAX_PATH, m_szExportFolder); PathAddBackslash(m_szTempFile); TCHAR tempBit[32]; StringCchPrintf(tempBit, 32, TEXT("%04u - "), m_ulCurrentFileIndex); StringCchCat(m_szTempFile, MAX_PATH, tempBit); StringCchCat(m_szTempFile, MAX_PATH, PathFindFileName(libraryEntry.szURL)); CopyFile(libraryEntry.szURL, m_szTempFile, TRUE); m_ulCurrentFileIndex++; return true; } bool CNumberedFileExporter::EndExport(void) { return false; }
20.7
212
0.765432
Harteex
636d8faf922ac3c55de0aaf64a883266b3778283
4,184
cpp
C++
coast/wdbase/ServerLFThreadPoolsManager.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/wdbase/ServerLFThreadPoolsManager.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/wdbase/ServerLFThreadPoolsManager.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ #include "ServerLFThreadPoolsManager.h" #include "Server.h" #include "LFListenerPool.h" #include "WPMStatHandler.h" #include "RequestProcessor.h" RegisterServerPoolsManagerInterface(ServerLFThreadPoolsManager); ServerLFThreadPoolsManager::ServerLFThreadPoolsManager(const char *ServerThreadPoolsManagerName) : ServerPoolsManagerInterface(ServerThreadPoolsManagerName) , fLFPool(0) , fThreadPoolSz(25) { StartTrace(ServerLFThreadPoolsManager.Ctor); } ServerLFThreadPoolsManager::~ServerLFThreadPoolsManager() { StartTrace(ServerLFThreadPoolsManager.Dtor); RequestTermination(); Terminate(); delete fLFPool; fLFPool = 0; } int ServerLFThreadPoolsManager::Init(Server *server) { StartTrace(ServerLFThreadPoolsManager.Init); // return 0 in case of success return ( SetupLFPool(server) ? 0 : 1 ); } bool ServerLFThreadPoolsManager::SetupLFPool(Server *server) { StartTrace(ServerLFThreadPoolsManager.SetupLFPool); Context ctx; ctx.SetServer(server); ctx.Push("ServerLFThreadPoolsManager", this); fThreadPoolSz = ctx.Lookup("ThreadPoolSize", fThreadPoolSz); ROAnything listenerPoolConfig; if (!ctx.Lookup("ListenerPool", listenerPoolConfig)) { const char *msg = "ListenerPool configuration not found"; SYSERROR(msg); Trace(msg); return false; } TraceAny(listenerPoolConfig, "ListenerPool config:"); RequestReactor *rr = new RequestReactor(server->MakeProcessor(), new WPMStatHandler(fThreadPoolSz)); server->AddStatGatherer2Observe(rr); fLFPool = new LFListenerPool(rr); bool usePoolStorage = (ctx.Lookup("UsePoolStorage", 0L) != 0L); return fLFPool->Init(fThreadPoolSz, listenerPoolConfig, usePoolStorage); } RequestProcessor* ServerLFThreadPoolsManager::DoGetRequestProcessor() { if ( fLFPool && fLFPool->GetReactor() ) { RequestReactor* pReactor = dynamic_cast<RequestReactor*>(fLFPool->GetReactor()); if ( pReactor ) { return pReactor->GetRequestProcessor(); } } return 0; } int ServerLFThreadPoolsManager::ReInit(Server *server) { StartTrace(ServerLFThreadPoolsManager.ReInit); return 0; } int ServerLFThreadPoolsManager::Run(Server *server) { StartTrace(ServerLFThreadPoolsManager.Run); Assert(fLFPool); Context ctx; ctx.SetServer(server); ctx.Push("ServerLFThreadPoolsManager", this); bool usePoolStorage = (ctx.Lookup("UsePoolStorage", 0L) != 0L); u_long poolStorageSize = (u_long)ctx.Lookup("PoolStorageSize", 1000L); u_long numOfPoolBucketSizes = (u_long)ctx.Lookup("NumOfPoolBucketSizes", 20L); int retVal = fLFPool->Start(usePoolStorage, poolStorageSize, numOfPoolBucketSizes); if ( retVal != 0 ) { SYSERROR("server (" << fName << ") start accept loops failed"); return retVal; } SetReady(true); // wait on Join forever retVal = fLFPool->Join(0); SetReady(false); return retVal; } bool ServerLFThreadPoolsManager::BlockRequests(Server *server) { StartTrace(ServerLFThreadPoolsManager.BlockRequests); fLFPool->BlockRequests(); String m(" done\n"); SystemLog::WriteToStderr(m); Trace("done"); m = "Waiting for requests to terminate \n"; SystemLog::WriteToStderr(m); Trace(m); Context ctx; ctx.SetServer(server); ctx.Push("ServerLFThreadPoolsManager", this); return fLFPool->AwaitEmpty(ctx.Lookup("AwaitResetEmpty", 120L)); } void ServerLFThreadPoolsManager::UnblockRequests() { StartTrace(ServerLFThreadPoolsManager.UnblockRequests); fLFPool->UnblockRequests(); } int ServerLFThreadPoolsManager::RequestTermination() { StartTrace(ServerLFThreadPoolsManager.RequestTermination); if ( fLFPool ) { fLFPool->RequestTermination(); } return 0; } void ServerLFThreadPoolsManager::Terminate() { StartTrace(ServerLFThreadPoolsManager.Terminate); if ( fLFPool ) { fLFPool->RequestTermination(); fLFPool->Join(20); } Trace("setting ready to false"); SetReady(false); } long ServerLFThreadPoolsManager::GetThreadPoolSize() { return fThreadPoolSz; }
27.346405
102
0.769598
zer0infinity
636ee9507dff33daf93aa51f732e5acb3874fcbe
1,040
hpp
C++
include/ce2/asset/prefab.hpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
include/ce2/asset/prefab.hpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
include/ce2/asset/prefab.hpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
#pragma once #include "chokoengine.hpp" CE_BEGIN_NAMESPACE /* Prefab class * A holder of scene objects * Saves a configuration of objects * that can be instantiated into the scene */ class _Prefab : public _Asset { CE_OBJECT_COMMON public: class _ObjBase; class _ObjTreeBase; typedef std::function<Prefab(const std::string&)> _Sig2Prb; typedef std::function<Asset(AssetType, const std::string&)> _Sig2Ass; private: std::unique_ptr<_ObjBase> _data; std::unique_ptr<_ObjTreeBase> _tree; public: _Prefab(const SceneObject&, bool link); _Prefab(const JsonObject&, _Sig2Prb); ~_Prefab(); //explicit destructor where _ObjBase is defined JsonObject ToJson() const; SceneObject Instantiate(_Sig2Ass); std::unique_ptr<_ObjBase>& GetPrefabObj(size_t id); _ObjTreeBase& GetTreeObj(size_t id); std::unique_ptr<_ObjTreeBase>& GetTree(); void Apply(const SceneObject&, bool tree = false, size_t id = -1); void Revert(const SceneObject&, size_t id = -1); void _UpdateObjs(const SceneObject&); }; CE_END_NAMESPACE
22.12766
70
0.748077
chokomancarr
636f587683123d6d775c7f54b0782efecbf89a75
2,883
cc
C++
src/publishclient/testpublishclient.cc
wangzhezhe/observerchain
faa8fb9d845a2720704538f01e1e7597083d4510
[ "MIT" ]
null
null
null
src/publishclient/testpublishclient.cc
wangzhezhe/observerchain
faa8fb9d845a2720704538f01e1e7597083d4510
[ "MIT" ]
null
null
null
src/publishclient/testpublishclient.cc
wangzhezhe/observerchain
faa8fb9d845a2720704538f01e1e7597083d4510
[ "MIT" ]
null
null
null
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <iostream> #include <memory> #include <string> #include <vector> #include <unistd.h> #include <pthread.h> #include <grpc++/grpc++.h> #include "workflowserver.grpc.pb.h" #include "pubsubclient.h" using grpc::Channel; using grpc::ClientContext; using grpc::Status; using workflowserver::Greeter; using workflowserver::HelloReply; using workflowserver::HelloRequest; using workflowserver::PubSubReply; using workflowserver::PubSubRequest; using namespace std; void *PublishOperation(void *ptr) { sleep(5); printf("new thread push event\n"); vector<string> publisheventList; publisheventList.push_back("event1"); GreeterClient *greeter = GreeterClient::getClient(); if (greeter == NULL) { printf("failed to get initialised greeter\n"); return NULL; } string metadata="testmeta"; string reply = greeter->Publish(publisheventList,"CLIENT",metadata); cout << "Publish return value: " << reply << endl; } int main(int argc, char **argv) { // Instantiate the client. It requires a channel, out of which the actual RPCs // are created. This channel models a connection to an endpoint (in this case, // localhost at port 50051). We indicate that the channel isn't authenticated // (use of InsecureChannelCredentials()). string user("world"); //get greeter GreeterClient *greeter = GreeterClient::getClient(); if (greeter == NULL) { printf("failed to get initialised greeter\n"); return 0; } string reply = greeter->SayHello(user); cout << "Greeter received: " << reply << endl; //pthread_t id; //pthread_create(&id, NULL, PublishOperation, NULL); vector<string> subeventList; subeventList.push_back("event1"); //eventList.push_back("event2"); //RepeatedPtrField<string> tpf; //eventList.insert("event1"); //int size=eventList.size(); //int i=0; //for(i=0;i<size;i++){ // tpf->set_pubsubmessage(i,eventList[i]); //} //intiSocketAddr(); string clientid("testid"); reply = greeter->Subscribe(subeventList,clientid); cout << "Subscribe return value: " << reply << endl; //start a new thread to do the push operation // initMultiClients(); // return 0; }
27.198113
82
0.677072
wangzhezhe
6375d48c6b603142842dd3cfe1637313ef3fef9a
1,553
cpp
C++
Gems/EMotionFX/Code/Tests/TestAssetCode/TestActorAssets.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
1
2022-03-12T14:13:45.000Z
2022-03-12T14:13:45.000Z
Gems/EMotionFX/Code/Tests/TestAssetCode/TestActorAssets.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
3
2021-09-08T03:41:27.000Z
2022-03-12T01:01:29.000Z
Gems/EMotionFX/Code/Tests/TestAssetCode/TestActorAssets.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzCore/IO/SystemFile.h> #include <AzCore/std/containers/vector.h> #include <AzFramework/StringFunc/StringFunc.h> #include <EMotionFX/Source/Actor.h> #include <EMotionFX/Source/EMotionFXManager.h> #include <EMotionFX/Source/Importer/Importer.h> #include <Tests/TestAssetCode/TestActorAssets.h> namespace EMotionFX { AZStd::string TestActorAssets::FileToBase64(const char* filePath) { AZ::IO::SystemFile systemFile; if (systemFile.Open(filePath, AZ::IO::SystemFile::SF_OPEN_READ_ONLY)) { const size_t sizeInBytes = systemFile.Length(); AZStd::vector<AZ::u8> dataToEncode; dataToEncode.resize(sizeInBytes); systemFile.Read(sizeInBytes, dataToEncode.begin()); return AzFramework::StringFunc::Base64::Encode(dataToEncode.begin(), sizeInBytes); } return AZStd::string(); } AZ::Data::Asset<Integration::ActorAsset> TestActorAssets::GetAssetFromActor(const AZ::Data::AssetId& assetId, AZStd::unique_ptr<Actor>&& actor) { AZ::Data::Asset<Integration::ActorAsset> actorAsset = AZ::Data::AssetManager::Instance().CreateAsset<Integration::ActorAsset>(assetId); actorAsset.GetAs<Integration::ActorAsset>()->SetData(AZStd::move(actor)); return actorAsset; } } // namespace EMotionFX
36.97619
147
0.701867
cypherdotXd
63788e10e9f9ae1a431836d21577228f7f8afa36
2,574
cpp
C++
src/main/resources/templates/c++11/XmlPGen/impl/Log.cpp
BWeng20/XmlPGen
280f1dace7c222a9446670b60a6e0f905e9abb2d
[ "MIT" ]
null
null
null
src/main/resources/templates/c++11/XmlPGen/impl/Log.cpp
BWeng20/XmlPGen
280f1dace7c222a9446670b60a6e0f905e9abb2d
[ "MIT" ]
null
null
null
src/main/resources/templates/c++11/XmlPGen/impl/Log.cpp
BWeng20/XmlPGen
280f1dace7c222a9446670b60a6e0f905e9abb2d
[ "MIT" ]
null
null
null
/* Part of XmlPGen * Copyright (c) 2013-2016 Bernd Wengenroth * Licensed under the MIT License. * See LICENSE file for details. */ #include "../Log.h" #include <cstdio> #include <cstdarg> #include <time.h> #include <iomanip> namespace XmlPGen { ::std::string Log::currentTime() { ::std::string s; char buffer[31]; ::time_t t; ::tm ttm; ::time(&t); #ifdef _MSC_VER ::localtime_s(&ttm, &t); #else ::localtime_s(&t, &ttm); #endif ::asctime_s(buffer, 30, &ttm); buffer[30] = 0; s.append(buffer); return s; } void ConsoleLog::info( char const *format, ... ) { printf( "%s INF ", currentTime().c_str() ); va_list args; va_start (args, format); ::vprintf(format,args); va_end (args); printf( "\n" ); } void ConsoleLog::warning( char const *format, ... ) { printf("%s WRN ", currentTime().c_str()); va_list args; va_start (args, format); ::vprintf(format,args); va_end (args); printf( "\n" ); } void ConsoleLog::error ( char const *format, ... ) { printf("%s ERR ", currentTime().c_str()); va_list args; va_start (args, format); ::vprintf(format,args); va_end (args); printf( "\n" ); } StreamLog::StreamLog( ::std::shared_ptr< ::std::ostream > stream ) : logstream(stream) { } void StreamLog::info( char const *format, ... ) { if ( logstream ) { va_list args; va_start (args, format); ::vsnprintf(buffer,1024,format,args); va_end (args); (*logstream) << ::std::right << ::std::setw(5) << ::time(nullptr) << " INF " << buffer << ::std::endl ; } } void StreamLog::warning( char const *format, ... ) { if ( logstream ) { va_list args; va_start (args, format); ::vsnprintf(buffer,1024,format,args); va_end (args); (*logstream) << ::std::right << ::std::setw(5) << ::time(nullptr) << " WRN " << buffer << ::std::endl ; } } void StreamLog::error ( char const *format, ... ) { if ( logstream ) { va_list args; va_start (args, format); ::vsnprintf(buffer,1024,format,args); va_end (args); (*logstream) << ::std::right << ::std::setw(5) << ::time(nullptr) << " ERR " << buffer << ::std::endl ; } } }
23.614679
115
0.491064
BWeng20
6378afe632187919bb9e47b4fb4b5b5915cd3ae1
3,130
cpp
C++
src/Shay/AABB.cpp
MajorArkwolf/stonks
5671f7811f19af33450e5fd07ab61c700f71ee69
[ "0BSD" ]
null
null
null
src/Shay/AABB.cpp
MajorArkwolf/stonks
5671f7811f19af33450e5fd07ab61c700f71ee69
[ "0BSD" ]
null
null
null
src/Shay/AABB.cpp
MajorArkwolf/stonks
5671f7811f19af33450e5fd07ab61c700f71ee69
[ "0BSD" ]
null
null
null
#include "AABB.hpp" using Shay::AABB; /** * @brief Sets the max X value for the bounding box * @param tempX The maxmimum x-coordinate */ void AABB::SetMaxX(GLfloat tempX) { if (this->currentAABB >= m_BBox.size()) { m_BBox.push_back({}); } m_BBox[this->currentAABB].max.x = tempX; } /** * @brief Sets the min X value for the bounding box * @param tempX The minimum x-coordinate */ void AABB::SetMinX(GLfloat tempX) { if (this->currentAABB >= m_BBox.size()) { m_BBox.push_back({}); } m_BBox[this->currentAABB].min.x = tempX; } /** * @brief Sets the max Y value for the bounding box * @param tempY The maxmimum y-coordinate */ void AABB::SetMaxY(GLfloat tempY) { if (this->currentAABB >= m_BBox.size()) { m_BBox.push_back({}); } m_BBox[this->currentAABB].max.y = tempY; } /** * @brief Sets the min Y value for the bounding box * @param tempY The minimum y-coordinate */ void AABB::SetMinY(GLfloat tempY) { if (this->currentAABB >= m_BBox.size()) { m_BBox.push_back({}); } m_BBox[this->currentAABB].min.y = tempY; } /** * @brief Sets the max Z value for the bounding box * @param tempZ The maxmimum z-coordinate */ void AABB::SetMaxZ(GLfloat tempZ) { if (this->currentAABB >= m_BBox.size()) { m_BBox.push_back({}); } m_BBox[this->currentAABB].max.z = tempZ; } /** * @brief Sets the min Z value for the bounding box * @param tempZ The minimum z-coordinate */ void AABB::SetMinZ(GLfloat tempZ) { if (this->currentAABB >= m_BBox.size()) { m_BBox.push_back({}); } m_BBox[this->currentAABB].min.z = tempZ; } /** * @brief Sets the index for the bounding box * @param index The index number to set the bounding box to */ auto AABB::SetAABBIndex(size_t index) -> void { this->currentAABB = index; } /** * @brief Finishes the AABB, what does this do */ auto AABB::FinishAABB() -> void { this->currentAABB++; } /** * @brief Returns the Max X coordinate of the bounding box * @return The max X coordinate */ GLfloat AABB::GetMaxX() { return m_BBox[this->currentAABB].max.x; } /** * @brief Returns the min X value for the bounding box * @return The min X coordinate */ GLfloat AABB::GetMinX() { return m_BBox[this->currentAABB].min.x; } /** * @brief Returns the max Y value for the bounding box * @return The max Y coordinate */ GLfloat AABB::GetMaxY() { return m_BBox[this->currentAABB].max.y; } /** * @brief Returns the min Y value for the bounding box * @return The min Y coordinate */ GLfloat AABB::GetMinY() { return m_BBox[this->currentAABB].min.y; } /** * @brief Returns the max Z value for the bounding box * @return The max Z coordinate */ GLfloat AABB::GetMaxZ() { return m_BBox[this->currentAABB].max.z; } /** * @brief Returns the min Z value for the bounding box * @return The min Z coordinate */ GLfloat AABB::GetMinZ() { return m_BBox[this->currentAABB].min.z; } /** * @brief Returns the number of bounding boxes * @return The bounding box index number */ size_t AABB::GetNoBoundingBoxes() { return m_BBox.size(); }
22.198582
59
0.650479
MajorArkwolf
637df57ae3ae75940cce55398bb82674b91ca161
4,887
cxx
C++
Testing/Unit/sitkSystemInformationTest.cxx
nathantspencer/SimpleElastix
a9641c1197e58a4ff614145e9ba5ca43c2833ebf
[ "Apache-2.0" ]
576
2015-01-14T12:47:35.000Z
2022-03-31T07:45:52.000Z
Testing/Unit/sitkSystemInformationTest.cxx
nathantspencer/SimpleElastix
a9641c1197e58a4ff614145e9ba5ca43c2833ebf
[ "Apache-2.0" ]
874
2015-01-15T10:19:16.000Z
2022-03-29T16:51:12.000Z
Testing/Unit/sitkSystemInformationTest.cxx
nathantspencer/SimpleElastix
a9641c1197e58a4ff614145e9ba5ca43c2833ebf
[ "Apache-2.0" ]
186
2015-01-16T15:39:27.000Z
2022-03-21T17:22:35.000Z
/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * 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 "itksys/SystemTools.hxx" #include "itksys/SystemInformation.hxx" #include <iostream> #include <fstream> #include <string> #include <cstdlib> namespace { void SystemInformationPrintFile(const std::string &name, std::ostream& os) { const char* div = "======================================================================="; os << "System Information File \"" << name << "\""; if(! itksys::SystemTools::FileExists( name.c_str(), true) ) { os << " does not exist.\n"; return; } std::ifstream fin(name.c_str()); if(fin) { os << ":\n[" << div << "[\n"; os << fin.rdbuf(); os << "]" << div << "]\n"; os.flush(); } else { os << " but cannot be opened for read.\n"; } } void SystemInformationPrint(std::ostream& os) { itksys::SystemInformation mySys; mySys.RunCPUCheck(); mySys.RunOSCheck(); mySys.RunMemoryCheck(); os << "---------- System Information ----------" << std::endl; os << "VendorString: " << mySys.GetVendorString() << std::endl; os << "VendorID: " << mySys.GetVendorID() << std::endl; os << "TypeID: " << mySys.GetTypeID() << std::endl; os << "FamilyID: " << mySys.GetFamilyID() << std::endl; os << "ModelID: " << mySys.GetModelID() << std::endl; os << "SteppingCode: " << mySys.GetSteppingCode() << std::endl; os << "ExtendedProcessorName: " << mySys.GetExtendedProcessorName() << std::endl; os << "DoesCPUSupportCPUID: " << mySys.DoesCPUSupportCPUID() << std::endl;; os << "ProcessorSerialNumber: " << mySys.GetProcessorSerialNumber() << std::endl; os << "ProcessorCacheSize: " << mySys.GetProcessorCacheSize() << std::endl; os << "LogicalProcessorsPerPhysical: " << mySys.GetLogicalProcessorsPerPhysical() << std::endl; os << "ProcessorClockFrequency: " << mySys.GetProcessorClockFrequency() << std::endl; os << "ProcessorAPICID: " << mySys.GetProcessorAPICID() << std::endl; os << "OSName: " << mySys.GetOSName() << std::endl; os << "Hostname: " << mySys.GetHostname() << std::endl; os << "OSRelease: " << mySys.GetOSRelease() << std::endl; os << "OSVersion: " << mySys.GetOSVersion() << std::endl; os << "OSPlatform: " << mySys.GetOSPlatform() << std::endl; os << "Is64Bits: " << mySys.Is64Bits() << std::endl; os << "NumberOfLogicalCPU: " << mySys.GetNumberOfLogicalCPU() << std::endl; os << "NumberOfPhysicalCPU: " << mySys.GetNumberOfPhysicalCPU() << std::endl; // Retrieve memory information in megabyte. os << "TotalVirtualMemory: " << mySys.GetTotalVirtualMemory() << std::endl; os << "AvailableVirtualMemory: " << mySys.GetAvailableVirtualMemory() << std::endl; os << "TotalPhysicalMemory: " << mySys.GetTotalPhysicalMemory() << std::endl; os << "AvailablePhysicalMemory: " << mySys.GetAvailablePhysicalMemory() << std::endl; } } int main(int argc, char* argv[]) { if(argc != 2) { std::cerr << "Usage: itkSystemInformationTest <top-of-build-tree>\n"; return EXIT_FAILURE; } std::string build_dir = argv[1]; build_dir += "/"; const char* files[] = { "CMakeCache.txt", "CMakeCacheInit.txt", "sitkConfigure.h", "CMakeFiles/CMakeOutput.log", "CMakeFiles/CMakeError.log", "SimpleITKConfig.cmake", "SimpleITKConfigVersion.cmake", "SimpleITKTargets.cmake", 0 }; // Preserve valuable output regardless of the limits set in // CMake/CTestCustom.cmake std::cout << "CTEST_FULL_OUTPUT" << std::endl; for(const char** f = files; *f; ++f) { std::string fname = build_dir + *f; SystemInformationPrintFile(fname.c_str(), std::cout); } SystemInformationPrint( std::cout ); return EXIT_SUCCESS; }
29.618182
94
0.548394
nathantspencer
6380f392b8bd5dfc9a0f3473430cc68dc3f7508f
2,301
cpp
C++
Entry 0 - Call to Adventure/ex4_2_daily_planner.cpp
tensorush/Cpp-Deep-Dive
fa2aa46b906662cf29b48359a2f17c3ddc1b1792
[ "MIT" ]
1
2021-01-24T22:42:29.000Z
2021-01-24T22:42:29.000Z
Entry 0 - Call to Adventure/ex4_2_daily_planner.cpp
geotrush/Cpp-Deep-Dive
fa2aa46b906662cf29b48359a2f17c3ddc1b1792
[ "MIT" ]
null
null
null
Entry 0 - Call to Adventure/ex4_2_daily_planner.cpp
geotrush/Cpp-Deep-Dive
fa2aa46b906662cf29b48359a2f17c3ddc1b1792
[ "MIT" ]
1
2021-09-12T11:41:35.000Z
2021-09-12T11:41:35.000Z
/* Input The input stream contains an integer q (number of queries) as well as some sequence of the following queries (guaranteed to be valid): - "ADD i t": add task t on the i-th day (indexed from '1') of the current month; - "DUMP i": check all tasks planned on the i-th day (indexed from '1'); - "NEXT": transfer all tasks from the current month to the next one, moving the tasks that didn't fit to the last day of the new month. Notes: January is the starting month; February always has 28 days. Output You should output the number of planned tasks for the i-th day as well as their names in any order, separated by spaces at every "DUMP i" query (on a new line). */ #include <iostream> #include <string> #include <vector> using std::cin; using std::cout; using std::endl; using std::string; using std::vector; int main() { const vector<int> days_in_month = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int month_count = days_in_month.size(); int month; int q; cin >> q; vector<vector<string>> daily_planner(days_in_month[month]); for (int i = 0; i < q; ++i) { string query; cin >> query; if (query == "ADD") { int day; cin >> day; string task; cin >> task; daily_planner[--day].push_back(task); } else if (query == "NEXT") { const int old_month_length = days_in_month[month]; month = (month + 1) % month_count; const int new_month_length = days_in_month[month]; if (new_month_length < old_month_length) { vector<string>& last_day_tasks = daily_planner[new_month_length - 1]; for (int i = new_month_length; i < old_month_length; i++) { last_day_tasks.insert(end(last_day_tasks), begin(daily_planner[i]), end(daily_planner[i])); } } daily_planner.resize(new_month_length); } else if (query == "DUMP") { int day; cin >> day; cout << daily_planner[--day].size() << ' '; for (const string& task : daily_planner[day]) { cout << task << ' '; } cout << endl; } } return 0; }
31.094595
87
0.575837
tensorush
6381a2aec8a5a08b9d538961656d22ab3b982ebb
1,183
cpp
C++
RisLib/tsThreadLocal.cpp
chrishoen/Dev_RisLibLx
ca68b7d1a928ba9adb64c5e4996c4ec2e01de1ff
[ "MIT" ]
null
null
null
RisLib/tsThreadLocal.cpp
chrishoen/Dev_RisLibLx
ca68b7d1a928ba9adb64c5e4996c4ec2e01de1ff
[ "MIT" ]
null
null
null
RisLib/tsThreadLocal.cpp
chrishoen/Dev_RisLibLx
ca68b7d1a928ba9adb64c5e4996c4ec2e01de1ff
[ "MIT" ]
null
null
null
/*============================================================================== ==============================================================================*/ //****************************************************************************** //****************************************************************************** //****************************************************************************** #include "stdafx.h" #include "tsThreadLocal.h" namespace TS { //****************************************************************************** //****************************************************************************** //****************************************************************************** ThreadLocal::ThreadLocal() { strcpy(mThreadName, "NoThreadName"); mCode = 0; mPrintCount4 = 0; } void ThreadLocal::setThreadName(const char* aName) { strncpy(mThreadName, aName,cMaxStringSize); } //****************************************************************************** //****************************************************************************** //****************************************************************************** }//namespace
32.861111
80
0.172443
chrishoen
6382d4793f4f3841a7710b5e0e238d2d79a7e4f5
25,902
cpp
C++
orca/gporca/libnaucrates/src/statistics/CBucket.cpp
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
3
2017-12-10T16:41:21.000Z
2020-07-08T12:59:12.000Z
orca/gporca/libnaucrates/src/statistics/CBucket.cpp
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
null
null
null
orca/gporca/libnaucrates/src/statistics/CBucket.cpp
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
4
2017-12-10T16:41:35.000Z
2020-11-28T12:20:30.000Z
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2011 EMC Corp. // // @filename: // CBucket.cpp // // @doc: // Implementation of histogram bucket // // @owner: // // // @test: // // //--------------------------------------------------------------------------- #include <stdlib.h> #include "gpos/base.h" #include "naucrates/base/IDatumStatisticsMappable.h" #include "naucrates/statistics/CBucket.h" #include "naucrates/statistics/CStatisticsUtils.h" #include "naucrates/statistics/CStatistics.h" #include "gpopt/base/COptCtxt.h" using namespace gpnaucrates; //--------------------------------------------------------------------------- // @function: // CBucket::CBucket // // @doc: // Ctor // //--------------------------------------------------------------------------- CBucket::CBucket ( CPoint *ppointLower, CPoint *ppointUpper, BOOL fLowerClosed, BOOL fUpperClosed, CDouble dFrequency, CDouble dDistinct ) : m_ppointLower(ppointLower), m_ppointUpper(ppointUpper), m_fLowerClosed(fLowerClosed), m_fUpperClosed(fUpperClosed), m_dFrequency(dFrequency), m_dDistinct(dDistinct) { GPOS_ASSERT(NULL != m_ppointLower); GPOS_ASSERT(NULL != m_ppointUpper); GPOS_ASSERT(0.0 <= m_dFrequency && 1.0 >= m_dFrequency); GPOS_ASSERT(0.0 <= m_dDistinct); // singleton bucket lower and upper bound are closed GPOS_ASSERT_IMP(FSingleton(), fLowerClosed && fUpperClosed); // null values should be in null fraction of the histogram GPOS_ASSERT(!m_ppointLower->Pdatum()->FNull()); GPOS_ASSERT(!m_ppointUpper->Pdatum()->FNull()); } //--------------------------------------------------------------------------- // @function: // CBucket::~CBucket // // @doc: // Dtor // //--------------------------------------------------------------------------- CBucket::~CBucket() { m_ppointLower->Release(); m_ppointLower = NULL; m_ppointUpper->Release(); m_ppointUpper = NULL; } //--------------------------------------------------------------------------- // @function: // CBucket::FContains // // @doc: // Does bucket contain the point? // //--------------------------------------------------------------------------- BOOL CBucket::FContains ( const CPoint *ppoint ) const { // special case for singleton bucket if (FSingleton()) { return m_ppointLower->FEqual(ppoint); } // special case if point equal to lower bound if (m_fLowerClosed && m_ppointLower->FEqual(ppoint)) { return true; } // special case if point equal to upper bound if (m_fUpperClosed && m_ppointUpper->FEqual(ppoint)) { return true; } return m_ppointLower->FLessThan(ppoint) && m_ppointUpper->FGreaterThan(ppoint); } //--------------------------------------------------------------------------- // @function: // CBucket::FBefore // // @doc: // Is the point before the lower bound of the bucket // //--------------------------------------------------------------------------- BOOL CBucket::FBefore ( const CPoint *ppoint ) const { GPOS_ASSERT(NULL != ppoint); return (m_fLowerClosed && m_ppointLower->FGreaterThan(ppoint)) || (!m_fLowerClosed && m_ppointLower->FGreaterThanOrEqual(ppoint)); } //--------------------------------------------------------------------------- // @function: // CBucket::FAfter // // @doc: // Is the point after the upper bound of the bucket // //--------------------------------------------------------------------------- BOOL CBucket::FAfter ( const CPoint *ppoint ) const { GPOS_ASSERT(NULL != ppoint); return ((m_fUpperClosed && m_ppointUpper->FLessThan(ppoint)) || (!m_fUpperClosed && m_ppointUpper->FLessThanOrEqual(ppoint))); } //--------------------------------------------------------------------------- // @function: // CBucket::DOverlap // // @doc: // What percentage of the bucket is covered by [lower bound, point] // //--------------------------------------------------------------------------- CDouble CBucket::DOverlap ( const CPoint *ppoint ) const { // special case of upper bound equal to ppoint if (this->PpUpper()->FLessThanOrEqual(ppoint)) { return CDouble(1.0); } // if point is not contained, then no overlap if (!this->FContains(ppoint)) { return CDouble(0.0); } // special case for singleton bucket if (FSingleton()) { GPOS_ASSERT(this->m_ppointLower->FEqual(ppoint)); return CDouble(1.0); } // general case, compute distance ratio CDouble dDistanceUpper = m_ppointUpper->DDistance(m_ppointLower); GPOS_ASSERT(dDistanceUpper > 0.0); CDouble dDistanceMiddle = ppoint->DDistance(m_ppointLower); GPOS_ASSERT(dDistanceMiddle >= 0.0); CDouble dRes = 1 / dDistanceUpper; if (dDistanceMiddle > 0.0) { dRes = dRes * dDistanceMiddle; } return CDouble(std::min(dRes.DVal(), DOUBLE(1.0))); } //--------------------------------------------------------------------------- // @function: // CBucket::OsPrint // // @doc: // Print function // //--------------------------------------------------------------------------- IOstream& CBucket::OsPrint ( IOstream &os ) const { os << "CBucket("; if (m_fLowerClosed) { os << " ["; } else { os << " ("; } m_ppointLower->OsPrint(os); os << ", "; m_ppointUpper->OsPrint(os); if (m_fUpperClosed) { os << "]"; } else { os << ")"; } os << " "; os << m_dFrequency << ", " << m_dDistinct ; os << ")"; return os; } //--------------------------------------------------------------------------- // @function: // CBucket::PbucketGreaterThan // // @doc: // Construct new bucket with lower bound greater than given point and // the new bucket's upper bound is the upper bound of the current bucket //--------------------------------------------------------------------------- CBucket * CBucket::PbucketGreaterThan ( IMemoryPool *pmp, CPoint *ppoint ) const { GPOS_ASSERT(FContains(ppoint)); if (FSingleton() || PpUpper()->FEqual(ppoint)) { return NULL; } CBucket *pbucketGT = NULL; CMDAccessor *pmda = COptCtxt::PoctxtFromTLS()->Pmda(); CPoint *ppointNew = CStatisticsUtils::PpointNext(pmp, pmda, ppoint); if (NULL != ppointNew) { if (FContains(ppointNew)) { pbucketGT = PbucketScaleLower(pmp, ppointNew, true /* fIncludeLower */); } ppointNew->Release(); } else { pbucketGT = PbucketScaleLower(pmp, ppoint, false /* fIncludeLower */); } return pbucketGT; } //--------------------------------------------------------------------------- // @function: // CBucket::PbucketScaleUpper // // @doc: // Create a new bucket that is a scaled down version // of this bucket with the upper boundary adjusted. // //--------------------------------------------------------------------------- CBucket* CBucket::PbucketScaleUpper ( IMemoryPool *pmp, CPoint *ppointUpperNew, BOOL fIncludeUpper ) const { GPOS_ASSERT(pmp); GPOS_ASSERT(ppointUpperNew); GPOS_ASSERT(this->FContains(ppointUpperNew)); // scaling upper to be same as lower is identical to producing a singleton bucket if (this->m_ppointLower->FEqual(ppointUpperNew)) { // invalid bucket, e.g. if bucket is [5,10) and // ppointUpperNew is 5 open, null should be returned if (false == fIncludeUpper) { return NULL; } return PbucketSingleton(pmp, ppointUpperNew); } CDouble dFrequencyNew = this->DFrequency(); CDouble dDistinctNew = this->DDistinct(); if (!this->m_ppointUpper->FEqual(ppointUpperNew)) { CDouble dOverlap = this->DOverlap(ppointUpperNew); dFrequencyNew = dFrequencyNew * dOverlap; dDistinctNew = dDistinctNew * dOverlap; } // reuse the lower from this bucket this->m_ppointLower->AddRef(); ppointUpperNew->AddRef(); return GPOS_NEW(pmp) CBucket ( this->m_ppointLower, ppointUpperNew, this->m_fLowerClosed, fIncludeUpper, dFrequencyNew, dDistinctNew ); } //--------------------------------------------------------------------------- // @function: // CBucket::PbucketScaleLower // // @doc: // Create a new bucket that is a scaled down version // of this bucket with the Lower boundary adjusted // //--------------------------------------------------------------------------- CBucket* CBucket::PbucketScaleLower ( IMemoryPool *pmp, CPoint *ppointLowerNew, BOOL fIncludeLower ) const { GPOS_ASSERT(pmp); GPOS_ASSERT(ppointLowerNew); GPOS_ASSERT(this->FContains(ppointLowerNew)); // scaling lower to be same as upper is identical to producing a singleton bucket if (this->m_ppointUpper->FEqual(ppointLowerNew)) { return PbucketSingleton(pmp, ppointLowerNew); } CDouble dFrequencyNew = this->DFrequency(); CDouble dDistinctNew = this->DDistinct(); if (!this->PpLower()->FEqual(ppointLowerNew)) { CDouble dOverlap = CDouble(1.0) - this->DOverlap(ppointLowerNew); dFrequencyNew = this->DFrequency() * dOverlap; dDistinctNew = this->DDistinct() * dOverlap; } // reuse the lower from this bucket this->m_ppointUpper->AddRef(); ppointLowerNew->AddRef(); return GPOS_NEW(pmp) CBucket ( ppointLowerNew, this->m_ppointUpper, fIncludeLower, this->m_fUpperClosed, dFrequencyNew, dDistinctNew ); } //--------------------------------------------------------------------------- // @function: // CBucket::PbucketSingleton // // @doc: // Create a new bucket that is a scaled down version // singleton // //--------------------------------------------------------------------------- CBucket* CBucket::PbucketSingleton ( IMemoryPool *pmp, CPoint *ppointSingleton ) const { GPOS_ASSERT(pmp); GPOS_ASSERT(ppointSingleton); GPOS_ASSERT(this->FContains(ppointSingleton)); // assume that this point is one of the ndistinct values // in the bucket CDouble dDistinctRatio = CDouble(1.0) / this->m_dDistinct; CDouble dFrequencyNew = std::min(DOUBLE(1.0), (this->m_dFrequency * dDistinctRatio).DVal()); CDouble dDistinctNew = CDouble(1.0); // singleton point is both lower and upper ppointSingleton->AddRef(); ppointSingleton->AddRef(); return GPOS_NEW(pmp) CBucket ( ppointSingleton, ppointSingleton, true /* fLowerClosed */, true /* fUpperClosed */, dFrequencyNew, dDistinctNew ); } //--------------------------------------------------------------------------- // @function: // CBucket::PbucketCopy // // @doc: // Copy of bucket. Points are shared. // //--------------------------------------------------------------------------- CBucket * CBucket::PbucketCopy ( IMemoryPool *pmp ) { // reuse the points m_ppointLower->AddRef(); m_ppointUpper->AddRef(); return GPOS_NEW(pmp) CBucket(m_ppointLower, m_ppointUpper, m_fLowerClosed, m_fUpperClosed, m_dFrequency, m_dDistinct); } //--------------------------------------------------------------------------- // @function: // CBucket::PbucketUpdateFrequency // // @doc: // Create copy of bucket with a copy of the bucket with updated frequency // based on the new total number of rows //--------------------------------------------------------------------------- CBucket * CBucket::PbucketUpdateFrequency ( IMemoryPool *pmp, CDouble dRowsOld, CDouble dRowsNew ) { // reuse the points m_ppointLower->AddRef(); m_ppointUpper->AddRef(); CDouble dFrequencyNew = (this->m_dFrequency * dRowsOld) / dRowsNew; return GPOS_NEW(pmp) CBucket(m_ppointLower, m_ppointUpper, m_fLowerClosed, m_fUpperClosed, dFrequencyNew, m_dDistinct); } //--------------------------------------------------------------------------- // @function: // CBucket::ICompareLowerBounds // // @doc: // Compare lower bounds of the buckets, return 0 if they match, 1 if // lb of bucket1 is greater than lb of bucket2 and -1 otherwise. // //--------------------------------------------------------------------------- INT CBucket::ICompareLowerBounds ( const CBucket *pbucket1, const CBucket *pbucket2 ) { GPOS_ASSERT(NULL != pbucket1); GPOS_ASSERT(NULL != pbucket2); CPoint *ppoint1 = pbucket1->PpLower(); CPoint *ppoint2 = pbucket2->PpLower(); BOOL fClosedPoint1 = pbucket1->FLowerClosed(); BOOL fClosedPoint2 = pbucket1->FLowerClosed(); if (ppoint1->FEqual(ppoint2)) { if (fClosedPoint1 == fClosedPoint2) { return 0; } if (fClosedPoint1) { // pbucket1 contains the lower bound (lb), while pbucket2 contain all // values between (lb + delta) and upper bound (ub) return -1; } return 1; } if (ppoint1->FLessThan(ppoint2)) { return -1; } return 1; } //--------------------------------------------------------------------------- // @function: // CBucket::ICompareLowerBoundToUpperBound // // @doc: // Compare lb of the first bucket to the ub of the second bucket, // return 0 if they match, 1 if lb of bucket1 is greater // than ub of bucket2 and -1 otherwise. //--------------------------------------------------------------------------- INT CBucket::ICompareLowerBoundToUpperBound ( const CBucket *pbucket1, const CBucket *pbucket2 ) { CPoint *ppoint1Lower = pbucket1->PpLower(); CPoint *ppoint2Upper = pbucket2->PpUpper(); if (ppoint1Lower->FGreaterThan(ppoint2Upper)) { return 1; } if (ppoint1Lower->FLessThan(ppoint2Upper)) { return -1; } // equal if (pbucket1->FLowerClosed() && pbucket2->FUpperClosed()) { return 0; } return 1; // points not comparable } //--------------------------------------------------------------------------- // @function: // CBucket::ICompareUpperBounds // // @doc: // Compare upper bounds of the buckets, return 0 if they match, 1 if // ub of bucket1 is greater than that of bucket2 and -1 otherwise. // //--------------------------------------------------------------------------- INT CBucket::ICompareUpperBounds ( const CBucket *pbucket1, const CBucket *pbucket2 ) { GPOS_ASSERT(NULL != pbucket1); GPOS_ASSERT(NULL != pbucket2); CPoint *ppoint1 = pbucket1->PpUpper(); CPoint *ppoint2 = pbucket2->PpUpper(); BOOL fClosedPoint1 = pbucket1->FUpperClosed(); BOOL fClosedPoint2 = pbucket1->FUpperClosed(); if (ppoint1->FEqual(ppoint2)) { if (fClosedPoint1 == fClosedPoint2) { return 0; } if (fClosedPoint1) { // pbucket2 contains all values less than upper bound not including upper bound point // therefore pbucket1 upper bound greater than pbucket2 upper bound return 1; } return -1; } if (ppoint1->FLessThan(ppoint2)) { return -1; } return 1; } //--------------------------------------------------------------------------- // @function: // CBucket::FIntersects // // @doc: // Does this bucket intersect with another? // //--------------------------------------------------------------------------- BOOL CBucket::FIntersects ( const CBucket *pbucket ) const { if (this->FSingleton() && pbucket->FSingleton()) { return PpLower()->FEqual(pbucket->PpLower()); } if (this->FSingleton()) { return pbucket->FContains(PpLower()); } if (pbucket->FSingleton()) { return FContains(pbucket->PpLower()); } if (this->FSubsumes(pbucket) || pbucket->FSubsumes(this)) { return true; } if (0 >= ICompareLowerBounds(this, pbucket)) { // current bucket starts before the other bucket if (0 >= ICompareLowerBoundToUpperBound(pbucket, this)) { // other bucket starts before current bucket ends return true; } return false; } if (0 >= ICompareLowerBoundToUpperBound(this, pbucket)) { // current bucket starts before the other bucket ends return true; } return false; } //--------------------------------------------------------------------------- // @function: // CBucket::FSubsumes // // @doc: // Does this bucket subsume another? // //--------------------------------------------------------------------------- BOOL CBucket::FSubsumes ( const CBucket *pbucket ) const { // both are singletons if (this->FSingleton() && pbucket->FSingleton()) { return PpLower()->FEqual(pbucket->PpLower()); } // other one is a singleton if (pbucket->FSingleton()) { return this->FContains(pbucket->PpLower()); } INT iPoint1LowerPoint2Lower = ICompareLowerBounds(this, pbucket); INT iPoint1UpperPoint2Upper = ICompareUpperBounds(this, pbucket); return (0 >= iPoint1LowerPoint2Lower && 0 <= iPoint1UpperPoint2Upper); } //--------------------------------------------------------------------------- // @function: // CBucket::PbucketIntersect // // @doc: // Create a new bucket by intersecting with another // and return the percentage of each of the buckets that intersect. // Points will be shared //--------------------------------------------------------------------------- CBucket * CBucket::PbucketIntersect ( IMemoryPool *pmp, CBucket *pbucket, CDouble *pdFreqIntersect1, CDouble *pdFreqIntersect2 ) const { // should only be called on intersecting bucket GPOS_ASSERT(FIntersects(pbucket)); CPoint *ppNewLower = CPoint::PpointMax(this->PpLower(), pbucket->PpLower()); CPoint *ppNewUpper = CPoint::PpointMin(this->PpUpper(), pbucket->PpUpper()); BOOL fNewLowerClosed = true; BOOL fNewUpperClosed = true; CDouble dDistanceNew = 1.0; if (!ppNewLower->FEqual(ppNewUpper)) { fNewLowerClosed = this->m_fLowerClosed; fNewUpperClosed = this->m_fUpperClosed; if (ppNewLower->FEqual(pbucket->PpLower())) { fNewLowerClosed = pbucket->FLowerClosed(); if (ppNewLower->FEqual(this->PpLower())) { fNewLowerClosed = this->FLowerClosed() && pbucket->FLowerClosed(); } } if (ppNewUpper->FEqual(pbucket->PpUpper())) { fNewUpperClosed = pbucket->FUpperClosed(); if (ppNewUpper->FEqual(this->PpUpper())) { fNewUpperClosed = this->FUpperClosed() && pbucket->FUpperClosed(); } } dDistanceNew = ppNewUpper->DDistance(ppNewLower); } // TODO: , May 1 2013, distance function for data types such as bpchar/varchar // that require binary comparison GPOS_ASSERT_IMP(!ppNewUpper->Pdatum()->FSupportsBinaryComp(ppNewLower->Pdatum()), dDistanceNew <= DWidth()); GPOS_ASSERT_IMP(!ppNewUpper->Pdatum()->FSupportsBinaryComp(ppNewLower->Pdatum()), dDistanceNew <= pbucket->DWidth()); CDouble dRatio1 = dDistanceNew / DWidth(); CDouble dRatio2 = dDistanceNew / pbucket->DWidth(); // edge case if (FSingleton() && pbucket->FSingleton()) { dRatio1 = CDouble(1.0); dRatio2 = CDouble(1.0); } CDouble dDistinctNew ( std::min ( dRatio1.DVal() * m_dDistinct.DVal(), dRatio2.DVal() * pbucket->m_dDistinct.DVal() ) ); // For computing frequency, we assume that the bucket with larger number // of distinct values corresponds to the dimension. Therefore, selectivity // of the join is: // 1. proportional to the modified frequency values of both buckets // 2. inversely proportional to the max number of distinct values in both buckets CDouble dFreqIntersect1 = dRatio1 * m_dFrequency; CDouble dFreqIntersect2 = dRatio2 * pbucket->m_dFrequency; CDouble dFrequencyNew ( dFreqIntersect1 * dFreqIntersect2 * DOUBLE(1.0) / std::max ( dRatio1.DVal() * m_dDistinct.DVal(), dRatio2.DVal() * pbucket->DDistinct().DVal() ) ); ppNewLower->AddRef(); ppNewUpper->AddRef(); *pdFreqIntersect1 = dFreqIntersect1; *pdFreqIntersect2 = dFreqIntersect2; return GPOS_NEW(pmp) CBucket ( ppNewLower, ppNewUpper, fNewLowerClosed, fNewUpperClosed, dFrequencyNew, dDistinctNew ); } //--------------------------------------------------------------------------- // @function: // CBucket::DWidth // // @doc: // Width of bucket // //--------------------------------------------------------------------------- CDouble CBucket::DWidth() const { if (FSingleton()) { return CDouble(1.0); } else { return m_ppointUpper->DDistance(m_ppointLower); } } //--------------------------------------------------------------------------- // @function: // CBucket::Difference // // @doc: // Remove a bucket range. This produces an upper and lower split either // of which may be NULL. // // //--------------------------------------------------------------------------- void CBucket::Difference ( IMemoryPool *pmp, CBucket *pbucketOther, CBucket **ppbucketLower, CBucket **ppbucketUpper ) { // we shouldn't be overwriting anything important GPOS_ASSERT(NULL == *ppbucketLower); GPOS_ASSERT(NULL == *ppbucketUpper); // if other bucket subsumes this bucket, then result is NULL, NULL if (pbucketOther->FSubsumes(this)) { *ppbucketLower = NULL; *ppbucketUpper = NULL; return; } // if this bucket is below the other bucket, then return this, NULL if (this->FBefore(pbucketOther)) { *ppbucketLower = this->PbucketCopy(pmp); *ppbucketUpper = NULL; return; } // if other bucket is "below" this bucket, then return NULL, this if (pbucketOther->FBefore(this)) { *ppbucketLower = NULL; *ppbucketUpper = this->PbucketCopy(pmp); return; } // if other bucket's LB is after this bucket's LB, then we get a valid first split if (this->PpLower()->FLessThan(pbucketOther->PpLower())) { *ppbucketLower = this->PbucketScaleUpper(pmp, pbucketOther->PpLower(), !pbucketOther->FLowerClosed()); } // if other bucket's UB is lesser than this bucket's LB, then we get a valid split if (pbucketOther->PpUpper()->FLessThan(this->PpUpper())) { *ppbucketUpper = this->PbucketScaleLower(pmp, pbucketOther->PpUpper(), !pbucketOther->FUpperClosed()); } return; } //--------------------------------------------------------------------------- // @function: // CBucket::FBefore // // @doc: // Does this bucket occur before other? E.g. [1,2) is before [3,4) // //--------------------------------------------------------------------------- BOOL CBucket::FBefore ( const CBucket *pbucket ) const { if (this->FIntersects(pbucket)) { return false; } return this->PpUpper()->FLessThanOrEqual(pbucket->PpLower()); } //--------------------------------------------------------------------------- // @function: // CBucket::FAfter // // @doc: // Does this bucket occur after other? E.g. [2,4) is after [1,2) // //--------------------------------------------------------------------------- BOOL CBucket::FAfter ( const CBucket *pbucket ) const { if (this->FIntersects(pbucket)) { return false; } return this->PpLower()->FGreaterThanOrEqual(pbucket->PpUpper()); } //--------------------------------------------------------------------------- // @function: // CBucket::PbucketMerge // // @doc: // Merges with another bucket. Returns merged bucket that should be part // of the output. It also returns what is leftover from the merge. // E.g. // merge of [1,100) and [50,150) produces [1, 100), NULL, [100, 150) // merge of [1,100) and [50,75) produces [1, 75), [75,100), NULL // merge of [1,1) and [1,1) produces [1,1), NULL, NULL // //--------------------------------------------------------------------------- CBucket * CBucket::PbucketMerge ( IMemoryPool *pmp, CBucket *pbucketOther, CDouble dRows, CDouble dRowsOther, CBucket **ppbucket1New, CBucket **ppbucket2New, BOOL fUnionAll ) { // we shouldn't be overwriting anything important GPOS_ASSERT(NULL == *ppbucket1New); GPOS_ASSERT(NULL == *ppbucket2New); CPoint *ppLowerNew = CPoint::PpointMin(this->PpLower(), pbucketOther->PpLower()); CPoint *ppUpperNew = CPoint::PpointMin(this->PpUpper(), pbucketOther->PpUpper()); CDouble dOverlap = this->DOverlap(ppUpperNew); CDouble dDistinct = this->DDistinct() * dOverlap; CDouble dRowNew = dRows * this->DFrequency() * dOverlap; CDouble dFrequency = this->DFrequency() * this->DOverlap(ppUpperNew); if (fUnionAll) { CDouble dRowsOutput = (dRowsOther + dRows); CDouble dOverlapOther = pbucketOther->DOverlap(ppUpperNew); dDistinct = dDistinct + (pbucketOther->DDistinct() * dOverlapOther); dRowNew = dRowsOther * pbucketOther->DFrequency() * dOverlapOther; dFrequency = dRowNew / dRowsOutput; } BOOL fUpperClosed = ppLowerNew->FEqual(ppUpperNew); if (ppUpperNew->FLessThan(this->PpUpper())) { *ppbucket1New = this->PbucketScaleLower(pmp, ppUpperNew, !fUpperClosed); } if (ppUpperNew->FLessThan(pbucketOther->PpUpper())) { *ppbucket2New = pbucketOther->PbucketScaleLower(pmp, ppUpperNew, !fUpperClosed); } ppLowerNew->AddRef(); ppUpperNew->AddRef(); return GPOS_NEW(pmp) CBucket(ppLowerNew, ppUpperNew, true /* fLowerClosed */, fUpperClosed, dFrequency, dDistinct); } //--------------------------------------------------------------------------- // @function: // CBucket::DSample // // @doc: // Generate a random data point within bucket boundaries // //--------------------------------------------------------------------------- CDouble CBucket::DSample ( ULONG *pulSeed ) const { GPOS_ASSERT(FCanSample()); CDouble dLow = 0; IDatumStatisticsMappable *pdatumstatsmapableLower = dynamic_cast<IDatumStatisticsMappable *>(m_ppointLower->Pdatum()); IDatumStatisticsMappable *pdatumstatsmapableUpper = dynamic_cast<IDatumStatisticsMappable *>(m_ppointUpper->Pdatum()); DOUBLE dLowerVal = pdatumstatsmapableLower->DMappingVal().DVal(); if (FSingleton()) { return CDouble(dLowerVal); } DOUBLE dUpperVal = pdatumstatsmapableUpper->DMappingVal().DVal(); DOUBLE dRandVal = ((DOUBLE) clib::UlRandR(pulSeed)) / RAND_MAX; return CDouble(dLowerVal + dRandVal * (dUpperVal - dLowerVal)); } //--------------------------------------------------------------------------- // @function: // CBucket::PbucketSingleton // // @doc: // Create a new singleton bucket with the given datum as it lower // and upper bounds // //--------------------------------------------------------------------------- CBucket* CBucket::PbucketSingleton ( IMemoryPool *pmp, IDatum *pdatum ) { GPOS_ASSERT(NULL != pdatum); pdatum->AddRef(); pdatum->AddRef(); return GPOS_NEW(pmp) CBucket ( GPOS_NEW(pmp) CPoint(pdatum), GPOS_NEW(pmp) CPoint(pdatum), true /* fLowerClosed */, true /* fUpperClosed */, CDouble(1.0), CDouble(1.0) ); } // EOF
23.293165
131
0.579029
vitessedata
6388478c98205199031129eabe5f02ca67748796
1,207
hpp
C++
include/Library/Physics/Time.hpp
cowlicks/library-physics
dd314011132430fcf074a9a1633b24471745cf92
[ "Apache-2.0" ]
null
null
null
include/Library/Physics/Time.hpp
cowlicks/library-physics
dd314011132430fcf074a9a1633b24471745cf92
[ "Apache-2.0" ]
null
null
null
include/Library/Physics/Time.hpp
cowlicks/library-physics
dd314011132430fcf074a9a1633b24471745cf92
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @project Library ▸ Physics /// @file Library/Physics/Time.hpp /// @author Lucas Brémond <lucas@loftorbital.com> /// @license Apache License 2.0 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef __Library_Physics_Time__ #define __Library_Physics_Time__ #include <Library/Physics/Time/Instant.hpp> #include <Library/Physics/Time/Duration.hpp> #include <Library/Physics/Time/Interval.hpp> #include <Library/Physics/Time/DateTime.hpp> #include <Library/Physics/Time/Date.hpp> #include <Library/Physics/Time/Time.hpp> #include <Library/Physics/Time/Scale.hpp> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #endif ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
46.423077
160
0.339685
cowlicks
638a1b59b9be595225712a7150cd96d9698d2e34
2,498
cpp
C++
tests/cpp-tests/Classes/VRTest/VRTest.cpp
DelinWorks/adxe
0f1ba3a086d744bb52e157e649fa986ae3c7ab05
[ "MIT" ]
null
null
null
tests/cpp-tests/Classes/VRTest/VRTest.cpp
DelinWorks/adxe
0f1ba3a086d744bb52e157e649fa986ae3c7ab05
[ "MIT" ]
4
2020-10-22T05:45:37.000Z
2020-10-23T12:11:44.000Z
tests/cpp-tests/Classes/VRTest/VRTest.cpp
DelinWorks/adxe
0f1ba3a086d744bb52e157e649fa986ae3c7ab05
[ "MIT" ]
1
2020-10-22T03:17:28.000Z
2020-10-22T03:17:28.000Z
/**************************************************************************** Copyright (c) 2012 cocos2d-x.org Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. https://adxeproject.github.io/ 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 "VRTest.h" USING_NS_CC; VRTests::VRTests() { ADD_TEST_CASE(VRTest1); }; //------------------------------------------------------------------ // // VRTest1 // //------------------------------------------------------------------ VRTest1::VRTest1() { auto size = Director::getInstance()->getVisibleSize(); auto image = Sprite::create("Images/background.png"); image->setPosition(size / 2); addChild(image); auto button = MenuItemFont::create("Enable / Disable VR", [](Ref* ref) { auto glview = Director::getInstance()->getOpenGLView(); auto vrimpl = glview->getVR(); if (vrimpl) { glview->setVR(nullptr); } else { auto genericvr = new VRGenericRenderer; glview->setVR(genericvr); } }); button->setFontSizeObj(16); auto menu = Menu::create(button, nullptr); addChild(menu); menu->setPosition(size / 6); } std::string VRTest1::title() const { return "Testing Generic VR"; } std::string VRTest1::subtitle() const { return "Enable / Disable it with the button"; }
31.620253
78
0.617294
DelinWorks
638c611b543c3ee35594ac1b41efdf74566d2021
2,473
cc
C++
egserver.cc
jdb19937/tewel
e2dc25c0998b2bf2763cd68ff66691e0c9f86928
[ "MIT" ]
null
null
null
egserver.cc
jdb19937/tewel
e2dc25c0998b2bf2763cd68ff66691e0c9f86928
[ "MIT" ]
null
null
null
egserver.cc
jdb19937/tewel
e2dc25c0998b2bf2763cd68ff66691e0c9f86928
[ "MIT" ]
null
null
null
#define __MAKEMORE_EGSERVER_CC__ 1 #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <sys/fcntl.h> #include <sys/socket.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/signal.h> #include <sys/mman.h> #include <netinet/in.h> #include <string.h> #include <string> #include <vector> #include <list> #include "egserver.hh" #include "youtil.hh" #include "chain.hh" #include "colonel.hh" namespace makemore { using namespace std; EGServer::EGServer(const std::vector<std::string> &_ctx, int _pw, int _ph, int _cuda, int _kbs, double _reload, bool _pngout) : Server() { pw = _pw; ph = _ph; ctx = _ctx; chn = NULL; cuda = _cuda; kbs = _kbs; reload = _reload; pngout = _pngout; last_reload = 0.0; } void EGServer::prepare() { setkdev(cuda >= 0 ? cuda : kndevs() > 1 ? 1 : 0); setkbs(kbs); chn = new Chain; for (auto ctxfn : ctx) chn->push(ctxfn, O_RDONLY); chn->prepare(pw, ph); last_reload = now(); Server::prepare(); } void EGServer::extend() { if (reload > 0 && last_reload + reload < now()) { info("reloading chain"); chn->load(); last_reload = now(); } } bool EGServer::handle(Client *client) { int inpn = chn->head->iw * chn->head->ih * chn->head->ic; assert(inpn > 0); while (client->can_read(256 + inpn * sizeof(double))) { uint8_t *hdr = client->inpbuf; int32_t stop; memcpy(&stop, hdr, 4); if (stop > 0 || stop < -4) return false; Paracortex *tail = chn->ctxv[chn->ctxv.size() + stop - 1]; int outn = tail->ow * tail->oh * tail->oc; assert(outn > 0); double *buf = new double[outn]; uint8_t *rgb = new uint8_t[outn]; double *dat = (double *)(client->inpbuf + 256); enk(dat, inpn, chn->kinp()); assert(client->read(NULL, 256 + inpn * sizeof(double))); info(fmt("synthing inpn=%d outn=%d", inpn, outn)); chn->synth(stop); info("done with synth"); dek(tail->kout(), outn, buf); if (pngout) { for (int i = 0; i < outn; ++i) rgb[i] = (uint8_t)clamp(buf[i] * 256.0, 0, 255); assert(tail->oc == 3); uint8_t *png; unsigned long pngn; rgbpng(rgb, tail->ow, tail->oh, &png, &pngn); delete[] buf; delete[] rgb; if (!client->write(png, pngn)) return false; } else { if (!client->write((uint8_t *)buf, outn * sizeof(double))) return false; } } return true; } }
20.608333
138
0.59078
jdb19937
b0ccfed4d8592390066a586e72f4df3e732369d1
3,440
cpp
C++
SurgSim/Devices/MultiAxis/linux/FileDescriptor.cpp
dbungert/opensurgsim
bd30629f2fd83f823632293959b7654275552fa9
[ "Apache-2.0" ]
24
2015-01-19T16:18:59.000Z
2022-03-13T03:29:11.000Z
SurgSim/Devices/MultiAxis/linux/FileDescriptor.cpp
dbungert/opensurgsim
bd30629f2fd83f823632293959b7654275552fa9
[ "Apache-2.0" ]
3
2018-12-21T14:54:08.000Z
2022-03-14T12:38:07.000Z
SurgSim/Devices/MultiAxis/linux/FileDescriptor.cpp
dbungert/opensurgsim
bd30629f2fd83f823632293959b7654275552fa9
[ "Apache-2.0" ]
8
2015-04-10T19:45:36.000Z
2022-02-02T17:00:59.000Z
// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/Devices/MultiAxis/linux/FileDescriptor.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <poll.h> #include <string> #include "SurgSim/Framework/Assert.h" namespace SurgSim { namespace Devices { FileDescriptor::FileDescriptor() : m_descriptor(INVALID_VALUE), m_canRead(false), m_canWrite(false) { } FileDescriptor::FileDescriptor(FileDescriptor&& other) : m_descriptor(other.m_descriptor), m_canRead(other.m_canRead), m_canWrite(other.m_canWrite) { other.m_descriptor = INVALID_VALUE; // take ownership } FileDescriptor& FileDescriptor::operator=(FileDescriptor&& other) { m_descriptor = other.m_descriptor; m_canRead = other.m_canRead; m_canWrite = other.m_canWrite; other.m_descriptor = INVALID_VALUE; // take ownership return *this; } FileDescriptor::~FileDescriptor() { reset(); } bool FileDescriptor::isValid() const { return (m_descriptor != INVALID_VALUE); } bool FileDescriptor::canRead() const { return isValid() && m_canRead; } bool FileDescriptor::canWrite() const { return isValid() && m_canWrite; } int FileDescriptor::get() const { SURGSIM_ASSERT(m_descriptor != INVALID_VALUE); return m_descriptor; } bool FileDescriptor::openForReadingAndWriting(const std::string& path) { reset(); m_descriptor = open(path.c_str(), O_RDWR); m_canRead = true; m_canWrite = true; return isValid(); } bool FileDescriptor::openForReading(const std::string& path) { reset(); m_descriptor = open(path.c_str(), O_RDONLY); m_canRead = true; m_canWrite = false; return isValid(); } bool FileDescriptor::openForWriting(const std::string& path) { reset(); m_descriptor = open(path.c_str(), O_WRONLY); m_canRead = false; m_canWrite = true; return isValid(); } bool FileDescriptor::openForReadingAndMaybeWriting(const std::string& path) { if (! openForReadingAndWriting(path)) { if (! openForReading(path)) { return false; } } return true; } void FileDescriptor::reset() { if (m_descriptor != INVALID_VALUE) { close(m_descriptor); m_descriptor = INVALID_VALUE; } } bool FileDescriptor::hasDataToRead() const { if (! canRead()) { return false; } struct pollfd pollData[1]; pollData[0].fd = m_descriptor; pollData[0].events = POLLIN; //const int timeoutMsec = 10; const int nonBlockingOnly = 0; int status = poll(pollData, 1, nonBlockingOnly); return (status > 0); } bool FileDescriptor::readBytes(void* dataBuffer, size_t bytesToRead, size_t* bytesActuallyRead) { SURGSIM_ASSERT(canRead()); ssize_t numBytesRead = read(m_descriptor, dataBuffer, bytesToRead); if (numBytesRead < 0) { *bytesActuallyRead = 0; return false; } else { *bytesActuallyRead = numBytesRead; return true; } } }; // namespace Devices }; // namespace SurgSim
20.598802
95
0.730523
dbungert
b0d129f89a08b8df69b1999afa3f85faba544a80
1,171
hpp
C++
include/uitsl/fetch/detect_tar.hpp
mmore500/pipe-profile
861babd819909d1bda5e933269e7bc64018272d6
[ "MIT" ]
15
2020-07-31T23:06:09.000Z
2022-01-13T18:05:33.000Z
include/uitsl/fetch/detect_tar.hpp
mmore500/pipe-profile
861babd819909d1bda5e933269e7bc64018272d6
[ "MIT" ]
137
2020-08-13T23:32:17.000Z
2021-10-16T04:00:40.000Z
include/uitsl/fetch/detect_tar.hpp
mmore500/pipe-profile
861babd819909d1bda5e933269e7bc64018272d6
[ "MIT" ]
3
2020-08-09T01:52:03.000Z
2020-10-02T02:13:47.000Z
#pragma once #ifndef UITSL_FETCH_DETECT_TAR_HPP_INCLUDE #define UITSL_FETCH_DETECT_TAR_HPP_INCLUDE #include <fstream> #include <istream> #include "../nonce/ScopeGuard.hpp" #include "../polyfill/filesystem.hpp" namespace uitsl { inline bool detect_tar( const std::filesystem::path& path ) { char buffer[265]; std::ifstream file; const uitsl::ScopeGuard guard( [&](){ file.open( path, std::ios::binary ); }, [&](){ file.close(); } ); file.read( buffer, 265 ); // see https://en.wikipedia.org/wiki/List_of_file_signatures const bool is_posix_tar{ (buffer[257] == 'u') && (buffer[258] == 's') && (buffer[259] == 't') && (buffer[260] == 'a') && (buffer[261] == 'r') && (buffer[262] == '\0') && (buffer[263] == '0') && (buffer[264] == '0') }; const bool is_gnu_tar{ (buffer[257] == 'u') && (buffer[258] == 's') && (buffer[259] == 't') && (buffer[260] == 'a') && (buffer[261] == 'r') && (buffer[262] == ' ') && (buffer[263] == ' ') && (buffer[264] == '\0') }; return is_posix_tar || is_gnu_tar; } } // namespace uitsl #endif // #ifndef UITSL_FETCH_DETECT_TAR_HPP_INCLUDE
21.290909
62
0.570453
mmore500
b0d764c95382d51f1b2857e01d548f2c86a5230b
718
cpp
C++
CrackingTheCodingInterview/IsThisABinarySearchTree.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
CrackingTheCodingInterview/IsThisABinarySearchTree.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
CrackingTheCodingInterview/IsThisABinarySearchTree.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
/* Hidden stub code will pass a root argument to the function below. Complete the function to solve the challenge. Hint: you may want to write one or more helper functions. The Node struct is defined as follows: struct Node { int data; Node* left; Node* right; } */ vector<int> tree; void inOrderTraversal(Node* root) { if(root!=NULL) { inOrderTraversal(root->left); tree.push_back(root->data); inOrderTraversal(root->right); } } bool checkBST(Node* root) { inOrderTraversal(root); for(int i=0; i<tree.size()-1; i++) if(tree[i]>=tree[i+1]) return false; return true; }
24.758621
174
0.577994
HannoFlohr
b0d7ef07b20683853f6b0946d548c3d0a3ec98b4
6,910
cc
C++
stig/indy/disk/util/stig_dm.cc
ctidder/stigdb
d9ef3eb117d46542745ca98c55df13ec71447091
[ "Apache-2.0" ]
5
2018-04-24T12:36:50.000Z
2020-03-25T00:37:17.000Z
stig/indy/disk/util/stig_dm.cc
ctidder/stigdb
d9ef3eb117d46542745ca98c55df13ec71447091
[ "Apache-2.0" ]
null
null
null
stig/indy/disk/util/stig_dm.cc
ctidder/stigdb
d9ef3eb117d46542745ca98c55df13ec71447091
[ "Apache-2.0" ]
2
2018-04-24T12:39:24.000Z
2020-03-25T00:45:08.000Z
/* <stig/indy/disk/util/stig_dm.cc> The 'main' of the Stig disk manager. Copyright 2010-2014 Tagged 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 <iostream> #include <base/booster.h> #include <base/cmd.h> #include <base/log.h> #include <stig/indy/disk/util/disk_util.h> using namespace std; using namespace chrono; using namespace Base; using namespace Stig::Indy::Fiber; using namespace Stig::Indy::Disk; using namespace Stig::Indy::Disk::Util; /* Command-line arguments. */ class TCmd final : public Base::TLog::TCmd { public: /* Construct with defaults. */ TCmd() : ZeroSuperBlock(false), List(false), CreateVolume(false), InstanceName(""), VolumeKind("Stripe"), DeviceSpeed(""), NumDevicesInVolume(0UL), ReplicationFactor(1UL), StripeSizeKB(64), ReadTest(false) {} /* Construct from argc/argv. */ TCmd(int argc, char *argv[]) : TCmd() { Parse(argc, argv, TMeta()); } /* If true, clear the superblock of the provided devices */ bool ZeroSuperBlock; /* If true, then list all the devices. */ bool List; /* If true, then create a new volume. */ bool CreateVolume; std::string InstanceName; std::string VolumeKind; std::string DeviceSpeed; size_t NumDevicesInVolume; size_t ReplicationFactor; size_t StripeSizeKB; /* If true, perform a read test on the specified instance volume */ bool ReadTest; /* The device set. */ std::set<std::string> DeviceSet; private: /* Our meta-type. */ class TMeta final : public Base::TLog::TCmd::TMeta { public: /* Registers our fields. */ TMeta() : Base::TLog::TCmd::TMeta("Stig disk utility") { Param( &TCmd::ZeroSuperBlock, "zero-super-block", Optional, "zero-super-block\0", "Zero out the super block of the provded devices." ); Param( &TCmd::ReadTest, "read-test", Optional, "read-test\0", "Perform a read test on the specified instance volume. (Not Implemented)" ); Param( &TCmd::List, "list", Optional, "list\0l\0", "List all the devices on this system." ); Param( &TCmd::CreateVolume, "create-volume", Optional, "create-volume\0cb\0", "Create a new volume." ); Param( &TCmd::InstanceName, "instance-name", Optional, "instance-name\0iname\0", "The instance name used for the newly created volume." ); Param( &TCmd::VolumeKind, "strategy", Optional, "strategy\0strat\0", "(stripe | chain). The strategy used when creating a new volume." ); Param( &TCmd::DeviceSpeed, "device-speed", Optional, "device-speed\0speed\0", "(fast | slow). The speed of the devices used in creating a new volume." ); Param( &TCmd::NumDevicesInVolume, "num-devices", Optional, "num-devices\0nd\0", "The number of device names expected when creating a new volume." ); Param( &TCmd::ReplicationFactor, "replication-factor", Optional, "replication-factor\0rf\0", "The replication factor used when creating a new volume." ); Param( &TCmd::StripeSizeKB, "stripe-size", Optional, "stripe-size\0", "The stripe size (in KB) used when creating a new striped volume." ); Param( &TCmd::DeviceSet, "dev", Optional, /*"dev\0",*/ "The list of devices on which to act." ); } }; // TCmd::TMeta }; // TCmd int main(int argc, char *argv[]) { ::TCmd cmd(argc, argv); Base::TLog log(cmd); Base::TScheduler scheduler(Base::TScheduler::TPolicy(1, 64, milliseconds(10))); if(cmd.ZeroSuperBlock) { const auto &device_set = cmd.DeviceSet; for (const auto &device : device_set) { string device_path = "/dev/" + device; TDeviceUtil::ZeroSuperBlock(device_path.c_str()); } return EXIT_SUCCESS; } else if (cmd.ReadTest) { throw std::logic_error("Read test is not implemented"); } Util::TCacheCb cache_cb = [](TCacheInstr /*cache_instr*/, const TOffset /*logical_start_offset*/, void */*buf*/, size_t /*count*/) {}; TDiskController controller; TDiskUtil disk_util(&scheduler, &controller, Base::TOpt<std::string>(), cache_cb, true); if (cmd.List) { stringstream ss; //disk_util.List(ss); cout << ss.str(); cout << "Device\t\tStigFS\tVolumeId\tVolume Device #\t# Devices in Volume\tLogical Extent Start\tLogical Extent Size\tVolume Kind\tInstance Name" << endl; TDeviceUtil::ForEachDevice([](const char *path) { TDeviceUtil::TStigDevice device_info; string path_to_device = "/dev/"; path_to_device += path; bool ret = TDeviceUtil::ProbeDevice(path_to_device.c_str(), device_info); cout << "/dev/" << path << "\t"; if (ret) { cout << "YES\t[" << string(device_info.VolumeId.InstanceName) << ", " << device_info.VolumeId.Id << "]" << "\t" << device_info.VolumeDeviceNumber << "\t" << device_info.NumDevicesInVolume << "\t" << device_info.LogicalExtentStart << "\t" << device_info.LogicalExtentSize << "\t"; switch (device_info.VolumeStrategy) { case 1UL: { cout << "Stripe"; break; } case 2UL: { cout << "Chain"; break; } } } cout << endl; return true; }); return EXIT_SUCCESS; } else if (cmd.CreateVolume) { TVolume::TDesc::TKind strategy; TVolume::TDesc::TStorageSpeed speed; if (strncmp(cmd.VolumeKind.c_str(), "stripe", 5) == 0) { strategy = TVolume::TDesc::Striped; } else if (strncmp(cmd.VolumeKind.c_str(), "chain", 4) == 0) { strategy = TVolume::TDesc::Chained; } else { throw std::runtime_error("strategy must be (stripe | chain)"); } if (strncmp(cmd.DeviceSpeed.c_str(), "fast", 4) == 0) { speed = TVolume::TDesc::TStorageSpeed::Fast; } else if (strncmp(cmd.DeviceSpeed.c_str(), "slow", 4) == 0) { speed = TVolume::TDesc::TStorageSpeed::Slow; } else { throw std::runtime_error("device speed must be (fast | slow)"); } disk_util.CreateVolume(cmd.InstanceName, cmd.NumDevicesInVolume, cmd.DeviceSet, strategy, cmd.ReplicationFactor, cmd.StripeSizeKB, speed); } }
33.221154
158
0.618958
ctidder
b0e0e9c86e1475f700fae7a1fb276e7bf76f751f
19,105
cpp
C++
kittycat/catcontainer.cpp
siilky/catomania
cb3a05cbef523d16b8929b390e190e0cd5924ee9
[ "MIT" ]
1
2021-02-05T23:20:07.000Z
2021-02-05T23:20:07.000Z
kittycat/catcontainer.cpp
siilky/catomania
cb3a05cbef523d16b8929b390e190e0cd5924ee9
[ "MIT" ]
null
null
null
kittycat/catcontainer.cpp
siilky/catomania
cb3a05cbef523d16b8929b390e190e0cd5924ee9
[ "MIT" ]
null
null
null
#include "stdafx.h" #include <QMimeData> #include <QVector> #include "catcontainer.h" CatContainer::CatContainer(const JsonValue & config, CatGroup *parent) : TreeItem(parent) , config_(config) , cat_(new CatCtl(config)) , catView_(new CatView(cat_)) { std::wstring tag; config.get(L"Tag", tag); tag_ = QString::fromStdWString(tag); } CatContainer::CatContainer(const CatContainer &r, CatGroup *parent) : TreeItem(parent) , config_(r.config_) , tag_(r.tag_) , cat_(r.cat_) , catView_(r.catView_) { } CatContainer::operator JsonValue &() { config_.set(L"Tag", tag_.toStdWString()); return config_; } int CatContainer::columnCount() const { return 1; } int CatContainer::row() const { if (parent_ != NULL) { CatGroup *cg = static_cast<CatGroup*>(parent_); for (int i = 0; i < cg->cats_.count(); i++) { if (*cg->cats_[i] == *this) { return i; } } } return -1; } QVariant CatContainer::data(int column, int role) const { if (column != 0) { return QVariant(); } switch (role) { case Qt::DecorationRole: { if ( ! catView_) { return QVariant(); } CatView::CatState state = catView_->state(); switch (state) { case CatView::Offline: return QIcon(":/catView/door_16.png"); case CatView::Online: return QIcon(":/catView/door_open_16.png"); case CatView::Locked: return QIcon(":/catView/lock_16.png"); case CatView::MarketOpened: return QIcon(":/catView/cat.png"); case CatView::Dead: return QIcon(":/catView/pirate_flag_16.png"); case CatView::Waiting: return QIcon(":/catView/time.png"); } break; } case Qt::DisplayRole: case Qt::EditRole: { if ( ! tag_.isEmpty()) { return tag_; } QString acc = catView_->currentAccount(); return acc.isEmpty() ? "[...]" : acc; } } return QVariant(); } bool CatContainer::setData(int column, const QVariant &value) { if (column == 0) { tag_ = value.toString(); return true; } return false; } CatGroup::CatGroup() : TreeItem(NULL) { } CatGroup::CatGroup(const CatGroup & r) : TreeItem(NULL) , tag_(r.tag_) { foreach(CatContainer *c, r.cats_) { cats_.push_back(new CatContainer(*c, this)); } } CatGroup::CatGroup(const JsonValue & config) : TreeItem(NULL) { std::wstring tag; config.get(L"Tag", tag); tag_ = QString::fromStdWString(tag); class CatConverter { public: CatConverter(CatGroup * group) : group_(group) {} CatContainer * convertIn(const JsonValue & v) const { return new CatContainer(v, group_); } private: CatGroup * group_; }; std::vector<CatContainer *> cats; config.get(L"Cats", cats, CatConverter(this)); cats_ = QVector<CatContainer *>::fromStdVector(cats).toList(); } CatGroup::~CatGroup() { qDeleteAll(cats_); } CatGroup::operator JsonValue() { JsonValue config; config.set(L"Tag", tag_.toStdWString()); config.set(L"Cats", cats_.toVector().toStdVector(), json::TransparentPtrConversion<CatContainer>()); return config; } int CatGroup::rowCount() const { return cats_.count(); } TreeItem * CatGroup::child(int number) { if (number < 0 || number >= cats_.count()) { return NULL; } return cats_[number]; } int CatGroup::columnCount() const { return 1; } QVariant CatGroup::data(int column, int role) const { if (column != 0) { return QVariant(); } switch(role) { case Qt::DecorationRole: return QIcon(":/multiView/reseller_programm.png"); case Qt::DisplayRole: case Qt::EditRole: return tag_.isEmpty() ? "..." : tag_; } return QVariant(); } bool CatGroup::setData(int column, const QVariant &value) { if (column == 0) { tag_ = value.toString(); return true; } return false; } bool CatGroup::insertChildren(int position, int count) { if (position < 0 || position > cats_.size()) { return false; } for (int row = 0; row < count; ++row) { cats_.insert(position, new CatContainer(JsonValue(), this)); } return true; } bool CatGroup::removeChildren(int position, int count) { if (position < 0 || position > cats_.size()) { return false; } while (position < cats_.count() && count > 0) { CatContainer *cat = cats_.takeAt(position); delete cat; count--; } return true; } // CatTreeModel::~CatTreeModel() { qDeleteAll(groups_); } void CatTreeModel::setCats(const QList<CatGroup*> & cats) { beginResetModel(); // qDeleteAll(groups_); // groups_.clear(); groups_ = cats; endResetModel(); /* if ( ! cats.isEmpty()) { beginInsertRows(QModelIndex(), 0, cats.count()); endInsertRows(); } */ } void CatTreeModel::loadItem(const QString & filename, int row, const QModelIndex & parent) { JsonValue jscfg; if (jscfg.loadFrom(filename.toStdWString()) && jscfg.isObject()) { beginInsertRows(parent, row, row); TreeItem *parentItem = getItem(parent); if (parentItem != NULL) { CatGroup *cg = dynamic_cast<CatGroup*>(parentItem); if (cg != NULL) { if (jscfg.contains(L"Client")) { // old-style configuration cg->cats_.insert(row, new CatContainer(jscfg.get(L"Client"), cg)); } else { cg->cats_.insert(row, new CatContainer(jscfg, cg)); } } } else { // no parent, top-level // TBD groups_.insert(position, new CatGroup()); } endInsertRows(); } } bool CatTreeModel::canBeSaved(const QModelIndex & item) { TreeItem * i = getItem(item); if (i != NULL) { CatContainer *cc = dynamic_cast<CatContainer *>(i); return cc != NULL; } return false; } void CatTreeModel::saveItem(const QString & filename, const QModelIndex & item) { TreeItem * i = getItem(item); if (i != NULL) { CatContainer *cc = dynamic_cast<CatContainer *>(i); if (cc != NULL) { cc->operator JsonValue &().saveTo(filename.toStdWString()); } } } // QModelIndex CatTreeModel::index(int row, int column, const QModelIndex &parent /*= QModelIndex()*/) const { if (parent.isValid() && parent.column() != 0) { return QModelIndex(); } TreeItem *parentItem = getItem(parent); if (parentItem != NULL) { TreeItem *childItem = parentItem->child(row); if (childItem != NULL) { return createIndex(row, column, childItem); } } else { // no parent, top-level if (row < groups_.count()) { return createIndex(row, column, groups_[row]); } } return QModelIndex(); } QModelIndex CatTreeModel::parent(const QModelIndex &index) const { if (!index.isValid()) { return QModelIndex(); } TreeItem *item = getItem(index); if (item != NULL) { TreeItem *parentItem = item->parent(); if (parentItem != NULL) { // parent of not top-level item int pos = groups_.indexOf(static_cast<CatGroup*>(parentItem)); return createIndex(pos, 0, parentItem); } } return QModelIndex(); } int CatTreeModel::rowCount(const QModelIndex &parent /*= QModelIndex()*/) const { TreeItem *parentItem = getItem(parent); if (parentItem != NULL) { return parentItem->rowCount(); } else { // top-level return groups_.count(); } } int CatTreeModel::columnCount(const QModelIndex &parent /*= QModelIndex()*/) const { TreeItem *parentItem = getItem(parent); if (parentItem != NULL) { if (parentItem->rowCount() > 0) { return parentItem->child(0)->columnCount(); } } else { // top-level if (groups_.count() > 0) { return groups_[0]->columnCount(); } } return 0; } QVariant CatTreeModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) { return QVariant(); } switch(role) { case Qt::DecorationRole: case Qt::DisplayRole: case Qt::EditRole: { TreeItem *item = getItem(index); if (item != 0) { return item->data(index.column(), role); } break; } case CatItemRole: { TreeItem *item = getItem(index); if (item != 0) { return QVariant::fromValue((void*)item); } break; } } return QVariant(); } QVariant CatTreeModel::headerData(int /*section*/, Qt::Orientation /*orientation*/, int /*role*/ /*= Qt::DisplayRole*/) const { return QVariant(); } bool CatTreeModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (role != Qt::EditRole) { return false; } TreeItem *item = getItem(index); bool result = item->setData(index.column(), value); if (result) { emit dataChanged(index, index); } return result; } Qt::ItemFlags CatTreeModel::flags(const QModelIndex &index) const { return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsDragEnabled | ((index.isValid() && index.parent().isValid()) ? 0 : Qt::ItemIsDropEnabled) | /*((index.isValid() && index.parent().isValid()) ? */Qt::ItemIsSelectable/* : 0)*/; } Qt::DropActions CatTreeModel::supportedDropActions() const { return Qt::MoveAction | Qt::CopyAction; } bool CatTreeModel::insertRows(int position, int rows, const QModelIndex &parent /*= QModelIndex()*/) { beginInsertRows(parent, position, position + rows - 1); bool success = false; TreeItem *parentItem = getItem(parent); if (parentItem != NULL) { success = parentItem->insertChildren(position, rows); } else { // no parent, top-level groups_.insert(position, new CatGroup()); } endInsertRows(); return success; } bool CatTreeModel::removeRows(int position, int rows, const QModelIndex &parent /*= QModelIndex()*/) { if (position < 0) { return false; } beginRemoveRows(parent, position, position + rows - 1); bool success = true; TreeItem *parentItem = getItem(parent); if (parentItem != NULL) { success = parentItem->removeChildren(position, rows); } else { // no parent, top-level while (position < groups_.count() && rows > 0) { CatGroup *cg = groups_.takeAt(position); delete cg; rows--; } } endRemoveRows(); return success; } TreeItem *CatTreeModel::getItem(const QModelIndex & index) const { if (index.isValid()) { TreeItem *item = static_cast<TreeItem*>(index.internalPointer()); return item; } else { // top-level items return NULL; } } QStringList CatTreeModel::mimeTypes() const { return QStringList() << "application/x-catmodeldatalist" << "text/uri-list"; } QMimeData * CatTreeModel::mimeData(const QModelIndexList & indexes) const { if (indexes.count() <= 0) { return NULL; } QByteArray encoded; QDataStream stream(&encoded, QIODevice::WriteOnly); for (QModelIndexList::ConstIterator it = indexes.begin(); it != indexes.end(); ++it) { TreeItem *item = static_cast<TreeItem*>(it->internalPointer()); TreeItem *parent= static_cast<TreeItem*>(it->parent().internalPointer()); if (parent == NULL) { // group level CatGroup *cg = static_cast<CatGroup*>(item); stream << false << groups_.indexOf(cg); } else { // cat level CatContainer *cc = static_cast<CatContainer*>(item); CatGroup *cg = static_cast<CatGroup*>(parent); stream << true << groups_.indexOf(cg) << cc->row(); } } QString format = mimeTypes().at(0); QMimeData *data = new QMimeData(); data->setData(format, encoded); return data; } bool CatTreeModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex & parent) { QStringList types = mimeTypes(); if (!data || types.isEmpty() || (data->hasFormat(types.at(0)) && action != Qt::MoveAction) || (data->hasFormat(types.at(1)) && action != Qt::CopyAction)) { return false; } if (column == -1) column = 0; // move to // - empty space: parent=-1 row=-1 // - on group: parent=group row=-1 // - below group: parent=-1 row=nextGroup // - above group: parent=-1 row=group // - on cat: parent=cat row=-1 // - between cats: parent=group row=cat if (data->hasFormat(types.at(0))) { QByteArray encoded = data->data(types.at(0)); QDataStream stream(&encoded, QIODevice::ReadOnly); bool isCat; int fromGroup; stream >> isCat >> fromGroup; if (isCat) { // moving cat to other group or within group int fromRow; stream >> fromRow; QModelIndex fromIdx = index(fromRow, 0, index(fromGroup, 0, QModelIndex())); QModelIndex toGroupIdx = parent; int toRow = 0; if (parent.parent().isValid()) // directly to cat { toRow = parent.row(); toGroupIdx = parent.parent(); if (toRow > fromRow && toGroupIdx.row() >= fromGroup) { toRow++; } } else if (parent.isValid() && row >= 0) // between cats; row < 0 : directly to groups { toRow = row; } else if (parent.isValid() && row < 0) // directly on group { TreeItem *item = (TreeItem *)parent.internalPointer(); toRow = item->rowCount(); } else if (row < 0) // && ! parent.isValid() // to empty space { if ( ! groups_.isEmpty()) { toGroupIdx = index(groups_.count() - 1, 0, QModelIndex()); toRow = groups_[toGroupIdx.row()]->rowCount(); } } else // row >= 0 && !parent.isValid() // group level between groups { if ( ! groups_.isEmpty()) { toGroupIdx = index(row > 0 ? row - 1 : row, 0, QModelIndex()); toRow = groups_[toGroupIdx.row()]->rowCount(); } } beginInsertRows(toGroupIdx, toRow, toRow); groups_[toGroupIdx.row()]->put(toRow, new CatContainer(*groups_[fromGroup]->cats_[fromRow], groups_[toGroupIdx.row()])); endInsertRows(); } else { // moving/reordering groups int toRow; if (parent.parent().isValid()) // directly to cat { toRow = parent.parent().row(); } else if (parent.isValid()) // row >= 0 : between cats; row < 0 : directly on group { toRow = parent.row(); } else if (row < 0) // && ! parent.isValid() // to empty space { toRow = groups_.count(); } else // row >= 0 && !parent.isValid() // group level between groups { toRow = row; } // 'down' direction should increment index by 1 if (toRow > fromGroup && !(row >= 0 && !parent.isValid())) { toRow++; } beginInsertRows(QModelIndex(), toRow, toRow); groups_.insert(toRow, new CatGroup(*groups_[fromGroup])); endInsertRows(); } } else if (data->hasFormat(types.at(1))) { // QByteArray encoded = data->data(types.at(1)); // QString filename = QString::fromWCharArray((wchar_t*)encoded.data(), encoded.count() / sizeof(wchar_t)); QModelIndex toGroupIdx = parent; int toRow = 0; if (parent.parent().isValid()) // directly to cat { toRow = parent.row(); toGroupIdx = parent.parent(); } else if (parent.isValid() && row >= 0) // between cats; row < 0 : directly to groups { toRow = row; } else if (parent.isValid() && row < 0) // directly on group { TreeItem *item = (TreeItem *)parent.internalPointer(); toRow = item->rowCount(); } else if (row < 0) // && ! parent.isValid() // to empty space { if ( ! groups_.isEmpty()) { toGroupIdx = index(groups_.count() - 1, 0, QModelIndex()); toRow = groups_[toGroupIdx.row()]->rowCount(); } } else // row >= 0 && !parent.isValid() // group level between groups { if ( ! groups_.isEmpty()) { toGroupIdx = index(row > 0 ? row - 1 : row, 0, QModelIndex()); toRow = groups_[toGroupIdx.row()]->rowCount(); } } QList<QUrl> urlList = data->urls(); for (int i = 0; i < urlList.size(); ++i) { loadItem(urlList[i].toLocalFile(), toRow++, toGroupIdx); } } return true; } void CatTreeModel::itemUpdate(CatView * w) { // TBD should be a tree-like for (int i = 0; i < groups_.count(); i++) { // QModelIndex index = groups_[i]->indexOf(w); QModelIndex index; const QList<CatContainer*> & cats_ = groups_.at(i)->cats_; for (int c = 0; c < cats_.count(); c++) { if (cats_[c]->catView() == w) { index = createIndex(c, 0, cats_[c]); break; } } if (index.isValid()) { emit dataChanged(index, index); break; } } }
24.462228
132
0.521853
siilky
b0e11a739cb231fb61906c2334874e98c5550944
2,190
cpp
C++
libQGLViewer-2.2.6-1/examples/frustumCulling/cullingCamera.cpp
szmurlor/fiver
083251420eb934d860c99dcf1eb07ae5b8ba7e8c
[ "Apache-2.0" ]
null
null
null
libQGLViewer-2.2.6-1/examples/frustumCulling/cullingCamera.cpp
szmurlor/fiver
083251420eb934d860c99dcf1eb07ae5b8ba7e8c
[ "Apache-2.0" ]
null
null
null
libQGLViewer-2.2.6-1/examples/frustumCulling/cullingCamera.cpp
szmurlor/fiver
083251420eb934d860c99dcf1eb07ae5b8ba7e8c
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** Copyright (C) 2002-2006 Gilles Debunne (Gilles.Debunne@imag.fr) This file is part of the QGLViewer library. Version 2.2.6-1, released on July 4, 2007. http://artis.imag.fr/Members/Gilles.Debunne/QGLViewer libQGLViewer 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. libQGLViewer 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 libQGLViewer; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *****************************************************************************/ #include "cullingCamera.h" using namespace qglviewer; float CullingCamera::distanceToFrustumPlane(int index, const Vec& pos) const { return pos * Vec(planeCoefficients[index]) - planeCoefficients[index][3]; } bool CullingCamera::sphereIsVisible(const Vec& center, float radius) const { for (int i=0; i<6; ++i) if (distanceToFrustumPlane(i, center) > radius) return false; return true; } bool CullingCamera::aaBoxIsVisible(const Vec& p1, const Vec& p2, bool* entirely) const { bool allInForAllPlanes = true; for (int i=0; i<6; ++i) { bool allOut = true; for (unsigned int c=0; c<8; ++c) { const Vec pos((c&4)?p1.x:p2.x, (c&2)?p1.y:p2.y, (c&1)?p1.z:p2.z); if (distanceToFrustumPlane(i, pos) > 0.0) allInForAllPlanes = false; else allOut = false; } // The eight points are on the outside side of this plane if (allOut) return false; } if (entirely) // Entirely visible : the eight points are on the inside side of the 6 planes *entirely = allInForAllPlanes; // Too conservative, but tangent cases are too expensive to detect return true; }
31.285714
86
0.664384
szmurlor
b0e43d3b2a34cd1f30259295f2b66697ee18e1cf
3,737
cc
C++
main.cc
tamerfrombk/gbdsm
098798c934de124a7a3b7a37dd67e5de83644b7e
[ "MIT" ]
null
null
null
main.cc
tamerfrombk/gbdsm
098798c934de124a7a3b7a37dd67e5de83644b7e
[ "MIT" ]
null
null
null
main.cc
tamerfrombk/gbdsm
098798c934de124a7a3b7a37dd67e5de83644b7e
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <limits> #include "ops.h" #include "common.h" #include "dasm.h" static void print_help() { std::printf("gbdsm %s -- The GameBoy ROM disassembler.\n", GBDSM_VERSION); std::putchar('\n'); std::puts("Usage: gbdsm '/path/to/rom.gb' [-h] [-b address] [-e address] [--linear | --recursive]"); std::putchar('\n'); std::puts("Optional arguments:"); std::puts("-h show this help message and exit."); std::puts("-b address set the starting address for the disassembler in decimal. Defaults to 0x0."); std::puts("-e address set the end address for the disassembler in decimal. Defaults to the end of ROM."); std::puts("--linear use the linear sweep algorithm for disassembly. This algorithm is the default."); std::puts("--recursive use the recursive search algorithm for disassembly."); } static size_t fsize(std::FILE *file) { size_t curr = std::ftell(file); std::fseek(file, 0, SEEK_END); size_t size = std::ftell(file); std::fseek(file, curr, SEEK_SET); return size; } static gbdsm::Rom read_rom(const char* path) { std::FILE *file = std::fopen(path, "rb"); if (!file) { return gbdsm::Rom{}; } size_t fileSize = fsize(file); gbdsm::Rom rom(fileSize, 0); size_t bytesRead = std::fread(rom.data(), sizeof(uint8_t), fileSize, file); if (bytesRead != fileSize) { std::fclose(file); return gbdsm::Rom{}; } std::fclose(file); return rom; } struct Args { std::string rom_path; size_t begin, end; gbdsm::DisassemblerAlgo algo; bool print_help; }; static Args parse_args(int argc, char **argv) { Args args; if (argc < 2) { return args; } if (std::strcmp("-h", argv[1]) == 0) { args.print_help = true; return args; } args.rom_path = argv[1]; args.begin = 0; args.end = std::numeric_limits<size_t>::max(); args.print_help = false; args.algo = gbdsm::DisassemblerAlgo::LINEAR_SWEEP; for (int i = 2; i < argc;) { if (std::strcmp(argv[i], "-b") == 0) { args.begin = std::stoull(argv[i + 1]); i += 2; } else if (std::strcmp(argv[i], "-e") == 0) { args.end = std::stoull(argv[i + 1]); i += 2; } else if (std::strcmp(argv[i], "-h") == 0) { args.print_help = true; ++i; } else if (std::strcmp(argv[i], "--linear") == 0) { args.algo = gbdsm::DisassemblerAlgo::LINEAR_SWEEP; ++i; } else if (std::strcmp(argv[i], "--recursive") == 0) { args.algo = gbdsm::DisassemblerAlgo::RECURSIVE_SEARCH; ++i; } else { gbdsm::error("Unrecognized argument %s.\n", argv[i]); std::exit(1); } } return args; } int main(int argc, char **argv) { Args args = parse_args(argc, argv); if (args.print_help) { print_help(); return 0; } if (args.rom_path.empty()) { gbdsm::error("The GameBoy ROM file was not supplied.\n"); return 1; } if (args.end < args.begin) { gbdsm::error("The end (%zu) cannot be less than the beginning (%zu).\n", args.end, args.begin); return 1; } auto rom = read_rom(args.rom_path.c_str()); if (rom.empty()) { gbdsm::error("Could not read %s.\n", args.rom_path.c_str()); return 1; } if (args.end > rom.size()) { args.end = rom.size(); } auto dasm = gbdsm::create_dasm(rom, args.algo); dasm->disassemble(args.begin, args.end); }
24.585526
112
0.552047
tamerfrombk
b0e5b0b3e6be2c8f91e67f2995a273dc26c6d985
2,455
cpp
C++
src/Core/Resource/Factory/CAudioGroupLoader.cpp
henriquegemignani/PrimeWorldEditor
741185e8d695c5bc86b7efbfadaf4e5dcd67d4d9
[ "MIT" ]
1
2018-12-25T02:09:27.000Z
2018-12-25T02:09:27.000Z
src/Core/Resource/Factory/CAudioGroupLoader.cpp
henriquegemignani/PrimeWorldEditor
741185e8d695c5bc86b7efbfadaf4e5dcd67d4d9
[ "MIT" ]
null
null
null
src/Core/Resource/Factory/CAudioGroupLoader.cpp
henriquegemignani/PrimeWorldEditor
741185e8d695c5bc86b7efbfadaf4e5dcd67d4d9
[ "MIT" ]
1
2020-02-21T15:22:56.000Z
2020-02-21T15:22:56.000Z
#include "CAudioGroupLoader.h" CAudioGroup* CAudioGroupLoader::LoadAGSC(IInputStream& rAGSC, CResourceEntry *pEntry) { // For now we only load sound define IDs and the group ID! // Version check uint32 Check = rAGSC.PeekLong(); EGame Game = (Check == 0x1 ? EGame::Echoes : EGame::Prime); CAudioGroup *pOut = new CAudioGroup(pEntry); // Read header, navigate to Proj chunk if (Game == EGame::Prime) { rAGSC.ReadString(); pOut->mGroupName = rAGSC.ReadString(); uint32 PoolSize = rAGSC.ReadLong(); rAGSC.Seek(PoolSize + 0x4, SEEK_CUR); } else { rAGSC.Seek(0x4, SEEK_CUR); pOut->mGroupName = rAGSC.ReadString(); pOut->mGroupID = rAGSC.ReadShort(); uint32 PoolSize = rAGSC.ReadLong(); rAGSC.Seek(0xC + PoolSize, SEEK_CUR); } // Read needed data from the Proj chunk uint16 Peek = rAGSC.PeekShort(); if (Peek != 0xFFFF) { uint32 ProjStart = rAGSC.Tell(); rAGSC.Seek(0x4, SEEK_CUR); uint16 GroupID = rAGSC.ReadShort(); uint16 GroupType = rAGSC.ReadShort(); rAGSC.Seek(0x14, SEEK_CUR); uint32 SfxTableStart = rAGSC.ReadLong(); if (Game == EGame::Prime) pOut->mGroupID = GroupID; else ASSERT(pOut->mGroupID == GroupID); if (GroupType == 1) { rAGSC.Seek(ProjStart + SfxTableStart, SEEK_SET); uint16 NumSounds = rAGSC.ReadShort(); rAGSC.Seek(0x2, SEEK_CUR); for (uint32 iSfx = 0; iSfx < NumSounds; iSfx++) { pOut->mDefineIDs.push_back( rAGSC.ReadShort() ); rAGSC.Seek(0x8, SEEK_CUR); } } } return pOut; } CAudioLookupTable* CAudioGroupLoader::LoadATBL(IInputStream& rATBL, CResourceEntry *pEntry) { CAudioLookupTable *pOut = new CAudioLookupTable(pEntry); uint32 NumMacroIDs = rATBL.ReadLong(); for (uint32 iMacro = 0; iMacro < NumMacroIDs; iMacro++) pOut->mDefineIDs.push_back( rATBL.ReadShort() ); return pOut; } CStringList* CAudioGroupLoader::LoadSTLC(IInputStream& rSTLC, CResourceEntry *pEntry) { CStringList *pOut = new CStringList(pEntry); uint32 NumStrings = rSTLC.ReadLong(); pOut->mStringList.reserve(NumStrings); for (uint32 iStr = 0; iStr < NumStrings; iStr++) pOut->mStringList.push_back( rSTLC.ReadString() ); return pOut; }
28.882353
91
0.611405
henriquegemignani
b0e67c98e7e73e9500e520a0d9084a414f5cbcc7
2,621
hh
C++
src/systems/AudioSystem.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
src/systems/AudioSystem.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
src/systems/AudioSystem.hh
rovedit/Fort-Candle
445fb94852df56c279c71b95c820500e7fb33cf7
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> #include <glow/fwd.hh> #include "glow/common/log.hh" #include "ecs/Engine.hh" #include "ecs/System.hh" #include "AL/al.h" #include "AL/alc.h" #include "typed-geometry/tg.hh" #include "utility/Sound.hh" namespace gamedev { class AudioSystem : public System { public: void Init(std::shared_ptr<EngineECS>& ecs); void AddEntity(InstanceHandle& handle, Signature entitySignature); void RemoveEntity(InstanceHandle& handle, Signature entitySignature); void RemoveEntity(InstanceHandle& handle); void RemoveAllEntities(); void Update(float dt); void UpdateListener(tg::pos3 position, tg::vec3 forward, tg::vec3 velocity = {0, 0, 0}); void SetMasterVolume(float value); void SetVolume(int type, float value); void PlayLocalSound(InstanceHandle handle, std::string name, SoundType type = effect, float volume = 1.0f, bool looping = false, float minRadius = 1.f, float maxRadius = 50.f, SoundPriority priority = low); void PlayLocalSound(tg::pos3 position, std::string name, SoundType type = effect, float volume = 1.0f, bool looping = false, float minRadius = 1.f, float maxRadius = 50.f, SoundPriority priority = low); void PlayGlobalSound(std::string name, SoundType type = effect, float volume = 1.0f, bool looping = false, SoundPriority priority = low); void LoadSounds(); void destroy(); private: void UpdateSoundState(InstanceHandle handle, float dt); void CullEmitters(InstanceHandle handle); void CleanupLocalEmitters(); void AttachSource(InstanceHandle handle, OALSource* s); void DetachSource(InstanceHandle handle); void DetachSources(vector<InstanceHandle>::iterator from, vector<InstanceHandle>::iterator to); void AttachSources(vector<InstanceHandle>::iterator from, vector<InstanceHandle>::iterator to); OALSource* GetSource(); bool CompareNodesByPriority(InstanceHandle handle1, InstanceHandle handle2); std::shared_ptr<EngineECS> mECS; unsigned int channels; float masterVolume; std::vector<float> volumes; std::vector<OALSource*> sources; tg::pos3 mListenerPosition; vector<InstanceHandle> emitters; vector<InstanceHandle> mLocalEmitters; ALCcontext* context; ALCdevice* device; }; }
28.802198
141
0.636398
rovedit
b0e76565499e49fd0da413f8b1c38cf0f93e2bca
2,558
cpp
C++
Frame/OpenGL/Test/StaticMeshTest.cpp
anirul/Frame
6bf93cc032cc53eb9f9c94965f4b7e795812fa13
[ "MIT" ]
null
null
null
Frame/OpenGL/Test/StaticMeshTest.cpp
anirul/Frame
6bf93cc032cc53eb9f9c94965f4b7e795812fa13
[ "MIT" ]
1
2021-02-24T08:59:22.000Z
2021-02-24T08:59:22.000Z
Frame/OpenGL/Test/StaticMeshTest.cpp
anirul/Frame
6bf93cc032cc53eb9f9c94965f4b7e795812fa13
[ "MIT" ]
null
null
null
#include "StaticMeshTest.h" #include <GL/glew.h> #include "Frame/BufferInterface.h" #include "Frame/File/FileSystem.h" #include "Frame/OpenGL/File/LoadStaticMesh.h" #include "Frame/Level.h" namespace test { TEST_F(StaticMeshTest, CreateCubeMeshTest) { EXPECT_EQ(GLEW_OK, glewInit()); ASSERT_TRUE(window_); auto level = std::make_unique<frame::Level>(); auto maybe_mesh_vec = frame::opengl::file::LoadStaticMeshesFromFile( level.get(), frame::file::FindFile("Asset/Model/Cube.obj"), "cube"); ASSERT_TRUE(maybe_mesh_vec); auto mesh_vec = maybe_mesh_vec.value(); auto node_id = mesh_vec.at(0); auto node = level->GetSceneNodeFromId(node_id); ASSERT_TRUE(node); auto static_mesh_id = node->GetLocalMesh(); EXPECT_NE(0, static_mesh_id); frame::StaticMeshInterface* static_mesh = level->GetStaticMeshFromId(static_mesh_id); EXPECT_EQ(1, mesh_vec.size()); EXPECT_TRUE(static_mesh); EXPECT_EQ(0, static_mesh->GetMaterialId()); EXPECT_NE(0, static_mesh->GetPointBufferId()); EXPECT_NE(0, static_mesh->GetNormalBufferId()); EXPECT_NE(0, static_mesh->GetTextureBufferId()); EXPECT_NE(0, static_mesh->GetIndexBufferId()); auto id = static_mesh->GetIndexBufferId(); auto index_buffer = level->GetBufferFromId(id); EXPECT_LE(18, index_buffer->GetSize()); EXPECT_GE(144, index_buffer->GetSize()); EXPECT_TRUE(static_mesh); } TEST_F(StaticMeshTest, CreateTorusMeshTest) { EXPECT_EQ(GLEW_OK, glewInit()); EXPECT_TRUE(window_); auto level = std::make_unique<frame::Level>(); auto maybe_mesh_vec = frame::opengl::file::LoadStaticMeshesFromFile( level.get(), frame::file::FindFile("Asset/Model/Torus.obj"), "torus"); ASSERT_TRUE(maybe_mesh_vec); auto mesh_vec = maybe_mesh_vec.value(); EXPECT_EQ(1, mesh_vec.size()); auto node_id = mesh_vec.at(0); auto node = level->GetSceneNodeFromId(node_id); auto static_mesh_id = node->GetLocalMesh(); EXPECT_NE(0, static_mesh_id); frame::StaticMeshInterface* static_mesh = level->GetStaticMeshFromId(static_mesh_id); ASSERT_TRUE(static_mesh); EXPECT_EQ(0, static_mesh->GetMaterialId()); EXPECT_NE(0, static_mesh->GetPointBufferId()); EXPECT_NE(0, static_mesh->GetNormalBufferId()); EXPECT_NE(0, static_mesh->GetTextureBufferId()); EXPECT_NE(0, static_mesh->GetIndexBufferId()); auto id = static_mesh->GetIndexBufferId(); auto index_buffer = level->GetBufferFromId(id); EXPECT_LE(3456, index_buffer->GetSize()); EXPECT_GE(13824, index_buffer->GetSize()); EXPECT_TRUE(static_mesh); } } // End namespace test.
33.657895
70
0.738468
anirul
b0e9b5edb7d9d7d7b1c61f6b174fcf4a5cd7627b
739
hpp
C++
src/it/resources/expected/cpp_dependent_interface/cpp-headers/dependent_interface.hpp
mutagene/djinni-generator
09b420537183e0f941ae55afbf15d72c3f8b76a1
[ "Apache-2.0" ]
60
2020-10-17T18:05:37.000Z
2022-03-14T22:58:27.000Z
src/it/resources/expected/cpp_dependent_interface/cpp-headers/dependent_interface.hpp
mutagene/djinni-generator
09b420537183e0f941ae55afbf15d72c3f8b76a1
[ "Apache-2.0" ]
85
2020-10-13T21:58:40.000Z
2022-03-16T09:29:01.000Z
src/it/resources/expected/cpp_dependent_interface/cpp-headers/dependent_interface.hpp
mutagene/djinni-generator
09b420537183e0f941ae55afbf15d72c3f8b76a1
[ "Apache-2.0" ]
24
2020-10-16T21:22:31.000Z
2022-03-02T18:15:29.000Z
// AUTOGENERATED FILE - DO NOT MODIFY! // This file was generated by Djinni from cpp_dependent_interface.djinni #pragma once #include "interface_dependency.hpp" #include <memory> #include <optional> class DependentInterface { public: virtual ~DependentInterface() {} virtual void method_taking_interface_dependency(const dropbox::oxygen::nn_shared_ptr<::InterfaceDependency> & dep) = 0; virtual void method_taking_optional_interface_dependency(const std::shared_ptr<::InterfaceDependency> & dep) = 0; virtual dropbox::oxygen::nn_shared_ptr<::InterfaceDependency> method_returning_interface_dependency() = 0; virtual std::shared_ptr<::InterfaceDependency> method_returning_optional_interface_dependency() = 0; };
33.590909
123
0.786198
mutagene
b0ecad68b354c13040a0c987f7568a40d423c4a5
1,012
hh
C++
auxil/broker/include/broker/detail/hash.hh
hugolin615/zeek-4.0.0-ele420520-spring2021
258e9b2ee1f2a4bd45c6332a75304793b7d44d40
[ "Apache-2.0" ]
null
null
null
auxil/broker/include/broker/detail/hash.hh
hugolin615/zeek-4.0.0-ele420520-spring2021
258e9b2ee1f2a4bd45c6332a75304793b7d44d40
[ "Apache-2.0" ]
null
null
null
auxil/broker/include/broker/detail/hash.hh
hugolin615/zeek-4.0.0-ele420520-spring2021
258e9b2ee1f2a4bd45c6332a75304793b7d44d40
[ "Apache-2.0" ]
null
null
null
#pragma once #include <functional> namespace broker { namespace detail { /// Calculate hash for an object and combine with a provided hash. template <class T> inline void hash_combine(size_t& seed, const T& v) { seed ^= std::hash<T>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } template <class It> inline size_t hash_range(It first, It last) { size_t seed = 0; for (; first != last; ++first) hash_combine(seed, *first); return seed; } template <class It> inline void hash_range(size_t& seed, It first, It last) { for (; first != last; ++first) hash_combine(seed, *first); } // Allows hashing of composite types. template <class Container> struct container_hasher { using result_type = size_t; result_type operator()(const Container& c) const { auto result = result_type{0}; auto n = result_type{0}; for (auto& e : c) { hash_combine(result, e); ++n; } hash_combine(result, n); return result; } }; } // namespace detail } // namespace broker
21.531915
69
0.65415
hugolin615
b0f0c9e511948015e676815f65d9fe47a9908ab2
1,514
hpp
C++
src/binary/bin_wrappers.hpp
kbentum/LPLANN
c526113e583058c3b9f4ea5ef5ccc7d5a9d658d3
[ "MIT" ]
null
null
null
src/binary/bin_wrappers.hpp
kbentum/LPLANN
c526113e583058c3b9f4ea5ef5ccc7d5a9d658d3
[ "MIT" ]
null
null
null
src/binary/bin_wrappers.hpp
kbentum/LPLANN
c526113e583058c3b9f4ea5ef5ccc7d5a9d658d3
[ "MIT" ]
null
null
null
#ifndef BINWRAPPERS_HPP #define BINWRAPPERS_HPP #include <vector> #include <memory> #include <math.h> #include "src/construction/layer.hpp" #include "src/binary/conv.hpp" #include "src/binary/fc.hpp" #include "src/ops/print.hpp" //In general, we always assume a function has binary input and output, not reg template <typename T1> void conv2d_wrapper(Layer<T1> & in_layer, Layer<binary16> & out_layer, int slice){ float2bin_conv(in_layer, out_layer, slice); } template <typename T1> void conv2d_wrapper(Layer<T1> & in_layer, Layer<binary16> & out_layer){ float2bin_conv(in_layer, out_layer); } void conv2d_wrapper(Layer<binary16> & in_layer, Layer<binary16> & out_layer){ bin2reg_conv_prep(in_layer, out_layer); reg2bin_conv(in_layer, out_layer); } void fc_wrapper(Layer<binary16> & in_layer, Layer<binary16> & out_layer){ binary16 * arr = out_layer.output->arr; binary16 * in = in_layer.output->arr; bin2reg_fc_prep(in_layer); reg2int_fc(in_layer, out_layer); int2bin_fc_prep(out_layer); } void fc_output_wrapper(Layer<binary16> & in_layer, Layer<binary16> & out_layer){ bin2reg_fc_prep(in_layer); reg2int_fc(in_layer, out_layer); } void bin2float_wrapper(Layer<binary16> & in_layer, Layer<float> & out_layer){ int size = 1; for (int i=0; i < in_layer.output->dims.size(); i++){ size *= in_layer.output->dims[i]; } for (int i = 0; i < size; i++){ out_layer.output->arr[i] = in_layer.output->arr[i] * -2 + 1.0; } } #endif
27.527273
82
0.703435
kbentum
b0f1752b1ca9f4c019ec0e0f115d547f9ff1574b
3,172
cpp
C++
Tridor/src/Log/AppLog.cpp
AzadKshitij/Triger
969dbead69f5ebc40d8ef6bc9ec9d763c4510ecb
[ "MIT" ]
2
2020-10-25T15:51:46.000Z
2020-11-10T15:06:22.000Z
Tridor/src/Log/AppLog.cpp
AzadKshitij/Triger
969dbead69f5ebc40d8ef6bc9ec9d763c4510ecb
[ "MIT" ]
3
2020-11-11T16:54:49.000Z
2020-11-29T14:35:31.000Z
Tridor/src/Log/AppLog.cpp
AzadKshitij/Triger
969dbead69f5ebc40d8ef6bc9ec9d763c4510ecb
[ "MIT" ]
null
null
null
#include "AppLog.h" namespace Triger { void AppLog::Clear() { m_Buf.clear(); m_LineOffsets.clear(); m_LineOffsets.push_back(0); } void AppLog::OnImGuiRender() { /*if (!ImGui::Begin(title, p_open)) { ImGui::End(); return; }*/ // Options menu if (ImGui::BeginPopup("Options")) { ImGui::Checkbox("Auto-scroll", &m_AutoScroll); ImGui::EndPopup(); } // Main window if (ImGui::Button("Options")) ImGui::OpenPopup("Options"); ImGui::SameLine(); bool clear = ImGui::Button("Clear"); ImGui::SameLine(); bool copy = ImGui::Button("Copy"); ImGui::SameLine(); m_Filter.Draw("Filter", -100.0f); ImGui::Separator(); ImGui::BeginChild("scrolling", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar); if (clear) Clear(); if (copy) ImGui::LogToClipboard(); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0)); const char* buf = m_Buf.begin(); const char* buf_end = m_Buf.end(); if (m_Filter.IsActive()) { for (int line_no = 0; line_no < m_LineOffsets.Size; line_no++) { const char* line_start = buf + m_LineOffsets[line_no]; const char* line_end = (line_no + 1 < m_LineOffsets.Size) ? (buf + m_LineOffsets[line_no + 1] - 1) : buf_end; if (m_Filter.PassFilter(line_start, line_end)) ImGui::TextUnformatted(line_start, line_end); } } else { ImGuiListClipper clipper; clipper.Begin(m_LineOffsets.Size); while (clipper.Step()) { for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++) { const char* line_start = buf + m_LineOffsets[line_no]; const char* line_end = (line_no + 1 < m_LineOffsets.Size) ? (buf + m_LineOffsets[line_no + 1] - 1) : buf_end; ImGui::TextUnformatted(line_start, line_end); } } clipper.End(); } ImGui::PopStyleVar(); if (m_AutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY()) ImGui::SetScrollHereY(1.0f); ImGui::EndChild(); ImGui::End(); } void AppLog::ShowExampleAppLog( ) { static AppLog log; // For the demo: add a debug button _BEFORE_ the normal log window contents // We take advantage of a rarely used feature: multiple calls to Begin()/End() are appending to the _same_ window. // Most of the contents of the window will be added by the log.Draw() call. ImGui::SetNextWindowSize(ImVec2(500, 400), ImGuiCond_FirstUseEver); ImGui::Begin("Logs"); if (ImGui::SmallButton("[Debug] Add 5 entries")) { static int counter = 0; const char* categories[3] = { "info", "warn", "error" }; const char* words[] = { "Bumfuzzled", "Cattywampus", "Snickersnee", "Abibliophobia", "Absquatulate", "Nincompoop", "Pauciloquent" }; for (int n = 0; n < 5; n++) { const char* category = categories[counter % IM_ARRAYSIZE(categories)]; const char* word = words[counter % IM_ARRAYSIZE(words)]; log.AddLog("[%05d] [%s] Hello, current time is %.1f, here's a word: '%s'\n", ImGui::GetFrameCount(), category, ImGui::GetTime(), word); counter++; } } // Actually call in the regular Log helper (which will Begin() into the same window as we just did) log.OnImGuiRender( ); ImGui::End(); } }
28.321429
135
0.6529
AzadKshitij
b0f8934becf2b16425721328c498fc05bb52bbd1
49
hpp
C++
libraries/protocol/include/offer/protocol/protocol.hpp
nharan/offer
9d26f480a7d3009969b2b06c0cd2e83772f52c25
[ "MIT" ]
null
null
null
libraries/protocol/include/offer/protocol/protocol.hpp
nharan/offer
9d26f480a7d3009969b2b06c0cd2e83772f52c25
[ "MIT" ]
null
null
null
libraries/protocol/include/offer/protocol/protocol.hpp
nharan/offer
9d26f480a7d3009969b2b06c0cd2e83772f52c25
[ "MIT" ]
null
null
null
#pragma once #include <offer/protocol/block.hpp>
16.333333
35
0.77551
nharan
b0f943d10c768e22f9de9aeeef3c86f9b543356e
822
cpp
C++
8.二叉树的下一个结点/8.二叉树的下一个结点.cpp
shenweichen/coding_interviews
990cc54a62b8fa277b743289e8d6f6e96a95225d
[ "MIT" ]
483
2020-01-05T12:58:59.000Z
2022-03-19T05:44:00.000Z
8.二叉树的下一个结点/8.二叉树的下一个结点.py
moshilangzi/coding_interviews
990cc54a62b8fa277b743289e8d6f6e96a95225d
[ "MIT" ]
1
2020-01-20T08:47:15.000Z
2020-01-27T13:24:15.000Z
8.二叉树的下一个结点/8.二叉树的下一个结点.py
moshilangzi/coding_interviews
990cc54a62b8fa277b743289e8d6f6e96a95225d
[ "MIT" ]
122
2020-01-05T14:10:04.000Z
2022-03-19T05:24:42.000Z
/* struct TreeLinkNode { int val; struct TreeLinkNode *left; struct TreeLinkNode *right; struct TreeLinkNode *next; TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) { } }; */ class Solution { public: TreeLinkNode* GetNext(TreeLinkNode* pNode) { if (pNode->right != nullptr){ TreeLinkNode *p = pNode->right; while(p->left != nullptr){ p = p->left; } return p; } while(pNode->next!=nullptr){ if(isLeftChild(pNode)) return pNode->next; pNode = pNode->next; } return nullptr; } bool isLeftChild(TreeLinkNode* p){ if(p->next!=nullptr && p->next->left == p) return true; else return false; } };
22.833333
70
0.512165
shenweichen
b0fadbdd1f063125434102d8af24ac696e8558bb
1,138
cpp
C++
src/swagger/v1/model/InterfaceProtocolConfig_eth.cpp
gchagnotSpt/openperf
0ae14cb7a685b1b059f707379773fb3bcb421d40
[ "Apache-2.0" ]
20
2019-12-04T01:28:52.000Z
2022-03-17T14:09:34.000Z
src/swagger/v1/model/InterfaceProtocolConfig_eth.cpp
gchagnotSpt/openperf
0ae14cb7a685b1b059f707379773fb3bcb421d40
[ "Apache-2.0" ]
115
2020-02-04T21:29:54.000Z
2022-02-17T13:33:51.000Z
src/swagger/v1/model/InterfaceProtocolConfig_eth.cpp
gchagnotSpt/openperf
0ae14cb7a685b1b059f707379773fb3bcb421d40
[ "Apache-2.0" ]
16
2019-12-03T16:41:18.000Z
2021-11-06T04:44:11.000Z
/** * OpenPerf API * REST API interface for OpenPerf * * OpenAPI spec version: 1 * Contact: support@spirent.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ #include "InterfaceProtocolConfig_eth.h" namespace swagger { namespace v1 { namespace model { InterfaceProtocolConfig_eth::InterfaceProtocolConfig_eth() { m_Mac_address = ""; } InterfaceProtocolConfig_eth::~InterfaceProtocolConfig_eth() { } void InterfaceProtocolConfig_eth::validate() { // TODO: implement validation } nlohmann::json InterfaceProtocolConfig_eth::toJson() const { nlohmann::json val = nlohmann::json::object(); val["mac_address"] = ModelBase::toJson(m_Mac_address); return val; } void InterfaceProtocolConfig_eth::fromJson(nlohmann::json& val) { setMacAddress(val.at("mac_address")); } std::string InterfaceProtocolConfig_eth::getMacAddress() const { return m_Mac_address; } void InterfaceProtocolConfig_eth::setMacAddress(std::string value) { m_Mac_address = value; } } } }
17.242424
75
0.731107
gchagnotSpt
b0fd1a632a37aa3bfb58fd3a6d009f1f672a7c9a
994
cpp
C++
src/hello_imgui/widgets/logger.cpp
jhoffmann2/hello_imgui
7430223491de1ee12b4e3c30cc430d026ae10d62
[ "MIT" ]
245
2020-06-21T10:06:45.000Z
2022-03-24T04:43:23.000Z
src/hello_imgui/widgets/logger.cpp
jhoffmann2/hello_imgui
7430223491de1ee12b4e3c30cc430d026ae10d62
[ "MIT" ]
19
2020-06-22T22:06:25.000Z
2021-09-05T12:28:44.000Z
src/hello_imgui/widgets/logger.cpp
jhoffmann2/hello_imgui
7430223491de1ee12b4e3c30cc430d026ae10d62
[ "MIT" ]
36
2020-06-20T04:42:54.000Z
2022-03-29T10:55:20.000Z
#include "hello_imgui/widgets/logger.h" namespace HelloImGui { namespace Widgets { Logger::Logger(std::string label_, DockSpaceName dockSpaceName_) : DockableWindow(label_, dockSpaceName_, {}) , log_(logBuffer_, maxBufferSize) { this->GuiFonction = [this]() { log_.draw(); }; } void Logger::debug(char const* const format, ...) { va_list args; va_start(args, format); log_.debug(format, args); va_end(args); } void Logger::info(char const* const format, ...) { va_list args; va_start(args, format); log_.info(format, args); va_end(args); } void Logger::warning(char const* const format, ...) { va_list args; va_start(args, format); log_.warning(format, args); va_end(args); } void Logger::error(char const* const format, ...) { va_list args; va_start(args, format); log_.error(format, args); va_end(args); } void Logger::clear() { log_.clear(); } } // namespace Widgets } // namespace HelloImGui
19.115385
64
0.645875
jhoffmann2
b0fe257dc68660f61f07cf6370abb386d9d89965
577
cpp
C++
src/client/src/InkEditorModel.cpp
don-reba/peoples-note
c22d6963846af833c55f4294dd0474e83344475d
[ "BSD-2-Clause" ]
null
null
null
src/client/src/InkEditorModel.cpp
don-reba/peoples-note
c22d6963846af833c55f4294dd0474e83344475d
[ "BSD-2-Clause" ]
null
null
null
src/client/src/InkEditorModel.cpp
don-reba/peoples-note
c22d6963846af833c55f4294dd0474e83344475d
[ "BSD-2-Clause" ]
null
null
null
#include "stdafx.h" #include "InkEditorModel.h" #include "IRegistryKey.h" InkEditorModel::InkEditorModel ( IRegistryKey & registryKey ) : registryKey (registryKey) { } void InkEditorModel::GetPen ( std::wstring & width , std::wstring & color ) { width = registryKey.GetString(L"pen width", L"1px"); color = registryKey.GetString(L"pen color", L"black"); } void InkEditorModel::SetPen ( const wchar_t * width , const wchar_t * color ) { registryKey.SetString(L"pen width", width); registryKey.SetString(L"pen color", color); }
19.233333
56
0.670711
don-reba
b0ffdb556c82bdc96bad3e96c7f850757aa90f06
3,625
cpp
C++
DFS.cpp
BlackTimber-Labs/HacktoberFest2021
393dc81a6d21331007e729a2eafac0ec15b7a45a
[ "MIT" ]
10
2021-10-02T14:14:32.000Z
2021-11-08T09:27:42.000Z
DFS.cpp
BlackTimber-Labs/HacktoberFest2021
393dc81a6d21331007e729a2eafac0ec15b7a45a
[ "MIT" ]
24
2021-10-02T14:33:44.000Z
2021-10-31T17:32:49.000Z
DFS.cpp
BlackTimber-Labs/HacktoberFest2021
393dc81a6d21331007e729a2eafac0ec15b7a45a
[ "MIT" ]
63
2021-10-02T10:22:04.000Z
2021-10-31T18:35:11.000Z
#include <bits/stdc++.h> #include <chrono> //#include <ext/pb_ds/assoc_container.hpp> //#include <ext/pb_ds/tree_policy.hpp> //using namespace __gnu_pbds; using namespace std; using namespace chrono; //template<class T> using oset = tree<T, null_type, less<T>, rb_tree_tag , tree_order_statistics_node_update >; #define ll long long int #define vi vector<int> #define vll vector<ll> #define pb push_back #define pf push_front #define pob pop_back #define pof pop_front #define ff first #define ss second #define lb lower_bound #define ub upper_bound #define ins insert #define read(x) \ for (auto &inps : x) \ cin >> inps #define all(v) v.begin(), v.end() #define F_OR(i, a, b, s) for (int i = (a); (s) > 0 ? i < (b) : i > (b); i += (s)) #define F_OR1(e) F_OR(i, 0, e, 1) #define F_OR2(i, e) F_OR(i, 0, e, 1) #define F_OR3(i, b, e) F_OR(i, b, e, 1) #define F_OR4(i, b, e, s) F_OR(i, b, e, s) #define GET5(a, b, c, d, e, ...) e #define F_ORC(...) GET5(__VA_ARGS__, F_OR4, F_OR3, F_OR2, F_OR1) #define FOR(...) \ F_ORC(__VA_ARGS__) \ (__VA_ARGS__) const int mod = 1e9 + 7; const int smod = 1e5 + 1; void __print(int x) { cerr << x; } void __print(long x) { cerr << x; } void __print(long long x) { cerr << x; } void __print(unsigned x) { cerr << x; } void __print(unsigned long x) { cerr << x; } void __print(unsigned long long x) { cerr << x; } void __print(float x) { cerr << x; } void __print(double x) { cerr << x; } void __print(long double x) { cerr << x; } void __print(char x) { cerr << '\'' << x << '\''; } void __print(const char *x) { cerr << '\"' << x << '\"'; } void __print(const string &x) { cerr << '\"' << x << '\"'; } void __print(bool x) { cerr << (x ? "true" : "false"); } template <typename T, typename V> void __print(const pair<T, V> &x) { cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}'; } template <typename T> void __print(const T &x) { int f = 0; cerr << '{'; for (auto &i : x) cerr << (f++ ? "," : ""), __print(i); cerr << "}"; } void _print() { cerr << "]\n"; } template <typename T, typename... V> void _print(T t, V... v) { __print(t); if (sizeof...(v)) cerr << ", "; _print(v...); } #ifndef ONLINE_JUDGE #define debug(x...) \ cerr << "[" << #x << "] = ["; \ _print(x) #else #define debug(x...) #endif bool isPowerOfTwo(ll n) { return !(n && (n & (n - 1))); } int setBits(ll n) { ll ans = 0; while (n > 0) { n = (n & (n - 1)); ans++; } return ans; } void init_code() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } vector<int> adj[smod]; vector<bool> vis(smod, false); void dfs(vi &dfsvector, int start) { vis[start] = true; dfsvector.pb(start); for (auto i : adj[start]) { if (!vis[i]) { dfs(dfsvector, i); } } } void solve() { int n, m; cin >> n >> m; for (int i = 0; i < m; i++) { int x, y; cin >> x >> y; adj[x].pb(y); adj[y].pb(x); } vector<int> dfsv; dfs(dfsv, 1); for (auto i : dfsv) { cout << i << " "; } } int main() { init_code(); auto start = high_resolution_clock::now(); ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); solve(); auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); float timeCount = duration.count(); timeCount /= 1000000; debug("Time Taken", timeCount); return 0; }
22.376543
112
0.548414
BlackTimber-Labs
7c000c1959c00a89b9a7a760e596ebe108aac7f0
2,416
cpp
C++
CubeEngine/Application/CubeGame/Gun/FPGun.cpp
tangziwen/Cube-Engine
c79b878dcc7e2e382f4463ca63519627d6220afd
[ "MIT" ]
360
2015-01-26T08:15:01.000Z
2021-07-11T16:30:58.000Z
CubeEngine/Application/CubeGame/Gun/FPGun.cpp
tangziwen/Cube-Engine
c79b878dcc7e2e382f4463ca63519627d6220afd
[ "MIT" ]
6
2015-03-09T09:15:07.000Z
2020-07-06T01:34:00.000Z
CubeEngine/Application/CubeGame/Gun/FPGun.cpp
tangziwen/CubeMiniGame
90bffa66d4beba5fddc39fc642a8fb36703cf32d
[ "MIT" ]
41
2015-03-10T03:17:46.000Z
2021-07-13T06:26:26.000Z
#include "FPGun.h" #include "CubeGame/BulletMgr.h" #include "CubeGame/GameUISystem.h" #include "Lighting/PointLight.h" #include "Scene/SceneMgr.h" #include "AudioSystem/AudioSystem.h" namespace tzw { FPGun::FPGun(FPGunData * gunData): m_data(gunData) { m_model = Model::create(m_data->m_filePath); m_model->setPos(0.12,0.6, -0.22); m_model->setRotateE(m_data->m_rotateE); m_model->setScale(vec3(m_data->m_scale, m_data->m_scale, m_data->m_scale)); m_model->setIsAccpectOcTtree(false); auto pointLight = new PointLight(); pointLight->setRadius(5); pointLight->setLightColor(vec3(5, 2.5, 0)); pointLight->setPos(vec3(-33.408, 0, 0)); pointLight->setIsVisible(false); m_pointLight = pointLight; g_GetCurrScene()->addNode(pointLight); m_fireSound = AudioSystem::shared()->createSound("Sound/m4a1.wav"); } void FPGun::setIsADS(bool isADS, bool isNeedTransient) { if(isADS && !m_data->m_isAllowADS)//not allowed aim down sight return; m_isAds = isADS; if(m_isAds) { GameUISystem::shared()->setIsNeedShowCrossHair(false); } else { GameUISystem::shared()->setIsNeedShowCrossHair(true); } } void FPGun::toggleADS(bool isNeedTransient) { setIsADS(!m_isAds, isNeedTransient); } void FPGun::tick(bool isMoving, float dt) { if(m_pointLight->getIsVisible()) { m_flashTime += dt; if(m_flashTime > 0.035) { m_pointLight->setIsVisible(false); m_flashTime = 0.0; } } float offset = 0.002; if(m_isAds) { offset = 0.0005; } float freq = 1.2; if (isMoving) { if(m_isAds) { offset = 0.0008; } else { offset = 0.006; } freq = 8; } m_shakeTime += freq * dt; if(m_isAds) { m_model->setPos(vec3(m_data->m_adsPos.x, m_data->m_adsPos.y + sinf(m_shakeTime) * offset, m_data->m_adsPos.z)); } else { m_model->setPos(vec3(m_data->m_hipPos.x, m_data->m_hipPos.y + sinf(m_shakeTime) * offset, m_data->m_hipPos.z)); } } void FPGun::shoot() { auto cam = g_GetCurrScene()->defaultCamera(); auto mdata = cam->getTransform().data(); vec3 gunPointPos = m_model->getTransform().transformVec3(vec3(-33.408,0, 0)); auto bullet = BulletMgr::shared()->fire(nullptr,cam->getWorldPos() ,gunPointPos, cam->getForward(), 15, BulletType::HitScanTracer); m_pointLight->setIsVisible(true); m_pointLight->setPos(cam->getWorldPos() + cam->getForward() * 0.15); m_flashTime = 0.0; auto event = m_fireSound->playWithOutCare(); event.setVolume(1.2f); } }
23.009524
132
0.695364
tangziwen
7c0049b4a77f51a230bd957d365651322e605be4
132
cpp
C++
src/main.cpp
borninla/R-Shell
72b35fdb5ef7cba23791c65045a8b2bf0272321b
[ "MIT" ]
null
null
null
src/main.cpp
borninla/R-Shell
72b35fdb5ef7cba23791c65045a8b2bf0272321b
[ "MIT" ]
null
null
null
src/main.cpp
borninla/R-Shell
72b35fdb5ef7cba23791c65045a8b2bf0272321b
[ "MIT" ]
null
null
null
#include <iostream> #include "../header/manager.h" using namespace std; int main() { Manager m; m.run(); return 0; }
10.153846
30
0.598485
borninla
7c0649e1ccdc5efa9bae15d7d181ec1eef88d889
1,630
cpp
C++
src/MapEditor/UnitEditor/UnitDlg.cpp
vitek-karas/WarPlusPlus
3abb26ff30dc0e93de906ab6141b89c2fa301ae4
[ "MIT" ]
4
2019-06-17T13:44:49.000Z
2021-01-19T10:39:48.000Z
src/MapEditor/UnitEditor/UnitDlg.cpp
vitek-karas/WarPlusPlus
3abb26ff30dc0e93de906ab6141b89c2fa301ae4
[ "MIT" ]
null
null
null
src/MapEditor/UnitEditor/UnitDlg.cpp
vitek-karas/WarPlusPlus
3abb26ff30dc0e93de906ab6141b89c2fa301ae4
[ "MIT" ]
4
2019-06-17T16:03:20.000Z
2020-02-15T09:14:30.000Z
// UnitDlg.cpp : implementation file // #include "stdafx.h" #include "..\MapEditor.h" #include "UnitDlg.h" #include "..\DataObjects\EMap.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CUnitDlg IMPLEMENT_DYNAMIC(CUnitDlg, CPropertySheet) CUnitDlg::CUnitDlg(UINT nIDCaption, CWnd* pParentWnd, UINT iSelectPage) :CPropertySheet(nIDCaption, pParentWnd, iSelectPage) { } CUnitDlg::CUnitDlg(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage) :CPropertySheet(pszCaption, pParentWnd, iSelectPage) { } CUnitDlg::~CUnitDlg() { } BEGIN_MESSAGE_MAP(CUnitDlg, CPropertySheet) //{{AFX_MSG_MAP(CUnitDlg) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CUnitDlg message handlers void CUnitDlg::Create(CEUnitType *pUnitType, CEMap *pMap) { ASSERT_VALID(pUnitType); ASSERT_VALID(pMap); m_pUnitType = pUnitType; m_pMap = pMap; // we have to load all appearances into the memory // so do it m_pUnitType->LoadGraphics(); m_MainPage.Create(m_pUnitType); AddPage(&m_MainPage); m_ModesPage.Create(m_pUnitType); AddPage(&m_ModesPage); m_AppearancePage.Create(m_pUnitType); AddPage(&m_AppearancePage); m_LandTypesPage.Create(m_pUnitType, m_pMap); AddPage(&m_LandTypesPage); m_SkillsPage.Create(m_pUnitType); AddPage(&m_SkillsPage); } void CUnitDlg::Delete() { // clear the unit appearances m_pUnitType->ReleaseGraphics(); }
22.027027
77
0.678528
vitek-karas
7c09ee479bcf6a832ed5af7a14a248b03e62786c
3,749
cpp
C++
MCMF_Template.cpp
vicennial/Competitive-Coding-Library
48e338ca5f572d44d8f4224cdb373bb0cab5b856
[ "MIT" ]
1
2019-02-20T06:44:04.000Z
2019-02-20T06:44:04.000Z
MCMF_Template.cpp
vicennial/Competitive-Coding-Library
48e338ca5f572d44d8f4224cdb373bb0cab5b856
[ "MIT" ]
null
null
null
MCMF_Template.cpp
vicennial/Competitive-Coding-Library
48e338ca5f572d44d8f4224cdb373bb0cab5b856
[ "MIT" ]
null
null
null
//Gvs Akhil (Vicennial) #include<bits/stdc++.h> #define int long long #define pb push_back #define eb emplace_back #define mp make_pair #define mt make_tuple #define ld(a) while(a--) #define tci(v,i) for(auto i=v.begin();i!=v.end();i++) #define tcf(v,i) for(auto i : v) #define all(v) v.begin(),v.end() #define rep(i,start,lim) for(long long (i)=(start);i<(lim);i++) #define sync ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0) #define osit ostream_iterator #define INF 0x3f3f3f3f #define LLINF 1000111000111000111LL #define PI 3.14159265358979323 #define endl '\n' #define trace1(x) cerr<<#x<<": "<<x<<endl #define trace2(x, y) cerr<<#x<<": "<<x<<" | "<<#y<<": "<<y<<endl #define trace3(x, y, z) cerr<<#x<<":" <<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<endl #define trace4(a, b, c, d) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<endl #define trace5(a, b, c, d, e) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<endl #define trace6(a, b, c, d, e, f) cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<" | "<<#f<<": "<<f<<endl const int N=1000006; using namespace std; typedef vector<int> vi; typedef vector<vi> vvi; typedef long long ll; typedef vector<long long> vll; typedef vector<vll> vvll; typedef long double ld; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<vii> vvii; typedef tuple<int,int,int> iii; typedef set<int> si; typedef complex<double> pnt; typedef vector<pnt> vpnt; typedef priority_queue<ii,vii,greater<ii> > spq; const ll MOD=1000000007LL; template<typename T> T gcd(T a,T b){if(a==0) return b; return gcd(b%a,a);} template<typename T> T power(T x,T y,ll m=MOD){T ans=1;while(y>0){if(y&1LL) ans=(ans*x)%m;y>>=1LL;x=(x*x)%m;}return ans%m;} const int mxN = 40; const int inf = 2e9; struct Edgee { int to, cost, cap, flow, backEdge; }; struct MCMF { int s, t, n; vector<Edgee> g[mxN]; MCMF(int _s, int _t, int _n) { // source,sink, total nodes s = _s, t = _t, n = _n; } void addEdge(int u, int v, int cost, int cap) { // src,dest,cost,capacity Edgee e1 = { v, cost, cap, 0, g[v].size() }; Edgee e2 = { u, -cost, 0, 0, g[u].size() }; g[u].push_back(e1); g[v].push_back(e2); } pair<int, int> minCostMaxFlow() { int flow = 0, cost = 0; vector<int> state(n), from(n), from_edge(n), d(n); deque<int> q; while (true) { for (int i = 0; i < n; i++) state[i] = 2, d[i] = inf, from[i] = -1; state[s] = 1; q.clear(); q.push_back(s); d[s] = 0; while (!q.empty()) { int v = q.front(); q.pop_front(); state[v] = 0; for (int i = 0; i < (int) g[v].size(); i++) { Edgee e = g[v][i]; if (e.flow >= e.cap || d[e.to] <= d[v] + e.cost) continue; int to = e.to; d[to] = d[v] + e.cost; from[to] = v; from_edge[to] = i; if (state[to] == 1) continue; if (!state[to] || (!q.empty() && d[q.front()] > d[to])) q.push_front(to); else q.push_back(to); state[to] = 1; } } if (d[t] == inf) break; int it = t, addflow = inf; while (it != s) { addflow = min(addflow, g[from[it]][from_edge[it]].cap - g[from[it]][from_edge[it]].flow); it = from[it]; } it = t; while (it != s) { g[from[it]][from_edge[it]].flow += addflow; g[it][g[from[it]][from_edge[it]].backEdge].flow -= addflow; cost += g[from[it]][from_edge[it]].cost * addflow; it = from[it]; } flow += addflow; } return {cost,flow}; } }; main(){ }
35.704762
157
0.516671
vicennial
7c0ae2ece9247caf1221df2fc8b40c45c9ea0978
449
hpp
C++
bridge_graph.hpp
ibaned/omega_h_v1
9ab9efca33d66e4411f87206a7bd1534cec116e4
[ "MIT" ]
null
null
null
bridge_graph.hpp
ibaned/omega_h_v1
9ab9efca33d66e4411f87206a7bd1534cec116e4
[ "MIT" ]
null
null
null
bridge_graph.hpp
ibaned/omega_h_v1
9ab9efca33d66e4411f87206a7bd1534cec116e4
[ "MIT" ]
null
null
null
#ifndef BRIDGE_GRAPH_HPP #define BRIDGE_GRAPH_HPP namespace omega_h { void bridge_graph( unsigned nverts, unsigned const* adj_offsets, unsigned const* adj, unsigned* nedges_out, unsigned** verts_of_edges_out); void bridge_dual_graph( unsigned elem_dim, unsigned nelems, unsigned const* elems_of_elems, unsigned* nsides_out, unsigned** elems_of_sides_out, unsigned** elem_side_of_sides_out); } #endif
18.708333
39
0.737194
ibaned
7c125a1bf1323b388cbb4a8620cbecbaa69084dd
6,035
cpp
C++
src/midiutils/midiread.cpp
alexames/midiutils
12ac041c3f2f472473755c46f5f6306e02c2b564
[ "Unlicense" ]
null
null
null
src/midiutils/midiread.cpp
alexames/midiutils
12ac041c3f2f472473755c46f5f6306e02c2b564
[ "Unlicense" ]
null
null
null
src/midiutils/midiread.cpp
alexames/midiutils
12ac041c3f2f472473755c46f5f6306e02c2b564
[ "Unlicense" ]
null
null
null
#include "midiutils.hpp" #include <fstream> #include <iostream> using namespace std; //////////////////////////////////////////////////////////////////////////////// namespace midi { static unsigned int readUInt32be(istream& in) { char data[4]; in.read(data, 4); return (static_cast<unsigned char>(data[0]) << 24) | (static_cast<unsigned char>(data[1]) << 16) | (static_cast<unsigned char>(data[2]) << 8) | static_cast<unsigned char>(data[3]); } static unsigned short readUInt16be(istream& in) { char data[2]; in.read(static_cast<char*>(data), 2); return (static_cast<unsigned char>(data[0]) << 8) | static_cast<unsigned char>(data[1]); } //////////////////////////////////////////////////////////////////////////////// static bool isTrackEnd(const Event& event) { return event.command == Event::Meta && event.meta.command == Event::MetaEvent::EndOfTrack; } static void readEventTime(unsigned int& out, istream& in, unsigned int& byteCount) { out = 0; unsigned char byte; do { byte = in.get(); out <<= 7; out += byte & 0x7f; if (--byteCount == 0) { throw exception(); } } while (byte & 0x80); } static void readNoteEndEvent(Event::NoteEndEvent& event, istream& in, unsigned int& byteCount) { event.noteNumber = in.get(); event.velocity = in.get(); byteCount -= 2; } static void readNoteBeginEvent(Event::NoteBeginEvent& event, istream& in, unsigned int& byteCount) { event.noteNumber = in.get(); event.velocity = in.get(); byteCount -= 2; } static void readVelocityChangeEvent(Event::VelocityChangeEvent& event, istream& in, unsigned int& byteCount) { event.noteNumber = in.get(); event.velocity = in.get(); byteCount -= 2; } static void readControllerChangeEvent(Event::ControllerChangeEvent& event, istream& in, unsigned int& byteCount) { event.controllerNumber = in.get(); event.velocity = in.get(); byteCount -= 2; } static void readProgramChangeEvent(Event::ProgramChangeEvent& event, istream& in, unsigned int& byteCount) { event.newProgramNumber = in.get(); byteCount -= 1; } static void readChannelPressureChangeEvent(Event::ChannelPressureChangeEvent& event, istream& in, unsigned int& byteCount) { event.channelNumber = in.get(); byteCount -= 1; } static void readPitchWheelChangeEvent(Event::PitchWheelChangeEvent& event, istream& in, unsigned int& byteCount) { event.bottom = in.get(); event.top = in.get(); byteCount -= 2; } static void readMetaEvent(Event::MetaEvent& event, istream& in, unsigned int& byteCount) { event.command = static_cast<Event::MetaEvent::MetaCommand>(in.get()); unsigned int length = event.length = in.get(); byteCount -= 2 + event.length; event.data = (char*)malloc(event.length); for (unsigned int i = 0; i < length; i++) event.data[i] = in.get(); } unsigned char readEventCommand(istream& in, unsigned char& previousCommandByte, unsigned int& byteCount) { unsigned char commandByte = in.peek(); if (commandByte & 0x80) { --byteCount; return in.get(); } else { return previousCommandByte; } } static bool readEvent(Event& event, istream& in, unsigned int& byteCount, unsigned char& previousCommandByte, bool strict) { readEventTime(event.timeDelta, in, byteCount); unsigned char commandByte = readEventCommand(in, previousCommandByte, byteCount); previousCommandByte = commandByte; event.command = static_cast<Event::Command>(commandByte & 0xF0); event.channel = commandByte & 0x0F; switch(event.command) { case Event::NoteEnd: readNoteEndEvent(event.noteEnd, in, byteCount); break; case Event::NoteBegin: readNoteBeginEvent(event.noteBegin, in, byteCount); break; case Event::VelocityChange: readVelocityChangeEvent(event.velocityChange, in, byteCount); break; case Event::ControllerChange: readControllerChangeEvent(event.controllerChange, in, byteCount); break; case Event::ProgramChange: readProgramChangeEvent(event.programChange, in, byteCount); break; case Event::ChannelPressureChange: readChannelPressureChangeEvent(event.channelPressureChange, in, byteCount); break; case Event::PitchWheelChange: readPitchWheelChangeEvent(event.pitchWheelChange, in, byteCount); break; case Event::Meta: readMetaEvent(event.meta, in, byteCount); if (isTrackEnd(event)) { if (strict && (byteCount != 0)) { throw exception("Invalid track length"); } else { return false; } } break; default: throw exception("Invalid midi event"); } return true; } static void readTrack(Track& track, istream& in, bool strict) { if (readUInt32be(in) != 'MTrk') { throw exception("Invalid midi track header"); } unsigned int byteCount = readUInt32be(in); unsigned char previousCommand = 0; if (byteCount || !strict) { do { track.events.push_back(Event()); } while (readEvent(track.events.back(), in, byteCount, previousCommand, strict)); } } void readFile(MidiFile& midi, istream& in, bool strict) { if (readUInt32be(in) != 'MThd' || readUInt32be(in) != 0x0006) { throw exception("Invalid midi header"); } midi.format = static_cast<Format>(readUInt16be(in)); midi.tracks.resize(readUInt16be(in)); midi.ticks = readUInt16be(in); for (Track& track : midi.tracks) { readTrack(track, in, strict); } } } // namespace midi
28.738095
123
0.60116
alexames
7c1612776c03d383b17ff57dfd67c9bffced3cb6
516
cpp
C++
compendium/test_bundles/ManagedServiceAndFactoryBundle/src/ManagedServiceFactoryServiceImpl.cpp
fmilano/CppMicroServices
b7e79edb558a63e45f6788e4a8b4e787cf956689
[ "Apache-2.0" ]
588
2015-10-07T15:55:08.000Z
2022-03-29T00:35:44.000Z
compendium/test_bundles/ManagedServiceAndFactoryBundle/src/ManagedServiceFactoryServiceImpl.cpp
fmilano/CppMicroServices
b7e79edb558a63e45f6788e4a8b4e787cf956689
[ "Apache-2.0" ]
459
2015-10-05T23:29:59.000Z
2022-03-29T14:13:37.000Z
compendium/test_bundles/ManagedServiceAndFactoryBundle/src/ManagedServiceFactoryServiceImpl.cpp
fmilano/CppMicroServices
b7e79edb558a63e45f6788e4a8b4e787cf956689
[ "Apache-2.0" ]
218
2015-11-04T08:19:48.000Z
2022-03-24T02:17:08.000Z
#include "ManagedServiceFactoryServiceImpl.hpp" namespace cppmicroservices { namespace service { namespace cm { namespace test { TestManagedServiceFactoryServiceImpl::TestManagedServiceFactoryServiceImpl( int initialValue) : value{ initialValue } {} TestManagedServiceFactoryServiceImpl::~TestManagedServiceFactoryServiceImpl() = default; int TestManagedServiceFactoryServiceImpl::getValue() { return value; } } // namespace test } // namespace cm } // namespace service } // namespace cppmicroservices
20.64
79
0.800388
fmilano
7c1dc825ae6fba53a1fb46f42f03168f1c4d15c6
13,663
cpp
C++
src/executors/sort.cpp
ShubhamAgrawal-13/Relational_Database
5d315633742df18eda6952d286cf86501d93ed58
[ "MIT" ]
null
null
null
src/executors/sort.cpp
ShubhamAgrawal-13/Relational_Database
5d315633742df18eda6952d286cf86501d93ed58
[ "MIT" ]
null
null
null
src/executors/sort.cpp
ShubhamAgrawal-13/Relational_Database
5d315633742df18eda6952d286cf86501d93ed58
[ "MIT" ]
null
null
null
#include"global.h" const int SORT_MAX = 1e5+5; int temp[SORT_MAX]; // bool isDigit(char ch) { // if (ch >= '0' && ch <= '9') // return true; // return false; // } /** * @brief File contains method to process SORT commands. * * syntax: * R <- SORT relation_name BY column_name IN sorting_order * * sorting_order = ASC | DESC */ bool syntacticParseSORT(){ logger.log("syntacticParseSORT"); if(tokenizedQuery.size()== 10){ if(tokenizedQuery[4] != "BY" || tokenizedQuery[6] != "IN" || tokenizedQuery[8] != "BUFFER"){ cout<<"SYNTAX ERROR"<<endl; return false; } parsedQuery.queryType = SORT; parsedQuery.sortResultRelationName = tokenizedQuery[0]; parsedQuery.sortColumnName = tokenizedQuery[5]; parsedQuery.sortRelationName = tokenizedQuery[3]; string sortingStrateg = tokenizedQuery[7]; parsedQuery.sortBuffer = tokenizedQuery[9]; string str = tokenizedQuery[9]; for (int i = 0; i < str.length(); i++) { if (!(str[i] >= '0' && str[i] <= '9')) { cout<<"SYNTAX ERROR : Buffer should be an Integer"<<endl; return false; } } if(sortingStrateg == "ASC") parsedQuery.sortingStrategy = ASC; else if(sortingStrateg == "DESC") parsedQuery.sortingStrategy = DESC; else{ cout<<"SYNTAX ERROR : sorting strategy should be only ASC or DESC"<<endl; return false; } return true; } else if(tokenizedQuery.size()== 8){ if(tokenizedQuery[4] != "BY" || tokenizedQuery[6] != "IN"){ cout<<"SYNTAX ERROR"<<endl; return false; } parsedQuery.queryType = SORT; parsedQuery.sortResultRelationName = tokenizedQuery[0]; parsedQuery.sortColumnName = tokenizedQuery[5]; parsedQuery.sortRelationName = tokenizedQuery[3]; string sortingStrateg = tokenizedQuery[7]; if(sortingStrateg == "ASC") parsedQuery.sortingStrategy = ASC; else if(sortingStrateg == "DESC") parsedQuery.sortingStrategy = DESC; else{ cout<<"SYNTAX ERROR"<<endl; return false; } return true; } cout<<"SYNTAX ERROR"<<endl; return false; } bool semanticParseSORT(){ logger.log("semanticParseSORT"); if(tableCatalogue.isTable(parsedQuery.sortResultRelationName)){ cout<<"SEMANTIC ERROR: Resultant relation already exists"<<endl; return false; } if(!tableCatalogue.isTable(parsedQuery.sortRelationName)){ cout<<"SEMANTIC ERROR: Relation doesn't exist " << parsedQuery.sortRelationName <<endl; return false; } if(!tableCatalogue.isColumnFromTable(parsedQuery.sortColumnName, parsedQuery.sortRelationName)){ cout<<"SEMANTIC ERROR: Column doesn't exist in relation"<<endl; return false; } return true; } /** * @brief Merging Function * * @param a { array which is to be sorted} * @param[in] l { lower index } * @param[in] m { mid index } * @param[in] r { higher index } */ void merging(vector<int> &a, int l, int m, int r){ memset(temp, 0, sizeof(temp)); int i=l; int j=m+1; int k=l; while(i<=m && j<=r){ if(a[i]>a[j]) temp[k++]=a[j++]; else temp[k++]=a[i++]; } while(i<=m) temp[k++]=a[i++]; while(j<=r) temp[k++]=a[j++]; for(int i=l;i<=r;i++) a[i]=temp[i]; } /** * @brief General Merge Sort Algorithm * * @param a { array which is to be sorted} * @param[in] l { lower index } * @param[in] r { higher index } */ void mSort(vector<int> &a, int l, int r) { if(l>=r) return; int m = l + (r - l)/2; //left half mSort(a, l, m); //right half mSort(a, m + 1, r); //merging step merging(a, l, m, r); } /** * @brief Node for heap which is used to merge files. */ struct HeapNode{ int element; string row; int filePointer; }; /** * @brief Comparator for Min Heap */ struct comp_min{ bool operator()(const HeapNode &a, const HeapNode &b) const{ return a.element > b.element; } }; /** * @brief Comparator for Max Heap */ struct comp_max{ bool operator()(const HeapNode &a, const HeapNode &b) const{ return a.element < b.element; } }; /** * @brief Merge Files input files to a output file * * As k is Buffers available. * So, k-1 buffers for input files * and 1 buffer for output. * * @param[in] input_filenames The input filenames * @param[in] output_filename The output filename * @param[in] columnIndex The column index * @param[in] flag The flag (ASC / DESC) */ void mergeFiles(vector<string> input_filenames, string output_filename, int columnIndex, int flag){ int k = input_filenames.size(); ifstream inputPointers[k]; ofstream outputPointer; for(int i=0; i<k; i++){ inputPointers[i].open(input_filenames[i]); } outputPointer.open(output_filename); if(flag==0){ //min priority_queue<HeapNode, vector<HeapNode>, comp_min> min_heap; for(int i=0; i<k; i++){ string line, word; getline(inputPointers[i], line); stringstream s(line); vector<int> temp; while(getline(s, word, ' ')){ temp.push_back(stoi(word)); } min_heap.push({ temp[columnIndex], line, i}); } while(!min_heap.empty()){ HeapNode node = min_heap.top(); min_heap.pop(); outputPointer << node.row <<"\n"; string line, word; if(getline(inputPointers[node.filePointer], line)){ stringstream s(line); vector<int> temp; while(getline(s, word, ' ')){ temp.push_back(stoi(word)); } min_heap.push({ temp[columnIndex], line, node.filePointer}); } } } else{ //max priority_queue<HeapNode, vector<HeapNode>, comp_max> max_heap; for(int i=0; i<k; i++){ string line, word; getline(inputPointers[i], line); stringstream s(line); vector<int> temp; while(getline(s, word, ' ')){ temp.push_back(stoi(word)); } max_heap.push({ temp[columnIndex], line, i}); } while(!max_heap.empty()){ HeapNode node = max_heap.top(); max_heap.pop(); outputPointer << node.row <<"\n"; string line, word; if(getline(inputPointers[node.filePointer], line)){ stringstream s(line); vector<int> temp; while(getline(s, word, ' ')){ temp.push_back(stoi(word)); } max_heap.push({ temp[columnIndex], line, node.filePointer}); } } } // Closing all file pointers for(int i=0; i<k; i++){ inputPointers[i].close(); } outputPointer.close(); } /** * @brief Phase 2 of merge sort i.e., merging * * @param[in] tableName The table name * @param[in] blockCount The block count * @param[in] columnIndex The column index * @param[in] flag The flag (ASC / DESC) * @param[in] k Buffer Size * * @return { return file output filename } */ string phase2(string tableName, int blockCount, int columnIndex, int flag, int k){ //buffers = k ( k-1 inputs and 1 output) vector<string> files; for(int i=0; i<blockCount; i++){ string pageName = "../data/temp/" + tableName + "_temp_Page" + to_string(i); files.push_back(pageName); } int pass=1; while(files.size()>1){ vector<string> files_output; // int passes = ceil(blockCount/1.0*k); int out=0; // number of output files for(int i=0; i<files.size();){ int pp=0; vector<string> inputs; while(pp<k-1 && i<files.size()){ inputs.push_back(files[i]); pp++; i++; } string output_filename = "../data/temp/" + tableName + "_temp_Page_" + to_string(pass) + "_" + to_string(out); mergeFiles(inputs, output_filename, columnIndex, flag); files_output.push_back(output_filename); out++; } //delete all files in files vector for(string file : files){ if (remove(file.c_str())){ logger.log("SORT :: deleting temporary files : ERROR"); cout << "SORT :: deleting temporary files : ERROR"; } else{ logger.log("SORT :: deleting temporary files : SUCCESS"); } } files.clear(); for(string s : files_output){ files.push_back(s); } files_output.clear(); pass++; } return files[0]; } /** * @brief Sort by Decreasing order * * @param[in] a { parameter_description } * @param[in] b { parameter_description } * * @return { description_of_the_return_value } */ bool sortByDesc(const pair<int,int> &a, const pair<int,int> &b){ return a.first>b.first; } /** * @brief Sorting one block * * @param[in] pageName The page name * @param[in] columnIndex The column index * @param[in] columnIndex The flag ASC or DESC */ void sortPage(string pageName, int columnIndex, int flag){ string line, word; ifstream fin(pageName, ios::in); vector<string> rows; vector<pair<int, int>> res; // columnIndex, original index int i=0; while(getline(fin, line)){ stringstream s(line); vector<int> temp; while(getline(s, word, ' ')){ temp.push_back(stoi(word)); } //cout<<temp[columnIndex]<<endl; res.push_back({temp[columnIndex], i}); i++; rows.push_back(line); //cout<<line<<endl; } fin.close(); //cout<<"Read Successfullly\n"; if(flag==0) sort(res.begin(), res.end()); else sort(res.begin(), res.end(), sortByDesc); ofstream fout(pageName, ios::trunc); for (int r = 0; r < res.size(); r++){ auto p = res[r].second; //cout<< rows[p] <<"\n"; fout << rows[p] <<"\n"; } fout.close(); //cout<<"Written Successfullly\n"; } /** * @brief Doing phase 1 of 2 phase merge sort. * Sorting individual pages. * * @param[in] tableName The table name * @param[in] blockCount The block count * @param[in] columnIndex The column index * @param[in] columnIndex The flag ASC or DESC */ void phase1(string tableName, int blockCount, int columnIndex, int flag){ for(int i=0; i<blockCount; i++){ //string pageName = "../data/temp/" + tableName + "_Page" + to_string(i); // cout<<pageName << endl; string pageName1 = "../data/temp/" + tableName + "_Page" + to_string(i); string pageName2 = "../data/temp/" + tableName + "_temp_Page" + to_string(i); string cmd = "cp " + pageName1 + " " + pageName2; system(cmd.c_str()); sortPage(pageName2, columnIndex, flag); // cout<<"Sorted : "<<pageName<<endl; } } // AA <- SORT S BY a IN ASC // AA <- SORT S BY a IN DESC void executeSORT(){ logger.log("executeSORT"); Table* table = tableCatalogue.getTable(parsedQuery.sortRelationName); int k=5; //Initially Default buffers available if(parsedQuery.sortBuffer != ""){ k = stoi(parsedQuery.sortBuffer); } // cout<< parsedQuery.sortRelationName <<endl; // cout<< parsedQuery.sortResultRelationName <<endl; // cout<< parsedQuery.sortColumnName <<endl; // cout<< parsedQuery.sortingStrategy <<endl; cout<<"Block Count : " << table->blockCount<<endl; int columnIndex=0; vector<string> cols = table->columns; for(int i=0; i<cols.size(); i++){ //cout<< i <<" : "<<cols[i]<<endl; if(cols[i] == parsedQuery.sortColumnName){ columnIndex = i; break; } } cout<< "Column Index : " << columnIndex << endl; phase1(parsedQuery.sortRelationName, (int)table->blockCount, columnIndex, parsedQuery.sortingStrategy); string output_filename = phase2(parsedQuery.sortRelationName, (int)table->blockCount, columnIndex, parsedQuery.sortingStrategy, k); //blockify the large file Table *resultantTable = new Table(parsedQuery.sortResultRelationName, table->columns); string line, word; ifstream fin(output_filename, ios::in); while(getline(fin, line)){ stringstream s(line); vector<int> row; while(getline(s, word, ' ')){ row.push_back(stoi(word)); } resultantTable->writeRow<int>(row); } fin.close(); resultantTable->blockify(); tableCatalogue.insertTable(resultantTable); //delete temporary output file if (remove(output_filename.c_str())){ logger.log("SORT :: deleting temporary files : ERROR"); cout << "SORT :: deleting temporary files : ERROR"; } else{ logger.log("SORT :: deleting temporary files : SUCCESS"); } cout<<"Sorting Completed\n"; return; } //added function
27.826884
135
0.554344
ShubhamAgrawal-13
7c20d0729b19017b895a9f9e8dbecfc0e4bd7ed8
2,226
cpp
C++
openbr/plugins/imgproc/inpaint.cpp
kassemitani/openbr
7b453f7abc6f997839a858f4b7686bc5e21ef7b2
[ "Apache-2.0" ]
61
2016-01-27T04:23:04.000Z
2020-06-19T20:45:16.000Z
openbr/plugins/imgproc/inpaint.cpp
kassemitani/openbr
7b453f7abc6f997839a858f4b7686bc5e21ef7b2
[ "Apache-2.0" ]
2
2016-04-09T13:55:15.000Z
2017-11-21T03:08:08.000Z
openbr/plugins/imgproc/inpaint.cpp
kassemitani/openbr
7b453f7abc6f997839a858f4b7686bc5e21ef7b2
[ "Apache-2.0" ]
18
2016-01-27T13:07:47.000Z
2022-01-22T17:19:18.000Z
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 The MITRE Corporation * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <opencv2/photo/photo.hpp> #include <openbr/plugins/openbr_internal.h> using namespace cv; namespace br { /*! * \ingroup transforms * \brief Wraps OpenCV inpainting * \br_link http://docs.opencv.org/modules/photo/doc/inpainting.html * \author Josh Klontz \cite jklontz */ class InpaintTransform : public UntrainableTransform { Q_OBJECT Q_ENUMS(Method) Q_PROPERTY(int radius READ get_radius WRITE set_radius RESET reset_radius STORED false) Q_PROPERTY(Method method READ get_method WRITE set_method RESET reset_method STORED false) public: /*!< */ enum Method { NavierStokes = INPAINT_NS, Telea = INPAINT_TELEA }; private: BR_PROPERTY(int, radius, 1) BR_PROPERTY(Method, method, NavierStokes) Transform *cvtGray; void init() { cvtGray = make("Cvt(Gray)"); } void project(const Template &src, Template &dst) const { inpaint(src, (*cvtGray)(src)<5, dst, radius, method); } }; } // namespace br #include "imgproc/inpaint.moc"
35.333333
94
0.520665
kassemitani
7c2196f9b836bad8e9a1fa61581196663988528e
1,791
cc
C++
Alignment/CommonAlignmentAlgorithm/src/AlignmentExtendedCorrelationsEntry.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
Alignment/CommonAlignmentAlgorithm/src/AlignmentExtendedCorrelationsEntry.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
Alignment/CommonAlignmentAlgorithm/src/AlignmentExtendedCorrelationsEntry.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentExtendedCorrelationsEntry.h" AlignmentExtendedCorrelationsEntry::AlignmentExtendedCorrelationsEntry(void) : // theCounter( 0 ), theNRows(0), theNCols(0) {} AlignmentExtendedCorrelationsEntry::AlignmentExtendedCorrelationsEntry(short unsigned int nRows, short unsigned int nCols) : // theCounter( 0 ), theNRows(nRows), theNCols(nCols), theData(nRows * nCols) {} AlignmentExtendedCorrelationsEntry::AlignmentExtendedCorrelationsEntry(short unsigned int nRows, short unsigned int nCols, const float init) : // theCounter( 0 ), theNRows(nRows), theNCols(nCols), theData(nRows * nCols, init) {} AlignmentExtendedCorrelationsEntry::AlignmentExtendedCorrelationsEntry(const AlgebraicMatrix& mat) : // theCounter( 0 ), theNRows(mat.num_row()), theNCols(mat.num_col()), theData(mat.num_row() * mat.num_col()) { for (int i = 0; i < mat.num_row(); ++i) { for (int j = 0; j < mat.num_col(); ++j) { theData[i * theNCols + j] = mat[i][j]; } } } void AlignmentExtendedCorrelationsEntry::operator*=(const float multiply) { for (std::vector<float>::iterator it = theData.begin(); it != theData.end(); ++it) (*it) *= multiply; } AlgebraicMatrix AlignmentExtendedCorrelationsEntry::matrix(void) const { AlgebraicMatrix result(theNRows, theNCols); for (int i = 0; i < theNRows; ++i) { for (int j = 0; j < theNCols; ++j) { result[i][j] = theData[i * theNCols + j]; } } return result; }
34.442308
98
0.59129
ckamtsikis
7c2206902b5919999e8b1ae74f423c522c6c3c08
1,100
cpp
C++
Testable/Testable/Terrain.cpp
piotr-mamenas/SDL-RTS
5b7bb113156f63d87e83f977593bad2d154d9a8b
[ "MIT" ]
2
2020-01-22T03:21:58.000Z
2020-04-11T16:50:23.000Z
Testable/Testable/Terrain.cpp
piotr-mamenas/SDL-RTS
5b7bb113156f63d87e83f977593bad2d154d9a8b
[ "MIT" ]
null
null
null
Testable/Testable/Terrain.cpp
piotr-mamenas/SDL-RTS
5b7bb113156f63d87e83f977593bad2d154d9a8b
[ "MIT" ]
3
2019-11-08T09:32:17.000Z
2022-03-20T17:18:45.000Z
#include "Terrain.h" #include "GameObject.h" #include <nlohmann\json.hpp> using json = nlohmann::json; Terrain::Terrain(int initialPositionX, int initialPositionY, std::shared_ptr<Terrain> terrainTemplate) : GameObject(initialPositionX, initialPositionY) { _id = terrainTemplate->getId(); _width = terrainTemplate->getWidth(); _height = terrainTemplate->getHeight(); _spriteId = terrainTemplate->getSpriteId(); } Terrain::Terrain(json terrainJson) : GameObject(terrainJson) { deserializeFrom(terrainJson); } bool Terrain::isBlocked(int positionX, int positionY, int width, int height) { if (_isBlocking) { return true; } if (positionX + width < _blockingXStart) { return false; } if (positionX > _blockingXEnd) { return false; } if (positionY + height < _blockingYStart) { return false; } if (positionY > _blockingYEnd) { return false; } return true; } void Terrain::deserializeFrom(json json) { _id = json.at("id").get<int>(); _spriteId = json.at("spriteId").get<int>(); _width = json.at("width").get<int>(); _height = json.at("height").get<int>(); }
18.644068
103
0.705455
piotr-mamenas
7c268a74c47b7d848e1f5195fdab2ea183d3b7ae
2,364
cpp
C++
FileFormats/Key/Key_Friendly.cpp
xloss/NWNFileFormats
0b3fd4fba416bcdb79f4d898a40a4107234ceea0
[ "WTFPL" ]
9
2018-03-02T17:03:43.000Z
2021-09-02T13:26:04.000Z
FileFormats/Key/Key_Friendly.cpp
xloss/NWNFileFormats
0b3fd4fba416bcdb79f4d898a40a4107234ceea0
[ "WTFPL" ]
8
2018-03-04T09:20:46.000Z
2020-12-06T04:28:33.000Z
FileFormats/Key/Key_Friendly.cpp
xloss/NWNFileFormats
0b3fd4fba416bcdb79f4d898a40a4107234ceea0
[ "WTFPL" ]
8
2018-03-04T09:18:49.000Z
2020-12-01T01:15:41.000Z
#include "FileFormats/Key/Key_Friendly.hpp" #include "Utility/Assert.hpp" #include <algorithm> #include <cstring> namespace FileFormats::Key::Friendly { Key::Key(Raw::Key const& rawKey) { // Get the referenced BIFs. for (Raw::KeyFile const& rawFile : rawKey.m_Files) { KeyBifReference reference; reference.m_Drives = rawFile.m_Drives; reference.m_FileSize = rawFile.m_FileSize; std::uint32_t offSetStartIntoFilenameTable = rawKey.m_Header.m_OffsetToFileTable + (rawKey.m_Header.m_BIFCount * sizeof(Raw::KeyFile)); // End of file table std::uint32_t offSetIntoFilenameTable = rawFile.m_FilenameOffset - offSetStartIntoFilenameTable; ASSERT(offSetStartIntoFilenameTable + offSetIntoFilenameTable + rawFile.m_FilenameSize <= rawKey.m_Header.m_OffsetToKeyTable); char const* ptr = rawKey.m_Filenames.data() + offSetIntoFilenameTable; reference.m_Path = std::string(ptr, strnlen(ptr, rawFile.m_FilenameSize)); // Replace all back slash with forward slashes. This avoids any nasty platform-related issues. std::replace(std::begin(reference.m_Path), std::end(reference.m_Path), '\\', '/'); m_ReferencedBifs.emplace_back(std::move(reference)); } // Get the references resources. for (Raw::KeyEntry const& rawEntry : rawKey.m_Entries) { std::string resref = std::string(rawEntry.m_ResRef, rawEntry.m_ResRef + strnlen(rawEntry.m_ResRef, 16)); // NWN is case insensitive and cases are mixed like crazy in the official modules. // We just do the conversion to lower here to simplify things. std::transform(std::begin(resref), std::end(resref), std::begin(resref), ::tolower); KeyBifReferencedResource entry; entry.m_ResRef = std::move(resref); entry.m_ResType = rawEntry.m_ResourceType; entry.m_ResId = rawEntry.m_ResID; entry.m_ReferencedBifResId = rawEntry.m_ResID & 0x00003FFF; // See Bif_Friendly.cpp for explanation. entry.m_ReferencedBifIndex = rawEntry.m_ResID >> 20; m_ReferencedResources.emplace_back(std::move(entry)); } } std::vector<KeyBifReference> const& Key::GetReferencedBifs() const { return m_ReferencedBifs; } std::vector<KeyBifReferencedResource> const& Key::GetReferencedResources() const { return m_ReferencedResources; } }
38.129032
164
0.71066
xloss
7c2d4722dfd3a7e5fea2a29ddb9e407847fefec3
784
cpp
C++
UVa 10759 - Dice Throwing/sample/10759 - Dice Throwing.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 10759 - Dice Throwing/sample/10759 - Dice Throwing.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 10759 - Dice Throwing/sample/10759 - Dice Throwing.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
#include <stdio.h> typedef unsigned long long ULL; ULL gcd(ULL x, ULL y) { if(x == 0) return y; if(y == 0) return x; ULL tmp; while(x%y) { tmp = x, x = y, y = tmp%y; } return y; } int main() { ULL DP[25][151] = {}, total[25]; int i, j, k, n, m; DP[0][0] = 1, total[0] = 1; for(i = 1; i <= 24; i++) { for(j = 6*i; j >= i; j--) { for(k = 1; k <= 6 && j-k >= 0; k++) DP[i][j] += DP[i-1][j-k]; } total[i] = total[i-1]*6; } for(i = 1; i <= 24; i++) { for(j = 6*i; j >= 0; j--) { DP[i][j] += DP[i][j+1]; } } while(scanf("%d %d", &n, &m) == 2) { if(n == 0 && m == 0) break; ULL x = DP[n][m], y = total[n]; ULL GCD = gcd(x, y); x /= GCD; y /= GCD; if(y == 1) printf("%llu\n", x); else printf("%llu/%llu\n", x, y); } return 0; }
18.666667
38
0.422194
tadvi
7c2d81b806417511d7d03b5955e9c996790e4c7d
7,221
hpp
C++
include/poincare_embedding.hpp
nmfisher/poincare-embeddings
9dcf7113e1db468b35d81f02e462f6d01fd7d8b7
[ "MIT" ]
18
2017-10-15T20:47:44.000Z
2021-06-21T02:52:46.000Z
include/poincare_embedding.hpp
nmfisher/poincare-embeddings
9dcf7113e1db468b35d81f02e462f6d01fd7d8b7
[ "MIT" ]
3
2017-10-24T19:17:10.000Z
2017-11-21T10:58:16.000Z
include/poincare_embedding.hpp
nmfisher/poincare-embeddings
9dcf7113e1db468b35d81f02e462f6d01fd7d8b7
[ "MIT" ]
3
2017-10-15T20:47:53.000Z
2018-04-10T11:30:17.000Z
#ifndef POINCARE_EMBEDDING_HPP #define POINCARE_EMBEDDING_HPP #include <cassert> #include <iostream> #include <vector> #include <memory> #include <random> #include <numeric> #include <string> #include <unordered_map> #include <fstream> #include <algorithm> #include <thread> #include <chrono> #include <iomanip> #include "config.hpp" #include "dictionary.hpp" constexpr float EPS = 1e-6; #include "vector.hpp" #include "matrix.hpp" #include "utils.hpp" #include "model.hpp" namespace poincare_disc { /////////////////////////////////////////////////////////////////////////////////////////// // Poincare Embedding /////////////////////////////////////////////////////////////////////////////////////////// template <class RealType> void clip(Vector<RealType>& v, const RealType& thresh = 1-EPS) { RealType vv = v.squared_sum(); if(vv >= thresh*thresh){ v.mult_(thresh / std::sqrt(vv)); } } template <class RealType> bool train_thread(const std::string& infile, Matrix<RealType>& w_i, Matrix<RealType>& w_o, Dictionary<std::string>& dict, const Config<RealType>& config, LinearLearningRate<RealType>& lr, const std::size_t thread_no, const std::size_t token_count_per_thread, const unsigned int seed, const size_t epoch, UniformNegativeSampler& negative_sampler) { // clip for(std::size_t i = 0, I = w_i.nrow(); i < I; ++i){ clip(w_i[i]); clip(w_o[i]); } // start training auto tick = std::chrono::system_clock::now(); auto start_time = tick; constexpr std::size_t progress_interval = 10000; double avg_loss = 0; double cum_loss = 0; std::ifstream ifs(infile); size_t start = thread_no * size(ifs) / config.num_threads; size_t end = (thread_no + 1) * size(ifs) / config.num_threads; seek(ifs, start); int64_t localTokenCount = 0; int64_t totalTokenCount = 0; std::vector<int32_t> line; std::vector<int32_t> target; std::vector<int32_t> window; Model<RealType> model(w_i, w_o, negative_sampler, lr, config, ZeroInitializer<RealType>()); while (ifs.tellg() < end) { dict.getLine(ifs, line); for (int32_t w = 0; w < line.size(); w++) { localTokenCount++; if(thread_no == 0 && localTokenCount % progress_interval == 0 && ifs.tellg() < end){ auto tack = std::chrono::system_clock::now(); auto millisec = std::chrono::duration_cast<std::chrono::milliseconds>(tack-tick).count(); tick = tack; double percent; percent = 100.0 * ifs.tellg() / end; cum_loss += avg_loss; std::cout << "\r" <<std::setw(5) << std::fixed << std::setprecision(5) << percent << " %" << " " << localTokenCount*1000./millisec << " tokens/sec/thread" << " " << "loss: " << avg_loss / progress_interval << " " << "lr: " << lr() << " " << "epoch: " << epoch << " / " << config.max_epoch << std::flush; avg_loss = 0; totalTokenCount += localTokenCount; localTokenCount = 0; } target.push_back(line[w]); // generate context window for (int32_t c = -config.ws; c <= config.ws; c++) { if (c != 0 && w + c >= 0 && w + c < line.size()) { window.push_back(line[w+c]); } } if(window.size() == 0) { continue; } if(config.model == ModelType::CBOW) { avg_loss += model.update(window, target); } else if (config.model == ModelType::SKIPGRAM) { avg_loss += model.update(target, window); } else { std::cout << config.model; } window.clear(); target.clear(); } } if(thread_no == 0){ auto tack = std::chrono::system_clock::now(); auto millisec = std::chrono::duration_cast<std::chrono::milliseconds>(tack-tick).count(); tick = tack; double percent = 100.0; cum_loss += avg_loss; std::cout << "\r" <<std::setw(5) << std::fixed << std::setprecision(5) << percent << " %" << " " << localTokenCount *1000./millisec << " tokens/sec/thread" << " " << "loss: " << cum_loss / totalTokenCount << " " << "lr: " << lr() << " " << "epoch: " << epoch << " / " << config.max_epoch << std::flush; avg_loss = 0; } ifs.close(); return true; } template <class RealType> bool poincare_embedding(const std::string& infile, Matrix<RealType>& w_i, Matrix<RealType>& w_o, Dictionary<std::string>& dict, const Config<RealType>& config) { using real = RealType; std::default_random_engine engine(config.seed); w_i.init(dict.size(), config.dim, config.initializer); w_o.init(dict.size(), config.dim, config.initializer); std::cout << "embedding size: " << w_i.nrow() << " x " << w_i.ncol() << std::endl; // fit LinearLearningRate<real> lr(config.lr0, config.lr1, dict.tokenCount() * config.max_epoch); std::cout << "num_threads = " << config.num_threads << std::endl; std::size_t data_size_per_thread = (size_t) dict.tokenCount() / config.num_threads; std::cout << "data size = " << data_size_per_thread << "/thread" << std::endl; for(std::size_t epoch = 0; epoch < config.max_epoch; ++epoch){ std::cout << std::endl; const unsigned int thread_seed = engine(); // construct negative sampler, shared between threads std::vector<size_t> counts = dict.counts(); UniformNegativeSampler negative_sampler(counts.begin(), counts.end(), thread_seed); // multi thread if(config.num_threads > 1){ std::vector<std::thread> threads; for(std::size_t i = 0; i < config.num_threads; ++i){ threads.push_back(std::thread( [&infile, &w_i, &w_o, &dict, &config, &lr, i, data_size_per_thread, thread_seed, epoch, &negative_sampler ]() mutable { train_thread(infile, w_i, w_o, dict, config, lr, i, data_size_per_thread, thread_seed, epoch, negative_sampler); } )); } for(auto& th : threads){ th.join(); } // single thread } else{ train_thread(infile, w_i, w_o, dict, config, lr, 0, data_size_per_thread, thread_seed, epoch, negative_sampler); } } return true; } } #endif
34.385714
284
0.504778
nmfisher
7c363a4058ccd0b05b8d9b5886de610267d1e842
5,307
hpp
C++
Lodestar/primitives/sets/SetUnion.hpp
helkebir/Lodestar
6b325d3e7a388676ed31d44eac1146630ee4bb2c
[ "BSD-3-Clause" ]
4
2020-06-05T14:08:23.000Z
2021-06-26T22:15:31.000Z
Lodestar/primitives/sets/SetUnion.hpp
helkebir/Lodestar
6b325d3e7a388676ed31d44eac1146630ee4bb2c
[ "BSD-3-Clause" ]
2
2021-06-25T15:14:01.000Z
2021-07-01T17:43:20.000Z
Lodestar/primitives/sets/SetUnion.hpp
helkebir/Lodestar
6b325d3e7a388676ed31d44eac1146630ee4bb2c
[ "BSD-3-Clause" ]
1
2021-06-16T03:15:23.000Z
2021-06-16T03:15:23.000Z
// // Created by Hamza El-Kebir on 6/21/21. // #ifndef LODESTAR_SETUNION_HPP #define LODESTAR_SETUNION_HPP #include "SetExpression.hpp" #include <type_traits> #include <algorithm> namespace ls { namespace primitives { namespace sets { /** * @brief Union of two SetExpressions. * * @details The syntax is as follows: * \code * // C = A U B * auto C = SetUnion(A, B); * \endcode * * @tparam TTypeLeft Type of the left SetExpression. * @tparam TTypeRight Type of the right SetExpression. */ template<typename TTypeLeft, typename TTypeRight> class SetUnion : public SetExpression<SetUnion<TTypeLeft, TTypeRight>> { public: using Base = SetExpression<SetUnion<TTypeLeft, TTypeRight>>; //! Base class. using ltype = TTypeLeft; //! Left type. using rtype = TTypeRight; //! Right type. using type = SetUnion<TTypeLeft, TTypeRight>; //! Expression type. /** * @brief Constructor for the union operation. * * @details The syntax is as follows: * \code * // A U B * SetUnion(A, B); * \endcode * * @param left The left operand. * @param right The right operand. * * @param empty If true, the expression will be treated as the empty set. */ SetUnion(const TTypeLeft &left, const TTypeRight &right, bool empty = false) : left_(left), right_(right), empty_(empty) { // if (std::is_same<TTypeLeft, TTypeRight>::value) // Base::sEnum_ = static_cast<TTypeLeft const &>(left).getEnum(); // else this->sEnum_ = SetEnum::Union; } /** * @brief Returns true if the expression is the empty set. * * @return True if expression is the empty set. */ bool isEmpty() const { return empty_; } /** * @brief Returns true if this expression contains \c el. * * @tparam TElementType Type of the element. * * @param el Element. * * @return True if this expression contains \c el, false otherwise. */ template<typename TElementType> bool contains(const TElementType &el) const { return left_.contains(el) || right_.contains(el); } /** * @brief Creates a union between this expression and another SetExpression. * * @tparam TExpression Type of the other expression. * * @param expr Expression to create a union with. * * @return Union. */ template<typename TOtherExpr> SetUnion<type, TOtherExpr> unionize(const SetExpression <TOtherExpr> &expr) { return SetUnion<type, TOtherExpr>(*this, *static_cast<const TOtherExpr *>(&expr), isEmpty() && expr.isEmpty()); } /** * @brief Returns signed distance to \c p. * * @tparam Derived Derived MatrixBase class. * * @param p A point. * * @return Signed distance. */ template<typename Derived> double sdf(Eigen::MatrixBase<Derived> &p) const { if (isEmpty()) return std::numeric_limits<double>::infinity(); else return std::min(left_.sdf(p), right_.sdf(p)); } /** * @brief Gets the left expression. * * @return Left expression. */ const TTypeLeft &getLeft() const { return left_; } /** * @brief Gets the right expression. * * @return Right expression. */ const TTypeRight &getRight() const { return right_; } protected: const TTypeLeft &left_; //! Left constant reference. const TTypeRight &right_; //! Right constant reference. bool empty_; //! Empty bool. }; } } } #endif //LODESTAR_SETUNION_HPP
35.61745
109
0.419823
helkebir
7c38523fe7d90353fb50cc5dc38bb1f9c613a054
592
inl
C++
rasterizables/RasterizablePrimitiveList.inl
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
6
2015-12-29T07:21:01.000Z
2020-05-29T10:47:38.000Z
rasterizables/RasterizablePrimitiveList.inl
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
null
null
null
rasterizables/RasterizablePrimitiveList.inl
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
null
null
null
/*! \file RasterizablePrimitiveList.inl * \author Jared Hoberock * \brief Inline file for RasterizablePrimitiveList.h. */ #include "RasterizablePrimitiveList.h" template<typename PrimitiveListParentType> void RasterizablePrimitiveList<PrimitiveListParentType> ::rasterize(void) { for(typename Parent0::iterator prim = Parent0::begin(); prim != Parent0::end(); ++prim) { Rasterizable *r = dynamic_cast<Rasterizable*>((*prim).get()); if(r != 0) { r->rasterize(); } // end if } // end for prim } // end RasterizablePrimitiveList::rasterize()
25.73913
65
0.679054
jaredhoberock
7c392c21845d34e3c5949f6343d8f32e2f5399eb
23,141
cpp
C++
include/delfem2/mat4.cpp
nobuyuki83/delfem2
118768431ccc5b77ed10b8f76f625d38e0b552f0
[ "MIT" ]
153
2018-08-16T21:51:33.000Z
2022-03-28T10:34:48.000Z
include/delfem2/mat4.cpp
mmer547/delfem2
4f4b28931c96467ac30948e6b3f83150ea530c92
[ "MIT" ]
63
2018-08-16T21:53:34.000Z
2022-02-22T13:50:34.000Z
include/delfem2/mat4.cpp
mmer547/delfem2
4f4b28931c96467ac30948e6b3f83150ea530c92
[ "MIT" ]
18
2018-12-17T05:39:15.000Z
2021-11-16T08:21:16.000Z
/* * Copyright (c) 2019 Nobuyuki Umetani * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "delfem2/mat4.h" #include <cstring> #include <climits> // ------------------------ namespace delfem2::mat4 { template<typename REAL> DFM2_INLINE void CalcInvMat( REAL *a, const unsigned int n, int &info) { REAL tmp1; info = 0; for (unsigned int i = 0; i < n; i++) { if (fabs(a[i * n + i]) < 1.0e-30) { info = 1; return; } if (a[i * n + i] < 0.0) { info--; } tmp1 = 1 / a[i * n + i]; a[i * n + i] = 1.0; for (unsigned int k = 0; k < n; k++) { a[i * n + k] *= tmp1; } for (unsigned int j = 0; j < n; j++) { if (j != i) { tmp1 = a[j * n + i]; a[j * n + i] = 0.0; for (unsigned int k = 0; k < n; k++) { a[j * n + k] -= tmp1 * a[i * n + k]; } } } } } template<typename REAL> bool CalcInvMatPivot(REAL *a, unsigned int n, unsigned int *tmp) { unsigned int *row = tmp; for (unsigned int ipv = 0; ipv < n; ipv++) { // find maximum REAL big = 0.0; unsigned int pivot_row = UINT_MAX; for (unsigned int i = ipv; i < n; i++) { if (fabs(a[i * n + ipv]) < big) { continue; } big = fabs(a[i * n + ipv]); pivot_row = i; } if (pivot_row == UINT_MAX) { return false; } row[ipv] = pivot_row; // swapping column if (ipv != pivot_row) { for (unsigned int i = 0; i < n; i++) { REAL temp = a[ipv * n + i]; a[ipv * n + i] = a[pivot_row * n + i]; a[pivot_row * n + i] = temp; } } // set diagonal 1 for for pivotting column REAL inv_pivot = 1 / a[ipv * n + ipv]; a[ipv * n + ipv] = 1.0; for (unsigned int j = 0; j < n; j++) { a[ipv * n + j] *= inv_pivot; } // set pivot column 0 except for pivotting column for (unsigned int i = 0; i < n; i++) { if (i == ipv) { continue; } REAL temp = a[i * n + ipv]; a[i * n + ipv] = 0.0; for (unsigned int j = 0; j < n; j++) { a[i * n + j] -= temp * a[ipv * n + j]; } } } // swaping column for (int j = int(n - 1); j >= 0; j--) { if ((unsigned int) j == row[j]) { continue; } for (unsigned int i = 0; i < n; i++) { REAL temp = a[i * n + j]; a[i * n + j] = a[i * n + row[j]]; a[i * n + row[j]] = temp; } } return true; } template<typename REAL> DFM2_INLINE void Normalize3D( REAL vec[3]) { const REAL len = std::sqrt(vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2]); const REAL leninv = 1 / len; vec[0] *= leninv; vec[1] *= leninv; vec[2] *= leninv; } template<typename REAL> DFM2_INLINE void Cross3D( REAL r[3], const REAL v1[3], const REAL v2[3]) { r[0] = v1[1] * v2[2] - v2[1] * v1[2]; r[1] = v1[2] * v2[0] - v2[2] * v1[0]; r[2] = v1[0] * v2[1] - v2[0] * v1[1]; } } // ------------------------------ // below: mat4 template<typename REAL> DFM2_INLINE void delfem2::Mat4_AffineProjectionOrtho( REAL mP[16], REAL xmin, REAL xmax, // -x, +x REAL ymin, REAL ymax, // -y, +y REAL zmin, REAL zmax) // -z, +z { // column 0 mP[0] = static_cast<REAL>(2.0 / (xmax - xmin)); mP[4] = 0; mP[8] = 0; mP[12] = 0; // column 1 mP[1] = 0; mP[5] = static_cast<REAL>(2.0 / (ymax - ymin)); mP[9] = 0; mP[13] = 0; // column 2 mP[2] = 0; mP[6] = 0; mP[10] = static_cast<REAL>(2.0 / (zmax - zmin)); mP[14] = 0; // collumn 3 mP[3] = static_cast<REAL>(-(xmin + xmax) / (xmax - xmin)); mP[7] = static_cast<REAL>(-(ymax + ymin) / (ymax - ymin)); mP[11] = static_cast<REAL>(-(zmax + zmin) / (zmax - zmin)); mP[15] = 1; } #ifdef DFM2_STATIC_LIBRARY template void delfem2::Mat4_AffineProjectionOrtho( double mP[16], double xmin, double xmax, // -x, +x double ymin, double ymax, // -y, +y double zmin, double zmax); // -z, +z template void delfem2::Mat4_AffineProjectionOrtho( float mP[16], float xmin, float xmax, // -x, +x float ymin, float ymax, // -y, +y float zmin, float zmax); // -z, +z #endif // ----------------------- // http://www.3dcpptutorials.sk/index.php?id=2 template<typename REAL> DFM2_INLINE void delfem2::Mat4_AffineProjectionFrustum( REAL mP[16], REAL fovyInRad, REAL aspectRatio, REAL zmin, REAL zmax) { const REAL yratio = 1 / std::tan(fovyInRad / 2); // how z change w.r.t. the y change const REAL xratio = yratio / aspectRatio; // column 0 mP[0] = xratio; mP[4] = 0.0; mP[8] = 0.0; mP[12] = 0.0; // column 1 mP[1] = 0.0; mP[5] = yratio; mP[9] = 0.0; mP[13] = 0.0; // column 2 mP[2] = 0.0; mP[6] = 0.0; mP[10] = -(zmin + zmax) / (zmax - zmin); mP[14] = -1.0; // column 3 mP[3] = 0.0; mP[7] = 0.0; mP[11] = +(zmin * zmax * 2) / (zmax - zmin); mP[15] = 0.0; } #ifdef DFM2_STATIC_LIBRARY template DFM2_INLINE void delfem2::Mat4_AffineProjectionFrustum( float mP[16], float fovyInRad, float aspectRatio, float zmin, float zmax); template DFM2_INLINE void delfem2::Mat4_AffineProjectionFrustum( double mP[16], double fovyInRad, double aspectRatio, double zmin, double zmax); #endif // ----------------------------------------- template<typename REAL> DFM2_INLINE void delfem2::Mat4_AffineLookAt( REAL *Mat, REAL eyex, REAL eyey, REAL eyez, REAL cntx, REAL cnty, REAL cntz, REAL upx, REAL upy, REAL upz) { const REAL eyePosition3D[3] = {eyex, eyey, eyez}; const REAL center3D[3] = {cntx, cnty, cntz}; const REAL upVector3D[3] = {upx, upy, upz}; // ------------------ REAL forward[3] = { center3D[0] - eyePosition3D[0], center3D[1] - eyePosition3D[1], center3D[2] - eyePosition3D[2]}; mat4::Normalize3D(forward); // ------------------ // Side = forward x up REAL side[3] = {1, 0, 0}; mat4::Cross3D(side, forward, upVector3D); mat4::Normalize3D(side); // ------------------ //Recompute up as: up = side x forward REAL up[3] = {0, 1, 0}; mat4::Cross3D(up, side, forward); // ------------------ const REAL Mr[16]{ side[0], side[1], side[2], 0, up[0], up[1], up[2], 0, -forward[0], -forward[1], -forward[2], 0, 0, 0, 0, 1 }; REAL Mt[16]; Mat4_AffineTranslation( Mt, -eyePosition3D[0], -eyePosition3D[1], -eyePosition3D[2]); MatMat4(Mat, Mr, Mt); } #ifdef DFM2_STATIC_LIBRARY template DFM2_INLINE void delfem2::Mat4_AffineLookAt( double *Mr, double eyex, double eyey, double eyez, double cntx, double cnty, double cntz, double upx, double upy, double upz); template DFM2_INLINE void delfem2::Mat4_AffineLookAt( float *Mr, float eyex, float eyey, float eyez, float cntx, float cnty, float cntz, float upx, float upy, float upz); #endif // ------------------------ // below: mat vec template<typename T> DFM2_INLINE void delfem2::Mat4Vec3( T vo[3], const T M[16], const T vi[3]) { vo[0] = M[0 * 4 + 0] * vi[0] + M[0 * 4 + 1] * vi[1] + M[0 * 4 + 2] * vi[2]; vo[1] = M[1 * 4 + 0] * vi[0] + M[1 * 4 + 1] * vi[1] + M[1 * 4 + 2] * vi[2]; vo[2] = M[2 * 4 + 0] * vi[0] + M[2 * 4 + 1] * vi[1] + M[2 * 4 + 2] * vi[2]; } #ifdef DFM2_STATIC_LIBRARY template void delfem2::Mat4Vec3(float vo[3], const float M[16], const float vi[3]); template void delfem2::Mat4Vec3(double vo[3], const double M[16], const double vi[3]); #endif DFM2_INLINE void delfem2::Vec3Mat4( double vo[3], const double vi[3], const double M[16]) { vo[0] = vi[0] * M[0 * 4 + 0] + vi[1] * M[1 * 4 + 0] + vi[2] * M[2 * 4 + 0]; vo[1] = vi[0] * M[0 * 4 + 1] + vi[1] * M[1 * 4 + 1] + vi[2] * M[2 * 4 + 1]; vo[2] = vi[0] * M[0 * 4 + 2] + vi[1] * M[1 * 4 + 2] + vi[2] * M[2 * 4 + 2]; } template<typename T> DFM2_INLINE void delfem2::MatVec4( T v[4], const T A[16], const T x[4]) { v[0] = A[0 * 4 + 0] * x[0] + A[0 * 4 + 1] * x[1] + A[0 * 4 + 2] * x[2] + A[0 * 4 + 3] * x[3]; v[1] = A[1 * 4 + 0] * x[0] + A[1 * 4 + 1] * x[1] + A[1 * 4 + 2] * x[2] + A[1 * 4 + 3] * x[3]; v[2] = A[2 * 4 + 0] * x[0] + A[2 * 4 + 1] * x[1] + A[2 * 4 + 2] * x[2] + A[2 * 4 + 3] * x[3]; v[3] = A[3 * 4 + 0] * x[0] + A[3 * 4 + 1] * x[1] + A[3 * 4 + 2] * x[2] + A[3 * 4 + 3] * x[3]; } #ifdef DFM2_STATIC_LIBRARY template void delfem2::MatVec4( float v[4], const float A[16], const float x[4]); template void delfem2::MatVec4( double v[4], const double A[16], const double x[4]); #endif template<typename T> DFM2_INLINE void delfem2::VecMat4( T v[4], const T x[4], const T A[16]) { v[0] = A[0 * 4 + 0] * x[0] + A[1 * 4 + 0] * x[1] + A[2 * 4 + 0] * x[2] + A[3 * 4 + 0] * x[3]; v[1] = A[0 * 4 + 1] * x[0] + A[1 * 4 + 1] * x[1] + A[2 * 4 + 1] * x[2] + A[3 * 4 + 1] * x[3]; v[2] = A[0 * 4 + 2] * x[0] + A[1 * 4 + 2] * x[1] + A[2 * 4 + 2] * x[2] + A[3 * 4 + 2] * x[3]; v[3] = A[0 * 4 + 3] * x[0] + A[1 * 4 + 3] * x[1] + A[2 * 4 + 3] * x[2] + A[3 * 4 + 3] * x[3]; } #ifdef DFM2_STATIC_LIBRARY template void delfem2::VecMat4( float v[4], const float x[4], const float A[16]); template void delfem2::VecMat4( double v[4], const double x[4], const double A[16]); #endif // --------------------------- template<typename T0, typename T1, typename T2> DFM2_INLINE void delfem2::Vec3_Mat4Vec3_Homography( T0 y0[3], const T1 a[16], const T2 x0[3]) { const T1 x1[4] = { (T1) x0[0], (T1) x0[1], (T1) x0[2], 1}; T1 y1[4]; MatVec4(y1, a, x1); y0[0] = y1[0] / y1[3]; y0[1] = y1[1] / y1[3]; y0[2] = y1[2] / y1[3]; } #ifdef DFM2_STATIC_LIBRARY template void delfem2::Vec3_Mat4Vec3_Homography( float y0[3], const float a[16], const float x0[3]); template void delfem2::Vec3_Mat4Vec3_Homography( double y0[3], const double a[16], const double x0[3]); #endif // --------------------------- template<typename T> DFM2_INLINE std::array<T, 2> delfem2::Vec2_Mat4Vec3_Homography( const T a[16], const T x0[3]) { const T x1[4] = {x0[0], x0[1], x0[2], 1}; T y1[4]; MatVec4(y1, a, x1); return {y1[0] / y1[3], y1[1] / y1[3]}; } #ifdef DFM2_STATIC_LIBRARY template std::array<float, 2> delfem2::Vec2_Mat4Vec3_Homography( const float a[16], const float x0[3]); template std::array<double, 2> delfem2::Vec2_Mat4Vec3_Homography( const double a[16], const double x0[3]); #endif // ---------------------------- template<typename T0, typename T1, typename T2> DFM2_INLINE void delfem2::Vec3_Vec3Mat4_Homography( T0 y0[3], const T1 x0[3], const T2 a[16]) { const T2 x1[4] = {(T2) x0[0], (T2) x0[1], (T2) x0[2], 1}; T2 y1[4]; VecMat4(y1, x1, a); y0[0] = y1[0] / y1[3]; y0[1] = y1[1] / y1[3]; y0[2] = y1[2] / y1[3]; } #ifdef DFM2_STATIC_LIBRARY template void delfem2::Vec3_Vec3Mat4_Homography( float y0[3], const float x0[3], const float a[16]); template void delfem2::Vec3_Vec3Mat4_Homography( double y0[3], const double x0[3], const double a[16]); #endif // ---------------------- template<typename T> DFM2_INLINE void delfem2::Vec3_Mat4Vec3_Affine( T y0[3], const T a[16], const T x0[3]) { const T x1[4] = {x0[0], x0[1], x0[2], 1.0}; T y1[4]; MatVec4(y1, a, x1); y0[0] = y1[0]; y0[1] = y1[1]; y0[2] = y1[2]; } #ifdef DFM2_STATIC_LIBRARY template void delfem2::Vec3_Mat4Vec3_Affine( float y0[3], const float a[16], const float x0[3]); template void delfem2::Vec3_Mat4Vec3_Affine( double y0[3], const double a[16], const double x0[3]); #endif // ---------------------- template<typename T> DFM2_INLINE void delfem2::Mat4_AffineScale (T A[16], T s) { for (int i = 0; i < 16; ++i) { A[i] = 0.0; } A[0 * 4 + 0] = s; A[1 * 4 + 1] = s; A[2 * 4 + 2] = s; A[3 * 4 + 3] = 1.0; } #ifdef DFM2_STATIC_LIBRARY template void delfem2::Mat4_AffineScale(float A[16], float s); template void delfem2::Mat4_AffineScale(double A[16], double s); #endif // ------------------------ template<typename T> DFM2_INLINE void delfem2::Mat4_AffineTranslation (T A[16], T dx, T dy, T dz) { for (auto i = 0; i < 16; ++i) { A[i] = 0.0; } for (int i = 0; i < 4; ++i) { A[i * 4 + i] = 1.0; } A[0 * 4 + 3] = dx; A[1 * 4 + 3] = dy; A[2 * 4 + 3] = dz; } #ifdef DFM2_STATIC_LIBRARY template void delfem2::Mat4_AffineTranslation( float A[16], float dx, float dy, float dz); template void delfem2::Mat4_AffineTranslation( double A[16], double dx, double dy, double dz); #endif template<typename T> DFM2_INLINE void delfem2::Mat4_AffineTranslation( T A[16], const T v[3]) { A[0 * 4 + 0] = 1; A[0 * 4 + 1] = 0; A[0 * 4 + 2] = 0; A[0 * 4 + 3] = v[0]; A[1 * 4 + 0] = 0; A[1 * 4 + 1] = 1; A[1 * 4 + 2] = 0; A[1 * 4 + 3] = v[1]; A[2 * 4 + 0] = 0; A[2 * 4 + 1] = 0; A[2 * 4 + 2] = 1; A[2 * 4 + 3] = v[2]; A[3 * 4 + 0] = 0; A[3 * 4 + 1] = 0; A[3 * 4 + 2] = 0; A[3 * 4 + 3] = 1; } #ifdef DFM2_STATIC_LIBRARY template void delfem2::Mat4_AffineTranslation( float A[16], const float v[3]); template void delfem2::Mat4_AffineTranslation( double A[16], const double v[3]); #endif // -------------------------- template<typename T> DFM2_INLINE void delfem2::Mat4_AffineRotationRodriguez( T A[16], T dx, T dy, T dz) { constexpr T half = static_cast<T>(0.5); constexpr T one4th = static_cast<T>(0.25); for (int i = 0; i < 16; ++i) { A[i] = 0; } // const T sqlen = dx * dx + dy * dy + dz * dz; const T tmp1 = 1 / (1 + one4th * sqlen); A[0 * 4 + 0] = 1 + tmp1 * (+half * dx * dx - half * sqlen); A[0 * 4 + 1] = +tmp1 * (-dz + half * dx * dy); A[0 * 4 + 2] = +tmp1 * (+dy + half * dx * dz); A[0 * 4 + 3] = 0; // A[1 * 4 + 0] = +tmp1 * (+dz + half * dy * dx); A[1 * 4 + 1] = 1 + tmp1 * (+half * dy * dy - half * sqlen); A[1 * 4 + 2] = +tmp1 * (-dx + half * dy * dz); A[1 * 4 + 3] = 0; // A[2 * 4 + 0] = +tmp1 * (-dy + half * dz * dx); A[2 * 4 + 1] = +tmp1 * (+dx + half * dz * dy); A[2 * 4 + 2] = 1 + tmp1 * (+half * dz * dz - half * sqlen); A[2 * 4 + 3] = 0; // A[3 * 4 + 0] = 0; A[3 * 4 + 1] = 0; A[3 * 4 + 2] = 0; A[3 * 4 + 3] = 1; } #ifdef DFM2_STATIC_LIBRARY template void delfem2::Mat4_AffineRotationRodriguez( float A[16], float dx, float dy, float dz); template void delfem2::Mat4_AffineRotationRodriguez( double A[16], double dx, double dy, double dz); #endif // ------------------------------------------------ template<typename REAL> void delfem2::Mat4_Identity( REAL A[16]) { for (int i = 0; i < 16; ++i) { A[i] = 0; } A[0 * 4 + 0] = 1; A[1 * 4 + 1] = 1; A[2 * 4 + 2] = 1; A[3 * 4 + 3] = 1; } #ifdef DFM2_STATIC_LIBRARY template void delfem2::Mat4_Identity(float A[16]); template void delfem2::Mat4_Identity(double A[16]); #endif // ------------------------------------------------ /* template<typename REAL> void delfem2::Mat4_Transpose( REAL A[16], REAL B[16]) { for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { A[i * 4 + j] = B[j * 4 + i]; } } } #ifdef DFM2_STATIC_LIBRARY template void delfem2::Mat4_Transpose(float A[16], float B[16]); template void delfem2::Mat4_Transpose(double A[16], double B[16]); #endif */ // ------------------------------------------------ template<typename REAL> void delfem2::Rotate_Mat4AffineRodriguez( REAL A[16], const REAL V[3]) { REAL B[16]; Mat4_AffineRotationRodriguez(B, V[0], V[1], V[2]); REAL C[16]; MatMat4(C, B, A); for (int i = 0; i < 16; ++i) { A[i] = C[i]; } } #ifdef DFM2_STATIC_LIBRARY template void delfem2::Rotate_Mat4AffineRodriguez( float A[16], const float V[3]); template void delfem2::Rotate_Mat4AffineRodriguez( double A[16], const double V[3]); #endif // ----------------------------------- template<typename REAL> void delfem2::Mat4_AffineRotationCartesian( REAL mat[16], const REAL vec[3]) { const REAL sqt = vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2]; if (sqt < 1.0e-20) { // infinitesmal rotation approximation // row0 mat[0 * 4 + 0] = 1; mat[0 * 4 + 1] = -vec[2]; mat[0 * 4 + 2] = +vec[1]; mat[0 * 4 + 3] = 0; // row1 mat[1 * 4 + 0] = +vec[2]; mat[1 * 4 + 1] = 1; mat[1 * 4 + 2] = -vec[0]; mat[1 * 4 + 3] = 0; // row2 mat[2 * 4 + 0] = -vec[1]; mat[2 * 4 + 1] = +vec[0]; mat[2 * 4 + 2] = 1; mat[2 * 4 + 3] = 0; // row3 mat[3 * 4 + 0] = 0; mat[3 * 4 + 1] = 0; mat[3 * 4 + 2] = 0; mat[3 * 4 + 3] = 1; return; } REAL t = std::sqrt(sqt); REAL invt = 1 / t; REAL n[3] = {vec[0] * invt, vec[1] * invt, vec[2] * invt}; const REAL c0 = std::cos(t); const REAL s0 = std::sin(t); // row0 mat[0 * 4 + 0] = c0 + (1 - c0) * n[0] * n[0]; mat[0 * 4 + 1] = -n[2] * s0 + (1 - c0) * n[0] * n[1]; mat[0 * 4 + 2] = +n[1] * s0 + (1 - c0) * n[0] * n[2]; mat[0 * 4 + 3] = 0; // row1 mat[1 * 4 + 0] = +n[2] * s0 + (1 - c0) * n[1] * n[0]; mat[1 * 4 + 1] = c0 + (1 - c0) * n[1] * n[1]; mat[1 * 4 + 2] = -n[0] * s0 + (1 - c0) * n[1] * n[2]; mat[1 * 4 + 3] = 0; // row2 mat[2 * 4 + 0] = -n[1] * s0 + (1 - c0) * n[2] * n[0]; mat[2 * 4 + 1] = +n[0] * s0 + (1 - c0) * n[2] * n[1]; mat[2 * 4 + 2] = c0 + (1 - c0) * n[2] * n[2]; mat[2 * 4 + 3] = 0; // row3 mat[3 * 4 + 0] = 0; mat[3 * 4 + 1] = 0; mat[3 * 4 + 2] = 0; mat[3 * 4 + 3] = 1; } #ifdef DFM2_STATIC_LIBRARY template void delfem2::Mat4_AffineRotationCartesian(float mat[16], const float vec[3]); template void delfem2::Mat4_AffineRotationCartesian(double mat[16], const double vec[3]); #endif // ---------------------------- template<typename REAL> void delfem2::Translate_Mat4Affine( REAL A[16], const REAL V[3]) { A[0 * 4 + 3] += V[0]; A[1 * 4 + 3] += V[1]; A[2 * 4 + 3] += V[2]; } #ifdef DFM2_STATIC_LIBRARY template void delfem2::Translate_Mat4Affine(float A[16], const float V[3]); template void delfem2::Translate_Mat4Affine(double A[16], const double V[3]); #endif // ------------------- DFM2_INLINE void delfem2::Mat4_ScaleRotTrans( double m[16], double scale, const double quat[4], const double trans[3]) { delfem2::Mat4_AffineQuaternion(m, quat); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { m[i * 4 + j] *= scale; } } m[0 * 4 + 3] = trans[0]; m[1 * 4 + 3] = trans[1]; m[2 * 4 + 3] = trans[2]; } // ---------------------------- template<typename REAL> DFM2_INLINE void delfem2::Mat4_AffineQuaternion( REAL r[], const REAL q[]) { const REAL x2 = q[0] * q[0] * 2; const REAL y2 = q[1] * q[1] * 2; const REAL z2 = q[2] * q[2] * 2; const REAL xy = q[0] * q[1] * 2; const REAL yz = q[1] * q[2] * 2; const REAL zx = q[2] * q[0] * 2; const REAL xw = q[0] * q[3] * 2; const REAL yw = q[1] * q[3] * 2; const REAL zw = q[2] * q[3] * 2; r[0] = 1 - y2 - z2; r[1] = xy - zw; r[2] = zx + yw; r[3] = 0; r[4] = xy + zw; r[5] = 1 - z2 - x2; r[6] = yz - xw; r[7] = 0; r[8] = zx - yw; r[9] = yz + xw; r[10] = 1 - x2 - y2; r[11] = 0; r[12] = 0; r[13] = 0; r[14] = 0; r[15] = 1; } #ifdef DFM2_STATIC_LIBRARY template void delfem2::Mat4_AffineQuaternion( float r[], const float q[]); template void delfem2::Mat4_AffineQuaternion( double r[], const double q[]); #endif // -------------------------------- // return transpose matrix of Mat4_AffineQuaternion template<typename REAL> DFM2_INLINE void delfem2::Mat4_AffineQuaternionConjugate( REAL *r, const REAL *q) { const REAL x2 = q[0] * q[0] * 2; const REAL y2 = q[1] * q[1] * 2; const REAL z2 = q[2] * q[2] * 2; const REAL xy = q[0] * q[1] * 2; const REAL yz = q[1] * q[2] * 2; const REAL zx = q[2] * q[0] * 2; const REAL xw = q[0] * q[3] * 2; const REAL yw = q[1] * q[3] * 2; const REAL zw = q[2] * q[3] * 2; r[0] = 1 - y2 - z2; r[1] = xy + zw; r[2] = zx - yw; r[3] = 0; r[4] = xy - zw; r[5] = 1 - z2 - x2; r[6] = yz + xw; r[7] = 0; r[8] = zx + yw; r[9] = yz - xw; r[10] = 1 - x2 - y2; r[11] = 0; r[12] = 0; r[13] = 0; r[14] = 0; r[15] = 1; } #ifdef DFM2_STATIC_LIBRARY template DFM2_INLINE void delfem2::Mat4_AffineQuaternionConjugate(float *r, const float *q); template DFM2_INLINE void delfem2::Mat4_AffineQuaternionConjugate(double *r, const double *q); #endif // -------------------------------------- template<typename REAL> DFM2_INLINE void delfem2::Inverse_Mat4( REAL minv[16], const REAL m[16]) { for (int i = 0; i < 16; ++i) { minv[i] = m[i]; } int info; mat4::CalcInvMat(minv, 4, info); if (info != 0) { for (int i = 0; i < 16; ++i) { minv[i] = m[i]; } unsigned int tmp[4]; mat4::CalcInvMatPivot(minv, 4, tmp); } } #ifdef DFM2_STATIC_LIBRARY template void delfem2::Inverse_Mat4(float minv[], const float m[]); template void delfem2::Inverse_Mat4(double minv[], const double m[]); #endif // ------------------------------------------------------------------ template<typename REAL> delfem2::CMat4<REAL> delfem2::CMat4<REAL>::Quat(const REAL *q) { const REAL x2 = q[0] * q[0] * 2; const REAL y2 = q[1] * q[1] * 2; const REAL z2 = q[2] * q[2] * 2; const REAL xy = q[0] * q[1] * 2; const REAL yz = q[1] * q[2] * 2; const REAL zx = q[2] * q[0] * 2; const REAL xw = q[0] * q[3] * 2; const REAL yw = q[1] * q[3] * 2; const REAL zw = q[2] * q[3] * 2; return CMat4<REAL>{ 1 - y2 - z2, xy - zw, zx + yw, 0, xy + zw, 1 - z2 - x2, yz - xw, 0, zx - yw, yz + xw, 1 - x2 - y2, 0, 0, 0, 0, 1}; } #ifdef DFM2_STATIC_LIBRARY template delfem2::CMat4<float> delfem2::CMat4<float>::Quat(const float *q); template delfem2::CMat4<double> delfem2::CMat4<double>::Quat(const double *q); #endif // --------------------------- namespace delfem2 { template<typename T> CMat4<T> operator*(const CMat4<T> &lhs, const CMat4<T> &rhs) { CMat4<T> q; MatMat4(q.mat, lhs.mat, rhs.mat); return q; } #ifdef DFM2_STATIC_LIBRARY template CMat4d operator*(const CMat4d &lhs, const CMat4d &rhs); template CMat4f operator*(const CMat4f &lhs, const CMat4f &rhs); #endif template<typename T> CMat4<T> operator-(const CMat4<T> &lhs, const CMat4<T> &rhs) { CMat4<T> q; for (int i = 0; i < 16; ++i) { q.mat[i] = lhs.mat[i] - rhs.mat[i]; } return q; } #ifdef DFM2_STATIC_LIBRARY template CMat4d operator-(const CMat4d &lhs, const CMat4d &rhs); template CMat4f operator-(const CMat4f &lhs, const CMat4f &rhs); #endif template<typename T> CMat4<T> operator+(const CMat4<T> &lhs, const CMat4<T> &rhs) { CMat4<T> q; for (int i = 0; i < 16; ++i) { q.mat[i] = lhs.mat[i] + rhs.mat[i]; } return q; } #ifdef DFM2_STATIC_LIBRARY template CMat4d operator+(const CMat4d &lhs, const CMat4d &rhs); template CMat4f operator+(const CMat4f &lhs, const CMat4f &rhs); #endif } // -------------------------------------------- template<typename REAL> delfem2::CMat4<REAL> delfem2::CMat4<REAL>::Inverse() const { CMat4<REAL> m; std::memcpy(m.mat, mat, sizeof(REAL) * 16); Inverse_Mat4(m.mat, this->mat); return m; } #ifdef DFM2_STATIC_LIBRARY template delfem2::CMat4d delfem2::CMat4d::Inverse() const; template delfem2::CMat4f delfem2::CMat4f::Inverse() const; #endif
26.939464
95
0.527073
nobuyuki83
7c3a81683459fac9a0ba9307804e0775f8ae07fb
1,776
hpp
C++
include/engine/game/scripttrigger.hpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
include/engine/game/scripttrigger.hpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
include/engine/game/scripttrigger.hpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
/* Copyright 2009-2021 Nicolas Colombe 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. */ #pragma once #include <engine/physics/trigger.hpp> namespace eXl { class LuaScriptSystem; struct ScriptTrigger : TriggerCallback { ScriptTrigger(World& iWorld); void OnEnter(const Vector<ObjectPair>& iNewPairs); void OnLeave(const Vector<ObjectPair>& iNewPairs); World& m_World; LuaScriptSystem& m_Scripts; private: Name m_BehaviourName; Name m_EnterName; Name m_LeaveName; }; class ScriptTriggerSystem : public WorldSystem { DECLARE_RTTI(ScriptTriggerSystem, WorldSystem); public: void Register(World& iWorld); TriggerCallbackHandle GetScriptCallbackhandle() const { return m_Handle; } protected: TriggerCallbackHandle m_Handle; }; }
40.363636
460
0.773649
eXl-Nic
7c3c7ff8f6955166bdbd693e0effd6edc45ca4ac
1,463
cpp
C++
tests/streaming/src_model/Model.cpp
TonyBrewer/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
13
2015-02-26T22:46:18.000Z
2020-03-24T11:53:06.000Z
tests/streaming/src_model/Model.cpp
PacificBiosciences/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
5
2016-02-25T17:08:19.000Z
2018-01-20T15:24:36.000Z
tests/streaming/src_model/Model.cpp
TonyBrewer/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
12
2015-04-13T21:39:54.000Z
2021-01-15T01:00:13.000Z
#include "Ht.h" void HtCoprocModel() { uint32_t haltCnt = 0; uint16_t nau = 0; uint16_t au = 0; CHtModelHif *pModel = new CHtModelHif; CHtModelAuUnit *const *pAuUnits = pModel->AllocAllAuUnits(); nau = pModel->GetAuUnitCnt(); uint16_t rcvAu; uint32_t rcvCnt; // Loop until all AUs are done echoing data while (haltCnt < nau) { for (au = 0; au < nau; au++) { uint32_t wordCnt = 0; uint64_t recvData = 0; int32_t errs = 0; if(pAuUnits[au]->RecvCall_htmain(rcvAu, rcvCnt)) { printf("Model: AU %2d - Processing\n", rcvAu); while (wordCnt < rcvCnt) { // Rerun loop if no data to read if (!pAuUnits[au]->RecvHostData(1, &recvData)) { continue; } // At this point, there is valid data in recvData // Generate an expected response and compare uint64_t expectedData = 0; expectedData |= ((rcvAu & 0xFFFFLL)<<48); expectedData |= ((wordCnt + 1) & 0xFFFFFFFFFFFFLL); if (expectedData != recvData) { printf("Model: WARNING - Expected Data did not match Received data!\n"); printf(" 0x%016llx != 0x%016llx\n", (unsigned long long)expectedData, (unsigned long long)recvData); errs++; } // Send it back! while (!pAuUnits[au]->SendHostData(1, &expectedData)); wordCnt++; } while (!pAuUnits[au]->SendReturn_htmain(errs)); } haltCnt += pAuUnits[au]->RecvHostHalt(); } } pModel->FreeAllAuUnits(); delete pModel; }
21.514706
77
0.626111
TonyBrewer
7c3eba0795cd22609dde200195c4fd3e6b8b8741
5,485
cpp
C++
savedecrypter-master/savedecrypter/ClanLib-2.0/Sources/Core/System/thread_local_storage.cpp
ZephyrXD/Z-Builder-Source-CPP
f48e0f22b5d4d183b841abb8e61e1bdb5c25999d
[ "Apache-2.0" ]
6
2020-11-11T15:49:11.000Z
2021-03-08T10:29:23.000Z
savedecrypter-master/savedecrypter/ClanLib-2.0/Sources/Core/System/thread_local_storage.cpp
ZeppyXD/Z-Builder-Source-CPP
f48e0f22b5d4d183b841abb8e61e1bdb5c25999d
[ "Apache-2.0" ]
1
2020-11-08T17:28:35.000Z
2020-11-09T01:35:27.000Z
savedecrypter-master/savedecrypter/ClanLib-2.0/Sources/Core/System/thread_local_storage.cpp
ZeppyXD/Z-Builder-Source-CPP
f48e0f22b5d4d183b841abb8e61e1bdb5c25999d
[ "Apache-2.0" ]
3
2021-06-26T13:00:23.000Z
2022-02-01T02:16:50.000Z
/* ** ClanLib SDK ** Copyright (c) 1997-2010 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Harry Storbacka */ #include "Core/precomp.h" #include "API/Core/System/thread_local_storage.h" #include "thread_local_storage_impl.h" #include "../core_global.h" ///////////////////////////////////////////////////////////////////////////// // CL_ThreadLocalStorage Construction: void CL_ThreadLocalStorage::create_initial_instance() { if (!cl_core_global.cl_tls) { cl_core_global.cl_tls = new(CL_ThreadLocalStorage); } } CL_ThreadLocalStorage::CL_ThreadLocalStorage() { CL_System::alloc_thread_temp_pool(); #ifdef WIN32 if (cl_core_global.cl_tls_index == TLS_OUT_OF_INDEXES) { CL_MutexSection mutex_lock(&cl_core_global.cl_tls_mutex); cl_core_global.cl_tls_index = TlsAlloc(); } CL_ThreadLocalStorage_Impl *tls_impl = (CL_ThreadLocalStorage_Impl *) TlsGetValue(cl_core_global.cl_tls_index); if (!tls_impl) { tls_impl = new CL_ThreadLocalStorage_Impl; TlsSetValue(cl_core_global.cl_tls_index, tls_impl); } else { tls_impl->add_reference(); } #elif !defined(HAVE_TLS) if (!cl_core_global.cl_tls_index_created) { CL_MutexSection mutex_lock(&cl_core_global.cl_tls_mutex); pthread_key_create(&cl_core_global.cl_tls_index, 0); cl_core_global.cl_tls_index_created = true; } CL_ThreadLocalStorage_Impl *tls_impl = (CL_ThreadLocalStorage_Impl *) pthread_getspecific(cl_core_global.cl_tls_index); if (!tls_impl) { tls_impl = new CL_ThreadLocalStorage_Impl; pthread_setspecific(cl_core_global.cl_tls_index, tls_impl); } else { tls_impl->add_reference(); } #else if (!cl_core_global.cl_tls_impl) { cl_core_global.cl_tls_impl = new CL_ThreadLocalStorage_Impl; } else { cl_core_global.cl_tls_impl->add_reference(); } #endif } CL_ThreadLocalStorage::~CL_ThreadLocalStorage() { #ifdef WIN32 if (cl_core_global.cl_tls_index == TLS_OUT_OF_INDEXES) return; CL_ThreadLocalStorage_Impl *tls_impl = (CL_ThreadLocalStorage_Impl *) TlsGetValue(cl_core_global.cl_tls_index); if (tls_impl) tls_impl->release_reference(); #elif !defined(HAVE_TLS) if (!cl_core_global.cl_tls_index_created) return; CL_ThreadLocalStorage_Impl *tls_impl = (CL_ThreadLocalStorage_Impl *) pthread_getspecific(cl_core_global.cl_tls_index); if (tls_impl) tls_impl->release_reference(); #else if (cl_core_global.cl_tls_impl) cl_core_global.cl_tls_impl->release_reference(); #endif CL_System::free_thread_temp_pool(); } ///////////////////////////////////////////////////////////////////////////// // CL_ThreadLocalStorage Attributes: CL_UnknownSharedPtr CL_ThreadLocalStorage::get_variable(const CL_StringRef &name) { #ifdef WIN32 if (cl_core_global.cl_tls_index == TLS_OUT_OF_INDEXES) throw CL_Exception("No CL_ThreadLocalStorage object created for this thread."); CL_ThreadLocalStorage_Impl *tls_impl = (CL_ThreadLocalStorage_Impl *) TlsGetValue(cl_core_global.cl_tls_index); #elif !defined(HAVE_TLS) if (!cl_core_global.cl_tls_index_created) throw CL_Exception("No CL_ThreadLocalStorage object created for this thread."); CL_ThreadLocalStorage_Impl *tls_impl = (CL_ThreadLocalStorage_Impl *) pthread_getspecific(cl_core_global.cl_tls_index); #else CL_ThreadLocalStorage_Impl *tls_impl = cl_core_global.cl_tls_impl; #endif if (tls_impl == 0) throw CL_Exception("No CL_ThreadLocalStorage object created for this thread."); return tls_impl->get_variable(name); } ///////////////////////////////////////////////////////////////////////////// // CL_ThreadLocalStorage Operations: void CL_ThreadLocalStorage::set_variable(const CL_StringRef &name, CL_UnknownSharedPtr ptr) { #ifdef WIN32 if (cl_core_global.cl_tls_index == TLS_OUT_OF_INDEXES) throw CL_Exception("No CL_ThreadLocalStorage object created for this thread."); CL_ThreadLocalStorage_Impl *tls_impl = (CL_ThreadLocalStorage_Impl *) TlsGetValue(cl_core_global.cl_tls_index); #elif !defined(HAVE_TLS) if (!cl_core_global.cl_tls_index_created) throw CL_Exception("No CL_ThreadLocalStorage object created for this thread."); CL_ThreadLocalStorage_Impl *tls_impl = (CL_ThreadLocalStorage_Impl *) pthread_getspecific(cl_core_global.cl_tls_index); #else CL_ThreadLocalStorage_Impl *tls_impl = cl_core_global.cl_tls_impl; #endif if (tls_impl == 0) throw CL_Exception("No CL_ThreadLocalStorage object created for this thread."); tls_impl->set_variable(name,ptr); } ///////////////////////////////////////////////////////////////////////////// // CL_ThreadLocalStorage Implementation:
32.844311
120
0.742024
ZephyrXD
7c4322ea9124bd0cf70e1bcd2068fe34e3292236
1,091
cc
C++
third_party/sqlite/fuzz/sql_strftime_fuzzer.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
third_party/sqlite/fuzz/sql_strftime_fuzzer.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
third_party/sqlite/fuzz/sql_strftime_fuzzer.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <cstdlib> #include <iostream> #include <string> #include <vector> #include "testing/libfuzzer/proto/lpm_interface.h" #include "third_party/sqlite/fuzz/sql_query_grammar.pb.h" #include "third_party/sqlite/fuzz/sql_query_proto_to_string.h" #include "third_party/sqlite/fuzz/sql_run_queries.h" using namespace sql_query_grammar; DEFINE_BINARY_PROTO_FUZZER(const StrftimeFn& sql_strftime) { std::string strftime_str = sql_fuzzer::StrftimeFnToString(sql_strftime); // Convert printf command into runnable SQL query. strftime_str = "SELECT " + strftime_str + ";"; if (getenv("LPM_DUMP_NATIVE_INPUT")) { std::cout << "_________________________" << std::endl; std::cout << strftime_str << std::endl; std::cout << "------------------------" << std::endl; } std::vector<std::string> queries; queries.push_back(strftime_str); sql_fuzzer::RunSqlQueries(queries, ::getenv("LPM_SQLITE_TRACE")); }
34.09375
74
0.729606
zealoussnow
7c47701300dfe2487a85d90fc459ba063cae22a6
654
cpp
C++
windows-lockscreen-extractor/src/helpers/User.cpp
chistyakoviv/windows-lockscreen-extractor
189c396fe15fd3facdb2ebe4d8cab2317af0098f
[ "MIT" ]
null
null
null
windows-lockscreen-extractor/src/helpers/User.cpp
chistyakoviv/windows-lockscreen-extractor
189c396fe15fd3facdb2ebe4d8cab2317af0098f
[ "MIT" ]
null
null
null
windows-lockscreen-extractor/src/helpers/User.cpp
chistyakoviv/windows-lockscreen-extractor
189c396fe15fd3facdb2ebe4d8cab2317af0098f
[ "MIT" ]
null
null
null
#include "User.h" #include <clocale> #include <locale> #include <codecvt> static const wchar_t* LOCK_SCREEN_IMAGES_PATH = L"\\AppData\\Local\\Packages\\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\\LocalState\\Assets"; static std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> s_Converter; std::wstring User::GetProfileDir() { return s_Converter.from_bytes(getenv("USERPROFILE")); } std::wstring User::GetLockScreenImagesDir() { return User::GetProfileDir() + LOCK_SCREEN_IMAGES_PATH; } std::wstring User::GetLockScreenImageAbsolutePath(const std::wstring& imageName) { return User::GetLockScreenImagesDir() + L"\\" + imageName; }
26.16
154
0.778287
chistyakoviv
7c4aed921ec64f75f6cd7158352edf044939f391
2,781
cpp
C++
Demo/GameCode/IntroScene.cpp
TimPhoeniX/LuaDemo
99930f376f08f080e43737eb28606ab3f5d24eb9
[ "MIT" ]
2
2019-09-26T09:12:54.000Z
2019-10-03T10:43:59.000Z
Demo/GameCode/IntroScene.cpp
TimPhoeniX/LuaDemo
99930f376f08f080e43737eb28606ab3f5d24eb9
[ "MIT" ]
null
null
null
Demo/GameCode/IntroScene.cpp
TimPhoeniX/LuaDemo
99930f376f08f080e43737eb28606ab3f5d24eb9
[ "MIT" ]
null
null
null
#include "IntroScene.hpp" #include <Object/Shape/sge_shape.hpp> #include <Game/sge_game.hpp> #include <Game/Director/sge_director.hpp> #include "Image.hpp" #include "Logics.hpp" #include "Actions.hpp" #include "Renderer/sge_renderer.hpp" IntroScene::IntroScene(SGE::Scene* next, const char* path): path(path), next(next) {} void IntroScene::loadScene() { auto o = new Image(0, 0, SGE::Shape::Rectangle(1024.f / 64.f, 768.f / 64.f, true)); auto g = SGE::Game::getGame(); auto game = SGE::Game::getGame(); SGE::BatchRenderer* renderer = game->getRenderer(); auto program = renderer->getProgramID("BatchShader.vert","BatchShader.frag"); size_t batch = renderer->newBatch(program, path, 1, false, true); renderer->getBatch(batch)->addObject(o); o->setVisible(true); o->setDrawable(true); this->addObject(o); this->addLogic(new Timer(2, new Load(next))); g->getCamera()->setPositionGLM(0, 0); g->getCamera()->setCameraScale(1.f); } IntroScene::~IntroScene() {} void IntroScene::finalize() {} void IntroScene::onDraw() { auto g = SGE::Game::getGame(); g->getCamera()->setPositionGLM(0, 0); g->getCamera()->setCameraScale(1.f); SGE::Director::getDirector()->unloadScene(next); } EndScene::EndScene(Scene* next, const char* path, const char* path2): IntroScene(next, path), path2(path2), won(nullptr) { } void EndScene::onDraw() { auto g = SGE::Game::getGame(); g->getCamera()->setPositionGLM(0, 0); g->getCamera()->setCameraScale(1.f); if(this->won) { this->getObjects()[0]->setVisible(true); this->getObjects()[1]->setVisible(false); } else { this->getObjects()[0]->setVisible(false); this->getObjects()[1]->setVisible(true); } SGE::Director::getDirector()->unloadScene(next); } void EndScene::loadScene() { auto i1 = new Image(0, 0, SGE::Shape::Rectangle(1024.f / 64.f, 768.f / 64.f, true)); auto i2 = new Image(0, 0, SGE::Shape::Rectangle(1024.f / 64.f, 768.f / 64.f, true)); auto game = SGE::Game::getGame(); SGE::BatchRenderer* renderer = game->getRenderer(); if(this->winBatch == 0) { auto program = renderer->getProgramID("BatchShader.vert", "BatchShader.frag"); this->winBatch = renderer->newBatch(program, path, 1, false, true); } if(this->loseBatch == 0) { auto program = renderer->getProgramID("BatchShader.vert", "BatchShader.frag"); this->loseBatch = renderer->newBatch(program, path2, 1, false, true); } renderer->getBatch(this->winBatch)->addObject(i1); i1->setVisible(true); i1->setDrawable(true); renderer->getBatch(this->loseBatch)->addObject(i2); i2->setVisible(true); i2->setDrawable(true); auto g = SGE::Game::getGame(); this->addObject(i1); this->addObject(i2); this->addLogic(new OnKey(SGE::Key::Return, next)); g->getCamera()->setPositionGLM(0, 0); g->getCamera()->setCameraScale(1.f); }
28.670103
120
0.685365
TimPhoeniX
7c510ec662d1a3d9eb901118b6cf9ce02e546aba
1,403
cpp
C++
src/windows/filesystem_win32.cpp
puremourning/netcoredbg
c34eaef68abe06197d03bc8c19282707cfc1adda
[ "MIT" ]
null
null
null
src/windows/filesystem_win32.cpp
puremourning/netcoredbg
c34eaef68abe06197d03bc8c19282707cfc1adda
[ "MIT" ]
null
null
null
src/windows/filesystem_win32.cpp
puremourning/netcoredbg
c34eaef68abe06197d03bc8c19282707cfc1adda
[ "MIT" ]
null
null
null
// Copyright (C) 2020 Samsung Electronics Co., Ltd. // See the LICENSE file in the project root for more information. /// \file filesystem_win32.cpp /// This file contains definitions of windows-specific functions related to file system. #ifdef WIN32 #include <windows.h> #include <string> #include "filesystem.h" namespace netcoredbg { const char* FileSystemTraits<Win32PlatformTag>::PathSeparatorSymbols = "/\\"; // Function returns absolute path to currently running executable. std::string GetExeAbsPath() { const size_t MAX_LONGPATH = 1024; char hostPath[MAX_LONGPATH + 1]; static const std::string result(hostPath, ::GetModuleFileNameA(NULL, hostPath, MAX_LONGPATH)); return result; } // Function returns path to directory, which should be used for creation of // temporary files. Typically this is `/tmp` on Unix and something like // `C:\Users\localuser\Appdata\Local\Temp` on Windows. string_view GetTempDir() { CHAR path[MAX_PATH + 1]; static const std::string result(path, GetTempPathA(MAX_PATH, path)); return result; } // Function changes current working directory. Return value is `false` in case of error. bool SetWorkDir(string_view path) { char str[MAX_PATH]; if (path.size() >= sizeof(str)) return false; path.copy(str, path.size()); str[path.size()] = 0; return SetCurrentDirectoryA(str); } } // ::netcoredbg #endif
26.980769
98
0.721311
puremourning
7c540cd285c2a41253b995ad72bc218634d63192
604
cpp
C++
34. Find First and Last Position of Element in Sorted Array.cpp
kushagra-18/Leetcode-solutions
cf276e6cc5491429144a79c59dd1097f1d625a6b
[ "MIT" ]
null
null
null
34. Find First and Last Position of Element in Sorted Array.cpp
kushagra-18/Leetcode-solutions
cf276e6cc5491429144a79c59dd1097f1d625a6b
[ "MIT" ]
null
null
null
34. Find First and Last Position of Element in Sorted Array.cpp
kushagra-18/Leetcode-solutions
cf276e6cc5491429144a79c59dd1097f1d625a6b
[ "MIT" ]
null
null
null
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int n = nums.size(),i,count = 0,flag; for(i = 0;i<n;i++){ if(nums[i]==target){ count++; flag = i; } } if(count==0){ vector <int> arr = {-1,-1}; return arr; }else{ vector <int> arr = {(flag-count) +1 ,flag}; return arr; } } };
19.483871
60
0.306291
kushagra-18
7c58e5f186694bb171931cf1d8266e2c31118507
3,303
cpp
C++
tests/test_transpose/test_transpose.cpp
mablanchard/Fastor
f5ca2f608bdfee34833d5008a93a3f82ce42ddef
[ "MIT" ]
424
2017-05-15T14:34:30.000Z
2022-03-29T08:58:22.000Z
tests/test_transpose/test_transpose.cpp
manodeep/Fastor
aefce47955dd118f04e7b36bf5dbb2d86997ff8f
[ "MIT" ]
150
2016-12-23T10:08:12.000Z
2022-01-16T03:53:45.000Z
tests/test_transpose/test_transpose.cpp
manodeep/Fastor
aefce47955dd118f04e7b36bf5dbb2d86997ff8f
[ "MIT" ]
43
2017-09-20T19:47:24.000Z
2022-02-22T21:12:49.000Z
#include <Fastor/Fastor.h> using namespace Fastor; #define Tol 1e-12 #define BigTol 1e-5 #define HugeTol 1e-2 template<typename T, size_t M, size_t N> Tensor<T,N,M> transpose_ref(const Tensor<T,M,N>& a) { Tensor<T,N,M> out; for (size_t i=0; i<M; ++i) { for (size_t j=0; j<N; ++j) { out(j,i) = a(i,j); } } return out; } template<typename T, size_t M, size_t N> void TEST_TRANSPOSE(Tensor<T,M,N>& a) { Tensor<T,N,M> b1 = transpose_ref(a); Tensor<T,N,M> b2 = transpose(a); Tensor<T,N,M> b3 = trans(a); for (size_t i=0; i<N; ++i) { for (size_t j=0; j<M; ++j) { FASTOR_EXIT_ASSERT(std::abs(b1(i,j) - b2(i,j)) < Tol); FASTOR_EXIT_ASSERT(std::abs(b1(i,j) - b3(i,j)) < Tol); } } FASTOR_EXIT_ASSERT(std::abs(norm(transpose(a))-norm(a))< HugeTol); FASTOR_EXIT_ASSERT(std::abs(norm(trans(a))-norm(a))< HugeTol); } template<typename T> void test_transpose() { { Tensor<T,2,2> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,3,3> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,4,4> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,5,5> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,7,7> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,8,8> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,9,9> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,10,10> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,12,12> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,16,16> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,17,17> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,20,20> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,24,24> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,40,40> t1; t1.iota(5); TEST_TRANSPOSE(t1); } // non-square { Tensor<T,2,3> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,3,4> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,4,5> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,5,6> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,6,7> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,17,29> t1; t1.iota(5); TEST_TRANSPOSE(t1); } // transpose expressions { Tensor<T,2,3> t1; t1.iota(5); FASTOR_EXIT_ASSERT(std::abs(sum(transpose(t1 + 0)) - sum(t1)) < BigTol); FASTOR_EXIT_ASSERT(std::abs(sum(trans(t1 + 0)) - sum(t1)) < BigTol); FASTOR_EXIT_ASSERT(std::abs(sum(transpose(t1 + t1*2 - t1 - t1)) - sum(t1)) < BigTol); FASTOR_EXIT_ASSERT(std::abs(sum(trans(t1 + t1*2 - t1 - t1)) - sum(t1)) < BigTol); } print(FGRN(BOLD("All tests passed successfully"))); } int main() { print(FBLU(BOLD("Testing tensor transpose routine: single precision"))); test_transpose<float>(); print(FBLU(BOLD("Testing tensor transpose routine: double precision"))); test_transpose<double>(); return 0; }
22.02
93
0.518619
mablanchard
7c5b8418e332dc639e4c9bc7b60fde9c073c2ce7
204
cpp
C++
src/main.cpp
JoseLuisC99/GraphDB
63735389e0637746333b404583ae8e54ea309497
[ "MIT" ]
null
null
null
src/main.cpp
JoseLuisC99/GraphDB
63735389e0637746333b404583ae8e54ea309497
[ "MIT" ]
null
null
null
src/main.cpp
JoseLuisC99/GraphDB
63735389e0637746333b404583ae8e54ea309497
[ "MIT" ]
null
null
null
#include <iostream> #include "graph/Vertex.hpp" #include "graph/Edge.hpp" #include "graph/Graph.hpp" using namespace std; int main(int argc, char** argv) { cout << "GraphDB" << endl; return 0; }
18.545455
33
0.666667
JoseLuisC99
7c630c5a5847b69203f8ac94a8f6d844da57a24c
528
cpp
C++
chapter-15/Program 1.cpp
JahanzebNawaz/Introduction-to-C-plus-plus-CPP-Chapter-Exercises
dc3cd3a0091686580aa8414f3d021fe5bb7bb513
[ "MIT" ]
null
null
null
chapter-15/Program 1.cpp
JahanzebNawaz/Introduction-to-C-plus-plus-CPP-Chapter-Exercises
dc3cd3a0091686580aa8414f3d021fe5bb7bb513
[ "MIT" ]
null
null
null
chapter-15/Program 1.cpp
JahanzebNawaz/Introduction-to-C-plus-plus-CPP-Chapter-Exercises
dc3cd3a0091686580aa8414f3d021fe5bb7bb513
[ "MIT" ]
null
null
null
/* program of inheritance */ #include<iostream> #include<conio.h> using namespace std; class move { protected: int position; public: move() { position=0; } void forward() { position++; } void show() { cout<<" Position = "<<position<<endl; } }; class move2: public move { public: void backword() { position--; } }; main() { move2 m; m.show(); m.forward(); m.show(); m.backword(); m.show(); getch(); }
11.234043
43
0.486742
JahanzebNawaz
7c637803e72b33ad45f5566aabf2d06ddf7c949e
37,796
cc
C++
Code/BBearEditor/Engine/Serializer/BBMaterial.pb.cc
xiaoxianrouzhiyou/BBearEditor
0f1b779d87c297661f9a1e66d0613df43f5fe46b
[ "MIT" ]
26
2021-06-30T02:19:30.000Z
2021-07-23T08:38:46.000Z
Code/BBearEditor/Engine/Serializer/BBMaterial.pb.cc
xiaoxianrouzhiyou/BBearEditor-2.0
0f1b779d87c297661f9a1e66d0613df43f5fe46b
[ "MIT" ]
null
null
null
Code/BBearEditor/Engine/Serializer/BBMaterial.pb.cc
xiaoxianrouzhiyou/BBearEditor-2.0
0f1b779d87c297661f9a1e66d0613df43f5fe46b
[ "MIT" ]
3
2021-09-01T08:19:30.000Z
2021-12-28T19:06:40.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: BBMaterial.proto #include "BBMaterial.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> PROTOBUF_PRAGMA_INIT_SEG namespace BBSerializer { constexpr BBMaterial::BBMaterial( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : texturename_() , texturepath_() , floatname_() , floatvalue_() , vec4name_() , vec4value_() , shadername_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , vshaderpath_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , fshaderpath_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , cubemapname_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , cubemappaths_(nullptr) , srcblendfunc_(0) , blendstate_(false) , cullstate_(false) , dstblendfunc_(0) , cullface_(0){} struct BBMaterialDefaultTypeInternal { constexpr BBMaterialDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~BBMaterialDefaultTypeInternal() {} union { BBMaterial _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT BBMaterialDefaultTypeInternal _BBMaterial_default_instance_; } // namespace BBSerializer static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_BBMaterial_2eproto[1]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_BBMaterial_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_BBMaterial_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_BBMaterial_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, _has_bits_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, shadername_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, vshaderpath_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, fshaderpath_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, texturename_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, texturepath_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, floatname_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, floatvalue_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, vec4name_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, vec4value_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, blendstate_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, srcblendfunc_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, dstblendfunc_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, cullstate_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, cullface_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, cubemapname_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, cubemappaths_), 0, 1, 2, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, 6, 5, 8, 7, 9, 3, 4, }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, 21, sizeof(::BBSerializer::BBMaterial)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::BBSerializer::_BBMaterial_default_instance_), }; const char descriptor_table_protodef_BBMaterial_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\020BBMaterial.proto\022\014BBSerializer\032\016BBVect" "or.proto\032\017BBCubeMap.proto\"\321\004\n\nBBMaterial" "\022\027\n\nshaderName\030\001 \001(\tH\000\210\001\001\022\030\n\013vShaderPath" "\030\002 \001(\tH\001\210\001\001\022\030\n\013fShaderPath\030\003 \001(\tH\002\210\001\001\022\023\n" "\013textureName\030\004 \003(\t\022\023\n\013texturePath\030\005 \003(\t\022" "\021\n\tfloatName\030\006 \003(\t\022\022\n\nfloatValue\030\007 \003(\002\022\020" "\n\010vec4Name\030\010 \003(\t\022+\n\tvec4Value\030\t \003(\0132\030.BB" "Serializer.BBVector4f\022\027\n\nblendState\030\n \001(" "\010H\003\210\001\001\022\031\n\014SRCBlendFunc\030\013 \001(\005H\004\210\001\001\022\031\n\014DST" "BlendFunc\030\014 \001(\005H\005\210\001\001\022\026\n\tcullState\030\r \001(\010H" "\006\210\001\001\022\025\n\010cullFace\030\016 \001(\005H\007\210\001\001\022\030\n\013cubeMapNa" "me\030\017 \001(\tH\010\210\001\001\0222\n\014cubeMapPaths\030\020 \001(\0132\027.BB" "Serializer.BBCubeMapH\t\210\001\001B\r\n\013_shaderName" "B\016\n\014_vShaderPathB\016\n\014_fShaderPathB\r\n\013_ble" "ndStateB\017\n\r_SRCBlendFuncB\017\n\r_DSTBlendFun" "cB\014\n\n_cullStateB\013\n\t_cullFaceB\016\n\014_cubeMap" "NameB\017\n\r_cubeMapPathsb\006proto3" ; static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_BBMaterial_2eproto_deps[2] = { &::descriptor_table_BBCubeMap_2eproto, &::descriptor_table_BBVector_2eproto, }; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_BBMaterial_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_BBMaterial_2eproto = { false, false, 669, descriptor_table_protodef_BBMaterial_2eproto, "BBMaterial.proto", &descriptor_table_BBMaterial_2eproto_once, descriptor_table_BBMaterial_2eproto_deps, 2, 1, schemas, file_default_instances, TableStruct_BBMaterial_2eproto::offsets, file_level_metadata_BBMaterial_2eproto, file_level_enum_descriptors_BBMaterial_2eproto, file_level_service_descriptors_BBMaterial_2eproto, }; PROTOBUF_ATTRIBUTE_WEAK const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable* descriptor_table_BBMaterial_2eproto_getter() { return &descriptor_table_BBMaterial_2eproto; } // Force running AddDescriptors() at dynamic initialization time. PROTOBUF_ATTRIBUTE_INIT_PRIORITY static ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptorsRunner dynamic_init_dummy_BBMaterial_2eproto(&descriptor_table_BBMaterial_2eproto); namespace BBSerializer { // =================================================================== class BBMaterial::_Internal { public: using HasBits = decltype(std::declval<BBMaterial>()._has_bits_); static void set_has_shadername(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_vshaderpath(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_fshaderpath(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_blendstate(HasBits* has_bits) { (*has_bits)[0] |= 64u; } static void set_has_srcblendfunc(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static void set_has_dstblendfunc(HasBits* has_bits) { (*has_bits)[0] |= 256u; } static void set_has_cullstate(HasBits* has_bits) { (*has_bits)[0] |= 128u; } static void set_has_cullface(HasBits* has_bits) { (*has_bits)[0] |= 512u; } static void set_has_cubemapname(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static const ::BBSerializer::BBCubeMap& cubemappaths(const BBMaterial* msg); static void set_has_cubemappaths(HasBits* has_bits) { (*has_bits)[0] |= 16u; } }; const ::BBSerializer::BBCubeMap& BBMaterial::_Internal::cubemappaths(const BBMaterial* msg) { return *msg->cubemappaths_; } void BBMaterial::clear_vec4value() { vec4value_.Clear(); } void BBMaterial::clear_cubemappaths() { if (GetArena() == nullptr && cubemappaths_ != nullptr) { delete cubemappaths_; } cubemappaths_ = nullptr; _has_bits_[0] &= ~0x00000010u; } BBMaterial::BBMaterial(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), texturename_(arena), texturepath_(arena), floatname_(arena), floatvalue_(arena), vec4name_(arena), vec4value_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:BBSerializer.BBMaterial) } BBMaterial::BBMaterial(const BBMaterial& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), texturename_(from.texturename_), texturepath_(from.texturepath_), floatname_(from.floatname_), floatvalue_(from.floatvalue_), vec4name_(from.vec4name_), vec4value_(from.vec4value_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); shadername_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_shadername()) { shadername_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_shadername(), GetArena()); } vshaderpath_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_vshaderpath()) { vshaderpath_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_vshaderpath(), GetArena()); } fshaderpath_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_fshaderpath()) { fshaderpath_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_fshaderpath(), GetArena()); } cubemapname_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_cubemapname()) { cubemapname_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_cubemapname(), GetArena()); } if (from._internal_has_cubemappaths()) { cubemappaths_ = new ::BBSerializer::BBCubeMap(*from.cubemappaths_); } else { cubemappaths_ = nullptr; } ::memcpy(&srcblendfunc_, &from.srcblendfunc_, static_cast<size_t>(reinterpret_cast<char*>(&cullface_) - reinterpret_cast<char*>(&srcblendfunc_)) + sizeof(cullface_)); // @@protoc_insertion_point(copy_constructor:BBSerializer.BBMaterial) } void BBMaterial::SharedCtor() { shadername_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); vshaderpath_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); fshaderpath_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); cubemapname_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&cubemappaths_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&cullface_) - reinterpret_cast<char*>(&cubemappaths_)) + sizeof(cullface_)); } BBMaterial::~BBMaterial() { // @@protoc_insertion_point(destructor:BBSerializer.BBMaterial) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void BBMaterial::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); shadername_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); vshaderpath_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); fshaderpath_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); cubemapname_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete cubemappaths_; } void BBMaterial::ArenaDtor(void* object) { BBMaterial* _this = reinterpret_cast< BBMaterial* >(object); (void)_this; } void BBMaterial::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void BBMaterial::SetCachedSize(int size) const { _cached_size_.Set(size); } void BBMaterial::Clear() { // @@protoc_insertion_point(message_clear_start:BBSerializer.BBMaterial) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; texturename_.Clear(); texturepath_.Clear(); floatname_.Clear(); floatvalue_.Clear(); vec4name_.Clear(); vec4value_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000001fu) { if (cached_has_bits & 0x00000001u) { shadername_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { vshaderpath_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { fshaderpath_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { cubemapname_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000010u) { if (GetArena() == nullptr && cubemappaths_ != nullptr) { delete cubemappaths_; } cubemappaths_ = nullptr; } } if (cached_has_bits & 0x000000e0u) { ::memset(&srcblendfunc_, 0, static_cast<size_t>( reinterpret_cast<char*>(&cullstate_) - reinterpret_cast<char*>(&srcblendfunc_)) + sizeof(cullstate_)); } if (cached_has_bits & 0x00000300u) { ::memset(&dstblendfunc_, 0, static_cast<size_t>( reinterpret_cast<char*>(&cullface_) - reinterpret_cast<char*>(&dstblendfunc_)) + sizeof(cullface_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* BBMaterial::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // string shaderName = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_shadername(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.shaderName")); CHK_(ptr); } else goto handle_unusual; continue; // string vShaderPath = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { auto str = _internal_mutable_vshaderpath(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.vShaderPath")); CHK_(ptr); } else goto handle_unusual; continue; // string fShaderPath = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { auto str = _internal_mutable_fshaderpath(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.fShaderPath")); CHK_(ptr); } else goto handle_unusual; continue; // repeated string textureName = 4; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { ptr -= 1; do { ptr += 1; auto str = _internal_add_texturename(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.textureName")); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<34>(ptr)); } else goto handle_unusual; continue; // repeated string texturePath = 5; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) { ptr -= 1; do { ptr += 1; auto str = _internal_add_texturepath(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.texturePath")); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<42>(ptr)); } else goto handle_unusual; continue; // repeated string floatName = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) { ptr -= 1; do { ptr += 1; auto str = _internal_add_floatname(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.floatName")); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<50>(ptr)); } else goto handle_unusual; continue; // repeated float floatValue = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedFloatParser(_internal_mutable_floatvalue(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 61) { _internal_add_floatvalue(::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr)); ptr += sizeof(float); } else goto handle_unusual; continue; // repeated string vec4Name = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 66)) { ptr -= 1; do { ptr += 1; auto str = _internal_add_vec4name(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.vec4Name")); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<66>(ptr)); } else goto handle_unusual; continue; // repeated .BBSerializer.BBVector4f vec4Value = 9; case 9: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 74)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_vec4value(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<74>(ptr)); } else goto handle_unusual; continue; // bool blendState = 10; case 10: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 80)) { _Internal::set_has_blendstate(&has_bits); blendstate_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // int32 SRCBlendFunc = 11; case 11: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 88)) { _Internal::set_has_srcblendfunc(&has_bits); srcblendfunc_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // int32 DSTBlendFunc = 12; case 12: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 96)) { _Internal::set_has_dstblendfunc(&has_bits); dstblendfunc_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // bool cullState = 13; case 13: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 104)) { _Internal::set_has_cullstate(&has_bits); cullstate_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // int32 cullFace = 14; case 14: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 112)) { _Internal::set_has_cullface(&has_bits); cullface_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // string cubeMapName = 15; case 15: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 122)) { auto str = _internal_mutable_cubemapname(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.cubeMapName")); CHK_(ptr); } else goto handle_unusual; continue; // .BBSerializer.BBCubeMap cubeMapPaths = 16; case 16: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 130)) { ptr = ctx->ParseMessage(_internal_mutable_cubemappaths(), ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* BBMaterial::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:BBSerializer.BBMaterial) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string shaderName = 1; if (_internal_has_shadername()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_shadername().data(), static_cast<int>(this->_internal_shadername().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.shaderName"); target = stream->WriteStringMaybeAliased( 1, this->_internal_shadername(), target); } // string vShaderPath = 2; if (_internal_has_vshaderpath()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_vshaderpath().data(), static_cast<int>(this->_internal_vshaderpath().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.vShaderPath"); target = stream->WriteStringMaybeAliased( 2, this->_internal_vshaderpath(), target); } // string fShaderPath = 3; if (_internal_has_fshaderpath()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_fshaderpath().data(), static_cast<int>(this->_internal_fshaderpath().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.fShaderPath"); target = stream->WriteStringMaybeAliased( 3, this->_internal_fshaderpath(), target); } // repeated string textureName = 4; for (int i = 0, n = this->_internal_texturename_size(); i < n; i++) { const auto& s = this->_internal_texturename(i); ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( s.data(), static_cast<int>(s.length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.textureName"); target = stream->WriteString(4, s, target); } // repeated string texturePath = 5; for (int i = 0, n = this->_internal_texturepath_size(); i < n; i++) { const auto& s = this->_internal_texturepath(i); ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( s.data(), static_cast<int>(s.length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.texturePath"); target = stream->WriteString(5, s, target); } // repeated string floatName = 6; for (int i = 0, n = this->_internal_floatname_size(); i < n; i++) { const auto& s = this->_internal_floatname(i); ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( s.data(), static_cast<int>(s.length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.floatName"); target = stream->WriteString(6, s, target); } // repeated float floatValue = 7; if (this->_internal_floatvalue_size() > 0) { target = stream->WriteFixedPacked(7, _internal_floatvalue(), target); } // repeated string vec4Name = 8; for (int i = 0, n = this->_internal_vec4name_size(); i < n; i++) { const auto& s = this->_internal_vec4name(i); ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( s.data(), static_cast<int>(s.length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.vec4Name"); target = stream->WriteString(8, s, target); } // repeated .BBSerializer.BBVector4f vec4Value = 9; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_vec4value_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(9, this->_internal_vec4value(i), target, stream); } // bool blendState = 10; if (_internal_has_blendstate()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(10, this->_internal_blendstate(), target); } // int32 SRCBlendFunc = 11; if (_internal_has_srcblendfunc()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(11, this->_internal_srcblendfunc(), target); } // int32 DSTBlendFunc = 12; if (_internal_has_dstblendfunc()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(12, this->_internal_dstblendfunc(), target); } // bool cullState = 13; if (_internal_has_cullstate()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(13, this->_internal_cullstate(), target); } // int32 cullFace = 14; if (_internal_has_cullface()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(14, this->_internal_cullface(), target); } // string cubeMapName = 15; if (_internal_has_cubemapname()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_cubemapname().data(), static_cast<int>(this->_internal_cubemapname().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.cubeMapName"); target = stream->WriteStringMaybeAliased( 15, this->_internal_cubemapname(), target); } // .BBSerializer.BBCubeMap cubeMapPaths = 16; if (_internal_has_cubemappaths()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 16, _Internal::cubemappaths(this), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:BBSerializer.BBMaterial) return target; } size_t BBMaterial::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:BBSerializer.BBMaterial) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated string textureName = 4; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(texturename_.size()); for (int i = 0, n = texturename_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( texturename_.Get(i)); } // repeated string texturePath = 5; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(texturepath_.size()); for (int i = 0, n = texturepath_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( texturepath_.Get(i)); } // repeated string floatName = 6; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(floatname_.size()); for (int i = 0, n = floatname_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( floatname_.Get(i)); } // repeated float floatValue = 7; { unsigned int count = static_cast<unsigned int>(this->_internal_floatvalue_size()); size_t data_size = 4UL * count; if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } total_size += data_size; } // repeated string vec4Name = 8; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(vec4name_.size()); for (int i = 0, n = vec4name_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( vec4name_.Get(i)); } // repeated .BBSerializer.BBVector4f vec4Value = 9; total_size += 1UL * this->_internal_vec4value_size(); for (const auto& msg : this->vec4value_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x000000ffu) { // string shaderName = 1; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_shadername()); } // string vShaderPath = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_vshaderpath()); } // string fShaderPath = 3; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_fshaderpath()); } // string cubeMapName = 15; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_cubemapname()); } // .BBSerializer.BBCubeMap cubeMapPaths = 16; if (cached_has_bits & 0x00000010u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *cubemappaths_); } // int32 SRCBlendFunc = 11; if (cached_has_bits & 0x00000020u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_srcblendfunc()); } // bool blendState = 10; if (cached_has_bits & 0x00000040u) { total_size += 1 + 1; } // bool cullState = 13; if (cached_has_bits & 0x00000080u) { total_size += 1 + 1; } } if (cached_has_bits & 0x00000300u) { // int32 DSTBlendFunc = 12; if (cached_has_bits & 0x00000100u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_dstblendfunc()); } // int32 cullFace = 14; if (cached_has_bits & 0x00000200u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_cullface()); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BBMaterial::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:BBSerializer.BBMaterial) GOOGLE_DCHECK_NE(&from, this); const BBMaterial* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<BBMaterial>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:BBSerializer.BBMaterial) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:BBSerializer.BBMaterial) MergeFrom(*source); } } void BBMaterial::MergeFrom(const BBMaterial& from) { // @@protoc_insertion_point(class_specific_merge_from_start:BBSerializer.BBMaterial) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; texturename_.MergeFrom(from.texturename_); texturepath_.MergeFrom(from.texturepath_); floatname_.MergeFrom(from.floatname_); floatvalue_.MergeFrom(from.floatvalue_); vec4name_.MergeFrom(from.vec4name_); vec4value_.MergeFrom(from.vec4value_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x000000ffu) { if (cached_has_bits & 0x00000001u) { _internal_set_shadername(from._internal_shadername()); } if (cached_has_bits & 0x00000002u) { _internal_set_vshaderpath(from._internal_vshaderpath()); } if (cached_has_bits & 0x00000004u) { _internal_set_fshaderpath(from._internal_fshaderpath()); } if (cached_has_bits & 0x00000008u) { _internal_set_cubemapname(from._internal_cubemapname()); } if (cached_has_bits & 0x00000010u) { _internal_mutable_cubemappaths()->::BBSerializer::BBCubeMap::MergeFrom(from._internal_cubemappaths()); } if (cached_has_bits & 0x00000020u) { srcblendfunc_ = from.srcblendfunc_; } if (cached_has_bits & 0x00000040u) { blendstate_ = from.blendstate_; } if (cached_has_bits & 0x00000080u) { cullstate_ = from.cullstate_; } _has_bits_[0] |= cached_has_bits; } if (cached_has_bits & 0x00000300u) { if (cached_has_bits & 0x00000100u) { dstblendfunc_ = from.dstblendfunc_; } if (cached_has_bits & 0x00000200u) { cullface_ = from.cullface_; } _has_bits_[0] |= cached_has_bits; } } void BBMaterial::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:BBSerializer.BBMaterial) if (&from == this) return; Clear(); MergeFrom(from); } void BBMaterial::CopyFrom(const BBMaterial& from) { // @@protoc_insertion_point(class_specific_copy_from_start:BBSerializer.BBMaterial) if (&from == this) return; Clear(); MergeFrom(from); } bool BBMaterial::IsInitialized() const { return true; } void BBMaterial::InternalSwap(BBMaterial* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); texturename_.InternalSwap(&other->texturename_); texturepath_.InternalSwap(&other->texturepath_); floatname_.InternalSwap(&other->floatname_); floatvalue_.InternalSwap(&other->floatvalue_); vec4name_.InternalSwap(&other->vec4name_); vec4value_.InternalSwap(&other->vec4value_); shadername_.Swap(&other->shadername_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); vshaderpath_.Swap(&other->vshaderpath_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); fshaderpath_.Swap(&other->fshaderpath_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); cubemapname_.Swap(&other->cubemapname_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(BBMaterial, cullface_) + sizeof(BBMaterial::cullface_) - PROTOBUF_FIELD_OFFSET(BBMaterial, cubemappaths_)>( reinterpret_cast<char*>(&cubemappaths_), reinterpret_cast<char*>(&other->cubemappaths_)); } ::PROTOBUF_NAMESPACE_ID::Metadata BBMaterial::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_BBMaterial_2eproto_getter, &descriptor_table_BBMaterial_2eproto_once, file_level_metadata_BBMaterial_2eproto[0]); } // @@protoc_insertion_point(namespace_scope) } // namespace BBSerializer PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::BBSerializer::BBMaterial* Arena::CreateMaybeMessage< ::BBSerializer::BBMaterial >(Arena* arena) { return Arena::CreateMessageInternal< ::BBSerializer::BBMaterial >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
40.904762
172
0.707324
xiaoxianrouzhiyou
7c65564d6a6d4b54ed3b7a5ababd4394bff7452b
201
cpp
C++
3-C-And-CPlusPlus-Interview/3-6-CPlusPlusTest/3-6-4-Test4.cpp
wuping5719/JustFun
18140dc1ee314ac8b87d7a95271e4ed2ddf7acd5
[ "MIT" ]
6
2016-05-25T05:23:00.000Z
2021-10-04T09:31:28.000Z
3-C-And-CPlusPlus-Interview/3-6-CPlusPlusTest/3-6-4-Test4.cpp
wuping5719/JustFun
18140dc1ee314ac8b87d7a95271e4ed2ddf7acd5
[ "MIT" ]
null
null
null
3-C-And-CPlusPlus-Interview/3-6-CPlusPlusTest/3-6-4-Test4.cpp
wuping5719/JustFun
18140dc1ee314ac8b87d7a95271e4ed2ddf7acd5
[ "MIT" ]
2
2016-10-15T17:59:31.000Z
2018-06-06T09:44:35.000Z
#include "stdafx.h" #include<stdio.h> #include<stdlib.h> void main() { int a=-3; unsigned int b=2; long c=a+b; printf("%ld\n",c); int x=10; int y=10; x=y=++y; printf("%d %d",x,y); }
11.823529
24
0.542289
wuping5719
7c681e767fdd267c0413fe96aa9ec6f9bb3d14f5
16,453
cpp
C++
ROLE/vision/hls/gammacorrection/src/gammacorrection.cpp
cloudFPGA/cFp_Zoo
3aefb12108f99fcfd0d39a8aae97cf87428a6873
[ "Apache-2.0" ]
6
2021-12-29T10:58:28.000Z
2022-02-15T06:07:05.000Z
ROLE/vision/hls/gammacorrection/src/gammacorrection.cpp
cloudFPGA/cFp_Zoo
3aefb12108f99fcfd0d39a8aae97cf87428a6873
[ "Apache-2.0" ]
2
2022-01-17T10:35:55.000Z
2022-02-04T09:28:47.000Z
ROLE/vision/hls/gammacorrection/src/gammacorrection.cpp
cloudFPGA/cFp_Zoo
3aefb12108f99fcfd0d39a8aae97cf87428a6873
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** * @file gammacorrection.cpp * @brief The Role for a Gammacorrection Example application (UDP or TCP) * @author FAB, WEI, NGL, DID * @date May 2020 *---------------------------------------------------------------------------- * * @details This application implements a UDP-oriented Vitis function. * * @deprecated For the time being, we continue designing with the DEPRECATED * directives because the new PRAGMAs do not work for us. * *---------------------------------------------------------------------------- * * @ingroup GammacorrectionHLS * @addtogroup GammacorrectionHLS * \{ *****************************************************************************/ #include "../include/gammacorrection.hpp" #include "../include/xf_gammacorrection_config.h" #ifdef USE_HLSLIB_DATAFLOW #include "../../../../../hlslib/include/hlslib/xilinx/Stream.h" #include "../../../../../hlslib/include/hlslib/xilinx/Simulation.h" #endif #ifdef USE_HLSLIB_STREAM using hlslib::Stream; #endif using hls::stream; //#define Data_t ap_uint<INPUT_PTR_WIDTH> //#define Data_t NetworkWord #define Data_t ap_axiu<INPUT_PTR_WIDTH, 0, 0, 0> PacketFsmType enqueueFSM = WAIT_FOR_META; PacketFsmType dequeueFSM = WAIT_FOR_STREAM_PAIR; PacketFsmType GammacorrectionFSM = WAIT_FOR_META; /***************************************************************************** * @brief Store a word from ethernet to local memory * @return Nothing. *****************************************************************************/ void storeWordToArray(uint64_t input, ap_uint<INPUT_PTR_WIDTH> img[IMG_PACKETS], unsigned int *processed_word, unsigned int *image_loaded) { #pragma HLS INLINE img[*processed_word] = (ap_uint<INPUT_PTR_WIDTH>) input; printf("DEBUG in storeWordToArray: input = %u = 0x%16.16llX \n", input, input); printf("DEBUG in storeWordToArray: img[%u]= %u = 0x%16.16llX \n", *processed_word, (uint64_t)img[*processed_word], (uint64_t)img[*processed_word]); if (*processed_word < IMG_PACKETS-1) { *processed_word++; } else { printf("DEBUG in storeWordToArray: WARNING - you've reached the max depth of img[%u]. Will put *processed_word = 0.\n", *processed_word); *processed_word = 0; *image_loaded = 1; } } /***************************************************************************** * @brief Store a word from ethernet to a local AXI stream * @return Nothing. *****************************************************************************/ void storeWordToAxiStream( NetworkWord word, //Stream<Data_t, IMG_PACKETS> &img_in_axi_stream, stream<Data_t> &img_in_axi_stream, unsigned int *processed_word_rx, unsigned int *image_loaded) { #pragma HLS INLINE Data_t v; v.data = word.tdata; v.keep = word.tkeep; v.last = word.tlast; //Data_t v; //v = word.tdata; img_in_axi_stream.write(v); if (*processed_word_rx < IMG_PACKETS-1) { (*processed_word_rx)++; } else { printf("DEBUG in storeWordToAxiStream: WARNING - you've reached the max depth of img. Will put *processed_word_rx = 0.\n"); *processed_word_rx = 0; *image_loaded = 1; } } /***************************************************************************** * @brief Receive Path - From SHELL to THIS. * * @param[in] siSHL_This_Data * @param[in] siNrc_meta * @param[out] sRxtoTx_Meta * @param[out] img_in_axi_stream * @param[out] meta_tmp * @param[out] processed_word * @param[out] image_loaded * * @return Nothing. ******************************************************************************/ void pRXPath( stream<NetworkWord> &siSHL_This_Data, stream<NetworkMetaStream> &siNrc_meta, stream<NetworkMetaStream> &sRxtoTx_Meta, //Stream<Data_t, IMG_PACKETS> &img_in_axi_stream, stream<Data_t> &img_in_axi_stream, NetworkMetaStream meta_tmp, unsigned int *processed_word_rx, unsigned int *image_loaded ) { //-- DIRECTIVES FOR THIS PROCESS ------------------------------------------ //#pragma HLS DATAFLOW interval=1 #pragma HLS INLINE //-- LOCAL VARIABLES ------------------------------------------------------ UdpWord udpWord; switch(enqueueFSM) { case WAIT_FOR_META: printf("DEBUG in pRXPath: enqueueFSM - WAIT_FOR_META, *processed_word_rx=%u\n", *processed_word_rx); if ( !siNrc_meta.empty() && !sRxtoTx_Meta.full() ) { meta_tmp = siNrc_meta.read(); meta_tmp.tlast = 1; //just to be sure... sRxtoTx_Meta.write(meta_tmp); enqueueFSM = PROCESSING_PACKET; } //*processed_word_rx = 0; *image_loaded = 0; break; case PROCESSING_PACKET: printf("DEBUG in pRXPath: enqueueFSM - PROCESSING_PACKET, *processed_word_rx=%u\n", *processed_word_rx); if ( !siSHL_This_Data.empty() && !img_in_axi_stream.full() ) { //-- Read incoming data chunk udpWord = siSHL_This_Data.read(); storeWordToAxiStream(udpWord, img_in_axi_stream, processed_word_rx, image_loaded); if(udpWord.tlast == 1) { enqueueFSM = WAIT_FOR_META; } } break; } } /***************************************************************************** * @brief Processing Path - Main processing FSM for Vitis kernels. * * @param[out] sRxpToTxp_Data * @param[in] img_in_axi_stream * @param[in] img_out_axi_stream * @param[out] processed_word_rx * @param[in] image_loaded * * @return Nothing. ******************************************************************************/ void pProcPath( stream<NetworkWord> &sRxpToTxp_Data, //Stream<Data_t, IMG_PACKETS> &img_in_axi_stream, //Stream<Data_t, IMG_PACKETS> &img_out_axi_stream, stream<Data_t> &img_in_axi_stream, stream<Data_t> &img_out_axi_stream, unsigned int *processed_word_rx, unsigned int *image_loaded ) { //-- DIRECTIVES FOR THIS PROCESS ------------------------------------------ //#pragma HLS DATAFLOW interval=1 #pragma HLS INLINE //-- LOCAL VARIABLES ------------------------------------------------------ NetworkWord newWord; uint16_t Thresh = 442; float K = 0.04; uint16_t k = K * (1 << 16); // Convert to Q0.16 format switch(GammacorrectionFSM) { case WAIT_FOR_META: printf("DEBUG in pProcPath: WAIT_FOR_META\n"); if ( (*image_loaded) == 1 ) { GammacorrectionFSM = PROCESSING_PACKET; *processed_word_rx = 0; } break; case PROCESSING_PACKET: printf("DEBUG in pProcPath: PROCESSING_PACKET\n"); if ( !img_in_axi_stream.empty() && !img_out_axi_stream.full() ) { GammacorrectionAccelStream(img_in_axi_stream, img_out_axi_stream, WIDTH, HEIGHT, Thresh, k); if ( !img_out_axi_stream.empty() ) { GammacorrectionFSM = GAMMACORRECTION_RETURN_RESULTS; } } break; case GAMMACORRECTION_RETURN_RESULTS: printf("DEBUG in pProcPath: GAMMACORRECTION_RETURN_RESULTS\n"); if ( !img_out_axi_stream.empty() && !sRxpToTxp_Data.full() ) { Data_t temp = img_out_axi_stream.read(); if ( img_out_axi_stream.empty() ) { temp.last = 1; GammacorrectionFSM = WAIT_FOR_META; } else { temp.last = 0; } //TODO: find why Vitis kernel does not set keep and last by itself temp.keep = 255; newWord = NetworkWord(temp.data, temp.keep, temp.last); sRxpToTxp_Data.write(newWord); } break; } // end switch } /***************************************************************************** * @brief Transmit Path - From THIS to SHELL. * * @param[out] soTHIS_Shl_Data * @param[out] soNrc_meta * @param[in] sRxpToTxp_Data * @param[in] sRxtoTx_Meta * @param[in] pi_rank * @param[in] pi_size * * @return Nothing. *****************************************************************************/ void pTXPath( stream<NetworkWord> &soTHIS_Shl_Data, stream<NetworkMetaStream> &soNrc_meta, stream<NetworkWord> &sRxpToTxp_Data, stream<NetworkMetaStream> &sRxtoTx_Meta, unsigned int *processed_word_tx, ap_uint<32> *pi_rank, ap_uint<32> *pi_size ) { //-- DIRECTIVES FOR THIS PROCESS ------------------------------------------ //#pragma HLS DATAFLOW interval=1 #pragma HLS INLINE //-- LOCAL VARIABLES ------------------------------------------------------ UdpWord udpWordTx; NetworkMeta meta_in = NetworkMeta(); switch(dequeueFSM) { case WAIT_FOR_STREAM_PAIR: printf("DEBUG in pTXPath: dequeueFSM=%d - WAIT_FOR_STREAM_PAIR, *processed_word_tx=%u\n", dequeueFSM, *processed_word_tx); //-- Forward incoming chunk to SHELL *processed_word_tx = 0; /* printf("!sRxpToTxp_Data.empty()=%d\n", !sRxpToTxp_Data.empty()); printf("!sRxtoTx_Meta.empty()=%d\n", !sRxtoTx_Meta.empty()); printf("!soTHIS_Shl_Data.full()=%d\n", !soTHIS_Shl_Data.full()); printf("!soNrc_meta.full()=%d\n", !soNrc_meta.full()); */ if (( !sRxpToTxp_Data.empty() && !sRxtoTx_Meta.empty() && !soTHIS_Shl_Data.full() && !soNrc_meta.full() )) { udpWordTx = sRxpToTxp_Data.read(); // in case MTU=8 ensure tlast is set in WAIT_FOR_STREAM_PAIR and don't visit PROCESSING_PACKET if (PACK_SIZE == 8) { udpWordTx.tlast = 1; } soTHIS_Shl_Data.write(udpWordTx); meta_in = sRxtoTx_Meta.read().tdata; NetworkMetaStream meta_out_stream = NetworkMetaStream(); meta_out_stream.tlast = 1; meta_out_stream.tkeep = 0xFF; //just to be sure //printf("rank: %d; size: %d; \n", (int) *pi_rank, (int) *pi_size); meta_out_stream.tdata.dst_rank = (*pi_rank + 1) % *pi_size; //printf("meat_out.dst_rank: %d\n", (int) meta_out_stream.tdata.dst_rank); meta_out_stream.tdata.dst_port = DEFAULT_TX_PORT; meta_out_stream.tdata.src_rank = (NodeId) *pi_rank; meta_out_stream.tdata.src_port = DEFAULT_RX_PORT; //meta_out_stream.tdata.len = meta_in.len; soNrc_meta.write(meta_out_stream); (*processed_word_tx)++; if(udpWordTx.tlast != 1) { dequeueFSM = PROCESSING_PACKET; } } break; case PROCESSING_PACKET: printf("DEBUG in pTXPath: dequeueFSM=%d - PROCESSING_PACKET, *processed_word_tx=%u\n", dequeueFSM, *processed_word_tx); if( !sRxpToTxp_Data.empty() && !soTHIS_Shl_Data.full()) { udpWordTx = sRxpToTxp_Data.read(); // This is a normal termination of the axi stream from vitis functions if(udpWordTx.tlast == 1) { dequeueFSM = WAIT_FOR_STREAM_PAIR; } // This is our own termination based on the custom MTU we have set in PACK_SIZE. // TODO: We can map PACK_SIZE to a dynamically assigned value either through MMIO or header // in order to have a functional bitstream for any MTU size (*processed_word_tx)++; if (((*processed_word_tx)*8) % PACK_SIZE == 0) { udpWordTx.tlast = 1; dequeueFSM = WAIT_FOR_STREAM_PAIR; } soTHIS_Shl_Data.write(udpWordTx); } break; } } /***************************************************************************** * @brief Main process of the Gammacorrection Application * directives. * @deprecated This functions is using deprecated AXI stream interface * @return Nothing. *****************************************************************************/ void gammacorrection( ap_uint<32> *pi_rank, ap_uint<32> *pi_size, //------------------------------------------------------ //-- SHELL / This / Udp/TCP Interfaces //------------------------------------------------------ stream<NetworkWord> &siSHL_This_Data, stream<NetworkWord> &soTHIS_Shl_Data, stream<NetworkMetaStream> &siNrc_meta, stream<NetworkMetaStream> &soNrc_meta, ap_uint<32> *po_rx_ports ) { //-- DIRECTIVES FOR THE BLOCK --------------------------------------------- //#pragma HLS INTERFACE ap_ctrl_none port=return //#pragma HLS INTERFACE ap_stable port=piSHL_This_MmioEchoCtrl #pragma HLS INTERFACE axis register both port=siSHL_This_Data #pragma HLS INTERFACE axis register both port=soTHIS_Shl_Data #pragma HLS INTERFACE axis register both port=siNrc_meta #pragma HLS INTERFACE axis register both port=soNrc_meta #pragma HLS INTERFACE ap_ovld register port=po_rx_ports name=poROL_NRC_Rx_ports #pragma HLS INTERFACE ap_stable register port=pi_rank name=piFMC_ROL_rank #pragma HLS INTERFACE ap_stable register port=pi_size name=piFMC_ROL_size //-- LOCAL VARIABLES ------------------------------------------------------ NetworkMetaStream meta_tmp = NetworkMetaStream(); static stream<NetworkWord> sRxpToTxp_Data("sRxpToTxP_Data"); // FIXME: works even with no static static stream<NetworkMetaStream> sRxtoTx_Meta("sRxtoTx_Meta"); static unsigned int processed_word_rx; static unsigned int processed_word_tx; static unsigned int image_loaded; const int img_packets = IMG_PACKETS; const int tot_transfers = TOT_TRANSFERS; static stream<Data_t> img_in_axi_stream ("img_in_axi_stream" ); static stream<Data_t> img_out_axi_stream("img_out_axi_stream"); //static Stream<Data_t, IMG_PACKETS> img_in_axi_stream ("img_in_axi_stream"); //static Stream<Data_t, IMG_PACKETS> img_out_axi_stream ("img_out_axi_stream"); *po_rx_ports = 0x1; //currently work only with default ports... //-- DIRECTIVES FOR THIS PROCESS ------------------------------------------ #pragma HLS DATAFLOW //#pragma HLS STREAM variable=sRxpToTxp_Data depth=TOT_TRANSFERS #pragma HLS stream variable=sRxtoTx_Meta depth=tot_transfers #pragma HLS reset variable=enqueueFSM #pragma HLS reset variable=dequeueFSM #pragma HLS reset variable=GammacorrectionFSM #pragma HLS reset variable=processed_word_rx #pragma HLS reset variable=processed_word_tx #pragma HLS reset variable=image_loaded #pragma HLS stream variable=img_in_axi_stream depth=img_packets #pragma HLS stream variable=img_out_axi_stream depth=img_packets #ifdef USE_HLSLIB_DATAFLOW /* * Use this snippet to early check for C++ errors related to dataflow and bounded streams (empty * and full) during simulation. It can also be both synthesized and used in co-simulation. * Practically we use hlslib when we want to run simulation as close as possible to the HW, by * executing all functions of dataflow in thread-safe parallel executions, i.e the function * HLSLIB_DATAFLOW_FINALIZE() acts as a barrier for the threads spawned to serve every function * called in HLSLIB_DATAFLOW_FUNCTION(func, args...). */ // Dataflow functions running in parallel HLSLIB_DATAFLOW_INIT(); HLSLIB_DATAFLOW_FUNCTION(pRXPath, siSHL_This_Data, siNrc_meta, sRxtoTx_Meta, img_in_axi_stream, meta_tmp, &processed_word_rx, &image_loaded); HLSLIB_DATAFLOW_FUNCTION(pProcPath, sRxpToTxp_Data, img_in_axi_stream, img_out_axi_stream, &processed_word_rx, &image_loaded); HLSLIB_DATAFLOW_FUNCTION(pTXPath, soTHIS_Shl_Data, soNrc_meta, sRxpToTxp_Data, sRxtoTx_Meta, &processed_word_tx, pi_rank, pi_size); HLSLIB_DATAFLOW_FINALIZE(); #else // !USE_HLSLIB_DATAFLOW pRXPath( siSHL_This_Data, siNrc_meta, sRxtoTx_Meta, img_in_axi_stream, meta_tmp, &processed_word_rx, &image_loaded); pProcPath(sRxpToTxp_Data, img_in_axi_stream, img_out_axi_stream, &processed_word_rx, &image_loaded); pTXPath( soTHIS_Shl_Data, soNrc_meta, sRxpToTxp_Data, sRxtoTx_Meta, &processed_word_tx, pi_rank, pi_size); #endif // USE_HLSLIB_DATAFLOW } /*! \} */
33.238384
141
0.587917
cloudFPGA
7c6932698dcd328d5f0ea9a9641c7efacd43d132
2,841
cpp
C++
cpp/recursionAlgorithms.cpp
chaohan/code-samples
0ae7da954a36547362924003d56a8bece845802c
[ "MIT" ]
null
null
null
cpp/recursionAlgorithms.cpp
chaohan/code-samples
0ae7da954a36547362924003d56a8bece845802c
[ "MIT" ]
null
null
null
cpp/recursionAlgorithms.cpp
chaohan/code-samples
0ae7da954a36547362924003d56a8bece845802c
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/assignment.hpp> #include <boost/math/special_functions/binomial.hpp> namespace recursionAlgorithms { using namespace std; using namespace boost::numeric::ublas; /*9.1 count ways to cover N steps by hopping either 1,2 or 3 steps at a time */ int waysToHopSlow(int N) { if (N==1 || N==0) { return 1; } if (N<0) { return 0; } return waysToHopSlow(N-1)+waysToHopSlow(N-2)+waysToHopSlow(N-3); }; int waysToHopFast(int N, std::vector<int> &cache) { if (N==0 || N==1) { return 1; } if (N<0) { return 0; } if (cache[N]>0) { return cache[N]; } cache[N] = waysToHopFast(N-1,cache) + waysToHopFast(N-2,cache) + waysToHopFast(N-3,cache); return cache[N]; }; /*9.2 Return the number of ways connecting the top-left corner of a MxN matrix/grid to the bottom-right corner, going only downward and rightward. Off-limits grid points are allow by specifying a -1 value in the cache input matrix */ int ways2D(int r, int c, matrix<int> &cache) { if (r == cache.size1()-1 && c == cache.size2()-1 ) { return 1;} if (r >= cache.size1() || c >= cache.size2() || cache(r,c) == -1) { return 0; } if (cache(r,c)>0) { return cache(r,c); } cache(r,c) = ways2D(r,c+1,cache) + ways2D(r+1,c,cache); return cache(r,c); }; template <typename dataType> void printMatrix(matrix<dataType> &mat) { for (int row=0;row<mat.size1();row++) { for (int col=0;col<mat.size2()-1;col++) { cout << mat(row,col) << " "; } cout << mat(row,mat.size2()-1) << endl; } }; }; int main() { using namespace recursionAlgorithms; using namespace boost::math; //matrix<int> input(12,1); //input <<= 1,0,1,2,2,1,3,3,3,0,10,11; // test 9.1 //int Nin = 35; //std::vector<int> cache(Nin,0); //cout << waysToHopSlow(Nin) << endl; //cout << waysToHopFast(Nin,cache) << endl; // test 9.2 int M,N; M = 10; N= 10; matrix<int> input(M,N); //input(1,1) = -1; printMatrix(input); cout << "calculated number of ways = "<< ways2D(0,0,input) << endl; cout << "true number of ways = " << binomial_coefficient<double>(M+N-2,M-1) << endl; printMatrix(input); return 0; }
30.548387
91
0.489968
chaohan
7c69fedde02fc2b628a2647295210f9458bd8b0e
590
cpp
C++
1800.cpp
heltonricardo/URI
160cca22d94aa667177c9ebf2a1c9864c5e55b41
[ "MIT" ]
6
2021-04-13T00:33:43.000Z
2022-02-10T10:23:59.000Z
1800.cpp
heltonricardo/URI
160cca22d94aa667177c9ebf2a1c9864c5e55b41
[ "MIT" ]
null
null
null
1800.cpp
heltonricardo/URI
160cca22d94aa667177c9ebf2a1c9864c5e55b41
[ "MIT" ]
3
2021-03-23T18:42:24.000Z
2022-02-10T10:24:07.000Z
#include <iostream> using namespace std; bool tem(int n, int *p, int e) { int i; for (i = 0; i < e; ++i) if (n == p[i]) return true; return false; } int main(void) { int i, n, q, e, *p; cin >> q >> e; p = (int *) realloc(p, e * sizeof(int)); for (i = 0; i < e; ++i) cin >> p[i]; for (i = 0; i < q; ++i) { cin >> n; if (tem(n, p, e)) cout << 0; else { cout << 1; ++e; p = (int *) realloc(p, e * sizeof(int)); p[e-1] = n; } cout << endl; } delete [] p; return 0; }
15.945946
49
0.391525
heltonricardo
7c6f89b99a1f79e2af8474f3b44af03200f0a6c3
4,119
cpp
C++
main-menu.cpp
Daft-Freak/super-blit-kart
9fa17ad45c8857eebd72d0928d0be74afdf9e1fb
[ "MIT" ]
2
2021-10-15T23:22:21.000Z
2021-11-11T06:34:56.000Z
main-menu.cpp
Daft-Freak/super-blit-kart
9fa17ad45c8857eebd72d0928d0be74afdf9e1fb
[ "MIT" ]
null
null
null
main-menu.cpp
Daft-Freak/super-blit-kart
9fa17ad45c8857eebd72d0928d0be74afdf9e1fb
[ "MIT" ]
null
null
null
#include "engine/save.hpp" #include "graphics/font.hpp" #include "graphics/tilemap.hpp" #include "main-menu.hpp" #include "fonts.hpp" #include "game.hpp" #include "kart-select.hpp" static const int menu_target_y = 96; static const int logo_target_y = 8; // where the logo is when the menu is up MainMenu::MainMenu(Game *game, bool initial_state) : game(game), menu("", {{Menu_Race, "Race"}, {Menu_TimeTrial, "Time Trial"}, {Menu_Multiplayer, "Multiplayer"}}, menu_font) { int menu_y; logo = blit::Surface::load(asset_logo); // nice animations on initial load if(initial_state) { logo_y = ((blit::screen.bounds.h - 16) - logo->bounds.h) / 2; menu_y = blit::screen.bounds.h; sprites = blit::Surface::load(asset_menu_sprites); } else { logo_y = logo_target_y; menu_y = menu_target_y; display_menu = intro_done = true; fade = 0; } menu.set_display_rect({0, menu_y, blit::screen.bounds.w, blit::screen.bounds.h - menu_target_y}); // TODO: nicer menu, maybe some sprites or something menu.set_on_item_activated(std::bind(&MainMenu::on_menu_item_selected, this, std::placeholders::_1)); } MainMenu::~MainMenu() { } void MainMenu::update(uint32_t time) { if(fade) fade--; if(!intro_done) { for(auto &kart : karts) { if(kart.pos.x < -32 || kart.pos.x > blit::screen.bounds.w) { // maybe reset auto rand = blit::random(); if(rand & 0x1FF) continue; if(((rand >> 10) & 0x3F) == 0) { // go backwards for fun kart.pos.x = blit::screen.bounds.w; kart.speed = -1; } else { kart.pos.x = -32; kart.speed = ((rand >> 16) & 3) + 1; } kart.pos.y = blit::screen.bounds.h - 44 + ((rand >> 18) & 0xF); kart.kart = (rand >> 22) & 1; } kart.pos.x += kart.speed; } // sort by y std::sort(std::begin(karts), std::end(karts), [](auto &a, auto &b){return a.pos.y < b.pos.y;}); } if(!display_menu) { if(blit::buttons.released) { display_menu = true; } return; } // transition if(logo_y > logo_target_y) { logo_y--; return; } auto &menu_rect = menu.get_display_rect(); if(menu_rect.y > menu_target_y) { menu.set_display_rect({menu_rect.x, menu_rect.y - 1, menu_rect.w, menu_rect.h}); } else intro_done = true; menu.update(time); } void MainMenu::render() { using blit::screen; screen.pen = {0x63, 0x9b, 0xff}; // "sky" colour screen.clear(); int x = (screen.bounds.w - logo->bounds.w) / 2; screen.blit(logo, {{0, 0}, logo->bounds}, {x, logo_y}); // road screen.pen = {0x59, 0x56, 0x52}; screen.rectangle({0, screen.bounds.h - 24, screen.bounds.w, 24}); if(!display_menu && blit::now() % 1000 < 500) { screen.pen = {255, 255, 255}; screen.text("Press a button!", tall_font, {screen.bounds.w / 2, screen.bounds.h - 40}, true, blit::TextAlign::center_center); } // karts // display until menu has finished scrolling if(!intro_done) { screen.sprites = sprites; for(auto &kart : karts) screen.sprite({kart.kart * 4, 0, 4, 4}, kart.pos); } menu.render(); if(!message.empty()) screen.text(message, tall_font, {screen.bounds.w / 2, screen.bounds.h - 20}, true, blit::TextAlign::center_center); if(fade) { screen.pen = {0,0,0, fade}; screen.clear(); } } void MainMenu::on_menu_item_selected(const Menu::Item &item) { switch(item.id) { case Menu_Race: game->change_state<KartSelect>(RaceMode::Race); break; case Menu_TimeTrial: game->change_state<KartSelect>(RaceMode::TimeTrial); break; case Menu_Multiplayer: message = "Maybe later : )"; break; } }
27.831081
176
0.55159
Daft-Freak
7c72de651605385eff7faae5b93f30321a5953b8
7,805
cpp
C++
D&D Wrath of Silumgar/Motor2D/UIBar.cpp
Wilhelman/DD-Shadow-over-Mystara
d4303ad87cc442414c0facb71ce9cd5564b51039
[ "MIT" ]
3
2019-06-21T04:40:16.000Z
2020-07-07T13:09:53.000Z
D&D Wrath of Silumgar/Motor2D/UIBar.cpp
Wilhelman/DD-Shadow-over-Mystara
d4303ad87cc442414c0facb71ce9cd5564b51039
[ "MIT" ]
56
2018-05-07T10:30:08.000Z
2018-05-15T08:27:06.000Z
D&D Wrath of Silumgar/Motor2D/UIBar.cpp
Wilhelman/DD-Shadow-over-Mystara
d4303ad87cc442414c0facb71ce9cd5564b51039
[ "MIT" ]
3
2019-01-03T17:24:57.000Z
2019-05-04T08:49:12.000Z
#include "ctApp.h" #include "UIBar.h" #include "ctLog.h" #include "ctInput.h" #include "ctPerfTimer.h" UIBar::UIBar(int x, int y, int max_capacity, UI_Type type, ctModule* callback, Entity* entity, UIElement* parent) : UIElement(x, y, type, parent) { this->entity = entity; this->callback = callback; bar_type = type; bar_pos.x = x; bar_pos.y = y; this->max_capacity = max_capacity; current_quantity = max_capacity; if (type == LIFEBAR) { max_width = max_player_bar_width; current_width = max_width; previous_width = max_width; bar_height = player_bar_height; lower_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 571,107,max_width,bar_height }); upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,107,max_width,bar_height }); } else if (type == MANABAR) { max_width = max_player_bar_width; current_width = max_width; previous_width = max_width; bar_height = player_bar_height; lower_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 0,129,max_width,bar_height }); upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 318,445,max_width,bar_height }); } else if (type == ENEMYLIFEBAR) { max_width = max_enemy_bar_width; current_width = max_width; previous_width = max_width; bar_height = enemy_bar_height; lower_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 571,110,max_width,bar_height }); upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,110,max_width,bar_height }); } if (bar_type != ENEMYLIFEBAR) { SetBarNumbers(); } LOG("UIBar created in x:%i, y:%i", x, y); } void UIBar::Update() { //Destroy the yellowbar after 500ms if (yellow_bar != nullptr && yellow_bar_time.ReadMs() > 500) { App->gui->DeleteUIElement(*yellow_bar); yellow_bar = nullptr; } //if (current_quantity <=0 && bar_type == LIFEBAR) { // DeleteElements(); // lower_bar = nullptr; // upper_bar = nullptr; // yellow_bar = nullptr; //} } void UIBar::LowerBar(int quantity) { //Lower width of the bar when losing hp/mana if (lower_bar != nullptr) { if (quantity<0) { if ((current_quantity - quantity) >= 0) { current_width = CalculateBarWidth(quantity); App->gui->DeleteUIElement(*upper_bar); if (bar_type == LIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,107,current_width,bar_height }); DrawYellowBar(); } else if (bar_type == MANABAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 317,444,current_width,bar_height }); DrawYellowBar(); } else if (bar_type == ENEMYLIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,110,current_width,bar_height }); DrawYellowBar(); } } else { current_width = CalculateBarWidth(-current_quantity); App->gui->DeleteUIElement(*upper_bar); if (bar_type == LIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,107,current_width,bar_height }); DrawYellowBar(); } else if (bar_type == MANABAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 317,444,current_width,bar_height }); DrawYellowBar(); } else if (bar_type == ENEMYLIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,110,current_width,bar_height }); DrawYellowBar(); } } } else if (quantity>0){ if (lower_bar != nullptr) { if ((current_quantity + quantity) < max_capacity) { current_width = CalculateBarWidth(quantity); App->gui->DeleteUIElement(*upper_bar); if (bar_type == LIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,107,current_width,bar_height }); } else if (bar_type == MANABAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 317,444,current_width,bar_height }); } else if (bar_type == ENEMYLIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,110,current_width,bar_height }); DrawYellowBar(); } } else { current_width = CalculateBarWidth((max_capacity - current_quantity)); App->gui->DeleteUIElement(*upper_bar); if (bar_type == LIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,107,current_width,bar_height }); } else if (bar_type == MANABAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 317,444,current_width,bar_height }); } else if (bar_type == ENEMYLIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,110,current_width,bar_height }); DrawYellowBar(); } } } } } if (bar_type != ENEMYLIFEBAR) { SetBarNumbers(); } } void UIBar::RecoverBar(int quantity) { //Recover width of the bar when wining hp/mana if (lower_bar != nullptr) { if ((current_quantity + quantity) < max_capacity) { current_width = CalculateBarWidth(quantity); App->gui->DeleteUIElement(*upper_bar); if (bar_type == LIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,107,current_width,bar_height }); } else if (bar_type == MANABAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 317,444,current_width,bar_height }); } if (bar_type == ENEMYLIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,110,current_width,bar_height }); } } else { current_width = CalculateBarWidth((max_capacity - current_quantity)); App->gui->DeleteUIElement(*upper_bar); if (bar_type == LIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,107,current_width,bar_height }); } else if (bar_type == MANABAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 317,444,current_width,bar_height }); } if (bar_type == ENEMYLIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,110,current_width,bar_height }); } } } if (bar_type != ENEMYLIFEBAR) { SetBarNumbers(); } } void UIBar::DrawYellowBar() { //Draw a yellow bar showing what you've lost if (yellow_bar != nullptr) { App->gui->DeleteUIElement(*yellow_bar); } if (current_width > 0) { yellow_bar = App->gui->AddUIImage(bar_pos.x + current_width, bar_pos.y, { 583,130,(previous_width - current_width),bar_height }); } else { yellow_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 583,130,(previous_width),bar_height }); } yellow_bar_time.Start(); } void UIBar::DeleteElements() { App->gui->DeleteUIElement(*lower_bar); lower_bar = nullptr; App->gui->DeleteUIElement(*upper_bar); upper_bar = nullptr; App->gui->DeleteUIElement(*yellow_bar); yellow_bar = nullptr; App->gui->DeleteUIElement(*bar_numbers); bar_numbers = nullptr; } int UIBar::CalculateBarWidth(int quantity) { //Calculate the new bar width when losing/wining hp/mana quantity int new_width = current_width; previous_width = current_width; int new_quantity = (current_quantity + quantity); current_quantity = new_quantity; if(max_capacity != 0) new_width = (new_quantity * max_width) / max_capacity; return new_width; } int UIBar::CurrentQuantity() { return current_quantity; } void UIBar::MakeElementsInvisible() { lower_bar->non_drawable = true; upper_bar->non_drawable = true; if (yellow_bar != nullptr) { yellow_bar->non_drawable = true; } } void UIBar::MakeElementsVisible() { lower_bar->non_drawable = false; upper_bar->non_drawable = false; if (yellow_bar != nullptr) { yellow_bar->non_drawable = false; } } void UIBar::SetBarNumbers() { if (bar_numbers != nullptr) { App->gui->DeleteUIElement(*bar_numbers); } if (current_quantity<0) { current_quantity = 0; } std::string bar_nums_char = std::to_string(current_quantity) + "/" + std::to_string(max_capacity); bar_numbers = App->gui->AddUILabel(bar_pos.x + (max_width/2) - 10 , bar_pos.y + 3, bar_nums_char, { 255,255,255,255 }, 16, nullptr, nullptr, Second_Font); }
31.095618
155
0.678796
Wilhelman
7c72e74f787e49768ff10fe148f2314d278fd7a0
1,991
cpp
C++
src/source/DRV_STATUS.cpp
ManuelMcLure/TMCStepper
c425c40f0adfa24c1c21ce7d6428bcffc2c921ae
[ "MIT" ]
336
2018-03-26T13:51:46.000Z
2022-03-21T21:58:47.000Z
src/source/DRV_STATUS.cpp
ManuelMcLure/TMCStepper
c425c40f0adfa24c1c21ce7d6428bcffc2c921ae
[ "MIT" ]
218
2017-07-28T06:13:53.000Z
2022-03-26T16:41:21.000Z
src/source/DRV_STATUS.cpp
ManuelMcLure/TMCStepper
c425c40f0adfa24c1c21ce7d6428bcffc2c921ae
[ "MIT" ]
176
2018-09-11T22:16:27.000Z
2022-03-26T13:04:03.000Z
#include "TMCStepper.h" #include "TMC_MACROS.h" #define GET_REG(NS, SETTING) NS::DRV_STATUS_t r{0}; r.sr = DRV_STATUS(); return r.SETTING uint32_t TMC2130Stepper::DRV_STATUS() { return read(DRV_STATUS_t::address); } uint16_t TMC2130Stepper::sg_result(){ GET_REG(TMC2130_n, sg_result); } bool TMC2130Stepper::fsactive() { GET_REG(TMC2130_n, fsactive); } uint8_t TMC2130Stepper::cs_actual() { GET_REG(TMC2130_n, cs_actual); } bool TMC2130Stepper::stallguard() { GET_REG(TMC2130_n, stallGuard); } bool TMC2130Stepper::ot() { GET_REG(TMC2130_n, ot); } bool TMC2130Stepper::otpw() { GET_REG(TMC2130_n, otpw); } bool TMC2130Stepper::s2ga() { GET_REG(TMC2130_n, s2ga); } bool TMC2130Stepper::s2gb() { GET_REG(TMC2130_n, s2gb); } bool TMC2130Stepper::ola() { GET_REG(TMC2130_n, ola); } bool TMC2130Stepper::olb() { GET_REG(TMC2130_n, olb); } bool TMC2130Stepper::stst() { GET_REG(TMC2130_n, stst); } uint32_t TMC2208Stepper::DRV_STATUS() { return read(TMC2208_n::DRV_STATUS_t::address); } bool TMC2208Stepper::otpw() { GET_REG(TMC2208_n, otpw); } bool TMC2208Stepper::ot() { GET_REG(TMC2208_n, ot); } bool TMC2208Stepper::s2ga() { GET_REG(TMC2208_n, s2ga); } bool TMC2208Stepper::s2gb() { GET_REG(TMC2208_n, s2gb); } bool TMC2208Stepper::s2vsa() { GET_REG(TMC2208_n, s2vsa); } bool TMC2208Stepper::s2vsb() { GET_REG(TMC2208_n, s2vsb); } bool TMC2208Stepper::ola() { GET_REG(TMC2208_n, ola); } bool TMC2208Stepper::olb() { GET_REG(TMC2208_n, olb); } bool TMC2208Stepper::t120() { GET_REG(TMC2208_n, t120); } bool TMC2208Stepper::t143() { GET_REG(TMC2208_n, t143); } bool TMC2208Stepper::t150() { GET_REG(TMC2208_n, t150); } bool TMC2208Stepper::t157() { GET_REG(TMC2208_n, t157); } uint16_t TMC2208Stepper::cs_actual() { GET_REG(TMC2208_n, cs_actual); } bool TMC2208Stepper::stealth() { GET_REG(TMC2208_n, stealth); } bool TMC2208Stepper::stst() { GET_REG(TMC2208_n, stst); }
51.051282
89
0.692617
ManuelMcLure
7c7472c04ab1ade0a573cefb0c73da8759b41c18
5,786
hpp
C++
utility/common.hpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
utility/common.hpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
utility/common.hpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
// utility/common.hpp // // Copyright (c) 2007, 2008 Valentin Palade (vipalade @ gmail . com) // // This file is part of SolidFrame framework. // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt. // #ifndef UTILITY_COMMON_HPP #define UTILITY_COMMON_HPP #include "system/common.hpp" namespace solid{ template <typename T> inline T tmax(const T &v1, const T &v2){ return (v1 < v2) ? v2 : v1; } template <typename T> inline T tmin(const T &v1, const T &v2){ return (v1 > v2) ? v2 : v1; } //! A fast template inline function for exchanging values template <typename T> void exchange(T &a, T &b, T &tmp){ tmp = a; a = b; b = tmp; } //! A fast template inline function for exchanging values template <typename T> void exchange(T &a, T &b){ T tmp(a); a = b; b = tmp; } #if 0 bool overflow_safe_great(const uint32 _u1, const uint32 _u2){ if(_u1 > _u2){ return (_u1 - _u2) <= (uint32)(0xffffffff/2); }else{ return (_u2 - _u1) > (uint32)(0xffffffff/2); } } #endif inline bool overflow_safe_less(const uint32 &_u1, const uint32 &_u2){ if(_u1 < _u2){ return (_u2 - _u1) <= (uint32)(0xffffffff/2); }else{ return (_u1 - _u2) > (uint32)(0xffffffff/2); } } inline bool overflow_safe_less(const uint64 &_u1, const uint64 &_u2){ if(_u1 < _u2){ return (_u2 - _u1) <= ((uint64)-1)/2; }else{ return (_u1 - _u2) > ((uint64)-1)/2; } } inline uint32 overflow_safe_max(const uint32 &_u1, const uint32 &_u2){ if(overflow_safe_less(_u1, _u2)){ return _u2; }else{ return _u1; } } inline uint64 overflow_safe_max(const uint64 &_u1, const uint64 &_u2){ if(overflow_safe_less(_u1, _u2)){ return _u2; }else{ return _u1; } } template <typename T> inline T circular_distance(const T &_v, const T &_piv, const T& _max){ if(_v >= _piv){ return _v - _piv; }else{ return _max - _piv + _v; } } inline size_t padding_size(const size_t _sz, const size_t _pad){ return ((_sz / _pad) + 1) * _pad; } inline size_t fast_padding_size(const size_t _sz, const size_t _bitpad){ return ((_sz >> _bitpad) + 1) << _bitpad; } uint8 bit_count(const uint8 _v); uint16 bit_count(const uint16 _v); uint32 bit_count(const uint32 _v); uint64 bit_count(const uint64 _v); template <typename T> struct CRCValue; template<> struct CRCValue<uint64>{ static CRCValue<uint64> check_and_create(uint64 _v); static bool check(uint64 _v); static const uint64 maximum(){ return (1ULL << 58) - 1ULL; } CRCValue(uint64 _v); CRCValue(const CRCValue<uint64> &_v):v(_v.v){} bool ok()const{ return v != (uint64)-1; } const uint64 value()const{ return v >> 6; } const uint64 crc()const{ return v & ((1ULL << 6) - 1); } operator uint64()const{ return v; } private: CRCValue(uint64 _v, bool):v(_v){} const uint64 v; }; template<> struct CRCValue<uint32>{ static CRCValue<uint32> check_and_create(uint32 _v); static bool check(uint32 _v); static const uint32 maximum(){ return (1UL << 27) - 1UL; } CRCValue(uint32 _v); CRCValue(const CRCValue<uint32> &_v):v(_v.v){} bool ok()const{ return v != (uint32)-1; } uint32 value()const{ //return v & ((1UL << 27) - 1); return v >> 5; } uint32 crc()const{ //return v >> 27; return v & ((1UL << 5) - 1); } operator uint32()const{ return v; } private: CRCValue(uint32 _v, bool):v(_v){} const uint32 v; }; template<> struct CRCValue<uint16>{ static CRCValue<uint16> check_and_create(uint16 _v); static bool check(uint16 _v); static const uint16 maximum(){ return ((1 << 12) - 1); } CRCValue(uint16 _idx); CRCValue(const CRCValue<uint16> &_v):v(_v.v){} bool ok()const{ return v != (uint16)-1; } uint16 value()const{ //return v & ((1 << 12) - 1); return v >> 4; } uint16 crc()const{ //return v >> 12; return v & ((1 << 4) - 1); } operator uint16()const{ return v; } private: CRCValue(uint16 _v, bool):v(_v){} const uint16 v; }; template<> struct CRCValue<uint8>{ static CRCValue<uint8> check_and_create(uint8 _v); static bool check(uint8 _v); static const uint8 maximum(){ return ((1 << 5) - 1); } CRCValue(uint8 _idx); CRCValue(const CRCValue<uint8> &_v):v(_v.v){} bool ok()const{ return v != (uint8)-1; } uint8 value()const{ //return v & ((1 << 5) - 1); return v >> 3; } uint8 crc()const{ //return v >> 5; return v & ((1 << 3) - 1); } operator uint8()const{ return v; } private: CRCValue(uint8 _v, bool):v(_v){} const uint8 v; }; template <int N> struct NumberType{ enum{ Number = N }; }; inline void pack(uint32 &_v, const uint16 _v1, const uint16 _v2){ _v = _v2; _v <<= 16; _v |= _v1; } inline uint32 pack(const uint16 _v1, const uint16 _v2){ uint32 v; pack(v, _v1, _v2); return v; } inline void unpack(uint16 &_v1, uint16 &_v2, const uint32 _v){ _v1 = _v & 0xffffUL; _v2 = (_v >> 16) & 0xffffUL; } extern const uint8 reverted_chars[]; inline uint32 bit_revert(const uint32 _v){ uint32 r = (((uint32)reverted_chars[_v & 0xff]) << 24); r |= (((uint32)reverted_chars[(_v >> 8) & 0xff]) << 16); r |= (((uint32)reverted_chars[(_v >> 16) & 0xff]) << 8); r |= (((uint32)reverted_chars[(_v >> 24) & 0xff]) << 0); return r; } inline uint64 bit_revert(const uint64 _v){ uint64 r = (((uint64)reverted_chars[_v & 0xff]) << 56); r |= (((uint64)reverted_chars[(_v >> 8) & 0xff]) << 48); r |= (((uint64)reverted_chars[(_v >> 16) & 0xff]) << 40); r |= (((uint64)reverted_chars[(_v >> 24) & 0xff]) << 32); r |= (((uint64)reverted_chars[(_v >> 32) & 0xff]) << 24); r |= (((uint64)reverted_chars[(_v >> 40) & 0xff]) << 16); r |= (((uint64)reverted_chars[(_v >> 48) & 0xff]) << 8); r |= (((uint64)reverted_chars[(_v >> 56) & 0xff]) << 0); return r; } }//namespace solid #endif
20.230769
89
0.636709
joydit
7c7a0027366c78fc4135120f217b0a26563d406d
1,243
hpp
C++
src/details/std_includes.hpp
spanishgum/leetcode-driver
71883bcdca946684133fbf263a1186f1758ef594
[ "MIT" ]
null
null
null
src/details/std_includes.hpp
spanishgum/leetcode-driver
71883bcdca946684133fbf263a1186f1758ef594
[ "MIT" ]
null
null
null
src/details/std_includes.hpp
spanishgum/leetcode-driver
71883bcdca946684133fbf263a1186f1758ef594
[ "MIT" ]
null
null
null
#ifndef LEET_STD_INCLUDES #define LEET_STD_INCLUDES // Utilities #include <any> #include <bitset> #include <chrono> #include <cstddef> #include <cstdlib> #include <ctime> #include <functional> #include <initializer_list> #include <optional> #include <tuple> #include <utility> #include <variant> // Numeric limits #include <cfloat> #include <cinttypes> #include <climits> #include <cstdint> #include <limits> // Strings #include <cctype> #include <cstring> #include <string> #include <string_view> // Containers #include <array> #include <deque> #include <forward_list> #include <list> #include <map> #include <queue> #include <set> #include <stack> #include <unordered_map> #include <unordered_set> #include <vector> // Iterators #include <iterator> // Algorithms #include <algorithm> // Numerics #include <cfenv> #include <cmath> #include <complex> #include <numeric> #include <random> #include <ratio> #include <valarray> // I/O #include <cstdio> #include <iomanip> #include <iostream> #include <sstream> #include <streambuf> // Regex #include <regex> // Atomic #include <atomic> // Threading #include <condition_variable> #include <future> #include <mutex> #include <shared_mutex> #include <thread> using namespace std; #endif
15.345679
29
0.730491
spanishgum
7c7a08c9852c8e5c95ae138d13b55f428b9d6967
1,198
cpp
C++
LeetCode/Tag/Tree/cpp/1026.maximum-difference-between-node-and-ancestor.cpp
pakosel/competitive-coding-problems
187a2f13725e06ab3301ae2be37f16fbec0c0588
[ "MIT" ]
17
2017-08-12T14:42:46.000Z
2022-02-26T16:35:44.000Z
LeetCode/Tag/Tree/cpp/1026.maximum-difference-between-node-and-ancestor.cpp
pakosel/competitive-coding-problems
187a2f13725e06ab3301ae2be37f16fbec0c0588
[ "MIT" ]
21
2019-09-20T07:06:27.000Z
2021-11-02T10:30:50.000Z
LeetCode/Tag/Tree/cpp/1026.maximum-difference-between-node-and-ancestor.cpp
pakosel/competitive-coding-problems
187a2f13725e06ab3301ae2be37f16fbec0c0588
[ "MIT" ]
21
2017-05-28T10:15:07.000Z
2021-07-20T07:19:58.000Z
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { int V = 0; void updateChildrenMinMax(TreeNode* root, int& siblingMin, int& siblingMax) { if (!root) { return; } int minChild = 1e5 + 1, maxChild = -1; updateChildrenMinMax(root->left, minChild, maxChild); updateChildrenMinMax(root->right, minChild, maxChild); if (maxChild > -1) { int diff = max(abs(root->val - maxChild), abs(root->val - minChild)); if (V < diff) { V = diff; } } siblingMin = min(siblingMin, min(root->val, minChild)); siblingMax = max(siblingMax, max(root->val, maxChild)); } public: int maxAncestorDiff(TreeNode* root) { int minChild = 1e5 + 1, maxChild = -1; updateChildrenMinMax(root, minChild, maxChild); return V; } };
31.526316
93
0.558431
pakosel
7c7a1d21ea3255ef6f49069dd2d2f724ec0f54d9
474
cpp
C++
Source/Pickup/BodyPickup.cpp
thatguyabass/Kill-O-Byte-Source
0d4dfea226514161bb9799f55359f91da0998256
[ "Apache-2.0" ]
2
2016-12-13T19:13:10.000Z
2017-08-14T04:46:52.000Z
Source/Pickup/BodyPickup.cpp
thatguyabass/Kill-O-Byte-Source
0d4dfea226514161bb9799f55359f91da0998256
[ "Apache-2.0" ]
null
null
null
Source/Pickup/BodyPickup.cpp
thatguyabass/Kill-O-Byte-Source
0d4dfea226514161bb9799f55359f91da0998256
[ "Apache-2.0" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "Snake_Project.h" #include "BodyPickup.h" #include "SnakeCharacter/SnakeLink.h" ABodyPickup::ABodyPickup(const class FObjectInitializer& PCIP) : Super(PCIP) { BodyCount = 1; PrimaryActorTick.bCanEverTick = true; } void ABodyPickup::GiveTo(ASnakeLink* Link) { for (int32 c = 0; c < BodyCount; c++) { //Link->SpawnBody(); } bCollected = true; OnRep_Collected(bCollected); }
19.75
78
0.729958
thatguyabass
75a984de4827742461d2830e303d1937594eb911
181
cpp
C++
src/musl/setsid.cpp
jaeh/IncludeOS
1cc2bcf36758ff5ef3099e0c0c1ee55f0bb1de02
[ "Apache-2.0" ]
3,673
2015-12-01T22:14:02.000Z
2019-03-22T03:07:20.000Z
src/musl/setsid.cpp
jaeh/IncludeOS
1cc2bcf36758ff5ef3099e0c0c1ee55f0bb1de02
[ "Apache-2.0" ]
960
2015-12-01T20:40:36.000Z
2019-03-22T13:21:21.000Z
src/musl/setsid.cpp
AndreasAakesson/IncludeOS
891b960a0a7473c08cd0d93a2bba7569c6d88b48
[ "Apache-2.0" ]
357
2015-12-02T09:32:50.000Z
2019-03-22T09:32:34.000Z
#include "common.hpp" #include <sys/types.h> #include <unistd.h> long sys_setsid() { return 0; } extern "C" long syscall_SYS_setsid() { return strace(sys_setsid, "setsid"); }
12.066667
38
0.685083
jaeh
75aca9ce130ac4b59f5fa9339df6ad748481735b
1,623
cpp
C++
tests/madoka/topic.cpp
cre-ne-jp/irclog2json
721f9c6f247ae9d972dff8c1b3befa36bb1e062e
[ "MIT" ]
null
null
null
tests/madoka/topic.cpp
cre-ne-jp/irclog2json
721f9c6f247ae9d972dff8c1b3befa36bb1e062e
[ "MIT" ]
8
2019-08-26T22:57:37.000Z
2021-09-11T17:35:50.000Z
tests/madoka/topic.cpp
cre-ne-jp/irclog2json
721f9c6f247ae9d972dff8c1b3befa36bb1e062e
[ "MIT" ]
null
null
null
#define _XOPEN_SOURCE #include <doctest/doctest.h> #include <ctime> #include <picojson.h> #include "message/madoka_line_parser.h" #include "message/message_base.h" #include "tests/test_helper.h" TEST_CASE("Madoka TOPIC") { using irclog2json::message::MadokaLineParser; struct tm tm_date {}; strptime("1999-02-21", "%F", &tm_date); MadokaLineParser parser{"kataribe", tm_date}; const auto m = parser.ToMessage("00:38:04 Topic of channel #kataribe by sf: " "創作TRPG語り部関係雑談:質問者・相談者歓迎(MLに全転送)"); REQUIRE(m); const auto o = m->ToJsonObject(); SUBCASE("type") { CHECK_OBJ_STR_EQ(o, "type", "TOPIC"); } SUBCASE("channel") { CHECK_OBJ_STR_EQ(o, "channel", "kataribe"); } SUBCASE("timestamp") { CHECK_OBJ_STR_EQ(o, "timestamp", "1999-02-21 00:38:04 +0900"); } SUBCASE("nick") { CHECK_OBJ_STR_EQ(o, "nick", "sf"); } SUBCASE("message") { CHECK_OBJ_STR_EQ(o, "message", "創作TRPG語り部関係雑談:質問者・相談者歓迎(MLに全転送)"); } } TEST_CASE("Madoka TOPIC containing mIRC codes") { using irclog2json::message::MadokaLineParser; struct tm tm_date {}; strptime("1999-02-21", "%F", &tm_date); MadokaLineParser parser{"kataribe", tm_date}; const auto m = parser.ToMessage( "00:38:04 Topic of channel #kataribe by sf: " "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0B\x0C\x0E\x0F" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F" "通常の文字"); REQUIRE(m); const auto o = m->ToJsonObject(); CHECK_OBJ_STR_EQ(o, "message", "\x02\x03\x04\x0F\x11\x16\x1D\x1E\x1F通常の文字"); }
22.232877
72
0.637708
cre-ne-jp
75b8fcfd7bc4f73455647918ce2b8430faf484ec
38
hpp
C++
include/minsoo/fracbit/fixed30_2.hpp
RatkoFri/minsoo_caffe
be68b7ad0006d6145d6629eeb5b65cf3dd8b7437
[ "BSD-2-Clause" ]
1
2020-10-19T10:17:39.000Z
2020-10-19T10:17:39.000Z
include/minsoo/fracbit/fixed30_2.hpp
RatkoFri/minsoo_caffe
be68b7ad0006d6145d6629eeb5b65cf3dd8b7437
[ "BSD-2-Clause" ]
null
null
null
include/minsoo/fracbit/fixed30_2.hpp
RatkoFri/minsoo_caffe
be68b7ad0006d6145d6629eeb5b65cf3dd8b7437
[ "BSD-2-Clause" ]
1
2021-11-15T08:39:10.000Z
2021-11-15T08:39:10.000Z
#define INTBITS 30 #define FRACBITS 2
12.666667
18
0.789474
RatkoFri
75bbf795200ee302081f4ab835ab59176362c83d
461
hpp
C++
engine/utility/type/Color.hpp
zhec9/nemo
b719b89933ce722a14355e7ed825a76dea680501
[ "MIT" ]
null
null
null
engine/utility/type/Color.hpp
zhec9/nemo
b719b89933ce722a14355e7ed825a76dea680501
[ "MIT" ]
null
null
null
engine/utility/type/Color.hpp
zhec9/nemo
b719b89933ce722a14355e7ed825a76dea680501
[ "MIT" ]
null
null
null
#pragma once #include <SFML/Graphics/Color.hpp> namespace nemo { struct BorderColor { sf::Color v_; }; struct BackgroundColor { sf::Color v_; }; struct TextColor { sf::Color v_; }; struct TextBoxColors { BorderColor border_; BackgroundColor backgnd_; TextColor text_; TextBoxColors(const BorderColor border, const BackgroundColor backgnd, const TextColor text) : border_ (border) , backgnd_(backgnd) , text_ (text) { } }; }
13.171429
72
0.696312
zhec9
75bd90ce5ea5c0489bee31cb9146d845703813bf
1,736
hpp
C++
include/Map.hpp
sarahkittyy/raycasting-3d-test
7c2c849bafd4156ce66819ed89afe24aeb570503
[ "MIT" ]
null
null
null
include/Map.hpp
sarahkittyy/raycasting-3d-test
7c2c849bafd4156ce66819ed89afe24aeb570503
[ "MIT" ]
null
null
null
include/Map.hpp
sarahkittyy/raycasting-3d-test
7c2c849bafd4156ce66819ed89afe24aeb570503
[ "MIT" ]
null
null
null
#pragma once #include <SFML/Graphics.hpp> #include <fstream> #include <iostream> #include <string> #include <vector> #include "nlohmann/json.hpp" #include "Line.hpp" /** * @brief Drawable map class, consisting of lines strewn around the screen. * */ class Map : public sf::Drawable { public: /** * @brief Construct the map * */ Map(); /** * @brief Load the map from given json filename * * @param fname The path to the map json file */ void loadFromJson(std::string fname); /** * @brief Push a new line to the map. * * @param a Pt A * @param b Pt B * @param color The line color * * @returns A constant pointer to the created line */ Line* pushLine(sf::Vector2f a, sf::Vector2f b, sf::Color color = sf::Color::White); /** * @brief Casts a ray from the given point, with the given angle. * * @param pt1 The point of origin for the ray. * @param theta The angle at which the ray is sent at. * @param max The maximum ray distance. * * @return sf::Vector2f The point of intersection of the ray on the map's lines, or the initial point if no intersection was found. */ sf::Vector2f castRay(sf::Vector2f pt1, double theta, float max); private: /** * @brief SFML's draw() override. * */ virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const; /** * @brief The map vertex array. * * @remarks NEVER DIRECTLY MODIFY THIS * USE Line::bind()!! * */ sf::VertexArray mVertices; /** * @brief The main vector of lines. * */ std::vector<Line> mLines; //RAYCASTING METHODS /** * @brief Convert degrees to radians * */ constexpr float toRad(float deg) { return deg * 3.14159265358979 / 180; } };
19.288889
132
0.640553
sarahkittyy
75c031dc828206695086c835452e2c652e519b04
732
cpp
C++
various/STL/remove.cpp
chgogos/oop
3b0e6bbd29a76f863611e18d082913f080b1b571
[ "MIT" ]
14
2019-04-23T13:45:10.000Z
2022-03-12T18:26:47.000Z
various/STL/remove.cpp
chgogos/oop
3b0e6bbd29a76f863611e18d082913f080b1b571
[ "MIT" ]
null
null
null
various/STL/remove.cpp
chgogos/oop
3b0e6bbd29a76f863611e18d082913f080b1b571
[ "MIT" ]
9
2019-09-01T15:17:45.000Z
2020-11-13T20:31:36.000Z
// remove, remove_if, erase #include <iostream> #include <vector> using namespace std; void print_vector(vector<int> v){ for_each(begin(v), end(v), [](int x){cout << x << " ";}); cout << endl; } int main() { vector<int> v{1,2,3,4,5,2,3,2}; auto mark = remove(begin(v), end(v), 2); print_vector(v); v.erase(mark, end(v)); print_vector(v); // erase και remove σε 1 γραμμή v = {1,2,3,4,5,2,3,2}; v.erase(remove(begin(v), end(v), 2), end(v)); print_vector(v); // διαγραφή όλων των περιττών τιμών v = {1,2,3,4,5,2,3,2}; v.erase(remove_if(begin(v), end(v), [](int x){return x%2==1;}), end(v)); print_vector(v); } /* 1 3 4 5 3 2 3 2 1 3 4 5 3 1 3 4 5 3 2 4 2 2 */
19.263158
76
0.54918
chgogos
75c18c6cd22c7100d9932b21c1e61c08c544bc5d
880
cpp
C++
1SST/7LW/7task_6.cpp
AVAtarMod/University
3c784a1e109b7a6f6ea495278ec3dc126258625a
[ "BSD-3-Clause" ]
1
2021-07-31T06:55:08.000Z
2021-07-31T06:55:08.000Z
1SST/7LW/7task_6.cpp
AVAtarMod/University-C
e516aac99eabbcbe14d897239f08acf6c8e146af
[ "BSD-3-Clause" ]
1
2020-11-25T12:00:11.000Z
2021-01-13T08:51:52.000Z
1SST/7LW/7task_6.cpp
AVAtarMod/University-C
e516aac99eabbcbe14d897239f08acf6c8e146af
[ "BSD-3-Clause" ]
null
null
null
// Даны два натуральных числа A и B (A < B). Написать функцию, выводящую все числа из диапазона [A; B], которые делятся на свою наибольшую цифру. Для поиск наибольшей цифры числа реализовать отдельную функцию #include <iostream> int maxDigitInNumber(int number); int main(){ printf("\n\nВведите А и B через пробел: "); int a,b; scanf("%d %d",&a,&b); printf("Числа, соответсвующие условиям: "); for (; a <= b; a++) if (a%maxDigitInNumber(a) == 0) printf(" %d",a); printf("\n"); return 0; } int maxDigitInNumber(int number){ int maxDigitInNumber; for (int previousDigit=0; number > 0; number /= 10) { int currentDigit = number%10; if (currentDigit > previousDigit){ previousDigit = currentDigit; maxDigitInNumber = currentDigit; } } return maxDigitInNumber; }
27.5
209
0.619318
AVAtarMod
75c8031474bb28baf1f6f513faa409feaf1487f2
3,255
cxx
C++
panda/src/pgui/pgMouseWatcherBackground.cxx
kestred/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
3
2018-03-09T12:07:29.000Z
2021-02-25T06:50:25.000Z
panda/src/pgui/pgMouseWatcherBackground.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
panda/src/pgui/pgMouseWatcherBackground.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
// Filename: pgMouseWatcherBackground.cxx // Created by: drose (23Aug01) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include "pgMouseWatcherBackground.h" #include "pgItem.h" TypeHandle PGMouseWatcherBackground::_type_handle; //////////////////////////////////////////////////////////////////// // Function: PGMouseWatcherBackground::Constructor // Access: Public // Description: //////////////////////////////////////////////////////////////////// PGMouseWatcherBackground:: PGMouseWatcherBackground() : MouseWatcherRegion("PGMouseWatcherBackground", 0, 0, 0, 0) { set_active(false); set_keyboard(true); } //////////////////////////////////////////////////////////////////// // Function: PGMouseWatcherBackground::Destructor // Access: Public, Virtual // Description: //////////////////////////////////////////////////////////////////// PGMouseWatcherBackground:: ~PGMouseWatcherBackground() { } //////////////////////////////////////////////////////////////////// // Function: PGMouseWatcherBackground::press // Access: Public, Virtual // Description: This is a callback hook function, called whenever a // mouse or keyboard button is depressed while the mouse // is within the background. //////////////////////////////////////////////////////////////////// void PGMouseWatcherBackground:: press(const MouseWatcherParameter &param) { PGItem::background_press(param); } //////////////////////////////////////////////////////////////////// // Function: PGMouseWatcherBackground::release // Access: Public, Virtual // Description: This is a callback hook function, called whenever a // mouse or keyboard button previously depressed with // press() is released. //////////////////////////////////////////////////////////////////// void PGMouseWatcherBackground:: release(const MouseWatcherParameter &param) { PGItem::background_release(param); } //////////////////////////////////////////////////////////////////// // Function: PGMouseWatcherBackground::keystroke // Access: Public, Virtual // Description: This is a callback hook function, called whenever // the user presses a key. //////////////////////////////////////////////////////////////////// void PGMouseWatcherBackground:: keystroke(const MouseWatcherParameter &param) { PGItem::background_keystroke(param); } //////////////////////////////////////////////////////////////////// // Function: PGMouseWatcherBackground::candidate // Access: Public, Virtual // Description: This is a callback hook function, called whenever // the user uses the IME. //////////////////////////////////////////////////////////////////// void PGMouseWatcherBackground:: candidate(const MouseWatcherParameter &param) { PGItem::background_candidate(param); }
37.413793
70
0.508449
kestred
75c96a3527e78516d556343142cffc8d07fe920e
44,190
cc
C++
release/src-rt-6.x.4708/router/mysql/storage/myisammrg/ha_myisammrg.cc
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
278
2015-11-03T03:01:20.000Z
2022-01-20T18:21:05.000Z
release/src-rt-6.x.4708/router/mysql/storage/myisammrg/ha_myisammrg.cc
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
374
2015-11-03T12:37:22.000Z
2021-12-17T14:18:08.000Z
release/src-rt-6.x.4708/router/mysql/storage/myisammrg/ha_myisammrg.cc
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
96
2015-11-22T07:47:26.000Z
2022-01-20T19:52:19.000Z
/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* MyISAM MERGE tables A MyISAM MERGE table is kind of a union of zero or more MyISAM tables. Besides the normal form file (.frm) a MERGE table has a meta file (.MRG) with a list of tables. These are paths to the MyISAM table files. The last two components of the path contain the database name and the table name respectively. When a MERGE table is open, there exists an TABLE object for the MERGE table itself and a TABLE object for each of the MyISAM tables. For abbreviated writing, I call the MERGE table object "parent" and the MyISAM table objects "children". A MERGE table is almost always opened through open_and_lock_tables() and hence through open_tables(). When the parent appears in the list of tables to open, the initial open of the handler does nothing but read the meta file and collect a list of TABLE_LIST objects for the children. This list is attached to the parent TABLE object as TABLE::child_l. The end of the children list is saved in TABLE::child_last_l. Back in open_tables(), add_merge_table_list() is called. It updates each list member with the lock type and a back pointer to the parent TABLE_LIST object TABLE_LIST::parent_l. The list is then inserted in the list of tables to open, right behind the parent. Consequently, open_tables() opens the children, one after the other. The TABLE references of the TABLE_LIST objects are implicitly set to the open tables. The children are opened as independent MyISAM tables, right as if they are used by the SQL statement. TABLE_LIST::parent_l is required to find the parent 1. when the last child has been opened and children are to be attached, and 2. when an error happens during child open and the child list must be removed from the queuery list. In these cases the current child does not have TABLE::parent set or does not have a TABLE at all respectively. When the last child is open, attach_merge_children() is called. It removes the list of children from the open list. Then the children are "attached" to the parent. All required references between parent and children are set up. The MERGE storage engine sets up an array with references to the low-level MyISAM table objects (MI_INFO). It remembers the state of the table in MYRG_INFO::children_attached. Every child TABLE::parent references the parent TABLE object. That way TABLE objects belonging to a MERGE table can be identified. TABLE::parent is required because the parent and child TABLE objects can live longer than the parent TABLE_LIST object. So the path child->pos_in_table_list->parent_l->table can be broken. If necessary, the compatibility of parent and children is checked. This check is necessary when any of the objects are reopend. This is detected by comparing the current table def version against the remembered child def version. On parent open, the list members are initialized to an "impossible"/"undefined" version value. So the check is always executed on the first attach. The version check is done in myisammrg_attach_children_callback(), which is called for every child. ha_myisammrg::attach_children() initializes 'need_compat_check' to FALSE and myisammrg_attach_children_callback() sets it ot TRUE if a table def version mismatches the remembered child def version. Finally the parent TABLE::children_attached is set. --- On parent open the storage engine structures are allocated and initialized. They stay with the open table until its final close. */ #ifdef USE_PRAGMA_IMPLEMENTATION #pragma implementation // gcc: Class implementation #endif #define MYSQL_SERVER 1 #include "mysql_priv.h" #include <mysql/plugin.h> #include <m_ctype.h> #include "../myisam/ha_myisam.h" #include "ha_myisammrg.h" #include "myrg_def.h" static handler *myisammrg_create_handler(handlerton *hton, TABLE_SHARE *table, MEM_ROOT *mem_root) { return new (mem_root) ha_myisammrg(hton, table); } /** @brief Constructor */ ha_myisammrg::ha_myisammrg(handlerton *hton, TABLE_SHARE *table_arg) :handler(hton, table_arg), file(0), is_cloned(0) {} /** @brief Destructor */ ha_myisammrg::~ha_myisammrg(void) {} static const char *ha_myisammrg_exts[] = { ".MRG", NullS }; extern int table2myisam(TABLE *table_arg, MI_KEYDEF **keydef_out, MI_COLUMNDEF **recinfo_out, uint *records_out); extern int check_definition(MI_KEYDEF *t1_keyinfo, MI_COLUMNDEF *t1_recinfo, uint t1_keys, uint t1_recs, MI_KEYDEF *t2_keyinfo, MI_COLUMNDEF *t2_recinfo, uint t2_keys, uint t2_recs, bool strict, TABLE *table_arg); static void split_file_name(const char *file_name, LEX_STRING *db, LEX_STRING *name); extern "C" void myrg_print_wrong_table(const char *table_name) { LEX_STRING db= {NULL, 0}, name; char buf[FN_REFLEN]; split_file_name(table_name, &db, &name); memcpy(buf, db.str, db.length); buf[db.length]= '.'; memcpy(buf + db.length + 1, name.str, name.length); buf[db.length + name.length + 1]= 0; push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_ERROR, ER_ADMIN_WRONG_MRG_TABLE, ER(ER_ADMIN_WRONG_MRG_TABLE), buf); } const char **ha_myisammrg::bas_ext() const { return ha_myisammrg_exts; } const char *ha_myisammrg::index_type(uint key_number) { return ((table->key_info[key_number].flags & HA_FULLTEXT) ? "FULLTEXT" : (table->key_info[key_number].flags & HA_SPATIAL) ? "SPATIAL" : (table->key_info[key_number].algorithm == HA_KEY_ALG_RTREE) ? "RTREE" : "BTREE"); } /** @brief Callback function for open of a MERGE parent table. @detail This function adds a TABLE_LIST object for a MERGE child table to a list of tables of the parent TABLE object. It is called for each child table. The list of child TABLE_LIST objects is kept in the TABLE object of the parent for the whole life time of the MERGE table. It is inserted in the statement list behind the MERGE parent TABLE_LIST object when the MERGE table is opened. It is removed from the statement list after the last child is opened. All memeory used for the child TABLE_LIST objects and the strings referred by it are taken from the parent TABLE::mem_root. Thus they are all freed implicitly at the final close of the table. TABLE::child_l -> TABLE_LIST::next_global -> TABLE_LIST::next_global # # ^ # ^ # # | # | # # +--------- TABLE_LIST::prev_global # # | # |<--- TABLE_LIST::prev_global | # | TABLE::child_last_l -----------------------------------------+ @param[in] callback_param data pointer as given to myrg_parent_open() @param[in] filename file name of MyISAM table without extension. @return status @retval 0 OK @retval != 0 Error */ static int myisammrg_parent_open_callback(void *callback_param, const char *filename) { ha_myisammrg *ha_myrg= (ha_myisammrg*) callback_param; TABLE *parent= ha_myrg->table_ptr(); TABLE_LIST *child_l; size_t dirlen; char dir_path[FN_REFLEN]; char name_buf[NAME_LEN]; DBUG_ENTER("myisammrg_parent_open_callback"); /* Get a TABLE_LIST object. */ if (!(child_l= (TABLE_LIST*) alloc_root(&parent->mem_root, sizeof(TABLE_LIST)))) { /* purecov: begin inspected */ DBUG_PRINT("error", ("my_malloc error: %d", my_errno)); DBUG_RETURN(1); /* purecov: end */ } bzero((char*) child_l, sizeof(TABLE_LIST)); /* Depending on MySQL version, filename may be encoded by table name to file name encoding or not. Always encoded if parent table is created by 5.1.46+. Encoded if parent is created by 5.1.6+ and child table is in different database. */ if (!has_path(filename)) { /* Child is in the same database as parent. */ child_l->db_length= parent->s->db.length; child_l->db= strmake_root(&parent->mem_root, parent->s->db.str, child_l->db_length); /* Child table name is encoded in parent dot-MRG starting with 5.1.46. */ if (parent->s->mysql_version >= 50146) { child_l->table_name_length= filename_to_tablename(filename, name_buf, sizeof(name_buf)); child_l->table_name= strmake_root(&parent->mem_root, name_buf, child_l->table_name_length); } else { child_l->table_name_length= strlen(filename); child_l->table_name= strmake_root(&parent->mem_root, filename, child_l->table_name_length); } } else { DBUG_ASSERT(strlen(filename) < sizeof(dir_path)); fn_format(dir_path, filename, "", "", 0); /* Extract child table name and database name from filename. */ dirlen= dirname_length(dir_path); /* Child db/table name is encoded in parent dot-MRG starting with 5.1.6. */ if (parent->s->mysql_version >= 50106) { child_l->table_name_length= filename_to_tablename(dir_path + dirlen, name_buf, sizeof(name_buf)); child_l->table_name= strmake_root(&parent->mem_root, name_buf, child_l->table_name_length); dir_path[dirlen - 1]= 0; dirlen= dirname_length(dir_path); child_l->db_length= filename_to_tablename(dir_path + dirlen, name_buf, sizeof(name_buf)); child_l->db= strmake_root(&parent->mem_root, name_buf, child_l->db_length); } else { child_l->table_name_length= strlen(dir_path + dirlen); child_l->table_name= strmake_root(&parent->mem_root, dir_path + dirlen, child_l->table_name_length); dir_path[dirlen - 1]= 0; dirlen= dirname_length(dir_path); child_l->db_length= strlen(dir_path + dirlen); child_l->db= strmake_root(&parent->mem_root, dir_path + dirlen, child_l->db_length); } } DBUG_PRINT("myrg", ("open: '%.*s'.'%.*s'", (int) child_l->db_length, child_l->db, (int) child_l->table_name_length, child_l->table_name)); /* Convert to lowercase if required. */ if (lower_case_table_names && child_l->table_name_length) child_l->table_name_length= my_casedn_str(files_charset_info, child_l->table_name); /* Set alias. */ child_l->alias= child_l->table_name; /* Initialize table map to 'undefined'. */ child_l->init_child_def_version(); /* Link TABLE_LIST object into the parent list. */ if (!parent->child_last_l) { /* Initialize parent->child_last_l when handling first child. */ parent->child_last_l= &parent->child_l; } *parent->child_last_l= child_l; child_l->prev_global= parent->child_last_l; parent->child_last_l= &child_l->next_global; DBUG_RETURN(0); } /** @brief Callback function for attaching a MERGE child table. @detail This function retrieves the MyISAM table handle from the next child table. It is called for each child table. @param[in] callback_param data pointer as given to myrg_attach_children() @return pointer to open MyISAM table structure @retval !=NULL OK, returning pointer @retval NULL, my_errno == 0 Ok, no more child tables @retval NULL, my_errno != 0 error */ static MI_INFO *myisammrg_attach_children_callback(void *callback_param) { ha_myisammrg *ha_myrg; TABLE *parent; TABLE *child; TABLE_LIST *child_l; MI_INFO *UNINIT_VAR(myisam); DBUG_ENTER("myisammrg_attach_children_callback"); my_errno= 0; ha_myrg= (ha_myisammrg*) callback_param; parent= ha_myrg->table_ptr(); /* Get child list item. */ child_l= ha_myrg->next_child_attach; if (!child_l) { DBUG_PRINT("myrg", ("No more children to attach")); DBUG_RETURN(NULL); } child= child_l->table; DBUG_PRINT("myrg", ("child table: '%s'.'%s' 0x%lx", child->s->db.str, child->s->table_name.str, (long) child)); /* Prepare for next child. Used as child_l in next call to this function. We cannot rely on a NULL-terminated chain. */ if (&child_l->next_global == parent->child_last_l) { DBUG_PRINT("myrg", ("attaching last child")); ha_myrg->next_child_attach= NULL; } else ha_myrg->next_child_attach= child_l->next_global; /* Set parent reference. */ child->parent= parent; /* Do a quick compatibility check. The table def version is set when the table share is created. The child def version is copied from the table def version after a sucessful compatibility check. We need to repeat the compatibility check only if a child is opened from a different share than last time it was used with this MERGE table. */ DBUG_PRINT("myrg", ("table_def_version last: %lu current: %lu", (ulong) child_l->get_child_def_version(), (ulong) child->s->get_table_def_version())); if (child_l->get_child_def_version() != child->s->get_table_def_version()) ha_myrg->need_compat_check= TRUE; /* If parent is temporary, children must be temporary too and vice versa. This check must be done for every child on every open because the table def version can overlap between temporary and non-temporary tables. We need to detect the case where a non-temporary table has been replaced with a temporary table of the same version. Or vice versa. A very unlikely case, but it could happen. */ if (child->s->tmp_table != parent->s->tmp_table) { DBUG_PRINT("error", ("temporary table mismatch parent: %d child: %d", parent->s->tmp_table, child->s->tmp_table)); my_errno= HA_ERR_WRONG_MRG_TABLE_DEF; goto err; } /* Extract the MyISAM table structure pointer from the handler object. */ if ((child->file->ht->db_type != DB_TYPE_MYISAM) || !(myisam= ((ha_myisam*) child->file)->file_ptr())) { DBUG_PRINT("error", ("no MyISAM handle for child table: '%s'.'%s' 0x%lx", child->s->db.str, child->s->table_name.str, (long) child)); my_errno= HA_ERR_WRONG_MRG_TABLE_DEF; } DBUG_PRINT("myrg", ("MyISAM handle: 0x%lx my_errno: %d", my_errno ? 0L : (long) myisam, my_errno)); err: DBUG_RETURN(my_errno ? NULL : myisam); } /** @brief Open a MERGE parent table, not its children. @detail This function initializes the MERGE storage engine structures and adds a child list of TABLE_LIST to the parent TABLE. @param[in] name MERGE table path name @param[in] mode read/write mode, unused @param[in] test_if_locked_arg open flags @return status @retval 0 OK @retval -1 Error, my_errno gives reason */ int ha_myisammrg::open(const char *name, int mode __attribute__((unused)), uint test_if_locked_arg) { DBUG_ENTER("ha_myisammrg::open"); DBUG_PRINT("myrg", ("name: '%s' table: 0x%lx", name, (long) table)); DBUG_PRINT("myrg", ("test_if_locked_arg: %u", test_if_locked_arg)); /* Save for later use. */ test_if_locked= test_if_locked_arg; /* retrieve children table list. */ my_errno= 0; if (is_cloned) { /* Open and attaches the MyISAM tables,that are under the MERGE table parent, on the MyISAM storage engine interface directly within the MERGE engine. The new MyISAM table instances, as well as the MERGE clone itself, are not visible in the table cache. This is not a problem because all locking is handled by the original MERGE table from which this is cloned of. */ if (!(file= myrg_open(name, table->db_stat, HA_OPEN_IGNORE_IF_LOCKED))) { DBUG_PRINT("error", ("my_errno %d", my_errno)); DBUG_RETURN(my_errno ? my_errno : -1); } file->children_attached= TRUE; info(HA_STATUS_NO_LOCK | HA_STATUS_VARIABLE | HA_STATUS_CONST); } else if (!(file= myrg_parent_open(name, myisammrg_parent_open_callback, this))) { DBUG_PRINT("error", ("my_errno %d", my_errno)); DBUG_RETURN(my_errno ? my_errno : -1); } DBUG_PRINT("myrg", ("MYRG_INFO: 0x%lx", (long) file)); DBUG_RETURN(0); } /** Returns a cloned instance of the current handler. @return A cloned handler instance. */ handler *ha_myisammrg::clone(const char *name, MEM_ROOT *mem_root) { MYRG_TABLE *u_table,*newu_table; ha_myisammrg *new_handler= (ha_myisammrg*) get_new_handler(table->s, mem_root, table->s->db_type()); if (!new_handler) return NULL; /* Inform ha_myisammrg::open() that it is a cloned handler */ new_handler->is_cloned= TRUE; /* Allocate handler->ref here because otherwise ha_open will allocate it on this->table->mem_root and we will not be able to reclaim that memory when the clone handler object is destroyed. */ if (!(new_handler->ref= (uchar*) alloc_root(mem_root, ALIGN_SIZE(ref_length)*2))) { delete new_handler; return NULL; } if (new_handler->ha_open(table, name, table->db_stat, HA_OPEN_IGNORE_IF_LOCKED)) { delete new_handler; return NULL; } /* Iterate through the original child tables and copy the state into the cloned child tables. We need to do this because all the child tables can be involved in delete. */ newu_table= new_handler->file->open_tables; for (u_table= file->open_tables; u_table < file->end_table; u_table++) { newu_table->table->state= u_table->table->state; newu_table++; } return new_handler; } /** @brief Attach children to a MERGE table. @detail Let the storage engine attach its children through a callback function. Check table definitions for consistency. @note Special thd->open_options may be in effect. We can make use of them in attach. I.e. we use HA_OPEN_FOR_REPAIR to report the names of mismatching child tables. We cannot transport these options in ha_myisammrg::test_if_locked because they may change after the parent is opened. The parent is kept open in the table cache over multiple statements and can be used by other threads. Open options can change over time. @return status @retval 0 OK @retval != 0 Error, my_errno gives reason */ int ha_myisammrg::attach_children(void) { MYRG_TABLE *u_table; MI_COLUMNDEF *recinfo; MI_KEYDEF *keyinfo; uint recs; uint keys= table->s->keys; int error; DBUG_ENTER("ha_myisammrg::attach_children"); DBUG_PRINT("myrg", ("table: '%s'.'%s' 0x%lx", table->s->db.str, table->s->table_name.str, (long) table)); DBUG_PRINT("myrg", ("test_if_locked: %u", this->test_if_locked)); DBUG_ASSERT(!this->file->children_attached); /* Initialize variables that are used, modified, and/or set by myisammrg_attach_children_callback(). 'next_child_attach' traverses the chain of TABLE_LIST objects that has been compiled during myrg_parent_open(). Every call to myisammrg_attach_children_callback() moves the pointer to the next object. 'need_compat_check' is set by myisammrg_attach_children_callback() if a child fails the table def version check. 'my_errno' is set by myisammrg_attach_children_callback() in case of an error. */ next_child_attach= table->child_l; need_compat_check= FALSE; my_errno= 0; if (myrg_attach_children(this->file, this->test_if_locked | current_thd->open_options, myisammrg_attach_children_callback, this, (my_bool *) &need_compat_check)) { DBUG_PRINT("error", ("my_errno %d", my_errno)); DBUG_RETURN(my_errno ? my_errno : -1); } DBUG_PRINT("myrg", ("calling myrg_extrafunc")); myrg_extrafunc(file, query_cache_invalidate_by_MyISAM_filename_ref); if (!(test_if_locked == HA_OPEN_WAIT_IF_LOCKED || test_if_locked == HA_OPEN_ABORT_IF_LOCKED)) myrg_extra(file,HA_EXTRA_NO_WAIT_LOCK,0); info(HA_STATUS_NO_LOCK | HA_STATUS_VARIABLE | HA_STATUS_CONST); if (!(test_if_locked & HA_OPEN_WAIT_IF_LOCKED)) myrg_extra(file,HA_EXTRA_WAIT_LOCK,0); /* The compatibility check is required only if one or more children do not match their table def version from the last check. This will always happen at the first attach because the reference child def version is initialized to 'undefined' at open. */ DBUG_PRINT("myrg", ("need_compat_check: %d", need_compat_check)); if (need_compat_check) { TABLE_LIST *child_l; if (table->s->reclength != stats.mean_rec_length && stats.mean_rec_length) { DBUG_PRINT("error",("reclength: %lu mean_rec_length: %lu", table->s->reclength, stats.mean_rec_length)); if (test_if_locked & HA_OPEN_FOR_REPAIR) myrg_print_wrong_table(file->open_tables->table->filename); error= HA_ERR_WRONG_MRG_TABLE_DEF; goto err; } /* Both recinfo and keyinfo are allocated by my_multi_malloc(), thus only recinfo must be freed. */ if ((error= table2myisam(table, &keyinfo, &recinfo, &recs))) { /* purecov: begin inspected */ DBUG_PRINT("error", ("failed to convert TABLE object to MyISAM " "key and column definition")); goto err; /* purecov: end */ } for (u_table= file->open_tables; u_table < file->end_table; u_table++) { if (check_definition(keyinfo, recinfo, keys, recs, u_table->table->s->keyinfo, u_table->table->s->rec, u_table->table->s->base.keys, u_table->table->s->base.fields, false, NULL)) { DBUG_PRINT("error", ("table definition mismatch: '%s'", u_table->table->filename)); error= HA_ERR_WRONG_MRG_TABLE_DEF; if (!(this->test_if_locked & HA_OPEN_FOR_REPAIR)) { my_free((uchar*) recinfo, MYF(0)); goto err; } myrg_print_wrong_table(u_table->table->filename); } } my_free((uchar*) recinfo, MYF(0)); if (error == HA_ERR_WRONG_MRG_TABLE_DEF) goto err; /* All checks passed so far. Now update child def version. */ for (child_l= table->child_l; ; child_l= child_l->next_global) { child_l->set_child_def_version( child_l->table->s->get_table_def_version()); if (&child_l->next_global == table->child_last_l) break; } } #if !defined(BIG_TABLES) || SIZEOF_OFF_T == 4 /* Merge table has more than 2G rows */ if (table->s->crashed) { DBUG_PRINT("error", ("MERGE table marked crashed")); error= HA_ERR_WRONG_MRG_TABLE_DEF; goto err; } #endif DBUG_RETURN(0); err: myrg_detach_children(file); DBUG_RETURN(my_errno= error); } /** @brief Detach all children from a MERGE table. @note Detach must not touch the children in any way. They may have been closed at ths point already. All references to the children should be removed. @return status @retval 0 OK @retval != 0 Error, my_errno gives reason */ int ha_myisammrg::detach_children(void) { DBUG_ENTER("ha_myisammrg::detach_children"); DBUG_ASSERT(this->file && this->file->children_attached); if (myrg_detach_children(this->file)) { /* purecov: begin inspected */ DBUG_PRINT("error", ("my_errno %d", my_errno)); DBUG_RETURN(my_errno ? my_errno : -1); /* purecov: end */ } DBUG_RETURN(0); } /** @brief Close a MERGE parent table, not its children. @note The children are expected to be closed separately by the caller. @return status @retval 0 OK @retval != 0 Error, my_errno gives reason */ int ha_myisammrg::close(void) { int rc; DBUG_ENTER("ha_myisammrg::close"); /* Children must not be attached here. Unless the MERGE table has no children or the handler instance has been cloned. In these cases children_attached is always true. */ DBUG_ASSERT(!this->file->children_attached || !this->file->tables || this->is_cloned); rc= myrg_close(file); file= 0; DBUG_RETURN(rc); } int ha_myisammrg::write_row(uchar * buf) { DBUG_ENTER("ha_myisammrg::write_row"); DBUG_ASSERT(this->file->children_attached); ha_statistic_increment(&SSV::ha_write_count); if (file->merge_insert_method == MERGE_INSERT_DISABLED || !file->tables) DBUG_RETURN(HA_ERR_TABLE_READONLY); if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_INSERT) table->timestamp_field->set_time(); if (table->next_number_field && buf == table->record[0]) { int error; if ((error= update_auto_increment())) DBUG_RETURN(error); /* purecov: inspected */ } DBUG_RETURN(myrg_write(file,buf)); } int ha_myisammrg::update_row(const uchar * old_data, uchar * new_data) { DBUG_ASSERT(this->file->children_attached); ha_statistic_increment(&SSV::ha_update_count); if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_UPDATE) table->timestamp_field->set_time(); return myrg_update(file,old_data,new_data); } int ha_myisammrg::delete_row(const uchar * buf) { DBUG_ASSERT(this->file->children_attached); ha_statistic_increment(&SSV::ha_delete_count); return myrg_delete(file,buf); } int ha_myisammrg::index_read_map(uchar * buf, const uchar * key, key_part_map keypart_map, enum ha_rkey_function find_flag) { DBUG_ASSERT(this->file->children_attached); ha_statistic_increment(&SSV::ha_read_key_count); int error=myrg_rkey(file,buf,active_index, key, keypart_map, find_flag); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_myisammrg::index_read_idx_map(uchar * buf, uint index, const uchar * key, key_part_map keypart_map, enum ha_rkey_function find_flag) { DBUG_ASSERT(this->file->children_attached); ha_statistic_increment(&SSV::ha_read_key_count); int error=myrg_rkey(file,buf,index, key, keypart_map, find_flag); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_myisammrg::index_read_last_map(uchar *buf, const uchar *key, key_part_map keypart_map) { DBUG_ASSERT(this->file->children_attached); ha_statistic_increment(&SSV::ha_read_key_count); int error=myrg_rkey(file,buf,active_index, key, keypart_map, HA_READ_PREFIX_LAST); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_myisammrg::index_next(uchar * buf) { DBUG_ASSERT(this->file->children_attached); ha_statistic_increment(&SSV::ha_read_next_count); int error=myrg_rnext(file,buf,active_index); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_myisammrg::index_prev(uchar * buf) { DBUG_ASSERT(this->file->children_attached); ha_statistic_increment(&SSV::ha_read_prev_count); int error=myrg_rprev(file,buf, active_index); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_myisammrg::index_first(uchar * buf) { DBUG_ASSERT(this->file->children_attached); ha_statistic_increment(&SSV::ha_read_first_count); int error=myrg_rfirst(file, buf, active_index); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_myisammrg::index_last(uchar * buf) { DBUG_ASSERT(this->file->children_attached); ha_statistic_increment(&SSV::ha_read_last_count); int error=myrg_rlast(file, buf, active_index); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_myisammrg::index_next_same(uchar * buf, const uchar *key __attribute__((unused)), uint length __attribute__((unused))) { int error; DBUG_ASSERT(this->file->children_attached); ha_statistic_increment(&SSV::ha_read_next_count); do { error= myrg_rnext_same(file,buf); } while (error == HA_ERR_RECORD_DELETED); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_myisammrg::rnd_init(bool scan) { DBUG_ASSERT(this->file->children_attached); return myrg_reset(file); } int ha_myisammrg::rnd_next(uchar *buf) { DBUG_ASSERT(this->file->children_attached); ha_statistic_increment(&SSV::ha_read_rnd_next_count); int error=myrg_rrnd(file, buf, HA_OFFSET_ERROR); table->status=error ? STATUS_NOT_FOUND: 0; return error; } int ha_myisammrg::rnd_pos(uchar * buf, uchar *pos) { DBUG_ASSERT(this->file->children_attached); ha_statistic_increment(&SSV::ha_read_rnd_count); int error=myrg_rrnd(file, buf, my_get_ptr(pos,ref_length)); table->status=error ? STATUS_NOT_FOUND: 0; return error; } void ha_myisammrg::position(const uchar *record) { DBUG_ASSERT(this->file->children_attached); ulonglong row_position= myrg_position(file); my_store_ptr(ref, ref_length, (my_off_t) row_position); } ha_rows ha_myisammrg::records_in_range(uint inx, key_range *min_key, key_range *max_key) { DBUG_ASSERT(this->file->children_attached); return (ha_rows) myrg_records_in_range(file, (int) inx, min_key, max_key); } int ha_myisammrg::info(uint flag) { MYMERGE_INFO mrg_info; DBUG_ASSERT(this->file->children_attached); (void) myrg_status(file,&mrg_info,flag); /* The following fails if one has not compiled MySQL with -DBIG_TABLES and one has more than 2^32 rows in the merge tables. */ stats.records = (ha_rows) mrg_info.records; stats.deleted = (ha_rows) mrg_info.deleted; #if !defined(BIG_TABLES) || SIZEOF_OFF_T == 4 if ((mrg_info.records >= (ulonglong) 1 << 32) || (mrg_info.deleted >= (ulonglong) 1 << 32)) table->s->crashed= 1; #endif stats.data_file_length= mrg_info.data_file_length; if (mrg_info.errkey >= (int) table_share->keys) { /* If value of errkey is higher than the number of keys on the table set errkey to MAX_KEY. This will be treated as unknown key case and error message generator won't try to locate key causing segmentation fault. */ mrg_info.errkey= MAX_KEY; } table->s->keys_in_use.set_prefix(table->s->keys); stats.mean_rec_length= mrg_info.reclength; /* The handler::block_size is used all over the code in index scan cost calculations. It is used to get number of disk seeks required to retrieve a number of index tuples. If the merge table has N underlying tables, then (assuming underlying tables have equal size, the only "simple" approach we can use) retrieving X index records from a merge table will require N times more disk seeks compared to doing the same on a MyISAM table with equal number of records. In the edge case (file_tables > myisam_block_size) we'll get block_size==0, and index calculation code will act as if we need one disk seek to retrieve one index tuple. TODO: In 5.2 index scan cost calculation will be factored out into a virtual function in class handler and we'll be able to remove this hack. */ stats.block_size= 0; if (file->tables) stats.block_size= myisam_block_size / file->tables; stats.update_time= 0; #if SIZEOF_OFF_T > 4 ref_length=6; // Should be big enough #else ref_length=4; // Can't be > than my_off_t #endif if (flag & HA_STATUS_CONST) { if (table->s->key_parts && mrg_info.rec_per_key) { #ifdef HAVE_purify /* valgrind may be unhappy about it, because optimizer may access values between file->keys and table->key_parts, that will be uninitialized. It's safe though, because even if opimizer will decide to use a key with such a number, it'll be an error later anyway. */ bzero((char*) table->key_info[0].rec_per_key, sizeof(table->key_info[0].rec_per_key[0]) * table->s->key_parts); #endif memcpy((char*) table->key_info[0].rec_per_key, (char*) mrg_info.rec_per_key, sizeof(table->key_info[0].rec_per_key[0]) * min(file->keys, table->s->key_parts)); } } if (flag & HA_STATUS_ERRKEY) { errkey= mrg_info.errkey; my_store_ptr(dup_ref, ref_length, mrg_info.dupp_key_pos); } return 0; } int ha_myisammrg::extra(enum ha_extra_function operation) { if (operation == HA_EXTRA_ATTACH_CHILDREN) { int rc= attach_children(); if (!rc) (void) extra(HA_EXTRA_NO_READCHECK); // Not needed in SQL return(rc); } else if (operation == HA_EXTRA_DETACH_CHILDREN) { /* Note that detach must not touch the children in any way. They may have been closed at ths point already. */ int rc= detach_children(); return(rc); } /* As this is just a mapping, we don't have to force the underlying tables to be closed */ if (operation == HA_EXTRA_FORCE_REOPEN || operation == HA_EXTRA_PREPARE_FOR_DROP) return 0; return myrg_extra(file,operation,0); } int ha_myisammrg::reset(void) { return myrg_reset(file); } /* To be used with WRITE_CACHE, EXTRA_CACHE and BULK_INSERT_BEGIN */ int ha_myisammrg::extra_opt(enum ha_extra_function operation, ulong cache_size) { DBUG_ASSERT(this->file->children_attached); if ((specialflag & SPECIAL_SAFE_MODE) && operation == HA_EXTRA_WRITE_CACHE) return 0; return myrg_extra(file, operation, (void*) &cache_size); } int ha_myisammrg::external_lock(THD *thd, int lock_type) { DBUG_ASSERT(this->file->children_attached); return myrg_lock_database(file,lock_type); } uint ha_myisammrg::lock_count(void) const { /* Return the real lock count even if the children are not attached. This method is used for allocating memory. If we would return 0 to another thread (e.g. doing FLUSH TABLE), and attach the children before the other thread calls store_lock(), then we would return more locks in store_lock() than we claimed by lock_count(). The other tread would overrun its memory. */ return file->tables; } THR_LOCK_DATA **ha_myisammrg::store_lock(THD *thd, THR_LOCK_DATA **to, enum thr_lock_type lock_type) { MYRG_TABLE *open_table; /* This method can be called while another thread is attaching the children. If the processor reorders instructions or write to memory, 'children_attached' could be set before 'open_tables' has all the pointers to the children. Use of a mutex here and in myrg_attach_children() forces consistent data. */ pthread_mutex_lock(&this->file->mutex); /* When MERGE table is open, but not yet attached, other threads could flush it, which means call mysql_lock_abort_for_thread() on this threads TABLE. 'children_attached' is FALSE in this situaton. Since the table is not locked, return no lock data. */ if (!this->file->children_attached) goto end; /* purecov: tested */ for (open_table=file->open_tables ; open_table != file->end_table ; open_table++) { *(to++)= &open_table->table->lock; if (lock_type != TL_IGNORE && open_table->table->lock.type == TL_UNLOCK) open_table->table->lock.type=lock_type; } end: pthread_mutex_unlock(&this->file->mutex); return to; } /* Find out database name and table name from a filename */ static void split_file_name(const char *file_name, LEX_STRING *db, LEX_STRING *name) { size_t dir_length, prefix_length; char buff[FN_REFLEN]; db->length= 0; strmake(buff, file_name, sizeof(buff)-1); dir_length= dirname_length(buff); if (dir_length > 1) { /* Get database */ buff[dir_length-1]= 0; // Remove end '/' prefix_length= dirname_length(buff); db->str= (char*) file_name+ prefix_length; db->length= dir_length - prefix_length -1; } name->str= (char*) file_name+ dir_length; name->length= (uint) (fn_ext(name->str) - name->str); } void ha_myisammrg::update_create_info(HA_CREATE_INFO *create_info) { DBUG_ENTER("ha_myisammrg::update_create_info"); if (!(create_info->used_fields & HA_CREATE_USED_UNION)) { MYRG_TABLE *open_table; THD *thd=current_thd; create_info->merge_list.next= &create_info->merge_list.first; create_info->merge_list.elements=0; for (open_table=file->open_tables ; open_table != file->end_table ; open_table++) { TABLE_LIST *ptr; LEX_STRING db, name; LINT_INIT(db.str); if (!(ptr = (TABLE_LIST *) thd->calloc(sizeof(TABLE_LIST)))) goto err; split_file_name(open_table->table->filename, &db, &name); if (!(ptr->table_name= thd->strmake(name.str, name.length))) goto err; if (db.length && !(ptr->db= thd->strmake(db.str, db.length))) goto err; create_info->merge_list.elements++; (*create_info->merge_list.next) = ptr; create_info->merge_list.next= &ptr->next_local; } *create_info->merge_list.next=0; } if (!(create_info->used_fields & HA_CREATE_USED_INSERT_METHOD)) { create_info->merge_insert_method = file->merge_insert_method; } DBUG_VOID_RETURN; err: create_info->merge_list.elements=0; create_info->merge_list.first=0; DBUG_VOID_RETURN; } int ha_myisammrg::create(const char *name, register TABLE *form, HA_CREATE_INFO *create_info) { char buff[FN_REFLEN]; const char **table_names, **pos; TABLE_LIST *tables= create_info->merge_list.first; THD *thd= current_thd; size_t dirlgt= dirname_length(name); DBUG_ENTER("ha_myisammrg::create"); /* Allocate a table_names array in thread mem_root. */ if (!(table_names= (const char**) thd->alloc((create_info->merge_list.elements+1) * sizeof(char*)))) DBUG_RETURN(HA_ERR_OUT_OF_MEM); /* Create child path names. */ for (pos= table_names; tables; tables= tables->next_local) { const char *table_name= buff; /* Construct the path to the MyISAM table. Try to meet two conditions: 1.) Allow to include MyISAM tables from different databases, and 2.) allow for moving DATADIR around in the file system. The first means that we need paths in the .MRG file. The second means that we should not have absolute paths in the .MRG file. The best, we can do, is to use 'mysql_data_home', which is '.' in mysqld and may be an absolute path in an embedded server. This means that it might not be possible to move the DATADIR of an embedded server without changing the paths in the .MRG file. Do the same even for temporary tables. MERGE children are now opened through the table cache. They are opened by db.table_name, not by their path name. */ uint length= build_table_filename(buff, sizeof(buff), tables->db, tables->table_name, "", 0); /* If a MyISAM table is in the same directory as the MERGE table, we use the table name without a path. This means that the DATADIR can easily be moved even for an embedded server as long as the MyISAM tables are from the same database as the MERGE table. */ if ((dirname_length(buff) == dirlgt) && ! memcmp(buff, name, dirlgt)) { table_name+= dirlgt; length-= dirlgt; } if (!(table_name= thd->strmake(table_name, length))) DBUG_RETURN(HA_ERR_OUT_OF_MEM); /* purecov: inspected */ *pos++= table_name; } *pos=0; /* Create a MERGE meta file from the table_names array. */ DBUG_RETURN(myrg_create(fn_format(buff,name,"","", MY_RESOLVE_SYMLINKS| MY_UNPACK_FILENAME|MY_APPEND_EXT), table_names, create_info->merge_insert_method, (my_bool) 0)); } void ha_myisammrg::append_create_info(String *packet) { const char *current_db; size_t db_length; THD *thd= current_thd; TABLE_LIST *open_table, *first; if (file->merge_insert_method != MERGE_INSERT_DISABLED) { packet->append(STRING_WITH_LEN(" INSERT_METHOD=")); packet->append(get_type(&merge_insert_method,file->merge_insert_method-1)); } /* There is no sence adding UNION clause in case there is no underlying tables specified. */ if (file->open_tables == file->end_table) return; packet->append(STRING_WITH_LEN(" UNION=(")); current_db= table->s->db.str; db_length= table->s->db.length; for (first= open_table= table->child_l;; open_table= open_table->next_global) { LEX_STRING db= { open_table->db, open_table->db_length }; if (open_table != first) packet->append(','); /* Report database for mapped table if it isn't in current database */ if (db.length && (db_length != db.length || strncmp(current_db, db.str, db.length))) { append_identifier(thd, packet, db.str, db.length); packet->append('.'); } append_identifier(thd, packet, open_table->table_name, open_table->table_name_length); if (&open_table->next_global == table->child_last_l) break; } packet->append(')'); } bool ha_myisammrg::check_if_incompatible_data(HA_CREATE_INFO *info, uint table_changes) { /* For myisammrg, we should always re-generate the mapping file as this is trivial to do */ return COMPATIBLE_DATA_NO; } int ha_myisammrg::check(THD* thd, HA_CHECK_OPT* check_opt) { return HA_ADMIN_OK; } ha_rows ha_myisammrg::records() { return myrg_records(file); } extern int myrg_panic(enum ha_panic_function flag); int myisammrg_panic(handlerton *hton, ha_panic_function flag) { return myrg_panic(flag); } static int myisammrg_init(void *p) { handlerton *myisammrg_hton; myisammrg_hton= (handlerton *)p; myisammrg_hton->db_type= DB_TYPE_MRG_MYISAM; myisammrg_hton->create= myisammrg_create_handler; myisammrg_hton->panic= myisammrg_panic; myisammrg_hton->flags= HTON_NO_PARTITION; return 0; } struct st_mysql_storage_engine myisammrg_storage_engine= { MYSQL_HANDLERTON_INTERFACE_VERSION }; mysql_declare_plugin(myisammrg) { MYSQL_STORAGE_ENGINE_PLUGIN, &myisammrg_storage_engine, "MRG_MYISAM", "MySQL AB", "Collection of identical MyISAM tables", PLUGIN_LICENSE_GPL, myisammrg_init, /* Plugin Init */ NULL, /* Plugin Deinit */ 0x0100, /* 1.0 */ NULL, /* status variables */ NULL, /* system variables */ NULL /* config options */ } mysql_declare_plugin_end;
33.325792
88
0.667413
afeng11
75ccfae159f1fa788169a3ad78a906d158d397f4
790
cpp
C++
BashuOJ-Code/2905.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/2905.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
BashuOJ-Code/2905.cpp
magicgh/algorithm-contest-code
c21a90b11f73535c61e6363a4305b74cff24a85b
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstring> #include<iomanip> #include<cmath> #define N 50005 bool PrimeNum[N*100]={0}; int Num[N]={0}; void Prime() { int i,j; PrimeNum[0]=PrimeNum[1]=1; PrimeNum[2]=0; for(i=2;i<sqrt(N);i++) { if(PrimeNum[i]==0) { j=2; while(i*j<N) { PrimeNum[i*j]=1; j++; } } } return; } using namespace std; int main(){ long long l,r,cnt=0,ans=0; cin>>l>>r; memset(PrimeNum,0,sizeof(PrimeNum)); Prime(); for(int i=2;i<N;i++)if(!PrimeNum[i])Num[++cnt]=i; memset(PrimeNum,0,sizeof(PrimeNum)); for(int i=1;i<=cnt;i++) { long long j=l/Num[i]; if(j*Num[i]<l)j++; if(j==1)j++; for(;j*Num[i]<=r;j++)PrimeNum[j*Num[i]-l]=1; } for(int i=0;i<=r-l;i++)if(!PrimeNum[i])ans++; cout<<ans; return 0; }
17.173913
50
0.563291
magicgh
75cf9a9fb0254ab8b3422850313ba06ea6f79795
1,991
cpp
C++
Book/problem_solving/ch06/main.cpp
coder137/CPP-Repo
852dffa42e7fc42e320e4a90abd80d5a045d4ffd
[ "MIT" ]
null
null
null
Book/problem_solving/ch06/main.cpp
coder137/CPP-Repo
852dffa42e7fc42e320e4a90abd80d5a045d4ffd
[ "MIT" ]
null
null
null
Book/problem_solving/ch06/main.cpp
coder137/CPP-Repo
852dffa42e7fc42e320e4a90abd80d5a045d4ffd
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> // File IO #include <cstdlib> // exit statement #include <iomanip> // manipulator using namespace std; static const string READ_FILE = "r.txt"; static const string WRITE_FILE = "w.txt"; // Reads and writes to the file void read_write_example(); // Writes data to a written file without creating a new one void append_example(); // Reads the entire file till the end void read_complete_file(); // Reads the entire file checking for eof void read_complete_file_eof(); int main() { cout << "Hello world!" << endl; // File Read Write read_write_example(); // Append append_example(); // Exit // exit(1); // using namespace ios (Page 360) // Manipulators (iomanip) cout << "Hello" << setw(10) << "World" << setw(15) << 12 << endl; // File IO must be call by reference read_complete_file(); read_complete_file_eof(); // get, put, putback for single character io return 0; } void read_complete_file_eof() { ifstream inStream; inStream.open(WRITE_FILE); string data; while(1) { if (inStream.eof()) { cout << "Breaking" << endl; break; } else { inStream >> data; cout << "Got data: " << data << inStream.eof() << endl; } } inStream.close(); } void read_complete_file() { ifstream inStream; inStream.open(WRITE_FILE); // char data; string data; while (inStream >> data) { cout << "New Data: " << data << endl; } inStream.close(); } void append_example() { ofstream outStream; outStream.open(WRITE_FILE, ios::app); outStream << "APPEND" << endl; outStream.close(); } void read_write_example() { ifstream inStream; ofstream outStream; inStream.open(READ_FILE); outStream.open(WRITE_FILE); int i1, i2; // Read data from file inStream >> i1 >> i2; cout << i1 << i2 << endl; // Write data to file outStream << 1 << endl << 2 << endl; inStream.close(); outStream.close(); }
17.464912
69
0.629332
coder137
75cff7cc71e9cbc6e1c6da336bd2c926ccbfb761
2,371
cpp
C++
test/dldist_test.cpp
namreeb/string_algorithms
a91ac5752538bd06d02c390a96e831d4b084bf7d
[ "MIT" ]
null
null
null
test/dldist_test.cpp
namreeb/string_algorithms
a91ac5752538bd06d02c390a96e831d4b084bf7d
[ "MIT" ]
null
null
null
test/dldist_test.cpp
namreeb/string_algorithms
a91ac5752538bd06d02c390a96e831d4b084bf7d
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2019 namreeb (legal@namreeb.org) http://github.com/namreeb/string_algorithms * * 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 "dldist.hpp" #include <iostream> #include <string> const struct { std::string a; std::string b; int expected_score; } tests[] = { { "test", "test", 0}, // trivial case { "test", "et", 2}, // deletion { "test", "thisisateststring", 13}, // insertions { "test", "tEst", 1}, // substitution { "test", "stet", 2}, // transposition }; int main() { auto constexpr num_tests = sizeof(tests) / sizeof(tests[0]); for (auto i = 0u; i < num_tests; ++i) { auto const score1 = nam::damerau_levenshtein_distance(tests[i].a, tests[i].b); auto const score2 = nam::damerau_levenshtein_distance(tests[i].b, tests[i].a); if (score1 != score2) std::cout << "WARNING: commutative property violation" << std::endl; std::cout << "nam::damerau_levenshtein_distance(\"" << tests[i].a << "\", \"" << tests[i].b << "\") = " << score1 << ". Expected " << tests[i].expected_score << std::endl; if (score1 != tests[i].expected_score) return EXIT_FAILURE; } return EXIT_SUCCESS; }
36.476923
111
0.645297
namreeb
75d15718c760e3149f547fc246fb041a3dd0a22c
2,923
hpp
C++
Box2D/Dynamics/JointAtty.hpp
louis-langholtz/Box2D
7c74792bf177cf36640d735de2bba0225bf7f852
[ "Zlib" ]
32
2016-10-20T05:55:04.000Z
2021-11-25T16:34:41.000Z
Box2D/Dynamics/JointAtty.hpp
louis-langholtz/Box2D
7c74792bf177cf36640d735de2bba0225bf7f852
[ "Zlib" ]
50
2017-01-07T21:40:16.000Z
2018-01-31T10:04:05.000Z
Box2D/Dynamics/JointAtty.hpp
louis-langholtz/Box2D
7c74792bf177cf36640d735de2bba0225bf7f852
[ "Zlib" ]
7
2017-02-09T10:02:02.000Z
2020-07-23T22:49:04.000Z
/* * Original work Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * Modified work Copyright (c) 2017 Louis Langholtz https://github.com/louis-langholtz/Box2D * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef JointAtty_hpp #define JointAtty_hpp /// @file /// Declaration of the JointAtty class. #include <Box2D/Dynamics/Joints/Joint.hpp> namespace box2d { /// @brief Joint attorney. /// /// @details This class uses the "attorney-client" idiom to control the granularity of /// friend-based access to the Joint class. This is meant to help preserve and enforce /// the invariants of the Joint class. /// /// @sa https://en.wikibooks.org/wiki/More_C++_Idioms/Friendship_and_the_Attorney-Client /// class JointAtty { private: static Joint* Create(const box2d::JointDef &def) { return Joint::Create(def); } static void Destroy(const Joint* j) { Joint::Destroy(j); } static void InitVelocityConstraints(Joint& j, BodyConstraintsMap &bodies, const box2d::StepConf &step, const ConstraintSolverConf &conf) { j.InitVelocityConstraints(bodies, step, conf); } static bool SolveVelocityConstraints(Joint& j, BodyConstraintsMap &bodies, const box2d::StepConf &conf) { return j.SolveVelocityConstraints(bodies, conf); } static bool SolvePositionConstraints(Joint& j, BodyConstraintsMap &bodies, const ConstraintSolverConf &conf) { return j.SolvePositionConstraints(bodies, conf); } static bool IsIslanded(const Joint& j) noexcept { return j.IsIslanded(); } static void SetIslanded(Joint& j) noexcept { j.SetIslanded(); } static void UnsetIslanded(Joint& j) noexcept { j.UnsetIslanded(); } friend class World; }; } #endif /* JointAtty_hpp */
32.842697
116
0.640096
louis-langholtz
75d6e972d9a4b3e2aa3bcfe07af269cf53758571
2,378
cpp
C++
cpp/module1_prac/main.cpp
FinancialEngineerLab/bootstrappingSwapCurve
2b2e7b92b6a945ecf09c78f53b53227afe580195
[ "MIT" ]
null
null
null
cpp/module1_prac/main.cpp
FinancialEngineerLab/bootstrappingSwapCurve
2b2e7b92b6a945ecf09c78f53b53227afe580195
[ "MIT" ]
null
null
null
cpp/module1_prac/main.cpp
FinancialEngineerLab/bootstrappingSwapCurve
2b2e7b92b6a945ecf09c78f53b53227afe580195
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include <iomanip> #include "utilities.hpp" #include "curvebuilder.hpp" using namespace std; int main() { ifstream infile; infile.open("data.txt"); double x; int mark = 1; vector<curveUtils> bondSeries; vector<curveUtils>::iterator bondSeries_iter = bondSeries.begin(); vector<double> parameters; while (mark) { infile >> x; if (infile) { parameters.push_back(x); } else { mark = 0; if (infile.eof()) { cout << endl; cout << '\t' << '\t' << '\t' << " --- *** End of the file ***---" << endl; } else { cout << "Wrong !! " << endl; } } } for (int i = 0, j = 0; i < parameters.size() / 3; i++) { curveUtils temp(parameters[j], parameters[j + 1], parameters[j + 2]); bondSeries.push_back(temp); j += 3; } // Constructing a complete term // for (bondSeries_iter = bondSeries.begin(); bondSeries_iter != bondSeries.end() - 1; bondSeries_iter++) { double m = ((*(bondSeries_iter + 1)).get_maturity() - (*(bondSeries_iter)).get_maturity()) / 0.5 - 1.0; if (m > 0) { double insert_coupon = (*(bondSeries_iter)).get_rawcoupon() + ((*(bondSeries_iter + 1)).get_rawcoupon() - (*(bondSeries_iter)).get_rawcoupon()) / (m + 1); double insert_maturtiy = (*bondSeries_iter).get_maturity() + 0.5; curveUtils insertBond(insert_coupon, 100, insert_maturtiy); bondSeries.insert((bondSeries_iter + 1), insertBond); bondSeries_iter = bondSeries.begin(); } } curveBuilder calculator(bondSeries); calculator.spot_rate(); calculator.discount_factor(); calculator.forward(); vector<double> spot_rate = calculator.get_result(); vector<double> discount = calculator.get_discount(); vector<double> forward = calculator.get_forward(); vector<double>::iterator it_1 = spot_rate.begin(); vector<double>::iterator it_2 = discount.begin(); vector<double>::iterator it_3 = forward.begin(); cout << endl; cout << "Tenor (M)" << "\t" << "Spot_Rate (%) " << "\t" << "\t" << "DF (%) " << "\t " << "Forwad (%) " << endl; int m = 1; for (; it_1 != spot_rate.end(); it_1++, it_2++, it_3++, ++m) { cout << setprecision(5) << m * 6 << "\t" << "\t" << "\t" << (*it_1) * 100 << "\t" << "\t" << "\t" << (*it_2) << "\t" << "\t" << "\t" << (*it_3) << endl; } return 1; }
29.358025
158
0.586207
FinancialEngineerLab
75d7330ef3ae13d656f42931b16afae3e2ee5a5a
4,300
cpp
C++
XsGameEngine/src/Renderer/OpenGL_Renderer/OpenGL_Renderer.cpp
XsAndre-L/XsGameEngine-REF
82bbb6424c9b63e0ccf381bd73c0beabce0da141
[ "Apache-2.0" ]
null
null
null
XsGameEngine/src/Renderer/OpenGL_Renderer/OpenGL_Renderer.cpp
XsAndre-L/XsGameEngine-REF
82bbb6424c9b63e0ccf381bd73c0beabce0da141
[ "Apache-2.0" ]
null
null
null
XsGameEngine/src/Renderer/OpenGL_Renderer/OpenGL_Renderer.cpp
XsAndre-L/XsGameEngine-REF
82bbb6424c9b63e0ccf381bd73c0beabce0da141
[ "Apache-2.0" ]
null
null
null
#include "OpenGL_Renderer.h" #pragma region Public Functions int OpenGL_Renderer::init_OpenGL_Renderer(GLFWwindow* newWindow) { window = newWindow; int gladStatus = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); if (gladStatus == 0) { printf("Glad initialization failed!"); glfwDestroyWindow(newWindow); return 1; } glEnable(GL_DEPTH_TEST); glEnable(GL_ARB_gl_spirv); //Allows for spir-v Shaders //TODO int width, height; glfwGetWindowSize(newWindow, &width, &height); glViewport(0, 0, width, height); shaders.CompileShaders(); glm::mat4 projection = glm::perspective(45.0f, (GLfloat)width / (GLfloat)height, 0.1f, 100.0f); shaders.SetProjection(projection); glfwSwapInterval(1); #if defined GUI_LAYER && defined OPENGL bool test = true; new_GUI_Renderer = GUI_Renderer(*newWindow, test, AssetManager); new_GUI_Renderer.createImGuiInstance(); #endif /// <summary> std::string Obj1 = "Models/plane.obj"; std::string Obj2 = "Models/basicOBJ.obj"; AssetManager.createAsset(Obj1.c_str()); AssetManager.createAsset(Obj2.c_str()); //AssetManager.addTexture("Textures/plain.png"); //AssetManager.createOpenGL_MeshModel(Obj3.c_str()); return 0; } //AT the moment this function only refreshes the View and Model Matrices void GLMmovements(OpenGL_MeshModel mod, GLuint MVPuniform, int modelIndex, const Shaders& shaders) { glm::mat4 ViewMat = shaders.GetViewMatrix(); glm::mat4 ModelMat = mod.getMatrix(); glBindBuffer(GL_UNIFORM_BUFFER, MVPuniform); glBufferSubData(GL_UNIFORM_BUFFER, 0, 64, &ModelMat); glBufferSubData(GL_UNIFORM_BUFFER, 64, 64, &ViewMat); glBindBuffer(GL_UNIFORM_BUFFER, 0); //glUniformMatrix4fv(uniformModel, 1, GL_FALSE, glm::value_ptr(model)); } void OpenGL_Renderer::draw() { if (AssetManager.Load_Model_Files) { AssetManager.createOpenGL_MeshModel(); } #if defined GUI_LAYER && defined OPENGL glClearColor(new_GUI_Renderer.clearColor.x, new_GUI_Renderer.clearColor.y, new_GUI_Renderer.clearColor.z, 1.0f); #else glClearColor(40.0f, 40.0f, 40.0f, 1.0f); #endif glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(shaders.getProgram()); for (size_t i = 0; i < AssetManager.MeshModelList.size(); i++) // TODO { GLMmovements(AssetManager.MeshModelList[i], shaders.getMvpLocation(), 0, shaders); // This sets the model Uniform //AssetManager.OpenGL_MeshModelList[i].RenderModel(); auto currModel = AssetManager.MeshModelList[i]; for (size_t i = 0; i < currModel.getMeshCount(); i++) { uint32_t materialIndex = currModel.getMeshToTex()->at(i);//meshToTex[i]; if (materialIndex < AssetManager.textureList.size() && &AssetManager.textureList[materialIndex] != nullptr) { AssetManager.textureList[materialIndex].UseTexture(); } //currModel.meshList[i].renderMesh(); currModel.getMesh(i)->renderMesh(); } } //printf("size %i",(modelList.size())); //shaders.SetDirectionalLight(&mainLight); //shaders.SetPointLight(pointLights, pointLightCount); //shinyMaterial.useMaterial(uniformSpecularIntensityLocation, uniformShininessLocation); //shaders.SetSpotLight(spotLights, spotLightCount); //glUniformMatrix4fv(shaders.getUniformView(), 1, GL_FALSE, glm::value_ptr(camera.calculateViewMatrix())); //glUniform3f(shaders.getEyePositionLocation(), camera.getCameraPosition().x, camera.getCameraPosition().y, camera.getCameraPosition().z); glUseProgram(0); #if defined GUI_LAYER && defined OPENGL OpenGL_MeshModel* mesh; if (AssetManager.MeshModelList.size() > 0) { AssetManager.MeshModelList[*AssetManager.SetSelected()].updateMatrix(); mesh = &AssetManager.MeshModelList[*AssetManager.SetSelected()]; } else { mesh = nullptr; } new_GUI_Renderer.RenderMenus<OpenGL_Assets::AllAssets*>(mesh->getTransformType(),mesh->getPosition(),mesh->getRotation(),mesh->getScale(),AssetManager.SetSelected() ,AssetManager.getAssetInfo()); //The ImGUI Function That Renders The GUI if (ImGui::GetCurrentContext()) ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); #endif glfwSwapBuffers(window); } void OpenGL_Renderer::shutdown_Renderer() { printf("Deleting Renderer\n"); #if defined GUI_LAYER && defined OPENGL new_GUI_Renderer.CleanUpGuiComponents(); new_GUI_Renderer.CleanUpGUI(); #endif } #pragma endregion
27.741935
197
0.75093
XsAndre-L
75d75da91d4357d52c388be777de3f2df0f7e489
5,039
hpp
C++
source/use_case/kws_asr/include/Wav2LetterMfcc.hpp
alifsemi/ensembleML
223ae0e8e765d118b982ffbcb280b5acdc799a75
[ "Apache-2.0" ]
null
null
null
source/use_case/kws_asr/include/Wav2LetterMfcc.hpp
alifsemi/ensembleML
223ae0e8e765d118b982ffbcb280b5acdc799a75
[ "Apache-2.0" ]
null
null
null
source/use_case/kws_asr/include/Wav2LetterMfcc.hpp
alifsemi/ensembleML
223ae0e8e765d118b982ffbcb280b5acdc799a75
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021 Arm Limited. All rights reserved. * SPDX-License-Identifier: Apache-2.0 * * 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. */ #ifndef KWS_ASR_WAV2LET_MFCC_HPP #define KWS_ASR_WAV2LET_MFCC_HPP #include "Mfcc.hpp" namespace arm { namespace app { namespace audio { /* Class to provide Wav2Letter specific MFCC calculation requirements. */ class Wav2LetterMFCC : public MFCC { public: static constexpr uint32_t ms_defaultSamplingFreq = 16000; static constexpr uint32_t ms_defaultNumFbankBins = 128; static constexpr uint32_t ms_defaultMelLoFreq = 0; static constexpr uint32_t ms_defaultMelHiFreq = 8000; static constexpr bool ms_defaultUseHtkMethod = false; explicit Wav2LetterMFCC(const size_t numFeats, const size_t frameLen) : MFCC(MfccParams( ms_defaultSamplingFreq, ms_defaultNumFbankBins, ms_defaultMelLoFreq, ms_defaultMelHiFreq, numFeats, frameLen, ms_defaultUseHtkMethod)) {} Wav2LetterMFCC() = delete; ~Wav2LetterMFCC() = default; protected: /** * @brief Overrides base class implementation of this function. * @param[in] fftVec Vector populated with FFT magnitudes. * @param[in] melFilterBank 2D Vector with filter bank weights. * @param[in] filterBankFilterFirst Vector containing the first indices of filter bank * to be used for each bin. * @param[in] filterBankFilterLast Vector containing the last indices of filter bank * to be used for each bin. * @param[out] melEnergies Pre-allocated vector of MEL energies to be * populated. * @return true if successful, false otherwise. */ bool ApplyMelFilterBank( std::vector<float>& fftVec, std::vector<std::vector<float>>& melFilterBank, std::vector<uint32_t>& filterBankFilterFirst, std::vector<uint32_t>& filterBankFilterLast, std::vector<float>& melEnergies) override; /** * @brief Override for the base class implementation convert mel * energies to logarithmic scale. The difference from * default behaviour is that the power is converted to dB * and subsequently clamped. * @param[in,out] melEnergies 1D vector of Mel energies. **/ void ConvertToLogarithmicScale( std::vector<float>& melEnergies) override; /** * @brief Create a matrix used to calculate Discrete Cosine * Transform. Override for the base class' default * implementation as the first and last elements * use a different normaliser. * @param[in] inputLength Input length of the buffer on which * DCT will be performed. * @param[in] coefficientCount Total coefficients per input length. * @return 1D vector with inputLength x coefficientCount elements * populated with DCT coefficients. */ std::vector<float> CreateDCTMatrix( int32_t inputLength, int32_t coefficientCount) override; /** * @brief Given the low and high Mel values, get the normaliser * for weights to be applied when populating the filter * bank. Override for the base class implementation. * @param[in] leftMel Low Mel frequency value. * @param[in] rightMel High Mel frequency value. * @param[in] useHTKMethod Bool to signal if HTK method is to be * used for calculation. * @return Value to use for normalising. */ float GetMelFilterBankNormaliser( const float& leftMel, const float& rightMel, bool useHTKMethod) override; }; } /* namespace audio */ } /* namespace app */ } /* namespace arm */ #endif /* KWS_ASR_WAV2LET_MFCC_HPP */
44.201754
98
0.580274
alifsemi
75d7d2c124375ff010f8e56e4f3b08c7be2174a2
849
cpp
C++
src/algorithms/warmup/TimeConversion.cpp
notoes/HackerRankChallenges
95f280334846a57cfc8433662a1ed0de2aacc3e9
[ "MIT" ]
null
null
null
src/algorithms/warmup/TimeConversion.cpp
notoes/HackerRankChallenges
95f280334846a57cfc8433662a1ed0de2aacc3e9
[ "MIT" ]
null
null
null
src/algorithms/warmup/TimeConversion.cpp
notoes/HackerRankChallenges
95f280334846a57cfc8433662a1ed0de2aacc3e9
[ "MIT" ]
null
null
null
/* https://www.hackerrank.com/challenges/time-conversion Given a time in AM/PM format, convert it to military (2424-hour) time. */ #include <iostream> #include <iomanip> #include <sstream> using namespace std; int string_to_int( const string& str ) { stringstream stream(str); int res; return (stream >> res) ? res : 0; } int main() { string timeStr; cin >> timeStr; string hourStr = timeStr.substr(0, 2); string minuteStr = timeStr.substr(3, 2); string secondStr = timeStr.substr(6, 2); string amPmStr = timeStr.substr(8,2); int hour = string_to_int(hourStr); if( amPmStr=="AM" ) hour = hour==12 ? 0 : hour; if( amPmStr=="PM" ) hour = hour==12 ? 12 : hour + 12; cout << setfill('0') << setw(2) << hour << ":" << minuteStr << ":" << secondStr << endl; return 0; }
22.945946
92
0.603062
notoes
75e5d14fbcb52d1ad2af711a5fc2503d16dce2aa
556
cpp
C++
src/examples/06_module/01_bank/atm.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-blacksea2003
c3e3c7e5d08cd1b397346d209095f67714f76689
[ "MIT" ]
null
null
null
src/examples/06_module/01_bank/atm.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-blacksea2003
c3e3c7e5d08cd1b397346d209095f67714f76689
[ "MIT" ]
null
null
null
src/examples/06_module/01_bank/atm.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-blacksea2003
c3e3c7e5d08cd1b397346d209095f67714f76689
[ "MIT" ]
null
null
null
//atm.cpp #include "atm.h" using std::cout; using std::cin; ATM::ATM() { customers.push_back(Customer(1, "john doe")); customers.push_back(Customer(2, "mary doe")); customers.push_back(Customer(3, "john hancock")); customers.push_back(Customer(4, "mary hancock")); } void scan_card() { cout<<"enter 1 for checking 2 for saving: "; cin>>account_index; customer_index = rand() % customers.size()-1 + 1; } void ATM::display_balance() { cout<<"Balance: "<<customers[customer_index].get_account(account_index -1)<<"\n"; }
20.592593
85
0.656475
acc-cosc-1337-fall-2020
75e763f1eb7e2de6c3fdfa6fc3cc69dafcf05ed6
14,024
cpp
C++
tools/mayaexp/meuvmap.cpp
Caprica666/vixen
b71e9415bbfa5f080aee30a831e3b0c8f70fcc7d
[ "BSD-2-Clause" ]
1
2019-02-13T15:39:56.000Z
2019-02-13T15:39:56.000Z
tools/mayaexp/meuvmap.cpp
Caprica666/vixen
b71e9415bbfa5f080aee30a831e3b0c8f70fcc7d
[ "BSD-2-Clause" ]
null
null
null
tools/mayaexp/meuvmap.cpp
Caprica666/vixen
b71e9415bbfa5f080aee30a831e3b0c8f70fcc7d
[ "BSD-2-Clause" ]
2
2017-11-09T12:06:41.000Z
2019-02-13T15:40:02.000Z
#include "vix_all.h" #include <maya/MFnSet.h> #include <maya/MFnTransform.h> #include <maya/MPlug.h> #include <maya/MPlugArray.h> #include <maya/MItDependencyGraph.h> #include <maya/MFnCompoundAttribute.h> /*! * @fn SharedObj* meConvProj::Make() * * A Maya projection node applies a 3D projection onto a texture. It has two inputs - * the texture image and a 3D texture placement (4x4 matrix). * This converter exists to provide a way to link the 3D texture matrix to the texture. * It does not have a corresponding Vixen object. * * @return NULL * * @see meConvTex::Make meConvProj::Convert */ SharedObj* meConvProj::Make() { meConnIter iter(m_MayaObj, "image", true); MPlug plug; while (iter.Next(m_TexImage, MFn::kTexture2d)) return NULL; ME_ERROR(("ERROR: Projection texture %s has no image file", GetMayaName()), NULL); return NULL; } /*! * @fn int meConvProj::Link(meConvObj* convparent) * * Links this UV mapper to the texture converter associated with * the image used as input to the projection. This effectively associates * the 3D texture matrix with the right texture. * * @return -1 on error, 0 if no link, 1 if successful link * * @see meConvTex::Make */ int meConvProj::Link(meConvObj* convparent) { ConvRef cvref = Exporter->MayaObjects[m_TexImage]; meConvTex* texconv = dynamic_cast<meConvTex*>( (meConvObj*) cvref ); MObject uvmapper; meConvUV3* uvconv; if (!texconv) return -1; assert(convparent == NULL); /* * Find the UV converter which uses the projection matrix */ meConnIter iter(m_MayaObj, "placementMatrix", true); if (!iter.Next(uvmapper, MFn::kPlace3dTexture)) return -1; cvref = Exporter->MayaObjects[uvmapper]; uvconv = dynamic_cast<meConvUV3*> ((meConvObj*) cvref); if (!uvconv) return -1; uvconv->NoTexCoords = true; // texcoords generated automatically uvconv->UVGen = Sampler::TEXGEN_SPHERE; // assume spherical projection /* * Link the UV converter to the texture converter */ if (!texconv->UVMapper.IsNull()) { ME_ERROR(("ERROR: texture %s with multiple UV mappers", texconv->GetMayaName()), 0); } meLog(1, "UV projection %s linked to texture %s", uvconv->GetMayaName(), texconv->GetMayaName()); texconv->UVMapper = uvconv; // link UV mapper to the texture texconv->DoConvert = true; // link texture to state return 1; } meConvUV::meConvUV(MObject& uvobj) : meConvShader(uvobj) { MStatus status; MFnDependencyNode uvmap(uvobj, &status); MPlug plug; RotateFrame = 0; RotateUV = 0; CoverageU = 1; CoverageV = 1; TranslateU = 0; TranslateV = 0; RepeatU = 1; RepeatV = 1; OffsetU = 1; OffsetV = 0; WrapU = 1; WrapV = 1; Stagger = 0; Mirror = 0; HasMapper = false; NoTexCoords = false; MakeTexCoords = false; } /*! * @fn SharedObj* meConvUV::Make() * * Extracts UV mapping parameters from the Maya texture placement object. * If the UV mapper is attached to a texture, this converter becomes a * child of the texture's converter. * * @see meConvGeo::LinkUVMappers */ SharedObj* meConvUV::Make() { MStatus status; MFnDependencyNode uvmap(m_MayaObj, &status); MPlug plug; if (!status || !m_MayaObj.hasFn(MFn::kPlace2dTexture)) return NULL; HasMapper = true; plug = uvmap.findPlug("coverageU"); plug.getValue(CoverageU); plug = uvmap.findPlug("coverageV"); plug.getValue(CoverageV); plug = uvmap.findPlug("translateU"); plug.getValue(TranslateU); plug = uvmap.findPlug("translateV"); plug.getValue(TranslateV); plug = uvmap.findPlug("repeatU"); plug.getValue(RepeatU); plug = uvmap.findPlug("repeatV"); plug.getValue(RepeatV); plug = uvmap.findPlug("offsetU"); plug.getValue(OffsetU); plug = uvmap.findPlug("offsetV"); plug.getValue(OffsetV); plug = uvmap.findPlug("wrapU"); plug.getValue(WrapU); plug = uvmap.findPlug("wrapV"); plug.getValue(WrapV); plug = uvmap.findPlug("rotateUV"); plug.getValue(RotateUV); plug = uvmap.findPlug("rotateFrame"); plug.getValue(RotateFrame); return this; } int meConvUV::Convert(meConvObj*) { meLog(1, "%s: Converting UV mapper", GetMayaName()); return 1; } /*! * @fn bool meConvUV::MapUV(Vec2* uv, Vec3* loc, Vec3* ctr) * @param uv U and V coordinates before (input) and after (output) mapping * @param loc location at this UV * @param ctr center of object * * Maps a U,V coordinate from a Maya mesh using the given texture placement object. * The location and center are not used by the base implementation but are * included for subclasses which generate texcoords from object space coordinates. * * @returns true if mapping successful, false if no mapper * * @see meConvUV3::MapUV */ bool meConvUV::MapUV(Vec2* uv, Vec3* loc, Vec3* ctr) { float outu, outv; if (!HasMapper) return false; map(uv->x, uv->y, outu, outv); uv->x = outu; uv->y = outv; return true; } /*! * @fn bool meConvUV::MapUV(Vec2* uvs, int n) * @param uvs input and output array of UVs * Maps U,V coordinates from a Maya mesh using the given texture placement object. * * @returns true if mapping successful, false if no texture mapper */ bool meConvUV::MapUV(Vec2* uvs, int n) { float outU, outV; float inU, inV; if (!HasMapper) return false; for (int i = 0; i < n; ++i) { Vec2* uvptr = uvs + i; Vec2& tc = *uvptr; inU = tc.x; inV = tc.y; map(inU, inV, outU, outV); tc.x = outU; tc.y = outV; } return true; } /* * @fn int meConvUV::Link(meConvObj* convparent) * Find the converter for texture which uses this UV mapper and attach * the UV mapper as a child of the texture converter. * This relationship is used later in determining which UV mapper * to use for which set of mesh texture coordinates. */ int meConvUV::Link(meConvObj* convparent) { MObject texobj; meConnIter iter(m_MayaObj, "outUV", false); while (iter.Next(texobj)) { ConvRef cvref; meConvTex* txconv; if (!texobj.hasFn(MFn::kTexture2d) && // not a texture? !texobj.hasFn(MFn::kTexture3d)) continue; cvref = Exporter->MayaObjects[texobj]; txconv = dynamic_cast<meConvTex*>( (meConvObj*) cvref ); if (!txconv) continue; if (!txconv->UVMapper.IsNull() && ((meConvUV*) txconv->UVMapper != this)) { meLog(1, "ERROR: %s texture with multiple UV mappers", txconv->GetMayaName()); continue; } else { meLog(1, "%s: UV mapper linked to texture %s", GetMayaName(), txconv->GetMayaName()); txconv->UVMapper = this; // make UV mapper a child of the texture } } return 1; } #define ME_MAPMETHOD1 void meConvUV::map(float inU, float inV, float& outU, float& outV) { bool inside = true; float tmp; outU = mapU(inU, inV, inside); outV = mapV(inU, inV, inside); if (inside) { if (Stagger) if (int(ffloor(outV)) % 2) outU += 0.5f; if (Mirror) { if (int(ffloor(outU)) % 2) outU = 2 * ffloor(outU) + 1.0f - outU; if (int(ffloor(outV)) % 2) outV = 2 * ffloor(outV) + 1.0f - outV; } #ifdef ME_MAPMETHOD1 float cosa = cos(-RotateUV); float sina = sin(-RotateUV); outU -= 0.5f; outV -= 0.5f; tmp = outU * cosa - outV * sina + 0.5f; outV = outU * sina + outV * cosa + 0.5f; #else float cosa = cos(RotateUV); float sina = sin(RotateUV); outU -= 0.5f; outV -= 0.5f; tmp = outU * sina + outV * cosa + 0.5; outV = outU * cosa - outV * sina + 0.5; #endif outU = tmp; } } float meConvUV::mapU(float inU, float inV, bool& inside) { #ifdef ME_MAPMETHOD1 double outU = (inV - 0.5) * sin(-RotateFrame) + (inU - 0.5) * cos(-RotateFrame) + 0.5; if (CoverageU < 1.0) { if (outU >= 1.0) outU -= floor(outU); else if (outU < 0.0) outU = outU - floor(outU) + 1.0; outU -= TranslateU; if (WrapU) { if (outU >= CoverageU) outU -= 1.0; else if (outU < 0.0) outU += 1.0; } #else float outU = (inU - 0.5) * sin(RotateFrame) + (inV - 0.5) * cos(RotateFrame) + 0.5; if (CoverageU < 1.0) { if (WrapU) { if (outU > 1.0) outU -= ffloor(outU); else if (outU < 0.0) outU = outU - ffloor(outU) + 1.0; outU = outU - (TranslateU - ffloor(TranslateU)); if (outU > CoverageU) outU -= 1.0; else if (outU < 0.0) outU += 1.0; outU /= CoverageU; } #endif if (outU < 0.0 || outU > 1.0) inside = false; } else { outU = (outU - TranslateU) / CoverageU; if (!WrapU) { if (outU < 0.0 || outU > 1.0) inside = false; } } return (float) (outU * RepeatU + OffsetU); } float meConvUV::mapV(float inU, float inV, bool& inside) { #ifdef ME_MAPMETHOD1 float outV = (inV - 0.5f) * cos(-RotateFrame) - (inU - 0.5f) * sin(-RotateFrame) + 0.5f; if (CoverageV < 1.0f) { if (WrapV) { if (outV > 1.0f) outV -= ffloor(outV); else if (outV < 0.0f) outV = outV - ffloor(outV) + 1.0f; outV = outV - (TranslateV - ffloor(TranslateV)); if (outV > CoverageV) outV -= 1.0f; else if (outV < 0.0f) outV += 1.0f; outV /= CoverageV; } #else float outV = (inU - 0.5f) * cos(RotateFrame) - (inV - 0.5f) * sin(RotateFrame) + 0.5f; if (CoverageV < 1.0f) { if (WrapV) { if (outV > 1.0f) outV -= ffloor(outV); else if (outV < 0.0f) outV = outV - ffloor(outV) + 1.0f; outV = outV - (TranslateV - ffloor(TranslateV)); if (outV > CoverageV) outV -= 1.0f; else if (outV < 0.0f) outV += 1.0f; outV /= CoverageV; } #endif if (outV < 0.0f || outV > 1.0f) inside = false; } else { outV = (outV - TranslateV) / CoverageV; if (!WrapV) { if (outV < 0.0f || outV > 1.0f) inside = false; } } return outV * RepeatV + OffsetV; } meConvUV3::meConvUV3(MObject& uvobj) : meConvUV(uvobj) { HasMapper = false; NoTexCoords = true; UVMatrix.Identity(); } /*! * @fn SharedObj* meConvUV3::Make() * * Extracts UV mapping matrix from the Maya 3D texture placement object. * The Maya UV mapping may be directly attached to a texture or it may * be linked to an environment mapping node. * * 3D texture placement generates texture coordinates - it does not * start with a UV set from Maya. The 3D matrix becomes the Vixen * texture projection matrix in the GeoState. If it is used as a * reflection map, the texture coordinates that are generated dynamically * use a spherical projection and vary with the eyepoint. * * Note: 3D matrix currently disabled - not sure how to apply it in Vixen. * * @see meConvGeo::LinkUVMappers meConvUV3::Link meConvUV3::UpdateState */ SharedObj* meConvUV3::Make() { MFnTransform uvmap(m_MayaObj, &m_Status); MDagPath dagPath; if (!m_Status || !m_MayaObj.hasFn(MFn::kPlace3dTexture)) return NULL; MTransformationMatrix tmtx = uvmap.transformation(); MMatrix mtx = tmtx.asMatrix(); float fltdata[4][4]; if (!mtx.isEquivalent(MMatrix::identity)) { mtx.get(fltdata); UVMatrix.SetMatrix(&fltdata[0][0]); UVMatrix.Transpose(); } // HasMapper = true; return NULL; } int meConvUV3::Link(meConvObj* convparent) { MFnTransform uvmap(m_MayaObj); MPlug plug = uvmap.findPlug("worldInverseMatrix"); MObject texobj; if (IsChild()) // already attached? return 1; if (plug.numElements() < 1) return 0; meConnIter iter(plug[0], false); while (iter.Next(texobj)) { if (texobj.hasFn(MFn::kTexture3d)) // associated with 3D texture? MakeTexCoords = true; // generate static texcoords else if (!texobj.hasFn(MFn::kTexture2d)) // not a texture? continue; ConvRef cvref = Exporter->MayaObjects[texobj]; meConvTex* txconv = dynamic_cast<meConvTex*>( (meConvObj*) cvref ); if (!txconv) continue; meLog(1, "UV mapping %s linked to texture %s", GetMayaName(), txconv->GetMayaName()); txconv->Append(this); // make UV mapper a child of the texture assert(UVGen == Sampler::NONE); } return 1; } int meConvUV3::Convert(meConvObj*) { meLog(1, "%s: Converting 3D UV mapper", GetMayaName()); return 1; } /*! * @fn void meConvUV3::UpdateState(meConvState* state, int texindex) * @state state converter for GeoState to update * @texindex index of texture to update * * Updates the Vixen GeoState invormation for 3D UV mapping. * The UV matrix from this converter becomes the Vixen * texture matrix. */ void meConvUV3::UpdateState(meConvState* state, int texindex) { } void meConvUV3::map(float inU, float inV, float& outU, float& outV) { if (!HasMapper || NoTexCoords) { outU = inU; outV = inV; return; } Vec3 vec(inU, inV, 0); vec *= UVMatrix; outU = vec[0]; outV = vec[1]; } /*! * @fn bool meConvUV::MapUV(Vec2* uv, Vec3* loc, Vec3* ctr) * @param uv U and V coordinates before (input) and after (output) mapping * @param loc location at this UV * @param ctr center of object * * Maps a U,V coordinate from a Maya mesh using the given texture placement object. * The location and center are only used if texture coordinates are being generated * from the object space coordinates (MakeTexCoords is set). In this case, * there are no input UVs. * * @returns true if mapping successful, false if no mapper */ bool meConvUV3::MapUV(Vec2* uv, Vec3* loc, Vec3* center) { Vec3 v; if (!HasMapper) return false; if (!MakeTexCoords) return meConvUV::MapUV(uv, loc, center); if (NoTexCoords) return false; v = *loc - *center; // generate UVs in spherical projection v.Normalize(); uv->x = v[0] / 2 + 0.5f; uv->y = v[2] / 2 + 0.5f; uv->x *= 4; uv->y *= 4; return true; }
26.311445
101
0.626569
Caprica666
75ea5655890fd577b72626602b66c3d853426fa5
616
cpp
C++
src/common/onRead.cpp
LeandreBl/Subprocess
b45320878ca43ae0058676c93222be4a46ac8cd1
[ "Apache-2.0" ]
4
2020-12-10T20:22:53.000Z
2021-11-08T08:24:49.000Z
src/common/onRead.cpp
LeandreBl/Subprocess
b45320878ca43ae0058676c93222be4a46ac8cd1
[ "Apache-2.0" ]
null
null
null
src/common/onRead.cpp
LeandreBl/Subprocess
b45320878ca43ae0058676c93222be4a46ac8cd1
[ "Apache-2.0" ]
1
2021-11-08T08:33:22.000Z
2021-11-08T08:33:22.000Z
#include <assert.h> #include "Process.hpp" namespace lp { void Process::onReadStdout( const std::function<void(Process &process, std::stringstream &stream)> &callback) noexcept { onRead(Stdout, callback); } void Process::onReadStderr( const std::function<void(Process &process, std::stringstream &stream)> &callback) noexcept { onRead(Stderr, callback); } void Process::onRead( enum streamType stream, const std::function<void(Process &process, std::stringstream &stream)> &callback) noexcept { assert(stream != Stdin); _callbacks[stream - 1] = callback; } } // namespace lp
26.782609
98
0.699675
LeandreBl
75ed0014c7c7b474158a7e27ed29bd24aa0f13e6
5,817
cc
C++
tests/TestConvolution.cc
vbertone/NangaParbat
49529d0a2e810dfe0ec676c8e96081be39a8800d
[ "MIT" ]
3
2020-01-16T17:15:54.000Z
2020-01-17T10:59:39.000Z
tests/TestConvolution.cc
vbertone/NangaParbat
49529d0a2e810dfe0ec676c8e96081be39a8800d
[ "MIT" ]
null
null
null
tests/TestConvolution.cc
vbertone/NangaParbat
49529d0a2e810dfe0ec676c8e96081be39a8800d
[ "MIT" ]
3
2020-01-18T22:10:02.000Z
2020-08-01T18:42:36.000Z
// // Author: Valerio Bertone: valerio.bertone@cern.ch // #include "NangaParbat/createtmdgrid.h" #include "NangaParbat/factories.h" #include "NangaParbat/bstar.h" #include "NangaParbat/nonpertfunctions.h" #include <LHAPDF/LHAPDF.h> #include <sys/stat.h> #include <fstream> #include <cstring> //_________________________________________________________________________________ int main(int argc, char* argv[]) { // Check that the input is correct otherwise stop the code if (argc < 3 || strcmp(argv[1], "--help") == 0) { std::cout << "\nInvalid Parameters:" << std::endl; std::cout << "Syntax: ./TestConvolution <set 1> <set 2>\n" << std::endl; exit(-10); } // Kinematics const double Q = 5; const double x = 0.1; const double z = 0.3; // Fully differential results const int PerturbativeOrder = 1; // Get non-perturbative functions const NangaParbat::Parameterisation* fNP = NangaParbat::GetParametersation("PV17"); // Open LHAPDF sets LHAPDF::PDF* distpdf = LHAPDF::mkPDF("MMHT2014lo68cl"); LHAPDF::PDF* distff = LHAPDF::mkPDF("DSS14_NLO_PiSum"); // Get heavy-quark thresholds from the PDF LHAPDF set std::vector<double> Thresholds; for (auto const& v : distpdf->flavors()) if (v > 0 && v < 7) Thresholds.push_back(distpdf->quarkThreshold(v)); // Alpha_s const auto AlphasPDF = [&] (double const& mu) -> double{ return distpdf->alphasQ(mu); }; const auto AlphasFF = [&] (double const& mu) -> double{ return distff->alphasQ(mu); }; // Charges const std::function<std::vector<double>(double const&)> Bq = [] (double const&) -> std::vector<double> { return apfel::QCh2; }; // Setup APFEL++ x-space grids const apfel::Grid gpdf{{{60, 1e-4, 3}, {60, 1e-1, 3}, {50, 6e-1, 3}, {50, 8e-1, 3}}}; const apfel::Grid gff{{{60, 1e-2, 3}, {50, 6e-1, 3}, {50, 8e-1, 3}}}; // Rotate PDF set into the QCD evolution basis const auto RotPDFs = [=] (double const& x, double const& mu) -> std::map<int,double> { return apfel::PhysToQCDEv(distpdf->xfxQ(x, mu)); }; const auto RotFFs = [=] (double const& x, double const& mu) -> std::map<int,double> { return apfel::PhysToQCDEv(distff->xfxQ(x, mu)); }; // Construct set of distributions as a function of the scale to be // tabulated const auto EvolvedPDFs = [=,&gpdf] (double const& mu) -> apfel::Set<apfel::Distribution> { return apfel::Set<apfel::Distribution>{apfel::EvolutionBasisQCD{apfel::NF(mu, Thresholds)}, DistributionMap(gpdf, RotPDFs, mu)}; }; const auto EvolvedFFs = [=,&gff] (double const& mu) -> apfel::Set<apfel::Distribution> { return apfel::Set<apfel::Distribution>{apfel::EvolutionBasisQCD{apfel::NF(mu, Thresholds)}, DistributionMap(gff, RotFFs, mu)}; }; // Tabulate collinear PDFs and FFs const apfel::TabulateObject<apfel::Set<apfel::Distribution>> TabPDFs{EvolvedPDFs, 100, 0.5, distpdf->qMax(), 3, Thresholds}; const auto CollPDFs = [&] (double const& mu) -> apfel::Set<apfel::Distribution> { return TabPDFs.Evaluate(mu); }; const apfel::TabulateObject<apfel::Set<apfel::Distribution>> TabFFs{EvolvedFFs, 100, 0.5, distff->qMax(), 3, Thresholds}; const auto CollFFs = [&] (double const& mu) -> apfel::Set<apfel::Distribution> { return TabFFs.Evaluate(mu); }; // Initialize TMD objects const auto TmdObjPDF = apfel::InitializeTmdObjects(gpdf, Thresholds); const auto TmdObjFF = apfel::InitializeTmdObjects(gff, Thresholds); // Build evolved TMD PDFs and FFs const auto EvTMDPDFs = BuildTmdPDFs(TmdObjPDF, CollPDFs, AlphasPDF, PerturbativeOrder, 1); const auto EvTMDFFs = BuildTmdPDFs(TmdObjFF, CollFFs, AlphasFF, PerturbativeOrder, 1); //apfel::OgataQuadrature DEObj{0, 1e-9, 0.00001}; apfel::DoubleExponentialQuadrature DEObj{}; const int nf = apfel::NF(Q, Thresholds); const std::function<apfel::DoubleObject<apfel::Distribution>(double const&)> Lumib = [=] (double const& bs) -> apfel::DoubleObject<apfel::Distribution> { const std::map<int, apfel::Distribution> xF = QCDEvToPhys(EvTMDPDFs(bs, Q, Q * Q).GetObjects()); const std::map<int, apfel::Distribution> xD = QCDEvToPhys(EvTMDFFs(bs, Q, Q * Q).GetObjects()); apfel::DoubleObject<apfel::Distribution> L{}; for (int i = 1; i <= nf; i++) { L.AddTerm({Bq(0)[i-1], xF.at(i), xD.at(i)}); L.AddTerm({Bq(0)[i-1], xF.at(-i), xD.at(-i)}); } return L; }; const std::function<double(double const&)> bInt = [=] (double const& b) -> double { return b * fNP->Evaluate(z, b, Q * Q, 1) * fNP->Evaluate(x, b, Q * Q, 0) * Lumib(NangaParbat::bstarmin(b, Q)).Evaluate(x, z) / z / z; }; // Read in grid and convolute them NangaParbat::TMDGrid* TMD1 = NangaParbat::mkTMD(argv[1]); NangaParbat::TMDGrid* TMD2 = NangaParbat::mkTMD(argv[2]); const auto conv1 = Convolution(TMD1, TMD2, Bq, 1); const auto conv2 = Convolution(TMD1, TMD2, Bq, 0.9); const auto conv3 = Convolution(TMD1, TMD2, Bq, 0.8); const auto conv4 = Convolution(TMD1, TMD2, Bq, 0.7); const auto conv5 = Convolution(TMD1, TMD2, Bq, 0.6); const auto conv6 = Convolution(TMD1, TMD2, Bq, 0.5); // Values of qT const int nqT = 30; const double qTmin = Q * 1e-4; const double qTmax = 0.5 * Q; const double qTstp = ( qTmax - qTmin ) / ( nqT - 1 ); std::vector<double> qTv; std::cout << std::scientific; for (double qT = qTmin; qT <= qTmax; qT += qTstp) std::cout << qT / Q << "\t" << DEObj.transform(bInt, qT) << "\t" << conv1(x, z, Q, qT) << "\t" << conv2(x, z, Q, qT) << "\t" << conv3(x, z, Q, qT) << "\t" << conv4(x, z, Q, qT) << "\t" << conv5(x, z, Q, qT) << "\t" << conv5(x, z, Q, qT) << "\t" << conv6(x, z, Q, qT) << "\t" << std::endl; delete TMD1; delete TMD2; return 0; }
41.55
153
0.636754
vbertone
75efbcc08d8d0e3ee914dc8da19344269d439dca
868
hpp
C++
src/designpattern/Interpret.hpp
brucexia1/DesignPattern
09dab7aaa4e3d72b64467efe3906e4e504e220c4
[ "MIT" ]
null
null
null
src/designpattern/Interpret.hpp
brucexia1/DesignPattern
09dab7aaa4e3d72b64467efe3906e4e504e220c4
[ "MIT" ]
null
null
null
src/designpattern/Interpret.hpp
brucexia1/DesignPattern
09dab7aaa4e3d72b64467efe3906e4e504e220c4
[ "MIT" ]
null
null
null
#pragma once #include <string> using namespace std; class ContextIpt; class AbstractExpression { public: virtual ~AbstractExpression(); virtual void Interpret(const ContextIpt& c) = 0; protected: AbstractExpression(); }; class TerminalExpression:public AbstractExpression { public: TerminalExpression(const string& statement); ~TerminalExpression(); void Interpret(const ContextIpt& c); protected: private: string _statement; }; class NonterminalExpression:public AbstractExpression { public: NonterminalExpression(AbstractExpression* expression,int times); ~ NonterminalExpression(); void Interpret(const ContextIpt& c); protected: private: AbstractExpression* _expression; int _times; }; class ContextIpt { public: ContextIpt(); ~ContextIpt(); void GlobalInfo(); };
18.083333
67
0.708525
brucexia1
75f0e03b43ef4d956d8b7cf47e2e63accf57452e
6,655
hpp
C++
Include/LibYT/GenericFormatter.hpp
MalteDoemer/YeetOS2
82be488ec1ed13e6558af4e248977dad317b3b85
[ "BSD-2-Clause" ]
null
null
null
Include/LibYT/GenericFormatter.hpp
MalteDoemer/YeetOS2
82be488ec1ed13e6558af4e248977dad317b3b85
[ "BSD-2-Clause" ]
null
null
null
Include/LibYT/GenericFormatter.hpp
MalteDoemer/YeetOS2
82be488ec1ed13e6558af4e248977dad317b3b85
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2021 Malte Dömer * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "Types.hpp" #include "Platform.hpp" #include "Concepts.hpp" #include "StdLib.hpp" #include "Functions.hpp" namespace YT { class GenericFormatter { protected: enum FormatOptions { None = 0, ZeroPad = 1, Sign = 2, Plus = 4, Space = 8, Left = 16, Prefix = 32, Lowercase = 64, }; public: using OutputFunction = Function<void(char, char*, size_t, size_t)>; protected: template<IntegralType T, u8 base> requires requires { requires base >= 2 && base <= 36; } void write_integer(T value, int width, int precision, FormatOptions opts) { constexpr size_t max_buffer_size = sizeof(T) * __CHAR_BIT__; char sign, pad; char local_buffer[max_buffer_size]; const char* digits = (opts & Lowercase) ? "0123456789abcdefghjkilmnopqrstuvwxyz" : "0123456789ABCDEFGHJKILMNOPQRSTUVWXYZ"; /* Left aligned cannot be zero padded */ if (opts & Left) { opts = static_cast<FormatOptions>(opts & ~ZeroPad); } if (opts & ZeroPad) { pad = '0'; } else { pad = ' '; } if (opts & Sign) { using SignedT = typename MakeSigned<T>::Type; if (static_cast<SignedT>(value) < 0) { sign = '-'; SignedT s = static_cast<SignedT>(value); s *= -1; value = static_cast<T>(s); } else if (opts & Plus) { sign = '+'; } else if (opts & Space) { sign = ' '; } else { sign = 0; } } else { sign = 0; } /* Decrease the width if we need to display a sign */ if (sign) { width--; } /* Decrease the width if there is a prefix (0x, 0o, 0b) */ if (opts & Prefix) { switch (base) { case 16: case 8: case 2: width -= 2; break; default: break; } } int i = 0; /* Zero is a special case */ if (value == 0) { local_buffer[0] = '0'; i = 1; } for (; value; i++) { local_buffer[i] = digits[value % base]; value /= base; } if (i > precision) { precision = i; } width -= precision; if (!(opts & ZeroPad) && !(opts & Left)) { while (width > 0) { m_out_func(' ', m_buffer, m_index++, m_maxlen); width--; } } if (sign) { m_out_func(sign, m_buffer, m_index++, m_maxlen); } if (opts & Prefix) { if (base == 16) { m_out_func('0', m_buffer, m_index++, m_maxlen); m_out_func('x', m_buffer, m_index++, m_maxlen); } else if (base == 8) { m_out_func('0', m_buffer, m_index++, m_maxlen); m_out_func('o', m_buffer, m_index++, m_maxlen); } else if (base == 2) { m_out_func('0', m_buffer, m_index++, m_maxlen); m_out_func('b', m_buffer, m_index++, m_maxlen); } } if (!(opts & Left)) { while (width > 0) { m_out_func(pad, m_buffer, m_index++, m_maxlen); width--; } } while (i < precision) { m_out_func('0', m_buffer, m_index++, m_maxlen); precision--; } while (i) { m_out_func(local_buffer[--i], m_buffer, m_index++, m_maxlen); } while (width > 0) { m_out_func(' ', m_buffer, m_index++, m_maxlen); width--; } } template<FloatingPointType T> void write_float(T value, int width, int precision, FormatOptions opts) { VERIFY_NOT_REACHED(); } void write_string(const char* str, int width, int precision, FormatOptions opts) { size_t len; if (precision > 0) { len = strnlen(str, precision); } else { len = strlen(str); } width -= len; if (!(opts & Left)) { while (width > 0) { m_out_func(' ', m_buffer, m_index++, m_maxlen); width--; } } while (len--) { m_out_func(*str++, m_buffer, m_index++, m_maxlen); } while (width > 0) { m_out_func(' ', m_buffer, m_index++, m_maxlen); width--; } } void write_char(char c, int width, int precision, FormatOptions opts) { if (!(opts & Left)) { while (width > 0) { m_out_func(' ', m_buffer, m_index++, m_maxlen); width--; } m_out_func(c, m_buffer, m_index++, m_maxlen); while (width > 0) { m_out_func(' ', m_buffer, m_index++, m_maxlen); width--; } } } protected: OutputFunction m_out_func; char* m_buffer { nullptr }; size_t m_index { 0 }; size_t m_maxlen { 0 }; }; } using YT::GenericFormatter;
27.729167
115
0.518407
MalteDoemer
75f1bc7ff426f5f916c96191f9b8b555070793bb
113
cpp
C++
src/ace/ACE_wrappers/ACEXML/common/Element_Def_Builder.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
8
2017-06-05T08:56:27.000Z
2020-04-08T16:50:11.000Z
src/ace/ACE_wrappers/ACEXML/common/Element_Def_Builder.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
null
null
null
src/ace/ACE_wrappers/ACEXML/common/Element_Def_Builder.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
17
2017-06-05T08:54:27.000Z
2021-08-29T14:19:12.000Z
#include "ACEXML/common/Element_Def_Builder.h" ACEXML_Element_Def_Builder::~ACEXML_Element_Def_Builder () { }
14.125
58
0.80531
wfnex
75f382549281b6d76b030be15fe9b88c8b99759c
2,938
cpp
C++
library/src/main/cpp/filters/PolarPixellateFilter.cpp
1463836/android-gpuimage-plus
ad00886e8947e69548814eb457e39985aebea103
[ "MIT" ]
null
null
null
library/src/main/cpp/filters/PolarPixellateFilter.cpp
1463836/android-gpuimage-plus
ad00886e8947e69548814eb457e39985aebea103
[ "MIT" ]
null
null
null
library/src/main/cpp/filters/PolarPixellateFilter.cpp
1463836/android-gpuimage-plus
ad00886e8947e69548814eb457e39985aebea103
[ "MIT" ]
null
null
null
/* * cgePolarPixellateFilter.cpp * * Created on: 2015-2-1 * Author: Wang Yang */ #include "PolarPixellateFilter.h" static ConstString s_fshPolarPixellate = CGE_SHADER_STRING_PRECISION_M ( varying vec2 textureCoordinate; uniform sampler2D inputImageTexture; uniform vec2 center; uniform vec2 pixelSize; void main() { vec2 normCoord = 2.0 * textureCoordinate - 1.0; vec2 normCenter = 2.0 * center - 1.0; normCoord -= normCenter; float r = length( normCoord); // to polar coords float phi = atan(normCoord.y, normCoord.x); // to polar coords r = r - mod(r, pixelSize.x) + 0.03; phi = phi - mod(phi, pixelSize.y); normCoord.x = r * cos(phi); normCoord.y = r * sin(phi); normCoord += normCenter; vec2 textureCoordinateToUse = normCoord / 2.0 + 0.5; gl_FragColor = texture2D(inputImageTexture, textureCoordinateToUse); }); namespace CGE { ConstString CGEPolarPixellateFilter::paramCenter = "center"; ConstString CGEPolarPixellateFilter::paramPixelSize = "pixelSize"; bool CGEPolarPixellateFilter::init() { if (initShadersFromString(g_vshDefaultWithoutTexCoord, s_fshPolarPixellate)) { setCenter(0.5f, 0.5f); setPixelSize(0.05f, 0.05f); return true; } return false; } void CGEPolarPixellateFilter::setCenter(float x, float y) { m_program.bind(); m_program.sendUniformf(paramCenter, x, y); } void CGEPolarPixellateFilter::setPixelSize(float x, float y) { m_program.bind(); m_program.sendUniformf(paramPixelSize, x, y); } }
43.850746
105
0.365895
1463836
75f867193418ac6fda899f1462b53aaf2c76eb50
316
cpp
C++
Baekjoon Online Judge/1 ~ 9999/2501/boj-2501.cpp
kesakiyo/Competitive-Programming
e42331b28c3d8c10bd4853c8fa0ebbfc58dfa033
[ "MIT" ]
1
2019-05-17T16:16:43.000Z
2019-05-17T16:16:43.000Z
Baekjoon Online Judge/1 ~ 9999/2501/boj-2501.cpp
kesakiyo/Competitive-Programming
e42331b28c3d8c10bd4853c8fa0ebbfc58dfa033
[ "MIT" ]
null
null
null
Baekjoon Online Judge/1 ~ 9999/2501/boj-2501.cpp
kesakiyo/Competitive-Programming
e42331b28c3d8c10bd4853c8fa0ebbfc58dfa033
[ "MIT" ]
null
null
null
/* Copyright(c) 2019. Minho Cheon. All rights reserved. */ #include <iostream> using namespace std; int main() { int n, k; cin >> n >> k; int cnt = 0; for (int i = 1 ; i <= n ; ++i) { if (n % i == 0) { ++cnt; if (cnt == k) { cout << i << endl; return 0; } } } cout << 0 << endl; }
12.64
56
0.46519
kesakiyo