hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
11a57fafbdb38844f8d8e26d28cfe82dca09aabd
1,795
cpp
C++
Documents/RacimoAire/Libreria/LogsSystem/adminlogssystem.cpp
JoseSalamancaCoy/RACIMO_AIRE
628d6ff184a30af0efd25bff675b0006500d4ba2
[ "MIT" ]
null
null
null
Documents/RacimoAire/Libreria/LogsSystem/adminlogssystem.cpp
JoseSalamancaCoy/RACIMO_AIRE
628d6ff184a30af0efd25bff675b0006500d4ba2
[ "MIT" ]
null
null
null
Documents/RacimoAire/Libreria/LogsSystem/adminlogssystem.cpp
JoseSalamancaCoy/RACIMO_AIRE
628d6ff184a30af0efd25bff675b0006500d4ba2
[ "MIT" ]
null
null
null
#include "adminlogssystem.h" AdminLogsSystem::AdminLogsSystem(QObject *parent): QObject(parent) { logsSystem = new LogsSystem; logsSystem->moveToThread(&logsSystemThread); connect(&logsSystemThread, &QThread::finished, logsSystem, &QObject::deleteLater); connect(this, &AdminLogsSystem::operate, logsSystem, &LogsSystem::doWork); connect(logsSystem, &LogsSystem::resultReady, this, &AdminLogsSystem::handleResults); connect(logsSystem, &LogsSystem::SignalTemperatura, this, &AdminLogsSystem::SlotTemperatura); connect(logsSystem, &LogsSystem::SignalRAM, this, &AdminLogsSystem::SlotRAM); connect(logsSystem, &LogsSystem::SignalProcesos, this, &AdminLogsSystem::SignalProcesos); connect(logsSystem, &LogsSystem::SignalSOCKET, this, &AdminLogsSystem::SignalSOCKET); connect(logsSystem, &LogsSystem::SignalStatusWIFI, this, &AdminLogsSystem::SignalStatusWIFI); connect(logsSystem, &LogsSystem::SignalEspacioDisco, this, &AdminLogsSystem::SlotEspacioDisco); logsSystemThread.start(); //initHilo(accion); } AdminLogsSystem::~AdminLogsSystem() { } void AdminLogsSystem::SlotTemperatura(float temperatura) { emit SignalTemperatura(temperatura); } void AdminLogsSystem::SlotRAM(QString RAM) { emit SignalRAM(RAM); } void AdminLogsSystem::SlotSOCKET(int SOCKET) { emit SignalSOCKET(SOCKET); } void AdminLogsSystem::SlotProcesos(int Procesos) { emit SignalProcesos(Procesos); } void AdminLogsSystem::SlotStatusWIFI(bool StatusWIFI) { emit SignalStatusWIFI(StatusWIFI); } void AdminLogsSystem::SlotEspacioDisco(QString EspacioDisco) { emit SignalEspacioDisco(EspacioDisco); } void AdminLogsSystem::initHilo(int accion) { emit operate(accion); } void AdminLogsSystem::handleResults(const QString &result) { }
26.397059
99
0.764345
JoseSalamancaCoy
11a96bea30f234550c1e85ed2eecb7fd4303fe4b
11,613
cpp
C++
src/base/event/Brent.cpp
ddj116/gmat
39673be967d856f14616462fb6473b27b21b149f
[ "NASA-1.3" ]
1
2020-05-16T16:58:21.000Z
2020-05-16T16:58:21.000Z
src/base/event/Brent.cpp
ddj116/gmat
39673be967d856f14616462fb6473b27b21b149f
[ "NASA-1.3" ]
null
null
null
src/base/event/Brent.cpp
ddj116/gmat
39673be967d856f14616462fb6473b27b21b149f
[ "NASA-1.3" ]
null
null
null
//$Id: Brent.cpp 10052 2011-12-06 22:56:03Z djcinsb $ //------------------------------------------------------------------------------ // Brent //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool. // // Copyright (c) 2002-2011 United States Government as represented by the // Administrator of The National Aeronautics and Space Administration. // All Other Rights Reserved. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under NASA Prime // Contract NNG10CP02C, Task Order 28 // // Author: Darrel J. Conway, Thinking Systems, Inc. // Created: Sep 20, 2011 // /** * Implementation of Brent's Method used in event location and, eventually, * stopping conditions */ //------------------------------------------------------------------------------ #include "Brent.hpp" #include "EventException.hpp" #include "RealUtilities.hpp" #include "MessageInterface.hpp" //#define DEBUG_BRENT //#define DEBUG_BRENT_BUFFER //#define DEBUG_BRACKETACCESS //------------------------------------------------------------------------------ // Brent() //------------------------------------------------------------------------------ /** * Default constructor */ //------------------------------------------------------------------------------ Brent::Brent() : RootFinder ("BrentsMethod"), bisectionUsed (true), epochOfStep (-1.0), step (0.0), oldCValue (-1.0) { bufferSize = 3; } //------------------------------------------------------------------------------ // ~Brent() //------------------------------------------------------------------------------ /** * Destructor */ //------------------------------------------------------------------------------ Brent::~Brent() { } //------------------------------------------------------------------------------ // Brent(const Brent & b) //------------------------------------------------------------------------------ /** * Copy constructor * * @param b The original being copied here */ //------------------------------------------------------------------------------ Brent::Brent(const Brent & b) : RootFinder (b), bisectionUsed (true), epochOfStep (-1.0), step (0.0), oldCValue (-1.0) { } //------------------------------------------------------------------------------ // Brent &operator =(const Brent & b) //------------------------------------------------------------------------------ /** * Assignment operator * * @param b The original being copied here * * @return this instance, set to match b. */ //------------------------------------------------------------------------------ Brent & Brent::operator =(const Brent & b) { if (this != &b) { RootFinder::operator =(b); bisectionUsed = true; epochOfStep = -1.0; step = 0.0; oldCValue = -1.0; } return *this; } //------------------------------------------------------------------------------ // bool Brent::Initialize(GmatEpoch t0, Real f0, GmatEpoch t1, Real f1) //------------------------------------------------------------------------------ /** * Prepares Brent's Method for use * * This method calls the RootFinder initialization to prepare the buffers for * use, then rearranges the buffers as needed and sets the third data point to * the first as needed by the algorithm. * * @param t0 The earlier epoch for the data. * @param f0 The function value at t0 * @param t1 The later epoch for the data. * @param f1 The function value at t1 * * @return true if initialization succeeds, false if it fails. */ //------------------------------------------------------------------------------ bool Brent::Initialize(GmatEpoch t0, Real f0, GmatEpoch t1, Real f1) { #ifdef DEBUG_BRENT MessageInterface::ShowMessage("Brent::Initialize(%15.9lf, %12lf, %15.9lf, " "%12lf) called\n", t0, f0, t1, f1); #endif if (f0 * f1 >= 0.0) throw EventException("Error initializing Brent's method; the solution is " "not bracketed"); bool retval = RootFinder::Initialize(t0, f0, t1, f1); if (retval) { if (buffer[0] < buffer[1]) { Swap(0, 1); } epochBuffer[2] = epochBuffer[0]; buffer[2] = buffer[0]; bisectionUsed = true; // Act as if bisection was used previously } #ifdef DEBUG_BRENT_BUFFER MessageInterface::ShowMessage("Brent::Buffer Data:\n %15.9lf " "%.12lf\n %15.9lf %.12lf\n %15.9lf %.12lf\n", epochBuffer[0], buffer[0], epochBuffer[1], buffer[1], epochBuffer[2], buffer[2]); #endif return retval; } //------------------------------------------------------------------------------ // void SetValue(GmatEpoch forEpoch, Real withValue) //------------------------------------------------------------------------------ /** * Adds a new data point to the algorithm, discarding the stale data * * @param forEpoch The epoch of the new data * @param withValue The new data value * * @return true on success. (This Brent's method override always returns true) */ //------------------------------------------------------------------------------ bool Brent::SetValue(GmatEpoch forEpoch, Real withValue) { #ifdef DEBUG_BRENT_BUFFER MessageInterface::ShowMessage("Received data: %15.9lf %.12lf\n", forEpoch, withValue); MessageInterface::ShowMessage("Brent::SetValue Initial Buffer Data:\n " "%15.9lf %.12lf\n %15.9lf %.12lf\n %15.9lf %.12lf\n", epochBuffer[0], buffer[0], epochBuffer[1], buffer[1], epochBuffer[2], buffer[2]); #endif bool retval = true; oldCValue = epochBuffer[2]; epochBuffer[2] = epochBuffer[1]; buffer[2] = buffer[1]; if (buffer[0] * withValue < 0.0) { epochBuffer[1] = forEpoch; buffer[1] = withValue; } else { epochBuffer[0] = forEpoch; buffer[0] = withValue; } if (GmatMathUtil::Abs(buffer[0]) < GmatMathUtil::Abs(buffer[1])) Swap(0,1); #ifdef DEBUG_BRENT_BUFFER MessageInterface::ShowMessage("Brent::SetValue Updated Buffer Data:\n " "%15.9lf %.12lf\n %15.9lf %.12lf\n %15.9lf %.12lf\n", epochBuffer[0], buffer[0], epochBuffer[1], buffer[1], epochBuffer[2], buffer[2]); #endif return retval; } //------------------------------------------------------------------------------ // Real FindStep() //------------------------------------------------------------------------------ /** * Finds the next step to take, given the data in the buffers. * * @param currentEpoch The epoch of the latest data in the buffers. If not set, * the return value is treated as absolute and the step is not converted * from days to seconds from the current epoch. * * @return The next step * * @todo Complete the implementation of Brent's algorithm. THe current code is * performing bisection. */ //------------------------------------------------------------------------------ Real Brent::FindStep(const GmatEpoch currentEpoch) { bool bisectOnly = false; if (bisectOnly) { epochOfStep = 0.5 * (epochBuffer[0] + epochBuffer[1]); } else { Real diffAB, diffAC, diffBC; diffAB = buffer[0] - buffer[1]; if ((buffer[0] != buffer[2]) && (buffer[1] != buffer[2])) { diffAC = buffer[0] - buffer[2]; diffBC = buffer[1] - buffer[2]; // Inverse quadratic interpolation epochOfStep = epochBuffer[0] * buffer[1] * buffer[2] / ((diffAB*diffAC)) + epochBuffer[1] * buffer[0] * buffer[2] / ((-diffAB*diffBC)) + epochBuffer[2] * buffer[0] * buffer[1] / ((diffAC*diffBC)); } else { // Secant method epochOfStep = epochBuffer[1] - buffer[1] * (epochBuffer[0] - epochBuffer[1])/diffAB; } // Figure out if we need to drop back to bisection Real delta = 1.0e-8; // Numerical tolerance for epochs; set to ~1 msec Real deltaC, bMinusC, sMinusB; deltaC = GmatMathUtil::Abs(epochBuffer[2] - oldCValue); bMinusC = GmatMathUtil::Abs(epochBuffer[1]-epochBuffer[2]); sMinusB = GmatMathUtil::Abs(epochOfStep - epochBuffer[1]); if ( ((epochOfStep >= (3.0 * epochBuffer[0] + epochBuffer[1]) / 4.0) && (epochOfStep <= epochBuffer[1])) || (bisectionUsed && (sMinusB >= bMinusC / 2.0)) || (!bisectionUsed && (sMinusB >= deltaC / 2.0)) || (bisectionUsed && (bMinusC < delta)) || (!bisectionUsed && deltaC < delta) ) { // Drop back to bisection. Sigh. epochOfStep = 0.5 * (epochBuffer[0] + epochBuffer[1]); bisectionUsed = true; } else bisectionUsed = false; } // Get the step in seconds to the epochOfStep if input in days was set if (currentEpoch != -1.0) step = (epochOfStep - currentEpoch) * GmatTimeConstants::SECS_PER_DAY; else step = epochOfStep; #ifdef DEBUG_BRENT MessageInterface::ShowMessage("Brent's Method: Current Epoch: %15.9lf, " "Epoch of Step: %15.9lf, step: %15.9lf\n", currentEpoch, epochOfStep, step); #endif return step; } //------------------------------------------------------------------------------ // Real GetStepMeasure() //------------------------------------------------------------------------------ /** * Retrieves the size of the epoch brackets * * @return The difference, in seconds, between the two epochs bracketing the * zero */ //------------------------------------------------------------------------------ Real Brent::GetStepMeasure() { GmatEpoch start, end; GetBrackets(start, end); return (end - start) * GmatTimeConstants::SECS_PER_DAY; } //------------------------------------------------------------------------------ // void GetBrackets(GmatEpoch &start, GmatEpoch &end) //------------------------------------------------------------------------------ /** * Retrieves the bracketing epochs from the epoch buffer. * * @param start The epoch earlier than the zero value * @param end The epoch later than the zero value */ //------------------------------------------------------------------------------ void Brent::GetBrackets(GmatEpoch &start, GmatEpoch &end) { Real val = GmatMathUtil::Abs(buffer[0]), temp; GmatEpoch locT = epochBuffer[0], t2, dt = 9.0e9; Integer found = 0; // Find the index of the closest to zero function value for (Integer i = 1; i < 3; ++i) { temp = GmatMathUtil::Abs(buffer[i]); if (temp < val) { val = temp; locT = epochBuffer[i]; found = i; } } // Find the index of the other side t2 = epochBuffer[0]; for (Integer i = 0; i < 3; ++i) { if (found != i) { if (buffer[found] * buffer[i] < 0.0) { if (GmatMathUtil::Abs(locT - epochBuffer[i]) < dt) t2 = epochBuffer[i]; } } } start = (locT < t2 ? locT : t2); end = (locT > t2 ? locT : t2); #ifdef DEBUG_BRACKETACCESS MessageInterface::ShowMessage("Buffer data:\n"); for (Integer i = 0; i < 3; ++i) MessageInterface::ShowMessage(" %.12lf %le\n", epochBuffer[i], buffer[i]); MessageInterface::ShowMessage("Bracketing epochs: [%.12lf %.12lf]\n", start, end); #endif }
31.557065
83
0.473607
ddj116
11a97bc5e1c85f39e68e8dc81a1208fca151da56
2,913
hpp
C++
src/include/ulib/stream/ITextStream.hpp
vividos/UlibCpp
d96348844348a00523b7742b3e7a5c9764613877
[ "BSD-2-Clause" ]
null
null
null
src/include/ulib/stream/ITextStream.hpp
vividos/UlibCpp
d96348844348a00523b7742b3e7a5c9764613877
[ "BSD-2-Clause" ]
null
null
null
src/include/ulib/stream/ITextStream.hpp
vividos/UlibCpp
d96348844348a00523b7742b3e7a5c9764613877
[ "BSD-2-Clause" ]
null
null
null
// // ulib - a collection of useful classes // Copyright (C) 2007,2008,2012,2014,2017,2020 Michael Fink // /// \file ITextStream.hpp text stream interface // #pragma once namespace Stream { /// text stream interface class ITextStream { public: /// text encoding that is possible for text files enum ETextEncoding { textEncodingNative, ///< native encoding; compiler options decide if ANSI or Unicode is used for output textEncodingAnsi, ///< ANSI text encoding; depends on the current codepage (not recommended) textEncodingUTF8, ///< UTF-8 encoding textEncodingUCS2, ///< UCS-2 encoding }; /// line ending mode used to detect lines or is used for writing enum ELineEndingMode { lineEndingCRLF, ///< a CR and LF char (\\r\\n) is used to separate lines; Win32-style lineEndingLF, ///< a LF char (\\n) is used to separate lines; Linux-style lineEndingCR, ///< a CR char (\\r) is used to separate lines; Mac-style lineEndingReadAny,///< when reading, any of the above line ending modes are detected when using ReadLine() lineEndingNative, ///< native mode is used }; /// ctor ITextStream(ETextEncoding textEncoding = textEncodingNative, ELineEndingMode lineEndingMode = lineEndingNative) :m_textEncoding(textEncoding), m_lineEndingMode(lineEndingMode) { } /// dtor virtual ~ITextStream() { // nothing to cleanup } // stream capabilities /// returns text encoding currently in use ETextEncoding TextEncoding() const { return m_textEncoding; } /// returns line ending mode currently in use ELineEndingMode LineEndingMode() const { return m_lineEndingMode; } /// returns true when stream can be read virtual bool CanRead() const = 0; /// returns true when stream can be written to virtual bool CanWrite() const = 0; /// returns true when the stream end is reached virtual bool AtEndOfStream() const = 0; // read support /// reads a single character virtual TCHAR ReadChar() = 0; /// reads a whole line using line ending settings virtual void ReadLine(CString& line) = 0; // write support /// writes text virtual void Write(const CString& text) = 0; /// writes endline character virtual void WriteEndline() = 0; /// writes a line void WriteLine(const CString& line) { Write(line); WriteEndline(); } /// flushes out text stream virtual void Flush() = 0; private: friend class TextStreamFilter; /// current text encoding ETextEncoding m_textEncoding; /// current line ending mode ELineEndingMode m_lineEndingMode; }; } // namespace Stream
28.558824
115
0.626502
vividos
11acb9ab7d7b558cb8d1d57f2fd725893e1f16e0
2,236
cpp
C++
examples/particleSim/Particle.cpp
nitro44x/mirror
545e609cd260579ec132f91788921ef4f9fa2049
[ "BSD-3-Clause" ]
null
null
null
examples/particleSim/Particle.cpp
nitro44x/mirror
545e609cd260579ec132f91788921ef4f9fa2049
[ "BSD-3-Clause" ]
null
null
null
examples/particleSim/Particle.cpp
nitro44x/mirror
545e609cd260579ec132f91788921ef4f9fa2049
[ "BSD-3-Clause" ]
null
null
null
#include "Particle.hpp" #include <device_launch_parameters.h> #include <mirror/simt_macros.hpp> #include <mirror/simt_allocator.hpp> #include <mirror/simt_vector.hpp> #include <mirror/simt_serialization.hpp> #include <mirror/simt_utilities.hpp> ParticleSquare::ParticleSquare(double L) : m_L(L) {} ParticleSquare::~ParticleSquare() { ; } HOSTDEVICE double ParticleSquare::area() const { return m_L * m_L; } HOSTDEVICE double ParticleSquare::mass() const { return 1.0; } HOST void ParticleSquare::write(mirror::serializer & io) const { io.write(m_L); } HOSTDEVICE void ParticleSquare::read(mirror::serializer::size_type startPosition, mirror::serializer & io) { io.read(startPosition, &m_L); } HOSTDEVICE ParticleSquare::type_id_t ParticleSquare::type() const { return ParticleTypes::eParticleSquare; } ParticleCircle::ParticleCircle(double radius) : m_radius(radius) {} ParticleCircle::~ParticleCircle() { ; } HOSTDEVICE double ParticleCircle::area() const { return 3.1415 * m_radius * m_radius; } HOSTDEVICE double ParticleCircle::mass() const { return 1.0; } HOST void ParticleCircle::write(mirror::serializer & io) const { io.write(m_radius); } HOSTDEVICE void ParticleCircle::read(mirror::serializer::size_type startPosition, mirror::serializer & io) { io.read(startPosition, &m_radius); } HOSTDEVICE ParticleCircle::type_id_t ParticleCircle::type() const { return ParticleTypes::eParticleCircle; } ParticleTriangle::ParticleTriangle(double base, double height) : m_base(base), m_height(height) {} ParticleTriangle::~ParticleTriangle() { ; } HOSTDEVICE double ParticleTriangle::area() const { return 0.5 * m_base * m_height; } HOSTDEVICE double ParticleTriangle::mass() const { return 1.0; } HOST void ParticleTriangle::write(mirror::serializer & io) const { io.write(m_base); io.write(m_height); } HOSTDEVICE void ParticleTriangle::read(mirror::serializer::size_type startPosition, mirror::serializer & io) { io.read(startPosition, &m_base); io.read(startPosition, &m_height); } HOSTDEVICE ParticleTriangle::type_id_t ParticleTriangle::type() const { return ParticleTypes::eParticleTriangle; } size_t mirror::polymorphic_traits<Particle>::cache[enum_type::Max_];
30.216216
110
0.753131
nitro44x
11adc36baae639ef2d1a38bdb34760937cd7c580
1,959
cpp
C++
ECS/ECS/ECS.cpp
oWASDo/ECS
4131269889e13be7990e250b8b9376b9a16229a3
[ "MIT" ]
null
null
null
ECS/ECS/ECS.cpp
oWASDo/ECS
4131269889e13be7990e250b8b9376b9a16229a3
[ "MIT" ]
null
null
null
ECS/ECS/ECS.cpp
oWASDo/ECS
4131269889e13be7990e250b8b9376b9a16229a3
[ "MIT" ]
null
null
null
// ECS.cpp : Questo file contiene la funzione 'main', in cui inizia e termina l'esecuzione del programma. // #include <iostream> #include <vector> #include <time.h> #include "Heder/ECS_Context.h" #include "Heder/Component.h" class ClassTest { public: ClassTest(); ~ClassTest(); void Adding() { inttt += 5; } private: int inttt; }; ClassTest::ClassTest() { inttt = 5; } ClassTest::~ClassTest() { } using namespace std; int main() { size_t entttSNumber = 5; //Create ECS context ECS_Context* context = new ECS_Context(); for (int i = 0; i < entttSNumber; i++) { //Create entity context->CreateAndAddEntity(); //Link component to entity context->AddComponentToEntity<Integer>(context->GetEntity(i), Integer(0)); if (i % 2) { context->AddComponentToEntity<Boolean>(context->GetEntity(i), Boolean()); } } context->RemoveComponentToEntity<Integer>(context->GetEntity(3)); context->AddComponentToEntity<Integer>(context->GetEntity(3), Integer(0)); { std::vector< Integer*> ii; context->GetTypes<Integer>(ii); //___________________________________________________________ clock_t begin_time = clock(); for (size_t j = 0; j < ii.size(); j++) { ii[j]->integer += 5; } std::cout << "ecs time " << clock() - begin_time << std::endl; std::cout << "ecs time " << float(clock() - begin_time) << std::endl; ii.clear(); ii.shrink_to_fit(); //___________________________________________________________ std::list<ClassTest*> v; for (size_t i = 0; i < entttSNumber; i++) { v.emplace(v.end(), new ClassTest()); } clock_t begin_time0 = clock(); for (auto vEl : v) { vEl->Adding(); } std::cout << "class time " << clock() - begin_time << std::endl; std::cout << "class time " << float(clock() - begin_time0) << std::endl;; //___________________________________________________________ for (auto vEl : v) { delete vEl; } v.clear(); delete context; } }
18.481132
105
0.654416
oWASDo
11aea2549bf0a5d545908508a65fe7247dcfbdcb
11,430
cpp
C++
src/platform/DBlmdb.cpp
mygirl8893/evo
c90f69ad6132c426042749ff3fe4174d22aa63b2
[ "MIT" ]
1
2019-05-20T01:00:40.000Z
2019-05-20T01:00:40.000Z
src/platform/DBlmdb.cpp
mygirl8893/evo
c90f69ad6132c426042749ff3fe4174d22aa63b2
[ "MIT" ]
4
2018-05-07T07:15:53.000Z
2018-06-01T19:35:46.000Z
src/platform/DBlmdb.cpp
mygirl8893/evo
c90f69ad6132c426042749ff3fe4174d22aa63b2
[ "MIT" ]
10
2018-05-09T10:45:07.000Z
2020-01-11T17:21:28.000Z
#include "DBlmdb.hpp" #include <boost/lexical_cast.hpp> #include <iostream> #include "PathTools.hpp" using namespace platform; #ifdef _WIN32 #pragma comment(lib, "ntdll.lib") // dependency of lmdb, here to avoid linker arguments #endif static void lmdb_check(int rc, const char *msg) { if (rc != MDB_SUCCESS) throw platform::lmdb::Error(msg + std::to_string(rc)); } platform::lmdb::Env::Env() { lmdb_check(::mdb_env_create(&handle), "mdb_env_create "); } platform::lmdb::Env::~Env() { ::mdb_env_close(handle); handle = nullptr; } platform::lmdb::Txn::Txn(Env &db_env) { lmdb_check(::mdb_txn_begin(db_env.handle, nullptr, 0, &handle), "mdb_txn_begin "); } void platform::lmdb::Txn::commit() { lmdb_check(::mdb_txn_commit(handle), "mdb_txn_commit "); handle = nullptr; } platform::lmdb::Txn::~Txn() { ::mdb_txn_abort(handle); handle = nullptr; } // ::mdb_dbi_close should never be called according to docs platform::lmdb::Dbi::Dbi(Txn &db_txn) { lmdb_check(::mdb_dbi_open(db_txn.handle, nullptr, 0, &handle), "mdb_dbi_open "); } bool platform::lmdb::Dbi::get(Txn &db_txn, MDB_val *const key, MDB_val *const data) { const int rc = ::mdb_get(db_txn.handle, handle, key, data); if (rc != MDB_SUCCESS && rc != MDB_NOTFOUND) throw Error("mdb_get " + std::to_string(rc)); return (rc == MDB_SUCCESS); } platform::lmdb::Cur::Cur(Txn &db_txn, Dbi &db_dbi) { lmdb_check(::mdb_cursor_open(db_txn.handle, db_dbi.handle, &handle), "mdb_cursor_open "); } platform::lmdb::Cur::Cur(Cur &&other) noexcept { std::swap(handle, other.handle); } bool platform::lmdb::Cur::get(MDB_val *const key, MDB_val *const data, const MDB_cursor_op op) { const int rc = ::mdb_cursor_get(handle, key, data, op); if (rc != MDB_SUCCESS && rc != MDB_NOTFOUND) throw Error("mdb_cursor_get" + std::to_string(rc)); return (rc == MDB_SUCCESS); } platform::lmdb::Cur::~Cur() { ::mdb_cursor_close(handle); handle = nullptr; } DBlmdb::DBlmdb(const std::string &full_path, uint64_t max_db_size) : full_path(full_path) { std::cout << "lmdb libversion=" << mdb_version(nullptr, nullptr, nullptr) << std::endl; lmdb_check(::mdb_env_set_mapsize(db_env.handle, max_db_size), "mdb_env_set_mapsize "); create_directories_if_necessary(full_path); lmdb_check(::mdb_env_open(db_env.handle, full_path.c_str(), MDB_NOMETASYNC, 0644), "mdb_env_open "); // MDB_NOMETASYNC - We agree to trade chance of losing 1 last transaction for 2x performance boost db_txn.reset(new lmdb::Txn(db_env)); db_dbi.reset(new lmdb::Dbi(*db_txn)); } size_t DBlmdb::test_get_approximate_size() const { MDB_stat sta{}; lmdb_check(::mdb_env_stat(db_env.handle, &sta), "mdb_env_stat "); return sta.ms_psize * (sta.ms_branch_pages + sta.ms_leaf_pages + sta.ms_overflow_pages); } size_t DBlmdb::get_approximate_items_count() const { MDB_stat sta{}; lmdb_check(::mdb_env_stat(db_env.handle, &sta), "mdb_env_stat "); return sta.ms_entries; } DBlmdb::Cursor::Cursor( lmdb::Cur &&cur, const std::string &prefix, const std::string &middle, size_t max_key_size, bool forward) : db_cur(std::move(cur)), prefix(prefix), forward(forward) { std::string start = prefix + middle; lmdb::Val itkey(start); if (forward) is_end = !db_cur.get(itkey, data, start.empty() ? MDB_FIRST : MDB_SET_RANGE); else { if (start.empty()) is_end = !db_cur.get(itkey, data, MDB_LAST); else { if (start.size() < max_key_size) start += std::string(max_key_size - start.size(), char(0xff)); itkey = lmdb::Val(start); is_end = !db_cur.get(itkey, data, MDB_SET_RANGE); is_end = !db_cur.get(itkey, data, is_end ? MDB_LAST : MDB_PREV); // If failed to find a key >= prefix, then it should be last in db } } check_prefix(itkey); } void DBlmdb::Cursor::next() { lmdb::Val itkey; is_end = !db_cur.get(itkey, &*data, forward ? MDB_NEXT : MDB_PREV); check_prefix(itkey); } void DBlmdb::Cursor::erase() { if (is_end) return; // Some precaution lmdb_check(::mdb_cursor_del(db_cur.handle, 0), "mdb_cursor_del "); next(); } void DBlmdb::Cursor::check_prefix(const lmdb::Val &itkey) { if (is_end || itkey.size() < prefix.size() || std::char_traits<char>::compare(prefix.data(), itkey.data(), prefix.size()) != 0) { is_end = true; data = lmdb::Val{}; suffix = std::string(); return; } suffix = std::string(itkey.data() + prefix.size(), itkey.size() - prefix.size()); } std::string DBlmdb::Cursor::get_value_string() const { return std::string(data.data(), data.size()); } common::BinaryArray DBlmdb::Cursor::get_value_array() const { return common::BinaryArray(data.data(), data.data() + data.size()); } DBlmdb::Cursor DBlmdb::begin(const std::string &prefix, const std::string &middle) const { int max_key_size = ::mdb_env_get_maxkeysize(db_env.handle); return Cursor(lmdb::Cur(*db_txn, *db_dbi), prefix, middle, max_key_size, true); } DBlmdb::Cursor DBlmdb::rbegin(const std::string &prefix, const std::string &middle) const { int max_key_size = ::mdb_env_get_maxkeysize(db_env.handle); return Cursor(lmdb::Cur(*db_txn, *db_dbi), prefix, middle, max_key_size, false); } void DBlmdb::commit_db_txn() { db_txn->commit(); db_txn.reset(); db_txn.reset(new lmdb::Txn(db_env)); } void DBlmdb::put(const std::string &key, const common::BinaryArray &value, bool nooverwrite) { lmdb::Val temp_value(value.data(), value.size()); const int rc = ::mdb_put(db_txn->handle, db_dbi->handle, lmdb::Val(key), temp_value, nooverwrite ? MDB_NOOVERWRITE : 0); if (rc != MDB_SUCCESS && rc != MDB_KEYEXIST) throw lmdb::Error("DBlmdb::put failed " + std::string(key.data(), key.size())); if (nooverwrite && rc == MDB_KEYEXIST) throw lmdb::Error( "DBlmdb::put failed or nooverwrite key already exists " + std::string(key.data(), key.size())); } void DBlmdb::put(const std::string &key, const std::string &value, bool nooverwrite) { lmdb::Val temp_value(value.data(), value.size()); const int rc = ::mdb_put(db_txn->handle, db_dbi->handle, lmdb::Val(key), temp_value, nooverwrite ? MDB_NOOVERWRITE : 0); if (rc != MDB_SUCCESS && rc != MDB_KEYEXIST) throw lmdb::Error("DBlmdb::put failed " + std::string(key.data(), key.size())); if (nooverwrite && rc == MDB_KEYEXIST) throw lmdb::Error( "DBlmdb::put failed or nooverwrite key already exists " + std::string(key.data(), key.size())); } bool DBlmdb::get(const std::string &key, common::BinaryArray &value) const { lmdb::Val val1; if (!db_dbi->get(*db_txn, lmdb::Val(key), val1)) return false; value.assign(val1.data(), val1.data() + val1.size()); return true; } bool DBlmdb::get(const std::string &key, std::string &value) const { lmdb::Val val1; if (!db_dbi->get(*db_txn, lmdb::Val(key), val1)) return false; value = std::string(val1.data(), val1.size()); return true; } bool DBlmdb::get(const std::string &key, Value &value) const { return db_dbi->get(*db_txn, lmdb::Val(key), value); } void DBlmdb::del(const std::string &key, bool mustexist) { const int rc = ::mdb_del(db_txn->handle, db_dbi->handle, lmdb::Val(key), nullptr); if (rc != MDB_SUCCESS && rc != MDB_NOTFOUND) throw lmdb::Error("DBlmdb::del failed " + std::string(key.data(), key.size())); if (mustexist && rc == MDB_NOTFOUND) // Soemtimes lmdb returns 0 for non existing keys, we have to get our own check upwards throw lmdb::Error("DBlmdb::del key does not exist " + std::string(key.data(), key.size())); } std::string DBlmdb::to_ascending_key(uint32_t key) { char buf[32] = {}; sprintf(buf, "%08X", key); return std::string(buf); } uint32_t DBlmdb::from_ascending_key(const std::string &key) { return boost::lexical_cast<uint32_t>(std::stoull(key, nullptr, 16)); } std::string DBlmdb::clean_key(const std::string &key) { std::string result = key; for (char &ch : result) { unsigned char uch = ch; if (uch >= 128) uch -= 128; if (uch == 127) uch = 'F'; if (uch < 32) uch = '0' + uch; ch = uch; } return result; } void DBlmdb::delete_db(const std::string &path) { std::remove((path + "/data.mdb").c_str()); std::remove((path + "/lock.mdb").c_str()); std::remove(path.c_str()); } void DBlmdb::run_tests() { delete_db("temp_db"); { DBlmdb db("temp_db"); db.put("history/ha", "ua", false); db.put("history/hb", "ub", false); db.put("history/hc", "uc", false); db.put("unspent/ua", "ua", false); db.put("unspent/ub", "ub", false); db.put("unspent/uc", "uc", false); std::cout << "-- all keys forward --" << std::endl; for (auto cur = db.begin(std::string()); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- all keys backward --" << std::endl; for (auto cur = db.rbegin(std::string()); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- history forward --" << std::endl; for (auto cur = db.begin("history/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- history backward --" << std::endl; for (auto cur = db.rbegin("history/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- unspent forward --" << std::endl; for (auto cur = db.begin("unspent/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- unspent backward --" << std::endl; for (auto cur = db.rbegin("unspent/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- alpha forward --" << std::endl; for (auto cur = db.begin("alpha/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- alpha backward --" << std::endl; for (auto cur = db.rbegin("alpha/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- zero forward --" << std::endl; for (auto cur = db.begin("zero/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- zero backward --" << std::endl; for (auto cur = db.rbegin("zero/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } int c = 0; std::cout << "-- deleting c=2 iterating forward --" << std::endl; for (auto cur = db.begin(std::string()); !cur.end(); ++c) { if (c == 2) { std::cout << "deleting " << cur.get_suffix() << std::endl; cur.erase(); } else { std::cout << cur.get_suffix() << std::endl; cur.next(); } } std::cout << "-- all keys forward --" << std::endl; for (auto cur = db.begin(std::string()); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } c = 0; std::cout << "-- deleting c=2 iterating backward --" << std::endl; for (auto cur = db.rbegin(std::string()); !cur.end(); ++c) { if (c == 2) { std::cout << "deleting " << cur.get_suffix() << std::endl; cur.erase(); } else { std::cout << cur.get_suffix() << std::endl; cur.next(); } } std::cout << "-- all keys forward --" << std::endl; for (auto cur = db.begin(std::string()); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } } delete_db("temp_db"); }
35.830721
117
0.626859
mygirl8893
11afd35840a70a13c2cda758bb4e90d370e3391a
1,578
cpp
C++
src/AdcNode.cpp
elbowz/yahnc
5ffe8adcad19f25b31a252f330fe8e29d1891b4f
[ "MIT" ]
null
null
null
src/AdcNode.cpp
elbowz/yahnc
5ffe8adcad19f25b31a252f330fe8e29d1891b4f
[ "MIT" ]
null
null
null
src/AdcNode.cpp
elbowz/yahnc
5ffe8adcad19f25b31a252f330fe8e29d1891b4f
[ "MIT" ]
null
null
null
#include "AdcNode.hpp" extern int __get_adc_mode(); /** * TODO: * * manage status topic: isnan(ESP.getVcc()) => setProperty(cStatusTopic).send("error") * note: check what happen when no wire is connected to ADC pin */ AdcNode::AdcNode(const char *id, const char *name, uint32_t readInterval, float sendOnChangeAbs, const SensorBase<float>::ReadMeasurementFunc &readMeasurementFunc, const SensorBase<float>::SendMeasurementFunc &sendMeasurementFunc, const SensorBase<float>::OnChangeFunc &onChangeFunc) : BaseNode(id, name, "adc"), SensorBase(id, readInterval, 0, sendOnChangeAbs, readMeasurementFunc, sendMeasurementFunc, onChangeFunc) { // ADC pin used to measure VCC (e.g. on battery) // true if previously called macro ADC_MODE(ADC_VCC) mReadVcc = __get_adc_mode() == ADC_VCC; } void AdcNode::setup() { advertise(SensorBase::getName()) .setDatatype("float") .setFormat("0:1.00") .setUnit(cUnitVolt); } void AdcNode::loop() { SensorBase::loop(); } float AdcNode::readMeasurement() { if (mReadMeasurementFunc) { return mReadMeasurementFunc(); } return static_cast<float>(mReadVcc ? ESP.getVcc() : analogRead(A0)) / 1024.0f; } void AdcNode::sendMeasurement(float value) const { if (mSendMeasurementFunc) { return mSendMeasurementFunc(value); } if (Homie.isConnected()) { setProperty(SensorBase::getName()).send(String(value)); } }
27.684211
116
0.63815
elbowz
11b034306b11b95efa9bcd9811c5145ad39314a5
5,049
cpp
C++
3rdparty/stout/tests/lambda_tests.cpp
sagar8192/mesos
a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7
[ "Apache-2.0" ]
null
null
null
3rdparty/stout/tests/lambda_tests.cpp
sagar8192/mesos
a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7
[ "Apache-2.0" ]
null
null
null
3rdparty/stout/tests/lambda_tests.cpp
sagar8192/mesos
a018cf33d5f06f5a9f9099a4c74b2daea00bd0f7
[ "Apache-2.0" ]
null
null
null
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License #include <gtest/gtest.h> #include <stout/lambda.hpp> #include <stout/numify.hpp> struct OnlyMoveable { OnlyMoveable() : i(-1) {} OnlyMoveable(int i) : i(i) {} OnlyMoveable(OnlyMoveable&& that) { *this = std::move(that); } OnlyMoveable(const OnlyMoveable&) = delete; OnlyMoveable& operator=(OnlyMoveable&& that) { i = that.i; j = that.j; that.valid = false; return *this; } OnlyMoveable& operator=(const OnlyMoveable&) = delete; int i; int j = 0; bool valid = true; }; std::vector<std::string> function() { return {"1", "2", "3"}; } TEST(LambdaTest, Map) { std::vector<int> expected = {1, 2, 3}; EXPECT_EQ( expected, lambda::map( [](std::string s) { return numify<int>(s).get(); }, std::vector<std::string>{"1", "2", "3"})); EXPECT_EQ( expected, lambda::map( [](const std::string& s) { return numify<int>(s).get(); }, std::vector<std::string>{"1", "2", "3"})); EXPECT_EQ( expected, lambda::map( [](std::string&& s) { return numify<int>(s).get(); }, std::vector<std::string>{"1", "2", "3"})); std::vector<std::string> concat = {"11", "22", "33"}; EXPECT_EQ( concat, lambda::map( [](std::string&& s) { return s + s; }, function())); std::vector<OnlyMoveable> v; v.emplace_back(1); v.emplace_back(2); std::vector<OnlyMoveable> result = lambda::map( [](OnlyMoveable&& o) { o.j = o.i; return std::move(o); }, std::move(v)); for (const OnlyMoveable& o : result) { EXPECT_EQ(o.i, o.j); } } namespace { template <typename F, typename ...Args> auto callable(F&& f, Args&&... args) -> decltype(std::forward<F>(f)(std::forward<Args>(args)...), void(), std::true_type()); template <typename F> std::false_type callable(F&& f, ...); // Compile-time check that f cannot be called with specified arguments. // This is implemented by defining two callable function overloads and // differentiating on return type. The first overload is selected only // when call expression is valid, and it has return type of std::true_type, // while second overload is selected for everything else. template <typename F, typename ...Args> void EXPECT_CALL_INVALID(F&& f, Args&&... args) { static_assert( !decltype( callable(std::forward<F>(f), std::forward<Args>(args)...))::value, "call expression is expected to be invalid"); } } // namespace { namespace { int returnIntNoParams() { return 8; } void returnVoidStringParam(std::string s) {} void returnVoidStringCRefParam(const std::string& s) {} int returnIntOnlyMovableParam(OnlyMoveable o) { EXPECT_TRUE(o.valid); return 1; } } // namespace { // This is mostly a compile time test of lambda::partial, // verifying that it works for different types of expressions. TEST(PartialTest, Test) { // standalone functions auto p1 = lambda::partial(returnIntNoParams); int p1r1 = p1(); int p1r2 = std::move(p1)(); EXPECT_EQ(p1r1, p1r2); auto p2 = lambda::partial(returnVoidStringParam, ""); p2(); std::move(p2)(); auto p3 = lambda::partial(returnVoidStringParam, lambda::_1); p3(""); std::move(p3)(""); auto p4 = lambda::partial(&returnVoidStringCRefParam, lambda::_1); p4(""); std::move(p4)(""); auto p5 = lambda::partial(&returnIntOnlyMovableParam, lambda::_1); p5(OnlyMoveable()); p5(10); std::move(p5)(OnlyMoveable()); auto p6 = lambda::partial(&returnIntOnlyMovableParam, OnlyMoveable()); EXPECT_CALL_INVALID(p6); std::move(p6)(); // lambdas auto l1 = [](const OnlyMoveable& m) { EXPECT_TRUE(m.valid); }; auto pl1 = lambda::partial(l1, OnlyMoveable()); pl1(); pl1(); std::move(pl1)(); auto pl2 = lambda::partial([](OnlyMoveable&& m) { EXPECT_TRUE(m.valid); }, lambda::_1); pl2(OnlyMoveable()); pl2(OnlyMoveable()); std::move(pl2)(OnlyMoveable()); auto pl3 = lambda::partial([](OnlyMoveable&& m) { EXPECT_TRUE(m.valid); }, OnlyMoveable()); EXPECT_CALL_INVALID(pl3); std::move(pl3)(); // member functions struct Object { int method() { return 0; }; }; auto mp1 = lambda::partial(&Object::method, lambda::_1); mp1(Object()); std::move(mp1)(Object()); auto mp2 = lambda::partial(&Object::method, Object()); mp2(); std::move(mp2)(); }
22.44
76
0.614379
sagar8192
11b81cd2f6dc35ce782342449966f5893f99bdb2
1,330
cpp
C++
tests/network_common.cpp
Andrei-Masilevich/barbacoa-server-lib
2eda2fab20c6c1d5a8a78b71952ca61330d04878
[ "MIT" ]
null
null
null
tests/network_common.cpp
Andrei-Masilevich/barbacoa-server-lib
2eda2fab20c6c1d5a8a78b71952ca61330d04878
[ "MIT" ]
null
null
null
tests/network_common.cpp
Andrei-Masilevich/barbacoa-server-lib
2eda2fab20c6c1d5a8a78b71952ca61330d04878
[ "MIT" ]
null
null
null
#include "network_common.h" #include <server_lib/platform_config.h> #if defined(SERVER_LIB_PLATFORM_LINUX) #include <sys/socket.h> #include <netinet/ip.h> #include <sys/types.h> #endif namespace server_lib { namespace tests { uint16_t basic_network_fixture::get_free_port() { int result = 0; #if defined(SERVER_LIB_PLATFORM_LINUX) int max_loop = 5; int socket_fd = -1; while (result < 1024 && --max_loop > 0) { struct sockaddr_in sin; socket_fd = socket(AF_INET, SOCK_STREAM, 0); if (socket_fd == -1) return -1; sin.sin_family = AF_INET; sin.sin_port = 0; sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK); if (bind(socket_fd, (struct sockaddr*)&sin, sizeof(struct sockaddr_in)) == -1) break; socklen_t len = sizeof(sin); if (getsockname(socket_fd, (struct sockaddr*)&sin, &len) == -1) break; result = sin.sin_port; close(socket_fd); socket_fd = -1; } if (socket_fd > 0) close(socket_fd); #endif if (result < 1024) return get_default_port(); return static_cast<uint16_t>(result); } } // namespace tests } // namespace server_lib
27.142857
90
0.566917
Andrei-Masilevich
11b84455382fe2f87c88031e8a87b9b3cd4897ac
549
cpp
C++
etc/cpsco2019-s1/e/main.cpp
wotsushi/competitive-programming
17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86
[ "MIT" ]
3
2019-06-25T06:17:38.000Z
2019-07-13T15:18:51.000Z
etc/cpsco2019-s1/e/main.cpp
wotsushi/competitive-programming
17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86
[ "MIT" ]
null
null
null
etc/cpsco2019-s1/e/main.cpp
wotsushi/competitive-programming
17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86
[ "MIT" ]
null
null
null
#include "template.hpp" int main() { ll(N, Q); vll(A, N); vll(L, R, X, Q); set<ll> S; each(a, A) { if (S.count(a)) { S.erase(a); } else { S.insert(a); } } rep(i, Q) { ll ans = 0; ll c = 0; vi D; for (auto j = S.lower_bound(L[i]); j != S.end() and *j <= R[i]; ++j) { ans ^= *j; D.push_back(*j); ++c; } each(d, D) { S.erase(d); } out(ans); if (c & 1) { if (S.count(X[i])) { S.erase(X[i]); } else { S.insert(X[i]); } } } }
15.685714
74
0.369763
wotsushi
11b9d47dd38ffb40e49306220e5122fc23a174a0
1,016
hpp
C++
src/View/HeatMapView.hpp
dlasalle/matrixinspector
7fc1b0065c2ea2cd01de58a96c2ffa99a9c2659e
[ "MIT" ]
2
2018-02-04T21:10:14.000Z
2018-02-13T15:24:28.000Z
src/View/HeatMapView.hpp
dlasalle/matrixinspector
7fc1b0065c2ea2cd01de58a96c2ffa99a9c2659e
[ "MIT" ]
15
2017-09-05T20:55:04.000Z
2018-12-21T09:12:21.000Z
src/View/HeatMapView.hpp
dlasalle/matrixinspector
7fc1b0065c2ea2cd01de58a96c2ffa99a9c2659e
[ "MIT" ]
null
null
null
/** * @file HeatMapView.hpp * @brief The HeatMapView class. * @author Dominique LaSalle <dominique@solidlake.com> * Copyright 2017 * @version 1 */ #ifndef MATRIXINSPECTOR_VIEW_HEATMAPVIEW_HPP #define MATRIXINSPECTOR_VIEW_HEATMAPVIEW_HPP #include "View.hpp" #include "HeatMap.hpp" namespace MatrixInspector { class HeatMapView : public View { public: HeatMapView( wxFrame * parent); ~HeatMapView(); void draw() override; void refresh() override; private: HeatMap m_heatmap; GLuint m_glTexture; wxPoint m_mousePos; float m_zoom; float m_originX; float m_originY; void onMouseMove( wxMouseEvent& event); void onKey( wxKeyEvent& event); void onWheel( wxMouseEvent& event); void releaseTexture(); // disable copying HeatMapView( HeatMapView const & rhs); HeatMapView& operator=( HeatMapView const & rhs); wxDECLARE_EVENT_TABLE(); }; } #endif
10.924731
54
0.642717
dlasalle
11c856e5b8f6ef982b1e821a187aca4b82ca19d3
3,677
cpp
C++
Plugins/Mipf_Plugin_ASM/GenerateTrainingSetView.cpp
linson7017/MIPF
adf982ae5de69fca9d6599fbbbd4ca30f4ae9767
[ "ECL-2.0", "Apache-2.0" ]
4
2017-04-13T06:01:49.000Z
2019-12-04T07:23:53.000Z
Plugins/Mipf_Plugin_ASM/GenerateTrainingSetView.cpp
linson7017/MIPF
adf982ae5de69fca9d6599fbbbd4ca30f4ae9767
[ "ECL-2.0", "Apache-2.0" ]
1
2017-10-27T02:00:44.000Z
2017-10-27T02:00:44.000Z
Plugins/Mipf_Plugin_ASM/GenerateTrainingSetView.cpp
linson7017/MIPF
adf982ae5de69fca9d6599fbbbd4ca30f4ae9767
[ "ECL-2.0", "Apache-2.0" ]
2
2017-09-06T01:59:07.000Z
2019-12-04T07:23:54.000Z
#include "GenerateTrainingSetView.h" //qt #include <QFileDialog> //qf #include "iqf_main.h" //mipf #include "MitkMain/IQF_MitkIO.h" #include "MitkMain/IQF_MitkDataManager.h" #include "ITKImageTypeDef.h" //itk #include <itkImage.h> #include <itkChangeInformationImageFilter.h> //mitk #include "mitkImage.h" #include "mitkImageCast.h" #include "mitkDataNode.h" #include "mitkRenderingManager.h" #include "ITK_Helpers.h" GenerateTrainingSetView::GenerateTrainingSetView(QF::IQF_Main* pMain, QWidget* parent) :QWidget(parent), m_pMain(pMain) { m_ui.setupUi(this); m_ui.ImageList->setHeaderLabels(QStringList() << "Name" << "Path"); connect(m_ui.DataDirBrowseBtn, &QPushButton::clicked, this, &GenerateTrainingSetView::DataDirBrowseFile); connect(m_ui.OutputDirBrowseBtn, &QPushButton::clicked, this, &GenerateTrainingSetView::OutputDirBrowseFile); connect(m_ui.ApplyBtn, &QPushButton::clicked, this, &GenerateTrainingSetView::Apply); } GenerateTrainingSetView::~GenerateTrainingSetView() { } void GenerateTrainingSetView::DataDirBrowseFile() { QString dirStr = QFileDialog::getExistingDirectory(this, "Select An Directory."); if (dirStr.isEmpty()) { return; } m_ui.DataDirLE->setText(dirStr); QDir dir(dirStr); QFileInfoList files = dir.entryInfoList(QDir::Files, QDir::Name); m_ui.ImageList->clear(); QList<QTreeWidgetItem*> items; foreach(QFileInfo fileInfo, files) { QTreeWidgetItem* item = new QTreeWidgetItem(QStringList() << fileInfo.fileName() << fileInfo.filePath()); items.append(item); } m_ui.ImageList->addTopLevelItems(items); } void GenerateTrainingSetView::OutputDirBrowseFile() { QString dirStr = QFileDialog::getExistingDirectory(this, "Select An Directory."); if (dirStr.isEmpty()) { return; } m_ui.OutputDirLE->setText(dirStr); } template <class TImageType> void CreateBaseImage(TImageType* input, TImageType*output) { } void GenerateTrainingSetView::Apply() { IQF_MitkDataManager* pDataManager = (IQF_MitkDataManager*)m_pMain->GetInterfacePtr(QF_MitkMain_DataManager); IQF_MitkIO* pIO = (IQF_MitkIO*)m_pMain->GetInterfacePtr(QF_MitkMain_IO); for (int i=0;i<m_ui.ImageList->topLevelItemCount();i++) { QString resultName = QString("TrainData%1").arg(i); mitk::DataNode* node = pIO->Load(m_ui.ImageList->topLevelItem(i)->text(1).toStdString().c_str()); if (!node) { return; } mitk::Image* mitkImage = dynamic_cast<mitk::Image*>(node->GetData()); UChar3DImageType::Pointer itkImage; mitk::CastToItkImage(mitkImage, itkImage); UChar3DImageType::Pointer output = UChar3DImageType::New(); int size[3] = { 256,128,256 }; double spacing[3] = {2,4,2}; ITKHelpers::ExtractCentroidImageWithGivenSize(itkImage.GetPointer(), output.GetPointer(), size, spacing); typedef itk::ChangeInformationImageFilter< UChar3DImageType > CenterFilterType; CenterFilterType::Pointer center = CenterFilterType::New(); center->CenterImageOn(); center->SetInput(output); center->Update(); mitk::Image::Pointer image; mitk::CastToMitkImage(center->GetOutput(), image); mitk::DataNode::Pointer on = mitk::DataNode::New(); on->SetData(image); on->SetName(resultName.toStdString().c_str()); pDataManager->GetDataStorage()->Add(on); pDataManager->GetDataStorage()->Remove(node); ITKHelpers::SaveImage(center->GetOutput(), m_ui.OutputDirLE->text().append("/%1.mha").arg(resultName).toStdString()); } }
30.139344
125
0.689693
linson7017
11c990bba3548437b8697512c79b1e1ee915992f
310
cpp
C++
imposc-service/imposc-cpp/charts/src/charts.cpp
FelixDux/imposccpp
c8c612df87a53ddaca6260816c913ade44adbe6d
[ "MIT" ]
null
null
null
imposc-service/imposc-cpp/charts/src/charts.cpp
FelixDux/imposccpp
c8c612df87a53ddaca6260816c913ade44adbe6d
[ "MIT" ]
1
2021-03-22T17:27:17.000Z
2021-07-02T07:31:39.000Z
imposc-service/imposc-cpp/charts/src/charts.cpp
FelixDux/imposccpp
c8c612df87a53ddaca6260816c913ade44adbe6d
[ "MIT" ]
null
null
null
#include "charts.hpp" #include "forcing_phase.hpp" #include "gnuplot_if.hpp" using namespace dynamics; namespace charts { void plot_impacts(const std::vector<Impact> &impacts, const std::string &outfile, const Parameters &params) { do_plot( {prepare_plot(impacts, "", "dots")}, outfile, params); } }
20.666667
108
0.722581
FelixDux
11c9f91d07c85dee71b7c0636643cac4ca80b346
14,275
cpp
C++
src/kits/midi2/MidiRosterLooper.cpp
stasinek/BHAPI
5d9aa61665ae2cc5c6e34415957d49a769325b2b
[ "BSD-3-Clause", "MIT" ]
3
2018-05-21T15:32:32.000Z
2019-03-21T13:34:55.000Z
src/kits/midi2/MidiRosterLooper.cpp
stasinek/BHAPI
5d9aa61665ae2cc5c6e34415957d49a769325b2b
[ "BSD-3-Clause", "MIT" ]
null
null
null
src/kits/midi2/MidiRosterLooper.cpp
stasinek/BHAPI
5d9aa61665ae2cc5c6e34415957d49a769325b2b
[ "BSD-3-Clause", "MIT" ]
null
null
null
/* * Copyright 2006, Haiku. * * Copyright (c) 2002-2004 Matthijs Hollemans * Distributed under the terms of the MIT License. * * Authors: * Matthijs Hollemans */ #include <kits/debug/Debug.h> #include <MidiConsumer.h> #include <MidiProducer.h> #include <MidiRoster.h> #include <MidiRosterLooper.h> #include <protocol.h> using namespace BPrivate; BMidiRosterLooper::BMidiRosterLooper() : BLooper("MidiRosterLooper") { fInitLock = -1; fRoster = NULL; fWatcher = NULL; } BMidiRosterLooper::~BMidiRosterLooper() { StopWatching(); if (fInitLock >= B_OK) { delete_sem(fInitLock); } // At this point, our list may still contain endpoints with a // zero reference count. These objects are proxies for remote // endpoints, so we can safely delete them. If the list also // contains endpoints with a non-zero refcount (which can be // either remote or local), we will output a warning message. // It would have been better to jump into the debugger, but I // did not want to risk breaking any (misbehaving) old apps. for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); if (endp->fRefCount > 0) { fprintf( stderr, "[midi] WARNING: Endpoint %" B_PRId32 " (%p) has " "not been Release()d properly (refcount = %" B_PRId32 ")\n", endp->ID(), endp, endp->fRefCount); } else { delete endp; } } } bool BMidiRosterLooper::Init(BMidiRoster* roster_) { ASSERT(roster_ != NULL) fRoster = roster_; // We create a semaphore with a zero count. BMidiRoster's // MidiRoster() method will try to acquire this semaphore, // but blocks because the count is 0. When we receive the // "app registered" message in our MessageReceived() hook, // we release the semaphore and MidiRoster() will unblock. fInitLock = create_sem(0, "InitLock"); if (fInitLock < B_OK) { WARN("Could not create semaphore") return false; } thread_id threadId = Run(); if (threadId < B_OK) { WARN("Could not start looper thread") return false; } return true; } BMidiEndpoint* BMidiRosterLooper::NextEndpoint(int32* id) { ASSERT(id != NULL) for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); if (endp->ID() > *id) { if (endp->IsRemote() && endp->IsRegistered()) { *id = endp->ID(); return endp; } } } return NULL; } BMidiEndpoint* BMidiRosterLooper::FindEndpoint(int32 id) { for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); if (endp->ID() == id) { return endp; } } return NULL; } void BMidiRosterLooper::AddEndpoint(BMidiEndpoint* endp) { ASSERT(endp != NULL) ASSERT(!fEndpoints.HasItem(endp)) // We store the endpoints sorted by ID, because that // simplifies the implementation of NextEndpoint(). // Although the midi_server assigns IDs in ascending // order, we can't assume that the mNEW messages also // are delivered in this order (mostly they will be). int32 t; for (t = CountEndpoints(); t > 0; --t) { BMidiEndpoint* other = EndpointAt(t - 1); if (endp->ID() > other->ID()) { break; } } fEndpoints.AddItem(endp, t); #ifdef DEBUG DumpEndpoints(); #endif } void BMidiRosterLooper::RemoveEndpoint(BMidiEndpoint* endp) { ASSERT(endp != NULL) ASSERT(fEndpoints.HasItem(endp)) fEndpoints.RemoveItem(endp); if (endp->IsConsumer()) { DisconnectDeadConsumer((BMidiConsumer*) endp); } else { DisconnectDeadProducer((BMidiProducer*) endp); } #ifdef DEBUG DumpEndpoints(); #endif } void BMidiRosterLooper::StartWatching(const BMessenger* watcher_) { ASSERT(watcher_ != NULL) StopWatching(); fWatcher = new BMessenger(*watcher_); AllEndpoints(); AllConnections(); } void BMidiRosterLooper::StopWatching() { delete fWatcher; fWatcher = NULL; } void BMidiRosterLooper::MessageReceived(BMessage* msg) { #ifdef DEBUG printf("IN "); msg->PrintToStream(); #endif switch (msg->what) { case MSG_APP_REGISTERED: OnAppRegistered(msg); break; case MSG_ENDPOINT_CREATED: OnEndpointCreated(msg); break; case MSG_ENDPOINT_DELETED: OnEndpointDeleted(msg); break; case MSG_ENDPOINT_CHANGED: OnEndpointChanged(msg); break; case MSG_ENDPOINTS_CONNECTED: OnConnectedDisconnected(msg); break; case MSG_ENDPOINTS_DISCONNECTED: OnConnectedDisconnected(msg); break; default: super::MessageReceived(msg); break; } } void BMidiRosterLooper::OnAppRegistered(BMessage* msg) { release_sem(fInitLock); } void BMidiRosterLooper::OnEndpointCreated(BMessage* msg) { int32 id; bool isRegistered; BString name; BMessage properties; bool isConsumer; if ((msg->FindInt32("midi:id", &id) == B_OK) && (msg->FindBool("midi:registered", &isRegistered) == B_OK) && (msg->FindString("midi:name", &name) == B_OK) && (msg->FindMessage("midi:properties", &properties) == B_OK) && (msg->FindBool("midi:consumer", &isConsumer) == B_OK)) { if (isConsumer) { int32 port; bigtime_t latency; if ((msg->FindInt32("midi:port", &port) == B_OK) && (msg->FindInt64("midi:latency", &latency) == B_OK)) { BMidiConsumer* cons = new BMidiConsumer(); cons->fName = name; cons->fId = id; cons->fIsRegistered = isRegistered; cons->fPort = port; cons->fLatency = latency; *(cons->fProperties) = properties; AddEndpoint(cons); return; } } else { // producer BMidiProducer* prod = new BMidiProducer(); prod->fName = name; prod->fId = id; prod->fIsRegistered = isRegistered; *(prod->fProperties) = properties; AddEndpoint(prod); return; } } WARN("Could not create proxy for remote endpoint") } void BMidiRosterLooper::OnEndpointDeleted(BMessage* msg) { int32 id; if (msg->FindInt32("midi:id", &id) == B_OK) { BMidiEndpoint* endp = FindEndpoint(id); if (endp != NULL) { RemoveEndpoint(endp); // If the client is watching, and the endpoint is // registered remote, we need to let it know that // the endpoint is now unregistered. if (endp->IsRemote() && endp->IsRegistered()) { if (fWatcher != NULL) { BMessage notify; notify.AddInt32("be:op", B_MIDI_UNREGISTERED); ChangeEvent(&notify, endp); } } // If the proxy object for this endpoint is no // longer being used, we can delete it. However, // if the refcount is not zero, we must defer // destruction until the client Release()'s the // object. We clear the "isRegistered" flag to // let the client know the object is now invalid. if (endp->fRefCount == 0) { delete endp; } else { // still being used endp->fIsRegistered = false; endp->fIsAlive = false; } return; } } WARN("Could not delete proxy for remote endpoint") } void BMidiRosterLooper::OnEndpointChanged(BMessage* msg) { int32 id; if (msg->FindInt32("midi:id", &id) == B_OK) { BMidiEndpoint* endp = FindEndpoint(id); if ((endp != NULL) && endp->IsRemote()) { ChangeRegistered(msg, endp); ChangeName(msg, endp); ChangeProperties(msg, endp); ChangeLatency(msg, endp); #ifdef DEBUG DumpEndpoints(); #endif return; } } WARN("Could not change endpoint attributes") } void BMidiRosterLooper::OnConnectedDisconnected(BMessage* msg) { int32 prodId, consId; if ((msg->FindInt32("midi:producer", &prodId) == B_OK) && (msg->FindInt32("midi:consumer", &consId) == B_OK)) { BMidiEndpoint* endp1 = FindEndpoint(prodId); BMidiEndpoint* endp2 = FindEndpoint(consId); if ((endp1 != NULL) && endp1->IsProducer()) { if ((endp2 != NULL) && endp2->IsConsumer()) { BMidiProducer* prod = (BMidiProducer*) endp1; BMidiConsumer* cons = (BMidiConsumer*) endp2; bool mustConnect = (msg->what == MSG_ENDPOINTS_CONNECTED); if (mustConnect) { prod->ConnectionMade(cons); } else { prod->ConnectionBroken(cons); } if (fWatcher != NULL) { ConnectionEvent(prod, cons, mustConnect); } #ifdef DEBUG DumpEndpoints(); #endif return; } } } WARN("Could not connect/disconnect endpoints") } void BMidiRosterLooper::ChangeRegistered(BMessage* msg, BMidiEndpoint* endp) { ASSERT(msg != NULL) ASSERT(endp != NULL) bool isRegistered; if (msg->FindBool("midi:registered", &isRegistered) == B_OK) { if (endp->fIsRegistered != isRegistered) { endp->fIsRegistered = isRegistered; if (fWatcher != NULL) { BMessage notify; if (isRegistered) { notify.AddInt32("be:op", B_MIDI_REGISTERED); } else { notify.AddInt32("be:op", B_MIDI_UNREGISTERED); } ChangeEvent(&notify, endp); } } } } void BMidiRosterLooper::ChangeName(BMessage* msg, BMidiEndpoint* endp) { ASSERT(msg != NULL) ASSERT(endp != NULL) BString name; if (msg->FindString("midi:name", &name) == B_OK) { if (endp->fName != name) { endp->fName = name; if ((fWatcher != NULL) && endp->IsRegistered()) { BMessage notify; notify.AddInt32("be:op", B_MIDI_CHANGED_NAME); notify.AddString("be:name", name); ChangeEvent(&notify, endp); } } } } void BMidiRosterLooper::ChangeProperties(BMessage* msg, BMidiEndpoint* endp) { ASSERT(msg != NULL) ASSERT(endp != NULL) BMessage properties; if (msg->FindMessage("midi:properties", &properties) == B_OK) { *(endp->fProperties) = properties; if ((fWatcher != NULL) && endp->IsRegistered()) { BMessage notify; notify.AddInt32("be:op", B_MIDI_CHANGED_PROPERTIES); notify.AddMessage("be:properties", &properties); ChangeEvent(&notify, endp); } } } void BMidiRosterLooper::ChangeLatency(BMessage* msg, BMidiEndpoint* endp) { ASSERT(msg != NULL) ASSERT(endp != NULL) bigtime_t latency; if (msg->FindInt64("midi:latency", &latency) == B_OK) { if (endp->IsConsumer()) { BMidiConsumer* cons = (BMidiConsumer*) endp; if (cons->fLatency != latency) { cons->fLatency = latency; if ((fWatcher != NULL) && cons->IsRegistered()) { BMessage notify; notify.AddInt32("be:op", B_MIDI_CHANGED_LATENCY); notify.AddInt64("be:latency", latency); ChangeEvent(&notify, endp); } } } } } void BMidiRosterLooper::AllEndpoints() { BMessage notify; for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); if (endp->IsRemote() && endp->IsRegistered()) { notify.MakeEmpty(); notify.AddInt32("be:op", B_MIDI_REGISTERED); ChangeEvent(&notify, endp); } } } void BMidiRosterLooper::AllConnections() { for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); if (endp->IsRemote() && endp->IsRegistered()) { if (endp->IsProducer()) { BMidiProducer* prod = (BMidiProducer*) endp; if (prod->LockProducer()) { for (int32 k = 0; k < prod->CountConsumers(); ++k) { ConnectionEvent(prod, prod->ConsumerAt(k), true); } prod->UnlockProducer(); } } } } } void BMidiRosterLooper::ChangeEvent(BMessage* msg, BMidiEndpoint* endp) { ASSERT(fWatcher != NULL) ASSERT(msg != NULL) ASSERT(endp != NULL) msg->what = B_MIDI_EVENT; msg->AddInt32("be:id", endp->ID()); if (endp->IsConsumer()) { msg->AddString("be:type", "consumer"); } else { msg->AddString("be:type", "producer"); } fWatcher->SendMessage(msg); } void BMidiRosterLooper::ConnectionEvent( BMidiProducer* prod, BMidiConsumer* cons, bool mustConnect) { ASSERT(fWatcher != NULL) ASSERT(prod != NULL) ASSERT(cons != NULL) BMessage notify; notify.what = B_MIDI_EVENT; notify.AddInt32("be:producer", prod->ID()); notify.AddInt32("be:consumer", cons->ID()); if (mustConnect) { notify.AddInt32("be:op", B_MIDI_CONNECTED); } else { notify.AddInt32("be:op", B_MIDI_DISCONNECTED); } fWatcher->SendMessage(&notify); } void BMidiRosterLooper::DisconnectDeadConsumer(BMidiConsumer* cons) { ASSERT(cons != NULL) // Note: Rather than looping through each producer's list // of connected consumers, we let ConnectionBroken() tell // us whether the consumer really was connected. for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); if (endp->IsProducer()) { BMidiProducer* prod = (BMidiProducer*) endp; if (prod->ConnectionBroken(cons)) { if (cons->IsRemote() && (fWatcher != NULL)) { ConnectionEvent(prod, cons, false); } } } } } void BMidiRosterLooper::DisconnectDeadProducer(BMidiProducer* prod) { ASSERT(prod != NULL) // We don't need to lock or remove the consumers from // the producer's list of connections, because when this // function is called, we're destroying the object. if (prod->IsRemote() && (fWatcher != NULL)) { for (int32 t = 0; t < prod->CountConsumers(); ++t) { ConnectionEvent(prod, prod->ConsumerAt(t), false); } } } int32 BMidiRosterLooper::CountEndpoints() { return fEndpoints.CountItems(); } BMidiEndpoint* BMidiRosterLooper::EndpointAt(int32 index) { ASSERT(index >= 0 && index < CountEndpoints()) return (BMidiEndpoint*) fEndpoints.ItemAt(index); } #ifdef DEBUG void BMidiRosterLooper::DumpEndpoints() { if (Lock()) { printf("*** START DumpEndpoints\n"); for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); printf("\tendpoint %" B_PRId32 " (%p):\n", t, endp); printf( "\t\tid %" B_PRId32 ", name '%s', %s, %s, %s, %s, refcount %" B_PRId32 "\n", endp->ID(), endp->Name(), endp->IsConsumer() ? "consumer" : "producer", endp->IsRegistered() ? "registered" : "unregistered", endp->IsLocal() ? "local" : "remote", endp->IsValid() ? "valid" : "invalid", endp->fRefCount); printf("\t\tproperties: "); endp->fProperties->PrintToStream(); if (endp->IsConsumer()) { BMidiConsumer* cons = (BMidiConsumer*) endp; printf("\t\tport %" B_PRId32 ", latency %" B_PRIdBIGTIME "\n", cons->fPort, cons->fLatency); } else { BMidiProducer* prod = (BMidiProducer*) endp; if (prod->LockProducer()) { printf("\t\tconnections:\n"); for (int32 k = 0; k < prod->CountConsumers(); ++k) { BMidiConsumer* cons = prod->ConsumerAt(k); printf("\t\t\tid %" B_PRId32 " (%p)\n", cons->ID(), cons); } prod->UnlockProducer(); } } } printf("*** END DumpEndpoints\n"); Unlock(); } } #endif
22.987118
76
0.654431
stasinek
11cd6fce1f1f0eeca2ec14e83242e44739043a7e
5,574
cpp
C++
src/ace/ACE_wrappers/ACEXML/examples/SAXPrint/SAXPrint_Handler.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/examples/SAXPrint/SAXPrint_Handler.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
null
null
null
src/ace/ACE_wrappers/ACEXML/examples/SAXPrint/SAXPrint_Handler.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
17
2017-06-05T08:54:27.000Z
2021-08-29T14:19:12.000Z
// -*- C++ -*- #include "SAXPrint_Handler.h" #include "ace/ACE.h" #include "ace/Log_Msg.h" #if !defined (__ACEXML_INLINE__) # include "SAXPrint_Handler.inl" #endif /* __ACEXML_INLINE__ */ ACEXML_SAXPrint_Handler::ACEXML_SAXPrint_Handler (const ACEXML_Char* filename) : indent_ (0), fileName_(ACE::strnew (filename)), locator_ (0) { // no-op } ACEXML_SAXPrint_Handler::~ACEXML_SAXPrint_Handler (void) { delete [] this->fileName_; } void ACEXML_SAXPrint_Handler::characters (const ACEXML_Char *cdata, size_t, size_t) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%s"), cdata)); } void ACEXML_SAXPrint_Handler::endDocument (void) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); } void ACEXML_SAXPrint_Handler::endElement (const ACEXML_Char *, const ACEXML_Char *, const ACEXML_Char *qName) { this->dec_indent (); this->print_indent (); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("</%s>"), qName)); } void ACEXML_SAXPrint_Handler::endPrefixMapping (const ACEXML_Char *) { // ACE_DEBUG ((LM_DEBUG, // ACE_TEXT ("* Event endPrefixMapping (%s) ***************\n"), // prefix)); } void ACEXML_SAXPrint_Handler::ignorableWhitespace (const ACEXML_Char * cdata, int, int) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%s"), cdata)); // ACE_DEBUG ((LM_DEBUG, // ACE_TEXT ("* Event ignorableWhitespace () ***************\n"))); } void ACEXML_SAXPrint_Handler::processingInstruction (const ACEXML_Char *target, const ACEXML_Char *data) { this->print_indent (); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("<?%s %s>\n"), target, data)); } void ACEXML_SAXPrint_Handler::setDocumentLocator (ACEXML_Locator * locator) { this->locator_ = locator; //ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("* Event setDocumentLocator () ***************\n"))); } void ACEXML_SAXPrint_Handler::skippedEntity (const ACEXML_Char *name) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("* Event skippedEntity (%s) ***************\n"), name)); } void ACEXML_SAXPrint_Handler::startDocument (void) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("* Event startDocument () ***************\n"))); } void ACEXML_SAXPrint_Handler::startElement (const ACEXML_Char *, const ACEXML_Char *, const ACEXML_Char *qName, ACEXML_Attributes *alist) { this->print_indent (); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("<%s"), qName)); if (alist != 0) for (size_t i = 0; i < alist->getLength (); ++i) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" %s = \"%s\""), alist->getQName (i), alist->getValue (i))); } ACE_DEBUG ((LM_DEBUG, ACE_TEXT (">"))); this->inc_indent (); } void ACEXML_SAXPrint_Handler::startPrefixMapping (const ACEXML_Char * , const ACEXML_Char *) { // ACE_DEBUG ((LM_DEBUG, // ACE_TEXT ("* Event startPrefixMapping () ***************\n"))); // ACE_DEBUG ((LM_DEBUG, // ACE_TEXT ("Prefix = %s, URI = %s\n"), prefix, uri)); } // *** Methods inherited from ACEXML_DTDHandler. void ACEXML_SAXPrint_Handler::notationDecl (const ACEXML_Char *, const ACEXML_Char *, const ACEXML_Char *) { // No-op. } void ACEXML_SAXPrint_Handler::unparsedEntityDecl (const ACEXML_Char *, const ACEXML_Char *, const ACEXML_Char *, const ACEXML_Char *) { // No-op. } // Methods inherited from ACEXML_EnitityResolver. ACEXML_InputSource * ACEXML_SAXPrint_Handler::resolveEntity (const ACEXML_Char *, const ACEXML_Char *) { // No-op. return 0; } // Methods inherited from ACEXML_ErrorHandler. /* * Receive notification of a recoverable error. */ void ACEXML_SAXPrint_Handler::error (ACEXML_SAXParseException & ex) { ACE_DEBUG ((LM_DEBUG, "%s: line: %d col: %d ", (this->locator_->getSystemId() == 0 ? this->fileName_ : this->locator_->getSystemId()), this->locator_->getLineNumber(), this->locator_->getColumnNumber())); ex.print(); } void ACEXML_SAXPrint_Handler::fatalError (ACEXML_SAXParseException & ex) { ACE_DEBUG ((LM_DEBUG, "%s: line: %d col: %d ", (this->locator_->getSystemId() == 0 ? this->fileName_ : this->locator_->getSystemId()), this->locator_->getLineNumber(), this->locator_->getColumnNumber())); ex.print(); } void ACEXML_SAXPrint_Handler::warning (ACEXML_SAXParseException & ex) { ACE_DEBUG ((LM_DEBUG, "%s: line: %d col: %d ", (this->locator_->getSystemId() == 0 ? this->fileName_ : this->locator_->getSystemId()), this->locator_->getLineNumber(), this->locator_->getColumnNumber())); ex.print(); } void ACEXML_SAXPrint_Handler::print_indent (void) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); for (size_t i = 0; i < this->indent_; ++i) ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" "))); }
25.568807
101
0.544492
wfnex
11cdb8d22ff907a9adfd4cb8c16720795a585bfb
2,463
cpp
C++
src/libs/wavm_common/WavmUtils.cpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
1
2020-03-04T10:38:00.000Z
2020-03-04T10:38:00.000Z
src/libs/wavm_common/WavmUtils.cpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
null
null
null
src/libs/wavm_common/WavmUtils.cpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
1
2020-03-04T10:38:01.000Z
2020-03-04T10:38:01.000Z
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: WavmUtils.cpp * Author: ubuntu * * Created on April 22, 2018, 5:42 PM */ #include <string> #include <iostream> #include "keto/common/Log.hpp" #include "keto/wavm_common/WavmUtils.hpp" namespace keto { namespace wavm_common { std::string WavmUtils::readCString(Runtime::MemoryInstance* memory,I32 stringAddress) { // Validate the path name and make a local copy of it. std::string returnString; int index = 0; while(true) { int c = Runtime::memoryRef<char>(memory,stringAddress + index); if(c == 0) { break; } else { returnString += c; } index ++; }; return returnString; } std::string WavmUtils::readTypeScriptString(Runtime::MemoryInstance* memory,I32 stringAddress) { // Validate the path name and make a local copy of it. std::string returnString; int size = Runtime::memoryRef<char>(memory,stringAddress); size += Runtime::memoryRef<char>(memory,stringAddress+1) * 100; size += Runtime::memoryRef<char>(memory,stringAddress+2) * 10000; for (int index = 0; index < (size * 2); index++) { if ((int)Runtime::memoryRef<char>(memory,stringAddress + 4 + index) != 0) { returnString += (int)Runtime::memoryRef<char>(memory,stringAddress + 4 + index); } } return returnString; } std::vector<char> WavmUtils::buildTypeScriptString(const std::string& value) { int currentValue = value.length(); std::vector<char> result; for (int count = 0 ; count < 4; count++) { int mod = currentValue % 100; result.push_back((char)mod); currentValue = currentValue / 100; } for (const char character : value) { result.push_back(character); result.push_back(0); } return result; } void WavmUtils::log(uint32_t intLevel,const std::string& msg) { switch(intLevel) { case 1 : KETO_LOG_DEBUG << msg; break; case 2 : KETO_LOG_INFO << msg; break; case 3 : KETO_LOG_WARNING << msg; break; case 4 : KETO_LOG_ERROR << msg; break; case 5 : KETO_LOG_FATAL << msg; break; }; } } }
26.202128
96
0.598051
burntjam
11d338cac985ed167a065d6e891f82926344834b
2,591
cpp
C++
src/Explosion/Box.cpp
crazytuzi/CyclonePhysics
4dd47779d425d9de45a125e948b690f0e8bd1f12
[ "MIT" ]
null
null
null
src/Explosion/Box.cpp
crazytuzi/CyclonePhysics
4dd47779d425d9de45a125e948b690f0e8bd1f12
[ "MIT" ]
null
null
null
src/Explosion/Box.cpp
crazytuzi/CyclonePhysics
4dd47779d425d9de45a125e948b690f0e8bd1f12
[ "MIT" ]
null
null
null
#include "Box.h" #include "gl/glut.h" Box::Box(): bIsOverlapping(false) { body = new cyclone::RigidBody(); } Box::~Box() { delete body; } void Box::Render() const { // Get the OpenGL transformation GLfloat mat[16]; body->GetGLTransform(mat); if (bIsOverlapping) { glColor3f(0.7f, 1.f, 0.7f); } else if (body->GetAwake()) { glColor3f(1.f, 0.7f, 0.7f); } else { glColor3f(0.7f, 0.7f, 1.f); } glPushMatrix(); glMultMatrixf(mat); glScalef(halfSize.x * 2, halfSize.y * 2, halfSize.z * 2); glutSolidCube(1.f); glPopMatrix(); } void Box::RenderShadow() const { // Get the OpenGL transformation GLfloat matrix[16]; body->GetGLTransform(matrix); glPushMatrix(); glScalef(1.f, 0.f, 1.f); glMultMatrixf(matrix); glScalef(halfSize.x * 2, halfSize.y * 2, halfSize.z * 2); glutSolidCube(1.f); glPopMatrix(); } void Box::SetState(const cyclone::Vector3& position, const cyclone::Quaternion& orientation, const cyclone::Vector3& extents, const cyclone::Vector3& velocity) { body->SetPosition(position); body->SetOrientation(orientation); body->SetVelocity(velocity); body->SetRotation(cyclone::Vector3()); halfSize = extents; const auto mass = halfSize.x * halfSize.y * halfSize.z * 8.f; body->SetMass(mass); cyclone::Matrix tensor; const auto squares = halfSize * halfSize; tensor.M[0][0] = 0.3f * mass * (squares.y + squares.z); tensor.M[0][1] = tensor.M[1][0] = 0.f; tensor.M[0][2] = tensor.M[2][0] = 0.f; tensor.M[1][1] = 0.3f * mass * (squares.x + squares.z); tensor.M[1][2] = tensor.M[2][1] = 0.f; tensor.M[2][2] = 0.3f * mass * (squares.x + squares.y); tensor.M[3][3] = 1.f; body->SetInertiaTensor(tensor); body->SetLinearDamping(0.95f); body->SetAngularDamping(0.8f); body->ClearAccumulators(); body->SetAcceleration(0.f, -10.f, 0.f); body->SetAwake(); body->CalculateDerivedData(); } void Box::Random(cyclone::Random* random) { if (random != nullptr) { const static cyclone::Vector3 minPosition(-5.f, 5.f, -5.f); const static cyclone::Vector3 maxPosition(5.f, 10.0, 5.f); const static cyclone::Vector3 minSize(0.5f, 0.5f, 0.5f); const static cyclone::Vector3 maxSize(4.5f, 1.5f, 1.5f); SetState(random->RandomVector(minPosition, maxPosition), random->RandomQuaternion(), random->RandomVector(minSize, maxSize), cyclone::Vector3()); } }
19.778626
92
0.599768
crazytuzi
11d4eec341bbb7075bece8c5ac3e4a2a5e54b0cb
659
hpp
C++
credits.hpp
jasonhutchens/kranzky_ice
8b1cf40f7948ac8811cdf49729d1df0acb7fc611
[ "Unlicense" ]
4
2016-06-05T04:36:12.000Z
2016-08-21T20:11:49.000Z
credits.hpp
kranzky/kranzky_ice
8b1cf40f7948ac8811cdf49729d1df0acb7fc611
[ "Unlicense" ]
null
null
null
credits.hpp
kranzky/kranzky_ice
8b1cf40f7948ac8811cdf49729d1df0acb7fc611
[ "Unlicense" ]
null
null
null
//============================================================================== #ifndef ArseAbout #define ArseAbout #pragma once #include <context.hpp> //------------------------------------------------------------------------------ class Credits : public Context { public: Credits(); virtual ~Credits(); private: Credits( const Credits & ); Credits & operator=( const Credits & ); public: virtual void init(); virtual void fini(); virtual bool update( float dt ); virtual void render(); private: bool m_interact; }; #endif //==============================================================================
19.382353
80
0.402124
jasonhutchens
11dc5332d8f92aba3955636f5a6cc962047739e4
8,370
cpp
C++
src/AbstractTab.cpp
shtroizel/completable
f98372fc655aa8a8fcffaf9ef5e0fa8fab73a048
[ "BSD-3-Clause" ]
null
null
null
src/AbstractTab.cpp
shtroizel/completable
f98372fc655aa8a8fcffaf9ef5e0fa8fab73a048
[ "BSD-3-Clause" ]
null
null
null
src/AbstractTab.cpp
shtroizel/completable
f98372fc655aa8a8fcffaf9ef5e0fa8fab73a048
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2020, Eric Hyer All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "AbstractTab.h" #include <ncurses.h> #include "AbstractWindow.h" #include "EnablednessSetting.h" #include "Layer.h" #include "VisibilityAspect.h" #include "key_codes.h" AbstractTab::AbstractTab() : layers{ std::make_shared< matchable::MatchBox< Layer::Type, std::pair<std::vector<AbstractWindow *>, AbstractWindow *> > >() } { for (auto l : Layer::variants()) layers->mut_at(l).second = nullptr; EnablednessSetting::Borders::grab().add_enabledness_observer([&](){ draw(true); }); Tab::nil.set_AbstractTab(nullptr); } AbstractTab::~AbstractTab() { layers.reset(); active_tab() = nullptr; left_neighbor = Tab::nil; right_neighbor = Tab::nil; } void AbstractTab::add_window(AbstractWindow * win) { if (nullptr == win) return; layers->mut_at(win->get_layer()).first.push_back(win); win->add_tab(AccessKey_AbstractWindow_add_tab(), as_handle()); // guarantee active window by setting first window active if (layers->at(win->get_layer()).first.size() == 1) layers->mut_at(win->get_layer()).second = win; } void AbstractTab::resize() { if (is_active()) for (auto l : Layer::variants()) for (auto w : layers->mut_at(l).first) w->resize(); } void AbstractTab::draw(bool clear_first) { if (is_active()) { for (auto w : layers->mut_at(Layer::Bottom::grab()).first) w->draw(clear_first); if (layer_F_enabled) for (auto w : layers->mut_at(Layer::F::grab()).first) w->draw(clear_first); if (layer_Help_enabled) for (auto w : layers->mut_at(Layer::Help::grab()).first) w->draw(clear_first); } } void AbstractTab::set_active_tab(Tab::Type tab) { if (tab.is_nil()) return; if (nullptr != active_tab()) for (auto l : Layer::variants()) for (auto w : active_tab()->layers->mut_at(l).first) w->disable(VisibilityAspect::TabVisibility::grab()); AbstractWindow const * tab_act_win = tab.as_AbstractTab()->get_active_window(); // synce WindowVisibility aspect for Help layer, specifically: // // if help enabled for old tab then enable help for new tab if not already // and... // if help disabled for old tab then disable help for new tab if not already if (nullptr != active_tab() && nullptr != tab_act_win) { // if help enabled for old/current active_tab() if (nullptr != active_tab()->get_active_window() && active_tab()->get_active_window()->get_layer() == Layer::Help::grab()) { // then enable if help disabled for new active_tab() if (tab_act_win->get_layer() != Layer::Help::grab()) tab.as_AbstractTab()->on_COMMA(); } else // otherwise if help disabled for old/current active_tab() { // then disable if help enabled for new active_tab() if (tab_act_win->get_layer() == Layer::Help::grab()) tab.as_AbstractTab()->on_COMMA(); } } active_tab() = tab.as_AbstractTab(); // enable TabVisibility aspect for each window within each layer if (nullptr != active_tab()) for (auto l : Layer::variants()) for (auto w : active_tab()->layers->mut_at(l).first) w->enable(VisibilityAspect::TabVisibility::grab()); } Tab::Type AbstractTab::get_active_tab() { if (nullptr == active_tab()) return Tab::nil; return active_tab()->as_handle(); } void AbstractTab::set_active_window(AbstractWindow * win) { if (nullptr == win) return; // verify given window exists in the given layer { bool found = false; for (auto w : layers->at(win->get_layer()).first) { if (w == win) { found = true; break; } } if (!found) return; } // need to redraw both old and new active windows layers->mut_at(win->get_layer()).second->mark_dirty(); win->mark_dirty(); layers->mut_at(win->get_layer()).second = win; } AbstractWindow * AbstractTab::get_active_window() { if (layer_Help_enabled) return layers->mut_at(Layer::Help::grab()).second; if (layer_F_enabled) return layers->mut_at(Layer::F::grab()).second; return layers->mut_at(Layer::Bottom::grab()).second; } AbstractWindow * AbstractTab::get_active_window(Layer::Type layer) { return layers->mut_at(layer).second; } void AbstractTab::on_KEY(int key) { if (!is_active()) return; switch (key) { case KEY_F(1) : case KEY_F(2) : case KEY_F(3) : case KEY_F(4) : case KEY_F(5) : case KEY_F(6) : case KEY_F(7) : case KEY_F(8) : case KEY_F(9) : case KEY_F(10) : case KEY_F(11) : case KEY_F(12) : on_ANY_F(); return; case ',' : on_COMMA(); return; case SHIFT_LEFT : on_SHIFT_LEFT(); return; case SHIFT_RIGHT : on_SHIFT_RIGHT(); return; } auto active_win = get_active_window(); if (nullptr != active_win) { if (active_win->get_layer() == Layer::Help::grab()) { switch (key) { case KEY_LEFT : on_SHIFT_LEFT(); return; case KEY_RIGHT : on_SHIFT_RIGHT(); return; } } active_win->on_KEY(key); } } void AbstractTab::on_ANY_F() { if (layer_Help_enabled) return; if (layers->at(Layer::F::grab()).first.size() > 0) toggle_layer(Layer::F::grab(), layer_F_enabled); } void AbstractTab::on_COMMA() { toggle_layer(Layer::Help::grab(), layer_Help_enabled); } void AbstractTab::toggle_layer(Layer::Type layer, bool & layer_enabled) { if (layer_enabled) { // disable layer layer_enabled = false; for (auto w : layers->mut_at(layer).first) w->disable(VisibilityAspect::WindowVisibility::grab()); // mark other layers dirty for (auto l : Layer::variants()) if (l != layer) for (auto w : layers->mut_at(l).first) w->mark_dirty(); } else { // enable layer layer_enabled = true; for (auto w : layers->mut_at(layer).first) w->enable(VisibilityAspect::WindowVisibility::grab()); } } void AbstractTab::on_SHIFT_LEFT() { if (!left_neighbor.is_nil()) AbstractTab::set_active_tab(left_neighbor); } void AbstractTab::on_SHIFT_RIGHT() { if (!right_neighbor.is_nil()) AbstractTab::set_active_tab(right_neighbor); }
27
87
0.61362
shtroizel
11dd4cc7eea31c758a7d5706cb80cb0892be57b8
1,216
cpp
C++
libgpos/src/task/CAutoTraceFlag.cpp
khannaekta/gporca
94e509d0a2456851a2cabf02e933c3523946b87b
[ "ECL-2.0", "Apache-2.0" ]
28
2016-01-29T08:27:42.000Z
2021-03-11T01:42:33.000Z
libgpos/src/task/CAutoTraceFlag.cpp
khannaekta/gporca
94e509d0a2456851a2cabf02e933c3523946b87b
[ "ECL-2.0", "Apache-2.0" ]
22
2016-02-01T16:31:50.000Z
2017-07-13T13:25:53.000Z
libgpos/src/task/CAutoTraceFlag.cpp
khannaekta/gporca
94e509d0a2456851a2cabf02e933c3523946b87b
[ "ECL-2.0", "Apache-2.0" ]
23
2016-01-28T03:19:24.000Z
2021-05-28T07:32:51.000Z
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2011 EMC Corp. // // @filename: // CAutoTraceFlag.cpp // // @doc: // Auto object to toggle TF in scope //--------------------------------------------------------------------------- #include "gpos/base.h" #include "gpos/task/CAutoTraceFlag.h" using namespace gpos; //--------------------------------------------------------------------------- // @function: // CAutoTraceFlag::CAutoTraceFlag // // @doc: // ctor // //--------------------------------------------------------------------------- CAutoTraceFlag::CAutoTraceFlag ( ULONG ulTrace, BOOL fVal ) : m_ulTrace(ulTrace), m_fOrig(false) { GPOS_ASSERT(NULL != ITask::PtskSelf()); m_fOrig = ITask::PtskSelf()->FTrace(m_ulTrace, fVal); } //--------------------------------------------------------------------------- // @function: // CAutoTraceFlag::~CAutoTraceFlag // // @doc: // dtor // //--------------------------------------------------------------------------- CAutoTraceFlag::~CAutoTraceFlag() { GPOS_ASSERT(NULL != ITask::PtskSelf()); // reset original value ITask::PtskSelf()->FTrace(m_ulTrace, m_fOrig); } // EOF
20.965517
77
0.409539
khannaekta
11e56d15b8518951eaa1e705fe1b4e6149fc0615
2,005
cpp
C++
mkra/src/module.cpp
unihykes/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
2
2018-03-27T02:46:03.000Z
2018-05-24T02:49:17.000Z
mkra/src/module.cpp
six-th/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
null
null
null
mkra/src/module.cpp
six-th/monk
d5ad969fea75912d4aad913adf945f78ec4df60e
[ "Apache-2.0" ]
null
null
null
/*************************************************************************************************** LICENSE: 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. Author:liu.hao(33852613@163.com) Time:2021-4 info: ***************************************************************************************************/ #include <markcore.h> #include "mkLIRSReplacement.h" MK_DEFINE_MODULE_INSTANCE_VERSION(1, 0, 0); class mkLIRSReplacementOption : public mkIOption { public: virtual bool OnSetValue(const string& key, const string& value) { if("--lir_size" == key) { lir_size = std::stoi(value); return true; } if("--hir_Size" == key) { hir_Size = std::stoi(value); return true; } return false; } virtual void OnApply() { } public: int lir_size = 100; int hir_Size = 100; }; void mkIReplacementBuilder::PushOptions(const string& key, const string& value) { MK_CALL_ONCE_BEGIN g_switch->ClearOption<mkLIRSReplacementOption>(); MK_CALL_ONCE_END g_switch->SetOptions(key, value, false); } std::shared_ptr<mkIReplacement> mkIReplacementBuilder::LIRS(shared_ptr<mkIReplaceValueBuilder> pBuilder) { const auto& lir_size = g_switch->GetOption<mkLIRSReplacementOption>()->lir_size; const auto& hir_Size = g_switch->GetOption<mkLIRSReplacementOption>()->hir_Size; return make_shared<mkLIRSReplacement>(lir_size, hir_Size, pBuilder); }
27.465753
100
0.618953
unihykes
11e5f9bd49da4e120dce1a093ce869f80b8b0ece
24,133
cpp
C++
src/game/server/entities/triggers/CChangeLevel.cpp
GEEKiDoS/source-sdk-2013-mp
9c4d61d342a23d7da1a2b35e28423e205c11d7fa
[ "Unlicense" ]
1
2021-03-20T14:27:22.000Z
2021-03-20T14:27:22.000Z
src/game/server/entities/triggers/CChangeLevel.cpp
GEEKiDoS/source-sdk-2013-mp
9c4d61d342a23d7da1a2b35e28423e205c11d7fa
[ "Unlicense" ]
null
null
null
src/game/server/entities/triggers/CChangeLevel.cpp
GEEKiDoS/source-sdk-2013-mp
9c4d61d342a23d7da1a2b35e28423e205c11d7fa
[ "Unlicense" ]
null
null
null
//========= Copyright Valve Corporation, All rights reserved. ============// #include "cbase.h" #include "ai_basenpc.h" #include "ai_behavior_lead.h" #include "entityapi.h" #include "saverestore.h" #include "saverestoretypes.h" #include "triggers.h" #include "entities/triggers/CChangeLevel.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" ConVar g_debug_transitions("g_debug_transitions", "0", FCVAR_NONE, "Set to 1 and restart the map to be warned if the map has no trigger_transition volumes. Set to 2 to see a dump of all entities & associated results during a transition."); LINK_ENTITY_TO_CLASS( trigger_changelevel, CChangeLevel ); // Global Savedata for changelevel trigger BEGIN_DATADESC( CChangeLevel ) DEFINE_AUTO_ARRAY( m_szMapName, FIELD_CHARACTER ), DEFINE_AUTO_ARRAY( m_szLandmarkName, FIELD_CHARACTER ), // DEFINE_FIELD( m_touchTime, FIELD_TIME ), // don't save // DEFINE_FIELD( m_bTouched, FIELD_BOOLEAN ), // Function Pointers DEFINE_FUNCTION( TouchChangeLevel ), DEFINE_INPUTFUNC( FIELD_VOID, "ChangeLevel", InputChangeLevel ), // Outputs DEFINE_OUTPUT( m_OnChangeLevel, "OnChangeLevel"), END_DATADESC() // // Cache user-entity-field values until spawn is called. // bool CChangeLevel::KeyValue( const char *szKeyName, const char *szValue ) { if (FStrEq(szKeyName, "map")) { if (strlen(szValue) >= cchMapNameMost) { Warning( "Map name '%s' too long (32 chars)\n", szValue ); Assert(0); } Q_strncpy(m_szMapName, szValue, sizeof(m_szMapName)); } else if (FStrEq(szKeyName, "landmark")) { if (strlen(szValue) >= cchMapNameMost) { Warning( "Landmark name '%s' too long (32 chars)\n", szValue ); Assert(0); } Q_strncpy(m_szLandmarkName, szValue, sizeof( m_szLandmarkName )); } else return BaseClass::KeyValue( szKeyName, szValue ); return true; } void CChangeLevel::Spawn( void ) { if ( FStrEq( m_szMapName, "" ) ) { Msg( "a trigger_changelevel doesn't have a map" ); } if ( FStrEq( m_szLandmarkName, "" ) ) { Msg( "trigger_changelevel to %s doesn't have a landmark", m_szMapName ); } InitTrigger(); if ( !HasSpawnFlags(SF_CHANGELEVEL_NOTOUCH) ) { SetTouch( &CChangeLevel::TouchChangeLevel ); } // Msg( "TRANSITION: %s (%s)\n", m_szMapName, m_szLandmarkName ); } void CChangeLevel::Activate( void ) { BaseClass::Activate(); if ( gpGlobals->eLoadType == MapLoad_NewGame ) { if ( HasSpawnFlags( SF_CHANGELEVEL_CHAPTER ) ) { VPhysicsInitStatic(); RemoveSolidFlags( FSOLID_NOT_SOLID | FSOLID_TRIGGER ); SetTouch( NULL ); return; } } // Level transitions will bust if they are in solid CBaseEntity *pLandmark = FindLandmark( m_szLandmarkName ); if ( pLandmark ) { int clusterIndex = engine->GetClusterForOrigin( pLandmark->GetAbsOrigin() ); if ( clusterIndex < 0 ) { Warning( "trigger_changelevel to map %s has a landmark embedded in solid!\n" "This will break level transitions!\n", m_szMapName ); } if ( g_debug_transitions.GetInt() ) { if ( !gEntList.FindEntityByClassname( NULL, "trigger_transition" ) ) { Warning( "Map has no trigger_transition volumes for landmark %s\n", m_szLandmarkName ); } } } m_bTouched = false; } static char st_szNextMap[cchMapNameMost]; static char st_szNextSpot[cchMapNameMost]; // Used to show debug for only the transition volume we're currently in static int g_iDebuggingTransition = 0; CBaseEntity *CChangeLevel::FindLandmark( const char *pLandmarkName ) { CBaseEntity *pentLandmark; pentLandmark = gEntList.FindEntityByName( NULL, pLandmarkName ); while ( pentLandmark ) { // Found the landmark if ( FClassnameIs( pentLandmark, "info_landmark" ) ) return pentLandmark; else pentLandmark = gEntList.FindEntityByName( pentLandmark, pLandmarkName ); } Warning( "Can't find landmark %s\n", pLandmarkName ); return NULL; } //----------------------------------------------------------------------------- // Purpose: Allows level transitions to be triggered by buttons, etc. //----------------------------------------------------------------------------- void CChangeLevel::InputChangeLevel( inputdata_t &inputdata ) { // Ignore changelevel transitions if the player's dead or attempting a challenge if ( gpGlobals->maxClients == 1 ) { CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); if ( pPlayer && ( !pPlayer->IsAlive() || pPlayer->GetBonusChallenge() > 0 ) ) return; } ChangeLevelNow( inputdata.pActivator ); } //----------------------------------------------------------------------------- // Purpose: Performs the level change and fires targets. // Input : pActivator - //----------------------------------------------------------------------------- bool CChangeLevel::IsEntityInTransition( CBaseEntity *pEntity ) { int transitionState = InTransitionVolume(pEntity, m_szLandmarkName); if ( transitionState == TRANSITION_VOLUME_SCREENED_OUT ) { return false; } // look for a landmark entity CBaseEntity *pLandmark = FindLandmark( m_szLandmarkName ); if ( !pLandmark ) return false; // Check to make sure it's also in the PVS of landmark byte pvs[MAX_MAP_CLUSTERS/8]; int clusterIndex = engine->GetClusterForOrigin( pLandmark->GetAbsOrigin() ); engine->GetPVSForCluster( clusterIndex, sizeof(pvs), pvs ); Vector vecSurroundMins, vecSurroundMaxs; pEntity->CollisionProp()->WorldSpaceSurroundingBounds( &vecSurroundMins, &vecSurroundMaxs ); return engine->CheckBoxInPVS( vecSurroundMins, vecSurroundMaxs, pvs, sizeof( pvs ) ); } void CChangeLevel::NotifyEntitiesOutOfTransition() { CBaseEntity *pEnt = gEntList.FirstEnt(); while ( pEnt ) { // Found the landmark if ( pEnt->ObjectCaps() & FCAP_NOTIFY_ON_TRANSITION ) { variant_t emptyVariant; if ( !(pEnt->ObjectCaps() & (FCAP_ACROSS_TRANSITION|FCAP_FORCE_TRANSITION)) || !IsEntityInTransition( pEnt ) ) { pEnt->AcceptInput( "OutsideTransition", this, this, emptyVariant, 0 ); } else { pEnt->AcceptInput( "InsideTransition", this, this, emptyVariant, 0 ); } } pEnt = gEntList.NextEnt( pEnt ); } } //------------------------------------------------------------------------------ // Purpose : Checks all spawned AIs and prints a warning if any are actively leading // Input : // Output : //------------------------------------------------------------------------------ void CChangeLevel::WarnAboutActiveLead( void ) { int i; CAI_BaseNPC * ai; CAI_BehaviorBase * behavior; for ( i = 0; i < g_AI_Manager.NumAIs(); i++ ) { ai = g_AI_Manager.AccessAIs()[i]; behavior = ai->GetRunningBehavior(); if ( behavior ) { if ( dynamic_cast<CAI_LeadBehavior *>( behavior ) ) { Warning( "Entity '%s' is still actively leading\n", STRING( ai->GetEntityName() ) ); } } } } void CChangeLevel::ChangeLevelNow( CBaseEntity *pActivator ) { CBaseEntity *pLandmark; levellist_t levels[16]; Assert(!FStrEq(m_szMapName, "")); // Don't work in deathmatch if ( g_pGameRules->IsDeathmatch() ) return; // Some people are firing these multiple times in a frame, disable if ( m_bTouched ) return; m_bTouched = true; CBaseEntity *pPlayer = (pActivator && pActivator->IsPlayer()) ? pActivator : UTIL_GetLocalPlayer(); int transitionState = InTransitionVolume(pPlayer, m_szLandmarkName); if ( transitionState == TRANSITION_VOLUME_SCREENED_OUT ) { DevMsg( 2, "Player isn't in the transition volume %s, aborting\n", m_szLandmarkName ); return; } // look for a landmark entity pLandmark = FindLandmark( m_szLandmarkName ); if ( !pLandmark ) return; // no transition volumes, check PVS of landmark if ( transitionState == TRANSITION_VOLUME_NOT_FOUND ) { byte pvs[MAX_MAP_CLUSTERS/8]; int clusterIndex = engine->GetClusterForOrigin( pLandmark->GetAbsOrigin() ); engine->GetPVSForCluster( clusterIndex, sizeof(pvs), pvs ); if ( pPlayer ) { Vector vecSurroundMins, vecSurroundMaxs; pPlayer->CollisionProp()->WorldSpaceSurroundingBounds( &vecSurroundMins, &vecSurroundMaxs ); bool playerInPVS = engine->CheckBoxInPVS( vecSurroundMins, vecSurroundMaxs, pvs, sizeof( pvs ) ); //Assert( playerInPVS ); if ( !playerInPVS ) { Warning( "Player isn't in the landmark's (%s) PVS, aborting\n", m_szLandmarkName ); #ifndef HL1_DLL // HL1 works even with these errors! return; #endif } } } WarnAboutActiveLead(); g_iDebuggingTransition = 0; st_szNextSpot[0] = 0; // Init landmark to NULL Q_strncpy(st_szNextSpot, m_szLandmarkName,sizeof(st_szNextSpot)); // This object will get removed in the call to engine->ChangeLevel, copy the params into "safe" memory Q_strncpy(st_szNextMap, m_szMapName, sizeof(st_szNextMap)); m_hActivator = pActivator; m_OnChangeLevel.FireOutput(pActivator, this); NotifyEntitiesOutOfTransition(); //// Msg( "Level touches %d levels\n", ChangeList( levels, 16 ) ); if ( g_debug_transitions.GetInt() ) { Msg( "CHANGE LEVEL: %s %s\n", st_szNextMap, st_szNextSpot ); } // If we're debugging, don't actually change level if ( g_debug_transitions.GetInt() == 0 ) { engine->ChangeLevel( st_szNextMap, st_szNextSpot ); } else { // Build a change list so we can see what would be transitioning CSaveRestoreData *pSaveData = SaveInit( 0 ); if ( pSaveData ) { g_pGameSaveRestoreBlockSet->PreSave( pSaveData ); pSaveData->levelInfo.connectionCount = BuildChangeList( pSaveData->levelInfo.levelList, MAX_LEVEL_CONNECTIONS ); g_pGameSaveRestoreBlockSet->PostSave(); } SetTouch( NULL ); } } // // GLOBALS ASSUMED SET: st_szNextMap // void CChangeLevel::TouchChangeLevel( CBaseEntity *pOther ) { CBasePlayer *pPlayer = ToBasePlayer(pOther); if ( !pPlayer ) return; if( pPlayer->IsSinglePlayerGameEnding() ) { // Some semblance of deceleration, but allow player to fall normally. // Also, disable controls. Vector vecVelocity = pPlayer->GetAbsVelocity(); vecVelocity.x *= 0.5f; vecVelocity.y *= 0.5f; pPlayer->SetAbsVelocity( vecVelocity ); pPlayer->AddFlag( FL_FROZEN ); return; } if ( !pPlayer->IsInAVehicle() && pPlayer->GetMoveType() == MOVETYPE_NOCLIP ) { DevMsg("In level transition: %s %s\n", st_szNextMap, st_szNextSpot ); return; } ChangeLevelNow( pOther ); } // Add a transition to the list, but ignore duplicates // (a designer may have placed multiple trigger_changelevels with the same landmark) int CChangeLevel::AddTransitionToList( levellist_t *pLevelList, int listCount, const char *pMapName, const char *pLandmarkName, edict_t *pentLandmark ) { int i; if ( !pLevelList || !pMapName || !pLandmarkName || !pentLandmark ) return 0; // Ignore changelevels to the level we're ready in. Mapmakers love to do this! if ( stricmp( pMapName, STRING(gpGlobals->mapname) ) == 0 ) return 0; for ( i = 0; i < listCount; i++ ) { if ( pLevelList[i].pentLandmark == pentLandmark && stricmp( pLevelList[i].mapName, pMapName ) == 0 ) return 0; } Q_strncpy( pLevelList[listCount].mapName, pMapName, sizeof(pLevelList[listCount].mapName) ); Q_strncpy( pLevelList[listCount].landmarkName, pLandmarkName, sizeof(pLevelList[listCount].landmarkName) ); pLevelList[listCount].pentLandmark = pentLandmark; CBaseEntity *ent = CBaseEntity::Instance( pentLandmark ); Assert( ent ); pLevelList[listCount].vecLandmarkOrigin = ent->GetAbsOrigin(); return 1; } int BuildChangeList( levellist_t *pLevelList, int maxList ) { return CChangeLevel::ChangeList( pLevelList, maxList ); } struct collidelist_t { const CPhysCollide *pCollide; Vector origin; QAngle angles; }; // NOTE: This routine is relatively slow. If you need to use it for per-frame work, consider that fact. // UNDONE: Expand this to the full matrix of solid types on each side and move into enginetrace static bool TestEntityTriggerIntersection_Accurate(CBaseEntity *pTrigger, CBaseEntity *pEntity) { Assert(pTrigger->GetSolid() == SOLID_BSP); if (pTrigger->Intersects(pEntity)) // It touches one, it's in the volume { switch (pEntity->GetSolid()) { case SOLID_BBOX: { ICollideable *pCollide = pTrigger->CollisionProp(); Ray_t ray; trace_t tr; ray.Init(pEntity->GetAbsOrigin(), pEntity->GetAbsOrigin(), pEntity->WorldAlignMins(), pEntity->WorldAlignMaxs()); enginetrace->ClipRayToCollideable(ray, MASK_ALL, pCollide, &tr); if (tr.startsolid) return true; } break; case SOLID_BSP: case SOLID_VPHYSICS: { CPhysCollide *pTriggerCollide = modelinfo->GetVCollide(pTrigger->GetModelIndex())->solids[0]; Assert(pTriggerCollide); CUtlVector<collidelist_t> collideList; IPhysicsObject *pList[VPHYSICS_MAX_OBJECT_LIST_COUNT]; int physicsCount = pEntity->VPhysicsGetObjectList(pList, ARRAYSIZE(pList)); if (physicsCount) { for (int i = 0; i < physicsCount; i++) { const CPhysCollide *pCollide = pList[i]->GetCollide(); if (pCollide) { collidelist_t element; element.pCollide = pCollide; pList[i]->GetPosition(&element.origin, &element.angles); collideList.AddToTail(element); } } } else { vcollide_t *pVCollide = modelinfo->GetVCollide(pEntity->GetModelIndex()); if (pVCollide && pVCollide->solidCount) { collidelist_t element; element.pCollide = pVCollide->solids[0]; element.origin = pEntity->GetAbsOrigin(); element.angles = pEntity->GetAbsAngles(); collideList.AddToTail(element); } } for (int i = collideList.Count() - 1; i >= 0; --i) { const collidelist_t &element = collideList[i]; trace_t tr; physcollision->TraceCollide(element.origin, element.origin, element.pCollide, element.angles, pTriggerCollide, pTrigger->GetAbsOrigin(), pTrigger->GetAbsAngles(), &tr); if (tr.startsolid) return true; } } break; default: return true; } } return false; } int CChangeLevel::InTransitionVolume(CBaseEntity *pEntity, const char *pVolumeName) { CBaseEntity *pVolume; if (pEntity->ObjectCaps() & FCAP_FORCE_TRANSITION) return TRANSITION_VOLUME_PASSED; // If you're following another entity, follow it through the transition (weapons follow the player) pEntity = pEntity->GetRootMoveParent(); int inVolume = TRANSITION_VOLUME_NOT_FOUND; // Unless we find a trigger_transition, everything is in the volume pVolume = gEntList.FindEntityByName(NULL, pVolumeName); while (pVolume) { if (pVolume && FClassnameIs(pVolume, "trigger_transition")) { if (TestEntityTriggerIntersection_Accurate(pVolume, pEntity)) // It touches one, it's in the volume return TRANSITION_VOLUME_PASSED; inVolume = TRANSITION_VOLUME_SCREENED_OUT; // Found a trigger_transition, but I don't intersect it -- if I don't find another, don't go! } pVolume = gEntList.FindEntityByName(pVolume, pVolumeName); } return inVolume; } //------------------------------------------------------------------------------ // Builds the list of entities to save when moving across a transition //------------------------------------------------------------------------------ int CChangeLevel::BuildChangeLevelList(levellist_t *pLevelList, int maxList) { int nCount = 0; CBaseEntity *pentChangelevel = gEntList.FindEntityByClassname(NULL, "trigger_changelevel"); while (pentChangelevel) { CChangeLevel *pTrigger = dynamic_cast<CChangeLevel *>(pentChangelevel); if (pTrigger) { // Find the corresponding landmark CBaseEntity *pentLandmark = FindLandmark(pTrigger->m_szLandmarkName); if (pentLandmark) { // Build a list of unique transitions if (AddTransitionToList(pLevelList, nCount, pTrigger->m_szMapName, pTrigger->m_szLandmarkName, pentLandmark->edict())) { ++nCount; if (nCount >= maxList) // FULL!! break; } } } pentChangelevel = gEntList.FindEntityByClassname(pentChangelevel, "trigger_changelevel"); } return nCount; } //------------------------------------------------------------------------------ // Adds a single entity to the transition list, if appropriate. Returns the new count //------------------------------------------------------------------------------ int CChangeLevel::ComputeEntitySaveFlags(CBaseEntity *pEntity) { if (g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE) { Msg("Trying %s (%s): ", pEntity->GetClassname(), pEntity->GetDebugName()); } int caps = pEntity->ObjectCaps(); if (caps & FCAP_DONT_SAVE) { if (g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE) { Msg("IGNORED due to being marked \"Don't save\".\n"); } return 0; } // If this entity can be moved or is global, mark it int flags = 0; if (caps & FCAP_ACROSS_TRANSITION) { flags |= FENTTABLE_MOVEABLE; } if (pEntity->m_iGlobalname != NULL_STRING && !pEntity->IsDormant()) { flags |= FENTTABLE_GLOBAL; } if (g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE && !flags) { Msg("IGNORED, no across_transition flag & no globalname\n"); } return flags; } //------------------------------------------------------------------------------ // Adds a single entity to the transition list, if appropriate. Returns the new count //------------------------------------------------------------------------------ inline int CChangeLevel::AddEntityToTransitionList(CBaseEntity *pEntity, int flags, int nCount, CBaseEntity **ppEntList, int *pEntityFlags) { ppEntList[nCount] = pEntity; pEntityFlags[nCount] = flags; ++nCount; // If we're debugging, make it visible if (g_iDebuggingTransition) { if (g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE) { // In verbose mode we've already printed out what the entity is Msg("ADDED.\n"); } else { // In non-verbose mode, we just print this line Msg("ADDED %s (%s) to transition.\n", pEntity->GetClassname(), pEntity->GetDebugName()); } pEntity->m_debugOverlays |= (OVERLAY_BBOX_BIT | OVERLAY_NAME_BIT); } return nCount; } //------------------------------------------------------------------------------ // Builds the list of entities to bring across a particular transition //------------------------------------------------------------------------------ int CChangeLevel::BuildEntityTransitionList(CBaseEntity *pLandmarkEntity, const char *pLandmarkName, CBaseEntity **ppEntList, int *pEntityFlags, int nMaxList) { int iEntity = 0; // Only show debug for the transition to the level we're going to if (g_debug_transitions.GetInt() && pLandmarkEntity->NameMatches(st_szNextSpot)) { g_iDebuggingTransition = g_debug_transitions.GetInt(); // Show us where the landmark entity is pLandmarkEntity->m_debugOverlays |= (OVERLAY_PIVOT_BIT | OVERLAY_BBOX_BIT | OVERLAY_NAME_BIT); } else { g_iDebuggingTransition = 0; } // Follow the linked list of entities in the PVS of the transition landmark CBaseEntity *pEntity = NULL; while ((pEntity = UTIL_EntitiesInPVS(pLandmarkEntity, pEntity)) != NULL) { int flags = ComputeEntitySaveFlags(pEntity); if (!flags) continue; // Check to make sure the entity isn't screened out by a trigger_transition if (!InTransitionVolume(pEntity, pLandmarkName)) { if (g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE) { Msg("IGNORED, outside transition volume.\n"); } continue; } if (iEntity >= nMaxList) { Warning("Too many entities across a transition!\n"); Assert(0); return iEntity; } iEntity = AddEntityToTransitionList(pEntity, flags, iEntity, ppEntList, pEntityFlags); } return iEntity; } //------------------------------------------------------------------------------ // Tests bits in a bitfield //------------------------------------------------------------------------------ static inline bool IsBitSet(char *pBuf, int nBit) { return (pBuf[nBit >> 3] & (1 << (nBit & 0x7))) != 0; } static inline void Set(char *pBuf, int nBit) { pBuf[nBit >> 3] |= 1 << (nBit & 0x7); } //------------------------------------------------------------------------------ // Adds in all entities depended on by entities near the transition //------------------------------------------------------------------------------ #define MAX_ENTITY_BYTE_COUNT (NUM_ENT_ENTRIES >> 3) int CChangeLevel::AddDependentEntities(int nCount, CBaseEntity **ppEntList, int *pEntityFlags, int nMaxList) { char pEntitiesSaved[MAX_ENTITY_BYTE_COUNT]; memset(pEntitiesSaved, 0, MAX_ENTITY_BYTE_COUNT * sizeof(char)); // Populate the initial bitfield int i; for (i = 0; i < nCount; ++i) { // NOTE: Must use GetEntryIndex because we're saving non-networked entities int nEntIndex = ppEntList[i]->GetRefEHandle().GetEntryIndex(); // We shouldn't already have this entity in the list! Assert(!IsBitSet(pEntitiesSaved, nEntIndex)); // Mark the entity as being in the list Set(pEntitiesSaved, nEntIndex); } IEntitySaveUtils *pSaveUtils = GetEntitySaveUtils(); // Iterate over entities whose dependencies we've not yet processed // NOTE: nCount will change value during this loop in AddEntityToTransitionList for (i = 0; i < nCount; ++i) { CBaseEntity *pEntity = ppEntList[i]; // Find dependencies in the hash. int nDepCount = pSaveUtils->GetEntityDependencyCount(pEntity); if (!nDepCount) continue; CBaseEntity **ppDependentEntities = (CBaseEntity**)stackalloc(nDepCount * sizeof(CBaseEntity*)); pSaveUtils->GetEntityDependencies(pEntity, nDepCount, ppDependentEntities); for (int j = 0; j < nDepCount; ++j) { CBaseEntity *pDependent = ppDependentEntities[j]; if (!pDependent) continue; // NOTE: Must use GetEntryIndex because we're saving non-networked entities int nEntIndex = pDependent->GetRefEHandle().GetEntryIndex(); // Don't re-add it if it's already in the list if (IsBitSet(pEntitiesSaved, nEntIndex)) continue; // Mark the entity as being in the list Set(pEntitiesSaved, nEntIndex); int flags = ComputeEntitySaveFlags(pEntity); if (flags) { if (nCount >= nMaxList) { Warning("Too many entities across a transition!\n"); Assert(0); return false; } if (g_debug_transitions.GetInt()) { Msg("ADDED DEPENDANCY: %s (%s)\n", pEntity->GetClassname(), pEntity->GetDebugName()); } nCount = AddEntityToTransitionList(pEntity, flags, nCount, ppEntList, pEntityFlags); } else { Warning("Warning!! Save dependency is linked to an entity that doesn't want to be saved!\n"); } } } return nCount; } //------------------------------------------------------------------------------ // This builds the list of all transitions on this level and which entities // are in their PVS's and can / should be moved across. //------------------------------------------------------------------------------ // We can only ever move 512 entities across a transition #define MAX_ENTITY 512 // FIXME: This has grown into a complicated beast. Can we make this more elegant? int CChangeLevel::ChangeList(levellist_t *pLevelList, int maxList) { // Find all of the possible level changes on this BSP int count = BuildChangeLevelList(pLevelList, maxList); if (!gpGlobals->pSaveData || (static_cast<CSaveRestoreData *>(gpGlobals->pSaveData)->NumEntities() == 0)) return count; CSave saveHelper(static_cast<CSaveRestoreData *>(gpGlobals->pSaveData)); // For each level change, find nearby entities and save them int i; for (i = 0; i < count; i++) { CBaseEntity *pEntList[MAX_ENTITY]; int entityFlags[MAX_ENTITY]; // First, figure out which entities are near the transition CBaseEntity *pLandmarkEntity = CBaseEntity::Instance(pLevelList[i].pentLandmark); int iEntity = BuildEntityTransitionList(pLandmarkEntity, pLevelList[i].landmarkName, pEntList, entityFlags, MAX_ENTITY); // FIXME: Activate if we have a dependency problem on level transition // Next, add in all entities depended on by entities near the transition // iEntity = AddDependentEntities( iEntity, pEntList, entityFlags, MAX_ENTITY ); int j; for (j = 0; j < iEntity; j++) { // Mark entity table with 1<<i int index = saveHelper.EntityIndex(pEntList[j]); // Flag it with the level number saveHelper.EntityFlagsSet(index, entityFlags[j] | (1 << i)); } } return count; }
29.394641
239
0.667716
GEEKiDoS
eb1ce47710b2db11e95553ba08515d320e18ad0a
453
cpp
C++
array/989_add_to_array_form_interger.cpp
rspezialetti/leetcode
4614ffe2a4923aae02f93096b6200239e6f201c1
[ "MIT" ]
1
2019-08-21T21:25:34.000Z
2019-08-21T21:25:34.000Z
array/989_add_to_array_form_interger.cpp
rspezialetti/leetcode
4614ffe2a4923aae02f93096b6200239e6f201c1
[ "MIT" ]
null
null
null
array/989_add_to_array_form_interger.cpp
rspezialetti/leetcode
4614ffe2a4923aae02f93096b6200239e6f201c1
[ "MIT" ]
null
null
null
class Solution { public: vector<int> addToArrayForm(vector<int>& A, int K) { vector<int> result; int i = A.size(); int carry = K; while(--i >= 0 || carry > 0) { if(i >= 0) carry += A[i]; result.push_back(carry % 10); carry /= 10; } reverse(result.begin(), result.end()); return result; } };
20.590909
54
0.399558
rspezialetti
eb1d8b56429200d4dab81c8a1cc8b6625a3a9458
20,074
cpp
C++
src/server/scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp
FrenchCORE/OLD_FrenchCORE
edf1a2859246493c0667b44497c4bbb0fe718cbd
[ "OpenSSL" ]
1
2019-12-03T18:41:39.000Z
2019-12-03T18:41:39.000Z
src/server/scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp
FrenchCORE/OLD_FrenchCORE
edf1a2859246493c0667b44497c4bbb0fe718cbd
[ "OpenSSL" ]
null
null
null
src/server/scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp
FrenchCORE/OLD_FrenchCORE
edf1a2859246493c0667b44497c4bbb0fe718cbd
[ "OpenSSL" ]
null
null
null
/* * Copyright (C) 2005 - 2012 MaNGOS <http://www.getmangos.com/> * * Copyright (C) 2008 - 2012 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2012 - 2012 FrenchCORE <http://www.frcore.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Onyxia SD%Complete: 95 SDComment: <Known bugs> Ground visual for Deep Breath effect; Not summoning whelps on phase 3 (lacks info) </Known bugs> SDCategory: Onyxia's Lair EndScriptData */ #include "ScriptPCH.h" #include "onyxias_lair.h" enum eYells { SAY_AGGRO = -1249000, SAY_KILL = -1249001, SAY_PHASE_2_TRANS = -1249002, SAY_PHASE_3_TRANS = -1249003, EMOTE_BREATH = -1249004, }; enum eSpells { // Phase 1 spells SPELL_WING_BUFFET = 18500, SPELL_FLAME_BREATH = 18435, SPELL_CLEAVE = 68868, SPELL_TAIL_SWEEP = 68867, // Phase 2 spells SPELL_DEEP_BREATH = 23461, SPELL_FIREBALL = 18392, //Not much choise about these. We have to make own defintion on the direction/start-end point SPELL_BREATH_NORTH_TO_SOUTH = 17086, // 20x in "array" SPELL_BREATH_SOUTH_TO_NORTH = 18351, // 11x in "array" SPELL_BREATH_EAST_TO_WEST = 18576, // 7x in "array" SPELL_BREATH_WEST_TO_EAST = 18609, // 7x in "array" SPELL_BREATH_SE_TO_NW = 18564, // 12x in "array" SPELL_BREATH_NW_TO_SE = 18584, // 12x in "array" SPELL_BREATH_SW_TO_NE = 18596, // 12x in "array" SPELL_BREATH_NE_TO_SW = 18617, // 12x in "array" //SPELL_BREATH = 21131, // 8x in "array", different initial cast than the other arrays // Phase 3 spells SPELL_BELLOWING_ROAR = 18431, SPELL_LAIRGUARDCLEAVE = 15284, SPELL_LAIRGUARDBLASTNOVA = 68958, SPELL_LAIRGUARDIGNITE = 68960 }; struct sOnyxMove { uint32 uiLocId; uint32 uiLocIdEnd; uint32 uiSpellId; float fX, fY, fZ; }; static sOnyxMove aMoveData[]= { {0, 1, SPELL_BREATH_WEST_TO_EAST, -33.5561f, -182.682f, -56.9457f}, //west {1, 0, SPELL_BREATH_EAST_TO_WEST, -31.4963f, -250.123f, -55.1278f}, //east {2, 4, SPELL_BREATH_NW_TO_SE, 6.8951f, -180.246f, -55.896f}, //north-west {3, 5, SPELL_BREATH_NE_TO_SW, 10.2191f, -247.912f, -55.896f}, //north-east {4, 2, SPELL_BREATH_SE_TO_NW, -63.5156f, -240.096f, -55.477f}, //south-east {5, 3, SPELL_BREATH_SW_TO_NE, -58.2509f, -189.020f, -55.790f}, //south-west {6, 7, SPELL_BREATH_SOUTH_TO_NORTH, -65.8444f, -213.809f, -55.2985f}, //south {7, 6, SPELL_BREATH_NORTH_TO_SOUTH, 22.8763f, -217.152f, -55.0548f}, //north }; const Position MiddleRoomLocation = {-23.6155f, -215.357f, -55.7344f, 0.0f}; const Position Phase2Location = {-80.924f, -214.299f, -82.942f, 0.0f}; static Position aSpawnLocations[3]= { //Whelps {-30.127f, -254.463f, -89.440f, 0.0f}, {-30.817f, -177.106f, -89.258f, 0.0f}, //Lair Guard {-145.950f, -212.831f, -68.659f, 0.0f} }; class boss_onyxia : public CreatureScript { public: boss_onyxia() : CreatureScript("boss_onyxia") { } CreatureAI* GetAI(Creature* creature) const { return new boss_onyxiaAI (creature); } struct boss_onyxiaAI : public ScriptedAI { boss_onyxiaAI(Creature* creature) : ScriptedAI(creature), Summons(me) { m_instance = creature->GetInstanceScript(); Reset(); me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true); me->ApplySpellImmune(0, IMMUNITY_ID, 49560, true); // Death Grip jump effect } InstanceScript* m_instance; SummonList Summons; uint32 m_uiPhase; uint32 m_uiFlameBreathTimer; uint32 m_uiCleaveTimer; uint32 m_uiTailSweepTimer; uint32 m_uiWingBuffetTimer; uint32 m_uiMovePoint; uint32 m_uiMovementTimer; sOnyxMove* m_pPointData; uint32 m_uiFireballTimer; uint32 m_uiWhelpTimer; uint32 m_uiLairGuardTimer; uint32 m_uiDeepBreathTimer; uint32 m_uiBellowingRoarTimer; uint8 m_uiSummonWhelpCount; bool m_bIsMoving; void Reset() { if (!IsCombatMovement()) SetCombatMovement(true); m_uiPhase = PHASE_START; m_uiFlameBreathTimer = urand(10000, 20000); m_uiTailSweepTimer = urand(15000, 20000); m_uiCleaveTimer = urand(2000, 5000); m_uiWingBuffetTimer = urand(10000, 20000); m_uiMovePoint = urand(0, 5); m_uiMovementTimer = 14000; m_pPointData = GetMoveData(); m_uiFireballTimer = 15000; m_uiWhelpTimer = 60000; m_uiLairGuardTimer = 60000; m_uiDeepBreathTimer = 85000; m_uiBellowingRoarTimer = 30000; Summons.DespawnAll(); m_uiSummonWhelpCount = 0; m_bIsMoving = false; if (m_instance) { m_instance->SetData(DATA_ONYXIA, NOT_STARTED); m_instance->SetData(DATA_ONYXIA_PHASE, m_uiPhase); m_instance->DoStopTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, ACHIEV_TIMED_START_EVENT); } } void EnterCombat(Unit* /*who*/) { DoScriptText(SAY_AGGRO, me); me->SetInCombatWithZone(); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true); if (m_instance) { m_instance->SetData(DATA_ONYXIA, IN_PROGRESS); m_instance->DoStartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, ACHIEV_TIMED_START_EVENT); } } void JustDied(Unit* /*killer*/) { if (m_instance) m_instance->SetData(DATA_ONYXIA, DONE); Summons.DespawnAll(); } void JustSummoned(Creature* summoned) { summoned->SetInCombatWithZone(); if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) summoned->AI()->AttackStart(target); switch (summoned->GetEntry()) { case NPC_WHELP: ++m_uiSummonWhelpCount; break; case NPC_LAIRGUARD: summoned->setActive(true); break; } Summons.Summon(summoned); } void SummonedCreatureDespawn(Creature* summon) { Summons.Despawn(summon); } void KilledUnit(Unit* /*victim*/) { DoScriptText(SAY_KILL, me); } void SpellHit(Unit* /*pCaster*/, const SpellEntry* pSpell) { if (pSpell->Id == SPELL_BREATH_EAST_TO_WEST || pSpell->Id == SPELL_BREATH_WEST_TO_EAST || pSpell->Id == SPELL_BREATH_SE_TO_NW || pSpell->Id == SPELL_BREATH_NW_TO_SE || pSpell->Id == SPELL_BREATH_SW_TO_NE || pSpell->Id == SPELL_BREATH_NE_TO_SW) { m_pPointData = GetMoveData(); m_uiMovePoint = m_pPointData->uiLocIdEnd; me->SetSpeed(MOVE_FLIGHT, 1.5f); me->GetMotionMaster()->MovePoint(8, MiddleRoomLocation); } } void MovementInform(uint32 type, uint32 id) { if (type == POINT_MOTION_TYPE) { switch (id) { case 8: m_pPointData = GetMoveData(); if (m_pPointData) { me->SetSpeed(MOVE_FLIGHT, 1.0f); me->GetMotionMaster()->MovePoint(m_pPointData->uiLocId, m_pPointData->fX, m_pPointData->fY, m_pPointData->fZ); } break; case 9: me->GetMotionMaster()->MoveChase(me->getVictim()); m_uiBellowingRoarTimer = 1000; break; case 10: me->SetFlying(true); me->GetMotionMaster()->MovePoint(11, Phase2Location.GetPositionX(), Phase2Location.GetPositionY(), Phase2Location.GetPositionZ()+25); me->SetSpeed(MOVE_FLIGHT, 1.0f); DoScriptText(SAY_PHASE_2_TRANS, me); if (m_instance) m_instance->SetData(DATA_ONYXIA_PHASE, m_uiPhase); m_uiWhelpTimer = 5000; m_uiLairGuardTimer = 15000; break; case 11: if (m_pPointData) me->GetMotionMaster()->MovePoint(m_pPointData->uiLocId, m_pPointData->fX, m_pPointData->fY, m_pPointData->fZ); me->GetMotionMaster()->Clear(false); me->GetMotionMaster()->MoveIdle(); break; default: m_bIsMoving = false; break; } } } void SpellHitTarget(Unit* target, const SpellEntry* pSpell) { //Workaround - Couldn't find a way to group this spells (All Eruption) if (((pSpell->Id >= 17086 && pSpell->Id <= 17095) || (pSpell->Id == 17097) || (pSpell->Id >= 18351 && pSpell->Id <= 18361) || (pSpell->Id >= 18564 && pSpell->Id <= 18576) || (pSpell->Id >= 18578 && pSpell->Id <= 18607) || (pSpell->Id == 18609) || (pSpell->Id >= 18611 && pSpell->Id <= 18628) || (pSpell->Id >= 21132 && pSpell->Id <= 21133) || (pSpell->Id >= 21135 && pSpell->Id <= 21139) || (pSpell->Id >= 22191 && pSpell->Id <= 22202) || (pSpell->Id >= 22267 && pSpell->Id <= 22268)) && (target->GetTypeId() == TYPEID_PLAYER)) { if (m_instance) { m_instance->SetData(DATA_SHE_DEEP_BREATH_MORE, FAIL); } } } sOnyxMove* GetMoveData() { uint32 uiMaxCount = sizeof(aMoveData)/sizeof(sOnyxMove); for (uint32 i = 0; i < uiMaxCount; ++i) { if (aMoveData[i].uiLocId == m_uiMovePoint) return &aMoveData[i]; } return NULL; } void SetNextRandomPoint() { uint32 uiMaxCount = sizeof(aMoveData)/sizeof(sOnyxMove); uint32 iTemp = rand()%(uiMaxCount-1); if (iTemp >= m_uiMovePoint) ++iTemp; m_uiMovePoint = iTemp; } void UpdateAI(const uint32 uiDiff) { if (!UpdateVictim()) return; //Common to PHASE_START && PHASE_END if (m_uiPhase == PHASE_START || m_uiPhase == PHASE_END) { //Specific to PHASE_START || PHASE_END if (m_uiPhase == PHASE_START) { if (HealthBelowPct(60)) { SetCombatMovement(false); m_uiPhase = PHASE_BREATH; me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, true); me->ApplySpellImmune(0, IMMUNITY_EFFECT,SPELL_EFFECT_ATTACK_ME, true); me->GetMotionMaster()->MovePoint(10, Phase2Location); return; } } else { if (m_uiBellowingRoarTimer <= uiDiff) { DoCastVictim(SPELL_BELLOWING_ROAR); // Eruption GameObject* pFloor = NULL; Trinity::GameObjectInRangeCheck check(me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), 15); Trinity::GameObjectLastSearcher<Trinity::GameObjectInRangeCheck> searcher(me, pFloor, check); me->VisitNearbyGridObject(30, searcher); if (m_instance && pFloor) m_instance->SetData64(DATA_FLOOR_ERUPTION_GUID, pFloor->GetGUID()); m_uiBellowingRoarTimer = 30000; } else m_uiBellowingRoarTimer -= uiDiff; } if (m_uiFlameBreathTimer <= uiDiff) { DoCastVictim(SPELL_FLAME_BREATH); m_uiFlameBreathTimer = urand(10000, 20000); } else m_uiFlameBreathTimer -= uiDiff; if (m_uiTailSweepTimer <= uiDiff) { DoCastAOE(SPELL_TAIL_SWEEP); m_uiTailSweepTimer = urand(15000, 20000); } else m_uiTailSweepTimer -= uiDiff; if (m_uiCleaveTimer <= uiDiff) { DoCastVictim(SPELL_CLEAVE); m_uiCleaveTimer = urand(2000, 5000); } else m_uiCleaveTimer -= uiDiff; if (m_uiWingBuffetTimer <= uiDiff) { DoCastVictim(SPELL_WING_BUFFET); m_uiWingBuffetTimer = urand(15000, 30000); } else m_uiWingBuffetTimer -= uiDiff; DoMeleeAttackIfReady(); } else { if (HealthBelowPct(40)) { m_uiPhase = PHASE_END; if (m_instance) m_instance->SetData(DATA_ONYXIA_PHASE, m_uiPhase); DoScriptText(SAY_PHASE_3_TRANS, me); SetCombatMovement(true); me->SetFlying(false); m_bIsMoving = false; me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, false); me->ApplySpellImmune(0, IMMUNITY_EFFECT,SPELL_EFFECT_ATTACK_ME, false); me->GetMotionMaster()->MovePoint(9,me->GetHomePosition()); return; } if (m_uiDeepBreathTimer <= uiDiff) { if (!m_bIsMoving) { if (me->IsNonMeleeSpellCasted(false)) me->InterruptNonMeleeSpells(false); DoScriptText(EMOTE_BREATH, me); DoCast(me, m_pPointData->uiSpellId); m_uiDeepBreathTimer = 70000; } } else m_uiDeepBreathTimer -= uiDiff; if (m_uiMovementTimer <= uiDiff) { if (!m_bIsMoving) { SetNextRandomPoint(); m_pPointData = GetMoveData(); if (!m_pPointData) return; me->GetMotionMaster()->MovePoint(m_pPointData->uiLocId, m_pPointData->fX, m_pPointData->fY, m_pPointData->fZ); m_bIsMoving = true; m_uiMovementTimer = 25000; } } else m_uiMovementTimer -= uiDiff; if (m_uiFireballTimer <= uiDiff) { if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() != POINT_MOTION_TYPE) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) DoCast(target, SPELL_FIREBALL); m_uiFireballTimer = 8000; } } else m_uiFireballTimer -= uiDiff; if (m_uiLairGuardTimer <= uiDiff) { me->SummonCreature(NPC_LAIRGUARD, aSpawnLocations[2].GetPositionX(), aSpawnLocations[2].GetPositionY(), aSpawnLocations[2].GetPositionZ(), 0.0f, TEMPSUMMON_CORPSE_DESPAWN); m_uiLairGuardTimer = 30000; } else m_uiLairGuardTimer -= uiDiff; if (m_uiWhelpTimer <= uiDiff) { me->SummonCreature(NPC_WHELP, aSpawnLocations[0].GetPositionX(), aSpawnLocations[0].GetPositionY(), aSpawnLocations[0].GetPositionZ(), 0.0f, TEMPSUMMON_CORPSE_DESPAWN); me->SummonCreature(NPC_WHELP, aSpawnLocations[1].GetPositionX(), aSpawnLocations[1].GetPositionY(), aSpawnLocations[1].GetPositionZ(), 0.0f, TEMPSUMMON_CORPSE_DESPAWN); if (m_uiSummonWhelpCount >= RAID_MODE(20, 40)) { m_uiSummonWhelpCount = 0; m_uiWhelpTimer = 90000; } else m_uiWhelpTimer = 500; } else m_uiWhelpTimer -= uiDiff; } } }; }; class npc_onyxia_lairguard : public CreatureScript { public: npc_onyxia_lairguard() : CreatureScript("npc_onyxia_lairguard") { } CreatureAI* GetAI(Creature* creature) const { return new npc_onyxia_lairguardAI(creature); } struct npc_onyxia_lairguardAI : public ScriptedAI { npc_onyxia_lairguardAI(Creature* creature) : ScriptedAI(creature) { m_instance = creature->GetInstanceScript(); Reset(); } InstanceScript* m_instance; uint32 m_uiLairGuardCleaveTimer; bool novadone; bool ignitedone; void Reset() { novadone = false; ignitedone = false; m_uiLairGuardCleaveTimer = urand(5000, 10000); } void UpdateAI(const uint32 uiDiff) { if (!UpdateVictim()) return; if (me->HasUnitState(UNIT_STAT_CASTING)) return; if (!ignitedone) { DoCast(me, SPELL_LAIRGUARDIGNITE); ignitedone = true; } if (!novadone && HealthBelowPct(25)) { DoCast(me, SPELL_LAIRGUARDBLASTNOVA, true); novadone = true; } if (m_uiLairGuardCleaveTimer <= uiDiff) { DoCast(me->getVictim(), SPELL_LAIRGUARDCLEAVE); m_uiLairGuardCleaveTimer = urand(5000, 10000); } else m_uiLairGuardCleaveTimer -= uiDiff; DoMeleeAttackIfReady(); } }; }; void AddSC_boss_onyxia() { new boss_onyxia(); new npc_onyxia_lairguard(); }
34.550775
192
0.506825
FrenchCORE
eb1e0ebbe1b88faf7c231da8b4c74218249a8e80
3,941
cpp
C++
src/core/technology.cpp
awlck/stellaris-stat-viewer
454d0286b07bcdf2b1b519d6a62ca9c569abc468
[ "Apache-2.0" ]
2
2019-05-28T13:43:33.000Z
2019-06-06T22:08:55.000Z
src/core/technology.cpp
awlck/stellaris-stat-viewer
454d0286b07bcdf2b1b519d6a62ca9c569abc468
[ "Apache-2.0" ]
8
2019-03-19T11:44:46.000Z
2019-06-03T11:43:07.000Z
src/core/technology.cpp
awlck/stellaris-stat-viewer
454d0286b07bcdf2b1b519d6a62ca9c569abc468
[ "Apache-2.0" ]
1
2020-03-08T21:02:35.000Z
2020-03-08T21:02:35.000Z
/* core/technology.cpp: Extracting technology information from an AST. * * Copyright 2019 Adrian "ArdiMaster" Welcker * * 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 "technology.h" #include "model_private_macros.h" #include "parser.h" using Parsing::AstNode; namespace Galaxy { Technology::Technology(QObject *parent) : QObject(parent) {} const QString &Technology::getName() const { return name; } const QStringList &Technology::getRequirements() const { return requirements; } bool Technology::getIsStartingTech() const { return isStartingTech; } bool Technology::getIsRare() const { return isRare; } bool Technology::getIsRepeatable() const { return isRepeatable; } bool Technology::getIsWeightZero() const { return isWeightZero; } const QList<WeightModifier>& Technology::getWeightModifyingTechs() const { return weightModifyingTechs; } int Technology::getTier() const { return tier; } TechArea Technology::getArea() const { return area; } Technology *Technology::createFromAst(const Parsing::AstNode *node, QObject *parent) { Technology *state = new Technology(parent); state->name = QString(node->myName); AstNode *areaNode = node->findChildWithName("area"); CHECK_PTR(areaNode); if (qstrcmp(areaNode->val.Str, "engineering") == 0) state->area = TechArea::Engineering; else if (qstrcmp(areaNode->val.Str, "society") == 0) state->area = TechArea::Society; else if (qstrcmp(areaNode->val.Str, "physics") == 0) state->area = TechArea::Physics; else { delete state; return nullptr; } AstNode *startTechNode = node->findChildWithName("start_tech"); state->isStartingTech = startTechNode ? startTechNode->val.Bool : false; AstNode *rareNode = node->findChildWithName("is_rare"); state->isRare = rareNode ? rareNode->val.Bool : false; state->isRepeatable = state->name.startsWith("tech_repeatable_"); if (!state->isRepeatable) { AstNode *tierNode = node->findChildWithName("tier"); CHECK_PTR(tierNode); state->tier = tierNode->val.Int; } else state->tier = -1; AstNode *prerequisitesNode = node->findChildWithName("prerequisites"); if (prerequisitesNode && prerequisitesNode->type == Parsing::NT_STRINGLIST) { ITERATE_CHILDREN(prerequisitesNode, aPrerequisite) { state->requirements.append(aPrerequisite->val.Str); } } AstNode *weightNode = node->findChildWithName("weight"); state->isWeightZero = !weightNode || (weightNode->type == Parsing::NT_INT && weightNode->val.Int == 0); AstNode *weightModifierNode = node->findChildWithName("weight_modifier"); if (weightModifierNode) { ITERATE_CHILDREN(weightModifierNode, modifier) { if (qstrcmp(modifier->myName, "modifier") == 0) { if (modifier->countChildren() != 2) continue; AstNode *factorNode = modifier->findChildWithName("factor"); AstNode *hasTechNode = modifier->findChildWithName("has_technology"); if (!factorNode || !hasTechNode) continue; if (hasTechNode->type != Parsing::NT_STRING) continue; switch (factorNode->type) { case Parsing::NT_INT: state->weightModifyingTechs.append({QString(hasTechNode->val.Str), (double) factorNode->val.Int}); break; case Parsing::NT_DOUBLE: state->weightModifyingTechs.append({QString(hasTechNode->val.Str), factorNode->val.Double}); break; default: continue; } } } } return state; } }
32.04065
105
0.710226
awlck
eb2a24dc18716cab6697c6fa3608c3806d954948
5,322
cc
C++
crosdns/hosts_modifier_test.cc
dgreid/platform2
9b8b30df70623c94f1c8aa634dba94195343f37b
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
crosdns/hosts_modifier_test.cc
dgreid/platform2
9b8b30df70623c94f1c8aa634dba94195343f37b
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
crosdns/hosts_modifier_test.cc
dgreid/platform2
9b8b30df70623c94f1c8aa634dba94195343f37b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Chromium OS 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 "crosdns/hosts_modifier.h" #include <string> #include <base/files/scoped_temp_dir.h> #include <base/files/file_path.h> #include <base/files/file_util.h> #include <gtest/gtest.h> namespace crosdns { namespace { constexpr char kBaseFileContents[] = "# Example /etc/hosts file\n" "127.0.0.1 localhost\n"; constexpr char kFileModificationDelimeter[] = "\n#####DYNAMIC-CROSDNS-ENTRIES#####\n"; class HostsModifierTest : public ::testing::Test { public: HostsModifierTest() { CHECK(temp_dir_.CreateUniqueTempDir()); hosts_file_ = temp_dir_.GetPath().Append("hosts"); WriteHostsContents(kBaseFileContents); } HostsModifierTest(const HostsModifierTest&) = delete; HostsModifierTest& operator=(const HostsModifierTest&) = delete; ~HostsModifierTest() override = default; void WriteHostsContents(const std::string& file_contents) { EXPECT_EQ(file_contents.size(), base::WriteFile(hosts_file_, file_contents.c_str(), file_contents.size())); } std::string ReadHostsContents() const { std::string ret; EXPECT_TRUE(base::ReadFileToString(hosts_file_, &ret)); return ret; } HostsModifier* hosts_modifier() { return &hosts_modifier_; } base::FilePath hosts_file() const { return hosts_file_; } private: base::ScopedTempDir temp_dir_; base::FilePath hosts_file_; HostsModifier hosts_modifier_; }; } // namespace TEST_F(HostsModifierTest, InitSucceeds) { EXPECT_TRUE(hosts_modifier()->Init(hosts_file())); // The hosts file contents should be unchanged now. EXPECT_EQ(kBaseFileContents, ReadHostsContents()); } TEST_F(HostsModifierTest, InitFailsNonExistentFile) { EXPECT_TRUE(base::DeleteFile(hosts_file())); EXPECT_FALSE(hosts_modifier()->Init(hosts_file())); } TEST_F(HostsModifierTest, InitRemovesOldEntries) { std::string extra_contents = kBaseFileContents; extra_contents += kFileModificationDelimeter; extra_contents += "1.2.3.4 example.com\n"; WriteHostsContents(extra_contents); EXPECT_TRUE(hosts_modifier()->Init(hosts_file())); // The hosts file contents should be the original contents up to our // delimeter. EXPECT_EQ(kBaseFileContents, ReadHostsContents()); } TEST_F(HostsModifierTest, SettingRemovingHostnames) { std::string err; EXPECT_TRUE(hosts_modifier()->Init(hosts_file())); // Valid hostname for default container. EXPECT_TRUE(hosts_modifier()->SetHostnameIpMapping( "penguin.linux.test", "100.115.92.24", "", &err)); // Valid hostnames for vm/container. EXPECT_TRUE(hosts_modifier()->SetHostnameIpMapping( "foo12.linux.test", "100.115.92.22", "", &err)); EXPECT_TRUE(hosts_modifier()->SetHostnameIpMapping( "penguin.termina.linux.test", "100.115.92.253", "", &err)); // Invalid hostnames. EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "google.com", "100.115.92.24", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "localhost", "100.115.92.24", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "-foo-local", "100.115.92.24", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "foo..linux.test", "100.115.92.24", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( ".linux.test", "100.115.92.24", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "linux.test", "100.115.92.24", "", &err)); EXPECT_FALSE( hosts_modifier()->SetHostnameIpMapping("", "100.115.92.24", "", &err)); // Invalid IPs. EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "penguin.linux.test", "100.115.91.24", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping("penguin.linux.test", "8.8.8.8", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "penguin.linux.test", "101.115.92.24", "", &err)); // Verify the contents of the hosts file. We are assuming an ordered map is // used here (which it is in the code) to make analyzing the results easier. std::string extra_contents = kBaseFileContents; extra_contents += kFileModificationDelimeter; extra_contents += "100.115.92.22 foo12.linux.test\n"; extra_contents += "100.115.92.24 penguin.linux.test\n"; extra_contents += "100.115.92.253 penguin.termina.linux.test\n"; EXPECT_EQ(extra_contents, ReadHostsContents()); // Removing an invalid hostname should fail. EXPECT_FALSE(hosts_modifier()->RemoveHostnameIpMapping("bar-local", &err)); EXPECT_FALSE(hosts_modifier()->RemoveHostnameIpMapping("google.com", &err)); // Removing a valid hostname should succeed. EXPECT_TRUE( hosts_modifier()->RemoveHostnameIpMapping("penguin.linux.test", &err)); EXPECT_TRUE( hosts_modifier()->RemoveHostnameIpMapping("foo12.linux.test", &err)); // Verify the contents of the hosts file again, there should be one entry // left. extra_contents = kBaseFileContents; extra_contents += kFileModificationDelimeter; extra_contents += "100.115.92.253 penguin.termina.linux.test\n"; EXPECT_EQ(extra_contents, ReadHostsContents()); } } // namespace crosdns
37.744681
78
0.708568
dgreid
eb3217a3380b7b765ddf7ba8a8ee22cf96fa262b
2,662
cpp
C++
algorithms/binary_search_tree.cpp
sylveryte/algorithms-data-structure-cpp
3fc4690972fa061851f7a46a06797bf441043eda
[ "MIT" ]
null
null
null
algorithms/binary_search_tree.cpp
sylveryte/algorithms-data-structure-cpp
3fc4690972fa061851f7a46a06797bf441043eda
[ "MIT" ]
null
null
null
algorithms/binary_search_tree.cpp
sylveryte/algorithms-data-structure-cpp
3fc4690972fa061851f7a46a06797bf441043eda
[ "MIT" ]
null
null
null
/* * binary_search_tree.cpp * Copyright (C) 2020 sylveryte <sylveryte@archred> * * Distributed under terms of the MIT license. */ #include "binary_search_tree.h" #include "../sylvtools.cpp" int main(){ binary_search_tree b(21); b.insert(21); b.insert(1); b.insert(23); b.insert(233); b.insert(4); b.print_tree(); //to sort //yeah!! i'm amazing int a[13]={12,24,54,2,452,36,23,6,325732,45,2346234,23,1}; printa("before",a,13); binary_search_tree sor(12); for(int i=1;i<13;i++)sor.insert(a[i]); sor.print_tree(); sor.get_sorted_array(a); printa("after",a,13); return 0; } //implementations binary_search_tree::binary_search_tree(int value){ this -> head = new node(value); this -> size = 1; } void binary_search_tree::insert(int value){ node* node_ptr = this -> head; while(true) if(node_ptr -> value >= value){ //cout << "arg " << node_ptr-> value << " <= " << value << endl; //cout << "adding " << value << " to left" << endl; if( node_ptr -> leftchild == nullptr) { node_ptr -> leftchild = new node(value); node_ptr -> leftchild -> parent = node_ptr; this -> size++; break; } node_ptr = node_ptr -> leftchild; } else{ //cout << "arg " << node_ptr-> value << " > " << value << endl; //cout << "adding " << value << " to rigth" << endl; if( node_ptr -> rightchild == nullptr) { node_ptr -> rightchild = new node(value); node_ptr -> rightchild -> parent = node_ptr; this -> size++; break; } node_ptr = node_ptr -> rightchild; } } void binary_search_tree::inorder_traverse(int* a, node* n){ /* takes an empty array a and node from where sorted array needed. * fills array with ascending order node vallues (sorted array) using inorder_traverssal * */ if(n-> leftchild != nullptr)inorder_traverse(a,n->leftchild); a[this -> inorder_index++]=n->value; if(n-> rightchild != nullptr)inorder_traverse(a,n->rightchild); } void binary_search_tree::get_sorted_array(int* a){ this -> inorder_index = 0; inorder_traverse(a,this->head); } /* printing purpose */ void binary_search_tree::print_node(node* ptr){ if(ptr -> leftchild == nullptr && ptr -> rightchild == nullptr)return; cout << "|| " << ptr -> value << " : "; if(ptr->leftchild != nullptr){ cout << ptr-> leftchild-> value ; } cout<< " _ "; if(ptr->rightchild != nullptr){ cout << ptr-> rightchild-> value ; } cout << " ||" << endl; if(ptr->leftchild != nullptr)print_node(ptr->leftchild); if(ptr->rightchild != nullptr)print_node(ptr->rightchild); } void binary_search_tree::print_tree(){ cout << "Tree of size : " << this->size << endl; print_node(this->head); cout <<endl; }
25.84466
89
0.635988
sylveryte
eb33b183ed90e4998b9537607d6f85c34383b990
10,369
cpp
C++
Asteroid.cpp
timaeudg/3DAsteroids
d6d3047ee4375ce2ac54081ed0311bd73023b458
[ "BSD-2-Clause" ]
1
2015-05-04T07:04:04.000Z
2015-05-04T07:04:04.000Z
Asteroid.cpp
timaeudg/3DAsteroids
d6d3047ee4375ce2ac54081ed0311bd73023b458
[ "BSD-2-Clause" ]
null
null
null
Asteroid.cpp
timaeudg/3DAsteroids
d6d3047ee4375ce2ac54081ed0311bd73023b458
[ "BSD-2-Clause" ]
null
null
null
#include "Asteroid.h" #define REFINEMENT_LEVEL 2 #define BASE_RADIUS 1.9021f #define MAX_VELOCITY 0.05 #define MAX_ROTATION 5.0 float Asteroid::nextID = 1.0; Asteroid::Asteroid(){ Asteroid(glm::vec3(0), 0, 1.9021); } Asteroid::Asteroid(glm::vec3 startingPosition, int elementOffset, GLfloat radius) { this->radius = radius; setStartingPoint(startingPosition); this->elementOffset = elementOffset; alive = true; asteroidID = nextID; nextID += 1.0; generateAsteroidBase(); deformAndTransformBase(); calculateDeformedResultantRadius(); GLfloat xPos = -MAX_VELOCITY + (float)rand()/((float)RAND_MAX/(MAX_VELOCITY-(-MAX_VELOCITY))); GLfloat yPos = -MAX_VELOCITY + (float)rand()/((float)RAND_MAX/(MAX_VELOCITY-(-MAX_VELOCITY))); GLfloat zPos = -MAX_VELOCITY + (float)rand()/((float)RAND_MAX/(MAX_VELOCITY-(-MAX_VELOCITY))); velocityVector = glm::vec3(xPos, yPos, zPos); GLfloat xRot = -MAX_ROTATION + (float)rand()/((float)RAND_MAX/(MAX_ROTATION-(-MAX_ROTATION))); GLfloat yRot = -MAX_ROTATION + (float)rand()/((float)RAND_MAX/(MAX_ROTATION-(-MAX_ROTATION))); GLfloat zRot = -MAX_ROTATION + (float)rand()/((float)RAND_MAX/(MAX_ROTATION-(-MAX_ROTATION))); this->rotationRates = glm::vec3(xRot, yRot, zRot); this->rotation = glm::mat4(1); } Asteroid::~Asteroid(void) { } vector<GLfloat> Asteroid::getNormals(){ return this->asteroidGLNormals; } vector<GLfloat> Asteroid::getVertices(){ return this->asteroidGLVertices; } vector<GLuint> Asteroid::getElementArray(){ return elements; } vector<GLfloat> Asteroid::getColors(){ return colors; } glm::vec3 Asteroid::getPosition(){ return this->position; } GLfloat Asteroid::getRadius(){ return this->radius; } bool Asteroid::isAlive(){ return alive; } void Asteroid::kill(){ this->alive = false; } float Asteroid::getID(){ return this->asteroidID; } void Asteroid::setStartingPoint(glm::vec3 startingPosition){ this->position = startingPosition; glm::vec3 translateVector = this->position; this->translation = glm::translate(glm::mat4(1), translateVector); } glm::mat4 Asteroid::getTransformMatrix(float bounds, bool pickingPass){ glm::mat4 S = glm::scale(glm::mat4(1), glm::vec3(radius / deformedResultantRadius, radius / deformedResultantRadius, radius / deformedResultantRadius)); if(!pickingPass){ this->position += velocityVector; glm::mat4 T = glm::translate(this->translation, velocityVector); this->translation = T; if(this->position.x + radius >= bounds || this->position.x - radius <= -bounds){ velocityVector = glm::vec3(-velocityVector.x, velocityVector.y, velocityVector.z); rotationRates = glm::vec3(rotationRates.x, -rotationRates.y, -rotationRates.z); } if(this->position.y + radius >= bounds || this->position.y - radius <= -bounds){ velocityVector = glm::vec3(velocityVector.x, -velocityVector.y, velocityVector.z); rotationRates = glm::vec3(-rotationRates.x, rotationRates.y, -rotationRates.z); } if(this->position.z + radius>= bounds || this->position.z - radius<= -bounds){ velocityVector = glm::vec3(velocityVector.x, velocityVector.y, -velocityVector.z); rotationRates = glm::vec3(-rotationRates.x, -rotationRates.y, rotationRates.z); } glm::mat4 R = glm::rotate(this->rotation, rotationRates.x, glm::vec3(1,0,0)); R = glm::rotate(R, rotationRates.y, glm::vec3(0,1,0)); R = glm::rotate(R, rotationRates.z, glm::vec3(0,0,1)); this->rotation = R; return T*R*S; } else { return this->translation * this->rotation * S; } } void Asteroid::generateAsteroidBase(){ if(this->asteroidPoints.size() == 0){ //We haven't made the base of the asteroid, so we need to createIcosahedronPoints(); createIcosahedronTriangles(); //Now we have the icosahedron, we should make it a bit better though for(int i = 0; i < REFINEMENT_LEVEL; i++){ deformAsteroid(&this->asteroidPoints); refineIcoSphere(); } } } void Asteroid::deformAndTransformBase(){ transformToGL(); vector<GLuint> elements = vector<GLuint>(); for(int i = 0; i < this->asteroidTriangles.size()*3; i++){ elements.push_back(i+this->elementOffset); } this->elements = elements; for(int i = 0; i < this->asteroidGLVertices.size(); i++){ this->colors.push_back(1.0f); this->colors.push_back(1.0f); this->colors.push_back(1.0f); } } void Asteroid::transformToGL(){ for(int i = 0; i < this->asteroidTriangles.size(); i++){ Triangle* tri = &this->asteroidTriangles[i]; tri->recalculateNormal(this->asteroidPoints[tri->p1Index], this->asteroidPoints[tri->p2Index], this->asteroidPoints[tri->p3Index]); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p1Index].coords.r); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p1Index].coords.g); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p1Index].coords.b); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p2Index].coords.r); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p2Index].coords.g); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p2Index].coords.b); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p3Index].coords.r); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p3Index].coords.g); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p3Index].coords.b); for(int k = 0; k < 3; k++){ this->asteroidGLNormals.push_back(tri->normal.r); this->asteroidGLNormals.push_back(tri->normal.g); this->asteroidGLNormals.push_back(tri->normal.b); } } } void Asteroid::deformAsteroid(vector<Point>* points){ //srand(time(NULL)); for(int i = 0; i < points->size(); i++){ points->data()[i].moveInRandomDirection(1.0f); } } void Asteroid::createIcosahedronPoints(){ GLfloat reductionFactor = 1; GLfloat baseSize = 1; GLfloat t = (1.0 + sqrt(5.0)) / 2.0; t = reductionFactor * t; baseSize = baseSize * reductionFactor; this->asteroidPoints.push_back(Point(-baseSize, t, 0)); this->asteroidPoints.push_back(Point( baseSize, t, 0)); this->asteroidPoints.push_back(Point(-baseSize, -t, 0)); this->asteroidPoints.push_back(Point( baseSize, -t, 0)); this->asteroidPoints.push_back(Point( 0, -baseSize, t)); this->asteroidPoints.push_back(Point( 0, baseSize, t)); this->asteroidPoints.push_back(Point( 0, -baseSize, -t)); this->asteroidPoints.push_back(Point( 0, baseSize, -t)); this->asteroidPoints.push_back(Point( t, 0, -baseSize)); this->asteroidPoints.push_back(Point( t, 0, baseSize)); this->asteroidPoints.push_back(Point(-t, 0, -baseSize)); this->asteroidPoints.push_back(Point(-t, 0, baseSize)); } void Asteroid::createIcosahedronTriangles(){ this->asteroidTriangles.push_back(Triangle( 0, 11, 5)); this->asteroidTriangles.push_back(Triangle( 0, 5, 1)); this->asteroidTriangles.push_back(Triangle( 0, 1, 7)); this->asteroidTriangles.push_back(Triangle( 0, 7, 10)); this->asteroidTriangles.push_back(Triangle( 0, 10, 11)); this->asteroidTriangles.push_back(Triangle( 1, 5, 9)); this->asteroidTriangles.push_back(Triangle( 5, 11, 4)); this->asteroidTriangles.push_back(Triangle(11, 10, 2)); this->asteroidTriangles.push_back(Triangle(10, 7, 6)); this->asteroidTriangles.push_back(Triangle( 7, 1, 8)); this->asteroidTriangles.push_back(Triangle( 3, 9, 4)); this->asteroidTriangles.push_back(Triangle( 3, 4, 2)); this->asteroidTriangles.push_back(Triangle( 3, 2, 6)); this->asteroidTriangles.push_back(Triangle( 3, 6, 8)); this->asteroidTriangles.push_back(Triangle( 3, 8, 9)); this->asteroidTriangles.push_back(Triangle( 4, 9, 5)); this->asteroidTriangles.push_back(Triangle( 2, 4, 11)); this->asteroidTriangles.push_back(Triangle( 6, 2, 10)); this->asteroidTriangles.push_back(Triangle( 8, 6, 7)); this->asteroidTriangles.push_back(Triangle( 9, 8, 1)); } int Asteroid::calculateMiddlePoint(int p1, int p2, vector<Point>* points){ bool firstSmaller = p1 < p2; int64_t smallerIndex = firstSmaller ? p1 : p2; int64_t greaterIndex = firstSmaller ? p2 : p1; int64_t key = (smallerIndex << 32) + greaterIndex; map<int64_t, int>::iterator iter = middlePointCache.find(key); if(iter != middlePointCache.end()){ //We found the element return iter->second; } Point* first = &((*points)[p1]); Point* second = &((*points)[p2]); Point middlePoint = Point((first->coords.r + second->coords.r)/2.0, (first->coords.g + second->coords.g)/2.0, (first->coords.b + second->coords.b)/2.0); int index = affixVertex(middlePoint, *first, points); middlePointCache.insert(make_pair(key, index)); return index; } int Asteroid::affixVertex(Point middlePoint, Point derpPoint, vector<Point>* pointsVector){ double derpLength = sqrt(derpPoint.coords.r*derpPoint.coords.r + derpPoint.coords.g*derpPoint.coords.g + derpPoint.coords.b*derpPoint.coords.b); double length = sqrt(middlePoint.coords.r*middlePoint.coords.r + middlePoint.coords.g*middlePoint.coords.g + middlePoint.coords.b*middlePoint.coords.b); double ration = derpLength / length; //ration = 1 / length; //length = length/2; (*pointsVector).push_back(Point(middlePoint.coords.r * ration, middlePoint.coords.g * ration, middlePoint.coords.b * ration)); return (*pointsVector).size()-1; } void Asteroid::refineIcoSphere(){ vector<Triangle> refined = vector<Triangle>(); for(int i = 0; i < this->asteroidTriangles.size(); i++){ Triangle tri = this->asteroidTriangles[i]; int a = calculateMiddlePoint(tri.p1Index, tri.p2Index, &this->asteroidPoints); int b = calculateMiddlePoint(tri.p2Index, tri.p3Index, &this->asteroidPoints); int c = calculateMiddlePoint(tri.p3Index, tri.p1Index, &this->asteroidPoints); refined.push_back(Triangle(tri.p1Index, a, c)); refined.push_back(Triangle(tri.p2Index, b, a)); refined.push_back(Triangle(tri.p3Index, c, b)); refined.push_back(Triangle(a, b, c)); } this->asteroidTriangles = refined; } void Asteroid::calculateDeformedResultantRadius(){ GLfloat maxRadius = BASE_RADIUS; for(int i = 0; i < this->asteroidPoints.size(); i++){ Point p = this->asteroidPoints.data()[i]; GLfloat currentRadius = sqrt(p.coords.r*p.coords.r + p.coords.g*p.coords.g + p.coords.b*p.coords.g); if(currentRadius > maxRadius){ maxRadius = currentRadius; } } this->deformedResultantRadius = maxRadius; }
34.448505
153
0.710001
timaeudg
eb35b6ab1b405a6864b888ba7b72b6525eadf4f9
1,411
cpp
C++
Assigment 13/a13_p7.cpp
UrfanAlvany/Programming-in-C-and-Cpp
e23a485d5ce302cbbc14bd67a0f656797c3f6af1
[ "MIT" ]
1
2022-01-02T16:02:09.000Z
2022-01-02T16:02:09.000Z
Assigment 13/a13_p7.cpp
UrfanAlvany/Programming-in-C-and-Cpp
e23a485d5ce302cbbc14bd67a0f656797c3f6af1
[ "MIT" ]
null
null
null
Assigment 13/a13_p7.cpp
UrfanAlvany/Programming-in-C-and-Cpp
e23a485d5ce302cbbc14bd67a0f656797c3f6af1
[ "MIT" ]
null
null
null
#include <iostream> #include <stdexcept> #include <string> using namespace std; class OwnException: public exception{ //class derived from exception private: string a; //declaring string public: OwnException(){ a = "Default case exception"; //when default thsi is printed } OwnException(const string& s){ this->a = a; } virtual const char* what() const throw(){ //overwriting what() return "OwnException"; } }; void types(int n){ switch(n){ case 1: //when parameter is 1 a is thrown throw 'a'; break; case 2: //when parameter is 2, 12 is thrown throw 12; break; case 3: //when parameter is 3, bool is true throw true; break; default: //default throw new OwnException; } return; } int main(){ try{ types(1); //try with parameter 1 } catch(char ch){ cerr<<"Exception caught in main: "<<ch<<endl; } try{ types(2); //try with parameter 2 } catch(int i){ cerr<<"Exception caught in main: "<<i<<endl; } try{ types(3); //try with parameter 3 } catch(bool t){ cerr<<"Exception caught in main: "<<t<<endl; } try{ types(4); //try with parameter 4 } catch(OwnException* m){ cerr<<"Exception caught in main: "<<m->what()<<endl; } return 1; }
20.75
68
0.554926
UrfanAlvany
eb36232e45bd0e485e485524f1039cc48db55613
6,137
cpp
C++
samples/tools/save_pose_into_pcd.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
17
2015-11-16T14:21:10.000Z
2020-11-09T02:57:33.000Z
samples/tools/save_pose_into_pcd.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
35
2015-07-27T15:04:43.000Z
2019-08-22T10:52:35.000Z
samples/tools/save_pose_into_pcd.cpp
ToMadoRe/v4r
7cb817e05cb9d99cb2f68db009c27d7144d07f09
[ "MIT" ]
18
2015-08-06T09:26:27.000Z
2020-09-03T01:31:00.000Z
/* * adds pose information given by pose_000x.txt into cloud_000x.pcd files (old dataset structure) * now we can use pcl_viewer *.pcd to show all point clouds in common coordinate system * * Created on: Dec 04, 2014 * Author: Thomas Faeulhammer * */ #include <v4r/io/filesystem.h> #include <v4r/io/eigen.h> #include <v4r/common/faat_3d_rec_framework_defines.h> #include <v4r/common/pcl_utils.h> #include <pcl/common/transforms.h> #include <pcl/console/parse.h> #include <pcl/io/pcd_io.h> #include <iostream> #include <sstream> #include <boost/program_options.hpp> #include <glog/logging.h> namespace po = boost::program_options; typedef pcl::PointXYZRGB PointT; int main (int argc, char ** argv) { std::string input_dir, out_dir = "/tmp/clouds_with_pose/"; std::string cloud_prefix = "cloud_", pose_prefix = "pose_", indices_prefix = "object_indices_"; bool invert_pose = false; bool use_indices = false; po::options_description desc("Save camera pose given by seperate pose file directly into header of .pcd file\n======================================\n**Allowed options"); desc.add_options() ("help,h", "produce help message") ("input_dir,i", po::value<std::string>(&input_dir)->required(), "directory containing both .pcd and pose files") ("output_dir,o", po::value<std::string>(&out_dir)->default_value(out_dir), "output directory") ("use_indices,u", po::bool_switch(&use_indices), "if true, uses indices") ("invert_pose,t", po::bool_switch(&invert_pose), "if true, takes the inverse of the pose file (e.g. required for Willow Dataset)") ("cloud_prefix,c", po::value<std::string>(&cloud_prefix)->default_value(cloud_prefix)->implicit_value(""), "prefix of cloud names") ("pose_prefix,p", po::value<std::string>(&pose_prefix)->default_value(pose_prefix), "prefix of camera pose names (e.g. transformation_)") ("indices_prefix,d", po::value<std::string>(&indices_prefix)->default_value(indices_prefix), "prefix of object indices names") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); if (vm.count("help")) { std::cout << desc << std::endl; return false; } try { po::notify(vm); } catch(std::exception& e) { std::cerr << "Error: " << e.what() << std::endl << std::endl << desc << std::endl; return false; } std::vector< std::string> sub_folder_names = v4r::io::getFoldersInDirectory( input_dir ); if( sub_folder_names.empty() ) sub_folder_names.push_back(""); for (const std::string &sub_folder : sub_folder_names) { const std::string path_extended = input_dir + "/" + sub_folder; std::cout << "Processing all point clouds in folder " << path_extended; // const std::string search_pattern = ".*." + cloud_prefix + ".*.pcd"; const std::string search_pattern = ".*.pcd"; std::vector < std::string > cloud_files = v4r::io::getFilesInDirectory (path_extended, search_pattern, true); for (const std::string &cloud_file : cloud_files) { const std::string full_path = path_extended + "/" + cloud_file; const std::string out_fn = out_dir + "/" + sub_folder + "/" + cloud_file; // Loading file and corresponding indices file (if it exists) pcl::PointCloud<PointT>::Ptr cloud (new pcl::PointCloud<PointT>); pcl::io::loadPCDFile (full_path, *cloud); if(use_indices) { // Check if indices file exist std::string indices_filename( cloud_file ); boost::replace_first (indices_filename, cloud_prefix, indices_prefix); if( v4r::io::existsFile( path_extended+"/"+indices_filename ) ) { pcl::PointCloud<IndexPoint> obj_indices_cloud; pcl::io::loadPCDFile(path_extended+"/"+indices_filename, obj_indices_cloud); pcl::PointIndices indices; indices.indices.resize(obj_indices_cloud.points.size()); for(size_t kk=0; kk < obj_indices_cloud.points.size(); kk++) indices.indices[kk] = obj_indices_cloud.points[kk].idx; pcl::copyPointCloud(*cloud, indices, *cloud); } else { boost::replace_last( indices_filename, ".pcd", ".txt"); if( v4r::io::existsFile( path_extended+"/"+indices_filename ) ) { std::vector<int> indices; int idx_tmp; std::ifstream mask_f( path_extended+"/"+indices_filename ); while (mask_f >> idx_tmp) indices.push_back(idx_tmp); mask_f.close(); pcl::copyPointCloud(*cloud, indices, *cloud); } else { std::cerr << "Indices file " << path_extended << "/" << indices_filename << " does not exist." << std::endl; } } } // Check if pose file exist std::string pose_fn( cloud_file ); boost::replace_first (pose_fn, cloud_prefix, pose_prefix); boost::replace_last (pose_fn, ".pcd", ".txt"); const std::string full_pose_path = input_dir + pose_fn; if( v4r::io::existsFile( full_pose_path ) ) { Eigen::Matrix4f global_trans = v4r::io::readMatrixFromFile(full_pose_path); if(invert_pose) global_trans = global_trans.inverse(); v4r::setCloudPose(global_trans, *cloud); v4r::io::createDirForFileIfNotExist(out_fn); pcl::io::savePCDFileBinary(out_fn, *cloud); } else std::cerr << "Pose file " << full_pose_path << " does not exist." << std::endl; } } }
42.618056
174
0.575363
ToMadoRe
eb3657cc9e281efeb7c55ddaac0e7294e6f34004
1,704
cpp
C++
src/PostProcessing/PostProcessing.cpp
ArjenSimons/RayTracing
3f2e8084fa61c7d2372b5a87d3f95901e8518524
[ "CC0-1.0" ]
2
2022-02-08T13:48:02.000Z
2022-02-08T13:48:05.000Z
src/PostProcessing/PostProcessing.cpp
ArjenSimons/RayTracing
3f2e8084fa61c7d2372b5a87d3f95901e8518524
[ "CC0-1.0" ]
null
null
null
src/PostProcessing/PostProcessing.cpp
ArjenSimons/RayTracing
3f2e8084fa61c7d2372b5a87d3f95901e8518524
[ "CC0-1.0" ]
1
2021-12-08T15:01:17.000Z
2021-12-08T15:01:17.000Z
#include "precomp.h" //TODO: Compute post processing effects on GPU void PostProcessing::Vignette(Color renderBuffer[SCRWIDTH][SCRHEIGHT], float2 uv[SCRWIDTH][SCRHEIGHT], float outerRadius, float smoothness, float intensity) { outerRadius = clamp(outerRadius, 0.0f, 1.0f); intensity = clamp(intensity, 0.0f, 1.0f); smoothness = max(0.0001f, smoothness); float innerRadius = outerRadius - smoothness; for (int i = 0; i < SCRWIDTH; i++) for (int j = 0; j < SCRHEIGHT; j++) { float2 p = uv[i][j] - .5f; float len = dot(p, p); float vignette = smoothstep(outerRadius, innerRadius, len) * intensity; renderBuffer[i][j] = renderBuffer[i][j] * vignette; } } void PostProcessing::GammaCorrection(Color renderBuffer[SCRWIDTH][SCRHEIGHT], float gamma) { float invGamma = 1 / gamma; for (int i = 0; i < SCRWIDTH; i++) for (int j = 0; j < SCRHEIGHT; j++) { float x = pow(renderBuffer[i][j].value.x, invGamma); float y = pow(renderBuffer[i][j].value.y, invGamma); float z = pow(renderBuffer[i][j].value.z, invGamma); renderBuffer[i][j] = float3(x, y, z); } } Color tempBuffer[SCRWIDTH][SCRHEIGHT]; void PostProcessing::ChromaticAberration(Color renderBuffer[SCRWIDTH][SCRHEIGHT], int2 redOffset, int2 greenOffset, int2 blueOffset) { for (int i = 0; i < SCRWIDTH; i++) for (int j = 0; j < SCRHEIGHT; j++) { float r = renderBuffer[i - redOffset.x][j - redOffset.y].value.x; float g = renderBuffer[i - greenOffset.x][j - greenOffset.y].value.y; float b = renderBuffer[i - blueOffset.x][j - blueOffset.y].value.z; tempBuffer[i][j] = float3(r, g, b); } for (int i = 0; i < SCRWIDTH; i++) for (int j = 0; j < SCRHEIGHT; j++) { renderBuffer[i][j] = tempBuffer[i][j]; } }
32.150943
156
0.670775
ArjenSimons
eb3e3b028285fd8cf10cacbe7b65ee374e3951b2
2,605
cpp
C++
test/module/irohad/main/server_runner_test.cpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
test/module/irohad/main/server_runner_test.cpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
test/module/irohad/main/server_runner_test.cpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. 2018 All Rights Reserved. * http://soramitsu.co.jp * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include <boost/format.hpp> #include "endpoint.grpc.pb.h" // any gRPC service is required for test #include "main/server_runner.hpp" boost::format address{"0.0.0.0:%d"}; auto port_visitor = iroha::make_visitor( [](iroha::expected::Value<int> x) { return x.value; }, [](iroha::expected::Error<std::string> x) { return 0; }); /** * @given a running ServerRunner * @when another ServerRunner tries to run on the same port without port reuse * @then Result with error is returned */ TEST(ServerRunnerTest, SamePortNoReuse) { ServerRunner first_runner((address % 0).str()); auto first_query_service = std::make_shared<iroha::protocol::QueryService_v1::Service>(); auto result = first_runner.append(first_query_service).run(); auto port = boost::apply_visitor(port_visitor, result); ASSERT_NE(0, port); ServerRunner second_runner((address % port).str(), false); auto second_query_service = std::make_shared<iroha::protocol::QueryService_v1::Service>(); result = second_runner.append(second_query_service).run(); port = boost::apply_visitor(port_visitor, result); ASSERT_EQ(0, port); } /** * @given a running ServerRunner * @when another ServerRunner tries to run on the same port with port reuse * @then Result with port number is returned */ TEST(ServerRunnerTest, SamePortWithReuse) { ServerRunner first_runner((address % 0).str()); auto first_query_service = std::make_shared<iroha::protocol::QueryService_v1::Service>(); auto result = first_runner.append(first_query_service).run(); auto port = boost::apply_visitor(port_visitor, result); ASSERT_NE(0, port); ServerRunner second_runner((address % port).str(), true); auto second_query_service = std::make_shared<iroha::protocol::QueryService_v1::Service>(); result = second_runner.append(second_query_service).run(); port = boost::apply_visitor(port_visitor, result); ASSERT_NE(0, port); }
37.214286
78
0.727063
coderintherye
eb445c2d12a3a6ef046a8123286c6f628b50caa7
2,402
cpp
C++
src/atlas/hlr/load_library.cpp
marovira/atlas
ccc9ec2449a9392e41a25a6c638302b940f5e5da
[ "MIT" ]
10
2016-11-30T08:44:55.000Z
2022-02-05T16:47:05.000Z
src/atlas/hlr/load_library.cpp
marovira/atlas
ccc9ec2449a9392e41a25a6c638302b940f5e5da
[ "MIT" ]
12
2016-01-13T20:31:11.000Z
2020-03-27T19:14:03.000Z
src/atlas/hlr/load_library.cpp
marovira/atlas
ccc9ec2449a9392e41a25a6c638302b940f5e5da
[ "MIT" ]
10
2016-01-07T16:22:36.000Z
2020-01-16T05:58:48.000Z
#include "load_library.hpp" #include <fmt/printf.h> #include <zeus/platform.hpp> #if defined(ZEUS_PLATFORM_WINDOWS) # define WIN32_LEAN_AND_MEAN # include <windows.h> #else # include <dlfcn.h> #endif namespace atlas::hlr { #if defined(ZEUS_PLATFORM_WINDOWS) void* load_library_handle(std::string const& library_name) { void* handle = LoadLibrary(library_name.c_str()); if (handle == nullptr) { auto error_code = GetLastError(); fmt::print(stderr, "error: LoadLibrary returned error code {}\n", error_code); } return handle; } void* load_raw_function_ptr(void* handle, std::string const& function_name) { if (handle == nullptr) { fmt::print(stderr, "error: null library handle\n"); return nullptr; } auto hmodule = reinterpret_cast<HMODULE>(handle); FARPROC prog_address = GetProcAddress(hmodule, function_name.c_str()); if (prog_address == nullptr) { auto error_code = GetLastError(); fmt::print(stderr, "error: GetProcAddress returned error code {}\n", error_code); } return prog_address; } void unload_library_handle(void* handle) { auto h = reinterpret_cast<HMODULE>(handle); FreeLibrary(h); } #else void* load_library_handle(std::string const& library_name) { void* handle = dlopen(library_name.c_str(), RTLD_LAZY); if (handle == nullptr) { auto error_message = dlerror(); fmt::print(stderr, "error: in dlopen: {}\n", error_message); } return handle; } void* load_raw_function_ptr(void* handle, std::string const& function_name) { if (handle == nullptr) { fmt::print(stderr, "error: null library handle\n"); return nullptr; } void* prog_address = dlsym(handle, function_name.c_str()); if (prog_address == nullptr) { auto error_message = dlerror(); fmt::print(stderr, "error: in dlsym: {}\n", error_message); } return prog_address; } void unload_library_handle(void* handle) { dlclose(handle); } #endif } // namespace atlas::hlr
25.827957
79
0.567027
marovira
eb53ef71a732559eb4276b24987d810708931040
30
cpp
C++
Refureku/Library/Tests/AB.cpp
jsoysouvanh/Refureku
7548cb3b196793119737a51c1cedc136aa60d3ee
[ "MIT" ]
143
2020-04-07T21:38:21.000Z
2022-03-30T01:06:33.000Z
Refureku/Library/Tests/AB.cpp
jsoysouvanh/Refureku
7548cb3b196793119737a51c1cedc136aa60d3ee
[ "MIT" ]
7
2021-03-30T07:26:21.000Z
2022-03-28T16:31:02.000Z
Refureku/Library/Tests/AB.cpp
jsoysouvanh/Refureku
7548cb3b196793119737a51c1cedc136aa60d3ee
[ "MIT" ]
11
2020-06-06T09:45:12.000Z
2022-01-25T17:17:55.000Z
#include "Generated/AB.rfks.h"
30
30
0.766667
jsoysouvanh
eb55db2d10860204a0d7d4edebae5c61db156dd7
3,252
hpp
C++
distribution_survival/boost/statistics/detail/distribution/survival/models/common/importance_sampling/proposals_manager.hpp
rogard/boost_sandbox_statistics
16aacbc716a31a9f7bb6c535b1c90dc343282a23
[ "BSL-1.0" ]
null
null
null
distribution_survival/boost/statistics/detail/distribution/survival/models/common/importance_sampling/proposals_manager.hpp
rogard/boost_sandbox_statistics
16aacbc716a31a9f7bb6c535b1c90dc343282a23
[ "BSL-1.0" ]
null
null
null
distribution_survival/boost/statistics/detail/distribution/survival/models/common/importance_sampling/proposals_manager.hpp
rogard/boost_sandbox_statistics
16aacbc716a31a9f7bb6c535b1c90dc343282a23
[ "BSL-1.0" ]
null
null
null
///////////////////////////////////////////////////////////////////////////////////////// // distribution::survival::models::common::importance_sampling::proposals_manager.hpp // // // // Copyright 2009 Erwann Rogard. 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 BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_IMPORTANCE_SAMPLING_PROPOSALS_MANAGER_HPP_ER_2009 #define BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_IMPORTANCE_SAMPLING_PROPOSALS_MANAGER_HPP_ER_2009 #include <boost/typeof/typeof.hpp> #include <boost/fusion/include/make_map.hpp> #include <boost/fusion/include/pair.hpp> #include <boost/statistics/detail/traits/remove_cvref.hpp> #include <boost/statistics/detail/distribution_common/meta/value.hpp> #include <boost/statistics/detail/distribution_common/meta/random/distribution.hpp> #include <boost/statistics/detail/distribution_common/meta/random/generator.hpp> namespace boost { namespace statistics{ namespace detail{ namespace distribution{ namespace survival { namespace importance_sampling{ template<typename D> class proposals_manager{ typedef typename distribution::meta::value<D>::type val_; typedef distribution::meta::random_distribution<D> meta_random_; typedef typename meta_random_::type random_; typedef typename random_::result_type par_value1_; typedef typename statistics::detail::traits::remove_cvref< par_value1_ >::type par_value_; public: proposals_manager(const D& dist):dist_(dist){} proposals_manager(const proposals_manager& that):dist_(that.dist_){} // Tags struct tag{ struct parameter{}; struct log_pdf{}; }; typedef typename tag::parameter tag_par_; typedef typename tag::log_pdf tag_lpdf_; typedef typename boost::fusion::map< boost::fusion::pair<tag_par_,par_value_>, boost::fusion::pair<tag_lpdf_,val_> > proposal_; typedef std::vector<proposal_> proposals_type; // Generate posterior sample const D& distribution()const{ return this->dist_; } template<typename U,typename N> void refresh(U& urng,N n){ BOOST_AUTO( gen, distribution::make_random_generator(urng,this->dist_) ); this->proposals_.clear(); this->proposals_.reserve(n); for(unsigned i = 0; i<n; i++) { par_value_ p = gen(); val_ lpdf = log_unnormalized_pdf(this->dist_,p); this->proposals_.push_back( boost::fusion::make_map<tag_par_,tag_lpdf_>(p,lpdf) ); } } const proposals_type& operator()()const{ return this->proposals_; } private: proposals_type proposals_; D dist_; }; }// importance_sampling }// survival }// distribution }// detail }// statistics }// boost #endif
35.347826
110
0.621464
rogard
eb55e082fd5281ba7b6dd6b8807f138828dd1685
8,236
cpp
C++
main.cpp
MinghuaShen/HLS
f53220ef475f15c2d11902d6f392b9cb783fd5b0
[ "MIT" ]
4
2020-03-14T05:11:57.000Z
2021-03-23T15:02:37.000Z
main.cpp
MinghuaShen/HLS
f53220ef475f15c2d11902d6f392b9cb783fd5b0
[ "MIT" ]
null
null
null
main.cpp
MinghuaShen/HLS
f53220ef475f15c2d11902d6f392b9cb783fd5b0
[ "MIT" ]
2
2018-07-26T15:52:39.000Z
2021-02-21T10:42:47.000Z
// Copyright (c) 2018 Hongzheng Chen // E-mail: chenhzh37@mail2.sysu.edu.cn // This is the implementation of Entropy-directed scheduling (EDS) algorithm for FPGA high-level synthesis. // This file is the main function of EDS. #include <iostream> #include <fstream> #include <string> #include <cstdlib> #include <chrono> // timing using Clock = std::chrono::high_resolution_clock; #include "graph.h" #include "graph.hpp" using namespace std; // Benchmarks for our experiments can be downloaded at // https://www.ece.ucsb.edu/EXPRESS/benchmark/ const vector<string> dot_file = { "", "hal", "horner_bezier_surf_dfg__12"/*c*/, "arf", "motion_vectors_dfg__7"/*c*/, "ewf", "fir2", "fir1", "h2v2_smooth_downsample_dfg__6", "feedback_points_dfg__7"/*c*/, "collapse_pyr_dfg__113"/*c*/, "cosine1", "cosine2", "write_bmp_header_dfg__7"/*c*/, "interpolate_aux_dfg__12"/*c*/, "matmul_dfg__3"/*c*/, "idctcol_dfg__3"/*c*/, "jpeg_idct_ifast_dfg__5"/*c*/, "jpeg_fdct_islow_dfg__6"/*c*/, "smooth_color_z_triangle_dfg__31"/*c*/, "invert_matrix_general_dfg__3"/*c*/, "dag_500", "dag_1000", "dag_1500" }; // if you need to load from other path, please modify here string path = "./Benchmarks/"; // default constraints for resource-constrained scheduling // these fine-tuned constraints are first presented in the paper below // ----------------------------------------------------------------- // @Article{ // Author = {G. Wang and W. Gong and B. DeRenzi and R. Kastner}, // title = {Ant Colony Optimizations for Resource- and Timing-Constrained Operation Scheduling}, // journal = {IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems (TCAD)}, // year = {2007} // } // ----------------------------------------------------------------- // const vector<map<string,int>> RC = { // {{"MUL",0 }, {"ALU",0 }},/*null*/ // {{"MUL",2 }, {"ALU",1 }},/*1*/ // {{"MUL",2 }, {"ALU",1 }},/*2*/ // {{"MUL",3 }, {"ALU",1 }},/*3*/ // {{"MUL",3 }, {"ALU",4 }},/*4*/ // {{"MUL",1 }, {"ALU",2 }},/*5*/ // {{"MUL",2 }, {"ALU",3 }},/*6*/ // {{"MUL",2 }, {"ALU",3 }},/*7*/ // {{"MUL",1 }, {"ALU",3 }},/*8*/ // {{"MUL",3 }, {"ALU",3 }},/*9*/ // {{"MUL",3 }, {"ALU",5 }},/*10*/ // {{"MUL",4 }, {"ALU",5 }},/*11*/ // {{"MUL",5 }, {"ALU",8 }},/*12*/ // {{"MUL",1 }, {"ALU",9 }},/*13*/ // {{"MUL",9 }, {"ALU",8 }},/*14*/ // {{"MUL",9 }, {"ALU",8 }},/*15*/ // {{"MUL",5 }, {"ALU",6 }},/*16*/ // {{"MUL",10}, {"ALU",9 }},/*17*/ // {{"MUL",5 }, {"ALU",7 }},/*18*/ // {{"MUL",8 }, {"ALU",9 }},/*19*/ // {{"MUL",15}, {"ALU",11}},/*20*/ // {{"MUL",5 }, {"ALU",9 }},/*21*/ // {{"MUL",6 }, {"ALU",12}},/*22*/ // {{"MUL",7 }, {"ALU",13}},/*23*/ // }; // Complex FU library const vector<map<string,int>> RC = { {{"MUL",0 }, {"ALU",0 }},/*null*/ {{"MUL",2 }, {"add",1 },{"sub",1},{"les",1}},/*1*/ {{"MUL",1 }, {"ADD",1 },{"LOD",1},{"STR",1}},/*2*/ {{"MUL",3 }, {"ADD",1 }},/*3*/ {{"MUL",3 }, {"LOD",1 },{"ADD",2},{"STR",1}},/*4*/ {{"MUL",1 }, {"ADD",2 }},/*5*/ {{"MUL",2 }, {"add",1 },{"exp",1},{"imp",2}},/*6*/ {{"MUL",2 }, {"ADD",2 },{"MemR",2},{"MemW",1}},/*7*/ {{"MUL",1 }, {"ADD",2 },{"ASR",1},{"STR",1},{"LOD",1}},/*8*/ {{"MUL",3 }, {"STR",2 },{"LOD",1},{"BGE",1},{"ADD",2}},/*9*/ {{"MUL",3 }, {"ADD",3 },{"SUB",1},{"STR",3},{"LSL",1},{"LOD",3},{"ASR",1}},/*10*/ {{"MUL",4 }, {"imp",6 },{"sub",1},{"exp",2},{"add",2}},/*11*/ {{"MUL",4 }, {"add",1 },{"exp",2},{"imp",2},{"sub",2}},/*12*/ {{"MUL",1 }, {"STR",3 },{"LSR",1},{"LOD",4},{"BNE",1},{"ASR",2},{"AND",2},{"ADD",4}},/*13*/ {{"MUL",9 }, {"ADD",4 },{"SUB",2},{"STR",2},{"LOD",5}},/*14*/ {{"MUL",8 }, {"STR",2 },{"LOD",3},{"ADD",3}},/*15*/ {{"MUL",4 }, {"SUB",2 },{"STR",2},{"LSL",1},{"LOD",2},{"ASR",2},{"ADD",2}},/*16*/ {{"MUL",4 }, {"SUB",1 },{"STR",2},{"LOD",4},{"ASR",1},{"ADD",4}},/*17*/ {{"MUL",4 }, {"SUB",2 },{"STR",2},{"LOD",4},{"ASR",1},{"ADD",4}},/*18*/ {{"MUL",8 }, {"SUB",3 },{"ADD",6},{"LOD",6}},/*19*/ {{"MUL",14}, {"SUB",3 },{"STR",3},{"NEG",2},{"LOD",8},{"ADD",8}},/*20*/ {{"MUL",5 }, {"add",9 }},/*21*/ {{"MUL",6 }, {"add",12}},/*22*/ {{"MUL",7 }, {"add",13}},/*23*/ }; void interactive() { while (1) { cout << "\nPlease enter the file num." << endl; for (int file_num = 1; file_num < dot_file.size(); ++file_num) cout << file_num << ": " << dot_file[file_num] << endl; int file_num; cin >> file_num; cout << "Begin reading dot file..." << endl; ifstream infile(path + dot_file[file_num] + ".dot"); if (infile) cout << "Read in dot file successfully!\n" << endl; else { cout << "Error: No such files!" << endl; return; } graph gp; vector<int> MODE; cout << "\nPlease enter the scheduling mode:" << endl; cout << "Time-constrained(TC):\t0 EDS\t1 IEDS\t2 ILP\t3 FDS\t4 LS" << endl; cout << "Resource-constrained(RC):\t10 EDS\t11 IEDS\t12 ILP\t13 FDS\t 14 LS" << endl; int mode; cin >> mode; MODE.push_back(mode); if (MODE[0] < 10) { double lc; cout << "Please enter the latency factor." << endl; cin >> lc; gp.setLC(lc); } else gp.setMAXRESOURCE(RC.at(file_num)); cout << "\nPlease enter the scheduling order:" << endl; cout << "0. Top-down\t 1.Bottom-up" << endl; cin >> mode; MODE.push_back(mode); gp.setMODE(MODE); gp.readFile(infile); if (MODE[0] == 2) { try{ system("md TC_ILP"); } catch(...){} char str[10]; snprintf(str,sizeof(str),"%.1f",gp.getLC()); ofstream outfile("./TC_ILP/"+dot_file[file_num]+"_"+string(str)+".lp"); gp.generateTC_ILP(outfile); outfile.close(); } else if (MODE[0] == 12) { try{ system("md RC_ILP"); } catch(...){} ofstream outfile("./RC_ILP/"+dot_file[file_num]+".lp"); gp.generateRC_ILP(outfile); outfile.close(); } else gp.mainScheduling(); infile.close(); } } // set these argv from cmd // argv[0] default file path: needn't give // argv[1] scheduling mode: // time-constrained(TC): 0 EDS 1 IEDS 2 ILP 3 FDS 4 LS // resource-constrained(RC): 10 EDS 11 IEDS 12 ILP 13 FDS 14 LS // ****** If the arguments below are not needed, you needn't type anything more. ****** // argv[2] latency factor (LC) or scheduling order // 0 top-down 1 bottom-up void commandline(char *argv[]) { vector<int> MODE; MODE.push_back(stoi(string(argv[1]))); // scheduling mode switch (MODE[0]) { case 0: case 1: case 3: case 4: MODE.push_back(stoi(string(argv[3])));break; case 10: case 11: case 13: case 14: MODE.push_back(stoi(string(argv[2])));break; case 2: MODE.push_back(stoi(string(argv[2])));break; case 12: MODE.push_back(stoi(string(argv[1])));break; default: cout << "Error: Mode wrong!" << endl;break; } for (int file_num = 1; file_num < dot_file.size(); ++file_num) { ifstream infile(path + dot_file[file_num] + ".dot"); if (!infile) { cout << "Error: No such files!" << endl; return; } graph gp; gp.setMODE(MODE); gp.setPRINT(0); gp.readFile(infile); if (MODE[0] >= 10) gp.setMAXRESOURCE(RC.at(file_num)); else gp.setLC(stod(string(argv[2]))); if (MODE[0] == 2) { try{ system("md TC_ILP"); } catch(...){} char str[10]; snprintf(str,sizeof(str),"%.1f",gp.getLC()); ofstream outfile("./TC_ILP/"+dot_file[file_num]+"_"+string(str)+".lp"); gp.generateTC_ILP(outfile); outfile.close(); } else if (MODE[0] == 12) { try{ system("md RC_ILP"); } catch(...){} ofstream outfile("./RC_ILP/"+dot_file[file_num]+".lp"); gp.generateRC_ILP(outfile); outfile.close(); } else { cout << "File # " << file_num << " (" << dot_file[file_num] << ") :" <<endl; gp.mainScheduling(1); } infile.close(); } } int main(int argc,char *argv[]) { if (argc == 1) // interactive interactive(); else // read from cmd commandline(argv); return 0; } // Some abbreviations appear in ExPRESS // 1.MUL // mul: multipy // div: divide // 2.ALU // imp: import // exp: export // MemR: memory read // MemW: memory write // str: store register // les: less // lod: load data into memory? // bge: ? // neg: negetive // add: add // sub: subtract // and: logical and // lsr: logical shift right // asr: arithmetic shift right // bne: Branch if Not Equal
28.013605
107
0.535697
MinghuaShen
eb56133760a6445cd88612e1a1f6e2143fa054ad
2,073
cc
C++
rdc_libs/bootstrap/src/RdcLibraryLoader.cc
RadeonOpenCompute/rdc
bb11a0abf5bea0ca8ad3d17bd687379c45149ed9
[ "MIT" ]
2
2020-09-10T02:04:00.000Z
2020-12-03T10:55:38.000Z
rdc_libs/bootstrap/src/RdcLibraryLoader.cc
RadeonOpenCompute/rdc
bb11a0abf5bea0ca8ad3d17bd687379c45149ed9
[ "MIT" ]
2
2022-03-29T00:32:43.000Z
2022-03-31T18:09:36.000Z
rdc_libs/bootstrap/src/RdcLibraryLoader.cc
RadeonOpenCompute/rdc
bb11a0abf5bea0ca8ad3d17bd687379c45149ed9
[ "MIT" ]
2
2020-09-15T08:05:43.000Z
2021-09-02T03:06:41.000Z
/* Copyright (c) 2020 - present Advanced Micro Devices, Inc. All rights reserved. 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 "rdc_lib/RdcLibraryLoader.h" namespace amd { namespace rdc { RdcLibraryLoader::RdcLibraryLoader(): libHandler_(nullptr) { } rdc_status_t RdcLibraryLoader::load(const char* filename) { if (filename == nullptr) { return RDC_ST_FAIL_LOAD_MODULE; } if (libHandler_) { unload(); } std::lock_guard<std::mutex> guard(library_mutex_); libHandler_ = dlopen(filename, RTLD_LAZY); if (!libHandler_) { char* error = dlerror(); RDC_LOG(RDC_ERROR, "Fail to open " << filename <<": " << error); return RDC_ST_FAIL_LOAD_MODULE; } return RDC_ST_OK; } rdc_status_t RdcLibraryLoader::unload() { std::lock_guard<std::mutex> guard(library_mutex_); if (libHandler_) { dlclose(libHandler_); libHandler_ = nullptr; } return RDC_ST_OK; } RdcLibraryLoader::~RdcLibraryLoader() { unload(); } } // namespace rdc } // namespace amd
31.892308
78
0.71973
RadeonOpenCompute
eb5aea67a93b7475845e8cbfad9baac236ded1f1
1,562
cpp
C++
codeforces/gym/2018 ICPC Asia Jakarta Regional Contest/g.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
4
2020-10-05T19:24:10.000Z
2021-07-15T00:45:43.000Z
codeforces/gym/2018 ICPC Asia Jakarta Regional Contest/g.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
codeforces/gym/2018 ICPC Asia Jakarta Regional Contest/g.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
#include <cpplib/stdinc.hpp> bool check(int n, int m, vector<list<int> > iadj, vvb mat, vi dg, int k){ queue<ii> q; set<int> inq; for(int u=0; u<n; ++u){ for(int v=0; v<n; ++v){ } } while(!q.empty()){ int u = q.front(); q.pop(); inq.erase(u); for(auto it=iadj[u].begin(); it != iadj[u].end();){ int v = *it; if(dg[u] + dg[v] < k){ it++; continue; } m++; dg[u]++; dg[v]++; if(!inq.count(u)){ inq.ep(u); q.ep(u); } if(!inq.count(v)){ inq.ep(v); q.ep(v); } it = iadj[u].erase(it); } } return m == n*(n-1)/2; } int32_t main(){ desync(); int n, m; cin >> n >> m; vi dg(n); vvb mat(n, vb(n)); for(int i=0; i<m; ++i){ int u, v; cin >> u >> v; u--; v--; dg[u]++; dg[v]++; mat[u][v] = mat[v][u] = true; } vector<list<int> > iadj(n); for(int u=0; u<n; ++u){ for(int v=u+1; v<n; ++v){ if(mat[u][v]) continue; iadj[u].eb(v); } } int lo = 0, hi = 2*n, ans = hi; while(lo <= hi){ int mid = (lo+hi)/2; if(check(n, m, iadj, mat, dg, mid)){ ans = mid; lo = mid+1; } else hi = mid-1; } cout << ans << endl; return 0; }
19.525
73
0.330346
tysm
eb5d1fc687dd9ef164a10ff6717e6a05624e6fbb
115
cpp
C++
src/main/cpp/MathHelper.cpp
frcteam4458/2022-Command
131634be15ab6da2eed68c5b41dd87b3ee2ffe0a
[ "BSD-3-Clause" ]
1
2022-03-17T02:46:36.000Z
2022-03-17T02:46:36.000Z
src/main/cpp/MathHelper.cpp
frcteam4458/2022-Command
131634be15ab6da2eed68c5b41dd87b3ee2ffe0a
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/MathHelper.cpp
frcteam4458/2022-Command
131634be15ab6da2eed68c5b41dd87b3ee2ffe0a
[ "BSD-3-Clause" ]
null
null
null
#include <math.h> #include "MathHelper.h" double pythagorean(float a, float b) { return sqrt(a * a + b * b); }
16.428571
36
0.634783
frcteam4458
eb64843a7a0245f6a31e67e1ec16bfee4c59d291
3,287
cpp
C++
firmware/examples/FreeRTOS_Blinker/source/main.cpp
2721Aperez/SJSU-Dev2
87052080d2754803dbd1dae2864bd9024d123086
[ "Apache-2.0" ]
1
2018-07-07T01:41:34.000Z
2018-07-07T01:41:34.000Z
firmware/examples/FreeRTOS_Blinker/source/main.cpp
2721Aperez/SJSU-Dev2
87052080d2754803dbd1dae2864bd9024d123086
[ "Apache-2.0" ]
null
null
null
firmware/examples/FreeRTOS_Blinker/source/main.cpp
2721Aperez/SJSU-Dev2
87052080d2754803dbd1dae2864bd9024d123086
[ "Apache-2.0" ]
1
2018-09-19T01:58:48.000Z
2018-09-19T01:58:48.000Z
#include <cstdint> #include <cstdio> #include "FreeRTOS.h" #include "task.h" #include "config.hpp" #include "L0_LowLevel/LPC40xx.h" #include "L2_Utilities/debug_print.hpp" #include "L2_Utilities/macros.hpp" #include "L2_Utilities/rtos.hpp" namespace { void LedToggle(void * parameters) { DEBUG_PRINT("Setting up task..."); DEBUG_PRINT("Retrieving delay amount from parameters..."); auto delay = rtos::RetrieveParameter(parameters); DEBUG_PRINT("Initializing LEDs..."); LPC_IOCON->P1_1 &= ~(0b111); LPC_IOCON->P1_8 &= ~(0b111); LPC_GPIO1->DIR |= (1 << 1); LPC_GPIO1->PIN &= ~(1 << 1); LPC_GPIO1->DIR |= (1 << 8); LPC_GPIO1->PIN |= (1 << 8); DEBUG_PRINT("LEDs Initialized..."); DEBUG_PRINT("Toggling LEDs..."); // Loop blinks the LEDs back and forth at a rate that depends on the // pvParameter's value. while (true) { LPC_GPIO1->PIN ^= 0b0001'0000'0010; vTaskDelay(delay); } } constexpr uint32_t kButtonPinNumber = 14; constexpr uint32_t kLedNumber = 15; bool CheckSwitch3() { return (LPC_GPIO1->PIN & (1 << kButtonPinNumber)); } void ButtonReader(void * parameters) { SJ2_USED(parameters); DEBUG_PRINT("Setting up task..."); DEBUG_PRINT("Initializing LED3 and SW3..."); LPC_IOCON->P1_14 &= ~(0b111); LPC_IOCON->P1_15 &= ~(0b111); LPC_GPIO1->DIR &= ~(1 << kButtonPinNumber); LPC_GPIO1->DIR |= (1 << kLedNumber); LPC_GPIO1->PIN |= (1 << kLedNumber); DEBUG_PRINT("LED3 and SW3 Initialized..."); DEBUG_PRINT("Press and release SW3 to toggle LED3 state..."); bool button_pressed = false; // Loop detects when the button has been released and changes the LED state // accordingly. while (true) { if (CheckSwitch3()) { button_pressed = true; } else if (!CheckSwitch3() && button_pressed) { LPC_GPIO1->PIN ^= (1 << kLedNumber); button_pressed = false; } else { button_pressed = false; } vTaskDelay(50); } } } // namespace int main(void) { TaskHandle_t handle = NULL; DEBUG_PRINT("Creating Tasks ..."); // See https://www.freertos.org/a00125.html for the xTaskCreate API // See L2_Utilities/rtos.hpp for the rtos:: namespace utility functions xTaskCreate( LedToggle, // Make function LedToggle a task "LedToggle", // Give this task the name "LedToggle" rtos::StackSize(256), // Size of stack allocated to task rtos::PassParameter(100), // Parameter to be passed to task rtos::Priority::kLow, // Give this task low priority &handle); // Reference to the task xTaskCreate( ButtonReader, // Make function ButtonReader a task "ButtonReader", // Give this task the name "ButtonReader" rtos::StackSize(256), // Size of stack allocated to task rtos::kNoParameter, // Pass nothing to this task rtos::Priority::kMedium, // Give this task medium priority rtos::kNoHandle); // Do not supply a task handle DEBUG_PRINT("Starting Scheduler ..."); vTaskStartScheduler(); return 0; }
30.719626
79
0.604807
2721Aperez
eb69835c7702dde170dbc1a2588237ffc0688b75
10,953
cc
C++
core/src/CommonClient.cc
zzboy/aliyun-kms-cpp-sdk
95ff35e92212e9bc1331fc6760606aa08c93cb94
[ "Apache-2.0" ]
null
null
null
core/src/CommonClient.cc
zzboy/aliyun-kms-cpp-sdk
95ff35e92212e9bc1331fc6760606aa08c93cb94
[ "Apache-2.0" ]
null
null
null
core/src/CommonClient.cc
zzboy/aliyun-kms-cpp-sdk
95ff35e92212e9bc1331fc6760606aa08c93cb94
[ "Apache-2.0" ]
1
2019-10-14T10:37:47.000Z
2019-10-14T10:37:47.000Z
/* * Copyright 1999-2019 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/core/AlibabaCloud.h> #include <alibabacloud/core/CommonClient.h> #include <alibabacloud/core/location/LocationClient.h> #include <alibabacloud/core/SimpleCredentialsProvider.h> #include <ctime> #include <algorithm> #include <iomanip> #include <sstream> #include <alibabacloud/core/Utils.h> namespace AlibabaCloud { namespace { const std::string SERVICE_NAME = "Common"; } CommonClient::CommonClient(const Credentials &credentials, const ClientConfiguration &configuration) : CoreClient(SERVICE_NAME, configuration), credentialsProvider_( std::make_shared<SimpleCredentialsProvider>(credentials)), signer_(std::make_shared<HmacSha1Signer>()) { } CommonClient::CommonClient( const std::shared_ptr<CredentialsProvider> &credentialsProvider, const ClientConfiguration &configuration) : CoreClient(SERVICE_NAME, configuration), credentialsProvider_(credentialsProvider), signer_(std::make_shared<HmacSha1Signer>()) { } CommonClient::CommonClient(const std::string &accessKeyId, const std::string &accessKeySecret, const ClientConfiguration &configuration) : CoreClient(SERVICE_NAME, configuration), credentialsProvider_(std::make_shared<SimpleCredentialsProvider>(accessKeyId, accessKeySecret)), signer_(std::make_shared<HmacSha1Signer>()) { } CommonClient::~CommonClient() { } CommonClient::JsonOutcome CommonClient::makeRequest(const std::string &endpoint, const CommonRequest &msg, HttpRequest::Method method) const { auto outcome = AttemptRequest(endpoint, msg, method); if (outcome.isSuccess()) return JsonOutcome(std::string(outcome.result().body(), outcome.result().bodySize())); else return JsonOutcome(outcome.error()); } CommonClient::CommonResponseOutcome CommonClient::commonResponse( const CommonRequest &request) const { auto outcome = makeRequest(request.domain(), request, request.httpMethod()); if (outcome.isSuccess()) return CommonResponseOutcome(CommonResponse(outcome.result())); else return CommonResponseOutcome(Error(outcome.error())); } void CommonClient::commonResponseAsync(const CommonRequest &request, const CommonResponseAsyncHandler &handler, const std::shared_ptr<const AsyncCallerContext> &context) const { auto fn = [this, request, handler, context]() { handler(this, request, commonResponse(request), context); }; asyncExecute(new Runnable(fn)); } CommonClient::CommonResponseOutcomeCallable CommonClient::commonResponseCallable(const CommonRequest &request) const { auto task = std::make_shared<std::packaged_task<CommonResponseOutcome()>>( [this, request]() { return this->commonResponse(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } HttpRequest CommonClient::buildHttpRequest(const std::string &endpoint, const ServiceRequest &msg, HttpRequest::Method method) const { return buildHttpRequest(endpoint, dynamic_cast<const CommonRequest &>(msg), method); } HttpRequest CommonClient::buildHttpRequest(const std::string &endpoint, const CommonRequest &msg, HttpRequest::Method method) const { if (msg.requestPattern() == CommonRequest::RpcPattern) return buildRpcHttpRequest(endpoint, msg, method); else return buildRoaHttpRequest(endpoint, msg, method); } HttpRequest CommonClient::buildRoaHttpRequest(const std::string &endpoint, const CommonRequest &msg, HttpRequest::Method method) const { const Credentials credentials = credentialsProvider_->getCredentials(); Url url; if (msg.scheme().empty()) { url.setScheme("https"); } else { url.setScheme(msg.scheme()); } url.setHost(endpoint); url.setPath(msg.resourcePath()); auto params = msg.headerParameters(); std::map<std::string, std::string> queryParams; for (const auto &p : params) { if (!p.second.empty()) queryParams[p.first] = p.second; } if (!queryParams.empty()) { std::stringstream queryString; for (const auto &p : queryParams) { if (p.second.empty()) queryString << "&" << p.first; else queryString << "&" << p.first << "=" << p.second; } url.setQuery(queryString.str().substr(1)); } HttpRequest request(url); request.setMethod(method); if (msg.connectTimeout() != kInvalidTimeout) { request.setConnectTimeout(msg.connectTimeout()); } else { request.setConnectTimeout(configuration().connectTimeout()); } if (msg.readTimeout() != kInvalidTimeout) { request.setReadTimeout(msg.readTimeout()); } else { request.setReadTimeout(configuration().readTimeout()); } if (msg.headerParameter("Accept").empty()) { request.setHeader("Accept", "application/json"); } else { request.setHeader("Accept", msg.headerParameter("Accept")); } std::stringstream ss; ss << msg.contentSize(); request.setHeader("Content-Length", ss.str()); if (msg.headerParameter("Content-Type").empty()) { request.setHeader("Content-Type", "application/octet-stream"); } else { request.setHeader("Content-Type", msg.headerParameter("Content-Type")); } request.setHeader("Content-MD5", ComputeContentMD5(msg.content(), msg.contentSize())); request.setBody(msg.content(), msg.contentSize()); std::time_t t = std::time(nullptr); std::stringstream date; #if defined(__GNUG__) && __GNUC__ < 5 char tmbuff[26]; strftime(tmbuff, 26, "%a, %d %b %Y %T", std::gmtime(&t)); date << tmbuff << " GMT"; #else date << std::put_time(std::gmtime(&t), "%a, %d %b %Y %T GMT"); #endif request.setHeader("Date", date.str()); request.setHeader("Host", url.host()); request.setHeader("x-sdk-client", std::string("CPP/").append(ALIBABACLOUD_VERSION_STR)); request.setHeader("x-acs-region-id", configuration().regionId()); if (!credentials.sessionToken().empty()) request.setHeader("x-acs-security-token", credentials.sessionToken()); request.setHeader("x-acs-signature-method", signer_->name()); request.setHeader("x-acs-signature-nonce", GenerateUuid()); request.setHeader("x-acs-signature-version", signer_->version()); request.setHeader("x-acs-version", msg.version()); std::stringstream plaintext; plaintext << HttpMethodToString(method) << "\n" << request.header("Accept") << "\n" << request.header("Content-MD5") << "\n" << request.header("Content-Type") << "\n" << request.header("Date") << "\n" << canonicalizedHeaders(request.headers()); if (!url.hasQuery()) plaintext << url.path(); else plaintext << url.path() << "?" << url.query(); std::stringstream sign; sign << "acs " << credentials.accessKeyId() << ":" << signer_->generate(plaintext.str(), credentials.accessKeySecret()); request.setHeader("Authorization", sign.str()); return request; } HttpRequest CommonClient::buildRpcHttpRequest(const std::string &endpoint, const CommonRequest &msg, HttpRequest::Method method) const { const Credentials credentials = credentialsProvider_->getCredentials(); Url url; if (msg.scheme().empty()) { url.setScheme("https"); } else { url.setScheme(msg.scheme()); } url.setHost(endpoint); url.setPath(msg.resourcePath()); auto params = msg.queryParameters(); std::map<std::string, std::string> queryParams; for (const auto &p : params) { if (!p.second.empty()) queryParams[p.first] = p.second; } queryParams["AccessKeyId"] = credentials.accessKeyId(); queryParams["Format"] = "JSON"; queryParams["RegionId"] = configuration().regionId(); queryParams["SecurityToken"] = credentials.sessionToken(); queryParams["SignatureMethod"] = signer_->name(); queryParams["SignatureNonce"] = GenerateUuid(); queryParams["SignatureVersion"] = signer_->version(); std::time_t t = std::time(nullptr); std::stringstream ss; #if defined(__GNUG__) && __GNUC__ < 5 char tmbuff[26]; strftime(tmbuff, 26, "%FT%TZ", std::gmtime(&t)); ss << tmbuff; #else ss << std::put_time(std::gmtime(&t), "%FT%TZ"); #endif queryParams["Timestamp"] = ss.str(); queryParams["Version"] = msg.version(); std::stringstream plaintext; plaintext << HttpMethodToString(method) << "&" << UrlEncode(url.path()) << "&" << UrlEncode(canonicalizedQuery(queryParams)); queryParams["Signature"] = signer_->generate(plaintext.str(), credentials.accessKeySecret() + "&"); std::stringstream queryString; for (const auto &p : queryParams) queryString << "&" << p.first << "=" << UrlEncode(p.second); url.setQuery(queryString.str().substr(1)); HttpRequest request(url); if (msg.connectTimeout() != kInvalidTimeout) { request.setConnectTimeout(msg.connectTimeout()); } else { request.setConnectTimeout(configuration().connectTimeout()); } if (msg.readTimeout() != kInvalidTimeout) { request.setReadTimeout(msg.readTimeout()); } else { request.setReadTimeout(configuration().readTimeout()); } request.setMethod(method); request.setHeader("Host", url.host()); request.setHeader("x-sdk-client", std::string("CPP/").append(ALIBABACLOUD_VERSION_STR)); return request; } } // namespace AlibabaCloud
32.598214
154
0.626221
zzboy
eb6ab78ef53d83c85753654fdcc9cb12b388a22b
1,844
hpp
C++
source/NanairoCore/Data/ray-inl.hpp
byzin/Nanairo
23fb6deeec73509c538a9c21009e12be63e8d0e4
[ "MIT" ]
30
2015-09-06T03:14:29.000Z
2021-06-18T11:00:19.000Z
source/NanairoCore/Data/ray-inl.hpp
byzin/Nanairo
23fb6deeec73509c538a9c21009e12be63e8d0e4
[ "MIT" ]
31
2016-01-14T14:50:34.000Z
2018-06-25T13:21:48.000Z
source/NanairoCore/Data/ray-inl.hpp
byzin/Nanairo
23fb6deeec73509c538a9c21009e12be63e8d0e4
[ "MIT" ]
6
2017-04-09T13:07:47.000Z
2021-05-29T21:17:34.000Z
/*! \file ray-inl.hpp \author Sho Ikeda Copyright (c) 2015-2018 Sho Ikeda This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ #ifndef NANAIRO_RAY_INL_HPP #define NANAIRO_RAY_INL_HPP #include "ray.hpp" // Standard C++ library #include <array> #include <limits> // Zisc #include "zisc/math.hpp" // Nanairo #include "NanairoCore/nanairo_core_config.hpp" #include "NanairoCore/Geometry/point.hpp" #include "NanairoCore/Geometry/vector.hpp" namespace nanairo { /*! \details No detailed. */ inline Ray::Ray() noexcept : is_alive_{kFalse} { initialize(); } /*! \details No detailed. */ inline Ray::Ray(const Point3& origin, const Vector3& direction) noexcept : origin_{origin}, direction_{direction}, is_alive_{kTrue} { initialize(); } /*! \details No detailed. */ inline const Vector3& Ray::direction() const noexcept { return direction_; } /*! \details No detailed. */ inline bool Ray::isAlive() const noexcept { return is_alive_ == kTrue; } /*! */ inline Ray Ray::makeRay(const Point3& origin, const Vector3& direction) noexcept { Ray ray{origin, direction}; return ray; } /*! \details No detailed. */ inline const Point3& Ray::origin() const noexcept { return origin_; } /*! \details No detailed. */ inline void Ray::setDirection(const Vector3& direction) noexcept { direction_ = direction; } /*! \details No detailed. */ inline void Ray::setOrigin(const Point3& origin) noexcept { origin_ = origin; } /*! \details No detailed. */ inline void Ray::setAlive(const bool is_alive) noexcept { is_alive_ = is_alive ? kTrue : kFalse; } /*! */ inline void Ray::initialize() noexcept { // Avoid warnings static_cast<void>(padding_); } } // namespace nanairo #endif // NANAIRO_RAY_INL_HPP
14.076336
73
0.68167
byzin
eb6bd3304473cf8f613568de2e21de57eb3ddedd
8,122
cpp
C++
src/platform/osx/main_carbon_old.cpp
guitarpukpui/OpenLara
4b73fad5664eadfe8c27f4d32e656f55aeddd177
[ "BSD-2-Clause" ]
3,999
2016-09-07T15:36:25.000Z
2022-03-31T14:54:44.000Z
src/platform/osx/main_carbon_old.cpp
guitarpukpui/OpenLara
4b73fad5664eadfe8c27f4d32e656f55aeddd177
[ "BSD-2-Clause" ]
333
2016-08-23T10:03:40.000Z
2022-03-31T13:25:19.000Z
src/platform/osx/main_carbon_old.cpp
guitarpukpui/OpenLara
4b73fad5664eadfe8c27f4d32e656f55aeddd177
[ "BSD-2-Clause" ]
403
2016-10-31T15:11:02.000Z
2022-03-31T15:03:52.000Z
#include "game.h" bool isQuit = false; WindowRef window; AGLContext context; #define SND_SIZE 8192 static AudioQueueRef audioQueue; void soundFill(void* inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer) { void* frames = inBuffer->mAudioData; UInt32 count = inBuffer->mAudioDataBytesCapacity / 4; Sound::fill((Sound::Frame*)frames, count); inBuffer->mAudioDataByteSize = count * 4; AudioQueueEnqueueBuffer(audioQueue, inBuffer, 0, NULL); // TODO: mutex } void soundInit() { AudioStreamBasicDescription deviceFormat; deviceFormat.mSampleRate = 44100; deviceFormat.mFormatID = kAudioFormatLinearPCM; deviceFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger; deviceFormat.mBytesPerPacket = 4; deviceFormat.mFramesPerPacket = 1; deviceFormat.mBytesPerFrame = 4; deviceFormat.mChannelsPerFrame = 2; deviceFormat.mBitsPerChannel = 16; deviceFormat.mReserved = 0; AudioQueueNewOutput(&deviceFormat, soundFill, NULL, NULL, NULL, 0, &audioQueue); for (int i = 0; i < 2; i++) { AudioQueueBufferRef mBuffer; AudioQueueAllocateBuffer(audioQueue, SND_SIZE, &mBuffer); soundFill(NULL, audioQueue, mBuffer); } AudioQueueStart(audioQueue, NULL); } // common input functions InputKey keyToInputKey(int code) { static const int codes[] = { 0x7B, 0x7C, 0x7E, 0x7D, 0x31, 0x24, 0x35, 0x38, 0x3B, 0x3A, 0x1D, 0x12, 0x13, 0x14, 0x15, 0x17, 0x16, 0x1A, 0x1C, 0x19, // 0..9 0x00, 0x0B, 0x08, 0x02, 0x0E, 0x03, 0x05, 0x04, 0x22, 0x26, 0x28, 0x25, 0x2E, // A..M 0x2D, 0x1F, 0x23, 0x0C, 0x0F, 0x01, 0x11, 0x20, 0x09, 0x0D, 0x07, 0x10, 0x06, // N..Z }; for (int i = 0; i < sizeof(codes) / sizeof(codes[0]); i++) if (codes[i] == code) return (InputKey)(ikLeft + i); return ikNone; } InputKey mouseToInputKey(int btn) { switch (btn) { case 1 : return ikMouseL; case 2 : return ikMouseR; case 3 : return ikMouseM; } return ikNone; } OSStatus eventHandler(EventHandlerCallRef handler, EventRef event, void* userData) { OSType eventClass = GetEventClass(event); UInt32 eventKind = GetEventKind(event); switch (eventClass) { case kEventClassWindow : switch (eventKind) { case kEventWindowClosed : isQuit = true; break; case kEventWindowBoundsChanged : { aglUpdateContext(context); Rect rect; GetWindowPortBounds(window, &rect); Core::width = rect.right - rect.left; Core::height = rect.bottom - rect.top; break; } } break; case kEventClassMouse : { EventMouseButton mouseButton; CGPoint mousePos; Rect wndRect; GetEventParameter(event, kEventParamMouseLocation, typeHIPoint, NULL, sizeof(mousePos), NULL, &mousePos); GetEventParameter(event, kEventParamMouseButton, typeMouseButton, NULL, sizeof(mouseButton), nil, &mouseButton); GetWindowBounds(window, kWindowContentRgn, &wndRect); mousePos.x -= wndRect.left; mousePos.y -= wndRect.top; vec2 pos(mousePos.x, mousePos.y); switch (eventKind) { case kEventMouseDown : case kEventMouseUp : { InputKey key = mouseToInputKey(mouseButton); Input::setPos(key, pos); Input::setDown(key, eventKind == kEventMouseDown); break; } case kEventMouseDragged : Input::setPos(ikMouseL, pos); break; } break; } case kEventClassKeyboard : { switch (eventKind) { case kEventRawKeyDown : case kEventRawKeyUp : { uint32 keyCode; if (GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL, sizeof(keyCode), NULL, &keyCode) == noErr) Input::setDown(keyToInputKey(keyCode), eventKind != kEventRawKeyUp); break; } case kEventRawKeyModifiersChanged : { uint32 modifiers; if (GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(modifiers), NULL, &modifiers) == noErr) { Input::setDown(ikShift, modifiers & shiftKey); Input::setDown(ikCtrl, modifiers & controlKey); Input::setDown(ikAlt, modifiers & optionKey); } break; } } break; } } return CallNextEventHandler(handler, event); } int getTime() { UInt64 t; Microseconds((UnsignedWide*)&t); return int(t / 1000); } char *contentPath; int main() { // init window Rect rect = {0, 0, 720, 1280}; CreateNewWindow(kDocumentWindowClass, kWindowCloseBoxAttribute | kWindowCollapseBoxAttribute | kWindowFullZoomAttribute | kWindowResizableAttribute | kWindowStandardHandlerAttribute, &rect, &window); SetWTitle(window, "\pOpenLara"); // init OpenGL context GLint attribs[] = { AGL_RGBA, AGL_DOUBLEBUFFER, AGL_BUFFER_SIZE, 32, AGL_DEPTH_SIZE, 24, AGL_STENCIL_SIZE, 8, AGL_NONE }; AGLPixelFormat format = aglChoosePixelFormat(NULL, 0, (GLint*)&attribs); context = aglCreateContext(format, NULL); aglDestroyPixelFormat(format); aglSetDrawable(context, GetWindowPort(window)); aglSetCurrentContext(context); // get path to game content CFBundleRef bundle = CFBundleGetMainBundle(); CFURLRef bundleURL = CFBundleCopyBundleURL(bundle); CFStringRef pathStr = CFURLCopyFileSystemPath(bundleURL, kCFURLPOSIXPathStyle); contentPath = new char[1024]; CFStringGetFileSystemRepresentation(pathStr, contentPath, 1024); strcat(contentPath, "/Contents/Resources/"); soundInit(); Game::init(); // show window const int events[][2] = { { kEventClassWindow, kEventWindowClosed }, { kEventClassWindow, kEventWindowBoundsChanged }, { kEventClassKeyboard, kEventRawKeyDown }, { kEventClassKeyboard, kEventRawKeyUp }, { kEventClassKeyboard, kEventRawKeyModifiersChanged }, { kEventClassMouse, kEventMouseDown }, { kEventClassMouse, kEventMouseUp }, { kEventClassMouse, kEventMouseDragged }, }; InstallEventHandler(GetApplicationEventTarget(), (EventHandlerUPP)eventHandler, sizeof(events) / sizeof(events[0]), (EventTypeSpec*)&events, NULL, NULL); SelectWindow(window); ShowWindow(window); int lastTime = getTime(), fpsTime = lastTime + 1000, fps = 0; EventRecord event; while (!isQuit) if (!GetNextEvent(0xffff, &event)) { int time = getTime(); if (time <= lastTime) continue; float delta = (time - lastTime) * 0.001f; while (delta > EPS) { Core::deltaTime = min(delta, 1.0f / 30.0f); Game::update(); delta -= Core::deltaTime; } lastTime = time; Core::stats.dips = 0; Core::stats.tris = 0; Game::render(); aglSwapBuffers(context); if (fpsTime < getTime()) { LOG("FPS: %d DIP: %d TRI: %d\n", fps, Core::stats.dips, Core::stats.tris); fps = 0; fpsTime = getTime() + 1000; } else fps++; } Game::free(); delete[] contentPath; // TODO: sndFree aglSetCurrentContext(NULL); ReleaseWindow(window); return 0; }
34.270042
203
0.575967
guitarpukpui
eb71541b97afe7d8bded1d4c273baa49503822ee
22,796
cpp
C++
mllib/LogisticRegression.cpp
Christina-hshi/Boosting-with-Husky
1744f0c90567a969d3e50d19f27f358f5865d2f6
[ "Apache-2.0" ]
1
2019-01-23T02:10:10.000Z
2019-01-23T02:10:10.000Z
mllib/LogisticRegression.cpp
Christina-hshi/Boosting-with-Husky
1744f0c90567a969d3e50d19f27f358f5865d2f6
[ "Apache-2.0" ]
null
null
null
mllib/LogisticRegression.cpp
Christina-hshi/Boosting-with-Husky
1744f0c90567a969d3e50d19f27f358f5865d2f6
[ "Apache-2.0" ]
null
null
null
/* Edit by Christina */ #include "LogisticRegression.hpp" namespace husky{ namespace mllib{ /* train a logistic regression model with even weighted instances. */ void LogisticRegression::fit(const Instances& instances){ if(this->mode == MODE::GLOBAL){ global_fit(instances); } else if(this->mode == MODE::LOCAL){ local_fit(instances); } else{ throw std::invalid_argument("MODE " + std::to_string((int)mode) + " dosen't exit! Only 0(GLOBAL) and 1(LOCAL) mode are provided."); } } /* train a logistic regression model using instance weight, which is specified as a attribute list of original_instances, name of which is 'instance_weight_name'. */ void LogisticRegression::fit(const Instances& instances, std::string instance_weight_name){ if(this->mode == MODE::GLOBAL){ global_fit(instances, instance_weight_name); } else if(this->mode == MODE::LOCAL){ local_fit(instances, instance_weight_name); } else{ throw std::invalid_argument("MODE " + std::to_string((int)mode) + " dosen't exit! Only 0(GLOBAL) and 1(LOCAL) mode are provided."); } } /* train model in global mode. */ void LogisticRegression::global_fit(const Instances& instances){ const int num_attri = instances.numAttributes; matrix_double init_mat; for(int i = 1; i < this->class_num; i++){ init_mat.push_back(vec_double(num_attri + 1, 0.0)); } husky::lib::Aggregator<matrix_double> para_mat(init_mat, [](matrix_double& a, const matrix_double& b){ a += b;}, [num_attri, this](matrix_double& m){ m.clear(); for(int i = 1; i < this->class_num; i++){ m.push_back(vec_double(num_attri + 1, 0.0)); } }); husky::lib::Aggregator<double> global_squared_error(0.0, [](double& a, const double& b){ a += b;}, [](double& v){ v = 0; } ); global_squared_error.to_reset_each_iter(); auto& ac = husky::lib::AggregatorFactory::get_channel(); double old_weighted_squared_error = std::numeric_limits<double>::max(); double eta = eta0; int eta_update_counter = 1; int trival_improve_iter = 0; //max_iter for(int iter = 1; iter <= max_iter && trival_improve_iter < max_trival_improve_iter; iter++){ if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("Iter#" + std::to_string(iter) + "\teta: " + std::to_string(eta)); } matrix_double para_update; for(int i = 1; i < this->class_num; i++){ para_update.push_back(vec_double(num_attri + 1, 0.0)); } matrix_double para_old = para_mat.get_value(); vec_double class_prob_tmp(this->class_num, 0.0); list_execute(instances.enumerator(), {}, {&ac}, [&](Instance& instance){ vec_double x_with_const_term = instance.X; x_with_const_term.push_back(1); //calculate probability double sum_tmp = 0; for(int x = 0; x < class_num - 1; x++){ class_prob_tmp[x] = exp(para_old[x] * x_with_const_term); sum_tmp += class_prob_tmp[x]; } sum_tmp += 1; class_prob_tmp.back() = 1; class_prob_tmp /= sum_tmp; //calculate error and udpate with regularization auto label_tmp = instances.get_class(instance); class_prob_tmp[label_tmp] -= 1; global_squared_error.update(class_prob_tmp * class_prob_tmp); for(int x = 0; x < class_num - 1; x++){ para_update[x] -= (eta * class_prob_tmp[x] * x_with_const_term); } }); //to do the division only once. para_update /= instances.numInstances; //add regularization double tmp; for(int x = 0; x < class_num - 1; x++){ tmp = para_old[x].back(); para_old[x].back() = 0; para_update[x] -= (eta * alpha * para_old[x]); para_old[x].back() = tmp; } para_mat.update(para_update); double weighted_squared_error = global_squared_error.get_value() / instances.numInstances; //output the training infor. if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("\tGlobal averaged squared error: " + std::to_string(weighted_squared_error)); } if(old_weighted_squared_error < weighted_squared_error){ eta = eta0/pow(++eta_update_counter, 0.5); trival_improve_iter = 0; } else if (fabs(old_weighted_squared_error - weighted_squared_error) < trival_improve_th ){ trival_improve_iter ++; } else{ trival_improve_iter = 0; } old_weighted_squared_error = weighted_squared_error; husky::lib::AggregatorFactory::sync(); if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("\tParameters: " + matrix_to_str(para_mat.get_value())); } } this->param_matrix = para_mat.get_value(); if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("Training completed!"); } return; } void LogisticRegression::global_fit(const Instances& instances, std::string instance_weight_name){ const int num_attri = instances.numAttributes; matrix_double init_mat; for(int i = 1; i < this->class_num; i++){ init_mat.push_back(vec_double(num_attri + 1, 0.0)); } husky::lib::Aggregator<matrix_double> para_mat(init_mat, [](matrix_double& a, const matrix_double& b){ a += b;}, [num_attri, this](matrix_double& m){ m.clear(); for(int i = 1; i < this->class_num; i++){ m.push_back(vec_double(num_attri + 1, 0.0)); } }); husky::lib::Aggregator<double> global_squared_error(0.0, [](double& a, const double& b){ a += b;}, [](double& v){ v = 0; } ); global_squared_error.to_reset_each_iter(); auto& ac = husky::lib::AggregatorFactory::get_channel(); auto& weight_attrList = instances.getAttrlist<double>(instance_weight_name); double old_weighted_squared_error = std::numeric_limits<double>::max(); double eta = eta0; int eta_update_counter = 1; int trival_improve_iter = 0; //max_iter for(int iter = 1; iter <= max_iter && trival_improve_iter < max_trival_improve_iter; iter++){ if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("Iter#" + std::to_string(iter) + "\teta: " + std::to_string(eta)); } matrix_double para_update; for(int i = 1; i < this->class_num; i++){ para_update.push_back(vec_double(num_attri + 1, 0.0)); } matrix_double para_old = para_mat.get_value(); vec_double class_prob_tmp(this->class_num, 0.0); list_execute(instances.enumerator(), {}, {&ac}, [&](Instance& instance){ vec_double x_with_const_term = instance.X; x_with_const_term.push_back(1); //calculate probability double sum_tmp = 0; for(int x = 0; x < class_num - 1; x++){ class_prob_tmp[x] = exp(x_with_const_term * para_old[x]); sum_tmp += class_prob_tmp[x]; } sum_tmp += 1; class_prob_tmp.back() = 1; class_prob_tmp /= sum_tmp; //calculate error and udpate with regularization double weight = weight_attrList.get(instance); auto label_tmp = instances.get_class(instance); class_prob_tmp[label_tmp] -= 1; global_squared_error.update(weight * class_prob_tmp * class_prob_tmp); for(int x = 0; x < class_num - 1; x++){ para_update[x] -= (weight * eta * class_prob_tmp[x] * x_with_const_term); } }); double tmp; for(int x = 0; x < class_num - 1; x++){ tmp = para_old[x].back(); para_old[x].back() = 0; para_update[x] -= (eta * alpha * para_old[x]); para_old[x].back() = tmp; } para_mat.update(para_update); double weighted_squared_error = global_squared_error.get_value(); //output the training infor. if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("\tGlobal averaged squared error: " + std::to_string(weighted_squared_error)); } if(old_weighted_squared_error < weighted_squared_error){ eta = eta0/pow(++eta_update_counter, 0.5); trival_improve_iter = 0; } else if (fabs(old_weighted_squared_error - weighted_squared_error) < trival_improve_th ){ trival_improve_iter ++; } else{ trival_improve_iter = 0; } old_weighted_squared_error = weighted_squared_error; husky::lib::AggregatorFactory::sync(); if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("\tParameters: " + matrix_to_str(para_mat.get_value())); } } this->param_matrix = para_mat.get_value(); if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("Training completed!"); } return; } /* train model in local mode. */ void LogisticRegression::local_fit(const Instances& instances){ int num_attri = instances.numAttributes; matrix_double param_update; for(int i = 1; i < this->class_num; i++){ param_matrix.push_back(vec_double(num_attri + 1, 0.0)); param_update.push_back(vec_double(num_attri + 1, 0.0)); } double weighted_squared_error = 0; double old_weighted_squared_error = std::numeric_limits<double>::max(); double eta = eta0; int eta_update_counter = 1; int trival_improve_iter = 0; //count how many instances in local machine int num_instances_local = 0; list_execute(instances.enumerator(),{},{}, [&num_instances_local](Instance& instance){ num_instances_local++; } ); //max_iter for(int iter = 1; iter <= max_iter && trival_improve_iter < max_trival_improve_iter; iter++){ /* if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("Iter#" + std::to_string(iter) + "\teta: " + std::to_string(eta)); } */ //reset variables weighted_squared_error = 0; for(int i = 0; i < this->class_num-1; i++){ param_update[i].assign(num_attri + 1, 0.0); } vec_double class_prob_tmp(this->class_num, 0.0); list_execute(instances.enumerator(), {}, {}, [&](Instance& instance){ vec_double x_with_const_term = instance.X; x_with_const_term.push_back(1); //calculate probability double sum_tmp = 0; for(int x = 0; x < class_num-1; x++ ){ class_prob_tmp[x] = exp(x_with_const_term * param_matrix[x]); sum_tmp += class_prob_tmp[x]; } sum_tmp += 1; class_prob_tmp.back() = 1; class_prob_tmp /= sum_tmp; //calculate error and update auto label_tmp = instances.get_class(instance); class_prob_tmp[label_tmp] -= 1; weighted_squared_error += (class_prob_tmp * class_prob_tmp); for(int x = 0; x < class_num - 1; x++){ param_update[x] -= (eta * class_prob_tmp[x] * x_with_const_term); } } ); //update parameters. param_update /= num_instances_local; //regularization term double tmp; for(int x = 0; x < class_num - 1; x++){ tmp = param_matrix[x].back(); param_matrix[x].back() = 0; param_update[x] -= (eta * alpha * param_matrix[x]); param_matrix[x].back() = tmp; } param_matrix += param_update; weighted_squared_error /= num_instances_local; //output local error. if(husky::Context::get_global_tid() == 0){ husky::base::log_msg("Iter#" + std::to_string(iter) + "\n" + "Local averaged squared error: " + std::to_string(weighted_squared_error) + "\n" + "Parameters: " + matrix_to_str(param_matrix)); //std::cout<<"Parameters: " + matrix_to_str(param_matrix)<<std::endl; } if(old_weighted_squared_error < weighted_squared_error){ eta = eta0/pow(++eta_update_counter, 0.5); trival_improve_iter = 0; } else if (fabs(old_weighted_squared_error - weighted_squared_error) < trival_improve_th ){ trival_improve_iter ++; } else{ trival_improve_iter = 0; } old_weighted_squared_error = weighted_squared_error; } if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("Training completed!"); } return; } void LogisticRegression::local_fit(const Instances& instances, std::string instance_weight_name){ int num_attri = instances.numAttributes; matrix_double param_update; for(int i = 1; i < this->class_num; i++){ param_matrix.push_back(vec_double(num_attri + 1, 0.0)); param_update.push_back(vec_double(num_attri + 1, 0.0)); } auto& weight_attrList = instances.getAttrlist<double>(instance_weight_name); double weighted_squared_error = 0; double old_weighted_squared_error = std::numeric_limits<double>::max(); double eta = eta0; int eta_update_counter = 1; int trival_improve_iter = 0; //count how many instances in local machine int num_instances_local = 0; list_execute(instances.enumerator(),{},{}, [&num_instances_local](Instance& instance){ num_instances_local++; } ); //max_iter for(int iter = 1; iter <= max_iter && trival_improve_iter < max_trival_improve_iter; iter++){ /* if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("Iter#" + std::to_string(iter) + "\teta: " + std::to_string(eta)); } */ //reset variables weighted_squared_error = 0; for(int i = 0; i < this->class_num-1; i++){ param_update[i].assign(num_attri + 1, 0.0); } vec_double class_prob_tmp(this->class_num, 0.0); list_execute(instances.enumerator(), {}, {}, [&](Instance& instance){ vec_double x_with_const_term = instance.X; x_with_const_term.push_back(1); //calculate probability double sum_tmp = 0; for(int x = 0; x < class_num-1; x++ ){ class_prob_tmp[x] = exp(x_with_const_term * param_matrix[x]); sum_tmp += class_prob_tmp[x]; } sum_tmp += 1; class_prob_tmp.back() = 1; class_prob_tmp /= sum_tmp; //calculate error and update double weight = weight_attrList.get(instance); auto label_tmp = instances.get_class(instance); class_prob_tmp[label_tmp] -= 1; weighted_squared_error += (weight * class_prob_tmp * class_prob_tmp); for(int x = 0; x < class_num - 1; x++){ param_update[x] -= (weight * eta * class_prob_tmp[x] * x_with_const_term); } } ); //regularization term double tmp; for(int x = 0; x < class_num - 1; x++){ tmp = param_matrix[x].back(); param_matrix[x].back() = 0; param_update[x] -= (eta * alpha * param_matrix[x]); param_matrix[x].back() = tmp; } param_matrix += param_update; weighted_squared_error /= num_instances_local; //output local error. if(husky::Context::get_global_tid() == 0){ husky::base::log_msg("Iter#" + std::to_string(iter) + "\n" + "Local averaged squared error: " + std::to_string(weighted_squared_error) + "\n" + "Parameters: " + matrix_to_str(param_matrix)); } if(old_weighted_squared_error < weighted_squared_error){ eta = eta0/pow(++eta_update_counter, 0.5); trival_improve_iter = 0; } else if (fabs(old_weighted_squared_error - weighted_squared_error) < trival_improve_th ){ trival_improve_iter ++; } else{ trival_improve_iter = 0; } old_weighted_squared_error = weighted_squared_error; } if (husky::Context::get_global_tid() == 0) { husky::base::log_msg("Training completed!"); } return; } /* * predict #prediciton contains label and class_proba in it. */ AttrList<Instance, Prediction>& LogisticRegression::predict(const Instances& instances,std::string prediction_name){ if(this->mode == MODE::LOCAL){ throw std::invalid_argument("Prediciton is not provided after training in LOCAL mode!"); } AttrList<Instance, Prediction>& prediction = instances.enumerator().has_attrlist(prediction_name)? instances.getAttrlist<Prediction>(prediction_name) : instances.createAttrlist<Prediction>(prediction_name); list_execute(instances.enumerator(), [&prediction, this](Instance& instance) { vec_double feature_vector=instance.X; feature_vector.push_back(1); //calculate probability vec_double class_prob_tmp(class_num, 0.0); double sum_tmp = 0; for(int x = 0; x < class_num-1; x++ ){ class_prob_tmp[x] = exp(feature_vector * param_matrix[x]); sum_tmp += class_prob_tmp[x]; } sum_tmp += 1; class_prob_tmp.back() = 1; class_prob_tmp /= sum_tmp; //choose label with highest probability double max_p = 0; int label; for(int x = 0; x < class_num; x++){ if(class_prob_tmp[x] > max_p){ max_p = class_prob_tmp[x]; label = x; } } prediction.set(instance, Prediction(label, class_prob_tmp)); }); return prediction; } } }
41.372051
217
0.469995
Christina-hshi
eb71b86555363e03ff019f9cb0f704a08eee1358
993
cpp
C++
binarysearch.io/easy/Pattern-to-Word-Bijection.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
binarysearch.io/easy/Pattern-to-Word-Bijection.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
binarysearch.io/easy/Pattern-to-Word-Bijection.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Pattern to Word Bijection https://binarysearch.com/problems/Pattern-to-Word-Bijection Given two strings s and p, return whether s follows the pattern in p. That is, return whether each character in p can map to a non-empty word such that it maps to s. Constraints n ≤ 100,000 where n is the length of s Example 1 Input s = "hello world world world hello" p = "abbba" Output true Explanation We can map "a" = "hello" and "b" = "world". */ #include "solution.hpp" using namespace std; class Solution { public: bool solve(string s, string p) { unordered_map<string, int> m; istringstream iss(s); string ss; int i = 0; while(iss>>ss){ if(m.count(ss)) { if(m[ss]!=p[i]) return false; } else { for(auto& k: m) { if(k.second == p[i]) return false; } m[ss]=p[i]; } i++; } return true; } };
21.586957
165
0.548842
wingkwong
eb765ec6e408bf6b2d058d5fc59b6849a5233b36
4,254
hpp
C++
hostsvc/Connection.hpp
lishunan246/b
82023dee34b023dfbc3dd2f0381fdbd7e266604e
[ "BSD-2-Clause" ]
null
null
null
hostsvc/Connection.hpp
lishunan246/b
82023dee34b023dfbc3dd2f0381fdbd7e266604e
[ "BSD-2-Clause" ]
null
null
null
hostsvc/Connection.hpp
lishunan246/b
82023dee34b023dfbc3dd2f0381fdbd7e266604e
[ "BSD-2-Clause" ]
null
null
null
// // Created by lishunan on 4/19/16. // #ifndef HOSTSVC_RPCCHANNEL_H #define HOSTSVC_RPCCHANNEL_H #include "HostSvcCommon.hpp" #include <unordered_map> using namespace google::protobuf; namespace GkcHostSvc { using messageHandler = function<void(RPCResponse)>; class Connection : public protobuf::RpcChannel { private: std::condition_variable cv; std::mutex m; std::atomic<bool> connected{ false }; std::unordered_map<string, messageHandler> handlerMap; RPCResponse response1; int _clientID = -1; WebsocketClient _WSclient; shared_ptr < WebsocketConnecton> con; shared_ptr<thread> pthread; char pSend[1000]; public: static shared_ptr<Connection> create(const string &server) { return make_shared<Connection>(server); } void registerHandler(const string& s,messageHandler h) { handlerMap.insert({ s,h }); } Connection(const string &server) { _WSclient.init_asio(); _WSclient.start_perpetual(); _WSclient.set_access_channels(websocketpp::log::alevel::none); _WSclient.set_open_handler([this](websocketpp::connection_hdl hdl) { this->connected = true; cout << "connected" << endl; }); _WSclient.set_message_handler([this](websocketpp::connection_hdl hdl,WebsocketClient::message_ptr msg) { auto _respondString = msg->get_payload(); //cout << msg->get_opcode() << "opcode" << "received:" << _respondString.size() << endl; RPCResponse r; r.ParseFromString(_respondString); if(r.ispushmessage()) { cout << "received:"<<_respondString.size() << endl; auto tt = handlerMap.at(r.pushtype()); tt(r); } else { response1 = r; _clientID = r.clientid(); print(_clientID); println(" receive response"); cv.notify_one(); } }); #ifdef GKC_SSL _WSclient.set_tls_init_handler([this](websocketpp::connection_hdl hdl)->shared_ptr<asio::ssl::context> { auto ctx = make_shared<asio::ssl::context>(asio::ssl::context::sslv23_client); try { ctx->set_options(asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3 | asio::ssl::context::single_dh_use); ctx->set_verify_mode(0); } catch (std::exception& e) { std::cout << e.what() << std::endl; } return ctx; }); string protocal = "wss://"; #else string protocal = "ws://"; #endif pthread=make_shared<thread>([this]() { cout << "running" << endl; _WSclient.run(); }); error_code ec; con = _WSclient.get_connection(protocal+server,ec); if(ec) { cout << "connection fail "+ec.message()<< endl; exit(1); } if (_WSclient.connect(con) != nullptr) { } else { cout << "error connection" << endl; } } Connection(const Connection &) = delete; Connection(Connection &&) = default; Connection &operator=(const Connection &) = delete; Connection &operator=(Connection &&) = default; int getClientID() { return _clientID; } ~Connection() { } void close() { con->close(websocketpp::close::status::normal,"quit"); _WSclient.stop_perpetual(); pthread->join(); pthread.reset(); } void CallMethod(const MethodDescriptor *method, RpcController *controller, const Message *request, Message *response, Closure *done) override{ std::unique_lock<std::mutex> lk(m); auto p = dynamic_cast<const RPCRequest *> (request); while (!connected) ; //cout << p->DebugString() << endl << p->ByteSize() << endl; p->SerializeToArray(pSend, sizeof pSend); auto messageSize = static_cast<size_t > (p->ByteSize()); auto ec = con->send(pSend, messageSize); if (ec) { cerr << "?" << ec.message() << endl; return; } cv.wait(lk); if(controller->Failed()) { cerr << controller->ErrorText(); } auto pLocalResponse = static_cast<RPCResponse *>(response); *pLocalResponse = response1; if (done != nullptr) done->Run(); lk.unlock(); } }; using pConnection=shared_ptr<Connection>; } #endif //HOSTSVC_RPCCHANNEL_H
24.448276
106
0.621533
lishunan246
eb781c081e36e72e1b02bb2962d3472c404f4ecd
20,939
cxx
C++
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimController_ZoneControlTemperature_ThermostatThermalComfort.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
3
2016-05-30T15:12:16.000Z
2022-03-22T08:11:13.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimController_ZoneControlTemperature_ThermostatThermalComfort.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
21
2016-06-13T11:33:45.000Z
2017-05-23T09:46:52.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimController_ZoneControlTemperature_ThermostatThermalComfort.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
null
null
null
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU 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 // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // // Begin prologue. // // // End prologue. #include <xsd/cxx/pre.hxx> #include "SimController_ZoneControlTemperature_ThermostatThermalComfort.hxx" #include "simcntrl_thermalcomfortcontrol_1_4_objecttype.hxx" namespace schema { namespace simxml { namespace MepModel { // SimController_ZoneControlTemperature_ThermostatThermalComfort // const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_AveragingMethod_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_AveragingMethod () const { return this->SimCntrl_AveragingMethod_; } SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_AveragingMethod_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_AveragingMethod () { return this->SimCntrl_AveragingMethod_; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_AveragingMethod (const SimCntrl_AveragingMethod_type& x) { this->SimCntrl_AveragingMethod_.set (x); } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_AveragingMethod (const SimCntrl_AveragingMethod_optional& x) { this->SimCntrl_AveragingMethod_ = x; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_AveragingMethod (::std::auto_ptr< SimCntrl_AveragingMethod_type > x) { this->SimCntrl_AveragingMethod_.set (x); } const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_SpecificPeopleName_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_SpecificPeopleName () const { return this->SimCntrl_SpecificPeopleName_; } SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_SpecificPeopleName_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_SpecificPeopleName () { return this->SimCntrl_SpecificPeopleName_; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_SpecificPeopleName (const SimCntrl_SpecificPeopleName_type& x) { this->SimCntrl_SpecificPeopleName_.set (x); } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_SpecificPeopleName (const SimCntrl_SpecificPeopleName_optional& x) { this->SimCntrl_SpecificPeopleName_ = x; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_SpecificPeopleName (::std::auto_ptr< SimCntrl_SpecificPeopleName_type > x) { this->SimCntrl_SpecificPeopleName_.set (x); } const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_MinDry_BulbTempSetpoint_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_MinDry_BulbTempSetpoint () const { return this->SimCntrl_MinDry_BulbTempSetpoint_; } SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_MinDry_BulbTempSetpoint_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_MinDry_BulbTempSetpoint () { return this->SimCntrl_MinDry_BulbTempSetpoint_; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_MinDry_BulbTempSetpoint (const SimCntrl_MinDry_BulbTempSetpoint_type& x) { this->SimCntrl_MinDry_BulbTempSetpoint_.set (x); } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_MinDry_BulbTempSetpoint (const SimCntrl_MinDry_BulbTempSetpoint_optional& x) { this->SimCntrl_MinDry_BulbTempSetpoint_ = x; } const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_MaxDry_BulbTempSetpoint_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_MaxDry_BulbTempSetpoint () const { return this->SimCntrl_MaxDry_BulbTempSetpoint_; } SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_MaxDry_BulbTempSetpoint_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_MaxDry_BulbTempSetpoint () { return this->SimCntrl_MaxDry_BulbTempSetpoint_; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_MaxDry_BulbTempSetpoint (const SimCntrl_MaxDry_BulbTempSetpoint_type& x) { this->SimCntrl_MaxDry_BulbTempSetpoint_.set (x); } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_MaxDry_BulbTempSetpoint (const SimCntrl_MaxDry_BulbTempSetpoint_optional& x) { this->SimCntrl_MaxDry_BulbTempSetpoint_ = x; } const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_ThermalComfortControlTypeScheduleName_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControlTypeScheduleName () const { return this->SimCntrl_ThermalComfortControlTypeScheduleName_; } SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_ThermalComfortControlTypeScheduleName_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControlTypeScheduleName () { return this->SimCntrl_ThermalComfortControlTypeScheduleName_; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControlTypeScheduleName (const SimCntrl_ThermalComfortControlTypeScheduleName_type& x) { this->SimCntrl_ThermalComfortControlTypeScheduleName_.set (x); } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControlTypeScheduleName (const SimCntrl_ThermalComfortControlTypeScheduleName_optional& x) { this->SimCntrl_ThermalComfortControlTypeScheduleName_ = x; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControlTypeScheduleName (::std::auto_ptr< SimCntrl_ThermalComfortControlTypeScheduleName_type > x) { this->SimCntrl_ThermalComfortControlTypeScheduleName_.set (x); } const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_ThermalComfortControl_1_4_ObjectType_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_ObjectType () const { return this->SimCntrl_ThermalComfortControl_1_4_ObjectType_; } SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_ThermalComfortControl_1_4_ObjectType_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_ObjectType () { return this->SimCntrl_ThermalComfortControl_1_4_ObjectType_; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_ObjectType (const SimCntrl_ThermalComfortControl_1_4_ObjectType_type& x) { this->SimCntrl_ThermalComfortControl_1_4_ObjectType_.set (x); } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_ObjectType (const SimCntrl_ThermalComfortControl_1_4_ObjectType_optional& x) { this->SimCntrl_ThermalComfortControl_1_4_ObjectType_ = x; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_ObjectType (::std::auto_ptr< SimCntrl_ThermalComfortControl_1_4_ObjectType_type > x) { this->SimCntrl_ThermalComfortControl_1_4_ObjectType_.set (x); } const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_ThermalComfortControl_1_4_Name_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_Name () const { return this->SimCntrl_ThermalComfortControl_1_4_Name_; } SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_ThermalComfortControl_1_4_Name_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_Name () { return this->SimCntrl_ThermalComfortControl_1_4_Name_; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_Name (const SimCntrl_ThermalComfortControl_1_4_Name_type& x) { this->SimCntrl_ThermalComfortControl_1_4_Name_.set (x); } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_Name (const SimCntrl_ThermalComfortControl_1_4_Name_optional& x) { this->SimCntrl_ThermalComfortControl_1_4_Name_ = x; } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimCntrl_ThermalComfortControl_1_4_Name (::std::auto_ptr< SimCntrl_ThermalComfortControl_1_4_Name_type > x) { this->SimCntrl_ThermalComfortControl_1_4_Name_.set (x); } } } } #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; } namespace schema { namespace simxml { namespace MepModel { // SimController_ZoneControlTemperature_ThermostatThermalComfort // SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimController_ZoneControlTemperature_ThermostatThermalComfort () : ::schema::simxml::MepModel::SimController_ZoneControlTemperature (), SimCntrl_AveragingMethod_ (this), SimCntrl_SpecificPeopleName_ (this), SimCntrl_MinDry_BulbTempSetpoint_ (this), SimCntrl_MaxDry_BulbTempSetpoint_ (this), SimCntrl_ThermalComfortControlTypeScheduleName_ (this), SimCntrl_ThermalComfortControl_1_4_ObjectType_ (this), SimCntrl_ThermalComfortControl_1_4_Name_ (this) { } SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimController_ZoneControlTemperature_ThermostatThermalComfort (const RefId_type& RefId) : ::schema::simxml::MepModel::SimController_ZoneControlTemperature (RefId), SimCntrl_AveragingMethod_ (this), SimCntrl_SpecificPeopleName_ (this), SimCntrl_MinDry_BulbTempSetpoint_ (this), SimCntrl_MaxDry_BulbTempSetpoint_ (this), SimCntrl_ThermalComfortControlTypeScheduleName_ (this), SimCntrl_ThermalComfortControl_1_4_ObjectType_ (this), SimCntrl_ThermalComfortControl_1_4_Name_ (this) { } SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimController_ZoneControlTemperature_ThermostatThermalComfort (const SimController_ZoneControlTemperature_ThermostatThermalComfort& x, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::MepModel::SimController_ZoneControlTemperature (x, f, c), SimCntrl_AveragingMethod_ (x.SimCntrl_AveragingMethod_, f, this), SimCntrl_SpecificPeopleName_ (x.SimCntrl_SpecificPeopleName_, f, this), SimCntrl_MinDry_BulbTempSetpoint_ (x.SimCntrl_MinDry_BulbTempSetpoint_, f, this), SimCntrl_MaxDry_BulbTempSetpoint_ (x.SimCntrl_MaxDry_BulbTempSetpoint_, f, this), SimCntrl_ThermalComfortControlTypeScheduleName_ (x.SimCntrl_ThermalComfortControlTypeScheduleName_, f, this), SimCntrl_ThermalComfortControl_1_4_ObjectType_ (x.SimCntrl_ThermalComfortControl_1_4_ObjectType_, f, this), SimCntrl_ThermalComfortControl_1_4_Name_ (x.SimCntrl_ThermalComfortControl_1_4_Name_, f, this) { } SimController_ZoneControlTemperature_ThermostatThermalComfort:: SimController_ZoneControlTemperature_ThermostatThermalComfort (const ::xercesc::DOMElement& e, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::MepModel::SimController_ZoneControlTemperature (e, f | ::xml_schema::flags::base, c), SimCntrl_AveragingMethod_ (this), SimCntrl_SpecificPeopleName_ (this), SimCntrl_MinDry_BulbTempSetpoint_ (this), SimCntrl_MaxDry_BulbTempSetpoint_ (this), SimCntrl_ThermalComfortControlTypeScheduleName_ (this), SimCntrl_ThermalComfortControl_1_4_ObjectType_ (this), SimCntrl_ThermalComfortControl_1_4_Name_ (this) { if ((f & ::xml_schema::flags::base) == 0) { ::xsd::cxx::xml::dom::parser< char > p (e, true, false, true); this->parse (p, f); } } void SimController_ZoneControlTemperature_ThermostatThermalComfort:: parse (::xsd::cxx::xml::dom::parser< char >& p, ::xml_schema::flags f) { this->::schema::simxml::MepModel::SimController_ZoneControlTemperature::parse (p, f); for (; p.more_content (); p.next_content (false)) { const ::xercesc::DOMElement& i (p.cur_element ()); const ::xsd::cxx::xml::qualified_name< char > n ( ::xsd::cxx::xml::dom::name< char > (i)); // SimCntrl_AveragingMethod // if (n.name () == "SimCntrl_AveragingMethod" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimCntrl_AveragingMethod_type > r ( SimCntrl_AveragingMethod_traits::create (i, f, this)); if (!this->SimCntrl_AveragingMethod_) { this->SimCntrl_AveragingMethod_.set (r); continue; } } // SimCntrl_SpecificPeopleName // if (n.name () == "SimCntrl_SpecificPeopleName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimCntrl_SpecificPeopleName_type > r ( SimCntrl_SpecificPeopleName_traits::create (i, f, this)); if (!this->SimCntrl_SpecificPeopleName_) { this->SimCntrl_SpecificPeopleName_.set (r); continue; } } // SimCntrl_MinDry_BulbTempSetpoint // if (n.name () == "SimCntrl_MinDry_BulbTempSetpoint" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimCntrl_MinDry_BulbTempSetpoint_) { this->SimCntrl_MinDry_BulbTempSetpoint_.set (SimCntrl_MinDry_BulbTempSetpoint_traits::create (i, f, this)); continue; } } // SimCntrl_MaxDry_BulbTempSetpoint // if (n.name () == "SimCntrl_MaxDry_BulbTempSetpoint" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimCntrl_MaxDry_BulbTempSetpoint_) { this->SimCntrl_MaxDry_BulbTempSetpoint_.set (SimCntrl_MaxDry_BulbTempSetpoint_traits::create (i, f, this)); continue; } } // SimCntrl_ThermalComfortControlTypeScheduleName // if (n.name () == "SimCntrl_ThermalComfortControlTypeScheduleName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimCntrl_ThermalComfortControlTypeScheduleName_type > r ( SimCntrl_ThermalComfortControlTypeScheduleName_traits::create (i, f, this)); if (!this->SimCntrl_ThermalComfortControlTypeScheduleName_) { this->SimCntrl_ThermalComfortControlTypeScheduleName_.set (r); continue; } } // SimCntrl_ThermalComfortControl_1_4_ObjectType // if (n.name () == "SimCntrl_ThermalComfortControl_1_4_ObjectType" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimCntrl_ThermalComfortControl_1_4_ObjectType_type > r ( SimCntrl_ThermalComfortControl_1_4_ObjectType_traits::create (i, f, this)); if (!this->SimCntrl_ThermalComfortControl_1_4_ObjectType_) { this->SimCntrl_ThermalComfortControl_1_4_ObjectType_.set (r); continue; } } // SimCntrl_ThermalComfortControl_1_4_Name // if (n.name () == "SimCntrl_ThermalComfortControl_1_4_Name" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimCntrl_ThermalComfortControl_1_4_Name_type > r ( SimCntrl_ThermalComfortControl_1_4_Name_traits::create (i, f, this)); if (!this->SimCntrl_ThermalComfortControl_1_4_Name_) { this->SimCntrl_ThermalComfortControl_1_4_Name_.set (r); continue; } } break; } } SimController_ZoneControlTemperature_ThermostatThermalComfort* SimController_ZoneControlTemperature_ThermostatThermalComfort:: _clone (::xml_schema::flags f, ::xml_schema::container* c) const { return new class SimController_ZoneControlTemperature_ThermostatThermalComfort (*this, f, c); } SimController_ZoneControlTemperature_ThermostatThermalComfort& SimController_ZoneControlTemperature_ThermostatThermalComfort:: operator= (const SimController_ZoneControlTemperature_ThermostatThermalComfort& x) { if (this != &x) { static_cast< ::schema::simxml::MepModel::SimController_ZoneControlTemperature& > (*this) = x; this->SimCntrl_AveragingMethod_ = x.SimCntrl_AveragingMethod_; this->SimCntrl_SpecificPeopleName_ = x.SimCntrl_SpecificPeopleName_; this->SimCntrl_MinDry_BulbTempSetpoint_ = x.SimCntrl_MinDry_BulbTempSetpoint_; this->SimCntrl_MaxDry_BulbTempSetpoint_ = x.SimCntrl_MaxDry_BulbTempSetpoint_; this->SimCntrl_ThermalComfortControlTypeScheduleName_ = x.SimCntrl_ThermalComfortControlTypeScheduleName_; this->SimCntrl_ThermalComfortControl_1_4_ObjectType_ = x.SimCntrl_ThermalComfortControl_1_4_ObjectType_; this->SimCntrl_ThermalComfortControl_1_4_Name_ = x.SimCntrl_ThermalComfortControl_1_4_Name_; } return *this; } SimController_ZoneControlTemperature_ThermostatThermalComfort:: ~SimController_ZoneControlTemperature_ThermostatThermalComfort () { } } } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace schema { namespace simxml { namespace MepModel { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
42.046185
195
0.723865
EnEff-BIM
eb781e552af0f6852b5b20040b828cf0b784c6d1
565
cpp
C++
Reverse a Linked List in groups of given size.cpp
Subhash3/Algorithms-For-Software-Developers
2e0ac4f51d379a2b10a40fca7fa82a8501d3db94
[ "BSD-2-Clause" ]
2
2021-10-01T04:20:04.000Z
2021-10-01T04:20:06.000Z
Reverse a Linked List in groups of given size.cpp
Subhash3/Algorithms-For-Software-Developers
2e0ac4f51d379a2b10a40fca7fa82a8501d3db94
[ "BSD-2-Clause" ]
1
2021-10-01T18:00:09.000Z
2021-10-01T18:00:09.000Z
Reverse a Linked List in groups of given size.cpp
Subhash3/Algorithms-For-Software-Developers
2e0ac4f51d379a2b10a40fca7fa82a8501d3db94
[ "BSD-2-Clause" ]
8
2021-10-01T04:20:38.000Z
2022-03-19T17:05:05.000Z
class Solution { public: int l(struct node* h){ int c; while(h){ h=h->next; ++c; } return c; } struct node *reverse (struct node *head, int k) { if(l(head)<k) return head; struct node *prev=0; struct node *next=0; struct node *curr=head; for(int i=0;i<k;i++){ next=curr->next; curr->next=prev; prev=curr; curr=next; } head->next=reverse(curr,k); return prev; } };
19.482759
51
0.424779
Subhash3
eb79e846435d4de4af5e754ac5f49b0460911081
2,122
cpp
C++
querier/BaseChunkSeriesSet.cpp
Jimx-/tsdb-fork
f92cfa0a998c03b3a2cb4c8e46990de8b47aae15
[ "Apache-2.0" ]
1
2020-06-04T06:56:40.000Z
2020-06-04T06:56:40.000Z
querier/BaseChunkSeriesSet.cpp
Jimx-/tsdb-fork
f92cfa0a998c03b3a2cb4c8e46990de8b47aae15
[ "Apache-2.0" ]
null
null
null
querier/BaseChunkSeriesSet.cpp
Jimx-/tsdb-fork
f92cfa0a998c03b3a2cb4c8e46990de8b47aae15
[ "Apache-2.0" ]
1
2020-06-04T03:35:58.000Z
2020-06-04T03:35:58.000Z
#include "querier/BaseChunkSeriesSet.hpp" #include "base/Logging.hpp" #include "index/PostingSet.hpp" #include <unordered_set> namespace tsdb { namespace querier { // BaseChunkSeriesSet loads the label set and chunk references for a postings // list from an index. It filters out series that have labels set that should be // unset // // The chunk pointer in ChunkMeta is not set // NOTE(Alec), BaseChunkSeriesSet fine-grained filters the chunks using // tombstone. BaseChunkSeriesSet::BaseChunkSeriesSet( const std::shared_ptr<block::IndexReaderInterface>& ir, const std::shared_ptr<tombstone::TombstoneReaderInterface>& tr, const std::set<tagtree::TSID>& list) : ir(ir), tr(tr), cm(new ChunkSeriesMeta()), err_(false) { p = std::make_unique<index::PostingSet>(list); } // next() always called before at(). const std::shared_ptr<ChunkSeriesMeta>& BaseChunkSeriesSet::at() const { return cm; } bool BaseChunkSeriesSet::next() const { if (err_) return false; while (p->next()) { auto tsid = p->at(); cm->clear(); cm->tsid = tsid; // Get labels and deque of ChunkMeta of the corresponding series. if (!ir->series(tsid, cm->chunks)) { // TODO, ErrNotFound // err_ = true; // return false; continue; } // Get Intervals from MemTombstones try { // LOG_INFO << ref; cm->intervals = tr->get(tsid); } catch (const std::out_of_range& e) { } if (!(cm->intervals).empty()) { std::vector<std::shared_ptr<chunk::ChunkMeta>>::iterator it = cm->chunks.begin(); while (it != cm->chunks.end()) { if (tombstone::is_subrange((*it)->min_time, (*it)->max_time, cm->intervals)) it = cm->chunks.erase(it); else ++it; } } return true; } return false; } bool BaseChunkSeriesSet::error() const { return err_; } } // namespace querier } // namespace tsdb
27.921053
80
0.582941
Jimx-
eb7a0116bdd5d901141b9585dff6b9973b0049f5
2,046
cc
C++
absl/base/internal/scoped_set_env.cc
abaskin/abseil-cpp
9e598094c380d79119c752d4a472c0765728ec81
[ "Apache-2.0" ]
null
null
null
absl/base/internal/scoped_set_env.cc
abaskin/abseil-cpp
9e598094c380d79119c752d4a472c0765728ec81
[ "Apache-2.0" ]
1
2020-02-17T08:25:41.000Z
2020-02-18T08:08:59.000Z
absl/base/internal/scoped_set_env.cc
abaskin/abseil-cpp
9e598094c380d79119c752d4a472c0765728ec81
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 The Abseil 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 // // https://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 "absl/base/internal/scoped_set_env.h" #ifdef _WIN32 #include <windows.h> #endif #include <cstdlib> #include "absl/base/internal/raw_logging.h" namespace absl { inline namespace lts_2019_08_08 { namespace base_internal { namespace { #ifdef _WIN32 const int kMaxEnvVarValueSize = 1024; #endif void SetEnvVar(const char* name, const char* value) { #ifdef _WIN32 SetEnvironmentVariableA(name, value); #else if (value == nullptr) { ::unsetenv(name); } else { ::setenv(name, value, 1); } #endif } } // namespace ScopedSetEnv::ScopedSetEnv(const char* var_name, const char* new_value) : var_name_(var_name), was_unset_(false) { #ifdef _WIN32 char buf[kMaxEnvVarValueSize]; auto get_res = GetEnvironmentVariableA(var_name_.c_str(), buf, sizeof(buf)); ABSL_INTERNAL_CHECK(get_res < sizeof(buf), "value exceeds buffer size"); if (get_res == 0) { was_unset_ = (GetLastError() == ERROR_ENVVAR_NOT_FOUND); } else { old_value_.assign(buf, get_res); } SetEnvironmentVariableA(var_name_.c_str(), new_value); #else const char* val = ::getenv(var_name_.c_str()); if (val == nullptr) { was_unset_ = true; } else { old_value_ = val; } #endif SetEnvVar(var_name_.c_str(), new_value); } ScopedSetEnv::~ScopedSetEnv() { SetEnvVar(var_name_.c_str(), was_unset_ ? nullptr : old_value_.c_str()); } } // namespace base_internal } // inline namespace lts_2019_08_08 } // namespace absl
24.95122
78
0.716031
abaskin
eb7d731262e2c5b0ac6a7e3f1d3fd9ff7f408dc8
11,378
cpp
C++
ftaction.cpp
sphinxlogic/shell32
ef38d3338afd575a2d456d737c7bd6a105392d88
[ "MIT" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
shell/shell32/ftaction.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
shell/shell32/ftaction.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "shellprv.h" #include "ids.h" #include "ftadv.h" #include "ftcmmn.h" #include "ftaction.h" #include "ftassoc.h" const static DWORD cs_rgdwHelpIDsArray[] = { // Context Help IDs IDC_FT_CMD_ACTION, IDH_FCAB_FT_CMD_ACTION, IDC_FT_CMD_EXETEXT, IDH_FCAB_FT_CMD_EXE, IDC_FT_CMD_EXE, IDH_FCAB_FT_CMD_EXE, IDC_FT_CMD_BROWSE, IDH_FCAB_FT_CMD_BROWSE, IDC_FT_CMD_DDEGROUP, IDH_FCAB_FT_CMD_USEDDE, IDC_FT_CMD_USEDDE, IDH_FCAB_FT_CMD_USEDDE, IDC_FT_CMD_DDEMSG, IDH_FCAB_FT_CMD_DDEMSG, IDC_FT_CMD_DDEAPP, IDH_FCAB_FT_CMD_DDEAPP, IDC_FT_CMD_DDEAPPNOT, IDH_FCAB_FT_CMD_DDEAPPNOT, IDC_FT_CMD_DDETOPIC, IDH_FCAB_FT_CMD_DDETOPIC, 0, 0 }; CFTActionDlg::CFTActionDlg(PROGIDACTION* pProgIDAction, LPTSTR pszProgIDDescr, BOOL fEdit) : CFTDlg((ULONG_PTR)cs_rgdwHelpIDsArray), _pProgIDAction(pProgIDAction), _pszProgIDDescr(pszProgIDDescr), _fEdit(fEdit) { } CFTActionDlg::~CFTActionDlg() { } /////////////////////////////////////////////////////////////////////////////// // Logic specific to our problem LRESULT CFTActionDlg::OnInitDialog(WPARAM wParam, LPARAM lParam) { DECLAREWAITCURSOR; SetWaitCursor(); if (_fEdit || _fShowAgain) { TCHAR szTitle[50 + MAX_PROGIDDESCR + 5]; TCHAR szTitleTemplate[50]; _fShowAgain = FALSE; if (LoadString(g_hinst, IDS_FT_EDITTITLE, szTitleTemplate, ARRAYSIZE(szTitleTemplate))) { StringCchPrintf(szTitle, ARRAYSIZE(szTitle), szTitleTemplate, _pszProgIDDescr); SetWindowText(_hwnd, szTitle); } SetDlgItemText(_hwnd, IDC_FT_CMD_ACTION, _pProgIDAction->szAction); SetDlgItemText(_hwnd, IDC_FT_CMD_EXE, _pProgIDAction->szCmdLine); SetDlgItemText(_hwnd, IDC_FT_CMD_DDEMSG, _pProgIDAction->szDDEMsg); SetDlgItemText(_hwnd, IDC_FT_CMD_DDEAPP, _pProgIDAction->szDDEApplication); SetDlgItemText(_hwnd, IDC_FT_CMD_DDEAPPNOT, _pProgIDAction->szDDEAppNotRunning); SetDlgItemText(_hwnd, IDC_FT_CMD_DDETOPIC, _pProgIDAction->szDDETopic); CheckDlgButton(_hwnd, IDC_FT_CMD_USEDDE, _pProgIDAction->fUseDDE); _ResizeDlgForDDE(_pProgIDAction->fUseDDE); } else { CheckDlgButton(_hwnd, IDC_FT_CMD_USEDDE, FALSE); _ResizeDlgForDDE(FALSE); } Edit_LimitText(GetDlgItem(_hwnd, IDC_FT_CMD_ACTION), MAX_ACTION - 1); Edit_LimitText(GetDlgItem(_hwnd, IDC_FT_CMD_EXE), MAX_ACTIONCMDLINE - 1); Edit_LimitText(GetDlgItem(_hwnd, IDC_FT_CMD_DDEMSG), MAX_ACTIONDDEMSG - 1); Edit_LimitText(GetDlgItem(_hwnd, IDC_FT_CMD_DDEAPP), MAX_ACTIONAPPL - 1); Edit_LimitText(GetDlgItem(_hwnd, IDC_FT_CMD_DDEAPPNOT), MAX_ACTIONDDEAPPNOTRUN - 1); Edit_LimitText(GetDlgItem(_hwnd, IDC_FT_CMD_DDETOPIC), MAX_ACTIONTOPIC - 1); ResetWaitCursor(); // Return TRUE so that system set focus return TRUE; } BOOL CFTActionDlg::_Validate() { BOOL bRet = TRUE; // Check the Action TCHAR szAction[MAX_ACTION]; if (!GetDlgItemText(_hwnd, IDC_FT_CMD_ACTION, szAction, ARRAYSIZE(szAction)) || !*szAction) { ShellMessageBox(g_hinst, _hwnd, MAKEINTRESOURCE(IDS_FT_MB_NOACTION), MAKEINTRESOURCE(IDS_FT), MB_OK | MB_ICONSTOP); PostMessage(_hwnd, WM_CTRL_SETFOCUS, (WPARAM)0, (LPARAM)GetDlgItem(_hwnd, IDC_FT_CMD_ACTION)); bRet = FALSE; } if (bRet) { TCHAR szPath[MAX_PATH]; LPTSTR pszFileName = NULL; // Check for valid exe GetDlgItemText(_hwnd, IDC_FT_CMD_EXE, szPath, ARRAYSIZE(szPath)); PathRemoveArgs(szPath); PathUnquoteSpaces(szPath); pszFileName = PathFindFileName(szPath); if(!(*szPath) || !(PathIsExe(szPath)) || ((!(PathFileExists(szPath))) && (!(PathFindOnPath(pszFileName, NULL))))) { // Tell user that this exe is invalid ShellMessageBox(g_hinst, _hwnd, MAKEINTRESOURCE(IDS_FT_MB_EXETEXT), MAKEINTRESOURCE(IDS_FT), MB_OK | MB_ICONSTOP); PostMessage(_hwnd, WM_CTRL_SETFOCUS, (WPARAM)0, (LPARAM)GetDlgItem(_hwnd, IDC_FT_CMD_EXE)); bRet = FALSE; } } return bRet; } void CFTActionDlg::SetShowAgain() { _fShowAgain = TRUE; } BOOL _IsThereAnyPercentArgument(LPTSTR pszCommand) { BOOL fRet = FALSE; LPTSTR pszArgs = PathGetArgs(pszCommand); if (pszArgs && *pszArgs) { if (StrStr(pszArgs, TEXT("%"))) { fRet = TRUE; } } return fRet; } LRESULT CFTActionDlg::OnOK(WORD wNotif) { if (_Validate()) { GetDlgItemText(_hwnd, IDC_FT_CMD_ACTION, _pProgIDAction->szAction, MAX_ACTION); // Is this a new action? if (!_fEdit) { // Yes, initialize the old action field StringCchCopy(_pProgIDAction->szOldAction, ARRAYSIZE(_pProgIDAction->szOldAction), _pProgIDAction->szAction); // Build the ActionReg StringCchCopy(_pProgIDAction->szActionReg, ARRAYSIZE(_pProgIDAction->szActionReg), _pProgIDAction->szAction); // Replace spaces with underscores LPTSTR psz = _pProgIDAction->szActionReg; while (*psz) { if (TEXT(' ') == *psz) { *psz = TEXT('_'); } psz = CharNext(psz); } StringCchCopy(_pProgIDAction->szOldActionReg, ARRAYSIZE(_pProgIDAction->szOldActionReg), _pProgIDAction->szActionReg); } GetDlgItemText(_hwnd, IDC_FT_CMD_EXE, _pProgIDAction->szCmdLine, MAX_ACTIONCMDLINE); GetDlgItemText(_hwnd, IDC_FT_CMD_DDEMSG, _pProgIDAction->szDDEMsg, MAX_ACTIONDDEMSG); GetDlgItemText(_hwnd, IDC_FT_CMD_DDEAPP, _pProgIDAction->szDDEApplication, MAX_ACTIONAPPL); GetDlgItemText(_hwnd, IDC_FT_CMD_DDEAPPNOT, _pProgIDAction->szDDEAppNotRunning, MAX_ACTIONDDEAPPNOTRUN); GetDlgItemText(_hwnd, IDC_FT_CMD_DDETOPIC, _pProgIDAction->szDDETopic, MAX_ACTIONTOPIC); _pProgIDAction->fUseDDE = IsDlgButtonChecked(_hwnd, IDC_FT_CMD_USEDDE); // Append %1 to action field, if required if (!_IsThereAnyPercentArgument(_pProgIDAction->szCmdLine)) { TCHAR* pszPercentToAppend; if (StrChr(_pProgIDAction->szCmdLine,TEXT('\\'))) { if (App_IsLFNAware(_pProgIDAction->szCmdLine)) pszPercentToAppend = TEXT(" \"%1\""); else pszPercentToAppend = TEXT(" %1"); } else { TCHAR szFullPathFileName[MAX_PATH]; // StringCchCopy(szFullPathFileName, ARRAYSIZE(szFullPathFileName), _pProgIDAction->szCmdLine); //PathFindOnPath: first param is the filename, if it is on the path // then it returns fully qualified, if not return false. //Second param is optional directory to look in first if (PathFindOnPath(szFullPathFileName, NULL)) { if (App_IsLFNAware(szFullPathFileName)) pszPercentToAppend = TEXT(" \"%1\""); else pszPercentToAppend = TEXT(" %1"); } else {//just in case, default to good old behavior. Should not come here because // ActionExeIsValid was done earlier pszPercentToAppend = TEXT(" %1"); } } //append... StringCchCat(_pProgIDAction->szCmdLine, ARRAYSIZE(_pProgIDAction->szCmdLine), pszPercentToAppend); } EndDialog(_hwnd, IDOK); } return FALSE; } LRESULT CFTActionDlg::OnCancel(WORD wNotif) { EndDialog(_hwnd, IDCANCEL); return FALSE; } LRESULT CFTActionDlg::OnUseDDE(WORD wNotif) { _ResizeDlgForDDE(IsDlgButtonChecked(_hwnd, IDC_FT_CMD_USEDDE)); return FALSE; } LRESULT CFTActionDlg::OnBrowse(WORD wNotif) { TCHAR szPath[MAX_PATH]; TCHAR szTitle[40]; TCHAR szEXE[MAX_PATH]; TCHAR szFilters[MAX_PATH]; LPTSTR psz; szPath[0] = 0; EVAL(LoadString(g_hinst, IDS_CAP_OPENAS, szTitle, ARRAYSIZE(szTitle))); EVAL(LoadString(g_hinst, IDS_FT_EXE, szEXE, ARRAYSIZE(szEXE))); // And we need to convert #'s to \0's... EVAL(LoadString(g_hinst, IDS_PROGRAMSFILTER, szFilters, ARRAYSIZE(szFilters))); psz = szFilters; while (*psz) { if (*psz == TEXT('#')) { LPTSTR pszT = psz; psz = CharNext(psz); *pszT = TEXT('\0'); } else psz = CharNext(psz); } if (GetFileNameFromBrowse(_hwnd, szPath, ARRAYSIZE(szPath), NULL, szEXE, szFilters, szTitle)) { PathQuoteSpaces(szPath); SetDlgItemText(_hwnd, IDC_FT_CMD_EXE, szPath); } return FALSE; } void CFTActionDlg::_ResizeDlgForDDE(BOOL fShow) { RECT rcDialog; RECT rcControl; GetWindowRect(_hwnd, &rcDialog); if(fShow) GetWindowRect(GetDlgItem(_hwnd, IDC_FT_CMD_DDEGROUP), &rcControl); else GetWindowRect(GetDlgItem(_hwnd, IDC_FT_CMD_USEDDE), &rcControl); // Hide/Show the windows to take care of the Tabbing. If we don't hide them then // we tab through the "visible" window outside of the dialog. ShowWindow(GetDlgItem(_hwnd, IDC_FT_CMD_DDEMSG), fShow); ShowWindow(GetDlgItem(_hwnd, IDC_FT_CMD_DDEAPP), fShow); ShowWindow(GetDlgItem(_hwnd, IDC_FT_CMD_DDEAPPNOT), fShow); ShowWindow(GetDlgItem(_hwnd, IDC_FT_CMD_DDETOPIC), fShow); ShowWindow(GetDlgItem(_hwnd, IDC_FT_CMD_DDEGROUP), fShow); SetWindowPos(GetDlgItem(_hwnd, IDC_FT_CMD_USEDDE), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_SHOWWINDOW); MoveWindow(_hwnd, rcDialog.left, rcDialog.top, rcDialog.right - rcDialog.left, (rcControl.bottom - rcDialog.top) + 10, TRUE); SetFocus(GetDlgItem(_hwnd, IDC_FT_CMD_USEDDE)); } LRESULT CFTActionDlg::OnDestroy(WPARAM wParam, LPARAM lParam) { CFTDlg::OnDestroy(wParam, lParam); return FALSE; } /////////////////////////////////////////////////////////////////////////////// // Windows boiler plate code LRESULT CFTActionDlg::OnCommand(WPARAM wParam, LPARAM lParam) { LRESULT lRes = FALSE; switch(GET_WM_COMMAND_ID(wParam, lParam)) { case IDC_FT_CMD_USEDDE: // Resize Dialog to see/hide DDE controls lRes = OnUseDDE(GET_WM_COMMAND_CMD(wParam, lParam)); break; case IDC_FT_CMD_BROWSE: lRes = OnBrowse(GET_WM_COMMAND_CMD(wParam, lParam)); break; default: lRes = CFTDlg::OnCommand(wParam, lParam); break; } return lRes; }
32.323864
122
0.604939
sphinxlogic
eb7d97242833f1043f9e24cfe06fc026b99bf264
2,975
cpp
C++
source/Worker.cpp
jacobmcleman/JobBot
1ef82a2f2fbf3321ba3ef4f2a006128bed1388c0
[ "MIT" ]
null
null
null
source/Worker.cpp
jacobmcleman/JobBot
1ef82a2f2fbf3321ba3ef4f2a006128bed1388c0
[ "MIT" ]
null
null
null
source/Worker.cpp
jacobmcleman/JobBot
1ef82a2f2fbf3321ba3ef4f2a006128bed1388c0
[ "MIT" ]
null
null
null
/************************************************************************** Contains implementation for Worker class and its JobQueue subclass, which handle job queues and stealing. Author: Jake McLeman **************************************************************************/ #include <algorithm> #ifdef _DEBUG #include <assert.h> #endif #include "Job.h" #include "JobExceptions.h" #include "Manager.h" #include "Worker.h" namespace JobBot { Worker::Worker(Manager* aManager, Mode aMode, const Specialization& aSpecialization) : manager_(aManager), workerMode_(aMode), workerSpecialization_(aSpecialization), threadID_(std::this_thread::get_id()), keepWorking_(false), isWorking_(false) { } Worker::Specialization Worker::Specialization::None = { {JobType::Huge, JobType::Graphics, JobType::Misc, JobType::IO, JobType::Tiny}}; Worker::Specialization Worker::Specialization::IO = { {JobType::IO, JobType::Huge, JobType::Misc, JobType::Graphics, JobType::Tiny}}; Worker::Specialization Worker::Specialization::Graphics = { {JobType::Graphics, JobType::Tiny, JobType::Misc, JobType::Null, JobType::Null}}; Worker::Specialization Worker::Specialization::RealTime = { {JobType::Tiny, JobType::Misc, JobType::Graphics, JobType::Null, JobType::Null}}; void Worker::WorkWhileWaitingFor(Job* aWaitJob) { bool wasWorking = isWorking_; isWorking_ = true; aWaitJob->SetAllowCompletion(false); while (!aWaitJob->IsFinished()) { DoSingleJob(); } aWaitJob->SetAllowCompletion(true); isWorking_ = wasWorking; } void Worker::WorkWhileWaitingFor(std::atomic_bool& condition) { bool wasWorking = isWorking_; isWorking_ = true; while (!condition) { DoSingleJob(); } isWorking_ = wasWorking; } void Worker::Start() { keepWorking_ = true; DoWork(); } void Worker::Stop() { keepWorking_ = false; while (isWorking_) ; } void Worker::StopAfterCurrentTask() { keepWorking_ = false; } Worker::Mode Worker::GetMode() { return workerMode_; } std::thread::id Worker::GetThreadID() const { return threadID_; } bool Worker::IsWorking() const { return isWorking_; } void Worker::DoWork() { isWorking_ = true; while (keepWorking_) { DoSingleJob(); } isWorking_ = false; } void Worker::DoSingleJob() { static std::mutex waitMutex; Job* job = GetAJob(); #ifdef _DEBUG if (job != nullptr && job->GetUnfinishedJobCount() > 0) #else if (job != nullptr) #endif { job->Run(); } else { // If no job was found by any method, be a good citizen and step aside // so that other processes on CPU can happen if (workerMode_ == Mode::Volunteer) { std::this_thread::yield(); } else { std::unique_lock<std::mutex> uniqueWait(waitMutex); manager_->JobNotifier.wait(uniqueWait); } } } Job* Worker::GetAJob() { return manager_->RequestJob(workerSpecialization_); } }
21.557971
78
0.640672
jacobmcleman
eb84c978c897afc0f16982b1ed521bdb0a014a3a
6,080
cpp
C++
sobol-dpct/sobol.dp.cpp
jchlanda/oneAPI-DirectProgramming
82a1be635f89b4b2a83e36965a60b19fd71e46b2
[ "BSD-3-Clause" ]
null
null
null
sobol-dpct/sobol.dp.cpp
jchlanda/oneAPI-DirectProgramming
82a1be635f89b4b2a83e36965a60b19fd71e46b2
[ "BSD-3-Clause" ]
null
null
null
sobol-dpct/sobol.dp.cpp
jchlanda/oneAPI-DirectProgramming
82a1be635f89b4b2a83e36965a60b19fd71e46b2
[ "BSD-3-Clause" ]
null
null
null
/* * Portions Copyright (c) 1993-2015 NVIDIA Corporation. All rights reserved. * Please refer to the NVIDIA end user license agreement (EULA) associated * with this source code for terms and conditions that govern your use of * this software. Any use, reproduction, disclosure, or distribution of * this software and related documentation outside the terms of the EULA * is strictly prohibited. * * Portions Copyright (c) 2009 Mike Giles, Oxford University. All rights reserved. * Portions Copyright (c) 2008 Frances Y. Kuo and Stephen Joe. All rights reserved. * * Sobol Quasi-random Number Generator example * * Based on CUDA code submitted by Mike Giles, Oxford University, United Kingdom * http://people.maths.ox.ac.uk/~gilesm/ * * and C code developed by Stephen Joe, University of Waikato, New Zealand * and Frances Kuo, University of New South Wales, Australia * http://web.maths.unsw.edu.au/~fkuo/sobol/ * * For theoretical background see: * * P. Bratley and B.L. Fox. * Implementing Sobol's quasirandom sequence generator * http://portal.acm.org/citation.cfm?id=42288 * ACM Trans. on Math. Software, 14(1):88-100, 1988 * * S. Joe and F. Kuo. * Remark on algorithm 659: implementing Sobol's quasirandom sequence generator. * http://portal.acm.org/citation.cfm?id=641879 * ACM Trans. on Math. Software, 29(1):49-57, 2003 */ #include <CL/sycl.hpp> #include <dpct/dpct.hpp> #include <iostream> #include <stdexcept> #include <math.h> #include "sobol.h" #include "sobol_gold.h" #include "sobol_gpu.h" #define L1ERROR_TOLERANCE (1e-6) void printHelp(int argc, char *argv[]) { if (argc > 0) { std::cout << "\nUsage: " << argv[0] << " <options>\n\n"; } else { std::cout << "\nUsage: <program name> <options>\n\n"; } std::cout << "\t--vectors=M specify number of vectors (required)\n"; std::cout << "\t The generator will output M vectors\n\n"; std::cout << "\t--dimensions=N specify number of dimensions (required)\n"; std::cout << "\t Each vector will consist of N components\n\n"; std::cout << std::endl; } int main(int argc, char *argv[]) { dpct::device_ext &dev_ct1 = dpct::get_current_device(); sycl::queue &q_ct1 = dev_ct1.default_queue(); // We will generate n_vectors vectors of n_dimensions numbers int n_vectors = atoi(argv[1]); //100000; int n_dimensions = atoi(argv[2]); //100; // Allocate memory for the arrays std::cout << "Allocating CPU memory..." << std::endl; unsigned int *h_directions = 0; float *h_outputCPU = 0; float *h_outputGPU = 0; try { h_directions = new unsigned int [n_dimensions * n_directions]; h_outputCPU = new float [n_vectors * n_dimensions]; h_outputGPU = new float [n_vectors * n_dimensions]; } catch (std::exception e) { std::cerr << "Caught exception: " << e.what() << std::endl; std::cerr << "Unable to allocate CPU memory (try running with fewer vectors/dimensions)" << std::endl; exit(EXIT_FAILURE); } std::cout << "Allocating GPU memory..." << std::endl; unsigned int *d_directions; float *d_output; d_directions = sycl::malloc_device<unsigned int>(n_dimensions * n_directions, q_ct1); d_output = sycl::malloc_device<float>(n_vectors * n_dimensions, q_ct1); // Initialize the direction numbers (done on the host) std::cout << "Initializing direction numbers..." << std::endl; initSobolDirectionVectors(n_dimensions, h_directions); std::cout << "Executing QRNG on GPU..." << std::endl; q_ct1 .memcpy(d_directions, h_directions, n_dimensions * n_directions * sizeof(unsigned int)) .wait(); dev_ct1.queues_wait_and_throw(); sobolGPU(n_vectors, n_dimensions, d_directions, d_output); q_ct1 .memcpy(h_outputGPU, d_output, n_vectors * n_dimensions * sizeof(float)) .wait(); std::cout << std::endl; // Execute the QRNG on the host std::cout << "Executing QRNG on CPU..." << std::endl; sobolCPU(n_vectors, n_dimensions, h_directions, h_outputCPU); // Check the results std::cout << "Checking results..." << std::endl; float l1norm_diff = 0.0F; float l1norm_ref = 0.0F; float l1error; // Special case if n_vectors is 1, when the vector should be exactly 0 if (n_vectors == 1) { for (int d = 0, v = 0 ; d < n_dimensions ; d++) { float ref = h_outputCPU[d * n_vectors + v]; l1norm_diff += fabs(h_outputGPU[d * n_vectors + v] - ref); l1norm_ref += fabs(ref); } // Output the L1-Error l1error = l1norm_diff; if (l1norm_ref != 0) { std::cerr << "Error: L1-Norm of the reference is not zero (for single vector), golden generator appears broken\n"; } else { std::cout << "L1-Error: " << l1error << std::endl; } } else { for (int d = 0 ; d < n_dimensions ; d++) { for (int v = 0 ; v < n_vectors ; v++) { float ref = h_outputCPU[d * n_vectors + v]; l1norm_diff += fabs(h_outputGPU[d * n_vectors + v] - ref); l1norm_ref += fabs(ref); } } // Output the L1-Error l1error = l1norm_diff / l1norm_ref; if (l1norm_ref == 0) { std::cerr << "Error: L1-Norm of the reference is zero, golden generator appears broken\n"; } else { std::cout << "L1-Error: " << l1error << std::endl; } } // Cleanup and terminate std::cout << "Shutting down..." << std::endl; delete h_directions; delete h_outputCPU; delete h_outputGPU; sycl::free(d_directions, q_ct1); sycl::free(d_output, q_ct1); // Check pass/fail using L1 error if (l1error < L1ERROR_TOLERANCE) std::cout << "PASS" << std::endl; else std::cout << "FAIL" << std::endl; return 0; }
32
126
0.611184
jchlanda
eb88d9cdfe66817f340c9c4668261a9e17b791bb
1,152
cpp
C++
Platinum/2015-16/Open 2016/landscape.cpp
WilliamYue37/USACO
f18b222ff505e2640018288a608dbed6d24ae64a
[ "MIT" ]
null
null
null
Platinum/2015-16/Open 2016/landscape.cpp
WilliamYue37/USACO
f18b222ff505e2640018288a608dbed6d24ae64a
[ "MIT" ]
null
null
null
Platinum/2015-16/Open 2016/landscape.cpp
WilliamYue37/USACO
f18b222ff505e2640018288a608dbed6d24ae64a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define ff first #define ss second typedef long long ll; typedef long double ld; typedef pair<int, int> pi; typedef pair<long long, long long> pl; const int MOD = 1e9 + 7; const ll INF = 1e18; const double EPS = 1e-6; int N; ll X, Y, Z; priority_queue<ll, vector<ll>, greater<ll>> extra, need; int main() { freopen("landscape.in", "r", stdin); freopen("landscape.out", "w", stdout); ios_base::sync_with_stdio(0); cin.tie(0); cin >> N >> X >> Y >> Z; ll ans = 0; for (int i = 0; i < N; ++i) { int A, B; cin >> A >> B; int delta = B - A; if (delta > 0) { for (int j = 0; j < delta; ++j) { ll cost = X; if (!extra.empty() && extra.top() + Z * i < X) { cost = extra.top() + Z * i; extra.pop(); } ans += cost; need.push(-cost - Z * i); } } else { for (int j = 0; j < -delta; ++j) { ll cost = Y; if (!need.empty() && need.top() + Z * i < Y) { cost = need.top() + Z * i; need.pop(); } ans += cost; extra.push(-cost - Z * i); } } } cout << ans << '\n'; return 0; }
20.571429
77
0.497396
WilliamYue37
eb8bcd0a2f8df7ca38e42fd06ac2acd945613e79
984
cpp
C++
examples/code-samples/cpp/23_AddTags.cpp
MarkusRannare/modio-sdk
70220009ac6c375bebd4b807de1e7f8a19680a41
[ "MIT" ]
42
2017-11-14T19:45:20.000Z
2019-02-03T02:43:24.000Z
examples/code-samples/cpp/23_AddTags.cpp
MarkusRannare/modio-sdk
70220009ac6c375bebd4b807de1e7f8a19680a41
[ "MIT" ]
16
2019-05-09T02:14:02.000Z
2020-09-03T05:35:49.000Z
examples/code-samples/cpp/23_AddTags.cpp
MarkusRannare/modio-sdk
70220009ac6c375bebd4b807de1e7f8a19680a41
[ "MIT" ]
15
2019-07-15T04:26:01.000Z
2020-09-12T03:58:19.000Z
#include "modio.h" #include <iostream> int main(void) { modio::Instance modio_instance(MODIO_ENVIRONMENT_TEST, 7, "e91c01b8882f4affeddd56c96111977b"); volatile static bool finished = false; auto wait = [&]() { while (!finished) { modio_instance.sleep(10); modio_instance.process(); } }; auto finish = [&]() { finished = true; }; u32 mod_id; std::cout << "Enter the mod id: " << std::endl; std::cin >> mod_id; std::vector<std::string> tags; tags.push_back("Hard"); // We add tags to a mod by providing the tag names. Remember, they must be valid tags allowed by the parrent game modio_instance.addModTags(mod_id, tags, [&](const modio::Response &response) { std::cout << "Add tags response: " << response.code << std::endl; if (response.code == 201) { std::cout << "Tags added successfully" << std::endl; } finish(); }); wait(); std::cout << "Process finished" << std::endl; return 0; }
21.866667
115
0.619919
MarkusRannare
eb9172f1e3acb18c6c71dec13b45b7688e73e744
4,904
cpp
C++
test/core/FilesystemDeviceCacheTest.cpp
jozhalaj/gateway
49168dcbcf833da690048880bb33542ffbc90ce3
[ "BSD-3-Clause" ]
7
2018-06-09T05:55:59.000Z
2021-01-05T05:19:02.000Z
test/core/FilesystemDeviceCacheTest.cpp
jozhalaj/gateway
49168dcbcf833da690048880bb33542ffbc90ce3
[ "BSD-3-Clause" ]
1
2019-12-25T10:39:06.000Z
2020-01-03T08:35:29.000Z
test/core/FilesystemDeviceCacheTest.cpp
jozhalaj/gateway
49168dcbcf833da690048880bb33542ffbc90ce3
[ "BSD-3-Clause" ]
11
2018-05-10T08:29:05.000Z
2020-01-22T20:49:32.000Z
#include <cppunit/extensions/HelperMacros.h> #include <Poco/File.h> #include "cppunit/BetterAssert.h" #include "cppunit/FileTestFixture.h" #include "core/FilesystemDeviceCache.h" #include "model/DevicePrefix.h" using namespace Poco; namespace BeeeOn { class FilesystemDeviceCacheTest : public FileTestFixture { CPPUNIT_TEST_SUITE(FilesystemDeviceCacheTest); CPPUNIT_TEST(testPairUnpair); CPPUNIT_TEST(testPrepaired); CPPUNIT_TEST(testBatchPair); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void tearDown(); void testPairUnpair(); void testNothingPrepaired(); void testPrepaired(); void testBatchPair(); private: FilesystemDeviceCache m_cache; }; CPPUNIT_TEST_SUITE_REGISTRATION(FilesystemDeviceCacheTest); void FilesystemDeviceCacheTest::setUp() { setUpAsDirectory(); m_cache.setCacheDir(testingPath().toString()); } void FilesystemDeviceCacheTest::tearDown() { // remove all created named mutexes for (const auto &prefix : DevicePrefix::all()) { File mutex("/tmp/" + prefix.toString() + ".mutex"); try { mutex.remove(); } catch (...) {} } } /** * @brief Test we can pair and unpair a device and such device can be * detected as paired. Paired device would always have a corresponding * file created in the filesystem. */ void FilesystemDeviceCacheTest::testPairUnpair() { const DevicePrefix &VDEV = DevicePrefix::PREFIX_VIRTUAL_DEVICE; const Path vdev(testingPath(), "vdev"); CPPUNIT_ASSERT_FILE_NOT_EXISTS(vdev); const Path a300000001020304(testingPath(), "vdev/0xa300000001020304"); CPPUNIT_ASSERT(m_cache.paired(VDEV).empty()); CPPUNIT_ASSERT(!m_cache.paired({0xa300000001020304})); m_cache.markPaired({0xa300000001020304}); CPPUNIT_ASSERT_FILE_EXISTS(vdev); CPPUNIT_ASSERT_FILE_EXISTS(a300000001020304); CPPUNIT_ASSERT_EQUAL(1, m_cache.paired(VDEV).size()); CPPUNIT_ASSERT(m_cache.paired({0xa300000001020304})); m_cache.markUnpaired({0xa300000001020304}); CPPUNIT_ASSERT_FILE_NOT_EXISTS(a300000001020304); CPPUNIT_ASSERT(m_cache.paired(VDEV).empty()); CPPUNIT_ASSERT(!m_cache.paired({0xa300000001020304})); } /** * @brief Test we can pre-pair a set of devices by creating appropriate files * in the filesystem. Only such pre-paired devices are marked as paired. */ void FilesystemDeviceCacheTest::testPrepaired() { const DevicePrefix &VDEV = DevicePrefix::PREFIX_VIRTUAL_DEVICE; const Path vdev(testingPath(), "vdev"); CPPUNIT_ASSERT_FILE_NOT_EXISTS(vdev); CPPUNIT_ASSERT_NO_THROW(File(vdev).createDirectories()); const Path a3000000aaaaaaaa(testingPath(), "vdev/0xa3000000aaaaaaaa"); const Path a3000000bbbbbbbb(testingPath(), "vdev/0xa3000000bbbbbbbb"); CPPUNIT_ASSERT_FILE_NOT_EXISTS(a3000000aaaaaaaa); CPPUNIT_ASSERT_NO_THROW(File(a3000000aaaaaaaa).createFile()); CPPUNIT_ASSERT_FILE_NOT_EXISTS(a3000000bbbbbbbb); CPPUNIT_ASSERT_NO_THROW(File(a3000000bbbbbbbb).createFile()); CPPUNIT_ASSERT_EQUAL(2, m_cache.paired(VDEV).size()); CPPUNIT_ASSERT(m_cache.paired({0xa3000000aaaaaaaa})); CPPUNIT_ASSERT(m_cache.paired({0xa3000000bbbbbbbb})); CPPUNIT_ASSERT(!m_cache.paired({0xa300000001020304})); } /** * @brief Test pairing as a batch process. All already paired devices * should be removed and only the given set is to be paired. The pairing * status is visible when watching the filesystem. */ void FilesystemDeviceCacheTest::testBatchPair() { const DevicePrefix &VDEV = DevicePrefix::PREFIX_VIRTUAL_DEVICE; const Path vdev(testingPath(), "vdev"); CPPUNIT_ASSERT_FILE_NOT_EXISTS(vdev); const Path a3000000aaaaaaaa(testingPath(), "vdev/0xa3000000aaaaaaaa"); const Path a3000000bbbbbbbb(testingPath(), "vdev/0xa3000000bbbbbbbb"); const Path a300000001020304(testingPath(), "vdev/0xa300000001020304"); CPPUNIT_ASSERT(m_cache.paired(VDEV).empty()); m_cache.markPaired(VDEV, {{0xa3000000aaaaaaaa}, {0xa3000000bbbbbbbb}}); CPPUNIT_ASSERT_FILE_EXISTS(a3000000aaaaaaaa); CPPUNIT_ASSERT_FILE_EXISTS(a3000000bbbbbbbb); CPPUNIT_ASSERT_FILE_NOT_EXISTS(a300000001020304); CPPUNIT_ASSERT_EQUAL(2, m_cache.paired(VDEV).size()); CPPUNIT_ASSERT(m_cache.paired({0xa3000000aaaaaaaa})); CPPUNIT_ASSERT(m_cache.paired({0xa3000000bbbbbbbb})); CPPUNIT_ASSERT(!m_cache.paired({0xa300000001020304})); m_cache.markPaired(VDEV, {{0xa300000001020304}}); CPPUNIT_ASSERT_FILE_NOT_EXISTS(a3000000aaaaaaaa); CPPUNIT_ASSERT_FILE_NOT_EXISTS(a3000000bbbbbbbb); CPPUNIT_ASSERT_FILE_EXISTS(a300000001020304); CPPUNIT_ASSERT_EQUAL(1, m_cache.paired(VDEV).size()); CPPUNIT_ASSERT(!m_cache.paired({0xa3000000aaaaaaaa})); CPPUNIT_ASSERT(!m_cache.paired({0xa3000000bbbbbbbb})); CPPUNIT_ASSERT(m_cache.paired({0xa300000001020304})); m_cache.markPaired(VDEV, {}); CPPUNIT_ASSERT(m_cache.paired(VDEV).empty()); CPPUNIT_ASSERT_FILE_NOT_EXISTS(a3000000aaaaaaaa); CPPUNIT_ASSERT_FILE_NOT_EXISTS(a3000000bbbbbbbb); CPPUNIT_ASSERT_FILE_NOT_EXISTS(a300000001020304); CPPUNIT_ASSERT_DIR_EMPTY(vdev); } }
29.365269
77
0.791191
jozhalaj
eb94497f121080b88cab98d76dd3da6be810c9ef
1,059
cpp
C++
TrainingGround/src/assignment-3/main.cpp
elloop/algorithm
5485be0aedbc18968f775cff9533a2d444dbdcb5
[ "MIT" ]
15
2015-11-04T12:53:23.000Z
2021-08-10T09:53:12.000Z
TrainingGround/src/assignment-3/main.cpp
elloop/algorithm
5485be0aedbc18968f775cff9533a2d444dbdcb5
[ "MIT" ]
null
null
null
TrainingGround/src/assignment-3/main.cpp
elloop/algorithm
5485be0aedbc18968f775cff9533a2d444dbdcb5
[ "MIT" ]
6
2015-11-13T10:17:01.000Z
2020-05-14T07:25:48.000Z
#include "common.h" #include "LoadVehicle.h" #include "PassengerVehicle.h" #include "EmergencyEquipment.h" #include "EmergecyVehicle.h" #include "Decision.h" #include <list> using namespace std; // temparorily commented. /* int main() { // the vehicle list. Decision::VehicleList vehicleList; // create Vehicles. LoadVehicle * lv1 = new LoadVehicle ( "load1" ); vehicleList.push_back ( lv1 ); PassengerVehicle * pv1 = new PassengerVehicle ( "passenger1" ); vehicleList.push_back ( pv1 ); EmergecyVehicle * ev1 = new EmergecyVehicle ( "emergency1", "super", "buaa", 101 ); vehicleList.push_back ( ev1 ); // create Decison object. Decision decision ( vehicleList ); pc ("part 1"); decision.printVehiclesSpecifications(); cr; pc ("part 2"); decision.printEmergencyVehicles(); cr; pc ("part 3"); ps ( decision.numberLongDistanceEmergencyVehicles() ); cr; pc ("part 4"); ps ( decision.numBeds() ); cr; pc ("part 5"); ps ( decision.numPassengers() ); cr; // clear... delete lv1; delete pv1; delete ev1; return 0; } */
17.949153
84
0.68272
elloop
eb95266a0948bc9eeb811342cf7b0c16d3cba086
2,965
cpp
C++
src/blitzide2/FileView.cpp
blitz3d-ng/blitz3d-ng
adc829fb76e2c63612b50c725c0944b2b6b0ddaf
[ "Zlib" ]
53
2017-08-10T10:52:34.000Z
2021-12-09T18:03:30.000Z
src/blitzide2/FileView.cpp
kfprimm/blitz3d
adc829fb76e2c63612b50c725c0944b2b6b0ddaf
[ "Zlib" ]
21
2017-05-03T20:28:28.000Z
2022-03-25T12:11:00.000Z
src/blitzide2/FileView.cpp
kfprimm/blitz3d
adc829fb76e2c63612b50c725c0944b2b6b0ddaf
[ "Zlib" ]
8
2017-04-23T02:09:24.000Z
2022-02-01T21:17:27.000Z
#include "FileView.h" #include <wx/stc/stc.h> #include <wx/textfile.h> enum { MARGIN_LINE_NUMBERS }; static wxString keywordsList; static bool keywordsLoaded=false; // rgb_bkgrnd=RGB( 0x22,0x55,0x88 ); // rgb_string=RGB( 0x00,0xff,0x66 ); // rgb_ident=RGB( 0xff,0xff,0xff ); // rgb_keyword=RGB( 0xaa,0xff,0xff ); // rgb_comment=RGB( 0xff,0xee,0x00 ); // rgb_digit=RGB( 0x33,0xff,0xdd ); // rgb_default=RGB( 0xee,0xee,0xee ); extern wxString blitzpath; void FileView::LoadKeywords(){ if (!keywordsLoaded) { wxArrayString keywords; wxExecute( blitzpath + "/bin/blitzcc -k",keywords ); keywordsList = ""; wxArrayString::iterator it; for( it=keywords.begin();it<keywords.end();it++ ){ keywordsList << " " << (*it).Lower(); } keywordsLoaded = true; } } FileView::FileView( wxString &path,wxWindow *parent,wxWindowID id ):path(path),wxPanel( parent,id ){ LoadKeywords(); // Inconsolata, Monaco, Consolas, 'Courier New', Courier wxFont font; #ifdef __WXMSW__ font = wxFontInfo(12).FaceName("Consolas"); #else font = wxFontInfo(12).FaceName("Monaco"); #endif wxStyledTextCtrl* text = new wxStyledTextCtrl(this, wxID_ANY); if ( path.length()>0 ){ wxTextFile file; file.Open( path ); source.Clear(); while( !file.Eof() ) { source.Append( file.GetNextLine() ); source.Append( "\n" ); } file.Close(); text->SetText( source ); } text->StyleSetBackground( wxSTC_STYLE_DEFAULT, wxColour( 0x22,0x55,0x88 ) ); text->StyleSetForeground( wxSTC_STYLE_DEFAULT, wxColour( 0xee,0xee,0xee ) ); // text->StyleClearAll(); text->SetMarginWidth (MARGIN_LINE_NUMBERS, 25); text->SetCaretForeground( wxColour( 0xff,0xff,0xff ) ); text->SetCaretLineBackground( wxColour( 0x1e,0x4a,0x76 ) ); text->SetCaretLineVisible( true ); text->SetMarginType(MARGIN_LINE_NUMBERS, wxSTC_MARGIN_NUMBER); text->SetLexer(wxSTC_LEX_BLITZBASIC); text->StyleSetFont( wxSTC_STYLE_DEFAULT,font ); text->StyleSetForeground( wxSTC_STYLE_LINENUMBER, wxColour (0xee,0xee,0xee) ); text->StyleSetBackground( wxSTC_STYLE_LINENUMBER, wxColour (0x1e,0x4a,0x76) ); text->StyleSetBackground( wxSTC_B_DEFAULT, wxColour( 0x22,0x55,0x88 ) ); text->StyleSetForeground( wxSTC_B_DEFAULT, wxColour( 0xee,0xee,0xee ) ); text->StyleSetBackground( wxSTC_B_STRING, wxColour( 0x22,0x55,0x88 ) ); text->StyleSetForeground( wxSTC_B_STRING, wxColour( 0x00,0xff,0x66 ) ); text->StyleSetForeground( wxSTC_B_COMMENT, wxColour( 0xff,0xee,0x00 ) ); text->StyleSetForeground( wxSTC_B_KEYWORD, wxColour( 0xaa,0xff,0xff ) ); text->StyleSetForeground( wxSTC_B_NUMBER, wxColour( 0x33,0xff,0xdd ) ); text->SetKeyWords(0, keywordsList); wxBoxSizer *sizer = new wxBoxSizer( wxVERTICAL ); sizer->Add( text,1,wxEXPAND,0 ); SetSizer( sizer ); } bool FileView::Save(){ wxTextFile file( path ); file.Open(); file.AddLine( source ); file.Write(); file.Close(); return true; }
25.782609
100
0.696796
blitz3d-ng
eb978dad3af8589d102fe466e1899304c74afb4e
2,754
hpp
C++
pythran/pythonic/numpy/transpose.hpp
Pikalchemist/Pythran
17d4108b56b3b365e089a4e1b01a09eb7e12942b
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/transpose.hpp
Pikalchemist/Pythran
17d4108b56b3b365e089a4e1b01a09eb7e12942b
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/transpose.hpp
Pikalchemist/Pythran
17d4108b56b3b365e089a4e1b01a09eb7e12942b
[ "BSD-3-Clause" ]
1
2017-03-12T20:32:36.000Z
2017-03-12T20:32:36.000Z
#ifndef PYTHONIC_NUMPY_TRANSPOSE_HPP #define PYTHONIC_NUMPY_TRANSPOSE_HPP #include "pythonic/utils/proxy.hpp" #include "pythonic/utils/numpy_conversion.hpp" #include "pythonic/utils/nested_container.hpp" #include "pythonic/types/ndarray.hpp" #include "pythonic/types/numpy_type.hpp" #include "pythonic/__builtin__/ValueError.hpp" namespace pythonic { namespace numpy { template<class T> types::numpy_texpr<types::ndarray<T, 2>> transpose(types::ndarray<T, 2> const& arr) { return types::numpy_texpr<types::ndarray<T, 2>>(arr); } template<class T, unsigned long N, class... C> types::ndarray<T,N> _transpose(types::ndarray<T,N> const & a, long const l[N]) { auto shape = a.shape; types::array<long, N> shp; for(unsigned long i=0; i<N; ++i) shp[i] = shape[l[i]]; types::ndarray<T,N> new_array(shp, __builtin__::None); types::array<long, N> new_strides; new_strides[N-1] = 1; std::transform(new_strides.rbegin(), new_strides.rend() -1, shp.rbegin(), new_strides.rbegin() + 1, std::multiplies<long>()); types::array<long, N> old_strides; old_strides[N-1] = 1; std::transform(old_strides.rbegin(), old_strides.rend() -1, shape.rbegin(), old_strides.rbegin() + 1, std::multiplies<long>()); auto iter = a.buffer, iter_end = a.buffer + a.flat_size(); for(long i=0; iter!=iter_end; ++iter, ++i) { long offset = 0; for(unsigned long s=0; s<N; s++) offset += ((i/old_strides[l[s]]) % shape[l[s]])*new_strides[s]; new_array.buffer[offset] = *iter; } return new_array; } template<class T, size_t N> types::ndarray<T,N> transpose(types::ndarray<T,N> const & a) { long t[N]; for(unsigned long i = 0; i<N; ++i) t[N-1-i] = i; return _transpose(a, t); } template<class T, size_t N, size_t M> types::ndarray<T,N> transpose(types::ndarray<T,N> const & a, types::array<long, M> const& t) { static_assert(N==M, "axes don't match array"); long val = t[M-1]; if(val>=long(N)) throw types::ValueError("invalid axis for this array"); return _transpose(a, &t[0]); } NUMPY_EXPR_TO_NDARRAY0(transpose); PROXY(pythonic::numpy, transpose); } } #endif
34.860759
143
0.520334
Pikalchemist
eba233191f70e61054b58edd9042d737ac537d7c
9,636
hpp
C++
lib/include/efyj/matrix.hpp
quesnel/efyj
5f214449e26000fb30f3a037cac52269704fe703
[ "MIT" ]
1
2021-05-04T16:06:55.000Z
2021-05-04T16:06:55.000Z
lib/include/efyj/matrix.hpp
quesnel/efyj
5f214449e26000fb30f3a037cac52269704fe703
[ "MIT" ]
null
null
null
lib/include/efyj/matrix.hpp
quesnel/efyj
5f214449e26000fb30f3a037cac52269704fe703
[ "MIT" ]
null
null
null
/* Copyright (C) 2016-2017 INRA * * 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. */ #ifndef ORG_VLEPROJECT_EFYJ_MATRIX_HPP #define ORG_VLEPROJECT_EFYJ_MATRIX_HPP #include <algorithm> #include <initializer_list> #include <vector> #include <cassert> namespace efyj { /** * An \e matrix defined a two-dimensional template array. Informations are * stored into a \e std::vector<T> by default. * * \tparam T Type of element * \tparam Containre Type of container to store two-dimensional array. */ template<typename T, class Container = std::vector<T>> class matrix { public: using container_type = Container; using value_type = T; using reference = typename container_type::reference; using const_reference = typename container_type::const_reference; using iterator = typename container_type::iterator; using const_iterator = typename container_type::const_iterator; using reverse_iterator = typename container_type::reverse_iterator; using const_reverse_iterator = typename container_type::const_reverse_iterator; using size_type = typename container_type::size_type; protected: container_type m_c; size_type m_rows, m_columns; public: matrix(); explicit matrix(size_type rows, size_type cols); explicit matrix(size_type rows, size_type cols, const value_type& value); ~matrix() = default; matrix(const matrix& q) = default; matrix(matrix&& q) = default; matrix& operator=(const matrix& q) = default; matrix& operator=(matrix&& q) = default; void assign(std::initializer_list<value_type> list); void resize(size_type rows, size_type cols); void resize(size_type rows, size_type cols, const value_type& value); iterator begin() noexcept; const_iterator begin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; reverse_iterator rbegin() noexcept; const_reverse_iterator rbegin() const noexcept; reverse_iterator rend() noexcept; const_reverse_iterator rend() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; const_reverse_iterator crbegin() const noexcept; const_reverse_iterator crend() const noexcept; bool empty() const noexcept; size_type size() const noexcept; size_type rows() const noexcept; size_type columns() const noexcept; void set(size_type row, size_type col, const value_type& x); void set(size_type row, size_type col, value_type&& x); template<class... Args> void emplace(size_type row, size_type col, Args&&... args); const_reference operator()(size_type row, size_type col) const; reference operator()(size_type row, size_type col); void swap(matrix& c) noexcept(noexcept(m_c.swap(c.m_c))); void clear() noexcept; private: void m_check_index(size_type row, size_type col) const; }; template<typename T, class Container> matrix<T, Container>::matrix() : m_c() , m_rows(0) , m_columns(0) {} template<typename T, class Container> matrix<T, Container>::matrix(size_type rows, size_type columns) : m_c(rows * columns) , m_rows(rows) , m_columns(columns) {} template<typename T, class Container> matrix<T, Container>::matrix(size_type rows, size_type columns, const value_type& value) : m_c(rows * columns, value) , m_rows(rows) , m_columns(columns) {} template<typename T, class Container> void matrix<T, Container>::assign(std::initializer_list<value_type> list) { m_c.assign(list.begin(), list.end()); } template<typename T, class Container> void matrix<T, Container>::resize(size_type rows, size_type cols) { container_type new_c(rows * cols); size_type rmin = std::min(rows, m_rows); size_type cmin = std::min(cols, m_columns); for (size_type r = 0; r != rmin; ++r) for (size_type c = 0; c != cmin; ++c) new_c[r * cols + c] = m_c[r * m_columns + c]; m_columns = cols; m_rows = rows; std::swap(new_c, m_c); } template<typename T, class Container> void matrix<T, Container>::resize(size_type rows, size_type cols, const value_type& value) { m_c.resize(rows * cols); m_rows = rows; m_columns = cols; std::fill(m_c.begin(), m_c.end(), value); } template<typename T, class Container> typename matrix<T, Container>::iterator matrix<T, Container>::begin() noexcept { return m_c.begin(); } template<typename T, class Container> typename matrix<T, Container>::const_iterator matrix<T, Container>::begin() const noexcept { return m_c.begin(); } template<typename T, class Container> typename matrix<T, Container>::iterator matrix<T, Container>::end() noexcept { return m_c.end(); } template<typename T, class Container> typename matrix<T, Container>::const_iterator matrix<T, Container>::end() const noexcept { return m_c.end(); } template<typename T, class Container> typename matrix<T, Container>::reverse_iterator matrix<T, Container>::rbegin() noexcept { return m_c.rbegin(); } template<typename T, class Container> typename matrix<T, Container>::const_reverse_iterator matrix<T, Container>::rbegin() const noexcept { return m_c.rbegin(); } template<typename T, class Container> typename matrix<T, Container>::reverse_iterator matrix<T, Container>::rend() noexcept { return m_c.rend(); } template<typename T, class Container> typename matrix<T, Container>::const_reverse_iterator matrix<T, Container>::rend() const noexcept { return m_c.rend(); } template<typename T, class Container> typename matrix<T, Container>::const_iterator matrix<T, Container>::cbegin() const noexcept { return m_c.cbegin(); } template<typename T, class Container> typename matrix<T, Container>::const_iterator matrix<T, Container>::cend() const noexcept { return m_c.cend(); } template<typename T, class Container> typename matrix<T, Container>::const_reverse_iterator matrix<T, Container>::crbegin() const noexcept { return m_c.crbegin(); } template<typename T, class Container> typename matrix<T, Container>::const_reverse_iterator matrix<T, Container>::crend() const noexcept { return m_c.crend(); } template<typename T, class Container> bool matrix<T, Container>::empty() const noexcept { return m_c.empty(); } template<typename T, class Container> typename matrix<T, Container>::size_type matrix<T, Container>::size() const noexcept { return m_c.size(); } template<typename T, class Container> typename matrix<T, Container>::size_type matrix<T, Container>::rows() const noexcept { return m_rows; } template<typename T, class Container> typename matrix<T, Container>::size_type matrix<T, Container>::columns() const noexcept { return m_columns; } template<typename T, class Container> void matrix<T, Container>::set(size_type row, size_type column, const value_type& x) { m_check_index(row, column); m_c[row * m_columns + column] = x; } template<typename T, class Container> void matrix<T, Container>::set(size_type row, size_type column, value_type&& x) { m_check_index(row, column); m_c.emplace(m_c.begin() + (row * m_columns + column), std::move(x)); } template<typename T, class Container> template<class... Args> void matrix<T, Container>::emplace(size_type row, size_type column, Args&&... args) { m_check_index(row, column); m_c.emplace(m_c.begin() + (row * m_columns + column), std::forward<Args>(args)...); } template<typename T, class Container> typename matrix<T, Container>::const_reference matrix<T, Container>::operator()(size_type row, size_type column) const { m_check_index(row, column); return m_c[row * m_columns + column]; } template<typename T, class Container> typename matrix<T, Container>::reference matrix<T, Container>::operator()(size_type row, size_type column) { m_check_index(row, column); return m_c[row * m_columns + column]; } template<typename T, class Container> void matrix<T, Container>::swap(matrix& c) noexcept(noexcept(m_c.swap(c.m_c))) { std::swap(m_c, c.m_c); std::swap(m_columns, c.m_columns); std::swap(m_rows, c.m_rows); } template<typename T, class Container> void matrix<T, Container>::clear() noexcept { m_c.clear(); m_rows = 0; m_columns = 0; } template<typename T, class Container> void matrix<T, Container>::m_check_index([[maybe_unused]] size_type row, [[maybe_unused]] size_type column) const { assert(column < m_columns || row < m_rows); } } #endif
26.766667
79
0.709734
quesnel
eba3edf7b9de7a2dad2aa25bddbc1f57d1ebfca3
10,787
cpp
C++
lonestar/gmetis/GMetis.cpp
bowu/Galois
81f619a2bb1bdc95899729f2d96a7da38dd0c0a3
[ "BSD-3-Clause" ]
null
null
null
lonestar/gmetis/GMetis.cpp
bowu/Galois
81f619a2bb1bdc95899729f2d96a7da38dd0c0a3
[ "BSD-3-Clause" ]
null
null
null
lonestar/gmetis/GMetis.cpp
bowu/Galois
81f619a2bb1bdc95899729f2d96a7da38dd0c0a3
[ "BSD-3-Clause" ]
null
null
null
/* * This file belongs to the Galois project, a C++ library for exploiting parallelism. * The code is being released under the terms of the 3-Clause BSD License (a * copy is located in LICENSE.txt at the top-level directory). * * Copyright (C) 2018, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. */ #include <vector> #include <set> #include <map> #include <iostream> #include <string.h> #include <stdlib.h> #include <numeric> #include <algorithm> #include <cmath> #include <fstream> #include "Metis.h" #include "galois/graphs/ReadGraph.h" #include "galois/Timer.h" //#include "GraphReader.h" #include "Lonestar/BoilerPlate.h" #include "galois/graphs/FileGraph.h" #include "galois/LargeArray.h" namespace cll = llvm::cl; static const char* name = "GMetis"; static const char* desc = "Partitions a graph into K parts and minimizing the graph cut"; static const char* url = "gMetis"; static cll::opt<InitialPartMode> partMode( cll::desc("Choose a inital part mode:"), cll::values(clEnumVal(GGP, "GGP"), clEnumVal(GGGP, "GGGP (default)"), clEnumVal(MGGGP, "MGGGP")), cll::init(GGGP)); static cll::opt<refinementMode> refineMode( cll::desc("Choose a refinement mode:"), cll::values(clEnumVal(BKL, "BKL"), clEnumVal(BKL2, "BKL2 (default)"), clEnumVal(ROBO, "ROBO"), clEnumVal(GRACLUS, "GRACLUS") ), cll::init(BKL2)); static cll::opt<bool> mtxInput("mtxinput", cll::desc("Use text mtx files instead of binary galois gr files"), cll::init(false)); static cll::opt<bool> weighted("weighted", cll::desc("weighted"), cll::init(false)); static cll::opt<bool> verbose("verbose", cll::desc("verbose output (debugging mode, takes extra time)"), cll::init(false)); static cll::opt<std::string> outfile("output", cll::desc("output partition file name")); static cll::opt<std::string> orderedfile("ordered", cll::desc("output ordered graph file name")); static cll::opt<std::string> permutationfile("permutation", cll::desc("output permutation file name")); static cll::opt<std::string> filename(cll::Positional, cll::desc("<input file>"), cll::Required); static cll::opt<int> numPartitions(cll::Positional, cll::desc("<Number of partitions>"), cll::Required); static cll::opt<double> imbalance( "balance", cll::desc("Fraction deviated from mean partition size (default 0.01)"), cll::init(0.01)); // const double COARSEN_FRACTION = 0.9; /** * KMetis Algorithm */ void Partition(MetisGraph* metisGraph, unsigned nparts) { galois::StatTimer TM; TM.start(); unsigned fineMetisGraphWeight = metisGraph->getTotalWeight(); unsigned meanWeight = ((double)fineMetisGraphWeight) / (double)nparts; // unsigned coarsenTo = std::max(metisGraph->getNumNodes() / (40 * // intlog2(nparts)), 20 * (nparts)); unsigned coarsenTo = 20 * nparts; if (verbose) std::cout << "Starting coarsening: \n"; galois::StatTimer T("Coarsen"); T.start(); MetisGraph* mcg = coarsen(metisGraph, coarsenTo, verbose); T.stop(); if (verbose) std::cout << "Time coarsen: " << T.get() << "\n"; galois::StatTimer T2("Partition"); T2.start(); std::vector<partInfo> parts; parts = partition(mcg, fineMetisGraphWeight, nparts, partMode); T2.stop(); if (verbose) std::cout << "Init edge cut : " << computeCut(*mcg->getGraph()) << "\n\n"; std::vector<partInfo> initParts = parts; if (verbose) std::cout << "Time clustering: " << T2.get() << '\n'; if (verbose) { switch (refineMode) { case BKL2: std::cout << "Sorting refinnement with BKL2\n"; break; case BKL: std::cout << "Sorting refinnement with BKL\n"; break; case ROBO: std::cout << "Sorting refinnement with ROBO\n"; break; case GRACLUS: std::cout << "Sorting refinnement with GRACLUS\n"; break; default: abort(); } } galois::StatTimer T3("Refine"); T3.start(); refine(mcg, parts, meanWeight - (unsigned)(meanWeight * imbalance), meanWeight + (unsigned)(meanWeight * imbalance), refineMode, verbose); T3.stop(); if (verbose) std::cout << "Time refinement: " << T3.get() << "\n"; TM.stop(); std::cout << "Initial dist\n"; printPartStats(initParts); std::cout << "\n"; std::cout << "Refined dist\n"; printPartStats(parts); std::cout << "\n"; std::cout << "Time: " << TM.get() << '\n'; return; } // printGraphBeg(*graph) typedef galois::graphs::FileGraph FG; typedef FG::GraphNode FN; template <typename GNode, typename Weights> struct order_by_degree { GGraph& graph; Weights& weights; order_by_degree(GGraph& g, Weights& w) : graph(g), weights(w) {} bool operator()(const GNode& a, const GNode& b) { uint64_t wa = weights[a]; uint64_t wb = weights[b]; int pa = graph.getData(a, galois::MethodFlag::UNPROTECTED).getPart(); int pb = graph.getData(b, galois::MethodFlag::UNPROTECTED).getPart(); if (pa != pb) { return pa < pb; } return wa < wb; } }; typedef galois::substrate::PerThreadStorage<std::map<GNode, uint64_t>> PerThreadDegInfo; int main(int argc, char** argv) { galois::SharedMemSys G; LonestarStart(argc, argv, name, desc, url); srand(-1); MetisGraph metisGraph; GGraph& graph = *metisGraph.getGraph(); galois::graphs::readGraph(graph, filename); galois::do_all(galois::iterate(graph), [&](GNode node) { for (auto jj : graph.edges(node)) { graph.getEdgeData(jj) = 1; // weight+=1; } }, galois::loopname("initMorphGraph")); graphStat(graph); std::cout << "\n"; galois::preAlloc(galois::runtime::numPagePoolAllocTotal() * 5); galois::reportPageAlloc("MeminfoPre"); Partition(&metisGraph, numPartitions); galois::reportPageAlloc("MeminfoPost"); std::cout << "Total edge cut: " << computeCut(graph) << "\n"; if (outfile != "") { MetisGraph* coarseGraph = &metisGraph; while (coarseGraph->getCoarserGraph()) coarseGraph = coarseGraph->getCoarserGraph(); std::ofstream outFile(outfile.c_str()); for (auto it = graph.begin(), ie = graph.end(); it != ie; it++) { unsigned gPart = graph.getData(*it).getPart(); outFile << gPart << '\n'; } } if (orderedfile != "" || permutationfile != "") { galois::graphs::FileGraph g; g.fromFile(filename); typedef galois::LargeArray<GNode> Permutation; Permutation perm; perm.create(g.size()); std::copy(graph.begin(), graph.end(), perm.begin()); PerThreadDegInfo threadDegInfo; std::vector<int> parts(numPartitions); for (unsigned int i = 0; i < parts.size(); i++) { parts[i] = i; } using WL = galois::worklists::PerSocketChunkFIFO<16>; galois::for_each( galois::iterate(parts), [&](int part, auto& lwl) { constexpr auto flag = galois::MethodFlag::UNPROTECTED; typedef std::vector< std::pair<unsigned, GNode>, galois::PerIterAllocTy::rebind<std::pair<unsigned, GNode>>::other> GD; // copy and translate all edges GD orderedNodes(GD::allocator_type(lwl.getPerIterAlloc())); for (auto n : graph) { auto& nd = graph.getData(n, flag); if (static_cast<int>(nd.getPart()) == part) { int edges = std::distance(graph.edge_begin(n, flag), graph.edge_end(n, flag)); orderedNodes.push_back(std::make_pair(edges, n)); } } std::sort(orderedNodes.begin(), orderedNodes.end()); int index = 0; std::map<GNode, uint64_t>& threadMap(*threadDegInfo.getLocal()); for (auto p : orderedNodes) { GNode n = p.second; threadMap[n] += index; for (auto eb : graph.edges(n, flag)) { GNode neigh = graph.getEdgeDst(eb); auto& nd = graph.getData(neigh, flag); if (static_cast<int>(nd.getPart()) == part) { threadMap[neigh] += index; } } index++; } }, galois::wl<WL>(), galois::per_iter_alloc(), galois::loopname("Order Graph")); std::map<GNode, uint64_t> globalMap; for (unsigned int i = 0; i < threadDegInfo.size(); i++) { std::map<GNode, uint64_t>& localMap(*threadDegInfo.getRemote(i)); for (auto mb = localMap.begin(), me = localMap.end(); mb != me; mb++) { globalMap[mb->first] = mb->second; } } order_by_degree<GNode, std::map<GNode, uint64_t>> fn(graph, globalMap); std::map<GNode, int> nodeIdMap; int id = 0; for (auto nb = graph.begin(), ne = graph.end(); nb != ne; nb++) { nodeIdMap[*nb] = id; id++; } // compute inverse std::stable_sort(perm.begin(), perm.end(), fn); galois::LargeArray<uint64_t> perm2; perm2.create(g.size()); // compute permutation id = 0; for (auto pb = perm.begin(), pe = perm.end(); pb != pe; pb++) { int prevId = nodeIdMap[*pb]; perm2[prevId] = id; // std::cout<<prevId <<" "<<id<<std::endl; id++; } galois::graphs::FileGraph out; galois::graphs::permute<int>(g, perm2, out); if (orderedfile != "") out.toFile(orderedfile); if (permutationfile != "") { std::ofstream file(permutationfile.c_str()); galois::LargeArray<uint64_t> transpose; transpose.create(g.size()); uint64_t id = 0; for (auto& ii : perm2) { transpose[ii] = id++; } for (auto& ii : transpose) { file << ii << "\n"; } } } return 0; }
33.5
85
0.605266
bowu
eba72406c8bd972322ff51424249df7f49ea68b4
388
hpp
C++
parpm/grid.hpp
shigh/parpm
45d09bfa3103244fd8559dc32bc7c3ad5f83f614
[ "MIT" ]
null
null
null
parpm/grid.hpp
shigh/parpm
45d09bfa3103244fd8559dc32bc7c3ad5f83f614
[ "MIT" ]
null
null
null
parpm/grid.hpp
shigh/parpm
45d09bfa3103244fd8559dc32bc7c3ad5f83f614
[ "MIT" ]
null
null
null
#pragma once #include "types.hpp" struct Grid { // Number of grid points int Nx; int Ny; int Nz; // Starting grid points int Nx0; int Ny0; int Nz0; // Length of domain in this grid // Domain in this grid is [L0,L0+L] FLOAT Lx; FLOAT Ly; FLOAT Lz; FLOAT Lx0; FLOAT Ly0; FLOAT Lz0; // MPI info int rank; int size; int[3][3][3] neighbors; };
11.411765
37
0.597938
shigh
eba7f09abce753624cea5622578aac1653fa435a
28,858
cpp
C++
es/src/v20180416/EsClient.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
es/src/v20180416/EsClient.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
es/src/v20180416/EsClient.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/es/v20180416/EsClient.h> #include <tencentcloud/core/Executor.h> #include <tencentcloud/core/Runnable.h> using namespace TencentCloud; using namespace TencentCloud::Es::V20180416; using namespace TencentCloud::Es::V20180416::Model; using namespace std; namespace { const string VERSION = "2018-04-16"; const string ENDPOINT = "es.tencentcloudapi.com"; } EsClient::EsClient(const Credential &credential, const string &region) : EsClient(credential, region, ClientProfile()) { } EsClient::EsClient(const Credential &credential, const string &region, const ClientProfile &profile) : AbstractClient(ENDPOINT, VERSION, credential, region, profile) { } EsClient::CreateInstanceOutcome EsClient::CreateInstance(const CreateInstanceRequest &request) { auto outcome = MakeRequest(request, "CreateInstance"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); CreateInstanceResponse rsp = CreateInstanceResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return CreateInstanceOutcome(rsp); else return CreateInstanceOutcome(o.GetError()); } else { return CreateInstanceOutcome(outcome.GetError()); } } void EsClient::CreateInstanceAsync(const CreateInstanceRequest& request, const CreateInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->CreateInstance(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::CreateInstanceOutcomeCallable EsClient::CreateInstanceCallable(const CreateInstanceRequest &request) { auto task = std::make_shared<std::packaged_task<CreateInstanceOutcome()>>( [this, request]() { return this->CreateInstance(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::DeleteInstanceOutcome EsClient::DeleteInstance(const DeleteInstanceRequest &request) { auto outcome = MakeRequest(request, "DeleteInstance"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DeleteInstanceResponse rsp = DeleteInstanceResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DeleteInstanceOutcome(rsp); else return DeleteInstanceOutcome(o.GetError()); } else { return DeleteInstanceOutcome(outcome.GetError()); } } void EsClient::DeleteInstanceAsync(const DeleteInstanceRequest& request, const DeleteInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DeleteInstance(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::DeleteInstanceOutcomeCallable EsClient::DeleteInstanceCallable(const DeleteInstanceRequest &request) { auto task = std::make_shared<std::packaged_task<DeleteInstanceOutcome()>>( [this, request]() { return this->DeleteInstance(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::DescribeInstanceLogsOutcome EsClient::DescribeInstanceLogs(const DescribeInstanceLogsRequest &request) { auto outcome = MakeRequest(request, "DescribeInstanceLogs"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeInstanceLogsResponse rsp = DescribeInstanceLogsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeInstanceLogsOutcome(rsp); else return DescribeInstanceLogsOutcome(o.GetError()); } else { return DescribeInstanceLogsOutcome(outcome.GetError()); } } void EsClient::DescribeInstanceLogsAsync(const DescribeInstanceLogsRequest& request, const DescribeInstanceLogsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeInstanceLogs(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::DescribeInstanceLogsOutcomeCallable EsClient::DescribeInstanceLogsCallable(const DescribeInstanceLogsRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeInstanceLogsOutcome()>>( [this, request]() { return this->DescribeInstanceLogs(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::DescribeInstanceOperationsOutcome EsClient::DescribeInstanceOperations(const DescribeInstanceOperationsRequest &request) { auto outcome = MakeRequest(request, "DescribeInstanceOperations"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeInstanceOperationsResponse rsp = DescribeInstanceOperationsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeInstanceOperationsOutcome(rsp); else return DescribeInstanceOperationsOutcome(o.GetError()); } else { return DescribeInstanceOperationsOutcome(outcome.GetError()); } } void EsClient::DescribeInstanceOperationsAsync(const DescribeInstanceOperationsRequest& request, const DescribeInstanceOperationsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeInstanceOperations(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::DescribeInstanceOperationsOutcomeCallable EsClient::DescribeInstanceOperationsCallable(const DescribeInstanceOperationsRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeInstanceOperationsOutcome()>>( [this, request]() { return this->DescribeInstanceOperations(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::DescribeInstancesOutcome EsClient::DescribeInstances(const DescribeInstancesRequest &request) { auto outcome = MakeRequest(request, "DescribeInstances"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeInstancesResponse rsp = DescribeInstancesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeInstancesOutcome(rsp); else return DescribeInstancesOutcome(o.GetError()); } else { return DescribeInstancesOutcome(outcome.GetError()); } } void EsClient::DescribeInstancesAsync(const DescribeInstancesRequest& request, const DescribeInstancesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeInstances(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::DescribeInstancesOutcomeCallable EsClient::DescribeInstancesCallable(const DescribeInstancesRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeInstancesOutcome()>>( [this, request]() { return this->DescribeInstances(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::DescribeViewsOutcome EsClient::DescribeViews(const DescribeViewsRequest &request) { auto outcome = MakeRequest(request, "DescribeViews"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeViewsResponse rsp = DescribeViewsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeViewsOutcome(rsp); else return DescribeViewsOutcome(o.GetError()); } else { return DescribeViewsOutcome(outcome.GetError()); } } void EsClient::DescribeViewsAsync(const DescribeViewsRequest& request, const DescribeViewsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeViews(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::DescribeViewsOutcomeCallable EsClient::DescribeViewsCallable(const DescribeViewsRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeViewsOutcome()>>( [this, request]() { return this->DescribeViews(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::DiagnoseInstanceOutcome EsClient::DiagnoseInstance(const DiagnoseInstanceRequest &request) { auto outcome = MakeRequest(request, "DiagnoseInstance"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DiagnoseInstanceResponse rsp = DiagnoseInstanceResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DiagnoseInstanceOutcome(rsp); else return DiagnoseInstanceOutcome(o.GetError()); } else { return DiagnoseInstanceOutcome(outcome.GetError()); } } void EsClient::DiagnoseInstanceAsync(const DiagnoseInstanceRequest& request, const DiagnoseInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DiagnoseInstance(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::DiagnoseInstanceOutcomeCallable EsClient::DiagnoseInstanceCallable(const DiagnoseInstanceRequest &request) { auto task = std::make_shared<std::packaged_task<DiagnoseInstanceOutcome()>>( [this, request]() { return this->DiagnoseInstance(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::GetRequestTargetNodeTypesOutcome EsClient::GetRequestTargetNodeTypes(const GetRequestTargetNodeTypesRequest &request) { auto outcome = MakeRequest(request, "GetRequestTargetNodeTypes"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); GetRequestTargetNodeTypesResponse rsp = GetRequestTargetNodeTypesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return GetRequestTargetNodeTypesOutcome(rsp); else return GetRequestTargetNodeTypesOutcome(o.GetError()); } else { return GetRequestTargetNodeTypesOutcome(outcome.GetError()); } } void EsClient::GetRequestTargetNodeTypesAsync(const GetRequestTargetNodeTypesRequest& request, const GetRequestTargetNodeTypesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->GetRequestTargetNodeTypes(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::GetRequestTargetNodeTypesOutcomeCallable EsClient::GetRequestTargetNodeTypesCallable(const GetRequestTargetNodeTypesRequest &request) { auto task = std::make_shared<std::packaged_task<GetRequestTargetNodeTypesOutcome()>>( [this, request]() { return this->GetRequestTargetNodeTypes(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::RestartInstanceOutcome EsClient::RestartInstance(const RestartInstanceRequest &request) { auto outcome = MakeRequest(request, "RestartInstance"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); RestartInstanceResponse rsp = RestartInstanceResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return RestartInstanceOutcome(rsp); else return RestartInstanceOutcome(o.GetError()); } else { return RestartInstanceOutcome(outcome.GetError()); } } void EsClient::RestartInstanceAsync(const RestartInstanceRequest& request, const RestartInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->RestartInstance(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::RestartInstanceOutcomeCallable EsClient::RestartInstanceCallable(const RestartInstanceRequest &request) { auto task = std::make_shared<std::packaged_task<RestartInstanceOutcome()>>( [this, request]() { return this->RestartInstance(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::RestartKibanaOutcome EsClient::RestartKibana(const RestartKibanaRequest &request) { auto outcome = MakeRequest(request, "RestartKibana"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); RestartKibanaResponse rsp = RestartKibanaResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return RestartKibanaOutcome(rsp); else return RestartKibanaOutcome(o.GetError()); } else { return RestartKibanaOutcome(outcome.GetError()); } } void EsClient::RestartKibanaAsync(const RestartKibanaRequest& request, const RestartKibanaAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->RestartKibana(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::RestartKibanaOutcomeCallable EsClient::RestartKibanaCallable(const RestartKibanaRequest &request) { auto task = std::make_shared<std::packaged_task<RestartKibanaOutcome()>>( [this, request]() { return this->RestartKibana(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::RestartNodesOutcome EsClient::RestartNodes(const RestartNodesRequest &request) { auto outcome = MakeRequest(request, "RestartNodes"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); RestartNodesResponse rsp = RestartNodesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return RestartNodesOutcome(rsp); else return RestartNodesOutcome(o.GetError()); } else { return RestartNodesOutcome(outcome.GetError()); } } void EsClient::RestartNodesAsync(const RestartNodesRequest& request, const RestartNodesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->RestartNodes(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::RestartNodesOutcomeCallable EsClient::RestartNodesCallable(const RestartNodesRequest &request) { auto task = std::make_shared<std::packaged_task<RestartNodesOutcome()>>( [this, request]() { return this->RestartNodes(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::UpdateDiagnoseSettingsOutcome EsClient::UpdateDiagnoseSettings(const UpdateDiagnoseSettingsRequest &request) { auto outcome = MakeRequest(request, "UpdateDiagnoseSettings"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UpdateDiagnoseSettingsResponse rsp = UpdateDiagnoseSettingsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UpdateDiagnoseSettingsOutcome(rsp); else return UpdateDiagnoseSettingsOutcome(o.GetError()); } else { return UpdateDiagnoseSettingsOutcome(outcome.GetError()); } } void EsClient::UpdateDiagnoseSettingsAsync(const UpdateDiagnoseSettingsRequest& request, const UpdateDiagnoseSettingsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UpdateDiagnoseSettings(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::UpdateDiagnoseSettingsOutcomeCallable EsClient::UpdateDiagnoseSettingsCallable(const UpdateDiagnoseSettingsRequest &request) { auto task = std::make_shared<std::packaged_task<UpdateDiagnoseSettingsOutcome()>>( [this, request]() { return this->UpdateDiagnoseSettings(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::UpdateDictionariesOutcome EsClient::UpdateDictionaries(const UpdateDictionariesRequest &request) { auto outcome = MakeRequest(request, "UpdateDictionaries"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UpdateDictionariesResponse rsp = UpdateDictionariesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UpdateDictionariesOutcome(rsp); else return UpdateDictionariesOutcome(o.GetError()); } else { return UpdateDictionariesOutcome(outcome.GetError()); } } void EsClient::UpdateDictionariesAsync(const UpdateDictionariesRequest& request, const UpdateDictionariesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UpdateDictionaries(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::UpdateDictionariesOutcomeCallable EsClient::UpdateDictionariesCallable(const UpdateDictionariesRequest &request) { auto task = std::make_shared<std::packaged_task<UpdateDictionariesOutcome()>>( [this, request]() { return this->UpdateDictionaries(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::UpdateInstanceOutcome EsClient::UpdateInstance(const UpdateInstanceRequest &request) { auto outcome = MakeRequest(request, "UpdateInstance"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UpdateInstanceResponse rsp = UpdateInstanceResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UpdateInstanceOutcome(rsp); else return UpdateInstanceOutcome(o.GetError()); } else { return UpdateInstanceOutcome(outcome.GetError()); } } void EsClient::UpdateInstanceAsync(const UpdateInstanceRequest& request, const UpdateInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UpdateInstance(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::UpdateInstanceOutcomeCallable EsClient::UpdateInstanceCallable(const UpdateInstanceRequest &request) { auto task = std::make_shared<std::packaged_task<UpdateInstanceOutcome()>>( [this, request]() { return this->UpdateInstance(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::UpdateJdkOutcome EsClient::UpdateJdk(const UpdateJdkRequest &request) { auto outcome = MakeRequest(request, "UpdateJdk"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UpdateJdkResponse rsp = UpdateJdkResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UpdateJdkOutcome(rsp); else return UpdateJdkOutcome(o.GetError()); } else { return UpdateJdkOutcome(outcome.GetError()); } } void EsClient::UpdateJdkAsync(const UpdateJdkRequest& request, const UpdateJdkAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UpdateJdk(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::UpdateJdkOutcomeCallable EsClient::UpdateJdkCallable(const UpdateJdkRequest &request) { auto task = std::make_shared<std::packaged_task<UpdateJdkOutcome()>>( [this, request]() { return this->UpdateJdk(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::UpdatePluginsOutcome EsClient::UpdatePlugins(const UpdatePluginsRequest &request) { auto outcome = MakeRequest(request, "UpdatePlugins"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UpdatePluginsResponse rsp = UpdatePluginsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UpdatePluginsOutcome(rsp); else return UpdatePluginsOutcome(o.GetError()); } else { return UpdatePluginsOutcome(outcome.GetError()); } } void EsClient::UpdatePluginsAsync(const UpdatePluginsRequest& request, const UpdatePluginsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UpdatePlugins(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::UpdatePluginsOutcomeCallable EsClient::UpdatePluginsCallable(const UpdatePluginsRequest &request) { auto task = std::make_shared<std::packaged_task<UpdatePluginsOutcome()>>( [this, request]() { return this->UpdatePlugins(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::UpdateRequestTargetNodeTypesOutcome EsClient::UpdateRequestTargetNodeTypes(const UpdateRequestTargetNodeTypesRequest &request) { auto outcome = MakeRequest(request, "UpdateRequestTargetNodeTypes"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UpdateRequestTargetNodeTypesResponse rsp = UpdateRequestTargetNodeTypesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UpdateRequestTargetNodeTypesOutcome(rsp); else return UpdateRequestTargetNodeTypesOutcome(o.GetError()); } else { return UpdateRequestTargetNodeTypesOutcome(outcome.GetError()); } } void EsClient::UpdateRequestTargetNodeTypesAsync(const UpdateRequestTargetNodeTypesRequest& request, const UpdateRequestTargetNodeTypesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UpdateRequestTargetNodeTypes(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::UpdateRequestTargetNodeTypesOutcomeCallable EsClient::UpdateRequestTargetNodeTypesCallable(const UpdateRequestTargetNodeTypesRequest &request) { auto task = std::make_shared<std::packaged_task<UpdateRequestTargetNodeTypesOutcome()>>( [this, request]() { return this->UpdateRequestTargetNodeTypes(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::UpgradeInstanceOutcome EsClient::UpgradeInstance(const UpgradeInstanceRequest &request) { auto outcome = MakeRequest(request, "UpgradeInstance"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UpgradeInstanceResponse rsp = UpgradeInstanceResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UpgradeInstanceOutcome(rsp); else return UpgradeInstanceOutcome(o.GetError()); } else { return UpgradeInstanceOutcome(outcome.GetError()); } } void EsClient::UpgradeInstanceAsync(const UpgradeInstanceRequest& request, const UpgradeInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UpgradeInstance(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::UpgradeInstanceOutcomeCallable EsClient::UpgradeInstanceCallable(const UpgradeInstanceRequest &request) { auto task = std::make_shared<std::packaged_task<UpgradeInstanceOutcome()>>( [this, request]() { return this->UpgradeInstance(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::UpgradeLicenseOutcome EsClient::UpgradeLicense(const UpgradeLicenseRequest &request) { auto outcome = MakeRequest(request, "UpgradeLicense"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UpgradeLicenseResponse rsp = UpgradeLicenseResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UpgradeLicenseOutcome(rsp); else return UpgradeLicenseOutcome(o.GetError()); } else { return UpgradeLicenseOutcome(outcome.GetError()); } } void EsClient::UpgradeLicenseAsync(const UpgradeLicenseRequest& request, const UpgradeLicenseAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UpgradeLicense(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::UpgradeLicenseOutcomeCallable EsClient::UpgradeLicenseCallable(const UpgradeLicenseRequest &request) { auto task = std::make_shared<std::packaged_task<UpgradeLicenseOutcome()>>( [this, request]() { return this->UpgradeLicense(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); }
33.555814
215
0.682306
suluner
ebacd0352d7062bcc1367156311b30e3282f5317
864
hpp
C++
irohad/ametsuchi/wsv_restorer.hpp
IvanTyulyandin/iroha
442a08325c7b808236569600653370e28ec5eff6
[ "Apache-2.0" ]
24
2016-09-26T17:11:46.000Z
2020-03-03T13:42:58.000Z
irohad/ametsuchi/wsv_restorer.hpp
ecsantana76/iroha
9cc430bb2c8eb885393e2a636fa92d1e605443ae
[ "Apache-2.0" ]
11
2016-10-13T10:09:55.000Z
2019-06-13T08:49:11.000Z
irohad/ametsuchi/wsv_restorer.hpp
ecsantana76/iroha
9cc430bb2c8eb885393e2a636fa92d1e605443ae
[ "Apache-2.0" ]
4
2016-09-27T13:18:28.000Z
2019-08-05T20:47:15.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_WSVRESTORER_HPP #define IROHA_WSVRESTORER_HPP #include "common/result.hpp" namespace iroha { namespace ametsuchi { class Storage; /** * Interface for World State View restoring from the storage */ class WsvRestorer { public: virtual ~WsvRestorer() = default; /** * Recover WSV (World State View). * @param storage storage of blocks in ledger * @return ledger state after restoration on success, otherwise error * string */ virtual iroha::expected:: Result<boost::optional<std::unique_ptr<LedgerState>>, std::string> restoreWsv(Storage &storage) = 0; }; } // namespace ametsuchi } // namespace iroha #endif // IROHA_WSVRESTORER_HPP
23.351351
76
0.649306
IvanTyulyandin
ebae48b12ed38473e0991443ea1b7902cb844a6c
19,369
cpp
C++
src/maze.cpp
TimQuelch/mazes
486291e0c84264664953b1bebfa77593854d9e77
[ "MIT" ]
1
2018-05-15T02:27:12.000Z
2018-05-15T02:27:12.000Z
src/maze.cpp
TimQuelch/mazes
486291e0c84264664953b1bebfa77593854d9e77
[ "MIT" ]
null
null
null
src/maze.cpp
TimQuelch/mazes
486291e0c84264664953b1bebfa77593854d9e77
[ "MIT" ]
null
null
null
/// \author Tim Quelch #include <algorithm> #include <chrono> #include <cmath> #include <deque> #include <iomanip> #include <iostream> #include <png++/png.hpp> #include <random> #include <tuple> #include "maze.h" namespace mazes { namespace detail { /// Holds the x y coordinates of a point in the maze struct Point { int x; ///< x coordinate int y; ///< y coordinate /// Construct with given values /// \param x The x coordinate /// \param y The y coordinate Point(int x = 0, int y = 0) : x{x} , y{y} {} /// Orders points lexicographically by x coordinate then y coordinate /// \param rhs Another point /// \returns true if the point is lexicographically less than the other by x then y bool operator<(const Point& rhs) { return std::tie(x, y) < std::tie(rhs.x, rhs.y); } /// Points are equal if both x and y are equal /// \param rhs Another point /// \returns true if both x and y are equal bool operator==(const Point& rhs) { return x == rhs.x && y == rhs.y; } }; /// Generates a random integer between a and b int randInt(int a, int b) { static auto seed = std::chrono::system_clock::now().time_since_epoch().count(); static auto randEngine = std::default_random_engine{seed}; auto dist = std::uniform_int_distribution{a, b}; return dist(randEngine); } /// Checks if a coordinate is within the boundaries of the maze. That is, if it x and y are /// greater than 1 and less than size - 1 /// \param p A Point /// \param gridSize the length of the side of the maze /// \returns true if the point is within the walls of the maze bool isLegal(Point p, int gridSize) { return p.x > 0 && p.x < gridSize - 1 && p.y > 0 && p.y < gridSize - 1; } /// Checks if point is a wall that can be removed to form a loop. Wall must be a vertical or /// horizontal wall, not a T wall, or X wall. /// \param grid Grid of the maze /// \param p A Point /// \returns true if the point can be removed to form a loop bool isWall(const std::vector<std::vector<bool>>& grid, Point p) { int countWalls = 0; countWalls += grid[p.x - 1][p.y] ? 0 : 1; countWalls += grid[p.x + 1][p.y] ? 0 : 1; countWalls += grid[p.x][p.y - 1] ? 0 : 1; countWalls += grid[p.x][p.y + 1] ? 0 : 1; bool wall = !grid[p.x][p.y]; bool nsWall = !grid[p.x][p.y + 1] && !grid[p.x][p.y - 1]; bool esWall = !grid[p.x - 1][p.y] && !grid[p.x + 1][p.y]; return wall && (nsWall || esWall) && !(nsWall && esWall) && (countWalls < 3); } /// Returns a list the points of the neighbours of a point. Neighbours are in the four /// cardinal directions and are a distance of two away. They are two away so that the wall /// inbetween is jumped. std::list<Point> getNeighbours(unsigned gridSize, Point p) { auto newNodes = std::list<Point>{}; newNodes.push_back({p.x - 2, p.y}); newNodes.push_back({p.x, p.y - 2}); newNodes.push_back({p.x, p.y + 2}); newNodes.push_back({p.x + 2, p.y}); newNodes.remove_if([gridSize](Point p) { return !isLegal(p, gridSize); }); return newNodes; } /// Returns and removes a random point from a list /// \param points Reference to a list of points. A random point is removed from this list /// \returns The Point removed from the list Point popPoint(std::list<Point>& points) { unsigned index = randInt(0, points.size() - 1); auto it = points.begin(); for (unsigned i = 0; i < index; i++) { it++; } points.erase(it); return *it; } /// Check if a point is a horizontal corridor. That is, it has corridors to the left and /// right, and walls to the top and bottom bool isHCorridor(Point p, const std::vector<std::vector<bool>>& grid) { return grid[p.x - 1][p.y] && grid[p.x + 1][p.y] && !grid[p.x][p.y - 1] && !grid[p.x][p.y + 1]; } /// Check if a point is a vertical corridor. That is, it has corridors to the top and /// bottom, and walls to the left and right bool isVCorridor(Point p, const std::vector<std::vector<bool>>& grid) { return !grid[p.x - 1][p.y] && !grid[p.x + 1][p.y] && grid[p.x][p.y - 1] && grid[p.x][p.y + 1]; } /// Calculate the manhatten distance between two points int calcCost(Point one, Point two) { return std::abs(one.x - two.x) + std::abs(one.y - two.y); } /// Initialise a grid to false std::vector<std::vector<bool>> initGrid(unsigned size) { auto grid = std::vector<std::vector<bool>>(); grid.resize(size); for (unsigned i = 0; i < size; i++) { grid[i].resize(size, false); } return grid; } /// Generate maze with Prims method void generatePrims(std::vector<std::vector<bool>>& grid) { const auto size = grid.size(); // Randomly generate initial point auto init = Point{randInt(0, (size - 2) / 2) * 2 + 1, randInt(0, (size - 2) / 2) * 2 + 1}; grid[init.x][init.y] = true; // Generate frontier points from neighbours auto frontierPoints = std::list<Point>{getNeighbours(size, init)}; // Expand maze until grid is full while (!frontierPoints.empty()) { // Pick random frontier point and set it to true auto p1 = Point{popPoint(frontierPoints)}; grid[p1.x][p1.y] = true; // Pick a random neighbours which is a pathway, and link the two points by setting // the intermediate point to a pathway auto neighbours = std::list<Point>{getNeighbours(size, p1)}; neighbours.remove_if([&grid](Point p) { return !grid[p.x][p.y]; }); auto p2 = Point{popPoint(neighbours)}; grid[p2.x - (p2.x - p1.x) / 2][p2.y - (p2.y - p1.y) / 2] = true; // Find and add the new frontier points auto newFrontierPoints = std::list<Point>{getNeighbours(size, p1)}; newFrontierPoints.remove_if([&grid](Point p) { return grid[p.x][p.y]; }); frontierPoints.merge(newFrontierPoints); frontierPoints.unique(); } } std::list<std::pair<Point, Point>> divideChamber(std::vector<std::vector<bool>>& grid, std::pair<Point, Point> chamber) { const auto x1 = chamber.first.x; const auto y1 = chamber.first.y; const auto x2 = chamber.second.x; const auto y2 = chamber.second.y; const auto size = x2 - x1; const auto mid = (size + 1) / 2; if (size < 2) { return {}; } // Set chamber to pathways for (auto i = x1; i <= x2; i++) { for (auto j = y1; j <= y2; j++) { grid[i][j] = true; } } // Set inner walls to walls for (auto i = x1; i <= x2; i++) { grid[i][y1 + mid] = false; } for (auto j = y1; j <= y2; j++) { grid[x1 + mid][j] = false; } // Create openings in walls const auto rand = [mid]() { return randInt(0, mid / 2) * 2; }; auto openings = std::vector<Point>{{x1 + mid, y1 + rand()}, {x1 + mid, y1 + mid + 1 + rand()}, {x1 + rand(), y1 + mid}, {x1 + mid + 1 + rand(), y1 + mid}}; openings.erase(openings.cbegin() + randInt(0, 3)); for (auto p : openings) { grid[p.x][p.y] = true; } // Return the subdivided chambers return {{{x1, y1}, {x1 + mid - 1, y1 + mid - 1}}, {{x1 + mid + 1, y1 + mid + 1}, {x2, y2}}, {{x1 + mid + 1, y1}, {x2, y1 + mid - 1}}, {{x1, y1 + mid + 1}, {x1 + mid - 1, y2}}}; } /// Generate maze with recursive division method void generateDivision(std::vector<std::vector<bool>>& grid) { const auto size = static_cast<int>(grid.size()); auto chambers = std::deque<std::pair<Point, Point>>{}; chambers.push_back({{1, 1}, {size - 2, size - 2}}); while (!chambers.empty()) { auto newChambers = divideChamber(grid, chambers.front()); chambers.pop_front(); for (const auto& c : newChambers) { chambers.push_back(c); } } } /// Remove walls to create multiple paths in the maze. Pick random points until a valid /// wall is found, then set it to be a pathway void addLoops(std::vector<std::vector<bool>>& grid, double loopFactor) { const auto size = grid.size(); const unsigned loops = size * size * loopFactor * loopFactor; for (unsigned i = 0; i < loops; i++) { Point p; do { p = Point(randInt(1, size - 2), randInt(1, size - 2)); } while (!isWall(grid, p)); grid[p.x][p.y] = true; } } /// Add the entrance and exit of the maze void addEntranceAndExit(std::vector<std::vector<bool>>& grid) { const auto size = grid.size(); grid[1][0] = true; grid[size - 2][size - 1] = true; } /// Generate the grid of a maze. There is an entrance in the top left, and an exit in the /// bottom right. /// \param size the length of the side of the maze /// \param loopFactor the factor of loopiness in the maze. 0 means there is a single /// solution, increasing increases number of solutions /// \returns the grid of the maze. can be indexed with v[x][y] /// \callgraph std::vector<std::vector<bool>> generateGrid(unsigned size, double loopFactor, Maze::Method method) { auto grid = initGrid(size); switch (method) { case Maze::Method::prims: generatePrims(grid); break; case Maze::Method::division: generateDivision(grid); break; } addLoops(grid, loopFactor); addEntranceAndExit(grid); return grid; } /// Generate the graph of a maze from the grid. The maze is sorted left to right, then top /// to bottom, therefore the entrance is the first node, and the exit is the last node /// \param grid The Maze grid to generate the graph from /// \returns A list of Nodes that make up the graph of the maze std::list<std::shared_ptr<Maze::Node>> generateGraph(const std::vector<std::vector<bool>>& grid) { using Node = Maze::Node; using Edge = Maze::Edge; const int size = grid.size(); auto graph = std::list<std::shared_ptr<Node>>{}; // nodes in the graph auto above = std::list<std::shared_ptr<Node>>{}; // nodes that are above current // Add start node auto first = std::make_shared<Node>(1, 0, std::list<Edge>{}); graph.push_back(first); above.push_back(first); // Iterate through whole grid for (int j = 1; j < size; j++) { auto left = std::shared_ptr<Node>{nullptr}; // The node that is left of present auto nodeAbove = above.begin(); // Iterator to start of above nodes for (int i = 1; i < size - 1; i++) { if (grid[i][j]) { // Ignore point if it is a corridor if (!isHCorridor({i, j}, grid) && !isVCorridor({i, j}, grid)) { auto edges = std::list<Edge>{}; // Add edge if there is a node to the left if (left) { int cost = calcCost({i, j}, {left->x, left->y}); edges.push_back({left, cost}); } // Add edge if there is a node above if (nodeAbove != above.end() && (*nodeAbove)->x == i) { int cost = calcCost({i, j}, {(*nodeAbove)->x, (*nodeAbove)->y}); edges.push_back({*nodeAbove, cost}); nodeAbove = above.erase(nodeAbove); } // Create the node auto node = std::make_shared<Node>(i, j, edges); graph.push_back(node); above.insert(nodeAbove, node); left = node; // Add edges to this node from all edges for (const auto& edge : edges) { edge.node->edges.push_back({node, edge.cost}); } } // Iterate above iterator if needed if (isVCorridor({i, j}, grid) && nodeAbove != above.end() && (*nodeAbove)->x == i) { nodeAbove++; } } else { // If current is wall, reset left and iterate above left = nullptr; if (nodeAbove != above.end() && (*nodeAbove)->x == i) { nodeAbove = above.erase(nodeAbove); } } } } // Sort the list of nodes. Entrance will be first, exit will be last graph.sort([](auto& one, auto& two) { return std::tie(one->x, one->y) < std::tie(two->x, two->y); }); return graph; } } // namespace detail // Construct maze with given size. Generate grid and graph Maze::Maze(unsigned size, double loopFactor, Maze::Method method) : size_{size} , grid_{detail::generateGrid(size, loopFactor, method)} , graph_{detail::generateGraph(grid_)} {} // Print the maze to stdout void Maze::print() const { std::cout << " "; for (unsigned i = 0; i < size_; i++) { std::cout << std::setw(2) << i << " "; } std::cout << "\n\n"; for (unsigned j = 0; j < size_; j++) { std::cout << std::setw(2) << j << " "; for (unsigned i = 0; i < size_; i++) { if (grid_[i][j]) { std::cout << " "; } else { std::cout << " # "; } } std::cout << "\n"; } std::cout << "\n"; } // Print the graph nodes over the maze to stdout void Maze::printGraph() const { // Create grid where nodes are true auto graphGrid = std::vector<std::vector<bool>>{}; graphGrid.resize(size_); for (unsigned i = 0; i < size_; i++) { graphGrid[i].resize(size_, false); } for (auto nodePtr : graph_) { graphGrid[nodePtr->x][nodePtr->y] = true; } // Print to output std::cout << " "; for (unsigned i = 0; i < size_; i++) { std::cout << std::setw(2) << i << " "; } std::cout << "\n\n"; for (unsigned j = 0; j < size_; j++) { std::cout << std::setw(2) << j << " "; for (unsigned i = 0; i < size_; i++) { if (graphGrid[i][j]) { std::cout << " o "; } else if (grid_[i][j]) { std::cout << " "; } else { std::cout << " # "; } } std::cout << "\n"; } std::cout << "\n"; } // Write the maze to PNG void Maze::writePng(std::string_view filename) const { auto image = png::image<png::rgb_pixel>{size_, size_}; for (unsigned j = 0; j < size_; j++) { for (unsigned i = 0; i < size_; i++) { if (grid_[i][j]) { image[j][i] = png::rgb_pixel(255, 255, 255); } else { image[j][i] = png::rgb_pixel(0, 0, 0); } } } image.write(filename.data()); } // Write the graph nodes over the maze to PNG void Maze::writePngGraph(std::string_view filename) const { auto image = png::image<png::rgb_pixel>{size_, size_}; // Write maze for (unsigned j = 0; j < size_; j++) { for (unsigned i = 0; i < size_; i++) { if (grid_[i][j]) { image[j][i] = png::rgb_pixel(255, 255, 255); } else { image[j][i] = png::rgb_pixel(0, 0, 0); } } } // Write graph for (auto nodePtr : graph_) { image[nodePtr->y][nodePtr->x] = png::rgb_pixel(255, 0, 0); } image.write(filename.data()); } // Write the maze with a given path to PNG void Maze::writePngPath(std::list<std::shared_ptr<Node>> path, std::string_view filename) const { auto image = png::image<png::rgb_pixel>{size_, size_}; // Write maze for (unsigned j = 0; j < size_; j++) { for (unsigned i = 0; i < size_; i++) { if (grid_[i][j]) { image[j][i] = png::rgb_pixel(255, 255, 255); } else { image[j][i] = png::rgb_pixel(0, 0, 0); } } } // Write path auto prev = detail::Point{path.front()->x, path.front()->y}; for (const auto& node : path) { auto start = detail::Point{std::min(prev.x, node->x), std::min(prev.y, node->y)}; auto end = detail::Point{std::max(prev.x + 1, node->x + 1), std::max(prev.y + 1, node->y + 1)}; for (int i = start.x; i != end.x; i++) { for (int j = start.y; j != end.y; j++) { image[j][i] = png::rgb_pixel(255, 0, 0); } } prev = {node->x, node->y}; } image.write(filename.data()); } } // namespace mazes
40.268191
100
0.466209
TimQuelch
ebb83be9b4f4f129f5275956a96bcaa9e416ebc4
2,720
hpp
C++
include/libtorrent/aux_/deferred_handler.hpp
projectxorg/libtorrent
449b39318796addaafc6e655c9affc88706b8aa7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
50
2016-01-26T15:42:58.000Z
2022-02-27T11:32:58.000Z
include/libtorrent/aux_/deferred_handler.hpp
projectxorg/libtorrent
449b39318796addaafc6e655c9affc88706b8aa7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2016-04-05T02:38:33.000Z
2017-06-01T20:16:29.000Z
include/libtorrent/aux_/deferred_handler.hpp
projectxorg/libtorrent
449b39318796addaafc6e655c9affc88706b8aa7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
53
2016-01-25T01:14:54.000Z
2022-03-13T10:20:36.000Z
/* Copyright (c) 2017, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_DEFERRED_HANDLER_HPP #define TORRENT_DEFERRED_HANDLER_HPP #include "libtorrent/assert.hpp" #include "libtorrent/io_service.hpp" namespace libtorrent { namespace aux { template <typename Handler> struct handler_wrapper { handler_wrapper(bool& in_flight, Handler&& h) : m_handler(std::move(h)) , m_in_flight(in_flight) {} template <typename... Args> void operator()(Args&&... a) { TORRENT_ASSERT(m_in_flight); m_in_flight = false; m_handler(std::forward<Args>(a)...); } // forward asio handler allocator to the underlying handler's friend void* asio_handler_allocate( std::size_t size, handler_wrapper<Handler>* h) { return asio_handler_allocate(size, &h->m_handler); } friend void asio_handler_deallocate( void* ptr, std::size_t size, handler_wrapper<Handler>* h) { asio_handler_deallocate(ptr, size, &h->m_handler); } private: Handler m_handler; bool& m_in_flight; }; struct deferred_handler { template <typename Handler> void post(io_service& ios, Handler&& h) { if (m_in_flight) return; m_in_flight = true; ios.post(handler_wrapper<Handler>(m_in_flight, std::forward<Handler>(h))); } private: bool m_in_flight = false; }; }} #endif
30.909091
78
0.766176
projectxorg
ebb8b68a37b50af44db4f0b268185c3f9781b188
842
cpp
C++
pix/Color.cpp
Andrewich/deadjustice
48bea56598e79a1a10866ad41aa3517bf7d7c724
[ "BSD-3-Clause" ]
3
2019-04-20T10:16:36.000Z
2021-03-21T19:51:38.000Z
pix/Color.cpp
Andrewich/deadjustice
48bea56598e79a1a10866ad41aa3517bf7d7c724
[ "BSD-3-Clause" ]
null
null
null
pix/Color.cpp
Andrewich/deadjustice
48bea56598e79a1a10866ad41aa3517bf7d7c724
[ "BSD-3-Clause" ]
2
2020-04-18T20:04:24.000Z
2021-09-19T05:07:41.000Z
#include "Color.h" #include "Colorf.h" #include <assert.h> #include "config.h" //----------------------------------------------------------------------------- namespace pix { inline static uint8_t convertColorFloatToByte( float src ) { float f = src; if ( f < 0.f ) f = 0.f; else if ( f > 1.f ) f = 1.f; int i = (int)( f*255.f + .5f ); if ( i < 0 ) i = 0; else if ( i > 255 ) i = 255; assert( i >= 0 && i < 256 ); return (uint8_t)i; } //----------------------------------------------------------------------------- Color::Color( const Colorf& source ) { setRed( convertColorFloatToByte(source.red()) ); setGreen( convertColorFloatToByte(source.green()) ); setBlue( convertColorFloatToByte(source.blue()) ); setAlpha( convertColorFloatToByte(source.alpha()) ); } } // pix
20.047619
80
0.472684
Andrewich
ebb9c905af47c4e3fd9c1e69f364d2108a856508
4,311
hpp
C++
modules/boost/simd/base/include/boost/simd/arithmetic/functions/generic/remquo.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/boost/simd/base/include/boost/simd/arithmetic/functions/generic/remquo.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/base/include/boost/simd/arithmetic/functions/generic/remquo.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // Copyright 2012 - 2014 MetaScale SAS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_GENERIC_REMQUO_HPP_INCLUDED #define BOOST_SIMD_ARITHMETIC_FUNCTIONS_GENERIC_REMQUO_HPP_INCLUDED #include <boost/simd/arithmetic/functions/remquo.hpp> #include <boost/simd/include/functions/simd/round2even.hpp> #include <boost/simd/include/functions/simd/toint.hpp> #include <boost/simd/include/functions/simd/minus.hpp> #include <boost/simd/include/functions/simd/is_eqz.hpp> #include <boost/simd/include/functions/simd/divides.hpp> #include <boost/simd/include/functions/simd/is_invalid.hpp> #include <boost/simd/include/functions/simd/logical_or.hpp> #include <boost/simd/include/functions/simd/multiplies.hpp> #include <boost/simd/include/functions/simd/if_allbits_else.hpp> #include <boost/simd/sdk/config.hpp> #include <boost/dispatch/meta/as_integer.hpp> #include <boost/fusion/include/std_pair.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/dispatch/attributes.hpp> namespace boost { namespace simd { namespace ext { BOOST_DISPATCH_IMPLEMENT_IF ( remquo_ , tag::cpu_ , (A0)(A1) , ( boost::is_same < typename dispatch::meta:: as_integer<A0,signed>::type , A1 > ) , (generic_< floating_<A0> >) (generic_< floating_<A0> >) (generic_< integer_<A1> > ) ) { typedef A0 result_type; BOOST_FORCEINLINE result_type operator()(A0 const& a0,A0 const& a1,A1& a3) const { result_type a2; boost::simd::remquo(a0, a1, a2, a3); return a2; } }; BOOST_DISPATCH_IMPLEMENT ( remquo_, tag::cpu_ , (A0) , (generic_< floating_<A0> >) (generic_< floating_<A0> >) ) { typedef typename dispatch::meta::as_integer<A0, signed>::type quo_t; typedef std::pair<A0,quo_t> result_type; BOOST_FORCEINLINE result_type operator()(A0 const& a0,A0 const& a1) const { A0 first; quo_t second; boost::simd::remquo( a0, a1, first, second ); return result_type(first, second); } }; BOOST_DISPATCH_IMPLEMENT_IF ( remquo_, tag::cpu_ , (A0)(A1) , ( boost::is_same < typename dispatch::meta:: as_integer<A0,signed>::type , A1 > ) , (generic_<floating_<A0> >) (generic_<floating_<A0> >) (generic_<floating_<A0> >) (generic_<integer_ <A1> >) ) { typedef void result_type; BOOST_FORCEINLINE result_type operator()(A0 const& a0, A0 const& a1,A0& a2, A1& a3) const { A0 const d = round2even(a0/a1); #if defined(BOOST_SIMD_NO_INVALIDS) a2 = if_allbits_else(is_eqz(a1), a0-d*a1); #else a2 = if_allbits_else(l_or(is_invalid(a0), is_eqz(a1)), a0-d*a1); #endif a3 = toint(d); } }; } } } #endif
40.28972
81
0.474136
psiha
ebbfad0796ffae5b6ca5cfef50b3b69190d2175d
474
cpp
C++
tests/src/simple_modifications_json/src/simple_modifications_json_test.cpp
egelwan/Karabiner-Elements
896439dd2130904275553282063dd7fe4852e1a8
[ "Unlicense" ]
2
2021-03-24T17:34:09.000Z
2021-07-01T12:16:54.000Z
tests/src/simple_modifications_json/src/simple_modifications_json_test.cpp
XXXalice/Karabiner-Elements
52f579cbf60251cf18915bd938eb4431360b763b
[ "Unlicense" ]
null
null
null
tests/src/simple_modifications_json/src/simple_modifications_json_test.cpp
XXXalice/Karabiner-Elements
52f579cbf60251cf18915bd938eb4431360b763b
[ "Unlicense" ]
null
null
null
#include <catch2/catch.hpp> #include "../../share/json_helper.hpp" #include "manipulator/types.hpp" #include <pqrs/json.hpp> TEST_CASE("simple_modifications.json") { auto json = krbn::unit_testing::json_helper::load_jsonc("../../../src/apps/PreferencesWindow/Resources/simple_modifications.json"); for (const auto& entry : json) { if (auto data = pqrs::json::find_object(entry, "data")) { krbn::manipulator::to_event_definition e(data->value()); } } }
31.6
133
0.694093
egelwan
ebc66fbe4477496f88babdff871bf18700c7e690
539
cc
C++
src/openvslam/data/bow_vocabulary.cc
soallak/openvslam
23d155918a89eb791cf98bc25e1758b6e44f4f85
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
src/openvslam/data/bow_vocabulary.cc
soallak/openvslam
23d155918a89eb791cf98bc25e1758b6e44f4f85
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
src/openvslam/data/bow_vocabulary.cc
soallak/openvslam
23d155918a89eb791cf98bc25e1758b6e44f4f85
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
#include "openvslam/data/bow_vocabulary.h" namespace openvslam { namespace data { namespace bow_vocabulary_util { void compute_bow(data::bow_vocabulary* bow_vocab, const cv::Mat& descriptors, data::bow_vector& bow_vec, data::bow_feature_vector& bow_feat_vec) { #ifdef USE_DBOW2 bow_vocab->transform(util::converter::to_desc_vec(descriptors), bow_vec, bow_feat_vec, 4); #else bow_vocab->transform(descriptors, 4, bow_vec, bow_feat_vec); #endif } }; // namespace bow_vocabulary_util }; // namespace data }; // namespace openvslam
29.944444
146
0.7718
soallak
ebc78addb8dbf2038ce1d61b33f5b6652537fd82
14,499
cpp
C++
ZooidEngine/ResourceManagers/MeshManager.cpp
azon04/Z0-Engine
1a44781fb5308c11c3b63b954ad683a51e9ba271
[ "MIT" ]
4
2019-05-31T22:55:49.000Z
2020-11-26T11:55:34.000Z
ZooidEngine/ResourceManagers/MeshManager.cpp
azon04/Z0-Engine
1a44781fb5308c11c3b63b954ad683a51e9ba271
[ "MIT" ]
null
null
null
ZooidEngine/ResourceManagers/MeshManager.cpp
azon04/Z0-Engine
1a44781fb5308c11c3b63b954ad683a51e9ba271
[ "MIT" ]
1
2018-04-11T02:50:47.000Z
2018-04-11T02:50:47.000Z
#include "MeshManager.h" #include "BufferManager.h" #include "MaterialManager.h" #include "SkeletonManager.h" #include "Resources/Mesh.h" #include "Resources/Material.h" #include "FileSystem/FileReader.h" #include "FileSystem/DirectoryHelper.h" #include "Renderer/IRenderer.h" #include "Physics/Physics.h" #include "ZEGameContext.h" #define RETURN_SHAPE_IF(shapeType, s) \ if (StringFunc::Compare(s, #shapeType ) == 0) \ { \ return shapeType; \ } namespace ZE { IMPLEMENT_CLASS_1(MeshManager, ResourceManager) struct MeshSkinData { Float32 Position[3]; Float32 Normal[3]; Float32 TexCoord[2]; Int32 BoneIDs[4]; Float32 BoneWeights[4]; }; struct MeshSkinDataWithTangent { Float32 Position[3]; Float32 Normal[3]; Float32 TexCoord[2]; Int32 BoneIDs[4]; Float32 BoneWeights[4]; Float32 Tangent[3]; }; MeshManager* MeshManager::s_instance = nullptr; void MeshManager::Init() { Handle hMeshManager("Mesh Manager", sizeof(MeshManager)); s_instance = new(hMeshManager) MeshManager(); } void MeshManager::Destroy() { if(s_instance) s_instance->unloadResources(); delete s_instance; s_instance = nullptr; } ZE::MeshManager* MeshManager::GetInstance() { return s_instance; } PhysicsShape GetShapeFromString(const char* shapeName) { RETURN_SHAPE_IF(BOX, shapeName) RETURN_SHAPE_IF(SPHERE, shapeName) RETURN_SHAPE_IF(CAPSULE, shapeName) RETURN_SHAPE_IF(PLANE, shapeName) RETURN_SHAPE_IF(CONVEX_MESHES, shapeName) RETURN_SHAPE_IF(TRIANGLE_MESHES, shapeName) RETURN_SHAPE_IF(HEIGHT_FIELDS, shapeName) return PHYSICS_SHAPE_NONE; } void MeshManager::loadPhysicsBodySetup(FileReader* fileReader, Mesh* pMesh) { Handle hPhysicsBodySetup("Physics Body Setup", sizeof(PhysicsBodySetup)); PhysicsBodySetup* pPhysicsBodySetup = new(hPhysicsBodySetup) PhysicsBodySetup(); char tokenBuffer[64]; // Read physic data type : single/file/multi fileReader->readNextString(tokenBuffer); if (StringFunc::Compare(tokenBuffer, "single") == 0) { PhysicsBodyDesc bodyDesc; fileReader->readNextString(tokenBuffer); bodyDesc.ShapeType = GetShapeFromString(tokenBuffer); switch (bodyDesc.ShapeType) { case BOX: bodyDesc.HalfExtent.setX(fileReader->readNextFloat()); bodyDesc.HalfExtent.setY(fileReader->readNextFloat()); bodyDesc.HalfExtent.setZ(fileReader->readNextFloat()); break; case SPHERE: bodyDesc.Radius = fileReader->readNextFloat(); break; case CAPSULE: bodyDesc.Radius = fileReader->readNextFloat(); bodyDesc.HalfHeight = fileReader->readNextFloat(); break; case PLANE: break; case CONVEX_MESHES: // #TODO Read buffer break; case TRIANGLE_MESHES: // #TODO Read buffer break; case HEIGHT_FIELDS: // #TODO Read HeightField break; } // Mass expected fileReader->readNextString(tokenBuffer); if (StringFunc::Compare(tokenBuffer, "Mass") == 0) { pPhysicsBodySetup->Mass = fileReader->readNextFloat(); } pPhysicsBodySetup->m_bodies.push_back(bodyDesc); } else if (StringFunc::Compare(tokenBuffer, "multi") == 0) { // #TODO need to implement multi descriptor } else if (StringFunc::Compare(tokenBuffer, "file") == 0) { // #TODO need to implement file descriptor for this } pMesh->m_hPhysicsBodySetup = hPhysicsBodySetup; } ZE::ERenderTopologyEnum getTopologyByName(const char* stringType) { COMPARE_RETURN(stringType, TOPOLOGY_TRIANGLE_STRIP); COMPARE_RETURN(stringType, TOPOLOGY_POINT); COMPARE_RETURN(stringType, TOPOLOGY_LINE); COMPARE_RETURN(stringType, TOPOLOGY_LINE_STRIP); return TOPOLOGY_TRIANGLE; } void MeshManager::loadBuffers(FileReader* fileReader, Mesh* pMesh) { char buffer[256]; // READ VERTEX BUFFER fileReader->readNextString(buffer); int bufferLayoutType = getBufferLayoutByString(buffer); if (bufferLayoutType == -1) { ZEINFO("BufferManager: Can't find buffer layout type for %s", buffer); return; } Handle hVertexBufferData("Buffer Data", sizeof(BufferData)); BufferData* pVertexBuffer = new(hVertexBufferData) BufferData(VERTEX_BUFFER); pVertexBuffer->setBufferLayout(bufferLayoutType); int numVertex = fileReader->readNextInt(); Handle dataHandle; if (bufferLayoutType == BUFFER_LAYOUT_V3_N3_TC2_SKIN) { dataHandle = Handle("Data", sizeof(MeshSkinData) * numVertex); MeshSkinData* pData = new(dataHandle) MeshSkinData[numVertex]; Vector3 minVertex(999999.9f); Vector3 maxVertex(-999999.9f); Vector3 centerVertex(0.0f); for (int i = 0; i < numVertex; i++) { pData[i].Position[0] = fileReader->readNextFloat(); pData[i].Position[1] = fileReader->readNextFloat(); pData[i].Position[2] = fileReader->readNextFloat(); pData[i].Normal[0] = fileReader->readNextFloat(); pData[i].Normal[1] = fileReader->readNextFloat(); pData[i].Normal[2] = fileReader->readNextFloat(); pData[i].TexCoord[0] = fileReader->readNextFloat(); pData[i].TexCoord[1] = fileReader->readNextFloat(); pData[i].BoneIDs[0] = fileReader->readNextInt(); pData[i].BoneIDs[1] = fileReader->readNextInt(); pData[i].BoneIDs[2] = fileReader->readNextInt(); pData[i].BoneIDs[3] = fileReader->readNextInt(); pData[i].BoneWeights[0] = fileReader->readNextFloat(); pData[i].BoneWeights[1] = fileReader->readNextFloat(); pData[i].BoneWeights[2] = fileReader->readNextFloat(); pData[i].BoneWeights[3] = fileReader->readNextFloat(); if (minVertex.m_x > pData[i].Position[0]) { minVertex.m_x = pData[i].Position[0]; } if (minVertex.m_y > pData[i].Position[1]) { minVertex.m_y = pData[i].Position[1]; } if (minVertex.m_z > pData[i].Position[2]) { minVertex.m_z = pData[i].Position[2]; } if (maxVertex.m_x < pData[i].Position[0]) { maxVertex.m_x = pData[i].Position[0]; } if (maxVertex.m_y < pData[i].Position[1]) { maxVertex.m_y = pData[i].Position[1]; } if (maxVertex.m_z < pData[i].Position[2]) { maxVertex.m_z = pData[i].Position[2]; } centerVertex = centerVertex + Vector3(pData[i].Position); } centerVertex = (minVertex + maxVertex) * 0.5f; pMesh->m_boxMin = minVertex; pMesh->m_boxMax = maxVertex; pMesh->m_centerOffset = centerVertex; Vector3 centerToMax = maxVertex - centerVertex; pMesh->m_radius = centerToMax.length(); pVertexBuffer->SetData(pData, sizeof(MeshSkinData), numVertex); } else if (bufferLayoutType == BUFFER_LAYOUT_V3_N3_T3_TC2_SKIN) { dataHandle = Handle("Data", sizeof(MeshSkinDataWithTangent) * numVertex); MeshSkinDataWithTangent* pData = new(dataHandle) MeshSkinDataWithTangent[numVertex]; Vector3 minVertex(9999.9f); Vector3 maxVertex(-9999.9f); Vector3 centerVertex(0.0f); for (int i = 0; i < numVertex; i++) { pData[i].Position[0] = fileReader->readNextFloat(); pData[i].Position[1] = fileReader->readNextFloat(); pData[i].Position[2] = fileReader->readNextFloat(); pData[i].Normal[0] = fileReader->readNextFloat(); pData[i].Normal[1] = fileReader->readNextFloat(); pData[i].Normal[2] = fileReader->readNextFloat(); pData[i].TexCoord[0] = fileReader->readNextFloat(); pData[i].TexCoord[1] = fileReader->readNextFloat(); pData[i].Tangent[0] = fileReader->readNextFloat(); pData[i].Tangent[1] = fileReader->readNextFloat(); pData[i].Tangent[2] = fileReader->readNextFloat(); pData[i].BoneIDs[0] = fileReader->readNextInt(); pData[i].BoneIDs[1] = fileReader->readNextInt(); pData[i].BoneIDs[2] = fileReader->readNextInt(); pData[i].BoneIDs[3] = fileReader->readNextInt(); pData[i].BoneWeights[0] = fileReader->readNextFloat(); pData[i].BoneWeights[1] = fileReader->readNextFloat(); pData[i].BoneWeights[2] = fileReader->readNextFloat(); pData[i].BoneWeights[3] = fileReader->readNextFloat(); if (minVertex.m_x > pData[i].Position[0]) { minVertex.m_x = pData[i].Position[0]; } if (minVertex.m_y > pData[i].Position[1]) { minVertex.m_y = pData[i].Position[1]; } if (minVertex.m_z > pData[i].Position[2]) { minVertex.m_z = pData[i].Position[2]; } if (maxVertex.m_x < pData[i].Position[0]) { maxVertex.m_x = pData[i].Position[0]; } if (maxVertex.m_y < pData[i].Position[1]) { maxVertex.m_y = pData[i].Position[1]; } if (maxVertex.m_z < pData[i].Position[2]) { maxVertex.m_z = pData[i].Position[2]; } } centerVertex = (minVertex + maxVertex) * 0.5f; pMesh->m_boxMin = minVertex; pMesh->m_boxMax = maxVertex; pMesh->m_centerOffset = centerVertex; Vector3 centerToMax = maxVertex - centerVertex; pMesh->m_radius = centerToMax.length(); pVertexBuffer->SetData(pData, sizeof(MeshSkinDataWithTangent), numVertex); } else { int dataPerVertex = 6; switch (bufferLayoutType) { case BUFFER_LAYOUT_V3_C3: dataPerVertex = 6; break; case BUFFER_LAYOUT_V3_N3_TC2: dataPerVertex = 8; break; case BUFFER_LAYOUT_V3_N3_T3_TC2: dataPerVertex = 11; break; case BUFFER_LAYOUT_V3_N3_TC2_SKIN: dataPerVertex = 16; break; default: break; } int totalSize = dataPerVertex * numVertex; dataHandle = Handle("Data", sizeof(Float32) * totalSize); Float32* pData = new(dataHandle) Float32[totalSize]; Vector3 minVertex(999999.9f); Vector3 maxVertex(-999999.9f); Vector3 centerVertex(0.0f); for (int i = 0; i < totalSize; ++i) { pData[i] = fileReader->readNextFloat(); if (i % dataPerVertex == 0) { if (minVertex.m_x > pData[i]) { minVertex.m_x = pData[i]; } if (maxVertex.m_x < pData[i]) { maxVertex.m_x = pData[i]; } } else if (i % dataPerVertex == 1) { if (minVertex.m_y > pData[i]) { minVertex.m_y = pData[i]; } if (maxVertex.m_y < pData[i]) { maxVertex.m_y = pData[i]; } } else if (i % dataPerVertex == 2) { if (minVertex.m_z > pData[i]) { minVertex.m_z = pData[i]; } if (maxVertex.m_z < pData[i]) { maxVertex.m_z = pData[i]; } } } centerVertex = (minVertex + maxVertex) * 0.5f; pMesh->m_boxMin = minVertex; pMesh->m_boxMax = maxVertex; pMesh->m_centerOffset = centerVertex; Vector3 centerToMax = maxVertex - centerVertex; pMesh->m_radius = centerToMax.length(); pVertexBuffer->SetData(pData, sizeof(Float32) * dataPerVertex, numVertex); } // READ OPTIONAL INDEX BUFFER Handle hIndexBufferData("Buffer Data", sizeof(BufferData)); BufferData* pIndexBuffer = nullptr; Handle indexDataHandle; fileReader->readNextString(buffer); if (StringFunc::Compare(buffer, "INDICE_BUFFER_NONE") != 0) { int numIndex = fileReader->readNextInt(); indexDataHandle = Handle("Data", sizeof(Int32) * numIndex); UInt32* indexData = new(indexDataHandle) UInt32[numIndex]; for (int i = 0; i < numIndex; ++i) { indexData[i] = fileReader->readNextInt(); } pIndexBuffer = new(hIndexBufferData) BufferData(INDEX_BUFFER); pIndexBuffer->SetData(indexData, sizeof(UInt32), numIndex); } ScopedRenderThreadOwnership renderLock(gGameContext->getRenderer()); Handle hResult = BufferManager::getInstance()->createBufferArray(pVertexBuffer, pIndexBuffer, nullptr); if (hVertexBufferData.isValid()) { hVertexBufferData.release(); dataHandle.release(); } if (hIndexBufferData.isValid()) { hIndexBufferData.release(); indexDataHandle.release(); } pMesh->m_bufferArray = hResult.getObject<IGPUBufferArray>(); fileReader->readNextString(buffer); if (StringFunc::Compare(buffer, "TOPOLOGY") == 0) { fileReader->readNextString(buffer); if (pMesh->m_bufferArray) { pMesh->m_bufferArray->setRenderTopology(getTopologyByName(buffer)); } } fileReader->close(); } int MeshManager::getBufferLayoutByString(const char* stringType) { COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_C3); COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_N3_TC2); COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_N3_TC2_SKIN); COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_N3_T3_TC2); COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_N3_T3_TC2_SKIN); COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_N3_T3_B3_TC2); COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_N3_T3_B3_TC2_SKIN); return -1; } ZE::Handle MeshManager::loadResource_Internal(const char* resourceFilePath, ResourceCreateSettings* settings) { Handle meshHandle("Mesh Handle", sizeof(Mesh)); Mesh* pMesh; FileReader reader(resourceFilePath); if (!reader.isValid()) { ZEWARNING("Mesh file not found : %s", resourceFilePath); return meshHandle; } char tokenBuffer[256]; pMesh = new(meshHandle) Mesh(); while (!reader.eof()) { reader.readNextString(tokenBuffer); if (StringFunc::Compare(tokenBuffer, "vbuff") == 0) { reader.readNextString(tokenBuffer); String path = GetResourcePath(tokenBuffer); FileReader bufferFileReader(path.c_str()); if (!bufferFileReader.isValid()) { ZEINFO("BufferManager: File %s not find", path.c_str()); return Handle(); } loadBuffers(&bufferFileReader, pMesh); } else if (StringFunc::Compare(tokenBuffer, "mat") == 0) { reader.readNextString(tokenBuffer); Handle hMaterial = MaterialManager::GetInstance()->loadResource(GetResourcePath(tokenBuffer).c_str()); if (hMaterial.isValid()) { pMesh->m_material = hMaterial.getObject<Material>(); } } else if (StringFunc::Compare(tokenBuffer, "double_side") == 0) { pMesh->m_doubleSided = true; } else if (StringFunc::Compare(tokenBuffer, "physics") == 0) { loadPhysicsBodySetup(&reader, pMesh); } else if (StringFunc::Compare(tokenBuffer, "skeleton") == 0) { reader.readNextString(tokenBuffer); Handle hSkeleton = SkeletonManager::GetInstance()->loadResource(GetResourcePath(tokenBuffer).c_str()); if (hSkeleton.isValid()) { pMesh->m_hSkeleton = hSkeleton; } } } reader.close(); return meshHandle; } void MeshManager::preUnloadResource(Resource* _resource) { Mesh* pMesh = _resource->m_hActual.getObject<Mesh>(); if (pMesh) { if (pMesh->m_hPhysicsBodySetup.isValid()) { pMesh->m_hPhysicsBodySetup.release(); } if (pMesh->m_bufferArray) { pMesh->m_bufferArray->release(); } } } }
26.313975
110
0.682254
azon04
ebc7ebe677453a33460d0d33c349895dbe0871ca
5,036
hpp
C++
components/scream/src/share/util/scream_std_meta.hpp
AaronDonahue/scream
a1e1cc67ac6db87ce6525315a5548d0e7b0f5e97
[ "zlib-acknowledgement", "FTL", "RSA-MD" ]
null
null
null
components/scream/src/share/util/scream_std_meta.hpp
AaronDonahue/scream
a1e1cc67ac6db87ce6525315a5548d0e7b0f5e97
[ "zlib-acknowledgement", "FTL", "RSA-MD" ]
3
2019-04-25T18:18:33.000Z
2019-05-07T16:43:36.000Z
components/scream/src/share/util/scream_std_meta.hpp
AaronDonahue/scream
a1e1cc67ac6db87ce6525315a5548d0e7b0f5e97
[ "zlib-acknowledgement", "FTL", "RSA-MD" ]
null
null
null
#ifndef SCREAM_STD_META_HPP #define SCREAM_STD_META_HPP /* * Emulating c++1z features * * This file contains some features that belongs to the std namespace, * and that are likely (if not already scheduled) to be in future standards. * However, we have limited access to c++1z standard on target platforms, * so we can only rely on c++11 features. Everything else that we may need, * we try to emulate here. */ #include <memory> #include "share/scream_assert.hpp" namespace scream { namespace util { // =============== type_traits utils ============== // // <type_traits> has remove_all_extents but lacks the analogous // remove_all_pointers template<typename T> struct remove_all_pointers { using type = T; }; template<typename T> struct remove_all_pointers<T*> { using type = typename remove_all_pointers<T>::type; }; // std::remove_const does not remove the leading const cv from // the type <const T*>. Indeed, remove_const can only remove the // const cv from the pointer, not the pointee. template<typename T> struct remove_all_consts : std::remove_const<T> {}; template<typename T> struct remove_all_consts<T*> { using type = typename remove_all_consts<T>::type*; }; // ================ std::any ================= // namespace impl { class holder_base { public: virtual ~holder_base() = default; virtual const std::type_info& type () const = 0; }; template <typename HeldType> class holder : public holder_base { public: template<typename... Args> static holder<HeldType>* create(const Args&... args) { holder* ptr = new holder<HeldType>(); ptr->m_value = std::make_shared<HeldType>(args...); return ptr; } template<typename T> static typename std::enable_if<std::is_base_of<HeldType,T>::value,holder<HeldType>*>::type create(std::shared_ptr<T> ptr_in) { holder* ptr = new holder<HeldType>(); ptr->m_value = ptr_in; return ptr; } const std::type_info& type () const { return typeid(HeldType); } HeldType& value () { return *m_value; } std::shared_ptr<HeldType> ptr () const { return m_value; } private: holder () = default; // Note: we store a shared_ptr rather than a HeldType directly, // since we may store multiple copies of the concrete object. // Since we don't know if the actual object is copiable, we need // to store copiable pointers (hence, cannot use unique_ptr). std::shared_ptr<HeldType> m_value; }; } // namespace impl class any { public: any () = default; template<typename T, typename... Args> void reset (Args... args) { m_content.reset( impl::holder<T>::create(args...) ); } impl::holder_base& content () const { error::runtime_check(static_cast<bool>(m_content), "Error! Object not yet initialized.\n", -1); return *m_content; } impl::holder_base* content_ptr () const { return m_content.get(); } private: std::shared_ptr<impl::holder_base> m_content; }; template<typename ConcreteType> bool any_is_type (const any& src) { const auto& src_type = src.content().type(); const auto& req_type = typeid(ConcreteType); return src_type==req_type; } template<typename ConcreteType> ConcreteType& any_cast (any& src) { const auto& src_type = src.content().type(); const auto& req_type = typeid(ConcreteType); error::runtime_check(src_type==req_type, std::string("Error! Invalid cast requested, from '") + src_type.name() + "' to '" + req_type.name() + "'.\n", -1); impl::holder<ConcreteType>* ptr = dynamic_cast<impl::holder<ConcreteType>*>(src.content_ptr()); error::runtime_check(ptr!=nullptr, "Error! Failed dynamic_cast during any_cast. This is an internal problem, please, contact developers.\n", -1); return ptr->value(); } template<typename ConcreteType> const ConcreteType& any_cast (const any& src) { const auto& src_type = src.content().type(); const auto& req_type = typeid(ConcreteType); error::runtime_check(src_type==req_type, std::string("Error! Invalid cast requested, from '") + src_type.name() + "' to '" + req_type.name() + "'.\n", -1); impl::holder<ConcreteType>* ptr = dynamic_cast<impl::holder<ConcreteType>*>(src.content_ptr()); error::runtime_check(ptr!=nullptr, "Error! Failed dynamic_cast during any_cast. This is an internal problem, please, contact developers.\n", -1); return ptr->value(); } template<typename ConcreteType> std::shared_ptr<ConcreteType> any_ptr_cast (any& src) { const auto& src_type = src.content().type(); const auto& req_type = typeid(ConcreteType); error::runtime_check(src_type==req_type, std::string("Error! Invalid cast requested, from '") + src_type.name() + "' to '" + req_type.name() + "'.\n", -1); impl::holder<ConcreteType>* ptr = dynamic_cast<impl::holder<ConcreteType>*>(src.content_ptr()); error::runtime_check(ptr!=nullptr, "Error! Failed dynamic_cast during any_cast. This is an internal problem, please, contact developers.\n", -1); return ptr->ptr(); } } // namespace util } // namespace scream #endif // SCREAM_STD_META_HPP
29.109827
157
0.691422
AaronDonahue
1b0ecd9d9b84ecee10157c72e9177550b3170fc2
1,200
hpp
C++
WinFelix/EncodingRenderer.hpp
42Bastian/Felix
3c0b31a245a7c73bae97ad39a378edcdde1e386d
[ "MIT" ]
19
2021-10-31T20:57:14.000Z
2022-03-22T11:48:56.000Z
WinFelix/EncodingRenderer.hpp
42Bastian/Felix
3c0b31a245a7c73bae97ad39a378edcdde1e386d
[ "MIT" ]
99
2021-10-29T20:31:09.000Z
2022-02-09T12:24:03.000Z
WinFelix/EncodingRenderer.hpp
42Bastian/Felix
3c0b31a245a7c73bae97ad39a378edcdde1e386d
[ "MIT" ]
3
2021-11-05T15:14:41.000Z
2021-12-11T14:16:11.000Z
#pragma once class IEncoder; class EncodingRenderer { public: EncodingRenderer( std::shared_ptr<IEncoder> encoder, ComPtr<ID3D11Device> pD3DDevice, ComPtr<ID3D11DeviceContext> pImmediateContext, boost::rational<int32_t> refreshRate ); void renderEncoding( ID3D11ShaderResourceView* srv ); private: std::shared_ptr<IEncoder> mEncoder; ComPtr<ID3D11Device> mD3DDevice; ComPtr<ID3D11DeviceContext> mImmediateContext; ComPtr<ID3D11Texture2D> mPreStagingY; ComPtr<ID3D11Texture2D> mPreStagingU; ComPtr<ID3D11Texture2D> mPreStagingV; ComPtr<ID3D11Texture2D> mStagingY; ComPtr<ID3D11Texture2D> mStagingU; ComPtr<ID3D11Texture2D> mStagingV; ComPtr<ID3D11UnorderedAccessView> mPreStagingYUAV; ComPtr<ID3D11UnorderedAccessView> mPreStagingUUAV; ComPtr<ID3D11UnorderedAccessView> mPreStagingVUAV; ComPtr<ID3D11Buffer> mVSizeCB; ComPtr<ID3D11ComputeShader> mRendererYUVCS; struct CBVSize { uint32_t vscale; uint32_t padding1; uint32_t padding2; uint32_t padding3; } mCb; boost::rational<int32_t> mRefreshRate; };
30.769231
175
0.706667
42Bastian
1b17a79dbcbd4f9185be1bf7554e09d938888aea
6,191
cpp
C++
Compiler/AST/ASTExpr.cpp
rozaxe/emojicode
de62ef1871859429e569e4275c38c18bd43c5271
[ "Artistic-2.0" ]
1
2018-12-31T03:57:28.000Z
2018-12-31T03:57:28.000Z
Compiler/AST/ASTExpr.cpp
rozaxe/emojicode
de62ef1871859429e569e4275c38c18bd43c5271
[ "Artistic-2.0" ]
null
null
null
Compiler/AST/ASTExpr.cpp
rozaxe/emojicode
de62ef1871859429e569e4275c38c18bd43c5271
[ "Artistic-2.0" ]
1
2019-01-01T13:34:14.000Z
2019-01-01T13:34:14.000Z
// // ASTExpr.cpp // Emojicode // // Created by Theo Weidmann on 03/08/2017. // Copyright © 2017 Theo Weidmann. All rights reserved. // #include "ASTExpr.hpp" #include "Analysis/FunctionAnalyser.hpp" #include "Compiler.hpp" #include "Functions/Initializer.hpp" #include "MemoryFlowAnalysis/MFFunctionAnalyser.hpp" #include "Scoping/SemanticScoper.hpp" #include "Types/Class.hpp" #include "Types/Enum.hpp" #include "Types/TypeExpectation.hpp" namespace EmojicodeCompiler { void ASTUnaryMFForwarding::analyseMemoryFlow(MFFunctionAnalyser *analyser, MFFlowCategory type) { expr_->analyseMemoryFlow(analyser, type); } Type ASTTypeAsValue::analyse(ExpressionAnalyser *analyser, const TypeExpectation &expectation) { auto &type = type_->analyseType(analyser->typeContext()); ASTTypeValueType::checkTypeValue(tokenType_, type, analyser->typeContext(), position()); return Type(MakeTypeAsValue, type); } Type ASTSizeOf::analyse(ExpressionAnalyser *analyser, const TypeExpectation &expectation) { type_->analyseType(analyser->typeContext()); return analyser->integer(); } Type ASTConditionalAssignment::analyse(ExpressionAnalyser *analyser, const TypeExpectation &expectation) { Type t = analyser->expect(TypeExpectation(false, false), &expr_); if (t.unboxedType() != TypeType::Optional) { throw CompilerError(position(), "Condition assignment can only be used with optionals."); } t = t.optionalType(); auto &variable = analyser->scoper().currentScope().declareVariable(varName_, t, true, position()); variable.initialize(); varId_ = variable.id(); return analyser->boolean(); } void ASTConditionalAssignment::analyseMemoryFlow(MFFunctionAnalyser *analyser, MFFlowCategory type) { analyser->recordVariableSet(varId_, expr_.get(), expr_->expressionType().optionalType()); analyser->take(expr_.get()); } Type ASTSuper::analyse(ExpressionAnalyser *analyser, const TypeExpectation &expectation) { if (isSuperconstructorRequired(analyser->functionType())) { analyseSuperInit(analyser); return Type::noReturn(); } if (analyser->functionType() != FunctionType::ObjectMethod) { throw CompilerError(position(), "Not within an object-context."); } Class *superclass = analyser->typeContext().calleeType().klass()->superclass(); if (superclass == nullptr) { throw CompilerError(position(), "Class has no superclass."); } function_ = superclass->getMethod(name_, Type(superclass), analyser->typeContext(), args_.mood(), position()); calleeType_ = Type(superclass); return analyser->analyseFunctionCall(&args_, calleeType_, function_); } void ASTSuper::analyseSuperInit(ExpressionAnalyser *analyser) { if (analyser->typeContext().calleeType().klass()->superclass() == nullptr) { throw CompilerError(position(), "Class does not have a super class"); } if (analyser->pathAnalyser().hasPotentially(PathAnalyserIncident::CalledSuperInitializer)) { analyser->compiler()->error(CompilerError(position(), "Superinitializer might have already been called.")); } analyser->scoper().instanceScope()->uninitializedVariablesCheck(position(), "Instance variable \"", "\" must be " "initialized before calling the superinitializer."); init_ = true; auto eclass = analyser->typeContext().calleeType().klass(); auto initializer = eclass->superclass()->getInitializer(name_, Type(eclass), analyser->typeContext(), position()); calleeType_ = Type(eclass->superclass()); analyser->analyseFunctionCall(&args_, calleeType_, initializer); analyseSuperInitErrorProneness(analyser, initializer); function_ = initializer; analyser->pathAnalyser().recordIncident(PathAnalyserIncident::CalledSuperInitializer); } void ASTSuper::analyseMemoryFlow(MFFunctionAnalyser *analyser, MFFlowCategory type) { analyser->recordThis(function_->memoryFlowTypeForThis()); analyser->analyseFunctionCall(&args_, nullptr, function_); } void ASTSuper::analyseSuperInitErrorProneness(ExpressionAnalyser *eanalyser, const Initializer *initializer) { auto analyser = dynamic_cast<FunctionAnalyser *>(eanalyser); if (initializer->errorProne()) { auto thisInitializer = dynamic_cast<const Initializer*>(analyser->function()); if (!thisInitializer->errorProne()) { throw CompilerError(position(), "Cannot call an error-prone super initializer in a non ", "error-prone initializer."); } if (!initializer->errorType()->type().identicalTo(thisInitializer->errorType()->type(), analyser->typeContext(), nullptr)) { throw CompilerError(position(), "Super initializer must have same error enum type."); } manageErrorProneness_ = true; analyseInstanceVariables(analyser); } } Type ASTCallableCall::analyse(ExpressionAnalyser *analyser, const TypeExpectation &expectation) { Type type = analyser->expect(TypeExpectation(false, false), &callable_); if (type.type() != TypeType::Callable) { throw CompilerError(position(), "Given value is not callable."); } if (args_.args().size() != type.genericArguments().size() - 1) { throw CompilerError(position(), "Callable expects ", type.genericArguments().size() - 1, " arguments but ", args_.args().size(), " were supplied."); } for (size_t i = 1; i < type.genericArguments().size(); i++) { analyser->expectType(type.genericArguments()[i], &args_.args()[i - 1]); } return type.genericArguments()[0]; } void ASTCallableCall::analyseMemoryFlow(MFFunctionAnalyser *analyser, MFFlowCategory type) { callable_->analyseMemoryFlow(analyser, MFFlowCategory::Borrowing); for (auto &arg : args_.args()) { analyser->take(arg.get()); arg->analyseMemoryFlow(analyser, MFFlowCategory::Escaping); // We cannot at all say what the callable will do. } } } // namespace EmojicodeCompiler
42.696552
120
0.689065
rozaxe
1b19c1da753967c960e5297f2bd9a409517e6f77
31,795
cpp
C++
libs/vision/src/tracking.cpp
mrliujie/mrpt-learning-code
7b41a9501fc35c36580c93bc1499f5a36d26c216
[ "BSD-3-Clause" ]
2
2020-04-21T08:51:21.000Z
2022-03-21T10:47:52.000Z
libs/vision/src/tracking.cpp
qifengl/mrpt
979a458792273a86ec5ab105e0cd6c963c65ea73
[ "BSD-3-Clause" ]
null
null
null
libs/vision/src/tracking.cpp
qifengl/mrpt
979a458792273a86ec5ab105e0cd6c963c65ea73
[ "BSD-3-Clause" ]
null
null
null
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include "vision-precomp.h" // Precompiled headers #include <mrpt/vision/tracking.h> #include <mrpt/vision/CFeatureExtraction.h> // Universal include for all versions of OpenCV #include <mrpt/otherlibs/do_opencv_includes.h> using namespace mrpt; using namespace mrpt::vision; using namespace mrpt::img; using namespace mrpt::tfest; using namespace mrpt::math; using namespace std; // ------------------------------- internal helper templates // --------------------------------- namespace mrpt::vision::detail { template <typename FEATLIST> inline void trackFeatures_checkResponses( FEATLIST& featureList, const CImage& cur_gray, const float minimum_KLT_response, const unsigned int KLT_response_half_win, const unsigned int max_x, const unsigned int max_y); template <> inline void trackFeatures_checkResponses<CFeatureList>( CFeatureList& featureList, const CImage& cur_gray, const float minimum_KLT_response, const unsigned int KLT_response_half_win, const unsigned int max_x, const unsigned int max_y) { const auto itFeatEnd = featureList.end(); for (auto itFeat = featureList.begin(); itFeat != itFeatEnd; ++itFeat) { CFeature* ft = itFeat->get(); if (ft->track_status != status_TRACKED) continue; // Skip if it's not correctly tracked. const unsigned int x = ft->x; const unsigned int y = ft->y; if (x > KLT_response_half_win && y > KLT_response_half_win && x < max_x && y < max_y) { // Update response: ft->response = cur_gray.KLT_response(x, y, KLT_response_half_win); // Is it good enough? // http://grooveshark.com/s/Goonies+Are+Good+Enough/2beBfO?src=5 if (ft->response < minimum_KLT_response) { // Nope! ft->track_status = status_LOST; } } else { // Out of bounds ft->response = 0; ft->track_status = status_OOB; } } } // end of trackFeatures_checkResponses<> template <class FEAT_LIST> inline void trackFeatures_checkResponses_impl_simple( FEAT_LIST& featureList, const CImage& cur_gray, const float minimum_KLT_response, const unsigned int KLT_response_half_win, const unsigned int max_x_, const unsigned int max_y_) { if (featureList.empty()) return; using pixel_coord_t = typename FEAT_LIST::feature_t::pixel_coord_t; const auto half_win = static_cast<pixel_coord_t>(KLT_response_half_win); const auto max_x = static_cast<pixel_coord_t>(max_x_); const auto max_y = static_cast<pixel_coord_t>(max_y_); for (int N = featureList.size() - 1; N >= 0; --N) { typename FEAT_LIST::feature_t& ft = featureList[N]; if (ft.track_status != status_TRACKED) continue; // Skip if it's not correctly tracked. if (ft.pt.x > half_win && ft.pt.y > half_win && ft.pt.x < max_x && ft.pt.y < max_y) { // Update response: ft.response = cur_gray.KLT_response(ft.pt.x, ft.pt.y, KLT_response_half_win); // Is it good enough? // http://grooveshark.com/s/Goonies+Are+Good+Enough/2beBfO?src=5 if (ft.response < minimum_KLT_response) { // Nope! ft.track_status = status_LOST; } } else { // Out of bounds ft.response = 0; ft.track_status = status_OOB; } } } // end of trackFeatures_checkResponses<> template <> inline void trackFeatures_checkResponses<TSimpleFeatureList>( TSimpleFeatureList& featureList, const CImage& cur_gray, const float minimum_KLT_response, const unsigned int KLT_response_half_win, const unsigned int max_x, const unsigned int max_y) { trackFeatures_checkResponses_impl_simple<TSimpleFeatureList>( featureList, cur_gray, minimum_KLT_response, KLT_response_half_win, max_x, max_y); } template <> inline void trackFeatures_checkResponses<TSimpleFeaturefList>( TSimpleFeaturefList& featureList, const CImage& cur_gray, const float minimum_KLT_response, const unsigned int KLT_response_half_win, const unsigned int max_x, const unsigned int max_y) { trackFeatures_checkResponses_impl_simple<TSimpleFeaturefList>( featureList, cur_gray, minimum_KLT_response, KLT_response_half_win, max_x, max_y); } template <typename FEATLIST> inline void trackFeatures_updatePatch( FEATLIST& featureList, const CImage& cur_gray); template <> inline void trackFeatures_updatePatch<CFeatureList>( CFeatureList& featureList, const CImage& cur_gray) { for (auto& itFeat : featureList) { CFeature* ft = itFeat.get(); if (ft->track_status != status_TRACKED) continue; // Skip if it's not correctly tracked. const size_t patch_width = ft->patch.getWidth(); const size_t patch_height = ft->patch.getHeight(); if (patch_width > 0 && patch_height > 0) { try { const int offset = (int)patch_width / 2; // + 1; cur_gray.extract_patch( ft->patch, round(ft->x) - offset, round(ft->y) - offset, patch_width, patch_height); } catch (std::exception&) { ft->track_status = status_OOB; // Out of bounds! } } } } // end of trackFeatures_updatePatch<> template <> inline void trackFeatures_updatePatch<TSimpleFeatureList>( TSimpleFeatureList& featureList, const CImage& cur_gray) { MRPT_UNUSED_PARAM(featureList); MRPT_UNUSED_PARAM(cur_gray); // This list type does not have patch stored explicitly } // end of trackFeatures_updatePatch<> template <> inline void trackFeatures_updatePatch<TSimpleFeaturefList>( TSimpleFeaturefList& featureList, const CImage& cur_gray) { MRPT_UNUSED_PARAM(featureList); MRPT_UNUSED_PARAM(cur_gray); // This list type does not have patch stored explicitly } // end of trackFeatures_updatePatch<> template <typename FEATLIST> inline void trackFeatures_addNewFeats( FEATLIST& featureList, const TSimpleFeatureList& new_feats, const std::vector<size_t>& sorted_indices, const size_t nNewToCheck, const size_t maxNumFeatures, const float minimum_KLT_response_to_add, const double threshold_sqr_dist_to_add_new, const size_t patchSize, const CImage& cur_gray, TFeatureID& max_feat_ID_at_input); template <> inline void trackFeatures_addNewFeats<CFeatureList>( CFeatureList& featureList, const TSimpleFeatureList& new_feats, const std::vector<size_t>& sorted_indices, const size_t nNewToCheck, const size_t maxNumFeatures, const float minimum_KLT_response_to_add, const double threshold_sqr_dist_to_add_new, const size_t patchSize, const CImage& cur_gray, TFeatureID& max_feat_ID_at_input) { const TImageSize imgSize = cur_gray.getSize(); const int offset = (int)patchSize / 2 + 1; const int w_off = int(imgSize.x - offset); const int h_off = int(imgSize.y - offset); for (size_t i = 0; i < nNewToCheck && featureList.size() < maxNumFeatures; i++) { const TSimpleFeature& feat = new_feats[sorted_indices[i]]; if (feat.response < minimum_KLT_response_to_add) continue; double min_dist_sqr = square(10000); if (!featureList.empty()) { // m_timlog.enter("[CGenericFeatureTracker] add new // features.kdtree"); min_dist_sqr = featureList.kdTreeClosestPoint2DsqrError(feat.pt.x, feat.pt.y); // m_timlog.leave("[CGenericFeatureTracker] add new // features.kdtree"); } if (min_dist_sqr > threshold_sqr_dist_to_add_new && feat.pt.x > offset && feat.pt.y > offset && feat.pt.x < w_off && feat.pt.y < h_off) { // Add new feature: CFeature::Ptr ft = mrpt::make_aligned_shared<CFeature>(); ft->type = featFAST; ft->ID = ++max_feat_ID_at_input; ft->x = feat.pt.x; ft->y = feat.pt.y; ft->response = feat.response; ft->orientation = 0; ft->scale = 1; ft->patchSize = patchSize; // The size of the feature patch if (patchSize > 0) cur_gray.extract_patch( ft->patch, round(ft->x) - offset, round(ft->y) - offset, patchSize, patchSize); // Image patch surronding the feature featureList.push_back(ft); } } } // end of trackFeatures_addNewFeats<> template <class FEAT_LIST> inline void trackFeatures_addNewFeats_simple_list( FEAT_LIST& featureList, const TSimpleFeatureList& new_feats, const std::vector<size_t>& sorted_indices, const size_t nNewToCheck, const size_t maxNumFeatures, const float minimum_KLT_response_to_add, const double threshold_sqr_dist_to_add_new, const size_t patchSize, const CImage& cur_gray, TFeatureID& max_feat_ID_at_input) { #if 0 // Brute-force version: const int max_manhatan_dist = std::sqrt(2*threshold_sqr_dist_to_add_new); for (size_t i=0;i<nNewToCheck && featureList.size()<maxNumFeatures;i++) { const TSimpleFeature &feat = new_feats[ sorted_indices[i] ]; if (feat.response<minimum_KLT_response_to_add) break; // continue; // Check the min-distance: int manh_dist = std::numeric_limits<int>::max(); for (size_t j=0;j<featureList.size();j++) { const TSimpleFeature &existing = featureList[j]; const int d = std::abs(existing.pt.x-feat.pt.x)+std::abs(existing.pt.y-feat.pt.y); mrpt::keep_min(manh_dist, d); } if (manh_dist<max_manhatan_dist) continue; // Already occupied! skip. // OK: accept it featureList.push_back_fast(feat.pt.x,feat.pt.y); // (x,y) //featureList.mark_kdtree_as_outdated(); // Fill out the rest of data: TSimpleFeature &newFeat = featureList.back(); newFeat.ID = ++max_feat_ID_at_input; newFeat.response = feat.response; newFeat.octave = 0; /** Inactive: right after detection, and before being tried to track */ newFeat.track_status = status_IDLE; } #elif 0 // Version with an occupancy grid: const int grid_cell_log2 = round( std::log(std::sqrt(threshold_sqr_dist_to_add_new) * 0.5) / std::log(2.0)); int grid_lx = 1 + (cur_gray.getWidth() >> grid_cell_log2); int grid_ly = 1 + (cur_gray.getHeight() >> grid_cell_log2); mrpt::math::CMatrixBool& occupied_sections = featureList.getOccupiedSectionsMatrix(); occupied_sections.setSize( grid_lx, grid_ly); // See the comments above for an explanation. occupied_sections.fillAll(false); for (size_t i = 0; i < featureList.size(); i++) { const TSimpleFeature& feat = featureList[i]; const int section_idx_x = feat.pt.x >> grid_cell_log2; const int section_idx_y = feat.pt.y >> grid_cell_log2; if (!section_idx_x || !section_idx_y || section_idx_x >= grid_lx - 1 || section_idx_y >= grid_ly - 1) continue; // This may be too radical, but speeds up the logic // below... // Mark sections as occupied bool* ptr1 = &occupied_sections.get_unsafe(section_idx_x - 1, section_idx_y - 1); bool* ptr2 = &occupied_sections.get_unsafe(section_idx_x - 1, section_idx_y); bool* ptr3 = &occupied_sections.get_unsafe(section_idx_x - 1, section_idx_y + 1); ptr1[0] = ptr1[1] = ptr1[2] = true; ptr2[0] = ptr2[1] = ptr2[2] = true; ptr3[0] = ptr3[1] = ptr3[2] = true; } for (size_t i = 0; i < nNewToCheck && featureList.size() < maxNumFeatures; i++) { const TSimpleFeature& feat = new_feats[sorted_indices[i]]; if (feat.response < minimum_KLT_response_to_add) break; // continue; // Check the min-distance: const int section_idx_x = feat.pt.x >> grid_cell_log2; const int section_idx_y = feat.pt.y >> grid_cell_log2; if (!section_idx_x || !section_idx_y || section_idx_x >= grid_lx - 2 || section_idx_y >= grid_ly - 2) continue; // This may be too radical, but speeds up the logic // below... if (occupied_sections(section_idx_x, section_idx_y)) continue; // Already occupied! skip. // Mark section as occupied bool* ptr1 = &occupied_sections.get_unsafe(section_idx_x - 1, section_idx_y - 1); bool* ptr2 = &occupied_sections.get_unsafe(section_idx_x - 1, section_idx_y); bool* ptr3 = &occupied_sections.get_unsafe(section_idx_x - 1, section_idx_y + 1); ptr1[0] = ptr1[1] = ptr1[2] = true; ptr2[0] = ptr2[1] = ptr2[2] = true; ptr3[0] = ptr3[1] = ptr3[2] = true; // OK: accept it featureList.push_back_fast(feat.pt.x, feat.pt.y); // (x,y) // featureList.mark_kdtree_as_outdated(); // Fill out the rest of data: TSimpleFeature& newFeat = featureList.back(); newFeat.ID = ++max_feat_ID_at_input; newFeat.response = feat.response; newFeat.octave = 0; /** Inactive: right after detection, and before being tried to track */ newFeat.track_status = status_IDLE; } #else MRPT_UNUSED_PARAM(patchSize); MRPT_UNUSED_PARAM(cur_gray); // Version with KD-tree CFeatureListKDTree<typename FEAT_LIST::feature_t> kdtree( featureList.getVector()); for (size_t i = 0; i < nNewToCheck && featureList.size() < maxNumFeatures; i++) { const TSimpleFeature& feat = new_feats[sorted_indices[i]]; if (feat.response < minimum_KLT_response_to_add) break; // continue; // Check the min-distance: double min_dist_sqr = std::numeric_limits<double>::max(); if (!featureList.empty()) { // m_timlog.enter("[CGenericFeatureTracker] add new // features.kdtree"); min_dist_sqr = kdtree.kdTreeClosestPoint2DsqrError(feat.pt.x, feat.pt.y); // m_timlog.leave("[CGenericFeatureTracker] add new // features.kdtree"); } if (min_dist_sqr > threshold_sqr_dist_to_add_new) { // OK: accept it featureList.push_back_fast(feat.pt.x, feat.pt.y); // (x,y) kdtree.mark_as_outdated(); // Fill out the rest of data: typename FEAT_LIST::feature_t& newFeat = featureList.back(); newFeat.ID = ++max_feat_ID_at_input; newFeat.response = feat.response; newFeat.octave = 0; /** Inactive: right after detection, and before being tried to track */ newFeat.track_status = status_IDLE; } } #endif } // end of trackFeatures_addNewFeats<> template <> inline void trackFeatures_addNewFeats<TSimpleFeatureList>( TSimpleFeatureList& featureList, const TSimpleFeatureList& new_feats, const std::vector<size_t>& sorted_indices, const size_t nNewToCheck, const size_t maxNumFeatures, const float minimum_KLT_response_to_add, const double threshold_sqr_dist_to_add_new, const size_t patchSize, const CImage& cur_gray, TFeatureID& max_feat_ID_at_input) { trackFeatures_addNewFeats_simple_list<TSimpleFeatureList>( featureList, new_feats, sorted_indices, nNewToCheck, maxNumFeatures, minimum_KLT_response_to_add, threshold_sqr_dist_to_add_new, patchSize, cur_gray, max_feat_ID_at_input); } template <> inline void trackFeatures_addNewFeats<TSimpleFeaturefList>( TSimpleFeaturefList& featureList, const TSimpleFeatureList& new_feats, const std::vector<size_t>& sorted_indices, const size_t nNewToCheck, const size_t maxNumFeatures, const float minimum_KLT_response_to_add, const double threshold_sqr_dist_to_add_new, const size_t patchSize, const CImage& cur_gray, TFeatureID& max_feat_ID_at_input) { trackFeatures_addNewFeats_simple_list<TSimpleFeaturefList>( featureList, new_feats, sorted_indices, nNewToCheck, maxNumFeatures, minimum_KLT_response_to_add, threshold_sqr_dist_to_add_new, patchSize, cur_gray, max_feat_ID_at_input); } // Return the number of removed features template <typename FEATLIST> inline size_t trackFeatures_deleteOOB( FEATLIST& trackedFeats, const size_t img_width, const size_t img_height, const int MIN_DIST_MARGIN_TO_STOP_TRACKING); template <typename FEATLIST> inline size_t trackFeatures_deleteOOB_impl_simple_feat( FEATLIST& trackedFeats, const size_t img_width, const size_t img_height, const int MIN_DIST_MARGIN_TO_STOP_TRACKING) { if (trackedFeats.empty()) return 0; std::vector<size_t> survival_idxs; const size_t N = trackedFeats.size(); // 1st: Build list of survival indexes: survival_idxs.reserve(N); for (size_t i = 0; i < N; i++) { const typename FEATLIST::feature_t& ft = trackedFeats[i]; const TFeatureTrackStatus status = ft.track_status; bool eras = (status_TRACKED != status && status_IDLE != status); if (!eras) { // Also, check if it's too close to the image border: const int x = ft.pt.x; const int y = ft.pt.y; if (x < MIN_DIST_MARGIN_TO_STOP_TRACKING || y < MIN_DIST_MARGIN_TO_STOP_TRACKING || x > static_cast<int>( img_width - MIN_DIST_MARGIN_TO_STOP_TRACKING) || y > static_cast<int>( img_height - MIN_DIST_MARGIN_TO_STOP_TRACKING)) { eras = true; } } if (!eras) survival_idxs.push_back(i); } // 2nd: Build updated list: const size_t N2 = survival_idxs.size(); const size_t n_removed = N - N2; for (size_t i = 0; i < N2; i++) { if (survival_idxs[i] != i) trackedFeats[i] = trackedFeats[survival_idxs[i]]; } trackedFeats.resize(N2); return n_removed; } // end of trackFeatures_deleteOOB template <> inline size_t trackFeatures_deleteOOB( TSimpleFeatureList& trackedFeats, const size_t img_width, const size_t img_height, const int MIN_DIST_MARGIN_TO_STOP_TRACKING) { return trackFeatures_deleteOOB_impl_simple_feat<TSimpleFeatureList>( trackedFeats, img_width, img_height, MIN_DIST_MARGIN_TO_STOP_TRACKING); } template <> inline size_t trackFeatures_deleteOOB( TSimpleFeaturefList& trackedFeats, const size_t img_width, const size_t img_height, const int MIN_DIST_MARGIN_TO_STOP_TRACKING) { return trackFeatures_deleteOOB_impl_simple_feat<TSimpleFeaturefList>( trackedFeats, img_width, img_height, MIN_DIST_MARGIN_TO_STOP_TRACKING); } template <> inline size_t trackFeatures_deleteOOB( CFeatureList& trackedFeats, const size_t img_width, const size_t img_height, const int MIN_DIST_MARGIN_TO_STOP_TRACKING) { auto itFeat = trackedFeats.begin(); size_t n_removed = 0; while (itFeat != trackedFeats.end()) { const TFeatureTrackStatus status = (*itFeat)->track_status; bool eras = (status_TRACKED != status && status_IDLE != status); if (!eras) { // Also, check if it's too close to the image border: const float x = (*itFeat)->x; const float y = (*itFeat)->y; if (x < MIN_DIST_MARGIN_TO_STOP_TRACKING || y < MIN_DIST_MARGIN_TO_STOP_TRACKING || x > (img_width - MIN_DIST_MARGIN_TO_STOP_TRACKING) || y > (img_height - MIN_DIST_MARGIN_TO_STOP_TRACKING)) { eras = true; } } if (eras) // Erase or keep? { itFeat = trackedFeats.erase(itFeat); n_removed++; } else ++itFeat; } return n_removed; } // end of trackFeatures_deleteOOB } // namespace mrpt::vision::detail // ---------------------------- end of internal helper templates // ------------------------------- void CGenericFeatureTracker::trackFeatures_impl( const CImage& old_img, const CImage& new_img, TSimpleFeaturefList& inout_featureList) { MRPT_UNUSED_PARAM(old_img); MRPT_UNUSED_PARAM(new_img); MRPT_UNUSED_PARAM(inout_featureList); THROW_EXCEPTION("Method not implemented by derived class!"); } /** Perform feature tracking from "old_img" to "new_img", with a (possibly *empty) list of previously tracked features "featureList". * This is a list of parameters (in "extraParams") accepted by ALL *implementations of feature tracker (see each derived class for more specific *parameters). * - "add_new_features" (Default=0). If set to "1", new features will be *also *added to the existing ones in areas of the image poor of features. * This method actually first call the pure virtual "trackFeatures_impl" *method, then implements the optional detection of new features if *"add_new_features"!=0. */ template <typename FEATLIST> void CGenericFeatureTracker::internal_trackFeatures( const CImage& old_img, const CImage& new_img, FEATLIST& featureList) { m_timlog.enter( "[CGenericFeatureTracker::trackFeatures] Complete iteration"); const size_t img_width = new_img.getWidth(); const size_t img_height = new_img.getHeight(); // Take the maximum ID of "old" features so new feats (if // "add_new_features==true") will be id+1, id+2, ... TFeatureID max_feat_ID_at_input = 0; if (!featureList.empty()) max_feat_ID_at_input = featureList.getMaxID(); // Grayscale images // ========================================= m_timlog.enter("[CGenericFeatureTracker] Convert grayscale"); const CImage prev_gray(old_img, FAST_REF_OR_CONVERT_TO_GRAY); const CImage cur_gray(new_img, FAST_REF_OR_CONVERT_TO_GRAY); m_timlog.leave("[CGenericFeatureTracker] Convert grayscale"); // ================================= // (1st STEP) Do the actual tracking // ================================= m_newly_detected_feats.clear(); m_timlog.enter("[CGenericFeatureTracker] trackFeatures_impl"); trackFeatures_impl(prev_gray, cur_gray, featureList); m_timlog.leave("[CGenericFeatureTracker] trackFeatures_impl"); // ======================================================== // (2nd STEP) For successfully followed features, check their KLT response?? // ======================================================== const int check_KLT_response_every = extra_params.getWithDefaultVal("check_KLT_response_every", 0); const float minimum_KLT_response = extra_params.getWithDefaultVal("minimum_KLT_response", 5); const unsigned int KLT_response_half_win = extra_params.getWithDefaultVal("KLT_response_half_win", 4); if (check_KLT_response_every > 0 && ++m_check_KLT_counter >= size_t(check_KLT_response_every)) { m_timlog.enter("[CGenericFeatureTracker] check KLT responses"); m_check_KLT_counter = 0; const unsigned int max_x = img_width - KLT_response_half_win; const unsigned int max_y = img_height - KLT_response_half_win; detail::trackFeatures_checkResponses( featureList, cur_gray, minimum_KLT_response, KLT_response_half_win, max_x, max_y); m_timlog.leave("[CGenericFeatureTracker] check KLT responses"); } // end check_KLT_response_every // ============================================================ // (3rd STEP) Remove Out-of-bounds or badly tracked features // or those marked as "bad" by their low KLT response // ============================================================ const bool remove_lost_features = extra_params.getWithDefaultVal("remove_lost_features", 0) != 0; if (remove_lost_features) { m_timlog.enter("[CGenericFeatureTracker] removal of OOB"); static const int MIN_DIST_MARGIN_TO_STOP_TRACKING = 10; const size_t nRemoved = detail::trackFeatures_deleteOOB( featureList, img_width, img_height, MIN_DIST_MARGIN_TO_STOP_TRACKING); m_timlog.leave("[CGenericFeatureTracker] removal of OOB"); last_execution_extra_info.num_deleted_feats = nRemoved; } else { last_execution_extra_info.num_deleted_feats = 0; } // ======================================================== // (4th STEP) For successfully followed features, update its patch: // ======================================================== const int update_patches_every = extra_params.getWithDefaultVal("update_patches_every", 0); if (update_patches_every > 0 && ++m_update_patches_counter >= size_t(update_patches_every)) { m_timlog.enter("[CGenericFeatureTracker] update patches"); m_update_patches_counter = 0; // Update the patch for each valid feature: detail::trackFeatures_updatePatch(featureList, cur_gray); m_timlog.leave("[CGenericFeatureTracker] update patches"); } // end if update_patches_every // ======================================================== // (5th STEP) Do detection of new features?? // ======================================================== const bool add_new_features = extra_params.getWithDefaultVal("add_new_features", 0) != 0; const double threshold_dist_to_add_new = extra_params.getWithDefaultVal("add_new_feat_min_separation", 15); // Additional operation: if "add_new_features==true", find new features and // add them in // areas spare of valid features: if (add_new_features) { m_timlog.enter("[CGenericFeatureTracker] add new features"); // Look for new features and save in "m_newly_detected_feats", if // they're not already computed: if (m_newly_detected_feats.empty()) { // Do the detection CFeatureExtraction::detectFeatures_SSE2_FASTER12( cur_gray, m_newly_detected_feats, m_detector_adaptive_thres); } const size_t N = m_newly_detected_feats.size(); last_execution_extra_info.raw_FAST_feats_detected = N; // Extra out info. // Update the adaptive threshold. const size_t desired_num_features = extra_params.getWithDefaultVal( "desired_num_features_adapt", size_t((img_width * img_height) >> 9)); updateAdaptiveNewFeatsThreshold(N, desired_num_features); // Use KLT response instead of the OpenCV's original "response" field: { const unsigned int max_x = img_width - KLT_response_half_win; const unsigned int max_y = img_height - KLT_response_half_win; for (size_t i = 0; i < N; i++) { const unsigned int x = m_newly_detected_feats[i].pt.x; const unsigned int y = m_newly_detected_feats[i].pt.y; if (x > KLT_response_half_win && y > KLT_response_half_win && x < max_x && y < max_y) m_newly_detected_feats[i].response = cur_gray.KLT_response(x, y, KLT_response_half_win); else m_newly_detected_feats[i].response = 0; // Out of bounds } } // Sort them by "response": It's ~100 times faster to sort a list of // indices "sorted_indices" than sorting directly the actual list // of features "m_newly_detected_feats" std::vector<size_t> sorted_indices(N); for (size_t i = 0; i < N; i++) sorted_indices[i] = i; std::sort( sorted_indices.begin(), sorted_indices.end(), KeypointResponseSorter<TSimpleFeatureList>(m_newly_detected_feats)); // For each new good feature, add it to the list of tracked ones only if // it's pretty // isolated: const size_t nNewToCheck = std::min(size_t(1500), N); const double threshold_sqr_dist_to_add_new = square(threshold_dist_to_add_new); const size_t maxNumFeatures = extra_params.getWithDefaultVal("add_new_feat_max_features", 100); const size_t patchSize = extra_params.getWithDefaultVal("add_new_feat_patch_size", 11); const float minimum_KLT_response_to_add = extra_params.getWithDefaultVal("minimum_KLT_response_to_add", 10); // Do it: detail::trackFeatures_addNewFeats( featureList, m_newly_detected_feats, sorted_indices, nNewToCheck, maxNumFeatures, minimum_KLT_response_to_add, threshold_sqr_dist_to_add_new, patchSize, cur_gray, max_feat_ID_at_input); m_timlog.leave("[CGenericFeatureTracker] add new features"); } m_timlog.leave( "[CGenericFeatureTracker::trackFeatures] Complete iteration"); } // end of CGenericFeatureTracker::trackFeatures void CGenericFeatureTracker::trackFeatures( const CImage& old_img, const CImage& new_img, CFeatureList& featureList) { internal_trackFeatures<CFeatureList>(old_img, new_img, featureList); } void CGenericFeatureTracker::trackFeatures( const CImage& old_img, const CImage& new_img, TSimpleFeatureList& featureList) { internal_trackFeatures<TSimpleFeatureList>(old_img, new_img, featureList); } void CGenericFeatureTracker::trackFeatures( const CImage& old_img, const CImage& new_img, TSimpleFeaturefList& featureList) { internal_trackFeatures<TSimpleFeaturefList>(old_img, new_img, featureList); } void CGenericFeatureTracker::updateAdaptiveNewFeatsThreshold( const size_t nNewlyDetectedFeats, const size_t desired_num_features) { const size_t hysteresis_min_num_feats = desired_num_features * 0.9; const size_t hysteresis_max_num_feats = desired_num_features * 1.1; if (nNewlyDetectedFeats < hysteresis_min_num_feats) m_detector_adaptive_thres = std::max( 2.0, std::min( m_detector_adaptive_thres - 1.0, m_detector_adaptive_thres * 0.8)); else if (nNewlyDetectedFeats > hysteresis_max_num_feats) m_detector_adaptive_thres = std::max( m_detector_adaptive_thres + 1.0, m_detector_adaptive_thres * 1.2); } /*------------------------------------------------------------ checkTrackedFeatures -------------------------------------------------------------*/ void vision::checkTrackedFeatures( CFeatureList& leftList, CFeatureList& rightList, vision::TMatchingOptions options) { ASSERT_(leftList.size() == rightList.size()); // std::cout << std::endl << "Tracked features checking ..." << std::endl; CFeatureList::iterator itLeft, itRight; size_t u, v; double res; for (itLeft = leftList.begin(), itRight = rightList.begin(); itLeft != leftList.end();) { bool delFeat = false; if ((*itLeft)->x < 0 || (*itLeft)->y < 0 || // Out of bounds (*itRight)->x < 0 || (*itRight)->y < 0 || // Out of bounds fabs((*itLeft)->y - (*itRight)->y) > options .epipolar_TH) // Not fulfillment of the epipolar constraint { // Show reason std::cout << "Bad tracked match:"; if ((*itLeft)->x < 0 || (*itLeft)->y < 0 || (*itRight)->x < 0 || (*itRight)->y < 0) std::cout << " Out of bounds: (" << (*itLeft)->x << "," << (*itLeft)->y << " & (" << (*itRight)->x << "," << (*itRight)->y << ")" << std::endl; if (fabs((*itLeft)->y - (*itRight)->y) > options.epipolar_TH) std::cout << " Bad row checking: " << fabs((*itLeft)->y - (*itRight)->y) << std::endl; delFeat = true; } else { // Compute cross correlation: openCV_cross_correlation( (*itLeft)->patch, (*itRight)->patch, u, v, res); if (res < options.minCC_TH) { std::cout << "Bad tracked match (correlation failed):" << " CC Value: " << res << std::endl; delFeat = true; } } // end if if (delFeat) // Erase the pair of features { itLeft = leftList.erase(itLeft); itRight = rightList.erase(itRight); } else { itLeft++; itRight++; } } // end for } // end checkTrackedFeatures /*------------------------------------------------------------- filterBadCorrsByDistance -------------------------------------------------------------*/ void vision::filterBadCorrsByDistance( TMatchingPairList& feat_list, unsigned int numberOfSigmas) { ASSERT_(numberOfSigmas > 0); // MRPT_UNUSED_PARAM( numberOfSigmas ); MRPT_START TMatchingPairList::iterator itPair; CMatrix dist; double v_mean, v_std; unsigned int count = 0; dist.setSize(feat_list.size(), 1); // v_mean.resize(1); // v_std.resize(1); // Compute mean and standard deviation of the distance for (itPair = feat_list.begin(); itPair != feat_list.end(); itPair++, count++) { // cout << "(" << itPair->other_x << "," << itPair->other_y << "," << // itPair->this_z << ")" << "- (" << itPair->this_x << "," << // itPair->this_y << "," << itPair->other_z << "): "; // cout << sqrt( square( itPair->other_x - itPair->this_x ) + square( // itPair->other_y - itPair->this_y ) + square( itPair->other_z - // itPair->this_z ) ) << endl; dist(count, 0) = sqrt( square(itPair->other_x - itPair->this_x) + square(itPair->other_y - itPair->this_y) + square(itPair->other_z - itPair->this_z)); } dist.meanAndStdAll(v_mean, v_std); cout << endl << "*****************************************************" << endl; cout << "Mean: " << v_mean << " - STD: " << v_std << endl; cout << endl << "*****************************************************" << endl; // Filter out bad points unsigned int idx = 0; // for( int idx = (int)feat_list.size()-1; idx >= 0; idx-- ) for (itPair = feat_list.begin(); itPair != feat_list.end(); idx++) { // if( dist( idx, 0 ) > 1.2 ) if (fabs(dist(idx, 0) - v_mean) > v_std * numberOfSigmas) { cout << "Outlier deleted: " << dist(idx, 0) << " vs " << v_std * numberOfSigmas << endl; itPair = feat_list.erase(itPair); } else itPair++; } MRPT_END } // end filterBadCorrsByDistance
34.005348
88
0.692436
mrliujie
1b1c2b6586c3a6de8fc761325bb22f65b1775fd5
14,936
cpp
C++
Runtime/Resource/Import/ImageImporter.cpp
slimlime/SpartanEngine
9f1b14dc158eda0e951ee05824c5a4a1084dde14
[ "MIT" ]
null
null
null
Runtime/Resource/Import/ImageImporter.cpp
slimlime/SpartanEngine
9f1b14dc158eda0e951ee05824c5a4a1084dde14
[ "MIT" ]
null
null
null
Runtime/Resource/Import/ImageImporter.cpp
slimlime/SpartanEngine
9f1b14dc158eda0e951ee05824c5a4a1084dde14
[ "MIT" ]
null
null
null
/* Copyright(c) 2016-2021 Panos Karabelas 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. */ //= INCLUDES ========================= #include "Spartan.h" #include "ImageImporter.h" #define FREEIMAGE_LIB #include <FreeImage.h> #include <Utilities.h> #include "../../Threading/Threading.h" #include "../../RHI/RHI_Texture2D.h" //==================================== //= NAMESPACES ===== using namespace std; //================== namespace Spartan { static FREE_IMAGE_FILTER filter_downsample = FREE_IMAGE_FILTER::FILTER_BOX; // A struct that rescaling threads will work with struct RescaleJob { uint32_t width = 0; uint32_t height = 0; uint32_t channel_count = 0; RHI_Texture_Mip* mip = nullptr; bool done = false; RescaleJob(const uint32_t width, const uint32_t height, const uint32_t channel_count) { this->width = width; this->height = height; this->channel_count = channel_count; } }; static uint32_t get_bytes_per_channel(FIBITMAP* bitmap) { if (!bitmap) { LOG_ERROR_INVALID_PARAMETER(); return 0; } const auto type = FreeImage_GetImageType(bitmap); uint32_t size = 0; if (type == FIT_BITMAP) { size = sizeof(BYTE); } else if (type == FIT_UINT16 || type == FIT_RGB16 || type == FIT_RGBA16) { size = sizeof(WORD); } else if (type == FIT_FLOAT || type == FIT_RGBF || type == FIT_RGBAF) { size = sizeof(float); } return size; } static uint32_t get_channel_count(FIBITMAP* bitmap) { if (!bitmap) { LOG_ERROR_INVALID_PARAMETER(); return 0; } const uint32_t bytes_per_pixel = FreeImage_GetLine(bitmap) / FreeImage_GetWidth(bitmap); const uint32_t channel_count = bytes_per_pixel / get_bytes_per_channel(bitmap); return channel_count; } static RHI_Format get_rhi_format(const uint32_t bytes_per_channel, const uint32_t channel_count) { const uint32_t bits_per_channel = bytes_per_channel * 8; if (channel_count == 1) { if (bits_per_channel == 8) return RHI_Format_R8_Unorm; } else if (channel_count == 2) { if (bits_per_channel == 8) return RHI_Format_R8G8_Unorm; } else if (channel_count == 3) { if (bits_per_channel == 32) return RHI_Format_R32G32B32A32_Float; } else if (channel_count == 4) { if (bits_per_channel == 8) return RHI_Format_R8G8B8A8_Unorm; if (bits_per_channel == 16) return RHI_Format_R16G16B16A16_Float; if (bits_per_channel == 32) return RHI_Format_R32G32B32A32_Float; } LOG_ERROR("Could not deduce format"); return RHI_Format_Undefined; } static FIBITMAP* convert_to_32bits(FIBITMAP* bitmap) { if (!bitmap) { LOG_ERROR_INVALID_PARAMETER(); return nullptr; } const auto previous_bitmap = bitmap; bitmap = FreeImage_ConvertTo32Bits(previous_bitmap); if (!bitmap) { LOG_ERROR("Failed (%d bpp, %d channels).", FreeImage_GetBPP(previous_bitmap), get_channel_count(previous_bitmap)); return nullptr; } FreeImage_Unload(previous_bitmap); return bitmap; } static FIBITMAP* apply_bitmap_corrections(FIBITMAP* bitmap) { SP_ASSERT(bitmap != nullptr); // Convert to a standard bitmap. FIT_UINT16 and FIT_RGBA16 are processed without errors // but show up empty in the editor. For now, we convert everything to a standard bitmap. const FREE_IMAGE_TYPE type = FreeImage_GetImageType(bitmap); if (type != FIT_BITMAP) { // FreeImage can't convert FIT_RGBF if (type != FIT_RGBF) { const auto previous_bitmap = bitmap; bitmap = FreeImage_ConvertToType(bitmap, FIT_BITMAP); FreeImage_Unload(previous_bitmap); } } // Convert it to 32 bits (if lower) if (FreeImage_GetBPP(bitmap) < 32) { bitmap = convert_to_32bits(bitmap); } // Most GPUs can't use a 32 bit RGB texture as a color attachment. // Vulkan tells you, your GPU doesn't support it. // D3D11 seems to be doing some sort of emulation under the hood while throwing some warnings regarding sampling it. // So to prevent that, we maintain the 32 bits and convert to an RGBA format. const uint32_t image_bits_per_channel = get_bytes_per_channel(bitmap) * 8; const uint32_t image_channels = get_channel_count(bitmap); const bool is_r32g32b32_float = image_channels == 3 && image_bits_per_channel == 32; if (is_r32g32b32_float) { const auto previous_bitmap = bitmap; bitmap = FreeImage_ConvertToRGBAF(bitmap); FreeImage_Unload(previous_bitmap); } // Convert BGR to RGB (if needed) if (FreeImage_GetBPP(bitmap) == 32) { if (FreeImage_GetRedMask(bitmap) == 0xff0000 && get_channel_count(bitmap) >= 2) { if (!SwapRedBlue32(bitmap)) { LOG_ERROR("Failed to swap red with blue channel"); } } } // Flip it vertically FreeImage_FlipVertical(bitmap); return bitmap; } static FIBITMAP* rescale(FIBITMAP* bitmap, const uint32_t width, const uint32_t height) { if (!bitmap || width == 0 || height == 0) { LOG_ERROR_INVALID_PARAMETER(); return nullptr; } const auto previous_bitmap = bitmap; bitmap = FreeImage_Rescale(previous_bitmap, width, height, filter_downsample); if (!bitmap) { LOG_ERROR("Failed"); return previous_bitmap; } FreeImage_Unload(previous_bitmap); return bitmap; } ImageImporter::ImageImporter(Context* context) { // Initialize m_context = context; FreeImage_Initialise(); // Register error handler const auto free_image_error_handler = [](const FREE_IMAGE_FORMAT fif, const char* message) { const auto text = (message != nullptr) ? message : "Unknown error"; const auto format = (fif != FIF_UNKNOWN) ? FreeImage_GetFormatFromFIF(fif) : "Unknown"; LOG_ERROR("%s, Format: %s", text, format); }; FreeImage_SetOutputMessage(free_image_error_handler); // Get version m_context->GetSubsystem<Settings>()->RegisterThirdPartyLib("FreeImage", FreeImage_GetVersion(), "http://freeimage.sourceforge.net/download.html"); } ImageImporter::~ImageImporter() { FreeImage_DeInitialise(); } bool ImageImporter::Load(const string& file_path, const uint32_t slice_index, RHI_Texture* texture) { SP_ASSERT(texture != nullptr); if (!FileSystem::Exists(file_path)) { LOG_ERROR("Path \"%s\" is invalid.", file_path.c_str()); return false; } // Acquire image format FREE_IMAGE_FORMAT format = FreeImage_GetFileType(file_path.c_str(), 0); format = (format == FIF_UNKNOWN) ? FreeImage_GetFIFFromFilename(file_path.c_str()) : format; // If the format is unknown, try to work it out from the file path if (!FreeImage_FIFSupportsReading(format)) // If the format is still unknown, give up { LOG_ERROR("Unsupported format"); return false; } // Load the image auto bitmap = FreeImage_Load(format, file_path.c_str()); if (!bitmap) { LOG_ERROR("Failed to load \"%s\"", file_path.c_str()); return false; } // Deduce image properties. Important that this is done here, before ApplyBitmapCorrections(), as after that, results for grayscale seem to be always false const bool image_is_transparent = FreeImage_IsTransparent(bitmap); const bool image_is_grayscale = FreeImage_GetColorType(bitmap) == FREE_IMAGE_COLOR_TYPE::FIC_MINISBLACK; // Perform some fix ups bitmap = apply_bitmap_corrections(bitmap); if (!bitmap) { LOG_ERROR("Failed to apply bitmap corrections"); return false; } // Deduce image properties const uint32_t image_bytes_per_channel = get_bytes_per_channel(bitmap); const uint32_t image_channel_count = get_channel_count(bitmap); const RHI_Format image_format = get_rhi_format(image_bytes_per_channel, image_channel_count); // Perform any scaling (if necessary) const auto user_define_dimensions = (texture->GetWidth() != 0 && texture->GetHeight() != 0); const auto dimension_mismatch = (FreeImage_GetWidth(bitmap) != texture->GetWidth() && FreeImage_GetHeight(bitmap) != texture->GetHeight()); const auto scale = user_define_dimensions && dimension_mismatch; bitmap = scale ? rescale(bitmap, texture->GetWidth(), texture->GetHeight()) : bitmap; // Deduce image properties const unsigned int image_width = FreeImage_GetWidth(bitmap); const unsigned int image_height = FreeImage_GetHeight(bitmap); // Fill RGBA vector with the data from the FIBITMAP RHI_Texture_Mip& mip = texture->CreateMip(slice_index); GetBitsFromFibitmap(&mip, bitmap, image_width, image_height, image_channel_count); // If the texture supports mipmaps, generate them if (texture->GetFlags() & RHI_Texture_GenerateMipsWhenLoading) { GenerateMipmaps(bitmap, texture, image_width, image_height, image_channel_count, slice_index); } // Free memory FreeImage_Unload(bitmap); // Fill RHI_Texture with image properties texture->SetBitsPerChannel(image_bytes_per_channel * 8); texture->SetWidth(image_width); texture->SetHeight(image_height); texture->SetChannelCount(image_channel_count); texture->SetTransparency(image_is_transparent); texture->SetFormat(image_format); texture->SetGrayscale(image_is_grayscale); return true; } bool ImageImporter::GetBitsFromFibitmap(RHI_Texture_Mip* mip, FIBITMAP* bitmap, const uint32_t width, const uint32_t height, const uint32_t channels) const { // Validate SP_ASSERT(mip != nullptr); SP_ASSERT(width != 0); SP_ASSERT(height != 0); SP_ASSERT(channels != 0); // Compute expected data size and reserve enough memory const size_t size_bytes = width * height * channels * get_bytes_per_channel(bitmap); if (size_bytes != mip->bytes.size()) { mip->bytes.clear(); mip->bytes.reserve(size_bytes); mip->bytes.resize(size_bytes); } // Copy the data over to our vector const auto bits = FreeImage_GetBits(bitmap); memcpy(&mip->bytes[0], bits, size_bytes); return true; } void ImageImporter::GenerateMipmaps(FIBITMAP* bitmap, RHI_Texture* texture, uint32_t width, uint32_t height, uint32_t channels, const uint32_t slice_index) { // Validate SP_ASSERT(texture != nullptr); // Create a RescaleJob for every mip that we need vector<RescaleJob> jobs; while (width > 1 && height > 1) { width = Math::Helper::Max(width / 2, static_cast<uint32_t>(1)); height = Math::Helper::Max(height / 2, static_cast<uint32_t>(1)); jobs.emplace_back(width, height, channels); // Resize the RHI_Texture vector accordingly const auto size = width * height * channels; RHI_Texture_Mip& mip = texture->CreateMip(slice_index); mip.bytes.reserve(size); mip.bytes.resize(size); } // Pass data pointers (now that the RHI_Texture mip vector has been constructed) for (uint32_t i = 0; i < jobs.size(); i++) { // reminder: i + 1 because the 0 mip is the default image size jobs[i].mip = &texture->GetMip(0, i + 1); } // Parallelize mipmap generation using multiple threads (because FreeImage_Rescale() is expensive) auto threading = m_context->GetSubsystem<Threading>(); for (auto& job : jobs) { threading->AddTask([this, &job, &bitmap]() { FIBITMAP* bitmap_scaled = FreeImage_Rescale(bitmap, job.width, job.height, filter_downsample); if (!GetBitsFromFibitmap(job.mip, bitmap_scaled, job.width, job.height, job.channel_count)) { LOG_ERROR("Failed to create mip level %dx%d", job.width, job.height); } FreeImage_Unload(bitmap_scaled); job.done = true; }); } // Wait until all mipmaps have been generated auto ready = false; while (!ready) { ready = true; for (const auto& job : jobs) { if (!job.done) { ready = false; } } this_thread::sleep_for(chrono::milliseconds(16)); } } }
36.518337
189
0.601834
slimlime
1b1f432683175f3753b72f8c9853fec747556e13
2,028
hpp
C++
include/nanorange/algorithm/min_element.hpp
paulbendixen/NanoRange
993dc03ebb2d3de5395648f3c0d112d230127c65
[ "BSL-1.0" ]
null
null
null
include/nanorange/algorithm/min_element.hpp
paulbendixen/NanoRange
993dc03ebb2d3de5395648f3c0d112d230127c65
[ "BSL-1.0" ]
null
null
null
include/nanorange/algorithm/min_element.hpp
paulbendixen/NanoRange
993dc03ebb2d3de5395648f3c0d112d230127c65
[ "BSL-1.0" ]
null
null
null
// nanorange/algorithm/min_element.hpp // // Copyright (c) 2018 Tristan Brindle (tcbrindle at gmail dot com) // 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 NANORANGE_ALGORITHM_MIN_ELEMENT_HPP_INCLUDED #define NANORANGE_ALGORITHM_MIN_ELEMENT_HPP_INCLUDED #include <nanorange/ranges.hpp> NANO_BEGIN_NAMESPACE namespace detail { struct min_element_fn { private: friend struct nth_element_fn; template <typename I, typename S, typename Comp, typename Proj> static constexpr I impl(I first, S last, Comp& comp, Proj& proj) { if (first == last) { return first; } I i = nano::next(first); while (i != last) { if (nano::invoke(comp, nano::invoke(proj, *i), nano::invoke(proj, *first))) { first = i; } ++i; } return first; } public: template <typename I, typename S, typename Comp = ranges::less, typename Proj = identity> constexpr std::enable_if_t< forward_iterator<I> && sentinel_for<S, I> && indirect_strict_weak_order<Comp, projected<I, Proj>>, I> operator()(I first, S last, Comp comp = Comp{}, Proj proj = Proj{}) const { return min_element_fn::impl(std::move(first), std::move(last), comp, proj); } template <typename Rng, typename Comp = ranges::less, typename Proj = identity> constexpr std::enable_if_t< forward_range<Rng> && indirect_strict_weak_order<Comp, projected<iterator_t<Rng>, Proj>>, safe_iterator_t<Rng>> operator()(Rng&& rng, Comp comp = Comp{}, Proj proj = Proj{}) const { return min_element_fn::impl(nano::begin(rng), nano::end(rng), comp, proj); } }; } NANO_INLINE_VAR(detail::min_element_fn, min_element) NANO_END_NAMESPACE #endif
28.971429
83
0.611933
paulbendixen
1b2102649b8327917e9f3305a46ab5cea968329c
632
cpp
C++
Kattis_Problems/MosiquitoMultiplication.cpp
MAXI0008/Kattis-Problems
ff6ec752b741a56fc37a993c528fc925ca302cc8
[ "MIT" ]
3
2019-04-01T05:38:09.000Z
2021-11-17T11:43:20.000Z
Kattis_Problems/MosiquitoMultiplication.cpp
MAXI0008/Algorithms-Practices
ff6ec752b741a56fc37a993c528fc925ca302cc8
[ "MIT" ]
null
null
null
Kattis_Problems/MosiquitoMultiplication.cpp
MAXI0008/Algorithms-Practices
ff6ec752b741a56fc37a993c528fc925ca302cc8
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; #define FOR(i, a, b) for(int (i) = (a); (i) <= (b); (i)++) int main() { int M, P, L, E, R, S, N; int pre_M; int pre_L; int pre_P; while (cin >> M && cin >> P && cin >> L && cin >> E && cin >> R && cin >> S && cin >> N) { FOR(i, 0, N - 1) { pre_M = M; pre_L = L; pre_P = P; M -= pre_M; L += pre_M * E; L -= pre_L; P += (int)(((1 / (double)R)) * pre_L); P -= pre_P; M += (int)(((1 / (double)S)) * pre_P); } cout << M << endl; } }
20.387097
94
0.351266
MAXI0008
1b22d3d8058cbc13b2f313ae6a9a9071f0727ba4
268
cpp
C++
(1)Beginner/1174/c++/1174.cpp
G4DavidAlmeida/mySolutionsUriOnline
47e427e3205124da00a8a44fb9900086d85c30ec
[ "MIT" ]
null
null
null
(1)Beginner/1174/c++/1174.cpp
G4DavidAlmeida/mySolutionsUriOnline
47e427e3205124da00a8a44fb9900086d85c30ec
[ "MIT" ]
null
null
null
(1)Beginner/1174/c++/1174.cpp
G4DavidAlmeida/mySolutionsUriOnline
47e427e3205124da00a8a44fb9900086d85c30ec
[ "MIT" ]
null
null
null
#include<iostream> #include<iomanip> using namespace std; int main(){ double x[100]; int i; for(i=0;i<100;i++)cin >> x[i]; for(i=0;i<100;i++){ if(x[i]<=10){ cout << "A[" << i << "] = " << fixed << setprecision(1) << x[i] << endl; } } return 0; }
14.105263
76
0.503731
G4DavidAlmeida
1b2688575d9fca5eb44b23be640d94591e0bbacd
336
cpp
C++
src/common/file_util.cpp
cugdc/Jumpy-Thieves
fc5a68ed6854dd9a057d433910ccfb1f6031256e
[ "Apache-2.0" ]
2
2020-03-21T09:49:27.000Z
2020-03-31T16:59:59.000Z
src/common/file_util.cpp
cugdc/Jumpy-Thieves
fc5a68ed6854dd9a057d433910ccfb1f6031256e
[ "Apache-2.0" ]
null
null
null
src/common/file_util.cpp
cugdc/Jumpy-Thieves
fc5a68ed6854dd9a057d433910ccfb1f6031256e
[ "Apache-2.0" ]
null
null
null
#include "file_util.hpp" auto read_file(std::string_view path) -> std::string { std::ifstream file{path.data()}; if (!file.is_open()) { spdlog::error("Cannot open file {}\n", path); std::fflush(stdout); } std::stringstream ss; // read file's buffer contents into streams ss << file.rdbuf(); return ss.str(); }
18.666667
52
0.633929
cugdc
1b2b98101105315bf3d6eaae77eb3c1ef04e2077
1,782
hpp
C++
src/Rect.hpp
JesseMaurais/SGe
f73bd03d30074a54642847b05f82151128481371
[ "MIT" ]
1
2017-04-20T06:27:36.000Z
2017-04-20T06:27:36.000Z
src/Rect.hpp
JesseMaurais/SGe
f73bd03d30074a54642847b05f82151128481371
[ "MIT" ]
null
null
null
src/Rect.hpp
JesseMaurais/SGe
f73bd03d30074a54642847b05f82151128481371
[ "MIT" ]
null
null
null
#ifndef Rect_hpp #define Rect_hpp #include "SDL.hpp" #include <vector> #include <utility> namespace SDL { using namespace std::rel_ops; struct Size { int w, h; }; using Point = SDL_Point; using Rect = SDL_Rect; using Points = std::vector<Point>; using Rects = std::vector<Rect>; using Line = std::pair<Point, Point>; using Lines = std::vector<Line>; using Sizes = std::vector<Size>; inline bool operator!(Rect const &A) { return SDL_RectEmpty(&A); } inline bool operator<(Rect const &A, Rect const &B) { return A.w < B.w and A.h < B.h and A.x > B.x and A.y > B.y; } inline bool operator==(Rect const &A, Rect const &B) { return SDL_RectEquals(&A, &B); } inline bool operator&&(Rect const &A, Rect const &B) { return SDL_HasIntersection(&A, &B); } inline bool operator&&(Rect const &A, Point const &B) { return SDL_PointInRect(&B, &A); } inline bool operator&&(Rect const &A, Line B) { return SDL_IntersectRectAndLine(&A, &B.first.x, &B.first.y, &B.second.x, &B.second.y); } inline Line operator&(Rect const &A, Line B) { if (not SDL_IntersectRectAndLine(&A, &B.first.x, &B.first.y, &B.second.x, &B.second.y)) { B.first.x = B.first.y = B.second.x = B.second.y = 0; } return B; } inline Rect operator&(Rect const &A, Rect const &B) { Rect C; if (not SDL_IntersectRect(&A, &B, &C)) { C.x = C.y = C.w = C.h = 0; } return C; } inline Rect operator|(Rect const &A, Rect const &B) { Rect C; SDL_UnionRect(&A, &B, &C); return C; } } #endif // file
21.46988
95
0.540404
JesseMaurais
1b2f38e0e299b0cfe98825544ad980435b2968e8
1,313
cpp
C++
4.3A.cpp
SushmaNagaraj/Coding
9ec85c117fceb6b77512b0af513671bb8adce815
[ "Apache-2.0" ]
1
2019-05-19T19:59:55.000Z
2019-05-19T19:59:55.000Z
4.3A.cpp
SushmaNagaraj/Coding
9ec85c117fceb6b77512b0af513671bb8adce815
[ "Apache-2.0" ]
null
null
null
4.3A.cpp
SushmaNagaraj/Coding
9ec85c117fceb6b77512b0af513671bb8adce815
[ "Apache-2.0" ]
null
null
null
/** Given pointers start and end that point to the first and past the last element of a segment inside an array, reverse all elements in the segment. */ void reverse(int* start, int* end) { int * tempEnd = end-1; while(start < tempEnd) { int temp = *start; *start = *tempEnd; *tempEnd = temp; start++; tempEnd--; } } #include <iostream> using namespace std; void reverse(int* start, int* end); void print(int* a, int n) { cout << "{"; for (int i = 0; i < n; i++) { cout << " " << a[i]; if (i < n - 1) cout << ","; } cout << " }" << endl; } int main() { int a[] = { 5, 1, 4, 9, -4, 8, -9, 0 }; reverse(a + 1, a + 5); print(a, sizeof(a) / sizeof(a[0])); cout << "Expected: { 5, -4, 9, 4, 1, 8, -9, 0 }" << endl; int b[] = { 1, 4, 9, 0 }; reverse(b + 1, b + 4); print(b, sizeof(b) / sizeof(b[0])); cout << "Expected: { 1, 0, 9, 4 }" << endl; int c[] = { 12, 13 }; reverse(c, c + 1); print(c, sizeof(c) / sizeof(c[0])); cout << "Expected: { 12, 13 }" << endl; int d[] = { 14, 15 }; reverse(d, d); print(d, sizeof(d) / sizeof(d[0])); cout << "Expected: { 14, 15 }" << endl; return 0; }
20.84127
61
0.450114
SushmaNagaraj
1b2f85a1efd4185d3a0a3898bc24641c1d85851f
1,773
cpp
C++
src/omwmm/extractor.cpp
luluco250/omwmm
ee9cd11e4876515c84ad4f2c97372ba23616ac2b
[ "MIT" ]
null
null
null
src/omwmm/extractor.cpp
luluco250/omwmm
ee9cd11e4876515c84ad4f2c97372ba23616ac2b
[ "MIT" ]
null
null
null
src/omwmm/extractor.cpp
luluco250/omwmm
ee9cd11e4876515c84ad4f2c97372ba23616ac2b
[ "MIT" ]
null
null
null
#include <omwmm/extractor.hpp> #include <filesystem> #include <memory> #include <string> #include <string_view> #include <unordered_map> #include <algorithm> #include <cctype> #include <7zpp/7zpp.h> #include <omwmm/exceptions.hpp> using SevenZip::SevenZipLibrary; using SevenZip::SevenZipExtractor; using SevenZipString = SevenZip::TString; using SevenZip::CompressionFormat; using SevenZip::CompressionFormatEnum; namespace fs = std::filesystem; namespace omwmm { using namespace exceptions; Extractor::Extractor() : _data(SevenZipLibrary()) { auto lzma_lib = std::any_cast<SevenZipLibrary>(&_data); if (!lzma_lib->Load()) throw ExtractorException("Failed to load 7z dll"); } static const std::unordered_map<std::string_view, CompressionFormatEnum> extensions{ {".7z", CompressionFormat::SevenZip}, {".zip", CompressionFormat::Zip}, {".rar", CompressionFormat::Rar} }; void Extractor::extract(const fs::path& source, const fs::path& dest) { if (!fs::exists(source)) throw ExtractorException("Source file doesn't exist"); if (!fs::exists(dest)) fs::create_directory(dest); auto lib = std::any_cast<SevenZipLibrary>(&_data); auto str = fs::path(source).make_preferred().native(); SevenZipString name; name.assign(str.begin(), str.end()); auto ext = SevenZipExtractor(*lib, name); str.assign(dest.native()); name.assign(str.begin(), str.end()); if (!ext.DetectCompressionFormat()) { auto sf = source.extension().string(); std::transform(sf.begin(), sf.end(), sf.begin(), std::tolower); if (extensions.find(sf) != extensions.end()) ext.SetCompressionFormat(extensions.at(sf)); else ext.SetCompressionFormat(CompressionFormat::Zip); } if (!ext.ExtractArchive(name)) throw ExtractorException("Failed to extract file"); } }
25.328571
72
0.72758
luluco250
1b2fba2d04eb922606dcd40ed10f58c7689e3ec8
665
cpp
C++
src/vswhere.lib/Exceptions.cpp
www22111/vswhere
ded0fdd04473772af1dd001d82b6e3c871731788
[ "MIT" ]
335
2019-05-08T04:02:50.000Z
2022-03-30T20:41:31.000Z
src/vswhere.lib/Exceptions.cpp
www22111/vswhere
ded0fdd04473772af1dd001d82b6e3c871731788
[ "MIT" ]
79
2019-05-07T18:48:27.000Z
2022-03-16T22:27:59.000Z
src/vswhere.lib/Exceptions.cpp
www22111/vswhere
ded0fdd04473772af1dd001d82b6e3c871731788
[ "MIT" ]
39
2019-06-26T22:04:30.000Z
2022-01-07T15:09:44.000Z
// <copyright file="Exceptions.cpp" company="Microsoft Corporation"> // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE.txt in the project root for license information. // </copyright> #include "stdafx.h" using namespace std; wstring win32_error::format_message(_In_ int code) { const size_t max = 65536; wstring err(max, wstring::value_type()); if (auto ch = ::FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, code, 0, const_cast<LPWSTR>(err.c_str()), err.size(), NULL)) { err.resize(ch); return err; } return L"unknown error"; }
28.913043
161
0.703759
www22111
1b323dc164b2b53e4f2f7e516b224d02093d42ff
61,762
cxx
C++
src/ramsesio.cxx
bwvdnbro/VELOCIraptor-STF
9c4a07eee20309152bcde40602029315c8bd50ca
[ "MIT" ]
4
2020-08-28T11:29:09.000Z
2021-10-16T20:17:54.000Z
src/ramsesio.cxx
bwvdnbro/VELOCIraptor-STF
9c4a07eee20309152bcde40602029315c8bd50ca
[ "MIT" ]
118
2019-05-06T11:46:28.000Z
2022-03-14T17:14:37.000Z
src/ramsesio.cxx
bwvdnbro/VELOCIraptor-STF
9c4a07eee20309152bcde40602029315c8bd50ca
[ "MIT" ]
4
2020-10-01T05:22:31.000Z
2021-07-26T13:07:42.000Z
/*! \file ramsesio.cxx * \brief this file contains routines for ramses snapshot file io * * \todo need to check if amr file quantity ngrid_current is actually the number of cells in the file as * an example fortran code I have been given seems to also use the ngridlevel array, which stores the number of cells * at a given resolution level. * \todo need to add in ability for multiple read threads and sends between read threads * * * Edited by: Rodrigo Ca\~nas * rodrigo.canas@icrar.org * * Last edited: 7 - Jun - 2017 * * */ //-- RAMSES SPECIFIC IO #include "stf.h" #include "io.h" #include "ramsesitems.h" #include "endianutils.h" int RAMSES_fortran_read(fstream &F, int &i){ int dummy,byteoffset=0; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); F.read((char*)&i,sizeof(int)); byteoffset+=dummy; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); return byteoffset; } int RAMSES_fortran_read(fstream &F, RAMSESFLOAT &f){ int dummy,byteoffset=0; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); F.read((char*)&f,sizeof(RAMSESFLOAT)); byteoffset+=dummy; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); return byteoffset; } int RAMSES_fortran_read(fstream &F, int *i){ int dummy,byteoffset=0; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); F.read((char*)i,dummy); byteoffset+=dummy; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); return byteoffset; } int RAMSES_fortran_read(fstream &F, unsigned int *i){ int dummy,byteoffset=0; F.read((char*)&dummy, sizeof(dummy)); byteoffset += sizeof(int); F.read((char*)i,dummy); byteoffset += dummy; F.read((char*)&dummy, sizeof(dummy)); byteoffset += sizeof(int); return byteoffset; } int RAMSES_fortran_read(fstream &F, long long *i){ int dummy,byteoffset=0; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); F.read((char*)i,dummy); byteoffset+=dummy; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); return byteoffset; } int RAMSES_fortran_read(fstream &F, RAMSESFLOAT *f){ int dummy,byteoffset=0; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); F.read((char*)f,dummy); byteoffset+=dummy; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); return byteoffset; } int RAMSES_fortran_skip(fstream &F, int nskips){ int dummy,byteoffset=0; for (int i=0;i<nskips;i++) { F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); F.seekg(dummy,ios::cur); byteoffset+=dummy; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); } return byteoffset; } Int_t RAMSES_get_nbodies(char *fname, int ptype, Options &opt) { char buf[2000],buf1[2000],buf2[2000]; double * dummy_age, * dummy_mass; double dmp_mass; double OmegaM, OmegaB; int totalghost = 0; int totalstars = 0; int totaldm = 0; int alltotal = 0; int ghoststars = 0; string stringbuf; int ninputoffset = 0; sprintf(buf1,"%s/amr_%s.out00001",fname,opt.ramsessnapname); sprintf(buf2,"%s/amr_%s.out",fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); else { printf("Error. Can't find AMR data \nneither as `%s'\nnor as `%s'\n\n", buf1, buf2); exit(9); } //if gas searched in some fashion then load amr/hydro data if (opt.partsearchtype==PSTGAS||opt.partsearchtype==PSTALL||(opt.partsearchtype==PSTDARK&&opt.iBaryonSearch)) { sprintf(buf1,"%s/hydro_%s.out00001",fname,opt.ramsessnapname); sprintf(buf2,"%s/hydro_%s.out",fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); else { printf("Error. Can't find Hydro data \nneither as `%s'\nnor as `%s'\n\n", buf1, buf2); exit(9); } } sprintf(buf1,"%s/part_%s.out00001",fname,opt.ramsessnapname); sprintf(buf2,"%s/part_%s.out",fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); else { printf("Error. Can't find Particle data \nneither as `%s'\nnor as `%s'\n\n", buf1, buf2); exit(9); } fstream Framses; RAMSES_Header ramses_header_info; //buffers to load data int intbuff[NRAMSESTYPE]; long long longbuff[NRAMSESTYPE]; int i,j,k,ireaderror=0; Int_t nbodies=0; //IntType inttype; int dummy; int nusetypes,usetypes[NRAMSESTYPE]; if (ptype==PSTALL) {nusetypes=4;usetypes[0]=RAMSESGASTYPE;usetypes[1]=RAMSESDMTYPE;usetypes[2]=RAMSESSTARTYPE;usetypes[3]=RAMSESBHTYPE;} else if (ptype==PSTDARK) {nusetypes=1;usetypes[0]=RAMSESDMTYPE;} else if (ptype==PSTGAS) {nusetypes=1;usetypes[0]=RAMSESGASTYPE;} else if (ptype==PSTSTAR) {nusetypes=1;usetypes[0]=RAMSESSTARTYPE;} else if (ptype==PSTBH) {nusetypes=1;usetypes[0]=RAMSESBHTYPE;} for (j = 0; j < NRAMSESTYPE; j++) ramses_header_info.npartTotal[j] = 0; //Open the specified file and the specified dataset in the file. //first open amr data sprintf(buf1,"%s/amr_%s.out00001",fname,opt.ramsessnapname); sprintf(buf2,"%s/amr_%s.out",fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); Framses.open(buf, ios::binary|ios::in); //read header info //this is based on a ramsestotipsy fortran code that does not detail everything in the header block but at least its informative. The example has /* read(10)ncpu read(10)ndim read(10)nx,ny,nz read(10)nlevelmax read(10)ngridmax read(10)nboundary read(10)ngrid_current read(10)boxlen read(10) read(10) read(10) read(10) read(10) read(10) read(10) read(10) read(10) read(10) read(10)msph close(10) */ // Number of files Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.num_files, sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); opt.num_files=ramses_header_info.num_files; // Number of dimensions Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.ndim, sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); // Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.nx, sizeof(int)); Framses.read((char*)&ramses_header_info.ny, sizeof(int)); Framses.read((char*)&ramses_header_info.nz, sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); // Maximum refinement level Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.nlevelmax, sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); // Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.ngridmax, sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); // Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.nboundary, sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); //this would be number of active grids but ignore for now Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); // Boxsize Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.BoxSize, sizeof(RAMSESFLOAT)); Framses.read((char*)&dummy, sizeof(dummy)); //now skip 10 blocks for (i=0;i<10;i++) { Framses.read((char*)&dummy, sizeof(dummy)); //skip block size given by dummy Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); } Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.mass[RAMSESGASTYPE], sizeof(RAMSESFLOAT)); Framses.read((char*)&dummy, sizeof(dummy)); Framses.close(); //reopen to get number of amr cells might need to alter to read grid information and what cells have no so-called son cells if (opt.partsearchtype==PSTGAS||opt.partsearchtype==PSTALL||(opt.partsearchtype==PSTDARK&&opt.iBaryonSearch)) { for (i=0;i<ramses_header_info.num_files;i++) { sprintf(buf1,"%s/amr_%s.out%05d",fname,opt.ramsessnapname,i+1); sprintf(buf2,"%s/amr_%s.out",fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); Framses.open(buf, ios::binary|ios::in); for (j=0;j<6;j++) { Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); } Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.npart[RAMSESGASTYPE], sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); ramses_header_info.npartTotal[RAMSESGASTYPE]+=ramses_header_info.npart[RAMSESGASTYPE]; } //now hydro header data sprintf(buf1,"%s/hydro_%s.out00001",fname,opt.ramsessnapname); sprintf(buf2,"%s/hydro_%s.out",fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); Framses.open(buf, ios::binary|ios::in); Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.nvarh, sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); for (i=0;i<3;i++) { Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); } Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.gamma_index, sizeof(RAMSESFLOAT)); Framses.read((char*)&dummy, sizeof(dummy)); Framses.close(); } // // Compute Mass of DM particles in RAMSES code units // fstream Finfo; sprintf(buf1,"%s/info_%s.txt", fname,opt.ramsessnapname); Finfo.open(buf1, ios::in); Finfo>>stringbuf>>stringbuf>>opt.num_files; getline(Finfo,stringbuf);//ndim getline(Finfo,stringbuf);//lmin getline(Finfo,stringbuf);//lmax getline(Finfo,stringbuf);//ngridmax getline(Finfo,stringbuf);//nstep getline(Finfo,stringbuf);//blank getline(Finfo,stringbuf);//box getline(Finfo,stringbuf);//time getline(Finfo,stringbuf);//a getline(Finfo,stringbuf);//hubble Finfo>>stringbuf>>stringbuf>>OmegaM; getline(Finfo,stringbuf); getline(Finfo,stringbuf); getline(Finfo,stringbuf); Finfo>>stringbuf>>stringbuf>>OmegaB; Finfo.close(); dmp_mass = 1.0 / (opt.Neff*opt.Neff*opt.Neff) * (OmegaM - OmegaB) / OmegaM; //now particle info for (i=0;i<ramses_header_info.num_files;i++) { sprintf(buf1,"%s/part_%s.out%05d",fname,opt.ramsessnapname,i+1); sprintf(buf2,"%s/part_%s.out",fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); Framses.open(buf, ios::binary|ios::in); ramses_header_info.npart[RAMSESDMTYPE] = 0; ramses_header_info.npart[RAMSESSTARTYPE] = 0; ramses_header_info.npart[RAMSESSINKTYPE] = 0; //number of cpus Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); //number of dimensions Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); // Total number of LOCAL particles Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.npartlocal, sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); // Random seeds Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); // Total number of Stars over all processors Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.nstarTotal, sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); // Total mass of stars Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); // Total lost mass of stars Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); // Number of sink particles over the whole simulation (all are included in // all processors) Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.npartTotal[RAMSESSINKTYPE], sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); //to determine how many particles of each type, need to look at the mass // Skip pos, vel, mass for (j = 0; j < 6; j++) { Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); } //allocate memory to store masses and ages dummy_mass = new double [ramses_header_info.npartlocal]; dummy_age = new double [ramses_header_info.npartlocal]; // Read Mass Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&dummy_mass[0], dummy); Framses.read((char*)&dummy, sizeof(dummy)); // Skip Id Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); // Skip level Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); // Read Birth epoch //necessary to separate ghost star particles with negative ages from real one Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&dummy_age[0], dummy); Framses.read((char*)&dummy, sizeof(dummy)); ghoststars = 0; for (j = 0; j < ramses_header_info.npartlocal; j++) { if (fabs((dummy_mass[j]-dmp_mass)/dmp_mass) < 1e-5) ramses_header_info.npart[RAMSESDMTYPE]++; else if (dummy_age[j] != 0.0) ramses_header_info.npart[RAMSESSTARTYPE]++; else ghoststars++; } delete [] dummy_age; delete [] dummy_mass; Framses.close(); totalghost += ghoststars; totalstars += ramses_header_info.npart[RAMSESSTARTYPE]; totaldm += ramses_header_info.npart[RAMSESDMTYPE]; alltotal += ramses_header_info.npartlocal; //now with information loaded, set totals ramses_header_info.npartTotal[RAMSESDMTYPE]+=ramses_header_info.npart[RAMSESDMTYPE]; ramses_header_info.npartTotal[RAMSESSTARTYPE]+=ramses_header_info.npart[RAMSESSTARTYPE]; ramses_header_info.npartTotal[RAMSESSINKTYPE]+=ramses_header_info.npart[RAMSESSINKTYPE]; } for(j=0, nbodies=0; j<nusetypes; j++) { k=usetypes[j]; nbodies+=ramses_header_info.npartTotal[k]; //nbodies+=((long long)(ramses_header_info.npartTotalHW[k]) << 32); } for (j=0;j<NPARTTYPES;j++) opt.numpart[j]=0; if (ptype==PSTALL || ptype==PSTDARK) opt.numpart[DARKTYPE]=ramses_header_info.npartTotal[RAMSESDMTYPE]; if (ptype==PSTALL || ptype==PSTGAS) opt.numpart[GASTYPE]=ramses_header_info.npartTotal[RAMSESGASTYPE]; if (ptype==PSTALL || ptype==PSTSTAR) opt.numpart[STARTYPE]=ramses_header_info.npartTotal[RAMSESSTARTYPE]; if (ptype==PSTALL || ptype==PSTBH) opt.numpart[BHTYPE]=ramses_header_info.npartTotal[RAMSESSINKTYPE]; return nbodies; } /// Reads a ramses file. If cosmological simulation uses cosmology (generally /// assuming LCDM or small deviations from this) to estimate the mean interparticle /// spacing and scales physical linking length passed by this distance. Also reads /// header and overrides passed cosmological parameters with ones stored in header. void ReadRamses(Options &opt, vector<Particle> &Part, const Int_t nbodies, Particle *&Pbaryons, Int_t nbaryons) { char buf[2000],buf1[2000],buf2[2000]; string stringbuf,orderingstring; fstream Finfo; fstream *Famr; fstream *Fhydro; fstream *Fpart, *Fpartvel,*Fpartid,*Fpartmass, *Fpartlevel, *Fpartage, *Fpartmet; RAMSES_Header *header; int intbuff[NRAMSESTYPE]; long long longbuff[NRAMSESTYPE]; int i,j,k,n,idim,ivar,igrid,ireaderror=0; Int_t count2,bcount2; //IntType inttype; int dummy,byteoffset; Double_t MP_DM=MAXVALUE,LN,N_DM,MP_B=0; double z,aadjust,Hubble,Hubbleflow; Double_t mscale,lscale,lvscale,rhoscale; Double_t mtemp,utemp,rhotemp,Ztemp,Ttemp; Coordinate xpos,vpos; RAMSESFLOAT xtemp[3],vtemp[3]; RAMSESIDTYPE idval; int typeval; RAMSESFLOAT ageval,metval; int *ngridlevel,*ngridbound,*ngridfile; int lmin=1000000,lmax=0; double dmp_mass; int ninputoffset = 0; int ifirstfile=0,ibuf=0; std::vector<int> ireadfile; Int_t ibufindex; int *ireadtask,*readtaskID; #ifndef USEMPI int ThisTask=0,NProcs=1; ireadfile = std::vector<int>(opt.num_files, 1); #else MPI_Bcast (&(opt.num_files), sizeof(opt.num_files), MPI_BYTE, 0, MPI_COMM_WORLD); MPI_Barrier (MPI_COMM_WORLD); #endif ///\todo because of the stupid fortran format, easier if chunksize is BIG so that ///number of particles local to a file are smaller Int_t chunksize=RAMSESCHUNKSIZE,nchunk; RAMSESFLOAT *xtempchunk, *vtempchunk, *mtempchunk, *sphtempchunk, *agetempchunk, *mettempchunk, *hydrotempchunk; RAMSESIDTYPE *idvalchunk, *levelchunk; int *icellchunk; Famr = new fstream[opt.num_files]; Fhydro = new fstream[opt.num_files]; Fpart = new fstream[opt.num_files]; Fpartvel = new fstream[opt.num_files]; Fpartmass = new fstream[opt.num_files]; Fpartid = new fstream[opt.num_files]; Fpartlevel = new fstream[opt.num_files]; Fpartage = new fstream[opt.num_files]; Fpartmet = new fstream[opt.num_files]; header = new RAMSES_Header[opt.num_files]; Particle *Pbuf; #ifdef USEMPI MPI_Status status; MPI_Comm mpi_comm_read; vector<Particle> *Preadbuf; //for parallel io Int_t BufSize=opt.mpiparticlebufsize; Int_t Nlocalbuf,*Nbuf, *Nreadbuf,*nreadoffset; Int_t *Nlocalthreadbuf,Nlocaltotalbuf; int *irecv, sendTask,recvTask,irecvflag, *mpi_irecvflag; MPI_Request *mpi_request; Int_t inreadsend,totreadsend; Int_t *mpi_nsend_baryon; Int_t *mpi_nsend_readthread; Int_t *mpi_nsend_readthread_baryon; if (opt.iBaryonSearch) mpi_nsend_baryon=new Int_t[NProcs*NProcs]; if (opt.nsnapread>1) { mpi_nsend_readthread=new Int_t[opt.nsnapread*opt.nsnapread]; if (opt.iBaryonSearch) mpi_nsend_readthread_baryon=new Int_t[opt.nsnapread*opt.nsnapread]; } Nbuf=new Int_t[NProcs]; nreadoffset=new Int_t[opt.nsnapread]; ireadtask=new int[NProcs]; readtaskID=new int[opt.nsnapread]; MPIDistributeReadTasks(opt,ireadtask,readtaskID); MPI_Comm_split(MPI_COMM_WORLD, (ireadtask[ThisTask]>=0), ThisTask, &mpi_comm_read); if (ireadtask[ThisTask]>=0) { //to temporarily store data Pbuf=new Particle[BufSize*NProcs]; Nreadbuf=new Int_t[opt.nsnapread]; for (int j=0;j<NProcs;j++) Nbuf[j]=0; for (int j=0;j<opt.nsnapread;j++) Nreadbuf[j]=0; if (opt.nsnapread>1){ Preadbuf=new vector<Particle>[opt.nsnapread]; for (int j=0;j<opt.nsnapread;j++) Preadbuf[j].reserve(BufSize); } //to determine which files the thread should read ireadfile = std::vector<int>(opt.num_files); ifirstfile=MPISetFilesRead(opt,ireadfile,ireadtask); inreadsend=0; for (int j=0;j<opt.num_files;j++) inreadsend+=ireadfile[j]; MPI_Allreduce(&inreadsend,&totreadsend,1,MPI_Int_t,MPI_MIN,mpi_comm_read); } else { Nlocalthreadbuf=new Int_t[opt.nsnapread]; irecv=new int[opt.nsnapread]; mpi_irecvflag=new int[opt.nsnapread]; for (i=0;i<opt.nsnapread;i++) irecv[i]=1; mpi_request=new MPI_Request[opt.nsnapread]; } Nlocal=0; if (opt.iBaryonSearch) Nlocalbaryon[0]=0; if (ireadtask[ThisTask]>=0) { #endif //first read cosmological information sprintf(buf1,"%s/info_%s.txt",opt.fname,opt.ramsessnapname); Finfo.open(buf1, ios::in); getline(Finfo,stringbuf);//nfiles getline(Finfo,stringbuf);//ndim Finfo>>stringbuf>>stringbuf>>header[ifirstfile].levelmin; getline(Finfo,stringbuf);//lmax getline(Finfo,stringbuf);//ngridmax getline(Finfo,stringbuf);//nstep getline(Finfo,stringbuf);//blank Finfo>>stringbuf>>stringbuf>>header[ifirstfile].BoxSize; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].time; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].aexp; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].HubbleParam; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].Omegam; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].OmegaLambda; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].Omegak; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].Omegab; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].scale_l; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].scale_d; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].scale_t; //convert boxsize to comoving kpc/h header[ifirstfile].BoxSize*=header[ifirstfile].scale_l/3.086e21/header[ifirstfile].aexp*header[ifirstfile].HubbleParam/100.0; getline(Finfo,stringbuf); Finfo>>stringbuf>>orderingstring; getline(Finfo,stringbuf); Finfo.close(); opt.p = header[ifirstfile].BoxSize; opt.a = header[ifirstfile].aexp; opt.Omega_m = header[ifirstfile].Omegam; opt.Omega_Lambda = header[ifirstfile].OmegaLambda; opt.Omega_b = header[ifirstfile].Omegab; opt.h = header[ifirstfile].HubbleParam/100.0; opt.Omega_cdm = opt.Omega_m-opt.Omega_b; //set hubble unit to km/s/kpc opt.H = 0.1; //set Gravity to value for kpc (km/s)^2 / solar mass opt.G = 4.30211349e-6; //and for now fix the units opt.lengthtokpc=opt.velocitytokms=opt.masstosolarmass=1.0; //Hubble flow if (opt.comove) aadjust=1.0; else aadjust=opt.a; CalcOmegak(opt); Hubble=GetHubble(opt, aadjust); CalcCriticalDensity(opt, aadjust); CalcBackgroundDensity(opt, aadjust); CalcVirBN98(opt,aadjust); //if opt.virlevel<0, then use virial overdensity based on Bryan and Norman 1997 virialization level is given by if (opt.virlevel<0) opt.virlevel=opt.virBN98; PrintCosmology(opt); //adjust length scale so that convert from 0 to 1 (box units) to kpc comoving //to scale mpi domains correctly need to store in opt.lengthinputconversion the box size in comoving little h value //opt.lengthinputconversion= opt.p*opt.h/opt.a; opt.lengthinputconversion = header[ifirstfile].BoxSize; //adjust velocity scale to that ramses is converted to km/s from which you can convert again; opt.velocityinputconversion = header[ifirstfile].scale_l/header[ifirstfile].scale_t*1e-5; //convert mass from code units to Solar Masses mscale = header[ifirstfile].scale_d * (header[ifirstfile].scale_l * header[ifirstfile].scale_l * header[ifirstfile].scale_l) / 1.988e+33; //convert length from code units to kpc (this lscale includes the physical box size) lscale = header[ifirstfile].scale_l/3.086e21; //convert velocity from code units to km/s lvscale = header[ifirstfile].scale_l/header[ifirstfile].scale_t*1e-5; //convert density to Msun/kpc^3 rhoscale = mscale/(lscale*lscale*lscale); //ignore hubble flow Hubbleflow=0.; //for (int j=0;j<NPARTTYPES;j++) nbodies+=opt.numpart[j]; cout<<"Particle system contains "<<nbodies<<" particles (of interest) at is at time "<<opt.a<<" in a box of size "<<opt.p<<endl; //number of DM particles //NOTE: this assumes a uniform box resolution. However this is not used in the rest of this function N_DM = opt.Neff*opt.Neff*opt.Neff; //interparticle spacing (assuming a uniform resolution box) LN = (lscale/(double)opt.Neff); opt.ellxscale = LN; //grab from the first particle file the dimensions of the arrays and also the number of cpus (should be number of files) sprintf(buf1,"%s/part_%s.out00001",opt.fname,opt.ramsessnapname); Fpart[ifirstfile].open(buf1, ios::binary|ios::in); RAMSES_fortran_read(Fpart[ifirstfile],header[ifirstfile].nfiles); RAMSES_fortran_read(Fpart[ifirstfile],header[ifirstfile].ndim); //adjust the number of files opt.num_files=header[ifirstfile].nfiles; Fpart[ifirstfile].close(); #ifdef USEMPI //now read tasks prepped and can read files to send information } #endif #ifdef USEMPI if (ireadtask[ThisTask]>=0) { #endif dmp_mass = 1.0 / (opt.Neff*opt.Neff*opt.Neff) * opt.Omega_cdm / opt.Omega_m; #ifdef USEMPI } MPI_Bcast (&dmp_mass, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); #endif //if not only gas being searched open particle data count2=bcount2=0; if (opt.partsearchtype!=PSTGAS) { #ifdef USEMPI if (ireadtask[ThisTask]>=0) { inreadsend=0; #endif //read particle files consists of positions,velocities, mass, id, and level (along with ages and met if some flags set) for (i=0;i<opt.num_files;i++) { if (ireadfile[i]) { sprintf(buf1,"%s/part_%s.out%05d",opt.fname,opt.ramsessnapname,i+1); sprintf(buf2,"%s/part_%s.out",opt.fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); Fpart[i].open(buf, ios::binary|ios::in); Fpartvel[i].open(buf, ios::binary|ios::in); Fpartmass[i].open(buf, ios::binary|ios::in); Fpartid[i].open(buf, ios::binary|ios::in); Fpartlevel[i].open(buf, ios::binary|ios::in); Fpartage[i].open(buf, ios::binary|ios::in); Fpartmet[i].open(buf, ios::binary|ios::in); //skip header information in each file save for number in the file //@{ byteoffset=0; // ncpus byteoffset+=RAMSES_fortran_skip(Fpart[i]); // ndims byteoffset+=RAMSES_fortran_skip(Fpart[i]); // store number of particles locally in file byteoffset+=RAMSES_fortran_read(Fpart[i],header[i].npartlocal); // skip local seeds, nstartot, mstartot, mstarlost, nsink byteoffset+=RAMSES_fortran_skip(Fpart[i],5); //byteoffset now stores size of header offset for particles Fpartvel[i].seekg(byteoffset,ios::cur); Fpartmass[i].seekg(byteoffset,ios::cur); Fpartid[i].seekg(byteoffset,ios::cur); Fpartlevel[i].seekg(byteoffset,ios::cur); Fpartage[i].seekg(byteoffset,ios::cur); Fpartmet[i].seekg(byteoffset,ios::cur); //skip positions for(idim=0;idim<header[ifirstfile].ndim;idim++) { RAMSES_fortran_skip(Fpartvel[i]); RAMSES_fortran_skip(Fpartmass[i]); RAMSES_fortran_skip(Fpartid[i]); RAMSES_fortran_skip(Fpartlevel[i]); RAMSES_fortran_skip(Fpartage[i]); RAMSES_fortran_skip(Fpartmet[i]); } //skip velocities for(idim=0;idim<header[ifirstfile].ndim;idim++) { RAMSES_fortran_skip(Fpartmass[i]); RAMSES_fortran_skip(Fpartid[i]); RAMSES_fortran_skip(Fpartlevel[i]); RAMSES_fortran_skip(Fpartage[i]); RAMSES_fortran_skip(Fpartmet[i]); } //skip mass RAMSES_fortran_skip(Fpartid[i]); RAMSES_fortran_skip(Fpartlevel[i]); RAMSES_fortran_skip(Fpartage[i]); RAMSES_fortran_skip(Fpartmet[i]); //skip ids; RAMSES_fortran_skip(Fpartlevel[i]); RAMSES_fortran_skip(Fpartage[i]); RAMSES_fortran_skip(Fpartmet[i]); //skip levels RAMSES_fortran_skip(Fpartage[i]); RAMSES_fortran_skip(Fpartmet[i]); //skip ages RAMSES_fortran_skip(Fpartmet[i]); //@} //data loaded into memory in chunks chunksize = nchunk = header[i].npartlocal; ninputoffset = 0; xtempchunk = new RAMSESFLOAT [3*chunksize]; vtempchunk = new RAMSESFLOAT [3*chunksize]; mtempchunk = new RAMSESFLOAT [chunksize]; idvalchunk = new RAMSESIDTYPE [chunksize]; levelchunk = new RAMSESIDTYPE [chunksize]; agetempchunk = new RAMSESFLOAT [chunksize]; mettempchunk = new RAMSESFLOAT [chunksize]; for(idim=0;idim<header[ifirstfile].ndim;idim++) { RAMSES_fortran_read(Fpart[i],&xtempchunk[idim*nchunk]); RAMSES_fortran_read(Fpartvel[i],&vtempchunk[idim*nchunk]); } RAMSES_fortran_read(Fpartmass[i], mtempchunk); RAMSES_fortran_read(Fpartid[i], idvalchunk); RAMSES_fortran_read(Fpartlevel[i], levelchunk); RAMSES_fortran_read(Fpartage[i], agetempchunk); RAMSES_fortran_read(Fpartmet[i], mettempchunk); RAMSES_fortran_read(Fpartid[i],idvalchunk); for (int nn=0;nn<nchunk;nn++) { if (fabs((mtempchunk[nn]-dmp_mass)/dmp_mass) > 1e-5 && (agetempchunk[nn] == 0.0)) { // GHOST PARTIRCLE!!! } else { xtemp[0] = xtempchunk[nn]; xtemp[1] = xtempchunk[nn+nchunk]; xtemp[2] = xtempchunk[nn+2*nchunk]; vtemp[0] = vtempchunk[nn]; vtemp[1] = vtempchunk[nn+nchunk]; vtemp[2] = vtempchunk[nn+2*nchunk]; idval = idvalchunk[nn]; ///Need to check this for correct 'endianness' // for (int kk=0;kk<3;kk++) {xtemp[kk]=LittleRAMSESFLOAT(xtemp[kk]);vtemp[kk]=LittleRAMSESFLOAT(vtemp[kk]);} #ifndef NOMASS mtemp=mtempchunk[nn]; #else mtemp=1.0; #endif ageval = agetempchunk[nn]; if (fabs((mtemp-dmp_mass)/dmp_mass) < 1e-5) typeval = DARKTYPE; else typeval = STARTYPE; /* if (ageval==0 && idval>0) typeval=DARKTYPE; else if (idval>0) typeval=STARTYPE; else typeval=BHTYPE; */ #ifdef USEMPI //determine processor this particle belongs on based on its spatial position ibuf=MPIGetParticlesProcessor(opt, xtemp[0],xtemp[1],xtemp[2]); ibufindex=ibuf*BufSize+Nbuf[ibuf]; #endif //reset hydro quantities of buffer #ifdef USEMPI #ifdef GASON Pbuf[ibufindex].SetU(0); #ifdef STARON Pbuf[ibufindex].SetSFR(0); Pbuf[ibufindex].SetZmet(0); #endif #endif #ifdef STARON Pbuf[ibufindex].SetZmet(0); Pbuf[ibufindex].SetTage(0); #endif #ifdef BHON #endif #endif if (opt.partsearchtype==PSTALL) { #ifdef USEMPI Pbuf[ibufindex]=Particle(mtemp*mscale, xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale, vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0], vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1], vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2], count2,typeval); Pbuf[ibufindex].SetPID(idval); #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Part[ibufindex].SetInputFileID(i); Part[ibufindex].SetInputIndexInFile(nn+ninputoffset); } #endif Nbuf[ibuf]++; MPIAddParticletoAppropriateBuffer(opt, ibuf, ibufindex, ireadtask, BufSize, Nbuf, Pbuf, Nlocal, Part.data(), Nreadbuf, Preadbuf); #else Part[count2]=Particle(mtemp*mscale, xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale, vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0], vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1], vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2], count2,typeval); Part[count2].SetPID(idval); #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Part[count2].SetInputFileID(i); Part[count2].SetInputIndexInFile(nn+ninputoffset); } #endif #endif count2++; } else if (opt.partsearchtype==PSTDARK) { if (!(typeval==STARTYPE||typeval==BHTYPE)) { #ifdef USEMPI Pbuf[ibufindex]=Particle(mtemp*mscale, xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale, vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0], vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1], vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2], count2,DARKTYPE); Pbuf[ibufindex].SetPID(idval); #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Pbuf[ibufindex].SetInputFileID(i); Pbuf[ibufindex].SetInputIndexInFile(nn+ninputoffset); } #endif //ensure that store number of particles to be sent to other reading threads Nbuf[ibuf]++; MPIAddParticletoAppropriateBuffer(opt, ibuf, ibufindex, ireadtask, BufSize, Nbuf, Pbuf, Nlocal, Part.data(), Nreadbuf, Preadbuf); #else Part[count2]=Particle(mtemp*mscale, xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale, vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0], vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1], vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2], count2,typeval); Part[count2].SetPID(idval); #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Part[count2].SetInputFileID(i); Part[count2].SetInputIndexInFile(nn+ninputoffset); } #endif #endif count2++; } else if (opt.iBaryonSearch) { #ifdef USEMPI Pbuf[ibufindex]=Particle(mtemp*mscale, xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale, vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0], vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1], vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2], count2); Pbuf[ibufindex].SetPID(idval); #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Pbuf[ibufindex].SetInputFileID(i); Pbuf[ibufindex].SetInputIndexInFile(nn+ninputoffset); } #endif if (typeval==STARTYPE) Pbuf[ibufindex].SetType(STARTYPE); else if (typeval==BHTYPE) Pbuf[ibufindex].SetType(BHTYPE); //ensure that store number of particles to be sent to the reading threads Nbuf[ibuf]++; if (ibuf==ThisTask) { if (k==RAMSESSTARTYPE) Nlocalbaryon[2]++; else if (k==RAMSESSINKTYPE) Nlocalbaryon[3]++; } MPIAddParticletoAppropriateBuffer(opt, ibuf, ibufindex, ireadtask, BufSize, Nbuf, Pbuf, Nlocalbaryon[0], Pbaryons, Nreadbuf, Preadbuf); #else Pbaryons[bcount2]=Particle(mtemp*mscale, xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale, vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0], vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1], vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2], count2,typeval); Pbaryons[bcount2].SetPID(idval); #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Part[bcount2].SetInputFileID(i); Part[bcount2].SetInputIndexInFile(nn+ninputoffset); } #endif #endif bcount2++; } } else if (opt.partsearchtype==PSTSTAR) { if (typeval==STARTYPE) { #ifdef USEMPI //if using MPI, determine proccessor and place in ibuf, store particle in particle buffer and if buffer full, broadcast data //unless ibuf is 0, then just store locally Pbuf[ibufindex]=Particle(mtemp*mscale, xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale, vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0], vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1], vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2], count2,STARTYPE); //ensure that store number of particles to be sent to the reading threads Pbuf[ibufindex].SetPID(idval); #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Pbuf[ibufindex].SetInputFileID(i); Pbuf[ibufindex].SetInputIndexInFile(nn+ninputoffset); } #endif Nbuf[ibuf]++; MPIAddParticletoAppropriateBuffer(opt, ibuf, ibufindex, ireadtask, BufSize, Nbuf, Pbuf, Nlocal, Part.data(), Nreadbuf, Preadbuf); #else Part[count2]=Particle(mtemp*mscale, xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale, vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0], vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1], vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2], count2,typeval); Part[count2].SetPID(idval); #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Part[count2].SetInputFileID(i); Part[count2].SetInputIndexInFile(nn+ninputoffset); } #endif #endif count2++; } } }//end of ghost particle check }//end of loop over chunk delete[] xtempchunk; delete[] vtempchunk; delete[] mtempchunk; delete[] idvalchunk; delete[] agetempchunk; delete[] levelchunk; delete[] mettempchunk; Fpart[i].close(); Fpartvel[i].close(); Fpartmass[i].close(); Fpartid[i].close(); Fpartlevel[i].close(); Fpartage[i].close(); Fpartmet[i].close(); #ifdef USEMPI //send information between read threads if (opt.nsnapread>1&&inreadsend<totreadsend){ MPI_Allgather(Nreadbuf, opt.nsnapread, MPI_Int_t, mpi_nsend_readthread, opt.nsnapread, MPI_Int_t, mpi_comm_read); MPISendParticlesBetweenReadThreads(opt, Preadbuf, Part.data(), ireadtask, readtaskID, Pbaryons, mpi_comm_read, mpi_nsend_readthread, mpi_nsend_readthread_baryon); inreadsend++; for(ibuf = 0; ibuf < opt.nsnapread; ibuf++) Nreadbuf[ibuf]=0; } #endif }//end of whether reading a file }//end of loop over file #ifdef USEMPI //once finished reading the file if there are any particles left in the buffer broadcast them for(ibuf = 0; ibuf < NProcs; ibuf++) if (ireadtask[ibuf]<0) { MPI_Ssend(&Nbuf[ibuf],1,MPI_Int_t, ibuf, ibuf+NProcs, MPI_COMM_WORLD); if (Nbuf[ibuf]>0) { MPI_Ssend(&Pbuf[ibuf*BufSize], sizeof(Particle)*Nbuf[ibuf], MPI_BYTE, ibuf, ibuf, MPI_COMM_WORLD); Nbuf[ibuf]=0; //last broadcast with Nbuf[ibuf]=0 so that receiver knows no more particles are to be broadcast MPI_Ssend(&Nbuf[ibuf],1,MPI_Int_t,ibuf,ibuf+NProcs,MPI_COMM_WORLD); } } if (opt.nsnapread>1){ MPI_Allgather(Nreadbuf, opt.nsnapread, MPI_Int_t, mpi_nsend_readthread, opt.nsnapread, MPI_Int_t, mpi_comm_read); MPISendParticlesBetweenReadThreads(opt, Preadbuf, Part.data(), ireadtask, readtaskID, Pbaryons, mpi_comm_read, mpi_nsend_readthread, mpi_nsend_readthread_baryon); } }//end of ireadtask[ibuf]>0 #endif #ifdef USEMPI else { MPIReceiveParticlesFromReadThreads(opt,Pbuf,Part.data(),readtaskID, irecv, mpi_irecvflag, Nlocalthreadbuf, mpi_request,Pbaryons); } #endif } //if gas searched in some fashion then load amr/hydro data if (opt.partsearchtype==PSTGAS||opt.partsearchtype==PSTALL||(opt.partsearchtype==PSTDARK&&opt.iBaryonSearch)) { #ifdef USEMPI if (ireadtask[ThisTask]>=0) { inreadsend=0; #endif for (i=0;i<opt.num_files;i++) if (ireadfile[i]) { sprintf(buf1,"%s/amr_%s.out%05d",opt.fname,opt.ramsessnapname,i+1); sprintf(buf2,"%s/amr_%s.out",opt.fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); Famr[i].open(buf, ios::binary|ios::in); sprintf(buf1,"%s/hydro_%s.out%05d",opt.fname,opt.ramsessnapname,i+1); sprintf(buf2,"%s/hydro_%s.out",opt.fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); Fhydro[i].open(buf, ios::binary|ios::in); //read some of the amr header till get to number of cells in current file //@{ byteoffset=0; byteoffset+=RAMSES_fortran_read(Famr[i],header[i].ndim); header[i].twotondim=pow(2,header[i].ndim); Famr[i].read((char*)&dummy, sizeof(dummy)); Famr[i].read((char*)&header[i].nx, sizeof(int)); Famr[i].read((char*)&header[i].ny, sizeof(int)); Famr[i].read((char*)&header[i].nz, sizeof(int)); Famr[i].read((char*)&dummy, sizeof(dummy)); byteoffset+=RAMSES_fortran_read(Famr[i],header[i].nlevelmax); byteoffset+=RAMSES_fortran_read(Famr[i],header[i].ngridmax); byteoffset+=RAMSES_fortran_read(Famr[i],header[i].nboundary); byteoffset+=RAMSES_fortran_read(Famr[i],header[i].npart[RAMSESGASTYPE]); //then skip the rest for (j=0;j<14;j++) RAMSES_fortran_skip(Famr[i]); if (lmin>header[i].nlevelmax) lmin=header[i].nlevelmax; if (lmax<header[i].nlevelmax) lmax=header[i].nlevelmax; //@} //read header info from hydro files //@{ RAMSES_fortran_skip(Fhydro[i]); RAMSES_fortran_read(Fhydro[i],header[i].nvarh); RAMSES_fortran_skip(Fhydro[i]); RAMSES_fortran_skip(Fhydro[i]); RAMSES_fortran_skip(Fhydro[i]); RAMSES_fortran_read(Fhydro[i],header[i].gamma_index); //@} } for (i=0;i<opt.num_files;i++) if (ireadfile[i]) { //then apparently read ngridlevels, which appears to be an array storing the number of grids at a given level ngridlevel=new int[header[i].nlevelmax]; ngridfile=new int[(1+header[i].nboundary)*header[i].nlevelmax]; RAMSES_fortran_read(Famr[i],ngridlevel); for (j=0;j<header[i].nlevelmax;j++) ngridfile[j]=ngridlevel[j]; //skip some more RAMSES_fortran_skip(Famr[i]); //if nboundary>0 then need two skip twice then read ngridbound if(header[i].nboundary>0) { ngridbound=new int[header[i].nboundary*header[i].nlevelmax]; RAMSES_fortran_skip(Famr[i]); RAMSES_fortran_skip(Famr[i]); //ngridbound is an array of some sort but I don't see what it is used for RAMSES_fortran_read(Famr[i],ngridbound); for (j=0;j<header[i].nlevelmax;j++) ngridfile[header[i].nlevelmax+j]=ngridbound[j]; } //skip some more RAMSES_fortran_skip(Famr[i],2); //if odering list in info is bisection need to skip more if (orderingstring==string("bisection")) RAMSES_fortran_skip(Famr[i],5); else RAMSES_fortran_skip(Famr[i],4); ninputoffset=0; for (k=0;k<header[i].nboundary+1;k++) { for (j=0;j<header[i].nlevelmax;j++) { //first read amr for positions chunksize=nchunk=ngridfile[k*header[i].nlevelmax+j]; if (chunksize>0) { xtempchunk=new RAMSESFLOAT[3*chunksize]; //store son value in icell icellchunk=new int[header[i].twotondim*chunksize]; //skip grid index, next index and prev index. RAMSES_fortran_skip(Famr[i],3); //now read grid centre for (idim=0;idim<header[i].ndim;idim++) { RAMSES_fortran_read(Famr[i],&xtempchunk[idim*chunksize]); } //skip father index, then neighbours index RAMSES_fortran_skip(Famr[i],1+2*header[i].ndim); //read son index to determine if a cell in a specific grid is at the highest resolution and needs to be represented by a particle for (idim=0;idim<header[i].twotondim;idim++) { RAMSES_fortran_read(Famr[i],&icellchunk[idim*chunksize]); } //skip cpu map and refinement map (2^ndim*2) RAMSES_fortran_skip(Famr[i],2*header[i].twotondim); } RAMSES_fortran_skip(Fhydro[i]); //then read hydro for other variables (first is density, then velocity, then pressure, then metallicity ) if (chunksize>0) { hydrotempchunk=new RAMSESFLOAT[chunksize*header[i].twotondim*header[i].nvarh]; //first read velocities (for 2 cells per number of dimensions (ie: cell corners?)) for (idim=0;idim<header[i].twotondim;idim++) { for (ivar=0;ivar<header[i].nvarh;ivar++) { RAMSES_fortran_read(Fhydro[i],&hydrotempchunk[idim*chunksize*header[i].nvarh+ivar*chunksize]); for (igrid=0;igrid<chunksize;igrid++) { //once we have looped over all the hydro data then can start actually storing it into the particle structures if (ivar==header[i].nvarh-1) { //if cell has no internal cells or at maximum level produce a particle if (icellchunk[idim*chunksize+igrid]==0 || j==header[i].nlevelmax-1) { //first suggestion is to add some jitter to the particle positions double dx = pow(0.5, j); int ix, iy, iz; //below assumes three dimensions with 8 corners (? maybe cells) per grid iz = idim/4; iy = (idim - (4*iz))/2; ix = idim - (2*iy) - (4*iz); // Calculate absolute coordinates + jitter, and generate particle xpos[0] = ((((float)rand()/(float)RAND_MAX) * header[i].BoxSize * dx) +(header[i].BoxSize * (xtempchunk[igrid] + (double(ix)-0.5) * dx )) - (header[i].BoxSize*dx/2.0)) ; xpos[1] = ((((float)rand()/(float)RAND_MAX) * header[i].BoxSize * dx) +(header[i].BoxSize * (xtempchunk[igrid+1*chunksize] + (double(iy)-0.5) * dx )) - (header[i].BoxSize*dx/2.0)) ; xpos[2] = ((((float)rand()/(float)RAND_MAX) * header[i].BoxSize * dx) +(header[i].BoxSize * (xtempchunk[igrid+2*chunksize] + (double(iz)-0.5) * dx )) - (header[i].BoxSize*dx/2.0)) ; #ifdef USEMPI //determine processor this particle belongs on based on its spatial position ibuf=MPIGetParticlesProcessor(opt, xpos[0],xpos[1],xpos[2]); ibufindex=ibuf*BufSize+Nbuf[ibuf]; #endif vpos[0]=hydrotempchunk[idim*chunksize*header[i].nvarh+1*chunksize+igrid]; vpos[1]=hydrotempchunk[idim*chunksize*header[i].nvarh+2*chunksize+igrid]; vpos[2]=hydrotempchunk[idim*chunksize*header[i].nvarh+3*chunksize+igrid]; mtemp=dx*dx*dx*hydrotempchunk[idim*chunksize*header[i].nvarh+0*chunksize+igrid]; //the self energy P/rho is given by utemp=hydrotempchunk[idim*chunksize*header[i].nvarh+4*chunksize+igrid]/hydrotempchunk[idim*chunksize*header[i].nvarh+0*chunksize+igrid]/(header[i].gamma_index-1.0); rhotemp=hydrotempchunk[idim*chunksize*header[i].nvarh+0*chunksize+igrid]*rhoscale; Ztemp=hydrotempchunk[idim*chunksize*header[i].nvarh+5*chunksize+igrid]; if (opt.partsearchtype==PSTALL) { #ifdef USEMPI Pbuf[ibufindex]=Particle(mtemp*mscale, xpos[0]*lscale,xpos[1]*lscale,xpos[2]*lscale, vpos[0]*opt.velocityinputconversion+Hubbleflow*xpos[0], vpos[1]*opt.velocityinputconversion+Hubbleflow*xpos[1], vpos[2]*opt.velocityinputconversion+Hubbleflow*xpos[2], count2,GASTYPE); Pbuf[ibufindex].SetPID(idval); #ifdef GASON Pbuf[ibufindex].SetU(utemp); Pbuf[ibufindex].SetSPHDen(rhotemp); #ifdef STARON Pbuf[ibufindex].SetZmet(Ztemp); #endif #endif #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Pbuf[ibufindex].SetInputFileID(i); Pbuf[ibufindex].SetInputIndexInFile(idim*chunksize*header[i].nvarh+0*chunksize+igrid+ninputoffset); } #endif //ensure that store number of particles to be sent to the threads involved with reading snapshot files Nbuf[ibuf]++; MPIAddParticletoAppropriateBuffer(opt, ibuf, ibufindex, ireadtask, BufSize, Nbuf, Pbuf, Nlocal, Part.data(), Nreadbuf, Preadbuf); #else Part[count2]=Particle(mtemp*mscale, xpos[0]*lscale,xpos[1]*lscale,xpos[2]*lscale, vpos[0]*opt.velocityinputconversion+Hubbleflow*xpos[0], vpos[1]*opt.velocityinputconversion+Hubbleflow*xpos[1], vpos[2]*opt.velocityinputconversion+Hubbleflow*xpos[2], count2,GASTYPE); Part[count2].SetPID(idval); #ifdef GASON Part[count2].SetU(utemp); Part[count2].SetSPHDen(rhotemp); #ifdef STARON Part[count2].SetZmet(Ztemp); #endif #endif #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Part[count2].SetInputFileID(i); Part[count2].SetInputIndexInFile(idim*chunksize*header[i].nvarh+0*chunksize+igrid+ninputoffset); } #endif #endif count2++; } else if (opt.partsearchtype==PSTDARK&&opt.iBaryonSearch) { #ifdef USEMPI Pbuf[ibufindex]=Particle(mtemp*mscale, xpos[0]*lscale,xpos[1]*lscale,xpos[2]*lscale, vpos[0]*opt.velocityinputconversion+Hubbleflow*xpos[0], vpos[1]*opt.velocityinputconversion+Hubbleflow*xpos[1], vpos[2]*opt.velocityinputconversion+Hubbleflow*xpos[2], count2,GASTYPE); Pbuf[ibufindex].SetPID(idval); #ifdef GASON Pbuf[ibufindex].SetU(utemp); Pbuf[ibufindex].SetSPHDen(rhotemp); #ifdef STARON Pbuf[ibufindex].SetZmet(Ztemp); #endif #endif #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Pbuf[ibufindex].SetInputFileID(i); Pbuf[ibufindex].SetInputIndexInFile(idim*chunksize*header[i].nvarh+0*chunksize+igrid+ninputoffset); } #endif //ensure that store number of particles to be sent to the reading threads if (ibuf==ThisTask) { Nlocalbaryon[1]++; } MPIAddParticletoAppropriateBuffer(opt, ibuf, ibufindex, ireadtask, BufSize, Nbuf, Pbuf, Nlocalbaryon[0], Pbaryons, Nreadbuf, Preadbuf); #else Pbaryons[bcount2]=Particle(mtemp*mscale, xpos[0]*lscale,xpos[1]*lscale,xpos[2]*lscale, vpos[0]*opt.velocityinputconversion+Hubbleflow*xpos[0], vpos[1]*opt.velocityinputconversion+Hubbleflow*xpos[1], vpos[2]*opt.velocityinputconversion+Hubbleflow*xpos[2], count2,GASTYPE); Pbaryons[bcount2].SetPID(idval); #ifdef GASON Pbaryons[bcount2].SetU(utemp); Pbaryons[bcount2].SetSPHDen(rhotemp); #ifdef STARON Pbaryons[bcount2].SetZmet(Ztemp); #endif #endif #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Pbaryons[bcount2].SetInputFileID(i); Pbaryons[bcount2].SetInputIndexInFile(idim*chunksize*header[i].nvarh+0*chunksize+igrid+ninputoffset); } #endif #endif bcount2++; } } } } } } } if (chunksize>0) { delete[] xtempchunk; delete[] hydrotempchunk; } } } Famr[i].close(); #ifdef USEMPI //send information between read threads if (opt.nsnapread>1&&inreadsend<totreadsend){ MPI_Allgather(Nreadbuf, opt.nsnapread, MPI_Int_t, mpi_nsend_readthread, opt.nsnapread, MPI_Int_t, mpi_comm_read); MPISendParticlesBetweenReadThreads(opt, Preadbuf, Part.data(), ireadtask, readtaskID, Pbaryons, mpi_comm_read, mpi_nsend_readthread, mpi_nsend_readthread_baryon); inreadsend++; for(ibuf = 0; ibuf < opt.nsnapread; ibuf++) Nreadbuf[ibuf]=0; } #endif } #ifdef USEMPI //once finished reading the file if there are any particles left in the buffer broadcast them for(ibuf = 0; ibuf < NProcs; ibuf++) if (ireadtask[ibuf]<0) { MPI_Ssend(&Nbuf[ibuf],1,MPI_Int_t, ibuf, ibuf+NProcs, MPI_COMM_WORLD); if (Nbuf[ibuf]>0) { MPI_Ssend(&Pbuf[ibuf*BufSize], sizeof(Particle)*Nbuf[ibuf], MPI_BYTE, ibuf, ibuf, MPI_COMM_WORLD); MPISendHydroInfoFromReadThreads(opt, Nbuf[ibuf], &Pbuf[ibuf*BufSize], ibuf); MPISendStarInfoFromReadThreads(opt, Nbuf[ibuf], &Pbuf[ibuf*BufSize], ibuf); MPISendBHInfoFromReadThreads(opt, Nbuf[ibuf], &Pbuf[ibuf*BufSize], ibuf); Nbuf[ibuf]=0; //last broadcast with Nbuf[ibuf]=0 so that receiver knows no more particles are to be broadcast MPI_Ssend(&Nbuf[ibuf],1,MPI_Int_t,ibuf,ibuf+NProcs,MPI_COMM_WORLD); } } if (opt.nsnapread>1){ MPI_Allgather(Nreadbuf, opt.nsnapread, MPI_Int_t, mpi_nsend_readthread, opt.nsnapread, MPI_Int_t, mpi_comm_read); MPISendParticlesBetweenReadThreads(opt, Preadbuf, Part.data(), ireadtask, readtaskID, Pbaryons, mpi_comm_read, mpi_nsend_readthread, mpi_nsend_readthread_baryon); } }//end of reading task #endif #ifdef USEMPI //if not reading information than waiting to receive information else { MPIReceiveParticlesFromReadThreads(opt,Pbuf,Part.data(),readtaskID, irecv, mpi_irecvflag, Nlocalthreadbuf, mpi_request,Pbaryons); } #endif }//end of check if gas loaded //update info opt.p*=opt.a/opt.h; #ifdef HIGHRES opt.zoomlowmassdm=MP_DM*mscale; #endif #ifdef USEMPI MPI_Barrier(MPI_COMM_WORLD); //update cosmological data and boundary in code units MPI_Bcast(&(opt.p),sizeof(opt.p),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.a),sizeof(opt.a),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.Omega_cdm),sizeof(opt.Omega_cdm),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.Omega_b),sizeof(opt.Omega_b),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.Omega_m),sizeof(opt.Omega_m),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.Omega_Lambda),sizeof(opt.Omega_Lambda),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.h),sizeof(opt.h),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.rhocrit),sizeof(opt.rhocrit),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.rhobg),sizeof(opt.rhobg),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.virlevel),sizeof(opt.virlevel),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.virBN98),sizeof(opt.virBN98),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.ellxscale),sizeof(opt.ellxscale),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.lengthinputconversion),sizeof(opt.lengthinputconversion),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.velocityinputconversion),sizeof(opt.velocityinputconversion),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.massinputconversion),sizeof(opt.massinputconversion),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.G),sizeof(opt.G),MPI_BYTE,0,MPI_COMM_WORLD); #ifdef NOMASS MPI_Bcast(&(opt.MassValue),sizeof(opt.MassValue),MPI_BYTE,0,MPI_COMM_WORLD); #endif MPI_Bcast(&(Ntotal),sizeof(Ntotal),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&opt.zoomlowmassdm,sizeof(opt.zoomlowmassdm),MPI_BYTE,0,MPI_COMM_WORLD); #endif //store how to convert input internal energies to physical output internal energies //as we already convert ramses units to sensible output units, nothing to do. opt.internalenergyinputconversion = 1.0; //a bit of clean up #ifdef USEMPI MPI_Comm_free(&mpi_comm_read); if (opt.iBaryonSearch) delete[] mpi_nsend_baryon; if (opt.nsnapread>1) { delete[] mpi_nsend_readthread; if (opt.iBaryonSearch) delete[] mpi_nsend_readthread_baryon; if (ireadtask[ThisTask]>=0) delete[] Preadbuf; } delete[] Nbuf; if (ireadtask[ThisTask]>=0) { delete[] Nreadbuf; delete[] Pbuf; } delete[] ireadtask; delete[] readtaskID; #endif }
45.114682
221
0.595884
bwvdnbro
1b33777a2a36ad950befdfe2fc1206700de58728
4,432
cpp
C++
tools/nx_probe.cpp
tienex/apfs
afc6041c6078d3bc96c2ffec8ea6a8e572b79678
[ "MIT" ]
42
2017-12-01T15:23:20.000Z
2022-02-25T07:08:28.000Z
tools/nx_probe.cpp
tienex/apfs
afc6041c6078d3bc96c2ffec8ea6a8e572b79678
[ "MIT" ]
3
2017-12-04T19:31:53.000Z
2018-07-27T22:47:41.000Z
tools/nx_probe.cpp
tienex/apfs
afc6041c6078d3bc96c2ffec8ea6a8e572b79678
[ "MIT" ]
5
2017-12-02T22:10:53.000Z
2019-11-15T05:06:46.000Z
/* * Copyright (c) 2017-present Orlando Bassotto * * 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 "nx/nx.h" #include "nxcompat/nxcompat.h" #include <cstdio> #include <cstdlib> #include <memory> #include <string> #include <vector> #define INVALID_XID (static_cast<uint64_t>(-1)) static void usage(char const *progname) { fprintf(stderr, "usage: %s [-f|-x xid] [-kpq] device\n", progname); } enum action { ACTION_PRINT_NAME, ACTION_PRINT_UUID, ACTION_CHECK }; int main(int argc, char **argv) { char const *progname = *argv; bool first_xid = false; uint64_t xid = INVALID_XID; enum action action = ACTION_PRINT_NAME; int c; while ((c = getopt(argc, argv, "fkpqx:")) != EOF) { switch (c) { case 'p': action = ACTION_PRINT_NAME; break; case 'k': action = ACTION_PRINT_UUID; break; case 'q': action = ACTION_CHECK; break; case 'f': first_xid = true; break; case 'x': xid = strtoull(optarg, nullptr, 0); break; default: usage(progname); exit(EXIT_FAILURE); } } argc -= optind; argv += optind; if (argc < 1) { usage(progname); exit(EXIT_FAILURE); } std::string devname = argv[0]; // // Is this a real path? // if (access(devname.c_str(), R_OK) != 0 && errno == ENOENT) { std::string devname2 = "/dev/" + devname; if (access(devname2.c_str(), R_OK) != 0) { fprintf(stderr, "error: cannot find '%s' for reading: %s\n", devname.c_str(), strerror(errno)); exit(EXIT_FAILURE); } devname = devname2; } nx::context context; nx::device device; context.set_main_device(&device); if (!device.open(devname.c_str())) { fprintf(stderr, "error: cannot open '%s' for reading: %s\n", devname.c_str(), strerror(errno)); exit(EXIT_FAILURE); } auto container = new nx::container(&context); bool opened; if (xid != INVALID_XID) { opened = container->open_at(xid); } else { opened = container->open(!first_xid); } if (!opened) { exit(EXIT_FAILURE); } nx::container::info info; if (!container->get_info(info)) { exit(EXIT_FAILURE); } char buf[128]; auto vused = info.volumes - info.vfree; if (vused > 1) { auto uuid = container->get_uuid(); nx_uuid_format(&uuid, buf, sizeof(buf)); if (action == ACTION_PRINT_UUID) { printf("%s\n", buf); } else if (action == ACTION_PRINT_NAME) { printf("APFS Container %s\n", buf); } } else { auto volume = container->open_volume(0); if (volume == nullptr) { exit(EXIT_FAILURE); } if (action == ACTION_PRINT_UUID) { auto uuid = volume->get_uuid(); nx_uuid_format(&uuid, buf, sizeof(buf)); printf("%s\n", buf); } else if (action == ACTION_PRINT_NAME) { printf("%s\n", volume->get_name()); } delete volume; } delete container; exit(EXIT_SUCCESS); return EXIT_SUCCESS; }
26.538922
81
0.580325
tienex
1b33bc669f78412647362d828eaa5216b33aa488
632
cpp
C++
3425/6859847_AC_16MS_236K.cpp
vandreas19/POJ_sol
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
18
2017-08-14T07:34:42.000Z
2022-01-29T14:20:29.000Z
3425/6859847_AC_16MS_236K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
null
null
null
3425/6859847_AC_16MS_236K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
14
2016-12-21T23:37:22.000Z
2021-07-24T09:38:57.000Z
#include<iostream> #include<map> using namespace std; int main(){ int answerNum; cin>>answerNum; map<int,int> correctAnswerNum; int payment=0; while(answerNum--){ int questionID; bool correct,withExplanaion; cin>>questionID>>correct>>withExplanaion; if(correct){ if(withExplanaion) payment+=40; else payment+=20; if(correctAnswerNum.find(questionID)==correctAnswerNum.end()) correctAnswerNum[questionID]=1; else{ payment+=10*correctAnswerNum[questionID]; correctAnswerNum[questionID]++; } } else payment+=10; } cout<<payment<<endl; return 0; }
20.387097
65
0.664557
vandreas19
1b35b13dfbc9ac339d9e12246414b4aa61a1a6c6
624
cpp
C++
LeetCode/Problems/Algorithms/#1695_MaximumErasureValue_sol2_sliding_window_O(N+MAX_ELEM)_time_O(MAX_ELEM)_extra_space_156ms_89.1MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#1695_MaximumErasureValue_sol2_sliding_window_O(N+MAX_ELEM)_time_O(MAX_ELEM)_extra_space_156ms_89.1MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#1695_MaximumErasureValue_sol2_sliding_window_O(N+MAX_ELEM)_time_O(MAX_ELEM)_extra_space_156ms_89.1MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: int maximumUniqueSubarray(vector<int>& nums) { const int N = nums.size(); const int MAX_ELEM = *max_element(nums.begin(), nums.end()); int answer = 0; vector<bool> vis(MAX_ELEM + 1, false); for(int i = 0, j = 0, sum = 0; j < N; ++j){ while(vis[nums[j]]){ vis[nums[i]] = false; sum -= nums[i]; i += 1; } vis[nums[j]] = true; sum += nums[j]; answer = max(sum, answer); } return answer; } };
28.363636
69
0.410256
Tudor67
1b3a262e959eca2cba52e2f2f5e971429ce17db9
568
cpp
C++
Engine/SQ/Renderer/Renderer.cpp
chry003/SqEngine
bb98881a29da48c8c92b33c3534da1fcdd46b92a
[ "MIT" ]
null
null
null
Engine/SQ/Renderer/Renderer.cpp
chry003/SqEngine
bb98881a29da48c8c92b33c3534da1fcdd46b92a
[ "MIT" ]
null
null
null
Engine/SQ/Renderer/Renderer.cpp
chry003/SqEngine
bb98881a29da48c8c92b33c3534da1fcdd46b92a
[ "MIT" ]
null
null
null
#include "pch.hpp" #include "Renderer.hpp" namespace Sq { Renderer::OrthographicCameraMatrix* Renderer::m_RendererElements = new Renderer::OrthographicCameraMatrix; void Renderer::Begin(OrthographicCamera& camera) { m_RendererElements->ViewProjectionMatrix = camera.GetViewProjectionMatrix(); } void Renderer::Submit(const Ref<VertexArray>& vertexArray, const Ref<Shader>& shader) { shader->Bind(); vertexArray->Bind(); shader->SetMat4("u_ViewPorjectionMatrix", m_RendererElements->ViewProjectionMatrix); RendererCommand::Draw(vertexArray); } }
25.818182
107
0.772887
chry003
1b3a7e04b3e2384f8f7c4fec8d5927b598e19444
4,804
cpp
C++
apps/ossim-cli/ossim-cli.cpp
IvanLJF/ossim
2e0143f682b9884a09ff2598ef8737f29e44fbdf
[ "MIT" ]
1
2018-03-04T10:45:56.000Z
2018-03-04T10:45:56.000Z
apps/ossim-cli/ossim-cli.cpp
IvanLJF/ossim
2e0143f682b9884a09ff2598ef8737f29e44fbdf
[ "MIT" ]
null
null
null
apps/ossim-cli/ossim-cli.cpp
IvanLJF/ossim
2e0143f682b9884a09ff2598ef8737f29e44fbdf
[ "MIT" ]
null
null
null
//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include <iostream> #include <sstream> #include <map> using namespace std; #include <ossim/init/ossimInit.h> #include <ossim/base/ossimArgumentParser.h> #include <ossim/base/ossimApplicationUsage.h> #include <ossim/base/ossimStdOutProgress.h> #include <ossim/base/ossimTimer.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/util/ossimToolRegistry.h> #include <ossim/base/ossimException.h> #define CINFO ossimNotify(ossimNotifyLevel_INFO) #define CWARN ossimNotify(ossimNotifyLevel_WARN) #define CFATAL ossimNotify(ossimNotifyLevel_FATAL) void showAvailableCommands() { ossimToolFactoryBase* factory = ossimToolRegistry::instance(); map<string, string> capabilities; factory->getCapabilities(capabilities); map<string, string>::iterator iter = capabilities.begin(); CINFO<<"\nAvailable commands:\n"<<endl; for (;iter != capabilities.end(); ++iter) CINFO<<" "<<iter->first<<" -- "<<iter->second<<endl; CINFO<<endl; } void usage(char* appName) { CINFO << "\nUsages: \n" << " "<<appName<<" <command> [command options and parameters]\n" << " "<<appName<<" --spec <command-spec-file>\n" << " "<<appName<<" --version\n" << " "<<appName<<" help <command> -- To get help on specific command."<<endl; showAvailableCommands(); } bool runCommand(ossimArgumentParser& ap) { ossimString command = ap[1]; ap.remove(1); ossimToolFactoryBase* factory = ossimToolRegistry::instance(); ossimRefPtr<ossimTool> utility = factory->createTool(command); if (!utility.valid()) { CWARN << "\nDid not understand command <"<<command<<">"<<endl; showAvailableCommands(); return false; } ossimTimer* timer = ossimTimer::instance(); timer->setStartTick(); if (!utility->initialize(ap)) { CWARN << "\nCould not execute command <"<<command<<"> with arguments and options " "provided."<<endl; return false; } if (utility->helpRequested()) return true; if (!utility->execute()) { CWARN << "\nAn error was encountered executing the command. Check options."<<endl; return false; } //CINFO << "\nElapsed time after initialization: "<<timer->time_s()<<" s.\n"<<endl; return true; } int main(int argc, char *argv[]) { ossimArgumentParser ap (&argc, argv); ap.getApplicationUsage()->setApplicationName(argv[0]); bool status_ok = true; try { // Initialize ossim stuff, factories, plugin, etc. ossimInit::instance()->initialize(ap); do { if (argc == 1) { // Blank command line: usage(argv[0]); break; } // Spec file provided containing command's arguments and options? ossimString argv1 = argv[1]; if (( argv1 == "--spec") && (argc > 2)) { // Command line provided in spec file: ifstream ifs (argv[2]); if (ifs.fail()) { CWARN<<"\nCould not open the spec file at <"<<argv[2]<<">\n"<<endl; status_ok = false; break; } ossimString spec; ifs >> spec; ifs.close(); ossimArgumentParser new_ap(spec); status_ok = runCommand(new_ap); break; } // Need help with app or specific command? if (argv1.contains("help")) { // If no command was specified, then general usage help shown: if (argc == 2) { // Blank command line: usage(argv[0]); break; } else { // rearrange command line for individual utility help: ostringstream cmdline; cmdline<<argv[0]<<" "<<argv[2]<<" --help"; ossimArgumentParser new_ap(cmdline.str()); status_ok = runCommand(new_ap); break; } } if (argv1.string()[0] == '-') { // Treat as info call: ap.insert(1, "info"); status_ok = runCommand(ap); break; } // Conventional command line, just remove this app's name: status_ok = runCommand(ap); } while (false); } catch (const exception& e) { CFATAL<<e.what()<<endl; exit(1); } if (status_ok) exit(0); exit(1); }
28.093567
100
0.541216
IvanLJF
1b3d730d31d8ba59d01928ed4ffef1d92a825262
1,065
hpp
C++
libs/cg/include/sge/cg/parameter/detail/check_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/cg/include/sge/cg/parameter/detail/check_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/cg/include/sge/cg/parameter/detail/check_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // 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 SGE_CG_PARAMETER_DETAIL_CHECK_TYPE_HPP_INCLUDED #define SGE_CG_PARAMETER_DETAIL_CHECK_TYPE_HPP_INCLUDED #include <sge/cg/detail/symbol.hpp> #include <sge/cg/parameter/object_fwd.hpp> #include <sge/cg/parameter/detail/pp_types.hpp> #include <fcppt/config/external_begin.hpp> #include <boost/preprocessor/seq/for_each.hpp> #include <fcppt/config/external_end.hpp> namespace sge::cg::parameter::detail { template <typename Type> SGE_CG_DETAIL_SYMBOL void check_type(sge::cg::parameter::object const &); } #define SGE_CG_PARAMETER_DETAIL_DECLARE_CHECK_TYPE(seq, _, base_type) \ extern template SGE_CG_DETAIL_SYMBOL void sge::cg::parameter::detail::check_type<base_type>( \ sge::cg::parameter::object const &); BOOST_PP_SEQ_FOR_EACH( SGE_CG_PARAMETER_DETAIL_DECLARE_CHECK_TYPE, _, SGE_CG_PARAMETER_DETAIL_PP_TYPES) #endif
33.28125
96
0.781221
cpreh
1b44f1786a0e9ff5bb3663ab4bfc25af064cea78
8,420
hpp
C++
include/codegen/include/Zenject/PlaceholderFactory_11.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Zenject/PlaceholderFactory_11.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Zenject/PlaceholderFactory_11.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:44 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: Zenject.PlaceholderFactoryBase`1 #include "Zenject/PlaceholderFactoryBase_1.hpp" // Including type: Zenject.IFactory`11 #include "Zenject/IFactory_11.hpp" // Including type: System.Collections.Generic.IEnumerable`1 #include "System/Collections/Generic/IEnumerable_1.hpp" // Including type: System.Collections.Generic.IEnumerator`1 #include "System/Collections/Generic/IEnumerator_1.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: Zenject namespace Zenject { // Skipping declaration: <get_ParamTypes>d__2 because it is already included! } // Forward declaring namespace: System namespace System { // Forward declaring type: Type class Type; } // Completed forward declares // Type namespace: Zenject namespace Zenject { // Autogenerated type: Zenject.PlaceholderFactory`11 template<typename TValue, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5, typename TParam6, typename TParam7, typename TParam8, typename TParam9, typename TParam10> class PlaceholderFactory_11 : public Zenject::PlaceholderFactoryBase_1<TValue>, public Zenject::IFactory_11<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue>, public Zenject::IFactory { public: // Nested type: Zenject::PlaceholderFactory_11::$get_ParamTypes$d__2<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue> class $get_ParamTypes$d__2; // Autogenerated type: Zenject.PlaceholderFactory`11/<get_ParamTypes>d__2 class $get_ParamTypes$d__2 : public ::Il2CppObject, public ::il2cpp_utils::il2cpp_type_check::NestedType, public System::Collections::Generic::IEnumerable_1<System::Type*>, public System::Collections::IEnumerable, public System::Collections::Generic::IEnumerator_1<System::Type*>, public System::Collections::IEnumerator, public System::IDisposable { public: using declaring_type = PlaceholderFactory_11<TValue, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10>*; // private System.Int32 <>1__state // Offset: 0x0 int $$1__state; // private System.Type <>2__current // Offset: 0x0 System::Type* $$2__current; // private System.Int32 <>l__initialThreadId // Offset: 0x0 int $$l__initialThreadId; // public System.Void .ctor(System.Int32 $$1__state) // Offset: 0x15D5C40 static typename PlaceholderFactory_11<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue>::$get_ParamTypes$d__2* New_ctor(int $$1__state) { return (typename PlaceholderFactory_11<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue>::$get_ParamTypes$d__2*)CRASH_UNLESS(il2cpp_utils::New(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<typename PlaceholderFactory_11<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue>::$get_ParamTypes$d__2*>::get(), $$1__state)); } // private System.Void System.IDisposable.Dispose() // Offset: 0x15D5C80 // Implemented from: System.IDisposable // Base method: System.Void IDisposable::Dispose() void System_IDisposable_Dispose() { CRASH_UNLESS(il2cpp_utils::RunMethod(this, "System.IDisposable.Dispose")); } // private System.Boolean MoveNext() // Offset: 0x15D5C84 // Implemented from: System.Collections.IEnumerator // Base method: System.Boolean IEnumerator::MoveNext() bool MoveNext() { return CRASH_UNLESS(il2cpp_utils::RunMethod<bool>(this, "MoveNext")); } // private System.Type System.Collections.Generic.IEnumerator<System.Type>.get_Current() // Offset: 0x15D6090 // Implemented from: System.Collections.Generic.IEnumerator`1 // Base method: T IEnumerator`1::get_Current() System::Type* System_Collections_Generic_IEnumerator_1_get_Current() { return CRASH_UNLESS(il2cpp_utils::RunMethod<System::Type*>(this, "System.Collections.Generic.IEnumerator<System.Type>.get_Current")); } // private System.Void System.Collections.IEnumerator.Reset() // Offset: 0x15D6098 // Implemented from: System.Collections.IEnumerator // Base method: System.Void IEnumerator::Reset() void System_Collections_IEnumerator_Reset() { CRASH_UNLESS(il2cpp_utils::RunMethod(this, "System.Collections.IEnumerator.Reset")); } // private System.Object System.Collections.IEnumerator.get_Current() // Offset: 0x15D60F8 // Implemented from: System.Collections.IEnumerator // Base method: System.Object IEnumerator::get_Current() ::Il2CppObject* System_Collections_IEnumerator_get_Current() { return CRASH_UNLESS(il2cpp_utils::RunMethod<::Il2CppObject*>(this, "System.Collections.IEnumerator.get_Current")); } // private System.Collections.Generic.IEnumerator`1<System.Type> System.Collections.Generic.IEnumerable<System.Type>.GetEnumerator() // Offset: 0x15D6100 // Implemented from: System.Collections.Generic.IEnumerable`1 // Base method: System.Collections.Generic.IEnumerator`1<T> IEnumerable`1::GetEnumerator() System::Collections::Generic::IEnumerator_1<System::Type*>* System_Collections_Generic_IEnumerable_1_GetEnumerator() { return CRASH_UNLESS(il2cpp_utils::RunMethod<System::Collections::Generic::IEnumerator_1<System::Type*>*>(this, "System.Collections.Generic.IEnumerable<System.Type>.GetEnumerator")); } // private System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() // Offset: 0x15D6194 // Implemented from: System.Collections.IEnumerable // Base method: System.Collections.IEnumerator IEnumerable::GetEnumerator() System::Collections::IEnumerator* System_Collections_IEnumerable_GetEnumerator() { return CRASH_UNLESS(il2cpp_utils::RunMethod<System::Collections::IEnumerator*>(this, "System.Collections.IEnumerable.GetEnumerator")); } }; // Zenject.PlaceholderFactory`11/<get_ParamTypes>d__2 // public TValue Create(TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, TParam7 param7, TParam8 param8, TParam9 param9, TParam10 param10) // Offset: 0x15D61B8 TValue Create(TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, TParam7 param7, TParam8 param8, TParam9 param9, TParam10 param10) { return CRASH_UNLESS(il2cpp_utils::RunMethod<TValue>(this, "Create", param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)); } // protected override System.Collections.Generic.IEnumerable`1<System.Type> get_ParamTypes() // Offset: 0x15D64AC // Implemented from: Zenject.PlaceholderFactoryBase`1 // Base method: System.Collections.Generic.IEnumerable`1<System.Type> PlaceholderFactoryBase`1::get_ParamTypes() System::Collections::Generic::IEnumerable_1<System::Type*>* get_ParamTypes() { return CRASH_UNLESS(il2cpp_utils::RunMethod<System::Collections::Generic::IEnumerable_1<System::Type*>*>(this, "get_ParamTypes")); } // public System.Void .ctor() // Offset: 0x15D650C // Implemented from: Zenject.PlaceholderFactoryBase`1 // Base method: System.Void PlaceholderFactoryBase`1::.ctor() // Base method: System.Void Object::.ctor() static PlaceholderFactory_11<TValue, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10>* New_ctor() { return (PlaceholderFactory_11<TValue, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10>*)CRASH_UNLESS(il2cpp_utils::New(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<PlaceholderFactory_11<TValue, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10>*>::get())); } }; // Zenject.PlaceholderFactory`11 } DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(Zenject::PlaceholderFactory_11, "Zenject", "PlaceholderFactory`11"); #pragma pack(pop)
65.78125
428
0.740855
Futuremappermydud
1b46e1fbcd5e96681945dca1dce78d1d4eed6306
524
cpp
C++
src/utils.cpp
armagidon-exception/watch-os
83c9adf814313f88101d8a57da1e50c45e98bb49
[ "MIT" ]
null
null
null
src/utils.cpp
armagidon-exception/watch-os
83c9adf814313f88101d8a57da1e50c45e98bb49
[ "MIT" ]
null
null
null
src/utils.cpp
armagidon-exception/watch-os
83c9adf814313f88101d8a57da1e50c45e98bb49
[ "MIT" ]
null
null
null
#include "utils.h" void setBit(uint8_t* data, uint8_t bit, bool flag) { if (flag) { *data = *data | (1 << bit); } else { *data = *data & ~(1 << bit); } } Dimension createDimension(unit w, unit h) { return {w, h}; } Vec2D createVec2D(unit x, unit y) { return {x, y}; } sunit getVecX(Vec2D* vec) { return (sunit) vec->x; } sunit getVecY(Vec2D* vec) { return (sunit) vec->y; } unit abs(sunit x) { if (x & (1 << 7) != 0) { x = ~x; x + 1; } return x; }
16.375
52
0.5
armagidon-exception
1b4738d727dd738d156ea45e7f725d74c208cc7c
10,090
cpp
C++
modules/serialflash/spiflash.cpp
nvitya/nvcm
80b5fb2736b400a10edeecdaf24eb998dfab9759
[ "Zlib" ]
13
2018-02-26T14:56:02.000Z
2022-03-31T06:01:56.000Z
modules/serialflash/spiflash.cpp
nvitya/nvcm
80b5fb2736b400a10edeecdaf24eb998dfab9759
[ "Zlib" ]
null
null
null
modules/serialflash/spiflash.cpp
nvitya/nvcm
80b5fb2736b400a10edeecdaf24eb998dfab9759
[ "Zlib" ]
3
2020-11-04T09:15:01.000Z
2021-07-06T09:42:00.000Z
/* ----------------------------------------------------------------------------- * This file is a part of the NVCM project: https://github.com/nvitya/nvcm * Copyright (c) 2018 Viktor Nagy, nvitya * * 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. * --------------------------------------------------------------------------- */ /* * file: spiflash.cpp * brief: SPI Flash Memory Implementation * version: 1.00 * date: 2018-02-10 * authors: nvitya */ #include "spiflash.h" bool TSpiFlash::InitInherited() { if (!pin_cs.Assigned()) { return false; } if (!txdma.initialized || !rxdma.initialized) { return false; } spi.DmaAssign(true, &txdma); spi.DmaAssign(false, &rxdma); return true; } bool TSpiFlash::ReadIdCode() { txbuf[0] = 0x9F; txbuf[1] = 0x00; txbuf[2] = 0x00; txbuf[3] = 0x00; rxbuf[0] = 0; rxbuf[1] = 0; rxbuf[2] = 0; rxbuf[3] = 0; //rxbuf[0] = 0x55; rxbuf[1] = 0x56; rxbuf[2] = 0x57; rxbuf[3] = 0x58; ExecCmd(4); unsigned * up = (unsigned *)&(rxbuf[0]); idcode = (*up >> 8); if ((idcode == 0) || (idcode == 0x00FFFFFF)) { // SPI communication error return false; } return true; } void TSpiFlash::StartCmd(unsigned acmdlen) { pin_cs.Set1(); curcmdlen = acmdlen; txfer.srcaddr = &txbuf[0]; txfer.bytewidth = 1; txfer.count = curcmdlen; txfer.flags = 0; rxfer.dstaddr = &rxbuf[0]; rxfer.bytewidth = 1; rxfer.flags = 0; rxfer.count = txfer.count; pin_cs.Set0(); // activate CS spi.DmaStartRecv(&rxfer); spi.DmaStartSend(&txfer); } void TSpiFlash::ExecCmd(unsigned acmdlen) { StartCmd(acmdlen); while (!spi.DmaRecvCompleted()) { // wait } pin_cs.Set1(); } void TSpiFlash::Run() { if (0 == state) { // idle return; } if (SERIALFLASH_STATE_READMEM == state) // read memory { switch (phase) { case 0: // start remaining = datalen; txbuf[0] = 0x03; // read command txbuf[1] = ((address >> 16) & 0xFF); txbuf[2] = ((address >> 8) & 0xFF); txbuf[3] = ((address >> 0) & 0xFF); StartCmd(4); // activates the CS too phase = 1; break; case 1: // wait for address phase completition if (spi.DmaRecvCompleted()) { phase = 2; Run(); // phase jump return; } break; case 2: // start read next data chunk if (remaining == 0) { // finished. phase = 10; Run(); // phase jump return; } // start data phase chunksize = maxchunksize; if (chunksize > remaining) chunksize = remaining; txbuf[0] = 0; txfer.srcaddr = &txbuf[0]; txfer.bytewidth = 1; txfer.count = chunksize; txfer.flags = DMATR_NO_ADDR_INC; // sending the same zero character rxfer.dstaddr = dataptr; rxfer.bytewidth = 1; rxfer.flags = 0; rxfer.count = chunksize; spi.DmaStartRecv(&rxfer); spi.DmaStartSend(&txfer); phase = 3; break; case 3: // wait for completion if (spi.DmaRecvCompleted()) { // read next chunk dataptr += chunksize; remaining -= chunksize; phase = 2; Run(); // phase jump return; } // TODO: timeout handling break; case 10: // finished pin_cs.Set1(); completed = true; state = 0; // go to idle break; } } else if (SERIALFLASH_STATE_WRITEMEM == state) // write memory { switch (phase) { case 0: // initialization remaining = datalen; ++phase; break; // write next chunk case 1: // set write enable if (remaining == 0) { // finished. phase = 20; Run(); // phase jump return; } // set write enable txbuf[0] = 0x06; StartCmd(1); // activates the CS too ++phase; break; case 2: // wait for command phase completition if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS ++phase; Run(); // phase jump return; } break; case 3: // write data txbuf[0] = 0x02; // page program command txbuf[1] = ((address >> 16) & 0xFF); txbuf[2] = ((address >> 8) & 0xFF); txbuf[3] = ((address >> 0) & 0xFF); StartCmd(4); // activates the CS too ++phase; break; case 4: // wait for command phase completition if (spi.DmaRecvCompleted()) { ++phase; Run(); // phase jump return; } break; case 5: // data phase chunksize = 256 - (address & 0xFF); // page size if (chunksize > remaining) chunksize = remaining; txfer.srcaddr = dataptr; txfer.bytewidth = 1; txfer.count = chunksize; txfer.flags = 0; rxfer.dstaddr = &rxbuf[0]; rxfer.bytewidth = 1; rxfer.flags = DMATR_NO_ADDR_INC; // ignore the received data rxfer.count = chunksize; spi.DmaStartRecv(&rxfer); spi.DmaStartSend(&txfer); ++phase; break; case 6: // wait for completion if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS ++phase; Run(); return; } // TODO: timeout handling break; case 7: // read status register, repeat until BUSY flag is set StartReadStatus(); ++phase; break; case 8: if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS // check the result if (rxbuf[1] & 1) // busy { // repeat status register read phase = 7; Run(); return; } // Write finished. address += chunksize; dataptr += chunksize; remaining -= chunksize; phase = 1; Run(); // phase jump return; } // TODO: timeout break; case 20: // finished completed = true; state = 0; // go to idle break; } } else if (SERIALFLASH_STATE_ERASE == state) // erase memory { switch (phase) { case 0: // initialization // correct start address if necessary if (address & erasemask) { // correct the length too datalen += (address & erasemask); address &= ~erasemask; } // round up to 4k the data length datalen = ((datalen + erasemask) & ~erasemask); remaining = datalen; ++phase; break; // erase next sector case 1: // set write enable if (remaining == 0) { // finished. phase = 20; Run(); // phase jump return; } // set write enable txbuf[0] = 0x06; StartCmd(1); // activates the CS too ++phase; break; case 2: // wait for command phase completition if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS ++phase; Run(); // phase jump return; } break; case 3: // erase sector / block if (has4kerase && ((address & 0xFFFF) || (datalen < 0x10000))) { // 4k sector erase chunksize = 0x01000; txbuf[0] = 0x20; } else { // 64k block erase chunksize = 0x10000; txbuf[0] = 0xD8; } txbuf[1] = ((address >> 16) & 0xFF); txbuf[2] = ((address >> 8) & 0xFF); txbuf[3] = ((address >> 0) & 0xFF); StartCmd(4); // activates the CS too ++phase; break; case 4: // wait for command phase completition if (spi.DmaRecvCompleted()) { phase = 7; Run(); // phase jump return; } break; case 7: // read status register, repeat until BUSY flag is set StartReadStatus(); ++phase; break; case 8: if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS // check the result if (rxbuf[1] & 1) // busy { // repeat status register read phase = 7; Run(); return; } // Write finished. address += chunksize; remaining -= chunksize; phase = 1; Run(); // phase jump return; } // TODO: timeout break; case 20: // finished completed = true; state = 0; // go to idle break; } } else if (SERIALFLASH_STATE_ERASEALL == state) // erase all / chip { switch (phase) { case 0: // initialization ++phase; break; case 1: // set write enable // set write enable txbuf[0] = 0x06; StartCmd(1); // activates the CS too ++phase; break; case 2: // wait for command phase completition if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS ++phase; Run(); // phase jump return; } break; case 3: // issue bulk erase txbuf[0] = 0xC7; StartCmd(1); // activates the CS too ++phase; break; case 4: // wait for command phase completition if (spi.DmaRecvCompleted()) { phase = 7; Run(); // phase jump return; } break; case 7: // read status register, repeat until BUSY flag is set StartReadStatus(); ++phase; break; case 8: if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS // check the result if (rxbuf[1] & 1) // busy { // repeat status register read phase = 7; Run(); return; } // finished. phase = 20; Run(); // phase jump return; } // TODO: timeout break; case 20: // finished completed = true; state = 0; // go to idle break; } } } bool TSpiFlash::StartReadStatus() { txbuf[0] = 0x05; txbuf[1] = 0x00; rxbuf[1] = 0x7F; StartCmd(2); return true; } void TSpiFlash::ResetChip() { txbuf[0] = 0x66; ExecCmd(1); txbuf[0] = 0x99; ExecCmd(1); }
20.50813
81
0.56888
nvitya
1b48e13003361890ece0a6ccd6af14a81d94865b
48
hpp
C++
examples/shared-sources/Source/Hello.hpp
chaos0x8/rake-builder
6320739bc1f4e9a9ec31af5cb12bf813b30eed66
[ "MIT" ]
2
2020-10-27T11:32:42.000Z
2020-10-28T21:12:20.000Z
examples/shared-sources/Source/Hello.hpp
chaos0x8/rake-builder
6320739bc1f4e9a9ec31af5cb12bf813b30eed66
[ "MIT" ]
null
null
null
examples/shared-sources/Source/Hello.hpp
chaos0x8/rake-builder
6320739bc1f4e9a9ec31af5cb12bf813b30eed66
[ "MIT" ]
null
null
null
#pragma once namespace lib { void hello(); }
8
15
0.645833
chaos0x8
1b4dc36550029270b7674cb5c6607127fc4f5938
556
hpp
C++
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/snes/system/audio.hpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
1,414
2015-06-28T09:57:51.000Z
2021-10-14T03:51:10.000Z
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/snes/system/audio.hpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
2,369
2015-06-25T01:45:44.000Z
2021-10-16T08:44:18.000Z
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/snes/system/audio.hpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
430
2015-06-29T04:28:58.000Z
2021-10-05T18:24:17.000Z
struct Audio { void coprocessor_enable(bool state); void coprocessor_frequency(double frequency); void sample(int16 lsample, int16 rsample); void coprocessor_sample(int16 lsample, int16 rsample); void init(); private: nall::DSP dspaudio; bool coprocessor; enum : unsigned { buffer_size = 256, buffer_mask = buffer_size - 1 }; uint32 dsp_buffer[buffer_size], cop_buffer[buffer_size]; unsigned dsp_rdoffset, cop_rdoffset; unsigned dsp_wroffset, cop_wroffset; unsigned dsp_length, cop_length; void flush(); }; extern Audio audio;
26.47619
71
0.757194
redscientistlabs
1b51f0f5083947eacae4626a9abc0faf9a1f657b
7,706
cpp
C++
artifact/storm/src/storm/modelchecker/prctl/helper/BaierUpperRewardBoundsComputer.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/modelchecker/prctl/helper/BaierUpperRewardBoundsComputer.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/modelchecker/prctl/helper/BaierUpperRewardBoundsComputer.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
1
2022-02-05T12:39:53.000Z
2022-02-05T12:39:53.000Z
#include "storm/modelchecker/prctl/helper/BaierUpperRewardBoundsComputer.h" #include "storm/adapters/RationalNumberAdapter.h" #include "storm/storage/SparseMatrix.h" #include "storm/storage/BitVector.h" #include "storm/storage/StronglyConnectedComponentDecomposition.h" #include "storm/utility/macros.h" namespace storm { namespace modelchecker { namespace helper { template<typename ValueType> BaierUpperRewardBoundsComputer<ValueType>::BaierUpperRewardBoundsComputer(storm::storage::SparseMatrix<ValueType> const& transitionMatrix, std::vector<ValueType> const& rewards, std::vector<ValueType> const& oneStepTargetProbabilities) : _transitionMatrix(transitionMatrix), _rewards(rewards), _oneStepTargetProbabilities(oneStepTargetProbabilities) { // Intentionally left empty. } template<typename ValueType> std::vector<ValueType> BaierUpperRewardBoundsComputer<ValueType>::computeUpperBoundOnExpectedVisitingTimes(storm::storage::SparseMatrix<ValueType> const& transitionMatrix, std::vector<ValueType> const& oneStepTargetProbabilities) { std::vector<uint64_t> stateToScc(transitionMatrix.getRowGroupCount()); { // Start with an SCC decomposition of the system. storm::storage::StronglyConnectedComponentDecomposition<ValueType> sccDecomposition(transitionMatrix); uint64_t sccIndex = 0; for (auto const& block : sccDecomposition) { for (auto const& state : block) { stateToScc[state] = sccIndex; } ++sccIndex; } } // The states that we still need to assign a value. storm::storage::BitVector remainingStates(transitionMatrix.getRowGroupCount(), true); // A choice is valid iff it goes to non-remaining states with non-zero probability. storm::storage::BitVector validChoices(transitionMatrix.getRowCount()); // Initially, mark all choices as valid that have non-zero probability to go to the target states directly. uint64_t index = 0; for (auto const& e : oneStepTargetProbabilities) { if (!storm::utility::isZero(e)) { validChoices.set(index); } ++index; } // Vector that holds the result. std::vector<ValueType> result(transitionMatrix.getRowGroupCount()); // Process all states as long as there are remaining ones. std::vector<uint64_t> newStates; while (!remainingStates.empty()) { for (auto state : remainingStates) { bool allChoicesValid = true; for (auto row = transitionMatrix.getRowGroupIndices()[state], endRow = transitionMatrix.getRowGroupIndices()[state + 1]; row < endRow; ++row) { if (validChoices.get(row)) { continue; } bool choiceValid = false; for (auto const& entry : transitionMatrix.getRow(row)) { if (storm::utility::isZero(entry.getValue())) { continue; } if (!remainingStates.get(entry.getColumn())) { choiceValid = true; break; } } if (choiceValid) { validChoices.set(row); } else { allChoicesValid = false; } } if (allChoicesValid) { newStates.push_back(state); } } // Compute d_t over the newly found states. for (auto state : newStates) { result[state] = storm::utility::one<ValueType>(); for (auto row = transitionMatrix.getRowGroupIndices()[state], endRow = transitionMatrix.getRowGroupIndices()[state + 1]; row < endRow; ++row) { ValueType rowValue = oneStepTargetProbabilities[row]; for (auto const& entry : transitionMatrix.getRow(row)) { if (!remainingStates.get(entry.getColumn())) { rowValue += entry.getValue() * (stateToScc[state] == stateToScc[entry.getColumn()] ? result[entry.getColumn()] : storm::utility::one<ValueType>()); } } STORM_LOG_ASSERT(rowValue > storm::utility::zero<ValueType>(), "Expected entry with value greater 0."); result[state] = std::min(result[state], rowValue); } } remainingStates.set(newStates.begin(), newStates.end(), false); newStates.clear(); } // Transform the d_t to an upper bound for zeta(t) for (auto& r : result) { r = storm::utility::one<ValueType>() / r; } return result; } template<typename ValueType> ValueType BaierUpperRewardBoundsComputer<ValueType>::computeUpperBound() { STORM_LOG_TRACE("Computing upper reward bounds using variant-2 of Baier et al."); std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now(); auto expVisits = computeUpperBoundOnExpectedVisitingTimes(_transitionMatrix, _oneStepTargetProbabilities); ValueType upperBound = storm::utility::zero<ValueType>(); for (uint64_t state = 0; state < expVisits.size(); ++state) { ValueType maxReward = storm::utility::zero<ValueType>(); for (auto row = _transitionMatrix.getRowGroupIndices()[state], endRow = _transitionMatrix.getRowGroupIndices()[state + 1]; row < endRow; ++row) { maxReward = std::max(maxReward, _rewards[row]); } upperBound += expVisits[state] * maxReward; } STORM_LOG_TRACE("Baier algorithm for reward bound computation (variant 2) computed bound " << upperBound << "."); std::chrono::high_resolution_clock::time_point end = std::chrono::high_resolution_clock::now(); STORM_LOG_TRACE("Computed upper bounds on rewards in " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms."); return upperBound; } template class BaierUpperRewardBoundsComputer<double>; #ifdef STORM_HAVE_CARL template class BaierUpperRewardBoundsComputer<storm::RationalNumber>; #endif } } }
53.513889
363
0.511549
glatteis
1b53a37578a685ec07c72fc040ef7929d3048973
1,378
cpp
C++
Deitel/Chapter06/exercises/6.17/ex_617.cpp
SebastianTirado/Cpp-Learning-Archive
fb83379d0cc3f9b2390cef00119464ec946753f4
[ "MIT" ]
19
2019-09-15T12:23:51.000Z
2020-06-18T08:31:26.000Z
Deitel/Chapter06/exercises/6.17/ex_617.cpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
15
2021-12-07T06:46:03.000Z
2022-01-31T07:55:32.000Z
Deitel/Chapter06/exercises/6.17/ex_617.cpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
13
2019-06-29T02:58:27.000Z
2020-05-07T08:52:22.000Z
/* * ===================================================================================== * * Filename: * * Description: * * Version: 1.0 * Created: Thanks to github you know it * Revision: none * Compiler: g++ * * Author: Mahmut Erdem ÖZGEN m.erdemozgen@gmail.com * * * ===================================================================================== */ #include <iostream> #include <random> #include <vector> std::random_device rd; std::mt19937 gen(rd()); int getRandomNumber(const int&, const int&); int main(int argc, const char *argv[]) { // offsets v set 1 v v set 2 v v set 3 v std::vector<int> set {2, 4, 6, 8, 10, 2, 5, 7, 9, 11, 6, 10, 14, 18, 22}; std::cout << "Random number from each of the following sets: " << std::endl; std::cout << "\n2 4 6 8 10: " << set[getRandomNumber(0, 4)]; std::cout << "\n2 5 7 9 11: " << set[getRandomNumber(5, 9)]; std::cout << "\n6 10 14 18 22: " << set[getRandomNumber(10, set.size() - 1)] << std::endl; return 0; } /** * Creates a random distribution and returns a value in the range min max. * @param int * @param int * @return int */ int getRandomNumber(const int& min, const int& max) { return std::uniform_int_distribution<int>{min, max}(gen); } // end method getRandomNumber
28.708333
94
0.498549
SebastianTirado
1b5e0ce8d017488337862f7e9b41acfffb6ff73d
1,936
cpp
C++
src/trace/buffer.cpp
ArnauBigas/chopstix
37831cdbddf8ad3b11e9cc8fd2dd2999907e44ed
[ "Apache-2.0" ]
3
2019-06-06T12:57:24.000Z
2020-03-21T15:25:48.000Z
src/trace/buffer.cpp
ArnauBigas/chopstix
37831cdbddf8ad3b11e9cc8fd2dd2999907e44ed
[ "Apache-2.0" ]
32
2019-06-17T20:31:33.000Z
2022-03-02T16:43:41.000Z
src/trace/buffer.cpp
ArnauBigas/chopstix
37831cdbddf8ad3b11e9cc8fd2dd2999907e44ed
[ "Apache-2.0" ]
5
2019-06-06T12:57:41.000Z
2020-06-29T14:42:02.000Z
/* # # ---------------------------------------------------------------------------- # # Copyright 2019 IBM 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 "buffer.h" #include "support/check.h" #include "support/safeformat.h" #include <fcntl.h> #include <linux/limits.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <sys/syscall.h> using namespace chopstix; #define PERM_664 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH TraceBuffer::~TraceBuffer() { if (pos_ > 0) write_back(); if (fd_ != -1) { syscall(SYS_close, fd_); fd_ = -1; } } void TraceBuffer::setup(const char *trace_root) { char fpath[PATH_MAX]; sfmt::format(fpath, sizeof(fpath), "%s/trace.bin", trace_root); fd_ = syscall(SYS_openat, AT_FDCWD, fpath, O_WRONLY | O_CREAT | O_TRUNC, PERM_664); check(fd_ != -1, "Unable to open 'trace.bin'"); } void TraceBuffer::start_trace(int trace_id, bool isNewInvocation) { if(isNewInvocation) write(-3); write(-1); } void TraceBuffer::stop_trace(int trace_id) { write(-2); } void TraceBuffer::save_page(long page_addr) { write(page_addr); } void TraceBuffer::write_back() { syscall(SYS_write, fd_, buf_, pos_ * sizeof(long)); pos_ = 0; } void TraceBuffer::write(long dat) { if (pos_ == buf_size) write_back(); buf_[pos_++] = dat; }
27.657143
111
0.63843
ArnauBigas
1b62def7ce8e586f33b3d5b271743adf094d9136
2,987
cpp
C++
aws-cpp-sdk-imagebuilder/source/model/PipelineExecutionStartCondition.cpp
grujicbr/aws-sdk-cpp
bdd43c178042f09c6739645e3f6cd17822a7c35c
[ "Apache-2.0" ]
1
2020-03-11T05:36:20.000Z
2020-03-11T05:36:20.000Z
aws-cpp-sdk-imagebuilder/source/model/PipelineExecutionStartCondition.cpp
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-imagebuilder/source/model/PipelineExecutionStartCondition.cpp
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/imagebuilder/model/PipelineExecutionStartCondition.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace imagebuilder { namespace Model { namespace PipelineExecutionStartConditionMapper { static const int EXPRESSION_MATCH_ONLY_HASH = HashingUtils::HashString("EXPRESSION_MATCH_ONLY"); static const int EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE_HASH = HashingUtils::HashString("EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE"); PipelineExecutionStartCondition GetPipelineExecutionStartConditionForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == EXPRESSION_MATCH_ONLY_HASH) { return PipelineExecutionStartCondition::EXPRESSION_MATCH_ONLY; } else if (hashCode == EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE_HASH) { return PipelineExecutionStartCondition::EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<PipelineExecutionStartCondition>(hashCode); } return PipelineExecutionStartCondition::NOT_SET; } Aws::String GetNameForPipelineExecutionStartCondition(PipelineExecutionStartCondition enumValue) { switch(enumValue) { case PipelineExecutionStartCondition::EXPRESSION_MATCH_ONLY: return "EXPRESSION_MATCH_ONLY"; case PipelineExecutionStartCondition::EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE: return "EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace PipelineExecutionStartConditionMapper } // namespace Model } // namespace imagebuilder } // namespace Aws
36.876543
160
0.709742
grujicbr