hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
float64
1
77k
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
float64
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
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
dee9518ffeb35a2f6dc7b3f566346a6fd6e6d3fd
22,804
cpp
C++
src/slib/db/sqlite.cpp
emarc99/SLib
4e492d6c550f845fd1b3f40bf10183097eb0e53c
[ "MIT" ]
146
2017-03-21T07:50:43.000Z
2022-03-19T03:32:22.000Z
src/slib/db/sqlite.cpp
Crasader/SLib
4e492d6c550f845fd1b3f40bf10183097eb0e53c
[ "MIT" ]
50
2017-03-22T04:08:15.000Z
2019-10-21T16:55:48.000Z
src/slib/db/sqlite.cpp
Crasader/SLib
4e492d6c550f845fd1b3f40bf10183097eb0e53c
[ "MIT" ]
55
2017-03-21T07:52:58.000Z
2021-12-27T13:02:08.000Z
/* * Copyright (c) 2008-2019 SLIBIO <https://github.com/SLIBIO> * * 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 "sqlite/sqlite3.h" #include "slib/db/sqlite.h" #include "slib/db/sql.h" #include "slib/core/file.h" #include "slib/core/log.h" #include "slib/core/scoped.h" #include "slib/core/safe_static.h" #include "slib/crypto/sha2.h" #include "slib/crypto/chacha.h" #define TAG "SQLiteDatabase" #define ENCRYPTION_PREFIX_SIZE 80 namespace slib { SLIB_DEFINE_CLASS_DEFAULT_MEMBERS(SQLiteParam) SQLiteParam::SQLiteParam() { flagCreate = sl_true; flagReadonly = sl_false; } SLIB_DEFINE_OBJECT(SQLiteDatabase, Database) SQLiteDatabase::SQLiteDatabase() { m_dialect = DatabaseDialect::SQLite; } SQLiteDatabase::~SQLiteDatabase() { } namespace priv { namespace sqlite { class DatabaseImpl; class CursorImpl : public DatabaseCursor { public: Ref<DatabaseStatement> m_statementObj; sqlite3_stmt* m_statement; CList<String> m_listColumnNames; sl_uint32 m_nColumnNames; String* m_columnNames; CHashMap<String, sl_int32> m_mapColumnIndexes; public: CursorImpl(Database* db, DatabaseStatement* statementObj, sqlite3_stmt* statement) { m_db = db; m_statementObj = statementObj; m_statement = statement; sl_int32 cols = sqlite3_column_count(statement); for (sl_int32 i = 0; i < cols; i++) { const char* buf = sqlite3_column_name(statement, (int)i); String name = String::create(buf); m_listColumnNames.add_NoLock(name); m_mapColumnIndexes.put_NoLock(name, i); } m_nColumnNames = (sl_uint32)(m_listColumnNames.getCount()); m_columnNames = m_listColumnNames.getData(); db->lock(); } ~CursorImpl() { sqlite3_reset(m_statement); sqlite3_clear_bindings(m_statement); m_db->unlock(); } public: sl_uint32 getColumnsCount() override { return m_nColumnNames; } String getColumnName(sl_uint32 index) override { if (index < m_nColumnNames) { return m_columnNames[index]; } return sl_null; } sl_int32 getColumnIndex(const StringParam& name) override { return m_mapColumnIndexes.getValue_NoLock(name.toString(), -1); } HashMap<String, Variant> getRow() override { HashMap<String, Variant> ret; if (m_nColumnNames > 0) { for (sl_uint32 index = 0; index < m_nColumnNames; index++) { ret.put_NoLock(m_columnNames[index], _getValue(index)); } } return ret; } String _getString(sl_uint32 index) { int n = sqlite3_column_bytes(m_statement, index); const void* buf = sqlite3_column_text(m_statement, index); if (buf && n > 0) { return String::fromUtf8(buf, n); } return String::getEmpty(); } Memory _getBlob(sl_uint32 index) { int n = sqlite3_column_bytes(m_statement, index); const void* buf = sqlite3_column_blob(m_statement, index); if (buf && n > 0) { return Memory::create(buf, n); } return sl_null; } Variant _getValue(sl_uint32 index) { int type = sqlite3_column_type(m_statement, index); switch (type) { case SQLITE_INTEGER: { sl_int64 v64 = sqlite3_column_int64(m_statement, index); sl_int32 v32 = (sl_int32)v64; if (v64 == v32) { return v32; } else { return v64; } } break; case SQLITE_FLOAT: return sqlite3_column_double(m_statement, index); case SQLITE_TEXT: return _getString(index); case SQLITE_BLOB: return _getBlob(index); } return sl_null; } Variant getValue(sl_uint32 index) override { if (index < m_nColumnNames) { return _getValue(index); } return sl_null; } String getString(sl_uint32 index) override { if (index < m_nColumnNames) { int type = sqlite3_column_type(m_statement, index); switch (type) { case SQLITE_INTEGER: return String::fromInt64(sqlite3_column_int64(m_statement, index)); case SQLITE_FLOAT: return String::fromDouble(sqlite3_column_double(m_statement, index)); case SQLITE_TEXT: return _getString(index); } } return sl_null; } sl_int64 getInt64(sl_uint32 index, sl_int64 defaultValue) override { if (index < m_nColumnNames) { int type = sqlite3_column_type(m_statement, index); switch (type) { case SQLITE_INTEGER: return sqlite3_column_int64(m_statement, index); case SQLITE_FLOAT: return (sl_int64)(sqlite3_column_double(m_statement, index)); case SQLITE_TEXT: return _getString(index).parseInt64(10, defaultValue); } } return defaultValue; } sl_uint64 getUint64(sl_uint32 index, sl_uint64 defaultValue) override { if (index < m_nColumnNames) { int type = sqlite3_column_type(m_statement, index); switch (type) { case SQLITE_INTEGER: return sqlite3_column_int64(m_statement, index); case SQLITE_FLOAT: return (sl_uint64)(sqlite3_column_double(m_statement, index)); case SQLITE_TEXT: return _getString(index).parseUint64(10, defaultValue); } } return defaultValue; } sl_int32 getInt32(sl_uint32 index, sl_int32 defaultValue) override { if (index < m_nColumnNames) { int type = sqlite3_column_type(m_statement, index); switch (type) { case SQLITE_INTEGER: return sqlite3_column_int(m_statement, index); case SQLITE_FLOAT: return (sl_int32)(sqlite3_column_double(m_statement, index)); case SQLITE_TEXT: return _getString(index).parseInt32(10, defaultValue); } } return defaultValue; } sl_uint32 getUint32(sl_uint32 index, sl_uint32 defaultValue) override { if (index < m_nColumnNames) { int type = sqlite3_column_type(m_statement, index); switch (type) { case SQLITE_INTEGER: return (sl_uint32)(sqlite3_column_int64(m_statement, index)); case SQLITE_FLOAT: return (sl_uint32)(sqlite3_column_double(m_statement, index)); case SQLITE_TEXT: return _getString(index).parseUint32(10, defaultValue); } } return defaultValue; } float getFloat(sl_uint32 index, float defaultValue) override { if (index < m_nColumnNames) { int type = sqlite3_column_type(m_statement, index); switch (type) { case SQLITE_INTEGER: return (float)(sqlite3_column_int64(m_statement, index)); case SQLITE_FLOAT: return (float)(sqlite3_column_double(m_statement, index)); case SQLITE_TEXT: return _getString(index).parseFloat(defaultValue); } } return defaultValue; } double getDouble(sl_uint32 index, double defaultValue) override { if (index < m_nColumnNames) { int type = sqlite3_column_type(m_statement, index); switch (type) { case SQLITE_INTEGER: return (double)(sqlite3_column_int64(m_statement, index)); case SQLITE_FLOAT: return (sqlite3_column_double(m_statement, index)); case SQLITE_TEXT: return _getString(index).parseDouble(defaultValue); } } return defaultValue; } Memory getBlob(sl_uint32 index) override { if (index < m_nColumnNames) { int type = sqlite3_column_type(m_statement, index); switch (type) { case SQLITE_TEXT: case SQLITE_BLOB: return _getBlob(index); } } return sl_null; } sl_bool moveNext() override { sl_int32 nRet = sqlite3_step(m_statement); if (nRet == SQLITE_ROW) { return sl_true; } return sl_false; } }; class StatementImpl : public DatabaseStatement { public: sqlite3* m_sqlite; sqlite3_stmt* m_statement; Array<Variant> m_boundParams; public: StatementImpl(Database* db, sqlite3* sqlite, sqlite3_stmt* statement) { m_db = db; m_sqlite = sqlite; m_statement = statement; } ~StatementImpl() { sqlite3_finalize(m_statement); } public: sl_bool isLoggingErrors() { if (m_db.isNotNull()) { return m_db->isLoggingErrors(); } return sl_false; } sl_bool _execute(const Variant* _params, sl_uint32 nParams) { sqlite3_reset(m_statement); sqlite3_clear_bindings(m_statement); m_boundParams.setNull(); if (nParams == 0) { return sl_true; } Array<Variant> params = Array<Variant>::create(_params, nParams); if (params.isNull()) { return sl_false; } sl_uint32 n = (sl_uint32)(sqlite3_bind_parameter_count(m_statement)); if (n == nParams) { if (n > 0) { for (sl_uint32 i = 0; i < n; i++) { int iRet = SQLITE_ABORT; Variant& var = (params.getData())[i]; switch (var.getType()) { case VariantType::Null: iRet = sqlite3_bind_null(m_statement, i+1); break; case VariantType::Boolean: case VariantType::Int32: iRet = sqlite3_bind_int(m_statement, i+1, var.getInt32()); break; case VariantType::Uint32: case VariantType::Int64: case VariantType::Uint64: iRet = sqlite3_bind_int64(m_statement, i+1, var.getInt64()); break; case VariantType::Float: case VariantType::Double: iRet = sqlite3_bind_double(m_statement, i+1, var.getDouble()); break; default: if (var.isMemory()) { Memory mem = var.getMemory(); sl_size size = mem.getSize(); if (size > 0x7fffffff) { iRet = sqlite3_bind_blob64(m_statement, i+1, mem.getData(), size, SQLITE_STATIC); } else { iRet = sqlite3_bind_blob(m_statement, i+1, mem.getData(), (sl_uint32)size, SQLITE_STATIC); } } else { String str = var.getString(); var = str; iRet = sqlite3_bind_text(m_statement, i+1, str.getData(), (sl_uint32)(str.getLength()), SQLITE_STATIC); } } if (iRet != SQLITE_OK) { return sl_false; } } } m_boundParams = params; return sl_true; } else { if (isLoggingErrors()) { LogError(TAG, "Bind error: requires %d params but %d params provided", n, nParams); } } return sl_false; } sl_int64 executeBy(const Variant* params, sl_uint32 nParams) override { ObjectLocker lock(m_db.get()); if (_execute(params, nParams)) { if (sqlite3_step(m_statement) == SQLITE_DONE) { sqlite3_reset(m_statement); sqlite3_clear_bindings(m_statement); return sqlite3_changes(m_sqlite); } } return -1; } Ref<DatabaseCursor> queryBy(const Variant* params, sl_uint32 nParams) override { ObjectLocker lock(m_db.get()); Ref<DatabaseCursor> ret; if (_execute(params, nParams)) { ret = new CursorImpl(m_db.get(), this, m_statement); if (ret.isNotNull()) { return ret; } sqlite3_reset(m_statement); sqlite3_clear_bindings(m_statement); } return ret; } }; class EncryptionVfs : public sqlite3_vfs { public: DatabaseImpl* db; }; class EncryptionIo : public sqlite3_io_methods { public: DatabaseImpl* db; const sqlite3_io_methods* ioOriginal; ChaCha20_Core encrypt; sl_uint32 encryptIV[4]; }; struct EncryptionCustomFile { EncryptionIo io; }; class DatabaseImpl : public SQLiteDatabase { public: sqlite3* m_db; EncryptionVfs m_vfs; sqlite3_vfs* m_vfsOriginal; int m_vfsFileCustomOffset; char m_encryptionKey[32]; public: DatabaseImpl() { m_db = sl_null; } ~DatabaseImpl() { if (m_db) { sqlite3_close(m_db); } } static Ref<DatabaseImpl> open(const SQLiteParam& param) { Ref<DatabaseImpl> ret = new DatabaseImpl; if (ret.isNotNull()) { if (ret->initialize(param)) { return ret; } } return sl_null; } sl_bool initialize(const SQLiteParam& param) { sqlite3* db = sl_null; int flags; if (param.flagCreate) { flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; } else { flags = param.flagReadonly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_READWRITE; } int iResult; if (param.encryptionKey.isNotEmpty()) { SHA256::hash(param.encryptionKey, m_encryptionKey); sqlite3_vfs* vfsDefault = sqlite3_vfs_find(0); Base::copyMemory(&m_vfs, vfsDefault, sizeof(sqlite3_vfs)); m_vfs.db = this; m_vfs.zName = "slib_encryption"; m_vfs.xOpen = &xOpenEncryption; m_vfsFileCustomOffset = ((m_vfs.szOsFile - 1) | 15) + 1; m_vfs.szOsFile = m_vfsFileCustomOffset + sizeof(EncryptionCustomFile); m_vfsOriginal = vfsDefault; SLIB_SAFE_STATIC(Mutex, mutex) MutexLocker lock(&mutex); sqlite3_vfs_register(&m_vfs, 0); iResult = sqlite3_open_v2(param.path.getData(), &db, flags, m_vfs.zName); sqlite3_vfs_unregister(&m_vfs); } else { iResult = sqlite3_open_v2(param.path.getData(), &db, flags, sl_null); } if (SQLITE_OK == iResult) { m_db = db; return sl_true; } return sl_false; } static int xOpenEncryption(sqlite3_vfs* vfs, const char *zName, sqlite3_file* file, int flags, int *pOutFlags) { return ((EncryptionVfs*)vfs)->db->onOpenEncryption(vfs, zName, file, flags, pOutFlags); } int onOpenEncryption(sqlite3_vfs* vfs, const char *zName, sqlite3_file* file, int flags, int *pOutFlags) { int iRet = (m_vfsOriginal->xOpen)(vfs, zName, file, flags, pOutFlags); if (iRet == SQLITE_OK) { EncryptionCustomFile* custom = (EncryptionCustomFile*)(((char*)(void*)file) + m_vfsFileCustomOffset); Base::copyMemory(&(custom->io), file->pMethods, sizeof(sqlite3_io_methods)); custom->io.db = this; custom->io.ioOriginal = file->pMethods; custom->io.iVersion = 0; custom->io.xRead = &xReadEncryption; custom->io.xWrite = &xWriteEncryption; custom->io.xTruncate = &xTruncateEncryption; custom->io.xFileSize = &xFileSizeEncryption; sqlite3_int64 size = 0; (file->pMethods->xFileSize)(file, &size); if (!size) { (vfs->xRandomness)(vfs, 4, (char*)(custom->io.encryptIV)); (vfs->xRandomness)(vfs, 4, (char*)(custom->io.encryptIV + 1)); (vfs->xRandomness)(vfs, 4, (char*)(custom->io.encryptIV + 2)); (vfs->xRandomness)(vfs, 4, (char*)(custom->io.encryptIV + 3)); char header[ENCRYPTION_PREFIX_SIZE]; MIO::writeUint32LE(header, custom->io.encryptIV[0]); MIO::writeUint32LE(header + 4, custom->io.encryptIV[1]); MIO::writeUint32LE(header + 8, custom->io.encryptIV[2]); MIO::writeUint32LE(header + 12, custom->io.encryptIV[3]); (vfs->xRandomness)(vfs, 32, header + 16); char check[48]; Base::copyMemory(check, header, 16); Base::copyMemory(check + 16, m_encryptionKey, 32); char h[32]; SHA256::hash(check, 48, h); Base::copyMemory(header + 48, h, 32); iRet = (file->pMethods->xWrite)(file, header, ENCRYPTION_PREFIX_SIZE, 0); if (iRet != SQLITE_OK) { file->pMethods = sl_null; return iRet; } char key[32]; for (int i = 0; i < 32; i++) { key[i] = header[16 + i] ^ m_encryptionKey[i]; } custom->io.encrypt.setKey(key, 32); } else { char header[ENCRYPTION_PREFIX_SIZE]; iRet = (file->pMethods->xRead)(file, header, ENCRYPTION_PREFIX_SIZE, 0); if (iRet != SQLITE_OK) { file->pMethods = sl_null; return iRet; } char check[48]; Base::copyMemory(check, header, 16); Base::copyMemory(check + 16, m_encryptionKey, 32); char h[32]; SHA256::hash(check, 48, h); if (!(Base::equalsMemory(h, header + 48, 32))) { file->pMethods = sl_null; return SQLITE_AUTH; } custom->io.encryptIV[0] = MIO::readUint32LE(header); custom->io.encryptIV[1] = MIO::readUint32LE(header + 4); custom->io.encryptIV[2] = MIO::readUint32LE(header + 8); custom->io.encryptIV[3] = MIO::readUint32LE(header + 12); char key[32]; for (int i = 0; i < 32; i++) { key[i] = header[16 + i] ^ m_encryptionKey[i]; } custom->io.encrypt.setKey(key, 32); } file->pMethods = &(custom->io); } return iRet; } static int xReadEncryption(sqlite3_file* file, void* buf, int iAmt, sqlite3_int64 iOfst) { EncryptionIo* io = (EncryptionIo*)(file->pMethods); int iRet = (io->ioOriginal->xRead)(file, buf, iAmt, iOfst + ENCRYPTION_PREFIX_SIZE); if (iRet == SQLITE_OK && iAmt > 0) { io->db->encrypt(io, iOfst, buf, iAmt); } return iRet; } static int xWriteEncryption(sqlite3_file* file, const void* buf, int iAmt, sqlite3_int64 iOfst) { EncryptionIo* io = (EncryptionIo*)(file->pMethods); if (iAmt > 0) { int n = iAmt >> 10; if (iAmt & 1023) { n++; } char* b = (char*)buf; char t[1024]; sqlite3_int64 o = iOfst; for (int i = 0; i < n; i++) { int size = iAmt; if (size > 1024) { size = 1024; } Base::copyMemory(t, b, (sl_size)size); io->db->encrypt(io, o, t, size); int iRet = (io->ioOriginal->xWrite)(file, t, size, o + ENCRYPTION_PREFIX_SIZE); if (iRet != SQLITE_OK) { return iRet; } o += 1024; b += 1024; iAmt -= 1024; } } return SQLITE_OK; } static int xTruncateEncryption(sqlite3_file* file, sqlite3_int64 size) { EncryptionIo* io = (EncryptionIo*)(file->pMethods); return (io->ioOriginal->xTruncate)(file, size + ENCRYPTION_PREFIX_SIZE); } static int xFileSizeEncryption(sqlite3_file* file, sqlite3_int64 *pSize) { EncryptionIo* io = (EncryptionIo*)(file->pMethods); int iResult = (io->ioOriginal->xFileSize)(file, pSize); if (iResult == SQLITE_OK) { if (*pSize > ENCRYPTION_PREFIX_SIZE) { *pSize -= ENCRYPTION_PREFIX_SIZE; } else { *pSize = 0; } } return iResult; } void encrypt(EncryptionIo* io, sqlite3_int64 iOfst, void* buf, int size) { if (iOfst < 0) { return; } if (size < 1) { return; } sl_uint64 offset = (sl_uint64)iOfst; sl_uint64 block = offset >> 6; sl_uint32 pos = (sl_uint32)(offset & 63); sl_uint64 offsetEnd = (sl_uint64)(iOfst + size); sl_uint64 blockEnd = offsetEnd >> 6; sl_uint32 posEnd = (sl_uint32)(offsetEnd & 63); char* b = (char*)buf; char h[64]; for (; block <= blockEnd; block++) { io->encrypt.generateBlock(io->encryptIV[0], io->encryptIV[1], io->encryptIV[2] + ((sl_uint32)(block >> 32)), io->encryptIV[3] + ((sl_uint32)block), h); sl_uint32 e; if (block == blockEnd) { e = posEnd; } else { e = 64; } sl_uint32 n = e - pos; for (sl_uint32 i = 0; i < n; i++) { b[i] ^= h[pos + i]; } b += n; pos = 0; } } sl_int64 _execute(const StringParam& _sql) override { StringCstr sql(_sql); ObjectLocker lock(this); if (SQLITE_OK == sqlite3_exec(m_db, sql.getData(), 0, 0, sl_null)) { return sqlite3_changes(m_db); } return -1; } Ref<DatabaseStatement> _prepareStatement(const StringParam& _sql) override { StringCstr sql(_sql); ObjectLocker lock(this); Ref<DatabaseStatement> ret; sqlite3_stmt* statement = sl_null; if (SQLITE_OK == sqlite3_prepare_v2(m_db, sql.getData(), -1, &statement, sl_null)) { ret = new StatementImpl(this, m_db, statement); if (ret.isNotNull()) { return ret; } sqlite3_finalize(statement); } return ret; } String getErrorMessage() override { String error = String::create(sqlite3_errmsg(m_db)); if (error.isEmpty() || error == "not an error") { return sl_null; } return error; } sl_bool isDatabaseExisting(const StringParam& name) override { return sl_false; } List<String> getDatabases() override { return sl_null; } sl_bool isTableExisting(const StringParam& _name) override { SqlBuilder builder(m_dialect); SLIB_STATIC_STRING(s, "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name LIKE ") builder.append(s); StringData name(_name); builder.appendIdentifier(name.getData(), name.getLength()); return getValue(builder.toString()).getUint32() > 0; } List<String> getTables() override { List<String> ret; Ref<DatabaseCursor> cursor = query("SELECT name FROM sqlite_master WHERE type='table'"); if (cursor.isNotNull()) { while (cursor->moveNext()) { ret.add_NoLock(cursor->getString(0)); } } return ret; } sl_uint64 getLastInsertRowId() override { return (sl_uint64)(sqlite3_last_insert_rowid(m_db)); } }; } } Ref<SQLiteDatabase> SQLiteDatabase::open(const SQLiteParam& param) { return priv::sqlite::DatabaseImpl::open(param); } Ref<SQLiteDatabase> SQLiteDatabase::open(const String& path) { SQLiteParam param; param.path = path; return priv::sqlite::DatabaseImpl::open(param); } }
28.433915
157
0.620944
deeb50bf2737a13113f6383e8c965541b118890b
7,337
hpp
C++
Extensions/Gameplay/IndexedHalfEdgeMesh.hpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
1
2022-03-26T21:08:19.000Z
2022-03-26T21:08:19.000Z
Extensions/Gameplay/IndexedHalfEdgeMesh.hpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
null
null
null
Extensions/Gameplay/IndexedHalfEdgeMesh.hpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// /// /// Authors: Joshua Davis /// Copyright 2017, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #pragma once namespace Zero { template <typename ArrayType> class BoundArrayRange; /// Base functionality for binding a pre-existing array. Currently designed as /// a templated base to reduce code duplication, especially while prototyping. Possibly split to /// individual classes (due to differences, code documentation, etc...) or make generic enough to use elsewhere later. template <typename OwningType, typename DataTypeT> class BoundArray : public SafeId32Object { public: typedef BoundArray<OwningType, DataTypeT> SelfType; typedef DataTypeT DataType; typedef Array<DataTypeT> ArrayType; typedef BoundArrayRange<SelfType> RangeType; BoundArray() { mBoundArray = nullptr; } BoundArray(ArrayType* arrayData) { mBoundArray = arrayData; } Vec3Param operator[](size_t index) const { return (*mBoundArray)[index]; } DataTypeT Get(int arrayIndex) const { if(!ValidateArrayIndex(arrayIndex)) return DataTypeT(); return (*mBoundArray)[arrayIndex]; } int GetCount() const { return (int)(*mBoundArray).Size(); } RangeType GetAll() { return RangeType(this); } bool ValidateArrayIndex(int arrayIndex) const { int count = GetCount(); if(arrayIndex >= count) { String msg = String::Format("Index %d is invalid. Array only contains %d element(s).", arrayIndex, count); DoNotifyException("Invalid index", msg); return false; } return true; } /// The array that this class represents. Assumes that this data cannot go away without this class also going away. ArrayType* mBoundArray; }; template <typename ArrayTypeT> class BoundArrayRange { public: typedef BoundArrayRange<ArrayTypeT> SelfType; typedef ArrayTypeT ArrayType; // Required for binding typedef typename ArrayTypeT::DataType FrontResult; BoundArrayRange() { mArray = nullptr; mIndex = 0; } BoundArrayRange(ArrayTypeT* array) { mArray = array; mIndex = 0; } bool Empty() { // Validate that the range hasn't been destroyed ArrayType* array = mArray; if(array == nullptr) { DoNotifyException("Range is invalid", "The array this range is referencing has been destroyed."); return true; } return mIndex >= (size_t)array->GetCount(); } FrontResult Front() { // If the range is empty (or the range has been destroyed) then throw an exception. if(Empty()) { DoNotifyException("Invalid Range Operation", "Cannot access an item in an empty range."); return FrontResult(); } return mArray->Get(mIndex); } void PopFront() { ++mIndex; } SelfType& All() { return *this; } private: HandleOf<ArrayTypeT> mArray; size_t mIndex; }; class IndexedHalfEdgeVertex; class IndexedHalfEdge; class IndexedHalfEdgeFace; class IndexedHalfEdgeMesh; //-------------------------------------------------------------------IndexedHalfEdgeMeshVertexArray class IndexedHalfEdgeMeshVertexArray : public BoundArray<IndexedHalfEdgeMesh, Vec3> { public: ZilchDeclareType(IndexedHalfEdgeMeshVertexArray, TypeCopyMode::ReferenceType); }; //-------------------------------------------------------------------IndexedHalfEdgeMeshEdgeArray class IndexedHalfEdgeMeshEdgeArray : public BoundArray<IndexedHalfEdgeMesh, IndexedHalfEdge*> { public: ZilchDeclareType(IndexedHalfEdgeMeshEdgeArray, TypeCopyMode::ReferenceType); }; //-------------------------------------------------------------------IndexedHalfEdgeFaceEdgeIndexArray class IndexedHalfEdgeFaceEdgeIndexArray : public BoundArray<IndexedHalfEdgeFace, int> { public: ZilchDeclareType(IndexedHalfEdgeFaceEdgeIndexArray, TypeCopyMode::ReferenceType); }; //-------------------------------------------------------------------IndexedHalfEdgeMeshFaceArray class IndexedHalfEdgeMeshFaceArray : public BoundArray<IndexedHalfEdgeMesh, IndexedHalfEdgeFace*> { public: ZilchDeclareType(IndexedHalfEdgeMeshFaceArray, TypeCopyMode::ReferenceType); }; //-------------------------------------------------------------------IndexedHalfEdge class IndexedHalfEdge : public SafeId32Object { public: ZilchDeclareType(IndexedHalfEdge, TypeCopyMode::ReferenceType); /// Index of the tail vertex in the vertex list. int mVertexIndex; /// Index of the twin edge (edge on adjacent face). int mTwinIndex; /// Index of the face that owns this edge. int mFaceIndex; }; //-------------------------------------------------------------------IndexedHalfEdgeFace class IndexedHalfEdgeFace : public SafeId32Object { public: ZilchDeclareType(IndexedHalfEdgeFace, TypeCopyMode::ReferenceType); typedef Array<int> EdgeArray; typedef IndexedHalfEdgeFaceEdgeIndexArray BoundEdgeArray; IndexedHalfEdgeFace(); /// The list of half-edges owned by this face. BoundEdgeArray* GetEdges(); /// The actual edge array of indices. EdgeArray mEdges; /// The bound array of edges. This allows safe referencing in script. BoundEdgeArray mBoundEdges; }; //-------------------------------------------------------------------IndexedHalfEdgeMesh /// An index based half-edge mesh. This is an edge-centric mesh representation that allows /// efficient traversal from edges to anywhere else. Each edge is broken up into two /// half-edges, one for each face it's a part of. Most sub-shapes contain indices back into /// the 'global' list (e.g. an edge contains the index of the vertex in the mesh's vertex list). /// This mesh format is meant for efficient traversal, but manipulation is not as easy with indices. /// This should be loaded into a more efficient format (such as pointers) if manipulating a mesh. class IndexedHalfEdgeMesh : public ReferenceCountedObject { public: ZilchDeclareType(IndexedHalfEdgeMesh, TypeCopyMode::ReferenceType); typedef Array<Vec3> VertexArray; typedef Array<IndexedHalfEdge*> EdgeArray; typedef Array<IndexedHalfEdgeFace*> FaceArray; typedef IndexedHalfEdgeMeshVertexArray BoundVertexArray; typedef IndexedHalfEdgeMeshEdgeArray BoundEdgeArray; typedef IndexedHalfEdgeMeshFaceArray BoundFaceArray; IndexedHalfEdgeMesh(); /// Create the buffers to store the provided mesh size. void Create(int vertexCount, int edgeCount, int faceCount); /// Clear all mesh data. void Clear(); /// The list of vertices in this mesh. BoundVertexArray* GetVertices(); /// The list of edge in this mesh. BoundEdgeArray* GetEdges(); /// The list of faces in this mesh. BoundFaceArray* GetFaces(); // The internal data that's efficient to work with at run-time VertexArray mVertices; EdgeArray mEdges; FaceArray mFaces; // The proxy arrays for binding. This allows safe referencing of the underlying primitives. BoundVertexArray mBoundVertices; BoundEdgeArray mBoundEdges; BoundFaceArray mBoundFaces; }; }// namespace Zero
29.704453
119
0.654355
deeff73bf44115b9aa19e662852a661458027b77
221
cpp
C++
C++/170923/170923/Item_4_Heal.cpp
ChoiChangYong/Game_Programing
6c290e31eaac526b0dbdfc59731e6479126e95bc
[ "MIT" ]
null
null
null
C++/170923/170923/Item_4_Heal.cpp
ChoiChangYong/Game_Programing
6c290e31eaac526b0dbdfc59731e6479126e95bc
[ "MIT" ]
null
null
null
C++/170923/170923/Item_4_Heal.cpp
ChoiChangYong/Game_Programing
6c290e31eaac526b0dbdfc59731e6479126e95bc
[ "MIT" ]
1
2020-04-27T12:41:20.000Z
2020-04-27T12:41:20.000Z
#include "Item_4_Heal.h" #include "Game.h" #include <iostream> using namespace std; void Item_4_Heal::onCheck(Game* pGame) { pGame->Use_Item_4_Heal(); } Item_4_Heal::Item_4_Heal() { } Item_4_Heal::~Item_4_Heal() { }
11.631579
38
0.714932
def119c406c8eaa5a601880b39120d51f9266eec
2,917
cpp
C++
bitsafe/window_effective.cpp
codereba/bittrace
6826559565aaafc9412d20427d21b73e23febcfe
[ "Unlicense" ]
10
2018-11-09T01:08:15.000Z
2020-06-21T05:39:54.000Z
bitsafe/window_effective.cpp
codereba/bittrace
6826559565aaafc9412d20427d21b73e23febcfe
[ "Unlicense" ]
null
null
null
bitsafe/window_effective.cpp
codereba/bittrace
6826559565aaafc9412d20427d21b73e23febcfe
[ "Unlicense" ]
4
2018-11-09T03:29:52.000Z
2021-07-23T03:30:03.000Z
/* * * Copyright 2010 JiJie Shi(weixin:AIChangeLife) * * This file is part of bittrace. * * bittrace is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * bittrace 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 bittrace. If not, see <http://www.gnu.org/licenses/>. * */ #include "stdafx.h" #include "window_effective.h" #define SHORT_WINDOW_DELAY 1 #define SHORT_WINDOW_STEP_SIZE 5 LRESULT short_window_close( CPaintManagerUI *pm, HWND wnd, ULONG delay, ULONG step ) { LRESULT ret = ERROR_SUCCESS; BOOL _ret; RECT rect; ULONG height; INT32 i; RECT cur_rect; RECT paint_rc; SIZE old_min_info; do { ASSERT( wnd != NULL ); ASSERT( pm != NULL ); if( step == 0 ) { step = SHORT_WINDOW_STEP_SIZE; } if( delay == 0 ) { delay = SHORT_WINDOW_DELAY; } if( FALSE == ::IsWindow( wnd ) ) { ASSERT( FALSE && "input the invalid window to show effective" ); break; } _ret = GetWindowRect( wnd, &rect ); if( FALSE == _ret ) { SAFE_SET_ERROR_CODE( ret ); break; } height = _abs( rect.bottom - rect.top ); cur_rect = rect; old_min_info = pm->GetMinInfo(); pm->SetMinInfo( 0, 0 ); for( i = 0; ( ULONG )i < height / 2; i += step ) { cur_rect.bottom = rect.bottom - i; cur_rect.top = rect.top + i; paint_rc = cur_rect; _ret = SetWindowPos( wnd, NULL, cur_rect.left, cur_rect.top, RECT_WIDTH( cur_rect ), RECT_HEIGHT( cur_rect ), SWP_SHOWWINDOW | SWP_NOREDRAW ); if( _ret == FALSE ) {} { pm->PaintStretchShortEffective( wnd, paint_rc ); } Sleep( delay ); } SetWindowPos( wnd, NULL, cur_rect.left, cur_rect.top, RECT_WIDTH( rect ), RECT_HEIGHT( rect ), SWP_HIDEWINDOW ); pm->SetMinInfo( old_min_info.cx, old_min_info.cy ); } while ( FALSE ); return ret; } #define DEF_TRANSPARENT_ANIMATE_TIME 5000 LRESULT transparent_animate( HWND wnd, ULONG time ) { LRESULT ret = ERROR_SUCCESS; BOOL _ret; ASSERT( wnd != NULL ); if( FALSE == IsWindow( wnd ) ) { ret = ERROR_INVALID_PARAMETER; goto _return; } if( time == 0 ) { time = DEF_TRANSPARENT_ANIMATE_TIME; } #if(WINVER >= 0x0500) _ret = AnimateWindow( wnd, time, AW_ACTIVATE | AW_CENTER | AW_BLEND ); if( _ret == FALSE ) { ret = GetLastError(); } #endif // WINVER >= 0x0500 _return: return ret; }
21.768657
147
0.629071
def25db62073c18ceca30494b8ac3956e4a26189
1,169
cpp
C++
Old Code/SM64FM/src/main.cpp
sonich2401/SM64_Save_File_Converter
bd6876d66cbc3177b634540c7a2241e0ae8c759c
[ "MIT-0" ]
6
2020-07-27T19:07:37.000Z
2021-08-29T19:16:07.000Z
Old Code/SM64FM/src/main.cpp
sonich2401/SM64_Save_File_Converter
bd6876d66cbc3177b634540c7a2241e0ae8c759c
[ "MIT-0" ]
2
2021-06-09T05:49:41.000Z
2022-01-30T04:06:40.000Z
Old Code/SM64FM/src/main.cpp
sonich2401/SM64_Save_File_Converter
bd6876d66cbc3177b634540c7a2241e0ae8c759c
[ "MIT-0" ]
null
null
null
#include <stdlib.h> #include <stdio.h> #include <typedefs.h> #include "menu/option_decode.h" #include "util/load_file/load_bin.h" #include "EEPROM/EEPROM.h" #include "menu/menu_choice.h" #include "util/os/linux/escape_codes.h" void exit_program(option_struct * options); int main(int argc, cstring argv[]){ option_struct * options = option_decode(argc, argv); EEPROM_Storage::get().orginal = (EEPROM*)malloc(sizeof(EEPROM)); if(options->in_path == NULL) return 0; unsigned char * infile = load_bin(options->in_path); *EEPROM_Storage::get().orginal = init_EEPROM(infile); EEPROM_Storage::get().edited = (EEPROM*)memcpy(EEPROM_Storage::get().edited, EEPROM_Storage::get().orginal, 512); free(infile); menu_ask((directory*)&root, NULL); exit_program(options); return 0; } void exit_program(option_struct * options){ for(uint8 backup = 0; backup < 2; backup++){ for(uint8 sav = 0; sav < 4; sav++){ set_checksum(&eeprom->game_saves[sav][backup], 0); } set_checksum(&eeprom->menu_saves[backup], 1); } write_bin(options->out_path,(unsigned char*)eeprom, 512); }
25.977778
117
0.663815
def94d20ef029a33c8313959adb0651a463e3480
4,645
cpp
C++
Desktop/FOSSA-GroundStationControlPanel/FOSSASatTracker/SGP4_experiments/main.cpp
FOSSASystems/FOSSA-GroundStationControlPanel
af83a09619239abe9fca09e073ab41c68bfd4822
[ "MIT" ]
2
2021-11-07T16:26:46.000Z
2022-03-20T10:14:41.000Z
Desktop/FOSSA-GroundStationControlPanel/FOSSASatTracker/SGP4_experiments/main.cpp
FOSSASystems/FOSSA-GroundStationControlPanel
af83a09619239abe9fca09e073ab41c68bfd4822
[ "MIT" ]
18
2020-08-28T13:38:36.000Z
2020-09-30T11:08:42.000Z
Desktop/FOSSA-GroundStationControlPanel/FOSSASatTracker/SGP4_experiments/main.cpp
FOSSASystems/FOSSA-GroundStationControlPanel
af83a09619239abe9fca09e073ab41c68bfd4822
[ "MIT" ]
2
2020-07-29T21:19:28.000Z
2021-08-16T03:58:14.000Z
#include "sgp4io.h" #include "sgp4unit.h" #include <GeographicLib/Geocentric.hpp> #include <iostream> int main() { /* INPUT is e.g. 2019 12 6 1 1 1 2020 12 6 1 1 1 */ char fossasatTLELineA[70] = "1 44829U 19084F 20183.10006475 .00039774 00000-0 23016-3 0 9991"; char fossasatTLELineB[70] = "2 44829 96.9730 52.2137 0026683 179.4781 180.6520 15.77974288 32594"; std::cout << "Running! (" << SGP4Version << ")" << std::endl; std::cout << "TLE: " << std::endl; std::cout << fossasatTLELineA << std::endl; std::cout << fossasatTLELineB << std::endl; std::cout << std::endl; // AIAA-2006-6753-Rev2.pdf (page 50 of 94) // Parse the TLE data into the elsetrec structure. elsetrec satrec; char typerun = 'm'; char opsmode = 'i'; char typeinput = 'e'; gravconsttype gravconst = wgs84; double startmfe; double stopmfe; double deltamin; /// @warning stripping const qualifier. // This method also invokes "Day2DMYHMS", "JDAY", "SGP4Init". /* * author : david vallado 719-573-2600 1 mar 2001 * * inputs : * longstr1 - first line of the tle * longstr2 - second line of the tle * typerun - type of run verification 'v', catalog 'c', * manual 'm' * typeinput - type of manual input mfe 'm', epoch 'e', dayofyr 'd' * opsmode - mode of operation afspc or improved 'a', 'i' * whichconst - which set of constants to use 72, 84 * * outputs : * satrec - structure containing all the sgp4 satellite information */ twoline2rv((char*)fossasatTLELineA, (char*)fossasatTLELineB, typerun, typeinput, opsmode, gravconst, startmfe, stopmfe, deltamin, satrec); // Call the propogater (integrator?) at T=0 double positionVector[3]; // km double velocityVector[3]; // km/s /* * * author : david vallado 719-573-2600 28 jun 2005 * * inputs : * satrec - initialised structure from sgp4init() call. * tsince - time eince epoch (minutes) * * outputs : * r - position vector km * v - velocity km/sec * return code - non-zero on error. * 1 - mean elements, ecc >= 1.0 or ecc < -0.001 or a < 0.95 er * 2 - mean motion less than 0.0 * 3 - pert elements, ecc < 0.0 or ecc > 1.0 * 4 - semi-latus rectum < 0.0 * 5 - epoch elements are sub-orbital * 6 - satellite has decayed */ // call the propogator once to get the initial state vector value. sgp4(gravconst, satrec, 0.0, positionVector, velocityVector); double tsince = startmfe; const GeographicLib::Geocentric& ellipsoid = GeographicLib::Geocentric::WGS84(); if (fabs(tsince) > 1.8e-8) { tsince = tsince - deltamin; } while ((tsince < stopmfe) && (satrec.error == 0)) { tsince = tsince + deltamin; if (tsince > stopmfe) { tsince = stopmfe; } sgp4(gravconst, satrec, tsince, positionVector, velocityVector); if (satrec.error > 0) { std::cout << "Make sure the input is in the form\r\n2020\r\n\12\r\n\6\r\n\1\r\n1\r\n\1" << std::endl; printf("Error %f code %3d\r\n", satrec.t, satrec.error); } if (satrec.error == 0) { // convert the position vector from Geocentric to Geodetic. double lat, lon, h; ellipsoid.Reverse(positionVector[0], positionVector[1], positionVector[2], lat, lon, h); // get the current datetime. double jd = satrec.jdsatepoch + (tsince / 1440.0); int year, mon, day, hr, min; double sec; invjday(jd, year, mon, day, hr, min, sec); // print the information %5i%3i%3i %2i:%2i:%9.6f std::cout << year << ":" << mon << ":" << day << " " << hr << ":" << min << ":" << sec << std::endl; std::cout << std::endl; std::cout << "Position Vector (km): " << std::endl; std::cout << "(" << positionVector[0] << "," << positionVector[1] << "," << positionVector[2] << ")" << std::endl; std::cout << std::endl; std::cout << "Position Vector (Lat/Long): " << std::endl; std::cout << "(" << lat << ", " << lon << ", " << h << ")" << std::endl; std::cout << std::endl; std::cout << "Velocity Vector (km/s): " << std::endl; std::cout << "(" << velocityVector[0] << "," << velocityVector[1] << "," << velocityVector[2] << ")" << std::endl; std::cout << std::endl; } } std::cout << "Finished. Press any key to continue." << std::endl; int v; std::cin >> v; return 0; }
27.323529
117
0.56254
defaa02a4762d4b70cc4f0fb2249bf63a7fccfca
757
cpp
C++
alpaca/portfolio.cpp
aidanjalili/alpaca-trade-api-cpp
0914de8ba46cea4c289ef362539d77b2bee74807
[ "MIT" ]
43
2020-04-07T03:28:22.000Z
2022-03-30T21:34:16.000Z
alpaca/portfolio.cpp
aidanjalili/alpaca-trade-api-cpp
0914de8ba46cea4c289ef362539d77b2bee74807
[ "MIT" ]
5
2020-04-29T03:45:36.000Z
2021-03-31T00:59:43.000Z
alpaca/portfolio.cpp
aidanjalili/alpaca-trade-api-cpp
0914de8ba46cea4c289ef362539d77b2bee74807
[ "MIT" ]
18
2020-04-27T18:35:18.000Z
2022-02-05T17:13:38.000Z
#include "alpaca/portfolio.h" #include "alpaca/json.h" #include "rapidjson/document.h" namespace alpaca { Status PortfolioHistory::fromJSON(const std::string& json) { rapidjson::Document d; if (d.Parse(json.c_str()).HasParseError()) { return Status(1, "Received parse error when deserializing portfolio JSON"); } if (!d.IsObject()) { return Status(1, "Deserialized valid JSON but it wasn't a portfolio object"); } PARSE_DOUBLE(base_value, "base_value") PARSE_VECTOR_DOUBLES(equity, "equity") PARSE_VECTOR_DOUBLES(profit_loss, "profit_loss") PARSE_VECTOR_DOUBLES(profit_loss_pct, "profit_loss_pct") PARSE_STRING(timeframe, "timeframe") PARSE_VECTOR_UINT64(timestamp, "timestamp") return Status(); } } // namespace alpaca
28.037037
81
0.738441
defb2c5f63928f233ffce6f66bbca5071e7175b0
395
cc
C++
C++/algorithms/iterative_bsearch.cc
Pejo-306/mystdlib
89d94bfb2fb590775f6d6f689eea6dbf89afd849
[ "MIT" ]
null
null
null
C++/algorithms/iterative_bsearch.cc
Pejo-306/mystdlib
89d94bfb2fb590775f6d6f689eea6dbf89afd849
[ "MIT" ]
null
null
null
C++/algorithms/iterative_bsearch.cc
Pejo-306/mystdlib
89d94bfb2fb590775f6d6f689eea6dbf89afd849
[ "MIT" ]
null
null
null
using namespace std; int bsearch(int *arr, int size, int value) { int left = 0, right = size - 1, middle; while (left <= right) { middle = (left + right) / 2; if (arr[middle] == value) return middle; else if (arr[middle] < value) left = middle + 1; else right = middle - 1; } return -1; // value not found }
21.944444
43
0.498734
deff9e0ef99374df542a6693b5dcc62e077471c5
6,456
cpp
C++
src/IB/IBLagrangianForceStrategySet.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
2
2017-12-06T06:16:36.000Z
2021-03-13T12:28:08.000Z
src/IB/IBLagrangianForceStrategySet.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
null
null
null
src/IB/IBLagrangianForceStrategySet.cpp
MSV-Project/IBAMR
3cf614c31bb3c94e2620f165ba967cba719c45ea
[ "BSD-3-Clause" ]
null
null
null
// Filename: IBLagrangianForceStrategySet.cpp // Created on 04 April 2007 by Boyce Griffith // // Copyright (c) 2002-2013, Boyce Griffith // 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 New York University 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. /////////////////////////////// INCLUDES ///////////////////////////////////// #include "IBLagrangianForceStrategySet.h" #include "PatchHierarchy.h" #include "ibamr/namespaces.h" // IWYU pragma: keep #include "ibtk/IBTK_CHKERRQ.h" #include "ibtk/LData.h" namespace IBTK { class LDataManager; } // namespace IBTK /////////////////////////////// NAMESPACE //////////////////////////////////// namespace IBAMR { /////////////////////////////// STATIC /////////////////////////////////////// /////////////////////////////// PUBLIC /////////////////////////////////////// IBLagrangianForceStrategySet::~IBLagrangianForceStrategySet() { // intentionally blank return; }// ~IBLagrangianForceStrategySet void IBLagrangianForceStrategySet::setTimeInterval( const double current_time, const double new_time) { for (std::vector<Pointer<IBLagrangianForceStrategy> >::const_iterator cit = d_strategy_set.begin(); cit != d_strategy_set.end(); ++cit) { (*cit)->setTimeInterval(current_time, new_time); } return; }// setTimeInterval void IBLagrangianForceStrategySet::initializeLevelData( const Pointer<PatchHierarchy<NDIM> > hierarchy, const int level_number, const double init_data_time, const bool initial_time, LDataManager* const l_data_manager) { for (std::vector<Pointer<IBLagrangianForceStrategy> >::const_iterator cit = d_strategy_set.begin(); cit != d_strategy_set.end(); ++cit) { (*cit)->initializeLevelData( hierarchy, level_number, init_data_time, initial_time, l_data_manager); } return; }// initializeLevelData void IBLagrangianForceStrategySet::computeLagrangianForce( Pointer<LData> F_data, Pointer<LData> X_data, Pointer<LData> U_data, const Pointer<PatchHierarchy<NDIM> > hierarchy, const int level_number, const double data_time, LDataManager* const l_data_manager) { for (std::vector<Pointer<IBLagrangianForceStrategy> >::const_iterator cit = d_strategy_set.begin(); cit != d_strategy_set.end(); ++cit) { (*cit)->computeLagrangianForce( F_data, X_data, U_data, hierarchy, level_number, data_time, l_data_manager); } return; }// computeLagrangianForce void IBLagrangianForceStrategySet::computeLagrangianForceJacobianNonzeroStructure( std::vector<int>& d_nnz, std::vector<int>& o_nnz, const Pointer<PatchHierarchy<NDIM> > hierarchy, const int level_number, LDataManager* const l_data_manager) { for (std::vector<Pointer<IBLagrangianForceStrategy> >::const_iterator cit = d_strategy_set.begin(); cit != d_strategy_set.end(); ++cit) { (*cit)->computeLagrangianForceJacobianNonzeroStructure( d_nnz, o_nnz, hierarchy, level_number, l_data_manager); } return; }// computeLagrangianForceJacobianNonzeroStructure void IBLagrangianForceStrategySet::computeLagrangianForceJacobian( Mat& J_mat, MatAssemblyType assembly_type, const double X_coef, Pointer<LData> X_data, const double U_coef, Pointer<LData> U_data, const Pointer<PatchHierarchy<NDIM> > hierarchy, const int level_number, const double data_time, LDataManager* const l_data_manager) { for (std::vector<Pointer<IBLagrangianForceStrategy> >::const_iterator cit = d_strategy_set.begin(); cit != d_strategy_set.end(); ++cit) { (*cit)->computeLagrangianForceJacobian( J_mat, MAT_FLUSH_ASSEMBLY, X_coef, X_data, U_coef, U_data, hierarchy, level_number, data_time, l_data_manager); } if (assembly_type != MAT_FLUSH_ASSEMBLY) { int ierr; ierr = MatAssemblyBegin(J_mat, assembly_type); IBTK_CHKERRQ(ierr); ierr = MatAssemblyEnd(J_mat, assembly_type); IBTK_CHKERRQ(ierr); } return; }// computeLagrangianForceJacobian double IBLagrangianForceStrategySet::computeLagrangianEnergy( Pointer<LData> X_data, Pointer<LData> U_data, const Pointer<PatchHierarchy<NDIM> > hierarchy, const int level_number, const double data_time, LDataManager* const l_data_manager) { double ret_val = 0.0; for (std::vector<Pointer<IBLagrangianForceStrategy> >::const_iterator cit = d_strategy_set.begin(); cit != d_strategy_set.end(); ++cit) { ret_val += (*cit)->computeLagrangianEnergy(X_data, U_data, hierarchy, level_number, data_time, l_data_manager); } return ret_val; }// computeLagrangianEnergy /////////////////////////////// PROTECTED //////////////////////////////////// /////////////////////////////// PRIVATE ////////////////////////////////////// /////////////////////////////// NAMESPACE //////////////////////////////////// } // namespace IBAMR //////////////////////////////////////////////////////////////////////////////
37.103448
139
0.670074
72007729164461efc492cbee49cf51da6b5c9677
2,935
cpp
C++
example/sql/test_multithread.cpp
zizzzw/fflib
ba9b465347b650d86c34876fbfae48bc31194d97
[ "MIT" ]
1
2022-02-08T07:28:07.000Z
2022-02-08T07:28:07.000Z
example/sql/test_multithread.cpp
zizzzw/fflib
ba9b465347b650d86c34876fbfae48bc31194d97
[ "MIT" ]
null
null
null
example/sql/test_multithread.cpp
zizzzw/fflib
ba9b465347b650d86c34876fbfae48bc31194d97
[ "MIT" ]
2
2022-01-06T02:16:09.000Z
2022-01-19T12:49:54.000Z
/*********************************************** The MIT License (MIT) Copyright (c) 2012 Athrun Arthur <athrunarthur@gmail.com> 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 "ff/sql/mysql.hpp" #include "ff/sql/table.h" #include <thread> struct mymeta { constexpr static const char *table_name = "yyy"; }; define_column(c1, column, uint64_t, "id"); define_column(c2, key, std::string, "event"); define_column(c3, index, uint64_t, "ts"); typedef ff::sql::table<ff::sql::mysql<ff::sql::cppconn>, mymeta, c1, c2, c3> mytable; int main(int argc, char *argv[]) { ff::sql::mysql<ff::sql::cppconn> engine("tcp://127.0.0.1:3306", "root", "", "test"); mytable::create_table(&engine); mytable::row_collection_type rows; mytable::row_collection_type::row_type t1, t2; t1.set<c1, c2, c3>(1, "c1", 123435); rows.push_back(std::move(t1)); t2.set<c1, c2, c3>(2, "c2", 1235); rows.push_back(std::move(t2)); mytable::insert_or_replace_rows(&engine, rows); std::thread thrd([&engine]() { auto local_engine = engine.thread_copy(); auto ret2 = mytable::select<c1, c2, c3>(local_engine.get()) // auto ret2 = mytable::select<c1, c2, c3>(&engine) .where(c1::eq(2)) .order_by<c1, ff::sql::desc>() .limit(1) .eval(); std::cout << ret2.size() << std::endl; std::cout << ret2[0].get<c1>() << ", " << ret2[0].get<c2>() << ", " << ret2[0].get<c3>() << std::endl; }); auto ret1 = mytable::select<c1, c2, c3>(&engine).eval(); std::cout << "size: " << ret1.size() << std::endl; for (size_t i = 0; i < ret1.size(); ++i) { std::cout << ret1[i].get<c1>() << ", " << ret1[i].get<c2>() << ", " << ret1[i].get<c3>() << std::endl; } thrd.join(); return 0; }
37.151899
79
0.612947
7200cb8c29aa54b386846e16aac4f09b5848effa
9,142
cpp
C++
Code/Core/CoreTest/Tests/TestSmallBlockAllocator.cpp
qq573011406/FASTBuild_UnrealEngine
29c49672f82173a903cb32f0e4656e2fd07ebef2
[ "MIT" ]
30
2020-07-15T06:16:55.000Z
2022-02-10T21:37:52.000Z
Code/Core/CoreTest/Tests/TestSmallBlockAllocator.cpp
qq573011406/FASTBuild_UnrealEngine
29c49672f82173a903cb32f0e4656e2fd07ebef2
[ "MIT" ]
1
2020-11-23T13:35:00.000Z
2020-11-23T13:35:00.000Z
Code/Core/CoreTest/Tests/TestSmallBlockAllocator.cpp
qq573011406/FASTBuild_UnrealEngine
29c49672f82173a903cb32f0e4656e2fd07ebef2
[ "MIT" ]
12
2020-09-16T17:39:34.000Z
2021-08-17T11:32:37.000Z
// TestSmallBlockAllocator.cpp //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include "TestFramework/UnitTest.h" #include "Core/Containers/Array.h" #include "Core/Math/Random.h" #include "Core/Mem/Mem.h" #include "Core/Mem/SmallBlockAllocator.h" #include "Core/Process/Thread.h" #include "Core/Time/Timer.h" #include "Core/Tracing/Tracing.h" // System #include <stdlib.h> // TestSmallBlockAllocator //------------------------------------------------------------------------------ class TestSmallBlockAllocator : public UnitTest { private: DECLARE_TESTS void SingleThreaded() const; void MultiThreaded() const; // struct for managing threads class ThreadInfo { public: Thread::ThreadHandle m_ThreadHandle = INVALID_THREAD_HANDLE; Array< uint32_t > * m_AllocationSizes = nullptr; uint32_t m_RepeatCount = 0; float m_TimeTaken = 0.0f; }; // Helper functions static void GetRandomAllocSizes( const uint32_t numAllocs, Array< uint32_t> & allocSizes ); static float AllocateFromSystemAllocator( const Array< uint32_t > & allocSizes, const uint32_t repeatCount ); static float AllocateFromSmallBlockAllocator( const Array< uint32_t > & allocSizes, const uint32_t repeatCount, const bool threadSafe = true ); static uint32_t ThreadFunction_System( void * userData ); static uint32_t ThreadFunction_SmallBlock( void * userData ); }; // Register Tests //------------------------------------------------------------------------------ REGISTER_TESTS_BEGIN( TestSmallBlockAllocator ) REGISTER_TEST( SingleThreaded ) REGISTER_TEST( MultiThreaded ) REGISTER_TESTS_END // SingleThreaded //------------------------------------------------------------------------------ void TestSmallBlockAllocator::SingleThreaded() const { #if defined( DEBUG ) const uint32_t numAllocs( 10 * 1000 ); #else const uint32_t numAllocs( 100 * 1000 ); #endif const uint32_t repeatCount( 10 ); Array< uint32_t > allocSizes( 0, true ); GetRandomAllocSizes( numAllocs, allocSizes ); float time1 = AllocateFromSystemAllocator( allocSizes, repeatCount ); float time2 = AllocateFromSmallBlockAllocator( allocSizes, repeatCount ); float time3 = AllocateFromSmallBlockAllocator( allocSizes, repeatCount, false ); // Thread-safe = false // output OUTPUT( "System (malloc) : %2.3fs - %u allocs @ %u allocs/sec\n", (double)time1, ( numAllocs * repeatCount ), (uint32_t)( float( numAllocs * repeatCount ) / time1 ) ); OUTPUT( "SmallBlockAllocator : %2.3fs - %u allocs @ %u allocs/sec\n", (double)time2, ( numAllocs * repeatCount ), (uint32_t)( float( numAllocs * repeatCount ) / time2 ) ); OUTPUT( "SmallBlockAllocator (Single-Threaded mode) : %2.3fs - %u allocs @ %u allocs/sec\n", (double)time3, ( numAllocs * repeatCount ), (uint32_t)( float( numAllocs * repeatCount ) / time3 ) ); } // MultiThreaded //------------------------------------------------------------------------------ void TestSmallBlockAllocator::MultiThreaded() const { #if defined( DEBUG ) const uint32_t numAllocs( 10 * 1000 ); #else const uint32_t numAllocs( 100 * 1000 ); #endif const uint32_t repeatCount( 10 ); Array< uint32_t > allocSizes( 0, true ); GetRandomAllocSizes( numAllocs, allocSizes ); float time1( 0.0f ); float time2( 0.0f ); const size_t numThreads = 4; // System Allocator { // Create some threads ThreadInfo info[ numThreads ]; for ( size_t i = 0; i < numThreads; ++i ) { info[ i ].m_AllocationSizes = & allocSizes; info[ i ].m_RepeatCount = repeatCount; info[ i ].m_ThreadHandle = Thread::CreateThread( ThreadFunction_System, "SmallBlock", ( 64 * KILOBYTE ), (void*)&info[ i ] ); TEST_ASSERT( info[ i ].m_ThreadHandle != INVALID_THREAD_HANDLE ); } // Join the threads for ( size_t i = 0; i < numThreads; ++i ) { bool timedOut; Thread::WaitForThread( info[ i ].m_ThreadHandle, 500 * 1000, timedOut ); Thread::CloseHandle( info[ i ].m_ThreadHandle ); TEST_ASSERT( timedOut == false ); time1 += info[ i ].m_TimeTaken; } } // Small Block Allocator { // Create some threads ThreadInfo info[ numThreads ]; for ( size_t i = 0; i < numThreads; ++i ) { info[ i ].m_AllocationSizes = & allocSizes; info[ i ].m_RepeatCount = repeatCount; info[ i ].m_ThreadHandle = Thread::CreateThread( ThreadFunction_SmallBlock, "SmallBlock", ( 64 * KILOBYTE ), (void*)&info[ i ] ); TEST_ASSERT( info[ i ].m_ThreadHandle != INVALID_THREAD_HANDLE ); } // Join the threads for ( size_t i = 0; i < numThreads; ++i ) { bool timedOut; Thread::WaitForThread( info[ i ].m_ThreadHandle, 500 * 1000, timedOut ); Thread::CloseHandle( info[ i ].m_ThreadHandle ); TEST_ASSERT( timedOut == false ); time2 += info[ i ].m_TimeTaken; } time2 /= numThreads; } // output OUTPUT( "System (malloc) : %2.3fs - %u allocs @ %u allocs/sec\n", (double)time1, ( numAllocs * repeatCount ), (uint32_t)( float( numAllocs * repeatCount ) / time1 ) ); OUTPUT( "SmallBlockAllocator : %2.3fs - %u allocs @ %u allocs/sec\n", (double)time2, ( numAllocs * repeatCount ), (uint32_t)( float( numAllocs * repeatCount ) / time2 ) ); } // GetRandomAllocSizes //------------------------------------------------------------------------------ /*static*/ void TestSmallBlockAllocator::GetRandomAllocSizes( const uint32_t numAllocs, Array< uint32_t > & allocSizes ) { const size_t maxSize( 256 ); // max supported size of block allocator allocSizes.SetCapacity( numAllocs ); Random r; r.SetSeed( 0 ); // Deterministic between runs by using a consistent seed for ( size_t i = 0; i < numAllocs; ++i ) { allocSizes.Append( r.GetRandIndex( maxSize ) ); } } // AllocateFromSystemAllocator //------------------------------------------------------------------------------ /*static*/ float TestSmallBlockAllocator::AllocateFromSystemAllocator( const Array< uint32_t > & allocSizes, const uint32_t repeatCount ) { const size_t numAllocs = allocSizes.GetSize(); Array< void * > allocs( numAllocs, false ); Timer timer; for ( size_t r = 0; r < repeatCount; ++r ) { // use malloc for ( uint32_t i = 0; i < numAllocs; ++i ) { uint32_t * mem = (uint32_t *)malloc( allocSizes[ i ] ); allocs.Append( mem ); } // use free for ( uint32_t i = 0; i < numAllocs; ++i ) { void * mem = allocs[ i ]; free( mem ); } allocs.Clear(); } return timer.GetElapsed(); } // AllocateFromSmallBlockAllocator //------------------------------------------------------------------------------ /*static*/ float TestSmallBlockAllocator::AllocateFromSmallBlockAllocator( const Array< uint32_t > & allocSizes, const uint32_t repeatCount, const bool threadSafe ) { const size_t numAllocs = allocSizes.GetSize(); Array< void * > allocs( numAllocs, false ); Timer timer; if ( threadSafe == false ) { SmallBlockAllocator::SetSingleThreadedMode( true ); } for ( size_t r = 0; r < repeatCount; ++r ) { // Use ALLOC for ( uint32_t i = 0; i < numAllocs; ++i ) { uint32_t * mem = (uint32_t *)ALLOC( allocSizes[ i ] ); allocs.Append( mem ); } // Use FREE for ( uint32_t i = 0; i < numAllocs; ++i ) { void * mem = allocs[ i ]; FREE( mem ); } allocs.Clear(); } if ( threadSafe == false ) { SmallBlockAllocator::SetSingleThreadedMode( false ); } return timer.GetElapsed(); } // ThreadFunction_System //------------------------------------------------------------------------------ /*static*/ uint32_t TestSmallBlockAllocator::ThreadFunction_System( void * userData ) { ThreadInfo & info = *( reinterpret_cast< ThreadInfo * >( userData ) ); info.m_TimeTaken = AllocateFromSystemAllocator( *info.m_AllocationSizes, info.m_RepeatCount ); return 0; } // ThreadFunction_SmallBlock //------------------------------------------------------------------------------ /*static*/ uint32_t TestSmallBlockAllocator::ThreadFunction_SmallBlock( void * userData ) { ThreadInfo & info = *( reinterpret_cast< ThreadInfo * >( userData ) ); info.m_TimeTaken = AllocateFromSmallBlockAllocator( *info.m_AllocationSizes, info.m_RepeatCount ); return 0; } //------------------------------------------------------------------------------
35.710938
198
0.556005
72028a958d4a35056f23ad403159ba57ac3b6bbc
1,639
h++
C++
include/wheels/adl/swap.h++
dendisuhubdy/wheels
a49e790dbc277335907b393ebaddea947ae14d0e
[ "CC0-1.0" ]
null
null
null
include/wheels/adl/swap.h++
dendisuhubdy/wheels
a49e790dbc277335907b393ebaddea947ae14d0e
[ "CC0-1.0" ]
null
null
null
include/wheels/adl/swap.h++
dendisuhubdy/wheels
a49e790dbc277335907b393ebaddea947ae14d0e
[ "CC0-1.0" ]
1
2019-11-16T18:30:53.000Z
2019-11-16T18:30:53.000Z
// Wheels - various C++ utilities // // Written in 2013 by Martinho Fernandes <martinho.fernandes@gmail.com> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/> // ADL-enabled swap #ifndef WHEELS_ADL_SWAP_HPP #define WHEELS_ADL_SWAP_HPP #include <utility> // swap, declval namespace wheels { namespace adl { namespace detail { using std::swap; template <typename T, typename U, typename Result = decltype(swap(std::declval<T>(), std::declval<U>())), bool NoExcept = noexcept(swap(std::declval<T>(), std::declval<U>()))> Result adl_swap(T&& t, U&& u) noexcept(NoExcept) { return swap(std::forward<T>(t), std::forward<U>(u)); } } // namespace detail // Calls swap with ADL-lookup include std::swap template <typename T, typename U, typename Result = decltype(detail::adl_swap(std::declval<T>(), std::declval<U>())), bool NoExcept = noexcept(detail::adl_swap(std::declval<T>(), std::declval<U>()))> Result swap(T&& t, U&& u) noexcept(NoExcept) { return detail::adl_swap(std::forward<T>(t), std::forward<U>(u)); } } // namespace adl } // namespace wheels #endif // WHEELS_ADL_SWAP_HPP
38.116279
101
0.626602
72029ac0401188223aa3ccc577020843e1245dd9
3,722
cc
C++
src/connectivity/wlan/drivers/testing/lib/sim-env/sim-env.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
src/connectivity/wlan/drivers/testing/lib/sim-env/sim-env.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
src/connectivity/wlan/drivers/testing/lib/sim-env/sim-env.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia 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 "sim-env.h" #include <zircon/assert.h> namespace wlan::simulation { uint64_t Environment::event_count_ = 0; void Environment::Run() { while (!events_.empty()) { auto event = std::move(events_.front()); events_.pop_front(); // Make sure that time is always moving forward ZX_ASSERT(event->time >= time_); time_ = event->time; // Send event to client who requested it event->requester->ReceiveNotification(event->payload); } } void Environment::TxBeacon(StationIfc* sender, const wlan_channel_t& channel, const wlan_ssid_t& ssid, const common::MacAddr& bssid) { for (auto sta : stations_) { if (sta != sender) { sta->RxBeacon(channel, ssid, bssid); } } } void Environment::TxAssocReq(StationIfc* sender, const wlan_channel_t& channel, const common::MacAddr& src, const common::MacAddr& bssid) { for (auto sta : stations_) { if (sta != sender) { sta->RxAssocReq(channel, src, bssid); } } } void Environment::TxAssocResp(StationIfc* sender, const wlan_channel_t& channel, const common::MacAddr& src, const common::MacAddr& dst, uint16_t status) { for (auto sta : stations_) { if (sta != sender) { sta->RxAssocResp(channel, src, dst, status); } } } void Environment::TxDisassocReq(StationIfc* sender, const wlan_channel_t& channel, const common::MacAddr& src, const common::MacAddr& dst, uint16_t reason) { for (auto sta : stations_) { if (sta != sender) { sta->RxDisassocReq(channel, src, dst, reason); } } } void Environment::TxProbeReq(StationIfc* sender, const wlan_channel_t& channel, const common::MacAddr& src) { for (auto sta : stations_) { if (sta != sender) { sta->RxProbeReq(channel, src); } } } void Environment::TxProbeResp(StationIfc* sender, const wlan_channel_t& channel, const common::MacAddr& src, const common::MacAddr& dst, const wlan_ssid_t& ssid) { for (auto sta : stations_) { if (sta != sender) { sta->RxProbeResp(channel, src, dst, ssid); } } } zx_status_t Environment::ScheduleNotification(StationIfc* sta, zx::duration delay, void* payload, uint64_t* id_out) { uint64_t id = event_count_++; // Disallow past events if (delay < zx::usec(0)) { return ZX_ERR_INVALID_ARGS; } auto event = std::make_unique<EnvironmentEvent>(); event->id = id; event->time = time_ + delay; event->requester = sta; event->payload = payload; // Keep our events sorted in ascending order of absolute time. When multiple events are // scheduled for the same time, the first requested will be processed first. auto event_iter = events_.begin(); while (event_iter != events_.end() && (*event_iter)->time <= event->time) { event_iter++; } events_.insert(event_iter, std::move(event)); if (id_out != nullptr) { *id_out = id; } return ZX_OK; } // Since all events are processed synchronously, we don't have to worry about locking. zx_status_t Environment::CancelNotification(StationIfc* sta, uint64_t id) { for (auto& event_iter : events_) { if (event_iter->requester == sta && event_iter->id == id) { events_.remove(event_iter); return ZX_OK; } } return ZX_ERR_NOT_FOUND; } } // namespace wlan::simulation
29.539683
97
0.622783
7202f264bd57851ca7f5b279dd6700bd6f5d9dd6
556
cc
C++
examples/toy/andor.cc
paulhjkelly/taskgraph-metaprogramming
54c4e2806a97bec555a90784ab4cf0880660bf89
[ "BSD-3-Clause" ]
5
2020-04-11T21:30:19.000Z
2021-12-04T16:16:09.000Z
examples/toy/andor.cc
paulhjkelly/taskgraph-metaprogramming
54c4e2806a97bec555a90784ab4cf0880660bf89
[ "BSD-3-Clause" ]
null
null
null
examples/toy/andor.cc
paulhjkelly/taskgraph-metaprogramming
54c4e2806a97bec555a90784ab4cf0880660bf89
[ "BSD-3-Clause" ]
null
null
null
#include <TaskGraph> using namespace tg; typedef TaskGraph<void,int> andor_TaskGraph; int main( int argc, char *argv[] ) { andor_TaskGraph T; taskgraph( andor_TaskGraph, T, tuple1(a) ) { tVar(int, b); b = ((a < 12) + (a > 42)); b = ((a > 6) - (a < 9)); b = ((a < 12) * (a > 42)); b = ((a > 6) / (a < 9)); b = ((a < 12) & (a > 42)); b = ((a > 6) | (a < 9)); b = ((a < 12) && (a > 42)); b = ((a > 6) || (a < 9)); b = ((a < 12) << (a > 42)); b = ((a > 6) >> (a < 9)); tIf( b > 1 ) { } } T.print(); }
22.24
46
0.393885
7208b1a74f7a044ea3b92c8d2697cdd2dffbc33f
437
hpp
C++
include/imgui.hpp
richard-vock/graphene
1a721894a9972c8865a1ad0861d500cef8436932
[ "Unlicense" ]
null
null
null
include/imgui.hpp
richard-vock/graphene
1a721894a9972c8865a1ad0861d500cef8436932
[ "Unlicense" ]
null
null
null
include/imgui.hpp
richard-vock/graphene
1a721894a9972c8865a1ad0861d500cef8436932
[ "Unlicense" ]
null
null
null
#pragma once #include <string> #include <imgui.h> #include "common.hpp" #include "events.hpp" struct GLFWwindow; namespace graphene::imgui { IMGUI_IMPL_API bool init_application(GLFWwindow* window, const std::string& font_path, float font_size, std::shared_ptr<event_manager> events); IMGUI_IMPL_API void shutdown_application(); IMGUI_IMPL_API void init_frame(); IMGUI_IMPL_API void draw_frame(); } // namespace graphene::imgui
20.809524
143
0.78032
7209c4bdc94f639f48deccad6ab5e8cd5451ec5e
4,139
cpp
C++
libdclalgo/tests/AzimuthEvaluationTests.cpp
OlegZhavoronkov/tnk_certification
9ef3544f3fd27073b78e38bba26af76e79f55a78
[ "Unlicense" ]
null
null
null
libdclalgo/tests/AzimuthEvaluationTests.cpp
OlegZhavoronkov/tnk_certification
9ef3544f3fd27073b78e38bba26af76e79f55a78
[ "Unlicense" ]
null
null
null
libdclalgo/tests/AzimuthEvaluationTests.cpp
OlegZhavoronkov/tnk_certification
9ef3544f3fd27073b78e38bba26af76e79f55a78
[ "Unlicense" ]
null
null
null
#include "AzimuthEvaluation.h" #include "PolarDecomposition.h" #include "LibraryParameters.h" #include <opencv2/core.hpp> #include <gtest/gtest.h> #include <limits> #include <vector> class AzimuthEvaluationTests : public ::testing::Test { public: AzimuthEvaluationTests(); cv::Mat genRandomMat(double min, double max); protected: cv::Mat x; cv::Mat y; cv::Mat atan2XYAnswer; std::vector<double> polarAngles = {0, 45, 90, 135}; std::vector<double> pInverseMatrixData = {0.2500, 0.2500, 0.2500, 0.2500, 0.5000, 0.0000, -0.5000, 0.0000, 0.0000, 0.5000, 0.0000, -0.5000}; cv::Mat pInverseMatrix; std::vector<uint8_t> imageData1 = { 1, 2, 3, 4, 5, 6 }; std::vector<uint8_t> imageData2 = { 11, 12, 13, 14, 15, 16 }; std::vector<uint8_t> combinedImageData = { 1, 2, 3, 4, 5, 6, 11, 12, 13, 14, 15, 16, }; cv::Mat image1; cv::Mat image2; cv::Mat combinedImage; int rows = 2048; int cols = 2448; double reflection = 1.3; std::vector<double> standardAnglesRad = {0, M_PI / 4, M_PI / 2, M_PI * 3 / 4}; }; AzimuthEvaluationTests::AzimuthEvaluationTests() { cv::theRNG().state = time(nullptr); double xData = 1. / sqrt(2.); double yData = 1. / sqrt(2.); double atan2Answer = atan2(yData, xData); int vectorSize = 10000000; x = cv::Mat(1, vectorSize, CV_64FC1, xData); y = cv::Mat(1, vectorSize, CV_64FC1, yData); atan2XYAnswer = cv::Mat(vectorSize, 1, CV_64FC1, atan2Answer); pInverseMatrix = cv::Mat(3, 4, CV_64FC1, pInverseMatrixData.data()); image1 = cv::Mat(2, 3, CV_8UC1, imageData1.data()); image2 = cv::Mat(2, 3, CV_8UC1, imageData2.data()); combinedImage = cv::Mat(2, 6, CV_8UC1, combinedImageData.data()); LibraryParameters::configure(LibraryParameters::PolarizationSensorOrder::order90_45_135_0); } cv::Mat AzimuthEvaluationTests::genRandomMat(double min, double max) { cv::Mat dst(rows, cols, CV_64FC1, 0.); cv::randu(dst, min, max); return dst; } static cv::Mat epsilon(int rows, int cols) { // Epsilon for double values 1e-15, // std::numeric_limits<double>::epsilon() is not good way, // close values don't fit return cv::Mat(rows, cols, CV_64FC1, 1e-15); } TEST_F(AzimuthEvaluationTests, getAtan2Vector) { cv::Mat atanRes = getAtan2Vector(x, y); EXPECT_EQ(cv::countNonZero(atan2XYAnswer != atanRes), 0); } TEST_F(AzimuthEvaluationTests, getAtan2VectorParallel) { cv::Mat atanRes = getAtan2VectorParallel(x, y); EXPECT_EQ(cv::countNonZero(atan2XYAnswer != atanRes), 0); } TEST_F(AzimuthEvaluationTests, getReshapedPolarImagesFast) { cv::Mat p = getReshapedPolarImages_fast({image1, image2}); EXPECT_EQ(cv::countNonZero(combinedImage != p), 0); } TEST_F(AzimuthEvaluationTests, getReshapedPolarImagesFastTemplate) { cv::Mat p = getReshapedPolarImages_fast_template<uint8_t>({image1, image2}); EXPECT_EQ(cv::countNonZero(combinedImage != p), 0); } TEST_F(AzimuthEvaluationTests, computeAzimuth) { cv::Mat x(1, 2, CV_64FC1, 1.3); std::vector<cv::Mat> polarImages = decomposeImages(x, x, x, standardAnglesRad); cv::Mat res(1, 2, CV_64FC1, 0.); computeAzimuth(polarImages, res); EXPECT_EQ(cv::countNonZero(cv::abs(res - x) > epsilon(1, 2)), 0); } TEST_F(AzimuthEvaluationTests, computeAzimuthFast) { cv::Mat x(1, 2, CV_64FC1, 1.3); std::vector<cv::Mat> polarImages = decomposeImages(x, x, x, standardAnglesRad); cv::Mat res(1, 2, CV_64FC1, 0.); computeAzimuth_fast(polarImages, res); EXPECT_EQ(cv::countNonZero(cv::abs(res - x) > epsilon(1, 2)), 0); } TEST_F(AzimuthEvaluationTests, computePolDegree) { cv::Mat x(1, 2, CV_64FC1, 1.0); std::vector<cv::Mat> polarImages = decomposeImages(x, x, x, standardAnglesRad); cv::Mat res(1, 2, CV_64FC1, 0.); computePolDegree(polarImages, res); EXPECT_EQ(cv::countNonZero(cv::abs(res - x) > epsilon(1, 2)), 0); }
30.433824
93
0.636144
7209c78d917330a56ef4ad047da24049bab203e5
7,107
cc
C++
virtual-machine/instructions.cc
AlexGustafsson/mjavac
6efbf8d77ba67760cff5ab87a3e858de769ac33e
[ "Unlicense" ]
null
null
null
virtual-machine/instructions.cc
AlexGustafsson/mjavac
6efbf8d77ba67760cff5ab87a3e858de769ac33e
[ "Unlicense" ]
null
null
null
virtual-machine/instructions.cc
AlexGustafsson/mjavac
6efbf8d77ba67760cff5ab87a3e858de769ac33e
[ "Unlicense" ]
1
2021-08-19T02:56:28.000Z
2021-08-19T02:56:28.000Z
#include <iostream> #include <list> #include <tuple> #include "instructions.hpp" using namespace mjavac::vm; Instruction_iload::Instruction_iload(std::string identifier) : identifier(identifier) { } void Instruction_iload::perform(State *state) const { state->stack.push(state->variables[this->identifier]); state->instruction_pointer++; } void Instruction_iload::write(std::ostream &stream) const { stream << "iload " << this->identifier << std::endl; } Instruction_iconst::Instruction_iconst(long value) : value(value) { } void Instruction_iconst::perform(State *state) const { state->stack.push(this->value); state->instruction_pointer++; } void Instruction_iconst::write(std::ostream &stream) const { stream << "iconst " << this->value << std::endl; } Instruction_istore::Instruction_istore(std::string identifier) : identifier(identifier) { } void Instruction_istore::perform(State *state) const { state->variables[this->identifier] = (int)state->stack.top(); state->stack.pop(); state->instruction_pointer++; } void Instruction_istore::write(std::ostream &stream) const { stream << "istore " << this->identifier << std::endl; } Instruction_iadd::Instruction_iadd() { } void Instruction_iadd::perform(State *state) const { int b = (int)state->stack.top(); state->stack.pop(); int a = (int)state->stack.top(); state->stack.pop(); state->stack.push(a + b); state->instruction_pointer++; } void Instruction_iadd::write(std::ostream &stream) const { stream << "iadd" << std::endl; } Instruction_isub::Instruction_isub() { } void Instruction_isub::perform(State *state) const { int b = (int)state->stack.top(); state->stack.pop(); int a = (int)state->stack.top(); state->stack.pop(); state->stack.push(a - b); state->instruction_pointer++; } void Instruction_isub::write(std::ostream &stream) const { stream << "isub" << std::endl; } Instruction_imul::Instruction_imul() { } void Instruction_imul::perform(State *state) const { int b = (int)state->stack.top(); state->stack.pop(); int a = (int)state->stack.top(); state->stack.pop(); state->stack.push(a * b); state->instruction_pointer++; } void Instruction_imul::write(std::ostream &stream) const { stream << "imul" << std::endl; } Instruction_idiv::Instruction_idiv() { } void Instruction_idiv::perform(State *state) const { int b = (int)state->stack.top(); state->stack.pop(); int a = (int)state->stack.top(); state->stack.pop(); state->stack.push(a / b); state->instruction_pointer++; } void Instruction_idiv::write(std::ostream &stream) const { stream << "idiv" << std::endl; } Instruction_ilt::Instruction_ilt() { } void Instruction_ilt::perform(State *state) const { int b = (int)state->stack.top(); state->stack.pop(); int a = (int)state->stack.top(); state->stack.pop(); state->stack.push(a < b ? 1 : 0); state->instruction_pointer++; } void Instruction_ilt::write(std::ostream &stream) const { stream << "ilt" << std::endl; } Instruction_iand::Instruction_iand() { } void Instruction_iand::perform(State *state) const { int b = (int)state->stack.top(); state->stack.pop(); int a = (int)state->stack.top(); state->stack.pop(); state->stack.push(a * b == 0 ? 0 : 1); state->instruction_pointer++; } void Instruction_iand::write(std::ostream &stream) const { stream << "iand" << std::endl; } Instruction_ior::Instruction_ior() { } void Instruction_ior::perform(State *state) const { int b = (int)state->stack.top(); state->stack.pop(); int a = (int)state->stack.top(); state->stack.pop(); state->stack.push(a + b == 0 ? 0 : 1); state->instruction_pointer++; } void Instruction_ior::write(std::ostream &stream) const { stream << "ior" << std::endl; } Instruction_inot::Instruction_inot() { } void Instruction_inot::perform(State *state) const { int a = (int)state->stack.top(); state->stack.pop(); state->stack.push(a == 0 ? 1 : 0); state->instruction_pointer++; } void Instruction_inot::write(std::ostream &stream) const { stream << "inot" << std::endl; } Instruction_goto::Instruction_goto(long target) : target(target) { } void Instruction_goto::perform(State *state) const { state->current_block = std::to_string(this->target); state->instruction_pointer = 0; } void Instruction_goto::write(std::ostream &stream) const { stream << "goto " << this->target << std::endl; } Instruction_iffalse::Instruction_iffalse(long target) : target(target) { } void Instruction_iffalse::perform(State *state) const { int a = (int)state->stack.top(); state->stack.pop(); if (a == 0) { state->current_block = std::to_string(this->target); state->instruction_pointer = 0; } else { state->instruction_pointer++; } } void Instruction_iffalse::write(std::ostream &stream) const { stream << "iffalse " << this->target << std::endl; } Instruction_invokevirtual::Instruction_invokevirtual(std::string identifier) : identifier(identifier) { } void Instruction_invokevirtual::perform(State *state) const { // Push all the variables to the variable stack state->variable_stack.push(state->variables); state->variables.clear(); // Push the current call to the call stack state->call_stack.push(std::tuple<std::string, long>(state->current_block, state->instruction_pointer)); // Change the target block state->current_block = this->identifier; state->instruction_pointer = 0; // Pop the number of parameters passed, as it's not used state->stack.pop(); } void Instruction_invokevirtual::write(std::ostream &stream) const { stream << "invokevirtual " << this->identifier << std::endl; } Instruction_ireturn::Instruction_ireturn() { } void Instruction_ireturn::perform(State *state) const { // Pop all the variables from the variable stack state->variables = state->variable_stack.top(); state->variable_stack.pop(); // Pop the previous call from the call stack std::tuple<std::string, long> entry = state->call_stack.top(); // Change the target block state->current_block = std::get<0>(entry); state->instruction_pointer = std::get<1>(entry); state->call_stack.pop(); // Increment the instruction pointer by one to move on state->instruction_pointer++; } void Instruction_ireturn::write(std::ostream &stream) const { stream << "ireturn" << std::endl; } Instruction_print::Instruction_print() { } void Instruction_print::perform(State *state) const { int parameter_count = (int)state->stack.top(); state->stack.pop(); for (int i = 0; i < parameter_count; i++) { int parameter = (int)state->stack.top(); state->stack.pop(); std::cout << parameter << std::endl; } state->instruction_pointer++; } void Instruction_print::write(std::ostream &stream) const { stream << "print" << std::endl; } Instruction_stop::Instruction_stop() { } void Instruction_stop::perform(State *state) const { // Will end as the block ends after this instruction state->instruction_pointer++; } void Instruction_stop::write(std::ostream &stream) const { stream << "stop" << std::endl; }
25.024648
106
0.686647
720bb2895a6c02e62838eab7e95643be1aa134eb
6,035
cc
C++
apis/ocpdiag/ocpdiag/core/results/internal/logging_test.cc
opencomputeproject/ocp-diag-core
37b83ff6f69684b435364000d26cd913eb6ff5f3
[ "Apache-2.0" ]
10
2021-11-09T20:20:56.000Z
2022-03-25T11:59:14.000Z
apis/ocpdiag/ocpdiag/core/results/internal/logging_test.cc
opencomputeproject/ocp-diag-core
37b83ff6f69684b435364000d26cd913eb6ff5f3
[ "Apache-2.0" ]
2
2022-02-10T21:27:33.000Z
2022-03-23T22:08:30.000Z
apis/ocpdiag/ocpdiag/core/results/internal/logging_test.cc
opencomputeproject/ocp-diag-core
37b83ff6f69684b435364000d26cd913eb6ff5f3
[ "Apache-2.0" ]
1
2021-11-24T04:46:00.000Z
2021-11-24T04:46:00.000Z
// Copyright 2021 Google LLC // // 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 "ocpdiag/core/results/internal/logging.h" #include <stdio.h> #include <unistd.h> #include <array> #include <future> // #include <sstream> #include <string> #include <vector> #include "google/protobuf/repeated_field.h" #include "google/protobuf/util/json_util.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "ocpdiag/core/compat/status_converters.h" #include "ocpdiag/core/results/internal/test_utils.h" #include "ocpdiag/core/results/results.pb.h" #include "ocpdiag/core/testing/proto_matchers.h" #include "ocpdiag/core/testing/status_matchers.h" namespace ocpdiag { namespace results { using internal::ArtifactWriter; using internal::TestFile; using ::ocpdiag::testing::EqualsProto; using ::ocpdiag::testing::IsOkAndHolds; using ::ocpdiag::testing::Partially; using ::ocpdiag::testing::StatusIs; using ::testing::Pointwise; namespace { namespace rpb = ::ocpdiag::results_pb; TEST(OpenAndReturnDescriptor, ValidFilepath) { EXPECT_OK(internal::OpenAndGetDescriptor("/dev/null")); } TEST(OpenAndReturnDescriptor, InvalidFilepath) { EXPECT_THAT(internal::OpenAndGetDescriptor("invalid/"), StatusIs(absl::StatusCode::kInternal)); } TEST(OpenAndReturnDescriptor, EmptyString) { EXPECT_THAT(internal::OpenAndGetDescriptor(""), IsOkAndHolds(-1)); } // Manually confirms that artifact contents are as expected TEST(ArtifactWriter, Simple) { TestFile file; std::stringstream json_stream; { ArtifactWriter writer(dup(fileno(file.ptr)), &json_stream); rpb::OutputArtifact out_pb; rpb::TestStepArtifact* step_pb = out_pb.mutable_test_step_artifact(); rpb::Diagnosis* diag = step_pb->mutable_diagnosis(); *diag->mutable_hardware_info_id()->Add() = "7"; diag->set_msg("test message"); diag->set_symptom("test symptom"); diag->set_type(rpb::Diagnosis::PASS); step_pb->set_test_step_id("7"); writer.Write(out_pb); } // writers fall out of scope and Flush/close file // Convert human-readable JSON output back to message rpb::OutputArtifact got; auto status = AsAbslStatus(google::protobuf::util::JsonStringToMessage(json_stream.str(), &got)); ASSERT_OK(status); // Compare to what we expect (ignoring timestamp) auto want = R"pb( test_step_artifact { diagnosis { symptom: "test symptom" type: PASS msg: "test message" hardware_info_id: "7" } test_step_id: "7" } sequence_number: 0 )pb"; EXPECT_THAT(got, Partially(testing::EqualsProto(want))); } // TEST(ArtifactWriter, MultipleWritersInOrder) { std::vector<rpb::OutputArtifact> wants; std::vector<rpb::OutputArtifact> gots; TestFile file; std::stringstream json_stream; { ArtifactWriter writer1(dup(fileno(file.ptr)), &json_stream); ArtifactWriter writer2 = writer1; rpb::OutputArtifact out_pb; rpb::TestStepArtifact* step_pb = out_pb.mutable_test_step_artifact(); rpb::Log* log_pb = step_pb->mutable_log(); step_pb->set_test_step_id("76"); log_pb->set_text("Hello, "); writer1.Write(out_pb); wants.push_back(out_pb); log_pb->set_text("World!"); writer2.Write(out_pb); wants.push_back(out_pb); } // writers fall out of scope and Flush/close file } // Confirms that all newline '\n' characters are escaped '\\n'. // And that all escaped newline '\\n' characters are ignored. TEST(ArtifactWriter, replace_newlines) { const std::string input = "escape this newline\n, but not this one\\n"; const std::string want = "escape this newline\\n, but not this one\\n"; std::stringstream json_stream; { ArtifactWriter writer(-1, &json_stream); rpb::OutputArtifact out_pb; out_pb.mutable_test_step_artifact()->mutable_log()->set_text(input); writer.Write(out_pb); } // writers fall out of scope and Flush/close file rpb::OutputArtifact got; auto status = AsAbslStatus(google::protobuf::util::JsonStringToMessage(json_stream.str(), &got)); ASSERT_OK(status); ASSERT_STREQ(got.test_step_artifact().log().text().c_str(), want.c_str()); } // Confirms that artifact integrity is maintained with many asynchronous writes TEST(ArtifactWriter, ThreadSafetyCheck) { TestFile file; const int writer_copies = 20; const int artifact_count = 1000; { ArtifactWriter root_writer(dup(fileno(file.ptr)), nullptr); std::array<ArtifactWriter, writer_copies> writers; for (int i = 0; i < writer_copies; i++) { writers[i] = root_writer; } std::vector<std::future<void>> threads; for (auto& writer : writers) { threads.push_back(std::async(std::launch::async, [&] { for (int i = 0; i < artifact_count; i++) { rpb::OutputArtifact out_pb; writer.Write(out_pb); } })); } for (std::future<void>& thread : threads) { thread.wait(); } } // writers fall out of scope and Flush/close file } // Confirms that writer does not write after Close() and fails gracefully TEST(ArtifactWriter, WriteFailAfterClose) { TestFile file; std::stringstream json; ArtifactWriter writer(fileno(file.ptr), &json); writer.Close(); rpb::OutputArtifact out_pb; *out_pb.mutable_test_step_artifact() = rpb::TestStepArtifact(); writer.Write(out_pb); } } // namespace } // namespace results } // namespace ocpdiag
31.432292
89
0.708699
720c50dc8d59b9d1cfb7c087510ca8fb74d2d718
7,580
cpp
C++
level1/p11_linkedList/linkedList.cpp
shui12jiao/c2021
0a21392fe0c35cbebc04335d43e134410e17d89c
[ "MIT" ]
null
null
null
level1/p11_linkedList/linkedList.cpp
shui12jiao/c2021
0a21392fe0c35cbebc04335d43e134410e17d89c
[ "MIT" ]
null
null
null
level1/p11_linkedList/linkedList.cpp
shui12jiao/c2021
0a21392fe0c35cbebc04335d43e134410e17d89c
[ "MIT" ]
null
null
null
#include <sstream> #include "illegalParameter.h" #include "linearList.h" #include "linkedNode.h" template <typename T> class linkedList : public linearList<T> { //链表 public: linkedList(); linkedList(const linkedList<T>&); ~linkedList(); bool empty() const { return listSize == 0; } int size() const { return listSize; }; T& get(int theIndex) const; int indexOf(const T& theElement, int theIndex = -1) const; void erase(int theIndex); void insert(int theIndex, const T& theElement); void output(std::ostream& out) const; void clear(); void push_back(const T& theElement); void pop_back(); void set(int theIndex, const T& theElement); void resize(int size, const T& theElement); void reverse(); protected: linkedNode<T>* firstNode; linkedNode<T>* lastNode; int listSize; }; template <typename T> linkedList<T>::linkedList() { firstNode = nullptr; lastNode = nullptr; listSize = 0; } template <typename T> linkedList<T>::linkedList(const linkedList<T>& theList) { listSize = theList.listSize; if (listSize == 0) { linkedList(); return; } linkedNode<T>* sourceNode = theList.firstNode; firstNode = new linkedNode<T>(sourceNode->element); linkedNode<T>* currentNode = firstNode; sourceNode = sourceNode->next; while (sourceNode != nullptr) { currentNode->next = new linkedNode<T>(sourceNode->element); currentNode = currentNode->next; sourceNode = sourceNode->next; } lastNode = currentNode; lastNode->next = nullptr; } template <typename T> linkedList<T>::~linkedList() { linkedNode<T>* tempNode; while (firstNode != nullptr) { tempNode = firstNode->next; delete firstNode; firstNode = tempNode; } } template <typename T> T& linkedList<T>::get(int theIndex) const { if (theIndex >= listSize || theIndex < 0) { std::ostringstream s; s << "获取失败 链表大小为" << listSize << " 输入Index为" << theIndex << std::endl; throw illegalParameter(s.str()); } linkedNode<T>* currentNode = firstNode; for (int i = 0; i < theIndex; ++i) { currentNode = currentNode->next; } return currentNode->element; } template <typename T> int linkedList<T>::indexOf(const T& theElement, int theIndex) const { if (theIndex >= listSize - 1 || theIndex < -1) { return -1; } linkedNode<T>* currentNode = firstNode; int index = theIndex + 1; for (int i = -1; i < theIndex; ++i) { currentNode = currentNode->next; } while (currentNode != nullptr && currentNode->element != theElement) { ++index; currentNode = currentNode->next; } if (currentNode == nullptr) { return -1; } return index; } template <typename T> void linkedList<T>::erase(int theIndex) { if (theIndex >= listSize || theIndex < 0) { std::ostringstream s; s << "删除失败 链表大小为" << listSize << " 输入Index为" << theIndex << std::endl; throw illegalParameter(s.str()); } linkedNode<T>* deleteNode; if (theIndex == 0) { deleteNode = firstNode; firstNode = firstNode->next; } else { linkedNode<T>* preNode = firstNode; for (int i = 1; i < theIndex; ++i) { preNode = preNode->next; } deleteNode = preNode->next; preNode->next = deleteNode->next; if (deleteNode == lastNode) lastNode = preNode; } delete deleteNode; --listSize; } template <typename T> void linkedList<T>::insert(int theIndex, const T& theElement) { if (theIndex > listSize || theIndex < 0) { std::ostringstream s; s << "插入失败 链表大小为" << listSize << " 输入Index为" << theIndex << std::endl; throw illegalParameter(s.str()); } if (theIndex == 0) { firstNode = new linkedNode<T>(theElement, firstNode); if (listSize == 0) { lastNode = firstNode; } } else { linkedNode<T>* preNode = firstNode; for (int i = 1; i < theIndex; ++i) { preNode = preNode->next; } preNode->next = new linkedNode<T>(theElement, preNode->next); if (listSize == theIndex) { lastNode = preNode->next; } } ++listSize; } template <typename T> void linkedList<T>::output(std::ostream& out) const { for (linkedNode<T>* currentNode = firstNode; currentNode != nullptr; currentNode = currentNode->next) { out << currentNode->element << ' '; } } template <typename T> void linkedList<T>::clear() { linkedNode<T>* tempNode = firstNode; while (firstNode != nullptr) { tempNode = firstNode->next; delete firstNode; firstNode = tempNode; } listSize = 0; } template <typename T> void linkedList<T>::push_back(const T& theElement) { linkedNode<T>* newNode = new linkedNode<T>(theElement, nullptr); if (listSize == 0) { firstNode = newNode; lastNode = newNode; } else { lastNode->next = newNode; lastNode = newNode; } ++listSize; } template <typename T> void linkedList<T>::pop_back() { if (listSize == 0) { std::cerr << "链表为空" << std::endl; return; } else if (listSize == 1) { delete firstNode; firstNode = nullptr; lastNode = nullptr; } else { linkedNode<T>* preNode = firstNode; for (int i = 2; i < listSize; ++i) { preNode = preNode->next; } delete lastNode; preNode->next = nullptr; lastNode = preNode; } --listSize; } template <typename T> std::ostream& operator<<(std::ostream& out, const linkedList<T>& l) { l.output(out); return out; } template <typename T> void linkedList<T>::set(int theIndex, const T& theElement) { if (theIndex >= listSize || theIndex < 0) { std::cerr << "更改失败 链表大小为" << listSize << " 输入Index为" << theIndex << std::endl; return; } linkedNode<T>* currentNode = firstNode; for (int i = 0; i < theIndex; ++i) { currentNode = currentNode->next; } currentNode->element = theElement; } template <typename T> void linkedList<T>::resize(int size, const T& theElement) { if (size < 0) { std::ostringstream s; s << "失败 大小为" << listSize << " 输入Size为" << size << std::endl; throw illegalParameter(s.str()); } else if (size < listSize) { while (size < listSize) { pop_back(); } } else if (size > listSize) { while (size > listSize) { push_back(theElement); } } else { return; } } template <typename T> void linkedList<T>::reverse() { lastNode = firstNode; linkedNode<T>* tempNode = nullptr; linkedNode<T>* nextNode = nullptr; while (firstNode != nullptr) { nextNode = firstNode->next; firstNode->next = tempNode; tempNode = firstNode; firstNode = nextNode; } firstNode = tempNode; } int main() { linkedList<int> l; for (int i = 1; i <= 10; ++i) l.push_back(i); l.set(9, 5); linkedList<int> list(l); std::cout << list << std::endl; list.reverse(); std::cout << list << std::endl; int i1 = list.indexOf(5); int i2 = list.indexOf(5, i1); int i3 = list.indexOf(5, i2); std::cout << "节点序号从0开始" << std::endl; std::cout << "数字5第一次出现节点序号:" << i1 << std::endl; std::cout << "数字5第一次出现节点序号:" << i2 << std::endl; std::cout << "数字5第一次出现节点序号:" << i3 << std::endl; return 0; }
26.784452
107
0.581003
720e527a45f234e6add1ca37bbf847a70b75d5fc
1,617
cpp
C++
src/lib/Mutex.cpp
romoadri21/boi
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
[ "BSD-3-Clause" ]
null
null
null
src/lib/Mutex.cpp
romoadri21/boi
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
[ "BSD-3-Clause" ]
null
null
null
src/lib/Mutex.cpp
romoadri21/boi
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010, Piet Hein Schouten. All rights reserved. * This code is licensed under a BSD-style license that can be * found in the LICENSE file. The license can also be found at: * http://www.boi-project.org/license */ #include <QMutex> #include <QWaitCondition> #include "ThreadLockData.h" #include "MutexBase.h" #include "Mutex.h" namespace BOI { Mutex::Mutex() : m_numAccessors(0), m_doWait(true), m_pHead(NULL), m_pTail(NULL), m_pMutex(NULL), m_pBase(NULL) { } void Mutex::Lock() { if (m_numAccessors.fetchAndAddAcquire(1) != 0) { m_pMutex->lock(); if (m_doWait || (m_pHead != NULL)) { ThreadLockData* pThreadLockData = m_pBase->GetData(); pThreadLockData->pNext = NULL; /* * Enqueue the thread. */ if (m_pHead == NULL) { m_pHead = pThreadLockData; } else { m_pTail->pNext = pThreadLockData; } m_pTail = pThreadLockData; pThreadLockData->waitCondition.wait(m_pMutex); /* * Dequeue thread. */ m_pHead = m_pHead->pNext; } m_doWait = true; m_pMutex->unlock(); } } void Mutex::Unlock() { if (m_numAccessors.fetchAndAddRelease(-1) != 1) { m_pMutex->lock(); m_doWait = false; if (m_pHead != NULL) { m_pHead->waitCondition.wakeOne(); } m_pMutex->unlock(); } } } // namespace BOI
18.586207
65
0.520717
72116306bdcb5a850237fd09e64692faddd4be31
299
cpp
C++
code/hackerrank/left rotation.cpp
Codernob/problem-solving-codes
c852bae4e31887bd442d70af921348c8f1d246bf
[ "MIT" ]
null
null
null
code/hackerrank/left rotation.cpp
Codernob/problem-solving-codes
c852bae4e31887bd442d70af921348c8f1d246bf
[ "MIT" ]
null
null
null
code/hackerrank/left rotation.cpp
Codernob/problem-solving-codes
c852bae4e31887bd442d70af921348c8f1d246bf
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void lr(int a[],int n) { int temp=a[0]; for(int i=0;i<n-1;i++) a[i]=a[i+1]; a[n-1]=temp; } int main() { int n,d; cin>>n/*>>d*/; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; /*for(int i=1;i<=d;i++)*/ lr(a,n); for(int i=0;i<n;i++) cout<<a[i]<<" "; return 0; }
18.6875
38
0.521739
72127937d14cdbfedbe5d1c95ae94d20942522bf
664
hpp
C++
include/simple_math/vec.hpp
signekatt/simple_math
aa17f449330a2dd38a10222074c1139fdbdeeb75
[ "MIT" ]
null
null
null
include/simple_math/vec.hpp
signekatt/simple_math
aa17f449330a2dd38a10222074c1139fdbdeeb75
[ "MIT" ]
null
null
null
include/simple_math/vec.hpp
signekatt/simple_math
aa17f449330a2dd38a10222074c1139fdbdeeb75
[ "MIT" ]
null
null
null
// Copyright(c) 2019-present, Anton Lilja. // Distributed under the MIT License (http://opensource.org/licenses/MIT) #pragma once #include "vec2.hpp" #include "vec3.hpp" #include "vec4.hpp" namespace sm { // Other op funcs template <typename V> inline V inverse(const V& v) { return v.inverse(); } template <typename V> inline float magnitude(const V& v) { return v.magnitude(); } template <typename V> inline float square_magnitude(const V& v) { return v.square_magnitude(); } template <typename V> inline V normalize(const V& v) { return v.normalize(); } } // namespace sm
21.419355
73
0.626506
721acc9a9c532c8339dcd09529c1bacf2d4dcb43
4,277
cpp
C++
tests/test_jpeg_out.cpp
Hasnain17/modern_cpp_image_to_jpeg
889e37e051d12cf2430f0ffe75fd94bd1a44eb88
[ "MIT" ]
null
null
null
tests/test_jpeg_out.cpp
Hasnain17/modern_cpp_image_to_jpeg
889e37e051d12cf2430f0ffe75fd94bd1a44eb88
[ "MIT" ]
1
2021-03-02T08:46:30.000Z
2021-03-02T08:46:30.000Z
tests/test_jpeg_out.cpp
Hasnain17/modern_cpp_image_to_jpeg
889e37e051d12cf2430f0ffe75fd94bd1a44eb88
[ "MIT" ]
1
2021-03-02T07:19:32.000Z
2021-03-02T07:19:32.000Z
//! Integration test for C++17 variant of the toojpeg implementation #include <iostream> #include "toojpeg_17.h" #include "vendor/sha2.h" #include "tests.h" #include <filesystem> #include <array> using std::cout; using std::endl; // 800x600 image const auto width = 800; const auto height = 600; void testColor() { cout << "800*600 color gradient jpg: " << std::filesystem::current_path().append("color_gradient.jpg") << endl; // RGB: one byte each for red, green, blue const auto bytesPerPixel = 3; auto image = std::vector<unsigned char>(width * height * bytesPerPixel); // create a nice color transition for (auto y = 0; y < height; y++) { for (auto x = 0; x < width; x++) { // memory location of current pixel auto offset = (y * width + x) * bytesPerPixel; // red and green fade from 0 to 255, blue is always 127 image[offset] = 255 * x / width; image[offset + 1] = 255 * y / height; image[offset + 2] = 127; } } std::ofstream outfile("color_gradient.jpg", std::ios_base::trunc | std::ios_base::out | std::ios_base::binary); bool ok = TooJpeg17::writeJpeg<90>( [&outfile](ByteView v) { outfile.write(v.data(), v.size_); }, image.data(), width, height, false, true, "TooJpeg17 example image"); outfile.flush(); ASSERT_EQUAL(ok, true); std::vector<unsigned char> hash(picosha2::k_digest_size); std::array<unsigned char, picosha2::k_digest_size> expected = {123, 245, 49, 202, 213, 219, 131, 175, 72, 129, 182, 152, 15, 16, 158, 243, 136, 190, 229, 106, 233, 89, 60, 61, 122, 146, 59, 135, 173, 108, 90, 89}; std::ifstream in("color_gradient.jpg"); picosha2::hash256(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>(), hash.begin(), hash.end()); ASSERT_THROW(std::equal(hash.begin(), hash.end(), expected.begin())); } void testGrayscale() { cout << "800*600 grayscale gradient jpg: " << std::filesystem::current_path().append("grayscale_gradient.jpg") << endl; // Grayscale: one byte per pixel const auto bytesPerPixel = 1; auto image = std::vector<unsigned char>(width * height * bytesPerPixel); // create a grayscale transition for (auto y = 0; y < height; y++) { for (auto x = 0; x < width; x++) { // memory location of current pixel auto offset = (y * width + x) * bytesPerPixel; // red and green fade from 0 to 255, blue is always 127 image[offset] = 255 * x / width; image[offset + 1] = 255 * y / height; image[offset + 2] = 127; } } std::ofstream outfile("grayscale_gradient.jpg", std::ios_base::trunc | std::ios_base::out | std::ios_base::binary); bool ok = TooJpeg17::writeJpeg<90>( [&outfile](ByteView v) { outfile.write(v.data(), v.size_); }, image.data(), width, height, false, false, "TooJpeg17 example image"); outfile.flush(); ASSERT_EQUAL(ok, true); std::vector<unsigned char> hash(picosha2::k_digest_size); std::array<unsigned char, picosha2::k_digest_size> expected = {215, 33, 80, 145, 167, 9, 23, 212, 246, 246, 72, 55, 10, 102, 224, 237, 149, 162, 58, 10, 251, 204, 106, 3, 178, 5, 62, 55, 134, 202, 85, 46}; std::ifstream in("grayscale_gradient.jpg"); picosha2::hash256(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>(), hash.begin(), hash.end()); for (auto a: hash) std::cout << (int) a << ","; cout << endl; ASSERT_THROW(std::equal(hash.begin(), hash.end(), expected.begin())); } int main(int argc, char *argv[]) { std::ios_base::sync_with_stdio(false); ASSERT_EQUAL(argc, 2); switch (argv[1][0]) { case '0': testColor(); break; case '1': testGrayscale(); break; } return 0; }
40.349057
119
0.550386
721c2de3ada7099eceea094e17c91fb0912c52f8
4,875
cpp
C++
modules/dasClangBind/src/dasClangBind.func_3.cpp
profelis/daScript
eea57f39dec4dd6168ee64c8ae5139cbcf2937bc
[ "BSD-3-Clause" ]
421
2019-08-15T15:40:04.000Z
2022-03-29T06:59:06.000Z
modules/dasClangBind/src/dasClangBind.func_3.cpp
profelis/daScript
eea57f39dec4dd6168ee64c8ae5139cbcf2937bc
[ "BSD-3-Clause" ]
55
2019-08-17T13:50:53.000Z
2022-03-25T17:58:38.000Z
modules/dasClangBind/src/dasClangBind.func_3.cpp
profelis/daScript
eea57f39dec4dd6168ee64c8ae5139cbcf2937bc
[ "BSD-3-Clause" ]
58
2019-08-22T17:04:13.000Z
2022-03-25T17:43:28.000Z
// this file is generated via daScript automatic C++ binder // all user modifications will be lost after this file is re-generated #include "daScript/misc/platform.h" #include "daScript/ast/ast.h" #include "daScript/ast/ast_interop.h" #include "daScript/ast/ast_handle.h" #include "daScript/ast/ast_typefactory_bind.h" #include "daScript/simulate/bind_enum.h" #include "dasClangBind.h" #include "need_dasClangBind.h" namespace das { void Module_dasClangBind::initFunctions_3() { addExtern< void * (*)(void *) , clang_getChildDiagnostics >(*this,lib,"clang_getChildDiagnostics",SideEffects::worstDefault,"clang_getChildDiagnostics") ->args({"D"}); addExtern< unsigned int (*)(CXTranslationUnitImpl *) , clang_getNumDiagnostics >(*this,lib,"clang_getNumDiagnostics",SideEffects::worstDefault,"clang_getNumDiagnostics") ->args({"Unit"}); addExtern< void * (*)(CXTranslationUnitImpl *,unsigned int) , clang_getDiagnostic >(*this,lib,"clang_getDiagnostic",SideEffects::worstDefault,"clang_getDiagnostic") ->args({"Unit","Index"}); addExtern< void * (*)(CXTranslationUnitImpl *) , clang_getDiagnosticSetFromTU >(*this,lib,"clang_getDiagnosticSetFromTU",SideEffects::worstDefault,"clang_getDiagnosticSetFromTU") ->args({"Unit"}); addExtern< void (*)(void *) , clang_disposeDiagnostic >(*this,lib,"clang_disposeDiagnostic",SideEffects::worstDefault,"clang_disposeDiagnostic") ->args({"Diagnostic"}); addExtern< CXString (*)(void *,unsigned int) , clang_formatDiagnostic ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_formatDiagnostic",SideEffects::worstDefault,"clang_formatDiagnostic") ->args({"Diagnostic","Options"}); addExtern< unsigned int (*)() , clang_defaultDiagnosticDisplayOptions >(*this,lib,"clang_defaultDiagnosticDisplayOptions",SideEffects::worstDefault,"clang_defaultDiagnosticDisplayOptions"); addExtern< CXDiagnosticSeverity (*)(void *) , clang_getDiagnosticSeverity >(*this,lib,"clang_getDiagnosticSeverity",SideEffects::worstDefault,"clang_getDiagnosticSeverity") ->args({""}); addExtern< CXSourceLocation (*)(void *) , clang_getDiagnosticLocation ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticLocation",SideEffects::worstDefault,"clang_getDiagnosticLocation") ->args({""}); addExtern< CXString (*)(void *) , clang_getDiagnosticSpelling ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticSpelling",SideEffects::worstDefault,"clang_getDiagnosticSpelling") ->args({""}); addExtern< CXString (*)(void *,CXString *) , clang_getDiagnosticOption ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticOption",SideEffects::worstDefault,"clang_getDiagnosticOption") ->args({"Diag","Disable"}); addExtern< unsigned int (*)(void *) , clang_getDiagnosticCategory >(*this,lib,"clang_getDiagnosticCategory",SideEffects::worstDefault,"clang_getDiagnosticCategory") ->args({""}); addExtern< CXString (*)(unsigned int) , clang_getDiagnosticCategoryName ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticCategoryName",SideEffects::worstDefault,"clang_getDiagnosticCategoryName") ->args({"Category"}); addExtern< CXString (*)(void *) , clang_getDiagnosticCategoryText ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticCategoryText",SideEffects::worstDefault,"clang_getDiagnosticCategoryText") ->args({""}); addExtern< unsigned int (*)(void *) , clang_getDiagnosticNumRanges >(*this,lib,"clang_getDiagnosticNumRanges",SideEffects::worstDefault,"clang_getDiagnosticNumRanges") ->args({""}); addExtern< CXSourceRange (*)(void *,unsigned int) , clang_getDiagnosticRange ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticRange",SideEffects::worstDefault,"clang_getDiagnosticRange") ->args({"Diagnostic","Range"}); addExtern< unsigned int (*)(void *) , clang_getDiagnosticNumFixIts >(*this,lib,"clang_getDiagnosticNumFixIts",SideEffects::worstDefault,"clang_getDiagnosticNumFixIts") ->args({"Diagnostic"}); addExtern< CXString (*)(void *,unsigned int,CXSourceRange *) , clang_getDiagnosticFixIt ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getDiagnosticFixIt",SideEffects::worstDefault,"clang_getDiagnosticFixIt") ->args({"Diagnostic","FixIt","ReplacementRange"}); addExtern< CXString (*)(CXTranslationUnitImpl *) , clang_getTranslationUnitSpelling ,SimNode_ExtFuncCallAndCopyOrMove>(*this,lib,"clang_getTranslationUnitSpelling",SideEffects::worstDefault,"clang_getTranslationUnitSpelling") ->args({"CTUnit"}); addExtern< CXTranslationUnitImpl * (*)(void *,const char *,int,const char *const *,unsigned int,CXUnsavedFile *) , clang_createTranslationUnitFromSourceFile >(*this,lib,"clang_createTranslationUnitFromSourceFile",SideEffects::worstDefault,"clang_createTranslationUnitFromSourceFile") ->args({"CIdx","source_filename","num_clang_command_line_args","clang_command_line_args","num_unsaved_files","unsaved_files"}); } }
87.053571
284
0.791179
721f63b1042c4020bc953e493fbecf874d6fdb7c
3,585
cpp
C++
test/unit_tests/02_lock_acquire_release/test.cpp
stephenneuendorffer/mlir-aie
c95e5f4996f5490759705de63820adcf373444e6
[ "Apache-2.0" ]
67
2021-08-29T04:47:56.000Z
2022-03-29T05:38:32.000Z
test/unit_tests/02_lock_acquire_release/test.cpp
pssrawat/mlir-aie
b3f29a6344b70c6730d7ce0485b7bda54f3277dc
[ "Apache-2.0" ]
45
2021-09-02T21:35:59.000Z
2022-03-18T10:07:25.000Z
test/unit_tests/02_lock_acquire_release/test.cpp
hanchenye/mlir-aie
8027f07c8d58afc11c25aab743fbcb901dac2ae6
[ "Apache-2.0" ]
26
2021-08-29T17:38:33.000Z
2022-03-29T23:25:05.000Z
//===- test.cpp -------------------------------------------------*- C++ -*-===// // // This file is licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // // (c) Copyright 2020 Xilinx Inc. // //===----------------------------------------------------------------------===// #include <cassert> #include <cmath> #include <cstdio> #include <cstring> #include <thread> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <xaiengine.h> #include "test_library.h" #define HIGH_ADDR(addr) ((addr & 0xffffffff00000000) >> 32) #define LOW_ADDR(addr) (addr & 0x00000000ffffffff) #define mlir_aie_STACK_OFFSET 4096 #include "aie_inc.cpp" int main(int argc, char *argv[]) { printf("test start.\n"); aie_libxaie_ctx_t *_xaie = mlir_aie_init_libxaie(); mlir_aie_init_device(_xaie); mlir_aie_configure_cores(_xaie); mlir_aie_configure_switchboxes(_xaie); mlir_aie_initialize_locks(_xaie); mlir_aie_configure_dmas(_xaie); //XAieLib_usleep(1000); int errors = 0; // XAieTile_LockRelease(&(TileInst[j][i]), l, val, timeout) // XAIeTile_LockAcquire(&(TileInst[j][i]), l, val, timeout) // mlir_aie_acquire_lock(_xaie, 1, 3, 3, 0, 0); usleep(1000); u32 l = mlir_aie_read32(_xaie, mlir_aie_get_tile_addr(_xaie, 3, 1) + 0x0001EF00); u32 s = (l >> 6) & 0x3; printf("Lock acquire 3: 0 is %x\n",s); mlir_aie_acquire_lock(_xaie, 1, 3, 5, 0, 0); usleep(1000); l = mlir_aie_read32(_xaie, mlir_aie_get_tile_addr(_xaie, 3, 1) + 0x0001EF00); s = (l >> 10) & 0x3; printf("Lock acquire 5: 0 is %x\n",s); mlir_aie_release_lock(_xaie, 1, 3, 5, 1, 0); usleep(1000); l = mlir_aie_read32(_xaie, mlir_aie_get_tile_addr(_xaie, 3, 1) + 0x0001EF00); s = (l >> 10) & 0x3; printf("Lock release 5: 0 is %x\n",s); u32 locks = mlir_aie_read32(_xaie, mlir_aie_get_tile_addr(_xaie, 3, 1) + 0x0001EF00); for (int lock=0;lock<16;lock++) { u32 two_bits = (locks >> (lock*2)) & 0x3; if (two_bits) { printf("Lock %d: ", lock); u32 acquired = two_bits & 0x1; u32 value = two_bits & 0x2; if (acquired) printf("Acquired "); printf(value?"1":"0"); printf("\n"); if(((lock == 3) && (acquired != 1)) || ((lock == 5) && (acquired != 0) && (value != 0))) errors++; } } mlir_aie_configure_cores(_xaie); mlir_aie_start_cores(_xaie); usleep(1000); locks = mlir_aie_read32(_xaie, mlir_aie_get_tile_addr(_xaie, 3, 1) + 0x0001EF00); for (int lock=0;lock<16;lock++) { u32 two_bits = (locks >> (lock*2)) & 0x3; if (two_bits) { printf("Lock %d: ", lock); u32 acquired = two_bits & 0x1; u32 value = two_bits & 0x2; if (acquired) printf("Acquired "); printf(value?"1":"0"); printf("\n"); if(((lock == 3) && (acquired != 1)) || ((lock == 5) && (acquired != 0) && (value != 0))) errors++; } } int res = 0; if (!errors) { printf("PASS!\n"); res = 0; } else { printf("Fail!\n"); res = -1; } mlir_aie_deinit_libxaie(_xaie); printf("test done.\n"); return res; }
30.12605
100
0.530544
7220274c2f0659c42f463ff7829710cef92ef67a
2,359
cpp
C++
ojcpp/leetcode/000/001_e_twosum.cpp
softarts/oj
2f51f360a7a6c49e865461755aec2f3a7e721b9e
[ "Apache-2.0" ]
3
2019-05-04T03:26:02.000Z
2019-08-29T01:20:44.000Z
ojcpp/leetcode/000/001_e_twosum.cpp
softarts/oj
2f51f360a7a6c49e865461755aec2f3a7e721b9e
[ "Apache-2.0" ]
null
null
null
ojcpp/leetcode/000/001_e_twosum.cpp
softarts/oj
2f51f360a7a6c49e865461755aec2f3a7e721b9e
[ "Apache-2.0" ]
null
null
null
/* https://leetcode.com/problems/two-sum/ Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. 思路 在one pass中,每个element-target=value,看看value是否已存在于hash map中 */ #include <codech/codech_def.h> using namespace CODECH; using namespace std; /* vector<int> twoSum(vector<int>& nums, int target) { std::unordered_set<int> sets; vector<int> ret; std::copy(nums.begin(), nums.end(), inserter(sets,sets.begin())); for (int i = 0; i < nums.size(); i++) { int key = target - nums[i]; if (key == nums[i]) continue; auto found = sets.find(key); if (found != sets.end()) { ret.push_back(i); } } return ret; } */ class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { std::unordered_map<int,int> maps; vector<int> ret; for (int i = 0; i < nums.size(); i++) { int key = target - nums[i]; auto found = maps.find(nums[i]); if (found == maps.end()) { maps.insert(std::make_pair(key,i)); } else { ret.push_back(found->second); ret.push_back(i); break; } } return ret; } }; /* vector<int> twoSum(vector<int>& nums, int target) { std::unordered_map<int,int> maps; vector<int> ret; for (int i = 0; i < nums.size(); i++) { int key = target - nums[i]; auto found = maps.find(key); if (found == maps.end()) { maps.insert(std::make_pair(nums[i],i)); } else { ret.push_back(found->second); ret.push_back(i); break; } } return ret; } void printResult(const vector<int>& ret) { for_each(ret.begin(), ret.end(), [](int elem) { cout << elem << " "; } ); std::cout << std::endl; } */ DEFINE_CODE_TEST(001_twosum) { // vector<int> ret; // vector<int> test1 = { 2, 7, 11, 15 }; // printResult(twoSum(test1, 9)); // vector<int> test2 = { 3,2,4 }; // printResult(twoSum(test2, 6)); vector<int> test1 = { 2, 7, 11, 15 }; Solution obj; VERIFY_CASE(PRINT_VEC(obj.twoSum(test1, 9)),"0 1"); }
21.445455
69
0.492158
72208adfe8279fd00a279c401a823f6d33b2b62a
3,703
cpp
C++
android-quill-master/jni/org_libharu_Document.cpp
xiang-lab/Note
e8c902f13e59de22c3312f81da44d45436d84165
[ "Apache-2.0" ]
null
null
null
android-quill-master/jni/org_libharu_Document.cpp
xiang-lab/Note
e8c902f13e59de22c3312f81da44d45436d84165
[ "Apache-2.0" ]
null
null
null
android-quill-master/jni/org_libharu_Document.cpp
xiang-lab/Note
e8c902f13e59de22c3312f81da44d45436d84165
[ "Apache-2.0" ]
null
null
null
#include "org_libharu_Document.h" #include "org_libharu_HPDF.h" #include "haru_error_handler.h" #include <assert.h> jfieldID Document_HPDF_Doc_Pointer_ID; JNIEXPORT void JNICALL Java_org_libharu_Document_initIDs (JNIEnv *env, jclass cls) { Document_HPDF_Doc_Pointer_ID = env->GetFieldID(cls, "HPDF_Doc_Pointer", "I"); if (Document_HPDF_Doc_Pointer_ID == NULL) { return; } } HPDF_Doc get_HPDF_Doc(JNIEnv *env, jobject obj) { int ptr = env->GetIntField(obj, Document_HPDF_Doc_Pointer_ID); return (HPDF_Doc)ptr; } void set_HPDF_Doc(JNIEnv *env, jobject obj, HPDF_Doc ptr) { env->SetIntField(obj, Document_HPDF_Doc_Pointer_ID, (int)ptr); } JNIEXPORT void JNICALL Java_org_libharu_Document_construct (JNIEnv *env, jobject obj) { haru_setup_error_handler(env, __func__); HPDF_Doc pdf = HPDF_New(haru_error_handler, NULL); set_HPDF_Doc(env, obj, pdf); if (pdf == NULL) haru_throw_exception("Failed to create new PDF document."); haru_clear_error_handler(); } JNIEXPORT void JNICALL Java_org_libharu_Document_destruct (JNIEnv *env, jobject obj) { haru_setup_error_handler(env, __func__); HPDF_Doc pdf = get_HPDF_Doc(env, obj); HPDF_Free(pdf); haru_clear_error_handler(); } JNIEXPORT void JNICALL Java_org_libharu_Document_setCompressionMode (JNIEnv *env, jobject obj, jobject compression) { haru_setup_error_handler(env, __func__); jclass CompressionMode = env->FindClass("org/libharu/Document$CompressionMode"); jmethodID getNameMethod = env->GetMethodID(CompressionMode, "name", "()Ljava/lang/String;"); jstring comp_value = (jstring)env->CallObjectMethod(compression, getNameMethod); const char* comp_str = env->GetStringUTFChars(comp_value, 0); HPDF_UINT mode; if (strcmp(comp_str, "COMP_NONE") == 0) mode = HPDF_COMP_NONE; else if (strcmp(comp_str, "COMP_TEXT") == 0) mode = HPDF_COMP_TEXT; else if (strcmp(comp_str, "COMP_IMAGE") == 0) mode = HPDF_COMP_IMAGE; else if (strcmp(comp_str, "COMP_METADATA") == 0) mode = HPDF_COMP_METADATA; else if (strcmp(comp_str, "COMP_ALL") == 0) mode = HPDF_COMP_ALL; else haru_throw_exception("Unknown compression mode."); HPDF_Doc pdf = get_HPDF_Doc(env, obj); HPDF_SetCompressionMode (pdf, mode); haru_clear_error_handler(); } JNIEXPORT void JNICALL Java_org_libharu_Document_setPassword (JNIEnv *env, jobject obj, jstring jownerpass, jstring juserpass) { haru_setup_error_handler(env, __func__); const char *ownerpass = (char*)env->GetStringUTFChars(jownerpass, NULL); if (ownerpass == NULL) return; const char *userpass = (char*)env->GetStringUTFChars(juserpass, NULL); if (userpass == NULL) return; HPDF_Doc pdf = get_HPDF_Doc(env, obj); HPDF_SetPassword(pdf, ownerpass, userpass); env->ReleaseStringUTFChars(jownerpass, ownerpass); env->ReleaseStringUTFChars(juserpass, userpass); haru_clear_error_handler(); } JNIEXPORT void JNICALL Java_org_libharu_Document_saveToFile (JNIEnv *env, jobject obj, jstring filename) { haru_setup_error_handler(env, __func__); const char *str = (char*)env->GetStringUTFChars(filename, NULL); if (str == NULL) return; HPDF_Doc pdf = get_HPDF_Doc(env, obj); HPDF_STATUS rc = HPDF_SaveToFile(pdf, str); env->ReleaseStringUTFChars(filename, str); if (rc == HPDF_OK) ; else if (rc == HPDF_INVALID_DOCUMENT) haru_throw_exception("An invalid document handle is set."); else if (rc == HPDF_FAILD_TO_ALLOC_MEM) haru_throw_exception("Memory allocation failed."); else if (rc == HPDF_FILE_IO_ERROR) haru_throw_exception("An error occurred while processing file I/O."); else haru_throw_exception("Unknown return code."); haru_clear_error_handler(); }
31.922414
94
0.746422
72212be3fd2dd2fadb93b6595d42cb3cfec9fad0
5,065
cpp
C++
util/qtColorScheme.cpp
Kitware/qtextensions
0ff5b486f08435c8cdfbc9f05d2f104f63b16aed
[ "BSD-3-Clause" ]
19
2015-12-17T14:48:11.000Z
2021-11-26T13:43:40.000Z
util/qtColorScheme.cpp
Kitware/qtextensions
0ff5b486f08435c8cdfbc9f05d2f104f63b16aed
[ "BSD-3-Clause" ]
26
2015-11-16T21:34:23.000Z
2021-01-29T13:41:21.000Z
util/qtColorScheme.cpp
Kitware/qtextensions
0ff5b486f08435c8cdfbc9f05d2f104f63b16aed
[ "BSD-3-Clause" ]
13
2015-11-10T02:44:47.000Z
2020-11-16T06:07:21.000Z
// This file is part of qtExtensions, and is distributed under the // OSI-approved BSD 3-Clause License. See top-level LICENSE file or // https://github.com/Kitware/qtExtensions/blob/master/LICENSE for details. #include "qtColorScheme.h" #include <QSettings> #define ARGS(x) QPalette::x, #x //----------------------------------------------------------------------------- qtColorScheme::qtColorScheme() { } //----------------------------------------------------------------------------- void qtColorScheme::load(const QSettings& settings) { this->load(ARGS(Active), settings); this->load(ARGS(Inactive), settings); this->load(ARGS(Disabled), settings); } //----------------------------------------------------------------------------- void qtColorScheme::load(QPalette::ColorGroup group, const QString& groupName, QSettings const& settings) { this->load(group, groupName, ARGS(Base), settings); this->load(group, groupName, ARGS(Text), settings); #if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) this->load(group, groupName, ARGS(PlaceholderText), settings); #endif this->load(group, groupName, ARGS(AlternateBase), settings); this->load(group, groupName, ARGS(Window), settings); this->load(group, groupName, ARGS(WindowText), settings); this->load(group, groupName, ARGS(Button), settings); this->load(group, groupName, ARGS(ButtonText), settings); this->load(group, groupName, ARGS(Highlight), settings); this->load(group, groupName, ARGS(HighlightedText), settings); this->load(group, groupName, ARGS(ToolTipBase), settings); this->load(group, groupName, ARGS(ToolTipText), settings); this->load(group, groupName, ARGS(Link), settings); this->load(group, groupName, ARGS(LinkVisited), settings); this->load(group, groupName, ARGS(BrightText), settings); this->load(group, groupName, ARGS(Light), settings); this->load(group, groupName, ARGS(Midlight), settings); this->load(group, groupName, ARGS(Mid), settings); this->load(group, groupName, ARGS(Dark), settings); this->load(group, groupName, ARGS(Shadow), settings); } //----------------------------------------------------------------------------- void qtColorScheme::load(QPalette::ColorGroup group, const QString& groupName, QPalette::ColorRole role, const QString& roleName, const QSettings& settings) { auto const& color = settings.value(this->key(groupName, roleName)); if (color.isValid()) { this->setColor(group, role, QColor{color.toString()}); } } //----------------------------------------------------------------------------- void qtColorScheme::save(QSettings& settings) const { this->save(ARGS(Active), settings); this->save(ARGS(Inactive), settings); this->save(ARGS(Disabled), settings); } //----------------------------------------------------------------------------- void qtColorScheme::save(QPalette::ColorGroup group, const QString& groupName, QSettings& settings) const { this->save(group, groupName, ARGS(Base), settings); this->save(group, groupName, ARGS(Text), settings); #if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) this->save(group, groupName, ARGS(PlaceholderText), settings); #endif this->save(group, groupName, ARGS(AlternateBase), settings); this->save(group, groupName, ARGS(Window), settings); this->save(group, groupName, ARGS(WindowText), settings); this->save(group, groupName, ARGS(Button), settings); this->save(group, groupName, ARGS(ButtonText), settings); this->save(group, groupName, ARGS(Highlight), settings); this->save(group, groupName, ARGS(HighlightedText), settings); this->save(group, groupName, ARGS(ToolTipBase), settings); this->save(group, groupName, ARGS(ToolTipText), settings); this->save(group, groupName, ARGS(Link), settings); this->save(group, groupName, ARGS(LinkVisited), settings); this->save(group, groupName, ARGS(BrightText), settings); this->save(group, groupName, ARGS(Light), settings); this->save(group, groupName, ARGS(Midlight), settings); this->save(group, groupName, ARGS(Mid), settings); this->save(group, groupName, ARGS(Dark), settings); this->save(group, groupName, ARGS(Shadow), settings); } //----------------------------------------------------------------------------- void qtColorScheme::save(QPalette::ColorGroup group, const QString& groupName, QPalette::ColorRole role, const QString& roleName, QSettings& settings) const { settings.setValue(this->key(groupName, roleName), this->color(group, role).name()); } //----------------------------------------------------------------------------- QString qtColorScheme::key(const QString& group, const QString& role) const { return QString{"%1/%2"}.arg(group, role); } //----------------------------------------------------------------------------- qtColorScheme qtColorScheme::fromSettings(const QSettings& settings) { qtColorScheme scheme; scheme.load(settings); return scheme; }
41.516393
79
0.603356
722310472f4f466485792343c31670010863c197
11,228
hpp
C++
tcob/include/tcob/core/Automation.hpp
TobiasBohnen/tcob
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
[ "MIT" ]
2
2021-08-18T19:14:35.000Z
2021-12-01T14:14:49.000Z
tcob/include/tcob/core/Automation.hpp
TobiasBohnen/tcob
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
[ "MIT" ]
null
null
null
tcob/include/tcob/core/Automation.hpp
TobiasBohnen/tcob
53092b3c8e657f1ff5e48ce961659edf7cb1cb05
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Tobias Bohnen // // This software is released under the MIT License. // https://opensource.org/licenses/MIT #pragma once #include <tcob/tcob_config.hpp> #include <concepts> #include <queue> #include <vector> #include <tcob/core/Random.hpp> #include <tcob/core/Signal.hpp> #include <tcob/core/Updatable.hpp> #include <tcob/core/data/Color.hpp> #include <tcob/core/data/Point.hpp> #include <tcob/gfx/Quad.hpp> namespace tcob { //////////////////////////////////////////////////////////// template <typename T> concept AutomationFunction = requires(T& t, f32 elapsedRatio) { typename T::type; { t.get_value(elapsedRatio) } -> std::same_as<typename T::type>; }; //////////////////////////////////////////////////////////// template <typename T> concept Interpolatable = requires(T& t, f32 elapsedRatio) { { t.get_interpolated(t, elapsedRatio) } -> std::same_as<T>; }; //////////////////////////////////////////////////////////// class AutomationBase : public Updatable { public: explicit AutomationBase(MilliSeconds duration); virtual ~AutomationBase() = default; void start(bool looped = false); void restart(); void toggle_pause(); void stop(); void set_interval(MilliSeconds interval); auto is_running() const -> bool; auto get_progress() const -> f32; void update(MilliSeconds deltaTime) override; private: virtual void update_values() = 0; bool _isRunning { false }; bool _looped { false }; MilliSeconds _duration { 0 }; MilliSeconds _elapsedTime { 0 }; MilliSeconds _interval { 0 }; MilliSeconds _currentInterval { 0 }; }; //////////////////////////////////////////////////////////// template <AutomationFunction Func> class Automation final : public AutomationBase { using func_type = typename Func::type; public: Automation(MilliSeconds duration, Func&& ptr) : AutomationBase { duration } , _function { std::move(ptr) } { } Signal<func_type> ValueChanged; auto add_output(func_type* dest) -> Connection { return ValueChanged.connect([dest](const func_type& val) { *dest = val; }); } auto get_value() const -> func_type { return _function.get_value(get_progress()); } private: void update_values() override { ValueChanged.emit(get_value()); } Func _function; }; template <typename Func, typename... Rs> auto make_unique_automation(MilliSeconds duration, Rs&&... args) -> std::unique_ptr<Automation<Func>> { return std::unique_ptr<Automation<Func>>(new Automation<Func> { duration, Func { std::forward<Rs>(args)... } }); } template <typename Func, typename... Rs> auto make_shared_automation(MilliSeconds duration, Rs&&... args) -> std::shared_ptr<Automation<Func>> { return std::shared_ptr<Automation<Func>>(new Automation<Func> { duration, Func { std::forward<Rs>(args)... } }); } //////////////////////////////////////////////////////////// class AutomationQueue final : public Updatable { public: template <typename... Ts> void push(Ts&&... autom) { (_queue.push(std::forward<Ts>(autom)), ...); } void start(bool looped = false); void stop_and_clear(); auto is_empty() const -> bool; void update(MilliSeconds deltaTime) override; private: std::queue<std::shared_ptr<AutomationBase>> _queue {}; bool _isRunning { false }; bool _looped { false }; }; /////////FUNCTIONS////////////////////////////////////////// template <typename T> class LinearFunctionChain final { public: using type = T; LinearFunctionChain(std::vector<T>&& elements) : _elements { std::move(elements) } { } auto get_value(f32 elapsedRatio) const -> T { if (_elements.empty()) { return T {}; } const isize size { _elements.size() - 1 }; const f32 relElapsed { size * elapsedRatio }; const isize index { static_cast<isize>(relElapsed) }; if (index >= size) { return _elements[index]; } else { const T& current { _elements[index] }; const T& next { _elements[index + 1] }; if constexpr (Interpolatable<T>) { return current.get_interpolated(next, relElapsed - index); } else { return current + ((next - current) * (relElapsed - index)); } } } private: std::vector<T> _elements {}; }; //////////////////////////////////////////////////////////// template <typename T> struct PowerFunction final { using type = T; T StartValue; T EndValue; f32 Exponent; auto get_value(f32 elapsedRatio) const -> T { if (Exponent <= 0 && elapsedRatio == 0) { return StartValue; } if constexpr (Interpolatable<T>) { return StartValue.get_interpolated(EndValue, std::pow(elapsedRatio, Exponent)); } else { return StartValue + ((EndValue - StartValue) * std::pow(elapsedRatio, Exponent)); } } }; //////////////////////////////////////////////////////////// template <typename T> struct InversePowerFunction final { using type = T; T StartValue; T EndValue; f32 Exponent; auto get_value(f32 elapsedRatio) const -> T { if (Exponent <= 0 && elapsedRatio == 0) { return StartValue; } if constexpr (Interpolatable<T>) { return StartValue.get_interpolated(EndValue, 1 - std::pow(1 - elapsedRatio, Exponent)); } else { return StartValue + ((EndValue - StartValue) * (1 - std::pow(1 - elapsedRatio, Exponent))); } } }; //////////////////////////////////////////////////////////// template <typename T> struct LinearFunction final { using type = T; T StartValue; T EndValue; auto get_value(f32 elapsedRatio) const -> T { if (elapsedRatio == 0) { return StartValue; } if constexpr (Interpolatable<T>) { return StartValue.get_interpolated(EndValue, elapsedRatio); } else { return StartValue + ((EndValue - StartValue) * elapsedRatio); } } }; //////////////////////////////////////////////////////////// template <typename T> struct SmoothstepFunction final { using type = T; T Edge0; T Edge1; auto get_value(f32 elapsedRatio) const -> T { if (elapsedRatio == 0) { return Edge0; } f32 e { elapsedRatio * elapsedRatio * (3.f - 2.f * elapsedRatio) }; if constexpr (Interpolatable<T>) { return Edge0.get_interpolated(Edge1, e); } else { return Edge0 + ((Edge1 - Edge0) * e); } } }; //////////////////////////////////////////////////////////// template <typename T> struct SmootherstepFunction final { using type = T; T Edge0; T Edge1; auto get_value(f32 elapsedRatio) const -> T { if (elapsedRatio == 0) { return Edge0; } f32 e { elapsedRatio * elapsedRatio * elapsedRatio * (elapsedRatio * (elapsedRatio * 6 - 15) + 10) }; if constexpr (Interpolatable<T>) { return Edge0.get_interpolated(Edge1, e); } else { return Edge0 + ((Edge1 - Edge0) * e); } } }; //////////////////////////////////////////////////////////// template <typename T> struct SineWaveFunction final { using type = T; T MinValue; T MaxValue; f32 Frequency; f32 Phase; auto get_value(f32 elapsedRatio) const -> T { const f64 val { get_wavevalue((Frequency * elapsedRatio)) }; if constexpr (Interpolatable<T>) { return MinValue.get_interpolated(MaxValue, val); } else { return MinValue + ((MaxValue - MinValue) * val); } } private: auto get_wavevalue(f64 time) const -> f64 { return (std::sin((TAU * time) + (0.75 * TAU) + Phase) + 1) / 2; } }; //////////////////////////////////////////////////////////// template <typename T> struct TriangeWaveFunction final { using type = T; T MinValue; T MaxValue; f32 Frequency; f32 Phase; auto get_value(f32 elapsedRatio) const -> T { const f64 val { get_wavevalue((Frequency * elapsedRatio) + Phase) }; if constexpr (Interpolatable<T>) { return MinValue.get_interpolated(MaxValue, val); } else { return MinValue + ((MaxValue - MinValue) * val); } } private: auto get_wavevalue(f64 time) const -> f64 { return 2 * std::abs(std::round(time) - time); } }; //////////////////////////////////////////////////////////// template <typename T> struct SquareWaveFunction final { using type = T; T MinValue; T MaxValue; f32 Frequency; f32 Phase; auto get_value(f32 elapsedRatio) const -> T { const f64 val { get_wavevalue((Frequency * elapsedRatio)) }; if constexpr (Interpolatable<T>) { return MinValue.get_interpolated(MaxValue, val); } else { return MinValue + ((MaxValue - MinValue) * val); } } private: auto get_wavevalue(f64 time) const -> f64 { const f64 x { std::round(time + Phase) / 2 }; return 2 * (x - std::floor(x)); } }; //////////////////////////////////////////////////////////// template <typename T> struct SawtoothWaveFunction final { using type = T; T MinValue; T MaxValue; f32 Frequency; f32 Phase; auto get_value(f32 elapsedRatio) const -> T { const f64 val { get_wavevalue((Frequency * elapsedRatio) + Phase) }; if constexpr (Interpolatable<T>) { return MinValue.get_interpolated(MaxValue, val); } else { return MinValue + ((MaxValue - MinValue) * val); } } private: auto get_wavevalue(f64 time) const -> f64 { return time - std::floor(time); } }; //////////////////////////////////////////////////////////// struct CubicBezierFunction final { using type = PointF; PointF Start; PointF ControlPoint0; PointF ControlPoint1; PointF End; auto get_value(f32 elapsedRatio) const -> PointF { const PointF a { get_point_in_line(Start, ControlPoint0, elapsedRatio) }; const PointF b { get_point_in_line(ControlPoint0, ControlPoint1, elapsedRatio) }; const PointF c { get_point_in_line(ControlPoint1, End, elapsedRatio) }; return get_point_in_line(get_point_in_line(a, b, elapsedRatio), get_point_in_line(b, c, elapsedRatio), elapsedRatio); } private: auto get_point_in_line(const PointF& a, const PointF& b, f32 t) const -> PointF { return { a.X - ((a.X - b.X) * t), a.Y - ((a.Y - b.Y) * t) }; } }; //////////////////////////////////////////////////////////// template <typename T> struct RandomFunction final { using type = T; T MinValue; T MaxValue; mutable Random RNG; auto get_value(f32 elapsedRatio) const -> T { return RNG(MinValue, MaxValue); } }; }
24.408696
125
0.546491
722453a47a24987fd1452538469992a1e5025906
1,288
cpp
C++
ewk/unittest/utc_blink_ewk_context_proxy_uri_set_func.cpp
Jabawack/chromium-efl
6d3a3accc8afba0aa0eff6461eb5c83138172e6e
[ "BSD-3-Clause" ]
9
2015-04-09T20:22:08.000Z
2021-03-17T08:34:56.000Z
ewk/unittest/utc_blink_ewk_context_proxy_uri_set_func.cpp
Jabawack/chromium-efl
6d3a3accc8afba0aa0eff6461eb5c83138172e6e
[ "BSD-3-Clause" ]
2
2015-02-04T13:41:12.000Z
2015-05-25T14:00:40.000Z
ewk/unittest/utc_blink_ewk_context_proxy_uri_set_func.cpp
isabella232/chromium-efl
db2d09aba6498fb09bbea1f8440d071c4b0fde78
[ "BSD-3-Clause" ]
14
2015-02-12T16:20:47.000Z
2022-01-20T10:36:26.000Z
// Copyright 2014 Samsung Electronics. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "utc_blink_ewk_base.h" class utc_blink_ewk_context_proxy_uri_set : public utc_blink_ewk_base { protected: static const char*const url; }; const char*const utc_blink_ewk_context_proxy_uri_set::url="http://proxy.tc.url"; /** * @brief Positive TC for ewk_context_proxy_uri_set() */ TEST_F(utc_blink_ewk_context_proxy_uri_set, POS_TEST) { /* TODO: this code should use ewk_context_proxy_uri_set and check its behaviour. Results should be reported using one of utc_ macros */ Ewk_Context* defaultContext = ewk_context_default_get(); if (!defaultContext) utc_fail(); ewk_context_proxy_uri_set(defaultContext, url); utc_check_str_eq(ewk_context_proxy_uri_get(defaultContext), url); } /** * @brief Negative TC for ewk_context_proxy_uri_set() */ TEST_F(utc_blink_ewk_context_proxy_uri_set, NEG_TEST) { /* TODO: this code should use ewk_context_proxy_uri_set and check its behaviour. Results should be reported using one of utc_ macros */ Ewk_Context* defaultContext = ewk_context_default_get(); if (!defaultContext) utc_fail(); ewk_context_proxy_uri_set(NULL, NULL); utc_pass(); }
30.666667
82
0.776398
7228c338c7a4d565cdda960c9153395a6e053ef3
4,554
cpp
C++
DHT_U.cpp
bert386/esp32-pellet-hmi
17e389632defb51dbc42cb2eef968fdc74a39477
[ "Apache-2.0" ]
1
2021-03-03T05:35:43.000Z
2021-03-03T05:35:43.000Z
DHT_U.cpp
bert386/esp32-pellet-hmi
17e389632defb51dbc42cb2eef968fdc74a39477
[ "Apache-2.0" ]
null
null
null
DHT_U.cpp
bert386/esp32-pellet-hmi
17e389632defb51dbc42cb2eef968fdc74a39477
[ "Apache-2.0" ]
null
null
null
#include "DHT_U.h" DHT_Unified::DHT_Unified(uint8_t pin, uint8_t type, uint8_t count, int32_t tempSensorId, int32_t humiditySensorId): _dht(pin, type, count), _type(type), _temp(this, tempSensorId), _humidity(this, humiditySensorId) {} void DHT_Unified::begin() { _dht.begin(); } void DHT_Unified::setName(sensor_t* sensor) { switch(_type) { case DHT11: strncpy(sensor->name, "DHT11", sizeof(sensor->name) - 1); break; case DHT21: strncpy(sensor->name, "DHT21", sizeof(sensor->name) - 1); break; case DHT22: strncpy(sensor->name, "DHT22", sizeof(sensor->name) - 1); break; default: // TODO: Perhaps this should be an error? However main DHT library doesn't enforce // restrictions on the sensor type value. Pick a generic name for now. strncpy(sensor->name, "DHT?", sizeof(sensor->name) - 1); break; } sensor->name[sizeof(sensor->name)- 1] = 0; } void DHT_Unified::setMinDelay(sensor_t* sensor) { switch(_type) { case DHT11: sensor->min_delay = 1000000L; // 1 second (in microseconds) break; case DHT21: sensor->min_delay = 2000000L; // 2 seconds (in microseconds) break; case DHT22: sensor->min_delay = 2000000L; // 2 seconds (in microseconds) break; default: // Default to slowest sample rate in case of unknown type. sensor->min_delay = 2000000L; // 2 seconds (in microseconds) break; } } DHT_Unified::Temperature::Temperature(DHT_Unified* parent, int32_t id): _parent(parent), _id(id) {} bool DHT_Unified::Temperature::getEvent(sensors_event_t* event) { // Clear event definition. memset(event, 0, sizeof(sensors_event_t)); // Populate sensor reading values. event->version = sizeof(sensors_event_t); event->sensor_id = _id; event->type = SENSOR_TYPE_AMBIENT_TEMPERATURE; event->timestamp = millis(); event->temperature = _parent->_dht.readTemperature(); return true; } void DHT_Unified::Temperature::getSensor(sensor_t* sensor) { // Clear sensor definition. memset(sensor, 0, sizeof(sensor_t)); // Set sensor name. _parent->setName(sensor); // Set version and ID sensor->version = DHT_SENSOR_VERSION; sensor->sensor_id = _id; // Set type and characteristics. sensor->type = SENSOR_TYPE_AMBIENT_TEMPERATURE; _parent->setMinDelay(sensor); switch (_parent->_type) { case DHT11: sensor->max_value = 50.0F; sensor->min_value = 0.0F; sensor->resolution = 2.0F; break; case DHT21: sensor->max_value = 80.0F; sensor->min_value = -40.0F; sensor->resolution = 0.1F; break; case DHT22: sensor->max_value = 125.0F; sensor->min_value = -40.0F; sensor->resolution = 0.1F; break; default: // Unknown type, default to 0. sensor->max_value = 0.0F; sensor->min_value = 0.0F; sensor->resolution = 0.0F; break; } } DHT_Unified::Humidity::Humidity(DHT_Unified* parent, int32_t id): _parent(parent), _id(id) {} bool DHT_Unified::Humidity::getEvent(sensors_event_t* event) { // Clear event definition. memset(event, 0, sizeof(sensors_event_t)); // Populate sensor reading values. event->version = sizeof(sensors_event_t); event->sensor_id = _id; event->type = SENSOR_TYPE_RELATIVE_HUMIDITY; event->timestamp = millis(); event->relative_humidity = _parent->_dht.readHumidity(); return true; } void DHT_Unified::Humidity::getSensor(sensor_t* sensor) { // Clear sensor definition. memset(sensor, 0, sizeof(sensor_t)); // Set sensor name. _parent->setName(sensor); // Set version and ID sensor->version = DHT_SENSOR_VERSION; sensor->sensor_id = _id; // Set type and characteristics. sensor->type = SENSOR_TYPE_RELATIVE_HUMIDITY; _parent->setMinDelay(sensor); switch (_parent->_type) { case DHT11: sensor->max_value = 80.0F; sensor->min_value = 20.0F; sensor->resolution = 5.0F; break; case DHT21: sensor->max_value = 100.0F; sensor->min_value = 0.0F; sensor->resolution = 0.1F; break; case DHT22: sensor->max_value = 100.0F; sensor->min_value = 0.0F; sensor->resolution = 0.1F; break; default: // Unknown type, default to 0. sensor->max_value = 0.0F; sensor->min_value = 0.0F; sensor->resolution = 0.0F; break; } }
28.4625
115
0.63307
7229d3675fd07fda77dd0738036f04243218b3cb
1,625
cpp
C++
concept_tests/drivers/freertos_driver.cpp
jedrzejboczar/ubik-micromouse
6470368de0c3207fc278bcfa604d1fdd74aaeb8f
[ "MIT" ]
3
2019-10-30T07:37:47.000Z
2021-01-21T11:50:20.000Z
concept_tests/drivers/freertos_driver.cpp
jedrzejboczar/ubik-micromouse
6470368de0c3207fc278bcfa604d1fdd74aaeb8f
[ "MIT" ]
null
null
null
concept_tests/drivers/freertos_driver.cpp
jedrzejboczar/ubik-micromouse
6470368de0c3207fc278bcfa604d1fdd74aaeb8f
[ "MIT" ]
null
null
null
#include "freertos_driver.h" // void FreeRTOSDriverTask::task() { // run(); // } FreeRTOSDriverTask::FreeRTOSDriverTask( const char * name, int priority, int stack_depth, size_t request_queue_length, TickType_t timeout): FreeRTOSTask(name, priority, stack_depth), request_queue_length(request_queue_length), timeout(timeout), runner(nullptr) { } QueueHandle_t FreeRTOSDriverTask::create_queue( size_t queue_length, size_t data_size) { return xQueueCreate(queue_length, data_size); } void FreeRTOSDriverTask::create_request_queue(size_t data_size) { request_queue = create_queue(request_queue_length, data_size); configASSERT(request_queue); } bool FreeRTOSDriverTask::receive_request(void *into_buffer) { BaseType_t result = xQueueReceive(request_queue, into_buffer, portMAX_DELAY); // TODO: how to specify the delay!!! return result == pdTRUE; } bool FreeRTOSDriverTask::wait_for_isr() { uint32_t notification_value = ulTaskNotifyTake(pdTRUE, portMAX_DELAY); // TODO: how to specify the delay!!! return notification_value != 0; } void FreeRTOSDriverTask::send_response(QueueHandle_t response_queue, const void *from_buffer) { BaseType_t result = xQueueSend(response_queue, from_buffer, portMAX_DELAY); // TODO: how to specify the delay!!! (void) result; // the driver doesn't care, we could try multiple times if needed } void FreeRTOSDriverTask::set_task_runner(TaskRunner *runner) { this->runner = runner; } void FreeRTOSDriverTask::task() { configASSERT(runner != nullptr); runner->run(); }
31.25
95
0.729231
722e215ab9d583c68b4b931841d7e1501fc8ff49
1,453
cpp
C++
algorithms/KthSmallestElementinaBST/tree.cpp
PikachuPikachuHAHA/leetcode-2
4cf8d30509f4b994b1845765807380eeffb95c73
[ "MIT" ]
93
2016-04-27T23:25:27.000Z
2021-07-13T20:32:25.000Z
algorithms/KthSmallestElementinaBST/tree.cpp
shangan/leetcode
db05338f8057ad440cb5dd6cfe0151aafb7a8d56
[ "MIT" ]
null
null
null
algorithms/KthSmallestElementinaBST/tree.cpp
shangan/leetcode
db05338f8057ad440cb5dd6cfe0151aafb7a8d56
[ "MIT" ]
43
2016-05-31T15:46:50.000Z
2021-04-09T04:07:39.000Z
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <cstdio> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(nullptr), right(nullptr){} }; class Solution { public: int kthSmallest(TreeNode *root, int k) { int result; /* if (root == nullptr) { return 0; } */ kthSmallest(root, k, result); return result; } private: bool kthSmallest(TreeNode *root, int &k, int &result) { if (root->left) { if (kthSmallest(root->left, k, result)) { return true; } } k -= 1; if (k == 0) { result = root->val; return true; } if (root->right) { if (kthSmallest(root->right, k, result)) { return true; } } return false; } }; TreeNode *mk_node(int val) { return new TreeNode(val); } TreeNode *mk_child(TreeNode *root, TreeNode *left, TreeNode *right) { root->left = left; root->right = right; return root; } TreeNode *mk_child(TreeNode *root, int left, int right) { return mk_child(root, new TreeNode(left), new TreeNode(right)); } TreeNode *mk_child(int root, int left, int right) { return mk_child(new TreeNode(root), new TreeNode(left), new TreeNode(right)); } int main(int argc, char **argv) { Solution solution; TreeNode *root = mk_child(6, 4, 8); mk_child(root->left, 3, 5); mk_child(root->right, 7, 9); for (int i = 1; i <= 7; ++i) printf("%d\n", solution.kthSmallest(root, i)); return 0; }
19.90411
78
0.644184
7236a5e16e768f9e870eab43fe93378f499bac48
985
cpp
C++
System/GroundMissionControl.cpp
MatthewGotte/214_project_Derived
48a74a10bc4fd5b01d11d1f89a7203a5b070b9bd
[ "MIT" ]
null
null
null
System/GroundMissionControl.cpp
MatthewGotte/214_project_Derived
48a74a10bc4fd5b01d11d1f89a7203a5b070b9bd
[ "MIT" ]
null
null
null
System/GroundMissionControl.cpp
MatthewGotte/214_project_Derived
48a74a10bc4fd5b01d11d1f89a7203a5b070b9bd
[ "MIT" ]
null
null
null
#include "GroundMissionControl.h" #include "Satellite.h" GroundMissionControl::GroundMissionControl() { } void GroundMissionControl::attach(Satellite* addSatellite) { this->satelliteList.push_back(addSatellite); } void GroundMissionControl::detach(Satellite* removeSatellite) { vector<Satellite*>::iterator it; for (it = this->satelliteList.begin(); it != this->satelliteList.end(); ++it) { if (*it == removeSatellite && *it != nullptr) { this->satelliteList.erase(it); } } } void GroundMissionControl::notify() { vector<Satellite*>::iterator it; for (it = this->satelliteList.begin(); it != this->satelliteList.end(); ++it) { (*it)->update(); } } GroundMissionControl::~GroundMissionControl() { vector<Satellite*>::iterator it; for (it = this->satelliteList.begin(); it != this->satelliteList.end(); ++it) { delete *it; } }
24.625
84
0.603046
723825c6ae045d3688616d4d86c65a960f8057ce
4,609
cpp
C++
test/graphic/sphere_transparent_test.cpp
mpinto70/raytracing
5e3a46257b74a3df1b91fb066d7763b50273bf83
[ "MIT" ]
null
null
null
test/graphic/sphere_transparent_test.cpp
mpinto70/raytracing
5e3a46257b74a3df1b91fb066d7763b50273bf83
[ "MIT" ]
null
null
null
test/graphic/sphere_transparent_test.cpp
mpinto70/raytracing
5e3a46257b74a3df1b91fb066d7763b50273bf83
[ "MIT" ]
null
null
null
#include "graphic/sphere_transparent.h" #include <gtest/gtest.h> namespace graphic { using geometry::vec3d; TEST(sphere_transparent, creation) { constexpr vec3d C1{ 7, 8, 9 }; constexpr dim_t R1 = 5.0f; const sphere_transparent S1{ C1, R1, 1.458, 0.1, 0.2, 0.3 }; constexpr vec3d C2{ -2, 3, 10 }; constexpr dim_t R2 = 3.4f; const sphere_transparent S2{ C2, R2, 1.458, 0.4, 0.5, 0.7 }; EXPECT_EQ(S1.center(), C1); EXPECT_EQ(S1.radius(), R1); EXPECT_EQ(S1.dim_r(), dim_t(0.1)); EXPECT_EQ(S1.dim_g(), dim_t(0.2)); EXPECT_EQ(S1.dim_b(), dim_t(0.3)); EXPECT_EQ(S2.center(), C2); EXPECT_EQ(S2.radius(), R2); EXPECT_EQ(S2.dim_r(), dim_t(0.4)); EXPECT_EQ(S2.dim_g(), dim_t(0.5)); EXPECT_EQ(S2.dim_b(), dim_t(0.7)); } TEST(sphere_transparent, hit_simple_and_direct) { hit_record record{}; constexpr vec3d C{ 0, 0, -30 }; constexpr dim_t R = 5.0f; const ray r{ { 0, 0, 0 }, { 0, 0, -1 } }; const sphere_transparent s(C, R, 1.458, 0.1, 0.2, 0.3); constexpr vec3d hit_point{ 0, 0, -25 }; constexpr vec3d normal{ 0, 0, 1 }; EXPECT_TRUE(s.hit(r, 0.0, 500, record)); EXPECT_EQ(record.t, 25.0f); EXPECT_EQ(record.p, hit_point); EXPECT_EQ(record.normal, normal); } TEST(sphere_transparent, hit_out_of_range) { hit_record record{}; constexpr vec3d C{ 0, 0, -30 }; constexpr dim_t R = 5.0f; const ray r{ { 0, 0, 0 }, { 0, 0, -1 } }; const sphere_transparent s(C, R, 1.458, 0.1, 0.2, 0.3); EXPECT_FALSE(s.hit(r, 35.5f, 500, record)); } TEST(sphere_transparent, bounce_front_middle) { constexpr vec3d C{ 0, 0, -30 }; constexpr dim_t R = 5.0f; const ray r1{ { 0, 0, 0 }, { 0, 0, -1 } }; const sphere_transparent s(C, R, 1.458, 0.9, 0.9, 0.9); hit_record record; ASSERT_TRUE(s.hit(r1, 0.001, 1500000, record)); const auto r2 = s.bounce(r1, record); ASSERT_TRUE(r2); constexpr vec3d hit_p1{ 0, 0, -25 }; constexpr vec3d dir_p1{ 0, 0, -1 }; EXPECT_EQ(r2->origin(), hit_p1); EXPECT_EQ(r2->direction(), dir_p1); ASSERT_TRUE(s.hit(*r2, 0.001, 1500000, record)); const auto r3 = s.bounce(r1, record); ASSERT_TRUE(r3); constexpr vec3d hit_p2{ 0, 0, -35 }; constexpr vec3d dir_p2{ 0, 0, -1 }; EXPECT_EQ(r3->origin(), hit_p2); EXPECT_EQ(r3->direction(), dir_p2); } TEST(sphere_transparent, bounce_off_center) { constexpr vec3d C{ 0, 0, -30 }; constexpr dim_t R = 5.0f; const ray r1{ { 1, 1, 0 }, { 0, 0, -1 } }; const sphere_transparent s(C, R, 1.458, 0.9, 0.9, 0.9); hit_record record; ASSERT_TRUE(s.hit(r1, 0.001, 1500000, record)); const auto r2 = s.bounce(r1, record); ASSERT_TRUE(r2); constexpr vec3d hit_p1{ 1, 1, -25.204168 }; constexpr vec3d normal_p1{ 0.19999998, 0.19999998, 0.9591663 }; constexpr vec3d dir_p1{ -6.462767e-2, -6.462767e-2, -0.9958145 }; EXPECT_FLOAT_EQ(record.normal.x, normal_p1.x); EXPECT_FLOAT_EQ(record.normal.y, normal_p1.y); EXPECT_FLOAT_EQ(record.normal.z, normal_p1.z); EXPECT_FLOAT_EQ(r2->origin().x, hit_p1.x); EXPECT_FLOAT_EQ(r2->origin().y, hit_p1.y); EXPECT_FLOAT_EQ(r2->origin().z, hit_p1.z); EXPECT_FLOAT_EQ(r2->direction().x, dir_p1.x); EXPECT_FLOAT_EQ(r2->direction().y, dir_p1.y); EXPECT_FLOAT_EQ(r2->direction().z, dir_p1.z); ASSERT_TRUE(s.hit(*r2, 0.001, 1500000, record)); const auto r3 = s.bounce(*r2, record); ASSERT_TRUE(r3); constexpr vec3d hit_p2{ 0.366000692813, 0.366000692813, -34.9731369937 }; constexpr vec3d normal_p2{ 7.32001318686e-2, 7.32001318686e-2, -0.994627307783 }; constexpr vec3d dir_p2{ -0.128714342822, -0.128714342822, -0.983293056984 }; EXPECT_FLOAT_EQ(r3->origin().x, hit_p2.x); EXPECT_FLOAT_EQ(r3->origin().y, hit_p2.y); EXPECT_FLOAT_EQ(r3->origin().z, hit_p2.z); EXPECT_FLOAT_EQ(record.normal.x, normal_p2.x); EXPECT_FLOAT_EQ(record.normal.y, normal_p2.y); EXPECT_FLOAT_EQ(record.normal.z, normal_p2.z); EXPECT_FLOAT_EQ(r3->direction().x, dir_p2.x); EXPECT_FLOAT_EQ(r3->direction().y, dir_p2.y); EXPECT_FLOAT_EQ(r3->direction().z, dir_p2.z); } TEST(sphere_transparent, dim) { constexpr vec3d C{ 0, 0, -30 }; constexpr dim_t R = 5.0f; const ray r{ { 0, 0, 0 }, { -7, -2, -1 } }; const sphere_transparent s(C, R, 1.458, 0.1, 0.2, 0.3); auto out_color = s.dim(color{ 234, 123, 210 }); constexpr color expected_color = { 23, 24, 63 }; EXPECT_EQ(out_color.r, expected_color.r); EXPECT_EQ(out_color.g, expected_color.g); EXPECT_EQ(out_color.b, expected_color.b); } }
34.395522
85
0.635713
5cfb300c5618be540e9dab1268bc36675010d39a
2,624
cpp
C++
homomorphic_evaluation/ntl-11.3.2/src/Poly3TimeTest.cpp
dklee0501/PLDI_20_242_artifact_publication
f2b73df9165c76e8b521d8ebd639d68321e3862b
[ "MIT" ]
160
2016-05-11T09:45:56.000Z
2022-03-06T09:32:19.000Z
homomorphic_evaluation/ntl-11.3.2/src/Poly3TimeTest.cpp
dklee0501/Lobster
f2b73df9165c76e8b521d8ebd639d68321e3862b
[ "MIT" ]
57
2016-12-26T07:02:12.000Z
2022-03-06T16:34:31.000Z
homomorphic_evaluation/ntl-11.3.2/src/Poly3TimeTest.cpp
dklee0501/Lobster
f2b73df9165c76e8b521d8ebd639d68321e3862b
[ "MIT" ]
67
2016-10-10T17:56:22.000Z
2022-03-15T22:56:39.000Z
#include <NTL/ZZ_pX.h> #include <cstdio> NTL_CLIENT double clean_data(double *t) { double x, y, z; long i, ix, iy, n; x = t[0]; ix = 0; y = t[0]; iy = 0; for (i = 1; i < 5; i++) { if (t[i] < x) { x = t[i]; ix = i; } if (t[i] > y) { y = t[i]; iy = i; } } z = 0; n = 0; for (i = 0; i < 5; i++) { if (i != ix && i != iy) z+= t[i], n++; } z = z/n; return z; } void print_flag() { #if (defined(NTL_CRT_ALTCODE)) printf("CRT_ALTCODE "); #else printf("DEFAULT "); #endif printf("\n"); } int main() { SetSeed(ZZ(0)); long n, k; n = 1024; k = 30*NTL_SP_NBITS; ZZ p; RandomLen(p, k); if (!IsOdd(p)) p++; ZZ_p::init(p); // initialization ZZ_pX f, g, h, r1, r2, r3; random(g, n); // g = random polynomial of degree < n random(h, n); // h = " " random(f, n); // f = " " SetCoeff(f, n); // Sets coefficient of X^n to 1 // For doing arithmetic mod f quickly, one must pre-compute // some information. ZZ_pXModulus F; build(F, f); PlainMul(r1, g, h); // this uses classical arithmetic PlainRem(r1, r1, f); MulMod(r2, g, h, F); // this uses the FFT MulMod(r3, g, h, f); // uses FFT, but slower // compare the results... if (r1 != r2) { printf("999999999999999 "); print_flag(); return 0; } else if (r1 != r3) { printf("999999999999999 "); print_flag(); return 0; } double t; long i; long iter; ZZ_pX a, b, c; random(a, n); random(b, n); long da = deg(a); long db = deg(b); long dc = da + db; long l = NextPowerOfTwo(dc+1); FFTRep arep, brep, crep; ToFFTRep(arep, a, l, 0, da); ToFFTRep(brep, b, l, 0, db); mul(crep, arep, brep); ZZ_pXModRep modrep; FromFFTRep(modrep, crep); FromZZ_pXModRep(c, modrep, 0, dc); iter = 1; do { t = GetTime(); for (i = 0; i < iter; i++) { FromZZ_pXModRep(c, modrep, 0, dc); } t = GetTime() - t; iter = 2*iter; } while(t < 1); iter = iter/2; iter = long((3/t)*iter) + 1; double tvec[5]; long w; for (w = 0; w < 5; w++) { t = GetTime(); for (i = 0; i < iter; i++) { FromZZ_pXModRep(c, modrep, 0, dc); } t = GetTime() - t; tvec[w] = t; } t = clean_data(tvec); t = floor((t/iter)*1e12); if (t < 0 || t >= 1e15) printf("999999999999999 "); else printf("%015.0f ", t); printf(" [%ld] ", iter); print_flag(); return 0; }
15.255814
62
0.470655
5cfd9b6935f140e9eca09aeef566fb9c6424ab7f
1,120
cpp
C++
examples/week01/numbers/sizeof.cpp
DaveParillo/cisc187-docker
872c0dba7d79d2e5c7c0269a8b75045c6f2bc229
[ "MIT" ]
null
null
null
examples/week01/numbers/sizeof.cpp
DaveParillo/cisc187-docker
872c0dba7d79d2e5c7c0269a8b75045c6f2bc229
[ "MIT" ]
null
null
null
examples/week01/numbers/sizeof.cpp
DaveParillo/cisc187-docker
872c0dba7d79d2e5c7c0269a8b75045c6f2bc229
[ "MIT" ]
null
null
null
#include <iostream> #include <string> int main() { char c = 'a'; std::cout << "size of char: " << sizeof(c) << '\n' << "size of int: " << sizeof(int) << '\n' << "size of double: " << sizeof(double) << '\n' << "size of pointer: " << sizeof(&c) << std::endl; double foo[10] = {0.1, 3.14159, 1e1, 2e-6, 5, 6, 7, 8, 9, 10}; std::cout << "size of foo[]: " << sizeof(foo) << '\n' << "no. of elements in foo[]: " << sizeof(foo) / sizeof(foo[0]) << std::endl; std::string bar[10] = { "hi", "hello world!", "it doesn't actually matter how long these strings are as far as the array is concerned. What is stored is only a reference to the string in memory" }; std::cout << "size of bar[]: " << sizeof(bar) << '\n' << "size of &bar: " << sizeof(&bar) << '\n' << "size of *bar: " << sizeof(*bar) << '\n' << "size of bar[0]: " << sizeof(bar[0]) << '\n' << "size of bar[2]: " << sizeof(bar[2]) << '\n' << "no. of elements in bar[]: " << sizeof(bar) / sizeof(bar[0]) << std::endl; }
46.666667
178
0.473214
5cfeffcb3608cdbcd3725189563c08e85ff27ae1
9,461
cpp
C++
src/test-apps/weave-connection-tunnel.cpp
aiw-google/openweave-core
5dfb14b21d0898ef95bb62ff564cadfeea4b4702
[ "Apache-2.0" ]
1
2021-08-10T12:08:31.000Z
2021-08-10T12:08:31.000Z
src/test-apps/weave-connection-tunnel.cpp
aiw-google/openweave-core
5dfb14b21d0898ef95bb62ff564cadfeea4b4702
[ "Apache-2.0" ]
null
null
null
src/test-apps/weave-connection-tunnel.cpp
aiw-google/openweave-core
5dfb14b21d0898ef95bb62ff564cadfeea4b4702
[ "Apache-2.0" ]
1
2020-06-15T01:50:59.000Z
2020-06-15T01:50:59.000Z
/* * * Copyright (c) 2016-2017 Nest Labs, Inc. * 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. */ /** * @file * This file aims to test the WeaveConnectionTunnel functionality, three kinds of nodes: * - ConnectionTunnelAgent: create connections to Tunnel Source and Destination, establish tunnel between them * - ConnectionTunnelSource: wait for connection from Tunnel Agent, act as sender to verify tunnel link * - ConnectionTunnelDestination: wait for connection from Tunnel Agent, act as receiver to verify tunnel link * */ #define __STDC_FORMAT_MACROS #define __STDC_LIMIT_MACROS #include <inttypes.h> #include "ToolCommon.h" #define TOOL_NAME "weave-connection-tunnel" enum { ConnectionTunnelAgent = 0, ConnectionTunnelSource, ConnectionTunnelDest, }; static bool HandleOption(const char *progName, OptionSet *optSet, int id, const char *name, const char *arg); static bool HandleNonOptionArgs(const char *progName, int argc, char *argv[]); static void StartConnections(); static void DriveSending(); static void HandleConnectionReceived(WeaveMessageLayer *msgLayer, WeaveConnection *con); static void HandleConnectionComplete(WeaveConnection *con, WEAVE_ERROR conErr); static void HandleMessageReceived(WeaveConnection *con, WeaveMessageInfo *msgInfo, PacketBuffer *msgBuf); uint8_t Role = ConnectionTunnelAgent; WeaveConnectionTunnel *tun = NULL; WeaveConnection *conSource = NULL; WeaveConnection *conDest = NULL; WeaveConnection *connection = NULL; uint64_t TunnelSourceNodeId; uint64_t TunnelDestNodeId; IPAddress TunnelSourceAddr = IPAddress::Any; IPAddress TunnelDestAddr = IPAddress::Any; static OptionDef gToolOptionDefs[] = { { "tunnel-source", kNoArgument, 'S' }, { "tunnel-destination", kNoArgument, 'D' }, { "tunnel-agent", kNoArgument, 'A' }, { NULL } }; static const char *const gToolOptionHelp = " -S, --tunnel-source\n" " Specify the node as tunnel source, act as sender to vefify tunnel link\n" "\n" " -D, --tunnel-destination\n" " Specify the node as tunnel destination, act as receiver to vefify tunnel link\n" "\n" " -A, --tunnel-agent\n" " Specify the node as tunnel agent, establish connection tunnel between source node and destination node\n" "\n"; static OptionSet gToolOptions = { HandleOption, gToolOptionDefs, "GENERAL OPTIONS", gToolOptionHelp }; static HelpOptions gHelpOptions( TOOL_NAME, "Usage: " TOOL_NAME " [<options...>] --tunnel-source\n" " " TOOL_NAME " [<options...>] --tunnel-destination\n" " " TOOL_NAME " [<options...>] --tunnel-agent <source-node-id> <dest-node-id>\n", WEAVE_VERSION_STRING "\n" WEAVE_TOOL_COPYRIGHT ); static OptionSet *gToolOptionSets[] = { &gToolOptions, &gNetworkOptions, &gWeaveNodeOptions, &gFaultInjectionOptions, &gHelpOptions, NULL }; int main(int argc, char *argv[]) { InitToolCommon(); SetSIGUSR1Handler(); if (argc == 1) { gHelpOptions.PrintBriefUsage(stderr); exit(EXIT_FAILURE); } if (!ParseArgsFromEnvVar(TOOL_NAME, TOOL_OPTIONS_ENV_VAR_NAME, gToolOptionSets, NULL, true) || !ParseArgs(TOOL_NAME, argc, argv, gToolOptionSets, HandleNonOptionArgs) || !ResolveWeaveNetworkOptions(TOOL_NAME, gWeaveNodeOptions, gNetworkOptions)) { exit(EXIT_FAILURE); } InitSystemLayer(); InitNetwork(); InitWeaveStack(true, false); MessageLayer.OnConnectionReceived = HandleConnectionReceived; PrintNodeConfig(); // Tunnel Agent: create connections to Tunnel Source and Destination if (Role == ConnectionTunnelAgent) StartConnections(); while (!Done) { struct timeval sleepTime; sleepTime.tv_sec = 0; sleepTime.tv_usec = 100000; ServiceNetwork(sleepTime); if (Role == ConnectionTunnelSource) DriveSending(); } ShutdownWeaveStack(); ShutdownNetwork(); ShutdownSystemLayer(); return EXIT_SUCCESS; } void StartConnections() { WEAVE_ERROR err; conSource = MessageLayer.NewConnection(); conDest = MessageLayer.NewConnection(); VerifyOrExit(conSource != NULL && conDest != NULL, err = WEAVE_ERROR_NO_MEMORY); conSource->OnConnectionComplete = conDest->OnConnectionComplete = HandleConnectionComplete; TunnelSourceAddr = FabricState.SelectNodeAddress(TunnelSourceNodeId); TunnelDestAddr = FabricState.SelectNodeAddress(TunnelDestNodeId); err = conSource->Connect(TunnelSourceNodeId, TunnelSourceAddr); SuccessOrExit(err); err = conDest->Connect(TunnelDestNodeId, TunnelDestAddr); SuccessOrExit(err); return; exit: printf("Tunnel Agent: failed to create connections\n"); exit(EXIT_FAILURE); } bool HandleOption(const char *progName, OptionSet *optSet, int id, const char *name, const char *arg) { switch (id) { case 'A': Role = ConnectionTunnelAgent; break; case 'S': Role = ConnectionTunnelSource; break; case 'D': Role = ConnectionTunnelDest; break; default: PrintArgError("%s: INTERNAL ERROR: Unhandled option: %s\n", progName, name); return false; } return true; } bool HandleNonOptionArgs(const char *progName, int argc, char *argv[]) { if (Role == ConnectionTunnelAgent) { if (argc < 2) { PrintArgError("%s: weave-connection-tunnel: Please specify the tunnel source and destination node-id\n", progName); return false; } if (argc > 2) { PrintArgError("%s: weave-connection-tunnel: Unexpected argument: %s\n", argv[2]); return false; } if (!ParseNodeId(argv[0], TunnelSourceNodeId)) { PrintArgError("%s: weave-connection-tunnel: Invalid value specified for tunnel source node id: %s\n", progName, argv[0]); return false; } if (!ParseNodeId(argv[1], TunnelDestNodeId)) { PrintArgError("%s: weave-connection-tunnel: Invalid value specified for tunnel destination node id: %s\n", progName, argv[1]); return false; } } else { if (argc > 0) { PrintArgError("%s: weave-connection-tunnel: Unexpected argument: %s\n", progName, argv[0]); return false; } } return true; } void HandleMessageReceived(WeaveConnection *con, WeaveMessageInfo *msgInfo, PacketBuffer *msgBuf) { if (Role == ConnectionTunnelDest) { printf("%s\n", msgBuf->Start()); con->Close(); Done = true; } PacketBuffer::Free(msgBuf); } // Tunnel Source and Destination: will receive connection from Tunnel Agent. void HandleConnectionReceived(WeaveMessageLayer *msgLayer, WeaveConnection *con) { connection = con; connection->OnMessageReceived = HandleMessageReceived; } void HandleConnectionComplete(WeaveConnection *con, WEAVE_ERROR conErr) { WEAVE_ERROR res = WEAVE_NO_ERROR; if ((con == conSource) && (conErr == WEAVE_NO_ERROR)) printf("Tunnel Agent: source connected\n"); if ((con == conDest) && (conErr == WEAVE_NO_ERROR)) printf("Tunnel Agent: destination connected\n"); // Tunnel Agent: establish tunnel when the two connections are completed if ((conSource->State == WeaveConnection::kState_Connected) && (conDest->State == WeaveConnection::kState_Connected)) { res = MessageLayer.CreateTunnel(&tun, *conSource, *conDest, 1000000); if (res != WEAVE_NO_ERROR) { printf("Tunnel Agent: failed to establish tunnel\n"); exit(-1); } } } void DriveSending() { WEAVE_ERROR res = WEAVE_NO_ERROR; PacketBuffer *msgBuf = NULL; WeaveMessageInfo msgInfo; uint32_t len = 0; char *p; if ((connection != NULL) && (connection->State == WeaveConnection::kState_Connected)) { msgBuf = PacketBuffer::New(); if (msgBuf == NULL) { printf("Tunnel Source: PacketBuffer alloc failed\n"); exit(-1); } p = (char *)msgBuf->Start(); len = sprintf(p, "Message from tunnel source node to destination node\n"); msgBuf->SetDataLength(len); msgInfo.Clear(); msgInfo.MessageVersion = kWeaveMessageVersion_V2; msgInfo.Flags = 0; msgInfo.SourceNodeId = FabricState.LocalNodeId; msgInfo.DestNodeId = kNodeIdNotSpecified; msgInfo.EncryptionType = kWeaveEncryptionType_None; msgInfo.KeyId = WeaveKeyId::kNone; res = connection->SendMessage(&msgInfo, msgBuf); if (res != WEAVE_NO_ERROR) { printf("Tunnel Source: failed to send message\n"); exit(-1); } } }
29.381988
138
0.659233
cf03086f029e45cfbb3b2a27e454049c615950a8
2,462
cpp
C++
Dory/Sensores.cpp
project-neon/Dory
7a84ee5556b681f1b4d2a03db14f170734dd74ed
[ "MIT" ]
1
2021-11-08T20:17:21.000Z
2021-11-08T20:17:21.000Z
Dory/Sensores.cpp
project-neon/Dory
7a84ee5556b681f1b4d2a03db14f170734dd74ed
[ "MIT" ]
null
null
null
Dory/Sensores.cpp
project-neon/Dory
7a84ee5556b681f1b4d2a03db14f170734dd74ed
[ "MIT" ]
1
2021-11-08T19:57:53.000Z
2021-11-08T19:57:53.000Z
#include <VL53L0X.h> #include "Sensores.h" #include "_config.h" #include <Wire.h> VL53L0X Sensores::sensor1; VL53L0X Sensores::sensor2; void Sensores::init(){ Wire.begin(); pinMode(Xshut_1, OUTPUT); pinMode(Xshut_2, OUTPUT); digitalWrite(Xshut_1, LOW); digitalWrite(Xshut_2, LOW); delay(10); //Wire.begin(); //SENSOR (DIREITA) pinMode(Xshut_1, INPUT); delay(50); Sensores::sensor1.init(true); delay(20); Sensores::sensor1.setAddress((uint8_t)0x22); //SENSOR 3(ESQUERDA) pinMode(Xshut_2, INPUT); delay(50); Sensores::sensor2.init(true); delay(20); Sensores::sensor2.setAddress((uint8_t)0x2A); Sensores::sensor1.setTimeout(100); Sensores::sensor2.setTimeout(100); //Sensores::sensor.setMeasurementTimingBudget(20000); //Sensores::sensor2.setMeasurementTimingBudget(20000); //Sensores::sensor3.setMeasurementTimingBudget(20000); } int Sensores::get_valor(VL53L0X sensor){ return sensor.readRangeSingleMillimeters(); } /* void Sensores::Serial() { Serial.println("__________________________________________________________________"); Serial.println(""); Serial.println("================================="); Serial.println ("I2C scanner. Scanning ..."); //FWD OR SENSOR if (sensor.timeoutOccurred()) { Serial.println("_________________________________"); Serial.print("Distance FWD (READING): "); Serial.println(" TIMEOUT"); Serial.println("_________________________________"); Serial.println(""); } else { Serial.print("Distance SENSOR 0 (mm): "); Serial.println(Sensores::init(sensor)); } //FLT OR SENSOR2 if (sensor2.timeoutOccurred()) { Serial.print("Distance SENSOR 1 (READING): "); Serial.println(" TIMEOUT"); Serial.println("_________________________________"); Serial.println(""); } else { Serial.print("Distance SENSOR 1 (mm): "); Serial.println(Sensores::init(sensor2)); } //FRT OR SENSOR3 if (sensor3.timeoutOccurred()) { Serial.println("_________________________________"); Serial.print("Distance SENSOR 2 (READING): "); Serial.println(" TIMEOUT"); Serial.println("_________________________________"); Serial.println(""); } else { Serial.print("Distance SENSOR 2 (mm): "); Serial.println(Sensores::init(sensor3)); } delay(1000);//can change to a lower time like 100 }*/
26.191489
88
0.655971
cf054e4210c98e07939233cb28e89ffba22d1566
6,560
cc
C++
jni/main.cc
No9/leveldown-mobile
5bc696412771c126a2f4254a055b4942bd0d52d8
[ "BSD-3-Clause" ]
1
2019-06-12T19:37:47.000Z
2019-06-12T19:37:47.000Z
jni/main.cc
No9/leveldown-mobile
5bc696412771c126a2f4254a055b4942bd0d52d8
[ "BSD-3-Clause" ]
null
null
null
jni/main.cc
No9/leveldown-mobile
5bc696412771c126a2f4254a055b4942bd0d52d8
[ "BSD-3-Clause" ]
null
null
null
/* * This file contains sample wrappers showing Android Java Developers * who are not familiar with the NDK or JNI how to get data in and out of the * CPP and how to incorporate the sample code in * http://leveldb.googlecode.com/svn/trunk/doc/index.html into their JNI */ #include <string.h> #include <jni.h> #include <stdio.h> #include <stdlib.h> #include <android/log.h> #include "leveldb/db.h" #define LOG_TAG "AndroidLevelDB" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) leveldb::DB* db; bool isDBopen; char* databasePath; extern "C" { JNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbGet(JNIEnv * env, jobject thiz, jstring key1); }; JNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbGet(JNIEnv * env, jobject thiz, jstring key1) { //LOGI("In the get "); if(! isDBopen){ LOGE("Trying to get when DB wasn't open"); // LOGI("Opening database"); leveldb::Options options; options.create_if_missing = true; leveldb::Status status = leveldb::DB::Open(options, databasePath, &db); if (status.ok()) { //LOGI("Opened database"); isDBopen = true; }else{ LOGE("Failed to open database"); isDBopen = false; databasePath = const_cast<char*>(""); return env->NewStringUTF("NotFound"); } } const char* key = env->GetStringUTFChars(key1,0); //LOGI("Key"); // LOGI(key); std::string value; leveldb::Status status = db->Get(leveldb::ReadOptions(), key, &value); if (status.ok()) { const char* re = value.c_str(); // LOGI(re); return env->NewStringUTF(re); }else{ const char* re = status.ToString().c_str(); // LOGI(re); return env->NewStringUTF("NotFound"); } } extern "C" { JNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbPut(JNIEnv * env, jobject thiz, jstring key1, jstring value1); }; JNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbPut(JNIEnv * env, jobject thiz, jstring key1, jstring value1) { if(! isDBopen){ LOGE("Trying to put when DB wasn't open"); // LOGI("Opening database"); leveldb::Options options; options.create_if_missing = true; leveldb::Status status = leveldb::DB::Open(options, databasePath, &db); if (status.ok()) { //LOGI("Opened database"); isDBopen = true; }else{ LOGE("Failed to open database"); isDBopen = false; databasePath = const_cast<char*>(""); return env->NewStringUTF("NotFound"); } } // LOGI("In the put "); const char* key = env->GetStringUTFChars(key1,0); const char* value = env->GetStringUTFChars(value1,0); //LOGI("Key"); // LOGI(key); //LOGI("Value"); // LOGI(value); leveldb::Status status = db->Put(leveldb::WriteOptions(), key, value); if (status.ok()) { const char* re = status.ToString().c_str(); // LOGI(re); return env->NewStringUTF(value); }else{ const char* re = status.ToString().c_str(); return env->NewStringUTF("NotFound"); } } extern "C" { JNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbOpen(JNIEnv* env, jobject thiz, jstring dbpath); }; JNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbOpen(JNIEnv* env, jobject thiz, jstring dbpath) { if(isDBopen){ //LOGI("DB was already open"); return env->NewStringUTF("DB was already open"); } const char* path = env->GetStringUTFChars(dbpath,0); // LOGI("Opening database"); leveldb::Options options; options.create_if_missing = true; leveldb::Status status = leveldb::DB::Open(options, path, &db); if (status.ok()) { //LOGI(path); //LOGI("Opened database"); isDBopen = true; databasePath = const_cast<char*>(path); }else{ LOGE("Failed to open database"); isDBopen = false; databasePath = const_cast<char*>(""); } const char* re = status.ToString().c_str(); return env->NewStringUTF(re); } extern "C" { JNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbClose(JNIEnv* env, jobject thiz, jstring dbpath); }; JNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbClose(JNIEnv* env, jobject thiz, jstring dbpath) { if(isDBopen){ delete db; isDBopen = false; //LOGI("Closed database"); }else{ //LOGI("DB was already closed."); } return env->NewStringUTF("Closed database"); } extern "C" { JNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbDestroy(JNIEnv* env, jobject thiz, jstring dbpath); }; JNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbDestroy(JNIEnv* env, jobject thiz, jstring dbpath) { if(isDBopen){ delete db; } const char* path = env->GetStringUTFChars(dbpath,0); leveldb::Options options; options.create_if_missing = true; leveldb::Status status = DestroyDB(path, options); //LOGI("Destroyed (ie, cleared) database"); /*re-open database */ status = leveldb::DB::Open(options, path, &db); if (status.ok()) { //LOGI(path); //LOGI("Opened database"); isDBopen = true; databasePath = const_cast<char*>(path); }else{ LOGE("Failed to open database"); isDBopen = false; databasePath = const_cast<char*>(""); } return env->NewStringUTF("Destroyed (ie, cleared) database"); } extern "C" { JNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbDelete(JNIEnv * env, jobject thiz, jstring key1); }; JNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_dbDelete(JNIEnv * env, jobject thiz, jstring key1) { if(! isDBopen){ LOGE("Trying to delete when DB wasn't open"); // LOGI("Opening database"); leveldb::Options options; options.create_if_missing = true; leveldb::Status status = leveldb::DB::Open(options, databasePath, &db); if (status.ok()) { //LOGI("Opened database"); isDBopen = true; }else{ LOGE("Failed to open database"); isDBopen = false; databasePath = const_cast<char*>(""); return env->NewStringUTF("NotFound"); } } //LOGI("In the delete "); const char* key = env->GetStringUTFChars(key1,0); //LOGI("Key"); // LOGI(key); leveldb::Status status = db->Delete(leveldb::WriteOptions(), key); if (status.ok()) { const char* re = status.ToString().c_str(); return env->NewStringUTF(re); }else{ const char* re = status.ToString().c_str(); return env->NewStringUTF("NotFound"); } } extern "C" { JNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_GetProperty(JNIEnv * env, jobject thiz); }; JNIEXPORT jstring JNICALL Java_com_google_code_p_leveldb_LevelDB_GetProperty(JNIEnv * env, jobject thiz) { return env->NewStringUTF("calling get property to find out db size etc"); }
28.154506
129
0.709604
cf0e92dadd83905c9a73be9189544e26aab87294
30,067
cpp
C++
Source/Interface/Resources/FontResource.cpp
Noxagonal/Vulkan2DRenderer
5110a2422dfbf0bf5cfb1d3e13c5b97d5b80243e
[ "MIT" ]
90
2020-06-20T15:00:31.000Z
2022-03-22T21:03:45.000Z
Source/Interface/Resources/FontResource.cpp
Niko40/Vulkan2DRenderer
5110a2422dfbf0bf5cfb1d3e13c5b97d5b80243e
[ "MIT" ]
39
2019-11-04T01:40:14.000Z
2020-03-09T15:57:00.000Z
Source/Interface/Resources/FontResource.cpp
Niko40/Vulkan2DRenderer
5110a2422dfbf0bf5cfb1d3e13c5b97d5b80243e
[ "MIT" ]
4
2020-12-02T22:39:33.000Z
2021-12-27T07:55:12.000Z
#include "Core/SourceCommon.h" #include "System/ThreadPrivateResources.h" #include "Interface/InstanceImpl.h" #include "Interface/Resources/ResourceManager.h" #include "Interface/Resources/ResourceManagerImpl.h" #include "Interface/Resources/FontResource.h" #include "Interface/Resources/FontResourceImpl.h" #include "Interface/Resources/TextureResource.h" #include <stb_image_write.h> namespace vk2d { namespace _internal { // Private function declarations. uint32_t RoundToCeilingPowerOfTwo( uint32_t value ); } } //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // Interface. //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// VK2D_API vk2d::FontResource::FontResource( vk2d::_internal::ResourceManagerImpl * resource_manager, uint32_t loader_thread_index, vk2d::ResourceBase * parent_resource, const std::filesystem::path & file_path, uint32_t glyph_texel_size, bool use_alpha, uint32_t fallback_character, uint32_t glyph_atlas_padding ) { impl = std::make_unique<vk2d::_internal::FontResourceImplBase>( this, resource_manager, loader_thread_index, parent_resource, file_path, glyph_texel_size, use_alpha, fallback_character, glyph_atlas_padding ); if( !impl || !impl->IsGood() ) { impl = nullptr; resource_manager->GetInstance()->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot create font resource implementation!" ); return; } resource_impl = impl.get(); } VK2D_API vk2d::FontResource::~FontResource() {} VK2D_API vk2d::ResourceStatus VK2D_APIENTRY vk2d::FontResource::GetStatus() { return impl->GetStatus(); } VK2D_API vk2d::ResourceStatus VK2D_APIENTRY vk2d::FontResource::WaitUntilLoaded( std::chrono::nanoseconds timeout ) { return impl->WaitUntilLoaded( timeout ); } VK2D_API vk2d::ResourceStatus VK2D_APIENTRY vk2d::FontResource::WaitUntilLoaded( std::chrono::steady_clock::time_point timeout ) { return impl->WaitUntilLoaded( timeout ); } VK2D_API vk2d::Rect2f VK2D_APIENTRY vk2d::FontResource::CalculateRenderedSize( std::string_view text, float kerning, glm::vec2 scale, bool vertical, uint32_t font_face, bool wait_for_resource_load ) { return impl->CalculateRenderedSize( text, kerning, scale, vertical, font_face, wait_for_resource_load ); } VK2D_API bool VK2D_APIENTRY vk2d::FontResource::IsGood() const { return !!impl; } //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// // Implementation. //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// vk2d::_internal::FontResourceImplBase::FontResourceImplBase( vk2d::FontResource * my_interface, vk2d::_internal::ResourceManagerImpl * resource_manager, uint32_t loader_thread_index, vk2d::ResourceBase * parent_resource, const std::filesystem::path & file_path, uint32_t glyph_texel_size, bool use_alpha, uint32_t fallback_character, uint32_t glyph_atlas_padding ) : vk2d::_internal::ResourceImplBase( my_interface, loader_thread_index, resource_manager, parent_resource, { file_path } ) { assert( my_interface ); assert( resource_manager ); this->my_interface = my_interface; this->resource_manager = resource_manager; this->glyph_texel_size = glyph_texel_size; this->glyph_atlas_padding = glyph_atlas_padding; this->fallback_character = fallback_character; this->use_alpha = use_alpha; is_good = true; } vk2d::_internal::FontResourceImplBase::~FontResourceImplBase() {} vk2d::ResourceStatus vk2d::_internal::FontResourceImplBase::GetStatus() { if( !is_good ) return vk2d::ResourceStatus::FAILED_TO_LOAD; auto local_status = status.load(); if( local_status == vk2d::ResourceStatus::UNDETERMINED ) { if( load_function_run_fence.IsSet() ) { // "texture_resource" is set by the MTLoad() function so we can access it // without further mutex locking. ( "load_function_run_fence" is set ) status = local_status = texture_resource->GetStatus(); } } return local_status; } vk2d::ResourceStatus vk2d::_internal::FontResourceImplBase::WaitUntilLoaded( std::chrono::nanoseconds timeout ) { if( timeout == std::chrono::nanoseconds::max() ) { return WaitUntilLoaded( std::chrono::steady_clock::time_point::max() ); } return WaitUntilLoaded( std::chrono::steady_clock::now() + timeout ); } vk2d::ResourceStatus vk2d::_internal::FontResourceImplBase::WaitUntilLoaded( std::chrono::steady_clock::time_point timeout ) { // Make sure timeout is in the future. assert( timeout == std::chrono::steady_clock::time_point::max() || timeout + std::chrono::seconds( 5 ) >= std::chrono::steady_clock::now() ); if( !is_good ) return vk2d::ResourceStatus::FAILED_TO_LOAD; auto local_status = status.load(); if( local_status == vk2d::ResourceStatus::UNDETERMINED ) { if( load_function_run_fence.Wait( timeout ) ) { status = local_status = texture_resource->WaitUntilLoaded( timeout ); } } return local_status; } bool vk2d::_internal::FontResourceImplBase::MTLoad( vk2d::_internal::ThreadPrivateResource * thread_resource ) { // TODO: additional parameters: // From raw file. assert( thread_resource ); assert( my_interface->impl->GetFilePaths().size() ); auto loader_thread_resource = static_cast<vk2d::_internal::ThreadLoaderResource*>( thread_resource ); auto instance = loader_thread_resource->GetInstance(); auto path_str = my_interface->impl->GetFilePaths()[ 0 ].string(); auto max_texture_size = instance->GetVulkanPhysicalDeviceProperties().limits.maxImageDimension2D; auto min_texture_size = std::min( uint32_t( 128 ), max_texture_size ); // average_to_max_weight variable is used to estimate glyph space requirements on atlas textures. // 0 sets the estimation to average size, 1 sets the estimation to max weights. Default is 0.05 // which should give enough space in the atlas to contain all glyphs in auto average_to_max_weight = 0.05; auto total_glyph_count = uint64_t( 0 ); auto maximum_glyph_size = glm::dvec2( 0.0, 0.0 ); auto maximum_glyph_bitmap_size = glm::dvec2( 0.0, 0.0 ); auto maximum_glyph_bitmap_occupancy_size = glm::dvec2( 0.0, 0.0 ); auto average_glyph_bitmap_occupancy_size = glm::dvec2( 0.0, 0.0 ); if( my_interface->impl->IsFromFile() ) { // Try to load from file. // Get amount of faces in the file uint32_t face_count = 0; { FT_Face face {}; auto ft_error = FT_New_Face( loader_thread_resource->GetFreeTypeInstance(), path_str.c_str(), -1, &face ); switch( ft_error ) { case FT_Err_Ok: // All good face_count = uint32_t( face->num_faces ); FT_Done_Face( face ); break; case FT_Err_Cannot_Open_Resource: // Cannot open file error instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, std::string( "Cannot load font: File not found: " ) + path_str ); return false; case FT_Err_Unknown_File_Format: // Unknown file format error instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, std::string( "Cannot load font: Unknown file format: " ) + path_str ); return false; default: // Other errors instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, std::string( "Cannot load font: " ) + path_str ); return false; } } assert( !face_infos.size() ); // If hit, this function was called twice for some reason, should never happen. face_infos.clear(); face_infos.resize( face_count ); for( uint32_t i = 0; i < face_count; ++i ) { FT_Face face {}; { auto ft_error = FT_New_Face( loader_thread_resource->GetFreeTypeInstance(), path_str.c_str(), i, &face ); if( ft_error ) { instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, std::string( "Cannot load font: " ) + path_str ); return false; } } { auto ft_error = FT_Set_Pixel_Sizes( face, 0, glyph_texel_size ); if( ft_error ) { instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, std::string( "Cannot load font: " ) + path_str ); return false; } } // Get glyph sizes total_glyph_count += uint64_t( face->num_glyphs ) + 1; for( decltype( face->num_glyphs ) i = 0; i < face->num_glyphs; ++i ) { auto ft_load_error = FT_Load_Glyph( face, FT_UInt( i ), FT_LOAD_DEFAULT ); if( ft_load_error ) { instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot load font, cannot load glyph for bitmap metrics!" ); return false; } auto glyph_size = glm::dvec2( double( face->glyph->metrics.width ), double( face->glyph->metrics.height ) ); auto glyph_bitmap_size = glm::dvec2( double( face->glyph->bitmap.width ), double( face->glyph->bitmap.rows ) ); auto glyph_bitmap_space_occupancy = glm::dvec2( double( face->glyph->bitmap.width + glyph_atlas_padding ), double( face->glyph->bitmap.rows + glyph_atlas_padding ) ); maximum_glyph_size.x = std::max( maximum_glyph_size.x, glyph_size.x ); maximum_glyph_size.y = std::max( maximum_glyph_size.y, glyph_size.y ); maximum_glyph_bitmap_size.x = std::max( maximum_glyph_bitmap_size.x, glyph_bitmap_size.x ); maximum_glyph_bitmap_size.y = std::max( maximum_glyph_bitmap_size.y, glyph_bitmap_size.y ); maximum_glyph_bitmap_occupancy_size.x = std::max( maximum_glyph_bitmap_occupancy_size.x, glyph_bitmap_space_occupancy.x ); maximum_glyph_bitmap_occupancy_size.y = std::max( maximum_glyph_bitmap_occupancy_size.y, glyph_bitmap_space_occupancy.y ); average_glyph_bitmap_occupancy_size += glyph_bitmap_space_occupancy; } face_infos[ i ].face = face; } } else { // Try to load from data. assert( 0 && "Not implemented yet!" ); } if( !total_glyph_count ) { instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Cannot load font: Font contains no glyphs!" ); return false; } // Estimate appropriate atlas size. // This code tries to find a tradeoff between texture size and amount so that 1 to 3 textures are // created. For example if glyphs do not fit into 3 textures of size 512 * 512, a larger 1024 * 1024 // texture is created which should be able to contain the glyphs. average_glyph_bitmap_occupancy_size += glm::dvec2( double( glyph_atlas_padding ), double( glyph_atlas_padding ) ) * 2.0; average_glyph_bitmap_occupancy_size /= float( total_glyph_count ); { auto estimated_glyph_space_requirements = average_glyph_bitmap_occupancy_size * ( 1.0 - average_to_max_weight ) + maximum_glyph_bitmap_occupancy_size * average_to_max_weight; auto estimated_average_space_requirements = estimated_glyph_space_requirements / 1.5; // aim to have 1 to 4 textures to optimize memory usage // auto estimated_average_space_requirements = estimated_glyph_space_requirements / 5.0; // aim to have 1 to 4 textures to optimize memory usage atlas_size = RoundToCeilingPowerOfTwo( uint32_t( std::sqrt( std::ceil( estimated_average_space_requirements.x ) * std::ceil( estimated_average_space_requirements.y ) * double( total_glyph_count ) ) ) ); if( atlas_size > max_texture_size ) atlas_size = max_texture_size; if( atlas_size < min_texture_size ) atlas_size = min_texture_size; } // Stop if we don't have any font's to work with. if( !face_infos.size() ) { instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, std::string( "Internal error: Cannot load font: " ) + path_str ); return false; } current_atlas_texture = CreateNewAtlasTexture(); auto glyph_size_bitmap_size_ratio_vector = maximum_glyph_bitmap_size / maximum_glyph_size; auto glyph_size_bitmap_size_ratio = std::max( glyph_size_bitmap_size_ratio_vector.x, glyph_size_bitmap_size_ratio_vector.y ); // Process all glyphs from all font faces for( size_t face_index = 0; face_index < face_infos.size(); ++face_index ) { auto & face = face_infos[ face_index ]; face.glyph_infos.resize( face.face->num_glyphs ); for( auto glyph_index = 0; glyph_index < face.face->num_glyphs; ++glyph_index ) { { auto ft_load_error = FT_Load_Glyph( face.face, glyph_index, FT_LOAD_DEFAULT ); if( ft_load_error ) { instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot load font, cannot load glyph!" ); return false; } } { auto ft_render_error = FT_Render_Glyph( face.face->glyph, use_alpha ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO ); if( ft_render_error ) { instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot load font, cannot render glyph!" ); return false; } } auto ft_glyph = face.face->glyph; auto & ft_bitmap = ft_glyph->bitmap; std::vector<vk2d::Color8> final_glyph_pixels( size_t( ft_bitmap.rows ) * size_t( ft_bitmap.width ) ); switch( ft_bitmap.pixel_mode ) { case FT_PIXEL_MODE_MONO: { for( uint32_t y = 0; y < ft_bitmap.rows; ++y ) { for( uint32_t x = 0; x < ft_bitmap.width; ++x ) { auto texel_pos = y * ft_bitmap.width + x; auto & dst = final_glyph_pixels[ texel_pos ]; auto src_bit = 7 - x % 8; auto src_byte = ft_bitmap.buffer[ ( y * ft_bitmap.pitch ) + ( x / 8 ) ]; dst.r = ( ( src_byte >> src_bit ) & 1 ) * 255; dst.g = dst.r; dst.b = dst.r; dst.a = dst.r; } } } break; case FT_PIXEL_MODE_GRAY: { for( uint32_t y = 0; y < ft_bitmap.rows; ++y ) { for( uint32_t x = 0; x < ft_bitmap.width; ++x ) { auto texel_pos = y * ft_bitmap.width + x; auto & dst = final_glyph_pixels[ texel_pos ]; auto src = ft_bitmap.buffer[ texel_pos ]; dst.r = src; dst.g = src; dst.b = src; dst.a = src; } } } break; case FT_PIXEL_MODE_BGRA: { for( uint32_t y = 0; y < ft_bitmap.rows; ++y ) { for( uint32_t x = 0; x < ft_bitmap.width; ++x ) { auto texel_pos = y * ft_bitmap.width + x; auto & dst = final_glyph_pixels[ texel_pos ]; auto src = &ft_bitmap.buffer[ texel_pos * 4 ]; dst.r = src[ 2 ]; dst.g = src[ 1 ]; dst.b = src[ 0 ]; dst.a = src[ 3 ]; } } } break; default: // Unsupported instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot load font, Unsupported pixel format!" ); return false; break; } // Attach rendered glyph to final texture atlas. auto atlas_location = AttachGlyphToAtlas( face.face->glyph, glyph_atlas_padding, final_glyph_pixels ); if( !atlas_location.atlas_ptr ) { instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot create font, cannot copy glyph image to font texture atlas!" ); return false; } // Create glyph info structure for the glyph { vk2d::Rect2f uv_coords = { float( atlas_location.location.top_left.x ) / float( atlas_size ), float( atlas_location.location.top_left.y ) / float( atlas_size ), float( atlas_location.location.bottom_right.x ) / float( atlas_size ), float( atlas_location.location.bottom_right.y ) / float( atlas_size ) }; auto & metrics = face.face->glyph->metrics; auto glyph_size = glm::dvec2( metrics.width, metrics.height ) * glyph_size_bitmap_size_ratio; auto glyph_hori_top_left = glm::dvec2( metrics.horiBearingX, -metrics.horiBearingY ) * glyph_size_bitmap_size_ratio; auto glyph_hori_bottom_right = glyph_hori_top_left + glyph_size; auto glyph_vert_top_left = glm::dvec2( metrics.vertBearingX, metrics.vertBearingY ) * glyph_size_bitmap_size_ratio; auto glyph_vert_bottom_right = glyph_vert_top_left + glyph_size; auto hori_advance = metrics.horiAdvance * glyph_size_bitmap_size_ratio; auto vert_advance = metrics.vertAdvance * glyph_size_bitmap_size_ratio; vk2d::_internal::GlyphInfo glyph_info {}; glyph_info.face_index = uint32_t( face_index ); glyph_info.atlas_index = atlas_location.atlas_index; glyph_info.uv_coords = uv_coords; glyph_info.horisontal_coords.top_left = glm::vec2( float( glyph_hori_top_left.x ), float( glyph_hori_top_left.y ) ); glyph_info.horisontal_coords.bottom_right = glm::vec2( float( glyph_hori_bottom_right.x ), float( glyph_hori_bottom_right.y ) ); glyph_info.vertical_coords.top_left = glm::vec2( float( glyph_vert_top_left.x ), float( glyph_vert_top_left.y ) ); glyph_info.vertical_coords.bottom_right = glm::vec2( float( glyph_vert_bottom_right.x ), float( glyph_vert_bottom_right.y ) ); glyph_info.horisontal_advance = float( hori_advance ); glyph_info.vertical_advance = float( vert_advance ); face.glyph_infos[ glyph_index ] = glyph_info; } } // Create character map and get fallback character { FT_ULong charcode = {}; FT_UInt gindex = {}; FT_ULong fallback_glyph_index = {}; charcode = FT_Get_First_Char( face.face, &gindex ); fallback_glyph_index = gindex; while( gindex != 0 ) { face.charmap[ uint32_t( charcode ) ] = uint32_t( gindex ); charcode = FT_Get_Next_Char( face.face, charcode, &gindex ); } if( auto f = FT_Get_Char_Index( face.face, FT_ULong( fallback_character ) ) ) { fallback_glyph_index = f; } face.fallback_glyph_index = fallback_glyph_index; } } // Destroy font faces, we don't need them anymore. for( auto & f : face_infos ) { FT_Done_Face( f.face ); f.face = nullptr; } // Everything is baked into the atlas, create texture resource to store it. { std::vector<const std::vector<vk2d::Color8>*> texture_data_array( atlas_textures.size() ); for( size_t i = 0; i < atlas_textures.size(); ++i ) { texture_data_array[ i ] = &atlas_textures[ i ]->data; } texture_resource = resource_manager->CreateArrayTextureResource( glm::uvec2( atlas_size, atlas_size ), texture_data_array, my_interface ); if( !texture_resource ) { instance->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot create font, cannot create texture resource for font!" ); return false; } } return true; } void vk2d::_internal::FontResourceImplBase::MTUnload( vk2d::_internal::ThreadPrivateResource * thread_resource ) { // Make sure font faces are destroyed. for( auto f : face_infos ) { FT_Done_Face( f.face ); } face_infos.clear(); } vk2d::Rect2f vk2d::_internal::FontResourceImplBase::CalculateRenderedSize( std::string_view text, float kerning, glm::vec2 scale, bool vertical, uint32_t font_face, bool wait_for_resource_load ) { if( std::size( text ) <= 0 ) return {}; if( wait_for_resource_load ) { WaitUntilLoaded( std::chrono::nanoseconds::max() ); } else { if( GetStatus() == vk2d::ResourceStatus::UNDETERMINED ) return {}; } if( !FaceExists( font_face ) ) return {}; vk2d::Rect2f ret {}; float advance {}; if( vertical ) { // Vertical text // First letter sets defaults auto first_gi = GetGlyphInfo( font_face, text[ 0 ] ); ret.top_left.x = first_gi->vertical_coords.top_left.x; ret.bottom_right.x = first_gi->vertical_coords.bottom_right.x; if( std::size( text ) > 1 ) { advance += first_gi->vertical_advance; } for( size_t i = 1; i < std::size( text ) - 1; ++i ) { // Middle letters are spaced by "advance" value auto gi = GetGlyphInfo( font_face, text[ i ] ); ret.top_left.x = std::min( ret.top_left.x, gi->vertical_coords.top_left.x ); ret.bottom_right.x = std::max( ret.bottom_right.x, gi->vertical_coords.bottom_right.x ); advance += kerning + gi->vertical_advance; } // Need to get the size of the last letter, not the "advance" auto last_gi = GetGlyphInfo( font_face, text.back() ); ret.top_left.x = std::min( ret.top_left.x, last_gi->vertical_coords.top_left.x ); ret.bottom_right.x = std::max( ret.bottom_right.x, last_gi->vertical_coords.bottom_right.x ); ret.top_left.y = first_gi->vertical_coords.top_left.y; ret.bottom_right.y = advance + last_gi->vertical_coords.bottom_right.y; } else { // Horisontal text // First letter sets defaults auto first_gi = GetGlyphInfo( font_face, text[ 0 ] ); ret.top_left.y = first_gi->horisontal_coords.top_left.y; ret.bottom_right.y = first_gi->horisontal_coords.bottom_right.y; if( std::size( text ) > 1 ) { advance += first_gi->horisontal_advance; } for( size_t i = 1; i < std::size( text ) - 1; ++i ) { // Middle letters are spaced by "advance" value auto gi = GetGlyphInfo( font_face, text[ i ] ); ret.top_left.y = std::min( ret.top_left.y, gi->horisontal_coords.top_left.y ); ret.bottom_right.y = std::max( ret.bottom_right.y, gi->horisontal_coords.bottom_right.y ); advance += kerning + gi->horisontal_advance; } // Need to get the size of the last letter, not the "advance" auto last_gi = GetGlyphInfo( font_face, text.back() ); ret.top_left.y = std::min( ret.top_left.y, last_gi->horisontal_coords.top_left.y ); ret.bottom_right.y = std::max( ret.bottom_right.y, last_gi->horisontal_coords.bottom_right.y ); ret.top_left.x = first_gi->horisontal_coords.top_left.x; ret.bottom_right.x = advance + last_gi->horisontal_coords.bottom_right.x; } ret.top_left *= scale; ret.bottom_right *= scale; return ret; } bool vk2d::_internal::FontResourceImplBase::FaceExists( uint32_t font_face ) const { if( size_t( font_face ) < face_infos.size() ) { return true; } return false; } vk2d::TextureResource * vk2d::_internal::FontResourceImplBase::GetTextureResource() { if( GetStatus() == vk2d::ResourceStatus::LOADED ) { return texture_resource; } return {}; } const vk2d::_internal::GlyphInfo * vk2d::_internal::FontResourceImplBase::GetGlyphInfo( uint32_t font_face, uint32_t character ) const { auto & face_info = face_infos[ font_face ]; auto & charmap = face_info.charmap; auto glyph_it = charmap.find( character ); auto glyph_index = uint32_t( 0 ); if( glyph_it != charmap.end() ) { glyph_index = glyph_it->second; } else { glyph_index = face_info.fallback_glyph_index; } return &face_info.glyph_infos[ glyph_index ]; } bool vk2d::_internal::FontResourceImplBase::IsGood() const { return is_good; } vk2d::_internal::FontResourceImplBase::AtlasTexture * vk2d::_internal::FontResourceImplBase::CreateNewAtlasTexture() { auto new_atlas_texture = std::make_unique<vk2d::_internal::FontResourceImplBase::AtlasTexture>(); new_atlas_texture->data.resize( size_t( atlas_size ) * size_t( atlas_size ) ); new_atlas_texture->index = uint32_t( atlas_textures.size() ); std::memset( new_atlas_texture->data.data(), 0, new_atlas_texture->data.size() * sizeof( vk2d::Color8 ) ); auto new_atlas_texture_ptr = new_atlas_texture.get(); atlas_textures.push_back( std::move( new_atlas_texture ) ); return new_atlas_texture_ptr; } vk2d::_internal::FontResourceImplBase::AtlasLocation vk2d::_internal::FontResourceImplBase::ReserveSpaceForGlyphFromAtlasTextures( FT_GlyphSlot glyph, uint32_t glyph_atlas_padding ) { assert( current_atlas_texture ); auto FindLocationInAtlasTexture =[]( vk2d::_internal::FontResourceImplBase::AtlasTexture * atlas_texture, FT_GlyphSlot glyph, uint32_t atlas_size, uint32_t glyph_atlas_padding ) -> vk2d::_internal::FontResourceImplBase::AtlasLocation { uint32_t glyph_width = uint32_t( glyph->bitmap.width ) + glyph_atlas_padding; uint32_t glyph_height = uint32_t( glyph->bitmap.rows ) + glyph_atlas_padding; // Find space in the current atlas texture. if( atlas_texture->previous_row_height + glyph_height + glyph_atlas_padding < atlas_size ) { // Fits height wise. if( atlas_texture->current_write_location + glyph_width + glyph_atlas_padding < atlas_size ) { // Fits width wise, fits completely. vk2d::_internal::FontResourceImplBase::AtlasLocation new_glyph_location {}; new_glyph_location.atlas_ptr = atlas_texture; new_glyph_location.atlas_index = atlas_texture->index; new_glyph_location.location.top_left = { atlas_texture->current_write_location + glyph_atlas_padding, atlas_texture->previous_row_height + glyph_atlas_padding }; new_glyph_location.location.bottom_right = new_glyph_location.location.top_left + glm::uvec2( uint32_t( glyph->bitmap.width ), uint32_t( glyph->bitmap.rows ) ); // update current row height and write locations before returning the result. atlas_texture->current_row_height = std::max( atlas_texture->current_row_height, glyph_height ); atlas_texture->current_write_location += glyph_width; return new_glyph_location; } // Does not fit width wise, go to the next row. atlas_texture->previous_row_height += atlas_texture->current_row_height; atlas_texture->current_row_height = 0; atlas_texture->current_write_location = 0; // Check height again. if( atlas_texture->previous_row_height + glyph_height + glyph_atlas_padding < atlas_size ) { // Fits height wise. if( atlas_texture->current_write_location + glyph_width + glyph_atlas_padding < atlas_size ) { // Fits width wise. vk2d::_internal::FontResourceImplBase::AtlasLocation new_glyph_location {}; new_glyph_location.atlas_ptr = atlas_texture; new_glyph_location.atlas_index = atlas_texture->index; new_glyph_location.location.top_left = { atlas_texture->current_write_location + glyph_atlas_padding, atlas_texture->previous_row_height + glyph_atlas_padding }; new_glyph_location.location.bottom_right = new_glyph_location.location.top_left + glm::uvec2( uint32_t( glyph->bitmap.width ), uint32_t( glyph->bitmap.rows ) ); // update current row height and write locations before returning the result. atlas_texture->current_row_height = std::max( atlas_texture->current_row_height, glyph_height ); atlas_texture->current_write_location += glyph_width; return new_glyph_location; } // Does not fit width wise to a new row, this would only happen if a single // face glyph is too large to fit into a single atlas. This is an error. assert( 0 && "Glyph too big" ); return {}; } // Does not fit to a new row, need a new atlas texture return {}; } // Does not fit at all, need a new atlas texture. return {}; }; auto new_location = FindLocationInAtlasTexture( current_atlas_texture, glyph, atlas_size, glyph_atlas_padding ); if( !new_location.atlas_ptr ) { // Not enough space found, create new atlas and try again. current_atlas_texture = CreateNewAtlasTexture(); if( !current_atlas_texture ) { // Failed to create new atlas texture. resource_manager->GetInstance()->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot create font, cannot create new atlas texture for font!" ); return {}; } // Got new atlas texture, retry finding space in it. new_location = FindLocationInAtlasTexture( current_atlas_texture, glyph, atlas_size, glyph_atlas_padding ); if( !new_location.atlas_ptr ) { // Still could not find enough space, a single font face glyph is too large // to fit entire atlas, this should not happen so we raise an error. resource_manager->GetInstance()->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot create font, a single glyph wont fit into a new atlas." ); return {}; } return new_location; } return new_location; } void vk2d::_internal::FontResourceImplBase::CopyGlyphTextureToAtlasLocation( AtlasLocation atlas_location, const std::vector<vk2d::Color8> & converted_texture_data ) { assert( atlas_location.atlas_ptr ); auto glyph_width = atlas_location.location.bottom_right.x - atlas_location.location.top_left.x; auto glyph_height = atlas_location.location.bottom_right.y - atlas_location.location.top_left.y; glm::uvec2 location = atlas_location.location.top_left; for( uint32_t gy = 0; gy < glyph_height; ++gy ) { for( uint32_t gx = 0; gx < glyph_width; ++gx ) { auto ax = location.x + gx; auto ay = location.y + gy; atlas_location.atlas_ptr->data[ ay * atlas_size + ax ] = converted_texture_data[ gy * glyph_width + gx ]; } } } vk2d::_internal::FontResourceImplBase::AtlasLocation vk2d::_internal::FontResourceImplBase::AttachGlyphToAtlas( FT_GlyphSlot glyph, uint32_t glyph_atlas_padding, const std::vector<vk2d::Color8> & converted_texture_data ) { auto atlas_location = ReserveSpaceForGlyphFromAtlasTextures( glyph, glyph_atlas_padding ); if( atlas_location.atlas_ptr ) { CopyGlyphTextureToAtlasLocation( atlas_location, converted_texture_data ); return atlas_location; } else { resource_manager->GetInstance()->Report( vk2d::ReportSeverity::NON_CRITICAL_ERROR, "Internal error: Cannot create font, cannot attach glyph to atlas texture!" ); return {}; } } uint32_t vk2d::_internal::RoundToCeilingPowerOfTwo( uint32_t value ) { value--; value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; value++; return value; }
32.364909
177
0.683241
cf1375d321ab6dff3ca69728686c391b0bb9f4a4
827
cpp
C++
UVa 10585 - Center of symmetry/sample/10585 - Center of symmetry.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 10585 - Center of symmetry/sample/10585 - Center of symmetry.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 10585 - Center of symmetry/sample/10585 - Center of symmetry.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
#include <stdio.h> #include <map> using namespace std; long long x[10000], y[10000], avex, avey, n; void solve() { if(avex%n || avey%n) { puts("no"); return; } avex /= n, avey /= n; map<long long, int> r; int i; for(i = 0; i < n; i++) r[x[i]*100000000+y[i]] = 1; long long xx, yy; for(i = 0; i < n; i++) { xx = 2*avex - x[i]; yy = 2*avey - y[i]; if(r[x[i]*100000000+y[i]] == 0) { puts("no"); return; } } puts("yes"); } int main() { int t, i; scanf("%d", &t); while(t--) { scanf("%lld", &n); avex = 0, avey = 0; for(i = 0; i < n; i++) { scanf("%lld %lld", &x[i], &y[i]); avex += x[i], avey += y[i]; } solve(); } return 0; }
20.675
45
0.385732
cf1485d6b4456ed43ad3558b0191dc7ba14f6957
162
cpp
C++
src/utils/Application.cpp
mgeorgoulopoulos/gencut
e9751c0d04816311d5460d14a88eaa1fcbe6f40d
[ "MIT" ]
null
null
null
src/utils/Application.cpp
mgeorgoulopoulos/gencut
e9751c0d04816311d5460d14a88eaa1fcbe6f40d
[ "MIT" ]
null
null
null
src/utils/Application.cpp
mgeorgoulopoulos/gencut
e9751c0d04816311d5460d14a88eaa1fcbe6f40d
[ "MIT" ]
null
null
null
#include "Application.h" #include "GenomeModel.h" void Application::execute() { GenomeModel model; model.load(arguments.genomeModelFilename, geneRegistry); }
18
57
0.771605
cf16edca209b988b8b8becbb6e49ecf128e1f2b8
5,119
cxx
C++
src/curl/Request.cxx
CM4all/libcommon
fba0eae725b0e7a6cf93ff0be231d90e2c0aa04e
[ "BSD-2-Clause" ]
13
2017-06-30T15:38:21.000Z
2022-03-11T06:49:17.000Z
src/curl/Request.cxx
CM4all/libcommon
fba0eae725b0e7a6cf93ff0be231d90e2c0aa04e
[ "BSD-2-Clause" ]
2
2017-10-29T18:28:28.000Z
2020-08-20T00:43:21.000Z
src/curl/Request.cxx
CM4all/libcommon
fba0eae725b0e7a6cf93ff0be231d90e2c0aa04e
[ "BSD-2-Clause" ]
6
2017-10-29T11:38:13.000Z
2021-10-12T00:36:38.000Z
/* * Copyright 2008-2021 Max Kellermann <max.kellermann@gmail.com> * * 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. * * 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 * FOUNDATION 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 "Request.hxx" #include "Global.hxx" #include "Handler.hxx" #include "util/RuntimeError.hxx" #include "util/StringStrip.hxx" #include "util/StringView.hxx" #include "util/CharUtil.hxx" #include "version.h" #include <curl/curl.h> #include <algorithm> #include <cassert> #include <string.h> CurlRequest::CurlRequest(CurlGlobal &_global, CurlEasy _easy, CurlResponseHandler &_handler) :global(_global), handler(_handler), easy(std::move(_easy)) { SetupEasy(); } CurlRequest::CurlRequest(CurlGlobal &_global, CurlResponseHandler &_handler) :global(_global), handler(_handler) { SetupEasy(); } CurlRequest::~CurlRequest() noexcept { FreeEasy(); } void CurlRequest::SetupEasy() { error_buffer[0] = 0; easy.SetPrivate((void *)this); easy.SetUserAgent(PACKAGE " " VERSION); easy.SetHeaderFunction(_HeaderFunction, this); easy.SetWriteFunction(WriteFunction, this); easy.SetErrorBuffer(error_buffer); easy.SetNoProgress(); easy.SetNoSignal(); easy.SetConnectTimeout(10); } void CurlRequest::Start() { assert(!registered); global.Add(*this); registered = true; } void CurlRequest::Stop() noexcept { if (!registered) return; global.Remove(*this); registered = false; } void CurlRequest::FreeEasy() noexcept { if (!easy) return; Stop(); easy = nullptr; } void CurlRequest::Resume() noexcept { assert(registered); easy.Unpause(); global.InvalidateSockets(); } void CurlRequest::FinishHeaders() { if (state != State::HEADERS) return; state = State::BODY; long status = 0; easy.GetInfo(CURLINFO_RESPONSE_CODE, &status); handler.OnHeaders(status, std::move(headers)); } void CurlRequest::FinishBody() { FinishHeaders(); if (state != State::BODY) return; state = State::CLOSED; handler.OnEnd(); } void CurlRequest::Done(CURLcode result) noexcept { Stop(); try { if (result != CURLE_OK) { StripRight(error_buffer); const char *msg = error_buffer; if (*msg == 0) msg = curl_easy_strerror(result); throw FormatRuntimeError("CURL failed: %s", msg); } FinishBody(); } catch (...) { state = State::CLOSED; handler.OnError(std::current_exception()); } } [[gnu::pure]] static bool IsResponseBoundaryHeader(StringView s) noexcept { return s.size > 5 && s.StartsWith("HTTP/"); } inline void CurlRequest::HeaderFunction(StringView s) noexcept { if (state > State::HEADERS) return; if (IsResponseBoundaryHeader(s)) { /* this is the boundary to a new response, for example after a redirect */ headers.clear(); return; } const char *header = s.data; const char *end = StripRight(header, header + s.size); const char *value = s.Find(':'); if (value == nullptr) return; std::string name(header, value); std::transform(name.begin(), name.end(), name.begin(), ToLowerASCII); /* skip the colon */ ++value; /* strip the value */ value = StripLeft(value, end); end = StripRight(value, end); headers.emplace(std::move(name), std::string(value, end)); } std::size_t CurlRequest::_HeaderFunction(char *ptr, std::size_t size, std::size_t nmemb, void *stream) noexcept { CurlRequest &c = *(CurlRequest *)stream; size *= nmemb; c.HeaderFunction({ptr, size}); return size; } inline std::size_t CurlRequest::DataReceived(const void *ptr, std::size_t received_size) noexcept { assert(received_size > 0); try { FinishHeaders(); handler.OnData({ptr, received_size}); return received_size; } catch (CurlResponseHandler::Pause) { return CURL_WRITEFUNC_PAUSE; } } std::size_t CurlRequest::WriteFunction(char *ptr, std::size_t size, std::size_t nmemb, void *stream) noexcept { CurlRequest &c = *(CurlRequest *)stream; size *= nmemb; if (size == 0) return 0; return c.DataReceived(ptr, size); }
20.808943
78
0.714202
cf197e0fc95906c485da135c45136ca4783a1cd7
3,272
cpp
C++
src/script/scriptlistingdialog.cpp
nilsding/IrrerrC
0ff273e96c7a2f731ae23e17c9d58b872db14ebc
[ "BSD-2-Clause" ]
1
2016-06-14T14:21:27.000Z
2016-06-14T14:21:27.000Z
src/script/scriptlistingdialog.cpp
nilsding/IrrerrC
0ff273e96c7a2f731ae23e17c9d58b872db14ebc
[ "BSD-2-Clause" ]
null
null
null
src/script/scriptlistingdialog.cpp
nilsding/IrrerrC
0ff273e96c7a2f731ae23e17c9d58b872db14ebc
[ "BSD-2-Clause" ]
null
null
null
#include "scriptlistingdialog.h" #include "ui_scriptlistingdialog.h" ScriptListingDialog::ScriptListingDialog(QWidget *parent) : QDialog(parent), _ui(new Ui::ScriptListingDialog), _scriptDirModel(new QFileSystemModel), _currentScript(0) { _scriptDir = QFileInfo(_SETTINGS.fileName()).absolutePath() + "/scripts"; QDir d(_scriptDir); if (!d.exists()) { d.mkpath(_scriptDir); } connect(_scriptDirModel, &QFileSystemModel::directoryLoaded, this, [=](const QString &path) { _ui->qlvScriptList->setRootIndex(_scriptDirModel->index(path)); QDir d(path); d.setFilter(QDir::NoDotAndDotDot | QDir::Files); if (d.count() < 1) { _ui->qlScriptName->setText(""); _ui->qlAuthor->setText(""); _ui->qlDescription->setText(tr("You currently don't have any scripts installed.")); _qpbEdit->setEnabled(false); if (_currentScript) { _currentScript->deleteLater(); _currentScript = 0; } } else { if (!_currentScript) { _ui->qlDescription->setText(tr("Select a script from the list on the left.")); _qpbEdit->setEnabled(false); } } }); _ui->setupUi(this); _qpbEdit = _ui->qdbbButtons->addButton(tr("&Edit"), QDialogButtonBox::ActionRole); _qpbEdit->setEnabled(false); _ui->qlScriptName->setText(""); _ui->qlAuthor->setText(""); _ui->qlDescription->setText(""); _scriptDirModel->setRootPath(_scriptDir); _scriptDirModel->setFilter(QDir::NoDotAndDotDot | QDir::Files); QStringList filters; filters << "*.js"; _scriptDirModel->setNameFilters(filters); _scriptDirModel->setNameFilterDisables(false); _ui->qlvScriptList->setModel(_scriptDirModel); } ScriptListingDialog::~ScriptListingDialog() { _currentScript->deleteLater(); delete _ui; } void ScriptListingDialog::on_qdbbButtons_clicked(QAbstractButton *button) { auto buttons = _ui->qdbbButtons->buttons(); QAbstractButton *b = 0; for (auto btn : buttons) { if (btn == button) { b = btn; break; } } if (_ui->qdbbButtons->buttonRole(b) == QDialogButtonBox::ActionRole) { QUrl url; url.setPath(_scriptDirModel->filePath(_ui->qlvScriptList->selectionModel()->selectedIndexes().first())); url.setScheme(QLatin1String("file")); QDesktopServices::openUrl(url); } } void ScriptListingDialog::on_qpbOpenScriptDirectory_clicked() { QDesktopServices::openUrl(QUrl::fromLocalFile(_scriptDir)); } void ScriptListingDialog::on_qpbGetMoreScripts_clicked() { QDesktopServices::openUrl(QUrl("http://irc.rrerr.net/client/scripts")); } void ScriptListingDialog::on_qlvScriptList_clicked(const QModelIndex &index) { if (_currentScript) { _currentScript->deleteLater(); } _currentScript = new NScript(_scriptDirModel->filePath(index), this); _ui->qlScriptName->setText(_currentScript->scriptName().toHtmlEscaped()); _ui->qlAuthor->setText(tr("Author: <b>%1</b>").arg(_currentScript->author().toHtmlEscaped())); _ui->qlDescription->setText(_currentScript->description()); _qpbEdit->setEnabled(true); }
32.72
112
0.654951
cf19d1a9499b20b8b71a2f80ec54d258e801780e
3,505
cpp
C++
src/wbdl/wbdl.cpp
DAlexis/wb-display-lib
67317051282d69904774d10553c33ed6c2dedb56
[ "MIT" ]
null
null
null
src/wbdl/wbdl.cpp
DAlexis/wb-display-lib
67317051282d69904774d10553c33ed6c2dedb56
[ "MIT" ]
null
null
null
src/wbdl/wbdl.cpp
DAlexis/wb-display-lib
67317051282d69904774d10553c33ed6c2dedb56
[ "MIT" ]
null
null
null
#include "wbdl.hpp" #include <algorithm> using namespace wbdl; ////////////////////////// // FrameBuffer void FrameBuffer::clearDirty() { dirtyX0 = 0; dirtyY0 = 0; dirtyX1 = 0; dirtyY1 = 0; } bool FrameBuffer::isDirty() { return dirtyX0 != dirtyX1; } unsigned int FrameBuffer::bufferSize() { return width * height / 8; } void FrameBuffer::makePointDirty(unsigned int x, unsigned int y) { if (isDirty()) { dirtyX0 = x; dirtyX1 = x+1; dirtyY0 = y; dirtyY1 = y+1; return; } if (x < dirtyX0) dirtyX0 = x; else if (x+1 > dirtyX1) dirtyX1 = x+1; if (y < dirtyY0) dirtyY0 = y; else if (y+1 > dirtyY1) dirtyY1 = y+1; } void FrameBuffer::putPixelNoDirty(int x, int y, Color c) { if (x < 0 || y < 0 || x >= int(width) || y >= int(height)) return; unsigned int index; switch(order) { case BitsOrder::vertical: index = x + (y / 8) * width; if (c == Color::white) buffer[index] |= 1 << (y%8); else buffer[index] &= ~(1 << (y%8)); break; } } Color FrameBuffer::getPixel(int x, int y) const { if (x < 0 || y < 0 || x >= int(width) || y >= int(height)) return Color::black; unsigned int index; switch(order) { case BitsOrder::vertical: index = x + (y / 8) * width; return (buffer[index] & (1 << (y%8))) != 0 ? Color::white : Color::black; } return Color::black; } ////////////////////////// // Display Display::Display(IDisplayDriver& driver, FrameBuffer& frameBuffer) : m_driver(driver), m_frameBuffer(frameBuffer) { } void Display::updateScreen() { m_driver.updateScreen(m_frameBuffer); m_frameBuffer.clearDirty(); } void Display::putPixel(int x, int y, Color c) { m_frameBuffer.putPixelNoDirty(x, y, c); m_frameBuffer.makePointDirty(x, y); } void Display::line(int x0, int y0, int x1, int y1, Color c) { m_frameBuffer.makePointDirty(x0, y0); m_frameBuffer.makePointDirty(x1, y1); /** * It is a realization of Bresenham's line algorithm * without floats */ int dx = (x0 < x1) ? (x1 - x0) : (x0 - x1); int dy = (y0 < y1) ? (y1 - y0) : (y0 - y1); int sx = (x0 < x1) ? 1 : -1; int sy = (y0 < y1) ? 1 : -1; int err = ((dx > dy) ? dx : -dy) / 2; for(;;) { m_frameBuffer.putPixelNoDirty(x0, y0, c); if (x0 == x1 && y0 == y1) { break; } int oldErr = err; if (oldErr > -dx) { err -= dy; x0 += sx; } if (oldErr < dy) { err += dx; y0 += sy; } } } void Display::circle(int x0, int y0, int r, Color c) { int x = 0; int y = r; int delta = 1 - 2 * r; int error = 0; while (x <= y) { m_frameBuffer.putPixelNoDirty(x0 + x, y0 + y, c); m_frameBuffer.putPixelNoDirty(x0 + x, y0 - y, c); m_frameBuffer.putPixelNoDirty(x0 - x, y0 + y, c); m_frameBuffer.putPixelNoDirty(x0 - x, y0 - y, c); m_frameBuffer.putPixelNoDirty(x0 + y, y0 + x, c); m_frameBuffer.putPixelNoDirty(x0 + y, y0 - x, c); m_frameBuffer.putPixelNoDirty(x0 - y, y0 + x, c); m_frameBuffer.putPixelNoDirty(x0 - y, y0 - x, c); error = 2 * (delta + y) - 1; if ((delta < 0) && (error <= 0)) { delta += 2 * ++x + 1; continue; } error = 2 * (delta - x) - 1; if ((delta > 0) && (error > 0)) { delta += 1 - 2 * --y; continue; } x++; delta += 2 * (x - y); y--; } } int Display::left() { return 0; } int Display::right() { return m_frameBuffer.width-1; } int Display::top() { return 0; } int Display::bottom() { return m_frameBuffer.height-1; } int Display::centerX() { return m_frameBuffer.width / 2; } int Display::centerY() { return m_frameBuffer.height / 2; }
17.26601
75
0.580884
cf224860179885ffaa17a8ab974eef5da9fd7ae7
1,625
hpp
C++
third_party/boost/simd/detail/dispatch/property_of.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
6
2018-02-25T22:23:33.000Z
2021-01-15T15:13:12.000Z
third_party/boost/simd/detail/dispatch/property_of.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
third_party/boost/simd/detail/dispatch/property_of.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
7
2017-12-12T12:36:31.000Z
2020-02-10T14:27:07.000Z
//================================================================================================== /*! @file Defines the property_of meta-function @copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) **/ //================================================================================================== #ifndef BOOST_SIMD_DETAIL_DISPATCH_PROPERTY_OF_HPP_INCLUDED #define BOOST_SIMD_DETAIL_DISPATCH_PROPERTY_OF_HPP_INCLUDED #include <boost/simd/detail/dispatch/meta/scalar_of.hpp> #include <boost/simd/detail/dispatch/detail/property_of.hpp> #include <boost/simd/detail/nsm.hpp> namespace boost { namespace dispatch { /*! @ingroup group-hierarchy @brief Retrieve the fundamental hierarchy of a Type For any type @c T, returns the hierarchy describing the fundamental properties of any given types. This Fundamental Hierarchy is computed by computing the hierarchy of the innermost embedded scalar type of @c T. @tparam T Type to categorize @tparam Origin Type to store inside the generated hierarchy type @par Models: @metafunction **/ template<typename T, typename Origin = T> struct property_of #if !defined(DOXYGEN_ONLY) : ext::property_of<scalar_of_t<T>, typename std::remove_reference<Origin>::type> #endif {}; /*! @ingroup group-hierarchy Eager short-cut to boost::dispatch::property_of **/ template<typename T, typename Origin = T> using property_of_t = typename property_of<T,Origin>::type; } } #endif
30.092593
100
0.651077
cf23785fa10c5955c4187c84d5583a29b1301d3d
577
cpp
C++
demos/glyph_paint/side_pane.cpp
RyanDraves/CPPurses
19cbdae2d18e702144659187ec989c486c714a0f
[ "MIT" ]
null
null
null
demos/glyph_paint/side_pane.cpp
RyanDraves/CPPurses
19cbdae2d18e702144659187ec989c486c714a0f
[ "MIT" ]
null
null
null
demos/glyph_paint/side_pane.cpp
RyanDraves/CPPurses
19cbdae2d18e702144659187ec989c486c714a0f
[ "MIT" ]
null
null
null
#include "side_pane.hpp" #include <cppurses/painter/color.hpp> #include <cppurses/painter/glyph.hpp> #include <cppurses/widget/widgets/text_display.hpp> using namespace cppurses; namespace demos { namespace glyph_paint { Side_pane::Side_pane() { this->width_policy.fixed(16); space1.wallpaper = L'─'; space2.wallpaper = L'─'; glyph_select.height_policy.preferred(6); color_select_stack.height_policy.fixed(3); show_glyph.height_policy.fixed(1); show_glyph.set_alignment(Alignment::Center); } } // namespace glyph_paint } // namespace demos
22.192308
51
0.734835
cf240458e3e47526197c6cf80111a9ad1882045f
17,299
hpp
C++
bluetoe/attribute_handle.hpp
TorstenRobitzki/bluetoe
0f04ccefa4e9ba6a89bf4dfaa0dd62b8e3a46043
[ "MIT" ]
138
2015-04-11T12:07:19.000Z
2022-02-11T13:22:36.000Z
bluetoe/attribute_handle.hpp
TorstenRobitzki/bluetoe
0f04ccefa4e9ba6a89bf4dfaa0dd62b8e3a46043
[ "MIT" ]
60
2015-08-29T12:32:56.000Z
2022-03-25T07:20:21.000Z
bluetoe/attribute_handle.hpp
TorstenRobitzki/bluetoe
0f04ccefa4e9ba6a89bf4dfaa0dd62b8e3a46043
[ "MIT" ]
34
2015-07-08T22:06:25.000Z
2021-12-15T13:17:42.000Z
#ifndef BLUETOE_ATTRIBUTE_HANDLE_HPP #define BLUETOE_ATTRIBUTE_HANDLE_HPP #include <bluetoe/meta_types.hpp> #include <bluetoe/meta_tools.hpp> #include <cstdint> #include <cstdlib> #include <cassert> #include <algorithm> namespace bluetoe { namespace details { struct attribute_handle_meta_type {}; struct attribute_handles_meta_type {}; } /** * @brief define the first attribute handle used by a characteristic or service * * If this option is given to a service, the service attribute will be assigned * to the given handle value. For a characteristic, the Characteristic Declaration * attribute will be assigned to the given handle value. * * All following attrbutes are assigned handles with a larger value. * * @sa attribute_handles * @sa service * @sa characteristic */ template < std::uint16_t AttributeHandleValue > struct attribute_handle { /** @cond HIDDEN_SYMBOLS */ static constexpr std::uint16_t attribute_handle_value = AttributeHandleValue; struct meta_type : details::attribute_handle_meta_type, details::valid_service_option_meta_type, details::valid_characteristic_option_meta_type {}; /** @endcond */ }; /** * @brief define the attributes handles for the characteristic declaration, characteristic * value and optional, for a Client Characteristic Configuration descriptor. * * If the characteristic has no Client Characteristic Configuration descriptor, the CCCD * parameter has to be 0. Value has to be larger than Declaration and CCCD has to larger * than Value (or 0). * * @sa attribute_handle * @sa characteristic */ template < std::uint16_t Declaration, std::uint16_t Value, std::uint16_t CCCD = 0x0000 > struct attribute_handles { /** @cond HIDDEN_SYMBOLS */ static constexpr std::uint16_t declaration_handle = Declaration; static constexpr std::uint16_t value_handle = Value; static constexpr std::uint16_t cccd_handle = CCCD; static_assert( value_handle > declaration_handle, "value handle has to be larger than declaration handle" ); static_assert( cccd_handle > declaration_handle || cccd_handle == 0, "CCCD handle has to be larger than declaration handle" ); static_assert( cccd_handle > value_handle || cccd_handle == 0, "CCCD handle has to be larger than value handle" ); struct meta_type : details::attribute_handles_meta_type, details::valid_characteristic_option_meta_type {}; /** @endcond */ }; template < typename ... Options > class server; template < typename ... Options > class service; template < typename ... Options > class characteristic; namespace details { static constexpr std::uint16_t invalid_attribute_handle = 0; static constexpr std::size_t invalid_attribute_index = ~0; /* * select one of attribute_handle< H > or attribute_handle< H, B, C > */ template < std::uint16_t Default, class, class > struct select_attribute_handles { static constexpr std::uint16_t declaration_handle = Default; static constexpr std::uint16_t value_handle = Default + 1; static constexpr std::uint16_t cccd_handle = Default + 2; }; template < std::uint16_t Default, std::uint16_t AttributeHandleValue, typename T > struct select_attribute_handles< Default, attribute_handle< AttributeHandleValue >, T > { static constexpr std::uint16_t declaration_handle = AttributeHandleValue; static constexpr std::uint16_t value_handle = AttributeHandleValue + 1; static constexpr std::uint16_t cccd_handle = AttributeHandleValue + 2; }; template < std::uint16_t Default, typename T, std::uint16_t Declaration, std::uint16_t Value, std::uint16_t CCCD > struct select_attribute_handles< Default, T, attribute_handles< Declaration, Value, CCCD > > { static constexpr std::uint16_t declaration_handle = Declaration; static constexpr std::uint16_t value_handle = Value; static constexpr std::uint16_t cccd_handle = CCCD == 0 ? Value + 1 : CCCD; }; template < std::uint16_t Default, std::uint16_t AttributeHandleValue, std::uint16_t Declaration, std::uint16_t Value, std::uint16_t CCCD > struct select_attribute_handles< Default, attribute_handle< AttributeHandleValue >, attribute_handles< Declaration, Value, CCCD > > { static_assert( Declaration == Value, "either attribute_handle<> or attribute_handles<> can be used as characteristic<> option, not both." ); }; template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename ... Options > struct characteristic_index_mapping { using characteristic_t = ::bluetoe::characteristic< Options... >; using attribute_handles_t = select_attribute_handles< StartHandle, typename find_by_meta_type< attribute_handle_meta_type, Options... >::type, typename find_by_meta_type< attribute_handles_meta_type, Options... >::type >; static_assert( attribute_handles_t::declaration_handle >= StartHandle, "attribute_handle<> can only be used to create increasing attribute handles." ); static constexpr std::uint16_t end_handle = characteristic_t::number_of_attributes == 2 ? attribute_handles_t::value_handle + 1 : attribute_handles_t::cccd_handle + ( characteristic_t::number_of_attributes - 2 ); static constexpr std::uint16_t end_index = StartIndex + characteristic_t::number_of_attributes; static constexpr std::size_t declaration_position = 0; static constexpr std::size_t value_position = 1; static constexpr std::size_t cccd_position = 2; static std::uint16_t characteristic_attribute_handle_by_index( std::size_t index ) { const std::size_t relative_index = index - StartIndex; assert( relative_index < characteristic_t::number_of_attributes ); switch ( relative_index ) { case declaration_position: return attribute_handles_t::declaration_handle; break; case value_position: return attribute_handles_t::value_handle; break; case cccd_position: return attribute_handles_t::cccd_handle; break; } return relative_index - cccd_position + attribute_handles_t::cccd_handle; } static std::size_t characteristic_attribute_index_by_handle( std::uint16_t handle ) { if ( handle <= attribute_handles_t::declaration_handle ) return StartIndex + declaration_position; if ( handle <= attribute_handles_t::value_handle ) return StartIndex + value_position; if ( handle <= attribute_handles_t::cccd_handle ) return StartIndex + cccd_position; return StartIndex + cccd_position + handle - attribute_handles_t::cccd_handle; } }; template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename CharacteristicList > struct interate_characteristic_index_mappings; template < std::uint16_t StartHandle, std::uint16_t StartIndex > struct interate_characteristic_index_mappings< StartHandle, StartIndex, std::tuple<> > { static std::uint16_t attribute_handle_by_index( std::size_t ) { return invalid_attribute_handle; } static std::size_t attribute_index_by_handle( std::uint16_t ) { return invalid_attribute_index; } static constexpr std::uint16_t last_characteristic_end_handle = StartHandle; }; template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename Characteristics, typename ... Options > using next_characteristic_mapping = interate_characteristic_index_mappings< characteristic_index_mapping< StartHandle, StartIndex, Options... >::end_handle, characteristic_index_mapping< StartHandle, StartIndex, Options... >::end_index, Characteristics >; template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename ...Options, typename ... Chars > struct interate_characteristic_index_mappings< StartHandle, StartIndex, std::tuple< ::bluetoe::characteristic< Options... >, Chars... > > : characteristic_index_mapping< StartHandle, StartIndex, Options... > , next_characteristic_mapping< StartHandle, StartIndex, std::tuple< Chars... >, Options... > { static constexpr std::uint16_t last_characteristic_end_handle = next_characteristic_mapping< StartHandle, StartIndex, std::tuple< Chars... >, Options... >::last_characteristic_end_handle; using next = characteristic_index_mapping< StartHandle, StartIndex, Options... >; static std::uint16_t attribute_handle_by_index( std::size_t index ) { if ( index < next::end_index ) return next::characteristic_attribute_handle_by_index( index ); return next_characteristic_mapping< StartHandle, StartIndex, std::tuple< Chars... >, Options... >::attribute_handle_by_index( index ); } static std::size_t attribute_index_by_handle( std::uint16_t handle ) { if ( handle < next::end_handle ) return next::characteristic_attribute_index_by_handle( handle ); return next_characteristic_mapping< StartHandle, StartIndex, std::tuple< Chars... >, Options... >::attribute_index_by_handle( handle ); } }; template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename ... Options > struct service_start_handle { using start_handle_t = typename find_by_meta_type< attribute_handle_meta_type, Options..., attribute_handle< StartHandle > >::type; static constexpr std::uint16_t value = start_handle_t::attribute_handle_value; }; template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename ... Options > using next_char_mapping = interate_characteristic_index_mappings< service_start_handle< StartHandle, StartIndex, Options... >::value + 1, StartIndex + 1, typename find_all_by_meta_type< characteristic_meta_type, Options... >::type >; /* * Map index to handle within a single service */ template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename ... Options > struct service_index_mapping : next_char_mapping< StartHandle, StartIndex, Options... > { using service_t = ::bluetoe::service< Options... >; static constexpr std::uint16_t service_handle = service_start_handle< StartHandle, StartIndex, Options... >::value; static_assert( service_handle >= StartHandle, "attribute_handle<> can only be used to create increasing attribute handles." ); static constexpr std::uint16_t end_handle = next_char_mapping< StartHandle, StartIndex, Options... >::last_characteristic_end_handle; static constexpr std::uint16_t end_index = StartIndex + service_t::number_of_attributes; static std::uint16_t characteristic_handle_by_index( std::size_t index ) { if ( index == StartIndex ) return service_handle; return next_char_mapping< StartHandle, StartIndex, Options... >::attribute_handle_by_index( index ); } static std::size_t characteristic_first_index_by_handle( std::uint16_t handle ) { if ( handle <= service_handle ) return StartIndex; return next_char_mapping< StartHandle, StartIndex, Options... >::attribute_index_by_handle( handle ); } }; /* * Iterate over all services in a server */ template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename OptionTuple > struct interate_service_index_mappings; template < std::uint16_t StartHandle, std::uint16_t StartIndex > struct interate_service_index_mappings< StartHandle, StartIndex, std::tuple<> > { static std::uint16_t service_handle_by_index( std::size_t ) { return invalid_attribute_handle; } static std::size_t service_first_index_by_handle( std::uint16_t ) { return invalid_attribute_index; } }; template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename Services, typename ... Options > using next_service_mapping = interate_service_index_mappings< service_index_mapping< StartHandle, StartIndex, Options... >::end_handle, service_index_mapping< StartHandle, StartIndex, Options... >::end_index, Services >; template < std::uint16_t StartHandle, std::uint16_t StartIndex, typename ... Options, typename ... Services > struct interate_service_index_mappings< StartHandle, StartIndex, std::tuple< ::bluetoe::service< Options... >, Services... > > : service_index_mapping< StartHandle, StartIndex, Options... > , next_service_mapping< StartHandle, StartIndex, std::tuple< Services... >, Options... > { static std::uint16_t service_handle_by_index( std::size_t index ) { if ( index < service_index_mapping< StartHandle, StartIndex, Options... >::end_index ) return service_index_mapping< StartHandle, StartIndex, Options... >::characteristic_handle_by_index( index ); return next_service_mapping< StartHandle, StartIndex, std::tuple< Services... >, Options... >::service_handle_by_index( index ); } static std::size_t service_first_index_by_handle( std::uint16_t handle ) { if ( handle < service_index_mapping< StartHandle, StartIndex, Options... >::end_handle ) return service_index_mapping< StartHandle, StartIndex, Options... >::characteristic_first_index_by_handle( handle ); return next_service_mapping< StartHandle, StartIndex, std::tuple< Services... >, Options... >::service_first_index_by_handle( handle ); } }; /* * Interface, providing function to map from 0-based attribute index to ATT attribute handle and vice versa * * An attribute index is a 0-based into an array of all attributes contained in a server. Accessing the * attribute by table is very fast. If neither attribute_handle<> or attribute_handles<> is used, the mapping * is trivial and an index I is mapped to a handle I + 1. */ template < typename Server > struct handle_index_mapping; template < typename ... Options > struct handle_index_mapping< ::bluetoe::server< Options... > > : private interate_service_index_mappings< 1u, 0u, typename ::bluetoe::server< Options... >::services > { static constexpr std::size_t invalid_attribute_index = ::bluetoe::details::invalid_attribute_index; static constexpr std::uint16_t invalid_attribute_handle = ::bluetoe::details::invalid_attribute_handle; using iterator = interate_service_index_mappings< 1u, 0u, typename ::bluetoe::server< Options... >::services >; static std::uint16_t handle_by_index( std::size_t index ) { return iterator::service_handle_by_index( index ); } /** * @brief attribute index for a given handle * * Returns the index to the attribute with the lowest handle that is * equal or larger than the given handle. */ static std::size_t first_index_by_handle( std::uint16_t handle ) { return iterator::service_first_index_by_handle( handle ); } static std::size_t index_by_handle( std::uint16_t handle ) { std::size_t result = first_index_by_handle( handle ); if ( result != invalid_attribute_index && handle_by_index( result ) != handle ) result = invalid_attribute_index; return result; } }; } } #endif
45.643799
163
0.637493
cf25e5c06c8f4264e5dd840483da443534068a07
1,402
cpp
C++
earth_enterprise/src/third_party/sgl/v0_8_6/src/SkScan.cpp
ezeeyahoo/earthenterprise
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
[ "Apache-2.0" ]
2,661
2017-03-20T22:12:50.000Z
2022-03-30T09:43:19.000Z
earth_enterprise/src/third_party/sgl/v0_8_6/src/SkScan.cpp
ezeeyahoo/earthenterprise
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
[ "Apache-2.0" ]
1,531
2017-03-24T17:20:32.000Z
2022-03-16T18:11:14.000Z
earth_enterprise/src/third_party/sgl/v0_8_6/src/SkScan.cpp
ezeeyahoo/earthenterprise
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
[ "Apache-2.0" ]
990
2017-03-24T11:54:28.000Z
2022-03-22T11:51:47.000Z
/* libs/graphics/sgl/SkScan.cpp ** ** Copyright 2006, Google Inc. ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ #include "SkScan.h" #include "SkBlitter.h" #include "SkRegion.h" void SkScan::FillRect(const SkRect& rect, const SkRegion* clip, SkBlitter* blitter) { SkRect16 r; rect.round(&r); SkScan::FillDevRect(r, clip, blitter); } void SkScan::FillDevRect(const SkRect16& r, const SkRegion* clip, SkBlitter* blitter) { if (!r.isEmpty()) { if (clip) { SkRegion::Cliperator cliper(*clip, r); const SkRect16& rr = cliper.rect(); while (!cliper.done()) { blitter->blitRect(rr.fLeft, rr.fTop, rr.width(), rr.height()); cliper.next(); } } else blitter->blitRect(r.fLeft, r.fTop, r.width(), r.height()); } }
28.04
85
0.621969
cf26279b7f8fdff66c5b19b3d7b123f0c179dccd
739
cpp
C++
algorithms/implementation/AppendAndDelete.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
algorithms/implementation/AppendAndDelete.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
algorithms/implementation/AppendAndDelete.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; string appendAndDelete(string s, string t, int k) { if(s==t) return "Yes"; int i=0; while(s[i]==t[i]) i++; if( ( s.length()+t.length()-2*i ) > k ) return "No"; else if( (s.length()+t.length()-2*i) % 2 == k%2 ) return "Yes"; else if( (int)(s.length()+t.length()-k) < 0 ) return "Yes"; else return "No"; } int main() { ofstream fout(getenv("OUTPUT_PATH")); string s; getline(cin, s); string t; getline(cin, t); int k; cin >> k; cin.ignore(numeric_limits<streamsize>::max(), '\n'); string result = appendAndDelete(s, t, k); fout << result << "\n"; fout.close(); return 0; }
17.595238
56
0.515562
cf2697dcaaf5af85590c4600fd4bfac32c9c4d7e
549
cpp
C++
leetcode/easy/Add_Digits.cpp
HoussemBousmaha/Competitive-Programming
c4530fc01d8933bdfefec7fb6d31cd648e760334
[ "MIT" ]
6
2022-03-02T23:08:00.000Z
2022-03-07T07:26:48.000Z
leetcode/easy/Add_Digits.cpp
HoussemBousmaha/Competitive-Programming
c4530fc01d8933bdfefec7fb6d31cd648e760334
[ "MIT" ]
null
null
null
leetcode/easy/Add_Digits.cpp
HoussemBousmaha/Competitive-Programming
c4530fc01d8933bdfefec7fb6d31cd648e760334
[ "MIT" ]
null
null
null
class Solution { public: // int add_digits(int n) { // int ans = 0; // int k; // while (n != 0) { // k = n % 10; // ans += k; // n /= 10; // } // return ans; // } int addDigits(int n) { // while ((n / 10) != 0) { // n = add_digits(n); // } // return n; if (n == 0) return 0; return (n % 9 != 0 ? n % 9 : 9); } };
18.931034
42
0.256831
cf293d85b523041d2dfca0b8c7c7fa252e3fac76
469
cpp
C++
no3.cpp
bigdaddyjeff/JeffreyCSC102
dbdcbc50634b23ce7973c71329f4fdd2d3964927
[ "MIT" ]
null
null
null
no3.cpp
bigdaddyjeff/JeffreyCSC102
dbdcbc50634b23ce7973c71329f4fdd2d3964927
[ "MIT" ]
null
null
null
no3.cpp
bigdaddyjeff/JeffreyCSC102
dbdcbc50634b23ce7973c71329f4fdd2d3964927
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int var = 789; int *ptr2; int **ptr1; ptr2 = &var; ptr1 = &ptr2; cout << "The value of var = "<< var << endl; cout << "Content value of single pointer ptr2 = " << *ptr2 << endl; cout << "address value of single pointer ptr2 = " << ptr2 << endl; cout << "Content value of double pointer ptr1 = " << **ptr1 << endl; cout << "address value of double pointer ptr1 = " << ptr1 << endl; }
27.588235
71
0.58209
cf2a28aa2539b4286c59835f605a6abdd6eda519
18,747
cpp
C++
IP/IMap.cpp
bharat-varma/Software-Engineering
36cdff296010e1076fb440707bfb2424110308ca
[ "Apache-2.0" ]
null
null
null
IP/IMap.cpp
bharat-varma/Software-Engineering
36cdff296010e1076fb440707bfb2424110308ca
[ "Apache-2.0" ]
3
2017-12-09T03:16:32.000Z
2017-12-15T04:22:08.000Z
IP/IMap.cpp
bharat-varma/Software-Engineering
36cdff296010e1076fb440707bfb2424110308ca
[ "Apache-2.0" ]
1
2017-09-19T00:28:47.000Z
2017-09-19T00:28:47.000Z
#include <map> #include <set> #include <vector> #include <algorithm> #include <cstdlib> #include <stack> #include <cmath> using namespace std; class IntMap { public: static const long serialVersionUID = 1L; static const int FREE_KEY = 0; static const int NO_VALUE = 0; /** Keys and values */ vector<int> m_data; /** Do we have 'free' key in the map? */ bool m_hasFreeKey; /** Value of 'free' key */ int m_freeValue; /** Fill factor, must be between (0 and 1) */ float m_fillFactor; /** We will resize a map once it reaches this size */ int m_threshold; /** Current map size */ int m_size; /** Mask to calculate the original position */ int m_mask; int m_mask2; IntMap(); IntMap(int size); IntMap(int size, float fillFactor); int get(int key); // for use as IntSet - Paul Tarau bool contains(int key); bool add(int key); bool del(int key); bool isEmpty(); static void intersect0(IntMap &m, vector<IntMap> & maps, vector<IntMap> & vmaps, stack<int> r); static stack<int> * intersect(vector<IntMap> & maps, vector<IntMap> & vmaps); // end changes int put(int key, int value); int remove(int key); int shiftKeys(int pos); int size(); string show(); void rehash(int newCapacity); /** Taken from FastUtil implementation */ /** Return the least power of two greater than or equal to the specified value. * * <p>Note that this function will return 1 when the argument is 0. * * @param x a long integer smaller than or equal to 2<sup>62</sup>. * @return the least power of two greater than or equal to the specified value. */ static long nextPowerOfTwo(long x); /** Returns the least power of two smaller than or equal to 2<sup>30</sup> * and larger than or equal to <code>Math.ceil( expected / f )</code>. * * @param expected the expected number of elements in a hash table. * @param f the load factor. * @return the minimum possible size for a backing array. * @throws IllegalArgumentException if the necessary size is larger than 2<sup>30</sup>. */ static int arraySize(int expected, float f); //taken from FastUtil static const int INT_PHI = 0x9E3779B9; int static phiMix(int x); }; IntMap::IntMap():IntMap(1<<2) { //this(1 << 2); } IntMap::IntMap(int size):IntMap(size, 0.75f) { //this(size, 0.75f); } IntMap::IntMap(int size, float fillFactor) { //if (fillFactor <= 0 || fillFactor >= 1) // throw new IllegalArgumentException("FillFactor must be in (0, 1)"); //if (size <= 0) // throw new IllegalArgumentException("Size must be positive!"); int capacity = arraySize(size, fillFactor); m_mask = capacity - 1; m_mask2 = capacity * 2 - 1; m_fillFactor = fillFactor; m_data.resize(capacity * 2); m_threshold = (int) (capacity * fillFactor); } int IntMap::get(int key) { int ptr = (phiMix(key) & m_mask) << 1; if (key == FREE_KEY) return m_hasFreeKey ? m_freeValue : NO_VALUE; int k = m_data[ptr]; if (k == FREE_KEY) return NO_VALUE; //end of chain already if (k == key) //we check FREE prior to this call return m_data[ptr + 1]; while (true) { ptr = ptr + 2 & m_mask2; //that's next index k = m_data[ptr]; if (k == FREE_KEY) return NO_VALUE; if (k == key) return m_data[ptr + 1]; } } // for use as IntSet - Paul Tarau bool IntMap::contains(int key) { return NO_VALUE != get(key); } bool IntMap::add(int key) { return NO_VALUE != put(key, 666); } bool IntMap::del(int key) { return NO_VALUE != remove(key); } bool IntMap::isEmpty() { return 0 == m_size; } void IntMap::intersect0(IntMap &m, vector<IntMap> & maps, vector<IntMap> & vmaps, stack<int> r) { vector<int> & data = m.m_data; for (int k = 0; k < data.size(); k += 2) { bool found = true; int key = data[k]; if (FREE_KEY == key) { continue; } for (int i = 1; i < maps.size(); i++) { IntMap map = maps[i]; int val = map.get(key); if (NO_VALUE == val) { IntMap vmap = vmaps[i]; int vval = vmap.get(key); if (NO_VALUE == vval) { found = false; break; } } } if (found) { r.push(key); } } } stack<int> * IntMap::intersect(vector<IntMap> & maps, vector<IntMap> & vmaps) { stack<int> *r = new stack<int>; intersect0(maps[0], maps, vmaps, *r); intersect0(vmaps[0], maps, vmaps, *r); return r; } // end changes int IntMap::put(int key, int value) { if (key == FREE_KEY) { int ret = m_freeValue; if (!m_hasFreeKey) { ++m_size; } m_hasFreeKey = true; m_freeValue = value; return ret; } int ptr = (phiMix(key) & m_mask) << 1; int k = m_data[ptr]; if (k == FREE_KEY) //end of chain already { m_data[ptr] = key; m_data[ptr + 1] = value; if (m_size >= m_threshold) { rehash(m_data.size() * 2); //size is set inside } else { ++m_size; } return NO_VALUE; } else if (k == key) //we check FREE prior to this call { int ret = m_data[ptr + 1]; m_data[ptr + 1] = value; return ret; } while (true) { ptr = ptr + 2 & m_mask2; //that's next index calculation k = m_data[ptr]; if (k == FREE_KEY) { m_data[ptr] = key; m_data[ptr + 1] = value; if (m_size >= m_threshold) { rehash(m_data.size() * 2); //size is set inside } else { ++m_size; } return NO_VALUE; } else if (k == key) { int ret = m_data[ptr + 1]; m_data[ptr + 1] = value; return ret; } } } int IntMap::remove(int key) { if (key == FREE_KEY) { if (!m_hasFreeKey) return NO_VALUE; m_hasFreeKey = false; --m_size; return m_freeValue; //value is not cleaned } int ptr = (phiMix(key) & m_mask) << 1; int k = m_data[ptr]; if (k == key) //we check FREE prior to this call { int res = m_data[ptr + 1]; shiftKeys(ptr); --m_size; return res; } else if (k == FREE_KEY) return NO_VALUE; //end of chain already while (true) { ptr = ptr + 2 & m_mask2; //that's next index calculation k = m_data[ptr]; if (k == key) { int res = m_data[ptr + 1]; shiftKeys(ptr); --m_size; return res; } else if (k == FREE_KEY) return NO_VALUE; } } int IntMap::shiftKeys(int pos) { // Shift entries with the same hash. int last, slot; int k; vector<int> & data = m_data; while (true) { pos = (last = pos) + 2 & m_mask2; while (true) { if ((k = data[pos]) == FREE_KEY) { data[last] = FREE_KEY; return last; } slot = (phiMix(k) & m_mask) << 1; //calculate the starting slot for the current key if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos) { break; } pos = pos + 2 & m_mask2; //go to the next entry } data[last] = k; data[last + 1] = data[pos + 1]; } } int IntMap::size() { return m_size; } void IntMap::rehash(int newCapacity) { m_threshold = (int) (newCapacity / 2 * m_fillFactor); m_mask = newCapacity / 2 - 1; m_mask2 = newCapacity - 1; int oldCapacity = m_data.size(); vector<int> & oldData = m_data; m_data.resize(newCapacity); m_size = m_hasFreeKey ? 1 : 0; for (int i = 0; i < oldCapacity; i += 2) { int oldKey = oldData[i]; if (oldKey != FREE_KEY) { put(oldKey, oldData[i + 1]); } } } /** Taken from FastUtil implementation */ /** Return the least power of two greater than or equal to the specified value. * * <p>Note that this function will return 1 when the argument is 0. * * @param x a long integer smaller than or equal to 2<sup>62</sup>. * @return the least power of two greater than or equal to the specified value. */ long IntMap::nextPowerOfTwo(long x) { if (x == 0) return 1; x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return (x | x >> 32) + 1; } /** Returns the least power of two smaller than or equal to 2<sup>30</sup> * and larger than or equal to <code>Math.ceil( expected / f )</code>. * * @param expected the expected number of elements in a hash table. * @param f the load factor. * @return the minimum possible size for a backing array. * @throws IllegalArgumentException if the necessary size is larger than 2<sup>30</sup>. */ int IntMap::arraySize(int expected, float f) { long s = max(2l, nextPowerOfTwo((long) ceil(expected / f))); if (s > 1 << 30) return -1; //throw new IllegalArgumentException("Too large (" + expected + " expected elements with load factor " + f + ")"); return (int) s; } int IntMap::phiMix(int x) { int h = x * INT_PHI; return h ^ h >> 16; } string IntMap::show() { string b = "{"; int l = m_data.size(); bool first = true; for (int i = 0; i < l; i += 2) { int v = m_data[i]; if (v != FREE_KEY) { if (!first) { b += ","; } first = false; b+=v-1;; } } b+="}"; return b; } template <class K> class IMap { public: static const long serialVersionUID = 1L; map<K, IntMap*> mp; vector<K> mp_lst; IMap(); void clear(); bool put(K key, int val); IntMap get(K key); IntMap putget(K key); bool remove(K key, int val); bool remove(K key); int size(); //set<K> keySet(); static string show(vector<IMap<int> > imaps); static vector<IMap<int> > * create(int l); static bool put(vector<IMap<int> > imaps, int pos, int key, int val); static bool put(vector<IMap<int> > *imaps, int pos, int key, int val); static vector<int> * get(vector<IMap<int> > *iMaps, vector<IntMap> vmaps, vector<int> keys); string show(); }; template<class K> IMap<K>::IMap() { } template<class K> void IMap<K>::clear() { mp.clear(); } template<class K> bool IMap<K>::put(K key, int val) { if(mp.find(key) == mp.end()) { mp[key] = new IntMap(); } mp[key]->add(val); /* IntMap vals = mp.get(key); if (null == vals) { vals = new IntMap(); map.put(key, vals); } return vals.add(val); */ return mp[key]->add(val); } template<class K> IntMap IMap<K>::putget(K key) { //IntMap *s; if(mp.find(key) == mp.end()) //if(!mp.contains(key)) { //s = new IntMap(); return IntMap(); } else { //s = mp[key]; return *mp[key]; } /* IntMap s = map.get(key); if (null == s) { s = new IntMap(); } */ //return s; } template<class K> void remove_key(map<K,IntMap*> &mp, vector<K> mp_lst, K k) { auto element = mp.find(k); mp.erase(element); for(int i = 0; i < mp_lst.size(); i++) { if(mp_lst[i] == k) { mp_lst.erase(mp_lst.begin()+i); return; } } } template<class K> bool IMap<K>::remove(K key, int val) { IntMap vals = get(key); bool ok = vals.del(val); if (vals.isEmpty()) { remove_key(mp, mp_lst, key); // mp.remove(key); } return ok; } template<class K> bool IMap<K>::remove(K key) { bool ret = mp.find(key) != mp.end(); remove_key(mp, mp_lst, key); return ret; //return 0 != mp.remove(key); } template<class K> int IMap<K>::size() { int s = 0; for(const auto & k : mp_lst) { //IntMap *mp[k] s += get(k).size(); } /* Iterator<K> I = mp.keySet().iterator(); int s = 0; while (I.hasNext()) { K key = I.next(); IntMap vals = get(key); s += vals.size(); }*/ return s; } /* template<class K> set<K> IMap<K>::keySet() { set<K> s; for(const auto & k : mp_lst) { s.push(k); } return s; } */ /* Iterator<K> keyIterator() { return keySet().iterator(); }*/ /* @Override public String toString() { return map.toString(); }*/ // specialization for array of int maps template<class K> vector<IMap<int> > * IMap<K>::create(int l) { IMap<int> first = IMap<int>(); vector<IMap<int> >* imaps = new vector<IMap<int> >(l);// = (IMap<int>[]) java.lang.reflect.Array.newInstance(first.getClass(), l); // imaps = (IMap<int>[]) java.lang.reflect.Array.newInstance(first.getClass(), l); //new IMap[l]; (*imaps)[0] = first; for (int i = 1; i < l; i++) { (*imaps)[i] = IMap<int>(); } return imaps; } template<class K> bool IMap<K>::put(vector<IMap<int> > imaps, int pos, int key, int val) { return imaps[pos].put(key, val); } template<class K> bool IMap<K>::put(vector<IMap<int> >* imaps, int pos, int key, int val) { return ((*imaps)[pos]).put(key, val); } template<class K> vector<int> * IMap<K>::get(vector<IMap<int> > *iMaps, vector<IntMap> vmaps, vector<int> keys) { int l = iMaps->size(); vector<IntMap> ms; // = new ArrayList<IntMap>(); vector<IntMap> vms; // = new ArrayList<IntMap>(); for (int i = 0; i < l; i++) { int key = keys[i]; if (0 == key) { continue; } //Main.pp("i=" + i + " ,key=" + key); IntMap m = (*iMaps)[i].get(key); //Main.pp("m=" + m); ms.push_back(m); vms.push_back(vmaps[i]); } vector<IntMap> ims(ms.size());// = new IntMap[ms.size()]; vector<IntMap> vims(vms.size());// = new IntMap[vms.size()]; for (int i = 0; i < ims.size(); i++) { IntMap im = ms[i]; ims[i] = im; IntMap vim = vms[i]; vims[i] = vim; } //Main.pp("-------ims=" + Arrays.toString(ims)); //Main.pp("-------vims=" + Arrays.toString(vims)); stack<int> *cs = IntMap::intersect(ims, vims); // $$$ add vmaps here //vector<int> *is = new vector<int>(); int n = cs->size(); //int[] is = cs.toArray(); vector<int> *is = new vector<int>(n); for(int i=n-1;i>=0;i--) { (*is)[i] = cs->top(); cs->pop(); } delete cs; for (int i = 0; i < is->size(); i++) { (*is)[i] = (*is)[i] - 1; } sort(is->begin(), is->end()); //java.util.Arrays.sort(is); return is; } template<class K> string IMap<K>::show() { string s = ""; for(K k : mp_lst) { //char buffer[256]; //sprintf(buffer, "%d : ") //s += k + " : " + mp[k]; // s += ","; } return s; } template<class K> IntMap IMap<K>::get(K key) { if(mp.find(key) == mp.end()) { return IntMap(); } return *mp[key]; /* return mp[key]; IntMap s = map.get(key); if (null == s) { s = new IntMap(); } return s; */ } template<class K> string IMap<K>::show(vector<IMap<int> > imaps) { string s = ""; for(auto x : imaps) { s += x.show(); } return s; //Arrays.toString(imaps); } /* string show(vector<int> is) { return Arrays.toString(is); }*/ // end /* int main() { vector<IMap<int> > *imaps = IMap<int>::create(3); printf("1\n"); IMap<int>::put(*imaps, 0, 10, 100); IMap<int>::put(*imaps, 1, 20, 200); IMap<int>::put(*imaps, 2, 30, 777); IMap<int>::put(*imaps, 0, 10, 1000); IMap<int>::put(*imaps, 1, 20, 777); IMap<int>::put(*imaps, 2, 30, 3000); IMap<int>::put(*imaps, 0, 10, 777); IMap<int>::put(*imaps, 1, 20, 20000); IMap<int>::put(*imaps, 2, 30, 30000); IMap<int>::put(*imaps, 0, 10, 888); IMap<int>::put(*imaps, 1, 20, 888); IMap<int>::put(*imaps, 2, 30, 888); IMap<int>::put(*imaps, 0, 10, 0); IMap<int>::put(*imaps, 1, 20, 0); IMap<int>::put(*imaps, 2, 30, 0); return 0; } */ template class IMap<int>; #define IA 16807 #define IM 2147483647 #define IQ 127773 #define IR 2836 #define NTAB 32 #define EPS (1.2E-07) #define MAX(a,b) (a>b)?a:b #define MIN(a,b) (a<b)?a:b double ran1(int *idum) { int j,k; static int iv[NTAB],iy=0; void nrerror(); static double NDIV = 1.0/(1.0+(IM-1.0)/NTAB); static double RNMX = (1.0-EPS); static double AM = (1.0/IM); if ((*idum <= 0) || (iy == 0)) { *idum = MAX(-*idum,*idum); for(j=NTAB+7;j>=0;j--) { k = *idum/IQ; *idum = IA*(*idum-k*IQ)-IR*k; if(*idum < 0) *idum += IM; if(j < NTAB) iv[j] = *idum; } iy = iv[0]; } k = *idum/IQ; *idum = IA*(*idum-k*IQ)-IR*k; if(*idum<0) *idum += IM; j = iy*NDIV; iy = iv[j]; iv[j] = *idum; return MIN(AM*iy,RNMX); } int random_int(int *seed, int a, int b) { return (b-a)*ran1(seed)+a; } int main(int argc, char **argv) { int seed = -1; if(argc>1) { seed = atoi(argv[1]); if(seed > 0) seed = -seed; } vector<IMap<int> > *imaps = IMap<int>::create(3); int a = random_int(&seed, 1,5)*7; int b = random_int(&seed, 1,5)*5; int c = random_int(&seed, 1,5)*3; int va = random_int(&seed, 1,1000); int vb = random_int(&seed, 1,1000); int vc = random_int(&seed, 1,1000); IMap<int>::put(imaps, 0, a, va); IMap<int>::put(imaps, 1, b, vb); IMap<int>::put(imaps, 2, c, vc); printf("%d %d\n", a, (*imaps)[0].get(a).get(va)); printf("%d %d\n", b, (*imaps)[1].get(b).get(vb)); printf("%d %d\n", c, (*imaps)[2].get(c).get(vc)); va = random_int(&seed, 1,1000); vb = random_int(&seed, 1,1000); vc = random_int(&seed, 1,1000); IMap<int>::put(*imaps, 0, a, va); IMap<int>::put(*imaps, 1, b, vb); IMap<int>::put(*imaps, 2, c, vc); printf("%d %d\n", a, (*imaps)[0].get(a).get(va)); printf("%d %d\n", b, (*imaps)[1].get(b).get(vb)); printf("%d %d\n", c, (*imaps)[2].get(c).get(vc)); printf("%d %d\n", c, (*imaps)[2].get(c).get(vc+1)); va = random_int(&seed, 1,1000); vb = random_int(&seed, 1,1000); vc = random_int(&seed, 1,1000); IMap<int>::put(*imaps, 0, a, va); IMap<int>::put(*imaps, 1, b, vb); IMap<int>::put(*imaps, 2, c, vc); va = random_int(&seed, 1,1000); vb = random_int(&seed, 1,1000); vc = random_int(&seed, 1,1000); IMap<int>::put(*imaps, 0, a, va); IMap<int>::put(*imaps, 1, b, vb); IMap<int>::put(*imaps, 2, c, vc); IMap<int>::put(*imaps, 0, a, 0); IMap<int>::put(*imaps, 1, b, 0); IMap<int>::put(*imaps, 2, c, 0); printf("%d %d\n", a, (*imaps)[0].get(a).get(va)); printf("%d %d\n", b, (*imaps)[1].get(b).get(vb)); printf("%d %d\n", c, (*imaps)[2].get(c).get(vc)); printf("%d %d\n", c, (*imaps)[2].get(c).get(vc+1)); return 0; }
22.081272
134
0.53886
cf2eed74523c5d43661f04cba155aa1d24e3eba1
45,612
cpp
C++
stlsoft/samples/whereis/whereis.cpp
masscry/dmc
c7638f7c524a65bc2af0876c76621d8a11da42bb
[ "BSL-1.0" ]
86
2018-05-24T12:03:44.000Z
2022-03-13T03:01:25.000Z
stlsoft/samples/whereis/whereis.cpp
masscry/dmc
c7638f7c524a65bc2af0876c76621d8a11da42bb
[ "BSL-1.0" ]
1
2019-05-30T01:38:40.000Z
2019-10-26T07:15:01.000Z
stlsoft/samples/whereis/whereis.cpp
masscry/dmc
c7638f7c524a65bc2af0876c76621d8a11da42bb
[ "BSL-1.0" ]
14
2018-07-16T08:29:12.000Z
2021-08-23T06:21:30.000Z
/* ///////////////////////////////////////////////////////////////////////////// * File: whereis.cpp * * Purpose: Implementation file for the Synesis Software whereis utility * * Created: 19th January 1996 * Updated: 16th August 2004 * * Author: Matthew Wilson, Synesis Software Pty Ltd. * * The timestr() function and the verbose formatting in trace_file * used by kind permission of Walter Bright and Digital Mars. * * License: (Licensed under the Synesis Software Standard Public License) * * Copyright (C) 1999-2004, Synesis Software Pty Ltd. * Copyright (C) 1987-2004, Digital Mars. * * All rights reserved. * * www: http://www.synesis.com.au * http://www.synesis.com.au/software * * http://www.digitalmars.com/ * * email: software@synesis.com.au * * contact@digitalmars.com * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * (i) Redistributions of source code must retain the above * copyright notice and contact information, this list of * conditions and the following disclaimer. * * (ii) Redistributions in binary form must reproduce the above * copyright notice and contact information, this list of * conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * (iii) Any derived versions of this software (howsoever modified) * remain the sole property of Synesis Software. * * (iv) Any derived versions of this software (howsoever modified) * remain subject to all these conditions. * * (v) Neither the name of Synesis Software nor the names of any * subdivisions, employees or agents of Synesis Software, nor the * names of any other contributors to this software may be used to * endorse or promote products derived from this software without * specific prior written permission. * * This source code is provided by Synesis Software "as is" and any * warranties, whether expressed or implied, including, but not * limited to, the implied warranties of merchantability and * fitness for a particular purpose are disclaimed. In no event * shall the Synesis Software 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. * * ////////////////////////////////////////////////////////////////////////// */ /* ///////////////////////////////////////////////////////////////////////////// * Includes */ #include <stdio.h> #include <stlsoft.h> stlsoft_ns_using(ss_uint_t) stlsoft_ns_using(ss_sint64_t) stlsoft_ns_using(ss_bool_t) /* Regrettably, something in this program is too complex for early versions of * many compilers that the STLSoft libraries support. With some it is a compiler * issue, with others it either crashes or produces erroneous output. Thus, the * following restrictions are mandated: */ #if defined(__STLSOFT_COMPILER_IS_BORLAND) # if __BORLANDC__ < 0x0560 # error whereis.cpp cannot be successfully built by Borland C/C++ prior to version 5.6 # endif /* __BORLANDC__ < 0x0560 */ #elif defined(__STLSOFT_COMPILER_IS_DMC) # if __DMC__ < 0x0832 # error whereis.cpp cannot be successfully built by Digital Mars C/C++ prior to version 8.32 # endif /* __DMC__ < 0x0832 */ #elif defined(__STLSOFT_COMPILER_IS_GCC) # if __GNUC__ < 3 && \ __GNUC_MINOR__ < 95 # error whereis.cpp cannot be successfully built by GNU C/C++ prior to version 6.0 # endif /* __GNUC__ < 3 && __GNUC_MINOR__ < 95 */ #elif defined(__STLSOFT_COMPILER_IS_INTEL) # if __INTEL_COMPILER < 600 # error whereis.cpp cannot be successfully built by Intel C/C++ prior to version 6.0 # endif /* __INTEL_COMPILER < 600 */ #elif defined(__STLSOFT_COMPILER_IS_MWERKS) /* No problems with Metrowerks */ #elif defined(__STLSOFT_COMPILER_IS_MSVC) # if _MSC_VER < 1100 # error whereis.cpp cannot be successfully built by Microsoft Visual C/C++ prior to version 5.0 # endif /* _MSC_VER < 1100 */ #else # error Unrecognised compiler #endif /* compiler */ /* ///////////////////////////////////////////////////////////////////////////// * Warnings */ #if defined(__STLSOFT_COMPILER_IS_MSVC) # pragma warning(disable : 4702) #endif /* __STLSOFT_COMPILER_IS_INTEL */ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef _SYNSOFT_INTERNAL_BUILD # include "MLCompId.h" #else /* ? _SYNSOFT_INTERNAL_BUILD */ # define _nameSynesisSoftware "Synesis Software (Pty) Ltd" # define _wwwSynesisSoftware_SystemTools "http://synesis.com.au/systools.html" # define _emailSynesisSoftware_SystemTools "software@synesis.com.au" #endif /* _SYNSOFT_INTERNAL_BUILD */ /* ////////////////////////////////////////////////////////////////////////// */ #include <stlsoft_auto_buffer.h> stlsoft_ns_using(auto_buffer) #include <stlsoft_limit_traits.h> #include <stlsoft_malloc_allocator.h> stlsoft_ns_using(malloc_allocator) #include <stlsoft_string_access.h> stlsoft_ns_using(c_str_ptr) #include <stlsoft_simple_algorithms.h> stlsoft_ns_using(remove_duplicates_from_unordered_sequence) #include <stlsoft_string_tokeniser.h> stlsoft_ns_using(string_tokeniser) #if defined(UNIX) || \ defined(unix) || \ defined(__unix) || \ defined(__unix__) || \ ( defined(__xlC__) && \ defined(_POWER) && \ defined(_AIX)) /* UNIX includes */ # define WHEREIS_PLATFORM_IS_UNIX # include <unixstl.h> namespace platform_stl = unixstl; # include <unixstl_file_path_buffer.h> typedef unixstl_ns_qual(file_path_buffer_a) file_path_buffer; # include <unixstl_findfile_sequence.h> unixstl_ns_using(findfile_sequence) # include <unixstl_functionals.h> unixstl_ns_using(compare_path) # include <unixstl_environment_variable.h> unixstl_ns_using(basic_environment_variable) # include <unixstl_current_directory.h> unixstl_ns_using(basic_current_directory) # include <unixstl_filesystem_traits.h> unixstl_ns_using(filesystem_traits) # include <time.h> # include <sys/types.h> # include <sys/stat.h> #elif defined(WIN32) || \ defined(_WIN32) /* Win32 includes */ # define WHEREIS_PLATFORM_IS_WIN32 # include <winstl.h> namespace platform_stl = winstl; # include <winstl_file_path_buffer.h> typedef winstl_ns_qual(file_path_buffer_a) file_path_buffer; # include <winstl_findfile_sequence.h> typedef winstl_ns_qual(findfile_sequence_a) findfile_sequence; # include <winstl_functionals.h> winstl_ns_using(compare_path) # include <winstl_environment_variable.h> winstl_ns_using(basic_environment_variable) # include <winstl_current_directory.h> winstl_ns_using(basic_current_directory) # include <winstl_filesystem_traits.h> winstl_ns_using(filesystem_traits) #else # error Operating system not recognised #endif /* operating system */ #include <algorithm> stlsoft_ns_using_std(copy) stlsoft_ns_using_std(for_each) stlsoft_ns_using_std(remove_if) #include <functional> stlsoft_ns_using_std(unary_function) #include <iterator> stlsoft_ns_using_std(back_inserter) #include <string> stlsoft_ns_using_std(string) #include <vector> stlsoft_ns_using_std(vector) #include <list> stlsoft_ns_using_std(list) #include <map> stlsoft_ns_using_std(map) #ifdef _SYNSOFT_INTERNAL_BUILD # include <MRPathFn.h> # ifdef WHEREIS_PLATFORM_IS_WIN32 # define WHEREIS_USING_WIN32_VERSION_INFO # include <MWVerInf.h> # endif /* platform */ #endif /* _SYNSOFT_INTERNAL_BUILD */ /* ///////////////////////////////////////////////////////////////////////////// * Warnings */ #if defined(__STLSOFT_COMPILER_IS_INTEL) # pragma warning(disable : 383) # pragma warning(disable : 444) # pragma warning(disable : 1419) #endif /* __STLSOFT_COMPILER_IS_INTEL */ /* ///////////////////////////////////////////////////////////////////////////// * Tracing */ //#define WHEREIS_TRACE #if !defined(WHEREIS_TRACE) && \ defined(_DEBUG) # define WHEREIS_TRACE #endif /* !WHEREIS_TRACE && _DEBUG */ /* ///////////////////////////////////////////////////////////////////////////// * Version information * * Normally, Synesis Software components & tools are "versioned" by making use * of tool-generated header files, one of which - MBldHdr.h - defines symbolic * constants representing major, minor, revision and build numbers. * * * Since this file is to be available in a more public forum, including on the * Digital Mars site, these constants are merely defined here, rather than * encumber any developers who may wish to compile it with a lot of * Synesis-specific gunk. */ #ifdef _SYNSOFT_INTERNAL_BUILD # include "MBldHdr.h" # include "showver.h" extern "C" const int _mccVerHi = __SYV_MAJOR; extern "C" const int _mccVerLo = __SYV_MINOR; extern "C" const int _mccVerRev = __SYV_REVISION; extern "C" const int _mccBldNum = __SYV_BUILDNUMBER; #else /* ? _SYNSOFT_INTERNAL_BUILD */ extern "C" const int _mccVerHi = 1; extern "C" const int _mccVerLo = 12; extern "C" const int _mccVerRev = 1; extern "C" const int _mccBldNum = 52; #endif /* _SYNSOFT_INTERNAL_BUILD */ # define COMPANY_NAME "Synesis Software" # define TOOL_NAME "File Searching" # define EXE_NAME "whereis" /* ///////////////////////////////////////////////////////////////////////////// * Typedefs */ typedef string_tokeniser<string, char> tokeniser_string_t; typedef vector<string> searchpath_sorted_t; //typedef list<string> searchpath_sorted_t; typedef map<string, unsigned> extension_map_t; #if defined(WHEREIS_PLATFORM_IS_WIN32) typedef FILETIME whereis_time_t; #elif defined(WHEREIS_PLATFORM_IS_UNIX) typedef time_t whereis_time_t; #else # error Unknown platform #endif /* platform */ /* ///////////////////////////////////////////////////////////////////////////// * Enumerations */ namespace Trim { enum Trim { full , fileOnly , fromSearchRoot , fromCurrentDirectory }; } // namespace Trim namespace Flags { enum { verbose = 0x00000001 , showVersionInfo = 0x00000002 , showFiles = 0x00000004 , showDirectories = 0x00000008 , markDirectories = 0x00000010 }; } // namespace Flags /* ///////////////////////////////////////////////////////////////////////////// * Macros and definitions * * Visual C++, sigh. uses %I64d", rather than "%lld", so that is abstracted here */ #if defined(__STLSOFT_COMPILER_IS_BORLAND) || \ /* defined(__STLSOFT_COMPILER_IS_GCC) || */ \ defined(__STLSOFT_COMPILER_IS_INTEL) || \ defined(__STLSOFT_COMPILER_IS_MSVC) # define FMT_SINT64_WIDTH_(x) "%" #x "I64d" #else # define FMT_SINT64_WIDTH_(x) "%" #x "lld" #endif /* compiler */ /* ///////////////////////////////////////////////////////////////////////////// * Constants */ #ifdef __STLSOFT_COMPILER_IS_INTEL # pragma warning(disable : 1418) #endif /* __STLSOFT_COMPILER_IS_INTEL */ /* Multi-part path/pattern delimiter */ #if defined(__STLSOFT_COMPILER_IS_MSVC) && \ _MSC_VER < 1300 char const PATH_SEPARATOR = ';'; #else /* ? compiler */ char const PATH_SEPARATOR = filesystem_traits<char>::path_separator(); #endif /* compiler */ /* Path component delimiter */ #if defined(__STLSOFT_COMPILER_IS_MSVC) && \ _MSC_VER < 1300 char const PATH_NAME_SEPARATOR = '\\'; #else /* ? compiler */ char const PATH_NAME_SEPARATOR = filesystem_traits<char>::path_name_separator(); #endif /* compiler */ /* Subdirectory wildcard pattern */ #if defined(__STLSOFT_COMPILER_IS_MSVC) && \ _MSC_VER < 1300 char const *PATTERN_ALL = "*.*"; #else /* ? compiler */ char const *PATTERN_ALL = filesystem_traits<char>::pattern_all(); #endif /* compiler */ /* Illegal pattern characters string */ #if defined(_MSC_VER) /* For testing */ || \ defined(WHEREIS_PLATFORM_IS_WIN32) char const *BAD_PATTERN_CHARS = ":\\"; #elif defined(WHEREIS_PLATFORM_IS_UNIX) char const *BAD_PATTERN_CHARS = "/"; #else # error Unknown platform #endif /* platform */ #ifdef __STLSOFT_COMPILER_IS_INTEL # pragma warning(default : 1418) #endif /* __STLSOFT_COMPILER_IS_INTEL */ /* ///////////////////////////////////////////////////////////////////////////// * Function declarations * * (Primarily to keep Metrowerks happy, but that's a good thing to do!) */ static char *timestr(char *buffer, size_t cchBuffer, whereis_time_t const *ft); // Make Metrowerks happy /* ///////////////////////////////////////////////////////////////////////////// * Global variables */ static file_path_buffer s_root; static extension_map_t s_extMap; /* ///////////////////////////////////////////////////////////////////////////// * Helper Functions */ char *timestr(char *buffer, size_t cchBuffer, whereis_time_t const *t) { #if defined(WHEREIS_PLATFORM_IS_WIN32) FILETIME ftLocal; SYSTEMTIME st; char dateString[41]; char timeString[41]; ::FileTimeToLocalFileTime(t, &ftLocal); ::FileTimeToSystemTime(&ftLocal, &st); ::GetDateFormat(LOCALE_USER_DEFAULT, 0, &st, NULL, dateString, stlsoft_num_elements(dateString)); ::GetTimeFormat(LOCALE_USER_DEFAULT, 0, &st, NULL, timeString, stlsoft_num_elements(timeString)); #if 0 // Digital Mars format (US based) sprintf(buffer, "%02d/%02d/%02d %2d:%02d", st.wMonth, st.wDay, st.wYear % 100, st.wHour, st.wMinute); #else /* ? 0 */ // User-locale format sprintf(buffer, "%-10s %-s", dateString, timeString); #endif /* 0 */ STLSOFT_SUPPRESS_UNUSED(cchBuffer); #elif defined(WHEREIS_PLATFORM_IS_UNIX) struct tm tm_ = *localtime(t); strftime(buffer, cchBuffer, "%c", &tm_); #else # error Unknown platform #endif /* platform */ return buffer; } static char *copy_entry_filename(char *dest, findfile_sequence::value_type const &entry) { #if defined(WHEREIS_PLATFORM_IS_WIN32) return strcpy(dest, entry.get_filename()); #elif defined(WHEREIS_PLATFORM_IS_UNIX) // Use the get_full_path_name() file_path_buffer buffer; char *pFile = NULL; size_t cch = platform_stl::filesystem_traits<char>::get_full_path_name(entry, buffer.size(), &buffer[0], &pFile); STLSOFT_SUPPRESS_UNUSED(cch); return strcpy(dest, pFile); #else # error Unknown platform #endif /* platform */ } /* ///////////////////////////////////////////////////////////////////////////// * Functionals */ // struct trace_file // // This functional traces individual file records to stdout. struct trace_file : public unary_function<findfile_sequence::value_type const &, void> { typedef trace_file class_type; public: trace_file(char const *searchRoot, Trim::Trim trim, ss_uint_t flags) : m_flags(flags) , m_searchRoot(searchRoot) , m_trim(trim) {} void operator ()(findfile_sequence::value_type const &entry) const { file_path_buffer path; switch(m_trim) { default: stlsoft_assert(0); case Trim::full: strcpy(&path[0], c_str_ptr(entry)); break; case Trim::fileOnly: copy_entry_filename(&path[0], entry); break; #if defined(_SYNSOFT_INTERNAL_BUILD) && \ defined(WHEREIS_PLATFORM_IS_WIN32) case Trim::fromSearchRoot: SynesisCrt::deriverelativepath(stlsoft_ns_qual(c_str_ptr)(entry), m_searchRoot, &path[0]); break; case Trim::fromCurrentDirectory: SynesisCrt::deriverelativepath(stlsoft_ns_qual(c_str_ptr)(entry), stlsoft_ns_qual(c_str_ptr)(s_root), &path[0]); break; #endif /* _SYNSOFT_INTERNAL_BUILD */ } if(m_flags & Flags::verbose) { ss_sint64_t size; char timebuf[50]; char atts[8 + 1]; #if defined(WHEREIS_PLATFORM_IS_WIN32) findfile_sequence::find_data_type const &findData = entry.get_find_data(); DWORD const &att = findData.dwFileAttributes; int i; for (i = 0; i < 8; ++i) { static char tab[] = "RHSVDAXX"; if (att & (1 << i)) atts[i] = tab[i]; else atts[i] = '-'; } atts[8] = 0; timestr(timebuf, stlsoft_num_elements(timebuf), &findData.ftLastWriteTime); size = findData.nFileSizeHigh * __STLSOFT_GEN_SINT64_SUFFIX(0x100000000) + findData.nFileSizeLow; #elif defined(WHEREIS_PLATFORM_IS_UNIX) # ifdef _MSC_VER // For testing struct _stat st; _stat(entry, &st); # else /* ? _MSC_VER */ struct stat st; stat(entry, &st); # endif /* _MSC_VER */ atts[0] = ((st.st_mode & S_IWRITE) == 0) ? 'R' : '-'; // R atts[1] = '-'; // H atts[2] = '-'; // S atts[3] = '-'; // V atts[4] = ((st.st_mode & S_IFMT) == S_IFDIR) ? 'D' : '-'; // D atts[5] = '-'; // A atts[6] = '-'; // X atts[7] = '-'; // X atts[8] = 0; size = st.st_size; timestr(timebuf, stlsoft_num_elements(timebuf), &st.st_mtime); #else /* ? platform */ # error Unknown platform #endif /* platform */ #ifdef _SYNSOFT_INTERNAL_BUILD # if defined(WHEREIS_PLATFORM_IS_WIN32) if(m_flags & Flags::showVersionInfo) { SynesisWin::LPWinVerInfoA verInfo = SynesisWin::WinVer_GetVersionInformationA(c_str_ptr(entry)); char version[101]; if(NULL != verInfo) { sprintf(version, "%d.%d.%02d.%04d", verInfo->fileVerMajor, verInfo->fileVerMinor, verInfo->fileVerRevision, verInfo->fileVerBuild); SynesisWin::WinVer_CloseVersionInformationA(verInfo); } else { version[0] = '\0'; } printf("%-23s %16s %s " FMT_SINT64_WIDTH_(9) "\t%s\n", timebuf, version, atts, size, path.c_str()); } else # endif /* WHEREIS_PLATFORM_IS_WIN32 */ #endif /* _SYNSOFT_INTERNAL_BUILD */ { printf("%-23s %s " FMT_SINT64_WIDTH_(9) "\t%s\n", timebuf, atts, size, path.c_str()); } } else { fprintf(stdout, "%s\n", path.c_str()); } } // Members private: char const *const m_searchRoot; Trim::Trim const m_trim; ss_uint_t const m_flags; // Not to be implemented private: class_type &operator =(class_type const &); }; // struct process_searchspec // // This functional processes a search-spec within a given directory, passing any // file to be processed by trace_file. struct process_searchspec : public unary_function<tokeniser_string_t::value_type const &, void> { typedef process_searchspec class_type; public: process_searchspec(string const &path, char const *searchRoot, Trim::Trim trim, ss_uint_t flags) : m_path(path) , m_searchRoot(searchRoot) , m_trim(trim) , m_flags(flags) {} void operator ()(tokeniser_string_t::value_type const &value) const { #ifdef WHEREIS_PLATFORM_IS_UNIX try { #endif /* WHEREIS_PLATFORM_IS_UNIX */ int fs_flags = 0; if(m_flags & Flags::showDirectories) { fs_flags |= findfile_sequence::directories; } if(m_flags & Flags::showFiles) { fs_flags |= findfile_sequence::files; } findfile_sequence files(c_str_ptr(m_path), c_str_ptr(value), fs_flags); for_each(files.begin(), files.end(), trace_file(m_searchRoot, m_trim, m_flags)); #ifdef WHEREIS_PLATFORM_IS_UNIX } catch(unixstl::glob_sequence_exception &) {} #endif /* WHEREIS_PLATFORM_IS_UNIX */ } // Members private: string const m_path; char const *const m_searchRoot; Trim::Trim const m_trim; ss_uint_t const m_flags; // Not to be implemented private: class_type &operator =(class_type const &); }; // struct process_path // // This functional creates a search sequence for each path, and then processes // each one with the trace_file functional. struct process_path : public unary_function<string const &, void> { typedef process_path class_type; public: process_path(string const &searchSpec, Trim::Trim trim, ss_uint_t flags) : m_searchSpec(searchSpec) , m_searchRoot(NULL) , m_trim(trim) , m_flags(flags) {} process_path(string const &searchSpec, char const *searchRoot, Trim::Trim trim, ss_uint_t flags) : m_searchSpec(searchSpec) , m_searchRoot(searchRoot) , m_trim(trim) , m_flags(flags) {} void operator ()(string const &dir) const { typedef filesystem_traits<char> traits_type; file_path_buffer searchRoot_; char const *searchRoot = (traits_type::get_full_path_name((NULL != m_searchRoot) ? m_searchRoot : stlsoft_ns_qual(c_str_ptr)(dir), searchRoot_.size(), &searchRoot_[0]), stlsoft_ns_qual(c_str_ptr)(searchRoot_)); // Now split with the string_tokeniser into all the constituent paths tokeniser_string_t specs(&m_searchSpec[0], PATH_SEPARATOR); for_each(specs.begin(), specs.end(), process_searchspec(dir, stlsoft_ns_qual(c_str_ptr)(searchRoot), m_trim, m_flags)); } // Members private: string const m_searchSpec; char const *const m_searchRoot; Trim::Trim const m_trim; ss_uint_t const m_flags; // Not to be implemented private: class_type &operator =(class_type const &); }; // struct trace_dir // // This functional provides processing of a directory, used by the recursive // option. It process the current directory (via process_path), and then all // subdirectories (via trace_dir) "calling" itself recursively. struct trace_dir : public unary_function<string const &, void> { typedef trace_dir class_type; public: trace_dir(string const &searchSpec, Trim::Trim trim, ss_uint_t flags) : m_searchSpec(searchSpec) , m_searchRoot(NULL) , m_trim(trim) , m_flags(flags) {} trace_dir(string const &searchSpec, char const *searchRoot, Trim::Trim trim, ss_uint_t flags) : m_searchSpec(searchSpec) , m_searchRoot(searchRoot) , m_trim(trim) , m_flags(flags) {} void operator ()(char const *dir) const { typedef filesystem_traits<char> traits_type; file_path_buffer searchRoot_; char const *searchRoot = (traits_type::get_full_path_name((NULL != m_searchRoot) ? m_searchRoot : dir, searchRoot_.size(), &searchRoot_[0]), stlsoft_ns_qual(c_str_ptr)(searchRoot_)); process_path f(m_searchSpec, searchRoot, m_trim, m_flags); f(dir); #ifdef WHEREIS_PLATFORM_IS_UNIX try { #endif /* WHEREIS_PLATFORM_IS_UNIX */ findfile_sequence directories(stlsoft_ns_qual(c_str_ptr)(dir), PATTERN_ALL, findfile_sequence::directories); for_each(directories.begin(), directories.end(), trace_dir(m_searchSpec, searchRoot, m_trim, m_flags)); #ifdef WHEREIS_PLATFORM_IS_UNIX } catch(unixstl::glob_sequence_exception &) {} #endif /* WHEREIS_PLATFORM_IS_UNIX */ } template <ss_typename_param_k S> void operator ()(S const &dir) const { operator ()(stlsoft_ns_qual(c_str_ptr)(dir)); } private: string const m_searchSpec; char const *const m_searchRoot; Trim::Trim const m_trim; ss_uint_t const m_flags; // Not to be implemented private: class_type &operator =(class_type const &); }; /* ///////////////////////////////////////////////////////////////////////////// * Function declarations */ static void usage(int bExit, char const *reason, int invalidArg, int argc, char *argv[]); static char const *convert_path_separators(char const *path, char *buffer); #ifdef WHEREIS_PLATFORM_IS_WIN32 static char const *get_driveroots(char *buffer); #endif /* WHEREIS_PLATFORM_IS_WIN32 */ /* ///////////////////////////////////////////////////////////////////////////// * Helper functionals */ struct is_empty_path { template <ss_typename_param_k S> ss_bool_t operator ()(S const &s) const { return c_str_ptr(s)[0] == '\0'; } }; struct print_path { template <ss_typename_param_k S> void operator ()(S const &s) const { fprintf(stdout, " %s\n", c_str_ptr(s)); } }; #ifdef WHEREIS_TRACE struct trace_path { template <ss_typename_param_k S> void operator ()(S const &s) const { size_t len = c_str_len(s); auto_buffer<char, malloc_allocator<char>, 256> buffer(3 + len + 1); sprintf(buffer, " %s\n", c_str_ptr(s)); OutputDebugStringA(buffer); } }; #endif /* WHEREIS_TRACE */ /* ///////////////////////////////////////////////////////////////////////////// * main */ #ifdef WIN32 extern "C" __declspec(dllimport) void __stdcall Sleep(unsigned long ); #endif /* WIN32 */ static int main_(int argc, char **argv) { ss_bool_t bDisplayTotal = false; ss_bool_t bFromEnvironment = false; ss_bool_t bSearchGivenRoots = false; ss_bool_t bSearchCwd = false; ss_bool_t bDumpSearchRoots = false; ss_bool_t bVerbose = true; ss_bool_t bRecursive = false; ss_bool_t bSuppressRecursive = false; ss_bool_t bShowVersionInfo = false; ss_bool_t bSummariseExtensions = false; ss_bool_t bShowDirectories = false; ss_bool_t bShowFiles = false; ss_bool_t bMarkDirs = false; Trim::Trim trim = Trim::full; char const *rootSpec = NULL; char const *searchSpec = NULL; char const *envSpec = NULL; #ifdef WHEREIS_PLATFORM_IS_WIN32 char driveroots[105] = ""; #endif /* WHEREIS_PLATFORM_IS_WIN32 */ int totalFound = 0; for(int i = 1; i < argc; ++i) { char const *arg = argv[i]; if(arg[0] == '-') { if(arg[1] == '-') { if( 0 == strcmp("--directories", arg) || 0 == strcmp("--dirs", arg)) { bShowDirectories = true; } else if(0 == strcmp("--files", arg)) { bShowFiles = true; } #ifdef _SYNSOFT_INTERNAL_BUILD else if(0 == strcmp("--version", arg)) { return show_version(); } #endif /* _SYNSOFT_INTERNAL_BUILD */ else { usage(1, "Invalid argument(s) specified", i, argc, argv); } } else { switch(arg[1]) { case '?': usage(1, NULL, i, argc, argv); break; case 'd': bDumpSearchRoots = true; break; case 'e': bFromEnvironment = true; envSpec = arg + 2; break; case 'f': trim = Trim::fileOnly; break; #ifdef WHEREIS_PLATFORM_IS_WIN32 case 'h': bSearchGivenRoots = true; rootSpec = get_driveroots(driveroots); break; #endif /* WHEREIS_PLATFORM_IS_WIN32 */ case 'i': bFromEnvironment = true; envSpec = "INCLUDE"; break; case 'l': bFromEnvironment = true; envSpec = "LIB"; break; case 'm': bMarkDirs = true; break; // case 'n': // bDisplayTotal = true; // break; case 'r': bSearchGivenRoots = true; rootSpec = arg + 2; break; case 'p': bFromEnvironment = true; envSpec = "PATH"; break; case 's': bVerbose = false; break; case 't': trim = Trim::fromCurrentDirectory; break; case 'u': bRecursive = true; break; case 'v': bVerbose = true; break; case 'w': bSearchCwd = true; break; case 'x': bSummariseExtensions = false; break; case 'R': bSuppressRecursive = true; break; case 'F': trim = Trim::full; break; case 'T': trim = Trim::fromSearchRoot; break; #ifdef _SYNSOFT_INTERNAL_BUILD case 'V': bShowVersionInfo = true; break; #endif /* _SYNSOFT_INTERNAL_BUILD */ default: // fprintf(stderr, "Unrecognised argument \"%s\"\n", arg); usage(1, "Invalid argument(s) specified", i, argc, argv); break; } } } else { if(rootSpec == NULL) { rootSpec = arg; } else if(searchSpec == NULL) { searchSpec = arg; } else { usage(1, "<root-paths> and <search-spec> already specified", i, argc, argv); } } } STLSOFT_SUPPRESS_UNUSED(bSummariseExtensions); if( !bShowDirectories && !bShowFiles) { bShowFiles = true; } if( NULL == searchSpec && NULL == rootSpec) { usage(1, "No search parameters specified", 0, argc, argv); } if( ((bSearchCwd != false) + (bFromEnvironment != false) + (bSearchGivenRoots != false)) > 1) { usage(1, "Cannot specify two or more of -w, -r, -e, -l, -i, -p", 0, argc, argv); } // Validate the args. This entails just moving the root-dir into the // search-spec if no root-dir was specified. This simplifies the // previous command-line processing. if(NULL == searchSpec) { if( NULL != rootSpec && !bSearchGivenRoots) { searchSpec = rootSpec; rootSpec = NULL; } else { usage(1, "Unexpected condition. Please report to Synesis Software", 0, argc, argv); } } file_path_buffer rootDir_; if(bFromEnvironment) { rootSpec = NULL; } else { // If no directory is specified, the current directory is assumed if( rootSpec == NULL || *rootSpec == '\0') { strcpy(&rootDir_[0], basic_current_directory<char>()); rootSpec = stlsoft_ns_qual(c_str_ptr)(rootDir_); } } if( bFromEnvironment && ( envSpec == NULL || *envSpec == '\0')) { usage(1, "Cannot search from environment when no environment variable specified", 0, argc, argv); } #if defined(__STLSOFT_COMPILER_IS_MSVC) && \ _MSC_VER < 1200 GetCurrentDirectory(s_root.size(), s_root); #else /* ? compiler */ platform_stl::filesystem_traits<char>::get_current_directory(s_root.size(), &s_root[0]); #endif /* compiler */ // Handle forward slashes string _rootDir_(rootSpec != NULL ? rootSpec : ""); string _searchSpec_(searchSpec != NULL ? searchSpec : ""); rootSpec = convert_path_separators(rootSpec, const_cast<char*>(_rootDir_.data())); searchSpec = convert_path_separators(searchSpec, const_cast<char*>(_searchSpec_.data())); // Handle illegal characters if(strpbrk(searchSpec, BAD_PATTERN_CHARS) != 0) { char sz[101]; sprintf(sz, "<search-spec> contains illegal characters: \"%s\"\n", searchSpec); usage(1, sz, 0, argc, argv); } searchpath_sorted_t sorted; ss_uint_t flags = 0; if(bVerbose) { flags |= Flags::verbose; } if(bShowVersionInfo) { flags |= Flags::showVersionInfo; } if(bShowDirectories) { flags |= Flags::showDirectories; } if(bShowFiles) { flags |= Flags::showFiles; } if(bMarkDirs) { flags |= Flags::markDirectories; } #ifdef WHEREIS_USING_WIN32_VERSION_INFO SynesisWin::WinVer_Init(); #endif /* WHEREIS_USING_WIN32_VERSION_INFO */ // Commence the search if(bFromEnvironment) { basic_environment_variable<char> ENVVAR(envSpec); tokeniser_string_t paths(ENVVAR, PATH_SEPARATOR); #ifdef __STLSOFT_COMPILER_IS_DMC { tokeniser_string_t::const_iterator begin = paths.begin(); tokeniser_string_t::const_iterator end = paths.end(); for(; begin != end; ++begin) { sorted.push_back(*begin); } } #else copy(paths.begin(), paths.end(), back_inserter(sorted)); #endif /* __STLSOFT_COMPILER_IS_DMC */ // The roots may contain duplicate elements, so remove_duplicates_from_unordered_sequence(sorted, compare_path<char>()); // They may also contain empty paths, so sorted.erase(remove_if(sorted.begin(), sorted.end(), is_empty_path()), sorted.end()); if(bDumpSearchRoots) { fprintf(stdout, "Search roots:\n"); for_each(sorted.begin(), sorted.end(), print_path()); } // Now execute over the duplicate-free (but still in the correct search order) // sequence, applying the process_path functional to each one. if(bRecursive) { for_each(sorted.begin(), sorted.end(), trace_dir(searchSpec, trim, flags)); } else { for_each(sorted.begin(), sorted.end(), process_path(searchSpec, trim, flags)); } } else { tokeniser_string_t roots(rootSpec, PATH_SEPARATOR); #ifdef __STLSOFT_COMPILER_IS_DMC { tokeniser_string_t::const_iterator begin = roots.begin(); tokeniser_string_t::const_iterator end = roots.end(); for(; begin != end; ++begin) { sorted.push_back(*begin); } } #else copy(roots.begin(), roots.end(), back_inserter(sorted)); #endif /* __STLSOFT_COMPILER_IS_DMC */ // The roots may contain duplicate elements, so remove_duplicates_from_unordered_sequence(sorted, compare_path<char>()); // They may also contain empty paths, so sorted.erase(remove_if(sorted.begin(), sorted.end(), is_empty_path()), sorted.end()); if(bDumpSearchRoots) { fprintf(stdout, "Search roots:\n"); for_each(sorted.begin(), sorted.end(), print_path()); } // Now execute over the duplicate-free (but still in the correct search order) // sequence, applying the trace_dir functional to each one. if(!bSuppressRecursive) { for_each(sorted.begin(), sorted.end(), trace_dir(searchSpec, trim, flags)); } else { for_each(sorted.begin(), sorted.end(), process_path(searchSpec, trim, flags)); } } if(bDisplayTotal) { printf(" %5d file(s) found\n", totalFound); } #ifdef WHEREIS_USING_WIN32_VERSION_INFO SynesisWin::WinVer_Uninit(); #endif /* WHEREIS_USING_WIN32_VERSION_INFO */ return 0; } int main(int argc, char *argv[]) { int res; #if 0 ::Sleep(100000); #endif /* 0 */ try { res = main_(argc, argv); } catch(...) { fprintf(stderr, "Fatal error: Uncaught exception in main_()\n"); res = EXIT_FAILURE; } return res; } /* ///////////////////////////////////////////////////////////////////////////// * usage */ static void usage(int bExit, char const *reason, int invalidArg, int argc, char *argv[]) { fprintf(stderr, "\n"); fprintf(stderr, " %s %s Tool, v%d.%d.%d.%04d\n", COMPANY_NAME, TOOL_NAME, _mccVerHi, _mccVerLo, _mccVerRev, _mccBldNum); fprintf(stderr, "\n"); fprintf(stderr, " incorporating Digital Mars technology\n"); fprintf(stderr, "\n"); if(NULL != reason) { fprintf(stderr, " Error: %s\n", reason); fprintf(stderr, "\n"); } if(0 < invalidArg) { fprintf(stderr, " First invalid argument #%d: %s\n", invalidArg, argv[invalidArg]); fprintf(stderr, " Arguments were (first bad marked *):\n\n"); for(int i = 1; i < argc; ++i) { fprintf(stderr, " %s%s\n", (i == invalidArg) ? "* " : " ", argv[i]); } fprintf(stderr, "\n"); } fprintf(stderr, " USAGE 1: " "%s [{-w | -r<root-paths> | -p | -i | -l | -e<env-var> | -h}] [-u] [-d] " "[{<--dirs> | <--directories>}] | [<--files>] " #if defined(_SYNSOFT_INTERNAL_BUILD) && \ defined(WHEREIS_PLATFORM_IS_WIN32) "[{-v | -s}] [-f | -F | | -t | -T] [-V] " #else /* ? _SYNSOFT_INTERNAL_BUILD */ "[{-v | -s}] [-f | -F] " #endif /* _SYNSOFT_INTERNAL_BUILD */ "[<root-paths>] <search-spec>\n", EXE_NAME); fprintf(stderr, " where:\n\n"); #if 0 fprintf(stderr, " -c - case-sensitive search\n"); fprintf(stderr, " -C - case-insensitive search; (default)\n"); #endif /* 0 */ fprintf(stderr, " -d - displays the search root path(s)\n"); fprintf(stderr, " -e<env-var> - searches in the directories specified in the environment variable <env-var>\n"); fprintf(stderr, " -f - shows the filename and extension only\n"); fprintf(stderr, " -F - shows the full path; (default) \n"); fprintf(stderr, " -h - searches from the roots of all drives on the system\n"); fprintf(stderr, " -i - searches in the directories specified in the INCLUDE environment variable\n"); fprintf(stderr, " -l - searches in the directories specified in the LIB environment variable\n"); fprintf(stderr, " -m - mark directories with a trailing path separator\n"); // fprintf(stderr, " -n - Prints a total number of files found\n"); //// fprintf(stderr, " -N - Prints only the total number of files found\n"); #if defined(WHEREIS_PLATFORM_IS_WIN32) fprintf(stderr, " -p - searches in the Windows paths (the directories specified in the PATH environment variable)\n"); fprintf(stderr, " -r<root-paths> - searches from the given root path(s), separated by \';\', e.g.\n"); fprintf(stderr, " -r\"c:\\windows;x:\\bin\"\n"); #elif defined(WHEREIS_PLATFORM_IS_UNIX) fprintf(stderr, " -p - searches in the system paths (the directories specified in the PATH environment variable)\n"); fprintf(stderr, " -r<root-paths> - searches from the given root path(s), separated by \':\', e.g.\n"); fprintf(stderr, " -r\"/usr/include:/etc\"\n"); #else # error Unknown platform #endif /* platform */ fprintf(stderr, " -R - suppresses recursive search\n"); fprintf(stderr, " -s - succinct output. Prints path only\n"); #if defined(_SYNSOFT_INTERNAL_BUILD) && \ defined(WHEREIS_PLATFORM_IS_WIN32) fprintf(stderr, " -t - trims path relative to the current directory\n"); fprintf(stderr, " -T - trims path relative to the root directory(ies) specified for the search(es)\n"); #endif /* _SYNSOFT_INTERNAL_BUILD */ fprintf(stderr, " -u - recursive search. (Default except for environment variable searches.)\n"); fprintf(stderr, " -v - verbose output. Prints time, attributes, size and path; (default)\n"); #ifdef _SYNSOFT_INTERNAL_BUILD fprintf(stderr, " -V - displays the version information, if any, for the file. Suppressed by -s\n"); #endif /* _SYNSOFT_INTERNAL_BUILD */ fprintf(stderr, " -w - searches from the current working directory\n"); fprintf(stderr, " -x - summarises the file extensions\n"); fprintf(stderr, " --dirs - search for directories\n"); fprintf(stderr, " --directories - search for directories\n"); fprintf(stderr, " --files - search for files; (default if --files and --dir(ectorie)s not specified)\n"); fprintf(stderr, " <search-spec> - one or more file search specifications, separated by \';\',\n"); fprintf(stderr, " eg.\n"); fprintf(stderr, " \"*.exe\"\n"); fprintf(stderr, " \"myfile.ext\"\n"); fprintf(stderr, " \"*.exe;*.dll\"\n"); fprintf(stderr, " \"*.xl?;report.*\"\n"); fprintf(stderr, "\n"); fprintf(stderr, " USAGE 2: %s -?\n", EXE_NAME); fprintf(stderr, "\n"); fprintf(stderr, " Displays this help\n"); fprintf(stderr, "\n"); fprintf(stderr, " Contact %s\n", _nameSynesisSoftware); fprintf(stderr, " at \"%s\",\n", _wwwSynesisSoftware_SystemTools); fprintf(stderr, " or, via email, at \"%s\"\n", _emailSynesisSoftware_SystemTools); fprintf(stderr, "\n"); fprintf(stderr, " Contact Digital Mars\n"); fprintf(stderr, " at \"www.digitalmars.com\",\n"); fprintf(stderr, " or, via email, at \"software@digitalmars.com\"\n"); // fprintf(stderr, "\n"); if(bExit) { exit(EXIT_FAILURE); } } char const *convert_path_separators(char const *path, char *buffer) { #if defined(WHEREIS_PLATFORM_IS_WIN32) char const chWrong = '/'; #elif defined(WHEREIS_PLATFORM_IS_UNIX) char const chWrong = '\\'; #else # error Unknown platform #endif /* platform */ if( path != 0 && 0 != strchr(path, chWrong)) { char *pch; path = strcpy(buffer, path); for(pch = buffer; 0 != (pch = strchr(pch + 1, chWrong)); ) { *pch = PATH_NAME_SEPARATOR; } } return path; } #ifdef WHEREIS_PLATFORM_IS_WIN32 char const *get_driveroots(char *const buffer) { char drv[4] = "?:\\"; *buffer = '\0'; for(char ch = 'a'; ch <= 'z'; ++ch) { drv[0] = ch; long type = GetDriveTypeA(drv); if(DRIVE_FIXED == type) { strcat(buffer, drv); strcat(buffer, ";"); } } return buffer; } #endif /* WHEREIS_PLATFORM_IS_WIN32 */ /* ////////////////////////////////////////////////////////////////////////// */
31.829728
215
0.562001
cf33b92f91390297175f9db1e773eeda011fd2dc
1,461
cpp
C++
Progs/Ch05/Referst.cpp
singhnir/C-Plus-Plus-Robert-Lafore
7ce3c92d15958e157484fc989632b879360103aa
[ "MIT" ]
4
2021-02-24T06:53:51.000Z
2022-02-18T11:15:19.000Z
Progs/Ch05/Referst.cpp
singhnir/C-Plus-Plus-Robert-Lafore
7ce3c92d15958e157484fc989632b879360103aa
[ "MIT" ]
null
null
null
Progs/Ch05/Referst.cpp
singhnir/C-Plus-Plus-Robert-Lafore
7ce3c92d15958e157484fc989632b879360103aa
[ "MIT" ]
4
2021-02-24T07:05:43.000Z
2022-03-09T17:45:32.000Z
// referst.cpp // demonstrates passing structure by reference #include <iostream> using namespace std; //////////////////////////////////////////////////////////////// struct Distance //English distance { int feet; float inches; }; //////////////////////////////////////////////////////////////// void scale( Distance&, float ); //function void engldisp( Distance ); //declarations int main() { Distance d1 = { 12, 6.5 }; //initialize d1 and d2 Distance d2 = { 10, 5.5 }; cout << "d1 = "; engldisp(d1); //display old d1 and d2 cout << "\nd2 = "; engldisp(d2); scale(d1, 0.5); //scale d1 and d2 scale(d2, 0.25); cout << "\nd1 = "; engldisp(d1); //display new d1 and d2 cout << "\nd2 = "; engldisp(d2); cout << endl; return 0; } //-------------------------------------------------------------- // scale() // scales value of type Distance by factor void scale( Distance& dd, float factor) { float inches = (dd.feet*12 + dd.inches) * factor; dd.feet = static_cast<int>(inches / 12); dd.inches = inches - dd.feet * 12; } //-------------------------------------------------------------- // engldisp() // display structure of type Distance in feet and inches void engldisp( Distance dd ) //parameter dd of type Distance { cout << dd.feet << "\'-" << dd.inches << "\""; }
31.085106
65
0.450376
cf3b5ad84e6ad780c89f9600ea72d405d86631b9
738
cpp
C++
src/QtGadgets/Validators/nRegExpValidator.cpp
Vladimir-Lin/QtGadgets
5fcea23ca95d85088d68fa64996e16281549ec3c
[ "MIT" ]
null
null
null
src/QtGadgets/Validators/nRegExpValidator.cpp
Vladimir-Lin/QtGadgets
5fcea23ca95d85088d68fa64996e16281549ec3c
[ "MIT" ]
null
null
null
src/QtGadgets/Validators/nRegExpValidator.cpp
Vladimir-Lin/QtGadgets
5fcea23ca95d85088d68fa64996e16281549ec3c
[ "MIT" ]
null
null
null
#include <qtgadgets.h> N::RegExpValidator:: RegExpValidator ( QObject * parent ) : QRegExpValidator ( parent ) , Validator ( parent ) { } N::RegExpValidator::~RegExpValidator (void) { } int N::RegExpValidator::Type(void) const { return 1102 ; } void N::RegExpValidator::Fixup(QString & input) const { QRegExpValidator::fixup(input) ; } QLocale N::RegExpValidator::Locale(void) const { return QRegExpValidator::locale() ; } void N::RegExpValidator::setLocale (const QLocale & locale) { QRegExpValidator::setLocale(locale) ; } QValidator::State N::RegExpValidator::isValid(QString & input,int & pos) const { return QRegExpValidator::validate(input,pos) ; }
19.945946
78
0.658537
cf3d9a79062dafd4f1fe432932c9b68a30ce0998
1,097
cpp
C++
c++/primer_plus_s_pratt/ch_9/pr_ex4/sales.cpp
dinimar/Projects
7606c23c4e55d6f0c03692b4a1d2bb5b42f10992
[ "MIT" ]
null
null
null
c++/primer_plus_s_pratt/ch_9/pr_ex4/sales.cpp
dinimar/Projects
7606c23c4e55d6f0c03692b4a1d2bb5b42f10992
[ "MIT" ]
null
null
null
c++/primer_plus_s_pratt/ch_9/pr_ex4/sales.cpp
dinimar/Projects
7606c23c4e55d6f0c03692b4a1d2bb5b42f10992
[ "MIT" ]
null
null
null
#ifndef SALES_H #define SALES_H #include "sales.h" #endif #include <iostream> using namespace std; namespace SALES { void setSales(Sales &s, const double ar[], int n) { int count = 0; double max, min, ave = ar[0]; for(int i=0;i<n and i<QUARTERS;++i) { s.sales[i] = ar[i]; count++; if(max < ar[i]) max = ar[i]; if(min > ar[i]) min = ar[i]; ave += ar[i]; } for(int i=count;i<QUARTERS;++i) s.sales[i]=0; ave /= QUARTERS; s.min = min; s.max = max; s.average = ave; } void setSales(Sales &s) { double max, min, ave = 0; for(int i=0;i<QUARTERS;++i) { cin >> s.sales[i]; if(max < s.sales[i]) max = s.sales[i]; if(min > s.sales[i]) min = s.sales[i]; ave += s.sales[i]; } ave /= QUARTERS; s.min = min; s.max = max; s.average = ave; } void showSales(const Sales &s) { cout << "Sales\n" << "["; for (int i=0;i<QUARTERS-1;++i) { cout << s.sales[i] << ", "; } cout << s.sales[3] << "]\n"; cout << "Max: " << s.max << endl; cout << "Min: " << s.min << endl; cout << "Average: " << s.average << endl; } }
15.671429
50
0.52051
cf3dac6ef0e6d5ca630943ed95d601a3080002e5
2,746
cpp
C++
src/Kepler3rdLaw.cpp
wstern1234/CPP-Projects
e8712171355b7a833f8a63ce0ffa49dcca10b053
[ "MIT" ]
null
null
null
src/Kepler3rdLaw.cpp
wstern1234/CPP-Projects
e8712171355b7a833f8a63ce0ffa49dcca10b053
[ "MIT" ]
null
null
null
src/Kepler3rdLaw.cpp
wstern1234/CPP-Projects
e8712171355b7a833f8a63ce0ffa49dcca10b053
[ "MIT" ]
null
null
null
// Identification comments code block // Wills Stern // Kepler's 3rd Law // Editor(s) used: VS Code // Compiler(s) used: g++ #include <iostream> using std::cout; using std::cin; #include <string> using std::string; using std::endl; #include <cctype> // for toupper #include <cstdlib> // for atof #include <cmath> // for sqrt, pow, and cbrt // function prototypes double findPeriod(); double findAU(); int main() { // identification output code block cout << "Wills Stern\n\n"; cout << "Kepler's 3rd Law\n";\ cout << "Editor(s) used: VSCode\n"; cout << "Compiler(s) used: g++\n"; cout << "File: " << __FILE__ << "\n"; cout << "Compiled: " << __DATE__ << " at " << __TIME__ << "\n\n\n\n"; char opt; // infinite loop, continuely asks user for data unless 'Q'/'q' is entered while (true) { // menu with two options cout << "p² = a³\n\n"; cout << "Options:\n"; cout << " P: find orbital Period\n"; cout << " A: find distance in AU" << endl; cout << "Option: "; cin >> opt; // char variable, so no need for buffer // breaks with 'Q' or 'q' if (toupper(opt) == 'Q') break; // outputs the orbital period in years else if (toupper(opt) == 'P') cout << "\n" << findPeriod() << " years\n\n\n" << endl; // outputs the distance from the Sun in Astronomical Units (AU) else if (toupper(opt) == 'A') cout << "\n" << findAU() << " AU\n\n\n" << endl; // invalid input, continues on with loop else cout << "\nNot an option, try again.\n\n\n" << endl; } } /************************************************************* * Purpose: Finds the time for an object to orbit the Sun in Earth years * * Parameters: (None) * * Return: Time for an object to orbit the Sun in Earth years as a double **************************************************************/ double findPeriod() { string buf; cout << "Enter distance in Astronomical Units (AU): "; // uses buffer input method for safety cin >> buf; double distance = atof(buf.c_str()); // Kelper's 3rd Law of Planetary Motion: p² = a³ // ...becomes p = a⁽³ᐟ²⁾ return ( sqrt(pow(distance, 3)) ); } /************************************************************* * Purpose: Finds the distance of an object from the Sun in AU * * Parameters: (None) * * Return: Distance of the object from the Sun in AU as a double **************************************************************/ double findAU() { string buf; cout << "Enter orbital period in Earth years: "; // uses buffer input method for safety cin >> buf; double period = atof(buf.c_str()); // Kelper's 3rd Law of Planetary Motion: p² = a³ // ...becomes a = p⁽²ᐟ³⁾ return ( cbrt(pow(period, 2)) ); }
22.145161
75
0.550255
cf3e39d26b98da0c54f6d62a7faae7c489feb69d
17,443
hpp
C++
tests/unit/coherence/util/CircularArrayListTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-01T21:38:30.000Z
2021-11-03T01:35:11.000Z
tests/unit/coherence/util/CircularArrayListTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
1
2020-07-24T17:29:22.000Z
2020-07-24T18:29:04.000Z
tests/unit/coherence/util/CircularArrayListTest.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-10T18:40:58.000Z
2022-02-18T01:23:40.000Z
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #include "cxxtest/TestSuite.h" #include "coherence/lang.ns" #include "coherence/util/CircularArrayList.hpp" #include "private/coherence/util/logging/Logger.hpp" using namespace coherence::lang; using namespace std; /** * Test suite for the CircularArrayList object. * * 2008.02.08 nsa */ class CircularArrayListTest : public CxxTest::TestSuite { public: void testAddIndex() { CircularArrayList::Handle hList = CircularArrayList::create(); String::Handle hValue = String::create("Test Value"); String::Handle hValue2 = String::create("TV2"); hList->add(hValue); hList->add(0, hValue2); TS_ASSERT(hList->size() == 2); TS_ASSERT(hList->get(0)->equals(hValue2)); } void testAddAllIndex() { CircularArrayList::Handle hList = CircularArrayList::create(); for (int32_t x = 0; x < 10; ++x) { hList->add(COH_TO_STRING("List Value: " << x)); } TS_ASSERT(hList->size() == 10); CircularArrayList::Handle hList2 = CircularArrayList::create(); String::Handle hList2Value = String::create("hList2"); hList2->add(hList2Value); hList2->addAll(0, hList); TS_ASSERT(hList2->size() == 11); TS_ASSERT(hList2->get(10) == hList2Value); } void testGet() { CircularArrayList::Handle hList = CircularArrayList::create(); String::Handle hValue = String::create("Test Value"); hList->add(hValue); TS_ASSERT(hList->get(0)->equals(hValue)); String::Handle hValue2 = String::create("Test Value 2"); hList->add(hValue2); TS_ASSERT(hList->get(1)->equals(hValue2)); } void testIndexOf() { CircularArrayList::Handle hList = CircularArrayList::create(); String::Handle findMe; String::Handle notFound = String::create("Can't Find Me"); for (int32_t x = 0; x < 10; ++x) { String::Handle hString = COH_TO_STRING("List Value: " << x); if (x == 5) { findMe = hString; } hList->add(hString); } TS_ASSERT(hList->indexOf(findMe) == 5); TS_ASSERT(hList->indexOf(notFound) == List::npos); } void testLastIndexOf() { CircularArrayList::Handle hList = CircularArrayList::create(); String::Handle hDup = String::create("DuplicateString"); String::Handle hNotFound = String::create("Can't find me"); for (int32_t x = 0; x < 10; ++x) { if (x % 2 == 0) { hList->add(hDup); } else { hList->add(COH_TO_STRING("List Value: " << x)); } } TS_ASSERT(hList->lastIndexOf(hDup) == 8); TS_ASSERT(hList->lastIndexOf(hNotFound) == List::npos); } void testListIterator() { CircularArrayList::Handle hList = CircularArrayList::create(); TS_ASSERT_EQUALS(hList->listIterator()->hasNext(), false); TS_ASSERT_EQUALS(hList->listIterator()->hasPrevious(), false); int32_t x; for (x = 0; x < 10; ++x) { hList->add(Integer32::create(x)); } TS_ASSERT_EQUALS(hList->size(), size32_t(10)); ListIterator::Handle hIterator = hList->listIterator(); TS_ASSERT_EQUALS(hList->listIterator()->hasPrevious(), false); x = 0; while (hIterator->hasNext()) { Integer32::Handle hValue = cast<Integer32::Handle>(hIterator->next()); TS_ASSERT_EQUALS(hValue->getValue(), x); x++; } TS_ASSERT_EQUALS(x, 10); while (hIterator->hasPrevious()) { --x; Integer32::Handle hValue = cast<Integer32::Handle>(hIterator->previous()); TS_ASSERT_EQUALS(hValue->getValue(), x); } TS_ASSERT(x == 0); while (hIterator->hasNext()) { Integer32::Handle hValue = cast<Integer32::Handle>(hIterator->next()); TS_ASSERT_EQUALS(hValue->getValue(), x); ++x; } TS_ASSERT(x == 10); } void testListIteratorIndex() { CircularArrayList::Handle hList = CircularArrayList::create(); int32_t x; for (x = 0; x < 10; ++x) { hList->add(Integer32::create(x)); } x = 5; ListIterator::Handle hIterator = hList->listIterator(x); while (hIterator->hasNext()) { Integer32::Handle hValue = cast<Integer32::Handle>(hIterator->next()); TS_ASSERT_EQUALS(hValue->getValue(), x); ++x; } TS_ASSERT_EQUALS(x, 10); while (hIterator->hasPrevious()) { --x; Integer32::Handle hValue = cast<Integer32::Handle>(hIterator->previous()); TS_ASSERT_EQUALS(hValue->getValue(), x); } TS_ASSERT_EQUALS(x, 0); while (hIterator->hasNext()) { Integer32::Handle hValue = cast<Integer32::Handle>(hIterator->next()); TS_ASSERT_EQUALS(hValue->getValue(), x); ++x; } TS_ASSERT_EQUALS(x, 10); } void testListMuterator() { CircularArrayList::Handle hList = CircularArrayList::create(); TS_ASSERT_EQUALS(hList->listIterator()->hasNext(), false); TS_ASSERT_EQUALS(hList->listIterator()->hasPrevious(), false); size32_t x; ListMuterator::Handle hMiter = hList->listIterator(); for (x = 0; x < 10; ++x) { hMiter->add(Integer32::create(x)); } TS_ASSERT_EQUALS(hList->size(), x); while (hMiter->hasPrevious()) { --x; Integer32::Handle hValue = cast<Integer32::Handle>(hMiter->previous()); TS_ASSERT_EQUALS(hValue->getValue(), (int32_t)x); hMiter->remove(); TS_ASSERT(hMiter->hasNext() == false) } TS_ASSERT_EQUALS(x, 0u); TS_ASSERT_EQUALS(hList->size(), x); for (x = 0; x < 5; ++x) { hMiter->add(Integer32::create(x * 2)); } TS_ASSERT_EQUALS(hList->size(), x); hMiter = hList->listIterator(); for (x = 0; x < 10; x += 2) { hMiter->next(); hMiter->add(Integer32::create(x + 1)); } TS_ASSERT_EQUALS(hList->size(), x); while (hMiter->hasPrevious()) { --x; Integer32::Handle hValue = cast<Integer32::Handle>(hMiter->previous()); TS_ASSERT_EQUALS(hValue->getValue(), (int32_t)x); } size32_t iNextExpected = 0; for (x = 0; x < 10; x += 2) { TS_ASSERT_EQUALS(hMiter->nextIndex(), iNextExpected); Integer32::Handle hValue = cast<Integer32::Handle>(hMiter->next()); ++iNextExpected; TS_ASSERT_EQUALS(hValue->getValue(), (int32_t)x); TS_ASSERT_EQUALS(hMiter->previousIndex(), iNextExpected - 1); hMiter->remove(); --iNextExpected; hMiter->next(); ++iNextExpected; } TS_ASSERT_EQUALS(hList->size(), x/2); hMiter = hList->listIterator(); for (x = 1; x < 10; x += 2) { Integer32::Handle hValue = cast<Integer32::Handle>(hMiter->next()); TS_ASSERT_EQUALS(hValue->getValue(), (int32_t)x); hMiter->set(Integer32::create(x + 1)); } hMiter = hList->listIterator(); for (x = 1; x < 10; x += 2) { Integer32::Handle hValue = cast<Integer32::Handle>(hMiter->next()); TS_ASSERT_EQUALS(hValue->getValue(), (int32_t)(x + 1)); } // test next/prev toggle hMiter = hList->listIterator(); size32_t iNext = hMiter->nextIndex(); Object::View vNext = hMiter->next(); size32_t iPrev = hMiter->previousIndex(); Object::View vPrev = hMiter->previous(); TS_ASSERT_EQUALS(vNext, vPrev); TS_ASSERT_EQUALS(iNext, iPrev); iNext = hMiter->nextIndex(); vNext = hMiter->next(); TS_ASSERT_EQUALS(vNext, vPrev); TS_ASSERT_EQUALS(iNext, iPrev); } void testRemoveIndex() { CircularArrayList::Handle hList = CircularArrayList::create(); String::Handle s1 = String::create("test1"); String::Handle s2 = String::create("test2"); hList->add(s1); hList->add(s2); TS_ASSERT(hList->remove(1)->equals(s2)); TS_ASSERT(hList->size() == 1u); } void testSetIndex() { CircularArrayList::Handle hList = CircularArrayList::create(); String::Handle s1 = String::create("test1"); String::Handle s2 = String::create("test2"); String::Handle s3 = String::create("test3"); hList->add(s1); hList->add(s2); TS_ASSERT(hList->get(1)->equals(s2)); hList->set(1, s3); TS_ASSERT(hList->get(1)->equals(s3)); TS_ASSERT(hList->size() == 2u); } void testSubList() { CircularArrayList::Handle hList = CircularArrayList::create(); for (int32_t x = 0; x < 10; ++x) { hList->add(COH_TO_STRING("List Value: " << x)); } List::Handle hSub = hList->subList(1, 6); TS_ASSERT(hSub->size() == 5u); hSub->add(String::create("New Sub Value")); TS_ASSERT(hSub->size() == 6u); TS_ASSERT(hList->size() == 11u); Iterator::Handle hIter = hSub->iterator(); while (hIter->hasNext()) { TS_ASSERT(hList->contains(hIter->next())); } } void testSize() { CircularArrayList::Handle hList = CircularArrayList::create(); for (int32_t x = 0; x < 10; ++x) { hList->add(COH_TO_STRING("List Value: " << x)); } TS_ASSERT(hList->size() == 10u); } void testIterator() { CircularArrayList::Handle hList = CircularArrayList::create(); int32_t x; for (x = 0; x < 10; ++x) { hList->add(COH_TO_STRING("List Value: " << x)); } Iterator::Handle hIterator = hList->iterator(); x = 0; while (hIterator->hasNext()) { String::Handle hString = cast<String::Handle>(hIterator->next()); x++; } TS_ASSERT(x == 10); } void testAdd() { CircularArrayList::Handle hList = CircularArrayList::create(); String::Handle hValue = String::create("Test Value"); hList->add(hValue); TS_ASSERT(hList->size() == 1u); TS_ASSERT(hList->get(0)->equals(hValue)); } void testAddAll() { CircularArrayList::Handle hList = CircularArrayList::create(); for (int32_t x = 0; x < 10; ++x) { hList->add(COH_TO_STRING("List Value: " << x)); } TS_ASSERT(hList->size() == 10u); CircularArrayList::Handle hList2 = CircularArrayList::create(); String::Handle hList2Value = String::create("hList2"); hList2->add(hList2Value); hList2->addAll(hList); TS_ASSERT(hList2->size() == 11u); TS_ASSERT(hList2->get(10) == hList->get(hList->size() - 1)); } void testRemove() { String::Handle h1 = String::create("h1"); String::Handle h2 = String::create("h2"); CircularArrayList::Handle hList = CircularArrayList::create(); hList->add(h1); hList->add(h2); TS_ASSERT(hList->size() == 2u); hList->remove(h2); TS_ASSERT(hList->size() == 1u); } void testRemoveAll() { CircularArrayList::Handle hList = CircularArrayList::create(); for (int32_t x = 0; x < 10; ++x) { hList->add(COH_TO_STRING("List Value: " << x)); } TS_ASSERT(hList->size() == 10); CircularArrayList::Handle hList2 = CircularArrayList::create(); String::Handle hList2Value = String::create("hList2"); String::Handle hList2Valueb = String::create("hList2b"); hList2->add(hList2Value); hList2->add(hList2Valueb); hList->addAll(hList2); TS_ASSERT(hList->size() == 12u); hList->removeAll(hList2); TS_ASSERT(hList->size() == 10u); } void testRetainAll() { CircularArrayList::Handle hList = CircularArrayList::create(); for (int32_t x = 0; x < 10; ++x) { hList->add(COH_TO_STRING("List Value: " << x)); } TS_ASSERT(hList->size() == 10u); CircularArrayList::Handle hList2 = CircularArrayList::create(); String::Handle hList2Value = String::create("hList2"); String::Handle hList2Valueb = String::create("hList2b"); hList2->add(hList2Value); hList2->add(hList2Valueb); hList->addAll(hList2); TS_ASSERT(hList->size() == 12u); hList->retainAll(hList2); TS_ASSERT(hList->size() == 2u); } void testClear() { CircularArrayList::Handle hList = CircularArrayList::create(); for (int32_t x = 0; x < 10; ++x) { hList->add(COH_TO_STRING("List Value: " << x)); } TS_ASSERT(hList->size() == 10u); hList->clear(); TS_ASSERT(hList->size() == 0u); hList->add(String::create("foo")); TS_ASSERT(hList->size() == 1u); } void testClone() { CircularArrayList::Handle hList = CircularArrayList::create(); hList->add(String::create("test")); hList->add(String::create("test2")); CircularArrayList::View vList = hList; CircularArrayList::Handle hListClone = cast<CircularArrayList::Handle>(vList->clone()); TS_ASSERT(hListClone->size() == 2u); TS_ASSERT(cast<String::View>(hListClone->get(0))->equals("test")); TS_ASSERT(cast<String::View>(hListClone->get(1))->equals("test2")); } void testCleanup() { HeapAnalyzer::Snapshot::View vSnap = HeapAnalyzer::ensureHeap(); CircularArrayList::Handle hList = CircularArrayList::create(); for (int32_t i = 0; i < 10; ++i) { hList->add(Integer32::create(i)); } hList = NULL; HeapAnalyzer::ensureHeap(vSnap); } void testBigList() { HeapAnalyzer::Snapshot::View vSnap = HeapAnalyzer::ensureHeap(); CircularArrayList::Handle hList = CircularArrayList::create(); for (int32_t i = 0; i < 10000; ++i) { hList->add(Integer32::create(i)); } MemberHandle<List> hEscape(System::common(), hList); int32_t n = 0; for (Iterator::Handle hIter = hList->iterator(); hIter->hasNext(); ) { Integer32::Handle hN = cast<Integer32::Handle>(hIter->next()); TS_ASSERT(hN->getValue() == n++); TS_ASSERT(hN->_isEscaped()); } TS_ASSERT(n == 10000); hEscape = NULL; hList->_isEscaped(); // unescape hList = NULL; // delete HeapAnalyzer::ensureHeap(vSnap); } };
32.301852
98
0.480193
cf52f5bb6f126cfe12d71a828ecbec9b9d4b0bb0
617
cc
C++
ext/extbrotli.cc
dearblue/ruby-extbrotli
309a7088fdc8bc87354a00d6e442c97bf00da9f9
[ "BSD-2-Clause" ]
1
2017-05-23T07:13:40.000Z
2017-05-23T07:13:40.000Z
ext/extbrotli.cc
dearblue/ruby-extbrotli
309a7088fdc8bc87354a00d6e442c97bf00da9f9
[ "BSD-2-Clause" ]
null
null
null
ext/extbrotli.cc
dearblue/ruby-extbrotli
309a7088fdc8bc87354a00d6e442c97bf00da9f9
[ "BSD-2-Clause" ]
null
null
null
#include "extbrotli.h" VALUE mBrotli; VALUE mConst; VALUE eError; VALUE eNeedsMoreInput; VALUE eNeedsMoreOutput; EXTBROTLI_CEXTERN void Init_extbrotli(void) { mBrotli = rb_define_module("Brotli"); mConst = rb_define_module_under(mBrotli, "Constants"); rb_include_module(mBrotli, mConst); eError = rb_define_class_under(mBrotli, "Error", rb_eRuntimeError); eNeedsMoreInput = rb_define_class_under(mBrotli, "NeedsMoreInput", eError); eNeedsMoreOutput = rb_define_class_under(mBrotli, "NeedsMoreOutput", eError); extbrotli_init_lowlevelencoder(); extbrotli_init_lowleveldecoder(); }
24.68
81
0.773096
cf54a1975be0c92f61cc83bc42ca252674bcfe2f
18,260
cpp
C++
src/SystemConfigurator/CSPs/DiagnosticLogCSP.cpp
mehrdad-shokri/iot-core-azure-dm-client
09c203f158c5f66a5bd2e508a7d50ac2e1372b89
[ "MIT" ]
52
2017-05-02T09:43:39.000Z
2021-11-11T18:32:46.000Z
src/SystemConfigurator/CSPs/DiagnosticLogCSP.cpp
mehrdad-shokri/iot-core-azure-dm-client
09c203f158c5f66a5bd2e508a7d50ac2e1372b89
[ "MIT" ]
161
2017-04-07T19:04:26.000Z
2020-09-21T12:42:22.000Z
src/SystemConfigurator/CSPs/DiagnosticLogCSP.cpp
mehrdad-shokri/iot-core-azure-dm-client
09c203f158c5f66a5bd2e508a7d50ac2e1372b89
[ "MIT" ]
67
2017-03-31T00:33:02.000Z
2021-03-06T00:34:33.000Z
/* Copyright 2017 Microsoft 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 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 <stdafx.h> #include <filesystem> #include <fstream> #include <iomanip> #include "..\SharedUtilities\Logger.h" #include "..\SharedUtilities\Utils.h" #include "MdmProvision.h" #include "DiagnosticLogCSP.h" using namespace std; using namespace Microsoft::Devices::Management::Message; const wchar_t* DiagnosticLogCSPWorkingFolder = L"C:\\Data\\Users\\Public\\Documents"; const wchar_t* CSPQuerySuffix = L"?list=StructData"; const wchar_t* CSPCollectorsRoot = L"./Vendor/MSFT/DiagnosticLog/EtwLog/Collectors"; const wchar_t* CSPTrue = L"TRUE"; const wchar_t* CSPNodeType = L"node"; // Collectors const wchar_t* CSPTraceStatus = L"TraceStatus"; const wchar_t* CSPTraceLogFileMode = L"TraceLogFileMode"; const wchar_t* CSPLogFileSizeLimitMB = L"LogFileSizeLimitMB"; const wchar_t* CSPProvidersNode = L"Providers"; const wchar_t* CSPTraceControl = L"TraceControl"; const wchar_t* CSPTraceControlStart = L"START"; const wchar_t* CSPTraceControlStop = L"STOP"; // Providers const wchar_t* CSPTraceLevel = L"TraceLevel"; const wchar_t* CSPKeywords = L"Keywords"; const wchar_t* CSPState = L"State"; // Download Channel const wchar_t* CSPDataChannel = L"./Vendor/MSFT/DiagnosticLog/FileDownload/DMChannel"; const wchar_t* CSPBlockCount = L"BlockCount"; const wchar_t* CSPBlockIndexToRead = L"BlockIndexToRead"; const wchar_t* CSPBlockData = L"BlockData"; const wchar_t* JsonNoString = L"no"; const wchar_t* JsonYesString = L"yes"; const wchar_t* JsonFileModeSequential = L"sequential"; const wchar_t* JsonFileModeCircular = L"circular"; const wchar_t* JsonTraceLevelCritical = L"critical"; const wchar_t* JsonTraceLevelError = L"error"; const wchar_t* JsonTraceLevelWarning = L"warning"; const wchar_t* JsonTraceLevelInformation = L"information"; const wchar_t* JsonTraceLevelVerbose = L"verbose"; IResponse^ DiagnosticLogCSP::HandleGetEventTracingConfiguration(IRequest^ request) { TRACE(__FUNCTION__); map<wstring, CollectorReportedConfiguration^> encounteredCollectorsMap; GetEventTracingConfigurationResponse^ response = ref new GetEventTracingConfigurationResponse(ResponseStatus::Success); std::function<void(std::vector<std::wstring>&, std::wstring&)> valueHandler = [response, &encounteredCollectorsMap](vector<wstring>& uriTokens, wstring& value) { if (uriTokens.size() < 7) { return; } wstring cspCollectorName = uriTokens[6]; CollectorReportedConfiguration^ currentCollector; // 0/__1___/_2__/______3______/__4___/____5_____/___6___/ // ./Vendor/MSFT/DiagnosticLog/EtwLog/Collectors/AzureDM map<wstring, CollectorReportedConfiguration^>::iterator it = encounteredCollectorsMap.find(cspCollectorName); if (it == encounteredCollectorsMap.end()) { wstring collectorRegistryPath = RegEventTracing; collectorRegistryPath += L"\\"; collectorRegistryPath += cspCollectorName.c_str(); currentCollector = ref new CollectorReportedConfiguration(); currentCollector->Name = ref new String(cspCollectorName.c_str()); wstring reportToDeviceTwin = Utils::ReadRegistryValue(collectorRegistryPath, RegReportToDeviceTwin, JsonNoString /*default*/); currentCollector->ReportToDeviceTwin = ref new String(reportToDeviceTwin.c_str()); currentCollector->CSPConfiguration->LogFileFolder = ref new String(Utils::ReadRegistryValue(collectorRegistryPath, RegEventTracingLogFileFolder, cspCollectorName /*default*/).c_str()); currentCollector->CSPConfiguration->LogFileName = ref new String(Utils::ReadRegistryValue(collectorRegistryPath, RegEventTracingLogFileName, L"" /*default*/).c_str()); // Add it to the collectors list... response->Collectors->Append(currentCollector); // Save it in the collectors map so that we can find it easily next time // we need it while processing another token... encounteredCollectorsMap[cspCollectorName] = currentCollector; } else { currentCollector = it->second; } if (uriTokens.size() >= 8) { // 0/__1___/_2__/______3______/__4___/____5_____/___6___/____7______/ // ./Vendor/MSFT/DiagnosticLog/EtwLog/Collectors/AzureDM/TraceStatus if (uriTokens[7] == CSPTraceStatus) { currentCollector->CSPConfiguration->Started = std::stoi(value) == 1 ? true : false; } else if (uriTokens[7] == CSPTraceLogFileMode) { currentCollector->CSPConfiguration->TraceLogFileMode = ref new String(std::stoi(value) == 1 ? JsonFileModeSequential : JsonFileModeCircular); } else if (uriTokens[7] == CSPLogFileSizeLimitMB) { currentCollector->CSPConfiguration->LogFileSizeLimitMB = std::stoi(value); } } // Is this something under the Providers node? if (uriTokens.size() >= 9 && uriTokens[7] == CSPProvidersNode) { // 0/__1___/_2__/______3______/__4___/____5_____/___6___/____7____/_8__ // ./Vendor/MSFT/DiagnosticLog/EtwLog/Collectors/AzureDM/Providers/guid // Make sure the Providers list exists... if (currentCollector->CSPConfiguration->Providers == nullptr) { currentCollector->CSPConfiguration->Providers = ref new Vector<ProviderConfiguration^>(); } // Do we already have this provider? ProviderConfiguration^ currentProvider; for (auto provider : currentCollector->CSPConfiguration->Providers) { if (0 == _wcsicmp(provider->Guid->Data(), uriTokens[8].c_str())) { currentProvider = provider; } } // If we don't already have the provider, create a new one... if (currentProvider == nullptr) { ProviderConfiguration^ provider = ref new ProviderConfiguration(); provider->Guid = ref new String(uriTokens[8].c_str()); currentCollector->CSPConfiguration->Providers->Append(provider); currentProvider = provider; } // Is this a sub-property of the current provider? if (uriTokens.size() >= 10) { // 0/__1___/_2__/______3______/__4___/____5_____/___6___/___7_____/_8__/____9____ // ./Vendor/MSFT/DiagnosticLog/EtwLog/Collectors/AzureDM/Providers/guid/TraceLevel if (uriTokens[9] == CSPTraceLevel) { wstring jsonValue; if (value == L"1") { jsonValue = JsonTraceLevelCritical; } else if (value == L"2") { jsonValue = JsonTraceLevelError; } else if (value == L"3") { jsonValue = JsonTraceLevelWarning; } else if (value == L"4") { jsonValue = JsonTraceLevelInformation; } else if (value == L"5") { jsonValue = JsonTraceLevelVerbose; } currentProvider->TraceLevel = ref new String(jsonValue.c_str()); } else if (uriTokens[9] == CSPKeywords) { currentProvider->Keywords = ref new String(value.c_str()); } else if (uriTokens[9] == CSPState) { currentProvider->Enabled = (0 == _wcsicmp(value.c_str(), CSPTrue)) ? true : false; } } } }; wstring cspQuery; cspQuery += CSPCollectorsRoot; cspQuery += CSPQuerySuffix; MdmProvision::RunGetStructData(cspQuery, valueHandler); return response; } wstring DiagnosticLogCSP::GetFormattedTime() { TRACE(__FUNCTION__); time_t now; time(&now); tm nowParsed; errno_t errCode = localtime_s(&nowParsed, &now); if (errCode != 0) { string errorMessage = "Error: could not obtain local time."; TRACE(errorMessage.c_str()); throw DMException(errorMessage.c_str()); } basic_ostringstream<wchar_t> nowString; nowString << (nowParsed.tm_year + 1900) << L"_"; nowString << setw(2) << setfill(L'0') << (nowParsed.tm_mon + 1) << L"_"; nowString << setw(2) << setfill(L'0') << nowParsed.tm_mday << L"_"; nowString << setw(2) << setfill(L'0') << nowParsed.tm_hour << L"_"; nowString << setw(2) << setfill(L'0') << nowParsed.tm_min << L"_"; nowString << setw(2) << setfill(L'0') << nowParsed.tm_sec; return nowString.str(); } void DiagnosticLogCSP::CreateEtlFile(CollectorDesiredConfiguration^ collector) { TRACE(__FUNCTION__); // The etl file will be created in a folder like this: // c:\Data\Users\DefaultAccount\AppData\Local\Temp\<collector's folder> // Construct the data channel... wstring collectorFileCSPPath; collectorFileCSPPath += CSPDataChannel; collectorFileCSPPath += L"/"; collectorFileCSPPath += collector->Name->Data(); // Read data from CSP into our buffers... vector<vector<char>> decryptedEtlBuffer; int blockCount = 0; if (MdmProvision::TryGetNumber(collectorFileCSPPath + L"/" + CSPBlockCount, blockCount)) { for (int i = 0; i < blockCount; ++i) { MdmProvision::RunSet(collectorFileCSPPath + L"/" + CSPBlockIndexToRead, i); wstring blockData = MdmProvision::RunGetBase64(collectorFileCSPPath + L"/BlockData"); vector<char> decryptedBlock; Utils::Base64ToBinary(blockData, decryptedBlock); decryptedEtlBuffer.push_back(decryptedBlock); } } // Make sure the target folder exists... wstring etlFolderName; etlFolderName += Utils::GetDmUserFolder(); etlFolderName += L"\\"; etlFolderName += collector->CSPConfiguration->LogFileFolder->Data(); CreateDirectory(etlFolderName.c_str(), NULL); // Construct the file name... wstring etlFileName; if (collector->CSPConfiguration->LogFileName->Length() == 0) { etlFileName += collector->Name->Data(); etlFileName += L"_"; etlFileName += GetFormattedTime(); etlFileName += L".etl"; } else { etlFileName = collector->CSPConfiguration->LogFileName->Data(); } wstring etlFullFileName = etlFolderName + L"\\" + etlFileName; TRACEP(L"ETL Full File Name: ", etlFullFileName.c_str()); // Write the buffers to disk... ofstream etlFile(etlFullFileName, ios::out | ios::binary); for (auto it = decryptedEtlBuffer.begin(); it != decryptedEtlBuffer.end(); it++) { etlFile.write(it->data(), it->size()); } etlFile.close(); } void DiagnosticLogCSP::ApplyCollectorConfiguration(const wstring& cspRoot, CollectorDesiredConfiguration^ collector) { TRACE(__FUNCTION__); // Some validation... // If there is no configuration, there is no need to continue. if (collector->CSPConfiguration == nullptr) { TRACE(L"Warning: CSPConfiguration is nullptr."); return; } // ETL files cannot be saved to the IoTDM folder. // They have to be saved to a subfolder of IoTDM. if (collector->CSPConfiguration->LogFileFolder == nullptr || collector->CSPConfiguration->LogFileFolder->Length() == 0) { TRACE(L"Warning: LogFileFolder is null or empty. Using collector name as the LogFileFolder."); collector->CSPConfiguration->LogFileFolder = collector->Name; } // Make sure the user is not trying to access any files outside the IoTDM folder. if (nullptr != wcsstr(collector->CSPConfiguration->LogFileFolder->Data(), L"..") || nullptr != wcsstr(collector->CSPConfiguration->LogFileFolder->Data(), L"\\") || nullptr != wcsstr(collector->CSPConfiguration->LogFileFolder->Data(), L"/")) { string errorMessage = "Error: LogFileFolder cannot contain '/', '\\', or '..'."; TRACE(errorMessage.c_str()); throw DMException(errorMessage.c_str()); } if (collector->CSPConfiguration->LogFileName->Length() != 0) { if (nullptr != wcsstr(collector->CSPConfiguration->LogFileName->Data(), L"..") || nullptr != wcsstr(collector->CSPConfiguration->LogFileName->Data(), L"\\") || nullptr != wcsstr(collector->CSPConfiguration->LogFileName->Data(), L"/")) { string errorMessage = "Error: LogFileName cannot contain '/', '\\', or '..'."; TRACE(errorMessage.c_str()); throw DMException(errorMessage.c_str()); } } // Build paths... const wstring collectorCSPPath = cspRoot + L"/" + collector->Name->Data(); const wstring providersCSPPath = collectorCSPPath + L"/" + CSPProvidersNode; wstring collectorRegistryPath = RegEventTracing; collectorRegistryPath += L"\\"; collectorRegistryPath += collector->Name->Data(); // Add CSP node and set its properties... MdmProvision::RunAdd(cspRoot, collector->Name->Data()); Utils::WriteRegistryValue(collectorRegistryPath, RegReportToDeviceTwin, collector->ReportToDeviceTwin->Data()); Utils::WriteRegistryValue(collectorRegistryPath, RegEventTracingLogFileFolder, collector->CSPConfiguration->LogFileFolder->Data()); Utils::WriteRegistryValue(collectorRegistryPath, RegEventTracingLogFileName, collector->CSPConfiguration->LogFileName->Data()); MdmProvision::RunSet(collectorCSPPath + L"/LogFileSizeLimitMB", collector->CSPConfiguration->LogFileSizeLimitMB); MdmProvision::RunSet(collectorCSPPath + L"/TraceLogFileMode", collector->CSPConfiguration->TraceLogFileMode == L"sequential" ? 1 : 2); // Capture which providers are already part of this CSP collector configuration... wstring providersString = MdmProvision::RunGetString(providersCSPPath, true /*optional*/); // Iterate though each desired provider and add/apply its settings... for each (ProviderConfiguration^ provider in collector->CSPConfiguration->Providers) { wstring providerCSPPath = collectorCSPPath + L"/" + CSPProvidersNode + L"/" + provider->Guid->Data(); // Is the provider already part of this CSP collector configuration? if (wstring::npos == providersString.find(provider->Guid->Data())) { MdmProvision::RunAddTyped(providerCSPPath, CSPNodeType); } int traceLevel = 0; if (0 == _wcsicmp(provider->TraceLevel->Data(), JsonTraceLevelCritical)) { traceLevel = 1; } else if (0 == _wcsicmp(provider->TraceLevel->Data(), JsonTraceLevelError)) { traceLevel = 2; } else if (0 == _wcsicmp(provider->TraceLevel->Data(), JsonTraceLevelWarning)) { traceLevel = 3; } else if (0 == _wcsicmp(provider->TraceLevel->Data(), JsonTraceLevelInformation)) { traceLevel = 4; } else if (0 == _wcsicmp(provider->TraceLevel->Data(), JsonTraceLevelVerbose)) { traceLevel = 5; } MdmProvision::RunSet(providerCSPPath + L"/" + CSPState, provider->Enabled); MdmProvision::RunSet(providerCSPPath + L"/" + CSPKeywords, wstring(provider->Keywords->Data())); MdmProvision::RunSet(providerCSPPath + L"/" + CSPTraceLevel, traceLevel); } // Finally process the started/stopped status... unsigned int traceStatus = MdmProvision::RunGetUInt(collectorCSPPath + L"/" + CSPTraceStatus); if (collector->CSPConfiguration->Started) { if (traceStatus == 0 /*stopped*/) { TRACEP(L"Starting logging for ", collector->Name->Data()); MdmProvision::RunExecWithParameters(collectorCSPPath + L"/" + CSPTraceControl, CSPTraceControlStart); } } else { if (traceStatus == 1 /*started*/) { TRACEP(L"Stopping logging for ", collector->Name->Data()); MdmProvision::RunExecWithParameters(collectorCSPPath + L"/" + CSPTraceControl, CSPTraceControlStop); CreateEtlFile(collector); } } } IResponse^ DiagnosticLogCSP::HandleSetEventTracingConfiguration(IRequest^ request) { TRACE(__FUNCTION__); // ToDo: There is a bug in the CSP where if C:\Data\Users\Public\Documents // does not exist, it fails to start capturing events. // To work around that, we are making sure the documents folder exists. Utils::EnsureFolderExists(DiagnosticLogCSPWorkingFolder); auto eventTracingConfiguration = dynamic_cast<SetEventTracingConfigurationRequest^>(request); for each (CollectorDesiredConfiguration^ collector in eventTracingConfiguration->Collectors) { ApplyCollectorConfiguration(CSPCollectorsRoot, collector); } return ref new StringResponse(ResponseStatus::Success, ref new String(), DMMessageKind::SetEventTracingConfiguration); }
41.033708
196
0.648028
cf54ff4ccd37abfe5c66d8b83cbe74fcf6f7a80b
24,755
cpp
C++
src/test_infNaN_iamax.cpp
tlapack/testBLAS
dd63ade035880783cd55a8032c13a6d8e85dc490
[ "BSD-3-Clause" ]
null
null
null
src/test_infNaN_iamax.cpp
tlapack/testBLAS
dd63ade035880783cd55a8032c13a6d8e85dc490
[ "BSD-3-Clause" ]
null
null
null
src/test_infNaN_iamax.cpp
tlapack/testBLAS
dd63ade035880783cd55a8032c13a6d8e85dc490
[ "BSD-3-Clause" ]
1
2021-06-28T21:13:49.000Z
2021-06-28T21:13:49.000Z
/// @file test_infNaN_iamax.cpp /// @brief Test cases for iamax with NaNs, Infs and the overflow threshold (OV). // // Copyright (c) 2021, University of Colorado Denver. All rights reserved. // // This file is part of testBLAS. // testBLAS is free software: you can redistribute it and/or modify it under // the terms of the BSD 3-Clause license. See the accompanying LICENSE file. #include <catch2/catch.hpp> #include <tblas.hpp> #include "defines.hpp" #include "utils.hpp" #include <limits> #include <vector> #include <complex> using namespace blas; // ----------------------------------------------------------------------------- // Auxiliary routines /** * @brief Set Ak = -k + i*k */ template< typename real_t > inline void set_complexk( std::complex<real_t>& Ak, blas::idx_t k ){ Ak = std::complex<real_t>( -k, k ); } template< typename real_t > inline void set_complexk( real_t& Ak, blas::idx_t k ){ static_assert( ! is_complex<real_t>::value, "real_t must be a Real type." ); } /** * @brief Set Ak = OV * ((k+2)/(k+3)) * (1+i) */ template< typename real_t > inline void set_complexOV( std::complex<real_t>& Ak, blas::idx_t k ){ const real_t OV = std::numeric_limits<real_t>::max(); Ak = OV * (real_t)((k+2.)/(k+3.)) * std::complex<real_t>( 1, 1 ); } template< typename real_t > inline void set_complexOV( real_t& Ak, blas::idx_t k ){ static_assert( ! is_complex<real_t>::value, "real_t must be a Real type." ); } // ----------------------------------------------------------------------------- // Test cases for iamax with Infs and NaNs at specific positions /** * @brief Check if iamax( n, A, 1 ) works as expected using exactly 1 NaN * * NaN locations: @see testBLAS::set_array_locations * * If checkWithInf == true: * For NaN location above: * Insert Inf in first non-NaN location * Insert -Inf in first non-NaN location * Ditto for last non-NaN location * Ditto for first and last non-NaN locations * * @param[in] n * Size of A * @param[in] A * Array with non-NAN data * @param[in] checkWithInf * If true, run the test cases with Infs. */ template< typename TestType > void check_iamax_1nan( const blas::idx_t n, TestType A[], const bool checkWithInf = true ) { using real_t = real_type<TestType>; std::vector<TestType> nan_vec; testBLAS::set_nan_vector( nan_vec ); // Indexes for test std::vector<blas::idx_t> k_vec; testBLAS::set_array_locations( n, k_vec ); // Tests for (const auto& k : k_vec) { const TestType Ak = A[k]; const blas::idx_t infIdx1 = (k > 0) ? 0 : 1; const blas::idx_t infIdx2 = (k < n-1) ? n-1 : n-2; for (const auto& aNAN : nan_vec) { // NaN in A[k] A[k] = aNAN; // No Infs CHECK( iamax( n, A, 1 ) == k ); if( checkWithInf && n > 1 ) { const real_t inf = std::numeric_limits<real_t>::infinity(); const TestType AinfIdx1 = A[ infIdx1 ]; // Inf in first non-NaN location A[ infIdx1 ] = inf; CHECK( iamax( n, A, 1 ) == k ); // -Inf in first non-NaN location A[ infIdx1 ] = -inf; CHECK( iamax( n, A, 1 ) == k ); if( n > 2 ) { const TestType AinfIdx2 = A[ infIdx2 ]; // Inf in last non-NaN location A[ infIdx2 ] = inf; CHECK( iamax( n, A, 1 ) == k ); // -Inf in last non-NaN location A[ infIdx2 ] = -inf; CHECK( iamax( n, A, 1 ) == k ); // Inf in first and last non-NaN location A[ infIdx1 ] = A[ infIdx2 ] = inf; CHECK( iamax( n, A, 1 ) == k ); // -Inf in first and last non-NaN location A[ infIdx1 ] = A[ infIdx2 ] = -inf; CHECK( iamax( n, A, 1 ) == k ); // Reset value A[ infIdx2 ] = AinfIdx2; } // Reset value A[ infIdx1 ] = AinfIdx1; } // Reset value A[k] = Ak; } } } /** * @brief Check if iamax( n, A, 1 ) works as expected using exactly 2 NaNs * * NaN locations: @see testBLAS::set_array_pairLocations * * If checkWithInf == true: * For NaN location above: * Insert Inf in first non-NaN location * Insert -Inf in first non-NaN location * Ditto for last non-NaN location * Ditto for first and last non-NaN locations * * @param[in] n * Size of A * @param[in] A * Array with non-NAN data * @param[in] checkWithInf * If true, run the test cases with Infs. */ template< typename TestType > void check_iamax_2nans( const blas::idx_t n, TestType A[], const bool checkWithInf = true ) { using real_t = real_type<TestType>; std::vector<TestType> nan_vec; testBLAS::set_nan_vector( nan_vec ); // Indexes for test std::vector<blas::idx_t> k_vec; testBLAS::set_array_pairLocations( n, k_vec ); // Tests for (unsigned i = 0; i < k_vec.size(); i += 2) { const auto& k1 = k_vec[i]; const auto& k2 = k_vec[i+1]; const TestType Ak1 = A[k1]; const TestType Ak2 = A[k2]; const blas::idx_t infIdx1 = (k1 > 0) ? 0 : ( (k2 > 1) ? 1 : 2 ); const blas::idx_t infIdx2 = (k2 < n-1) ? n-1 : ( (k1 < n-2) ? n-2 : n-3 ); for (const auto& aNAN : nan_vec) { // NaNs in A[k1] and A[k2] A[k1] = A[k2] = aNAN; // No Infs CHECK( iamax( n, A, 1 ) == k1 ); if( checkWithInf && n > 2 ) { const real_t inf = std::numeric_limits<real_t>::infinity(); const TestType AinfIdx1 = A[ infIdx1 ]; // Inf in first non-NaN location A[ infIdx1 ] = inf; CHECK( iamax( n, A, 1 ) == k1 ); // -Inf in first non-NaN location A[ infIdx1 ] = -inf; CHECK( iamax( n, A, 1 ) == k1 ); if( n > 3 ) { const TestType AinfIdx2 = A[ infIdx2 ]; // Inf in last non-NaN location A[ infIdx2 ] = inf; CHECK( iamax( n, A, 1 ) == k1 ); // -Inf in last non-NaN location A[ infIdx2 ] = -inf; CHECK( iamax( n, A, 1 ) == k1 ); // Inf in first and last non-NaN location A[ infIdx1 ] = A[ infIdx2 ] = inf; CHECK( iamax( n, A, 1 ) == k1 ); // -Inf in first and last non-NaN location A[ infIdx1 ] = A[ infIdx2 ] = -inf; CHECK( iamax( n, A, 1 ) == k1 ); // Reset value A[ infIdx2 ] = AinfIdx2; } // Reset value A[ infIdx1 ] = AinfIdx1; } // Reset values A[k1] = Ak1; A[k2] = Ak2; } } } /** * @brief Check if iamax( n, A, 1 ) works as expected using exactly 3 NaNs * * NaN locations: @see testBLAS::set_array_trioLocations * * If checkWithInf == true: * For NaN location above: * Insert Inf in first non-NaN location * Insert -Inf in first non-NaN location * Ditto for last non-NaN location * Ditto for first and last non-NaN locations * * @param[in] n * Size of A * @param[in] A * Array with non-NAN data * @param[in] checkWithInf * If true, run the test cases with Infs. */ template< typename TestType > void check_iamax_3nans( const blas::idx_t n, TestType A[], const bool checkWithInf = true ) { using real_t = real_type<TestType>; std::vector<TestType> nan_vec; testBLAS::set_nan_vector( nan_vec ); // Indexes for test std::vector<blas::idx_t> k_vec; testBLAS::set_array_trioLocations( n, k_vec ); // Tests for (unsigned i = 0; i < k_vec.size(); i += 3) { const auto& k1 = k_vec[i]; const auto& k2 = k_vec[i+1]; const auto& k3 = k_vec[i+2]; const TestType Ak1 = A[k1]; const TestType Ak2 = A[k2]; const TestType Ak3 = A[k3]; const blas::idx_t infIdx1 = (k1 > 0) ? 0 : ( (k2 > 1) ? 1 : 2 ); const blas::idx_t infIdx2 = (k2 < n-1) ? n-1 : ( (k1 < n-2) ? n-2 : n-3 ); for (const auto& aNAN : nan_vec) { // NaNs in A[k1], A[k2] and A[k3] A[k1] = A[k2] = A[k3] = aNAN; // No Infs CHECK( iamax( n, A, 1 ) == k1 ); if( checkWithInf && n > 3 ) { const real_t inf = std::numeric_limits<real_t>::infinity(); const TestType AinfIdx1 = A[ infIdx1 ]; // Inf in first non-NaN location A[ infIdx1 ] = inf; CHECK( iamax( n, A, 1 ) == k1 ); // -Inf in first non-NaN location A[ infIdx1 ] = -inf; CHECK( iamax( n, A, 1 ) == k1 ); if( n > 4 ) { const TestType AinfIdx2 = A[ infIdx2 ]; // Inf in last non-NaN location A[ infIdx2 ] = inf; CHECK( iamax( n, A, 1 ) == k1 ); // -Inf in last non-NaN location A[ infIdx2 ] = -inf; CHECK( iamax( n, A, 1 ) == k1 ); // Inf in first and last non-NaN location A[ infIdx1 ] = A[ infIdx2 ] = inf; CHECK( iamax( n, A, 1 ) == k1 ); // -Inf in first and last non-NaN location A[ infIdx1 ] = A[ infIdx2 ] = -inf; CHECK( iamax( n, A, 1 ) == k1 ); // Reset value A[ infIdx2 ] = AinfIdx2; } // Reset value A[ infIdx1 ] = AinfIdx1; } // Reset values A[k1] = Ak1; A[k2] = Ak2; A[k3] = Ak3; } } } /** * @brief Check if iamax( n, A, 1 ) works as expected using exactly 1 Inf * * Inf locations: @see testBLAS::set_array_locations * * @param[in] n * Size of A. * @param[in] A * Array with finite values. */ template< typename TestType > void check_iamax_1inf( const blas::idx_t n, TestType A[] ) { std::vector<TestType> inf_vec; testBLAS::set_inf_vector( inf_vec ); // Indexes for test std::vector<blas::idx_t> k_vec; testBLAS::set_array_locations( n, k_vec ); // Tests for (const auto& k : k_vec) { const TestType Ak = A[k]; for (const auto& aInf : inf_vec) { // (-1)^k*Inf in A[k] A[k] = ( k % 2 == 0 ) ? aInf : -aInf; // No Infs CHECK( iamax( n, A, 1 ) == k ); // Reset value A[k] = Ak; } } } /** * @brief Check if iamax( n, A, 1 ) works as expected using exactly 2 Infs * * Inf locations: @see testBLAS::set_array_pairLocations * * @param[in] n * Size of A. * @param[in] A * Array with finite values. */ template< typename TestType > void check_iamax_2infs( const blas::idx_t n, TestType A[] ) { std::vector<TestType> inf_vec; testBLAS::set_inf_vector( inf_vec ); // Indexes for test std::vector<blas::idx_t> k_vec; testBLAS::set_array_pairLocations( n, k_vec ); // Tests for (unsigned i = 0; i < k_vec.size(); i += 2) { const auto& k1 = k_vec[i]; const auto& k2 = k_vec[i+1]; const TestType Ak1 = A[k1]; const TestType Ak2 = A[k2]; for (const auto& aInf : inf_vec) { // (-1)^k*Inf in A[k] A[k1] = ( k1 % 2 == 0 ) ? aInf : -aInf; A[k2] = ( k2 % 2 == 0 ) ? aInf : -aInf; CHECK( iamax( n, A, 1 ) == k1 ); // Reset values A[k1] = Ak1; A[k2] = Ak2; } } } /** * @brief Check if iamax( n, A, 1 ) works as expected using exactly 3 Infs * * Inf locations: @see testBLAS::set_array_trioLocations * * @param[in] n * Size of A. * @param[in] A * Array with finite values. */ template< typename TestType > void check_iamax_3infs( const blas::idx_t n, TestType A[] ) { std::vector<TestType> inf_vec; testBLAS::set_inf_vector( inf_vec ); // Indexes for test std::vector<blas::idx_t> k_vec; testBLAS::set_array_trioLocations( n, k_vec ); // Tests for (unsigned i = 0; i < k_vec.size(); i += 3) { const auto& k1 = k_vec[i]; const auto& k2 = k_vec[i+1]; const auto& k3 = k_vec[i+2]; const TestType Ak1 = A[k1]; const TestType Ak2 = A[k2]; const TestType Ak3 = A[k3]; for (const auto& aInf : inf_vec) { // (-1)^k*Inf in A[k] A[k1] = ( k1 % 2 == 0 ) ? aInf : -aInf; A[k2] = ( k2 % 2 == 0 ) ? aInf : -aInf; A[k3] = ( k3 % 2 == 0 ) ? aInf : -aInf; CHECK( iamax( n, A, 1 ) == k1 ); // Reset values A[k1] = Ak1; A[k2] = Ak2; A[k3] = Ak3; } } } // ----------------------------------------------------------------------------- // Main Test Cases /** * @brief Test case for iamax with arrays containing at least 1 NaN * * Default entries: * (1) A[k] = (-1)^k*k * (2) A[k] = (-1)^k*Inf * and, for complex data type: * (3) A[k] = -k + i*k for k even, and A[k] = OV*((k+2)/(k+3))*(1+i) for k odd * (4) A[k] = OV*((k+2)/(k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd * (5) A[k] = -k + i*k for k even, and A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k odd * (6) A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd */ TEMPLATE_TEST_CASE( "iamax returns the first NaN for real arrays with at least 1 NaN", "[iamax][BLASlv1][NaN]", TEST_TYPES ) { using real_t = real_type<TestType>; // Constants const blas::idx_t N = 128; // N > 0 const TestType inf = std::numeric_limits<real_t>::infinity(); // Arrays const std::vector<blas::idx_t> n_vec = { 1, 2, 3, 10, N }; // n_vec[i] > 0 TestType A[N]; SECTION( "At least 1 NaN in the array A" ) { WHEN( "A[k] = (-1)^k*k" ) { for (blas::idx_t k = 0; k < N; ++k) A[k] = ( k % 2 == 0 ) ? k : -k; for (const auto& n : n_vec) { check_iamax_1nan( n, A ); check_iamax_2nans( n, A ); check_iamax_3nans( n, A ); } } WHEN( "A[k] = (-1)^k*Inf" ) { for (blas::idx_t k = 0; k < N; ++k) A[k] = ( k % 2 == 0 ) ? inf : -inf; for (const auto& n : n_vec) { check_iamax_1nan( n, A, false ); check_iamax_2nans( n, A, false ); check_iamax_3nans( n, A, false ); } } if (is_complex<TestType>::value) { WHEN( "A[k] = -k + i*k for k even, and A[k] = OV*((k+2)/(k+3))*(1+i) for k odd" ) { for (blas::idx_t k = 0; k < N; ++k) { if ( k % 2 == 0 ) set_complexk( A[k], k ); else set_complexOV( A[k], k ); } for (const auto& n : n_vec) { check_iamax_1nan( n, A ); check_iamax_2nans( n, A ); check_iamax_3nans( n, A ); } } WHEN( "A[k] = OV*((k+2)/(k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd" ) { for (blas::idx_t k = 0; k < N; ++k) { if ( k % 2 == 0 ) set_complexOV( A[k], k ); else set_complexk( A[k], k ); } for (const auto& n : n_vec) { check_iamax_1nan( n, A ); check_iamax_2nans( n, A ); check_iamax_3nans( n, A ); } } WHEN( "A[k] = -k + i*k for k even, and A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k odd" ) { for (const auto& n : n_vec) { for (blas::idx_t k = 0; k < n; ++k) { if ( k % 2 == 0 ) set_complexk( A[k], k ); else set_complexOV( A[k], n-k ); } check_iamax_1nan( n, A ); check_iamax_2nans( n, A ); check_iamax_3nans( n, A ); } } WHEN( "A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd" ) { for (const auto& n : n_vec) { for (blas::idx_t k = 0; k < n; ++k) { if ( k % 2 == 0 ) set_complexOV( A[k], n-k ); else set_complexk( A[k], k ); } check_iamax_1nan( n, A ); check_iamax_2nans( n, A ); check_iamax_3nans( n, A ); } } } } SECTION( "All NaNs" ) { for (blas::idx_t k = 0; k < N; ++k) A[k] = NAN; for (const auto& n : n_vec) CHECK( iamax( n, A, 1 ) == 0 ); } } /** * @brief Test case for iamax with arrays containing at least 1 Inf and no NaNs * * Default entries: * (1) A[k] = (-1)^k*k * and, for complex data type: * (3) A[k] = -k + i*k for k even, and A[k] = OV*((k+2)/(k+3))*(1+i) for k odd * (4) A[k] = OV*((k+2)/(k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd * (5) A[k] = -k + i*k for k even, and A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k odd * (6) A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd */ TEMPLATE_TEST_CASE( "iamax returns the first Inf for real arrays with at least 1 Inf and no NaNs", "[iamax][BLASlv1][Inf]", TEST_TYPES ) { using real_t = real_type<TestType>; // Constants const blas::idx_t N = 128; // N > 0 const TestType inf = std::numeric_limits<real_t>::infinity(); // Arrays const std::vector<blas::idx_t> n_vec = { 1, 2, 3, 10, N }; // n_vec[i] > 0 TestType A[N]; SECTION( "At least 1 Inf in the array A" ) { WHEN( "A[k] = (-1)^k*k" ) { for (blas::idx_t k = 0; k < N; ++k) A[k] = ( k % 2 == 0 ) ? k : -k; for (const auto& n : n_vec) { check_iamax_1inf( n, A ); check_iamax_2infs( n, A ); check_iamax_3infs( n, A ); } } if (is_complex<TestType>::value) { WHEN( "A[k] = -k + i*k for k even, and A[k] = OV*((k+2)/(k+3))*(1+i) for k odd" ) { for (blas::idx_t k = 0; k < N; ++k) { if ( k % 2 == 0 ) set_complexk( A[k], k ); else set_complexOV( A[k], k ); } for (const auto& n : n_vec) { check_iamax_1inf( n, A ); check_iamax_2infs( n, A ); check_iamax_3infs( n, A ); } } WHEN( "A[k] = OV*((k+2)/(k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd" ) { for (blas::idx_t k = 0; k < N; ++k) { if ( k % 2 == 0 ) set_complexOV( A[k], k ); else set_complexk( A[k], k ); } for (const auto& n : n_vec) { check_iamax_1inf( n, A ); check_iamax_2infs( n, A ); check_iamax_3infs( n, A ); } } WHEN( "A[k] = -k + i*k for k even, and A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k odd" ) { for (const auto& n : n_vec) { for (blas::idx_t k = 0; k < n; ++k) { if ( k % 2 == 0 ) set_complexk( A[k], k ); else set_complexOV( A[k], n-k ); } check_iamax_1inf( n, A ); check_iamax_2infs( n, A ); check_iamax_3infs( n, A ); } } WHEN( "A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd" ) { for (const auto& n : n_vec) { for (blas::idx_t k = 0; k < n; ++k) { if ( k % 2 == 0 ) set_complexOV( A[k], n-k ); else set_complexk( A[k], k ); } check_iamax_1inf( n, A ); check_iamax_2infs( n, A ); check_iamax_3infs( n, A ); } } } } SECTION( "All Infs" ) { for (blas::idx_t k = 0; k < N; ++k) A[k] = ( k % 2 == 0 ) ? inf : -inf; for (const auto& n : n_vec) CHECK( iamax( n, A, 1 ) == 0 ); } } /** * @brief Test case for iamax where A(k) are finite but abs(real(A(k)))+abs(imag(A(k))) can overflow. * * 4 cases: * A(k) = -k + i*k for k even, A(k) = OV*((k+2)/(k+3)) + i*OV*((k+2)/(k+3)) for k odd. * (Correct answer = last odd k) * Swap odd and even. (Correct answer = last even k) * A(k) = -k + i*k for k even, A(k) = OV*((n-k+2)/(n-k+3)) + i*OV*((n-k+2)/(n-k+3)) for k odd. * (Correct answer = 1) * Swap odd and even (Correct answer = 2). */ TEMPLATE_TEST_CASE( "iamax works for complex data A when abs(real(A(k)))+abs(imag(A(k))) can overflow", "[iamax][BLASlv1]", TEST_CPLX_TYPES ) { // Constants const blas::idx_t N = 128; // N > 0 // Arrays const std::vector<blas::idx_t> n_vec = { 1, 2, 3, 10, N }; // n_vec[i] > 0 TestType A[N]; WHEN( "A[k] = -k + i*k for k even, and A[k] = OV*((k+2)/(k+3))*(1+i) for k odd" ) { for (blas::idx_t k = 0; k < N; ++k) { if ( k % 2 == 0 ) set_complexk( A[k], k ); else set_complexOV( A[k], k ); } for (const auto& n : n_vec) { if ( n == 1 ) CHECK( iamax( n, A, 1 ) == 0 ); else if ( n % 2 == 0 ) CHECK( iamax( n, A, 1 ) == n-1 ); else CHECK( iamax( n, A, 1 ) == n-2 ); } } WHEN( "A[k] = OV*((k+2)/(k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd" ) { for (blas::idx_t k = 0; k < N; ++k) { if ( k % 2 == 0 ) set_complexOV( A[k], k ); else set_complexk( A[k], k ); } for (const auto& n : n_vec) { if ( n == 1 ) CHECK( iamax( n, A, 1 ) == 0 ); else if ( n % 2 == 0 ) CHECK( iamax( n, A, 1 ) == n-2 ); else CHECK( iamax( n, A, 1 ) == n-1 ); } } WHEN( "A[k] = -k + i*k for k even, and A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k odd" ) { for (const auto& n : n_vec) { for (blas::idx_t k = 0; k < n; ++k) { if ( k % 2 == 0 ) set_complexk( A[k], k ); else set_complexOV( A[k], n-k ); } if ( n == 1 ) CHECK( iamax( n, A, 1 ) == 0 ); else CHECK( iamax( n, A, 1 ) == 1 ); } } WHEN( "A[k] = OV*((n-k+2)/(n-k+3))*(1+i) for k even, and A[k] = -k + i*k for k odd" ) { for (const auto& n : n_vec) { for (blas::idx_t k = 0; k < n; ++k) { if ( k % 2 == 0 ) set_complexOV( A[k], n-k ); else set_complexk( A[k], k ); } CHECK( iamax( n, A, 1 ) == 0 ); } } }
32.317232
103
0.428277
cf572f7d6c43f4e28dbc736337834fbc72e648fd
5,679
cpp
C++
src/visitors/interp_visitor.cpp
ut-amrl/pips
1f553dc850f8c27a460f020d91b35c8a18c479bb
[ "MIT" ]
null
null
null
src/visitors/interp_visitor.cpp
ut-amrl/pips
1f553dc850f8c27a460f020d91b35c8a18c479bb
[ "MIT" ]
null
null
null
src/visitors/interp_visitor.cpp
ut-amrl/pips
1f553dc850f8c27a460f020d91b35c8a18c479bb
[ "MIT" ]
null
null
null
#include "interp_visitor.hpp" #include <eigen3/Eigen/Core> // Vector2f #include <iostream> // cout, endl #include <memory> // make_shared #include <stdexcept> // invalid_argument #include <string> // string #include "ast/library_functions.hpp" using Eigen::Vector2f; using std::cout; using std::endl; using std::invalid_argument; using std::make_shared; using std::string; namespace AST { ast_ptr Interpret(const ast_ptr& program) { Interp interpreter; const ast_ptr result = program->Accept(&interpreter); return result; } ast_ptr Interpret(const ast_ptr& program, const Example& example) { Interp interpreter(example); const ast_ptr result = program->Accept(&interpreter); return result; } bool InterpretBool(const ast_ptr& program, const Example& example) { Interp interpreter(example); ast_ptr result = program->Accept(&interpreter); if (result->type_ == BOOL) { bool_ptr bool_result = std::dynamic_pointer_cast<Bool>(result); return bool_result->value_; } throw invalid_argument("Not a boolean expression."); } Interp::Interp() {} Interp::Interp(const Example& world) : world_(world) {} ast_ptr Interp::Visit(AST* node) { return ast_ptr(node); } ast_ptr Interp::Visit(BinOp* node) { ast_ptr left = node->left_->Accept(this); ast_ptr right = node->right_->Accept(this); const string op = node->op_; BinOp partial(left, right, node->op_, node->type_, node->dims_); ast_ptr result = make_shared<BinOp>(partial); // Don't try to evaluate if one of the arguments is symbolic if (left->symbolic_ || right->symbolic_) { result->symbolic_ = true; } else { // One if clause per binary operation if (op == "Plus") { result = Plus(left, right); } else if (op == "Minus") { result = Minus(left, right); } else if (op == "Times") { result = Times(left, right); } else if (op == "DividedBy") { result = DividedBy(left, right); } else if (op == "Cross") { result = Cross(left, right); } else if (op == "Dot") { result = Dot(left, right); } else if (op == "SqDist") { result = SqDist(left, right); } else if (op == "AngleDist") { result = AngleDist(left, right); } else if (op == "And") { result = And(left, right); } else if (op == "Or") { result = Or(left, right); } else if (op == "Eq") { result = Eq(left, right); } else if (op == "Gt") { result = Gt(left, right); } else if (op == "Lt") { result = Lt(left, right); } else if (op == "Gte") { result = Gte(left, right); } else if (op == "Lte") { result = Lte(left, right); } else { throw invalid_argument("unknown binary operation `" + op + "'"); } } return result; } ast_ptr Interp::Visit(Bool* node) { return make_shared<Bool>(*node); } ast_ptr Interp::Visit(Feature* node) { if (node->current_value_ == nullptr) { throw invalid_argument("AST has unfilled feature holes"); } else { ast_ptr result = node->current_value_->Accept(this); return result; } } ast_ptr Interp::Visit(Num* node) { return make_shared<Num>(*node); } ast_ptr Interp::Visit(Param* node) { if (node->current_value_ == nullptr) { // throw invalid_argument("AST has unfilled parameter holes"); return make_shared<Param>(*node); } else { ast_ptr result = node->current_value_->Accept(this); return result; } } // TODO(jaholtz) Throw errors instead of printing ast_ptr Interp::Visit(UnOp* node) { ast_ptr input = node->input_->Accept(this); const string op = node->op_; UnOp partial(input, node->op_, node->type_, node->dims_); ast_ptr result = make_shared<UnOp>(partial); // Don't try to evaluate if the input is symbolic if (input->symbolic_) { result->symbolic_ = true; } else { // One if clause per unary operation if (op == "Abs") { result = Abs(input); } else if (op == "Sq") { result = Sq(input); } else if (op == "Cos") { result = Cos(input); } else if (op == "Sin") { result = Sin(input); } else if (op == "Heading") { result = Heading(input); } else if (op == "Angle") { result = Angle(input); } else if (op == "NormSq") { result = NormSq(input); } else if (op == "Norm") { result = NormSq(input); } else if (op == "Perp") { result = Perp(input); } else if (op == "VecX") { result = VecX(input); } else if (op == "VecY") { result = VecY(input); } else if (op == "Not") { result = Not(input); } else if (op == "StraightFreePathLength") { result = StraightFreePathLength(input, world_.obstacles_); } else { throw invalid_argument("unknown unary operation `" + op + "'"); } } return result; } ast_ptr Interp::Visit(Var* node) { if (world_.symbol_table_.find(node->name_) != world_.symbol_table_.end()) { if (node->type_ == NUM) { const float value = world_.symbol_table_[node->name_].GetValue(); Num var_value(value, node->dims_); return make_shared<Num>(var_value); } else if (node->type_ == VEC) { const Vector2f float_vec = world_.symbol_table_[node->name_].GetValue(); const Vector2f value = Vector2f(float_vec.data()); Vec vec(value, node->dims_); return make_shared<Vec>(vec); } else { cout << node->name_ << endl; cout << "Error: Variable has unhandled type." << endl; } } cout << node->name_ << endl; cout << "Error: Variable not in symbol table" << endl; return make_shared<Var>(*node); } ast_ptr Interp::Visit(Vec* node) { return make_shared<Vec>(*node); } } // namespace AST
30.368984
78
0.61296
cf5817e955fde871be13b3af2de4f1caa3b99a8c
4,052
cpp
C++
main.cpp
arcanelab/telnet
9a74ecd7f43b7ab9a5cdb3527efda8db85a39db2
[ "Unlicense", "MIT" ]
3
2016-03-31T06:42:14.000Z
2019-05-30T00:35:17.000Z
main.cpp
arcanelab/telnet
9a74ecd7f43b7ab9a5cdb3527efda8db85a39db2
[ "Unlicense", "MIT" ]
null
null
null
main.cpp
arcanelab/telnet
9a74ecd7f43b7ab9a5cdb3527efda8db85a39db2
[ "Unlicense", "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <direct.h> #ifdef WIN32 #pragma warning(disable:4996) #include <conio.h> #endif #include "telnet.h" bool getInputString(char *buf,int len) { bool ret = true; int index = 0; bool exit = false; while ( !exit ) { unsigned int client; const char *input = gTelnet->receiveMessage(client); if ( input ) { //printf("[%d] %s\r\n", client, input ); printf("%s", input ); } if ( kbhit() ) { char c = (char)getch(); if ( c == 10 || c == 13 ) { buf[index] = 0; exit = true; } else if ( c == 27 ) { buf[index] = 0; exit = true; ret = false; } else if ( c == 8 ) { if ( index ) { index--; printf("%c",c); printf(" ",c); printf("%c",c); } } if ( c >= 32 && c <= 127 ) { buf[index] = c; index++; printf("%c",c); if ( index == (len-1) ) break; } } } buf[index] = 0; printf("\n"); return ret; } int main(int argc, const char **argv) { if(argc == 1) { gTelnet = TELNET::createTelnetClient("127.0.0.1", 23); } else if(argc == 4) { // host, port, type(server or client) const char* host = argv[1]; printf("Host is: %s\r\n", host); const char* charPort = argv[2]; int port = atoi(charPort); printf("port is: %s\r\n", charPort); const char* type = argv[3]; printf("Type is: %s\r\n", type); if(stricmp(type, "server") == 0) { gTelnet = TELNET::createTelnetServer(host, port); } else if(stricmp(type, "client") == 0) { gTelnet = TELNET::createTelnetClient(host, port); } else { printf("Error>>>Parameter Type is not right, you should according the rule:\r\n"); printf("Host port [server/client]\r\n"); printf("Please hit any key to end the program and try again."); getchar(); return -1; } } else { printf("Error>>>Parameters is not right, you should according the rule:\r\n"); printf("Host port [server/client]\r\n"); printf("Please hit any key to end the program and try again."); getchar(); return -1; } if(!gTelnet) { printf("Error>>>Created a Telnet Server or Client failed.\r\nPlease make sure that the iP and port is right!\r\n"); printf("Please hit any key to end the program."); getchar(); return -2; } if ( gTelnet->haveConnection() ) { if ( gTelnet->isServer() ) { printf("Created a Telnet Server\r\n"); } else { printf("Created a Telnet Client.\r\n"); } printf("Type a message and hit 'enter' to send it.\r\n"); printf("Type 'bye' and hit enter to quit (or the escape key)\r\n"); while ( 1 ) { char buff[512]; if ( getInputString(buff,512) ) { if ( stricmp(buff,"bye") == 0 ) { break; } gTelnet->sendMessage(0,"%s\r\n", buff ); } else { break; } } } else { printf("Unable to establish a telnet connection!\r\n"); } TELNET::releaseTelnet(gTelnet); //return 0; }
25.167702
124
0.411649
cf587e787585f40839ca0cc1592ee6b659a8b0d8
6,200
cpp
C++
pnwtl/optionscontrols.cpp
Adept-Space/pn
d722f408cf3c3b8d0b8028846c0199969b6a103c
[ "BSD-3-Clause" ]
null
null
null
pnwtl/optionscontrols.cpp
Adept-Space/pn
d722f408cf3c3b8d0b8028846c0199969b6a103c
[ "BSD-3-Clause" ]
null
null
null
pnwtl/optionscontrols.cpp
Adept-Space/pn
d722f408cf3c3b8d0b8028846c0199969b6a103c
[ "BSD-3-Clause" ]
null
null
null
/** * @file optionscontrols.cpp * @brief Controls for options dialogs (and the like). * @author Simon Steele * @note Copyright (c) 2002-2011 Simon Steele - http://untidy.net/ * * Programmer's Notepad 2 : The license file (license.[txt|html]) describes * the conditions under which this source may be modified / distributed. */ #include "stdafx.h" #include "resource.h" #include "optionscontrols.h" #include "schemeconfig.h" #include "outputview.h" #include "third_party/scintilla/include/scilexer.h" ////////////////////////////////////////////////////////////////////////////// // CStyleDisplay ////////////////////////////////////////////////////////////////////////////// CStyleDisplay::CStyleDisplay() { m_Font = NULL; memset(&m_lf, 0, sizeof(LOGFONT)); } CStyleDisplay::~CStyleDisplay() { if(m_Font) delete m_Font; } void CStyleDisplay::SetBold(bool bold) { m_lf.lfWeight = (bold ? FW_BOLD : FW_NORMAL); UpdateFont(); } void CStyleDisplay::SetItalic(bool italic) { m_lf.lfItalic = italic; UpdateFont(); } void CStyleDisplay::SetUnderline(bool underline) { m_lf.lfUnderline = underline; UpdateFont(); } void CStyleDisplay::SetFontName(LPCTSTR fontname) { _tcscpy(m_lf.lfFaceName, fontname); UpdateFont(); } void CStyleDisplay::SetSize(int size, bool bInvalidate) { HDC dc = GetDC(); m_lf.lfHeight = -MulDiv(size, GetDeviceCaps(dc, LOGPIXELSY), 72); ReleaseDC(dc); if(bInvalidate) UpdateFont(); } void CStyleDisplay::SetFore(COLORREF fore) { m_Fore = fore; Invalidate(); } void CStyleDisplay::SetBack(COLORREF back) { m_Back = back; Invalidate(); } void CStyleDisplay::SetStyle(LPCTSTR fontname, int fontsize, COLORREF fore, COLORREF back, LPCTSTR name, bool bold, bool italic, bool underline) { m_Name = name; m_Fore = fore; m_Back = back; SetSize(fontsize, false); m_lf.lfWeight = (bold ? FW_BOLD : FW_NORMAL); m_lf.lfUnderline = underline; m_lf.lfItalic = italic; _tcscpy(m_lf.lfFaceName, fontname); UpdateFont(); } LRESULT CStyleDisplay::OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { PAINTSTRUCT ps; BeginPaint(&ps); CDC dc(ps.hdc); CRect rc; GetClientRect(rc); dc.FillRect(rc, (HBRUSH)::GetStockObject(WHITE_BRUSH)); // Draw in the example text. if(m_Font) { HFONT hOldFont = dc.SelectFont(m_Font->m_hFont); dc.SetBkColor(m_Back); dc.SetTextColor(m_Fore); dc.DrawText(m_Name, m_Name.GetLength(), rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE); dc.SelectFont(hOldFont); } // Draw a light border around the control. HBRUSH light = ::GetSysColorBrush(COLOR_3DSHADOW); dc.FrameRect(rc, light); EndPaint(&ps); return 0; } LRESULT CStyleDisplay::OnEraseBkgnd(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { return 1; } void CStyleDisplay::UpdateFont() { if(m_Font) delete m_Font; m_Font = new CFont; m_Font->CreateFontIndirect(&m_lf); Invalidate(); } ////////////////////////////////////////////////////////////////////////////// // CScintillaREDialogWnd ////////////////////////////////////////////////////////////////////////////// int CScintillaREDialogWnd::HandleNotify(LPARAM lParam) { Scintilla::SCNotification *scn = (Scintilla::SCNotification*)lParam; if( scn->nmhdr.code == SCN_HOTSPOTCLICK ) { int style = GetStyleAt(scn->position); GetParent().PostMessage(PN_HANDLEHSCLICK, style, scn->position); return 0; } else return baseClass::HandleNotify(lParam); } ////////////////////////////////////////////////////////////////////////////// // CSchemeCombo ////////////////////////////////////////////////////////////////////////////// int CSchemeCombo::AddScheme(LPCTSTR title, SchemeDetails* pScheme) { int index = AddString(title); SetItemDataPtr(index, pScheme); return index; } void CSchemeCombo::Load(SchemeConfigParser* pConfig, LPCSTR selectScheme, bool bIncludePlainText, bool bIncludeInternal) { LPCSTR schemeToSelect = (selectScheme ? selectScheme : pConfig->GetCurrentScheme()); Clear(); tstring schemeText; if (bIncludePlainText) { schemeText = LS(IDS_DEFAULTSCHEME); int index = AddString(schemeText.c_str()); SetItemDataPtr(index, pConfig->GetPlainTextScheme()); } for (SchemeDetailsList::const_iterator i = pConfig->GetSchemes().begin(); i != pConfig->GetSchemes().end(); ++i) { // Skip internal (special) schemes? if (!bIncludeInternal && (*i)->IsInternal()) continue; int index = AddString((*i)->Title.c_str()); SetItemDataPtr(index, (*i)); if((*i)->Name == schemeToSelect) schemeText = (*i)->Title; } if (schemeText.size()) { SelectString(0, schemeText.c_str()); } else { // Default: select the first scheme. SetCurSel(0); } } SchemeDetails* CSchemeCombo::GetItemScheme(int index) { return static_cast<SchemeDetails*>(GetItemDataPtr(index)); } LRESULT CPNHotkeyCtrl::OnKeyDown(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { bHandled = false; if (wParam == VK_DELETE || wParam == VK_SPACE || wParam == VK_ESCAPE) { bHandled = true; } return 0; } LRESULT CPNHotkeyCtrl::OnKeyUp(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { bHandled = false; // For some reason space is still clearing the box before we get to here, so there're no // modifiers left. if (wParam == VK_DELETE || wParam == VK_SPACE || wParam == VK_ESCAPE) { int current = SendMessage(HKM_GETHOTKEY, 0, 0); if ((current & 0xff) != 0) { // No low-order byte value means no current key, // we don't want to use the current modifiers. current = 0; } if (wParam == VK_DELETE) { // Set extended to make sure we get DEL and not NUM DECIMAL current |= (HOTKEYF_EXT << 8); } int key = wParam | current; SendMessage(HKM_SETHOTKEY, key, 0); SendMessageW(GetParent(), WM_COMMAND, MAKEWPARAM(GetDlgCtrlID(), EN_CHANGE), (LPARAM)m_hWnd); bHandled = true; } return 0; } LRESULT CPNHotkeyCtrl::OnChar(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled) { bHandled = false; if (wParam == ' ') { bHandled = true; } return 0; } LRESULT CPNHotkeyCtrl::OnGetDlgCode(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { return DLGC_WANTALLKEYS; }
22.463768
144
0.647742
cf614dcba15e8f5442b2aedba5196ab8203bf185
2,744
cpp
C++
cpp/tests/tdmaMsgProcessor_UT.cpp
MinesJA/meshNetwork
5ffada57c13049cb00c2996fe239cdff6edf6f17
[ "NASA-1.3" ]
133
2017-06-24T02:44:28.000Z
2022-03-25T05:17:00.000Z
cpp/tests/tdmaMsgProcessor_UT.cpp
MinesJA/meshNetwork
5ffada57c13049cb00c2996fe239cdff6edf6f17
[ "NASA-1.3" ]
null
null
null
cpp/tests/tdmaMsgProcessor_UT.cpp
MinesJA/meshNetwork
5ffada57c13049cb00c2996fe239cdff6edf6f17
[ "NASA-1.3" ]
33
2017-06-19T03:24:40.000Z
2022-02-03T20:13:12.000Z
#include "tests/tdmaMsgProcessor_UT.hpp" #include "comm/tdmaCmds.hpp" #include "comm/tdmaComm.hpp" #include "comm/cmdHeader.hpp" #include "comm/commands.hpp" #include "node/nodeParams.hpp" #include "node/nodeState.hpp" #include <gtest/gtest.h> #include <cmath> #include <unistd.h> using std::vector; namespace { } namespace comm { TDMAMsgProcessor_UT::TDMAMsgProcessor_UT() { // Load configuration node::NodeParams::loadParams("nodeConfig.json"); // Populate message processor args m_args.cmdQueue = &m_cmdQueue; m_args.relayBuffer = &m_relayBuffer; // Load command dictionary for use std::unordered_map<uint8_t, comm::HeaderType> tdmaCmdDict = TDMACmds::getCmdDict(); Cmds::updateCmdDict(tdmaCmdDict); } void TDMAMsgProcessor_UT::SetUpTestCase(void) { } void TDMAMsgProcessor_UT::SetUp(void) { } TEST_F(TDMAMsgProcessor_UT, processMsg) { // Test all commands processed by NodeMsgProcessor std::vector<uint8_t> header; std::vector<uint8_t> msgBytes; // TDMACmds::TimeOffset uint8_t sourceId = 1; double offset = 2.1; CmdHeader cmdHeader = createHeader(TDMACmds::TimeOffset, sourceId); TDMA_TimeOffset timeOffset(offset, cmdHeader); msgBytes = timeOffset.serialize(); EXPECT_TRUE(m_tdmaMsgProcessor.processMsg(TDMACmds::TimeOffset, msgBytes, m_args)); EXPECT_TRUE(node::NodeParams::nodeStatus[sourceId-1].timeOffset == offset); // TDMACmds::TimeOffsetSummary // TDMACmds::MeshStatus cmdHeader = createHeader(TDMACmds::MeshStatus, sourceId); unsigned int startTime = ceil(node::NodeParams::clock.getTime()); TDMA_MeshStatus meshStatus(startTime, TDMASTATUS_NOMINAL, cmdHeader); msgBytes = meshStatus.serialize(); EXPECT_TRUE(m_tdmaMsgProcessor.processMsg(TDMACmds::MeshStatus, msgBytes, m_args)); EXPECT_TRUE(m_cmdQueue.find(TDMACmds::MeshStatus) != m_cmdQueue.end()); // command put in queue // TDMACmds::LinkStatus cmdHeader = createHeader(TDMACmds::LinkStatus, sourceId); std::vector<uint8_t> statusIn = {node::NoLink, node::IndirectLink, node::GoodLink, node::BadLink, node::NoLink, node::NoLink}; TDMA_LinkStatus linkStatus(statusIn, cmdHeader); msgBytes = linkStatus.serialize(); EXPECT_TRUE(m_tdmaMsgProcessor.processMsg(TDMACmds::LinkStatus, msgBytes, m_args)); for (unsigned int i = 0; i < node::NodeParams::linkStatus[sourceId-1].size(); i++) { EXPECT_TRUE(node::NodeParams::linkStatus[sourceId-1][i] == statusIn[i]); } // TDMACmds::LinkStatusSummary } }
33.876543
134
0.673105
cf6521d38e5984acfd1d3a5a8a35309c09d30c38
1,545
cc
C++
Codeforces/BubbleCup/Problem H/H.cc
VastoLorde95/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
170
2017-07-25T14:47:29.000Z
2022-01-26T19:16:31.000Z
Codeforces/BubbleCup/Problem H/H.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
null
null
null
Codeforces/BubbleCup/Problem H/H.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
55
2017-07-28T06:17:33.000Z
2021-10-31T03:06:22.000Z
#include <cstdio> #include <iostream> #include <cmath> #include <algorithm> #include <cstring> #include <map> #include <set> #include <vector> #include <utility> #include <queue> #include <stack> #define sd(x) scanf("%d",&x) #define sd2(x,y) scanf("%d%d",&x,&y) #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define fi first #define se second #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define LET(x, a) __typeof(a) x(a) #define foreach(it, v) for(LET(it, v.begin()); it != v.end(); it++) #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout); #define tr(x) cout<<x<<endl; #define tr2(x,y) cout<<x<<" "<<y<<endl; #define tr3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl; #define tr4(w,x,y,z) cout<<w<<" "<<x<<" "<<y<<" "<<z<<endl; #define tr5(v,w,x,y,z) cout<<v<<" "<<w<<" "<<x<<" "<<y<<" "<<z<<endl; #define tr6(u,v,w,x,y,z) cout<<u<<" "<<v<<" "<<w<<" "<<x<<" "<<y<<" "<<z<<endl; using namespace std; long long f[2001000], MOD = 1e9 + 7, ans = 0; int n; long long inv(long long a){ long long ret = 1, b = MOD-2; while(b){ if(b%2) ret = (ret*a)%MOD; a = (a*a)%MOD; b >>= 1; } return ret; } long long nCr(int x, int y){ long long ret = f[x]; ret = (ret * inv(f[y]))%MOD; ret = (ret * inv(f[x-y]))%MOD; return ret; } int main(){ f[0] = 1; for(int i = 1; i <= 2000010; i++){ f[i] = (f[i-1]*i)%MOD; } sd(n); for(int i = 0; i <= n; i++){ ans = (ans + nCr(n+i+1,i+1))%MOD; } cout << ans << "\n"; return 0; }
21.458333
79
0.551456
cf65bf0e6b368a9f22c998f5fe83b42b89c5c720
310
hpp
C++
systemc.hpp
dcblack/Simple-SystemC-Debug
b7997c7cb3b5ba0eed2016a2ae5ff85989216982
[ "Apache-2.0" ]
1
2021-06-20T02:26:30.000Z
2021-06-20T02:26:30.000Z
systemc.hpp
dcblack/Simple-SystemC-Debug
b7997c7cb3b5ba0eed2016a2ae5ff85989216982
[ "Apache-2.0" ]
null
null
null
systemc.hpp
dcblack/Simple-SystemC-Debug
b7997c7cb3b5ba0eed2016a2ae5ff85989216982
[ "Apache-2.0" ]
1
2021-03-01T14:58:27.000Z
2021-03-01T14:58:27.000Z
#pragma once #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #include <systemc> #include <sc_time_literal.hpp> #pragma clang diagnostic pop #pragma GCC diagnostic pop //vim:syntax=systemc
28.181818
53
0.790323
cf661d16ad9e0680abcf6f9984f642f6d3e51eb3
3,293
cpp
C++
test/src/player_test.cpp
nathiss/Fusion
673245a68f75997494deec202bdffdea6ac78d48
[ "MIT" ]
null
null
null
test/src/player_test.cpp
nathiss/Fusion
673245a68f75997494deec202bdffdea6ac78d48
[ "MIT" ]
null
null
null
test/src/player_test.cpp
nathiss/Fusion
673245a68f75997494deec202bdffdea6ac78d48
[ "MIT" ]
null
null
null
/** * @file player_test.cpp * * This module is a part of Fusion Server project. * It contains the implementation of the unit tests for the Player class. * * Copyright 2019 Kamil Rusin */ #include <gtest/gtest.h> #include <fusion_server/ui/player.hpp> using namespace fusion_server; TEST(PlayerTest, SerializeIncludesAllFields) { // Arrange ui::Player player{0, 0, "", 0.0, {}, 0.0, {}}; // Act auto json = player.Serialize(); // Assert ASSERT_EQ(decltype(json)::value_t::object, json.type()); EXPECT_TRUE(json.contains("player_id")); EXPECT_TRUE(json.contains("team_id")); EXPECT_TRUE(json.contains("nick")); EXPECT_TRUE(json.contains("color")); EXPECT_TRUE(json.contains("health")); EXPECT_TRUE(json.contains("position")); EXPECT_TRUE(json.contains("angle")); } TEST(PlayerTest, SerializeAllFieldsHaveProperTypes) { // Arrange ui::Player player{0, 0, "", 0.0, {}, 0.0, {}}; // Act auto json = player.Serialize(); // Assert EXPECT_EQ(decltype(json)::value_t::number_unsigned, json["player_id"].type()); EXPECT_EQ(decltype(json)::value_t::number_unsigned, json["team_id"].type()); EXPECT_EQ(decltype(json)::value_t::string, json["nick"].type()); EXPECT_EQ(decltype(json)::value_t::number_float, json["health"].type()); EXPECT_EQ(decltype(json)::value_t::number_float, json["angle"].type()); // Color ASSERT_EQ(decltype(json)::value_t::array, json["color"].type()); ASSERT_EQ(3, json["color"].size()); EXPECT_EQ(decltype(json)::value_t::number_unsigned, json["color"][0].type()); EXPECT_EQ(decltype(json)::value_t::number_unsigned, json["color"][1].type()); EXPECT_EQ(decltype(json)::value_t::number_unsigned, json["color"][2].type()); // Position ASSERT_EQ(decltype(json)::value_t::array, json["position"].type()); ASSERT_EQ(2, json["position"].size()); EXPECT_EQ(decltype(json)::value_t::number_integer, json["position"][0].type()); EXPECT_EQ(decltype(json)::value_t::number_integer, json["position"][1].type()); } TEST(PlayerTest, SetPositionWithSeperatedCoordinates) { // Arrange ui::Player player{0, 0, "", 0.0, {}, 0.0, {}}; // Act player.SetPosition(-1337, 9001); // Assert auto json = player.Serialize(); EXPECT_TRUE(-1337 == json["position"][0]); EXPECT_TRUE(9001 == json["position"][1]); } TEST(PlayerTest, SetPositionWithPointClassArgument) { // Arrange ui::Player player{0, 0, "", 0.0, {}, 0.0, {}}; // Act player.SetPosition({-1337, 9001}); // Assert auto json = player.Serialize(); EXPECT_TRUE(-1337 == json["position"][0]); EXPECT_TRUE(9001 == json["position"][1]); } TEST(PlayerTest, SetAngle) { // Arrange ui::Player player{0, 0, "", 0.0, {}, 0.0, {}}; // Act player.SetAngle(3.14); // Assert auto json = player.Serialize(); EXPECT_EQ(3.14, json["angle"]); } TEST(PlayerTest, GetId) { // Arrange ui::Player player1{0, 0, "", 0.0, {}, 0.0, {}}; ui::Player player2{1337, 0, "", 0.0, {}, 0.0, {}}; // Act // Assert EXPECT_EQ(0, player1.GetId()); EXPECT_EQ(1337, player2.GetId()); } TEST(PlayerTest, GetIdTheSameAsSerialise) { // Arrange ui::Player player{1337, 0, "", 0.0, {}, 0.0, {}}; auto json = player.Serialize(); // Act // Assert EXPECT_EQ(1337, player.GetId()); EXPECT_EQ(1337, json["player_id"]); }
26.991803
81
0.653811
cf6cf656205dfebbe7b6c6f7babd454f63dbfde3
486
cpp
C++
problemsets/Codeforces/C++/A910.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/Codeforces/C++/A910.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/Codeforces/C++/A910.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(0); int n, d; cin >> n >> d; int p = 0, l = p+d, next = -1; string a; cin >> a; int ret = 0; for (int i = 1; i < n; i++) { if (a[i]=='1') next = i; if (i == l || i == n-1) { if (next == -1) { cout << "-1"; return 0; } ret++; l = next+d; p = next; next = -1; } } cout << ret; }
19.44
49
0.469136
cf74b621634e4acb8c7e54c991f4ec11a5b7900c
14,792
cpp
C++
main.cpp
Sundragon1993/AI-Game-Pratices
7549b23f71c3b2b5145388f0d8d4900bdb307a7a
[ "MIT" ]
null
null
null
main.cpp
Sundragon1993/AI-Game-Pratices
7549b23f71c3b2b5145388f0d8d4900bdb307a7a
[ "MIT" ]
null
null
null
main.cpp
Sundragon1993/AI-Game-Pratices
7549b23f71c3b2b5145388f0d8d4900bdb307a7a
[ "MIT" ]
null
null
null
#pragma warning (disable:4786) #include <windows.h> #include <time.h> #include "constants.h" #include "misc/utils.h" #include "Time/PrecisionTimer.h" #include "Resource.h" #include "misc/windowutils.h" #include "misc/Cgdi.h" #include "debug/DebugConsole.h" #include "Raven_UserOptions.h" #include "Raven_Game.h" #include "lua/Raven_Scriptor.h" //need to include this for the toolbar stuff #include <commctrl.h> #pragma comment(lib, "comctl32.lib") //--------------------------------- Globals ------------------------------ //------------------------------------------------------------------------ char* g_szApplicationName = "Raven"; char* g_szWindowClassName = "MyWindowClass"; Raven_Game* g_pRaven; //---------------------------- WindowProc --------------------------------- // // This is the callback function which handles all the windows messages //------------------------------------------------------------------------- LRESULT CALLBACK WindowProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { //these hold the dimensions of the client window area static int cxClient, cyClient; //used to create the back buffer static HDC hdcBackBuffer; static HBITMAP hBitmap; static HBITMAP hOldBitmap; //to grab filenames static TCHAR szFileName[MAX_PATH], szTitleName[MAX_PATH]; switch (msg) { //A WM_CREATE msg is sent when your application window is first //created case WM_CREATE: { //to get get the size of the client window first we need to create //a RECT and then ask Windows to fill in our RECT structure with //the client window size. Then we assign to cxClient and cyClient //accordingly RECT rect; GetClientRect(hwnd, &rect); cxClient = rect.right; cyClient = rect.bottom; //seed random number generator srand((unsigned) time(NULL)); //---------------create a surface to render to(backbuffer) //create a memory device context hdcBackBuffer = CreateCompatibleDC(NULL); //get the DC for the front buffer HDC hdc = GetDC(hwnd); hBitmap = CreateCompatibleBitmap(hdc, cxClient, cyClient); //select the bitmap into the memory device context hOldBitmap = (HBITMAP)SelectObject(hdcBackBuffer, hBitmap); //don't forget to release the DC ReleaseDC(hwnd, hdc); //create the game g_pRaven = new Raven_Game(); //make sure the menu items are ticked/unticked accordingly CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SHOW_NAVGRAPH, UserOptions->m_bShowGraph); CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SHOW_PATH, UserOptions->m_bShowPathOfSelectedBot); CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_IDS, UserOptions->m_bShowBotIDs); CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SMOOTH_PATHS_QUICK, UserOptions->m_bSmoothPathsQuick); CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SMOOTH_PATHS_PRECISE, UserOptions->m_bSmoothPathsPrecise); CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_HEALTH, UserOptions->m_bShowBotHealth); CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_TARGET, UserOptions->m_bShowTargetOfSelectedBot); CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_FOV, UserOptions->m_bOnlyShowBotsInTargetsFOV); CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_SCORES, UserOptions->m_bShowScore); CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_GOAL_Q, UserOptions->m_bShowGoalsOfSelectedBot); CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SHOW_INDICES, UserOptions->m_bShowNodeIndices); CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_SENSED, UserOptions->m_bShowOpponentsSensedBySelectedBot); } break; case WM_KEYUP: { switch(wParam) { case VK_ESCAPE: { SendMessage(hwnd, WM_DESTROY, NULL, NULL); } break; case 'P': g_pRaven->TogglePause(); break; case '1': g_pRaven->ChangeWeaponOfPossessedBot(type_blaster); break; case '2': g_pRaven->ChangeWeaponOfPossessedBot(type_shotgun); break; case '3': g_pRaven->ChangeWeaponOfPossessedBot(type_rocket_launcher); break; case '4': g_pRaven->ChangeWeaponOfPossessedBot(type_rail_gun); break; case 'X': g_pRaven->ExorciseAnyPossessedBot(); break; case VK_UP: g_pRaven->AddBots(1); break; case VK_DOWN: g_pRaven->RemoveBot(); break; } } break; case WM_LBUTTONDOWN: { g_pRaven->ClickLeftMouseButton(MAKEPOINTS(lParam)); } break; case WM_RBUTTONDOWN: { g_pRaven->ClickRightMouseButton(MAKEPOINTS(lParam)); } break; case WM_COMMAND: { switch(wParam) { case IDM_GAME_LOAD: FileOpenDlg(hwnd, szFileName, szTitleName, "Raven map file (*.map)", "map"); debug_con << "Filename: " << szTitleName << ""; if (strlen(szTitleName) > 0) { g_pRaven->LoadMap(szTitleName); } break; case IDM_GAME_ADDBOT: g_pRaven->AddBots(1); break; case IDM_GAME_REMOVEBOT: g_pRaven->RemoveBot(); break; case IDM_GAME_PAUSE: g_pRaven->TogglePause(); break; case IDM_NAVIGATION_SHOW_NAVGRAPH: UserOptions->m_bShowGraph = !UserOptions->m_bShowGraph; CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SHOW_NAVGRAPH, UserOptions->m_bShowGraph); break; case IDM_NAVIGATION_SHOW_PATH: UserOptions->m_bShowPathOfSelectedBot = !UserOptions->m_bShowPathOfSelectedBot; CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SHOW_PATH, UserOptions->m_bShowPathOfSelectedBot); break; case IDM_NAVIGATION_SHOW_INDICES: UserOptions->m_bShowNodeIndices = !UserOptions->m_bShowNodeIndices; CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SHOW_INDICES, UserOptions->m_bShowNodeIndices); break; case IDM_NAVIGATION_SMOOTH_PATHS_QUICK: UserOptions->m_bSmoothPathsQuick = !UserOptions->m_bSmoothPathsQuick; UserOptions->m_bSmoothPathsPrecise = false; CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SMOOTH_PATHS_PRECISE, UserOptions->m_bSmoothPathsPrecise); CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SMOOTH_PATHS_QUICK, UserOptions->m_bSmoothPathsQuick); break; case IDM_NAVIGATION_SMOOTH_PATHS_PRECISE: UserOptions->m_bSmoothPathsPrecise = !UserOptions->m_bSmoothPathsPrecise; UserOptions->m_bSmoothPathsQuick = false; CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SMOOTH_PATHS_QUICK, UserOptions->m_bSmoothPathsQuick); CheckMenuItemAppropriately(hwnd, IDM_NAVIGATION_SMOOTH_PATHS_PRECISE, UserOptions->m_bSmoothPathsPrecise); break; case IDM_BOTS_SHOW_IDS: UserOptions->m_bShowBotIDs = !UserOptions->m_bShowBotIDs; CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_IDS, UserOptions->m_bShowBotIDs); break; case IDM_BOTS_SHOW_HEALTH: UserOptions->m_bShowBotHealth = !UserOptions->m_bShowBotHealth; CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_HEALTH, UserOptions->m_bShowBotHealth); break; case IDM_BOTS_SHOW_TARGET: UserOptions->m_bShowTargetOfSelectedBot = !UserOptions->m_bShowTargetOfSelectedBot; CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_TARGET, UserOptions->m_bShowTargetOfSelectedBot); break; case IDM_BOTS_SHOW_SENSED: UserOptions->m_bShowOpponentsSensedBySelectedBot = !UserOptions->m_bShowOpponentsSensedBySelectedBot; CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_SENSED, UserOptions->m_bShowOpponentsSensedBySelectedBot); break; case IDM_BOTS_SHOW_FOV: UserOptions->m_bOnlyShowBotsInTargetsFOV = !UserOptions->m_bOnlyShowBotsInTargetsFOV; CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_FOV, UserOptions->m_bOnlyShowBotsInTargetsFOV); break; case IDM_BOTS_SHOW_SCORES: UserOptions->m_bShowScore = !UserOptions->m_bShowScore; CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_SCORES, UserOptions->m_bShowScore); break; case IDM_BOTS_SHOW_GOAL_Q: UserOptions->m_bShowGoalsOfSelectedBot = !UserOptions->m_bShowGoalsOfSelectedBot; CheckMenuItemAppropriately(hwnd, IDM_BOTS_SHOW_GOAL_Q, UserOptions->m_bShowGoalsOfSelectedBot); break; }//end switch } case WM_PAINT: { PAINTSTRUCT ps; BeginPaint (hwnd, &ps); //fill our backbuffer with white BitBlt(hdcBackBuffer, 0, 0, cxClient, cyClient, NULL, NULL, NULL, WHITENESS); gdi->StartDrawing(hdcBackBuffer); g_pRaven->Render(); gdi->StopDrawing(hdcBackBuffer); //now blit backbuffer to front BitBlt(ps.hdc, 0, 0, cxClient, cyClient, hdcBackBuffer, 0, 0, SRCCOPY); EndPaint (hwnd, &ps); } break; //has the user resized the client area? case WM_SIZE: { //if so we need to update our variables so that any drawing //we do using cxClient and cyClient is scaled accordingly cxClient = LOWORD(lParam); cyClient = HIWORD(lParam); //now to resize the backbuffer accordingly. First select //the old bitmap back into the DC SelectObject(hdcBackBuffer, hOldBitmap); //don't forget to do this or you will get resource leaks DeleteObject(hBitmap); //get the DC for the application HDC hdc = GetDC(hwnd); //create another bitmap of the same size and mode //as the application hBitmap = CreateCompatibleBitmap(hdc, cxClient, cyClient); ReleaseDC(hwnd, hdc); //select the new bitmap into the DC SelectObject(hdcBackBuffer, hBitmap); } break; case WM_DESTROY: { //clean up our backbuffer objects SelectObject(hdcBackBuffer, hOldBitmap); DeleteDC(hdcBackBuffer); DeleteObject(hBitmap); // kill the application, this sends a WM_QUIT message PostQuitMessage (0); } break; }//end switch //this is where all the messages not specifically handled by our //winproc are sent to be processed return DefWindowProc (hwnd, msg, wParam, lParam); } //-------------------------------- WinMain ------------------------------- // // The entry point of the windows program //------------------------------------------------------------------------ int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow) { MSG msg; //handle to our window HWND hWnd; //the window class structure WNDCLASSEX winclass; // first fill in the window class stucture winclass.cbSize = sizeof(WNDCLASSEX); winclass.style = CS_HREDRAW | CS_VREDRAW; winclass.lpfnWndProc = WindowProc; winclass.cbClsExtra = 0; winclass.cbWndExtra = 0; winclass.hInstance = hInstance; winclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); winclass.hCursor = LoadCursor(NULL, IDC_ARROW); winclass.hbrBackground = NULL; winclass.lpszMenuName = MAKEINTRESOURCE(IDR_MENU1); winclass.lpszClassName = g_szWindowClassName; winclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION); //register the window class if (!RegisterClassEx(&winclass)) { MessageBox(NULL, "Registration Failed!", "Error", 0); //exit the application return 0; } try { //create the window and assign its ID to hwnd hWnd = CreateWindowEx (NULL, // extended style g_szWindowClassName, // window class name g_szApplicationName, // window caption WS_OVERLAPPED | WS_VISIBLE | WS_CAPTION | WS_SYSMENU, // window style GetSystemMetrics(SM_CXSCREEN)/2 - WindowWidth/2, GetSystemMetrics(SM_CYSCREEN)/2 - WindowHeight/2, WindowWidth, // initial x size WindowHeight, // initial y size NULL, // parent window handle NULL, // window menu handle hInstance, // program instance handle NULL); // creation parameters //make sure the window creation has gone OK if(!hWnd) { MessageBox(NULL, "CreateWindowEx Failed!", "Error!", 0); } //make the window visible ShowWindow (hWnd, iCmdShow); UpdateWindow (hWnd); //create a timer PrecisionTimer timer(FrameRate); //start the timer timer.Start(); //enter the message loop bool bDone = false; while(!bDone) { while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { if( msg.message == WM_QUIT ) { // Stop loop if it's a quit message bDone = true; } else { TranslateMessage( &msg ); DispatchMessage( &msg ); } } if (timer.ReadyForNextFrame() && msg.message != WM_QUIT) { g_pRaven->Update(); //render RedrawWindow(hWnd); } //give the OS a little time Sleep(2); }//end while }//end try block catch (const std::runtime_error& err) { ErrorBox(std::string(err.what())); //tidy up delete g_pRaven; UnregisterClass( g_szWindowClassName, winclass.hInstance ); return 0; } //tidy up UnregisterClass( g_szWindowClassName, winclass.hInstance ); delete g_pRaven; return msg.wParam; }
26.700361
114
0.60046
cf77bbe20e26934dc3acc307f4b1caa8f6b7cdfd
391
cpp
C++
cpp/cpp_primer/chapter19/ex_19_03.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
2
2019-12-21T00:53:47.000Z
2020-01-01T10:36:30.000Z
cpp/cpp_primer/chapter19/ex_19_03.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
null
null
null
cpp/cpp_primer/chapter19/ex_19_03.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
null
null
null
// // Created by kaiser on 19-3-16. // #include <iostream> class A { public: virtual ~A() = default; }; class B : public A {}; class C : public B {}; int main() { { A* pa = new C; if (B* pb = dynamic_cast<B*>(pa); !pb) { std::cerr << "error 1\n"; } } { B* pb = new B; if (C* pc = dynamic_cast<C*>(pb); !pc) { std::cerr << "error 2\n"; } } }
13.964286
44
0.468031
cf78dd0d497dca8c6985d07ecff1df821163605a
5,508
cpp
C++
src/hdp_py.cpp
jstraub/bnp
11cd28b49e9cf1db96f349181aff57a17672b6a4
[ "MIT" ]
12
2015-01-13T01:18:39.000Z
2021-06-16T20:16:54.000Z
src/hdp_py.cpp
jstraub/bnp
11cd28b49e9cf1db96f349181aff57a17672b6a4
[ "MIT" ]
1
2015-07-12T12:58:14.000Z
2015-07-12T12:58:14.000Z
src/hdp_py.cpp
jstraub/bnp
11cd28b49e9cf1db96f349181aff57a17672b6a4
[ "MIT" ]
2
2017-07-22T05:37:10.000Z
2018-08-26T07:11:34.000Z
/* Copyright (c) 2012, Julian Straub <jstraub@csail.mit.edu> * Licensed under the MIT license. See LICENSE.txt or * http://www.opensource.org/licenses/mit-license.php */ #include <baseMeasure_py.hpp> #include <hdp_gibbs_py.hpp> #include <hdp_var_py.hpp> #include <hdp_var_base_py.hpp> // using the hdp which utilizes sufficient statistics //#include <hdp_var_ss.hpp> #include <assert.h> #include <stddef.h> #include <stdint.h> #include <typeinfo> #include <armadillo> #include <boost/python.hpp> #include <boost/python/wrapper.hpp> #include <numpy/ndarrayobject.h> // for PyArrayObject #ifdef PYTHON_2_6 #include <python2.6/object.h> // for PyArray_FROM_O #endif #ifdef PYTHON_2_7 #include <python2.7/object.h> // for PyArray_FROM_O #endif using namespace boost::python; BOOST_PYTHON_MODULE(libbnp) { import_array(); boost::python::numeric::array::set_module_and_type("numpy", "ndarray"); class_<Dir_py>("Dir", init<numeric::array>()) .def(init<Dir_py>()) .def("asRow",&Dir_py::asRow) .def("rowDim",&Dir_py::rowDim); class_<NIW_py>("NIW",init<const numeric::array, double, const numeric::array, double>()) .def(init<NIW_py>()) .def("asRow",&NIW_py::asRow) .def("rowDim",&NIW_py::rowDim); // class_<DP_Dir>("DP_Dir",init<Dir_py,double>()); // class_<DP_INW>("DP_INW",init<NIW_py,double>()); class_<HDP_gibbs_Dir>("HDP_gibbs_Dir",init<Dir_py&,double,double>()) .def("densityEst",&HDP_gibbs_Dir::densityEst) .def("getClassLabels",&HDP_gibbs_Dir::getClassLabels) .def("addDoc",&HDP_gibbs_Dir::addDoc) .def("addHeldOut",&HDP_gibbs_Dir::addHeldOut) .def("getPerplexity",&HDP_gibbs_Dir::getPerplexity); // .def_readonly("mGamma", &HDP_Dir::mGamma); class_<HDP_gibbs_NIW>("HDP_gibbs_NIW",init<NIW_py&,double,double>()) .def("densityEst",&HDP_gibbs_NIW::densityEst) .def("getClassLabels",&HDP_gibbs_NIW::getClassLabels) .def("addDoc",&HDP_gibbs_NIW::addDoc); // .def_readonly("mGamma", &HDP_NIW::mGamma); class_<HDP_var_Dir_py>("HDP_var_Dir",init<Dir_py&,double,double>()) .def("densityEst",&HDP_var_Dir_py::densityEst) //TODO: not sure that one works: .def("updateEst",&HDP_var_Dir_py::updateEst) .def("updateEst_batch",&HDP_var_Dir_py::updateEst_batch) .def("addDoc",&HDP_var_Dir_py::addDoc) .def("addHeldOut",&HDP_var_Dir_py::addHeldOut) .def("getPerplexity",&HDP_var_Dir_py::getPerplexity_py) .def("getA",&HDP_var_Dir_py::getA_py) .def("getTopicPriorDescriptionLength",&HDP_var_Dir_py::getTopicPriorDescriptionLength) .def("getLambda",&HDP_var_Dir_py::getLambda_py) .def("getDocTopics",&HDP_var_Dir_py::getDocTopics_py) .def("getWordTopics",&HDP_var_Dir_py::getWordTopics_py) .def("getCorpTopicProportions",&HDP_var_Dir_py::getCorpTopicProportions_py) .def("getTopicsDescriptionLength",&HDP_var_Dir_py::getTopicsDescriptionLength) .def("getCorpTopics",&HDP_var_Dir_py::getCorpTopics_py) .def("getWordDistr",&HDP_var_Dir_py::getWordDistr_py); // .def_readonly("mGamma", &HDP_var_Dir_py::mGamma); // .def("perplexity",&HDP_var_Dir_py::perplexity) class_<HDP_var_NIW_py>("HDP_var_NIW",init<NIW_py&,double,double>()) .def("densityEst",&HDP_var_NIW_py::densityEst) //TODO: not sure that one works: .def("updateEst",&HDP_var_NIW_py::updateEst) .def("updateEst_batch",&HDP_var_NIW_py::updateEst_batch) .def("addDoc",&HDP_var_NIW_py::addDoc) .def("addHeldOut",&HDP_var_NIW_py::addHeldOut) .def("getPerplexity",&HDP_var_NIW_py::getPerplexity_py) .def("getA",&HDP_var_NIW_py::getA_py) .def("getTopicPriorDescriptionLength",&HDP_var_NIW_py::getTopicPriorDescriptionLength) .def("getLambda",&HDP_var_NIW_py::getLambda_py) .def("getDocTopics",&HDP_var_NIW_py::getDocTopics_py) .def("getWordTopics",&HDP_var_NIW_py::getWordTopics_py) .def("getCorpTopicProportions",&HDP_var_NIW_py::getCorpTopicProportions_py) .def("getTopicsDescriptionLength",&HDP_var_NIW_py::getTopicsDescriptionLength) .def("getCorpTopics",&HDP_var_NIW_py::getCorpTopics_py) .def("getWordDistr",&HDP_var_NIW_py::getWordDistr_py); // .def_readonly("mGamma", &HDP_var_NIW_py::mGamma); // .def("perplexity",&HDP_var_NIW_py::perplexity) // class_<HDP_var_ss_py>("HDP_var_ss",init<Dir_py&,double,double>()) // .def("densityEst",&HDP_var_ss_py::densityEst) // //TODO: not sure that one works .def("updateEst",&HDP_var_ss_py::updateEst) // .def("getPerplexity",&HDP_var_ss_py::getPerplexity_py) // .def("getA",&HDP_var_ss_py::getA_py) // .def("getLambda",&HDP_var_ss_py::getLambda_py) // .def("getDocTopics",&HDP_var_ss_py::getDocTopics_py) // .def("getWordTopics",&HDP_var_ss_py::getWordTopics_py) // .def("getCorpTopicProportions",&HDP_var_ss_py::getCorpTopicProportions_py) // .def("getCorpTopics",&HDP_var_ss_py::getCorpTopics_py) // .def("getWordDistr",&HDP_var_ss_py::getWordDistr_py); // .def("perplexity",&HDP_var_ss_py::perplexity) class_<TestNp2Arma_py>("TestNp2Arma",init<>()) .def("getAmat",&TestNp2Arma_py::getAmat) .def("getArect",&TestNp2Arma_py::getArect) .def("putArect",&TestNp2Arma_py::putArect) .def("getAcol",&TestNp2Arma_py::getAcol) .def("resizeAmat",&TestNp2Arma_py::resizeAmat) .def("getArow",&TestNp2Arma_py::getArow); }
43.714286
94
0.69971
cf79eafceff5d8d46fae59e5aa56764304bdc8ef
1,307
hpp
C++
code/adobe.poly/adobe/implementation/string_pool.hpp
andyprowl/virtual-concepts
ed3a5690c353b6998abcd3368a9b448f1bb2aa19
[ "Unlicense" ]
59
2015-04-01T12:55:36.000Z
2021-06-22T02:46:20.000Z
adobe/implementation/string_pool.hpp
brycelelbach/asl
df0d271f6c67fbb944039a9455c4eb69ae6df141
[ "MIT" ]
1
2015-06-29T14:51:55.000Z
2015-06-29T16:40:26.000Z
adobe/implementation/string_pool.hpp
brycelelbach/asl
df0d271f6c67fbb944039a9455c4eb69ae6df141
[ "MIT" ]
5
2016-04-19T09:21:11.000Z
2021-12-29T09:48:09.000Z
/* Copyright 2005-2007 Adobe Systems Incorporated Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt or a copy at http://stlab.adobe.com/licenses.html) */ /*************************************************************************************************/ #ifndef ADOBE_STRING_POOL_HPP #define ADOBE_STRING_POOL_HPP /*************************************************************************************************/ #include <adobe/config.hpp> #include <boost/noncopyable.hpp> /*************************************************************************************************/ namespace adobe { /**************************************************************************************************/ class unique_string_pool_t : boost::noncopyable { public: unique_string_pool_t(); ~unique_string_pool_t(); const char* add(const char* str); private: struct implementation_t; implementation_t* object_m; }; /**************************************************************************************************/ } // namespace adobe /**************************************************************************************************/ #endif /**************************************************************************************************/
26.673469
100
0.337414
cf7af2af2ce72a6cd137dfa8c94cc6880fa00c92
4,290
hpp
C++
include/ipfixprobe/process.hpp
CESNET/NEMEA-probe
c2c3cc3ba96e51bc241908b9b228ec3f2d73ef97
[ "BSD-3-Clause" ]
null
null
null
include/ipfixprobe/process.hpp
CESNET/NEMEA-probe
c2c3cc3ba96e51bc241908b9b228ec3f2d73ef97
[ "BSD-3-Clause" ]
null
null
null
include/ipfixprobe/process.hpp
CESNET/NEMEA-probe
c2c3cc3ba96e51bc241908b9b228ec3f2d73ef97
[ "BSD-3-Clause" ]
null
null
null
/** * \file process.hpp * \brief Generic interface of processing plugin * \author Vaclav Bartos <bartos@cesnet.cz> * \author Jiri Havranek <havranek@cesnet.cz> * \date 2021 */ /* * Copyright (C) 2021 CESNET * * LICENSE TERMS * * 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 Company nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * ALTERNATIVELY, provided that this notice is retained in full, this * product may be distributed under the terms of the GNU General Public * License (GPL) version 2 or later, in which case the provisions * of the GPL apply INSTEAD OF those given above. * * This software is provided ``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 company 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 IPXP_PROCESS_HPP #define IPXP_PROCESS_HPP #include <string> #include <vector> #include "plugin.hpp" #include "packet.hpp" #include "flowifc.hpp" namespace ipxp { /** * \brief Tell storage plugin to flush (immediately export) current flow. * Behavior when called from post_create, pre_update and post_update: flush current Flow and erase FlowRecord. */ #define FLOW_FLUSH 0x1 /** * \brief Tell storage plugin to flush (immediately export) current flow. * Behavior when called from post_create: flush current Flow and erase FlowRecord. * Behavior when called from pre_update and post_update: flush current Flow, erase FlowRecord and call post_create on packet. */ #define FLOW_FLUSH_WITH_REINSERT 0x3 /** * \brief Class template for flow cache plugins. */ class ProcessPlugin : public Plugin { public: ProcessPlugin() {} virtual ~ProcessPlugin() {} virtual ProcessPlugin *copy() = 0; virtual RecordExt *get_ext() const { return nullptr; } /** * \brief Called before a new flow record is created. * \param [in] pkt Parsed packet. * \return 0 on success or FLOW_FLUSH option. */ virtual int pre_create(Packet &pkt) { return 0; } /** * \brief Called after a new flow record is created. * \param [in,out] rec Reference to flow record. * \param [in] pkt Parsed packet. * \return 0 on success or FLOW_FLUSH option. */ virtual int post_create(Flow &rec, const Packet &pkt) { return 0; } /** * \brief Called before an existing record is update. * \param [in,out] rec Reference to flow record. * \param [in,out] pkt Parsed packet. * \return 0 on success or FLOW_FLUSH option. */ virtual int pre_update(Flow &rec, Packet &pkt) { return 0; } /** * \brief Called after an existing record is updated. * \param [in,out] rec Reference to flow record. * \param [in,out] pkt Parsed packet. * \return 0 on success or FLOW_FLUSH option. */ virtual int post_update(Flow &rec, const Packet &pkt) { return 0; } /** * \brief Called before a flow record is exported from the cache. * \param [in,out] rec Reference to flow record. */ virtual void pre_export(Flow &rec) { } }; } #endif /* IPXP_PROCESS_HPP */
30.863309
125
0.701399
cf7afec8d91451c3ae14adbeefc7ed64963657d9
743
hh
C++
src/collider-manager-2d.hh
obs145628/opl
aeb8e70f3dbca8b8564cd829c2327df25e00392e
[ "MIT" ]
null
null
null
src/collider-manager-2d.hh
obs145628/opl
aeb8e70f3dbca8b8564cd829c2327df25e00392e
[ "MIT" ]
null
null
null
src/collider-manager-2d.hh
obs145628/opl
aeb8e70f3dbca8b8564cd829c2327df25e00392e
[ "MIT" ]
null
null
null
/** @file ColliderManager2D ckass definition */ #ifndef COLLIDER_MANAGER_2D_HH_ # define COLLIDER_MANAGER_2D_HH_ # include <cstddef> # include <map> # include "object-2d.hh" # include "collider-2d.hh" namespace opl { class ColliderManager2D { public: static ColliderManager2D* instance (); bool are_colliding (Object2D* a, Object2D* b); bool are_colliding (Collider2D* a, Collider2D* b); private: using coll_fn_type = bool (*) (Collider2D*, Collider2D*); static ColliderManager2D* instance_; std::map<size_t, coll_fn_type> fns_; ColliderManager2D (); ColliderManager2D(const ColliderManager2D&) = delete; static size_t fn_id_get_ (size_t id1, size_t id2); }; } #endif //!COLLIDER_MANAGER_HH_
14.86
59
0.718708
cf8d4a21fc6e4946e1b77ff96f8b80daa1ee0b32
164
hpp
C++
src/semantic.hpp
amzamora/diamond
c9cad46401815461ebae8db781bbb669c11bd257
[ "MIT" ]
4
2021-02-02T19:55:23.000Z
2021-03-26T22:54:12.000Z
src/semantic.hpp
amzamora/diamond
c9cad46401815461ebae8db781bbb669c11bd257
[ "MIT" ]
28
2021-01-31T01:04:54.000Z
2021-12-11T13:53:49.000Z
src/semantic.hpp
amzamora/diamond
c9cad46401815461ebae8db781bbb669c11bd257
[ "MIT" ]
null
null
null
#ifndef SEMANTIC_HPP #define SEMANTIC_HPP #include "types.hpp" namespace semantic { Result<Ok, Errors> analyze(std::shared_ptr<Ast::Program> program); } #endif
14.909091
67
0.756098
cf8e46de8aa704945cb4baf7c5036b98a61190e3
5,277
cxx
C++
main/sw/source/ui/config/caption.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sw/source/ui/config/caption.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sw/source/ui/config/caption.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include <tools/debug.hxx> #include "numrule.hxx" #include "caption.hxx" #define VERSION_01 1 #define CAPTION_VERSION VERSION_01 /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ InsCaptionOpt::InsCaptionOpt(const SwCapObjType eType, const SvGlobalName* pOleId) : bUseCaption(sal_False), eObjType(eType), nNumType(SVX_NUM_ARABIC), sNumberSeparator( ::rtl::OUString::createFromAscii(". ") ), nPos(1), nLevel(0), sSeparator( String::CreateFromAscii( ": " ) ), bIgnoreSeqOpts(sal_False), bCopyAttributes(sal_False) { if (pOleId) aOleId = *pOleId; } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ InsCaptionOpt::InsCaptionOpt(const InsCaptionOpt& rOpt) { *this = rOpt; } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ InsCaptionOpt::~InsCaptionOpt() { } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ InsCaptionOpt& InsCaptionOpt::operator=( const InsCaptionOpt& rOpt ) { bUseCaption = rOpt.bUseCaption; eObjType = rOpt.eObjType; aOleId = rOpt.aOleId; sCategory = rOpt.sCategory; nNumType = rOpt.nNumType; sNumberSeparator = rOpt.sNumberSeparator; sCaption = rOpt.sCaption; nPos = rOpt.nPos; nLevel = rOpt.nLevel; sSeparator = rOpt.sSeparator; bIgnoreSeqOpts = rOpt.bIgnoreSeqOpts; sCharacterStyle = rOpt.sCharacterStyle; bCopyAttributes = rOpt.bCopyAttributes; return *this; } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ sal_Bool InsCaptionOpt::operator==( const InsCaptionOpt& rOpt ) const { return (eObjType == rOpt.eObjType && aOleId == rOpt.aOleId); // Damit gleiche Ole-IDs nicht mehrfach eingefuegt // werden koennen, auf nichts weiteres vergleichen /* && sCategory == rOpt.sCategory && nNumType == rOpt.nNumType && sCaption == rOpt.sCaption && nPos == rOpt.nPos && nLevel == rOpt.nLevel && cSeparator == rOpt.cSeparator);*/ } /************************************************************************* |* |* InsCaptionOpt::operator>>() |* |* Beschreibung Stream-Leseoperator |* *************************************************************************/ /*SvStream& operator>>( SvStream& rIStream, InsCaptionOpt& rCapOpt ) { rtl_TextEncoding eEncoding = gsl_getSystemTextEncoding(); sal_uInt16 nVal; sal_uInt8 cVal; sal_uInt8 nVersion; rIStream >> nVersion; rIStream >> cVal; rCapOpt.UseCaption() = cVal != 0; rIStream >> nVal; rCapOpt.eObjType = (SwCapObjType)nVal; rIStream >> rCapOpt.aOleId; rIStream.ReadByteString( rCapOpt.sCategory, eEncoding ); rIStream >> nVal; rCapOpt.nNumType = nVal; rIStream.ReadByteString( rCapOpt.sCaption, eEncoding ); rIStream >> nVal; rCapOpt.nPos = nVal; rIStream >> nVal; rCapOpt.nLevel = nVal; rIStream >> cVal; rCapOpt.sSeparator = UniString( ByteString(static_cast< char >(cVal)) , eEncoding).GetChar(0); return rIStream; } */ /************************************************************************* |* |* InsCaptionOpt::operator<<() |* |* Beschreibung Stream-Schreiboperator |* *************************************************************************/ /*SvStream& operator<<( SvStream& rOStream, const InsCaptionOpt& rCapOpt ) { rtl_TextEncoding eEncoding = gsl_getSystemTextEncoding(); rOStream << (sal_uInt8)CAPTION_VERSION << (sal_uInt8)rCapOpt.UseCaption() << (sal_uInt16)rCapOpt.eObjType << rCapOpt.aOleId; rOStream.WriteByteString( rCapOpt.sCategory, eEncoding ); rOStream << (sal_uInt16)rCapOpt.nNumType; rOStream.WriteByteString( rCapOpt.sCaption, eEncoding ); sal_uInt8 cSep = ByteString(rCapOpt.sSeparator, eEncoding).GetChar(0); rOStream << (sal_uInt16)rCapOpt.nPos << (sal_uInt16)rCapOpt.nLevel << cSep; return rOStream; } */
29.480447
84
0.565094
cf90ef7c36bf959177421f9dd048e4f5d2ee1611
1,637
cpp
C++
src/GUI/Selection.cpp
szebest/Basic-SFML-Application-Framework
e6b979283a1aba87ea5eefb1785d6f9bf4485d4a
[ "MIT" ]
null
null
null
src/GUI/Selection.cpp
szebest/Basic-SFML-Application-Framework
e6b979283a1aba87ea5eefb1785d6f9bf4485d4a
[ "MIT" ]
null
null
null
src/GUI/Selection.cpp
szebest/Basic-SFML-Application-Framework
e6b979283a1aba87ea5eefb1785d6f9bf4485d4a
[ "MIT" ]
null
null
null
#include "Selection.h" Selection::Selection(sf::Vector2f pos) : m_selected(false) { m_outerShape.setRadius(12); m_innerShape.setRadius(10); m_innerShape.setFillColor(sf::Color::Blue); setPosition(pos); } void Selection::handleEvents(sf::Event e, const sf::RenderWindow& window, sf::Vector2f displacement) { switch (e.type) { case sf::Event::MouseButtonPressed: { if (e.mouseButton.button == sf::Mouse::Left) if (isHovering(window, displacement)) m_selected = !m_selected; } break; default: break; } } void Selection::update(const sf::Time& deltaTime) { } void Selection::draw(sf::RenderTarget& target) { target.draw(m_outerShape); if (m_selected) target.draw(m_innerShape); } void Selection::setPosition(sf::Vector2f pos) { float outerRadius = m_outerShape.getRadius(); float innerRadius = m_innerShape.getRadius(); m_outerShape.setPosition(pos - sf::Vector2f(outerRadius, outerRadius)); m_innerShape.setPosition(pos - sf::Vector2f(innerRadius, innerRadius)); } sf::Vector2f Selection::getPosition() { float radius = m_outerShape.getRadius(); return m_outerShape.getPosition() + sf::Vector2f(radius, radius) / 2.f; } bool Selection::isHovering(const sf::RenderWindow& window, sf::Vector2f displacement) { auto pixelPos = sf::Mouse::getPosition(window); auto worldPos = window.mapPixelToCoords(pixelPos) + displacement; return m_outerShape.getGlobalBounds().contains(worldPos.x, worldPos.y); } void Selection::setSelected(bool _selected) { m_selected = _selected; } bool Selection::getSelected() { return m_selected; } const bool* Selection::getPointerToSelected() { return &m_selected; }
22.736111
100
0.744655
cf984f3074382b3d9970476ba611f764046adf3a
8,296
cpp
C++
Source/Motor2D/j1Player.cpp
Needlesslord/PaintWars_by_BrainDeadStudios
578985b1a41ab9f0b8c5dd087ba3bc3d3ffd2edf
[ "MIT" ]
2
2020-03-06T11:32:40.000Z
2020-03-20T12:17:30.000Z
Source/Motor2D/j1Player.cpp
Needlesslord/Heathen_Games
578985b1a41ab9f0b8c5dd087ba3bc3d3ffd2edf
[ "MIT" ]
2
2020-03-03T09:56:57.000Z
2020-05-02T15:50:45.000Z
Source/Motor2D/j1Player.cpp
Needlesslord/Heathen_Games
578985b1a41ab9f0b8c5dd087ba3bc3d3ffd2edf
[ "MIT" ]
1
2020-03-17T18:50:53.000Z
2020-03-17T18:50:53.000Z
#include "p2Defs.h" #include "j1App.h" #include "p2Log.h" #include "j1Textures.h" #include "j1Input.h" #include "j1Audio.h" #include "j1Render.h" #include "j1Window.h" #include "j1Player.h" #include "j1SceneManager.h" #include "j1EntityManager.h" #include "j1Window.h" #include "j1UI_manager.h" #include "Scene.h" #include "j1Timer.h" j1Player::j1Player() : j1Module() { name = ("player"); } j1Player::~j1Player() { App->CleanUp(); } bool j1Player::Awake(pugi::xml_node& config) { bool ret = true; folder = (config.child("folder").child_value()); camera_speed = config.child("camera").attribute("speed").as_int(1); camera_offset = config.child("camera").attribute("offset").as_int(10); node = config; return ret; } bool j1Player::Start() { bool ret = true; MinimapCameraBufferX = 0; MinimapCameraBufferY = 0; LOG("Player Started"); Tex_Player = App->tex->Load("textures/UI/UI_mouse.png"); App->win->GetWindowSize( win_width,win_height); SDL_ShowCursor(SDL_DISABLE); V = 0; return ret; } bool j1Player::PreUpdate() { //list<Entity*>::iterator entityCount = App->entities->activeEntities.begin(); //int B = 0; //int P = 0; //if (V != 1) { // while (entityCount != App->entities->activeEntities.end()) { // MiniMapEntities_Squares[B] = App->gui->AddElement(TypeOfUI::GUI_IMAGE, nullptr, { 1000,520 /*(*entityCount)->pos.x ,(*entityCount)->pos.y*/ }, { 0 , 0 }, false, true, { 4, 3, 2, 3 }, // nullptr, nullptr, TEXTURE::MINIMAP_ENTITIES); // // // MiniMapEntities_Squares[B]->map_position.x = MiniMapEntities_Squares[B]->init_map_position.x + App->render->camera.x + (*entityCount)->currentTile.x; // MiniMapEntities_Squares[B]->map_position.y = MiniMapEntities_Squares[B]->init_map_position.y + App->render->camera.y + (*entityCount)->currentTile.y; // entityCount++; // B++; // // } // //} //if (entityCount != App->entities->activeEntities.end()) { // V = 1; //} //LOG("ENTITY POSITION X,Y = %f %f", MiniMapEntities_Squares[B]->map_position.x, MiniMapEntities_Squares[B]->map_position.x); return true; } bool j1Player::Save(pugi::xml_node& data) { //PLAYER POSITION LOG("Loading player state"); mouse_position.x = data.child("position").attribute("X").as_int(); mouse_position.y = data.child("position").attribute("Y").as_int(); return true; } bool j1Player::Load(pugi::xml_node& data) { //PLAYER POSITION LOG("Loading player state"); mouse_position.x = data.child("position").attribute("X").as_int(); mouse_position.y = data.child("position").attribute("Y").as_int(); return true; } bool j1Player::Update(float dt) { int z = 0; App->input->GetMousePosition(mouse_position.x, mouse_position.y); Camera_Control(dt); Zoom(); if (App->PAUSE_ACTIVE == false) { if (App->scenes->IN_GAME_SCENE == true) { p2List_item<j1UIElement*>* UI_List = App->gui->GUI_ELEMENTS.start; while (UI_List != NULL) { if (App->gui->GUI_ELEMENTS[z]->textureType == TEXTURE::MINIMAP_CAMERA) { App->gui->GUI_ELEMENTS[z]->map_position.x = App->gui->GUI_ELEMENTS[z]->init_map_position.x + App->render->camera.x - MinimapCameraBufferX; App->gui->GUI_ELEMENTS[z]->map_position.y = App->gui->GUI_ELEMENTS[z]->init_map_position.y + App->render->camera.y - MinimapCameraBufferY; } else if (App->gui->GUI_ELEMENTS[z]->textureType == TEXTURE::MINIMAP_ENTITIES) { } else { //LOG("UI COUNT IS %d", z); App->gui->GUI_ELEMENTS[z]->map_position.x = App->gui->GUI_ELEMENTS[z]->init_map_position.x + App->render->camera.x; App->gui->GUI_ELEMENTS[z]->map_position.y = App->gui->GUI_ELEMENTS[z]->init_map_position.y + App->render->camera.y; /*if (App->gui->GUI_ELEMENTS[z]->textureType == TEXTURE::MINIMAP_ENTITIES) { LOG("SQUARE POSITION X=%f, Y=%f ", App->gui->GUI_ELEMENTS[z]->map_position.x, App->gui->GUI_ELEMENTS[z]->map_position.y); }*/ } UI_List = UI_List->next; ++z; } } } Select_Entities(selector); int B = 0; list<Entity*>::iterator entityCount = App->entities->activeEntities.begin(); while (entityCount != App->entities->activeEntities.end()) { /*MiniMapEntities_Squares[B] = App->gui->AddElement(TypeOfUI::GUI_IMAGE, nullptr, { (*entityCount)->pos.x , (*entityCount)->pos.y}, { 0 , 0 }, false, true, { 4, 3, 2, 3 }, nullptr, nullptr, TEXTURE::MINIMAP_ENTITIES); */ entityCount++; B++; } return true; } bool j1Player::CleanUp() { return true; } void j1Player::Camera_Control(float dt) { int z = 0; if (App->scenes->current_scene->scene_name == SCENES::GAME_SCENE) { if (App->PAUSE_ACTIVE==false) { if (mouse_position.x == 0 && App->render->camera.x <= 3750) { //LOG("Camera x at %d", App->render->camera.x); App->render->camera.x += camera_speed * dt * 1000; //1242X //695Y MinimapCameraBufferX = MinimapCameraBufferX + 1.1; } if (mouse_position.y == 0) { //LOG("Camera y at %d", App->render->camera.y); App->render->camera.y += camera_speed * dt * 1000; if (App->render->camera.y < 50) { MinimapCameraBufferY = MinimapCameraBufferY + 1.1; } } if (mouse_position.x > (win_width - camera_offset) / App->win->scale ) { //LOG("Camera x at %d", App->render->camera.x); App->render->camera.x -= camera_speed * dt * 1000; if (App->render->camera.x > -2900) { MinimapCameraBufferX = MinimapCameraBufferX - 1.1; } } if (mouse_position.y > (win_height - camera_offset) / App->win->scale) { //LOG("Camera y at %d", App->render->camera.y); App->render->camera.y -= camera_speed * dt * 1000; if (App->render->camera.y > -3150) { MinimapCameraBufferY = MinimapCameraBufferY - 1.1; } } if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT) App->render->camera.y += camera_speed * dt * 1000; if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT) App->render->camera.y -= camera_speed * dt * 1000; if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT) App->render->camera.x += camera_speed * dt * 1000; if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT) App->render->camera.x -= camera_speed * dt * 1000; if (App->render->camera.x < -2900) App->render->camera.x = -2900; if (App->render->camera.x > 3800) App->render->camera.x = 3800; if (App->render->camera.y > 50) App->render->camera.y = 50; if (App->render->camera.y < -3150) App->render->camera.y = -3150; if (App->input->GetKey(SDL_SCANCODE_H) == KEY_DOWN) { //has to update camera minimap if (App->scenes->Map_Forest_Active) { App->render->camera.x = 575; App->render->camera.y = -1200; MinimapCameraBufferX = 4; MinimapCameraBufferY = -4; } if (App->scenes->Map_Snow_Active) { App->render->camera.x = -329; App->render->camera.y = -608; MinimapCameraBufferX = -24; MinimapCameraBufferY = 15; } if (App->scenes->Map_Volcano_Active) { App->render->camera.x = 700; App->render->camera.y = 10; MinimapCameraBufferX = 4.39; MinimapCameraBufferY = 33; } } } } Mouse_Cursor(); } void j1Player::Select_Entities(SDL_Rect select_area) { int buffer; if (select_area.x > select_area.x + select_area.w) { select_area.x = select_area.x + select_area.w; select_area.w *= -1; } if (select_area.y > select_area.y + select_area.h) { select_area.y = select_area.y + select_area.h; select_area.h *= -1; } //LOG("Ax -> %d | Ay -> %d | Aw -> %d | Ah -> %d", select_area.x, select_area.y, select_area.w, select_area.h); } void j1Player::Mouse_Cursor() { mouse_position.x -= App->render->camera.x / App->win->GetScale(); mouse_position.y -= App->render->camera.y / App->win->GetScale(); App->render->RenderQueueUI(10,Tex_Player, mouse_position.x, mouse_position.y, texture_rect); } void j1Player::Zoom() { if (App->input->GetKey(SDL_SCANCODE_9) == KEY_REPEAT) //zoom IN { App->win->scale = App->win->scale + 0.001; } else if (App->input->GetKey(SDL_SCANCODE_0) == KEY_REPEAT)//zoom OUT { App->win->scale = App->win->scale - 0.001; } else if (App->input->GetKey(SDL_SCANCODE_R) == KEY_DOWN)//zoom RESET { App->win->scale = 0.5; } }
22.241287
187
0.639344
cf98dfda2cfd8ff4aba8b083cefe8ea8af931e8d
2,846
hpp
C++
third-party/casadi/casadi/core/global_options.hpp
dbdxnuliba/mit-biomimetics_Cheetah
f3b0c0f6a3835d33b7f2f345f00640b3fc256388
[ "MIT" ]
8
2020-02-18T09:07:48.000Z
2021-12-25T05:40:02.000Z
flip-optimization-master/casadi/include/casadi/core/global_options.hpp
WatsonZhouAnda/Cheetah-Software
05e416fb26f968300826f0deb0953be9afb22bfe
[ "MIT" ]
null
null
null
flip-optimization-master/casadi/include/casadi/core/global_options.hpp
WatsonZhouAnda/Cheetah-Software
05e416fb26f968300826f0deb0953be9afb22bfe
[ "MIT" ]
13
2019-08-25T12:32:06.000Z
2022-03-31T02:38:12.000Z
/* * This file is part of CasADi. * * CasADi -- A symbolic framework for dynamic optimization. * Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl, * K.U. Leuven. All rights reserved. * Copyright (C) 2011-2014 Greg Horn * * CasADi is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * CasADi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with CasADi; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef CASADI_GLOBAL_OPTIONS_HPP #define CASADI_GLOBAL_OPTIONS_HPP #include <iostream> #include <fstream> #include <casadi/core/casadi_export.h> #include "casadi/core/casadi_common.hpp" namespace casadi { /** * \brief Collects global CasADi options * * * Note to developers: \n * - use sparingly. Global options are - in general - a rather bad idea \n * - this class must never be instantiated. Access its static members directly \n * * \author Joris Gillis * \date 2012 */ class CASADI_EXPORT GlobalOptions { private: /// No instances are allowed GlobalOptions(); public: #ifndef SWIG /** \brief Indicates whether simplifications should be made on the fly. * e.g. cos(-x) -> cos(x) * Default: true */ static bool simplification_on_the_fly; static std::string casadipath; static bool hierarchical_sparsity; static casadi_int max_num_dir; static casadi_int start_index; #endif //SWIG // Setter and getter for simplification_on_the_fly static void setSimplificationOnTheFly(bool flag) { simplification_on_the_fly = flag; } static bool getSimplificationOnTheFly() { return simplification_on_the_fly; } // Setter and getter for hierarchical_sparsity static void setHierarchicalSparsity(bool flag) { hierarchical_sparsity = flag; } static bool getHierarchicalSparsity() { return hierarchical_sparsity; } static void setCasadiPath(const std::string & path) { casadipath = path; } static std::string getCasadiPath() { return casadipath; } static void setMaxNumDir(casadi_int ndir) { max_num_dir=ndir; } static casadi_int getMaxNumDir() { return max_num_dir; } }; } // namespace casadi #endif // CASADI_GLOBAL_OPTIONS_HPP
31.977528
92
0.696416
cf9d37798720db9786c9cc62bd9736ada53f15da
3,671
cpp
C++
modules/tracktion_engine/plugins/internal/tracktion_VCA.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
null
null
null
modules/tracktion_engine/plugins/internal/tracktion_VCA.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
null
null
null
modules/tracktion_engine/plugins/internal/tracktion_VCA.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
null
null
null
/* ,--. ,--. ,--. ,--. ,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018 '-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software | | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation `---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details. */ namespace tracktion_engine { class VcaAutomatableParameter : public AutomatableParameter { public: VcaAutomatableParameter (const juce::String& xmlTag, const juce::String& name, Plugin& owner, juce::Range<float> valueRangeToUse) : AutomatableParameter (xmlTag, name, owner, valueRangeToUse) { } ~VcaAutomatableParameter() override { notifyListenersOfDeletion(); } juce::String valueToString (float value) override { return juce::Decibels::toString (volumeFaderPositionToDB (value) + 0.001); } float stringToValue (const juce::String& str) override { return decibelsToVolumeFaderPosition (dbStringToDb (str)); } }; //============================================================================== VCAPlugin::VCAPlugin (PluginCreationInfo info) : Plugin (info) { addAutomatableParameter (volParam = new VcaAutomatableParameter ("vca", TRANS("VCA"), *this, { 0.0f, 1.0f })); volumeValue.referTo (state, IDs::volume, getUndoManager(), decibelsToVolumeFaderPosition (0.0f)); volParam->attachToCurrentValue (volumeValue); } VCAPlugin::~VCAPlugin() { notifyListenersOfDeletion(); volParam->detachFromCurrentValue(); } juce::ValueTree VCAPlugin::create() { juce::ValueTree v (IDs::PLUGIN); v.setProperty (IDs::type, xmlTypeName, nullptr); return v; } const char* VCAPlugin::xmlTypeName = "vca"; void VCAPlugin::initialise (const PluginInitialisationInfo&) {} void VCAPlugin::deinitialise() {} void VCAPlugin::applyToBuffer (const PluginRenderContext&) {} float VCAPlugin::getSliderPos() const { return volParam->getCurrentValue(); } void VCAPlugin::setVolumeDb (float dB) { setSliderPos (decibelsToVolumeFaderPosition (dB)); } float VCAPlugin::getVolumeDb() const { return volumeFaderPositionToDB (volParam->getCurrentValue()); } void VCAPlugin::setSliderPos (float newV) { volParam->setParameter (juce::jlimit (0.0f, 1.0f, newV), juce::sendNotification); } void VCAPlugin::muteOrUnmute() { if (getVolumeDb() > -90.0f) { lastVolumeBeforeMute = getVolumeDb(); setVolumeDb (lastVolumeBeforeMute - 0.01f); // needed so that automation is recorded correctly setVolumeDb (-100.0f); } else { if (lastVolumeBeforeMute < -100.0f) lastVolumeBeforeMute = 0.0f; setVolumeDb (getVolumeDb() + 0.01f); // needed so that automation is recorded correctly setVolumeDb (lastVolumeBeforeMute); } } float VCAPlugin::updateAutomationStreamAndGetVolumeDb (double time) { if (isAutomationNeeded()) { updateParameterStreams (time); updateLastPlaybackTime(); } return getVolumeDb(); } bool VCAPlugin::canBeMoved() { if (auto ft = dynamic_cast<FolderTrack*> (getOwnerTrack())) return ft->isSubmixFolder(); return false; } void VCAPlugin::restorePluginStateFromValueTree (const juce::ValueTree& v) { juce::CachedValue<float>* cvsFloat[] = { &volumeValue, nullptr }; copyPropertiesToNullTerminatedCachedValues (v, cvsFloat); for (auto p : getAutomatableParameters()) p->updateFromAttachedValue(); } }
27.192593
114
0.616998
cf9e02d74d153181e3e897ebe551f78dd73fe3ea
2,278
cpp
C++
FirstSemester(CS Project)/Plane.cpp
garretfox/C
9c6baeffc26e1131b873c1d7aaa99b0145635526
[ "MIT" ]
null
null
null
FirstSemester(CS Project)/Plane.cpp
garretfox/C
9c6baeffc26e1131b873c1d7aaa99b0145635526
[ "MIT" ]
null
null
null
FirstSemester(CS Project)/Plane.cpp
garretfox/C
9c6baeffc26e1131b873c1d7aaa99b0145635526
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Plane.h" #include <iostream> using namespace std; Plane::Plane() { isSet = 0; } Plane::Plane(char *c) { PlaneName = c; NumberOfParties = 0; for (int i = 0; i < 40; i++) { PartyArray[i].SetPartyName("NULL"); PartyArray[i].SetPartySize(0); }; isSet = 0; } void Plane::SetPartyAt(int i, char* c, int j) { GetPartyArrayAt(i).SetPartyName(c); GetPartyArrayAt(i).SetPartySize(j); } bool Plane::NameNull(int i) { if (PartyArray[i].GetPartyName() == "NULL") return 1; else return 0; } bool Plane::IsSet() { return isSet; } void Plane::AddSeats(int i) { int j = NumberOfSeats + i; NumberOfSeats = j; } void Plane::SubtractSeats(int i) { int j = NumberOfSeats - i; NumberOfSeats = j; } void Plane::SetSeatNumber() { bool valid = 0; int i; cout << "Enter " << PlaneName << "'s Seating Capacity" << endl; cin >> i; do { if (i > 40 || i < 0) { cout << " Invalid Number" << endl; } else { valid = 1; NumberOfSeats = i; OriginalNumberOfSeats = i; } } while (!valid); } void Plane::IncrementNumberOfParties() { NumberOfParties++; } void Plane::DecrementNumberOfParties() { NumberOfParties--; } int Plane::GetNumberOfAvailableSeats() { return NumberOfSeats; } void Plane::DisplayOnboardParties() { cout << "PARTY NAMES" << endl; for (int i = 0; i < NumberOfParties; i++) { if (GetPartyArrayAt(i).GetPartyName() != "NULL") { cout << "______________________ PARTY " << i << "_________________________" << endl; cout << *(GetPartyArrayAt(i).GetPartyName()) << endl; cout << "And Has " << GetPartyArrayAt(i).GetPartySize() << " People." << endl; cout << "_________________________________________________________________" << endl; } else; } } Party Plane::GetPartyArrayAt(int i) { return PartyArray[i]; } Party * Plane::GetPartyArray() { return PartyArray; } void Plane::Reset() { cout << "Passengers Departing on " << PlaneName << ":" << endl; cout << "__+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+___" << endl; DisplayOnboardParties(); for (int i = 0; i < 40; i++) { PartyArray[i].SetPartyName("NULL"); PartyArray[i].SetPartySize(0); }; NumberOfParties = 0; NumberOfSeats = OriginalNumberOfSeats; } int Plane::GetNumberofParties() { return NumberOfParties; }
18.672131
87
0.644425
cf9fad672f46c29a27693a166044d7a5eb688cdf
6,161
cc
C++
protocol/zigbee/app/framework/scenarios/z3/Z3SwitchWithVoice/keyword_detection.cc
PascalGuenther/gecko_sdk
2e82050dc8823c9fe0e8908c1b2666fb83056230
[ "Zlib" ]
82
2016-06-29T17:24:43.000Z
2021-04-16T06:49:17.000Z
protocol/zigbee/app/framework/scenarios/z3/Z3SwitchWithVoice/keyword_detection.cc
PascalGuenther/gecko_sdk
2e82050dc8823c9fe0e8908c1b2666fb83056230
[ "Zlib" ]
6
2022-01-12T18:22:08.000Z
2022-03-25T10:19:27.000Z
protocol/zigbee/app/framework/scenarios/z3/Z3SwitchWithVoice/keyword_detection.cc
PascalGuenther/gecko_sdk
2e82050dc8823c9fe0e8908c1b2666fb83056230
[ "Zlib" ]
56
2016-08-02T10:50:50.000Z
2021-07-19T08:57:34.000Z
/***************************************************************************//** * @file keywork_detection.cc * @brief Top level application functions ******************************************************************************* * # License * <b>Copyright 2021 Silicon Laboratories Inc. www.silabs.com</b> ******************************************************************************* * * The licensor of this software is Silicon Laboratories Inc. Your use of this * software is governed by the terms of Silicon Labs Master Software License * Agreement (MSLA) available at * www.silabs.com/about-us/legal/master-software-license-agreement. This * software is distributed to you in Source Code format and is governed by the * sections of the MSLA applicable to Source Code. * ******************************************************************************/ #include "sl_status.h" #include "sl_sleeptimer.h" #include "sl_component_catalog.h" #if defined(SL_CATALOG_POWER_MANAGER_PRESENT) #include "sl_power_manager.h" #endif #include "tensorflow/lite/micro/micro_error_reporter.h" #include "tensorflow/lite/micro/micro_interpreter.h" #include "tensorflow/lite/micro/micro_mutable_op_resolver.h" #include "tensorflow/lite/schema/schema_generated.h" #include "keyword_detection.h" #include "recognize_commands.h" #include "recognize_commands_config.h" #include "sl_tflite_micro_model.h" #include "sl_tflite_micro_init.h" #include "sl_ml_audio_feature_generation.h" /******************************************************************************* ******************************* DEFINES *********************************** ******************************************************************************/ #ifndef INFERENCE_INTERVAL_MS #define INFERENCE_INTERVAL_MS 200 #endif /******************************************************************************* *************************** LOCAL VARIABLES ******************************** ******************************************************************************/ // Instance Pointers static RecognizeCommands *command_recognizer = nullptr; static volatile bool inference_timeout; static sl_sleeptimer_timer_handle_t inference_timer; /***************************************************************************//** * Run model inference * * Copies the currently available data from the feature_buffer into the input * tensor and runs inference, updating the global output_tensor. ******************************************************************************/ static sl_status_t run_inference() { // Update model input tensor sl_status_t status = sl_ml_audio_feature_generation_fill_tensor(sl_tflite_micro_get_input_tensor()); if (status != SL_STATUS_OK) { return SL_STATUS_FAIL; } // Run the model on the spectrogram input and make sure it succeeds. TfLiteStatus invoke_status = sl_tflite_micro_get_interpreter()->Invoke(); if (invoke_status != kTfLiteOk) { return SL_STATUS_FAIL; } return SL_STATUS_OK; } /***************************************************************************//** * Processes the output from output_tensor ******************************************************************************/ sl_status_t process_output() { // Determine whether a command was recognized based on the output of inference uint8_t found_command_index = 0; uint8_t score = 0; bool is_new_command = false; uint32_t current_time_stamp; // Get current time stamp needed by CommandRecognizer current_time_stamp = sl_sleeptimer_tick_to_ms(sl_sleeptimer_get_tick_count()); TfLiteStatus process_status = command_recognizer->ProcessLatestResults( sl_tflite_micro_get_output_tensor(), current_time_stamp, &found_command_index, &score, &is_new_command); if (process_status != kTfLiteOk) { return SL_STATUS_FAIL; } if (is_new_command) { if (found_command_index == 0 || found_command_index == 1) { printf("Heard %s (%d) @%ldms\r\n", kCategoryLabels[found_command_index], score, current_time_stamp); keyword_detected(found_command_index); } } return SL_STATUS_OK; } /***************************************************************************//** * Inference timer callback ******************************************************************************/ static void inference_timer_callback(sl_sleeptimer_timer_handle_t *handle, void* data) { (void)handle; (void)data; inference_timeout = true; } /******************************************************************************* ************************** GLOBAL FUNCTIONS ******************************* ******************************************************************************/ /***************************************************************************//** * Initialize application. ******************************************************************************/ void keyword_detection_init(void) { #if defined(SL_CATALOG_POWER_MANAGER_PRESENT) // Add EM1 requirement to allow for continous microphone sampling sl_power_manager_add_em_requirement(SL_POWER_MANAGER_EM1); #endif // Initialize audio feature generation sl_ml_audio_feature_generation_init(); // Instantiate CommandRecognizer static RecognizeCommands static_recognizer(sl_tflite_micro_get_error_reporter(), SMOOTHING_WINDOW_DURATION_MS, DETECTION_THRESHOLD, SUPPRESION_TIME_MS, MINIMUM_DETECTION_COUNT); command_recognizer = &static_recognizer; // Start periodic timer for inference interval sl_sleeptimer_start_periodic_timer_ms(&inference_timer, INFERENCE_INTERVAL_MS, inference_timer_callback, NULL, 0, 0); } /***************************************************************************//** * Keyword detection process action ******************************************************************************/ void keyword_detection_process_action(void) { // Perform keyword detection every INFERENCE_INTERVAL_MS ms if (inference_timeout == true) { sl_ml_audio_feature_generation_update_features(); run_inference(); process_output(); inference_timeout = false; } }
39.748387
119
0.549586
cfa01b83595624a414618fe97995471a1d0b71be
583
cpp
C++
AppCUI/src/Controls/UserControl.cpp
rzaharia/AppCUI
9aa37b154e04d0aa3e69a75798a698f591b0c8ca
[ "MIT" ]
null
null
null
AppCUI/src/Controls/UserControl.cpp
rzaharia/AppCUI
9aa37b154e04d0aa3e69a75798a698f591b0c8ca
[ "MIT" ]
null
null
null
AppCUI/src/Controls/UserControl.cpp
rzaharia/AppCUI
9aa37b154e04d0aa3e69a75798a698f591b0c8ca
[ "MIT" ]
null
null
null
#include "ControlContext.hpp" using namespace AppCUI::Controls; bool UserControl::Create(Control* parent, const AppCUI::Utils::ConstString& caption, const std::string_view& layout) { CONTROL_INIT_CONTEXT(ControlContext); CHECK(Init(parent, caption, layout, false), false, "Failed to create user control !"); CREATE_CONTROL_CONTEXT(this, Members, false); Members->Flags = GATTR_VISIBLE | GATTR_ENABLE | GATTR_TABSTOP; return true; } bool UserControl::Create(Control* parent, const std::string_view& layout) { return UserControl::Create(parent, "", layout); }
36.4375
116
0.744425
cfa15397b6c7d61a6ac8537e4b9c2cdecbd4826b
1,360
hh
C++
src/ETransform.hh
jjzhang166/CxxLog4j
3c674f8a7f57deee228c5de6869c9f5852596930
[ "Apache-2.0" ]
5
2016-08-25T14:26:45.000Z
2018-11-07T08:30:38.000Z
src/ETransform.hh
jjzhang166/CxxLog4j
3c674f8a7f57deee228c5de6869c9f5852596930
[ "Apache-2.0" ]
1
2018-07-06T02:37:10.000Z
2018-07-11T05:47:47.000Z
src/ETransform.hh
jjzhang166/CxxLog4j
3c674f8a7f57deee228c5de6869c9f5852596930
[ "Apache-2.0" ]
4
2017-06-09T01:22:43.000Z
2019-02-19T07:19:59.000Z
/* * ETransform.hh * * Created on: 2015-8-11 * Author: cxxjava@163.com */ #ifndef ETRANSFORM_HH_ #define ETRANSFORM_HH_ #include "Efc.hh" #include "../inc/ELogger.hh" namespace efc { namespace log { /** * Utility class for transforming strings. */ class ETransform { public: /** * This method takes a string which may contain HTML tags (ie, * &lt;b&gt;, &lt;table&gt;, etc) and replaces any * '<', '>' , '&' or '"' * characters with respective predefined entity references. * * @param buf StringBuffer holding the escaped data to this point. * @param input The text to be converted. * */ static void appendEscapingTags(EString& buf, const char* input); /** * Ensures that embeded CDEnd strings (]]>) are handled properly * within message, NDC and throwable tag text. * * @param buf StringBuffer holding the XML data to this point. The * initial CDStart (<![CDATA[) and final CDEnd (]]>) of the CDATA * section are the responsibility of the calling method. * @param input The String that is inserted into an existing CDATA Section within buf. * */ static void appendEscapingCDATA(EString& buf, const char* input); /** * convert logger level from integer to string */ static const char* toLevelStr(ELogger::Level level); }; } /* namespace log */ } /* namespace efc */ #endif /* ETRANSFORM_HH_ */
24.727273
87
0.680147
cfa1a15555f29bc71b3ec1198ffc2ffa006c53f3
254
cpp
C++
abc/ABC161/cpp/a.cpp
yokotani92/atcoder
febaef2d13c40093a2a284c87a949cd46113801d
[ "MIT" ]
null
null
null
abc/ABC161/cpp/a.cpp
yokotani92/atcoder
febaef2d13c40093a2a284c87a949cd46113801d
[ "MIT" ]
null
null
null
abc/ABC161/cpp/a.cpp
yokotani92/atcoder
febaef2d13c40093a2a284c87a949cd46113801d
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <vector> #define rep(i, n) for (int i = 0; i < (int)(n); i++) using namespace std; typedef long long ll; const int MOD = 1E9 + 9; const int INF = 1 << 29; int main() { int A; cin >> A; cout << A; }
18.142857
52
0.598425
cfa44f9a16a58ec7ed3b6ee8a2744e12ce2704d7
1,985
cpp
C++
CSL/CSL-r/src/wmark/scanner_actions/tk_action.cpp
ZJU-ZSJ/CppTSL
6ce7673d5f7f8de8769c6377090b845492e63aa9
[ "BSD-2-Clause" ]
null
null
null
CSL/CSL-r/src/wmark/scanner_actions/tk_action.cpp
ZJU-ZSJ/CppTSL
6ce7673d5f7f8de8769c6377090b845492e63aa9
[ "BSD-2-Clause" ]
null
null
null
CSL/CSL-r/src/wmark/scanner_actions/tk_action.cpp
ZJU-ZSJ/CppTSL
6ce7673d5f7f8de8769c6377090b845492e63aa9
[ "BSD-2-Clause" ]
null
null
null
/* ** Xin YUAN, 2019, BSD (2) */ //////////////////////////////////////////////////////////////////////////////// #include "precomp.h" #include "../WmarkScanner.h" #include "../base/WmarkDef.h" //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// namespace CSL { //////////////////////////////////////////////////////////////////////////////// // TkAction RdScannerAction WmarkScannerHelper::get_TkAction() { return [](std::istream& stm, RdActionStack& stk, RdToken& token)->bool { //get a character char ch; stm.get(ch); if( stm.eof() ) { token.uID = TK_END_OF_EVENT; return true; } if( !stm.good() ) return false; token.strToken += ch; //return if( ch == '\n' ) { token.uID = WMARK_TK_RETURN; token.infoEnd.uRow ++; token.infoEnd.uCol = 0; return true; } if( ch == '\r' ) { stm.get(ch); if( stm.eof() ) { token.uID = WMARK_TK_RETURN; token.infoEnd.uRow ++; token.infoEnd.uCol = 0; return true; } if( !stm.good() ) return false; token.infoEnd.uRow ++; token.infoEnd.uCol = 0; if( ch == '\n' ) { token.strToken += ch; token.uID = WMARK_TK_RETURN; return true; } stm.unget(); token.uID = WMARK_TK_RETURN; return true; } token.infoEnd.uCol ++; //indent if( ch == '\t' ) { token.uID = WMARK_TK_INDENT; return true; } //< if( ch == '<' ) { stk.push(WMARK_SCANNER_COMMENT_ACTION); return true; } //others stk.push(WMARK_SCANNER_TEXT_ACTION); return true; }; } //////////////////////////////////////////////////////////////////////////////// } ////////////////////////////////////////////////////////////////////////////////
22.303371
81
0.38136
cfa5723015d33450fb4eb00278ee8b7638607106
1,079
cpp
C++
C++/Data_Structures/Path_Sum_II.cpp
IUC4801/HactoberFest21
ad52dee669deba54630584435b77a6ab07dc67b2
[ "Unlicense" ]
1
2021-10-03T08:02:58.000Z
2021-10-03T08:02:58.000Z
C++/Data_Structures/Path_Sum_II.cpp
IUC4801/HactoberFest21
ad52dee669deba54630584435b77a6ab07dc67b2
[ "Unlicense" ]
1
2021-10-06T04:41:55.000Z
2021-10-06T04:41:55.000Z
C++/Data_Structures/Path_Sum_II.cpp
IUC4801/HactoberFest21
ad52dee669deba54630584435b77a6ab07dc67b2
[ "Unlicense" ]
1
2021-10-08T12:31:04.000Z
2021-10-08T12:31:04.000Z
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<vector<int>> ans; void solve(TreeNode* root,int sum,vector<int> &res){ if(!root) { return; } if(root->left==NULL&&root->right==NULL&&sum==root->val){ res.push_back(root->val); ans.push_back(res); res.pop_back(); } else { res.push_back(root->val); solve(root->left,sum-root->val,res); solve(root->right,sum-root->val,res); res.pop_back(); } } vector<vector<int>> pathSum(TreeNode* root, int targetSum) { vector<int> res; solve(root,targetSum,res); return ans; } };
27.666667
93
0.510658
cfa6269395b8e032be571d81ad55df8fe1d840f4
1,902
cpp
C++
test/algorithm/test_scalar_product.cpp
jan-moeller/lina
9acaac27d7efb3e8b3c4d1ae2ad9425e79f233c8
[ "MIT" ]
null
null
null
test/algorithm/test_scalar_product.cpp
jan-moeller/lina
9acaac27d7efb3e8b3c4d1ae2ad9425e79f233c8
[ "MIT" ]
null
null
null
test/algorithm/test_scalar_product.cpp
jan-moeller/lina
9acaac27d7efb3e8b3c4d1ae2ad9425e79f233c8
[ "MIT" ]
null
null
null
// // MIT License // // Copyright (c) 2021 Jan Möller // // 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 "lina/lina.hpp" #include <catch2/catch.hpp> using namespace lina; TEST_CASE("scalar_product", "[algorithm]") { constexpr basic_matrix<double, {3, 2}> m{1, 2, 3, 4, 5, 6}; constexpr basic_matrix<double, {3, 2}> expected{3, 6, 9, 12, 15, 18}; constexpr float scalar = 3; SECTION("copy") { auto const result1 = scalar_product(scalar, m); auto const result2 = scalar_product(m, scalar); CHECK(result1 == expected); CHECK(result1 == result2); } SECTION("in place") { auto m1 = m; auto m2 = m; scalar_product(std::in_place, scalar, m1); scalar_product(std::in_place, m2, scalar); CHECK(m1 == expected); CHECK(m1 == m2); } }
35.886792
81
0.679811
cfa71a4d6fc15a687b05d19ccf96c7684a70116f
2,593
cpp
C++
src/database/core/SoXipMprActiveElement.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
2
2020-05-21T07:06:07.000Z
2021-06-28T02:14:34.000Z
src/database/core/SoXipMprActiveElement.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
null
null
null
src/database/core/SoXipMprActiveElement.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
6
2016-03-21T19:53:18.000Z
2021-06-08T18:06:03.000Z
/* Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation 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 <xip/inventor/core/SoXipMprActiveElement.h> SO_ELEMENT_SOURCE(SoXipMprActiveElement); //////////////////////////////////////////////////////////////////////// SoXipMprActiveElement::~SoXipMprActiveElement() { } void SoXipMprActiveElement::initClass() { SO_ELEMENT_INIT_CLASS(SoXipMprActiveElement, SoReplacedElement); } void SoXipMprActiveElement::init(SoState *) { mprId = 0; mprIdField = 0; } void SoXipMprActiveElement::set(SoState *state, SoNode *node, const int32_t index, SoSFInt32* indexField) { SoXipMprActiveElement *elt; // get an instance we can change (pushing if necessary) elt = (SoXipMprActiveElement *) getElement(state, classStackIndex, node); if ( (elt != NULL) ) { elt->mprId = index; elt->mprIdField = indexField; } } SoSFInt32* SoXipMprActiveElement::getMprFieldIndex(SoState *state) { const SoXipMprActiveElement *elt; elt = (const SoXipMprActiveElement *)getConstElement(state, classStackIndex); if ( (elt != NULL) ) return elt->mprIdField; else return NULL; } const int32_t SoXipMprActiveElement::getMprIndex(SoState *state) { const SoXipMprActiveElement *elt; elt = (const SoXipMprActiveElement *)getConstElement(state, classStackIndex); if ( (elt != NULL) ) return elt->mprId; else return 0; } // // Overrides this method to compare attenuation values. // SbBool SoXipMprActiveElement::matches(const SoElement *elt) const { SbBool match = FALSE; if ( (mprIdField == ((const SoXipMprActiveElement *) elt)->mprIdField) && (mprId == ((const SoXipMprActiveElement *) elt)->mprId) ) match = TRUE; return match; } // // Create a copy of this instance suitable for calling matches() // SoElement * SoXipMprActiveElement::copyMatchInfo() const { SoXipMprActiveElement *result = (SoXipMprActiveElement *)getTypeId().createInstance(); if(result) { result->mprId = mprId; return result; } else return NULL; }
21.429752
100
0.712302
cfa7ce00d119a08def66b1f055401db4c1bf0e76
19,869
cc
C++
chrome/browser/ui/views/tabs/overflow_view_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/ui/views/tabs/overflow_view_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/ui/views/tabs/overflow_view_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/tabs/overflow_view.h" #include <algorithm> #include <memory> #include <utility> #include "base/bind.h" #include "base/memory/raw_ptr.h" #include "base/numerics/safe_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/layout/flex_layout_types.h" #include "ui/views/layout/layout_types.h" #include "ui/views/test/test_views.h" #include "ui/views/view_class_properties.h" class OverflowViewTest : public testing::Test { public: OverflowViewTest() = default; ~OverflowViewTest() override = default; void SetUp() override { parent_view_ = std::make_unique<views::View>(); parent_view_->SetLayoutManager(std::make_unique<views::FillLayout>()); parent_view_->SetSize(kDefaultParentSize); } void TearDown() override { parent_view_.reset(); overflow_view_ = nullptr; } void Init(const gfx::Size& primary_minimum_size, const gfx::Size& primary_preferred_size, const gfx::Size& indicator_minimum_size, const gfx::Size& indicator_preferred_size) { auto primary_view = std::make_unique<views::StaticSizedView>(primary_preferred_size); primary_view->set_minimum_size(primary_minimum_size); primary_view_ = primary_view.get(); auto indicator_view = std::make_unique<views::StaticSizedView>(indicator_preferred_size); indicator_view->set_minimum_size(indicator_minimum_size); indicator_view_ = indicator_view.get(); overflow_view_ = parent_view_->AddChildView(std::make_unique<OverflowView>( std::move(primary_view), std::move(indicator_view))); } protected: static int InterpolateByTens(int minimum, int preferred, views::SizeBound bound) { if (!bound.is_bounded()) return preferred; if (bound.value() <= minimum) return minimum; if (bound.value() >= preferred) return preferred; return minimum + 10 * ((bound.value() - minimum) / 10); } // Flex rule where height and width step by 10s up from minimum to preferred // size. static gfx::Size StepwiseFlexRule(const views::View* view, const views::SizeBounds& bounds) { const gfx::Size preferred = view->GetPreferredSize(); const gfx::Size minimum = view->GetMinimumSize(); return gfx::Size( InterpolateByTens(minimum.width(), preferred.width(), bounds.width()), InterpolateByTens(minimum.height(), preferred.height(), bounds.height())); } // Flex rule where the vertical axis contracts from preferred to minimum size // by the same percentage as the horizontal axis is shrunk between preferred // and minimum size. So for instance, if the horizontal axis is constrained // by 20 DIPs and the difference between minimum and preferred is 80 DIPs, // then the vertical axis will be 75% of the way between minimum and preferred // size. static gfx::Size ProportionalFlexRule(const views::View* view, const views::SizeBounds& bounds) { const gfx::Size preferred = view->GetPreferredSize(); const gfx::Size minimum = view->GetMinimumSize(); const int width = std::max(minimum.width(), bounds.width().min_of(preferred.width())); DCHECK_GT(preferred.width(), minimum.width()); double ratio = static_cast<double>(width - minimum.width()) / (preferred.width() - minimum.width()); const int height = bounds.height().min_of( minimum.height() + base::ClampRound(ratio * (preferred.height() - minimum.height()))); return gfx::Size(width, height); } static constexpr gfx::Size kDefaultParentSize{100, 70}; static constexpr gfx::Size kPreferredSize{120, 80}; static constexpr gfx::Size kMinimumSize{40, 20}; static constexpr gfx::Size kPreferredSize2{55, 50}; static constexpr gfx::Size kMinimumSize2{25, 30}; std::unique_ptr<views::View> parent_view_; raw_ptr<OverflowView> overflow_view_ = nullptr; raw_ptr<views::StaticSizedView> primary_view_ = nullptr; raw_ptr<views::StaticSizedView> indicator_view_ = nullptr; }; constexpr gfx::Size OverflowViewTest::kDefaultParentSize; constexpr gfx::Size OverflowViewTest::kPreferredSize; constexpr gfx::Size OverflowViewTest::kMinimumSize; constexpr gfx::Size OverflowViewTest::kPreferredSize2; constexpr gfx::Size OverflowViewTest::kMinimumSize2; TEST_F(OverflowViewTest, SizesNoFlexRules) { Init(kMinimumSize, kPreferredSize, kMinimumSize2, kPreferredSize2); const gfx::Size expected_min( kMinimumSize2.width(), std::max(kMinimumSize.height(), kMinimumSize2.height())); EXPECT_EQ(expected_min, overflow_view_->GetMinimumSize()); EXPECT_EQ(kPreferredSize, overflow_view_->GetPreferredSize()); } TEST_F(OverflowViewTest, SizesNoFlexRulesIndicatorIsLarger) { Init(kMinimumSize2, kPreferredSize2, kMinimumSize, kPreferredSize); const gfx::Size expected_min( kMinimumSize.width(), std::max(kMinimumSize.height(), kMinimumSize2.height())); EXPECT_EQ(expected_min, overflow_view_->GetMinimumSize()); EXPECT_EQ(kPreferredSize, overflow_view_->GetPreferredSize()); EXPECT_EQ(kPreferredSize.height(), overflow_view_->GetHeightForWidth(200)); } TEST_F(OverflowViewTest, SizesNoFlexRulesVertical) { Init(kMinimumSize, kPreferredSize, kMinimumSize2, kPreferredSize2); overflow_view_->SetOrientation(views::LayoutOrientation::kVertical); const gfx::Size expected_min( std::max(kMinimumSize.width(), kMinimumSize2.width()), kMinimumSize2.height()); EXPECT_EQ(expected_min, overflow_view_->GetMinimumSize()); EXPECT_EQ(kPreferredSize, overflow_view_->GetPreferredSize()); } TEST_F(OverflowViewTest, SizesNoFlexRulesIndicatorIsLargerVertical) { Init(kMinimumSize2, kPreferredSize2, kMinimumSize, kPreferredSize); overflow_view_->SetOrientation(views::LayoutOrientation::kVertical); const gfx::Size expected_min( std::max(kMinimumSize.width(), kMinimumSize2.width()), kMinimumSize.height()); EXPECT_EQ(expected_min, overflow_view_->GetMinimumSize()); EXPECT_EQ(kPreferredSize, overflow_view_->GetPreferredSize()); EXPECT_EQ(kPreferredSize.height(), overflow_view_->GetHeightForWidth(200)); } class OverflowViewLayoutTest : public OverflowViewTest { public: OverflowViewLayoutTest() = default; ~OverflowViewLayoutTest() override = default; void SetUp() override { OverflowViewTest::SetUp(); Init(kPrimaryMinimumSize, kPrimaryPreferredSize, kIndicatorMinimumSize, kIndicatorPreferredSize); } void Resize(gfx::Size size) { parent_view_->SetSize(size); parent_view_->Layout(); } void SizeToPreferredSize() { parent_view_->SizeToPreferredSize(); } gfx::Rect primary_bounds() const { return primary_view_->bounds(); } gfx::Rect indicator_bounds() const { return indicator_view_->bounds(); } bool primary_visible() const { return primary_view_->GetVisible(); } bool indicator_visible() const { return indicator_view_->GetVisible(); } protected: static constexpr gfx::Size kPrimaryMinimumSize{80, 20}; static constexpr gfx::Size kPrimaryPreferredSize{160, 30}; static constexpr gfx::Size kIndicatorMinimumSize{16, 16}; static constexpr gfx::Size kIndicatorPreferredSize{32, 32}; static gfx::Size Transpose(const gfx::Size size) { return gfx::Size(size.height(), size.width()); } static gfx::Size TransposingFlexRule(const views::View* view, const views::SizeBounds& size_bounds) { const gfx::Size preferred = Transpose(view->GetPreferredSize()); const gfx::Size minimum = Transpose(view->GetMinimumSize()); int height; int width; if (size_bounds.height().is_bounded()) { height = std::max(minimum.height(), size_bounds.height().min_of(preferred.height())); } else { height = preferred.height(); } if (size_bounds.width().is_bounded()) { width = std::max(minimum.width(), size_bounds.width().min_of(preferred.width())); } else { width = preferred.width(); } return gfx::Size(width, height); } }; constexpr gfx::Size OverflowViewLayoutTest::kPrimaryMinimumSize; constexpr gfx::Size OverflowViewLayoutTest::kPrimaryPreferredSize; constexpr gfx::Size OverflowViewLayoutTest::kIndicatorMinimumSize; constexpr gfx::Size OverflowViewLayoutTest::kIndicatorPreferredSize; TEST_F(OverflowViewLayoutTest, SizeToPreferredSizeIndicatorSmallerThanPrimary) { indicator_view_->SetPreferredSize(kIndicatorMinimumSize); SizeToPreferredSize(); EXPECT_EQ(gfx::Rect(kPrimaryPreferredSize), primary_bounds()); EXPECT_FALSE(indicator_visible()); } TEST_F(OverflowViewLayoutTest, SizeToPreferredSizeIndicatorLargerThanPrimary) { SizeToPreferredSize(); gfx::Size expected = kPrimaryPreferredSize; expected.SetToMax(kIndicatorPreferredSize); EXPECT_EQ(gfx::Rect(expected), primary_bounds()); EXPECT_FALSE(indicator_visible()); } TEST_F(OverflowViewLayoutTest, ScaleToMinimum) { // Since default cross-axis alignment is stretch, the view should fill the // space even if it's larger than the preferred size. gfx::Size size = kPrimaryPreferredSize; size.Enlarge(10, 10); Resize(size); EXPECT_EQ(gfx::Rect(kPrimaryPreferredSize.width(), size.height()), primary_bounds()); EXPECT_FALSE(indicator_visible()); // Default behavior is to scale down smoothly between preferred and minimum // size. size = kPrimaryPreferredSize; size.Enlarge(-10, -10); Resize(size); EXPECT_EQ(gfx::Rect(size), primary_bounds()); EXPECT_FALSE(indicator_visible()); size = kPrimaryMinimumSize; Resize(size); EXPECT_EQ(gfx::Rect(size), primary_bounds()); EXPECT_FALSE(indicator_visible()); // Below minimum size, the stretch alignment means we'll compress. size.Enlarge(0, -5); Resize(size); EXPECT_EQ(gfx::Rect(size), primary_bounds()); EXPECT_FALSE(indicator_visible()); } TEST_F(OverflowViewLayoutTest, Alignment) { gfx::Size size = kPrimaryPreferredSize; size.Enlarge(0, 10); Resize(size); overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kStart); parent_view_->Layout(); EXPECT_EQ(gfx::Rect(gfx::Point(0, 0), kPrimaryPreferredSize), primary_bounds()); EXPECT_FALSE(indicator_visible()); overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kCenter); parent_view_->Layout(); EXPECT_EQ(gfx::Rect(gfx::Point(0, 5), kPrimaryPreferredSize), primary_bounds()); EXPECT_FALSE(indicator_visible()); overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kEnd); parent_view_->Layout(); EXPECT_EQ(gfx::Rect(gfx::Point(0, 10), kPrimaryPreferredSize), primary_bounds()); EXPECT_FALSE(indicator_visible()); size = kPrimaryMinimumSize; size.Enlarge(0, -10); Resize(size); overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kStart); parent_view_->Layout(); EXPECT_EQ(gfx::Rect(gfx::Point(0, 0), kPrimaryMinimumSize), primary_bounds()); EXPECT_FALSE(indicator_visible()); overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kCenter); parent_view_->Layout(); EXPECT_EQ(gfx::Rect(gfx::Point(0, -5), kPrimaryMinimumSize), primary_bounds()); EXPECT_FALSE(indicator_visible()); overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kEnd); parent_view_->Layout(); EXPECT_EQ(gfx::Rect(gfx::Point(0, -10), kPrimaryMinimumSize), primary_bounds()); EXPECT_FALSE(indicator_visible()); } TEST_F(OverflowViewLayoutTest, ScaleToMinimumVertical) { overflow_view_->SetOrientation(views::LayoutOrientation::kVertical); gfx::Size size = kPrimaryPreferredSize; size.Enlarge(10, 10); Resize(size); EXPECT_EQ(gfx::Rect(size.width(), kPrimaryPreferredSize.height()), primary_bounds()); EXPECT_FALSE(indicator_visible()); // Default behavior is to scale down smoothly between preferred and minimum // size. size = kPrimaryPreferredSize; size.Enlarge(-10, -10); Resize(size); EXPECT_EQ(gfx::Rect(size), primary_bounds()); EXPECT_FALSE(indicator_visible()); size = kPrimaryMinimumSize; Resize(size); EXPECT_EQ(gfx::Rect(size), primary_bounds()); EXPECT_FALSE(indicator_visible()); // Below minimum size, the stretch alignment means we'll compress. size.Enlarge(-5, 0); Resize(size); EXPECT_EQ(gfx::Rect(size), primary_bounds()); EXPECT_FALSE(indicator_visible()); } TEST_F(OverflowViewLayoutTest, AlignmentVertical) { overflow_view_->SetOrientation(views::LayoutOrientation::kVertical); gfx::Size size = kPrimaryPreferredSize; size.Enlarge(10, 0); Resize(size); overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kStart); parent_view_->Layout(); EXPECT_EQ(gfx::Rect(gfx::Point(), kPrimaryPreferredSize), primary_bounds()); EXPECT_FALSE(indicator_visible()); overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kCenter); parent_view_->Layout(); EXPECT_EQ(gfx::Rect(gfx::Point(5, 0), kPrimaryPreferredSize), primary_bounds()); EXPECT_FALSE(indicator_visible()); overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kEnd); parent_view_->Layout(); EXPECT_EQ(gfx::Rect(gfx::Point(10, 0), kPrimaryPreferredSize), primary_bounds()); EXPECT_FALSE(indicator_visible()); size = kPrimaryMinimumSize; size.Enlarge(-10, 0); Resize(size); overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kStart); parent_view_->Layout(); EXPECT_EQ(gfx::Rect(gfx::Point(0, 0), kPrimaryMinimumSize), primary_bounds()); EXPECT_FALSE(indicator_visible()); overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kCenter); parent_view_->Layout(); EXPECT_EQ(gfx::Rect(gfx::Point(-5, 0), kPrimaryMinimumSize), primary_bounds()); EXPECT_FALSE(indicator_visible()); overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kEnd); parent_view_->Layout(); EXPECT_EQ(gfx::Rect(gfx::Point(-10, 0), kPrimaryMinimumSize), primary_bounds()); EXPECT_FALSE(indicator_visible()); } TEST_F(OverflowViewLayoutTest, PrimaryOnlyRespectsFlexRule) { primary_view_->SetProperty(views::kFlexBehaviorKey, views::FlexSpecification(base::BindRepeating( &OverflowViewTest::StepwiseFlexRule))); overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kStart); // Since default cross-axis alignment is stretch, the view should fill the // space even if it's larger than the preferred size. gfx::Size size = kPrimaryPreferredSize; size.Enlarge(7, 7); Resize(size); EXPECT_EQ(gfx::Rect(kPrimaryPreferredSize), primary_bounds()); // At intermediate sizes, this flex rule steps down by multiples of 10, to the // next multiple smaller than the available space. size = kPrimaryPreferredSize; size.Enlarge(-7, -7); Resize(size); gfx::Size expected = kPrimaryPreferredSize; expected.Enlarge(-10, -10); EXPECT_EQ(gfx::Rect(expected), primary_bounds()); // The height bottoms out against the minimum size first. size = kPrimaryPreferredSize; size.Enlarge(-13, -13); Resize(size); EXPECT_EQ(gfx::Rect(kPrimaryPreferredSize.width() - 20, kPrimaryMinimumSize.height()), primary_bounds()); size = kPrimaryMinimumSize; Resize(size); EXPECT_EQ(gfx::Rect(size), primary_bounds()); // Below minimum vertical size we won't compress the primary view since we're // not stretching it. size.Enlarge(0, -5); Resize(size); EXPECT_EQ(gfx::Rect(kPrimaryMinimumSize), primary_bounds()); } TEST_F(OverflowViewLayoutTest, HorizontalOverflow) { overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kStart); // The primary view should start at the preferred size and scale down until it // hits the minimum size. gfx::Size size = kPrimaryPreferredSize; size.Enlarge(10, 0); Resize(size); EXPECT_TRUE(primary_view_->GetVisible()); EXPECT_FALSE(indicator_view_->GetVisible()); EXPECT_EQ(gfx::Rect(kPrimaryPreferredSize), primary_bounds()); size = kPrimaryPreferredSize; size.Enlarge(-10, 0); Resize(size); EXPECT_TRUE(primary_view_->GetVisible()); EXPECT_FALSE(indicator_view_->GetVisible()); EXPECT_EQ(gfx::Rect(size), primary_bounds()); size = kPrimaryMinimumSize; Resize(size); EXPECT_TRUE(primary_view_->GetVisible()); EXPECT_FALSE(indicator_view_->GetVisible()); EXPECT_EQ(gfx::Rect(size), primary_bounds()); // Below minimum size, the indicator will be displayed. size.Enlarge(-5, 0); Resize(size); EXPECT_TRUE(primary_view_->GetVisible()); EXPECT_TRUE(indicator_view_->GetVisible()); const gfx::Rect expected_indicator{ size.width() - kIndicatorPreferredSize.width(), 0, kIndicatorPreferredSize.width(), size.height()}; const gfx::Rect expected_primary( gfx::Size(expected_indicator.x(), size.height())); EXPECT_EQ(expected_indicator, indicator_bounds()); EXPECT_EQ(expected_primary, primary_bounds()); // If there is only enough room to show the indicator, then the primary view // loses visibility. size = kIndicatorMinimumSize; Resize(size); EXPECT_FALSE(primary_view_->GetVisible()); EXPECT_TRUE(indicator_view_->GetVisible()); EXPECT_EQ(gfx::Rect(size), indicator_bounds()); } TEST_F(OverflowViewLayoutTest, VerticalOverflow) { overflow_view_->SetOrientation(views::LayoutOrientation::kVertical); overflow_view_->SetCrossAxisAlignment(views::LayoutAlignment::kStart); const views::FlexRule flex_rule = base::BindRepeating(&OverflowViewLayoutTest::TransposingFlexRule); primary_view_->SetProperty(views::kFlexBehaviorKey, views::FlexSpecification(flex_rule)); indicator_view_->SetProperty(views::kFlexBehaviorKey, views::FlexSpecification(flex_rule)); const gfx::Size primary_preferred = Transpose(kPrimaryPreferredSize); const gfx::Size primary_minimum = Transpose(kPrimaryMinimumSize); const gfx::Size indicator_preferred = Transpose(kIndicatorPreferredSize); const gfx::Size indicator_minimum = Transpose(kIndicatorMinimumSize); // The primary view should start at the preferred size and scale down until it // hits the minimum size. gfx::Size size = primary_preferred; size.Enlarge(0, 10); Resize(size); EXPECT_TRUE(primary_view_->GetVisible()); EXPECT_FALSE(indicator_view_->GetVisible()); EXPECT_EQ(gfx::Rect(primary_preferred), primary_bounds()); size = primary_preferred; size.Enlarge(0, -10); Resize(size); EXPECT_TRUE(primary_view_->GetVisible()); EXPECT_FALSE(indicator_view_->GetVisible()); EXPECT_EQ(gfx::Rect(size), primary_bounds()); size = primary_minimum; Resize(size); EXPECT_TRUE(primary_view_->GetVisible()); EXPECT_FALSE(indicator_view_->GetVisible()); EXPECT_EQ(gfx::Rect(size), primary_bounds()); // Below minimum size, the indicator will be displayed. size.Enlarge(0, -5); Resize(size); EXPECT_TRUE(primary_view_->GetVisible()); EXPECT_TRUE(indicator_view_->GetVisible()); const gfx::Rect expected_indicator{ 0, size.height() - indicator_preferred.height(), size.width(), indicator_preferred.height()}; const gfx::Rect expected_primary( gfx::Size(size.width(), expected_indicator.y())); EXPECT_EQ(expected_indicator, indicator_bounds()); EXPECT_EQ(expected_primary, primary_bounds()); size = indicator_minimum; Resize(size); EXPECT_FALSE(primary_view_->GetVisible()); EXPECT_TRUE(indicator_view_->GetVisible()); EXPECT_EQ(gfx::Rect(size), indicator_bounds()); }
37.773764
80
0.726156
bbb9f9305db3702a4b26f8b6b4ba73adab3845da
424
cpp
C++
src/Engine/Renderer/Apis/Vulkan/Shader/VulkanMaterialData.cpp
sfulham/GameProject-1
83c065ac7abc4c0a098dfcb0d1cc13f9d8bf7a03
[ "MIT" ]
null
null
null
src/Engine/Renderer/Apis/Vulkan/Shader/VulkanMaterialData.cpp
sfulham/GameProject-1
83c065ac7abc4c0a098dfcb0d1cc13f9d8bf7a03
[ "MIT" ]
null
null
null
src/Engine/Renderer/Apis/Vulkan/Shader/VulkanMaterialData.cpp
sfulham/GameProject-1
83c065ac7abc4c0a098dfcb0d1cc13f9d8bf7a03
[ "MIT" ]
null
null
null
// // Created by MarcasRealAccount on 31. Oct. 2020 // #include "Engine/Renderer/Apis/Vulkan/Shader/VulkanMaterialData.h" #include "Engine/Renderer/Shader/Shader.h" namespace gp1::renderer::apis::vulkan::shader { VulkanMaterialData::VulkanMaterialData(renderer::shader::Material* material) : VulkanRendererData(material) {} void VulkanMaterialData::CleanUp() {} } // namespace gp1::renderer::apis::vulkan::shader
26.5
77
0.754717
bbbaf53d3973f2789d74f363bb43a4a2d77364d0
3,058
cc
C++
finter/finter_writer_bzip2.cc
cpalmer718/finter
93db360d5d73cb14e15974a93627bbf02e66b7a9
[ "MIT" ]
null
null
null
finter/finter_writer_bzip2.cc
cpalmer718/finter
93db360d5d73cb14e15974a93627bbf02e66b7a9
[ "MIT" ]
null
null
null
finter/finter_writer_bzip2.cc
cpalmer718/finter
93db360d5d73cb14e15974a93627bbf02e66b7a9
[ "MIT" ]
null
null
null
/*! \file finter_writer_bzip2.cc \brief method implementations for finter bzip2 writer \copyright Released under the MIT License. Copyright 2020 Cameron Palmer */ #include "finter/finter_writer_bzip2.h" void finter::finter_writer_bzip2::open(const char *filename) { if (_raw_output) throw std::domain_error( "finter::finter_writer_bzip2: attempted to reopen " "in-use handle"); _raw_output = fopen(filename, "w"); if (!_raw_output) throw std::domain_error( "finter::finter_writer_bzip2: cannot open file \"" + std::string(filename) + "\""); int error = 0; _bz_output = BZ2_bzWriteOpen(&error, _raw_output, 9, 0, 0); if (error == BZ_CONFIG_ERROR) { throw std::domain_error( "finter::finter_writer_bzip2::open: bzip2 writing " "library reports it was compiled improperly"); } else if (error == BZ_PARAM_ERROR) { _fail = true; } else if (error != BZ_OK) { _bad = true; } } void finter::finter_writer_bzip2::close() { int error = 0; if (_bz_output) { BZ2_bzWriteClose(&error, _bz_output, 0, 0, 0); if (error == BZ_SEQUENCE_ERROR) { throw std::domain_error( "finter::finter_writer_bzip2::close: bzip reports " "write/close operation called on read handle"); } _bz_output = 0; } if (_raw_output) { fclose(_raw_output); _raw_output = 0; } } void finter::finter_writer_bzip2::clear() { _good = true; _bad = _fail = false; } bool finter::finter_writer_bzip2::is_open() const { return (_raw_output && _bz_output); } void finter::finter_writer_bzip2::put(char c) { int error = 0; BZ2_bzWrite(&error, _bz_output, reinterpret_cast<void *>(&c), 1); if (error == BZ_PARAM_ERROR || error == BZ_IO_ERROR) { _fail = true; } else if (error == BZ_SEQUENCE_ERROR) { throw std::domain_error( "finter::finter_writer_bzip2::put: bzip reports " "write operation called on read handle"); } } void finter::finter_writer_bzip2::writeline( const std::string &orig_line) { int error = 0; std::string line = orig_line + get_newline(); BZ2_bzWrite(&error, _bz_output, const_cast<void *>(reinterpret_cast<const void *>(line.c_str())), static_cast<int>(line.size())); if (error == BZ_PARAM_ERROR || error == BZ_IO_ERROR) { _fail = true; } else if (error == BZ_SEQUENCE_ERROR) { throw std::domain_error( "finter::finter_writer_bzip2::writeline: bzip " "reports " "write operation called on read handle"); } } void finter::finter_writer_bzip2::write(char *buf, std::streamsize n) { int error = 0; BZ2_bzWrite(&error, _bz_output, reinterpret_cast<void *>(buf), static_cast<int>(n)); if (error == BZ_PARAM_ERROR || error == BZ_IO_ERROR) { _fail = true; } else if (error == BZ_SEQUENCE_ERROR) { throw std::domain_error( "finter::finter_writer_bzip2::write: bzip reports " "write operation called on read handle"); } }
30.277228
79
0.640615
bbbc772b8773e5cae180e4580e552b77666c8a72
3,599
cpp
C++
src/system/libroot/posix/unistd/lockf.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/system/libroot/posix/unistd/lockf.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/system/libroot/posix/unistd/lockf.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2007, Vasilis Kaoutsis, kaoutsis@sch.gr. * Distributed under the terms of the MIT License. */ #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <errno_private.h> int lockf(int fileDescriptor, int function, off_t size) { struct flock fileLock; fileLock.l_start = 0; fileLock.l_len = size; fileLock.l_whence = SEEK_CUR; if (function == F_ULOCK) { // unlock locked sections fileLock.l_type = F_UNLCK; return fcntl(fileDescriptor, F_SETLK, &fileLock); } else if (function == F_LOCK) { // lock a section for exclusive use fileLock.l_type = F_WRLCK; return fcntl(fileDescriptor, F_SETLKW, &fileLock); } else if (function == F_TLOCK) { // test and lock a section for exclusive use fileLock.l_type = F_WRLCK; return fcntl(fileDescriptor, F_SETLK, &fileLock); } else if (function == F_TEST) { // test a section for locks by other processes fileLock.l_type = F_WRLCK; if (fcntl(fileDescriptor, F_GETLK, &fileLock) == -1) return -1; if (fileLock.l_type == F_UNLCK) return 0; __set_errno(EAGAIN); return -1; } else { __set_errno(EINVAL); return -1; } // Notes regarding standard compliance (cf. Open Group Base Specs): // * "The interaction between fcntl() and lockf() locks is unspecified." // * fcntl() locking works on a per-process level. The lockf() description // is a little fuzzy on whether it works the same way. The first quote // seem to describe per-thread locks (though it might actually mean // "threads of other processes"), but the others quotes are strongly // indicating per-process locks: // - "Calls to lockf() from other threads which attempt to lock the locked // file section shall either return an error value or block until the // section becomes unlocked." // - "All the locks for a process are removed when the process // terminates." // - "F_TEST shall detect if a lock by another process is present on the // specified section." // - "The sections locked with F_LOCK or F_TLOCK may, in whole or in part, // contain or be contained by a previously locked section for the same // process. When this occurs, or if adjacent locked sections would // occur, the sections shall be combined into a single locked section." // * fcntl() and lockf() handle a 0 size argument differently. The former // use the file size at the time of the call: // "If the command is F_SETLKW and the process must wait for another // process to release a lock, then the range of bytes to be locked shall // be determined before the fcntl() function blocks. If the file size // or file descriptor seek offset change while fcntl() is blocked, this // shall not affect the range of bytes locked." // lockf(), on the other hand, is supposed to create a lock whose size // dynamically adjusts to the file size: // "If size is 0, the section from the current offset through the largest // possible file offset shall be locked (that is, from the current // offset through the present or any future end-of-file)." // * The lock release handling when closing descriptors sounds a little // different, though might actually mean the same. // For fcntl(): // "All locks associated with a file for a given process shall be removed // when a file descriptor for that file is closed by that process or the // process holding that file descriptor terminates." // For lockf(): // "File locks shall be released on first close by the locking process of // any file descriptor for the file." }
40.897727
77
0.701028
bbbef5de65bc8b029ed136f8309ca4db2a319ecb
1,879
cpp
C++
src/plugins/zalil/servicesmanager.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/zalil/servicesmanager.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/zalil/servicesmanager.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "servicesmanager.h" #include <algorithm> #include <QStringList> #include <QFileInfo> #include <QtDebug> #include "servicebase.h" #include "pendinguploadbase.h" #include "bitcheeseservice.h" namespace LC { namespace Zalil { ServicesManager::ServicesManager (const ICoreProxy_ptr& proxy, QObject *parent) : QObject { parent } , Proxy_ { proxy } { Services_ << std::make_shared<BitcheeseService> (proxy, this); } QStringList ServicesManager::GetNames (const QString& file) const { const auto fileSize = file.isEmpty () ? 0 : QFileInfo { file }.size (); QStringList result; for (const auto& service : Services_) if (service->GetMaxFileSize () > fileSize) result << service->GetName (); return result; } PendingUploadBase* ServicesManager::Upload (const QString& file, const QString& svcName) { const auto pos = std::find_if (Services_.begin (), Services_.end (), [&svcName] (const ServiceBase_ptr& service) { return service->GetName () == svcName; }); if (pos == Services_.end ()) { qWarning () << Q_FUNC_INFO << "cannot find service" << svcName; return nullptr; } const auto pending = (*pos)->UploadFile (file); if (!pending) { qWarning () << Q_FUNC_INFO << "unable to upload" << file << "to" << svcName; return nullptr; } connect (pending, SIGNAL (fileUploaded (QString, QUrl)), this, SIGNAL (fileUploaded (QString, QUrl))); return pending; } } }
25.053333
89
0.619478
bbc18b7e6cbf92a4660726cc386e7834f0fb3e2d
1,773
cpp
C++
code/mandelbrot_tty/main.cpp
battibass/pf2021
7d370d26a53588c3168b57614e34e0dda70f5bbf
[ "CC-BY-4.0" ]
7
2021-10-20T08:43:46.000Z
2022-03-26T14:18:19.000Z
code/mandelbrot_tty/main.cpp
battibass/pf2021
7d370d26a53588c3168b57614e34e0dda70f5bbf
[ "CC-BY-4.0" ]
null
null
null
code/mandelbrot_tty/main.cpp
battibass/pf2021
7d370d26a53588c3168b57614e34e0dda70f5bbf
[ "CC-BY-4.0" ]
10
2021-10-01T13:49:56.000Z
2022-03-29T10:28:06.000Z
#include <iostream> #include <string> class Complex { double r_; double i_; public: Complex(double r = 0., double i = 0.) : r_{r}, i_{i} { } double real() const { return r_; } double imag() const { return i_; } Complex& operator+=(Complex const& o) { r_ += o.r_; i_ += o.i_; return *this; } Complex& operator*=(Complex const& o) { auto t = r_ * o.r_ - i_ * o.i_; i_ = r_ * o.i_ + i_ * o.r_; r_ = t; return *this; } }; Complex operator-(Complex const& c) { return {-c.real(), -c.imag()}; } Complex operator+(Complex const& left, Complex const& right) { auto result = left; return result += right; } Complex operator-(Complex const& left, Complex const& right) { return left + (-right); } Complex operator*(Complex const& left, Complex const& right) { auto result = left; return result *= right; } double norm2(Complex const& c) { return c.real() * c.real() + c.imag() * c.imag(); } int mandelbrot(Complex const& c) { int i = 0; auto z = c; for (; i != 256 && norm2(z) < 4.; ++i) { z = z * z + c; } return i; } auto to_symbol(int k) { return k < 256 ? ' ' : '*'; } int main() { int const display_width = 100; int const display_height = 48; Complex const top_left{-2.3, 1.}; Complex const lower_right{0.8, -1.}; auto const diff = lower_right - top_left; auto const delta_x = diff.real() / display_width; auto const delta_y = diff.imag() / display_height; for (int row{0}; row != display_height; ++row) { std::string line; for (int column{0}; column != display_width; ++column) { auto k = mandelbrot(top_left + Complex{delta_x * column, delta_y * row}); line.push_back(to_symbol(k)); } std::cout << line << '\n'; } }
17.909091
79
0.585448
bbc1d2621c8dd95ab7076682e99978b9f8e22d8a
8,626
cpp
C++
Tests/DiligentToolsTest/src/RenderStateNotationParser/PipelineStateParserTest.cpp
SebMenozzi/DiligentTools
cf2d8b67df590a93862749051c65310535a2f3cd
[ "Apache-2.0" ]
null
null
null
Tests/DiligentToolsTest/src/RenderStateNotationParser/PipelineStateParserTest.cpp
SebMenozzi/DiligentTools
cf2d8b67df590a93862749051c65310535a2f3cd
[ "Apache-2.0" ]
null
null
null
Tests/DiligentToolsTest/src/RenderStateNotationParser/PipelineStateParserTest.cpp
SebMenozzi/DiligentTools
cf2d8b67df590a93862749051c65310535a2f3cd
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019-2022 Diligent Graphics LLC * * 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. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include "gtest/gtest.h" #include "DRSNLoader.hpp" using namespace Diligent; namespace { TEST(Tools_RenderStateNotationParser, ParsePipelineStateEnums) { DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()}; ASSERT_TRUE(TestEnum<PIPELINE_TYPE>(Allocator, PIPELINE_TYPE_GRAPHICS, PIPELINE_TYPE_LAST)); ASSERT_TRUE(TestBitwiseEnum<SHADER_VARIABLE_FLAGS>(Allocator, SHADER_VARIABLE_FLAG_LAST)); ASSERT_TRUE(TestBitwiseEnum<PIPELINE_SHADING_RATE_FLAGS>(Allocator, PIPELINE_SHADING_RATE_FLAG_LAST)); ASSERT_TRUE(TestBitwiseEnum<SHADER_VARIABLE_FLAGS>(Allocator, SHADER_VARIABLE_FLAG_LAST)); ASSERT_TRUE(TestBitwiseEnum<PSO_CREATE_FLAGS>(Allocator, PSO_CREATE_FLAG_LAST)); } TEST(Tools_RenderStateNotationParser, ParseSampleDesc) { CHECK_STRUCT_SIZE(SampleDesc, 2); DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()}; nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/SampleDesc.json"); SampleDesc DescReference{}; DescReference.Count = 4; DescReference.Quality = 1; SampleDesc Desc{}; ParseRSN(JsonReference, Desc, Allocator); ASSERT_EQ(Desc, DescReference); } TEST(Tools_RenderStateNotationParser, ParseShaderResourceVariableDesc) { CHECK_STRUCT_SIZE(ShaderResourceVariableDesc, 24); DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()}; nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/ShaderResourceVariableDesc.json"); ShaderResourceVariableDesc DescReference{}; DescReference.Name = "TestName"; DescReference.Type = SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC; DescReference.ShaderStages = SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL; DescReference.Flags = SHADER_VARIABLE_FLAG_NO_DYNAMIC_BUFFERS | SHADER_VARIABLE_FLAG_GENERAL_INPUT_ATTACHMENT; ShaderResourceVariableDesc Desc{}; ParseRSN(JsonReference, Desc, Allocator); ASSERT_EQ(Desc, DescReference); } TEST(Tools_RenderStateNotationParser, ParsePipelineResourceLayoutDesc) { CHECK_STRUCT_SIZE(PipelineResourceLayoutDesc, 40); DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()}; nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/PipelineResourceLayoutDesc.json"); constexpr ShaderResourceVariableDesc Variables[] = { {SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "TestName0", SHADER_RESOURCE_VARIABLE_TYPE_STATIC}, {SHADER_TYPE_VERTEX | SHADER_TYPE_PIXEL, "TestName1", SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC}}; constexpr ImmutableSamplerDesc Samplers[] = { ImmutableSamplerDesc{SHADER_TYPE_ALL_RAY_TRACING, "TestName0", {FILTER_TYPE_POINT, FILTER_TYPE_MAXIMUM_POINT, FILTER_TYPE_ANISOTROPIC}}, ImmutableSamplerDesc{SHADER_TYPE_PIXEL, "TestName1", {FILTER_TYPE_COMPARISON_POINT, FILTER_TYPE_COMPARISON_LINEAR, FILTER_TYPE_COMPARISON_ANISOTROPIC}}}; PipelineResourceLayoutDesc DescReference{}; DescReference.DefaultVariableMergeStages = SHADER_TYPE_ALL_GRAPHICS; DescReference.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE; DescReference.Variables = Variables; DescReference.NumVariables = _countof(Variables); DescReference.ImmutableSamplers = Samplers; DescReference.NumImmutableSamplers = _countof(Samplers); PipelineResourceLayoutDesc Desc{}; ParseRSN(JsonReference, Desc, Allocator); ASSERT_EQ(Desc, DescReference); } TEST(Tools_RenderStateNotationParser, ParseGraphicsPipelineDesc) { CHECK_STRUCT_SIZE(GraphicsPipelineDesc, 192); DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()}; nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/GraphicsPipelineDesc.json"); constexpr LayoutElement InputLayoutElemets[] = { LayoutElement{0, 0, 3, VT_FLOAT32}, LayoutElement{1, 0, 4, VT_FLOAT32}}; GraphicsPipelineDesc DescReference{}; DescReference.SampleMask = 1245678; DescReference.PrimitiveTopology = PRIMITIVE_TOPOLOGY_POINT_LIST; DescReference.NumViewports = 2; DescReference.SubpassIndex = 1; DescReference.NodeMask = 1; DescReference.DepthStencilDesc.DepthEnable = false; DescReference.RasterizerDesc.CullMode = CULL_MODE_FRONT; DescReference.ShadingRateFlags = PIPELINE_SHADING_RATE_FLAG_PER_PRIMITIVE | PIPELINE_SHADING_RATE_FLAG_TEXTURE_BASED; DescReference.BlendDesc.RenderTargets[0].BlendEnable = true; DescReference.InputLayout.LayoutElements = InputLayoutElemets; DescReference.InputLayout.NumElements = _countof(InputLayoutElemets); DescReference.DSVFormat = TEX_FORMAT_D32_FLOAT; DescReference.NumRenderTargets = 2; DescReference.RTVFormats[0] = TEX_FORMAT_RGBA8_UNORM; DescReference.RTVFormats[1] = TEX_FORMAT_RG16_FLOAT; DescReference.SmplDesc.Count = 4; DescReference.SmplDesc.Quality = 1; GraphicsPipelineDesc Desc{}; ParseRSN(JsonReference, Desc, Allocator); ASSERT_EQ(Desc, DescReference); } TEST(Tools_RenderStateNotationParser, ParseRayTracingPipelineDesc) { CHECK_STRUCT_SIZE(RayTracingPipelineDesc, 4); DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()}; nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/RayTracingPipelineDesc.json"); RayTracingPipelineDesc DescReference{}; DescReference.MaxRecursionDepth = 7; DescReference.ShaderRecordSize = 4096; RayTracingPipelineDesc Desc{}; ParseRSN(JsonReference, Desc, Allocator); ASSERT_EQ(Desc, DescReference); } TEST(Tools_RenderStateNotationParser, ParsePipelineStateDesc) { CHECK_STRUCT_SIZE(PipelineStateDesc, 64); DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()}; nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/PipelineStateDesc.json"); PipelineStateDesc DescReference{}; DescReference.PipelineType = PIPELINE_TYPE_COMPUTE; DescReference.Name = "TestName"; DescReference.SRBAllocationGranularity = 16; DescReference.ImmediateContextMask = 1; DescReference.ResourceLayout.DefaultVariableType = SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC; PipelineStateDesc Desc{}; ParseRSN(JsonReference, Desc, Allocator); ASSERT_EQ(Desc, DescReference); } TEST(Tools_RenderStateNotationParser, ParseTilePipelineDesc) { CHECK_STRUCT_SIZE(TilePipelineDesc, 18); DynamicLinearAllocator Allocator{DefaultRawMemoryAllocator::GetAllocator()}; nlohmann::json JsonReference = LoadDRSNFromFile("RenderStates/PipelineState/TilePipelineDesc.json"); TilePipelineDesc DescReference{}; DescReference.NumRenderTargets = 2; DescReference.RTVFormats[0] = TEX_FORMAT_RGBA8_UNORM; DescReference.RTVFormats[1] = TEX_FORMAT_RG16_FLOAT; DescReference.SampleCount = 4; TilePipelineDesc Desc{}; ParseRSN(JsonReference, Desc, Allocator); ASSERT_EQ(Desc, DescReference); } } // namespace
41.07619
161
0.761651
bbc21fea637e1879270776e4399ec10b782f2ba7
3,861
hpp
C++
source/Irrlicht/rtc/impl/threadpool.hpp
MagicAtom/irrlicht-ce
b94ea7f97d7d0d3000d5a8c9c7c712debef1e55d
[ "IJG" ]
null
null
null
source/Irrlicht/rtc/impl/threadpool.hpp
MagicAtom/irrlicht-ce
b94ea7f97d7d0d3000d5a8c9c7c712debef1e55d
[ "IJG" ]
null
null
null
source/Irrlicht/rtc/impl/threadpool.hpp
MagicAtom/irrlicht-ce
b94ea7f97d7d0d3000d5a8c9c7c712debef1e55d
[ "IJG" ]
null
null
null
/** * Copyright (c) 2020 Paul-Louis Ageneau * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef RTC_IMPL_THREADPOOL_H #define RTC_IMPL_THREADPOOL_H #include "common.hpp" #include "init.hpp" #include "internals.hpp" #include <chrono> #include <condition_variable> #include <deque> #include <functional> #include <future> #include <memory> #include <mutex> #include <queue> #include <stdexcept> #include <thread> #include <vector> namespace rtc::impl { template <class F, class... Args> using invoke_future_t = std::future<std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>>; class ThreadPool final { public: using clock = std::chrono::steady_clock; static ThreadPool &Instance(); ThreadPool(const ThreadPool &) = delete; ThreadPool &operator=(const ThreadPool &) = delete; ThreadPool(ThreadPool &&) = delete; ThreadPool &operator=(ThreadPool &&) = delete; int count() const; void spawn(int count = 1); void join(); void run(); bool runOne(); template <class F, class... Args> auto enqueue(F &&f, Args &&...args) -> invoke_future_t<F, Args...>; template <class F, class... Args> auto schedule(clock::duration delay, F &&f, Args &&...args) -> invoke_future_t<F, Args...>; template <class F, class... Args> auto schedule(clock::time_point time, F &&f, Args &&...args) -> invoke_future_t<F, Args...>; private: ThreadPool(); ~ThreadPool(); std::function<void()> dequeue(); // returns null function if joining std::vector<std::thread> mWorkers; std::atomic<int> mBusyWorkers = 0; std::atomic<bool> mJoining = false; struct Task { clock::time_point time; std::function<void()> func; bool operator>(const Task &other) const { return time > other.time; } bool operator<(const Task &other) const { return time < other.time; } }; std::priority_queue<Task, std::deque<Task>, std::greater<Task>> mTasks; std::condition_variable mTasksCondition, mWaitingCondition; mutable std::mutex mMutex, mWorkersMutex; }; template <class F, class... Args> auto ThreadPool::enqueue(F &&f, Args &&...args) -> invoke_future_t<F, Args...> { return schedule(clock::now(), std::forward<F>(f), std::forward<Args>(args)...); } template <class F, class... Args> auto ThreadPool::schedule(clock::duration delay, F &&f, Args &&...args) -> invoke_future_t<F, Args...> { return schedule(clock::now() + delay, std::forward<F>(f), std::forward<Args>(args)...); } template <class F, class... Args> auto ThreadPool::schedule(clock::time_point time, F &&f, Args &&...args) -> invoke_future_t<F, Args...> { std::unique_lock lock(mMutex); using R = std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>; auto bound = std::bind(std::forward<F>(f), std::forward<Args>(args)...); auto task = std::make_shared<std::packaged_task<R()>>([bound = std::move(bound)]() mutable { try { return bound(); } catch (const std::exception &e) { PLOG_WARNING << e.what(); throw; } }); std::future<R> result = task->get_future(); mTasks.push({time, [task = std::move(task), token = Init::Instance().token()]() { return (*task)(); }}); mTasksCondition.notify_one(); return result; } } // namespace rtc::impl #endif
30.642857
105
0.690236