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
sequencelengths
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
sequencelengths
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
sequencelengths
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
11e89ae4be449dc35bba4162b7bcf602238a19b9
1,469
cpp
C++
Libraries/LibC/mman.cpp
ZKing1000/serenity
cc68654a44be00deb5edf3b2d2319a663012f015
[ "BSD-2-Clause" ]
3
2019-09-22T11:38:04.000Z
2020-01-21T19:09:27.000Z
Libraries/LibC/mman.cpp
ZKing1000/serenity
cc68654a44be00deb5edf3b2d2319a663012f015
[ "BSD-2-Clause" ]
8
2019-08-25T12:52:40.000Z
2019-09-08T14:46:11.000Z
Libraries/LibC/mman.cpp
ZKing1000/serenity
cc68654a44be00deb5edf3b2d2319a663012f015
[ "BSD-2-Clause" ]
1
2021-08-03T13:04:49.000Z
2021-08-03T13:04:49.000Z
#include <Kernel/Syscall.h> #include <errno.h> #include <mman.h> #include <stdio.h> extern "C" { void* mmap(void* addr, size_t size, int prot, int flags, int fd, off_t offset) { Syscall::SC_mmap_params params { (u32)addr, size, prot, flags, fd, offset, nullptr }; int rc = syscall(SC_mmap, &params); if (rc < 0 && -rc < EMAXERRNO) { errno = -rc; return (void*)-1; } return (void*)rc; } void* mmap_with_name(void* addr, size_t size, int prot, int flags, int fd, off_t offset, const char* name) { Syscall::SC_mmap_params params { (u32)addr, size, prot, flags, fd, offset, name }; int rc = syscall(SC_mmap, &params); if (rc < 0 && -rc < EMAXERRNO) { errno = -rc; return (void*)-1; } return (void*)rc; } int munmap(void* addr, size_t size) { int rc = syscall(SC_munmap, addr, size); __RETURN_WITH_ERRNO(rc, rc, -1); } int mprotect(void* addr, size_t size, int prot) { int rc = syscall(SC_mprotect, addr, size, prot); __RETURN_WITH_ERRNO(rc, rc, -1); } int set_mmap_name(void* addr, size_t size, const char* name) { int rc = syscall(SC_set_mmap_name, addr, size, name); __RETURN_WITH_ERRNO(rc, rc, -1); } int shm_open(const char* name, int flags, mode_t mode) { int rc = syscall(SC_shm_open, name, flags, mode); __RETURN_WITH_ERRNO(rc, rc, -1); } int shm_unlink(const char* name) { int rc = syscall(SC_unlink, name); __RETURN_WITH_ERRNO(rc, rc, -1); } }
24.483333
106
0.632403
ZKing1000
11f3cbe46634b80efade80446aa4ed7b5742fe26
8,136
hpp
C++
include/dca/io/hdf5/hdf5_reader.hpp
gonidelis/DCA
b219350a335b96c85b74de9a88bd00d4f37f0ce2
[ "BSD-3-Clause" ]
null
null
null
include/dca/io/hdf5/hdf5_reader.hpp
gonidelis/DCA
b219350a335b96c85b74de9a88bd00d4f37f0ce2
[ "BSD-3-Clause" ]
11
2020-04-22T14:50:27.000Z
2021-09-10T05:43:51.000Z
include/dca/io/hdf5/hdf5_reader.hpp
weilewei/DCA
b219350a335b96c85b74de9a88bd00d4f37f0ce2
[ "BSD-3-Clause" ]
1
2019-09-22T16:33:19.000Z
2019-09-22T16:33:19.000Z
// Copyright (C) 2018 ETH Zurich // Copyright (C) 2018 UT-Battelle, LLC // All rights reserved. // // See LICENSE for terms of usage. // See CITATION.md for citation guidelines, if DCA++ is used for scientific publications. // // Author: Peter Staar ([email protected]) // // HDF5 reader. #ifndef DCA_IO_HDF5_HDF5_READER_HPP #define DCA_IO_HDF5_HDF5_READER_HPP #include <complex> #include <string> #include <vector> #include "H5Cpp.h" #include "dca/io/buffer.hpp" #include "dca/function/domains.hpp" #include "dca/function/function.hpp" #include "dca/io/hdf5/hdf5_types.hpp" #include "dca/linalg/matrix.hpp" #include "dca/linalg/vector.hpp" namespace dca { namespace io { // dca::io:: class HDF5Reader { public: typedef H5::H5File file_type; // In: verbose. If true, the reader outputs a short log whenever it is executed. HDF5Reader(bool verbose = true) : verbose_(verbose) {} ~HDF5Reader(); constexpr static bool is_reader = true; constexpr static bool is_writer = false; void open_file(std::string file_name); void close_file(); void open_group(std::string name) { paths_.push_back(name); } void close_group() { paths_.pop_back(); } std::string get_path(); template <typename arbitrary_struct_t> static void from_file(arbitrary_struct_t& arbitrary_struct, std::string file_name); // `execute` returns true if the object is read correctly. template <typename Scalartype> bool execute(const std::string& name, Scalartype& value); template <typename Scalar> bool execute(const std::string& name, std::vector<Scalar>& value); template <typename Scalar> bool execute(const std::string& name, std::vector<std::vector<Scalar>>& value); template <typename Scalar, std::size_t n> bool execute(const std::string& name, std::vector<std::array<Scalar, n>>& value); bool execute(const std::string& name, std::string& value); bool execute(const std::string& name, std::vector<std::string>& value); // TODO: Remove? (only thing that depends on domains.hpp) template <typename domain_type> bool execute(std::string /*name*/, func::dmn_0<domain_type>& /*dmn*/) { return false; } template <typename Scalartype, typename domain_type> bool execute(func::function<Scalartype, domain_type>& f); template <typename Scalartype, typename domain_type> bool execute(const std::string& name, func::function<Scalartype, domain_type>& f); template <typename Scalar> bool execute(const std::string& name, dca::linalg::Vector<Scalar, dca::linalg::CPU>& A); template <typename Scalar> bool execute(const std::string& name, dca::linalg::Matrix<Scalar, dca::linalg::CPU>& A); template <typename Scalar> bool execute(dca::linalg::Matrix<Scalar, dca::linalg::CPU>& A); bool execute(const std::string& name, io::Buffer& buff) { return execute(name, static_cast<io::Buffer::Container&>(buff)); } private: bool exists(const std::string& name) const; void read(const std::string& name, H5::DataType type, void* data) const; std::vector<hsize_t> readSize(const std::string& name) const; std::unique_ptr<H5::H5File> file_; std::vector<std::string> paths_; bool verbose_; }; template <typename arbitrary_struct_t> void HDF5Reader::from_file(arbitrary_struct_t& arbitrary_struct, std::string file_name) { HDF5Reader reader_obj; reader_obj.open_file(file_name); arbitrary_struct.read_write(reader_obj); reader_obj.close_file(); } template <typename Scalar> bool HDF5Reader::execute(const std::string& name, Scalar& value) { std::string full_name = get_path() + "/" + name; if (!exists(full_name)) { return false; } read(full_name, HDF5_TYPE<Scalar>::get_PredType(), &value); return true; } template <typename Scalar> bool HDF5Reader::execute(const std::string& name, std::vector<Scalar>& value) { std::string full_name = get_path() + "/" + name; if (!exists(full_name)) { return false; } auto dims = readSize(full_name); assert(dims.size() == 1); value.resize(dims.at(0)); read(full_name, HDF5_TYPE<Scalar>::get_PredType(), value.data()); return true; } template <typename Scalar> bool HDF5Reader::execute(const std::string& name, std::vector<std::vector<Scalar>>& value) { std::string full_name = get_path() + "/" + name; if (!exists(full_name)) { return false; } auto size = readSize(full_name)[0]; const auto type = H5::VarLenType(HDF5_TYPE<Scalar>::get_PredType()); std::vector<hvl_t> data(size); H5::DataSet dataset = file_->openDataSet(name.c_str()); dataset.read(data.data(), type); value.resize(size); for (int i = 0; i < size; ++i) { value[i].resize(data[i].len); std::copy_n(static_cast<Scalar*>(data[i].p), data[i].len, value[i].data()); } dataset.vlenReclaim(data.data(), type, dataset.getSpace()); return true; } template <typename Scalar, std::size_t n> bool HDF5Reader::execute(const std::string& name, std::vector<std::array<Scalar, n>>& value) { std::string full_name = get_path() + "/" + name; if (!exists(full_name)) { return false; } auto dims = readSize(full_name); assert(dims.size() == 2); if (dims.at(1) != n) { throw(std::length_error("Wrong array size")); } value.resize(dims[0]); read(full_name, HDF5_TYPE<Scalar>::get_PredType(), value.data()); return true; } template <typename Scalartype, typename domain_type> bool HDF5Reader::execute(func::function<Scalartype, domain_type>& f) { return execute(f.get_name(), f); } template <typename Scalartype, typename domain_type> bool HDF5Reader::execute(const std::string& name, func::function<Scalartype, domain_type>& f) { std::string full_name = get_path() + "/" + name; if (!exists(full_name)) { std::cout << "\n\n\t the function (" + name + ") does not exist in path : " + get_path() + "\n\n"; return false; } std::cout << "\n\tstart reading function : " << name; H5::DataSet dataset = file_->openDataSet(full_name.c_str()); try { // Read sizes. std::vector<hsize_t> dims; auto domain_attribute = dataset.openAttribute("domain-sizes"); hsize_t n_dims; domain_attribute.getSpace().getSimpleExtentDims(&n_dims); dims.resize(n_dims); domain_attribute.read(HDF5_TYPE<hsize_t>::get_PredType(), dims.data()); // Check sizes. if (dims.size() != f.signature()) throw(std::length_error("The number of domains is different")); for (int i = 0; i < f.signature(); ++i) { if (dims[i] != f[i]) throw(std::length_error("The size of domain " + std::to_string(i) + " is different")); } } catch (H5::Exception& err) { std::cerr << "Could not perform a size check on the function " << name << std::endl; } read(full_name, HDF5_TYPE<Scalartype>::get_PredType(), f.values()); return true; } template <typename Scalar> bool HDF5Reader::execute(const std::string& name, dca::linalg::Vector<Scalar, dca::linalg::CPU>& V) { std::string full_name = get_path() + "/" + name; if (!exists(full_name)) { return false; } auto dims = readSize(full_name); assert(dims.size() == 1); V.resize(dims.at(0)); read(full_name, HDF5_TYPE<Scalar>::get_PredType(), V.ptr()); return true; } template <typename Scalar> bool HDF5Reader::execute(const std::string& name, dca::linalg::Matrix<Scalar, dca::linalg::CPU>& A) { std::string full_name = get_path() + "/" + name; if (!exists(full_name)) { return false; } auto dims = readSize(full_name); assert(dims.size() == 2); std::vector<Scalar> linearized(dims[0] * dims[1]); read(full_name, HDF5_TYPE<Scalar>::get_PredType(), linearized.data()); // HDF5 is column major, while Matrix is row major. A.resizeNoCopy(std::make_pair(dims[0], dims[1])); for (int i = 0, linindex = 0; i < A.nrRows(); ++i) { for (int j = 0; j < A.nrCols(); ++j) A(i, j) = linearized[linindex++]; } A.set_name(name); return true; } template <typename Scalar> bool HDF5Reader::execute(dca::linalg::Matrix<Scalar, dca::linalg::CPU>& A) { return execute(A.get_name(), A); } } // namespace io } // namespace dca #endif // DCA_IO_HDF5_HDF5_READER_HPP
28.055172
101
0.678343
gonidelis
11f72ce0b197f74c326bdb0e5b8762a804b43bbb
27
cpp
C++
lib/STD/Ostream.cpp
hlp2/EnjoLib
6bb69d0b00e367a800b0ef2804808fd1303648f4
[ "BSD-3-Clause" ]
3
2021-06-14T15:36:46.000Z
2022-02-28T15:16:08.000Z
lib/STD/Ostream.cpp
hlp2/EnjoLib
6bb69d0b00e367a800b0ef2804808fd1303648f4
[ "BSD-3-Clause" ]
1
2021-07-17T07:52:15.000Z
2021-07-17T07:52:15.000Z
lib/STD/Ostream.cpp
hlp2/EnjoLib
6bb69d0b00e367a800b0ef2804808fd1303648f4
[ "BSD-3-Clause" ]
3
2021-07-12T14:52:38.000Z
2021-11-28T17:10:33.000Z
#include <STD/Ostream.hpp>
13.5
26
0.740741
hlp2
11fe3791e770cdf9ea0e90baba1f10810b5b35bc
23,298
cpp
C++
src/Solver/SolverNonLinear.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
12
2020-09-07T11:19:10.000Z
2022-02-17T17:40:19.000Z
src/Solver/SolverNonLinear.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
110
2020-09-02T15:29:24.000Z
2022-03-09T09:50:01.000Z
src/Solver/SolverNonLinear.cpp
chalmersplasmatheory/DREAM
715637ada94f5e35db16f23c2fd49bb7401f4a27
[ "MIT" ]
3
2021-05-21T13:24:31.000Z
2022-02-11T14:43:12.000Z
/** * Implementation of a custom Newton solver which only utilizes * the linear solvers of PETSc. */ #include <iostream> #include <string> #include <vector> #include "DREAM/IO.hpp" #include "DREAM/OutputGeneratorSFile.hpp" #include "DREAM/Solver/SolverNonLinear.hpp" using namespace DREAM; using namespace std; /** * Constructor. */ SolverNonLinear::SolverNonLinear( FVM::UnknownQuantityHandler *unknowns, vector<UnknownQuantityEquation*> *unknown_equations, EquationSystem *eqsys, enum OptionConstants::linear_solver ls, enum OptionConstants::linear_solver bk, const int_t maxiter, const real_t reltol, bool verbose ) : Solver(unknowns, unknown_equations, ls, bk), eqsys(eqsys), maxiter(maxiter), reltol(reltol), verbose(verbose) { this->timeKeeper = new FVM::TimeKeeper("Solver non-linear"); this->timerTot = this->timeKeeper->AddTimer("total", "Total time"); this->timerRebuild = this->timeKeeper->AddTimer("rebuildtot", "Rebuild coefficients"); this->timerResidual = this->timeKeeper->AddTimer("residual", "Construct residual"); this->timerJacobian = this->timeKeeper->AddTimer("jacobian", "Construct jacobian"); this->timerInvert = this->timeKeeper->AddTimer("invert", "Invert jacobian"); } /** * Destructor. */ SolverNonLinear::~SolverNonLinear() { Deallocate(); delete this->timeKeeper; } /** * "Accept" the current solution and prepare for taking * another Newton step. */ void SolverNonLinear::AcceptSolution() { real_t *x = this->x1; this->x1 = this->x0; this->x0 = x; this->StoreSolution(x); } /** * Allocate memory for all objects used by this solver. */ void SolverNonLinear::Allocate() { this->AllocateJacobianMatrix(); const len_t N = jacobian->GetNRows(); // Select linear solver this->SelectLinearSolver(N); VecCreateSeq(PETSC_COMM_WORLD, N, &this->petsc_F); VecCreateSeq(PETSC_COMM_WORLD, N, &this->petsc_dx); this->x0 = new real_t[N]; this->x1 = new real_t[N]; this->dx = new real_t[N]; this->xinit = new real_t[N]; this->x_2norm = new real_t[this->unknown_equations->size()]; this->dx_2norm = new real_t[this->unknown_equations->size()]; } /** * Allocates memory for and properly sets up the jacobian matrix. * If the jacobian matrix has previously been allocated, it will * first be deleted. * * WHY DO WE CALL THIS METHOD MORE THAN ONCE? * In the very first iteration, many elements of the jacobian matrix are often * identically zero. If we don't insert the zeros explicitly, PETSc will remove * the memory we allocated for them on the first call to 'Assemble()' requiring * the memory to be reallocated in the next iteration (which may take a _very_ * long time). However, if we insert the zeros explicitly, the linear solver * will not be able to tell that the elements are in fact non-zero and will * take ages to solve the system. As a compromise, we would like to use the * non-zero pattern obtained in the second Newton iteration of the simulation, * we should be very close to the non-zero pattern of the remainder of the * simulation. Hence, we call this method after the first iteration is finished * to completely reset the matrix, including the non-zero pattern. Reallocating * all the memory in one go is significantly faster than asking PETSc to * allocate memory specifically for all the elements we would like to add in the * second iteration. */ void SolverNonLinear::AllocateJacobianMatrix() { if (this->jacobian != nullptr) delete this->jacobian; this->jacobian = new FVM::BlockMatrix(); for (len_t i = 0; i < nontrivial_unknowns.size(); i++) { len_t id = nontrivial_unknowns[i]; UnknownQuantityEquation *eqn = this->unknown_equations->at(id); unknownToMatrixMapping[id] = this->jacobian->CreateSubEquation(eqn->NumberOfElements(), eqn->NumberOfNonZeros_jac(), id); } this->jacobian->ConstructSystem(); } /** * Deallocate memory used by this solver. */ void SolverNonLinear::Deallocate() { if (backupInverter != nullptr) delete backupInverter; delete mainInverter; delete jacobian; delete [] this->x_2norm; delete [] this->dx_2norm; delete [] this->x0; delete [] this->x1; delete [] this->dx; delete [] this->xinit; VecDestroy(&this->petsc_F); VecDestroy(&this->petsc_dx); } /** * Returns the name of the specified non-trivial unknown quantity. * * idx: Index into 'this->nontrivial_unknowns' of the non-trivial unknown * to return the name of. */ const string& SolverNonLinear::GetNonTrivialName(const len_t idx) { return this->unknowns->GetUnknown(this->nontrivial_unknowns[idx])->GetName(); } /** * Initialize the solver. */ void SolverNonLinear::initialize_internal( const len_t, vector<len_t>& ) { this->Allocate(); if (this->convChecker == nullptr) this->SetConvergenceChecker( new ConvergenceChecker(unknowns, this->nontrivial_unknowns, this->reltol) ); } /** * Check if the solver has converged. */ bool SolverNonLinear::IsConverged(const real_t *x, const real_t *dx) { if (this->GetIteration() >= this->MaxIter()){ throw SolverException( "Non-linear solver reached the maximum number of allowed " "iterations: " LEN_T_PRINTF_FMT ".", this->MaxIter() ); } // always print verbose for the last few iterations before reaching max const len_t numVerboseBeforeMax = 3; bool printVerbose = this->Verbose() || (this->MaxIter() - this->GetIteration())<=numVerboseBeforeMax; if (printVerbose) DREAM::IO::PrintInfo("ITERATION %d", this->GetIteration()); return convChecker->IsConverged(x, dx, printVerbose); } /** * Set the initial guess for the solver. * * guess: Vector containing values of initial guess. */ void SolverNonLinear::SetInitialGuess(const real_t *guess) { if (guess != nullptr) { for (len_t i = 0; i < this->matrix_size; i++) this->x0[i] = guess[i]; } else { for (len_t i = 0; i < this->matrix_size; i++) this->x0[i] = 0; } } /** * Revert the solution to the initial guess. */ void SolverNonLinear::ResetSolution() { this->unknowns->GetLongVectorPrevious(this->nontrivial_unknowns, this->x0); this->StoreSolution(this->x0); } /** * Solve the equation system (advance the system in time * by one step). * * t: Time at which the current solution is given. * dt: Time step to take. * * (the obtained solution will correspond to time t'=t+dt) */ void SolverNonLinear::Solve(const real_t t, const real_t dt) { // Return to main matrix inverter (in case backup inverter // was used to complete last time step) this->SwitchToMainInverter(); this->nTimeStep++; this->t = t; this->dt = dt; this->timeKeeper->StartTimer(timerTot); try { this->_InternalSolve(); } catch (FVM::FVMException &ex) { // Retry with backup-solver (if allowed and not already used) if (this->backupInverter != nullptr && this->inverter != this->backupInverter) { if (this->Verbose()) { DREAM::IO::PrintInfo( "Main inverter failed to converge. Switching to backup inverter." ); DREAM::IO::PrintError(ex.what()); } // Retry solve this->SwitchToBackupInverter(); this->_InternalSolve(); } else // Rethrow exception throw ex; } // Save basic statistics for step this->nIterations.push_back(this->iteration); this->usedBackupInverter.push_back(this->inverter == this->backupInverter); this->timeKeeper->StopTimer(timerTot); } void SolverNonLinear::_InternalSolve() { // Take Newton steps len_t iter = 0; const real_t *x, *dx; do { iter++; this->SetIteration(iter); REDO_ITER: dx = this->TakeNewtonStep(); // Solution rejected (solver likely switched) if (dx == nullptr) { if (iter < this->MaxIter()) goto REDO_ITER; else throw SolverException("Maximum number of iterations reached while dx=nullptr."); } x = UpdateSolution(dx); // TODO backtracking... AcceptSolution(); } while (!IsConverged(x, dx)); } /** * Debugging routine for saving both the "analytically" computed * Jacobian, as well as the Jacobian evaluated numerically using * finite differences, to file. When this method is called, the * 'jacobian' variable is assumed to contain the "analytical" * Jacobian matrix for the current time/iteration. This routine * will then save that matrix, compute the corresponding numerical * Jacobian, and save that. * * name: Base name to use for files. */ void SolverNonLinear::SaveNumericalJacobian(const std::string& name) { this->_EvaluateJacobianNumerically(this->jacobian); this->jacobian->View(FVM::Matrix::BINARY_MATLAB, name + "_num"); abort(); } void SolverNonLinear::SaveJacobian() { this->jacobian->View(FVM::Matrix::BINARY_MATLAB, "petsc_jacobian"); } void SolverNonLinear::SaveJacobian(const std::string& name) { this->jacobian->View(FVM::Matrix::BINARY_MATLAB, name); } /** * Store the current solution to the UnknownQuantityHandler. */ void SolverNonLinear::StoreSolution(const real_t *x) { this->unknowns->Store(this->nontrivial_unknowns, x); } /** * Calculate the next Newton step to take. */ const real_t *SolverNonLinear::TakeNewtonStep() { this->timeKeeper->StartTimer(timerRebuild); this->RebuildTerms(this->t, this->dt); this->timeKeeper->StopTimer(timerRebuild); // Evaluate function vector this->timeKeeper->StartTimer(timerResidual); real_t *fvec; VecGetArray(this->petsc_F, &fvec); this->BuildVector(this->t, this->dt, fvec, this->jacobian); VecRestoreArray(this->petsc_F, &fvec); this->timeKeeper->StopTimer(timerResidual); // Reconstruct the jacobian matrix after taking the first // iteration. // (See the comment above 'AllocateJacobianMatrix()' for // details about why we do this...) if (this->nTimeStep == 1 && this->iteration == 2) this->AllocateJacobianMatrix(); // Evaluate jacobian this->timeKeeper->StartTimer(timerJacobian); this->BuildJacobian(this->t, this->dt, this->jacobian); this->timeKeeper->StopTimer(timerJacobian); // Print/save debug info and apply preconditioner (if enabled) if (this->debugrescaled) { this->Precondition(this->jacobian, this->petsc_F); this->SaveDebugInfoBefore(this->nTimeStep, this->iteration); } else { this->SaveDebugInfoBefore(this->nTimeStep, this->iteration); this->Precondition(this->jacobian, this->petsc_F); } // Solve J*dx = F this->timeKeeper->StartTimer(timerInvert); inverter->Invert(this->jacobian, &this->petsc_F, &this->petsc_dx); if (inverter->GetReturnCode() != 0) { if (this->Verbose()) DREAM::IO::PrintInfo("Switching to backup inverter... " INT_T_PRINTF_FMT, inverter->GetReturnCode()); this->SwitchToBackupInverter(); return nullptr; } this->timeKeeper->StopTimer(timerInvert); // Undo preconditioner and save additional debug info (if requested) if (this->debugrescaled) { this->SaveDebugInfoAfter(this->nTimeStep, this->iteration); this->UnPrecondition(this->petsc_dx); } else { this->UnPrecondition(this->petsc_dx); this->SaveDebugInfoAfter(this->nTimeStep, this->iteration); } // Copy dx VecGetArray(this->petsc_dx, &fvec); for (len_t i = 0; i < this->matrix_size; i++) this->dx[i] = fvec[i]; VecRestoreArray(this->petsc_dx, &fvec); return this->dx; } /** * Helper function to damping factor calculation; given a quantity * X0 and its change dX in the iteration, returns the maximal step * length (damping) such that X>threshold*X0 after the iteration */ const real_t MaximalStepLengthAtGridPoint( real_t X0, real_t dX, real_t threshold ){ real_t maxStepAtI = 1.0; if(dX>X0*std::numeric_limits<real_t>::min()) // dX positive, with check to avoid overflow maxStepAtI = (1-threshold) * X0 / dX; return maxStepAtI; } /** * Returns a dampingFactor such that x1 = x0 - dampingFactor*dx satisfies * physically-motivated constraints, such as positivity of temperature. * If initial guess dx from Newton step satisfies all constraints, returns 1. */ const real_t MaximalPhysicalStepLength(real_t *x0, const real_t *dx, len_t iteration, std::vector<len_t> nontrivial_unknowns, FVM::UnknownQuantityHandler *unknowns, IonHandler *ionHandler, len_t &id_uqn){ real_t maxStepLength = 1.0; real_t threshold = 0.1; std::vector<len_t> ids_nonNegativeQuantities; // add those quantities which we expect to be non-negative // T_cold and n_cold will crash the simulation if negative, so they should always be added ids_nonNegativeQuantities.push_back(unknowns->GetUnknownID(OptionConstants::UQTY_T_COLD)); ids_nonNegativeQuantities.push_back(unknowns->GetUnknownID(OptionConstants::UQTY_N_TOT)); ids_nonNegativeQuantities.push_back(unknowns->GetUnknownID(OptionConstants::UQTY_N_COLD)); if(unknowns->HasUnknown(OptionConstants::UQTY_W_COLD)) ids_nonNegativeQuantities.push_back(unknowns->GetUnknownID(OptionConstants::UQTY_W_COLD)); if(unknowns->HasUnknown(OptionConstants::UQTY_WI_ENER)) ids_nonNegativeQuantities.push_back(unknowns->GetUnknownID(OptionConstants::UQTY_WI_ENER)); if(unknowns->HasUnknown(OptionConstants::UQTY_NI_DENS)) ids_nonNegativeQuantities.push_back(unknowns->GetUnknownID(OptionConstants::UQTY_NI_DENS)); bool nonNegativeZeff = true; const len_t id_ni = unknowns->GetUnknownID(OptionConstants::UQTY_ION_SPECIES); const len_t N = nontrivial_unknowns.size(); const len_t N_nn = ids_nonNegativeQuantities.size(); len_t offset = 0; // sum over non-trivial unknowns for (len_t it=0; it<N; it++) { const len_t id = nontrivial_unknowns[it]; FVM::UnknownQuantity *uq = unknowns->GetUnknown(id); len_t NCells = uq->NumberOfElements(); // check whether unknown it is a non-negative quantity bool isNonNegativeQuantity = false; for (len_t it_nn = 0; it_nn < N_nn; it_nn++) if(id==ids_nonNegativeQuantities[it_nn]) isNonNegativeQuantity = true; // Quantities which physically cannot be negative, require that they cannot // be reduced by more than some threshold in each iteration. if(isNonNegativeQuantity) for(len_t i=0; i<NCells; i++){ // require x1 > threshold*x0 real_t maxStepAtI = MaximalStepLengthAtGridPoint(x0[offset+i], dx[offset+i], threshold); // if this is a stronger constaint than current maxlength, override if(maxStepAtI < maxStepLength && maxStepAtI>0){ maxStepLength = maxStepAtI; id_uqn = id; } } if(nonNegativeZeff && id==id_ni){ len_t nZ = ionHandler->GetNZ(); const len_t *Zs = ionHandler->GetZs(); len_t nr = NCells/uq->NumberOfMultiples(); for(len_t ir=0; ir<nr; ir++){ real_t nZ0Z0=0; real_t dnZ0Z0=0; for(len_t iz=0; iz<nZ; iz++) for(len_t Z0=0; Z0<=Zs[iz]; Z0++){ len_t ind = ionHandler->GetIndex(iz,Z0); nZ0Z0 += Z0*Z0*x0[offset+ind*nr+ir]; dnZ0Z0 += Z0*Z0*dx[offset+ind*nr+ir]; } real_t maxStepAtI = MaximalStepLengthAtGridPoint(nZ0Z0, dnZ0Z0, threshold); if(maxStepAtI < maxStepLength && maxStepAtI>0){ maxStepLength = maxStepAtI; id_uqn = id; } } } offset += NCells; } // Add automatic damping for abnormally high number of iterations to force convergence bool automaticDampingWithItertion = false; // skip the below for now; the method did not seem to stabilize ill-posed cases if(automaticDampingWithItertion){ real_t minDamping = 0.1; len_t itMax = 100; len_t itThresh = 30; if(iteration>itThresh) maxStepLength *= std::max(minDamping, 1.0 - ((1.0-minDamping)*(iteration-itThresh))/(itMax-itThresh)); } return maxStepLength; } /** * Update the current solution with the Newton step 'dx'. * * dx: Newton step to take. */ const real_t *SolverNonLinear::UpdateSolution(const real_t *dx) { len_t id_uqn; real_t dampingFactor = MaximalPhysicalStepLength(x0,dx,iteration,nontrivial_unknowns,unknowns,ionHandler,id_uqn); if(dampingFactor < 1 && this->Verbose()) { DREAM::IO::PrintInfo(); DREAM::IO::PrintInfo("Newton iteration dynamically damped for unknown quantity: %s",unknowns->GetUnknown(id_uqn)->GetName().c_str()); DREAM::IO::PrintInfo("to conserve positivity, by a factor: %e", dampingFactor); DREAM::IO::PrintInfo(); } for (len_t i = 0; i < this->matrix_size; i++) this->x1[i] = this->x0[i] - dampingFactor*dx[i]; return this->x1; } /** * Print timing information after the solve. */ void SolverNonLinear::PrintTimings() { this->timeKeeper->PrintTimings(true, 0); this->Solver::PrintTimings_rebuild(); } /** * Save timing information to the given SFile object. * * sf: SFile object to save timing information to. * path: Path in file to save timing information to. */ void SolverNonLinear::SaveTimings(SFile *sf, const string& path) { this->timeKeeper->SaveTimings(sf, path); sf->CreateStruct(path+"/rebuild"); this->Solver::SaveTimings_rebuild(sf, path+"/rebuild"); } /** * Save debugging information for the current iteration, * _before_ the new solution has been calculated. * * iTimeStep: Current time step index. * iIteration: Current iteration index. */ void SolverNonLinear::SaveDebugInfoBefore( len_t iTimeStep, len_t iIteration ) { if ((this->savetimestep == iTimeStep && (this->saveiteration == iIteration || this->saveiteration == 0)) || this->savetimestep == 0) { string suffix = "_" + to_string(iTimeStep) + "_" + to_string(iIteration); if (this->savejacobian) { string jacname; if (this->savetimestep == 0 || this->saveiteration == 0) jacname = "petsc_jac" + suffix; else jacname = "petsc_jac"; SaveJacobian(jacname); } if (this->savevector) { string resname; if (this->savetimestep == 0 || this->saveiteration == 0) resname = "residual" + suffix + ".mat"; else resname = "residual.mat"; real_t *fvec; VecGetArray(this->petsc_F, &fvec); SFile *sf = SFile::Create(resname, SFILE_MODE_WRITE); sf->WriteList("F", fvec, this->jacobian->GetNRows()); sf->Close(); VecRestoreArray(this->petsc_F, &fvec); } if (this->savenumjac) { string jacname; if (this->savetimestep == 0 || this->saveiteration == 0) jacname = "petsc_jac" + suffix; else jacname = "petsc_jac"; SaveNumericalJacobian(jacname); } if (this->printjacobianinfo) this->jacobian->PrintInfo(); } } /** * Save debugging information for the current iteration, * _after_ the new solution has been calculated. * * iTimeStep: Current time step index. * iIteration: Current iteration index. */ void SolverNonLinear::SaveDebugInfoAfter( len_t iTimeStep, len_t iIteration ) { if ((this->savetimestep == iTimeStep && (this->saveiteration == iIteration || this->saveiteration == 0)) || this->savetimestep == 0) { string suffix = "_" + to_string(iTimeStep) + "_" + to_string(iIteration); if (this->savesolution) { string solname = "solution_dx"; if (this->savetimestep == 0 || this->saveiteration == 0) solname += suffix; solname += ".mat"; real_t *xvec; VecGetArray(this->petsc_dx, &xvec); SFile *sf = SFile::Create(solname, SFILE_MODE_WRITE); sf->WriteList("dx", xvec, this->jacobian->GetNRows()); sf->Close(); VecRestoreArray(this->petsc_dx, &xvec); } // Save full output? if (this->savesystem) { string outname = "debugout"; if (this->savetimestep == 0 || this->saveiteration == 0) outname += suffix; outname += ".h5"; OutputGeneratorSFile *outgen = new OutputGeneratorSFile(this->eqsys, outname); outgen->SaveCurrent(); delete outgen; } } } /** * Enable or disable debug mode. * * printjacobianinfo: If true, prints detailed debug information about the * PETSc matrix for the jacobian in every iteration. * savejacobian: If true, saves the jacobian using a PETSc viewer in * the specified time step(s). * savesolution: If true, saves the solution vector in the specified * time step(s). * savevector: If true, saves the residual vector in the specified * time step(s). * savenumjac: If true, calculates the jacobian numerically and saves * it using a PETSc viewer in the specified time step(s). * timestep: Time step index to save debug info for. If 0, saves * the information in every iteration of every time step. * iteration: Iteration of specified time step to save debug info for. * savesystem: If true, saves the full equation system, including grid information, * to a proper DREAMOutput file. However, only the most recently obtained * solution is saved. * rescaled: If true, saves the rescaled version of the jacobian/solution/residual. */ void SolverNonLinear::SetDebugMode( bool printjacobianinfo, bool savesolution, bool savejacobian, bool savevector, bool savenumjac, int_t timestep, int_t iteration, bool savesystem, bool rescaled ) { this->printjacobianinfo = printjacobianinfo; this->savejacobian = savejacobian; this->savesolution = savesolution; this->savevector = savevector; this->savenumjac = savenumjac; this->savetimestep = timestep; this->saveiteration = iteration; this->savesystem = savesystem; this->debugrescaled = rescaled; } /** * Override switch to backup inverter. */ void SolverNonLinear::SwitchToBackupInverter() { // Switch inverter to use this->Solver::SwitchToBackupInverter(); // Restore solution to initial guess for time step this->ResetSolution(); } /** * Write basic data from the solver to the output file. * This data is mainly statistics about the solution. * * sf: SFile object to use for writing. * name: Name of group within file to store data in. */ void SolverNonLinear::WriteDataSFile(SFile *sf, const std::string& name) { sf->CreateStruct(name); int32_t type = (int32_t)OptionConstants::SOLVER_TYPE_NONLINEAR; sf->WriteList(name+"/type", &type, 1); // Number of iterations per time step sf->WriteList(name+"/iterations", this->nIterations.data(), this->nIterations.size()); // Whether or not backup inverter was used for a given time step len_t nubi = this->usedBackupInverter.size(); int32_t *ubi = new int32_t[nubi]; for (len_t i = 0; i < nubi; i++) ubi[i] = this->usedBackupInverter[i] ? 1 : 0; sf->WriteList(name+"/backupinverter", ubi, nubi); delete [] ubi; }
32.72191
204
0.671646
chalmersplasmatheory
f5034e6203be2938ccfe99db5b1475da39f48d1c
10,595
cpp
C++
QtMainWindow.cpp
nvoronin1337/Qt-Database-Management-System
07ab5796f61eb95a90fef7c6e15d3048ae4549d5
[ "MIT" ]
null
null
null
QtMainWindow.cpp
nvoronin1337/Qt-Database-Management-System
07ab5796f61eb95a90fef7c6e15d3048ae4549d5
[ "MIT" ]
null
null
null
QtMainWindow.cpp
nvoronin1337/Qt-Database-Management-System
07ab5796f61eb95a90fef7c6e15d3048ae4549d5
[ "MIT" ]
null
null
null
#include "QtMainWindow.h" QtMainWindow::QtMainWindow(const std::string username, QWidget* parent) : QMainWindow(parent) { setupUi(this); this->username = username; this->user = new GuiUser(username); std::string fileName = username + "_form_gui.txt"; std::string title = "Data Hive | User: " + username; setWindowTitle(QString::fromStdString(title)); QStringList headers; headers << tr("Title") << tr("Description") << tr("Date Modified"); QFile file(QString::fromStdString(fileName)); file.open(QIODevice::ReadOnly); tree_model = new TreeModel(headers, file.readAll()); tree_model_selection = new QItemSelectionModel(tree_model); file.close(); treeView->header()->setStyleSheet("::section{ background-color: #424242;}"); treeView->setHeaderHidden(false); treeView->setModel(tree_model); treeView->setSelectionModel(tree_model_selection); for (int column = 0; column < tree_model->columnCount(); ++column) treeView->resizeColumnToContents(column); setupSlots(); } QtMainWindow::~QtMainWindow() { saveModelData(true); } void QtMainWindow::populateSimpleTreeFromStorage() const { QStandardItem* db_item; QStandardItem* table_item; QStandardItem* action1; QList<QStandardItem*> items; QStandardItemModel *tree_model = new QStandardItemModel(); /** * Loop through the Storage. For each database add an item to the tree. */ for (size_t i = 0; i < user->getStorageManager()->getStorage()->databases.size(); i++) { db_item = new QStandardItem(QIcon("dbIcon.png"), QString::fromStdString(user->getStorageManager()->getStorage()->databases[i]->databaseName)); action1 = new QStandardItem(QIcon("deleteIcon.png"), QString::fromStdString("")); items.append(db_item); items.append(action1); tree_model->appendRow(items); items.clear(); // Loop through the database. For each table add an item to the tree. for (size_t k = 0; k < user->getStorageManager()->getStorage()->databases[i]->tables.size(); k++) { table_item = new QStandardItem(QIcon("tableIcon.png"), QString::fromStdString(user->getStorageManager()->getStorage()->databases[i]->tables[k]->tableName)); action1 = new QStandardItem(QIcon("deleteIcon.png"), QString::fromStdString("")); items.append(table_item); items.append(action1); db_item->appendRow(items); items.clear(); } } treeView->setModel(tree_model); QModelIndex child_index = tree_model->index(0,0); tree_model->item(0, 0)->removeRow(0); } void QtMainWindow::setupSlots() noexcept { connect(readMeAction, &QAction::triggered, this, &QtMainWindow::openUrl); connect(treeView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &QtMainWindow::updateActions); connect(menuActions, &QMenu::aboutToShow, this, &QtMainWindow::updateActions); connect(insertRowAction, &QAction::triggered, this, &QtMainWindow::insertRow); connect(insertColumnAction, &QAction::triggered, this, &QtMainWindow::insertColumn); connect(removeRowAction, &QAction::triggered, this, &QtMainWindow::removeRow); connect(removeColumnAction, &QAction::triggered, this, &QtMainWindow::removeColumn); connect(insertChildAction, &QAction::triggered, this, &QtMainWindow::insertChild); connect(btnSave, SIGNAL(pressed()), this, SLOT(saveModelData())); connect(btnDetails, SIGNAL(pressed()), this, SLOT(btn_details_pressed())); updateActions(); } void QtMainWindow::writeItemData(QVector<QVariant> item_data, bool isChild) const noexcept { std::string filename_str = user->getUsername() + "_form_gui.txt"; QString filename = QString::fromStdString(filename_str); QFile fileout(filename); if (fileout.open(QFile::ReadWrite | QFile::Text | QFile::Append)) { QTextStream out(&fileout); for (QVector<QVariant>::iterator iter = item_data.begin(); iter < item_data.end(); iter++) { if(!isChild) out << iter->toString() << " "; else out << " " << iter->toString() << " "; } out << "\n"; fileout.close(); } } void QtMainWindow::updateUsersStorage(TreeItem* parent,TreeItem* child) const noexcept { auto parent_data = parent->getItemData(); QVector<QVariant>::iterator parent_iter = parent_data.begin(); std::string database_name = parent_iter->toString().toStdString(); // if database -> add database if (child == nullptr) { user->getStorageManager()->addDatabase(database_name); } // if table -> addTable else { auto child_data = child->getItemData(); QVector<QVariant>::iterator child_iter = child_data.begin(); std::string table_name = child_iter->toString().toStdString(); //empty columns for now (better change) std::vector<std::string> cols = { "test" }; user->getStorageManager()->addTableToDatabase(database_name, table_name, cols); } } void QtMainWindow::saveModelData(bool isQuitting) const { user->getStorageManager()->getStorage()->databases.clear(); std::string filename_str = user->getUsername() + "_form_gui.txt"; std::ofstream ofs; ofs.open(filename_str, std::ofstream::out | std::ofstream::trunc); ofs.close(); auto row_max = tree_model->rowCount(); auto column = 0; TreeItem* tree_item; QModelIndex model_index; for (int row = 0; row < row_max; row++) { model_index = tree_model->index(row, column); tree_item = tree_model->getItem(model_index); auto item_data = tree_item->getItemData(); writeItemData(item_data, false); updateUsersStorage(tree_item); if (tree_item->childCount() > 0) { for (int child_num = 0; child_num < tree_item->childCount(); child_num++) { auto childItem = tree_item->child(child_num); writeItemData(childItem->getItemData(), true); updateUsersStorage(tree_item, childItem); } } } auto helper = std::make_unique<dbms::FileIOHelper>(); helper->saveStorageText(user->getStorageManager()->getStorage(), this->user->getUsername() + ".txt"); if (!isQuitting) { QMessageBox msgbox; msgbox.setText("Data is saved!"); msgbox.setStyleSheet("QMessageBox { background-color: #424242; font: 75 italic 12pt \"Gill Sans MT\"; color: rgb(1, 223, 165);}"); msgbox.exec(); } } // DETAILS PRESSED void QtMainWindow::btn_details_pressed() const { QModelIndex index = treeView->selectionModel()->currentIndex(); auto item = tree_model->getItem(index); if (item->childCount() != 0) { QMessageBox msgbox; msgbox.setText("Please select a table!"); msgbox.setStyleSheet("QMessageBox { background-color: #424242; font: 75 italic 12pt \"Gill Sans MT\"; color: rgb(1, 223, 165);}"); msgbox.exec(); return; } auto parent_item = item->parent(); auto parent_item_data = parent_item->getItemData(); auto iter_parent = parent_item_data.begin(); std::string database = iter_parent->toString().toStdString(); auto item_data = item->getItemData(); auto iter = item_data.begin(); std::string table_name = iter->toString().toStdString(); std::unique_ptr<QtTableDetailsDialog> details_dialog = std::make_unique<QtTableDetailsDialog>(database, table_name, user); //Qt::WindowFlags flags(Qt::WindowTitleHint); //details_dialog->setWindowFlags(flags); details_dialog->exec(); } // SLOTS void QtMainWindow::insertChild() { QModelIndex index = treeView->selectionModel()->currentIndex(); QAbstractItemModel* model = treeView->model(); if (model->columnCount(index) == 0) { if (!model->insertColumn(0, index)) return; } if (!model->insertRow(0, index)) return; for (int column = 0; column < model->columnCount(index); ++column) { QModelIndex child = model->index(0, column, index); model->setData(child, QVariant("[No data]"), Qt::EditRole); if (!model->headerData(column, Qt::Horizontal).isValid()) model->setHeaderData(column, Qt::Horizontal, QVariant("[No header]"), Qt::EditRole); } treeView->selectionModel()->setCurrentIndex(model->index(0, 0, index), QItemSelectionModel::ClearAndSelect); updateActions(); } bool QtMainWindow::insertColumn() { QAbstractItemModel* model = treeView->model(); int column = treeView->selectionModel()->currentIndex().column(); // Insert a column in the parent item. bool changed = model->insertColumn(column + 1); if (changed) model->setHeaderData(column + 1, Qt::Horizontal, QVariant("[No header]"), Qt::EditRole); updateActions(); return changed; } void QtMainWindow::insertRow() { QModelIndex index = treeView->selectionModel()->currentIndex(); QAbstractItemModel* model = treeView->model(); if (!model->insertRow(index.row() + 1, index.parent())) return; updateActions(); for (int column = 0; column < model->columnCount(index.parent()); ++column) { QModelIndex child = model->index(index.row() + 1, column, index.parent()); model->setData(child, QVariant("[No data]"), Qt::EditRole); } } bool QtMainWindow::removeColumn() { QAbstractItemModel* model = treeView->model(); int column = treeView->selectionModel()->currentIndex().column(); // Insert columns in each child of the parent item. bool changed = model->removeColumn(column); if (changed) updateActions(); return changed; } void QtMainWindow::removeRow() { QModelIndex index = treeView->selectionModel()->currentIndex(); QAbstractItemModel* model = treeView->model(); if (model->removeRow(index.row(), index.parent())) updateActions(); } bool QtMainWindow::openUrl() { return QDesktopServices::openUrl(QUrl("file:///C:/Users/Nikita/source/repos/QtGuiDBMS_v4_0/QtGuiApplication1/html/annotated.html", QUrl::TolerantMode)); } void QtMainWindow::updateActions() { bool hasSelection = !treeView->selectionModel()->selection().isEmpty(); removeRowAction->setEnabled(hasSelection); removeColumnAction->setEnabled(hasSelection); bool hasCurrent = treeView->selectionModel()->currentIndex().isValid(); insertRowAction->setEnabled(hasCurrent); insertColumnAction->setEnabled(hasCurrent); if (hasCurrent) { treeView->closePersistentEditor(treeView->selectionModel()->currentIndex()); int row = treeView->selectionModel()->currentIndex().row(); int column = treeView->selectionModel()->currentIndex().column(); if (treeView->selectionModel()->currentIndex().parent().isValid()) Ui::QtGuiApplication1Class::statusBar->showMessage(tr("Position: (%1,%2)").arg(row).arg(column)); else Ui::QtGuiApplication1Class::statusBar->showMessage(tr("Position: (%1,%2) in top level").arg(row).arg(column)); } }
32.400612
160
0.695422
nvoronin1337
f5045c748160ad1a6302eed469cc2b9f98bc8aeb
228
cpp
C++
src/matlab.cpp
git-steb/structural-deformable-models
4706a65e0dc031d16e259e526fd6a55e805855d1
[ "MIT" ]
2
2017-03-01T20:07:09.000Z
2020-07-12T11:02:21.000Z
src/matlab.cpp
git-steb/structural-deformable-models
4706a65e0dc031d16e259e526fd6a55e805855d1
[ "MIT" ]
null
null
null
src/matlab.cpp
git-steb/structural-deformable-models
4706a65e0dc031d16e259e526fd6a55e805855d1
[ "MIT" ]
null
null
null
#include <stdlib.h> #include "common.h" #include "matlab.h" static string matlabprog = "matlab -nojvw -nosplash -nodesktop -r "; int matlabCall(const std::string& cmd) { return system((matlabprog+cmd+", exit").c_str()); }
20.727273
68
0.688596
git-steb
f505bb79f1133b578d55b81df8ad29303067731f
3,325
cpp
C++
components/scream/src/physics/p3/tests/p3_ni_conservation_tests.cpp
mauzey1/scream
d12eb1b13039a09d9c031236af74e04262066bfc
[ "zlib-acknowledgement", "RSA-MD", "FTL" ]
null
null
null
components/scream/src/physics/p3/tests/p3_ni_conservation_tests.cpp
mauzey1/scream
d12eb1b13039a09d9c031236af74e04262066bfc
[ "zlib-acknowledgement", "RSA-MD", "FTL" ]
null
null
null
components/scream/src/physics/p3/tests/p3_ni_conservation_tests.cpp
mauzey1/scream
d12eb1b13039a09d9c031236af74e04262066bfc
[ "zlib-acknowledgement", "RSA-MD", "FTL" ]
null
null
null
#include "catch2/catch.hpp" #include "share/scream_types.hpp" #include "ekat/ekat_pack.hpp" #include "ekat/kokkos/ekat_kokkos_utils.hpp" #include "physics/p3/p3_functions.hpp" #include "physics/p3/p3_functions_f90.hpp" #include "p3_unit_tests_common.hpp" namespace scream { namespace p3 { namespace unit_test { template <typename D> struct UnitWrap::UnitTest<D>::TestNiConservation { static void run_bfb() { NiConservationData f90_data[max_pack_size]; static constexpr Int num_runs = sizeof(f90_data) / sizeof(NiConservationData); // Generate random input data // Alternatively, you can use the f90_data construtors/initializer lists to hardcode data for (auto& d : f90_data) { d.randomize(); } // Create copies of data for use by cxx and sync it to device. Needs to happen before fortran calls so that // inout data is in original state view_1d<NiConservationData> cxx_device("cxx_device", max_pack_size); const auto cxx_host = Kokkos::create_mirror_view(cxx_device); std::copy(&f90_data[0], &f90_data[0] + max_pack_size, cxx_host.data()); Kokkos::deep_copy(cxx_device, cxx_host); // Get data from fortran for (auto& d : f90_data) { ni_conservation(d); } // Get data from cxx. Run ni_conservation from a kernel and copy results back to host Kokkos::parallel_for(num_test_itrs, KOKKOS_LAMBDA(const Int& i) { const Int offset = i * Spack::n; // Init pack inputs Spack nc2ni_immers_freeze_tend, ni, ni2nr_melt_tend, ni_nucleat_tend, ni_selfcollect_tend, ni_sublim_tend, nr2ni_immers_freeze_tend; for (Int s = 0, vs = offset; s < Spack::n; ++s, ++vs) { nc2ni_immers_freeze_tend[s] = cxx_device(vs).nc2ni_immers_freeze_tend; ni[s] = cxx_device(vs).ni; ni2nr_melt_tend[s] = cxx_device(vs).ni2nr_melt_tend; ni_nucleat_tend[s] = cxx_device(vs).ni_nucleat_tend; ni_selfcollect_tend[s] = cxx_device(vs).ni_selfcollect_tend; ni_sublim_tend[s] = cxx_device(vs).ni_sublim_tend; nr2ni_immers_freeze_tend[s] = cxx_device(vs).nr2ni_immers_freeze_tend; } Functions::ni_conservation(ni, ni_nucleat_tend, nr2ni_immers_freeze_tend, nc2ni_immers_freeze_tend, cxx_device(0).dt, ni2nr_melt_tend, ni_sublim_tend, ni_selfcollect_tend); // Copy spacks back into cxx_device view for (Int s = 0, vs = offset; s < Spack::n; ++s, ++vs) { cxx_device(vs).ni2nr_melt_tend = ni2nr_melt_tend[s]; cxx_device(vs).ni_selfcollect_tend = ni_selfcollect_tend[s]; cxx_device(vs).ni_sublim_tend = ni_sublim_tend[s]; } }); Kokkos::deep_copy(cxx_host, cxx_device); // Verify BFB results for (Int i = 0; i < num_runs; ++i) { NiConservationData& d_f90 = f90_data[i]; NiConservationData& d_cxx = cxx_host[i]; REQUIRE(d_f90.ni2nr_melt_tend == d_cxx.ni2nr_melt_tend); REQUIRE(d_f90.ni_sublim_tend == d_cxx.ni_sublim_tend); REQUIRE(d_f90.ni_selfcollect_tend == d_cxx.ni_selfcollect_tend); } } // run_bfb }; } // namespace unit_test } // namespace p3 } // namespace scream namespace { TEST_CASE("ni_conservation_bfb", "[p3]") { using TestStruct = scream::p3::unit_test::UnitWrap::UnitTest<scream::DefaultDevice>::TestNiConservation; TestStruct::run_bfb(); } } // empty namespace
33.928571
178
0.704662
mauzey1
f50c0a94e46967a99ecb3936474a09e047e75c0d
826
cpp
C++
summary-ranges/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
summary-ranges/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
summary-ranges/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
class Solution { protected: string yieldRange(int begin, int end) { if (begin == end) { return to_string(begin); } return to_string(begin) + "->" + to_string(end); } public: vector<string> summaryRanges(vector<int>& nums) { const int n = nums.size(); vector<string> result; if (n == 0) { return result; } if (n == 1) { result.push_back(yieldRange(nums[0], nums[0])); return result; } int last = nums[0]; int begin = last; for (int i = 1; i < n; ++i) { if (nums[i] - last != 1) { result.push_back(yieldRange(begin, last)); begin = nums[i]; } last = nums[i]; } result.push_back(yieldRange(begin, nums[n - 1])); return result; } };
21.179487
55
0.493947
tsenmu
f50f03ccfa9b71427ab0430e3de9159602a849f4
423
cpp
C++
tests/testsmain.cpp
k9lego/huestacean
e72b43b66cc3b6b58554fa49ac207ad9f945c3fb
[ "Apache-2.0" ]
540
2018-02-16T15:15:43.000Z
2022-03-01T22:35:18.000Z
tests/testsmain.cpp
k9lego/huestacean
e72b43b66cc3b6b58554fa49ac207ad9f945c3fb
[ "Apache-2.0" ]
153
2018-02-19T13:33:14.000Z
2022-02-26T04:57:10.000Z
tests/testsmain.cpp
k9lego/huestacean
e72b43b66cc3b6b58554fa49ac207ad9f945c3fb
[ "Apache-2.0" ]
66
2018-03-17T10:54:54.000Z
2022-02-16T16:20:46.000Z
#define CATCH_CONFIG_RUNNER #include "catch/catch.hpp" #include <QCoreApplication> int main(int argc, char* argv[]) { QCoreApplication a(argc, argv); QCoreApplication::setOrganizationName("Brady Brenot"); QCoreApplication::setOrganizationDomain("bradybrenot.com"); QCoreApplication::setApplicationName("Huestacean Test"); int result = Catch::Session().run(argc, argv); return (result < 0xff ? result : 0xff); }
22.263158
60
0.751773
k9lego
f5112da53a614a87c972b3056dee8ff3b0850e52
2,957
hpp
C++
include/codegen/include/UnityEngine/EventSystems/OVRPhysicsRaycaster_--c.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/EventSystems/OVRPhysicsRaycaster_--c.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/EventSystems/OVRPhysicsRaycaster_--c.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:06 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" // Including type: UnityEngine.EventSystems.OVRPhysicsRaycaster #include "UnityEngine/EventSystems/OVRPhysicsRaycaster.hpp" // Including type: UnityEngine.RaycastHit #include "UnityEngine/RaycastHit.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Comparison`1<T> template<typename T> class Comparison_1; } // Completed forward declares // Type namespace: UnityEngine.EventSystems namespace UnityEngine::EventSystems { // Autogenerated type: UnityEngine.EventSystems.OVRPhysicsRaycaster/<>c class OVRPhysicsRaycaster::$$c : public ::Il2CppObject { public: // Get static field: static public readonly UnityEngine.EventSystems.OVRPhysicsRaycaster/<>c <>9 static UnityEngine::EventSystems::OVRPhysicsRaycaster::$$c* _get_$$9(); // Set static field: static public readonly UnityEngine.EventSystems.OVRPhysicsRaycaster/<>c <>9 static void _set_$$9(UnityEngine::EventSystems::OVRPhysicsRaycaster::$$c* value); // Get static field: static public System.Comparison`1<UnityEngine.RaycastHit> <>9__15_0 static System::Comparison_1<UnityEngine::RaycastHit>* _get_$$9__15_0(); // Set static field: static public System.Comparison`1<UnityEngine.RaycastHit> <>9__15_0 static void _set_$$9__15_0(System::Comparison_1<UnityEngine::RaycastHit>* value); // Get static field: static public System.Comparison`1<UnityEngine.RaycastHit> <>9__16_0 static System::Comparison_1<UnityEngine::RaycastHit>* _get_$$9__16_0(); // Set static field: static public System.Comparison`1<UnityEngine.RaycastHit> <>9__16_0 static void _set_$$9__16_0(System::Comparison_1<UnityEngine::RaycastHit>* value); // static private System.Void .cctor() // Offset: 0x18EA91C static void _cctor(); // System.Int32 <Raycast>b__15_0(UnityEngine.RaycastHit r1, UnityEngine.RaycastHit r2) // Offset: 0x18EA98C int $Raycast$b__15_0(UnityEngine::RaycastHit r1, UnityEngine::RaycastHit r2); // System.Int32 <Spherecast>b__16_0(UnityEngine.RaycastHit r1, UnityEngine.RaycastHit r2) // Offset: 0x18EA9D0 int $Spherecast$b__16_0(UnityEngine::RaycastHit r1, UnityEngine::RaycastHit r2); // public System.Void .ctor() // Offset: 0x18EA984 // Implemented from: System.Object // Base method: System.Void Object::.ctor() static OVRPhysicsRaycaster::$$c* New_ctor(); }; // UnityEngine.EventSystems.OVRPhysicsRaycaster/<>c } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::EventSystems::OVRPhysicsRaycaster::$$c*, "UnityEngine.EventSystems", "OVRPhysicsRaycaster/<>c"); #pragma pack(pop)
50.118644
132
0.735543
Futuremappermydud
f511311f7559c4372d7dd7dca01bd935d8d911ca
1,069
hpp
C++
lib/inc/facter/facts/windows/dmi_resolver.hpp
whopper/cfacter
f489f62e19a161e2d909199aebd896e323dac0e8
[ "Apache-2.0" ]
null
null
null
lib/inc/facter/facts/windows/dmi_resolver.hpp
whopper/cfacter
f489f62e19a161e2d909199aebd896e323dac0e8
[ "Apache-2.0" ]
null
null
null
lib/inc/facter/facts/windows/dmi_resolver.hpp
whopper/cfacter
f489f62e19a161e2d909199aebd896e323dac0e8
[ "Apache-2.0" ]
null
null
null
/** * @file * Declares the Windows Desktop Management Information (DMI) fact resolver. */ #pragma once #include "../resolvers/dmi_resolver.hpp" #include <facter/util/windows/wmi.hpp> #include <string> #include <memory> namespace facter { namespace facts { namespace windows { /** * Responsible for resolving DMI facts. */ struct dmi_resolver : resolvers::dmi_resolver { /** * Constructs the dmi_resolver. * @param wmi_conn The WMI connection to use when resolving facts. */ dmi_resolver(std::shared_ptr<util::windows::wmi> wmi_conn = std::make_shared<util::windows::wmi>()); protected: /** * Collects the resolver data. * @param facts The fact collection that is resolving facts. * @return Returns the resolver data. */ virtual data collect_data(collection& facts) override; private: std::string read(std::string const& path); std::shared_ptr<util::windows::wmi> _wmi; }; }}} // namespace facter::facts::windows
27.410256
108
0.634238
whopper
f511d895d75af332b9ef48f66861792b00977e63
6,078
hpp
C++
communication/include/communication/CommDefs.hpp
irisk29/concord-bft
daf6a4a156fa2e9107f65de6ec6a26c39cd99796
[ "Apache-2.0" ]
null
null
null
communication/include/communication/CommDefs.hpp
irisk29/concord-bft
daf6a4a156fa2e9107f65de6ec6a26c39cd99796
[ "Apache-2.0" ]
null
null
null
communication/include/communication/CommDefs.hpp
irisk29/concord-bft
daf6a4a156fa2e9107f65de6ec6a26c39cd99796
[ "Apache-2.0" ]
null
null
null
// Concord // // Copyright (c) 2018-2020 VMware, Inc. All Rights Reserved. // // This product is licensed to you under the Apache 2.0 license (the "License"). // You may not use this product except in compliance with the Apache 2.0 License. // // This product may include a number of subcomponents with separate copyright // notices and license terms. Your use of these subcomponents is subject to the // terms and conditions of the subcomponent's license, as noted in the // LICENSE file. #pragma once #include <string> #include <cstdint> #include <memory> #include <unordered_map> #include <arpa/inet.h> #include <netdb.h> #include <sys/socket.h> #include <unistd.h> #include "communication/ICommunication.hpp" #include "communication/StatusInfo.h" #include "secret_data.h" namespace bft::communication { typedef struct sockaddr_in Addr; struct NodeInfo { std::string host; std::uint16_t port; bool isReplica; }; typedef std::unordered_map<NodeNum, NodeInfo> NodeMap; enum CommType { PlainUdp, SimpleAuthUdp, PlainTcp, SimpleAuthTcp, TlsTcp }; struct BaseCommConfig { CommType commType; std::string listenHost; uint16_t listenPort; uint32_t bufferLength; NodeMap nodes; UPDATE_CONNECTIVITY_FN statusCallback; NodeNum selfId; BaseCommConfig(CommType type, const std::string &host, uint16_t port, uint32_t bufLength, NodeMap _nodes, NodeNum _selfId, UPDATE_CONNECTIVITY_FN _statusCallback = nullptr) : commType{type}, listenHost{host}, listenPort{port}, bufferLength{bufLength}, nodes{std::move(_nodes)}, statusCallback{std::move(_statusCallback)}, selfId{_selfId} {} virtual ~BaseCommConfig() = default; }; struct PlainUdpConfig : BaseCommConfig { PlainUdpConfig(const std::string &host, uint16_t port, uint32_t bufLength, NodeMap _nodes, NodeNum _selfId, UPDATE_CONNECTIVITY_FN _statusCallback = nullptr) : BaseCommConfig( CommType::PlainUdp, host, port, bufLength, std::move(_nodes), _selfId, std::move(_statusCallback)) {} }; struct PlainTcpConfig : BaseCommConfig { int32_t maxServerId; PlainTcpConfig(const std::string &host, uint16_t port, uint32_t bufLength, NodeMap _nodes, int32_t _maxServerId, NodeNum _selfId, UPDATE_CONNECTIVITY_FN _statusCallback = nullptr) : BaseCommConfig( CommType::PlainTcp, host, port, bufLength, std::move(_nodes), _selfId, std::move(_statusCallback)), maxServerId{_maxServerId} {} }; struct TlsTcpConfig : PlainTcpConfig { std::string certificatesRootPath; // set specific suite or list of suites, as described in OpenSSL // https://www.openssl.org/docs/man1.0.2/man1/ciphers.html std::string cipherSuite; std::optional<concord::secretsmanager::SecretData> secretData; TlsTcpConfig(const std::string &host, uint16_t port, uint32_t bufLength, NodeMap _nodes, int32_t _maxServerId, NodeNum _selfId, const std::string &certRootPath, const std::string &ciphSuite, UPDATE_CONNECTIVITY_FN _statusCallback = nullptr, std::optional<concord::secretsmanager::SecretData> decryptionSecretData = std::nullopt) : PlainTcpConfig(host, port, bufLength, std::move(_nodes), _maxServerId, _selfId, std::move(_statusCallback)), certificatesRootPath{certRootPath}, cipherSuite{ciphSuite}, secretData{std::move(decryptionSecretData)} { commType = CommType::TlsTcp; } }; class PlainUDPCommunication : public ICommunication { public: static PlainUDPCommunication *create(const PlainUdpConfig &config); int getMaxMessageSize() override; int Start() override; int Stop() override; bool isRunning() const override; ConnectionStatus getCurrentConnectionStatus(NodeNum node) override; int send(NodeNum destNode, std::vector<uint8_t> &&msg) override; std::set<NodeNum> send(std::set<NodeNum> dests, std::vector<uint8_t> &&msg) override; void setReceiver(NodeNum receiverNum, IReceiver *receiver) override; ~PlainUDPCommunication() override; private: class PlainUdpImpl; // TODO(IG): convert to smart ptr PlainUdpImpl *_ptrImpl = nullptr; explicit PlainUDPCommunication(const PlainUdpConfig &config); }; class PlainTCPCommunication : public ICommunication { public: static PlainTCPCommunication *create(const PlainTcpConfig &config); int getMaxMessageSize() override; int Start() override; int Stop() override; bool isRunning() const override; ConnectionStatus getCurrentConnectionStatus(NodeNum node) override; int send(NodeNum destNode, std::vector<uint8_t> &&msg) override; std::set<NodeNum> send(std::set<NodeNum> dests, std::vector<uint8_t> &&msg) override; void setReceiver(NodeNum receiverNum, IReceiver *receiver) override; ~PlainTCPCommunication() override; private: class PlainTcpImpl; PlainTcpImpl *_ptrImpl = nullptr; explicit PlainTCPCommunication(const PlainTcpConfig &config); }; class TlsTCPCommunication : public ICommunication { public: static TlsTCPCommunication *create(const TlsTcpConfig &config); int getMaxMessageSize() override; int Start() override; int Stop() override; bool isRunning() const override; ConnectionStatus getCurrentConnectionStatus(NodeNum node) override; int send(NodeNum destNode, std::vector<uint8_t> &&msg) override; std::set<NodeNum> send(std::set<NodeNum> dests, std::vector<uint8_t> &&msg) override; void setReceiver(NodeNum receiverNum, IReceiver *receiver) override; ~TlsTCPCommunication() override; private: class TlsTcpImpl; friend class AsyncTlsConnection; std::unique_ptr<TlsTcpImpl> impl_; explicit TlsTCPCommunication(const TlsTcpConfig &config); }; } // namespace bft::communication
30.69697
116
0.699737
irisk29
f512db47e285be6ddab66ee5372e8d187e73778a
1,251
hpp
C++
include/pstore/http/http_date.hpp
paulhuggett/pstore2
a0c663d10a2e2713fdf39ecdae1f9c1e96041f5c
[ "Apache-2.0" ]
11
2018-02-02T21:24:49.000Z
2020-12-11T04:06:03.000Z
include/pstore/http/http_date.hpp
SNSystems/pstore
74e9dd960245d6bfc125af03ed964d8ad660a62d
[ "Apache-2.0" ]
63
2018-02-05T17:24:59.000Z
2022-03-22T17:26:28.000Z
include/pstore/http/http_date.hpp
paulhuggett/pstore
067be94d87c87fce524c8d76c6f47c347d8f1853
[ "Apache-2.0" ]
5
2020-01-13T22:47:11.000Z
2021-05-14T09:31:15.000Z
//===- include/pstore/http/http_date.hpp ------------------*- mode: C++ -*-===// //* _ _ _ _ _ * //* | |__ | |_| |_ _ __ __| | __ _| |_ ___ * //* | '_ \| __| __| '_ \ / _` |/ _` | __/ _ \ * //* | | | | |_| |_| |_) | | (_| | (_| | || __/ * //* |_| |_|\__|\__| .__/ \__,_|\__,_|\__\___| * //* |_| * //===----------------------------------------------------------------------===// // // Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions. // See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license // information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// /// \file http_date.hpp /// \brief Functions to return a dated formatted for HTTP. #ifndef PSTORE_HTTP_HTTP_DATE_HPP #define PSTORE_HTTP_HTTP_DATE_HPP #include <chrono> #include <ctime> #include <string> namespace pstore { namespace http { std::string http_date (std::chrono::system_clock::time_point time); std::string http_date (std::time_t time); } // end namespace http } // end namespace pstore #endif // PSTORE_HTTP_HTTP_DATE_HPP
35.742857
82
0.489209
paulhuggett
f513e4ca1c2b159ea29dd107a50d782fc2c2ca51
7,446
cpp
C++
src/qpsolver/basis.cpp
WTFHCN/HiGHS
6cec473fc821bca0d98517a11691da8b5e1b0e51
[ "MIT" ]
null
null
null
src/qpsolver/basis.cpp
WTFHCN/HiGHS
6cec473fc821bca0d98517a11691da8b5e1b0e51
[ "MIT" ]
null
null
null
src/qpsolver/basis.cpp
WTFHCN/HiGHS
6cec473fc821bca0d98517a11691da8b5e1b0e51
[ "MIT" ]
null
null
null
#include "basis.hpp" #include <cassert> #include <memory> Basis::Basis(Runtime& rt, std::vector<HighsInt> active, std::vector<BasisStatus> lower, std::vector<HighsInt> inactive) : runtime(rt), buffer_column_aq(rt.instance.num_var), buffer_row_ep(rt.instance.num_var) { for (HighsInt i = 0; i < active.size(); i++) { activeconstraintidx.push_back(active[i]); basisstatus[activeconstraintidx[i]] = lower[i]; } for (HighsInt i : inactive) { nonactiveconstraintsidx.push_back(i); } Atran = rt.instance.A.t(); build(); } void Basis::build() { updatessinceinvert = 0; baseindex = new HighsInt[activeconstraintidx.size() + nonactiveconstraintsidx.size()]; constraintindexinbasisfactor.clear(); basisfactor = HFactor(); constraintindexinbasisfactor.assign(Atran.num_row + Atran.num_col, -1); assert(nonactiveconstraintsidx.size() + activeconstraintidx.size() == Atran.num_row); HighsInt counter = 0; for (HighsInt i : nonactiveconstraintsidx) { baseindex[counter++] = i; } for (HighsInt i : activeconstraintidx) { baseindex[counter++] = i; } const bool empty_matrix = (int)Atran.index.size() == 0; if (empty_matrix) { // The index/value vectors have size zero if the matrix has no // columns. However, in the Windows build, referring to index 0 of a // vector of size zero causes a failure, so resize to 1 to prevent // this. assert(Atran.num_col == 0); Atran.index.resize(1); Atran.value.resize(1); } basisfactor.setup(Atran.num_col, Atran.num_row, (HighsInt*)&Atran.start[0], (HighsInt*)&Atran.index[0], (const double*)&Atran.value[0], baseindex); basisfactor.build(); for (size_t i = 0; i < activeconstraintidx.size() + nonactiveconstraintsidx.size(); i++) { constraintindexinbasisfactor[baseindex[i]] = i; } } void Basis::rebuild() { updatessinceinvert = 0; constraintindexinbasisfactor.clear(); constraintindexinbasisfactor.assign(Atran.num_row + Atran.num_col, -1); assert(nonactiveconstraintsidx.size() + activeconstraintidx.size() == Atran.num_row); basisfactor.build(); for (size_t i = 0; i < activeconstraintidx.size() + nonactiveconstraintsidx.size(); i++) { constraintindexinbasisfactor[baseindex[i]] = i; } } void Basis::report() { printf("basis: "); for (HighsInt a_ : activeconstraintidx) { printf("%" HIGHSINT_FORMAT " ", a_); } printf(" - "); for (HighsInt n_ : nonactiveconstraintsidx) { printf("%" HIGHSINT_FORMAT " ", n_); } printf("\n"); } // move that constraint into V section basis (will correspond to Nullspace // from now on) void Basis::deactivate(HighsInt conid) { // printf("deact %" HIGHSINT_FORMAT "\n", conid); assert(contains(activeconstraintidx, conid)); basisstatus.erase(conid); remove(activeconstraintidx, conid); nonactiveconstraintsidx.push_back(conid); } void Basis::activate(Runtime& rt, HighsInt conid, BasisStatus atlower, HighsInt nonactivetoremove, Pricing* pricing) { // printf("activ %" HIGHSINT_FORMAT "\n", conid); if (!contains(activeconstraintidx, (HighsInt)conid)) { basisstatus[conid] = atlower; activeconstraintidx.push_back(conid); } else { printf("Degeneracy? constraint %" HIGHSINT_FORMAT " already in basis\n", conid); exit(1); } // printf("drop %d\n", nonactivetoremove); // remove non-active row from basis HighsInt rowtoremove = constraintindexinbasisfactor[nonactivetoremove]; baseindex[rowtoremove] = conid; remove(nonactiveconstraintsidx, nonactivetoremove); updatebasis(rt, conid, nonactivetoremove, pricing); if (updatessinceinvert != 0) { constraintindexinbasisfactor[nonactivetoremove] = -1; constraintindexinbasisfactor[conid] = rowtoremove; } } void Basis::updatebasis(Runtime& rt, HighsInt newactivecon, HighsInt droppedcon, Pricing* pricing) { if (newactivecon == droppedcon) { return; } HighsInt droppedcon_rowindex = constraintindexinbasisfactor[droppedcon]; Atran.extractcol(newactivecon, buffer_column_aq); // column.report("col_pre_ftran"); HVector column_aq_hvec = vec2hvec(buffer_column_aq); basisfactor.ftran(column_aq_hvec, 1.0); // column.report("col_post_ftran"); Vector::unit(rt.instance.A.mat.num_col, droppedcon_rowindex, buffer_row_ep); // row_ep.report("rowep_pre_btran"); HVector row_ep_hvec = vec2hvec(buffer_row_ep); basisfactor.btran(row_ep_hvec, 1.0); // row_ep.report("rowep_post_btran"); pricing->update_weights(hvec2vec(column_aq_hvec), hvec2vec(row_ep_hvec), droppedcon, newactivecon); HighsInt hint = 99999; HighsInt row_out = droppedcon_rowindex; updatessinceinvert++; basisfactor.update(&column_aq_hvec, &row_ep_hvec, &row_out, &hint); if (updatessinceinvert >= rt.settings.reinvertfrequency || hint != 99999) { rebuild(); // printf("Hint: %d\n", hint); // printf("reinvert\n"); } } Vector& Basis::btran(const Vector& rhs, Vector& target) const { HVector rhs_hvec = vec2hvec(rhs); basisfactor.btran(rhs_hvec, 1.0); return hvec2vec(rhs_hvec, target); } Vector Basis::btran(const Vector& rhs) const { HVector rhs_hvec = vec2hvec(rhs); basisfactor.btran(rhs_hvec, 1.0); return hvec2vec(rhs_hvec); } Vector& Basis::ftran(const Vector& rhs, Vector& target) const { HVector rhs_hvec = vec2hvec(rhs); basisfactor.ftran(rhs_hvec, 1.0); return hvec2vec(rhs_hvec, target); } Vector Basis::ftran(const Vector& rhs) const { HVector rhs_hvec = vec2hvec(rhs); basisfactor.ftran(rhs_hvec, 1.0); return hvec2vec(rhs_hvec); } Vector Basis::recomputex(const Instance& inst) { assert(activeconstraintidx.size() == inst.num_var); Vector rhs(inst.num_var); for (HighsInt i = 0; i < inst.num_var; i++) { HighsInt con = activeconstraintidx[i]; if (constraintindexinbasisfactor[con] == -1) { printf("error\n"); } if (basisstatus[con] == BasisStatus::ActiveAtLower) { if (con < inst.num_con) { rhs.value[constraintindexinbasisfactor[con]] = inst.con_lo[con]; } else { rhs.value[constraintindexinbasisfactor[con]] = inst.var_lo[con - inst.num_con]; } } else { if (con < inst.num_con) { rhs.value[constraintindexinbasisfactor[con]] = inst.con_up[con]; // rhs.value[i] = inst.con_up[con]; } else { rhs.value[constraintindexinbasisfactor[con]] = inst.var_up[con - inst.num_con]; // rhs.value[i] = inst.var_up[con - inst.num_con]; } } rhs.index[i] = i; rhs.num_nz++; } HVector rhs_hvec = vec2hvec(rhs); basisfactor.btran(rhs_hvec, 1.0); return hvec2vec(rhs_hvec); } // void Basis::write(std::string filename) { // FILE* file = fopen(filename.c_str(), "w"); // fprintf(file, "%lu %lu\n", activeconstraintidx.size(), // nonactiveconstraintsidx.size()); for (HighsInt i=0; // i<activeconstraintidx.size(); i++) { // fprintf(file, "%" HIGHSINT_FORMAT " %" HIGHSINT_FORMAT "\n", // activeconstraintidx[i], (HighsInt)rowstatus[i]); // } // for (HighsInt i=0; i<nonactiveconstraintsidx.size(); i++) { // fprintf(file, "%" HIGHSINT_FORMAT " %" HIGHSINT_FORMAT "\n", // nonactiveconstraintsidx[i], (HighsInt)rowstatus[i]); // } // // TODO // fclose(file); // }
30.145749
80
0.668278
WTFHCN
f514f43dfc4e379bd2576de01936369eed88d2a8
14,357
hpp
C++
src/3rd party/boost/boost/multi_array/view.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
8
2016-01-25T20:18:51.000Z
2019-03-06T07:00:04.000Z
src/3rd party/boost/boost/multi_array/view.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
null
null
null
src/3rd party/boost/boost/multi_array/view.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
// Copyright (C) 2002 Ronald Garcia // // Permission to copy, use, sell and distribute this software is granted // provided this copyright notice appears in all copies. // Permission to modify the code and to distribute modified code is granted // provided this copyright notice appears in all copies, and a notice // that the code was modified is included with the copyright notice. // // This software is provided "as is" without express or implied warranty, // and with no claim as to its suitability for any purpose. // #ifndef BOOST_MULTI_ARRAY_VIEW_RG071301_HPP #define BOOST_MULTI_ARRAY_VIEW_RG071301_HPP // // view.hpp - code for creating "views" of array data. // #include "boost/multi_array/base.hpp" #include "boost/multi_array/concept_checks.hpp" #include "boost/multi_array/iterator.hpp" #include "boost/multi_array/storage_order.hpp" #include "boost/multi_array/subarray.hpp" #include "boost/multi_array/algorithm.hpp" #include "boost/array.hpp" #include "boost/limits.hpp" #include <algorithm> #include <cstddef> #include <functional> #include <numeric> namespace boost { namespace detail { namespace multi_array { // TPtr = const T* defaulted in base.hpp template <typename T, std::size_t NumDims, typename TPtr> class const_multi_array_view : public boost::detail::multi_array::multi_array_impl_base<T,NumDims> { typedef boost::detail::multi_array::multi_array_impl_base<T,NumDims> super_type; public: typedef typename super_type::value_type value_type; typedef typename super_type::const_reference const_reference; typedef typename super_type::const_iterator const_iterator; typedef typename super_type::const_iter_base const_iter_base; typedef typename super_type::const_reverse_iterator const_reverse_iterator; typedef typename super_type::element element; typedef typename super_type::size_type size_type; typedef typename super_type::difference_type difference_type; typedef typename super_type::index index; typedef typename super_type::extent_range extent_range; // template typedefs template <std::size_t NDims> struct const_array_view { typedef boost::detail::multi_array::const_multi_array_view<T,NDims> type; }; template <std::size_t NDims> struct array_view { typedef boost::detail::multi_array::multi_array_view<T,NDims> type; }; template <typename OPtr> const_multi_array_view(const const_multi_array_view<T,NumDims,OPtr>& other) : base_(other.base_), origin_offset_(other.origin_offset_), num_elements_(other.num_elements_), extent_list_(other.extent_list_), stride_list_(other.stride_list_), index_base_list_(other.index_base_list_) { } template <class BaseList> void reindex(const BaseList& values) { boost::copy_n(values.begin(),num_dimensions(),index_base_list_.begin()); origin_offset_ = this->calculate_indexing_offset(stride_list_,index_base_list_); } void reindex(index value) { index_base_list_.assign(value); origin_offset_ = this->calculate_indexing_offset(stride_list_,index_base_list_); } size_type num_dimensions() const { return NumDims; } size_type size() const { return extent_list_.front(); } size_type max_size() const { return num_elements(); } bool empty() const { return size() == 0; } const size_type* shape() const { return extent_list_.data(); } const index* strides() const { return stride_list_.data(); } const T* origin() const { return base_+origin_offset_; } size_type num_elements() const { return num_elements_; } const index* index_bases() const { return index_base_list_.data(); } template <typename IndexList> const element& operator()(IndexList indices) const { return super_type::access_element(boost::type<const element&>(), origin(), indices,strides()); } // Only allow const element access const_reference operator[](index idx) const { return super_type::access(boost::type<const_reference>(), idx,origin(), shape(),strides(), index_bases()); } // see generate_array_view in base.hpp #if !defined(BOOST_MSVC) || BOOST_MSVC > 1300 template <int NDims> #else template <int NumDims, int NDims> // else ICE #endif // BOOST_MSVC typename const_array_view<NDims>::type operator[](const boost::detail::multi_array:: index_gen<NumDims,NDims>& indices) const { typedef typename const_array_view<NDims>::type return_type; return super_type::generate_array_view(boost::type<return_type>(), indices, shape(), strides(), index_bases(), origin()); } const_iterator begin() const { return const_iterator(const_iter_base(*index_bases(),origin(), shape(),strides(),index_bases())); } const_iterator end() const { return const_iterator(const_iter_base(*index_bases()+*shape(),origin(), shape(),strides(),index_bases())); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } template <typename OPtr> bool operator==(const const_multi_array_view<T,NumDims,OPtr>& rhs) const { if(std::equal(extent_list_.begin(), extent_list_.end(), rhs.extent_list_.begin())) return std::equal(begin(),end(),rhs.begin()); else return false; } template <typename OPtr> bool operator<(const const_multi_array_view<T,NumDims,OPtr>& rhs) const { return std::lexicographical_compare(begin(),end(),rhs.begin(),rhs.end()); } template <typename OPtr> bool operator!=(const const_multi_array_view<T,NumDims,OPtr>& rhs) const { return !(*this == rhs); } template <typename OPtr> bool operator>(const const_multi_array_view<T,NumDims,OPtr>& rhs) const { return rhs < *this; } template <typename OPtr> bool operator<=(const const_multi_array_view<T,NumDims,OPtr>& rhs) const { return !(*this > rhs); } template <typename OPtr> bool operator>=(const const_multi_array_view<T,NumDims,OPtr>& rhs) const { return !(*this < rhs); } #ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS protected: template <typename,std::size_t> friend class multi_array_impl_base; template <typename,std::size_t,typename> friend class const_multi_array_view; #else public: // should be protected #endif // This constructor is used by multi_array_impl_base::generate_array_view // to create strides template <typename ExtentList, typename Index> explicit const_multi_array_view(TPtr base, const ExtentList& extents, const boost::array<Index,NumDims>& strides): base_(base), origin_offset_(0) { index_base_list_.assign(0); // Get the extents and strides boost::copy_n(extents.begin(),NumDims,extent_list_.begin()); boost::copy_n(strides.begin(),NumDims,stride_list_.begin()); // Calculate the array size num_elements_ = std::accumulate(extent_list_.begin(),extent_list_.end(), size_type(1),std::multiplies<size_type>()); assert(num_elements_ != 0); } typedef boost::array<size_type,NumDims> size_list; typedef boost::array<index,NumDims> index_list; TPtr base_; index origin_offset_; size_type num_elements_; size_list extent_list_; index_list stride_list_; index_list index_base_list_; private: // const_multi_array_view cannot be assigned to (no deep copies!) const_multi_array_view& operator=(const const_multi_array_view& other); }; template <typename T, std::size_t NumDims> class multi_array_view : public const_multi_array_view<T,NumDims,T*> { typedef const_multi_array_view<T,NumDims,T*> super_type; public: typedef typename super_type::value_type value_type; typedef typename super_type::reference reference; typedef typename super_type::iterator iterator; typedef typename super_type::iter_base iter_base; typedef typename super_type::reverse_iterator reverse_iterator; typedef typename super_type::const_reference const_reference; typedef typename super_type::const_iterator const_iterator; typedef typename super_type::const_iter_base const_iter_base; typedef typename super_type::const_reverse_iterator const_reverse_iterator; typedef typename super_type::element element; typedef typename super_type::size_type size_type; typedef typename super_type::difference_type difference_type; typedef typename super_type::index index; typedef typename super_type::extent_range extent_range; // template typedefs template <std::size_t NDims> struct const_array_view { typedef boost::detail::multi_array::const_multi_array_view<T,NDims> type; }; template <std::size_t NDims> struct array_view { typedef boost::detail::multi_array::multi_array_view<T,NDims> type; }; // Assignment from other ConstMultiArray types. template <typename ConstMultiArray> multi_array_view& operator=(const ConstMultiArray& other) { function_requires< boost::detail::multi_array:: ConstMultiArrayConcept<ConstMultiArray,NumDims> >(); // make sure the dimensions agree assert(other.num_dimensions() == this->num_dimensions()); assert(std::equal(other.shape(),other.shape()+this->num_dimensions(), this->shape())); // iterator-based copy std::copy(other.begin(),other.end(),begin()); return *this; } multi_array_view& operator=(const multi_array_view& other) { if (&other != this) { // make sure the dimensions agree assert(other.num_dimensions() == this->num_dimensions()); assert(std::equal(other.shape(),other.shape()+this->num_dimensions(), this->shape())); // iterator-based copy std::copy(other.begin(),other.end(),begin()); } return *this; } element* origin() { return this->base_+this->origin_offset_; } template <class IndexList> element& operator()(const IndexList& indices) { return super_type::access_element(boost::type<element&>(), origin(), indices,this->strides()); } reference operator[](index idx) { return super_type::access(boost::type<reference>(), idx,origin(), this->shape(),this->strides(), this->index_bases()); } // see generate_array_view in base.hpp #if !defined(BOOST_MSVC) || BOOST_MSVC > 1300 template <int NDims> #else template <int NumDims, int NDims> // else ICE #endif // BOOST_MSVC typename array_view<NDims>::type operator[](const boost::detail::multi_array:: index_gen<NumDims,NDims>& indices) { typedef typename array_view<NDims>::type return_type; return super_type::generate_array_view(boost::type<return_type>(), indices, this->shape(), this->strides(), this->index_bases(), origin()); } iterator begin() { return iterator(iter_base(*this->index_bases(),origin(), this->shape(),this->strides(), this->index_bases())); } iterator end() { return iterator(iter_base(*this->index_bases()+*this->shape(),origin(), this->shape(),this->strides(), this->index_bases())); } reverse_iterator rbegin() { return reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } // Using declarations don't seem to work for g++ // These are the proxies to work around this. const element* origin() const { return super_type::origin(); } template <class IndexList> const element& operator()(const IndexList& indices) const { return super_type::operator()(indices); } const_reference operator[](index idx) const { return super_type::operator[](idx); } // see generate_array_view in base.hpp #if !defined(BOOST_MSVC) || BOOST_MSVC > 1300 template <int NDims> #else template <int NumDims, int NDims> // else ICE #endif // BOOST_MSVC typename const_array_view<NDims>::type operator[](const boost::detail::multi_array:: index_gen<NumDims,NDims>& indices) const { return super_type::operator[](indices); } const_iterator begin() const { return super_type::begin(); } const_iterator end() const { return super_type::end(); } const_reverse_iterator rbegin() const { return super_type::rbegin(); } const_reverse_iterator rend() const { return super_type::rend(); } #ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS private: template <typename,std::size_t> friend class multi_array_impl_base; #else public: // should be private #endif // constructor used by multi_array_impl_base::generate_array_view to // generate array views template <typename ExtentList, typename Index> explicit multi_array_view(T* base, const ExtentList& extents, const boost::array<Index,NumDims>& strides) : super_type(base,extents,strides) { } }; } // namespace multi_array } // namespace detail // // traits classes to get array_view types // template <typename Array, int N> class array_view_gen { typedef typename Array::element element; public: typedef boost::detail::multi_array::multi_array_view<element,N> type; }; template <typename Array, int N> class const_array_view_gen { typedef typename Array::element element; public: typedef boost::detail::multi_array::const_multi_array_view<element,N> type; }; } // namespace boost #endif // BOOST_MULTI_ARRAY_VIEW_RG071301_HPP
31.415755
82
0.667479
OLR-xray
f51532f2627acb7402af27d8983ef8707db01a97
1,689
cpp
C++
src/service/ClockService.cpp
NoUITeam/TinyAndPretty
06cb20f1a2381fc2196674255a00fcba416ce830
[ "Apache-2.0" ]
null
null
null
src/service/ClockService.cpp
NoUITeam/TinyAndPretty
06cb20f1a2381fc2196674255a00fcba416ce830
[ "Apache-2.0" ]
null
null
null
src/service/ClockService.cpp
NoUITeam/TinyAndPretty
06cb20f1a2381fc2196674255a00fcba416ce830
[ "Apache-2.0" ]
2
2022-03-10T18:14:02.000Z
2022-03-14T15:39:59.000Z
#include <service/ClockSys.h> using namespace UTILSTD; def_HttpEntry(API_Clock , req) { Json j; // used for response std::string_view action { req.queryParam("action") }; CONSOLE_LOG(true,"* api/clock called [action:%s]\n",action.data()); /* Start listening server broadcast Notification */ if (action == "c") { j.push_back({"code" , TimeStatus::DUP}); // for j.push_back({"msg" , "Connection Duplication!"}); return Timer::createComet(req , new JsonResponse{j}); /* Query Server Clock INFO */ } else if (action == "q") { auto t_table = Timer::getVirtualTime(); j.push_back({"code" , TimeStatus::SUCC}); j.push_back({"msg" , "Query Successfully!"}); j.push_back({"data" , { {"ratio" , (int)Timer::getTimeLineRate()} , {"year" , t_table[0]} , {"mon" , t_table[1]} , {"day" , t_table[2]} , {"week" , t_table[3]} , {"hour" , t_table[4]} , {"min" , t_table[5]} , {"sec" , t_table[6]} }}); return new JsonResponse{j}; /* Modify time speed , and inform all online user*/ } else if (action == "m") { Timer::changeTimeLineRate( std::stoi(req.queryParam("rate").data()) ); { // broadcast to all alive client; Json elc; elc.push_back({"code" , TimeStatus::BROAD}); elc.push_back({"msg" , "Time Rate Changed!"}); Timer::launchBroadCast( new JsonResponse{elc} ); } j.push_back({"code" , TimeStatus::SUCC}); j.push_back({"msg" , "Modify Successfully!"}); return new JsonResponse{j}; /* No 'action' param */ } else { j.push_back({"code" , TimeStatus::ERR}); j.push_back({"msg" , "Params Error:No 'action'"}); return new JsonResponse{j , HTTP_STATUS_400}; } }
25.984615
68
0.6045
NoUITeam
f5168440a7bd50be36b6b0bbf912797204c8893a
5,934
hpp
C++
Source/AllProjects/CQCVoice/CQCVoice_BTSimpleCmdNodes.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
51
2020-12-26T18:17:16.000Z
2022-03-15T04:29:35.000Z
Source/AllProjects/CQCVoice/CQCVoice_BTSimpleCmdNodes.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
null
null
null
Source/AllProjects/CQCVoice/CQCVoice_BTSimpleCmdNodes.hpp
MarkStega/CQC
c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07
[ "MIT" ]
4
2020-12-28T07:24:39.000Z
2021-12-29T12:09:37.000Z
// // FILE NAME: CQCVoice_BTSimpleCmdNodes_.hpp // // AUTHOR: Dean Roddey // // CREATED: 01/08/2017 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the header for some of the simpler behavior tree command nodes, which don't // aren't part of any category sufficient to justify a separate file. // // CAVEATS/GOTCHAS: // // LOG: // #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) // --------------------------------------------------------------------------- // CLASS: TBTCmdReloadCfgNode // PREFIX: btnode // --------------------------------------------------------------------------- class TBTCmdReloadCfgNode : public TBTCQCVoiceNode { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TBTCmdReloadCfgNode ( const TString& strPath , const TString& strName ); TBTCmdReloadCfgNode(const TBTCmdReloadCfgNode&) = delete; ~TBTCmdReloadCfgNode(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TBTCmdReloadCfgNode& operator=(const TBTCmdReloadCfgNode&) = delete; // ------------------------------------------------------------------- // Public, virtual methods // ------------------------------------------------------------------- tCIDAI::ENodeStates eRun ( TAIBehaviorTree& btreeOwner ) override; }; // --------------------------------------------------------------------------- // CLASS: TBTCmdSetItToNumNode // PREFIX: btnode // --------------------------------------------------------------------------- class TBTCmdSetItToNumNode : public TBTCQCVoiceNode { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TBTCmdSetItToNumNode ( const TString& strPath , const TString& strName ); TBTCmdSetItToNumNode(const TBTCmdSetItToNumNode&) = delete; ~TBTCmdSetItToNumNode(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TBTCmdSetItToNumNode& operator=(const TBTCmdSetItToNumNode&) = delete; // ------------------------------------------------------------------- // Public, virtual methods // ------------------------------------------------------------------- tCIDAI::ENodeStates eRun ( TAIBehaviorTree& btreeOwner ) override; }; // --------------------------------------------------------------------------- // CLASS: TBTCmdSetRoomModeNode // PREFIX: btnode // --------------------------------------------------------------------------- class TBTCmdSetRoomModeNode : public TBTCQCVoiceNode { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TBTCmdSetRoomModeNode ( const TString& strPath , const TString& strName ); TBTCmdSetRoomModeNode(const TBTCmdSetRoomModeNode&) = delete; ~TBTCmdSetRoomModeNode(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TBTCmdSetRoomModeNode& operator=(const TBTCmdSetRoomModeNode&) = delete; // ------------------------------------------------------------------- // Public, virtual methods // ------------------------------------------------------------------- tCIDAI::ENodeStates eRun ( TAIBehaviorTree& btreeOwner ) override; }; // --------------------------------------------------------------------------- // CLASS: TBTCmdTurnItOffOnNode // PREFIX: btnode // --------------------------------------------------------------------------- class TBTCmdTurnItOffOnNode : public TBTCQCVoiceNode { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TBTCmdTurnItOffOnNode ( const TString& strPath , const TString& strName ); TBTCmdTurnItOffOnNode(const TBTCmdTurnItOffOnNode&) = delete; ~TBTCmdTurnItOffOnNode(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TBTCmdTurnItOffOnNode& operator=(const TBTCmdTurnItOffOnNode&) = delete; // ------------------------------------------------------------------- // Public, virtual methods // ------------------------------------------------------------------- tCIDAI::ENodeStates eRun ( TAIBehaviorTree& btreeOwner ) override; }; #pragma CIDLIB_POPPACK
32.966667
87
0.34058
MarkStega
f518590f0e1db5be786d907b41df8b96a8d5605c
2,750
cpp
C++
pkg/Bfdp/source/Data/Tristate.cpp
dpkristensen/bfdm
1fdbdb89263b35b5ecd3bd7e24bce700910b38f9
[ "BSD-3-Clause" ]
1
2018-07-27T17:20:59.000Z
2018-07-27T17:20:59.000Z
pkg/Bfdp/source/Data/Tristate.cpp
dpkristensen/bfdm
1fdbdb89263b35b5ecd3bd7e24bce700910b38f9
[ "BSD-3-Clause" ]
10
2018-07-28T03:21:05.000Z
2019-02-21T07:09:36.000Z
pkg/Bfdp/source/Data/Tristate.cpp
dpkristensen/bfdm
1fdbdb89263b35b5ecd3bd7e24bce700910b38f9
[ "BSD-3-Clause" ]
null
null
null
/** BFDP Data Tristate Definitions Copyright 2019, Daniel Kristensen, Garmin Ltd, or its subsidiaries. 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 holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Base Includes #include "Bfdp/Data/Tristate.hpp" namespace Bfdp { namespace Data { Tristate::Tristate() : mValue( Unset ) { } Tristate::Tristate ( bool const aValue ) : mValue( static_cast< char >( aValue ? True : False ) ) { } bool Tristate::IsFalse() const { return mValue == False; } bool Tristate::IsSet() const { return mValue != Unset; } bool Tristate::IsTrue() const { return mValue == True; } void Tristate::Reset() { mValue = Unset; } Tristate& Tristate::operator = ( bool const aValue ) { mValue = static_cast< char >( aValue ? True : False ); return *this; } Tristate::operator ValueType() const { return static_cast< ValueType >( mValue ); } } // namespace Data } // namespace Bfdp
29.569892
82
0.634182
dpkristensen
f51e18bedf148255e1eb544065f306899995a03b
3,092
cpp
C++
data-server/src/raft/test/cluster_test.cpp
13meimei/sharkstore
b73fd09e8cddf78fc1f690219529770b278b35b6
[ "Apache-2.0" ]
1
2019-09-11T06:16:42.000Z
2019-09-11T06:16:42.000Z
data-server/src/raft/test/cluster_test.cpp
gengdaomi/sharkstore
1b490176846d2da98ceca07a69b6c35646567a28
[ "Apache-2.0" ]
null
null
null
data-server/src/raft/test/cluster_test.cpp
gengdaomi/sharkstore
1b490176846d2da98ceca07a69b6c35646567a28
[ "Apache-2.0" ]
1
2021-09-03T10:35:21.000Z
2021-09-03T10:35:21.000Z
#include <unistd.h> #include <cassert> #include <iostream> #include <thread> #include <functional> #include "number_statemachine.h" #include "raft/raft.h" #include "raft/server.h" using namespace sharkstore; using namespace sharkstore::raft; static const size_t kNodeNum = 5; std::condition_variable g_cv; std::mutex g_mu; size_t g_finish_count = 0; std::vector<Peer> g_peers; void run_node(uint64_t node_id) { RaftServerOptions ops; ops.node_id = node_id; ops.tick_interval = std::chrono::milliseconds(100); ops.election_tick = 5; ops.transport_options.use_inprocess_transport = true; auto rs = CreateRaftServer(ops); assert(rs); auto s = rs->Start(); assert(s.ok()); auto sm = std::make_shared<raft::test::NumberStateMachine>(node_id); RaftOptions rops; rops.id = 1; rops.statemachine = sm; rops.use_memory_storage = true; rops.peers = g_peers; std::shared_ptr<Raft> r; s = rs->CreateRaft(rops, &r); std::cout << s.ToString() << std::endl; assert(s.ok()); while (true) { uint64_t leader; uint64_t term; r->GetLeaderTerm(&leader, &term); if (leader != 0) { break; } else { usleep(1000 * 100); } } int reqs_count = 10000; if (r->IsLeader()) { for (int i = 1; i <= reqs_count; ++i) { std::string cmd = std::to_string(i); s = r->Submit(cmd); assert(s.ok()); } } s = sm->WaitNumber(reqs_count); assert(s.ok()); std::cout << "[NODE" << node_id << "]" << " wait number return: " << s.ToString() << std::endl; r->Truncate(3); // 本节点任务完成 { std::lock_guard<std::mutex> lock(g_mu); ++g_finish_count; } g_cv.notify_all(); // 等待所有节点完成,退出 std::unique_lock<std::mutex> lock(g_mu); while (g_finish_count < kNodeNum) { g_cv.wait(lock); } }; // 测试顺序 5个节点 // // 1) 启动2个普通节点+1个learner节点 // 2) 等待复制完成以及日志截断 // 3) 启动剩下的1个普通节点 + 1个learner节点,验证快照逻辑 int main(int argc, char* argv[]) { if (kNodeNum < 5) { throw std::runtime_error("node number should greater than five."); } // 初始化集群成员 for (uint64_t i = 1; i <= kNodeNum; ++i) { Peer p; if (i == 3 || i == kNodeNum - 1) { p.type = PeerType::kLearner; } else { p.type = PeerType::kNormal; } p.node_id = i; p.peer_id = i; g_peers.push_back(p); } std::vector<std::thread> threads; // 先启动n-2个节点 for (uint64_t i = 1; i <= kNodeNum - 2; ++i) { threads.push_back(std::thread(std::bind(&run_node, i))); } // 等待n-2个节点复制完成和日志截断 { std::unique_lock<std::mutex> lock(g_mu); while (g_finish_count < kNodeNum - 2) { g_cv.wait(lock); } } // 启动最后两个节点,一个普通,一个learner 验证快照逻辑 threads.push_back(std::thread(std::bind(&run_node, kNodeNum - 1))); threads.push_back(std::thread(std::bind(&run_node, kNodeNum))); for (auto& t : threads) { t.join(); } }
22.903704
74
0.564683
13meimei
f51e1cb8dbaada4e3325782c731168f8e4f5c5a6
18,398
cpp
C++
src/platform/Linux/ThreadStackManagerImpl.cpp
tima-q/connectedhomeip
bfdbd458d86f6905b85fe7ff5c632c85d21bc010
[ "Apache-2.0" ]
3
2021-03-01T21:37:15.000Z
2021-05-14T08:55:13.000Z
src/platform/Linux/ThreadStackManagerImpl.cpp
cser2016/connectedhomeip
55349a53c8dab9a7aaff138c8bc19a52e2df9c40
[ "Apache-2.0" ]
153
2021-01-27T08:12:04.000Z
2022-02-22T14:58:29.000Z
src/platform/Linux/ThreadStackManagerImpl.cpp
cser2016/connectedhomeip
55349a53c8dab9a7aaff138c8bc19a52e2df9c40
[ "Apache-2.0" ]
5
2021-01-19T15:34:29.000Z
2021-02-17T12:16:18.000Z
/* * * Copyright (c) 2020 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <platform/internal/CHIPDeviceLayerInternal.h> #include <platform/internal/DeviceNetworkInfo.h> #include <app/AttributeAccessInterface.h> #include <lib/support/CodeUtils.h> #include <lib/support/logging/CHIPLogging.h> #include <platform/PlatformManager.h> #include <platform/ThreadStackManager.h> using namespace ::chip::app; using namespace ::chip::app::Clusters; namespace chip { namespace DeviceLayer { ThreadStackManagerImpl ThreadStackManagerImpl::sInstance; constexpr char ThreadStackManagerImpl::kDBusOpenThreadService[]; constexpr char ThreadStackManagerImpl::kDBusOpenThreadObjectPath[]; constexpr char ThreadStackManagerImpl::kOpenthreadDeviceRoleDisabled[]; constexpr char ThreadStackManagerImpl::kOpenthreadDeviceRoleDetached[]; constexpr char ThreadStackManagerImpl::kOpenthreadDeviceRoleChild[]; constexpr char ThreadStackManagerImpl::kOpenthreadDeviceRoleRouter[]; constexpr char ThreadStackManagerImpl::kOpenthreadDeviceRoleLeader[]; constexpr char ThreadStackManagerImpl::kPropertyDeviceRole[]; ThreadStackManagerImpl::ThreadStackManagerImpl() : mAttached(false) {} CHIP_ERROR ThreadStackManagerImpl::_InitThreadStack() { std::unique_ptr<GError, GErrorDeleter> err; mProxy.reset(openthread_io_openthread_border_router_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM, G_DBUS_PROXY_FLAGS_NONE, kDBusOpenThreadService, kDBusOpenThreadObjectPath, nullptr, &MakeUniquePointerReceiver(err).Get())); if (!mProxy) { ChipLogError(DeviceLayer, "openthread: failed to create openthread dbus proxy %s", err ? err->message : "unknown error"); return CHIP_ERROR_INTERNAL; } g_signal_connect(mProxy.get(), "g-properties-changed", G_CALLBACK(OnDbusPropertiesChanged), this); // If get property is called inside dbus thread (we are going to make it so), XXX_get_XXX can be used instead of XXX_dup_XXX // which is a little bit faster and the returned object doesn't need to be freed. Same for all following get properties. std::unique_ptr<gchar, GFree> role(openthread_io_openthread_border_router_dup_device_role(mProxy.get())); if (role) { ThreadDevcieRoleChangedHandler(role.get()); } return CHIP_NO_ERROR; } void ThreadStackManagerImpl::OnDbusPropertiesChanged(OpenthreadIoOpenthreadBorderRouter * proxy, GVariant * changed_properties, const gchar * const * invalidated_properties, gpointer user_data) { ThreadStackManagerImpl * me = reinterpret_cast<ThreadStackManagerImpl *>(user_data); if (g_variant_n_children(changed_properties) > 0) { const gchar * key; GVariant * value; std::unique_ptr<GVariantIter, GVariantIterDeleter> iter; g_variant_get(changed_properties, "a{sv}", &MakeUniquePointerReceiver(iter).Get()); if (!iter) return; while (g_variant_iter_loop(iter.get(), "{&sv}", &key, &value)) { if (key == nullptr || value == nullptr) continue; // ownership of key and value is still holding by the iter if (strcmp(key, kPropertyDeviceRole) == 0) { const gchar * value_str = g_variant_get_string(value, nullptr); if (value_str == nullptr) continue; ChipLogProgress(DeviceLayer, "Thread role changed to: %s", value_str); me->ThreadDevcieRoleChangedHandler(value_str); } } } } void ThreadStackManagerImpl::ThreadDevcieRoleChangedHandler(const gchar * role) { bool attached = strcmp(role, kOpenthreadDeviceRoleDetached) != 0 && strcmp(role, kOpenthreadDeviceRoleDisabled) != 0; ChipDeviceEvent event = ChipDeviceEvent{}; if (attached != mAttached) { event.Type = DeviceEventType::kThreadConnectivityChange; event.ThreadConnectivityChange.Result = attached ? ConnectivityChange::kConnectivity_Established : ConnectivityChange::kConnectivity_Lost; CHIP_ERROR status = PlatformMgr().PostEvent(&event); if (status != CHIP_NO_ERROR) { ChipLogError(DeviceLayer, "Failed to post thread connectivity change: %" CHIP_ERROR_FORMAT, status.Format()); } } mAttached = attached; event.Type = DeviceEventType::kThreadStateChange; event.ThreadStateChange.RoleChanged = true; CHIP_ERROR status = PlatformMgr().PostEvent(&event); if (status != CHIP_NO_ERROR) { ChipLogError(DeviceLayer, "Failed to post thread state change: %" CHIP_ERROR_FORMAT, status.Format()); } } void ThreadStackManagerImpl::_ProcessThreadActivity() {} bool ThreadStackManagerImpl::_HaveRouteToAddress(const Inet::IPAddress & destAddr) { if (!mProxy || !_IsThreadAttached()) { return false; } if (destAddr.IsIPv6LinkLocal()) { return true; } std::unique_ptr<GVariant, GVariantDeleter> routes(openthread_io_openthread_border_router_dup_external_routes(mProxy.get())); if (!routes) return false; if (g_variant_n_children(routes.get()) > 0) { std::unique_ptr<GVariantIter, GVariantIterDeleter> iter; g_variant_get(routes.get(), "av", &MakeUniquePointerReceiver(iter).Get()); if (!iter) return false; GVariant * route; while (g_variant_iter_loop(iter.get(), "&v", &route)) { if (route == nullptr) continue; std::unique_ptr<GVariant, GVariantDeleter> prefix; guint16 rloc16; guchar preference; gboolean stable; gboolean nextHopIsThisDevice; g_variant_get(route, "(&vqybb)", &MakeUniquePointerReceiver(prefix).Get(), &rloc16, &preference, &stable, &nextHopIsThisDevice); if (!prefix) continue; std::unique_ptr<GVariant, GVariantDeleter> address; guchar prefixLength; g_variant_get(prefix.get(), "(&vy)", &MakeUniquePointerReceiver(address).Get(), &prefixLength); if (!address) continue; GBytes * bytes = g_variant_get_data_as_bytes(address.get()); // the ownership still hold by address if (bytes == nullptr) continue; gsize size; gconstpointer data = g_bytes_get_data(bytes, &size); if (data == nullptr) continue; if (size != sizeof(struct in6_addr)) continue; Inet::IPPrefix p; p.IPAddr = Inet::IPAddress(*reinterpret_cast<const struct in6_addr *>(data)); p.Length = prefixLength; if (p.MatchAddress(destAddr)) { return true; } } } return false; } void ThreadStackManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) { (void) event; // The otbr-agent processes the Thread state handling by itself so there // isn't much to do in the Chip stack. } CHIP_ERROR ThreadStackManagerImpl::_SetThreadProvision(ByteSpan netInfo) { VerifyOrReturnError(mProxy, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError(Thread::OperationalDataset::IsValid(netInfo), CHIP_ERROR_INVALID_ARGUMENT); { std::unique_ptr<GBytes, GBytesDeleter> bytes(g_bytes_new(netInfo.data(), netInfo.size())); if (!bytes) return CHIP_ERROR_NO_MEMORY; std::unique_ptr<GVariant, GVariantDeleter> value( g_variant_new_from_bytes(G_VARIANT_TYPE_BYTESTRING, bytes.release(), true)); if (!value) return CHIP_ERROR_NO_MEMORY; openthread_io_openthread_border_router_set_active_dataset_tlvs(mProxy.get(), value.release()); } // post an event alerting other subsystems about change in provisioning state ChipDeviceEvent event; event.Type = DeviceEventType::kServiceProvisioningChange; event.ServiceProvisioningChange.IsServiceProvisioned = true; return PlatformMgr().PostEvent(&event); } CHIP_ERROR ThreadStackManagerImpl::_GetThreadProvision(ByteSpan & netInfo) { VerifyOrReturnError(mProxy, CHIP_ERROR_INCORRECT_STATE); { std::unique_ptr<GVariant, GVariantDeleter> value( openthread_io_openthread_border_router_dup_active_dataset_tlvs(mProxy.get())); GBytes * bytes = g_variant_get_data_as_bytes(value.get()); gsize size; const uint8_t * data = reinterpret_cast<const uint8_t *>(g_bytes_get_data(bytes, &size)); ReturnErrorOnFailure(mDataset.Init(ByteSpan(data, size))); } netInfo = mDataset.AsByteSpan(); return CHIP_NO_ERROR; } bool ThreadStackManagerImpl::_IsThreadProvisioned() { return static_cast<Thread::OperationalDataset &>(mDataset).IsCommissioned(); } void ThreadStackManagerImpl::_ErasePersistentInfo() { static_cast<Thread::OperationalDataset &>(mDataset).Clear(); } bool ThreadStackManagerImpl::_IsThreadEnabled() { if (!mProxy) { return false; } std::unique_ptr<gchar, GFree> role(openthread_io_openthread_border_router_dup_device_role(mProxy.get())); return (strcmp(role.get(), kOpenthreadDeviceRoleDisabled) != 0); } bool ThreadStackManagerImpl::_IsThreadAttached() { return mAttached; } CHIP_ERROR ThreadStackManagerImpl::_SetThreadEnabled(bool val) { VerifyOrReturnError(mProxy, CHIP_ERROR_INCORRECT_STATE); if (val) { std::unique_ptr<GError, GErrorDeleter> err; gboolean result = openthread_io_openthread_border_router_call_attach_sync(mProxy.get(), nullptr, &MakeUniquePointerReceiver(err).Get()); if (err) { ChipLogError(DeviceLayer, "openthread: _SetThreadEnabled calling %s failed: %s", "Attach", err->message); return CHIP_ERROR_INTERNAL; } if (!result) { ChipLogError(DeviceLayer, "openthread: _SetThreadEnabled calling %s failed: %s", "Attach", "return false"); return CHIP_ERROR_INTERNAL; } } else { std::unique_ptr<GError, GErrorDeleter> err; gboolean result = openthread_io_openthread_border_router_call_reset_sync(mProxy.get(), nullptr, &MakeUniquePointerReceiver(err).Get()); if (err) { ChipLogError(DeviceLayer, "openthread: _SetThreadEnabled calling %s failed: %s", "Reset", err->message); return CHIP_ERROR_INTERNAL; } if (!result) { ChipLogError(DeviceLayer, "openthread: _SetThreadEnabled calling %s failed: %s", "Reset", "return false"); return CHIP_ERROR_INTERNAL; } } return CHIP_NO_ERROR; } ConnectivityManager::ThreadDeviceType ThreadStackManagerImpl::_GetThreadDeviceType() { ConnectivityManager::ThreadDeviceType type = ConnectivityManager::ThreadDeviceType::kThreadDeviceType_NotSupported; if (!mProxy) { ChipLogError(DeviceLayer, "Cannot get device role with Thread api client: %s", ""); return ConnectivityManager::ThreadDeviceType::kThreadDeviceType_NotSupported; } std::unique_ptr<gchar, GFree> role(openthread_io_openthread_border_router_dup_device_role(mProxy.get())); if (!role) return ConnectivityManager::ThreadDeviceType::kThreadDeviceType_NotSupported; if (strcmp(role.get(), kOpenthreadDeviceRoleDetached) == 0 || strcmp(role.get(), kOpenthreadDeviceRoleDisabled) == 0) { return ConnectivityManager::ThreadDeviceType::kThreadDeviceType_NotSupported; } else if (strcmp(role.get(), kOpenthreadDeviceRoleChild) == 0) { std::unique_ptr<GVariant, GVariantDeleter> linkMode(openthread_io_openthread_border_router_dup_link_mode(mProxy.get())); if (!linkMode) return ConnectivityManager::ThreadDeviceType::kThreadDeviceType_NotSupported; gboolean rx_on_when_idle; gboolean device_type; gboolean network_data; g_variant_get(linkMode.get(), "(bbb)", &rx_on_when_idle, &device_type, &network_data); if (!rx_on_when_idle) { type = ConnectivityManager::ThreadDeviceType::kThreadDeviceType_SleepyEndDevice; } else { type = device_type ? ConnectivityManager::ThreadDeviceType::kThreadDeviceType_FullEndDevice : ConnectivityManager::ThreadDeviceType::kThreadDeviceType_MinimalEndDevice; } return type; } else if (strcmp(role.get(), kOpenthreadDeviceRoleLeader) == 0 || strcmp(role.get(), kOpenthreadDeviceRoleRouter) == 0) { return ConnectivityManager::ThreadDeviceType::kThreadDeviceType_Router; } else { ChipLogError(DeviceLayer, "Unknown Thread role: %s", role.get()); return ConnectivityManager::ThreadDeviceType::kThreadDeviceType_NotSupported; } } CHIP_ERROR ThreadStackManagerImpl::_SetThreadDeviceType(ConnectivityManager::ThreadDeviceType deviceType) { gboolean rx_on_when_idle = true; gboolean device_type = true; gboolean network_data = true; VerifyOrReturnError(mProxy, CHIP_ERROR_INCORRECT_STATE); if (deviceType == ConnectivityManager::ThreadDeviceType::kThreadDeviceType_MinimalEndDevice) { network_data = false; } else if (deviceType == ConnectivityManager::ThreadDeviceType::kThreadDeviceType_SleepyEndDevice) { rx_on_when_idle = false; network_data = false; } if (!network_data) { std::unique_ptr<GVariant, GVariantDeleter> linkMode(g_variant_new("(bbb)", rx_on_when_idle, device_type, network_data)); if (!linkMode) return CHIP_ERROR_NO_MEMORY; openthread_io_openthread_border_router_set_link_mode(mProxy.get(), linkMode.release()); } return CHIP_NO_ERROR; } #if CHIP_DEVICE_CONFIG_ENABLE_SED CHIP_ERROR ThreadStackManagerImpl::_GetSEDPollingConfig(ConnectivityManager::SEDPollingConfig & pollingConfig) { (void) pollingConfig; ChipLogError(DeviceLayer, "Polling config is not supported on linux"); return CHIP_ERROR_NOT_IMPLEMENTED; } CHIP_ERROR ThreadStackManagerImpl::_SetSEDPollingConfig(const ConnectivityManager::SEDPollingConfig & pollingConfig) { (void) pollingConfig; ChipLogError(DeviceLayer, "Polling config is not supported on linux"); return CHIP_ERROR_NOT_IMPLEMENTED; } CHIP_ERROR ThreadStackManagerImpl::_RequestSEDFastPollingMode(bool onOff) { (void) onOff; ChipLogError(DeviceLayer, "Polling config is not supported on linux"); return CHIP_ERROR_NOT_IMPLEMENTED; } #endif bool ThreadStackManagerImpl::_HaveMeshConnectivity() { // TODO: Remove Weave legacy APIs // For a leader with a child, the child is considered to have mesh connectivity // and the leader is not, which is a very confusing definition. // This API is Weave legacy and should be removed. ChipLogError(DeviceLayer, "HaveMeshConnectivity has confusing behavior and shouldn't be called"); return false; } CHIP_ERROR ThreadStackManagerImpl::_GetAndLogThreadStatsCounters() { // TODO: Remove Weave legacy APIs return CHIP_ERROR_NOT_IMPLEMENTED; } CHIP_ERROR ThreadStackManagerImpl::_GetAndLogThreadTopologyMinimal() { // TODO: Remove Weave legacy APIs return CHIP_ERROR_NOT_IMPLEMENTED; } CHIP_ERROR ThreadStackManagerImpl::_GetAndLogThreadTopologyFull() { // TODO: Remove Weave legacy APIs return CHIP_ERROR_NOT_IMPLEMENTED; } CHIP_ERROR ThreadStackManagerImpl::_GetPrimary802154MACAddress(uint8_t * buf) { VerifyOrReturnError(mProxy, CHIP_ERROR_INCORRECT_STATE); guint64 extAddr = openthread_io_openthread_border_router_get_extended_address(mProxy.get()); for (size_t i = 0; i < sizeof(extAddr); i++) { buf[sizeof(uint64_t) - i - 1] = (extAddr & UINT8_MAX); extAddr >>= CHAR_BIT; } return CHIP_NO_ERROR; } CHIP_ERROR ThreadStackManagerImpl::_GetExternalIPv6Address(chip::Inet::IPAddress & addr) { // TODO: Remove Weave legacy APIs return CHIP_ERROR_NOT_IMPLEMENTED; } CHIP_ERROR ThreadStackManagerImpl::_GetPollPeriod(uint32_t & buf) { // TODO: Remove Weave legacy APIs return CHIP_ERROR_NOT_IMPLEMENTED; } CHIP_ERROR ThreadStackManagerImpl::_JoinerStart() { // TODO: Remove Weave legacy APIs return CHIP_ERROR_NOT_IMPLEMENTED; } void ThreadStackManagerImpl::_ResetThreadNetworkDiagnosticsCounts() {} CHIP_ERROR ThreadStackManagerImpl::_WriteThreadNetworkDiagnosticAttributeToTlv(AttributeId attributeId, app::AttributeValueEncoder & encoder) { CHIP_ERROR err = CHIP_NO_ERROR; switch (attributeId) { case ThreadNetworkDiagnostics::Attributes::NeighborTableList::Id: case ThreadNetworkDiagnostics::Attributes::RouteTableList::Id: case ThreadNetworkDiagnostics::Attributes::SecurityPolicy::Id: case ThreadNetworkDiagnostics::Attributes::OperationalDatasetComponents::Id: case ThreadNetworkDiagnostics::Attributes::ActiveNetworkFaultsList::Id: { err = encoder.Encode(DataModel::List<EndpointId>()); break; } default: { err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; break; } } return err; } ThreadStackManager & ThreadStackMgr() { return chip::DeviceLayer::ThreadStackManagerImpl::sInstance; } ThreadStackManagerImpl & ThreadStackMgrImpl() { return chip::DeviceLayer::ThreadStackManagerImpl::sInstance; } } // namespace DeviceLayer } // namespace chip
35.863548
130
0.689368
tima-q
f51ee1c4562b4b3b9cc983fa40bb9d60f5066b76
530
cpp
C++
ffplay/app/src/main/cpp/play.cpp
chemoontheshy/kotlin
f11c06d8fe29c381cd2cb7ce15134662577cd4f9
[ "Apache-2.0" ]
null
null
null
ffplay/app/src/main/cpp/play.cpp
chemoontheshy/kotlin
f11c06d8fe29c381cd2cb7ce15134662577cd4f9
[ "Apache-2.0" ]
null
null
null
ffplay/app/src/main/cpp/play.cpp
chemoontheshy/kotlin
f11c06d8fe29c381cd2cb7ce15134662577cd4f9
[ "Apache-2.0" ]
null
null
null
// // Created by Administrator on 2021/3/3. // #include <jni.h> extern "C" { #include "include/libavcodec/avcodec.h" #include "include/libavfilter/avfilter.h" #include "include/libavformat/avformat.h" #include "include/libavutil/avutil.h" #include "include/libswresample/swresample.h" #include "include/libswscale/swscale.h" } extern "C" JNIEXPORT jstring JNICALL Java_com_qchemmo_ffplay_ui_activity_MainActivity_test( JNIEnv *env, jobject /* this */) { return env->NewStringUTF(swresample_configuration()); }
26.5
57
0.74717
chemoontheshy
f52083daf1718e5fe458f67edd515671d75eda52
1,226
hpp
C++
cpp_module_04/ex02/Brain.hpp
anolivei/cpp_piscine42
d33bfccd38ed62d393920601f7449b74836c5219
[ "MIT" ]
1
2022-01-27T02:32:39.000Z
2022-01-27T02:32:39.000Z
cpp_module_04/ex02/Brain.hpp
anolivei/cpp_piscine42
d33bfccd38ed62d393920601f7449b74836c5219
[ "MIT" ]
null
null
null
cpp_module_04/ex02/Brain.hpp
anolivei/cpp_piscine42
d33bfccd38ed62d393920601f7449b74836c5219
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Brain.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: anolivei <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/01/29 01:27:44 by anolivei #+# #+# */ /* Updated: 2022/01/31 18:20:57 by anolivei ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef BRAIN_HPP #define BRAIN_HPP #include <iostream> class Brain { public: Brain(void); Brain(const Brain& obj); virtual ~Brain(void); Brain& operator=(const Brain& obj); std::string* get_ideas(void); protected: std::string _ideas[100]; }; std::ostream& operator<<(std::ostream& o, const Brain& brain); #endif
34.055556
80
0.272431
anolivei
f524f836aa3e336a3f7beeb98ec2d7451dae061d
1,017
cpp
C++
src/CommandLineOpts.cpp
schwarzschild-radius/spmdfy
9b5543e3446347277f15b9fe2aee3c7f8311bc78
[ "MIT" ]
6
2019-07-26T12:37:32.000Z
2021-03-13T06:18:07.000Z
src/CommandLineOpts.cpp
schwarzschild-radius/spmdfy
9b5543e3446347277f15b9fe2aee3c7f8311bc78
[ "MIT" ]
6
2019-06-19T06:04:01.000Z
2019-08-23T11:12:31.000Z
src/CommandLineOpts.cpp
schwarzschild-radius/spmdfy
9b5543e3446347277f15b9fe2aee3c7f8311bc78
[ "MIT" ]
1
2020-05-28T06:43:12.000Z
2020-05-28T06:43:12.000Z
#include <spmdfy/CommandLineOpts.hpp> llvm::cl::OptionCategory spmdfy_options("spmdfy"); llvm::cl::opt<std::string> output_filename("o", llvm::cl::desc("Specify Ouput Filename"), llvm::cl::value_desc("filename"), llvm::cl::cat(spmdfy_options)); llvm::cl::opt<bool> verbosity("v", llvm::cl::desc("Show commands to run and use verbose output"), llvm::cl::cat(spmdfy_options)); llvm::cl::opt<bool> toggle_ispc_macros( "fno-ispc-macros", llvm::cl::desc( "toggle generation of ispc macros in the current output file"), llvm::cl::cat(spmdfy_options)); llvm::cl::opt<std::string> generate_ispc_macros( "generate-ispc-macros", llvm::cl::desc("File containing ISPC Macros"), llvm::cl::value_desc("filename"), llvm::cl::cat(spmdfy_options)); llvm::cl::opt<bool> generate_decl("fgenerate-decls", llvm::cl::desc("Generate only ISPC declarations"), llvm::cl::cat(spmdfy_options));
36.321429
76
0.628319
schwarzschild-radius
f52be7b2de907b85f6774c761857416c74034d66
2,507
cpp
C++
orig/07/listing_07.12.cpp
plaice/Williams
509349bc07bb0905387e93966e83b304900bb2c4
[ "BSL-1.0" ]
5
2016-11-15T21:56:46.000Z
2018-05-05T21:34:25.000Z
orig/07/listing_07.12.cpp
plaice/Williams
509349bc07bb0905387e93966e83b304900bb2c4
[ "BSL-1.0" ]
null
null
null
orig/07/listing_07.12.cpp
plaice/Williams
509349bc07bb0905387e93966e83b304900bb2c4
[ "BSL-1.0" ]
null
null
null
#include <atomic> #include <memory> template<typename T> class lock_free_stack { private: struct node; struct counted_node_ptr { int external_count; node* ptr; }; struct node { std::shared_ptr<T> data; std::atomic<int> internal_count; counted_node_ptr next; node(T const& data_): data(std::make_shared<T>(data_)), internal_count(0) {} }; std::atomic<counted_node_ptr> head; void increase_head_count(counted_node_ptr& old_counter) { counted_node_ptr new_counter; do { new_counter=old_counter; ++new_counter.external_count; } while(!head.compare_exchange_strong( old_counter,new_counter, std::memory_order_acquire, std::memory_order_relaxed)); old_counter.external_count=new_counter.external_count; } public: ~lock_free_stack() { while(pop()); } void push(T const& data) { counted_node_ptr new_node; new_node.ptr=new node(data); new_node.external_count=1; new_node.ptr->next=head.load(std::memory_order_relaxed); while(!head.compare_exchange_weak( new_node.ptr->next,new_node, std::memory_order_release, std::memory_order_relaxed)); } std::shared_ptr<T> pop() { counted_node_ptr old_head= head.load(std::memory_order_relaxed); for(;;) { increase_head_count(old_head); node* const ptr=old_head.ptr; if(!ptr) { return std::shared_ptr<T>(); } if(head.compare_exchange_strong( old_head,ptr->next,std::memory_order_relaxed)) { std::shared_ptr<T> res; res.swap(ptr->data); int const count_increase=old_head.external_count-2; if(ptr->internal_count.fetch_add( count_increase,std::memory_order_release)==-count_increase) { delete ptr; } return res; } else if(ptr->internal_count.fetch_add( -1,std::memory_order_relaxed)==1) { ptr->internal_count.load(std::memory_order_acquire); delete ptr; } } } };
28.168539
82
0.526526
plaice
f52d93a2e062ff8571612c32c27b77969093c9c3
2,101
hpp
C++
tstl/include/stack.hpp
ArdenyUser/ArdenWareOS
e09261093ba469d2291554c026037351bba28ab0
[ "MIT" ]
1,574
2015-01-15T16:35:30.000Z
2022-03-29T07:27:49.000Z
tstl/include/stack.hpp
bgwilf/thor-os
2dc0fef72595598aff7e5f950809042104f29b48
[ "MIT" ]
43
2016-08-23T16:22:29.000Z
2022-03-09T10:28:05.000Z
tstl/include/stack.hpp
bgwilf/thor-os
2dc0fef72595598aff7e5f950809042104f29b48
[ "MIT" ]
196
2016-02-17T10:52:24.000Z
2022-03-28T17:41:29.000Z
//======================================================================= // Copyright Baptiste Wicht 2013-2018. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #ifndef STL_STACK_H #define STL_STACK_H #include <vector.hpp> #include <types.hpp> namespace std { /*! * \brief Container adapter to provide a stack (LIFO) */ template<typename T, typename C = std::vector<T>> struct stack { using reference_type = typename C::reference_type; using const_reference_type = typename C::const_reference_type; /*! * \brief Indicates if the stack is empty */ bool empty() const { return size() == 0; } /*! * \brief Returns the size of the stack */ size_t size() const { return container.size(); } /*! * \brief Adds the element at the top of the stack * \param value The element to add on the stack */ void push(T&& value){ container.push_back(std::move(value)); } /*! * \brief Adds the element at the top of the stack * \param value The element to add on the stack */ void push(const T& value){ container.push_back(value); } /*! * \brief Create a new element inplace onto the stack */ template<typename... Args> reference_type emplace(Args&&... args){ return container.emplace_back(std::forward<Args>(args)...); } /*! * \brief Removes the element at the top of the stack */ void pop(){ container.pop_back(); } /*! * \brief Returns a reference to the element at the top of the stack */ reference_type top(){ return container.back(); } /*! * \brief Returns a const reference to the element at the top of the stack */ const_reference_type top() const { return container.back(); } private: C container; ///< The underlying container }; } //end of namespace std #endif
23.344444
78
0.568777
ArdenyUser
f52e2418091bfc9c0e9ace94636dd31cc4936a95
6,356
cpp
C++
qcom-caf/display/libhistogram/histogram_collector.cpp
Havoc-Devices/android_device_motorola_sm7250-common
c957b40642f2c2a6b174832e3a19e823aa25363f
[ "FTL" ]
4
2020-12-17T13:39:05.000Z
2022-02-11T10:24:58.000Z
qcom-caf/display/libhistogram/histogram_collector.cpp
Havoc-Devices/android_device_motorola_sm7250-common
c957b40642f2c2a6b174832e3a19e823aa25363f
[ "FTL" ]
null
null
null
qcom-caf/display/libhistogram/histogram_collector.cpp
Havoc-Devices/android_device_motorola_sm7250-common
c957b40642f2c2a6b174832e3a19e823aa25363f
[ "FTL" ]
4
2021-01-07T12:31:21.000Z
2021-12-27T19:08:12.000Z
/* * Copyright (C) 2018 The Android Open Source Project * * 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 <fcntl.h> #include <log/log.h> #include <pthread.h> #include <sys/epoll.h> #include <sys/prctl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <chrono> #include <ctime> #include <fstream> #include <iomanip> #include <memory> #include <sstream> #include <tuple> #include <unordered_map> #include <vector> #include <drm/msm_drm.h> #include <drm/msm_drm_pp.h> #include <xf86drm.h> #include <xf86drmMode.h> #include "histogram_collector.h" #include "ringbuffer.h" constexpr static auto implementation_defined_max_frame_ringbuffer = 300; histogram::HistogramCollector::HistogramCollector() : histogram(histogram::Ringbuffer::create(implementation_defined_max_frame_ringbuffer, std::make_unique<histogram::DefaultTimeKeeper>())) {} histogram::HistogramCollector::~HistogramCollector() { stop(); } namespace { static constexpr size_t numBuckets = 8; static_assert((HIST_V_SIZE % numBuckets) == 0, "histogram cannot be rebucketed to smaller number of buckets"); static constexpr int bucket_compression = HIST_V_SIZE / numBuckets; std::array<uint64_t, numBuckets> rebucketTo8Buckets( std::array<uint64_t, HIST_V_SIZE> const &frame) { std::array<uint64_t, numBuckets> bins; bins.fill(0); for (auto i = 0u; i < HIST_V_SIZE; i++) bins[i / bucket_compression] += frame[i]; return bins; } } // namespace std::string histogram::HistogramCollector::Dump() const { uint64_t num_frames = 0; std::array<uint64_t, HIST_V_SIZE> all_sample_buckets; std::tie(num_frames, all_sample_buckets) = histogram->collect_cumulative(); std::array<uint64_t, numBuckets> samples = rebucketTo8Buckets(all_sample_buckets); std::stringstream ss; ss << "Color Sampling, dark (0.0) to light (1.0): sampled frames: " << num_frames << '\n'; if (num_frames == 0) { ss << "\tno color statistics collected\n"; return ss.str(); } ss << std::fixed << std::setprecision(3); ss << "\tbucket\t\t: # of displayed pixels at bucket value\n"; for (auto i = 0u; i < samples.size(); i++) { ss << "\t" << i / static_cast<float>(samples.size()) << " to " << (i + 1) / static_cast<float>(samples.size()) << "\t: " << samples[i] << '\n'; } return ss.str(); } HWC2::Error histogram::HistogramCollector::collect( uint64_t max_frames, uint64_t timestamp, int32_t out_samples_size[NUM_HISTOGRAM_COLOR_COMPONENTS], uint64_t *out_samples[NUM_HISTOGRAM_COLOR_COMPONENTS], uint64_t *out_num_frames) const { if (!out_samples_size || !out_num_frames) return HWC2::Error::BadParameter; out_samples_size[0] = 0; out_samples_size[1] = 0; out_samples_size[2] = numBuckets; out_samples_size[3] = 0; uint64_t num_frames = 0; std::array<uint64_t, HIST_V_SIZE> samples; if (max_frames == 0 && timestamp == 0) { std::tie(num_frames, samples) = histogram->collect_cumulative(); } else if (max_frames == 0) { std::tie(num_frames, samples) = histogram->collect_after(timestamp); } else if (timestamp == 0) { std::tie(num_frames, samples) = histogram->collect_max(max_frames); } else { std::tie(num_frames, samples) = histogram->collect_max_after(timestamp, max_frames); } auto samples_rebucketed = rebucketTo8Buckets(samples); *out_num_frames = num_frames; if (out_samples && out_samples[2]) memcpy(out_samples[2], samples_rebucketed.data(), sizeof(uint64_t) * samples_rebucketed.size()); return HWC2::Error::None; } HWC2::Error histogram::HistogramCollector::getAttributes(int32_t *format, int32_t *dataspace, uint8_t *supported_components) const { if (!format || !dataspace || !supported_components) return HWC2::Error::BadParameter; *format = HAL_PIXEL_FORMAT_HSV_888; *dataspace = HAL_DATASPACE_UNKNOWN; *supported_components = HWC2_FORMAT_COMPONENT_2; return HWC2::Error::None; } void histogram::HistogramCollector::start() { start(implementation_defined_max_frame_ringbuffer); } void histogram::HistogramCollector::start(uint64_t max_frames) { std::unique_lock<decltype(mutex)> lk(mutex); if (started) { return; } started = true; histogram = histogram::Ringbuffer::create(max_frames, std::make_unique<histogram::DefaultTimeKeeper>()); monitoring_thread = std::thread(&HistogramCollector::blob_processing_thread, this); } void histogram::HistogramCollector::stop() { std::unique_lock<decltype(mutex)> lk(mutex); if (!started) { return; } started = false; cv.notify_all(); lk.unlock(); if (monitoring_thread.joinable()) monitoring_thread.join(); } void histogram::HistogramCollector::notify_histogram_event(int blob_source_fd, BlobId id) { std::unique_lock<decltype(mutex)> lk(mutex); if (!started) { ALOGW("Discarding event blob-id: %X", id); return; } if (work_available) { ALOGI("notified of histogram event before consuming last one. prior event discarded"); } work_available = true; blobwork = HistogramCollector::BlobWork{blob_source_fd, id}; cv.notify_all(); } void histogram::HistogramCollector::blob_processing_thread() { pthread_setname_np(pthread_self(), "histogram_blob"); std::unique_lock<decltype(mutex)> lk(mutex); while (true) { cv.wait(lk, [this] { return !started || work_available; }); if (!started) { return; } auto work = blobwork; work_available = false; lk.unlock(); drmModePropertyBlobPtr blob = drmModeGetPropertyBlob(work.fd, work.id); if (!blob || !blob->data) { lk.lock(); continue; } histogram->insert(*static_cast<struct drm_msm_hist *>(blob->data)); drmModeFreePropertyBlob(blob); lk.lock(); } }
30.705314
100
0.696665
Havoc-Devices
f52f9daac85badd14ed77a9dd5f2926218f2c88b
8,335
cpp
C++
tests/Loading/Theme.cpp
dmg103/TGUI
ed2ac830c399b8b579dc67493823551dbf966d63
[ "Zlib" ]
null
null
null
tests/Loading/Theme.cpp
dmg103/TGUI
ed2ac830c399b8b579dc67493823551dbf966d63
[ "Zlib" ]
null
null
null
tests/Loading/Theme.cpp
dmg103/TGUI
ed2ac830c399b8b579dc67493823551dbf966d63
[ "Zlib" ]
null
null
null
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // TGUI - Texus' Graphical User Interface // Copyright (C) 2012-2022 Bruno Van de Velde ([email protected]) // // 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 "Tests.hpp" #include <TGUI/Loading/Theme.hpp> #include <TGUI/Widgets/Label.hpp> // TODO: Reloading theme TEST_CASE("[Theme]") { SECTION("Loading") { SECTION("Renderers are shared") { tgui::Theme theme; REQUIRE(theme.getPrimary() == ""); REQUIRE_NOTHROW(theme.getRenderer("Button")); REQUIRE_NOTHROW(theme.load("resources/Black.txt")); REQUIRE(theme.getPrimary() == "resources/Black.txt"); REQUIRE_NOTHROW(theme.getRenderer("EditBox")); auto theme2 = tgui::Theme::create("resources/Black.txt"); REQUIRE(theme2->getPrimary() == "resources/Black.txt"); REQUIRE_NOTHROW(theme2->getRenderer("CheckBox")); } SECTION("nonexistent file") { REQUIRE_THROWS_AS(tgui::Theme("nonexistent_file"), tgui::Exception); tgui::Theme theme; REQUIRE_THROWS_AS(theme.load("nonexistent_file"), tgui::Exception); } SECTION("nonexistent section") { // White theme is created on the fly as it uses default values tgui::Theme theme1; REQUIRE(theme1.getRenderer("nonexistent_section")->propertyValuePairs.empty()); // Other themes on the other hand will let the ThemeLoader handle it tgui::Theme theme2("resources/Black.txt"); REQUIRE_THROWS_AS(theme2.getRenderer("nonexistent_section"), tgui::Exception); } } SECTION("Adding and removing renderers") { auto data = std::make_shared<tgui::RendererData>(); data->propertyValuePairs["TextColor"] = {tgui::Color(255, 0, 255, 200)}; tgui::Theme theme; REQUIRE(theme.getRenderer("Label1")->propertyValuePairs.empty()); REQUIRE(theme.getRenderer("Label2")->propertyValuePairs.empty()); theme.addRenderer("Label1", data); REQUIRE(theme.getRenderer("Label1")->propertyValuePairs.size() == 1); REQUIRE(theme.getRenderer("Label1")->propertyValuePairs["TextColor"].getColor() == tgui::Color(255, 0, 255, 200)); REQUIRE(theme.getRenderer("Label2")->propertyValuePairs.empty()); REQUIRE(theme.removeRenderer("Label1")); REQUIRE(theme.getRenderer("Label1")->propertyValuePairs.empty()); REQUIRE(!theme.removeRenderer("nonexistent")); } SECTION("Renderers are shared") { tgui::Theme theme{"resources/Black.txt"}; SECTION("With widgets") { SECTION("Using getSharedRenderer") { auto label1 = tgui::Label::create(); label1->getSharedRenderer()->setTextColor("red"); REQUIRE(label1->getSharedRenderer()->getTextColor() == tgui::Color::Red); label1->setRenderer(theme.getRenderer("Label")); REQUIRE(label1->getSharedRenderer()->getTextColor() != tgui::Color::Red); label1->getSharedRenderer()->setTextColor("green"); REQUIRE(label1->getSharedRenderer()->getTextColor() == tgui::Color::Green); auto label2 = tgui::Label::create(); label2->getSharedRenderer()->setTextColor("blue"); REQUIRE(label2->getSharedRenderer()->getTextColor() == tgui::Color::Blue); label2->setRenderer(theme.getRenderer("Label")); REQUIRE(label1->getSharedRenderer()->getTextColor() == tgui::Color::Green); // Changing the renderer of one label affects the look of the other one label1->getSharedRenderer()->setTextColor("yellow"); REQUIRE(label2->getSharedRenderer()->getTextColor() == tgui::Color::Yellow); // We messed with the default theme, so reset it to not affect other tests tgui::Theme::setDefault(nullptr); } SECTION("Using getRenderer") { auto label1 = tgui::Label::create(); label1->getRenderer()->setTextColor("red"); REQUIRE(label1->getRenderer()->getTextColor() == tgui::Color::Red); label1->setRenderer(theme.getRenderer("Label")); REQUIRE(label1->getRenderer()->getTextColor() != tgui::Color::Red); label1->getRenderer()->setTextColor("green"); REQUIRE(label1->getRenderer()->getTextColor() == tgui::Color::Green); auto label2 = tgui::Label::create(); label2->getRenderer()->setTextColor("blue"); REQUIRE(label2->getRenderer()->getTextColor() == tgui::Color::Blue); label2->setRenderer(theme.getRenderer("Label")); REQUIRE(label1->getRenderer()->getTextColor() == tgui::Color::Green); // Changing the renderer of one label does not affect the other one label1->getRenderer()->setTextColor("yellow"); REQUIRE(label2->getRenderer()->getTextColor() != tgui::Color::Yellow); } } SECTION("Without widgets") { REQUIRE(tgui::LabelRenderer(theme.getRenderer("Label")).getTextColor() != tgui::Color::Cyan); tgui::LabelRenderer(theme.getRenderer("Label")).setTextColor(tgui::Color::Cyan); REQUIRE(tgui::LabelRenderer(theme.getRenderer("Label")).getTextColor() == tgui::Color::Cyan); REQUIRE(theme.getRenderer("Label")->propertyValuePairs["TextColor"].getColor() == tgui::Color::Cyan); } } SECTION("setThemeLoader") { struct CustomThemeLoader : public tgui::BaseThemeLoader { void preload(const tgui::String& one) override { REQUIRE(one == "resources/Black.txt"); preloadCount++; } const std::map<tgui::String, tgui::String>& load(const tgui::String& one, const tgui::String& two) override { if (one != "") { REQUIRE(one == "resources/Black.txt"); REQUIRE(two == "EditBox"); } else REQUIRE(two == "Button"); loadCount++; return retVal; } bool canLoad(const tgui::String&, const tgui::String&) override { return true; } std::map<tgui::String, tgui::String> retVal; unsigned int preloadCount = 0; unsigned int loadCount = 0; }; auto loader = std::make_shared<CustomThemeLoader>(); tgui::Theme::setThemeLoader(loader); REQUIRE(tgui::Theme::getThemeLoader() == loader); tgui::Theme theme1; theme1.getRenderer("Button"); tgui::Theme theme2("resources/Black.txt"); theme2.getRenderer("EditBox"); tgui::Theme::setThemeLoader(std::make_shared<tgui::DefaultThemeLoader>()); REQUIRE(tgui::Theme::getThemeLoader() != loader); REQUIRE(loader->preloadCount == 1); REQUIRE(loader->loadCount == 2); } }
39.880383
129
0.574325
dmg103
f52fd92cd26d6c15a6b524d4a28644e6219fde2d
18,960
cpp
C++
test/entt/entity/sparse_set.cpp
janisozaur/entt
be3597524f07ee502be8784ed193812ce4fb9cb9
[ "MIT" ]
32
2018-05-14T23:26:54.000Z
2020-06-14T10:13:20.000Z
ext/entt-3.1.1/test/entt/entity/sparse_set.cpp
blockspacer/bootstrap-redux
2d0e0d7d2b1f6f203c3dd01f6929805042db8ec7
[ "MIT" ]
79
2018-08-01T11:50:45.000Z
2020-11-17T13:40:06.000Z
ext/entt-3.1.1/test/entt/entity/sparse_set.cpp
blockspacer/bootstrap-redux
2d0e0d7d2b1f6f203c3dd01f6929805042db8ec7
[ "MIT" ]
14
2021-01-08T05:05:19.000Z
2022-03-27T14:56:56.000Z
#include <cstdint> #include <utility> #include <iterator> #include <type_traits> #include <gtest/gtest.h> #include <entt/entity/sparse_set.hpp> #include <entt/entity/fwd.hpp> struct empty_type {}; struct boxed_int { int value; }; TEST(SparseSet, Functionalities) { entt::sparse_set<entt::entity> set; set.reserve(42); ASSERT_EQ(set.capacity(), 42); ASSERT_TRUE(set.empty()); ASSERT_EQ(set.size(), 0u); ASSERT_EQ(std::as_const(set).begin(), std::as_const(set).end()); ASSERT_EQ(set.begin(), set.end()); ASSERT_FALSE(set.has(entt::entity{0})); ASSERT_FALSE(set.has(entt::entity{42})); set.construct(entt::entity{42}); ASSERT_EQ(set.index(entt::entity{42}), 0u); ASSERT_FALSE(set.empty()); ASSERT_EQ(set.size(), 1u); ASSERT_NE(std::as_const(set).begin(), std::as_const(set).end()); ASSERT_NE(set.begin(), set.end()); ASSERT_FALSE(set.has(entt::entity{0})); ASSERT_TRUE(set.has(entt::entity{42})); ASSERT_EQ(set.index(entt::entity{42}), 0u); set.destroy(entt::entity{42}); ASSERT_TRUE(set.empty()); ASSERT_EQ(set.size(), 0u); ASSERT_EQ(std::as_const(set).begin(), std::as_const(set).end()); ASSERT_EQ(set.begin(), set.end()); ASSERT_FALSE(set.has(entt::entity{0})); ASSERT_FALSE(set.has(entt::entity{42})); set.construct(entt::entity{42}); ASSERT_FALSE(set.empty()); ASSERT_EQ(set.index(entt::entity{42}), 0u); ASSERT_TRUE(std::is_move_constructible_v<decltype(set)>); ASSERT_TRUE(std::is_move_assignable_v<decltype(set)>); entt::sparse_set<entt::entity> cpy{set}; set = cpy; ASSERT_FALSE(set.empty()); ASSERT_FALSE(cpy.empty()); ASSERT_EQ(set.index(entt::entity{42}), 0u); ASSERT_EQ(cpy.index(entt::entity{42}), 0u); entt::sparse_set<entt::entity> other{std::move(set)}; set = std::move(other); other = std::move(set); ASSERT_TRUE(set.empty()); ASSERT_FALSE(other.empty()); ASSERT_EQ(other.index(entt::entity{42}), 0u); other.reset(); ASSERT_TRUE(other.empty()); ASSERT_EQ(other.size(), 0u); ASSERT_EQ(std::as_const(other).begin(), std::as_const(other).end()); ASSERT_EQ(other.begin(), other.end()); ASSERT_FALSE(other.has(entt::entity{0})); ASSERT_FALSE(other.has(entt::entity{42})); } TEST(SparseSet, Pagination) { entt::sparse_set<entt::entity> set; constexpr auto entt_per_page = ENTT_PAGE_SIZE / sizeof(std::underlying_type_t<entt::entity>); ASSERT_EQ(set.extent(), 0); set.construct(entt::entity{entt_per_page-1}); ASSERT_EQ(set.extent(), entt_per_page); ASSERT_TRUE(set.has(entt::entity{entt_per_page-1})); set.construct(entt::entity{entt_per_page}); ASSERT_EQ(set.extent(), 2 * entt_per_page); ASSERT_TRUE(set.has(entt::entity{entt_per_page-1})); ASSERT_TRUE(set.has(entt::entity{entt_per_page})); ASSERT_FALSE(set.has(entt::entity{entt_per_page+1})); set.destroy(entt::entity{entt_per_page-1}); ASSERT_EQ(set.extent(), 2 * entt_per_page); ASSERT_FALSE(set.has(entt::entity{entt_per_page-1})); ASSERT_TRUE(set.has(entt::entity{entt_per_page})); set.shrink_to_fit(); set.destroy(entt::entity{entt_per_page}); ASSERT_EQ(set.extent(), 2 * entt_per_page); ASSERT_FALSE(set.has(entt::entity{entt_per_page-1})); ASSERT_FALSE(set.has(entt::entity{entt_per_page})); set.shrink_to_fit(); ASSERT_EQ(set.extent(), 0); } TEST(SparseSet, BatchAdd) { entt::sparse_set<entt::entity> set; entt::entity entities[2]; entities[0] = entt::entity{3}; entities[1] = entt::entity{42}; set.construct(entt::entity{12}); set.batch(std::begin(entities), std::end(entities)); set.construct(entt::entity{24}); ASSERT_TRUE(set.has(entities[0])); ASSERT_TRUE(set.has(entities[1])); ASSERT_FALSE(set.has(entt::entity{0})); ASSERT_FALSE(set.has(entt::entity{9})); ASSERT_TRUE(set.has(entt::entity{12})); ASSERT_TRUE(set.has(entt::entity{24})); ASSERT_FALSE(set.empty()); ASSERT_EQ(set.size(), 4u); ASSERT_EQ(set.index(entt::entity{12}), 0u); ASSERT_EQ(set.index(entities[0]), 1u); ASSERT_EQ(set.index(entities[1]), 2u); ASSERT_EQ(set.index(entt::entity{24}), 3u); ASSERT_EQ(set.data()[set.index(entt::entity{12})], entt::entity{12}); ASSERT_EQ(set.data()[set.index(entities[0])], entities[0]); ASSERT_EQ(set.data()[set.index(entities[1])], entities[1]); ASSERT_EQ(set.data()[set.index(entt::entity{24})], entt::entity{24}); } TEST(SparseSet, Iterator) { using iterator_type = typename entt::sparse_set<entt::entity>::iterator_type; entt::sparse_set<entt::entity> set; set.construct(entt::entity{3}); iterator_type end{set.begin()}; iterator_type begin{}; begin = set.end(); std::swap(begin, end); ASSERT_EQ(begin, set.begin()); ASSERT_EQ(end, set.end()); ASSERT_NE(begin, end); ASSERT_EQ(begin++, set.begin()); ASSERT_EQ(begin--, set.end()); ASSERT_EQ(begin+1, set.end()); ASSERT_EQ(end-1, set.begin()); ASSERT_EQ(++begin, set.end()); ASSERT_EQ(--begin, set.begin()); ASSERT_EQ(begin += 1, set.end()); ASSERT_EQ(begin -= 1, set.begin()); ASSERT_EQ(begin + (end - begin), set.end()); ASSERT_EQ(begin - (begin - end), set.end()); ASSERT_EQ(end - (end - begin), set.begin()); ASSERT_EQ(end + (begin - end), set.begin()); ASSERT_EQ(begin[0], *set.begin()); ASSERT_LT(begin, end); ASSERT_LE(begin, set.begin()); ASSERT_GT(end, begin); ASSERT_GE(end, set.end()); ASSERT_EQ(*begin, entt::entity{3}); ASSERT_EQ(*begin.operator->(), entt::entity{3}); } TEST(SparseSet, Find) { entt::sparse_set<entt::entity> set; set.construct(entt::entity{3}); set.construct(entt::entity{42}); set.construct(entt::entity{99}); ASSERT_NE(set.find(entt::entity{3}), set.end()); ASSERT_NE(set.find(entt::entity{42}), set.end()); ASSERT_NE(set.find(entt::entity{99}), set.end()); ASSERT_EQ(set.find(entt::entity{0}), set.end()); auto it = set.find(entt::entity{99}); ASSERT_EQ(*it, entt::entity{99}); ASSERT_EQ(*(++it), entt::entity{42}); ASSERT_EQ(*(++it), entt::entity{3}); ASSERT_EQ(++it, set.end()); ASSERT_EQ(++set.find(entt::entity{3}), set.end()); } TEST(SparseSet, Data) { entt::sparse_set<entt::entity> set; set.construct(entt::entity{3}); set.construct(entt::entity{12}); set.construct(entt::entity{42}); ASSERT_EQ(set.index(entt::entity{3}), 0u); ASSERT_EQ(set.index(entt::entity{12}), 1u); ASSERT_EQ(set.index(entt::entity{42}), 2u); ASSERT_EQ(*(set.data() + 0u), entt::entity{3}); ASSERT_EQ(*(set.data() + 1u), entt::entity{12}); ASSERT_EQ(*(set.data() + 2u), entt::entity{42}); } TEST(SparseSet, SortOrdered) { entt::sparse_set<entt::entity> set; set.construct(entt::entity{42}); set.construct(entt::entity{12}); set.construct(entt::entity{9}); set.construct(entt::entity{7}); set.construct(entt::entity{3}); ASSERT_EQ(*(set.data() + 0u), entt::entity{42}); ASSERT_EQ(*(set.data() + 1u), entt::entity{12}); ASSERT_EQ(*(set.data() + 2u), entt::entity{9}); ASSERT_EQ(*(set.data() + 3u), entt::entity{7}); ASSERT_EQ(*(set.data() + 4u), entt::entity{3}); set.sort(set.begin(), set.end(), [](const auto lhs, const auto rhs) { return std::underlying_type_t<entt::entity>(lhs) < std::underlying_type_t<entt::entity>(rhs); }); ASSERT_EQ(*(set.data() + 0u), entt::entity{42}); ASSERT_EQ(*(set.data() + 1u), entt::entity{12}); ASSERT_EQ(*(set.data() + 2u), entt::entity{9}); ASSERT_EQ(*(set.data() + 3u), entt::entity{7}); ASSERT_EQ(*(set.data() + 4u), entt::entity{3}); auto begin = set.begin(); auto end = set.end(); ASSERT_EQ(*(begin++), entt::entity{3}); ASSERT_EQ(*(begin++), entt::entity{7}); ASSERT_EQ(*(begin++), entt::entity{9}); ASSERT_EQ(*(begin++), entt::entity{12}); ASSERT_EQ(*(begin++), entt::entity{42}); ASSERT_EQ(begin, end); } TEST(SparseSet, SortReverse) { entt::sparse_set<entt::entity> set; set.construct(entt::entity{3}); set.construct(entt::entity{7}); set.construct(entt::entity{9}); set.construct(entt::entity{12}); set.construct(entt::entity{42}); ASSERT_EQ(*(set.data() + 0u), entt::entity{3}); ASSERT_EQ(*(set.data() + 1u), entt::entity{7}); ASSERT_EQ(*(set.data() + 2u), entt::entity{9}); ASSERT_EQ(*(set.data() + 3u), entt::entity{12}); ASSERT_EQ(*(set.data() + 4u), entt::entity{42}); set.sort(set.begin(), set.end(), [](const auto lhs, const auto rhs) { return std::underlying_type_t<entt::entity>(lhs) < std::underlying_type_t<entt::entity>(rhs); }); ASSERT_EQ(*(set.data() + 0u), entt::entity{42}); ASSERT_EQ(*(set.data() + 1u), entt::entity{12}); ASSERT_EQ(*(set.data() + 2u), entt::entity{9}); ASSERT_EQ(*(set.data() + 3u), entt::entity{7}); ASSERT_EQ(*(set.data() + 4u), entt::entity{3}); auto begin = set.begin(); auto end = set.end(); ASSERT_EQ(*(begin++), entt::entity{3}); ASSERT_EQ(*(begin++), entt::entity{7}); ASSERT_EQ(*(begin++), entt::entity{9}); ASSERT_EQ(*(begin++), entt::entity{12}); ASSERT_EQ(*(begin++), entt::entity{42}); ASSERT_EQ(begin, end); } TEST(SparseSet, SortUnordered) { entt::sparse_set<entt::entity> set; set.construct(entt::entity{9}); set.construct(entt::entity{7}); set.construct(entt::entity{3}); set.construct(entt::entity{12}); set.construct(entt::entity{42}); ASSERT_EQ(*(set.data() + 0u), entt::entity{9}); ASSERT_EQ(*(set.data() + 1u), entt::entity{7}); ASSERT_EQ(*(set.data() + 2u), entt::entity{3}); ASSERT_EQ(*(set.data() + 3u), entt::entity{12}); ASSERT_EQ(*(set.data() + 4u), entt::entity{42}); set.sort(set.begin(), set.end(), [](const auto lhs, const auto rhs) { return std::underlying_type_t<entt::entity>(lhs) < std::underlying_type_t<entt::entity>(rhs); }); ASSERT_EQ(*(set.data() + 0u), entt::entity{42}); ASSERT_EQ(*(set.data() + 1u), entt::entity{12}); ASSERT_EQ(*(set.data() + 2u), entt::entity{9}); ASSERT_EQ(*(set.data() + 3u), entt::entity{7}); ASSERT_EQ(*(set.data() + 4u), entt::entity{3}); auto begin = set.begin(); auto end = set.end(); ASSERT_EQ(*(begin++), entt::entity{3}); ASSERT_EQ(*(begin++), entt::entity{7}); ASSERT_EQ(*(begin++), entt::entity{9}); ASSERT_EQ(*(begin++), entt::entity{12}); ASSERT_EQ(*(begin++), entt::entity{42}); ASSERT_EQ(begin, end); } TEST(SparseSet, SortRange) { entt::sparse_set<entt::entity> set; set.construct(entt::entity{9}); set.construct(entt::entity{7}); set.construct(entt::entity{3}); set.construct(entt::entity{12}); set.construct(entt::entity{42}); ASSERT_EQ(*(set.data() + 0u), entt::entity{9}); ASSERT_EQ(*(set.data() + 1u), entt::entity{7}); ASSERT_EQ(*(set.data() + 2u), entt::entity{3}); ASSERT_EQ(*(set.data() + 3u), entt::entity{12}); ASSERT_EQ(*(set.data() + 4u), entt::entity{42}); set.sort(set.end(), set.end(), [](const auto lhs, const auto rhs) { return std::underlying_type_t<entt::entity>(lhs) < std::underlying_type_t<entt::entity>(rhs); }); ASSERT_EQ(*(set.data() + 0u), entt::entity{9}); ASSERT_EQ(*(set.data() + 1u), entt::entity{7}); ASSERT_EQ(*(set.data() + 2u), entt::entity{3}); ASSERT_EQ(*(set.data() + 3u), entt::entity{12}); ASSERT_EQ(*(set.data() + 4u), entt::entity{42}); set.sort(set.begin(), set.begin(), [](const auto lhs, const auto rhs) { return std::underlying_type_t<entt::entity>(lhs) < std::underlying_type_t<entt::entity>(rhs); }); ASSERT_EQ(*(set.data() + 0u), entt::entity{9}); ASSERT_EQ(*(set.data() + 1u), entt::entity{7}); ASSERT_EQ(*(set.data() + 2u), entt::entity{3}); ASSERT_EQ(*(set.data() + 3u), entt::entity{12}); ASSERT_EQ(*(set.data() + 4u), entt::entity{42}); set.sort(set.begin()+2, set.begin()+3, [](const auto lhs, const auto rhs) { return std::underlying_type_t<entt::entity>(lhs) < std::underlying_type_t<entt::entity>(rhs); }); ASSERT_EQ(*(set.data() + 0u), entt::entity{9}); ASSERT_EQ(*(set.data() + 1u), entt::entity{7}); ASSERT_EQ(*(set.data() + 2u), entt::entity{3}); ASSERT_EQ(*(set.data() + 3u), entt::entity{12}); ASSERT_EQ(*(set.data() + 4u), entt::entity{42}); set.sort(++set.begin(), --set.end(), [](const auto lhs, const auto rhs) { return std::underlying_type_t<entt::entity>(lhs) < std::underlying_type_t<entt::entity>(rhs); }); ASSERT_EQ(*(set.data() + 0u), entt::entity{9}); ASSERT_EQ(*(set.data() + 1u), entt::entity{12}); ASSERT_EQ(*(set.data() + 2u), entt::entity{7}); ASSERT_EQ(*(set.data() + 3u), entt::entity{3}); ASSERT_EQ(*(set.data() + 4u), entt::entity{42}); auto begin = set.begin(); auto end = set.end(); ASSERT_EQ(*(begin++), entt::entity{42}); ASSERT_EQ(*(begin++), entt::entity{3}); ASSERT_EQ(*(begin++), entt::entity{7}); ASSERT_EQ(*(begin++), entt::entity{12}); ASSERT_EQ(*(begin++), entt::entity{9}); ASSERT_EQ(begin, end); } TEST(SparseSet, RespectDisjoint) { entt::sparse_set<entt::entity> lhs; entt::sparse_set<entt::entity> rhs; lhs.construct(entt::entity{3}); lhs.construct(entt::entity{12}); lhs.construct(entt::entity{42}); ASSERT_EQ(lhs.index(entt::entity{3}), 0u); ASSERT_EQ(lhs.index(entt::entity{12}), 1u); ASSERT_EQ(lhs.index(entt::entity{42}), 2u); lhs.respect(rhs); ASSERT_EQ(std::as_const(lhs).index(entt::entity{3}), 0u); ASSERT_EQ(std::as_const(lhs).index(entt::entity{12}), 1u); ASSERT_EQ(std::as_const(lhs).index(entt::entity{42}), 2u); } TEST(SparseSet, RespectOverlap) { entt::sparse_set<entt::entity> lhs; entt::sparse_set<entt::entity> rhs; lhs.construct(entt::entity{3}); lhs.construct(entt::entity{12}); lhs.construct(entt::entity{42}); rhs.construct(entt::entity{12}); ASSERT_EQ(lhs.index(entt::entity{3}), 0u); ASSERT_EQ(lhs.index(entt::entity{12}), 1u); ASSERT_EQ(lhs.index(entt::entity{42}), 2u); lhs.respect(rhs); ASSERT_EQ(std::as_const(lhs).index(entt::entity{3}), 0u); ASSERT_EQ(std::as_const(lhs).index(entt::entity{12}), 2u); ASSERT_EQ(std::as_const(lhs).index(entt::entity{42}), 1u); } TEST(SparseSet, RespectOrdered) { entt::sparse_set<entt::entity> lhs; entt::sparse_set<entt::entity> rhs; lhs.construct(entt::entity{1}); lhs.construct(entt::entity{2}); lhs.construct(entt::entity{3}); lhs.construct(entt::entity{4}); lhs.construct(entt::entity{5}); ASSERT_EQ(lhs.index(entt::entity{1}), 0u); ASSERT_EQ(lhs.index(entt::entity{2}), 1u); ASSERT_EQ(lhs.index(entt::entity{3}), 2u); ASSERT_EQ(lhs.index(entt::entity{4}), 3u); ASSERT_EQ(lhs.index(entt::entity{5}), 4u); rhs.construct(entt::entity{6}); rhs.construct(entt::entity{1}); rhs.construct(entt::entity{2}); rhs.construct(entt::entity{3}); rhs.construct(entt::entity{4}); rhs.construct(entt::entity{5}); ASSERT_EQ(rhs.index(entt::entity{6}), 0u); ASSERT_EQ(rhs.index(entt::entity{1}), 1u); ASSERT_EQ(rhs.index(entt::entity{2}), 2u); ASSERT_EQ(rhs.index(entt::entity{3}), 3u); ASSERT_EQ(rhs.index(entt::entity{4}), 4u); ASSERT_EQ(rhs.index(entt::entity{5}), 5u); rhs.respect(lhs); ASSERT_EQ(rhs.index(entt::entity{6}), 0u); ASSERT_EQ(rhs.index(entt::entity{1}), 1u); ASSERT_EQ(rhs.index(entt::entity{2}), 2u); ASSERT_EQ(rhs.index(entt::entity{3}), 3u); ASSERT_EQ(rhs.index(entt::entity{4}), 4u); ASSERT_EQ(rhs.index(entt::entity{5}), 5u); } TEST(SparseSet, RespectReverse) { entt::sparse_set<entt::entity> lhs; entt::sparse_set<entt::entity> rhs; lhs.construct(entt::entity{1}); lhs.construct(entt::entity{2}); lhs.construct(entt::entity{3}); lhs.construct(entt::entity{4}); lhs.construct(entt::entity{5}); ASSERT_EQ(lhs.index(entt::entity{1}), 0u); ASSERT_EQ(lhs.index(entt::entity{2}), 1u); ASSERT_EQ(lhs.index(entt::entity{3}), 2u); ASSERT_EQ(lhs.index(entt::entity{4}), 3u); ASSERT_EQ(lhs.index(entt::entity{5}), 4u); rhs.construct(entt::entity{5}); rhs.construct(entt::entity{4}); rhs.construct(entt::entity{3}); rhs.construct(entt::entity{2}); rhs.construct(entt::entity{1}); rhs.construct(entt::entity{6}); ASSERT_EQ(rhs.index(entt::entity{5}), 0u); ASSERT_EQ(rhs.index(entt::entity{4}), 1u); ASSERT_EQ(rhs.index(entt::entity{3}), 2u); ASSERT_EQ(rhs.index(entt::entity{2}), 3u); ASSERT_EQ(rhs.index(entt::entity{1}), 4u); ASSERT_EQ(rhs.index(entt::entity{6}), 5u); rhs.respect(lhs); ASSERT_EQ(rhs.index(entt::entity{6}), 0u); ASSERT_EQ(rhs.index(entt::entity{1}), 1u); ASSERT_EQ(rhs.index(entt::entity{2}), 2u); ASSERT_EQ(rhs.index(entt::entity{3}), 3u); ASSERT_EQ(rhs.index(entt::entity{4}), 4u); ASSERT_EQ(rhs.index(entt::entity{5}), 5u); } TEST(SparseSet, RespectUnordered) { entt::sparse_set<entt::entity> lhs; entt::sparse_set<entt::entity> rhs; lhs.construct(entt::entity{1}); lhs.construct(entt::entity{2}); lhs.construct(entt::entity{3}); lhs.construct(entt::entity{4}); lhs.construct(entt::entity{5}); ASSERT_EQ(lhs.index(entt::entity{1}), 0u); ASSERT_EQ(lhs.index(entt::entity{2}), 1u); ASSERT_EQ(lhs.index(entt::entity{3}), 2u); ASSERT_EQ(lhs.index(entt::entity{4}), 3u); ASSERT_EQ(lhs.index(entt::entity{5}), 4u); rhs.construct(entt::entity{3}); rhs.construct(entt::entity{2}); rhs.construct(entt::entity{6}); rhs.construct(entt::entity{1}); rhs.construct(entt::entity{4}); rhs.construct(entt::entity{5}); ASSERT_EQ(rhs.index(entt::entity{3}), 0u); ASSERT_EQ(rhs.index(entt::entity{2}), 1u); ASSERT_EQ(rhs.index(entt::entity{6}), 2u); ASSERT_EQ(rhs.index(entt::entity{1}), 3u); ASSERT_EQ(rhs.index(entt::entity{4}), 4u); ASSERT_EQ(rhs.index(entt::entity{5}), 5u); rhs.respect(lhs); ASSERT_EQ(rhs.index(entt::entity{6}), 0u); ASSERT_EQ(rhs.index(entt::entity{1}), 1u); ASSERT_EQ(rhs.index(entt::entity{2}), 2u); ASSERT_EQ(rhs.index(entt::entity{3}), 3u); ASSERT_EQ(rhs.index(entt::entity{4}), 4u); ASSERT_EQ(rhs.index(entt::entity{5}), 5u); } TEST(SparseSet, CanModifyDuringIteration) { entt::sparse_set<entt::entity> set; set.construct(entt::entity{0}); ASSERT_EQ(set.capacity(), entt::sparse_set<entt::entity>::size_type{1}); const auto it = set.begin(); set.reserve(entt::sparse_set<entt::entity>::size_type{2}); ASSERT_EQ(set.capacity(), entt::sparse_set<entt::entity>::size_type{2}); // this should crash with asan enabled if we break the constraint const auto entity = *it; (void)entity; }
32.859619
101
0.626477
janisozaur
f53304f674c010aee4612a768253bd2b3e8a1f7d
3,748
hpp
C++
include/Shader.hpp
luanfagu/raylib-cpp
2524151b7d03262499660a8e696e126430a6ae0e
[ "Zlib" ]
253
2019-03-20T16:15:21.000Z
2022-03-28T06:04:48.000Z
include/Shader.hpp
luanfagu/raylib-cpp
2524151b7d03262499660a8e696e126430a6ae0e
[ "Zlib" ]
96
2019-08-19T22:12:28.000Z
2022-03-29T00:25:54.000Z
include/Shader.hpp
luanfagu/raylib-cpp
2524151b7d03262499660a8e696e126430a6ae0e
[ "Zlib" ]
56
2019-09-09T04:39:50.000Z
2022-03-28T17:42:46.000Z
#ifndef RAYLIB_CPP_INCLUDE_SHADER_HPP_ #define RAYLIB_CPP_INCLUDE_SHADER_HPP_ #include <string> #include "./raylib.hpp" #include "./raylib-cpp-utils.hpp" #include "Texture.hpp" namespace raylib { /** * Shader type (generic) */ class Shader : public ::Shader { public: Shader(const ::Shader& shader) { set(shader); } Shader(unsigned int id, int* locs = nullptr) : ::Shader{id, locs} {} Shader(const std::string& vsFileName, const std::string& fsFileName) { set(::LoadShader(vsFileName.c_str(), fsFileName.c_str())); } Shader(const Shader&) = delete; Shader(Shader&& other) { set(other); other.id = 0; other.locs = nullptr; } /** * Load shader from files and bind default locations. */ static ::Shader Load(const std::string& vsFileName, const std::string& fsFileName) { return ::LoadShader(vsFileName.c_str(), fsFileName.c_str()); } static ::Shader LoadFromMemory(const std::string& vsCode, const std::string& fsCode) { return ::LoadShaderFromMemory(vsCode.c_str(), fsCode.c_str()); } GETTERSETTER(unsigned int, Id, id) GETTERSETTER(int*, Locs, locs) Shader& operator=(const ::Shader& shader) { set(shader); return *this; } Shader& operator=(const Shader&) = delete; Shader& operator=(Shader&& other) { if (this != &other) { return *this; } Unload(); set(other); other.id = 0; other.locs = nullptr; } ~Shader() { Unload(); } void Unload() { if (locs != nullptr) { ::UnloadShader(*this); } } /** * Begin custom shader drawing. */ inline Shader& BeginMode() { ::BeginShaderMode(*this); return *this; } /** * End custom shader drawing (use default shader). */ inline Shader& EndMode() { ::EndShaderMode(); return *this; } /** * Get shader uniform location * * @see GetShaderLocation() */ inline int GetLocation(const std::string& uniformName) const { return ::GetShaderLocation(*this, uniformName.c_str()); } /** * Get shader attribute location * * @see GetShaderLocationAttrib() */ inline int GetLocationAttrib(const std::string& attribName) const { return ::GetShaderLocationAttrib(*this, attribName.c_str()); } /** * Set shader uniform value * * @see SetShaderValue() */ inline Shader& SetValue(int uniformLoc, const std::string& value, int uniformType) { ::SetShaderValue(*this, uniformLoc, value.c_str(), uniformType); return *this; } /** * Set shader uniform value vector * * @see SetShaderValueV() */ inline Shader& SetValue(int uniformLoc, const std::string& value, int uniformType, int count) { ::SetShaderValueV(*this, uniformLoc, value.c_str(), uniformType, count); return *this; } /** * Set shader uniform value (matrix 4x4) * * @see SetShaderValueMatrix() */ inline Shader& SetValue(int uniformLoc, const ::Matrix& mat) { ::SetShaderValueMatrix(*this, uniformLoc, mat); return *this; } /** * Set shader uniform value for texture * * @see SetShaderValueTexture() */ inline Shader& SetValue(int uniformLoc, const ::Texture2D& texture) { ::SetShaderValueTexture(*this, uniformLoc, texture); return *this; } private: inline void set(const ::Shader& shader) { id = shader.id; locs = shader.locs; } }; } // namespace raylib #endif // RAYLIB_CPP_INCLUDE_SHADER_HPP_
23.279503
99
0.585112
luanfagu
f5336b7e22febf505e104463a959d705b72f8ba2
482
cpp
C++
Section 08/Account/Account/Checking.cpp
yhaydar/beg_mod_cpp
6db3538d3f7d4484f7ce39065e13736a9676185a
[ "MIT" ]
null
null
null
Section 08/Account/Account/Checking.cpp
yhaydar/beg_mod_cpp
6db3538d3f7d4484f7ce39065e13736a9676185a
[ "MIT" ]
null
null
null
Section 08/Account/Account/Checking.cpp
yhaydar/beg_mod_cpp
6db3538d3f7d4484f7ce39065e13736a9676185a
[ "MIT" ]
null
null
null
#include "Checking.h" #include <iostream> Checking::Checking(const std::string &name, float balance, float minbalance): m_MinimumBalance(minbalance), Account(name, balance){ } Checking::~Checking() { } void Checking::Withdraw(float amount) { if ((m_Balance - amount) > m_MinimumBalance) { Account::Withdraw(amount); } else { std::cout << "Invalid amount" << std::endl; } } float Checking::GetMinimumBalance() const { return m_MinimumBalance; }
20.083333
78
0.674274
yhaydar
f535aa491fc4c96706a4d1b2fc377d86105e211e
3,032
cpp
C++
aws-cpp-sdk-sdb/source/model/DeletableItem.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-sdb/source/model/DeletableItem.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
18
2018-05-15T16:41:07.000Z
2018-05-21T00:46:30.000Z
aws-cpp-sdk-sdb/source/model/DeletableItem.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
1
2021-10-01T15:29:44.000Z
2021-10-01T15:29:44.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/sdb/model/DeletableItem.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace SimpleDB { namespace Model { DeletableItem::DeletableItem() : m_nameHasBeenSet(false), m_attributesHasBeenSet(false) { } DeletableItem::DeletableItem(const XmlNode& xmlNode) : m_nameHasBeenSet(false), m_attributesHasBeenSet(false) { *this = xmlNode; } DeletableItem& DeletableItem::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode nameNode = resultNode.FirstChild("ItemName"); if(!nameNode.IsNull()) { m_name = StringUtils::Trim(nameNode.GetText().c_str()); m_nameHasBeenSet = true; } XmlNode attributesNode = resultNode.FirstChild("Attribute"); if(!attributesNode.IsNull()) { XmlNode attributeMember = attributesNode; while(!attributeMember.IsNull()) { m_attributes.push_back(attributeMember); attributeMember = attributeMember.NextNode("Attribute"); } m_attributesHasBeenSet = true; } } return *this; } void DeletableItem::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_nameHasBeenSet) { oStream << location << index << locationValue << ".Name=" << StringUtils::URLEncode(m_name.c_str()) << "&"; } if(m_attributesHasBeenSet) { unsigned attributesIdx = 1; for(auto& item : m_attributes) { Aws::StringStream attributesSs; attributesSs << location << index << locationValue << ".Attribute." << attributesIdx++; item.OutputToStream(oStream, attributesSs.str().c_str()); } } } void DeletableItem::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_nameHasBeenSet) { oStream << location << ".Name=" << StringUtils::URLEncode(m_name.c_str()) << "&"; } if(m_attributesHasBeenSet) { unsigned attributesIdx = 1; for(auto& item : m_attributes) { Aws::StringStream attributesSs; attributesSs << location << ".Attribute." << attributesIdx++; item.OutputToStream(oStream, attributesSs.str().c_str()); } } } } // namespace Model } // namespace SimpleDB } // namespace Aws
26.137931
128
0.685356
curiousjgeorge
f54424576ac1d1e5e513f63901a9042a9e57ff19
1,888
cpp
C++
SourceFiles/Item.cpp
JamesBremner/Pack
bf968bafbff01f908e5c27919c475d404d2dceeb
[ "MIT" ]
19
2015-11-08T01:01:11.000Z
2021-06-28T23:10:14.000Z
SourceFiles/Item.cpp
JamesBremner/Pack
bf968bafbff01f908e5c27919c475d404d2dceeb
[ "MIT" ]
7
2016-03-28T05:03:31.000Z
2020-07-09T13:55:57.000Z
SourceFiles/Item.cpp
JamesBremner/Pack
bf968bafbff01f908e5c27919c475d404d2dceeb
[ "MIT" ]
9
2015-04-30T04:19:19.000Z
2017-10-22T12:09:12.000Z
#include "cPackEngine.h" int Item::nextPackSeq = 0; Item::Item() : myBinProgID( -1 ) , mySpinAxis( 0 ) , mySupport( 0 ) { } Item::Item(const Item& orig) { } Item::~Item() { } int Item::RotationConstraints() { return myRotationConstraints; } int Item::PositionConstraints() { return myPositionConstraints; } void Item::set_constraints( int value ) { myRotationConstraints = value % 100; myPositionConstraints = value / 100; } bool Item::IsSpinAllowed( int axis ) { // chack for any rotation constraint if( ! myRotationConstraints ) return true; // check for no rotation constraint if( myRotationConstraints == 7 ) return false; // check for single axis rotation constraint switch( axis ) { case 1: if( myRotationConstraints == 2 || myRotationConstraints == 4 || myRotationConstraints == 6 ) return true; break; case 2: if( myRotationConstraints == 3 || myRotationConstraints == 5 || myRotationConstraints == 6 ) return true; break; case 3: if( myRotationConstraints == 1 || myRotationConstraints == 4 || myRotationConstraints == 5 ) return true; break; } return false; } void Item::Print() { cout << "Item " << id() << " " << progid() << " in bin " << myBinProgID << " location " << myWLocation << "," << myHLocation << "," << myLLocation << " sides " << side_1()->size() <<" " << side_2()->size() <<" "<< side_3()->size() << " orig " << origSide1()->size() <<" "<< origSide2()->size() <<" "<< origSide3()->size() << " os " << side_1()->orig_side() <<" "<< side_2()->orig_side() <<" "<< side_3()->orig_side() << " spin " << mySpinAxis << endl; }
23.308642
103
0.532839
JamesBremner
f54d8cf911287f139e83cf5e3948bce812e904ca
4,876
cpp
C++
message.cpp
zhaoxy2850/TSDNSServer
ed84611238e744f8458a9cac7622fd6b1407297c
[ "MIT" ]
2
2017-10-22T15:24:06.000Z
2018-10-01T09:36:01.000Z
message.cpp
zhaoxy2850/TSDNSServer
ed84611238e744f8458a9cac7622fd6b1407297c
[ "MIT" ]
1
2019-12-25T06:13:32.000Z
2019-12-25T06:13:32.000Z
message.cpp
zhaoxy2850/TSDNSServer
ed84611238e744f8458a9cac7622fd6b1407297c
[ "MIT" ]
3
2017-02-28T07:09:38.000Z
2020-08-15T09:10:40.000Z
// // message.cpp // TSDNSServer // // Created by zhaoxy on 14-5-11. // Copyright (c) 2014年 tsinghua. All rights reserved. // #include "message.h" using namespace dns; using namespace std; //encode an address seperated by '.' like 'www.google.com' //to address seperated by substring length like '3www6google3com' void encode_address(char *addr, char *&buff) { string address(addr); int pos, current = 0; while ((pos = (int)address.find('.')) != string::npos) { address.erase(0, pos+1); *buff++ = pos; memcpy(buff, addr+current, pos); buff += pos; current += pos+1; } *buff++ = address.size(); memcpy(buff, addr+current, address.size()); buff += address.size(); *buff++ = 0; } //encode the message to the buffer void Message::encode_header(char *&buff) { MHeader header = {0}; header.hId = m_id; header.hFlags += ((m_qr?1:0)<<15); header.hFlags += (m_opcode<<11); header.hFlags += (m_aa<<10); header.hFlags += (m_tc<<9); header.hFlags += (m_rd<<8); header.hFlags += (m_ra<<7); header.hFlags += m_rcode; header.queryCount = m_qdCount; header.answCount = m_anCount; header.authCount = m_nsCount; header.addiCount = m_arCount; header.hId = htons(header.hId); header.hFlags = htons(header.hFlags); header.queryCount = htons(header.queryCount); header.answCount = htons(header.answCount); header.authCount = htons(header.authCount); header.addiCount = htons(header.addiCount); memcpy(buff, &header, sizeof(MHeader)); //offset buff += sizeof(MHeader); } //encode the questions of message to the buffer void Message::encode_questions(char *&buff) { //encode each question for (int i=0; i<m_qdCount; i++) { MQuestion question = m_questions[i]; encode_address(question.qName, buff); uint16_t nQType = htons(question.qType); memcpy(buff, &nQType, sizeof(uint16_t)); buff+=sizeof(uint16_t); uint16_t nQClass = htons(question.qClass); memcpy(buff, &nQClass, sizeof(uint16_t)); buff+=sizeof(uint16_t); } } //encode the answers of the message to the buffer void Message::encode_answers(char *&buff) { //encode each answer for (int i=0; i<m_anCount; i++) { MResource resource = m_answers[i]; encode_address(resource.rName, buff); uint16_t nRType = htons(resource.rType); memcpy(buff, &nRType, sizeof(uint16_t)); buff+=sizeof(uint16_t); uint16_t nRClass = htons(resource.rClass); memcpy(buff, &nRClass, sizeof(uint16_t)); buff+=sizeof(uint16_t); uint32_t nTTL = htonl(resource.rTTL); memcpy(buff, &nTTL, sizeof(uint32_t)); buff+=sizeof(uint32_t); uint16_t nRDLen = htons(resource.rdLength); memcpy(buff, &nRDLen, sizeof(uint16_t)); buff+=sizeof(uint16_t); if (MT_A == resource.rType) { memcpy(buff, resource.rData, sizeof(uint32_t)); buff+=sizeof(uint32_t); } } } //decode the message header from the buffer void Message::decode_header(const char *&buff) { MHeader header; memcpy(&header, buff, sizeof(MHeader)); //network order to host order header.hId = ntohs(header.hId); header.hFlags = ntohs(header.hFlags); header.queryCount = ntohs(header.queryCount); header.answCount = ntohs(header.answCount); header.authCount = ntohs(header.authCount); header.addiCount = ntohs(header.addiCount); //id m_id = header.hId; //flags m_qr = header.hFlags&QR_MASK; m_opcode = header.hFlags&OPCODE_MASK; m_aa = header.hFlags&AA_MASK; m_tc = header.hFlags&TC_MASK; m_rd = header.hFlags&RD_MASK; m_ra = header.hFlags&RA_MASK; m_rcode = header.hFlags&RCODE_MASK; //count m_qdCount = header.queryCount; m_anCount = header.answCount; m_nsCount = header.authCount; m_arCount = header.addiCount; //offset buff+= sizeof(MHeader); } //decode the questions of the message from the buffer void Message::decode_questions(const char *&buff) { //reset m_questions.clear(); //decode each question for (int i=0; i<m_qdCount; i++) { MQuestion question = {0}; //name while (1) { uint len = *buff++; if (len==0) break; if (strlen(question.qName)!=0) strcat(question.qName, "."); memcpy(question.qName+strlen(question.qName), buff, len); buff+=len; } //type question.qType = ntohs(*((uint16_t *)buff)); buff+=sizeof(uint16_t); //class question.qClass = ntohs(*((uint16_t *)buff)); buff+=sizeof(uint16_t); //add to list m_questions.push_back(question); } }
30.098765
71
0.612797
zhaoxy2850
f54e08ef99fa2907926ec3287c946a53e9f323ab
2,064
cpp
C++
Examples/CPP/ConvertingProjectData/UsingSvgOptions.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
1
2022-03-16T14:31:36.000Z
2022-03-16T14:31:36.000Z
Examples/CPP/ConvertingProjectData/UsingSvgOptions.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
null
null
null
Examples/CPP/ConvertingProjectData/UsingSvgOptions.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
1
2020-07-01T01:26:17.000Z
2020-07-01T01:26:17.000Z
/* This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Tasks for .NET API reference when the project is build. Please check https:// Docs.nuget.org/consume/nuget-faq for more information. If you do not wish to use NuGet, you can manually download Aspose.Tasks for .NET API from https://www.nuget.org/packages/Aspose.Tasks/, install it and then add its reference to this project. For any issues, questions or suggestions please feel free to contact us using https://forum.aspose.com/c/tasks */ #include "ConvertingProjectData/UsingSvgOptions.h" #include <visualization/Enums/Timescale.h> #include <system/type_info.h> #include <system/string.h> #include <system/shared_ptr.h> #include <system/reflection/method_base.h> #include <system/object.h> #include <saving/Svg/SvgOptions.h> #include <saving/SaveOptions.h> #include <Project.h> #include "RunExamples.h" using namespace Aspose::Tasks::Saving; using namespace Aspose::Tasks::Visualization; namespace Aspose { namespace Tasks { namespace Examples { namespace CPP { namespace ConvertingProjectData { RTTI_INFO_IMPL_HASH(2335436377u, ::Aspose::Tasks::Examples::CPP::ConvertingProjectData::UsingSvgOptions, ThisTypeBaseTypesInfo); void UsingSvgOptions::Run() { // The path to the documents directory. System::String dataDir = RunExamples::GetDataDir(System::Reflection::MethodBase::GetCurrentMethod(ASPOSE_CURRENT_FUNCTION)->get_DeclaringType().get_FullName()); // ExStart:UseSvgOptions // Read the input Project file System::SharedPtr<Project> project = System::MakeObject<Project>(dataDir + u"CreateProject2.mpp"); System::SharedPtr<SaveOptions> saveOptions = System::MakeObject<SvgOptions>(); saveOptions->set_FitContent(true); saveOptions->set_Timescale(Aspose::Tasks::Visualization::Timescale::ThirdsOfMonths); project->Save(dataDir + u"UseSvgOptions_out.svg", saveOptions); // ExEnd:UseSvgOptions } } // namespace ConvertingProjectData } // namespace CPP } // namespace Examples } // namespace Tasks } // namespace Aspose
36.210526
164
0.76938
aspose-tasks
f554b66a7e4617d91daf7917eeac37f219dcee22
8,342
cpp
C++
plugins/probe/3rd/poisson4/factor.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
49
2017-08-23T13:24:24.000Z
2022-03-16T09:10:58.000Z
plugins/probe/3rd/poisson4/factor.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
200
2018-07-20T15:18:26.000Z
2022-03-31T11:01:44.000Z
plugins/probe/3rd/poisson4/factor.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
31
2017-07-31T16:19:29.000Z
2022-02-14T23:41:03.000Z
/* Copyright (c) 2006, Michael Kazhdan and Matthew Bolitho 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 Johns Hopkins University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ ////////////////////// // Polynomial Roots // ////////////////////// #include <math.h> #include "poisson4/factor.h" namespace pcl { namespace poisson { int Factor(double a1,double a0,double roots[1][2],double EPS){ if(fabs(a1)<=EPS){return 0;} roots[0][0]=-a0/a1; roots[0][1]=0; return 1; } int Factor(double a2,double a1,double a0,double roots[2][2],double EPS){ double d; if(fabs(a2)<=EPS){return Factor(a1,a0,roots,EPS);} d=a1*a1-4*a0*a2; a1/=(2*a2); if(d<0){ d=sqrt(-d)/(2*a2); roots[0][0]=roots[1][0]=-a1; roots[0][1]=-d; roots[1][1]= d; } else{ d=sqrt(d)/(2*a2); roots[0][1]=roots[1][1]=0; roots[0][0]=-a1-d; roots[1][0]=-a1+d; } return 2; } // Solution taken from: http://mathworld.wolfram.com/CubicFormula.html // and http://www.csit.fsu.edu/~burkardt/f_src/subpak/subpak.f90 int Factor(double a3,double a2,double a1,double a0,double roots[3][2],double EPS){ double q,r,r2,q3; if(fabs(a3)<=EPS){return Factor(a2,a1,a0,roots,EPS);} a2/=a3; a1/=a3; a0/=a3; q=-(3*a1-a2*a2)/9; r=-(9*a2*a1-27*a0-2*a2*a2*a2)/54; r2=r*r; q3=q*q*q; if(r2<q3){ double sqrQ=sqrt(q); double theta = acos ( r / (sqrQ*q) ); double cTheta=cos(theta/3)*sqrQ; double sTheta=sin(theta/3)*sqrQ*SQRT_3/2; roots[0][1]=roots[1][1]=roots[2][1]=0; roots[0][0]=-2*cTheta; roots[1][0]=-2*(-cTheta*0.5-sTheta); roots[2][0]=-2*(-cTheta*0.5+sTheta); } else{ double s1,s2,sqr=sqrt(r2-q3); double t; t=-r+sqr; if(t<0){s1=-pow(-t,1.0/3);} else{s1=pow(t,1.0/3);} t=-r-sqr; if(t<0){s2=-pow(-t,1.0/3);} else{s2=pow(t,1.0/3);} roots[0][1]=0; roots[0][0]=s1+s2; s1/=2; s2/=2; roots[1][0]= roots[2][0]=-s1-s2; roots[1][1]= SQRT_3*(s1-s2); roots[2][1]=-roots[1][1]; } roots[0][0]-=a2/3; roots[1][0]-=a2/3; roots[2][0]-=a2/3; return 3; } double ArcTan2(double y,double x){ /* This first case should never happen */ if(y==0 && x==0){return 0;} if(x==0){ if(y>0){return PI/2.0;} else{return -PI/2.0;} } if(x>=0){return atan(y/x);} else{ if(y>=0){return atan(y/x)+PI;} else{return atan(y/x)-PI;} } } double Angle(const double in[2]){ if((in[0]*in[0]+in[1]*in[1])==0.0){return 0;} else{return ArcTan2(in[1],in[0]);} } void Sqrt(const double in[2],double out[2]){ double r=sqrt(sqrt(in[0]*in[0]+in[1]*in[1])); double a=Angle(in)*0.5; out[0]=r*cos(a); out[1]=r*sin(a); } void Add(const double in1[2],const double in2[2],double out[2]){ out[0]=in1[0]+in2[0]; out[1]=in1[1]+in2[1]; } void Subtract(const double in1[2],const double in2[2],double out[2]){ out[0]=in1[0]-in2[0]; out[1]=in1[1]-in2[1]; } void Multiply(const double in1[2],const double in2[2],double out[2]){ out[0]=in1[0]*in2[0]-in1[1]*in2[1]; out[1]=in1[0]*in2[1]+in1[1]*in2[0]; } void Divide(const double in1[2],const double in2[2],double out[2]){ double temp[2]; double l=in2[0]*in2[0]+in2[1]*in2[1]; temp[0]= in2[0]/l; temp[1]=-in2[1]/l; Multiply(in1,temp,out); } // Solution taken from: http://mathworld.wolfram.com/QuarticEquation.html // and http://www.csit.fsu.edu/~burkardt/f_src/subpak/subpak.f90 int Factor(double a4,double a3,double a2,double a1,double a0,double roots[4][2],double EPS){ double R[2],D[2],E[2],R2[2]; if(fabs(a4)<EPS){return Factor(a3,a2,a1,a0,roots,EPS);} a3/=a4; a2/=a4; a1/=a4; a0/=a4; Factor(1.0,-a2,a3*a1-4.0*a0,-a3*a3*a0+4.0*a2*a0-a1*a1,roots,EPS); R2[0]=a3*a3/4.0-a2+roots[0][0]; R2[1]=0; Sqrt(R2,R); if(fabs(R[0])>10e-8){ double temp1[2],temp2[2]; double p1[2],p2[2]; p1[0]=a3*a3*0.75-2.0*a2-R2[0]; p1[1]=0; temp2[0]=((4.0*a3*a2-8.0*a1-a3*a3*a3)/4.0); temp2[1]=0; Divide(temp2,R,p2); Add (p1,p2,temp1); Subtract(p1,p2,temp2); Sqrt(temp1,D); Sqrt(temp2,E); } else{ R[0]=R[1]=0; double temp1[2],temp2[2]; temp1[0]=roots[0][0]*roots[0][0]-4.0*a0; temp1[1]=0; Sqrt(temp1,temp2); temp1[0]=a3*a3*0.75-2.0*a2+2.0*temp2[0]; temp1[1]= 2.0*temp2[1]; Sqrt(temp1,D); temp1[0]=a3*a3*0.75-2.0*a2-2.0*temp2[0]; temp1[1]= -2.0*temp2[1]; Sqrt(temp1,E); } roots[0][0]=-a3/4.0+R[0]/2.0+D[0]/2.0; roots[0][1]= R[1]/2.0+D[1]/2.0; roots[1][0]=-a3/4.0+R[0]/2.0-D[0]/2.0; roots[1][1]= R[1]/2.0-D[1]/2.0; roots[2][0]=-a3/4.0-R[0]/2.0+E[0]/2.0; roots[2][1]= -R[1]/2.0+E[1]/2.0; roots[3][0]=-a3/4.0-R[0]/2.0-E[0]/2.0; roots[3][1]= -R[1]/2.0-E[1]/2.0; return 4; } int Solve(const double* eqns,const double* values,double* solutions,int dim){ int i,j,eIndex; double v,m; int *index=new int[dim]; int *set=new int[dim]; double* myEqns=new double[dim*dim]; double* myValues=new double[dim]; for(i=0;i<dim*dim;i++){myEqns[i]=eqns[i];} for(i=0;i<dim;i++){ myValues[i]=values[i]; set[i]=0; } for(i=0;i<dim;i++){ // Find the largest equation that has a non-zero entry in the i-th index m=-1; eIndex=-1; for(j=0;j<dim;j++){ if(set[j]){continue;} if(myEqns[j*dim+i]!=0 && fabs(myEqns[j*dim+i])>m){ m=fabs(myEqns[j*dim+i]); eIndex=j; } } if(eIndex==-1){ delete[] index; delete[] myValues; delete[] myEqns; delete[] set; return 0; } // The position in which the solution for the i-th variable can be found index[i]=eIndex; set[eIndex]=1; // Normalize the equation v=myEqns[eIndex*dim+i]; for(j=0;j<dim;j++){myEqns[eIndex*dim+j]/=v;} myValues[eIndex]/=v; // Subtract it off from everything else for(j=0;j<dim;j++){ if(j==eIndex){continue;} double vv=myEqns[j*dim+i]; for(int k=0;k<dim;k++){myEqns[j*dim+k]-=myEqns[eIndex*dim+k]*vv;} myValues[j]-=myValues[eIndex]*vv; } } for(i=0;i<dim;i++){solutions[i]=myValues[index[i]];} delete[] index; delete[] myValues; delete[] myEqns; delete[] set; return 1; } } }
30.445255
96
0.546392
azuki-monster
f5574313f17211eb9b87dd20071d9b004c846309
52
cpp
C++
app/src/data/gobaldata.cpp
black-sheep-dev/harbour-webcontrol
4feecae04ac07fed106d21abc002b1623fb6b767
[ "MIT" ]
2
2021-10-06T12:53:12.000Z
2021-10-12T09:07:26.000Z
app/src/data/gobaldata.cpp
black-sheep-dev/harbour-webcontrol
4feecae04ac07fed106d21abc002b1623fb6b767
[ "MIT" ]
3
2020-11-08T16:10:33.000Z
2021-09-26T06:02:44.000Z
app/src/data/gobaldata.cpp
black-sheep-dev/harbour-webcontrol
4feecae04ac07fed106d21abc002b1623fb6b767
[ "MIT" ]
1
2020-11-08T14:54:25.000Z
2020-11-08T14:54:25.000Z
#include "gobaldata.h" DataManager* g_dataManager;
13
27
0.788462
black-sheep-dev
f5591aae36e45b4c6d59fb2cb0ef9773ba8b351c
1,871
cpp
C++
basic/mobile_io/02f_feedback_background_mobile_io.cpp
HebiRobotics/hebi-cpp-examples
db01c9b957b3c97885d452d8b72f9919ba6c48c4
[ "Apache-2.0" ]
7
2018-03-31T06:52:08.000Z
2022-02-24T21:27:09.000Z
basic/mobile_io/02f_feedback_background_mobile_io.cpp
HebiRobotics/hebi-cpp-examples
db01c9b957b3c97885d452d8b72f9919ba6c48c4
[ "Apache-2.0" ]
34
2018-06-03T17:28:08.000Z
2021-05-29T01:15:25.000Z
basic/mobile_io/02f_feedback_background_mobile_io.cpp
HebiRobotics/hebi-cpp-examples
db01c9b957b3c97885d452d8b72f9919ba6c48c4
[ "Apache-2.0" ]
9
2018-02-08T22:50:58.000Z
2021-03-30T08:07:35.000Z
/* * Get feedback from a mobile io module and plot it live * * For more information, go to http://docs.hebi.us/tools.html#cpp-api * * HEBI Robotics * August 2019 */ #include <chrono> #include <iostream> #include <thread> #include "lookup.hpp" #include "group_feedback.hpp" #include "util/plot_functions.h" namespace plt = matplotlibcpp; using namespace hebi; int main() { // Find your module on the network Lookup lookup; std::string family_name("HEBI"); std::string module_name("Mobile IO"); auto group = lookup.getGroupFromNames({family_name}, {module_name}); // Confirm the module is found before preceding if (!group) { std::cout << "Group not found!" << std::endl; return -1; } // Set the feedback frequency. // This is by default "100"; setting this to 5 here allows the console output // to be more reasonable. group -> setFeedbackFrequencyHz(5); // Add a callback to react to feedback received on a background thread // Note: We use a C++11 "lambda function" here to pass in a function pointer, // but you can also pass in a C-style function pointer with the signature: // void func(const hebi::GroupFeedback& group_fbk); std::vector<double> y; group->addFeedbackHandler([&y](const GroupFeedback& group_fbk) { auto gyro = group_fbk.getGyro(); y = {gyro(0,0), gyro(0,1), gyro(0,2)}; // Plot the feedback std::vector<std::string> x_labels = {"X", "Y", "Z"}; std::vector<double> x_ticks = {0.0, 1.0, 2.0}; plt::clf(); plt::ylim(-3.14, 3.14); plt::xticks(x_ticks, x_labels); plt::xlabel("Axis"); plt::ylabel("Angular Velocity (rad/s)"); plt::bar(y); plt::pause(0.01); }); // Wait 10 seconds, and then stop and clear threads std::this_thread::sleep_for(std::chrono::milliseconds(10000)); group -> clearFeedbackHandlers(); return 0; }
26.728571
79
0.660075
HebiRobotics
f560f0b6eacdab2a247d5cf25f7b6408d6a3b0c5
2,797
cpp
C++
middleware/src/generator/mesh/cube_shape.cpp
TerraGraphics/TerraEngine
874165a22ab7dd3774a6cfdeb023485a552d9860
[ "Apache-2.0" ]
5
2019-12-24T21:43:13.000Z
2020-06-16T03:44:16.000Z
middleware/src/generator/mesh/cube_shape.cpp
TerraGraphics/TerraEngine
874165a22ab7dd3774a6cfdeb023485a552d9860
[ "Apache-2.0" ]
null
null
null
middleware/src/generator/mesh/cube_shape.cpp
TerraGraphics/TerraEngine
874165a22ab7dd3774a6cfdeb023485a552d9860
[ "Apache-2.0" ]
1
2020-03-30T00:17:27.000Z
2020-03-30T00:17:27.000Z
#include "middleware/generator/mesh/cube_shape.h" #include <memory> #include <utility> #include <type_traits> #include "core/common/exception.h" static auto MakeGenerator(const dg::float3 sizes, const dg::uint3 segments) { float offset = sizes.z * 0.5f; dg::float2 size = {sizes.x, sizes.y}; dg::uint2 sg = {segments.x, segments.y}; math::Axis2 axes = {math::Axis::X, math::Axis::Y}; auto p0 = PlaneShape(axes, math::Direction::POS_Z, size, sg); p0.SetCenter({0, 0, offset}); auto p1 = PlaneShape(axes, math::Direction::NEG_Z, size, sg); p1.SetCenter({0, 0, -offset}); offset = sizes.x * 0.5f; size = {sizes.y, sizes.z}; sg = {segments.y, segments.z}; axes = {math::Axis::Y, math::Axis::Z}; auto p2 = PlaneShape(axes, math::Direction::POS_X, size, sg); p2.SetCenter({offset, 0, 0}); auto p3 = PlaneShape(axes, math::Direction::NEG_X, size, sg); p3.SetCenter({-offset, 0, 0}); offset = sizes.y * 0.5f; size = {sizes.z, sizes.x}; sg = {segments.z, segments.x}; axes = {math::Axis::Z, math::Axis::X}; auto p4 = PlaneShape(axes, math::Direction::POS_Y, size, sg); p4.SetCenter({0, offset, 0}); auto p5 = PlaneShape(axes, math::Direction::NEG_Y, size, sg); p5.SetCenter({0, -offset, 0}); return MergeShape<PlaneShape, PlaneShape, PlaneShape, PlaneShape, PlaneShape, PlaneShape>( std::move(p0), std::move(p1), std::move(p2), std::move(p3), std::move(p4), std::move(p5)); } CubeShape::CubeShape(const dg::float3 sizes, const dg::uint3 segments) : Shape("CubeShape", {math::Axis::X, math::Axis::Y, math::Axis::Z}) , m_generator(MakeGenerator(sizes, segments)) { if (segments.x < 1) { throw EngineError("minimum value for segments.x in CubeShape is 1"); } if (segments.y < 1) { throw EngineError("minimum value for segments.y in CubeShape is 1"); } if (segments.z < 1) { throw EngineError("minimum value for segments.z in CubeShape is 1"); } if (sizes.x < 0) { throw EngineError("minimum value for sizes.x in CubeShape is greater than 0"); } if (sizes.y < 0) { throw EngineError("minimum value for sizes.y in CubeShape is greater than 0"); } if (sizes.z < 0) { throw EngineError("minimum value for sizes.z in CubeShape is greater than 0"); } SetGenerator(&m_generator); } CubeShape::CubeShape(CubeShape&& other) noexcept : Shape(std::move(other)) , m_generator(std::move(other.m_generator)) { SetGenerator(&m_generator); } CubeShape& CubeShape::operator=(CubeShape&& other) noexcept { Shape::operator=(std::move(other)); m_generator = std::move(other.m_generator); SetGenerator(&m_generator); return *this; }
32.523256
94
0.626385
TerraGraphics
f56128b2033187724c7d23af81c68307e0e3f51c
857
cpp
C++
foobar2000/SDK/main_thread_callback.cpp
ttsping/foo_fix
4a0b950ccb8c10c912a9abeeffdd85e777463309
[ "Info-ZIP" ]
294
2017-11-20T17:42:08.000Z
2022-03-31T04:15:13.000Z
foobar2000/SDK/main_thread_callback.cpp
ttsping/foo_fix
4a0b950ccb8c10c912a9abeeffdd85e777463309
[ "Info-ZIP" ]
108
2021-04-08T10:57:27.000Z
2022-03-27T08:02:15.000Z
foobar2000/SDK/main_thread_callback.cpp
ttsping/foo_fix
4a0b950ccb8c10c912a9abeeffdd85e777463309
[ "Info-ZIP" ]
14
2018-03-10T12:47:03.000Z
2021-11-11T09:00:08.000Z
#include "foobar2000.h" void main_thread_callback::callback_enqueue() { main_thread_callback_manager::get()->add_callback(this); } void main_thread_callback_add(main_thread_callback::ptr ptr) { main_thread_callback_manager::get()->add_callback(ptr); } namespace { typedef std::function<void ()> func_t; class mtcallback_func : public main_thread_callback { public: mtcallback_func(func_t const & f) : m_f(f) {} void callback_run() { m_f(); } private: func_t m_f; }; } void fb2k::inMainThread( std::function<void () > f ) { main_thread_callback_add( new service_impl_t<mtcallback_func>(f)); } void fb2k::inMainThread2( std::function<void () > f ) { if ( core_api::is_main_thread() ) { f(); } else { inMainThread(f); } }
22.552632
71
0.62077
ttsping
f5612a9a9cbccb0feb246b085e3e1225df11c4db
4,839
cpp
C++
source/pawgui.cpp
pawbyte/pawgui
24e77f4ce40bd0e91f5f5edc27cc87ff5783d0ab
[ "MIT" ]
2
2020-03-09T14:29:42.000Z
2021-02-06T05:07:39.000Z
source/pawgui.cpp
pawbyte/pawgui
24e77f4ce40bd0e91f5f5edc27cc87ff5783d0ab
[ "MIT" ]
null
null
null
source/pawgui.cpp
pawbyte/pawgui
24e77f4ce40bd0e91f5f5edc27cc87ff5783d0ab
[ "MIT" ]
null
null
null
/* pawgui.cpp This file is part of: PawByte Ambitious Working GUI(PAWGUI) https://www.pawbyte.com/pawgui Copyright (c) 2014-2020 Nathan Hurde, Chase Lee. Copyright (c) 2014-2020 PawByte LLC. Copyright (c) 2014-2020 PawByte Ambitious Working GUI(PAWGUI) contributors ( Contributors Page ) 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. -PawByte Ambitious Working GUI(PAWGUI) <https://www.pawbyte.com/pawgui> */ #include "pawgui.h" namespace pawgui { bool init_gui( std::string mono_font_location, int font_min_size ) { //gpe::cursor_main_controller->cursor_create_from_image( gpe::app_directory_name + "resources/gfx/iconpacks/fontawesome/asterisk.png" ); rsm_gui = new gpe::asset_manager( gpe::rph->get_default_render_package(), "pawgui"); if( load_default_fonts( mono_font_location, font_min_size) ) { gpe::error_log->report("IDE properly added all PawGUI Fonts... \n"); popup_font_size_width = 12; popup_font_size_height = 12; if( font_popup!=NULL) { font_popup->get_metrics("A",&popup_font_size_width,&popup_font_size_height); } } else { gpe::error_log->report("Unable to load PawGUI Fonts!\n"); return false; } main_settings = new gui_settings(); main_overlay_system = new overlay_system(); main_loader_display = new loader_display(); main_search_controller = new search_controller(); if( main_settings!=NULL && main_overlay_system!=NULL && main_search_controller!=NULL ) { main_context_menu = new popup_menu_option(" ",-1,false,false,true); main_context_menu->isTopOfMenu = true; texture_color_picker_gradient = rsm_gui->texture_add_filename( gpe::app_directory_name+"resources/gfx/textures/color_picker_gradient.png" ); std::string colorPickerFilename = gpe::app_directory_name+"resources/gfx/textures/color_picker_gradient.png"; checkmark_texture = rsm_gui->texture_add_filename( gpe::app_directory_name+"resources/gfx/iconpacks/fontawesome/chevron-down.png"); dropdown_arrow_texture = rsm_gui->texture_add_filename( gpe::app_directory_name+"resources/gfx/iconpacks/fontawesome/angle-down.png"); eyedropper_texture = rsm_gui->texture_add_filename( gpe::app_directory_name+"resources/gfx/iconpacks/fontawesome/eyedropper.png"); main_scrollbar_arrow = rsm_gui->animation_add("guiScrollArrowDown", gpe::app_directory_name+"resources/gfx/iconpacks/fontawesome/caret-down.png",1,true,0,0,false); return true; } return false; } bool quit_gui() { gpe::error_log->report("Deleting PAWGUI ...."); texture_color_picker_gradient = NULL; if( main_overlay_system !=NULL) { delete main_overlay_system; main_overlay_system = NULL; } if( main_loader_display !=NULL) { delete main_loader_display; main_loader_display = NULL; } if( main_search_controller !=NULL) { delete main_search_controller; main_search_controller = NULL; } if( main_settings !=NULL) { delete main_settings; main_settings = NULL; } gpe::error_log->report("Deleting mini-code-highlighter...."); if( main_syntax_highlighter!=NULL) { delete main_syntax_highlighter; main_syntax_highlighter = NULL; } if( rsm_gui!=NULL ) { delete rsm_gui; rsm_gui = NULL; } return true; } }
39.991736
176
0.65902
pawbyte
f56253d59fc5c13df8a30aea81798adeb68e743f
5,242
cpp
C++
dbms/src/Interpreters/tests/hash_map2.cpp
rudneff/ClickHouse
3cb59b92bccbeb888d136f7c6e14b622382c0434
[ "Apache-2.0" ]
3
2016-12-30T14:19:47.000Z
2021-11-13T06:58:32.000Z
dbms/src/Interpreters/tests/hash_map2.cpp
rudneff/ClickHouse
3cb59b92bccbeb888d136f7c6e14b622382c0434
[ "Apache-2.0" ]
1
2017-01-13T21:29:36.000Z
2017-01-16T18:29:08.000Z
dbms/src/Interpreters/tests/hash_map2.cpp
jbfavre/clickhouse-debian
3806e3370decb40066f15627a3bca4063b992bfb
[ "Apache-2.0" ]
1
2021-02-07T16:00:54.000Z
2021-02-07T16:00:54.000Z
#include <iostream> #include <iomanip> #include <vector> #include <unordered_map> #include <sparsehash/dense_hash_map> #include <sparsehash/sparse_hash_map> #include <DB/Common/Stopwatch.h> //#define DBMS_HASH_MAP_COUNT_COLLISIONS #define DBMS_HASH_MAP_DEBUG_RESIZES #include <DB/Core/Types.h> #include <DB/IO/ReadBufferFromFile.h> #include <DB/IO/CompressedReadBuffer.h> #include <DB/Common/HashTable/HashMap.h> using Key = UInt64; using Value = UInt64; struct CellWithoutZeroWithSavedHash : public HashMapCell<Key, Value, DefaultHash<Key> > { // size_t saved_hash; static constexpr bool need_zero_value_storage = false; CellWithoutZeroWithSavedHash() : HashMapCell() {} CellWithoutZeroWithSavedHash(const Key & key_, const State & state) : HashMapCell(key_, state) {} CellWithoutZeroWithSavedHash(const value_type & value_, const State & state) : HashMapCell(value_, state) {} /* bool keyEquals(const Key & key_) const { return value.first == key_; } bool keyEquals(const CellWithoutZeroWithSavedHash & other) const { return saved_hash == other.saved_hash && value.first == other.value.first; } void setHash(size_t hash_value) { saved_hash = hash_value; } size_t getHash(const DefaultHash<Key> & hash) const { return saved_hash; }*/ }; struct Grower : public HashTableGrower<> { /// Состояние этой структуры достаточно, чтобы получить размер буфера хэш-таблицы. /// Определяет начальный размер хэш-таблицы. static const size_t initial_size_degree = 16; Grower() { size_degree = initial_size_degree; } // size_t max_fill = (1 << initial_size_degree) * 0.9; /// Размер хэш-таблицы в ячейках. size_t bufSize() const { return 1 << size_degree; } size_t maxFill() const { return 1 << (size_degree - 1); } // size_t maxFill() const { return max_fill; } size_t mask() const { return bufSize() - 1; } /// Из значения хэш-функции получить номер ячейки в хэш-таблице. size_t place(size_t x) const { return x & mask(); } /// Следующая ячейка в цепочке разрешения коллизий. size_t next(size_t pos) const { ++pos; return pos & mask(); } /// Является ли хэш-таблица достаточно заполненной. Нужно увеличить размер хэш-таблицы, или удалить из неё что-нибудь ненужное. bool overflow(size_t elems) const { return elems > maxFill(); } /// Увеличить размер хэш-таблицы. void increaseSize() { size_degree += size_degree >= 23 ? 1 : 2; // max_fill = (1 << size_degree) * 0.9; } /// Установить размер буфера по количеству элементов хэш-таблицы. Используется при десериализации хэш-таблицы. void set(size_t num_elems) { throw Poco::Exception(__PRETTY_FUNCTION__); } }; int main(int argc, char ** argv) { size_t n = atoi(argv[1]); size_t m = atoi(argv[2]); std::vector<Key> data(n); std::cerr << "sizeof(Key) = " << sizeof(Key) << ", sizeof(Value) = " << sizeof(Value) << std::endl; { Stopwatch watch; DB::ReadBufferFromFileDescriptor in1(STDIN_FILENO); DB::CompressedReadBuffer in2(in1); in2.readStrict(reinterpret_cast<char*>(&data[0]), sizeof(data[0]) * n); watch.stop(); std::cerr << std::fixed << std::setprecision(2) << "Vector. Size: " << n << ", elapsed: " << watch.elapsedSeconds() << " (" << n / watch.elapsedSeconds() << " elem/sec.)" << std::endl; } if (m == 1) { Stopwatch watch; // using Map = HashMap<Key, Value>; /// Из-за WithoutZero быстрее на 0.7% (для не влезающей в L3-кэш) - 2.3% (для влезающей в L3-кэш). using Map = HashMapTable<Key, CellWithoutZeroWithSavedHash, DefaultHash<Key>, Grower>; Map map; Map::iterator it; bool inserted; for (size_t i = 0; i < n; ++i) { map.emplace(data[i], it, inserted); if (inserted) it->second = 0; ++it->second; } watch.stop(); std::cerr << std::fixed << std::setprecision(2) << "HashMap. Size: " << map.size() << ", elapsed: " << watch.elapsedSeconds() << " (" << n / watch.elapsedSeconds() << " elem/sec.)" #ifdef DBMS_HASH_MAP_COUNT_COLLISIONS << ", collisions: " << map.getCollisions() #endif << std::endl; } if (m == 2) { Stopwatch watch; std::unordered_map<Key, Value, DefaultHash<Key> > map; for (size_t i = 0; i < n; ++i) ++map[data[i]]; watch.stop(); std::cerr << std::fixed << std::setprecision(2) << "std::unordered_map. Size: " << map.size() << ", elapsed: " << watch.elapsedSeconds() << " (" << n / watch.elapsedSeconds() << " elem/sec.)" << std::endl; } if (m == 3) { Stopwatch watch; google::dense_hash_map<Key, Value, DefaultHash<Key> > map; map.set_empty_key(-1ULL); for (size_t i = 0; i < n; ++i) ++map[data[i]]; watch.stop(); std::cerr << std::fixed << std::setprecision(2) << "google::dense_hash_map. Size: " << map.size() << ", elapsed: " << watch.elapsedSeconds() << " (" << n / watch.elapsedSeconds() << " elem/sec.)" << std::endl; } if (m == 4) { Stopwatch watch; google::sparse_hash_map<Key, Value, DefaultHash<Key> > map; for (size_t i = 0; i < n; ++i) ++map[data[i]]; watch.stop(); std::cerr << std::fixed << std::setprecision(2) << "google::sparse_hash_map. Size: " << map.size() << ", elapsed: " << watch.elapsedSeconds() << " (" << n / watch.elapsedSeconds() << " elem/sec.)" << std::endl; } return 0; }
27.589474
144
0.652804
rudneff
f5650ac27d80d71ec2b9ad6f7a23a1bc4c539f77
27,677
cpp
C++
tests/gtests/test_batch_normalization_forward.cpp
PerfXLab/mkl-dnn
0fc7bd337d827d310d029e5f4219eaf72ca12825
[ "Apache-2.0" ]
9
2016-11-30T07:35:33.000Z
2021-05-09T01:15:06.000Z
tests/gtests/test_batch_normalization_forward.cpp
PerfXLab/mkl-dnn
0fc7bd337d827d310d029e5f4219eaf72ca12825
[ "Apache-2.0" ]
null
null
null
tests/gtests/test_batch_normalization_forward.cpp
PerfXLab/mkl-dnn
0fc7bd337d827d310d029e5f4219eaf72ca12825
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2016 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 <cmath> #include "mkldnn_test_common.hpp" #include "gtest/gtest.h" #include "mkldnn.hpp" namespace mkldnn { struct test_bnorm_desc_t { int mb, c; int h, w; float eps; }; template <typename data_t> void check_bnorm_fwd(test_bnorm_desc_t &bnd, const memory &src, const memory &weights, memory &dst) { const data_t *src_data = (const data_t *)src.get_data_handle(); const data_t *weights_data = (const data_t *)weights.get_data_handle(); data_t *dst_data = (data_t *)dst.get_data_handle(); data_t *workspace_data = new data_t[2*bnd.c]; const memory::desc src_d = src.get_primitive_desc().desc(); const memory::desc weights_d = weights.get_primitive_desc().desc(); const memory::desc dst_d = dst.get_primitive_desc().desc(); #pragma omp parallel for for (int c = 0; c < bnd.c; c++) { workspace_data[c] = data_t(0); for (int n = 0; n < bnd.mb; n++) for (int h = 0; h < bnd.h; h++) for (int w = 0; w < bnd.w; w++) { int sidx = n * bnd.c * bnd.h * bnd.w + c * bnd.h * bnd.w + h * bnd.w + w; workspace_data[c] += src_data[map_index(src_d, sidx)]; } workspace_data[c] /= bnd.mb * bnd.h * bnd.w; workspace_data[bnd.c + c] = data_t(0); for (int n = 0; n < bnd.mb; n++) for (int h = 0; h < bnd.h; h++) for (int w = 0; w < bnd.w; w++) { int sidx = n * bnd.c * bnd.h * bnd.w + c * bnd.h * bnd.w + h * bnd.w + w; data_t tmp = src_data[map_index(src_d, sidx)] - workspace_data[c]; workspace_data[bnd.c + c] += tmp * tmp; } workspace_data[bnd.c + c] = workspace_data[bnd.c + c] / (bnd.mb * bnd.h * bnd.w) + bnd.eps; workspace_data[bnd.c + c] = data_t(1) / sqrt(workspace_data[bnd.c + c]); for (int n = 0; n < bnd.mb; n++) for (int h = 0; h < bnd.h; h++) for (int w = 0; w < bnd.w; w++) { int sdidx = n * bnd.c * bnd.h * bnd.w + c * bnd.h * bnd.w + h * bnd.w + w; data_t ref_dst = weights_data[map_index(weights_d, c)] * (src_data[map_index(src_d, sdidx)] - workspace_data[c]) * workspace_data[bnd.c + c] + weights_data[map_index(weights_d, bnd.c + c)]; data_t out = dst_data[map_index(dst_d, sdidx)]; data_t eps = 1.e-6 * bnd.mb * bnd.h * bnd.w; data_t norm_max = std::max(fabs(out), fabs(ref_dst)); if (norm_max < eps) norm_max = data_t(1); EXPECT_NEAR((out - ref_dst) / norm_max, 0., eps); } } delete[] workspace_data; } struct bnorm_fwd_test_params { prop_kind aprop_kind; const engine::kind engine_kind; memory::format src_format; memory::format dst_format; memory::format weights_format; test_bnorm_desc_t test_bnd; }; template <typename data_t> class bnorm_forward_test : public ::testing::TestWithParam<bnorm_fwd_test_params> { protected: virtual void SetUp() { bnorm_fwd_test_params p = ::testing::TestWithParam<bnorm_fwd_test_params>::GetParam(); ASSERT_TRUE(p.engine_kind == engine::kind::cpu); ASSERT_TRUE(p.aprop_kind == prop_kind::forward_training || p.aprop_kind == prop_kind::forward_scoring); auto eng = engine(p.engine_kind, 0); memory::data_type data_type = data_traits<data_t>::data_type; ASSERT_EQ(data_type, mkldnn::memory::data_type::f32); test_bnorm_desc_t bnd = p.test_bnd; bool with_workspace = p.aprop_kind == prop_kind::forward_training; auto src_desc = create_md( { bnd.mb, bnd.c, bnd.h, bnd.w }, data_type, p.src_format); auto dst_desc = create_md( { bnd.mb, bnd.c, bnd.h, bnd.w }, data_type, p.dst_format); auto src_primitive_desc = memory::primitive_desc(src_desc, eng); auto dst_primitive_desc = memory::primitive_desc(dst_desc, eng); auto src_size = src_primitive_desc.get_size(); auto dst_size = dst_primitive_desc.get_size(); // TODO: free data_t *src_data = new data_t[src_size]; data_t *weights_data = nullptr; data_t *workspace_data = nullptr; data_t *dst_data = new data_t[dst_size]; auto src = memory(src_primitive_desc, src_data); auto dst = memory(dst_primitive_desc, dst_data); auto bn_desc = batch_normalization_forward::desc(p.aprop_kind, src_desc, bnd.eps); auto bn_prim_desc = batch_normalization_forward::primitive_desc(bn_desc, eng); auto weights_primitive_desc = bn_prim_desc.weights_primitive_desc(); auto weights_size = weights_primitive_desc.get_size(); weights_data = new data_t[weights_size]; auto weights = memory(weights_primitive_desc, weights_data); fill_data<data_t>( src.get_primitive_desc().get_size() / sizeof(data_t), (data_t *)src.get_data_handle()); fill_data<data_t>( weights.get_primitive_desc().get_size() / sizeof(data_t), (data_t *)weights.get_data_handle()); std::vector<primitive> pipeline; auto s = stream(stream::kind::lazy); if (with_workspace) { auto workspace_primitive_desc = bn_prim_desc.workspace_primitive_desc(); auto workspace_size = workspace_primitive_desc.get_size(); workspace_data = new data_t[workspace_size]; auto workspace = memory(workspace_primitive_desc, workspace_data); auto bn = batch_normalization_forward(bn_prim_desc, src, weights, workspace, dst); pipeline.push_back(bn); s.submit(pipeline).wait(); } else { auto bn = batch_normalization_forward(bn_prim_desc, src, weights, dst); pipeline.push_back(bn); s.submit(pipeline).wait(); } check_bnorm_fwd<data_t>(bnd, src, weights, dst); } }; using bnorm_forward_test_float = bnorm_forward_test<float>; using bnorm_fwd_test_params_float = bnorm_fwd_test_params; TEST_P(bnorm_forward_test_float, TestsBNorm) { } INSTANTIATE_TEST_CASE_P(TestBNormForward, bnorm_forward_test_float, ::testing::Values(bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 10, 4, 4, 0.1 } })); INSTANTIATE_TEST_CASE_P( TestBNormForwardBlocked, bnorm_forward_test_float, ::testing::Values( bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 8, 4, 4, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 16, 4, 4, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 16, 8, 8, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 16, 16, 8, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 16, 16, 10, 0.1 } })); INSTANTIATE_TEST_CASE_P( TestBNormGoogleNetForwardNCHW, bnorm_forward_test_float, ::testing::Values( bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 64, 112, 112, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 64, 56, 56, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 192, 56, 56, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 96, 28, 28, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 16, 28, 28, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 64, 28, 28, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 128, 28, 28, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 32, 28, 28, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 96, 28, 28, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 96, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 16, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 192, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 208, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 48, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 64, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 112, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 24, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 160, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 224, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 128, 4, 4, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 128, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 512, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 256, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 144, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 32, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 228, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 528, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 320, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 160, 7, 7, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 32, 7, 7, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 256, 7, 7, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 320, 7, 7, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 128, 7, 7, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 192, 7, 7, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 48, 7, 7, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nchw, memory::format::nchw, memory::format::nc, { 2, 384, 7, 7, 0.1 } })); INSTANTIATE_TEST_CASE_P( TestBNormGoogleNetForwardBlocked, bnorm_forward_test_float, ::testing::Values( bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 64, 112, 112, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 64, 56, 56, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 192, 56, 56, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 96, 28, 28, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 16, 28, 28, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 64, 28, 28, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 128, 28, 28, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 32, 28, 28, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 96, 28, 28, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 96, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 16, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 192, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 208, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 48, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 64, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 112, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 24, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 160, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 224, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 128, 4, 4, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 128, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 512, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 256, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 144, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 32, 14, 14, 0.1 } }, /* size is not supported by nChw8c format yet bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 228, 14, 14, 0.1 } }, */ bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 528, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 320, 14, 14, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 160, 7, 7, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 32, 7, 7, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 256, 7, 7, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 320, 7, 7, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 128, 7, 7, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 192, 7, 7, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 48, 7, 7, 0.1 } }, bnorm_fwd_test_params_float{ prop_kind::forward_training, engine::kind::cpu, memory::format::nChw8c, memory::format::nChw8c, memory::format::nc, { 2, 384, 7, 7, 0.1 } })); }
54.268627
86
0.509773
PerfXLab
f565250754ce6915087897513c950b1ca3f3ead6
979
hpp
C++
src/include/guinsoodb/execution/operator/helper/physical_transaction.hpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-04-22T05:41:54.000Z
2021-04-22T05:41:54.000Z
src/include/guinsoodb/execution/operator/helper/physical_transaction.hpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
null
null
null
src/include/guinsoodb/execution/operator/helper/physical_transaction.hpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-12-12T10:24:57.000Z
2021-12-12T10:24:57.000Z
//===----------------------------------------------------------------------===// // GuinsooDB // // guinsoodb/execution/operator/helper/physical_transaction.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "guinsoodb/execution/physical_operator.hpp" #include "guinsoodb/parser/parsed_data/transaction_info.hpp" namespace guinsoodb { //! PhysicalTransaction represents a transaction operator (e.g. BEGIN or COMMIT) class PhysicalTransaction : public PhysicalOperator { public: explicit PhysicalTransaction(unique_ptr<TransactionInfo> info, idx_t estimated_cardinality) : PhysicalOperator(PhysicalOperatorType::TRANSACTION, {LogicalType::BOOLEAN}, estimated_cardinality), info(move(info)) { } unique_ptr<TransactionInfo> info; public: void GetChunkInternal(ExecutionContext &context, DataChunk &chunk, PhysicalOperatorState *state) override; }; } // namespace guinsoodb
31.580645
107
0.642492
GuinsooLab
f5661c3d682c8d7272445b97b709789955e07a11
1,845
cpp
C++
src/+cv/getDerivKernels.cpp
1123852253/mexopencv
17db690133299f561924a45e9092673a4df66c5b
[ "BSD-3-Clause" ]
571
2015-01-04T06:23:19.000Z
2022-03-31T07:37:19.000Z
src/+cv/getDerivKernels.cpp
1123852253/mexopencv
17db690133299f561924a45e9092673a4df66c5b
[ "BSD-3-Clause" ]
362
2015-01-06T14:20:46.000Z
2022-01-20T08:10:46.000Z
src/+cv/getDerivKernels.cpp
1123852253/mexopencv
17db690133299f561924a45e9092673a4df66c5b
[ "BSD-3-Clause" ]
300
2015-01-20T03:21:27.000Z
2022-03-31T07:36:37.000Z
/** * @file getDerivKernels.cpp * @brief mex interface for cv::getDerivKernels * @ingroup imgproc * @author Kota Yamaguchi * @date 2011 */ #include "mexopencv.hpp" #include "opencv2/imgproc.hpp" using namespace std; using namespace cv; namespace { /// KSize map for option processing const ConstMap<string,int> KSizeMap = ConstMap<string,int> ("Scharr", CV_SCHARR); } /** * Main entry called from Matlab * @param nlhs number of left-hand-side arguments * @param plhs pointers to mxArrays in the left-hand-side * @param nrhs number of right-hand-side arguments * @param prhs pointers to mxArrays in the right-hand-side */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // Check the number of arguments nargchk((nrhs%2)==0 && nlhs<=2); // Argument vector vector<MxArray> rhs(prhs, prhs+nrhs); // Option processing int dx = 1; int dy = 1; int ksize = 3; bool normalize = false; int ktype = CV_32F; for (int i=0; i<nrhs; i+=2) { string key(rhs[i].toString()); if (key == "Dx") dx = rhs[i+1].toInt(); else if (key == "Dy") dy = rhs[i+1].toInt(); else if (key == "KSize") ksize = (rhs[i+1].isChar()) ? KSizeMap[rhs[i+1].toString()] : rhs[i+1].toInt(); else if (key == "Normalize") normalize = rhs[i+1].toBool(); else if (key == "KType") ktype = (rhs[i+1].isChar()) ? ClassNameMap[rhs[i+1].toString()] : rhs[i+1].toInt(); else mexErrMsgIdAndTxt("mexopencv:error", "Unrecognized option %s", key.c_str()); } // Process Mat kx, ky; getDerivKernels(kx, ky, dx, dy, ksize, normalize, ktype); plhs[0] = MxArray(kx); if (nlhs>1) plhs[1] = MxArray(ky); }
27.954545
76
0.579946
1123852253
f568a503a0c54e953a84d5c720cdc8f04bd72855
9,893
cpp
C++
src/VM/VM.cpp
Feral-Lang/Feral
908c507c823c8b836d3e2007baf77329c2d6b8bf
[ "MIT" ]
131
2020-03-19T15:22:37.000Z
2021-12-19T02:37:01.000Z
src/VM/VM.cpp
Feral-Lang/Feral
908c507c823c8b836d3e2007baf77329c2d6b8bf
[ "MIT" ]
14
2020-04-06T05:50:15.000Z
2021-06-26T06:19:04.000Z
src/VM/VM.cpp
Feral-Lang/Feral
908c507c823c8b836d3e2007baf77329c2d6b8bf
[ "MIT" ]
20
2020-04-06T07:28:30.000Z
2021-09-05T14:46:25.000Z
/* MIT License Copyright (c) 2020 Feral Language repositories 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. */ #include "VM/VM.hpp" #include <cstdarg> #include <cstdlib> #include <string> #include "Common/Env.hpp" #include "Common/FS.hpp" #include "Common/String.hpp" #include "VM/Vars.hpp" // env: FERAL_PATHS vm_state_t::vm_state_t(const std::string &self_bin, const std::string &self_base, const std::vector<std::string> &args, const size_t &flags, const bool &is_thread_copy) : exit_called(false), exec_stack_count_exceeded(false), exit_code(0), exec_flags(flags), exec_stack_max(EXEC_STACK_MAX_DEFAULT), exec_stack_count(0), tru(new var_bool_t(true, 0, 0)), fals(new var_bool_t(false, 0, 0)), nil(new var_nil_t(0, 0)), vm_stack(new vm_stack_t()), dlib(is_thread_copy ? nullptr : new dyn_lib_t()), src_args(nullptr), m_self_bin(self_bin), m_self_base(self_base), m_src_load_fn(nullptr), m_src_read_code_fn(nullptr), m_is_thread_copy(is_thread_copy) { if(m_is_thread_copy) return; init_typenames(*this); std::vector<var_base_t *> src_args_vec; for(auto &arg : args) { src_args_vec.push_back(new var_str_t(arg, 0, 0)); } src_args = new var_vec_t(src_args_vec, false, 0, 0); std::vector<std::string> extra_search_paths = str::split(env::get("FERAL_PATHS"), ';'); for(auto &path : extra_search_paths) { m_inc_locs.push_back(path + "/include/feral"); m_dll_locs.push_back(path + "/lib/feral"); } m_inc_locs.push_back(m_self_base + "/include/feral"); m_dll_locs.push_back(m_self_base + "/lib/feral"); } vm_state_t::~vm_state_t() { delete vm_stack; if(!m_is_thread_copy) for(auto &typefn : m_typefns) delete typefn.second; for(auto &g : m_globals) var_dref(g.second); for(auto &src : all_srcs) var_dref(src.second); var_dref(nil); var_dref(fals); var_dref(tru); var_dref(src_args); for(auto &deinit_fn : m_dll_deinit_fns) { deinit_fn.second(); } if(m_is_thread_copy) return; delete dlib; } void vm_state_t::push_src(srcfile_t *src, const size_t &idx) { if(all_srcs.find(src->path()) == all_srcs.end()) { all_srcs[src->path()] = new var_src_t(src, new vars_t(), src->id(), idx); } var_iref(all_srcs[src->path()]); src_stack.push_back(all_srcs[src->path()]); } void vm_state_t::push_src(const std::string &src_path) { assert(all_srcs.find(src_path) != all_srcs.end()); var_iref(all_srcs[src_path]); src_stack.push_back(all_srcs[src_path]); } void vm_state_t::pop_src() { var_dref(src_stack.back()); src_stack.pop_back(); } void vm_state_t::add_typefn(const std::uintptr_t &type, const std::string &name, var_base_t *fn, const bool iref) { if(m_typefns.find(type) == m_typefns.end()) { m_typefns[type] = new vars_frame_t(); } if(m_typefns[type]->exists(name)) { fprintf(stderr, "function '%s' for type '%s' already exists\n", name.c_str(), type_name(type).c_str()); assert(false); return; } m_typefns[type]->add(name, fn, iref); } var_base_t *vm_state_t::get_typefn(var_base_t *var, const std::string &name) { auto it = m_typefns.find(var->typefn_id()); var_base_t *res = nullptr; if(it == m_typefns.end()) { if(var->attr_based()) goto attr_based; return m_typefns[type_id<var_all_t>()]->get(name); } res = it->second->get(name); if(res) return res; return m_typefns[type_id<var_all_t>()]->get(name); attr_based: it = m_typefns.find(var->type()); if(it == m_typefns.end()) return m_typefns[type_id<var_all_t>()]->get(name); res = it->second->get(name); if(res) return res; return m_typefns[type_id<var_all_t>()]->get(name); } void vm_state_t::set_typename(const std::uintptr_t &type, const std::string &name) { m_typenames[type] = name; } std::string vm_state_t::type_name(const std::uintptr_t &type) { if(m_typenames.find(type) != m_typenames.end()) { return m_typenames[type]; } return "typeid<" + std::to_string(type) + ">"; } std::string vm_state_t::type_name(const var_base_t *val) { return type_name(val->type()); } void vm_state_t::gadd(const std::string &name, var_base_t *val, const bool iref) { if(m_globals.find(name) != m_globals.end()) return; if(iref) var_iref(val); m_globals[name] = val; } var_base_t *vm_state_t::gget(const std::string &name) { if(m_globals.find(name) == m_globals.end()) return nullptr; return m_globals[name]; } bool vm_state_t::mod_exists(const std::vector<std::string> &locs, std::string &mod, const std::string &ext, std::string &dir) { if(mod.front() != '~' && mod.front() != '/' && mod.front() != '.') { for(auto &loc : locs) { if(fs::exists(loc + "/" + mod + ext)) { mod = fs::abs_path(loc + "/" + mod + ext, &dir); return true; } } } else { if(mod.front() == '~') { mod.erase(mod.begin()); std::string home = env::get("HOME"); mod.insert(mod.begin(), home.begin(), home.end()); } else if(mod.front() == '.') { // cannot have a module exists query with '.' outside all srcs assert(src_stack.size() > 0); mod.erase(mod.begin()); mod = src_stack.back()->src()->dir() + mod; } if(fs::exists(mod + ext)) { mod = fs::abs_path(mod + ext, &dir); return true; } } return false; } bool vm_state_t::nmod_load(const std::string &mod_str, const size_t &src_id, const size_t &idx) { std::string mod = mod_str.substr(mod_str.find_last_of('/') + 1); std::string mod_file = mod_str; std::string mod_dir; mod_file.insert(mod_file.find_last_of('/') + 1, "libferal"); if(!mod_exists(m_dll_locs, mod_file, nmod_ext(), mod_dir)) { fail(src_id, idx, "module file: %s not found in locations: %s", (mod_file + nmod_ext()).c_str(), str::stringify(m_dll_locs).c_str()); return false; } if(dlib->fexists(mod_file)) return true; if(!dlib->load(mod_file)) { fail(src_id, idx, "unable to load module file: %s", mod_file.c_str(), str::stringify(m_dll_locs).c_str()); return false; } mod_init_fn_t init_fn = (mod_init_fn_t)dlib->get(mod_file, "init_" + mod); if(init_fn == nullptr) { fail(src_id, idx, "module file: %s does not contain init function (%s)", mod_file.c_str(), ("init_" + mod).c_str()); dlib->unload(mod_file); return false; } if(!init_fn(*this, src_id, idx)) { dlib->unload(mod_file); fail(src_id, idx, "init function in module file: %s didn't return okay", mod_file.c_str()); return false; } // set deinit function if available mod_deinit_fn_t deinit_fn = (mod_deinit_fn_t)dlib->get(mod_file, "deinit_" + mod); if(deinit_fn) m_dll_deinit_fns[mod_file] = deinit_fn; return true; } // updated mod_str with actual file name (full canonical path) int vm_state_t::fmod_load(std::string &mod_file, const size_t &src_id, const size_t &idx) { std::string mod_dir; if(!mod_exists(m_inc_locs, mod_file, fmod_ext(), mod_dir)) { fail(src_id, idx, "import file: %s not found in locations: %s", (mod_file + fmod_ext()).c_str(), str::stringify(m_inc_locs).c_str()); return E_FAIL; } if(all_srcs.find(mod_file) != all_srcs.end()) return E_OK; Errors err = E_OK; srcfile_t *src = m_src_load_fn(mod_file, mod_dir, exec_flags, false, err, 0, -1); if(err != E_OK) { if(src) delete src; return err; } push_src(src, 0); int res = vm::exec(*this); pop_src(); return res; } void vm_state_t::fail(const size_t &src_id, const size_t &idx, const char *msg, ...) { va_list vargs; va_start(vargs, msg); if(fails.empty() || this->exit_called) { for(auto &src : all_srcs) { if(src.second->src()->id() == src_id) { src.second->src()->fail(idx, msg, vargs); break; } } } else { static char err[4096]; vsprintf(err, msg, vargs); fails.push(new var_str_t(err, src_id, idx), false); } va_end(vargs); } void vm_state_t::fail(const size_t &src_id, const size_t &idx, var_base_t *val, const char *msg, const bool &iref) { if(iref) var_iref(val); if(fails.empty() || this->exit_called) { for(auto &src : all_srcs) { if(src.second->src()->id() == src_id) { std::string data; val->to_str(*this, data, src_id, idx); var_dref(val); if(msg) src.second->src()->fail(idx, "%s (%s)", msg, data.c_str()); else src.second->src()->fail(idx, data.c_str()); break; } } } else { fails.push(val, false); } } bool vm_state_t::load_core_mods() { std::vector<std::string> mods = {"core", "utils"}; for(auto &mod : mods) { if(!nmod_load(mod, 0, 0)) return false; } return true; } vm_state_t *vm_state_t::thread_copy(const size_t &src_id, const size_t &idx) { vm_state_t *vm = new vm_state_t(m_self_bin, m_self_base, {}, exec_flags, true); for(auto &s : all_srcs) { vm->all_srcs[s.first] = static_cast<var_src_t *>(s.second->thread_copy(src_id, idx)); } for(auto &s : src_stack) { vm->src_stack.push_back(vm->all_srcs[s->src()->path()]); } vm->dlib = dlib; // don't delete in destructor var_iref(src_args); vm->src_args = src_args; vm->m_src_load_fn = m_src_load_fn; vm->m_src_read_code_fn = m_src_read_code_fn; vm->m_inc_locs = m_inc_locs; vm->m_dll_locs = m_dll_locs; vm->m_globals = m_globals; for(auto &glob : vm->m_globals) { var_iref(glob.second); } vm->m_typefns = m_typefns; // do not delete in destructor vm->m_typenames = m_typenames; // don't copy m_dll_deinit_fns as that will be called by the main thread return vm; } const char *nmod_ext() { #if __linux__ || __FreeBSD__ || __NetBSD__ || __OpenBSD__ || __bsdi__ || __DragonFly__ return ".so"; #elif __APPLE__ return ".dylib"; #endif } const char *fmod_ext(const bool compiled) { if(compiled) return ".cfer"; return ".fer"; }
29.01173
96
0.675124
Feral-Lang
f568cc4741f7e6838bddbed87284daeb0d7d505d
2,637
hpp
C++
examples/c/h2o2/chem_utils.hpp
stgeke/pyJac-v2
c2716a05df432efd8e5f6cc5cc3d46b72c24c019
[ "MIT" ]
null
null
null
examples/c/h2o2/chem_utils.hpp
stgeke/pyJac-v2
c2716a05df432efd8e5f6cc5cc3d46b72c24c019
[ "MIT" ]
null
null
null
examples/c/h2o2/chem_utils.hpp
stgeke/pyJac-v2
c2716a05df432efd8e5f6cc5cc3d46b72c24c019
[ "MIT" ]
null
null
null
#ifndef CHEM_UTILS_HPP #define CHEM_UTILS_HPP #ifdef _OPENMP #include <omp.h> #else #warning 'OpenMP not found! Unexpected results may occur if using more than one thread.' #define omp_get_num_threads() (1) #endif #include "mechanism.hpp" #include "chem_utils.hpp" #ifndef work_size #define work_size (omp_get_num_threads()) #endif #include <math.h> void eval_b(double const *__restrict__ phi, double *__restrict__ b); void eval_h(double const *__restrict__ phi, double *__restrict__ h); void eval_cp(double const *__restrict__ phi, double *__restrict__ cp); static double const T_mid[9] = { 1000.0, 1000.0, 1000.0, 1000.0, 1000.0, 1000.0, 1000.0, 1000.0, 1000.0 }; static double const a_hi[9 * 7] = { 3.3372792, -4.94024731e-05, 4.99456778e-07, -1.79566394e-10, 2.00255376e-14, -950.158922, -3.20502331, 2.50000001, -2.30842973e-11, 1.61561948e-14, -4.73515235e-18, 4.98197357e-22, 25473.6599, -0.446682914, 2.56942078, -8.59741137e-05, 4.19484589e-08, -1.00177799e-11, 1.22833691e-15, 29217.5791, 4.78433864, 3.28253784, 0.00148308754, -7.57966669e-07, 2.09470555e-10, -2.16717794e-14, -1088.45772, 5.45323129, 3.09288767, 0.000548429716, 1.26505228e-07, -8.79461556e-11, 1.17412376e-14, 3858.657, 4.4766961, 3.03399249, 0.00217691804, -1.64072518e-07, -9.7041987e-11, 1.68200992e-14, -30004.2971, 4.9667701, 4.0172109, 0.00223982013, -6.3365815e-07, 1.1424637e-10, -1.07908535e-14, 111.856713, 3.78510215, 4.16500285, 0.00490831694, -1.90139225e-06, 3.71185986e-10, -2.87908305e-14, -17861.7877, 2.91615662, 2.5, 0.0, 0.0, 0.0, 0.0, -745.375, 4.366 }; static double const a_lo[9 * 7] = { 2.34433112, 0.00798052075, -1.9478151e-05, 2.01572094e-08, -7.37611761e-12, -917.935173, 0.683010238, 2.5, 7.05332819e-13, -1.99591964e-15, 2.30081632e-18, -9.27732332e-22, 25473.6599, -0.446682853, 3.1682671, -0.00327931884, 6.64306396e-06, -6.12806624e-09, 2.11265971e-12, 29122.2592, 2.05193346, 3.78245636, -0.00299673416, 9.84730201e-06, -9.68129509e-09, 3.24372837e-12, -1063.94356, 3.65767573, 3.99201543, -0.00240131752, 4.61793841e-06, -3.88113333e-09, 1.3641147e-12, 3615.08056, -0.103925458, 4.19864056, -0.0020364341, 6.52040211e-06, -5.48797062e-09, 1.77197817e-12, -30293.7267, -0.849032208, 4.30179801, -0.00474912051, 2.11582891e-05, -2.42763894e-08, 9.29225124e-12, 294.80804, 3.71666245, 4.27611269, -0.000542822417, 1.67335701e-05, -2.15770813e-08, 8.62454363e-12, -17702.5821, 3.43505074, 2.5, 0.0, 0.0, 0.0, 0.0, -745.375, 4.366 }; void chem_utils(double const *__restrict__ t, double *__restrict__ b, double const *__restrict__ phi, double *__restrict__ h, double *__restrict__ cp, double *__restrict__ rwk); #endif
109.875
888
0.731134
stgeke
f568eac4a45a9abd8b3ca10d7f12e762040a912c
855
hpp
C++
Microtone/include/microtone/midi_input.hpp
DanielToby/microtone
10538a23fb67933abe5b492eb4ae771bd646f8d6
[ "MIT" ]
null
null
null
Microtone/include/microtone/midi_input.hpp
DanielToby/microtone
10538a23fb67933abe5b492eb4ae771bd646f8d6
[ "MIT" ]
null
null
null
Microtone/include/microtone/midi_input.hpp
DanielToby/microtone
10538a23fb67933abe5b492eb4ae771bd646f8d6
[ "MIT" ]
null
null
null
#pragma once #include <microtone/microtone_platform.hpp> #include <functional> #include <memory> #include <string> #include <vector> namespace microtone { //enum class MidiStatusMessage { // NoteOn = 0b10010000, // NoteOff = 0b10000000, // ControlChange = 0b10110000 //}; using OnMidiDataFn = std::function<void(int status, int note, int velocity)>; class MidiInput { public: explicit MidiInput(); MidiInput(const MidiInput&) = delete; MidiInput& operator=(const MidiInput&) = delete; MidiInput(MidiInput&&) noexcept; MidiInput& operator=(MidiInput&&) noexcept; ~MidiInput(); int portCount() const; std::string portName(int portNumber) const; void openPort(int portNumber); void start(OnMidiDataFn onReceivedDataFn); void stop(); private: class impl; std::unique_ptr<impl> _impl; }; }
20.853659
77
0.694737
DanielToby
f5793f6671b6cbbe299301fbcb23340696806b46
1,653
cpp
C++
library/dynamicProgramming/palindromicPartitioning.cpp
bluedawnstar/algorithm_library
4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6
[ "Unlicense" ]
40
2017-11-26T05:29:18.000Z
2020-11-13T00:29:26.000Z
library/dynamicProgramming/palindromicPartitioning.cpp
bluedawnstar/algorithm_library
4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6
[ "Unlicense" ]
101
2019-02-09T06:06:09.000Z
2021-12-25T16:55:37.000Z
library/dynamicProgramming/palindromicPartitioning.cpp
bluedawnstar/algorithm_library
4c7f64ec61fc2ba059b64ad7ba20fcb5b838ced6
[ "Unlicense" ]
6
2017-01-03T14:17:58.000Z
2021-01-22T10:37:04.000Z
#include <string> #include <functional> #include <vector> #include <algorithm> using namespace std; #include "palindromicPartitioning.h" /////////// For Testing /////////////////////////////////////////////////////// #include <time.h> #include <cassert> #include <string> #include <iostream> #include "../common/iostreamhelper.h" #include "../common/profile.h" void testPalindromicPartitioning() { //return; //TODO: if you want to test, make this line a comment. cout << "--- Palindromic Partitioning -----------------------------" << endl; { vector<pair<string, int>> in{ { "aab", 1 }, { "aba", 0 }, { "abc", 2 } }; for (auto& it : in) { int ans = PalindromicPartitioning::minCut(it.first); if (ans != it.second) cout << "Mismatched : " << ans << ", " << it.second << endl; assert(ans == it.second); } } { vector<tuple<string, int, int>> in{ { "abc" , 2, 1 }, { "aabbc" , 3, 0 }, { "abbcdefb", 8, 0 }, { "abcdefa" , 4, 2 } }; for (auto& it : in) { int ans1 = PalindromicPartitioning::palindromePartitionMemoization(get<0>(it), get<1>(it)); int ans2 = PalindromicPartitioning::palindromePartitionDP(get<0>(it), get<1>(it)); if (ans1 != get<2>(it) || ans2 != get<2>(it)) cout << "Mismatched : " << ans1 << ", " << ans2 << ", " << get<2>(it) << endl; assert(ans1 == get<2>(it)); assert(ans2 == get<2>(it)); } } cout << "OK!" << endl; }
29
103
0.46582
bluedawnstar
f579c75ed37e1c290f5e63bae9a94ad5f9169ae4
468
cpp
C++
solved-lightOj/1225.cpp
Maruf-Tuhin/Online_Judge
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
1
2019-03-31T05:47:30.000Z
2019-03-31T05:47:30.000Z
solved-lightOj/1225.cpp
the-redback/competitive-programming
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
null
null
null
solved-lightOj/1225.cpp
the-redback/competitive-programming
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstring> main() { char a[15],b[15]; int i,j,l,t,k; scanf("%d",&t); getchar(); for(i=1;i<=t;i++) { gets(a); l=strlen(a); for(j=l-1,k=0;j>=0;j--,k++) { b[k]=a[j]; } b[k]='\0'; if(strcmp(a,b)==0) { printf("Case %d: Yes\n",i); } else { printf("Case %d: No\n",i); } } return 0; }
15.6
39
0.333333
Maruf-Tuhin
f57a92b4a74fcff655a756b83424e97b70e55d7c
51,462
cpp
C++
src/utils/MSFraggerAdapter.cpp
avasq011/FinalProject_OpenMS_76ers
6c9e2c295df6ec0eb296a3badfcdff245a869d59
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
1
2019-07-15T20:50:22.000Z
2019-07-15T20:50:22.000Z
src/utils/MSFraggerAdapter.cpp
avasq011/FinalProject_OpenMS_76ers
6c9e2c295df6ec0eb296a3badfcdff245a869d59
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
150
2017-09-05T09:43:12.000Z
2020-02-03T10:07:36.000Z
src/utils/MSFraggerAdapter.cpp
avasq011/FinalProject_OpenMS_76ers
6c9e2c295df6ec0eb296a3badfcdff245a869d59
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
2
2018-04-02T18:41:20.000Z
2018-08-11T21:39:24.000Z
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2018. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Lukas Zimmermann $ // $Authors: Lukas Zimmermann, Leon Bichmann $ // -------------------------------------------------------------------------- #include <OpenMS/APPLICATIONS/TOPPBase.h> #include <OpenMS/FORMAT/FileHandler.h> #include <OpenMS/FORMAT/IdXMLFile.h> #include <OpenMS/FORMAT/PepXMLFile.h> #include <OpenMS/CHEMISTRY/ProteaseDB.h> #include <OpenMS/SYSTEM/JavaInfo.h> #include <QtCore/QDir> #include <QtCore/QProcess> #include <iostream> using namespace OpenMS; using namespace std; //------------------------------------------------------------- //Doxygen docu //------------------------------------------------------------- /** @page TOPP_MSFraggerAdapter MSFraggerAdapter @brief Peptide Identification with MSFragger <CENTER> <table> <tr> <td ALIGN = "center" BGCOLOR="#EBEBEB"> pot. predecessor tools </td> <td VALIGN="middle" ROWSPAN=2> \f$ \longrightarrow \f$ MSFraggerAdapter \f$ \longrightarrow \f$</td> <td ALIGN = "center" BGCOLOR="#EBEBEB"> pot. successor tools </td> </tr> <tr> <td VALIGN="middle" ALIGN = "center" ROWSPAN=1> any signal-/preprocessing tool @n (in mzML format)</td> <td VALIGN="middle" ALIGN = "center" ROWSPAN=1> @ref TOPP_IDFilter or @n any protein/peptide processing tool</td> </tr> </table> </CENTER> @em MSFragger must be installed before this adapter can be used. All MSFragger parameters (as specified in the fragger.params file) have been transcribed to parameters of this OpenMS util. It is not possible to provide an explicit fragger.params file to avoid redundancy with the ini file. This adapter creates an fragger.params file prior to calling MSFragger. If the fragger.params file should be inspected, set the -debug option to 2. MSFraggerAdapter will print the path to the working directory to standard out. MSFragger can process multiple input files (mzML, mzXML) one after another. The number of output files specified must match the number of input spectra files. The output file is then matched to the input file by index. The default parameters of the adapter are the same as given by the official MSFragger manual. Please cite: Andy T Kong, Felipe V Leprevost, Dmitry M Avtonomov, Dattatreya Mellacheruvu & Alexey I Nesvizhskii MSFragger: ultrafast and comprehensive peptide identification in mass spectrometry–based proteomics Nature Methods volume 14, pages 513–520 (2017) doi:10.1038/nmeth.4256 <B>The command line parameters of this tool are:</B> @verbinclude UTILS_MSFraggerAdapter.cli <B>INI file documentation of this tool:</B> @htmlinclude UTILS_MSFraggerAdapter.html */ // We do not want this class to show up in the docu: /// @cond TOPPCLASSES class TOPPMSFraggerAdapter final : public TOPPBase { public: static const String java_executable; static const String java_heapmemory; static const String executable; static const String in; static const String out; static const String opt_out; static const String database; // tolerance static const String precursor_mass_tolerance; static const String precursor_mass_unit; static const String precursor_true_tolerance; static const String precursor_true_unit; static const String fragment_mass_tolerance; static const String fragment_mass_unit; static const String isotope_error; // digest static const String search_enzyme_name; static const String search_enzyme_cutafter; static const String search_enzyme_nocutbefore; static const String num_enzyme_termini; static const String allowed_missed_cleavage; static const String digest_min_length; static const String digest_max_length; static const String digest_mass_range_min; static const String digest_mass_range_max; // varmod static const String clip_nterm_m; static const String varmod_masses; static const String varmod_syntax; static const String varmod_enable_common; static const String not_allow_multiple_variable_mods_on_residue; static const String max_variable_mods_per_mod; static const String max_variable_mods_combinations; // spectrum static const String minimum_peaks; static const String use_topn_peaks; static const String minimum_ratio; static const String clear_mz_range_min; static const String clear_mz_range_max; static const String max_fragment_charge; static const String override_charge; static const String precursor_charge_min; static const String precursor_charge_max; // search static const String track_zero_topn; static const String zero_bin_accept_expect; static const String zero_bin_mult_expect; static const String add_topn_complementary; static const String min_fragments_modeling; static const String min_matched_fragments; static const String output_report_topn; static const String output_max_expect; // statmod static const String add_cterm_peptide; static const String add_nterm_peptide; static const String add_cterm_protein; static const String add_nterm_protein; static const String add_G_glycine; static const String add_A_alanine; static const String add_S_serine; static const String add_P_proline; static const String add_V_valine; static const String add_T_threonine; static const String add_C_cysteine; static const String add_L_leucine; static const String add_I_isoleucine; static const String add_N_asparagine; static const String add_D_aspartic_acid; static const String add_Q_glutamine; static const String add_K_lysine; static const String add_E_glutamic_acid; static const String add_M_methionine; static const String add_H_histidine; static const String add_F_phenylalanine; static const String add_R_arginine; static const String add_Y_tyrosine; static const String add_W_tryptophan; // Log level for verbose output static const int LOG_LEVEL_VERBOSE; TOPPMSFraggerAdapter() : TOPPBase("MSFraggerAdapter", "Peptide Identification with MSFragger", false, { {"Kong AT, Leprevost FV, Avtonomov DM, Mellacheruvu D, Nesvizhskii AI", "MSFragger: ultrafast and comprehensive peptide identification in mass spectrometry–based proteomics", "Nature Methods volume 14, pages 513–520 (2017)", "doi:10.1038/nmeth.4256"} }), working_directory(""), java_exe(""), exe(""), parameter_file_path(""), input_file(), output_file() { } protected: void registerOptionsAndFlags_() override { const StringList emptyStrings; const std::vector< double > emptyDoubles; const StringList validUnits = ListUtils::create<String>("Da,ppm"); const StringList isotope_error_and_enzyme_termini = ListUtils::create<String>("0,1,2"); const StringList zero_to_five = ListUtils::create<String>("0,1,2,3,4,5"); // Java executable registerInputFile_(TOPPMSFraggerAdapter::java_executable, "<file>", "java", "The Java executable. Usually Java is on the system PATH. If Java is not found, use this parameter to specify the full path to Java", false, false, ListUtils::create<String>("skipexists")); registerIntOption_(TOPPMSFraggerAdapter::java_heapmemory, "<num>", 3500, "Maximum Java heap size (in MB)", false); // Handle executable registerInputFile_(TOPPMSFraggerAdapter::executable, "<path_to_executable>", "", "Path to the MSFragger executable to use; may be empty if the executable is globally available.", false, false, ListUtils::create<String>("skipexists")); // Input file registerInputFile_(TOPPMSFraggerAdapter::in, "<file>", "", "Input File with specta for MSFragger"); setValidFormats_(TOPPMSFraggerAdapter::in, ListUtils::create<String>("mzML,mzXML")); // Output file registerOutputFile_(TOPPMSFraggerAdapter::out, "<file>", "", "MSFragger output file"); setValidFormats_(TOPPMSFraggerAdapter::out, ListUtils::create<String>("idXML"), true); // Optional output file registerOutputFile_(TOPPMSFraggerAdapter::opt_out, "<file>", "", "MSFragger optional output file", false); setValidFormats_(TOPPMSFraggerAdapter::opt_out, ListUtils::create<String>("pepXML"), true); // Path to database to search registerInputFile_(TOPPMSFraggerAdapter::database, "<path_to_fasta>", "", "Protein FASTA database file path", true, false); setValidFormats_(TOPPMSFraggerAdapter::database, ListUtils::create<String>("FASTA,fasta,fa,fas"), false); // TOPP tolerance registerTOPPSubsection_("tolerance", "Search Tolerances"); // Precursor mass tolerance and unit _registerNonNegativeDouble(TOPPMSFraggerAdapter::precursor_mass_tolerance, "<precursor_mass_tolerance>", 20.0, "Precursor mass tolerance (window is +/- this value)", false, false); registerStringOption_(TOPPMSFraggerAdapter::precursor_mass_unit, "<precursor_mass_unit>", "ppm", "Unit of precursor mass tolerance", false, false); setValidStrings_(TOPPMSFraggerAdapter::precursor_mass_unit, validUnits); // Precursor true tolerance _registerNonNegativeDouble(TOPPMSFraggerAdapter::precursor_true_tolerance, "<precursor_true_tolerance>", 0.0, "True precursor mass tolerance (window is +/- this value). Used for tie breaker of results (in spectrally ambiguous cases) and zero bin boosting in open searches (0 disables these features). This option is STRONGLY recommended for open searches.", false, false); registerStringOption_(TOPPMSFraggerAdapter::precursor_true_unit, "<precursor_true_unit>", "ppm", "Unit of precursor true tolerance", false, false); setValidStrings_(TOPPMSFraggerAdapter::precursor_true_unit, validUnits); // Fragment mass tolerance _registerNonNegativeDouble(TOPPMSFraggerAdapter::fragment_mass_tolerance, "<fragment_mass_tolerance>", 20.0, "Fragment mass tolerance (window is +/- this value)", false, false); registerStringOption_(TOPPMSFraggerAdapter::fragment_mass_unit, "<fragment_mass_unit>", "ppm", "Unit of fragment mass tolerance", false, false); setValidStrings_(TOPPMSFraggerAdapter::fragment_mass_unit, validUnits); // Isotope error registerStringOption_(TOPPMSFraggerAdapter::isotope_error, "<isotope_error>", "0", "Isotope correction for MS/MS events triggered on isotopic peaks. Should be set to 0 (disabled) for open search or 0/1/2 for correction of narrow window searches. Shifts the precursor mass window to multiples of this value multiplied by the mass of C13-C12.", false, false); setValidStrings_(TOPPMSFraggerAdapter::isotope_error, isotope_error_and_enzyme_termini); // TOPP digest registerTOPPSubsection_("digest", "In-Silico Digestion Parameters"); // Enzyme StringList enzyme_names; ProteaseDB::getInstance()->getAllNames(enzyme_names); registerStringOption_(TOPPMSFraggerAdapter::search_enzyme_name, "<search_enzyme_name>", "Trypsin", "Name of the enzyme to be written to the pepXML file", false, false); setValidStrings_(TOPPMSFraggerAdapter::search_enzyme_name, enzyme_names); // Cut after registerStringOption_(TOPPMSFraggerAdapter::search_enzyme_cutafter, "<search_enzyme_cutafter>", "KR", "Residues after which the enzyme cuts (specified as a string of amino acids)", false , false); // No cut before registerStringOption_(TOPPMSFraggerAdapter::search_enzyme_nocutbefore, "<search_enzyme_nocutbefore>", "P", "Residues that the enzyme will not cut before", false, false); // Number of enzyme termini registerStringOption_(TOPPMSFraggerAdapter::num_enzyme_termini, "<num_enzyme_termini>", "fully", "Number of enzyme termini (non-enzymatic (0), semi (1), fully (2)", false, false); setValidStrings_(TOPPMSFraggerAdapter::num_enzyme_termini, ListUtils::create<String>("non-enzymatic,semi,fully")); // Allowed missed cleavages registerStringOption_(TOPPMSFraggerAdapter::allowed_missed_cleavage, "<allowed_missed_cleavage>", "2", "Allowed number of missed cleavages", false, false); setValidStrings_(TOPPMSFraggerAdapter::allowed_missed_cleavage, zero_to_five); // 5 is the max. allowed value according to MSFragger // Digest min length _registerNonNegativeInt(TOPPMSFraggerAdapter::digest_min_length, "<digest_min_length>", 7, "Minimum length of peptides to be generated during in-silico digestion", false, false); // Digest max length _registerNonNegativeInt(TOPPMSFraggerAdapter::digest_max_length, "<digest_max_length>", 64, "Maximum length of peptides to be generated during in-silico digestion", false, false); // Digest min mass range _registerNonNegativeDouble(TOPPMSFraggerAdapter::digest_mass_range_min, "<digest_mass_range_min>", 500.0, "Min mass of peptides to be generated (Da)", false, false); // Digest max mass range _registerNonNegativeDouble(TOPPMSFraggerAdapter::digest_mass_range_max, "<digest_mass_range_max>", 5000.0, "Max mass of peptides to be generated (Da)", false, false); // TOPP varmod registerTOPPSubsection_("varmod", "Variable Modification Parameters"); // Clip nterm M registerFlag_(TOPPMSFraggerAdapter::clip_nterm_m, "Specifies the trimming of a protein N-terminal methionine as a variable modification", false); // Modifications registerDoubleList_(TOPPMSFraggerAdapter::varmod_masses, "<varmod1_mass .. varmod7_mass>", emptyDoubles , "Masses for variable modifications", false, false); registerStringList_(TOPPMSFraggerAdapter::varmod_syntax, "<varmod1_syntax .. varmod7_syntax>", emptyStrings, "Syntax Strings for variable modifications", false, false); registerFlag_(TOPPMSFraggerAdapter::varmod_enable_common, "Enable common variable modifications (15.9949 M and 42.0106 [^)", false); // allow_multiple_variable_mods_on_residue registerFlag_(TOPPMSFraggerAdapter::not_allow_multiple_variable_mods_on_residue, "Do not allow any one amino acid to be modified by multiple variable modifications", false); // Max variable mods per mod registerStringOption_(TOPPMSFraggerAdapter::max_variable_mods_per_mod, "<max_variable_mods_per_mod>", "2", "Maximum number of residues that can be occupied by each variable modification", false, false); setValidStrings_(TOPPMSFraggerAdapter::max_variable_mods_per_mod, zero_to_five); // Max variable mods combinations _registerNonNegativeInt(TOPPMSFraggerAdapter::max_variable_mods_combinations, "<max_variable_mods_combinations>", 5000, "Maximum allowed number of modified variably modified peptides from each peptide sequence, (maximum of 65534). If a greater number than the maximum is generated, only the unmodified peptide is considered", false, false); setMaxInt_(TOPPMSFraggerAdapter::max_variable_mods_combinations, 65534); // TOPP spectrum registerTOPPSubsection_("spectrum", "Spectrum Processing Parameters"); _registerNonNegativeInt(TOPPMSFraggerAdapter::minimum_peaks, "<minimum_peaks>", 10, "Minimum number of peaks in experimental spectrum for matching", false, false); _registerNonNegativeInt(TOPPMSFraggerAdapter::use_topn_peaks, "<use_topN_peaks>", 50, "Pre-process experimental spectrum to only use top N peaks", false, false); _registerNonNegativeDouble(TOPPMSFraggerAdapter::minimum_ratio, "<minimum_ratio>", 0.0, "Filters out all peaks in experimental spectrum less intense than this multiple of the base peak intensity", false, false); setMaxFloat_(TOPPMSFraggerAdapter::minimum_ratio, 1.0); _registerNonNegativeDouble(TOPPMSFraggerAdapter::clear_mz_range_min, "<clear_mz_range_min>", 0.0, "Removes peaks in this m/z range prior to matching (minimum value). Useful for iTRAQ/TMT experiments (i.e. 0.0 150.0)", false, false); _registerNonNegativeDouble(TOPPMSFraggerAdapter::clear_mz_range_max, "<clear_mz_range_max>", 0.0, "Removes peaks in this m/z range prior to matching (maximum value). Useful for iTRAQ/TMT experiments (i.e. 0.0 150.0)", false, false); registerStringOption_(TOPPMSFraggerAdapter::max_fragment_charge, "<max_fragment_charge>", "2", "Maximum charge state for theoretical fragments to match", false, false); setValidStrings_(TOPPMSFraggerAdapter::max_fragment_charge, ListUtils::create<String>("1,2,3,4")); registerFlag_(TOPPMSFraggerAdapter::override_charge, "Ignores precursor charge and uses charge state specified in precursor_charge range (parameters: spectrum:precursor_charge_min and spectrum:precursor_charge_max)" , false); _registerNonNegativeInt(TOPPMSFraggerAdapter::precursor_charge_min, "<precursor_charge_min>", 1, "Min charge of precursor charge range to consider. If specified, also spectrum:override_charge must be set)" , false, false); _registerNonNegativeInt(TOPPMSFraggerAdapter::precursor_charge_max, "<precursor_charge_max>", 4, "Max charge of precursor charge range to consider. If specified, also spectrum:override_charge must be set)" , false, false); registerTOPPSubsection_("search", "Open Search Features"); _registerNonNegativeInt(TOPPMSFraggerAdapter::track_zero_topn, "<track_zero_topn>", 0, "Track top N unmodified peptide results separately from main results internally for boosting features. Should be set to a number greater than search:output_report_topN if zero bin boosting is desired", false, false); _registerNonNegativeDouble(TOPPMSFraggerAdapter::zero_bin_accept_expect, "<zero_bin_accept_expect>", 0.0, "Ranks a zero-bin hit above all non-zero-bin hit if it has expectation less than this value", false, false); _registerNonNegativeDouble(TOPPMSFraggerAdapter::zero_bin_mult_expect, "<zero_bin_mult_expect>", 1.0, "Multiplies expect value of PSMs in the zero-bin during results ordering (set to less than 1 for boosting)", false, false); _registerNonNegativeInt(TOPPMSFraggerAdapter::add_topn_complementary, "<add_topn_complementary>", 0, "Inserts complementary ions corresponding to the top N most intense fragments in each experimental spectrum. Useful for recovery of modified peptides near C-terminus in open search. 0 disables this option", false, false); _registerNonNegativeInt(TOPPMSFraggerAdapter::min_fragments_modeling, "<min_fragments_modeling>", 3, "Minimum number of matched peaks in PSM for inclusion in statistical modeling", false, false); _registerNonNegativeInt(TOPPMSFraggerAdapter::min_matched_fragments, "<min_matched_fragments>", 4, "Minimum number of matched peaks for PSM to be reported. MSFragger recommends a minimum of 4 for narrow window searching and 6 for open searches", false, false); _registerNonNegativeInt(TOPPMSFraggerAdapter::output_report_topn, "<output_report_topn>", 1, "Reports top N PSMs per input spectrum", false, false); _registerNonNegativeDouble(TOPPMSFraggerAdapter::output_max_expect, "<output_max_expect>", 50.0, "Suppresses reporting of PSM if top hit has expectation greater than this threshold", false, false); registerTOPPSubsection_("statmod", "Static Modification Parameters"); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_cterm_peptide, "<add_cterm_peptide>", 0.0, "Statically add mass in Da to C-terminal of peptide", false, false); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_nterm_peptide, "<add_nterm_peptide>", 0.0, "Statically add mass in Da to N-terminal of peptide", false, false); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_cterm_protein, "<add_cterm_protein>", 0.0, "Statically add mass in Da to C-terminal of protein", false, false); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_nterm_protein, "<add_nterm_protein>", 0.0, "Statically add mass in Da to N-terminal of protein", false, false); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_G_glycine, "<add_G_glycine>", 0.0, "Statically add mass to glycine", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_A_alanine, "<add_A_alanine>", 0.0, "Statically add mass to alanine", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_S_serine, "<add_S_serine>", 0.0, "Statically add mass to serine", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_P_proline, "<add_P_proline>", 0.0, "Statically add mass to proline", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_V_valine, "<add_V_valine>", 0.0, "Statically add mass to valine", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_T_threonine, "<add_T_threonine>", 0.0, "Statically add mass to threonine", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_C_cysteine, "<add_C_cysteine>", 57.021464, "Statically add mass to cysteine", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_L_leucine, "<add_L_leucine>", 0.0, "Statically add mass to leucine", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_I_isoleucine, "<add_I_isoleucine>", 0.0, "Statically add mass to isoleucine", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_N_asparagine, "<add_N_asparagine>", 0.0, "Statically add mass to asparagine", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_D_aspartic_acid, "<add_D_aspartic_acid>", 0.0, "Statically add mass to aspartic_acid", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_Q_glutamine, "<add_Q_glutamine>", 0.0, "Statically add mass to glutamine", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_K_lysine, "<add_K_lysine>", 0.0, "Statically add mass to lysine", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_E_glutamic_acid, "<add_E_glutamic_acid>", 0.0, "Statically add mass to glutamic_acid", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_M_methionine, "<add_M_methionine>", 0.0, "Statically add mass to methionine", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_H_histidine, "<add_H_histidine>", 0.0, "Statically add mass to histidine", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_F_phenylalanine, "<add_F_phenylalanine>", 0.0, "Statically add mass to phenylalanine", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_R_arginine, "<add_R_arginine>", 0.0, "Statically add mass to arginine", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_Y_tyrosine, "<add_Y_tyrosine>", 0.0, "Statically add mass to tyrosine", false, true); _registerNonNegativeDouble(TOPPMSFraggerAdapter::add_W_tryptophan, "<add_W_tryptophan>", 0.0, "Statically add mass to tryptophan", false, true); } ExitCodes main_(int, const char**) override { try { // java executable this->java_exe = this->getStringOption_(TOPPMSFraggerAdapter::java_executable); if (!JavaInfo::canRun(this->java_exe, true)) { _fatalError("Java executable cannot be run!"); } // executable this->exe = this->getStringOption_(TOPPMSFraggerAdapter::executable); if (this->exe.empty()) { // looks for MSFRAGGER_PATH in the environment QString qmsfragger_path = QProcessEnvironment::systemEnvironment().value("MSFRAGGER_PATH"); if (qmsfragger_path.isEmpty()) { _fatalError("No executable for MSFragger could be found!"); } this->exe = qmsfragger_path; } // input, output, database name const String database = this->getStringOption_(TOPPMSFraggerAdapter::database); input_file = (this->getStringOption_(TOPPMSFraggerAdapter::in)).toQString(); output_file = this->getStringOption_(TOPPMSFraggerAdapter::out); optional_output_file = this->getStringOption_(TOPPMSFraggerAdapter::opt_out); // tolerance const double arg_precursor_mass_tolerance(this->getDoubleOption_(TOPPMSFraggerAdapter::precursor_mass_tolerance)); const String & arg_precursor_mass_unit = this->getStringOption_(TOPPMSFraggerAdapter::precursor_mass_unit); const double arg_precursor_true_tolerance(this->getDoubleOption_(TOPPMSFraggerAdapter::precursor_true_tolerance)); const String & arg_precursor_true_unit = this->getStringOption_(TOPPMSFraggerAdapter::precursor_true_unit); const double arg_fragment_mass_tolerance(this->getDoubleOption_(TOPPMSFraggerAdapter::fragment_mass_tolerance)); const String & arg_fragment_mass_unit = this->getStringOption_(TOPPMSFraggerAdapter::fragment_mass_unit); const String & arg_isotope_error = this->getStringOption_(TOPPMSFraggerAdapter::isotope_error); // digest const String & arg_search_enzyme_name = this->getStringOption_(TOPPMSFraggerAdapter::search_enzyme_name); const String & arg_search_enzyme_cutafter = this->getStringOption_(TOPPMSFraggerAdapter::search_enzyme_cutafter); const String & arg_search_enzyme_nocutbefore = this->getStringOption_(TOPPMSFraggerAdapter::search_enzyme_nocutbefore); std::map< String,int > num_enzyme_termini; num_enzyme_termini["non-enzymatic"] = 0; num_enzyme_termini["semi"] = 1; num_enzyme_termini["fully"] = 2; const int arg_num_enzyme_termini = num_enzyme_termini[this->getStringOption_(TOPPMSFraggerAdapter::num_enzyme_termini)]; const String & arg_allowed_missed_cleavage = this->getStringOption_(TOPPMSFraggerAdapter::allowed_missed_cleavage); const int arg_digest_min_length = this->getIntOption_(TOPPMSFraggerAdapter::digest_min_length); const int arg_digest_max_length = this->getIntOption_(TOPPMSFraggerAdapter::digest_max_length); ensureRange(arg_digest_min_length, arg_digest_max_length, "Maximum length of digest is not allowed to be smaller than minimum length of digest"); const double arg_digest_mass_range_min = this->getDoubleOption_(TOPPMSFraggerAdapter::digest_mass_range_min); const double arg_digest_mass_range_max = this->getDoubleOption_(TOPPMSFraggerAdapter::digest_mass_range_max); ensureRange(arg_digest_mass_range_min, arg_digest_mass_range_max, "Maximum digest mass is not allowed to be smaller than minimum digest mass!"); // varmod const bool arg_clip_nterm_m = this->getFlag_(clip_nterm_m); std::vector< double > arg_varmod_masses = this->getDoubleList_(TOPPMSFraggerAdapter::varmod_masses); std::vector< String > arg_varmod_syntax = this->getStringList_(TOPPMSFraggerAdapter::varmod_syntax); // assignment of mass to syntax is by index, so the vectors have to be the same length if (arg_varmod_masses.size() != arg_varmod_syntax.size()) { _fatalError("List of arguments for the parameters 'varmod_masses' and 'varmod_syntax' must have the same length!"); } // only up to 7 variable modifications are allowed if (arg_varmod_masses.size() > 7) { _fatalError("MSFragger is restricted to at most 7 variable modifications."); } // add common variable modifications if requested if (this->getFlag_(varmod_enable_common)) { // oxidation on methionine this->_addVarMod(arg_varmod_masses, arg_varmod_syntax, 15.9949, "M"); // N-terminal acetylation this->_addVarMod(arg_varmod_masses, arg_varmod_syntax, 42.0106, "[^"); } const bool arg_not_allow_multiple_variable_mods_on_residue = this->getFlag_(TOPPMSFraggerAdapter::not_allow_multiple_variable_mods_on_residue); const String & arg_max_variable_mods_per_mod = this->getStringOption_(TOPPMSFraggerAdapter::max_variable_mods_per_mod); const int arg_max_variable_mods_combinations = this->getIntOption_(TOPPMSFraggerAdapter::max_variable_mods_combinations); // spectrum const int arg_minimum_peaks = this->getIntOption_(TOPPMSFraggerAdapter::minimum_peaks); const int arg_use_topn_peaks = this->getIntOption_(TOPPMSFraggerAdapter::use_topn_peaks); const double arg_minimum_ratio = this->getDoubleOption_(TOPPMSFraggerAdapter::minimum_ratio); const double arg_clear_mz_range_min = this->getDoubleOption_(TOPPMSFraggerAdapter::clear_mz_range_min); const double arg_clear_mz_range_max = this->getDoubleOption_(TOPPMSFraggerAdapter::clear_mz_range_max); ensureRange(arg_clear_mz_range_min, arg_clear_mz_range_max, "Maximum clear mz value is not allowed to be smaller than minimum clear mz value!"); const String & arg_max_fragment_charge = this->getStringOption_(TOPPMSFraggerAdapter::max_fragment_charge); const bool arg_override_charge = this->getFlag_(TOPPMSFraggerAdapter::override_charge); const int arg_precursor_charge_min = this->getIntOption_(TOPPMSFraggerAdapter::precursor_charge_min); const int arg_precursor_charge_max = this->getIntOption_(TOPPMSFraggerAdapter::precursor_charge_max); ensureRange(arg_precursor_charge_min, arg_precursor_charge_max, "Maximum precursor charge is not allowed to be smaller than minimum precursor charge!"); // ensures that the user is aware of overriding the precursoe charges if ((arg_precursor_charge_min != 1 || arg_precursor_charge_max != 4) && !arg_override_charge) { _fatalError("If you want to ignore the precursor charge, please also set the -" + override_charge + " flag!"); } // search const int arg_track_zero_topn = this->getIntOption_(TOPPMSFraggerAdapter::track_zero_topn); const double arg_zero_bin_accept_expect = this->getDoubleOption_(TOPPMSFraggerAdapter::zero_bin_accept_expect); const double arg_zero_bin_mult_expect = this->getDoubleOption_(TOPPMSFraggerAdapter::zero_bin_mult_expect); const int arg_add_topn_complementary = this->getIntOption_(TOPPMSFraggerAdapter::add_topn_complementary); const int arg_min_fragments_modeling = this->getIntOption_(TOPPMSFraggerAdapter::min_fragments_modeling); const int arg_min_matched_fragments = this->getIntOption_(TOPPMSFraggerAdapter::min_matched_fragments); const int arg_output_report_topn = this->getIntOption_(TOPPMSFraggerAdapter::output_report_topn); const double arg_output_max_expect = this->getDoubleOption_(TOPPMSFraggerAdapter::output_max_expect); // statmod const double arg_add_cterm_peptide = this->getDoubleOption_(TOPPMSFraggerAdapter::add_cterm_peptide); const double arg_add_nterm_peptide = this->getDoubleOption_(TOPPMSFraggerAdapter::add_nterm_peptide); const double arg_add_cterm_protein = this->getDoubleOption_(TOPPMSFraggerAdapter::add_cterm_protein); const double arg_add_nterm_protein = this->getDoubleOption_(TOPPMSFraggerAdapter::add_nterm_protein); const double arg_add_G_glycine = this->getDoubleOption_(TOPPMSFraggerAdapter::add_G_glycine); const double arg_add_A_alanine = this->getDoubleOption_(TOPPMSFraggerAdapter::add_A_alanine); const double arg_add_S_serine = this->getDoubleOption_(TOPPMSFraggerAdapter::add_S_serine); const double arg_add_P_proline = this->getDoubleOption_(TOPPMSFraggerAdapter::add_P_proline); const double arg_add_V_valine = this->getDoubleOption_(TOPPMSFraggerAdapter::add_V_valine); const double arg_add_T_threonine = this->getDoubleOption_(TOPPMSFraggerAdapter::add_T_threonine); const double arg_add_C_cysteine = this->getDoubleOption_(TOPPMSFraggerAdapter::add_C_cysteine); const double arg_add_L_leucine = this->getDoubleOption_(TOPPMSFraggerAdapter::add_L_leucine); const double arg_add_I_isoleucine = this->getDoubleOption_(TOPPMSFraggerAdapter::add_I_isoleucine); const double arg_add_N_asparagine = this->getDoubleOption_(TOPPMSFraggerAdapter::add_N_asparagine); const double arg_add_D_aspartic_acid = this->getDoubleOption_(TOPPMSFraggerAdapter::add_D_aspartic_acid); const double arg_add_Q_glutamine = this->getDoubleOption_(TOPPMSFraggerAdapter::add_Q_glutamine); const double arg_add_K_lysine = this->getDoubleOption_(TOPPMSFraggerAdapter::add_K_lysine); const double arg_add_E_glutamic_acid = this->getDoubleOption_(TOPPMSFraggerAdapter::add_E_glutamic_acid); const double arg_add_M_methionine = this->getDoubleOption_(TOPPMSFraggerAdapter::add_M_methionine); const double arg_add_H_histidine = this->getDoubleOption_(TOPPMSFraggerAdapter::add_H_histidine); const double arg_add_F_phenylalanine = this->getDoubleOption_(TOPPMSFraggerAdapter::add_F_phenylalanine); const double arg_add_R_arginine = this->getDoubleOption_(TOPPMSFraggerAdapter::add_R_arginine); const double arg_add_Y_tyrosine = this->getDoubleOption_(TOPPMSFraggerAdapter::add_Y_tyrosine); const double arg_add_W_tryptophan = this->getDoubleOption_(TOPPMSFraggerAdapter::add_W_tryptophan); // parameters have been read in and verified, they are now going to be written into the fragger.params file in a temporary directory QString working_directory = this->makeAutoRemoveTempDirectory_().toQString(); const QFileInfo tmp_param_file(this->working_directory, "fragger.params"); this->parameter_file_path = String(tmp_param_file.absoluteFilePath()); writeDebug_("Parameter file for MSFragger: '" + this->parameter_file_path + "'", TOPPMSFraggerAdapter::LOG_LEVEL_VERBOSE); writeDebug_("Working Directory: '" + String(this->working_directory) + "'", TOPPMSFraggerAdapter::LOG_LEVEL_VERBOSE); writeDebug_("If you want to keep the working directory and the parameter file, set the -debug to 2", 1); ofstream os(this->parameter_file_path.c_str()); // Write all the parameters into the file os << "database_name = " << String(database) << "\nnum_threads = " << this->getIntOption_("threads") << "\n\nprecursor_mass_tolerance = " << arg_precursor_mass_tolerance << "\nprecursor_mass_units = " << (arg_precursor_mass_unit == "Da" ? 0 : 1) << "\nprecursor_true_tolerance = " << arg_precursor_true_tolerance << "\nprecursor_true_units = " << (arg_precursor_true_unit == "Da" ? 0 : 1) << "\nfragment_mass_tolerance = " << arg_fragment_mass_tolerance << "\nfragment_mass_units = " << (arg_fragment_mass_unit == "Da" ? 0 : 1) << "\n\nisotope_error = " << arg_isotope_error << "\n\nsearch_enzyme_name = " << arg_search_enzyme_name << "\nsearch_enzyme_cutafter = " << arg_search_enzyme_cutafter << "\nsearch_enzyme_butnotafter = " << arg_search_enzyme_nocutbefore << "\n\nnum_enzyme_termini = " << arg_num_enzyme_termini << "\nallowed_missed_cleavage = " << arg_allowed_missed_cleavage << "\n\nclip_nTerm_M = " << arg_clip_nterm_m << '\n'; // Write variable modifications (and also write to log) writeLog_("Variable Modifications set to:"); for (Size i = 0; i < arg_varmod_masses.size(); ++i) { const String varmod = "variable_mod_0" + String(i+1) + " = " + String(arg_varmod_masses[i]) + " " + String(arg_varmod_syntax[i]); os << "\n" << varmod; writeLog_(varmod); } os << std::endl << "\nallow_multiple_variable_mods_on_residue = " << (arg_not_allow_multiple_variable_mods_on_residue ? 0 : 1) << "\nmax_variable_mods_per_mod = " << arg_max_variable_mods_per_mod << "\nmax_variable_mods_combinations = " << arg_max_variable_mods_combinations << "\n\noutput_file_extension = " << "pepXML" << "\noutput_format = " << "pepXML" << "\noutput_report_topN = " << arg_output_report_topn << "\noutput_max_expect = " << arg_output_max_expect << "\n\nprecursor_charge = " << arg_precursor_charge_min << " " << arg_precursor_charge_max << "\noverride_charge = " << (arg_override_charge ? 1 : 0) << "\n\ndigest_min_length = " << arg_digest_min_length << "\ndigest_max_length = " << arg_digest_max_length << "\ndigest_mass_range = " << arg_digest_mass_range_min << " " << arg_digest_mass_range_max << "\nmax_fragment_charge = " << arg_max_fragment_charge << "\n\ntrack_zero_topN = " << arg_track_zero_topn << "\nzero_bin_accept_expect = " << arg_zero_bin_accept_expect << "\nzero_bin_mult_expect = " << arg_zero_bin_mult_expect << "\nadd_topN_complementary = " << arg_add_topn_complementary << "\n\nminimum_peaks = " << arg_minimum_peaks << "\nuse_topN_peaks = " << arg_use_topn_peaks << "\nmin_fragments_modelling = " << arg_min_fragments_modeling << "\nmin_matched_fragments = " << arg_min_matched_fragments << "\nminimum_ratio = " << arg_minimum_ratio << "\nclear_mz_range = " << arg_clear_mz_range_min << " " << arg_clear_mz_range_max << "\nadd_Cterm_peptide = " << arg_add_cterm_peptide << "\nadd_Nterm_peptide = " << arg_add_nterm_peptide << "\nadd_Cterm_protein = " << arg_add_cterm_protein << "\nadd_Nterm_protein = " << arg_add_nterm_protein << "\n\nadd_G_glycine = " << arg_add_G_glycine << "\nadd_A_alanine = " << arg_add_A_alanine << "\nadd_S_serine = " << arg_add_S_serine << "\nadd_P_proline = " << arg_add_P_proline << "\nadd_V_valine = " << arg_add_V_valine << "\nadd_T_threonine = " << arg_add_T_threonine << "\nadd_C_cysteine = " << arg_add_C_cysteine << "\nadd_L_leucine = " << arg_add_L_leucine << "\nadd_I_isoleucine = " << arg_add_I_isoleucine << "\nadd_N_asparagine = " << arg_add_N_asparagine << "\nadd_D_aspartic_acid = " << arg_add_D_aspartic_acid << "\nadd_Q_glutamine = " << arg_add_Q_glutamine << "\nadd_K_lysine = " << arg_add_K_lysine << "\nadd_E_glutamic_acid = " << arg_add_E_glutamic_acid << "\nadd_M_methionine = " << arg_add_M_methionine << "\nadd_H_histidine = " << arg_add_H_histidine << "\nadd_F_phenylalanine = " << arg_add_F_phenylalanine << "\nadd_R_arginine = " << arg_add_R_arginine << "\nadd_Y_tyrosine = " << arg_add_Y_tyrosine << "\nadd_W_tryptophan = " << arg_add_W_tryptophan; os.close(); } catch (int) { return ILLEGAL_PARAMETERS; } QStringList process_params; // the actual process is Java, not MSFragger process_params << "-Xmx" + QString::number(this->getIntOption_(java_heapmemory)) + "m" << "-jar" << this->exe.toQString() << this->parameter_file_path.toQString() << input_file; QProcess process_msfragger; process_msfragger.setWorkingDirectory(this->working_directory); if (this->debug_level_ >= TOPPMSFraggerAdapter::LOG_LEVEL_VERBOSE) { writeDebug_("COMMAND LINE CALL IS:", 1); String command_line = this->java_exe; for (const auto& process_param : process_params) { command_line += (" " + process_param); } writeDebug_(command_line, TOPPMSFraggerAdapter::LOG_LEVEL_VERBOSE); } process_msfragger.start(this->java_exe.toQString(), process_params); if (!process_msfragger.waitForFinished(-1) || process_msfragger.exitCode() != 0) { OPENMS_LOG_FATAL_ERROR << "FATAL: Invocation of MSFraggerAdapter has failed. Error code was: " << process_msfragger.exitCode() << std::endl; const QString msfragger_stdout(process_msfragger.readAllStandardOutput()); const QString msfragger_stderr(process_msfragger.readAllStandardError()); writeLog_(msfragger_stdout); writeLog_(msfragger_stderr); writeLog_(String(process_msfragger.exitCode())); return EXTERNAL_PROGRAM_ERROR; } // convert from pepXML to idXML String pepxmlfile = File::removeExtension(input_file) + "." + "pepXML"; std::vector<PeptideIdentification> peptide_identifications; std::vector<ProteinIdentification> protein_identifications; PepXMLFile().load(pepxmlfile, protein_identifications, peptide_identifications); for (auto it = protein_identifications.begin(); it != protein_identifications.end(); it++) { it->setSearchEngine("MSFragger"); } IdXMLFile().store(output_file, protein_identifications, peptide_identifications); // remove the msfragger pepXML output from the user lcoation if (optional_output_file.empty()) { File::remove(pepxmlfile); } else { // rename the pepXML file to the opt_out QFile::rename(pepxmlfile.toQString(), optional_output_file.toQString()); } // remove ".pepindex" database file if (this->debug_level_ < 2) { String db_index = this->getStringOption_(TOPPMSFraggerAdapter::database) + ".1.pepindex"; File::remove(db_index); } return EXECUTION_OK; } private: QString working_directory; String java_exe; String exe; String parameter_file_path; QString input_file; String output_file; String optional_output_file; // adds variable modification if not already present void _addVarMod(std::vector< double > & masses, std::vector< String > & syntaxes, const double mass, const String & syntax) const { const std::vector< double >::iterator it1 = std::find(masses.begin(), masses.end(), mass); const std::vector< String >::iterator it2 = std::find(syntaxes.begin(), syntaxes.end(), syntax); // add the provided variable modification if not already present if ( it1 == masses.end() || it2 == syntaxes.end() || std::distance(masses.begin(), it1) != std::distance(syntaxes.begin(), it2)) { masses.push_back(mass); syntaxes.push_back(syntax); } } inline void _registerNonNegativeInt(const String & param_name, const String & argument, const int default_value, const String & description, const bool required, const bool advanced) { this->registerIntOption_(param_name, argument, default_value, description, required, advanced); this->setMinInt_(param_name, 0); } inline void _registerNonNegativeDouble(const String & param_name, const String & argument, const double default_value, const String & description, const bool required, const bool advanced) { this->registerDoubleOption_(param_name, argument, default_value, description, required, advanced); this->setMinFloat_(param_name, 0.0); } inline void _fatalError(const String & message) { OPENMS_LOG_FATAL_ERROR << "FATAL: " << message << std::endl; throw 1; } void checkUnique(const StringList & elements, const String & message) { for (Size i = 0; i < elements.size(); ++i) { for (Size j = 0; j < i; ++j) { if (elements[i] == elements[j]) { _fatalError(message); } } } } inline void ensureRange(const double left, const double right, const String & message) const { if (right < left) { OPENMS_LOG_ERROR << "FATAL: " << message << std::endl; throw 1; } } }; const String TOPPMSFraggerAdapter::java_executable = "java_executable"; const String TOPPMSFraggerAdapter::java_heapmemory = "java_heapmemory"; const String TOPPMSFraggerAdapter::executable = "executable"; const String TOPPMSFraggerAdapter::in = "in"; const String TOPPMSFraggerAdapter::out = "out"; const String TOPPMSFraggerAdapter::opt_out = "opt_out"; const String TOPPMSFraggerAdapter::database = "database"; // tolerance const String TOPPMSFraggerAdapter::precursor_mass_tolerance = "tolerance:precursor_mass_tolerance"; const String TOPPMSFraggerAdapter::precursor_mass_unit = "tolerance:precursor_mass_unit"; const String TOPPMSFraggerAdapter::precursor_true_tolerance = "tolerance:precursor_true_tolerance"; const String TOPPMSFraggerAdapter::precursor_true_unit = "tolerance:precursor_true_unit"; const String TOPPMSFraggerAdapter::fragment_mass_tolerance = "tolerance:fragment_mass_tolerance"; const String TOPPMSFraggerAdapter::fragment_mass_unit = "tolerance:fragment_mass_unit"; const String TOPPMSFraggerAdapter::isotope_error = "tolerance:isotope_error"; // digest const String TOPPMSFraggerAdapter::search_enzyme_name = "digest:search_enzyme_name"; const String TOPPMSFraggerAdapter::search_enzyme_cutafter = "digest:search_enzyme_cutafter"; const String TOPPMSFraggerAdapter::search_enzyme_nocutbefore = "digest:search_enzyme_nocutbefore"; const String TOPPMSFraggerAdapter::num_enzyme_termini = "digest:num_enzyme_termini"; const String TOPPMSFraggerAdapter::allowed_missed_cleavage = "digest:allowed_missed_cleavage"; const String TOPPMSFraggerAdapter::digest_min_length = "digest:min_length"; const String TOPPMSFraggerAdapter::digest_max_length = "digest:max_length"; const String TOPPMSFraggerAdapter::digest_mass_range_min = "digest:mass_range_min"; const String TOPPMSFraggerAdapter::digest_mass_range_max = "digest:mass_range_max"; // varmod const String TOPPMSFraggerAdapter::clip_nterm_m = "varmod:clip_nterm_m"; const String TOPPMSFraggerAdapter::varmod_masses = "varmod:masses"; const String TOPPMSFraggerAdapter::varmod_syntax = "varmod:syntaxes"; const String TOPPMSFraggerAdapter::varmod_enable_common = "varmod:enable_common"; const String TOPPMSFraggerAdapter::not_allow_multiple_variable_mods_on_residue = "varmod:not_allow_multiple_variable_mods_on_residue"; const String TOPPMSFraggerAdapter::max_variable_mods_per_mod = "varmod:max_variable_mods_per_mod"; const String TOPPMSFraggerAdapter::max_variable_mods_combinations = "varmod:max_variable_mods_combinations"; // spectrum const String TOPPMSFraggerAdapter::minimum_peaks = "spectrum:minimum_peaks"; const String TOPPMSFraggerAdapter::use_topn_peaks = "spectrum:use_topn_peaks"; const String TOPPMSFraggerAdapter::minimum_ratio = "spectrum:minimum_ratio"; const String TOPPMSFraggerAdapter::clear_mz_range_min = "spectrum:clear_mz_range_min"; const String TOPPMSFraggerAdapter::clear_mz_range_max = "spectrum:clear_mz_range_max"; const String TOPPMSFraggerAdapter::max_fragment_charge = "spectrum:max_fragment_charge"; const String TOPPMSFraggerAdapter::override_charge = "spectrum:override_charge"; const String TOPPMSFraggerAdapter::precursor_charge_min = "spectrum:precursor_charge_min"; const String TOPPMSFraggerAdapter::precursor_charge_max = "spectrum:precursor_charge_max"; // search const String TOPPMSFraggerAdapter::track_zero_topn = "search:track_zero_topn"; const String TOPPMSFraggerAdapter::zero_bin_accept_expect = "search:zero_bin_accept_expect"; const String TOPPMSFraggerAdapter::zero_bin_mult_expect = "search:zero_bin_mult_expect"; const String TOPPMSFraggerAdapter::add_topn_complementary = "search:add_topn_complementary"; const String TOPPMSFraggerAdapter::min_fragments_modeling = "search:min_fragments_modeling"; const String TOPPMSFraggerAdapter::min_matched_fragments = "search:min_matched_fragments"; const String TOPPMSFraggerAdapter::output_report_topn = "search:output_report_topn"; const String TOPPMSFraggerAdapter::output_max_expect = "search:output_max_expect"; // statmod const String TOPPMSFraggerAdapter::add_cterm_peptide = "statmod:add_cterm_peptide"; const String TOPPMSFraggerAdapter::add_nterm_peptide = "statmod:add_nterm_peptide"; const String TOPPMSFraggerAdapter::add_cterm_protein = "statmod:add_cterm_protein"; const String TOPPMSFraggerAdapter::add_nterm_protein = "statmod:add_nterm_protein"; const String TOPPMSFraggerAdapter::add_G_glycine = "statmod:add_G_glycine"; const String TOPPMSFraggerAdapter::add_A_alanine = "statmod:add_A_alanine"; const String TOPPMSFraggerAdapter::add_S_serine = "statmod:add_S_serine"; const String TOPPMSFraggerAdapter::add_P_proline = "statmod:add_P_proline"; const String TOPPMSFraggerAdapter::add_V_valine = "statmod:add_V_valine"; const String TOPPMSFraggerAdapter::add_T_threonine = "statmod:add_T_threonine"; const String TOPPMSFraggerAdapter::add_C_cysteine = "statmod:add_C_cysteine"; const String TOPPMSFraggerAdapter::add_L_leucine = "statmod:add_L_leucine"; const String TOPPMSFraggerAdapter::add_I_isoleucine = "statmod:add_I_isoleucine"; const String TOPPMSFraggerAdapter::add_N_asparagine = "statmod:add_N_asparagine"; const String TOPPMSFraggerAdapter::add_D_aspartic_acid = "statmod:add_D_aspartic_acid"; const String TOPPMSFraggerAdapter::add_Q_glutamine = "statmod:add_Q_glutamine"; const String TOPPMSFraggerAdapter::add_K_lysine = "statmod:add_K_lysine"; const String TOPPMSFraggerAdapter::add_E_glutamic_acid = "statmod:add_E_glutamic_acid"; const String TOPPMSFraggerAdapter::add_M_methionine = "statmod:add_M_methionine"; const String TOPPMSFraggerAdapter::add_H_histidine = "statmod:add_H_histidine"; const String TOPPMSFraggerAdapter::add_F_phenylalanine = "statmod:add_F_phenylalanine"; const String TOPPMSFraggerAdapter::add_R_arginine = "statmod:add_R_arginine"; const String TOPPMSFraggerAdapter::add_Y_tyrosine = "statmod:add_Y_tyrosine"; const String TOPPMSFraggerAdapter::add_W_tryptophan = "statmod:add_W_tryptophan"; const int TOPPMSFraggerAdapter::LOG_LEVEL_VERBOSE = 1; int main(int argc, const char** argv) { TOPPMSFraggerAdapter tool; return tool.main(argc, argv); } /// @endcond
60.614841
376
0.74179
avasq011
f58052c19e8ce9fb896998e3cc7b91608b4ec265
4,564
cpp
C++
legacy/galaxy/components/BatchSprite.cpp
reworks/rework
90508252c9a4c77e45a38e7ce63cfd99f533f42b
[ "Apache-2.0" ]
19
2020-02-02T16:36:46.000Z
2021-12-25T07:02:28.000Z
legacy/galaxy/components/BatchSprite.cpp
reworks/rework
90508252c9a4c77e45a38e7ce63cfd99f533f42b
[ "Apache-2.0" ]
103
2020-10-13T09:03:42.000Z
2022-03-26T03:41:50.000Z
legacy/galaxy/components/BatchSprite.cpp
reworks/rework
90508252c9a4c77e45a38e7ce63cfd99f533f42b
[ "Apache-2.0" ]
5
2020-03-13T06:14:37.000Z
2021-12-12T02:13:46.000Z
/// /// BatchSprite.cpp /// galaxy /// /// Refer to LICENSE.txt for more details. /// #include "galaxy/core/ServiceLocator.hpp" #include "galaxy/resource/TextureBook.hpp" #include "BatchSprite.hpp" namespace galaxy { namespace components { BatchSprite::BatchSprite() noexcept : Serializable {this} , m_index {0} , m_region {0.0f, 0.0f, 0.0f, 0.0f} , m_clip {0.0f, 0.0f} , m_opacity {255} { } BatchSprite::BatchSprite(const nlohmann::json& json) : Serializable {this} , m_index {0} , m_region {0.0f, 0.0f, 0.0f, 0.0f} , m_clip {0.0f, 0.0f} , m_opacity {255} { deserialize(json); } BatchSprite::BatchSprite(BatchSprite&& bs) noexcept : Serializable {this} { this->m_clip = std::move(bs.m_clip); this->m_key = std::move(bs.m_key); this->m_region = std::move(bs.m_region); this->m_index = bs.m_index; this->m_layer = std::move(bs.m_layer); this->m_opacity = bs.m_opacity; } BatchSprite& BatchSprite::operator=(BatchSprite&& bs) noexcept { if (this != &bs) { this->m_clip = std::move(bs.m_clip); this->m_key = std::move(bs.m_key); this->m_region = std::move(bs.m_region); this->m_index = bs.m_index; this->m_layer = std::move(bs.m_layer); this->m_opacity = bs.m_opacity; } return *this; } BatchSprite::~BatchSprite() noexcept { } void BatchSprite::create(const math::Rect<float>& region, std::string_view layer, std::size_t index) noexcept { m_region = region; m_index = index; m_clip = {0.0f, 0.0f}; m_layer = static_cast<std::string>(layer); } void BatchSprite::create(std::string_view texture_key, std::string_view layer) noexcept { auto info = SL_HANDLE.texturebook()->search(texture_key); if (info != std::nullopt) { m_key = static_cast<std::string>(texture_key); m_region = info.value().m_region; m_index = info.value().m_index; m_clip = {0.0f, 0.0f}; m_layer = static_cast<std::string>(layer); } else { GALAXY_LOG(GALAXY_ERROR, "Failed to get texture from textureatlas for batchsprite: {0}.", texture_key); } } void BatchSprite::update_region(std::string_view texture_key) noexcept { create(texture_key, m_layer); } void BatchSprite::set_layer(std::string_view layer) noexcept { m_layer = static_cast<std::string>(layer); } void BatchSprite::set_opacity(const std::uint8_t opacity) noexcept { m_opacity = std::clamp<std::uint8_t>(opacity, 0, 255); } void BatchSprite::clip_width(const float width) noexcept { m_clip.x = width; m_region.m_width = width; } void BatchSprite::clip_height(const float height) noexcept { m_clip.y = height; m_region.m_height = height; } const glm::vec2& BatchSprite::get_clip() const noexcept { return m_clip; } const std::string& BatchSprite::get_layer() const noexcept { return m_layer; } const std::uint8_t BatchSprite::get_opacity() const noexcept { return m_opacity; } const math::Rect<float>& BatchSprite::get_region() const noexcept { return m_region; } const std::string& BatchSprite::get_key() const noexcept { return m_key; } const std::size_t BatchSprite::get_atlas_index() const noexcept { return m_index; } nlohmann::json BatchSprite::serialize() { nlohmann::json json = "{}"_json; json["texture-key"] = m_key; json["layer"] = m_layer; json["opacity"] = m_opacity; json["clip"] = nlohmann::json::object(); json["clip"]["w"] = m_clip.x; json["clip"]["h"] = m_clip.y; json["region"] = nlohmann::json::object(); json["region"]["x"] = m_region.m_x; json["region"]["y"] = m_region.m_y; json["region"]["w"] = m_region.m_width; json["region"]["h"] = m_region.m_height; return json; } void BatchSprite::deserialize(const nlohmann::json& json) { if (json.count("texture-key") > 0) { create(json.at("texture-key"), json.at("layer")); } else if (json.count("region") > 0) { const auto& region = json.at("region"); m_region.m_x = region.at("x"); m_region.m_y = region.at("y"); m_region.m_width = region.at("w"); m_region.m_height = region.at("h"); create(region, json.at("layer")); } set_opacity(json.at("opacity")); if (json.count("clip") > 0) { const auto& clip = json.at("clip"); m_clip.x = clip.at("w"); m_clip.y = clip.at("h"); } } } // namespace components } // namespace galaxy
23.050505
111
0.622699
reworks
f580630eea06ce8ba9b530ae7bc4a4449b7fc846
1,167
cpp
C++
Contest 1008/E.cpp
PC-DOS/SEUCPP-OJ-KEYS
073f97fb29a659abd25554330382f0a7149c2511
[ "MIT" ]
null
null
null
Contest 1008/E.cpp
PC-DOS/SEUCPP-OJ-KEYS
073f97fb29a659abd25554330382f0a7149c2511
[ "MIT" ]
null
null
null
Contest 1008/E.cpp
PC-DOS/SEUCPP-OJ-KEYS
073f97fb29a659abd25554330382f0a7149c2511
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> #include <cmath> #include <string> #include <cstring> using namespace std; long GetNonOddCount(long number){ string num; long nCount = 0; num = to_string(number); long i; int tmp; for (i = 0; i <= num.length() - 1; ++i){ tmp = num[i] - '0'; if (tmp % 2 == 0) ++nCount; } return nCount; } void Process(int n){ n = abs(n); int Num; int Count_NotOdd; int Count_Odd; int i=0; if (n == 321) cout << 321; else if (n == 0){ cout << 101 << endl; Process(101); } else{ Num = int(log10(n)) + 1; Count_NotOdd = GetNonOddCount(n); Count_Odd = Num - Count_NotOdd; i += Count_NotOdd; if (i == 0) i += Count_Odd * 10; else i += Count_Odd*pow(10, int(log10(i)) + 1); i +=Num*pow(10, int(log10(i)) + 1); if (i != 321) cout << i << endl; Process(i); } } int main(){ long n; cin >> n; Process(n); //system("pause > nul"); return 0; }
21.611111
58
0.449871
PC-DOS
f5815785970c6447eadbd394e8317436b675aff9
847
cpp
C++
src/wallet/test/wallet_transaction_tests.cpp
wilofice/dahomey
5cbc2406a27e68bbe30f85a7162b86f4741effab
[ "MIT" ]
1
2022-03-19T13:35:37.000Z
2022-03-19T13:35:37.000Z
src/wallet/test/wallet_transaction_tests.cpp
wilofice/danxome
5cbc2406a27e68bbe30f85a7162b86f4741effab
[ "MIT" ]
null
null
null
src/wallet/test/wallet_transaction_tests.cpp
wilofice/danxome
5cbc2406a27e68bbe30f85a7162b86f4741effab
[ "MIT" ]
null
null
null
// Copyright (c) 2021 The Danxome Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <wallet/transaction.h> #include <wallet/test/wallet_test_fixture.h> #include <boost/test/unit_test.hpp> namespace wallet { BOOST_FIXTURE_TEST_SUITE(wallet_transaction_tests, WalletTestingSetup) BOOST_AUTO_TEST_CASE(roundtrip) { for (uint8_t hash = 0; hash < 5; ++hash) { for (int index = -2; index < 3; ++index) { TxState state = TxStateInterpretSerialized(TxStateUnrecognized{uint256{hash}, index}); BOOST_CHECK_EQUAL(TxStateSerializedBlockHash(state), uint256{hash}); BOOST_CHECK_EQUAL(TxStateSerializedIndex(state), index); } } } BOOST_AUTO_TEST_SUITE_END() } // namespace wallet
31.37037
98
0.726092
wilofice
f5815e86c78f4b08b3a49c393e4218bf434c004e
2,314
cpp
C++
gui/tool-panel.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
10
2016-12-28T22:06:31.000Z
2021-05-24T13:42:30.000Z
gui/tool-panel.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
4
2015-10-09T23:55:10.000Z
2020-04-04T08:09:22.000Z
gui/tool-panel.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
null
null
null
// -*- coding: us-ascii-unix -*- // Copyright 2012 Lukas Kemmer // // 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 "wx/defs.h" // wxEXPAND etc #include "gui/tool-bar.hh" #include "gui/tool-panel.hh" #include "gui/tool-setting-panel.hh" #include "util-wx/fwd-wx.hh" #include "util-wx/layout-wx.hh" namespace faint{ ToolPanel::ToolPanel(wxWindow* parent, StatusInterface& status, Art& art, DialogContext& dialogContext, const StringSource& unitStrings) { m_panel = create_panel(parent); m_toolbar = std::make_unique<Toolbar>(m_panel, status, art); m_toolSettingPanel = std::make_unique<ToolSettingPanel>(m_panel, status, art, dialogContext, unitStrings); const int borderSize = from_DIP(5, m_panel); using namespace layout; set_sizer(m_panel, create_column(OuterSpacing(0), ItemSpacing(0), { {m_toolbar->AsWindow(), Proportion(0), wxEXPAND|wxUP|wxLEFT|wxRIGHT, borderSize}, {m_toolSettingPanel->AsWindow(), Proportion(1), wxEXPAND|wxLEFT|wxRIGHT, borderSize}})); } ToolPanel::~ToolPanel(){ deleted_by_wx(m_panel); } wxWindow* ToolPanel::AsWindow(){ return m_panel; } bool ToolPanel::Visible() const{ return is_shown(m_panel); } void ToolPanel::Show(bool s){ show(m_panel, s); } void ToolPanel::Enable(bool e){ enable(m_panel, e); } void ToolPanel::Hide(){ hide(m_panel); } void ToolPanel::ShowSettings(const Settings& s){ m_toolSettingPanel->ShowSettings(s); } void ToolPanel::SelectTool(ToolId id){ // Fixme: Weird, IIRC, used to put all handling in a FaintWindow // event-handler, and not duplicate button state... m_toolbar->SendToolChoiceEvent(id); } void ToolPanel::SelectLayer(Layer layer){ // Fixme: See SelectTool note m_toolbar->SendLayerChoiceEvent(layer); } } // namespace
24.88172
70
0.715644
lukas-ke
f585e7241f39e3fbbe7260ebabf3270189f1610f
4,627
cpp
C++
libs/log/example/doc/sinks_xml_file.cpp
HelloSunyi/boost_1_54_0
429fea793612f973d4b7a0e69c5af8156ae2b56e
[ "BSL-1.0" ]
7
2015-03-03T15:45:12.000Z
2021-04-25T03:37:17.000Z
libs/log/example/doc/sinks_xml_file.cpp
graehl/boost
37cc4ca77896a86ad10e90dc03e1e825dc0d5492
[ "BSL-1.0" ]
1
2015-09-05T12:23:01.000Z
2015-09-05T12:23:01.000Z
libs/log/example/doc/sinks_xml_file.cpp
graehl/boost
37cc4ca77896a86ad10e90dc03e1e825dc0d5492
[ "BSL-1.0" ]
2
2017-07-28T17:38:16.000Z
2018-04-30T05:37:32.000Z
/* * Copyright Andrey Semashev 2007 - 2013. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ #include <stdexcept> #include <string> #include <iostream> #include <boost/shared_ptr.hpp> #include <boost/lambda/lambda.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/log/common.hpp> #include <boost/log/expressions.hpp> #include <boost/log/attributes.hpp> #include <boost/log/sinks.hpp> #include <boost/log/sources/logger.hpp> namespace logging = boost::log; namespace attrs = boost::log::attributes; namespace src = boost::log::sources; namespace sinks = boost::log::sinks; namespace expr = boost::log::expressions; namespace keywords = boost::log::keywords; typedef sinks::synchronous_sink< sinks::text_file_backend > file_sink; //[ example_sinks_xml_file_collecting void init_file_collecting(boost::shared_ptr< file_sink > sink) { sink->locked_backend()->set_file_collector(sinks::file::make_collector( keywords::target = "logs", /*< the target directory >*/ keywords::max_size = 16 * 1024 * 1024, /*< maximum total size of the stored files, in bytes >*/ keywords::min_free_space = 100 * 1024 * 1024 /*< minimum free space on the drive, in bytes >*/ )); } //] #if 0 //[ example_sinks_xml_file // Complete file sink type typedef sinks::synchronous_sink< sinks::text_file_backend > file_sink; void write_header(sinks::text_file_backend::stream_type& file) { file << "<?xml version=\"1.0\"?>\n<log>\n"; } void write_footer(sinks::text_file_backend::stream_type& file) { file << "</log>\n"; } void init_logging() { // Create a text file sink boost::shared_ptr< file_sink > sink(new file_sink( keywords::file_name = "%Y%m%d_%H%M%S_%5N.xml", /*< the resulting file name pattern >*/ keywords::rotation_size = 16384 /*< rotation size, in characters >*/ )); sink->set_formatter ( expr::format("\t<record id=\"%1%\" timestamp=\"%2%\">%3%</record>") % expr::attr< unsigned int >("RecordID") % expr::attr< boost::posix_time::ptime >("TimeStamp") % expr::xml_decor[ expr::stream << expr::smessage ] /*< the log message has to be decorated, if it contains special characters >*/ ); // Set header and footer writing functors sink->locked_backend()->set_open_handler(&write_header); sink->locked_backend()->set_close_handler(&write_footer); // Add the sink to the core logging::core::get()->add_sink(sink); } //] #endif //[ example_sinks_xml_file_final void init_logging() { // Create a text file sink boost::shared_ptr< file_sink > sink(new file_sink( keywords::file_name = "%Y%m%d_%H%M%S_%5N.xml", keywords::rotation_size = 16384 )); // Set up where the rotated files will be stored init_file_collecting(sink); // Upon restart, scan the directory for files matching the file_name pattern sink->locked_backend()->scan_for_files(); sink->set_formatter ( expr::format("\t<record id=\"%1%\" timestamp=\"%2%\">%3%</record>") % expr::attr< unsigned int >("RecordID") % expr::attr< boost::posix_time::ptime >("TimeStamp") % expr::xml_decor[ expr::stream << expr::smessage ] ); // Set header and footer writing functors namespace bll = boost::lambda; sink->locked_backend()->set_open_handler ( bll::_1 << "<?xml version=\"1.0\"?>\n<log>\n" ); sink->locked_backend()->set_close_handler ( bll::_1 << "</log>\n" ); // Add the sink to the core logging::core::get()->add_sink(sink); } //] enum { LOG_RECORDS_TO_WRITE = 2000 }; int main(int argc, char* argv[]) { try { // Initialize logging library init_logging(); // And also add some attributes logging::core::get()->add_global_attribute("TimeStamp", attrs::local_clock()); logging::core::get()->add_global_attribute("RecordID", attrs::counter< unsigned int >()); // Do some logging src::logger lg; for (unsigned int i = 0; i < LOG_RECORDS_TO_WRITE; ++i) { BOOST_LOG(lg) << "XML log record " << i; } // Test that XML character decoration works BOOST_LOG(lg) << "Special XML characters: &, <, >, '"; return 0; } catch (std::exception& e) { std::cout << "FAILURE: " << e.what() << std::endl; return 1; } }
30.24183
153
0.625027
HelloSunyi
f588fba044454b25731d2a5babd568d573654fda
12,610
cpp
C++
src/perception/segmentation/ground_truth_detections/test/test_ground_truth_detections_node.cpp
ruvus/auto
25ae62d6e575cae40212356eed43ec3e76e9a13e
[ "Apache-2.0" ]
1
2022-02-24T07:36:59.000Z
2022-02-24T07:36:59.000Z
src/perception/segmentation/ground_truth_detections/test/test_ground_truth_detections_node.cpp
ruvus/auto
25ae62d6e575cae40212356eed43ec3e76e9a13e
[ "Apache-2.0" ]
null
null
null
src/perception/segmentation/ground_truth_detections/test/test_ground_truth_detections_node.cpp
ruvus/auto
25ae62d6e575cae40212356eed43ec3e76e9a13e
[ "Apache-2.0" ]
1
2021-12-09T15:44:10.000Z
2021-12-09T15:44:10.000Z
// Copyright 2021 The Autoware Foundation // // 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. // // Co-developed by Tier IV, Inc. and Apex.AI, Inc. #include <ground_truth_detections/ground_truth_detections_node.hpp> #include <geometry_msgs/msg/vector3.hpp> #include <fake_test_node/fake_test_node.hpp> #include <math.h> #include <memory> #include "gtest/gtest.h" namespace { using autoware::ground_truth_detections::GroundTruthDetectionsNode; using autoware_auto_perception_msgs::msg::ClassifiedRoiArray; using autoware_auto_perception_msgs::msg::DetectedObjects; using geometry_msgs::msg::Vector3; using lgsvl_msgs::msg::Detection2DArray; using lgsvl_msgs::msg::Detection2D; using lgsvl_msgs::msg::Detection3DArray; using lgsvl_msgs::msg::Detection3D; using GroundTruth2dDetectionsTest = autoware::tools::testing::FakeTestNode; using GroundTruth3dDetectionsTest = autoware::tools::testing::FakeTestNode; using namespace std::chrono_literals; static constexpr float_t CAR_CENTER_X = 15.3F; static constexpr float_t CAR_CENTER_Y = 17.4F; static constexpr float_t CAR_BBOX_HEIGHT = 5.2F; static constexpr float_t CAR_BBOX_WIDTH = 2.7F; static constexpr double_t CAR_CENTER_3D_X = CAR_CENTER_X; static constexpr double_t CAR_CENTER_3D_Y = CAR_CENTER_Y; static constexpr double_t CAR_CENTER_3D_Z = 9.9F; // unit quaternion representing a rotation of 61.1° around an axis (-0.14, 0.16, 0.98) static constexpr double_t CAR_ORIENTATION_X = -0.0696078; static constexpr double_t CAR_ORIENTATION_Y = 0.0795518; static constexpr double_t CAR_ORIENTATION_Z = 0.497199; static constexpr double_t CAR_ORIENTATION_W = 0.861173; static constexpr float_t CAR_BBOX_3D_HEIGHT = 2.1F; static constexpr float_t CAR_BBOX_3D_LENGTH = 4.8F; static constexpr float_t CAR_BBOX_3D_WIDTH = 2.15F; static constexpr double_t CAR_TWIST_LINEAR_X = 2.0F; static constexpr double_t CAR_TWIST_LINEAR_Y = 2.3F; static constexpr double_t CAR_TWIST_LINEAR_Z = 2.5F; // One detection for each supported label + one detection with unsupported label Detection2DArray make_sample_detections_2d() { Detection2DArray detections; detections.header.stamp.sec = 24; detections.header.stamp.nanosec = 8723U; const auto add_detection = [&detections](const char * label) -> Detection2D & { detections.detections.emplace_back(detections.detections.back()); auto & d = detections.detections.back(); d.label = label; ++d.id; return d; }; { Detection2D d; d.label = "Hatchback"; d.header = detections.header; d.bbox.x = CAR_CENTER_X; d.bbox.y = CAR_CENTER_Y; d.bbox.height = CAR_BBOX_HEIGHT; d.bbox.width = CAR_BBOX_WIDTH; d.id = 0; d.score = 1.0F; d.velocity.linear = geometry_msgs::build<Vector3>() .x(CAR_TWIST_LINEAR_X) .y(CAR_TWIST_LINEAR_Y) .z(CAR_TWIST_LINEAR_Z); detections.detections.emplace_back(d); } add_detection("Jeep"); add_detection("Sedan"); add_detection("SUV"); add_detection("BoxTruck"); // add a position that would give rise to a lower-left corner just outside the allowed // range if half of the width (or height) were subtracted { Detection2D & d = add_detection("Pedestrian"); d.bbox.x = 5.0F; d.bbox.width = 10.00003F; d.bbox.y = 6.0F; d.bbox.height = 12.00002F; } add_detection("Unsupported_label"); return detections; } // cppcheck-suppress syntaxError TEST_F(GroundTruth2dDetectionsTest, ReceiveDetections) { rclcpp::NodeOptions options{}; const auto node = std::make_shared<GroundTruthDetectionsNode>(options); ClassifiedRoiArray::SharedPtr last_received_msg{}; const auto input_topic = "/simulator/ground_truth/detections2D"; const auto output_topic = "/perception/ground_truth_detections_2d"; auto fake_publisher = create_publisher<Detection2DArray>(input_topic, 1s); auto result_subscription = create_subscription<ClassifiedRoiArray>( output_topic, *node, // [&last_received_msg]( const ClassifiedRoiArray::SharedPtr msg) { last_received_msg = msg; }); Detection2DArray input_msg = make_sample_detections_2d(); const auto dt{100ms}; const auto max_wait_time{std::chrono::seconds{1LL}}; auto time_passed{std::chrono::milliseconds{0LL}}; while (!last_received_msg) { fake_publisher->publish(input_msg); rclcpp::spin_some(node); rclcpp::spin_some(get_fake_node()); std::this_thread::sleep_for(dt); time_passed += dt; if (time_passed > max_wait_time) { FAIL() << "Did not receive a message soon enough."; } } ASSERT_TRUE(last_received_msg); ASSERT_EQ(last_received_msg->rois.size(), input_msg.detections.size()); const auto & car_detection = last_received_msg->rois.front(); ASSERT_EQ(car_detection.classifications.size(), 1U); EXPECT_FLOAT_EQ(car_detection.classifications.front().probability, 1.0); EXPECT_EQ( car_detection.classifications.front().classification, autoware_auto_perception_msgs::msg::ObjectClassification::CAR); ASSERT_EQ(car_detection.polygon.points.size(), 4U); { const auto & lower_left = car_detection.polygon.points[0]; EXPECT_FLOAT_EQ(lower_left.x, CAR_CENTER_X - 0.5F * CAR_BBOX_WIDTH); EXPECT_FLOAT_EQ(lower_left.y, CAR_CENTER_Y - 0.5F * CAR_BBOX_HEIGHT); EXPECT_EQ(lower_left.z, 0.0F); const auto & lower_right = car_detection.polygon.points[1]; EXPECT_FLOAT_EQ(lower_right.x, CAR_CENTER_X + 0.5F * CAR_BBOX_WIDTH); EXPECT_FLOAT_EQ(lower_right.y, CAR_CENTER_Y - 0.5F * CAR_BBOX_HEIGHT); EXPECT_EQ(lower_right.z, 0.0F); const auto & upper_right = car_detection.polygon.points[2]; EXPECT_FLOAT_EQ(upper_right.x, CAR_CENTER_X + 0.5F * CAR_BBOX_WIDTH); EXPECT_FLOAT_EQ(upper_right.y, CAR_CENTER_Y + 0.5F * CAR_BBOX_HEIGHT); EXPECT_EQ(upper_right.z, 0.0F); const auto & upper_left = car_detection.polygon.points[3]; EXPECT_FLOAT_EQ(upper_left.x, CAR_CENTER_X - 0.5F * CAR_BBOX_WIDTH); EXPECT_FLOAT_EQ(upper_left.y, CAR_CENTER_Y + 0.5F * CAR_BBOX_HEIGHT); EXPECT_EQ(upper_left.z, 0.0F); } static constexpr size_t N_CARS = 4; for (size_t i = 1U; i < N_CARS; ++i) { const auto & other_car_roi = last_received_msg->rois[i]; EXPECT_EQ(other_car_roi.classifications, car_detection.classifications); EXPECT_EQ(other_car_roi.polygon, car_detection.polygon); } { const auto & truck_roi = last_received_msg->rois[N_CARS]; EXPECT_EQ( truck_roi.classifications.at(0).classification, autoware_auto_perception_msgs::msg::ObjectClassification::TRUCK); EXPECT_EQ(truck_roi.polygon, car_detection.polygon); } const auto & pedestrian_roi = *(last_received_msg->rois.rbegin() + 1); { EXPECT_EQ( pedestrian_roi.classifications.at(0).classification, autoware_auto_perception_msgs::msg::ObjectClassification::PEDESTRIAN); EXPECT_NE(pedestrian_roi.polygon, car_detection.polygon); // check clipping to non-negative values const auto & lower_left = pedestrian_roi.polygon.points.at(0); EXPECT_EQ(lower_left.x, 0.0F); EXPECT_EQ(lower_left.y, 0.0F); } { const auto & unknown_roi = last_received_msg->rois.back(); EXPECT_EQ( unknown_roi.classifications.at(0).classification, autoware_auto_perception_msgs::msg::ObjectClassification::UNKNOWN); EXPECT_EQ(unknown_roi.polygon, pedestrian_roi.polygon); } } Detection3DArray make_sample_detections_3d() { Detection3DArray detections; detections.header.stamp.sec = 24; detections.header.stamp.nanosec = 8723U; { Detection3D d; d.header = detections.header; d.id = 14224; d.label = "Hatchback"; d.score = 1.0F; d.bbox.position.position.x = CAR_CENTER_3D_X; d.bbox.position.position.y = CAR_CENTER_3D_Y; d.bbox.position.position.z = CAR_CENTER_3D_Z; d.bbox.position.orientation.x = CAR_ORIENTATION_X; d.bbox.position.orientation.y = CAR_ORIENTATION_Y; d.bbox.position.orientation.z = CAR_ORIENTATION_Z; d.bbox.position.orientation.w = CAR_ORIENTATION_W; d.bbox.size.x = CAR_BBOX_3D_LENGTH; d.bbox.size.y = CAR_BBOX_3D_WIDTH; d.bbox.size.z = CAR_BBOX_3D_HEIGHT; d.velocity.linear = geometry_msgs::build<Vector3>() .x(CAR_TWIST_LINEAR_X) .y(CAR_TWIST_LINEAR_Y) .z(CAR_TWIST_LINEAR_Z); detections.detections.emplace_back(d); } return detections; } TEST_F(GroundTruth3dDetectionsTest, ReceiveDetections) { rclcpp::NodeOptions options{}; const auto node = std::make_shared<GroundTruthDetectionsNode>(options); DetectedObjects::SharedPtr last_received_msg{}; const auto input_topic = "/simulator/ground_truth/detections3D"; const auto output_topic = "/perception/ground_truth_detections_3d"; auto fake_publisher = create_publisher<Detection3DArray>(input_topic, 1s); auto result_subscription = create_subscription<DetectedObjects>( output_topic, *node, // [&last_received_msg]( const DetectedObjects::SharedPtr msg) { last_received_msg = msg; }); Detection3DArray input_msg = make_sample_detections_3d(); const auto dt{100ms}; const auto max_wait_time{std::chrono::seconds{1LL}}; auto time_passed{std::chrono::milliseconds{0LL}}; while (!last_received_msg) { fake_publisher->publish(input_msg); rclcpp::spin_some(node); rclcpp::spin_some(get_fake_node()); std::this_thread::sleep_for(dt); time_passed += dt; if (time_passed > max_wait_time) { FAIL() << "Did not receive a message soon enough."; } } ASSERT_TRUE(last_received_msg); ASSERT_EQ(last_received_msg->objects.size(), input_msg.detections.size()); const auto & car_detection = last_received_msg->objects.front(); ASSERT_EQ(car_detection.existence_probability, 1.0F); // classification { ASSERT_EQ(car_detection.classification.size(), 1U); EXPECT_FLOAT_EQ(car_detection.classification.front().probability, 1.0); EXPECT_EQ( car_detection.classification.front().classification, autoware_auto_perception_msgs::msg::ObjectClassification::CAR); } // kinematics { const auto & k = car_detection.kinematics; EXPECT_EQ(k.pose_with_covariance.pose.position.x, CAR_CENTER_3D_X); EXPECT_EQ(k.pose_with_covariance.pose.position.y, CAR_CENTER_3D_Y); EXPECT_EQ(k.pose_with_covariance.pose.position.z, CAR_CENTER_3D_Z); EXPECT_FALSE(k.has_position_covariance); ASSERT_EQ( k.orientation_availability, autoware_auto_perception_msgs::msg::DetectedObjectKinematics::AVAILABLE); EXPECT_EQ(k.pose_with_covariance.pose.orientation.x, CAR_ORIENTATION_X); EXPECT_EQ(k.pose_with_covariance.pose.orientation.y, CAR_ORIENTATION_Y); EXPECT_EQ(k.pose_with_covariance.pose.orientation.z, CAR_ORIENTATION_Z); EXPECT_EQ(k.pose_with_covariance.pose.orientation.w, CAR_ORIENTATION_W); } // shape { const auto & s = car_detection.shape; EXPECT_EQ(s.height, CAR_BBOX_3D_HEIGHT); ASSERT_EQ(s.polygon.points.size(), 4UL); // contract: all corners have zero z value for (size_t i = 1; i < 4; ++i) { EXPECT_EQ(s.polygon.points[i].z, 0.0F) << i; } { const auto & rear_left_corner = s.polygon.points[0]; EXPECT_FLOAT_EQ(rear_left_corner.x, -0.5F * CAR_BBOX_3D_LENGTH); EXPECT_FLOAT_EQ(rear_left_corner.y, -0.5F * CAR_BBOX_3D_WIDTH); } { const auto & rear_right_corner = s.polygon.points[1]; EXPECT_FLOAT_EQ(rear_right_corner.x, -0.5F * CAR_BBOX_3D_LENGTH); EXPECT_FLOAT_EQ(rear_right_corner.y, +0.5F * CAR_BBOX_3D_WIDTH); } { const auto & front_right_corner = s.polygon.points[2]; EXPECT_FLOAT_EQ(front_right_corner.x, +0.5F * CAR_BBOX_3D_LENGTH); EXPECT_FLOAT_EQ(front_right_corner.y, +0.5F * CAR_BBOX_3D_WIDTH); } { const auto & front_left_corner = s.polygon.points[3]; EXPECT_FLOAT_EQ(front_left_corner.x, +0.5F * CAR_BBOX_3D_LENGTH); EXPECT_FLOAT_EQ(front_left_corner.y, -0.5F * CAR_BBOX_3D_WIDTH); } } } } // namespace
33.806971
92
0.727201
ruvus
f58b8b8ed78ab4e2e8a07025bb0b54ddc60bd931
1,349
cpp
C++
CO1028/LAB7/Ex4/main.cpp
Smithienious/hcmut-192
4f1dfa322321fc18d151835213a5b544c9d764f2
[ "MIT" ]
null
null
null
CO1028/LAB7/Ex4/main.cpp
Smithienious/hcmut-192
4f1dfa322321fc18d151835213a5b544c9d764f2
[ "MIT" ]
null
null
null
CO1028/LAB7/Ex4/main.cpp
Smithienious/hcmut-192
4f1dfa322321fc18d151835213a5b544c9d764f2
[ "MIT" ]
1
2020-04-26T10:28:41.000Z
2020-04-26T10:28:41.000Z
#include <iostream> #include <fstream> using namespace std; ifstream ifs; struct node { int data; node *next; }; node *createLinkList(int n) { node *head = new node; node *current = head; int dat = 0; for (int i = 0; i < n; i += 1) { ifs >> dat; current->data = dat; if (i != n - 1) { node *next = new node; current->next = next; current = next; } else current->next = nullptr; } return head; } bool isEqual(node *head1, node *head2) { node *current1 = head1, *current2 = head2; int result = 1, num1 = 0, num2 = 0; while (current1 != nullptr) { num1 += 1; current1 = current1->next; } while (current2 != nullptr) { num2 += 1; current2 = current2->next; } if (num1 != num2) result = 0; current1 = head1; current2 = head2; while (result && current1 != nullptr && current2 != nullptr) { if (current1->data != current2->data) result = 0; current1 = current1->next; current2 = current2->next; } return result; } int main(int argc, char **argv) { ifs.open(argv[1]); int n = 0; ifs >> n; if (n <= 0) { cout << "Invalid n" << endl; return 0; } node *head1 = createLinkList(n); int m = 0; ifs >> m; if (m <= 0) { cout << "Invalid m" << endl; return 0; } node *head2 = createLinkList(m); cout << isEqual(head1, head2) << endl; ifs.close(); return 0; }
14.052083
61
0.58043
Smithienious
f58c2231face6a37661e160650d6ee2b4e7ebb5f
7,960
cpp
C++
driver_files/src/Driver/HMDDevice.cpp
justinliang1020/AirPose
e651883f0e9c33fee0d7180d118b2456d54705e4
[ "MIT" ]
28
2021-06-15T21:06:01.000Z
2022-03-31T02:20:25.000Z
driver_files/src/Driver/HMDDevice.cpp
gergelyszaz/AirPose
9ba902b29aeaae6aa0eed4fdb4d7ea63014d546e
[ "MIT" ]
16
2021-10-30T21:24:31.000Z
2021-11-21T15:12:08.000Z
driver_files/src/Driver/HMDDevice.cpp
gergelyszaz/AirPose
9ba902b29aeaae6aa0eed4fdb4d7ea63014d546e
[ "MIT" ]
2
2021-09-10T13:15:15.000Z
2022-01-16T01:51:21.000Z
#include "HMDDevice.hpp" #include <Windows.h> PoseVRDriver::HMDDevice::HMDDevice(std::string serial):serial_(serial) { } std::string PoseVRDriver::HMDDevice::GetSerial() { return this->serial_; } void PoseVRDriver::HMDDevice::Update() { if (this->device_index_ == vr::k_unTrackedDeviceIndexInvalid) return; // Setup pose for this frame auto pose = IVRDevice::MakeDefaultPose(); float delta_seconds = GetDriver()->GetLastFrameTime().count() / 1000.0f; // Get orientation this->rot_y_ += (1.0f * (GetAsyncKeyState(VK_RIGHT) == 0) - 1.0f * (GetAsyncKeyState(VK_LEFT) == 0)) * delta_seconds; this->rot_x_ += (-1.0f * (GetAsyncKeyState(VK_UP) == 0) + 1.0f * (GetAsyncKeyState(VK_DOWN) == 0)) * delta_seconds; this->rot_x_ = std::fmax(this->rot_x_, -3.14159f/2); this->rot_x_ = std::fmin(this->rot_x_, 3.14159f/2); linalg::vec<float, 4> y_quat{ 0, std::sinf(this->rot_y_ / 2), 0, std::cosf(this->rot_y_ / 2) }; linalg::vec<float, 4> x_quat{ std::sinf(this->rot_x_ / 2), 0, 0, std::cosf(this->rot_x_ / 2) }; linalg::vec<float, 4> pose_rot = linalg::qmul(y_quat, x_quat); pose.qRotation.w = (float) pose_rot.w; pose.qRotation.x = (float) pose_rot.x; pose.qRotation.y = (float) pose_rot.y; pose.qRotation.z = (float) pose_rot.z; // Update position based on rotation linalg::vec<float, 3> forward_vec{-1.0f * (GetAsyncKeyState(0x44) == 0) + 1.0f * (GetAsyncKeyState(0x41) == 0), 0, 0}; linalg::vec<float, 3> right_vec{0, 0, 1.0f * (GetAsyncKeyState(0x57) == 0) - 1.0f * (GetAsyncKeyState(0x53) == 0) }; linalg::vec<float, 3> final_dir = forward_vec + right_vec; if (linalg::length(final_dir) > 0.01) { final_dir = linalg::normalize(final_dir) * (float)delta_seconds; final_dir = linalg::qrot(pose_rot, final_dir); this->pos_x_ += final_dir.x; this->pos_y_ += final_dir.y; this->pos_z_ += final_dir.z; } pose.vecPosition[0] = (float) this->pos_x_; pose.vecPosition[1] = (float) this->pos_y_; pose.vecPosition[2] = (float) this->pos_z_; // Post pose GetDriver()->GetDriverHost()->TrackedDevicePoseUpdated(this->device_index_, pose, sizeof(vr::DriverPose_t)); this->last_pose_ = pose; } DeviceType PoseVRDriver::HMDDevice::GetDeviceType() { return DeviceType::HMD; } vr::TrackedDeviceIndex_t PoseVRDriver::HMDDevice::GetDeviceIndex() { return this->device_index_; } vr::EVRInitError PoseVRDriver::HMDDevice::Activate(uint32_t unObjectId) { this->device_index_ = unObjectId; GetDriver()->Log("Activating HMD " + this->serial_); // Load settings values // Could probably make this cleaner with making a wrapper class try { int window_x = std::get<int>(GetDriver()->GetSettingsValue("window_x")); if (window_x > 0) this->window_x_ = window_x; } catch (const std::bad_variant_access&) {}; // Wrong type or doesnt exist try { int window_y = std::get<int>(GetDriver()->GetSettingsValue("window_y")); if (window_y > 0) this->window_x_ = window_y; } catch (const std::bad_variant_access&) {}; // Wrong type or doesnt exist try { int window_width = std::get<int>(GetDriver()->GetSettingsValue("window_width")); if (window_width > 0) this->window_width_ = window_width; } catch (const std::bad_variant_access&) {}; // Wrong type or doesnt exist try { int window_height = std::get<int>(GetDriver()->GetSettingsValue("window_height")); if (window_height > 0) this->window_height_ = window_height; } catch (const std::bad_variant_access&) {}; // Wrong type or doesnt exist // Get the properties handle auto props = GetDriver()->GetProperties()->TrackedDeviceToPropertyContainer(this->device_index_); // Set some universe ID (Must be 2 or higher) GetDriver()->GetProperties()->SetUint64Property(props, vr::Prop_CurrentUniverseId_Uint64, 2); // Set the IPD to be whatever steam has configured GetDriver()->GetProperties()->SetFloatProperty(props, vr::Prop_UserIpdMeters_Float, vr::VRSettings()->GetFloat(vr::k_pch_SteamVR_Section, vr::k_pch_SteamVR_IPD_Float)); // Set the display FPS GetDriver()->GetProperties()->SetFloatProperty(props, vr::Prop_DisplayFrequency_Float, 90.f); // Set up a model "number" (not needed but good to have) GetDriver()->GetProperties()->SetStringProperty(props, vr::Prop_ModelNumber_String, "EXAMPLE_HMD_DEVICE"); // Set up icon paths GetDriver()->GetProperties()->SetStringProperty(props, vr::Prop_NamedIconPathDeviceReady_String, "{example}/icons/hmd_ready.png"); GetDriver()->GetProperties()->SetStringProperty(props, vr::Prop_NamedIconPathDeviceOff_String, "{example}/icons/hmd_not_ready.png"); GetDriver()->GetProperties()->SetStringProperty(props, vr::Prop_NamedIconPathDeviceSearching_String, "{example}/icons/hmd_not_ready.png"); GetDriver()->GetProperties()->SetStringProperty(props, vr::Prop_NamedIconPathDeviceSearchingAlert_String, "{example}/icons/hmd_not_ready.png"); GetDriver()->GetProperties()->SetStringProperty(props, vr::Prop_NamedIconPathDeviceReadyAlert_String, "{example}/icons/hmd_not_ready.png"); GetDriver()->GetProperties()->SetStringProperty(props, vr::Prop_NamedIconPathDeviceNotReady_String, "{example}/icons/hmd_not_ready.png"); GetDriver()->GetProperties()->SetStringProperty(props, vr::Prop_NamedIconPathDeviceStandby_String, "{example}/icons/hmd_not_ready.png"); GetDriver()->GetProperties()->SetStringProperty(props, vr::Prop_NamedIconPathDeviceAlertLow_String, "{example}/icons/hmd_not_ready.png"); return vr::EVRInitError::VRInitError_None; } void PoseVRDriver::HMDDevice::Deactivate() { this->device_index_ = vr::k_unTrackedDeviceIndexInvalid; } void PoseVRDriver::HMDDevice::EnterStandby() { } void* PoseVRDriver::HMDDevice::GetComponent(const char* pchComponentNameAndVersion) { if (!_stricmp(pchComponentNameAndVersion, vr::IVRDisplayComponent_Version)) { return static_cast<vr::IVRDisplayComponent*>(this); } return nullptr; } void PoseVRDriver::HMDDevice::DebugRequest(const char* pchRequest, char* pchResponseBuffer, uint32_t unResponseBufferSize) { if (unResponseBufferSize >= 1) pchResponseBuffer[0] = 0; } vr::DriverPose_t PoseVRDriver::HMDDevice::GetPose() { return this->last_pose_; } void PoseVRDriver::HMDDevice::GetWindowBounds(int32_t* pnX, int32_t* pnY, uint32_t* pnWidth, uint32_t* pnHeight) { *pnX = this->window_x_; *pnY = this->window_y_; *pnWidth = this->window_width_; *pnHeight = this->window_height_; } bool PoseVRDriver::HMDDevice::IsDisplayOnDesktop() { return true; } bool PoseVRDriver::HMDDevice::IsDisplayRealDisplay() { return false; } void PoseVRDriver::HMDDevice::GetRecommendedRenderTargetSize(uint32_t* pnWidth, uint32_t* pnHeight) { *pnWidth = this->window_width_; *pnHeight = this->window_height_; } void PoseVRDriver::HMDDevice::GetEyeOutputViewport(vr::EVREye eEye, uint32_t* pnX, uint32_t* pnY, uint32_t* pnWidth, uint32_t* pnHeight) { *pnY = 0; *pnWidth = this->window_width_ / 2; *pnHeight = this->window_height_; if (eEye == vr::EVREye::Eye_Left) { *pnX = 0; } else { *pnX = this->window_width_ / 2; } } void PoseVRDriver::HMDDevice::GetProjectionRaw(vr::EVREye eEye, float* pfLeft, float* pfRight, float* pfTop, float* pfBottom) { *pfLeft = -1; *pfRight = 1; *pfTop = -1; *pfBottom = 1; } vr::DistortionCoordinates_t PoseVRDriver::HMDDevice::ComputeDistortion(vr::EVREye eEye, float fU, float fV) { vr::DistortionCoordinates_t coordinates; coordinates.rfBlue[0] = fU; coordinates.rfBlue[1] = fV; coordinates.rfGreen[0] = fU; coordinates.rfGreen[1] = fV; coordinates.rfRed[0] = fU; coordinates.rfRed[1] = fV; return coordinates; }
35.695067
172
0.690955
justinliang1020
f592a71e54548674f08d1c1ba8cdc6b11b68d3e6
28,338
hpp
C++
include/seqan3/alphabet/composite/alphabet_variant.hpp
anbratu/seqan3
8cbfe77a996572065b57c3fe67094cc56a2c43da
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
include/seqan3/alphabet/composite/alphabet_variant.hpp
anbratu/seqan3
8cbfe77a996572065b57c3fe67094cc56a2c43da
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
include/seqan3/alphabet/composite/alphabet_variant.hpp
anbratu/seqan3
8cbfe77a996572065b57c3fe67094cc56a2c43da
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2019, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2019, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- /*!\file * \author Marcel Ehrhardt <marcel.ehrhardt AT fu-berlin.de> * \author David Heller <david.heller AT fu-berlin.de> * \brief Provides seqan3::alphabet_variant. */ #pragma once #include <algorithm> #include <array> #include <utility> #include <cassert> #include <variant> #include <meta/meta.hpp> #include <seqan3/alphabet/concept.hpp> #include <seqan3/alphabet/composite/detail.hpp> #include <seqan3/alphabet/alphabet_base.hpp> #include <seqan3/core/concept/core_language.hpp> #include <seqan3/core/detail/int_types.hpp> #include <seqan3/core/type_traits/pack.hpp> #include <seqan3/core/type_traits/range.hpp> #include <seqan3/core/type_traits/transformation_trait_or.hpp> #include <seqan3/core/tuple_utility.hpp> #include <seqan3/std/concepts> #include <seqan3/std/type_traits> namespace seqan3::detail { /*!\brief Evaluates to true if the one of the alternatives of the seqan3::alphabet_variant satisifes a compile-time * predicate. * \tparam variant_t A specialisation of seqan3::alphabet_variant. * \tparam fun_t A template template that takes target_t as argument and exposes an `invoke` member type that * evaluates some predicate and returns `std::true_type` or `std::false_type`. * \tparam target_t The type you wish query. * \ingroup composite * * \details * * To prevent recursive template and/or concept instantiation this call needs to be guarded against many exceptions. * See the source file for more details. */ // default is false template <typename variant_t, template <typename> typename fun_t, typename target_t> inline bool constexpr one_alternative_is = false; //!\cond // actual implementation template <typename ...alternatives, template <typename> typename fun_t, typename target_t> inline bool constexpr one_alternative_is<alphabet_variant<alternatives...>, fun_t, target_t> = !meta::empty<meta::find_if<meta::list<alternatives...>, fun_t<target_t>>>::value; // guard against self template <typename ...alternatives, template <typename> typename fun_t> inline bool constexpr one_alternative_is<alphabet_variant<alternatives...>, fun_t, alphabet_variant<alternatives...>> = false; // guard against types convertible to self without needing self's constructors template <typename ...alternatives, template <typename> typename fun_t, typename target_t> requires convertible_to_by_member<target_t, alphabet_variant<alternatives...>> inline bool constexpr one_alternative_is<alphabet_variant<alternatives...>, fun_t, target_t> = false; // guard against tuple composites that contain the variant somewhere (they can implicitly convert at source) template <typename ...alternatives, template <typename> typename fun_t, typename target_t> requires alphabet_tuple_base_specialisation<target_t> && meta::in<detail::transformation_trait_or_t<recursive_tuple_components<target_t>, meta::list<>>, alphabet_variant<alternatives...>>::value inline bool constexpr one_alternative_is<alphabet_variant<alternatives...>, fun_t, target_t> = false; // guard against alternatives template <typename ...alternatives, template <typename> typename fun_t, typename target_t> requires type_in_pack_v<target_t, alternatives...> inline bool constexpr one_alternative_is<alphabet_variant<alternatives...>, fun_t, target_t> = false; // guard against alternatives (LHS and RHS switched) template <typename ...alternatives, template <typename> typename fun_t, typename target_t> requires type_in_pack_v<target_t, alternatives...> inline bool constexpr one_alternative_is<target_t, fun_t, alphabet_variant<alternatives...>> = false; // guard against ranges and iterators over self to prevent recursive instantiation template <typename ...alternatives, template <typename> typename fun_t, typename target_t> //NO, it's not possible to use the value_type type trait here requires requires { std::same_as<typename target_t::value_type, alphabet_variant<alternatives...>>; } inline bool constexpr one_alternative_is<alphabet_variant<alternatives...>, fun_t, target_t> = false; // guard against pairs/tuples that *might* contain self to prevent recursive instantiation // (applying tuple_like unfortunately does not work because it itself starts recursive instantiation) template <typename ...alternatives, template <typename> typename fun_t, typename target_t> requires tuple_size<target_t> && !alphabet_tuple_base_specialisation<target_t> inline bool constexpr one_alternative_is<alphabet_variant<alternatives...>, fun_t, target_t> = false; //!\endcond } // namespace seqan3::detail namespace seqan3 { /*!\brief A combined alphabet that can hold values of either of its alternatives. * \ingroup composite * \if DEV * \tparam ...alternative_types Types of possible values (at least 2); all must model * seqan3::detail::writable_constexpr_alphabet, not be references and be unique. * \implements seqan3::detail::writable_constexpr_alphabet * \else * \tparam ...alternative_types Types of possible values (at least 2); all must model seqan3::writable_alphabet, * must not be references and must be unique; all required functions for * seqan3::writable_alphabet need to be callable in a `constexpr`-context. * \endif * \implements seqan3::writable_alphabet * \implements seqan3::trivially_copyable * \implements seqan3::standard_layout * \details * * The alphabet_variant represents the union of two or more alternative alphabets (e.g. the * four letter DNA alternative + the gap alternative). It behaves similar to a * [variant](https://en.cppreference.com/w/cpp/language/variant) or std::variant, but it preserves the * seqan3::alphabet. * * Short description: * * combines multiple different alphabets in an "either-or"-fashion; * * is itself a seqan3::alphabet; * * its alphabet size is the sum of the individual sizes; * * default initialises to the the first alternative's default (no empty state like std::variant); * * constructible, assignable and (in-)equality-comparable with each alternative type and also all types that * these are constructible/assignable/equality-comparable with; * * only convertible to its alternatives through the member function convert_to() (which can throw!) * * ### Example * * \include test/snippet/alphabet/composite/alphabet_variant.cpp * * ### The `char` representation of an alphabet_variant * * Part of the seqan3::alphabet concept requires that the alphabet_variant provides a char representation in addition * to the rank representation. For an object of seqan3::alphabet_variant, the `to_char()` member function will always * return the same character as if invoked on the respective alternative. * In contrast, the `assign_char()` member function might be ambiguous between the alternative alphabets in a variant. * * For example, assigning a '!' to seqan3::dna15 resolves to an object of rank 8 with char representation 'N' while * assigning '!' to seqan3::gap always resolves to rank 0, the gap symbol itself ('-'_gap). * We tackle this ambiguousness by **defaulting unknown characters to the representation of the first alternative** * (e.g. `alphabet_variant<dna15, gap>{}.assign_char('!')` resolves to rank 8, representing `N`_dna15). * * On the other hand, two alternative alphabets might have the same char representation (e.g if * you combine dna4 with dna5, 'A', 'C', 'G' and 'T' are ambiguous). * We tackle this ambiguousness by **always choosing the first valid char representation** (e.g. * `alphabet_variant<dna4, dna5>{}.assign_char('A')` resolves to rank 0, representing an `A`_dna4). * * To explicitly assign via the character representation of a specific alphabet, * assign to that type first and then assign to the variant, e.g. * * \include test/snippet/alphabet/composite/alphabet_variant_char_representation.cpp */ template <typename ...alternative_types> //!\cond requires (detail::writable_constexpr_alphabet<alternative_types> && ...) && (!std::is_reference_v<alternative_types> && ...) && (sizeof...(alternative_types) >= 2) //TODO same char_type //!\endcond class alphabet_variant : public alphabet_base<alphabet_variant<alternative_types...>, (static_cast<size_t>(alphabet_size<alternative_types>) + ...), char> //TODO underlying char t { private: //!\brief The base type. using base_t = alphabet_base<alphabet_variant<alternative_types...>, (static_cast<size_t>(alphabet_size<alternative_types>) + ...), char>; //!\brief Befriend the base type. friend base_t; //!\brief A meta::list of the types of each alternative in the composite using alternatives = meta::list<alternative_types...>; static_assert(std::same_as<alternatives, meta::unique<alternatives>>, "All types in a alphabet_variant must be distinct."); using typename base_t::char_type; using typename base_t::rank_type; public: using base_t::alphabet_size; using base_t::to_char; using base_t::to_rank; using base_t::assign_rank; /*!\brief Returns true if alternative_t is one of the given alternative types. * \tparam alternative_t The type to check. * * \include test/snippet/alphabet/composite/alphabet_variant_holds_alternative.cpp */ template <typename alternative_t> static constexpr bool holds_alternative() noexcept { return detail::type_in_pack_v<alternative_t, alternative_types...>; } /*!\name Constructors, destructor and assignment * \{ */ constexpr alphabet_variant() noexcept = default; //!< Defaulted. constexpr alphabet_variant(alphabet_variant const &) noexcept = default; //!< Defaulted. constexpr alphabet_variant(alphabet_variant &&) noexcept = default; //!< Defaulted. constexpr alphabet_variant & operator=(alphabet_variant const &) noexcept = default; //!< Defaulted. constexpr alphabet_variant & operator=(alphabet_variant &&) noexcept = default; //!< Defaulted. ~alphabet_variant() noexcept = default; //!< Defaulted. /*!\brief Construction via the value of an alternative. * \tparam alternative_t One of the alternative types. * \param alternative The value of a alternative that should be assigned. * * \include test/snippet/alphabet/composite/alphabet_variant_value_construction.cpp */ template <typename alternative_t> //!\cond requires holds_alternative<alternative_t>() //!\endcond constexpr alphabet_variant(alternative_t const & alternative) noexcept { assign_rank(rank_by_type_(alternative)); } /*!\brief Construction via the value of a type that an alternative type is constructible from. * \tparam indirect_alternative_t A type that one of the alternative types is constructible from. * \param rhs The value that should be assigned. * * \include test/snippet/alphabet/composite/alphabet_variant_conversion.cpp * \attention When selecting the alternative alphabet types which require only implicit conversion * or constructor calls, are preferred over those that require explicit ones. */ template <typename indirect_alternative_t> //!\cond requires !detail::one_alternative_is<alphabet_variant, detail::implicitly_convertible_from, indirect_alternative_t> && detail::one_alternative_is<alphabet_variant, detail::constructible_from, indirect_alternative_t> //!\endcond constexpr alphabet_variant(indirect_alternative_t const & rhs) noexcept { assign_rank(rank_by_type_(meta::front<meta::find_if<alternatives, detail::constructible_from<indirect_alternative_t>>>(rhs))); } //!\cond template <typename indirect_alternative_t> requires detail::one_alternative_is<alphabet_variant, detail::implicitly_convertible_from, indirect_alternative_t> constexpr alphabet_variant(indirect_alternative_t const & rhs) noexcept { assign_rank( rank_by_type_( meta::front<meta::find_if<alternatives, detail::implicitly_convertible_from<indirect_alternative_t>>>(rhs))); } //!\endcond /*!\brief Assignment via a value that one of the alternative types is assignable from. * \tparam indirect_alternative_t A type that one of the alternatives is assignable from. * \param rhs The value of an alternative. * * \include test/snippet/alphabet/composite/alphabet_variant_subtype_construction.cpp */ template <typename indirect_alternative_t> //!\cond requires !detail::one_alternative_is<alphabet_variant, detail::implicitly_convertible_from, indirect_alternative_t> && // constructor takes care !detail::one_alternative_is<alphabet_variant, detail::constructible_from, indirect_alternative_t> && // constructor takes care detail::one_alternative_is<alphabet_variant, detail::assignable_from, indirect_alternative_t> //!\endcond constexpr alphabet_variant & operator=(indirect_alternative_t const & rhs) noexcept { using alternative_t = meta::front<meta::find_if<alternatives, detail::assignable_from<indirect_alternative_t>>>; alternative_t alternative{}; alternative = rhs; assign_rank(rank_by_type_(alternative)); return *this; } //!\} /*!\name Conversion (by index) * \{ */ //!\brief Whether the variant alphabet currently holds a value of the given alternative. //!\tparam index Index of the alternative to check for. template <size_t index> constexpr bool is_alternative() const noexcept { static_assert(index < alphabet_size, "The alphabet_variant contains less alternatives than you are checking."); return (to_rank() >= partial_sum_sizes[index]) && (to_rank() < partial_sum_sizes[index + 1]); } /*!\brief Convert to the specified alphabet (throws if is_alternative() would be false). * \tparam index Index of the alternative to check for. * \throws std::bad_variant_access If the variant_alphabet currently holds the value of a different alternative. */ template <size_t index> constexpr auto convert_to() const { return convert_impl<index, true>(); } /*!\brief Convert to the specified alphabet (**undefined behaviour** if is_alternative() would be false). * \tparam index Index of the alternative to check for. */ template <size_t index> constexpr auto convert_unsafely_to() const noexcept { return convert_impl<index, false>(); } //!\} /*!\name Conversion (by type) * \{ */ /*!\copybrief is_alternative() * \tparam alternative_t The type of the alternative that you wish to check for. */ template <typename alternative_t> constexpr bool is_alternative() const noexcept //!\cond requires holds_alternative<alternative_t>() //!\endcond { constexpr size_t index = meta::find_index<alternatives, alternative_t>::value; return is_alternative<index>(); } /*!\copybrief convert_to() * \tparam alternative_t The type of the alternative that you wish to check for. * \throws std::bad_variant_access If the variant_alphabet currently holds the value of a different alternative. */ template <typename alternative_t> constexpr alternative_t convert_to() const //!\cond requires holds_alternative<alternative_t>() //!\endcond { constexpr size_t index = meta::find_index<alternatives, alternative_t>::value; return convert_impl<index, true>(); } /*!\copybrief convert_unsafely_to() * \tparam alternative_t The type of the alternative that you wish to check for. */ template <typename alternative_t> constexpr alternative_t convert_unsafely_to() const noexcept //!\cond requires holds_alternative<alternative_t>() //!\endcond { constexpr size_t index = meta::find_index<alternatives, alternative_t>::value; return convert_impl<index, false>(); } //!\} /*!\name Comparison operators (against alternatives) * \brief Defines comparison against alternatives, e.g. `alphabet_variant<dna5, gap>{gap{}} == 'C'_dna5`. Only * (in-)equality comparison is explicitly defined, because it would be difficult to argue about e.g. * `alphabet_variant<dna5, gap>{gap{}} < 'C'_dna5`. * \{ */ //!\brief Checks for equality. template <typename alternative_t> constexpr bool operator==(alternative_t const rhs) const noexcept //!\cond requires holds_alternative<alternative_t>() //!\endcond { return is_alternative<alternative_t>() && (convert_unsafely_to<alternative_t>() == rhs); } //!\brief Checks for inequality. template <typename alternative_t> constexpr bool operator!=(alternative_t const rhs) const noexcept //!\cond requires holds_alternative<alternative_t>() //!\endcond { return !operator==(rhs); } //!\} /*!\name Comparison operators (against indirect alternatives) * \brief Defines comparison against types that are comparable with alternatives, e.g. * `alphabet_variant<dna5, gap>{'C'_dna5} == 'C'_rna5`. Only (in-)equality comparison is explicitly defined, * because it would be difficult to argue about e.g. * `alphabet_variant<dna5, gap>{gap{}} < 'C'_rna5`. * \{ */ //!\brief Checks for equality. template <typename indirect_alternative_type> constexpr bool operator==(indirect_alternative_type const rhs) const noexcept //!\cond requires detail::one_alternative_is<alphabet_variant, detail::weakly_equality_comparable_with_, indirect_alternative_type> //!\endcond { using alternative_t = meta::front<meta::find_if<alternatives, detail::weakly_equality_comparable_with_<indirect_alternative_type>>>; return is_alternative<alternative_t>() && (convert_unsafely_to<alternative_t>() == rhs); } //!\brief Checks for inequality. template <typename indirect_alternative_type> constexpr bool operator!=(indirect_alternative_type const rhs) const noexcept //!\cond requires detail::one_alternative_is<alphabet_variant, detail::weakly_equality_comparable_with_, indirect_alternative_type> //!\endcond { return !operator==(rhs); } //!\} protected: //!\privatesection /*!\brief Implementation function for convert_to() and convert_unsafely_to(). * \tparam index Index of the alternative to convert to. * \tparam throws Whether to perform checks (and throw) or not. */ template <size_t index, bool throws> constexpr auto convert_impl() const noexcept(!throws) -> meta::at_c<alternatives, index> { static_assert(index < alphabet_size, "The alphabet_variant contains less alternatives than you are checking."); using alternative_t = meta::at_c<alternatives, index>; if constexpr (throws) { if (!is_alternative<index>()) // [[unlikely]] { throw std::bad_variant_access{}; } } return seqan3::assign_rank_to(to_rank() - partial_sum_sizes[index], alternative_t{}); } /*!\brief Compile-time generated lookup table which contains the partial * sum up to the position of each alternative. * * An array which contains the prefix sum over all * alternative_types::alphabet_size's. * */ static constexpr std::array partial_sum_sizes = []() constexpr { constexpr size_t N = sizeof...(alternative_types) + 1; std::array<rank_type, N> partial_sum{0, seqan3::alphabet_size<alternative_types>...}; for (size_t i = 1u; i < N; ++i) partial_sum[i] += partial_sum[i-1]; return partial_sum; }(); /*!\brief Compile-time generated lookup table which maps the rank to char. * * A map generated at compile time where the key is the rank of the variant * of all alternatives and the value is the corresponding char of that rank * and alternative. * */ static constexpr std::array<char_type, alphabet_size> rank_to_char = []() constexpr { // Explicitly writing assign_rank_to_char within assign_rank_to_char // causes this bug (g++-7 and g++-8): // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=84684 auto assign_rank_to_char = [](auto alternative, size_t rank) constexpr { return seqan3::to_char(seqan3::assign_rank_to(rank, alternative)); }; auto assign_value_to_char = [assign_rank_to_char] (auto alternative, auto & value_to_char, auto & value) constexpr { using alternative_t = std::decay_t<decltype(alternative)>; for (size_t i = 0u; i < seqan3::alphabet_size<alternative_t>; ++i, ++value) value_to_char[value] = assign_rank_to_char(alternative, i); }; unsigned value = 0u; std::array<char_type, alphabet_size> value_to_char{}; // initializer lists guarantee sequencing; // the following expression behaves as: // for(auto alternative: alternative_types) // assign_rank_to_char(alternative, rank_to_char, value); ((assign_value_to_char(alternative_types{}, value_to_char, value)),...); return value_to_char; }(); //!\brief Converts an object of one of the given alternatives into the internal representation. //!\tparam index The position of `alternative_t` in the template pack `alternative_types`. //!\tparam alternative_t One of the alternative types. //!\param alternative The value of a alternative. template <size_t index, typename alternative_t> //!\cond requires holds_alternative<alternative_t>() //!\endcond static constexpr rank_type rank_by_index_(alternative_t const & alternative) noexcept { return partial_sum_sizes[index] + static_cast<rank_type>(seqan3::to_rank(alternative)); } //!\brief Converts an object of one of the given alternatives into the internal representation. //!\details Finds the index of alternative_t in the given types. //!\tparam alternative_t One of the alternative types. //!\param alternative The value of a alternative. template <typename alternative_t> //!\cond requires holds_alternative<alternative_t>() //!\endcond static constexpr rank_type rank_by_type_(alternative_t const & alternative) noexcept { constexpr size_t index = meta::find_index<alternatives, alternative_t>::value; return rank_by_index_<index>(alternative); } /*!\brief Compile-time generated lookup table which maps the char to rank. * * An map generated at compile time where the key is the char of one of the * alternatives and the value is the corresponding rank over all alternatives (by * conflict will default to the first). * */ static constexpr std::array char_to_rank = []() constexpr { constexpr size_t table_size = 1 << (sizeof(char_type) * 8); std::array<rank_type, table_size> char_to_rank{}; for (size_t i = 0u; i < table_size; ++i) { char_type chr = static_cast<char_type>(i); bool there_was_no_valid_representation{true}; meta::for_each(alternatives{}, [&] (auto && alt) { using alt_type = remove_cvref_t<decltype(alt)>; if (there_was_no_valid_representation && char_is_valid_for<alt_type>(chr)) { there_was_no_valid_representation = false; char_to_rank[i] = rank_by_type_(assign_char_to(chr, alt_type{})); } }); if (there_was_no_valid_representation) char_to_rank[i] = rank_by_type_(assign_char_to(chr, meta::front<alternatives>{})); } return char_to_rank; }(); //!\brief Validate whether a character is valid in the by any of the combined alphabet. static constexpr bool char_is_valid(char_type const chr) noexcept { bool is_valid{false}; meta::for_each(alternatives{}, [&] (auto && alt) { if (char_is_valid_for<remove_cvref_t<decltype(alt)>>(chr)) is_valid = true; }); return is_valid; } }; /*!\name Comparison operators * \relates alphabet_variant * \brief Free function (in-)equality comparison operators that forward to member operators (for types != self). *\{ */ //!\brief Checks for equality. template <typename lhs_t, typename ...alternative_types> constexpr bool operator==(lhs_t const lhs, alphabet_variant<alternative_types...> const rhs) noexcept //!\cond requires detail::weakly_equality_comparable_by_members_with<alphabet_variant<alternative_types...>, lhs_t> && !detail::weakly_equality_comparable_by_members_with<lhs_t, alphabet_variant<alternative_types...>> //!\endcond { return rhs == lhs; } //!\brief Checks for inequality. template <typename lhs_t, typename ...alternative_types> constexpr bool operator!=(lhs_t const lhs, alphabet_variant<alternative_types...> const rhs) noexcept //!\cond requires detail::weakly_equality_comparable_by_members_with<alphabet_variant<alternative_types...>, lhs_t> && !detail::weakly_equality_comparable_by_members_with<lhs_t, alphabet_variant<alternative_types...>> //!\endcond { return rhs != lhs; } //!\} } // namespace seqan3
43.198171
122
0.649058
anbratu
f5933b011ba63be0e9947627c5f263c62da7056f
5,231
cpp
C++
libs/tbb44_20160128oss_win_0/tbb44_20160128oss/examples/parallel_reduce/primes/main.cpp
umetaman/ofxExtremeGpuVideo
0bf28b131dedaf44899c269aef57e95dd700586c
[ "Zlib" ]
59
2016-04-13T20:18:50.000Z
2022-01-24T00:46:16.000Z
libs/tbb44_20160128oss_win_0/tbb44_20160128oss/examples/parallel_reduce/primes/main.cpp
umetaman/ofxExtremeGpuVideo
0bf28b131dedaf44899c269aef57e95dd700586c
[ "Zlib" ]
3
2016-11-19T18:33:49.000Z
2022-01-24T00:43:10.000Z
libs/tbb44_20160128oss_win_0/tbb44_20160128oss/examples/parallel_reduce/primes/main.cpp
umetaman/ofxExtremeGpuVideo
0bf28b131dedaf44899c269aef57e95dd700586c
[ "Zlib" ]
7
2016-05-01T02:58:05.000Z
2021-09-17T02:20:19.000Z
/* Copyright 2005-2016 Intel Corporation. All Rights Reserved. This file is part of Threading Building Blocks. Threading Building Blocks is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. Threading Building Blocks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Threading Building Blocks; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA As a special exception, you may use this file as part of a free software library without restriction. Specifically, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other files to produce an executable, this file does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. */ #include "primes.h" #include <cstdlib> #include <cstdio> #include <cstring> #include <cctype> #include <utility> #include <iostream> #include <sstream> #include "tbb/tick_count.h" #include "../../common/utility/utility.h" struct RunOptions{ //! NumberType of threads to use. utility::thread_number_range threads; //whether to suppress additional output bool silentFlag; // NumberType n; //! Grain size parameter NumberType grainSize; // number of time to repeat calculation NumberType repeatNumber; RunOptions(utility::thread_number_range threads, NumberType grainSize, NumberType n, bool silentFlag, NumberType repeatNumber) : threads(threads), grainSize(grainSize), n(n), silentFlag(silentFlag), repeatNumber(repeatNumber) {} }; int do_get_default_num_threads() { int threads; #if __TBB_MIC_OFFLOAD #pragma offload target(mic) out(threads) #endif // __TBB_MIC_OFFLOAD threads = tbb::task_scheduler_init::default_num_threads(); return threads; } int get_default_num_threads() { static int threads = do_get_default_num_threads(); return threads; } //! Parse the command line. static RunOptions ParseCommandLine( int argc, const char* argv[] ) { utility::thread_number_range threads( get_default_num_threads, 0, get_default_num_threads() ); NumberType grainSize = 1000; bool silent = false; NumberType number = 100000000; NumberType repeatNumber = 1; utility::parse_cli_arguments(argc,argv, utility::cli_argument_pack() //"-h" option for displaying help is present implicitly .positional_arg(threads,"n-of-threads",utility::thread_number_range_desc) .positional_arg(number,"number","upper bound of range to search primes in, must be a positive integer") .positional_arg(grainSize,"grain-size","must be a positive integer") .positional_arg(repeatNumber,"n-of-repeats","repeat the calculation this number of times, must be a positive integer") .arg(silent,"silent","no output except elapsed time") ); RunOptions options(threads,grainSize, number, silent, repeatNumber); return options; } int main( int argc, const char* argv[] ) { tbb::tick_count mainBeginMark = tbb::tick_count::now(); RunOptions options =ParseCommandLine(argc,argv); // Try different numbers of threads for( int p=options.threads.first; p<=options.threads.last; p=options.threads.step(p) ) { for (NumberType i=0; i<options.repeatNumber;++i){ tbb::tick_count iterationBeginMark = tbb::tick_count::now(); NumberType count = 0; NumberType n = options.n; if( p==0 ) { #if __TBB_MIC_OFFLOAD #pragma offload target(mic) in(n) out(count) #endif // __TBB_MIC_OFFLOAD count = SerialCountPrimes(n); } else { NumberType grainSize = options.grainSize; #if __TBB_MIC_OFFLOAD #pragma offload target(mic) in(n, p, grainSize) out(count) #endif // __TBB_MIC_OFFLOAD count = ParallelCountPrimes(n, p, grainSize); } tbb::tick_count iterationEndMark = tbb::tick_count::now(); if (!options.silentFlag){ std::cout <<"#primes from [2.." <<options.n<<"] = " << count <<" ("<<(iterationEndMark-iterationBeginMark).seconds()<< " sec with " ; if( 0 != p ) std::cout<<p<<"-way parallelism"; else std::cout<<"serial code"; std::cout<<")\n" ; } } } utility::report_elapsed_time((tbb::tick_count::now()-mainBeginMark).seconds()); return 0; }
41.848
130
0.66125
umetaman
f5961e8f0d68ed56253795151ded30646697bee3
887
cpp
C++
Source/moja.datarepository/tests/src/landunitinfotests.cpp
YevenLourance/FLINT
e584e39c36d3e898c9293c09bd0768557312e8ea
[ "BSL-1.0" ]
null
null
null
Source/moja.datarepository/tests/src/landunitinfotests.cpp
YevenLourance/FLINT
e584e39c36d3e898c9293c09bd0768557312e8ea
[ "BSL-1.0" ]
null
null
null
Source/moja.datarepository/tests/src/landunitinfotests.cpp
YevenLourance/FLINT
e584e39c36d3e898c9293c09bd0768557312e8ea
[ "BSL-1.0" ]
null
null
null
#include <moja/datarepository/landunitinfo.h> #include <moja/test/mockaspatialtileinfo.h> #include <boost/test/unit_test.hpp> using moja::datarepository::LandUnitInfo; using moja::test::MockAspatialTileInfo; BOOST_AUTO_TEST_SUITE(LandUnitInfoTests); BOOST_AUTO_TEST_CASE(datarepository_LandUnitInfo_ConstructorThrowsExceptionIfIdIsLessThanOne) { MockAspatialTileInfo mockTile; auto badIds = {0, -1, -100}; for (auto id : badIds) { BOOST_CHECK_THROW(LandUnitInfo(mockTile, id, 1.0), std::invalid_argument); } } BOOST_AUTO_TEST_CASE(datarepository_LandUnitInfo_ConstructorThrowsExceptionIfAreaIsZeroOrNegative) { MockAspatialTileInfo mockTile; auto badAreas = {0.0, -0.1, -100.0}; for (auto area : badAreas) { BOOST_CHECK_THROW(LandUnitInfo(mockTile, 1, area), std::invalid_argument); } } BOOST_AUTO_TEST_SUITE_END();
30.586207
101
0.750846
YevenLourance
f59645bf0540bba3ebef773575b6b8a761f92080
12,541
cpp
C++
openstudiocore/src/energyplus/ForwardTranslator/ForwardTranslateCoilCoolingDXTwoSpeed.cpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
openstudiocore/src/energyplus/ForwardTranslator/ForwardTranslateCoilCoolingDXTwoSpeed.cpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
openstudiocore/src/energyplus/ForwardTranslator/ForwardTranslateCoilCoolingDXTwoSpeed.cpp
ORNL-BTRIC/OpenStudio
878f94bebf6f025445d1373e8b2304ececac16d8
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2014, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include <energyplus/ForwardTranslator.hpp> #include <model/Model.hpp> #include <model/Schedule.hpp> #include <model/Schedule_Impl.hpp> #include <model/CoilCoolingDXTwoSpeed.hpp> #include <model/CoilCoolingDXTwoSpeed_Impl.hpp> #include <model/Curve.hpp> #include <model/Curve_Impl.hpp> #include <utilities/core/Logger.hpp> #include <utilities/core/Assert.hpp> #include <utilities/idd/CoilSystem_Cooling_DX_FieldEnums.hxx> #include <utilities/idd/Coil_Cooling_DX_TwoSpeed_FieldEnums.hxx> #include <utilities/idd/IddEnums.hxx> #include <utilities/idd/IddFactory.hxx> using namespace openstudio::model; using namespace std; namespace openstudio { namespace energyplus { boost::optional<IdfObject> ForwardTranslator::translateCoilCoolingDXTwoSpeedWithoutUnitary( model::CoilCoolingDXTwoSpeed & modelObject ) { //setup two boost optionals to use to store get method returns boost::optional<std::string> s; boost::optional<double> d; //create the IdfObject that will be the coil IdfObject idfObject(IddObjectType::Coil_Cooling_DX_TwoSpeed); //Name m_idfObjects.push_back(idfObject); s = modelObject.name(); if( s ) { idfObject.setName(*s); } // A2 , \field Availability Schedule Name Schedule sched = modelObject.getAvailabilitySchedule(); translateAndMapModelObject(sched); idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::AvailabilityScheduleName, sched.name().get() ); // N1 , \field Rated High Speed Total Cooling Capacity d = modelObject.getRatedHighSpeedTotalCoolingCapacity(); if( d ) { idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::HighSpeedGrossRatedTotalCoolingCapacity,*d); } else { idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::HighSpeedGrossRatedTotalCoolingCapacity,"Autosize"); } // N2 , \field Rated High Speed Sensible Heat Ratio d = modelObject.getRatedHighSpeedSensibleHeatRatio(); if( d ) { idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::HighSpeedRatedSensibleHeatRatio,*d); } else { idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::HighSpeedRatedSensibleHeatRatio,"Autosize"); } // N3 , \field Rated High Speed COP d = modelObject.getRatedHighSpeedCOP(); if( d ) { idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::HighSpeedGrossRatedCoolingCOP,*d); } // N4 , \field Rated High Speed Air Flow Rate d = modelObject.getRatedHighSpeedAirFlowRate(); if( d ) { idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::HighSpeedRatedAirFlowRate,*d); } else { idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::HighSpeedRatedAirFlowRate,"Autosize"); } //A3 , \field Air Inlet Node Name OptionalModelObject omo = modelObject.inletModelObject(); if( omo ) { translateAndMapModelObject(*omo); s = omo->name(); if(s) { idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::AirInletNodeName,*s ); } } //A4 , \field Air Outlet Node Name omo= modelObject.outletModelObject(); if( omo ) { translateAndMapModelObject(*omo); s = omo->name(); if(s) { idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::AirOutletNodeName,*s); } } // A5 , \field Total Cooling Capacity Function of Temperature Curve Name Curve cb = modelObject.getTotalCoolingCapacityFunctionOfTemperatureCurve(); translateAndMapModelObject(cb); idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::TotalCoolingCapacityFunctionofTemperatureCurveName, cb.name().get()); // A6 , \field Total Cooling Capacity Function of Flow Fraction Curve Name cb = modelObject.getTotalCoolingCapacityFunctionOfFlowFractionCurve(); translateAndMapModelObject(cb); idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::TotalCoolingCapacityFunctionofFlowFractionCurveName, cb.name().get()); // A7 , \field Energy Input Ratio Function of Temperature Curve Name cb =modelObject.getEnergyInputRatioFunctionOfTemperatureCurve(); translateAndMapModelObject(cb); idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::EnergyInputRatioFunctionofTemperatureCurveName, cb.name().get()); // A8 , \field Energy Input Ratio Function of Flow Fraction Curve Name Curve cq = modelObject.getEnergyInputRatioFunctionOfFlowFractionCurve(); translateAndMapModelObject(cq); idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::EnergyInputRatioFunctionofFlowFractionCurveName, cq.name().get()); // A9 , \field Part Load Fraction Correlation Curve Name cq = modelObject.getPartLoadFractionCorrelationCurve(); translateAndMapModelObject(cq); idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::PartLoadFractionCorrelationCurveName, cq.name().get()); // N5 , \field Rated Low Speed Total Cooling Capacity d = modelObject.getRatedLowSpeedTotalCoolingCapacity(); if( d ) { idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::LowSpeedGrossRatedTotalCoolingCapacity,*d); } else { idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::LowSpeedGrossRatedTotalCoolingCapacity,"Autosize"); } // N6 , \field Rated Low Speed Sensible Heat Ratio d = modelObject.getRatedLowSpeedSensibleHeatRatio(); if( d ) { idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::LowSpeedGrossRatedSensibleHeatRatio,*d); } else { idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::LowSpeedGrossRatedSensibleHeatRatio,"Autosize"); } // N7 , \field Rated Low Speed COP d = modelObject.getRatedLowSpeedCOP(); if( d ) { idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::LowSpeedGrossRatedCoolingCOP,*d); } // N8 , \field Rated Low Speed Air Flow Rate d = modelObject.getRatedLowSpeedAirFlowRate(); if( d ) { idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::LowSpeedRatedAirFlowRate,*d); } else { idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::LowSpeedRatedAirFlowRate,"Autosize"); } // A10, \field Low Speed Total Cooling Capacity Function of Temperature Curve Name cq = modelObject.getLowSpeedTotalCoolingCapacityFunctionOfTemperatureCurve(); translateAndMapModelObject(cq); idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::LowSpeedTotalCoolingCapacityFunctionofTemperatureCurveName, cq.name().get()); // A11, \field Low Speed Energy Input Ratio Function of Temperature Curve Name cq = modelObject.getLowSpeedEnergyInputRatioFunctionOfTemperatureCurve(); translateAndMapModelObject(cq); idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::LowSpeedEnergyInputRatioFunctionofTemperatureCurveName, cq.name().get()); // A12, \field Condenser Air Inlet Node Name s=modelObject.getCondenserAirInletNodeName(); if(s) { idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::CondenserAirInletNodeName,*s); } // A13, \field Condenser Type idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::CondenserType,modelObject.getCondenserType()); // N9, \field High Speed Evaporative Condenser Effectiveness d=modelObject.getHighSpeedEvaporativeCondenserEffectiveness(); if(d) { idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::HighSpeedEvaporativeCondenserEffectiveness,*d); } // N10, \field High Speed Evaporative Condenser Air Flow Rate d=modelObject.getHighSpeedEvaporativeCondenserAirFlowRate(); if(d) { idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::HighSpeedEvaporativeCondenserAirFlowRate,*d); } // N11, \field High Speed Evaporative Condenser Pump Rated Power Consumption d=modelObject.getHighSpeedEvaporativeCondenserPumpRatedPowerConsumption(); if(d) { idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::HighSpeedEvaporativeCondenserPumpRatedPowerConsumption,*d); } // N12, \field Low Speed Evaporative Condenser Effectiveness d=modelObject.getLowSpeedEvaporativeCondenserEffectiveness(); if(d) { idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::LowSpeedEvaporativeCondenserEffectiveness,*d); } // N13, \field Low Speed Evaporative Condenser Air Flow Rate d=modelObject.getLowSpeedEvaporativeCondenserAirFlowRate(); if(d) { idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::LowSpeedEvaporativeCondenserAirFlowRate,*d); } // N14, \field Low Speed Evaporative Condenser Pump Rated Power Consumption d=modelObject.getLowSpeedEvaporativeCondenserPumpRatedPowerConsumption(); if(d) { idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::LowSpeedEvaporativeCondenserPumpRatedPowerConsumption,*d); } //TODO // A14, \field Supply Water Storage Tank Name //getSupplyWaterStorageTankName //TODO // A15, \field Condensate Collection Water Storage Tank Name //getCondensateCollectionWaterStorageTankName // N15, \field Basin Heater Capacity d=modelObject.getBasinHeaterCapacity(); if(d) { idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::BasinHeaterCapacity,*d); } // N16, \field Basin Heater Setpoint Temperature d=modelObject.getBasinHeaterSetpointTemperature(); if(d) { idfObject.setDouble(Coil_Cooling_DX_TwoSpeedFields::BasinHeaterSetpointTemperature,*d); } // A16; \field Basin Heater Operating Schedule Name OptionalSchedule os = modelObject.getBasinHeaterOperatingSchedule(); if( os ) { translateAndMapModelObject(*os); idfObject.setString(Coil_Cooling_DX_TwoSpeedFields::BasinHeaterOperatingScheduleName, os->name().get() ); } return idfObject; } boost::optional<IdfObject> ForwardTranslator::translateCoilCoolingDXTwoSpeed( CoilCoolingDXTwoSpeed& modelObject ) { IdfObject coilSystemCoolingDXIdf(IddObjectType::CoilSystem_Cooling_DX); m_idfObjects.push_back(coilSystemCoolingDXIdf); boost::optional<IdfObject> oIdfObject = translateCoilCoolingDXTwoSpeedWithoutUnitary(modelObject); if( ! oIdfObject ) { return boost::none; } IdfObject idfObject = oIdfObject.get(); OptionalString s; s = modelObject.name(); if( s ) { coilSystemCoolingDXIdf.setString(CoilSystem_Cooling_DXFields::CoolingCoilObjectType,idfObject.iddObject().name()); coilSystemCoolingDXIdf.setString(CoilSystem_Cooling_DXFields::CoolingCoilName,*s); coilSystemCoolingDXIdf.setName(*s + " CoilSystem"); } Schedule sched = modelObject.getAvailabilitySchedule(); translateAndMapModelObject(sched); coilSystemCoolingDXIdf.setString(CoilSystem_Cooling_DXFields::AvailabilityScheduleName,sched.name().get()); OptionalModelObject omo = modelObject.inletModelObject(); if( omo ) { translateAndMapModelObject(*omo); s = omo->name(); if(s) { coilSystemCoolingDXIdf.setString(CoilSystem_Cooling_DXFields::DXCoolingCoilSystemInletNodeName,*s); } } omo= modelObject.outletModelObject(); if( omo ) { translateAndMapModelObject(*omo); s = omo->name(); if(s) { coilSystemCoolingDXIdf.setString(CoilSystem_Cooling_DXFields::DXCoolingCoilSystemOutletNodeName,*s); coilSystemCoolingDXIdf.setString(CoilSystem_Cooling_DXFields::DXCoolingCoilSystemSensorNodeName,*s); } } return coilSystemCoolingDXIdf; } } // energyplus } // openstudio
35.030726
137
0.728889
ORNL-BTRIC
f5973e76be760ccb5431975049488c77d9bf4592
638
cpp
C++
DATA STRUCTURES/Array/Kth Smallest Element/code_1.cpp
Jatin-Goyal5/Data-Structures-and-Algorithms
f6bd0f77e5640c2e0568f3fffc4694758e77af96
[ "MIT" ]
27
2019-01-31T10:22:29.000Z
2021-08-29T08:25:12.000Z
DATA STRUCTURES/Array/Kth Smallest Element/code_1.cpp
Jatin-Goyal5/Data-Structures-and-Algorithms
f6bd0f77e5640c2e0568f3fffc4694758e77af96
[ "MIT" ]
6
2020-09-30T19:01:49.000Z
2020-12-17T15:10:54.000Z
DATA STRUCTURES/Array/Kth Smallest Element/code_1.cpp
Jatin-Goyal5/Data-Structures-and-Algorithms
f6bd0f77e5640c2e0568f3fffc4694758e77af96
[ "MIT" ]
27
2019-09-21T14:19:32.000Z
2021-09-15T03:06:41.000Z
// // code_1.cpp // Algorithm // // Created by Mohd Shoaib Rayeen on 23/11/18. // Copyright © 2018 Shoaib Rayeen. All rights reserved. // #include <iostream> using namespace std; int kthSmallest(int arr[], int n, int k) { sort(arr, arr+n); return arr[k-1]; } int main() { int n; cout << "\nEnter Size\t:\t"; cin >> n; int *a = new int[n]; cout << "\nEnter Array Elements\n"; for ( int i = 0; i < n; i++ ) { cin >> a[i]; } int k; cout << "Enter K\t:\t"; cin >> k; cout << "\nKth Smallest Element\t:\t" << kthSmallest( a , n , k ) << endl; delete[] a; return 0; }
18.764706
78
0.523511
Jatin-Goyal5
60d6724ded3faac6c89df2a481c3676b9c87b110
925
cpp
C++
unique-binary-search-trees-ii/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
unique-binary-search-trees-ii/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
unique-binary-search-trees-ii/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: vector<TreeNode*> constructTree(int l, int r) { vector<TreeNode*> ans; if (l > r) { ans.push_back(NULL); return ans; } for (int i = l; i <= r; ++i) { vector<TreeNode*> leftNodes = constructTree(l, i - 1); vector<TreeNode*> rightNodes = constructTree(i + 1, r); for (int li = 0; li < leftNodes.size(); ++li) { for (int ri = 0; ri < rightNodes.size(); ++ri) { TreeNode* root = new TreeNode(i); root->left = leftNodes[li]; root->right = rightNodes[ri]; ans.push_back(root); } } } return ans; } public: vector<TreeNode*> generateTrees(int n) { return constructTree(1, n); } };
25.694444
61
0.537297
tsenmu
60d826675a40b7b77af03c245ec391d50e0c87d9
4,925
hpp
C++
dependencies/cpp/boost/container/detail/node_pool.hpp
fduffy/QuantLibAdjoint
d9d355db4f46824bb5e607e28381943aef994ed4
[ "BSD-3-Clause" ]
41
2016-03-19T02:31:54.000Z
2022-01-20T13:23:20.000Z
dependencies/cpp/boost/container/detail/node_pool.hpp
fduffy/QuantLibAdjoint
d9d355db4f46824bb5e607e28381943aef994ed4
[ "BSD-3-Clause" ]
4
2017-07-18T21:17:45.000Z
2020-09-17T02:54:52.000Z
dependencies/cpp/boost/container/detail/node_pool.hpp
fduffy/QuantLibAdjoint
d9d355db4f46824bb5e607e28381943aef994ed4
[ "BSD-3-Clause" ]
22
2016-03-17T14:14:36.000Z
2022-03-28T10:33:19.000Z
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/container for documentation. // ////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_CONTAINER_DETAIL_NODE_POOL_HPP #define BOOST_CONTAINER_DETAIL_NODE_POOL_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif #include <boost/container/detail/config_begin.hpp> #include <boost/container/detail/workaround.hpp> #include <boost/container/detail/mutex.hpp> #include <boost/container/detail/pool_common_alloc.hpp> #include <boost/container/detail/node_pool_impl.hpp> #include <boost/container/detail/mutex.hpp> #include <boost/intrusive/slist.hpp> #include <boost/move/utility_core.hpp> #include <cstddef> #include <functional> //std::unary_function #include <algorithm> //std::swap #include <cassert> namespace boost { namespace container { namespace container_detail { //!Pooled memory allocator using single segregated storage. Includes //!a reference count but the class does not delete itself, this is //!responsibility of user classes. Node size (NodeSize) and the number of //!nodes allocated per block (NodesPerBlock) are known at compile time template< std::size_t NodeSize, std::size_t NodesPerBlock > class private_node_pool //Inherit from the implementation to avoid template bloat : public boost::container::container_detail:: private_node_pool_impl<fake_segment_manager> { typedef boost::container::container_detail:: private_node_pool_impl<fake_segment_manager> base_t; //Non-copyable private_node_pool(const private_node_pool &); private_node_pool &operator=(const private_node_pool &); public: typedef typename base_t::multiallocation_chain multiallocation_chain; static const std::size_t nodes_per_block = NodesPerBlock; //!Constructor from a segment manager. Never throws private_node_pool() : base_t(0, NodeSize, NodesPerBlock) {} }; template< std::size_t NodeSize , std::size_t NodesPerBlock > class shared_node_pool : public private_node_pool<NodeSize, NodesPerBlock> { private: typedef private_node_pool<NodeSize, NodesPerBlock> private_node_allocator_t; public: typedef typename private_node_allocator_t::free_nodes_t free_nodes_t; typedef typename private_node_allocator_t::multiallocation_chain multiallocation_chain; //!Constructor from a segment manager. Never throws shared_node_pool() : private_node_allocator_t(){} //!Destructor. Deallocates all allocated blocks. Never throws ~shared_node_pool() {} //!Allocates array of count elements. Can throw std::bad_alloc void *allocate_node() { //----------------------- scoped_lock<default_mutex> guard(mutex_); //----------------------- return private_node_allocator_t::allocate_node(); } //!Deallocates an array pointed by ptr. Never throws void deallocate_node(void *ptr) { //----------------------- scoped_lock<default_mutex> guard(mutex_); //----------------------- private_node_allocator_t::deallocate_node(ptr); } //!Allocates a singly linked list of n nodes ending in null pointer. //!can throw std::bad_alloc void allocate_nodes(const std::size_t n, multiallocation_chain &chain) { //----------------------- scoped_lock<default_mutex> guard(mutex_); //----------------------- return private_node_allocator_t::allocate_nodes(n, chain); } void deallocate_nodes(multiallocation_chain &chain) { //----------------------- scoped_lock<default_mutex> guard(mutex_); //----------------------- private_node_allocator_t::deallocate_nodes(chain); } //!Deallocates all the free blocks of memory. Never throws void deallocate_free_blocks() { //----------------------- scoped_lock<default_mutex> guard(mutex_); //----------------------- private_node_allocator_t::deallocate_free_blocks(); } //!Deallocates all blocks. Never throws void purge_blocks() { //----------------------- scoped_lock<default_mutex> guard(mutex_); //----------------------- private_node_allocator_t::purge_blocks(); } std::size_t num_free_nodes() { //----------------------- scoped_lock<default_mutex> guard(mutex_); //----------------------- return private_node_allocator_t::num_free_nodes(); } private: default_mutex mutex_; }; } //namespace container_detail { } //namespace container { } //namespace boost { #include <boost/container/detail/config_end.hpp> #endif //#ifndef BOOST_CONTAINER_DETAIL_NODE_POOL_HPP
31.369427
90
0.655431
fduffy
60d8989a920e906e24ec3684360cf394dfcf6513
47,612
cpp
C++
src/cpu/x64/matmul/brgemm_matmul.cpp
cfRod/oneDNN
7981216b8341b8603e54472f5a0dd7a12ef9cf67
[ "Apache-2.0" ]
1,327
2018-01-25T21:23:47.000Z
2020-04-03T09:39:30.000Z
src/cpu/x64/matmul/brgemm_matmul.cpp
cfRod/oneDNN
7981216b8341b8603e54472f5a0dd7a12ef9cf67
[ "Apache-2.0" ]
498
2018-01-25T00:14:48.000Z
2020-04-03T16:21:44.000Z
src/cpu/x64/matmul/brgemm_matmul.cpp
cfRod/oneDNN
7981216b8341b8603e54472f5a0dd7a12ef9cf67
[ "Apache-2.0" ]
365
2018-01-29T16:12:36.000Z
2020-04-03T08:32:27.000Z
/******************************************************************************* * Copyright 2021-2022 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 "common/c_types_map.hpp" #include "common/dnnl_thread.hpp" #include "common/memory_tracking.hpp" #include "common/tag_traits.hpp" #include "common/type_helpers.hpp" #include "common/utils.hpp" #include "cpu/cpu_primitive.hpp" #include "cpu/x64/amx_tile_configure.hpp" #include "cpu/x64/injectors/jit_uni_binary_injector.hpp" #include "cpu/x64/matmul/brgemm_matmul.hpp" namespace dnnl { namespace impl { namespace cpu { namespace x64 { namespace matmul { using namespace dnnl::impl::memory_tracking::names; using namespace dnnl::impl::utils; using namespace nstl; using namespace data_type; template <cpu_isa_t isa> status_t brgemm_matmul_t<isa>::pd_t::init(engine_t *engine) { const auto src_dt = src_md_.data_type; const auto wei_dt = weights_md_.data_type; const auto dst_dt = dst_md_.data_type; const bool is_f32 = everyone_is(f32, src_dt, wei_dt, dst_dt); const bool is_int8 = one_of(src_dt, u8, s8) && wei_dt == s8 && one_of(dst_dt, u8, s8, s32, f32, bf16); const bool is_bf16 = everyone_is(bf16, src_dt, wei_dt) && one_of(dst_dt, bf16, f32); auto check_bias = [&]() -> bool { const bool is_bia_dt_correct = (is_int8 && one_of(weights_md(1)->data_type, f32, s32, s8, u8, bf16)) || (is_bf16 && one_of(weights_md(1)->data_type, f32, bf16)) || (is_f32 && weights_md(1)->data_type == f32); return IMPLICATION(with_bias(), is_bia_dt_correct && is_bias_1xN()); }; auto check_attr_oscale = [&]() -> bool { const auto &oscale = attr()->output_scales_; return IMPLICATION( oscale.mask_ != 0, oscale.mask_ == (1 << (dst_md_.ndims - 1))); }; auto check_attr_zero_points = [&]() -> bool { return attr()->zero_points_.common(); }; const bool problem_dt_correct = is_int8 || is_bf16 || is_f32; bool ok = mayiuse(isa) && problem_dt_correct && !has_runtime_dims_or_strides() && attr()->has_default_values( primitive_attr_t::skip_mask_t::oscale_runtime | primitive_attr_t::skip_mask_t::zero_points_runtime | primitive_attr_t::skip_mask_t::post_ops | primitive_attr_t::skip_mask_t::sum_dt, dst_dt) && attr()->post_ops_.check_sum_consistent_dt(dst_dt) && check_attr_oscale() && check_attr_zero_points() && check_bias(); if (!ok) return status::unimplemented; CHECK(init_brgemm_matmul_conf(isa, bgmmc_, *desc(), src_md_, weights_md_, dst_md_, bias_md_, attr_)); const float alpha = 1.0; const float beta = 1.0; const float beta_init = 0.0; for_(int i_bs = 0; i_bs < 2; i_bs++) for_(int i_init = 0; i_init < 2; i_init++) for_(int i_M = 0; i_M < 2; i_M++) for_(int i_N = 0; i_N < 2; i_N++) for (int i_K = 0; i_K < 2; i_K++) { auto vbeta = (i_init) ? beta_init : beta; auto vM = (i_M) ? bgmmc_.M_tail : bgmmc_.M_blk; auto vN = (i_N) ? bgmmc_.N_tail : bgmmc_.N_blk; auto vK = (i_K) ? bgmmc_.K_tail : bgmmc_.K_blk; int bs = get_brg_batchsize(bgmmc_, i_bs, i_K); int idx = get_brg_kernel_idx(i_bs, i_init, i_M, i_N, i_K); if (idx < 0) continue; brgemm_t &brg = brg_descs_[idx]; auto LDA = i_K && bgmmc_.use_buffer_a_tail_only ? (dim_t)bgmmc_.wei_k_blk : bgmmc_.LDA; CHECK(brgemm_desc_init(&brg, isa, bgmmc_.brg_type, bgmmc_.src_dt, bgmmc_.wei_dt, false, false, brgemm_row_major, alpha, vbeta, LDA, bgmmc_.LDB, bgmmc_.LDC, vM, vN, vK)); auto LDD = bgmmc_.LDD; CHECK(brgemm_desc_set_postops( &brg, attr(), &dst_md_, LDD, bgmmc_.bia_dt)); brgemm_attr_t brgattr; brgattr.generate_skip_accumulation = bgmmc_.post_ops_applicable && bgmmc_.nthr_k > 1; constexpr bool is_amx = one_of( isa, avx512_core_bf16_amx_int8, avx512_core_bf16_amx_bf16); if (is_amx) { if (!brgattr.generate_skip_accumulation) { // TODO: uker doesn't yet support generate_skip_accumulation brgattr.use_uker = true; brgattr.use_interleave_stores = true; } brgattr.max_bs = bs; brgattr.wary_tail_read = false; // TODO: change expected sizes to local chunks wrt L2 blocking brgattr.hint_expected_A_size = vM * vK * bs; brgattr.hint_expected_B_size = vN * vK * bs; brgattr.hint_expected_C_size = vM * vN * bs; brgattr.hint_innermost_loop = brgemm_ld_loop_innermost; brgattr.hint_prefetching = brgemm_kernel_prefetching_t::brgemm_prf_output1; } CHECK(brgemm_desc_set_attr(&brg, brgattr)); bgmmc_.wsp_tile_per_thr_bytes = nstl::max( brg.get_wsp_buffer_size(), bgmmc_.wsp_tile_per_thr_bytes); } auto scratchpad = scratchpad_registry().registrar(); init_scratchpad(scratchpad, bgmmc_); return status::success; } template <cpu_isa_t isa> status_t brgemm_matmul_t<isa>::init(engine_t *engine) { for_(int i_bs = 0; i_bs < 2; i_bs++) for_(int i_M = 0; i_M < 2; i_M++) for_(int i_N = 0; i_N < 2; i_N++) for_(int i_K = 0; i_K < 2; i_K++) for (int i_init = 0; i_init < 2; i_init++) { int idx = pd()->get_brg_kernel_idx(i_bs, i_init, i_M, i_N, i_K); if (idx < 0) continue; brgemm_kernel_t *ker = nullptr; CHECK(brgemm_kernel_create(&ker, pd()->get_brg_desc(idx))); CHECK(safe_ptr_assign(brg_kernels_[idx], ker)); if (one_of(isa, avx512_core_bf16_amx_int8, avx512_core_bf16_amx_bf16)) CHECK(brgemm_init_tiles( pd()->get_brg_desc(idx), &brg_kernel_palettes_[idx][0])); } const auto &bgmmc = pd()->get_brgemm_matmul_conf(); if (bgmmc.use_buffer_b) CHECK(create_brgemm_matmul_copy_b(copy_B_kernel_, &bgmmc)); if (bgmmc.use_buffer_a || bgmmc.use_buffer_a_tail_only) CHECK(create_brgemm_matmul_copy_a(copy_A_kernel_, &bgmmc)); if (bgmmc.nthr_k > 1 && bgmmc.acc_dt == f32) { CHECK(safe_ptr_assign( acc_ker_f32_, new cpu_accumulator_1d_t<data_type::f32>())); CHECK(acc_ker_f32_->create_kernel()); } else if (bgmmc.nthr_k > 1 && bgmmc.acc_dt == s32) { CHECK(safe_ptr_assign( acc_ker_s32_, new cpu_accumulator_1d_t<data_type::s32>())); CHECK(acc_ker_s32_->create_kernel()); } return status::success; } template <cpu_isa_t isa> status_t brgemm_matmul_t<isa>::execute_body(const exec_ctx_t &ctx) const { DEFINE_ZERO_POINT_VALUE(src_zero_point, DNNL_ARG_SRC); DEFINE_ZERO_POINT_VALUE(wei_zero_point, DNNL_ARG_WEIGHTS); DEFINE_ZERO_POINT_VALUE(dst_zero_point, DNNL_ARG_DST); DEFINE_SCALES_BUFFER(oscales); brg_matmul_exec_ctx_t brgmm_ctx( ctx, pd(), oscales, src_zero_point, wei_zero_point, dst_zero_point); const auto &bgmmc = pd()->get_brgemm_matmul_conf(); const bool use_buffer_a = bgmmc.use_buffer_a || bgmmc.use_buffer_a_tail_only; constexpr bool is_amx = one_of(isa, avx512_core_bf16_amx_int8, avx512_core_bf16_amx_bf16); const int num_threads = brgmm_ctx.get_num_threads_for_parallelization(); parallel(num_threads, [&](const int ithr, const int nthr) { const int ithr_bmn = brgmm_ctx.get_thread_idx_for_bmn(ithr); const int ithr_k = brgmm_ctx.get_thread_idx_for_k(ithr); if (ithr_bmn < 0 || ithr_k < 0) return; int start {0}, end {0}; balance211(brgmm_ctx.get_parallel_work_amount(), brgmm_ctx.get_num_threads_for_bmn(), ithr_bmn, start, end); int kc_start {0}, kc_end {bgmmc.K_chunks}; if (brgmm_ctx.parallel_reduction_is_used()) balance211((int)bgmmc.K_chunks, brgmm_ctx.get_num_threads_for_k(), ithr_k, kc_start, kc_end); if (is_amx) { const auto base_ker_idx = brgmm_ctx.get_base_brgemm_kernel_idx(); amx_tile_configure(&brg_kernel_palettes_[base_ker_idx][0]); } int b {0}, mc {0}, nc {0}; nd_iterator_init( start, b, bgmmc.batch, mc, bgmmc.M_chunks, nc, bgmmc.N_chunks); while (start < end) { auto m_start = mc * bgmmc.M_chunk_size; auto m_end = nstl::min( (mc + 1) * bgmmc.M_chunk_size, bgmmc.num_M_blocks); auto n_start = nc * bgmmc.N_chunk_size; auto n_end = nstl::min( (nc + 1) * bgmmc.N_chunk_size, bgmmc.num_N_blocks); for_(int kc = kc_start; kc < kc_end; kc++) for (int nb = n_start; nb < n_end; nb++) { if (bgmmc.use_buffer_b) copy_b_chunk_in_buffer(brgmm_ctx, ithr, b, nb, kc); for (int mb = m_start; mb < m_end; mb++) { if (use_buffer_a && nb == n_start) copy_a_chunk_in_buffer(brgmm_ctx, ithr, b, mb, kc); compute_kernel( brgmm_ctx, ithr, b, mb, nb, kc, kc == kc_start); } } ++start; nd_iterator_step( b, bgmmc.batch, mc, bgmmc.M_chunks, nc, bgmmc.N_chunks); } if (is_amx) { amx_tile_release(); } }); maybe_reduce_partial_results_and_apply_postops(brgmm_ctx); return status::success; } template <cpu_isa_t isa> void brgemm_matmul_t<isa>::compute_kernel( const brg_matmul_exec_ctx_t &brgmm_ctx, int ithr, int b_idx, int m_blk_idx, int n_blk_idx, int k_chunk_idx, bool do_init) const { constexpr bool is_amx = one_of(isa, avx512_core_bf16_amx_int8, avx512_core_bf16_amx_bf16); const auto &bgmmc = pd()->get_brgemm_matmul_conf(); const auto addr_batch = brgmm_ctx.get_batch_elem_ptr(ithr); const int base_brg_ker_idx = brgmm_ctx.get_base_brgemm_kernel_idx(); const auto wsp_tile = brgmm_ctx.get_tile_workspace(ithr); const int m = m_blk_idx * bgmmc.M_blk; const int n = n_blk_idx * bgmmc.N_blk; const int k_blk_idx = k_chunk_idx * bgmmc.brgemm_batch_size; const bool is_M_tail = (bgmmc.M - m < bgmmc.M_blk); const bool is_N_tail = (bgmmc.N - n < bgmmc.N_blk); const bool is_last_K_chunk = brgmm_ctx.is_last_K_chunk(k_chunk_idx); const int remaining_k_blks = (bgmmc.use_buffer_a ? utils::rnd_up(bgmmc.K, bgmmc.K_blk) : bgmmc.K) - k_chunk_idx * bgmmc.K_chunk_elems; const int gemm_batch = brgmm_ctx.get_brgemm_batch_size(k_chunk_idx); const bool is_K_tail = is_last_K_chunk && (gemm_batch * bgmmc.K_blk) != remaining_k_blks; auto is_bs_tail = (gemm_batch != bgmmc.brgemm_batch_size); const int brg_ker_idx = pd()->get_brg_kernel_idx( is_bs_tail, do_init, is_M_tail, is_N_tail, false); const auto ptr_bias = brgmm_ctx.get_bias_ptr(n); auto ptr_D = brgmm_ctx.get_data_C_ptr(b_idx, m, n); auto ptr_C = (bgmmc.use_buffer_c) ? brgmm_ctx.get_buf_C_ptr(ithr, m_blk_idx, n_blk_idx) : ptr_D; const auto zp_comp_a = brgmm_ctx.get_zp_a_compensation_ptr(ithr, n_blk_idx); const auto zp_comp_b = brgmm_ctx.get_zp_b_compensation_result_ptr(ithr, m_blk_idx); const auto zp_c_val_ptr = brgmm_ctx.get_zp_c_val_ptr(); const auto &post_ops_binary_rhs_arg_vec = brgmm_ctx.get_post_ops_binary_rhs_arg_vec(); const bool post_ops_applicable = bgmmc.post_ops_applicable && (bgmmc.nthr_k <= 1 || bgmmc.K_chunks == 1); if (gemm_batch > 0 && brg_ker_idx >= 0) { const auto brg_kernel = brg_kernels_[brg_ker_idx].get(); assert(brg_kernel != nullptr); const bool is_tile_reconf_required = is_amx && (is_M_tail || is_N_tail); if (is_tile_reconf_required) amx_tile_configure(&brg_kernel_palettes_[brg_ker_idx][0]); brgmm_ctx.init_brgemm_batch_elements_values( ithr, 0, gemm_batch, b_idx, m_blk_idx, k_blk_idx, n_blk_idx); if (post_ops_applicable && is_last_K_chunk && !is_K_tail) { void *scratch = is_amx ? static_cast<void *>(wsp_tile) : static_cast<void *>(brgmm_ctx.get_s8s8_comp_ptr( ithr, b_idx, n_blk_idx)); const size_t dst_row_logical_off = m_blk_idx * bgmmc.M_blk; const size_t batch_first_dim_idx = bgmmc.batch_ndims > 1 ? b_idx / bgmmc.batch_without_first_dim : 0; const size_t first_mb_matrix_addr_off = batch_first_dim_idx * (bgmmc.M * bgmmc.N) + (m * bgmmc.N + n); const brgemm_post_ops_data_t post_ops_data { static_cast<const void *>(ptr_bias), brgmm_ctx.get_oscales_ptr(n), post_ops_binary_rhs_arg_vec.data(), static_cast<size_t>(n), dst_row_logical_off, brgmm_ctx.get_data_C_ptr(0, 0, 0), first_mb_matrix_addr_off, static_cast<const void *>(zp_comp_a), static_cast<const void *>(zp_comp_b), static_cast<const void *>(zp_c_val_ptr)}; brgemm_kernel_execute_postops(brg_kernel, gemm_batch, addr_batch, (void *)ptr_C, (void *)ptr_D, post_ops_data, scratch); } else { brgemm_kernel_execute(brg_kernel, gemm_batch, addr_batch, (void *)ptr_C, is_amx ? (void *)wsp_tile : nullptr); } if (is_tile_reconf_required) amx_tile_configure(&brg_kernel_palettes_[base_brg_ker_idx][0]); } if (is_K_tail) { brgmm_ctx.init_brgemm_batch_elements_values( ithr, gemm_batch, 1, b_idx, m_blk_idx, k_blk_idx, n_blk_idx); const bool use_init_ker = (do_init && gemm_batch == 0); const int brg_ker_idx = pd()->get_brg_kernel_idx( false, use_init_ker, is_M_tail, is_N_tail, true); const auto brg_kernel_k_tail = brg_kernels_[brg_ker_idx].get(); const bool is_tile_reconf_required = is_amx && bgmmc.K_tail != bgmmc.K_blk; if (is_tile_reconf_required) amx_tile_configure(&brg_kernel_palettes_[brg_ker_idx][0]); if (post_ops_applicable) { void *scratch = is_amx ? static_cast<void *>(wsp_tile) : static_cast<void *>(brgmm_ctx.get_s8s8_comp_ptr( ithr, b_idx, n_blk_idx)); const size_t dst_row_logical_off = m_blk_idx * bgmmc.M_blk; const size_t batch_first_dim_idx = bgmmc.batch_ndims > 1 ? b_idx / bgmmc.batch_without_first_dim : 0; const size_t first_mb_matrix_addr_off = batch_first_dim_idx * (bgmmc.M * bgmmc.N) + (m * bgmmc.N + n); const brgemm_post_ops_data_t post_ops_data { static_cast<const void *>(ptr_bias), brgmm_ctx.get_oscales_ptr(n), post_ops_binary_rhs_arg_vec.data(), static_cast<size_t>(n), dst_row_logical_off, brgmm_ctx.get_data_C_ptr(0, 0, 0), first_mb_matrix_addr_off, static_cast<const void *>(zp_comp_a), static_cast<const void *>(zp_comp_b), static_cast<const void *>(zp_c_val_ptr)}; brgemm_kernel_execute_postops(brg_kernel_k_tail, 1, addr_batch, (void *)ptr_C, (void *)ptr_D, post_ops_data, scratch); } else { brgemm_kernel_execute(brg_kernel_k_tail, 1, addr_batch, (void *)ptr_C, is_amx ? (void *)wsp_tile : nullptr); } if (is_tile_reconf_required) amx_tile_configure(&brg_kernel_palettes_[base_brg_ker_idx][0]); } } template <cpu_isa_t isa> void brgemm_matmul_t<isa>::maybe_reduce_partial_results_and_apply_postops( const brg_matmul_exec_ctx_t &brgmm_ctx) const { if (!brgmm_ctx.parallel_reduction_is_used()) return; const auto &bgmmc = pd()->get_brgemm_matmul_conf(); const int num_threads = brgmm_ctx.get_num_threads_for_parallelization(); parallel(num_threads, [&](const int ithr, const int nthr) { const int nthr_k = brgmm_ctx.get_num_threads_for_k(); const int ithr_bmn = brgmm_ctx.get_thread_idx_for_bmn(ithr); const int ithr_k = brgmm_ctx.get_thread_idx_for_k(ithr); if (ithr_bmn < 0 || ithr_k < 0) return; const int num_reduction_buffers = nstl::min(nthr_k, bgmmc.K_chunks); int bmn_start {0}, bmn_end {0}; int start {0}, end {0}; balance211(brgmm_ctx.get_parallel_work_amount(), brgmm_ctx.get_num_threads_for_bmn(), ithr_bmn, bmn_start, bmn_end); balance211(bmn_end - bmn_start, nthr_k, ithr_k, start, end); int b {0}, mc {0}, nc {0}; assert(bgmmc.batch == 1); nd_iterator_init(bmn_start + start, b, bgmmc.batch, mc, bgmmc.M_chunks, nc, bgmmc.N_chunks); while (start < end) { auto mb_start = mc * bgmmc.M_chunk_size; auto mb_end = nstl::min( (mc + 1) * bgmmc.M_chunk_size, bgmmc.num_M_blocks); auto nb_start = nc * bgmmc.N_chunk_size; auto nb_end = nstl::min( (nc + 1) * bgmmc.N_chunk_size, bgmmc.num_N_blocks); for (int mb = mb_start; mb < mb_end; mb++) { const int curr_M_blk = nstl::min(bgmmc.M - mb * bgmmc.M_blk, bgmmc.M_blk); const bool is_M_tail = curr_M_blk < bgmmc.M_blk; const int curr_N_chunk_size = nstl::min(bgmmc.N, nb_end * bgmmc.N_blk) - nb_start * bgmmc.N_blk; char *buf_reduced_base = brgmm_ctx.get_buf_C_par_reduction_ptr( 0, mb, nb_start); const size_t m_offset = bgmmc.LDC * bgmmc.acc_dt_sz; for (int r = 1; r < num_reduction_buffers; r++) { const char *buf_to_reduce_base = brgmm_ctx.get_buf_C_par_reduction_ptr( r, mb, nb_start); for (int m = 0; m < curr_M_blk; m++) { accumulate(buf_reduced_base + m * m_offset, buf_to_reduce_base + m * m_offset, curr_N_chunk_size); } } if (bgmmc.post_ops_applicable) { for (int nb = nb_start; nb < nb_end; nb++) { const bool is_N_tail = (bgmmc.N - nb * bgmmc.N_blk < bgmmc.N_blk); const int brg_ker_idx = pd()->get_brg_kernel_idx( false, false, is_M_tail, is_N_tail, false); const auto brg_kernel = brg_kernels_[brg_ker_idx].get(); const int m = mb * bgmmc.M_blk; const int n = nb * bgmmc.N_blk; const auto ptr_bias = brgmm_ctx.get_bias_ptr(n); auto ptr_D = brgmm_ctx.get_data_C_ptr(b, m, n); auto ptr_C = brgmm_ctx.get_buf_C_par_reduction_ptr( 0, mb, nb); // TODO: support reduction for zp/s8s8 compensations // computed in copy routines const auto zp_comp_a = brgmm_ctx.get_zp_a_compensation_ptr(ithr, nb); const auto zp_comp_b = brgmm_ctx.get_zp_b_compensation_result_ptr( ithr, mb); const auto zp_c_val_ptr = brgmm_ctx.get_zp_c_val_ptr(); const auto &post_ops_binary_rhs_arg_vec = brgmm_ctx.get_post_ops_binary_rhs_arg_vec(); const size_t dst_row_logical_off = mb * bgmmc.M_blk; const size_t batch_first_dim_idx = bgmmc.batch_ndims > 1 ? b / bgmmc.batch_without_first_dim : 0; const size_t first_mb_matrix_addr_off = batch_first_dim_idx * (bgmmc.M * bgmmc.N) + (m * bgmmc.N + n); // apply post-ops and convert to dst data type only constexpr bool skip_accumulation = true; const brgemm_post_ops_data_t post_ops_data { static_cast<const void *>(ptr_bias), brgmm_ctx.get_oscales_ptr(n), post_ops_binary_rhs_arg_vec.data(), static_cast<size_t>(n), dst_row_logical_off, brgmm_ctx.get_data_C_ptr(0, 0, 0), first_mb_matrix_addr_off, static_cast<const void *>(zp_comp_a), static_cast<const void *>(zp_comp_b), static_cast<const void *>(zp_c_val_ptr), skip_accumulation}; brgemm_kernel_execute_postops(brg_kernel, 0, nullptr, (void *)ptr_C, (void *)ptr_D, post_ops_data, nullptr); } } } ++start; nd_iterator_step( b, bgmmc.batch, mc, bgmmc.M_chunks, nc, bgmmc.N_chunks); } }); } template <cpu_isa_t isa> void brgemm_matmul_t<isa>::copy_a_chunk_in_buffer( const brg_matmul_exec_ctx_t &brgmm_ctx, int ithr, int b_idx, int m_blk_idx, int k_chunk_idx) const { const auto &bgmmc = pd()->get_brgemm_matmul_conf(); auto ctx = jit_brgemm_matmul_copy_a_t::ctx_t(); const int k_start = k_chunk_idx * bgmmc.K_chunk_elems; const bool is_K_tail = brgmm_ctx.is_last_K_chunk(k_chunk_idx) && bgmmc.K_tail > 0; const int gemm_batch = brgmm_ctx.get_brgemm_batch_size(k_chunk_idx); const int gemm_batch_iters = bgmmc.use_buffer_a_tail_only ? 0 : gemm_batch; const int m = m_blk_idx * bgmmc.M_blk; const bool is_M_tail = (bgmmc.M - m < bgmmc.M_blk); ctx.current_M_blk = is_M_tail ? bgmmc.M_tail : bgmmc.M_blk; ctx.zp_b_compensation_buffer_ptr = (void *)brgmm_ctx.get_zp_b_compensation_buffer_ptr( ithr, m_blk_idx); ctx.zp_a_compensation_result_ptr = (void *)brgmm_ctx.get_zp_b_compensation_result_ptr( ithr, m_blk_idx); ctx.zp_b_neg_value_ptr = (void *)brgmm_ctx.get_zp_b_neg_val_ptr(); ctx.zp_ab_comp_ptr = (void *)brgmm_ctx.get_zp_ab_mixed_comp_ptr(); for (int gb = 0; gb < gemm_batch_iters; gb++) { const int k = k_start + gb * bgmmc.K_blk; ctx.src = (void *)brgmm_ctx.get_data_A_ptr(b_idx, m, k); ctx.tr_src = (void *)brgmm_ctx.get_buf_A_ptr(ithr, m_blk_idx, gb); ctx.current_K_blk = nstl::min(bgmmc.K_blk, bgmmc.K); ctx.current_K_start = k; (*copy_A_kernel_)(&ctx); } if (is_K_tail) { const auto K_tail = bgmmc.K % bgmmc.K_blk; const int k = k_start + gemm_batch * bgmmc.K_blk; ctx.src = (void *)brgmm_ctx.get_data_A_ptr(b_idx, m, k); ctx.tr_src = (void *)brgmm_ctx.get_buf_A_ptr( ithr, m_blk_idx, gemm_batch_iters); ctx.current_K_blk = K_tail; ctx.current_K_start = k; (*copy_A_kernel_)(&ctx); } } template <cpu_isa_t isa> void brgemm_matmul_t<isa>::copy_b_chunk_in_buffer( const brg_matmul_exec_ctx_t &brgmm_ctx, int ithr, int b_idx, int n_blk_idx, int k_chunk_idx) const { const auto &bgmmc = pd()->get_brgemm_matmul_conf(); const int k_start = k_chunk_idx * bgmmc.K_chunk_elems; const bool is_K_tail = brgmm_ctx.is_last_K_chunk(k_chunk_idx) && bgmmc.K_tail > 0; const int gemm_batch = brgmm_ctx.get_brgemm_batch_size(k_chunk_idx); auto ctx = jit_brgemm_matmul_copy_b_t::ctx_t(); const int n = n_blk_idx * bgmmc.N_blk; const bool is_N_tail = (bgmmc.N - n < bgmmc.N_blk); ctx.current_N_blk = is_N_tail ? bgmmc.N_tail : bgmmc.N_blk; ctx.zp_a_compensation_ptr = (void *)brgmm_ctx.get_zp_a_compensation_ptr(ithr, n_blk_idx); ctx.zp_a_neg_value_ptr = (void *)brgmm_ctx.get_zp_a_neg_val_ptr(); int gb = 0; for (; gb < gemm_batch; gb++) { const int k = k_start + gb * bgmmc.K_blk; ctx.src = (void *)brgmm_ctx.get_data_B_ptr(b_idx, k, n); ctx.tr_src = (void *)brgmm_ctx.get_buf_B_ptr(ithr, gb, n_blk_idx); ctx.compensation_ptr = (void *)brgmm_ctx.get_s8s8_comp_ptr(ithr, b_idx, n_blk_idx); ctx.current_K_start = k; ctx.current_K_iters = nstl::min(bgmmc.K_blk, bgmmc.K); (*copy_B_kernel_)(&ctx); } if (is_K_tail) { const int k = k_start + gb * bgmmc.K_blk; ctx.src = (void *)brgmm_ctx.get_data_B_ptr(b_idx, k, n); ctx.tr_src = (void *)brgmm_ctx.get_buf_B_ptr(ithr, gb, n_blk_idx); ctx.compensation_ptr = (void *)brgmm_ctx.get_s8s8_comp_ptr(ithr, b_idx, n_blk_idx); ctx.current_K_start = k; ctx.current_K_iters = bgmmc.K % bgmmc.K_blk; (*copy_B_kernel_)(&ctx); } } template <cpu_isa_t isa> void brgemm_matmul_t<isa>::accumulate( char *result_ptr, const char *reduce_ptr, size_t size) const { if (pd()->get_brgemm_matmul_conf().acc_dt == f32) acc_ker_f32_->accumulate( (float *)result_ptr, (const float *)reduce_ptr, size); else if (pd()->get_brgemm_matmul_conf().acc_dt == s32) acc_ker_s32_->accumulate( (int32_t *)result_ptr, (const int32_t *)reduce_ptr, size); else assert(!"unsupported accumulation data type"); } template <cpu_isa_t isa> struct brgemm_matmul_t<isa>::brg_matmul_exec_ctx_t { brg_matmul_exec_ctx_t(const exec_ctx_t &ctx, const pd_t *pd, const float *oscales, int32_t src_zp, int32_t wei_zp, int32_t dst_zp) : bgmmc_(pd->get_brgemm_matmul_conf()) { data_A_ptr_ = CTX_IN_MEM(const char *, DNNL_ARG_SRC); data_B_ptr_ = CTX_IN_MEM(const char *, DNNL_ARG_WEIGHTS); data_C_ptr_ = CTX_OUT_MEM(char *, DNNL_ARG_DST); bias_ptr_ = CTX_IN_MEM(const char *, DNNL_ARG_BIAS); oscales_ptr_ = oscales; memory_tracking::grantor_t scratchpad = ctx.get_scratchpad_grantor(); const auto &bgmmc = pd->get_brgemm_matmul_conf(); batch_element_ptr_ = scratchpad.template get<brgemm_batch_element_t>( key_brgemm_primitive_batch); const bool use_buffer_a = bgmmc.use_buffer_a || bgmmc.use_buffer_a_tail_only; buf_A_ptr_ = (use_buffer_a) ? scratchpad.template get<char>(key_brgemm_primitive_buffer_a) : nullptr; buf_B_ptr_ = (bgmmc.use_buffer_b) ? scratchpad.template get<char>(key_brgemm_primitive_buffer_b) : nullptr; buf_C_ptr_ = (bgmmc.use_buffer_c) ? scratchpad.template get<char>(key_brgemm_primitive_buffer) : nullptr; is_amx_ = one_of( isa, avx512_core_bf16_amx_int8, avx512_core_bf16_amx_bf16); wsp_tile_ptr_ = is_amx_ ? ctx.get_scratchpad_grantor().template get<char>( key_conv_amx_tile_buffer) : nullptr; const memory_desc_wrapper weights_d(pd->weights_md(0)); const dim_t comp_offset = bgmmc_.b_dt_sz * (weights_d.size() - weights_d.additional_buffer_size()); s8s8_compensation_ptr_ = (bgmmc.s8s8_compensation_required) ? ((bgmmc.use_buffer_b) ? scratchpad.template get<int32_t>( key_brgemm_primitive_buffer_comp) : const_cast<int32_t *>( reinterpret_cast<const int32_t *>( &data_B_ptr_[comp_offset]))) : nullptr; assert(IMPLICATION(bgmmc.s8s8_compensation_required, bgmmc_.b_dt_sz == bgmmc_.tr_b_dt_sz)); zero_point_a_compensations_ptr_ = bgmmc.has_zero_point_a ? scratchpad.template get<int32_t>( key_brgemm_primitive_zp_comp_a) : nullptr; zero_point_b_compensations_ptr_ = bgmmc.has_zero_point_b ? scratchpad.template get<int32_t>( key_brgemm_primitive_zp_comp_b) : nullptr; zero_point_a_negative_val_ = -src_zp; zero_point_b_negative_val_ = -wei_zp; zero_point_mixed_ab_compensation_component_ = bgmmc.K * zero_point_a_negative_val_; zero_point_c_val_ = dst_zp; post_ops_binary_rhs_arg_vec_ = binary_injector::prepare_binary_args( pd->attr()->post_ops_, ctx); base_brg_ker_idx_ = pd->get_brg_kernel_idx(false, true, false, false, false); vnni_factor = isa == avx512_core_bf16_amx_int8 ? 4 : isa == avx512_core_bf16_amx_bf16 ? 2 : 1; reorder_zp_a_comp_ptr_ = nullptr; if (bgmmc_.has_zero_point_a && bgmmc_.blocked_B) { // Store the pointer to computed in reorder compensation values to // scale them locally by zp_a value just before usage in post-ops. // Using the single global scaling before parallel section might // produce significant overhead for small problems running in // multitreaded execution mode const size_t reorder_zp_a_comp_offset = weights_d.size() - weights_d.additional_buffer_size(); const size_t s8s8_buffer_sz = bgmmc.s8s8_compensation_required ? bgmmc.s8s8_comp_b_str * sizeof(int32_t) : 0; reorder_zp_a_comp_ptr_ = const_cast<int32_t *>(reinterpret_cast<const int32_t *>( &data_B_ptr_[reorder_zp_a_comp_offset + s8s8_buffer_sz])); } // Set last_chunk_brgemm_batch_size_ to brgemm_batch_size // when K_tail = 0 and brgemm_batch_tail_size = 0 last_chunk_brgemm_batch_size_ = bgmmc.brgemm_batch_tail_size; if (bgmmc.K_tail == 0 && last_chunk_brgemm_batch_size_ == 0) last_chunk_brgemm_batch_size_ = bgmmc.brgemm_batch_size; // parallelization parallel_work_amount_ = bgmmc.batch * bgmmc.M_chunks * bgmmc.N_chunks; // The number of threads available during primitive execution may // increase (ex. Eigen threadpool implementation) or decrease // (ex. nested parallelism) compared to the // number of threads available during primitive creation. // So we limit the total number of threads to the // minimum of these two values to prevent potential OOM issues. nthr_ = nstl::min(dnnl_get_current_num_threads(), bgmmc.nthr); nthr_k_ = bgmmc.nthr_k > 0 && bgmmc.nthr_k <= nthr_ ? bgmmc.nthr_k : 1; nthr_bmn_ = nthr_ / nthr_k_; num_threads_used_ = nthr_k_ * nthr_bmn_; // If parallel_work_amount_ == 1 and parallel reduction is not used, we // limit num threads to 1 as parallel(1, ...) does not create parallel // section at all. We do not limit number of threads for case // 1 < parallel_work_amount_ < dnnl_get_max_threads() to avoid potential // overhead on spawning different number of OMP threads from layer to // layer. if (parallel_work_amount_ == 1 && !parallel_reduction_is_used()) nthr_ = nthr_bmn_ = nthr_k_ = 1; const bool need_to_calculate_compensation_for_a = bgmmc.has_zero_point_b; const bool need_to_calculate_compensation_for_b = !IMPLICATION( (bgmmc.has_zero_point_a || bgmmc.s8s8_compensation_required), bgmmc.blocked_B); const bool calculate_compensations_in_copy_routines = need_to_calculate_compensation_for_a || need_to_calculate_compensation_for_b; // currently parallel reduction is supported only for case of // non-batched problems without computation of any compensations in // copy routines assert(IMPLICATION(parallel_reduction_is_used(), bgmmc.batch == 1 && !calculate_compensations_in_copy_routines)); MAYBE_UNUSED(need_to_calculate_compensation_for_a); MAYBE_UNUSED(need_to_calculate_compensation_for_b); MAYBE_UNUSED(calculate_compensations_in_copy_routines); } // NOTE: gb --> generalized batch, bb --> broadcast batch int get_bb_idx(int gb_idx, const brgemm_matmul_bcast_desc_t &bd) const { if (!bd.bcast_mask) // no broadcast return gb_idx; int gb_off_before_bcast = utils::rnd_dn( gb_idx, bd.first_bcast_dim_to_last_batch_dim_prod); int bb_idx = gb_off_before_bcast / (bd.bcast_dims_prod); dim_t cur_bcast_dims_prod = bd.bcast_dims_prod; int mask = 1 << (bgmmc_.batch_ndims - bd.first_bcast_dim - 1); for (int d = bd.first_bcast_dim; d < bd.last_bcast_dim; ++d) { if (bd.bcast_mask & mask) // broadcast cur_bcast_dims_prod /= bd.batch_dims[d]; else { int cur_b = (gb_idx / bd.gb_off[d]) % bd.batch_dims[d]; bb_idx += cur_b * (bd.gb_off[d] / cur_bcast_dims_prod); } mask >>= 1; } bb_idx += gb_idx % bd.gb_off[bd.last_bcast_dim]; return bb_idx; } const char *get_data_A_ptr(int b, int m, int k) const { int cur_b = get_bb_idx(b, bgmmc_.bcast_A_desc); return data_A_ptr_ + get_data_A_off(cur_b, m, k); } const char *get_data_B_ptr(int b, int k, int n) const { int cur_b = get_bb_idx(b, bgmmc_.bcast_B_desc); return data_B_ptr_ + get_data_B_off(cur_b, k, n); } char *get_data_C_ptr(int b, int m, int n) const { return data_C_ptr_ + get_data_C_off(b, m, n); } brgemm_batch_element_t *get_batch_elem_ptr(int ithr) const { return batch_element_ptr_ + ithr * bgmmc_.brgemm_batch_element_per_thr_sz; } void init_brgemm_batch_elements_values(int ithr, int brg_batch_start, int brg_batch_iters, int b_idx, int m_blk_idx, int k_blk_idx, int n_blk_idx) const { auto addr_batch = get_batch_elem_ptr(ithr); const int m = m_blk_idx * bgmmc_.M_blk; const int n = n_blk_idx * bgmmc_.N_blk; for (int b_iter = 0; b_iter < brg_batch_iters; b_iter++) { const int brg_batch_idx = brg_batch_start + b_iter; const int k = (k_blk_idx + brg_batch_idx) * bgmmc_.K_blk; addr_batch[b_iter].ptr.A = bgmmc_.use_buffer_a ? get_buf_A_ptr(ithr, m_blk_idx, brg_batch_idx) : get_data_A_ptr(b_idx, m, k); addr_batch[b_iter].ptr.B = (bgmmc_.use_buffer_b) ? get_buf_B_ptr(ithr, brg_batch_idx, n_blk_idx) : get_data_B_ptr(b_idx, k, n); } } char *get_buf_A_ptr(int ithr, int m_blk_idx, int k_blk_idx) const { if (!bgmmc_.use_buffer_a && !bgmmc_.use_buffer_a_tail_only) return nullptr; const int k_blk_local = bgmmc_.use_buffer_a_tail_only ? 0 : k_blk_idx; const int m_blk_local = m_blk_idx % bgmmc_.M_chunk_size; return buf_A_ptr_ + ithr * bgmmc_.buffer_a_per_thread_sz + m_blk_local * bgmmc_.buffer_a_chunk_shift_along_m + k_blk_local * bgmmc_.buffer_a_chunk_sz; } char *get_buf_B_ptr(int ithr, int k_blk_idx, int n_blk_idx) const { UNUSED(n_blk_idx); if (!bgmmc_.use_buffer_b) return nullptr; return buf_B_ptr_ + ithr * bgmmc_.buffer_b_per_thread_sz + k_blk_idx * bgmmc_.buffer_b_chunk_sz; } char *get_buf_C_ptr(int ithr, int m_blk_idx, int n_blk_idx) const { if (!bgmmc_.use_buffer_c) return nullptr; if (bgmmc_.nthr_k > 1) { const int nthr_k = bgmmc_.nthr_k <= nthr_ ? bgmmc_.nthr_k : 1; const int nthr_bmn = nthr_ / nthr_k; const int ithr_k = ithr / nthr_bmn; return get_buf_C_par_reduction_ptr(ithr_k, m_blk_idx, n_blk_idx); } const int m_blk_local = m_blk_idx % bgmmc_.M_chunk_size; const int n_blk_local = n_blk_idx % bgmmc_.N_chunk_size; const int buf_idx = bgmmc_.N_chunk_size * m_blk_local + n_blk_local; return buf_C_ptr_ + ithr * bgmmc_.buffer_c_per_thread_sz + buf_idx * bgmmc_.buffer_c_chunk_sz; } char *get_buf_C_par_reduction_ptr( int ithr_k, int m_blk_idx, int n_blk_idx) const { if (bgmmc_.nthr_k <= 1) return nullptr; const int m = m_blk_idx * bgmmc_.M_blk; const int n = n_blk_idx * bgmmc_.N_blk; if (!bgmmc_.post_ops_applicable && ithr_k == 0) return get_data_C_ptr(0, m, n); int k_buf_idx = ithr_k - (!bgmmc_.post_ops_applicable ? 1 : 0); return buf_C_ptr_ + k_buf_idx * bgmmc_.buffer_c_per_thread_sz + get_data_C_off(0, m, n) * bgmmc_.acc_dt_sz / bgmmc_.c_dt_sz; } // Auxiliary functions for getting offsets with pre-calculated memory // strides for each tensor to get general sulution for all possible // dimension without significant overhead dim_t get_data_A_off(int b, int m, int k) const { using namespace format_tag; if (bgmmc_.src_tag == acbd || bgmmc_.src_tag == adbc) { dim_t b_off = 0; if (!bgmmc_.bcast_A_desc.bcast_mask) { // no broadcast const dim_t batch_dim1 = bgmmc_.bcast_A_desc.batch_dims[1]; b_off = bgmmc_.A_strides[2] * (b % batch_dim1) + (b / batch_dim1) * bgmmc_.A_ptr_shift_b; } else { b_off = b * bgmmc_.A_ptr_shift_b; } return b_off + bgmmc_.A_strides[1] * m + bgmmc_.A_strides[0] * k; } else { return bgmmc_.A_strides[2] * b + bgmmc_.A_strides[1] * m + bgmmc_.A_strides[0] * k; } } dim_t get_data_B_off(int b, int k, int n) const { using namespace format_tag; if (bgmmc_.wei_tag == acbd || bgmmc_.wei_tag == adbc) { dim_t b_off = 0; if (!bgmmc_.bcast_B_desc.bcast_mask) { // no broadcast const dim_t batch_dim1 = bgmmc_.bcast_B_desc.batch_dims[1]; b_off = bgmmc_.B_strides[2] * (b % batch_dim1) + (b / batch_dim1) * bgmmc_.B_ptr_shift_b; } else { b_off = b * bgmmc_.B_ptr_shift_b; } return b_off + bgmmc_.B_strides[1] * k + bgmmc_.B_strides[0] * n; } else { int dt_b_k_blk = bgmmc_.is_bf32 ? data_type_vnni_simd_elems<avx512_core>(f32) : bgmmc_.wei_k_blk; int k_idx = bgmmc_.blocked_B ? k / dt_b_k_blk : k; int n_idx = bgmmc_.blocked_B ? n / bgmmc_.wei_n_blk : n; return bgmmc_.B_strides[2] * b + bgmmc_.B_strides[1] * k_idx + bgmmc_.B_strides[0] * n_idx + get_data_B_off_within_block(k, n); } } dim_t get_data_B_off_within_block(int k, int n) const { using namespace format_tag; if (!bgmmc_.blocked_B) return 0; int x0 = k % bgmmc_.wei_k_blk; int x1 = n % bgmmc_.wei_n_blk; dim_t offset = (x0 / vnni_factor) * vnni_factor * bgmmc_.wei_n_blk + x1 * vnni_factor + x0 % vnni_factor; return bgmmc_.b_dt_sz * offset; } dim_t get_data_C_off(int b, int m, int n) const { using namespace format_tag; assert(bgmmc_.dst_tag != adbc); if (bgmmc_.dst_tag == acbd) { const dim_t batch_dim1 = bgmmc_.bcast_A_desc.batch_dims[1]; dim_t b_off = bgmmc_.C_strides[2] * (b % batch_dim1) + (b / batch_dim1) * bgmmc_.C_ptr_shift_b; return b_off + bgmmc_.C_strides[1] * m + bgmmc_.C_strides[0] * n; } else { return bgmmc_.C_strides[2] * b + bgmmc_.C_strides[1] * m + bgmmc_.C_strides[0] * n; } } const char *get_bias_ptr(int n) const { if (!bgmmc_.with_bias) return nullptr; return bias_ptr_ + n * bgmmc_.bias_dt_sz; } int32_t *get_s8s8_comp_ptr(int ithr, int b, int n_blk_idx) const { if (!bgmmc_.s8s8_compensation_required) return nullptr; const int n_blk_local = bgmmc_.use_buffer_b ? n_blk_idx % bgmmc_.N_chunk_size : n_blk_idx; return s8s8_compensation_ptr_ + ithr * bgmmc_.s8s8_comp_ithr_str + b * bgmmc_.s8s8_comp_b_str + n_blk_local * bgmmc_.s8s8_comp_n_str; } const float *get_oscales_ptr(int n) const { return oscales_ptr_ + bgmmc_.is_oscale_per_n * n; } const int32_t *get_zp_a_neg_val_ptr() const { return &zero_point_a_negative_val_; } const int32_t *get_zp_b_neg_val_ptr() const { return &zero_point_b_negative_val_; } const int32_t *get_zp_ab_mixed_comp_ptr() const { return &zero_point_mixed_ab_compensation_component_; } const int32_t *get_zp_c_val_ptr() const { return &zero_point_c_val_; } int32_t *get_zp_a_compensation_ptr(int ithr, int n_blk_idx) const { if (!bgmmc_.has_zero_point_a) return nullptr; const int n_blk_local = n_blk_idx % bgmmc_.N_chunk_size; int32_t *zp_comp = zero_point_a_compensations_ptr_ + ithr * bgmmc_.zp_a_comp_elems_per_thr + n_blk_local * bgmmc_.zp_a_comp_shift_n; if (bgmmc_.blocked_B) { // Scale computed in reorder compensation values by zp_a value // locally just before usage. Using the single global scaling before // parallel section might produce significant overhead for small // problems running in multitreaded execution mode const int base_offset = n_blk_idx * bgmmc_.wei_n_blk; PRAGMA_OMP_SIMD() for (int b = 0; b < bgmmc_.wei_n_blk; b++) zp_comp[b] = -zero_point_a_negative_val_ * reorder_zp_a_comp_ptr_[base_offset + b]; } return zp_comp; } int32_t *get_zp_b_compensation_result_ptr(int ithr, int m_blk_idx) const { if (!bgmmc_.has_zero_point_b) return nullptr; const int m_blk_local = m_blk_idx % bgmmc_.M_chunk_size; return zero_point_b_compensations_ptr_ + ithr * bgmmc_.zp_b_comp_elems_per_thr + m_blk_local * bgmmc_.zp_b_comp_result_shift_m; } int32_t *get_zp_b_compensation_buffer_ptr(int ithr, int m_blk_idx) const { if (!bgmmc_.has_zero_point_b) return nullptr; const int m_blk_local = m_blk_idx % bgmmc_.M_chunk_size; return get_zp_b_compensation_result_ptr(ithr, 0) + bgmmc_.zp_b_comp_buffer_start + m_blk_local * bgmmc_.zp_b_comp_buffer_shift_m; } char *get_tile_workspace(int ithr) const { return is_amx_ ? wsp_tile_ptr_ + ithr * bgmmc_.wsp_tile_per_thr_bytes : nullptr; } const std::vector<const void *> &get_post_ops_binary_rhs_arg_vec() const { return post_ops_binary_rhs_arg_vec_; } int get_base_brgemm_kernel_idx() const { return base_brg_ker_idx_; } bool is_last_K_chunk(int k_chunk_idx) const { return k_chunk_idx == bgmmc_.K_chunks - 1; } int get_brgemm_batch_size(int k_chunk_idx) const { return is_last_K_chunk(k_chunk_idx) ? last_chunk_brgemm_batch_size_ : bgmmc_.brgemm_batch_size; } int get_parallel_work_amount() const { return parallel_work_amount_; } int get_num_threads_for_k() const { return nthr_k_; } bool parallel_reduction_is_used() const { return nthr_k_ > 1 && bgmmc_.K_chunks > 1; } int get_num_threads_for_bmn() const { return nthr_bmn_; } // ithr = ithr_k * nthr_bmn + ithr_bmn int get_thread_idx_for_k(int ithr) const { if (ithr >= num_threads_used_) return -1; const int ithr_k = ithr / nthr_bmn_; return ithr_k < bgmmc_.K_chunks ? ithr_k : -1; } int get_thread_idx_for_bmn(int ithr) const { if (ithr >= num_threads_used_) return -1; const int ithr_bmn = ithr % nthr_bmn_; return ithr_bmn < parallel_work_amount_ ? ithr_bmn : -1; } int get_num_threads_for_parallelization() const { return nthr_; } private: bool is_amx_; const brgemm_matmul_conf_t &bgmmc_; const char *data_A_ptr_; const char *data_B_ptr_; char *data_C_ptr_; brgemm_batch_element_t *batch_element_ptr_; char *buf_A_ptr_; char *buf_B_ptr_; char *buf_C_ptr_; char *wsp_tile_ptr_; const char *bias_ptr_; const float *oscales_ptr_; int32_t *s8s8_compensation_ptr_; int32_t *zero_point_a_compensations_ptr_; int32_t *zero_point_b_compensations_ptr_; int32_t *reorder_zp_a_comp_ptr_; int32_t zero_point_a_negative_val_; int32_t zero_point_b_negative_val_; int32_t zero_point_mixed_ab_compensation_component_; int32_t zero_point_c_val_; std::vector<const void *> post_ops_binary_rhs_arg_vec_; int base_brg_ker_idx_; int vnni_factor; // parallelization parameters int parallel_work_amount_; int nthr_, nthr_k_, nthr_bmn_, num_threads_used_; int last_chunk_brgemm_batch_size_; }; template struct brgemm_matmul_t<avx512_core_bf16_amx_int8>; template struct brgemm_matmul_t<avx512_core_bf16_amx_bf16>; template struct brgemm_matmul_t<avx512_core_bf16>; template struct brgemm_matmul_t<avx512_core_vnni>; template struct brgemm_matmul_t<avx512_core>; } // namespace matmul } // namespace x64 } // namespace cpu } // namespace impl } // namespace dnnl
43.205082
80
0.608943
cfRod
60d9059ece51cd24e336ac5ee1826e2a584293f4
307
hxx
C++
src/mod/pub/tst/sws/sws-drop-down-list-tst/mod-sws-drop-down-list-tst.hxx
indigoabstract/appplex
83c3b903db6c6ea83690ccffbd533ff6ab01d246
[ "MIT" ]
1
2017-12-26T14:29:37.000Z
2017-12-26T14:29:37.000Z
src/mod/pub/tst/sws/sws-drop-down-list-tst/mod-sws-drop-down-list-tst.hxx
indigoabstract/appplex
83c3b903db6c6ea83690ccffbd533ff6ab01d246
[ "MIT" ]
null
null
null
src/mod/pub/tst/sws/sws-drop-down-list-tst/mod-sws-drop-down-list-tst.hxx
indigoabstract/appplex
83c3b903db6c6ea83690ccffbd533ff6ab01d246
[ "MIT" ]
null
null
null
#pragma once #include "appplex-conf.hxx" #ifdef MOD_SWS_DROP_DOWN_LIST_TST #include "mws-mod.hxx" class mod_sws_drop_down_list_tst : public mws_mod { public: static mws_sp<mod_sws_drop_down_list_tst> nwi(); virtual void build_sws() override; private: mod_sws_drop_down_list_tst(); }; #endif
14.619048
51
0.765472
indigoabstract
60db821a92f86bbc26237642c9e518a42ace9403
5,349
cpp
C++
FECore/FEModelParam.cpp
Scriptkiddi/FEBioStudio
b4cafde6b2761c9184e7e66451a9555b81a8a3dc
[ "MIT" ]
null
null
null
FECore/FEModelParam.cpp
Scriptkiddi/FEBioStudio
b4cafde6b2761c9184e7e66451a9555b81a8a3dc
[ "MIT" ]
null
null
null
FECore/FEModelParam.cpp
Scriptkiddi/FEBioStudio
b4cafde6b2761c9184e7e66451a9555b81a8a3dc
[ "MIT" ]
null
null
null
/*This file is part of the FEBio source code and is licensed under the MIT license listed below. See Copyright-FEBio.txt for details. Copyright (c) 2021 University of Utah, The Trustees of Columbia University in the City of New York, and others. 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 "FEModelParam.h" #include "MObjBuilder.h" #include "FEDataArray.h" #include "DumpStream.h" #include "FEConstValueVec3.h" //--------------------------------------------------------------------------------------- FEModelParam::FEModelParam() { m_scl = 1.0; m_dom = 0; } FEModelParam::~FEModelParam() { } // serialization void FEModelParam::Serialize(DumpStream& ar) { ar & m_scl; } //--------------------------------------------------------------------------------------- FEParamDouble::FEParamDouble() { m_val = fecore_new<FEScalarValuator>("const", nullptr); } FEParamDouble::~FEParamDouble() { delete m_val; } FEParamDouble::FEParamDouble(const FEParamDouble& p) { m_val = p.m_val->copy(); m_scl = p.m_scl; m_dom = p.m_dom; } // set the value void FEParamDouble::operator = (double v) { FEConstValue* val = fecore_new<FEConstValue>("const", nullptr); *val->constValue() = v; setValuator(val); } // set the valuator void FEParamDouble::setValuator(FEScalarValuator* val) { if (m_val) delete m_val; m_val = val; if (val) val->SetModelParam(this); } // get the valuator FEScalarValuator* FEParamDouble::valuator() { return m_val; } // is this a const value bool FEParamDouble::isConst() const { return m_val->isConst(); }; // get the const value (returns 0 if param is not const) double& FEParamDouble::constValue() { assert(isConst()); return *m_val->constValue(); } double FEParamDouble::constValue() const { assert(isConst()); return *m_val->constValue(); } void FEParamDouble::Serialize(DumpStream& ar) { FEModelParam::Serialize(ar); ar & m_val; } bool FEParamDouble::Init() { return (m_val ? m_val->Init() : true); } //--------------------------------------------------------------------------------------- FEParamVec3::FEParamVec3() { m_val = fecore_new<FEVec3dValuator>("vector", nullptr); } FEParamVec3::~FEParamVec3() { delete m_val; } FEParamVec3::FEParamVec3(const FEParamVec3& p) { m_val = p.m_val->copy(); m_scl = p.m_scl; m_dom = p.m_dom; } // set the value void FEParamVec3::operator = (const vec3d& v) { FEConstValueVec3* val = fecore_new<FEConstValueVec3>("vector", nullptr); val->value() = v; setValuator(val); } // set the valuator void FEParamVec3::setValuator(FEVec3dValuator* val) { if (m_val) delete m_val; m_val = val; if (val) val->SetModelParam(this); } void FEParamVec3::Serialize(DumpStream& ar) { FEModelParam::Serialize(ar); ar & m_val; } //========================================================================== FEParamMat3d::FEParamMat3d() { m_val = fecore_new<FEMat3dValuator>("const", nullptr); } FEParamMat3d::~FEParamMat3d() { delete m_val; } FEParamMat3d::FEParamMat3d(const FEParamMat3d& p) { m_val = p.m_val->copy(); m_scl = p.m_scl; m_dom = p.m_dom; } // set the value void FEParamMat3d::operator = (const mat3d& v) { FEConstValueMat3d* val = fecore_new<FEConstValueMat3d>("const", nullptr); val->value() = v; setValuator(val); } // set the valuator void FEParamMat3d::setValuator(FEMat3dValuator* val) { if (m_val) delete m_val; m_val = val; if (val) val->SetModelParam(this); } // get the valuator FEMat3dValuator* FEParamMat3d::valuator() { return m_val; } void FEParamMat3d::Serialize(DumpStream& ar) { FEModelParam::Serialize(ar); ar & m_val; } //========================================================================== FEParamMat3ds::FEParamMat3ds() { m_val = fecore_new<FEMat3dsValuator>("const", nullptr); } FEParamMat3ds::~FEParamMat3ds() { delete m_val; } FEParamMat3ds::FEParamMat3ds(const FEParamMat3ds& p) { m_val = p.m_val->copy(); m_scl = p.m_scl; m_dom = p.m_dom; } // set the value void FEParamMat3ds::operator = (const mat3ds& v) { FEConstValueMat3ds* val = fecore_new<FEConstValueMat3ds>("const", nullptr); val->value() = v; setValuator(val); } // set the valuator void FEParamMat3ds::setValuator(FEMat3dsValuator* val) { if (m_val) delete m_val; m_val = val; if (val) val->SetModelParam(this); } void FEParamMat3ds::Serialize(DumpStream& ar) { FEModelParam::Serialize(ar); ar & m_val; }
22.56962
92
0.673584
Scriptkiddi
60dc566e97861e559e5f744a595e973d2fd05a11
7,141
cc
C++
tensorflow/compiler/mlir/xla/transforms/legalize_tf_control_flow.cc
5GApp/tensorflow
ca87089f9e0073bad9fc999ce9c318f661d2e425
[ "Apache-2.0" ]
1
2019-12-23T20:23:43.000Z
2019-12-23T20:23:43.000Z
tensorflow/compiler/mlir/xla/transforms/legalize_tf_control_flow.cc
5GApp/tensorflow
ca87089f9e0073bad9fc999ce9c318f661d2e425
[ "Apache-2.0" ]
null
null
null
tensorflow/compiler/mlir/xla/transforms/legalize_tf_control_flow.cc
5GApp/tensorflow
ca87089f9e0073bad9fc999ce9c318f661d2e425
[ "Apache-2.0" ]
1
2020-04-22T01:47:46.000Z
2020-04-22T01:47:46.000Z
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // This file implements logic for lowering TensorFlow dialect's control flow to // the XLA dialect. #include <cstddef> #include <cstdint> #include <iterator> #include <numeric> #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/StringSet.h" #include "llvm/ADT/iterator_range.h" #include "mlir/Dialect/StandardOps/Ops.h" // TF:local_config_mlir #include "mlir/IR/Attributes.h" // TF:local_config_mlir #include "mlir/IR/BlockAndValueMapping.h" // TF:local_config_mlir #include "mlir/IR/Function.h" // TF:local_config_mlir #include "mlir/IR/MLIRContext.h" // TF:local_config_mlir #include "mlir/IR/Module.h" // TF:local_config_mlir #include "mlir/IR/Operation.h" // TF:local_config_mlir #include "mlir/IR/StandardTypes.h" // TF:local_config_mlir #include "mlir/IR/TypeUtilities.h" // TF:local_config_mlir #include "mlir/IR/Types.h" // TF:local_config_mlir #include "mlir/Pass/Pass.h" // TF:local_config_mlir #include "mlir/Pass/PassRegistry.h" // TF:local_config_mlir #include "mlir/Transforms/DialectConversion.h" // TF:local_config_mlir #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" #include "tensorflow/compiler/mlir/xla/ir/hlo_ops.h" #include "tensorflow/compiler/mlir/xla/transforms/passes.h" #include "tensorflow/core/util/tensor_format.h" using mlir::PassRegistration; namespace mlir { namespace xla_hlo { namespace { class LegalizeTFControlFlow : public ModulePass<LegalizeTFControlFlow> { public: void runOnModule() override; }; } // namespace std::unique_ptr<mlir::OpPassBase<mlir::ModuleOp>> createLegalizeTFControlFlowPass() { return std::make_unique<LegalizeTFControlFlow>(); } namespace { void Detuple(ValuePtr tuple, Operation::result_range replace, OpBuilder* builder) { // De-tuple the results of the xla hlo conditional result. for (auto result_it : llvm::enumerate(replace)) { auto get_tuple_value = builder->create<xla_hlo::GetTupleElementOp>( result_it.value()->getLoc(), tuple, result_it.index()); result_it.value()->replaceAllUsesWith(get_tuple_value); } } // Imports the source region into the destination region. The XLA conditional // operation only supports one argument per branch. Therefore any branch that // requires additional arguments requires their values be tupled together. Then, // to support multiple returns (as XLA only supports a single return value) the // results of the conditional are tupled together. void ImportXlaRegion(mlir::FuncOp func, Region* dest_region, Location loc, bool tuple_return = true) { BlockAndValueMapping mapper; OpBuilder builder(dest_region); auto entry_block = builder.createBlock(dest_region); auto tuple_arg = entry_block->addArgument( builder.getTupleType(func.getType().getInputs())); llvm::SmallVector<ValuePtr, 4> detupled_args; detupled_args.reserve(func.getNumArguments()); for (int64_t i = 0, s = func.getNumArguments(); i < s; i++) { auto extract = builder.create<GetTupleElementOp>(loc, tuple_arg, i); detupled_args.push_back(extract); } auto result = builder.create<CallOp>(loc, func, detupled_args).getResults(); if (!tuple_return) { builder.create<xla_hlo::ReturnOp>(loc, result); } else { auto tuple_op = builder.create<TupleOp>(loc, result); builder.create<xla_hlo::ReturnOp>(loc, tuple_op.getResult()); } } void LowerIf(TF::IfOp op, ModuleOp module) { Location loc = op.getLoc(); OpBuilder builder(op); // XLA prefers tuple arguments for control flow due to XLA not supporting // multiple return values. SmallVector<ValuePtr, 3> inputs(op.input()); builder.setInsertionPoint(op); auto tuple_input = builder.create<xla_hlo::TupleOp>(loc, inputs); // Create the new conditional op with tuple inputs. SmallVector<ValuePtr, 3> operands(op.getOperands()); SmallVector<Type, 4> types(op.getResultTypes()); auto result_type = builder.getTupleType(types); auto conditional = builder.create<xla_hlo::ConditionalOp>( loc, result_type, op.cond(), tuple_input, tuple_input); // Import the regions for both the true and false cases. These regions // must be updated to tuple the return results together and use the xla hlo // return op. BlockAndValueMapping mapper; auto then_branch = module.lookupSymbol<mlir::FuncOp>(op.then_branch()); auto else_branch = module.lookupSymbol<mlir::FuncOp>(op.else_branch()); ImportXlaRegion(then_branch, &conditional.true_branch(), loc); ImportXlaRegion(else_branch, &conditional.false_branch(), loc); // De-tuple the results of the xla hlo conditional result. builder.setInsertionPointAfter(op); Detuple(conditional.getResult(), op.getResults(), &builder); op.erase(); } void LowerWhile(TF::WhileOp op, ModuleOp module) { Location loc = op.getLoc(); OpBuilder builder(op); // XLA prefers tuple arguments for control flow due to XLA not supporting // multiple return values. SmallVector<ValuePtr, 3> inputs(op.input()); builder.setInsertionPoint(op); ValuePtr tuple_input = builder.create<xla_hlo::TupleOp>(loc, inputs); // Create the new while op with tuple inputs. SmallVector<ValuePtr, 3> operands(op.getOperands()); SmallVector<Type, 4> types(op.getResultTypes()); auto while_op = builder.create<xla_hlo::WhileOp>( loc, builder.getTupleType(types), tuple_input); // Import the regions for both the cond and body. These regions must be // updated to tuple the return results together and use the xla hlo return op. auto body_branch = module.lookupSymbol<mlir::FuncOp>(op.body()); auto cond_branch = module.lookupSymbol<mlir::FuncOp>(op.cond()); ImportXlaRegion(body_branch, &while_op.body(), loc); ImportXlaRegion(cond_branch, &while_op.cond(), loc, /*tuple_return=*/false); // De-tuple the results of the xla hlo while. builder.setInsertionPointAfter(op); Detuple(while_op.getResult(), op.getResults(), &builder); op.erase(); } } // namespace void LegalizeTFControlFlow::runOnModule() { auto module = getModule(); module.walk([&](TF::WhileOp op) -> void { LowerWhile(op, module); }); module.walk([&](TF::IfOp op) -> void { LowerIf(op, module); }); } } // namespace xla_hlo } // namespace mlir static PassRegistration<mlir::xla_hlo::LegalizeTFControlFlow> cfpass( "xla-legalize-tf-control-flow", "Legalize TensorFlow control flow to the XLA dialect");
39.236264
80
0.734071
5GApp
60e185b99620b37ab58388bc558cc2db494aaa54
7,909
cpp
C++
Libraries/Editor/PropertyView.cpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
1
2019-07-13T03:36:11.000Z
2019-07-13T03:36:11.000Z
Libraries/Editor/PropertyView.cpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
Libraries/Editor/PropertyView.cpp
RyanTylerRae/WelderEngineRevamp
3efdad59dd1821ddb1c09b59520e8e2d7023bb10
[ "MIT" ]
null
null
null
// MIT Licensed (see LICENSE.md). #include "Precompiled.hpp" namespace Zero { namespace PropertyViewUi { const cstr cLocation = "EditorUi/PropertyView"; Tweakable(float, ObjectSize, Pixels(24), cLocation); // Size of objects Tweakable(float, PropertySize, Pixels(20), cLocation); // Size of each property widget Tweakable(float, PropertySpacing, Pixels(2), cLocation); // Pixels in between each property Tweakable(float, IndentSize, Pixels(10), cLocation); // Indent per level } // namespace PropertyViewUi namespace Events { DefineEvent(NameActivated); DefineEvent(OpenAdd); } // namespace Events ZilchDefineType(PropertyView, builder, type) { ZilchBindOverloadedMethod(SetObject, ZilchInstanceOverload(void, Object*)); ZilchBindMethod(Refresh); ZilchBindMethod(Invalidate); ZilchBindMethod(ActivateAutoUpdate); } PropertyView::PropertyView(Composite* parent) : Composite(parent), mFixedHeight(false) { mScrollArea = new ScrollArea(this); mScrollArea->SetClientSize(Pixels(10, 10)); mScrollArea->DisableScrollBar(0); mMinSize = Vec2(100, 100); mNamePercent = 0.42f; mDefSet = parent->GetDefinitionSet()->GetDefinitionSet("PropertyGrid"); mRoot = nullptr; mPropertyInterface = nullptr; SetPropertyInterface(&mDefaultPropertyInterface); ConnectThisTo(this, Events::KeyDown, OnKeyDown); ConnectThisTo(MetaDatabase::GetInstance(), Events::MetaModified, OnMetaModified); } PropertyView::~PropertyView() { } void PropertyView::DisconnectAllObjects() { // Disconnect from all old objects forRange (HandleParam oldObject, mSelectedObjects.All()) { // Disconnect if the handle is a valid Object if (Object* object = oldObject.Get<Object*>()) if (EventDispatcher* dispatcher = object->GetDispatcherObject()) dispatcher->Disconnect(this); } } Handle PropertyView::GetObject() { return mSelectedObject; } void PropertyView::Invalidate() { this->MarkAsNeedsUpdate(); // We need to release handles in case of meta changing. See the comment // above ObjectPropertyNode::ReleaseHandles if (mRoot) mRoot->mNode->ReleaseHandles(); // Destroy the tree SafeDestroy(mRoot); mSelectedObjects.Clear(); // Clear the additional widgets forRange (Widget* widget, mAddtionalWidgets.All()) widget->Destroy(); mAddtionalWidgets.Clear(); } void PropertyView::Rebuild() { Handle instance = GetObject(); if (instance.IsNotNull()) { // SafeDelete(mRootObjectNode); auto rootObjectNode = mPropertyInterface->BuildObjectTree(nullptr, instance); if (rootObjectNode == nullptr) return; PropertyWidgetInitializer initializer; initializer.Instance = instance; initializer.Grid = this; initializer.Parent = mScrollArea->GetClientWidget(); initializer.Property = nullptr; initializer.CurrentInterface = mPropertyInterface; initializer.ObjectNode = rootObjectNode; // Create and open the root node PropertyWidgetObject* node = new PropertyWidgetObject(initializer, nullptr); mRoot = node; mRoot->OpenNode(false); mRoot->UpdateTransformExternal(); } Refresh(); } void PropertyView::SetObject(HandleParam newObject, PropertyInterface* newInterface) { DisconnectAllObjects(); // We no longer care about the old objects mSelectedObjects.Clear(); // If it's not a valid object, just rebuild the tree with nothing in it if (newObject.IsNull()) { // not a valid object clear the grid. mSelectedObject = Handle(); Invalidate(); return; } // Store the handle mSelectedObject = newObject; // Set the property interface without rebuilding the tree (we're going // to rebuild it again in a second) SetPropertyInterface(newInterface); // We need to know when a component has changed on one of the objects // we have selected in order to properly rebuild the tree mPropertyInterface->GetObjects(newObject, mSelectedObjects); forRange (Handle object, mSelectedObjects.All()) { // Connect if handle is a valid Object if (Object* objectPointer = object.Get<Object*>()) { if (EventDispatcher* dispatcher = objectPointer->GetDispatcherObject()) { Connect(objectPointer, Events::ComponentsModified, this, &ZilchSelf::OnInvalidate, ConnectNotify::Ignore); Connect(objectPointer, Events::ObjectStructureModified, this, &ZilchSelf::OnInvalidate, ConnectNotify::Ignore); } } } // Refresh and rebuild. Invalidate(); } void PropertyView::SetObject(Object* object) { PropertyView::SetObject(Handle(object)); } void PropertyView::UpdateTransform() { mScrollArea->SetSize(mSize); if (mDestroyed) return; if (mRoot == nullptr) Rebuild(); if (mRoot) { float rootHeight = mRoot->GetSize().y; // Subtract the width if the scroll bar is active float width = mSize.x; if (rootHeight > mSize.y) width -= mScrollArea->GetScrollBarSize(); // If there is extra height use if for layouts float height = Math::Max(mSize.y, rootHeight); // Resize root widget with adjusted width mRoot->SetSize(Vec2(width, rootHeight)); // Size client widget in case of layouts mScrollArea->GetClientWidget()->SetSize(Vec2(width, height)); mScrollArea->SetClientSize(Vec2(width, height)); } else { // Nothing selected reset the mScrollArea->SetClientSize(Vec2(10, 10)); } Composite::UpdateTransform(); } void PropertyView::SizeToContents() { UpdateTransform(); ReturnIf(mRoot == nullptr, , "No valid on object selected on property grid. Size will be invalid"); Vec2 sizeNeeded = mRoot->GetSize(); this->SetSize(sizeNeeded); } Vec2 PropertyView::GetMinSize() { if (mRoot && mFixedHeight) return Vec2(mMinSize.x, mRoot->GetSize().y); else return mMinSize; } void PropertyView::ActivateAutoUpdate() { ConnectThisTo(this->GetRootWidget(), Events::WidgetUpdate, OnWidgetUpdate); } void PropertyView::Refresh() { // Is the object still valid? Handle instance = GetObject(); if (instance.IsNotNull()) { if (mRoot == nullptr) { Rebuild(); } else { mRoot->Refresh(); mRoot->MarkAsNeedsUpdate(); } } else { // Object is lost, clear the tree if (mRoot != nullptr) Invalidate(); } } void PropertyView::SetPropertyInterface(PropertyInterface* propInterface, bool rebuild) { mPropertyInterface = propInterface; // Use the default if none was specified if (mPropertyInterface == nullptr) mPropertyInterface = &mDefaultPropertyInterface; mPropertyInterface->mPropertyGrid = this; if (rebuild) Invalidate(); } void PropertyView::AddCustomPropertyIcon(CustomIconCreatorFunction callback, void* clientData) { // If it's already in the array, no need to add it if (mCustomIconCallbacks.Contains(callback)) return; // Insert the client data mCallbackClientData[(void*)callback] = clientData; mCustomIconCallbacks.PushBack(callback); Invalidate(); Rebuild(); } void PropertyView::RemoveCustomPropertyIcon(CustomIconCreatorFunction callback) { if (!mCustomIconCallbacks.Contains(callback)) return; mCustomIconCallbacks.EraseValueError(callback); mCallbackClientData.Erase((void*)callback); Invalidate(); Rebuild(); } void PropertyView::OnWidgetUpdate(UpdateEvent* update) { // Only refresh if the property grid is active (could be hidden behind a tab) if (GetGlobalActive()) Refresh(); } void PropertyView::OnInvalidate(Event* e) { Invalidate(); } void PropertyView::OnKeyDown(KeyboardEvent* e) { if (!e->CtrlPressed) return; if (e->Key == Keys::Z) { mPropertyInterface->Undo(); e->Handled = true; } else if (e->Key == Keys::Y) { mPropertyInterface->Redo(); e->Handled = true; } } void PropertyView::OnMetaModified(MetaLibraryEvent* e) { Invalidate(); } } // namespace Zero
24.335385
119
0.706916
RyanTylerRae
60e2788527ed01a599fa809c6a1f49167236d0aa
486
cpp
C++
app/comm/timer.cpp
ligavin/udt_server
c4a21497136bad53b915d3eb3d99f0ad07426e66
[ "BSD-3-Clause" ]
null
null
null
app/comm/timer.cpp
ligavin/udt_server
c4a21497136bad53b915d3eb3d99f0ad07426e66
[ "BSD-3-Clause" ]
null
null
null
app/comm/timer.cpp
ligavin/udt_server
c4a21497136bad53b915d3eb3d99f0ad07426e66
[ "BSD-3-Clause" ]
null
null
null
/* * timer.cpp * * Created on: 2015年9月3日 * Author: gavinlli */ #include "timer.h" #include <stdio.h> timer::timer() { // TODO Auto-generated constructor stub start(); } timer::~timer() { // TODO Auto-generated destructor stub } void timer::start() { gettimeofday( &m_start, NULL); } int timer::get_time() { struct timeval end; gettimeofday( &end, NULL); int timeuse = (end.tv_sec - m_start.tv_sec ) * 1000000 + (end.tv_usec - m_start.tv_usec); return timeuse; }
15.1875
90
0.654321
ligavin
60e4f5770fc568b86fcf87e11b9894989b363963
5,326
cpp
C++
test/integration/acceptance/create_account_test.cpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
test/integration/acceptance/create_account_test.cpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
test/integration/acceptance/create_account_test.cpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include <gtest/gtest.h> #include "framework/integration_framework/integration_test_framework.hpp" #include "integration/acceptance/acceptance_fixture.hpp" using namespace integration_framework; using namespace shared_model; using namespace common_constants; class CreateAccount : public AcceptanceFixture { public: auto makeUserWithPerms(const interface::RolePermissionSet &perms = { interface::permissions::Role::kCreateAccount}) { return AcceptanceFixture::makeUserWithPerms(perms); } const std::string kNewUser = "userone"; const crypto::Keypair kNewUserKeypair = crypto::DefaultCryptoAlgorithmType::generateKeypair(); }; /** * @given some user with can_create_account permission * @when execute tx with CreateAccount command * @then there is the tx in proposal */ TEST_F(CreateAccount, Basic) { IntegrationTestFramework(1) .setInitialState(kAdminKeypair) .sendTx(makeUserWithPerms()) .skipProposal() .skipBlock() .sendTxAwait( complete(baseTx().createAccount( kNewUser, kDomain, kNewUserKeypair.publicKey())), [](auto &block) { ASSERT_EQ(block->transactions().size(), 1); }); } /** * @given some user without can_create_account permission * @when execute tx with CreateAccount command * @then verified proposal is empty */ TEST_F(CreateAccount, NoPermissions) { IntegrationTestFramework(1) .setInitialState(kAdminKeypair) .sendTx(makeUserWithPerms({interface::permissions::Role::kGetMyTxs})) .skipProposal() .skipVerifiedProposal() .skipBlock() .sendTx(complete(baseTx().createAccount( kNewUser, kDomain, kNewUserKeypair.publicKey()))) .skipProposal() .checkVerifiedProposal( [](auto &proposal) { ASSERT_EQ(proposal->transactions().size(), 0); }) .checkBlock( [](auto block) { ASSERT_EQ(block->transactions().size(), 0); }); } /** * @given some user with can_create_account permission * @when execute tx with CreateAccount command with nonexistent domain * @then verified proposal is empty */ TEST_F(CreateAccount, NoDomain) { const std::string nonexistent_domain = "asdf"; IntegrationTestFramework(1) .setInitialState(kAdminKeypair) .sendTx(makeUserWithPerms()) .skipProposal() .skipVerifiedProposal() .skipBlock() .sendTx(complete(baseTx().createAccount( kNewUser, nonexistent_domain, kNewUserKeypair.publicKey()))) .skipProposal() .checkVerifiedProposal( [](auto &proposal) { ASSERT_EQ(proposal->transactions().size(), 0); }) .checkBlock( [](auto block) { ASSERT_EQ(block->transactions().size(), 0); }); } /** * @given some user with can_create_account permission * @when execute tx with CreateAccount command with already existing username * @then verified proposal is empty */ TEST_F(CreateAccount, ExistingName) { std::string existing_name = kUser; IntegrationTestFramework(1) .setInitialState(kAdminKeypair) .sendTx(makeUserWithPerms()) .skipProposal() .skipVerifiedProposal() .skipBlock() .sendTx(complete(baseTx().createAccount( existing_name, kDomain, kNewUserKeypair.publicKey()))) .skipProposal() .checkVerifiedProposal( [](auto &proposal) { ASSERT_EQ(proposal->transactions().size(), 0); }) .checkBlock( [](const auto block) { ASSERT_EQ(block->transactions().size(), 0); }); } /** * @given some user with can_create_account permission * @when execute tx with CreateAccount command with maximum available length * @then there is the tx in proposal */ TEST_F(CreateAccount, MaxLenName) { IntegrationTestFramework(1) .setInitialState(kAdminKeypair) .sendTx(makeUserWithPerms()) .skipProposal() .skipBlock() .sendTxAwait( complete(baseTx().createAccount( std::string(32, 'a'), kDomain, kNewUserKeypair.publicKey())), [](auto &block) { ASSERT_EQ(block->transactions().size(), 1); }); } /** * @given some user with can_create_account permission * @when execute tx with CreateAccount command with too long length * @then the tx hasn't passed stateless validation * (aka skipProposal throws) */ TEST_F(CreateAccount, TooLongName) { IntegrationTestFramework(1) .setInitialState(kAdminKeypair) .sendTx(makeUserWithPerms()) .skipProposal() .skipBlock() .sendTx(complete(baseTx().createAccount( std::string(33, 'a'), kDomain, kNewUserKeypair.publicKey())), CHECK_STATELESS_INVALID); } /** * @given some user with can_create_account permission * @when execute tx with CreateAccount command with empty user name * @then the tx hasn't passed stateless validation * (aka skipProposal throws) */ TEST_F(CreateAccount, EmptyName) { std::string empty_name = ""; IntegrationTestFramework(1) .setInitialState(kAdminKeypair) .sendTx(makeUserWithPerms()) .skipProposal() .skipBlock() .sendTx(complete(baseTx().createAccount( empty_name, kDomain, kNewUserKeypair.publicKey())), CHECK_STATELESS_INVALID); }
33.496855
80
0.68344
coderintherye
60eadec343c01187f38466d14ec8d8a7cd56cdfc
18,616
cpp
C++
app/src/main/jni/src/main.cpp
zimspy007/Funda-Ndebele-ECD-App
d2df5ff54e1cc482870ff7b0b08e89898ed25645
[ "BSD-3-Clause" ]
1
2019-10-12T12:07:01.000Z
2019-10-12T12:07:01.000Z
app/src/main/jni/src/main.cpp
zimspy007/Funda-Ndebele-ECD-App
d2df5ff54e1cc482870ff7b0b08e89898ed25645
[ "BSD-3-Clause" ]
null
null
null
app/src/main/jni/src/main.cpp
zimspy007/Funda-Ndebele-ECD-App
d2df5ff54e1cc482870ff7b0b08e89898ed25645
[ "BSD-3-Clause" ]
1
2019-12-04T17:45:29.000Z
2019-12-04T17:45:29.000Z
#include "game_code/puzzle_data.hpp" #include "game_code/game.hpp" #include "game_code/grid.hpp" #include "game_code/card.hpp" #include "game_code/puzzle.hpp" #include "game_code/alien.hpp" #include "game_code/walking_alien.hpp" #include "game_code/black_bird.hpp" #include "game_code/butterfly.hpp" #include "game_code/pink_tree.hpp" #include "game_code/firework.hpp" #include "game_code/button.hpp" #ifdef __ANDROID__ #endif //__ANDROID__ /*amount of fireworks to use for fireworks effect*/ #define AMOUNT 18 /*destroys sdl textures and frees up memory*/ void destroyTextures(); /*loads all media into memory, returns true if successful*/ bool loadmedia(); void processInput(SDL_Point _point); bool showFireworks = false; /*pointer to the game object*/ Game *game; /*the camera object. used to project screen to a specific rect but only useful for scrolling screens*/ Camera cam; Grid grid; GTexture bgTex; GTexture forestbg; GTexture scrnTex; GTexture schoolTex; GTexture creditsTex; Card clickCard; Alien alien; WalkingAlien walkingalien; Butterfly bfly; BlackBird blackbird; PinkTree pinktree; PinkTree greentree; int MAX_LEVEL = 45; int puzzles_index = 0; Puzzle currPuzzle, oldPuzzle; int puzzleCounter = 0; bool updatePuzzle = false; Button btnquit; Button btninfo; Button btnPlay; Mix_Chunk *eff_help; Mix_Chunk *eff_hello; Mix_Chunk *eff_tools; Mix_Chunk *eff_correct; Mix_Chunk *eff_retry; mFirework fire[AMOUNT]; const int GAME_STATE_MENU = 10; const int GAME_STATE_CREDITS = 20; const int GAME_STATE_LOADING = 30; const int GAME_STATE_EXITING = 40; const int GAME_STATE_3PUZZLE = 50; int GAME_STATE = GAME_STATE_MENU; int main(int argc, char *argv[]) { game = new Game(); grid = Grid(game->getScrnW(), game->getScrnH()); cam = Camera(game->getScrnW(), game->getScrnH()); std::random_shuffle(puzzles, puzzles + sizeof(puzzles) / sizeof(puzzles[0])); //load game stuff here if (!loadmedia()) exit(2); //Center the camera over the screen cam.camRect.x = 0; cam.camRect.y = 0; game->runGame(); destroyTextures(); game->shutdown(); exit(0); } void destroyTextures() { bgTex.destroyTex(); forestbg.destroyTex(); scrnTex.destroyTex(); schoolTex.destroyTex(); creditsTex.destroyTex(); clickCard.getTex()->destroyTex(); currPuzzle.dispose(); alien.dispose(); walkingalien.dispose(); bfly.dispose(); blackbird.dispose(); pinktree.dispose(); greentree.dispose(); for (int i = 0; i < AMOUNT; i++) { fire[i].destroyFirework(); } btnPlay.disposeTex(); btnquit.disposeTex(); btninfo.disposeTex(); Mix_FreeChunk(eff_hello); Mix_FreeChunk(eff_help); Mix_FreeChunk(eff_tools); Mix_FreeChunk(eff_correct); Mix_FreeChunk(eff_retry); } /*implementation of global function declared in game.cpp*/ void updateGame(float deltaTime) { switch (GAME_STATE) { case GAME_STATE_MENU: bfly.update(deltaTime, game->getScrnW(), game->getScrnH()); blackbird.update(deltaTime, game->getScrnW(), game->getScrnH()); pinktree.update(150); greentree.update(265); break; case GAME_STATE_CREDITS: alien.update(); break; case GAME_STATE_LOADING: if (walkingalien.getTex()->getTexRect()->x < game->getScrnW()) { walkingalien.setPos(walkingalien.getTex()->getTexRect()->x + 2, walkingalien.getTex()->getTexRect()->y); } else { GAME_STATE = GAME_STATE_3PUZZLE; Mix_PlayChannel(-1, eff_help, 0); } walkingalien.update(); break; case GAME_STATE_EXITING: if (walkingalien.getTex()->getTexRect()->x > 0) { walkingalien.setPos(walkingalien.getTex()->getTexRect()->x - 2, walkingalien.getTex()->getTexRect()->y); } else { GAME_STATE = GAME_STATE_MENU; } walkingalien.update(); break; case GAME_STATE_3PUZZLE: if (showFireworks) { for (int i = 0; i < AMOUNT; i++) { fire[i].updateFirework(); } } alien.update(); if (updatePuzzle) { puzzleCounter++; if (puzzleCounter == 275) { updatePuzzle = false; puzzleCounter = 0; showFireworks = false; clickCard.setPos(grid.getUpperpos2().x, grid.getUpperpos2().y); puzzles_index++; if (puzzles_index < MAX_LEVEL + 1) { oldPuzzle = currPuzzle; Puzzle puzzle = Puzzle(game->getRenderer(), &grid, puzzles[puzzles_index]); currPuzzle = puzzle; oldPuzzle.dispose(); eff_help = Mix_LoadWAV(puzzle.getPuzzleSound().c_str()); } else { puzzles_index = 0; oldPuzzle = currPuzzle; Puzzle puzzle = Puzzle(game->getRenderer(), &grid, puzzles[puzzles_index]); currPuzzle = puzzle; oldPuzzle.dispose(); eff_help = Mix_LoadWAV(puzzle.getPuzzleSound().c_str()); } /*Use puzzleType to play a sound and introduce the puzzle*/ Mix_PlayChannel(-1, eff_help, 0); } } break; default: break; } } /*implementation of global function declared in game.cpp*/ void drawGame() { switch (GAME_STATE) { case GAME_STATE_MENU: forestbg.draw(game->getRenderer(), forestbg.getTexRect(), &cam.camRect, 0.0f); pinktree.draw(game->getRenderer(), &cam.camRect); greentree.draw(game->getRenderer(), &cam.camRect); btnPlay.draw(game->getRenderer(), &cam.camRect); bfly.draw(game->getRenderer(), &cam.camRect); blackbird.draw(game->getRenderer(), &cam.camRect); btninfo.draw(game->getRenderer(), &cam.camRect); btnquit.draw(game->getRenderer(), &cam.camRect); break; case GAME_STATE_CREDITS: creditsTex.draw(game->getRenderer(), creditsTex.getTexRect(), &cam.camRect, 0.0f); alien.draw(game->getRenderer(), &cam.camRect); break; case GAME_STATE_LOADING: schoolTex.draw(game->getRenderer(), schoolTex.getTexRect(), &cam.camRect, 0.0f); walkingalien.draw(game->getRenderer(), &cam.camRect); break; case GAME_STATE_EXITING: schoolTex.draw(game->getRenderer(), schoolTex.getTexRect(), &cam.camRect, 0.0f); walkingalien.draw(game->getRenderer(), &cam.camRect, -1); break; case GAME_STATE_3PUZZLE: bgTex.draw(game->getRenderer(), bgTex.getTexRect(), &cam.camRect, 0.0f); scrnTex.draw(game->getRenderer(), scrnTex.getTexRect(), &cam.camRect, 0.0f); alien.draw(game->getRenderer(), &cam.camRect); currPuzzle.draw(game->getRenderer(), &cam.camRect); clickCard.draw(game->getRenderer(), &cam.camRect); if (showFireworks) { // for (int i = 0; i < AMOUNT; i++) { fire[i].sketchFirework(game->getRenderer(), &cam.camRect); } } break; default: break; } } bool loadmedia() { bool success = false; schoolTex = GTexture(game->getRenderer(), "media/images/school.png", 0.0f); schoolTex.setupRect(0, 0, game->getScrnW(), game->getScrnH()); bgTex = GTexture(game->getRenderer(), "media/images/winter_bg.png", 0.0f); bgTex.setupRect(0, 0, game->getScrnW(), game->getScrnH()); forestbg = GTexture(game->getRenderer(), "media/images/forest.jpg", 0.0f); forestbg.setupRect(0, 0, game->getScrnW(), game->getScrnH()); creditsTex = GTexture(game->getRenderer(), "media/images/credits.png", 0.0f); creditsTex.setupRect(0, 0, game->getScrnW(), game->getScrnH()); scrnTex = GTexture(game->getRenderer(), "media/images/screen.png", 0.0f); float scrW = float(game->getScrnW() * 0.975f); float scrH = float(game->getScrnH() * 0.975f); int scrX = (game->getScrnW() / 2) - (scrW / 2); int scrY = (game->getScrnH() / 2) - (scrH / 2); scrnTex.setupRect(scrX, scrY, scrW, scrH); clickCard = Card(game->getRenderer(), &grid, "media/images/clickcard.png"); clickCard.setPos(grid.getUpperpos2().x, grid.getUpperpos2().y); //calculate image rect dimensions /*int cardW = 400, cardH = 400; float cardDimens = grid.getCardwidth();*/ float imgScale = float(grid.getCardwidth() / clickCard.getTex()->getTextureW()); alien = Alien(game->getRenderer(), "media/images/alien/alien_idle.png", imgScale * 213, imgScale * 400); alien.setPos(0, game->getScrnH() - (imgScale * 400)); walkingalien = WalkingAlien(game->getRenderer(), "media/images/alien/alien_walk.png", imgScale * 176, imgScale * 430); walkingalien.setPos(0, game->getScrnH() - (imgScale * 430)); bfly = Butterfly(game->getRenderer(), "media/images/butterfly/butterfly.png", imgScale * 70, imgScale * 70); bfly.setPos(0, /*game->getScrnW()*/ 100); blackbird = BlackBird(game->getRenderer(), "media/images/birds/black_bird.png", imgScale * 180, imgScale * 120); blackbird.setPos(0, /*game->getScrnW()*/ 100); pinktree = PinkTree(game->getRenderer(), "media/images/trees/pink_tree.png", (imgScale * 271) * 3, (imgScale * 240) * 3); pinktree.setPos(0, (game->getScrnH() - (imgScale * 240 * 3))); greentree = PinkTree(game->getRenderer(), "media/images/trees/green_tree.png", (imgScale * 271) * 2.75f, (imgScale * 240) * 2.75f); greentree.setPos(game->getScrnW() - (((imgScale * 271) * 3.25f)), (game->getScrnH() - (imgScale * 240 * 2.75f))); currPuzzle = Puzzle(game->getRenderer(), &grid, puzzles[puzzles_index]); btnPlay = Button(game->getRenderer(), "media/ui/play.png", grid.getCardwidth(), grid.getCardheight()); btnPlay.setPos(grid.getUpperpos2()); btnquit = Button(game->getRenderer(), "media/ui/quit.png", imgScale * 128, imgScale * 128); SDL_Vector _pos325 = SDL_Vector(game->getScrnW() - (imgScale * 128), 0, 0); btnquit.setPos(_pos325); btninfo = Button(game->getRenderer(), "media/ui/info.png", imgScale * 128, imgScale * 128); SDL_Vector _pos335 = SDL_Vector(btnPlay.getPos().x + (btnPlay.getBtnRect()->w / 2), btnPlay.getPos().y + (btnPlay.getBtnRect()->h + 28), 0); btninfo.setPos(_pos335); if (bgTex.getTex() != NULL) { success = true; } eff_help = Mix_LoadWAV(currPuzzle.getPuzzleSound().c_str()); eff_hello = Mix_LoadWAV("media/sounds/hello.ogg"); eff_tools = Mix_LoadWAV("media/sounds/hello.ogg"); eff_correct = Mix_LoadWAV("media/sounds/bing.ogg"); eff_retry = Mix_LoadWAV("media/sounds/no.ogg"); Mix_PlayChannel(-1, eff_hello, 0); for (int n = 0; n < AMOUNT; n++) { fire[n] = mFirework(game->getRenderer(), game->getScrnW(), game->getScrnH(), AMOUNT); } SDL_Color txtCol1 = {255, 255, 255, 0}; return success; } /*implementation of global function declared in game.cpp*/ void handleTouchUps(float touchX, float touchY) { } /*implementation of global function declared in game.cpp*/ void handleTouchDwns(float touchX, float touchY) { SDL_Point touchLoc = {touchX, touchY,}; switch (GAME_STATE) { case GAME_STATE_MENU: if (game->getTouchDwn()) { if (SDL_PointInRect(&touchLoc, btnPlay.getBtnRect())) { GAME_STATE = GAME_STATE_LOADING; } if (SDL_PointInRect(&touchLoc, btninfo.getBtnRect())) { GAME_STATE = GAME_STATE_CREDITS; } if (SDL_PointInRect(&touchLoc, btnquit.getBtnRect())) { exit(EXIT_SUCCESS); } } break; case GAME_STATE_CREDITS: break; case GAME_STATE_LOADING: break; case GAME_STATE_EXITING: break; case GAME_STATE_3PUZZLE: if (game->getTouchDwn()) { processInput(touchLoc); if (SDL_PointInRect(&touchLoc, btnquit.getBtnRect())) { GAME_STATE = GAME_STATE_EXITING; } } break; default: break; } } /*implementation of global function declared in game.cpp*/ void handleMouseInput(SDL_Event *event) { switch (GAME_STATE) { case GAME_STATE_MENU: switch (event->type) { case SDL_MOUSEBUTTONDOWN: switch (event->button.button) { case SDL_BUTTON_LEFT: int x, y; SDL_GetMouseState(&x, &y); SDL_Point clickpoint = {x, y,}; if (SDL_PointInRect(&clickpoint, btnPlay.getBtnRect())) { GAME_STATE = GAME_STATE_LOADING; } if (SDL_PointInRect(&clickpoint, btninfo.getBtnRect())) { GAME_STATE = GAME_STATE_CREDITS; } break; } break; case SDL_MOUSEBUTTONUP: switch (event->button.button) { case SDL_BUTTON_LEFT: break; } break; } break; case GAME_STATE_CREDITS: switch (event->type) { case SDL_MOUSEBUTTONDOWN: switch (event->button.button) { case SDL_BUTTON_LEFT: int x, y; SDL_GetMouseState(&x, &y); SDL_Point clickpoint = {x, y,}; /*if (SDL_PointInRect(&clickpoint, btnquit.getBtnRect())) { GAME_STATE = GAME_STATE_MENU; }*/ break; } break; case SDL_MOUSEBUTTONUP: switch (event->button.button) { case SDL_BUTTON_LEFT: break; } break; } break; case GAME_STATE_LOADING: break; case GAME_STATE_EXITING: break; case GAME_STATE_3PUZZLE: switch (event->type) { case SDL_MOUSEBUTTONDOWN: switch (event->button.button) { case SDL_BUTTON_LEFT: int x, y; SDL_GetMouseState(&x, &y); SDL_Point clickpoint = {x, y,}; processInput(clickpoint); if (SDL_PointInRect(&clickpoint, btnquit.getBtnRect())) { GAME_STATE = GAME_STATE_EXITING; } break; } break; case SDL_MOUSEBUTTONUP: switch (event->button.button) { case SDL_BUTTON_LEFT: break; } break; } break; default: break; } } /*implementation of global function declared in game.cpp*/ void handleInput(SDL_Event *event) { if (event->type == SDL_KEYDOWN) { switch (event->key.keysym.sym) { case SDLK_AC_BACK: if (GAME_STATE == GAME_STATE_CREDITS) { GAME_STATE = GAME_STATE_MENU; } else if (GAME_STATE == GAME_STATE_3PUZZLE) { GAME_STATE = GAME_STATE_EXITING; } else if (GAME_STATE == GAME_STATE_MENU) { //exit(0); } break; } } } void processInput(SDL_Point _point) { switch (GAME_STATE) { case GAME_STATE_MENU: break; case GAME_STATE_CREDITS: break; case GAME_STATE_LOADING: break; case GAME_STATE_3PUZZLE: if (SDL_PointInRect(&_point, currPuzzle.getLowerCard1().getTex()->getTexRect())) { clickCard.setPos(currPuzzle.getLowerCard1().getPos()); if (currPuzzle.getSolution() == currPuzzle.getLowerCard1().getName()) { updatePuzzle = true; showFireworks = true; Mix_PlayChannel(-1, eff_correct, 0); } else { Mix_PlayChannel(-1, eff_retry, 0); } } else if (SDL_PointInRect(&_point, currPuzzle.getLowerCard2().getTex()->getTexRect())) { clickCard.setPos(currPuzzle.getLowerCard2().getPos()); if (currPuzzle.getSolution() == currPuzzle.getLowerCard2().getName()) { updatePuzzle = true; showFireworks = true; Mix_PlayChannel(-1, eff_correct, 0); } else { Mix_PlayChannel(-1, eff_retry, 0); } } else if (SDL_PointInRect(&_point, currPuzzle.getLowerCard3().getTex()->getTexRect())) { clickCard.setPos(currPuzzle.getLowerCard3().getPos()); if (currPuzzle.getSolution() == currPuzzle.getLowerCard3().getName()) { updatePuzzle = true; showFireworks = true; Mix_PlayChannel(-1, eff_correct, 0); } else { Mix_PlayChannel(-1, eff_retry, 0); } } break; default: break; } }
29.409163
102
0.538408
zimspy007
60ebdecbb33d45a182fe10debff0c30be64326d6
4,950
cpp
C++
libraries/disp3D/engine/model/materials/networkmaterial.cpp
MagCPP/mne-cpp
05f634a8401b20226bd719254a5da227e67a379b
[ "BSD-3-Clause" ]
1
2019-05-14T07:38:25.000Z
2019-05-14T07:38:25.000Z
libraries/disp3D/engine/model/materials/networkmaterial.cpp
MagCPP/mne-cpp
05f634a8401b20226bd719254a5da227e67a379b
[ "BSD-3-Clause" ]
1
2018-08-23T12:40:56.000Z
2018-08-23T12:40:56.000Z
libraries/disp3D/engine/model/materials/networkmaterial.cpp
MagCPP/mne-cpp
05f634a8401b20226bd719254a5da227e67a379b
[ "BSD-3-Clause" ]
null
null
null
//============================================================================================================= /** * @file networkmaterial.cpp * @author Lorenz Esch <[email protected]>; * Matti Hamalainen <[email protected]> * @version 1.0 * @date January, 2017 * * @section LICENSE * * Copyright (C) 2017, Lorenz Esch and Matti Hamalainen. 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 MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief NetworkMaterial class definition */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "networkmaterial.h" //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <Qt3DRender/qshaderprogram.h> #include <QFilterKey> #include <QUrl> #include <QVector3D> #include <QVector4D> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace DISP3DLIB; using namespace Qt3DRender; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= NetworkMaterial::NetworkMaterial(bool bUseSortPolicy, QNode *parent) : AbstractPhongAlphaMaterial(bUseSortPolicy, parent) , m_pVertexGL3Shader(new QShaderProgram()) , m_pVertexES2Shader(new QShaderProgram()) { init(); setShaderCode(); } //************************************************************************************************************* void NetworkMaterial::setShaderCode() { m_pVertexGL3Shader->setVertexShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/engine/model/materials/shaders/gl3/network.vert")))); m_pVertexGL3Shader->setFragmentShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/engine/model/materials/shaders/gl3/network.frag")))); m_pVertexES2Shader->setVertexShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/engine/model/materials/shaders/es2/network.vert")))); m_pVertexES2Shader->setFragmentShaderCode(QShaderProgram::loadSource(QUrl(QStringLiteral("qrc:/engine/model/materials/shaders/es2/network.frag")))); addShaderToRenderPass(QStringLiteral("pVertexGL3RenderPass"), m_pVertexGL3Shader); addShaderToRenderPass(QStringLiteral("pVertexGL2RenderPass"), m_pVertexES2Shader); addShaderToRenderPass(QStringLiteral("pVertexES2RenderPass"), m_pVertexES2Shader); } //*************************************************************************************************************
50.510204
152
0.512727
MagCPP
60eec60018467016f3b41e2931e782248998080f
21,511
cpp
C++
lgc/elfLinker/GlueShader.cpp
asuonpaa/llpc
89eac816465c27bb788186a1cb3bb54d8a7183d4
[ "MIT" ]
1
2019-11-25T04:54:55.000Z
2019-11-25T04:54:55.000Z
lgc/elfLinker/GlueShader.cpp
asuonpaa/llpc
89eac816465c27bb788186a1cb3bb54d8a7183d4
[ "MIT" ]
null
null
null
lgc/elfLinker/GlueShader.cpp
asuonpaa/llpc
89eac816465c27bb788186a1cb3bb54d8a7183d4
[ "MIT" ]
null
null
null
/* *********************************************************************************************************************** * * Copyright (c) 2020-2021 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. * **********************************************************************************************************************/ /** *********************************************************************************************************************** * @file GlueShader.cpp * @brief LGC source file: Glue shader (fetch shader, parameter/color export shader) generated in linking *********************************************************************************************************************** */ #include "GlueShader.h" #include "lgc/BuilderBase.h" #include "lgc/patch/FragColorExport.h" #include "lgc/patch/ShaderInputs.h" #include "lgc/patch/VertexFetch.h" #include "lgc/state/AbiMetadata.h" #include "lgc/state/PassManagerCache.h" #include "lgc/state/ShaderStage.h" #include "lgc/state/TargetInfo.h" #include "lgc/util/AddressExtender.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/IntrinsicsAMDGPU.h" #include "llvm/IR/Module.h" #include "llvm/Target/TargetMachine.h" using namespace lgc; using namespace llvm; // ===================================================================================================================== // Compile the glue shader // // @param [in/out] outStream : Stream to write ELF to void GlueShader::compile(raw_pwrite_stream &outStream) { // Generate the glue shader IR module. std::unique_ptr<Module> module(generate()); // Add empty PAL metadata, to ensure that the back-end writes its PAL metadata in MsgPack format. PalMetadata *palMetadata = new PalMetadata(nullptr); palMetadata->record(&*module); delete palMetadata; // Get the pass manager and run it on the module, generating ELF. PassManager &passManager = m_lgcContext->getPassManagerCache()->getGlueShaderPassManager(outStream); passManager.run(*module); m_lgcContext->getPassManagerCache()->resetStream(); } namespace { // ===================================================================================================================== // A fetch shader class FetchShader : public GlueShader { public: FetchShader(PipelineState *pipelineState, ArrayRef<VertexFetchInfo> fetches, const VsEntryRegInfo &vsEntryRegInfo); ~FetchShader() override {} // Get the string for this glue shader. This is some encoding or hash of the inputs to the create*Shader function // that the front-end client can use as a cache key to avoid compiling the same glue shader more than once. StringRef getString() override; // Get the symbol name of the main shader that this glue shader is prolog or epilog for. StringRef getMainShaderName() override; // Get the symbol name of the glue shader. StringRef getGlueShaderName() override { return getEntryPointName(m_vsEntryRegInfo.callingConv, /*isFetchlessVs=*/false); } // Get whether this glue shader is a prolog (rather than epilog) for its main shader. bool isProlog() override { return true; } // Get the name of this glue shader. StringRef getName() const override { return "fetch shader"; } protected: // Generate the glue shader to IR module Module *generate() override; private: Function *createFetchFunc(); // The information stored here is all that is needed to generate the fetch shader. We deliberately do not // have access to PipelineState, so we can hash the information here and let the front-end use it as the // key for a cache of glue shaders. SmallVector<VertexFetchInfo, 8> m_fetches; VsEntryRegInfo m_vsEntryRegInfo; SmallVector<const VertexInputDescription *, 8> m_fetchDescriptions; // The encoded or hashed (in some way) single string version of the above. std::string m_shaderString; }; // ===================================================================================================================== // A color export shader class ColorExportShader : public GlueShader { public: ColorExportShader(PipelineState *pipelineState, ArrayRef<ColorExportInfo> exports); ~ColorExportShader() override {} // Get the string for this glue shader. This is some encoding or hash of the inputs to the create*Shader function // that the front-end client can use as a cache key to avoid compiling the same glue shader more than once. StringRef getString() override; // Get the symbol name of the main shader that this glue shader is prolog or epilog for. StringRef getMainShaderName() override; // Get the symbol name of the glue shader. StringRef getGlueShaderName() override { return "color_export_shader"; } // Get whether this glue shader is a prolog (rather than epilog) for its main shader. bool isProlog() override { return false; } // Get the name of this glue shader. StringRef getName() const override { return "color export shader"; } protected: // Generate the glue shader to IR module Module *generate() override; private: Function *createColorExportFunc(); // The information stored here is all that is needed to generate the color export shader. We deliberately do not // have access to PipelineState, so we can hash the information here and let the front-end use it as the // key for a cache of glue shaders. SmallVector<ColorExportInfo, 8> m_exports; ExportFormat m_exportFormat[MaxColorTargets]; // The export format for each hw color target. // The encoded or hashed (in some way) single string version of the above. std::string m_shaderString; PipelineState *m_pipelineState; // The pipeline state. Used to set meta data information. bool m_killEnabled; // True if this fragement shader has kill enabled. }; } // anonymous namespace // ===================================================================================================================== // Create a fetch shader object GlueShader *GlueShader::createFetchShader(PipelineState *pipelineState, ArrayRef<VertexFetchInfo> fetches, const VsEntryRegInfo &vsEntryRegInfo) { return new FetchShader(pipelineState, fetches, vsEntryRegInfo); } // ===================================================================================================================== // Create a color export shader object std::unique_ptr<GlueShader> GlueShader::createColorExportShader(PipelineState *pipelineState, ArrayRef<ColorExportInfo> exports) { return std::make_unique<ColorExportShader>(pipelineState, exports); } // ===================================================================================================================== // Constructor. This is where we store all the information needed to generate the fetch shader; other methods // do not need to look at PipelineState. FetchShader::FetchShader(PipelineState *pipelineState, ArrayRef<VertexFetchInfo> fetches, const VsEntryRegInfo &vsEntryRegInfo) : GlueShader(pipelineState->getLgcContext()), m_vsEntryRegInfo(vsEntryRegInfo) { m_fetches.append(fetches.begin(), fetches.end()); for (const auto &fetch : m_fetches) m_fetchDescriptions.push_back(pipelineState->findVertexInputDescription(fetch.location)); } // ===================================================================================================================== // Get the string for this fetch shader. This is some encoding or hash of the inputs to the createFetchShader function // that the front-end client can use as a cache key to avoid compiling the same glue shader more than once. StringRef FetchShader::getString() { if (m_shaderString.empty()) { m_shaderString = StringRef(reinterpret_cast<const char *>(m_fetches.data()), m_fetches.size() * sizeof(VertexFetchInfo)).str(); m_shaderString += StringRef(reinterpret_cast<const char *>(&m_vsEntryRegInfo), sizeof(m_vsEntryRegInfo)).str(); for (const VertexInputDescription *description : m_fetchDescriptions) { if (!description) m_shaderString += StringRef("\0", 1); else m_shaderString += StringRef(reinterpret_cast<const char *>(description), sizeof(*description)); } } return m_shaderString; } // ===================================================================================================================== // Get the symbol name of the main shader that this glue shader is prolog or epilog for StringRef FetchShader::getMainShaderName() { return getEntryPointName(m_vsEntryRegInfo.callingConv, /*isFetchlessVs=*/true); } // ===================================================================================================================== // Generate the IR module for the fetch shader Module *FetchShader::generate() { // Create the function. Function *fetchFunc = createFetchFunc(); // Process each vertex input. std::unique_ptr<VertexFetch> vertexFetch(VertexFetch::create(m_lgcContext)); auto ret = cast<ReturnInst>(fetchFunc->back().getTerminator()); Value *result = ret->getOperand(0); BuilderBase builder(ret); for (unsigned idx = 0; idx != m_fetches.size(); ++idx) { const auto &fetch = m_fetches[idx]; const VertexInputDescription *description = m_fetchDescriptions[idx]; unsigned structIdx = idx + m_vsEntryRegInfo.sgprCount + m_vsEntryRegInfo.vgprCount; Type *ty = cast<StructType>(result->getType())->getElementType(structIdx); if (description) { // Fetch the vertex. Value *vertex = vertexFetch->fetchVertex(ty, description, fetch.location, fetch.component, builder); result = builder.CreateInsertValue(result, vertex, structIdx); } } ret->setOperand(0, result); // Hook up the inputs (vertex buffer, base vertex, base instance, vertex ID, instance ID). The fetchVertex calls // left its uses of them as lgc.special.user.data and lgc.shader.input calls. for (Function &func : *fetchFunc->getParent()) { if (!func.isDeclaration()) continue; if (func.getName().startswith(lgcName::SpecialUserData) || func.getName().startswith(lgcName::ShaderInput)) { while (!func.use_empty()) { auto call = cast<CallInst>(func.use_begin()->getUser()); Value *replacement = nullptr; switch (cast<ConstantInt>(call->getArgOperand(0))->getZExtValue()) { case static_cast<unsigned>(UserDataMapping::VertexBufferTable): { // Need to extend 32-bit vertex buffer table address to 64 bits. AddressExtender extender(fetchFunc); Value *highAddr = call->getArgOperand(1); builder.SetInsertPoint(&*fetchFunc->front().getFirstInsertionPt()); replacement = extender.extend(fetchFunc->getArg(m_vsEntryRegInfo.vertexBufferTable), highAddr, call->getType(), builder); break; } case static_cast<unsigned>(UserDataMapping::BaseVertex): replacement = fetchFunc->getArg(m_vsEntryRegInfo.baseVertex); break; case static_cast<unsigned>(UserDataMapping::BaseInstance): replacement = fetchFunc->getArg(m_vsEntryRegInfo.baseInstance); break; case static_cast<unsigned>(ShaderInput::VertexId): builder.SetInsertPoint(&*fetchFunc->front().getFirstInsertionPt()); replacement = builder.CreateBitCast(fetchFunc->getArg(m_vsEntryRegInfo.sgprCount + m_vsEntryRegInfo.vertexId), builder.getInt32Ty()); break; case static_cast<unsigned>(ShaderInput::InstanceId): builder.SetInsertPoint(&*fetchFunc->front().getFirstInsertionPt()); replacement = builder.CreateBitCast( fetchFunc->getArg(m_vsEntryRegInfo.sgprCount + m_vsEntryRegInfo.instanceId), builder.getInt32Ty()); break; default: llvm_unreachable("Unexpected special user data or shader input"); } call->replaceAllUsesWith(replacement); call->eraseFromParent(); } } } return fetchFunc->getParent(); } // ===================================================================================================================== // Create module with function for the fetch shader. On return, the function contains only the code to copy the // wave dispatch SGPRs and VGPRs to the return value. Function *FetchShader::createFetchFunc() { // Create the module Module *module = new Module("fetchShader", getContext()); TargetMachine *targetMachine = m_lgcContext->getTargetMachine(); module->setTargetTriple(targetMachine->getTargetTriple().getTriple()); module->setDataLayout(targetMachine->createDataLayout()); // Get the function type. Its inputs are the wave dispatch SGPRs and VGPRs. Its return type is a struct // containing the wave dispatch SGPRs and VGPRs, plus the fetched values in VGPRs. In the return type struct, // VGPR values must be FP so the back-end puts them into VGPRs; we do the same for the inputs for symmetry. SmallVector<Type *, 16> types; types.append(m_vsEntryRegInfo.sgprCount, Type::getInt32Ty(getContext())); types.append(m_vsEntryRegInfo.vgprCount, Type::getFloatTy(getContext())); for (const auto &fetch : m_fetches) types.push_back(getVgprTy(fetch.ty)); Type *retTy = StructType::get(getContext(), types); auto entryTys = ArrayRef<Type *>(types).slice(0, m_vsEntryRegInfo.sgprCount + m_vsEntryRegInfo.vgprCount); auto funcTy = FunctionType::get(retTy, entryTys, false); // Create the function. Mark SGPR inputs as "inreg". Function *func = Function::Create(funcTy, GlobalValue::ExternalLinkage, getGlueShaderName(), module); func->setCallingConv(m_vsEntryRegInfo.callingConv); for (unsigned i = 0; i != m_vsEntryRegInfo.sgprCount; ++i) func->getArg(i)->addAttr(Attribute::InReg); // Add mnemonic names to input args. func->getArg(m_vsEntryRegInfo.vertexBufferTable)->setName("VertexBufferTable"); func->getArg(m_vsEntryRegInfo.baseVertex)->setName("BaseVertex"); func->getArg(m_vsEntryRegInfo.baseInstance)->setName("BaseInstance"); func->getArg(m_vsEntryRegInfo.sgprCount + m_vsEntryRegInfo.vertexId)->setName("VertexId"); func->getArg(m_vsEntryRegInfo.sgprCount + m_vsEntryRegInfo.instanceId)->setName("InstanceId"); if (m_lgcContext->getTargetInfo().getGfxIpVersion().major >= 10) { // Set up wave32 or wave64 to match the vertex shader. func->addFnAttr("target-features", m_vsEntryRegInfo.wave32 ? "+wavefrontsize32" : "+wavefrontsize64"); } BasicBlock *block = BasicBlock::Create(func->getContext(), "", func); BuilderBase builder(block); if (m_vsEntryRegInfo.callingConv == CallingConv::AMDGPU_HS || m_vsEntryRegInfo.callingConv == CallingConv::AMDGPU_GS) { // The VS is the first half of a merged shader, LS-HS or ES-GS. This fetch shader needs to include code // to enable the correct lanes for the vertices. It happens that LS vertex count in LS-HS and ES vertex // count in ES-GS are in the same place: the low 8 bits of s3. constexpr unsigned MergedWaveInfoSgpr = 3; builder.CreateIntrinsic(Intrinsic::amdgcn_init_exec_from_input, {}, {func->getArg(MergedWaveInfoSgpr), builder.getInt32(0)}); } // Copy the wave dispatch SGPRs and VGPRs from inputs to outputs. builder.SetInsertPoint(&func->back()); Value *retVal = UndefValue::get(retTy); for (unsigned i = 0; i != m_vsEntryRegInfo.sgprCount + m_vsEntryRegInfo.vgprCount; ++i) retVal = builder.CreateInsertValue(retVal, func->getArg(i), i); builder.CreateRet(retVal); return func; } // ===================================================================================================================== // Constructor. This is where we store all the information needed to generate the export shader; other methods // do not need to look at PipelineState. ColorExportShader::ColorExportShader(PipelineState *pipelineState, ArrayRef<ColorExportInfo> exports) : GlueShader(pipelineState->getLgcContext()) { m_exports.append(exports.begin(), exports.end()); memset(m_exportFormat, 0, sizeof(m_exportFormat)); for (auto &exp : m_exports) { if (exp.hwColorTarget == MaxColorTargets) continue; m_exportFormat[exp.hwColorTarget] = static_cast<ExportFormat>(pipelineState->computeExportFormat(exp.ty, exp.location)); } m_pipelineState = pipelineState; PalMetadata *metadata = pipelineState->getPalMetadata(); DB_SHADER_CONTROL shaderControl = {}; shaderControl.u32All = metadata->getRegister(mmDB_SHADER_CONTROL); m_killEnabled = shaderControl.bits.KILL_ENABLE; } // ===================================================================================================================== // Get the string for this color export shader. This is some encoding or hash of the inputs to the // createColorExportShader function that the front-end client can use as a cache key to avoid compiling the same glue // shader more than once. StringRef ColorExportShader::getString() { if (m_shaderString.empty()) { m_shaderString = StringRef(reinterpret_cast<const char *>(m_exports.data()), m_exports.size() * sizeof(ColorExportInfo)).str(); m_shaderString += StringRef(reinterpret_cast<const char *>(m_exportFormat), sizeof(m_exportFormat)).str(); m_shaderString += StringRef(reinterpret_cast<const char *>(&m_killEnabled), sizeof(m_killEnabled)); } return m_shaderString; } // ===================================================================================================================== // Get the symbol name of the main shader that this glue shader is prolog or epilog for StringRef ColorExportShader::getMainShaderName() { return getEntryPointName(CallingConv::AMDGPU_PS, /*isFetchlessVs=*/false); } // ===================================================================================================================== // Generate the IR module for the color export shader Module *ColorExportShader::generate() { // Create the function. Function *colorExportFunc = createColorExportFunc(); // Process each vertex input. std::unique_ptr<FragColorExport> fragColorExport(new FragColorExport(&getContext(), m_pipelineState)); auto ret = cast<ReturnInst>(colorExportFunc->back().getTerminator()); BuilderBase builder(ret); SmallVector<Value *, 8> values(MaxColorTargets + 1, nullptr); for (unsigned idx = 0; idx != m_exports.size(); ++idx) { values[m_exports[idx].hwColorTarget] = colorExportFunc->getArg(idx); } bool dummyExport = m_lgcContext->getTargetInfo().getGfxIpVersion().major < 10 || m_killEnabled; fragColorExport->generateExportInstructions(m_exports, values, m_exportFormat, dummyExport, builder); bool hasDepthExpFmtZero = true; for (auto &info : m_exports) { if (info.hwColorTarget == MaxColorTargets) { hasDepthExpFmtZero = false; break; } } m_pipelineState->getPalMetadata()->updateSpiShaderColFormat(m_exports, hasDepthExpFmtZero, m_killEnabled); return colorExportFunc->getParent(); } // ===================================================================================================================== // Create module with function for the fetch shader. On return, the function contains only the code to copy the // wave dispatch SGPRs and VGPRs to the return value. Function *ColorExportShader::createColorExportFunc() { // Create the module Module *module = new Module("colorExportShader", getContext()); TargetMachine *targetMachine = m_lgcContext->getTargetMachine(); module->setTargetTriple(targetMachine->getTargetTriple().getTriple()); module->setDataLayout(targetMachine->createDataLayout()); // Get the function type. Its inputs are the outputs from the unlinked pixel shader or similar. SmallVector<Type *, 16> entryTys; for (const auto &exp : m_exports) entryTys.push_back(exp.ty); auto funcTy = FunctionType::get(Type::getVoidTy(getContext()), entryTys, false); // Create the function. Mark SGPR inputs as "inreg". Function *func = Function::Create(funcTy, GlobalValue::ExternalLinkage, getGlueShaderName(), module); func->setCallingConv(CallingConv::AMDGPU_PS); BasicBlock *block = BasicBlock::Create(func->getContext(), "", func); BuilderBase builder(block); builder.CreateRetVoid(); return func; }
49.111872
120
0.653247
asuonpaa
60f0c82f8c9af612e75f5ef9960dbc8b1ca8c3d3
12,684
hpp
C++
boost/atomic/detail/base.hpp
juslee/boost-svn
6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb
[ "BSL-1.0" ]
null
null
null
boost/atomic/detail/base.hpp
juslee/boost-svn
6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb
[ "BSL-1.0" ]
null
null
null
boost/atomic/detail/base.hpp
juslee/boost-svn
6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb
[ "BSL-1.0" ]
null
null
null
#ifndef BOOST_ATOMIC_DETAIL_BASE_HPP #define BOOST_ATOMIC_DETAIL_BASE_HPP // Copyright (c) 2009 Helge Bahmann // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Base class definition and fallback implementation. // To be overridden (through partial specialization) by // platform implementations. #include <string.h> #include <boost/atomic/detail/lockpool.hpp> #define BOOST_ATOMIC_DECLARE_BASE_OPERATORS \ operator value_type(void) volatile const \ { \ return load(memory_order_seq_cst); \ } \ \ this_type & \ operator=(value_type v) volatile \ { \ store(v, memory_order_seq_cst); \ return *const_cast<this_type *>(this); \ } \ \ bool \ compare_exchange_strong( \ value_type & expected, \ value_type desired, \ memory_order order = memory_order_seq_cst) volatile \ { \ return compare_exchange_strong(expected, desired, order, calculate_failure_order(order)); \ } \ \ bool \ compare_exchange_weak( \ value_type & expected, \ value_type desired, \ memory_order order = memory_order_seq_cst) volatile \ { \ return compare_exchange_weak(expected, desired, order, calculate_failure_order(order)); \ } \ \ #define BOOST_ATOMIC_DECLARE_ADDITIVE_OPERATORS \ value_type \ operator++(int) volatile \ { \ return fetch_add(1); \ } \ \ value_type \ operator++(void) volatile \ { \ return fetch_add(1) + 1; \ } \ \ value_type \ operator--(int) volatile \ { \ return fetch_sub(1); \ } \ \ value_type \ operator--(void) volatile \ { \ return fetch_sub(1) - 1; \ } \ \ value_type \ operator+=(difference_type v) volatile \ { \ return fetch_add(v) + v; \ } \ \ value_type \ operator-=(difference_type v) volatile \ { \ return fetch_sub(v) - v; \ } \ #define BOOST_ATOMIC_DECLARE_BIT_OPERATORS \ value_type \ operator&=(difference_type v) volatile \ { \ return fetch_and(v) & v; \ } \ \ value_type \ operator|=(difference_type v) volatile \ { \ return fetch_or(v) | v; \ } \ \ value_type \ operator^=(difference_type v) volatile \ { \ return fetch_xor(v) ^ v; \ } \ #define BOOST_ATOMIC_DECLARE_POINTER_OPERATORS \ BOOST_ATOMIC_DECLARE_BASE_OPERATORS \ BOOST_ATOMIC_DECLARE_ADDITIVE_OPERATORS \ #define BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS \ BOOST_ATOMIC_DECLARE_BASE_OPERATORS \ BOOST_ATOMIC_DECLARE_ADDITIVE_OPERATORS \ BOOST_ATOMIC_DECLARE_BIT_OPERATORS \ namespace boost { namespace atomics { namespace detail { static inline memory_order calculate_failure_order(memory_order order) { switch(order) { case memory_order_acq_rel: return memory_order_acquire; case memory_order_release: return memory_order_relaxed; default: return order; } } template<typename T, typename C , unsigned int Size, bool Sign> class base_atomic { private: typedef base_atomic this_type; typedef T value_type; typedef lockpool::scoped_lock guard_type; public: base_atomic(void) {} explicit base_atomic(const value_type & v) { memcpy(&v_, &v, Size); } void store(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile { guard_type guard(const_cast<char *>(v_)); memcpy(const_cast<char *>(v_), &v, Size); } value_type load(memory_order /*order*/ = memory_order_seq_cst) volatile const { guard_type guard(const_cast<const char *>(v_)); value_type v; memcpy(&v, const_cast<const char *>(v_), Size); return v; } bool compare_exchange_strong( value_type & expected, value_type desired, memory_order /*success_order*/, memory_order /*failure_order*/) volatile { guard_type guard(const_cast<char *>(v_)); if (memcmp(const_cast<char *>(v_), &expected, Size) == 0) { memcpy(const_cast<char *>(v_), &desired, Size); return true; } else { memcpy(&expected, const_cast<char *>(v_), Size); return false; } } bool compare_exchange_weak( value_type & expected, value_type desired, memory_order success_order, memory_order failure_order) volatile { return compare_exchange_strong(expected, desired, success_order, failure_order); } value_type exchange(value_type v, memory_order /*order*/=memory_order_seq_cst) volatile { guard_type guard(const_cast<char *>(v_)); value_type tmp; memcpy(&tmp, const_cast<char *>(v_), Size); memcpy(const_cast<char *>(v_), &v, Size); return tmp; } bool is_lock_free(void) const volatile { return false; } BOOST_ATOMIC_DECLARE_BASE_OPERATORS private: base_atomic(const base_atomic &) /* = delete */ ; void operator=(const base_atomic &) /* = delete */ ; char v_[Size]; }; template<typename T, unsigned int Size, bool Sign> class base_atomic<T, int, Size, Sign> { private: typedef base_atomic this_type; typedef T value_type; typedef T difference_type; typedef lockpool::scoped_lock guard_type; public: explicit base_atomic(value_type v) : v_(v) {} base_atomic(void) {} void store(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile { guard_type guard(const_cast<value_type *>(&v_)); v_ = v; } value_type load(memory_order /*order*/ = memory_order_seq_cst) const volatile { guard_type guard(const_cast<value_type *>(&v_)); value_type v = const_cast<const volatile value_type &>(v_); return v; } value_type exchange(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile { guard_type guard(const_cast<value_type *>(&v_)); value_type old = v_; v_ = v; return old; } bool compare_exchange_strong(value_type & expected, value_type desired, memory_order /*success_order*/, memory_order /*failure_order*/) volatile { guard_type guard(const_cast<value_type *>(&v_)); if (v_ == expected) { v_ = desired; return true; } else { expected = v_; return false; } } bool compare_exchange_weak(value_type & expected, value_type desired, memory_order success_order, memory_order failure_order) volatile { return compare_exchange_strong(expected, desired, success_order, failure_order); } value_type fetch_add(difference_type v, memory_order /*order*/ = memory_order_seq_cst) volatile { guard_type guard(const_cast<value_type *>(&v_)); value_type old = v_; v_ += v; return old; } value_type fetch_sub(difference_type v, memory_order /*order*/ = memory_order_seq_cst) volatile { guard_type guard(const_cast<value_type *>(&v_)); value_type old = v_; v_ -= v; return old; } value_type fetch_and(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile { guard_type guard(const_cast<value_type *>(&v_)); value_type old = v_; v_ &= v; return old; } value_type fetch_or(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile { guard_type guard(const_cast<value_type *>(&v_)); value_type old = v_; v_ |= v; return old; } value_type fetch_xor(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile { guard_type guard(const_cast<value_type *>(&v_)); value_type old = v_; v_ ^= v; return old; } bool is_lock_free(void) const volatile { return false; } BOOST_ATOMIC_DECLARE_INTEGRAL_OPERATORS private: base_atomic(const base_atomic &) /* = delete */ ; void operator=(const base_atomic &) /* = delete */ ; value_type v_; }; template<typename T, unsigned int Size, bool Sign> class base_atomic<T *, void *, Size, Sign> { private: typedef base_atomic this_type; typedef T * value_type; typedef ptrdiff_t difference_type; typedef lockpool::scoped_lock guard_type; public: explicit base_atomic(value_type v) : v_(v) {} base_atomic(void) {} void store(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile { guard_type guard(const_cast<value_type *>(&v_)); v_ = v; } value_type load(memory_order /*order*/ = memory_order_seq_cst) const volatile { guard_type guard(const_cast<value_type *>(&v_)); value_type v = const_cast<const volatile value_type &>(v_); return v; } value_type exchange(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile { guard_type guard(const_cast<value_type *>(&v_)); value_type old = v_; v_ = v; return old; } bool compare_exchange_strong(value_type & expected, value_type desired, memory_order /*success_order*/, memory_order /*failure_order*/) volatile { guard_type guard(const_cast<value_type *>(&v_)); if (v_ == expected) { v_ = desired; return true; } else { expected = v_; return false; } } bool compare_exchange_weak(value_type & expected, value_type desired, memory_order success_order, memory_order failure_order) volatile { return compare_exchange_strong(expected, desired, success_order, failure_order); } value_type fetch_add(difference_type v, memory_order /*order*/ = memory_order_seq_cst) volatile { guard_type guard(const_cast<value_type *>(&v_)); value_type old = v_; v_ += v; return old; } value_type fetch_sub(difference_type v, memory_order /*order*/ = memory_order_seq_cst) volatile { guard_type guard(const_cast<value_type *>(&v_)); value_type old = v_; v_ -= v; return old; } bool is_lock_free(void) const volatile { return false; } BOOST_ATOMIC_DECLARE_POINTER_OPERATORS private: base_atomic(const base_atomic &) /* = delete */ ; void operator=(const base_atomic &) /* = delete */ ; value_type v_; }; template<unsigned int Size, bool Sign> class base_atomic<void *, void *, Size, Sign> { private: typedef base_atomic this_type; typedef void * value_type; typedef lockpool::scoped_lock guard_type; public: explicit base_atomic(value_type v) : v_(v) {} base_atomic(void) {} void store(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile { guard_type guard(const_cast<value_type *>(&v_)); v_ = v; } value_type load(memory_order /*order*/ = memory_order_seq_cst) const volatile { guard_type guard(const_cast<value_type *>(&v_)); value_type v = const_cast<const volatile value_type &>(v_); return v; } value_type exchange(value_type v, memory_order /*order*/ = memory_order_seq_cst) volatile { guard_type guard(const_cast<value_type *>(&v_)); value_type old = v_; v_ = v; return old; } bool compare_exchange_strong(value_type & expected, value_type desired, memory_order /*success_order*/, memory_order /*failure_order*/) volatile { guard_type guard(const_cast<value_type *>(&v_)); if (v_ == expected) { v_ = desired; return true; } else { expected = v_; return false; } } bool compare_exchange_weak(value_type & expected, value_type desired, memory_order success_order, memory_order failure_order) volatile { return compare_exchange_strong(expected, desired, success_order, failure_order); } bool is_lock_free(void) const volatile { return false; } BOOST_ATOMIC_DECLARE_BASE_OPERATORS private: base_atomic(const base_atomic &) /* = delete */ ; void operator=(const base_atomic &) /* = delete */ ; value_type v_; }; } } } #endif
24.725146
99
0.622044
juslee
60f468280dabfd003c3f29bd05c07f724b45b4ac
911
hpp
C++
Main course/Homework4/Problem2/Header files/KeyValueDatabase.hpp
nia-flo/FMI-OOP
9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba
[ "MIT" ]
null
null
null
Main course/Homework4/Problem2/Header files/KeyValueDatabase.hpp
nia-flo/FMI-OOP
9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba
[ "MIT" ]
null
null
null
Main course/Homework4/Problem2/Header files/KeyValueDatabase.hpp
nia-flo/FMI-OOP
9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba
[ "MIT" ]
null
null
null
#pragma once #include "Object.hpp" #include <vector> class KeyValueDatabase : public Object { public: KeyValueDatabase(const std::string& name, const std::string& location, const std::string& extension); void add_entry(const std::pair<std::string, int>& entry); int get_value(const std::string& key) const; bool operator==(const Comparable* toCompare) const override; bool operator!=(const Comparable* toCompare) const override; bool operator==(const KeyValueDatabase& toCompare) const; bool operator!=(const KeyValueDatabase& toCompare) const; std::string to_string() const override; void from_string(const std::string& stringData) override; std::string debug_print() const override; Object* clone() const override; private: std::vector< std::pair<std::string, int> > data; const std::pair<std::string, int>* find(const std::string& key) const; };
28.46875
105
0.712404
nia-flo
60f784ab8f262a7bbaab47844a0b93133bd1444b
189
hpp
C++
include/riw/concepts/signed_integral.hpp
SachiSakurane/riw
9d3f61359d82ba93d4a1efae06a86f2f5337564d
[ "BSL-1.0" ]
2
2021-04-13T15:38:42.000Z
2021-06-13T16:12:11.000Z
include/riw/concepts/signed_integral.hpp
SachiSakurane/riw
9d3f61359d82ba93d4a1efae06a86f2f5337564d
[ "BSL-1.0" ]
1
2021-06-07T08:14:24.000Z
2021-06-07T08:14:44.000Z
include/riw/concepts/signed_integral.hpp
SachiSakurane/riw
9d3f61359d82ba93d4a1efae06a86f2f5337564d
[ "BSL-1.0" ]
null
null
null
#pragma once #include <type_traits> #include <riw/concepts/integral.hpp> namespace riw { template <class Type> concept signed_integral = riw::integral<Type> && std::is_signed_v<Type>; }
17.181818
72
0.746032
SachiSakurane
60f9c89cdcc144305597557c7d60663853036b26
979
cpp
C++
samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlMessageFormatter Example/CPP/source3.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlMessageFormatter Example/CPP/source3.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_Remoting/Classic XmlMessageFormatter Example/CPP/source3.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
// <Snippet3> #using <System.dll> #using <System.Messaging.dll> using namespace System; using namespace System::Messaging; // placeholder; see complete definition elsewhere in this section public ref class Order { public: int itemId; int quantity; String^ address; void ShipItems(){} }; // Creates the queue if it does not already exist. void EnsureQueueExists( String^ path ) { if ( !MessageQueue::Exists( path ) ) { MessageQueue::Create( path ); } } int main() { String^ queuePath = ".\\orders"; EnsureQueueExists( queuePath ); MessageQueue^ queue = gcnew MessageQueue( queuePath ); Order^ orderRequest = gcnew Order; orderRequest->itemId = 1025; orderRequest->quantity = 5; orderRequest->address = "One Microsoft Way"; queue->Send( orderRequest ); // This line uses a new method you define on the Order class: // orderRequest.PrintReceipt(); } // </Snippet3>
20.829787
66
0.6476
hamarb123
60fb7467cd56855f2f511e3fd6c6023de48b5585
11,302
hpp
C++
include/GlobalNamespace/ColorHueSlider.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/ColorHueSlider.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/ColorHueSlider.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: HMUI.CircleSlider #include "HMUI/CircleSlider.hpp" // Including type: ColorChangeUIEventType #include "GlobalNamespace/ColorChangeUIEventType.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Action`3<T1, T2, T3> template<typename T1, typename T2, typename T3> class Action_3; } // Forward declaring namespace: UnityEngine::EventSystems namespace UnityEngine::EventSystems { // Forward declaring type: PointerEventData class PointerEventData; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // WARNING Size may be invalid! // Autogenerated type: ColorHueSlider // [TokenAttribute] Offset: FFFFFFFF class ColorHueSlider : public HMUI::CircleSlider { public: // private UnityEngine.Color _darkColor // Size: 0x10 // Offset: 0x124 UnityEngine::Color darkColor; // Field size check static_assert(sizeof(UnityEngine::Color) == 0x10); // private UnityEngine.Color _lightColor // Size: 0x10 // Offset: 0x134 UnityEngine::Color lightColor; // Field size check static_assert(sizeof(UnityEngine::Color) == 0x10); // private System.Action`3<ColorHueSlider,System.Single,ColorChangeUIEventType> colorHueDidChangeEvent // Size: 0x8 // Offset: 0x148 System::Action_3<GlobalNamespace::ColorHueSlider*, float, GlobalNamespace::ColorChangeUIEventType>* colorHueDidChangeEvent; // Field size check static_assert(sizeof(System::Action_3<GlobalNamespace::ColorHueSlider*, float, GlobalNamespace::ColorChangeUIEventType>*) == 0x8); // Creating value type constructor for type: ColorHueSlider ColorHueSlider(UnityEngine::Color darkColor_ = {}, UnityEngine::Color lightColor_ = {}, System::Action_3<GlobalNamespace::ColorHueSlider*, float, GlobalNamespace::ColorChangeUIEventType>* colorHueDidChangeEvent_ = {}) noexcept : darkColor{darkColor_}, lightColor{lightColor_}, colorHueDidChangeEvent{colorHueDidChangeEvent_} {} // Get instance field reference: private UnityEngine.Color _darkColor UnityEngine::Color& dyn__darkColor(); // Get instance field reference: private UnityEngine.Color _lightColor UnityEngine::Color& dyn__lightColor(); // Get instance field reference: private System.Action`3<ColorHueSlider,System.Single,ColorChangeUIEventType> colorHueDidChangeEvent System::Action_3<GlobalNamespace::ColorHueSlider*, float, GlobalNamespace::ColorChangeUIEventType>*& dyn_colorHueDidChangeEvent(); // public System.Void add_colorHueDidChangeEvent(System.Action`3<ColorHueSlider,System.Single,ColorChangeUIEventType> value) // Offset: 0x10E1214 void add_colorHueDidChangeEvent(System::Action_3<GlobalNamespace::ColorHueSlider*, float, GlobalNamespace::ColorChangeUIEventType>* value); // public System.Void remove_colorHueDidChangeEvent(System.Action`3<ColorHueSlider,System.Single,ColorChangeUIEventType> value) // Offset: 0x10E12BC void remove_colorHueDidChangeEvent(System::Action_3<GlobalNamespace::ColorHueSlider*, float, GlobalNamespace::ColorChangeUIEventType>* value); // private System.Void HandleNormalizedValueDidChange(HMUI.CircleSlider slider, System.Single normalizedValue) // Offset: 0x10E1510 void HandleNormalizedValueDidChange(HMUI::CircleSlider* slider, float normalizedValue); // public System.Void .ctor() // Offset: 0x10E1618 // Implemented from: HMUI.CircleSlider // Base method: System.Void CircleSlider::.ctor() // Base method: System.Void Selectable::.ctor() // Base method: System.Void UIBehaviour::.ctor() // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ColorHueSlider* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::ColorHueSlider::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<ColorHueSlider*, creationType>())); } // protected override System.Void Awake() // Offset: 0x10E1364 // Implemented from: UnityEngine.UI.Selectable // Base method: System.Void Selectable::Awake() void Awake(); // protected override System.Void OnDestroy() // Offset: 0x10E13F0 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::OnDestroy() void OnDestroy(); // protected override System.Void UpdateVisuals() // Offset: 0x10E147C // Implemented from: HMUI.CircleSlider // Base method: System.Void CircleSlider::UpdateVisuals() void UpdateVisuals(); // public override System.Void OnPointerUp(UnityEngine.EventSystems.PointerEventData eventData) // Offset: 0x10E158C // Implemented from: UnityEngine.UI.Selectable // Base method: System.Void Selectable::OnPointerUp(UnityEngine.EventSystems.PointerEventData eventData) void OnPointerUp(UnityEngine::EventSystems::PointerEventData* eventData); }; // ColorHueSlider // WARNING Not writing size check since size may be invalid! } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::ColorHueSlider*, "", "ColorHueSlider"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::ColorHueSlider::add_colorHueDidChangeEvent // Il2CppName: add_colorHueDidChangeEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorHueSlider::*)(System::Action_3<GlobalNamespace::ColorHueSlider*, float, GlobalNamespace::ColorChangeUIEventType>*)>(&GlobalNamespace::ColorHueSlider::add_colorHueDidChangeEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`3"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "ColorHueSlider"), ::il2cpp_utils::GetClassFromName("System", "Single"), ::il2cpp_utils::GetClassFromName("", "ColorChangeUIEventType")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorHueSlider*), "add_colorHueDidChangeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::ColorHueSlider::remove_colorHueDidChangeEvent // Il2CppName: remove_colorHueDidChangeEvent template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorHueSlider::*)(System::Action_3<GlobalNamespace::ColorHueSlider*, float, GlobalNamespace::ColorChangeUIEventType>*)>(&GlobalNamespace::ColorHueSlider::remove_colorHueDidChangeEvent)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`3"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "ColorHueSlider"), ::il2cpp_utils::GetClassFromName("System", "Single"), ::il2cpp_utils::GetClassFromName("", "ColorChangeUIEventType")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorHueSlider*), "remove_colorHueDidChangeEvent", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::ColorHueSlider::HandleNormalizedValueDidChange // Il2CppName: HandleNormalizedValueDidChange template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorHueSlider::*)(HMUI::CircleSlider*, float)>(&GlobalNamespace::ColorHueSlider::HandleNormalizedValueDidChange)> { static const MethodInfo* get() { static auto* slider = &::il2cpp_utils::GetClassFromName("HMUI", "CircleSlider")->byval_arg; static auto* normalizedValue = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorHueSlider*), "HandleNormalizedValueDidChange", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{slider, normalizedValue}); } }; // Writing MetadataGetter for method: GlobalNamespace::ColorHueSlider::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: GlobalNamespace::ColorHueSlider::Awake // Il2CppName: Awake template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorHueSlider::*)()>(&GlobalNamespace::ColorHueSlider::Awake)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorHueSlider*), "Awake", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ColorHueSlider::OnDestroy // Il2CppName: OnDestroy template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorHueSlider::*)()>(&GlobalNamespace::ColorHueSlider::OnDestroy)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorHueSlider*), "OnDestroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ColorHueSlider::UpdateVisuals // Il2CppName: UpdateVisuals template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorHueSlider::*)()>(&GlobalNamespace::ColorHueSlider::UpdateVisuals)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorHueSlider*), "UpdateVisuals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::ColorHueSlider::OnPointerUp // Il2CppName: OnPointerUp template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::ColorHueSlider::*)(UnityEngine::EventSystems::PointerEventData*)>(&GlobalNamespace::ColorHueSlider::OnPointerUp)> { static const MethodInfo* get() { static auto* eventData = &::il2cpp_utils::GetClassFromName("UnityEngine.EventSystems", "PointerEventData")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ColorHueSlider*), "OnPointerUp", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{eventData}); } };
63.494382
332
0.750133
Fernthedev
60fbe922ed8a64b7ceae9b263b0cb60e2a62e301
119
cpp
C++
libwx/src/Maps/MapSpin.cpp
EnjoMitch/EnjoLib
321167146657cba1497a9d3b4ffd71430f9b24b3
[ "BSD-3-Clause" ]
3
2021-06-14T15:36:46.000Z
2022-02-28T15:16:08.000Z
libwx/src/Maps/MapSpin.cpp
EnjoMitch/EnjoLib
321167146657cba1497a9d3b4ffd71430f9b24b3
[ "BSD-3-Clause" ]
1
2021-07-17T07:52:15.000Z
2021-07-17T07:52:15.000Z
libwx/src/Maps/MapSpin.cpp
EnjoMitch/EnjoLib
321167146657cba1497a9d3b4ffd71430f9b24b3
[ "BSD-3-Clause" ]
3
2021-07-12T14:52:38.000Z
2021-11-28T17:10:33.000Z
#include "MapSpin.hpp" #include <wx/spinctrl.h> MapSpin::MapSpin() { //ctor } MapSpin::~MapSpin() { //dtor }
9.153846
24
0.596639
EnjoMitch
60fdd3353c1bec13e9aba440f1f8d2410a5768c7
345
cpp
C++
src_db/base_io_stream/OutputStream.cpp
alinous-core/codable-cash
32a86a152a146c592bcfd8cc712f4e8cb38ee1a0
[ "MIT" ]
6
2019-01-06T05:02:39.000Z
2020-10-01T11:45:32.000Z
src_db/base_io_stream/OutputStream.cpp
Codablecash/codablecash
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
[ "MIT" ]
209
2018-05-18T03:07:02.000Z
2022-03-26T11:42:41.000Z
src_db/base_io_stream/OutputStream.cpp
Codablecash/codablecash
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
[ "MIT" ]
3
2019-07-06T09:16:36.000Z
2020-10-15T08:23:28.000Z
/* * OutputStream.cpp * * Created on: 2018/04/19 * Author: iizuka */ #include "debug/debugMacros.h" #include "OutputStream.h" namespace alinous { OutputStream::OutputStream() { } OutputStream::~OutputStream() { } void OutputStream::write(const char* buffer, int size) { write(buffer, 0, size); } } /* namespace alinous */
13.269231
56
0.657971
alinous-core
8801d684bd26fb6bcbb6b3c1be97d0e1658c1342
901
cpp
C++
01.basic_algorithms/01.Sort/quickSelection/quick_selection_template.cpp
digSelf/algorithms
c0778fb9b2ad441861ed0b681f60baf2d6472109
[ "MIT" ]
4
2022-02-25T05:53:12.000Z
2022-03-21T02:42:39.000Z
01.basic_algorithms/01.Sort/quickSelection/quick_selection_template.cpp
digSelf/algorithms
c0778fb9b2ad441861ed0b681f60baf2d6472109
[ "MIT" ]
null
null
null
01.basic_algorithms/01.Sort/quickSelection/quick_selection_template.cpp
digSelf/algorithms
c0778fb9b2ad441861ed0b681f60baf2d6472109
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> const int N = 1e5 + 5; int arr[N]; // arr, [start, end], k int quickSelection(int *arr, int start, int end, int k) { // exit condition if (start >= end) return arr[start]; int left = start - 1, right = end + 1; int pivot = arr[(left + right) >> 1]; while (left < right) { while (arr[++left] < pivot); // >= while (arr[--right] > pivot); // <= if (left < right) { std::swap(arr[left], arr[right]); } } if (k <= right - start + 1) { return quickSelection(arr, start, right, k); } else { return quickSelection(arr, right + 1, end, k - right + start - 1); } } int main() { int n = 0, k = 0; scanf("%d%d", &n, &k); for (int i = 0; i < n; ++i) { scanf("%d", &arr[i]); } printf("%d\n", quickSelection(arr, 0, n - 1, k)); return 0; }
21.452381
74
0.473918
digSelf
88028aa144f2dcf090153252157a1b9b46e13279
8,707
cc
C++
tensorflow/lite/toco/tflite/import.cc
aeverall/tensorflow
7992bf97711919f56f80bff9e5510cead4ab2095
[ "Apache-2.0" ]
52
2018-11-12T06:39:35.000Z
2022-03-08T05:31:27.000Z
tensorflow/lite/toco/tflite/import.cc
aeverall/tensorflow
7992bf97711919f56f80bff9e5510cead4ab2095
[ "Apache-2.0" ]
2
2018-12-04T08:35:40.000Z
2020-10-22T16:17:39.000Z
tensorflow/lite/toco/tflite/import.cc
aeverall/tensorflow
7992bf97711919f56f80bff9e5510cead4ab2095
[ "Apache-2.0" ]
17
2019-03-11T01:17:16.000Z
2022-02-21T00:44:47.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/toco/tflite/import.h" #include "flatbuffers/flexbuffers.h" #include "tensorflow/lite/model.h" #include "tensorflow/lite/schema/schema_generated.h" #include "tensorflow/lite/toco/tflite/operator.h" #include "tensorflow/lite/toco/tflite/types.h" #include "tensorflow/lite/toco/tooling_util.h" #include "tensorflow/lite/tools/verifier.h" namespace toco { namespace tflite { namespace details { void LoadTensorsTable(const ::tflite::Model& input_model, TensorsTable* tensors_table) { // TODO(aselle): add support to toco for multiple subgraphs. auto tensors = (*input_model.subgraphs())[0]->tensors(); if (!tensors) return; for (const auto* tensor : *tensors) { tensors_table->push_back(tensor->name()->c_str()); } } void LoadOperatorsTable(const ::tflite::Model& input_model, OperatorsTable* operators_table) { auto opcodes = input_model.operator_codes(); if (!opcodes) return; for (const auto* opcode : *opcodes) { if (opcode->builtin_code() != ::tflite::BuiltinOperator_CUSTOM) { operators_table->push_back( EnumNameBuiltinOperator(opcode->builtin_code())); } else { operators_table->push_back(opcode->custom_code()->c_str()); } } } } // namespace details void ImportTensors(const ::tflite::Model& input_model, Model* model) { auto tensors = (*input_model.subgraphs())[0]->tensors(); auto* buffers = input_model.buffers(); // auto tensors = input_model.tensors(); if (!tensors) return; for (const auto* input_tensor : *tensors) { Array& array = model->GetOrCreateArray(input_tensor->name()->c_str()); array.data_type = DataType::Deserialize(input_tensor->type()); int buffer_index = input_tensor->buffer(); auto* buffer = buffers->Get(buffer_index); DataBuffer::Deserialize(*input_tensor, *buffer, &array); auto shape = input_tensor->shape(); if (shape) { // If the shape is 0-dimensional, make sure to record it as such, // as oppose to leaving the array without a shape. array.mutable_shape()->mutable_dims()->clear(); for (int i = 0; i < shape->Length(); ++i) { auto d = shape->Get(i); array.mutable_shape()->mutable_dims()->push_back(d); } } auto quantization = input_tensor->quantization(); if (quantization) { // Note that tf.mini only supports a single quantization parameters for // the whole array. if (quantization->min() && quantization->max()) { CHECK_EQ(1, quantization->min()->Length()); CHECK_EQ(1, quantization->max()->Length()); MinMax& minmax = array.GetOrCreateMinMax(); minmax.min = quantization->min()->Get(0); minmax.max = quantization->max()->Get(0); } if (quantization->scale() && quantization->zero_point()) { CHECK_EQ(1, quantization->scale()->Length()); CHECK_EQ(1, quantization->zero_point()->Length()); QuantizationParams& q = array.GetOrCreateQuantizationParams(); q.scale = quantization->scale()->Get(0); q.zero_point = quantization->zero_point()->Get(0); } } } } void ImportOperators( const ::tflite::Model& input_model, const std::map<string, std::unique_ptr<BaseOperator>>& ops_by_name, const details::TensorsTable& tensors_table, const details::OperatorsTable& operators_table, Model* model) { // TODO(aselle): add support for multiple subgraphs. auto ops = (*input_model.subgraphs())[0]->operators(); if (!ops) return; for (const auto* input_op : *ops) { int index = input_op->opcode_index(); if (index < 0 || index > operators_table.size()) { LOG(FATAL) << "Index " << index << " must be between zero and " << operators_table.size(); } string opname = operators_table.at(index); // Find and use the appropriate operator deserialization factory. std::unique_ptr<Operator> new_op = nullptr; if (ops_by_name.count(opname) == 0) { string effective_opname = "TENSORFLOW_UNSUPPORTED"; if (ops_by_name.count(effective_opname) == 0) { LOG(FATAL) << "Internal logic error: TENSORFLOW_UNSUPPORTED not found."; } new_op = ops_by_name.at(effective_opname) ->Deserialize(input_op->builtin_options(), input_op->custom_options()); if (new_op->type == OperatorType::kUnsupported) { auto* unsupported_op = static_cast<TensorFlowUnsupportedOperator*>(new_op.get()); unsupported_op->tensorflow_op = opname; // TODO(b/109932940): Remove this when quantized is removed. // For now, we assume all ops are quantized. unsupported_op->quantized = true; } else { LOG(FATAL) << "Expected a TensorFlowUnsupportedOperator"; } } else { new_op = ops_by_name.at(opname)->Deserialize(input_op->builtin_options(), input_op->custom_options()); } model->operators.emplace_back(new_op.release()); auto* op = model->operators.back().get(); // Make sure all the inputs and outputs are hooked up. auto inputs = input_op->inputs(); for (int i = 0; i < inputs->Length(); i++) { auto input_index = inputs->Get(i); // input_index == -1 indicates optional tensor. if (input_index != -1) { const string& input_name = tensors_table.at(input_index); op->inputs.push_back(input_name); } else { const string& tensor_name = toco::AvailableArrayName(*model, "OptionalTensor"); model->CreateOptionalArray(tensor_name); op->inputs.push_back(tensor_name); } } auto outputs = input_op->outputs(); for (int i = 0; i < outputs->Length(); i++) { auto output_index = outputs->Get(i); const string& output_name = tensors_table.at(output_index); op->outputs.push_back(output_name); } } } void ImportIOTensors(const ::tflite::Model& input_model, const details::TensorsTable& tensors_table, Model* model) { auto inputs = (*input_model.subgraphs())[0]->inputs(); if (inputs) { for (int input : *inputs) { const string& input_name = tensors_table.at(input); model->flags.add_input_arrays()->set_name(input_name); } } auto outputs = (*input_model.subgraphs())[0]->outputs(); if (outputs) { for (int output : *outputs) { const string& output_name = tensors_table.at(output); model->flags.add_output_arrays(output_name); } } } namespace { bool Verify(const void* buf, size_t len) { ::flatbuffers::Verifier verifier(static_cast<const uint8_t*>(buf), len); return ::tflite::VerifyModelBuffer(verifier); } } // namespace std::unique_ptr<Model> Import(const ModelFlags& model_flags, const string& input_file_contents) { ::tflite::AlwaysTrueResolver r; if (!::tflite::Verify(input_file_contents.data(), input_file_contents.size(), r, ::tflite::DefaultErrorReporter())) { LOG(FATAL) << "Invalid flatbuffer."; } const ::tflite::Model* input_model = ::tflite::GetModel(input_file_contents.data()); // Full list of all known operators. const auto ops_by_name = BuildOperatorByNameMap(); if (!input_model->subgraphs() || input_model->subgraphs()->size() != 1) { LOG(FATAL) << "Number of subgraphs in tflite should be exactly 1."; } std::unique_ptr<Model> model; model.reset(new Model); details::TensorsTable tensors_table; details::LoadTensorsTable(*input_model, &tensors_table); details::OperatorsTable operators_table; details::LoadOperatorsTable(*input_model, &operators_table); ImportTensors(*input_model, model.get()); ImportOperators(*input_model, ops_by_name, tensors_table, operators_table, model.get()); ImportIOTensors(*input_model, tensors_table, model.get()); UndoWeightsShuffling(model.get()); return model; } } // namespace tflite } // namespace toco
37.530172
80
0.653153
aeverall
88092dcacdb9dacb0171f27c1fdba05360e57e51
207
hpp
C++
callback.hpp
gregvw/cython-callback-numpy-arrays
6f3bc342745ca35651d79b74616e6c37fc523fdd
[ "MIT" ]
null
null
null
callback.hpp
gregvw/cython-callback-numpy-arrays
6f3bc342745ca35651d79b74616e6c37fc523fdd
[ "MIT" ]
null
null
null
callback.hpp
gregvw/cython-callback-numpy-arrays
6f3bc342745ca35651d79b74616e6c37fc523fdd
[ "MIT" ]
null
null
null
typedef double (*Callback)( void *apply, const double &x ); void function( Callback callback, void *apply, const double *x, double *y, int n );
23
59
0.492754
gregvw
880bd00f22dbf5087fd53e5e1aff990899148672
14,303
cpp
C++
unit_tests/sharings/gl/gl_create_from_texture_tests.cpp
cwang64/compute-runtime
440520ffdc5807574f0abfbf64b3790d1c0547e4
[ "MIT" ]
null
null
null
unit_tests/sharings/gl/gl_create_from_texture_tests.cpp
cwang64/compute-runtime
440520ffdc5807574f0abfbf64b3790d1c0547e4
[ "MIT" ]
null
null
null
unit_tests/sharings/gl/gl_create_from_texture_tests.cpp
cwang64/compute-runtime
440520ffdc5807574f0abfbf64b3790d1c0547e4
[ "MIT" ]
3
2019-05-16T07:22:51.000Z
2019-11-11T03:05:32.000Z
/* * Copyright (C) 2018-2019 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "runtime/helpers/get_info.h" #include "runtime/mem_obj/image.h" #include "runtime/sharings/gl/gl_texture.h" #include "test.h" #include "unit_tests/libult/create_command_stream.h" #include "unit_tests/libult/ult_command_stream_receiver.h" #include "unit_tests/mocks/gl/mock_gl_sharing.h" #include "unit_tests/mocks/mock_context.h" #include "unit_tests/mocks/mock_execution_environment.h" #include "unit_tests/mocks/mock_gmm.h" #include "gtest/gtest.h" namespace NEO { class CreateFromGlTexture : public ::testing::Test { public: // temp solution - we need to query size from GMM: class TempMM : public OsAgnosticMemoryManager { public: TempMM() : OsAgnosticMemoryManager(*(new MockExecutionEnvironment(*platformDevices))) { mockExecutionEnvironment.reset(&executionEnvironment); } GraphicsAllocation *createGraphicsAllocationFromSharedHandle(osHandle handle, const AllocationProperties &properties, bool requireSpecificBitness) override { auto alloc = OsAgnosticMemoryManager::createGraphicsAllocationFromSharedHandle(handle, properties, requireSpecificBitness); if (handle == CreateFromGlTexture::mcsHandle) { alloc->setDefaultGmm(forceMcsGmm); } else { alloc->setDefaultGmm(forceGmm); } return alloc; } size_t forceAllocationSize; Gmm *forceGmm = nullptr; Gmm *forceMcsGmm = nullptr; std::unique_ptr<ExecutionEnvironment> mockExecutionEnvironment; }; void SetUp() override { imgDesc = {}; imgInfo = {}; clContext.setSharingFunctions(glSharing->sharingFunctions.release()); ASSERT_FALSE(overrideCommandStreamReceiverCreation); clContext.memoryManager = &tempMM; } void TearDown() override { gmm.release(); mcsGmm.release(); } void updateImgInfoAndForceGmm() { imgInfo = MockGmm::initImgInfo(imgDesc, 0, nullptr); gmm = MockGmm::queryImgParams(imgInfo); tempMM.forceAllocationSize = imgInfo.size; tempMM.forceGmm = gmm.get(); if (glSharing->m_textureInfoOutput.globalShareHandleMCS != 0) { cl_image_desc mcsImgDesc = {}; mcsImgDesc.image_height = 128; mcsImgDesc.image_row_pitch = 256; mcsImgDesc.image_width = 128; mcsImgDesc.image_type = CL_MEM_OBJECT_IMAGE2D; auto mcsImgInfo = MockGmm::initImgInfo(mcsImgDesc, 0, nullptr); mcsGmm = MockGmm::queryImgParams(mcsImgInfo); tempMM.forceMcsGmm = mcsGmm.get(); } } cl_image_desc imgDesc; ImageInfo imgInfo = {0}; std::unique_ptr<Gmm> gmm; std::unique_ptr<Gmm> mcsGmm; TempMM tempMM; MockContext clContext; std::unique_ptr<MockGlSharing> glSharing = std::make_unique<MockGlSharing>(); cl_int retVal; static const unsigned int mcsHandle = 0xFF; }; class CreateFromGlTextureTestsWithParams : public CreateFromGlTexture, public ::testing::WithParamInterface<unsigned int /*cl_GLenum*/> { }; class CreateFromGlTextureTests : public CreateFromGlTexture { }; INSTANTIATE_TEST_CASE_P( CreateFromGlTextureTestsWithParams, CreateFromGlTextureTestsWithParams, testing::ValuesIn(glTextureTargets::supportedTargets)); TEST_P(CreateFromGlTextureTestsWithParams, givenAllTextureSpecificParamsWhenCreateIsCalledThenFillImageDescription) { unsigned int target = GetParam(); unsigned int baseTarget = GlTexture::getBaseTargetType(target); imgDesc.image_type = GlTexture::getClMemObjectType(target); imgDesc.image_width = 5; if (target == GL_TEXTURE_1D_ARRAY || target == GL_TEXTURE_2D_ARRAY || target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY) { imgDesc.image_array_size = 5; } if (target == GL_TEXTURE_2D || target == GL_TEXTURE_RECTANGLE || target == GL_TEXTURE_2D_ARRAY || target == GL_TEXTURE_3D || target == GL_RENDERBUFFER_EXT || baseTarget == GL_TEXTURE_CUBE_MAP_ARB || target == GL_TEXTURE_2D_MULTISAMPLE || target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY) { imgDesc.image_height = 5; } if (target == GL_TEXTURE_3D) { imgDesc.image_depth = 5; } if (target == GL_TEXTURE_BUFFER) { // size and width for texture buffer are queried from textureInfo - not from gmm glSharing->m_textureInfoOutput.textureBufferWidth = 64; glSharing->m_textureInfoOutput.textureBufferSize = 1024; glSharing->uploadDataToTextureInfo(); } if (target == GL_TEXTURE_2D_MULTISAMPLE || target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY) { imgDesc.num_samples = 16; glSharing->m_textureInfoOutput.numberOfSamples = 16; glSharing->m_textureInfoOutput.globalShareHandleMCS = CreateFromGlTexture::mcsHandle; glSharing->uploadDataToTextureInfo(); } updateImgInfoAndForceGmm(); auto glImage = GlTexture::createSharedGlTexture(&clContext, (cl_mem_flags)0, target, 0, 0, &retVal); ASSERT_EQ(CL_SUCCESS, retVal); if (target == GL_RENDERBUFFER_EXT) { EXPECT_EQ(1, glSharing->dllParam->getParam("GLAcquireSharedRenderBufferCalled")); } else { EXPECT_EQ(1, glSharing->dllParam->getParam("GLAcquireSharedTextureCalled")); } EXPECT_EQ(GmmHelper::getCubeFaceIndex(target), glImage->getCubeFaceIndex()); auto glTexture = reinterpret_cast<GlTexture *>(glImage->peekSharingHandler()); EXPECT_EQ(glTexture->getTarget(), target); EXPECT_EQ(glImage->getImageDesc().image_type, imgDesc.image_type); if (target == GL_TEXTURE_BUFFER) { EXPECT_EQ(glImage->getImageDesc().image_width, static_cast<size_t>(glTexture->getTextureInfo()->textureBufferWidth)); EXPECT_EQ(glImage->getImageDesc().image_row_pitch, static_cast<size_t>(glTexture->getTextureInfo()->textureBufferSize)); } else { EXPECT_EQ(glImage->getImageDesc().image_width, gmm->gmmResourceInfo->getBaseWidth()); size_t slicePitch = glImage->getHostPtrSlicePitch(); size_t rowPitch = glImage->getHostPtrRowPitch(); EXPECT_EQ(glImage->getImageDesc().image_row_pitch, rowPitch); EXPECT_EQ(glImage->getImageDesc().image_slice_pitch, slicePitch); size_t gmmRowPitch = gmm->gmmResourceInfo->getRenderPitch(); if (gmmRowPitch == 0) { size_t alignedWidth = alignUp(glImage->getImageDesc().image_width, gmm->gmmResourceInfo->getHAlign()); size_t bpp = gmm->gmmResourceInfo->getBitsPerPixel() >> 3; EXPECT_EQ(glImage->getImageDesc().image_row_pitch, alignedWidth * bpp); } else { EXPECT_EQ(glImage->getImageDesc().image_row_pitch, gmmRowPitch); } size_t ImageInfoRowPitch = 0; retVal = clGetImageInfo(glImage, CL_IMAGE_ROW_PITCH, sizeof(size_t), &ImageInfoRowPitch, NULL); ASSERT_EQ(CL_SUCCESS, retVal); ASSERT_EQ(rowPitch, ImageInfoRowPitch); size_t ImageInfoSlicePitch = 0; slicePitch *= !(glImage->getImageDesc().image_type == CL_MEM_OBJECT_IMAGE2D || glImage->getImageDesc().image_type == CL_MEM_OBJECT_IMAGE1D || glImage->getImageDesc().image_type == CL_MEM_OBJECT_IMAGE1D_BUFFER); retVal = clGetImageInfo(glImage, CL_IMAGE_SLICE_PITCH, sizeof(size_t), &ImageInfoSlicePitch, NULL); ASSERT_EQ(CL_SUCCESS, retVal); ASSERT_EQ(slicePitch, ImageInfoSlicePitch); } EXPECT_EQ(glImage->getImageDesc().image_height, gmm->gmmResourceInfo->getBaseHeight()); EXPECT_EQ(glImage->getImageDesc().image_array_size, gmm->gmmResourceInfo->getArraySize()); if (target == GL_TEXTURE_3D) { EXPECT_EQ(glImage->getImageDesc().image_depth, gmm->gmmResourceInfo->getBaseDepth()); } else { EXPECT_EQ(glImage->getImageDesc().image_depth, 0u); } if (imgDesc.image_array_size > 1 || imgDesc.image_depth > 1) { GMM_REQ_OFFSET_INFO GMMReqInfo = {}; GMMReqInfo.ArrayIndex = imgDesc.image_array_size > 1 ? 1 : 0; GMMReqInfo.Slice = imgDesc.image_depth > 1 ? 1 : 0; GMMReqInfo.ReqLock = 1; gmm->gmmResourceInfo->getOffset(GMMReqInfo); size_t expectedSlicePitch = GMMReqInfo.Lock.Offset; EXPECT_EQ(glImage->getImageDesc().image_slice_pitch, expectedSlicePitch); } else { EXPECT_EQ(glImage->getImageDesc().image_slice_pitch, imgInfo.size); } EXPECT_EQ(glImage->getQPitch(), gmm->queryQPitch(gmm->gmmResourceInfo->getResourceType())); // gmm returns 1 by default - OCL requires 0 uint32_t numSamples = static_cast<uint32_t>(gmm->gmmResourceInfo->getNumSamples()); auto expectedNumSamples = getValidParam(numSamples, 0u, 1u); EXPECT_EQ(expectedNumSamples, glImage->getImageDesc().num_samples); if (target == GL_TEXTURE_2D_MULTISAMPLE || target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY) { EXPECT_NE(nullptr, glImage->getMcsAllocation()); EXPECT_EQ(getValidParam(static_cast<uint32_t>(mcsGmm->gmmResourceInfo->getRenderPitch() / 128)), glImage->getMcsSurfaceInfo().pitch); EXPECT_EQ(static_cast<uint32_t>(mcsGmm->gmmResourceInfo->getQPitch()), glImage->getMcsSurfaceInfo().qPitch); EXPECT_EQ(GmmHelper::getRenderMultisamplesCount(static_cast<uint32_t>(gmm->gmmResourceInfo->getNumSamples())), glImage->getMcsSurfaceInfo().multisampleCount); } delete glImage; } TEST_P(CreateFromGlTextureTestsWithParams, givenArrayTextureTargetAndArraySizeEqualOneWhenCreateIsCalledThenSlicePitchAndSizeAreEqual) { unsigned int target = GetParam(); // only array targets if (target == GL_TEXTURE_1D_ARRAY || target == GL_TEXTURE_2D_ARRAY) { imgDesc.image_type = GlTexture::getClMemObjectType(target); imgDesc.image_width = 5; if (target == GL_TEXTURE_2D_ARRAY) { imgDesc.image_height = 5; } imgDesc.image_array_size = 1; updateImgInfoAndForceGmm(); auto glImage = GlTexture::createSharedGlTexture(&clContext, (cl_mem_flags)0, target, 0, 0, &retVal); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_EQ(glImage->getImageDesc().image_slice_pitch, imgInfo.size); delete glImage; } } TEST_P(CreateFromGlTextureTestsWithParams, givenZeroRowPitchFromGmmWhenCreatingTextureThenComputeIt) { unsigned int target = GL_TEXTURE_2D; imgDesc.image_type = GlTexture::getClMemObjectType(target); imgDesc.image_width = 5; imgDesc.image_height = 5; imgDesc.image_array_size = 1; updateImgInfoAndForceGmm(); auto mockResInfo = reinterpret_cast<::testing::NiceMock<MockGmmResourceInfo> *>(gmm->gmmResourceInfo.get()); mockResInfo->overrideReturnedRenderPitch(0u); auto alignedWidth = alignUp(imgDesc.image_width, gmm->gmmResourceInfo->getHAlign()); auto expectedRowPitch = alignedWidth * (gmm->gmmResourceInfo->getBitsPerPixel() >> 3); auto glImage = std::unique_ptr<Image>(GlTexture::createSharedGlTexture(&clContext, (cl_mem_flags)0, target, 0, 0, &retVal)); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_EQ(imgInfo.size, glImage->getImageDesc().image_slice_pitch); EXPECT_EQ(expectedRowPitch, glImage->getImageDesc().image_row_pitch); } TEST_F(CreateFromGlTextureTests, GivenGlTextureTargetAndMipLevelNegativeWhenCreateIsCalledThenMipMappedImageIsCreated) { unsigned int target = GL_TEXTURE_3D; cl_GLint miplevel = -1; imgDesc.image_type = GlTexture::getClMemObjectType(target); imgDesc.image_height = 13; imgDesc.image_width = 15; imgDesc.image_depth = 7; updateImgInfoAndForceGmm(); auto glImage = std::unique_ptr<Image>(GlTexture::createSharedGlTexture(&clContext, 0u, target, miplevel, 0, &retVal)); EXPECT_EQ(CL_SUCCESS, retVal); size_t actualHeight = 0; size_t actualWidth = 0; size_t actualDepth = 0; glImage->getImageInfo(CL_IMAGE_HEIGHT, sizeof(size_t), &actualHeight, nullptr); glImage->getImageInfo(CL_IMAGE_WIDTH, sizeof(size_t), &actualWidth, nullptr); glImage->getImageInfo(CL_IMAGE_DEPTH, sizeof(size_t), &actualDepth, nullptr); EXPECT_EQ(13u, actualHeight); EXPECT_EQ(15u, actualWidth); EXPECT_EQ(7u, actualDepth); EXPECT_EQ(gmm->gmmResourceInfo->getMaxLod() + 1, glImage->getImageDesc().num_mip_levels); EXPECT_EQ(glImage->peekBaseMipLevel(), 0); } TEST_F(CreateFromGlTextureTests, GivenGlTextureTargetAndMipLevelNonNegativeWhenCreateIsCalledThenImageFromChosenMipLevelIsCreated) { unsigned int target = GL_TEXTURE_3D; cl_GLint miplevel = 2; imgDesc.image_type = GlTexture::getClMemObjectType(target); imgDesc.image_height = 13; imgDesc.image_width = 15; imgDesc.image_depth = 7; updateImgInfoAndForceGmm(); auto glImage = std::unique_ptr<Image>(GlTexture::createSharedGlTexture(&clContext, 0u, target, miplevel, 0, &retVal)); EXPECT_EQ(CL_SUCCESS, retVal); size_t actualHeight = 0; size_t actualWidth = 0; size_t actualDepth = 0; glImage->getImageInfo(CL_IMAGE_HEIGHT, sizeof(size_t), &actualHeight, nullptr); glImage->getImageInfo(CL_IMAGE_WIDTH, sizeof(size_t), &actualWidth, nullptr); glImage->getImageInfo(CL_IMAGE_DEPTH, sizeof(size_t), &actualDepth, nullptr); EXPECT_EQ(3u, actualHeight); EXPECT_EQ(3u, actualWidth); EXPECT_EQ(1u, actualDepth); EXPECT_GE(1u, glImage->getImageDesc().num_mip_levels); EXPECT_EQ(glImage->peekBaseMipLevel(), 2); } TEST_F(CreateFromGlTextureTests, GivenGlTextureWhenCreateIsCalledThenAllocationTypeIsSharedImage) { unsigned int target = GL_TEXTURE_3D; cl_GLint miplevel = 2; imgDesc.image_type = GlTexture::getClMemObjectType(target); imgDesc.image_height = 13; imgDesc.image_width = 15; imgDesc.image_depth = 7; updateImgInfoAndForceGmm(); auto glImage = std::unique_ptr<Image>(GlTexture::createSharedGlTexture(&clContext, 0u, target, miplevel, 0, &retVal)); EXPECT_EQ(CL_SUCCESS, retVal); ASSERT_NE(nullptr, glImage->getGraphicsAllocation()); EXPECT_EQ(GraphicsAllocation::AllocationType::SHARED_IMAGE, glImage->getGraphicsAllocation()->getAllocationType()); } } // namespace NEO
41.33815
218
0.709851
cwang64
880f5d2038863ba860602fb540447258bd39b302
5,781
cpp
C++
src/InputSample.cpp
MSeys/PSV_2DCore_samples
3942c75391aeda9172dfed75165e80b5628a7a60
[ "MIT" ]
null
null
null
src/InputSample.cpp
MSeys/PSV_2DCore_samples
3942c75391aeda9172dfed75165e80b5628a7a60
[ "MIT" ]
null
null
null
src/InputSample.cpp
MSeys/PSV_2DCore_samples
3942c75391aeda9172dfed75165e80b5628a7a60
[ "MIT" ]
null
null
null
#include "InputSample.h" InputSample::InputSample() { } InputSample::~InputSample() { } void InputSample::Draw() const { // Note: This code was based on VitaTester (hence the code inside the Draw function instead of the respective event functions). // https://github.com/SMOKE5/VitaTester // // You can however check ONE button state (accessible through ButtonEvent / bEvent inside the function) // These are used in the menu, you can check out that class for an example how it works. // Draw background FillRect(Rectf{ 0, 0, float(SCREEN_WIDTH), float(SCREEN_HEIGHT) }, Color4{ 0, 0, 0, 255 }); Bank::FindUI("input_background")->Draw(Point2f{ 0, 54 }); // Draw analog sticks Bank::FindUI("analog")->Draw(Point2f{ 85.f + float(PSV_Joysticks.at(LSTICK).x - 128) / 8, 285.f + float(PSV_Joysticks.at(LSTICK).y - 128) / 8.f }); Bank::FindUI("analog")->Draw(Point2f{ 802.f + float(PSV_Joysticks.at(RSTICK).x - 128) / 8, 285.f + float(PSV_Joysticks.at(RSTICK).y - 128) / 8.f }); // This is a way to check directly in other functions besides the Event functions // These are also handy if you want to check multiple buttons states at the same time. if(PSV_Buttons.at(DPAD_UP).isPressed || PSV_Buttons.at(DPAD_UP).isHeld) { Bank::FindUI("dpad")->Draw(Point2f{ 59, 134 }); } if (PSV_Buttons.at(DPAD_DOWN).isPressed || PSV_Buttons.at(DPAD_DOWN).isHeld) { Bank::FindUI("dpad")->Draw(Point2f{ 130, 272 }, 3.14f); } if (PSV_Buttons.at(DPAD_LEFT).isPressed || PSV_Buttons.at(DPAD_LEFT).isHeld) { Bank::FindUI("dpad")->Draw(Point2f{ 24.3f, 238.6f }, -1.57f); } if (PSV_Buttons.at(DPAD_RIGHT).isPressed || PSV_Buttons.at(DPAD_RIGHT).isHeld) { Bank::FindUI("dpad")->Draw(Point2f{ 164, 166 }, 1.57f); } if (PSV_Buttons.at(CROSS).isPressed || PSV_Buttons.at(CROSS).isHeld) { Bank::FindUI("cross")->Draw(Point2f{ 830, 202 }); } if (PSV_Buttons.at(CIRCLE).isPressed || PSV_Buttons.at(CIRCLE).isHeld) { Bank::FindUI("circle")->Draw(Point2f{ 869, 165 }); } if (PSV_Buttons.at(SQUARE).isPressed || PSV_Buttons.at(SQUARE).isHeld) { Bank::FindUI("square")->Draw(Point2f{ 790, 165 }); } if (PSV_Buttons.at(TRIANGLE).isPressed || PSV_Buttons.at(TRIANGLE).isHeld) { Bank::FindUI("triangle")->Draw(Point2f{ 830, 127 }); } if (PSV_Buttons.at(START).isPressed || PSV_Buttons.at(START).isHeld) { Bank::FindUI("start")->Draw(Point2f{ 841, 373 }); } if (PSV_Buttons.at(SELECT).isPressed || PSV_Buttons.at(SELECT).isHeld) { Bank::FindUI("select")->Draw(Point2f{ 781, 375 }); } if (PSV_Buttons.at(LTRIGGER).isPressed || PSV_Buttons.at(LTRIGGER).isHeld) { Bank::FindUI("ltrigger")->Draw(Point2f{ 38, 40 }); } if (PSV_Buttons.at(RTRIGGER).isPressed || PSV_Buttons.at(RTRIGGER).isHeld) { Bank::FindUI("rtrigger")->Draw(Point2f{ 720, 40 }); } } void InputSample::ProcessKeyUpEvent(const PSV_ButtonEvent& bEvent) { // Example of key event - triggered on release if(bEvent.buttonType == SQUARE) { // if Square is released } // you can also use a switch switch (bEvent.buttonType) { case CROSS: break; case CIRCLE: break; case SQUARE: break; case TRIANGLE: break; case LTRIGGER: break; case RTRIGGER: break; case DPAD_UP: break; case DPAD_DOWN: break; case DPAD_LEFT: break; case DPAD_RIGHT: break; case START: break; case SELECT: break; default: break; } // Note: There is not much data to send with button actions except held, pressed or released, but these are handled separately. } void InputSample::ProcessKeyDownEvent(const PSV_ButtonEvent& bEvent) { // Example of key event - triggered on press // pressed state changes to false if button gets released or goes into held after 0.4 seconds if(bEvent.buttonType == CIRCLE) { // if Circle is pressed } // you can also use a switch switch (bEvent.buttonType) { case CROSS: break; case CIRCLE: break; case SQUARE: break; case TRIANGLE: break; case LTRIGGER: break; case RTRIGGER: break; case DPAD_UP: break; case DPAD_DOWN: break; case DPAD_LEFT: break; case DPAD_RIGHT: break; case START: break; case SELECT: break; default: break; } // Note: There is not much data to send with button actions except held, pressed or released, but these are handled separately. } void InputSample::ProcessKeyHeldEvent(const PSV_ButtonEvent& bEvent) { // Example of key event - triggered on held (which is after 0.4 seconds) // held state changes to false if button gets released if(bEvent.buttonType == CROSS) { // if Cross is held } // you can also use a switch switch (bEvent.buttonType) { case CROSS: break; case CIRCLE: break; case SQUARE: break; case TRIANGLE: break; case LTRIGGER: break; case RTRIGGER: break; case DPAD_UP: break; case DPAD_DOWN: break; case DPAD_LEFT: break; case DPAD_RIGHT: break; case START: break; case SELECT: break; default: break; } // Note: There is not much data to send with button actions except held, pressed or released, but these are handled separately. } void InputSample::ProcessJoystickMotionEvent(const PSV_JoystickEvent& jEvent) { //Example of joystick motion if(jEvent.joyType == LSTICK) { // Direction of joystick, including 4 main directions, the diagonals and the middle/idle position. if(jEvent.joyDirection == MIDDLE) { // Middle position } else if(jEvent.joyDirection == NE) { // North east direction } // You can also use a switch case switch(jEvent.joyDirection) { case NW: break; case N: break; case NE: break; case W: break; case E: break; case SW: break; case S: break; case SE: break; case MIDDLE: break; default: break; } } // There is also more values you can get using the JoystickEvent such as the x and y value, aswell as the angle the stick is positioned in, in radians or degrees. }
26.640553
163
0.702647
MSeys
8811e63ba85df59615c1468a1fb1ee9b480581d3
811
hpp
C++
Source/SFMLIntegration/CSprite.hpp
sizlo/TimGameLib
b70605c4b043a928645f063a2bb3b267fa91f2c6
[ "MIT" ]
null
null
null
Source/SFMLIntegration/CSprite.hpp
sizlo/TimGameLib
b70605c4b043a928645f063a2bb3b267fa91f2c6
[ "MIT" ]
null
null
null
Source/SFMLIntegration/CSprite.hpp
sizlo/TimGameLib
b70605c4b043a928645f063a2bb3b267fa91f2c6
[ "MIT" ]
null
null
null
// // CSprite.hpp // TimGameLib // // Created by Tim Brier on 18/10/2014. // Copyright (c) 2014 tbrier. All rights reserved. // #ifndef __TimeGameLib__CSprite__ #define __TimeGameLib__CSprite__ // ============================================================================= // Include files // ----------------------------------------------------------------------------- #include <SFML/Graphics.hpp> // ============================================================================= // Class definition // ----------------------------------------------------------------------------- class CSprite : public sf::Sprite { public: CSprite(); CSprite(std::string filename); CSprite(std::string filename, bool flipX, bool flipY); ~CSprite(); }; #endif /* defined(__TimeGameLib__CSprite__) */
27.033333
80
0.420469
sizlo
8814c5fa438660fa67acf61756d1f707129f6e9a
3,674
hpp
C++
inc/Measure.hpp
RuneKokNielsen/TopAwaRe
de5099111fca790a3ddf46aeb7f7aeae70229715
[ "MIT" ]
2
2019-11-28T11:45:50.000Z
2020-03-25T13:38:29.000Z
inc/Measure.hpp
RuneKokNielsen/TopAwaRe
de5099111fca790a3ddf46aeb7f7aeae70229715
[ "MIT" ]
null
null
null
inc/Measure.hpp
RuneKokNielsen/TopAwaRe
de5099111fca790a3ddf46aeb7f7aeae70229715
[ "MIT" ]
null
null
null
#ifndef MEASURE_HPP #define MEASURE_HPP #include "Node.hpp" #include <Image.hpp> #include "Interpolator.hpp" namespace measure{ /** * A Context holds time-local variables necessary for locally * computing a measure and its gradients. **/ struct Context{ /** * \param timesteps The number of timesteps within this context. **/ Context(uint timesteps): _timesteps(timesteps){ }; /** * Get the context at given timestep. * \param timestep The timestep of the target context. **/ virtual Context* getContext(uint timestep) = 0; // Number of timesteps of the context. uint _timesteps; // Interpolator object which might be required for computations. Interpolator* _interpolator; virtual ~Context(){ } /** * Initialize the context with required objects. * \param S The target image. * \param I The source image. * \param interpolator Interpolator object to be used within this context. **/ virtual void init(Image S, Image I, Interpolator* interpolator){ _I = I; _S = S; _interpolator = interpolator; } /** * Update the context based on the current transformation at the * timestep of this context. **/ virtual void update(vector<Image> phi, vector<Image> phiInv){ // Surpress unused-warning of optional virtual function (void) phi; (void) phiInv; }; // Reference to the source image. Image _I; // Reference to the target image. Image _S; /** * Holds the individual contexts for all timesteps, this object * corresponding to the first element. **/ vector<Context*> _subs; }; /** * A Measure describes how to compute a given similarity measure * as well as its gradients within a given Measure::Context. **/ class Measure : Conf::Node { public: /** * Given a context, computes the similarity measure value. * \param context The context to compute the measure in. **/ virtual double measure(const Context* context) const = 0; /** * Given a context, computes the gradient of the similarity measure. * \param context The context to compute the gradient in. **/ virtual vector<Image> gradient(const Context* context) const = 0; /** * Returns the default context for a dsicretization with * given number of timesteps. * \param timesteps The number of timesteps. **/ virtual Context *baseContext(uint timesteps) const = 0; }; /** * An AlphaContext is any Measure::Context that somehow handles * an alpha channel. This is required for applying the * topology-aware parts of the implementation. **/ struct AlphaContext : virtual Context{ AlphaContext(): Context(1){ } virtual ~AlphaContext(){ } /** * Returns a copy of itself that can be modified without changing * anything within this context. **/ virtual AlphaContext* copy() = 0; virtual AlphaContext *getContext(uint t){ return t==0?this:dynamic_cast<AlphaContext*>(_subs.at(t)); } /** * One-sided update. * This function is used for finite difference approximation * of the gradient w.r.t. changes in the singularity model. * Updates the context using a full transformation. * Note that the alpha field within this context has already * accounted for this transformation and as such should not * be transformed again! * \param phi Transformation to apply. **/ virtual void updateAlpha(vector<Image> phi) = 0; /** * Current alpha field. **/ Image alpha; }; } #endif
26.056738
106
0.650517
RuneKokNielsen
8816bf9e86f575c772285e37008732f0191fcafc
42,515
cc
C++
processors/IA32/bochs/iodev/cdrom.cc
bavison/opensmalltalk-vm
d494240736f7c0309e3e819784feb1d53ed0985a
[ "MIT" ]
445
2016-06-30T08:19:11.000Z
2022-03-28T06:09:49.000Z
processors/IA32/bochs/iodev/cdrom.cc
bavison/opensmalltalk-vm
d494240736f7c0309e3e819784feb1d53ed0985a
[ "MIT" ]
439
2016-06-29T20:14:36.000Z
2022-03-17T19:59:58.000Z
processors/IA32/bochs/iodev/cdrom.cc
bavison/opensmalltalk-vm
d494240736f7c0309e3e819784feb1d53ed0985a
[ "MIT" ]
137
2016-07-02T17:32:07.000Z
2022-03-20T11:17:25.000Z
///////////////////////////////////////////////////////////////////////// // $Id: cdrom.cc,v 1.91 2008/02/15 22:05:41 sshwarts Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2002 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ///////////////////////////////////////////////////////////////////////// // These are the low-level CDROM functions which are called // from 'harddrv.cc'. They effect the OS specific functionality // needed by the CDROM emulation in 'harddrv.cc'. Mostly, just // ioctl() calls and such. Should be fairly easy to add support // for your OS if it is not supported yet. #ifndef BX_IODEV_CDROM_H #define BX_IODEV_CDROM_H // Define BX_PLUGGABLE in files that can be compiled into plugins. For // platforms that require a special tag on exported symbols, BX_PLUGGABLE // is used to know when we are exporting symbols and when we are importing. #define BX_PLUGGABLE #include "bochs.h" #if BX_SUPPORT_CDROM #include "cdrom.h" #define LOG_THIS /* no SMF tricks here, not needed */ extern "C" { #include <errno.h> } #ifdef __linux__ extern "C" { #include <sys/ioctl.h> #include <linux/cdrom.h> // I use the framesize in non OS specific code too #define BX_CD_FRAMESIZE CD_FRAMESIZE } #elif defined(__GNU__) || (defined(__CYGWIN32__) && !defined(WIN32)) extern "C" { #include <sys/ioctl.h> #define BX_CD_FRAMESIZE 2048 #define CD_FRAMESIZE 2048 } #elif BX_WITH_MACOS #define BX_CD_FRAMESIZE 2048 #define CD_FRAMESIZE 2048 #elif defined(__sun) extern "C" { #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <sys/cdio.h> #define BX_CD_FRAMESIZE CDROM_BLK_2048 } #elif defined(__DJGPP__) extern "C" { #include <sys/ioctl.h> #define BX_CD_FRAMESIZE 2048 #define CD_FRAMESIZE 2048 } #elif defined(__BEOS__) #include "cdrom_beos.h" #define BX_CD_FRAMESIZE 2048 #elif (defined(__NetBSD__) || defined(__NetBSD_kernel__) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)) // OpenBSD pre version 2.7 may require extern "C" { } structure around // all the includes, because the i386 sys/disklabel.h contains code which // c++ considers invalid. #include <sys/types.h> #include <sys/param.h> #include <sys/file.h> #include <sys/cdio.h> #include <sys/ioctl.h> #include <sys/disklabel.h> // ntohl(x) et al have been moved out of sys/param.h in FreeBSD 5 #include <netinet/in.h> // XXX #define BX_CD_FRAMESIZE 2048 #define CD_FRAMESIZE 2048 #elif defined(__APPLE__) #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> #if defined (__GNUC__) && (__GNUC__ >= 4) #include <sys/disk.h> #else #include <dev/disk.h> #endif #include <errno.h> #include <paths.h> #include <sys/param.h> #define Float32 KLUDGE_Float32 #define Float64 KLUDGE_Float64 #include <IOKit/IOKitLib.h> #include <IOKit/IOBSD.h> #include <IOKit/storage/IOCDMedia.h> #include <IOKit/storage/IOMedia.h> #include <IOKit/storage/IOCDTypes.h> #include <CoreFoundation/CoreFoundation.h> #undef Float32 #undef Float64 // These definitions were taken from mount_cd9660.c // There are some similar definitions in IOCDTypes.h // however there seems to be some dissagreement in // the definition of CDTOC.length struct _CDMSF { u_char minute; u_char second; u_char frame; }; #define MSF_TO_LBA(msf) \ (((((msf).minute * 60UL) + (msf).second) * 75UL) + (msf).frame - 150) struct _CDTOC_Desc { u_char session; u_char ctrl_adr; /* typed to be machine and compiler independent */ u_char tno; u_char point; struct _CDMSF address; u_char zero; struct _CDMSF p; }; struct _CDTOC { u_short length; /* in native cpu endian */ u_char first_session; u_char last_session; struct _CDTOC_Desc trackdesc[1]; }; static kern_return_t FindEjectableCDMedia(io_iterator_t *mediaIterator, mach_port_t *masterPort); static kern_return_t GetDeviceFilePath(io_iterator_t mediaIterator, char *deviceFilePath, CFIndex maxPathSize); //int OpenDrive(const char *deviceFilePath); static struct _CDTOC *ReadTOC(const char *devpath); static char CDDevicePath[MAXPATHLEN]; #define BX_CD_FRAMESIZE 2048 #define CD_FRAMESIZE 2048 #elif defined(WIN32) // windows.h included by bochs.h #include <winioctl.h> #include "aspi-win32.h" #include "scsidefs.h" DWORD (*GetASPI32SupportInfo)(void); DWORD (*SendASPI32Command)(LPSRB); BOOL (*GetASPI32Buffer)(PASPI32BUFF); BOOL (*FreeASPI32Buffer)(PASPI32BUFF); BOOL (*TranslateASPI32Address)(PDWORD,PDWORD); DWORD (*GetASPI32DLLVersion)(void); static OSVERSIONINFO osinfo; static BOOL isWindowsXP; static BOOL bHaveDev; static UINT cdromCount = 0; static HINSTANCE hASPI = NULL; #define BX_CD_FRAMESIZE 2048 #define CD_FRAMESIZE 2048 // READ_TOC_EX structure(s) and #defines #define CDROM_READ_TOC_EX_FORMAT_TOC 0x00 #define CDROM_READ_TOC_EX_FORMAT_SESSION 0x01 #define CDROM_READ_TOC_EX_FORMAT_FULL_TOC 0x02 #define CDROM_READ_TOC_EX_FORMAT_PMA 0x03 #define CDROM_READ_TOC_EX_FORMAT_ATIP 0x04 #define CDROM_READ_TOC_EX_FORMAT_CDTEXT 0x05 #define IOCTL_CDROM_BASE FILE_DEVICE_CD_ROM #define IOCTL_CDROM_READ_TOC_EX CTL_CODE(IOCTL_CDROM_BASE, 0x0015, METHOD_BUFFERED, FILE_READ_ACCESS) #ifndef IOCTL_DISK_GET_LENGTH_INFO #define IOCTL_DISK_GET_LENGTH_INFO CTL_CODE(IOCTL_DISK_BASE, 0x0017, METHOD_BUFFERED, FILE_READ_ACCESS) #endif typedef struct _CDROM_READ_TOC_EX { UCHAR Format : 4; UCHAR Reserved1 : 3; // future expansion UCHAR Msf : 1; UCHAR SessionTrack; UCHAR Reserved2; // future expansion UCHAR Reserved3; // future expansion } CDROM_READ_TOC_EX, *PCDROM_READ_TOC_EX; typedef struct _TRACK_DATA { UCHAR Reserved; UCHAR Control : 4; UCHAR Adr : 4; UCHAR TrackNumber; UCHAR Reserved1; UCHAR Address[4]; } TRACK_DATA, *PTRACK_DATA; typedef struct _CDROM_TOC_SESSION_DATA { // Header UCHAR Length[2]; // add two bytes for this field UCHAR FirstCompleteSession; UCHAR LastCompleteSession; // One track, representing the first track // of the last finished session TRACK_DATA TrackData[1]; } CDROM_TOC_SESSION_DATA, *PCDROM_TOC_SESSION_DATA; // End READ_TOC_EX structure(s) and #defines #else // all others (Irix, Tru64) #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #define BX_CD_FRAMESIZE 2048 #define CD_FRAMESIZE 2048 #endif #include <stdio.h> #ifdef __APPLE__ static kern_return_t FindEjectableCDMedia(io_iterator_t *mediaIterator, mach_port_t *masterPort) { kern_return_t kernResult; CFMutableDictionaryRef classesToMatch; kernResult = IOMasterPort(bootstrap_port, masterPort); if (kernResult != KERN_SUCCESS) { fprintf (stderr, "IOMasterPort returned %d\n", kernResult); return kernResult; } // CD media are instances of class kIOCDMediaClass. classesToMatch = IOServiceMatching(kIOCDMediaClass); if (classesToMatch == NULL) fprintf (stderr, "IOServiceMatching returned a NULL dictionary.\n"); else { // Each IOMedia object has a property with key kIOMediaEjectableKey // which is true if the media is indeed ejectable. So add property // to CFDictionary for matching. CFDictionarySetValue(classesToMatch, CFSTR(kIOMediaEjectableKey), kCFBooleanTrue); } kernResult = IOServiceGetMatchingServices(*masterPort, classesToMatch, mediaIterator); if ((kernResult != KERN_SUCCESS) || (*mediaIterator == NULL)) fprintf(stderr, "No ejectable CD media found.\n kernResult = %d\n", kernResult); return kernResult; } static kern_return_t GetDeviceFilePath(io_iterator_t mediaIterator, char *deviceFilePath, CFIndex maxPathSize) { io_object_t nextMedia; kern_return_t kernResult = KERN_FAILURE; nextMedia = IOIteratorNext(mediaIterator); if (nextMedia == NULL) { *deviceFilePath = '\0'; } else { CFTypeRef deviceFilePathAsCFString; deviceFilePathAsCFString = IORegistryEntryCreateCFProperty(nextMedia, CFSTR(kIOBSDNameKey), kCFAllocatorDefault, 0); *deviceFilePath = '\0'; if (deviceFilePathAsCFString) { size_t devPathLength = strlen(_PATH_DEV); strcpy(deviceFilePath, _PATH_DEV); if (CFStringGetCString((const __CFString *) deviceFilePathAsCFString, deviceFilePath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII)) { // fprintf(stderr, "BSD path: %s\n", deviceFilePath); kernResult = KERN_SUCCESS; } CFRelease(deviceFilePathAsCFString); } } IOObjectRelease(nextMedia); return kernResult; } static int OpenDrive(const char *deviceFilePath) { int fileDescriptor = open(deviceFilePath, O_RDONLY); if (fileDescriptor == -1) fprintf(stderr, "Error %d opening device %s.\n", errno, deviceFilePath); return fileDescriptor; } static struct _CDTOC * ReadTOC(const char *devpath) { struct _CDTOC * toc_p = NULL; io_iterator_t iterator = 0; io_registry_entry_t service = 0; CFDictionaryRef properties = 0; CFDataRef data = 0; mach_port_t port = 0; char *devname; if ((devname = strrchr(devpath, '/')) != NULL) { ++devname; } else { devname = (char *) devpath; } if (IOMasterPort(bootstrap_port, &port) != KERN_SUCCESS) { fprintf(stderr, "IOMasterPort failed\n"); goto Exit; } if (IOServiceGetMatchingServices(port, IOBSDNameMatching(port, 0, devname), &iterator) != KERN_SUCCESS) { fprintf(stderr, "IOServiceGetMatchingServices failed\n"); goto Exit; } service = IOIteratorNext(iterator); IOObjectRelease(iterator); iterator = 0; while (service && !IOObjectConformsTo(service, "IOCDMedia")) { if (IORegistryEntryGetParentIterator(service, kIOServicePlane, &iterator) != KERN_SUCCESS) { fprintf(stderr, "IORegistryEntryGetParentIterator failed\n"); goto Exit; } IOObjectRelease(service); service = IOIteratorNext(iterator); IOObjectRelease(iterator); } if (service == NULL) { fprintf(stderr, "CD media not found\n"); goto Exit; } if (IORegistryEntryCreateCFProperties(service, (__CFDictionary **) &properties, kCFAllocatorDefault, kNilOptions) != KERN_SUCCESS) { fprintf(stderr, "IORegistryEntryGetParentIterator failed\n"); goto Exit; } data = (CFDataRef) CFDictionaryGetValue(properties, CFSTR(kIOCDMediaTOCKey)); if (data == NULL) { fprintf(stderr, "CFDictionaryGetValue failed\n"); goto Exit; } else { CFRange range; CFIndex buflen; buflen = CFDataGetLength(data) + 1; range = CFRangeMake(0, buflen); toc_p = (struct _CDTOC *) malloc(buflen); if (toc_p == NULL) { fprintf(stderr, "Out of memory\n"); goto Exit; } else { CFDataGetBytes(data, range, (unsigned char *) toc_p); } /* fprintf(stderr, "Table of contents\n length %d first %d last %d\n", toc_p->length, toc_p->first_session, toc_p->last_session); */ CFRelease(properties); } Exit: if (service) { IOObjectRelease(service); } return toc_p; } #endif #ifdef WIN32 bool ReadCDSector(unsigned int hid, unsigned int tid, unsigned int lun, unsigned long frame, unsigned char *buf, int bufsize) { HANDLE hEventSRB; SRB_ExecSCSICmd srb; DWORD dwStatus; hEventSRB = CreateEvent(NULL, TRUE, FALSE, NULL); memset(&srb,0,sizeof(SRB_ExecSCSICmd)); srb.SRB_Cmd = SC_EXEC_SCSI_CMD; srb.SRB_HaId = hid; srb.SRB_Target = tid; srb.SRB_Lun = lun; srb.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY; srb.SRB_SenseLen = SENSE_LEN; srb.SRB_PostProc = hEventSRB; srb.SRB_BufPointer = buf; srb.SRB_BufLen = bufsize; srb.SRB_CDBLen = 10; srb.CDBByte[0] = SCSI_READ10; srb.CDBByte[2] = (unsigned char) (frame>>24); srb.CDBByte[3] = (unsigned char) (frame>>16); srb.CDBByte[4] = (unsigned char) (frame>>8); srb.CDBByte[5] = (unsigned char) (frame); srb.CDBByte[7] = 0; srb.CDBByte[8] = 1; /* read 1 frames */ ResetEvent(hEventSRB); dwStatus = SendASPI32Command((SRB *)&srb); if(dwStatus == SS_PENDING) { WaitForSingleObject(hEventSRB, 100000); } CloseHandle(hEventSRB); return (srb.SRB_TargStat == STATUS_GOOD); } int GetCDCapacity(unsigned int hid, unsigned int tid, unsigned int lun) { HANDLE hEventSRB; SRB_ExecSCSICmd srb; DWORD dwStatus; unsigned char buf[8]; hEventSRB = CreateEvent(NULL, TRUE, FALSE, NULL); memset(&buf, 0, sizeof(buf)); memset(&srb,0,sizeof(SRB_ExecSCSICmd)); srb.SRB_Cmd = SC_EXEC_SCSI_CMD; srb.SRB_HaId = hid; srb.SRB_Target = tid; srb.SRB_Lun = lun; srb.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY; srb.SRB_SenseLen = SENSE_LEN; srb.SRB_PostProc = hEventSRB; srb.SRB_BufPointer = (unsigned char *)buf; srb.SRB_BufLen = 8; srb.SRB_CDBLen = 10; srb.CDBByte[0] = SCSI_READCDCAP; srb.CDBByte[2] = 0; srb.CDBByte[3] = 0; srb.CDBByte[4] = 0; srb.CDBByte[5] = 0; srb.CDBByte[8] = 0; ResetEvent(hEventSRB); dwStatus = SendASPI32Command((SRB *)&srb); if(dwStatus == SS_PENDING) { WaitForSingleObject(hEventSRB, 100000); } CloseHandle(hEventSRB); return ((buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3]) * ((buf[4] << 24) + (buf[5] << 16) + (buf[6] << 8) + buf[7]); } #endif cdrom_interface::cdrom_interface(char *dev) { put("CD"); settype(CDLOG); fd = -1; // File descriptor not yet allocated if (dev == NULL) { path = NULL; } else { path = strdup(dev); } using_file=0; #ifdef WIN32 bUseASPI = FALSE; osinfo.dwOSVersionInfoSize = sizeof(osinfo); GetVersionEx(&osinfo); isWindowsXP = (osinfo.dwMajorVersion >= 5) && (osinfo.dwMinorVersion >= 1); #endif } void cdrom_interface::init(void) { BX_DEBUG(("Init $Id: cdrom.cc,v 1.91 2008/02/15 22:05:41 sshwarts Exp $")); BX_INFO(("file = '%s'",path)); } cdrom_interface::~cdrom_interface(void) { #ifdef WIN32 #else if (fd >= 0) close(fd); #endif if (path) free(path); BX_DEBUG(("Exit")); } bx_bool cdrom_interface::insert_cdrom(char *dev) { unsigned char buffer[BX_CD_FRAMESIZE]; #ifndef WIN32 ssize_t ret; #endif // Load CD-ROM. Returns 0 if CD is not ready. if (dev != NULL) path = strdup(dev); BX_INFO (("load cdrom with path=%s", path)); #ifdef WIN32 char drive[256]; if ((path[1] == ':') && (strlen(path) == 2)) { if(osinfo.dwPlatformId == VER_PLATFORM_WIN32_NT) { // Use direct device access under windows NT/2k/XP // With all the backslashes it's hard to see, but to open D: drive // the name would be: \\.\d: sprintf(drive, "\\\\.\\%s", path); BX_INFO (("Using direct access for cdrom.")); // This trick only works for Win2k and WinNT, so warn the user of that. } else { BX_INFO(("Using ASPI for cdrom. Drive letters are unused yet.")); bUseASPI = TRUE; } using_file = 0; } else { strcpy(drive,path); using_file = 1; BX_INFO (("Opening image file as a cd")); } if(bUseASPI) { DWORD d; UINT cdr, cnt, max; UINT i, j, k; SRB_HAInquiry sh; SRB_GDEVBlock sd; if (!hASPI) { hASPI = LoadLibrary("WNASPI32.DLL"); if (hASPI) { SendASPI32Command = (DWORD(*)(LPSRB))GetProcAddress(hASPI, "SendASPI32Command"); GetASPI32DLLVersion = (DWORD(*)(void))GetProcAddress(hASPI, "GetASPI32DLLVersion"); GetASPI32SupportInfo = (DWORD(*)(void))GetProcAddress(hASPI, "GetASPI32SupportInfo"); d = GetASPI32DLLVersion(); BX_INFO(("WNASPI32.DLL version %d.%02d initialized", d & 0xff, (d >> 8) & 0xff)); } else { BX_PANIC(("Could not load ASPI drivers, so cdrom access will fail")); return 0; } } cdr = 0; bHaveDev = FALSE; d = GetASPI32SupportInfo(); cnt = LOBYTE(LOWORD(d)); for(i = 0; i < cnt; i++) { memset(&sh, 0, sizeof(sh)); sh.SRB_Cmd = SC_HA_INQUIRY; sh.SRB_HaId = i; SendASPI32Command((LPSRB)&sh); if(sh.SRB_Status != SS_COMP) continue; max = (int)sh.HA_Unique[3]; for(j = 0; j < max; j++) { for(k = 0; k < 8; k++) { memset(&sd, 0, sizeof(sd)); sd.SRB_Cmd = SC_GET_DEV_TYPE; sd.SRB_HaId = i; sd.SRB_Target = j; sd.SRB_Lun = k; SendASPI32Command((LPSRB)&sd); if(sd.SRB_Status == SS_COMP) { if(sd.SRB_DeviceType == DTYPE_CDROM) { cdr++; if(cdr > cdromCount) { hid = i; tid = j; lun = k; cdromCount++; bHaveDev = TRUE; } } } if(bHaveDev) break; } if(bHaveDev) break; } } fd=1; } else { hFile=CreateFile((char *)&drive, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, NULL); if (hFile !=(void *)0xFFFFFFFF) fd=1; if (!using_file) { DWORD lpBytesReturned; DeviceIoControl(hFile, IOCTL_STORAGE_LOAD_MEDIA, NULL, 0, NULL, 0, &lpBytesReturned, NULL); } } #elif defined(__APPLE__) if(strcmp(path, "drive") == 0) { mach_port_t masterPort = NULL; io_iterator_t mediaIterator; kern_return_t kernResult; BX_INFO(("Insert CDROM")); kernResult = FindEjectableCDMedia(&mediaIterator, &masterPort); if (kernResult != KERN_SUCCESS) { BX_INFO(("Unable to find CDROM")); return 0; } kernResult = GetDeviceFilePath(mediaIterator, CDDevicePath, sizeof(CDDevicePath)); if (kernResult != KERN_SUCCESS) { BX_INFO(("Unable to get CDROM device file path")); return 0; } // Here a cdrom was found so see if we can read from it. // At this point a failure will result in panic. if (strlen(CDDevicePath)) { fd = open(CDDevicePath, O_RDONLY); } } else { fd = open(path, O_RDONLY); } #else // all platforms except win32 fd = open(path, O_RDONLY); #endif if (fd < 0) { BX_ERROR(("open cd failed for %s: %s", path, strerror(errno))); return 0; } #ifndef WIN32 // do fstat to determine if it's a file or a device, then set using_file. struct stat stat_buf; ret = fstat (fd, &stat_buf); if (ret) { BX_PANIC (("fstat cdrom file returned error: %s", strerror (errno))); } if (S_ISREG (stat_buf.st_mode)) { using_file = 1; BX_INFO (("Opening image file %s as a cd.", path)); } else { using_file = 0; BX_INFO (("Using direct access for cdrom.")); } #endif // I just see if I can read a sector to verify that a // CD is in the drive and readable. return read_block(buffer, 0, 2048); } bx_bool cdrom_interface::start_cdrom() { // Spin up the cdrom drive. if (fd >= 0) { #if defined(__NetBSD__) || defined(__NetBSD_kernel__) if (ioctl (fd, CDIOCSTART) < 0) BX_DEBUG(("start_cdrom: start returns error: %s", strerror (errno))); return 1; #else BX_INFO(("start_cdrom: your OS is not supported yet")); return 0; // OS not supported yet, return 0 always #endif } return 0; } void cdrom_interface::eject_cdrom() { // Logically eject the CD. I suppose we could stick in // some ioctl() calls to really eject the CD as well. if (fd >= 0) { #if (defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)) (void) ioctl (fd, CDIOCALLOW); if (ioctl (fd, CDIOCEJECT) < 0) BX_DEBUG(("eject_cdrom: eject returns error")); #endif #ifdef WIN32 if (using_file == 0) { if(bUseASPI) { } else { DWORD lpBytesReturned; DeviceIoControl(hFile, IOCTL_STORAGE_EJECT_MEDIA, NULL, 0, NULL, 0, &lpBytesReturned, NULL); } } #else // WIN32 #if __linux__ if (!using_file) ioctl (fd, CDROMEJECT, NULL); #endif close(fd); #endif // WIN32 fd = -1; } } bx_bool cdrom_interface::read_toc(Bit8u* buf, int* length, bx_bool msf, int start_track, int format) { unsigned i; // Read CD TOC. Returns 0 if start track is out of bounds. if (fd < 0) { BX_PANIC(("cdrom: read_toc: file not open.")); return 0; } // This is a hack and works okay if there's one rom track only #if defined(WIN32) if (!isWindowsXP || using_file) { #else if (using_file || (format != 0)) { #endif Bit32u blocks; int len = 4; switch (format) { case 0: // From atapi specs : start track can be 0-63, AA if ((start_track > 1) && (start_track != 0xaa)) return 0; buf[2] = 1; buf[3] = 1; if (start_track <= 1) { buf[len++] = 0; // Reserved buf[len++] = 0x14; // ADR, control buf[len++] = 1; // Track number buf[len++] = 0; // Reserved // Start address if (msf) { buf[len++] = 0; // reserved buf[len++] = 0; // minute buf[len++] = 2; // second buf[len++] = 0; // frame } else { buf[len++] = 0; buf[len++] = 0; buf[len++] = 0; buf[len++] = 0; // logical sector 0 } } // Lead out track buf[len++] = 0; // Reserved buf[len++] = 0x16; // ADR, control buf[len++] = 0xaa; // Track number buf[len++] = 0; // Reserved blocks = capacity(); // Start address if (msf) { buf[len++] = 0; // reserved buf[len++] = (Bit8u)(((blocks + 150) / 75) / 60); // minute buf[len++] = (Bit8u)(((blocks + 150) / 75) % 60); // second buf[len++] = (Bit8u)((blocks + 150) % 75); // frame; } else { buf[len++] = (blocks >> 24) & 0xff; buf[len++] = (blocks >> 16) & 0xff; buf[len++] = (blocks >> 8) & 0xff; buf[len++] = (blocks >> 0) & 0xff; } buf[0] = ((len-2) >> 8) & 0xff; buf[1] = (len-2) & 0xff; break; case 1: // multi session stuff - emulate a single session only buf[0] = 0; buf[1] = 0x0a; buf[2] = 1; buf[3] = 1; for (i = 0; i < 8; i++) buf[4+i] = 0; len = 12; break; case 2: // raw toc - emulate a single session only (ported from qemu) buf[2] = 1; buf[3] = 1; for (i = 0; i < 4; i++) { buf[len++] = 1; buf[len++] = 0x14; buf[len++] = 0; if (i < 3) { buf[len++] = 0xa0 + i; } else { buf[len++] = 1; } buf[len++] = 0; buf[len++] = 0; buf[len++] = 0; if (i < 2) { buf[len++] = 0; buf[len++] = 1; buf[len++] = 0; buf[len++] = 0; } else if (i == 2) { blocks = capacity(); if (msf) { buf[len++] = 0; // reserved buf[len++] = (Bit8u)(((blocks + 150) / 75) / 60); // minute buf[len++] = (Bit8u)(((blocks + 150) / 75) % 60); // second buf[len++] = (Bit8u)((blocks + 150) % 75); // frame; } else { buf[len++] = (blocks >> 24) & 0xff; buf[len++] = (blocks >> 16) & 0xff; buf[len++] = (blocks >> 8) & 0xff; buf[len++] = (blocks >> 0) & 0xff; } } else { buf[len++] = 0; buf[len++] = 0; buf[len++] = 0; buf[len++] = 0; } } buf[0] = ((len-2) >> 8) & 0xff; buf[1] = (len-2) & 0xff; break; default: BX_PANIC(("cdrom: read_toc: unknown format")); return 0; } *length = len; return 1; } // all these implementations below are the platform-dependent code required // to read the TOC from a physical cdrom. #ifdef WIN32 if (isWindowsXP) { // This only works with WinXP CDROM_READ_TOC_EX input; memset(&input, 0, sizeof(input)); input.Format = format; input.Msf = msf; input.SessionTrack = start_track; // We have to allocate a chunk of memory to make sure it is aligned on a sector base. UCHAR *data = (UCHAR *) VirtualAlloc(NULL, 2048*2, MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE); unsigned long iBytesReturned; DeviceIoControl(hFile, IOCTL_CDROM_READ_TOC_EX, &input, sizeof(input), data, 804, &iBytesReturned, NULL); // now copy it to the users buffer and free our buffer *length = data[1] + (data[0] << 8) + 2; memcpy(buf, data, *length); VirtualFree(data, 0, MEM_RELEASE); return 1; } else { return 0; } #elif __linux__ || defined(__sun) { struct cdrom_tochdr tochdr; if (ioctl(fd, CDROMREADTOCHDR, &tochdr)) BX_PANIC(("cdrom: read_toc: READTOCHDR failed.")); if ((start_track > tochdr.cdth_trk1) && (start_track != 0xaa)) return 0; buf[2] = tochdr.cdth_trk0; buf[3] = tochdr.cdth_trk1; if (start_track < tochdr.cdth_trk0) start_track = tochdr.cdth_trk0; int len = 4; for (int i = start_track; i <= tochdr.cdth_trk1; i++) { struct cdrom_tocentry tocentry; tocentry.cdte_format = (msf) ? CDROM_MSF : CDROM_LBA; tocentry.cdte_track = i; if (ioctl(fd, CDROMREADTOCENTRY, &tocentry)) BX_PANIC(("cdrom: read_toc: READTOCENTRY failed.")); buf[len++] = 0; // Reserved buf[len++] = (tocentry.cdte_adr << 4) | tocentry.cdte_ctrl ; // ADR, control buf[len++] = i; // Track number buf[len++] = 0; // Reserved // Start address if (msf) { buf[len++] = 0; // reserved buf[len++] = tocentry.cdte_addr.msf.minute; buf[len++] = tocentry.cdte_addr.msf.second; buf[len++] = tocentry.cdte_addr.msf.frame; } else { buf[len++] = (((unsigned)tocentry.cdte_addr.lba) >> 24) & 0xff; buf[len++] = (((unsigned)tocentry.cdte_addr.lba) >> 16) & 0xff; buf[len++] = (((unsigned)tocentry.cdte_addr.lba) >> 8) & 0xff; buf[len++] = (((unsigned)tocentry.cdte_addr.lba) >> 0) & 0xff; } } // Lead out track struct cdrom_tocentry tocentry; tocentry.cdte_format = (msf) ? CDROM_MSF : CDROM_LBA; #ifdef CDROM_LEADOUT tocentry.cdte_track = CDROM_LEADOUT; #else tocentry.cdte_track = 0xaa; #endif if (ioctl(fd, CDROMREADTOCENTRY, &tocentry)) BX_PANIC(("cdrom: read_toc: READTOCENTRY lead-out failed.")); buf[len++] = 0; // Reserved buf[len++] = (tocentry.cdte_adr << 4) | tocentry.cdte_ctrl ; // ADR, control buf[len++] = 0xaa; // Track number buf[len++] = 0; // Reserved // Start address if (msf) { buf[len++] = 0; // reserved buf[len++] = tocentry.cdte_addr.msf.minute; buf[len++] = tocentry.cdte_addr.msf.second; buf[len++] = tocentry.cdte_addr.msf.frame; } else { buf[len++] = (((unsigned)tocentry.cdte_addr.lba) >> 24) & 0xff; buf[len++] = (((unsigned)tocentry.cdte_addr.lba) >> 16) & 0xff; buf[len++] = (((unsigned)tocentry.cdte_addr.lba) >> 8) & 0xff; buf[len++] = (((unsigned)tocentry.cdte_addr.lba) >> 0) & 0xff; } buf[0] = ((len-2) >> 8) & 0xff; buf[1] = (len-2) & 0xff; *length = len; return 1; } #elif (defined(__NetBSD__) || defined(__NetBSD_kernel__) || defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)) { struct ioc_toc_header h; struct ioc_read_toc_entry t; if (ioctl (fd, CDIOREADTOCHEADER, &h) < 0) BX_PANIC(("cdrom: read_toc: READTOCHDR failed.")); if ((start_track > h.ending_track) && (start_track != 0xaa)) return 0; buf[2] = h.starting_track; buf[3] = h.ending_track; if (start_track < h.starting_track) start_track = h.starting_track; int len = 4; for (int i = start_track; i <= h.ending_track; i++) { struct cd_toc_entry tocentry; t.address_format = (msf) ? CD_MSF_FORMAT : CD_LBA_FORMAT; t.starting_track = i; t.data_len = sizeof(tocentry); t.data = &tocentry; if (ioctl (fd, CDIOREADTOCENTRYS, &t) < 0) BX_PANIC(("cdrom: read_toc: READTOCENTRY failed.")); buf[len++] = 0; // Reserved buf[len++] = (tocentry.addr_type << 4) | tocentry.control ; // ADR, control buf[len++] = i; // Track number buf[len++] = 0; // Reserved // Start address if (msf) { buf[len++] = 0; // reserved buf[len++] = tocentry.addr.msf.minute; buf[len++] = tocentry.addr.msf.second; buf[len++] = tocentry.addr.msf.frame; } else { buf[len++] = (((unsigned)tocentry.addr.lba) >> 24) & 0xff; buf[len++] = (((unsigned)tocentry.addr.lba) >> 16) & 0xff; buf[len++] = (((unsigned)tocentry.addr.lba) >> 8) & 0xff; buf[len++] = (((unsigned)tocentry.addr.lba) >> 0) & 0xff; } } // Lead out track struct cd_toc_entry tocentry; t.address_format = (msf) ? CD_MSF_FORMAT : CD_LBA_FORMAT; t.starting_track = 0xaa; t.data_len = sizeof(tocentry); t.data = &tocentry; if (ioctl (fd, CDIOREADTOCENTRYS, &t) < 0) BX_PANIC(("cdrom: read_toc: READTOCENTRY lead-out failed.")); buf[len++] = 0; // Reserved buf[len++] = (tocentry.addr_type << 4) | tocentry.control ; // ADR, control buf[len++] = 0xaa; // Track number buf[len++] = 0; // Reserved // Start address if (msf) { buf[len++] = 0; // reserved buf[len++] = tocentry.addr.msf.minute; buf[len++] = tocentry.addr.msf.second; buf[len++] = tocentry.addr.msf.frame; } else { buf[len++] = (((unsigned)tocentry.addr.lba) >> 24) & 0xff; buf[len++] = (((unsigned)tocentry.addr.lba) >> 16) & 0xff; buf[len++] = (((unsigned)tocentry.addr.lba) >> 8) & 0xff; buf[len++] = (((unsigned)tocentry.addr.lba) >> 0) & 0xff; } buf[0] = ((len-2) >> 8) & 0xff; buf[1] = (len-2) & 0xff; *length = len; return 1; } #elif defined(__APPLE__) // Read CD TOC. Returns 0 if start track is out of bounds. #if 1 { struct _CDTOC *toc = ReadTOC(CDDevicePath); if ((start_track > toc->last_session) && (start_track != 0xaa)) return 0; buf[2] = toc->first_session; buf[3] = toc->last_session; if (start_track < toc->first_session) start_track = toc->first_session; int len = 4; for (int i = start_track; i <= toc->last_session; i++) { buf[len++] = 0; // Reserved buf[len++] = toc->trackdesc[i].ctrl_adr ; // ADR, control buf[len++] = i; // Track number buf[len++] = 0; // Reserved // Start address if (msf) { buf[len++] = 0; // reserved buf[len++] = toc->trackdesc[i].address.minute; buf[len++] = toc->trackdesc[i].address.second; buf[len++] = toc->trackdesc[i].address.frame; } else { unsigned lba = (unsigned)(MSF_TO_LBA(toc->trackdesc[i].address)); buf[len++] = (lba >> 24) & 0xff; buf[len++] = (lba >> 16) & 0xff; buf[len++] = (lba >> 8) & 0xff; buf[len++] = (lba >> 0) & 0xff; } } // Lead out track buf[len++] = 0; // Reserved buf[len++] = 0x16; // ADR, control buf[len++] = 0xaa; // Track number buf[len++] = 0; // Reserved Bit32u blocks = capacity(); // Start address if (msf) { buf[len++] = 0; // reserved buf[len++] = (Bit8u)(((blocks + 150) / 75) / 60); // minute buf[len++] = (Bit8u)(((blocks + 150) / 75) % 60); // second buf[len++] = (Bit8u)((blocks + 150) % 75); // frame; } else { buf[len++] = (blocks >> 24) & 0xff; buf[len++] = (blocks >> 16) & 0xff; buf[len++] = (blocks >> 8) & 0xff; buf[len++] = (blocks >> 0) & 0xff; } buf[0] = ((len-2) >> 8) & 0xff; buf[1] = (len-2) & 0xff; *length = len; return 1; } #else BX_INFO(("Read TOC - Not Implemented")); return 0; #endif #else BX_INFO(("read_toc: your OS is not supported yet")); return 0; // OS not supported yet, return 0 always. #endif } Bit32u cdrom_interface::capacity() { // Return CD-ROM capacity. I believe you want to return // the number of blocks of capacity the actual media has. #if !defined WIN32 // win32 has its own way of doing this if (using_file) { // return length of the image file struct stat stat_buf; int ret = fstat (fd, &stat_buf); if (ret) { BX_PANIC (("fstat on cdrom image returned err: %s", strerror(errno))); } if ((stat_buf.st_size % 2048) != 0) { BX_ERROR (("expected cdrom image to be a multiple of 2048 bytes")); } return (stat_buf.st_size / 2048); } #endif #ifdef __BEOS__ return GetNumDeviceBlocks(fd, BX_CD_FRAMESIZE); #elif defined(__sun) { struct stat buf = {0}; if (fd < 0) { BX_PANIC(("cdrom: capacity: file not open.")); } if(fstat(fd, &buf) != 0) BX_PANIC(("cdrom: capacity: stat() failed.")); return(buf.st_size); } #elif (defined(__NetBSD__) || defined(__NetBSD_kernel__) || defined(__OpenBSD__)) { // We just read the disklabel, imagine that... struct disklabel lp; if (fd < 0) BX_PANIC(("cdrom: capacity: file not open.")); if (ioctl(fd, DIOCGDINFO, &lp) < 0) BX_PANIC(("cdrom: ioctl(DIOCGDINFO) failed")); BX_DEBUG(("capacity: %u", lp.d_secperunit)); return(lp.d_secperunit); } #elif defined(__linux__) { // Read the TOC to get the data size, since BLKGETSIZE doesn't work on // non-ATAPI drives. This is based on Keith Jones code below. // <[email protected]> 21 June 2001 int i, dtrk_lba, num_sectors; int dtrk = 0; struct cdrom_tochdr td; struct cdrom_tocentry te; if (fd < 0) BX_PANIC(("cdrom: capacity: file not open.")); if (ioctl(fd, CDROMREADTOCHDR, &td) < 0) BX_PANIC(("cdrom: ioctl(CDROMREADTOCHDR) failed")); num_sectors = -1; dtrk_lba = -1; for (i = td.cdth_trk0; i <= td.cdth_trk1; i++) { te.cdte_track = i; te.cdte_format = CDROM_LBA; if (ioctl(fd, CDROMREADTOCENTRY, &te) < 0) BX_PANIC(("cdrom: ioctl(CDROMREADTOCENTRY) failed")); if (dtrk_lba != -1) { num_sectors = te.cdte_addr.lba - dtrk_lba; break; } if (te.cdte_ctrl & CDROM_DATA_TRACK) { dtrk = i; dtrk_lba = te.cdte_addr.lba; } } if (num_sectors < 0) { if (dtrk_lba != -1) { te.cdte_track = CDROM_LEADOUT; te.cdte_format = CDROM_LBA; if (ioctl(fd, CDROMREADTOCENTRY, &te) < 0) BX_PANIC(("cdrom: ioctl(CDROMREADTOCENTRY) failed")); num_sectors = te.cdte_addr.lba - dtrk_lba; } else BX_PANIC(("cdrom: no data track found")); } BX_INFO(("cdrom: Data track %d, length %d", dtrk, num_sectors)); return(num_sectors); } #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) { // Read the TOC to get the size of the data track. // Keith Jones <[email protected]>, 16 January 2000 #define MAX_TRACKS 100 int i, num_tracks, num_sectors; struct ioc_toc_header td; struct ioc_read_toc_entry rte; struct cd_toc_entry toc_buffer[MAX_TRACKS + 1]; if (fd < 0) BX_PANIC(("cdrom: capacity: file not open.")); if (ioctl(fd, CDIOREADTOCHEADER, &td) < 0) BX_PANIC(("cdrom: ioctl(CDIOREADTOCHEADER) failed")); num_tracks = (td.ending_track - td.starting_track) + 1; if (num_tracks > MAX_TRACKS) BX_PANIC(("cdrom: TOC is too large")); rte.address_format = CD_LBA_FORMAT; rte.starting_track = td.starting_track; rte.data_len = (num_tracks + 1) * sizeof(struct cd_toc_entry); rte.data = toc_buffer; if (ioctl(fd, CDIOREADTOCENTRYS, &rte) < 0) BX_PANIC(("cdrom: ioctl(CDIOREADTOCENTRYS) failed")); num_sectors = -1; for (i = 0; i < num_tracks; i++) { if (rte.data[i].control & 4) { /* data track */ num_sectors = ntohl(rte.data[i + 1].addr.lba) - ntohl(rte.data[i].addr.lba); BX_INFO(("cdrom: Data track %d, length %d", rte.data[i].track, num_sectors)); break; } } if (num_sectors < 0) BX_PANIC(("cdrom: no data track found")); return(num_sectors); } #elif defined WIN32 { if (bUseASPI) { return ((GetCDCapacity(hid, tid, lun) / 2352) + 1); } else if (using_file) { ULARGE_INTEGER FileSize; FileSize.LowPart = GetFileSize(hFile, &FileSize.HighPart); return (Bit32u)(FileSize.QuadPart / 2048); } else { /* direct device access */ if (isWindowsXP) { LARGE_INTEGER length; DWORD iBytesReturned; DeviceIoControl(hFile, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &length, sizeof(length), &iBytesReturned, NULL); return (Bit32u)(length.QuadPart / 2048); } else { ULARGE_INTEGER FreeBytesForCaller; ULARGE_INTEGER TotalNumOfBytes; ULARGE_INTEGER TotalFreeBytes; GetDiskFreeSpaceEx(path, &FreeBytesForCaller, &TotalNumOfBytes, &TotalFreeBytes); return (Bit32u)(TotalNumOfBytes.QuadPart / 2048); } } } #elif defined __APPLE__ // Find the size of the first data track on the cd. This has produced // the same results as the linux version on every cd I have tried, about // 5. The differences here seem to be that the entries in the TOC when // retrieved from the IOKit interface appear in a reversed order when // compared with the linux READTOCENTRY ioctl. { // Return CD-ROM capacity. I believe you want to return // the number of bytes of capacity the actual media has. BX_INFO(("Capacity")); struct _CDTOC *toc = ReadTOC(CDDevicePath); if (toc == NULL) { BX_PANIC(("capacity: Failed to read toc")); } size_t toc_entries = (toc->length - 2) / sizeof(struct _CDTOC_Desc); BX_DEBUG(("reading %d toc entries\n", toc_entries)); int start_sector = -1; int data_track = -1; // Iterate through the list backward. Pick the first data track and // get the address of the immediately previous (or following depending // on how you look at it). The difference in the sector numbers // is returned as the sized of the data track. for (int i=toc_entries - 1; i>=0; i--) { BX_DEBUG(("session %d ctl_adr %d tno %d point %d lba %d z %d p lba %d\n", (int)toc->trackdesc[i].session, (int)toc->trackdesc[i].ctrl_adr, (int)toc->trackdesc[i].tno, (int)toc->trackdesc[i].point, MSF_TO_LBA(toc->trackdesc[i].address), (int)toc->trackdesc[i].zero, MSF_TO_LBA(toc->trackdesc[i].p))); if (start_sector != -1) { start_sector = MSF_TO_LBA(toc->trackdesc[i].p) - start_sector; break; } if ((toc->trackdesc[i].ctrl_adr >> 4) != 1) continue; if (toc->trackdesc[i].ctrl_adr & 0x04) { data_track = toc->trackdesc[i].point; start_sector = MSF_TO_LBA(toc->trackdesc[i].p); } } free(toc); if (start_sector == -1) { start_sector = 0; } BX_INFO(("first data track %d data size is %d", data_track, start_sector)); return start_sector; } #else BX_ERROR(("capacity: your OS is not supported yet")); return(0); #endif } bx_bool BX_CPP_AttrRegparmN(3) cdrom_interface::read_block(Bit8u* buf, int lba, int blocksize) { // Read a single block from the CD #ifdef WIN32 LARGE_INTEGER pos; #else off_t pos; #endif ssize_t n = 0; Bit8u try_count = 3; Bit8u* buf1; if (blocksize == 2352) { memset(buf, 0, 2352); memset(buf+1, 0xff, 10); int raw_block = lba + 150; buf[12] = (raw_block / 75) / 60; buf[13] = (raw_block / 75) % 60; buf[14] = (raw_block % 75); buf[15] = 0x01; buf1 = buf + 16; } else { buf1 = buf; } do { #ifdef WIN32 if(bUseASPI) { ReadCDSector(hid, tid, lun, lba, buf1, BX_CD_FRAMESIZE); n = BX_CD_FRAMESIZE; } else { pos.QuadPart = (LONGLONG)lba*BX_CD_FRAMESIZE; pos.LowPart = SetFilePointer(hFile, pos.LowPart, &pos.HighPart, SEEK_SET); if ((pos.LowPart == 0xffffffff) && (GetLastError() != NO_ERROR)) { BX_PANIC(("cdrom: read_block: SetFilePointer returned error.")); } else { ReadFile(hFile, (void *) buf1, BX_CD_FRAMESIZE, (unsigned long *) &n, NULL); } } #elif defined(__APPLE__) #define CD_SEEK_DISTANCE kCDSectorSizeWhole if(using_file) { pos = lseek(fd, lba*BX_CD_FRAMESIZE, SEEK_SET); if (pos < 0) { BX_PANIC(("cdrom: read_block: lseek returned error.")); } else { n = read(fd, buf1, BX_CD_FRAMESIZE); } } else { // This seek will leave us 16 bytes from the start of the data // hence the magic number. pos = lseek(fd, lba*CD_SEEK_DISTANCE + 16, SEEK_SET); if (pos < 0) { BX_PANIC(("cdrom: read_block: lseek returned error.")); } else { n = read(fd, buf1, CD_FRAMESIZE); } } #else pos = lseek(fd, lba*BX_CD_FRAMESIZE, SEEK_SET); if (pos < 0) { BX_PANIC(("cdrom: read_block: lseek returned error.")); } else { n = read(fd, (char*) buf1, BX_CD_FRAMESIZE); } #endif } while ((n != BX_CD_FRAMESIZE) && (--try_count > 0)); return (n == BX_CD_FRAMESIZE); } void cdrom_interface::seek(int lba) { unsigned char buffer[BX_CD_FRAMESIZE]; read_block(buffer, lba, BX_CD_FRAMESIZE); } #endif /* if BX_SUPPORT_CDROM */ #endif
28.745774
136
0.607809
bavison
8818cfcc689f073b42bba15806349f2a6b9723ae
3,594
cpp
C++
main.cpp
rogii-com/SceneSample
df414805899a4ef7e76d62840c2173934bcc6dd6
[ "MIT" ]
3
2019-12-23T12:36:18.000Z
2021-07-24T09:16:13.000Z
main.cpp
rogii-com/SceneSample
df414805899a4ef7e76d62840c2173934bcc6dd6
[ "MIT" ]
null
null
null
main.cpp
rogii-com/SceneSample
df414805899a4ef7e76d62840c2173934bcc6dd6
[ "MIT" ]
4
2019-12-23T11:35:21.000Z
2020-01-09T17:04:46.000Z
#include <QApplication> #include <QQuickView> #include <QQmlEngine> #include "Scene.hpp" #include "LogTrackSceneCameraManipulator.hpp" #include "LineStrip.hpp" class Helper : public QObject { Q_OBJECT public: enum Direction { Horizontal = 0x1, Vertical = 0x2 }; Q_DECLARE_FLAGS(Directions, Direction) public: Helper(rogii::qt_quick::Scene * scene) : QObject(scene) , mScene(scene) , mFlags(Directions().setFlag(Horizontal).setFlag(Vertical)) { } Directions & getFlags() { return mFlags; } public Q_SLOTS: void onShift(double dx, double dy) { rogii::qt_quick::LogTrackSceneCameraManipulator m(mScene->getSceneCamera()); const double trueDx = (mFlags.testFlag(Horizontal) ? dx : 0); const double trueDy = (mFlags.testFlag(Vertical) ? dy : 0); m.shift(trueDx, trueDy); } void onZoom(double step, QPointF pivot) { rogii::qt_quick::LogTrackSceneCameraManipulator m(mScene->getSceneCamera()); const double trueX = (mFlags.testFlag(Horizontal) ? pivot.x() : 0); const double trueY = (mFlags.testFlag(Vertical) ? pivot.y() : 0); m.zoom(step, QPoint(trueX, trueY)); } private: rogii::qt_quick::Scene * mScene; Directions mFlags; }; int main(int argc, char * argv[]) { QApplication::setAttribute(Qt::AA_UseOpenGLES); QApplication::setAttribute(Qt::AA_DisableHighDpiScaling); QApplication app(argc, argv); qmlRegisterType<rogii::qt_quick::Scene>("ROGII.QtQuick", 1, 0, "Scene"); qmlRegisterType<LineStrip>("ROGII.QtQuick", 1, 0, "LineStrip"); QQuickView view; view.engine()->addImportPath(QCoreApplication::applicationDirPath() + QStringLiteral("/qml")); view.resize(800, 400); view.setResizeMode(QQuickView::SizeRootObjectToView); view.setSource(QUrl("qrc:///SceneSample/main.qml")); view.show(); { auto * scene1 = view.rootObject()->findChild<rogii::qt_quick::Scene *>(QLatin1String("scene1")); auto * shiftArea = scene1->findChild<QQuickItem *>(QLatin1String("sceneMouseArea")); auto * h = new Helper(scene1); QObject::connect(shiftArea, SIGNAL(shift(double, double)), h, SLOT(onShift(double, double))); QObject::connect(shiftArea, SIGNAL(zoom(double, QPointF)), h, SLOT(onZoom(double, QPointF))); h->getFlags().setFlag(Helper::Horizontal, false); } { auto * scene = view.rootObject()->findChild<rogii::qt_quick::Scene *>(QLatin1String("scene2")); auto * shiftArea = scene->findChild<QQuickItem *>(QLatin1String("sceneMouseArea")); auto * h = new Helper(scene); QObject::connect(shiftArea, SIGNAL(shift(double, double)), h, SLOT(onShift(double, double))); QObject::connect(shiftArea, SIGNAL(zoom(double, QPointF)), h, SLOT(onZoom(double, QPointF))); h->getFlags().setFlag(Helper::Vertical, false); } { auto * scene = view.rootObject()->findChild<rogii::qt_quick::Scene *>(QLatin1String("scene3")); auto * shiftArea = scene->findChild<QQuickItem *>(QLatin1String("sceneMouseArea")); auto * h = new Helper(scene); QObject::connect(shiftArea, SIGNAL(shift(double, double)), h, SLOT(onShift(double, double))); QObject::connect(shiftArea, SIGNAL(zoom(double, QPointF)), h, SLOT(onZoom(double, QPointF))); } return app.exec(); } #include "main.moc"
31.526316
104
0.625765
rogii-com
881afe4df63cbad01e892ec69a5829f625bbdc71
5,329
cpp
C++
components/eam/src/physics/crm/samxx/shear_prod2D.cpp
katsmith133/E3SM
996c7e7aa3150822b81b0e34c427b820c74268a2
[ "BSD-3-Clause" ]
null
null
null
components/eam/src/physics/crm/samxx/shear_prod2D.cpp
katsmith133/E3SM
996c7e7aa3150822b81b0e34c427b820c74268a2
[ "BSD-3-Clause" ]
null
null
null
components/eam/src/physics/crm/samxx/shear_prod2D.cpp
katsmith133/E3SM
996c7e7aa3150822b81b0e34c427b820c74268a2
[ "BSD-3-Clause" ]
null
null
null
#include "shear_prod2D.h" void shear_prod2D(real4d &def2) { YAKL_SCOPE( dx , :: dx ); YAKL_SCOPE( dz , :: dz ); YAKL_SCOPE( adz , :: adz ); YAKL_SCOPE( adzw , :: adzw ); YAKL_SCOPE( u , :: u ); YAKL_SCOPE( v , :: v ); YAKL_SCOPE( w , :: w ); YAKL_SCOPE( u0 , :: u0 ); YAKL_SCOPE( v0 , :: v0 ); YAKL_SCOPE( ncrms , :: ncrms ); // for (int k=0; k<nzm; k++) { // for (int i=0; i<nx; i++) { // for (int icrm=0; icrm<ncrms; icrm++) { parallel_for( SimpleBounds<3>(nzm,nx,ncrms) , YAKL_LAMBDA (int k, int i, int icrm) { real rdx0 = 1.0/dx; int j = 0; int kb, kc, ib, ic; real rdz, rdzw_up, rdzw_dn, rdx, rdx_up, rdx_dn; if (k>=1 && k <= nzm-2) { kb = k-1; kc = k+1; rdz = 1.0/(dz(icrm)*adz(k,icrm)); rdzw_up = 1.0/(dz(icrm)*adzw(kc,icrm)); rdzw_dn = 1.0/(dz(icrm)*adzw(k,icrm)); rdx = rdx0*sqrt(dx*rdz); rdx_up = rdx0 *sqrt(dx*rdzw_up); rdx_dn = rdx0 *sqrt(dx*rdzw_dn); ib = i-1; ic = i+1; real tmp1 = ((u(k,j+offy_u,ic+offx_u,icrm)-u(k,j+offy_u,i+offx_u,icrm))*rdx); real tmp2 = ((w(kc,j+offy_w,i+offx_w,icrm)-w(k,j+offy_w,i+offx_w,icrm))*rdz); real tmp3 = (v(k,j+offy_v,ic+offx_v,icrm)-v(k,j+offy_v,i+offx_v,icrm))*rdx; real tmp4 = (v(k,j+offy_v,i+offx_v,icrm)-v(k,j+offy_v,ib+offx_v,icrm))*rdx; real tmp5 = ( (u(kc,j+offy_u,ic+offx_u,icrm)-u0(kc,icrm)-u(k,j+offy_u,ic+offx_u,icrm)+u0(k,icrm))*rdzw_up + (w(kc,j+offy_w,ic+offx_w,icrm)-w(kc,j+offy_w,i+offx_w,icrm))*rdx_up); real tmp6 = ( (u(kc,j+offy_u,i+offx_u,icrm)-u0(kc,icrm)-u(k,j+offy_u,i+offx_u,icrm)+u0(k,icrm))*rdzw_up + (w(kc,j+offy_w,i+offx_w,icrm)-w(kc,j+offy_w,ib+offx_w,icrm))*rdx_up); real tmp7 = ( (u(k,j+offy_u,ic+offx_u,icrm)-u0(k,icrm)-u(kb,j+offy_u,ic+offx_u,icrm)+u0(kb,icrm))*rdzw_dn + (w(k,j+offy_w,ic+offx_w,icrm)-w(k,j+offy_w,i+offx_w,icrm))*rdx_dn); real tmp8 = ( (u(k,j+offy_u,i+offx_u,icrm)-u0(k,icrm)-u(kb,j+offy_u,i+offx_u,icrm)+u0(kb,icrm))*rdzw_dn + (w(k,j+offy_w,i+offx_w,icrm)-w(k,j+offy_w,ib+offx_w,icrm))*rdx_dn); real tmp9 = ( (v(kc,j+offy_v,i+offx_v,icrm)-v0(kc,icrm)-v(k,j+offy_v,i+offx_v,icrm)+v0(k,icrm))*rdzw_up); real tmp10 = ( (v(k,j+offy_v,i+offx_v,icrm)-v0(k,icrm)-v(kb,j+offy_v,i+offx_v,icrm)+v0(kb,icrm))*rdzw_dn); def2(k,j,i,icrm) = 2.0 * ( tmp1*tmp1 + tmp2*tmp2 ) + 0.5 * ( tmp3*tmp3 + tmp4*tmp4 + tmp5*tmp5 + tmp6 *tmp6 + tmp7*tmp7 + tmp8*tmp8 + tmp9*tmp9 + tmp10*tmp10 ); } else if (k==0) { kc = k+1; rdz = 1.0/(dz(icrm)*adz(k,icrm)); rdzw_up = 1.0/(dz(icrm)*adzw(kc,icrm)); rdx = rdx0*sqrt(dx*rdz); rdx_up = rdx0 *sqrt(dx*rdzw_up); ib = i-1; ic = i+1; real tmp1 = ((u(k,j+offy_u,ic+offx_u,icrm)-u(k,j+offy_u,i+offx_u,icrm))*rdx); real tmp2 = ((w(kc,j+offy_w,i+offx_w,icrm)-w(k,j+offy_w,i+offx_w,icrm))*rdz); real tmp3 = ( (v(k,j+offy_v,ic+offx_v,icrm)-v(k,j+offy_v,i+offx_v,icrm))*rdx); real tmp4 = ( (v(k,j+offy_v,i+offx_v,icrm)-v(k,j+offy_v,ib+offx_v,icrm))*rdx); real tmp5 = ( (v(kc,j+offy_v,i+offx_v,icrm)-v0(kc,icrm)-v(k,j+offy_v,i+offx_v,icrm)+v0(k,icrm))*rdzw_up); real tmp6 = ( (u(kc,j+offy_u,ic+offx_u,icrm)-u0(kc,icrm)-u(k,j+offy_u,ic+offx_u,icrm)+u0(k,icrm))*rdzw_up + (w(kc,j+offy_w,ic+offx_w,icrm)-w(kc,j+offy_w,i+offx_w,icrm))*rdx_up); real tmp7 = ( (u(kc,j+offy_u,i+offx_u,icrm)-u0(kc,icrm)-u(k,j+offy_u,i+offx_u,icrm)+u0(k,icrm))*rdzw_up + (w(kc,j+offy_w,i+offx_w,icrm)-w(kc,j+offy_w,ib+offx_w,icrm))*rdx_up); def2(k,j,i,icrm) = 2.0* ( tmp1*tmp1 + tmp2*tmp2 ) + 0.5 * ( tmp3*tmp3 + tmp4*tmp4 ) + tmp5*tmp5 + 0.5 * ( tmp6*tmp6 + tmp7*tmp7 ); } else if (k==nzm-1) { kc = k+1; kb = k-1; rdz = 1.0/(dz(icrm)*adz(k,icrm)); rdzw_dn = 1.0/(dz(icrm)*adzw(k,icrm)); rdx = rdx0*sqrt(dx*rdz); rdx_dn = rdx0 *sqrt(dx*rdzw_dn); ib = i-1; ic = i+1; real tmp1 = ( (u(k,j+offy_u,ic+offx_u,icrm)-u(k,j+offy_u,i+offx_u,icrm))*rdx); real tmp2 = ( (w(kc,j+offy_w,i+offx_w,icrm)-w(k,j+offy_w,i+offx_w,icrm))*rdz); real tmp3 = ( (v(k,j+offy_v,ic+offx_v,icrm)-v(k,j+offy_v,i+offx_v,icrm))*rdx); real tmp4 = ( (v(k,j+offy_v,i+offx_v,icrm)-v(k,j+offy_v,ib+offx_v,icrm))*rdx); real tmp5 = ( (v(k,j+offy_v,i+offx_v,icrm)-v0(k,icrm)-v(kb,j+offy_v,i+offx_v,icrm)+v0(kb,icrm))*rdzw_dn); real tmp6 = ( (u(k,j+offy_u,ic+offx_u,icrm)-u0(k,icrm)-u(kb,j+offy_u,ic+offx_u,icrm)+u0(kb,icrm))*rdzw_dn); real tmp7 = ( (w(k,j+offy_w,ic+offx_w,icrm)-w(k,j+offy_w,i+offx_w,icrm))*rdx_dn); real tmp8 = ( (u(k,j+offy_u,i+offx_u,icrm)-u0(k,icrm)-u(kb,j+offy_u,i+offx_u,icrm)+u0(kb,icrm))*rdzw_dn+ (w(k,j+offy_w,i+offx_w,icrm)-w(k,j+offy_w,ib+offx_w,icrm))*rdx_dn); def2(k,j,i,icrm) = 2.0 * ( tmp1*tmp1 + tmp2*tmp2 ) + 0.5 * ( tmp3*tmp3 + tmp4*tmp4 ) + tmp5*tmp5 + 0.5 * ( tmp6*tmp6 + tmp7*tmp7 + tmp8*tmp8 ); } }); }
52.245098
117
0.536874
katsmith133
881bcd5f5848285edc638fdb9594440aa969d9cd
2,317
cpp
C++
NeuKaDiS/KaDiS/external/RBC/external/tlx/tlx/string/compare_icase.cpp
bingmann/distributed-string-sorting
238bdfd5f6139f2f14e33aed7b4d9bbffac5d295
[ "BSD-2-Clause" ]
284
2017-02-26T08:49:15.000Z
2022-03-30T21:55:37.000Z
NeuKaDiS/KaDiS/external/RBC/external/tlx/tlx/string/compare_icase.cpp
bingmann/distributed-string-sorting
238bdfd5f6139f2f14e33aed7b4d9bbffac5d295
[ "BSD-2-Clause" ]
24
2017-09-05T21:02:41.000Z
2022-03-07T10:09:59.000Z
NeuKaDiS/KaDiS/external/RBC/external/tlx/tlx/string/compare_icase.cpp
bingmann/distributed-string-sorting
238bdfd5f6139f2f14e33aed7b4d9bbffac5d295
[ "BSD-2-Clause" ]
62
2017-02-23T12:29:27.000Z
2022-03-31T07:45:59.000Z
/******************************************************************************* * tlx/string/compare_icase.cpp * * Part of tlx - http://panthema.net/tlx * * Copyright (C) 2007-2017 Timo Bingmann <[email protected]> * * All rights reserved. Published under the Boost Software License, Version 1.0 ******************************************************************************/ #include <tlx/string/compare_icase.hpp> #include <tlx/string/to_lower.hpp> #include <algorithm> namespace tlx { int compare_icase(const char* a, const char* b) { while (*a != 0 && *b != 0) { int ca = to_lower(*a++); int cb = to_lower(*b++); if (ca == cb) continue; if (ca < cb) return -1; else return +1; } if (*a == 0 && *b != 0) return +1; else if (*a != 0 && *b == 0) return -1; else return 0; } int compare_icase(const char* a, const std::string& b) { std::string::const_iterator bi = b.begin(); while (*a != 0 && bi != b.end()) { int ca = to_lower(*a++); int cb = to_lower(*bi++); if (ca == cb) continue; if (ca < cb) return -1; else return +1; } if (*a == 0 && bi != b.end()) return +1; else if (*a != 0 && bi == b.end()) return -1; else return 0; } int compare_icase(const std::string& a, const char* b) { std::string::const_iterator ai = a.begin(); while (ai != a.end() && *b != 0) { int ca = to_lower(*ai++); int cb = to_lower(*b++); if (ca == cb) continue; if (ca < cb) return -1; else return +1; } if (ai == a.end() && *b != 0) return +1; else if (ai != a.end() && *b == 0) return -1; else return 0; } int compare_icase(const std::string& a, const std::string& b) { std::string::const_iterator ai = a.begin(); std::string::const_iterator bi = b.begin(); while (ai != a.end() && bi != b.end()) { int ca = to_lower(*ai++); int cb = to_lower(*bi++); if (ca == cb) continue; if (ca < cb) return -1; else return +1; } if (ai == a.end() && bi != b.end()) return +1; else if (ai != a.end() && bi == b.end()) return -1; else return 0; } } // namespace tlx /******************************************************************************/
24.648936
80
0.45792
bingmann
881c429235adc29f370d5f644492664e29004cc0
697
cpp
C++
Test/FastFourierTransform.test.cpp
tkmst201/library
3abe841f5dde6078e8f26c9fd5d1a0716d4edc7d
[ "CC0-1.0" ]
null
null
null
Test/FastFourierTransform.test.cpp
tkmst201/library
3abe841f5dde6078e8f26c9fd5d1a0716d4edc7d
[ "CC0-1.0" ]
null
null
null
Test/FastFourierTransform.test.cpp
tkmst201/library
3abe841f5dde6078e8f26c9fd5d1a0716d4edc7d
[ "CC0-1.0" ]
null
null
null
#define PROBLEM "https://judge.yosupo.jp/problem/frequency_table_of_tree_distance" #include "GraphTheory/CentroidDecomposition.hpp" #include "Convolution/FastFourierTransform.hpp" #include "Algorithm/frequency_table_of_tree_distance.hpp" #include <cstdio> #include <vector> int main() { int N; scanf("%d", &N); CentroidDecomposition::Graph g(N); for (int i = 0; i < N - 1; ++i) { int a, b; scanf("%d %d", &a, &b); g[a].emplace_back(b); g[b].emplace_back(a); } auto table = tk::frequency_table_of_tree_distance<CentroidDecomposition, FastFourierTransform>(g); for (int i = 1; i < N; ++i) printf("%lld%c", i < table.size() ? table[i] : 0, " \n"[i + 1 == N]); }
31.681818
100
0.658537
tkmst201
8820d7c40c0d4b7395950dbe80bb81a78815f8f5
1,225
cpp
C++
src/executors/loadmatrix.cpp
bhavyajeet/Project-PreQL
9a8fffe450a37b324f09b53fbc1bc762aa7cc556
[ "MIT" ]
null
null
null
src/executors/loadmatrix.cpp
bhavyajeet/Project-PreQL
9a8fffe450a37b324f09b53fbc1bc762aa7cc556
[ "MIT" ]
null
null
null
src/executors/loadmatrix.cpp
bhavyajeet/Project-PreQL
9a8fffe450a37b324f09b53fbc1bc762aa7cc556
[ "MIT" ]
null
null
null
#include "global.h" /** * @brief * SYNTAX: LOAD relation_name */ bool syntacticParseLOADMATRIX() { logger.log("syntacticParseLOADMATRIX"); if (tokenizedQuery.size() != 3) { cout << "SYNTAX ERROR PLEASE SPECIFY MATRIX NAME" << endl; return false; } parsedQuery.queryType = LOADMATRIX; parsedQuery.loadMatrixRelationName = tokenizedQuery[2]; return true; } bool semanticParseLOADMATRIX() { logger.log("semanticParseLOADMATRIX"); if (matrixCatalogue.isMatrix(parsedQuery.loadMatrixRelationName)) { cout << "SEMANTIC ERROR: Relation already exists" << endl; return false; } if (!isFileExists(parsedQuery.loadMatrixRelationName)) { cout << "SEMANTIC ERROR: Data file doesn't exist" << endl; return false; } return true; } void executeLOADMATRIX() { Matrix *matrix = new Matrix(parsedQuery.loadMatrixRelationName); if (matrix->load()) { matrixCatalogue.insertMatrix(matrix); cout << "Loaded Matrix. Column Count: " << matrix->columnCount << " Row Count: " << matrix->rowCount << endl; } logger.log("executeLOADMATRIX"); return; }
26.06383
118
0.62449
bhavyajeet
88220f53e046ce6c80b1138b272aac1adbc5884b
1,502
cpp
C++
regression/advection_pdbott_prepare_tracers.cpp
aurianer/gridtools
5f99471bf36215e2a53317d2c7844bf057231ffa
[ "BSD-3-Clause" ]
null
null
null
regression/advection_pdbott_prepare_tracers.cpp
aurianer/gridtools
5f99471bf36215e2a53317d2c7844bf057231ffa
[ "BSD-3-Clause" ]
null
null
null
regression/advection_pdbott_prepare_tracers.cpp
aurianer/gridtools
5f99471bf36215e2a53317d2c7844bf057231ffa
[ "BSD-3-Clause" ]
null
null
null
/* * GridTools * * Copyright (c) 2014-2019, ETH Zurich * All rights reserved. * * Please, refer to the LICENSE file in the root directory. * SPDX-License-Identifier: BSD-3-Clause */ #include <vector> #include <gtest/gtest.h> #include <gridtools/stencil_composition/cartesian.hpp> #include <gridtools/tools/cartesian_regression_fixture.hpp> using namespace gridtools; using namespace cartesian; struct prepare_tracers { using data = inout_accessor<0>; using data_nnow = in_accessor<1>; using rho = in_accessor<2>; using param_list = make_param_list<data, data_nnow, rho>; template <typename Evaluation> GT_FUNCTION static void apply(Evaluation eval) { eval(data()) = eval(rho()) * eval(data_nnow()); } }; using advection_pdbott_prepare_tracers = regression_fixture<>; TEST_F(advection_pdbott_prepare_tracers, test) { std::vector<storage_type> in, out; for (size_t i = 0; i < 11; ++i) { out.push_back(make_storage()); in.push_back(make_storage(i)); } auto comp = [grid = make_grid(), &in, &out, rho = make_const_storage(1.1)] { expandable_run<2>( [](auto out, auto in, auto rho) { return execute_parallel().stage(prepare_tracers(), out, in, rho); }, backend_t(), grid, out, in, rho); }; comp(); for (size_t i = 0; i != out.size(); ++i) verify([i](int, int, int) { return 1.1 * i; }, out[i]); benchmark(comp); }
25.033333
114
0.62783
aurianer
88225addc320c91a69c06e582c018e8bc49de7b2
226
hpp
C++
libraries/singularity/singularity/include/graphene/poi/singularity.hpp
petrkotegov/gravity-core
52c9a96126739c33ee0681946e1d88c5be9a6190
[ "MIT" ]
8
2018-05-25T17:58:46.000Z
2018-06-23T21:13:26.000Z
libraries/singularity/singularity/include/graphene/poi/singularity.hpp
petrkotegov/gravity-core
52c9a96126739c33ee0681946e1d88c5be9a6190
[ "MIT" ]
14
2018-05-25T19:44:30.000Z
2018-08-03T11:35:27.000Z
libraries/singularity/singularity/include/graphene/poi/singularity.hpp
petrkotegov/gravity-core
52c9a96126739c33ee0681946e1d88c5be9a6190
[ "MIT" ]
6
2018-05-30T04:37:46.000Z
2019-03-05T14:47:34.000Z
#ifndef SINGULARITY_HPP #define SINGULARITY_HPP #include <graphene/singularity/emission.hpp> #include <graphene/singularity/gravity_index_calculator.hpp> #include <graphene/singularity/activity_index_calculator.hpp> #endif
22.6
61
0.845133
petrkotegov
882407e038138ed1b82282d20ca8912d00060b27
17,985
cc
C++
plugin_injector/plugin_injector.cc
teamsimplepay/sorbet
8c2053b1b1e2e6d1f721e7b52335fbba478ef114
[ "Apache-2.0" ]
null
null
null
plugin_injector/plugin_injector.cc
teamsimplepay/sorbet
8c2053b1b1e2e6d1f721e7b52335fbba478ef114
[ "Apache-2.0" ]
null
null
null
plugin_injector/plugin_injector.cc
teamsimplepay/sorbet
8c2053b1b1e2e6d1f721e7b52335fbba478ef114
[ "Apache-2.0" ]
1
2021-12-02T07:50:49.000Z
2021-12-02T07:50:49.000Z
// These violate our poisons so have to happen first #include "llvm/IR/DIBuilder.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/Support/Host.h" #include "llvm/Transforms/Utils/Cloning.h" #include "absl/cleanup/cleanup.h" #include "absl/strings/str_split.h" #include "absl/synchronization/mutex.h" #include "ast/ast.h" #include "cfg/CFG.h" #include "common/FileOps.h" #include "common/typecase.h" #include "compiler/Core/AbortCompilation.h" #include "compiler/Core/CompilerState.h" #include "compiler/Core/FailCompilation.h" #include "compiler/Core/OptimizerException.h" #include "compiler/Errors/Errors.h" #include "compiler/IREmitter/IREmitter.h" #include "compiler/IREmitter/IREmitterHelpers.h" #include "compiler/IREmitter/Payload/PayloadLoader.h" #include "compiler/ObjectFileEmitter/ObjectFileEmitter.h" #include "core/ErrorQueue.h" #include "main/options/options.h" #include "main/pipeline/semantic_extension/SemanticExtension.h" #include <cxxopts.hpp> #include <optional> using namespace std; namespace sorbet::pipeline::semantic_extension { namespace { string objectFileName(const core::GlobalState &gs, const core::FileRef &f) { string sourceFile(f.data(gs).path()); if (sourceFile[0] == '.' && sourceFile[1] == '/') { sourceFile = sourceFile.substr(2); } return sourceFile; } void ensureOutputDir(const string_view outputDir, string_view fileName) { string path(outputDir); auto finalSlashPos = fileName.rfind('/'); if (finalSlashPos == string_view::npos) { return; } // Trim the filename so that we only iterate directory parts below fileName.remove_suffix(fileName.size() - finalSlashPos); for (auto part : absl::StrSplit(fileName, '/')) { absl::StrAppend(&path, "/", part); FileOps::ensureDir(path); } } } // namespace // Sorbet's pipeline is architected such that one thread is typechecking one file at a time. // This struct allows us to store state local to one typechecking thread. class TypecheckThreadState { public: // Creating an LLVMContext is somewhat expensive, so we don't want to create more than one per thread. llvm::LLVMContext lctx; // The file this thread is currently typechecking core::FileRef file; // The output of IREmitter for a file. // // "Combined" because all the methods in this file get compiled and accumulated into this Module, // but each method is typechecked (and thus compiled) individually. unique_ptr<llvm::Module> combinedModule; unique_ptr<llvm::DIBuilder> debugInfo; llvm::DICompileUnit *compileUnit = nullptr; // The basic-block that holds the initialization of string constants. llvm::BasicBlock *allocRubyIdsEntry = nullptr; compiler::StringTable stringTable; compiler::IDTable idTable; // The function that holds calls to global constructors // // This works as a replacement to llvm.global_ctors so that we can delay initialization until after // our sorbet_ruby version check. llvm::BasicBlock *globalConstructorsEntry = nullptr; bool aborted = false; const unique_ptr<const llvm::Module> codegenPayload; TypecheckThreadState() : codegenPayload(compiler::PayloadLoader::readDefaultModule(lctx)) {} }; class LLVMSemanticExtension : public SemanticExtension { optional<string> compiledOutputDir; optional<string> irOutputDir; bool forceCompiled; mutable struct { UnorderedMap<std::thread::id, shared_ptr<TypecheckThreadState>> states; absl::Mutex mtx; } mutableState; shared_ptr<TypecheckThreadState> getTypecheckThreadState() const { { absl::ReaderMutexLock lock(&mutableState.mtx); if (mutableState.states.contains(std::this_thread::get_id())) { return mutableState.states.at(std::this_thread::get_id()); } } { absl::WriterMutexLock lock(&mutableState.mtx); return mutableState.states[std::this_thread::get_id()] = make_shared<TypecheckThreadState>(); } } bool shouldCompile(const core::GlobalState &gs, const core::FileRef &f) const { if (!compiledOutputDir.has_value()) { return false; } if (forceCompiled) { return true; } // TODO parse this the same way as `typed:` return isCompiledTrue(gs, f); } bool isCompiledTrue(const core::GlobalState &gs, const core::FileRef &f) const { return f.data(gs).compiledLevel == core::CompiledLevel::True; } // There are a certain class of method calls that sorbet generates for auxiliary // information for IDEs that do not have meaning at runtime. These calls are all // of the form `foo(bar(baz))`, i.e. straight line code with no variables. // We take advantage of this special knowledge to do a simple form of dead code // elimination. void deleteDoNothingSends(cfg::CFG &cfg) const { for (auto &block : cfg.basicBlocks) { UnorderedSet<cfg::LocalRef> refsToDelete; for (auto i = block->exprs.rbegin(), e = block->exprs.rend(); i != e; ++i) { auto &binding = *i; if (auto *send = cfg::cast_instruction<cfg::Send>(binding.value)) { switch (send->fun.rawId()) { case core::Names::keepForIde().rawId(): case core::Names::keepForTypechecking().rawId(): // TODO: figure out why we can't delete this. // case core::Names::keepForCfg().rawId(): refsToDelete.emplace(binding.bind.variable); break; default: if (!refsToDelete.contains(binding.bind.variable)) { continue; } break; } // We're binding a ref that is unneeded, so anything that this // instruction requires must be unneeded as well. for (auto &arg : send->args) { refsToDelete.emplace(arg.variable); } refsToDelete.emplace(send->recv.variable); } } auto e = std::remove_if(block->exprs.begin(), block->exprs.end(), [&](auto &binding) { return refsToDelete.contains(binding.bind.variable); }); block->exprs.erase(e, block->exprs.end()); } } public: LLVMSemanticExtension(optional<string> compiledOutputDir, optional<string> irOutputDir, bool forceCompiled) { this->compiledOutputDir = move(compiledOutputDir); this->irOutputDir = move(irOutputDir); this->forceCompiled = forceCompiled; } virtual void run(core::MutableContext &ctx, ast::ClassDef *klass) const override{}; virtual void typecheck(const core::GlobalState &gs, cfg::CFG &cfg, ast::MethodDef &md) const override { if (!shouldCompile(gs, cfg.file)) { return; } // This method will be handled as a VM_METHOD_TYPE_IVAR method by the // standard VM mechanisms, so we don't need to generate code for it. if (md.flags.isAttrReader && !md.symbol.data(gs)->flags.isFinal) { return; } if (md.symbol.data(gs)->name == core::Names::staticInit()) { auto attachedClass = md.symbol.data(gs)->owner.data(gs)->attachedClass(gs); if (attachedClass.exists() && attachedClass.data(gs)->name.isTEnumName(gs)) { return; } } auto threadState = getTypecheckThreadState(); if (threadState->aborted) { return; } deleteDoNothingSends(cfg); llvm::LLVMContext &lctx = threadState->lctx; unique_ptr<llvm::Module> &module = threadState->combinedModule; unique_ptr<llvm::DIBuilder> &debug = threadState->debugInfo; llvm::DICompileUnit *&compUnit = threadState->compileUnit; // TODO: Figure out why this isn't true // ENFORCE(absl::c_find(cfg.symbol.data(gs)->locs(), md->loc) != cfg.symbol.data(gs)->locs().end(), // loc.toString(gs)); ENFORCE(cfg.file.exists()); if (!module) { ENFORCE(threadState->globalConstructorsEntry == nullptr); ENFORCE(debug == nullptr); ENFORCE(compUnit == nullptr); module = llvm::CloneModule(*threadState->codegenPayload); module->addModuleFlag(llvm::Module::Warning, "Debug Info Version", llvm::DEBUG_METADATA_VERSION); module->addModuleFlag(llvm::Module::Override, "cf-protection-return", 1); module->addModuleFlag(llvm::Module::Override, "cf-protection-branch", 1); if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) { // osx only supports dwarf2 module->addModuleFlag(llvm::Module::Warning, "Dwarf Version", 2); } debug = std::make_unique<llvm::DIBuilder>(*module); // NOTE: we use C here because our generated functions follow its abi auto language = llvm::dwarf::DW_LANG_C; auto filename = cfg.file.data(gs).path(); auto isOptimized = false; auto runtimeVersion = 0; compUnit = debug->createCompileUnit( language, debug->createFile(llvm::StringRef(filename.data(), filename.size()), "."), "Sorbet LLVM", isOptimized, "", runtimeVersion); threadState->file = cfg.file; threadState->stringTable.clear(); threadState->idTable.clear(); { auto linkageType = llvm::Function::InternalLinkage; auto argTys = std::vector<llvm::Type *>{llvm::Type::getInt64Ty(lctx)}; auto varArgs = false; auto ft = llvm::FunctionType::get(llvm::Type::getVoidTy(lctx), argTys, varArgs); auto globalConstructors = llvm::Function::Create(ft, linkageType, "sorbet_globalConstructors", *module); threadState->allocRubyIdsEntry = llvm::BasicBlock::Create(lctx, "allocRubyIds", globalConstructors); threadState->globalConstructorsEntry = llvm::BasicBlock::Create(lctx, "globalConstructors", globalConstructors); } } else { ENFORCE(threadState->file == cfg.file); ENFORCE(threadState->globalConstructorsEntry != nullptr); } ENFORCE(threadState->file.exists()); compiler::CompilerState state(gs, lctx, module.get(), debug.get(), compUnit, threadState->file, threadState->allocRubyIdsEntry, threadState->globalConstructorsEntry, threadState->stringTable, threadState->idTable); absl::Cleanup dropInternalState = [&] { threadState->aborted = true; module = nullptr; threadState->file = core::FileRef(); }; try { compiler::IREmitter::run(state, cfg, md); string fileName = objectFileName(gs, cfg.file); compiler::IREmitter::buildInitFor(state, cfg.symbol, fileName); std::move(dropInternalState).Cancel(); } catch (sorbet::compiler::AbortCompilation &) { threadState->aborted = true; std::move(dropInternalState).Cancel(); } catch (sorbet::compiler::OptimizerException &oe) { threadState->aborted = true; std::move(dropInternalState).Cancel(); // This exception is thrown from within an optimizer pass, where GlobalState // is not available, so we need to emit an error here, where we do have // access to GlobalState. if (auto e = gs.beginError(core::Loc(cfg.file, 0, 0), core::errors::Compiler::OptimizerFailure)) { e.setHeader("{}", oe.what()); } } }; virtual void finishTypecheckFile(const core::GlobalState &gs, const core::FileRef &f) const override { if (!shouldCompile(gs, f)) { return; } if (f.data(gs).minErrorLevel() >= core::StrictLevel::True) { if (f.data(gs).source().find("frozen_string_literal: true"sv) == string_view::npos) { compiler::failCompilation(gs, core::Loc(f, 0, 0), "Compiled files need to have '# frozen_string_literal: true'"); } } else { compiler::failCompilation(gs, core::Loc(f, 0, 0), "Compiled files must be at least '# typed: true' or above"); } auto threadState = getTypecheckThreadState(); llvm::LLVMContext &lctx = threadState->lctx; unique_ptr<llvm::Module> module = move(threadState->combinedModule); unique_ptr<llvm::DIBuilder> debug = move(threadState->debugInfo); threadState->compileUnit = nullptr; // It is possible, though unusual, to never have typecheck() called. if (!module) { ENFORCE(!threadState->file.exists()); return; } if (threadState->aborted) { threadState->file = core::FileRef(); return; } { llvm::IRBuilder<> builder(lctx); threadState->stringTable.defineGlobalVariables(lctx, *module); builder.SetInsertPoint(threadState->allocRubyIdsEntry); threadState->idTable.defineGlobalVariables(lctx, *module, builder); builder.CreateBr(threadState->globalConstructorsEntry); builder.SetInsertPoint(threadState->globalConstructorsEntry); builder.CreateRetVoid(); } threadState->globalConstructorsEntry = nullptr; ENFORCE(threadState->file.exists()); ENFORCE(f == threadState->file); ENFORCE(threadState->combinedModule == nullptr); ENFORCE(threadState->globalConstructorsEntry == nullptr); threadState->file = core::FileRef(); debug->finalize(); string fileName = objectFileName(gs, f); ensureOutputDir(compiledOutputDir.value(), fileName); if (irOutputDir.has_value()) { ensureOutputDir(irOutputDir.value(), fileName); } if (!compiler::ObjectFileEmitter::run(gs.tracer(), lctx, move(module), compiledOutputDir.value(), irOutputDir, fileName)) { compiler::failCompilation(gs, core::Loc(f, 0, 0), "Object file emitter failed"); } }; virtual void finishTypecheck(const core::GlobalState &gs) const override {} virtual ~LLVMSemanticExtension(){}; virtual std::unique_ptr<SemanticExtension> deepCopy(const core::GlobalState &from, core::GlobalState &to) override { return make_unique<LLVMSemanticExtension>(this->compiledOutputDir, this->irOutputDir, this->forceCompiled); }; virtual void merge(const core::GlobalState &from, core::GlobalState &to, core::NameSubstitution &subst) override {} }; class LLVMSemanticExtensionProvider : public SemanticExtensionProvider { public: virtual void injectOptions(cxxopts::Options &optsBuilder) const override { optsBuilder.add_options("compiler")( "compiled-out-dir", "Output compiled code (*.rb.so or *.rb.bundle) to directory, which must already exist", cxxopts::value<string>()); optsBuilder.add_options("compiler")("llvm-ir-dir", "Output LLVM IR to directory, which must already exist", cxxopts::value<string>()); optsBuilder.add_options("compiler")("force-compiled", "Force all files to this compiled level", cxxopts::value<bool>()); }; virtual std::unique_ptr<SemanticExtension> readOptions(cxxopts::ParseResult &providedOptions) const override { if (providedOptions["version"].as<bool>()) { fmt::print("Sorbet compiler {}\n", sorbet_full_version_string); throw EarlyReturnWithCode(0); } optional<string> compiledOutputDir; optional<string> irOutputDir; bool forceCompiled = false; if (providedOptions.count("compiled-out-dir") > 0) { auto outputDir = providedOptions["compiled-out-dir"].as<string>(); if (!FileOps::dirExists(outputDir)) { fmt::print("Missing output directory {}\n", outputDir); throw EarlyReturnWithCode(1); } compiledOutputDir = outputDir; } if (providedOptions.count("llvm-ir-dir") > 0) { auto outputDir = providedOptions["llvm-ir-dir"].as<string>(); if (!FileOps::dirExists(outputDir)) { fmt::print("Missing output directory {}\n", outputDir); throw EarlyReturnWithCode(1); } irOutputDir = outputDir; } if (providedOptions.count("force-compiled") > 0) { forceCompiled = providedOptions["force-compiled"].as<bool>(); } return make_unique<LLVMSemanticExtension>(compiledOutputDir, irOutputDir, forceCompiled); }; virtual std::unique_ptr<SemanticExtension> defaultInstance() const override { optional<string> compiledOutputDir; optional<string> irOutputDir; auto forceCompile = false; return make_unique<LLVMSemanticExtension>(compiledOutputDir, irOutputDir, forceCompile); } virtual ~LLVMSemanticExtensionProvider(){}; }; vector<SemanticExtensionProvider *> SemanticExtensionProvider::getProviders() { static LLVMSemanticExtensionProvider provider; return {&provider}; } } // namespace sorbet::pipeline::semantic_extension
41.923077
120
0.617125
teamsimplepay
88243da6da01aa28eae1f7e434b85f789ab9feaa
2,757
hpp
C++
include/tmxlite/ObjectGroup.hpp
jsundgren/MindTheGap
baddbf2b50bd0b136f303402bcf2e26f3e089ba9
[ "MIT" ]
9
2018-11-11T12:56:29.000Z
2021-11-14T20:38:00.000Z
UrsusEngine/tmxlite/include/tmxlite/ObjectGroup.hpp
l1ttl3-Sh4m4n/UrsusEngine
a18074a6aae118ad6321ab6b352ad9904eff2070
[ "MIT" ]
null
null
null
UrsusEngine/tmxlite/include/tmxlite/ObjectGroup.hpp
l1ttl3-Sh4m4n/UrsusEngine
a18074a6aae118ad6321ab6b352ad9904eff2070
[ "MIT" ]
5
2018-11-11T21:16:29.000Z
2021-09-13T14:59:22.000Z
/********************************************************************* Matt Marchant 2016 http://trederia.blogspot.com tmxlite - Zlib license. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. *********************************************************************/ #ifndef TMXLITE_OBJECTGROUP_HPP_ #define TMXLITE_OBJECTGROUP_HPP_ #include <tmxlite/Config.hpp> #include <tmxlite/Layer.hpp> #include <tmxlite/Object.hpp> #include <vector> namespace tmx { /*! \brief ObjectGroup layers contain a series of Objects which may be made up of shapes or images. */ class TMXLITE_EXPORT_API ObjectGroup final : public Layer { public: enum class DrawOrder { Index, //< objects should be drawn in the order in which they appear TopDown //< objects should be drawn sorted by their Y position }; ObjectGroup(); ~ObjectGroup() = default; Type getType() const override { return Layer::Type::Object; } void parse(const pugi::xml_node&) override; /*! \brief Returns the colour associated with this layer */ const Colour& getColour() const { return m_colour; } /*! \brief Returns the DrawOrder for the objects in this group. Defaults to TopDown, where Objects are drawn sorted by Y position */ DrawOrder getDrawOrder() const { return m_drawOrder; } /*! \brief Returns a reference to the vector of properties for the ObjectGroup */ const std::vector<Property>& getProperties() const { return m_properties; } /*! \brief Returns a reference to the vector of Objects which belong to the group */ const std::vector<Object>& getObjects() const { return m_objects; } private: Colour m_colour; DrawOrder m_drawOrder; std::vector<Property> m_properties; std::vector<Object> m_objects; }; } #endif //TMXLITE_OBJECTGROUP_HPP_
32.05814
85
0.65506
jsundgren
88270e6a33ee9696f778d082a73fe4ba2efbac20
751
cpp
C++
Practice Programs/chef_and_rainbow_array.cpp
C-Nikks/CPP_Language_Programs
e3ed1990aedd6b41f2746cdab7661c40f24d5588
[ "MIT" ]
3
2021-02-04T17:59:00.000Z
2022-01-29T17:21:42.000Z
Practice Programs/chef_and_rainbow_array.cpp
C-Nikks/CPP_Language_Programs
e3ed1990aedd6b41f2746cdab7661c40f24d5588
[ "MIT" ]
null
null
null
Practice Programs/chef_and_rainbow_array.cpp
C-Nikks/CPP_Language_Programs
e3ed1990aedd6b41f2746cdab7661c40f24d5588
[ "MIT" ]
3
2021-10-02T14:38:21.000Z
2021-10-05T06:19:22.000Z
#include <iostream> using namespace std; int main() { int T; cin >> T; while (T--) { int N, half, flag = 0; cin >> N; int arr[N]; for (int i = 0; i < N; i++) { cin >> arr[i]; } int count = 0; if (arr[N / 2] == 7 && arr[0] == 1) { for (int i = 0; i < N / 2; i++) { if ((arr[i] == arr[N - 1 - i]) && (arr[i] == arr[i + 1] || arr[i] + 1 == arr[i + 1])) { count++; } } } if (count == N / 2) { cout << "yes" << endl; } else { cout << "no" << endl; } } return 0; }
19.763158
101
0.274301
C-Nikks