hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
fe43ebf51be651d1da0fd64829ecf6a0b1efb7e8
670
cpp
C++
src/MeteringSDK/MCORE/MTypeCasting.cpp
beroset/C12Adapter
593b201db169481245b0673813e19d174560a41e
[ "MIT" ]
9
2016-09-02T17:24:58.000Z
2021-12-14T19:43:48.000Z
src/MeteringSDK/MCORE/MTypeCasting.cpp
beroset/C12Adapter
593b201db169481245b0673813e19d174560a41e
[ "MIT" ]
1
2018-09-06T21:48:42.000Z
2018-09-06T21:48:42.000Z
src/MeteringSDK/MCORE/MTypeCasting.cpp
beroset/C12Adapter
593b201db169481245b0673813e19d174560a41e
[ "MIT" ]
4
2016-09-06T16:54:36.000Z
2021-12-16T16:15:24.000Z
// File MCORE/MTypeCasting.cpp #include "MCOREExtern.h" #include "MObject.h" // included instead of MTypeCasting.h #include "MException.h" M_FUNC M_NORETURN_FUNC void MDoThrowBadConversionUint64(const char* typeName) { MException::Throw(MException::ErrorSoftware, M_CODE_STR_P1(MErrorEnum::BadConversion, M_I("Could not convert 64-bit unsigned integer to '%s'"), typeName)); M_ENSURED_ASSERT(0); } M_FUNC M_NORETURN_FUNC void MDoThrowBadConversionInt64(const char* typeName) { MException::Throw(MException::ErrorSoftware, M_CODE_STR_P1(MErrorEnum::BadConversion, M_I("Could not convert 64-bit signed integer to '%s'"), typeName)); M_ENSURED_ASSERT(0); }
35.263158
158
0.777612
beroset
1cfb31356e49096d53dc216d70e33f3b0575fd5f
3,168
cpp
C++
test/test_harmonic1d.cpp
grasingerm/port-authority
51db6b09d6a1545eafeaf6be037a23d47313c490
[ "MIT" ]
null
null
null
test/test_harmonic1d.cpp
grasingerm/port-authority
51db6b09d6a1545eafeaf6be037a23d47313c490
[ "MIT" ]
null
null
null
test/test_harmonic1d.cpp
grasingerm/port-authority
51db6b09d6a1545eafeaf6be037a23d47313c490
[ "MIT" ]
null
null
null
#include <iostream> #include <cassert> #include <cstdlib> #include <ctime> #include <random> #include "port_authority.hpp" #include "mpi.h" using namespace std; using namespace pauth; int main() { int taskid, numtasks; MPI_Init(nullptr, nullptr); MPI_Comm_size(MPI_COMM_WORLD, &numtasks); MPI_Comm_rank(MPI_COMM_WORLD, &taskid); srand(time(NULL)); const auto delta_max = static_cast<double>( (rand() % 200 + 50) / 100.0 ); const auto spring_const = static_cast<double>( (rand() % 1990 + 10) / 500.0 ); const auto T = static_cast<double>( (rand() % 200000 + 10) / 1000.0 ); const auto x0 = static_cast<double>( (rand() % 100 - 200) / 50.0 ); const unsigned nsteps = 20000000; if (taskid == 0) { cout << "1D Harmonic test started.\n"; cout << '\n'; cout << "delta_max = " << delta_max << '\n'; cout << "k = " << spring_const << '\n'; cout << "T = " << T << '\n'; cout << "x0 = " << x0 << '\n'; cout << '\n'; } const double dx = 0.1; const double kB = 1.0; const molecular_id id = molecular_id::Test1; const size_t N = 1; const size_t D = 1; const double L = 1.0; const metric m = euclidean; const bc boundary = no_bc; const_k_spring_potential pot(spring_const); metropolis sim(id, N, D, L, continuous_trial_move(delta_max), &pot, T, kB, m, boundary, metropolis_acc, hardware_entropy_seed_gen, true); sim.set_positions({x0}, 0); const double u0 = accessors::U(sim); metropolis_suite msuite(sim, 0, 1, info_lvl_flag::QUIET); msuite.add_variable_to_average("x", [](const metropolis &sim) { return sim.positions()(0, 0); }); msuite.add_variable_to_average("x^2", [](const metropolis &sim) { return sim.positions()(0, 0) * sim.positions()(0, 0); }); msuite.add_variable_to_average("U", accessors::U); msuite.add_variable_to_average("delta(x - x0)", [=](const metropolis &sim) { const double x = sim.positions()(0, 0); return (x < x0 + dx && x > x0 - dx) ? 1 : 0; }); msuite.simulate(nsteps); if(taskid == 0) { auto averages = msuite.averages(); const double exp_x = averages["x"]; const double exp_xsq = averages["x^2"]; const double exp_E = averages["U"]; const auto exp_xsq_an = (kB * T / spring_const); const auto exp_E_an = kB * T / 2.0; const auto Z_an = sqrt(2.0 * M_PI * kB * T / spring_const); cout << "exp_x = " << exp_x << '\n'; assert(abs(exp_x) < 5e-2); cout << "exp_xsq = " << exp_xsq << " ?= " << exp_xsq_an << '\n'; assert(abs((exp_xsq - exp_xsq_an) / exp_xsq_an) < 1e-2); cout << "exp_E = " << exp_E << " ?= " << exp_E_an << '\n'; assert(abs((exp_E - exp_E_an) / exp_E_an) < 1e-2); cout << "Z = " << (2.0 * dx * exp(-u0 / (kB * T)) / averages["delta(x - x0)"]) << " ?= " << Z_an << '\n'; assert(abs( ((2.0 * dx * exp(-u0 / (kB * T)) / averages["delta(x - x0)"]) - Z_an) / Z_an ) < 1e-2); cout << "---------------------------------------------\n"; } if(taskid == 0) cout << "1D Harmonic test passed.\n"; MPI_Finalize(); return 0; }
31.68
80
0.561553
grasingerm
e80028ad367f2469b3c6449533f19dc84eb2b828
1,591
cpp
C++
test_package/example.cpp
memsharded/conan-eastl
1c0de6b7f650036224fe4f51e5001f59aa609de0
[ "MIT" ]
null
null
null
test_package/example.cpp
memsharded/conan-eastl
1c0de6b7f650036224fe4f51e5001f59aa609de0
[ "MIT" ]
null
null
null
test_package/example.cpp
memsharded/conan-eastl
1c0de6b7f650036224fe4f51e5001f59aa609de0
[ "MIT" ]
null
null
null
#include <cstdlib> #include <iostream> #include <EASTL/hash_map.h> #include <EASTL/string.h> // EASTL expects us to define these, see allocator.h line 194 void* operator new[](size_t size, const char* /* pName */, int /* flags */, unsigned /* debugFlags */, const char* /* file */, int /* line */) { return malloc(size); } void* operator new[](size_t size, size_t alignment, size_t /* alignmentOffset */, const char* /* pName */, int /* flags */, unsigned /* debugFlags */, const char* /* file */, int /* line */) { // this allocator doesn't support alignment EASTL_ASSERT(alignment <= 8); return malloc(size); } // EASTL also wants us to define this (see string.h line 197) int Vsnprintf8(char8_t* pDestination, size_t n, const char8_t* pFormat, va_list arguments) { #ifdef _MSC_VER return _vsnprintf(pDestination, n, pFormat, arguments); #else return vsnprintf(pDestination, n, pFormat, arguments); #endif } void test_hash_map() { eastl::hash_map<eastl::string, eastl::string> map; map["key1"] = "value1"; map["key2"] = "value2"; EASTL_ASSERT(map.find("key1")->second == "value1"); } void test_string() { eastl::string str; str += "testing "; str += "simple "; str += "string "; str += "concat"; EASTL_ASSERT(str == "testing simple string concat"); str.sprintf("%d", 20); EASTL_ASSERT(str == "20"); } int main() { test_hash_map(); test_string(); return EXIT_SUCCESS; }
27.912281
75
0.59208
memsharded
e802fbd2c9ca1e00f17cf66c860bdb14a403a0e8
1,878
cpp
C++
Camera.cpp
CJT-Jackton/The-Color-of-Tea
d7c79279613bdc04237e8692bcc2cb6918172900
[ "BSD-2-Clause" ]
1
2020-09-15T06:32:08.000Z
2020-09-15T06:32:08.000Z
Camera.cpp
CJT-Jackton/The-Color-of-Tea
d7c79279613bdc04237e8692bcc2cb6918172900
[ "BSD-2-Clause" ]
null
null
null
Camera.cpp
CJT-Jackton/The-Color-of-Tea
d7c79279613bdc04237e8692bcc2cb6918172900
[ "BSD-2-Clause" ]
null
null
null
// // Camera.cpp // // Camera class implementations. // // Author: Jietong Chen // Date: 5/2/2018 // #include <glm/gtc/matrix_transform.hpp> #include "Camera.h" /// // Constructor // // @param position - camera location // @param lookat - lookat point location // @param fov - field of view // @param aspect - aspect ratio // @param near - near clipping plate // @param far - far clipping plate /// Camera::Camera( vec3 position, vec3 lookat, float fov, float aspect, float near, float far ) : position( position ), lookat( lookat ), fov( fov ), aspect( aspect ), znear( near ), zfar( far ) { // default up vector up = vec3( 0.0f, 1.0f, 0.0f ); } /// // Get the viewing transformation matrix of the camera. // // @return the viewing transformation matrix /// mat4 Camera::getViewMat() { // n-axis of camera coordinate vec3 n = normalize( position - lookat ); // u-axis of camera coordinate vec3 u = normalize( cross( up, n ) ); // v-axis of camera coordinate vec3 v = normalize( cross( n, u ) ); return mat4( u.x, v.x, n.x, 0.0f, u.y, v.y, n.y, 0.0f, u.z, v.z, n.z, 0.0f, -dot( u, position ), -dot( v, position ), -dot( n, position ), 1.0f ); } /// // Get the projection matrix of the camera. // // @return the projection matrix /// mat4 Camera::getProjectionMat() { mat4 Projection = mat4( 0.0f ); float tanHalfFov = tan( fov * float( M_PI ) / 360.0f ); Projection[ 0 ][ 0 ] = 1.0f / ( aspect * tanHalfFov ); Projection[ 1 ][ 1 ] = 1.0f / ( tanHalfFov ); Projection[ 2 ][ 3 ] = -1.0f; Projection[ 2 ][ 2 ] = -( zfar + znear ) / ( zfar - znear ); Projection[ 3 ][ 2 ] = -( 2.0f * zfar * znear ) / ( zfar - znear ); return Projection; }
27.217391
80
0.551118
CJT-Jackton
e8046a51eb12bfe61e487c86917358894bf37cc1
31,943
cpp
C++
src/Filesystem/Filesystem.cpp
NerdThings/Ngine
e5c4754d07ec38e727d8baaf7250dbb996cad49e
[ "Apache-2.0" ]
2
2019-05-24T15:20:14.000Z
2019-06-12T11:55:27.000Z
src/Filesystem/Filesystem.cpp
NerdThings/Ngine
e5c4754d07ec38e727d8baaf7250dbb996cad49e
[ "Apache-2.0" ]
23
2019-06-05T12:52:33.000Z
2020-03-11T15:23:00.000Z
src/Filesystem/Filesystem.cpp
NerdThings/Ngine
e5c4754d07ec38e727d8baaf7250dbb996cad49e
[ "Apache-2.0" ]
1
2019-10-02T20:31:12.000Z
2019-10-02T20:31:12.000Z
/********************************************************************************************** * * Ngine - The 2D game engine. * * Copyright (C) 2019 NerdThings * * LICENSE: Apache License 2.0 * View: https://github.com/NerdThings/Ngine/blob/master/LICENSE * **********************************************************************************************/ #include "Filesystem.h" #if defined(_WIN32) #include <Windows.h> #include <shlobj.h> #elif defined(__linux__) #define _GNU_SOURCE #define __USE_GNU #include <unistd.h> #include <limits.h> #include <pwd.h> #include <linux/limits.h> #include <dlfcn.h> #elif defined(__APPLE__) #include <mach-o/dyld.h> #include <dlfcn.h> #include <sys/syslimits.h> #include <unistd.h> #include <pwd.h> #endif #if defined(__linux__) || defined(__APPLE__) #include <unistd.h> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> #endif #include <sstream> namespace NerdThings::Ngine::Filesystem { //////// // Path //////// // Public Constructors Path::Path() { // Mark as improper _HasProperValue = false; } Path::Path(const std::string &pathString_) { // Set internal path _InternalPath = pathString_; // Check path __CorrectPath(); } Path::Path(const std::string &path_, const std::string &pathB_) { // Set internal path _InternalPath = path_ + __GetJoinChar() + pathB_; // Check path __CorrectPath(); } Path::Path(const Path& path_, const Path& pathB_) { // Set internal path _InternalPath = path_._InternalPath + __GetJoinChar() + pathB_._InternalPath; // Check path __CorrectPath(); } Path::Path(const Path &path_, const std::string &pathB_) { // Set internal path _InternalPath = path_._InternalPath + __GetJoinChar() + pathB_; // Check path __CorrectPath(); } Path::Path(const std::string &path_, const Path &pathB_) { // Set internal path _InternalPath = path_ + __GetJoinChar() + pathB_._InternalPath; // Check path __CorrectPath(); } // Public Methods Path Path::GetAbsolute() const { // If we are already absolute, ignore if (IsAbsolute()) return *this; // Get relative to executable dir return GetExecutableDirectory() / *this; } Path Path::GetAppDataDirectory() { #if defined(PLATFORM_DESKTOP) #if defined(_WIN32) // %APPDATA% return std::string(getenv("APPDATA")); #elif defined(__linux__) // Home local share return __GetHome() + ".local/share"; #elif defined(__APPLE__) // Application Support return __GetHome() + "/Library/Application Support" #endif #elif defined(PLATFORM_UWP) // Windows specific path auto roamingAppData = Windows::Storage::ApplicationData::Current->RoamingFolder->Path->ToString(); std::wstring tmp(roamingAppData->Begin()); std::string path(tmp.begin(), tmp.end()); return path; #endif } Path Path::GetExecutableDirectory() { #if defined(PLATFORM_UWP) auto installed = Windows::ApplicationModel::Package::Current->InstalledLocation->Path; std::wstring tmp(installed->Begin()); std::string installedPath(tmp.begin(), tmp.end()); return installedPath; #else return GetExecutablePath().GetParent(); #endif } Path Path::GetExecutablePath() { // https://github.com/cginternals/cpplocate/blob/master/source/liblocate/source/liblocate.c#L39 // I trust this works as there are no issues about it... #if defined(_WIN32) && defined(PLATFORM_DESKTOP) char exePath[MAX_PATH]; unsigned int len = GetModuleFileNameA(GetModuleHandleA(nullptr), exePath, MAX_PATH); if (len == 0) return Path(""); return Path(std::string(exePath)); #elif defined(_WIN32) && defined(PLATFORM_UWP) throw std::runtime_error("Cannot get executable path of UWP app, get executable directory instead."); #elif defined(__linux__) char exePath[PATH_MAX]; int len = readlink("/proc/self/exe", exePath, PATH_MAX); if (len <= 0 || len == PATH_MAX) return Path(""); return Path(std::string(exePath)); #elif defined(__APPLE__) char exePath[PATH_MAX]; unsigned int len = (unsigned int)PATH_MAX; if (_NSGetExecutablePath(exePath, &len) == 0) { char * realPath = realpath(exePath, 0x0); if (realPath == 0x0) { return Path(""); } auto pathStr = std::string(realPath); free(realPath); return Path(pathStr); } else { char * intermediatePath = (char *)malloc(sizeof(char) * len); if (_NSGetExecutablePath(intermediatePath, &len) != 0) { free(intermediatePath); return Path(""); } char * realPath = realpath(intermediatePath, 0x0); free(intermediatePath); if (realPath == 0x0) { return Path(""); } auto pathStr = std::string(realPath); free(realPath); return Path(pathStr); } #else // Returns blank, this cannot be used return Path(""); #endif } std::string Path::GetFileExtension() const { // Get path string auto path = GetString(); // Get file extension auto dot = path.find_last_of('.'); auto lastSlash = path.find_last_of(__GetJoinChar()); if (std::string::npos != dot) { if (dot > lastSlash) { return path.substr(dot + 1); } } return ""; } std::string Path::GetObjectName() const { // Get path string auto nameTemp = GetString(); // Search for the last directory slash auto fSlash = nameTemp.find_last_of(__GetJoinChar()); if (std::string::npos != fSlash) { nameTemp.erase(0, fSlash + 1); } // Remove the file extension auto dot = nameTemp.find_last_of('.'); if (std::string::npos != dot) { nameTemp.erase(dot); } return nameTemp; } Path Path::GetParent() const { auto lastSlash = _InternalPath.find_last_of(__GetJoinChar()); if (std::string::npos != lastSlash) return Path(_InternalPath.substr(0, lastSlash)); else return Path(); } Path Path::GetRelativeTo(const Path &base_) const { // The base must be absolute auto basePath = base_; if (!basePath.IsAbsolute()) basePath = basePath.GetAbsolute(); // Base must be a directory if (basePath.GetResourceType() != TYPE_DIRECTORY) throw std::runtime_error("Base must be a directory."); // I must be absolute if (!IsAbsolute()) throw std::runtime_error("Path must be absolute."); // Find common path auto commonPathPos = 0; auto baseStr = basePath.GetString(); auto str = GetString(); for (auto i = 0; i < baseStr.size() && i < str.size(); i++) { if (baseStr[i] != str[i]) { break; } commonPathPos++; } // Catches things like different drives if (commonPathPos == 0) { throw std::runtime_error("Cannot get relative path to files on different drives."); } // Remove from both strings baseStr.erase(0, commonPathPos); str.erase(0, commonPathPos); // Remove initial slash if left if (str.size() > 0) { if (str[0] == __GetJoinChar()) { str.erase(0, 1); } } // Prepend ../ for all extra parts int subdirs = (int)std::count(baseStr.begin(), baseStr.end(), __GetJoinChar()); // Add one more if it doesn't end in a slash if (baseStr.size() > 0) { if (baseStr[baseStr.size() - 1] != __GetJoinChar()) { subdirs += 1; } } for (auto i = 0; i < subdirs; i++) { str = std::string("..") + __GetJoinChar() + str; } // Return, we're done return str; } ResourceType Path::GetResourceType() const { #if defined(_WIN32) DWORD dwAttrib = GetFileAttributesA(GetString().c_str()); if (dwAttrib != INVALID_FILE_ATTRIBUTES) { return dwAttrib & FILE_ATTRIBUTE_DIRECTORY ? TYPE_DIRECTORY : TYPE_FILE; } #elif defined(__linux__) || defined(__APPLE__) // Get path info struct stat path_stat; stat(GetString().c_str(), &path_stat); if (S_ISREG(path_stat.st_mode)) return TYPE_FILE; else if (S_ISDIR(path_stat.st_mode)) return TYPE_DIRECTORY; #endif return TYPE_INVALID; } std::string Path::GetString() const { return _InternalPath; } std::string Path::GetStringNoExtension() const { auto lastDot = _InternalPath.find_last_of('.'); auto lastSlash = _InternalPath.find_last_of(__GetJoinChar()); if (std::string::npos != lastDot) { if (std::string::npos != lastSlash) { if (lastDot > lastSlash) { return _InternalPath.substr(0, lastDot); } } else { return _InternalPath.substr(0, lastDot); } } return _InternalPath; } Path Path::GetWorkingDirectory() { #if defined(_WIN32) // Create buffer DWORD bufferLen = MAX_PATH; auto buffer = new char[MAX_PATH + 1]; // Get current dir GetCurrentDirectoryA(MAX_PATH + 1, buffer); // Null terminate buffer[MAX_PATH] = 0; // Convert to string std::string string(buffer); // Delete buffer delete[] buffer; // Return return Path(string); #elif defined(__linux) || defined(__APPLE__) // Create buffer auto buffer = new char[PATH_MAX]; // Get working dir if (getcwd(buffer, PATH_MAX) == nullptr) throw std::runtime_error("Unable to determine working directory."); // Convert to string std::string string(buffer); // Delete buffer delete[] buffer; // Return return Path(string); #endif } bool Path::IsAbsolute() const { #if defined(_WIN32) // Test if we have (*):\ at the start if (_InternalPath.size() > 3) return _InternalPath[1] == ':' && _InternalPath[2] == '\\'; #elif defined(__linux__) || defined(__APPLE__) // Test we have an initial slash if (_InternalPath.size() > 0) return _InternalPath[0] == '/'; #endif return false; } Path Path::Join(const std::string &pathA_, const std::string &pathB_) { return Path(pathA_, pathB_); } Path Path::Join(const Path &pathA_, const Path &pathB_) { return Path(pathA_, pathB_); } bool Path::Valid() const { return _HasProperValue; } // Operators Path operator/(const std::string &path_, const std::string &pathB_) { return Path(path_, pathB_); } Path operator/(const Path &path_, const Path &pathB_) { return Path(path_, pathB_); } Path operator/(const std::string &path_, const Path &pathB_) { return Path(path_, pathB_); } Path operator/(const Path &path_, const std::string &pathB_) { return Path(path_, pathB_); } void Path::operator/=(const Path &pathB_) { // Set internal path _InternalPath = _InternalPath + __GetJoinChar() + pathB_._InternalPath; // Check path __CorrectPath(); } void Path::operator/=(const std::string &pathB_) { // Set internal path _InternalPath = _InternalPath + __GetJoinChar() + pathB_; // Check path __CorrectPath(); } Path::operator std::string() const { return _InternalPath; } // Private Methods std::string Path::__CleanPathString(const std::string &str_) { #if defined(_WIN32) && defined(PLATFORM_DESKTOP) // TODO: Another way to fix Unicode path names. // TODO: Basically Ngine needs better Unicode support in general return str_; // // Get path length // auto len = GetShortPathNameA(str_.c_str(), nullptr, 0); // // // Check length // if (len == 0) { // auto e = GetLastError(); // if (e == 0x2 || e == 0x3) // File not found/Path not found, cannot clean it // return str_; // else throw std::runtime_error("GetShortPathNameA error."); // } // // // Allocate buffer // auto buffer = new char[len]; // // // Get path // len = GetShortPathNameA(str_.c_str(), buffer, len); // // // Check length // if (len == 0) { // auto e = GetLastError(); // if (e == 0x2 || e == 0x3) // File not found/Path not found, cannot clean it // return str_; // else throw std::runtime_error("GetShortPathNameA error."); // } // // // Convert to string // auto string = std::string(buffer); // // // Delete buffer // delete[] buffer; // // return string; #endif return str_; } void Path::__CorrectPath() { // Clean path _InternalPath = __CleanPathString(_InternalPath); // Search for empty string if (_InternalPath.empty()) { // Not a correct value _HasProperValue = false; return; } // Look for any non-whitespace chars bool hasNonWhitespace = false; for (auto c : _InternalPath) { if (c != ' ') { hasNonWhitespace = true; break; } } if (!hasNonWhitespace) { // Not a correct value _HasProperValue = false; return; } // Look for notation foreign to this OS if (__GetJoinChar() != '\\') { std::replace(_InternalPath.begin(), _InternalPath.end(), '\\', __GetJoinChar()); } if (__GetJoinChar() != '/') { std::replace(_InternalPath.begin(), _InternalPath.end(), '/', __GetJoinChar()); } // Is valid _HasProperValue = true; } std::string Path::__GetHome() { #if defined(__linux__) || defined(__APPLE__) int uid = getuid(); // Use HOME environment variable if not run as root const char *homeVar = std::getenv("HOME"); if (uid != 0 && homeVar) return std::string(homeVar); // Use psswd home struct passwd *pw = getpwuid(uid); return std::string(pw->pw_dir); #endif return ""; } char Path::__GetJoinChar() { // TODO: See if there are any more variations #if defined(_WIN32) return '\\'; #else return '/'; #endif } //////// // FilesystemObject //////// // Public Methods void FilesystemObject::Move(const Path &newPath_) { // Move file rename(ObjectPath.GetString().c_str(), newPath_.GetString().c_str()); } void FilesystemObject::Rename(const std::string &newName_) { // Rename Move(ObjectPath / newName_); } std::string FilesystemObject::GetObjectName() const { return ObjectPath.GetObjectName(); } Path FilesystemObject::GetObjectPath() const { return ObjectPath; } // Protected Constructors FilesystemObject::FilesystemObject(const Path &path_) : ObjectPath(path_) {} //////// // File //////// // InternalFileHandler Destructor File::InternalFileHandler::~InternalFileHandler() { if (InternalHandle != nullptr) fclose(InternalHandle); InternalHandle = nullptr; } // Public Constructor(s) File::File() : FilesystemObject(Path()) { // Create an empty handler _InternalHandle = std::make_shared<InternalFileHandler>(); } File::File(const Path &path_) : FilesystemObject(path_) { // Check path is valid if (!path_.Valid()) throw std::runtime_error("File must be given a valid path."); // Create an empty handler _InternalHandle = std::make_shared<InternalFileHandler>(); } // Destructor File::~File() { // Close file in case it isnt gone already Close(); } // Public Methods void File::Close() { // Close file if (_InternalHandle->InternalHandle != nullptr) { fclose(_InternalHandle->InternalHandle); _InternalHandle->InternalHandle = nullptr; } // Set mode _InternalOpenMode = MODE_NONE; } File File::CreateNewFile(const Path &path_, bool leaveOpen_, bool binary_) { File f(path_); f.Open(MODE_WRITE, binary_); if (!leaveOpen_) f.Close(); return f; } bool File::Delete() { // Ensure that we are closed Close(); // Remove from filesystem return remove(ObjectPath.GetString().c_str()) == 0; } bool File::Exists() const { // If we are open, we know we exist if (IsOpen()) return true; // Using C apis so that it is cross platform FILE *file = fopen(ObjectPath.GetString().c_str(), "r"); if (file != nullptr) { fclose(file); return true; } return false; } FileOpenMode File::GetCurrentMode() const { return _InternalOpenMode; } File File::GetFile(const Path &path_) { return File(path_); } std::string File::GetFileExtension() const { return ObjectPath.GetFileExtension(); } FILE *File::GetFileHandle() const { if (!IsOpen()) { ConsoleMessage("Cannot get handle of file that is not open.", "WARN", "File"); return nullptr; } return _InternalHandle->InternalHandle; } int File::GetSize() const { if (!IsOpen()) { ConsoleMessage("Cannot determine size of file that is not open.", "WARN", "File"); return 0; } fseek(_InternalHandle->InternalHandle, 0, SEEK_END); auto s = ftell(_InternalHandle->InternalHandle); fseek(_InternalHandle->InternalHandle, 0, SEEK_SET); return s; } bool File::IsOpen() const { if (_InternalHandle == nullptr) return false; return _InternalHandle->InternalHandle != nullptr; } bool File::Open(FileOpenMode mode_, bool binary_) { // Check validity of path if (!ObjectPath.Valid()) throw std::runtime_error("This file's path is invalid"); // Open with selected mode switch(mode_) { case MODE_READ: // Check this is actually a file if (ObjectPath.GetResourceType() != TYPE_FILE) throw std::runtime_error("This path does not point to a file."); // Open binary file for read _InternalHandle->InternalHandle = fopen(ObjectPath.GetString().c_str(), binary_ ? "rb" : "r"); // Set mode _InternalOpenMode = mode_; break; case MODE_WRITE: // Open binary file for write _InternalHandle->InternalHandle = fopen(ObjectPath.GetString().c_str(), binary_ ? "wb" : "w"); // Set mode _InternalOpenMode = mode_; break; case MODE_APPEND: // Open binary file for append _InternalHandle->InternalHandle = fopen(ObjectPath.GetString().c_str(), binary_ ? "ab" : "a"); // Set mode _InternalOpenMode = mode_; break; case MODE_READ_WRITE: // Open binary file for read and write _InternalHandle->InternalHandle = fopen(ObjectPath.GetString().c_str(), binary_ ? "w+b" : "w+"); // Set mode _InternalOpenMode = mode_; break; case MODE_READ_APPEND: // Open binary file for read and append _InternalHandle->InternalHandle = fopen(ObjectPath.GetString().c_str(), binary_ ? "a+b" : "a+"); // Set mode _InternalOpenMode = mode_; break; default: ConsoleMessage("File mode not supported.", "WARN", "File"); // Set mode _InternalOpenMode = MODE_NONE; break; } // Return success return IsOpen(); } unsigned char *File::ReadBytes(int size_, int offset_) { if (!IsOpen()) throw std::runtime_error("Cannot read from closed file."); // Check for our mode if (_InternalOpenMode != MODE_READ && _InternalOpenMode != MODE_READ_WRITE && _InternalOpenMode != MODE_READ_APPEND) throw std::runtime_error("File not opened for reading."); // Determine file size if size is -1 auto filesize_ = GetSize(); if (size_ == -1) { size_ = filesize_; } if (size_ <= 0) { throw std::runtime_error("Invalid read size."); } if (offset_ >= filesize_ || offset_ < 0) { throw std::runtime_error("Invalid offset."); } if (size_ + offset_ > filesize_) { throw std::runtime_error("Data out of bounds."); } // Seek to the offset fseek(_InternalHandle->InternalHandle, offset_, SEEK_SET); // Read bytes to array auto *buffer = new unsigned char[size_]; fread(buffer, size_, 1, _InternalHandle->InternalHandle); // Return data return buffer; } std::string File::ReadString(int size_, int offset_) { // Check we're open if (!IsOpen()) throw std::runtime_error("Cannot read from closed file."); // Check for our mode if (_InternalOpenMode != MODE_READ && _InternalOpenMode != MODE_READ_WRITE && _InternalOpenMode != MODE_READ_APPEND) throw std::runtime_error("File not opened for reading."); // Determine file size if size is -1 auto filesize_ = GetSize(); if (size_ == -1) { size_ = filesize_; } if (size_ <= 0) { throw std::runtime_error("Invalid read size."); } if (offset_ >= filesize_ || offset_ < 0) { throw std::runtime_error("Invalid offset."); } if (size_ + offset_ > filesize_) { throw std::runtime_error("Data out of bounds."); } // Seek to the offset fseek(_InternalHandle->InternalHandle, offset_, SEEK_SET); // Read to c string auto buffer = new char[size_ + 1]; int r = fread(buffer, 1, size_, _InternalHandle->InternalHandle); // Null-terminate buffer buffer[r] = '\0'; // Convert to string auto str = std::string(buffer); // Delete buffer delete[] buffer; return str; } bool File::WriteBytes(unsigned char *data_, int size_) { // Check we're open if (!IsOpen()) throw std::runtime_error("Cannot write to a closed file."); // Check for our mode if (_InternalOpenMode != MODE_WRITE && _InternalOpenMode != MODE_APPEND && _InternalOpenMode != MODE_READ_WRITE && _InternalOpenMode != MODE_READ_APPEND) throw std::runtime_error("File not opened for writing."); // Write return fwrite(data_, 1, size_, _InternalHandle->InternalHandle) == 1; } bool File::WriteString(const std::string &string_) { // Check we're open if (!IsOpen()) throw std::runtime_error("Cannot write to closed file."); // Check for our mode if (_InternalOpenMode != MODE_WRITE && _InternalOpenMode != MODE_APPEND && _InternalOpenMode != MODE_READ_WRITE && _InternalOpenMode != MODE_READ_APPEND) throw std::runtime_error("File not opened for writing."); // Write string return fputs(string_.c_str(), _InternalHandle->InternalHandle) != EOF; } //////// // Directory //////// Directory::Directory() : FilesystemObject(Path()) {} Directory::Directory(const Path &path_) : FilesystemObject(path_) { // Check for valid path if (!path_.Valid()) throw std::runtime_error("Directory must be given a valid path."); } bool Directory::Create() { auto success = false; #if defined(_WIN32) // Create directory success = CreateDirectoryA(GetObjectPath().GetString().c_str(), nullptr) != 0; #elif defined(__linux__) || defined(__APPLE__) // Create directory success = mkdir(GetObjectPath().GetString().c_str(), 0777) == 0; #endif return success; } std::pair<bool, Directory> Directory::Create(const Path &path_) { auto dir = Directory(path_); return {dir.Create(), dir}; } bool Directory::Delete() { // Check __ThrowAccessErrors(); #if defined(_WIN32) // Try to delete (not recursive) auto del = RemoveDirectoryA(ObjectPath.GetString().c_str()); return del != 0; #elif defined(__linux__) || defined(__APPLE__) return remove(ObjectPath.GetString().c_str()) == 0; #endif return false; } bool Directory::DeleteRecursive() { // Check __ThrowAccessErrors(); // Success tracker auto success = true; // Delete my own files for (auto file : GetFiles()) { if (!file.Delete()) { success = false; break; } } // Stop if we find an issue if (!success) return false; // Get directories auto dirs = GetDirectories(); // Delete child directories for (auto dir : dirs) { if (!dir.DeleteRecursive()) { success = false; break; } } // Stop if we find an issue if (!success) return false; // Delete self success = Delete(); // Return return success; } bool Directory::Exists() const { #if defined(_WIN32) // https://stackoverflow.com/a/6218445 // Get attributes for directory DWORD dwAttrib = GetFileAttributesA(ObjectPath.GetString().c_str()); return (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); #elif defined(__linux__) || defined(__APPLE__) // Test opening of file DIR *dir = opendir(ObjectPath.GetString().c_str()); if (dir) { closedir(dir); return true; } return false; #endif return false; } Directory Directory::GetAppDataDirectory() { return Directory(Path::GetAppDataDirectory()); } std::vector<Directory> Directory::GetDirectories() const { // Check __ThrowAccessErrors(); // Directories vector auto dirs = std::vector<Directory>(); #if defined(_WIN32) // Find first directory WIN32_FIND_DATAA FindFileData; HANDLE hFind = FindFirstFileA((ObjectPath.GetString() + "\\*").c_str(), &FindFileData); // Check exists if (hFind == INVALID_HANDLE_VALUE) { throw std::runtime_error("Invalid directory."); } // Search for directories do { if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { auto dirName = FindFileData.cFileName; // Avoids . and .. directories if (strcmp(dirName, ".") != 0 && strcmp(dirName, "..") != 0) dirs.push_back(Directory(Path(ObjectPath, dirName))); } } while (FindNextFileA(hFind, &FindFileData) != 0); // Close search FindClose(hFind); #elif defined(__linux__) || defined(__APPLE__) // Variables DIR *dir; dirent *entry; // Open dir dir = opendir(ObjectPath.GetString().c_str()); // Test open if (!dir) throw std::runtime_error("Cannot open directory."); // Read all directories while ((entry = readdir(dir)) != nullptr) { if (entry->d_type == DT_DIR) { if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) dirs.push_back(Directory(Path(ObjectPath, entry->d_name))); } } // Close directory closedir(dir); #endif return dirs; } std::vector<File> Directory::GetFiles() const { // Check __ThrowAccessErrors(); // Files vector auto files = std::vector<File>(); #if defined(_WIN32) // Find the first file in the directory WIN32_FIND_DATAA FindFileData; HANDLE hFind = FindFirstFileA((ObjectPath.GetString() + "\\*").c_str(), &FindFileData); // Check it exists if (hFind == INVALID_HANDLE_VALUE) { auto err = GetLastError(); throw std::runtime_error("Invalid directory."); } // Get all files do { if (!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { auto filename = FindFileData.cFileName; files.push_back(File(Path(ObjectPath, filename))); } } while (FindNextFileA(hFind, &FindFileData) != 0); // Close search FindClose(hFind); #elif defined(__linux__) || defined(__APPLE__) // Variables DIR *dir; dirent *entry; // Open dir dir = opendir(ObjectPath.GetString().c_str()); // Test open if (!dir) throw std::runtime_error("Cannot open directory."); // Read all directories while ((entry = readdir(dir)) != nullptr) { if (entry->d_type != DT_DIR) { files.push_back(File(Path(ObjectPath, entry->d_name))); } } // Close directory closedir(dir); #endif return files; } std::vector<File> Directory::GetFilesRecursive() const { // Check __ThrowAccessErrors(); // Keep track of all files auto files = std::vector<File>(); // Grab my files auto myFiles = GetFiles(); files.insert(files.end(), myFiles.begin(), myFiles.end()); // Get all descendant directories auto dirs = GetDirectories(); for (auto dir : dirs) { auto dirFiles = dir.GetFilesRecursive(); files.insert(files.end(), dirFiles.begin(), dirFiles.end()); } return files; } Directory Directory::GetDirectory(const Path &path_) { return Directory(path_); } Directory Directory::GetExecutableDirectory() { return Directory(Path::GetExecutableDirectory()); } Directory Directory::GetWorkingDirectory() { return Directory(Path::GetWorkingDirectory()); } // Private Fields void Directory::__ThrowAccessErrors() const { // Check exists if (!Exists()) throw std::runtime_error("This directory does not exist."); // Check this is actually a directory if (GetObjectPath().GetResourceType() != TYPE_DIRECTORY) throw std::runtime_error("This path does not point to a directory."); } }
28.243148
134
0.556648
NerdThings
e809d18d381bc7627564d835d0abda51c14e182e
1,578
cpp
C++
Store/XamlWin2D/App.cpp
moutend/cppwinrt
737cbbb11fe56e4d94ff9d84a44aa72e0689016b
[ "MIT" ]
83
2017-11-15T22:51:43.000Z
2022-03-01T09:54:00.000Z
Store/XamlWin2D/App.cpp
moutend/cppwinrt
737cbbb11fe56e4d94ff9d84a44aa72e0689016b
[ "MIT" ]
1
2017-11-13T03:14:01.000Z
2017-11-14T18:01:06.000Z
Store/XamlWin2D/App.cpp
moutend/cppwinrt
737cbbb11fe56e4d94ff9d84a44aa72e0689016b
[ "MIT" ]
24
2017-11-16T22:01:41.000Z
2021-08-04T09:27:46.000Z
#include "pch.h" using namespace winrt; using namespace Windows::ApplicationModel::Activation; using namespace Windows::Foundation; using namespace Windows::Foundation::Numerics; using namespace Windows::UI; using namespace Windows::UI::Xaml; using namespace Microsoft::Graphics::Canvas; using namespace Microsoft::Graphics::Canvas::Text; using namespace Microsoft::Graphics::Canvas::UI::Xaml; struct App : ApplicationT<App> { void OnLaunched(LaunchActivatedEventArgs const &) { CanvasTextFormat format; format.HorizontalAlignment(CanvasHorizontalAlignment::Center); format.VerticalAlignment(CanvasVerticalAlignment::Center); format.FontSize(72.0f); format.FontFamily(L"Segoe UI Semibold"); CanvasControl control; control.Draw([=](CanvasControl const& sender, CanvasDrawEventArgs const& args) { float2 size = sender.Size(); float2 center{ size.x / 2.0f, size.y / 2.0f }; Rect bounds{ 0.0f, 0.0f, size.x, size.y }; CanvasDrawingSession session = args.DrawingSession(); session.FillEllipse(center, center.x - 50.0f, center.y - 50.0f, Colors::DarkSlateGray()); session.DrawText(L"Win2D with\nC++/WinRT!", bounds, Colors::Orange(), format); }); Window window = Window::Current(); window.Content(control); window.Activate(); } }; int __stdcall wWinMain(HINSTANCE, HINSTANCE, PWSTR, int) { Application::Start([](auto &&) { make<App>(); }); }
32.204082
102
0.646388
moutend
e80e829eed92f0153300cb9a252f84846b85801d
1,561
cpp
C++
c/src/algorithm/sunday.cpp
jc1995wade/dwadelib
06fa17e4687f6a1cd8503d5804c49ca924f9cfb7
[ "Apache-2.0" ]
2
2020-04-15T15:04:21.000Z
2022-03-30T06:22:00.000Z
c/src/algorithm/sunday.cpp
jc1995wade/dwadelib
06fa17e4687f6a1cd8503d5804c49ca924f9cfb7
[ "Apache-2.0" ]
null
null
null
c/src/algorithm/sunday.cpp
jc1995wade/dwadelib
06fa17e4687f6a1cd8503d5804c49ca924f9cfb7
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <string.h> int * getStep(int *step, char *a, char *b) { int i, sublen; for (i=0; i<256; i++) { step[i] = strlen(b) + 1; } sublen = strlen(b); for (i=0; i<sublen; i++) { step[b[i]] = sublen - i; } return step; } int sundaySearch(char *mainstr, char *substr, int *step) { int i=0,j=0; int temp; int mainlen=strlen(mainstr); int sublen=strlen(substr); while (i<mainlen){ temp = i; while (j<sublen){ if (mainstr[i]==substr[j]){ i++; j++; continue; } else { i = temp + step[mainstr[temp+sublen]]; if (i+sublen>mainlen) return -1; j=0; break; } } if (j==sublen) return temp; } } int main(int argc, char *argv[]) { int ret; char a[]="LESSONS TEARNED IN SOFTWARE TE"; char b[]="SOFTWsdjfARE"; int step[256]; FILE *fp = NULL; char *fret = NULL; int i = 0; char line[1024]; access(argv[1], F_OK|W_OK); printf("argv[1]=%s\n", argv[1]); fp = fopen(argv[1], "r"); if (NULL == fp) { printf("Error opening file.\n"); return -1; } do { memset(line, 0, sizeof(line)); fret = fgets(line, sizeof(line), fp); printf("%d %s", i++, line); } while(fret); getStep(step, a, b); ret = sundaySearch(a, b, step); printf("ret=%d\n", ret); fclose(fp); return 0; }
19.036585
56
0.497758
jc1995wade
e81ec3c4d0aeb319af81acb7fd418a3da15970d9
9,666
cpp
C++
examples/rapidxml_example.cpp
zlecky/gamecell
309c4e094ed214f79183429e2d2ae9a1464f9b45
[ "MIT" ]
null
null
null
examples/rapidxml_example.cpp
zlecky/gamecell
309c4e094ed214f79183429e2d2ae9a1464f9b45
[ "MIT" ]
null
null
null
examples/rapidxml_example.cpp
zlecky/gamecell
309c4e094ed214f79183429e2d2ae9a1464f9b45
[ "MIT" ]
null
null
null
#include <string> #include <fstream> #include <iostream> #include <string> #include <cmath> #include "rapidxml/rapidxml.hpp" #include "rapidxml/rapidxml_utils.hpp" #include "rapidxml/rapidxml_print.hpp" namespace { void write_doc_to_xml(const std::string& file, rapidxml::xml_document<>& doc) { // write it into xml file. std::string content; rapidxml::print(std::back_inserter(content), doc, 0); std::cout << content << std::endl; std::fstream out(file, std::ios::out | std::ios::trunc); out << content; out.close(); } void create_xml(const std::string& file) { rapidxml::xml_document<> doc; // declaration node by "node_declaration". { auto declaration = doc.allocate_node(rapidxml::node_declaration); declaration->append_attribute(doc.allocate_attribute("version", "1.0")); declaration->append_attribute(doc.allocate_attribute("encoding", "utf-8")); doc.append_node(declaration); } // declaration node by "node_pi" { auto declaration = doc.allocate_node(rapidxml::node_pi, doc.allocate_string(R"(xml version="1.0" encoding="utf-8")")); doc.append_node(declaration); } // node comment { auto comment = doc.allocate_node(rapidxml::node_comment, nullptr, "RapidXml很好用哟!"); doc.append_node(comment); } // node element called "root" auto root = doc.allocate_node(rapidxml::node_element, "config"); doc.append_node(root); // node element called "srv" auto srv = doc.allocate_node(rapidxml::node_element, "srv"); { // node comment of "srv" { auto comment = doc.allocate_node(rapidxml::node_comment, nullptr, "服务器配置"); srv->append_node(comment); } // node element called "item" without value { auto item = doc.allocate_node(rapidxml::node_element, "item"); item->append_attribute(doc.allocate_attribute("id", "1")); item->append_attribute(doc.allocate_attribute("ip", "127.0.0.1")); item->append_attribute(doc.allocate_attribute("port", "8081")); srv->append_node(item); } // node element called "item" with value { auto item = doc.allocate_node(rapidxml::node_element, "item", "2"); item->append_attribute(doc.allocate_attribute("id", "2")); item->append_attribute(doc.allocate_attribute("ip", "127.0.0.1")); item->append_attribute(doc.allocate_attribute("port", "8082")); srv->append_node(item); } // the right way to append attribute in loops for (size_t i = 3; i <= 10; ++i) { auto item = doc.allocate_node(rapidxml::node_element, "item", nullptr); auto id_attr_val = doc.allocate_string(std::to_string(i).data()); auto port_attr_val = doc.allocate_string(std::to_string(i + 8080).data()); item->append_attribute(doc.allocate_attribute("id", id_attr_val)); item->append_attribute(doc.allocate_attribute("ip", "127.0.0.1")); item->append_attribute(doc.allocate_attribute("port", port_attr_val)); srv->append_node(item); } // The following way is wrong, because the ownership of strings. As follows: // Nodes and attributes produced by RapidXml do not own their name and value strings. // They merely hold the pointers to them. // Care must be taken to ensure that lifetime of the string passed is at least as long as lifetime of the node/attribute. // The easiest way to achieve it is to allocate the string from memory_pool owned by the document. // Use memory_pool::allocate_string() function for this purpose. // It's done this way for speed, but this feels like an car crash waiting to happen. /* for (size_t i = 11; i <= 12; ++i) { auto item = doc.allocate_node(rapidxml::node_element, "item", nullptr); item->append_attribute(doc.allocate_attribute("id", std::to_string(i).data())); item->append_attribute(doc.allocate_attribute("ip", "127.0.0.1")); item->append_attribute(doc.allocate_attribute("port", std::to_string(i + 8080).data())); srv->append_node(item); } */ } // append node element "srv" to "config" root->append_node(srv); write_doc_to_xml(file, doc); } void traverse_doc(rapidxml::xml_document<>& doc) { // traverse doc, then print auto config = doc.first_node("config"); for (auto srv = config->first_node("srv"); srv != nullptr; srv = srv->next_sibling()) { for (auto item = srv->first_node("item"); item != nullptr; item = item->next_sibling()) { std::cout << "<" << item->name() << " "; for (auto attr = item->first_attribute(); attr != nullptr; attr = attr->next_attribute()) { std::cout << attr->name() << "=\"" << attr->value() << "\" "; } if (item->first_node() != nullptr) { std::cout << ">" << item->value() << "</" << item->name() << ">"; } else { std::cout << "/>"; } std::cout << std::endl; } } } void read_xml_by_file(const std::string& file) { rapidxml::file<> fd(file.data()); rapidxml::xml_document<> doc; doc.parse<0>(fd.data()); traverse_doc(doc); } void read_xml_by_stream(const std::string& file) { std::ifstream in(file, std::ios::in); char buf[2048] = {0}; in.read(buf, 2048); rapidxml::xml_document<> doc; doc.parse<0>(buf); traverse_doc(doc); } void modify_xml_node_attr(const std::string& file) { rapidxml::file<> fd(file.data()); rapidxml::xml_document<> doc; doc.parse<rapidxml::parse_no_data_nodes>(fd.data()); auto root = doc.first_node(); auto srv = root->first_node("srv"); for (auto item = srv->first_node("item"); item != nullptr; item = item->next_sibling()) { auto id = item->first_attribute("id"); if (id != nullptr) { if (2 == std::strtol(id->value(), nullptr, 10)) { item->value("Yeah, find it!"); auto ip = item->first_attribute("ip"); if (ip != nullptr) { ip->value("192.168.1.1"); } } } } write_doc_to_xml(file, doc); } void remove_xml_node_attr(const std::string& file) { rapidxml::file<> fd(file.data()); rapidxml::xml_document<> doc; doc.parse<rapidxml::parse_no_data_nodes>(fd.data()); auto root = doc.first_node(); auto srv = root->first_node("srv"); // remove first and last node of "srv" srv->remove_first_node(); srv->remove_last_node(); for (auto item = srv->first_node("item"); item != nullptr; item = item->next_sibling()) { auto id = item->first_attribute("id"); if (id != nullptr) { // remove 2th node's attrs if (2 == std::strtol(id->value(), nullptr, 10)) item->remove_all_attributes(); else if (3 == std::strtol(id->value(), nullptr, 10)) { // remove 3th node's first attr item->remove_first_attribute(); // remove 3th node's last attr item->remove_last_attribute(); // remove 3th node's sub nodes item->remove_all_nodes(); } } } write_doc_to_xml(file, doc); } void insert_xml_node_attr(const std::string& file) { rapidxml::file<> fd(file.data()); rapidxml::xml_document<> doc; doc.parse<rapidxml::parse_no_data_nodes>(fd.data()); auto root = doc.first_node(); auto srv = root->first_node("srv"); for (auto item = srv->first_node("item"); item != nullptr; item = item->next_sibling()) { auto id = item->first_attribute("id"); if (id != nullptr) { // insert new "item" before 2th "item" if (2 == std::strtol(id->value(), nullptr, 10)) { auto new_item = doc.allocate_node(rapidxml::node_element, "item", "11"); // new "item" some attrs new_item->append_attribute(doc.allocate_attribute("id", doc.allocate_string(std::to_string(11).data()))); new_item->append_attribute(doc.allocate_attribute("ip", "192.168.0.1")); new_item->append_attribute(doc.allocate_attribute("port", doc.allocate_string(std::to_string(11 + 8080).data()))); root->insert_node(item, new_item); } } } write_doc_to_xml(file, doc); } } int main() { const std::string file("data/rapidxml.xml"); //create_xml(file); //read_xml_by_file(file); //read_xml_by_stream(file); //modify_xml_node_attr(file); //remove_xml_node_attr(file); insert_xml_node_attr(file); return 0; }
35.667897
134
0.545003
zlecky
e8205f2d64eea0c48d1c378993430260508df213
2,841
cpp
C++
src/Framework/Entities/Components/MeshComponent.cpp
xcasadio/casaengine
19e34c0457265435c28667df7f2e5c137d954b98
[ "MIT" ]
null
null
null
src/Framework/Entities/Components/MeshComponent.cpp
xcasadio/casaengine
19e34c0457265435c28667df7f2e5c137d954b98
[ "MIT" ]
null
null
null
src/Framework/Entities/Components/MeshComponent.cpp
xcasadio/casaengine
19e34c0457265435c28667df7f2e5c137d954b98
[ "MIT" ]
null
null
null
#include "Entities/BaseEntity.h" #include "Entities/ComponentTypeEnum.h" #include "Base.h" #include "Game/Game.h" #include "Assets/AssetManager.h" #include "Maths/Matrix4.h" #include "MeshComponent.h" #include "StringUtils.h" #include "TransformComponent.h" #include "Game/MeshRendererGameComponent.h" namespace CasaEngine { /** * */ MeshComponent::MeshComponent(BaseEntity* pEntity_) : Component(pEntity_, MODEL_3D), m_pModel(nullptr), m_pTransform(nullptr), m_pModelRenderer(nullptr), m_pProgram(nullptr) { } /** * */ MeshComponent::~MeshComponent() { } /** * */ void MeshComponent::Initialize() { m_pTransform = GetEntity()->GetComponentMgr()->GetComponent<TransformComponent>(); CA_ASSERT(m_pTransform != nullptr, "MeshComponent::Initialize() can't find the TransformComponent. Please add it before add a MeshComponent"); m_pModelRenderer = Game::Instance().GetGameComponent<MeshRendererGameComponent>(); CA_ASSERT(m_pModelRenderer != nullptr, "MeshComponent::Initialize() can't find the MeshRendererGameComponent."); } /** * */ Mesh *MeshComponent::GetModel() const { return m_pModel; } /** * */ void MeshComponent::SetModel(Mesh *val) { m_pModel = val; } /** * */ Program *MeshComponent::GetEffect() const { return m_pProgram; } /** * */ void MeshComponent::SetProgram(Program *pVal_) { m_pProgram = pVal_; } /** * */ void MeshComponent::Update(const GameTime& /*gameTime_*/) { } /** * */ void MeshComponent::Draw() { CA_ASSERT(m_pModel != nullptr, "MeshComponent::Draw() : m_pModel is nullptr"); CA_ASSERT(m_pModelRenderer != nullptr, "MeshComponent::Draw() : m_pModelRenderer is nullptr"); Matrix4 mat = m_pTransform->GetWorldMatrix(); m_pModelRenderer->AddModel(m_pModel, mat, m_pProgram); } /** * */ /*void MeshComponent::HandleEvent(const Event* pEvent_) { }*/ /** * */ void MeshComponent::Write(std::ostream& /*os*/) const { } /** * */ void MeshComponent::Read (std::ifstream& /*is*/) { } /** * Editor */ void MeshComponent::ShowDebugWidget() { /* const ImGuiStyle& style = ImGui::GetStyle(); if (ImGui::CollapsingHeader("Static Mesh")) { ImGui::Text("TODO thumbnail"); } if (ImGui::CollapsingHeader("Materials")) { const float widgetWidth = 50.0f; Material *pMat = m_pModel->GetMaterial(); ImGui::PushItemWidth(widgetWidth); ImGui::Text("Texture 0"); ImGui::SameLine(0, style.ItemInnerSpacing.x); ImGui::PushItemWidth(widgetWidth); ImGui::Text("TODO thumbnail"); ImGui::PushItemWidth(widgetWidth); ImGui::Text("Texture 0 rep"); ImGui::SameLine(0, style.ItemInnerSpacing.x); ImGui::PushItemWidth(widgetWidth); ImGui::DragFloat("U", &pMat->m_Texture0Repeat.x, 0.01f); ImGui::SameLine(0, style.ItemInnerSpacing.x); ImGui::PushItemWidth(widgetWidth); ImGui::DragFloat("V", &pMat->m_Texture0Repeat.y, 0.01f); } */ } }
18.095541
143
0.698698
xcasadio
e82374536f7a46934b251770f446679b13c4779b
2,962
cpp
C++
src/sdb/sdbexception.cpp
raghunayak/libaws
e62cbf2887e7b4177ff72df2e50468ab228edfac
[ "Apache-2.0" ]
null
null
null
src/sdb/sdbexception.cpp
raghunayak/libaws
e62cbf2887e7b4177ff72df2e50468ab228edfac
[ "Apache-2.0" ]
null
null
null
src/sdb/sdbexception.cpp
raghunayak/libaws
e62cbf2887e7b4177ff72df2e50468ab228edfac
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2008 28msec, 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 "common.h" #include <libaws/sdbexception.h> #include "sdb/sdbresponse.h" namespace aws { SDBException::SDBException(const QueryErrorResponse& aError) { theErrorMessage = aError.getErrorMessage(); theOrigErrorCode = aError.getErrorCode(); theErrorCode = parseError(theOrigErrorCode); theRequestId = aError.getRequestId(); } SDBException::~SDBException() throw() { } const char* SDBException::what() const throw() { std::stringstream lTmp; lTmp << "Code:" << theOrigErrorCode << " Message:" << theErrorMessage << " RequestId:" << theRequestId; lTmp.str().c_str(); return lTmp.str().c_str(); } SDBException::ErrorCode SDBException::parseError(const std::string& aString) { return SDBException::Unknown; } CreateDomainException::CreateDomainException(const QueryErrorResponse& aError) : SDBException(aError) { } CreateDomainException::~CreateDomainException() throw() { } ListDomainsException::ListDomainsException(const QueryErrorResponse& aError) : SDBException(aError) { } ListDomainsException::~ListDomainsException() throw() { } DeleteDomainException::DeleteDomainException(const QueryErrorResponse& aError) : SDBException(aError) { } DeleteDomainException::~DeleteDomainException() throw() { } DomainMetadataException::DomainMetadataException(const QueryErrorResponse& aError) : SDBException(aError) { } DomainMetadataException::~DomainMetadataException() throw() { } PutAttributesException::PutAttributesException(const QueryErrorResponse& aError) : SDBException(aError) { } PutAttributesException::~PutAttributesException() throw() { } BatchPutAttributesException::BatchPutAttributesException(const QueryErrorResponse& aError) : SDBException(aError) { } BatchPutAttributesException::~BatchPutAttributesException() throw() { } DeleteAttributesException::DeleteAttributesException( const QueryErrorResponse& aError) : SDBException(aError) { } DeleteAttributesException::~DeleteAttributesException() throw() { } GetAttributesException::GetAttributesException( const QueryErrorResponse& aError) : SDBException(aError) { } GetAttributesException::~GetAttributesException() throw() { } QueryException::QueryException( const QueryErrorResponse& aError) : SDBException(aError) { } QueryException::~QueryException() throw() { } } /* namespace aws */
26.212389
105
0.753545
raghunayak
e82566042e055fb3cd4de8673fd2a6eb4a0e2bd8
3,013
hpp
C++
extlibs/SSVUtilsJson/extlibs/SSVUtils/include/SSVUtils/Core/ConsoleFmt/ConsoleFmt.hpp
questor/git-ws
4c6db1dd6586be21baf74d97e3caf1006a239aec
[ "AFL-3.0" ]
null
null
null
extlibs/SSVUtilsJson/extlibs/SSVUtils/include/SSVUtils/Core/ConsoleFmt/ConsoleFmt.hpp
questor/git-ws
4c6db1dd6586be21baf74d97e3caf1006a239aec
[ "AFL-3.0" ]
null
null
null
extlibs/SSVUtilsJson/extlibs/SSVUtils/include/SSVUtils/Core/ConsoleFmt/ConsoleFmt.hpp
questor/git-ws
4c6db1dd6586be21baf74d97e3caf1006a239aec
[ "AFL-3.0" ]
null
null
null
// Copyright (c) 2013-2014 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: http://opensource.org/licenses/AFL-3.0 #ifndef SSVU_CORE_CONSOLEFMT #define SSVU_CORE_CONSOLEFMT namespace ssvu { namespace Console { /// @brief Number of styles. constexpr SizeT styleCount{13}; /// @brief Number of colors. constexpr SizeT colorCount{16}; /// @brief Enum class representing all the possible styles. enum class Style : int { None = 0, Bold = 1, Dim = 2, Underline = 3, Blink = 4, ReverseFGBG = 5, Hidden = 6, ResetBold = 7, ResetDim = 8, ResetUnderline = 9, ResetBlink = 10, ResetReverse = 11, ResetHidden = 12 }; /// @brief Enum class representing all the possible colors. enum class Color : int { Default = 0, Black = 1, Red = 2, Green = 3, Yellow = 4, Blue = 5, Magenta = 6, Cyan = 7, LightGray = 8, DarkGray = 9, LightRed = 10, LightGreen = 11, LightYellow = 12, LightBlue = 13, LightMagenta = 14, LightCyan = 15, LightWhite = 16 }; } } // Depending on the OS, the correct implementation file is included. #if defined(SSVU_OS_LINUX) #include "SSVUtils/Core/ConsoleFmt/Internal/ConsoleFmtImplUnix.hpp" #elif defined(SSVU_OS_WINDOWS) #include "SSVUtils/Core/ConsoleFmt/Internal/ConsoleFmtImplWin.hpp" #else #include "SSVUtils/Core/ConsoleFmt/Internal/ConsoleFmtImplNull.hpp" #endif namespace ssvu { namespace Console { /// @brief Returns a format string that resets the current formatting. inline const auto& resetFmt() noexcept { return Internal::getStrResetFmt(); } /// @brief Returns a format string that sets the current style. /// @param mStyle Desired style. (ssvu::Console::Style member) inline const auto& setStyle(Style mStyle) noexcept { return Internal::getStrStyle(mStyle); } /// @brief Returns a format string that sets the current foreground color. /// @param mStyle Desired color. (ssvu::Console::Color member) inline const auto& setColorFG(Color mColor) noexcept { return Internal::getStrColorFG(mColor); } /// @brief Returns a format string that sets the current background color. /// @param mStyle Desired color. (ssvu::Console::Color member) inline const auto& setColorBG(Color mColor) noexcept { return Internal::getStrColorBG(mColor); } /// @brief Returns a format string that clears the console window. inline const auto& clear() noexcept { return Internal::getStrClear(); } /// @brief Returns true if valid console information is available. inline bool isInfoValid() noexcept { return Internal::isInfoValid(); } namespace Info { /// @brief Returns then number of columns of the console screen. inline SizeT getColumnCount() noexcept { return Internal::Info::getColumnCount(); } /// @brief Returns then number of rows of the console screen. inline SizeT getRowCount() noexcept { return Internal::Info::getRowCount(); } } } } #endif
28.158879
98
0.689346
questor
e82f4a12e54a57a96ed43b5bab19981b6d0f88c5
1,123
cpp
C++
data/dailyCodingProblem987.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
2
2020-09-04T20:56:23.000Z
2021-06-11T07:42:26.000Z
data/dailyCodingProblem987.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
data/dailyCodingProblem987.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /* Given an array of numbers and an index i, return the index of the nearest larger number of the number at index i, where distance is measured in array indices. For example, given [4, 1, 3, 5, 6] and index 0, you should return 3. If two distances to larger numbers are the equal, then return any one of them. If the array at i doesn't have a nearest larger integer, then return null. Follow-up: If you can preprocess the array, can you do this in constant time? */ int closestDistance(int arr[], int n, int index){ int left = index, right = index; while(left > 0 || right < n-1){ left--; right++; if(left >= 0 && arr[left] > arr[index]) return left; if(right < n && arr[right] > arr[index]) return right; } return -1; } // main function int main(){ int arr[] = {4, 1, 3, 5, 6}; int n = sizeof(arr)/sizeof(arr[0]); cout << closestDistance(arr, n, 0) << "\n"; cout << closestDistance(arr, n, 1) << "\n"; cout << closestDistance(arr, n, 2) << "\n"; cout << closestDistance(arr, n, 3) << "\n"; cout << closestDistance(arr, n, 4) << "\n"; return 0; }
28.075
96
0.647373
vidit1999
e832d4fb2d0fe78dc887506718cabdfaeda2dd4b
503
cpp
C++
JammaLib/src/actions/DoubleAction.cpp
malisimo/Jamma
69831e79a64e652e82aa41f8141e082c3899896b
[ "MIT" ]
null
null
null
JammaLib/src/actions/DoubleAction.cpp
malisimo/Jamma
69831e79a64e652e82aa41f8141e082c3899896b
[ "MIT" ]
null
null
null
JammaLib/src/actions/DoubleAction.cpp
malisimo/Jamma
69831e79a64e652e82aa41f8141e082c3899896b
[ "MIT" ]
null
null
null
#include "DoubleAction.h" using namespace actions; using base::ActionSender; using base::ActionReceiver; DoubleAction::DoubleAction(double value) : _value(value), Action() { } DoubleAction::~DoubleAction() { } double DoubleAction::Value() const { return _value; } DoubleActionUndo::DoubleActionUndo(double value, std::weak_ptr<ActionSender> sender) : _value(value), ActionUndo(sender) { } DoubleActionUndo::~DoubleActionUndo() { } double DoubleActionUndo::Value() const { return _value; }
13.594595
48
0.747515
malisimo
e83551b6fccba0088ef3735bd74e8ac99ca171e6
287
cc
C++
material.cc
KXue/CLRT
2b2dcb3addf5f638cda86fb03322779e0a33aee1
[ "MIT" ]
null
null
null
material.cc
KXue/CLRT
2b2dcb3addf5f638cda86fb03322779e0a33aee1
[ "MIT" ]
null
null
null
material.cc
KXue/CLRT
2b2dcb3addf5f638cda86fb03322779e0a33aee1
[ "MIT" ]
null
null
null
#include "material.hpp" Material::Material(float r, float g, float b, int computeColorType): computeColorType(computeColorType){ color[0] = r; color[1] = g; color[2] = b; } int Material::getComputeColorType(){ return computeColorType; } float* Material::GetColor(){ return color; }
22.076923
104
0.724739
KXue
e838091afc5d9e4b405895d692f78c1121b5c18a
15,878
cpp
C++
Visual Studio/Others/Calculateur d'adresses IP/IP_CalculatorDlg.cpp
Jeanmilost/Demos
2b71f6edc85948540660d290183530fd846262ad
[ "MIT" ]
1
2022-03-22T14:41:15.000Z
2022-03-22T14:41:15.000Z
Visual Studio/Others/Calculateur d'adresses IP/IP_CalculatorDlg.cpp
Jeanmilost/Demos
2b71f6edc85948540660d290183530fd846262ad
[ "MIT" ]
null
null
null
Visual Studio/Others/Calculateur d'adresses IP/IP_CalculatorDlg.cpp
Jeanmilost/Demos
2b71f6edc85948540660d290183530fd846262ad
[ "MIT" ]
null
null
null
// IP_CalculatorDlg.cpp : implementation file // #include "stdafx.h" #include "IP_Calculator.h" #include "IP_CalculatorDlg.h" #include "IP_Properties.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CIP_CalculatorDlg dialog CIP_CalculatorDlg::CIP_CalculatorDlg(CWnd* pParent /*=NULL*/) : CDialog(CIP_CalculatorDlg::IDD, pParent) { //{{AFX_DATA_INIT(CIP_CalculatorDlg) m_strIP1 = _T(""); m_strIP2 = _T(""); m_strIP3 = _T(""); m_strIP4 = _T(""); m_strBit = _T(""); m_strUserP = _T(""); m_strUserSR = _T(""); m_strMask1 = _T(""); m_strMask2 = _T(""); m_strMask3 = _T(""); m_strMask4 = _T(""); m_strMaxP = _T(""); m_strMaxSR = _T(""); m_strPas = _T(""); m_strPlage1 = _T(""); m_strPlage2 = _T(""); m_strNbBitsP = _T(""); m_strNbBitsSR = _T(""); //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CIP_CalculatorDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CIP_CalculatorDlg) DDX_Control(pDX, IDC_NBBITSSR, m_ctrlNbBitsSR); DDX_Control(pDX, IDC_NBBITSP, m_ctrlNbBitsP); DDX_Control(pDX, IDC_PLAGE2, m_ctrlPlage2); DDX_Control(pDX, IDC_PLAGE1, m_ctrlPlage1); DDX_Control(pDX, IDC_PAS, m_ctrlPas); DDX_Control(pDX, IDC_MAXSR, m_ctrlMaxSR); DDX_Control(pDX, IDC_MAXP, m_ctrlMaxP); DDX_Control(pDX, IDC_MASK4, m_ctrlMask4); DDX_Control(pDX, IDC_MASK3, m_ctrlMask3); DDX_Control(pDX, IDC_MASK2, m_ctrlMask2); DDX_Control(pDX, IDC_MASK1, m_ctrlMask1); DDX_Control(pDX, IDC_USERSR, m_ctrlUserSR); DDX_Control(pDX, IDC_USERP, m_ctrlUserP); DDX_Control(pDX, IDC_NBBITS, m_ctrlBit); DDX_Control(pDX, IDC_IP4, m_ctrlIP4); DDX_Control(pDX, IDC_IP3, m_ctrlIP3); DDX_Control(pDX, IDC_IP2, m_ctrlIP2); DDX_Control(pDX, IDC_IP1, m_ctrlIP1); DDX_Text(pDX, IDC_IP1, m_strIP1); DDX_Text(pDX, IDC_IP2, m_strIP2); DDX_Text(pDX, IDC_IP3, m_strIP3); DDX_Text(pDX, IDC_IP4, m_strIP4); DDX_Text(pDX, IDC_NBBITS, m_strBit); DDX_Text(pDX, IDC_USERP, m_strUserP); DDX_Text(pDX, IDC_USERSR, m_strUserSR); DDX_Text(pDX, IDC_MASK1, m_strMask1); DDX_Text(pDX, IDC_MASK2, m_strMask2); DDX_Text(pDX, IDC_MASK3, m_strMask3); DDX_Text(pDX, IDC_MASK4, m_strMask4); DDX_Text(pDX, IDC_MAXP, m_strMaxP); DDX_Text(pDX, IDC_MAXSR, m_strMaxSR); DDX_Text(pDX, IDC_PAS, m_strPas); DDX_Text(pDX, IDC_PLAGE1, m_strPlage1); DDX_Text(pDX, IDC_PLAGE2, m_strPlage2); DDX_Text(pDX, IDC_NBBITSP, m_strNbBitsP); DDX_Text(pDX, IDC_NBBITSSR, m_strNbBitsSR); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CIP_CalculatorDlg, CDialog) //{{AFX_MSG_MAP(CIP_CalculatorDlg) ON_WM_SYSCOMMAND() ON_WM_DESTROY() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_RESET, OnReset) ON_EN_CHANGE(IDC_IP1, OnChangeIp1) ON_EN_CHANGE(IDC_IP2, OnChangeIp2) ON_EN_CHANGE(IDC_IP3, OnChangeIp3) ON_EN_CHANGE(IDC_IP4, OnChangeIp4) ON_EN_CHANGE(IDC_NBBITS, OnChangeNbbits) ON_EN_CHANGE(IDC_USERP, OnChangeUserp) ON_EN_CHANGE(IDC_USERSR, OnChangeUsersr) ON_BN_CLICKED(IDC_CALCULATE, OnCalculate) ON_EN_KILLFOCUS(IDC_NBBITS, OnKillfocusNbbits) ON_BN_CLICKED(IDC_OPTIONS, OnOptions) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CIP_CalculatorDlg message handlers BOOL CIP_CalculatorDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here m_ctrlIP1.SetLimitText(3); m_ctrlIP2.SetLimitText(3); m_ctrlIP3.SetLimitText(3); m_ctrlIP4.SetLimitText(3); m_ctrlBit.SetLimitText(2); m_ctrlUserP.SetLimitText(10); m_ctrlUserSR.SetLimitText(10); m_ctrlMask1.SetLimitText(3); m_ctrlMask2.SetLimitText(3); m_ctrlMask3.SetLimitText(3); m_ctrlMask4.SetLimitText(3); m_ctrlMaxP.SetLimitText(10); m_ctrlMaxSR.SetLimitText(10); m_ctrlPas.SetLimitText(2); return TRUE; // return TRUE unless you set the focus to a control } void CIP_CalculatorDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } void CIP_CalculatorDlg::OnDestroy() { WinHelp(0L, HELP_QUIT); CDialog::OnDestroy(); } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CIP_CalculatorDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CIP_CalculatorDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CIP_CalculatorDlg::OnReset() { // TODO: Add your control notification handler code here m_strIP1 = _T(""); m_strIP2 = _T(""); m_strIP3 = _T(""); m_strIP4 = _T(""); m_strBit = _T(""); m_strUserP = _T(""); m_strUserSR = _T(""); m_strMask1 = _T(""); m_strMask2 = _T(""); m_strMask3 = _T(""); m_strMask4 = _T(""); m_strMaxP = _T(""); m_strMaxSR = _T(""); m_strPas = _T(""); m_strPlage1 = _T(""); m_strPlage2 = _T(""); m_strNbBitsP=_T(""); m_strNbBitsSR=_T(""); m_ctrlIP1.SetWindowText(_T("")); m_ctrlIP2.SetWindowText(_T("")); m_ctrlIP3.SetWindowText(_T("")); m_ctrlIP4.SetWindowText(_T("")); m_ctrlBit.SetWindowText(_T("")); m_ctrlUserP.SetWindowText(_T("")); m_ctrlUserSR.SetWindowText(_T("")); m_ctrlMask1.SetWindowText(_T("")); m_ctrlMask2.SetWindowText(_T("")); m_ctrlMask3.SetWindowText(_T("")); m_ctrlMask4.SetWindowText(_T("")); m_ctrlMaxP.SetWindowText(_T("")); m_ctrlMaxSR.SetWindowText(_T("")); m_ctrlPas.SetWindowText(_T("")); m_ctrlNbBitsP.SetWindowText(_T("")); m_ctrlNbBitsSR.SetWindowText(_T("")); m_ctrlPlage1.SetWindowText(_T("")); m_ctrlPlage2.SetWindowText(_T("")); IP_Adr.IP_Reset(); } void CIP_CalculatorDlg::OnChangeIp1() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here m_ctrlIP1.GetWindowText(m_strIP1); DWORD Result=ConvertStringToDWORD(m_strIP1); if (Result>255) { m_strIP1=_T("255"); m_ctrlIP1.SetWindowText(m_strIP1); Result=255; } IP_Adr.SetIP1(Result); } void CIP_CalculatorDlg::OnChangeIp2() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here m_ctrlIP2.GetWindowText(m_strIP2); DWORD Result=ConvertStringToDWORD(m_strIP2); if (Result>255) { m_strIP2=_T("255"); m_ctrlIP2.SetWindowText(m_strIP2); Result=255; } IP_Adr.SetIP2(Result); } void CIP_CalculatorDlg::OnChangeIp3() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here m_ctrlIP3.GetWindowText(m_strIP3); DWORD Result=ConvertStringToDWORD(m_strIP3); if (Result>255) { m_strIP3=_T("255"); m_ctrlIP3.SetWindowText(m_strIP3); Result=255; } IP_Adr.SetIP3(Result); } void CIP_CalculatorDlg::OnChangeIp4() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here m_ctrlIP4.GetWindowText(m_strIP4); DWORD Result=ConvertStringToDWORD(m_strIP4); if (Result>255) { m_strIP4=_T("255"); m_ctrlIP4.SetWindowText(m_strIP4); Result=255; } IP_Adr.SetIP4(Result); } void CIP_CalculatorDlg::OnChangeNbbits() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here m_ctrlBit.GetWindowText(m_strBit); DWORD Result=ConvertStringToDWORD(m_strBit); IP_Adr.SetBitMask(Result); } void CIP_CalculatorDlg::OnChangeUserp() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here m_ctrlUserP.GetWindowText(m_strUserP); if (m_strUserP.GetLength()==10) { CString FirstEntry=m_strUserP.GetAt(0); CString LastEntry=m_strUserP.GetAt(9); DWORD FirstNumber=ConvertStringToDWORD(FirstEntry); DWORD LastNumber=ConvertStringToDWORD(LastEntry); DWORD Entry=ConvertStringToDWORD(m_strUserP); if (LastNumber>2 || FirstNumber>1) { m_strUserP=_T("1073741822"); m_ctrlUserP.SetWindowText(m_strUserP); } else if (Entry>1073741822) { m_strUserP=_T("1073741822"); m_ctrlUserP.SetWindowText(m_strUserP); } } IP_Adr.SetNbPostes(ConvertStringToDWORD(m_strUserP)); } void CIP_CalculatorDlg::OnChangeUsersr() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here m_ctrlUserSR.GetWindowText(m_strUserSR); if (m_strUserSR.GetLength()==10) { CString FirstEntry=m_strUserSR.GetAt(0); CString LastEntry=m_strUserSR.GetAt(9); DWORD FirstNumber=ConvertStringToDWORD(FirstEntry); DWORD LastNumber=ConvertStringToDWORD(LastEntry); DWORD Entry=ConvertStringToDWORD(m_strUserSR); if (LastNumber>2 || FirstNumber>1) { m_strUserSR=_T("1073741822"); m_ctrlUserSR.SetWindowText(m_strUserSR); } else if (Entry>1073741822) { m_strUserSR=_T("1073741822"); m_ctrlUserSR.SetWindowText(m_strUserSR); } } IP_Adr.SetNbReseaux(ConvertStringToDWORD(m_strUserSR)); } void CIP_CalculatorDlg::OnCalculate() { // TODO: Add your control notification handler code here IP_Adr.IP_Calculate(); m_ctrlBit.SetWindowText(IP_Adr.strBit); m_ctrlIP1.SetWindowText(IP_Adr.strIP1); m_ctrlIP2.SetWindowText(IP_Adr.strIP2); m_ctrlIP3.SetWindowText(IP_Adr.strIP3); m_ctrlIP4.SetWindowText(IP_Adr.strIP4); m_ctrlMask1.SetWindowText(IP_Adr.str_Mask1); m_ctrlMask2.SetWindowText(IP_Adr.str_Mask2); m_ctrlMask3.SetWindowText(IP_Adr.str_Mask3); m_ctrlMask4.SetWindowText(IP_Adr.str_Mask4); m_ctrlMaxP.SetWindowText(IP_Adr.strMaxP); m_ctrlNbBitsP.SetWindowText(IP_Adr.strNbBitsP); m_ctrlMaxSR.SetWindowText(IP_Adr.strMaxSR); m_ctrlNbBitsSR.SetWindowText(IP_Adr.strNbBitsSR); m_ctrlPas.SetWindowText(IP_Adr.strPas); m_ctrlPlage1.SetWindowText(IP_Adr.str_Plage1); m_ctrlPlage2.SetWindowText(IP_Adr.str_Plage2); m_ctrlUserP.SetWindowText(IP_Adr.str_UserP); m_ctrlUserSR.SetWindowText(IP_Adr.str_UserSR); IP_Adr.IP_Flush(); m_strIP1 = _T(""); m_strIP2 = _T(""); m_strIP3 = _T(""); m_strIP4 = _T(""); m_strBit = _T(""); m_strUserP = _T(""); m_strUserSR = _T(""); m_strMask1 = _T(""); m_strMask2 = _T(""); m_strMask3 = _T(""); m_strMask4 = _T(""); m_strMaxP = _T(""); m_strMaxSR = _T(""); m_strPas = _T(""); m_strPlage1 = _T(""); m_strPlage2 = _T(""); m_strNbBitsP=_T(""); m_strNbBitsSR=_T(""); } void CIP_CalculatorDlg::OnKillfocusNbbits() { // TODO: Add your control notification handler code here DWORD Bit=IP_Adr.GetBitMask(); m_ctrlBit.GetWindowText(m_strBit); DWORD Result=ConvertStringToDWORD(m_strBit); if (Result!=Bit) { m_strBit.Format(_T("%d"), Bit); m_ctrlBit.SetWindowText(m_strBit); } } void CIP_CalculatorDlg::OnOptions() { // TODO: Add your control notification handler code here CIP_Properties Options(IP_Adr.GetUnlock()); if (Options.DoModal()==IDOK) { if (Options.m_boolBitMaskEntry==TRUE) { IP_SetWarning(War_UnlockMask); IP_Adr.SetUnlock(TRUE); } else IP_Adr.SetUnlock(FALSE); } }
28.053004
77
0.659466
Jeanmilost
e83c52514866dc6a83663fc12008a7ea911212b2
4,785
cpp
C++
src/Chronicles/entity/item.cpp
gregtour/chronicles-game
813a33c6d484bff59f210d81a3252bef2e0d3ea2
[ "CC0-1.0" ]
1
2015-04-28T15:12:14.000Z
2015-04-28T15:12:14.000Z
src/Chronicles/entity/item.cpp
gregtour/chronicles-game
813a33c6d484bff59f210d81a3252bef2e0d3ea2
[ "CC0-1.0" ]
null
null
null
src/Chronicles/entity/item.cpp
gregtour/chronicles-game
813a33c6d484bff59f210d81a3252bef2e0d3ea2
[ "CC0-1.0" ]
null
null
null
#include "item.h" #include "../../engine/engine.h" #include "../main.h" #include <string> #include <sstream> #include "particles/spark.h" CItem::CItem() { #ifdef LOW_RESOLUTION_TEXTURES mTexture = CManagedTexture::Load( &gResourceManager, "data/low/crate.bmp" ); #else mTexture = CManagedTexture::Load( &gResourceManager, "data/crate.bmp" ); #endif } CItem::~CItem() { CManagedTexture::Unload( &gResourceManager, mTexture ); } void CItem::Update( float dt ) { }; void CItem::Render() { { float mX = mObject->GetPosition().x; float mZ = mObject->GetPosition().y; float x, y, z; gCamera->GetPosition( &x, &y, &z ); if ( ((x-mX)*(x-mX) + (z-mZ)*(z-mZ)) > VIEW_DISTANCE_SQUARED ) return; } gLevel->Light( mObject->GetPosition() ); glEnable( GL_TEXTURE_2D ); mTexture->BindTexture(); float r = ((CPCircle*)mObject)->GetRadius() * 0.9f; glTranslatef( mObject->GetPosition().x, r, mObject->GetPosition().y ); /* Temporary Code, Draw A Cube as a Placeholder */ glBegin(GL_QUADS); // Draw The Cube Using quads glColor3f( 0.7f, 0.7f, 0.7f ); glNormal3f( 0.0f, 1.0f, 0.0f ); glTexCoord2f( 0.0f, 0.0f ); glVertex3f( r, r,-r); // Top Right Of The Quad (Top) glTexCoord2f( 1.0f, 0.0f ); glVertex3f(-r, r,-r); // Top Left Of The Quad (Top) glTexCoord2f( 1.0f, 1.0f ); glVertex3f(-r, r, r); // Bottom Left Of The Quad (Top) glTexCoord2f( 0.0f, 1.0f ); glVertex3f( r, r, r); // Bottom Right Of The Quad (Top) // glColor3f(1.0f,0.5f,0.0f); // Color Orange glNormal3f( 0.0f, -1.0f, 0.0f ); glTexCoord2f( 0.0f, 0.0f ); glVertex3f( r,-r, r); // Top Right Of The Quad (Bottom) glTexCoord2f( 1.0f, 0.0f ); glVertex3f(-r,-r, r); // Top Left Of The Quad (Bottom) glTexCoord2f( 1.0f, 1.0f ); glVertex3f(-r,-r,-r); // Bottom Left Of The Quad (Bottom) glTexCoord2f( 0.0f, 1.0f ); glVertex3f( r,-r,-r); // Bottom Right Of The Quad (Bottom) // glColor3f(1.0f,0.0f,0.0f); // Color Red glNormal3f( 0.0f, 0.0f, 1.0f ); glTexCoord2f( 0.0f, 0.0f ); glVertex3f( r, r, r); // Top Right Of The Quad (Front) glTexCoord2f( 1.0f, 0.0f ); glVertex3f(-r, r, r); // Top Left Of The Quad (Front) glTexCoord2f( 1.0f, 1.0f ); glVertex3f(-r,-r, r); // Bottom Left Of The Quad (Front) glTexCoord2f( 0.0f, 1.0f ); glVertex3f( r,-r, r); // Bottom Right Of The Quad (Front) // glColor3f(1.0f,1.0f,0.0f); // Color Yellow glNormal3f( 0.0f, 0.0f, -1.0f ); glTexCoord2f( 0.0f, 0.0f ); glVertex3f( r,-r,-r); // Top Right Of The Quad (Back) glTexCoord2f( 1.0f, 0.0f ); glVertex3f(-r,-r,-r); // Top Left Of The Quad (Back) glTexCoord2f( 1.0f, 1.0f ); glVertex3f(-r, r,-r); // Bottom Left Of The Quad (Back) glTexCoord2f( 0.0f, 1.0f ); glVertex3f( r, r,-r); // Bottom Right Of The Quad (Back) /// glColor3f(0.0f,0.0f,1.0f); // Color Blue glNormal3f( -1.0f, 0.0f, 0.0f ); glTexCoord2f( 0.0f, 0.0f ); glVertex3f(-r, r, r); // Top Right Of The Quad (Left) glTexCoord2f( 1.0f, 0.0f ); glVertex3f(-r, r,-r); // Top Left Of The Quad (Left) glTexCoord2f( 1.0f, 1.0f ); glVertex3f(-r,-r,-r); // Bottom Left Of The Quad (Left) glTexCoord2f( 0.0f, 1.0f ); glVertex3f(-r,-r, r); // Bottom Right Of The Quad (Left) // glColor3f(1.0f,0.0f,1.0f); // Color Violet glNormal3f( 1.0f, 0.0f, 0.0f ); glTexCoord2f( 0.0f, 0.0f ); glVertex3f( r, r,-r); // Top Right Of The Quad (Right) glTexCoord2f( 1.0f, 0.0f ); glVertex3f( r, r, r); // Top Left Of The Quad (Right) glTexCoord2f( 1.0f, 1.0f ); glVertex3f( r,-r, r); // Bottom Left Of The Quad (Right) glTexCoord2f( 0.0f, 1.0f ); glVertex3f( r,-r,-r); // Bottom Right Of The Quad (Right) glEnd(); // End Drawing The Cube glDisable( GL_TEXTURE_2D ); }; void CItem::Hit( IPhysicalObj* by, float force ) { SVector v; mObject->GetPosition().Difference( &by->GetPhysicalObject()->GetPosition(), &v ); SPoint pointOfContact = mObject->GetPosition(); v.Scale( -0.5f ); pointOfContact.Translate( &v ); gEntities.Add( new CSpark( pointOfContact.x, 3.0f, pointOfContact.y, 1.0f, 1.0f, 1.0f, 2.0f, 1, 4.4f, 15.0f, "data/wood.bmp" ) ); v.Flip(); v.Normalize(); v.Scale( force * by->GetPhysicalObject()->GetMass() / mObject->GetMass() ); mObject->SetVelocity( &v ); } void CItem::LogState() { std::string state; if ( mObject ) { std::stringstream stream; stream << "X: " << mObject->GetPosition().x << " Y: " << mObject->GetPosition().y << " XSP: " << mObject->GetVelocity().x << " YSP " << mObject->GetVelocity().y; state = stream.str(); } else { state = "No Physical Existance"; } gLog.LogItem( new CLogMessage( state ) ); }
29.720497
99
0.597492
gregtour
e83f40a8a2af17a5c25da13f190872a94202a862
1,912
cpp
C++
example/example.cpp
bobsayshilol/tser
5d7bd971bbf8837f3d4d67005565b21a1ede8bfd
[ "BSL-1.0" ]
null
null
null
example/example.cpp
bobsayshilol/tser
5d7bd971bbf8837f3d4d67005565b21a1ede8bfd
[ "BSL-1.0" ]
null
null
null
example/example.cpp
bobsayshilol/tser
5d7bd971bbf8837f3d4d67005565b21a1ede8bfd
[ "BSL-1.0" ]
null
null
null
// Licensed under the Boost License <https://opensource.org/licenses/BSL-1.0>. // SPDX-License-Identifier: BSL-1.0 #include <cassert> #include <optional> #include <tser/tser.hpp> enum class Item : char { NONE = 0, RADAR = 'R', TRAP = 'T', ORE = 'O' }; namespace x { struct Point { DEFINE_SERIALIZABLE(Point,x,y) int x = 0, y = 0; }; } struct Robot { DEFINE_SERIALIZABLE(Robot,point,item) x::Point point; std::optional<Item> item; }; int main() { auto robot = Robot{ x::Point{3,4}, Item::RADAR }; std::cout << robot << '\n'; // prints { "Robot": {"point" : { "Point": {"x" : 3, "y" : 4}}, "item" : R}} std::cout << Robot() << '\n'; // prints { "Robot": {"point" : { "Point": {"x" : 3, "y" : 4}}, "item" : {null}}} tser::BinaryArchive ba; ba.save(robot); std::cout << ba; //prints BggBUg to the console via base64 encoding (base64 means only printable characters are used) //this way it's quickly possible to log entire objects to the console or logfiles //due to varint encoding only 6 printable characters are needed, although the struct is 12 bytes in size //e.g. a size_t in the range of 0-127 will only take 1 byte (before the base 64 encoding) } void test() { //if we construct BinaryArchive with a string it will decode it and initialized it's internal buffer with it //so it's basically one or two lines of code to load a complex object into a test and start using it tser::BinaryArchive ba2("BggBUg"); auto loadedRobot = ba2.load<Robot>(); auto robot = Robot{ x::Point{3,4}, Item::RADAR }; //all the comparision operators are implemented, so I could directly use std::set<Robot> bool areEqual = (robot == loadedRobot) && !(robot != loadedRobot) && !(robot < loadedRobot); (void)areEqual; std::cout << loadedRobot; //prints{ "Robot": {"point" : { "Point": {"x" : 3, "y" : 4}}, "item" : R} } }
39.833333
121
0.630753
bobsayshilol
e840ec70db85f7c504f638759011e6799d264b1d
1,485
hpp
C++
framework/renderer.hpp
Montag55/Das-raytracer
356eac6a2ad6fe4f09015a94df9bbafe490f9585
[ "MIT" ]
null
null
null
framework/renderer.hpp
Montag55/Das-raytracer
356eac6a2ad6fe4f09015a94df9bbafe490f9585
[ "MIT" ]
null
null
null
framework/renderer.hpp
Montag55/Das-raytracer
356eac6a2ad6fe4f09015a94df9bbafe490f9585
[ "MIT" ]
null
null
null
#ifndef BUW_RENDERER_HPP #define BUW_RENDERER_HPP #include "color.hpp" #include "pixel.hpp" #include "ppmwriter.hpp" #include <string> #include <glm/glm.hpp> #include "scene.hpp" #include "hit.hpp" #include "ray.hpp" class Renderer { public: Renderer(Scene const& scene, unsigned int width, unsigned int height, std::string const& ofile); void render(); void write(Pixel const& p); Hit ohit(glm::mat4x4 const& trans_mat, Ray const& ray) const; Color raytrace(Ray const& ray, unsigned int depth); Color render_antialiase(Ray rayman, float antialiase_faktor, unsigned int depth); Color tonemap(Color tempcolor); void reflectedlight(Color & clr, Hit const& Hitze, Ray const& ray, unsigned int depth); void ambientlight(Color & clr, Color const& ka); void pointlight(Color & clr, std::shared_ptr<Light> const& light, Hit const& Hitze, Ray const& ray); void diffuselight(Color & clr, Hit const& Hitze, std::shared_ptr<Light> const& light, Ray const& raylight); void specularlight(Color & clr, Hit const& Hitze, std::shared_ptr<Light> const& light, Ray const& raylight, Ray const& ray); void refractedlight(Color & clr, Hit const& Hitze, Ray const& ray, unsigned int depth); inline std::vector<Color> const& colorbuffer() const { return m_colorbuffer; } private: Scene m_scene; unsigned int m_width; unsigned int m_height; std::vector<Color> m_colorbuffer; std::string m_outfile; PpmWriter m_ppm; }; #endif // #ifndef BUW_RENDERER_HPP
32.282609
127
0.731313
Montag55
e84314662841bfc5ff1becb4c52ec4f15c329cf7
3,924
cc
C++
modules/external_packages/src/alien/kernels/petsc/data_structure/PETScMatrix.cc
cedricga91/alien_legacy_plugins-1
459701026d76dbe1e8a6b20454f6b50ec9722f7f
[ "Apache-2.0" ]
4
2021-12-02T09:06:38.000Z
2022-01-10T14:22:35.000Z
modules/external_packages/src/alien/kernels/petsc/data_structure/PETScMatrix.cc
cedricga91/alien_legacy_plugins-1
459701026d76dbe1e8a6b20454f6b50ec9722f7f
[ "Apache-2.0" ]
null
null
null
modules/external_packages/src/alien/kernels/petsc/data_structure/PETScMatrix.cc
cedricga91/alien_legacy_plugins-1
459701026d76dbe1e8a6b20454f6b50ec9722f7f
[ "Apache-2.0" ]
7
2021-11-23T14:50:58.000Z
2022-03-17T13:23:07.000Z
#include "PETScMatrix.h" /* Author : havep at Wed Jul 18 14:46:45 2012 * Generated by createNew */ #include "petscmat.h" #include <alien/kernels/petsc/data_structure/PETScVector.h> #include <alien/kernels/petsc/PETScBackEnd.h> #include <alien/kernels/petsc/data_structure/PETScInternal.h> #include <alien/core/impl/MultiMatrixImpl.h> /*---------------------------------------------------------------------------*/ namespace Alien { /*---------------------------------------------------------------------------*/ PETScMatrix::PETScMatrix(const MultiMatrixImpl* multi_impl) : IMatrixImpl(multi_impl, AlgebraTraits<BackEnd::tag::petsc>::name()) , m_internal(nullptr) { const auto& row_space = multi_impl->rowSpace(); const auto& col_space = multi_impl->colSpace(); if (row_space.size() != col_space.size()) throw Arccore::FatalErrorException("MTL matrix must be square"); } /*---------------------------------------------------------------------------*/ PETScMatrix::~PETScMatrix() { delete m_internal; } /*---------------------------------------------------------------------------*/ bool PETScMatrix::initMatrix(const int local_size, const int local_offset, const int global_size, Arccore::ConstArrayView<Arccore::Integer> diag_lineSizes, Arccore::ConstArrayView<Arccore::Integer> offdiag_lineSizes, const bool parallel) { int ierr = 0; // code d'erreur de retour if (m_internal) { delete m_internal; } m_internal = new MatrixInternal(parallel); Arccore::Integer max_diag_size = 0, max_offdiag_size = 0; // -- Matrix -- #ifdef PETSC_HAVE_MATVALID PetscTruth valid_flag; ierr += MatValid(m_internal->m_internal, &valid_flag); if (valid_flag == PETSC_TRUE) return (ierr == 0); #endif /* PETSC_HAVE_MATVALID */ ierr += MatCreate(PETSC_COMM_WORLD, &m_internal->m_internal); ierr += MatSetSizes( m_internal->m_internal, local_size, local_size, global_size, global_size); ierr += MatSetType(m_internal->m_internal, m_internal->m_type); if (parallel) { // Use parallel structures ierr += MatMPIAIJSetPreallocation(m_internal->m_internal, max_diag_size, diag_lineSizes.unguardedBasePointer(), max_offdiag_size, offdiag_lineSizes.unguardedBasePointer()); } else { // Use sequential structures ierr += MatSeqAIJSetPreallocation( m_internal->m_internal, max_diag_size, diag_lineSizes.unguardedBasePointer()); } // Offsets are implicit with PETSc, we can to check that // they are compatible with the expected behaviour PetscInt low; ierr += MatGetOwnershipRange(m_internal->m_internal, &low, PETSC_NULL); if (low != local_offset) return false; return (ierr == 0); } /*---------------------------------------------------------------------------*/ bool PETScMatrix::addMatrixValues( const int row, const int ncols, const int* cols, const Arccore::Real* values) { int ierr = MatSetValues(m_internal->m_internal, 1, &row, ncols, cols, values, ADD_VALUES); return (ierr == 0); } /*---------------------------------------------------------------------------*/ bool PETScMatrix::setMatrixValues( const int row, const int ncols, const int* cols, const Arccore::Real* values) { int ierr = MatSetValues(m_internal->m_internal, 1, &row, ncols, cols, values, INSERT_VALUES); return (ierr == 0); } /*---------------------------------------------------------------------------*/ bool PETScMatrix::assemble() { int ierr = 0; ierr += MatAssemblyBegin(m_internal->m_internal, MAT_FINAL_ASSEMBLY); ierr += MatAssemblyEnd(m_internal->m_internal, MAT_FINAL_ASSEMBLY); return (ierr == 0); } /*---------------------------------------------------------------------------*/ } // namespace Alien /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ //#pragma clang diagnostic pop
31.645161
88
0.579001
cedricga91
e848d5692fdcd65984e89793ebd611ed9f7627f7
1,516
hpp
C++
headers/permutations.hpp
DouglasSherk/project-euler
f3b188b199ff31671c6d7683b15675be7484c5b8
[ "MIT" ]
null
null
null
headers/permutations.hpp
DouglasSherk/project-euler
f3b188b199ff31671c6d7683b15675be7484c5b8
[ "MIT" ]
null
null
null
headers/permutations.hpp
DouglasSherk/project-euler
f3b188b199ff31671c6d7683b15675be7484c5b8
[ "MIT" ]
null
null
null
#ifndef __EULER_PERMUTATIONS_INCLUDED_ #define __EULER_PERMUTATIONS_INCLUDED_ #include <string> #include <utility> #include <algorithm> #include <climits> #include "types.hpp" namespace euler { bool nextPermutation(std::string& n) { // 1. Find largest x s.t. P[x]<P[x+1] int x = -1; for (int i = n.length() - 2; i >= 0; i--) { if (n[i] < n[i + 1]) { x = i; break; } } // 1a. If there is no such x, then this was the last permutation. if (x == -1) { return false; } // 2. Find largest y s.t. P[x]<P[y] int y = -1; for (int i = n.length() - 1; i >= 0; i--) { if (n[x] < n[i]) { y = i; break; } } // 3. Swap P[x] and P[y] std::swap(n[x], n[y]); // 4. Reverse P[x+1]..P[n] std::reverse(n.begin() + x + 1, n.end()); return true; } template <class T> bool nextPermutation(T& n) { std::string permutation = std::to_string(n); bool retVal = nextPermutation(permutation); n = toInt<T>(permutation); return retVal; } bool isPermutation(const std::string& a, const std::string& b) { unsigned char charsA[UCHAR_MAX] = {0}, charsB[UCHAR_MAX] = {0}; for (auto c : a) { charsA[(unsigned char)c]++; } for (auto c : b) { charsB[(unsigned char)c]++; } for (int i = 0; i < UCHAR_MAX; i++) { if (charsA[i] != charsB[i]) { return false; } } return true; } bool isPermutation(int a, int b) { return isPermutation(std::to_string(a), std::to_string(b)); } } #endif // __EULER_PERMUTATIONS_INCLUDED_
18.95
67
0.574538
DouglasSherk
e84c4df6e679a44c7a091eac3534e0115d1dc8cb
523
cpp
C++
mainRun.cpp
LvWenHan/lwh
7f7a219623433e5c06cecbaab72b3cd658e1b94b
[ "Apache-2.0" ]
2
2021-03-20T04:25:41.000Z
2021-03-20T06:52:36.000Z
mainRun.cpp
LvWenHan/lwh
7f7a219623433e5c06cecbaab72b3cd658e1b94b
[ "Apache-2.0" ]
null
null
null
mainRun.cpp
LvWenHan/lwh
7f7a219623433e5c06cecbaab72b3cd658e1b94b
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main(){ int a, b, t,sumA = 0,i = 1; cin >> a >> b >> t; // sumA += a; while(true) { if (sumA + a >= t) { //xxx } if (b * i + b >= t) { //xx } } for(;!(sumA + a >= t || b * i + b >= t);i++){ if(sumA <= b * i){ sumA += a; } cout << sumA << ' ' << b * i << endl; } if(sumA == b * i){ cout << "tongshi" << endl; } else if((t - sumA) > b * i){ cout << "tuzi" << endl; } else{ cout << "wugui" << endl; } return 0; }
14.135135
46
0.414914
LvWenHan
e8572eeb790963169619fe590f6c05beb3d79ffc
9,995
cpp
C++
src/InstantInterface/WebInterface.cpp
matthieu-ft/InstantInterface
b27212df6769be6e9a5d168a2b0ed49e0130ce42
[ "MIT" ]
null
null
null
src/InstantInterface/WebInterface.cpp
matthieu-ft/InstantInterface
b27212df6769be6e9a5d168a2b0ed49e0130ce42
[ "MIT" ]
null
null
null
src/InstantInterface/WebInterface.cpp
matthieu-ft/InstantInterface
b27212df6769be6e9a5d168a2b0ed49e0130ce42
[ "MIT" ]
null
null
null
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // License Agreement // For InstantInterface Library // // The MIT License (MIT) // // Copyright (c) 2016 Matthieu Fraissinet-Tachet (www.matthieu-ft.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. // //M*/ #include "WebInterface.h" #include <json/json.h> #include <fstream> using namespace std; namespace InstantInterface { WebInterface::WebInterface(bool withThread) : m_count(0), threaded(withThread), structureCache(""), valuesCache(""), m_stopped(false) { // set up access channels to only log interesting things m_endpoint.clear_access_channels(websocketpp::log::alevel::all); m_endpoint.set_access_channels(websocketpp::log::alevel::access_core); m_endpoint.set_access_channels(websocketpp::log::alevel::app); m_endpoint.set_reuse_addr(true); // Initialize the Asio transport policy m_endpoint.init_asio(); // Bind the handlers we are using using websocketpp::lib::placeholders::_1; using websocketpp::lib::placeholders::_2; using websocketpp::lib::bind; m_endpoint.set_open_handler(bind(&WebInterface::on_open,this,_1)); m_endpoint.set_close_handler(bind(&WebInterface::on_close,this,_1)); m_endpoint.set_http_handler(bind(&WebInterface::on_http,this,_1)); m_endpoint.set_message_handler(bind(&WebInterface::on_message,this,_1,_2)); } bool WebInterface::poll() { try { m_endpoint.poll(); } catch (websocketpp::exception const & e) { std::cout << e.what() << std::endl; } return !m_stopped; } void WebInterface::stop() { //do not accept new connection m_endpoint.stop_listening(); //close properly all existing connections for(auto& it: m_connections) { m_endpoint.close(it,websocketpp::close::status::normal, "close button pressed"); } m_stopped = true; thread.join(); } void WebInterface::init(uint16_t port, std::string docroot) { std::stringstream ss; if(docroot == "#") { //in this case we look for the path in the file pathToWebInterface.txt std::ifstream ifstr ("pathToWebInterface.txt"); if(!std::getline(ifstr, docroot)) { std::cout<<"InstantInterface::WebInterface::init(), couldn't find the path to the web interface. " "Make sure that the file pathToWebInterface.txt exists in the same directory where the program is executed" " and make sure that there are no additional space or lines in the file." " Also, don't forget to add a directory separator at the end of the file"<<std::endl; return; } } ss << "Running telemetry server on port "<< port <<" using docroot=" << docroot; m_endpoint.get_alog().write(websocketpp::log::alevel::app,ss.str()); m_docroot = docroot; // listen on specified port m_endpoint.listen(port); // Start the server accept loop m_endpoint.start_accept(); } void WebInterface::run() { updateStructureCache(); updateParameterCache(); // Start the ASIO io_service run loop try { if(threaded) { thread = std::thread(&server::run,&m_endpoint); } else { m_endpoint.run(); } } catch (websocketpp::exception const & e) { std::cout << e.what() << std::endl; } } void WebInterface::on_message(websocketpp::connection_hdl hdl, server::message_ptr msg) { if (msg->get_opcode() == websocketpp::frame::opcode::text) { std::string content = msg->get_payload(); if(content == "send_interface") { send_interface(hdl); } else if (content == "update") { send_values_update(hdl); } else { //this must contain json, so we try to do the udpate if(threaded) { addCommand(content); } else { executeSingleCommand(content); } } } else { std::cout<<"we don't know what to do with this message, because this is no text"<<std::endl; } } void WebInterface::send_interface(websocketpp::connection_hdl hdl) { if (threaded) { scoped_lock lock(parametersMutex); m_endpoint.send(hdl,structureCache,websocketpp::frame::opcode::text); } else { m_endpoint.send(hdl,getStructureJsonString(),websocketpp::frame::opcode::text); } //after sending the interface we send the update of all the parameters, because the structure of the interface //is stored in json::value that is not synchronized with the actual values of the parameters send_values_update(hdl); } void WebInterface::send_values_update(websocketpp::connection_hdl hdl) { if(threaded) { scoped_lock lock(parametersMutex); m_endpoint.send(hdl,valuesCache,websocketpp::frame::opcode::text); } else { m_endpoint.send(hdl,getStateJsonString(),websocketpp::frame::opcode::text); } } void WebInterface::addCommand(const std::string &command) { scoped_lock lock (mainPrgMessagesMutex); mainPrgMessages.push(command); } void WebInterface::executeCommands() { std::queue<std::string> queueCopy; { scoped_lock lock (mainPrgMessagesMutex); queueCopy = std::move(mainPrgMessages); } std::string content; while(!queueCopy.empty()) { content = queueCopy.front(); queueCopy.pop(); executeSingleCommand(content); } } bool WebInterface::executeSingleCommand(const string &content) { Json::Reader reader; Json::Value messageJson; bool success = reader.parse(content.c_str(), messageJson); if(!success) { std::cout<<"Couldn't parse received message to json."<<std::endl; return false; } if(messageJson["type"].asString()=="update") { Json::Value updates = messageJson["content"]; for(Json::ValueIterator itr = updates.begin(); itr != updates.end(); itr++) { std::string paramId = (*itr)["id"].asString(); updateInterfaceElement(paramId,(*itr)["value"]); } return true; } return false; } void WebInterface::updateStructureCache() { scoped_lock lock (parametersMutex); structureCache = this->getStructureJsonString(); } void WebInterface::updateParameterCache() { scoped_lock lock (parametersMutex); valuesCache = this->getStateJsonString(); } void WebInterface::forceRefreshAll() { updateParameterCache(); for(auto& it: m_connections) { send_values_update(it); } } void WebInterface::forceRefreshStructureAll() { updateStructureCache(); for(auto& it: m_connections) { send_interface(it); } } void WebInterface::on_http(WebInterface::connection_hdl hdl) { // Upgrade our connection handle to a full connection_ptr server::connection_ptr con = m_endpoint.get_con_from_hdl(hdl); std::ifstream file; std::string filename = con->get_uri()->get_resource(); std::string response; m_endpoint.get_alog().write(websocketpp::log::alevel::app, "http request1: "+filename); if (filename == "/") { filename = m_docroot+"index.html"; } else { filename = m_docroot+filename.substr(1); } m_endpoint.get_alog().write(websocketpp::log::alevel::app, "http request2: "+filename); file.open(filename.c_str(), std::ios::in); if (!file) { // 404 error std::stringstream ss; ss << "<!doctype html><html><head>" << "<title>Error 404 (Resource not found)</title><body>" << "<h1>Error 404</h1>" << "<p>The requested URL " << filename << " was not found on this server.</p>" << "</body></head></html>"; con->set_body(ss.str()); con->set_status(websocketpp::http::status_code::not_found); return; } file.seekg(0, std::ios::end); response.reserve(file.tellg()); file.seekg(0, std::ios::beg); response.assign((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); con->set_body(response); con->set_status(websocketpp::http::status_code::ok); } void WebInterface::on_open(WebInterface::connection_hdl hdl) { m_connections.insert(hdl); } void WebInterface::on_close(WebInterface::connection_hdl hdl) { m_connections.erase(hdl); } }
27.610497
130
0.634317
matthieu-ft
e859ada3637cdae6ad9d53c476e3ceea2404e1f8
903
cpp
C++
codeforces/D - Riverside Curio/Accepted (2).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/D - Riverside Curio/Accepted (2).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/D - Riverside Curio/Accepted (2).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Mar/26/2018 18:41 * solution_verdict: Accepted language: GNU C++14 * run_time: 140 ms memory_used: 5100 KB * problem: https://codeforces.com/contest/957/problem/D ****************************************************************************************/ #include<bits/stdc++.h> using namespace std; long long n,arr[100005],ans,tmp[100005]; int main() { cin>>n; for(int i=1;i<=n;i++)cin>>arr[i]; for(int i=1;i<=n;i++)tmp[i]=max(tmp[i-1],arr[i]+1); for(int i=n;i>=1;i--)tmp[i]=max(tmp[i],tmp[i+1]-1); for(int i=1;i<=n;i++)ans+=tmp[i]-arr[i]-1; cout<<ans<<endl; return 0; }
47.526316
111
0.369878
kzvd4729
e85bc666455c7d89246688864cd3f712c3447a25
1,586
cpp
C++
codeforces/538div2/B/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
codeforces/538div2/B/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
19
2016-05-04T02:46:31.000Z
2021-11-27T06:18:33.000Z
codeforces/538div2/B/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> #define each(i, c) for (auto& i : c) #define unless(cond) if (!(cond)) using namespace std; typedef long long int lli; typedef unsigned long long ull; typedef complex<double> point; template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; } template<typename P, typename Q> istream& operator >> (istream& is, pair<P, Q>& p) { is >> p.first >> p.second; return is; } template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; each (i, v) os << i << ","; os << ")"; return os; } template<typename T> istream& operator >> (istream& is, vector<T>& v) { each (i, v) is >> i; return is; } template<typename T> inline T setmax(T& a, T b) { return a = std::max(a, b); } template<typename T> inline T setmin(T& a, T b) { return a = std::min(a, b); } int main(int argc, char *argv[]) { ios_base::sync_with_stdio(0); cin.tie(0); int n, m, k; while (cin >> n >> m >> k) { vector<int> a(n); cin >> a; auto b = a; sort(b.begin(), b.end()); reverse(b.begin(), b.end()); map<int, int> cnt; lli sum = 0; for (int i = 0; i < m * k; ++i) { ++cnt[b[i]]; sum += b[i]; } vector<int> idx; int x = m; for (int i = 0; i < a.size(); ++i) { if (cnt[a[i]]) { --x; --cnt[a[i]]; } if (!x) { idx.push_back(i + 1); x = m; } } idx.pop_back(); cout << sum << endl; each (i, idx) cout << i << ' ' ; cout << endl; } return 0; }
26.433333
144
0.516393
Johniel
e86c708436fe4f50479c49c8adda64e688fec8a1
26,264
cc
C++
soa/service/zmq_endpoint.cc
oktal/rtbkit
1b1b3b76ab211111c20b2957634619b3ba2813f4
[ "Apache-2.0" ]
1
2019-02-12T10:40:08.000Z
2019-02-12T10:40:08.000Z
soa/service/zmq_endpoint.cc
oktal/rtbkit
1b1b3b76ab211111c20b2957634619b3ba2813f4
[ "Apache-2.0" ]
null
null
null
soa/service/zmq_endpoint.cc
oktal/rtbkit
1b1b3b76ab211111c20b2957634619b3ba2813f4
[ "Apache-2.0" ]
null
null
null
/* zmq_endpoint.cc Jeremy Barnes, 9 November 2012 Copyright (c) 2012 Datacratic Inc. All rights reserved. */ #include "zmq_endpoint.h" #include "jml/utils/smart_ptr_utils.h" #include <sys/utsname.h> #include <thread> #include "jml/arch/timers.h" #include "jml/arch/info.h" using namespace std; namespace Datacratic { /******************************************************************************/ /* ZMQ LOGS */ /******************************************************************************/ Logging::Category ZmqLogs::print("ZMQ"); Logging::Category ZmqLogs::error("ZMQ Error", ZmqLogs::print); Logging::Category ZmqLogs::trace("ZMQ Trace", ZmqLogs::print); /*****************************************************************************/ /* ZMQ EVENT SOURCE */ /*****************************************************************************/ ZmqEventSource:: ZmqEventSource() : socket_(0), socketLock_(nullptr) { needsPoll = false; } ZmqEventSource:: ZmqEventSource(zmq::socket_t & socket, SocketLock * socketLock) : socket_(&socket), socketLock_(socketLock) { needsPoll = false; updateEvents(); } void ZmqEventSource:: init(zmq::socket_t & socket, SocketLock * socketLock) { socket_ = &socket; socketLock_ = socketLock; needsPoll = false; updateEvents(); } int ZmqEventSource:: selectFd() const { int res = -1; size_t resSize = sizeof(int); socket().getsockopt(ZMQ_FD, &res, &resSize); if (res == -1) THROW(ZmqLogs::error) << "no fd for zeromq socket" << endl; return res; } bool ZmqEventSource:: poll() const { if (currentEvents & ZMQ_POLLIN) return true; std::unique_lock<SocketLock> guard; if (socketLock_) guard = std::unique_lock<SocketLock>(*socketLock_); updateEvents(); return currentEvents & ZMQ_POLLIN; } void ZmqEventSource:: updateEvents() const { size_t events_size = sizeof(currentEvents); socket().getsockopt(ZMQ_EVENTS, &currentEvents, &events_size); } bool ZmqEventSource:: processOne() { using namespace std; if (debug_) cerr << "called processOne on " << this << ", poll = " << poll() << endl; if (!poll()) return false; std::vector<std::string> msg; // We process all events, as otherwise the select fd can't be guaranteed to wake us up for (;;) { { std::unique_lock<SocketLock> guard; if (socketLock_) guard = std::unique_lock<SocketLock>(*socketLock_); msg = recvAllNonBlocking(socket()); if (msg.empty()) { if (currentEvents & ZMQ_POLLIN) throw ML::Exception("empty message with currentEvents"); return false; // no more events } updateEvents(); } if (debug_) cerr << "got message of length " << msg.size() << endl; handleMessage(msg); } return currentEvents & ZMQ_POLLIN; } void ZmqEventSource:: handleMessage(const std::vector<std::string> & message) { if (asyncMessageHandler) { asyncMessageHandler(message); return; } auto reply = handleSyncMessage(message); if (!reply.empty()) { sendAll(socket(), reply); } } std::vector<std::string> ZmqEventSource:: handleSyncMessage(const std::vector<std::string> & message) { if (!syncMessageHandler) THROW(ZmqLogs::error) << "no message handler set" << std::endl; return syncMessageHandler(message); } /*****************************************************************************/ /* ZMQ SOCKET MONITOR */ /*****************************************************************************/ //static int numMonitors = 0; ZmqSocketMonitor:: ZmqSocketMonitor(zmq::context_t & context) : monitorEndpoint(new zmq::socket_t(context, ZMQ_PAIR)), monitoredSocket(0) { //cerr << "creating socket monitor at " << this << endl; //__sync_fetch_and_add(&numMonitors, 1); } void ZmqSocketMonitor:: shutdown() { if (!monitorEndpoint) return; //cerr << "shutting down socket monitor at " << this << endl; connectedUri.clear(); std::unique_lock<Lock> guard(lock); monitorEndpoint.reset(); //cerr << __sync_add_and_fetch(&numMonitors, -1) << " monitors still active" // << endl; } void ZmqSocketMonitor:: disconnect() { std::unique_lock<Lock> guard(lock); if (monitorEndpoint) monitorEndpoint->tryDisconnect(connectedUri.c_str()); } void ZmqSocketMonitor:: init(zmq::socket_t & socketToMonitor, int events) { static int serial = 0; // Initialize the monitor connection connectedUri = ML::format("inproc://monitor-%p-%d", this, __sync_fetch_and_add(&serial, 1)); monitoredSocket = &socketToMonitor; //using namespace std; //cerr << "connecting monitor to " << connectedUri << endl; int res = zmq_socket_monitor(socketToMonitor, connectedUri.c_str(), events); if (res == -1) throw zmq::error_t(); // Connect it in monitorEndpoint->connect(connectedUri.c_str()); // Make sure we receive events from it ZmqBinaryTypedEventSource<zmq_event_t>::init(*monitorEndpoint); messageHandler = [=] (const zmq_event_t & event) { this->handleEvent(event); }; } bool debugZmqMonitorEvents = false; int ZmqSocketMonitor:: handleEvent(const zmq_event_t & event) { if (debugZmqMonitorEvents) { cerr << "got socket event " << printZmqEvent(event.event) << " at " << this << " " << connectedUri << " for socket " << monitoredSocket << endl; } auto doEvent = [&] (const EventHandler & handler, const char * addr, int param) { if (handler) handler(addr, param, event); else if (defaultHandler) defaultHandler(addr, param, event); else return 0; return 1; }; switch (event.event) { // Bind case ZMQ_EVENT_LISTENING: return doEvent(bindHandler, event.data.listening.addr, event.data.listening.fd); case ZMQ_EVENT_BIND_FAILED: return doEvent(bindFailureHandler, event.data.bind_failed.addr, event.data.bind_failed.err); // Accept case ZMQ_EVENT_ACCEPTED: return doEvent(acceptHandler, event.data.accepted.addr, event.data.accepted.fd); case ZMQ_EVENT_ACCEPT_FAILED: return doEvent(acceptFailureHandler, event.data.accept_failed.addr, event.data.accept_failed.err); break; // Connect case ZMQ_EVENT_CONNECTED: return doEvent(connectHandler, event.data.connected.addr, event.data.connected.fd); case ZMQ_EVENT_CONNECT_DELAYED: return doEvent(connectFailureHandler, event.data.connect_delayed.addr, event.data.connect_delayed.err); case ZMQ_EVENT_CONNECT_RETRIED: return doEvent(connectRetryHandler, event.data.connect_retried.addr, event.data.connect_retried.interval); // Close and disconnection case ZMQ_EVENT_CLOSE_FAILED: return doEvent(closeFailureHandler, event.data.close_failed.addr, event.data.close_failed.err); case ZMQ_EVENT_CLOSED: return doEvent(closeHandler, event.data.closed.addr, event.data.closed.fd); case ZMQ_EVENT_DISCONNECTED: return doEvent(disconnectHandler, event.data.disconnected.addr, event.data.disconnected.fd); default: LOG(ZmqLogs::print) << "got unknown event type " << event.event << endl; return doEvent(defaultHandler, "", -1); } } /*****************************************************************************/ /* NAMED ZEROMQ ENDPOINT */ /*****************************************************************************/ ZmqNamedEndpoint:: ZmqNamedEndpoint(std::shared_ptr<zmq::context_t> context) : context_(context) { } void ZmqNamedEndpoint:: init(std::shared_ptr<ConfigurationService> config, int socketType, const std::string & endpointName) { NamedEndpoint::init(config, endpointName); this->socketType = socketType; this->socket_.reset(new zmq::socket_t(*context_, socketType)); setHwm(*socket_, 65536); addSource("ZmqNamedEndpoint::socket", std::make_shared<ZmqBinaryEventSource> (*socket_, [=] (std::vector<zmq::message_t> && message) { handleRawMessage(std::move(message)); })); } std::string ZmqNamedEndpoint:: bindTcp(PortRange const & portRange, std::string host) { std::unique_lock<Lock> guard(lock); if (!socket_) THROW(ZmqLogs::error) << "bind called before init" << std::endl; using namespace std; if (host == "") host = "*"; int port = bindAndReturnOpenTcpPort(*socket_, portRange, host); auto getUri = [&] (const std::string & host) { return "tcp://" + host + ":" + to_string(port); }; Json::Value config; auto addEntry = [&] (const std::string& addr, const std::string& hostScope) { std::string uri; if(hostScope != "*") { uri = "tcp://" + addr + ":" + to_string(port); } else { uri = "tcp://" + ML::fqdn_hostname(to_string(port)) + ":" + to_string(port); } Json::Value & entry = config[config.size()]; entry["zmqConnectUri"] = uri; Json::Value & transports = entry["transports"]; transports[0]["name"] = "tcp"; transports[0]["addr"] = addr; transports[0]["hostScope"] = hostScope; transports[0]["port"] = port; transports[1]["name"] = "zeromq"; transports[1]["socketType"] = socketType; transports[1]["uri"] = uri; }; if (host == "*") { auto interfaces = getInterfaces({AF_INET}); for (unsigned i = 0; i < interfaces.size(); ++i) { addEntry(interfaces[i].addr, interfaces[i].hostScope); } publishAddress("tcp", config); return getUri(host); } else { string host2 = addrToIp(host); // TODO: compute the host scope; don't just assume "*" addEntry(host2, "*"); publishAddress("tcp", config); return getUri(host2); } } /*****************************************************************************/ /* NAMED ZEROMQ PROXY */ /*****************************************************************************/ ZmqNamedProxy:: ZmqNamedProxy() : context_(new zmq::context_t(1)), local(true) { } ZmqNamedProxy:: ZmqNamedProxy(std::shared_ptr<zmq::context_t> context) : context_(context), local(true) { } void ZmqNamedProxy:: init(std::shared_ptr<ConfigurationService> config, int socketType, const std::string & identity) { this->connectionType = NO_CONNECTION; this->connectionState = NOT_CONNECTED; this->config = config; socket_.reset(new zmq::socket_t(*context_, socketType)); if (identity != "") setIdentity(*socket_, identity); setHwm(*socket_, 65536); serviceWatch.init(std::bind(&ZmqNamedProxy::onServiceNodeChange, this, std::placeholders::_1, std::placeholders::_2)); endpointWatch.init(std::bind(&ZmqNamedProxy::onEndpointNodeChange, this, std::placeholders::_1, std::placeholders::_2)); } bool ZmqNamedProxy:: connect(const std::string & endpointName, ConnectionStyle style) { if (!config) { THROW(ZmqLogs::error) << "attempt to connect to " << endpointName << " without calling init()" << endl; } if (connectionState == CONNECTED) THROW(ZmqLogs::error) << "already connected" << endl; this->connectedService = endpointName; if (connectionType == NO_CONNECTION) connectionType = CONNECT_DIRECT; LOG(ZmqLogs::print) << "connecting to " << endpointName << endl; vector<string> children = config->getChildren(endpointName, endpointWatch); auto setPending = [&] { std::lock_guard<ZmqEventSource::SocketLock> guard(socketLock_); if (connectionState == NOT_CONNECTED) connectionState = CONNECTION_PENDING; }; for (auto c: children) { ExcAssertNotEqual(connectionState, CONNECTED); string key = endpointName + "/" + c; Json::Value epConfig = config->getJson(key); for (auto & entry: epConfig) { if (!entry.isMember("zmqConnectUri")) return true; string uri = entry["zmqConnectUri"].asString(); auto hs = entry["transports"][0]["hostScope"]; if (!hs) continue; string hostScope = hs.asString(); if (hs != "*") { utsname name; if (uname(&name)) { THROW(ZmqLogs::error) << "uname error: " << strerror(errno) << std::endl; } if (hostScope != name.nodename) continue; // wrong host scope } { std::lock_guard<ZmqEventSource::SocketLock> guard(socketLock_); socket().connect(uri.c_str()); connectedUri = uri; connectionState = CONNECTED; } LOG(ZmqLogs::print) << "connected to " << uri << endl; onConnect(uri); return true; } setPending(); return false; } if (style == CS_MUST_SUCCEED && connectionState != CONNECTED) { THROW(ZmqLogs::error) << "couldn't connect to any services of class " << serviceClass << endl; } setPending(); return connectionState == CONNECTED; } bool ZmqNamedProxy:: connectToServiceClass(const std::string & serviceClass, const std::string & endpointName, bool local_, ConnectionStyle style) { local = local_; // TODO: exception safety... if we bail don't screw around the auction ExcAssertNotEqual(connectionType, CONNECT_DIRECT); ExcAssertNotEqual(serviceClass, ""); ExcAssertNotEqual(endpointName, ""); this->serviceClass = serviceClass; this->endpointName = endpointName; if (connectionType == NO_CONNECTION) connectionType = CONNECT_TO_CLASS; if (!config) { THROW(ZmqLogs::error) << "attempt to connect to " << endpointName << " without calling init()" << endl; } if (connectionState == CONNECTED) THROW(ZmqLogs::error) << "attempt to double connect connection" << endl; vector<string> children = config->getChildren("serviceClass/" + serviceClass, serviceWatch); for (auto c: children) { string key = "serviceClass/" + serviceClass + "/" + c; Json::Value value = config->getJson(key); std::string name = value["serviceName"].asString(); std::string path = value["servicePath"].asString(); std::string location = value["serviceLocation"].asString(); if (local && location != config->currentLocation) { LOG(ZmqLogs::trace) << path << " / " << name << " dropped while connecting to " << serviceClass << "/" << endpointName << "(" << location << " != " << config->currentLocation << ")" << std::endl; continue; } if (connect(path + "/" + endpointName, style == CS_ASYNCHRONOUS ? CS_ASYNCHRONOUS : CS_SYNCHRONOUS)) return true; } if (style == CS_MUST_SUCCEED && connectionState != CONNECTED) { THROW(ZmqLogs::error) << "couldn't connect to any services of class " << serviceClass << endl; } { std::lock_guard<ZmqEventSource::SocketLock> guard(socketLock_); if (connectionState == NOT_CONNECTED) connectionState = CONNECTION_PENDING; } return connectionState == CONNECTED; } void ZmqNamedProxy:: onServiceNodeChange(const std::string & path, ConfigurationService::ChangeType change) { if (connectionState != CONNECTION_PENDING) return; // no need to watch anymore connectToServiceClass(serviceClass, endpointName, local, CS_ASYNCHRONOUS); } void ZmqNamedProxy:: onEndpointNodeChange(const std::string & path, ConfigurationService::ChangeType change) { if (connectionState != CONNECTION_PENDING) return; // no need to watch anymore connect(connectedService, CS_ASYNCHRONOUS); } /******************************************************************************/ /* ZMQ MULTIPLE NAMED CLIENT BUS PROXY */ /******************************************************************************/ void ZmqMultipleNamedClientBusProxy:: connectAllServiceProviders(const std::string & serviceClass, const std::string & endpointName, bool local) { if (connected) { THROW(ZmqLogs::error) << "already connected to " << serviceClass << " / " << endpointName << std::endl; } this->serviceClass = serviceClass; this->endpointName = endpointName; serviceProvidersWatch.init([=] (const std::string & path, ConfigurationService::ChangeType change) { ++changesCount[change]; onServiceProvidersChanged("serviceClass/" + serviceClass, local); }); onServiceProvidersChanged("serviceClass/" + serviceClass, local); connected = true; } /** Zookeeper makes the onServiceProvidersChanged calls re-entrant which is annoying to deal with. Instead, when a re-entrant call is detected we defer the call until we're done with the original call. */ bool ZmqMultipleNamedClientBusProxy:: enterProvidersChanged(const std::string& path, bool local) { std::lock_guard<ML::Spinlock> guard(providersChangedLock); if (!inProvidersChanged) { inProvidersChanged = true; return true; } LOG(ZmqLogs::trace) << "defering providers changed for " << path << std::endl; deferedProvidersChanges.emplace_back(path, local); return false; } void ZmqMultipleNamedClientBusProxy:: exitProvidersChanged() { std::vector<DeferedProvidersChanges> defered; { std::lock_guard<ML::Spinlock> guard(providersChangedLock); defered = std::move(deferedProvidersChanges); inProvidersChanged = false; } for (const auto& item : defered) onServiceProvidersChanged(item.first, item.second); } void ZmqMultipleNamedClientBusProxy:: onServiceProvidersChanged(const std::string & path, bool local) { if (!enterProvidersChanged(path, local)) return; // The list of service providers has changed std::vector<std::string> children = config->getChildren(path, serviceProvidersWatch); for (auto c: children) { Json::Value value = config->getJson(path + "/" + c); std::string name = value["serviceName"].asString(); std::string path = value["servicePath"].asString(); std::string location = value["serviceLocation"].asString(); if (local && location != config->currentLocation) { LOG(ZmqLogs::trace) << path << " / " << name << " dropped (" << location << " != " << config->currentLocation << ")" << std::endl; continue; } watchServiceProvider(name, path); } // deleting the connection could trigger a callback which is a bad idea // while we're holding the connections lock. So instead we move all the // connections to be deleted to a temp map which we'll wipe once the // lock is released. ConnectionMap pendingDisconnects; { std::unique_lock<Lock> guard(connectionsLock); // Services that are no longer in zookeeper are considered to be // disconnected so remove them from our connection map. for (auto& conn : connections) { auto it = find(children.begin(), children.end(), conn.first); if (it != children.end()) continue; // Erasing from connections in this loop would invalidate our // iterator so defer until we're done with the connections map. removeSource(conn.second.get()); pendingDisconnects[conn.first] = std::move(conn.second); } for (const auto& conn : pendingDisconnects) connections.erase(conn.first); } // We're no longer holding the lock so any delayed. Time to really // disconnect and trigger the callbacks. pendingDisconnects.clear(); exitProvidersChanged(); } /** Encapsulates a lock-free state machine that manages the logic of the on config callback. The problem being solved is that the onConnect callback should not call the user's callback while we're holding the connection lock but should do it when the lock is released. The lock-free state machine guarantees that no callbacks are lost and that no callbacks will be triggered before a call to release is made. The overhead of this class amounts to at most 2 CAS when the callback is triggered; one if there's no contention. Note that this isn't an ideal solution to this problem because we really should get rid of the locks when manipulating these events. \todo could be generalized if we need this pattern elsewhere. */ struct ZmqMultipleNamedClientBusProxy::OnConnectCallback { OnConnectCallback(const ConnectionHandler& fn, std::string name) : fn(fn), name(name), state(DEFER) {} /** Should ONLY be called AFTER the lock is released. */ void release() { State old = state; ExcAssertNotEqual(old, CALL); // If the callback wasn't triggered while we were holding the lock // then trigger it the next time we see it. if (old == DEFER && ML::cmp_xchg(state, old, CALL)) return; ExcAssertEqual(old, DEFERRED); fn(name); } void operator() (std::string blah) { State old = state; ExcAssertNotEqual(old, DEFERRED); // If we're still in the locked section then trigger the callback // when release is called. if (old == DEFER && ML::cmp_xchg(state, old, DEFERRED)) return; // We're out of the locked section so just trigger the callback. ExcAssertEqual(old, CALL); fn(name); } private: ConnectionHandler fn; std::string name; enum State { DEFER, // We're holding the lock so defer an incoming callback. DEFERRED, // We were called while holding the lock. CALL // We were not called while holding the lock. } state; }; void ZmqMultipleNamedClientBusProxy:: watchServiceProvider(const std::string & name, const std::string & path) { // Protects the connections map... I think. std::unique_lock<Lock> guard(connectionsLock); auto & c = connections[name]; // already connected if (c) { LOG(ZmqLogs::trace) << path << " / " << name << " is already connected" << std::endl; return; } LOG(ZmqLogs::trace) << "connecting to " << path << " / " << name << std::endl; try { auto newClient = std::make_shared<ZmqNamedClientBusProxy>(zmqContext); newClient->init(config, identity); // The connect call below could trigger this callback while we're // holding the connectionsLock which is a big no-no. This fancy // wrapper ensures that it's only called after we call its release // function. if (connectHandler) newClient->connectHandler = OnConnectCallback(connectHandler, name); newClient->disconnectHandler = [=] (std::string s) { // TODO: chain in so that we know it's not around any more this->onDisconnect(s); }; newClient->connect(path + "/" + endpointName); newClient->messageHandler = [=] (const std::vector<std::string> & msg) { this->handleMessage(name, msg); }; c = std::move(newClient); // Add it to our message loop so that it can process messages addSource("ZmqMultipleNamedClientBusProxy child " + name, c); guard.unlock(); if (connectHandler) c->connectHandler.target<OnConnectCallback>()->release(); } catch (...) { // Avoid triggering the disconnect callbacks while holding the // connectionsLock by defering the delete of the connection until // we've manually released the lock. ConnectionMap::mapped_type conn(std::move(connections[name])); connections.erase(name); guard.unlock(); // conn is a unique_ptr so it gets destroyed here. throw; } } } // namespace Datacratic
29.410974
91
0.563585
oktal
e86fa29433ef1ba27d0011d69c29eb071d1e5777
19,559
cpp
C++
src/sgcmc.cpp
sinamoeini/mapp4py
923ef57ee5bdb6231bec2885c09a58993b6c0f1f
[ "MIT" ]
3
2018-06-06T05:43:36.000Z
2020-07-18T14:31:37.000Z
src/sgcmc.cpp
sinamoeini/mapp4py
923ef57ee5bdb6231bec2885c09a58993b6c0f1f
[ "MIT" ]
null
null
null
src/sgcmc.cpp
sinamoeini/mapp4py
923ef57ee5bdb6231bec2885c09a58993b6c0f1f
[ "MIT" ]
7
2018-01-16T03:21:20.000Z
2020-07-20T19:36:13.000Z
/*-------------------------------------------- Created by Sina on 06/05/13. Copyright (c) 2013 MIT. All rights reserved. --------------------------------------------*/ #include "elements.h" #include "sgcmc.h" #include "memory.h" #include "random.h" #include "neighbor_md.h" #include "ff_md.h" #include "xmath.h" #include "atoms_md.h" #include "MAPP.h" #include "dynamic_md.h" using namespace MAPP_NS; /*-------------------------------------------- constructor --------------------------------------------*/ SGCMC::SGCMC(AtomsMD*& __atoms,ForceFieldMD*&__ff,DynamicMD*& __dynamic,int __m,elem_type __gas_type,type0 __mu,type0 __T,int seed): GCMC(__atoms,__ff,__dynamic,__gas_type,__mu,__T,seed), m(__m) { s_x_buff=NULL; head_atm=NULL; cell_coord_buff=NULL; n_cells=0; /*-------------------------------------------------- find the relative neighbor list for cells here we figure out the number of neighboring cells and also allocate the memory for rel_neigh_lst and rel_neigh_lst_coord. values for rel_neigh_lst_coord is assigned here,but finding the values for rel_neigh_lst requires knowledge of the box and domain, it will be differed to create() --------------------------------------------------*/ int countr[__dim__]; for(int i=0;i<__dim__;i++) countr[i]=-m; int max_no_neighs=1; for(int i=0;i<__dim__;i++) max_no_neighs*=2*m+1; nneighs=0; rel_neigh_lst_coord=new int[max_no_neighs*__dim__]; int* rel_neigh_lst_coord_=rel_neigh_lst_coord; int sum; int rc_sq=m*m; for(int i=0;i<max_no_neighs;i++) { sum=0; for(int j=0;j<__dim__;j++) { sum+=countr[j]*countr[j]; if(countr[j]!=0) sum+=1-2*std::abs(countr[j]); } if(sum<rc_sq) { for(int j=0;j<__dim__;j++) rel_neigh_lst_coord_[j]=countr[j]; rel_neigh_lst_coord_+=__dim__; nneighs++; } countr[0]++; for(int j=0;j<__dim__-1;j++) if(countr[j]==m+1) { countr[j]=-m; countr[j+1]++; } } rel_neigh_lst_coord_=new int[nneighs*__dim__]; memcpy(rel_neigh_lst_coord_,rel_neigh_lst_coord,nneighs*__dim__*sizeof(int)); delete [] rel_neigh_lst_coord; rel_neigh_lst_coord=rel_neigh_lst_coord_; } /*-------------------------------------------- destructor --------------------------------------------*/ SGCMC::~SGCMC() { delete [] rel_neigh_lst_coord; } /*-------------------------------------------- --------------------------------------------*/ void SGCMC::init() { dof_empty=atoms->x_dof->is_empty(); GCMC::init(); MPI_Scan(&ngas_lcl,&ngas_before,1,MPI_INT,MPI_SUM,world); ngas_before-=ngas_lcl; box_setup(); vars=new type0[ff->gcmc_n_vars]; lcl_vars=new type0[ff->gcmc_n_vars]; } /*-------------------------------------------- --------------------------------------------*/ void SGCMC::fin() { delete [] vars; delete [] lcl_vars; box_dismantle(); GCMC::fin(); } /*-------------------------------------------- --------------------------------------------*/ void SGCMC::box_setup() { GCMC::box_setup(); n_cells=1; for(int i=0;i<__dim__;i++) { cell_size[i]=cut_s[i]/static_cast<type0>(m); N_cells[i]=static_cast<int>((s_hi[i]-s_lo[i])/cell_size[i])+1; B_cells[i]=n_cells; n_cells*=N_cells[i]; } head_atm=new int[n_cells]; cell_coord_buff=new int[max_ntrial_atms*__dim__]; s_x_buff=new type0[__dim__*max_ntrial_atms]; } /*-------------------------------------------- --------------------------------------------*/ void SGCMC::box_dismantle() { delete [] head_atm; delete [] cell_coord_buff; delete [] s_x_buff; head_atm=NULL; cell_coord_buff=NULL; s_x_buff=NULL; n_cells=0; } /*-------------------------------------------- construct the bin list --------------------------------------------*/ void SGCMC::xchng(bool chng_box,int nattmpts) { curr_comm=&world; curr_root=0; dynamic->init_xchng(); if(chng_box) box_setup(); /*-------------------------------------------------- here we allocate the memory for cell_vec & next_vec --------------------------------------------------*/ if(ff->gcmc_tag_enabled) tag_vec_p=new Vec<int>(atoms,1); else tag_vec_p=NULL; cell_vec_p=new Vec<int>(atoms,1); next_vec_p=new Vec<int>(atoms,1); s_vec_p=new Vec<type0>(atoms,__dim__); memcpy(s_vec_p->begin(),atoms->x->begin(),sizeof(type0)*natms_lcl*__dim__); /*-------------------------------------------------- here we reset head_atm --------------------------------------------------*/ for(int i=0;i<n_cells;i++) head_atm[i]=-1; /*-------------------------------------------------- here we assign values for cell_vec, next_vec & headt_atm; it is supposed that we have fractional coordinates at this point --------------------------------------------------*/ int* next_vec=next_vec_p->begin(); int* cell_vec=cell_vec_p->begin(); type0* s=atoms->x->begin()+(natms_lcl-1)*__dim__; for(int i=natms_lcl-1;i>-1;i--,s-=__dim__) { find_cell_no(s,cell_vec[i]); next_vec[i]=head_atm[cell_vec[i]]; head_atm[cell_vec[i]]=i; } ff->neighbor->create_list(chng_box); ff->init_xchng(); for(int i=0;i<atoms->ndynamic_vecs;i++) atoms->dynamic_vecs[i]->resize(natms_lcl); ngas_lcl=0; elem_type* elem=atoms->elem->begin(); for(int i=0;i<natms_lcl;i++) if(elem[i]==gas_type) ngas_lcl++; MPI_Scan(&ngas_lcl,&ngas_before,1,MPI_INT,MPI_SUM,world); MPI_Allreduce(&ngas_lcl,&ngas,1,MPI_INT,MPI_SUM,world); ngas_before-=ngas_lcl; next_jatm_p=&SGCMC::next_jatm_reg; dof_diff=0; for(int i=0;i<nattmpts;i++) attmpt(); ff->fin_xchng(); memcpy(atoms->x->begin(),s_vec_p->begin(),sizeof(type0)*natms_lcl*__dim__); delete tag_vec_p; delete s_vec_p; delete next_vec_p; delete cell_vec_p; dynamic->fin_xchng(); } /*-------------------------------------------- this must be used only for local atoms --------------------------------------------*/ inline void SGCMC::find_cell_no(type0*& s,int& cell_no) { cell_no=0; for(int i=0;i<__dim__;i++) cell_no+=B_cells[i]*MIN(static_cast<int>((s[i]-s_lo[i])/cell_size[i]),N_cells[i]-1); } /*-------------------------------------------- --------------------------------------------*/ inline void SGCMC::find_cell_coord(type0*& s,int*& cell_coord) { for(int i=0;i<__dim__;i++) { if(s[i]<s_lo[i]) cell_coord[i]=-static_cast<int>((s_lo[i]-s[i])/cell_size[i])-1; else if(s_hi[i]<=s[i]) cell_coord[i]=MAX(static_cast<int>((s[i]-s_lo[i])/cell_size[i]),N_cells[i]-1); else cell_coord[i]=MIN(static_cast<int>((s[i]-s_lo[i])/cell_size[i]),N_cells[i]-1); } } /*-------------------------------------------- attempt an insertion --------------------------------------------*/ void SGCMC::attmpt() { if(random->uniform()<0.5) { xchng_mode=INS_MODE; im_root=true; int iproc=-1; for(int i=0;i<__dim__;i++) { s_buff[i]=random->uniform(); if(s_buff[i]<s_lo[i] || s_buff[i]>=s_hi[i]) im_root=false; } if(im_root) iproc=atoms->comm_rank; MPI_Allreduce(&iproc,&curr_root,1,MPI_INT,MPI_MAX,world); } else { if(ngas==0) return; xchng_mode=DEL_MODE; igas=static_cast<int>(ngas*random->uniform()); int iproc=-1; im_root=false; if(ngas_before<=igas && igas<ngas_before+ngas_lcl) { im_root=true; iproc=atoms->comm_rank; int n=igas-ngas_before; int icount=-1; elem_type* elem=atoms->elem->begin(); del_idx=0; for(;icount!=n;del_idx++) if(elem[del_idx]==gas_type) icount++; del_idx--; gas_id=atoms->id->begin()[del_idx]; memcpy(s_buff,s_vec_p->begin()+del_idx*__dim__,__dim__*sizeof(type0)); } MPI_Allreduce(&iproc,&curr_root,1,MPI_INT,MPI_MAX,world); MPI_Bcast(s_buff,__dim__,Vec<type0>::MPI_T,curr_root,world); MPI_Bcast(&gas_id,1,MPI_INT,curr_root,world); } prep_s_x_buff(); if(tag_vec_p) reset_tag(); ff->pre_xchng_energy_timer(this); delta_u=ff->xchng_energy_timer(this); MPI_Bcast(&delta_u,1,Vec<type0>::MPI_T,curr_root,world); type0 fac; root_succ=false; if(xchng_mode==INS_MODE) { fac=z_fac*vol/((static_cast<type0>(ngas)+1.0)*exp(beta*delta_u)); if(random->uniform()<fac) { root_succ=true; ins_succ(); ff->post_xchng_energy_timer(this); } } else { fac=static_cast<type0>(ngas)*exp(beta*delta_u)/(z_fac*vol); if(random->uniform()<fac) { root_succ=true; del_succ(); ff->post_xchng_energy_timer(this); } } } /*-------------------------------------------- things to do after a successful insertion --------------------------------------------*/ void SGCMC::ins_succ() { int new_id=get_new_id(); for(int i=0;i<__dim__;i++) vel_buff[i]=random->gaussian()*sigma; if(im_root) { atoms->add(); memcpy(atoms->x->begin()+(natms_lcl-1)*__dim__,s_x_buff,__dim__*sizeof(type0)); memcpy(atoms->x_d->begin()+(natms_lcl-1)*__dim__,vel_buff,__dim__*sizeof(type0)); atoms->elem->begin()[natms_lcl-1]=gas_type; atoms->id->begin()[natms_lcl-1]=new_id; if(tag_vec_p) tag_vec_p->begin()[natms_lcl-1]=-1; if(!dof_empty) { bool* dof=atoms->x_dof->begin()+(natms_lcl-1)*__dim__; for(int i=0;i<__dim__;i++) dof[i]=true; } memcpy(s_vec_p->begin()+(natms_lcl-1)*__dim__,s_buff,__dim__*sizeof(type0)); int cell_=0; for(int i=0;i<__dim__;i++) cell_+=B_cells[i]*cell_coord_buff[i]; cell_vec_p->begin()[natms_lcl-1]=cell_; int* nxt_p=head_atm+cell_; while(*nxt_p!=-1) nxt_p=next_vec_p->begin()+*nxt_p; *nxt_p=natms_lcl-1; next_vec_p->begin()[natms_lcl-1]=-1; ngas_lcl++; } else { if(atoms->comm_rank>curr_root) ngas_before++; } dof_diff+=__dim__; ngas++; atoms->natms++; } /*-------------------------------------------- things to do after a successful deletion --------------------------------------------*/ void SGCMC::del_succ() { add_del_id(&gas_id,1); if(im_root) { /*-------------------------------------------------- 0.0 find the link to del_idx --------------------------------------------------*/ int* p_2_idx=head_atm+cell_vec_p->begin()[del_idx]; while(*p_2_idx!=del_idx) p_2_idx=next_vec_p->begin()+*p_2_idx; /*-------------------------------------------------- 0.1 replace link to del_idx with link from del_idx --------------------------------------------------*/ *p_2_idx=next_vec_p->begin()[del_idx]; if(del_idx!=natms_lcl-1) { /*-------------------------------------------------- 1.0 find the first link to after del_idx --------------------------------------------------*/ int* p_2_first_aft_del=head_atm+cell_vec_p->begin()[natms_lcl-1]; while(*p_2_first_aft_del<del_idx) p_2_first_aft_del=next_vec_p->begin()+*p_2_first_aft_del; /*-------------------------------------------------- 1.1 find the link to natms_lcl-1 --------------------------------------------------*/ int* p_2_last=p_2_first_aft_del; while(*p_2_last!=natms_lcl-1) p_2_last=next_vec_p->begin()+*p_2_last; /*-------------------------------------------------- 1.2 remove the link to natms_lcl-1 and end it ther --------------------------------------------------*/ *p_2_last=-1; /*-------------------------------------------------- 1.3 insert the new link at del_idx, but for now it is at natms_lcl-1 after the move operation which happens next it will go del_idx --------------------------------------------------*/ next_vec_p->begin()[natms_lcl-1]=*p_2_first_aft_del; *p_2_first_aft_del=del_idx; } atoms->del(del_idx); ngas_lcl--; } else { if(igas<ngas_before) ngas_before--; } dof_diff-=__dim__; ngas--; atoms->natms--; } /*-------------------------------------------- --------------------------------------------*/ void SGCMC::prep_s_x_buff() { im_root=true; for(int i=0;i<__dim__;i++) if(s_buff[i]<s_lo[i] || s_buff[i]>=s_hi[i]) im_root=false; int n_per_dim[__dim__]; type0 s; int no; ntrial_atms=1; for(int i=0;i<__dim__;i++) { no=0; s=s_buff[i]; for(type0 s_=s;s_<s_hi_ph[i];s_++) if(s_lo_ph[i]<=s_ && s_<s_hi_ph[i]) s_trials[i][no++]=s_; for(type0 s_=s-1.0;s_lo_ph[i]<=s_;s_--) if(s_lo_ph[i]<=s_ && s_<s_hi_ph[i]) s_trials[i][no++]=s_; ntrial_atms*=no; n_per_dim[i]=no; } int count[__dim__]; type0* buff=s_x_buff; int* cell_coord=cell_coord_buff; //type0 (&H)[__dim__][__dim__]=atoms->H; for(int i=0;i<__dim__;i++) count[i]=0; for(int i=0;i<ntrial_atms;i++) { for(int j=0;j<__dim__;j++) buff[j]=s_trials[j][count[j]]; find_cell_coord(buff,cell_coord); //XMatrixVector::s2x<__dim__>(buff,H); Algebra::S2X<__dim__>(atoms->__h,buff); count[0]++; for(int j=0;j<__dim__-1;j++) if(count[j]==n_per_dim[j]) { count[j]=0; count[j+1]++; } cell_coord+=__dim__; buff+=__dim__; } } /*-------------------------------------------- this is used for insertion trial --------------------------------------------*/ void SGCMC::reset_iatm() { itrial_atm=-1; next_iatm(); } /*-------------------------------------------- this is used for insertion trial --------------------------------------------*/ void SGCMC::next_iatm() { itrial_atm++; if(itrial_atm==ntrial_atms) { /*-------------------------------------------------- if we have reached the end of the list --------------------------------------------------*/ iatm=-1; return; } /*-------------------------------------------------- give the atom a number that cannot be the same as the existing ones: iatm=natms_lcl+natms_ph+itrial_atm; natms_lcl+natms_ph <= iatm iatm < natms_lcl+natms_ph+ntrial_atms --------------------------------------------------*/ if(itrial_atm==0 && im_root && xchng_mode==DEL_MODE) iatm=del_idx; else iatm=natms_lcl+itrial_atm; /*-------------------------------------------------- assign the cell number and the already calculated cell coordinates --------------------------------------------------*/ for(int i=0;i<__dim__;i++) icell_coord[i]=cell_coord_buff[__dim__*itrial_atm+i]; /*-------------------------------------------------- assign the position of iatm --------------------------------------------------*/ ix=s_x_buff+itrial_atm*__dim__; } /*-------------------------------------------- this is used for insertion trial --------------------------------------------*/ void SGCMC::reset_jatm() { ineigh=0; jatm_next=-1; next_jatm_reg(); } /*-------------------------------------------- find the next lcl atom --------------------------------------------*/ inline void SGCMC::next_jatm_reg() { while(true) { while(jatm_next==-1 && ineigh<nneighs) { bool lcl=true; jcell=0; for(int i=0;i<__dim__ && lcl;i++) { jcell_coord[i]=icell_coord[i]+rel_neigh_lst_coord[ineigh*__dim__+i]; jcell+=B_cells[i]*jcell_coord[i]; if(jcell_coord[i]<0 || jcell_coord[i]>N_cells[i]-1) lcl=false; } if(lcl) jatm_next=head_atm[jcell]; ineigh++; } jatm=jatm_next; if(jatm==-1) { if(itrial_atm==0 && im_root) { iself=0; next_jatm_p=&SGCMC::next_jatm_self; return next_jatm_self(); } else return; } jatm_next=next_vec_p->begin()[jatm]; if(jatm==iatm) continue; jx=atoms->x->begin()+__dim__*jatm; jelem=atoms->elem->begin()[jatm]; rsq=Algebra::RSQ<__dim__>(ix,jx); if(rsq>=cut_sq[ielem][jelem]) continue; if(tag_vec_p) tag_vec_p->begin()[jatm]=icomm; return; } } /*-------------------------------------------- find the next interactin image atom --------------------------------------------*/ inline void SGCMC::next_jatm_self() { while(true) { iself++; if(iself==ntrial_atms) { next_jatm_p=&SGCMC::next_jatm_reg; jatm=-1; return; } jatm=natms_lcl+iself; jx=s_x_buff+iself*__dim__; jelem=gas_type; rsq=Algebra::RSQ<__dim__>(ix,jx); if(rsq>=cut_sq[ielem][jelem]) continue; return; } } /*-------------------------------------------- find the next interactin image atom --------------------------------------------*/ void SGCMC::next_jatm() { (this->*next_jatm_p)(); } /*-------------------------------------------- --------------------------------------------*/ void SGCMC::next_icomm() { icomm=-1; } /*-------------------------------------------- --------------------------------------------*/ void SGCMC::reset_icomm() { icomm=0; } /*-------------------------------------------- --------------------------------------------*/ inline void SGCMC::refresh() { for(int i=0;i<n_cells;i++) head_atm[i]=-1; int* next_vec=next_vec_p->begin()+natms_lcl-1; int* cell_vec=cell_vec_p->begin()+natms_lcl-1; for(int i=natms_lcl-1;i>-1;i--,next_vec--,cell_vec--) { *next_vec=head_atm[*cell_vec]; head_atm[*cell_vec]=i; } } /*-------------------------------------------- --------------------------------------------*/ void SGCMC::reset_tag() { int* tag=tag_vec_p->begin(); for(int i=0;i<natms_lcl;i++) tag[i]=-1; }
28.387518
132
0.448029
sinamoeini
e871800708f2bfcd67139cb614c0a8abff434087
2,214
cpp
C++
source/procedural_objects/triangulate_geometry.cpp
diegoarjz/selector
976abd0d9e721639e6314e2599ef7e6f3dafdc4f
[ "MIT" ]
12
2019-04-16T17:35:53.000Z
2020-04-12T14:37:27.000Z
source/procedural_objects/triangulate_geometry.cpp
diegoarjz/selector
976abd0d9e721639e6314e2599ef7e6f3dafdc4f
[ "MIT" ]
47
2019-05-27T15:24:43.000Z
2020-04-27T17:54:54.000Z
source/procedural_objects/triangulate_geometry.cpp
diegoarjz/selector
976abd0d9e721639e6314e2599ef7e6f3dafdc4f
[ "MIT" ]
null
null
null
#include "triangulate_geometry.h" #include "procedural_object_system.h" #include "geometry_component.h" #include "geometry_system.h" #include "hierarchical_component.h" #include "hierarchical_system.h" #include "procedural_component.h" #include "geometry_operations/ear_clipping.h" #include <memory> namespace pagoda { const std::string TriangulateGeometry::sInputGeometry("in"); const std::string TriangulateGeometry::sOutputGeometry("out"); const char* TriangulateGeometry::name = "TriangulateGeometry"; TriangulateGeometry::TriangulateGeometry(ProceduralObjectSystemPtr objectSystem) : ProceduralOperation(objectSystem) { START_PROFILE; CreateInputInterface(sInputGeometry); CreateOutputInterface(sOutputGeometry); } TriangulateGeometry::~TriangulateGeometry() {} void TriangulateGeometry::DoWork() { START_PROFILE; auto geometrySystem = m_proceduralObjectSystem->GetComponentSystem<GeometrySystem>(); auto hierarchicalSystem = m_proceduralObjectSystem->GetComponentSystem<HierarchicalSystem>(); EarClipping<Geometry> earClipping; while (HasInput(sInputGeometry)) { // Geometry ProceduralObjectPtr inObject = GetInputProceduralObject(sInputGeometry); ProceduralObjectPtr outObject = CreateOutputProceduralObject(sOutputGeometry); std::shared_ptr<GeometryComponent> inGeometryComponent = geometrySystem->GetComponentAs<GeometryComponent>(inObject); std::shared_ptr<GeometryComponent> outGeometryComponent = geometrySystem->CreateComponentAs<GeometryComponent>(outObject); GeometryPtr inGeometry = inGeometryComponent->GetGeometry(); auto outGeometry = std::make_shared<Geometry>(); earClipping.Execute(inGeometry, outGeometry); outGeometryComponent->SetGeometry(outGeometry); outGeometryComponent->SetScope(inGeometryComponent->GetScope()); // Hierarchy std::shared_ptr<HierarchicalComponent> inHierarchicalComponent = hierarchicalSystem->GetComponentAs<HierarchicalComponent>(inObject); std::shared_ptr<HierarchicalComponent> outHierarchicalComponent = hierarchicalSystem->GetComponentAs<HierarchicalComponent>(outObject); hierarchicalSystem->SetParent(outHierarchicalComponent, inHierarchicalComponent); } } } // namespace pagoda
32.558824
116
0.81617
diegoarjz
e87b6f023edd43aad0befbe7aec559d135808a55
5,116
cpp
C++
NativeCode/Plugin_SpatializerReverb.cpp
PStewart95/Unity
f80b7d47dd98fa11a9fa6fd7eb1191d5fdf0f331
[ "MIT" ]
58
2020-03-05T09:20:59.000Z
2022-03-31T10:06:20.000Z
NativeCode/Plugin_SpatializerReverb.cpp
PStewart95/Unity
f80b7d47dd98fa11a9fa6fd7eb1191d5fdf0f331
[ "MIT" ]
5
2021-01-18T12:47:27.000Z
2022-03-08T08:41:06.000Z
NativeCode/Plugin_SpatializerReverb.cpp
PStewart95/Unity
f80b7d47dd98fa11a9fa6fd7eb1191d5fdf0f331
[ "MIT" ]
13
2020-09-14T09:50:41.000Z
2022-02-08T15:53:33.000Z
// Simple Velvet-noise based reverb just to demonstrate how to send data from Spatializer to a common mix buffer that is routed into the mixer. #include "AudioPluginUtil.h" float reverbmixbuffer[65536] = { 0 }; namespace SpatializerReverb { const int MAXTAPS = 1024; enum { P_DELAYTIME, P_DIFFUSION, P_NUM }; struct InstanceChannel { struct Tap { int pos; float amp; }; struct Delay { enum { MASK = 0xFFFFF }; int writepos; inline void Write(float x) { writepos = (writepos + MASK) & MASK; data[writepos] = x; } inline float Read(int delay) const { return data[(writepos + delay) & MASK]; } float data[MASK + 1]; }; Tap taps[1024]; Delay delay; }; struct EffectData { float p[P_NUM]; Random random; InstanceChannel ch[2]; }; int InternalRegisterEffectDefinition(UnityAudioEffectDefinition& definition) { int numparams = P_NUM; definition.paramdefs = new UnityAudioParameterDefinition[numparams]; RegisterParameter(definition, "Delay Time", "", 0.0f, 5.0f, 2.0f, 1.0f, 1.0f, P_DELAYTIME, "Delay time in seconds"); RegisterParameter(definition, "Diffusion", "%", 0.0f, 1.0f, 0.5f, 100.0f, 1.0f, P_DIFFUSION, "Diffusion amount"); return numparams; } UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK CreateCallback(UnityAudioEffectState* state) { EffectData* effectdata = new EffectData; memset(effectdata, 0, sizeof(EffectData)); state->effectdata = effectdata; InitParametersFromDefinitions(InternalRegisterEffectDefinition, effectdata->p); return UNITY_AUDIODSP_OK; } UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK ReleaseCallback(UnityAudioEffectState* state) { EffectData* data = state->GetEffectData<EffectData>(); delete data; return UNITY_AUDIODSP_OK; } UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK SetFloatParameterCallback(UnityAudioEffectState* state, int index, float value) { EffectData* data = state->GetEffectData<EffectData>(); if (index >= P_NUM) return UNITY_AUDIODSP_ERR_UNSUPPORTED; data->p[index] = value; return UNITY_AUDIODSP_OK; } UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK GetFloatParameterCallback(UnityAudioEffectState* state, int index, float* value, char *valuestr) { EffectData* data = state->GetEffectData<EffectData>(); if (index >= P_NUM) return UNITY_AUDIODSP_ERR_UNSUPPORTED; if (value != NULL) *value = data->p[index]; if (valuestr != NULL) valuestr[0] = 0; return UNITY_AUDIODSP_OK; } int UNITY_AUDIODSP_CALLBACK GetFloatBufferCallback(UnityAudioEffectState* state, const char* name, float* buffer, int numsamples) { return UNITY_AUDIODSP_OK; } UNITY_AUDIODSP_RESULT UNITY_AUDIODSP_CALLBACK ProcessCallback(UnityAudioEffectState* state, float* inbuffer, float* outbuffer, unsigned int length, int inchannels, int outchannels) { if (inchannels != 2 || outchannels != 2) { memcpy(outbuffer, inbuffer, length * outchannels * sizeof(float)); return UNITY_AUDIODSP_OK; } EffectData* data = state->GetEffectData<EffectData>(); const float delaytime = data->p[P_DELAYTIME] * state->samplerate + 1.0f; const int numtaps = (int)(data->p[P_DIFFUSION] * (MAXTAPS - 2) + 1); data->random.Seed(0); for (int c = 0; c < 2; c++) { InstanceChannel& ch = data->ch[c]; const InstanceChannel::Tap* tap_end = ch.taps + numtaps; float decay = powf(0.01f, 1.0f / (float)numtaps); float p = 0.0f, amp = (decay - 1.0f) / (powf(decay, numtaps + 1) - 1.0f); InstanceChannel::Tap* tap = ch.taps; while (tap != tap_end) { p += data->random.GetFloat(0.0f, 100.0f); tap->pos = p; tap->amp = amp; amp *= decay; ++tap; } float scale = delaytime / p; tap = ch.taps; while (tap != tap_end) { tap->pos *= scale; ++tap; } for (int n = 0; n < length; n++) { ch.delay.Write(inbuffer[n * 2 + c] + reverbmixbuffer[n * 2 + c]); float s = 0.0f; const InstanceChannel::Tap* tap = ch.taps; while (tap != tap_end) { s += ch.delay.Read(tap->pos) * tap->amp; ++tap; } outbuffer[n * 2 + c] = s; } } memset(reverbmixbuffer, 0, sizeof(reverbmixbuffer)); return UNITY_AUDIODSP_OK; } }
31.006061
184
0.561572
PStewart95
e87d53d3851d9e31961506fc18709be8060bb742
16,313
hpp
C++
include/gb/cpu.inc.hpp
nfsu/gb
bfbed4c0effa541fac1ed48e79544f054b8c7376
[ "MIT" ]
null
null
null
include/gb/cpu.inc.hpp
nfsu/gb
bfbed4c0effa541fac1ed48e79544f054b8c7376
[ "MIT" ]
null
null
null
include/gb/cpu.inc.hpp
nfsu/gb
bfbed4c0effa541fac1ed48e79544f054b8c7376
[ "MIT" ]
null
null
null
namespace gb { //Debugging template<bool isCb, typename ...args> _inline_ void Emulator::operation(const args &...arg) { oic::System::log()->debug(oic::Log::concat(std::hex, arg...), "\t\t; $", oic::Log::concat(std::hex, pc - 1 - isCb)); } const char *crName[] = { "b", "c", "d", "e", "h", "l", "(hl)", "a" }; const char *addrRegName[] = { "bc", "de", "hl+", "hl-" }; const char *shortRegName[] = { "bc", "de", "hl", "sp" }; const char *shortRegNameAf[] = { "bc", "de", "hl", "af" }; const char *aluName[] = { "add", "adc", "sub", "sbc", "and", "xor", "or", "cp" }; const char *condName[] = { "nz", "z", "nc", "c", "" }; //Function for setting a cr template<u8 cr, typename T> _inline_ void Emulator::set(const T &t) { m; if constexpr (cr != 6) regs[registerMapping[cr]] = t; else m.set(hl, t); } template<u8 c, typename T> _inline_ void Emulator::setc(const T &t) { set<(c >> 3) & 7>(t); } //Function for getting a cr template<u8 cr, typename T> _inline_ T Emulator::get() { m; if constexpr (cr == 6) return m.get<T>(hl); else if constexpr ((cr & 0x8) != 0) { const T t = m.get<T>(pc); pc += sizeof(T); return t; } else return regs[registerMapping[cr]]; } template<u8 c, typename T> _inline_ T Emulator::getc() { return get<c & 7, T>(); } //Special instructions _inline_ usz Emulator::halt() { //TODO: HALT operation("halt"); return 1; } _inline_ usz Emulator::stop() { //TODO: Stop operation("stop"); return 1; } template<bool enable, usz flag> _inline_ void Emulator::setFlag() { if constexpr (enable) m.getMemory<u8>(flag >> 8) |= flag & 0xFF; else m.getMemory<u8>(flag >> 8) &= ~(flag & 0xFF); } template<usz flag> _inline_ bool Emulator::getFlag() { return m.getMemory<u8>(flag >> 8) & (flag & 0xFF); } template<usz flag> _inline_ bool Emulator::getFlagFromAddress() { return m.getRef<u8>(flag >> 8) & (flag & 0xFF); } //LD operations //LD cr, cr template<u8 c> _inline_ usz Emulator::ld() { operation("ld ", crName[(c >> 3) & 7], ",", crName[c & 7]); setc<c, u8>(getc<c, u8>()); return (c & 0x7) == 6 || ((c >> 3) & 7) == 6 ? 2 : 1; } //LD cr, (pc) template<u8 s> _inline_ u16 Emulator::addrFromReg() { if constexpr (s < 2) return lregs[s]; else if constexpr (s == 2) { ++hl; return hl - 1; } else { --hl; return hl + 1; } } template<u8 c> _inline_ usz Emulator::ldi() { //LD cr, #8 if constexpr ((c & 7) == 6) { u8 v = get<8, u8>(); operation("ld ", crName[(c >> 3) & 7], ",", u16(v)); setc<c>(v); } //LD (nn), A else if constexpr ((c & 0xF) == 2) { operation("ld (", addrRegName[c >> 4], "),a"); m[addrFromReg<u8(c >> 4)>()] = a; } //LD A, (nn) else { operation("ld a,(", addrRegName[c >> 4], ")"); a = m[addrFromReg<u8(c >> 4)>()]; } return c == 0x36 ? 3 : 2; } //LD A, (a16) / LD (a16), A template<u8 c> _inline_ usz Emulator::lds() { operation("ld ", shortRegName[c / 16], ",", m.get<u16>(pc)); shortReg<c>() = m.get<u16>(pc); pc += 2; return 3; } //All alu operations (ADD/ADC/SUB/SUBC/AND/XOR/OR/CP) template<u8 c> _inline_ usz Emulator::performAlu(u8 b) { static constexpr u8 code = c & 0x3F; if constexpr (code < 0x08) emu::addTo(f, a, b); else if constexpr (code < 0x10) emu::adcTo(f, a, b); else if constexpr (code < 0x18) emu::subFrom(f, a, b); else if constexpr (code < 0x20) emu::sbcFrom(f, a, b); else if constexpr (code < 0x28) emu::andInto(f, a, b); else if constexpr (code < 0x30) emu::eorInto(f, a, b); else if constexpr (code < 0x38) emu::orrInto(f, a, b); else emu::sub(f, a, b); return 1; } template<u8 c> _inline_ usz Emulator::aluOp() { //(HL) or (pc) if constexpr ((c & 7) == 6) { if constexpr (c < 0xC0) { operation(aluName[(c >> 3) & 7], " a,(hl)"); return performAlu<c>(m[hl]); } else { operation(aluName[(c >> 3) & 7], " a,", u16(m[pc])); usz v = performAlu<c>(m[pc]); ++pc; return v; } } //Reg ALU else { operation(aluName[(c >> 3) & 7], " a,", crName[c & 7]); return performAlu<c>(regs[c & 7]); } } //RST x instruction template<u8 addr> _inline_ usz Emulator::reset() { operation("rst ", u16(addr)); Stack::push(m, sp, pc); pc = addr; return 4; } template<u8 c> _inline_ usz Emulator::rst() { return reset<(c & 0x30) | (c & 0x8)>(); } //Condtional calls template<u8 c> _inline_ bool Emulator::cond() { static constexpr u8 condition = (c >> 3) & 3; if constexpr (condition == 0) return !f.zero(); else if constexpr (condition == 1) return f.zero(); else if constexpr (condition == 2) return !f.carry(); else return f.carry(); } //JR/JP calls template<u8 jp, u8 check> _inline_ usz Emulator::branch() { //Print operation if constexpr ((jp & 3) == 3) operation("ret", jp & 8 ? "i" : " ", check != 0 ? condName[(check >> 3) & 3] : ""); else if constexpr (inRegion<jp & 3, 1, 3>) operation((jp & 3) == 1 ? "jp " : "call ", check != 0 ? condName[(check >> 3) & 3] : "", check != 0 ? "," : "", jp & 4 ? "(hl)" : oic::Log::num<16>(m.get<u16>(pc)) ); else if constexpr ((jp & 3) == 0) operation("jr ", check != 0 ? condName[(check >> 3) & 3] : "", check != 0 ? "," : "", i32(m.get<i8>(pc)) ); //Jump if check failed if constexpr (check != 0) if (!cond<check>()) { //2-width instructions if constexpr (inRegion<jp & 3, 1, 3>) { pc += 2; return 3; } //1-width instructions else if constexpr ((jp & 3) == 0) { ++pc; return 2; } else return 2; } //RET if constexpr ((jp & 3) == 3) { Stack::pop(m, sp, pc); if constexpr ((jp & 8) != 0) //RETI setFlag<true, Emulator::IME>(); return check == 0 ? 4 : 5; } //JP/CALL else if constexpr (inRegion<jp & 3, 1, 3>) { //CALL if constexpr ((jp & 3) == 2) Stack::push(m, sp, pc + 2); if constexpr ((jp & 4) != 0) pc = m.get<u16>(hl); else pc = m.get<u16>(pc); return 2 + jp * 2; } //JR else { pc += u16(i16(m.get<i8>(pc))); ++pc; return 3; } } template<u8 c, u8 code> _inline_ usz Emulator::jmp() { if constexpr (c == 0x18) return branch<0, 0>(); //JR else if constexpr (c < 0x40) return branch<0, c>(); //JR conditional else if constexpr (c == 0xC3) return branch<1, 0>(); //JP else if constexpr (code == 2) return branch<1, c>(); //JP conditional else if constexpr (c == 0xCD) return branch<2, 0>(); //CALL else if constexpr (code == 4) return branch<2, c>(); //CALL conditional else if constexpr (c == 0xE9) return branch<5, 0>(); //JP (HL) else if constexpr (c == 0xC9) return branch<7, 0>(); //RET else if constexpr (c == 0xD9) return branch<15, 0>(); //RETI else return branch<3, c>(); //RET conditional } //INC/DEC x instructions template<u8 c> _inline_ usz Emulator::inc() { static constexpr u8 add = c & 1 ? u8_MAX : 1; static constexpr u8 r1 = (c >> 3) & 7; if constexpr ((c & 1) == 0) { operation("inc ", crName[r1]); f.clearSubtract(); } else { operation("dec ", crName[r1]); f.setSubtract(); } u8 v; if constexpr (r1 != 6) v = regs[registerMapping[r1]] += add; else v = m[hl] += add; f.carryHalf(v & 0x10); f.zero(v == 0); return r1 == 6 ? 3 : 1; } //Short register functions template<u8 c> _inline_ u16 &Emulator::shortReg() { if constexpr (((c >> 4) & 3) < 3) return lregs[c >> 4]; else return sp; } template<u8 c> _inline_ usz Emulator::incs() { static constexpr u16 add = c & 8 ? u16_MAX : 1; operation(c & 8 ? "dec " : "inc ", shortRegName[(c >> 4) & 3]); shortReg<c>() += add; return 2; } //Every case runs through this template<u8 c, u8 start, u8 end> static constexpr bool inRegion = c >= start && c < end; template<u8 c, u8 code, u8 hi> static constexpr bool isJump = (inRegion<c, 0x18, 0x40> && code == 0) || //JR (inRegion<c, 0xC0, 0xE0> && ( //JP/RET/CALL code == 0 || //RET conditional code == 2 || //JP conditional code == 4 || //CALL conditional c == 0xC3 || //JP hi == 9 || //RET/RETI c == 0xCD //CALL )) || c == 0xE9; //JP (HL) enum OpCode : u8 { NOP = 0x00, STOP = 0x10, HALT = 0x76, DI = 0xF3, EI = 0xFB }; template<u8 c> _inline_ usz Emulator::opCb() { static constexpr u8 p = (c >> 3) & 7; static constexpr u8 cr = c & 7; //Barrel shifts if constexpr (c < 0x40) { f.clearSubtract(); f.clearHalf(); u8 i = get<cr, u8>(), j = i; j; //RLC (rotate to the left) if constexpr (p == 0) { operation("rlc ", crName[cr]); a = i = u8(i << 1) | u8(i >> 7); } //RRC (rotate to the right) else if constexpr (p == 1) { operation("rrc ", crName[cr]); a = i = u8(i >> 1) | u8(i << 7); } //RL (<<1 shift in carry) else if constexpr (p == 2) { operation("rl ", crName[cr]); a = i = (i << 1) | u8(f.carry()); } //RR (>>1 shift in carry) else if constexpr (p == 3) { operation("rr ", crName[cr]); a = i = (i >> 1) | u8(0x80 * f.carry()); } //SLA (a = cr << 1) else if constexpr (p == 4) { operation("sla ", crName[cr]); a = i <<= 1; } //SRA (a = cr >> 1 (maintain sign)) else if constexpr (p == 5) { operation("sra ", crName[cr]); a = i = (i >> 1) | (i & 0x80); } //Swap two nibbles else if constexpr (p == 6) { operation("swap ", crName[cr]); a = i = u8(i << 4) | (i >> 4); } //SRL else { operation("srl ", crName[cr]); a = i >>= 1; } //Set carry if constexpr ((p & 1) == 1) //Shifted to the left f.carry(j & 1); else if constexpr (p < 6) //Shifted to the right f.carry(j & 0x80); else //N.A. f.clearCarry(); //Set zero f.zero(i == 0); } //Bit masks else if constexpr (c < 0x80) { operation<true>("bit ", std::to_string(p), ",", crName[cr]); f.setHalf(); f.clearSubtract(); f.zero(!(get<cr, u8>() & (1 << p))); } //Reset bit else if constexpr (c < 0xC0) { operation<true>("res ", std::to_string(p), ",", crName[cr]); set<cr, u8>(get<cr, u8>() & ~(1 << p)); } //Set bit else { operation<true>("set ", std::to_string(p), ",", crName[cr]); set<cr, u8>(get<cr, u8>() | (1 << p)); } return cr == 6 ? 4 : 2; } template<u8 i> _inline_ usz Emulator::op256() { static constexpr u8 code = i & 0x07, hi = i & 0xF; if constexpr (i == NOP) { operation("nop"); return 1; } else if constexpr (i == STOP) return stop(); else if constexpr (i == HALT) return halt(); //DI/EI; disable/enable interrupts else if constexpr (i == DI || i == EI) { operation(i == DI ? "di" : "ei"); setFlag<i == EI, Emulator::IME>(); return 1; } //LD (a16), SP instruction; TODO: else if constexpr (i == 0x8) { m.set(m.get<u16>(pc), sp); pc += 2; return 5; } //RET, JP, JR and CALL else if constexpr (isJump<i, code, hi>) return jmp<i, code>(); //RLCA, RLA, RRCA, RRA else if constexpr (i < 0x20 && code == 7) return opCb<i>(); else if constexpr (i < 0x40) { if constexpr (hi == 1) return lds<i>(); else if constexpr (hi == 0x9) { operation("add hl,", shortRegName[(i >> 4) & 3]); u16 hl_ = hl; hl += shortReg<i>(); f.clearSubtract(); f.carryHalf(hl & 0x10); f.carry(hl < hl_); return 2; } else if constexpr (code == 3) return incs<i>(); else if constexpr (code == 4 || code == 5) return inc<i>(); else if constexpr (code == 2 || code == 6) return ldi<i>(); //SCF, CCF else if constexpr (i == 0x37 || i == 0x3F) { operation(i == 0x37 ? "scf" : "ccf"); f.clearSubtract(); f.clearHalf(); if constexpr (i == 0x37) f.setCarry(); else f.carry(!f.carry()); return 1; } //CPL else if constexpr (i == 0x2F) { operation("cpl"); f.setSubtract(); f.setHalf(); a = ~a; return 1; } //DAA else if constexpr (i == 0x27) { operation("daa"); u8 k = 0, j = a; f.clearCarry(); if (f.carryHalf() || (!f.subtract() && (j & 0xF) > 0x9)) k |= 0x6; if (f.carry() || (!f.subtract() && j > 0x99)) { k |= 0x60; f.setCarry(); } a = j += u8(-i8(k)); f.clearHalf(); f.zero(j == 0); return 1; } //TODO: LD (a16), SP else throw std::exception(); } else if constexpr (i < 0x80) return ld<i>(); else if constexpr (i < 0xC0 || code == 0x6) return aluOp<i>(); else if constexpr (code == 0x7) return rst<i>(); //LD (a8/a16/C)/A, (a8/a16/C)/A else if constexpr (i >= 0xE0 && (hi == 0x0 || hi == 0x2 || hi == 0xA)) { u16 addr; //TODO: ??? if constexpr (hi == 0x0) { const u8 im = m[pc]; operation( "ldh ", i < 0xF0 ? oic::Log::num<16>((u16)im) : "a", ",", i >= 0xF0 ? oic::Log::num<16>((u16)im) : "a" ); addr = 0xFF00 | im; ++pc; } else if constexpr (hi == 0x2) { operation("ld ", i < 0xF0 ? "(c)," : "a,", i >= 0xF0 ? "(c)" : "a"); addr = 0xFF00 | c; } else { const u16 j = m.get<u16>(pc); operation( "ld ", i < 0xF0 ? oic::Log::num<16>(j) : "a", ",", i >= 0xF0 ? oic::Log::num<16>(j) : "a" ); addr = j; pc += 2; } if constexpr (i < 0xF0) //Store m[addr] = a; else //Load a = m[addr]; return 1; } //CB instructions (mask, reset, set, rlc/rrc/rl/rr/sla/sra/swap/srl) else if constexpr (i == 0xCB) return cbInstruction(); //PUSH/POP else if constexpr (hi == 1 || hi == 5) { static constexpr u8 reg = (i - 0xC0) >> 4; operation(hi == 1 ? "pop " : "push ", shortRegNameAf[reg]); //Push to or pop from stack if constexpr (hi == 1) Stack::pop(m, sp, lregs[reg]); else Stack::push(m, sp, lregs[reg]); return hi == 1 ? 3 : 4; } //LD HL, SP+a8 else if constexpr (i == 0xF8) { operation("ld hl, sp+", u16(m[pc])); hl = emu::add(f, sp, u16(m[pc])); ++pc; f.clearZero(); return 3; } //TODO: ADD SP, r8 //TODO: LD HL, SP+a8 //TODO: LD SP, HL else //Undefined operation throw std::exception(); } //Switch case of all opcodes //For our switch case of 256 entries #define case1(x,y) case x: return op##y<x>(); #define case2(x,y) case1(x,y) case1(x + 1,y) #define case4(x,y) case2(x,y) case2(x + 2,y) #define case8(x,y) case4(x,y) case4(x + 4,y) #define case16(x,y) case8(x,y) case8(x + 8,y) #define case32(x,y) case16(x,y) case16(x + 16,y) #define case64(x,y) case32(x,y) case32(x + 32,y) #define case128(x,y) case64(x,y) case64(x + 64,y) #define case256(y) case128(0,y) case128(128,y) _inline_ usz Emulator::cbInstruction() { u8 opCode = m[pc]; print(u16(opCode), '\t'); ++pc; switch (opCode) { case256(Cb) } return 0; } _inline_ usz Emulator::cpuStep() { u8 &mem = m.getMemory<u8>(Emulator::IS_IN_BIOS >> 8); constexpr u8 bit = Emulator::IS_IN_BIOS & 0xFF; if (mem & bit && pc >= MemoryMapper::biosLength) mem &= ~bit; u8 opCode = m[pc]; print(std::hex, pc, ' ', u16(opCode), '\t'); ++pc; switch (opCode) { case256(256) } return 0; } _inline usz Emulator::interruptHandler() { #ifndef NDEBUG print( u16(a), " ", u16(b), " ", u16(c), " ", u16(d), " ", u16(e), " ", u16(f.v), " ", sp, "\n" ); /*if((pc >= 0x2A0 && pc < 0x2795) || pc >= 0x27A3) system("pause");*/ #endif usz counter {}; if (getFlag<Emulator::IME>()) { u8 &u = m.getRef<u8>(io::IF); const u8 &enabled = m.getRef<u8>(io::IE); const u8 g = u & enabled; u &= ~g; //Mark as handled if (g) setFlag<false, Emulator::IME>(); if (g & 1) //V-Blank counter += reset<0x40>(); if (g & 2) //LCD STAT counter += reset<0x48>(); if (g & 4) //Timer counter += reset<0x50>(); if (g & 8) //Serial counter += reset<0x58>(); if (g & 16) //Joypad counter += reset<0x60>(); } return counter; } }
19.443385
118
0.518482
nfsu
e87e40bb54d3ff3333c68a07c392b39b4763d71b
4,492
cpp
C++
commandsFonts.cpp
SamuraiCrow/AmosKittens
e89477b94a28916e4320fa946c18c0d769c710b2
[ "MIT" ]
7
2018-04-24T22:11:58.000Z
2021-09-10T22:12:35.000Z
commandsFonts.cpp
SamuraiCrow/AmosKittens
e89477b94a28916e4320fa946c18c0d769c710b2
[ "MIT" ]
36
2018-02-24T18:34:18.000Z
2021-08-08T10:33:29.000Z
commandsFonts.cpp
SamuraiCrow/AmosKittens
e89477b94a28916e4320fa946c18c0d769c710b2
[ "MIT" ]
2
2018-10-22T18:47:30.000Z
2020-09-16T06:10:52.000Z
#include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <string> #include <iostream> #include <vector> #include <string> #ifdef __amigaos4__ #include <proto/exec.h> #include <proto/exec.h> #include <proto/dos.h> #include <proto/diskfont.h> #include <proto/graphics.h> #include <proto/retroMode.h> #include "amosString.h" extern struct RastPort font_render_rp; #endif #ifdef __linux__ #include "os/linux/stuff.h" #endif #include <amosKittens.h> #include <stack.h> #include "debug.h" #include "commandsFonts.h" #include "kittyErrors.h" #include "engine.h" extern struct TextFont *open_font( char const *filename, int size ); extern struct TextFont *gfx_font ; using namespace std; class font { public: string amosString; string name; int size; }; vector<font> fonts; void set_font_buffer( char *buffer, char *name, int size, char *type ) { char *c; char *b; int n; memset(buffer,' ',37); // char 0 to 36 buffer[37]=0; n = 0; b = buffer; for (c=name;(*c) && (n<37);c++) { *b++=*c; n++; } n = 0; b = buffer+37-4; for (c=type;(*c) && (n<4);c++) { *b++=*c; n++; } b = buffer+37-6; while (size) { n = size % 10; size /=10; *b-- = n + '0'; } } void getfonts(char *buffer, int source_type ) { int32 afShortage, afSize; struct AvailFontsHeader *afh; struct AvailFonts *_fonts; font tfont; afSize = 400; do { afh = (struct AvailFontsHeader *) AllocVecTags(afSize, TAG_END); if (afh) { afShortage = AvailFonts( (char *) afh, afSize, AFF_MEMORY | AFF_DISK); if (afShortage) { FreeVec(afh); afSize += afShortage; } else { int n; _fonts = (AvailFonts *) ((char *) afh + sizeof(uint16_t)); for (n=0;n<afh -> afh_NumEntries;n++) { if ((_fonts -> af_Type | source_type ) && (_fonts -> af_Attr.ta_Style == FS_NORMAL)) { set_font_buffer(buffer, (char *) _fonts -> af_Attr.ta_Name, _fonts -> af_Attr.ta_YSize, (char *) "disc"); tfont.amosString =buffer; tfont.name = _fonts -> af_Attr.ta_Name; tfont.size = _fonts -> af_Attr.ta_YSize; fonts.push_back(tfont); } _fonts++; } FreeVec(afh); } } else { printf("AllocMem of AvailFonts buffer afh failed\n"); break; } } while (afShortage); } char *fontsGetRomFonts(struct nativeCommand *cmd, char *tokenBuffer) { char buffer[39]; fonts.erase( fonts.begin(), fonts.end() ); getfonts( buffer, AFF_MEMORY ); return tokenBuffer; } char *fontsGetDiscFonts(struct nativeCommand *cmd, char *tokenBuffer) { char buffer[39]; fonts.erase( fonts.begin(), fonts.end() ); getfonts( buffer, AFF_DISK ); return tokenBuffer; } char *fontsGetAllFonts(struct nativeCommand *cmd, char *tokenBuffer) { char buffer[39]; fonts.erase( fonts.begin(), fonts.end() ); getfonts( buffer, AFF_DISK | AFF_MEMORY ); return tokenBuffer; } char *_fontsSetFont( struct glueCommands *data, int nextToken ) { int args =__stack - data->stack +1 ; int ret = 0; printf("%s:%d\n",__FUNCTION__,__LINE__); switch (args) { case 1: ret = getStackNum(__stack ) ; if ((ret>=0)&&(ret<=(int) fonts.size())) { if (gfx_font) CloseFont(gfx_font); gfx_font = open_font( fonts[ret].name.c_str(),fonts[ret].size ); engine_lock(); if (engine_ready()) { SetFont( &font_render_rp, gfx_font ); } engine_unlock(); } break; default: setError(22,data->tokenBuffer); } popStack(__stack - data->stack ); return NULL; } char *fontsSetFont(struct nativeCommand *cmd, char *tokenBuffer) { stackCmdNormal( _fontsSetFont, tokenBuffer ); setStackNone(); return tokenBuffer; } char *_fontsFontsStr( struct glueCommands *data, int nextToken ) { int args =__stack - data->stack +1 ; unsigned int index; string font; printf("%s:%d\n",__FUNCTION__,__LINE__); switch (args) { case 1: index = (unsigned int) getStackNum(__stack); if ((index>0) && (index <= fonts.size())) { popStack(__stack - data->stack ); setStackStr( toAmosString( fonts[ index-1 ].amosString.c_str(), strlen(fonts[ index-1 ].amosString.c_str()) ) ); return NULL; } break; default: setError(22,data->tokenBuffer); } popStack(__stack - data->stack ); setStackStrDup(toAmosString("",0)); return NULL; } char *fontsFontsStr(struct nativeCommand *cmd, char *tokenBuffer) { stackCmdParm( _fontsFontsStr, tokenBuffer ); setStackNone(); return tokenBuffer; }
18.716667
111
0.645147
SamuraiCrow
e88e8c7a26dee04f4f1b5749a556d436496df34e
1,614
cpp
C++
sentutil/chat.cpp
surrealwaffle/thesurrealwaffle
6937d8e2604628a5c9141feef837d89e81f68165
[ "BSL-1.0" ]
3
2018-07-20T23:04:45.000Z
2021-07-09T04:16:42.000Z
sentutil/chat.cpp
surrealwaffle/thesurrealwaffle
6937d8e2604628a5c9141feef837d89e81f68165
[ "BSL-1.0" ]
null
null
null
sentutil/chat.cpp
surrealwaffle/thesurrealwaffle
6937d8e2604628a5c9141feef837d89e81f68165
[ "BSL-1.0" ]
1
2018-07-21T06:32:13.000Z
2018-07-21T06:32:13.000Z
// Copyright surrealwaffle 2018 - 2020. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) #include <sentutil/chat.hpp> #include <cstdarg> // std::va_list #include <cstring> // std::strlen #include <cwchar> // std::vswprintf #include <iterator> // std::size #include <string> // std::wstring namespace { void send_chat_valist(int channel, const char* fmt, std::va_list args); void send_chat_wvalist(int channel, const wchar_t* fmt, std::va_list args); } // namespace (anonymous) namespace sentutil { namespace chat { void send_chat(utility::format_marker_type, int channel, const char* fmt, ...) { std::va_list args; va_start(args, fmt); send_chat_valist(channel, fmt, args); va_end(args); } void send_chat(utility::format_marker_type, const char* fmt, ...) { std::va_list args; va_start(args, fmt); send_chat_valist(0, fmt, args); va_end(args); } } } // namespace sentutil::chat namespace { void send_chat_valist(int channel, const char* fmt, va_list args) { std::wstring wfmt(fmt, fmt + std::strlen(fmt)); return send_chat_wvalist(channel, wfmt.c_str(), args); } void send_chat_wvalist(int channel, const wchar_t* fmt, va_list args) { wchar_t buf[0xFF]; buf[0xFE] = L'\0'; std::vswprintf(buf, std::size(buf) - 1, fmt, args); sentinel_Chat_SendChatToServer(channel, buf); } } // namespace (anonymous)
24.830769
76
0.639405
surrealwaffle
e895368d7b727dd0fcc78181bc264e55667dd1ed
907
cpp
C++
sicxe/sim/device.cpp
blaz-r/SIC-XE-simulator
c148657a120331eea26e137db219c0f60662a1e8
[ "MIT" ]
null
null
null
sicxe/sim/device.cpp
blaz-r/SIC-XE-simulator
c148657a120331eea26e137db219c0f60662a1e8
[ "MIT" ]
null
null
null
sicxe/sim/device.cpp
blaz-r/SIC-XE-simulator
c148657a120331eea26e137db219c0f60662a1e8
[ "MIT" ]
null
null
null
#include "device.h" #include <iostream> uint8_t InputDevice::read() { return inputStream.get(); } void OutputDevice::write(uint8_t value) { outputStream.write(reinterpret_cast<char*>(&value), 1); outputStream.flush(); } FileDevice::FileDevice(std::string file) { fileStream.open(file, std::fstream::in); if(!fileStream) { fileStream.open(file, std::fstream::out); } fileStream.close(); fileStream.open(file, std::fstream::out | std::fstream::in); } FileDevice::~FileDevice() { fileStream.close(); } uint8_t FileDevice::read() { if (fileStream.peek() == EOF) { return 0; } else { return fileStream.get(); } } void FileDevice::write(uint8_t value) { fileStream.write(reinterpret_cast<char*>(&value), 1); fileStream.flush(); } void FileDevice::reset() { fileStream.clear(); fileStream.seekg(0); }
16.490909
64
0.628445
blaz-r
e8999ac0e209fb7bb469a1ebd6d497d3929d8e97
6,515
cc
C++
homeworks/HierarchicalErrorEstimator/mastersolution/hierarchicalerrorestimator.cc
0xBachmann/NPDECODES
70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea
[ "MIT" ]
1
2022-02-22T10:59:19.000Z
2022-02-22T10:59:19.000Z
homeworks/HierarchicalErrorEstimator/mastersolution/hierarchicalerrorestimator.cc
0xBachmann/NPDECODES
70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea
[ "MIT" ]
null
null
null
homeworks/HierarchicalErrorEstimator/mastersolution/hierarchicalerrorestimator.cc
0xBachmann/NPDECODES
70a9d251033ab3d8719f0e221de4c2f4e9e8f4ea
[ "MIT" ]
null
null
null
/** * @ file * @ brief NPDE homework on hierarchical error estimation * @ author Ralf Hiptmair * @ date July 2021 * @ copyright Developed at SAM, ETH Zurich */ #include "hierarchicalerrorestimator.h" namespace HEST { /* SAM_LISTING_BEGIN_3 */ Eigen::VectorXd trfLinToQuad( std::shared_ptr<const lf::uscalfe::FeSpaceLagrangeO1<double>> fes_lin_p, std::shared_ptr<const lf::uscalfe::FeSpaceLagrangeO2<double>> fes_quad_p, const Eigen::VectorXd &mu) { using gdof_idx_t = lf::assemble::gdof_idx_t; // Obtain local-to-global index mappings const lf::assemble::DofHandler &dh_lin{fes_lin_p->LocGlobMap()}; const lf::assemble::DofHandler &dh_quad{fes_quad_p->LocGlobMap()}; LF_ASSERT_MSG(dh_lin.Mesh() == dh_quad.Mesh(), "DofHandlers must be based on the same mesh"); LF_ASSERT_MSG(dh_lin.NumDofs() == mu.size(), "Vector length mismath"); // Underlying mesh std::shared_ptr<const lf::mesh::Mesh> mesh_p{dh_lin.Mesh()}; const lf::mesh::Mesh &mesh{*mesh_p}; LF_ASSERT_MSG( (dh_lin.NumDofs() == mesh.NumEntities(2)) && (dh_quad.NumDofs() == mesh.NumEntities(2) + mesh.NumEntities(1)), "#DOFs do not match #entities"); // The coefficients of a FE function in the quadratic Lagrangian FE space with // respect to the nodal basis are simply its values at the nodes and the // midpoints of the edges. Eigen::VectorXd nu(dh_quad.NumDofs()); // Visit nodes (codimension =2) and copy values for (const lf::mesh::Entity *node : mesh.Entities(2)) { nonstd::span<const gdof_idx_t> lf_dof_idx{dh_lin.GlobalDofIndices(*node)}; LF_ASSERT_MSG(lf_dof_idx.size() == 1, "Exactly one LFE basis functiona at a node"); LF_ASSERT_MSG(lf_dof_idx[0] < dh_lin.NumDofs(), "LFE dof number too large"); nonstd::span<const gdof_idx_t> qf_dof_idx{dh_quad.GlobalDofIndices(*node)}; LF_ASSERT_MSG(lf_dof_idx.size() == 1, "Exactly one QFE basis functiona at a node"); LF_ASSERT_MSG(qf_dof_idx[0] < dh_quad.NumDofs(), "QFE dof number too large"); nu[qf_dof_idx[0]] = mu[lf_dof_idx[0]]; } // Run through all edges for (const lf::mesh::Entity *edge : mesh.Entities(1)) { // Obtain global numbers of LFE DOFs associated with the endpoints of // the edge, that is, of those DOFs covering the edge. nonstd::span<const gdof_idx_t> lf_dof_idx{dh_lin.GlobalDofIndices(*edge)}; LF_ASSERT_MSG(lf_dof_idx.size() == 2, "Exactly two basis functions must cover an edge"); LF_ASSERT_MSG((lf_dof_idx[0] < dh_lin.NumDofs()) && (lf_dof_idx[1] < dh_lin.NumDofs()), "LFE dof numbers too large"); // Obtain global number of QFE basis function associated with the edge nonstd::span<const gdof_idx_t> qf_dof_idx{ dh_quad.InteriorGlobalDofIndices(*edge)}; LF_ASSERT_MSG(qf_dof_idx.size() == 1, "A single QFE basis function is associated to an edge!"); LF_ASSERT_MSG(qf_dof_idx[0] < dh_quad.NumDofs(), "QFE dof number too large"); // Value of p.w. linear continuous FE function at the midpoint of the edge const double mp_val = (mu[lf_dof_idx[0]] + mu[lf_dof_idx[1]]) / 2.0; // Store value as appropriate coefficient nu[qf_dof_idx[0]] = mp_val; } return nu; } /* SAM_LISTING_END_3 */ std::tuple<double, double, double> solveAndEstimate( std::shared_ptr<const lf::mesh::Mesh> mesh_p) { // Note: the mesh must cover the unit square for this test setting ! // Create finite element space for p.w. linear Lagrangian FE std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO1<double>> lfe_space_p = std::make_shared<lf::uscalfe::FeSpaceLagrangeO1<double>>(mesh_p); std::shared_ptr<lf::uscalfe::FeSpaceLagrangeO2<double>> quad_space_p = std::make_shared<lf::uscalfe::FeSpaceLagrangeO2<double>>(mesh_p); // Define homogeneous Dirichlet boundary value problem // Diffusion coefficient function std::function<double(Eigen::Vector2d)> alpha = [](Eigen::Vector2d x) -> double { return (1.0 /* + x.squaredNorm() */); }; // Manufactured exact solution auto u_exact = [](Eigen::Vector2d x) -> double { return (x[0] * (1.0 - x[0]) * x[1] * (1.0 - x[1])); }; auto grad_u = [](Eigen::Vector2d x) -> Eigen::Vector2d { return ((Eigen::Vector2d() << (1 - 2 * x[0]) * x[1] * (1 - x[1]), x[0] * (1 - x[0]) * (1 - 2 * x[1])) .finished()); }; // Right-hand side matching exact solution auto f = [](Eigen::Vector2d x) -> double { return 2 * (x[1] * (1 - x[1]) + x[0] * (1 - x[0])); }; // Lambdas have to be wrapped into a mesh function for error computation lf::mesh::utils::MeshFunctionGlobal mf_u{u_exact}; lf::mesh::utils::MeshFunctionGlobal mf_grad_u{grad_u}; lf::mesh::utils::MeshFunctionGlobal mf_alpha{alpha}; lf::mesh::utils::MeshFunctionGlobal mf_f{f}; // Compute basis expansion coefficient vector of finite-element solution const Eigen::VectorXd mu{solveBVPWithLinFE(mf_alpha, mf_f, lfe_space_p)}; // Compute error norms // create MeshFunctions representing solution / gradient of LFE solution const lf::fe::MeshFunctionFE mf_sol(lfe_space_p, mu); const lf::fe::MeshFunctionGradFE mf_grad_sol(lfe_space_p, mu); // compute errors with 3rd order quadrature rules, which is sufficient for // piecewise linear finite elements double L2err = // NOLINT std::sqrt(lf::fe::IntegrateMeshFunction( *mesh_p, lf::mesh::utils::squaredNorm(mf_sol - mf_u), 2)); double H1serr = std::sqrt(lf::fe::IntegrateMeshFunction( // NOLINT *mesh_p, lf::mesh::utils::squaredNorm(mf_grad_sol - mf_grad_u), 2)); std::cout << "Mesh (" << mesh_p->NumEntities(0) << " cells, " << mesh_p->NumEntities(1) << " edges, " << mesh_p->NumEntities(2) << " nodes): L2err = " << L2err << ", H1serr = " << H1serr << std::endl; // Evaluate a-posteriori error estimator const Eigen::VectorXd nu = compHierSurplusSolution(mf_alpha, mf_f, lfe_space_p, quad_space_p, mu); // Compute H1-seminorm of solution in hierarchical surplus space const lf::fe::MeshFunctionGradFE mf_grad_hps(quad_space_p, nu); double hier_surplus_norm = std::sqrt(lf::fe::IntegrateMeshFunction( // NOLINT *mesh_p, lf::mesh::utils::squaredNorm(mf_grad_hps), 4)); std::cout << "Estimated error = " << hier_surplus_norm << std::endl; return {L2err, H1serr, hier_surplus_norm}; } // end solveAndEstimate } // namespace HEST
46.205674
80
0.666616
0xBachmann
e89edf4bc15b80365ab3ef7cc4313005917998e8
996
cpp
C++
sdl/Hypergraph/src/UseOpenFst.cpp
sdl-research/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
29
2015-01-26T21:49:51.000Z
2021-06-18T18:09:42.000Z
sdl/Hypergraph/src/UseOpenFst.cpp
hypergraphs/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
1
2015-12-08T15:03:15.000Z
2016-01-26T14:31:06.000Z
sdl/Hypergraph/src/UseOpenFst.cpp
hypergraphs/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
4
2015-11-21T14:25:38.000Z
2017-10-30T22:22:00.000Z
// Copyright 2014-2015 SDL plc // 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 <sdl/Hypergraph/UseOpenFst.hpp> #if HAVE_OPENFST #include <graehl/shared/warning_push.h> GCC6_DIAG_IGNORE(misleading-indentation) GCC_DIAG_IGNORE(uninitialized) GCC_DIAG_IGNORE(unused-local-typedefs) #include <lib/compat.cc> #include <lib/flags.cc> #include <lib/fst.cc> #include <lib/properties.cc> #include <lib/symbol-table.cc> #include <lib/util.cc> #include <graehl/shared/warning_pop.h> #endif
31.125
75
0.767068
sdl-research
e89fe7ec6cc06a497dbc6c11ed45b36c858ee463
598
cpp
C++
src/window_with_linux_gamepad.cpp
hissingshark/game-window
7d270d3ffc711ae4c66a014cd18ad5276cdbc0a4
[ "MIT" ]
4
2019-03-10T02:35:16.000Z
2021-02-20T17:57:17.000Z
src/window_with_linux_gamepad.cpp
hissingshark/game-window
7d270d3ffc711ae4c66a014cd18ad5276cdbc0a4
[ "MIT" ]
2
2020-06-28T09:28:37.000Z
2021-04-17T10:35:49.000Z
src/window_with_linux_gamepad.cpp
hissingshark/game-window
7d270d3ffc711ae4c66a014cd18ad5276cdbc0a4
[ "MIT" ]
7
2019-06-12T00:03:25.000Z
2021-07-29T13:06:32.000Z
#include "window_with_linux_gamepad.h" #include "joystick_manager_linux_gamepad.h" WindowWithLinuxJoystick::WindowWithLinuxJoystick(std::string const& title, int width, int height, GraphicsApi api) : GameWindow(title, width, height, api) { } WindowWithLinuxJoystick::~WindowWithLinuxJoystick() { LinuxGamepadJoystickManager::instance.removeWindow(this); } void WindowWithLinuxJoystick::addWindowToGamepadManager() { LinuxGamepadJoystickManager::instance.addWindow(this); } void WindowWithLinuxJoystick::updateGamepad() { LinuxGamepadJoystickManager::instance.update(this); }
33.222222
116
0.799331
hissingshark
e8a426d4b092a2a3bad7dd0e7f1f17ab34287675
3,363
hpp
C++
uActor/include/remote/remote_connection.hpp
uActor/uActor
1180db98f48ad447639a3d625573307d87b28902
[ "MIT" ]
1
2021-09-15T12:41:37.000Z
2021-09-15T12:41:37.000Z
uActor/include/remote/remote_connection.hpp
uActor/uActor
1180db98f48ad447639a3d625573307d87b28902
[ "MIT" ]
null
null
null
uActor/include/remote/remote_connection.hpp
uActor/uActor
1180db98f48ad447639a3d625573307d87b28902
[ "MIT" ]
null
null
null
#pragma once extern "C" { #include <arpa/inet.h> } #include <atomic> #include <cstdint> #include <cstring> #include <list> #include <map> #include <memory> #include <mutex> #include <queue> #include <set> #include <string> #include <unordered_map> #include <vector> #include "forwarder_api.hpp" #include "forwarding_strategy.hpp" #include "pubsub/publication_factory.hpp" #include "remote/sequence_info.hpp" #include "subscription_processors/subscription_processor.hpp" namespace uActor::Remote { class TCPForwarder; enum struct ConnectionRole : uint8_t { SERVER = 0, CLIENT = 1 }; class RemoteConnection { public: RemoteConnection(const RemoteConnection&) = delete; RemoteConnection& operator=(const RemoteConnection&) = delete; RemoteConnection(RemoteConnection&&) = default; RemoteConnection& operator=(RemoteConnection&&) = default; RemoteConnection(uint32_t local_id, int32_t socket_id, std::string remote_addr, uint16_t remote_port, ConnectionRole connection_role, ForwarderSubscriptionAPI* handle); ~RemoteConnection(); enum ProcessingState { empty, waiting_for_size, waiting_for_data, }; void handle_subscription_update_notification( const PubSub::Publication& update_message); void send_routing_info(); void process_data(uint32_t len, char* data); static std::map<std::string, std::string> local_location_labels; static std::list<std::vector<std::string>> clusters; private: uint32_t local_id; int sock = 0; // TCP Related // TODO(raphaelhetzel) potentially move this to a separate // wrapper once we have more types of forwarders std::string partner_ip; uint16_t partner_port; ConnectionRole connection_role; // Subscription related ForwarderSubscriptionAPI* handle; std::set<uint32_t> subscription_ids; uint32_t update_sub_id = 0; uint32_t local_sub_added_id = 0; uint32_t local_sub_removed_id = 0; uint32_t remote_subs_added_id = 0; uint32_t remote_subs_removed_id = 0; // Peer related std::string partner_node_id; std::map<std::string, std::string> partner_location_labels; uint32_t last_read_contact = 0; uint32_t last_write_contact = 0; std::vector<std::unique_ptr<SubscriptionProcessor>> egress_subscription_processors; // Connection statemachine ProcessingState state{empty}; int len = 0; std::vector<char> rx_buffer = std::vector<char>(512); // The size field may be split into multiple recvs char size_buffer[4]{0, 0, 0, 0}; uint32_t size_field_remaining_bytes{0}; uint32_t publicaton_remaining_bytes{0}; uint32_t publicaton_full_size{0}; PubSub::PublicationFactory publication_buffer = PubSub::PublicationFactory(); std::unique_ptr<ForwardingStrategy> forwarding_strategy; std::queue<std::shared_ptr<std::vector<char>>> write_buffer; size_t write_offset = 0; void process_remote_publication(PubSub::Publication&& p); void handle_local_subscription_removed(const PubSub::Publication& p); void handle_local_subscription_added(const PubSub::Publication& p); void handle_remote_subscriptions_removed(const PubSub::Publication& p); void handle_remote_subscriptions_added(const PubSub::Publication& p); void handle_remote_hello(PubSub::Publication&& p); friend uActor::Remote::TCPForwarder; }; } // namespace uActor::Remote
27.120968
79
0.749926
uActor
e8aab68527a7cd0ffa9fc714daad51ea18c92a75
134
hpp
C++
src/hardware/chips/stm32/stm32f103c4.hpp
xenris/nblib
72bf25b6d086bf6f6f3003d709f92a9975bfddaf
[ "MIT" ]
3
2016-03-31T04:41:32.000Z
2017-07-17T02:50:38.000Z
src/hardware/chips/stm32/stm32f103c4.hpp
xenris/nbavr
72bf25b6d086bf6f6f3003d709f92a9975bfddaf
[ "MIT" ]
18
2015-08-12T12:13:16.000Z
2017-05-10T12:55:55.000Z
src/hardware/chips/stm32/stm32f103c4.hpp
xenris/nblib
72bf25b6d086bf6f6f3003d709f92a9975bfddaf
[ "MIT" ]
null
null
null
#ifndef NBLIB_STM32F103C4_HPP #define NBLIB_STM32F103C4_HPP #include "stm32f103t4.hpp" #undef CHIP #define CHIP stm32f103c4 #endif
13.4
29
0.820896
xenris
e8aae74fc176487bb56981bc58fab4197dd93a2a
8,390
hpp
C++
ufora/core/Logging.hpp
ufora/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
571
2015-11-05T20:07:07.000Z
2022-01-24T22:31:09.000Z
ufora/core/Logging.hpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
218
2015-11-05T20:37:55.000Z
2021-05-30T03:53:50.000Z
ufora/core/Logging.hpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
40
2015-11-07T21:42:19.000Z
2021-05-23T03:48:19.000Z
/*************************************************************************** Copyright 2015 Ufora 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. ****************************************************************************/ #pragma once #include <ostream> #include <stdio.h> #include <sstream> #include "cppml/CPPMLPrettyPrinter.hppml" enum LogLevel { LOG_LEVEL_DEBUG = 0, LOG_LEVEL_INFO, LOG_LEVEL_WARN, LOG_LEVEL_ERROR, LOG_LEVEL_CRITICAL, LOG_LEVEL_TEST }; #define LOG_LEVEL_SCOPED(scope) \ ([]() { \ static LogLevel** shouldLog = \ Ufora::Logging::getScopedLoggingLevelHandle(scope, __FILE__); \ return **shouldLog; \ }()) #define SHOULD_LOG_DEBUG_SCOPED(scope) (LOG_LEVEL_SCOPED(scope) <= LOG_LEVEL_DEBUG) #define SHOULD_LOG_INFO_SCOPED(scope) (LOG_LEVEL_SCOPED(scope) <= LOG_LEVEL_INFO) #define SHOULD_LOG_WARN_SCOPED(scope) (LOG_LEVEL_SCOPED(scope) <= LOG_LEVEL_WARN) #define SHOULD_LOG_ERROR_SCOPED(scope) (LOG_LEVEL_SCOPED(scope) <= LOG_LEVEL_ERROR) #define SHOULD_LOG_CRITICAL_SCOPED(scope) (LOG_LEVEL_SCOPED(scope) <= LOG_LEVEL_CRITICAL) #define SHOULD_LOG_TEST_SCOPED(scope) (LOG_LEVEL_SCOPED(scope) <= LOG_LEVEL_TEST) #define SHOULD_LOG_DEBUG() SHOULD_LOG_DEBUG_SCOPED("") #define SHOULD_LOG_INFO() SHOULD_LOG_INFO_SCOPED("") #define SHOULD_LOG_WARN() SHOULD_LOG_WARN_SCOPED("") #define SHOULD_LOG_ERROR() SHOULD_LOG_ERROR_SCOPED("") #define SHOULD_LOG_CRITICAL() SHOULD_LOG_CRITICAL_SCOPED("") #define SHOULD_LOG_TEST() SHOULD_LOG_TEST_SCOPED("") #define LOG_DEBUG if(!SHOULD_LOG_DEBUG()) ; else (::Ufora::Logging::Logger(LOG_LEVEL_DEBUG, __FILE__, __LINE__)) #define LOG_INFO if(!SHOULD_LOG_INFO()) ; else ::Ufora::Logging::Logger(LOG_LEVEL_INFO, __FILE__, __LINE__) #define LOG_WARN if(!SHOULD_LOG_WARN()) ; else (::Ufora::Logging::Logger(LOG_LEVEL_WARN, __FILE__, __LINE__)) #define LOG_ERROR if(!SHOULD_LOG_ERROR()) ; else (::Ufora::Logging::Logger(LOG_LEVEL_ERROR, __FILE__, __LINE__)) #define LOG_CRITICAL if(!SHOULD_LOG_CRITICAL()) ; else (::Ufora::Logging::Logger(LOG_LEVEL_CRITICAL, __FILE__, __LINE__)) #define LOG_TEST if(!SHOULD_LOG_TEST()) ; else (::Ufora::Logging::Logger(LOG_LEVEL_TEST, __FILE__, __LINE__)) #define LOG_DEBUG_SCOPED(scope) if(!SHOULD_LOG_DEBUG_SCOPED(scope)) ; else (::Ufora::Logging::Logger(LOG_LEVEL_DEBUG, __FILE__, __LINE__)) #define LOG_INFO_SCOPED(scope) if(!SHOULD_LOG_INFO_SCOPED(scope)) ; else ::Ufora::Logging::Logger(LOG_LEVEL_INFO, __FILE__, __LINE__) #define LOG_WARN_SCOPED(scope) if(!SHOULD_LOG_WARN_SCOPED(scope)) ; else (::Ufora::Logging::Logger(LOG_LEVEL_WARN, __FILE__, __LINE__)) #define LOG_ERROR_SCOPED(scope) if(!SHOULD_LOG_ERROR_SCOPED(scope)) ; else (::Ufora::Logging::Logger(LOG_LEVEL_ERROR, __FILE__, __LINE__)) #define LOG_CRITICAL_SCOPED(scope) if(!SHOULD_LOG_CRITICAL_SCOPED(scope)) ; else (::Ufora::Logging::Logger(LOG_LEVEL_CRITICAL, __FILE__, __LINE__)) #define LOG_TEST_SCOPED(scope) if(!SHOULD_LOG_TEST_SCOPED(scope)) ; else (::Ufora::Logging::Logger(LOG_LEVEL_TEST, __FILE__, __LINE__)) #define LOGGER_DEBUG ::Ufora::Logging::Logger(LOG_LEVEL_DEBUG, __FILE__, __LINE__, SHOULD_LOG_DEBUG()) #define LOGGER_INFO ::Ufora::Logging::Logger(LOG_LEVEL_INFO, __FILE__, __LINE__, SHOULD_LOG_INFO()) #define LOGGER_WARN ::Ufora::Logging::Logger(LOG_LEVEL_WARN, __FILE__, __LINE__, SHOULD_LOG_WARN()) #define LOGGER_ERROR ::Ufora::Logging::Logger(LOG_LEVEL_ERROR, __FILE__, __LINE__, SHOULD_LOG_ERROR()) #define LOGGER_CRITICAL ::Ufora::Logging::Logger(LOG_LEVEL_CRITICAL, __FILE__, __LINE__, SHOULD_LOG_CRITICAL()) #define LOGGER_TEST ::Ufora::Logging::Logger(LOG_LEVEL_TEST, __FILE__, __LINE__, SHOULD_LOG_TEST()) #define LOGGER_DEBUG_SCOPED(scope) ::Ufora::Logging::Logger(LOG_LEVEL_DEBUG, __FILE__, __LINE__, SHOULD_LOG_DEBUG_SCOPED(scope)) #define LOGGER_INFO_SCOPED(scope) ::Ufora::Logging::Logger(LOG_LEVEL_INFO, __FILE__, __LINE__, SHOULD_LOG_INFO_SCOPED(scope)) #define LOGGER_WARN_SCOPED(scope) ::Ufora::Logging::Logger(LOG_LEVEL_WARN, __FILE__, __LINE__, SHOULD_LOG_WARN_SCOPED(scope)) #define LOGGER_ERROR_SCOPED(scope) ::Ufora::Logging::Logger(LOG_LEVEL_ERROR, __FILE__, __LINE__, SHOULD_LOG_ERROR_SCOPED(scope)) #define LOGGER_CRITICAL_SCOPED(scope) ::Ufora::Logging::Logger(LOG_LEVEL_CRITICAL, __FILE__, __LINE__, SHOULD_LOG_CRITICAL_SCOPED(scope)) #define LOGGER_TEST_SCOPED(scope) ::Ufora::Logging::Logger(LOG_LEVEL_TEST, __FILE__, __LINE__, SHOULD_LOG_TEST_SCOPED(scope)) #define LOGGER_DEBUG_T ::Ufora::Logging::Logger #define LOGGER_INFO_T ::Ufora::Logging::Logger #define LOGGER_WARN_T ::Ufora::Logging::Logger #define LOGGER_ERROR_T ::Ufora::Logging::Logger #define LOGGER_CRITICAL_T ::Ufora::Logging::Logger #define LOGGER_TEST_T ::Ufora::Logging::Logger namespace Ufora { namespace Logging { using LogWriter = std::function<void(LogLevel level, const char* filename, int lineNumber, const std::string& message)>; void setLogLevel(LogLevel logLevel); class Logger { public: static void setLogWriter(LogWriter writer); static void logToStream(std::ostream& stream, LogLevel level, const char* filename, int lineNumber, const std::string& message); Logger(LogLevel logLevel, const char * file, int line, bool shouldLog = true); Logger(const Logger& other); ~Logger(); Logger& operator<<(const bool& in) { mStringstream << in; return *this; } Logger& operator<<(const int8_t& in) { mStringstream << in; return *this; } Logger& operator<<(const int16_t& in) { mStringstream << in; return *this; } Logger& operator<<(const int32_t& in) { mStringstream << in; return *this; } Logger& operator<<(const int64_t& in) { mStringstream << in; return *this; } Logger& operator<<(const uint8_t& in) { mStringstream << in; return *this; } Logger& operator<<(const uint16_t& in) { mStringstream << in; return *this; } Logger& operator<<(const uint32_t& in) { mStringstream << in; return *this; } Logger& operator<<(const uint64_t& in) { mStringstream << in; return *this; } Logger& operator<<(const double& in) { mStringstream << in; return *this; } Logger& operator<<(const float& in) { mStringstream << in; return *this; } Logger& operator<<(const std::string& in) { mStringstream << in; return *this; } Logger& operator<<(const char* in) { mStringstream << in; return *this; } Logger& operator<<( std::ostream&(*streamer)(std::ostream& ) ); Logger& operator<<( std::ios_base&(*streamer)(std::ios_base& ) ); Logger& operator<<(const decltype(std::setw(0))& t) { mStringstream << t; return *this; } Logger& operator<<(const decltype(std::setprecision(0))& t) { mStringstream << t; return *this; } template<class T> Logger& operator<<(const T& t) { mStringstream << prettyPrintString(t); return *this; } static std::string logLevelToString(LogLevel level); private: static LogWriter logWriter; const char* mFileName; int mLineNumber; LogLevel mLogLevel; std::ostringstream mStringstream; bool mShouldLog; }; LogLevel** getScopedLoggingLevelHandle(const char* scope, const char* file); void setScopedLoggingLevel(std::string scopeRegex, std::string fileRegex, LogLevel logLevel); void resetScopedLoggingLevelToDefault(std::string scopeRegex, std::string fileRegex); } }
34.958333
147
0.682598
ufora
e8ba1a2fb6a73ff12564cd09de787c50e025df4f
3,625
cpp
C++
test/sandbox/test_digraph.cpp
wataro/midso
8190ac06b2cf391d69c3db49f32147831ba39f5d
[ "MIT" ]
null
null
null
test/sandbox/test_digraph.cpp
wataro/midso
8190ac06b2cf391d69c3db49f32147831ba39f5d
[ "MIT" ]
null
null
null
test/sandbox/test_digraph.cpp
wataro/midso
8190ac06b2cf391d69c3db49f32147831ba39f5d
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include <algorithm> #include <memory> #include <vector> template<typename T_> using Vector = std::vector<T_>; template<typename T1_, typename T2_> using Pair = std::pair<T1_, T2_>; template<typename T_> using Pointer = std::shared_ptr<T_>; template<typename T_> class Layer { public: typedef T_ Value; Layer(const T_ & value): value_(value) {} const T_ & output(void) const { return this->value_; } void set_input(const T_ & value) { this->input_values_.push_back(value); } void propagate(void) { for(auto v: this->input_values_) { std::cout << this->value_ << " <- " << v << std::endl; } this->input_values_.clear(); } private: Vector<Value> input_values_; Value value_; }; template<typename T_> struct Vertex_ { typedef T_ Item; typedef Vertex_<Item> Vertex; Vertex_(Item key, Item value): key_(key), depends_(1, value){} Item key_; Vector<Item> depends_; }; template<typename T_> class Graph { public: typedef T_ Item; typedef Pair<Item, Item> Arc; typedef Vertex_<Item> Vertex; Graph(Vector<Arc> & arcs) : arcs_(arcs) { this->build_dependencies(); } Vector<Vertex> & vertices() { return this->vertices_; } static Vector<Arc> reversed_arcs(Vector<Arc> & arcs) { Vector<Arc> arcs_rev(arcs.rbegin(), arcs.rend()); for(auto & arc: arcs_rev) { std::swap(arc.first, arc.second); } return arcs_rev; } private: void build_dependencies() { if (this->arcs_.empty()) { return; } for(auto arc: this->arcs_) { auto key = arc.second; auto it = std::find_if(this->vertices_.begin(), this->vertices_.end(), [key](const Vertex & v) { return v.key_ == key; }); if (this->vertices_.end() == it) { auto value = arc.first; this->vertices_.push_back(Vertex(key, value)); } else { auto value = arc.first; it->depends_.push_back(value); } } } Vector<Arc> arcs_; Vector<Vertex> vertices_; }; TEST(SANDBOX, DIGRAPH) { /* * [0] -- [1] --+-- [2] -- [4] --+-- [5] * | | * +-- [3] ---------+ * */ Layer<char> layers[] = {'0', '1', '2', '3', '4', '5'}; Graph<Layer<char>*>::Arc arc_array[] = { std::make_pair(layers + 0, layers + 1), std::make_pair(layers + 1, layers + 2), std::make_pair(layers + 1, layers + 3), std::make_pair(layers + 2, layers + 4), std::make_pair(layers + 3, layers + 5), std::make_pair(layers + 4, layers + 5), }; Vector<typename Graph<Layer<char>*>::Arc> arcs; arcs.push_back(arc_array[0]); arcs.push_back(arc_array[1]); arcs.push_back(arc_array[2]); arcs.push_back(arc_array[3]); arcs.push_back(arc_array[4]); arcs.push_back(arc_array[5]); Graph<Layer<char>*> digraph(arcs); for(auto vertex: digraph.vertices()) { for(auto depend: vertex.depends_) { vertex.key_->set_input(depend->output()); } vertex.key_->propagate(); } arcs = Graph<Layer<char>*>::reversed_arcs(arcs); Graph<Layer<char>*> digraph_rev(arcs); for(auto vertex: digraph_rev.vertices()) { for(auto depend: vertex.depends_) { vertex.key_->set_input(depend->output()); } vertex.key_->propagate(); } }
26.459854
86
0.543448
wataro
e8c1780e18d20c5b439240af585541cf69438cb1
6,089
cpp
C++
STEPVis.cpp
steptools/STEPGraph
e35712e9572e836ca8a7c4db40e54c97c9f08079
[ "Apache-2.0" ]
10
2015-07-23T14:51:11.000Z
2021-06-11T17:37:27.000Z
STEPVis.cpp
steptools/STEPGraph
e35712e9572e836ca8a7c4db40e54c97c9f08079
[ "Apache-2.0" ]
null
null
null
STEPVis.cpp
steptools/STEPGraph
e35712e9572e836ca8a7c4db40e54c97c9f08079
[ "Apache-2.0" ]
4
2015-09-08T01:55:18.000Z
2017-12-24T15:14:36.000Z
#include <rose.h> #include <stp_schema.h> using namespace System; void markme(RoseObject * obj); void graphaddnode(Microsoft::Msagl::Drawing::Graph^ graph, String^ out, String^ in, String^ name=""); void graphatts(RoseObject* obj, Microsoft::Msagl::Drawing::Graph^ graph); void parsetonode(RoseObject*parent, RoseObject*child, String^ attstr, Microsoft::Msagl::Drawing::Graph^ graph); void graphdepth(RoseObject* obj, Microsoft::Msagl::Drawing::Graph^ graph, int depth = 0); int maxdepth = 0; int main(int argc, char ** argv) { if (argc < 3) { Console::WriteLine("Usage: STEPVis.exe [step file to map] [depth]"); return -1; } int depth; try { String ^ depthstr = gcnew String(argv[2]); depth = Convert::ToInt32(depthstr); } catch (Exception^) { Console::WriteLine("invalid depth parameter."); return -1; } maxdepth = depth; ROSE.quiet(ROSE_TRUE); FILE * f = fopen("rlog.txt","w"); if (nullptr == f) return -1; ROSE.error_reporter()->error_file(f); stplib_init(); System::Windows::Forms::Form^ form = gcnew System::Windows::Forms::Form(); Microsoft::Msagl::GraphViewerGdi::GViewer^ viewer = gcnew Microsoft::Msagl::GraphViewerGdi::GViewer(); Microsoft::Msagl::Drawing::Graph^ graph = gcnew Microsoft::Msagl::Drawing::Graph("graph"); RoseDesign * d = ROSE.findDesign(argv[1]); if (!d) { printf("Usage: %s [step file to map]", argv[0]); return -1; } RoseCursor curs; curs.traverse(d); RoseObject * obj; curs.domain(ROSE_DOMAIN(stp_draughting_model)); while(obj = curs.next()) { graphdepth(obj, graph); } viewer->Graph = graph; //associate the viewer with the form form->SuspendLayout(); viewer->Dock = System::Windows::Forms::DockStyle::Fill; form->Controls->Add(viewer); form->ResumeLayout(); //show the form form->ShowDialog(); return 0; } void graphdepth(RoseObject* obj, Microsoft::Msagl::Drawing::Graph^ graph, int depth) { if (obj==nullptr) return; if (maxdepth >=0 && depth > maxdepth) return; if (obj->isa(ROSE_DOMAIN(RoseUnion))) { obj = rose_get_nested_object(ROSE_CAST(RoseUnion, obj)); if (nullptr == obj) return; //Select with a non-object type } if (obj->isa(ROSE_DOMAIN(RoseAggregate))) { if (nullptr == obj->getObject((unsigned)0)) { graphatts(obj, graph);//not an aggregate of objects. return; } for (unsigned j = 0, jsz = obj->size(); j < jsz; j++) { graphdepth(obj->getObject(j), graph, depth + 1); } } if (obj->isa(ROSE_DOMAIN(RoseStructure))) { graphatts(obj, graph); for (unsigned i = 0, sz = obj->attributes()->size(); i < sz; i++) { graphdepth(obj->getObject(obj->attributes()->get(i)), graph, depth + 1); } } } void graphatts(RoseObject* obj,Microsoft::Msagl::Drawing::Graph^ graph) { printf("Getting atts of Obj %s\n", obj->domain()->name()); auto eid = obj->entity_id(); for (auto i = 0u, sz = obj->attributes()->size(); i < sz; i++) { auto sobj = obj->getObject(obj->attributes()->get(i)); if (nullptr == sobj) { printf("\t att %d: %s\n", i, obj->attributes()->get(i)->name()); graphaddnode(graph, gcnew String(obj->domain()->name()), gcnew String(obj->attributes()->get(i)->name()), gcnew String(obj->attributes()->get(i)->name())); continue; } printf("\t att %d: %s\n", i, sobj->domain()->name()); parsetonode(obj, sobj, gcnew String(obj->attributes()->get(i)->name()), graph); } } void parsetonode(RoseObject*parent, RoseObject*child,String ^ attstr, Microsoft::Msagl::Drawing::Graph^ graph) { if (!child || !parent) return; if (child->isa(ROSE_DOMAIN(RoseUnion))) { RoseObject * unnestchild = rose_get_nested_object(ROSE_CAST(RoseUnion, child)); graphaddnode(graph, gcnew String(parent->domain()->name()), gcnew String(child->domain()->name()), attstr); if (nullptr == unnestchild) return; else { parsetonode(child, unnestchild, gcnew String(""), graph); return; } } if (child->isa(ROSE_DOMAIN(RoseAggregate))) { graphaddnode(graph, gcnew String(parent->domain()->name()), gcnew String(child->domain()->name()), attstr); for (unsigned i = 0, sz = child->size(); i < sz; i++) { if (nullptr == child->getObject(i)) return; parsetonode(child,child->getObject(i),gcnew String(child->getAttribute()->name()),graph); } } if (child->isa(ROSE_DOMAIN(RoseStructure))) graphaddnode(graph, gcnew String(parent->domain()->name()), gcnew String(child->domain()->name()), attstr); } void graphaddnode(Microsoft::Msagl::Drawing::Graph^ graph, String^ out, String^ in,String^ name) { if (in == "name") in = out + "_name"; if (in == "description") in = out + "_description"; Microsoft::Msagl::Drawing::Node^ nout = graph->FindNode(out); Microsoft::Msagl::Drawing::Node^ nin = graph->FindNode(in); if (!nout) { nout = graph->AddNode(out); } if (!nin) { nin = graph->AddNode(in); } for each (auto edge in nout->Edges) { if (edge->TargetNode == nin && edge->SourceNode == nout) return; } Microsoft::Msagl::Drawing::Edge ^ edge = gcnew Microsoft::Msagl::Drawing::Edge(nout,nin,Microsoft::Msagl::Drawing::ConnectionToGraph::Connected); edge->LabelText = name; if (in == out + "_name") nin->LabelText = "name"; if (in == out + "_description") nin->LabelText = "description"; return; } void markme(RoseObject*obj) { if (nullptr == obj) return; if (rose_is_marked(obj)) return; //MARK HERE rose_mark_set(obj); auto foo = obj->attributes(); if (obj->isa(ROSE_DOMAIN(RoseStructure))) { for (auto i = 0u; i < foo->size(); i++) { markme(obj->getObject(foo->get(i))); } } if (obj->isa(ROSE_DOMAIN(RoseUnion))) { markme(rose_get_nested_object(ROSE_CAST(RoseUnion,obj))); } if (obj->isa(ROSE_DOMAIN(RoseAggregate))) { RoseAttribute *att = obj->getAttribute(); if (!att->isObject()) return; for (auto i = 0u, sz = obj->size(); i < sz;i++) { markme(obj->getObject(i)); } } }
31.066327
160
0.629824
steptools
e8c22bf8af4daf96ece0f21a30578992f4291cf8
253
cpp
C++
Wind_Vegetation_GOW4/Source/Wind_Vegetation_GOW4/Wind_Vegetation_GOW4.cpp
SungJJinKang/UE4_Interactive_Wind_and_Vegetation_in_God_of_War
cecf72dd6f0982d03b1b01c2fff15cdd07028f11
[ "MIT" ]
15
2022-02-16T00:20:21.000Z
2022-03-21T14:40:37.000Z
Wind_Vegetation_GOW4/Source/Wind_Vegetation_GOW4/Wind_Vegetation_GOW4.cpp
SungJJinKang/UE4_Interactive_Wind_and_Vegetation_in_God_of_War
cecf72dd6f0982d03b1b01c2fff15cdd07028f11
[ "MIT" ]
1
2022-03-06T20:41:06.000Z
2022-03-08T18:21:41.000Z
Wind_Vegetation_GOW4/Source/Wind_Vegetation_GOW4/Wind_Vegetation_GOW4.cpp
SungJJinKang/UE4_Interactive_Wind_and_Vegetation_in_God_of_War
cecf72dd6f0982d03b1b01c2fff15cdd07028f11
[ "MIT" ]
1
2022-03-25T02:09:14.000Z
2022-03-25T02:09:14.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "Wind_Vegetation_GOW4.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, Wind_Vegetation_GOW4, "Wind_Vegetation_GOW4" );
36.142857
102
0.83004
SungJJinKang
e8c23c1a1ef9d468819e1ac045e7f0b522b2d841
28,136
hpp
C++
lib/dmitigr/pgfe/array_conversions.hpp
dmitigr/pgfe
c5dd21c0f4949cf6ea2e71368e3c6025c3daf69a
[ "Zlib" ]
121
2018-05-23T19:51:00.000Z
2022-03-12T13:05:34.000Z
lib/dmitigr/pgfe/array_conversions.hpp
dmitigr/pgfe
c5dd21c0f4949cf6ea2e71368e3c6025c3daf69a
[ "Zlib" ]
36
2019-11-11T03:25:10.000Z
2022-03-28T21:54:07.000Z
lib/dmitigr/pgfe/array_conversions.hpp
dmitigr/pgfe
c5dd21c0f4949cf6ea2e71368e3c6025c3daf69a
[ "Zlib" ]
17
2018-05-24T04:01:28.000Z
2022-01-16T13:22:26.000Z
// -*- C++ -*- // Copyright (C) Dmitry Igrishin // For conditions of distribution and use, see files LICENSE.txt or pgfe.hpp #ifndef DMITIGR_PGFE_ARRAY_CONVERSIONS_HPP #define DMITIGR_PGFE_ARRAY_CONVERSIONS_HPP #include "dmitigr/pgfe/basic_conversions.hpp" #include "dmitigr/pgfe/conversions_api.hpp" #include "dmitigr/pgfe/data.hpp" #include "dmitigr/pgfe/exceptions.hpp" #include <dmitigr/misc/str.hpp> #include <algorithm> #include <cassert> #include <locale> #include <memory> #include <optional> #include <string> #include <utility> namespace dmitigr::pgfe { namespace detail { /// @returns The PostgreSQL array literal representation of the `container`. template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator, typename ... Types> std::string to_array_literal(const Container<Optional<T>, Allocator<Optional<T>>>& container, char delimiter = ',', Types&& ... args); /// @returns The container representation of the PostgreSQL array `literal`. template<class Container, typename ... Types> Container to_container(const char* literal, char delimiter = ',', Types&& ... args); // ============================================================================= /** * The compile-time converter from a "container of values" type * to a "container of optionals" type. */ template<typename T> struct Cont_of_opts final { using Type = T; }; /** * @brief Forces treating `std::string` as a non-container type. * * Without this specialization, `std::string` treated as * `std::basic_string<Optional<char>, ...>`. * * @remarks This is a workaround for GCC since the partial specialization by * `std::basic_string<CharT, Traits, Allocator>` (see below) does not works. */ template<> struct Cont_of_opts<std::string> final { using Type = std::string; }; /** * @brief Forces treating `std::basic_string<>` as a non-container type. * * Without this specialization, `std::basic_string<CharT, ...>` treated as * `std::basic_string<Optional<CharT>, ...>`. * * @remarks This specialization doesn't works with GCC (tested with version 8), * and doesn't needs to MSVC. It's exists just in case, probably, for other * compilers. */ template<class CharT, class Traits, class Allocator> struct Cont_of_opts<std::basic_string<CharT, Traits, Allocator>> final { using Type = std::basic_string<CharT, Traits, Allocator>; }; /// The partial specialization of Cont_of_opts. template<typename T, template<class, class> class Container, template<class> class Allocator> struct Cont_of_opts<Container<T, Allocator<T>>> final { private: using Elem = typename Cont_of_opts<T>::Type; public: using Type = Container<std::optional<Elem>, Allocator<std::optional<Elem>>>; }; /// The convenient alias of Cont_of_opts. template<typename T> using Cont_of_opts_t = typename Cont_of_opts<T>::Type; // ===================================== /** * The compile-time converter from a "container of optionals" * to a "container of values". */ template<typename T> struct Cont_of_vals final { using Type = T; }; /// The partial specialization of Cont_of_vals. template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator> struct Cont_of_vals<Container<Optional<T>, Allocator<Optional<T>>>> final { private: using Elem = typename Cont_of_vals<T>::Type; public: using Type = Container<Elem, Allocator<Elem>>; }; /// The convenient alias of the structure template Cont_of_vals. template<typename T> using Cont_of_vals_t = typename Cont_of_vals<T>::Type; // ===================================== /** * @returns The container of values converted from the container of optionals. * * @throws An instance of type Improper_value_type_of_container if there are * element `e` presents in `container` for which `(bool(e) == false)`. */ template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator> Cont_of_vals_t<Container<Optional<T>, Allocator<Optional<T>>>> to_container_of_values(Container<Optional<T>, Allocator<Optional<T>>>&& container); /// @returns The container of optionals converted from the container of values. template<template<class> class Optional, typename T, template<class, class> class Container, template<class> class Allocator> Cont_of_opts_t<Container<T, Allocator<T>>> to_container_of_optionals(Container<T, Allocator<T>>&& container); // ============================================================================= /// Nullable array to/from `std::string` conversions. template<typename> struct Array_string_conversions_opts; /// Nullable array to/from Data conversions. template<typename> struct Array_data_conversions_opts; /// The partial specialization of Array_string_conversions_opts. template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator> struct Array_string_conversions_opts<Container<Optional<T>, Allocator<Optional<T>>>> final { using Type = Container<Optional<T>, Allocator<Optional<T>>>; template<typename ... Types> static Type to_type(const std::string& literal, Types&& ... args) { return to_container<Type>(literal.c_str(), ',', std::forward<Types>(args)...); } template<typename ... Types> static std::string to_string(const Type& value, Types&& ... args) { return to_array_literal(value, ',', std::forward<Types>(args)...); } }; /// The partial specialization of Array_data_conversions_opts. template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator> struct Array_data_conversions_opts<Container<Optional<T>, Allocator<Optional<T>>>> final { using Type = Container<Optional<T>, Allocator<Optional<T>>>; template<typename ... Types> static Type to_type(const Data* const data, Types&& ... args) { assert(data && data->format() == Data_format::text); return to_container<Type>(static_cast<const char*>(data->bytes()), ',', std::forward<Types>(args)...); } template<typename ... Types> static Type to_type(std::unique_ptr<Data>&& data, Types&& ... args) { return to_type(data.get(), std::forward<Types>(args)...); } template<typename ... Types> static std::unique_ptr<Data> to_data(const Type& value, Types&& ... args) { using StringConversions = Array_string_conversions_opts<Type>; return Data::make(StringConversions::to_string(value, std::forward<Types>(args)...), Data_format::text); } }; // ============================================================================= /// Non-nullable array to/from `std::string` conversions. template<typename> struct Array_string_conversions_vals; /// Non-nullable array to/from Data conversions. template<typename> struct Array_data_conversions_vals; /// The partial specialization of Array_string_conversions_vals. template<typename T, template<class, class> class Container, template<class> class Allocator> struct Array_string_conversions_vals<Container<T, Allocator<T>>> final { using Type = Container<T, Allocator<T>>; template<typename ... Types> static Type to_type(const std::string& literal, Types&& ... args) { return to_container_of_values(Array_string_conversions_opts<Cont>::to_type(literal, std::forward<Types>(args)...)); } template<typename ... Types> static std::string to_string(const Type& value, Types&& ... args) { return Array_string_conversions_opts<Cont>::to_string( to_container_of_optionals<std::optional>(value), std::forward<Types>(args)...); } private: using Cont = Cont_of_opts_t<Type>; }; /// The partial specialization of Array_data_conversions_vals. template<typename T, template<class, class> class Container, template<class> class Allocator> struct Array_data_conversions_vals<Container<T, Allocator<T>>> final { using Type = Container<T, Allocator<T>>; template<typename ... Types> static Type to_type(const Data* const data, Types&& ... args) { return to_container_of_values(Array_data_conversions_opts<Cont>::to_type(data, std::forward<Types>(args)...)); } template<typename ... Types> static Type to_type(std::unique_ptr<Data>&& data, Types&& ... args) { return to_container_of_values(Array_data_conversions_opts<Cont>::to_type(std::move(data), std::forward<Types>(args)...)); } template<typename ... Types> static std::unique_ptr<Data> to_data(Type&& value, Types&& ... args) { return Array_data_conversions_opts<Cont>::to_data( to_container_of_optionals<std::optional>(std::forward<Type>(value)), std::forward<Types>(args)...); } private: using Cont = Cont_of_opts_t<Type>; }; // ----------------------------------------------------------------------------- // Parser and filler // ------------------------------------------------------------------------------ /** * @brief Fills the container with values extracted from the PostgreSQL array * literal. * * This functor is for filling the deepest (sub-)container of STL-container (of * container ...) with a values extracted from the PostgreSQL array literals. * I.e., it's a filler of a STL-container of the highest dimensionality. * * @par Requires * See the requirements of the API. Also, `T` mustn't be container. */ template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator> class Filler_of_deepest_container final { private: template<typename U> struct Is_container final : std::false_type{}; template<typename U, template<class> class Opt, template<class, class> class Cont, template<class> class Alloc> struct Is_container<Cont<Opt<U>, Alloc<Opt<U>>>> final : std::true_type{}; public: using Value_type = T; using Optional_type = Optional<Value_type>; using Allocator_type = Allocator<Optional_type>; using Container_type = Container<Optional_type, Allocator_type>; static constexpr bool is_value_type_container = Is_container<Value_type>::value; explicit constexpr Filler_of_deepest_container(Container_type& c) : cont_(c) {} constexpr void operator()(const int /*dimension*/) {} template<typename ... Types> void operator()(std::string&& value, const bool is_null, const int /*dimension*/, Types&& ... args) { if constexpr (!is_value_type_container) { if (is_null) cont_.push_back(Optional_type()); else cont_.push_back(Conversions<Value_type>::to_type(std::move(value), std::forward<Types>(args)...)); } else { (void)value; // dummy usage (void)is_null; // dummy usage throw Client_exception{Client_errc::excessive_array_dimensionality}; } } private: Container_type& cont_; }; // ===================================== /// Special overloads. namespace arrays { /// Used by fill_container(). template<typename T, typename ... Types> const char* fill_container(T& /*result*/, const char* /*literal*/, const char /*delimiter*/, Types&& ... /*args*/) { throw Client_exception{Client_errc::insufficient_array_dimensionality}; } /// Used by to_array_literal() template<typename T> const char* quote_for_array_element(const T&) { return "\""; } /// Used by to_array_literal(). template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator> const char* quote_for_array_element(const Container<Optional<T>, Allocator<Optional<T>>>&) { return ""; } /// Used by to_array_literal(). template<typename T, typename ... Types> std::string to_array_literal(const T& element, const char /*delimiter*/, Types&& ... args) { return Conversions<T>::to_string(element, std::forward<Types>(args)...); } /// Used by to_array_literal(). template<class CharT, class Traits, class Allocator, typename ... Types> std::string to_array_literal(const std::basic_string<CharT, Traits, Allocator>& element, const char /*delimiter*/, Types&& ... args) { using String = std::basic_string<CharT, Traits, Allocator>; std::string result{Conversions<String>::to_string(element, std::forward<Types>(args)...)}; // Escaping quotes. typename String::size_type i = result.find("\""); while (i != String::npos) { result.replace(i, 1, "\\\""); i = result.find("\"", i + 2); } return result; } /// Used by to_container_of_values(). template<typename T> T to_container_of_values(T&& element) { return std::move(element); } /** * @brief Used by to_container_of_optionals(). * * @remarks Workaround for GCC. */ template<template<class> class Optional> Optional<std::string> to_container_of_optionals(std::string&& element) { return Optional<std::string>{std::move(element)}; } /** * @overload * * @remarks It does'nt works with GCC (tested on version 8), and it does not * needs to MSVC. It's exists just in case, probably, for other compilers. */ template<template<class> class Optional, class CharT, class Traits, class Allocator> Optional<std::basic_string<CharT, Traits, Allocator>> to_container_of_optionals(std::basic_string<CharT, Traits, Allocator>&& element) { using String = std::basic_string<CharT, Traits, Allocator>; return Optional<String>{std::move(element)}; } /** * @overload * * @brief Used by to_container_of_optionals(). */ template<template<class> class Optional, typename T> Optional<T> to_container_of_optionals(T&& element) { return Optional<T>{std::move(element)}; } } // namespace arrays // ===================================== /** * @brief PostgreSQL array parsing routine. * * Calls `handler(dimension)` every time the opening curly bracket is reached. * Here, dimension - is a zero-based index of type `int` of the reached * dimension of the literal. * * Calls `handler(element, is_element_null, dimension, args)` each time when * the element is extracted. Here: * - element (std::string&&) -- is a text representation of the array element; * - is_element_null (bool) is a flag that equals to true if the extracted * element is SQL NULL; * - dimension -- is a zero-based index of type `int` of the element dimension; * - args -- extra arguments for passing to the conversion routine. * * @returns The pointer that points to a next character after the last closing * curly bracket found in the `literal`. * * @throws Client_exception. */ template<class F, typename ... Types> const char* parse_array_literal(const char* literal, const char delimiter, F& handler, Types&& ... args) { assert(literal); /* * Syntax of the array literals: * * '{ val1 delimiter val2 delimiter ... }' * * Examples of valid literals: * * {} * {{}} * {1,2} * {{1,2},{3,4}} * {{{1,2}},{{3,4}}} */ enum { in_beginning, in_dimension, in_quoted_element, in_unquoted_element } state = in_beginning; int dimension{}; char previous_char{}; char previous_nonspace_char{}; std::string element; const std::locale loc; while (const char c = *literal) { switch (state) { case in_beginning: { if (c == '{') { handler(dimension); dimension = 1; state = in_dimension; } else if (std::isspace(c, loc)) { // Skip space. } else throw Client_exception{Client_errc::malformed_array_literal}; goto preparing_to_the_next_iteration; } case in_dimension: { assert(dimension > 0); if (std::isspace(c, loc)) { // Skip space. } else if (c == delimiter) { if (previous_nonspace_char == delimiter || previous_nonspace_char == '{') throw Client_exception{Client_errc::malformed_array_literal}; } else if (c == '{') { handler(dimension); ++dimension; } else if (c == '}') { if (previous_nonspace_char == delimiter) throw Client_exception{Client_errc::malformed_array_literal}; --dimension; if (dimension == 0) { // Any character may follow after the closing curly bracket. It's ok. ++literal; // consuming the closing curly bracket return literal; } } else if (c == '"') { state = in_quoted_element; } else { state = in_unquoted_element; continue; } goto preparing_to_the_next_iteration; } case in_quoted_element: { if (c == '\\' && previous_char != '\\') { // Skip escape character '\\'. } else if (c == '"' && previous_char != '\\') goto element_extracted; else element += c; goto preparing_to_the_next_iteration; } case in_unquoted_element: { if (c == delimiter || c == '{' || c == '}') goto element_extracted; else element += c; goto preparing_to_the_next_iteration; } } // switch (state) element_extracted: { if (element.empty()) throw Client_exception{Client_errc::malformed_array_literal}; const bool is_element_null = ((state == in_unquoted_element && element.size() == 4) && ((element[0] == 'n' || element[0] == 'N') && (element[1] == 'u' || element[1] == 'U') && (element[2] == 'l' || element[2] == 'L') && (element[3] == 'l' || element[3] == 'L'))); handler(std::move(element), is_element_null, dimension, std::forward<Types>(args)...); element = std::string{}; // The element was moved and must be recreated! if (state == in_unquoted_element) { /* * Just after extracting unquoted element, the (*literal) is a * character that must be processed next. Thus, continue immediately. */ state = in_dimension; continue; } else { state = in_dimension; } } // extracted element processing preparing_to_the_next_iteration: if (!std::isspace(c, loc)) previous_nonspace_char = c; previous_char = c; ++literal; } // while if (dimension != 0) throw Client_exception{Client_errc::malformed_array_literal}; return literal; } /** * @brief Fills the container with elements extracted from the PostgreSQL array * literal. * * @returns The pointer that points to a next character after the last closing * curly bracket found in the `literal`. * * @throws Client_error. */ template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator, typename ... Types> const char* fill_container(Container<Optional<T>, Allocator<Optional<T>>>& result, const char* literal, const char delimiter, Types&& ... args) { assert(result.empty()); assert(literal); /* * Note: On MSVS the "fatal error C1001: An internal error has occurred in the compiler." * is possible if the using directive below points to the incorrect symbol! */ using str::next_non_space_pointer; literal = next_non_space_pointer(literal); if (*literal != '{') throw Client_exception{Client_errc::malformed_array_literal}; const char* subliteral = next_non_space_pointer(literal + 1); if (*subliteral == '{') { // Multidimensional array literal detected. while (true) { using Subcontainer = T; result.push_back(Subcontainer()); Optional<Subcontainer>& element = result.back(); Subcontainer& subcontainer = *element; /* * The type of the result must have proper dimensionality to correspond * the dimensionality of array represented by the literal. * We are using overload of fill_container() defined in the nested * namespace "arrays" which throws exception if the dimensionality of the * result is insufficient. */ using namespace arrays; subliteral = fill_container(subcontainer, subliteral, delimiter, std::forward<Types>(args)...); // For better understanding, imagine the source literal as "{{{1,2}},{{3,4}}}". subliteral = next_non_space_pointer(subliteral); if (*subliteral == delimiter) { /* * The end of the subarray of the current dimension: subliteral is ",{{3,4}}}". * Parsing will be continued. The subliteral of next array must begins with '{'. */ subliteral = next_non_space_pointer(subliteral + 1); if (*subliteral != '{') throw Client_exception{Client_errc::malformed_array_literal}; } else if (*subliteral == '}') { // The end of the dimension: subliteral is "},{{3,4}}}" ++subliteral; return subliteral; } } } else { Filler_of_deepest_container<T, Optional, Container, Allocator> handler(result); return parse_array_literal(literal, delimiter, handler, std::forward<Types>(args)...); } } /// @returns PostgreSQL array literal converted from the given `container`. template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator, typename ... Types> std::string to_array_literal(const Container<Optional<T>, Allocator<Optional<T>>>& container, const char delimiter, Types&& ... args) { auto i = cbegin(container); const auto e = cend(container); std::string result("{"); if (i != e) { while (true) { if (const Optional<T>& element = *i) { /* * End elements shall be quoted, subliterals shall not be quoted. * We are using overloads defined in nested namespace "arrays" for this. */ using namespace arrays; result.append(quote_for_array_element(*element)); result.append(to_array_literal(*element, delimiter, std::forward<Types>(args)...)); result.append(quote_for_array_element(*element)); } else result.append("NULL"); if (++i != e) result += delimiter; else break; } } result.append("}"); return result; } /// @returns A container converted from PostgreSQL array literal. template<class Container, typename ... Types> Container to_container(const char* const literal, const char delimiter, Types&& ... args) { Container result; fill_container(result, literal, delimiter, std::forward<Types>(args)...); return result; } /** * @returns A container of non-null values converted from PostgreSQL array literal. * * @throws Improper_value_type_of_container. */ template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator> auto to_container_of_values(Container<Optional<T>, Allocator<Optional<T>>>&& container) -> Cont_of_vals_t<Container<Optional<T>, Allocator<Optional<T>>>> { Cont_of_vals_t<Container<Optional<T>, Allocator<Optional<T>>>> result; result.resize(container.size()); std::transform(begin(container), end(container), begin(result), [](auto& elem) { using namespace arrays; if (elem) return to_container_of_values(std::move(*elem)); else throw Client_exception{Client_errc::improper_value_type_of_container}; }); return result; } /// @returns A container of nullable values converted from PostgreSQL array literal. template<template<class> class Optional, typename T, template<class, class> class Container, template<class> class Allocator> auto to_container_of_optionals(Container<T, Allocator<T>>&& container) -> Cont_of_opts_t<Container<T, Allocator<T>>> { Cont_of_opts_t<Container<T, Allocator<T>>> result; result.resize(container.size()); std::transform(begin(container), end(container), begin(result), [](auto& elem) { using namespace arrays; return to_container_of_optionals<Optional>(std::move(elem)); }); return result; } } // namespace detail /** * @ingroup conversions * * @brief The partial specialization of Conversions for nullable arrays (i.e. * containers with optional values). * * @par Requirements * @parblock * Requirements to the type T of elements of array: * - default-constructible, copy-constructible; * - convertible (there shall be a suitable specialization of Conversions). * * Requirements to the type Optional: * - default-constructible, copy-constructible; * - implemented operator bool() that returns true if the value is not null, or * false otherwise. (For default constructed Optional<T> it should return false); * - implemented operator*() that returns a reference to the value of type T. * @endparblock * * @tparam T The type of the elements of the Container (which may be a container * of optionals). * @tparam Optional The optional template class, such as `std::optional`. * @tparam Container The container template class, such as `std::vector`. * @tparam Allocator The allocator template class, such as `std::allocator`. * * The support of the following data formats is implemented: * - for input data - Data_format::text; * - for output data - Data_format::text. */ template<typename T, template<class> class Optional, template<class, class> class Container, template<class> class Allocator> struct Conversions<Container<Optional<T>, Allocator<Optional<T>>>> final : public Basic_conversions<Container<Optional<T>, Allocator<Optional<T>>>, detail::Array_string_conversions_opts<Container<Optional<T>, Allocator<Optional<T>>>>, detail::Array_data_conversions_opts<Container<Optional<T>, Allocator<Optional<T>>>>> {}; /** * @ingroup conversions * * @brief The partial specialization of Conversions for non-nullable arrays. * * @par Requirements * @parblock * Requirements to the type T of elements of array: * - default-constructible, copy-constructible; * - convertible (there shall be a suitable specialization of Conversions). * @endparblock * * @tparam T The type of the elements of the Container (which may be a container). * @tparam Container The container template class, such as `std::vector`. * @tparam Allocator The allocator template class, such as `std::allocator`. * * @throws An instance of type Improper_value_type_of_container when converting * the PostgreSQL array representations with at least one `NULL` element. * * The support of the following data formats is implemented: * - for input data - Data_format::text; * - for output data - Data_format::text. */ template<typename T, template<class, class> class Container, template<class> class Allocator> struct Conversions<Container<T, Allocator<T>>> : public Basic_conversions<Container<T, Allocator<T>>, detail::Array_string_conversions_vals<Container<T, Allocator<T>>>, detail::Array_data_conversions_vals<Container<T, Allocator<T>>>> {}; /** * @brief The partial specialization of Conversions for non-nullable arrays. * * This is a workaround for GCC. When using multidimensional STL-containers GCC * (at least version 8.1) incorrectly choises the specialization of * `Conversions<Container<Optional<T>, Allocator<Optional<T>>>>` by deducing * `Optional` as an STL container, instead of choising * `Conversions<Container<T>, Allocator<T>>` and thus, the nested vector in * `std::vector<std::vector<int>>` treated as `Optional`. */ template<typename T, template<class, class> class Container, template<class, class> class Subcontainer, template<class> class ContainerAllocator, template<class> class SubcontainerAllocator> struct Conversions<Container<Subcontainer<T, SubcontainerAllocator<T>>, ContainerAllocator<Subcontainer<T, SubcontainerAllocator<T>>>>> : public Basic_conversions<Container<Subcontainer<T, SubcontainerAllocator<T>>, ContainerAllocator<Subcontainer<T, SubcontainerAllocator<T>>>>, detail::Array_string_conversions_vals<Container<Subcontainer<T, SubcontainerAllocator<T>>, ContainerAllocator<Subcontainer<T, SubcontainerAllocator<T>>>>>, detail::Array_data_conversions_vals<Container<Subcontainer<T, SubcontainerAllocator<T>>, ContainerAllocator<Subcontainer<T, SubcontainerAllocator<T>>>>>> {}; } // namespace dmitigr::pgfe #endif // DMITIGR_PGFE_ARRAY_CONVERSIONS_HPP
33.140165
125
0.681902
dmitigr
e8c64818f81bb22edcb898ba35b7f60f1e9530d5
843
cpp
C++
cap04/cap04-ex4_3-00-dinamic_array-replaceString.cpp
ggaaaff/think_like_a_programmer--test_code
fb081d24d70db6dd503608562625b84607c7a3ab
[ "MIT" ]
1
2020-12-08T10:54:39.000Z
2020-12-08T10:54:39.000Z
cap04/cap04-ex4_3-00-dinamic_array-replaceString.cpp
ggaaaff/think_like_a_programmer--test_code
fb081d24d70db6dd503608562625b84607c7a3ab
[ "MIT" ]
null
null
null
cap04/cap04-ex4_3-00-dinamic_array-replaceString.cpp
ggaaaff/think_like_a_programmer--test_code
fb081d24d70db6dd503608562625b84607c7a3ab
[ "MIT" ]
null
null
null
//2014.03.28 Gustaf - CTG. /* EXERCISE 4-3 : For our dynamically allocated strings, create a function replaceString that takes three parameters, each of type arrayString: source, target, and replaceText. The function replaces every occurrence of target in source with replaceText. For example, if source points to an array containing "abcdabee", target points to "ab", and replaceText points to "xyz", then when the function ends, source should point to an array containing "xyzcdxyzee". === PLAN === - Diagram of the example. - Traverse (go over) the SOURCE string and identify the initial and final positions in the TARGET string. */ #include <iostream> using namespace std; typedef char *arrayString; int main() { cout << "Variable-Length String Manipulation. REPLACE" << endl; cout << endl; return 0; }
18.326087
105
0.729537
ggaaaff
e8c737caea08dc08f30b761194ab66c7955ee9ac
2,843
cpp
C++
dev/Mobile/PerfMonitor/Views/ToolBoxView.cpp
PixPh/kaleido3d
8a8356586f33a1746ebbb0cfe46b7889d0ae94e9
[ "MIT" ]
38
2019-01-10T03:10:12.000Z
2021-01-27T03:14:47.000Z
dev/Mobile/PerfMonitor/Views/ToolBoxView.cpp
fuqifacai/kaleido3d
ec77753b516949bed74e959738ef55a0bd670064
[ "MIT" ]
null
null
null
dev/Mobile/PerfMonitor/Views/ToolBoxView.cpp
fuqifacai/kaleido3d
ec77753b516949bed74e959738ef55a0bd670064
[ "MIT" ]
8
2019-04-16T07:56:27.000Z
2020-11-19T02:38:37.000Z
#include "ToolBoxView.h" #include <MobileDeviceBridge.h> #include <QBoxLayout> #include <QPushButton> #include <QLabel> #include <QLineEdit> #include <QFileDialog> #include <QListWidget> ToolBoxView::ToolBoxView(QWidget* parent) : QWidget(parent) , m_Device(nullptr) { CreateUI(); } ToolBoxView::~ToolBoxView() { } void ToolBoxView::CreateUI() { QVBoxLayout* rootLayout = new QVBoxLayout; QHBoxLayout* toolLine = new QHBoxLayout; QHBoxLayout* inputLine = new QHBoxLayout; QPushButton* btnInstall = new QPushButton(tr("Install App"), this); connect(btnInstall, SIGNAL(clicked()), SLOT(showApkInstallDirectory())); QPushButton* btnPull = new QPushButton(tr("Pull"), this); connect(btnPull, SIGNAL(clicked()), SLOT(pullRemoteToLocal())); QPushButton* btnPush = new QPushButton(tr("Push"), this); connect(btnPush, SIGNAL(clicked()), SLOT(pushLocalToRemote())); toolLine->addWidget(btnInstall); toolLine->addWidget(btnPull); toolLine->addWidget(btnPush); QLabel* localLb = new QLabel(tr("Local Dir:"), this); QLabel* remoteLb = new QLabel(tr("Remote Dir:"), this); m_LocalDir = new QLineEdit(this); m_RemoteDir = new QLineEdit(this); inputLine->addWidget(localLb); inputLine->addWidget(m_LocalDir); inputLine->addWidget(remoteLb); inputLine->addWidget(m_RemoteDir); rootLayout->addLayout(toolLine); rootLayout->addLayout(inputLine); setLayout(rootLayout); } void ToolBoxView::SetCurrentDevice(k3d::mobi::IDevice * pDevice) { m_Device = pDevice; } void ToolBoxView::showApkInstallDirectory() { if (!m_Device) return; auto plat = m_Device->GetPlatform(); QFileDialog dialog(this); dialog.setWindowTitle(plat == k3d::mobi::EPlatform::Android ? tr("Select App (Android: apk) to Install") : tr("Select App (iOS: ipa) to Install") ); dialog.setDirectory("."); dialog.setNameFilter(plat == k3d::mobi::EPlatform::Android ? tr("Android App (*.apk)") : tr("iOS App (*.ipa)")); dialog.setFileMode(QFileDialog::ExistingFile); dialog.setViewMode(QFileDialog::Detail); QStringList fileNames; if (dialog.exec()) { fileNames = dialog.selectedFiles(); } if (fileNames.size() == 1) { QString appPath = fileNames[0]; m_Device->InstallApp(appPath.toUtf8().data()); // add recent installed app } } void ToolBoxView::pullRemoteToLocal() { QString localDir = m_LocalDir->text(); QString remoteDir = m_RemoteDir->text(); m_Device->Download(localDir.toUtf8().data(), remoteDir.toUtf8().data()); } void ToolBoxView::pushLocalToRemote() { QString localDir = m_LocalDir->text(); QString remoteDir = m_RemoteDir->text(); m_Device->Upload(localDir.toUtf8().data(), remoteDir.toUtf8().data()); }
28.148515
76
0.673584
PixPh
e8c98b346df12bf53ae3a3a51e720e1baedd0486
2,536
cpp
C++
webkit/WebCore/plugins/Plugin.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
15
2016-01-05T12:43:41.000Z
2022-03-15T10:34:47.000Z
webkit/WebCore/plugins/Plugin.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
null
null
null
webkit/WebCore/plugins/Plugin.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
2
2020-11-30T18:36:01.000Z
2021-02-05T23:20:24.000Z
/* * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) * * 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 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 */ #include "config.h" #include "Plugin.h" #include "AtomicString.h" #include "PluginData.h" #include "Frame.h" namespace WebCore { Plugin::Plugin(PluginData* pluginData, unsigned index) : m_pluginData(pluginData) , m_index(index) { } Plugin::~Plugin() { } String Plugin::name() const { return m_pluginData->plugins()[m_index]->name; } String Plugin::filename() const { return m_pluginData->plugins()[m_index]->file; } String Plugin::description() const { return m_pluginData->plugins()[m_index]->desc; } unsigned Plugin::length() const { return m_pluginData->plugins()[m_index]->mimes.size(); } PassRefPtr<MimeType> Plugin::item(unsigned index) { const Vector<PluginInfo*>& plugins = m_pluginData->plugins(); if (index >= plugins[m_index]->mimes.size()) return 0; MimeClassInfo* mime = plugins[m_index]->mimes[index]; const Vector<MimeClassInfo*>& mimes = m_pluginData->mimes(); for (unsigned i = 0; i < mimes.size(); ++i) if (mimes[i] == mime) return MimeType::create(m_pluginData.get(), i).get(); return 0; } bool Plugin::canGetItemsForName(const AtomicString& propertyName) { const Vector<MimeClassInfo*>& mimes = m_pluginData->mimes(); for (unsigned i = 0; i < mimes.size(); ++i) if (mimes[i]->type == propertyName) return true; return false; } PassRefPtr<MimeType> Plugin::namedItem(const AtomicString& propertyName) { const Vector<MimeClassInfo*>& mimes = m_pluginData->mimes(); for (unsigned i = 0; i < mimes.size(); ++i) if (mimes[i]->type == propertyName) return MimeType::create(m_pluginData.get(), i).get(); return 0; } } // namespace WebCore
27.565217
82
0.682177
s1rcheese
e8cd32226646c8f0e83a040e7344d0c1989634cf
12,725
cpp
C++
Misc/UnusedCode/RSLibAndTests/RSLib/Code/Graphics/Rendering/GraphicsRenderer2D.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Misc/UnusedCode/RSLibAndTests/RSLib/Code/Graphics/Rendering/GraphicsRenderer2D.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Misc/UnusedCode/RSLibAndTests/RSLib/Code/Graphics/Rendering/GraphicsRenderer2D.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
using namespace RSLib; //------------------------------------------------------------------------------------------------- // class rsGraphicsRenderer2D (the abstract baseclass): // construction/destruction: rsGraphicsRenderer2D::rsGraphicsRenderer2D() { } rsGraphicsRenderer2D::~rsGraphicsRenderer2D() { } // setup: void rsGraphicsRenderer2D::setColor(const rsColorRGBA& newColor) { state.color = newColor; } void rsGraphicsRenderer2D::setLineThickness(const double newThickness) { state.lineThickness = newThickness; } // drawing: void rsGraphicsRenderer2D::drawFilledEllipseInscribedPolygon(int numVertices, double cx, double cy, double rx, double ry, double a) { rsPolygon2D<double> polygon(numVertices, rsPoint2D<double>(cx, cy), rx, ry, a); drawFilledPolygon(polygon); } void rsGraphicsRenderer2D::drawLine(double x1, double y1, double x2, double y2) { double dx = x2 - x1; double dy = y2 - y1; double d = rsSqrt(dx*dx + dy*dy); double s = 0.5*state.lineThickness/d; dx = s * dy; dy = s * (x2-x1); // == s times the old dx (before reassigning it) rsPolygon2D<double> p; p.reserveVertexMemory(4); p.addVertex(rsPoint2D<double>(x1 - dx, y1 + dy)); p.addVertex(rsPoint2D<double>(x2 - dx, y2 + dy)); p.addVertex(rsPoint2D<double>(x2 + dx, y2 - dy)); p.addVertex(rsPoint2D<double>(x1 + dx, y1 - dy)); drawFilledPolygon(p); } void rsGraphicsRenderer2D::drawOutlinedRectangle(double x, double y, double w, double h) { double t = state.lineThickness; double t2 = 0.5*t; drawFilledRectangle(x-t2, y-t2, t, h+t2); // left edge drawFilledRectangle(x-t2, y-t2, w+t2, t); // top edge drawFilledRectangle(x+w-t2, y-t2, t, h+t2); // right edge drawFilledRectangle(x-t2, y+h-t2, w+t2, t); // bottom edge } void rsGraphicsRenderer2D::drawFilledRectangle(double x, double y, double w, double h) { rsPolygon2D<double> p; p.reserveVertexMemory(4); p.addVertex(rsPoint2D<double>(x, y )); p.addVertex(rsPoint2D<double>(x+w, y )); p.addVertex(rsPoint2D<double>(x+w, y+h)); p.addVertex(rsPoint2D<double>(x, y+h)); drawFilledPolygon(p); } void rsGraphicsRenderer2D::drawFilledEllipse(double cx, double cy, double rx, double ry) { int n = rsMax((int) ceil(rx), (int) ceil(ry)); // \todo use rsCeilInt if( rsIsOdd(n) ) n += 1; n = rsMax(n, 8); // at least 8 vertices drawFilledEllipseInscribedPolygon(n, cx, cy, rx, ry); // \todo maybe an ellipse can be drawn more efficiently using some functions from // agg_renderer_primitives.h - look into this, if this turns out to be true, override it // rsGraphicsRenderer2DImage } void rsGraphicsRenderer2D::drawOutlinedPixelRectangle(int x, int y, int w, int h) { drawFilledRectangle(x, y, 1.0, h); // left edge drawFilledRectangle(x, y, w, 1.0); // top edge drawFilledRectangle(x+w-1.0, y, 1.0, h); // right edge drawFilledRectangle(x, y+h-1.0, w, 1.0); // top edge } void rsGraphicsRenderer2D::drawFilledPixelRectangle(int x, int y, int w, int h) { drawFilledRectangle(x, y, w, h); } //------------------------------------------------------------------------------------------------- // class rsGraphicsRenderer2DImage: rsGraphicsRenderer2DImage::rsGraphicsRenderer2DImage(rsImageRegionRGBA &imageRegionToRenderOn) : imageRegion(imageRegionToRenderOn) { } rsGraphicsRenderer2DImage::~rsGraphicsRenderer2DImage() { } // drawing: void rsGraphicsRenderer2DImage::fillAll() { imageRegion.fillAll(state.color); } void rsGraphicsRenderer2DImage::drawFilledPolygon(const rsPolygon2D<double> &polygon) { rsAGG::drawFilledPolygon(polygon, imageRegion, state.color); } void rsGraphicsRenderer2DImage::drawOutlinedPolygon(const rsPolygon2D<double> &polygon) { rsAGG::drawOutlinedPolygon(polygon, imageRegion, state.color, state.lineThickness); } void rsGraphicsRenderer2DImage::drawText(const rsString &text, int x, int y, int width, int height) { const rsPixelFont *fontToUse = rsGlobalFontInstances::getPixelFontRoundedBoldA16D0(); // \todo shall become reference parameter or state-variable later int kerning = fontToUse->getDefaultKerning(); rsJustification justification; //justification.setJustifiedLeft(); //justification.setJustifiedRight(); //justification.setHorizontallyCentered(); //justification.setJustifiedTop(); //justification.setVerticallyCentered(); //justification.setJustifiedBottom(); //justification.setCentered(); // adjust x, y according to justification (factor out): int xText = x; int yText = y; int textWidth = fontToUse->getTextPixelWidth(text, kerning); int textHeight = fontToUse->getFontHeight(); if( justification.isHorizontallyCentered() ) xText += (width - textWidth) / 2; else if( justification.isJustifiedRight() ) xText += (width - textWidth); if( justification.isVerticallyCentered() ) yText += (height - textHeight) / 2; else if( justification.isJustifiedBottom() ) yText += (height - textHeight); // draw top-left justified text with the modified x, y (factor out): int xMin = x; int yMin = y; int xMax = x + width; int yMax = y + height; for(int i = 0; i < text.getLength(); i++) { rsUint8 c = text.getElement(i); const rsImageGray *glyphImage = fontToUse->getGlyphImage(c/*, state.color*/); if( glyphImage != NULL ) { // clip glyph when text extends beyond its box: int x = rsMax(xText, xMin); int y = rsMax(yText, yMin); int w = rsMin(glyphImage->getWidth(), xMax-x); int h = rsMin(glyphImage->getHeight(), yMax-y); // draw glyph: fillRectangleUsingAlphaMask(x, y, w, h, glyphImage, x-xText, y-yText); xText += fontToUse->getGlyphWidth(c) + kerning; } } // \todo maybe handle line-break characters by incrementing y // \todo factor out a function drawTopLeftJustifiedTextAt } void rsGraphicsRenderer2DImage::fillRectangleWithBilinearGradient(int x, int y, int w, int h, const rsColorRGBA &topLeftColor, const rsColorRGBA &topRightColor, const rsColorRGBA &bottomLeftColor, const rsColorRGBA &bottomRightColor) { rsColorRGBA cL, cR; double scaler = 1.0 / (h-1); rsUint8 weight; int iStart = rsMax(y, 0); int iEnd = rsMin(y+h-1, imageRegion.getHeight()-1); for(int i = iStart; i <= iEnd; i++) { weight = (rsUint8) (255.f * scaler * (i-y)); cL.setAsWeightedAverage(topLeftColor, bottomLeftColor, weight); cR.setAsWeightedAverage(topRightColor, bottomRightColor, weight); drawHorizontalGradientLine(y+i, x, x+w-1, cL, cR); } } void rsGraphicsRenderer2DImage::drawOutlinedPixelRectangle(int x, int y, int w, int h) { if( w <= 0 || h <= 0 ) return; int xMax = imageRegion.getWidth() - 1; int yMax = imageRegion.getHeight() - 1; if( rsIsInRange(y, 0, yMax) ) drawHorizontalPixelLine(y, x, x+w-1); // top line if( rsIsInRange(y+h-1, 0, yMax) ) drawHorizontalPixelLine(y+h-1, x, x+w-1); // bottom line if( rsIsInRange(x, 0, xMax) ) drawVerticalPixelLine(x, y, y+h-1); // left line if( rsIsInRange(x+w-1, 0, xMax) ) drawVerticalPixelLine(x+w-1, y, y+h-1); // right line } void rsGraphicsRenderer2DImage::drawFilledPixelRectangle(int x, int y, int w, int h) { clipToValidRange(x, y, w, h); for(int iy = y; iy < y+h; iy++) { for(int ix = x; ix < x+w; ix++) imageRegion.setPixelColor(ix, iy, state.color); } } void rsGraphicsRenderer2DImage::drawHorizontalPixelLine(int y, int x1, int x2) { rsSortAscending(x1, x2); for(int x = rsMax(0, x1); x <= rsMin(x2, imageRegion.getWidth()-1); x++) imageRegion.setPixelColor(x, y, state.color); } void rsGraphicsRenderer2DImage::drawVerticalPixelLine(int x, int y1, int y2) { rsSortAscending(y1, y2); for(int y = rsMax(0, y1); y <= rsMin(y2, imageRegion.getHeight()-1); y++) imageRegion.setPixelColor(x, y, state.color); } void rsGraphicsRenderer2DImage::drawBresenhamLine(int x1, int y1, int x2, int y2) { bool steep = abs(y2 - y1) > abs(x2 - x1); if( steep ) { rsSwap(x1, y1); rsSwap(x2, y2); } if( x1 > x2 ) { rsSwap(x1, x2); rsSwap(y1, y2); } int deltaX = x2 - x1; int deltaY = abs(y2 - y1); int error = deltaX / 2; int ystep; int y = y1; if( y1 < y2 ) ystep = 1; else ystep = -1; for(int x=x1; x<=x2; x++) { if( steep ) imageRegion.setPixelColor(y, x, state.color); else imageRegion.setPixelColor(x, y, state.color); error = error - deltaY; if( error < 0 ) { y = y + ystep; error = error + deltaX; } } } void rsGraphicsRenderer2DImage::drawVerticalGradientLine(int x, int yTop, int yBottom, const rsColorRGBA &topColor, const rsColorRGBA &bottomColor) { if( x < 0 || x > imageRegion.getWidth()-1 ) return; int h = yBottom - yTop; double scaler = 1.0 / h; rsColorRGBA c; rsUint8 weight; int iStart = rsMax(yTop, 0); int iEnd = rsMin(yBottom, imageRegion.getHeight()-1); for(int i = iStart; i <= iEnd; i++) { weight = (rsUint8) (255.f * scaler * (i-yTop)); c.setAsWeightedAverage(topColor, bottomColor, weight); imageRegion.setPixelColor(x, i, c); } } void rsGraphicsRenderer2DImage::drawHorizontalGradientLine(int y, int xLeft, int xRight, const rsColorRGBA &leftColor, const rsColorRGBA &rightColor) { if( y < 0 || y > imageRegion.getHeight()-1 ) return; int w = xRight - xLeft; double scaler = 1.0 / w; rsColorRGBA c; rsUint8 weight; int iStart = rsMax(xLeft, 0); int iEnd = rsMin(xRight, imageRegion.getWidth()-1); for(int i = iStart; i <= iEnd; i++) { weight = (rsUint8) (255.f * scaler * (i-xLeft)); c.setAsWeightedAverage(leftColor, rightColor, weight); imageRegion.setPixelColor(i, y, c); } } void rsGraphicsRenderer2DImage::fillRectangleUsingAlphaMask(int x, int y, int w, int h, const rsImageGray *mask, int xOffset, int yOffset) { // range checking (write a test and factor this out (maybe into // rsImage::restrictImageCopyRange or something)) if( x < 0 ) { w += x; x = 0; } if( y < 0 ) { h += y; y = 0; } if( x+w > imageRegion.getWidth() ) w = imageRegion.getWidth() - x; if( y+h > imageRegion.getHeight() ) h = imageRegion.getHeight() - y; if( w > imageRegion.getWidth()-xOffset ) w = imageRegion.getWidth() - xOffset; if( h > imageRegion.getHeight()-yOffset ) h = imageRegion.getHeight() - yOffset; // OK - range should be safe now for(int iy = 0; iy < h; iy++) { for(int ix = 0; ix < w; ix++) { rsUint8 alpha = mask->getPixelColor(ix+xOffset, iy+yOffset); rsColorRGBA oldColor = imageRegion.getPixelColor(x+ix, y+iy); rsColorRGBA newColor = state.color; rsColorRGBA blendColor; blendColor.setAsWeightedAverage(oldColor, newColor, alpha); imageRegion.setPixelColor(x+ix, y+iy, blendColor); // \todo take into account the alpha value of "newColor" - retain alpha of the "oldColor" but // mix-in the new color according to its own alpha value and the alpha value from the // alpha-mask // write rsColorRGBA.alphaBlendWith(newColor, alpha) and // image.blendPixelWith(x, y, color, alpha) // ....maybe it can be streamlined } } } void rsGraphicsRenderer2DImage::clipToValidRange(int &x, int &y, int &w, int &h) { x = rsClipToRange(x, 0, imageRegion.getWidth()-1); w = rsClipToRange(w, 0, imageRegion.getWidth()-x); y = rsClipToRange(y, 0, imageRegion.getHeight()-1); h = rsClipToRange(h, 0, imageRegion.getHeight()-y); } //------------------------------------------------------------------------------------------------- // class rsGraphicsRenderer2DOpenGL: rsGraphicsRenderer2DOpenGL::rsGraphicsRenderer2DOpenGL() { } rsGraphicsRenderer2DOpenGL::~rsGraphicsRenderer2DOpenGL() { } // setup: void rsGraphicsRenderer2DOpenGL::setColor(const rsColorRGBA& newColor) { rsGraphicsRenderer2D::setColor(newColor); // glSetColor ...or something } // drawing: /* void rsGraphicsRenderer2DOpenGL::drawLine(rsPoint2D<double> p1, rsPoint2D<double> p2) { // glDrawLine or something } */
30.442584
140
0.627741
RobinSchmidt
e8d05c7655dd1149727b26b9f7b175237253d9a1
5,861
cpp
C++
vaca/FileDialog.cpp
picrap/vaca
377070c2124bb71649313f6a144c6bd40fdee723
[ "MIT" ]
null
null
null
vaca/FileDialog.cpp
picrap/vaca
377070c2124bb71649313f6a144c6bd40fdee723
[ "MIT" ]
null
null
null
vaca/FileDialog.cpp
picrap/vaca
377070c2124bb71649313f6a144c6bd40fdee723
[ "MIT" ]
null
null
null
// Vaca - Visual Application Components Abstraction // Copyright (c) 2005-2010 David Capello // // This file is distributed under the terms of the MIT license, // please read LICENSE.txt for more information. #include "vaca/FileDialog.h" #include "vaca/Widget.h" #include "vaca/Application.h" #include "vaca/System.h" #include "vaca/String.h" // 32k is the limit for Win95/98/Me/NT4/2000/XP with ANSI version #define FILENAME_BUFSIZE (1024*32) using namespace vaca; // ====================================================================== // FileDialog FileDialog::FileDialog(const String& title, Widget* parent) : CommonDialog(parent) , m_title(title) , m_defaultExtension(L"") , m_showReadOnly(false) , m_showHelp(false) , m_defaultFilter(0) { m_fileName = new Char[FILENAME_BUFSIZE]; ZeroMemory(m_fileName, sizeof(Char[FILENAME_BUFSIZE])); } FileDialog::~FileDialog() { delete[] m_fileName; } /** Sets the title text. */ void FileDialog::setTitle(const String& str) { m_title = str; } /** Sets the default extension to add to the entered file name when an extension isn't specified by the user. By default it's an empty string. */ void FileDialog::setDefaultExtension(const String& str) { m_defaultExtension = str; } /** Sets the property that indicates if the dialog should show the read only check box. By default it's false: the button is hidden. */ void FileDialog::setShowReadOnly(bool state) { m_showReadOnly = state; } /** Sets the property that indicates if the dialog should show the help button. By default it's false: the button is hidden. */ void FileDialog::setShowHelp(bool state) { m_showHelp = state; } void FileDialog::addFilter(const String& extensions, const String& description, bool defaultFilter) { m_filters.push_back(std::make_pair(extensions, description)); if (defaultFilter) m_defaultFilter = m_filters.size(); } String FileDialog::getFileName() { return String(m_fileName); } void FileDialog::setFileName(const String& fileName) { copy_string_to(fileName, m_fileName, FILENAME_BUFSIZE); } LPTSTR FileDialog::getOriginalFileName() { return m_fileName; } bool FileDialog::doModal() { // make the m_filtersString m_filtersString.clear(); for (std::vector<std::pair<String, String> >::iterator it=m_filters.begin(); it!=m_filters.end(); ++it) { m_filtersString.append(it->first); m_filtersString.push_back('\0'); m_filtersString.append(it->second); m_filtersString.push_back('\0'); } m_filtersString.push_back('\0'); // fill the OPENFILENAME structure OPENFILENAME ofn; ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = getParentHandle(); ofn.hInstance = Application::getHandle(); ofn.lpstrFilter = m_filtersString.c_str(); ofn.lpstrCustomFilter = NULL; ofn.nMaxCustFilter = 0; ofn.nFilterIndex = m_defaultFilter; ofn.lpstrFile = m_fileName; ofn.nMaxFile = FILENAME_BUFSIZE; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; ofn.lpstrTitle = m_title.c_str(); ofn.Flags = 0 // #define OFN_CREATEPROMPT 0x2000 // #define OFN_ENABLEHOOK 32 | OFN_ENABLESIZING // #define OFN_ENABLETEMPLATE 64 // #define OFN_ENABLETEMPLATEHANDLE 128 | OFN_EXPLORER // #define OFN_EXTENSIONDIFFERENT 0x400 | (m_showReadOnly ? 0: OFN_HIDEREADONLY) | OFN_LONGNAMES | OFN_NOCHANGEDIR // | OFN_NODEREFERENCELINKS // | OFN_NOLONGNAMES // | OFN_NONETWORKBUTTON // | OFN_NOREADONLYRETURN // | OFN_NOTESTFILECREATE // | OFN_NOVALIDATE // #define OFN_READONLY 1 // #define OFN_SHAREAWARE 0x4000 | (m_showHelp ? OFN_SHOWHELP: 0) ; // | OFN_SHAREFALLTHROUGH // | OFN_SHARENOWARN // | OFN_SHAREWARN // | OFN_NODEREFERENCELINKS // #if (_WIN32_WINNT >= 0x0500) // | OFN_DONTADDTORECENT // #endif ofn.nFileOffset = 0; ofn.nFileExtension = 0; ofn.lpstrDefExt = m_defaultExtension.c_str(); ofn.lCustData = 0; ofn.lpfnHook = NULL; ofn.lpTemplateName = NULL; #if (_WIN32_WINNT >= 0x0500) ofn.pvReserved = NULL; ofn.dwReserved = 0; ofn.FlagsEx = 0; #endif return showDialog(&ofn); } // ====================================================================== // OpenFileDialog OpenFileDialog::OpenFileDialog(const String& title, Widget* parent) : FileDialog(title, parent) , m_multiselect(false) { } OpenFileDialog::~OpenFileDialog() { } /** By default it's false. */ void OpenFileDialog::setMultiselect(bool state) { m_multiselect = state; } std::vector<String> OpenFileDialog::getFileNames() { std::vector<String> result; if (m_multiselect) { LPTSTR ptr, start; String path; for (ptr=start=getOriginalFileName(); ; ++ptr) { if (*ptr == '\0') { if (path.empty()) path = start; else result.push_back(path + L"\\" + start); if (*(++ptr) == '\0') break; start = ptr; } } } // empty results? one file-name selected if (result.empty()) result.push_back(getFileName()); return result; } bool OpenFileDialog::showDialog(LPOPENFILENAME lpofn) { lpofn->Flags |= 0 | (m_multiselect ? OFN_ALLOWMULTISELECT: 0) | OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST ; return GetOpenFileName(lpofn) != FALSE; } // ====================================================================== // SaveFileDialog SaveFileDialog::SaveFileDialog(const String& title, Widget* parent) : FileDialog(title, parent) { } SaveFileDialog::~SaveFileDialog() { } bool SaveFileDialog::showDialog(LPOPENFILENAME lpofn) { lpofn->Flags |= 0 | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT ; return GetSaveFileName(lpofn) != FALSE; }
23.257937
100
0.651254
picrap
e8d473761c3328e29927eddb682114201b63f940
302
cpp
C++
SimpleLearn/99.Learn/Test2.cpp
codeworkscn/learn-cpp
c72b2330934bdead2489509cd89343e666e631b4
[ "Apache-2.0" ]
null
null
null
SimpleLearn/99.Learn/Test2.cpp
codeworkscn/learn-cpp
c72b2330934bdead2489509cd89343e666e631b4
[ "Apache-2.0" ]
null
null
null
SimpleLearn/99.Learn/Test2.cpp
codeworkscn/learn-cpp
c72b2330934bdead2489509cd89343e666e631b4
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<string> using namespace std; int Test2(void) { const int n = 9 ; for(int i=1 ; i!= n+1 ; ++i) { for(int j=1 ; j!= i+1 ; ++j) { cout << i << "*" << j << "=" << i*j << "\t"; if(! (j%10) && j) { cout << endl ; } } cout << endl ; } return 0 ; }
12.583333
47
0.427152
codeworkscn
e8d76f278c8b413083732ba9463daecbb233465e
2,991
cpp
C++
test/TestReadIterator.cpp
RPG-18/QMiniZip
aba71ec55e05e4a67e9ece81ca1aa16f825e438e
[ "MIT" ]
null
null
null
test/TestReadIterator.cpp
RPG-18/QMiniZip
aba71ec55e05e4a67e9ece81ca1aa16f825e438e
[ "MIT" ]
null
null
null
test/TestReadIterator.cpp
RPG-18/QMiniZip
aba71ec55e05e4a67e9ece81ca1aa16f825e438e
[ "MIT" ]
2
2018-05-23T14:46:30.000Z
2018-06-23T02:04:32.000Z
#include <gtest/gtest.h> #include <config.h> #include <QtCore/QDir> #include <QtCore/QDebug> #include <QtCore/QVector> #include <QtCore/QStringList> #include "ZipFile.h" #include "ZipReadIterator.h" using namespace QMiniZip; TEST(ZipReadIterator, next) { QDir dir(TEST_SOURCE_DIR); ASSERT_TRUE(dir.cd("data")); const auto archive = dir.absoluteFilePath("dataset1.zip"); ZipFile zipFile(archive); ASSERT_TRUE(zipFile.open(ZipFile::UNZIP)); ZipReadIterator zIiterator(zipFile); ASSERT_TRUE(zIiterator.toBegin()); int cnt = 1; while(zIiterator.next()) { ++cnt; } ASSERT_EQ(4, cnt); } TEST(ZipReadIterator, fileInfo) { QDir dir(TEST_SOURCE_DIR); ASSERT_TRUE(dir.cd("data")); const auto archive = dir.absoluteFilePath("dataset1.zip"); ZipFile zipFile(archive); ASSERT_TRUE(zipFile.open(ZipFile::UNZIP)); ZipReadIterator zIiterator(zipFile); ASSERT_TRUE(zIiterator.toBegin()); int cnt = 0; QStringList files; QVector<size_t> unSizes; do { const auto info = zIiterator.fileInfo(); files<<info.name(); unSizes.push_back(info.uncompressedSize()); ++cnt; }while(zIiterator.next()); ASSERT_EQ(4, cnt); const QStringList expectedFiles = {"folder1/zen2.txt", "folder1/zen1.txt", "folder3/zen4.txt", "folder2/zen3.txt"}; ASSERT_EQ(expectedFiles, files); const QVector<size_t> expectedUnSizes = {5099, 916, 1970, 1792}; ASSERT_EQ(expectedUnSizes, unSizes); } TEST(ZipReadIterator, read) { QDir dir(TEST_SOURCE_DIR); ASSERT_TRUE(dir.cd("data")); const auto archive = dir.absoluteFilePath("dataset1.zip"); ZipFile zipFile(archive); ASSERT_TRUE(zipFile.open(ZipFile::UNZIP)); ZipReadIterator zIiterator(zipFile); ASSERT_TRUE(zIiterator.toBegin()); ASSERT_TRUE(zIiterator.openCurrentFile()); QByteArray data; QByteArray buff(1024, 0); while(qint64 cnt = zIiterator.read(buff.data(), buff.size())) { if(cnt<0) { break; } data.append(buff.data(), cnt); } ASSERT_EQ(5099, data.size()); } TEST(ZipReadIterator, readAll) { QDir dir(TEST_SOURCE_DIR); ASSERT_TRUE(dir.cd("data")); const auto archive = dir.absoluteFilePath("dataset1.zip"); ZipFile zipFile(archive); ASSERT_TRUE(zipFile.open(ZipFile::UNZIP)); ZipReadIterator zIiterator(zipFile); ASSERT_TRUE(zIiterator.toBegin()); QVector<QByteArray> dataSet; do { ASSERT_TRUE(zIiterator.openCurrentFile()); dataSet.push_back(zIiterator.readAll()); ASSERT_TRUE(dataSet.back().size()>0); }while(zIiterator.next()); const QVector<int> expectedUnSizes = {5099, 916, 1970, 1792}; ASSERT_EQ(expectedUnSizes.size(), dataSet.size()); for(int i = 0; i < expectedUnSizes.size(); ++i) { ASSERT_EQ(expectedUnSizes[i], dataSet[i].size()); } }
22.320896
65
0.646272
RPG-18
e8e050b4cda28176096b6e8f3f9bdaff02d15143
8,011
cpp
C++
tools/ctmconv.cpp
SaeedTaghavi/OpenCTM
d6c1138eb39632244e6b5d133a100f431c5c5082
[ "Zlib" ]
80
2015-04-08T08:48:06.000Z
2022-03-23T10:36:55.000Z
tools/ctmconv.cpp
rasata/OpenCTM
243a343bd23bbeef8731f06ed91e3996604e1af4
[ "Zlib" ]
7
2015-09-25T21:11:59.000Z
2021-11-09T00:22:18.000Z
tools/ctmconv.cpp
rasata/OpenCTM
243a343bd23bbeef8731f06ed91e3996604e1af4
[ "Zlib" ]
36
2015-05-21T16:34:42.000Z
2021-12-29T06:41:52.000Z
//----------------------------------------------------------------------------- // Product: OpenCTM tools // File: ctmconv.cpp // Description: 3D file format conversion tool. The program can be used to // convert various 3D file formats to and from the OpenCTM file // format, and also for conversion between other formats. //----------------------------------------------------------------------------- // Copyright (c) 2009-2010 Marcus Geelnard // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not // be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. //----------------------------------------------------------------------------- #include <stdexcept> #include <vector> #include <iostream> #include <list> #include <string> #include <cctype> #include "systimer.h" #include "convoptions.h" #include "mesh.h" #include "meshio.h" using namespace std; //----------------------------------------------------------------------------- // PreProcessMesh() //----------------------------------------------------------------------------- static void PreProcessMesh(Mesh &aMesh, Options &aOptions) { // Nothing to do? if((aOptions.mScale == 1.0f) && (aOptions.mUpAxis == uaZ) && (!aOptions.mFlipTriangles) && (!aOptions.mCalcNormals)) return; // Create 3x3 transformation matrices for the vertices and the normals Vector3 vX, vY, vZ; Vector3 nX, nY, nZ; switch(aOptions.mUpAxis) { case uaX: nX = Vector3(0.0f, 0.0f, 1.0f); nY = Vector3(0.0f, 1.0f, 0.0f); nZ = Vector3(-1.0f, 0.0f, 0.0f); break; case uaY: nX = Vector3(1.0f, 0.0f, 0.0f); nY = Vector3(0.0f, 0.0f, 1.0f); nZ = Vector3(0.0f, -1.0f, 0.0f); break; case uaZ: nX = Vector3(1.0f, 0.0f, 0.0f); nY = Vector3(0.0f, 1.0f, 0.0f); nZ = Vector3(0.0f, 0.0f, 1.0f); break; case uaNX: nX = Vector3(0.0f, 0.0f, -1.0f); nY = Vector3(0.0f, 1.0f, 0.0f); nZ = Vector3(1.0f, 0.0f, 0.0f); break; case uaNY: nX = Vector3(1.0f, 0.0f, 0.0f); nY = Vector3(0.0f, 0.0f, -1.0f); nZ = Vector3(0.0f, 1.0f, 0.0f); break; case uaNZ: nX = Vector3(-1.0f, 0.0f, 0.0f); nY = Vector3(0.0f, 1.0f, 0.0f); nZ = Vector3(0.0f, 0.0f, -1.0f); break; } vX = nX * aOptions.mScale; vY = nY * aOptions.mScale; vZ = nZ * aOptions.mScale; cout << "Processing... " << flush; SysTimer timer; timer.Push(); // Update all vertex coordinates for(CTMuint i = 0; i < aMesh.mVertices.size(); ++ i) aMesh.mVertices[i] = vX * aMesh.mVertices[i].x + vY * aMesh.mVertices[i].y + vZ * aMesh.mVertices[i].z; // Update all normals if(aMesh.HasNormals() && !aOptions.mNoNormals) { for(CTMuint i = 0; i < aMesh.mNormals.size(); ++ i) aMesh.mNormals[i] = nX * aMesh.mNormals[i].x + nY * aMesh.mNormals[i].y + nZ * aMesh.mNormals[i].z; } // Flip trianlges? if(aOptions.mFlipTriangles) { CTMuint triCount = aMesh.mIndices.size() / 3; for(CTMuint i = 0; i < triCount; ++ i) { CTMuint tmp = aMesh.mIndices[i * 3]; aMesh.mIndices[i * 3] = aMesh.mIndices[i * 3 + 1]; aMesh.mIndices[i * 3 + 1] = tmp; } } // Calculate normals? if((!aOptions.mNoNormals) && aOptions.mCalcNormals && (!aMesh.HasNormals())) aMesh.CalculateNormals(); double dt = timer.PopDelta(); cout << 1000.0 * dt << " ms" << endl; } //----------------------------------------------------------------------------- // main() //----------------------------------------------------------------------------- int main(int argc, char ** argv) { // Get file names and options Options opt; string inFile; string outFile; try { if(argc < 3) throw runtime_error("Too few arguments."); inFile = string(argv[1]); outFile = string(argv[2]); opt.GetFromArgs(argc, argv, 3); } catch(exception &e) { cout << "Error: " << e.what() << endl << endl; cout << "Usage: " << argv[0] << " infile outfile [options]" << endl << endl; cout << "Options:" << endl; cout << endl << " Data manipulation (all formats)" << endl; cout << " --scale arg Scale the mesh by a scalar factor." << endl; cout << " --upaxis arg Set up axis (X, Y, Z, -X, -Y, -Z). If != Z, the mesh will" << endl; cout << " be flipped." << endl; cout << " --flip Flip triangle orientation." << endl; cout << " --calc-normals If the source file does not contain any normals, calculate" << endl; cout << " them." << endl; cout << " --no-normals Do not export normals." << endl; cout << " --no-texcoords Do not export texture coordinates." << endl; cout << " --no-colors Do not export vertex colors." << endl; cout << endl << " OpenCTM output" << endl; cout << " --method arg Select compression method (RAW, MG1, MG2)" << endl; cout << " --level arg Set the compression level (0 - 9)" << endl; cout << endl << " OpenCTM MG2 method" << endl; cout << " --vprec arg Set vertex precision" << endl; cout << " --vprecrel arg Set vertex precision, relative method" << endl; cout << " --nprec arg Set normal precision" << endl; cout << " --tprec arg Set texture map precision" << endl; cout << " --cprec arg Set color precision" << endl; cout << " --aprec arg Set attributes precision" << endl; cout << endl << " Miscellaneous" << endl; cout << " --comment arg Set the file comment (default is to use the comment" << endl; cout << " from the input file, if any)." << endl; cout << " --texfile arg Set the texture file name reference for the texture" << endl; cout << " (default is to use the texture file name reference" << endl; cout << " from the input file, if any)." << endl; // Show supported formats cout << endl << "Supported file formats:" << endl << endl; list<string> formatList; SupportedFormats(formatList); for(list<string>::iterator i = formatList.begin(); i != formatList.end(); ++ i) cout << " " << (*i) << endl; cout << endl; return 0; } try { // Define mesh Mesh mesh; // Create a timer instance SysTimer timer; double dt; // Load input file cout << "Loading " << inFile << "... " << flush; timer.Push(); ImportMesh(inFile.c_str(), &mesh); dt = timer.PopDelta(); cout << 1000.0 * dt << " ms" << endl; // Manipulate the mesh PreProcessMesh(mesh, opt); // Override comment? if(opt.mComment.size() > 0) mesh.mComment = opt.mComment; // Override texture file name? if(opt.mTexFileName.size() > 0) mesh.mTexFileName = opt.mTexFileName; // Save output file cout << "Saving " << outFile << "... " << flush; timer.Push(); ExportMesh(outFile.c_str(), &mesh, opt); dt = timer.PopDelta(); cout << 1000.0 * dt << " ms" << endl; } catch(exception &e) { cout << "Error: " << e.what() << endl; return 1; } return 0; }
33.801688
99
0.536887
SaeedTaghavi
e8e907277d26798fc44242b4d2f30dde38835985
12,350
cpp
C++
UnitTest/Basic.cpp
akfreed/CppSocketsXPlatform
06be7da54e4ac29ac87c6e68626bbc3226217f4e
[ "Apache-2.0" ]
null
null
null
UnitTest/Basic.cpp
akfreed/CppSocketsXPlatform
06be7da54e4ac29ac87c6e68626bbc3226217f4e
[ "Apache-2.0" ]
null
null
null
UnitTest/Basic.cpp
akfreed/CppSocketsXPlatform
06be7da54e4ac29ac87c6e68626bbc3226217f4e
[ "Apache-2.0" ]
null
null
null
// ================================================================== // Copyright 2018 Alexander K. Freed // // 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. // ================================================================== // Contains the basic tests. #include "TcpListener.h" #include "TcpSocket.h" #include "UdpSocket.h" #include <cstring> #include <string> #include <vector> #include <array> #include "TestReport.h" #include "UnitTestMain.h" //============================================================================ // tests template <typename SOCKET> TestReport SendRecvChar(bool assumptions, SOCKET& sender, SOCKET& receiver) { TestReport report("SendRecvChar", "Sends and receives a char."); char sentData = 'f'; if (!assumptions) { report.ResultNotes = "Failed assumptions."; report.FailedAssumptions = true; return report; } if (!IsValidSocket(sender)) { report.ResultNotes = "Sender not connected."; return report; } if (!IsValidSocket(receiver)) { report.ResultNotes = "Receiver not connected."; return report; } if (receiver.DataAvailable() != 0) { report.ResultNotes = "Receiver had data in buffer before data was sent."; return report; } if (!sender.Write(sentData)) { report.ResultNotes = "Write failed."; return report; } if (!receiver.SetReadTimeout(5000)) { report.ResultNotes = "Receiver setsockopt failed when setting read timeout."; return report; } char c; if (!receiver.Read(c)) { report.ResultNotes = "Read failed."; return report; } if (c != sentData) { report.ResultNotes = "Read received wrong data."; return report; } report.Passed = true; return report; } //---------------------------------------------------------------------------- template <typename SOCKET> TestReport SendRecvBool(bool assumptions, SOCKET& sender, SOCKET& receiver) { TestReport report("SendRecvBool", "Sends and receives true and false."); if (!assumptions) { report.ResultNotes = "Failed assumptions."; report.FailedAssumptions = true; return report; } if (!IsValidSocket(sender)) { report.ResultNotes = "Sender not connected."; return report; } if (!IsValidSocket(receiver)) { report.ResultNotes = "Receiver not connected."; return report; } if (receiver.DataAvailable() != 0) { report.ResultNotes = "Receiver had data in buffer before data was sent."; return report; } if (!sender.Write(false)) { report.ResultNotes = "Write failed."; return report; } if (!sender.Write(true)) { report.ResultNotes = "Write failed."; return report; } if (!sender.Write(true)) { report.ResultNotes = "Write failed."; return report; } if (!receiver.SetReadTimeout(5000)) { report.ResultNotes = "Receiver setsockopt failed when setting read timeout."; return report; } bool b; if (!receiver.Read(b)) { report.ResultNotes = "Read failed."; return report; } if (b != false) { report.ResultNotes = "Read received wrong data."; return report; } if (!receiver.Read(b)) { report.ResultNotes = "Read failed."; return report; } if (b != true) { report.ResultNotes = "Read received wrong data."; return report; } // this test is not necessary char c; if (!receiver.Read(c)) { report.ResultNotes = "Read failed."; return report; } if (c != 1) { report.ResultNotes = "Read received wrong data."; return report; } report.Passed = true; return report; } //---------------------------------------------------------------------------- template <typename SOCKET> TestReport SendRecvInt(bool assumptions, SOCKET& sender, SOCKET& receiver) { TestReport report("SendRecvInt", "Sends and receives an int32."); int sentData = -20; if (!assumptions) { report.ResultNotes = "Failed assumptions."; report.FailedAssumptions = true; return report; } if (!IsValidSocket(sender)) { report.ResultNotes = "Sender not connected."; return report; } if (!IsValidSocket(receiver)) { report.ResultNotes = "Receiver not connected."; return report; } if (receiver.DataAvailable() != 0) { report.ResultNotes = "Receiver had data in buffer before data was sent."; return report; } if (!sender.Write(sentData)) { report.ResultNotes = "Write failed."; return report; } if (!receiver.SetReadTimeout(5000)) { report.ResultNotes = "Receiver setsockopt failed when setting read timeout."; return report; } int i; if (!receiver.Read(i)) { report.ResultNotes = "Read failed."; return report; } if (i != sentData) { report.ResultNotes = "Read received wrong data."; return report; } report.Passed = true; return report; } //---------------------------------------------------------------------------- template <typename SOCKET> TestReport SendRecvDouble(bool assumptions, SOCKET& sender, SOCKET& receiver) { TestReport report("SendRecvDouble", "Sends and receives a double."); double sentData = 5.1234567890; if (!assumptions) { report.ResultNotes = "Failed assumptions."; report.FailedAssumptions = true; return report; } if (!IsValidSocket(sender)) { report.ResultNotes = "Sender not connected."; return report; } if (!IsValidSocket(receiver)) { report.ResultNotes = "Receiver not connected."; return report; } if (receiver.DataAvailable() != 0) { report.ResultNotes = "Receiver had data in buffer before data was sent."; return report; } if (!sender.Write(sentData)) { report.ResultNotes = "Write failed."; return report; } if (!receiver.SetReadTimeout(5000)) { report.ResultNotes = "Receiver setsockopt failed when setting read timeout."; return report; } double d; if (!receiver.Read(d)) { report.ResultNotes = "Read failed."; return report; } if (d != sentData) { report.ResultNotes = "Read received wrong data."; return report; } report.Passed = true; return report; } //---------------------------------------------------------------------------- template <typename SOCKET> TestReport SendRecvBuf(bool assumptions, SOCKET& sender, SOCKET& receiver) { TestReport report("SendRecvBuf", "Sends and receives a char buffer."); char sentData[6] = { 1, 2, 3, 4, 5, 6 }; if (!assumptions) { report.ResultNotes = "Failed assumptions."; report.FailedAssumptions = true; return report; } if (!IsValidSocket(sender)) { report.ResultNotes = "Sender not connected."; return report; } if (!IsValidSocket(receiver)) { report.ResultNotes = "Receiver not connected."; return report; } if (receiver.DataAvailable() != 0) { report.ResultNotes = "Receiver had data in buffer before data was sent."; return report; } if (!sender.Write(sentData, 5)) { report.ResultNotes = "Write failed."; return report; } if (!receiver.SetReadTimeout(5000)) { report.ResultNotes = "Receiver setsockopt failed when setting read timeout."; return report; } char buf[6] = { 0, 0, 0, 0, 0 }; std::array<char, 6> expected = { 1, 2, 3, 4, 5, 0 }; if (!receiver.Read(buf, 5)) { report.ResultNotes = "Read failed."; return report; } if (!bufferMatches(buf, expected, 5)) { report.ResultNotes = "Read received wrong data."; return report; } if (!sender.Write(sentData + 3, 3)) { report.ResultNotes = "Write failed."; return report; } if (!sender.Write(sentData, 3)) { report.ResultNotes = "Write failed."; return report; } expected = { 4, 5, 3, 4, 5, 0 }; if (!receiver.Read(buf, 2)) { report.ResultNotes = "Read failed."; return report; } expected = { 6, 1, 2, 3, 5, 0 }; if (!receiver.Read(buf, 4)) { report.ResultNotes = "Read failed."; return report; } report.Passed = true; return report; } //---------------------------------------------------------------------------- template <typename SOCKET> TestReport SendRecvCharString(bool assumptions, SOCKET& sender, SOCKET& receiver) { TestReport report("SendRecvCharString", "Sends and receives a char string."); char s[101] = "Hello, World!"; if (!assumptions) { report.ResultNotes = "Failed assumptions."; report.FailedAssumptions = true; return report; } if (!IsValidSocket(sender)) { report.ResultNotes = "Sender not connected."; return report; } if (!IsValidSocket(receiver)) { report.ResultNotes = "Receiver not connected."; return report; } if (receiver.DataAvailable() != 0) { report.ResultNotes = "Receiver had data in buffer before data was sent."; return report; } if (!sender.WriteString(s)) { report.ResultNotes = "Write failed."; return report; } if (!receiver.SetReadTimeout(5000)) { report.ResultNotes = "Receiver setsockopt failed when setting read timeout."; return report; } char msg[101]; memset(msg, 0xFF, 101); if (!receiver.ReadString(msg, 101)) { report.ResultNotes = "Read failed."; return report; } if (strcmp(s, msg) != 0) { report.ResultNotes = "Read received wrong data."; return report; } report.Passed = true; return report; } //============================================================================ // Test Basic Main TestReport TestBasic() { TestReport report("RunBasic", "Runs basic read/write tests."); TestReport result; TcpSocket senderTcp, receiverTcp; result = SelfConnect("11111", senderTcp, receiverTcp); report.SubTests.push_back(result); bool assumptions = result.Passed; result = SendRecvChar(assumptions, senderTcp, receiverTcp); report.SubTests.push_back(result); result = SendRecvBool(assumptions, senderTcp, receiverTcp); report.SubTests.push_back(result); result = SendRecvInt(assumptions, senderTcp, receiverTcp); report.SubTests.push_back(result); result = SendRecvDouble(assumptions, senderTcp, receiverTcp); report.SubTests.push_back(result); result = SendRecvBuf(assumptions, senderTcp, receiverTcp); report.SubTests.push_back(result); result = SendRecvCharString(assumptions, senderTcp, receiverTcp); report.SubTests.push_back(result); UdpSocket senderUdp, receiverUdp; result = SelfConnect(11111, senderUdp, receiverUdp); report.SubTests.push_back(result); assumptions = result.Passed; result = SendRecvBuf(assumptions, senderUdp, receiverUdp); report.SubTests.push_back(result); // set top-level report report.Passed = true; for (auto& subtest : report.SubTests) { if (!subtest.Passed) { report.Passed = false; break; } } return report; }
23.434535
85
0.570202
akfreed
e8ecdaba33e0129890adb674a80dc6aedd1a59a4
564
hpp
C++
src/breakout/ball_object.hpp
clsrfish/learnogl
3e1cc42a595dd12779268ba587ef68fa4991e1f5
[ "Apache-2.0" ]
null
null
null
src/breakout/ball_object.hpp
clsrfish/learnogl
3e1cc42a595dd12779268ba587ef68fa4991e1f5
[ "Apache-2.0" ]
null
null
null
src/breakout/ball_object.hpp
clsrfish/learnogl
3e1cc42a595dd12779268ba587ef68fa4991e1f5
[ "Apache-2.0" ]
null
null
null
#if !defined(BALL_OBJECT_H) #define BALL_OBJECT_H #include "./game_object.hpp" namespace breakout { class BallObject : public GameObject { public: // ball state float Radius; bool Stuck; BallObject(); BallObject(glm::vec2 pos, float radius, glm::vec2 velocity, Texture2D sprite); ~BallObject(); glm::vec2 Move(float dt, unsigned int windowWidth); void Reset(glm::vec2 pos, glm::vec2 velocity); private: /* data */ }; } // namespace breakout #endif // BALL_OBJECT_H
19.448276
86
0.613475
clsrfish
e8ef2e7dfc0e4b9073b3f91f0947ba70037b8eff
7,739
cc
C++
src/metrics_filter_interpreter.cc
mxzeng/gestures
4d354c4fa38e74fcb8f8a88a903e6fc080f83bc1
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
src/metrics_filter_interpreter.cc
mxzeng/gestures
4d354c4fa38e74fcb8f8a88a903e6fc080f83bc1
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
src/metrics_filter_interpreter.cc
mxzeng/gestures
4d354c4fa38e74fcb8f8a88a903e6fc080f83bc1
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright (c) 2013 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gestures/include/metrics_filter_interpreter.h" #include <cmath> #include "gestures/include/filter_interpreter.h" #include "gestures/include/finger_metrics.h" #include "gestures/include/gestures.h" #include "gestures/include/logging.h" #include "gestures/include/prop_registry.h" #include "gestures/include/tracer.h" #include "gestures/include/util.h" namespace gestures { MetricsFilterInterpreter::MetricsFilterInterpreter( PropRegistry* prop_reg, Interpreter* next, Tracer* tracer, GestureInterpreterDeviceClass devclass) : FilterInterpreter(NULL, next, tracer, false), mstate_mm_(kMaxFingers * MState::MaxHistorySize()), history_mm_(kMaxFingers), devclass_(devclass), mouse_movement_session_index_(0), mouse_movement_current_session_length(0), mouse_movement_current_session_start(0), mouse_movement_current_session_last(0), mouse_movement_current_session_distance(0), noisy_ground_distance_threshold_(prop_reg, "Metrics Noisy Ground Distance", 10.0), noisy_ground_time_threshold_(prop_reg, "Metrics Noisy Ground Time", 0.1), mouse_moving_time_threshold_(prop_reg, "Metrics Mouse Moving Time", 0.05), mouse_control_warmup_sessions_(prop_reg, "Metrics Mouse Warmup Session", 100) { InitName(); } void MetricsFilterInterpreter::SyncInterpretImpl(HardwareState* hwstate, stime_t* timeout) { if (devclass_ == GESTURES_DEVCLASS_TOUCHPAD) { // Right now, we only want to update finger states for built-in touchpads // because all the generated metrics gestures would be put under each // platform's hat on the Chrome UMA dashboard. If we send metrics gestures // (e.g. noisy ground instances) for external peripherals (e.g. multi-touch // mice), they would be mistaken as from the platform's touchpad and thus // results in over-counting. // // TODO(sheckylin): Don't send metric gestures for external touchpads // either. // TODO(sheckylin): Track finger related metrics for external peripherals // as well after gaining access to the UMA log. UpdateFingerState(*hwstate); } else if (devclass_ == GESTURES_DEVCLASS_MOUSE || devclass_ == GESTURES_DEVCLASS_MULTITOUCH_MOUSE) { UpdateMouseMovementState(*hwstate); } next_->SyncInterpret(hwstate, timeout); } template <class StateType, class DataType> void MetricsFilterInterpreter::AddNewStateToBuffer( MemoryManagedList<StateType>* history, const DataType& data, const HardwareState& hwstate) { // The history buffer is already full, pop one if (history->size() == StateType::MaxHistorySize()) history->DeleteFront(); // Push the new finger state to the back of buffer StateType* current = history->PushNewEltBack(); if (!current) { Err("MetricsFilterInterpreter buffer out of space"); return; } current->Init(data, hwstate); } void MetricsFilterInterpreter::UpdateMouseMovementState( const HardwareState& hwstate) { // Skip finger-only hardware states for multi-touch mice. if (hwstate.rel_x == 0 && hwstate.rel_y == 0) return; // If the last movement is too long ago, we consider the history // an independent session. Report statistic for it and start a new // one. if (mouse_movement_current_session_length >= 1 && (hwstate.timestamp - mouse_movement_current_session_last > mouse_moving_time_threshold_.val_)) { // We skip the first a few sessions right after the user starts using the // mouse because they tend to be more noisy. if (mouse_movement_session_index_ >= mouse_control_warmup_sessions_.val_) ReportMouseStatistics(); mouse_movement_current_session_length = 0; mouse_movement_current_session_distance = 0; ++mouse_movement_session_index_; } // We skip the movement of the first event because there is no way to tell // the start time of it. if (!mouse_movement_current_session_length) { mouse_movement_current_session_start = hwstate.timestamp; } else { mouse_movement_current_session_distance += sqrtf(hwstate.rel_x * hwstate.rel_x + hwstate.rel_y * hwstate.rel_y); } mouse_movement_current_session_last = hwstate.timestamp; ++mouse_movement_current_session_length; } void MetricsFilterInterpreter::ReportMouseStatistics() { // At least 2 samples are needed to compute delta t. if (mouse_movement_current_session_length == 1) return; // Compute the average speed. stime_t session_time = mouse_movement_current_session_last - mouse_movement_current_session_start; double avg_speed = mouse_movement_current_session_distance / session_time; // Send the metrics gesture. ProduceGesture(Gesture(kGestureMetrics, mouse_movement_current_session_start, mouse_movement_current_session_last, kGestureMetricsTypeMouseMovement, avg_speed, session_time)); } void MetricsFilterInterpreter::UpdateFingerState( const HardwareState& hwstate) { FingerHistoryMap removed; RemoveMissingIdsFromMap(&histories_, hwstate, &removed); for (FingerHistoryMap::const_iterator it = removed.begin(); it != removed.end(); ++it) { it->second->DeleteAll(); history_mm_.Free(it->second); } FingerState *fs = hwstate.fingers; for (short i = 0; i < hwstate.finger_cnt; i++) { FingerHistory* hp; // Update the map if the contact is new if (!MapContainsKey(histories_, fs[i].tracking_id)) { hp = history_mm_.Allocate(); if (!hp) { Err("FingerHistory out of space"); continue; } hp->Init(&mstate_mm_); histories_[fs[i].tracking_id] = hp; } else { hp = histories_[fs[i].tracking_id]; } // Check if the finger history contains interesting patterns AddNewStateToBuffer(hp, fs[i], hwstate); DetectNoisyGround(hp); } } bool MetricsFilterInterpreter::DetectNoisyGround( const FingerHistory* history) { MState* current = history->Tail(); size_t n_samples = history->size(); // Noise pattern takes 3 samples if (n_samples < 3) return false; MState* past_1 = current->prev_; MState* past_2 = past_1->prev_; // Noise pattern needs to happen in a short period of time if(current->timestamp - past_2->timestamp > noisy_ground_time_threshold_.val_) { return false; } // vec[when][x,y] float vec[2][2]; vec[0][0] = current->data.position_x - past_1->data.position_x; vec[0][1] = current->data.position_y - past_1->data.position_y; vec[1][0] = past_1->data.position_x - past_2->data.position_x; vec[1][1] = past_1->data.position_y - past_2->data.position_y; const float thr = noisy_ground_distance_threshold_.val_; // We dictate the noise pattern as two consecutive big moves in // opposite directions in either X or Y for (size_t i = 0; i < arraysize(vec[0]); i++) if ((vec[0][i] < -thr && vec[1][i] > thr) || (vec[0][i] > thr && vec[1][i] < -thr)) { ProduceGesture(Gesture(kGestureMetrics, past_2->timestamp, current->timestamp, kGestureMetricsTypeNoisyGround, vec[0][i], vec[1][i])); return true; } return false; } } // namespace gestures
37.206731
79
0.68032
mxzeng
e8f1e771a41dd05d5ac23c8f7ba8886f641d2b04
344
hpp
C++
src/searches/benchmarks.hpp
adienes/remainder-tree
0aa76214ab6f2a4389ec45a239ea660749989a90
[ "MIT" ]
null
null
null
src/searches/benchmarks.hpp
adienes/remainder-tree
0aa76214ab6f2a4389ec45a239ea660749989a90
[ "MIT" ]
null
null
null
src/searches/benchmarks.hpp
adienes/remainder-tree
0aa76214ab6f2a4389ec45a239ea660749989a90
[ "MIT" ]
null
null
null
#ifndef REMAINDERTREE_SRC_SEARCHES_BENCHMARKS_H_ #define REMAINDERTREE_SRC_SEARCHES_BENCHMARKS_H_ //std::function< std::vector<bool> (long N)> remember this is what is being passed in! #include <vector> std::vector<bool> constant_slow(long); std::vector<bool> random_zz(long, long, long); #endif //REMAINDERTREE_SRC_SEARCHES_BENCHMARKS_H_
26.461538
86
0.802326
adienes
e8f637ad13bb661a9253fcf598c2c0e248e03ae3
2,193
hpp
C++
include/codegen/include/Oculus/Platform/MessageWithMatchmakingEnqueueResult.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Oculus/Platform/MessageWithMatchmakingEnqueueResult.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Oculus/Platform/MessageWithMatchmakingEnqueueResult.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:07 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: Oculus.Platform.Message`1 #include "Oculus/Platform/Message_1.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: Oculus::Platform::Models namespace Oculus::Platform::Models { // Forward declaring type: MatchmakingEnqueueResult class MatchmakingEnqueueResult; } // Forward declaring namespace: System namespace System { // Skipping declaration: IntPtr because it is already included! } // Completed forward declares // Type namespace: Oculus.Platform namespace Oculus::Platform { // Autogenerated type: Oculus.Platform.MessageWithMatchmakingEnqueueResult class MessageWithMatchmakingEnqueueResult : public Oculus::Platform::Message_1<Oculus::Platform::Models::MatchmakingEnqueueResult*> { public: // protected Oculus.Platform.Models.MatchmakingEnqueueResult GetDataFromMessage(System.IntPtr c_message) // Offset: 0xE8E7E0 Oculus::Platform::Models::MatchmakingEnqueueResult* GetDataFromMessage(System::IntPtr c_message); // public System.Void .ctor(System.IntPtr c_message) // Offset: 0xE88740 // Implemented from: Oculus.Platform.Message`1 // Base method: System.Void Message`1::.ctor(System.IntPtr c_message) // Base method: System.Void Message::.ctor(System.IntPtr c_message) static MessageWithMatchmakingEnqueueResult* New_ctor(System::IntPtr c_message); // public override Oculus.Platform.Models.MatchmakingEnqueueResult GetMatchmakingEnqueueResult() // Offset: 0xE8E79C // Implemented from: Oculus.Platform.Message // Base method: Oculus.Platform.Models.MatchmakingEnqueueResult Message::GetMatchmakingEnqueueResult() Oculus::Platform::Models::MatchmakingEnqueueResult* GetMatchmakingEnqueueResult(); }; // Oculus.Platform.MessageWithMatchmakingEnqueueResult } DEFINE_IL2CPP_ARG_TYPE(Oculus::Platform::MessageWithMatchmakingEnqueueResult*, "Oculus.Platform", "MessageWithMatchmakingEnqueueResult"); #pragma pack(pop)
48.733333
137
0.760146
Futuremappermydud
e8fc5928349f4b930c3d40219bd4f5a2ea1a92c5
4,699
cpp
C++
src/soundproducer-track-manager.cpp
adct-the-experimenter/Binaural-Audio-Editor
213e37f6cfe0530f0091b82a700085159ee7babe
[ "BSD-3-Clause" ]
42
2019-05-20T12:54:14.000Z
2022-03-18T01:01:56.000Z
src/soundproducer-track-manager.cpp
adct-the-experimenter/Binaural-Audio-Editor
213e37f6cfe0530f0091b82a700085159ee7babe
[ "BSD-3-Clause" ]
21
2019-05-13T18:40:32.000Z
2021-05-03T20:17:44.000Z
src/soundproducer-track-manager.cpp
adct-the-experimenter/Binaural-Audio-Editor
213e37f6cfe0530f0091b82a700085159ee7babe
[ "BSD-3-Clause" ]
5
2020-05-08T06:02:07.000Z
2021-04-17T12:15:41.000Z
#include "soundproducer-track-manager.h" SoundProducerTrackManager::SoundProducerTrackManager(const wxString& title,ALCdevice* thisAudioDevice,ALCcontext* thisAudioContext) : Track(title) { //initialize audio player audioPlayer = new OpenALSoftPlayer(); audioPlayer->SetReferenceToAudioContext(thisAudioContext); audioPlayer->SetReferenceToAudioDevice(thisAudioDevice); soundProducerTracks_vec = nullptr; SoundProducerTrackManager::SetSoundPlayingBool(false); } SoundProducerTrackManager::~SoundProducerTrackManager() { if(audioPlayer != nullptr) { delete audioPlayer; } } void SoundProducerTrackManager::SetReferenceToAudioDevice(ALCdevice* thisAudioDevice){audioDevicePtr = thisAudioDevice;} void SoundProducerTrackManager::SetReferenceToAudioContext(ALCcontext* thisAudioContext){alContextPtr = thisAudioContext;} void SoundProducerTrackManager::SetReferenceToSoundProducerTrackVector(std::vector <SoundProducerTrack*> *thisTrackVec) { soundProducerTracks_vec = thisTrackVec; } void SoundProducerTrackManager::AddSourceOfLastTrackToSoundProducerTrackManager() { if(soundProducerTracks_vec != nullptr) { ALuint* thisSource = soundProducerTracks_vec->at(soundProducerTracks_vec->size() - 1)->GetReferenceToTrackSource(); soundproducertracks_sources_vector.push_back(thisSource); } } void SoundProducerTrackManager::RemoveSourceOfLastTrackFromSoundProducerTrackManager() { soundproducertracks_sources_vector.pop_back(); } //Functions inherited from Track void SoundProducerTrackManager::SetReferenceToCurrentTimeVariable(double* thisTimeVariable){Track::SetReferenceToCurrentTimeVariable(thisTimeVariable);} double SoundProducerTrackManager::GetCurrentTime(){return Track::GetCurrentTime();} //function to call in timer loop, variable to manipulate gets changed here void SoundProducerTrackManager::FunctionToCallInPlayState() { SoundProducerTrackManager::SetSoundPlayingBool(true); //buffer audio for all track sources for(size_t i=0; i < soundProducerTracks_vec->size(); i++) { soundProducerTracks_vec->at(i)->FunctionToCallInPlayState(); } //play all sources in sync if(soundProducerTracks_vec->at(0)->GetReferenceToStereoAudioTrack()->GetAudioTrackState() == StereoAudioTrack::State::PLAYER_NULL) { audioPlayer->PlayMultipleSources(&soundproducertracks_sources_vector); } else if(soundProducerTracks_vec->at(0)->GetReferenceToStereoAudioTrack()->GetAudioTrackState() == StereoAudioTrack::State::PLAYER_PLAYING) { audioPlayer->PlayMultipleUpdatedPlayerBuffers(&soundproducertracks_sources_vector); } } void SoundProducerTrackManager::FunctionToCallInPauseState() { SoundProducerTrackManager::SetSoundPlayingBool(false); for(size_t i=0; i < soundProducerTracks_vec->size(); i++) { soundProducerTracks_vec->at(i)->FunctionToCallInPauseState(); } } void SoundProducerTrackManager::FunctionToCallInRewindState() { SoundProducerTrackManager::SetSoundPlayingBool(false); for(size_t i=0; i < soundProducerTracks_vec->size(); i++) { soundProducerTracks_vec->at(i)->FunctionToCallInRewindState(); } } void SoundProducerTrackManager::FunctionToCallInFastForwardState() { SoundProducerTrackManager::SetSoundPlayingBool(false); for(size_t i=0; i < soundProducerTracks_vec->size(); i++) { soundProducerTracks_vec->at(i)->FunctionToCallInFastForwardState(); } } void SoundProducerTrackManager::FunctionToCallInNullState() { SoundProducerTrackManager::SetSoundPlayingBool(false); for(size_t i=0; i < soundProducerTracks_vec->size(); i++) { soundProducerTracks_vec->at(i)->FunctionToCallInNullState(); } } void SoundProducerTrackManager::SetSoundPlayingBool(bool status){soundPlaying = status;} bool SoundProducerTrackManager::IsSoundBeingPlayed(){return soundPlaying;} void SoundProducerTrackManager::PlayThisTrackFromSoundProducerTrackVector(int& index) { //buffer audio for track source //soundProducerTracks_vec->at(index)->FunctionToCallInPlayState(); double current_time = 0; soundProducerTracks_vec->at(index)->BufferAndPlayAudio(current_time); } void SoundProducerTrackManager::PauseThisTrackFromSoundProducerTrackVector(int& index) { audioPlayer->PauseSource(soundproducertracks_sources_vector[index]); } void SoundProducerTrackManager::StopThisTrackFromSoundProducerTrackVector(int& index) { soundProducerTracks_vec->at(index)->StopAudio(); } void SoundProducerTrackManager::BrowseAudioForThisSoundProducer(SoundProducer* lastProducer) { //get sound producer name of last sound producer created soundProducerTracks_vec->back()->SelectSoundProducerByName(lastProducer->GetNameString()); soundProducerTracks_vec->back()->GetReferenceToStereoAudioTrack()->BrowseForInputAudioFile(); }
31.75
152
0.816557
adct-the-experimenter
33062b0624f425e8eef0c18b7ff4dfb3b67ef0eb
8,298
cxx
C++
third-party/libstudxml/xml/serializer.cxx
haquocviet/xlnt
8f39375f4c29e7f7590efaeb6ce8c56490560c1f
[ "Unlicense" ]
8
2019-02-28T14:49:56.000Z
2022-03-29T06:32:09.000Z
third-party/libstudxml/xml/serializer.cxx
haquocviet/xlnt
8f39375f4c29e7f7590efaeb6ce8c56490560c1f
[ "Unlicense" ]
2
2021-04-09T15:36:05.000Z
2021-11-17T22:38:10.000Z
third-party/libstudxml/xml/serializer.cxx
haquocviet/xlnt
8f39375f4c29e7f7590efaeb6ce8c56490560c1f
[ "Unlicense" ]
3
2019-12-31T14:04:17.000Z
2022-03-18T11:44:49.000Z
// file : xml/serializer.cxx // copyright : Copyright (c) 2013-2017 Code Synthesis Tools CC // license : MIT; see accompanying LICENSE file #include <new> // std::bad_alloc #include <cstring> // std::strlen #include <xml/serializer> using namespace std; namespace xml { // serialization // void serialization:: init () { if (!name_.empty ()) { what_ += name_; what_ += ": "; } what_ += "error: "; what_ += description_; } // serializer // extern "C" genxStatus genx_write (void* p, constUtf8 us) { // It would have been easier to throw the exception directly, // however, the Genx code is most likely not exception safe. // ostream* os (static_cast<ostream*> (p)); const char* s (reinterpret_cast<const char*> (us)); os->write (s, static_cast<streamsize> (strlen (s))); return os->good () ? GENX_SUCCESS : GENX_IO_ERROR; } extern "C" genxStatus genx_write_bound (void* p, constUtf8 start, constUtf8 end) { ostream* os (static_cast<ostream*> (p)); const char* s (reinterpret_cast<const char*> (start)); streamsize n (static_cast<streamsize> (end - start)); os->write (s, n); return os->good () ? GENX_SUCCESS : GENX_IO_ERROR; } extern "C" genxStatus genx_flush (void* p) { ostream* os (static_cast<ostream*> (p)); os->flush (); return os->good () ? GENX_SUCCESS : GENX_IO_ERROR; } serializer:: ~serializer () { if (s_ != 0) genxDispose (s_); } serializer:: serializer (ostream& os, const string& oname, unsigned short ind) : os_ (os), os_state_ (os.exceptions ()), oname_ (oname), depth_ (0) { // Temporarily disable exceptions on the stream. // os_.exceptions (ostream::goodbit); // Allocate the serializer. Make sure nothing else can throw after // this call since otherwise we will leak it. // s_ = genxNew (0, 0, 0); if (s_ == 0) throw bad_alloc (); genxSetUserData (s_, &os_); if (ind != 0) genxSetPrettyPrint (s_, ind); sender_.send = &genx_write; sender_.sendBounded = &genx_write_bound; sender_.flush = &genx_flush; if (genxStatus e = genxStartDocSender (s_, &sender_)) { string m (genxGetErrorMessage (s_, e)); genxDispose (s_); throw serialization (oname, m); } } void serializer:: handle_error (genxStatus e) const { switch (e) { case GENX_ALLOC_FAILED: throw bad_alloc (); case GENX_IO_ERROR: // Restoring the original exception state should trigger the // exception. If it doesn't (e.g., because the user didn't // configure the stream to throw), then fall back to the // serialiation exception. // os_.exceptions (os_state_); // Fall through. default: throw serialization (oname_, genxGetErrorMessage (s_, e)); } } void serializer:: start_element (const string& ns, const string& name) { if (genxStatus e = genxStartElementLiteral ( s_, reinterpret_cast<constUtf8> (ns.empty () ? 0 : ns.c_str ()), reinterpret_cast<constUtf8> (name.c_str ()))) handle_error (e); depth_++; } void serializer:: end_element () { if (genxStatus e = genxEndElement (s_)) handle_error (e); // Call EndDocument() if we are past the root element. // if (--depth_ == 0) { if (genxStatus e = genxEndDocument (s_)) handle_error (e); // Also restore the original exception state on the stream. // os_.exceptions (os_state_); } } void serializer:: end_element (const string& ns, const string& name) { constUtf8 cns, cn; genxStatus e; if ((e = genxGetCurrentElement (s_, &cns, &cn)) || reinterpret_cast<const char*> (cn) != name || (cns == 0 ? !ns.empty () : reinterpret_cast<const char*> (cns) != ns)) { handle_error (e != GENX_SUCCESS ? e : GENX_SEQUENCE_ERROR); } end_element (); } void serializer:: element (const string& ns, const string& n, const string& v) { start_element (ns, n); element (v); } void serializer:: start_attribute (const string& ns, const string& name) { if (genxStatus e = genxStartAttributeLiteral ( s_, reinterpret_cast<constUtf8> (ns.empty () ? 0 : ns.c_str ()), reinterpret_cast<constUtf8> (name.c_str ()))) handle_error (e); } void serializer:: end_attribute () { if (genxStatus e = genxEndAttribute (s_)) handle_error (e); } void serializer:: end_attribute (const string& ns, const string& name) { constUtf8 cns, cn; genxStatus e; if ((e = genxGetCurrentAttribute (s_, &cns, &cn)) || reinterpret_cast<const char*> (cn) != name || (cns == 0 ? !ns.empty () : reinterpret_cast<const char*> (cns) != ns)) { handle_error (e != GENX_SUCCESS ? e : GENX_SEQUENCE_ERROR); } end_attribute (); } void serializer:: attribute (const string& ns, const string& name, const string& value) { if (genxStatus e = genxAddAttributeLiteral ( s_, reinterpret_cast<constUtf8> (ns.empty () ? 0 : ns.c_str ()), reinterpret_cast<constUtf8> (name.c_str ()), reinterpret_cast<constUtf8> (value.c_str ()))) handle_error (e); } void serializer:: characters (const string& value) { if (genxStatus e = genxAddCountedText ( s_, reinterpret_cast<constUtf8> (value.c_str ()), value.size ())) handle_error (e); } void serializer:: namespace_decl (const string& ns, const string& p) { if (genxStatus e = ns.empty () && p.empty () ? genxUnsetDefaultNamespace (s_) : genxAddNamespaceLiteral ( s_, reinterpret_cast<constUtf8> (ns.c_str ()), reinterpret_cast<constUtf8> (p.c_str ()))) handle_error (e); } void serializer:: xml_decl (const string& ver, const string& enc, const string& stl) { if (genxStatus e = genxXmlDeclaration ( s_, reinterpret_cast<constUtf8> (ver.c_str ()), (enc.empty () ? 0 : reinterpret_cast<constUtf8> (enc.c_str ())), (stl.empty () ? 0 : reinterpret_cast<constUtf8> (stl.c_str ())))) handle_error (e); } void serializer:: doctype_decl (const string& re, const string& pi, const string& si, const string& is) { if (genxStatus e = genxDoctypeDeclaration ( s_, reinterpret_cast<constUtf8> (re.c_str ()), (pi.empty () ? 0 : reinterpret_cast<constUtf8> (pi.c_str ())), (si.empty () ? 0 : reinterpret_cast<constUtf8> (si.c_str ())), (is.empty () ? 0 : reinterpret_cast<constUtf8> (is.c_str ())))) handle_error (e); } bool serializer:: lookup_namespace_prefix (const string& ns, string& p) const { // Currently Genx will create a namespace mapping if one doesn't // already exist. // genxStatus e; genxNamespace gns ( genxDeclareNamespace ( s_, reinterpret_cast<constUtf8> (ns.c_str ()), 0, &e)); if (e != GENX_SUCCESS) handle_error (e); p = reinterpret_cast<const char*> (genxGetNamespacePrefix (gns)); return true; } qname serializer:: current_element () const { constUtf8 ns, n; if (genxStatus e = genxGetCurrentElement (s_, &ns, &n)) handle_error (e); return qname (ns != 0 ? reinterpret_cast<const char*> (ns) : "", reinterpret_cast<const char*> (n)); } qname serializer:: current_attribute () const { constUtf8 ns, n; if (genxStatus e = genxGetCurrentAttribute (s_, &ns, &n)) handle_error (e); return qname (ns != 0 ? reinterpret_cast<const char*> (ns) : "", reinterpret_cast<const char*> (n)); } void serializer:: suspend_indentation () { if (genxStatus e = genxSuspendPrettyPrint (s_)) handle_error (e); } void serializer:: resume_indentation () { if (genxStatus e = genxResumePrettyPrint (s_)) handle_error (e); } size_t serializer:: indentation_suspended () const { return static_cast<size_t> (genxPrettyPrintSuspended (s_)); } }
25.453988
78
0.600265
haquocviet
3306cd5d1317baed6256f45ba3c47e4b0136ae61
2,700
hpp
C++
SOLVER/src/core/element/material/elastic/Elastic.hpp
nicklinyi/AxiSEM-3D
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
[ "MIT" ]
8
2020-06-05T01:13:20.000Z
2022-02-24T05:11:50.000Z
SOLVER/src/core/element/material/elastic/Elastic.hpp
nicklinyi/AxiSEM-3D
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
[ "MIT" ]
24
2020-10-21T19:03:38.000Z
2021-11-17T21:32:02.000Z
SOLVER/src/core/element/material/elastic/Elastic.hpp
nicklinyi/AxiSEM-3D
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
[ "MIT" ]
5
2020-06-21T11:54:22.000Z
2021-06-23T01:02:39.000Z
// // Elastic.hpp // AxiSEM3D // // Created by Kuangdai Leng on 2/26/19. // Copyright © 2019 Kuangdai Leng. All rights reserved. // // elastic material #ifndef Elastic_hpp #define Elastic_hpp #include "Attenuation.hpp" class Elastic { public: // constructor Elastic(bool is1D, std::unique_ptr<Attenuation> &attenuation): m1D(is1D), mAttenuation(attenuation.release()) { // nothing } // copy constructor Elastic(const Elastic &other): m1D(other.m1D), mAttenuation((other.mAttenuation == nullptr) ? nullptr : other.mAttenuation->clone()) { // nothing } // destructor virtual ~Elastic() = default; // clone for copy constructor virtual std::unique_ptr<Elastic> clone() const = 0; // 1D operation bool is1D() const { return m1D; } // check compatibility virtual void checkCompatibility(int nr, bool elemInFourier) const { if (mAttenuation) { mAttenuation->checkCompatibility(nr, elemInFourier, m1D); } } // reset to zero void resetToZero() const { if (mAttenuation) { mAttenuation->resetToZero(); } } ///////////////////////// strain to stress ///////////////////////// // RTZ coordinates virtual bool inRTZ() const = 0; // strain => stress in Fourier space virtual void strainToStress_FR(const eigen::vec_ar6_CMatPP_RM &strain, eigen::vec_ar6_CMatPP_RM &stress, int nu_1) const = 0; // strain => stress in cardinal space virtual void strainToStress_CD(const eigen::RMatXN6 &strain, eigen::RMatXN6 &stress, int nr) const = 0; ///////////////////////// attenuation ///////////////////////// protected: // attenuation in Fourier space void applyAttenuation(const eigen::vec_ar6_CMatPP_RM &strain, eigen::vec_ar6_CMatPP_RM &stress, int nu_1) const { if (mAttenuation) { mAttenuation->apply(strain, stress, nu_1); } } // attenuation in cardinal space void applyAttenuation(const eigen::RMatXN6 &strain, eigen::RMatXN6 &stress, int nr) const { if (mAttenuation) { mAttenuation->apply(strain, stress, nr); } } ////////////////////////// data ////////////////////////// protected: // 1D/3D flag const bool m1D; private: // attenuation const std::unique_ptr<Attenuation> mAttenuation; }; #endif /* Elastic_hpp */
26.213592
77
0.537778
nicklinyi
331012ad1f9182cfb56eee2c8fb656a32fc7dc7a
1,642
cpp
C++
src/platform/testing/alchemy/audio.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
11
2015-03-02T07:43:00.000Z
2021-12-04T04:53:02.000Z
src/platform/testing/alchemy/audio.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
1
2015-03-28T17:17:13.000Z
2016-10-10T05:49:07.000Z
src/platform/testing/alchemy/audio.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
3
2016-11-04T01:14:31.000Z
2020-05-07T23:42:27.000Z
/**************************** Copyright © 2006-2011 Luke Salisbury This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ****************************/ #include "../luxengine.h" #include "../functions.h" #include "../gamepack.h" AudioSystem::AudioSystem ( ) { lux::core->SystemMessage(SYSTEM_MESSAGE_LOG) << "Audio System" << std::endl; } AudioSystem::~AudioSystem ( ) { } bool AudioSystem::Init() { return true; } bool AudioSystem::LoadAudio(std::string name) { return false; } bool AudioSystem::PlayEffect ( std::string requestSound ) { return false; } bool AudioSystem::PlayDialog ( int requestSound ) { return false; } bool AudioSystem::PlayMusic ( std::string requestMusic, int loop, int fadeLength ) { return false; } int AudioSystem::SetMusicVolume(int volume) { return 0; } int AudioSystem::SetEffectsVolume(int volume) { return 0; } void AudioSystem::Pause() { }
26.063492
243
0.732643
mokoi
33109be627e39e30e59be26f77467aa853c51efe
16,952
cpp
C++
MarlinClient/TestsetClient/TestWS.cpp
zYg-sys/Marlin
eeabb4d324c5f8d253a50c106208bb833cb824e8
[ "MIT" ]
23
2016-09-16T11:25:54.000Z
2022-03-03T07:18:57.000Z
MarlinClient/TestsetClient/TestWS.cpp
zYg-sys/Marlin
eeabb4d324c5f8d253a50c106208bb833cb824e8
[ "MIT" ]
26
2016-10-21T11:07:54.000Z
2022-03-05T18:27:03.000Z
MarlinClient/TestsetClient/TestWS.cpp
zYg-sys/Marlin
eeabb4d324c5f8d253a50c106208bb833cb824e8
[ "MIT" ]
7
2018-09-11T12:17:46.000Z
2021-07-08T09:10:04.000Z
///////////////////////////////////////////////////////////////////////////////// // // SourceFile: TestWS.cpp // // Marlin Server: Internet server/client // // Copyright (c) 2015-2018 ir. W.E. Huisman // All rights reserved // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "stdafx.h" #include "SOAPMessage.h" #include "XMLMessage.h" #include "TestClient.h" #include "HTTPClient.h" #include "WebServiceClient.h" #include "GetLastErrorAsString.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif int DoSend(HTTPClient& p_client,SOAPMessage* p_msg,char* p_what,bool p_fault = false) { bool result = false; // 1: CHECK SYNCHROON VERZONDEN. NORMAAL BERICHT if(p_client.Send(p_msg)) { if(p_msg->GetFaultCode().IsEmpty()) { xprintf("Received: %s\n%s",p_msg->GetSoapAction().GetString(),p_msg->GetSoapMessage().GetString()); CString action = p_msg->GetSoapAction(); CString test = p_msg->GetParameter("Three"); int number = p_msg->GetParameterInteger("Four"); CString testing = p_msg->GetParameter("Testing"); xprintf("Answer: %s : %s\n","Three",test.GetString()); xprintf("Answer: %s : %d\n","Four",number); // See if the answer is satisfying if(test == "DEF" || number == 123 && action == "TestMessageResponse" || testing == "OK") { result = true; } // SUMMARY OF THE TEST // --- "---------------------------------------------- - ------ printf("Send: SOAP Message %-27s : %s\n",p_what,result ? "OK" : "ERROR"); } else { if(p_fault) { if(p_msg->GetFaultCode() == "FX1" && p_msg->GetFaultActor() == "Server" && p_msg->GetFaultString() == "Testing SOAP Fault" && p_msg->GetFaultDetail() == "See if the SOAP Fault does work!") { result = true; } // SUMMARY OF THE TEST // --- "---------------------------------------------- - ------ printf("Send: SOAP Message %-27s : %s\n",p_what,result ? "OK" : "ERROR"); } else { // But we where NOT expecting a FAULT! printf("Answer with error: %s\n",(LPCTSTR)p_msg->GetFault()); printf("SOAP Fault code: %s\n",(LPCTSTR)p_msg->GetFaultCode()); printf("SOAP Fault actor: %s\n",(LPCTSTR)p_msg->GetFaultActor()); printf("SOAP Fault string: %s\n",(LPCTSTR)p_msg->GetFaultString()); printf("SOAP FAULT detail: %s\n",(LPCTSTR)p_msg->GetFaultDetail()); } } } else { // Possibly a SOAP fault as answer if(!p_msg->GetFaultCode().IsEmpty()) { printf("SOAP Fault: %s\n",p_msg->GetFault().GetString()); } else { // Raw HTTP error BYTE* response = NULL; unsigned length = 0; p_client.GetResponse(response, length); printf("Message not sent!\n"); printf("Service answer: %s\n", (char*)response); printf("HTTP Client error: %s\n", p_client.GetStatusText().GetString()); } } // ready with the message delete p_msg; return result ? 0 : 1; } int DoSendPrice(HTTPClient& p_client, SOAPMessage* p_msg,double p_price) { bool result = false; // 1: CHECK SYNCHROON VERZONDEN. NORMAAL BERICHT if (p_client.Send(p_msg)) { if(p_msg->GetFaultCode().IsEmpty()) { double priceInclusive = p_msg->GetParameterDouble("PriceInclusive"); if(priceInclusive - (p_price * 1.21) < 0.005) // Dutch VAT percentage { result = true; } } else { printf("Answer with error: %s\n", (LPCTSTR)p_msg->GetFault()); printf("SOAP Fault code: %s\n", (LPCTSTR)p_msg->GetFaultCode()); printf("SOAP Fault actor: %s\n", (LPCTSTR)p_msg->GetFaultActor()); printf("SOAP Fault string: %s\n", (LPCTSTR)p_msg->GetFaultString()); printf("SOAP FAULT detail: %s\n", (LPCTSTR)p_msg->GetFaultDetail()); } } else { // Possibly a SOAP fault as answer if(!p_msg->GetFaultCode().IsEmpty()) { printf("SOAP Fault: %s\n", p_msg->GetFault().GetString()); } else { // Raw HTTP error BYTE* response = NULL; unsigned length = 0; p_client.GetResponse(response, length); printf("Message not sent!\n"); printf("Service answer: %s\n", (char*)response); printf("HTTP Client error: %s\n", p_client.GetStatusText().GetString()); } } // SUMMARY OF THE TEST // --- "---------------------------------------------- - ------ printf("Send: SOAP datatype double calculation : %s\n", result ? "OK" : "ERROR"); // ready with the message delete p_msg; return (result == true) ? 0 : 1; } SOAPMessage* CreateSoapMessage(CString p_namespace ,CString p_command ,CString p_url ,SoapVersion p_version = SoapVersion::SOAP_12 ,XMLEncryption p_encrypt = XMLEncryption::XENC_Plain) { // Build message SOAPMessage* msg = new SOAPMessage(p_namespace,p_command,p_version,p_url); msg->SetParameter("One","ABC"); msg->SetParameter("Two","1-2-3"); // "17" will stop the server XMLElement* param = msg->SetParameter("Units",""); XMLElement* enh1 = msg->AddElement(param,"Unit",XDT_String,""); XMLElement* enh2 = msg->AddElement(param,"Unit",XDT_String,""); msg->SetElement(enh1,"Unitnumber",12345); msg->SetElement(enh2,"Unitnumber",67890); msg->SetAttribute(enh1,"Independent",true); msg->SetAttribute(enh2,"Independent",false); if(p_encrypt != XMLEncryption::XENC_Plain) { msg->SetSecurityLevel(p_encrypt); msg->SetSecurityPassword("ForEverSweet16"); if(p_encrypt == XMLEncryption::XENC_Body) { // msg->SetSigningMethod(CALG_RSA_SIGN); } } return msg; } SOAPMessage* CreateSoapPriceMessage(CString p_namespace ,CString p_command ,CString p_url ,double p_price) { SOAPMessage* msg = new SOAPMessage(p_namespace,p_command,SoapVersion::SOAP_12,p_url); msg->SetParameter("Price", p_price); return msg; } int TestReliableMessaging(HTTPClient* p_client,CString p_namespace,CString p_action,CString p_url,bool p_tokenProfile) { int errors = 0; int totalDone = 0; WebServiceClient client(p_namespace,p_url,"",true); client.SetHTTPClient(p_client); client.SetLogAnalysis(p_client->GetLogging()); // testing soap compression // client.SetSoapCompress(true); // Testing with WS-Security Token profile if(p_tokenProfile) { client.SetUser("marlin"); client.SetPassword("M@rl!nS3cr3t"); client.SetTokenProfile(true); } SOAPMessage* message = nullptr; try { // Client must be opened for RM protocol client.Open(); for(int ind = 0; ind < NUM_RM_TESTS; ++ind) { // Make a copy of the message message = CreateSoapMessage(p_namespace,p_action,p_url); // Forced that it is not set to reliable. It doesn't have to, becouse the client.Send() will do that // message->SetReliability(true); xprintf("Sending RM message: %s\n",message->GetSoapMessage().GetString()); if(client.Send(message)) { xprintf("Received: %s\n%s",message->GetSoapAction().GetString(),message->GetSoapMessage().GetString()); CString action = message->GetSoapAction(); CString test = message->GetParameter("Three"); int number = message->GetParameterInteger("Four"); xprintf("Answer: %s : %s\n","Three",test.GetString()); xprintf("Answer: %s : %d\n","Four ",number); bool result = false; if(test == "DEF" || number == 123 && action == "TestMessageResponse") { ++totalDone; result = true; } else { printf("Answer with fault: %s\n",message->GetFault().GetString()); result = false; } // SUMMARY OF THE TEST // --- "---------------------------------------------- - ------ printf("Send: SOAP WS-ReliableMessaging : %s\n",result ? "OK" : "ERROR"); errors += result ? 0 : 1; } else { ++errors; printf("Message **NOT** correctly sent!\n"); printf("Error code WebServiceClient: %s\n",client.GetErrorText().GetString()); printf("Return message error:\n%s\n",message->GetFault().GetString()); } // Ready with the message if(message) { delete message; message = nullptr; } } // Must be closed to complete RM protocol client.Close(); } catch(StdException& error) { ++errors; printf("ERROR received : %s\n",error.GetErrorMessage().GetString()); printf("ERROR from WS Client: %s\n",client.GetErrorText().GetString()); } if(message) { delete message; message = nullptr; } return (totalDone == NUM_RM_TESTS) ? 0 : 1; } int DoSendByQueue(HTTPClient& p_client,CString p_namespace,CString p_action,CString p_url) { int times = 20; CString name("TestNumber"); for(int x = 1; x <= times; ++x) { SOAPMessage* message = CreateSoapMessage(p_namespace,p_action,p_url); message->SetParameter(name,x); p_client.AddToQueue(message); } // --- "---------------------------------------------- - ------ printf("Send: [%d] messages added to the sending queue : OK\n",times); return 0; } int DoSendAsyncQueue(HTTPClient& p_client,CString p_namespace,CString p_url) { int times = 10; CString resetMess("MarlinReset"); CString textMess ("MarlinText"); SOAPMessage* reset1 = new SOAPMessage(p_namespace,resetMess,SoapVersion::SOAP_12,p_url); SOAPMessage* reset2 = new SOAPMessage(p_namespace,resetMess,SoapVersion::SOAP_12,p_url); reset1->SetParameter("DoReset",true); reset2->SetParameter("DoReset",true); p_client.AddToQueue(reset1); for(int ind = 0;ind < times; ++ind) { SOAPMessage* msg = new SOAPMessage(p_namespace,textMess,SoapVersion::SOAP_12,p_url); msg->SetParameter("Text","This is a testing message to see if async SOAP messages are delivered."); p_client.AddToQueue(msg); } p_client.AddToQueue(reset2); // --- "---------------------------------------------- - ------ printf("Send: Asynchronous messages added to the queue : OK\n"); return 0; } inline CString CreateURL(CString p_extra) { CString url; url.Format("http://%s:%d/MarlinTest/%s",MARLIN_HOST,TESTING_HTTP_PORT,p_extra.GetString()); return url; } int TestWebservices(HTTPClient& client) { int errors = 0; extern CString logfileName; SOAPMessage* msg = nullptr; // Testing cookie function errors += TestCookies(client); // Standard values for messages CString namesp("http://interface.marlin.org/services"); CString command("TestMessage"); CString url(CreateURL("Insecure")); // Test 1 xprintf("TESTING STANDARD SOAP MESSAGE TO /MarlinTest/Insecure/\n"); xprintf("====================================================\n"); msg = CreateSoapMessage(namesp,command,url); errors += DoSend(client,msg,(char*)"insecure"); // Test 2 xprintf("TESTING BODY SIGNING SOAP TO /MarlinTest/BodySigning/\n"); xprintf("===================================================\n"); url = CreateURL("BodySigning"); msg = CreateSoapMessage(namesp,command,url,SoapVersion::SOAP_12, XMLEncryption::XENC_Signing); errors += DoSend(client,msg,(char*)"body signing"); // Test 3 xprintf("TESTING BODY ENCRYPTION SOAP TO /MarlinTest/BodyEncrypt/\n"); xprintf("======================================================\n"); url = CreateURL("BodyEncrypt"); msg = CreateSoapMessage(namesp,command,url, SoapVersion::SOAP_12, XMLEncryption::XENC_Body); errors += DoSend(client,msg,(char*)"body encrypting"); // Test 4 xprintf("TESTING WHOLE MESSAGE ENCRYPTION TO /MarlinTest/MessageEncrypt/\n"); xprintf("=============================================================\n"); url = CreateURL("MessageEncrypt"); msg = CreateSoapMessage(namesp,command,url, SoapVersion::SOAP_12, XMLEncryption::XENC_Message); errors += DoSend(client,msg,(char*)"message encrypting"); // Test 5 xprintf("TESTING RELIABLE MESSAGING TO /MarlinTest/Reliable/\n"); xprintf("=================================================\n"); url = CreateURL("Reliable"); errors += TestReliableMessaging(&client,namesp,command,url,false); // Test 6 xprintf("TESTING RELIABLE MESSAGING TO /MarlinTest/ReliableBA/ with WS-Security token profile\n"); xprintf("=================================================\n"); url = CreateURL("ReliableBA"); errors += TestReliableMessaging(&client,namesp,command,url,true); // Test 7 xprintf("TESTING THE TOKEN FUNCTION TO /MarlinTest/TestToken/\n"); xprintf("====================================================\n"); url = CreateURL("TestToken"); msg = CreateSoapMessage(namesp,command,url); client.SetSingleSignOn(true); CString user("CERT6\\Beheerder"); CString password("altijd"); client.SetUser(user); client.SetPassword(password); errors += DoSend(client,msg,(char*)"token testing"); client.SetSingleSignOn(false); // Test 8 xprintf("TESTING THE SUB-SITES FUNCTION TO /MarlinTest/TestToken/One/\n"); xprintf("TESTING THE SUB-SITES FUNCTION TO /MarlinTest/TestToken/Two/\n"); xprintf("============================================================\n"); CString url1 = CreateURL("TestToken/One"); CString url2 = CreateURL("TestToken/Two"); msg = CreateSoapMessage(namesp,command,url1); client.SetSingleSignOn(true); client.SetUser(user); client.SetPassword(password); errors += DoSend(client,msg,(char*)"single sign on"); msg = CreateSoapMessage(namesp,command,url2); errors += DoSend(client,msg,(char*)"single sign on"); client.SetSingleSignOn(false); // Test 9 xprintf("TESTING SOAP FAULT TO /MarlinTest/Insecure/\n"); xprintf("=================================================\n"); url = CreateURL("Insecure"); msg = CreateSoapMessage(namesp,command,url); msg->SetParameter("TestFault",true); errors += DoSend(client,msg,(char*)"soap fault",true); // Test 10 xprintf("TESTING UNICODE SENDING TO /MarlinTest/Insecure/\n"); xprintf("================================================\n"); url = CreateURL("Insecure"); msg = CreateSoapMessage(namesp,command,url); msg->SetSendUnicode(true); errors += DoSend(client,msg,(char*)"sending unicode"); // Test 11 xprintf("TESTING FILTERING CAPABILITIES TO /MarlinTest/Filter/\n"); xprintf("=====================================================\n"); url = CreateURL("Filter"); msg = CreateSoapPriceMessage(namesp,command,url,456.78); errors += DoSendPrice(client,msg,456.78); // Test 12 xprintf("TESTING HIGH SPEED QUEUE TO /MarlinTest/Insecure/\n"); xprintf("=================================================\n"); url = CreateURL("Insecure"); errors += DoSendByQueue(client,namesp,command,url); // Test 13 xprintf("TESTING ASYNCHRONEOUS SOAP MESSAGES TO /MarlinTest/Asynchrone/\n"); xprintf("==============================================================\n"); url = CreateURL("Asynchrone"); errors += DoSendAsyncQueue(client,namesp,url); // Waiting for the queue to drain printf("\nWait for last test to complete.\n"); while(client.GetQueueSize()) { Sleep(200); } printf("\n**READY**\n\nType a word and ENTER\n"); // Wait for key to occur // so the messages can be send and debugged :-) WaitForKey(); printf("Stopping the client\n"); client.StopClient(); printf("The client is %s\n",client.GetIsRunning() ? "still running!\n" : "stopped.\n"); // Any error found CString boodschap; int error = client.GetError(&boodschap); if(error) { CString systeemText = GetLastErrorAsString(error); printf("ERROR! Code: %d = %s\nErrortext: %s\n",error,systeemText.GetString(),boodschap.GetString()); } return errors; }
33.044834
114
0.611137
zYg-sys
33129146cb1044846470f9ed6329c2a1e51be0a9
3,522
cpp
C++
PrettyEngine/src/engine/Networking/Client.cpp
cristi191096/Pretty_Engine
53a5d305b3de5786223e3ad6775199dbc7b5e90c
[ "Apache-2.0" ]
null
null
null
PrettyEngine/src/engine/Networking/Client.cpp
cristi191096/Pretty_Engine
53a5d305b3de5786223e3ad6775199dbc7b5e90c
[ "Apache-2.0" ]
null
null
null
PrettyEngine/src/engine/Networking/Client.cpp
cristi191096/Pretty_Engine
53a5d305b3de5786223e3ad6775199dbc7b5e90c
[ "Apache-2.0" ]
1
2021-04-16T09:10:46.000Z
2021-04-16T09:10:46.000Z
#include "pepch.h" #include "Client.h" namespace PrettyEngine { Client::Client(bool isHost) : m_IsHost(isHost) { if (isHost) { m_Address.host = ENET_HOST_ANY; m_Address.port = 1234; m_Host = enet_host_create(&m_Address, 32, 2, 0, 0); if (m_Host == NULL) PE_ERROR("Host could not be initialised!"); } else { m_Host = enet_host_create(NULL, 1, 2, 0, 0); if (m_Host == NULL) PE_ERROR("Host could not be initialised!"); enet_address_set_host(&m_Address, "localhost"); m_Address.port = 1234; m_Peer = enet_host_connect(m_Host, &m_Address, 2, 0); if (m_Peer == NULL) PE_ERROR("No available peers for initializing an ENet connection!"); } } Client::~Client() { } void Client::SendData(void* data, size_t size) { if (!m_IsHost) { m_PlayerConnected = true; m_Data = enet_packet_create(data, size, ENET_PACKET_FLAG_RELIABLE); enet_peer_send(m_Peer, 0, m_Data); } else { m_Data = enet_packet_create(data, size, ENET_PACKET_FLAG_RELIABLE); enet_host_broadcast(m_Host, 0, m_Data); } while (enet_host_service(m_Host, &m_Event, 0) > 0) { if (m_IsHost) { //String data = "someClient"; int packetType = 0; switch (m_Event.type) { case ENET_EVENT_TYPE_CONNECT: m_PlayerConnected = true; m_ConnectedClients++; id = enet_packet_create(&m_ConnectedClients, sizeof(int), ENET_PACKET_FLAG_RELIABLE); enet_peer_send(m_Event.peer, 0, id); break; case ENET_EVENT_TYPE_RECEIVE: if (m_Event.packet && m_Event.packet->data) memcpy(&packetType, m_Event.packet->data, sizeof(int)); if (packetType == PacketType::LEVELINFO) { LevelInfo* tempInfo = new LevelInfo; memcpy(tempInfo, m_Event.packet->data, sizeof(LevelInfo)); if (!tempInfo->isFromHost) { memcpy(&m_LevelData, m_Event.packet->data, sizeof(LevelInfo)); } } if (packetType == PacketType::TRANSFORM) { TransformData* tempTransform = new TransformData; memcpy(tempTransform, m_Event.packet->data, sizeof(TransformData)); if (!tempTransform->isFromHost) { memcpy(&m_TransformData, m_Event.packet->data, sizeof(TransformData)); } } break; default: break; } } else { int packetType = 0; //m_PlayerConnected = true; //enet_peer_send(m_Peer, 0, m_Data); switch (m_Event.type) { case ENET_EVENT_TYPE_CONNECT: break; case ENET_EVENT_TYPE_RECEIVE: if (m_Event.packet && m_Event.packet->dataLength == sizeof(int)) { memcpy(&m_ClientID, m_Event.packet->data, sizeof(int)); } if (m_Event.packet && m_Event.packet->data) memcpy(&packetType, m_Event.packet->data, sizeof(int)); if (packetType == PacketType::LEVELINFO) { LevelInfo* tempInfo = new LevelInfo; memcpy(tempInfo, m_Event.packet->data, sizeof(LevelInfo)); if (tempInfo->isFromHost && tempInfo->clientID != m_ClientID) { memcpy(&m_LevelData, m_Event.packet->data, sizeof(LevelInfo)); } } if (packetType == PacketType::TRANSFORM) { TransformData* tempTransform = new TransformData; memcpy(tempTransform, m_Event.packet->data, sizeof(TransformData)); if (tempTransform->isFromHost && tempTransform->clientID != m_ClientID) memcpy(&m_TransformData, m_Event.packet->data, sizeof(TransformData)); } break; default: break; } } } } }
23.797297
90
0.638842
cristi191096
33135cc07e32c6a3d5c92fe5b3273e2978f26d72
2,387
cpp
C++
src/piper-token-to-cst.cpp
PiperLang/piper
7b2dc57793fca7f3bb153e399e36b0ad0ec33ca1
[ "MIT" ]
null
null
null
src/piper-token-to-cst.cpp
PiperLang/piper
7b2dc57793fca7f3bb153e399e36b0ad0ec33ca1
[ "MIT" ]
null
null
null
src/piper-token-to-cst.cpp
PiperLang/piper
7b2dc57793fca7f3bb153e399e36b0ad0ec33ca1
[ "MIT" ]
null
null
null
#include <array> #include <cassert> #include <cerrno> #include <cstring> #include <vector> #include <iostream> #include <scanner.hpp> #include <tokentype.hpp> #define INIT_BUFFER_SIZE 1024 int main(int argc, char *argv[]) { std::freopen(nullptr, "rb", stdin); if (std::ferror(stdin)) { throw std::runtime_error(std::strerror(errno)); } std::size_t len; std::array<char, INIT_BUFFER_SIZE> buf; std::vector<char> input; while ((len = std::fread(buf.data(), sizeof(buf[0]), buf.size(), stdin)) > 0) { if (std::ferror(stdin) && !std::feof(stdin)) { throw std::runtime_error(std::strerror(errno)); } input.insert(input.end(), buf.data(), buf.data() + len); } int idx = 0; assert(input.at(idx++) == 'P'); assert(input.at(idx++) == 'P'); assert(input.at(idx++) == 'R'); assert(input.at(idx++) == 'A'); assert(input.at(idx++) == 'L'); assert(input.at(idx++) == 'C'); assert(input.at(idx++) == 'F'); assert(input.at(idx++) == 'T'); assert(input.at(idx++) == 'T'); assert(input.at(idx++) == 0); int string_count = (int)input.at(idx++); std::cout << "String Count: " << string_count << std::endl; for (int i = 0; i < string_count; i++) { int single_string_length = (int)input.at(idx++); std::cout << " Single string (" << single_string_length << "): "; for (int p = 0; p < single_string_length; p++) { std::cout << input.at(idx++); } std::cout << std::endl; } while (true) { bool is_at_end = false; uint8_t token_type = input.at(idx++); uint8_t token_line = input.at(idx++); uint8_t token_column = input.at(idx++); std::cout << "(" << std::hex << (int)token_type << "): " << piper::Scanner::getTokenName(static_cast<piper::TokenType>(token_type)) << std::endl; switch (token_type) { case piper::TokenType::TOKEN_EOF: is_at_end = true; break; case piper::TokenType::FORMAT_STRING: case piper::TokenType::IDENTIFIER: case piper::TokenType::NUMBER: case piper::TokenType::STRING: idx++; break; } if (is_at_end) break; } // use input vector here }
27.125
86
0.528697
PiperLang
3315e71bb76a9986841cd5c493beee6dcfe223bb
5,774
cpp
C++
drivers/windows/drv_ndis_intermediate/notifyObj/src/dllmain.cpp
openPOWERLINK-Team/openPOWERLINK_V2
048650a80db37fa372330c3a900d2c8edb327e47
[ "BSD-3-Clause" ]
100
2016-05-18T06:38:44.000Z
2022-03-30T13:53:58.000Z
drivers/windows/drv_ndis_intermediate/notifyObj/src/dllmain.cpp
openPOWERLINK-Team/openPOWERLINK_V2
048650a80db37fa372330c3a900d2c8edb327e47
[ "BSD-3-Clause" ]
238
2016-03-31T06:52:57.000Z
2019-10-17T13:35:03.000Z
drivers/windows/drv_ndis_intermediate/notifyObj/src/dllmain.cpp
openPOWERLINK-Team/openPOWERLINK_V2
048650a80db37fa372330c3a900d2c8edb327e47
[ "BSD-3-Clause" ]
72
2016-04-04T07:29:24.000Z
2022-03-13T05:26:54.000Z
/** ******************************************************************************** \file dllmain.cpp \brief Main file for notify object dll for Windows NDIS intermediate driver This file implements the DLL access routines for notify object. \ingroup module_notify_ndisim *******************************************************************************/ /*------------------------------------------------------------------------------ Copyright (c) 2015, Kalycito Infotech Private Limited All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holders 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 COPYRIGHT HOLDERS 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 "stdafx.h" #include "resource.h" #include "notifyObj_i.h" #include "dllmain.h" #include "notify.h" #include <netcfgn.h> #include "common.h" //============================================================================// // G L O B A L D E F I N I T I O N S // //============================================================================// //------------------------------------------------------------------------------ // const defines //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // module global vars //------------------------------------------------------------------------------ CNotifyObjModule _AtlModule; BEGIN_OBJECT_MAP(ObjectMap) OBJECT_ENTRY(CLSID_CNotify, CNotify) END_OBJECT_MAP() //------------------------------------------------------------------------------ // global function prototypes //------------------------------------------------------------------------------ //============================================================================// // P R I V A T E D E F I N I T I O N S // //============================================================================// //------------------------------------------------------------------------------ // const defines //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // local types //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // local vars //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // local function prototypes //------------------------------------------------------------------------------ //============================================================================// // P U B L I C F U N C T I O N S // //============================================================================// //------------------------------------------------------------------------------ // DLL Entry Point //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ /** \brief DLL main routine The function implements openPOWERLINK Windows kernel driver initialization callback. OS calls this routine on driver registration. \ingroup module_notify_ndisim */ //------------------------------------------------------------------------------ extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance_p, DWORD reason_p, LPVOID pReserved_p) { TRACE(L"DllMain.\n"); if (reason_p == DLL_PROCESS_ATTACH) { TRACE(L" Reason: Attach.\n"); DisableThreadLibraryCalls(hInstance_p); } else { if (reason_p == DLL_PROCESS_DETACH) { TRACE(L" Reason: Detach.\n"); } } return _AtlModule.DllMain(reason_p, pReserved_p); } //============================================================================// // P R I V A T E F U N C T I O N S // //============================================================================// /// \name Private Functions /// \{ /// \}
42.77037
89
0.38275
openPOWERLINK-Team
331d7bfe9da030abc8be507cfc44b2476b7e031e
26,670
cpp
C++
LambdaEngine/Source/Rendering/ParticleRenderer.cpp
IbexOmega/CrazyCanvas
f60f01aaf9c988e4da8990dc1ef3caac20cecf7e
[ "MIT" ]
18
2020-09-04T08:00:54.000Z
2021-08-29T23:04:45.000Z
LambdaEngine/Source/Rendering/ParticleRenderer.cpp
IbexOmega/LambdaEngine
f60f01aaf9c988e4da8990dc1ef3caac20cecf7e
[ "MIT" ]
32
2020-09-12T19:24:50.000Z
2020-12-11T14:29:44.000Z
LambdaEngine/Source/Rendering/ParticleRenderer.cpp
IbexOmega/LambdaEngine
f60f01aaf9c988e4da8990dc1ef3caac20cecf7e
[ "MIT" ]
2
2020-12-15T15:36:13.000Z
2021-03-27T14:27:02.000Z
#include "Rendering/ParticleRenderer.h" #include "Rendering/Core/API/CommandAllocator.h" #include "Rendering/Core/API/CommandList.h" #include "Rendering/Core/API/DescriptorHeap.h" #include "Rendering/Core/API/DescriptorSet.h" #include "Rendering/Core/API/PipelineState.h" #include "Rendering/Core/API/TextureView.h" #include "Rendering/ParticleManager.h" #include "Rendering/RenderAPI.h" namespace LambdaEngine { ParticleRenderer* ParticleRenderer::s_pInstance = nullptr; ParticleRenderer::ParticleRenderer() { VALIDATE(s_pInstance == nullptr); s_pInstance = this; m_ParticleCount = 0; m_EmitterCount = 1; } ParticleRenderer::~ParticleRenderer() { VALIDATE(s_pInstance != nullptr); s_pInstance = nullptr; if (m_Initilized) { for (uint32 b = 0; b < m_BackBufferCount; b++) { SAFERELEASE(m_ppGraphicCommandLists[b]); SAFERELEASE(m_ppGraphicCommandAllocators[b]); } SAFEDELETE_ARRAY(m_ppGraphicCommandLists); SAFEDELETE_ARRAY(m_ppGraphicCommandAllocators); } } bool LambdaEngine::ParticleRenderer::CreatePipelineLayout() { DescriptorBindingDesc perFrameBufferBindingDesc = {}; perFrameBufferBindingDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_CONSTANT_BUFFER; perFrameBufferBindingDesc.DescriptorCount = 1; perFrameBufferBindingDesc.Binding = 0; perFrameBufferBindingDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_ALL; DescriptorBindingDesc textureBindingDesc0 = {}; textureBindingDesc0.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER; textureBindingDesc0.DescriptorCount = 100; textureBindingDesc0.Binding = 0; textureBindingDesc0.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER; textureBindingDesc0.Flags = FDescriptorSetLayoutBindingFlag::DESCRIPTOR_SET_LAYOUT_BINDING_FLAG_PARTIALLY_BOUND; DescriptorBindingDesc textureBindingDesc1 = {}; textureBindingDesc1.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER; textureBindingDesc1.DescriptorCount = 1; textureBindingDesc1.Binding = 1; textureBindingDesc1.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER; textureBindingDesc1.Flags = FDescriptorSetLayoutBindingFlag::DESCRIPTOR_SET_LAYOUT_BINDING_FLAG_PARTIALLY_BOUND; DescriptorBindingDesc textureBindingDesc2 = {}; textureBindingDesc2.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER; textureBindingDesc2.DescriptorCount = 100; textureBindingDesc2.Binding = 2; textureBindingDesc2.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER; textureBindingDesc2.Flags = FDescriptorSetLayoutBindingFlag::DESCRIPTOR_SET_LAYOUT_BINDING_FLAG_PARTIALLY_BOUND; DescriptorBindingDesc verticesBindingDesc = {}; verticesBindingDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER; verticesBindingDesc.DescriptorCount = 1; verticesBindingDesc.Binding = 0; verticesBindingDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_VERTEX_SHADER; DescriptorBindingDesc instanceBindingDesc = {}; instanceBindingDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER; instanceBindingDesc.DescriptorCount = 1; instanceBindingDesc.Binding = 1; instanceBindingDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_VERTEX_SHADER; DescriptorBindingDesc emitterBindingDesc = {}; emitterBindingDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER; emitterBindingDesc.DescriptorCount = 1; emitterBindingDesc.Binding = 2; emitterBindingDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_VERTEX_SHADER; DescriptorBindingDesc emitterIndexBindingDesc = {}; emitterIndexBindingDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER; emitterIndexBindingDesc.DescriptorCount = 1; emitterIndexBindingDesc.Binding = 3; emitterIndexBindingDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_VERTEX_SHADER; DescriptorBindingDesc lightBufferBindingDesc = {}; lightBufferBindingDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER; lightBufferBindingDesc.DescriptorCount = 1; lightBufferBindingDesc.Binding = 4; lightBufferBindingDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER; DescriptorBindingDesc atlasDataBindingDesc = {}; atlasDataBindingDesc.DescriptorType = EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER; atlasDataBindingDesc.DescriptorCount = 1; atlasDataBindingDesc.Binding = 0; atlasDataBindingDesc.ShaderStageMask = FShaderStageFlag::SHADER_STAGE_FLAG_VERTEX_SHADER; DescriptorSetLayoutDesc descriptorSetLayoutDesc1 = {}; descriptorSetLayoutDesc1.DescriptorBindings = { perFrameBufferBindingDesc }; DescriptorSetLayoutDesc descriptorSetLayoutDesc2 = {}; descriptorSetLayoutDesc2.DescriptorBindings = { textureBindingDesc0, textureBindingDesc1, textureBindingDesc2 }; DescriptorSetLayoutDesc descriptorSetLayoutDesc3 = {}; descriptorSetLayoutDesc3.DescriptorBindings = { verticesBindingDesc, instanceBindingDesc, emitterBindingDesc, emitterIndexBindingDesc, lightBufferBindingDesc }; DescriptorSetLayoutDesc descriptorSetLayoutDesc4 = {}; descriptorSetLayoutDesc4.DescriptorBindings = { atlasDataBindingDesc }; PipelineLayoutDesc pipelineLayoutDesc = { }; pipelineLayoutDesc.DebugName = "Particle Renderer Pipeline Layout"; pipelineLayoutDesc.DescriptorSetLayouts = { descriptorSetLayoutDesc1, descriptorSetLayoutDesc2, descriptorSetLayoutDesc3, descriptorSetLayoutDesc4 }; m_PipelineLayout = RenderAPI::GetDevice()->CreatePipelineLayout(&pipelineLayoutDesc); return m_PipelineLayout != nullptr; } bool LambdaEngine::ParticleRenderer::CreateDescriptorSets() { DescriptorHeapInfo descriptorCountDesc = { }; descriptorCountDesc.SamplerDescriptorCount = 0; descriptorCountDesc.TextureDescriptorCount = 0; descriptorCountDesc.TextureCombinedSamplerDescriptorCount = 1; descriptorCountDesc.ConstantBufferDescriptorCount = 1; descriptorCountDesc.UnorderedAccessBufferDescriptorCount = 5; descriptorCountDesc.UnorderedAccessTextureDescriptorCount = 0; descriptorCountDesc.AccelerationStructureDescriptorCount = 0; DescriptorHeapDesc descriptorHeapDesc = { }; descriptorHeapDesc.DebugName = "Particle Renderer Descriptor Heap"; descriptorHeapDesc.DescriptorSetCount = 64; descriptorHeapDesc.DescriptorCount = descriptorCountDesc; m_DescriptorHeap = RenderAPI::GetDevice()->CreateDescriptorHeap(&descriptorHeapDesc); if (!m_DescriptorHeap) { return false; } m_PerFrameBufferDescriptorSet = RenderAPI::GetDevice()->CreateDescriptorSet("Particle Buffer Descriptor Set 0", m_PipelineLayout.Get(), 0, m_DescriptorHeap.Get()); if (m_PerFrameBufferDescriptorSet == nullptr) { LOG_ERROR("[ParticleRenderer]: Failed to create PerFrameBuffer Descriptor Set 0"); return false; } return true; } bool LambdaEngine::ParticleRenderer::CreateShaders() { bool success = true; if (m_MeshShaders) { m_MeshShaderGUID = ResourceManager::LoadShaderFromFile("/Particles/Particle.mesh", FShaderStageFlag::SHADER_STAGE_FLAG_MESH_SHADER, EShaderLang::SHADER_LANG_GLSL); success &= m_MeshShaderGUID != GUID_NONE; } else { m_VertexShaderGUID = ResourceManager::LoadShaderFromFile("/Particles/Particle.vert", FShaderStageFlag::SHADER_STAGE_FLAG_VERTEX_SHADER, EShaderLang::SHADER_LANG_GLSL); success &= m_VertexShaderGUID != GUID_NONE; } m_PixelShaderGUID = ResourceManager::LoadShaderFromFile("/Particles/Particle.frag", FShaderStageFlag::SHADER_STAGE_FLAG_PIXEL_SHADER, EShaderLang::SHADER_LANG_GLSL); success &= m_PixelShaderGUID != GUID_NONE; return success; } bool LambdaEngine::ParticleRenderer::CreateCommandLists() { m_ppGraphicCommandAllocators = DBG_NEW CommandAllocator * [m_BackBufferCount]; m_ppGraphicCommandLists = DBG_NEW CommandList * [m_BackBufferCount]; for (uint32 b = 0; b < m_BackBufferCount; b++) { m_ppGraphicCommandAllocators[b] = RenderAPI::GetDevice()->CreateCommandAllocator("Particle Renderer Graphics Command Allocator " + std::to_string(b), ECommandQueueType::COMMAND_QUEUE_TYPE_GRAPHICS); if (!m_ppGraphicCommandAllocators[b]) { return false; } CommandListDesc commandListDesc = {}; commandListDesc.DebugName = "Particle Renderer Graphics Command List " + std::to_string(b); commandListDesc.CommandListType = ECommandListType::COMMAND_LIST_TYPE_PRIMARY; commandListDesc.Flags = FCommandListFlag::COMMAND_LIST_FLAG_ONE_TIME_SUBMIT; m_ppGraphicCommandLists[b] = RenderAPI::GetDevice()->CreateCommandList(m_ppGraphicCommandAllocators[b], &commandListDesc); if (!m_ppGraphicCommandLists[b]) { return false; } } return true; } bool LambdaEngine::ParticleRenderer::CreateRenderPass(RenderPassAttachmentDesc* pColorAttachmentDesc, RenderPassAttachmentDesc* pDepthStencilAttachmentDesc) { RenderPassAttachmentDesc colorAttachmentDesc = {}; colorAttachmentDesc.Format = EFormat::FORMAT_R8G8B8A8_UNORM; colorAttachmentDesc.SampleCount = 1; colorAttachmentDesc.LoadOp = ELoadOp::LOAD_OP_CLEAR; colorAttachmentDesc.StoreOp = EStoreOp::STORE_OP_STORE; colorAttachmentDesc.StencilLoadOp = ELoadOp::LOAD_OP_DONT_CARE; colorAttachmentDesc.StencilStoreOp = EStoreOp::STORE_OP_DONT_CARE; colorAttachmentDesc.InitialState = pColorAttachmentDesc->InitialState; colorAttachmentDesc.FinalState = pColorAttachmentDesc->FinalState; RenderPassAttachmentDesc depthAttachmentDesc = {}; depthAttachmentDesc.Format = EFormat::FORMAT_D24_UNORM_S8_UINT; depthAttachmentDesc.SampleCount = 1; depthAttachmentDesc.LoadOp = ELoadOp::LOAD_OP_LOAD; depthAttachmentDesc.StoreOp = EStoreOp::STORE_OP_STORE; depthAttachmentDesc.StencilLoadOp = ELoadOp::LOAD_OP_DONT_CARE; depthAttachmentDesc.StencilStoreOp = EStoreOp::STORE_OP_DONT_CARE; depthAttachmentDesc.InitialState = pDepthStencilAttachmentDesc->InitialState; depthAttachmentDesc.FinalState = pDepthStencilAttachmentDesc->FinalState; RenderPassSubpassDesc subpassDesc = {}; subpassDesc.RenderTargetStates = { ETextureState::TEXTURE_STATE_RENDER_TARGET }; subpassDesc.DepthStencilAttachmentState = ETextureState::TEXTURE_STATE_DEPTH_STENCIL_ATTACHMENT; RenderPassSubpassDependencyDesc subpassDependencyDesc = {}; subpassDependencyDesc.SrcSubpass = EXTERNAL_SUBPASS; subpassDependencyDesc.DstSubpass = 0; subpassDependencyDesc.SrcAccessMask = 0; subpassDependencyDesc.DstAccessMask = FMemoryAccessFlag::MEMORY_ACCESS_FLAG_MEMORY_READ | FMemoryAccessFlag::MEMORY_ACCESS_FLAG_MEMORY_WRITE; subpassDependencyDesc.SrcStageMask = FPipelineStageFlag::PIPELINE_STAGE_FLAG_RENDER_TARGET_OUTPUT; subpassDependencyDesc.DstStageMask = FPipelineStageFlag::PIPELINE_STAGE_FLAG_RENDER_TARGET_OUTPUT; RenderPassDesc renderPassDesc = {}; renderPassDesc.DebugName = "Particle Renderer Render Pass"; renderPassDesc.Attachments = { colorAttachmentDesc, depthAttachmentDesc }; renderPassDesc.Subpasses = { subpassDesc }; renderPassDesc.SubpassDependencies = { subpassDependencyDesc }; m_RenderPass = RenderAPI::GetDevice()->CreateRenderPass(&renderPassDesc); return true; } bool LambdaEngine::ParticleRenderer::CreatePipelineState() { ManagedGraphicsPipelineStateDesc pipelineStateDesc = {}; pipelineStateDesc.DebugName = "Particle Pipeline State"; pipelineStateDesc.RenderPass = m_RenderPass; pipelineStateDesc.PipelineLayout = m_PipelineLayout; pipelineStateDesc.InputAssembly.PrimitiveTopology = EPrimitiveTopology::PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; pipelineStateDesc.RasterizerState.LineWidth = 1.f; pipelineStateDesc.RasterizerState.PolygonMode = EPolygonMode::POLYGON_MODE_FILL; pipelineStateDesc.RasterizerState.CullMode = ECullMode::CULL_MODE_NONE; pipelineStateDesc.DepthStencilState = {}; pipelineStateDesc.DepthStencilState.DepthTestEnable = true; pipelineStateDesc.DepthStencilState.DepthWriteEnable = true; pipelineStateDesc.BlendState.BlendAttachmentStates = { { .BlendOp = EBlendOp::BLEND_OP_ADD, .SrcBlend = EBlendFactor::BLEND_FACTOR_SRC_ALPHA, .DstBlend = EBlendFactor::BLEND_FACTOR_INV_SRC_ALPHA, .BlendOpAlpha = EBlendOp::BLEND_OP_ADD, .SrcBlendAlpha = EBlendFactor::BLEND_FACTOR_SRC_ALPHA, .DstBlendAlpha = EBlendFactor::BLEND_FACTOR_INV_SRC_ALPHA, .RenderTargetComponentMask = COLOR_COMPONENT_FLAG_R | COLOR_COMPONENT_FLAG_G | COLOR_COMPONENT_FLAG_B | COLOR_COMPONENT_FLAG_A, .BlendEnabled = true } }; pipelineStateDesc.VertexShader.ShaderGUID = m_VertexShaderGUID; pipelineStateDesc.PixelShader.ShaderGUID = m_PixelShaderGUID; m_PipelineStateID = PipelineStateManager::CreateGraphicsPipelineState(&pipelineStateDesc); return true; } bool LambdaEngine::ParticleRenderer::Init() { m_BackBufferCount = BACK_BUFFER_COUNT; m_ParticleCount = 0; if (!CreatePipelineLayout()) { LOG_ERROR("[ParticleRenderer]: Failed to create PipelineLayout"); return false; } if (!CreateDescriptorSets()) { LOG_ERROR("[ParticleRenderer]: Failed to create DescriptorSet"); return false; } if (!CreateShaders()) { LOG_ERROR("[ParticleRenderer]: Failed to create Shaders"); return false; } return true; } bool LambdaEngine::ParticleRenderer::RenderGraphInit(const CustomRendererRenderGraphInitDesc* pPreInitDesc) { VALIDATE(pPreInitDesc); VALIDATE(pPreInitDesc->pColorAttachmentDesc != nullptr); VALIDATE(pPreInitDesc->pDepthStencilAttachmentDesc != nullptr); if (!m_Initilized) { if (!CreateCommandLists()) { LOG_ERROR("[ParticleRenderer]: Failed to create render command lists"); return false; } if (!CreateRenderPass(pPreInitDesc->pColorAttachmentDesc, pPreInitDesc->pDepthStencilAttachmentDesc)) { LOG_ERROR("[ParticleRenderer]: Failed to create RenderPass"); return false; } if (!CreatePipelineState()) { LOG_ERROR("[ParticleRenderer]: Failed to create PipelineState"); return false; } // Create a initial particle atlas descriptor set and set the content to a default texture. m_AtlasTexturesDescriptorSet = m_DescriptorCache.GetDescriptorSet("Particle Atlas texture Descriptor Set", m_PipelineLayout.Get(), 1, m_DescriptorHeap.Get()); if (m_AtlasTexturesDescriptorSet != nullptr) { TextureView* textureView = ResourceManager::GetTextureView(GUID_TEXTURE_DEFAULT_COLOR_MAP); Sampler* sampler = Sampler::GetLinearSampler(); m_AtlasTexturesDescriptorSet->WriteTextureDescriptors( &textureView, &sampler, ETextureState::TEXTURE_STATE_SHADER_READ_ONLY, 0, 1, EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER, true ); } else { LOG_ERROR("[ParticleRenderer]: Failed to update DescriptorSet[%d]", 0); } m_Initilized = true; } return true; } void ParticleRenderer::Update(Timestamp delta, uint32 modFrameIndex, uint32 backBufferIndex) { UNREFERENCED_VARIABLE(delta); UNREFERENCED_VARIABLE(backBufferIndex); m_DescriptorCache.HandleUnavailableDescriptors(modFrameIndex); } void ParticleRenderer::UpdateTextureResource(const String& resourceName, const TextureView* const* ppPerImageTextureViews, const TextureView* const* ppPerSubImageTextureViews, const Sampler* const* ppPerImageSamplers, uint32 imageCount, uint32 subImageCount, bool backBufferBound) { UNREFERENCED_VARIABLE(ppPerSubImageTextureViews); UNREFERENCED_VARIABLE(subImageCount); UNREFERENCED_VARIABLE(backBufferBound); if (resourceName == "PARTICLE_IMAGE") { if (imageCount == 1) { m_RenderTarget = MakeSharedRef(ppPerImageTextureViews[0]); } else { LOG_ERROR("[ParticleRenderer]: Failed to update Render Target Resource"); } } else if (resourceName == SCENE_PARTICLE_ATLAS_IMAGES) { constexpr uint32 setIndex = 1U; constexpr uint32 setBinding = 0U; m_AtlasTexturesDescriptorSet = m_DescriptorCache.GetDescriptorSet("Particle Atlas texture Descriptor Set", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get()); if (m_AtlasTexturesDescriptorSet != nullptr) { m_AtlasTexturesDescriptorSet->WriteTextureDescriptors( ppPerImageTextureViews, ppPerImageSamplers, ETextureState::TEXTURE_STATE_SHADER_READ_ONLY, setBinding, imageCount, EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER, true ); } else { LOG_ERROR("[ParticleRenderer]: Failed to update m_AtlasTexturesDescriptorSet"); } } else if (resourceName == "DIRL_SHADOWMAP") { constexpr uint32 setIndex = 1U; constexpr uint32 setBinding = 1U; m_AtlasTexturesDescriptorSet = m_DescriptorCache.GetDescriptorSet("Particle Point Lights texture Descriptor Set", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get()); if (m_AtlasTexturesDescriptorSet != nullptr) { m_AtlasTexturesDescriptorSet->WriteTextureDescriptors( ppPerImageTextureViews, ppPerImageSamplers, ETextureState::TEXTURE_STATE_SHADER_READ_ONLY, setBinding, imageCount, EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER, false ); } else { LOG_ERROR("[ParticleRenderer]: Failed to update m_AtlasTexturesDescriptorSet"); } } else if (resourceName == SCENE_POINT_SHADOWMAPS) { constexpr uint32 setIndex = 1U; constexpr uint32 setBinding = 2U; m_AtlasTexturesDescriptorSet = m_DescriptorCache.GetDescriptorSet("Particle Point Lights texture Descriptor Set", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get()); if (m_AtlasTexturesDescriptorSet != nullptr) { //Sampler* pSampler = Sampler::GetLinearSampler(); m_AtlasTexturesDescriptorSet->WriteTextureDescriptors( ppPerImageTextureViews, ppPerImageSamplers, ETextureState::TEXTURE_STATE_SHADER_READ_ONLY, setBinding, imageCount, EDescriptorType::DESCRIPTOR_TYPE_SHADER_RESOURCE_COMBINED_SAMPLER, false ); } else { LOG_ERROR("[ParticleRenderer]: Failed to update m_AtlasTexturesDescriptorSet"); } } else if (resourceName == "G_BUFFER_DEPTH_STENCIL") { if (imageCount == 1) { m_DepthStencil = MakeSharedRef(ppPerImageTextureViews[0]); } else { LOG_ERROR("[ParticleRenderer]: Failed to update Depth Stencil Resource"); } } } void ParticleRenderer::UpdateBufferResource(const String& resourceName, const Buffer* const* ppBuffers, uint64* pOffsets, uint64* pSizesInBytes, uint32 count, bool backBufferBound) { UNREFERENCED_VARIABLE(resourceName); UNREFERENCED_VARIABLE(ppBuffers); UNREFERENCED_VARIABLE(pOffsets); UNREFERENCED_VARIABLE(pSizesInBytes); UNREFERENCED_VARIABLE(count); UNREFERENCED_VARIABLE(backBufferBound); if (resourceName == PER_FRAME_BUFFER) { constexpr uint32 setIndex = 0U; constexpr uint32 setBinding = 0U; m_PerFrameBufferDescriptorSet = m_DescriptorCache.GetDescriptorSet("Per Frame Buffer Descriptor Set 0 Binding 0", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get()); if (m_PerFrameBufferDescriptorSet != nullptr) { m_PerFrameBufferDescriptorSet->WriteBufferDescriptors( ppBuffers, pOffsets, pSizesInBytes, setBinding, count, EDescriptorType::DESCRIPTOR_TYPE_CONSTANT_BUFFER ); } else { LOG_ERROR("[ParticleRenderer]: Failed to update m_PerFrameBufferDescriptorSet"); } } if (resourceName == SCENE_PARTICLE_VERTEX_BUFFER) { if (count == 1) { constexpr uint32 setIndex = 2U; constexpr uint32 setBinding = 0U; m_VertexInstanceDescriptorSet = m_DescriptorCache.GetDescriptorSet("Vertex Instance Buffer Descriptor Set 2 Binding 0", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get()); if (m_VertexInstanceDescriptorSet != nullptr) { m_VertexInstanceDescriptorSet->WriteBufferDescriptors(ppBuffers, pOffsets, pSizesInBytes, setBinding, 1, EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER); } else { LOG_ERROR("[ParticleRenderer]: Failed to update VertexInstanceDescriptorSet"); } } } else if (resourceName == SCENE_PARTICLE_INSTANCE_BUFFER) { if (count == 1) { constexpr uint32 setIndex = 2U; constexpr uint32 setBinding = 1U; m_VertexInstanceDescriptorSet = m_DescriptorCache.GetDescriptorSet("Particle Instance Buffer Descriptor Set 2 Binding 1", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get()); if (m_VertexInstanceDescriptorSet != nullptr) { m_VertexInstanceDescriptorSet->WriteBufferDescriptors(ppBuffers, pOffsets, pSizesInBytes, setBinding, 1, EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER); } else { LOG_ERROR("[ParticleRenderer]: Failed to update VertexInstanceDescriptorSet"); } } } else if (resourceName == SCENE_EMITTER_INSTANCE_BUFFER) { constexpr uint32 setIndex = 2U; constexpr uint32 setBinding = 2U; m_VertexInstanceDescriptorSet = m_DescriptorCache.GetDescriptorSet("Emitter Instance Buffer Descriptor Set 2 Binding 2", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get()); if (m_VertexInstanceDescriptorSet != nullptr) { m_VertexInstanceDescriptorSet->WriteBufferDescriptors( ppBuffers, pOffsets, pSizesInBytes, setBinding, count, EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER ); } else { LOG_ERROR("[ParticleUpdater]: Failed to update DescriptorSet[%d]", 0); } } else if (resourceName == SCENE_EMITTER_INDEX_BUFFER) { constexpr uint32 setIndex = 2U; constexpr uint32 setBinding = 3U; m_VertexInstanceDescriptorSet = m_DescriptorCache.GetDescriptorSet("Emitter Index Buffer Descriptor Set 2 Binding 3", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get()); if (m_VertexInstanceDescriptorSet != nullptr) { m_VertexInstanceDescriptorSet->WriteBufferDescriptors( ppBuffers, pOffsets, pSizesInBytes, setBinding, count, EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER ); } else { LOG_ERROR("[ParticleUpdater]: Failed to update DescriptorSet[%d]", 0); } } else if (resourceName == SCENE_LIGHTS_BUFFER) { constexpr uint32 setIndex = 2U; constexpr uint32 setBinding = 4U; m_VertexInstanceDescriptorSet = m_DescriptorCache.GetDescriptorSet("Emitter Index Buffer Descriptor Set 2 Binding 4", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get()); if (m_VertexInstanceDescriptorSet != nullptr) { m_VertexInstanceDescriptorSet->WriteBufferDescriptors( ppBuffers, pOffsets, pSizesInBytes, setBinding, count, EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER ); } else { LOG_ERROR("[ParticleUpdater]: Failed to update DescriptorSet[%d]", 0); } } if (resourceName == SCENE_PARTICLE_INDEX_BUFFER) { if (count == 1) { m_pIndexBuffer = ppBuffers[0]; } } if (resourceName == SCENE_PARTICLE_INDIRECT_BUFFER) { if (count == 1) { m_pIndirectBuffer = ppBuffers[0]; } } if (resourceName == SCENE_PARTICLE_ATLAS_INFO_BUFFER) { if (count == 1) { constexpr uint32 setIndex = 3U; constexpr uint32 setBinding = 0U; m_AtlasInfoBufferDescriptorSet = m_DescriptorCache.GetDescriptorSet("Atlas Info Buffer Descriptor Set 3 Binding 0", m_PipelineLayout.Get(), setIndex, m_DescriptorHeap.Get()); if (m_AtlasInfoBufferDescriptorSet != nullptr) { m_AtlasInfoBufferDescriptorSet->WriteBufferDescriptors(ppBuffers, pOffsets, pSizesInBytes, setBinding, 1, EDescriptorType::DESCRIPTOR_TYPE_UNORDERED_ACCESS_BUFFER); } else { LOG_ERROR("[ParticleRenderer]: Failed to update m_AtlasInfoBufferDescriptorSet"); } } } } void ParticleRenderer::Render(uint32 modFrameIndex, uint32 backBufferIndex, CommandList** ppFirstExecutionStage, CommandList** ppSecondaryExecutionStage, bool Sleeping) { UNREFERENCED_VARIABLE(modFrameIndex); UNREFERENCED_VARIABLE(backBufferIndex); UNREFERENCED_VARIABLE(ppFirstExecutionStage); UNREFERENCED_VARIABLE(ppSecondaryExecutionStage); CommandList* pCommandList = m_ppGraphicCommandLists[modFrameIndex]; m_ppGraphicCommandAllocators[modFrameIndex]->Reset(); pCommandList->Begin(nullptr); pCommandList->BindGraphicsPipeline(PipelineStateManager::GetPipelineState(m_PipelineStateID)); TSharedRef<const TextureView> renderTarget = m_RenderTarget; uint32 width = renderTarget->GetDesc().pTexture->GetDesc().Width; uint32 height = renderTarget->GetDesc().pTexture->GetDesc().Height; Viewport viewport = {}; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; viewport.Width = (float32)width; viewport.Height = -(float32)height; viewport.x = 0.0f; viewport.y = (float32)height; pCommandList->SetViewports(&viewport, 0, 1); ScissorRect scissorRect = {}; scissorRect.Width = width; scissorRect.Height = height; pCommandList->SetScissorRects(&scissorRect, 0, 1); ClearColorDesc clearColors[1] = {}; clearColors[0].Color[0] = 0.f; clearColors[0].Color[1] = 0.f; clearColors[0].Color[2] = 0.f; clearColors[0].Color[3] = 0.f; pCommandList->BindDescriptorSetGraphics(m_PerFrameBufferDescriptorSet.Get(), m_PipelineLayout.Get(), 0); pCommandList->BindDescriptorSetGraphics(m_AtlasTexturesDescriptorSet.Get(), m_PipelineLayout.Get(), 1); pCommandList->BindDescriptorSetGraphics(m_VertexInstanceDescriptorSet.Get(), m_PipelineLayout.Get(), 2); pCommandList->BindDescriptorSetGraphics(m_AtlasInfoBufferDescriptorSet.Get(), m_PipelineLayout.Get(), 3); pCommandList->BindIndexBuffer(m_pIndexBuffer, 0, EIndexType::INDEX_TYPE_UINT32); BeginRenderPassDesc beginRenderPassDesc = {}; beginRenderPassDesc.pRenderPass = m_RenderPass.Get(); beginRenderPassDesc.ppRenderTargets = renderTarget.GetAddressOf(); beginRenderPassDesc.RenderTargetCount = 1; beginRenderPassDesc.pDepthStencil = m_DepthStencil.Get(); beginRenderPassDesc.Width = width; beginRenderPassDesc.Height = height; beginRenderPassDesc.Flags = FRenderPassBeginFlag::RENDER_PASS_BEGIN_FLAG_INLINE; beginRenderPassDesc.pClearColors = clearColors; beginRenderPassDesc.ClearColorCount = 1; beginRenderPassDesc.Offset.x = 0; beginRenderPassDesc.Offset.y = 0; pCommandList->BeginRenderPass(&beginRenderPassDesc); if (!Sleeping) { if (m_EmitterCount > 0) { pCommandList->DrawIndexedIndirect(m_pIndirectBuffer, 0, m_EmitterCount, sizeof(IndirectData)); } } pCommandList->EndRenderPass(); pCommandList->End(); (*ppFirstExecutionStage) = pCommandList; } }
36.534247
281
0.78069
IbexOmega
3323a3e19530d845d8d07fe37aae1399682c80cf
8,585
hpp
C++
ivarp/include/ivarp/number/exact_less_than.hpp
phillip-keldenich/squares-in-disk
501ebeb00b909b9264a9611fd63e082026cdd262
[ "MIT" ]
null
null
null
ivarp/include/ivarp/number/exact_less_than.hpp
phillip-keldenich/squares-in-disk
501ebeb00b909b9264a9611fd63e082026cdd262
[ "MIT" ]
null
null
null
ivarp/include/ivarp/number/exact_less_than.hpp
phillip-keldenich/squares-in-disk
501ebeb00b909b9264a9611fd63e082026cdd262
[ "MIT" ]
null
null
null
// The code is open source under the MIT license. // Copyright 2019-2020, Phillip Keldenich, TU Braunschweig, Algorithms Group // https://ibr.cs.tu-bs.de/alg // // 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. // // Created by Phillip Keldenich on 28.10.19. // #pragma once /** * @file exact_less_than.hpp * Implementation of \f$a < b\f$ or \f$a > b\f$ * that is guaranteed to return the correct result, * for the following situations with builtin number types: * \f$a\f$ integral and \f$b\f$ floating-point (or vice-versa), * \f$a\f$ and \f$b\f$ floating-point. * Also works if any involved type is rational. * * The problem with the builtin operators is that the comparison is * implemented as if by casting the integer to the floating-point type * before the conversion, which is not exact for large integers and * can thus lead to incorrect results. */ namespace ivarp { namespace impl { template<bool GreaterThan, typename IntType> static IVARP_HD inline bool exact_comp_pos(IntType a, double b) { constexpr int int_bits = std::numeric_limits<IntType>::digits; const double max_exact = IVARP_NOCUDA_USE_STD ldexp(1., std::numeric_limits<double>::digits); const double larger_than_max_int = IVARP_NOCUDA_USE_STD ldexp(1., int_bits); if(b <= max_exact) { return GreaterThan; } // b is an integral number > max_exact if(b >= larger_than_max_int) { return !GreaterThan; } // we can exactly convert b to our integer type auto ib = static_cast<IntType>(b); return GreaterThan ? a > ib : a < ib; } template<bool GreaterThan, typename IntType> static IVARP_HD inline bool exact_comp_neg(IntType a, double b) { // a is below -max_exact constexpr int int_bits = std::numeric_limits<IntType>::digits; const double max_exact = IVARP_NOCUDA_USE_STD ldexp(1., std::numeric_limits<double>::digits); const double min_int = IVARP_NOCUDA_USE_STD ldexp(-1., int_bits); if(b >= -max_exact) { return !GreaterThan; } // b is integral. if(b < min_int) { // b is below any integer values return GreaterThan; } // b is integral and in range. auto ib = static_cast<IntType>(b); return GreaterThan ? a > ib : a < ib; } template<bool GreaterThan, typename UIntType> static inline IVARP_HD std::enable_if_t<std::is_unsigned<UIntType>::value, bool> exact_comp(UIntType a, double b) noexcept { constexpr UIntType max_exact = UIntType(1u) << unsigned(std::numeric_limits<double>::digits); // an overflowing int should be rare, therefore a jump is probably good to predict if(BOOST_LIKELY(a <= max_exact)) { auto da = static_cast<double>(a); return GreaterThan ? da > b : da < b; } return exact_comp_pos<GreaterThan>(a, b); } template<bool GreaterThan, typename IntType> static inline IVARP_HD std::enable_if_t<std::is_signed<IntType>::value, bool> exact_comp(IntType a, double b) noexcept { constexpr IntType max_exact = IntType(1) << unsigned(std::numeric_limits<double>::digits); IntType absa = a < 0 ? -a : a; // the only case where this returns negative is exactly representable // an overflowing int should be rare if(BOOST_LIKELY(absa <= max_exact)) { auto da = static_cast<double>(a); return GreaterThan ? da > b : da < b; } if(a < 0) { return exact_comp_neg<GreaterThan>(a, b); } else { return exact_comp_pos<GreaterThan>(a, b); } } /// Handling the case where the int does not necessarily fit into a double's mantissa. template<typename Int, typename Float, bool GreaterThan, bool FitsFloat = (std::numeric_limits<Int>::digits <= std::numeric_limits<Float>::digits), bool FitsDouble = (std::numeric_limits<Int>::digits <= std::numeric_limits<double>::digits)> struct ExactCompIntFloat { IVARP_HD static bool compare(Int i, Float f) { return exact_comp<GreaterThan>(i, f); } }; /// Handling the case where the int fits into the float's mantissa. template<typename Int, typename Float, bool GreaterThan, bool FD> struct ExactCompIntFloat<Int,Float,GreaterThan,true,FD> { IVARP_HD static bool compare(Int i, Float f) noexcept { auto floati = static_cast<Float>(i); return GreaterThan ? floati > f : floati < f; } }; /// Handling the case where the int fits into a double's mantissa. template<typename Int, typename Float, bool GreaterThan> struct ExactCompIntFloat<Int,Float,GreaterThan,false,true> { IVARP_HD static bool compare(Int i, Float f) noexcept { auto doublei = static_cast<double>(i); double doublef(f); return GreaterThan ? doublei > doublef : doublei < doublef; } }; } /// Handling the int/float case. template<typename T1, typename T2> static inline IVARP_HD std::enable_if_t<std::is_integral<BareType<T1>>::value && std::is_floating_point<BareType<T2>>::value, bool> exact_less_than(T1 a, T2 b) noexcept { return impl::ExactCompIntFloat<T1, T2, false>::compare(a,b); } /// Handling the float/int case. template<typename T1, typename T2> static inline IVARP_HD std::enable_if_t<std::is_integral<BareType<T2>>::value && std::is_floating_point<BareType<T1>>::value, bool> exact_less_than(T1 a, T2 b) noexcept { return impl::ExactCompIntFloat<T2, T1, true>::compare(b, a); } /// Easy case: both are already floating point. template<typename T1, typename T2> static inline IVARP_HD std::enable_if_t<std::is_floating_point<BareType<T1>>::value && std::is_floating_point<BareType<T2>>::value, bool> exact_less_than(T1 a, T2 b) noexcept { return a < b; } /// Handle the case where at least one is rational and the other is not floating-point. template<typename T1, typename T2> static inline IVARP_H std::enable_if_t<(IsRational<T1>::value && !std::is_floating_point<T2>::value) || (!std::is_floating_point<T1>::value && IsRational<T2>::value), bool> exact_less_than(const T1& a, const T2& b) { return a < b; } /// Handle the case where one argument is rational and one is floating-point. template<typename T1, typename T2> static inline IVARP_H std::enable_if_t<IsRational<T1>::value && std::is_floating_point<T2>::value, bool> exact_less_than(const T1& a, T2 b) { if(b == std::numeric_limits<T2>::infinity()) { return true; } else if(b == -std::numeric_limits<T2>::infinity()) { return false; } else { return a < b; } } template<typename T1, typename T2> static inline IVARP_H std::enable_if_t<IsRational<T2>::value && std::is_floating_point<T1>::value, bool> exact_less_than(T1 a, const T2& b) { if(a == std::numeric_limits<T1>::infinity()) { return false; } else if(a == -std::numeric_limits<T1>::infinity()) { return true; } else { return a < b; } } }
39.74537
158
0.639371
phillip-keldenich
332481d7162d8778bee2027dc26d914d313eb59e
1,070
cpp
C++
src/medGui/database/medDatabaseNavigatorItemOverlay.cpp
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
src/medGui/database/medDatabaseNavigatorItemOverlay.cpp
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
src/medGui/database/medDatabaseNavigatorItemOverlay.cpp
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
/*========================================================================= medInria Copyright (c) INRIA 2013. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include <medDatabaseNavigatorItemOverlay.h> // ///////////////////////////////////////////////////////////////// // medDatabaseNavigatorItemOverlay // ///////////////////////////////////////////////////////////////// class medDatabaseNavigatorItemOverlayPrivate { }; medDatabaseNavigatorItemOverlay::medDatabaseNavigatorItemOverlay(QGraphicsItem *parent) : QObject(), QGraphicsPixmapItem(parent), d(new medDatabaseNavigatorItemOverlayPrivate) { } medDatabaseNavigatorItemOverlay::~medDatabaseNavigatorItemOverlay(void) { delete d; d = NULL; } void medDatabaseNavigatorItemOverlay::mousePressEvent(QGraphicsSceneMouseEvent *event) { emit clicked(); }
26.75
91
0.581308
ocommowi
33250e1fa4466a4185959a8a159ef4ad0e6639f3
1,330
cpp
C++
UVA/11753.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
3
2020-11-01T06:31:30.000Z
2022-02-21T20:37:51.000Z
UVA/11753.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
null
null
null
UVA/11753.cpp
MaGnsio/CP-Problems
a7f518a20ba470f554b6d54a414b84043bf209c5
[ "Unlicense" ]
1
2021-05-05T18:56:31.000Z
2021-05-05T18:56:31.000Z
/** * author: MaGnsi0 * created: 20/09/2021 23:24:38 **/ #include <bits/stdc++.h> using namespace std; int n, k; vector<int> v; int dp(int i, int j, int curk) { if (curk > k || i >= j) { return curk; } if (v[i] == v[j]) { return dp(i + 1, j - 1, curk); } else { return min(dp(i + 1, j, curk + 1), dp(i, j - 1, curk + 1)); } } int main() { ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0); int T; cin >> T; for (int t = 1; t <= T; ++t) { cin >> n >> k; v = vector<int>(n); for (int i = 0; i < n; ++i) { cin >> v[i]; } int res = dp(0, n - 1, 0); cout << "Case " << t << ": "; if (res == 0) { cout << "Too easy\n"; } else if (res <= k) { cout << res << "\n"; } else { cout << "Too difficult\n"; } } } /* EDITORIAL :- * * as (1 <= n <= 10000) we can't do normal O(n^2) longest palindromic subsequence algorithm. * so we have to take advantage of small k (1 <= k <= 20) * if we go normal recursion without memoization with state (i, j, curk) * : i(starting index), j(ending index), (curk)number of insertions made so far. * we can't go no more than max(n, 2^k) different states wich is an acceptable complexity. */
25.576923
92
0.478947
MaGnsio
332aa0fef8ee76ee418f2033edb2ff24f5dfbd71
2,497
cpp
C++
processor/src/ComponentTreeNode.cpp
mballance-sf/open-ps
a5ed44ce30bfe59462801ca7de4361d16950bcd2
[ "Apache-2.0" ]
null
null
null
processor/src/ComponentTreeNode.cpp
mballance-sf/open-ps
a5ed44ce30bfe59462801ca7de4361d16950bcd2
[ "Apache-2.0" ]
null
null
null
processor/src/ComponentTreeNode.cpp
mballance-sf/open-ps
a5ed44ce30bfe59462801ca7de4361d16950bcd2
[ "Apache-2.0" ]
null
null
null
/* * ComponentTreeNode.cpp * * 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. * * Created on: Jan 31, 2018 * Author: ballance */ #include "ComponentTreeNode.h" namespace qpssc { ComponentTreeNode::ComponentTreeNode( ComponentTreeNode *parent, const std::string &name, IComponent *comp, uint32_t id) { m_parent = parent; m_name = name; m_component = comp; m_id = id; } ComponentTreeNode::~ComponentTreeNode() { // TODO Auto-generated destructor stub } std::string ComponentTreeNode::toString() { std::string ret; toString(ret, ""); return ret; } void ComponentTreeNode::toString( std::string &str, const std::string &ind) { str.append(ind + m_name + " : " + m_component->getName() + "\n"); for (std::vector<ComponentTreeNode *>::const_iterator it=m_children.begin(); it!=m_children.end(); it++) { (*it)->toString(str, (ind + " ")); } } ComponentTreeNode *ComponentTreeNode::build( IModel *model, IComponent *comp) { uint32_t id = 0; return build(model, 0, comp->getName(), comp, id); } ComponentTreeNode *ComponentTreeNode::build( IModel *model, ComponentTreeNode *parent, const std::string &name, IComponent *comp, uint32_t &id) { ComponentTreeNode *node = new ComponentTreeNode( parent, name, comp, id++); if (parent) { parent->m_children.push_back(node); } // TODO: find binds and assess their impact // TODO: iterate through actions at this level // Traverse sub-component instances for (std::vector<IBaseItem *>::const_iterator it=comp->getItems().begin(); it != comp->getItems().end(); it++) { if ((*it)->getType() == IBaseItem::TypeField) { IField *field = dynamic_cast<IField *>(*it); if (dynamic_cast<IComponent *>(field->getDataType())) { // This is a component-type field build(model, node, field->getName(), dynamic_cast<IComponent *>(field->getDataType()), id); } } } return node; } } /* namespace qpssc */
23.780952
77
0.670404
mballance-sf
332b05dab42636fbb8920123ff41da8ce1582eff
23,059
cc
C++
tests/bench/fdb_bench.cc
hundredbag/forestdb-io_uring
bb2f49ec889d3fa2db7b3d7057e20dcb6fd4d822
[ "Apache-2.0" ]
6
2020-11-12T07:18:46.000Z
2020-11-17T01:46:30.000Z
tests/bench/fdb_bench.cc
rundun159/forestdb-io_uring
bb2f49ec889d3fa2db7b3d7057e20dcb6fd4d822
[ "Apache-2.0" ]
null
null
null
tests/bench/fdb_bench.cc
rundun159/forestdb-io_uring
bb2f49ec889d3fa2db7b3d7057e20dcb6fd4d822
[ "Apache-2.0" ]
3
2020-11-12T07:18:50.000Z
2020-11-16T05:03:04.000Z
#include <stdio.h> #include "config.h" #include "timing.h" #include "libforestdb/forestdb.h" #include "test.h" struct thread_context { fdb_kvs_handle *handle; ts_nsec latency1; ts_nsec latency2; float avg_latency1; float avg_latency2; }; void print_stat(const char *name, float latency){ printf("%-15s %f\n", name, latency); } void print_stats(fdb_file_handle *h){ TEST_INIT(); int i; fdb_status status; fdb_latency_stat stat; const char *name; for (i=0;i<FDB_LATENCY_NUM_STATS;i++){ memset(&stat, 0, sizeof(fdb_latency_stat)); status = fdb_get_latency_stats(h, &stat, i); TEST_CHK(status == FDB_RESULT_SUCCESS); if(stat.lat_count==0){ continue; } name = fdb_latency_stat_name(i); printf("%-15s %u\n", name, stat.lat_avg); } } void print_stats_aggregate(fdb_file_handle **dbfiles, int nfiles){ TEST_INIT(); int i,j; uint32_t cnt, sum, avg = 0; fdb_status status; fdb_latency_stat stat; const char *name; for (i=0;i<FDB_LATENCY_NUM_STATS;i++){ cnt = 0; sum = 0; // avg of each stat across dbfiles for(j=0;j<nfiles;j++){ memset(&stat, 0, sizeof(fdb_latency_stat)); status = fdb_get_latency_stats(dbfiles[j], &stat, i); TEST_CHK(status == FDB_RESULT_SUCCESS); cnt += stat.lat_count; sum += stat.lat_avg; } if(cnt > 0){ name = fdb_latency_stat_name(i); avg = sum/nfiles; printf("%-15s %u\n", name, avg); } } } void str_gen(char *s, const int len) { int i = 0; static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; size_t n_ch = strlen(alphanum); if (len < 1){ return; } // return same ordering of chars while(i<len){ s[i] = alphanum[i%n_ch]; i++; } s[len-1] = '\0'; } void swap(char *x, char *y) { char temp; temp = *x; *x = *y; *y = temp; } void permute(fdb_kvs_handle *kv, char *a, int l, int r) { int i; char keybuf[256], metabuf[256], bodybuf[512]; fdb_doc *doc = NULL; str_gen(bodybuf, 64); if (l == r) { sprintf(keybuf, a, l); sprintf(metabuf, "meta%d", r); fdb_doc_create(&doc, (void*)keybuf, strlen(keybuf), (void*)metabuf, strlen(metabuf), (void*)bodybuf, strlen(bodybuf)); fdb_set(kv, doc); fdb_doc_free(doc); } else { for (i = l; i <= r; i++) { swap((a+l), (a+i)); permute(kv, a, l+1, r); swap((a+l), (a+i)); //backtrack } } } void setup_db(fdb_file_handle **fhandle, fdb_kvs_handle **kv){ int r; char cmd[64]; fdb_status status; fdb_config config; fdb_kvs_config kvs_config; kvs_config = fdb_get_default_kvs_config(); config = fdb_get_default_config(); config.durability_opt = FDB_DRB_ASYNC; config.compaction_mode = FDB_COMPACTION_MANUAL; // cleanup first sprintf(cmd, SHELL_DEL" %s*>errorlog.txt", BENCHDB_NAME); r = system(cmd); (void)r; status = fdb_open(fhandle, BENCHDB_NAME, &config); assert(status == FDB_RESULT_SUCCESS); status = fdb_kvs_open(*fhandle, kv, BENCHKV_NAME , &kvs_config); assert(status == FDB_RESULT_SUCCESS); } void sequential_set(bool walflush){ TEST_INIT(); int i, n = NDOCS; ts_nsec latency, latency_tot = 0, latency_tot2 = 0; float latency_avg = 0; char keybuf[256], metabuf[256], bodybuf[512]; fdb_file_handle *fhandle; fdb_status status; fdb_kvs_handle *kv, *snap_kv; fdb_doc *doc = NULL; fdb_iterator *iterator; printf("\nBENCH-SEQUENTIAL_SET-WALFLUSH-%d \n", walflush); // setup setup_db(&fhandle, &kv); str_gen(bodybuf, 64); // create for (i=0;i<n;++i){ sprintf(keybuf, "key%d", i); sprintf(metabuf, "meta%d", i); fdb_doc_create(&doc, (void*)keybuf, strlen(keybuf), (void*)metabuf, strlen(metabuf), (void*)bodybuf, strlen(bodybuf)); status = fdb_set(kv, doc); TEST_CHK(status == FDB_RESULT_SUCCESS); fdb_doc_free(doc); doc = NULL; } // commit status = fdb_commit(fhandle, FDB_COMMIT_MANUAL_WAL_FLUSH); TEST_CHK(status == FDB_RESULT_SUCCESS); // create an iterator for full range latency = timed_fdb_iterator_init(kv, &iterator); print_stat(ST_ITR_INIT, latency); for (i=0;i<n;++i){ // sum time of all gets latency = timed_fdb_iterator_get(iterator, &doc); if(latency == ERR_NS){ break; } latency_tot += latency; // sum time of calls to next latency = timed_fdb_iterator_next(iterator); if(latency == ERR_NS){ break; } latency_tot2 += latency; fdb_doc_free(doc); doc = NULL; } latency_avg = float(latency_tot)/float(n); print_stat(ST_ITR_GET, latency_avg); latency_avg = float(latency_tot2)/float(n); print_stat(ST_ITR_NEXT, latency_avg); latency = timed_fdb_iterator_close(iterator); print_stat(ST_ITR_CLOSE, latency); // get for (i=0;i<n;++i){ sprintf(keybuf, "key%d", i); fdb_doc_create(&doc, keybuf, strlen(keybuf), NULL, 0, NULL, 0); status = fdb_get(kv, doc); TEST_CHK(status == FDB_RESULT_SUCCESS); fdb_doc_free(doc); doc = NULL; } // snapshot status = fdb_snapshot_open(kv, &snap_kv, FDB_SNAPSHOT_INMEM); TEST_CHK(status == FDB_RESULT_SUCCESS); // compact status = fdb_compact(fhandle, NULL); TEST_CHK(status == FDB_RESULT_SUCCESS); // delete latency_tot = 0; for (i=0;i<n;++i){ sprintf(keybuf, "key%d", i); fdb_doc_create(&doc, keybuf, strlen(keybuf), NULL, 0, NULL, 0); latency = timed_fdb_delete(kv, doc); latency_tot += latency; fdb_doc_free(doc); doc = NULL; } latency_avg = float(latency_tot)/float(n); print_stat(ST_DELETE, latency_avg); print_stats(fhandle); latency = timed_fdb_kvs_close(snap_kv); print_stat(ST_SNAP_CLOSE, latency); latency = timed_fdb_kvs_close(kv); print_stat(ST_KV_CLOSE, latency); latency = timed_fdb_close(fhandle); print_stat(ST_FILE_CLOSE, latency); latency = timed_fdb_shutdown(); print_stat(ST_SHUTDOWN, latency); } void permutated_keyset() { TEST_INIT(); char str[] = "abc123"; int n = strlen(str); ts_nsec latency, latency_tot = 0, latency_tot2 = 0; float latency_avg = 0; fdb_doc *rdoc = NULL; fdb_file_handle *fhandle; fdb_iterator *iterator; fdb_kvs_handle *kv; fdb_status status; printf("\nBENCH-PERMUTATED_KEYSET\n"); // setup setup_db(&fhandle, &kv); // load permuated keyset permute(kv, str, 0, n-1); status = fdb_commit(fhandle, FDB_COMMIT_MANUAL_WAL_FLUSH); TEST_CHK(status == FDB_RESULT_SUCCESS); // create an iterator for full range latency = timed_fdb_iterator_init(kv, &iterator); print_stat(ST_ITR_INIT, latency); // repeat until fail do { // sum time of all gets latency = timed_fdb_iterator_get(iterator, &rdoc); fdb_doc_free(rdoc); rdoc = NULL; if(latency == ERR_NS){ break; } latency_tot += latency; // sum time of calls to next latency = timed_fdb_iterator_next(iterator); if(latency == ERR_NS){ break; } latency_tot2 += latency; } while (latency != ERR_NS); latency_avg = float(latency_tot)/float(n); print_stat(ST_ITR_GET, latency_avg); latency_avg = float(latency_tot2)/float(n); print_stat(ST_ITR_NEXT, latency_avg); latency = timed_fdb_iterator_close(iterator); print_stat(ST_ITR_CLOSE, latency); print_stats(fhandle); latency = timed_fdb_kvs_close(kv); print_stat(ST_KV_CLOSE, latency); latency = timed_fdb_close(fhandle); print_stat(ST_FILE_CLOSE, latency); latency = timed_fdb_shutdown(); print_stat(ST_SHUTDOWN, latency); } void *writer_thread(void *args){ TEST_INIT(); thread_context *ctx= (thread_context*)args; fdb_kvs_handle *db = ctx->handle; char keybuf[KEY_SIZE]; // load a permutated keyset str_gen(keybuf, KEY_SIZE); permute(db, keybuf, 0, PERMUTED_BYTES); return NULL; } void *reader_thread(void *args){ TEST_INIT(); thread_context *ctx= (thread_context*)args; fdb_kvs_handle *db = ctx->handle; fdb_iterator *iterator; fdb_doc *rdoc = NULL; ts_nsec latency = 0; float a_latency1 = 0.0, a_latency2 = 0.0; int samples = 0; latency = timed_fdb_iterator_init(db, &iterator); ctx->latency1 = latency; // repeat until fail do { // sum time of all gets latency = timed_fdb_iterator_get(iterator, &rdoc); fdb_doc_free(rdoc); rdoc = NULL; if(latency == ERR_NS){ break; } a_latency1 += latency; // sum time of calls to next latency = timed_fdb_iterator_next(iterator); if(latency == ERR_NS){ break; } a_latency2 += latency; samples++; } while (latency != ERR_NS); a_latency1 = a_latency1/samples; a_latency2 = a_latency2/samples; // get latency ctx->avg_latency1 = a_latency1; // seek latency ctx->avg_latency2 = a_latency2; // close latency latency = timed_fdb_iterator_close(iterator); ctx->latency2 = latency; return NULL; } void single_file_single_kvs(int n_threads){ printf("\nBENCH-SINGLE_FILE_SINGLE_KVS\n"); TEST_INIT(); memleak_start(); int i, r; ts_nsec latency =0, latency2= 0; float a_latency1 = 0, a_latency2 = 0; char cmd[64]; fdb_status status; fdb_kvs_config kvs_config = fdb_get_default_kvs_config(); fdb_config fconfig = fdb_get_default_config(); thread_t *tid = alca(thread_t, n_threads); void **thread_ret = alca(void *, n_threads); thread_context *ctx = alca(thread_context, n_threads); sprintf(cmd, SHELL_DEL" bench* > errorlog.txt"); r = system(cmd); (void)r; // init db with flags fdb_file_handle *dbfile; fdb_kvs_handle **db = alca(fdb_kvs_handle*, n_threads); fdb_kvs_handle **snap_db = alca(fdb_kvs_handle*, n_threads); fconfig.compaction_mode = FDB_COMPACTION_MANUAL; fconfig.auto_commit = false; status = fdb_open(&dbfile, "bench1", &fconfig); TEST_CHK(status == FDB_RESULT_SUCCESS); for (i=0;i<n_threads;++i){ status = fdb_kvs_open(dbfile, &db[i], "db1", &kvs_config); TEST_CHK(status == FDB_RESULT_SUCCESS); ctx[i].handle = db[i]; thread_create(&tid[i], writer_thread, (void*)&ctx[i]); } for (i=0;i<n_threads;++i){ thread_join(tid[i], &thread_ret[i]); } status = fdb_commit(dbfile, FDB_COMMIT_MANUAL_WAL_FLUSH); TEST_CHK(status == FDB_RESULT_SUCCESS); // compact status = fdb_compact(dbfile, NULL); TEST_CHK(status == FDB_RESULT_SUCCESS); // snapshot for (i=0;i<n_threads;++i){ status = fdb_snapshot_open(db[i], &snap_db[i], FDB_SNAPSHOT_INMEM); TEST_CHK(status == FDB_RESULT_SUCCESS); } // n concurrent readers with snap_db latency = 0; latency2 = 0; a_latency1 = 0; a_latency2 = 0; for (i=0;i<n_threads;++i){ ctx[i].handle = snap_db[i]; thread_create(&tid[i], reader_thread, (void*)&ctx[i]); } for (i=0;i<n_threads;++i){ thread_join(tid[i], &thread_ret[i]); latency += ctx[i].latency1; latency2 += ctx[i].latency2; a_latency1 += ctx[i].avg_latency1; a_latency2 += ctx[i].avg_latency2; } latency = latency/n_threads; print_stat(ST_ITR_INIT, latency); a_latency1 = a_latency1/n_threads; print_stat(ST_ITR_GET, a_latency1); a_latency2 = a_latency2/n_threads; print_stat(ST_ITR_NEXT, a_latency2); latency2 = latency2/n_threads; print_stat(ST_ITR_CLOSE, latency2); // close snap and db latency = 0; for (i=0;i<n_threads;++i){ latency += timed_fdb_kvs_close(snap_db[i]); } latency = latency/n_threads; print_stat(ST_SNAP_CLOSE, latency); print_stats(dbfile); // close latency = 0; for (i=0;i<n_threads;++i){ latency += timed_fdb_kvs_close(db[i]); } latency = latency/n_threads; print_stat(ST_KV_CLOSE, latency); latency = timed_fdb_close(dbfile); print_stat(ST_FILE_CLOSE, latency); latency = timed_fdb_shutdown(); print_stat(ST_SHUTDOWN, latency); memleak_end(); } void single_file_multi_kvs(int n_threads){ printf("\nBENCH-SINGLE_FILE_MULTI_KVS\n"); TEST_INIT(); memleak_start(); int i, r; char cmd[64], db_name[64]; ts_nsec latency =0, latency2= 0; float a_latency1 = 0, a_latency2 = 0; fdb_status status; fdb_kvs_config kvs_config = fdb_get_default_kvs_config(); fdb_config fconfig = fdb_get_default_config(); thread_t *tid = alca(thread_t, n_threads); void **thread_ret = alca(void *, n_threads); thread_context *ctx = alca(thread_context, n_threads); sprintf(cmd, SHELL_DEL" bench* > errorlog.txt"); r = system(cmd); (void)r; // init db with flags fdb_file_handle *dbfile; fdb_kvs_handle **db = alca(fdb_kvs_handle*, n_threads); fdb_kvs_handle **snap_db = alca(fdb_kvs_handle*, n_threads); fconfig.compaction_mode = FDB_COMPACTION_MANUAL; fconfig.auto_commit = false; status = fdb_open(&dbfile, "bench1", &fconfig); TEST_CHK(status == FDB_RESULT_SUCCESS); for (i=0;i<n_threads;++i){ sprintf(db_name, "db%d", i); status = fdb_kvs_open(dbfile, &db[i], db_name, &kvs_config); TEST_CHK(status == FDB_RESULT_SUCCESS); ctx[i].handle = db[i]; thread_create(&tid[i], writer_thread, (void*)&ctx[i]); } for (i=0;i<n_threads;++i){ thread_join(tid[i], &thread_ret[i]); } status = fdb_commit(dbfile, FDB_COMMIT_MANUAL_WAL_FLUSH); TEST_CHK(status == FDB_RESULT_SUCCESS); // compact status = fdb_compact(dbfile, NULL); TEST_CHK(status == FDB_RESULT_SUCCESS); // snapshot for (i=0;i<n_threads;++i){ status = fdb_snapshot_open(db[i], &snap_db[i], FDB_SNAPSHOT_INMEM); TEST_CHK(status == FDB_RESULT_SUCCESS); } // readers latency = 0; latency2 = 0; a_latency1 = 0; a_latency2 = 0; for (i=0;i<n_threads;++i){ ctx[i].handle = snap_db[i]; thread_create(&tid[i], reader_thread, (void*)&ctx[i]); } for (i=0;i<n_threads;++i){ thread_join(tid[i], &thread_ret[i]); latency += ctx[i].latency1; latency2 += ctx[i].latency2; a_latency1 += ctx[i].avg_latency1; a_latency2 += ctx[i].avg_latency2; } latency = latency/n_threads; print_stat(ST_ITR_INIT, latency); a_latency1 = a_latency1/n_threads; print_stat(ST_ITR_GET, a_latency1); a_latency2 = a_latency2/n_threads; print_stat(ST_ITR_NEXT, a_latency2); latency2 = latency2/n_threads; print_stat(ST_ITR_CLOSE, latency2); // close snap and db latency = 0; for (i=0;i<n_threads;++i){ latency += timed_fdb_kvs_close(snap_db[i]); } latency = latency/n_threads; print_stat(ST_SNAP_CLOSE, latency); print_stats(dbfile); // close latency = 0; for (i=0;i<n_threads;++i){ latency += timed_fdb_kvs_close(db[i]); } latency = latency/n_threads; print_stat(ST_KV_CLOSE, latency); latency = timed_fdb_close(dbfile); print_stat(ST_FILE_CLOSE, latency); latency = timed_fdb_shutdown(); print_stat(ST_SHUTDOWN, latency); memleak_end(); } void multi_file_single_kvs(int n_threads){ printf("\nBENCH-MULTI_FILE_SINGLE_KVS\n"); TEST_INIT(); memleak_start(); int i, r; char cmd[64], fname[64]; ts_nsec latency =0, latency2= 0; float a_latency1 = 0, a_latency2 = 0; fdb_status status; fdb_kvs_config kvs_config = fdb_get_default_kvs_config(); fdb_config fconfig = fdb_get_default_config(); thread_t *tid = alca(thread_t, n_threads); void **thread_ret = alca(void *, n_threads); thread_context *ctx = alca(thread_context, n_threads); sprintf(cmd, SHELL_DEL" bench* > errorlog.txt"); r = system(cmd); (void)r; // init db with flags fdb_file_handle **dbfile = alca(fdb_file_handle*, n_threads); fdb_kvs_handle **db = alca(fdb_kvs_handle*, n_threads); fdb_kvs_handle **snap_db = alca(fdb_kvs_handle*, n_threads); fconfig.compaction_mode = FDB_COMPACTION_MANUAL; fconfig.auto_commit = false; for (i=0;i<n_threads;++i){ sprintf(fname, "bench%d",i); status = fdb_open(&dbfile[i], fname, &fconfig); TEST_CHK(status == FDB_RESULT_SUCCESS); // all same kv='db1' status = fdb_kvs_open(dbfile[i], &db[i], "db1", &kvs_config); TEST_CHK(status == FDB_RESULT_SUCCESS); ctx[i].handle = db[i]; thread_create(&tid[i], writer_thread, (void*)&ctx[i]); } for (i=0;i<n_threads;++i){ thread_join(tid[i], &thread_ret[i]); } // commit for (i=0;i<n_threads;++i){ status = fdb_commit(dbfile[i], FDB_COMMIT_MANUAL_WAL_FLUSH); TEST_CHK(status == FDB_RESULT_SUCCESS); } // compact for (i=0;i<n_threads;++i){ status = fdb_compact(dbfile[i], NULL); TEST_CHK(status == FDB_RESULT_SUCCESS); } // snapshot for (i=0;i<n_threads;++i){ status = fdb_snapshot_open(db[i], &snap_db[i], FDB_SNAPSHOT_INMEM); TEST_CHK(status == FDB_RESULT_SUCCESS); } // readers latency = 0; latency2 = 0; a_latency1 = 0; a_latency2 = 0; for (i=0;i<n_threads;++i){ ctx[i].handle = snap_db[i]; thread_create(&tid[i], reader_thread, (void*)&ctx[i]); } for (i=0;i<n_threads;++i){ thread_join(tid[i], &thread_ret[i]); latency += ctx[i].latency1; latency2 += ctx[i].latency2; a_latency1 += ctx[i].avg_latency1; a_latency2 += ctx[i].avg_latency2; } latency = latency/n_threads; print_stat(ST_ITR_INIT, latency); a_latency1 = a_latency1/n_threads; print_stat(ST_ITR_GET, a_latency1); a_latency2 = a_latency2/n_threads; print_stat(ST_ITR_NEXT, a_latency2); latency2 = latency2/n_threads; print_stat(ST_ITR_CLOSE, latency2); // close snap and db latency = 0; for (i=0;i<n_threads;++i){ latency += timed_fdb_kvs_close(snap_db[i]); } latency = latency/n_threads; print_stat(ST_SNAP_CLOSE, latency); print_stats_aggregate(dbfile, n_threads); // close latency = 0; for (i=0;i<n_threads;++i){ latency += timed_fdb_kvs_close(db[i]); } latency = latency/n_threads; print_stat(ST_KV_CLOSE, latency); for (i=0;i<n_threads;++i){ latency = timed_fdb_close(dbfile[i]); } latency = latency/n_threads; print_stat(ST_FILE_CLOSE, latency); latency = timed_fdb_shutdown(); print_stat(ST_SHUTDOWN, latency); memleak_end(); } void multi_file_multi_kvs(int n_threads){ printf("\nBENCH-MULTI_FILE_MULTI_KVS\n"); TEST_INIT(); memleak_start(); int i, j, r; char cmd[64], fname[64], dbname[64]; int n2_threads = n_threads*n_threads; ts_nsec latency =0, latency2= 0; float a_latency1 = 0, a_latency2 = 0; fdb_status status; fdb_kvs_config kvs_config = fdb_get_default_kvs_config(); fdb_config fconfig = fdb_get_default_config(); thread_t *tid = alca(thread_t, n2_threads); void **thread_ret = alca(void *, n2_threads); thread_context *ctx = alca(thread_context, n2_threads); sprintf(cmd, SHELL_DEL" bench* > errorlog.txt"); r = system(cmd); (void)r; // init db with flags fdb_file_handle **dbfile = alca(fdb_file_handle*, n_threads); fdb_kvs_handle **db = alca(fdb_kvs_handle*, n2_threads); fdb_kvs_handle **snap_db = alca(fdb_kvs_handle*, n2_threads); fconfig.compaction_mode = FDB_COMPACTION_MANUAL; fconfig.auto_commit = false; for (i=0; i < n_threads; ++i){ sprintf(fname, "bench%d",i); status = fdb_open(&dbfile[i], fname, &fconfig); TEST_CHK(status == FDB_RESULT_SUCCESS); for (j=i*n_threads; j < (i*n_threads + n_threads); ++j){ sprintf(dbname, "db%d",j); status = fdb_kvs_open(dbfile[i], &db[j], dbname, &kvs_config); TEST_CHK(status == FDB_RESULT_SUCCESS); ctx[j].handle = db[j]; thread_create(&tid[j], writer_thread, (void*)&ctx[j]); } } for (i=0;i<n2_threads;++i){ thread_join(tid[i], &thread_ret[i]); } // commit for (i=0;i<n_threads;++i){ status = fdb_commit(dbfile[i], FDB_COMMIT_MANUAL_WAL_FLUSH); TEST_CHK(status == FDB_RESULT_SUCCESS); } // compact for (i=0;i<n_threads;++i){ status = fdb_compact(dbfile[i], NULL); TEST_CHK(status == FDB_RESULT_SUCCESS); } // snapshot latency = 0; for (i=0;i<n2_threads;++i){ status = fdb_snapshot_open(db[i], &snap_db[i], FDB_SNAPSHOT_INMEM); TEST_CHK(status == FDB_RESULT_SUCCESS); } // readers latency = 0; latency2 = 0; a_latency1 = 0; a_latency2 = 0; for (i=0;i<n2_threads;++i){ ctx[i].handle = snap_db[i]; thread_create(&tid[i], reader_thread, (void*)&ctx[i]); } for (i=0;i<n2_threads;++i){ thread_join(tid[i], &thread_ret[i]); latency += ctx[i].latency1; latency2 += ctx[i].latency2; a_latency1 += ctx[i].avg_latency1; a_latency2 += ctx[i].avg_latency2; } latency = latency/n2_threads; print_stat(ST_ITR_INIT, latency); a_latency1 = a_latency1/n2_threads; print_stat(ST_ITR_GET, a_latency1); a_latency2 = a_latency2/n2_threads; print_stat(ST_ITR_NEXT, a_latency2); latency2 = latency2/n2_threads; print_stat(ST_ITR_CLOSE, latency2); // close snap and db latency = 0; for (i=0;i<n2_threads;++i){ latency += timed_fdb_kvs_close(snap_db[i]); } latency = latency/n2_threads; print_stat(ST_SNAP_CLOSE, latency); print_stats_aggregate(dbfile, n_threads); // close latency = 0; for (i=0;i<n2_threads;++i){ latency += timed_fdb_kvs_close(db[i]); } latency = latency/n2_threads; print_stat(ST_KV_CLOSE, latency); for (i=0;i<n_threads;++i){ latency = timed_fdb_close(dbfile[i]); } latency = latency/n_threads; print_stat(ST_FILE_CLOSE, latency); latency = timed_fdb_shutdown(); print_stat(ST_SHUTDOWN, latency); memleak_end(); } int main(int argc, char* args[]) { sequential_set(true); sequential_set(false); permutated_keyset(); // threaded single_file_single_kvs(10); single_file_multi_kvs(10); multi_file_single_kvs(10); multi_file_multi_kvs(10); }
26.906651
78
0.624442
hundredbag
06a33a4cfa6cdb28bdf60b636539b38a7f9cc0ce
1,359
cpp
C++
Problems/Hackerrank/rotateArray.cpp
pedrotorreao/DSA
31f9dffbed5275590d5c7b7f6a73fd6dea411564
[ "MIT" ]
1
2021-07-08T01:02:06.000Z
2021-07-08T01:02:06.000Z
Problems/Hackerrank/rotateArray.cpp
pedrotorreao/DSA
31f9dffbed5275590d5c7b7f6a73fd6dea411564
[ "MIT" ]
null
null
null
Problems/Hackerrank/rotateArray.cpp
pedrotorreao/DSA
31f9dffbed5275590d5c7b7f6a73fd6dea411564
[ "MIT" ]
null
null
null
/************************************************************/ /*Problem: Rotate Array (HR) ********/ /************************************************************/ /* -- Summary: A left rotation operation on an array shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2]. Note that the lowest index item moves to the highest index in a rotation. This is called a circular array. Given an array 'a' of integers and a number, d, perform d left rotations on the array. Return the updated array to be printed as a single line of space-separated integers. -- Input(s): a: array containing n integers d: the number of rotations -- Expected output(s): a': rotated array -- Constraints: (1 ≤ n ≤ 10^6), (1 ≤ d ≤ n), (1 ≤ a[i] ≤ 10^6) */ #include <iostream> #include <vector> #include <algorithm> void rotLeft(std::vector<int> a, int d) { if (a.size() == d) { return; } std::rotate(a.begin(), a.begin() + d, a.end()); for (auto i : a) { std::cout << i << " "; } std::cout << "\n"; } int main() { std::vector<int> a1{1, 2, 3, 4, 5}; std::vector<int> a2{0, 0, 0, 0, 1}; int d1{4}; int d2{3}; rotLeft(a1, d1); rotLeft(a2, d2); return 0; }
26.134615
101
0.534216
pedrotorreao
06a4cc5b66aa8f7b8b4106f25c53297268a8bd29
456
hpp
C++
engine/time/include/SpecialDayObserver.hpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
engine/time/include/SpecialDayObserver.hpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
engine/time/include/SpecialDayObserver.hpp
prolog/shadow-of-the-wyrm
a1312c3e9bb74473f73c4e7639e8bd537f10b488
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#pragma once #include "ITimeObserver.hpp" #include "Map.hpp" #include "Calendar.hpp" class SpecialDayObserver : public ITimeObserver { public: void notify(const ulonglong minutes_elapsed) override; std::unique_ptr<ITimeObserver> clone() override; protected: void check_special_day(const std::map<int, CalendarDay>& calendar_days, const Calendar& calendar); private: ClassIdentifier internal_class_identifier() const override; };
22.8
102
0.760965
prolog
06a6d2e1a71286edf3abf664abcce0a1ef1a08cc
3,155
hh
C++
src/operators/Op_Face_CellBndFace.hh
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
37
2017-04-26T16:27:07.000Z
2022-03-01T07:38:57.000Z
src/operators/Op_Face_CellBndFace.hh
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
494
2016-09-14T02:31:13.000Z
2022-03-13T18:57:05.000Z
src/operators/Op_Face_CellBndFace.hh
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
43
2016-09-26T17:58:40.000Z
2022-03-25T02:29:59.000Z
/* Operators Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL. Amanzi is released under the three-clause BSD License. The terms of use and "as is" disclaimer for this license are provided in the top-level COPYRIGHT file. Author: Ethan Coon (ecoon@lanl.gov) */ #ifndef AMANZI_OP_FACE_CELLFACE_HH_ #define AMANZI_OP_FACE_CELLFACE_HH_ #include <vector> #include "DenseMatrix.hh" #include "Operator.hh" #include "Op.hh" /* Op classes are small structs that play two roles: 1. They provide a class name to the schema, enabling visitor patterns. 2. They are a container for local matrices. This Op class is for storing local matrices of length nfaces and with dofs on cells, i.e. for Advection or for TPFA. */ namespace Amanzi { namespace Operators { class Op_Face_CellBndFace : public Op { public: Op_Face_CellBndFace(std::string& name, const Teuchos::RCP<const AmanziMesh::Mesh> mesh) : Op(OPERATOR_SCHEMA_BASE_FACE | OPERATOR_SCHEMA_DOFS_CELL | OPERATOR_SCHEMA_DOFS_FACE | OPERATOR_SCHEMA_DOFS_BNDFACE, name, mesh) { WhetStone::DenseMatrix null_matrix; nfaces_owned = mesh->num_entities(AmanziMesh::FACE, AmanziMesh::Parallel_type::OWNED); matrices.resize(nfaces_owned, null_matrix); matrices_shadow = matrices; } virtual void ApplyMatrixFreeOp(const Operator* assembler, const CompositeVector& X, CompositeVector& Y) const { assembler->ApplyMatrixFreeOp(*this, X, Y); } virtual void SymbolicAssembleMatrixOp(const Operator* assembler, const SuperMap& map, GraphFE& graph, int my_block_row, int my_block_col) const { assembler->SymbolicAssembleMatrixOp(*this, map, graph, my_block_row, my_block_col); } virtual void AssembleMatrixOp(const Operator* assembler, const SuperMap& map, MatrixFE& mat, int my_block_row, int my_block_col) const { assembler->AssembleMatrixOp(*this, map, mat, my_block_row, my_block_col); } virtual void Rescale(const CompositeVector& scaling) { if ((scaling.HasComponent("cell"))&&(scaling.HasComponent("boundary_face"))) { const Epetra_MultiVector& s_c = *scaling.ViewComponent("cell",true); const Epetra_MultiVector& s_bnd = *scaling.ViewComponent("boundary_face",true); AmanziMesh::Entity_ID_List cells; for (int f = 0; f != matrices.size(); ++f) { mesh_->face_get_cells(f, AmanziMesh::Parallel_type::ALL, &cells); if (cells.size() > 1) { matrices[f](0,0) *= s_c[0][cells[0]]; matrices[f](0,1) *= s_c[0][cells[1]]; matrices[f](1,0) *= s_c[0][cells[0]]; matrices[f](1,1) *= s_c[0][cells[1]]; }else if (cells.size()==1) { int bf = mesh_->exterior_face_map(false).LID(mesh_->face_map(false).GID(f)); matrices[f](0,0) *= s_c[0][cells[0]]; matrices[f](1,0) *= s_c[0][cells[0]]; matrices[f](0,1) *= s_bnd[0][bf]; matrices[f](1,1) *= s_bnd[0][bf]; } } } } protected: int nfaces_owned; }; } // namespace Operators } // namespace Amanzi #endif
32.525773
94
0.662758
fmyuan
06ad574224ad027a6116bff88722c86540a0b880
2,419
cpp
C++
tan/samples/src/FileToHeader/stdafx.cpp
amono/TAN
690ed6a92c594f4ba3a26d1c8b77dbff386c9b04
[ "MIT" ]
128
2016-08-17T21:57:05.000Z
2022-03-30T17:44:36.000Z
tan/samples/src/FileToHeader/stdafx.cpp
amono/TAN
690ed6a92c594f4ba3a26d1c8b77dbff386c9b04
[ "MIT" ]
8
2016-08-18T18:39:12.000Z
2021-11-12T19:10:30.000Z
tan/samples/src/FileToHeader/stdafx.cpp
isabella232/TAN
690ed6a92c594f4ba3a26d1c8b77dbff386c9b04
[ "MIT" ]
30
2016-08-18T19:36:06.000Z
2022-03-30T17:28:31.000Z
// // MIT license // // Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // stdafx.cpp : source file that includes just the standard includes // CLKernelPreprocessor.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" #if !defined(_WIN32) && defined( __GNUC__ ) #include <cassert> #include <cerrno> #include <cerrno> #include <cwchar> #include <cstdlib> /*inline std::string narrow(std::wstring const& text) { std::locale const loc(""); wchar_t const* from = text.c_str(); std::size_t const len = text.size(); std::vector<char> buffer(len + 1); std::use_facet<std::ctype<wchar_t> >(loc).narrow(from, from + len, '_', &buffer[0]); return std::string(&buffer[0], &buffer[len]); } std::string w2s(const std::wstring &var) { static std::locale loc(""); auto &facet = std::use_facet<std::codecvt<wchar_t, char, std::mbstate_t>>(loc); return std::wstring_convert<std::remove_reference<decltype(facet)>::type, wchar_t>(&facet).to_bytes(var); } std::wstring s2w(const std::string &var) { static std::locale loc(""); auto &facet = std::use_facet<std::codecvt<wchar_t, char, std::mbstate_t>>(loc); return std::wstring_convert<std::remove_reference<decltype(facet)>::type, wchar_t>(&facet).from_bytes(var); }*/ #endif
39.016129
110
0.724266
amono
06b09ea60d30ace1f4d18be2244f7f9b3d31af8f
3,950
cpp
C++
graph-source-code/450-D/12227770.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/450-D/12227770.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/450-D/12227770.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++11 #include <cctype> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <sstream> #include <iomanip> #include <string> #include <vector> #include <set> #include <map> #include <queue> #include <stack> #include <list> #include <algorithm> using namespace std; #define nln puts("") ///prLLInewline #define getLLI(a) scanf("%d",&a); #define max3(a,b,c) max(a,max(b,c)) ///3 ta theke max #define min3(a,b,c) min(a,min(b,c)) ///3 ta theke min #define FOR1(i,n) for(LLI i=1;i<=n;i++) #define FOR0(i,n) for(LLI i=0;i<n;i++) ///looping #define FORR(i,n) for(LLI i=n-1;i>=0;i--) #define ALL(p) p.begin(),p.end() #define SET(p) memset(p,-1,sizeof(p)) #define CLR(p) memset(p,0,sizeof(p)) ///memset #define MEM(p,v) memset(p,v,sizeof(p)) #define READ(f) freopen(f, "r", stdin) /// file #define WRITE(f) freopen(f, "w", stdout) #define SZ(c) (LLI)c.size() #define PB(x) push_back(x) ///STL defines #define MP(x,y) make_pair(x,y) #define ff first #define ss second #define LI long LLI #define LLI long long #define f64 long double #define PI acos(-1.0) ///PI er value #define mx 300005 #define ll long long #define inf 1e10 vector<LLI>G[mx],dis[mx]; void CI(LLI &_x) { scanf("%I64d",&_x); } map<pair<LLI,LLI>,LLI>train_route; struct node { ll city,cost; bool operator <(const node& p)const { return cost>p.cost; } }; //vector<ll>G[mx],dis[mx]; LLI col[mx]; ll d[mx]; ll path[mx]; ll djs(ll src) { for(ll i=0; i<mx; i++) d[i]=inf,path[i]=-1; d[src]=0; node a; a.city=src,a.cost=0; priority_queue<node>Q; Q.push(a); while(!Q.empty()) { a=Q.top(); Q.pop(); ll u=a.city; if(col[u]==1)continue; col[u]=1; // if(des==u) // { // // puts("ffffffffff"); // return d[u]; // // } for(ll i=0; i<G[u].size(); i++) { ll v=G[u][i]; // cout<<v<<" "; //cout<<d[u]<<" "<<dis[u][i]<<endl; if(d[u]+dis[u][i]<d[v]) { //puts("ffffffffff"); d[v]=d[u]+dis[u][i]; path[v]=u; a.city=v; a.cost=d[v]; Q.push(a); } } } return -1; } LLI used[mx]; int main() { LLI n,m,k; // cin>>n>>m>>k; CI(n); CI(m); CI(k); LLI u,v,w; FOR0(i,m) { LLI u,v,w; // cin>>u>>v>>w; CI(u); CI(v); CI(w); // if(found[MP(min(u,v),max(u,v))]==0) // found[MP(min(u,v),max(u,v))]=1<<30; // found[MP(min(u,v),max(u,v))]=min(w,found[MP(min(u,v),max(u,v))]); G[u].PB(v); G[v].PB(u); dis[u].PB(w); dis[v].PB(w); } vector<LLI>V; memset(col,-1,sizeof col); LLI kount=0; FOR0(i,k) { LLI s,y; // cin>>s>>y; CI(s); CI(y); V.PB(s); G[1].PB(s); dis[1].PB(y); } djs(1); FOR0(i,k) { G[1].pop_back(); dis[1].pop_back(); } for(LLI i=1; i<=n; i++) for(LLI j=0; j<G[i].size(); j++) { LLI u=i,v=G[i][j]; if(d[v]==d[u]+dis[i][j]) used[v]=1; } // LLI kount=0; for(LLI i=0; i<V.size(); i++) { if(used[V[i]]==1){ } else{ kount++; used[V[i]]=1; } } cout<<k-kount<<"\n"; }
19.849246
79
0.409114
AmrARaouf
06b41a5ea007dc3b23dc70c96d092fa876523fdb
17,745
cpp
C++
trview.app.tests/ItemsWindowTests.cpp
chreden/trview
e2a5e3539036f27adfa54fc7fcf4c3537b99a221
[ "MIT" ]
20
2018-10-17T02:00:03.000Z
2022-03-24T09:37:20.000Z
trview.app.tests/ItemsWindowTests.cpp
chreden/trview
e2a5e3539036f27adfa54fc7fcf4c3537b99a221
[ "MIT" ]
396
2018-07-22T16:11:47.000Z
2022-03-29T11:57:03.000Z
trview.app.tests/ItemsWindowTests.cpp
chreden/trview
e2a5e3539036f27adfa54fc7fcf4c3537b99a221
[ "MIT" ]
8
2018-07-25T21:31:06.000Z
2021-11-01T14:36:26.000Z
#include <trview.app/Windows/ItemsWindow.h> #include <trview.tests.common/Window.h> #include <trview.ui/Button.h> #include <trview.ui/Checkbox.h> #include <trview.common/Size.h> #include <trview.app/Elements/Types.h> #include <trview.graphics/mocks/IDeviceWindow.h> #include <trview.ui.render/Mocks/IRenderer.h> #include <trview.common/Mocks/Windows/IClipboard.h> #include <trview.ui/Mocks/Input/IInput.h> #include <trview.app/Mocks/Elements/ITrigger.h> #include <trview.app/Mocks/UI/IBubble.h> using namespace trview; using namespace trview::tests; using namespace trview::graphics; using namespace trview::graphics::mocks; using namespace trview::ui; using namespace trview::ui::mocks; using namespace trview::ui::render; using namespace trview::ui::render::mocks; using namespace trview::mocks; namespace { auto register_test_module() { struct test_module { IDeviceWindow::Source device_window_source{ [](auto&&...) { return std::make_unique<MockDeviceWindow>(); } }; IRenderer::Source renderer_source{ [](auto&&...) { return std::make_unique<MockRenderer>(); } }; IInput::Source input_source{ [](auto&&...) { return std::make_unique<MockInput>(); } }; trview::Window window{ create_test_window(L"ItemsWindowTests") }; std::shared_ptr<IClipboard> clipboard{ std::make_shared<MockClipboard>() }; IBubble::Source bubble_source{ [](auto&&...) { return std::make_unique<MockBubble>(); } }; test_module& with_bubble_source(const IBubble::Source& source) { this->bubble_source = source; return *this; } std::unique_ptr<ItemsWindow> build() { return std::make_unique<ItemsWindow>(device_window_source, renderer_source, input_source, window, clipboard, bubble_source); } }; return test_module {}; } } TEST(ItemsWindow, AddToRouteEventRaised) { auto window = register_test_module().build(); std::optional<Item> raised_item; auto token = window->on_add_to_route += [&raised_item](const auto& item) { raised_item = item; }; std::vector<Item> items { Item(0, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero), Item(1, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero) }; window->set_items(items); window->set_selected_item(items[1]); auto button = window->root_control()->find<ui::Button>(ItemsWindow::Names::add_to_route_button); ASSERT_NE(button, nullptr); button->clicked(Point()); ASSERT_TRUE(raised_item.has_value()); ASSERT_EQ(raised_item.value().number(), 1); } TEST(ItemsWindow, ClearSelectedItemClearsSelection) { auto window = register_test_module().build(); std::optional<Item> raised_item; auto token = window->on_item_selected += [&raised_item](const auto& item) { raised_item = item; }; auto trigger = std::make_shared<MockTrigger>(); std::vector<Item> items { Item(0, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero), Item(1, 0, 0, L"Type", 0, 0, { trigger }, DirectX::SimpleMath::Vector3::Zero) }; window->set_items(items); window->set_triggers({ trigger }); auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox); ASSERT_NE(list, nullptr); auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "1"); ASSERT_NE(row, nullptr); auto cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#"); ASSERT_NE(cell, nullptr); cell->clicked(Point()); ASSERT_TRUE(raised_item.has_value()); ASSERT_EQ(raised_item.value().number(), 1); auto stats_list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::stats_listbox); ASSERT_NE(stats_list, nullptr); auto stats_items = stats_list->items(); ASSERT_NE(stats_items.size(), 0); auto triggers_list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::triggers_listbox); ASSERT_NE(triggers_list, nullptr); auto triggers_items = triggers_list->items(); ASSERT_NE(triggers_items.size(), 0); window->clear_selected_item(); stats_items = stats_list->items(); ASSERT_EQ(stats_items.size(), 0); triggers_items = triggers_list->items(); ASSERT_EQ(triggers_items.size(), 0); } TEST(ItemsWindow, ItemSelectedNotRaisedWhenSyncItemDisabled) { auto window = register_test_module().build(); std::optional<Item> raised_item; auto token = window->on_item_selected += [&raised_item](const auto& item) { raised_item = item; }; std::vector<Item> items { Item(0, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero), Item(1, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero) }; window->set_items(items); auto sync = window->root_control()->find<ui::Checkbox>(ItemsWindow::Names::sync_item_checkbox); ASSERT_NE(sync, nullptr); sync->clicked(Point()); auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox); ASSERT_NE(list, nullptr); auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "1"); ASSERT_NE(row, nullptr); auto cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#"); ASSERT_NE(cell, nullptr); cell->clicked(Point()); ASSERT_FALSE(raised_item.has_value()); } TEST(ItemsWindow, ItemSelectedRaisedWhenSyncItemEnabled) { auto window = register_test_module().build(); std::optional<Item> raised_item; auto token = window->on_item_selected += [&raised_item](const auto& item) { raised_item = item; }; std::vector<Item> items { Item(0, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero), Item(1, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero) }; window->set_items(items); auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox); ASSERT_NE(list, nullptr); auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "1"); ASSERT_NE(row, nullptr); auto cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#"); ASSERT_NE(cell, nullptr); cell->clicked(Point()); ASSERT_TRUE(raised_item.has_value()); ASSERT_EQ(raised_item.value().number(), 1); } TEST(ItemsWindow, ItemVisibilityRaised) { auto window = register_test_module().build(); std::optional<std::tuple<Item, bool>> raised_item; auto token = window->on_item_visibility += [&raised_item](const auto& item, bool state) { raised_item = { item, state }; }; std::vector<Item> items { Item(0, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero), Item(1, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero) }; window->set_items(items); auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox); ASSERT_NE(list, nullptr); auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "1"); ASSERT_NE(row, nullptr); auto cell = row->find<ui::Checkbox>(ui::Listbox::Row::Names::cell_name_format + "Hide"); ASSERT_NE(cell, nullptr); cell->clicked(Point()); ASSERT_TRUE(raised_item.has_value()); ASSERT_FALSE(std::get<1>(raised_item.value())); ASSERT_EQ(std::get<0>(raised_item.value()).number(), 1); } TEST(ItemsWindow, ItemsListNotFilteredWhenRoomSetAndTrackRoomDisabled) { auto window = register_test_module().build(); std::optional<Item> raised_item; auto token = window->on_item_selected += [&raised_item](const auto& item) { raised_item = item; }; std::vector<Item> items { Item(0, 55, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero), Item(1, 78, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero) }; window->set_items(items); window->set_current_room(78); auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox); ASSERT_NE(list, nullptr); auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "0"); ASSERT_NE(row, nullptr); auto cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#"); ASSERT_NE(cell, nullptr); cell->clicked(Point()); ASSERT_TRUE(raised_item.has_value()); ASSERT_EQ(raised_item.value().number(), 0); } TEST(ItemsWindow, ItemsListFilteredWhenRoomSetAndTrackRoomEnabled) { auto window = register_test_module().build(); std::optional<Item> raised_item; auto token = window->on_item_selected += [&raised_item](const auto& item) { raised_item = item; }; std::vector<Item> items { Item(0, 55, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero), Item(1, 78, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero) }; window->set_items(items); window->set_current_room(78); auto track = window->root_control()->find<ui::Checkbox>(ItemsWindow::Names::track_room_checkbox); ASSERT_NE(track, nullptr); track->clicked(Point()); auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox); ASSERT_NE(list, nullptr); auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "0"); ASSERT_NE(row, nullptr); auto cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#"); ASSERT_NE(cell, nullptr); cell->clicked(Point()); ASSERT_TRUE(raised_item.has_value()); ASSERT_EQ(raised_item.value().number(), 1); } TEST(ItemsWindow, ItemsListPopulatedOnSet) { auto window = register_test_module().build(); std::vector<Item> items { Item(0, 55, 0, L"Lara", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero), Item(1, 78, 0, L"Winston", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero) }; window->set_items(items); auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox); ASSERT_NE(list, nullptr); for (auto i = 0; i < items.size(); ++i) { const auto& item = items[i]; auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + std::to_string(i)); ASSERT_NE(row, nullptr); auto number_cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#"); ASSERT_NE(number_cell, nullptr); ASSERT_EQ(number_cell->text(), std::to_wstring(item.number())); auto room_cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "Room"); ASSERT_NE(room_cell, nullptr); ASSERT_EQ(room_cell->text(), std::to_wstring(item.room())); auto type_cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "Type"); ASSERT_NE(type_cell, nullptr); ASSERT_EQ(type_cell->text(), item.type()); } } TEST(ItemsWindow, ItemsListUpdatedWhenFiltered) { auto window = register_test_module().build(); std::vector<Item> items { Item(0, 55, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero), Item(1, 78, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero) }; window->set_items(items); window->set_current_room(78); auto track = window->root_control()->find<ui::Checkbox>(ItemsWindow::Names::track_room_checkbox); ASSERT_NE(track, nullptr); track->clicked(Point()); auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox); ASSERT_NE(list, nullptr); auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "0"); ASSERT_NE(row, nullptr); auto cell = row->find<ui::Checkbox>(ui::Listbox::Row::Names::cell_name_format + "Hide"); ASSERT_NE(cell, nullptr); ASSERT_FALSE(cell->state()); items[1].set_visible(false); window->update_items(items); cell = row->find<ui::Checkbox>(ui::Listbox::Row::Names::cell_name_format + "Hide"); ASSERT_TRUE(cell->state()); } TEST(ItemsWindow, ItemsListUpdatedWhenNotFiltered) { auto window = register_test_module().build(); std::vector<Item> items { Item(0, 55, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero), Item(1, 78, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero) }; window->set_items(items); auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox); ASSERT_NE(list, nullptr); auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "1"); ASSERT_NE(row, nullptr); auto cell = row->find<ui::Checkbox>(ui::Listbox::Row::Names::cell_name_format + "Hide"); ASSERT_NE(cell, nullptr); ASSERT_FALSE(cell->state()); items[1].set_visible(false); window->update_items(items); cell = row->find<ui::Checkbox>(ui::Listbox::Row::Names::cell_name_format + "Hide"); ASSERT_TRUE(cell->state()); } TEST(ItemsWindow, SelectionSurvivesFiltering) { auto window = register_test_module().build(); std::vector<Item> items { Item(0, 55, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero), Item(1, 78, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero) }; window->set_items(items); window->set_current_room(78); auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox); ASSERT_NE(list, nullptr); auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "1"); ASSERT_NE(row, nullptr); auto cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#"); ASSERT_NE(cell, nullptr); cell->clicked(Point()); auto track = window->root_control()->find<ui::Checkbox>(ItemsWindow::Names::track_room_checkbox); ASSERT_NE(track, nullptr); track->clicked(Point()); auto now_selected = list->selected_item(); ASSERT_TRUE(now_selected.has_value()); ASSERT_EQ(now_selected.value().value(L"#"), L"1"); } TEST(ItemsWindow, TriggersLoadedForItem) { auto window = register_test_module().build(); auto trigger1 = std::make_shared<MockTrigger>()->with_number(0); auto trigger2 = std::make_shared<MockTrigger>()->with_number(1); std::vector<Item> items { Item(0, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero), Item(1, 0, 0, L"Type", 0, 0, { trigger1, trigger2 }, DirectX::SimpleMath::Vector3::Zero) }; window->set_items(items); window->set_triggers({ trigger1, trigger2 }); auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox); ASSERT_NE(list, nullptr); auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "1"); ASSERT_NE(row, nullptr); auto cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#"); ASSERT_NE(cell, nullptr); cell->clicked(Point()); auto triggers_list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::triggers_listbox); ASSERT_NE(triggers_list, nullptr); auto triggers_items = triggers_list->items(); ASSERT_EQ(triggers_items.size(), 2); ASSERT_EQ(triggers_items[0].value(L"#"), L"0"); ASSERT_EQ(triggers_items[1].value(L"#"), L"1"); } TEST(ItemsWindow, TriggerSelectedEventRaised) { auto window = register_test_module().build(); std::optional<std::weak_ptr<ITrigger>> raised_trigger; auto token = window->on_trigger_selected += [&raised_trigger](const auto& trigger) { raised_trigger = trigger; }; auto trigger = std::make_shared<MockTrigger>(); std::vector<Item> items { Item(0, 0, 0, L"Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero), Item(1, 0, 0, L"Type", 0, 0, { trigger }, DirectX::SimpleMath::Vector3::Zero) }; window->set_items(items); window->set_triggers({ trigger }); auto list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::items_listbox); ASSERT_NE(list, nullptr); auto row = list->find<ui::Control>(ui::Listbox::Names::row_name_format + "1"); ASSERT_NE(row, nullptr); auto cell = row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#"); ASSERT_NE(row, nullptr); cell->clicked(Point()); auto triggers_list = window->root_control()->find<ui::Listbox>(ItemsWindow::Names::triggers_listbox); ASSERT_NE(triggers_list, nullptr); auto triggers_row = triggers_list->find<ui::Control>(ui::Listbox::Names::row_name_format + "0"); ASSERT_NE(triggers_row, nullptr); auto triggers_cell = triggers_row->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "#"); ASSERT_NE(triggers_cell, nullptr); triggers_cell->clicked(Point()); ASSERT_TRUE(raised_trigger.has_value()); ASSERT_EQ(raised_trigger.value().lock(), trigger); } TEST(ItemsWindow, ClickStatShowsBubble) { auto bubble = std::make_unique<MockBubble>(); EXPECT_CALL(*bubble, show(testing::A<const Point&>())).Times(1); auto window = register_test_module().with_bubble_source([&](auto&&...) { return std::move(bubble); }).build(); std::vector<Item> items { Item(0, 0, 0, L"Test Type", 0, 0, {}, DirectX::SimpleMath::Vector3::Zero) }; window->set_items(items); window->set_selected_item(items[0]); auto stats = window->root_control()->find<Listbox>(ItemsWindow::Names::stats_listbox); ASSERT_NE(stats, nullptr); auto first_stat = stats->find<ui::Control>(Listbox::Names::row_name_format + "0"); ASSERT_NE(first_stat, nullptr); auto value = first_stat->find<ui::Button>(ui::Listbox::Row::Names::cell_name_format + "Value"); ASSERT_NE(value, nullptr); value->clicked(Point()); }
35.561122
140
0.656579
chreden
06c23d1725d489d827b15bf1889a6b3c62707a06
694
hpp
C++
CamelusMips/Timer.hpp
MForever78/CamelusMips
fd55f00e70bee448ad25951013cc1fdad3d3b456
[ "MIT" ]
null
null
null
CamelusMips/Timer.hpp
MForever78/CamelusMips
fd55f00e70bee448ad25951013cc1fdad3d3b456
[ "MIT" ]
1
2016-05-02T05:23:08.000Z
2016-05-02T05:24:01.000Z
CamelusMips/Timer.hpp
MForever78/CamelusMips
fd55f00e70bee448ad25951013cc1fdad3d3b456
[ "MIT" ]
null
null
null
// // Created by MForever78 on 16/4/19. // #ifndef TIMER_HPP #define TIMER_HPP #include "Device.hpp" class Timer: Device { public: inline void set(const std::uint32_t data) override { counting = true; reverseCount = data; } inline std::uint32_t get() const override { return clock; }; void tick() { clock++; timeSlice++; if (counting) reverseCount--; if (reverseCount == 0) { counting = false; interrupting = true; } } private: std::uint32_t clock = 0; bool counting = false; std::uint32_t reverseCount = 0; std::uint32_t timeSlice = 0; }; #endif //TIMER_HPP
17.794872
56
0.569164
MForever78
06d02c7c4e8dc590c433c9111fd27d9385257673
1,567
cpp
C++
Lab6/orange_sorting.cpp
NLaDuke/CSIII-Labs
8f2658d6fcf6cc838bbef17bc5110a10c742bf0e
[ "MIT" ]
null
null
null
Lab6/orange_sorting.cpp
NLaDuke/CSIII-Labs
8f2658d6fcf6cc838bbef17bc5110a10c742bf0e
[ "MIT" ]
null
null
null
Lab6/orange_sorting.cpp
NLaDuke/CSIII-Labs
8f2658d6fcf6cc838bbef17bc5110a10c742bf0e
[ "MIT" ]
null
null
null
#include <iostream> #include <ctime> #include <cstdlib> #include <map> #include <vector> #include <string> using std::cin; using std::cout; using std::endl; using std::string; using std::multimap; using std::vector; //---------------------------- // File: orange_sorting.cpp // By: Nolan LaDuke // Date: 2/23/2021 //------------------------------------------------------------------------------ // Function: Generates random 'fruits', then prints out the color of each // orange separated by a ' '. Implemented using a multimap //------------------------------------------------------------------------------ // Based on a file provided by Mikhal Nesterenko, KSU //------------------------------------------------------------------------------ // Setup to convert random-integers into usable data enum class Variety {orange, pear, apple}; vector<string> colors = {"red", "green", "yellow"}; int main(){ // Set seed srand(time(nullptr)); // Set up variables: multimap<Variety, string> tree; // Structure to contain generated fruit int numOfFruits = (rand()%100+1); // Number of fruits to generate for(int i = 0; i < numOfFruits; i++){ // Generate fruit pair and add it to tree tree.emplace(std::make_pair(static_cast<Variety>(rand() % 3), colors[rand() % 3])); } cout << "Colors of the oranges: "; // Iterate through oranges and print out the color of each for(auto f=tree.lower_bound(Variety(0)); f!=tree.upper_bound(Variety(0));++f) cout << f->second << " "; cout << endl; }
33.340426
80
0.539247
NLaDuke
06d5dfc2c7dd31fc4be1b00c490ad9746a9298e2
2,382
cpp
C++
TestApp1/DragTextUI.cpp
EndofDeath/Duilib_adrival
2fc0a4cc2a6ea2a6d945baf16e41d252c1417be3
[ "BSD-2-Clause", "MIT" ]
null
null
null
TestApp1/DragTextUI.cpp
EndofDeath/Duilib_adrival
2fc0a4cc2a6ea2a6d945baf16e41d252c1417be3
[ "BSD-2-Clause", "MIT" ]
null
null
null
TestApp1/DragTextUI.cpp
EndofDeath/Duilib_adrival
2fc0a4cc2a6ea2a6d945baf16e41d252c1417be3
[ "BSD-2-Clause", "MIT" ]
null
null
null
#include "stdafx.h" #include "DragTextUI.h" LPCTSTR UI_DRAGTEXT = _T("DragText"); CDragTextUI::CDragTextUI() { } CDragTextUI::~CDragTextUI() { } LPCTSTR CDragTextUI::GetClass() const { return UI_DRAGTEXT; } LPVOID CDragTextUI::GetInterface(LPCTSTR pstrName) { if (_tcscmp(pstrName, UI_DRAGTEXT) == 0) return static_cast<CDragTextUI*>(this); return CTextUI::GetInterface(pstrName); } void CDragTextUI::DoEvent(TEventUI& event) { { if (event.Type == UIEVENT_BUTTONDOWN && IsEnabled()) { m_ptLastMouse = event.ptMouse; m_rcNewPos = m_rcItem; if (m_pManager) m_pManager->AddPostPaint(this); return; } if (event.Type == UIEVENT_BUTTONUP) { RECT rcParent = m_pParent->GetPos(); m_rcNewPos.left -= rcParent.left; m_rcNewPos.right -= rcParent.left; m_rcNewPos.top -= rcParent.top; m_rcNewPos.bottom -= rcParent.top; SetPos(m_rcNewPos); if (m_pManager) m_pManager->RemovePostPaint(this); NeedParentUpdate(); return; } if (event.Type == UIEVENT_MOUSEMOVE) { { LONG cx = event.ptMouse.x - m_ptLastMouse.x; LONG cy = event.ptMouse.y - m_ptLastMouse.y; m_ptLastMouse = event.ptMouse; RECT rc = m_rcNewPos; rc.left += cx; rc.right += cx; rc.top += cy; rc.bottom += cy; CDuiRect rcInvalidate = m_rcNewPos; m_rcNewPos = rc; rcInvalidate.Join(m_rcNewPos); if (m_pManager) m_pManager->Invalidate(rcInvalidate); return; } } if (event.Type == UIEVENT_SETCURSOR) { if (IsEnabled()) { ::SetCursor(::LoadCursor(NULL, IDC_HAND)); return; } } } CTextUI::DoEvent(event); } void CDragTextUI::DoPostPaint(HDC hDC, const RECT& rcPaint) { int nWidth = GetWidth(); int nHeight = GetHeight(); RECT rcDropPos = m_rcNewPos; RECT rcParent = m_pParent->GetPos(); if (m_rcNewPos.left < rcParent.left) { rcDropPos.left = rcParent.left; rcDropPos.right = rcDropPos.left + nWidth; } if (m_rcNewPos.right > rcParent.right) { rcDropPos.right = rcParent.right; rcDropPos.left = rcDropPos.right - nWidth; } if (m_rcNewPos.top < rcParent.top) { rcDropPos.top = rcParent.top; rcDropPos.bottom = rcDropPos.top + nHeight; } if (m_rcNewPos.bottom > rcParent.bottom) { rcDropPos.bottom = rcParent.bottom; rcDropPos.top = rcDropPos.bottom - nHeight; } CRenderEngine::DrawColor(hDC, rcDropPos, 0xAA000000); m_rcNewPos = rcDropPos; }
21.853211
81
0.680101
EndofDeath
06d9989f42d8e7f9301a9654d13ed390ecb3768c
1,072
cpp
C++
Doom/src/Doom/Components/PointLight.cpp
Shturm0weak/OpenGL_Engine
6e6570f8dd9000724274942fff5a100f0998b780
[ "MIT" ]
126
2020-10-20T21:39:53.000Z
2022-01-25T14:43:44.000Z
Doom/src/Doom/Components/PointLight.cpp
Shturm0weak/2D_OpenGL_Engine
6e6570f8dd9000724274942fff5a100f0998b780
[ "MIT" ]
2
2021-01-07T17:29:19.000Z
2021-08-14T14:04:28.000Z
Doom/src/Doom/Components/PointLight.cpp
Shturm0weak/2D_OpenGL_Engine
6e6570f8dd9000724274942fff5a100f0998b780
[ "MIT" ]
16
2021-01-09T09:08:40.000Z
2022-01-25T14:43:46.000Z
#include "../pch.h" #include "PointLight.h" using namespace Doom; void Doom::PointLight::Copy(const PointLight& rhs) { m_Constant = rhs.m_Constant; m_Linear = rhs.m_Linear; m_Quadratic = rhs.m_Quadratic; m_Color = rhs.m_Color; } void Doom::PointLight::operator=(const PointLight& rhs) { Copy(rhs); } Component* Doom::PointLight::Create() { return new PointLight(); } Doom::PointLight::PointLight(const PointLight& rhs) { Copy(rhs); } Doom::PointLight::PointLight() { std::function<void()>* f = new std::function<void()>([=] { SpriteRenderer* sr = m_OwnerOfCom->GetComponent<SpriteRenderer>(); if (sr == nullptr) sr = m_OwnerOfCom->AddComponent<SpriteRenderer>(); sr->m_DisableRotation = true; sr->m_Texture = Texture::Get("src/UIimages/Lamp.png"); s_PointLights.push_back(this); }); EventSystem::GetInstance().SendEvent(EventType::ONMAINTHREADPROCESS, nullptr, f); } Doom::PointLight::~PointLight() { auto iter = std::find(s_PointLights.begin(), s_PointLights.end(), this); if (iter != s_PointLights.end()) s_PointLights.erase(iter); }
22.333333
82
0.70709
Shturm0weak
06e82ce46e53badcce22a05eec8cc34cfad94f59
579
cpp
C++
quests/dziwne_sumowanie/dziwne_sumowanie/dziwne_sumowanie.cpp
Donkrzawayan/DECODE-IT_pracuj_pl
a09daa973d32d46d9dc8e7dec284821f52a10607
[ "Apache-2.0" ]
1
2021-01-06T22:15:09.000Z
2021-01-06T22:15:09.000Z
quests/dziwne_sumowanie/dziwne_sumowanie/dziwne_sumowanie.cpp
Donkrzawayan/DECODE-IT_pracuj_pl
a09daa973d32d46d9dc8e7dec284821f52a10607
[ "Apache-2.0" ]
null
null
null
quests/dziwne_sumowanie/dziwne_sumowanie/dziwne_sumowanie.cpp
Donkrzawayan/DECODE-IT_pracuj_pl
a09daa973d32d46d9dc8e7dec284821f52a10607
[ "Apache-2.0" ]
null
null
null
// #include <iostream> #include <vector> #include <cstdint> #include <string> void processString() { unsigned n; std::cin >> n; std::cin.get(); //clear input std::vector<uint_fast8_t> str(4 * n); for (unsigned j = 0; j < 4 * n; ++j) str[j] = std::cin.get() - '0'; std::cin.get(); //clear input std::string answer; for (unsigned j = 0; j < 4 * n; j += 4) answer += (str[j] * 10 + str[j + 2]) + (str[j + 1] * 10 + str[j + 3]); std::cout << answer << "\n"; } int main() { unsigned t; std::cin >> t; for (unsigned i = 0; i < t; ++i) processString(); } // 100
18.09375
72
0.542314
Donkrzawayan
06e9f05fba4fd522479cff255bd0739a90440b1d
30,542
cc
C++
lib/memoro/memoro_interceptors.cc
epfl-vlsc/compiler-rt
8d8b3f33c09f637f3fbe406eebf38280e9ee7340
[ "MIT" ]
2
2020-02-04T15:21:22.000Z
2020-02-05T08:20:25.000Z
lib/memoro/memoro_interceptors.cc
epfl-vlsc/compiler-rt
8d8b3f33c09f637f3fbe406eebf38280e9ee7340
[ "MIT" ]
1
2019-11-05T13:08:01.000Z
2019-11-05T13:08:01.000Z
lib/memoro/memoro_interceptors.cc
epfl-vlsc/compiler-rt
8d8b3f33c09f637f3fbe406eebf38280e9ee7340
[ "MIT" ]
null
null
null
//=-- memoro_interceptors.cc ----------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of Memoro. // Stuart Byma, EPFL. // // Interceptors for Memoro. // //===----------------------------------------------------------------------===// #include "memoro_interceptors.h" #include "interception/interception.h" #include "memoro.h" #include "memoro_allocator.h" #include "memoro_flags.h" #include "memoro_thread.h" #include "sanitizer_common/sanitizer_allocator.h" #include "sanitizer_common/sanitizer_allocator_checks.h" #include "sanitizer_common/sanitizer_platform_interceptors.h" #include "sanitizer_common/sanitizer_posix.h" #include "sanitizer_common/sanitizer_tls_get_addr.h" #include <stddef.h> using namespace __memoro; // Fake std::nothrow_t and std::align_val_t to avoid including <new>. namespace std { struct nothrow_t {}; enum class align_val_t: size_t {}; } // namespace std extern "C" { int pthread_attr_init(void *attr); int pthread_attr_destroy(void *attr); // int pthread_attr_getdetachstate(void *attr, int *v); int pthread_key_create(unsigned *key, void (*destructor)(void *v)); int pthread_setspecific(unsigned key, const void *v); } ///// Malloc/free interceptors. ///// namespace std { struct nothrow_t; } DECLARE_REAL_AND_INTERCEPTOR(void *, malloc, uptr) DECLARE_REAL_AND_INTERCEPTOR(void, free, void *) #if !SANITIZER_MAC static uptr allocated_for_dlsym; static const uptr kDlsymAllocPoolSize = 1024 * 1024; static uptr alloc_memory_for_dlsym[kDlsymAllocPoolSize]; static bool IsInDlsymAllocPool(const void *ptr) { uptr off = (uptr)ptr - (uptr)alloc_memory_for_dlsym; return off < sizeof(alloc_memory_for_dlsym); } static void *AllocateFromLocalPool(uptr size_in_bytes) { uptr size_in_words = RoundUpTo(size_in_bytes, kWordSize) / kWordSize; void *mem = (void*)&alloc_memory_for_dlsym[allocated_for_dlsym]; allocated_for_dlsym += size_in_words; CHECK_LT(allocated_for_dlsym, kDlsymAllocPoolSize); return mem; } INTERCEPTOR(void *, malloc, uptr size) { if (UNLIKELY(!memoro_inited)) // Hack: dlsym calls malloc before REAL(malloc) is retrieved from dlsym. return AllocateFromLocalPool(size); ENSURE_MEMORO_INITED(); GET_STACK_TRACE_MALLOC; return memoro_malloc(size, stack); } INTERCEPTOR(void, free, void *p) { if (UNLIKELY(IsInDlsymAllocPool(p))) return; ENSURE_MEMORO_INITED(); memoro_free(p); } INTERCEPTOR(void *, calloc, uptr nmemb, uptr size) { if (UNLIKELY(!memoro_inited)) // Hack: dlsym calls calloc before REAL(calloc) is retrieved from dlsym. return AllocateFromLocalPool(nmemb * size); ENSURE_MEMORO_INITED(); GET_STACK_TRACE_MALLOC; return memoro_calloc(nmemb, size, stack); } INTERCEPTOR(void *, realloc, void *ptr, uptr size) { GET_STACK_TRACE_MALLOC; if (UNLIKELY(IsInDlsymAllocPool(ptr))) { uptr offset = (uptr)ptr - (uptr)alloc_memory_for_dlsym; uptr copy_size = Min(size, kDlsymAllocPoolSize - offset); void *new_ptr = memoro_malloc(size, stack); internal_memcpy(new_ptr, ptr, copy_size); return new_ptr; } ENSURE_MEMORO_INITED(); return memoro_realloc(ptr, size, stack); } INTERCEPTOR(int, posix_memalign, void **memptr, uptr alignment, uptr size) { ENSURE_MEMORO_INITED(); GET_STACK_TRACE_MALLOC; *memptr = memoro_memalign(alignment, size, stack); // FIXME: Return ENOMEM if user requested more than max alloc size. return 0; } INTERCEPTOR(void *, valloc, uptr size) { ENSURE_MEMORO_INITED(); GET_STACK_TRACE_MALLOC; return memoro_valloc(size, stack); } #endif #if SANITIZER_INTERCEPT_MEMALIGN INTERCEPTOR(void *, memalign, uptr alignment, uptr size) { ENSURE_MEMORO_INITED(); GET_STACK_TRACE_MALLOC; return memoro_memalign(alignment, size, stack); } #define MEMORO_MAYBE_INTERCEPT_MEMALIGN INTERCEPT_FUNCTION(memalign) INTERCEPTOR(void *, __libc_memalign, uptr alignment, uptr size) { ENSURE_MEMORO_INITED(); GET_STACK_TRACE_MALLOC; void *res = memoro_memalign(alignment, size, stack); DTLS_on_libc_memalign(res, size); return res; } #define MEMORO_MAYBE_INTERCEPT___LIBC_MEMALIGN \ INTERCEPT_FUNCTION(__libc_memalign) #else #define MEMORO_MAYBE_INTERCEPT_MEMALIGN #define MEMORO_MAYBE_INTERCEPT___LIBC_MEMALIGN #endif // SANITIZER_INTERCEPT_MEMALIGN #if SANITIZER_INTERCEPT_ALIGNED_ALLOC INTERCEPTOR(void *, aligned_alloc, uptr alignment, uptr size) { ENSURE_MEMORO_INITED(); GET_STACK_TRACE_MALLOC; return memoro_memalign(alignment, size, stack); } #define MEMORO_MAYBE_INTERCEPT_ALIGNED_ALLOC INTERCEPT_FUNCTION(aligned_alloc) #else #define MEMORO_MAYBE_INTERCEPT_ALIGNED_ALLOC #endif #if SANITIZER_INTERCEPT_MALLOC_USABLE_SIZE INTERCEPTOR(uptr, malloc_usable_size, void *ptr) { ENSURE_MEMORO_INITED(); return GetMallocUsableSize(ptr); } #define MEMORO_MAYBE_INTERCEPT_MALLOC_USABLE_SIZE \ INTERCEPT_FUNCTION(malloc_usable_size) #else #define MEMORO_MAYBE_INTERCEPT_MALLOC_USABLE_SIZE #endif #if SANITIZER_INTERCEPT_MALLOPT_AND_MALLINFO struct fake_mallinfo { int x[10]; }; INTERCEPTOR(struct fake_mallinfo, mallinfo, void) { struct fake_mallinfo res; internal_memset(&res, 0, sizeof(res)); return res; } #define MEMORO_MAYBE_INTERCEPT_MALLINFO INTERCEPT_FUNCTION(mallinfo) INTERCEPTOR(int, mallopt, int cmd, int value) { return -1; } #define MEMORO_MAYBE_INTERCEPT_MALLOPT INTERCEPT_FUNCTION(mallopt) #else #define MEMORO_MAYBE_INTERCEPT_MALLINFO #define MEMORO_MAYBE_INTERCEPT_MALLOPT #endif // SANITIZER_INTERCEPT_MALLOPT_AND_MALLINFO #if SANITIZER_INTERCEPT_PVALLOC INTERCEPTOR(void *, pvalloc, uptr size) { ENSURE_MEMORO_INITED(); GET_STACK_TRACE_MALLOC; uptr PageSize = GetPageSizeCached(); size = RoundUpTo(size, PageSize); if (size == 0) { // pvalloc(0) should allocate one page. size = PageSize; } return Allocate(stack, size, GetPageSizeCached(), kAlwaysClearMemory); } #define MEMORO_MAYBE_INTERCEPT_PVALLOC INTERCEPT_FUNCTION(pvalloc) #else #define MEMORO_MAYBE_INTERCEPT_PVALLOC #endif // SANITIZER_INTERCEPT_PVALLOC #if SANITIZER_INTERCEPT_CFREE INTERCEPTOR(void, cfree, void *p) ALIAS(WRAPPER_NAME(free)); #define MEMORO_MAYBE_INTERCEPT_CFREE INTERCEPT_FUNCTION(cfree) #else #define MEMORO_MAYBE_INTERCEPT_CFREE #endif // SANITIZER_INTERCEPT_CFREE #define OPERATOR_NEW_BODY \ ENSURE_MEMORO_INITED(); \ GET_STACK_TRACE_MALLOC; \ return Allocate(stack, size, 1, kAlwaysClearMemory); #define OPERATOR_NEW_BODY_ALIGN \ ENSURE_MEMORO_INITED(); \ GET_STACK_TRACE_MALLOC; \ return Allocate(stack, size, (uptr)align, kAlwaysClearMemory); INTERCEPTOR_ATTRIBUTE void *operator new(size_t size) { OPERATOR_NEW_BODY; } INTERCEPTOR_ATTRIBUTE void *operator new[](size_t size) { OPERATOR_NEW_BODY; } INTERCEPTOR_ATTRIBUTE void *operator new(size_t size, std::nothrow_t const &) { OPERATOR_NEW_BODY; } INTERCEPTOR_ATTRIBUTE void *operator new[](size_t size, std::nothrow_t const &) { OPERATOR_NEW_BODY; } INTERCEPTOR_ATTRIBUTE void *operator new(size_t size, std::align_val_t align) { OPERATOR_NEW_BODY_ALIGN; } INTERCEPTOR_ATTRIBUTE void *operator new[](size_t size, std::align_val_t align) { OPERATOR_NEW_BODY_ALIGN; } INTERCEPTOR_ATTRIBUTE void *operator new(size_t size, std::align_val_t align, std::nothrow_t const&) { OPERATOR_NEW_BODY_ALIGN; } INTERCEPTOR_ATTRIBUTE void *operator new[](size_t size, std::align_val_t align, std::nothrow_t const&) { OPERATOR_NEW_BODY_ALIGN; } #define OPERATOR_DELETE_BODY \ ENSURE_MEMORO_INITED(); \ Deallocate(ptr); INTERCEPTOR_ATTRIBUTE void operator delete(void *ptr)NOEXCEPT { OPERATOR_DELETE_BODY; } INTERCEPTOR_ATTRIBUTE void operator delete[](void *ptr) NOEXCEPT { OPERATOR_DELETE_BODY; } INTERCEPTOR_ATTRIBUTE void operator delete(void *ptr, std::nothrow_t const &) { OPERATOR_DELETE_BODY; } INTERCEPTOR_ATTRIBUTE void operator delete[](void *ptr, std::nothrow_t const &) { OPERATOR_DELETE_BODY; } INTERCEPTOR_ATTRIBUTE void operator delete(void *ptr, size_t size) NOEXCEPT { OPERATOR_DELETE_BODY; } INTERCEPTOR_ATTRIBUTE void operator delete[](void *ptr, size_t size) NOEXCEPT { OPERATOR_DELETE_BODY; } INTERCEPTOR_ATTRIBUTE void operator delete(void *ptr, std::align_val_t align) NOEXCEPT { OPERATOR_DELETE_BODY; } INTERCEPTOR_ATTRIBUTE void operator delete[](void *ptr, std::align_val_t align) NOEXCEPT { OPERATOR_DELETE_BODY; } INTERCEPTOR_ATTRIBUTE void operator delete(void *ptr, std::align_val_t align, std::nothrow_t const&) { OPERATOR_DELETE_BODY; } INTERCEPTOR_ATTRIBUTE void operator delete[](void *ptr, std::align_val_t align, std::nothrow_t const&) { OPERATOR_DELETE_BODY; } INTERCEPTOR_ATTRIBUTE void operator delete(void *ptr, size_t size, std::align_val_t align) NOEXCEPT { OPERATOR_DELETE_BODY; } INTERCEPTOR_ATTRIBUTE void operator delete[](void *ptr, size_t size, std::align_val_t align) NOEXCEPT { OPERATOR_DELETE_BODY; } #define MEMORO_READ_RANGE(ctx, offset, size) \ processRangeAccess(GET_CALLER_PC(), (uptr)offset, size, false) #define MEMORO_WRITE_RANGE(ctx, offset, size) \ processRangeAccess(GET_CALLER_PC(), (uptr)offset, size, true) // Behavior of functions like "memcpy" or "strcpy" is undefined // if memory intervals overlap. We report error in this case. // Macro is used to avoid creation of new frames. static inline bool RangesOverlap(const char *offset1, uptr length1, const char *offset2, uptr length2) { return !((offset1 + length1 <= offset2) || (offset2 + length2 <= offset1)); } #define CHECK_RANGES_OVERLAP(name, _offset1, length1, _offset2, length2) \ do { \ const char *offset1 = (const char *)_offset1; \ const char *offset2 = (const char *)_offset2; \ if (RangesOverlap(offset1, length1, offset2, length2)) { \ GET_STACK_TRACE_FATAL; \ Printf("Ranges overlap wtf\n"); \ } \ } while (0) #define MEMORO_MEMCPY_IMPL(ctx, to, from, size) \ do { \ if (UNLIKELY(!memoro_inited)) \ return internal_memcpy(to, from, size); \ if (memoro_init_is_running) { \ return REAL(memcpy)(to, from, size); \ } \ ENSURE_MEMORO_INITED(); \ if (getFlags()->replace_intrin) { \ if (to != from) { \ CHECK_RANGES_OVERLAP("memcpy", to, size, from, size); \ } \ MEMORO_READ_RANGE(ctx, from, size); \ MEMORO_WRITE_RANGE(ctx, to, size); \ } \ return REAL(memcpy)(to, from, size); \ } while (0) // memset is called inside Printf. #define MEMORO_MEMSET_IMPL(ctx, block, c, size) \ do { \ if (UNLIKELY(!memoro_inited)) \ return internal_memset(block, c, size); \ if (memoro_init_is_running) { \ return REAL(memset)(block, c, size); \ } \ ENSURE_MEMORO_INITED(); \ if (getFlags()->replace_intrin) { \ MEMORO_WRITE_RANGE(ctx, block, size); \ } \ return REAL(memset)(block, c, size); \ } while (0) #define MEMORO_MEMMOVE_IMPL(ctx, to, from, size) \ do { \ if (UNLIKELY(!memoro_inited)) \ return internal_memmove(to, from, size); \ ENSURE_MEMORO_INITED(); \ if (getFlags()->replace_intrin) { \ MEMORO_READ_RANGE(ctx, from, size); \ MEMORO_WRITE_RANGE(ctx, to, size); \ } \ return internal_memmove(to, from, size); \ } while (0) void SetThreadName(const char *name) { u32 t = GetCurrentThread(); if (t) memoroThreadRegistry().SetThreadName(t, name); } // should this direct to the main OnExit in memoro_interface.cc? int OnExit() { return 0; } struct MemoroInterceptorContext { const char *interceptor_name; }; #define MEMORO_INTERCEPTOR_ENTER(ctx, func) \ MemoroInterceptorContext _ctx = {#func}; \ ctx = (void *)&_ctx; \ (void)ctx; #define COMMON_INTERCEPT_FUNCTION(name) MEMORO_INTERCEPT_FUNC(name) #define COMMON_INTERCEPT_FUNCTION_VER(name, ver) \ MEMORO_INTERCEPT_FUNC_VER(name, ver) #define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size) \ MEMORO_WRITE_RANGE(ctx, ptr, size) #define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, size) \ MEMORO_READ_RANGE(ctx, ptr, size) #define COMMON_INTERCEPTOR_ENTER(ctx, func, ...) \ MEMORO_INTERCEPTOR_ENTER(ctx, func); \ do { \ if (memoro_init_is_running) \ return REAL(func)(__VA_ARGS__); \ if (SANITIZER_MAC && UNLIKELY(!memoro_inited)) \ return REAL(func)(__VA_ARGS__); \ ENSURE_MEMORO_INITED(); \ } while (false) #define COMMON_INTERCEPTOR_DIR_ACQUIRE(ctx, path) \ do { \ } while (false) #define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \ do { \ } while (false) #define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \ do { \ } while (false) #define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \ do { \ } while (false) #define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) SetThreadName(name) // Should be memoroThreadRegistry().SetThreadNameByUserId(thread, name) // But memoro does not remember UserId's for threads (pthread_t); // and remembers all ever existed threads, so the linear search by UserId // can be slow. #define COMMON_INTERCEPTOR_SET_PTHREAD_NAME(ctx, thread, name) \ do { \ } while (false) #define COMMON_INTERCEPTOR_BLOCK_REAL(name) REAL(name) // Strict init-order checking is dlopen-hostile: // https://github.com/google/sanitizers/issues/178 #define COMMON_INTERCEPTOR_ON_DLOPEN(filename, flag) \ {} #define COMMON_INTERCEPTOR_ON_EXIT(ctx) OnExit() #define COMMON_INTERCEPTOR_LIBRARY_LOADED(filename, handle) \ {} #define COMMON_INTERCEPTOR_LIBRARY_UNLOADED() \ {} #define COMMON_INTERCEPTOR_NOTHING_IS_INITIALIZED (!memoro_inited) #define COMMON_INTERCEPTOR_GET_TLS_RANGE(begin, end) \ if (ThreadContext *t = CurrentThreadContext()) { \ *begin = t->tls_begin(); \ *end = t->tls_end(); \ } else { \ *begin = *end = 0; \ } #define COMMON_INTERCEPTOR_MEMMOVE_IMPL(ctx, to, from, size) \ do { \ MEMORO_INTERCEPTOR_ENTER(ctx, memmove); \ MEMORO_MEMMOVE_IMPL(ctx, to, from, size); \ } while (false) #define COMMON_INTERCEPTOR_MEMCPY_IMPL(ctx, to, from, size) \ do { \ MEMORO_INTERCEPTOR_ENTER(ctx, memcpy); \ MEMORO_MEMCPY_IMPL(ctx, to, from, size); \ } while (false) #define COMMON_INTERCEPTOR_MEMSET_IMPL(ctx, block, c, size) \ do { \ MEMORO_INTERCEPTOR_ENTER(ctx, memset); \ MEMORO_MEMSET_IMPL(ctx, block, c, size); \ } while (false) // realpath interceptor does something weird with wrapped malloc on mac OS #undef SANITIZER_INTERCEPT_REALPATH #undef SANITIZER_INTERCEPT_TLS_GET_ADDR #include "sanitizer_common/sanitizer_common_interceptors.inc" ///// Thread initialization and finalization. ///// static unsigned g_thread_finalize_key; static void thread_finalize(void *v) { uptr iter = (uptr)v; if (iter > 1) { if (pthread_setspecific(g_thread_finalize_key, (void *)(iter - 1))) { Report("LeakSanitizer: failed to set thread key.\n"); Die(); } return; } ThreadFinish(); } struct ThreadParam { void *(*callback)(void *arg); void *param; atomic_uintptr_t tid; }; extern "C" void *__memoro_thread_start_func(void *arg) { ThreadParam *p = (ThreadParam *)arg; void *(*callback)(void *arg) = p->callback; void *param = p->param; // Wait until the last iteration to maximize the chance that we are the last // destructor to run. if (pthread_setspecific(g_thread_finalize_key, (void *)GetPthreadDestructorIterations())) { Report("Memoro: failed to set thread key.\n"); Die(); } u32 tid = 0; while ((tid = (u32)atomic_load(&p->tid, memory_order_acquire)) == 0) internal_sched_yield(); SetCurrentThread(tid); ThreadStart(tid, GetTid()); atomic_store(&p->tid, 0, memory_order_release); return callback(param); } INTERCEPTOR(int, pthread_create, void *th, void *attr, void *(*callback)(void *), void *param) { ENSURE_MEMORO_INITED(); EnsureMainThreadIDIsCorrect(); __sanitizer_pthread_attr_t myattr; if (!attr) { pthread_attr_init(&myattr); attr = &myattr; } AdjustStackSize(attr); int detached = 0; pthread_attr_getdetachstate(attr, &detached); ThreadParam p; p.callback = callback; p.param = param; atomic_store(&p.tid, 0, memory_order_relaxed); int res; { // Ignore all allocations made by pthread_create: thread stack/TLS may be // stored by pthread for future reuse even after thread destruction, and // the linked list it's stored in doesn't even hold valid pointers to the // objects, the latter are calculated by obscure pointer arithmetic. // stuart: for memoro this may be an unneeded relic ScopedInterceptorDisabler disabler; res = REAL(pthread_create)(th, attr, __memoro_thread_start_func, &p); } if (res == 0) { int tid = ThreadCreate(GetCurrentThread(), *(uptr *)th, /*detached == PTHREAD_CREATE_DETACHED*/ false); CHECK_NE(tid, 0); atomic_store(&p.tid, tid, memory_order_release); while (atomic_load(&p.tid, memory_order_acquire) != 0) internal_sched_yield(); } if (attr == &myattr) pthread_attr_destroy(&myattr); return res; } INTERCEPTOR(int, pthread_join, void *th, void **ret) { ENSURE_MEMORO_INITED(); u32 tid = ThreadTid((uptr)th); int res = REAL(pthread_join)(th, ret); if (res == 0) ThreadJoin(tid); return res; } #define MEMORO_READ_STRING_OF_LEN(ctx, s, len, n) \ MEMORO_READ_RANGE((ctx), (s), \ common_flags()->strict_string_checks ? (len) + 1 : (n)) #define MEMORO_READ_STRING(ctx, s, n) \ MEMORO_READ_STRING_OF_LEN((ctx), (s), REAL(strlen)(s), (n)) static inline uptr MaybeRealStrnlen(const char *s, uptr maxlen) { #if SANITIZER_INTERCEPT_STRNLEN if (REAL(strnlen)) { return REAL(strnlen)(s, maxlen); } #endif return internal_strnlen(s, maxlen); } // For both strcat() and strncat() we need to check the validity of |to| // argument irrespective of the |from| length. INTERCEPTOR(char *, strcat, char *to, const char *from) { // NOLINT void *ctx; MEMORO_INTERCEPTOR_ENTER(ctx, strcat); // NOLINT ENSURE_MEMORO_INITED(); if (getFlags()->replace_str) { uptr from_length = REAL(strlen)(from); MEMORO_READ_RANGE(ctx, from, from_length + 1); uptr to_length = REAL(strlen)(to); MEMORO_READ_STRING_OF_LEN(ctx, to, to_length, to_length); MEMORO_WRITE_RANGE(ctx, to + to_length, from_length + 1); // If the copying actually happens, the |from| string should not overlap // with the resulting string starting at |to|, which has a length of // to_length + from_length + 1. if (from_length > 0) { CHECK_RANGES_OVERLAP("strcat", to, from_length + to_length + 1, from, from_length + 1); } } return REAL(strcat)(to, from); // NOLINT } INTERCEPTOR(char *, strncat, char *to, const char *from, uptr size) { void *ctx; MEMORO_INTERCEPTOR_ENTER(ctx, strncat); ENSURE_MEMORO_INITED(); if (getFlags()->replace_str) { uptr from_length = MaybeRealStrnlen(from, size); uptr copy_length = Min(size, from_length + 1); MEMORO_READ_RANGE(ctx, from, copy_length); uptr to_length = REAL(strlen)(to); MEMORO_READ_STRING_OF_LEN(ctx, to, to_length, to_length); MEMORO_WRITE_RANGE(ctx, to + to_length, from_length + 1); if (from_length > 0) { CHECK_RANGES_OVERLAP("strncat", to, to_length + copy_length + 1, from, copy_length); } } return REAL(strncat)(to, from, size); } INTERCEPTOR(char *, strcpy, char *to, const char *from) { // NOLINT void *ctx; MEMORO_INTERCEPTOR_ENTER(ctx, strcpy); // NOLINT #if SANITIZER_MAC if (UNLIKELY(!memoro_inited)) return REAL(strcpy)(to, from); // NOLINT #endif // strcpy is called from malloc_default_purgeable_zone() // in __memoro::ReplaceSystemAlloc() on Mac. if (memoro_init_is_running) { return REAL(strcpy)(to, from); // NOLINT } ENSURE_MEMORO_INITED(); if (getFlags()->replace_str) { uptr from_size = REAL(strlen)(from) + 1; CHECK_RANGES_OVERLAP("strcpy", to, from_size, from, from_size); MEMORO_READ_RANGE(ctx, from, from_size); MEMORO_WRITE_RANGE(ctx, to, from_size); } return REAL(strcpy)(to, from); // NOLINT } INTERCEPTOR(char *, strdup, const char *s) { void *ctx; MEMORO_INTERCEPTOR_ENTER(ctx, strdup); if (UNLIKELY(!memoro_inited)) return internal_strdup(s); ENSURE_MEMORO_INITED(); uptr length = REAL(strlen)(s); if (getFlags()->replace_str) { MEMORO_READ_RANGE(ctx, s, length + 1); } GET_STACK_TRACE_MALLOC; void *new_mem = memoro_malloc(length + 1, stack); MEMORO_WRITE_RANGE(ctx, new_mem, length + 1); REAL(memcpy)(new_mem, s, length + 1); return reinterpret_cast<char *>(new_mem); } #if MEMORO_INTERCEPT___STRDUP INTERCEPTOR(char *, __strdup, const char *s) { void *ctx; MEMORO_INTERCEPTOR_ENTER(ctx, strdup); if (UNLIKELY(!memoro_inited)) return internal_strdup(s); ENSURE_MEMORO_INITED(); uptr length = REAL(strlen)(s); if (getFlags()->replace_str) { MEMORO_READ_RANGE(ctx, s, length + 1); } GET_STACK_TRACE_MALLOC; void *new_mem = memoro_malloc(length + 1, stack); REAL(memcpy)(new_mem, s, length + 1); return reinterpret_cast<char *>(new_mem); } #endif // MEMORO_INTERCEPT___STRDUP INTERCEPTOR(char *, strncpy, char *to, const char *from, uptr size) { void *ctx; MEMORO_INTERCEPTOR_ENTER(ctx, strncpy); ENSURE_MEMORO_INITED(); if (getFlags()->replace_str) { uptr from_size = Min(size, MaybeRealStrnlen(from, size) + 1); CHECK_RANGES_OVERLAP("strncpy", to, from_size, from, from_size); MEMORO_READ_RANGE(ctx, from, from_size); MEMORO_WRITE_RANGE(ctx, to, size); } return REAL(strncpy)(to, from, size); } INTERCEPTOR(long, strtol, const char *nptr, // NOLINT char **endptr, int base) { void *ctx; MEMORO_INTERCEPTOR_ENTER(ctx, strtol); ENSURE_MEMORO_INITED(); if (!getFlags()->replace_str) { return REAL(strtol)(nptr, endptr, base); } char *real_endptr; long result = REAL(strtol)(nptr, &real_endptr, base); // NOLINT StrtolFixAndCheck(ctx, nptr, endptr, real_endptr, base); return result; } INTERCEPTOR(int, atoi, const char *nptr) { void *ctx; MEMORO_INTERCEPTOR_ENTER(ctx, atoi); #if SANITIZER_MAC if (UNLIKELY(!memoro_inited)) return REAL(atoi)(nptr); #endif ENSURE_MEMORO_INITED(); if (!getFlags()->replace_str) { return REAL(atoi)(nptr); } char *real_endptr; // "man atoi" tells that behavior of atoi(nptr) is the same as // strtol(nptr, 0, 10), i.e. it sets errno to ERANGE if the // parsed integer can't be stored in *long* type (even if it's // different from int). So, we just imitate this behavior. int result = REAL(strtol)(nptr, &real_endptr, 10); FixRealStrtolEndptr(nptr, &real_endptr); MEMORO_READ_STRING(ctx, nptr, (real_endptr - nptr) + 1); return result; } INTERCEPTOR(long, atol, const char *nptr) { // NOLINT void *ctx; MEMORO_INTERCEPTOR_ENTER(ctx, atol); #if SANITIZER_MAC if (UNLIKELY(!memoro_inited)) return REAL(atol)(nptr); #endif ENSURE_MEMORO_INITED(); if (!getFlags()->replace_str) { return REAL(atol)(nptr); } char *real_endptr; long result = REAL(strtol)(nptr, &real_endptr, 10); // NOLINT FixRealStrtolEndptr(nptr, &real_endptr); MEMORO_READ_STRING(ctx, nptr, (real_endptr - nptr) + 1); return result; } #if MEMORO_INTERCEPT_ATOLL_AND_STRTOLL INTERCEPTOR(long long, strtoll, const char *nptr, // NOLINT char **endptr, int base) { void *ctx; MEMORO_INTERCEPTOR_ENTER(ctx, strtoll); ENSURE_MEMORO_INITED(); if (!getFlags()->replace_str) { return REAL(strtoll)(nptr, endptr, base); } char *real_endptr; long long result = REAL(strtoll)(nptr, &real_endptr, base); // NOLINT StrtolFixAndCheck(ctx, nptr, endptr, real_endptr, base); return result; } INTERCEPTOR(long long, atoll, const char *nptr) { // NOLINT void *ctx; MEMORO_INTERCEPTOR_ENTER(ctx, atoll); ENSURE_MEMORO_INITED(); if (!getFlags()->replace_str) { return REAL(atoll)(nptr); } char *real_endptr; long long result = REAL(strtoll)(nptr, &real_endptr, 10); // NOLINT FixRealStrtolEndptr(nptr, &real_endptr); MEMORO_READ_STRING(ctx, nptr, (real_endptr - nptr) + 1); return result; } #endif // MEMORO_INTERCEPTA_ATOLL_AND_STRTOLL namespace __memoro { void InitializeInterceptors() { static bool was_called_once; CHECK(!was_called_once); was_called_once = true; InitializeCommonInterceptors(); // Intercept str* functions. MEMORO_INTERCEPT_FUNC(strcat); // NOLINT MEMORO_INTERCEPT_FUNC(strcpy); // NOLINT MEMORO_INTERCEPT_FUNC(wcslen); MEMORO_INTERCEPT_FUNC(strncat); MEMORO_INTERCEPT_FUNC(strncpy); MEMORO_INTERCEPT_FUNC(strdup); #if MEMORO_INTERCEPT___STRDUP MEMORO_INTERCEPT_FUNC(__strdup); #endif #if MEMORO_INTERCEPT_INDEX && MEMORO_USE_ALIAS_ATTRIBUTE_FOR_INDEX MEMORO_INTERCEPT_FUNC(index); #endif MEMORO_INTERCEPT_FUNC(atoi); MEMORO_INTERCEPT_FUNC(atol); MEMORO_INTERCEPT_FUNC(strtol); #if MEMORO_INTERCEPT_ATOLL_AND_STRTOLL MEMORO_INTERCEPT_FUNC(atoll); MEMORO_INTERCEPT_FUNC(strtoll); #endif INTERCEPT_FUNCTION(malloc); INTERCEPT_FUNCTION(free); MEMORO_MAYBE_INTERCEPT_CFREE; INTERCEPT_FUNCTION(calloc); INTERCEPT_FUNCTION(realloc); INTERCEPT_FUNCTION(puts); INTERCEPT_FUNCTION(fread); INTERCEPT_FUNCTION(fwrite); MEMORO_MAYBE_INTERCEPT_MEMALIGN; MEMORO_MAYBE_INTERCEPT___LIBC_MEMALIGN; MEMORO_MAYBE_INTERCEPT_ALIGNED_ALLOC; INTERCEPT_FUNCTION(posix_memalign); INTERCEPT_FUNCTION(valloc); MEMORO_MAYBE_INTERCEPT_PVALLOC; MEMORO_MAYBE_INTERCEPT_MALLOC_USABLE_SIZE; MEMORO_MAYBE_INTERCEPT_MALLINFO; MEMORO_MAYBE_INTERCEPT_MALLOPT; INTERCEPT_FUNCTION(pthread_create); INTERCEPT_FUNCTION(pthread_join); if (pthread_key_create(&g_thread_finalize_key, &thread_finalize)) { Report("Memoro: failed to create thread key.\n"); Die(); } } } // namespace __memoro
37.799505
80
0.611715
epfl-vlsc
06fb1bcc1d69479e99dbdd3a5726c5fd7cecae81
11,905
cpp
C++
src/misc/jfontload.cpp
akmed772/dosvax
878a4187d3a126b93a6ae8f79f28267b83d323e5
[ "MIT" ]
1
2022-03-16T08:50:16.000Z
2022-03-16T08:50:16.000Z
src/misc/jfontload.cpp
akmed772/dosvax
878a4187d3a126b93a6ae8f79f28267b83d323e5
[ "MIT" ]
null
null
null
src/misc/jfontload.cpp
akmed772/dosvax
878a4187d3a126b93a6ae8f79f28267b83d323e5
[ "MIT" ]
null
null
null
/* Copyright (c) 2016-2022 akm All rights reserved. This content is under the MIT License. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "dosbox.h" #include "control.h" #include "support.h" #include "jsupport.h" //#include "jega.h"//for AX //#include "ps55.h"//for PS/55 using namespace std; #define SBCS 0 #define DBCS 1 #define ID_LEN 6 #define NAME_LEN 8 Bit8u jfont_sbcs_19[SBCS19_LEN];//256 * 19( * 8 bit) Bit8u jfont_dbcs_16[DBCS16_LEN];//65536 * 16 * (16 bit) //Bit16u jfont_sbcs_24[SBCS24_LEN];//256 * 24 * (16 bit) Bit8u ps55font_24[DBCS24_LEN];//65536 * 24 * (24 bit) typedef struct { char id[ID_LEN]; char name[NAME_LEN]; unsigned char width; unsigned char height; unsigned char type; } fontx_h; typedef struct { Bit16u start; Bit16u end; } fontxTbl; Bit16u chrtosht(FILE *fp) { Bit16u i, j; i = (Bit8u)getc(fp); j = (Bit8u)getc(fp) << 8; return(i | j); } /* --------------------------------81=====9F---------------E0=====FC-: High byte of SJIS ----------------40=========7E-80===============================FC-: Low byte of SJIS 00=====1E1F=====3B------------------------------------------------: High byte of IBMJ 00=========3839===============================FB------------------: Low byte of IBMJ A B C 2ADC, 2C5F, +5524 --> 8000 2614, 2673, +90EC --> B700 2384, 2613, +906C --> B3F0 0682, 1F7D, +0000 */ //convert Shift JIS code to PS/55 internal char code Bit16u SJIStoIBMJ(Bit16u knj) { //verify code if (knj < 0x8140 || knj > 0xfc4b) return 0xffff; Bitu knj1 = (knj >> 8) & 0xff;// = FCh - 40h //higher code (ah) Bitu knj2 = knj & 0xff;//lower code (al) knj1 -= 0x81; if (knj1 > 0x5E) knj1 -= 0x40; knj2 -= 0x40; if (knj2 > 0x3F) knj2--; knj1 *= 0xBC; knj = knj1 + knj2; knj += 0x100; //shift code out of JIS standard if (knj >= 0x2ADC && knj <= 0x2C5F) knj += 0x5524; else if (knj >= 0x2384 && knj <= 0x2613) knj += 0x906c; else if (knj >= 0x2614 && knj <= 0x2673) knj += 0x90ec; return knj; } //Convert internal char code to Shift JIS code (obsolete) Bit16u IBMJtoSJIS(Bit16u knj) { //verify code if (knj < 0x100) return 0xffff; knj -= 0x100; if (knj <= 0x1f7d) ;//do nothing else if(knj >= 0xb700 && knj <= 0xb75f) { knj -= 0x90ec; } else if (knj >= 0xb3f0 && knj <= 0xb67f) { knj -= 0x906c; } else if (knj >= 0x8000 && knj <= 0x8183) { knj -= 0x5524; } else return 0xffff; Bitu knj1 = knj / 0xBC;// = FCh - 40h //higher code (ah) Bitu knj2 = knj - (knj1 * 0xBC);//lower code (al) //knj1 = knj >> 8;//higher code (ah) knj1 += 0x81; if (knj1 > 0x9F) knj1 += 0x40; knj2 += 0x40; if (knj2 > 0x7E) knj2++; //verify code if (!isKanji1(knj1)) return 0xffff; if (!isKanji2(knj2)) return 0xffff; knj = knj1 << 8; knj |= knj2; return knj; } Bitu getfontx2header(FILE *fp, fontx_h *header) { fread(header->id, ID_LEN, 1, fp); if (strncmp(header->id, "FONTX2", ID_LEN) != 0) { return 1; } fread(header->name, NAME_LEN, 1, fp); header->width = (Bit8u)getc(fp); header->height = (Bit8u)getc(fp); header->type = (Bit8u)getc(fp); return 0; } void readfontxtbl(fontxTbl *table, Bitu size, FILE *fp) { while (size > 0) { table->start = chrtosht(fp); table->end = chrtosht(fp); ++table; --size; } } static Bitu LoadFontxFile(const char * fname) { fontx_h head; fontxTbl *table; Bit8u buf; Bitu code; Bit8u size; Bitu font; Bitu ibmcode; if (!fname) return 127; if(*fname=='\0') return 127; FILE * mfile=fopen(fname,"rb"); if (!mfile) { LOG_MSG("MSG: Can't open FONTX2 file: %s",fname); return 127; } if (getfontx2header(mfile, &head) != 0) { fclose(mfile); LOG_MSG("MSG: FONTX2 header is incorrect\n"); return 1; } // switch whether the font is DBCS or not if (head.type == DBCS) { if (head.width == 16 && head.height == 16) {//for JEGA (AX) size = getc(mfile); table = (fontxTbl *)calloc(size, sizeof(fontxTbl)); readfontxtbl(table, size, mfile); for (Bitu i = 0; i < size; i++) for (code = table[i].start; code <= table[i].end; code++) fread(&jfont_dbcs_16[(code * 32)], sizeof(Bit8u), 32, mfile); } else if (head.width == 24 && head.height == 24) {//for PS/55 size = getc(mfile); table = (fontxTbl *)calloc(size, sizeof(fontxTbl)); readfontxtbl(table, size, mfile); for (Bitu i = 0; i < size; i++) for (code = table[i].start; code <= table[i].end; code++) { ibmcode = SJIStoIBMJ(code); if (ibmcode >= 0x8000 && ibmcode <= 0x8183)//IBM extensions ibmcode -= 0x6000; if (ibmcode > DBCS24_CHARS) {//address is out of memory LOG_MSG("MSG: FONTX2 DBCS code point %X may be wrong\n", code); continue; } fread(&ps55font_24[(ibmcode * 72)], sizeof(Bit8u), 72, mfile); } } else { fclose(mfile); LOG_MSG("MSG: FONTX2 DBCS font size is not correct\n"); return 4; } } else { if (head.width == 8 && head.height == 19) { fread(jfont_sbcs_19, sizeof(Bit8u), SBCS19_LEN, mfile); } else if (head.width == 12 && head.height == 24) { //fread(jfont_sbcs_24, sizeof(Bit16u), SBCS24_LEN, mfile); //fread(&jfont_dbcs_24[72 * 0x2780], sizeof(Bit8u), SBCS24_LEN, mfile); for (Bitu i = 0; i < SBCS24_CHARS; i++) { ps55font_24[0x98000 + i * 64] = 0; ps55font_24[0x98000 + i * 64 + 1] = 0; ps55font_24[0x98000 + i * 64 + 2] = 0; ps55font_24[0x98000 + i * 64 + 3] = 0; ps55font_24[0x98000 + i * 64 + 52] = 0; ps55font_24[0x98000 + i * 64 + 53] = 0; ps55font_24[0x98000 + i * 64 + 54] = 0; ps55font_24[0x98000 + i * 64 + 55] = 0; ps55font_24[0x98000 + i * 64 + 56] = 0; ps55font_24[0x98000 + i * 64 + 57] = 0; for (Bitu line = 2 + 0; line < 2 + 24; line++) { fread(&buf, sizeof(Bit8u), 1, mfile); font = buf << 8; fread(&buf, sizeof(Bit8u), 1, mfile); font |= buf; font >> 1; ps55font_24[0x98000 + i * 64 + line * 2 + 1] = font & 0xff; ps55font_24[0x98000 + i * 64 + line * 2] = (font >> 8) & 0xff; } } } else { fclose(mfile); LOG_MSG("MSG: FONTX2 SBCS font size is not correct\n"); return 4; } } fclose(mfile); return 0; } /* Font specification BF800h 24 x 24 Font data 120 (78h) bytes FF FF FF F8 xxxx xxxx, xxxx xxxx, xxxx xxxx, xxxx x000 width 29 pixels ? height 30 pixels ? footer? 8 (8h) bytes 00 00 00 00 20 07 20 00 $JPNHZ24.FNT 12 x 24 Font data 48 bytes FF F, F FF $SYSHN24.FNT 13 x 30 Font data 60 (3Ch) bytes FF F8 xxxx xxxx, xxxx x000 width 13 pixels height 30 pixels ? need to exclude 0x81-90, 0xE0-FC */ //Font Loader for $JPNHN24.FNT included in DOS/V static Bitu LoadDOSVHNFontFile(const char* fname) { Bit8u buf; Bitu code = 0; Bit8u size; Bitu font; Bitu fsize; if (!fname) return 127; if (*fname == '\0') return 127; FILE* mfile = fopen(fname, "rb"); if (!mfile) { LOG_MSG("MSG: Can't open IBM font file: %s", fname); return 127; } fseek(mfile, 0, SEEK_END); fsize = ftell(mfile);//get filesize fseek(mfile, 0, SEEK_SET); if (fsize != 12288) { //LOG_MSG("The size of font file is incorrect \n"); fclose(mfile); return 1; } Bitu j = 0; while (ftell(mfile) < fsize) { fread(&buf, sizeof(Bit8u), 1, mfile); font = buf << 7; fread(&buf, sizeof(Bit8u), 1, mfile); font |= (buf & 0xf0) >> 1; ps55font_24[0x98000 + code * 64] = 0; ps55font_24[0x98000 + code * 64 + 1] = 0; ps55font_24[0x98000 + code * 64 + 2] = 0; ps55font_24[0x98000 + code * 64 + 3] = 0; ps55font_24[0x98000 + code * 64 + 52] = 0; ps55font_24[0x98000 + code * 64 + 53] = 0; ps55font_24[0x98000 + code * 64 + 54] = 0; ps55font_24[0x98000 + code * 64 + 55] = 0; ps55font_24[0x98000 + code * 64 + 56] = 0; ps55font_24[0x98000 + code * 64 + 57] = 0; ps55font_24[0x98000 + code * 64 + j + 4] = font >> 8;//a b j++; ps55font_24[0x98000 + code * 64 + j + 4] = font & 0xff;//a b j++; font = (buf & 0x0f) << 11; fread(&buf, sizeof(Bit8u), 1, mfile); font |= buf << 3; ps55font_24[0x98000 + code * 64 + j + 4] = font >> 8;//a b j++; ps55font_24[0x98000 + code * 64 + j + 4] = font & 0xff;//a b j++; if (j >= 48) { code++; j = 0; } } return 0; } //Font Loader for $SYSHN24.FNT included in DOS K3.3 static Bitu LoadIBMHN24Font(const char* fname) { Bit8u buf; Bitu code = 0; Bitu fsize; if (!fname) return 127; if (*fname == '\0') return 127; FILE* mfile = fopen(fname, "rb"); if (!mfile) { LOG_MSG("MSG: Can't open IBM font file: %s", fname); return 127; } fseek(mfile, 0, SEEK_END); fsize = ftell(mfile);//get filesize fseek(mfile, 0, SEEK_SET); if (fsize != 11760) { //LOG_MSG("The size of font file is incorrect \n"); fclose(mfile); return 1; } Bitu j = 0; while (ftell(mfile) < fsize) { if (isKanji1(code)) { code++; continue; } fread(&buf, sizeof(Bit8u), 1, mfile); ps55font_24[0x98000 + code * 64 + j] = buf;//a b j++; if (j >= 60) { code++; j = 0; } } return 0; } //Font Loader for $SYSEX24.FNT included in DOS K3.3 static Bitu LoadIBMEX24Font(const char* fname) { Bit8u buf; Bitu code = 0; Bitu fsize; if (!fname) return 127; if (*fname == '\0') return 127; FILE* mfile = fopen(fname, "rb"); if (!mfile) { LOG_MSG("MSG: Can't open IBM font file: %s", fname); return 127; } fseek(mfile, 0, SEEK_END); fsize = ftell(mfile);//get filesize fseek(mfile, 0, SEEK_SET); if (fsize != 15360) { //LOG_MSG("The size of font file is incorrect \n"); fclose(mfile); return 1; } Bitu j = 0; while (ftell(mfile) < fsize) { fread(&buf, sizeof(Bit8u), 1, mfile); ps55font_24[0xb0000 + code * 64 + j] = buf;//a b j++; if (j >= 60) { code++; j = 0; } } return 0; } static void LoadAnyFontFile(const char* fname) { if (LoadFontxFile(fname) != 1) return; if (LoadDOSVHNFontFile(fname) != 1) return; if (LoadIBMHN24Font(fname) != 1) return; if (LoadIBMEX24Font(fname) != 1) return; LOG_MSG("MSG: The font file is incorrect or broken.\n"); } //#define TESLENG 64 void JFONT_Init(Section_prop * section) { std::string file_name; Prop_path* pathprop = section->Get_path("jfontsbcs"); //initialize memory array memset(jfont_sbcs_19, 0xff, SBCS19_LEN); memset(jfont_dbcs_16, 0xff, DBCS16_LEN); memset(ps55font_24, 0xff, DBCS24_LEN); //for (int i = 0; i < DBCS24_LEN / TESLENG; i++) {//for test // jfont_dbcs_24[i * TESLENG + 2] = i & 0xff; // jfont_dbcs_24[i * TESLENG + 4] = (i >> 8) & 0xff; // jfont_dbcs_24[i * TESLENG + 6] = (i >> 16) & 0xff; // jfont_dbcs_24[i * TESLENG + 8] = (i >> 24) & 0xff; // jfont_dbcs_24[i * TESLENG + 10] = 0xaa;//1010 1010 // jfont_dbcs_24[i * TESLENG + 12] = 0xcc;//1100 1100 // jfont_dbcs_24[i * TESLENG + 14] = 0xf0;//1111 0000 //} if (pathprop) LoadFontxFile(pathprop->realpath.c_str()); else LOG_MSG("MSG: SBCS font file path is not specified.\n"); pathprop = section->Get_path("jfontdbcs"); if(pathprop) LoadFontxFile(pathprop->realpath.c_str()); else LOG_MSG("MSG: DBCS font file path is not specified.\n"); pathprop = section->Get_path("jfont24sbcs"); if (pathprop) LoadAnyFontFile(pathprop->realpath.c_str()); else LOG_MSG("MSG: SBCS24 font file path is not specified.\n"); pathprop = section->Get_path("jfont24dbcs"); if (pathprop) LoadFontxFile(pathprop->realpath.c_str()); else LOG_MSG("MSG: DBCS24 font file path is not specified.\n"); pathprop = section->Get_path("jfont24sbex"); if (pathprop) LoadAnyFontFile(pathprop->realpath.c_str()); //else LOG_MSG("MSG: SBEX24 font file path is not specified.\n"); }
27.880562
86
0.584292
akmed772
06fb99b73c5854ff64505f1495ea8d32e2bf8cd1
101
cc
C++
.ccls-cache/@Users@clp@id@idl/lg@src@main.cc
clpi/idx
fe86a22e090685d55774101dff132407f593fd9e
[ "MIT" ]
null
null
null
.ccls-cache/@Users@clp@id@idl/lg@src@main.cc
clpi/idx
fe86a22e090685d55774101dff132407f593fd9e
[ "MIT" ]
null
null
null
.ccls-cache/@Users@clp@id@idl/lg@src@main.cc
clpi/idx
fe86a22e090685d55774101dff132407f593fd9e
[ "MIT" ]
null
null
null
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <ncurses.h> class Lexer { };
9.181818
20
0.653465
clpi
06fddfe7aa3897e8a65c6843c54556b0e41eed4c
6,108
cpp
C++
src/flow_table/tests/flow_table_test.cpp
AlexandrePieroux/DNFC
53756f5ec98409357407d4730dca2344ffb256d3
[ "MIT" ]
2
2017-04-25T23:48:01.000Z
2017-06-12T14:20:41.000Z
src/flow_table/tests/flow_table_test.cpp
AlexandrePieroux/DNFC
53756f5ec98409357407d4730dca2344ffb256d3
[ "MIT" ]
null
null
null
src/flow_table/tests/flow_table_test.cpp
AlexandrePieroux/DNFC
53756f5ec98409357407d4730dca2344ffb256d3
[ "MIT" ]
null
null
null
#define _BSD_SOURCE #include <stdio.h> #include <stdlib.h> extern "C" { #include "../flow_table.h" #include "../../memory_management/memory_management.h" } #include <gtest/gtest.h> #include <boost/bind.hpp> #include <boost/asio.hpp> #define NB_NUMBERS 1000000 #define NB_THREADS 64 #define HEADER_LENGTH 16 #define HEADER_BIT_L 320 struct arguments_t { u_char** numbers; uint32_t* index; uint32_t size; hash_table** table; }; uint32_t *get_random_numbers(uint32_t min, uint32_t max); void* job_insert(void* args); void* job_get(void* args); void* job_remove(void* args); void init(arguments_t*** args); TEST (FlowTable, Insert) { arguments_t** args; threadpool_t* pool = new_threadpool(NB_THREADS); init(&args); for (uint32_t i = 0; i < NB_THREADS; ++i) threadpool_add_work(pool, job_insert, args[i]); threadpool_wait(pool); free_threadpool(pool); hash_table_free(args[0]->table); } TEST (FlowTable, Get) { arguments_t** args; threadpool_t* pool = new_threadpool(NB_THREADS); init(&args); for (uint32_t i = 0; i < NB_NUMBERS; ++i) put_flow(*(*args)->table, (*args)->numbers[i], &(*args)->numbers[i]); for (uint32_t i = 0; i < NB_THREADS; ++i) threadpool_add_work(pool, job_get, args[i]); threadpool_wait(pool); free_threadpool(pool); hash_table_free(args[0]->table); } TEST (FlowTable, Remove) { arguments_t** args; threadpool_t* pool = new_threadpool(NB_THREADS); init(&args); for (uint32_t i = 0; i < NB_NUMBERS; ++i) put_flow(*(*args)->table, (*args)->numbers[i], &(*args)->numbers[i]); for (uint32_t i = 0; i < NB_THREADS; ++i) threadpool_add_work(pool, job_remove, args[i]); threadpool_wait(pool); free_threadpool(pool); hash_table_free(args[0]->table); } int main(int argc, char **argv) { srand(time(NULL)); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } uint32_t *get_random_numbers(uint32_t min, uint32_t max) { uint32_t size = max - min; uint32_t *result = new uint32_t[size]; bool is_used[max]; for (uint32_t i = 0; i < size; i++) { is_used[i] = false; } uint32_t im = 0; for (uint32_t in = min; in < max && im < size; ++in) { uint32_t r = rand() % (in + 1); /* generate a random number 'r' */ if (is_used[r]) /* we already have 'r' */ r = in; /* use 'in' instead of the generated number */ result[im++] = r + min; is_used[r] = true; } return result; } void init(arguments_t*** args) { // Get random unique flows uint32_t* source_address = get_random_numbers(0, NB_NUMBERS); uint32_t* destination_address = get_random_numbers(NB_NUMBERS, (NB_NUMBERS * 2)); uint32_t* source_port = get_random_numbers(0, 65535); uint32_t* destination_port = get_random_numbers(0, 65535); u_char** keys = new u_char*[NB_NUMBERS]; uint32_t j = 0; uint32_t* nb = new uint32_t; uint8_t zero = 0; uint8_t ihl = 5; uint8_t version = 4; uint8_t TCP_p = 6; u_short eth_type = 2048; for(uint32_t i = 0; i < NB_NUMBERS; i++){ key_type tmp = new_byte_stream(); // Ethernet type for(uint32_t j = 0; j < 12; j++) append_bytes(tmp, &zero, 1); append_bytes(tmp, &eth_type, 2); // IHL IPv4 field append_bytes(tmp, &ihl, 1); // Version IPv4 field append_bytes(tmp, &version, 1); // Put the offset of port (9 bytes) for(uint32_t j = 0; j < 7; j++) append_bytes(tmp, &zero, 1); // Put the TCP protocol number append_bytes(tmp, &TCP_p, 1); // Put the offset of the addresses (2 bytes) for(uint32_t j = 0; j < 2; j++) append_bytes(tmp, &zero, 1); // Put the source address *nb = source_address[i]; append_bytes(tmp, nb, 4); // Put the destination address *nb = destination_address[i]; append_bytes(tmp, nb, 4); // Put the offset of the source ports (16 bytes) for(uint32_t j = 0; j < 16; j++) append_bytes(tmp, &zero, 1); // Put the source port *nb = source_port[(i % 65536)]; append_bytes(tmp, nb, 2); // Put the destination port *nb = destination_port[(i % 65536)]; append_bytes(tmp, nb, 2); // Get the uint8_t array that form the header keys[j++] = tmp->stream; } // Preparing the structure *args = new arguments_t*[NB_THREADS]; hash_table** table = new hash_table*; *table = new_hash_table(FNV_1, NB_THREADS); // We distribute the work per threads uint32_t divider = NB_NUMBERS / NB_THREADS; uint32_t remain = NB_NUMBERS % NB_THREADS; uint32_t* indexes = new uint32_t[NB_NUMBERS]; for (uint32_t i = 0; i < NB_NUMBERS; i++) indexes[i] = i; for (uint32_t p = 0; p < NB_THREADS; ++p) { (*args)[p] = new arguments_t; (*args)[p]->numbers = &keys[p * divider]; (*args)[p]->index = &(indexes[p * divider]); if(p != (NB_THREADS - 1)) (*args)[p]->size = divider; else (*args)[p]->size = divider + remain; (*args)[p]->table = table; } } void* job_insert(void* args) { arguments_t* args_cast = (arguments_t*)args; for (uint32_t i = 0; i < args_cast->size; ++i){ bool result = put_flow(*args_cast->table, args_cast->numbers[i], &args_cast->numbers[i]); EXPECT_TRUE(result); } return NULL; } void* job_get(void* args) { arguments_t* args_cast = (arguments_t*)args; for (uint32_t i = 0; i < args_cast->size; ++i){ if (args_cast->numbers[i]) EXPECT_EQ(get_flow(*args_cast->table, args_cast->numbers[i]), &args_cast->numbers[i]); } return NULL; } void* job_remove(void* args) { arguments_t* args_cast = (arguments_t*)args; for(uint32_t i = 0; i < args_cast->size; ++i){ bool result = remove_flow(*args_cast->table, args_cast->numbers[i]); EXPECT_TRUE(result); } return NULL; }
24.728745
95
0.599869
AlexandrePieroux
660445d356b337943caa6087fe5f1ef00456eb71
19,468
cpp
C++
src/graphics/VoxelRenderer.cpp
Retro52/Minecraft-Clone
6417ad7f77978d71f90bb6db20e518ad467a3c83
[ "Unlicense" ]
null
null
null
src/graphics/VoxelRenderer.cpp
Retro52/Minecraft-Clone
6417ad7f77978d71f90bb6db20e518ad467a3c83
[ "Unlicense" ]
null
null
null
src/graphics/VoxelRenderer.cpp
Retro52/Minecraft-Clone
6417ad7f77978d71f90bb6db20e518ad467a3c83
[ "Unlicense" ]
null
null
null
#include "VoxelRenderer.h" #include "mesh.h" #include "../voxels/voxel.h" #include "../voxels/Block.h" #include "../lighting/Lightmap.h" #define VERTEX_SIZE (3 + 2 + 4) #define CDIV(X,A) (((X) < 0) ? ((X) / (A) - 1) : ((X) / (A))) #define LOCAL_NEG(X, SIZE) (((X) < 0) ? ((SIZE)+(X)) : (X)) #define LOCAL(X, SIZE) ((X) >= (SIZE) ? ((X) - (SIZE)) : LOCAL_NEG(X, SIZE)) #define IS_CHUNK(X,Y,Z) (GET_CHUNK(X,Y,Z) != nullptr) #define GET_CHUNK(X,Y,Z) (chunks[((CDIV(Y, CHUNK_H)+1) * 3 + CDIV(Z, CHUNK_D) + 1) * 3 + CDIV(X, CHUNK_W) + 1]) #define LIGHT(X,Y,Z, CHANNEL) (IS_CHUNK(X,Y,Z) ? GET_CHUNK(X,Y,Z)->lightmap->get(LOCAL(X, CHUNK_W), LOCAL(Y, CHUNK_H), LOCAL(Z, CHUNK_D), (CHANNEL)) : 0) #define VOXEL(X,Y,Z) (GET_CHUNK(X,Y,Z)->voxels[(LOCAL(Y, CHUNK_H) * CHUNK_D + LOCAL(Z, CHUNK_D)) * CHUNK_W + LOCAL(X, CHUNK_W)]) #define IS_BLOCKED(X,Y,Z,GROUP) ((!IS_CHUNK(X, Y, Z)) || Block::blocks[VOXEL(X, Y, Z).id]->drawGroup == (GROUP)) #define VERTEX(INDEX, X,Y,Z, U,V, R,G,B,S) buffer[INDEX+0] = (X);\ buffer[INDEX+1] = (Y);\ buffer[INDEX+2] = (Z);\ buffer[INDEX+3] = (U);\ buffer[INDEX+4] = (V);\ buffer[INDEX+5] = (R);\ buffer[INDEX+6] = (G);\ buffer[INDEX+7] = (B);\ buffer[INDEX+8] = (S);\ INDEX += VERTEX_SIZE; #define SETUP_UV(INDEX) float u1 = ((INDEX) % 32) * uvsize;\ float v1 = 1-((1 + (INDEX) / 32) * uvsize);\ float u2 = u1 + uvsize;\ float v2 = v1 + uvsize; int chunk_attrs[] = {3,2,4, 0}; VoxelRenderer::VoxelRenderer(size_t capacity) : capacity(capacity) { buffer = new float[capacity * VERTEX_SIZE * 6]; } VoxelRenderer::~VoxelRenderer(){ delete[] buffer; } Mesh* VoxelRenderer::render(Chunk* chunk, const Chunk** chunks) { size_t index = 0; for (int y = 0; y < CHUNK_H; y++) { for (int z = 0; z < CHUNK_D; z++) { for (int x = 0; x < CHUNK_W; x++) { voxel vox = chunk->voxels[(y * CHUNK_D + z) * CHUNK_W + x]; unsigned int id = vox.id; if (!id) { continue; } float l; float uvsize = 1.0f/32.0f; Block* block = Block::blocks[id]; unsigned char group = block->drawGroup; if (!IS_BLOCKED(x,y+1,z,group)) { l = 1.0f; SETUP_UV(block->textureFaces[3]); float lr = LIGHT(x,y+1,z, 0) / 15.0f; float lg = LIGHT(x,y+1,z, 1) / 15.0f; float lb = LIGHT(x,y+1,z, 2) / 15.0f; float ls = LIGHT(x,y+1,z, 3) / 15.0f; float lr0 = (LIGHT(x-1,y+1,z,0) + lr*30 + LIGHT(x-1,y+1,z-1,0) + LIGHT(x,y+1,z-1,0)) / 5.0f / 15.0f; float lr1 = (LIGHT(x-1,y+1,z,0) + lr*30 + LIGHT(x-1,y+1,z+1,0) + LIGHT(x,y+1,z+1,0)) / 5.0f / 15.0f; float lr2 = (LIGHT(x+1,y+1,z,0) + lr*30 + LIGHT(x+1,y+1,z+1,0) + LIGHT(x,y+1,z+1,0)) / 5.0f / 15.0f; float lr3 = (LIGHT(x+1,y+1,z,0) + lr*30 + LIGHT(x+1,y+1,z-1,0) + LIGHT(x,y+1,z-1,0)) / 5.0f / 15.0f; float lg0 = (LIGHT(x-1,y+1,z,1) + lg*30 + LIGHT(x-1,y+1,z-1,1) + LIGHT(x,y+1,z-1,1)) / 5.0f / 15.0f; float lg1 = (LIGHT(x-1,y+1,z,1) + lg*30 + LIGHT(x-1,y+1,z+1,1) + LIGHT(x,y+1,z+1,1)) / 5.0f / 15.0f; float lg2 = (LIGHT(x+1,y+1,z,1) + lg*30 + LIGHT(x+1,y+1,z+1,1) + LIGHT(x,y+1,z+1,1)) / 5.0f / 15.0f; float lg3 = (LIGHT(x+1,y+1,z,1) + lg*30 + LIGHT(x+1,y+1,z-1,1) + LIGHT(x,y+1,z-1,1)) / 5.0f / 15.0f; float lb0 = (LIGHT(x-1,y+1,z,2) + lb*30 + LIGHT(x-1,y+1,z-1,2) + LIGHT(x,y+1,z-1,2)) / 5.0f / 15.0f; float lb1 = (LIGHT(x-1,y+1,z,2) + lb*30 + LIGHT(x-1,y+1,z+1,2) + LIGHT(x,y+1,z+1,2)) / 5.0f / 15.0f; float lb2 = (LIGHT(x+1,y+1,z,2) + lb*30 + LIGHT(x+1,y+1,z+1,2) + LIGHT(x,y+1,z+1,2)) / 5.0f / 15.0f; float lb3 = (LIGHT(x+1,y+1,z,2) + lb*30 + LIGHT(x+1,y+1,z-1,2) + LIGHT(x,y+1,z-1,2)) / 5.0f / 15.0f; float ls0 = (LIGHT(x-1,y+1,z,3) + ls*30 + LIGHT(x-1,y+1,z-1,3) + LIGHT(x,y+1,z-1,3)) / 5.0f / 15.0f; float ls1 = (LIGHT(x-1,y+1,z,3) + ls*30 + LIGHT(x-1,y+1,z+1,3) + LIGHT(x,y+1,z+1,3)) / 5.0f / 15.0f; float ls2 = (LIGHT(x+1,y+1,z,3) + ls*30 + LIGHT(x+1,y+1,z+1,3) + LIGHT(x,y+1,z+1,3)) / 5.0f / 15.0f; float ls3 = (LIGHT(x+1,y+1,z,3) + ls*30 + LIGHT(x+1,y+1,z-1,3) + LIGHT(x,y+1,z-1,3)) / 5.0f / 15.0f; VERTEX(index, x-0.5f, y+0.5f, z-0.5f, u2,v1, lr0, lg0, lb0, ls0); VERTEX(index, x-0.5f, y+0.5f, z+0.5f, u2,v2, lr1, lg1, lb1, ls1); VERTEX(index, x+0.5f, y+0.5f, z+0.5f, u1,v2, lr2, lg2, lb2, ls2); VERTEX(index, x-0.5f, y+0.5f, z-0.5f, u2,v1, lr0, lg0, lb0, ls0); VERTEX(index, x+0.5f, y+0.5f, z+0.5f, u1,v2, lr2, lg2, lb2, ls2); VERTEX(index, x+0.5f, y+0.5f, z-0.5f, u1,v1, lr3, lg3, lb3, ls3); } if (!IS_BLOCKED(x,y-1,z,group)){ l = 0.75f; SETUP_UV(block->textureFaces[2]); float lr = LIGHT(x,y-1,z, 0) / 15.0f; float lg = LIGHT(x,y-1,z, 1) / 15.0f; float lb = LIGHT(x,y-1,z, 2) / 15.0f; float ls = LIGHT(x,y-1,z, 3) / 15.0f; float lr0 = (LIGHT(x-1,y-1,z-1,0) + lr*30 + LIGHT(x-1,y-1,z,0) + LIGHT(x,y-1,z-1,0)) / 5.0f / 15.0f; float lr1 = (LIGHT(x+1,y-1,z+1,0) + lr*30 + LIGHT(x+1,y-1,z,0) + LIGHT(x,y-1,z+1,0)) / 5.0f / 15.0f; float lr2 = (LIGHT(x-1,y-1,z+1,0) + lr*30 + LIGHT(x-1,y-1,z,0) + LIGHT(x,y-1,z+1,0)) / 5.0f / 15.0f; float lr3 = (LIGHT(x+1,y-1,z-1,0) + lr*30 + LIGHT(x+1,y-1,z,0) + LIGHT(x,y-1,z-1,0)) / 5.0f / 15.0f; float lg0 = (LIGHT(x-1,y-1,z-1,1) + lg*30 + LIGHT(x-1,y-1,z,1) + LIGHT(x,y-1,z-1,1)) / 5.0f / 15.0f; float lg1 = (LIGHT(x+1,y-1,z+1,1) + lg*30 + LIGHT(x+1,y-1,z,1) + LIGHT(x,y-1,z+1,1)) / 5.0f / 15.0f; float lg2 = (LIGHT(x-1,y-1,z+1,1) + lg*30 + LIGHT(x-1,y-1,z,1) + LIGHT(x,y-1,z+1,1)) / 5.0f / 15.0f; float lg3 = (LIGHT(x+1,y-1,z-1,1) + lg*30 + LIGHT(x+1,y-1,z,1) + LIGHT(x,y-1,z-1,1)) / 5.0f / 15.0f; float lb0 = (LIGHT(x-1,y-1,z-1,2) + lb*30 + LIGHT(x-1,y-1,z,2) + LIGHT(x,y-1,z-1,2)) / 5.0f / 15.0f; float lb1 = (LIGHT(x+1,y-1,z+1,2) + lb*30 + LIGHT(x+1,y-1,z,2) + LIGHT(x,y-1,z+1,2)) / 5.0f / 15.0f; float lb2 = (LIGHT(x-1,y-1,z+1,2) + lb*30 + LIGHT(x-1,y-1,z,2) + LIGHT(x,y-1,z+1,2)) / 5.0f / 15.0f; float lb3 = (LIGHT(x+1,y-1,z-1,2) + lb*30 + LIGHT(x+1,y-1,z,2) + LIGHT(x,y-1,z-1,2)) / 5.0f / 15.0f; float ls0 = (LIGHT(x-1,y-1,z-1,3) + ls*30 + LIGHT(x-1,y-1,z,3) + LIGHT(x,y-1,z-1,3)) / 5.0f / 15.0f; float ls1 = (LIGHT(x+1,y-1,z+1,3) + ls*30 + LIGHT(x+1,y-1,z,3) + LIGHT(x,y-1,z+1,3)) / 5.0f / 15.0f; float ls2 = (LIGHT(x-1,y-1,z+1,3) + ls*30 + LIGHT(x-1,y-1,z,3) + LIGHT(x,y-1,z+1,3)) / 5.0f / 15.0f; float ls3 = (LIGHT(x+1,y-1,z-1,3) + ls*30 + LIGHT(x+1,y-1,z,3) + LIGHT(x,y-1,z-1,3)) / 5.0f / 15.0f; VERTEX(index, x-0.5f, y-0.5f, z-0.5f, u1,v1, lr0,lg0,lb0,ls0); VERTEX(index, x+0.5f, y-0.5f, z+0.5f, u2,v2, lr1,lg1,lb1,ls1); VERTEX(index, x-0.5f, y-0.5f, z+0.5f, u1,v2, lr2,lg2,lb2,ls2); VERTEX(index, x-0.5f, y-0.5f, z-0.5f, u1,v1, lr0,lg0,lb0,ls0); VERTEX(index, x+0.5f, y-0.5f, z-0.5f, u2,v1, lr3,lg3,lb3,ls3); VERTEX(index, x+0.5f, y-0.5f, z+0.5f, u2,v2, lr1,lg1,lb1,ls1); } if (!IS_BLOCKED(x+1,y,z,group)){ l = 0.95f; SETUP_UV(block->textureFaces[1]); float lr = LIGHT(x+1,y,z, 0) / 15.0f; float lg = LIGHT(x+1,y,z, 1) / 15.0f; float lb = LIGHT(x+1,y,z, 2) / 15.0f; float ls = LIGHT(x+1,y,z, 3) / 15.0f; float lr0 = (LIGHT(x+1,y-1,z-1,0) + lr*30 + LIGHT(x+1,y,z-1,0) + LIGHT(x+1,y-1,z,0)) / 5.0f / 15.0f; float lr1 = (LIGHT(x+1,y+1,z-1,0) + lr*30 + LIGHT(x+1,y,z-1,0) + LIGHT(x+1,y+1,z,0)) / 5.0f / 15.0f; float lr2 = (LIGHT(x+1,y+1,z+1,0) + lr*30 + LIGHT(x+1,y,z+1,0) + LIGHT(x+1,y+1,z,0)) / 5.0f / 15.0f; float lr3 = (LIGHT(x+1,y-1,z+1,0) + lr*30 + LIGHT(x+1,y,z+1,0) + LIGHT(x+1,y-1,z,0)) / 5.0f / 15.0f; float lg0 = (LIGHT(x+1,y-1,z-1,1) + lg*30 + LIGHT(x+1,y,z-1,1) + LIGHT(x+1,y-1,z,1)) / 5.0f / 15.0f; float lg1 = (LIGHT(x+1,y+1,z-1,1) + lg*30 + LIGHT(x+1,y,z-1,1) + LIGHT(x+1,y+1,z,1)) / 5.0f / 15.0f; float lg2 = (LIGHT(x+1,y+1,z+1,1) + lg*30 + LIGHT(x+1,y,z+1,1) + LIGHT(x+1,y+1,z,1)) / 5.0f / 15.0f; float lg3 = (LIGHT(x+1,y-1,z+1,1) + lg*30 + LIGHT(x+1,y,z+1,1) + LIGHT(x+1,y-1,z,1)) / 5.0f / 15.0f; float lb0 = (LIGHT(x+1,y-1,z-1,2) + lb*30 + LIGHT(x+1,y,z-1,2) + LIGHT(x+1,y-1,z,2)) / 5.0f / 15.0f; float lb1 = (LIGHT(x+1,y+1,z-1,2) + lb*30 + LIGHT(x+1,y,z-1,2) + LIGHT(x+1,y+1,z,2)) / 5.0f / 15.0f; float lb2 = (LIGHT(x+1,y+1,z+1,2) + lb*30 + LIGHT(x+1,y,z+1,2) + LIGHT(x+1,y+1,z,2)) / 5.0f / 15.0f; float lb3 = (LIGHT(x+1,y-1,z+1,2) + lb*30 + LIGHT(x+1,y,z+1,2) + LIGHT(x+1,y-1,z,2)) / 5.0f / 15.0f; float ls0 = (LIGHT(x+1,y-1,z-1,3) + ls*30 + LIGHT(x+1,y,z-1,3) + LIGHT(x+1,y-1,z,3)) / 5.0f / 15.0f; float ls1 = (LIGHT(x+1,y+1,z-1,3) + ls*30 + LIGHT(x+1,y,z-1,3) + LIGHT(x+1,y+1,z,3)) / 5.0f / 15.0f; float ls2 = (LIGHT(x+1,y+1,z+1,3) + ls*30 + LIGHT(x+1,y,z+1,3) + LIGHT(x+1,y+1,z,3)) / 5.0f / 15.0f; float ls3 = (LIGHT(x+1,y-1,z+1,3) + ls*30 + LIGHT(x+1,y,z+1,3) + LIGHT(x+1,y-1,z,3)) / 5.0f / 15.0f; VERTEX(index, x+0.5f, y-0.5f, z-0.5f, u2,v1, lr0,lg0,lb0,ls0); VERTEX(index, x+0.5f, y+0.5f, z-0.5f, u2,v2, lr1,lg1,lb1,ls1); VERTEX(index, x+0.5f, y+0.5f, z+0.5f, u1,v2, lr2,lg2,lb2,ls2); VERTEX(index, x+0.5f, y-0.5f, z-0.5f, u2,v1, lr0,lg0,lb0,ls0); VERTEX(index, x+0.5f, y+0.5f, z+0.5f, u1,v2, lr2,lg2,lb2,ls2); VERTEX(index, x+0.5f, y-0.5f, z+0.5f, u1,v1, lr3,lg3,lb3,ls3); } if (!IS_BLOCKED(x-1,y,z,group)){ l = 0.85f; SETUP_UV(block->textureFaces[0]); float lr = LIGHT(x-1,y,z, 0) / 15.0f; float lg = LIGHT(x-1,y,z, 1) / 15.0f; float lb = LIGHT(x-1,y,z, 2) / 15.0f; float ls = LIGHT(x-1,y,z, 3) / 15.0f; float lr0 = (LIGHT(x-1,y-1,z-1,0) + lr*30 + LIGHT(x-1,y,z-1,0) + LIGHT(x-1,y-1,z,0)) / 5.0f / 15.0f; float lr1 = (LIGHT(x-1,y+1,z+1,0) + lr*30 + LIGHT(x-1,y,z+1,0) + LIGHT(x-1,y+1,z,0)) / 5.0f / 15.0f; float lr2 = (LIGHT(x-1,y+1,z-1,0) + lr*30 + LIGHT(x-1,y,z-1,0) + LIGHT(x-1,y+1,z,0)) / 5.0f / 15.0f; float lr3 = (LIGHT(x-1,y-1,z+1,0) + lr*30 + LIGHT(x-1,y,z+1,0) + LIGHT(x-1,y-1,z,0)) / 5.0f / 15.0f; float lg0 = (LIGHT(x-1,y-1,z-1,1) + lg*30 + LIGHT(x-1,y,z-1,1) + LIGHT(x-1,y-1,z,1)) / 5.0f / 15.0f; float lg1 = (LIGHT(x-1,y+1,z+1,1) + lg*30 + LIGHT(x-1,y,z+1,1) + LIGHT(x-1,y+1,z,1)) / 5.0f / 15.0f; float lg2 = (LIGHT(x-1,y+1,z-1,1) + lg*30 + LIGHT(x-1,y,z-1,1) + LIGHT(x-1,y+1,z,1)) / 5.0f / 15.0f; float lg3 = (LIGHT(x-1,y-1,z+1,1) + lg*30 + LIGHT(x-1,y,z+1,1) + LIGHT(x-1,y-1,z,1)) / 5.0f / 15.0f; float lb0 = (LIGHT(x-1,y-1,z-1,2) + lb*30 + LIGHT(x-1,y,z-1,2) + LIGHT(x-1,y-1,z,2)) / 5.0f / 15.0f; float lb1 = (LIGHT(x-1,y+1,z+1,2) + lb*30 + LIGHT(x-1,y,z+1,2) + LIGHT(x-1,y+1,z,2)) / 5.0f / 15.0f; float lb2 = (LIGHT(x-1,y+1,z-1,2) + lb*30 + LIGHT(x-1,y,z-1,2) + LIGHT(x-1,y+1,z,2)) / 5.0f / 15.0f; float lb3 = (LIGHT(x-1,y-1,z+1,2) + lb*30 + LIGHT(x-1,y,z+1,2) + LIGHT(x-1,y-1,z,2)) / 5.0f / 15.0f; float ls0 = (LIGHT(x-1,y-1,z-1,3) + ls*30 + LIGHT(x-1,y,z-1,3) + LIGHT(x-1,y-1,z,3)) / 5.0f / 15.0f; float ls1 = (LIGHT(x-1,y+1,z+1,3) + ls*30 + LIGHT(x-1,y,z+1,3) + LIGHT(x-1,y+1,z,3)) / 5.0f / 15.0f; float ls2 = (LIGHT(x-1,y+1,z-1,3) + ls*30 + LIGHT(x-1,y,z-1,3) + LIGHT(x-1,y+1,z,3)) / 5.0f / 15.0f; float ls3 = (LIGHT(x-1,y-1,z+1,3) + ls*30 + LIGHT(x-1,y,z+1,3) + LIGHT(x-1,y-1,z,3)) / 5.0f / 15.0f; VERTEX(index, x-0.5f, y-0.5f, z-0.5f, u1,v1, lr0,lg0,lb0,ls0); VERTEX(index, x-0.5f, y+0.5f, z+0.5f, u2,v2, lr1,lg1,lb1,ls1); VERTEX(index, x-0.5f, y+0.5f, z-0.5f, u1,v2, lr2,lg2,lb2,ls2); VERTEX(index, x-0.5f, y-0.5f, z-0.5f, u1,v1, lr0,lg0,lb0,ls0); VERTEX(index, x-0.5f, y-0.5f, z+0.5f, u2,v1, lr3,lg3,lb3,ls3); VERTEX(index, x-0.5f, y+0.5f, z+0.5f, u2,v2, lr1,lg1,lb1,ls1); } if (!IS_BLOCKED(x,y,z+1,group)){ l = 0.9f; SETUP_UV(block->textureFaces[5]); float lr = LIGHT(x,y,z+1, 0) / 15.0f; float lg = LIGHT(x,y,z+1, 1) / 15.0f; float lb = LIGHT(x,y,z+1, 2) / 15.0f; float ls = LIGHT(x,y,z+1, 3) / 15.0f; float lr0 = l*(LIGHT(x-1,y-1,z+1,0) + lr*30 + LIGHT(x,y-1,z+1,0) + LIGHT(x-1,y,z+1,0)) / 5.0f / 15.0f; float lr1 = l*(LIGHT(x+1,y+1,z+1,0) + lr*30 + LIGHT(x,y+1,z+1,0) + LIGHT(x+1,y,z+1,0)) / 5.0f / 15.0f; float lr2 = l*(LIGHT(x-1,y+1,z+1,0) + lr*30 + LIGHT(x,y+1,z+1,0) + LIGHT(x-1,y,z+1,0)) / 5.0f / 15.0f; float lr3 = l*(LIGHT(x+1,y-1,z+1,0) + lr*30 + LIGHT(x,y-1,z+1,0) + LIGHT(x+1,y,z+1,0)) / 5.0f / 15.0f; float lg0 = l*(LIGHT(x-1,y-1,z+1,1) + lg*30 + LIGHT(x,y-1,z+1,1) + LIGHT(x-1,y,z+1,1)) / 5.0f / 15.0f; float lg1 = l*(LIGHT(x+1,y+1,z+1,1) + lg*30 + LIGHT(x,y+1,z+1,1) + LIGHT(x+1,y,z+1,1)) / 5.0f / 15.0f; float lg2 = l*(LIGHT(x-1,y+1,z+1,1) + lg*30 + LIGHT(x,y+1,z+1,1) + LIGHT(x-1,y,z+1,1)) / 5.0f / 15.0f; float lg3 = l*(LIGHT(x+1,y-1,z+1,1) + lg*30 + LIGHT(x,y-1,z+1,1) + LIGHT(x+1,y,z+1,1)) / 5.0f / 15.0f; float lb0 = l*(LIGHT(x-1,y-1,z+1,2) + lb*30 + LIGHT(x,y-1,z+1,2) + LIGHT(x-1,y,z+1,2)) / 5.0f / 15.0f; float lb1 = l*(LIGHT(x+1,y+1,z+1,2) + lb*30 + LIGHT(x,y+1,z+1,2) + LIGHT(x+1,y,z+1,2)) / 5.0f / 15.0f; float lb2 = l*(LIGHT(x-1,y+1,z+1,2) + lb*30 + LIGHT(x,y+1,z+1,2) + LIGHT(x-1,y,z+1,2)) / 5.0f / 15.0f; float lb3 = l*(LIGHT(x+1,y-1,z+1,2) + lb*30 + LIGHT(x,y-1,z+1,2) + LIGHT(x+1,y,z+1,2)) / 5.0f / 15.0f; float ls0 = l*(LIGHT(x-1,y-1,z+1,3) + ls*30 + LIGHT(x,y-1,z+1,3) + LIGHT(x-1,y,z+1,3)) / 5.0f / 15.0f; float ls1 = l*(LIGHT(x+1,y+1,z+1,3) + ls*30 + LIGHT(x,y+1,z+1,3) + LIGHT(x+1,y,z+1,3)) / 5.0f / 15.0f; float ls2 = l*(LIGHT(x-1,y+1,z+1,3) + ls*30 + LIGHT(x,y+1,z+1,3) + LIGHT(x-1,y,z+1,3)) / 5.0f / 15.0f; float ls3 = l*(LIGHT(x+1,y-1,z+1,3) + ls*30 + LIGHT(x,y-1,z+1,3) + LIGHT(x+1,y,z+1,3)) / 5.0f / 15.0f; VERTEX(index, x-0.5f, y-0.5f, z+0.5f, u1,v1, lr0,lg0,lb0,ls0); VERTEX(index, x+0.5f, y+0.5f, z+0.5f, u2,v2, lr1,lg1,lb1,ls1); VERTEX(index, x-0.5f, y+0.5f, z+0.5f, u1,v2, lr2,lg2,lb2,ls2); VERTEX(index, x-0.5f, y-0.5f, z+0.5f, u1,v1, lr0,lg0,lb0,ls0); VERTEX(index, x+0.5f, y-0.5f, z+0.5f, u2,v1, lr3,lg3,lb3,ls3); VERTEX(index, x+0.5f, y+0.5f, z+0.5f, u2,v2, lr1,lg1,lb1,ls1); } if (!IS_BLOCKED(x,y,z-1,group)){ l = 0.8f; SETUP_UV(block->textureFaces[4]); float lr = LIGHT(x,y,z-1, 0) / 15.0f; float lg = LIGHT(x,y,z-1, 1) / 15.0f; float lb = LIGHT(x,y,z-1, 2) / 15.0f; float ls = LIGHT(x,y,z-1, 3) / 15.0f; float lr0 = l*(LIGHT(x-1,y-1,z-1,0) + lr*30 + LIGHT(x,y-1,z-1,0) + LIGHT(x-1,y,z-1,0)) / 5.0f / 15.0f; float lr1 = l*(LIGHT(x-1,y+1,z-1,0) + lr*30 + LIGHT(x,y+1,z-1,0) + LIGHT(x-1,y,z-1,0)) / 5.0f / 15.0f; float lr2 = l*(LIGHT(x+1,y+1,z-1,0) + lr*30 + LIGHT(x,y+1,z-1,0) + LIGHT(x+1,y,z-1,0)) / 5.0f / 15.0f; float lr3 = l*(LIGHT(x+1,y-1,z-1,0) + lr*30 + LIGHT(x,y-1,z-1,0) + LIGHT(x+1,y,z-1,0)) / 5.0f / 15.0f; float lg0 = l*(LIGHT(x-1,y-1,z-1,1) + lg*30 + LIGHT(x,y-1,z-1,1) + LIGHT(x-1,y,z-1,1)) / 5.0f / 15.0f; float lg1 = l*(LIGHT(x-1,y+1,z-1,1) + lg*30 + LIGHT(x,y+1,z-1,1) + LIGHT(x-1,y,z-1,1)) / 5.0f / 15.0f; float lg2 = l*(LIGHT(x+1,y+1,z-1,1) + lg*30 + LIGHT(x,y+1,z-1,1) + LIGHT(x+1,y,z-1,1)) / 5.0f / 15.0f; float lg3 = l*(LIGHT(x+1,y-1,z-1,1) + lg*30 + LIGHT(x,y-1,z-1,1) + LIGHT(x+1,y,z-1,1)) / 5.0f / 15.0f; float lb0 = l*(LIGHT(x-1,y-1,z-1,2) + lb*30 + LIGHT(x,y-1,z-1,2) + LIGHT(x-1,y,z-1,2)) / 5.0f / 15.0f; float lb1 = l*(LIGHT(x-1,y+1,z-1,2) + lb*30 + LIGHT(x,y+1,z-1,2) + LIGHT(x-1,y,z-1,2)) / 5.0f / 15.0f; float lb2 = l*(LIGHT(x+1,y+1,z-1,2) + lb*30 + LIGHT(x,y+1,z-1,2) + LIGHT(x+1,y,z-1,2)) / 5.0f / 15.0f; float lb3 = l*(LIGHT(x+1,y-1,z-1,2) + lb*30 + LIGHT(x,y-1,z-1,2) + LIGHT(x+1,y,z-1,2)) / 5.0f / 15.0f; float ls0 = l*(LIGHT(x-1,y-1,z-1,3) + ls*30 + LIGHT(x,y-1,z-1,3) + LIGHT(x-1,y,z-1,3)) / 5.0f / 15.0f; float ls1 = l*(LIGHT(x-1,y+1,z-1,3) + ls*30 + LIGHT(x,y+1,z-1,3) + LIGHT(x-1,y,z-1,3)) / 5.0f / 15.0f; float ls2 = l*(LIGHT(x+1,y+1,z-1,3) + ls*30 + LIGHT(x,y+1,z-1,3) + LIGHT(x+1,y,z-1,3)) / 5.0f / 15.0f; float ls3 = l*(LIGHT(x+1,y-1,z-1,3) + ls*30 + LIGHT(x,y-1,z-1,3) + LIGHT(x+1,y,z-1,3)) / 5.0f / 15.0f; VERTEX(index, x-0.5f, y-0.5f, z-0.5f, u2,v1, lr0,lg0,lb0,ls0); VERTEX(index, x-0.5f, y+0.5f, z-0.5f, u2,v2, lr1,lg1,lb1,ls1); VERTEX(index, x+0.5f, y+0.5f, z-0.5f, u1,v2, lr2,lg2,lb2,ls2); VERTEX(index, x-0.5f, y-0.5f, z-0.5f, u2,v1, lr0,lg0,lb0,ls0); VERTEX(index, x+0.5f, y+0.5f, z-0.5f, u1,v2, lr2,lg2,lb2,ls2); VERTEX(index, x+0.5f, y-0.5f, z-0.5f, u1,v1, lr3,lg3,lb3,ls3); } } } } return new Mesh(buffer, index / VERTEX_SIZE, chunk_attrs); }
63.829508
153
0.441494
Retro52
660a6aa65cf0765eef4a5a396a834b4ac89e3cc1
6,780
cpp
C++
tech/Game/BeamWeapon.cpp
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
tech/Game/BeamWeapon.cpp
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
tech/Game/BeamWeapon.cpp
nbtdev/teardrop
fa9cc8faba03a901d1d14f655a04167e14cd08ee
[ "MIT" ]
null
null
null
/****************************************************************************** Copyright (c) 2015 Teardrop Games 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 "BeamWeapon.h" #include "Component_Render.h" #include "Component_Audio.h" #include "Component_EquipmentSlot.h" #include "Gfx/Mesh.h" #include "Gfx/Submesh.h" //#include "Gfx/VertexData.h" //#include "Gfx/IndexData.h" //#include "Gfx/VertexFormat.h" #include "Gfx/Material.h" #include "Gfx/ShaderConstantTable.h" #include "Gfx/ShaderConstant.h" //#include "Gfx/Util.h" #include "Math/Matrix44.h" #include "Math/MathUtil.h" #include "Util/Environment.h" using namespace Teardrop; //--------------------------------------------------------------------------- TD_CLASS_IMPL(BeamWeapon); //--------------------------------------------------------------------------- BeamWeapon::BeamWeapon() { m_pMountTransformConstant = 0; m_animationTimeRemaining = 0; m_recycleTimeRemaining = 0; } //--------------------------------------------------------------------------- BeamWeapon::~BeamWeapon() { } //--------------------------------------------------------------------------- bool BeamWeapon::_initialize() { #if 0 // TODO: do this a different way if (Environment::get().isServer) return true; m_inst.m_pProceduralMesh = TD_NEW GfxMesh; m_inst.m_pProceduralMesh->initialize(); Gfx::Submesh* pSubmesh = m_inst.m_pProceduralMesh->createSubMesh(); pSubmesh->setPrimitiveType(TRISTRIP); // beam vertex format: positions and single set of texcoord GfxVertexFormat fmt; GfxVertexFormat::Element elem; elem.setSource(0); elem.setUsage(0); elem.offset = 0; elem.semantic = POSITION; elem.type = FLOAT3; fmt.addElement(elem); elem.semantic = TEXCOORD; elem.type = FLOAT2; elem.offset = (unsigned char)GfxUtil::getSizeOf(FLOAT3); fmt.addElement(elem); // beam is in the shape of a cylinder, 18 quads (36 tris) total in a // tristrip, for a total of 38 verts m_pVertexData = TD_NEW Vertex[38]; Vertex* pData = m_pVertexData; // organize the vertex data into a cylinder, around the Z axis, // 18 faces (so step around a circle by 20 degrees). Cylinder is // 1 unit in length (length is along the +Z axis), with a radius // of 0.1 float oo360 = 1.f / 360.f; for (float d=360; d>=0; d-=20) { float i = d * oo360; float r = i * MathUtil::PI; float s = MathUtil::sin(r); float c = MathUtil::cos(r); float x = c * 0.1f; float y = s * 0.1f; // "near" point pData->pz = 0; pData->px = x; pData->py = y; pData->tx = i; pData->ty = 0; pData++; // "far" point pData->pz = -float(getRange()); pData->px = x; pData->py = y; pData->tx = i; pData->ty = 1; pData++; } size_t stream; pSubmesh->createVertexData( stream, Environment::get(), fmt.getVertexSize(), 38, (GfxVertexData::CreationFlags)(GfxVertexData::STATIC|GfxVertexData::WRITE_ONLY), m_pVertexData); pSubmesh->setVertexFormat(Environment::get(), fmt); // make a basic material for this mesh GfxMaterial* pMtl = TD_NEW GfxMaterial; pMtl->initialize(); pSubmesh->setMaterial(pMtl, true); //pMtl->setEmissive(GfxUtil::makePackedColor(0,1,0,1)); pMtl->setEmissive(Vector4(0,1,0,1)); // set up shader constant(s) on the RenderComponent RenderComponent* pComp; if (findComponents(RenderComponent::getClassDef(), (Component**)&pComp)) { GfxShaderConstantTable& constants = pComp->getShaderConstants(); constants.begin(); m_pMountTransformConstant = constants.addFloatConstant("mountTransform", 4); constants.end(); } #endif return true; } //--------------------------------------------------------------------------- bool BeamWeapon::_destroy() { #if 0 if (m_inst.m_pProceduralMesh) { m_inst.m_pProceduralMesh->destroy(); delete m_inst.m_pProceduralMesh; m_inst.m_pProceduralMesh = 0; } #endif return true; } //--------------------------------------------------------------------------- bool BeamWeapon::_update(float deltaT) { m_recycleTimeRemaining -= deltaT; m_animationTimeRemaining -= deltaT; // do double-duty here -- update our components and at the same time, look // for a RenderComponent RenderComponent* pComp=0; for (Components::iterator it = m_components.begin(); it != m_components.end(); ++it) { if (it->second->getDerivedClassDef() == RenderComponent::getClassDef()) { pComp = static_cast<RenderComponent*>(it->second); // turn off rendering if we are below zero in anim time remaining pComp->setEnabled(m_animationTimeRemaining > 0); } // update component it->second->update(deltaT); } if (m_animationTimeRemaining < 0 && m_recycleTimeRemaining < 0) { // early-out, we are entirely idle return true; } #if 0 if (m_pMountTransformConstant) { const Matrix44& xform = m_pSlot->getTransform(); Matrix44 tmp; xform.transpose(tmp); // update shader constant(s) on the RenderComponent m_pMountTransformConstant->setValue((Vector4*)&tmp); } if (pComp) { m_inst.setTransform(getTransformWS()); pComp->setMeshInstance(m_inst); } #endif return true; } //--------------------------------------------------------------------------- void BeamWeapon::fire() { // only bother if we are recycled and ready if (m_recycleTimeRemaining < 0) { // then we can turn on rendering by restarting these timers m_recycleTimeRemaining = getRecycleTime(); m_animationTimeRemaining = getAnimationTime(); // and then play the internal fire sfx AudioComponent* pAudio; if (findComponents(AudioComponent::getClassDef(), (Component**)&pAudio)) { // play the fire sound pAudio->play2D(getFireSfx_Internal()); // and also line up the recycle sound pAudio->play2D(getRecycleSfx(), getRecycleTime(), true); } } }
29.478261
82
0.64823
nbtdev
660ae7a6f3d6dc183db47b9ec80d91bca9f86cd4
27,592
ipp
C++
include/External/stlib/packages/numerical/optimization/QuasiNewtonLBFGS.ipp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
include/External/stlib/packages/numerical/optimization/QuasiNewtonLBFGS.ipp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
include/External/stlib/packages/numerical/optimization/QuasiNewtonLBFGS.ipp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
// -*- C++ -*- /* * C library of Limited memory BFGS (L-BFGS). * * Copyright (c) 1990, Jorge Nocedal * Copyright (c) 2007,2008,2009 Naoaki Okazaki * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #if !defined(__QuasiNewtonLBFGS_ipp__) #error This file is an implementation detail of the class QuasiNewtonLBFGS. #endif namespace numerical { template<class _Function> inline typename QuasiNewtonLBFGS<_Function>::Number QuasiNewtonLBFGS<_Function>:: minimize(Vector* x) { if (_areThrowingExceptions) { if (_areThrowingMaxComputationExceptions) { return _minimize(x); } else { try { return _minimize(x); } catch (OptMaxComputationError&) { _function.resetNumFunctionCalls(); Vector g(x->size()); return _function(*x, &g); } } } else { try { return _minimize(x); } catch (OptError&) { _function.resetNumFunctionCalls(); Vector g(x->size()); return _function(*x, &g); } } } template<class _Function> inline typename QuasiNewtonLBFGS<_Function>::Number QuasiNewtonLBFGS<_Function>:: _minimize(Vector* x) { // Start the timer. _timer.reset(); _timer.start(); const std::size_t n = x->size(); Number ys, yy; Number beta; Number fx = 0.; Number rate = 0.; /* Check the input parameters for errors. */ assert(n != 0); _function.resetNumFunctionCalls(); /* Allocate working space. */ Vector xp(n, 0.), g(n, 0.), gp(n, 0.), d(n, 0.); /* Allocate limited memory storage. */ std::vector<IterationData> lm(_m, IterationData(n)); /* Allocate an array for storing previous values of the objective function. */ Vector pf(_past, 0.); /* Evaluate the function value and its gradient. */ fx = _function(*x, &g); /* Store the initial value of the objective function. */ if (! pf.empty()) { pf[0] = fx; } /* Compute the direction; we assume the initial hessian matrix H_0 is the identity matrix. */ for (std::size_t i = 0; i != d.size(); ++i) { d[i] = -g[i]; } // Make sure that the initial variables are not a minimizer. if (hasGradientConverged(*x, g)) { return fx; } // Compute the initial step. Number step = 1. / std::sqrt(dot(d, d)); std::size_t j; std::size_t k = 1; std::size_t end = 0; for (;;) { /* Store the current position and gradient vectors. */ std::copy(x->begin(), x->end(), xp.begin()); std::copy(g.begin(), g.end(), gp.begin()); /* Search for an optimal step. */ try { lineSearch(x, &fx, &g, d, &step, xp); } catch (OptError&) { /* Revert to the previous point. */ std::copy(xp.begin(), xp.end(), x->begin()); std::copy(gp.begin(), gp.end(), g.begin()); throw; } // Check for gradient convergence. if (hasGradientConverged(*x, g)) { break; } /* Test for stopping criterion. The criterion is given by the following formula: (f(past_x) - f(x)) / f(x) < \delta */ if (! pf.empty()) { /* We don't test the stopping criterion while k < past. */ if (_past <= k) { /* Compute the relative improvement from the past. */ rate = (pf[k % _past] - fx) / fx; /* The stopping criterion. */ if (rate < _delta) { break; } } /* Store the current value of the objective function. */ pf[k % _past] = fx; } if (_maxIterations != 0 && _maxIterations < k+1) { throw OptMaxIterationsError("In QuasiNewtonLBFGS::_minimize(): Maximum number of iterations reached."); } // Check if we have exceeded the maximum allowed time. _timer.stop(); if (_timer > _maxTime) { throw OptMaxTimeError("In QuasiNewtonLBFGS::_minimize(): The maximum allowed time has been exceeded."); } _timer.start(); { /* Update vectors s and y: s_{k+1} = x_{k+1} - x_{k} = \step * d_{k}. y_{k+1} = g_{k+1} - g_{k}. */ IterationData& it = lm[end]; for (std::size_t i = 0; i != it.s.size(); ++i) { it.s[i] = (*x)[i] - xp[i]; it.y[i] = g[i] - gp[i]; } /* Compute scalars ys and yy: ys = y^t \cdot s = 1 / \rho. yy = y^t \cdot y. Notice that yy is used for scaling the hessian matrix H_0 (Cholesky factor). */ ys = dot(it.y, it.s); yy = dot(it.y, it.y); it.ys = ys; } /* Recursive formula to compute dir = -(H \cdot g). This is described in page 779 of: Jorge Nocedal. Updating Quasi-Newton Matrices with Limited Storage. Mathematics of Computation, Vol. 35, No. 151, pp. 773--782, 1980. */ const std::size_t bound = (_m <= k) ? _m : k; ++k; end = (end + 1) % _m; /* Compute the steepest direction. */ /* Compute the negative of gradients. */ for (std::size_t i = 0; i != d.size(); ++i) { d[i] = -g[i]; } j = end; for (std::size_t i = 0; i != bound; ++i) { j = (j + _m - 1) % _m; /* if (--j == -1) j = _m-1; */ IterationData& it = lm[j]; /* \alpha_{j} = \rho_{j} s^{t}_{j} \cdot q_{k+1}. */ it.alpha = dot(it.s, d); it.alpha /= it.ys; /* q_{i} = q_{i+1} - \alpha_{i} y_{i}. */ for (std::size_t i = 0; i != d.size(); ++i) { d[i] -= it.alpha * it.y[i]; } } d *= ys / yy; for (std::size_t i = 0; i != bound; ++i) { IterationData& it = lm[j]; /* \beta_{j} = \rho_{j} y^t_{j} \cdot \gamma_{i}. */ beta = dot(it.y, d); beta /= it.ys; /* \gamma_{i+1} = \gamma_{i} + (\alpha_{j} - \beta_{j}) s_{j}. */ for (std::size_t i = 0; i != d.size(); ++i) { d[i] += (it.alpha - beta) * it.s[i]; } j = (j + 1) % _m; /* if (++j == _m) j = 0; */ } /* Now the search direction d is ready. We try step = 1 first. */ step = 1.0; } return fx; } template<class _Function> inline typename QuasiNewtonLBFGS<_Function>::Number QuasiNewtonLBFGS<_Function>:: minimizeIllConditioned(Vector* x, const std::size_t groupSize) { if (_areThrowingExceptions) { if (_areThrowingMaxComputationExceptions) { return _minimizeIllConditioned(x, groupSize); } else { try { return _minimizeIllConditioned(x, groupSize); } catch (OptMaxComputationError&) { _function.resetNumFunctionCalls(); Vector g(x->size()); return _function(*x, &g); } } } else { try { return _minimizeIllConditioned(x, groupSize); } catch (OptError&) { _function.resetNumFunctionCalls(); Vector g(x->size()); return _function(*x, &g); } } } template<class _Function> inline typename QuasiNewtonLBFGS<_Function>::Number QuasiNewtonLBFGS<_Function>:: _minimizeIllConditioned(Vector* x, const std::size_t groupSize) { typedef FunctionOfSelectedCoordinates<ObjectiveFunction<Function> > Fosc; assert(groupSize > 0 && x->size() % groupSize == 0); std::size_t oldGroup = x->size() / groupSize; for (std::size_t i = 0; i != _maxResetIllConditioned; ++i) { try { // Return the minima if we can calculate it. return _minimize(x); } catch (OptError&) { // Determine the group with the maximum gradient. std::size_t group = findGroupWithMaximumGradient(*x, groupSize); // If it is the same group as last time then the last attempt to // improve the condition was not sufficient. if (group == oldGroup) { throw OptError("In QuasiNewtonLBFGS::minimizeIllConditioned(): Unable to substantially improve an ill-conditioned problem."); } oldGroup = group; // Select the coordinates in the group. std::vector<std::size_t> indices(groupSize); Vector y(groupSize); for (std::size_t j = 0; j != groupSize; ++j) { indices[j] = group * groupSize + j; y[j] = (*x)[indices[j]]; } // Perform a minimization on those coordinates. Fosc f(_function, *x, indices); ConjugateGradient<Fosc> opt(f); try { // Minimize on the selected coordinates. opt.minimize(&y); // Update the selected coordinates. for (std::size_t j = 0; j != groupSize; ++j) { (*x)[indices[j]] = y[j]; } } catch (OptError& error) { throw OptError(std::string("In QuasiNewtonLBFGS::minimizeIllConditioned(): Failed minimization on selected coordinates of an ill-conditioned problem. ") + error.what()); } } } throw OptMaxIterationsError("In QuasiNewtonLBFGS::minimizeIllConditioned(): Maximum number of resets for an ill-conditioned problem has been exceeded."); return 0; } template<class _Function> inline bool QuasiNewtonLBFGS<_Function>:: hasGradientConverged(const Vector& x, const Vector& g) const { /* Compute x and g norms. */ const Number xnorm = std::max(std::sqrt(dot(x, x)), 1.); const Number gnorm = std::sqrt(dot(g, g)); /* Relative gradient convergence test. The criterion is given by the following formula: |g(x)| / \max(1, |x|) < \epsilon */ if (gnorm <= _relativeGradientTolerance * xnorm) { /* Convergence. */ return true; } // RMS gradient convergence test. // ||g|| / sqrt(n) < epsilon // Formulate to avoid the square root and division. if (gnorm * gnorm < _rmsGradientTolerance * _rmsGradientTolerance * g.size()) { return true; } // If we are checking the maximum component of the gradient. if (_maxGradientTolerance != 0) { Number maximum = 0; Number magnitude; for (std::size_t i = 0; i != g.size(); ++i) { magnitude = std::abs(g[i]); if (magnitude > maximum) { maximum = magnitude; } } if (maximum < _maxGradientTolerance) { return true; } } return false; } template<class _Function> inline std::size_t QuasiNewtonLBFGS<_Function>:: findGroupWithMaximumGradient(const Vector& x, const std::size_t groupSize) { Vector gradient(x.size()); _function(x, &gradient); const std::size_t numGroups = x.size() / groupSize; std::size_t maxGroup = 0; Number maxSquaredGradient = 0; for (std::size_t g = 0; g != numGroups; ++g) { Number s = 0; for (std::size_t i = 0; i != groupSize; ++i) { s += gradient[g * groupSize + i] * gradient[g * groupSize + i]; } if (s > maxSquaredGradient) { maxGroup = g; maxSquaredGradient = s; } } return maxGroup; } template<class _Function> inline void QuasiNewtonLBFGS<_Function>:: lineSearch(Vector* x, Number* f, Vector* g, const Vector& s, // The search direction. Number* stp, const Vector& xp) { std::size_t count = 0; Number dg; Number stx, fx, dgx; Number sty, fy, dgy; Number fxm, dgxm, fym, dgym, fm, dgm; Number finit, ftest1, dgtest; Number width, previousWidth; Number stmin, stmax; /* Check the input parameters for errors. */ if (*stp <= 0.) { throw OptStepError("In QuasiNewtonLBFGS::lineSearch(): Non-positive step size."); } /* Compute the initial gradient in the search direction. */ Number dginit = dot(*g, s); /* Make sure that s points to a descent direction. */ if (0 < dginit) { throw OptStepError("In QuasiNewtonLBFGS::lineSearch(): Bad descent direction."); } /* Initialize local variables. */ bool isBracketed = false; bool stage1 = true; finit = *f; dgtest = _ftol * dginit; width = _maxStep - _minStep; previousWidth = 2.0 * width; /* The variables stx, fx, dgx contain the values of the step, function, and directional derivative at the best step. The variables sty, fy, dgy contain the value of the step, function, and derivative at the other endpoint of the interval of uncertainty. The variables stp, f, dg contain the values of the step, function, and derivative at the current step. */ stx = sty = 0.; fx = fy = finit; dgx = dgy = dginit; for (;;) { /* Set the minimum and maximum steps to correspond to the present interval of uncertainty. */ if (isBracketed) { stmin = std::min(stx, sty); stmax = std::max(stx, sty); } else { stmin = stx; stmax = *stp + 4.0 * (*stp - stx); } /* Clip the step in the range of [stpmin, stpmax]. */ if (*stp < _minStep) { *stp = _minStep; } if (_maxStep < *stp) { *stp = _maxStep; } /* If an unusual termination is to occur then let stp be the lowest point obtained so far. */ if ((isBracketed && ((*stp <= stmin || stmax <= *stp) || _maxLinesearch <= count + 1)) || (isBracketed && (stmax - stmin <= _xtol * stmax))) { *stp = stx; } /* Compute the current value of x: x <- x + (*stp) * s. */ for (std::size_t i = 0; i != x->size(); ++i) { (*x)[i] = xp[i] + *stp * s[i]; } /* Evaluate the function and gradient values. */ *f = _function(*x, g); dg = dot(*g, s); ftest1 = finit + *stp * dgtest; ++count; /* Test for errors and convergence. */ if (isBracketed && (*stp <= stmin || stmax <= *stp)) { throw OptError("In QuasiNewtonLBFGS::lineSearch(): Rounding errors prevent further progress."); } if (*stp == _maxStep && *f <= ftest1 && dg <= dgtest) { throw OptStepError("In QuasiNewtonLBFGS::lineSearch(): The step is the maximum value."); } if (*stp == _minStep && (ftest1 < *f || dgtest <= dg)) { std::ostringstream message; message << "In QuasiNewtonLBFGS::lineSearch():\n" << " The step is the minimum value.\n" << " *stp = " << *stp << '\n' << " _minStep = " << _minStep << '\n'; throw OptStepError(message.str()); } if (isBracketed && (stmax - stmin) <= _xtol * stmax) { throw OptError("In QuasiNewtonLBFGS::lineSearch(): Relative width of the interval of uncertainty is too small."); } if (_maxLinesearch <= count) { throw OptMaxIterationsError("In QuasiNewtonLBFGS::lineSearch(): Maximum number of iterations."); } if (*f <= ftest1 && std::abs(dg) <= _gtol * (-dginit)) { /* The sufficient decrease condition and the directional derivative condition hold. */ break; } /* In the first stage we seek a step for which the modified function has a nonpositive value and nonnegative derivative. */ if (stage1 && *f <= ftest1 && std::min(_ftol, _gtol) * dginit <= dg) { stage1 = false; } /* A modified function is used to predict the step only if we have not obtained a step for which the modified function has a nonpositive function value and nonnegative derivative, and if a lower function value has been obtained but the decrease is not sufficient. */ if (stage1 && ftest1 < *f && *f <= fx) { /* Define the modified function and derivative values. */ fm = *f - *stp * dgtest; fxm = fx - stx * dgtest; fym = fy - sty * dgtest; dgm = dg - dgtest; dgxm = dgx - dgtest; dgym = dgy - dgtest; /* Call updateTrialInterval() to update the interval of uncertainty and to compute the new step. */ updateTrialInterval(&stx, &fxm, &dgxm, &sty, &fym, &dgym, stp, &fm, &dgm, stmin, stmax, &isBracketed); /* Reset the function and gradient values for f. */ fx = fxm + stx * dgtest; fy = fym + sty * dgtest; dgx = dgxm + dgtest; dgy = dgym + dgtest; } else { /* Call update_trial_interval() to update the interval of uncertainty and to compute the new step. */ updateTrialInterval(&stx, &fx, &dgx, &sty, &fy, &dgy, stp, f, &dg, stmin, stmax, &isBracketed); } /* Force a sufficient decrease in the interval of uncertainty. */ if (isBracketed) { if (0.66 * previousWidth <= std::abs(sty - stx)) { *stp = stx + 0.5 * (sty - stx); } previousWidth = width; width = std::abs(sty - stx); } } } template<class _Function> inline void QuasiNewtonLBFGS<_Function>:: updateTrialInterval(Number* x, Number* fx, Number* dx, Number* y, Number* fy, Number* dy, Number* t, Number* ft, Number* dt, const Number tmin, const Number tmax, bool* isBracketed) { const bool dsign = *dt * (*dx / std::abs(*dx)) < 0.; /* Check the input parameters for errors. */ if (*isBracketed) { if (*t <= std::min(*x, *y) || std::max(*x, *y) <= *t) { throw OptError("In QuasiNewtonLBFGS::updateTrialInterval: The trival value t is out of the interval."); } if (0. <= *dx * (*t - *x)) { throw OptError("In QuasiNewtonLBFGS::updateTrialInterval: The function must decrease from x."); } if (tmax < tmin) { throw OptError("In QuasiNewtonLBFGS::updateTrialInterval: Incorrect tmin and tmax specified."); } } bool bound; Number mc; /* minimizer of an interpolated cubic. */ Number mq; /* minimizer of an interpolated quadratic. */ Number newt; /* new trial value. */ /* Trial value selection. */ if (*fx < *ft) { /* Case 1: a higher function value. The minimum is bracketed. If the cubic minimizer is closer to x than the quadratic one, the cubic one is taken, else the average of the minimizers is taken. */ *isBracketed = true; bound = true; mc = cubicMinimizer(*x, *fx, *dx, *t, *ft, *dt); mq = quadraticMinimizer(*x, *fx, *dx, *t, *ft); if (std::abs(mc - *x) < std::abs(mq - *x)) { newt = mc; } else { newt = mc + 0.5 * (mq - mc); } } else if (dsign) { /* Case 2: a lower function value and derivatives of opposite sign. The minimum is bracketed. If the cubic minimizer is closer to x than the quadratic (secant) one, the cubic one is taken, else the quadratic one is taken. */ *isBracketed = true; bound = false; mc = cubicMinimizer(*x, *fx, *dx, *t, *ft, *dt); mq = quadraticMinimizer(*x, *dx, *t, *dt); if (std::abs(mc - *t) > std::abs(mq - *t)) { newt = mc; } else { newt = mq; } } else if (std::abs(*dt) < std::abs(*dx)) { /* Case 3: a lower function value, derivatives of the same sign, and the magnitude of the derivative decreases. The cubic minimizer is only used if the cubic tends to infinity in the direction of the minimizer or if the minimum of the cubic is beyond t. Otherwise the cubic minimizer is defined to be either tmin or tmax. The quadratic (secant) minimizer is also computed and if the minimum is bracketed then the the minimizer closest to x is taken, else the one farthest away is taken. */ bound = true; mc = cubicMinimizer(*x, *fx, *dx, *t, *ft, *dt, tmin, tmax); mq = quadraticMinimizer(*x, *dx, *t, *dt); if (*isBracketed) { if (std::abs(*t - mc) < std::abs(*t - mq)) { newt = mc; } else { newt = mq; } } else { if (std::abs(*t - mc) > std::abs(*t - mq)) { newt = mc; } else { newt = mq; } } } else { /* Case 4: a lower function value, derivatives of the same sign, and the magnitude of the derivative does not decrease. If the minimum is not bracketed, the step is either tmin or tmax, else the cubic minimizer is taken. */ bound = false; if (*isBracketed) { newt = cubicMinimizer(*t, *ft, *dt, *y, *fy, *dy); } else if (*x < *t) { newt = tmax; } else { newt = tmin; } } /* Update the interval of uncertainty. This update does not depend on the new step or the case analysis above. - Case a: if f(x) < f(t), x <- x, y <- t. - Case b: if f(t) <= f(x) && f'(t)*f'(x) > 0, x <- t, y <- y. - Case c: if f(t) <= f(x) && f'(t)*f'(x) < 0, x <- t, y <- x. */ if (*fx < *ft) { /* Case a */ *y = *t; *fy = *ft; *dy = *dt; } else { /* Case c */ if (dsign) { *y = *x; *fy = *fx; *dy = *dx; } /* Cases b and c */ *x = *t; *fx = *ft; *dx = *dt; } /* Clip the new trial value in [tmin, tmax]. */ if (tmax < newt) { newt = tmax; } if (newt < tmin) { newt = tmin; } /* Redefine the new trial value if it is close to the upper bound of the interval. */ if (*isBracketed && bound) { mq = *x + 0.66 * (*y - *x); if (*x < *y) { if (mq < newt) { newt = mq; } } else { if (newt < mq) { newt = mq; } } } // Record the new trial value. *t = newt; } template<class _Function> inline typename QuasiNewtonLBFGS<_Function>::Number QuasiNewtonLBFGS<_Function>:: quadraticMinimizer(const Number u, const Number fu, const Number du, const Number v, const Number fv) const { const Number a = v - u; return u + du / ((fu - fv) / a + du) / 2 * a; } /** * Find a minimizer of an interpolated quadratic function. * @param u The value of one point, u. * @param du The value of f'(u). * @param v The value of another point, v. * @param dv The value of f'(v). * @return The minimizer of the interpolated quadratic. */ template<class _Function> inline typename QuasiNewtonLBFGS<_Function>::Number QuasiNewtonLBFGS<_Function>:: quadraticMinimizer(const Number u, const Number du, const Number v, const Number dv) const { const Number a = u - v; return v + dv / (dv - du) * a; } /** * Find a minimizer of an interpolated cubic function. * @param u The value of one point, u. * @param fu The value of f(u). * @param du The value of f'(u). * @param v The value of another point, v. * @param fv The value of f(v). * @param du The value of f'(v). * @return The minimizer of the interpolated cubic. */ template<class _Function> inline typename QuasiNewtonLBFGS<_Function>::Number QuasiNewtonLBFGS<_Function>:: cubicMinimizer(const Number u, const Number fu, const Number du, const Number v, const Number fv, const Number dv) const { const Number d = v - u; const Number theta = (fu - fv) * 3 / d + du + dv; Number p = std::abs(theta); Number q = std::abs(du); Number r = std::abs(dv); const Number s = std::max(std::max(p, q), r); /* gamma = s*sqrt((theta/s)**2 - (du/s) * (dv/s)) */ const Number a = theta / s; Number gamma = s * std::sqrt(a * a - (du / s) * (dv / s)); if (v < u) { gamma = -gamma; } p = gamma - du + theta; q = gamma - du + gamma + dv; r = p / q; return u + r * d; } /** * Find a minimizer of an interpolated cubic function. * @param u The value of one point, u. * @param fu The value of f(u). * @param du The value of f'(u). * @param v The value of another point, v. * @param fv The value of f(v). * @param du The value of f'(v). * @param xmin The minimum value. * @param xmax The maximum value. * @return The minimizer of the interpolated cubic. */ template<class _Function> inline typename QuasiNewtonLBFGS<_Function>::Number QuasiNewtonLBFGS<_Function>:: cubicMinimizer(const Number u, const Number fu, const Number du, const Number v, const Number fv, const Number dv, const Number xmin, const Number xmax) const { const Number d = v - u; const Number theta = (fu - fv) * 3 / d + du + dv; Number p = std::abs(theta); Number q = std::abs(du); Number r = std::abs(dv); const Number s = std::max(std::max(p, q), r); /* gamma = s*sqrt((theta/s)**2 - (du/s) * (dv/s)) */ const Number a = theta / s; Number gamma = s * std::sqrt(std::max(0., a * a - (du / s) * (dv / s))); if (u < v) { gamma = -gamma; } p = gamma - dv + theta; q = gamma - dv + gamma + du; r = p / q; Number result; if (r < 0. && gamma != 0.) { result = v - r * d; } else if (a < 0) { result = xmax; } else { result = xmin; } return result; } } // namespace numerical
31.142212
182
0.532546
bxl295
6614f85317377db14d1072c0519a80afa3ff5bc3
2,228
cpp
C++
Stp/Base/Thread/NativeThreadLinux.cpp
markazmierczak/Polonite
240f099cafc5c38dc1ae1cc6fc5773e13f65e9de
[ "MIT" ]
1
2019-07-11T12:47:52.000Z
2019-07-11T12:47:52.000Z
Stp/Base/Thread/NativeThreadLinux.cpp
Polonite/Polonite
240f099cafc5c38dc1ae1cc6fc5773e13f65e9de
[ "MIT" ]
null
null
null
Stp/Base/Thread/NativeThreadLinux.cpp
Polonite/Polonite
240f099cafc5c38dc1ae1cc6fc5773e13f65e9de
[ "MIT" ]
1
2019-07-11T12:47:53.000Z
2019-07-11T12:47:53.000Z
// Copyright 2017 Polonite Authors. All rights reserved. // Distributed under MIT license that can be found in the LICENSE file. #include "Base/Thread/NativeThread.h" #include "Base/String/StringSpan.h" #if !OS(ANDROID) # include <sched.h> #endif #if !OS(FREEBSD) # include <sys/prctl.h> #endif namespace stp { #if !OS(ANDROID) ErrorCode NativeThread::SetPriority(NativeThreadObject thread, ThreadPriority priority) { #ifdef SCHED_IDLE if (priority == ThreadPriority::Idle) { sched_param param = { 0 }; ErrorCode error = static_cast<PosixErrorCode>( pthread_setschedparam(thread, SCHED_IDLE, &param)); if (!isOk(error)) { // Unable to set idle policy for thread. return error; } return ErrorCode(); } #endif if (priority == ThreadPriority::RealtimeAudio) priority = ThreadPriority::TimeCritical; int policy = SCHED_RR; int min = sched_get_priority_min(policy); int max = sched_get_priority_max(policy); ASSERT(min != -1 && max != -1); constexpr int MaxPriority = static_cast<int>(ThreadPriority::TimeCritical); ASSERT(static_cast<int>(priority) <= MaxPriority); int p = min + (max - min) * static_cast<int>(priority) / MaxPriority; sched_param param = { p }; return static_cast<PosixErrorCode>(pthread_setschedparam(thread, policy, &param)); } #endif // OS(*) #if !OS(FREEBSD) ErrorCode NativeThread::SetName(const char* name_cstr) { // From spec: // The name can be up to 16 bytes long, including the terminating null byte. // (If the length of the string, including the terminating null byte, // exceeds 16 bytes, the string is silently truncated.) // // Sometimes the name of thread begins with organization prefix, like: // org.polonite.MyThread // constexpr int MaxNameLength = 16 - 1; // 1 for null character auto name = StringSpan::fromCString(name_cstr); if (name.length() > MaxNameLength) { int dot_index = name.lastIndexOf('.'); if (dot_index >= 0) name.removePrefix(dot_index + 1); } ASSERT(*(name.data() + name.length()) == '\0'); int rv = prctl(PR_SET_NAME, name.data()); if (rv != 0) return getLastPosixErrorCode(); return ErrorCode(); } #endif // OS(*) } // namespace stp
28.564103
89
0.687163
markazmierczak
6618b29423eeb2e49c37bcc9cfc69cdd293210a0
3,024
cpp
C++
Monopoly/GameState.cpp
dragonly/Monopoly
1dc013aed2bb49dd7c0c610df697f2bdfe282a8f
[ "MIT" ]
3
2018-06-24T13:44:50.000Z
2019-11-18T09:49:41.000Z
Monopoly/GameState.cpp
dragonly/Monopoly
1dc013aed2bb49dd7c0c610df697f2bdfe282a8f
[ "MIT" ]
null
null
null
Monopoly/GameState.cpp
dragonly/Monopoly
1dc013aed2bb49dd7c0c610df697f2bdfe282a8f
[ "MIT" ]
null
null
null
// // GameState.cpp // Monopoly // // Created by Dragonly on 4/27/16. // Copyright © 2016 Dragonly. All rights reserved. // #include "GameState.hpp" namespace monopoly { GameState::GameState() : today(2016, 5, 1), stockMarket() { Land lands[] = { // this is just for initializing, don't do logic on it!!! {"land", 0, 0, 0}, {"land", 0, 1, 0}, {"land", 0, 2, 0}, {"land", 0, 3, 0}, {"land", 0, 4, 0}, {"land", 0, 5, 0}, {"land", 0, 6, 0}, {"land", 0, 7, 0}, {"land", 1, 7, 1}, {"land", 1, 8, 1}, {"land", 1, 9, 1}, {"news", 1, 10, 1}, {"land", 2, 10, 1}, {"land", 3, 10, 1}, {"land", 4, 10, 1}, {"land", 4, 11, 2}, {"land", 4, 12, 2}, {"bank", 4, 13, 2}, {"land", 4, 14, 2}, {"land", 3, 14, 2}, {"land", 2, 14, 2}, {"land", 1, 14, 2}, {"land", 0, 14, 2}, {"lottery", 0, 15, 3}, {"land", 0, 16, 3}, {"land", 0, 17, 3}, {"land", 0, 18, 3}, {"coupon", 0, 19, 3}, {"land", 1, 19, 3}, {"land", 2, 19, 3}, {"land", 3, 19, 3}, {"land", 4, 19, 3}, {"land", 5, 19, 3}, {"land", 6, 19, 4}, {"land", 6, 18, 4}, {"blank", 6, 17, 4}, {"land", 6, 16, 4}, {"land", 7, 16, 4}, {"land", 8, 16, 4}, {"land", 8, 15, 4}, {"land", 8, 14, 4}, {"toolStore", 7, 14, 5}, {"land", 6, 14, 5}, {"land", 6, 13, 5}, {"land", 6, 12, 5}, {"land", 7, 12, 5}, {"land", 8, 12, 5}, {"gift", 9, 12, 5}, {"land", 9, 11, 5}, {"land", 9, 10, 5}, {"land", 9, 9, 5}, {"land", 8, 9, 6}, {"land", 7, 9, 6}, {"news", 6, 9, 6}, {"land", 6, 8, 6}, {"land", 6, 7, 6}, {"land", 6, 6, 6}, {"land", 5, 6, 6}, {"land", 5, 5, 6}, {"bank", 5, 4, 6}, {"land", 5, 3, 6}, {"land", 5, 2, 6}, {"land", 4, 2, 7}, {"land", 3, 2, 7}, {"land", 2, 2, 7}, {"lottery", 2, 1, 7}, {"land", 2, 0, 7}, {"land", 1, 0, 7}}; for (int i = 0; i < sizeof(lands)/sizeof(lands[0]); i++) { road.push_back(Land(lands[i])); streets[road[i].street].push_back(i); } state = GS::normal; error = false; gameover = false; message = ""; errMsg = ""; playerIndex = 0; lastRoll = -1; } Player& GameState::currentPlayer() { return players[playerIndex]; } Player& GameState::getPlayerByName(string name) { for (int i = 0; i < players.size(); i++) { if (players[i].name == name) { return players[i]; } } return players[0]; // this is bad :( , but no fix for now } int GameState::streetPenalty(int streetNum, string owner) { int ret = 0; int x, y; // road 本身的owner信息不可靠, 不用于判断, 只用于存储对应board位置和街道信息 for (auto i : streets[streetNum]) { x = road[i].pos.first; y = road[i].pos.second; if (board[x][y].owner == owner) { ret += road[i].basePrice * road[i].level; } } ret *= 0.1; return ret; } }
43.2
116
0.425265
dragonly
661975ec91a71aeb0ec9c0dd1429f627de00d2a9
12,852
cpp
C++
source/cpu/exec/exec.cpp
zhiayang/z86
708aa48f981dbba8025c83ae10918d42163da753
[ "Apache-2.0" ]
3
2020-10-12T15:52:20.000Z
2021-02-07T08:40:03.000Z
source/cpu/exec/exec.cpp
zhiayang/z86
708aa48f981dbba8025c83ae10918d42163da753
[ "Apache-2.0" ]
null
null
null
source/cpu/exec/exec.cpp
zhiayang/z86
708aa48f981dbba8025c83ae10918d42163da753
[ "Apache-2.0" ]
null
null
null
// exec.cpp // Copyright (c) 2020, zhiayang // Licensed under the Apache License Version 2.0. #include "defs.h" #include "cpu/cpu.h" #include "cpu/exec.h" namespace z86 { using Operand = instrad::x86::Operand; using Register = instrad::x86::Register; using Instruction = instrad::x86::Instruction; using InstrMods = instrad::x86::InstrModifiers; // jump.cpp void op_jcxz(CPU& cpu, const InstrMods& mods, const Operand& dst); void op_jo(CPU& cpu, const Operand& dst, bool check); void op_js(CPU& cpu, const Operand& dst, bool check); void op_ja(CPU& cpu, const Operand& dst, bool check); void op_jz(CPU& cpu, const Operand& dst, bool check); void op_jp(CPU& cpu, const Operand& dst, bool check); void op_jl(CPU& cpu, const Operand& dst, bool check); void op_jg(CPU& cpu, const Operand& dst, bool check); void op_jc(CPU& cpu, const Operand& dst, bool check); void op_jmp(CPU& cpu, const Operand& dst); // jump.cpp void op_call(CPU& cpu, const InstrMods& mods, const Operand& dst); void op_retf(CPU& cpu, const Instruction& instr); void op_ret(CPU& cpu, const Instruction& instr); // arithmetic.cpp void op_inc_dec(CPU& cpu, const instrad::x86::Op& op, const InstrMods& mods, const Operand& dst); void op_arithmetic(CPU& cpu, const instrad::x86::Op& op, const InstrMods& mods, const Operand& dst, const Operand& src); // adjust.cpp void op_daa(CPU& cpu); void op_das(CPU& cpu); void op_aaa(CPU& cpu); void op_aas(CPU& cpu); void op_aad(CPU& cpu, uint8_t base); void op_aam(CPU& cpu, uint8_t base); static void op_xchg(CPU& cpu, const InstrMods& mods, const Operand& dst, const Operand& src); static void op_mov(CPU& cpu, const InstrMods& mods, const Operand& dst, const Operand& src); static void op_pop(CPU& cpu, const InstrMods& mods, const Operand& dst); static void op_push(CPU& cpu, const InstrMods& mods, const Operand& src); void Executor::execute(const Instruction& instr) { using namespace instrad::x86; if(instr.lockPrefix()) m_cpu.memLock(); auto& op = instr.op(); switch(op.id()) { case ops::ADD.id(): case ops::ADC.id(): case ops::SUB.id(): case ops::SBB.id(): case ops::AND.id(): case ops::OR.id(): case ops::XOR.id(): case ops::CMP.id(): case ops::TEST.id(): op_arithmetic(m_cpu, op, instr.mods(), instr.dst(), instr.src()); break; case ops::INC.id(): case ops::DEC.id(): op_inc_dec(m_cpu, op, instr.mods(), instr.dst()); break; case ops::CALL.id(): op_call(m_cpu, instr.mods(), instr.dst()); break; case ops::RETF.id(): op_retf(m_cpu, instr); break; case ops::RET.id(): op_ret(m_cpu, instr); break; case ops::MOV.id(): op_mov(m_cpu, instr.mods(), instr.dst(), instr.src()); break; case ops::PUSH.id(): op_push(m_cpu, instr.mods(), instr.dst()); break; case ops::POP.id(): op_pop(m_cpu, instr.mods(), instr.dst()); break; case ops::XCHG.id(): op_xchg(m_cpu, instr.mods(), instr.dst(), instr.src()); break; case ops::DAA.id(): op_daa(m_cpu); break; case ops::DAS.id(): op_das(m_cpu); break; case ops::AAA.id(): op_aaa(m_cpu); break; case ops::AAS.id(): op_aas(m_cpu); break; case ops::AAM.id(): op_aam(m_cpu, instr.dst().imm() & 0xFF); break; case ops::AAD.id(): op_aad(m_cpu, instr.dst().imm() & 0xFF); break; case ops::JMP.id(): op_jmp(m_cpu, instr.dst()); break; case ops::JO.id(): op_jo(m_cpu, instr.dst(), true); break; case ops::JNO.id(): op_jo(m_cpu, instr.dst(), false); break; case ops::JS.id(): op_js(m_cpu, instr.dst(), true); break; case ops::JNS.id(): op_js(m_cpu, instr.dst(), false); break; case ops::JZ.id(): op_jz(m_cpu, instr.dst(), true); break; case ops::JNZ.id(): op_jz(m_cpu, instr.dst(), false); break; case ops::JB.id(): op_jc(m_cpu, instr.dst(), true); break; case ops::JNB.id(): op_jc(m_cpu, instr.dst(), false); break; case ops::JA.id(): op_ja(m_cpu, instr.dst(), true); break; case ops::JNA.id(): op_ja(m_cpu, instr.dst(), false); break; case ops::JL.id(): op_jl(m_cpu, instr.dst(), true); break; case ops::JGE.id(): op_jl(m_cpu, instr.dst(), false); break; case ops::JG.id(): op_jg(m_cpu, instr.dst(), true); break; case ops::JLE.id(): op_jg(m_cpu, instr.dst(), false); break; case ops::JP.id(): op_jp(m_cpu, instr.dst(), true); break; case ops::JNP.id(): op_jp(m_cpu, instr.dst(), false); break; case ops::JCXZ.id(): op_jcxz(m_cpu, instr.mods(), instr.dst()); break; // TODO: check privs case ops::STI.id(): m_cpu.flags().setIF(true); break; case ops::CLI.id(): m_cpu.flags().clearIF(); break; case ops::CMC.id(): m_cpu.flags().setCF(!m_cpu.flags().CF()); break; case ops::STC.id(): m_cpu.flags().setCF(true); break; case ops::STD.id(): m_cpu.flags().setDF(true); break; case ops::CLC.id(): m_cpu.flags().clearCF(); break; case ops::CLD.id(): m_cpu.flags().clearDF(); break; case ops::LAHF.id(): m_cpu.ah() = m_cpu.flags().flags() & 0xFF; break; case ops::SAHF.id(): m_cpu.flags().setFrom(m_cpu.ah()); break; case ops::PUSHF.id(): { if(m_cpu.mode() == CPUMode::Long) { if(instr.mods().operandSizeOverride) m_cpu.push16(m_cpu.flags().flags()); else m_cpu.push64(m_cpu.flags().rflags() & 0xFFFF'FFFF'FFFC'0000); } else { switch(get_operand_size(m_cpu, instr.mods())) { case 16: m_cpu.push16(m_cpu.flags().flags()); break; case 32: m_cpu.push32(m_cpu.flags().eflags() & 0xFFFC'0000); break; default: assert(false); } } } break; case ops::POPF.id(): { assert(m_cpu.mode() == CPUMode::Real); switch(get_operand_size(m_cpu, instr.mods())) { case 16: m_cpu.flags().setFrom(m_cpu.pop16()); break; case 32: m_cpu.flags().setFrom(m_cpu.pop32()); break; default: assert(false); } } break; default: lg::fatal("exec", "invalid opcode: {}", print_att(instr, m_cpu.ip(), 0, 1)); break; } if(instr.lockPrefix()) m_cpu.memUnlock(); } int get_operand_size(CPU& cpu, const InstrMods& mods, bool default64) { // TODO: i think this is broken for 64-bit. if(cpu.mode() == CPUMode::Real) { return mods.operandSizeOverride ? 32 : 16; } else if(cpu.mode() == CPUMode::Prot || cpu.mode() == CPUMode::Long) { if(mods.operandSizeOverride) return 16; else if(mods.rex.W()) return 64; else return 32; } else { assert(false && "invalid cpu mode"); } assert(false && "invalid operand size"); return 0; } int get_address_size(CPU& cpu, const InstrMods& mods) { if(cpu.mode() == CPUMode::Real) { return mods.addressSizeOverride ? 32 : 16; } else if(cpu.mode() == CPUMode::Prot || cpu.mode() == CPUMode::Long) { if(mods.addressSizeOverride) return 16; else if(mods.rex.W()) return 64; else return 32; } else { assert(false && "invalid cpu mode"); } assert(false && "invalid address size"); return 0; } static SegReg convert_sreg(const Register& reg) { auto idx = reg.index(); assert(idx & instrad::x86::regs::REG_FLAG_SEGMENT); return static_cast<SegReg>(idx & 0x7); } std::pair<SegReg, uint64_t> resolve_memory_access(CPU& cpu, const instrad::x86::MemoryRef& mem) { auto seg = SegReg::DS; uint64_t ofs = 0; uint64_t idx = 0; if(mem.segment().present()) seg = convert_sreg(mem.segment()); if(cpu.mode() == CPUMode::Real) { ofs += mem.base().present() ? cpu.reg16(mem.base()) : 0; idx = mem.index().present() ? cpu.reg16(mem.index()) : 0; } else if(cpu.mode() == CPUMode::Prot) { ofs += mem.base().present() ? cpu.reg32(mem.base()) : 0; idx = mem.index().present() ? cpu.reg32(mem.index()) : 0; } else if(cpu.mode() == CPUMode::Long) { ofs += mem.base().present() ? cpu.reg64(mem.base()) : 0; idx = mem.index().present() ? cpu.reg64(mem.index()) : 0; } else { assert(false && "invalid cpu mode"); } ofs += mem.displacement(); ofs += idx * mem.scale(); // a little gross to repeat it here, but whatever... if(cpu.mode() == CPUMode::Real) ofs &= 0xFFFF; else if(cpu.mode() == CPUMode::Prot) ofs &= 0xFFFF'FFFF; else if(cpu.mode() == CPUMode::Long) ofs &= 0xFFFF'FFFF'FFFF'FFFF; else assert(false && "invalid cpu mode"); return { seg, ofs }; } Value get_operand(CPU& cpu, const InstrMods& mods, const Operand& op) { if(op.isRegister()) { switch(op.reg().width()) { case 8: return cpu.reg8(op.reg()); case 16: return cpu.reg16(op.reg()); case 32: return cpu.reg32(op.reg()); case 64: return cpu.reg64(op.reg()); } } else if(op.isImmediate()) { switch(op.immediateSize()) { case 8: return Value(static_cast<uint8_t>(op.imm())); case 16: return Value(static_cast<uint16_t>(op.imm())); case 32: return Value(static_cast<uint32_t>(op.imm())); case 64: return Value(static_cast<uint64_t>(op.imm())); } } else if(op.isMemory()) { auto [ seg, ofs ] = resolve_memory_access(cpu, op.mem()); switch(op.mem().bits()) { case 8: return cpu.read8(seg, ofs); case 16: return cpu.read16(seg, ofs); case 32: return cpu.read32(seg, ofs); case 64: return cpu.read64(seg, ofs); } } // note: i'm deliberately *NOT* handling FarOffset here, // because it's a little complicated, and in particular we might need to // return 80-bit values, so it's better to just let the (small) handful of // instructions that need it to handle it themselves. assert(false && "invalid operand kind"); return static_cast<uint64_t>(0); } void set_operand(CPU& cpu, const InstrMods& mods, const Operand& op, Value value) { if(op.isRegister()) { switch(op.reg().width()) { case 8: { uint8_t x = value.u8(); cpu.reg8(op.reg()) = x; return; } case 16: cpu.reg16(op.reg()) = value.u16(); return; case 32: cpu.reg32(op.reg()) = value.u32(); return; case 64: cpu.reg64(op.reg()) = value.u64(); return; } } else if(op.isMemory()) { auto [ seg, ofs ] = resolve_memory_access(cpu, op.mem()); switch(op.mem().bits()) { case 8: cpu.write8(seg, ofs, value.u8()); return; case 16: cpu.write16(seg, ofs, value.u16()); return; case 32: cpu.write32(seg, ofs, value.u32()); return; case 64: cpu.write64(seg, ofs, value.u64()); return; } } assert(false && "invalid destination operand kind"); } static void op_xchg(CPU& cpu, const InstrMods& mods, const Operand& dst, const Operand& src) { // xchg always asserts the lock signal cpu.memLock(); auto s = get_operand(cpu, mods, src); auto d = get_operand(cpu, mods, dst); set_operand(cpu, mods, dst, s); set_operand(cpu, mods, src, d); cpu.memUnlock(); } static void op_push(CPU& cpu, const InstrMods& mods, const Operand& src) { auto src_val = get_operand(cpu, mods, src); switch(src_val.bits()) { case 8: return cpu.push8(src_val.u8()); case 16: return cpu.push16(src_val.u16()); case 32: return cpu.push32(src_val.u32()); case 64: return cpu.push64(src_val.u64()); } assert(false && "owo"); } static void op_pop(CPU& cpu, const InstrMods& mods, const Operand& dst) { auto bits = get_operand_size(cpu, mods) / 8; switch(bits) { case 8: set_operand(cpu, mods, dst, cpu.pop8()); case 16: set_operand(cpu, mods, dst, cpu.pop16()); case 32: set_operand(cpu, mods, dst, cpu.pop32()); case 64: set_operand(cpu, mods, dst, cpu.pop64()); } assert(false && "owo"); } static void op_mov(CPU& cpu, const InstrMods& mods, const Operand& dst, const Operand& src) { auto src_val = get_operand(cpu, mods, src); set_operand(cpu, mods, dst, src_val); } }
32.372796
121
0.569561
zhiayang
662078f2d9bfcbb447007249e862c143c63ef57d
214
cpp
C++
code/math/berlekamp-massey/debug.cpp
tonowak/acmlib
ec295b8c76c588914475ad42cff81a64a6f2ebd5
[ "MIT" ]
6
2019-06-25T14:07:08.000Z
2022-01-04T12:28:55.000Z
code/math/berlekamp-massey/debug.cpp
tonowak/acmlib
ec295b8c76c588914475ad42cff81a64a6f2ebd5
[ "MIT" ]
null
null
null
code/math/berlekamp-massey/debug.cpp
tonowak/acmlib
ec295b8c76c588914475ad42cff81a64a6f2ebd5
[ "MIT" ]
1
2021-11-12T01:40:38.000Z
2021-11-12T01:40:38.000Z
#include "../../utils/headers/main.cpp" #include "main.cpp" int main() { int n; cin >> n; vector<int> x(n); REP(i, n) cin >> x[i]; BerlekampMassey<int(1e9 + 696969)> bm(x); REP(k, 10) debug(k, bm.get(k)); }
16.461538
42
0.579439
tonowak
6622435f34c754ba5066588df2344014e217b585
4,999
cc
C++
test/random/curand/CurandPerformance.test.cc
whokion/celeritas
9e1cf3ec6b7b5a15c5bc197959f105d6a02e6612
[ "Apache-2.0", "MIT" ]
22
2020-03-31T14:18:22.000Z
2022-01-10T09:43:06.000Z
test/random/curand/CurandPerformance.test.cc
whokion/celeritas
9e1cf3ec6b7b5a15c5bc197959f105d6a02e6612
[ "Apache-2.0", "MIT" ]
261
2020-04-29T15:14:29.000Z
2022-03-31T19:07:14.000Z
test/random/curand/CurandPerformance.test.cc
whokion/celeritas
9e1cf3ec6b7b5a15c5bc197959f105d6a02e6612
[ "Apache-2.0", "MIT" ]
15
2020-05-01T19:47:19.000Z
2021-12-25T06:12:09.000Z
//----------------------------------*-C++-*----------------------------------// // Copyright 2020 UT-Battelle, LLC, and other Celeritas developers. // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: (Apache-2.0 OR MIT) //---------------------------------------------------------------------------// //! \file CurandPerformance.test.cc //---------------------------------------------------------------------------// #include "CurandPerformance.test.hh" #include "base/Range.hh" #include "random/RngData.hh" #include "random/DiagnosticRngEngine.hh" #include "random/distributions/GenerateCanonical.hh" #include "celeritas_test.hh" using namespace celeritas_test; using celeritas::range; //---------------------------------------------------------------------------// // TEST HARNESS //---------------------------------------------------------------------------// class CurandTest : public celeritas::Test { protected: void SetUp() override { // Test parameters on the host test_params.nsamples = 1.e+7; test_params.nblocks = 1; test_params.nthreads = 1; test_params.seed = 12345u; test_params.tolerance = 1.0e-3; } template<typename T> void check_mean_host() { T devStates; curand_init(test_params.seed, 0, 0, &devStates); double sum = 0; double sum2 = 0; for (CELER_MAYBE_UNUSED auto i : range(test_params.nsamples)) { double u01 = curand_uniform(&devStates); sum += u01; sum2 += u01 * u01; } double mean = sum / test_params.nsamples; double variance = sum2 / test_params.nsamples - mean * mean; EXPECT_SOFT_NEAR(mean, 0.5, test_params.tolerance); EXPECT_SOFT_NEAR(variance, 1 / 12., test_params.tolerance); } protected: // Test parameters TestParams test_params; }; //---------------------------------------------------------------------------// // HOST TESTS //---------------------------------------------------------------------------// #if CELERITAS_USE_CUDA TEST_F(CurandTest, curand_xorwow_host) { // XORWOW (default) generator this->check_mean_host<curandState>(); } TEST_F(CurandTest, curand_mrg32k3a_host) { // MRG32k3a generator this->check_mean_host<curandStateMRG32k3a>(); } TEST_F(CurandTest, curand_philox4_32_10_host) { // Philox4_32_10 generator this->check_mean_host<curandStatePhilox4_32_10_t>(); } #endif TEST_F(CurandTest, std_mt19937_host) { // Mersenne Twister generator auto rng = DiagnosticRngEngine<std::mt19937>(); double sum = 0; double sum2 = 0; for (CELER_MAYBE_UNUSED auto i : range(test_params.nsamples)) { double u01 = celeritas::generate_canonical<double>(rng); sum += u01; sum2 += u01 * u01; } double mean = sum / test_params.nsamples; double variance = sum2 / test_params.nsamples - mean * mean; EXPECT_SOFT_NEAR(mean, 0.5, test_params.tolerance); EXPECT_SOFT_NEAR(variance, 1 / 12., test_params.tolerance); } //---------------------------------------------------------------------------// // DEVICE TESTS //---------------------------------------------------------------------------// #if CELERITAS_USE_CUDA class CurandDeviceTest : public CurandTest { void SetUp() override { // Test parameters on the device (100 * host nsamples) test_params.nsamples = 1.e+9; test_params.nblocks = 64; test_params.nthreads = 256; test_params.seed = 12345u; test_params.tolerance = 1.0e-3; } public: void check_mean_device(TestOutput result) { double sum_total = 0; double sum2_total = 0; for (auto i : range(test_params.nblocks * test_params.nthreads)) { sum_total += result.sum[i]; sum2_total += result.sum2[i]; } double mean = sum_total / test_params.nsamples; double variance = sum2_total / test_params.nsamples - mean * mean; EXPECT_SOFT_NEAR(mean, 0.5, test_params.tolerance); EXPECT_SOFT_NEAR(variance, 1 / 12., test_params.tolerance); } }; TEST_F(CurandDeviceTest, curand_xorwow_device) { // XORWOW (default) generator auto output = curand_test<curandState>(test_params); this->check_mean_device(output); } TEST_F(CurandDeviceTest, curand_mrg32k3a_device) { // MRG32k3a generator auto output = curand_test<curandStateMRG32k3a>(test_params); this->check_mean_device(output); } TEST_F(CurandDeviceTest, curand_philox4_32_10_t_device) { // Philox4_32_10 generator auto output = curand_test<curandStatePhilox4_32_10_t>(test_params); this->check_mean_device(output); } TEST_F(CurandDeviceTest, curand_mtgp32_device) { // MTGP32-11213 (Mersenne Twister RNG for the GPU) auto output = curand_test<curandStateMtgp32>(test_params); this->check_mean_device(output); } #endif
29.405882
79
0.572515
whokion
6626884e716c12e8f453565c75b52c851941e1f3
1,312
cpp
C++
Cmds/baseFeatures.cpp
jli860/tnvme
208943be96c0fe073ed97a7098c0b00a2776ebf9
[ "Apache-2.0" ]
34
2015-03-09T17:54:24.000Z
2022-02-03T03:40:08.000Z
Cmds/baseFeatures.cpp
jli860/tnvme
208943be96c0fe073ed97a7098c0b00a2776ebf9
[ "Apache-2.0" ]
13
2015-05-20T02:21:09.000Z
2019-02-13T19:57:20.000Z
Cmds/baseFeatures.cpp
jli860/tnvme
208943be96c0fe073ed97a7098c0b00a2776ebf9
[ "Apache-2.0" ]
53
2015-03-13T02:46:24.000Z
2021-11-17T07:34:04.000Z
/* * Copyright (c) 2011, Intel Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "baseFeatures.h" #include "featureDefs.h" #define ZZ(a,b) b, const uint8_t FID[] = { FEATURE_TABLE FID_FENCE // always must be the last element }; const uint32_t FID_RES[] = { FEATURE_RESERVE_TABLE FID_FENCE }; #undef ZZ BaseFeatures::BaseFeatures() : Cmd(Trackable::OBJTYPE_FENCE) { // This constructor will throw } BaseFeatures::BaseFeatures(Trackable::ObjType objBeingCreated) : Cmd(objBeingCreated) { } BaseFeatures::~BaseFeatures() { } void BaseFeatures::SetFID(uint8_t fid) { LOG_NRM("Setting FID: 0x%02X", fid); SetByte(fid, 10, 0); } uint8_t BaseFeatures::GetFID() const { LOG_NRM("Getting FID"); return GetByte(10, 0); }
20.5
76
0.700457
jli860
662fcd4bc7ee63a550178422787435d8cf592569
7,290
hpp
C++
src/mem_datasource.hpp
calvinmetcalf/node-mapnik
3d26f2089dee3cfc901965f6646d50004a0e0e56
[ "BSD-3-Clause" ]
null
null
null
src/mem_datasource.hpp
calvinmetcalf/node-mapnik
3d26f2089dee3cfc901965f6646d50004a0e0e56
[ "BSD-3-Clause" ]
null
null
null
src/mem_datasource.hpp
calvinmetcalf/node-mapnik
3d26f2089dee3cfc901965f6646d50004a0e0e56
[ "BSD-3-Clause" ]
null
null
null
#ifndef __NODE_MAPNIK_MEM_DATASOURCE_H__ #define __NODE_MAPNIK_MEM_DATASOURCE_H__ #include <v8.h> #include <node.h> #include <node_object_wrap.h> using namespace v8; // mapnik #include <mapnik/box2d.hpp> #include <mapnik/query.hpp> #include <mapnik/params.hpp> #include <mapnik/sql_utils.hpp> #include <mapnik/datasource.hpp> #include <mapnik/feature_factory.hpp> #include <mapnik/value_types.hpp> // boost #include <boost/scoped_ptr.hpp> // stl #include <vector> #include <algorithm> class js_datasource : public mapnik::datasource { friend class js_featureset; public: js_datasource(const mapnik::parameters &params, Local<Value> cb); virtual ~js_datasource(); mapnik::datasource::datasource_t type() const; mapnik::featureset_ptr features(const mapnik::query& q) const; mapnik::featureset_ptr features_at_point(mapnik::coord2d const& pt) const; mapnik::box2d<double> envelope() const; boost::optional<mapnik::datasource::geometry_t> get_geometry_type() const; mapnik::layer_descriptor get_descriptor() const; size_t size() const; Persistent<Function> cb_; private: mutable mapnik::layer_descriptor desc_; mapnik::box2d<double> ext_; }; js_datasource::js_datasource(const mapnik::parameters &params, Local<Value> cb) : datasource (params), desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8")) { cb_ = Persistent<Function>::New(Handle<Function>::Cast(cb)); boost::optional<std::string> ext = params.get<std::string>("extent"); if (ext) ext_.from_string(*ext); else throw mapnik::datasource_exception("JSDatasource missing <extent> parameter"); } js_datasource::~js_datasource() { cb_.Dispose(); } mapnik::datasource::datasource_t js_datasource::type() const { return mapnik::datasource::Vector; } mapnik::box2d<double> js_datasource::envelope() const { return ext_; } boost::optional<mapnik::datasource::geometry_t> js_datasource::get_geometry_type() const { return boost::optional<mapnik::datasource::geometry_t>(); } mapnik::layer_descriptor js_datasource::get_descriptor() const { return mapnik::layer_descriptor("in-memory js datasource","utf-8"); } size_t js_datasource::size() const { return 0;//features_.size(); } class js_featureset : public mapnik::Featureset { public: js_featureset( const mapnik::query& q, const js_datasource* ds) : q_(q), feature_id_(1), tr_(new mapnik::transcoder("utf-8")), ds_(ds), obj_(Object::New()) { Local<Array> a = Array::New(4); mapnik::box2d<double> const& e = q_.get_bbox(); a->Set(0, Number::New(e.minx())); a->Set(1, Number::New(e.miny())); a->Set(2, Number::New(e.maxx())); a->Set(3, Number::New(e.maxy())); obj_->Set(String::NewSymbol("extent"), a); } virtual ~js_featureset() {} mapnik::feature_ptr next() { HandleScope scope; TryCatch try_catch; Local<Value> argv[2] = { Integer::New(feature_id_), obj_ }; Local<Value> val = ds_->cb_->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) { node::FatalException(try_catch); } else { if (!val->IsUndefined()) { if (val->IsObject()) { Local<Object> obj = val->ToObject(); if (obj->Has(String::New("x")) && obj->Has(String::New("y"))) { Local<Value> x = obj->Get(String::New("x")); Local<Value> y = obj->Get(String::New("y")); if (!x->IsUndefined() && x->IsNumber() && !y->IsUndefined() && y->IsNumber()) { mapnik::geometry_type * pt = new mapnik::geometry_type(mapnik::Point); pt->move_to(x->NumberValue(),y->NumberValue()); mapnik::context_ptr ctx = boost::make_shared<mapnik::context_type>(); mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx,feature_id_)); ++feature_id_; feature->add_geometry(pt); if (obj->Has(String::New("properties"))) { Local<Value> props = obj->Get(String::New("properties")); if (props->IsObject()) { Local<Object> p_obj = props->ToObject(); Local<Array> names = p_obj->GetPropertyNames(); unsigned int i = 0; unsigned int a_length = names->Length(); while (i < a_length) { Local<Value> name = names->Get(i)->ToString(); // if name in q.property_names() ? Local<Value> value = p_obj->Get(name); if (value->IsString()) { mapnik::value_unicode_string ustr = tr_->transcode(TOSTR(value)); feature->put_new(TOSTR(name),ustr); } else if (value->IsNumber()) { double num = value->NumberValue(); // todo - round if (num == value->IntegerValue()) { int integer = value->IntegerValue(); feature->put_new(TOSTR(name),integer); } else { double dub_val = value->NumberValue(); feature->put_new(TOSTR(name),dub_val); } } i++; } } } return feature; } } } } } return mapnik::feature_ptr(); } private: mapnik::query const& q_; unsigned int feature_id_; boost::scoped_ptr<mapnik::transcoder> tr_; const js_datasource* ds_; Local<Object> obj_; }; mapnik::featureset_ptr js_datasource::features(const mapnik::query& q) const { return mapnik::featureset_ptr(new js_featureset(q,this)); } mapnik::featureset_ptr js_datasource::features_at_point(mapnik::coord2d const& pt) const { /* box2d<double> box = box2d<double>(pt.x, pt.y, pt.x, pt.y); #ifdef MAPNIK_DEBUG std::clog << "box=" << box << ", pt x=" << pt.x << ", y=" << pt.y << "\n"; #endif return featureset_ptr(new memory_featureset(box,*this)); */ return mapnik::featureset_ptr(); } #endif // __NODE_MAPNIK_MEM_DATASOURCE_H__
33.906977
109
0.510562
calvinmetcalf
66317a8c0d391f473cfc537c75d00f2dffd6d0a9
5,583
cpp
C++
examples/bloom_filter/src/BloomFilter.cpp
swoole/phpx
3beb558f4ebed4660f0795fd98b193a350f924f6
[ "Apache-2.0" ]
213
2018-08-25T05:43:40.000Z
2021-05-04T11:40:19.000Z
examples/bloom_filter/src/BloomFilter.cpp
swoole/phpx
3beb558f4ebed4660f0795fd98b193a350f924f6
[ "Apache-2.0" ]
25
2018-09-09T05:54:59.000Z
2021-02-22T05:09:54.000Z
examples/bloom_filter/src/BloomFilter.cpp
swoole/phpx
3beb558f4ebed4660f0795fd98b193a350f924f6
[ "Apache-2.0" ]
41
2018-08-29T08:34:07.000Z
2021-03-08T15:12:27.000Z
#include "phpx.h" #include "ext/swoole/include/swoole.h" #include "ext/swoole/include/swoole_lock.h" #include "ext/swoole/include/swoole_file.h" #include "ext/swoole/ext-src/php_swoole.h" extern "C" { extern void MurmurHash3_x64_128(const void *key, const int len, const uint32_t seed, void *out); extern void SpookyHash128( const void *key, size_t len, uint64_t seed1, uint64_t seed2, uint64_t *hash1, uint64_t *hash2); } BEGIN_EXTERN_C() #if PHP_VERSION_ID < 80000 #include "BloomFilter_arginfo.h" #else #include "BloomFilter_arginfo.h" #endif END_EXTERN_C() #include <iostream> using namespace php; using namespace std; using swoole::File; using swoole::RWLock; struct BloomFilterObject { size_t capacity; char *array; uint32_t k_num; uint64_t bit_num; uint64_t *hashes; RWLock *lock; }; #define RESOURCE_NAME "BloomFilterResource" #define PROPERTY_NAME "ptr" static void compute_hashes(uint32_t k_num, char *key, size_t len, uint64_t *hashes) { uint64_t out[2]; MurmurHash3_x64_128(key, len, 0, out); hashes[0] = out[0]; hashes[1] = out[1]; uint64_t *hash1 = out; uint64_t *hash2 = hash1 + 1; SpookyHash128(key, len, 0, 0, hash1, hash2); hashes[2] = out[0]; hashes[3] = out[1]; for (uint32_t i = 4; i < k_num; i++) { hashes[i] = hashes[1] + ((i * hashes[3]) % 18446744073709551557U); } } static void BloomFilterResDtor(zend_resource *res) { BloomFilterObject *bf = static_cast<BloomFilterObject *>(res->ptr); efree(bf->hashes); delete bf->lock; sw_shm_free(bf); } PHPX_METHOD(BloomFilter, __construct) { long capacity = args[0].toInt(); if (capacity <= 0) { capacity = 65536; } uint32_t k_num = 2; if (args.exists(1)) { k_num = (uint32_t) args[1].toInt(); } BloomFilterObject *bf = (BloomFilterObject *) sw_shm_malloc(sizeof(BloomFilterObject) + capacity); if (bf == NULL) { throwException("RuntimeException", "sw_shm_malloc() failed."); } bf->capacity = capacity; bf->array = (char *) (bf + 1); bzero(bf->array, bf->capacity); bf->hashes = (uint64_t *) ecalloc(k_num, sizeof(uint64_t)); if (bf->hashes == NULL) { throwException("RuntimeException", "ecalloc() failed."); } bf->bit_num = bf->capacity * 8; bf->k_num = k_num; bf->lock = new RWLock(1); _this.oSet(PROPERTY_NAME, RESOURCE_NAME, bf); } PHPX_METHOD(BloomFilter, has) { BloomFilterObject *bf = _this.oGet<BloomFilterObject>(PROPERTY_NAME, RESOURCE_NAME); auto key = args[0]; compute_hashes(bf->k_num, key.toCString(), key.length(), bf->hashes); uint32_t i; uint32_t n; bool miss; bf->lock->lock_rd(); for (i = 0; i < bf->k_num; i++) { n = bf->hashes[i] % bf->bit_num; miss = !(bf->array[n / 8] & (1 << (n % 8))); if (miss) { bf->lock->unlock(); retval = false; return; } } bf->lock->unlock(); retval = true; } PHPX_METHOD(BloomFilter, add) { BloomFilterObject *bf = _this.oGet<BloomFilterObject>(PROPERTY_NAME, RESOURCE_NAME); auto key = args[0]; compute_hashes(bf->k_num, key.toCString(), key.length(), bf->hashes); uint32_t i; uint32_t n; bf->lock->lock(); for (i = 0; i < bf->k_num; i++) { n = bf->hashes[i] % bf->bit_num; bf->array[n / 8] |= (1 << (n % 8)); } bf->lock->unlock(); } PHPX_METHOD(BloomFilter, clear) { BloomFilterObject *bf = _this.oGet<BloomFilterObject>(PROPERTY_NAME, RESOURCE_NAME); bf->lock->lock(); bzero(bf->array, bf->capacity); bf->lock->unlock(); } PHPX_METHOD(BloomFilter, dump) { BloomFilterObject *bf = _this.oGet<BloomFilterObject>(PROPERTY_NAME, RESOURCE_NAME); auto file = args[0].toCString(); bf->lock->lock(); File fp(file, File::CREATE | File::WRITE, 0644); if (!fp.ready()) { fail: bf->lock->unlock(); retval = false; return; } if (fp.write(&bf->capacity, sizeof(bf->capacity)) == 0) { goto fail; } if (fp.write(bf->array, bf->capacity) == 0) { goto fail; } bf->lock->unlock(); retval = true; } PHPX_METHOD(BloomFilter, load) { auto file = args[0].toCString(); File fp(file, File::READ); if (!fp.ready()) { fail: retval = false; return; } size_t capacity = 0; if (fp.read(&capacity, sizeof(capacity)) == 0) { goto fail; } long filesize = fp.get_size(); if (filesize < 0 || filesize < capacity + sizeof(capacity)) { goto fail; } auto o = newObject("BloomFilter", (long) capacity); BloomFilterObject *bf = o.oGet<BloomFilterObject>(PROPERTY_NAME, RESOURCE_NAME); if (fp.read(bf->array, capacity) == 0) { goto fail; } retval = o; } PHPX_EXTENSION() { Extension *extension = new Extension("BloomFilter", "1.0.2"); extension->onStart = [extension]() noexcept { extension->registerConstant("BLOOMFILTER_VERSION", 10002); Class *c = new Class("BloomFilter"); c->registerFunctions(class_BloomFilter_methods); extension->registerClass(c); extension->registerResource(RESOURCE_NAME, BloomFilterResDtor); }; extension->require("swoole"); extension->info({"BloomFilter support", "enabled"}, { {"author", "Tianfeng Han"}, {"version", extension->version}, {"date", "2021-02-07"}, }); return extension; }
26.211268
102
0.602543
swoole
6636fcb78f0da9773abd1c90dfae28a58bedb03f
401
cpp
C++
Sources/thread-oop/main.cpp
igarcerant/curso_cpp_2021
97c4a44fda2917d159e4ae809cc0c2a7e4fb9d16
[ "MIT" ]
null
null
null
Sources/thread-oop/main.cpp
igarcerant/curso_cpp_2021
97c4a44fda2917d159e4ae809cc0c2a7e4fb9d16
[ "MIT" ]
null
null
null
Sources/thread-oop/main.cpp
igarcerant/curso_cpp_2021
97c4a44fda2917d159e4ae809cc0c2a7e4fb9d16
[ "MIT" ]
null
null
null
#include <iostream> #include <thread> #include <string> class Salutator { public: void saludar(std::string name, int times); }; void Salutator::saludar(std::string name, int times) { for(int i=0; i<times; i++) { std::cout << i << ": hello, " << name << "!" << std::endl; } } auto main() -> int { Salutator salut; std::thread th(&Salutator::saludar, salut, "mexico", 5); th.join(); }
13.827586
60
0.605985
igarcerant
663797e7995b05f9aaa50f86293786e3fd6d91bf
773
cpp
C++
_0707_div2/C_Going_Home.cpp
mingweihe/codeforces
8395d68a09373775009b76dbde189ce5bbba58ae
[ "MIT" ]
null
null
null
_0707_div2/C_Going_Home.cpp
mingweihe/codeforces
8395d68a09373775009b76dbde189ce5bbba58ae
[ "MIT" ]
null
null
null
_0707_div2/C_Going_Home.cpp
mingweihe/codeforces
8395d68a09373775009b76dbde189ce5bbba58ae
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int n; int a[200001], x[5000001], y[5000001]; // pigeonhole principle, O(n) time return for qualified input data void solve(){ cin >> n; for(int i = 1; i <= n; ++i) cin >> a[i]; memset(x, 0, sizeof(x)); memset(y, 0, sizeof(y)); for(int i = 1; i < n; ++i){ for(int j = i+1; j <= n; ++j){ int s = a[i] + a[j]; if(x[s] && x[s] != i && x[s] != j && y[s] != i && y[s] != j){ cout << "YES" << '\n'; cout << x[s] << ' ' << y[s] << ' ' << i << ' ' << j << '\n'; return; } x[s] = i, y[s] = j; } } cout << "NO" << '\n'; } int main(){ ios::sync_with_stdio(0); cin.tie(0); solve(); }
24.15625
76
0.384217
mingweihe
6643314eb2e52bc8a69dca09ab2e2ef51cf5e11c
1,160
hpp
C++
plugins/terrain_plugin/include/TerrainQuadtree.hpp
fuchstraumer/Caelestis
9c4b76288220681bb245d84e5d7bf8c7f69b2716
[ "MIT" ]
5
2018-08-16T00:55:33.000Z
2020-06-19T14:30:17.000Z
plugins/terrain_plugin/include/TerrainQuadtree.hpp
fuchstraumer/Caelestis
9c4b76288220681bb245d84e5d7bf8c7f69b2716
[ "MIT" ]
null
null
null
plugins/terrain_plugin/include/TerrainQuadtree.hpp
fuchstraumer/Caelestis
9c4b76288220681bb245d84e5d7bf8c7f69b2716
[ "MIT" ]
null
null
null
#pragma once #ifndef TERRAIN_PLUGIN_QUADTREE_HPP #define TERRAIN_PLUGIN_QUADTREE_HPP #include "ForwardDecl.hpp" #include "glm/vec3.hpp" #include "glm/mat4x4.hpp" #include <unordered_map> #include <memory> #include <vulkan/vulkan.h> class HeightNode; class TerrainNode; class TerrainQuadtree { TerrainQuadtree(const TerrainQuadtree&) = delete; TerrainQuadtree& operator=(const TerrainQuadtree&) = delete; public: TerrainQuadtree(const vpr::Device* device, const float& split_factor, const size_t& max_detail_level, const double& root_side_length, const glm::vec3& root_tile_position); void SetupNodePipeline(const VkRenderPass& renderpass, const glm::mat4& projection); void UpdateQuadtree(const glm::vec3 & camera_position, const glm::mat4& view); void RenderNodes(VkCommandBuffer& graphics_cmd, VkCommandBufferBeginInfo& begin_info, const glm::mat4& view, const glm::vec3& camera_pos, const VkViewport& viewport, const VkRect2D& rect); private: std::unique_ptr<TerrainNode> root; std::unordered_map<glm::ivec3, std::shared_ptr<HeightNode>> cachedHeightData; size_t MaxLOD; }; #endif // !TERRAIN_PLUGIN_QUADTREE_HPP
34.117647
192
0.776724
fuchstraumer
6643f8daf3ed7a59e05d29becc0c3db22161fc59
8,700
cpp
C++
sta-src/Astro-Core/cartesianTOrotating.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
6
2018-09-05T12:41:59.000Z
2021-07-01T05:34:23.000Z
sta-src/Astro-Core/cartesianTOrotating.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
2
2015-02-07T19:09:21.000Z
2015-08-14T03:15:42.000Z
sta-src/Astro-Core/cartesianTOrotating.cpp
hoehnp/SpaceDesignTool
9abd34048274b2ce9dbbb685124177b02d6a34ca
[ "IJG" ]
2
2015-03-25T15:50:31.000Z
2017-12-06T12:16:47.000Z
/* This program 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 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU Lesser General Public License can also be found on the world wide web at http://www.gnu.org. ------ Copyright (C) 2009 European Space Agency (space.trajectory.analysis AT gmail.com) ---- ------------------ Author: Valentino Zuccarelli ------------------------------------------------- ------------------ E-mail: (Valentino.Zuccarelli@gmail.com) ---------------------------- */ #include "cartesianTOrotating.h" #include "stabody.h" #include "stamath.h" #include "threebodyParametersComputation.h" #include "ascendingNode.h" #include <QDebug> /* this subroutine allows to go from the inertial body centred (usually: Sun or Earth) to the normalized co-rotating r.f. defined in the 3b-problem. */ sta::StateVector cartesianTOrotating (int mode, const StaBody* firstbody, const StaBody* secondbody, sta::StateVector cartesian, double JD) { sta::StateVector rotating; const StaBody* sun = STA_SOLAR_SYSTEM->sun(); double mu1=getGravParam_user(sun->mu(), secondbody->mu()); double mu2=getGravParam_user(firstbody->mu(),secondbody->mu()); //double velocity1=secondbody->linearV(); double velocity1=sqrt(sun->mu()/secondbody->distance()); //ephemerides of the 2nd body relative to the Sun Eigen::Vector3d positionBody2 = secondbody->stateVector(JD, sun, sta::COORDSYS_EME_J2000).position; Eigen::Vector3d velocityBody2 = secondbody->stateVector(JD, sun, sta::COORDSYS_EME_J2000).velocity; velocity1=velocityBody2.norm(); //velocity1=secondbody->stateVector(JD, sun, sta::COORDSYS_EME_J2000).velocity.norm(); double distance1=positionBody2.norm(); double i; double alfa=0; double beta=0; Eigen::Vector3d baricenter; //coefficients for coming computations //double A, B, a, b, c; if (firstbody != sun) //we are considering a system like Earth-Moon or Saturn-Titan (the Sun is NOT the first body!) { //qDebug()<<"CASE 1: NO SUN"; //velocity1=sqrt(firstbody->mu()/secondbody->distance()); Eigen::Vector3d positionBody1 = firstbody->stateVector(JD, sun, sta::COORDSYS_EME_J2000).position; Eigen::Vector3d positionBody1_Body2 = positionBody2 - positionBody1; //distance1=secondbody->distance()-firstbody->distance(); distance1=positionBody1_Body2.norm(); Eigen::Vector3d velocityBody1 = firstbody->stateVector(JD, sun, sta::COORDSYS_EME_J2000).velocity; Eigen::Vector3d velocityBody2 = secondbody->stateVector(JD, sun, sta::COORDSYS_EME_J2000).velocity; Eigen::Vector3d velocityBody1_Body2 = velocityBody2 - velocityBody1; velocity1=velocityBody1_Body2.norm(); //alfa = acos (positionBody1_Body2.z()/distance2); double nodeJD; ascendingNodeAngle (firstbody, secondbody, JD, nodeJD, alfa); beta=trueAnomalyFromAscNode (firstbody, secondbody, JD, nodeJD, alfa); //beta = atan2 (sqrt(pow(positionBody1_Body2.x(),2.0)+pow(positionBody1_Body2.y(),2.0)),positionBody1_Body2.z()); //alfa = atan2 (positionBody1_Body2.y(), positionBody1_Body2.x()); Eigen::Vector3d velocityCart=secondbody->stateVector(JD, firstbody, sta::COORDSYS_EME_J2000).velocity; Eigen::Vector3d crossProd=positionBody1_Body2.cross(velocityCart); //double inclinationReq; i=acos(crossProd(2)/crossProd.norm()); //qDebug()<<sta::radToDeg(i); //mu1=mu2; if (mode==0 || mode==1 || mode==3) //the initial orbit was around the 1st body { baricenter(0)= (-mu2);//*cos(beta)*sin(alfa); baricenter(1)= (mu2)*sin(beta)*sin(alfa); baricenter(2)= (mu2)*cos(alfa); //a=b=c=0; } else if (mode==2 || mode==4) //the initial orbit was around the 2nd body { baricenter(0)= (+1-mu2);//*cos(beta)*sin(alfa); baricenter(1)= (-1+mu2)*sin(beta)*sin(alfa); baricenter(2)= (-1+mu2)*cos(alfa); //a=b=c=0; } //A=-1/cos(alfa)*((cartesian.position.x()/distance1-baricenter(0))*cos(beta)+(cartesian.position.y()/distance1-baricenter(1))*sin(beta)); //B=1/(cos(beta)*sin(alfa))*((cartesian.position.y()/distance1-baricenter(1))*sin(alfa)+(cartesian.position.z()/distance1-baricenter(2))*sin(beta)*cos(alfa)); rotating.position.x()=(cartesian.position.x()*(cos(alfa)*cos(beta)-cos(i)*sin(alfa)*sin(beta))+cartesian.position.y()*(cos(alfa)*sin(beta)*cos(i)+sin(alfa)*cos(beta))+cartesian.position.z()*sin(i)*sin(beta))/distance1+baricenter(0); rotating.position.y()=(cartesian.position.x()*(-cos(i)*sin(alfa)*cos(beta)-cos(alfa)*sin(beta))+cartesian.position.y()*(cos(i)*cos(alfa)*cos(beta)-sin(alfa)*sin(beta))+cartesian.position.z()*(sin(i)*cos(beta)))/distance1; rotating.position.z()=(cartesian.position.x()*(sin(i)*sin(alfa))-cartesian.position.y()*(sin(i)*cos(alfa))+cartesian.position.z()*cos(i))/distance1; } else { //same transformation applied to a Sun-body system. This has to be done in any case //position of body 2 relative to body1 //qDebug()<<"CASE 2: SUN"; //alfa = acos (positionBody2.z()/distance1); double nodeJD; ascendingNodeAngle (firstbody, secondbody, JD, nodeJD, alfa); beta=trueAnomalyFromAscNode (firstbody, secondbody, JD, nodeJD, alfa); Eigen::Vector3d velocityCart=secondbody->stateVector(JD, firstbody, sta::COORDSYS_EME_J2000).velocity; Eigen::Vector3d crossProd=positionBody2.cross(velocityCart); //double inclinationReq; i=acos(crossProd(2)/crossProd.norm()); if (mode==0 || mode==1 || mode==3) //the initial orbit was around the 1st body { baricenter(0)= (-mu1);//*cos(beta)*sin(alfa); baricenter(1)= (mu1)*sin(beta)*sin(alfa); baricenter(2)= (mu1)*cos(alfa); //a=b=c=0; } else if (mode==2 || mode==4) //the initial orbit was around the 2nd body { baricenter(0)= (+1-mu1);//*cos(beta)*sin(alfa); baricenter(1)= (-1+mu1)*sin(beta)*sin(alfa); baricenter(2)= (-1+mu1)*cos(alfa); //a=b=c=0; } //A=-1/cos(alfa)*((cartesian.position.x()/distance1-baricenter(0))*cos(beta)+(cartesian.position.y()/distance1-baricenter(1))*sin(beta)); //B=1/(cos(beta)*sin(alfa))*((cartesian.position.y()/distance1-baricenter(1))*sin(alfa)+(cartesian.position.z()/distance1-baricenter(2))*sin(beta)*cos(alfa)); rotating.position.x()=(cartesian.position.x()*(cos(alfa)*cos(beta)-cos(i)*sin(alfa)*sin(beta))+cartesian.position.y()*(cos(alfa)*sin(beta)*cos(i)+sin(alfa)*cos(beta))+cartesian.position.z()*sin(i)*sin(beta))/distance1+baricenter(0); rotating.position.y()=(cartesian.position.x()*(-cos(i)*sin(alfa)*cos(beta)-cos(alfa)*sin(beta))+cartesian.position.y()*(cos(i)*cos(alfa)*cos(beta)-sin(alfa)*sin(beta))+cartesian.position.z()*(sin(i)*cos(beta)))/distance1; rotating.position.z()=(cartesian.position.x()*(sin(i)*sin(alfa))-cartesian.position.y()*(sin(i)*cos(alfa))+cartesian.position.z()*cos(i))/distance1; } //A=-1/cos(alfa)*((cartesian.velocity.x()/velocity1)*cos(beta)+(cartesian.velocity.y()/velocity1)*sin(beta)); //B=1/(cos(beta)*sin(alfa))*((cartesian.velocity.y()/velocity1)*sin(alfa)+(cartesian.velocity.z()/velocity1)*sin(beta)*cos(alfa)); rotating.velocity.x()=(cartesian.velocity.x()*(cos(alfa)*cos(beta)-cos(i)*sin(alfa)*sin(beta))+cartesian.velocity.y()*(cos(alfa)*sin(beta)*cos(i)+sin(alfa)*cos(beta))+cartesian.velocity.z()*sin(i)*sin(beta))/velocity1; rotating.velocity.y()=(cartesian.velocity.x()*(-cos(i)*sin(alfa)*cos(beta)-cos(alfa)*sin(beta))+cartesian.velocity.y()*(cos(i)*cos(alfa)*cos(beta)-sin(alfa)*sin(beta))+cartesian.velocity.z()*(sin(i)*cos(beta)))/velocity1; rotating.velocity.z()=(cartesian.velocity.x()*(sin(i)*sin(alfa))-cartesian.velocity.y()*(sin(i)*cos(alfa))+cartesian.velocity.z()*cos(i))/velocity1; return rotating; }
58.783784
240
0.661034
hoehnp
66466076d3c21cacd2d367ed0ca33b82af0d74b8
36,780
cpp
C++
CLucene/core/CLucene/index/SegmentInfos.cpp
asheeshv/CLucene-iOS-Android-Win8
46d3728178c59842472d43ebbb814375713ca7fa
[ "Apache-1.1" ]
2
2015-06-23T13:22:17.000Z
2019-04-28T06:35:02.000Z
CLucene/core/CLucene/index/SegmentInfos.cpp
asheeshv/CLucene-iOS-Android-Win8
46d3728178c59842472d43ebbb814375713ca7fa
[ "Apache-1.1" ]
null
null
null
CLucene/core/CLucene/index/SegmentInfos.cpp
asheeshv/CLucene-iOS-Android-Win8
46d3728178c59842472d43ebbb814375713ca7fa
[ "Apache-1.1" ]
null
null
null
/*------------------------------------------------------------------------------ * Copyright (C) 2003-2006 Ben van Klinken and the CLucene Team * * Distributable under the terms of either the Apache License (Version 2.0) or * the GNU Lesser General Public License, as specified in the COPYING file. ------------------------------------------------------------------------------*/ #include "CLucene/_ApiHeader.h" #include "_SegmentInfos.h" #include "_IndexFileNames.h" #include "_SegmentHeader.h" #include "MultiReader.h" #include <assert.h> #include <iostream> #include "CLucene/store/Directory.h" #include "CLucene/util/Misc.h" CL_NS_USE(store) CL_NS_USE(util) CL_NS_DEF(index) SegmentInfo::SegmentInfo(const char* _name, const int32_t _docCount, CL_NS(store)::Directory* _dir, bool _isCompoundFile, bool _hasSingleNormFile, int32_t _docStoreOffset, const char* _docStoreSegment, bool _docStoreIsCompoundFile) : docCount(_docCount), preLockless(false), delGen(SegmentInfo::NO), isCompoundFile(_isCompoundFile ? SegmentInfo::YES : SegmentInfo::NO), hasSingleNormFile(_hasSingleNormFile), _sizeInBytes(-1), docStoreOffset(_docStoreOffset), docStoreSegment( _docStoreSegment == NULL ? "" : _docStoreSegment ), docStoreIsCompoundFile(_docStoreIsCompoundFile) { CND_PRECONDITION(docStoreOffset == -1 || !docStoreSegment.empty(), "failed testing for (docStoreOffset == -1 || docStoreSegment != NULL)"); this->name = _name; this->dir = _dir; } string SegmentInfo::segString(Directory* dir) { string cfs; try { if (getUseCompoundFile()) cfs = "c"; else cfs = "C"; } catch (CLuceneError& ioe) { if ( ioe.number() != CL_ERR_IO ) throw ioe; cfs = "?"; } string docStore; if (docStoreOffset != -1) docStore = string("->") + docStoreSegment; else docStore = ""; return string(name) + ":" + cfs + string(this->dir == dir ? "" : "x") + Misc::toString(docCount) + docStore; } SegmentInfo::SegmentInfo(CL_NS(store)::Directory* _dir, int32_t format, CL_NS(store)::IndexInput* input): _sizeInBytes(-1) { this->dir = _dir; { char aname[CL_MAX_PATH]; input->readString(aname, CL_MAX_PATH); this->name = aname; } docCount = input->readInt(); if (format <= SegmentInfos::FORMAT_LOCKLESS) { delGen = input->readLong(); if (format <= SegmentInfos::FORMAT_SHARED_DOC_STORE) { docStoreOffset = input->readInt(); if (docStoreOffset != -1) { char aname[CL_MAX_PATH]; input->readString(aname, CL_MAX_PATH); docStoreSegment = aname; docStoreIsCompoundFile = (1 == input->readByte()); } else { docStoreSegment = name; docStoreIsCompoundFile = false; } } else { docStoreOffset = -1; docStoreSegment = name; docStoreIsCompoundFile = false; } if (format <= SegmentInfos::FORMAT_SINGLE_NORM_FILE) { hasSingleNormFile = (1 == input->readByte()); } else { hasSingleNormFile = false; } int32_t numNormGen = input->readInt(); normGen.deleteValues(); if (numNormGen == NO) { // normGen is already NULL, we'll just set normGenLen to 0 } else { normGen.values = _CL_NEWARRAY(int64_t, numNormGen); normGen.length = numNormGen; for(int32_t j=0;j<numNormGen;j++) { normGen.values[j] = input->readLong(); } } isCompoundFile = input->readByte(); preLockless = (isCompoundFile == CHECK_DIR); } else { delGen = CHECK_DIR; //normGen=NULL; normGenLen=0; isCompoundFile = CHECK_DIR; preLockless = true; hasSingleNormFile = false; docStoreOffset = -1; docStoreIsCompoundFile = false; } } void SegmentInfo::reset(const SegmentInfo* src) { clearFiles(); this->name = src->name; docCount = src->docCount; dir = src->dir; preLockless = src->preLockless; delGen = src->delGen; docStoreOffset = src->docStoreOffset; docStoreIsCompoundFile = src->docStoreIsCompoundFile; if (src->normGen.values == NULL) { this->normGen.deleteValues(); }else{ // optimized case to allocate new array only if current memory buffer is too small if (this->normGen.length < src->normGen.length) { normGen.resize(src->normGen.length); }else{ this->normGen.length = src->normGen.length; } memcpy(this->normGen.values, src->normGen.values, sizeof(int64_t) * this->normGen.length); } isCompoundFile = src->isCompoundFile; hasSingleNormFile = src->hasSingleNormFile; } SegmentInfo::~SegmentInfo(){ normGen.deleteValues(); } void SegmentInfo::setNumFields(const int32_t numFields) { if (normGen.values == NULL) { // normGen is null if we loaded a pre-2.1 segment // file, or, if this segments file hasn't had any // norms set against it yet: normGen.resize(numFields); if (preLockless) { // Do nothing: thus leaving normGen[k]==CHECK_DIR (==0), so that later we know // we have to check filesystem for norm files, because this is prelockless. } else { // This is a FORMAT_LOCKLESS segment, which means // there are no separate norms: for(int32_t i=0;i<numFields;i++) { normGen.values[i] = NO; } } } } /** Returns total size in bytes of all of files used by * this segment. */ int64_t SegmentInfo::sizeInBytes(){ if (_sizeInBytes == -1) { const vector<string>& __files = files(); size_t size = __files.size(); _sizeInBytes = 0; for(size_t i=0;i<size;i++) { const char* fileName = __files[i].c_str(); // We don't count bytes used by a shared doc store // against this segment: if (docStoreOffset == -1 || !IndexFileNames::isDocStoreFile(fileName)) _sizeInBytes += dir->fileLength(fileName); } } return _sizeInBytes; } void SegmentInfo::addIfExists(std::vector<std::string>& files, const std::string& fileName){ if (dir->fileExists(fileName.c_str())) files.push_back(fileName); } const vector<string>& SegmentInfo::files(){ if (!_files.empty()) { // Already cached: return _files; } bool useCompoundFile = getUseCompoundFile(); if (useCompoundFile) { _files.push_back( string(name) + "." + IndexFileNames::COMPOUND_FILE_EXTENSION); } else { ConstValueArray<const char*>& exts = IndexFileNames::NON_STORE_INDEX_EXTENSIONS(); for(size_t i=0;i<exts.length;i++){ addIfExists(_files, name + "." + exts[i]); } } if (docStoreOffset != -1) { // We are sharing doc stores (stored fields, term // vectors) with other segments assert (!docStoreSegment.empty()); if (docStoreIsCompoundFile) { _files.push_back(docStoreSegment + "." + IndexFileNames::COMPOUND_FILE_STORE_EXTENSION); } else { ConstValueArray<const char*>& exts = IndexFileNames::STORE_INDEX_EXTENSIONS(); for(size_t i=0;i<exts.length;i++) addIfExists(_files, docStoreSegment + "." + exts[i]); } } else if (!useCompoundFile) { // We are not sharing, and, these files were not // included in the compound file ConstValueArray<const char*>& exts = IndexFileNames::STORE_INDEX_EXTENSIONS(); for(size_t i=0;i<exts.length;i++) addIfExists(_files, name + "." + exts[i]); } string delFileName = IndexFileNames::fileNameFromGeneration(name.c_str(), (string(".") + IndexFileNames::DELETES_EXTENSION).c_str(), delGen); if ( !delFileName.empty() && (delGen >= YES || dir->fileExists(delFileName.c_str()))) { _files.push_back(delFileName); } // Careful logic for norms files if (normGen.values != NULL) { for(size_t i=0;i<normGen.length;i++) { int64_t gen = normGen[i]; if (gen >= YES) { // Definitely a separate norm file, with generation: string gens = string(".") + IndexFileNames::SEPARATE_NORMS_EXTENSION; gens += Misc::toString((int64_t)i); _files.push_back(IndexFileNames::fileNameFromGeneration(name.c_str(), gens.c_str(), gen)); } else if (NO == gen) { // No separate norms but maybe plain norms // in the non compound file case: if (!hasSingleNormFile && !useCompoundFile) { string fileName = name + "." + IndexFileNames::PLAIN_NORMS_EXTENSION; fileName += i; if (dir->fileExists(fileName.c_str())) { _files.push_back(fileName); } } } else if (CHECK_DIR == gen) { // Pre-2.1: we have to check file existence string fileName; if (useCompoundFile) { fileName = name + "." + IndexFileNames::SEPARATE_NORMS_EXTENSION; fileName += Misc::toString((int64_t)i); } else if (!hasSingleNormFile) { fileName = name + "." + IndexFileNames::PLAIN_NORMS_EXTENSION; fileName += Misc::toString((int64_t)i); } if ( !fileName.empty() && dir->fileExists(fileName.c_str())) { _files.push_back(fileName); } } } } else if (preLockless || (!hasSingleNormFile && !useCompoundFile)) { // Pre-2.1: we have to scan the dir to find all // matching _X.sN/_X.fN files for our segment: string prefix; if (useCompoundFile) prefix = name + "." + IndexFileNames::SEPARATE_NORMS_EXTENSION; else prefix = name + "." + IndexFileNames::PLAIN_NORMS_EXTENSION; size_t prefixLength = prefix.length(); vector<string> allFiles; if (dir->list(allFiles) == false ){ string err = "cannot read directory "; err += dir->toString(); err += ": list() returned null"; _CLTHROWA(CL_ERR_IO, err.c_str()); } for(size_t i=0;i<allFiles.size();i++) { string& fileName = allFiles[i]; if (fileName.length() > prefixLength && _istdigit(fileName[prefixLength]) && fileName.compare(0,prefix.length(),prefix)==0 ) { _files.push_back(fileName); } } } return _files; } bool SegmentInfo::hasDeletions() const { // Cases: // // delGen == NO: this means this segment was written // by the LOCKLESS code and for certain does not have // deletions yet // // delGen == CHECK_DIR: this means this segment was written by // pre-LOCKLESS code which means we must check // directory to see if .del file exists // // delGen >= YES: this means this segment was written by // the LOCKLESS code and for certain has // deletions // if (delGen == NO) { return false; } else if (delGen >= YES) { return true; } else { return dir->fileExists(getDelFileName().c_str()); } } void SegmentInfo::advanceDelGen() { // delGen 0 is reserved for pre-LOCKLESS format if (delGen == NO) { delGen = YES; } else { delGen++; } clearFiles(); } void SegmentInfo::clearDelGen() { delGen = NO; clearFiles(); } SegmentInfo* SegmentInfo::clone () { SegmentInfo* si = _CLNEW SegmentInfo(name.c_str(), docCount, dir); si->isCompoundFile = isCompoundFile; si->delGen = delGen; si->preLockless = preLockless; si->hasSingleNormFile = hasSingleNormFile; if (this->normGen.values != NULL) { si->normGen.resize(this->normGen.length); memcpy(si->normGen.values, this->normGen.values, sizeof(int64_t) * this->normGen.length); } si->docStoreOffset = docStoreOffset; si->docStoreSegment = docStoreSegment; si->docStoreIsCompoundFile = docStoreIsCompoundFile; return si; } string SegmentInfo::getDelFileName() const { if (delGen == NO) { // In this case we know there is no deletion filename // against this segment return NULL; } else { // If delGen is CHECK_DIR, it's the pre-lockless-commit file format return IndexFileNames::fileNameFromGeneration(name.c_str(), (string(".") + IndexFileNames::DELETES_EXTENSION).c_str(), delGen); } } bool SegmentInfo::hasSeparateNorms(const int32_t fieldNumber) const { if ((normGen.values == NULL && preLockless) || (normGen.values != NULL && normGen[fieldNumber] == CHECK_DIR)) { // Must fallback to directory file exists check: return dir->fileExists( (name + string(".s") + Misc::toString(fieldNumber)).c_str() ); } else if (normGen.values == NULL || normGen[fieldNumber] == NO) { return false; } else { return true; } } bool SegmentInfo::hasSeparateNorms() const { if (normGen.values == NULL) { if (!preLockless) { // This means we were created w/ LOCKLESS code and no // norms are written yet: return false; } else { // This means this segment was saved with pre-LOCKLESS // code. So we must fallback to the original // directory list check: vector<string> result; if ( !dir->list(result) ) { _CLTHROWA(CL_ERR_IO, (string("cannot read directory: ") + dir->toString() + string(" list() returned NULL")).c_str() ); } string pattern = name + string(".s"); for ( vector<string>::iterator itr = result.begin(); itr != result.end() ; itr ++ ){ if(strncmp(itr->c_str(), pattern.c_str(), pattern.length() ) == 0 && isdigit( (*itr)[pattern.length()])) { return true; } } return false; } } else { // This means this segment was saved with LOCKLESS // code so we first check whether any normGen's are >= 1 // (meaning they definitely have separate norms): for(size_t i=0;i<normGen.length;i++) { if (normGen[i] >= YES) { return true; } } // Next we look for any == 0. These cases were // pre-LOCKLESS and must be checked in directory: for(size_t j=0;j<normGen.length;j++) { if (normGen[j] == CHECK_DIR) { if (hasSeparateNorms(j)) { return true; } } } } return false; } void SegmentInfo::advanceNormGen(const int32_t fieldIndex) { if (normGen[fieldIndex] == NO) { normGen.values[fieldIndex] = YES; } else { normGen.values[fieldIndex]++; } clearFiles(); } string SegmentInfo::getNormFileName(const int32_t number) const { char prefix[10]; int64_t gen; if (normGen.values == NULL) { gen = CHECK_DIR; } else { gen = normGen[number]; } if (hasSeparateNorms(number)) { // case 1: separate norm cl_sprintf(prefix, 10, ".s%d", number); return IndexFileNames::fileNameFromGeneration(name.c_str(), prefix, gen); } if (hasSingleNormFile) { // case 2: lockless (or nrm file exists) - single file for all norms cl_sprintf(prefix, 10, ".%s", IndexFileNames::NORMS_EXTENSION); return IndexFileNames::fileNameFromGeneration(name.c_str(), prefix, WITHOUT_GEN); } // case 3: norm file for each field cl_sprintf(prefix, 10, ".f%d", number); return IndexFileNames::fileNameFromGeneration(name.c_str(), prefix, WITHOUT_GEN); } void SegmentInfo::setUseCompoundFile(const bool isCompoundFile) { if (isCompoundFile) { this->isCompoundFile = YES; } else { this->isCompoundFile = NO; } clearFiles(); } bool SegmentInfo::getUseCompoundFile() const { if (isCompoundFile == NO) { return false; } else if (isCompoundFile == YES) { return true; } else { return dir->fileExists( ((string)name + "." + IndexFileNames::COMPOUND_FILE_EXTENSION).c_str() ); } } int32_t SegmentInfo::getDocStoreOffset() const { return docStoreOffset; } bool SegmentInfo::getDocStoreIsCompoundFile() const { return docStoreIsCompoundFile; } void SegmentInfo::setDocStoreIsCompoundFile(const bool v) { docStoreIsCompoundFile = v; clearFiles(); } const string& SegmentInfo::getDocStoreSegment() const { return docStoreSegment; } void SegmentInfo::setDocStoreOffset(const int32_t offset) { docStoreOffset = offset; clearFiles(); } void SegmentInfo::write(CL_NS(store)::IndexOutput* output) { output->writeString(name); output->writeInt(docCount); output->writeLong(delGen); output->writeInt(docStoreOffset); if (docStoreOffset != -1) { output->writeString(docStoreSegment); output->writeByte(static_cast<uint8_t>(docStoreIsCompoundFile ? 1:0)); } output->writeByte(static_cast<uint8_t>(hasSingleNormFile ? 1:0)); if (normGen.values == NULL) { output->writeInt(NO); } else { output->writeInt(normGen.length); for(size_t j = 0; j < normGen.length; j++) { output->writeLong(normGen[j]); } } output->writeByte(isCompoundFile); } void SegmentInfo::clearFiles() { _files.clear(); _sizeInBytes = -1; } /** We consider another SegmentInfo instance equal if it * has the same dir and same name. */ bool SegmentInfo::equals(const SegmentInfo* obj) { return (obj->dir == this->dir && obj->name.compare(this->name) == 0 ); } std::ostream* SegmentInfos::infoStream = NULL; /** If non-null, information about retries when loading * the segments file will be printed to this. */ void SegmentInfos::setInfoStream(std::ostream* infoStream) { SegmentInfos::infoStream = infoStream; } /** * @see #setInfoStream */ std::ostream* SegmentInfos::getInfoStream() { return infoStream; } SegmentInfos::SegmentInfos(bool deleteMembers, int32_t reserveCount) : generation(0),lastGeneration(0), infos(deleteMembers) { //Func - Constructor //Pre - deleteMembers indicates if the instance to be created must delete // all SegmentInfo instances it manages when the instance is destroyed or not // true -> must delete, false may not delete //Post - An instance of SegmentInfos has been created. //initialize counter to 0 counter = 0; version = Misc::currentTimeMillis(); if (reserveCount > 1) infos.reserve(reserveCount); } SegmentInfos::~SegmentInfos(){ //Func - Destructor //Pre - true //Post - The instance has been destroyed. Depending on the constructor used // the SegmentInfo instances that this instance managed have been deleted or not. //Clear the list of SegmentInfo instances - make sure everything is deleted infos.clear(); } SegmentInfo* SegmentInfos::info(int32_t i) const { //Func - Returns a reference to the i-th SegmentInfo in the list. //Pre - i >= 0 //Post - A reference to the i-th SegmentInfo instance has been returned CND_PRECONDITION(i >= 0 && i < infos.size(), "i is out of bounds"); //Get the i-th SegmentInfo instance SegmentInfo *ret = infos[i]; //Condition check to see if the i-th SegmentInfo has been retrieved CND_CONDITION(ret != NULL,"No SegmentInfo instance found"); return ret; } int64_t SegmentInfos::getCurrentSegmentGeneration( std::vector<std::string>& files ) { if ( files.size() == 0 ) { return -1; } int64_t max = -1; vector<string>::iterator itr = files.begin(); const char* file; size_t seglen = strlen(IndexFileNames::SEGMENTS); while ( itr != files.end() ) { file = itr->c_str(); if ( strncmp( file, IndexFileNames::SEGMENTS, seglen ) == 0 && strcmp( file, IndexFileNames::SEGMENTS_GEN ) != 0 ) { int64_t gen = generationFromSegmentsFileName( file ); if ( gen > max ) { max = gen; } } itr++; } return max; } int64_t SegmentInfos::getCurrentSegmentGeneration( const CL_NS(store)::Directory* directory ) { vector<string> files; if ( !directory->list(&files) ){ _CLTHROWA(CL_ERR_IO, (string("cannot read directory ") + directory->toString() + string(": list() returned NULL")).c_str() ); } int64_t gen = getCurrentSegmentGeneration( files ); return gen; } string SegmentInfos::getCurrentSegmentFileName( vector<string>& files ) { return IndexFileNames::fileNameFromGeneration( IndexFileNames::SEGMENTS, "", getCurrentSegmentGeneration( files )); } std::string SegmentInfos::getCurrentSegmentFileName( CL_NS(store)::Directory* directory ) { return IndexFileNames::fileNameFromGeneration( IndexFileNames::SEGMENTS, "", getCurrentSegmentGeneration( directory )); } std::string SegmentInfos::getCurrentSegmentFileName() { return IndexFileNames::fileNameFromGeneration( IndexFileNames::SEGMENTS, "", lastGeneration ); } int64_t SegmentInfos::generationFromSegmentsFileName( const char* fileName ) { if ( strcmp( fileName, IndexFileNames::SEGMENTS ) == 0 ) { return 0; } else if ( strncmp( fileName, IndexFileNames::SEGMENTS, strlen(IndexFileNames::SEGMENTS) ) == 0 ) { return CL_NS(util)::Misc::base36ToLong( fileName + strlen( IndexFileNames::SEGMENTS )+1 ); } else { TCHAR err[CL_MAX_PATH + 35]; _sntprintf(err,CL_MAX_PATH + 35,_T("fileName \"%s\" is not a segments file"), fileName); _CLTHROWA(CL_ERR_IllegalArgument, err); return 0; } } std::string SegmentInfos::getNextSegmentFileName() { int64_t nextGeneration = 0; if ( generation == -1 ) { nextGeneration = 1; } else { nextGeneration = generation+1; } std::string retVal = IndexFileNames::fileNameFromGeneration( IndexFileNames::SEGMENTS, "", nextGeneration ); return retVal; } void SegmentInfos::clearto(size_t from, size_t end){ size_t range = end - from; if ( (infos.size() - from) >= range) { // Make sure we actually need to remove segmentInfosType::iterator itr,bitr=infos.begin()+from,eitr=infos.end(); size_t count = 0; for(itr=bitr;itr!=eitr && count < range;++itr, count++) { _CLLDELETE((*itr)); } infos.erase(bitr,bitr + count); } } void SegmentInfos::add(SegmentInfo* info, int32_t pos){ if ( pos == -1 ){ infos.push_back(info); }else{ if ( pos < 0 || pos >= (int32_t)infos.size()+1 ) _CLTHROWA(CL_ERR_IllegalArgument, "pos is out of range"); infos.insert( infos.begin()+pos, info ); } } int32_t SegmentInfos::size() const{ return infos.size(); } SegmentInfo* SegmentInfos::elementAt(int32_t pos) { return infos.at(pos); } void SegmentInfos::setElementAt(SegmentInfo* si, int32_t pos) { infos.set(pos, si); } void SegmentInfos::clear() { infos.clear(); } void SegmentInfos::insert(SegmentInfos* _infos, bool takeMemory){ infos.insert(infos.end(),_infos->infos.begin(),_infos->infos.end()); if ( takeMemory ){ while (_infos->infos.size() > 0 ) _infos->infos.remove(_infos->infos.begin(), true ); } } void SegmentInfos::insert(SegmentInfo* info){ infos.push_back(info); } int32_t SegmentInfos::indexOf(const SegmentInfo* info) const{ segmentInfosType::const_iterator itr = infos.begin(); int32_t c=-1; while ( itr != infos.end()){ c++; if ( *itr == info ){ return c; } itr++; } return -1; } void SegmentInfos::range(size_t from, size_t to, SegmentInfos& ret) const{ segmentInfosType::const_iterator itr = infos.begin(); itr+= from; for (size_t i=from;i<to && itr != infos.end();i++){ ret.infos.push_back(*itr); itr++; } } void SegmentInfos::remove(size_t index, bool dontDelete){ infos.remove(index, dontDelete); } void SegmentInfos::read(Directory* directory, const char* segmentFileName){ bool success = false; // Clear any previous segments: clear(); IndexInput* input = directory->openInput(segmentFileName); CND_CONDITION(input != NULL,"input == NULL"); generation = generationFromSegmentsFileName( segmentFileName ); lastGeneration = generation; try { int32_t format = input->readInt(); if(format < 0){ // file contains explicit format info // check that it is a format we can understand if (format < CURRENT_FORMAT){ char err[30]; cl_sprintf(err,30,"Unknown format version: %d", format); _CLTHROWA(CL_ERR_CorruptIndex, err); } version = input->readLong(); // read version counter = input->readInt(); // read counter } else{ // file is in old format without explicit format info counter = format; } for (int32_t i = input->readInt(); i > 0; i--) { // read segmentInfos infos.push_back( _CLNEW SegmentInfo(directory, format, input) ); } if(format >= 0){ // in old format the version number may be at the end of the file if (input->getFilePointer() >= input->length()) version = CL_NS(util)::Misc::currentTimeMillis(); // old file format without version number else version = input->readLong(); // read version } success = true; } _CLFINALLY({ input->close(); _CLDELETE(input); if (!success) { // Clear any segment infos we had loaded so we // have a clean slate on retry: clear(); } }); } void SegmentInfos::read(Directory* directory) { generation = lastGeneration = -1; FindSegmentsRead find(directory, this); find.run(); } void SegmentInfos::write(Directory* directory){ //Func - Writes a new segments file based upon the SegmentInfo instances it manages //Pre - directory is a valid reference to a Directory //Post - The new segment has been written to disk string segmentFileName = getNextSegmentFileName(); // Always advance the generation on write: if (generation == -1) { generation = 1; } else { generation++; } IndexOutput* output = directory->createOutput(segmentFileName.c_str()); bool success = false; try { output->writeInt(CURRENT_FORMAT); // write FORMAT output->writeLong(++version); // every write changes // the index output->writeInt(counter); // write counter output->writeInt(size()); // write infos for (int32_t i = 0; i < size(); i++) { info(i)->write(output); } }_CLFINALLY ( try { output->close(); _CLDELETE(output); success = true; } _CLFINALLY ( if (!success) { // Try not to leave a truncated segments_N file in // the index: directory->deleteFile(segmentFileName.c_str()); } ) ) try { output = directory->createOutput(IndexFileNames::SEGMENTS_GEN); try { output->writeInt(FORMAT_LOCKLESS); output->writeLong(generation); output->writeLong(generation); } _CLFINALLY( output->close(); _CLDELETE(output); ) } catch (CLuceneError& e) { if ( e.number() != CL_ERR_IO ) throw e; // It's OK if we fail to write this file since it's // used only as one of the retry fallbacks. } lastGeneration = generation; } SegmentInfos* SegmentInfos::clone() const{ SegmentInfos* sis = _CLNEW SegmentInfos(true, infos.size()); for(size_t i=0;i<infos.size();i++) { sis->setElementAt(infos[i]->clone(), i); } return sis; } int64_t SegmentInfos::getVersion() const { return version; } int64_t SegmentInfos::getGeneration() const { return generation; } int64_t SegmentInfos::getLastGeneration() const { return lastGeneration; } int64_t SegmentInfos::readCurrentVersion(Directory* directory){ FindSegmentsVersion find(directory); return find.run(); } //void SegmentInfos::setDefaultGenFileRetryCount(const int32_t count) { defaultGenFileRetryCount = count; } int32_t SegmentInfos::getDefaultGenFileRetryCount() { return defaultGenFileRetryCount; } //void SegmentInfos::setDefaultGenFileRetryPauseMsec(const int32_t msec) { defaultGenFileRetryPauseMsec = msec; } int32_t SegmentInfos::getDefaultGenFileRetryPauseMsec() { return defaultGenFileRetryPauseMsec; } //void SegmentInfos::setDefaultGenLookaheadCount(const int32_t count) { defaultGenLookaheadCount = count;} int32_t SegmentInfos::getDefaultGenLookahedCount() { return defaultGenLookaheadCount; } void SegmentInfos::_FindSegmentsFile::doRun(){ string segmentFileName; int64_t lastGen = -1; int64_t gen = 0; int32_t genLookaheadCount = 0; bool retry = false; CLuceneError exc; //saved exception int32_t method = 0; // Loop until we succeed in calling doBody() without // hitting an IOException. An IOException most likely // means a commit was in process and has finished, in // the time it took us to load the now-old infos files // (and segments files). It's also possible it's a // true error (corrupt index). To distinguish these, // on each retry we must see "forward progress" on // which generation we are trying to load. If we // don't, then the original error is real and we throw // it. // We have three methods for determining the current // generation. We try the first two in parallel, and // fall back to the third when necessary. while( true ) { if ( 0 == method ) { // Method 1: list the directory and use the highest // segments_N file. This method works well as long // as there is no stale caching on the directory // contents (NOTE: NFS clients often have such stale // caching): vector<string> files; int64_t genA = -1; if (directory != NULL){ if (directory->list(&files)) { genA = getCurrentSegmentGeneration( files ); files.clear(); } } if ( infoStream ){ (*infoStream) << "[SIS]: directory listing genA=" << genA << "\n"; } // Method 2: open segments.gen and read its // contents. Then we take the larger of the two // gen's. This way, if either approach is hitting // a stale cache (NFS) we have a better chance of // getting the right generation. int64_t genB = -1; if (directory != NULL) { CLuceneError e; for(int32_t i=0;i<defaultGenFileRetryCount;i++) { IndexInput* genInput = NULL; if ( ! directory->openInput(IndexFileNames::SEGMENTS_GEN, genInput, e) ){ if (e.number() == CL_ERR_IO ) { if ( infoStream ){ (*infoStream) << "[SIS]: segments.gen open: IOException " << e.what() << "\n"; } break; } else { genInput->close(); _CLLDELETE(genInput); throw e; } } if (genInput != NULL) { try { int32_t version = genInput->readInt(); if (version == FORMAT_LOCKLESS) { int64_t gen0 = genInput->readLong(); int64_t gen1 = genInput->readLong(); //CL_TRACE("fallback check: %d; %d", gen0, gen1); if (gen0 == gen1) { // The file is consistent. genB = gen0; genInput->close(); _CLDELETE(genInput); break; } } } catch (CLuceneError &err2) { if (err2.number() != CL_ERR_IO) { genInput->close(); _CLLDELETE(genInput); throw err2; // retry only for IOException } } _CLFINALLY({ genInput->close(); _CLDELETE(genInput); }); } _LUCENE_SLEEP(defaultGenFileRetryPauseMsec); /* //todo: Wrap the LUCENE_SLEEP call above with the following try/catch block if // InterruptedException is implemented try { } catch (CLuceneError &e) { //if (err2.number != CL_ERR_Interrupted) // retry only for InterruptedException // todo: see if CL_ERR_Interrupted needs to be added... throw e; }*/ } } //CL_TRACE("%s check: genB=%d", IndexFileNames::SEGMENTS_GEN, genB); // Pick the larger of the two gen's: if (genA > genB) gen = genA; else gen = genB; if (gen == -1) { // Neither approach found a generation _CLTHROWA(CL_ERR_IO, (string("No segments* file found in ") + directory->toString()).c_str()); } } // Third method (fallback if first & second methods // are not reliable): since both directory cache and // file contents cache seem to be stale, just // advance the generation. if ( 1 == method || ( 0 == method && lastGen == gen && retry )) { method = 1; if (genLookaheadCount < defaultGenLookaheadCount) { gen++; genLookaheadCount++; //CL_TRACE("look ahead increment gen to %d", gen); } } if (lastGen == gen) { // This means we're about to try the same // segments_N last tried. This is allowed, // exactly once, because writer could have been in // the process of writing segments_N last time. if (retry) { // OK, we've tried the same segments_N file // twice in a row, so this must be a real // error. We throw the original exception we // got. throw exc; } else { retry = true; } } else { // Segment file has advanced since our last loop, so // reset retry: retry = false; } lastGen = gen; segmentFileName = IndexFileNames::fileNameFromGeneration(IndexFileNames::SEGMENTS, "", gen); CLuceneError saved_error; if ( tryDoBody(segmentFileName.c_str(), saved_error) ){ return; } // Save the original root cause: if (exc.number() == 0) { CND_CONDITION( saved_error.number() > 0, "Unsupported error code"); exc.set(saved_error.number(),saved_error.what()); } //CL_TRACE("primary Exception on '" + segmentFileName + "': " + err + "'; will retry: retry=" + retry + "; gen = " + gen); if (!retry && gen > 1) { // This is our first time trying this segments // file (because retry is false), and, there is // possibly a segments_(N-1) (because gen > 1). // So, check if the segments_(N-1) exists and // try it if so: string prevSegmentFileName = IndexFileNames::fileNameFromGeneration( IndexFileNames::SEGMENTS, "", gen-1 ); bool prevExists=false; if (directory != NULL) prevExists = directory->fileExists(prevSegmentFileName.c_str()); else prevExists = Misc::dir_Exists( (string(fileDirectory) + prevSegmentFileName).c_str() ); if (prevExists) { //CL_TRACE("fallback to prior segment file '%s'", prevSegmentFileName); CLuceneError saved_error; if ( tryDoBody(prevSegmentFileName.c_str(), saved_error) ){ return; } //CL_TRACE("secondary Exception on '" + prevSegmentFileName + "': " + err2 + "'; will retry"); } } } } SegmentInfos::FindSegmentsRead::FindSegmentsRead( CL_NS(store)::Directory* dir, SegmentInfos* _this ) : SegmentInfos::FindSegmentsFile<bool>(dir) { this->_this = _this; } bool SegmentInfos::FindSegmentsRead::doBody( const char* segmentFileName ) { //Have SegmentInfos read the segments file in directory _this->read(directory, segmentFileName); return true; } SegmentInfos::FindSegmentsVersion::FindSegmentsVersion( CL_NS(store)::Directory* dir ) : SegmentInfos::FindSegmentsFile<int64_t>(dir) { } int64_t SegmentInfos::FindSegmentsVersion::doBody( const char* segmentFileName ) { IndexInput* input = directory->openInput( segmentFileName ); int32_t format = 0; int64_t version=0; try { format = input->readInt(); if(format < 0){ if(format < CURRENT_FORMAT){ char err[30]; cl_sprintf(err,30,"Unknown format version: %d",format); _CLTHROWA(CL_ERR_CorruptIndex,err); } version = input->readLong(); // read version } } _CLFINALLY( input->close(); _CLDELETE(input); ); if(format < 0) return version; // We cannot be sure about the format of the file. // Therefore we have to read the whole file and cannot simply seek to the version entry. SegmentInfos* sis = _CLNEW SegmentInfos(); sis->read(directory, segmentFileName); version = sis->getVersion(); _CLDELETE(sis); return version; } CL_NS_END
32.606383
145
0.615334
asheeshv