hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
a69143e9abf587347b57187bda9f3624ecb386f6
2,331
cpp
C++
projects/PathosEngine/src/pathos/wrapper/transform.cpp
codeonwort/pathosengine
ea568afeac9af3ebe3f2e53cc5abeecb40714466
[ "MIT" ]
11
2016-08-30T12:01:35.000Z
2021-12-29T15:34:03.000Z
projects/PathosEngine/src/pathos/wrapper/transform.cpp
codeonwort/pathosengine
ea568afeac9af3ebe3f2e53cc5abeecb40714466
[ "MIT" ]
9
2016-05-19T03:14:22.000Z
2021-01-17T05:45:52.000Z
projects/PathosEngine/src/pathos/wrapper/transform.cpp
codeonwort/pathosengine
ea568afeac9af3ebe3f2e53cc5abeecb40714466
[ "MIT" ]
null
null
null
#include "pathos/wrapper/transform.h" #include <glm/gtc/matrix_transform.hpp> namespace pathos { Transform::Transform() :matrix(glm::mat4(1.0f)) {} Transform::Transform(const glm::mat4& _matrix) { matrix = _matrix; } const glm::mat4& Transform::getMatrix() const { return matrix; } void Transform::identity() { matrix = glm::mat4(1.0f); } void Transform::append(const glm::mat4& t) { matrix = t * matrix; } //void Transform::appendMove(const glm::vec3& movement) { matrix = glm::translate(matrix, movement); } void Transform::appendMove(const glm::vec3& movement) { matrix = glm::translate(glm::mat4(1.0f), movement) * matrix; } void Transform::appendMove(float dx, float dy, float dz) { appendMove(glm::vec3(dx, dy, dz)); } void Transform::appendRotation(float angle, const glm::vec3& axis) { matrix = glm::rotate(glm::mat4(1.0f), angle, axis) * matrix; } void Transform::appendScale(const glm::vec3& scale) { matrix = glm::scale(glm::mat4(1.0f), scale) * matrix; } //void Transform::appendScale(const glm::vec3& scale) { matrix = glm::scale(matrix, scale); } void Transform::appendScale(float sx, float sy, float sz) { appendScale(glm::vec3(sx, sy, sz)); } void Transform::prepend(const glm::mat4& t) { matrix = matrix * t; } void Transform::prependMove(const glm::vec3& movement) { //matrix = glm::translate(matrix, movement); prepend(glm::translate(glm::mat4(1.0f), movement)); } void Transform::prependMove(float dx, float dy, float dz) { prependMove(glm::vec3(dx, dy, dz)); } void Transform::prependRotation(float angle, const glm::vec3& axis) { matrix = glm::rotate(matrix, angle, axis); } void Transform::prependScale(const glm::vec3& scale) { matrix = glm::scale(matrix, scale); } void Transform::prependScale(float sx, float sy, float sz) { prependScale(glm::vec3(sx, sy, sz)); } glm::vec3 Transform::transformVector(glm::vec3 v) { return glm::vec3(matrix * glm::vec4(v, 0.0f)); } glm::vec3 Transform::inverseTransformVector(glm::vec3 v) const { return glm::vec3(glm::transpose(matrix) * glm::vec4(v, 0.0f)); } glm::vec3 Transform::transformPoint(glm::vec3 v) { return glm::vec3(matrix * glm::vec4(v, 1.0f)); } glm::vec3 Transform::inverseTransformPoint(glm::vec3 v) { return glm::vec3(glm::transpose(matrix) * glm::vec4(v, 1.0f)); } }
31.5
103
0.681253
codeonwort
a69268faabb732483d24cc1b969714805e8d073b
9,591
cpp
C++
lib/PhasarLLVM/ControlFlow/LLVMBasedCFG.cpp
ddiepo-pjr/phasar
78c93057360f71bcd49bf98e275135c70eb27e90
[ "MIT" ]
null
null
null
lib/PhasarLLVM/ControlFlow/LLVMBasedCFG.cpp
ddiepo-pjr/phasar
78c93057360f71bcd49bf98e275135c70eb27e90
[ "MIT" ]
null
null
null
lib/PhasarLLVM/ControlFlow/LLVMBasedCFG.cpp
ddiepo-pjr/phasar
78c93057360f71bcd49bf98e275135c70eb27e90
[ "MIT" ]
1
2020-11-06T06:19:29.000Z
2020-11-06T06:19:29.000Z
/****************************************************************************** * Copyright (c) 2017 Philipp Schubert. * All rights reserved. This program and the accompanying materials are made * available under the terms of LICENSE.txt. * * Contributors: * Philipp Schubert and others *****************************************************************************/ /* * LLVMBasedCFG.cpp * * Created on: 07.06.2017 * Author: philipp */ #include "llvm/IR/BasicBlock.h" #include "llvm/IR/CFG.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "phasar/Config/Configuration.h" #include "phasar/PhasarLLVM/ControlFlow/LLVMBasedCFG.h" #include "phasar/Utils/LLVMShorthands.h" #include "phasar/Utils/Logger.h" #include "phasar/Utils/Utilities.h" #include <algorithm> #include <cassert> #include <iterator> using namespace std; using namespace psr; namespace psr { const llvm::Function * LLVMBasedCFG::getFunctionOf(const llvm::Instruction *Stmt) const { return Stmt->getFunction(); } vector<const llvm::Instruction *> LLVMBasedCFG::getPredsOf(const llvm::Instruction *I) const { vector<const llvm::Instruction *> Preds; if (!IgnoreDbgInstructions) { if (I->getPrevNode()) { Preds.push_back(I->getPrevNode()); } } else { if (I->getPrevNonDebugInstruction()) { Preds.push_back(I->getPrevNonDebugInstruction()); } } // If we do not have a predecessor yet, look for basic blocks which // lead to our instruction in question! if (Preds.empty()) { std::transform(llvm::pred_begin(I->getParent()), llvm::pred_end(I->getParent()), back_inserter(Preds), [](const llvm::BasicBlock *BB) { assert(BB && "BB under analysis was not well formed."); return BB->getTerminator(); }); } return Preds; } vector<const llvm::Instruction *> LLVMBasedCFG::getSuccsOf(const llvm::Instruction *I) const { vector<const llvm::Instruction *> Successors; // case we wish to consider LLVM's debug instructions if (!IgnoreDbgInstructions) { if (I->getNextNode()) { Successors.push_back(I->getNextNode()); } } else { if (I->getNextNonDebugInstruction()) { Successors.push_back(I->getNextNonDebugInstruction()); } } if (I->isTerminator()) { Successors.reserve(I->getNumSuccessors() + Successors.size()); std::transform(llvm::succ_begin(I), llvm::succ_end(I), back_inserter(Successors), [](const llvm::BasicBlock *BB) { return &BB->front(); }); } return Successors; } vector<pair<const llvm::Instruction *, const llvm::Instruction *>> LLVMBasedCFG::getAllControlFlowEdges(const llvm::Function *Fun) const { vector<pair<const llvm::Instruction *, const llvm::Instruction *>> Edges; for (const auto &BB : *Fun) { for (const auto &I : BB) { if (IgnoreDbgInstructions) { // Check for call to intrinsic debug function if (const auto *DbgCallInst = llvm::dyn_cast<llvm::CallInst>(&I)) { if (DbgCallInst->getCalledFunction() && DbgCallInst->getCalledFunction()->isIntrinsic() && (DbgCallInst->getCalledFunction()->getName() == "llvm.dbg.declare")) { continue; } } } auto Successors = getSuccsOf(&I); for (const auto *Successor : Successors) { Edges.emplace_back(&I, Successor); } } } return Edges; } vector<const llvm::Instruction *> LLVMBasedCFG::getAllInstructionsOf(const llvm::Function *Fun) const { vector<const llvm::Instruction *> Instructions; for (const auto &BB : *Fun) { for (const auto &I : BB) { Instructions.push_back(&I); } } return Instructions; } std::set<const llvm::Instruction *> LLVMBasedCFG::getStartPointsOf(const llvm::Function *Fun) const { if (!Fun) { return {}; } if (!Fun->isDeclaration()) { return {&Fun->front().front()}; } else { LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << "Could not get starting points of '" << Fun->getName().str() << "' because it is a declaration"); return {}; } } std::set<const llvm::Instruction *> LLVMBasedCFG::getExitPointsOf(const llvm::Function *Fun) const { if (!Fun) { return {}; } if (!Fun->isDeclaration()) { return {&Fun->back().back()}; } else { LOG_IF_ENABLE(BOOST_LOG_SEV(lg::get(), DEBUG) << "Could not get exit points of '" << Fun->getName().str() << "' which is declaration!"); return {}; } } bool LLVMBasedCFG::isCallStmt(const llvm::Instruction *Stmt) const { return llvm::isa<llvm::CallInst>(Stmt) || llvm::isa<llvm::InvokeInst>(Stmt); } bool LLVMBasedCFG::isExitStmt(const llvm::Instruction *Stmt) const { return llvm::isa<llvm::ReturnInst>(Stmt); } bool LLVMBasedCFG::isStartPoint(const llvm::Instruction *Stmt) const { return (Stmt == &Stmt->getFunction()->front().front()); } bool LLVMBasedCFG::isFieldLoad(const llvm::Instruction *Stmt) const { if (const auto *Load = llvm::dyn_cast<llvm::LoadInst>(Stmt)) { if (const auto *GEP = llvm::dyn_cast<llvm::GetElementPtrInst>( Load->getPointerOperand())) { return true; } } return false; } bool LLVMBasedCFG::isFieldStore(const llvm::Instruction *Stmt) const { if (const auto *Store = llvm::dyn_cast<llvm::StoreInst>(Stmt)) { if (const auto *GEP = llvm::dyn_cast<llvm::GetElementPtrInst>( Store->getPointerOperand())) { return true; } } return false; } bool LLVMBasedCFG::isFallThroughSuccessor(const llvm::Instruction *Stmt, const llvm::Instruction *Succ) const { // assert(false && "FallThrough not valid in LLVM IR"); if (const auto *B = llvm::dyn_cast<llvm::BranchInst>(Stmt)) { if (B->isConditional()) { return &B->getSuccessor(1)->front() == Succ; } else { return &B->getSuccessor(0)->front() == Succ; } } return false; } bool LLVMBasedCFG::isBranchTarget(const llvm::Instruction *Stmt, const llvm::Instruction *Succ) const { if (Stmt->isTerminator()) { for (const auto *BB : llvm::successors(Stmt->getParent())) { if (&BB->front() == Succ) { return true; } } } return false; } bool LLVMBasedCFG::isHeapAllocatingFunction(const llvm::Function *Fun) const { static const std::set<std::string> HeapAllocatingFunctions = { "_Znwm", "_Znam", "malloc", "calloc", "realloc"}; if (!Fun) { return false; } if (Fun->hasName() && HeapAllocatingFunctions.find(Fun->getName().str()) != HeapAllocatingFunctions.end()) { return true; } return false; } bool LLVMBasedCFG::isSpecialMemberFunction(const llvm::Function *Fun) const { return getSpecialMemberFunctionType(Fun) != SpecialMemberFunctionType::None; } SpecialMemberFunctionType LLVMBasedCFG::getSpecialMemberFunctionType(const llvm::Function *Fun) const { if (!Fun) { return SpecialMemberFunctionType::None; } auto FunctionName = Fun->getName(); // TODO this looks terrible and needs fix static const std::map<std::string, SpecialMemberFunctionType> Codes{ {"C1", SpecialMemberFunctionType::Constructor}, {"C2", SpecialMemberFunctionType::Constructor}, {"C3", SpecialMemberFunctionType::Constructor}, {"D0", SpecialMemberFunctionType::Destructor}, {"D1", SpecialMemberFunctionType::Destructor}, {"D2", SpecialMemberFunctionType::Destructor}, {"aSERKS_", SpecialMemberFunctionType::CopyAssignment}, {"aSEOS_", SpecialMemberFunctionType::MoveAssignment}}; std::vector<std::pair<std::size_t, SpecialMemberFunctionType>> Found; std::size_t Blacklist = 0; auto It = Codes.begin(); while (It != Codes.end()) { if (std::size_t Index = FunctionName.find(It->first, Blacklist)) { if (Index != std::string::npos) { Found.emplace_back(Index, It->second); Blacklist = Index + 1; } else { ++It; Blacklist = 0; } } } if (Found.empty()) { return SpecialMemberFunctionType::None; } // test if codes are in function name or type information bool NoName = true; for (auto Index : Found) { for (auto C = FunctionName.begin(); C < FunctionName.begin() + Index.first; ++C) { if (isdigit(*C)) { short I = 0; while (isdigit(*(C + I))) { ++I; } std::string ST(C, C + I); if (Index.first <= std::distance(FunctionName.begin(), C) + stoul(ST)) { NoName = false; break; } else { C = C + *C; } } } if (NoName) { return Index.second; } else { NoName = true; } } return SpecialMemberFunctionType::None; } string LLVMBasedCFG::getStatementId(const llvm::Instruction *Stmt) const { return llvm::cast<llvm::MDString>( Stmt->getMetadata(PhasarConfig::MetaDataKind())->getOperand(0)) ->getString() .str(); } string LLVMBasedCFG::getFunctionName(const llvm::Function *Fun) const { return Fun->getName().str(); } std::string LLVMBasedCFG::getDemangledFunctionName(const llvm::Function *Fun) const { return cxxDemangle(getFunctionName(Fun)); } void LLVMBasedCFG::print(const llvm::Function *F, std::ostream &OS) const { OS << llvmIRToString(F); } nlohmann::json LLVMBasedCFG::getAsJson(const llvm::Function *F) const { return ""; } } // namespace psr
30.255521
80
0.620686
ddiepo-pjr
a69458a1b541471333915ca9b97d16ec0dd433bf
669
inl
C++
dds/DCPS/transport/framework/RemoveAllVisitor.inl
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
dds/DCPS/transport/framework/RemoveAllVisitor.inl
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
dds/DCPS/transport/framework/RemoveAllVisitor.inl
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
/* * $Id: RemoveAllVisitor.inl 4387 2011-03-08 20:13:10Z mitza $ * * * Distributed under the OpenDDS License. * See: http://www.opendds.org/license.html */ #include "EntryExit.h" ACE_INLINE OpenDDS::DCPS::RemoveAllVisitor::RemoveAllVisitor() : status_(0), removed_bytes_(0) { DBG_ENTRY_LVL("RemoveAllVisitor","RemoveAllVisitor",6); } ACE_INLINE int OpenDDS::DCPS::RemoveAllVisitor::status() const { DBG_ENTRY_LVL("RemoveAllVisitor","status",6); return this->status_; } ACE_INLINE int OpenDDS::DCPS::RemoveAllVisitor::removed_bytes() const { DBG_ENTRY_LVL("RemoveAllVisitor","removed_bytes",6); return static_cast<int>(this->removed_bytes_); }
20.90625
62
0.733931
binary42
a69499de813ffb1eee8b222dac0963a292c9710b
4,796
cpp
C++
src/Processors/Formats/Impl/JSONEachRowRowOutputFormat.cpp
tianyiYoung/ClickHouse
41012b5ba49df807af52fc17ab475a21fadda9b3
[ "Apache-2.0" ]
5
2021-05-14T02:46:44.000Z
2021-11-23T04:58:20.000Z
src/Processors/Formats/Impl/JSONEachRowRowOutputFormat.cpp
tianyiYoung/ClickHouse
41012b5ba49df807af52fc17ab475a21fadda9b3
[ "Apache-2.0" ]
5
2021-05-21T06:26:01.000Z
2021-08-04T04:57:36.000Z
src/Processors/Formats/Impl/JSONEachRowRowOutputFormat.cpp
tianyiYoung/ClickHouse
41012b5ba49df807af52fc17ab475a21fadda9b3
[ "Apache-2.0" ]
8
2021-05-12T01:38:18.000Z
2022-02-10T06:08:41.000Z
#include <IO/WriteHelpers.h> #include <IO/WriteBufferValidUTF8.h> #include <Processors/Formats/Impl/JSONEachRowRowOutputFormat.h> #include <Formats/FormatFactory.h> namespace DB { JSONEachRowRowOutputFormat::JSONEachRowRowOutputFormat( WriteBuffer & out_, const Block & header_, const RowOutputFormatParams & params_, const FormatSettings & settings_) : IRowOutputFormat(header_, out_, params_), settings(settings_) { const auto & sample = getPort(PortKind::Main).getHeader(); size_t columns = sample.columns(); fields.resize(columns); for (size_t i = 0; i < columns; ++i) { WriteBufferFromString buf(fields[i]); writeJSONString(sample.getByPosition(i).name, buf, settings); } } void JSONEachRowRowOutputFormat::writeField(const IColumn & column, const ISerialization & serialization, size_t row_num) { writeString(fields[field_number], out); writeChar(':', out); if (settings.json.serialize_as_strings) { WriteBufferFromOwnString buf; serialization.serializeText(column, row_num, buf, settings); writeJSONString(buf.str(), out, settings); } else serialization.serializeTextJSON(column, row_num, out, settings); ++field_number; } void JSONEachRowRowOutputFormat::writeFieldDelimiter() { writeChar(',', out); } void JSONEachRowRowOutputFormat::writeRowStartDelimiter() { writeChar('{', out); } void JSONEachRowRowOutputFormat::writeRowEndDelimiter() { // Why do we need this weird `if`? // // The reason is the formatRow function that is broken with respect to // row-between delimiters. It should not write them, but it does, and then // hacks around it by having a special formatRowNoNewline version, which, as // you guessed, removes the newline from the end of row. But the row-between // delimiter goes into a second row, so it turns out to be in the beginning // of the line, and the removal doesn't work. There is also a second bug -- // the row-between delimiter in this format is written incorrectly. In fact, // it is not written at all, and the newline is written in a row-end // delimiter ("}\n" instead of the correct "}"). With these two bugs // combined, the test 01420_format_row works perfectly. // // A proper implementation of formatRow would use IRowOutputFormat directly, // and not write row-between delimiters, instead of using IOutputFormat // processor and its crutch row callback. This would require exposing // IRowOutputFormat, which we don't do now, but which can be generally useful // for other cases such as parallel formatting, that also require a control // flow different from the usual IOutputFormat. // // I just don't have time or energy to redo all of this, but I need to // support JSON array output here, which requires proper ",\n" row-between // delimiters. For compatibility, I preserve the bug in case of non-array // output. if (settings.json.array_of_rows) { writeCString("}", out); } else { writeCString("}\n", out); } field_number = 0; } void JSONEachRowRowOutputFormat::writeRowBetweenDelimiter() { // We preserve an existing bug here for compatibility. See the comment above. if (settings.json.array_of_rows) { writeCString(",\n", out); } } void JSONEachRowRowOutputFormat::writePrefix() { if (settings.json.array_of_rows) { writeCString("[\n", out); } } void JSONEachRowRowOutputFormat::writeSuffix() { if (settings.json.array_of_rows) { writeCString("\n]\n", out); } } void registerOutputFormatProcessorJSONEachRow(FormatFactory & factory) { factory.registerOutputFormatProcessor("JSONEachRow", []( WriteBuffer & buf, const Block & sample, const RowOutputFormatParams & params, const FormatSettings & _format_settings) { FormatSettings settings = _format_settings; settings.json.serialize_as_strings = false; return std::make_shared<JSONEachRowRowOutputFormat>(buf, sample, params, settings); }); factory.markOutputFormatSupportsParallelFormatting("JSONEachRow"); factory.registerOutputFormatProcessor("JSONStringsEachRow", []( WriteBuffer & buf, const Block & sample, const RowOutputFormatParams & params, const FormatSettings & _format_settings) { FormatSettings settings = _format_settings; settings.json.serialize_as_strings = true; return std::make_shared<JSONEachRowRowOutputFormat>(buf, sample, params, settings); }); factory.markOutputFormatSupportsParallelFormatting("JSONStringEachRow"); } }
30.35443
121
0.689741
tianyiYoung
a6951c83c993fefc29dd3e1decb69beececf8c5b
2,645
cpp
C++
codeforces/PracticeRound016/b.cpp
Shahraaz/CP_S5
2cfb5467841d660c1e47cb8338ea692f10ca6e60
[ "MIT" ]
3
2020-02-08T10:34:16.000Z
2020-02-09T10:23:19.000Z
codeforces/PracticeRound016/b.cpp
Shahraaz/CP_S5
2cfb5467841d660c1e47cb8338ea692f10ca6e60
[ "MIT" ]
null
null
null
codeforces/PracticeRound016/b.cpp
Shahraaz/CP_S5
2cfb5467841d660c1e47cb8338ea692f10ca6e60
[ "MIT" ]
2
2020-10-02T19:05:32.000Z
2021-09-08T07:01:49.000Z
// Optimise #include <bits/stdc++.h> using namespace std; #ifdef LOCAL #include "/home/shahraaz/bin/debug.h" #else #define db(...) #endif using ll = long long; #define f first #define s second #define pb push_back #define all(v) v.begin(), v.end() const int NAX = 2e5 + 5, MOD = 1000000007; class Solution { private: string truncate(string str) { string ret = ""; for (auto &x : str) { if (ret.size() == 0 && x == '0') continue; ret += x; } if (ret == "" and count(all(str), '0')) ret = "0"; return ret; } public: Solution() {} ~Solution() {} void solveCase() { string n; cin >> n; int sum = 0; for (auto &x : n) sum += (x - '0') % 3; sum %= 3; db(n, sum); vector<string> sols; if (sum == 0) { sols.pb(truncate(n)); } else { for (int i = n.size() - 1; i >= 0; i--) { if ((n[i] - 0) % 3 == sum) { auto t = n.substr(0, i) + n.substr(i + 1); t = truncate(t); if (t.size()) sols.pb(t); break; } } int p1 = -1; for (int i = n.size() - 1; i >= 0; i--) { if ((n[i] - 0) % 3 == 0) continue; if ((n[i] - 0) % 3 != sum) { if (p1 == -1) { p1 = i; continue; } auto t = n.substr(0, i) + n.substr(i + 1, p1 - i - 1) + n.substr(p1 + 1); t = truncate(t); if (t.size()) sols.pb(t); break; } } } db(sols); if (sols.size() == 0) cout << -1 << '\n'; else cout << *max_element(sols.begin(), sols.end(), [](string a, string b) -> bool { return a.length() < b.length(); }) << '\n'; } }; int32_t main() { #ifndef LOCAL ios_base::sync_with_stdio(0); cin.tie(0); #endif int t = 1; // cin >> t; Solution mySolver; for (int i = 1; i <= t; ++i) { mySolver.solveCase(); #ifdef LOCAL cerr << "Case #" << i << ": Time " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " s.\n"; TimeStart = chrono::steady_clock::now(); #endif } return 0; }
23.40708
135
0.36862
Shahraaz
a6972419470e24f0ba08520476ada6e9abb7018f
177
hh
C++
vpp/algorithms/line_tracker_4_sfm/hough_extruder.hh
WLChopSticks/vpp
2e17b21c56680bcfa94292ef5117f73572bf277d
[ "MIT" ]
624
2015-01-05T16:40:41.000Z
2022-03-01T03:09:43.000Z
vpp/algorithms/line_tracker_4_sfm/hough_extruder.hh
WLChopSticks/vpp
2e17b21c56680bcfa94292ef5117f73572bf277d
[ "MIT" ]
10
2015-01-22T20:50:13.000Z
2018-05-15T10:41:34.000Z
vpp/algorithms/line_tracker_4_sfm/hough_extruder.hh
WLChopSticks/vpp
2e17b21c56680bcfa94292ef5117f73572bf277d
[ "MIT" ]
113
2015-01-19T11:58:35.000Z
2022-03-28T05:15:20.000Z
#pragma once #include "hough_extruder/draw_trajectories_hough.hh" #include "symbols.hh" #include "hough_extruder/paint.hh" #include "hough_extruder/feature_matching_hough.hh"
22.125
52
0.819209
WLChopSticks
a69c4f7b0e8230f4d3b430d27aa4da4de86ac047
3,136
cpp
C++
examples/tests-div-detection/shortest-path/shortest-path.cpp
soarlab/S3FP
f1459d2a3d424651d5b87844e3f02a61e3ed2ad1
[ "MIT" ]
null
null
null
examples/tests-div-detection/shortest-path/shortest-path.cpp
soarlab/S3FP
f1459d2a3d424651d5b87844e3f02a61e3ed2ad1
[ "MIT" ]
null
null
null
examples/tests-div-detection/shortest-path/shortest-path.cpp
soarlab/S3FP
f1459d2a3d424651d5b87844e3f02a61e3ed2ad1
[ "MIT" ]
null
null
null
#include <stdio.h> #include <assert.h> #include <utility> #include "s3fp_utils.h" using namespace std; #ifndef IFT #define IFT float #endif #ifndef OFT #define OFT __float128 #endif unsigned int D = 0; // the number of nodes // first : true => is +/- inf // first : false => normal length typedef pair<bool, WFT> EDIST; inline EDIST edistAdd (EDIST ed1, EDIST ed2) { EDIST ret (true, 0); if (ed1.first || ed2.first) return ret; else { ret.first = false; ret.second = ed1.second + ed2.second; } return ret; } inline bool edistLessThan (EDIST ed1, EDIST ed2) { if (ed1.first) return false; if (ed2.first) return true; return ed1.second < ed2.second; } inline void SetDist(EDIST *dist, unsigned int s, unsigned int d, EDIST dis) { assert(s <= D); assert(d <= D); dist[s * D + d] = dis; } inline EDIST GetDist(EDIST *dist, unsigned int s, unsigned int d) { assert(s <= D); assert(d <= D); return dist[s * D + d]; } inline void DumpDists(EDIST *dist) { printf("==== dump dists ====\n"); for (unsigned int s = 0 ; s < D ; s++) { for (unsigned int d = 0 ; d < D ; d++) { EDIST ed = GetDist(dist, s, d); if (ed.first) printf("+/-inf "); else printf("%5.4f ", (double) ed.second); } printf("\n"); } printf("====================\n"); } int main (int argc, char *argv[]) { FILE *infile = s3fpGetInFile(argc, argv); FILE *outfile = s3fpGetOutFile(argc, argv); unsigned long fsize = s3fpFileSize(infile); assert(fsize % sizeof(IFT) == 0); fsize = fsize / sizeof(IFT); while (true) { if (D*D-D == fsize) break; assert((D*D-D) < fsize); D++; } assert(D >= 3); EDIST *dist = (EDIST*) malloc(sizeof(EDIST) * D * D); EDIST dzero (false, 0); EDIST dinf (true, 0); IFT idata; for (unsigned int s = 0 ; s < D ; s++) { for (unsigned int d = 0 ; d < D ; d++) { if (s == d) idata = 0; else fread(&idata, sizeof(IFT), 1, infile); SetDist(dist, s, d, EDIST(false, idata)); } } /* #ifdef __VERBOSE DumpDists(dist); #endif */ for (unsigned int m = 0 ; m < D ; m++) { for (unsigned int s = 0 ; s < D ; s++) { for (unsigned int d = 0 ; d < D ; d++) { EDIST stom = GetDist(dist, s, m); EDIST mtod = GetDist(dist, m, d); EDIST stod = GetDist(dist, s, d); EDIST stom_mtod = edistAdd(stom, mtod); if ( edistLessThan(stom_mtod, stod)) SetDist(dist, s, d, stom_mtod); } } } /* #ifdef __VERBOSE DumpDists(dist); #endif */ OFT *odata = (OFT*) malloc(sizeof(OFT) * (D-2)); bool neg_loop = false; for (unsigned int i = 0 ; i < (D-2) ; i++) { EDIST ed = GetDist(dist, i, i); odata[i] = ed.second; if (ed.first == false) { if (ed.second < 0) { #ifdef __VERBOSE printf("NEG LOOP: dist[%d][%d] = %21.20f \n", i, i, (double)ed.second); #endif neg_loop = true; } } } fwrite(odata, sizeof(OFT), (D-2), outfile); OFT out_det = (neg_loop ? 1.0 : 0.0); fwrite(&out_det, sizeof(OFT), 1,outfile); fclose(infile); fclose(outfile); return 0; }
20.232258
72
0.555804
soarlab
a69cf8307ec9c218c90a231427ebf5ea5ae8cce8
616
cpp
C++
UVa 541 error correction/sample/541 - Error Correction.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 541 error correction/sample/541 - Error Correction.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 541 error correction/sample/541 - Error Correction.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
#include<stdio.h> int main() { int matrix[101][101], n, i, j; while(scanf("%d", &n) == 1 && n) { for(i = 0; i < n; i++) for(j = 0; j < n; j++) scanf("%d", &matrix[i][j]); int R[100] = {0}, C[100] = {0}; for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { C[i] += matrix[i][j]; R[i] += matrix[j][i]; } } int ER = 0, EC = 0, er, ec; for(i = 0; i < n; i++) { if(R[i]&1) ER++, er = i; if(C[i]&1) EC++, ec = i; } if(ER == 0 && EC == 0) puts("OK"); else if(ER == 1 && EC == 1) printf("Change bit (%d,%d)\n", ec+1, er+1); else puts("Corrupt"); } return 0; }
20.533333
46
0.396104
tadvi
a6a01560fa8ffa9769cb0bff2c847e6266ed1a86
3,463
cpp
C++
FB/modes.cpp
ivanagui2/VMQemuVGA
57a2df0b00a31569efd6773e88d203d331264846
[ "MIT" ]
19
2018-01-15T22:44:50.000Z
2022-01-16T01:14:15.000Z
FB/modes.cpp
PureDarwin/VMQemuVGA
79f8fa75a1c6be904357517d235ca7a8d54d9439
[ "MIT" ]
null
null
null
FB/modes.cpp
PureDarwin/VMQemuVGA
79f8fa75a1c6be904357517d235ca7a8d54d9439
[ "MIT" ]
4
2016-11-06T14:15:26.000Z
2019-08-26T12:42:54.000Z
/* * modes.cpp * VMsvga2 * * Created by Zenith432 on July 11th 2009. * Copyright 2009-2011 Zenith432. All rights reserved. * */ /********************************************************** * Portions Copyright 2009 VMware, Inc. All rights reserved. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * **********************************************************/ #include <IOKit/graphics/IOGraphicsTypes.h> #include "common_fb.h" //Dot-Clock, HDisp, HSyncStart, HSyncEnd, HTotal, VDisp, VSyncStart, VSyncEnd, VTotal DisplayModeEntry const modeList[NUM_DISPLAY_MODES] = { 800, 600, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 4x3 Note: reserved for Custom Mode 800, 600, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 4x3 1024, 768, kDisplayModeValidFlag | kDisplayModeSafeFlag | kDisplayModeDefaultFlag, // 4x3 1152, 720, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 8x5 1152, 864, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 4x3 1152, 900, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 32x25 1280, 720, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 16x9 1280, 768, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 5x3 1280, 800, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 8x5 1280, 960, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 4x3 1280, 1024, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 5x4 //1366, 768, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 16x9 //give only garbage 1376, 1032, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 4x3 1400, 1050, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 4x3 1440, 900, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 8x5 Note: was 1400x900 1600, 900, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 16x9 1600, 1200, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 4x3 1680, 1050, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 8x5 1920, 1080, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 16x9 1920, 1200, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 8x5 1920, 1440, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 4x3 2048, 1152, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 16x9 2048, 1536, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 4x3 2360, 1770, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 4x3 Note: was 2364x1773 2560, 1440, kDisplayModeValidFlag | kDisplayModeSafeFlag, // 16x9 2560, 1600, kDisplayModeValidFlag | kDisplayModeSafeFlag // 8x5 };
48.097222
95
0.741265
ivanagui2
a6a3bcc076f85e16b9f3ecd155ccd6d9e102980f
1,639
cpp
C++
NNGameFramework/ProjectWugargar/PoorZombie.cpp
quxn6/wugargar
79e71a83e1240052ec4217d5223359ca5f1c3890
[ "MIT" ]
1
2017-02-13T06:09:17.000Z
2017-02-13T06:09:17.000Z
NNGameFramework/ProjectWugargar/PoorZombie.cpp
quxn6/wugargar
79e71a83e1240052ec4217d5223359ca5f1c3890
[ "MIT" ]
null
null
null
NNGameFramework/ProjectWugargar/PoorZombie.cpp
quxn6/wugargar
79e71a83e1240052ec4217d5223359ca5f1c3890
[ "MIT" ]
null
null
null
#include "PoorZombie.h" CPoorZombie::CPoorZombie(void) { initStatus(); } CPoorZombie::~CPoorZombie(void) { } void CPoorZombie::initStatus( void ) { m_zombieType = POOR_ZOMBIE; m_HealthPoint = 40; m_FullHP = m_HealthPoint; m_MovingSpeed = 40.0f; m_AttackPower = 15; m_DefensivePower = 2; m_AttackRange = 30.0f; m_NumberOfTarget = 1; m_AttackSpeed = 1500; m_CreateCost = 50; m_Identity = Zombie; m_SplashAttack = false; ApplyZombieLevel(); WalkAnimationImagePath.push_back(L"wugargar/poor/walk/0.png"); WalkAnimationImagePath.push_back(L"wugargar/poor/walk/1.png"); WalkAnimationImagePath.push_back(L"wugargar/poor/walk/2.png"); WalkAnimationImagePath.push_back(L"wugargar/poor/walk/3.png"); WalkAnimationImagePath.push_back(L"wugargar/poor/walk/4.png"); WalkAnimationImagePath.push_back(L"wugargar/poor/walk/5.png"); WalkAnimationImagePath.push_back(L"wugargar/poor/walk/6.png"); WalkAnimationImagePath.push_back(L"wugargar/poor/walk/7.png"); DeadAnimationImagePath.push_back(L"wugargar/poor/dead/0.png"); DeadAnimationImagePath.push_back(L"wugargar/poor/dead/1.png"); DeadAnimationImagePath.push_back(L"wugargar/poor/dead/2.png"); DeadAnimationImagePath.push_back(L"wugargar/poor/dead/3.png"); DeadAnimationImagePath.push_back(L"wugargar/poor/dead/4.png"); DeadAnimationImagePath.push_back(L"wugargar/poor/dead/5.png"); DeadAnimationImagePath.push_back(L"wugargar/poor/dead/6.png"); DeadAnimationImagePath.push_back(L"wugargar/poor/dead/7.png"); InitZombieAnimation(); } void CPoorZombie::Render() { NNObject::Render(); } void CPoorZombie::Update( float dTime ) { CCharacter::Update(dTime); }
26.015873
63
0.775473
quxn6
a6a8542ee0ec095d7e1b909772e725a9a3985e52
9,453
cpp
C++
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/GeneralData.cpp
mandeepshetty/iotivity
fea1aa7f7088fdf206ebc3ff587766da96836708
[ "Apache-2.0" ]
null
null
null
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/GeneralData.cpp
mandeepshetty/iotivity
fea1aa7f7088fdf206ebc3ff587766da96836708
[ "Apache-2.0" ]
null
null
null
service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/GeneralData.cpp
mandeepshetty/iotivity
fea1aa7f7088fdf206ebc3ff587766da96836708
[ "Apache-2.0" ]
1
2022-01-22T19:42:20.000Z
2022-01-22T19:42:20.000Z
/****************************************************************** * * Copyright 2014 Samsung Electronics 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 <stdio.h> #include <stdlib.h> #include <string.h> #include "GeneralData.h" //#define __INTER_DEBUG__ // Hidden Class define. template <typename TYPE> class AllFormat_data : public Virtual_data { typedef Virtual_data base; private : TYPE data; public : AllFormat_data(int typenum) : base(typenum), data() { #ifdef __INTER_DEBUG__ printf("[DEBUG] Test_data Constructor().\n"); #endif } virtual void put_data( void *value) { data = *(TYPE *)value; } virtual void *get_data( void ) { return (void *)&data; } }; /******************************************* * Virtual_data class member function define. */ void Virtual_data::s2data( const char *value) { switch (dataType) { case TYPE_CHAR : { char data = atoi(value); put_data( (void *)&data ); } break; case TYPE_INT : case TYPE_SHORT : { int data = atoi(value); put_data( (void *)&data ); } break; case TYPE_FLOAT : { float data = atof(value); put_data( (void *)&data ); } break; case TYPE_DOUBLE : { double data = atof(value); put_data( (void *)&data ); } break; case TYPE_NODEFINE : printf("Error: dataType must have defined.\n"); break; default : printf("Error: Not yet supported type.\n"); break; } } Virtual_data::Virtual_data( void ) { dataType = TYPE_NODEFINE; } Virtual_data::Virtual_data(int type) { #ifdef __INTER_DEBUG__ printf("[DEBUG] Virtual_data Constructor().\n"); #endif dataType = type; } void Virtual_data::put(std::string value) { if (dataType == TYPE_STRING ) put_data( (void *)&value ); else s2data( value.c_str() ); } void Virtual_data::put(char *value) { if (dataType == TYPE_STRING ) { std::string temp = std::string(value); put_data( (void *)&temp ); } else s2data( value ); } int Virtual_data::get( std::string *value) { if (dataType != TYPE_STRING) { printf("Error : dataType is Not string.\n"); return 0; } void *data = get_data(); *value = *(std::string *)data; return 1; } void Virtual_data::put_data( void *value ) { printf("Error: virtual function(put_data) called.\n"); } void *Virtual_data::get_data( void ) { printf("Error: virtual function(get) called.\n"); return NULL; } /******************************************* * GeneralData class member function define. */ void GeneralData::set_dataType(const char *type) { if ( strstr(type, "string") != NULL ) { dataType = TYPE_STRING; #ifdef __INTER_DEBUG__ printf("DataType is std::string.\n"); #endif return ; } if ( strstr(type, "char") != NULL ) { dataType = TYPE_CHAR; #ifdef __INTER_DEBUG__ printf("DataType is Character.\n"); #endif return ; } if ( strstr(type, "int") != NULL ) { dataType = TYPE_INT; #ifdef __INTER_DEBUG__ printf("DataType is Integer.\n"); #endif return ; } if ( strstr(type, "short") != NULL ) { dataType = TYPE_SHORT; #ifdef __INTER_DEBUG__ printf("DataType is Short.\n"); #endif return ; } if ( strstr(type, "float") != NULL ) { dataType = TYPE_FLOAT; #ifdef __INTER_DEBUG__ printf("DataType is Floating.\n"); #endif return ; } if ( strstr(type, "double") != NULL ) { dataType = TYPE_DOUBLE; #ifdef __INTER_DEBUG__ printf("DataType is Double.\n"); #endif return ; } dataType = TYPE_NODEFINE; } GeneralData::GeneralData( void ) { #ifdef __INTER_DEBUG__ printf("[DEBUG] Virtual_Test Constructor().\n"); #endif flag = false; Name = ""; dataType = TYPE_NODEFINE; pValue = 0; } GeneralData::GeneralData( std::string name, std::string type ) { #ifdef __INTER_DEBUG__ printf("[DEBUG] Data_Normal Constructor().\n"); #endif flag = false; Name = ""; dataType = TYPE_NODEFINE; pValue = 0; flag = initial( name, type ); } GeneralData::GeneralData( std::string name, std::string type, std::string value ) { #ifdef __INTER_DEBUG__ printf("[DEBUG] Data_Normal Constructor().\n"); #endif flag = false; Name = ""; dataType = TYPE_NODEFINE; pValue = 0; flag = initial( name, type ); put(value); } bool GeneralData::initial( std::string name, std::string type ) { Name = name; set_dataType( type.c_str() ); switch (dataType) { case TYPE_STRING : pValue = new AllFormat_data<std::string>(dataType); break; case TYPE_CHAR : pValue = new AllFormat_data<char>(dataType); break; case TYPE_INT : pValue = new AllFormat_data<int>(dataType); break; case TYPE_SHORT : pValue = new AllFormat_data<short>(dataType); break; case TYPE_FLOAT : pValue = new AllFormat_data<float>(dataType); break; case TYPE_DOUBLE : pValue = new AllFormat_data<double>(dataType); break; case TYPE_NODEFINE : pValue = 0; printf("Error : set_dataType()function is returned TYPE_NODEFINE.\n"); break; } return true; } bool GeneralData::get_Name( std::string &name ) { BOOLINIT_CHECK(); name = Name; return true; } void GeneralData::put( std::string value ) { VOIDINIT_CHECK(); pValue->put(value); } void GeneralData::put( const char *value ) { VOIDINIT_CHECK(); pValue->put(value); } int GeneralData::get_DataType( void ) { BOOLINIT_CHECK(); return dataType; } bool GeneralData::get( std::string *data ) { BOOLINIT_CHECK(); if ( pValue->get(data) == NULL ) { printf("Error : No data.\n"); *data = ""; return false; } return true; } void Conversion_DataFormat( std::vector < std::map< std::string, std::string > > lVector , std::vector< GeneralData > &gVector ) { #ifdef __INTERNAL_DEBUG__ std::cout << "[DEBUG] ITS::" << __func__ << " is called." << std::endl; #endif std::string name; std::string type; std::string value; for (unsigned int j = 0; j < lVector.size(); j++) { name = lVector[j]["name"]; type = lVector[j]["type"]; value = lVector[j]["value"]; GeneralData pValue(name, type, value); gVector.push_back(pValue); } /************************************************* * Debugging print ( GeneralData format confirm. ) */ #ifdef __INTERNAL_DEBUG__ for (unsigned int j = 0; j < gVector.size(); j++) { if ( gVector[j].get_Name(name) == false ) { printf("Error : Not initialed.\n"); return ; } int dataType = gVector[j].get_DataType(); switch (dataType) { case TYPE_STRING : { std::string data; if ( gVector[j].get(&data) == false ) { printf("Error : Not initialed.\n"); return ; } printf("name=%s , type=%d, value=%s\n", name.c_str(), dataType, data.c_str() ); } break; case TYPE_CHAR : case TYPE_SHORT : case TYPE_INT : { int data; if ( gVector[j].get(&data) == false ) { printf("Error : Not initialed.\n"); return ; } printf("name=%s , type=%d, value=%d\n", name.c_str(), dataType, data ); } break; case TYPE_FLOAT : case TYPE_DOUBLE : { float data; if ( gVector[j].get(&data) == false ) { printf("Error : Not initialed.\n"); return ; } printf("name=%s , type=%d, value=%f\n", name.c_str(), dataType, data ); } break; } } #endif printf("Conversion_DataFormat() is Successful.\n"); }
23.169118
99
0.515709
mandeepshetty
16f57350fc1bff2228952b0cc63072a9c9488e02
39,862
cpp
C++
src/Storage_base.cpp
yingjerkao/Cytnx
37ac8493fd7a9ace78c32c9281da25c03542c112
[ "Apache-2.0" ]
null
null
null
src/Storage_base.cpp
yingjerkao/Cytnx
37ac8493fd7a9ace78c32c9281da25c03542c112
[ "Apache-2.0" ]
null
null
null
src/Storage_base.cpp
yingjerkao/Cytnx
37ac8493fd7a9ace78c32c9281da25c03542c112
[ "Apache-2.0" ]
null
null
null
#ifdef UNI_OMP #include <omp.h> #endif #include "Storage.hpp" #include "utils/utils_internal_interface.hpp" #include "utils/vec_print.hpp" using namespace std; namespace cytnx{ //Storage Init interface. //============================= boost::intrusive_ptr<Storage_base> SIInit_cd(){ boost::intrusive_ptr<Storage_base> out(new ComplexDoubleStorage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_cf(){ boost::intrusive_ptr<Storage_base> out(new ComplexFloatStorage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_d(){ boost::intrusive_ptr<Storage_base> out(new DoubleStorage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_f(){ boost::intrusive_ptr<Storage_base> out(new FloatStorage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_u64(){ boost::intrusive_ptr<Storage_base> out(new Uint64Storage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_i64(){ boost::intrusive_ptr<Storage_base> out(new Int64Storage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_u32(){ boost::intrusive_ptr<Storage_base> out(new Uint32Storage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_i32(){ boost::intrusive_ptr<Storage_base> out(new Int32Storage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_u16(){ boost::intrusive_ptr<Storage_base> out(new Uint16Storage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_i16(){ boost::intrusive_ptr<Storage_base> out(new Int16Storage()); return out; } boost::intrusive_ptr<Storage_base> SIInit_b(){ boost::intrusive_ptr<Storage_base> out(new BoolStorage()); return out; } Storage_init_interface::Storage_init_interface(){ USIInit.resize(N_Type); USIInit[this->Double] = SIInit_d; USIInit[this->Float] = SIInit_f; USIInit[this->ComplexDouble] = SIInit_cd; USIInit[this->ComplexFloat] = SIInit_cf; USIInit[this->Uint64] = SIInit_u64; USIInit[this->Int64] = SIInit_i64; USIInit[this->Uint32]= SIInit_u32; USIInit[this->Int32] = SIInit_i32; USIInit[this->Uint16]= SIInit_u16; USIInit[this->Int16] = SIInit_i16; USIInit[this->Bool] = SIInit_b; } //========================== void Storage_base::Init(const unsigned long long &len_in,const int &device){ //cout << "Base.init" << endl; } Storage_base::Storage_base(const unsigned long long &len_in,const int &device){ this->Init(len_in,device); } Storage_base& Storage_base::operator=(Storage_base &Rhs){ cout << "dev"<< endl; return *this; } Storage_base::Storage_base(Storage_base &Rhs){ cout << "dev" << endl; } void Storage_base::resize(const cytnx_uint64 &newsize){ cytnx_error_msg(1, "[ERROR][internal] resize should not be called by base%s","\n"); } boost::intrusive_ptr<Storage_base> Storage_base::astype(const unsigned int &dtype){ boost::intrusive_ptr<Storage_base> out(new Storage_base()); if(dtype == this->dtype) return boost::intrusive_ptr<Storage_base>(this); if(this->device==Device.cpu){ if(utils_internal::uii.ElemCast[this->dtype][dtype]==NULL){ cytnx_error_msg(1, "[ERROR] not support type with dtype=%d",dtype); }else{ utils_internal::uii.ElemCast[this->dtype][dtype](this,out,this->len,1); } }else{ #ifdef UNI_GPU if(utils_internal::uii.cuElemCast[this->dtype][dtype]==NULL){ cytnx_error_msg(1,"[ERROR] not support type with dtype=%d",dtype); }else{ //std::cout << this->device << std::endl; utils_internal::uii.cuElemCast[this->dtype][dtype](this,out,this->len,this->device); } #else cytnx_error_msg(1,"%s","[ERROR][Internal Error] enter GPU section without CUDA support @ Storage.astype()"); #endif } return out; } boost::intrusive_ptr<Storage_base> Storage_base::_create_new_sametype(){ cytnx_error_msg(1,"%s","[ERROR] call _create_new_sametype in base"); return nullptr; } boost::intrusive_ptr<Storage_base> Storage_base::clone(){ boost::intrusive_ptr<Storage_base> out(new Storage_base()); return out; } string Storage_base::dtype_str()const{ return Type.getname(this->dtype); } string Storage_base::device_str()const{ return Device.getname(this->device); } void Storage_base::_Init_byptr(void *rawptr, const unsigned long long &len_in, const int &device, const bool &iscap, const unsigned long long &cap_in){ cytnx_error_msg(1,"%s","[ERROR] call _Init_byptr in base"); } Storage_base::~Storage_base(){ //cout << "delet" << endl; if(Mem != NULL){ if(this->device==Device.cpu){ free(Mem); }else{ #ifdef UNI_GPU cudaFree(Mem); #else cytnx_error_msg(1,"%s","[ERROR] trying to free an GPU memory without CUDA install"); #endif } } } void Storage_base::Move_memory_(const std::vector<cytnx_uint64> &old_shape, const std::vector<cytnx_uint64> &mapper, const std::vector<cytnx_uint64> &invmapper){ cytnx_error_msg(1,"%s","[ERROR] call Move_memory_ directly on Void Storage."); } boost::intrusive_ptr<Storage_base> Storage_base::Move_memory(const std::vector<cytnx_uint64> &old_shape, const std::vector<cytnx_uint64> &mapper, const std::vector<cytnx_uint64> &invmapper){ cytnx_error_msg(1,"%s","[ERROR] call Move_memory_ directly on Void Storage."); return nullptr; } void Storage_base::to_(const int &device){ cytnx_error_msg(1,"%s","[ERROR] call to_ directly on Void Storage."); } boost::intrusive_ptr<Storage_base> Storage_base::to(const int &device){ cytnx_error_msg(1,"%s","[ERROR] call to directly on Void Storage."); return nullptr; } void Storage_base::PrintElem_byShape(std::ostream &os, const std::vector<cytnx_uint64> &shape, const std::vector<cytnx_uint64> &mapper){ cytnx_error_msg(1,"%s","[ERROR] call PrintElem_byShape directly on Void Storage."); } void Storage_base::print_info(){ cout << "dtype : " << this->dtype_str() << endl; cout << "device: " << Device.getname(this->device) << endl; cout << "size : " << this->len << endl; } void Storage_base::print_elems(){ cytnx_error_msg(1,"%s","[ERROR] call print_elems directly on Void Storage."); } void Storage_base::print(){ this->print_info(); this->print_elems(); } // shadow new: // [0] shape: shape of current TN // [x] direct feed-in accessor? accessor->.next() to get next index? no // we dont need mapper's information! // if len(locators) < shape.size(), it means last shape.size()-len(locators) axes are grouped. void Storage_base::GetElem_byShape_v2(boost::intrusive_ptr<Storage_base> &out, const std::vector<cytnx_uint64> &shape, const std::vector<std::vector<cytnx_uint64> > &locators,const cytnx_uint64 &Nunit){ #ifdef UNI_DEBUG cytnx_error_msg(out->dtype != this->dtype, "%s","[ERROR][DEBUG] %s","internal, the output dtype does not match current storage dtype.\n"); #endif cytnx_uint64 TotalElem = 1; for(cytnx_uint32 i=0;i<locators.size();i++){ if(locators[i].size()) TotalElem*=locators[i].size(); else //axis get all! TotalElem*=shape[i]; } //cytnx_error_msg(out->size() != TotalElem, "%s", "[ERROR] internal, the out Storage size does not match the no. of elems calculated from Accessors.%s","\n"); std::vector<cytnx_uint64> c_offj(locators.size()); std::vector<cytnx_uint64> new_offj(locators.size()); cytnx_uint64 caccu=1,new_accu=1; for(cytnx_int32 i=locators.size()-1;i>=0;i--){ c_offj[i] = caccu; caccu*=shape[i]; new_offj[i] = new_accu; if(locators[i].size()) new_accu*=locators[i].size(); else new_accu*=shape[i]; } //std::cout << c_offj << std::endl; //std::cout << new_offj << std::endl; //std::cout << TotalElem << std::endl; if(this->device == Device.cpu){ utils_internal::uii.GetElems_conti_ii[this->dtype](out->Mem,this->Mem,c_offj,new_offj,locators,TotalElem,Nunit); }else{ #ifdef UNI_GPU checkCudaErrors(cudaSetDevice(this->device)); cytnx_error_msg(true,"[Developing][GPU Getelem v2][Note, currently slice on GPU is disabled for further inspection]%s","\n"); //utils_internal::uii.cuGetElems_contiguous_ii[this->dtype](out->Mem,this->Mem,c_offj,new_offj,locators,TotalElem,Nunit); #else cytnx_error_msg(true,"[ERROR][GetElem_byShape] fatal internal%s","the Storage is set on gpu without CUDA support\n"); #endif } } void Storage_base::GetElem_byShape(boost::intrusive_ptr<Storage_base> &out, const std::vector<cytnx_uint64> &shape, const std::vector<cytnx_uint64> &mapper, const std::vector<cytnx_uint64> &len, const std::vector<std::vector<cytnx_uint64> > &locators){ #ifdef UNI_DEBUG cytnx_error_msg(shape.size() != len.size(),"%s","[ERROR][DEBUG] internal Storage, shape.size() != len.size()"); cytnx_error_msg(out->dtype != this->dtype, "%s","[ERROR][DEBUG] %s","internal, the output dtype does not match current storage dtype.\n"); #endif //std::cout <<"=====" << len.size() << " " << locators.size() << std::endl; //create new instance: cytnx_uint64 TotalElem = 1; for(cytnx_uint32 i=0;i<len.size();i++) TotalElem*=len[i]; cytnx_error_msg(out->size() != TotalElem, "%s", "[ERROR] internal, the out Storage size does not match the no. of elems calculated from Accessors.%s","\n"); std::vector<cytnx_uint64> c_offj(shape.size()); std::vector<cytnx_uint64> new_offj(shape.size()); std::vector<cytnx_uint64> offj(shape.size()); cytnx_uint64 accu=1; for(cytnx_int32 i=shape.size()-1;i>=0;i--){ c_offj[i] = accu; accu*=shape[mapper[i]]; } accu = 1; for(cytnx_int32 i=len.size()-1;i>=0;i--){ new_offj[i] = accu; accu*=len[i]; //count-in the mapper: offj[i] = c_offj[mapper[i]]; } if(this->device == Device.cpu){ utils_internal::uii.GetElems_ii[this->dtype](out->Mem,this->Mem,offj,new_offj,locators,TotalElem); }else{ #ifdef UNI_GPU checkCudaErrors(cudaSetDevice(this->device)); utils_internal::uii.cuGetElems_ii[this->dtype](out->Mem,this->Mem,offj,new_offj,locators,TotalElem); #else cytnx_error_msg(true,"[ERROR][GetElem_byShape] fatal internal%s","the Storage is set on gpu without CUDA support\n"); #endif } } // This is deprecated !! void Storage_base::SetElem_byShape(boost::intrusive_ptr<Storage_base> &in, const std::vector<cytnx_uint64> &shape, const std::vector<cytnx_uint64> &mapper, const std::vector<cytnx_uint64> &len, const std::vector<std::vector<cytnx_uint64> > &locators, const bool &is_scalar){ #ifdef UNI_DEBUG cytnx_error_msg(shape.size() != len.size(),"%s","[ERROR][DEBUG] internal Storage, shape.size() != len.size()"); #endif //std::cout <<"=====" << len.size() << " " << locators.size() << std::endl; //create new instance: cytnx_uint64 TotalElem = 1; for(cytnx_uint32 i=0;i<len.size();i++) TotalElem*=len[i]; if(!is_scalar) cytnx_error_msg(in->size() != TotalElem, "%s", "[ERROR] internal, the out Storage size does not match the no. of elems calculated from Accessors.%s","\n"); //[warning] this version only work for scalar currently!. std::vector<cytnx_uint64> c_offj(shape.size()); std::vector<cytnx_uint64> new_offj(shape.size()); std::vector<cytnx_uint64> offj(shape.size()); cytnx_uint64 accu=1; for(cytnx_int32 i=shape.size()-1;i>=0;i--){ c_offj[i] = accu; accu*=shape[i]; } accu = 1; for(cytnx_int32 i=len.size()-1;i>=0;i--){ new_offj[i] = accu; accu*=len[i]; //count-in the mapper: offj[i] = c_offj[mapper[i]]; } if(this->device == Device.cpu){ if(utils_internal::uii.SetElems_ii[in->dtype][this->dtype] == NULL){ cytnx_error_msg(true, "[ERROR] %s","cannot assign complex element to real container.\n"); } utils_internal::uii.SetElems_ii[in->dtype][this->dtype](in->Mem,this->Mem,c_offj,new_offj,locators,TotalElem,is_scalar); }else{ #ifdef UNI_GPU if(utils_internal::uii.cuSetElems_ii[in->dtype][this->dtype] == NULL){ cytnx_error_msg(true, "%s","[ERROR] %s","cannot assign complex element to real container.\n"); } checkCudaErrors(cudaSetDevice(this->device)); utils_internal::uii.cuSetElems_ii[in->dtype][this->dtype](in->Mem,this->Mem,offj,new_offj,locators,TotalElem,is_scalar); #else cytnx_error_msg(true,"[ERROR][SetElem_byShape] fatal internal%s","the Storage is set on gpu without CUDA support\n"); #endif } } void Storage_base::SetElem_byShape_v2(boost::intrusive_ptr<Storage_base> &in, const std::vector<cytnx_uint64> &shape, const std::vector<std::vector<cytnx_uint64> > &locators,const cytnx_uint64 &Nunit, const bool &is_scalar){ // plan: we assume in is contiguous for now! // //std::cout <<"=====" << len.size() << " " << locators.size() << std::endl; //create new instance: cytnx_uint64 TotalElem = 1; for(cytnx_uint32 i=0;i<locators.size();i++){ if(locators[i].size()) TotalElem*=locators[i].size(); else //axis get all! TotalElem*=shape[i]; } //if(!is_scalar) // cytnx_error_msg(in->size() != TotalElem, "%s", "[ERROR] internal, the out Storage size does not match the no. of elems calculated from Accessors.%s","\n"); //[warning] this version only work for scalar currently!. std::vector<cytnx_uint64> c_offj(locators.size()); std::vector<cytnx_uint64> new_offj(locators.size()); cytnx_uint64 caccu=1,new_accu=1; for(cytnx_int32 i=locators.size()-1;i>=0;i--){ c_offj[i] = caccu; caccu*=shape[i]; new_offj[i] = new_accu; if(locators[i].size()) new_accu*=locators[i].size(); else new_accu*=shape[i]; } if(this->device == Device.cpu){ if(utils_internal::uii.SetElems_conti_ii[in->dtype][this->dtype] == NULL){ cytnx_error_msg(true, "[ERROR] %s","cannot assign complex element to real container.\n"); } utils_internal::uii.SetElems_conti_ii[in->dtype][this->dtype](in->Mem,this->Mem,c_offj,new_offj,locators,TotalElem,Nunit,is_scalar); }else{ #ifdef UNI_GPU //if(utils_internal::uii.cuSetElems_ii[in->dtype][this->dtype] == NULL){ // cytnx_error_msg(true, "%s","[ERROR] %s","cannot assign complex element to real container.\n"); //} //checkCudaErrors(cudaSetDevice(this->device)); //utils_internal::uii.cuSetElems_conti_ii[in->dtype][this->dtype](in->Mem,this->Mem,offj,new_offj,locators,TotalElem,Nunit,is_scalar); cytnx_error_msg(true,"[Developing][SetElem on gpu is now down for further inspection]%s","\n"); #else cytnx_error_msg(true,"[ERROR][SetElem_byShape] fatal internal%s","the Storage is set on gpu without CUDA support\n"); #endif } } //generators: void Storage_base::fill(const cytnx_complex128 &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_complex64 &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_double &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_float &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_int64 &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_uint64 &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_int32 &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_uint32 &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_int16 &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_uint16 &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::fill(const cytnx_bool &val){ cytnx_error_msg(1,"%s","[ERROR] call fill directly on Void Storage."); } void Storage_base::set_zeros(){ cytnx_error_msg(1,"%s","[ERROR] call set_zeros directly on Void Storage."); } void Storage_base::append(const cytnx_complex128 &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_complex64 &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_double &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_float &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_int64 &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_uint64 &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_int32 &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_uint32 &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_int16 &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_uint16 &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } void Storage_base::append(const cytnx_bool &val){ cytnx_error_msg(1,"%s","[ERROR] call append directly on Void Storage."); } //instantiation: //================================================ template<> float* Storage_base::data<float>()const{ //check type cytnx_error_msg(dtype != Type.Float, "[ERROR] type mismatch. try to get <float> type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<float*>(this->Mem); } template<> double* Storage_base::data<double>()const{ cytnx_error_msg(dtype != Type.Double, "[ERROR] type mismatch. try to get <double> type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<double*>(this->Mem); } template<> std::complex<double>* Storage_base::data<std::complex<double> >()const{ cytnx_error_msg(dtype != Type.ComplexDouble, "[ERROR] type mismatch. try to get < complex<double> > type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cytnx_error_msg(this->device!=Device.cpu, "%s","[ERROR] the Storage is on GPU but try to get with CUDA complex type complex<double>. use type <cuDoubleComplex> instead."); cudaDeviceSynchronize(); #endif return static_cast<std::complex<double>*>(this->Mem); } template<> std::complex<float>* Storage_base::data<std::complex<float> >()const{ cytnx_error_msg(dtype != Type.ComplexFloat, "[ERROR] type mismatch. try to get < complex<float> > type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cytnx_error_msg(this->device!=Device.cpu, "%s","[ERROR] the Storage is on GPU but try to get with CUDA complex type complex<float>. use type <cuFloatComplex> instead."); cudaDeviceSynchronize(); #endif return static_cast<std::complex<float>*>(this->Mem); } template<> uint32_t* Storage_base::data<uint32_t>()const{ cytnx_error_msg(dtype != Type.Uint32, "[ERROR] type mismatch. try to get <uint32_t> type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<uint32_t*>(this->Mem); } template<> int32_t* Storage_base::data<int32_t>()const{ cytnx_error_msg(dtype != Type.Int32, "[ERROR] type mismatch. try to get <int32_t> type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<int32_t*>(this->Mem); } template<> uint64_t* Storage_base::data<uint64_t>()const{ cytnx_error_msg(dtype != Type.Uint64, "[ERROR] type mismatch. try to get <uint64_t> type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<uint64_t*>(this->Mem); } template<> int64_t* Storage_base::data<int64_t>()const{ cytnx_error_msg(dtype != Type.Int64, "[ERROR] type mismatch. try to get <int64_t> type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<int64_t*>(this->Mem); } template<> int16_t* Storage_base::data<int16_t>()const{ cytnx_error_msg(dtype != Type.Int16, "[ERROR] type mismatch. try to get <int16_t> type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<int16_t*>(this->Mem); } template<> uint16_t* Storage_base::data<uint16_t>()const{ cytnx_error_msg(dtype != Type.Uint16, "[ERROR] type mismatch. try to get <uint16_t> type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<uint16_t*>(this->Mem); } template<> bool* Storage_base::data<bool>()const{ cytnx_error_msg(dtype != Type.Bool, "[ERROR] type mismatch. try to get <bool> type from raw data of type %s", Type.getname(dtype).c_str()); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<bool*>(this->Mem); } // get complex raw pointer using CUDA complex type #ifdef UNI_GPU template<> cuDoubleComplex* Storage_base::data<cuDoubleComplex>()const{ cytnx_error_msg(dtype != Type.ComplexDouble, "[ERROR] type mismatch. try to get <cuDoubleComplex> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->device==Device.cpu, "%s","[ERROR] the Storage is on CPU(Host) but try to get with CUDA complex type cuDoubleComplex. use type <cytnx_complex128> or < complex<double> > instead."); cudaDeviceSynchronize(); return static_cast<cuDoubleComplex*>(this->Mem); } template<> cuFloatComplex* Storage_base::data<cuFloatComplex>()const{ cytnx_error_msg(dtype != Type.ComplexFloat, "[ERROR] type mismatch. try to get <cuFloatComplex> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->device==Device.cpu, "%s","[ERROR] the Storage is on CPU(Host) but try to get with CUDA complex type cuFloatComplex. use type <cytnx_complex64> or < complex<float> > instead."); cudaDeviceSynchronize(); return static_cast<cuFloatComplex*>(this->Mem); } #endif //instantiation: //==================================================== template<> float& Storage_base::at<float>(const cytnx_uint64 &idx) const{ cytnx_error_msg(dtype != Type.Float, "[ERROR] type mismatch. try to get <float> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<float*>(this->Mem)[idx]; } template<> double& Storage_base::at<double>(const cytnx_uint64 &idx)const{ cytnx_error_msg(dtype != Type.Double, "[ERROR] type mismatch. try to get <double> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<double*>(this->Mem)[idx]; } template<> std::complex<float>& Storage_base::at<std::complex<float> >(const cytnx_uint64 &idx)const{ cytnx_error_msg(dtype != Type.ComplexFloat, "[ERROR] type mismatch. try to get < complex<float> > type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<complex<float>*>(this->Mem)[idx]; } template<> std::complex<double>& Storage_base::at<std::complex<double> >(const cytnx_uint64 &idx)const{ cytnx_error_msg(dtype != Type.ComplexDouble, "[ERROR] type mismatch. try to get < complex<double> > type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<complex<double>*>(this->Mem)[idx]; } template<> uint32_t& Storage_base::at<uint32_t>(const cytnx_uint64 &idx)const{ cytnx_error_msg(dtype != Type.Uint32, "[ERROR] type mismatch. try to get <uint32_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<uint32_t*>(this->Mem)[idx]; } template<> int32_t& Storage_base::at<int32_t>(const cytnx_uint64 &idx)const{ cytnx_error_msg(dtype != Type.Int32, "[ERROR] type mismatch. try to get <int32_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<int32_t*>(this->Mem)[idx]; } template<> uint64_t& Storage_base::at<uint64_t>(const cytnx_uint64 &idx) const{ cytnx_error_msg(dtype != Type.Uint64, "[ERROR] type mismatch. try to get <uint64_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<uint64_t*>(this->Mem)[idx]; } template<> int64_t& Storage_base::at<int64_t>(const cytnx_uint64 &idx)const{ cytnx_error_msg(dtype != Type.Int64, "[ERROR] type mismatch. try to get <int64_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<int64_t*>(this->Mem)[idx]; } template<> uint16_t& Storage_base::at<uint16_t>(const cytnx_uint64 &idx)const{ cytnx_error_msg(dtype != Type.Uint16, "[ERROR] type mismatch. try to get <uint16_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<uint16_t*>(this->Mem)[idx]; } template<> int16_t& Storage_base::at<int16_t>(const cytnx_uint64 &idx)const{ cytnx_error_msg(dtype != Type.Int16, "[ERROR] type mismatch. try to get <int16_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<int16_t*>(this->Mem)[idx]; } template<> bool& Storage_base::at<bool>(const cytnx_uint64 &idx)const{ cytnx_error_msg(dtype != Type.Bool, "[ERROR] type mismatch. try to get <bool> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(idx>=this->len, "[ERROR] index [%d] out of bound [%d]\n",idx,this->len); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<bool*>(this->Mem)[idx]; } //instantiation: //==================================================== template<> float& Storage_base::back<float>() const{ cytnx_error_msg(dtype != Type.Float, "[ERROR] type mismatch. try to get <float> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<float*>(this->Mem)[this->len-1]; } template<> double& Storage_base::back<double>()const{ cytnx_error_msg(dtype != Type.Double, "[ERROR] type mismatch. try to get <double> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<double*>(this->Mem)[this->len-1]; } template<> std::complex<float>& Storage_base::back<std::complex<float> >()const{ cytnx_error_msg(dtype != Type.ComplexFloat, "[ERROR] type mismatch. try to get < complex<float> > type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<complex<float>*>(this->Mem)[this->len-1]; } template<> std::complex<double>& Storage_base::back<std::complex<double> >()const{ cytnx_error_msg(dtype != Type.ComplexDouble, "[ERROR] type mismatch. try to get < complex<double> > type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<complex<double>*>(this->Mem)[this->len-1]; } template<> uint32_t& Storage_base::back<uint32_t>()const{ cytnx_error_msg(dtype != Type.Uint32, "[ERROR] type mismatch. try to get <uint32_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<uint32_t*>(this->Mem)[this->len-1]; } template<> int32_t& Storage_base::back<int32_t>()const{ cytnx_error_msg(dtype != Type.Int32, "[ERROR] type mismatch. try to get <int32_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<int32_t*>(this->Mem)[this->len-1]; } template<> uint64_t& Storage_base::back<uint64_t>() const{ cytnx_error_msg(dtype != Type.Uint64, "[ERROR] type mismatch. try to get <uint64_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<uint64_t*>(this->Mem)[this->len-1]; } template<> int64_t& Storage_base::back<int64_t>()const{ cytnx_error_msg(dtype != Type.Int64, "[ERROR] type mismatch. try to get <int64_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<int64_t*>(this->Mem)[this->len-1]; } template<> uint16_t& Storage_base::back<uint16_t>()const{ cytnx_error_msg(dtype != Type.Uint16, "[ERROR] type mismatch. try to get <uint16_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<uint16_t*>(this->Mem)[this->len-1]; } template<> int16_t& Storage_base::back<int16_t>()const{ cytnx_error_msg(dtype != Type.Int16, "[ERROR] type mismatch. try to get <int16_t> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<int16_t*>(this->Mem)[this->len-1]; } template<> bool& Storage_base::back<bool>()const{ cytnx_error_msg(dtype != Type.Bool, "[ERROR] type mismatch. try to get <bool> type from raw data of type %s", Type.getname(dtype).c_str()); cytnx_error_msg(this->len==0,"[ERROR] cannot call back on empty stoarge.%s","\n"); #ifdef UNI_GPU cudaDeviceSynchronize(); #endif return static_cast<bool*>(this->Mem)[this->len-1]; } void Storage_base::_cpy_bool(void *ptr, const std::vector<cytnx_bool> &vin){ bool *tmp = static_cast<bool*>(ptr); #ifdef UNI_OMP #pragma omp parallel for schedule(dynamic) #endif for(cytnx_uint64 i=0;i<vin.size();i++){ tmp[i] = vin[i]; } } boost::intrusive_ptr<Storage_base> Storage_base::real(){ cytnx_error_msg(true,"[ERROR] trying to call Storage.real() from void Storage%s","\n"); } boost::intrusive_ptr<Storage_base> Storage_base::imag(){ cytnx_error_msg(true,"[ERROR] trying to call Storage.imag() from void Storage%s","\n"); } Scalar Storage_base::get_item(const cytnx_uint64 &idx) const{ cytnx_error_msg(true,"[ERROR] trying to call Storage.get_item() from void Storage%s","\n"); return Scalar(); } void Storage_base::set_item(const cytnx_uint64 &idx,const Scalar &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_complex128 &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_complex64 &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_double &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_float &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_int64 &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_uint64 &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_int32 &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_uint32 &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_int16 &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_uint16 &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } void Storage_base::set_item(const cytnx_uint64 &idx,const cytnx_bool &val){ cytnx_error_msg(true,"[ERROR] trying to call Storage.set_item() from void Storage%s","\n"); } }//namespace cytnx;
43.565027
278
0.6086
yingjerkao
16fafdd8af96e9317de9b4a6cf6798a73b43c408
7,601
cpp
C++
tree.cpp
ramenhut/simple-rdf
ca6f9fb52dfa2fb464a0593ce71972d263dfd92c
[ "BSD-2-Clause" ]
3
2019-08-18T05:44:42.000Z
2019-09-02T06:19:30.000Z
tree.cpp
ramenhut/simple-rdf
ca6f9fb52dfa2fb464a0593ce71972d263dfd92c
[ "BSD-2-Clause" ]
null
null
null
tree.cpp
ramenhut/simple-rdf
ca6f9fb52dfa2fb464a0593ce71972d263dfd92c
[ "BSD-2-Clause" ]
null
null
null
#include "tree.h" #include "numeric.h" namespace base { float32 ComputeInformationGain(const Histogram& parent, const Histogram& left, const Histogram& right) { // Our computations use integer variables but must occur at float precision. float32 parent_total = parent.GetSampleTotal(); return parent.GetEntropy() - (((left.GetSampleTotal() / parent_total) * (left.GetEntropy())) + ((right.GetSampleTotal() / parent_total) * (right.GetEntropy()))); } bool DecisionNode::Train(const DecisionTreeParams& params, uint32 depth, vector<TrainSet>* samples, const Histogram& sample_histogram, string* error) { if (!samples) { if (error) { *error = "Invalid parameter(s) specified to DecisionNode::Train."; } return false; } // Cache our incoming histogram, which defines the statitics at the // current node. This is useful during training, and potentially useful // for classification if the current node ends up being a leaf. histogram_ = sample_histogram; // If we've reached our exit criteria then we early exit, leaving this // node as a leaf in the tree. if (depth >= params.max_tree_depth || !samples->size() || samples->size() < params.min_sample_count) { is_leaf_ = true; return true; } float32 node_entropy = histogram_.GetEntropy(); // If our incoming entropy is zero then our data set is of uniform // type, and we can declare this node a leaf. if (0.0f == node_entropy || -0.0f == node_entropy) { is_leaf_ = true; return true; } // Perform a maximum of params.node_trial_count trials to find // a best candidate split function for this node. We're guaranteed // to finish with a candidate, even if it's only a local best. float32 best_info_gain = -1.0f; Histogram best_left_hist, best_right_hist; vector<TrainSet> best_left_samples, best_right_samples; SplitFunction best_split_function, trial_split_function; for (uint32 i = 0; i < params.node_trial_count; i++) { Histogram trial_left_hist, trial_right_hist; vector<TrainSet> trial_left_samples, trial_right_samples; trial_left_hist.Initialize(params.class_count); trial_right_hist.Initialize(params.class_count); trial_left_samples.reserve(samples->size()); trial_right_samples.reserve(samples->size()); trial_split_function.Initialize(params.visual_search_radius); // Iterate over all samples, performing split. True goes right. for (uint32 j = 0; j < samples->size(); j++) { SplitCoord current_coord = samples->at(j).coord; uint8 sample_label = samples->at(j).data_source->label.GetPixel( current_coord.x, current_coord.y); if (trial_split_function.Split(current_coord, &samples->at(j).data_source->image)) { trial_right_samples.push_back(samples->at(j)); trial_right_hist.IncrementValue(sample_label); } else { trial_left_samples.push_back(samples->at(j)); trial_left_hist.IncrementValue(sample_label); } } float32 current_info_gain = ComputeInformationGain(histogram_, trial_left_hist, trial_right_hist); if (current_info_gain >= best_info_gain) { best_info_gain = current_info_gain; best_left_hist = trial_left_hist; best_right_hist = trial_right_hist; best_left_samples = std::move(trial_left_samples); best_right_samples = std::move(trial_right_samples); best_split_function = trial_split_function; // If our current info gain equals entropy (i.e. both buckets have zero // entropy), then we can immediately select this as our best option. if (current_info_gain == node_entropy) { break; } } } // Bind the best split function that we found during our trials. function_ = best_split_function; is_leaf_ = false; // We have our best so we allocate children and attempt to train them. left_child_.reset(new DecisionNode); right_child_.reset(new DecisionNode); if (!left_child_ || !right_child_) { if (error) { *error = "Failed to allocate child nodes."; } return false; } if (!left_child_->Train(params, depth + 1, &best_left_samples, best_left_hist, error) || !right_child_->Train(params, depth + 1, &best_right_samples, best_right_hist, error)) { return false; } return true; } bool DecisionNode::Classify(const SplitCoord& coord, Image* data_source, Histogram* output, string* error) { if ((!!left_child_) ^ (!!right_child_)) { if (error) { *error = "Invalid tree structure."; } return false; } if (!output || !data_source) { if (error) { *error = "Invalid parameter specified to DecisionNode::Classify."; } return false; } if (is_leaf_) { *output = histogram_; return true; } if (function_.Split(coord, data_source)) { return right_child_->Classify(coord, data_source, output); } return left_child_->Classify(coord, data_source, output); } bool DecisionTree::Train(const DecisionTreeParams& params, vector<ImageSet>* training_data, uint32 training_start_index, uint32 training_count, string* error) { if (training_data->empty() || training_count > training_data->size()) { if (error) { *error = "Invalid parameter specified to DecisionTree::Train."; } return false; } Histogram initial_histogram(params.class_count); vector<TrainSet> tree_training_set; // Cache a copy of our tree params for later use during classification. params_ = params; // This is one of the most expensive operations in our system, so we // estimate the required size and reserve memory for it. uint64 required_size = training_count * training_data->at(0).image.width * training_data->at(0).image.height; tree_training_set.reserve(required_size); for (uint32 i = 0; i < training_count; i++) { uint32 index = (training_start_index + i) % training_data->size(); uint32 width = training_data->at(index).image.width; uint32 height = training_data->at(index).image.height; for (uint32 y = 0; y < height; y++) for (uint32 x = 0; x < width; x++) { uint8 label_value = training_data->at(index).label.GetPixel(x, y); tree_training_set.emplace_back(&training_data->at(index), x, y); initial_histogram.IncrementValue(label_value); } } root_node_.reset(new DecisionNode); if (!root_node_) { if (error) { *error = "Failed allocation of decision tree root node."; } return false; } return root_node_->Train(params, 0, &tree_training_set, initial_histogram); } bool DecisionTree::ClassifyPixel(uint32 x, uint32 y, Image* input, Histogram* output, string* error) { if (!root_node_) { if (error) { *error = "Invalid root node detected."; } return false; } if (!input || !output) { if (error) { *error = "Invalid parameter specified to DecisionTree::ClassifyPixel."; } return false; } SplitCoord coord = {x, y}; return root_node_->Classify(coord, input, output, error); } } // namespace base
34.238739
81
0.641626
ramenhut
16ff5d447c95848b705b662b1f7c97b55baa1678
2,839
cpp
C++
LightOJ/LOJ_AC/1093 - Ghajini .cpp
Saikat-S/acm-problems-solutions
921c0f3e508e1ee8cd14be867587952d5f67bbb9
[ "MIT" ]
3
2018-05-11T07:33:20.000Z
2020-08-30T11:02:02.000Z
LightOJ/LOJ_AC/1093 - Ghajini .cpp
Saikat-S/acm-problems-solutions
921c0f3e508e1ee8cd14be867587952d5f67bbb9
[ "MIT" ]
1
2018-05-11T18:10:26.000Z
2018-05-12T18:00:28.000Z
LightOJ/LOJ_AC/1093 - Ghajini .cpp
Saikat-S/acm-problems-solutions
921c0f3e508e1ee8cd14be867587952d5f67bbb9
[ "MIT" ]
null
null
null
/*************************************************** * Problem name : 1093 - Ghajini .cpp * Problem Link : http://lightoj.com/volume_showproblem.php?problem=1093 * OJ : LOJ * Verdict : AC * Date : 19.05.2017 * Problem Type : * Author Name : Saikat Sharma * University : CSE, MBSTU ***************************************************/ #include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<string> #include<sstream> #include<cmath> #include<vector> #include<queue> #include<stack> #include<map> #include<set> #define __FastIO ios_base::sync_with_stdio(false); cin.tie(0) #define SET(a) memset(a,-1,sizeof(a)) #define pii pair<int,int> #define debug printf("#########\n") #define nl printf("\n") #define MAX 100005 using namespace std; typedef long long ll; ll ar[MAX],ar_max[MAX]; ll st[MAX][16], st_max[MAX][16]; void build_st(ll n) { for (int i = 0; i < n; i++) st[i][0] = i; for (int j = 1; j <= 1 << j; j++) { for (int i = 0; i <= n - (1 << j); i++) { ll x = st[i][j - 1]; ll y = st[i + (1 << (j - 1))][j - 1]; if (ar[x] <= ar[y]) st[i][j] = x; else st[i][j] = y; } } } int query(ll lb, ll ub) { ll cnt = ub - lb + 1; ll k = log2(cnt); ll x = st[lb][k]; ll y = st[ub - (1 << k) + 1][k]; if (ar[x] <= ar[y]) return x; else return y; } void build_st_max(ll n) { for (int i = 0; i < n; i++) st_max[i][0] = i; for (int j = 1; j <= 1 << j; j++) { for (int i = 0; i <= n - (1 << j); i++) { ll x = st_max[i][j - 1]; ll y = st_max[i + (1 << (j - 1))][j - 1]; if (ar_max[x] >= ar_max[y]) st_max[i][j] = x; else st_max[i][j] = y; } } } int query_max(ll lb, ll ub) { ll cnt = ub - lb + 1; ll k = log2(cnt); ll x = st_max[lb][k]; ll y = st_max[ub - (1 << k) + 1][k]; if (ar_max[x] >= ar_max[y]) return x; else return y; } int main () { int tc; ll n, d; scanf("%d", &tc); for (int t = 1; t <= tc; t++) { scanf("%lld %lld", &n, &d); for (int i = 0; i < n; i++) { scanf("%lld", &ar[i]); ar_max[i] = ar[i]; } build_st(n); build_st_max(n); ll mx = 0; for (int i = 0; i < n; i++) { ll x, y; x = i; y = (x + d) - 1; if(y>=n){ break; } ll m = ar_max[query_max(x,y)]; ll s = ar[query(x, y)]; //~ printf("%lld %lld\n", m,s); ll ans = m - s; mx = max(mx,ans); } printf("Case %d: %lld\n",t,mx); } return 0; }
27.833333
95
0.408242
Saikat-S
e5054599457e0656b4c7ef8ba221feaef6d81690
7,404
cpp
C++
ROS/topico/src/printint.cpp
zal-jlange/TopiCo
d9cf99d4510599c2fc506cbe866cdb8861f360c8
[ "BSD-3-Clause" ]
53
2021-03-16T09:55:42.000Z
2022-02-15T22:10:44.000Z
ROS/topico/src/printint.cpp
zal-jlange/TopiCo
d9cf99d4510599c2fc506cbe866cdb8861f360c8
[ "BSD-3-Clause" ]
14
2021-03-23T17:52:12.000Z
2021-08-17T01:00:32.000Z
ROS/topico/src/printint.cpp
zal-jlange/TopiCo
d9cf99d4510599c2fc506cbe866cdb8861f360c8
[ "BSD-3-Clause" ]
14
2021-04-11T06:12:24.000Z
2022-03-22T12:21:51.000Z
// // Academic License - for use in teaching, academic research, and meeting // course requirements at degree granting institutions only. Not for // government, commercial, or other organizational use. // // printint.cpp // // Code generation for function 'printint' // // Include files #include "printint.h" #include "i64ddiv.h" #include "rt_nonfinite.h" #include "topico_wrapper_data.h" #include "topico_wrapper_rtwutil.h" #include "topico_wrapper_types.h" #include <cmath> #include <sstream> #include <stdexcept> #include <stdio.h> #include <string> // Function Declarations static unsigned long _u64_d_(double b); static unsigned long _u64_div__(unsigned long b, unsigned long c); static unsigned long _u64_minus__(unsigned long b, unsigned long c); static unsigned long _u64_s32_(int b); static void mul_wide_u64(unsigned long in0, unsigned long in1, unsigned long *ptrOutBitsHi, unsigned long *ptrOutBitsLo); static unsigned long mulv_u64(unsigned long a, unsigned long b); static void rtDivisionByZeroErrorN(); // Function Definitions static unsigned long _u64_d_(double b) { unsigned long a; a = static_cast<unsigned long>(b); if ((b < 0.0) || (a != std::floor(b))) { rtIntegerOverflowErrorN(); } return a; } static unsigned long _u64_div__(unsigned long b, unsigned long c) { if (c == 0UL) { rtDivisionByZeroErrorN(); } return b / c; } static unsigned long _u64_minus__(unsigned long b, unsigned long c) { unsigned long a; a = b - c; if (b < c) { rtIntegerOverflowErrorN(); } return a; } static unsigned long _u64_s32_(int b) { unsigned long a; a = static_cast<unsigned long>(b); if (b < 0) { rtIntegerOverflowErrorN(); } return a; } static void mul_wide_u64(unsigned long in0, unsigned long in1, unsigned long *ptrOutBitsHi, unsigned long *ptrOutBitsLo) { unsigned long in0Hi; unsigned long in0Lo; unsigned long in1Hi; unsigned long in1Lo; unsigned long outBitsLo; unsigned long productHiLo; unsigned long productLoHi; in0Hi = in0 >> 32UL; in0Lo = in0 & 4294967295UL; in1Hi = in1 >> 32UL; in1Lo = in1 & 4294967295UL; productHiLo = in0Hi * in1Lo; productLoHi = in0Lo * in1Hi; in0Lo *= in1Lo; in1Lo = 0UL; outBitsLo = in0Lo + (productLoHi << 32UL); if (outBitsLo < in0Lo) { in1Lo = 1UL; } in0Lo = outBitsLo; outBitsLo += productHiLo << 32UL; if (outBitsLo < in0Lo) { in1Lo++; } *ptrOutBitsHi = ((in1Lo + in0Hi * in1Hi) + (productLoHi >> 32UL)) + (productHiLo >> 32UL); *ptrOutBitsLo = outBitsLo; } static unsigned long mulv_u64(unsigned long a, unsigned long b) { unsigned long result; unsigned long u64_chi; mul_wide_u64(a, b, &u64_chi, &result); if (u64_chi) { rtIntegerOverflowErrorN(); } return result; } static void rtDivisionByZeroErrorN() { std::stringstream outStream; outStream << "Division by zero detected.\nEarly termination due to division " "by zero."; outStream << "\n"; throw std::runtime_error(outStream.str()); } void printint(unsigned int number) { unsigned long b_number; unsigned long divisor; bool b_leading; b_number = number; b_leading = true; divisor = 10000000000000000000UL; while (divisor >= 1UL) { unsigned long d; if (divisor == 0UL) { d_rtErrorWithMessageID(f_emlrtRTEI.fName, f_emlrtRTEI.lineNo); } d = _u64_div__(b_number, divisor); b_leading = ((d == 0UL) && b_leading); if (!b_leading) { b_number = _u64_minus__(b_number, mulv_u64(d, divisor)); switch (d) { case 0UL: printf("0"); fflush(stdout); break; case 1UL: printf("1"); fflush(stdout); break; case 2UL: printf("2"); fflush(stdout); break; case 3UL: printf("3"); fflush(stdout); break; case 4UL: printf("4"); fflush(stdout); break; case 5UL: printf("5"); fflush(stdout); break; case 6UL: printf("6"); fflush(stdout); break; case 7UL: printf("7"); fflush(stdout); break; case 8UL: printf("8"); fflush(stdout); break; case 9UL: printf("9"); fflush(stdout); break; } } divisor = coder::internal::i64ddiv(divisor); } if (b_leading) { printf("0"); fflush(stdout); } } void printint(int number) { unsigned long b_number; unsigned long divisor; bool b_leading; b_number = _u64_s32_(number); b_leading = true; divisor = 10000000000000000000UL; while (divisor >= 1UL) { unsigned long d; if (divisor == 0UL) { d_rtErrorWithMessageID(f_emlrtRTEI.fName, f_emlrtRTEI.lineNo); } d = _u64_div__(b_number, divisor); b_leading = ((d == 0UL) && b_leading); if (!b_leading) { b_number = _u64_minus__(b_number, mulv_u64(d, divisor)); switch (d) { case 0UL: printf("0"); fflush(stdout); break; case 1UL: printf("1"); fflush(stdout); break; case 2UL: printf("2"); fflush(stdout); break; case 3UL: printf("3"); fflush(stdout); break; case 4UL: printf("4"); fflush(stdout); break; case 5UL: printf("5"); fflush(stdout); break; case 6UL: printf("6"); fflush(stdout); break; case 7UL: printf("7"); fflush(stdout); break; case 8UL: printf("8"); fflush(stdout); break; case 9UL: printf("9"); fflush(stdout); break; } } divisor = coder::internal::i64ddiv(divisor); } if (b_leading) { printf("0"); fflush(stdout); } } void printint(double number) { unsigned long b_number; unsigned long divisor; bool b_leading; b_number = _u64_d_(rt_roundd_snf(std::abs(number))); b_leading = true; divisor = 10000000000000000000UL; while (divisor >= 1UL) { unsigned long d; if (divisor == 0UL) { d_rtErrorWithMessageID(f_emlrtRTEI.fName, f_emlrtRTEI.lineNo); } d = _u64_div__(b_number, divisor); b_leading = ((d == 0UL) && b_leading); if (!b_leading) { b_number = _u64_minus__(b_number, mulv_u64(d, divisor)); switch (d) { case 0UL: printf("0"); fflush(stdout); break; case 1UL: printf("1"); fflush(stdout); break; case 2UL: printf("2"); fflush(stdout); break; case 3UL: printf("3"); fflush(stdout); break; case 4UL: printf("4"); fflush(stdout); break; case 5UL: printf("5"); fflush(stdout); break; case 6UL: printf("6"); fflush(stdout); break; case 7UL: printf("7"); fflush(stdout); break; case 8UL: printf("8"); fflush(stdout); break; case 9UL: printf("9"); fflush(stdout); break; } } divisor = coder::internal::i64ddiv(divisor); } if (b_leading) { printf("0"); fflush(stdout); } } // End of code generation (printint.cpp)
21.905325
80
0.581037
zal-jlange
e507364b38266b298cc052de7af6ff34572656de
528
cpp
C++
Code/Chapter-4/rayaabb.cpp
SampleText2k77/graphics-book
2b6ff89be1c27683744a8b64145d5a6a9de37d5d
[ "MIT" ]
16
2019-07-09T11:49:13.000Z
2022-02-22T03:01:30.000Z
Code/Chapter-4/rayaabb.cpp
SampleText2k77/graphics-book
2b6ff89be1c27683744a8b64145d5a6a9de37d5d
[ "MIT" ]
null
null
null
Code/Chapter-4/rayaabb.cpp
SampleText2k77/graphics-book
2b6ff89be1c27683744a8b64145d5a6a9de37d5d
[ "MIT" ]
5
2019-09-09T17:44:50.000Z
2021-04-29T20:16:51.000Z
#define GLM_FORCE_RADIANS #define GLM_SWIZZLE #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <glm/gtx/quaternion.hpp> #include <glm/gtc/matrix_inverse.hpp> #include <glm/geometric.hpp> #include "bbox.h" inline glm::vec3 closestPoint ( const glm::vec3& n, const bbox& box ) { return glm::vec3 ( n.x <= 0 ? box.getMaxPoint().x : box.getMinPoint().x, n.y <= 0 ? box.getMaxPoint().y : box.getMinPoint().y, n.z <= 0 ? box.getMaxPoint().z : box.getMinPoint().z ); }
31.058824
82
0.617424
SampleText2k77
e50745e4986fa4f06a37c4ddc5d44ac1c77423ee
8,244
cpp
C++
mapleall/maple_me/src/me_stmt_fre.cpp
lvyitian/mapleall
1112501c1bcbff5d9388bf46f195d56560c5863a
[ "MulanPSL-1.0" ]
null
null
null
mapleall/maple_me/src/me_stmt_fre.cpp
lvyitian/mapleall
1112501c1bcbff5d9388bf46f195d56560c5863a
[ "MulanPSL-1.0" ]
null
null
null
mapleall/maple_me/src/me_stmt_fre.cpp
lvyitian/mapleall
1112501c1bcbff5d9388bf46f195d56560c5863a
[ "MulanPSL-1.0" ]
null
null
null
/* * Copyright (c) [2020] Huawei Technologies Co., Ltd. All rights reserved. * * OpenArkCompiler is licensed under the Mulan Permissive Software License v2. * You can use this software according to the terms and conditions of the MulanPSL - 2.0. * You may obtain a copy of MulanPSL - 2.0 at: * * https://opensource.org/licenses/MulanPSL-2.0 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR * FIT FOR A PARTICULAR PURPOSE. * See the MulanPSL - 2.0 for more details. */ #include "me_stmt_pre.h" namespace maple { void MeStmtPre::ResetFullyAvail(MePhiOcc *occg) { occg->is_canbeavail = false; // reset those phiocc nodes that have oc as one of its operands for (MapleVector<MePhiOcc *>::iterator it = phi_occs.begin(); it != phi_occs.end(); it++) { MePhiOcc *phiocc = *it; MapleVector<MePhiOpndOcc *> &phiopnds = phiocc->phiopnds; for (uint32 i = 0; i < phiopnds.size(); i++) { MePhiOpndOcc *phiopnd = phiopnds[i]; if (phiopnd->def && phiopnd->def == occg) { // phiopnd is a use of occg if (!phiopnd->has_real_use && phiocc->is_canbeavail) { ResetFullyAvail(phiocc); } } } } } // the fullyavail attribute is stored in the is_canbeavail field void MeStmtPre::ComputeFullyAvail() { for (MapleVector<MePhiOcc *>::iterator it = phi_occs.begin(); it != phi_occs.end(); it++) { MePhiOcc *phiocc = *it; if (phiocc->is_canbeavail) { // reset canbeavail if any phi operand is null bool existNullDef = false; MapleVector<MePhiOpndOcc *> &phiopnds = phiocc->phiopnds; for (uint32 i = 0; i < phiopnds.size(); i++) { MePhiOpndOcc *phiopnd = phiopnds[i]; if (phiopnd->def == nullptr) { existNullDef = true; break; } } if (existNullDef) { ResetFullyAvail(phiocc); } } } } bool MeStmtPre::AllVarsSameVersionStmtFre(MeRealOcc *topocc, MeRealOcc *curocc) const { ASSERT(topocc->mestmt->op == OP_dassign, "AllVarsSameVersionStmtFre: only dassign is handled"); DassignMeStmt *dass1 = static_cast<DassignMeStmt *>(topocc->mestmt); DassignMeStmt *dass2 = static_cast<DassignMeStmt *>(curocc->mestmt); if (dass1->rhs != dass2->rhs) { return false; } return dass1->lhs == curocc->meexpr; } void MeStmtPre::Rename1StmtFre() { std::stack<MeOccur *> occStack; rename2_set.clear(); class_count = 1; // iterate the occurrence according to its preorder dominator tree for (MeOccur *occ : all_occs) { while (!occStack.empty() && !occStack.top()->IsDominate(dominance, occ)) { occStack.pop(); } switch (occ->occty) { case kOccReal: { if (occStack.empty()) { // assign new class occ->classid = class_count++; occStack.push(occ); break; } MeOccur *topoccur = occStack.top(); if (topoccur->occty == kOccMembar) { occ->classid = class_count++; occStack.push(occ); break; } MeRealOcc *realocc = static_cast<MeRealOcc *>(occ); if (topoccur->occty == kOccReal) { MeRealOcc *realtopoccur = static_cast<MeRealOcc *>(topoccur); if (AllVarsSameVersionStmtFre(realtopoccur, realocc)) { // all corresponding variables are the same realocc->classid = realtopoccur->classid; realocc->def = realtopoccur; } else { // assign new class occ->classid = class_count++; } occStack.push(occ); } else { // top of stack is a PHI occurrence std::vector<MeExpr *> varVec; CollectVarForCand(realocc, varVec); bool isalldom = true; for (std::vector<MeExpr *>::iterator varit = varVec.begin(); varit != varVec.end(); varit++) { MeExpr *varmeexpr = *varit; if (!DefVarDominateOcc(varmeexpr, topoccur)) { isalldom = false; } } if (isalldom) { realocc->classid = topoccur->classid; realocc->def = topoccur; rename2_set.insert(realocc->position); occStack.push(realocc); } else { // assign new class occ->classid = class_count++; } occStack.push(occ); } break; } case kOccPhiocc: { // assign new class occ->classid = class_count++; occStack.push(occ); break; } case kOccPhiopnd: { if (occStack.empty() || occStack.top()->occty == kOccMembar) { occ->def = nullptr; } else { MeOccur *topoccur = occStack.top(); occ->def = topoccur; occ->classid = topoccur->classid; if (topoccur->occty == kOccReal) { static_cast<MePhiOpndOcc *>(occ)->has_real_use = true; } } break; } case kOccExit: break; case kOccMembar: if (occStack.empty() || occStack.top()->occty != kOccMembar) { occStack.push(occ); } break; default: ASSERT(false, ""); } } if (ssapredebug) { PreWorkCand *curCand = work_cand; LogInfo::MapleLogger() << "======== ssafre candidate " << curCand->index << " after rename1StmtFre ===================\n"; for (MeOccur *occ : all_occs) { occ->Dump(irMap); LogInfo::MapleLogger() << std::endl; } LogInfo::MapleLogger() << "\n" << "rename2 set:\n"; for (uint32_t pos : rename2_set) { MeRealOcc *occur = work_cand->real_occs[pos]; occur->Dump(irMap); LogInfo::MapleLogger() << " with def at\n"; occur->def->Dump(irMap); LogInfo::MapleLogger() << "\n"; } LogInfo::MapleLogger() << "\n"; } } void MeStmtPre::DoSSAFRE() { if (ssapredebug) { LogInfo::MapleLogger() << "{{{{{{{{ start of SSAFRE }}}}}}}}" << std::endl; } // form new all_occs that has no use_occ and reflect insertions and deletions MapleVector<MeOccur *> newAllOccs(percand_allocator.Adapter()); ; int32 realoccCnt = 0; bool hasInsertion = false; // if there is insertion, do not perform SSAFRE // because SSA form has not been updated for (MeOccur *occ : all_occs) { switch (occ->occty) { case kOccReal: { MeRealOcc *realocc = static_cast<MeRealOcc *>(occ); if (!realocc->is_reload) { realocc->is_reload = false; realocc->is_save = false; realocc->classid = 0; realocc->def = nullptr; newAllOccs.push_back(realocc); realoccCnt++; } break; } case kOccPhiopnd: { MePhiOpndOcc *phiopnd = static_cast<MePhiOpndOcc *>(occ); if (phiopnd->def_phiocc->IsWillBeAvail()) { MeOccur *defocc = phiopnd->def; if (defocc && defocc->occty == kOccInserted && !phiopnd->is_phiopndreload) { hasInsertion = true; break; } } phiopnd->is_processed = false; phiopnd->has_real_use = false; phiopnd->is_insertedocc = false; phiopnd->is_phiopndreload = false; phiopnd->current_expr.mestmt = nullptr; phiopnd->classid = 0; phiopnd->def = nullptr; newAllOccs.push_back(phiopnd); break; } case kOccPhiocc: { MePhiOcc *phiocc = static_cast<MePhiOcc *>(occ); phiocc->is_downsafety = false; phiocc->is_canbeavail = true; phiocc->is_later = false; phiocc->is_extraneous = false; phiocc->is_removed = false; phiocc->classid = 0; newAllOccs.push_back(phiocc); break; } case kOccExit: case kOccMembar: newAllOccs.push_back(occ); break; case kOccUse: break; default: ASSERT(false, ""); } if (hasInsertion) { break; } } if (hasInsertion || realoccCnt <= 1) { return; } all_occs = newAllOccs; Rename1StmtFre(); Rename2(); ComputeFullyAvail(); Finalize1(); Finalize2(); CodeMotion(); } } // namespace maple
31.586207
126
0.577754
lvyitian
e508d32acc6e92da93071f9728c4abfaaa042691
325
cpp
C++
Cpp/1189.maximum-number-of-ballons.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
1
2015-12-19T23:05:35.000Z
2015-12-19T23:05:35.000Z
Cpp/1189.maximum-number-of-ballons.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
Cpp/1189.maximum-number-of-ballons.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
class Solution { public: int maxNumberOfBalloons(string text) { vector<int> cnts(26, 0); for (char c : text) { cnts[c-'a'] ++; } vector<int> ballon{cnts[0], cnts[1], cnts[11]/2, cnts[14]/2, cnts[13]}; return *min_element(ballon.begin(), ballon.end()); } };
27.083333
79
0.513846
zszyellow
e50da8dce16ecc613a3f2edd07f12ed8d9459177
532
cpp
C++
source/algorithms/gmi.cpp
tasseff/gomory
d18b9aac036d2ef6d8c582a26f68060994590eba
[ "MIT" ]
2
2017-04-27T23:24:32.000Z
2018-09-20T21:19:34.000Z
source/algorithms/gmi.cpp
tasseff/gomory
d18b9aac036d2ef6d8c582a26f68060994590eba
[ "MIT" ]
null
null
null
source/algorithms/gmi.cpp
tasseff/gomory
d18b9aac036d2ef6d8c582a26f68060994590eba
[ "MIT" ]
null
null
null
#include <common/document.h> #include <common/error.h> #include "gomory.h" int main(int argc, char* argv[]) { // Check if a JSON file has been specified. if (argc <= 1) { PrintErrorAndExit("JSON file has not been specified."); } // Read the scenario file. File model_file(argv[1]); // Parse the scenario file as a JSON document. Document json(model_file); // Set up the model. Gomory model(json.root["parameters"], argv[2], argv[3]); // Run the model. model.Run(); // Program executed successfully. return 0; }
20.461538
57
0.676692
tasseff
e5141d2137f8d0fee721a0dec66e794ad3fb72de
3,721
cpp
C++
tests/test_user_defined.cpp
ToruNiina/wad
f5f0445f7f0a53efd31988ce7d381bccb463b951
[ "MIT" ]
null
null
null
tests/test_user_defined.cpp
ToruNiina/wad
f5f0445f7f0a53efd31988ce7d381bccb463b951
[ "MIT" ]
null
null
null
tests/test_user_defined.cpp
ToruNiina/wad
f5f0445f7f0a53efd31988ce7d381bccb463b951
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "wad/integer.hpp" #include "wad/floating.hpp" #include "wad/string.hpp" #include "wad/in_place.hpp" #include "wad/archive.hpp" #include "wad/interface.hpp" #include "utility.hpp" namespace extlib { struct X { std::string s; std::int32_t i; double d; template<typename Arc> bool archive(Arc& arc) { return wad::archive<wad::type::map>(arc, "s", s, "i", i, "d", d); } }; struct Y { std::string s; std::int32_t i; double d; template<typename Arc> bool archive(Arc& arc) { return wad::archive<wad::type::array>(arc, s, i, d); } }; struct Z { std::string s; std::int32_t i; double d; template<typename Arc> bool save(Arc& arc) const { return wad::save<wad::type::map>(arc, "s", s, "i", i, "d", d); } template<typename Arc> bool load(Arc& arc) { return wad::load<wad::type::map>(arc, "s", s, "i", i, "d", d); } }; struct W { std::string s; std::int32_t i; double d; template<typename Arc> bool save(Arc& arc) const { return wad::save<wad::type::array>(arc, s, i, d); } template<typename Arc> bool load(Arc& arc) { return wad::load<wad::type::array>(arc, s, i, d); } }; struct V { std::string s; std::int32_t i; double d; }; template<typename Arc> bool save(Arc& arc, const V& v) { return wad::save<wad::type::array>(arc, v.s, v.i, v.d); } template<typename Arc> bool load(Arc& arc, V& v) { return wad::load<wad::type::array>(arc, v.s, v.i, v.d); } } // extlib TEST_CASE( "user_defined<map>::archive()", "[user_defined<map>::archive()]" ) { extlib::X x{"foo", 42, 3.14}; { extlib::X x1; wad::test_write_archive warc; wad::save(warc, x); wad::test_read_archive rarc(warc); wad::load(rarc, x1); REQUIRE(x.s == x1.s); REQUIRE(x.i == x1.i); REQUIRE(x.d == x1.d); } { extlib::X x1; wad::test_write_archive warc; wad::archive(warc, x); wad::test_read_archive rarc(warc); wad::archive(rarc, x1); REQUIRE(x.s == x1.s); REQUIRE(x.i == x1.i); REQUIRE(x.d == x1.d); } } TEST_CASE( "user_defined<array>::archive()", "[user_defined<array>::archive()]" ) { extlib::Y x{"foo", 42, 3.14}; { extlib::Y x1; wad::test_write_archive warc; wad::save(warc, x); wad::test_read_archive rarc(warc); wad::load(rarc, x1); REQUIRE(x.s == x1.s); REQUIRE(x.i == x1.i); REQUIRE(x.d == x1.d); } { extlib::Y x1; wad::test_write_archive warc; wad::archive(warc, x); wad::test_read_archive rarc(warc); wad::archive(rarc, x1); REQUIRE(x.s == x1.s); REQUIRE(x.i == x1.i); REQUIRE(x.d == x1.d); } } TEST_CASE( "user_defined<map>::save/load()", "[user_defined<map>::save/load()]" ) { const extlib::Z x{"foo", 42, 3.14}; const extlib::Z x1 = wad::save_load(x); REQUIRE(x.s == x1.s); REQUIRE(x.i == x1.i); REQUIRE(x.d == x1.d); } TEST_CASE( "user_defined<array>::save/load()", "[user_defined<array>::save/load()]" ) { const extlib::W x{"foo", 42, 3.14}; const extlib::W x1 = wad::save_load(x); REQUIRE(x.s == x1.s); REQUIRE(x.i == x1.i); REQUIRE(x.d == x1.d); } TEST_CASE( "save/load(user_defined<array>)", "[save/load(user_defined<array>)]" ) { const extlib::V x{"foo", 42, 3.14}; const extlib::V x1 = wad::save_load(x); REQUIRE(x.s == x1.s); REQUIRE(x.i == x1.i); REQUIRE(x.d == x1.d); }
21.262857
85
0.536684
ToruNiina
e51437479bf53620e86d489a138390efad5c728b
362
cpp
C++
book/Chap3/trythis.cpp
mjakebarrington/CPP-Exercises
9bb01f66ae9861c4d5323738fb478f15ad7e691c
[ "MIT" ]
null
null
null
book/Chap3/trythis.cpp
mjakebarrington/CPP-Exercises
9bb01f66ae9861c4d5323738fb478f15ad7e691c
[ "MIT" ]
null
null
null
book/Chap3/trythis.cpp
mjakebarrington/CPP-Exercises
9bb01f66ae9861c4d5323738fb478f15ad7e691c
[ "MIT" ]
null
null
null
/* * In chapter 3's "Try This" exercise, students are asked to print someones name out in months. */ #include <iostream> using namespace std; int main() { cout << "What is your name and age in years? \n"; string name; double age; cin >> name >> age; age *= 12; cout << "Hello, " << name << ", you are roughly " << age << " months old!\n"; return 0; }
21.294118
95
0.616022
mjakebarrington
e5167bc0f2f4370b07d763432feb78963c1397b6
487
hpp
C++
Chess/connector.hpp
classix-ps/Chess
1165cb3e5aab67de562b029f65c80f5156d6c26b
[ "CC-BY-4.0" ]
null
null
null
Chess/connector.hpp
classix-ps/Chess
1165cb3e5aab67de562b029f65c80f5156d6c26b
[ "CC-BY-4.0" ]
null
null
null
Chess/connector.hpp
classix-ps/Chess
1165cb3e5aab67de562b029f65c80f5156d6c26b
[ "CC-BY-4.0" ]
null
null
null
#pragma once #include <windows.h> #include <stdio.h> #include <iostream> #include <string> class Engine { public: Engine(LPCWSTR); void ConnectToEngine(); std::string getNextMove(std::string); void CloseConnection(); private: LPCWSTR enginePath; STARTUPINFO sti = { 0 }; SECURITY_ATTRIBUTES sats = { 0 }; PROCESS_INFORMATION pi = { 0 }; HANDLE pipin_w, pipin_r, pipout_w, pipout_r; BYTE buffer[8192]; DWORD writ, excode, read, available; };
21.173913
48
0.669405
classix-ps
e516cf6690454e4c5011ee2ba91596f67bf58444
1,822
cpp
C++
bruter/bruter/tests/bruter3.cpp
flyyee/riwlan-brute
0c886d48518a7f5258751c6a1dc43c51fa7f7fa1
[ "MIT" ]
null
null
null
bruter/bruter/tests/bruter3.cpp
flyyee/riwlan-brute
0c886d48518a7f5258751c6a1dc43c51fa7f7fa1
[ "MIT" ]
null
null
null
bruter/bruter/tests/bruter3.cpp
flyyee/riwlan-brute
0c886d48518a7f5258751c6a1dc43c51fa7f7fa1
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <fstream> #include <algorithm> #include <sstream> #include <iterator> void generate_words(const std::vector<char> &alphabet, size_t &word_length, std::vector<std::string> &results) { std::vector<size_t> index(word_length, 0); for (;;) { std::string word(index.size(), ' '); for (size_t i = 0; i < index.size(); ++i) { word[i] = alphabet[index[i]]; } results.emplace_back(word); for (int i = index.size() - 1; ; --i) { if (i < 0) { return; } ++index[i]; if (index[i] == alphabet.size()) { index[i] = 0; } else { break; } } } } int main(int argc, char **argv) { std::ifstream infile(argv[1], std::ios::in | std::ifstream::binary); std::string line; while (infile.good() && getline(infile, line)) { size_t word_length = std::stoi(line.substr(0, line.find(','))); std::string letters = line.substr(line.find(',') + 1); std::vector<char> alphabet; for (const auto &it : letters) { alphabet.push_back(it); } std::sort(alphabet.begin(), alphabet.end()); auto last = std::unique(alphabet.begin(), alphabet.end()); alphabet.erase(last, alphabet.end()); std::vector<std::string> results; generate_words(alphabet, word_length, results); std::ostringstream result_line; std::copy(results.begin(), results.end() - 1, std::ostream_iterator<std::string>(result_line, ",")); result_line << results.back(); std::cout << result_line.str() << "\n"; } }
25.305556
110
0.513172
flyyee
e51922575b32b9367b11b762324e23a9a87793cc
5,936
cpp
C++
WaveSabreCore/src/Twister.cpp
armak/WaveSabre
e72bf68e3bdd215cf8d310d106839cb234587793
[ "MIT" ]
3
2019-03-01T21:33:54.000Z
2021-09-16T09:40:56.000Z
WaveSabreCore/src/Twister.cpp
djh0ffman/WaveSabre
6a3885134fd9ef1ba31d60e7bb2be41de68f1a3b
[ "MIT" ]
null
null
null
WaveSabreCore/src/Twister.cpp
djh0ffman/WaveSabre
6a3885134fd9ef1ba31d60e7bb2be41de68f1a3b
[ "MIT" ]
1
2021-01-02T13:28:55.000Z
2021-01-02T13:28:55.000Z
#include <WaveSabreCore/Twister.h> #include <WaveSabreCore/Helpers.h> int const lookAhead = 4; namespace WaveSabreCore { Twister::Twister() : Device((int)ParamIndices::NumParams) { type = 0; amount = 0; feedback = 0.0f; spread = Spread::Mono; vibratoFreq = Helpers::ParamToVibratoFreq(0.0f); vibratoAmount = 0.0f; vibratoPhase = 0.0; lowCutFreq = 20.0f; highCutFreq = 20000.0f- 20.0f; dryWet = .5f; leftBuffer.SetLength(1000); rightBuffer.SetLength(1000); lastLeft = 0.0f; lastRight = 0.0f; for (int i = 0; i < 2; i++) { lowCutFilter[i].SetType(StateVariableFilterType::Highpass); highCutFilter[i].SetType(StateVariableFilterType::Lowpass); } } Twister::~Twister() { } void Twister::Run(double songPosition, float **inputs, float **outputs, int numSamples) { double vibratoDelta = (vibratoFreq / Helpers::CurrentSampleRate) * 0.25f; float outputLeft = 0.0f; float outputRight = 0.0f; float positionLeft = 0.0f; float positionRight = 0.0f; for (int i = 0; i < 2; i++) { lowCutFilter[i].SetFreq(lowCutFreq); highCutFilter[i].SetFreq(highCutFreq); } for (int i = 0; i < numSamples; i++) { float leftInput = inputs[0][i]; float rightInput = inputs[1][i]; double freq = Helpers::FastSin(vibratoPhase) * vibratoAmount; switch (spread) { case Spread::Mono: default: positionLeft = Helpers::Clamp((amount + (float)freq), 0.0f, 1.0f); positionRight = positionLeft; break; case Spread::FullInvert: positionLeft = Helpers::Clamp((amount + (float)freq), 0.0f, 1.0f); positionRight = (1.0f - Helpers::Clamp((amount + (float)freq), 0.0f, 1.0f)); break; case Spread::ModInvert: positionLeft = Helpers::Clamp((amount + (float)freq), 0.0f, 1.0f); positionRight = Helpers::Clamp((amount - (float)freq), 0.0f, 1.0f); break; } switch (type) { case 0: positionLeft *= 132.0f; positionRight *= 132.0f; outputLeft = highCutFilter[0].Next(lowCutFilter[0].Next(leftBuffer.ReadPosition(positionLeft + 2))); outputRight = highCutFilter[1].Next(lowCutFilter[1].Next(rightBuffer.ReadPosition(positionRight + 2))); leftBuffer.WriteSample(leftInput + (outputLeft * feedback)); rightBuffer.WriteSample(rightInput + (outputRight * feedback)); break; case 1: positionLeft *= 132.0f; positionRight *= 132.0f; outputLeft = highCutFilter[0].Next(lowCutFilter[0].Next(leftBuffer.ReadPosition(positionLeft + 2))); outputRight = highCutFilter[1].Next(lowCutFilter[1].Next(rightBuffer.ReadPosition(positionRight + 2))); leftBuffer.WriteSample(leftInput - (outputLeft * feedback)); rightBuffer.WriteSample(rightInput - (outputRight * feedback)); break; case 2: for (int i = 0; i<6; i++) allPassLeft[i].Delay(positionLeft); for (int i = 0; i<6; i++) allPassRight[i].Delay(positionRight); outputLeft = highCutFilter[0].Next(lowCutFilter[0].Next(AllPassUpdateLeft(leftInput + lastLeft * feedback))); outputRight = highCutFilter[1].Next(lowCutFilter[1].Next(AllPassUpdateRight(rightInput + lastRight * feedback))); lastLeft = outputLeft; lastRight = outputRight; break; case 3: for (int i = 0; i<6; i++) allPassLeft[i].Delay(positionLeft); for (int i = 0; i<6; i++) allPassRight[i].Delay(positionRight); outputLeft = highCutFilter[0].Next(lowCutFilter[0].Next(AllPassUpdateLeft(leftInput - lastLeft * feedback))); outputRight = highCutFilter[1].Next(lowCutFilter[1].Next(AllPassUpdateRight(rightInput - lastRight * feedback))); lastLeft = outputLeft; lastRight = outputRight; break; default: outputLeft = 0.0f; outputRight = 0.0f; break; } outputs[0][i] = (leftInput * (1.0f - dryWet)) + (outputLeft * dryWet); outputs[1][i] = (rightInput * (1.0f - dryWet)) + (outputRight * dryWet); vibratoPhase += vibratoDelta; } } float Twister::AllPassUpdateLeft(float input) { return( allPassLeft[0].Update( allPassLeft[1].Update( allPassLeft[2].Update( allPassLeft[3].Update( allPassLeft[4].Update( allPassLeft[5].Update(input))))))); } float Twister::AllPassUpdateRight(float input) { return( allPassRight[0].Update( allPassRight[1].Update( allPassRight[2].Update( allPassRight[3].Update( allPassRight[4].Update( allPassRight[5].Update(input))))))); } void Twister::SetParam(int index, float value) { switch ((ParamIndices)index) { case ParamIndices::Type: type = (int)(value * 3.0f); break; case ParamIndices::Amount: amount = value; break; case ParamIndices::Feedback: feedback = value; break; case ParamIndices::Spread: spread = Helpers::ParamToSpread(value); break; case ParamIndices::VibratoFreq: vibratoFreq = Helpers::ParamToVibratoFreq(value); break; case ParamIndices::VibratoAmount: vibratoAmount = value; break; case ParamIndices::LowCutFreq: lowCutFreq = Helpers::ParamToFrequency(value); break; case ParamIndices::HighCutFreq: highCutFreq = Helpers::ParamToFrequency(value); break; case ParamIndices::DryWet: dryWet = value; break; } } float Twister::GetParam(int index) const { switch ((ParamIndices)index) { case ParamIndices::Type: default: return type / 3.0f; case ParamIndices::Amount: return amount; case ParamIndices::Feedback: return feedback; case ParamIndices::Spread: return Helpers::SpreadToParam(spread); case ParamIndices::VibratoFreq: return Helpers::VibratoFreqToParam(vibratoFreq); case ParamIndices::VibratoAmount: return vibratoAmount; case ParamIndices::LowCutFreq: return Helpers::FrequencyToParam(lowCutFreq); case ParamIndices::HighCutFreq: return Helpers::FrequencyToParam(highCutFreq); case ParamIndices::DryWet: return dryWet; } } }
32.26087
118
0.670654
armak
e51931254833e9daae0b21d79018cb7aea95ea64
2,903
cpp
C++
tests/rwops/load/main.cpp
jamesl-github/scc
c1dddf41778eeb2ef2a910372d1eb6a6a8dfa68e
[ "Zlib" ]
8
2018-04-21T07:49:58.000Z
2019-02-21T15:04:28.000Z
tests/rwops/load/main.cpp
jamesl-github/scc
c1dddf41778eeb2ef2a910372d1eb6a6a8dfa68e
[ "Zlib" ]
null
null
null
tests/rwops/load/main.cpp
jamesl-github/scc
c1dddf41778eeb2ef2a910372d1eb6a6a8dfa68e
[ "Zlib" ]
2
2018-04-21T02:25:47.000Z
2018-04-21T15:03:15.000Z
/* SDL C++ Classes Copyright (C) 2017-2018 Mateus Carmo M. de F. Barbosa 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 <iostream> #include <stdexcept> #include <SDL.h> #include "rwops.hpp" using SDL::RWops; using SDL::FromRWops; const int ERR_SDL_INIT = -1; char mem[] = { 0, 1, 2, 3 }; bool init(Uint32 sdlInitFlags) { if(SDL_Init(sdlInitFlags) < 0) { return false; } return true; } void quit() { SDL_Quit(); } void printRWopsType(SDL_RWops *rwops) { std::cout << "RWops type: "; switch(rwops->type) { case SDL_RWOPS_UNKNOWN: std::cout << "unknown"; break; case SDL_RWOPS_WINFILE: std::cout << "win32 file"; break; case SDL_RWOPS_STDFILE: std::cout << "stdio file"; break; case SDL_RWOPS_JNIFILE: std::cout << "android asset"; break; case SDL_RWOPS_MEMORY: std::cout << "memory (read-write)"; break; case SDL_RWOPS_MEMORY_RO: std::cout << "memory (read-only)"; break; } std::cout << std::endl; } struct PseudoDeleter { void operator()(char *) {} }; // has to return the same type that PseudoDeleter::operator() recieves char * pseudoLoad(SDL_RWops *rwops, int freesrc, int extraArg) { if(freesrc != 0) { std::cout << "error: non-zero freesrc!" << std::endl; } printRWopsType(rwops); std::cout << "extra argument: " << extraArg << std::endl; if(extraArg < 0) { return NULL; } return mem; // could be any non-null char* } void test() { RWops rwops(mem, sizeof(mem)); // in both cases, we ignore load's return value try { FromRWops<PseudoDeleter>::load(rwops, pseudoLoad, "error: first load throws, but it shouldn't", 42); } catch(const std::exception &ex) { std::cout << ex.what() << std::endl; } try { FromRWops<PseudoDeleter>::load(rwops, pseudoLoad, "success: second load throws, as it should", -2); } catch(const std::exception &ex) { std::cout << ex.what() << std::endl; } } int main(int argc, char **argv) { Uint32 sdlFlags = SDL_INIT_VIDEO; if(!init(sdlFlags)) { SDL_LogCritical(SDL_LOG_CATEGORY_ERROR, "couldn't initialize SDL\n"); return ERR_SDL_INIT; } test(); quit(); return 0; }
23.41129
76
0.689631
jamesl-github
e51aec93c0d6f35d933af1768b3d9eadc13b8639
312
cpp
C++
cpp_solutions/lexf.cpp
lbovard/rosalind
92d0bde3282caf6af512114bdc0133ee3a1d6418
[ "Unlicense" ]
null
null
null
cpp_solutions/lexf.cpp
lbovard/rosalind
92d0bde3282caf6af512114bdc0133ee3a1d6418
[ "Unlicense" ]
null
null
null
cpp_solutions/lexf.cpp
lbovard/rosalind
92d0bde3282caf6af512114bdc0133ee3a1d6418
[ "Unlicense" ]
null
null
null
#include <iostream> #include <algorithm> int main() { std::vector<char> alphabet; int n; std::cout << facts[n] << std::endl; do { for(unsigned int i=0;i<n;++i) { std::cout << nums[i] << " "; } std::cout << std::endl; } while (std::next_permutation(nums,nums+n)); return 0; }
17.333333
47
0.544872
lbovard
e51b055f122e6e86dd30ea55b6172106bfc524c6
3,979
cc
C++
mindspore/lite/tools/converter/micro/coder/opcoders/nnacl/fp32/pad_fp32_coder.cc
httpsgithu/mindspore
c29d6bb764e233b427319cb89ba79e420f1e2c64
[ "Apache-2.0" ]
1
2022-02-23T09:13:43.000Z
2022-02-23T09:13:43.000Z
mindspore/lite/tools/converter/micro/coder/opcoders/nnacl/fp32/pad_fp32_coder.cc
949144093/mindspore
c29d6bb764e233b427319cb89ba79e420f1e2c64
[ "Apache-2.0" ]
null
null
null
mindspore/lite/tools/converter/micro/coder/opcoders/nnacl/fp32/pad_fp32_coder.cc
949144093/mindspore
c29d6bb764e233b427319cb89ba79e420f1e2c64
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Huawei Technologies Co., Ltd * * 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 "coder/opcoders/nnacl/fp32/pad_fp32_coder.h" #include <string> #include <vector> #include "coder/log.h" #include "coder/opcoders/serializers/nnacl_serializer/nnacl_fp32_serializer.h" #include "coder/opcoders/file_collector.h" #include "coder/opcoders/parallel.h" using mindspore::schema::PrimitiveType_PadFusion; namespace mindspore::lite::micro::nnacl { int PadFP32Coder::Prepare(CoderContext *const context) { pad_param_ = reinterpret_cast<PadParameter *>(parameter_); return ReSize(); } int PadFP32Coder::ReSize() { size_t rank = input_tensor_->shape().size(); if (rank > DEFAULT_PAD_NDIMS) { MS_LOG(ERROR) << "Pad input rank should <= " << DEFAULT_PAD_NDIMS << ", got " << rank; return RET_ERROR; } if (pad_param_->pad_mode_ == static_cast<int>(schema::PaddingMode_CONSTANT)) { MS_CHECK_RET_CODE(ExtendShape(in_, DEFAULT_PAD_NDIMS, input_tensor_->shape().data(), rank), "ExtendShape input error"); MS_CHECK_RET_CODE(ExtendShape(out_, DEFAULT_PAD_NDIMS, output_tensor_->shape().data(), rank), "ExtendShape output error"); if (pad_param_->padding_length < MAX_PAD_SIZE) { int ori_paddings[MAX_PAD_SIZE]; for (int i = 0; i < pad_param_->padding_length; ++i) { ori_paddings[i] = pad_param_->paddings_[i]; } MS_CHECK_RET_CODE(ExtendPaddings(pad_param_->paddings_, MAX_PAD_SIZE, ori_paddings, pad_param_->padding_length), "Extendpadding error"); pad_param_->padding_length = MAX_PAD_SIZE; } } return RET_OK; } int PadFP32Coder::ExtendShape(int *shape, int length, const int *ori_shape, int rank) { MS_CHECK_PTR(shape); MS_CHECK_PTR(ori_shape); for (int i = 0; i < length - rank; ++i) { shape[i] = 1; } for (int i = length - rank; i < length; ++i) { shape[i] = ori_shape[i - (length - rank)]; } return RET_OK; } int PadFP32Coder::ExtendPaddings(int *paddings, int length, const int *ori_paddings, int ori_length) { MS_CHECK_PTR(paddings); MS_CHECK_PTR(ori_paddings); for (int i = 0; i < length - ori_length; ++i) { paddings[i] = 0; } for (int i = length - ori_length; i < length; ++i) { paddings[i] = ori_paddings[i - (length - ori_length)]; } return RET_OK; } int PadFP32Coder::DoCode(CoderContext *const context) { Collect(context, { "nnacl/fp32/pad_fp32.h", "nnacl/pad_parameter.h", }, { "pad_fp32.c", }); NNaclFp32Serializer code; code.CodeArray("in_", in_, DEFAULT_PAD_NDIMS); code.CodeArray("out_", out_, DEFAULT_PAD_NDIMS); code.CodeArray("padding_", pad_param_->paddings_, MAX_PAD_SIZE); int output_size = output_tensor_->ElementsNum(); if (pad_param_->constant_value_ - 0.0f < 1e-5) { code.CodeFunction("memset", output_tensor_, "0", output_size * sizeof(float)); } else { std::vector<float> constant_values(output_size, pad_param_->constant_value_); code.CodeArray("output_tensor_", constant_values.data(), output_size); } code.CodeFunction("Pad", input_tensor_, output_tensor_, "in_", "out_", "padding_", kDefaultTaskId, thread_num_); context->AppendCode(code.str()); return RET_OK; } REG_OPERATOR_CODER(kAllTargets, kNumberTypeFloat32, PrimitiveType_PadFusion, CPUOpCoderCreator<PadFP32Coder>) } // namespace mindspore::lite::micro::nnacl
36.172727
118
0.690626
httpsgithu
e51ece6da259c4785f3f97b091e589df208d648f
1,010
cpp
C++
MainWindow.cpp
Evgenii-Evgenevich/qt-the-interface
0d12d110b09b5ff9c52adc7da70104b219220267
[ "Apache-2.0" ]
null
null
null
MainWindow.cpp
Evgenii-Evgenevich/qt-the-interface
0d12d110b09b5ff9c52adc7da70104b219220267
[ "Apache-2.0" ]
null
null
null
MainWindow.cpp
Evgenii-Evgenevich/qt-the-interface
0d12d110b09b5ff9c52adc7da70104b219220267
[ "Apache-2.0" ]
null
null
null
#include "MainWindow.h" #include <QLocale> #include <QScrollArea> #include <QTabWidget> #include <QPushButton> #include <QStatusBar> #include <QMenuBar> #include <QShowEvent> #include "Beam.h" MainWindow::MainWindow() : QMainWindow() { QScrollArea* scrollArea = new QScrollArea; scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setWidgetResizable(true); m_beam = new Beam(this); setWindowTitle("Beam"); setCentralWidget(scrollArea); scrollArea->setWidget(m_beam); QMenu* fileMenu = menuBar()->addMenu("&File"); statusBar()->addWidget(new QPushButton("Start Simulation")); const QIcon exitIcon = QIcon::fromTheme("application-exit"); QAction* exitAct = fileMenu->addAction(exitIcon, tr("E&xit"), this, &QWidget::close); exitAct->setShortcuts(QKeySequence::Quit); exitAct->setStatusTip(tr("Exit the application")); } void MainWindow::showEvent(QShowEvent* event) { QMainWindow::showEvent(event); }
25.897436
86
0.757426
Evgenii-Evgenevich
e520698bdb3967ab38489ba1f05f6381a238db60
1,704
cpp
C++
editor/echo/Base/UI/QtInterface/QComboBox.cpp
johndpope/echo
e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7
[ "MIT" ]
null
null
null
editor/echo/Base/UI/QtInterface/QComboBox.cpp
johndpope/echo
e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7
[ "MIT" ]
null
null
null
editor/echo/Base/UI/QtInterface/QComboBox.cpp
johndpope/echo
e9ce2f4037e8a5d49b74cc7a9d9ee09f296e7fa7
[ "MIT" ]
null
null
null
#include <QComboBox> #include <engine/core/util/StringUtil.h> #include "Studio.h" namespace Echo { void qComboBoxAddItem(QWidget* widget, const char* icon, const char* text) { if (widget) { QComboBox* comboBox = qobject_cast<QComboBox*>(widget); if (comboBox) { if (icon) comboBox->addItem(QIcon(icon), text); else comboBox->addItem(text); } } } int qComboBoxCurrentIndex(QWidget* widget) { String result; if (widget) { QComboBox* comboBox = qobject_cast<QComboBox*>(widget); if (comboBox) { return comboBox->currentIndex(); } } return -1; } String qComboBoxCurrentText(QWidget* widget) { String result; if (widget) { QComboBox* comboBox = qobject_cast<QComboBox*>(widget); if (comboBox) { result = comboBox->currentText().toStdString().c_str(); } } return result; } void qComboBoxSetCurrentIndex(QWidget* widget, int index) { if (widget) { QComboBox* comboBox = qobject_cast<QComboBox*>(widget); if (comboBox) { comboBox->setCurrentIndex( index); } } } void qComboBoxSetCurrentText(QWidget* widget, const char* text) { if (widget) { QComboBox* comboBox = qobject_cast<QComboBox*>(widget); if (comboBox) { comboBox->setCurrentText(text); } } } void qComboBoxSetItemText(QWidget* widget, int index, const char* text) { if (widget) { QComboBox* comboBox = qobject_cast<QComboBox*>(widget); if (comboBox) { comboBox->setItemText(index, text); } } } void qComboBoxClear(QWidget* widget) { if (widget) { QComboBox* comboBox = qobject_cast<QComboBox*>(widget); if (comboBox) { comboBox->clear(); } } } }
17.04
75
0.643779
johndpope
e524f5ed1b49b0b7b9ded472ec03bea8b73d32ab
400
cpp
C++
RayTracer/TexturedMaterial.cpp
MatthewSmit/RayTracer
86aff1867a6a6fa3f493a489b4848e75ca7370f0
[ "MIT" ]
2
2018-03-26T21:59:26.000Z
2019-11-14T13:54:44.000Z
RayTracer/TexturedMaterial.cpp
MatthewSmit/RayTracer
86aff1867a6a6fa3f493a489b4848e75ca7370f0
[ "MIT" ]
null
null
null
RayTracer/TexturedMaterial.cpp
MatthewSmit/RayTracer
86aff1867a6a6fa3f493a489b4848e75ca7370f0
[ "MIT" ]
null
null
null
#include "TexturedMaterial.h" #include "Image.h" #include "SceneObject.h" vec4 TexturedMaterial::getColour(const vec4& hitPoint, const SceneObject* object) const { auto textureCoordinates = object->getTextureCoordinates(hitPoint); textureCoordinates /= scaling; textureCoordinates = (textureCoordinates % vec4{ 1.0f } + vec4{ 1.0f }) % vec4 { 1.0f }; return image->sample(textureCoordinates); }
33.333333
89
0.7575
MatthewSmit
e52571a5af3bf5d17b16c3c5499490c303bf4d33
1,204
cc
C++
p2p/base/proxy_packet_socket_factory.cc
eagle3dstreaming/webrtc
fef9b3652f7744f722785fc1f4cc6b099f4c7aa7
[ "BSD-3-Clause" ]
null
null
null
p2p/base/proxy_packet_socket_factory.cc
eagle3dstreaming/webrtc
fef9b3652f7744f722785fc1f4cc6b099f4c7aa7
[ "BSD-3-Clause" ]
null
null
null
p2p/base/proxy_packet_socket_factory.cc
eagle3dstreaming/webrtc
fef9b3652f7744f722785fc1f4cc6b099f4c7aa7
[ "BSD-3-Clause" ]
null
null
null
#include "p2p/base/proxy_packet_socket_factory.h" namespace rtc { ProxyPacketSocketFactory::ProxyPacketSocketFactory() : BasicPacketSocketFactory() {} ProxyPacketSocketFactory::ProxyPacketSocketFactory(Thread* thread) : BasicPacketSocketFactory(thread) {} ProxyPacketSocketFactory::ProxyPacketSocketFactory( SocketFactory* socket_factory) : BasicPacketSocketFactory(socket_factory) {} ProxyPacketSocketFactory::~ProxyPacketSocketFactory() {} void ProxyPacketSocketFactory::SetProxyInformation(const ProxyInfo& proxy_info) { proxy_info_ = proxy_info; } AsyncPacketSocket* ProxyPacketSocketFactory::CreateClientTcpSocket( const SocketAddress& local_address, const SocketAddress& remote_address, const ProxyInfo& proxy_info, const std::string& user_agent, const PacketSocketTcpOptions& tcp_options) { return BasicPacketSocketFactory::CreateClientTcpSocket(local_address, remote_address, proxy_info_, user_agent, tcp_options); } }
34.4
81
0.656146
eagle3dstreaming
e527e0d5b1efa0f76eb376743d9d6631bf2d5df9
9,949
cpp
C++
compiler/extensions/cpp/runtime/test/zserio/SqliteConnectionTest.cpp
Klebert-Engineering/zserio-1
fbb4fc42d9ab6f3afa6c040a36267357399180f4
[ "BSD-3-Clause" ]
2
2019-02-06T17:50:24.000Z
2019-11-20T16:51:34.000Z
compiler/extensions/cpp/runtime/test/zserio/SqliteConnectionTest.cpp
Klebert-Engineering/zserio-1
fbb4fc42d9ab6f3afa6c040a36267357399180f4
[ "BSD-3-Clause" ]
1
2019-11-25T16:25:51.000Z
2019-11-25T18:09:39.000Z
compiler/extensions/cpp/runtime/test/zserio/SqliteConnectionTest.cpp
Klebert-Engineering/zserio-1
fbb4fc42d9ab6f3afa6c040a36267357399180f4
[ "BSD-3-Clause" ]
null
null
null
#include "zserio/SqliteConnection.h" #include "zserio/SqliteException.h" #include <string> #include <vector> #include <sqlite3.h> #include "gtest/gtest.h" namespace zserio { namespace { extern "C" int sqliteResultAccumulatorCallback(void *data, int nColumns, char** colValues, char** colNames); class SqliteResultAccumulator { public: typedef std::vector<std::string> TRow; typedef std::vector<TRow> TResult; TResult const& getResult() const { return result; } int callback(int nColumns, char** colValues, char**) { TRow row; row.reserve(nColumns); for (int i = 0; i < nColumns; ++i) row.push_back(std::string(colValues[i])); result.push_back(row); return 0; // continue } TResult result; }; int sqliteResultAccumulatorCallback(void *data, int nColumns, char** colValues, char** colNames) { SqliteResultAccumulator *self = static_cast<SqliteResultAccumulator*>(data); return self->callback(nColumns, colValues, colNames); } } // namespace static const char SQLITE3_MEM_DB[] = ":memory:"; TEST(SqliteConnectionTest, emptyConstructor) { SqliteConnection db; ASSERT_EQ(NULL, db.getConnection()); } TEST(SqliteConnectionTest, externalConstuctor) { sqlite3 *externalConnection = NULL; int result = sqlite3_open(SQLITE3_MEM_DB, &externalConnection); ASSERT_EQ(SQLITE_OK, result); SqliteConnection db(externalConnection, SqliteConnection::EXTERNAL_CONNECTION); ASSERT_EQ(externalConnection, db.getConnection()); ASSERT_EQ(SqliteConnection::EXTERNAL_CONNECTION, db.getConnectionType()); db.reset(); result = sqlite3_close(externalConnection); ASSERT_EQ(SQLITE_OK, result); ASSERT_EQ(SQLITE_OK, sqlite3_shutdown()); } TEST(SqliteConnectionTest, internalConstructor) { sqlite3* internalConnection = NULL; int result = sqlite3_open(SQLITE3_MEM_DB, &internalConnection); SqliteConnection db(internalConnection, SqliteConnection::INTERNAL_CONNECTION); ASSERT_EQ(internalConnection, db.getConnection()); ASSERT_EQ(SqliteConnection::INTERNAL_CONNECTION, db.getConnectionType()); db.reset(); ASSERT_EQ(NULL, db.getConnection()); result = sqlite3_close(internalConnection); ASSERT_NE(SQLITE_OK, result); // shall be already closed! ASSERT_EQ(SQLITE_OK, sqlite3_shutdown()); } TEST(SqliteConnectionTest, defaultInternalConstructor) { sqlite3* internalConnection = NULL; int result = sqlite3_open(SQLITE3_MEM_DB, &internalConnection); ASSERT_EQ(SQLITE_OK, result); SqliteConnection db(internalConnection, SqliteConnection::INTERNAL_CONNECTION); ASSERT_EQ(internalConnection, db.getConnection()); ASSERT_EQ(SqliteConnection::INTERNAL_CONNECTION, db.getConnectionType()); db.reset(); ASSERT_EQ(NULL, db.getConnection()); ASSERT_EQ(SQLITE_OK, sqlite3_shutdown()); } TEST(SqliteConnectionTest, resetExternal) { sqlite3 *externalConnection = NULL; int result = sqlite3_open(SQLITE3_MEM_DB, &externalConnection); ASSERT_EQ(SQLITE_OK, result); SqliteConnection db; db.reset(externalConnection, SqliteConnection::EXTERNAL_CONNECTION); ASSERT_EQ(externalConnection, db.getConnection()); ASSERT_EQ(SqliteConnection::EXTERNAL_CONNECTION, db.getConnectionType()); db.reset(); ASSERT_EQ(NULL, db.getConnection()); result = sqlite3_close(externalConnection); ASSERT_EQ(SQLITE_OK, result); ASSERT_EQ(SQLITE_OK, sqlite3_shutdown()); } TEST(SqliteConnectionTest, resetInternal) { sqlite3* internalConnection = NULL; int result = sqlite3_open(SQLITE3_MEM_DB, &internalConnection); ASSERT_EQ(SQLITE_OK, result); SqliteConnection db; db.reset(internalConnection, SqliteConnection::INTERNAL_CONNECTION); ASSERT_EQ(internalConnection, db.getConnection()); ASSERT_EQ(SqliteConnection::INTERNAL_CONNECTION, db.getConnectionType()); db.reset(); ASSERT_EQ(NULL, db.getConnection()); ASSERT_EQ(SQLITE_OK, sqlite3_shutdown()); } TEST(SqliteConnectionTest, resetDefaultInternal) { sqlite3* internalConnection = NULL; int result = sqlite3_open(SQLITE3_MEM_DB, &internalConnection); ASSERT_EQ(SQLITE_OK, result); SqliteConnection db; db.reset(internalConnection); ASSERT_EQ(internalConnection, db.getConnection()); ASSERT_EQ(SqliteConnection::INTERNAL_CONNECTION, db.getConnectionType()); db.reset(); ASSERT_EQ(NULL, db.getConnection()); ASSERT_EQ(SQLITE_OK, sqlite3_shutdown()); } TEST(SqliteConnectionTest, doubleResetExternal) { sqlite3 *externalConnection1 = NULL; int result = sqlite3_open(SQLITE3_MEM_DB, &externalConnection1); ASSERT_EQ(SQLITE_OK, result); sqlite3 *externalConnection2 = NULL; result = sqlite3_open(SQLITE3_MEM_DB, &externalConnection2); ASSERT_EQ(SQLITE_OK, result); { SqliteConnection db; db.reset(externalConnection1, SqliteConnection::EXTERNAL_CONNECTION); ASSERT_EQ(externalConnection1, db.getConnection()); ASSERT_EQ(SqliteConnection::EXTERNAL_CONNECTION, db.getConnectionType()); db.reset(externalConnection2, SqliteConnection::EXTERNAL_CONNECTION); ASSERT_EQ(externalConnection2, db.getConnection()); ASSERT_EQ(SqliteConnection::EXTERNAL_CONNECTION, db.getConnectionType()); } // db dtor result = sqlite3_close(externalConnection1); ASSERT_EQ(SQLITE_OK, result); result = sqlite3_close(externalConnection2); ASSERT_EQ(SQLITE_OK, result); ASSERT_EQ(SQLITE_OK, sqlite3_shutdown()); } TEST(SqliteConnectionTest, doubleResetInternal) { sqlite3 *internalConnection1 = NULL; int result = sqlite3_open(SQLITE3_MEM_DB, &internalConnection1); ASSERT_EQ(SQLITE_OK, result); sqlite3 *internalConnection2 = NULL; result = sqlite3_open(SQLITE3_MEM_DB, &internalConnection2); ASSERT_EQ(SQLITE_OK, result); { SqliteConnection db; db.reset(internalConnection1); ASSERT_EQ(internalConnection1, db.getConnection()); ASSERT_EQ(SqliteConnection::INTERNAL_CONNECTION, db.getConnectionType()); db.reset(internalConnection2); ASSERT_EQ(internalConnection2, db.getConnection()); ASSERT_EQ(SqliteConnection::INTERNAL_CONNECTION, db.getConnectionType()); } // db dtor ASSERT_EQ(SQLITE_OK, sqlite3_shutdown()); } TEST(SqliteConnectionTest, getConnection) { sqlite3 *internalConnection = NULL; int result = sqlite3_open(SQLITE3_MEM_DB, &internalConnection); ASSERT_EQ(SQLITE_OK, result); SqliteConnection db(internalConnection); ASSERT_EQ(internalConnection, db.getConnection()); db.reset(); ASSERT_EQ(NULL, db.getConnection()); ASSERT_EQ(SQLITE_OK, sqlite3_shutdown()); } TEST(SqliteConnectionTest, getConnectionType) { sqlite3 *internalConnection = NULL; int result = sqlite3_open(SQLITE3_MEM_DB, &internalConnection); ASSERT_EQ(SQLITE_OK, result); SqliteConnection db(internalConnection); ASSERT_EQ(SqliteConnection::INTERNAL_CONNECTION, db.getConnectionType()); sqlite3 *externalConnection = NULL; result = sqlite3_open(SQLITE3_MEM_DB, &externalConnection); ASSERT_EQ(SQLITE_OK, result); db.reset(externalConnection, SqliteConnection::EXTERNAL_CONNECTION); ASSERT_EQ(SqliteConnection::EXTERNAL_CONNECTION, db.getConnectionType()); } TEST(SqliteConnectionTest, reset) { sqlite3 *internalConnection = NULL; int result = sqlite3_open(SQLITE3_MEM_DB, &internalConnection); ASSERT_EQ(SQLITE_OK, result); SqliteConnection db; db.reset(internalConnection); ASSERT_EQ(internalConnection, db.getConnection()); db.reset(); ASSERT_EQ(NULL, db.getConnection()); ASSERT_EQ(SQLITE_OK, sqlite3_shutdown()); } TEST(SqliteConnectionTest, executeUpdate) { sqlite3 *internalConnection = NULL; int result = sqlite3_open(SQLITE3_MEM_DB, &internalConnection); ASSERT_EQ(SQLITE_OK, result); SqliteConnection db(internalConnection); db.executeUpdate("CREATE TABLE Foo AS SELECT 1"); sqlite3* const dbConnection = db.getConnection(); SqliteResultAccumulator resultAcc; sqlite3_exec(dbConnection, "SELECT * FROM Foo", sqliteResultAccumulatorCallback, &resultAcc, NULL); SqliteResultAccumulator::TResult const& accResult = resultAcc.getResult(); ASSERT_EQ(1, accResult.size()); SqliteResultAccumulator::TRow const& row = accResult.front(); ASSERT_EQ(1, row.size()); ASSERT_EQ("1", row.front()); db.reset(); ASSERT_EQ(SQLITE_OK, sqlite3_shutdown()); } TEST(SqliteConnectionTest, executeUpdateOnReadOnlyDatabase) { sqlite3 *internalConnection = NULL; int result = sqlite3_open_v2(SQLITE3_MEM_DB, &internalConnection, SQLITE_OPEN_READONLY, NULL); ASSERT_EQ(SQLITE_OK, result); SqliteConnection db(internalConnection); ASSERT_THROW(db.executeUpdate("CREATE TABLE Foo AS SELECT 1"), SqliteException); } TEST(SqliteConnectionTest, prepareStatement) { sqlite3 *internalConnection = NULL; int result = sqlite3_open(SQLITE3_MEM_DB, &internalConnection); ASSERT_EQ(SQLITE_OK, result); SqliteConnection db(internalConnection); db.executeUpdate("CREATE TABLE Foo AS SELECT 1"); sqlite3_stmt* const statement = db.prepareStatement("SELECT 1"); ASSERT_TRUE(statement != NULL); result = sqlite3_step(statement); ASSERT_EQ(SQLITE_ROW, result); ASSERT_EQ(1, sqlite3_column_count(statement)); const std::string resultString(reinterpret_cast<char const*>(sqlite3_column_text(statement, 0))); ASSERT_EQ("1", resultString); result = sqlite3_step(statement); ASSERT_EQ(SQLITE_DONE, result); result = sqlite3_finalize(statement); ASSERT_EQ(SQLITE_OK, result); db.reset(); ASSERT_EQ(SQLITE_OK, sqlite3_shutdown()); } } // namespace zserio
29.966867
112
0.728415
Klebert-Engineering
e52bf446ef1233cb4737b10c7b4bff5bf6cb606a
2,330
hpp
C++
src/backend/MoveList.hpp
Witek902/Caissa
07bb81e7cae23ea18bb44870d1c1eaa038ab0355
[ "MIT" ]
3
2022-01-11T22:37:06.000Z
2022-01-18T17:40:48.000Z
src/backend/MoveList.hpp
Witek902/Caissa
07bb81e7cae23ea18bb44870d1c1eaa038ab0355
[ "MIT" ]
1
2021-11-12T00:38:30.000Z
2021-11-12T00:38:30.000Z
src/backend/MoveList.hpp
Witek902/Caissa
07bb81e7cae23ea18bb44870d1c1eaa038ab0355
[ "MIT" ]
null
null
null
#pragma once #include "Move.hpp" class MoveList { friend class Position; friend class Search; friend class MoveOrderer; public: struct MoveEntry { Move move; int32_t score; }; static constexpr uint32_t MaxMoves = 255; uint32_t Size() const { return numMoves; } const Move& GetMove(uint32_t index) const { ASSERT(index < numMoves); return moves[index].move; } const MoveEntry& operator [] (uint32_t index) const { ASSERT(index < numMoves); return moves[index]; } MoveEntry& operator [] (uint32_t index) { ASSERT(index < numMoves); return moves[index]; } void RemoveMove(const Move& move); void Clear() { numMoves = 0; } void Push(const Move move) { ASSERT(numMoves < MaxMoves); for (uint32_t i = 0; i < numMoves; ++i) { ASSERT(move != moves[i].move); } uint32_t index = numMoves++; moves[index] = { move, 0 }; } uint32_t AssignTTScores(const TTEntry& ttEntry); void AssignPVScore(const Move pvMove); const Move PickBestMove(uint32_t index, int32_t& outMoveScore) { ASSERT(index < numMoves); int32_t bestScore = INT32_MIN; uint32_t bestMoveIndex = index; for (uint32_t i = index; i < numMoves; ++i) { if (moves[i].score > bestScore) { bestScore = moves[i].score; bestMoveIndex = i; } } if (bestMoveIndex != index) { std::swap(moves[index], moves[bestMoveIndex]); } outMoveScore = moves[index].score; return moves[index].move; } bool HasMove(const Move move) const { for (uint32_t i = 0; i < numMoves; ++i) { if (moves[i].move == move) { return true; } } return false; } bool HasMove(const PackedMove move) const { for (uint32_t i = 0; i < numMoves; ++i) { if (moves[i].move == move) { return true; } } return false; } void Shuffle(); void Print(const Position& pos, bool sorted = true) const; private: uint32_t numMoves = 0; MoveEntry moves[MaxMoves]; };
21.376147
106
0.535193
Witek902
e52ec98333442b65a838b3c7dc916f763f5ec67b
2,821
cpp
C++
EngineTransplant/onscripter-20120712/sardec.cpp
weimingtom/X-moe
8bcca62db18800cb5ac7ad1309535c4c95156eb6
[ "MIT" ]
6
2018-10-12T05:01:49.000Z
2020-11-01T02:47:22.000Z
EngineTransplant/onscripter-20120712/sardec.cpp
weimingtom/X-moe
8bcca62db18800cb5ac7ad1309535c4c95156eb6
[ "MIT" ]
null
null
null
EngineTransplant/onscripter-20120712/sardec.cpp
weimingtom/X-moe
8bcca62db18800cb5ac7ad1309535c4c95156eb6
[ "MIT" ]
3
2017-09-27T17:28:30.000Z
2019-11-21T15:13:57.000Z
/* -*- C++ -*- * * sardec.cpp - SAR archive decoder * * Copyright (c) 2001-2004 Ogapee. All rights reserved. * * ogapee@aqua.dti2.ne.jp * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include "SarReader.h" extern int errno; int main( int argc, char **argv ) { SarReader cSR; unsigned long length, buffer_length = 0; unsigned char *buffer = NULL; char file_name[256], dir_name[256]; unsigned int i, j, count; FILE *fp; struct stat file_stat; if ( argc != 2 ){ fprintf( stderr, "Usage: sardec arc_file\n"); exit(-1); } if (cSR.open( argv[1] ) != 0){ fprintf( stderr, "can't open file %s\n", argv[1] ); exit(-1); } count = cSR.getNumFiles(); SarReader::FileInfo sFI; for ( i=0 ; i<count ; i++ ){ sFI = cSR.getFileByIndex( i ); length = cSR.getFileLength( sFI.name ); if ( length > buffer_length ){ if ( buffer ) delete[] buffer; buffer = new unsigned char[length]; buffer_length = length; } if ( cSR.getFile( sFI.name, buffer ) != length ){ fprintf( stderr, "file %s can't be retrieved\n", sFI.name ); continue; } strcpy( file_name, sFI.name ); for ( j=0 ; j<strlen(file_name) ; j++ ){ if ( file_name[j] == '\\' ){ file_name[j] = '/'; strncpy( dir_name, file_name, j ); dir_name[j] = '\0'; /* If the directory does'nt exist, create it */ if ( stat ( dir_name, &file_stat ) == -1 && errno == ENOENT ) mkdir( dir_name, 00755 ); } } printf("opening %s\n", file_name ); if ( (fp = fopen( file_name, "wb" ) )){ fwrite( buffer, 1, length, fp ); fclose(fp); } else{ printf(" ... falied\n"); } } if ( buffer ) delete[] buffer; exit(0); }
28.785714
77
0.554768
weimingtom
e530686d7270d6309e2924632daac74183c88c65
982
hpp
C++
src/view/facing_dir.hpp
TiWinDeTea/NinjaClown
fdd48e62466f11036fa0360fad2bcb182d6d3352
[ "MIT" ]
2
2020-04-10T14:39:00.000Z
2021-02-11T15:52:16.000Z
src/view/facing_dir.hpp
TiWinDeTea/NinjaClown
fdd48e62466f11036fa0360fad2bcb182d6d3352
[ "MIT" ]
2
2019-12-17T08:50:20.000Z
2020-02-03T09:37:56.000Z
src/view/facing_dir.hpp
TiWinDeTea/NinjaClown
fdd48e62466f11036fa0360fad2bcb182d6d3352
[ "MIT" ]
1
2020-08-19T03:06:52.000Z
2020-08-19T03:06:52.000Z
#ifndef NINJACLOWN_VIEW_FACING_DIR_HPP #define NINJACLOWN_VIEW_FACING_DIR_HPP #include <array> #include <optional> #include <string_view> #include "utils/utils.hpp" namespace view::facing_direction { enum type : unsigned int { N, S, E, W, NE, NW, SE, SW, MAX_VAL }; constexpr std::array values = {N, S, E, W, NE, NW, SE, SW, MAX_VAL}; static_assert(utils::has_all_sorted(values, MAX_VAL), "values array might not contain every enum value"); constexpr std::string_view to_string(facing_direction::type val) noexcept { constexpr std::array<std::string_view, MAX_VAL + 1> direction_map = { "N", "S", "E", "W", "NE", "NW", "SE", "SW", "MAX_VAL", }; return direction_map[val]; } type from_angle(float rad); constexpr std::optional<facing_direction::type> from_string(std::string_view str) noexcept { for (auto val : values) { if (to_string(val) == str) { return val; } } return {}; } } // namespace view::facing_direction #endif //NINJACLOWN_VIEW_FACING_DIR_HPP
26.540541
105
0.709776
TiWinDeTea
e531843510969f3066e08d658b6e9b0b21f32499
8,891
cpp
C++
iterators/program.cpp
MatthewCalligaro/CS70Textbook
c7fb8e2163a0da562972aea37e35f2b5825a9b80
[ "MIT" ]
8
2020-01-24T20:50:59.000Z
2021-08-01T17:57:37.000Z
iterators/program.cpp
cs70-grutoring/CS70Textbook
c7fb8e2163a0da562972aea37e35f2b5825a9b80
[ "MIT" ]
null
null
null
iterators/program.cpp
cs70-grutoring/CS70Textbook
c7fb8e2163a0da562972aea37e35f2b5825a9b80
[ "MIT" ]
1
2020-04-04T17:15:19.000Z
2020-04-04T17:15:19.000Z
/** * \file program.cpp * \copyright Matthew Calligaro * \date January 2020 * \brief A command line program demonstrating the use of iterators */ #include <cassert> #include <iostream> #include <list> #include <string> int main() { std::list<std::string> list = {"alpha", "bravo", "charlie", "delta", "echo"}; std::list<std::string> list2; const std::list<std::string>& clist = list; std::list<double> dlist = {0.0, 1.0, 2.0, 3.0, 4.0}; /***************************************************************************** * Iterator Basics ****************************************************************************/ std::cout << std::endl << ">> Iterator Basics" << std::endl; // If a data structure supports an iterator, it should have a begin method // which returns an iterator pointing to the first element of the data // structure std::list<std::string>::iterator i1 = list.begin(); // operator* returns a reference to the element to which the iterator points std::cout << *i1 << std::endl; // operator-> returns a pointer to the element to which the iterator points std::cout << i1->size() << std::endl; // operator++ moves the iterator to the next element in the data structure ++i1; std::cout << *i1 << std::endl; // For a bidirectional iterator, operator-- moves the iterator to the previous // element in the data structure. A forward iterator need not support // operator--. --i1; std::cout << *i1 << std::endl; // It is undefined behavior to decrement an iterator equal to begin /** * --list.begin(); */ // If a data structure supports an iterator, it should have an end method // which returns an iterator pointing to the past-the-end element of the data // structure. This iterator is equal to an iterator that was pointing // to the last element and then was incremented. std::cout << *(--list.end()) << std::endl; // It is undefined behavior to use the *, ->, or ++ operators on an iterator // equal to end /** * std::list<std::string>::iterator end = list.end(); * *end; * end->size(); * ++end; */ // Two iterators will compare as equal if they point to the same location in // the data structure std::list<std::string>::iterator i2 = list.begin(); std::cout << (i1 == i2) << std::endl; ++i2; std::cout << (i1 == i2) << std::endl; // In an empty data structure, the iterators returned by begin and end must // compare as equal assert(list2.begin() == list2.end()); // This will cause a compile-time error because it compares iterators to // data structures of different types /** * list.begin() == dlist.begin(); */ // It is undefined behavior to compare two iterators pointing to different // data structures of the same type /** * list.begin() == list2.begin(); */ /***************************************************************************** * Default Iterators ****************************************************************************/ // STL data structures must support a default iterator std::list<std::string>::iterator default1; std::list<std::string>::iterator default2; // Two default iterators must be equal assert(default1 == default2); // It is undefined behavior to use the *, ->, ++, or -- operators on a default // iterator /** * *default1; * default1->size(); * ++default1; * --default1; */ // Once we give a default iterator a value, we can use it as normal default1 = list.begin(); ++default1; /***************************************************************************** * iterators vs. const_iterators ****************************************************************************/ std::cout << std::endl << ">> iterators vs const_iterators" << std::endl; // If a data structure supports an iterator, it should have a cbegin method // which returns an const_iterator pointing to the first element of the data // structure std::list<std::string>::const_iterator c1 = list.cbegin(); // If a data structure (or a reference to a data structure) is declared as // const, begin will return a const_iterator rather than an iterator std::list<std::string>::const_iterator c2 = clist.begin(); // A const_iterator is identical to an iterator except that operator* returns // a const reference rather than a reference and operator-> returns a const // pointer rather than a pointer. This means that we cannot use a // const_iterator to modify the elements of the data structure. std::cout << *c1 << std::endl; ++c1; std::cout << c2->substr(1, 3) << std::endl; // These would cause compile-time errors because they attempt to modify an // element of the data structure with a const reference/pointer /** * *c1 = "beta"; * c1->resize(2); */ // Iterators support a constructor and assignment operator which convert an // iterator to a const_iterator std::list<std::string>::const_iterator c3 = i1; c1 = i1; // These will cause compile time errors because Iterators do NOT support // conversion from const_iterator to iterator /** * std::list<std::string>::iterator i3 = c1; * i1 = c1; */ // If we declare an iterator or const_iterator with the const keyword, this // prevents the iterator itself from being changed (such as with ++ or --). // This is unrelated to the iterator/const_iterator distinction. const std::list<std::string>::iterator i4 = list.begin(); const std::list<std::string>::const_iterator c4 = c1; *i4 = "alfa"; std::cout << *c4 << std::endl; std::cout << (c4 == i4) << std::endl; // These will cause compile-time errors because i4 and c4 were declared with // the const keyword so cannot be modified /** * ++i4; * --i4; * c4 = c3; */ /***************************************************************************** * Using Iterators ****************************************************************************/ std::cout << std::endl << ">> Using Iterators" << std::endl; // std::next creates a copy of an iterator and increments (or decrements) the // copy n times without changing the original std::list<std::string>::iterator j1 = list.begin(); std::list<std::string>::iterator j2 = std::next(j1, 4); std::list<std::string>::iterator j3 = std::next(j2, -2); std::cout << *j1 << std::endl; std::cout << *j2 << std::endl; std::cout << *j3 << std::endl; // We can use an iterator to iterate through the elements of a data structure std::cout << std::endl << "For loop:" << std::endl; for (std::list<std::string>::const_iterator i = list.cbegin(); i != list.end(); ++i) { std::cout << *i << std::endl; } std::cout << std::endl; // The range-based for loop automatically iterates through a data structure // using the data structure's iterator. The following range-based for loop // has the exact same behavior as the previous for loop. std::cout << "Ranged-base for loop:" << std::endl; for (std::string str : list) { std::cout << str << std::endl; } std::cout << std::endl; // If a data structure implements an iterator, we can use several standard // library functions on the data structure. For example, std::equal compares // two data structures using their iterators. std::cout << std::equal(list.begin(), list.end(), list2.begin(), list2.end()) << std::endl; // If you are writing your own data structure with an iterator, it is often // easiest to use these standard library functions to implement methods of // your data structure, such as using std::equal for operator== // Sometimes, methods of a data structure will take an iterator as a parameter // and/or return an iterator. For example, std::list::erase takes an iterator // specifying which element to erase and returns an iterator to the element // directly after the element that was erased. std::list<std::string>::iterator j4 = list.erase(j3); std::cout << *j4 << std::endl; /***************************************************************************** * Invalid Iterators ****************************************************************************/ // Methods of a data structure may invalidate existing iterators. For // example, std::list::erase invalidates any iterator pointing to the element // that was erased. std::list<std::string>::iterator k1 = list.begin(); list.erase(list.begin()); // k1 is now invalid. It is undefined behavior to use an invalid iterator // in any way. /** * *k1; * ++k1; * --k1; * k1->size(); * k1 == j1; * std::list<std::string>::iterator k2 = k1; */ // If a method invalidates any iterators, it should explicitly specify which // iterators it invalidates in its documentation. A const method cannot // invalidate any iterators. return 0; }
35.706827
80
0.59982
MatthewCalligaro
e53387adb403d6c6c407a75760b8962b81ac3df6
13,764
cpp
C++
samples/snippets/cpp/VS_Snippets_Wpf/System.Windows.Interop.D3DImage/cpp/renderermanager.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
3,294
2016-10-30T05:27:20.000Z
2022-03-31T15:59:30.000Z
samples/snippets/cpp/VS_Snippets_Wpf/System.Windows.Interop.D3DImage/cpp/renderermanager.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
16,739
2016-10-28T19:41:29.000Z
2022-03-31T22:38:48.000Z
samples/snippets/cpp/VS_Snippets_Wpf/System.Windows.Interop.D3DImage/cpp/renderermanager.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
6,701
2016-10-29T20:56:11.000Z
2022-03-31T12:32:26.000Z
// <snippetRendererManagerCPP> //+----------------------------------------------------------------------------- // // CRendererManager // // Manages the list of CRenderers. Managed code pinvokes into this class // and this class forwards to the appropriate CRenderer. // //------------------------------------------------------------------------------ #include "StdAfx.h" const static TCHAR szAppName[] = TEXT("D3DImageSample"); typedef HRESULT (WINAPI *DIRECT3DCREATE9EXFUNCTION)(UINT SDKVersion, IDirect3D9Ex**); //+----------------------------------------------------------------------------- // // Member: // CRendererManager ctor // //------------------------------------------------------------------------------ CRendererManager::CRendererManager() : m_pD3D(NULL), m_pD3DEx(NULL), m_cAdapters(0), m_hwnd(NULL), m_pCurrentRenderer(NULL), m_rgRenderers(NULL), m_uWidth(1024), m_uHeight(1024), m_uNumSamples(0), m_fUseAlpha(false), m_fSurfaceSettingsChanged(true) { } //+----------------------------------------------------------------------------- // // Member: // CRendererManager dtor // //------------------------------------------------------------------------------ CRendererManager::~CRendererManager() { DestroyResources(); if (m_hwnd) { DestroyWindow(m_hwnd); UnregisterClass(szAppName, NULL); } } //+----------------------------------------------------------------------------- // // Member: // CRendererManager::Create // // Synopsis: // Creates the manager // //------------------------------------------------------------------------------ HRESULT CRendererManager::Create(CRendererManager **ppManager) { HRESULT hr = S_OK; *ppManager = new CRendererManager(); IFCOOM(*ppManager); Cleanup: return hr; } //+----------------------------------------------------------------------------- // // Member: // CRendererManager::EnsureRenderers // // Synopsis: // Makes sure the CRenderer objects exist // //------------------------------------------------------------------------------ HRESULT CRendererManager::EnsureRenderers() { HRESULT hr = S_OK; if (!m_rgRenderers) { IFC(EnsureHWND()); assert(m_cAdapters); m_rgRenderers = new CRenderer*[m_cAdapters]; IFCOOM(m_rgRenderers); ZeroMemory(m_rgRenderers, m_cAdapters * sizeof(m_rgRenderers[0])); for (UINT i = 0; i < m_cAdapters; ++i) { IFC(CTriangleRenderer::Create(m_pD3D, m_pD3DEx, m_hwnd, i, &m_rgRenderers[i])); } // Default to the default adapter m_pCurrentRenderer = m_rgRenderers[0]; } Cleanup: return hr; } //+----------------------------------------------------------------------------- // // Member: // CRendererManager::EnsureHWND // // Synopsis: // Makes sure an HWND exists if we need it // //------------------------------------------------------------------------------ // <snippetRendererManager_EnsureHWND> HRESULT CRendererManager::EnsureHWND() { HRESULT hr = S_OK; if (!m_hwnd) { WNDCLASS wndclass; wndclass.style = CS_HREDRAW | CS_VREDRAW; wndclass.lpfnWndProc = DefWindowProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = NULL; wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH); wndclass.lpszMenuName = NULL; wndclass.lpszClassName = szAppName; if (!RegisterClass(&wndclass)) { IFC(E_FAIL); } m_hwnd = CreateWindow(szAppName, TEXT("D3DImageSample"), WS_OVERLAPPEDWINDOW, 0, // Initial X 0, // Initial Y 0, // Width 0, // Height NULL, NULL, NULL, NULL); } Cleanup: return hr; } // </snippetRendererManager_EnsureHWND> //+----------------------------------------------------------------------------- // // Member: // CRendererManager::EnsureD3DObjects // // Synopsis: // Makes sure the D3D objects exist // //------------------------------------------------------------------------------ // <snippetRendererManager_EnsureD3DObjects> HRESULT CRendererManager::EnsureD3DObjects() { HRESULT hr = S_OK; HMODULE hD3D = NULL; if (!m_pD3D) { hD3D = LoadLibrary(TEXT("d3d9.dll")); DIRECT3DCREATE9EXFUNCTION pfnCreate9Ex = (DIRECT3DCREATE9EXFUNCTION)GetProcAddress(hD3D, "Direct3DCreate9Ex"); if (pfnCreate9Ex) { IFC((*pfnCreate9Ex)(D3D_SDK_VERSION, &m_pD3DEx)); IFC(m_pD3DEx->QueryInterface(__uuidof(IDirect3D9), reinterpret_cast<void **>(&m_pD3D))); } else { m_pD3D = Direct3DCreate9(D3D_SDK_VERSION); if (!m_pD3D) { IFC(E_FAIL); } } m_cAdapters = m_pD3D->GetAdapterCount(); } Cleanup: if (hD3D) { FreeLibrary(hD3D); } return hr; } // </snippetRendererManager_EnsureD3DObjects> //+----------------------------------------------------------------------------- // // Member: // CRendererManager::CleanupInvalidDevices // // Synopsis: // Checks to see if any devices are bad and if so, deletes all resources // // We could delete resources and wait for D3DERR_DEVICENOTRESET and reset // the devices, but if the device is lost because of an adapter order // change then our existing D3D objects would have stale adapter // information. We'll delete everything to be safe rather than sorry. // //------------------------------------------------------------------------------ void CRendererManager::CleanupInvalidDevices() { for (UINT i = 0; i < m_cAdapters; ++i) { if (FAILED(m_rgRenderers[i]->CheckDeviceState())) { DestroyResources(); break; } } } //+----------------------------------------------------------------------------- // // Member: // CRendererManager::GetBackBufferNoRef // // Synopsis: // Returns the surface of the current renderer without adding a reference // // This can return NULL if we're in a bad device state. // //------------------------------------------------------------------------------ HRESULT CRendererManager::GetBackBufferNoRef(IDirect3DSurface9 **ppSurface) { HRESULT hr = S_OK; // Make sure we at least return NULL *ppSurface = NULL; CleanupInvalidDevices(); IFC(EnsureD3DObjects()); // // Even if we never render to another adapter, this sample creates devices // and resources on each one. This is a potential waste of video memory, // but it guarantees that we won't have any problems (e.g. out of video // memory) when switching to render on another adapter. In your own code // you may choose to delay creation but you'll need to handle the issues // that come with it. // IFC(EnsureRenderers()); if (m_fSurfaceSettingsChanged) { if (FAILED(TestSurfaceSettings())) { IFC(E_FAIL); } for (UINT i = 0; i < m_cAdapters; ++i) { IFC(m_rgRenderers[i]->CreateSurface(m_uWidth, m_uHeight, m_fUseAlpha, m_uNumSamples)); } m_fSurfaceSettingsChanged = false; } if (m_pCurrentRenderer) { *ppSurface = m_pCurrentRenderer->GetSurfaceNoRef(); } Cleanup: // If we failed because of a bad device, ignore the failure for now and // we'll clean up and try again next time. if (hr == D3DERR_DEVICELOST) { hr = S_OK; } return hr; } //+----------------------------------------------------------------------------- // // Member: // CRendererManager::TestSurfaceSettings // // Synopsis: // Checks to see if our current surface settings are allowed on all // adapters. // //------------------------------------------------------------------------------ // <snippetRendererManager_TestSurfaceSettings> HRESULT CRendererManager::TestSurfaceSettings() { HRESULT hr = S_OK; D3DFORMAT fmt = m_fUseAlpha ? D3DFMT_A8R8G8B8 : D3DFMT_X8R8G8B8; // // We test all adapters because because we potentially use all adapters. // But even if this sample only rendered to the default adapter, you // should check all adapters because WPF may move your surface to // another adapter for you! // for (UINT i = 0; i < m_cAdapters; ++i) { // Can we get HW rendering? IFC(m_pD3D->CheckDeviceType( i, D3DDEVTYPE_HAL, D3DFMT_X8R8G8B8, fmt, TRUE )); // Is the format okay? IFC(m_pD3D->CheckDeviceFormat( i, D3DDEVTYPE_HAL, D3DFMT_X8R8G8B8, D3DUSAGE_RENDERTARGET | D3DUSAGE_DYNAMIC, // We'll use dynamic when on XP D3DRTYPE_SURFACE, fmt )); // D3DImage only allows multisampling on 9Ex devices. If we can't // multisample, overwrite the desired number of samples with 0. if (m_pD3DEx && m_uNumSamples > 1) { assert(m_uNumSamples <= 16); if (FAILED(m_pD3D->CheckDeviceMultiSampleType( i, D3DDEVTYPE_HAL, fmt, TRUE, static_cast<D3DMULTISAMPLE_TYPE>(m_uNumSamples), NULL ))) { m_uNumSamples = 0; } } else { m_uNumSamples = 0; } } Cleanup: return hr; } // </snippetRendererManager_TestSurfaceSettings> //+----------------------------------------------------------------------------- // // Member: // CRendererManager::DestroyResources // // Synopsis: // Delete all D3D resources // //------------------------------------------------------------------------------ void CRendererManager::DestroyResources() { SAFE_RELEASE(m_pD3D); SAFE_RELEASE(m_pD3DEx); for (UINT i = 0; i < m_cAdapters; ++i) { delete m_rgRenderers[i]; } delete [] m_rgRenderers; m_rgRenderers = NULL; m_pCurrentRenderer = NULL; m_cAdapters = 0; m_fSurfaceSettingsChanged = true; } //+----------------------------------------------------------------------------- // // Member: // CRendererManager::SetSize // // Synopsis: // Update the size of the surface. Next render will create a new surface. // //------------------------------------------------------------------------------ void CRendererManager::SetSize(UINT uWidth, UINT uHeight) { if (uWidth != m_uWidth || uHeight != m_uHeight) { m_uWidth = uWidth; m_uHeight = uHeight; m_fSurfaceSettingsChanged = true; } } //+----------------------------------------------------------------------------- // // Member: // CRendererManager::SetAlpha // // Synopsis: // Update the format of the surface. Next render will create a new surface. // //------------------------------------------------------------------------------ void CRendererManager::SetAlpha(bool fUseAlpha) { if (fUseAlpha != m_fUseAlpha) { m_fUseAlpha = fUseAlpha; m_fSurfaceSettingsChanged = true; } } //+----------------------------------------------------------------------------- // // Member: // CRendererManager::SetNumDesiredSamples // // Synopsis: // Update the MSAA settings of the surface. Next render will create a // new surface. // //------------------------------------------------------------------------------ void CRendererManager::SetNumDesiredSamples(UINT uNumSamples) { if (m_uNumSamples != uNumSamples) { m_uNumSamples = uNumSamples; m_fSurfaceSettingsChanged = true; } } //+----------------------------------------------------------------------------- // // Member: // CRendererManager::SetAdapter // // Synopsis: // Update the current renderer. Next render will use the new renderer. // //------------------------------------------------------------------------------ // <snippetRendererManager_SetAdapter> void CRendererManager::SetAdapter(POINT screenSpacePoint) { CleanupInvalidDevices(); // // After CleanupInvalidDevices, we may not have any D3D objects. Rather than // recreate them here, ignore the adapter update and wait for render to recreate. // if (m_pD3D && m_rgRenderers) { HMONITOR hMon = MonitorFromPoint(screenSpacePoint, MONITOR_DEFAULTTONULL); for (UINT i = 0; i < m_cAdapters; ++i) { if (hMon == m_pD3D->GetAdapterMonitor(i)) { m_pCurrentRenderer = m_rgRenderers[i]; break; } } } } // </snippetRendererManager_SetAdapter> //+----------------------------------------------------------------------------- // // Member: // CRendererManager::Render // // Synopsis: // Forward to the current renderer // //------------------------------------------------------------------------------ HRESULT CRendererManager::Render() { return m_pCurrentRenderer ? m_pCurrentRenderer->Render() : S_OK; } // </snippetRendererManagerCPP>
26.571429
118
0.483944
BaruaSourav
e53d8adb3787169e5e91f36be85233292251a14f
2,501
cpp
C++
src/CQDataFrameSVG.cpp
colinw7/CQDataFrame
bc82952dbe9f9a3fc79cc274f4c0ee97abcf0d5e
[ "MIT" ]
1
2021-12-23T02:25:36.000Z
2021-12-23T02:25:36.000Z
src/CQDataFrameSVG.cpp
colinw7/CQDataFrame
bc82952dbe9f9a3fc79cc274f4c0ee97abcf0d5e
[ "MIT" ]
null
null
null
src/CQDataFrameSVG.cpp
colinw7/CQDataFrame
bc82952dbe9f9a3fc79cc274f4c0ee97abcf0d5e
[ "MIT" ]
null
null
null
#include <CQDataFrameSVG.h> #include <QSvgRenderer> #include <QVBoxLayout> namespace CQDataFrame { SVGWidget:: SVGWidget(Area *area, const FileText &fileText) : Widget(area), fileText_(fileText) { setObjectName("svg"); } QString SVGWidget:: id() const { return QString("svg.%1").arg(pos()); } bool SVGWidget:: getNameValue(const QString &name, QVariant &value) const { return Widget::getNameValue(name, value); } bool SVGWidget:: setNameValue(const QString &name, const QVariant &value) { return Widget::setNameValue(name, value); } void SVGWidget:: draw(QPainter *painter, int /*dx*/, int /*dy*/) { QSvgRenderer renderer; if (fileText_.type == FileText::Type::TEXT) { QByteArray ba(fileText_.value.toLatin1()); renderer.load(ba); } else { renderer.load(fileText_.value); } renderer.render(painter, contentsRect()); } QSize SVGWidget:: contentsSizeHint() const { return QSize(-1, 400); } QSize SVGWidget:: contentsSize() const { QSvgRenderer renderer; if (fileText_.type == FileText::Type::TEXT) { QByteArray ba(fileText_.value.toLatin1()); renderer.load(ba); } else { renderer.load(fileText_.value); } auto s = renderer.defaultSize(); int width = s.width (); int height = s.height(); if (this->width () > 0) width = this->width (); if (this->height() > 0) height = this->height(); return QSize(width, height); } //------ void SVGTclCmd:: addArgs(CQTclCmd::CmdArgs &argv) { addArg(argv, "-file", ArgType::String, "svg file"); addArg(argv, "-text", ArgType::String, "svg text"); } QStringList SVGTclCmd:: getArgValues(const QString &option, const NameValueMap &nameValueMap) { QStringList strs; if (option == "file") { auto p = nameValueMap.find("file"); QString file = (p != nameValueMap.end() ? (*p).second : ""); return Frame::s_completeFile(file); } return strs; } bool SVGTclCmd:: exec(CQTclCmd::CmdArgs &argv) { addArgs(argv); bool rc; if (! argv.parse(rc)) return rc; //--- SVGWidget *widget = nullptr; auto *area = frame_->larea(); if (argv.hasParseArg("file")) { auto file = argv.getParseStr("file"); widget = makeWidget<SVGWidget>(area, FileText(FileText::Type::FILENAME, file)); } else if (argv.hasParseArg("text")) { auto text = argv.getParseStr("text"); widget = makeWidget<SVGWidget>(area, FileText(FileText::Type::TEXT, text)); } else return false; return frame_->setCmdRc(widget->id()); } //------ }
16.562914
83
0.652139
colinw7
e5409732acd3c4b8aeace4d355997d0ce71657a6
2,115
cpp
C++
linear_structures/string/1236_web-crawler.cpp
b1tank/leetcode
0b71eb7a4f52291ff072b1280d6b76e68f7adfee
[ "MIT" ]
null
null
null
linear_structures/string/1236_web-crawler.cpp
b1tank/leetcode
0b71eb7a4f52291ff072b1280d6b76e68f7adfee
[ "MIT" ]
null
null
null
linear_structures/string/1236_web-crawler.cpp
b1tank/leetcode
0b71eb7a4f52291ff072b1280d6b76e68f7adfee
[ "MIT" ]
null
null
null
// Author: b1tank // Email: b1tank@outlook.com //================================= /* 1236_web-crawler LeetCode Solution: - s.substr(0, s.find('/', 7)) */ #include <iostream> #include <sstream> // stringstream, istringstream, ostringstream #include <string> // to_string(), stoi() #include <cctype> // isalnum, isalpha, isdigit, islower, isupper, isspace; toupper, tolower #include <climits> // INT_MAX 2147483647 #include <cmath> // pow(3.0, 4.0) #include <cstdlib> // rand() % 100 + 1 #include <vector> #include <stack> #include <queue> #include <deque> #include <unordered_set> // unordered_set, unordered_multiset #include <set> // set, multiset #include <unordered_map> // unordered_map, unordered_multimap #include <map> // map, multimap #include <utility> // pair<> #include <tuple> // tuple<> #include <algorithm> // reverse, sort, transform, find, remove, count, count_if #include <memory> // shared_ptr<>, make_shared<> #include <stdexcept> // invalid_argument using namespace std; /** * // This is the HtmlParser's API interface. * // You should not implement it, or speculate about its implementation * class HtmlParser { * public: * vector<string> getUrls(string url); * }; */ class Solution { public: vector<string> crawl(string startUrl, HtmlParser htmlParser) { vector<string> res; queue<string> q; q.push(startUrl); unordered_set<string> visited; string hostname = startUrl.substr(7, startUrl.find('/', 7) - 7); // nice use of find and substr to extract something while (!q.empty()) { string cur = q.front(); q.pop(); visited.insert(cur); res.push_back(cur); vector<string> ns = htmlParser.getUrls(cur); for (auto& n : ns) { if (n.find(hostname) != string::npos && visited.find(n) == visited.end()) { // find substr in a string q.push(n); visited.insert(n); } } } return res; } };
31.567164
125
0.585343
b1tank
e5418770bc36e7c4c9b6d8dadd22b410d35e7e0f
29,091
cpp
C++
LJ_Argon_MD2.cpp
dc1394/LJ_Argon_MD2
d010df2563541008eb0bf76a382537038ded3e6f
[ "BSD-2-Clause" ]
null
null
null
LJ_Argon_MD2.cpp
dc1394/LJ_Argon_MD2
d010df2563541008eb0bf76a382537038ded3e6f
[ "BSD-2-Clause" ]
null
null
null
LJ_Argon_MD2.cpp
dc1394/LJ_Argon_MD2
d010df2563541008eb0bf76a382537038ded3e6f
[ "BSD-2-Clause" ]
1
2018-08-05T21:18:09.000Z
2018-08-05T21:18:09.000Z
/*! \file LJ_Argon_MD.cpp \brief 分子動力学シミュレーションを描画する Copyright © 2015 @dc1394 All Rights Reserved. This software is released under the BSD 2-Clause License. */ #include "DXUT.h" #include "SDKmisc.h" #include "DXUTcamera.h" #include "DXUTgui.h" #include "DXUTsettingsDlg.h" #include "DXUTShapes.h" #include "moleculardynamics/Ar_moleculardynamics.h" #include "utility/utility.h" #include <array> // for std::array #include <memory> // for std::unique_ptr #include <vector> // for std::vector #include <boost/assert.hpp> // for BOOST_ASSERT #include <boost/cast.hpp> // for boost::numeric_cast #include <boost/format.hpp> // for boost::wformat //! A function. /*! UIに変更があったときに呼ばれるコールバック関数 */ void CALLBACK OnGUIEvent(UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext); //! A function. /*! 球のメッシュを生成する \param pd3dDevice Direct3Dのデバイス */ void CreateSphereMesh(ID3D10Device* pd3dDevice); //! A function. /*! 箱を描画する \param pd3dDevice Direct3Dのデバイス */ void RenderBox(ID3D10Device* pd3dDevice); //! A function. /*! 画面の左上に情報を表示する \param pd3dDevice Direct3Dのデバイス */ void RenderText(ID3D10Device* pd3dDevice); //! A function. /*! UIを配置する */ void SetUI(); //! A global variable (constant). /*! 色の比率 */ static auto const COLORRATIO = 0.025f; //! A global variable (constant). /*! 格子定数の比率 */ static auto const LATTICERATIO = 50.0; //! A global variable (constant). /*! インデックスバッファの個数 */ static auto const NUMINDEXBUFFER = 16U; //! A global variable (constant). /*! 頂点バッファの個数 */ static auto const NUMVERTEXBUFFER = 8U; //! A global variable (constant). /*! 頂点バッファの個数 */ static auto const TINY = 1.0E-30f; //! A global variable (constant). /*! 画面サイズ(高さ) */ static auto const WINDOWHEIGHT = 960; //! A global variable (constant). /*! 画面サイズ(幅) */ static auto const WINDOWWIDTH = 1280; //! A global variable. /*! 分子動力学シミュレーションのオブジェクト */ moleculardynamics::Ar_moleculardynamics armd; //! A global variable. /*! 箱の色 */ D3DXVECTOR4 boxColor(1.0f, 1.0f, 1.0f, 1.0f); //! A global variable. /*! バッファー リソース */ D3D10_BUFFER_DESC bd; //! A global variable. /*! 背景の色 */ D3DXVECTOR4 clearColor(0.176f, 0.196f, 0.667f, 1.0f); //! A global variable. /*! Font for drawing text */ std::unique_ptr<ID3DX10Font, utility::Safe_Release<ID3DX10Font>> font; //! A global variable. /*! 格子定数が変更されたことを通知するフラグ */ bool modLatconst = false; //! A global variable. /*! スーパーセルが変更されたことを通知するフラグ */ bool modNc = false; //! A global variable. /*! ブレンディング・ステート */ std::unique_ptr<ID3D10BlendState, utility::Safe_Release<ID3D10BlendState>> pBlendStateNoBlend; //! A global variable. /*! エフェクト=シェーダプログラムを読ませるところ */ std::unique_ptr<ID3D10Effect, utility::Safe_Release<ID3D10Effect>> pEffect; //! A global variable. /*! インデックスバッファ */ std::unique_ptr<ID3D10Buffer, utility::Safe_Release<ID3D10Buffer>> pIndexBuffer; //! A global variable. /*! 入力レイアウト インターフェイス */ std::unique_ptr<ID3D10InputLayout, utility::Safe_Release<ID3D10InputLayout>> pInputLayout; //! A global variable. /*! メッシュへのスマートポインタが格納された可変長配列 */ std::vector<std::unique_ptr<ID3DX10Mesh, utility::Safe_Release<ID3DX10Mesh>>> pmeshvec; //! A global variable. /*! 頂点バッファ */ std::unique_ptr<ID3D10Buffer, utility::Safe_Release<ID3D10Buffer>> pVertexBuffer; //! A global variable. /*! 球の色 */ D3DXVECTOR4 sphereColor(1.0f, 0.0f, 1.0f, 1.0f); //! A global variable. /*! Sprite for batching text drawing */ std::unique_ptr<ID3DX10Sprite, utility::Safe_Release<ID3DX10Sprite>> sprite; //! A global variable. /*! テキスト表示用 */ std::unique_ptr<CDXUTTextHelper, utility::Safe_Delete<CDXUTTextHelper>> txthelper; //! A global variable. /*! A model viewing camera */ CModelViewerCamera g_Camera; //! A global variable. /*! manager for shared resources of dialogs */ CDXUTDialogResourceManager g_DialogResourceManager; //! A global variable. /*! Device settings dialog */ CD3DSettingsDlg g_D3DSettingsDlg; //! A global variable. /*! manages the 3D UI */ CDXUTDialog g_HUD; //! A global variable. /*! */ ID3D10EffectVectorVariable* g_pColorVariable = nullptr; //! A global variable. /*! */ ID3D10EffectMatrixVariable* g_pProjectionVariable = nullptr; //! A global variable. /*! */ ID3D10EffectTechnique* g_pRender = nullptr; //! A global variable. /*! */ ID3D10EffectMatrixVariable* g_pViewVariable = nullptr; //! A global variable. /*! */ ID3D10EffectMatrixVariable* g_pWorldVariable = nullptr; //! A global variable. /*! ビュー行列 */ D3DXMATRIX g_View; //-------------------------------------------------------------------------------------- // Structures //-------------------------------------------------------------------------------------- struct SimpleVertex { D3DXVECTOR3 Pos; }; //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- #define IDC_TOGGLEFULLSCREEN 1 #define IDC_CHANGEDEVICE 2 #define IDC_RECALC 3 #define IDC_OUTPUT 4 #define IDC_OUTPUT2 5 #define IDC_OUTPUT3 6 #define IDC_OUTPUT4 7 #define IDC_OUTPUT5 8 #define IDC_SLIDER 9 #define IDC_SLIDER2 10 #define IDC_SLIDER3 11 #define IDC_RADIOA 12 #define IDC_RADIOB 13 #define IDC_RADIOC 14 #define IDC_RADIOD 15 #define IDC_RADIOE 16 //-------------------------------------------------------------------------------------- // Initialize the app //-------------------------------------------------------------------------------------- void InitApp() { g_D3DSettingsDlg.Init(&g_DialogResourceManager); g_HUD.Init(&g_DialogResourceManager); g_HUD.SetCallback(OnGUIEvent); SetUI(); } //-------------------------------------------------------------------------------------- // Render the scene using the D3D10 device //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10FrameRender( ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ) { if (g_D3DSettingsDlg.IsActive()) { auto pRTV = DXUTGetD3D10RenderTargetView(); pd3dDevice->ClearRenderTargetView(pRTV, clearColor); g_D3DSettingsDlg.OnRender(fElapsedTime); return; } else { if (modLatconst) { RenderBox(pd3dDevice); modLatconst = false; } if (modNc) { CreateSphereMesh(pd3dDevice); RenderBox(pd3dDevice); modNc = false; } armd.runCalc(); // Clear render target and the depth stencil pd3dDevice->ClearRenderTargetView(DXUTGetD3D10RenderTargetView(), clearColor); pd3dDevice->ClearDepthStencilView(DXUTGetD3D10DepthStencilView(), D3D10_CLEAR_DEPTH, 1.0, 0); // Update variables g_pWorldVariable->SetMatrix(reinterpret_cast<float *>(const_cast<D3DXMATRIX *>(&(*g_Camera.GetWorldMatrix())))); g_pViewVariable->SetMatrix(reinterpret_cast<float *>(const_cast<D3DXMATRIX *>(&(*g_Camera.GetViewMatrix())))); g_pProjectionVariable->SetMatrix(reinterpret_cast<float *>(const_cast<D3DXMATRIX *>(&(*g_Camera.GetProjMatrix())))); D3D10_TECHNIQUE_DESC techDesc; g_pRender->GetDesc(&techDesc); g_pColorVariable->SetFloatVector(boxColor); // Set vertex buffer auto const stride = sizeof(SimpleVertex); auto const offset = 0U; auto const pVertexBuffertmp2 = pVertexBuffer.get(); pd3dDevice->IASetVertexBuffers(0, 1, &pVertexBuffertmp2, reinterpret_cast<UINT const *>(&stride), &offset); // Set index buffer pd3dDevice->IASetIndexBuffer(pIndexBuffer.get(), DXGI_FORMAT_R32_UINT, 0); // Set primitive topology pd3dDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP); for (auto p = 0U; p < techDesc.Passes; p++) { g_pRender->GetPassByIndex(p)->Apply(0); pd3dDevice->DrawIndexed(NUMINDEXBUFFER, 0, 0); } auto const pos = boost::numeric_cast<float>(armd.periodiclen()) * 0.5f; auto const size = pmeshvec.size(); for (auto i = 0U; i < size; i++) { auto color = sphereColor; auto const rcolor = COLORRATIO * armd.getForce(i); color.x = rcolor > 1.0f ? 1.0f : rcolor; g_pColorVariable->SetFloatVector(color); D3DXMATRIX World; D3DXMatrixTranslation( &World, boost::numeric_cast<float>(armd.Atoms()[i].r[0]) - pos, boost::numeric_cast<float>(armd.Atoms()[i].r[1]) - pos, boost::numeric_cast<float>(armd.Atoms()[i].r[2]) - pos); D3DXMatrixMultiply(&World, &(*g_Camera.GetWorldMatrix()), &World); // Update variables auto mWorld = World * (*g_Camera.GetWorldMatrix()); g_pWorldVariable->SetMatrix(reinterpret_cast<float *>(&mWorld)); UINT NumSubsets; pmeshvec[i]->GetAttributeTable(nullptr, &NumSubsets); for (auto p = 0U; p < techDesc.Passes; p++) { g_pRender->GetPassByIndex(p)->Apply(0); for (auto s = 0U; s < NumSubsets; s++) { pmeshvec[i]->DrawSubset(s); } } } DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, L"HUD / Stats"); g_HUD.OnRender(fElapsedTime); RenderText(pd3dDevice); DXUT_EndPerfEvent(); } } //-------------------------------------------------------------------------------------- // Reject any D3D10 devices that aren't acceptable by returning false //-------------------------------------------------------------------------------------- bool CALLBACK IsD3D10DeviceAcceptable( UINT Adapter, UINT Output, D3D10_DRIVER_TYPE DeviceType, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ) { return true; } //-------------------------------------------------------------------------------------- // Called right before creating a D3D9 or D3D10 device, allowing the app to modify the device settings as needed //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ) { return true; } //-------------------------------------------------------------------------------------- // Create any D3D10 resources that aren't dependant on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D10CreateDevice( ID3D10Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr = S_OK; V_RETURN(g_DialogResourceManager.OnD3D10CreateDevice(pd3dDevice)); V_RETURN(g_D3DSettingsDlg.OnD3D10CreateDevice(pd3dDevice)); ID3DX10Font * fonttemp; V_RETURN(D3DX10CreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial", &fonttemp)); font.reset(fonttemp); ID3DX10Sprite * spritetmp; V_RETURN(D3DX10CreateSprite(pd3dDevice, 512, &spritetmp)); sprite.reset(spritetmp); txthelper.reset(new CDXUTTextHelper(nullptr, nullptr, font.get(), sprite.get(), 15)); // Find the D3DX effect file std::array<WCHAR, MAX_PATH> str; V_RETURN( DXUTFindDXSDKMediaFileCch( str.data(), MAX_PATH, L"LJ_Argon_MD2.fx" ) ); auto dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) dwShaderFlags |= D3D10_SHADER_DEBUG; #endif ID3D10Effect * pEffecttmp; V_RETURN( D3DX10CreateEffectFromFile( str.data(), nullptr, nullptr, "fx_4_0", dwShaderFlags, 0, pd3dDevice, nullptr, nullptr, &pEffecttmp, nullptr, nullptr) ); pEffect.reset(pEffecttmp); // Obtain the technique g_pRender = pEffect->GetTechniqueByName( "Render" ); // Obtain the variables g_pWorldVariable = pEffect->GetVariableByName( "World" )->AsMatrix(); g_pViewVariable = pEffect->GetVariableByName( "View" )->AsMatrix(); g_pProjectionVariable = pEffect->GetVariableByName( "Projection" )->AsMatrix(); g_pColorVariable = pEffect->GetVariableByName( "Color" )->AsVector(); // Create an input layout D3D10_INPUT_ELEMENT_DESC const layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 }, }; D3D10_PASS_DESC PassDesc; g_pRender->GetPassByIndex( 0 )->GetDesc( &PassDesc ); ID3D10InputLayout * pInputLayouttmp; V_RETURN( pd3dDevice->CreateInputLayout( layout, sizeof(layout) / sizeof(layout[0]), PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &pInputLayouttmp) ); pInputLayout.reset(pInputLayouttmp); pd3dDevice->IASetInputLayout(pInputLayout.get()); D3D10_BLEND_DESC BlendState; ZeroMemory(&BlendState, sizeof(D3D10_BLEND_DESC)); BlendState.BlendEnable[0] = FALSE; BlendState.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL; ID3D10BlendState * pBlendStateNoBlendtmp = nullptr; pd3dDevice->CreateBlendState(&BlendState, &pBlendStateNoBlendtmp); pBlendStateNoBlend.reset(pBlendStateNoBlendtmp); RenderBox(pd3dDevice); CreateSphereMesh(pd3dDevice); D3DXVECTOR3 vEye(0.0f, 115.0f, 115.0f); D3DXVECTOR3 vLook(0.0f, 0.0f, 0.0f); D3DXVECTOR3 const Up(0.0f, 1.0f, 0.0f); D3DXMatrixLookAtLH(&g_View, &vEye, &vLook, &Up); // Update Variables that never change g_pViewVariable->SetMatrix(reinterpret_cast<float *>(&g_View)); g_Camera.SetViewParams(&vEye, &vLook); return S_OK; } //-------------------------------------------------------------------------------------- // Create any D3D10 resources that depend on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D10ResizedSwapChain( ID3D10Device* pd3dDevice, IDXGISwapChain *pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; V_RETURN(g_DialogResourceManager.OnD3D10ResizedSwapChain(pd3dDevice, pBackBufferSurfaceDesc)); V_RETURN(g_D3DSettingsDlg.OnD3D10ResizedSwapChain(pd3dDevice, pBackBufferSurfaceDesc)); g_HUD.SetLocation(pBackBufferSurfaceDesc->Width - 170, 0); g_HUD.SetSize(170, 170); auto const fAspectRatio = static_cast<float>(pBackBufferSurfaceDesc->Width) / static_cast<float>(pBackBufferSurfaceDesc->Height); g_Camera.SetProjParams(D3DX_PI / 4, fAspectRatio, 0.1f, 1000.0f); g_Camera.SetWindow(pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height); return S_OK; } //-------------------------------------------------------------------------------------- // Handle updates to the scene. This is called regardless of which D3D API is used //-------------------------------------------------------------------------------------- void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ) { g_Camera.FrameMove(fElapsedTime); } //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- void CALLBACK OnGUIEvent(UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext) { switch (nControlID) { case IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen(); break; case IDC_CHANGEDEVICE: g_D3DSettingsDlg.SetActive(!g_D3DSettingsDlg.IsActive()); break; case IDC_RECALC: armd.recalc(); break; case IDC_SLIDER: armd.setTgiven(static_cast<double>((reinterpret_cast<CDXUTSlider *>(pControl))->GetValue())); break; case IDC_SLIDER2: armd.setScale(static_cast<double>((reinterpret_cast<CDXUTSlider *>(pControl))->GetValue()) / LATTICERATIO); modLatconst = true; break; case IDC_SLIDER3: armd.setNc(reinterpret_cast<CDXUTSlider *>(pControl)->GetValue()); modNc = true; break; case IDC_RADIOA: armd.setEnsemble(moleculardynamics::EnsembleType::NVT); break; case IDC_RADIOB: armd.setEnsemble(moleculardynamics::EnsembleType::NVE); break; case IDC_RADIOC: armd.setTempContMethod(moleculardynamics::TempControlMethod::LANGEVIN); break; case IDC_RADIOD: armd.setTempContMethod(moleculardynamics::TempControlMethod::NOSE_HOOVER); break; case IDC_RADIOE: armd.setTempContMethod(moleculardynamics::TempControlMethod::VELOCITY); break; default: break; } } //-------------------------------------------------------------------------------------- // Release D3D10 resources created in OnD3D10ResizedSwapChain //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10ReleasingSwapChain( void* pUserContext ) { g_DialogResourceManager.OnD3D10ReleasingSwapChain(); } //-------------------------------------------------------------------------------------- // Release D3D10 resources created in OnD3D10CreateDevice //-------------------------------------------------------------------------------------- void CALLBACK OnD3D10DestroyDevice( void* pUserContext ) { font.reset(); pBlendStateNoBlend.reset(); pEffect.reset(); pInputLayout.reset(); pIndexBuffer.reset(); pVertexBuffer.reset(); sprite.reset(); txthelper.reset(); for (auto & pmesh : pmeshvec) { pmesh.reset(); } g_DialogResourceManager.OnD3D10DestroyDevice(); g_D3DSettingsDlg.OnD3D10DestroyDevice(); DXUTGetGlobalResourceCache().OnDestroyDevice(); } //-------------------------------------------------------------------------------------- // Handle messages to the application //-------------------------------------------------------------------------------------- LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ) { // Pass messages to dialog resource manager calls so GUI state is updated correctly *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam); if (*pbNoFurtherProcessing) return 0; // Pass messages to settings dialog if its active if (g_D3DSettingsDlg.IsActive()) { g_D3DSettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam); return 0; } // Give the dialogs a chance to handle the message first *pbNoFurtherProcessing = g_HUD.MsgProc(hWnd, uMsg, wParam, lParam); if (*pbNoFurtherProcessing) return 0; g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam); return 0; } //-------------------------------------------------------------------------------------- // Handle key presses //-------------------------------------------------------------------------------------- void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ) { } //-------------------------------------------------------------------------------------- // Handle mouse button presses //-------------------------------------------------------------------------------------- void CALLBACK OnMouse( bool bLeftButtonDown, bool bRightButtonDown, bool bMiddleButtonDown, bool bSideButton1Down, bool bSideButton2Down, int nMouseWheelDelta, int xPos, int yPos, void* pUserContext ) { } //-------------------------------------------------------------------------------------- // Call if device was removed. Return true to find a new device, false to quit //-------------------------------------------------------------------------------------- bool CALLBACK OnDeviceRemoved( void* pUserContext ) { return true; } void CreateSphereMesh(ID3D10Device* pd3dDevice) { using namespace moleculardynamics; auto const size = armd.NumAtom(); pmeshvec.resize(size); for (auto & pmesh : pmeshvec) { ID3DX10Mesh * pmeshtmp = nullptr; DXUTCreateSphere( pd3dDevice, static_cast<float>(Ar_moleculardynamics::VDW_RADIUS / Ar_moleculardynamics::SIGMA), 16, 16, &pmeshtmp); pmesh.reset(pmeshtmp); } } void RenderBox(ID3D10Device* pd3dDevice) { auto const pos = boost::numeric_cast<float>(armd.periodiclen()) * 0.5f; // Create vertex buffer std::array<SimpleVertex, NUMVERTEXBUFFER> const vertices = { D3DXVECTOR3(-pos, pos, -pos), D3DXVECTOR3(pos, pos, -pos), D3DXVECTOR3(pos, pos, pos), D3DXVECTOR3(-pos, pos, pos), D3DXVECTOR3(-pos, -pos, -pos), D3DXVECTOR3(pos, -pos, -pos), D3DXVECTOR3(pos, -pos, pos), D3DXVECTOR3(-pos, -pos, pos), }; bd.Usage = D3D10_USAGE_DEFAULT; bd.ByteWidth = sizeof(SimpleVertex) * NUMVERTEXBUFFER; bd.BindFlags = D3D10_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; bd.MiscFlags = 0; D3D10_SUBRESOURCE_DATA InitData; InitData.pSysMem = vertices.data(); ID3D10Buffer * pVertexBuffertmp; utility::v_return(pd3dDevice->CreateBuffer(&bd, &InitData, &pVertexBuffertmp)); pVertexBuffer.reset(pVertexBuffertmp); // Create index buffer // Create vertex buffer std::array<DWORD, NUMINDEXBUFFER> const indices = { 0, 1, 2, 3, 0, 4, 5, 1, 2, 6, 5, 4, 7, 3, 7, 6 }; bd.Usage = D3D10_USAGE_DEFAULT; bd.ByteWidth = sizeof(DWORD) * NUMINDEXBUFFER; bd.BindFlags = D3D10_BIND_INDEX_BUFFER; bd.CPUAccessFlags = 0; bd.MiscFlags = 0; InitData.pSysMem = indices.data(); ID3D10Buffer * pIndexBuffertmp; utility::v_return(pd3dDevice->CreateBuffer(&bd, &InitData, &pIndexBuffertmp)); pIndexBuffer.reset(pIndexBuffertmp); } //-------------------------------------------------------------------------------------- // Render the help and statistics text //-------------------------------------------------------------------------------------- void RenderText(ID3D10Device* pd3dDevice) { txthelper->Begin(); txthelper->SetInsertionPos(2, 0); txthelper->SetForegroundColor(D3DXCOLOR(1.000f, 0.945f, 0.059f, 1.000f)); txthelper->DrawTextLine(DXUTGetFrameStats(DXUTIsVsyncEnabled())); txthelper->DrawTextLine(DXUTGetDeviceStats()); txthelper->DrawTextLine((boost::wformat(L"原子数: %d") % armd.NumAtom).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"スーパーセルの個数: %d") % armd.Nc).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"MDのステップ数: %d") % armd.MD_iter).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"経過時間: %.3f (ps)") % armd.getDeltat()).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"格子定数: %.3f (nm)") % armd.getLatticeconst()).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"箱の一辺の長さ: %.3f (nm)") % armd.getPeriodiclen()).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"設定された温度: %.3f (K)") % armd.getTgiven()).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"計算された温度: %.3f (K)") % armd.getTcalc()).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"運動エネルギー: %.3f (Hartree)") % armd.Uk).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"ポテンシャルエネルギー: %.3f (Hartree)") % armd.Up).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"全エネルギー: %.3f (Hartree)") % armd.Utot).str().c_str()); txthelper->DrawTextLine((boost::wformat(L"圧力: %.3f (atm)") % armd.getPressure()).str().c_str()); txthelper->DrawTextLine(L"原子の色の違いは働いている力の違いを表す"); txthelper->DrawTextLine(L"赤色に近いほどその原子に働いている力が強い"); txthelper->End(); pd3dDevice->IASetInputLayout(pInputLayout.get()); auto const blendFactor = 0.0f; auto const sampleMask = 0xffffffff; pd3dDevice->OMSetBlendState(pBlendStateNoBlend.get(), &blendFactor, sampleMask); } void SetUI() { g_HUD.RemoveAllControls(); auto iY = 10; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 35, iY, 125, 22); g_HUD.AddButton(IDC_CHANGEDEVICE, L"Change device (F2)", 35, iY += 24, 125, 22, VK_F2); g_HUD.AddButton(IDC_RECALC, L"再計算", 35, iY += 34, 125, 22); // 温度の変更 g_HUD.AddStatic(IDC_OUTPUT, L"温度", 20, iY += 34, 125, 22); g_HUD.GetStatic(IDC_OUTPUT)->SetTextColor(D3DCOLOR_ARGB(255, 255, 255, 255)); g_HUD.AddSlider( IDC_SLIDER, 35, iY += 24, 125, 22, 1, 3000, boost::numeric_cast<int>(moleculardynamics::Ar_moleculardynamics::FIRSTTEMP)); // 格子定数の変更 g_HUD.AddStatic(IDC_OUTPUT2, L"格子定数", 20, iY += 34, 125, 22); g_HUD.GetStatic(IDC_OUTPUT2)->SetTextColor(D3DCOLOR_ARGB(255, 255, 255, 255)); g_HUD.AddSlider( IDC_SLIDER2, 35, iY += 24, 125, 22, 30, 1000, boost::numeric_cast<int>(moleculardynamics::Ar_moleculardynamics::FIRSTSCALE * LATTICERATIO)); // スーパーセルの個数の変更 g_HUD.AddStatic(IDC_OUTPUT3, L"スーパーセルの個数", 20, iY += 34, 125, 22); g_HUD.GetStatic(IDC_OUTPUT3)->SetTextColor(D3DCOLOR_ARGB(255, 255, 255, 255)); g_HUD.AddSlider( IDC_SLIDER3, 35, iY += 24, 125, 22, 1, 16, moleculardynamics::Ar_moleculardynamics::FIRSTNC); // アンサンブルの変更 g_HUD.AddStatic(IDC_OUTPUT4, L"アンサンブル", 20, iY += 40, 125, 22); g_HUD.GetStatic(IDC_OUTPUT4)->SetTextColor(D3DCOLOR_ARGB(255, 255, 255, 255)); g_HUD.AddRadioButton(IDC_RADIOA, 1, L"NVTアンサンブル", 35, iY += 24, 125, 22, true); g_HUD.AddRadioButton(IDC_RADIOB, 1, L"NVEアンサンブル", 35, iY += 28, 125, 22, false); // 温度制御法の変更 g_HUD.AddStatic(IDC_OUTPUT4, L"温度制御の方法", 20, iY += 40, 125, 22); g_HUD.GetStatic(IDC_OUTPUT4)->SetTextColor(D3DCOLOR_ARGB(255, 255, 255, 255)); g_HUD.AddRadioButton(IDC_RADIOC, 2, L"Langevin法", 35, iY += 24, 125, 22, false); g_HUD.AddRadioButton(IDC_RADIOD, 2, L"Nose-Hoover法", 35, iY += 28, 125, 22, false); g_HUD.AddRadioButton(IDC_RADIOE, 2, L"速度スケーリング法", 35, iY += 28, 125, 22, true); } //-------------------------------------------------------------------------------------- // Initialize everything and go into a render loop //-------------------------------------------------------------------------------------- int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow ) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif // Set general DXUT callbacks DXUTSetCallbackFrameMove( OnFrameMove ); DXUTSetCallbackKeyboard( OnKeyboard ); DXUTSetCallbackMouse( OnMouse ); DXUTSetCallbackMsgProc( MsgProc ); DXUTSetCallbackDeviceChanging( ModifyDeviceSettings ); DXUTSetCallbackDeviceRemoved( OnDeviceRemoved ); // Set the D3D10 DXUT callbacks. Remove these sets if the app doesn't need to support D3D10 DXUTSetCallbackD3D10DeviceAcceptable( IsD3D10DeviceAcceptable ); DXUTSetCallbackD3D10DeviceCreated( OnD3D10CreateDevice ); DXUTSetCallbackD3D10SwapChainResized( OnD3D10ResizedSwapChain ); DXUTSetCallbackD3D10FrameRender( OnD3D10FrameRender ); DXUTSetCallbackD3D10SwapChainReleasing( OnD3D10ReleasingSwapChain ); DXUTSetCallbackD3D10DeviceDestroyed( OnD3D10DestroyDevice ); DXUTInit( true, true, nullptr ); // Parse the command line, show msgboxes on error, no extra command line params DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen InitApp(); // ウィンドウを生成 auto const dispx = ::GetSystemMetrics(SM_CXSCREEN); auto const dispy = ::GetSystemMetrics(SM_CYSCREEN); auto const xpos = (dispx - WINDOWWIDTH) / 2; auto const ypos = (dispy - WINDOWHEIGHT) / 2; DXUTCreateWindow(L"アルゴンの古典分子動力学シミュレーション", nullptr, nullptr, nullptr, xpos, ypos); DXUTCreateDevice(true, WINDOWWIDTH, WINDOWHEIGHT); // 垂直同期をオフにする auto ds = DXUTGetDeviceSettings(); ds.d3d10.SyncInterval = 0; DXUTCreateDeviceFromSettings(&ds); DXUTMainLoop(); // Enter into the DXUT render loop return DXUTGetExitCode(); }
32.323333
165
0.594411
dc1394
e54280b14e701389df64bcf55a6e4b43a2d1b1ac
1,432
hpp
C++
module_04/ex03/MateriaSource.hpp
paulahemsi/piscine_cpp
f98feefd8e70308f77442f9b4cb64758676349a7
[ "MIT" ]
4
2021-12-14T18:02:53.000Z
2022-03-24T01:12:38.000Z
module_04/ex03/MateriaSource.hpp
paulahemsi/piscine_cpp
f98feefd8e70308f77442f9b4cb64758676349a7
[ "MIT" ]
null
null
null
module_04/ex03/MateriaSource.hpp
paulahemsi/piscine_cpp
f98feefd8e70308f77442f9b4cb64758676349a7
[ "MIT" ]
3
2021-11-01T00:34:50.000Z
2022-01-29T19:57:30.000Z
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* MateriaSource.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: phemsi-a <phemsi-a@student.42sp.org.br> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/10/12 12:50:12 by phemsi-a #+# #+# */ /* Updated: 2021/10/17 11:30:06 by phemsi-a ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef MATERIASOURCE_HPP #define MATERIASOURCE_HPP #include "IMateriaSource.hpp" #define MAX_MAGICS 4 class MateriaSource : public IMateriaSource { private: AMateria *_magicBook[MAX_MAGICS]; void _storeMateria(AMateria *materia, int i); void _initBook(void); public: MateriaSource(void); MateriaSource(MateriaSource const &instace); ~MateriaSource(void); MateriaSource &operator=(MateriaSource const &rightHandSide); void learnMateria(AMateria*) ; AMateria* createMateria(std::string const & type); }; #endif
35.8
80
0.363827
paulahemsi
e54362429cb0f41b3fcd49c00c8008e615077cac
2,355
cpp
C++
src/QtComponents/Configurators/CtrlPadRectF.cpp
Vladimir-Lin/QtComponents
e7f0a6abcf0504cc9144dcf59f3f14a52d08092c
[ "MIT" ]
null
null
null
src/QtComponents/Configurators/CtrlPadRectF.cpp
Vladimir-Lin/QtComponents
e7f0a6abcf0504cc9144dcf59f3f14a52d08092c
[ "MIT" ]
null
null
null
src/QtComponents/Configurators/CtrlPadRectF.cpp
Vladimir-Lin/QtComponents
e7f0a6abcf0504cc9144dcf59f3f14a52d08092c
[ "MIT" ]
null
null
null
#include <qtcomponents.h> #include "ui_CtrlPadRectF.h" N::CtrlPadRectF:: CtrlPadRectF ( QWidget * parent , Plan * p ) : Widget ( parent , p ) , ui ( new Ui::CtrlPadRectF ) , rect ( NULL ) , identifier ( 0 ) { WidgetClass ; Configure ( ) ; } N::CtrlPadRectF::~CtrlPadRectF(void) { delete ui ; } void N::CtrlPadRectF::closeEvent(QCloseEvent * event) { emit Closed ( identifier , this ) ; QWidget :: closeEvent ( event ) ; } void N::CtrlPadRectF::Configure (void) { ui -> setupUi ( this ) ; plan -> setFont ( this ) ; } void N::CtrlPadRectF::setIdentifier(int id) { identifier = id ; } void N::CtrlPadRectF::ValueChanged(double) { if ( IsNull(rect) ) return ; rect -> setX ( ui->X->value() ) ; rect -> setY ( ui->Y->value() ) ; rect -> setWidth ( ui->W->value() ) ; rect -> setHeight ( ui->H->value() ) ; emit Changed ( identifier , this ) ; } QRectF & N::CtrlPadRectF::Create(void) { rect = new QRectF ( ) ; rect -> setX ( 0 ) ; rect -> setY ( 0 ) ; rect -> setWidth ( 0 ) ; rect -> setHeight ( 0 ) ; return ( *rect ) ; } QRectF & N::CtrlPadRectF::Value(void) { return ( *rect ) ; } QRectF & N::CtrlPadRectF::setValue(QRectF & p) { rect = &p ; ui -> X -> blockSignals ( true ) ; ui -> Y -> blockSignals ( true ) ; ui -> W -> blockSignals ( true ) ; ui -> H -> blockSignals ( true ) ; ui -> X -> setValue ( p.x () ) ; ui -> Y -> setValue ( p.y () ) ; ui -> W -> setValue ( p.width () ) ; ui -> H -> setValue ( p.height() ) ; ui -> X -> blockSignals ( false ) ; ui -> Y -> blockSignals ( false ) ; ui -> W -> blockSignals ( false ) ; ui -> H -> blockSignals ( false ) ; return ( *rect ) ; } QDoubleSpinBox * N::CtrlPadRectF::SpinBox(int index) { switch ( index ) { case 0 : return ui -> X ; case 1 : return ui -> Y ; case 2 : return ui -> W ; case 3 : return ui -> H ; } ; return NULL ; }
25.322581
62
0.449682
Vladimir-Lin
e5482372454bee2f220f078ad09fecf18fba89d5
4,024
hpp
C++
opencl/ocl_device.hpp
kohnakagawa/lj_gpu
a82245dfedc3452b4d6aad72200d63be1119eed6
[ "MIT" ]
1
2016-11-15T11:21:32.000Z
2016-11-15T11:21:32.000Z
opencl/ocl_device.hpp
kohnakagawa/lj_gpu
a82245dfedc3452b4d6aad72200d63be1119eed6
[ "MIT" ]
4
2016-11-05T04:56:46.000Z
2017-05-19T10:51:11.000Z
opencl/ocl_device.hpp
kohnakagawa/lj_gpu
a82245dfedc3452b4d6aad72200d63be1119eed6
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <map> #include "ocl_util.hpp" class OclDevice { std::vector<cl::Platform> platforms; std::vector<cl::Device> devices; cl::Platform platform; cl::Device device; cl::Context context; cl::Program::Sources sources; cl::Program program; std::map<std::string, cl::Kernel> kernels; std::vector<std::string> kernel_names; void GetPlatformAll() { checkErr(cl::Platform::get(&platforms), "cl::Platform::get"); checkErr(platforms.size() != 0 ? CL_SUCCESS : -1, "cl::Platform::get"); } void DisplayPlatFormInfo(const cl::Platform& plt, const cl_platform_info id, const std::string str) { std::string info; checkErr(plt.getInfo(id, &info), "cl::Platform::getInfo" ); std::cerr << str << ": " << info << "\n"; } void DisplayPlatFormInfoAll() { std::cerr << "Platform number is: " << platforms.size() << "\n"; for (auto& plt : platforms) { DisplayPlatFormInfo(plt, CL_PLATFORM_NAME, "CL_PLATFORM_NAME"); DisplayPlatFormInfo(plt, CL_PLATFORM_PROFILE, "CL_PLATFORM_PROFILE"); DisplayPlatFormInfo(plt, CL_PLATFORM_VERSION, "CL_PLATFORM_VERSION"); DisplayPlatFormInfo(plt, CL_PLATFORM_VENDOR, "CL_PLATFORM_VENDOR"); DisplayPlatFormInfo(plt, CL_PLATFORM_EXTENSIONS, "CL_PLATFORM_EXTENSIONS"); } } void SetPlatform() { platform = *(platforms.rbegin()); } void GetDeviceAll(const cl_device_type type) { checkErr(platform.getDevices(type, &devices), "cl::Platform::getDevices"); } void DisplayDeviceInfo(const cl::Device& dev, const cl_device_info name, const std::string str) { std::string info; checkErr(dev.getInfo(name, &info), "cl::Device::getInfo"); std::cerr << str << ": " << info << "\n"; } void DisplayDeviceInfoAll() { std::cerr << "Number of devices " << devices.size() << " is found.\n"; for (auto& dev : devices) { DisplayDeviceInfo(dev, CL_DEVICE_NAME, "Device name"); DisplayDeviceInfo(dev, CL_DEVICE_VENDOR, "Device vendor"); DisplayDeviceInfo(dev, CL_DEVICE_PROFILE, "Device profile"); DisplayDeviceInfo(dev, CL_DEVICE_VERSION, "Device version"); DisplayDeviceInfo(dev, CL_DRIVER_VERSION, "Driver version"); DisplayDeviceInfo(dev, CL_DEVICE_OPENCL_C_VERSION, "OpenCL C version"); DisplayDeviceInfo(dev, CL_DEVICE_EXTENSIONS, "OpenCL device extensions"); } } void SetDevice() { device = *(devices.rbegin()); } public: OclDevice() {} ~OclDevice() {} void Initialize() { GetPlatformAll(); DisplayPlatFormInfoAll(); SetPlatform(); GetDeviceAll(CL_DEVICE_TYPE_GPU); DisplayDeviceInfoAll(); SetDevice(); } void AddProgramSource(const char* source_str) { sources.push_back(std::make_pair(source_str, std::strlen(source_str))); } void AddKernelName(const std::string name) { kernel_names.push_back(name); } void BuildProgram(const std::string build_opt) { program = cl::Program(context, sources); try { program.build(devices, build_opt.c_str()); } catch (cl::Error err) { if (err.err() == CL_BUILD_PROGRAM_FAILURE) { std::cerr << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) << std::endl; } else { std::cerr << "Unknown error #" << err.err() << " " << err.what() << "\n"; } } } void CreateContext() { context = cl::Context(device); } void CreateKernels() { for (const auto& name : kernel_names) { kernels[name] = cl::Kernel(program, name.c_str()); } } cl::Kernel& GetKernel(const std::string name) { return kernels.at(name); } template <typename T> void SetFunctionArg(const std::string name, const int pos, T& buf) { kernels.at(name).setArg(pos, buf); } cl::Device& GetCurrentDevice() { return device; } cl::Context& GetCurrentContext() { return context; } };
28.94964
85
0.633201
kohnakagawa
e5491219797554063211f8295cafc70f5da501b2
2,503
cpp
C++
include/obnsim_basic.cpp
sduerr85/OpenBuildNet
126feb4d17558e7bfe1e2e6f081bbfbf1514496f
[ "MIT" ]
null
null
null
include/obnsim_basic.cpp
sduerr85/OpenBuildNet
126feb4d17558e7bfe1e2e6f081bbfbf1514496f
[ "MIT" ]
null
null
null
include/obnsim_basic.cpp
sduerr85/OpenBuildNet
126feb4d17558e7bfe1e2e6f081bbfbf1514496f
[ "MIT" ]
null
null
null
/* -*- mode: C++; indent-tabs-mode: nil; -*- */ /** \file * \brief Basic definitions. * * This file is part of the openBuildNet simulation framework * (OBN-Sim) developed at EPFL. * * \author Truong X. Nghiem (xuan.nghiem@epfl.ch) */ #include <cassert> #include <obnsim_basic.h> #include <cctype> // Name of the GC port on any node const char *OBNsim::NODE_GC_PORT_NAME = "_gc_"; // std::chrono::time_point<std::chrono::steady_clock> OBNsim::clockStart; std::string OBNsim::Utils::trim(const std::string& s0) { std::string s(s0); std::size_t found = s.find_last_not_of(" \t\f\v\n\r"); if (found != std::string::npos) { s.erase(found+1); found = s.find_first_not_of(" \t\f\v\n\r"); s.erase(0, found); } else { s.clear(); } return s; } std::string OBNsim::Utils::toUpper(const std::string& s0) { std::string s(s0); for (auto& c: s) { c = std::toupper(c); } return s; } std::string OBNsim::Utils::toLower(const std::string& s0) { std::string s(s0); for (auto& c: s) { c = std::tolower(c); } return s; } bool OBNsim::Utils::isValidIdentifier(const std::string &name) { if (name.empty() || name[0] == '_') { return false; } return name.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") == std::string::npos; } bool OBNsim::Utils::isValidNodeName(const std::string &name) { if (name.empty() || name.front() == '_' || name.front() == '/' || name.back() == '/') { return false; } if (name.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_/") != std::string::npos) { return false; } // Double forward slashes are invalid // Underscore following / is also invalid return (name.find("//") == std::string::npos) && (name.find("/_") == std::string::npos); } void OBNsim::ResizableBuffer::allocateData(std::size_t newsize) { m_data_size = newsize; if (m_data) { // If _allocsize >= _size, we reuse the memory block if (m_data_allocsize < m_data_size) { delete [] m_data; } } else { m_data_allocsize = 0; // Make sure that _allocsize < _size } if (m_data_allocsize < m_data_size) { m_data_allocsize = (m_data_size & 0x0F)?(((m_data_size >> 4)+1) << 4):m_data_size; assert(m_data_allocsize >= m_data_size); m_data = new char[m_data_allocsize]; } }
28.443182
122
0.603676
sduerr85
e54a08078b3a332b8803c5275d4a1b5bde7eff21
219
cpp
C++
source/fifoSolver.cpp
Zegis/MPD-helper
b5a4c3299922e09276dd736520824d5f6a2baab3
[ "MIT" ]
null
null
null
source/fifoSolver.cpp
Zegis/MPD-helper
b5a4c3299922e09276dd736520824d5f6a2baab3
[ "MIT" ]
null
null
null
source/fifoSolver.cpp
Zegis/MPD-helper
b5a4c3299922e09276dd736520824d5f6a2baab3
[ "MIT" ]
null
null
null
#include "headers/fifoSolver.h" fifoSolver::fifoSolver() { } Solution fifoSolver::Solve(QList<Job *> jobs, int MachineAmount) { sortJobs(&jobs,0,&fifoSolver::AscendingBasedOnRelase); return Solution(jobs); }
16.846154
64
0.726027
Zegis
e54aa0a914225501eaa3d5c768628a6730d5babf
1,374
cpp
C++
tools.cpp
PapaSinku/SinkuEngine
2202162d12a52df8438d7cb8c5ffc37847fd87c4
[ "MIT" ]
null
null
null
tools.cpp
PapaSinku/SinkuEngine
2202162d12a52df8438d7cb8c5ffc37847fd87c4
[ "MIT" ]
null
null
null
tools.cpp
PapaSinku/SinkuEngine
2202162d12a52df8438d7cb8c5ffc37847fd87c4
[ "MIT" ]
null
null
null
#include "tools.hpp" using namespace std; void sdl_error(string error_message) { cout << error_message << endl << "SDL_Error: " << SDL_GetError() << endl; } void sdl_image_error(std::string error_message) { cout << error_message << endl << "SDL_Error: " << IMG_GetError() << endl; } SDL_Surface* imageSurfaceRead(std::string path, SDL_Surface *window_surface) { SDL_Surface* optimizedSurface = NULL; SDL_Surface* loadedSurface = IMG_Load(path.c_str()); if(loadedSurface == NULL) { sdl_image_error("Unable to load image"); return NULL; } optimizedSurface = SDL_ConvertSurface( loadedSurface, window_surface->format, 0 ); if( optimizedSurface == NULL ) { sdl_error("Unable to optimize image"); return loadedSurface; } SDL_FreeSurface( loadedSurface ); return optimizedSurface; } SDL_Texture* imageTextureRead(std::string path, SDL_Renderer *renderer) { SDL_Texture* optimizedSurface = NULL; SDL_Surface* loadedSurface = IMG_Load(path.c_str()); if(loadedSurface == NULL) { sdl_image_error("Unable to load image"); return NULL; } optimizedSurface = SDL_CreateTextureFromSurface(renderer, loadedSurface); if( optimizedSurface == NULL ) { sdl_error("Unable to create texture"); return NULL; } SDL_FreeSurface( loadedSurface ); return optimizedSurface; }
26.941176
86
0.694323
PapaSinku
e54ea1d7707a224e5dc3486938053bb2ea86e2e6
2,395
cpp
C++
frameworks/core/components/positioned/render_positioned.cpp
openharmony-gitee-mirror/ace_ace_engine
78013960cdce81348d1910e466a3292605442a5e
[ "Apache-2.0" ]
null
null
null
frameworks/core/components/positioned/render_positioned.cpp
openharmony-gitee-mirror/ace_ace_engine
78013960cdce81348d1910e466a3292605442a5e
[ "Apache-2.0" ]
null
null
null
frameworks/core/components/positioned/render_positioned.cpp
openharmony-gitee-mirror/ace_ace_engine
78013960cdce81348d1910e466a3292605442a5e
[ "Apache-2.0" ]
1
2021-09-13T11:17:50.000Z
2021-09-13T11:17:50.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 "core/components/positioned/render_positioned.h" #include "core/components/positioned/positioned_component.h" namespace OHOS::Ace { RefPtr<RenderNode> RenderPositioned::Create() { return AceType::MakeRefPtr<RenderPositioned>(); } void RenderPositioned::Update(const RefPtr<Component>& component) { const auto positioned = AceType::DynamicCast<PositionedComponent>(component); if (!positioned) { return; } bottom_ = positioned->GetBottom(); top_ = positioned->GetTop(); left_ = positioned->GetLeft(); right_ = positioned->GetRight(); width_ = positioned->GetWidth(); height_ = positioned->GetHeight(); hasLeft_ = positioned->HasLeft(); hasRight_ = positioned->HasRight(); hasTop_ = positioned->HasTop(); hasBottom_ = positioned->HasBottom(); MarkNeedLayout(); } void RenderPositioned::SetLeft(const Dimension& left) { if (NearEqual(left_.Value(), left.Value()) && (left_.Unit() == left.Unit())) { return; } left_ = left; hasLeft_ = true; MarkNeedLayout(); } void RenderPositioned::SetTop(const Dimension& top) { if (NearEqual(top_.Value(), top.Value()) && (top_.Unit() == top.Unit())) { return; } top_ = top; hasTop_ = true; MarkNeedLayout(); } void RenderPositioned::SetRight(const Dimension& right) { if (NearEqual(right_.Value(), right.Value()) && (right_.Unit() == right.Unit())) { return; } right_ = right; hasRight_ = true; MarkNeedLayout(); } void RenderPositioned::SetBottom(const Dimension& bottom) { if (NearEqual(bottom_.Value(), bottom.Value()) && (bottom_.Unit() == bottom.Unit())) { return; } bottom_ = bottom; hasBottom_ = true; MarkNeedLayout(); } } // namespace OHOS::Ace
27.528736
90
0.670146
openharmony-gitee-mirror
e55178e6ca721643affc7ab84cc5050926a440fa
8,058
cpp
C++
test/test_exec/nsearch/testNSearchLib.cpp
gitter-badger/PeriDEM
57c6db80ded86dba12bc8a9d731da439ce3d3947
[ "BSL-1.0" ]
null
null
null
test/test_exec/nsearch/testNSearchLib.cpp
gitter-badger/PeriDEM
57c6db80ded86dba12bc8a9d731da439ce3d3947
[ "BSL-1.0" ]
null
null
null
test/test_exec/nsearch/testNSearchLib.cpp
gitter-badger/PeriDEM
57c6db80ded86dba12bc8a9d731da439ce3d3947
[ "BSL-1.0" ]
null
null
null
/* * ---------------------------------- * Copyright (c) 2021 Prashant K. Jha * ---------------------------------- * * 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 "testNSearchLib.h" #include "nsearch/nsearch.h" #include "util/function.h" #include "util/matrix.h" #include "util/methods.h" #include "util/point.h" #include <bitset> #include <fstream> #include <iostream> #include <random> #include <vector> // hpx lib #include <hpx/include/parallel_algorithm.hpp> typedef nsearch::NSearchKd NSearch; typedef std::mt19937 RandGenerator; typedef std::uniform_real_distribution<> UniformDistribution; namespace { RandGenerator get_rd_gen(int seed) { //return RandGenerator(); if (seed < 0) { std::random_device rd; seed = rd(); } return RandGenerator(seed); } bool isInList(const std::vector<size_t> *list, size_t i) { for (auto j : *list) if (j == i) return true; return false; } void stats(const std::vector<double> &x, double &mean, double &std) { double mu = 0.; for (auto &y: x) mu += y; mu = mu/x.size(); double s = 0.; for (auto &y : x) s += (y - mu) * (y - mu); s = s / x.size(); std = std::sqrt(s); mean = mu; } void lattice(double L, size_t Nx, size_t Ny, size_t Nz, double dL, int seed, std::vector<util::Point> &x) { RandGenerator gen(get_rd_gen(seed)); UniformDistribution dist(-dL, dL); x.resize(Nx*Ny*Nz); size_t count = 0; for (size_t i=0; i<Nx; i++) for (size_t j=0; j<Ny; j++) for (size_t k=0; k<Nz; k++) { auto y = util::Point(); y.d_x = i*L + dist(gen); y.d_y = j*L + dist(gen); y.d_z = k*L + dist(gen); x[count] = y; count++; } } double neighSearchTree(const std::vector<util::Point> &x, const std::unique_ptr<NSearch> &nsearch, const double &r, std::vector<std::vector<size_t>> &neigh, std::vector<std::vector<float>> &neigh_sq_dist) { neigh.resize(x.size()); neigh_sq_dist.resize(x.size()); auto t1 = steady_clock::now(); hpx::parallel::for_loop( hpx::parallel::execution::par, 0, x.size(), [&x, &neigh, &neigh_sq_dist, &nsearch, r](boost::uint64_t i) { std::vector<int> neighs; std::vector<float> sqr_dist; pcl::PointXYZ searchPoint; searchPoint.x = x[i].d_x; searchPoint.y = x[i].d_y; searchPoint.z = x[i].d_z; if (nsearch->d_tree.radiusSearch( searchPoint, r, neighs, sqr_dist) > 0) { for (std::size_t j = 0; j < neighs.size(); ++j) if (size_t(neighs[j]) != i) { neigh[i].push_back(size_t(neighs[j])); neigh_sq_dist[i].push_back(sqr_dist[j]); } } }); auto t2 = steady_clock::now(); return util::methods::timeDiff(t1, t2); } double neighSearchBrute(const std::vector<util::Point> &x, const double &r, std::vector<std::vector<size_t>> &neigh, std::vector<std::vector<float>> &neigh_sq_dist) { neigh.resize(x.size()); neigh_sq_dist.resize(x.size()); auto t1 = steady_clock::now(); hpx::parallel::for_loop( hpx::parallel::execution::par, 0, x.size(), [&x, &neigh, &neigh_sq_dist, r] (boost::uint64_t i) { auto searchPoint = x[i]; for (size_t j = 0; j < x.size(); j++) { auto dx = searchPoint - x[j]; auto l = dx.length(); if (util::isLess(l, r) and j != i) { neigh[i].push_back(j); neigh_sq_dist[i].push_back(l); } } }); auto t2 = steady_clock::now(); return util::methods::timeDiff(t1, t2); } } void test::testNSearch(size_t N) { // create 3D lattice and perturb each lattice point int seed = 1000; double L = 1.; double dL = 0.2; size_t Nx, Ny, Nz; Nx = Ny = Nz = N; size_t N_tot = Nx*Ny*Nz; std::vector<util::Point> x(N_tot, util::Point()); lattice(L, Nx, Ny, Nz, dL, seed, x); std::cout << "Total points = " << x.size() << "\n"; std::vector<std::vector<size_t>> neigh_tree(N_tot, std::vector<size_t>()); std::vector<std::vector<float>> neigh_sq_dist_tree(N_tot, std::vector<float>()); std::vector<std::vector<size_t>> neigh(N_tot, std::vector<size_t>()); std::vector<std::vector<float>> neigh_sq_dist(N_tot, std::vector<float>()); // create search object and report time needed for creation std::cout << "Step 1: Initial setup \n"; std::unique_ptr<NSearch> nsearch = std::make_unique<NSearch>(0, 1.); auto set_cloud_pts_time = nsearch->updatePointCloud(x, true); auto set_tree_time = nsearch->setInputCloud(); std::cout << " tree_setup_time = " << set_cloud_pts_time + set_tree_time << " \n" << std::flush; // double search_r = 1.5 * L; std::cout << "Step 2: Search time \n"; auto tree_search_time = neighSearchTree( x, nsearch, search_r, neigh_tree, neigh_sq_dist_tree); std::cout << " tree_search_time = " << tree_search_time << " \n" << std::flush; auto brute_search_time = neighSearchBrute(x, search_r, neigh, neigh_sq_dist); std::cout << " brute_search_time = " << brute_search_time << " \n" << std::flush; // std::cout << "Step 3: Compare tree and brute results (match is not " "necessary!! \n"; size_t error_size = 0; size_t error_nodes = 0; size_t error_neighs = 0; std::ostringstream composs; for (size_t i=0; i<x.size(); i++) { size_t err_neighs = 0; auto &tree_neigh = neigh_tree[i]; auto &brute_neigh = neigh[i]; bool header_done = false; if (tree_neigh.size() != brute_neigh.size()) { composs << " Node = " << i << " \n"; composs << " size (tree) " << tree_neigh.size() << " != " << brute_neigh.size() << " (brute) not matching\n"; header_done = true; error_size++; } for (auto j : brute_neigh) { if (!isInList(&tree_neigh, j)) { if (!header_done) composs << " Node = " << i << " \n"; composs << " neigh = " << j << " not found in tree neighs\n"; err_neighs += 1; } } if (err_neighs > 0) error_neighs += err_neighs; } std::cout << " error_size = " << error_size << ", error_neighs = " << error_neighs << "\n"; std::cout << composs.str() << "\n"; // std::cout << "Step 4: Change points and redo calculations multiple times \n"; size_t N_test = 5; // to change perturbation size RandGenerator gen(get_rd_gen(seed*39)); UniformDistribution dist(dL*0.5, dL*2.); std::vector<double> compute_times_tree(N_test, 0.); std::vector<double> compute_times_brute(N_test, 0.); for (size_t i=0; i<N_test; i++) { double dL_rand = dist(gen); lattice(L, Nx, Ny, Nz, dL_rand, seed + i + 1, x); std::cout << " Test number = " << i << "\n"; auto tree_search_time = neighSearchTree( x, nsearch, search_r, neigh_tree, neigh_sq_dist_tree); std::cout << " tree_search_time = " << tree_search_time << " \n" << std::flush; auto brute_search_time = neighSearchBrute( x, search_r, neigh, neigh_sq_dist); std::cout << " brute_search_time = " << brute_search_time << " \n" << std::flush; compute_times_tree[i] = tree_search_time; compute_times_brute[i] = brute_search_time; } // compute stats and report double mean_brute = 0., std_brute = 0.; stats(compute_times_brute, mean_brute, std_brute); double mean_tree = 0., std_tree = 0.; stats(compute_times_tree, mean_tree, std_tree); std::cout << "\n"; std::cout << " brute state: mean = " << mean_brute << ", std = " << std_brute << "\n"; std::cout << " tree state: mean = " << mean_tree << ", std = " << std_tree << "\n"; }
29.301818
79
0.569372
gitter-badger
e55566aca5aee7fbd927a14f88ce511662120ec1
615
cpp
C++
ch06/ex6_1.cpp
zzb610/essential-cpp-solutions
166bf750102a1d8c08db1c5897d2f300027f6a39
[ "MulanPSL-1.0" ]
1
2021-09-11T07:59:14.000Z
2021-09-11T07:59:14.000Z
ch06/ex6_1.cpp
zzb610/essential-cpp-solutions
166bf750102a1d8c08db1c5897d2f300027f6a39
[ "MulanPSL-1.0" ]
null
null
null
ch06/ex6_1.cpp
zzb610/essential-cpp-solutions
166bf750102a1d8c08db1c5897d2f300027f6a39
[ "MulanPSL-1.0" ]
null
null
null
#include <iostream> template <typename ValType> class Example { public: Example(const ValType &min, const ValType &max); Example(const ValType *array, int size); ValType &operator[](int index); bool operator==(const Example &rhs) const; bool insert(const ValType *val, int index); bool insert(const ValType &elem); ValType min() const { return _min; } ValType max() const { return _max; } void min(const ValType &); void max(const ValType &); int count(const ValType &value) const; private: int size; ValType *parray; ValType _min; ValType _max; };
21.206897
52
0.658537
zzb610
e558a98dae94c13e4419d76686d76602c313ba65
2,220
hpp
C++
third_party/boost/sandbox/boost/logging/detail/tss/tss_ensure_proper_delete.hpp
gbucknell/fsc-sdk
11b7cda4eea35ec53effbe37382f4b28020cd59d
[ "MIT" ]
null
null
null
third_party/boost/sandbox/boost/logging/detail/tss/tss_ensure_proper_delete.hpp
gbucknell/fsc-sdk
11b7cda4eea35ec53effbe37382f4b28020cd59d
[ "MIT" ]
null
null
null
third_party/boost/sandbox/boost/logging/detail/tss/tss_ensure_proper_delete.hpp
gbucknell/fsc-sdk
11b7cda4eea35ec53effbe37382f4b28020cd59d
[ "MIT" ]
null
null
null
// tss_ensure_proper_delete.hpp // Boost Logging library // // Author: John Torjo, www.torjo.com // // Copyright (C) 2007 John Torjo (see www.torjo.com for email) // // 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 for updates, documentation, and revision history. // See http://www.torjo.com/log2/ for more details #ifndef JT28092007_tss_ensure_proper_delete_HPP_DEFINED #define JT28092007_tss_ensure_proper_delete_HPP_DEFINED #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif #include <boost/logging/detail/fwd.hpp> #include <vector> #include <stdlib.h> namespace boost { namespace logging { namespace detail { struct do_delete_base { virtual ~do_delete_base () {} }; template<class type> struct do_delete : do_delete_base { do_delete(type * val) : m_val(val) {} ~do_delete() { delete m_val; } type * m_val; }; #ifdef BOOST_LOG_TEST_TSS // just for testing void on_end_delete_objects(); #endif struct delete_array : std::vector< do_delete_base* > { typedef boost::logging::threading::mutex mutex; typedef std::vector< do_delete_base* > vector_base; delete_array() {} ~delete_array () { for ( const_iterator b = begin(), e = end(); b != e; ++b) delete *b; #ifdef BOOST_LOG_TEST_TSS on_end_delete_objects(); #endif } void push_back(do_delete_base* p) { mutex::scoped_lock lk(cs); vector_base::push_back(p); } private: mutex cs; }; inline delete_array & object_deleter() { static delete_array a ; return a; } template<class type> inline type * new_object_ensure_delete() { type * val = new type; delete_array & del = object_deleter(); del.push_back( new do_delete<type>(val) ); return val; } template<class type> inline type * new_object_ensure_delete(const type & init) { type * val = new type(init); delete_array & del = object_deleter(); del.push_back( new do_delete<type>(val) ); return val; } }}} #endif
24.395604
81
0.653604
gbucknell
e55e95f3f44d6adfe3cc7adb5b1f81e818affae0
306
hpp
C++
tests/chrono/chrono_full.hpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
11
2021-03-15T07:06:21.000Z
2021-09-27T13:54:25.000Z
tests/chrono/chrono_full.hpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
null
null
null
tests/chrono/chrono_full.hpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
1
2021-06-24T10:46:46.000Z
2021-06-24T10:46:46.000Z
#pragma once //------------------------------------------------------------------------------ namespace chrono_tests { //------------------------------------------------------------------------------ void run_full(); //------------------------------------------------------------------------------ }
21.857143
80
0.140523
olegpublicprofile
e56119450b708afa3994d4c459b6626cf86cb226
6,154
cpp
C++
WinAPI/L13/L13.cpp
virtualmode/Archive
04c41b29edd9b6df1c13ab2318b7c138e59dd81d
[ "MIT" ]
null
null
null
WinAPI/L13/L13.cpp
virtualmode/Archive
04c41b29edd9b6df1c13ab2318b7c138e59dd81d
[ "MIT" ]
null
null
null
WinAPI/L13/L13.cpp
virtualmode/Archive
04c41b29edd9b6df1c13ab2318b7c138e59dd81d
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <process.h> #include <windows.h> #define TEXT_SIZE 128 struct Thread { HANDLE hThread; unsigned Id; }; int k, n, p; // n - номер потока, p - приоритет. HDC hDC; // Указатель на контекст для рисования. HWND hWndControl[4]; Thread Threads[2]; HINSTANCE Instance; LRESULT Result; WNDPROC DefTextProc; // Указатель на функцию обработки текстового поля. wchar_t Text[TEXT_SIZE]; // Обработка сообщений текстового поля: LRESULT CALLBACK TextProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { Result = DefTextProc(hWnd, Message, wParam, lParam); switch (Message) { case WM_GETTEXT: // Обработка полученных данных: k = 0; n = 1; p = 0; while (Text[k] != 0 && Text[k] != L',') { k++; } Text[k] = 0; n = _wtoi(Text) - 1; p = _wtoi(Text + k + 1); if (n >= 0 && n < 2) { if (!SetThreadPriority(Threads[n].hThread, p)) { MessageBox(0, L"Невозможно изменить приоритет.", L"", 0); } else { swprintf(Text, TEXT_SIZE, L"Поток %i [Приоритет %i]", n + 1, p); SendMessage(hWndControl[n], WM_SETTEXT, 0, (LPARAM)Text); } } else { MessageBox(0, L"Введенный поток отсутствует.", L"", 0); } break; default: break; } return Result; } // Функция, работающая в первом потоке. Ее задача - тупо подвигать кнопку 1: unsigned __stdcall FirstThreadFunc( void* pArguments ) { bool d = false; int x = 30; for (int i = 0; i < 1480; i++) { Sleep(1); if (d == false) x++; else x--; if (x > 400) d = true; else if (x < 30) d = false; MoveWindow(hWndControl[0], x, 75, 250, 25, TRUE); } return 0; } // Функция, работающая в первом потоке. Ее задача - тупо подвигать кнопку 2: unsigned __stdcall SecondThreadFunc( void* pArguments ) { bool d = false; int y = 105; for (int i = 0; i < 600; i++) { Sleep(1); if (d == false) y++; else y--; if (y > 205) d = true; else if (y < 105) d = false; MoveWindow(hWndControl[1], 30, y, 250, 25, TRUE); } return 0; } // Функция обработки сообщений ОС Windows (!!! ЭТА ФУНКЦИЯ РАБОТАЕТ В ОСНОВНОМ ПОТОКЕ): LRESULT CALLBACK MainWinProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch (Message) { case WM_CREATE: // Инициализация основного окна и создание на нем элементов управления: hWndControl[0] = CreateWindowW(L"BUTTON", L"Поток 1 [Приоритет 0]", BS_PUSHBUTTON | WS_VISIBLE | WS_CHILD, 30, 75, 250, 25, hWnd, (HMENU)0, Instance, 0); hWndControl[1] = CreateWindowW(L"BUTTON", L"Поток 2 [Приоритет 0]", BS_PUSHBUTTON | WS_VISIBLE | WS_CHILD, 30, 105, 250, 25, hWnd, (HMENU)1, Instance, 0); hWndControl[2] = CreateWindowW(L"EDIT", 0, WS_CHILD | WS_BORDER | WS_VISIBLE | ES_LEFT, 30, 30, 200, 26, hWnd, (HMENU)2, Instance, 0); // Неиспользуемый указатель. hWndControl[3] = CreateWindowW(L"BUTTON", L"Установить приоритет [Номер потока, Приоритет]", BS_PUSHBUTTON | WS_VISIBLE | WS_CHILD, 240, 30, 350, 25, hWnd, (HMENU)3, Instance, 0); DefTextProc = (WNDPROC)GetWindowLong(hWndControl[2], GWL_WNDPROC); SetWindowLong(hWndControl[2], GWL_WNDPROC, (LONG)TextProc); break; case WM_PAINT: TextOutW(hDC, 30, 350, L"Варианты приоритета: -15 -2 -1 0 1 2 15", 46); // Вывод текста на экран. break; case WM_COMMAND: switch (LOWORD(wParam)) { case 0: // Создание потока: Threads[0].hThread = (HANDLE)_beginthreadex(NULL, 0, &FirstThreadFunc, NULL, 0, &Threads[0].Id); break; case 1: Threads[1].hThread = (HANDLE)_beginthreadex(NULL, 0, &SecondThreadFunc, NULL, 0, &Threads[1].Id); break; case 3: SendMessage(hWndControl[2], WM_GETTEXT, TEXT_SIZE, (LPARAM)Text); break; default: break; } break; case WM_DESTROY: PostQuitMessage(0); return 0; default: break; } return DefWindowProc(hWnd, Message, wParam, lParam); } // Точка входа в приложение: int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // Определение необходимых переменных: WNDCLASSEX WindowClassEx; // Структура для хранения информации о создаваемом окне. HWND hWndMain; // Идентификатор основного окна. MSG Message; // Переменная для обработки сообщений. // Заполнение структуры WindowClassEx: WindowClassEx.cbSize = sizeof(WNDCLASSEX); WindowClassEx.style = CS_DBLCLKS | CS_OWNDC | CS_HREDRAW | CS_VREDRAW; // Не напрягайтесь, это просто флаги. К лабораторной не имеют никакого отношения. WindowClassEx.lpfnWndProc = MainWinProc; // Указатель на функцию обработки сообщений ОС Windows. WindowClassEx.cbClsExtra = 0; WindowClassEx.cbWndExtra = 0; WindowClassEx.hInstance = hInstance; WindowClassEx.hIcon = NULL; // Иконка отсутствует. WindowClassEx.hCursor = LoadCursor(0, IDC_ARROW); WindowClassEx.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); // Белый цвет окна. WindowClassEx.lpszMenuName = 0; // Меню отсутствует. WindowClassEx.lpszClassName = L"Laboratory"; // Имя класса. Используется операционной системой. WindowClassEx.hIconSm = LoadIcon(0, MAKEINTRESOURCE(32517)); // Какая-то иконка по умолчанию. RegisterClassEx(&WindowClassEx); // Регистрация класса окна, информация о котором берется из вышеописанной структуры. // Создание основного окна: hWndMain = CreateWindowEx(0, L"Laboratory", L"Лабораторная работа 13", WS_TILEDWINDOW, 50, 50, 640, 480, 0, 0, hInstance, 0); // Отображение всего созданного на экране: ShowWindow(hWndMain, SW_SHOWDEFAULT); UpdateWindow(hWndMain); // Получение контекста для рисования в окне: hDC = GetWindowDC(hWndMain); SendMessage(hWndMain, WM_PAINT, 0, 0); // Запуск основного цикла обработки сообщений: while (GetMessage(&Message, 0, 0, 0)) { TranslateMessage(&Message); DispatchMessage(&Message); } // Destroy the thread object. CloseHandle(Threads[0].hThread); CloseHandle(Threads[1].hThread); // Если из цикла вышли, значит пользователь (а может и не он вовсе) закрыл приложение: return (int) Message.wParam; }
31.721649
183
0.668996
virtualmode
e563e1a28101ea2ec95776c0290115cf9d94f2ba
2,243
cpp
C++
samples/cpp/neural_networks/sources/daal_alexnet.cpp
rayrapetyan/daal
41cc748dc50097b1064e40395a4da7ce6f836244
[ "Apache-2.0" ]
null
null
null
samples/cpp/neural_networks/sources/daal_alexnet.cpp
rayrapetyan/daal
41cc748dc50097b1064e40395a4da7ce6f836244
[ "Apache-2.0" ]
null
null
null
samples/cpp/neural_networks/sources/daal_alexnet.cpp
rayrapetyan/daal
41cc748dc50097b1064e40395a4da7ce6f836244
[ "Apache-2.0" ]
null
null
null
/* file: daal_alexnet.cpp */ //============================================================== // // SAMPLE SOURCE CODE - SUBJECT TO THE TERMS OF SAMPLE CODE LICENSE AGREEMENT, // http://software.intel.com/en-us/articles/intel-sample-source-code-license-agreement/ // // Copyright 2017-2018 Intel Corporation // // THIS FILE IS PROVIDED "AS IS" WITH NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT // NOT LIMITED TO ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE, NON-INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS. // // ============================================================= /* ! Content: ! C++ example of neural network training and scoring with AlexNet topology !******************************************************************************/ #include "daal_commons.h" #include "daal_alexnet.h" const std::string defaultDatasetsPath = "./data"; const std::string datasetFileNames[] = { "train_227x227.blob", "test_227x227.blob" }; int main(int argc, char *argv[]) { std::string userDatasetsPath = getUserDatasetPath(argc, argv); std::string datasetsPath = selectDatasetPathOrExit( defaultDatasetsPath, userDatasetsPath, datasetFileNames, 2); /* Form path to the training and testing datasets */ std::string trainBlobPath = datasetsPath + "/" + datasetFileNames[0]; std::string testBlobPath = datasetsPath + "/" + datasetFileNames[1]; /* Create blob dataset reader for the training dataset (ImageBlobDatasetReader defined in blob_dataset.h) */ ImageBlobDatasetReader<float> trainDatasetReader(trainBlobPath, batchSize); training::TopologyPtr topology = configureNet(); /* defined in daal_alexnet.h */ /* Train model (trainClassifier is defined in daal_common.h) */ prediction::ModelPtr predictionModel = trainClassifier(topology, &trainDatasetReader); /* Create blob dataset reader for the testing dataset */ ImageBlobDatasetReader<float> testDatasetReader(testBlobPath, batchSize); /* Test model (testClassifier is defined in daal_common.h) */ float top5ErrorRate = testClassifier(predictionModel, &testDatasetReader); std::cout << "Top-5 error = " << top5ErrorRate * 100.0 << "%" << std::endl; return 0; }
39.350877
113
0.66206
rayrapetyan
e5641b7f89f4586d12b5ce3e79c1cd06e50d2895
4,680
cc
C++
src/vnsw/agent/ovs_tor_agent/ovsdb_client/ovsdb_resource_vxlan_id.cc
jnpr-pranav/contrail-controller
428eee37c28c31830fd764315794e1a6e52720c1
[ "Apache-2.0" ]
37
2020-09-21T10:42:26.000Z
2022-01-09T10:16:40.000Z
src/vnsw/agent/ovs_tor_agent/ovsdb_client/ovsdb_resource_vxlan_id.cc
jnpr-pranav/contrail-controller
428eee37c28c31830fd764315794e1a6e52720c1
[ "Apache-2.0" ]
2
2018-12-04T02:20:52.000Z
2018-12-22T06:16:30.000Z
src/vnsw/agent/ovs_tor_agent/ovsdb_client/ovsdb_resource_vxlan_id.cc
jnpr-pranav/contrail-controller
428eee37c28c31830fd764315794e1a6e52720c1
[ "Apache-2.0" ]
21
2020-08-25T12:48:42.000Z
2022-03-22T04:32:18.000Z
/* * Copyright (c) 2015 Juniper Networks, Inc. All rights reserved. */ #include <ovsdb_entry.h> #include <ovsdb_object.h> #include <ovsdb_resource_vxlan_id.h> using namespace OVSDB; OvsdbResourceVxLanId::OvsdbResourceVxLanId(OvsdbResourceVxLanIdTable *table, KSyncEntry *entry) : table_(table), entry_(entry), resource_id_(0), vxlan_id_(0), active_vxlan_id_(0) { } OvsdbResourceVxLanId::~OvsdbResourceVxLanId() { ReleaseVxLanId(true); ReleaseVxLanId(false); } bool OvsdbResourceVxLanId::AcquireVxLanId(uint32_t vxlan_id) { if (vxlan_id_ == vxlan_id) { return (resource_id_ == 0); } if (vxlan_id_ != 0) { if (resource_id_ != 0 || active_vxlan_id_ != 0) { ReleaseVxLanId(false); } else { active_vxlan_id_ = vxlan_id_; } } vxlan_id_ = vxlan_id; if (vxlan_id_ == 0) { return true; } if (vxlan_id_ == active_vxlan_id_) { active_vxlan_id_ = 0; resource_id_ = 0; return true; } return table_->AcquireVxLanId(this, vxlan_id); } void OvsdbResourceVxLanId::ReleaseVxLanId(bool active) { if (active) { if (active_vxlan_id_ != 0) { table_->ReleaseVxLanId(this, active_vxlan_id_, 0); active_vxlan_id_ = 0; } } else { if (vxlan_id_ != 0) { table_->ReleaseVxLanId(this, vxlan_id_, resource_id_); vxlan_id_ = 0; resource_id_ = 0; } } } void OvsdbResourceVxLanId::set_active_vxlan_id(uint32_t vxlan_id) { if (vxlan_id_ == vxlan_id) { assert(resource_id_ == 0); // release previous active vxlan id ReleaseVxLanId(true); return; } if (active_vxlan_id_ == vxlan_id) { // if it is same as active vxlan id return from here return; } assert(vxlan_id == 0); // release previous active vxlan id ReleaseVxLanId(true); } uint32_t OvsdbResourceVxLanId::VxLanId() const { return ((resource_id_ == 0) ? vxlan_id_ : 0); } uint32_t OvsdbResourceVxLanId::active_vxlan_id() const { if (active_vxlan_id_ == 0) { return VxLanId(); } return active_vxlan_id_; } OvsdbResourceVxLanIdTable::OvsdbResourceVxLanIdTable() { } OvsdbResourceVxLanIdTable::~OvsdbResourceVxLanIdTable() { } bool OvsdbResourceVxLanIdTable::AcquireVxLanId(OvsdbResourceVxLanId *entry, uint32_t vxlan_id) { std::map<uint32_t, ResourceEntry*>::iterator tbl_it = vxlan_table_.find(vxlan_id); ResourceEntry *res_entry; if (tbl_it != vxlan_table_.end()) { res_entry = tbl_it->second; } else { res_entry = new ResourceEntry(); vxlan_table_[vxlan_id] = res_entry; } entry->resource_id_ = res_entry->resource_id_count_; res_entry->resource_id_count_++; if (entry->resource_id_ == 0) { // first entry in the list res_entry->active_entry = entry; return true; } else { res_entry->pending_list.insert(entry); } return false; } void OvsdbResourceVxLanIdTable::ReleaseVxLanId(OvsdbResourceVxLanId *entry, uint32_t vxlan_id, uint32_t resource_id) { std::map<uint32_t, ResourceEntry*>::iterator tbl_it = vxlan_table_.find(vxlan_id); assert(tbl_it != vxlan_table_.end()); ResourceEntry *res_entry = tbl_it->second; if (resource_id == 0) { assert(res_entry->active_entry == entry); ResourcePendingList::iterator it = res_entry->pending_list.begin(); if (it == res_entry->pending_list.end()) { vxlan_table_.erase(tbl_it); delete res_entry; } else { (*it)->resource_id_ = 0; res_entry->active_entry = (*it); KSyncEntry *ovs_entry = (*it)->entry_; // only trigger for active entry if (ovs_entry->IsActive() && ovs_entry->GetObject() && (ovs_entry->GetObject()->delete_scheduled() == false)) { ovs_entry->GetObject()->Change(ovs_entry); } res_entry->pending_list.erase(it); if (res_entry->pending_list.empty()) { res_entry->resource_id_count_ = 1; } } } else { OvsdbResourceVxLanId key(NULL, entry->entry_); key.resource_id_ = resource_id; ResourcePendingList::iterator it = res_entry->pending_list.find(&key); assert(it != res_entry->pending_list.end()); res_entry->pending_list.erase(it); } }
29.433962
78
0.596795
jnpr-pranav
e56470106e642884890ee85c08b837144a8feafb
7,624
hpp
C++
library/ATF/CD3DApplicationInfo.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/CD3DApplicationInfo.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/CD3DApplicationInfo.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <CD3DApplication.hpp> START_ATF_NAMESPACE namespace Info { using CD3DApplicationAdjustWindowForChange1_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationAdjustWindowForChange1_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationAdjustWindowForChange1_ptr); using CD3DApplicationBuildDeviceList2_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationBuildDeviceList2_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationBuildDeviceList2_ptr); using CD3DApplicationctor_CD3DApplication3_ptr = int64_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationctor_CD3DApplication3_clbk = int64_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationctor_CD3DApplication3_ptr); using CD3DApplicationCleanup3DEnvironment4_ptr = void (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationCleanup3DEnvironment4_clbk = void (WINAPIV*)(struct CD3DApplication*, CD3DApplicationCleanup3DEnvironment4_ptr); using CD3DApplicationConfirmDevice5_ptr = int32_t (WINAPIV*)(struct CD3DApplication*, struct _D3DCAPS8*, uint32_t, _D3DFORMAT); using CD3DApplicationConfirmDevice5_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, struct _D3DCAPS8*, uint32_t, _D3DFORMAT, CD3DApplicationConfirmDevice5_ptr); using CD3DApplicationCreate6_ptr = int32_t (WINAPIV*)(struct CD3DApplication*, HINSTANCE); using CD3DApplicationCreate6_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, HINSTANCE, CD3DApplicationCreate6_ptr); using CD3DApplicationCreateDirect3D7_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationCreateDirect3D7_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationCreateDirect3D7_ptr); using CD3DApplicationDeleteDeviceObjects8_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationDeleteDeviceObjects8_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationDeleteDeviceObjects8_ptr); using CD3DApplicationDisplayErrorMsg9_ptr = int32_t (WINAPIV*)(struct CD3DApplication*, int32_t, uint32_t); using CD3DApplicationDisplayErrorMsg9_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, int32_t, uint32_t, CD3DApplicationDisplayErrorMsg9_ptr); using CD3DApplicationEndLoop10_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationEndLoop10_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationEndLoop10_ptr); using CD3DApplicationFinalCleanup11_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationFinalCleanup11_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationFinalCleanup11_ptr); using CD3DApplicationFindDepthStencilFormat12_ptr = int64_t (WINAPIV*)(struct CD3DApplication*, unsigned int, CD3DApplication::_D3DDEVTYPE, _D3DFORMAT, _D3DFORMAT*); using CD3DApplicationFindDepthStencilFormat12_clbk = int64_t (WINAPIV*)(struct CD3DApplication*, unsigned int, CD3DApplication::_D3DDEVTYPE, _D3DFORMAT, _D3DFORMAT*, CD3DApplicationFindDepthStencilFormat12_ptr); using CD3DApplicationForceWindowed13_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationForceWindowed13_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationForceWindowed13_ptr); using CD3DApplicationFrameMove14_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationFrameMove14_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationFrameMove14_ptr); using CD3DApplicationInitDeviceObjects15_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationInitDeviceObjects15_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationInitDeviceObjects15_ptr); using CD3DApplicationInitialize3DEnvironment16_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationInitialize3DEnvironment16_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationInitialize3DEnvironment16_ptr); using CD3DApplicationInvalidateDeviceObjects17_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationInvalidateDeviceObjects17_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationInvalidateDeviceObjects17_ptr); using CD3DApplicationMsgProc18_ptr = int64_t (WINAPIV*)(struct CD3DApplication*, HWND, UINT, WPARAM, LPARAM); using CD3DApplicationMsgProc18_clbk = int64_t (WINAPIV*)(struct CD3DApplication*, HWND, UINT, WPARAM, LPARAM, CD3DApplicationMsgProc18_ptr); using CD3DApplicationOneTimeSceneInit19_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationOneTimeSceneInit19_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationOneTimeSceneInit19_ptr); using CD3DApplicationPause20_ptr = void (WINAPIV*)(struct CD3DApplication*, int); using CD3DApplicationPause20_clbk = void (WINAPIV*)(struct CD3DApplication*, int, CD3DApplicationPause20_ptr); using CD3DApplicationPrepareLoop21_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationPrepareLoop21_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationPrepareLoop21_ptr); using CD3DApplicationRelease22_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationRelease22_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationRelease22_ptr); using CD3DApplicationRender23_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationRender23_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationRender23_ptr); using CD3DApplicationRender3DEnvironment24_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationRender3DEnvironment24_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationRender3DEnvironment24_ptr); using CD3DApplicationResize3DEnvironment25_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationResize3DEnvironment25_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationResize3DEnvironment25_ptr); using CD3DApplicationRestoreDeviceObjects26_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationRestoreDeviceObjects26_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationRestoreDeviceObjects26_ptr); using CD3DApplicationRun27_ptr = int64_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationRun27_clbk = int64_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationRun27_ptr); using CD3DApplicationSelectDeviceProc28_ptr = int64_t (WINAPIV*)(HWND__*, unsigned int, uint64_t, int64_t); using CD3DApplicationSelectDeviceProc28_clbk = int64_t (WINAPIV*)(HWND__*, unsigned int, uint64_t, int64_t, CD3DApplicationSelectDeviceProc28_ptr); using CD3DApplicationToggleFullscreen29_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationToggleFullscreen29_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationToggleFullscreen29_ptr); using CD3DApplicationUserSelectNewDevice30_ptr = int32_t (WINAPIV*)(struct CD3DApplication*); using CD3DApplicationUserSelectNewDevice30_clbk = int32_t (WINAPIV*)(struct CD3DApplication*, CD3DApplicationUserSelectNewDevice30_ptr); }; // end namespace Info END_ATF_NAMESPACE
103.027027
219
0.797613
lemkova
e564c3e71bca048d54edb8b13dcfcd96bf76d6ea
3,315
hpp
C++
include/Mahi/Robo/Mechatronics/AtiSensor.hpp
mahilab/mahi-robo
8df76b7d0174feb3569182cbd65b0305d2a57a22
[ "MIT" ]
1
2020-05-07T13:40:28.000Z
2020-05-07T13:40:28.000Z
include/Mahi/Robo/Mechatronics/AtiSensor.hpp
mahilab/mahi-robo
8df76b7d0174feb3569182cbd65b0305d2a57a22
[ "MIT" ]
null
null
null
include/Mahi/Robo/Mechatronics/AtiSensor.hpp
mahilab/mahi-robo
8df76b7d0174feb3569182cbd65b0305d2a57a22
[ "MIT" ]
1
2020-12-21T09:44:36.000Z
2020-12-21T09:44:36.000Z
// MIT License // // Copyright (c) 2020 Mechatronics and Haptic Interfaces Lab - Rice University // // 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. // // Author(s): Evan Pezent (epezent@rice.edu) #pragma once #include <Mahi/Robo/Mechatronics/ForceSensor.hpp> #include <Mahi/Robo/Mechatronics/TorqueSensor.hpp> #include <array> #include <string> namespace mahi { namespace robo { /// Implements an ATI force/torque transducer class AtiSensor : public ForceSensor, public TorqueSensor { public: /// Calibration matrix data obtained from "UserAxis" elements /// in ATI supplied calibration file (e.g. "FTXXXXX.cal") struct Calibration { std::array<double, 6> Fx; std::array<double, 6> Fy; std::array<double, 6> Fz; std::array<double, 6> Tx; std::array<double, 6> Ty; std::array<double, 6> Tz; }; public: /// Constucts AtiSensor with unspecified channels and no calibration AtiSensor(); /// Constructs AtiSensor with specified channels and loads calibration from filepath AtiSensor(const double* ch0, const double* ch1, const double* ch2, const double* ch3, const double* ch4, const double* ch5, const std::string& filepath); /// Constructs AtiSensor from specified channels and manual calibration AtiSensor(const double* ch0, const double* ch1, const double* ch2, const double* ch3, const double* ch4, const double* ch5, Calibration calibration); /// Sets the voltages channels associated with this ATI sensor void set_channels(const double* ch0, const double* ch1, const double* ch2, const double* ch3, const double* ch4, const double* ch5); /// Loads calibration from ATI calibration file (e.g. "FTXXXXX.cal") bool load_calibration(const std::string& filepath); /// Allows for manually setting calibration void set_calibration(Calibration calibration); /// Returns force along specified axis double get_force(Axis axis) override; /// Returns forces along X, Z, and Z axes std::vector<double> get_forces() override; /// Returns torque along specifed axis double get_torque(Axis axis) override; /// Returns torque along X, Z, and Z axes std::vector<double> get_torques() override; /// Zeros all forces and torques at current preload void zero() override; private: /// Updates biased voltages void update_biased_voltages(); private: std::vector<const double*> channels_; ///< raw voltage channels Calibration calibration_; ///< calibration matrix std::array<double, 6> bias_; ///< bias vector std::array<double, 6> bSTG_; ///< biased strain gauge voltages }; } // namespace robo } // namespace mahi
41.4375
97
0.694419
mahilab
e56775b18ae4c15e295d984d0440e50c30161375
2,852
cpp
C++
cpp/basix/brezzi-douglas-marini.cpp
nikhilTkur/basix
62b1a3b903f1aabbe207e848595432d5a2da0dba
[ "MIT" ]
null
null
null
cpp/basix/brezzi-douglas-marini.cpp
nikhilTkur/basix
62b1a3b903f1aabbe207e848595432d5a2da0dba
[ "MIT" ]
null
null
null
cpp/basix/brezzi-douglas-marini.cpp
nikhilTkur/basix
62b1a3b903f1aabbe207e848595432d5a2da0dba
[ "MIT" ]
null
null
null
// Copyright (c) 2020 Chris Richardson & Matthew Scroggs // FEniCS Project // SPDX-License-Identifier: MIT #include "brezzi-douglas-marini.h" #include "element-families.h" #include "lagrange.h" #include "maps.h" #include "moments.h" #include "nedelec.h" #include "polyset.h" #include "quadrature.h" #include <numeric> #include <vector> #include <xtensor/xbuilder.hpp> #include <xtensor/xpad.hpp> #include <xtensor/xtensor.hpp> #include <xtensor/xview.hpp> using namespace basix; //---------------------------------------------------------------------------- FiniteElement basix::create_bdm(cell::type celltype, int degree) { if (celltype != cell::type::triangle and celltype != cell::type::tetrahedron) throw std::runtime_error("Unsupported cell type"); const std::size_t tdim = cell::topological_dimension(celltype); const cell::type facettype = sub_entity_type(celltype, tdim - 1, 0); // The number of order (degree) scalar polynomials const std::size_t ndofs = tdim * polyset::dim(celltype, degree); // quadrature degree int quad_deg = 5 * degree; std::array<std::vector<xt::xtensor<double, 3>>, 4> M; std::array<std::vector<xt::xtensor<double, 2>>, 4> x; // Add integral moments on facets const FiniteElement facet_moment_space = create_dlagrange(facettype, degree); std::tie(x[tdim - 1], M[tdim - 1]) = moments::make_normal_integral_moments( facet_moment_space, celltype, tdim, quad_deg); const xt::xtensor<double, 3> facet_transforms = moments::create_normal_moment_dof_transformations(facet_moment_space); // Add integral moments on interior if (degree > 1) { // Interior integral moment std::tie(x[tdim], M[tdim]) = moments::make_dot_integral_moments( create_nedelec(celltype, degree - 1), celltype, tdim, quad_deg); } const std::vector<std::vector<std::vector<int>>> topology = cell::topology(celltype); std::map<cell::type, xt::xtensor<double, 3>> entity_transformations; switch (tdim) { case 2: entity_transformations[cell::type::interval] = facet_transforms; break; case 3: entity_transformations[cell::type::interval] = xt::xtensor<double, 3>({1, 0, 0}); entity_transformations[cell::type::triangle] = facet_transforms; break; default: throw std::runtime_error("Invalid topological dimension."); } // Create coefficients for order (degree-1) vector polynomials xt::xtensor<double, 3> coeffs = compute_expansion_coefficients( celltype, xt::eye<double>(ndofs), {M[tdim - 1], M[tdim]}, {x[tdim - 1], x[tdim]}, degree); return FiniteElement(element::family::BDM, celltype, degree, {tdim}, coeffs, entity_transformations, x, M, maps::type::contravariantPiola); } //-----------------------------------------------------------------------------
33.952381
79
0.65568
nikhilTkur
e567fe799a756faf5de1745546fc7f344992a2c7
10,116
cc
C++
thirdparty/aria2/src/DefaultBtMessageDispatcher.cc
deltegic/deltegic
9b4f3a505a6842db52efbe850150afbab3af5e2f
[ "BSD-3-Clause" ]
null
null
null
thirdparty/aria2/src/DefaultBtMessageDispatcher.cc
deltegic/deltegic
9b4f3a505a6842db52efbe850150afbab3af5e2f
[ "BSD-3-Clause" ]
2
2021-04-08T08:46:23.000Z
2021-04-08T08:57:58.000Z
thirdparty/aria2/src/DefaultBtMessageDispatcher.cc
deltegic/deltegic
9b4f3a505a6842db52efbe850150afbab3af5e2f
[ "BSD-3-Clause" ]
null
null
null
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "DefaultBtMessageDispatcher.h" #include <algorithm> #include "prefs.h" #include "BtAbortOutstandingRequestEvent.h" #include "BtCancelSendingPieceEvent.h" #include "BtChokingEvent.h" #include "BtMessageFactory.h" #include "message.h" #include "DownloadContext.h" #include "PeerStorage.h" #include "PieceStorage.h" #include "BtMessage.h" #include "Peer.h" #include "Piece.h" #include "LogFactory.h" #include "Logger.h" #include "a2functional.h" #include "a2algo.h" #include "RequestGroupMan.h" #include "RequestGroup.h" #include "util.h" #include "fmt.h" #include "PeerConnection.h" #include "BtCancelMessage.h" namespace aria2 { DefaultBtMessageDispatcher::DefaultBtMessageDispatcher() : cuid_{0}, downloadContext_{nullptr}, peerConnection_{nullptr}, messageFactory_{nullptr}, requestGroupMan_{nullptr}, requestTimeout_{0} { } DefaultBtMessageDispatcher::~DefaultBtMessageDispatcher() { A2_LOG_DEBUG("DefaultBtMessageDispatcher::deleted"); } void DefaultBtMessageDispatcher::addMessageToQueue( std::unique_ptr<BtMessage> btMessage) { btMessage->onQueued(); messageQueue_.push_back(std::move(btMessage)); } void DefaultBtMessageDispatcher::sendMessagesInternal() { auto tempQueue = std::vector<std::unique_ptr<BtMessage>>{}; while (!messageQueue_.empty()) { auto msg = std::move(messageQueue_.front()); messageQueue_.pop_front(); if (msg->isUploading()) { if (requestGroupMan_->doesOverallUploadSpeedExceed() || downloadContext_->getOwnerRequestGroup()->doesUploadSpeedExceed()) { tempQueue.push_back(std::move(msg)); continue; } } msg->send(); } if (!tempQueue.empty()) { messageQueue_.insert(std::begin(messageQueue_), std::make_move_iterator(std::begin(tempQueue)), std::make_move_iterator(std::end(tempQueue))); } } void DefaultBtMessageDispatcher::sendMessages() { if (peerConnection_->getBufferEntrySize() < A2_IOV_MAX) { sendMessagesInternal(); } peerConnection_->sendPendingData(); } namespace { std::vector<BtMessage*> toRawPointers(const std::deque<std::unique_ptr<BtMessage>>& v) { auto x = std::vector<BtMessage*>{}; x.reserve(v.size()); for (auto& i : v) { x.push_back(i.get()); } return x; } } // namespace // Cancel sending piece message to peer. void DefaultBtMessageDispatcher::doCancelSendingPieceAction(size_t index, int32_t begin, int32_t length) { BtCancelSendingPieceEvent event(index, begin, length); auto q = toRawPointers(messageQueue_); for (auto i : q) { i->onCancelSendingPieceEvent(event); } } // Cancel sending piece message to peer. // TODO Is this method really necessary? void DefaultBtMessageDispatcher::doCancelSendingPieceAction( const std::shared_ptr<Piece>& piece) { } namespace { void abortOutstandingRequest(const RequestSlot* slot, const std::shared_ptr<Piece>& piece, cuid_t cuid) { A2_LOG_DEBUG(fmt(MSG_DELETING_REQUEST_SLOT, cuid, static_cast<unsigned long>(slot->getIndex()), slot->getBegin(), static_cast<unsigned long>(slot->getBlockIndex()))); piece->cancelBlock(slot->getBlockIndex()); } } // namespace // localhost cancels outstanding download requests to the peer. void DefaultBtMessageDispatcher::doAbortOutstandingRequestAction( const std::shared_ptr<Piece>& piece) { for (auto& slot : requestSlots_) { if (slot->getIndex() == piece->getIndex()) { abortOutstandingRequest(slot.get(), piece, cuid_); } } requestSlots_.erase( std::remove_if(std::begin(requestSlots_), std::end(requestSlots_), [&](const std::unique_ptr<RequestSlot>& slot) { return slot->getIndex() == piece->getIndex(); }), std::end(requestSlots_)); BtAbortOutstandingRequestEvent event(piece); auto tempQueue = toRawPointers(messageQueue_); for (auto i : tempQueue) { i->onAbortOutstandingRequestEvent(event); } } // localhost received choke message from the peer. void DefaultBtMessageDispatcher::doChokedAction() { for (auto& slot : requestSlots_) { if (!peer_->isInPeerAllowedIndexSet(slot->getIndex())) { A2_LOG_DEBUG(fmt(MSG_DELETING_REQUEST_SLOT_CHOKED, cuid_, static_cast<unsigned long>(slot->getIndex()), slot->getBegin(), static_cast<unsigned long>(slot->getBlockIndex()))); slot->getPiece()->cancelBlock(slot->getBlockIndex()); } } requestSlots_.erase( std::remove_if(std::begin(requestSlots_), std::end(requestSlots_), [&](const std::unique_ptr<RequestSlot>& slot) { return !peer_->isInPeerAllowedIndexSet(slot->getIndex()); }), std::end(requestSlots_)); } // localhost dispatched choke message to the peer. void DefaultBtMessageDispatcher::doChokingAction() { BtChokingEvent event; auto tempQueue = toRawPointers(messageQueue_); for (auto i : tempQueue) { i->onChokingEvent(event); } } void DefaultBtMessageDispatcher::checkRequestSlotAndDoNecessaryThing() { for (auto& slot : requestSlots_) { if (slot->isTimeout(requestTimeout_)) { A2_LOG_DEBUG(fmt(MSG_DELETING_REQUEST_SLOT_TIMEOUT, cuid_, static_cast<unsigned long>(slot->getIndex()), slot->getBegin(), static_cast<unsigned long>(slot->getBlockIndex()))); slot->getPiece()->cancelBlock(slot->getBlockIndex()); peer_->snubbing(true); } else if (slot->getPiece()->hasBlock(slot->getBlockIndex())) { A2_LOG_DEBUG(fmt(MSG_DELETING_REQUEST_SLOT_ACQUIRED, cuid_, static_cast<unsigned long>(slot->getIndex()), slot->getBegin(), static_cast<unsigned long>(slot->getBlockIndex()))); addMessageToQueue(messageFactory_->createCancelMessage( slot->getIndex(), slot->getBegin(), slot->getLength())); } } requestSlots_.erase( std::remove_if(std::begin(requestSlots_), std::end(requestSlots_), [&](const std::unique_ptr<RequestSlot>& slot) { return slot->isTimeout(requestTimeout_) || slot->getPiece()->hasBlock(slot->getBlockIndex()); }), std::end(requestSlots_)); } bool DefaultBtMessageDispatcher::isSendingInProgress() { return peerConnection_->getBufferEntrySize(); } bool DefaultBtMessageDispatcher::isOutstandingRequest(size_t index, size_t blockIndex) { for (auto& slot : requestSlots_) { if (slot->getIndex() == index && slot->getBlockIndex() == blockIndex) { return true; } } return false; } const RequestSlot* DefaultBtMessageDispatcher::getOutstandingRequest(size_t index, int32_t begin, int32_t length) { for (auto& slot : requestSlots_) { if (slot->getIndex() == index && slot->getBegin() == begin && slot->getLength() == length) { return slot.get(); } } return nullptr; } void DefaultBtMessageDispatcher::removeOutstandingRequest( const RequestSlot* slot) { for (auto i = std::begin(requestSlots_), eoi = std::end(requestSlots_); i != eoi; ++i) { if (*(*i) == *slot) { abortOutstandingRequest((*i).get(), (*i)->getPiece(), cuid_); requestSlots_.erase(i); break; } } } void DefaultBtMessageDispatcher::addOutstandingRequest( std::unique_ptr<RequestSlot> slot) { requestSlots_.push_back(std::move(slot)); } size_t DefaultBtMessageDispatcher::countOutstandingUpload() { return std::count_if(std::begin(messageQueue_), std::end(messageQueue_), std::mem_fn(&BtMessage::isUploading)); } void DefaultBtMessageDispatcher::setPeer(const std::shared_ptr<Peer>& peer) { peer_ = peer; } void DefaultBtMessageDispatcher::setDownloadContext( DownloadContext* downloadContext) { downloadContext_ = downloadContext; } void DefaultBtMessageDispatcher::setBtMessageFactory(BtMessageFactory* factory) { messageFactory_ = factory; } void DefaultBtMessageDispatcher::setRequestGroupMan(RequestGroupMan* rgman) { requestGroupMan_ = rgman; } } // namespace aria2
31.6125
80
0.666568
deltegic
e56b185395191bc7c313969043e419e2ad1b893d
4,119
cpp
C++
src/tests/functional/plugin/gpu/concurrency/gpu_concurrency_tests.cpp
ivkalgin/openvino
81685c8d212135dd9980da86a18db41fbf6d250a
[ "Apache-2.0" ]
null
null
null
src/tests/functional/plugin/gpu/concurrency/gpu_concurrency_tests.cpp
ivkalgin/openvino
81685c8d212135dd9980da86a18db41fbf6d250a
[ "Apache-2.0" ]
18
2022-01-21T08:42:58.000Z
2022-03-28T13:21:31.000Z
src/tests/functional/plugin/gpu/concurrency/gpu_concurrency_tests.cpp
ematroso/openvino
403339f8f470c90dee6f6d94ed58644b2787f66b
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <string> #include <utility> #include <vector> #include <memory> #include "openvino/runtime/core.hpp" #include <gpu/gpu_config.hpp> #include <common_test_utils/test_common.hpp> #include <functional_test_utils/plugin_cache.hpp> #include "ngraph_functions/subgraph_builders.hpp" #include "functional_test_utils/blob_utils.hpp" #include "openvino/core/preprocess/pre_post_process.hpp" #include "transformations/utils/utils.hpp" using namespace ::testing; using ConcurrencyTestParams = std::tuple<size_t, // number of streams size_t>; // number of requests class OVConcurrencyTest : public CommonTestUtils::TestsCommon, public testing::WithParamInterface<ConcurrencyTestParams> { void SetUp() override { std::tie(num_streams, num_requests) = this->GetParam(); fn_ptrs = {ngraph::builder::subgraph::makeSplitMultiConvConcat(), ngraph::builder::subgraph::makeMultiSingleConv()}; }; public: static std::string getTestCaseName(const testing::TestParamInfo<ConcurrencyTestParams>& obj) { size_t streams, requests; std::tie(streams, requests) = obj.param; return "_num_streams_" + std::to_string(streams) + "_num_req_" + std::to_string(requests); } protected: size_t num_streams; size_t num_requests; std::vector<std::shared_ptr<ngraph::Function>> fn_ptrs; }; TEST_P(OVConcurrencyTest, canInferTwoExecNets) { auto ie = ov::runtime::Core(); ov::ResultVector outputs; std::vector<ov::runtime::InferRequest> irs; std::vector<std::vector<uint8_t>> ref; std::vector<int> outElementsCount; for (size_t i = 0; i < fn_ptrs.size(); ++i) { auto fn = fn_ptrs[i]; auto exec_net = ie.compile_model(fn_ptrs[i], CommonTestUtils::DEVICE_GPU, {{ov::ie::PluginConfigParams::KEY_GPU_THROUGHPUT_STREAMS, std::to_string(num_streams)}}); auto input = fn_ptrs[i]->get_parameters().at(0); auto output = fn_ptrs[i]->get_results().at(0); for (int j = 0; j < num_streams * num_requests; j++) { outputs.push_back(output); auto inf_req = exec_net.create_infer_request(); irs.push_back(inf_req); auto tensor = FuncTestUtils::create_and_fill_tensor(input->get_element_type(), input->get_shape()); inf_req.set_tensor(input, tensor); outElementsCount.push_back(ov::shape_size(fn_ptrs[i]->get_output_shape(0))); const auto in_tensor = inf_req.get_tensor(input); const auto tensorSize = in_tensor.get_byte_size(); const auto inBlobBuf = static_cast<uint8_t*>(in_tensor.data()); std::vector<uint8_t> inData(inBlobBuf, inBlobBuf + tensorSize); auto reOutData = ngraph::helpers::interpreterFunction(fn_ptrs[i], {inData}).front().second; ref.push_back(reOutData); } } const int niter = 10; for (int i = 0; i < niter; i++) { for (auto ir : irs) { ir.start_async(); } for (auto ir : irs) { ir.wait(); } } auto thr = FuncTestUtils::GetComparisonThreshold(InferenceEngine::Precision::FP32); for (size_t i = 0; i < irs.size(); ++i) { const auto &refBuffer = ref[i].data(); ASSERT_EQ(outElementsCount[i], irs[i].get_tensor(outputs[i]).get_size()); FuncTestUtils::compareRawBuffers(irs[i].get_tensor(outputs[i]).data<float>(), reinterpret_cast<const float *>(refBuffer), outElementsCount[i], outElementsCount[i], thr); } } const std::vector<size_t> num_streams{ 1, 2 }; const std::vector<size_t> num_requests{ 1, 4 }; INSTANTIATE_TEST_SUITE_P(smoke_RemoteTensor, OVConcurrencyTest, ::testing::Combine(::testing::ValuesIn(num_streams), ::testing::ValuesIn(num_requests)), OVConcurrencyTest::getTestCaseName);
37.108108
130
0.636562
ivkalgin
e56b5728f7bc6af2b0f1f216f2713363e3047faa
577
hpp
C++
include/fcppt/math/detail/binary_type.hpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
include/fcppt/math/detail/binary_type.hpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
include/fcppt/math/detail/binary_type.hpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_MATH_DETAIL_BINARY_TYPE_HPP_INCLUDED #define FCPPT_MATH_DETAIL_BINARY_TYPE_HPP_INCLUDED #include <fcppt/config/external_begin.hpp> #include <type_traits> #include <fcppt/config/external_end.hpp> #define FCPPT_MATH_DETAIL_BINARY_TYPE(\ left,\ op,\ right\ ) \ decltype(\ std::declval<left>() \ op \ std::declval<right>() \ ) #endif
20.607143
61
0.729636
vinzenz
e57059c1223fa766359d5c15c87c1a0537d43e5f
6,367
cpp
C++
src/gamebase/src/impl/ui/ScrollBar.cpp
TheMrButcher/opengl_lessons
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
1
2016-10-25T21:15:16.000Z
2016-10-25T21:15:16.000Z
src/gamebase/src/impl/ui/ScrollBar.cpp
TheMrButcher/gamebase
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
375
2016-06-04T11:27:40.000Z
2019-04-14T17:11:09.000Z
src/gamebase/src/impl/ui/ScrollBar.cpp
TheMrButcher/gamebase
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
null
null
null
/** * Copyright (c) 2018 Slavnejshev Filipp * This file is licensed under the terms of the MIT license. */ #include <stdafx.h> #include <gamebase/impl/ui/ScrollBar.h> #include <gamebase/impl/geom/PointGeometry.h> #include <gamebase/impl/geom/RectGeometry.h> #include <gamebase/impl/serial/ISerializer.h> #include <gamebase/impl/serial/IDeserializer.h> #include <gamebase/math/Math.h> namespace gamebase { namespace impl { class ScrollBar::DragBarMovement : public FloatValue { public: DragBarMovement(ScrollBar* scrollBar) : m_scrollBar(scrollBar) {} virtual float get() const override { THROW_EX() << "DragBarMovement::get() is unsupported"; } virtual void set(const float& value) override { if (!m_scrollBar->m_controlledValue) return; if (value == 0.0f) m_start = m_scrollBar->m_controlledValue->get(); else m_scrollBar->dragByPixels(m_start, value); } private: ScrollBar* m_scrollBar; float m_start; }; ScrollBar::ScrollBar( const std::shared_ptr<ScrollBarSkin>& skin, const std::shared_ptr<IRelativeOffset>& position) : OffsettedPosition(position) , Drawable(this) , m_skin(skin) , m_inited(false) , m_minVal(0) , m_maxVal(0) , m_visibleZoneSize(0) , m_dragBarOffset(std::make_shared<FixedOffset>()) , m_dragBarCallback(std::make_shared<DragBarMovement>(this)) , m_sizeFunc(m_skin->direction() == Direction::Horizontal ? &BoundingBox::width : &BoundingBox::height) { m_collection.setParentPosition(this); if (auto decButton = skin->createDecButton()) { decButton->setCallback([this]() { decrease(); }); m_collection.addObject(decButton); } if (auto incButton = skin->createIncButton()) { incButton->setCallback([this]() { increase(); }); m_collection.addObject(incButton); } if (m_dragBar = skin->createDragBar(m_dragBarOffset)) { if (m_skin->direction() == Direction::Horizontal) m_dragBar->setControlledHorizontal(m_dragBarCallback); else m_dragBar->setControlledVertical(m_dragBarCallback); m_collection.addObject(m_dragBar); } } void ScrollBar::move(float numOfSteps) { step(numOfSteps * m_skin->step()); } void ScrollBar::loadResources() { m_skin->loadResources(); m_collection.loadResources(); if (!m_inited) { m_inited = true; update(); m_collection.loadResources(); } } void ScrollBar::setBox(const BoundingBox& allowedBox) { m_skin->setBox(allowedBox); auto box = m_skin->box(); setPositionBoxes(allowedBox, box); m_collection.setBox(box); update(); } IScrollable* ScrollBar::findScrollableByPoint(const Vec2& point) { if (!isVisible()) return false; PointGeometry pointGeom(point); RectGeometry rectGeom(box()); if (!rectGeom.intersects(&pointGeom, position(), Transform2())) return nullptr; return this; } void ScrollBar::registerObject(PropertiesRegisterBuilder* builder) { builder->registerObject("skin", m_skin.get()); builder->registerObject("objects", &m_collection); } void ScrollBar::applyScroll(float scroll) { if (isVisible()) move(scroll); } void ScrollBar::serialize(Serializer& s) const { s << "minValue" << m_minVal << "maxValue" << m_maxVal << "visibleZone" << m_visibleZoneSize << "position" << m_offset << "skin" << m_skin; } std::unique_ptr<IObject> deserializeScrollBar(Deserializer& deserializer) { DESERIALIZE(std::shared_ptr<IRelativeOffset>, position); DESERIALIZE(std::shared_ptr<ScrollBarSkin>, skin); DESERIALIZE(float, minValue); DESERIALIZE(float, maxValue); DESERIALIZE(float, visibleZone); std::unique_ptr<ScrollBar> result(new ScrollBar(skin, position)); result->setRange(minValue, maxValue); result->setVisibleZoneSize(visibleZone); return std::move(result); } REGISTER_CLASS(ScrollBar); void ScrollBar::decrease() { move(-1); } void ScrollBar::increase() { move(+1); } void ScrollBar::update() { if (!m_inited) return; if (m_dragBar && box().isValid()) { auto dragBox = m_skin->dragBox(); if (m_visibleZoneSize >= m_maxVal - m_minVal) { if (!m_skin->alwaysShow()) { setVisible(false); } else { m_dragBar->setSelectionState(SelectionState::Disabled); } } else { setVisible(true); float boxSize = (dragBox.*m_sizeFunc)(); float dragBarSize = boxSize * m_visibleZoneSize / (m_maxVal - m_minVal); BoundingBox dragBarBox = m_skin->direction() == Direction::Horizontal ? BoundingBox( Vec2(-0.5f * dragBarSize, -0.5f * dragBox.height()), Vec2(0.5f * dragBarSize, 0.5f * dragBox.height())) : BoundingBox( Vec2(-0.5f * dragBox.width(), -0.5f * dragBarSize), Vec2(0.5f * dragBox.width(), 0.5f * dragBarSize)); m_dragBar->setBox(dragBarBox); m_dragBar->setSelectionState(SelectionState::None); } } step(0.0f); } void ScrollBar::dragByPixels(float startValue, float offsetInPixels) { float offset = offsetInPixels / (m_skin->dragBox().*m_sizeFunc)() * (m_maxVal - m_minVal); step(startValue + offset - m_controlledValue->get()); } void ScrollBar::step(float value) { if (!m_controlledValue) return; float curVal = m_controlledValue->get(); m_controlledValue->set(clamp( curVal + value, m_minVal, std::max(m_minVal, m_maxVal - m_visibleZoneSize))); if (m_dragBar && m_dragBar->selectionState() != SelectionState::Disabled && box().isValid()) { auto dragBox = m_skin->dragBox(); curVal = m_controlledValue->get(); float midRatio = (curVal + 0.5f * m_visibleZoneSize) / (m_maxVal - m_minVal); Vec2 offset = m_skin->direction() == Direction::Horizontal ? Vec2( dragBox.bottomLeft.x + midRatio * dragBox.width(), 0.5f * (dragBox.bottomLeft.y + dragBox.topRight.y)) : Vec2( 0.5f * (dragBox.bottomLeft.x + dragBox.topRight.x), dragBox.bottomLeft.y + midRatio * dragBox.height()); m_dragBarOffset->update(offset); } } } }
31.058537
98
0.639705
TheMrButcher
e5706f801da9659f49e9f9825e89e2ebdcb06b31
8,942
cpp
C++
src/autowiring/test/AutoPacketFactoryTest.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
87
2015-01-18T00:43:06.000Z
2022-02-11T17:40:50.000Z
src/autowiring/test/AutoPacketFactoryTest.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
274
2015-01-03T04:50:49.000Z
2021-03-08T09:01:09.000Z
src/autowiring/test/AutoPacketFactoryTest.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
15
2015-09-30T20:58:43.000Z
2020-12-19T21:24:56.000Z
// Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include <autowiring/CoreThread.h> #include CHRONO_HEADER #include THREAD_HEADER class AutoPacketFactoryTest: public testing::Test {}; TEST_F(AutoPacketFactoryTest, VerifyNoIssueWhileNotStarted) { AutoRequired<AutoPacketFactory> factory; ASSERT_THROW(factory->NewPacket(), autowiring_error) << "Issuing a packet in a context that has not yet been started should throw an exception"; } TEST_F(AutoPacketFactoryTest, StopReallyStops) { AutoCurrentContext()->SignalShutdown(); AutoRequired<AutoPacketFactory> factory; ASSERT_TRUE(factory->ShouldStop()) << "Expected that an attempt to insert a packet factory to an already-stopped context would stop the packet factory"; } TEST_F(AutoPacketFactoryTest, VerifyNoIssueWhileStopped) { AutoCurrentContext()->SignalShutdown(); AutoRequired<AutoPacketFactory> factory; ASSERT_THROW(factory->NewPacket(), autowiring_error) << "Issuing a packet in a context that has already been stopped should throw an exception"; } class IssuesPacketWaitsThenQuits: public CoreThread { public: IssuesPacketWaitsThenQuits(void) { // Note: Don't do this in practice. This only works because we only inject this type // into a context that's already running; normally, creating a packet from our ctor can // cause an exception if we are being injected before Initiate is called. AutoRequired<AutoPacketFactory> factory; m_packet = factory->NewPacket(); } bool m_hasQuit = false; std::shared_ptr<AutoPacket> m_packet; void Run(void) override { // Move shared pointer locally: std::shared_ptr<AutoPacket> packet; std::swap(packet, m_packet); // Just wait a bit, then return, just like we said we would this->ThreadSleep(std::chrono::milliseconds(50)); // Update our variable and then return out: m_hasQuit = true; } }; TEST_F(AutoPacketFactoryTest, WaitRunsDownAllPackets) { AutoCurrentContext()->Initiate(); // Create a factory in our context, factory had better be started: AutoRequired<AutoPacketFactory> factory; ASSERT_TRUE(factory->IsRunning()) << "Factory was not started even though it was a member of an initiated context"; // Make the thread create and hold a packet, and then return AutoRequired<IssuesPacketWaitsThenQuits> ipwtq; // Shutdown context AutoCurrentContext()->SignalShutdown(); // Now we're going to try to run down the factory: factory->Wait(); // Verify that the thread has quit: ASSERT_TRUE(ipwtq->m_hasQuit) << "AutoPacketFactory::Wait returned prematurely"; } class HoldsAutoPacketFactoryReference { public: AutoRequired<AutoPacketFactory> m_factory; int m_value = 0; // Just a dummy AutoFilter method so that this class is recognized as an AutoFilter void AutoFilter(int value) { m_value = value; } }; TEST_F(AutoPacketFactoryTest, AutoPacketFactoryCycle) { AutoCurrentContext()->Initiate(); std::weak_ptr<CoreContext> ctxtWeak; std::weak_ptr<HoldsAutoPacketFactoryReference> hapfrWeak; std::shared_ptr<AutoPacket> packet; { // Create a context, fill it up, kick it off: AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); AutoRequired<HoldsAutoPacketFactoryReference> hapfr(ctxt); ctxt->Initiate(); // A weak pointer is used to detect object destruction ctxtWeak = ctxt; hapfrWeak = hapfr; // Trivial validation-of-reciept: AutoRequired<AutoPacketFactory> factory; { auto trivial = factory->NewPacket(); trivial->Decorate((int) 54); ASSERT_EQ(54, hapfr->m_value) << "A simple packet was not received as expected by an AutoFilter"; } // Create a packet which will force in a back-reference: packet = factory->NewPacket(); // Terminate the context: ctxt->SignalShutdown(); // Verify that we can still decorate the packet and also that the packet is delivered to the factory: packet->Decorate((int) 55); // Relock, verify the value was received by the hapfr: ASSERT_EQ(55, hapfr->m_value) << "AutoFilter did not receive a packet as expected"; } // The context cannot go out of socpe until all packets in the context are out of scope ASSERT_FALSE(ctxtWeak.expired()) << "Context went out of scope before all packets were finished being processed"; // Now we can release the packet and verify that everything gets cleaned up: packet.reset(); ASSERT_TRUE(ctxtWeak.expired()) << "AutoPacketFactory incorrectly held a cyclic reference even after the context was shut down"; ASSERT_TRUE(hapfrWeak.expired()) << "The last packet from a factory was released; this should have resulted in teardown, but it did not"; } class DelaysAutoPacketsOneMS { public: void AutoFilter(int value) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } }; TEST_F(AutoPacketFactoryTest, AutoPacketStatistics) { // Create a context, fill it up, kick it off: AutoCurrentContext ctxt; AutoRequired<DelaysAutoPacketsOneMS> dapoms; AutoRequired<AutoPacketFactory> factory; ctxt->Initiate(); int numPackets = 20; // Send 20 packets which should all be delayed 1ms for (int i = 0; i < numPackets; ++i) { auto packet = factory->NewPacket(); packet->Decorate(i); } // Shutdown our context, and rundown our factory ctxt->SignalShutdown(); factory->Wait(); // Ensure that the statistics are not too wrong // We delayed each packet by one ms, and our statistics are given in nanoseconds double packetDelay = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::milliseconds(1)).count(); ASSERT_EQ(numPackets, factory->GetTotalPacketCount()) << "The factory did not get enough packets"; ASSERT_LE(packetDelay, factory->GetMeanPacketLifetime()) << "The mean packet lifetime was less than the delay on each packet"; } TEST_F(AutoPacketFactoryTest, MultipleInstanceAddition) { AutoCurrentContext ctxt; AutoRequired<AutoPacketFactory> factory; ctxt->Initiate(); bool ary[2] = {}; for (size_t i = 0; i < 2; i++) *factory += [i, &ary] (int) { ary[i] = true; }; auto packet = factory->NewPacket(); packet->Decorate(101); ASSERT_TRUE(ary[0]) << "First of two identically typed AutoFilter lambdas was not called"; ASSERT_TRUE(ary[1]) << "Second of two identically typed AutoFilter lambdas was not called"; } TEST_F(AutoPacketFactoryTest, AddSubscriberTest) { AutoCurrentContext ctxt; AutoRequired<AutoPacketFactory> factory; ctxt->Initiate(); bool first_called = false; bool second_called = false; factory->AddSubscriber(AutoFilterDescriptor([&first_called](int) {first_called = true; })); { std::vector<AutoFilterDescriptor> descs; factory->AppendAutoFiltersTo(descs); ASSERT_EQ(1UL, descs.size()) << "Expected exactly one AutoFilters after call to AddSubscriber"; } *factory += [&second_called] (int v) { second_called = true; ASSERT_EQ(101, v) << "Decoration value mismatch"; }; { std::vector<AutoFilterDescriptor> descs; factory->AppendAutoFiltersTo(descs); ASSERT_EQ(2UL, descs.size()) << "Expected exactly two AutoFilters on this packet"; } auto packet = factory->NewPacket(); ASSERT_FALSE(first_called) << "Normal subscriber called too early"; ASSERT_FALSE(second_called) << "Subscriber added with operator+= called too early"; packet->DecorateImmediate(int(101)); ASSERT_TRUE(first_called) << "Normal subscriber never called"; ASSERT_TRUE(second_called) << "Subscriber added with operator+= never called"; } TEST_F(AutoPacketFactoryTest, CanRemoveAddedLambda) { AutoCurrentContext()->Initiate(); AutoRequired<AutoPacketFactory> factory; auto desc = *factory += [](int&){}; auto packet1 = factory->NewPacket(); *factory -= desc; auto packet2 = factory->NewPacket(); ASSERT_TRUE(packet1->Has<int>()) << "First packet did not posess expected decoration"; ASSERT_FALSE(packet2->Has<int>()) << "Decoration present even after all filters were removed from a factory"; } TEST_F(AutoPacketFactoryTest, CurrentPacket) { AutoCurrentContext()->Initiate(); AutoRequired<AutoPacketFactory> factory; ASSERT_EQ(nullptr, factory->CurrentPacket()) << "Current packet returned before any packets were issued"; auto packet = factory->NewPacket(); ASSERT_EQ(packet, factory->CurrentPacket()) << "Current packet was not reported correctly as being issued to the known current packet"; packet.reset(); ASSERT_EQ(nullptr, factory->CurrentPacket()) << "A current packet was reported after the current packet has expired"; } TEST_F(AutoPacketFactoryTest, IsRunningWhilePacketIssued) { AutoCurrentContext ctxt; ctxt->Initiate(); AutoRequired<AutoPacketFactory> factory; auto packet = factory->NewPacket(); ctxt->SignalShutdown(); ASSERT_TRUE(factory->IsRunning()) << "Factory should be considered to be running as long as packets are outstanding"; }
35.066667
154
0.733057
CaseyCarter
e570ddf78ef8d128fe95cdf07a55b9ba910cec2e
2,421
cpp
C++
CodeChef/KS2.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
1
2018-01-30T13:21:30.000Z
2018-01-30T13:21:30.000Z
CodeChef/KS2.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
null
null
null
CodeChef/KS2.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
1
2018-08-29T13:26:50.000Z
2018-08-29T13:26:50.000Z
/** * > Author : TISparta * > Date : 17-06-19 * > Tags : DP, Binary Search, Greedy * > Difficulty : 5 / 10 */ #pragma comment (linker,"/STACK:1024000000") #pragma GCC optimize(2) #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #pragma GCC optimization ("unroll-loops") #include <bits/stdc++.h> #define all(A) begin(A), end(A) #define rall(A) rbegin(A), rend(A) #define sz(A) int(A.size()) using namespace std; typedef unsigned long long ll; typedef pair <int, int> pii; const int D = 19; const int MAX_TC = 1e5 + 10; const ll lim = 10000000000000000009ULL; long long dp[10][D]; int vis[10][D]; int len; int s[D]; inline long long rec (int pos, int res, bool flag) { int rpos = D - len + pos; if (rpos == D) return res == 0; if (flag and vis[res][rpos]) return dp[res][rpos]; if (flag) vis[res][rpos] = true; long long ret = 0; if (flag) { for (int d = 0; d <= 9; d++) { ret += rec(pos + 1, (res + d >= 10) ? res + d - 10: res + d, flag); } } else { for (int d = 0; d <= s[pos]; d++) { ret += rec(pos + 1, (res + d >= 10) ? res + d - 10: res + d, d < s[pos]); } } if (flag) dp[res][rpos] = ret; return ret; } inline ll count (ll num) { len = 0; while (num) s[len++] = num % 10, num /= 10; int i = 0, j = len - 1; while (i < j) swap(s[i], s[j]), i++, j--; return rec(0, 0, 0) - 1; } ll tc; pair <ll, int> arr[MAX_TC]; ll ans[MAX_TC]; ll mid; inline ll get (ll pos, ll l = 1, ll r = lim) { if (r != lim) l = max(1ULL, r - 250); while (l != r) { mid = l + ((r - l) >> 1); if (count(mid) < pos) l = mid + 1; else r = mid; } return l; } inline void read (ll& num) { num = 0; register char ch = getchar_unlocked(); while (ch < '0' or ch > '9') ch = getchar_unlocked(); while ('0' <= ch and ch <= '9') { num = (num << 3) + (num << 1) + (ch - '0'); ch = getchar_unlocked(); } } int main () { read(tc); for (int t = 0; t < tc; t++) { read(arr[t].first); arr[t].second = t; } sort(arr, arr + tc); ll prev = get(arr[0].first); ans[arr[0].second] = prev; for (int i = 1; i < tc; i++) { ll dif = arr[i].first - arr[i - 1].first; ans[arr[i].second] = get(arr[i].first, prev + 89 * (dif / 9), 19 + prev + 90 * ((dif + 8) / 9)); prev = ans[arr[i].second]; } prev = ans[0]; for (int i = 0; i < tc; i++) { printf("%llu\n", ans[i]); } return (0); }
23.278846
100
0.527468
TISparta
e5763e9b19aa0e988bd1b926a2cab8712d67d804
773
cpp
C++
NonLinearSimultaneousEquationsTest.cpp
Hiroshi-Nakamura/NonLinearSimultaneousEquations
a5afac2f151a3ff83b75ba46bb1d3317038d271d
[ "MIT" ]
null
null
null
NonLinearSimultaneousEquationsTest.cpp
Hiroshi-Nakamura/NonLinearSimultaneousEquations
a5afac2f151a3ff83b75ba46bb1d3317038d271d
[ "MIT" ]
null
null
null
NonLinearSimultaneousEquationsTest.cpp
Hiroshi-Nakamura/NonLinearSimultaneousEquations
a5afac2f151a3ff83b75ba46bb1d3317038d271d
[ "MIT" ]
null
null
null
#include "NonLinearSimultaneousEquations.hpp" #include <iostream> int main(int argc, char** argv){ /// prepair initial x Eigen::VectorXd x_val(2); x_val << 0.0, 0.5; /// solve NonLinearSimultaneousEquations::solve( { [](const std::vector<AutomaticDifferentiation::FuncPtr<double>> x) { return x[0]*x[0]+x[1]*x[1]-1.0; /// on unit circle }, [](const std::vector<AutomaticDifferentiation::FuncPtr<double>> x) { return (x[0]-1.0)*(x[0]-1.0)+(x[1]-1.0)*(x[1]-1.0)-1.0; /// on unit circle centered at (1.0,1.0) } }, /// equations x_val /// variables ); std::cout << "soluition x:" << std::endl << x_val <<std::endl; }
28.62963
112
0.518758
Hiroshi-Nakamura
e57666ffca08079430ef3296c1d10d213a89bebe
993
cc
C++
paddle/infrt/dialect/opt.cc
L-Net-1992/Paddle
4d0ca02ba56760b456f3d4b42a538555b9b6c307
[ "Apache-2.0" ]
11
2016-08-29T07:43:26.000Z
2016-08-29T07:51:24.000Z
paddle/infrt/dialect/opt.cc
L-Net-1992/Paddle
4d0ca02ba56760b456f3d4b42a538555b9b6c307
[ "Apache-2.0" ]
null
null
null
paddle/infrt/dialect/opt.cc
L-Net-1992/Paddle
4d0ca02ba56760b456f3d4b42a538555b9b6c307
[ "Apache-2.0" ]
1
2021-12-09T08:59:17.000Z
2021-12-09T08:59:17.000Z
// Copyright (c) 2021 PaddlePaddle 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 <mlir/Support/MlirOptMain.h> #include <mlir/Transforms/Passes.h> #include "paddle/infrt/dialect/init_dialects.h" int main(int argc, char **argv) { mlir::DialectRegistry registry; infrt::registerCinnDialects(registry); mlir::registerCanonicalizerPass(); return mlir::failed( mlir::MlirOptMain(argc, argv, "infrt mlir pass driver", registry)); }
36.777778
75
0.745217
L-Net-1992
ec77219258d453a0236d273a3cfdf01a71641a5c
23,036
hpp
C++
third_party/kangaru/container.hpp
kirillPshenychnyi/kangaru_di_sample
5e79860852d167b4b63185263edfb62c628741cc
[ "MIT" ]
2
2019-07-12T09:08:46.000Z
2020-09-01T13:12:45.000Z
third_party/kangaru/container.hpp
kirillPshenychnyi/kangaru_di_sample
5e79860852d167b4b63185263edfb62c628741cc
[ "MIT" ]
null
null
null
third_party/kangaru/container.hpp
kirillPshenychnyi/kangaru_di_sample
5e79860852d167b4b63185263edfb62c628741cc
[ "MIT" ]
null
null
null
#ifndef KGR_KANGARU_INCLUDE_KANGARU_CONTAINER_HPP #define KGR_KANGARU_INCLUDE_KANGARU_CONTAINER_HPP #include "detail/default_source.hpp" #include "detail/traits.hpp" #include "detail/validity_check.hpp" #include "detail/utils.hpp" #include "detail/override_range_service.hpp" #include "detail/container_service.hpp" #include "detail/autocall_traits.hpp" #include "detail/single.hpp" #include "detail/exception.hpp" #include "detail/service_storage.hpp" #include "detail/injected.hpp" #include "detail/error.hpp" #include "predicate.hpp" #include <unordered_map> #include <memory> #include <type_traits> #include "detail/define.hpp" namespace kgr { /** * The kangaru container class. * * This class will construct services and share single instances for a given definition. * It is the class that parses and manage dependency graphs and calls autocall functions. */ struct container : private detail::default_source { private: template<typename Condition, typename T = int> using enable_if = detail::enable_if_t<Condition::value, T>; template<typename Condition, typename T = int> using disable_if = detail::enable_if_t<!Condition::value, T>; template<typename T> using contained_service_t = typename std::conditional< detail::is_single<T>::value, detail::single_insertion_result_t<T>, T>::type; using unpack = int[]; auto source() const noexcept -> default_source const& { return static_cast<default_source const&>(*this); } auto source() noexcept -> default_source& { return static_cast<default_source&>(*this); } template<typename T> static auto static_unwrap_single(detail::single_insertion_result_t<T> single_result) -> T& { return *static_cast<T*>(std::get<0>(single_result).service); } explicit container(default_source&& source) : default_source{std::move(source)} {} public: explicit container() = default; container(container const&) = delete; container& operator=(container const&) = delete; container(container&&) = default; container& operator=(container&&) = default; /* * This function construct and save in place a service definition with the provided arguments. * The service is only constructed if it is not found. * It is usually used to instanciate supplied services. * It returns if the service has been constructed. * This function require the service to be single. */ template<typename T, typename... Args, enable_if<detail::is_emplace_valid<T, Args...>> = 0> bool emplace(Args&&... args) { // TODO: We're doing two search in the map: One before constructing the service and one to insert. We should do only one. return contains<T>() ? false : (autocall(static_unwrap_single<T>(make_service_instance<T>(std::forward<Args>(args)...))), true); } /* * The following two overloads are called in a case where the service is invalid, * or is called when provided arguments don't match the constructor. * In GCC, a diagnostic is provided. */ template<typename T, enable_if<std::is_default_constructible<detail::service_error<T>>> = 0> bool emplace(detail::service_error<T> = {}) = delete; template<typename T, typename... Args> bool emplace(detail::service_error<T, detail::identity_t<Args>...>, Args&&...) = delete; /* * This function construct and save in place a service definition with the provided arguments. * The inserted instance of the service will be used for now on. * It does not delete the old instance if any. * This function require the service to be single. */ template<typename T, typename... Args, enable_if<detail::is_emplace_valid<T, Args...>> = 0> void replace(Args&&... args) { autocall(static_unwrap_single<T>(make_service_instance<T>(std::forward<Args>(args)...))); } /* * The following two overloads are called in a case where the service is invalid, * or is called when provided arguments don't match the constructor. * In GCC, a diagnostic is provided. */ template<typename T, enable_if<std::is_default_constructible<detail::service_error<T>>> = 0> void replace(detail::service_error<T> = {}) = delete; template<typename T, typename... Args> void replace(detail::service_error<T, detail::identity_t<Args>...>, Args&&...) = delete; /* * This function returns the service given by service definition T. * T must be a valid service and must be constructible with arguments passed as parameters * In case of a non-single service, it takes additional arguments to be sent to the T::construct function. * T must not be a polymorphic type. */ template<typename T, typename... Args, enable_if<detail::is_service_valid<T, Args...>> = 0> auto service(Args&&... args) -> service_type<T> { return definition<T>(std::forward<Args>(args)...).forward(); } /* * The following two overloads are called in a case where the service is invalid, * or is called when provided arguments don't match the constructor. * In GCC, a diagnostic is provided. */ template<typename T, typename... Args> auto service(detail::service_error<T, detail::identity_t<Args>...>, Args&&...) -> detail::sink = delete; template<typename T, enable_if<std::is_default_constructible<detail::service_error<T>>> = 0> auto service(detail::service_error<T> = {}) -> detail::sink = delete; /* * This function returns the result of the callable object of type U. * Args are additional arguments to be sent to the function after services arguments. * This function will deduce arguments from the function signature. */ template<typename Map = map<>, typename U, typename... Args, enable_if<detail::is_map<Map>> = 0, enable_if<detail::is_invoke_valid<Map, detail::decay_t<U>, Args...>> = 0> auto invoke(Map, U&& function, Args&&... args) -> detail::invoke_function_result_t<Map, detail::decay_t<U>, Args...> { return invoke_helper<Map>( detail::tuple_seq_minus<detail::invoke_function_arguments_t<Map, detail::decay_t<U>, Args...>, sizeof...(Args)>{}, std::forward<U>(function), std::forward<Args>(args)... ); } /* * This function returns the result of the callable object of type U. * Args are additional arguments to be sent to the function after services arguments. * This function will deduce arguments from the function signature. */ template<typename Map = map<>, typename U, typename... Args, enable_if<detail::is_map<Map>> = 0, enable_if<detail::is_invoke_valid<Map, detail::decay_t<U>, Args...>> = 0> auto invoke(U&& function, Args&&... args) -> detail::invoke_function_result_t<Map, detail::decay_t<U>, Args...> { return invoke_helper<Map>( detail::tuple_seq_minus<detail::invoke_function_arguments_t<Map, detail::decay_t<U>, Args...>, sizeof...(Args)>{}, std::forward<U>(function), std::forward<Args>(args)... ); } /* * This function returns the result of the callable object of type U. * It will call the function with the sevices listed in the `Services` parameter pack. */ template<typename First, typename... Services, typename U, typename... Args, enable_if<detail::conjunction< detail::is_service_valid<First>, detail::is_service_valid<Services>...>> = 0> auto invoke(U&& function, Args&&... args) -> detail::call_result_t<U, service_type<First>, service_type<Services>..., Args...> { return std::forward<U>(function)(service<First>(), service<Services>()..., std::forward<Args>(args)...); } /* * This oveload is called when the function mannot be invoked. * It will provide diagnostic on GCC. */ template<typename... Services> auto invoke(detail::not_invokable_error = {}, ...) -> detail::sink = delete; /* * This function clears this container. * Every single services are invalidated after calling this function. */ inline void clear() { source().clear(); } /* * This function fork the container into a new container. * The new container will have the copied state of the first container. * Construction of new services within the new container will not affect the original one. * The new container must exist within the lifetime of the original container. * * It takes a predicate type as template argument. * The default predicate is kgr::all. * * This version of the function takes a predicate that is default constructible. * It will call fork() with a predicate as parameter. */ template<typename Predicate = all, detail::enable_if_t<std::is_default_constructible<Predicate>::value, int> = 0> auto fork() const -> container { return fork(Predicate{}); } /* * This function fork the container into a new container. * The new container will have the copied state of the first container. * Construction of new services within the new container will not affect the original one. * The new container must exist within the lifetime of the original container. * * It takes a predicate as argument. */ template<typename Predicate> auto fork(Predicate predicate) const -> container { return container{source().fork(predicate)}; } /* * This function merges a container with another. * The receiving container will prefer it's own instances in a case of conflicts. */ inline void merge(container&& other) { source().merge(std::move(other.source())); } /* * This function merges a container with another. * The receiving container will prefer it's own instances in a case of conflicts. * * This function consumes the container `other` */ inline void merge(container& other) { merge(std::move(other)); } /** * This function will add all services form the container sent as parameter into this one. * Note that the lifetime of the container sent as parameter must be at least as long as this one. * If the container you rebase from won't live long enough, consider using the merge function. * * It takes a predicate type as template argument. * The default predicate is kgr::all. * * This version of the function takes a predicate that is default constructible. * It will call rebase() with a predicate as parameter. */ template<typename Predicate = all, detail::enable_if_t<std::is_default_constructible<Predicate>::value, int> = 0> void rebase(const container& other) { rebase(other, Predicate{}); } /** * This function will add all services form the container sent as parameter into this one. * Note that the lifetime of the container sent as parameter must be at least as long as this one. * If the container you rebase from won't live long enough, consider using the merge function. * * It takes a predicate type as argument to filter. */ template<typename Predicate> void rebase(const container& other, Predicate predicate) { source().rebase(other.source(), predicate); } /* * This function return true if the container contains the service T. Returns false otherwise. * T nust be a single service. */ template<typename T, detail::enable_if_t<detail::is_service<T>::value && detail::is_single<T>::value, int> = 0> bool contains() const { return source().contains<T>(); } private: /////////////////////// // new service // /////////////////////// /* * This function will create a new instance and save it. * It also returns a reference to the constructed service. */ template<typename T, typename... Args, enable_if<detail::is_single<T>> = 0, disable_if<detail::is_polymorphic<T>> = 0, disable_if<detail::is_supplied_service<T>> = 0, disable_if<detail::is_abstract_service<T>> = 0> auto configure_new_service(Args&&... args) -> T& { auto& service = static_unwrap_single<T>(make_service_instance<T>(std::forward<Args>(args)...)); autocall(service); return service; } /* * This function will create a new instance and save it. * It also returns a reference to the constructed service. */ template<typename T, typename... Args, enable_if<detail::is_single<T>> = 0, enable_if<detail::is_polymorphic<T>> = 0, disable_if<detail::is_supplied_service<T>> = 0, disable_if<detail::is_abstract_service<T>> = 0> auto configure_new_service(Args&&... args) -> detail::typed_service_storage<T> { auto storage = make_service_instance<T>(std::forward<Args>(args)...); auto& service = static_unwrap_single<T>(storage); autocall(service); return std::get<0>(storage); } /* * This function is a specialization of configure_new_service for abstract classes. * Since you cannot construct an abstract class, this function always throw. */ template<typename T, typename... Args, enable_if<detail::is_single<T>> = 0, enable_if<detail::is_abstract_service<T>> = 0, disable_if<detail::has_default<T>> = 0> auto configure_new_service(Args&&...) -> detail::typed_service_storage<T> { KGR_KANGARU_THROW(abstract_not_found{}); } /* * This function is a specialization of configure_new_service for abstract classes. * Since you cannot construct an abstract class, this function always throw. */ template<typename T, typename... Args, enable_if<detail::is_single<T>> = 0, enable_if<detail::is_supplied_service<T>> = 0, disable_if<detail::is_abstract_service<T>> = 0> auto configure_new_service(Args&&...) -> detail::conditional_t<detail::is_polymorphic<T>::value, detail::typed_service_storage<T>, T&> { KGR_KANGARU_THROW(supplied_not_found{}); } /* * This function is a specialization of configure_new_service for abstract classes. * Since that abstract service has a default service specified, we can contruct that one. */ template<typename T, typename... Args, enable_if<detail::is_single<T>> = 0, disable_if<detail::is_supplied_service<T>> = 0, enable_if<detail::is_abstract_service<T>> = 0, enable_if<detail::has_default<T>> = 0> auto configure_new_service(Args&&...) -> detail::typed_service_storage<T> { auto storage = make_service_instance<detail::default_type<T>>(); auto& service = *static_cast<detail::default_type<T>*>(std::get<0>(storage).service); using service_index = detail::meta_list_find<T, detail::parent_types<detail::default_type<T>>>; autocall(service); // The static assert is still required here, if other checks fails and allow // a call to this function where the default service don't overrides T, it would be UB. static_assert(detail::is_overriden_by<T, detail::default_type<T>>::value, "The default service type of an abstract service must override that abstract service." ); return std::get<service_index::value + 1>(storage); } /////////////////////// // make instance // /////////////////////// /* * This function creates an instance of a service. * It forward the work to make_service_instance_helper with an integer sequence. */ template<typename T, typename... Args> auto make_service_instance(Args&&... args) -> contained_service_t<T> { return make_service_instance_helper<T>( detail::construct_result_seq<T, Args...>{}, std::forward<Args>(args)... ); } /* * This function is the helper for make_service_instance. * It construct the service using the values returned by construct. * It forward it's work to make_contained_service. */ template<typename T, typename... Args, std::size_t... S> auto make_service_instance_helper(detail::seq<S...>, Args&&... args) -> contained_service_t<T> { auto construct_args = invoke_definition<detail::construct_function<T, Args...>>(std::forward<Args>(args)...); // This line is used to shut unused-variable warning, since S can be empty. static_cast<void>(construct_args); return make_contained_service<T>( detail::parent_types<T>{}, std::forward<detail::tuple_element_t<S, decltype(construct_args)>>(std::get<S>(construct_args))... ); } /* * This function create a service with the received arguments. * It creating it in the right type for the container to contain it in it's container. */ template<typename T, typename... Overrides, typename... Args, enable_if<detail::is_single<T>> = 0, enable_if<detail::is_someway_constructible<T, in_place_t, Args...>> = 0> auto make_contained_service(detail::meta_list<Overrides...>, Args&&... args) -> detail::single_insertion_result_t<T> { return source().emplace<T, Overrides...>(detail::in_place, std::forward<Args>(args)...); } /* * This function create a service with the received arguments. * It creating it in the right type for the container return it and inject it without overhead. */ template<typename T, typename... Args, disable_if<detail::is_single<T>> = 0, enable_if<detail::is_someway_constructible<T, in_place_t, Args...>> = 0> auto make_contained_service(detail::meta_list<>, Args&&... args) -> T { return T{detail::in_place, std::forward<Args>(args)...}; } /* * This function create a service with the received arguments. * It creating it in the right type for the container to contain it in it's container. * This version of the function is called when the service definition has no valid constructor. * It will try to call an emplace function that construct the service in a lazy way. */ template<typename T, typename... Overrides, typename... Args, enable_if<detail::is_single<T>> = 0, disable_if<detail::is_someway_constructible<T, in_place_t, Args...>> = 0, enable_if<detail::is_emplaceable<T, Args...>> = 0> auto make_contained_service(detail::meta_list<Overrides...>, Args&&... args) -> detail::single_insertion_result_t<T> { auto storage = source().emplace<T, Overrides...>(); auto& service = static_unwrap_single<T>(storage); service.emplace(std::forward<Args>(args)...); return storage; } /* * This function create a service with the received arguments. * It creating it in the right type for the container return it and inject it without overhead. * This version of the function is called when the service definition has no valid constructor. * It will try to call an emplace function that construct the service in a lazy way. */ template<typename T, typename... Args, disable_if<detail::is_single<T>> = 0, disable_if<detail::is_someway_constructible<T, in_place_t, Args...>> = 0, enable_if<detail::is_emplaceable<T, Args...>> = 0> auto make_contained_service(detail::meta_list<>, Args&&... args) -> T { T service; service.emplace(std::forward<Args>(args)...); return service; } /////////////////////// // service // /////////////////////// /* * This function call service using the service map. * This function is called when the service map `Map` is valid for a given `T` */ template<typename Map, typename T, enable_if<detail::is_complete_map<Map, T>> = 0, enable_if<detail::is_service_valid<detail::detected_t<mapped_service_t, T, Map>>> = 0> auto mapped_service() -> service_type<mapped_service_t<T, Map>> { return service<mapped_service_t<T, Map>>(); } /////////////////////// // definition // /////////////////////// /* * This function returns a service definition. * This version of this function create the service each time it is called. */ template<typename T, typename... Args, disable_if<detail::is_single<T>> = 0, disable_if<detail::is_container_service<T>> = 0, disable_if<detail::is_override_range_service<T>> = 0> auto definition(Args&&... args) -> detail::injected_wrapper<T> { auto service = make_service_instance<T>(std::forward<Args>(args)...); autocall(service); return detail::injected_wrapper<T>{std::move(service)}; } /* * This function returns a service definition. * This version of this function is specific to a container service. */ template<typename T, enable_if<detail::is_container_service<T>> = 0> auto definition() -> detail::injected_wrapper<T> { return detail::injected<container_service>{container_service{*this}}; } /* * This function returns a service definition. * This version of this function is specific to a container service. */ template<typename T, enable_if<detail::is_override_range_service<T>> = 0> auto definition() -> detail::injected_wrapper<T> { return detail::injected<T>{T{source().overrides<detail::override_range_service_type_t<T>>()}}; } /* * This function returns a service definition. * This version of this function create the service if it was not created before. * It is called when getting a service definition for a single, non virtual service */ template<typename T, enable_if<detail::is_single<T>> = 0> auto definition() -> detail::injected_wrapper<T> { return source().find<T>( [](detail::injected_wrapper<T>&& storage) { return storage; }, [this]{ return detail::injected_wrapper<T>{configure_new_service<T>()}; } ); } /////////////////////// // invoke // /////////////////////// /* * This function is an helper for the public invoke function. * It unpacks arguments of the function with an integer sequence. */ template<typename Map, typename U, typename... Args, std::size_t... S> auto invoke_helper(detail::seq<S...>, U&& function, Args&&... args) -> detail::invoke_function_result_t<Map, detail::decay_t<U>, Args...> { return std::forward<U>(function)( mapped_service<Map, detail::invoke_function_argument_t<S, Map, detail::decay_t<U>, Args...>>()..., std::forward<Args>(args)... ); } /* * This function is the same as invoke but it sends service definitions instead of the service itself. * It is called with some autocall function and the make_service_instance function. */ template<typename U, typename... Args, typename F = typename U::value_type> auto invoke_definition(Args&&... args) -> detail::function_result_t<F> { return invoke_definition_helper<U>( detail::tuple_seq_minus<detail::function_arguments_t<F>, sizeof...(Args)>{}, std::forward<Args>(args)... ); } /* * This function is an helper of the invoke_definition function. * It unpacks arguments of the function U with an integer sequence. */ template<typename U, typename... Args, std::size_t... S, typename F = typename U::value_type> auto invoke_definition_helper(detail::seq<S...>, Args&&... args) -> detail::function_result_t<F> { return U::value(definition<detail::injected_argument_t<S, F>>()..., std::forward<Args>(args)...); } /////////////////////// // autocall // /////////////////////// /* * This function starts the iteration (autocall_helper). */ template<typename T, enable_if<detail::has_autocall<T>> = 0> void autocall(T& service) { autocall(detail::tuple_seq<typename T::autocall_functions>{}, service); } /* * This function is the iteration for autocall. */ template<typename T, std::size_t... S, enable_if<detail::has_autocall<T>> = 0> void autocall(detail::seq<S...>, T& service) { (void)unpack{(void( invoke_definition<detail::autocall_nth_function<T, S>>(service) ), 0)..., 0}; } /* * This function is called when there is no autocall to do. */ template<typename T, disable_if<detail::has_autocall<T>> = 0> void autocall(T&) {} }; } // namespace kgr #include "detail/undef.hpp" #endif // KGR_KANGARU_INCLUDE_KANGARU_CONTAINER_HPP
38.076033
130
0.704332
kirillPshenychnyi
ec79d74f4860d465c34f6f3276879ca28a6062e7
1,791
cc
C++
horace/terminate_flag.cc
gdshaw/libholmes-horace
6a7d8365f01e165853fc967ce8eae45b82102fdf
[ "BSD-3-Clause" ]
null
null
null
horace/terminate_flag.cc
gdshaw/libholmes-horace
6a7d8365f01e165853fc967ce8eae45b82102fdf
[ "BSD-3-Clause" ]
null
null
null
horace/terminate_flag.cc
gdshaw/libholmes-horace
6a7d8365f01e165853fc967ce8eae45b82102fdf
[ "BSD-3-Clause" ]
null
null
null
// This file is part of libholmes. // Copyright 2019 Graham Shaw // Redistribution and modification are permitted within the terms of the // BSD-3-Clause licence as defined by v3.4 of the SPDX Licence List. #include <unistd.h> #include <fcntl.h> #include <poll.h> #include "horace/libc_error.h" #include "horace/terminate_flag.h" namespace horace { terminate_flag::terminate_flag(): _terminating(false) { if (pipe(_pipefd) == -1) { throw libc_error(); } _nonblock(_pipefd[0]); _nonblock(_pipefd[1]); } void terminate_flag::_nonblock(int fd) { int flags = ::fcntl(fd, F_GETFL, 0); if (flags == -1) { throw libc_error(); } flags |= O_NONBLOCK; if (fcntl(fd, F_SETFL, flags) == -1) { throw libc_error(); } } terminate_flag& terminate_flag::operator=(bool terminating) { bool changed = terminating != _terminating; _terminating = terminating; if (changed) { if (terminating) { size_t count = write(_pipefd[1], "", 1); } else { char buffer; while (read(_pipefd[0], &buffer, sizeof(buffer)) > 0) {} } } return *this; } int terminate_flag::poll(int fd, int events, int timeout) const { struct pollfd fds[2] = {{0}}; fds[0].fd = _pipefd[0]; fds[0].events = POLLIN; fds[1].fd = fd; fds[1].events = events; while (::poll(fds, 2, timeout) == -1) { if (errno != EINTR) { throw libc_error(); } } if (fds[0].revents & POLLIN) { throw terminate_exception(); } return fds[1].revents; } void terminate_flag::millisleep(int timeout) const { struct pollfd fds[1] = {{0}}; fds[0].fd = _pipefd[0]; fds[0].events = POLLIN; if (::poll(fds, 1, timeout) == -1) { if (errno != EINTR) { throw libc_error(); } } if (fds[0].revents & POLLIN) { throw terminate_exception(); } } terminate_flag terminating; } /* namespace horace */
20.352273
72
0.650475
gdshaw
ec7fbacf407c35c6de50b087c96f860e417c388d
4,486
cxx
C++
applications/rtkprojectgeometricphantom/rtkprojectgeometricphantom.cxx
ferdymercury/RTK
0d524ea7904519f37b5155af35eb41641e231578
[ "Apache-2.0", "BSD-3-Clause" ]
167
2015-02-26T08:39:33.000Z
2022-03-31T04:40:35.000Z
applications/rtkprojectgeometricphantom/rtkprojectgeometricphantom.cxx
ferdymercury/RTK
0d524ea7904519f37b5155af35eb41641e231578
[ "Apache-2.0", "BSD-3-Clause" ]
270
2015-02-26T15:34:32.000Z
2022-03-22T09:49:24.000Z
applications/rtkprojectgeometricphantom/rtkprojectgeometricphantom.cxx
ferdymercury/RTK
0d524ea7904519f37b5155af35eb41641e231578
[ "Apache-2.0", "BSD-3-Clause" ]
117
2015-05-01T14:56:49.000Z
2022-03-11T03:18:26.000Z
/*========================================================================= * * Copyright RTK Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "rtkprojectgeometricphantom_ggo.h" #include "rtkGgoFunctions.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include "rtkRayEllipsoidIntersectionImageFilter.h" #include "rtkProjectGeometricPhantomImageFilter.h" #include <itkImageFileWriter.h> int main(int argc, char * argv[]) { GGO(rtkprojectgeometricphantom, args_info); using OutputPixelType = float; constexpr unsigned int Dimension = 3; using OutputImageType = itk::Image<OutputPixelType, Dimension>; // Geometry if (args_info.verbose_flag) std::cout << "Reading geometry information from " << args_info.geometry_arg << "..." << std::endl; rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader; geometryReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New(); geometryReader->SetFilename(args_info.geometry_arg); TRY_AND_EXIT_ON_ITK_EXCEPTION(geometryReader->GenerateOutputInformation()) // Create a stack of empty projection images using ConstantImageSourceType = rtk::ConstantImageSource<OutputImageType>; ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New(); rtk::SetConstantImageSourceFromGgo<ConstantImageSourceType, args_info_rtkprojectgeometricphantom>(constantImageSource, args_info); // Adjust size according to geometry ConstantImageSourceType::SizeType sizeOutput; sizeOutput[0] = constantImageSource->GetSize()[0]; sizeOutput[1] = constantImageSource->GetSize()[1]; sizeOutput[2] = geometryReader->GetOutputObject()->GetGantryAngles().size(); constantImageSource->SetSize(sizeOutput); using PPCType = rtk::ProjectGeometricPhantomImageFilter<OutputImageType, OutputImageType>; // Offset, scale, rotation PPCType::VectorType offset(0.); if (args_info.offset_given) { if (args_info.offset_given > 3) { std::cerr << "--offset needs up to 3 values" << std::endl; exit(EXIT_FAILURE); } offset[0] = args_info.offset_arg[0]; offset[1] = args_info.offset_arg[1]; offset[2] = args_info.offset_arg[2]; } PPCType::VectorType scale; scale.Fill(args_info.phantomscale_arg[0]); if (args_info.phantomscale_given) { if (args_info.phantomscale_given > 3) { std::cerr << "--phantomscale needs up to 3 values" << std::endl; exit(EXIT_FAILURE); } for (unsigned int i = 0; i < std::min(args_info.phantomscale_given, Dimension); i++) scale[i] = args_info.phantomscale_arg[i]; } PPCType::RotationMatrixType rot; rot.SetIdentity(); if (args_info.rotation_given) { if (args_info.rotation_given != 9) { std::cerr << "--phantomscale needs exactly 9 values" << std::endl; exit(EXIT_FAILURE); } for (unsigned int i = 0; i < Dimension; i++) for (unsigned int j = 0; j < Dimension; j++) rot[i][j] = args_info.rotation_arg[i * 3 + j]; } PPCType::Pointer ppc = PPCType::New(); ppc->SetInput(constantImageSource->GetOutput()); ppc->SetGeometry(geometryReader->GetOutputObject()); ppc->SetPhantomScale(scale); ppc->SetOriginOffset(offset); ppc->SetRotationMatrix(rot); ppc->SetConfigFile(args_info.phantomfile_arg); ppc->SetIsForbildConfigFile(args_info.forbild_flag); TRY_AND_EXIT_ON_ITK_EXCEPTION(ppc->Update()) // Write using WriterType = itk::ImageFileWriter<OutputImageType>; WriterType::Pointer writer = WriterType::New(); writer->SetFileName(args_info.output_arg); writer->SetInput(ppc->GetOutput()); if (args_info.verbose_flag) std::cout << "Projecting and writing... " << std::flush; TRY_AND_EXIT_ON_ITK_EXCEPTION(writer->Update()) return EXIT_SUCCESS; }
36.471545
120
0.689033
ferdymercury
ec80dcf16e1754aeda5189efa89e0e405fe61cc5
766
cpp
C++
DFG/DFGUICmd/DFGUICmd_SetNodeComment.cpp
yoann01/FabricUI
d4d24f25245b8ccd2d206aded2b6c5f2aca09155
[ "BSD-3-Clause" ]
null
null
null
DFG/DFGUICmd/DFGUICmd_SetNodeComment.cpp
yoann01/FabricUI
d4d24f25245b8ccd2d206aded2b6c5f2aca09155
[ "BSD-3-Clause" ]
null
null
null
DFG/DFGUICmd/DFGUICmd_SetNodeComment.cpp
yoann01/FabricUI
d4d24f25245b8ccd2d206aded2b6c5f2aca09155
[ "BSD-3-Clause" ]
null
null
null
// // Copyright (c) 2010-2017 Fabric Software Inc. All rights reserved. // #include <FabricUI/DFG/DFGUICmd/DFGUICmd_SetNodeComment.h> FABRIC_UI_DFG_NAMESPACE_BEGIN void DFGUICmd_SetNodeComment::appendDesc( QString &desc ) { desc += "Change comment of "; appendDesc_NodeName( m_nodeName, desc ); } void DFGUICmd_SetNodeComment::invoke( unsigned &coreUndoCount ) { invoke( m_nodeName.toUtf8().constData(), m_comment.toUtf8().constData(), coreUndoCount ); } void DFGUICmd_SetNodeComment::invoke( FTL::CStrRef nodeName, FTL::CStrRef comment, unsigned &coreUndoCount ) { getExec().setItemMetadata( nodeName.c_str(), "uiComment", comment.c_str(), true, true ); ++coreUndoCount; } FABRIC_UI_DFG_NAMESPACE_END
18.682927
68
0.712794
yoann01
ec8708c1cf6f3e2c019d92a9f0d1045135cdc18a
1,028
cpp
C++
core/src/ResourceManagement/Loaders/TextureLoader.cpp
tokongs/yage
14c9411d8efce08b89c0deb134b5c3023a32c577
[ "MIT" ]
null
null
null
core/src/ResourceManagement/Loaders/TextureLoader.cpp
tokongs/yage
14c9411d8efce08b89c0deb134b5c3023a32c577
[ "MIT" ]
null
null
null
core/src/ResourceManagement/Loaders/TextureLoader.cpp
tokongs/yage
14c9411d8efce08b89c0deb134b5c3023a32c577
[ "MIT" ]
null
null
null
#include "TextureLoader.h" #define STB_IMAGE_IMPLEMENTATION #include "stb_image/stb_image.h" namespace yage { TextureLoader::TextureLoader() { } TextureLoader::~TextureLoader() { } Resource *TextureLoader::load(std::string file_path) { std::string fileContent = mFileReader.readAsString(file_path); YAGE_INFO("Loading Material from {}", file_path); pugi::xml_document doc; pugi::xml_parse_result r = doc.load_string(fileContent.c_str()); if(!r){ YAGE_WARN("Failed to parse xml when loading material from {}", file_path); return nullptr; } pugi::xml_node root = doc.first_child(); std::string path = root.attribute("path").value(); int width, height, numChannels; unsigned char *data = stbi_load(path.c_str(), &width, &height, &numChannels, 0); Texture *result = new Texture(data, width, height, numChannels); stbi_image_free(data); return result; } } // namespace yage
30.235294
88
0.639105
tokongs
ec87d4f8b5d715af6485e69657a44d0a709fde61
588
cc
C++
chrome/browser/ui/athena/extensions/extension_install_ui_factory_athena.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-11-28T10:46:52.000Z
2019-11-28T10:46:52.000Z
chrome/browser/ui/athena/extensions/extension_install_ui_factory_athena.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/athena/extensions/extension_install_ui_factory_athena.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-03-27T11:15:39.000Z
2016-08-17T14:19:56.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/extensions/extension_install_ui_factory.h" #include "athena/extensions/public/extensions_delegate.h" #include "extensions/browser/install/extension_install_ui.h" namespace extensions { scoped_ptr<ExtensionInstallUI> CreateExtensionInstallUI( content::BrowserContext* context) { return athena::ExtensionsDelegate::Get(context)->CreateExtensionInstallUI(); } } // namespace extensions
32.666667
78
0.797619
kjthegod
ec888971842a8d55071566dfa0628fc4ed150deb
4,741
cpp
C++
refData/SRC/recog/recopt.cpp
xrick/Crafting_ASR_From_Scratch
a09820676e062db4b99b6ebabe5dd3ae4bb31a71
[ "MIT" ]
null
null
null
refData/SRC/recog/recopt.cpp
xrick/Crafting_ASR_From_Scratch
a09820676e062db4b99b6ebabe5dd3ae4bb31a71
[ "MIT" ]
null
null
null
refData/SRC/recog/recopt.cpp
xrick/Crafting_ASR_From_Scratch
a09820676e062db4b99b6ebabe5dd3ae4bb31a71
[ "MIT" ]
null
null
null
// ********************************************************************* // * This file is part of RES 6.0. * // * RES 6.0 is an original software distributed within the book * // * * // * |-----------------------------------------------------| * // * | "Speech Recognition: Theory and C++ Implementation" | * // * | John Wiley & Sons, Ltd | * // * | by Claudio Becchetti and Lucio Prina Ricotti | * // * |-----------------------------------------------------| * // * * // * See copyright.txt file for further info. on copyright * // ********************************************************************* // _____________________________________________________________________ // |-------------------------------------------------------------------| // | | // | FILE: recopt.cpp | // | FUNCTIONALITY: | // | PROGRAM: | // | COMMENTS: | // | CONTRIBUTIONS: Domenico | // | ACTUAL REVISION: 6.0 | // | DATA ACTUAL REVISION: 19/11/97 | // | FIRST VERSION: 2.0 | // | DATA FIRST VERSION: 20/2/96 | // | | // |-------------------------------------------------------------------| // _____________________________________________________________________ #define RECOPT_VERSION "V.6.0 of 19/11/98 " ## __FILE__ " c." ## __DATE__ #include "recopt.h" void RecogOptions::Config_File_Name(String & conf_fname)const { conf_fname = config_file_name; return ; }; void RecogOptions::Set_Options(const String & file_name) { ConfigFile config; String string_option; //open config file config_file_name=file_name; config.Open_File(config_file_name); //store algorithm type config.Get_String_Opt("Recognition", "AlgorithmType", string_option); if (string_option=="windowsearch") { algorithm=WindowSearch; window_width=config.Get_Unsigned_Opt("Recognition", "WindowWidth"); } else //if (string_option=="BeamSearch") { algorithm=BeamSearch; beam_initial=config.Get_Real_Opt("Recognition", "BeamCoefficientInitial"); beam_internal=config.Get_Real_Opt("Recognition", "BeamCoefficientInternal"); } //maximum volume of hypothesis tree tree_volume=config.Get_Unsigned_Opt("Recognition", "TreeVolume"); //names of output files config.Get_String_Opt("Recognition", "FileOfSolutions", file_of_solutions); config.Get_String_Opt("Recognition", "FileOfResults", file_of_results); //file of acoustic model config.Get_String_Opt("Recognition", "FileOfAcousticModels", file_of_acoustic_models); //static grammar level config.Get_String_Opt("Recognition", "StaticGrammar", string_option); if (string_option=="phongrammar") grammar=PhonGrammar; else //if (string_options=="WordGrammar") grammar=WordGrammar; penalty=config.Get_Real_Opt ("Recognition", "GrammarProbPenalty"); penalty_sil=config.Get_Real_Opt ("Recognition", "SilenceProbPenalty"); bigr_th=config.Get_Real_Opt ("Recognition", "BigrTh"); skip_th=config.Get_Real_Opt ("Recognition", "SkipTh"); desc_gr_const=config.Get_Real_Opt ("Recognition", "DescGrConst"); //grammar type config.Get_String_Opt("Recognition", "GrammarType", string_option); if (string_option=="nogrammar") grammar_type=NoGrammar; else // if (string_option=="Bigram") grammar_type=BiGram; //file of phonemes grammar config.Get_String_Opt("Recognition", "FileOfBigramPhonemeGrammar", file_of_phonemes_bigram); //file of word bigram config.Get_String_Opt("Recognition", "FileOfBigramWordGrammar", file_of_bigram); //file of vocabulary config.Get_String_Opt("Recognition", "FileOfVocabulary", file_of_vocabulary); config.Get_String_Opt("Recognition", "WordClass", string_option); if (string_option=="noclassif") word_class=NoClassif; else //if(string_option=="YesClassif") { word_class=YesClassif; config.Get_String_Opt("Recognition", "FileOfClasses", file_of_classes); config.Get_String_Opt("Recognition", "FileOfClassGrammar", file_of_bigram_classes); } return; }
40.87069
96
0.542502
xrick
ec8b689e183b75aa918208ebe7afed49133b9b71
1,412
cpp
C++
src/copper_pymodules/HOU/HOU_Geometry.cpp
cinepost/CopperFX
1729d1fb75b4d42f3560983fbde174df30371b97
[ "Unlicense" ]
2
2019-06-25T23:36:55.000Z
2022-03-07T04:15:50.000Z
src/copper_pymodules/HOU/HOU_Geometry.cpp
cinepost/CopperFX
1729d1fb75b4d42f3560983fbde174df30371b97
[ "Unlicense" ]
null
null
null
src/copper_pymodules/HOU/HOU_Geometry.cpp
cinepost/CopperFX
1729d1fb75b4d42f3560983fbde174df30371b97
[ "Unlicense" ]
1
2019-08-22T08:23:37.000Z
2019-08-22T08:23:37.000Z
//#include "copper_pymodule/COM/HOU_Module.h" #include "copper_pymodules/HOU/HOU_Point.h" #include "copper_pymodules/HOU/HOU_Geometry.h" using namespace copper; namespace hou_module { HOU_Geometry::HOU_Geometry() { this->_geo = new GeometryOpData(); } HOU_Geometry::HOU_Geometry(GeometryOpData *geo) { this->_geo = geo; } PyObject* HOU_Geometry::points() { std::vector<Point3d> *points = _geo->points(); boost::python::tuple* l = new boost::python::tuple(); std::vector<Point3d>::iterator it; int i = 0; for(it = points->begin(); it != points->end(); it++, i++ ) { (*l) += boost::python::make_tuple(boost::shared_ptr<HOU_Point>(new HOU_Point(i, &*it, this))); } return l->ptr(); } HOU_Point *HOU_Geometry::createPoint() { return new HOU_Point(_geo->points()->size(), _geo->createPoint(), this); } void export_Geometry() { boost::python::class_<HOU_Geometry, boost::noncopyable>("Geometry") //.def("freeze", &HOU_Geometry::freeze, boost::python::return_value_policy<boost::python::manage_new_object>()) .def("points", &HOU_Geometry::points) .def("createPoint", &HOU_Geometry::createPoint, boost::python::return_value_policy<boost::python::manage_new_object>()) ; //boost::python::to_python_converter<std::vector<Point*, std::allocator<Point*> >, vector_to_python_tuple<Point*> >(); //boost::python::to_python_converter<HOU_Point *, HOU_object_ptr_to_python<HOU_Point>>(); } }
30.695652
121
0.71034
cinepost
ec8cc8a89b0290455cf69cc837753cd28cfc6fb7
3,152
hxx
C++
src/interfaces/common/caller/ad3_caller.hxx
burcin/opengm
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
[ "MIT" ]
318
2015-01-07T15:22:02.000Z
2022-01-22T10:10:29.000Z
src/interfaces/common/caller/ad3_caller.hxx
burcin/opengm
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
[ "MIT" ]
89
2015-03-24T14:33:01.000Z
2020-07-10T13:59:13.000Z
src/interfaces/common/caller/ad3_caller.hxx
burcin/opengm
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
[ "MIT" ]
119
2015-01-13T08:35:03.000Z
2022-03-01T01:49:08.000Z
#ifndef AD3_CALLER_HXX_ #define AD3_CALLER_HXX_ #include <opengm/opengm.hxx> #include <opengm/inference/external/ad3.hxx> #include "inference_caller_base.hxx" #include "../argument/argument.hxx" namespace opengm { namespace interface { template <class IO, class GM, class ACC> class Ad3Caller : public InferenceCallerBase<IO, GM, ACC, Ad3Caller<IO, GM, ACC> > { public: typedef external::AD3Inf<GM, ACC> Solver; typedef InferenceCallerBase<IO, GM, ACC, Ad3Caller<IO, GM, ACC> > BaseClass; typedef typename Solver::VerboseVisitorType VerboseVisitorType; typedef typename Solver::EmptyVisitorType EmptyVisitorType; typedef typename Solver::TimingVisitorType TimingVisitorType; const static std::string name_; Ad3Caller(IO& ioIn); virtual ~Ad3Caller(); protected: using BaseClass::addArgument; using BaseClass::io_; using BaseClass::infer; typedef typename BaseClass::OutputBase OutputBase; typename Solver::Parameter param_; std::string selectedSolverType_; virtual void runImpl(GM& model, OutputBase& output, const bool verbose); size_t steps_; }; template <class IO, class GM, class ACC> inline Ad3Caller<IO, GM, ACC>::Ad3Caller(IO& ioIn) : BaseClass(name_, "detailed description of Ad3Caller caller...", ioIn) { addArgument(DoubleArgument<>(param_.eta_, "", "eta", "eta.", double(param_.eta_))); addArgument(BoolArgument(param_.adaptEta_, "", "adaptEta", "adaptEta")); addArgument(Size_TArgument<>(steps_, "", "steps", "maximum steps", size_t(param_.steps_))); addArgument(DoubleArgument<>(param_.residualThreshold_, "", "residualThreshold", "residualThreshold", double(param_.residualThreshold_))); addArgument(IntArgument<>(param_.verbosity_, "", "verbosity", "verbosity", int(param_.verbosity_))); std::vector<std::string> possibleSolverType; possibleSolverType.push_back(std::string("AD3_LP")); possibleSolverType.push_back(std::string("AD3_ILP")); possibleSolverType.push_back(std::string("PSDD_LP")); addArgument(StringArgument<>(selectedSolverType_, "", "solverType", "selects the update rule", possibleSolverType.at(0), possibleSolverType)); } template <class IO, class GM, class ACC> inline Ad3Caller<IO, GM, ACC>::~Ad3Caller() { } template <class IO, class GM, class ACC> inline void Ad3Caller<IO, GM, ACC>::runImpl(GM& model, OutputBase& output, const bool verbose) { std::cout << "running Ad3Caller caller" << std::endl; if(selectedSolverType_ == std::string("AD3_LP")) { param_.solverType_= Solver::AD3_LP; } else if(selectedSolverType_ == std::string("AD3_ILP")) { param_.solverType_= Solver::AD3_ILP; } else if(selectedSolverType_ == std::string("PSDD_LP")) { param_.solverType_= Solver::PSDD_LP; } else { throw RuntimeError("Unknown solverType for ad3"); } param_.steps_=steps_; this-> template infer<Solver, TimingVisitorType, typename Solver::Parameter>(model, output, verbose, param_); } template <class IO, class GM, class ACC> const std::string Ad3Caller<IO, GM, ACC>::name_ = "AD3"; } // namespace interface } // namespace opengm #endif /* AD3_CALLER_HXX_ */
32.494845
145
0.722716
burcin
ec8ed91b4d4f555be82915746445d8ac0ad529af
1,566
cpp
C++
Source/Motor2D/Dissolve.cpp
Needlesslord/PaintWars_by_BrainDeadStudios
578985b1a41ab9f0b8c5dd087ba3bc3d3ffd2edf
[ "MIT" ]
2
2020-03-06T11:32:40.000Z
2020-03-20T12:17:30.000Z
Source/Motor2D/Dissolve.cpp
Needlesslord/Heathen_Games
578985b1a41ab9f0b8c5dd087ba3bc3d3ffd2edf
[ "MIT" ]
2
2020-03-03T09:56:57.000Z
2020-05-02T15:50:45.000Z
Source/Motor2D/Dissolve.cpp
Needlesslord/Heathen_Games
578985b1a41ab9f0b8c5dd087ba3bc3d3ffd2edf
[ "MIT" ]
1
2020-03-17T18:50:53.000Z
2020-03-17T18:50:53.000Z
#include "Dissolve.h" #include "TransitionManager.h" Dissolve::Dissolve(SCENES next_scene, float step_duration) : Transition(next_scene, step_duration) , dissolving_alpha(0.0f) , condensing_alpha(0.0f) { InitDissolve(); } Dissolve::~Dissolve() { } void Dissolve::StepTransition() { switch (step) { case TRANSITION_STEP::ENTERING: Entering(); break; case TRANSITION_STEP::CHANGING: Changing(); break; case TRANSITION_STEP::EXITING: Exiting(); break; } ApplyDissolve(); } void Dissolve::Entering() { current_cutoff += GetCutoffRate(step_duration); if (current_cutoff <= MAX_CUTOFF) { current_cutoff = MAX_CUTOFF; step = TRANSITION_STEP::CHANGING; } } void Dissolve::Changing() { App->scenes->UnloadScene(App->scenes->current_scene); step = TRANSITION_STEP::EXITING; } void Dissolve::Exiting() { step = TRANSITION_STEP::NONE; App->transition_manager->DeleteActiveTransition(); } void Dissolve::ApplyDissolve() { dissolving_alpha += Lerp(MAX_ALPHA, MIN_ALPHA, dissolve_rate); // Decreasing alpha value. condensing_alpha += Lerp(MIN_ALPHA, MAX_ALPHA, dissolve_rate); // Increasing alpha value. SDL_SetTextureAlphaMod(App->scenes->current_scene->scene_texture, dissolving_alpha); SDL_SetTextureAlphaMod(App->scenes->next_scene->scene_texture, condensing_alpha); } void Dissolve::InitDissolve() { dissolve_rate = GetCutoffRate(step_duration); App->scenes->LoadScene(next_scene); SDL_SetTextureAlphaMod(App->scenes->next_scene->tileset_texture, 0.0f); step = TRANSITION_STEP::ENTERING; }
18.209302
98
0.736909
Needlesslord
ec8f41342830a6f2056500c0819252c425271da8
5,552
cpp
C++
qtlua/packages/qttorch/qttorch.cpp
elq/torch5
5965bd6410f8ca7e87c6bc9531aaf46e10ed281e
[ "BSD-3-Clause" ]
1
2016-05-09T05:34:15.000Z
2016-05-09T05:34:15.000Z
qtlua/packages/qttorch/qttorch.cpp
elq/torch5
5965bd6410f8ca7e87c6bc9531aaf46e10ed281e
[ "BSD-3-Clause" ]
null
null
null
qtlua/packages/qttorch/qttorch.cpp
elq/torch5
5965bd6410f8ca7e87c6bc9531aaf46e10ed281e
[ "BSD-3-Clause" ]
null
null
null
// -*- C++ -*- #include "qttorch.h" #include <QColor> #include <QDebug> #include <QImage> #include <QMetaType> #include "TH.h" #include "luaT.h" static const void* torch_Tensor_id; static int qttorch_qimage_fromtensor(lua_State *L) { THTensor *Tsrc = (THTensor*)luaT_checkudata(L,1,torch_Tensor_id); long depth = 1; if ( Tsrc->nDimension == 3) depth = Tsrc->size[2]; else if (Tsrc->nDimension != 2) luaL_error(L, "tensor must have 2 or 3 dimensions"); if (depth != 1 && depth != 3 && depth != 4) luaL_error(L, "tensor third dimension must be 1, 3, or 4."); // create image if (Tsrc->size[0] >= INT_MAX || Tsrc->size[1] >= INT_MAX) luaL_error(L, "image is too large"); int width = (int)(Tsrc->size[0]); int height = (int)(Tsrc->size[1]); QImage image(width, height, QImage::Format_ARGB32_Premultiplied); // fill image long s0 = Tsrc->stride[0]; long s1 = Tsrc->stride[1]; long s2 = (depth > 1) ? Tsrc->stride[2] : 0; double *tdata = THTensor_dataPtr(Tsrc); for(int j=0; j<height; j++) { QRgb *ip = (QRgb*)image.scanLine(j); double *tp = tdata + s1 * j; if (depth == 1) { for (int i=0; i<width; i++) { int g = (int)(tp[0] * 255.0) & 0xff; tp += s0; ip[i] = qRgb(g,g,g); } } else if (depth == 3) { for (int i=0; i<width; i++) { int r = (int)(tp[0] * 255.0) & 0xff; int g = (int)(tp[s2] * 255.0) & 0xff; int b = (int)(tp[s2+s2] * 255.0) & 0xff; tp += s0; ip[i] = qRgb(r,g,b); } } else if (depth == 4) { for (int i=0; i<width; i++) { int a = (int)(tp[s2+s2+s2] * 255.0) & 0xff; int r = (int)(tp[0] * a) & 0xff; int g = (int)(tp[s2] * a) & 0xff; int b = (int)(tp[s2+s2] * a) & 0xff; tp += s0; ip[i] = qRgba(r,g,b,a); } } } // return luaQ_pushqt(L, image); return 1; } static int qttorch_qimage_totensor(lua_State *L) { THTensor *Tdst = 0; QImage image = luaQ_checkqvariant<QImage>(L, 1); int width = image.width(); int height = image.height(); int depth = 1; int tpos = 0; // validate arguments if (lua_type(L, 2) == LUA_TUSERDATA) { tpos = 2; Tdst = (THTensor*)luaT_checkudata(L,2,torch_Tensor_id); if (Tdst->nDimension == 3) depth = Tdst->size[2]; else if (Tdst->nDimension != 2) luaL_error(L, "tensor must have 2 or 3 dimensions"); if (depth != 1 && depth != 3 && depth != 4) luaL_error(L, "tensor third dimension must be 1, 3, or 4."); if (width != Tdst->size[0] || height != Tdst->size[1]) luaL_error(L, "tensor dimensions must match the image size."); } else { depth = luaL_optinteger(L, 2, 3); if (depth != 1 && depth != 3 && depth != 4) luaL_error(L, "depth must be 1, 3, or 4."); if (depth == 1) Tdst = THTensor_newWithSize2d(width, height); else Tdst = THTensor_newWithSize3d(width, height, depth); } // convert image if (image.format() != QImage::Format_ARGB32) image = image.convertToFormat(QImage::Format_ARGB32); if (image.format() != QImage::Format_ARGB32) luaL_error(L, "Cannot convert image to format ARGB32"); // fill tensor long s0 = Tdst->stride[0]; long s1 = Tdst->stride[1]; long s2 = (depth > 1) ? Tdst->stride[2] : 0; double *tdata = THTensor_dataPtr(Tdst); for(int j=0; j<height; j++) { QRgb *ip = (QRgb*)image.scanLine(j); double *tp = tdata + s1 * j; if (depth == 1) { for (int i=0; i<width; i++) { QRgb v = ip[i]; tp[0] = (qreal)qGray(v) / 255.0; tp += s0; } } else if (depth == 3) { for (int i=0; i<width; i++) { QRgb v = ip[i]; tp[0] = (qreal)qRed(v) / 255.0; tp[s2] = (qreal)qGreen(v) / 255.0; tp[s2+s2] = (qreal)qBlue(v) / 255.0; tp += s0; } } else if (depth == 4) { for (int i=0; i<width; i++) { QRgb v = ip[i]; tp[0] = (qreal)qRed(v) / 255.0; tp[s2] = (qreal)qGreen(v) / 255.0; tp[s2+s2] = (qreal)qBlue(v) / 255.0; tp[s2+s2+s2] = (qreal)qAlpha(v) / 255.0; tp += s0; } } } // return if (tpos > 0) lua_pushvalue(L, tpos); else luaT_pushudata(L, (void*)Tdst, torch_Tensor_id); return 1; } struct luaL_Reg qttorch_qimage_lib[] = { {"fromTensor", qttorch_qimage_fromtensor}, {"toTensor", qttorch_qimage_totensor}, {0,0} }; int luaopen_libqttorch(lua_State *L) { // load module 'qt' if (luaL_dostring(L, "require 'qt'")) lua_error(L); // load modules 'torch' if (luaL_dostring(L, "require 'torch'")) lua_error(L); torch_Tensor_id = luaT_checktypename2id(L, "torch.Tensor"); // enrichs QImage luaQ_pushmeta(L, QMetaType::QImage); luaQ_getfield(L, -1, "__metatable"); luaL_register(L, 0, qttorch_qimage_lib); return 0; } /* ------------------------------------------------------------- Local Variables: c++-font-lock-extra-types: ("\\sw+_t" "\\(lua_\\)?[A-Z]\\sw*[a-z]\\sw*") End: ------------------------------------------------------------- */
26.821256
75
0.494597
elq
ec9243b2f8ba70c85d5e5eb1bd3ac257b9a9978c
9,012
cpp
C++
Source/ChilliSource/Rendering/Model/SubMesh.cpp
angelahnicole/ChilliSource_ParticleOpt
6bee7e091c7635384d6aefbf730a69bbb5b55721
[ "MIT" ]
null
null
null
Source/ChilliSource/Rendering/Model/SubMesh.cpp
angelahnicole/ChilliSource_ParticleOpt
6bee7e091c7635384d6aefbf730a69bbb5b55721
[ "MIT" ]
null
null
null
Source/ChilliSource/Rendering/Model/SubMesh.cpp
angelahnicole/ChilliSource_ParticleOpt
6bee7e091c7635384d6aefbf730a69bbb5b55721
[ "MIT" ]
null
null
null
// // SubMesh.cpp // Chilli Source // Created by Scott Downie on 08/10/2010. // // The MIT License (MIT) // // Copyright (c) 2010 Tag Games Limited // // 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 <ChilliSource/Rendering/Model/SubMesh.h> #include <ChilliSource/Core/Base/Application.h> #include <ChilliSource/Rendering/Base/RenderSystem.h> #include <ChilliSource/Rendering/Base/VertexLayouts.h> #include <ChilliSource/Rendering/Material/Material.h> #include <ChilliSource/Rendering/Model/SkinnedAnimation.h> #include <ChilliSource/Rendering/Model/SkinnedAnimationGroup.h> #include <ChilliSource/Rendering/Texture/Texture.h> #include <limits> namespace ChilliSource { //-------------------------------------------------------------------- /// Constructor //-------------------------------------------------------------------- SubMesh::SubMesh(const std::string& instrName) : mstrName(instrName), mpMeshBuffer(nullptr) { } //----------------------------------------------------------------- /// Get Internal Mesh Buffer //----------------------------------------------------------------- MeshBuffer* SubMesh::GetInternalMeshBuffer() const { return mpMeshBuffer; } //----------------------------------------------------------------- /// Get AABB //----------------------------------------------------------------- const AABB& SubMesh::GetAABB() const { return mBoundingBox; } //----------------------------------------------------------------- /// Get Name //----------------------------------------------------------------- const std::string& SubMesh::GetName() const { return mstrName; } //----------------------------------------------------------------- /// Get Number of Vertices //----------------------------------------------------------------- u32 SubMesh::GetNumVerts() const { if (mpMeshBuffer != nullptr) return mpMeshBuffer->GetVertexCount(); else return 0; } //----------------------------------------------------------------- /// Get Number of Indices //----------------------------------------------------------------- u32 SubMesh::GetNumIndices() const { if (mpMeshBuffer != nullptr) return mpMeshBuffer->GetIndexCount(); else return 0; } //----------------------------------------------------------------- /// Prepare //----------------------------------------------------------------- void SubMesh::Prepare(RenderSystem* inpRenderSystem, const VertexDeclaration& inVertexDeclaration, u32 inudwIndexSizeInBytes, u32 inudwVertexCapacityInBytes, u32 inudwIndexCapacityInBytes, BufferAccess inAccessFlag, PrimitiveType inPrimativeType) { BufferDescription desc; desc.eUsageFlag = BufferUsage::k_static; desc.VertexDataCapacity = inudwVertexCapacityInBytes; desc.IndexDataCapacity = inudwIndexCapacityInBytes; desc.ePrimitiveType = inPrimativeType; desc.eAccessFlag = inAccessFlag; desc.VertexLayout = inVertexDeclaration; desc.IndexSize = inudwIndexSizeInBytes; mpMeshBuffer = inpRenderSystem->CreateBuffer(desc); mpMeshBuffer->SetVertexCount(0); mpMeshBuffer->SetIndexCount(0); } //----------------------------------------------------------------- /// Alter Buffer Declaration //----------------------------------------------------------------- void SubMesh::AlterBufferDeclaration(const VertexDeclaration& inVertexDeclaration, u32 inudwIndexSizeInBytes) { BufferDescription desc; desc.eUsageFlag = BufferUsage::k_static; desc.VertexDataCapacity = mpMeshBuffer->GetVertexCapacity(); desc.IndexDataCapacity = mpMeshBuffer->GetIndexCapacity(); desc.ePrimitiveType = mpMeshBuffer->GetPrimitiveType(); desc.eAccessFlag = mpMeshBuffer->GetBufferDescription().eAccessFlag; desc.VertexLayout = inVertexDeclaration; desc.IndexSize = inudwIndexSizeInBytes; mpMeshBuffer->SetBufferDescription(desc); mpMeshBuffer->SetVertexCount(0); mpMeshBuffer->SetIndexCount(0); } //----------------------------------------------------------------- /// Build //----------------------------------------------------------------- void SubMesh::Build(void* inpVertexData, void* inpIndexData, u32 inudwNumVertices, u32 indwNumIndices, Vector3 invMin, Vector3 invMax) { mpMeshBuffer->SetVertexCount(inudwNumVertices); mpMeshBuffer->SetIndexCount(indwNumIndices); //get the new capacities for the mesh u32 udwVertexDataCapacity = inudwNumVertices * mpMeshBuffer->GetVertexDeclaration().GetTotalSize(); u32 udwIndexDataCapacity = indwNumIndices * mpMeshBuffer->GetBufferDescription().IndexSize; //Bind both buffers mpMeshBuffer->Bind(); //---Vertex Mapping u8* pVBuffer = nullptr; mpMeshBuffer->LockVertex((f32**)&pVBuffer, 0, 0); //Map the data from the cache into the buffer memcpy(pVBuffer, inpVertexData, udwVertexDataCapacity); //---End mapping - Vertex mpMeshBuffer->UnlockVertex(); //---Index Mapping if(udwIndexDataCapacity != 0) { u16* pIBuffer = nullptr; mpMeshBuffer->LockIndex(&pIBuffer, 0, 0); memcpy(pIBuffer, inpIndexData, udwIndexDataCapacity); //---End mapping - Index mpMeshBuffer->UnlockIndex(); } //Calculate the size of this meshes bounding box Vector3 vSize = invMax - invMin; //Build our bounding box based on the size of all our sub-meshes mBoundingBox = AABB((invMax + invMin) * 0.5f, vSize); } //----------------------------------------------------------------- /// Set Skeleton Controller //----------------------------------------------------------------- void SubMesh::SetInverseBindPose(const InverseBindPosePtr& inpInverseBindPose) { mpInverseBindPose = inpInverseBindPose; } //----------------------------------------------------------------- /// Render //----------------------------------------------------------------- void SubMesh::Render(RenderSystem* inpRenderSystem, const Matrix4 &inmatWorld, const MaterialCSPtr& inpMaterial, ShaderPass in_shaderPass, const SkinnedAnimationGroupSPtr& inpAnimationGroup) const { CS_ASSERT(mpMeshBuffer->GetVertexCount() > 0, "Cannot render Sub Mesh without vertices"); if (inpMaterial->GetShader(in_shaderPass) != nullptr) { inpRenderSystem->ApplyMaterial(inpMaterial, in_shaderPass); if (inpAnimationGroup != nullptr) { //Apply inverse bind pose matrix. std::vector<Matrix4> combinedMatrices; inpAnimationGroup->ApplyInverseBindPose(mpInverseBindPose->mInverseBindPoseMatrices, combinedMatrices); inpRenderSystem->ApplyJoints(combinedMatrices); } mpMeshBuffer->Bind(); if(mpMeshBuffer->GetIndexCount() > 0) { inpRenderSystem->RenderBuffer(mpMeshBuffer, 0, mpMeshBuffer->GetIndexCount(), inmatWorld); } else { inpRenderSystem->RenderVertexBuffer(mpMeshBuffer, 0, mpMeshBuffer->GetVertexCount(), inmatWorld); } } } //----------------------------------------------------------------- /// Destructor //----------------------------------------------------------------- SubMesh::~SubMesh() { CS_SAFEDELETE(mpMeshBuffer); } }
41.529954
200
0.533844
angelahnicole
ec93cb349d7d4ea9d43645d12a52e8b28c8df3ac
15,082
cpp
C++
ChessVisualizer/Board.cpp
nErumin/Interactive_Chess
8b7769febb5bf94e8099257785dff8997d9c3dec
[ "MIT" ]
3
2019-06-08T09:10:45.000Z
2019-11-24T03:10:00.000Z
ChessVisualizer/Board.cpp
Jang-Woo-Jin/Interactive_Chess
8b7769febb5bf94e8099257785dff8997d9c3dec
[ "MIT" ]
4
2019-03-23T14:59:57.000Z
2019-09-18T04:29:18.000Z
ChessVisualizer/Board.cpp
Jang-Woo-Jin/Interactive_Chess
8b7769febb5bf94e8099257785dff8997d9c3dec
[ "MIT" ]
null
null
null
#include <memory> #include <exception> #include "Vector2.h" #include "Board.h" #include "King.h" #include "Queen.h" #include "Rook.h" #include "Bishop.h" #include "Knight.h" #include "Pawn.h" #include "NullPiece.h" #include "Cell.h" #include "PieceColor.h" #include <algorithm> #include <cmath> #include "Piece.h" #include "MathUtils.h" #include <map> Board::Board() : boardCells{ boardSize, std::vector<Cell>(boardSize, Cell(sharedNullPiece)) } { initializeBoardCellColors(); } void Board::initializeBoardCellColors() { for (size_t i = 0; i < boardCells.size(); ++i) { for (size_t j = 0; j < boardCells[i].size(); ++j) { auto cellColor = (i * boardCells.size() + j) % 2 == 0 ? CellColor::White : CellColor::Black; boardCells[i][j].setColor(cellColor); } } } void Board::initializeBoardCellPieces(PieceColor topPieceColor, PieceColor bottomPieceColor) { pieceColors.first = topPieceColor; pieceColors.second = bottomPieceColor; boardCells[0][0].setPiece(std::make_shared<Rook>(pieceColors.first)); boardCells[0][1].setPiece(std::make_shared<Knight>(pieceColors.first)); boardCells[0][2].setPiece(std::make_shared<Bishop>(pieceColors.first)); boardCells[0][3].setPiece(std::make_shared<Queen>(pieceColors.first)); boardCells[0][4].setPiece(std::make_shared<King>(pieceColors.first)); boardCells[0][5].setPiece(std::make_shared<Bishop>(pieceColors.first)); boardCells[0][6].setPiece(std::make_shared<Knight>(pieceColors.first)); boardCells[0][7].setPiece(std::make_shared<Rook>(pieceColors.first)); boardCells[1][0].setPiece(std::make_shared<Pawn>(pieceColors.first)); boardCells[1][1].setPiece(std::make_shared<Pawn>(pieceColors.first)); boardCells[1][2].setPiece(std::make_shared<Pawn>(pieceColors.first)); boardCells[1][3].setPiece(std::make_shared<Pawn>(pieceColors.first)); boardCells[1][4].setPiece(std::make_shared<Pawn>(pieceColors.first)); boardCells[1][5].setPiece(std::make_shared<Pawn>(pieceColors.first)); boardCells[1][6].setPiece(std::make_shared<Pawn>(pieceColors.first)); boardCells[1][7].setPiece(std::make_shared<Pawn>(pieceColors.first)); boardCells[6][0].setPiece(std::make_shared<Pawn>(pieceColors.second)); boardCells[6][1].setPiece(std::make_shared<Pawn>(pieceColors.second)); boardCells[6][2].setPiece(std::make_shared<Pawn>(pieceColors.second)); boardCells[6][3].setPiece(std::make_shared<Pawn>(pieceColors.second)); boardCells[6][4].setPiece(std::make_shared<Pawn>(pieceColors.second)); boardCells[6][5].setPiece(std::make_shared<Pawn>(pieceColors.second)); boardCells[6][6].setPiece(std::make_shared<Pawn>(pieceColors.second)); boardCells[6][7].setPiece(std::make_shared<Pawn>(pieceColors.second)); std::dynamic_pointer_cast<Pawn>(boardCells[6][0].getPiece())->setRotationDegree(180.0); std::dynamic_pointer_cast<Pawn>(boardCells[6][1].getPiece())->setRotationDegree(180.0); std::dynamic_pointer_cast<Pawn>(boardCells[6][2].getPiece())->setRotationDegree(180.0); std::dynamic_pointer_cast<Pawn>(boardCells[6][3].getPiece())->setRotationDegree(180.0); std::dynamic_pointer_cast<Pawn>(boardCells[6][4].getPiece())->setRotationDegree(180.0); std::dynamic_pointer_cast<Pawn>(boardCells[6][5].getPiece())->setRotationDegree(180.0); std::dynamic_pointer_cast<Pawn>(boardCells[6][6].getPiece())->setRotationDegree(180.0); std::dynamic_pointer_cast<Pawn>(boardCells[6][7].getPiece())->setRotationDegree(180.0); boardCells[7][0].setPiece(std::make_shared<Rook>(pieceColors.second)); boardCells[7][1].setPiece(std::make_shared<Knight>(pieceColors.second)); boardCells[7][2].setPiece(std::make_shared<Bishop>(pieceColors.second)); boardCells[7][3].setPiece(std::make_shared<Queen>(pieceColors.second)); boardCells[7][4].setPiece(std::make_shared<King>(pieceColors.second)); boardCells[7][5].setPiece(std::make_shared<Bishop>(pieceColors.second)); boardCells[7][6].setPiece(std::make_shared<Knight>(pieceColors.second)); boardCells[7][7].setPiece(std::make_shared<Rook>(pieceColors.second)); } PieceColor Board::getTopPieceColor() const noexcept { return pieceColors.first; } PieceColor Board::getBottomPieceColor() const noexcept { return pieceColors.second; } Cell& Board::getCell(const Vector2& location) { auto& cellReference = const_cast<const Board*>(this)->getCell(location); return const_cast<Cell&>(cellReference); } const Cell& Board::getCell(const Vector2& location) const { const auto integerVector = normalizeToIntegerVector(location); // (x, y) ==> (y, x) in the vector. return boardCells[integerVector.second][integerVector.first]; } std::vector<std::vector<PieceColor>> Board::makeObstacleMap() const { std::vector<std::vector<PieceColor>> obstacleMap{ boardCells.front().size(), std::vector<PieceColor>(boardCells.size(), PieceColor::None) }; for (size_t i = 0; i < boardCells.size(); ++i) { for (size_t j = 0; j < boardCells[i].size(); ++j) { obstacleMap[j][i] = boardCells[i][j].getPiece()->getColor(); } } return obstacleMap; } std::vector<Vector2> Board::findPieceMovableLocations(const Vector2 pieceLocation, PieceColor colorThreshold) const { const auto& cell = getCell(pieceLocation); if (!cell.isPieceOnBoard()) { return {}; } auto movableLocations = cell.getPiece()->movableLocationsUsingObstacles(pieceLocation, makeObstacleMap(), colorThreshold); auto boundaryIterator = std::remove_if(movableLocations.begin(), movableLocations.end(), [](const Vector2& location) { if (std::round(location.x()) < 0 || std::round(location.y()) < 0 || std::round(location.x()) >= boardSize || std::round(location.y()) >= boardSize) { return true; } return false; }); movableLocations.erase(boundaryIterator, movableLocations.end()); return movableLocations; } void Board::movePiece(const Vector2 pieceLocation, const Vector2 deltaLocation) { auto& currentCell = getCell(pieceLocation); auto movableLocations = findPieceMovableLocations(pieceLocation, currentCell.getPiece()->getColor()); auto nextLocation = pieceLocation + deltaLocation; auto searchResult = std::find_if(movableLocations.cbegin(), movableLocations.cend(), [nextLocation](const Vector2& movableLocation) { return normalizeToIntegerVector(movableLocation) == normalizeToIntegerVector(nextLocation); }); auto& targetCell = getCell(nextLocation); // decide its movement will remove the opponent's piece. auto nextCurrentCellPiecePtr = targetCell.getPiece(); auto originalTargetPiece = targetCell.getPiece(); if (targetCell.getPiece()->getColor() != PieceColor::None) { nextCurrentCellPiecePtr = sharedNullPiece; } targetCell.setPiece(currentCell.getPiece()); currentCell.setPiece(nextCurrentCellPiecePtr); if (isPieceTypeOf<King>(targetCell.getPiece().get()) && isChecked(nextLocation)) { currentCell.setPiece(targetCell.getPiece()); targetCell.setPiece(originalTargetPiece); std::cout << "Oops! A king cannot move to checked locations." << std::endl; throw std::invalid_argument{ "cannot move to that location " }; } if (searchResult == movableLocations.cend()) { currentCell.setPiece(targetCell.getPiece()); targetCell.setPiece(originalTargetPiece); std::cout << "Invalid movement ==> Current: " << pieceLocation << ", Delta: " << deltaLocation << std::endl; for (const auto& movableLocation : movableLocations) { std::cout << "[L] " << movableLocation << std::endl; } throw std::invalid_argument{ "cannot move to that location " }; } // must be checked when a pawn is moved. if (auto pawnPiece = std::dynamic_pointer_cast<Pawn>(targetCell.getPiece()); pawnPiece != nullptr) { pawnPiece->setPawnMoved(true); } // is there an enemy on the diagonal cells? PawnsFor([this](Pawn& pawn, std::pair<size_t,size_t> indices) { pawn.markDiagnoalMovable(PawnDiagonalMask::None); auto diagonalLocations = pawn.getDiagonalLocations({ static_cast<double>(indices.second), static_cast<double>(indices.first) }); auto boundaryIterator = std::remove_if(diagonalLocations.begin(), diagonalLocations.end(), [this, &pawn](const auto& maskLocation) { if (maskLocation.second.x() < 0 || maskLocation.second.y() < 0 || maskLocation.second.x() >= boardSize || maskLocation.second.y() >= boardSize) { return true; } const auto& targetCell = getCell(maskLocation.second); return targetCell.getPiece()->getColor() == PieceColor::None || targetCell.getPiece()->getColor() == pawn.getColor(); }); diagonalLocations.erase(boundaryIterator, diagonalLocations.end()); for (const auto& maskLocation : diagonalLocations) { pawn.markDiagnoalMovable(pawn.getMask() | maskLocation.first); } }); Vector2 previousLocation = pieceLocation; notifyToObservers(currentCell, std::move(previousLocation)); notifyToObservers(targetCell, std::move(nextLocation)); } void Board::PawnsFor(std::function<void (Pawn&, std::pair<size_t,size_t>)> handler) const { for (size_t i = 0; i < boardCells.size(); ++i) { for (size_t j = 0; j < boardCells[i].size(); ++j) { if (auto pawnPiece = std::dynamic_pointer_cast<Pawn>(boardCells[i][j].getPiece()); pawnPiece != nullptr) { handler(*pawnPiece, std::make_pair(i, j)); } } } } Cell& Board::getCell(size_t row, size_t column) noexcept { return boardCells[row][column]; } const Cell& Board::getCell(size_t row, size_t column) const noexcept { return boardCells[row][column]; } template <typename T> std::vector<Vector2> Board::findPieces() const { std::vector<Vector2> pieceLocations; for (size_t i = 0; i < boardCells.size(); ++i) { for (size_t j = 0; j < boardCells[i].size(); ++j) { if (std::dynamic_pointer_cast<T>(boardCells[i][j].getPiece()) != nullptr) { pieceLocations.push_back({ static_cast<double>(j), static_cast<double>(i) }); } } } return pieceLocations; } bool Board::isColorChecked(PieceColor color) const { Vector2 kingPieceLocation; for (const auto& location : findPieces<King>()) { auto indices = normalizeToIntegerVector(location); if (boardCells[indices.second][indices.first].getPiece()->getColor() == color) { kingPieceLocation = location; } } return isChecked(kingPieceLocation); } bool Board::isPieceTracedByOpponent(const Vector2& targetLocation) const { for (size_t i = 0; i < boardCells.size(); ++i) { for (size_t j = 0; j < boardCells[i].size(); ++j) { if (isPieceTracedByOther(targetLocation, { static_cast<double>(j), static_cast<double>(i) })) { return true; } } } return false; } bool Board::isPieceTracedByOther(const Vector2& targetLocation, const Vector2& pieceLocation) const { const auto& targetIndices = normalizeToIntegerVector(targetLocation); const auto& targetPiece = boardCells[targetIndices.second][targetIndices.first].getPiece(); return isPieceTracedByOtherSimulated(targetLocation, pieceLocation, targetPiece->getColor()); } bool Board::isPieceTracedByOtherSimulated(const Vector2& targetLocation, const Vector2& pieceLocation, PieceColor targetColor) const { const auto& tracerIndices = normalizeToIntegerVector(pieceLocation); const auto& tracerPiece = boardCells[tracerIndices.second][tracerIndices.first].getPiece(); auto opponentColor = getEnemyColor(targetColor); if (tracerPiece->getColor() == opponentColor) { auto movableLocation = findPieceMovableLocations(pieceLocation, tracerPiece->getColor()); auto foundResult = std::find_if(movableLocation.cbegin(), movableLocation.cend(), [&targetLocation](const Vector2& location) { return normalizeToIntegerVector(location) == normalizeToIntegerVector(targetLocation); }); if (foundResult != movableLocation.cend()) { return true; } } return false; } bool Board::isChecked(const Vector2& kingLocation) const { return isPieceTracedByOpponent(kingLocation); } bool Board::isStaleMated(PieceColor pieceColor) const { std::vector<Vector2> opponentPieceMovableLocations; std::vector<Vector2> kingMovableLocations; for (size_t i = 0; i < boardCells.size(); ++i) { for (size_t j = 0; j < boardCells[i].size(); ++j) { auto piece = getCell(i, j).getPiece(); Vector2 pieceLocation{ static_cast<double>(j), static_cast<double>(i) }; auto threshold = piece->getColor() == pieceColor ? pieceColor : PieceColor::None; auto movableLocations = findPieceMovableLocations(pieceLocation, threshold); auto* copyingTargetContainer = &opponentPieceMovableLocations; if (piece->getColor() == pieceColor) { if (std::dynamic_pointer_cast<King>(piece) == nullptr && movableLocations.size() > 0) { return false; } copyingTargetContainer = &kingMovableLocations; } if (auto pawnPtr = std::dynamic_pointer_cast<Pawn>(piece); piece->getColor() != pieceColor && pawnPtr != nullptr) { auto diagnoalLocations = pawnPtr->getDiagonalLocations(pieceLocation); movableLocations.clear(); movableLocations.push_back(diagnoalLocations.at(0).second); movableLocations.push_back(diagnoalLocations.at(1).second); } std::copy(movableLocations.begin(), movableLocations.end(), std::back_inserter(*copyingTargetContainer)); } } return std::all_of(kingMovableLocations.begin(), kingMovableLocations.end(), [&opponentPieceMovableLocations](const Vector2& kingMovableLocation) { return std::find(opponentPieceMovableLocations.begin(), opponentPieceMovableLocations.end(), kingMovableLocation) != opponentPieceMovableLocations.end(); }); } bool Board::isKingDead(PieceColor color) const { auto kings = findPieces<King>(); return std::all_of(kings.cbegin(), kings.cend(), [color, this](const Vector2& kingLocation) { return getCell(kingLocation).getPiece()->getColor() != color; }); }
36.08134
144
0.660788
nErumin
ec93d1181751399f8eb18c3ca34f9c2d13088cf5
2,112
hpp
C++
MyLib/ipcresponse.hpp
NuLL3rr0r/e-pooyasokhan-com-lcms
cf4b8cd0118a10bbecc4a1bb29c443385fa21e12
[ "MIT", "Unlicense" ]
null
null
null
MyLib/ipcresponse.hpp
NuLL3rr0r/e-pooyasokhan-com-lcms
cf4b8cd0118a10bbecc4a1bb29c443385fa21e12
[ "MIT", "Unlicense" ]
null
null
null
MyLib/ipcresponse.hpp
NuLL3rr0r/e-pooyasokhan-com-lcms
cf4b8cd0118a10bbecc4a1bb29c443385fa21e12
[ "MIT", "Unlicense" ]
null
null
null
#ifndef IPCRESPONSE_HPP #define IPCRESPONSE_HPP #include <functional> #include <string> #include <unordered_map> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include "compression.hpp" #include "ipcprotocol.hpp" namespace MyLib { template<typename _ResponseStatusT, typename _ResponseStatusToStringT, typename _ResponseArgT, typename _ResponseArgToStringT> class BasicIPCResponse; class IPCResponse; } class MyLib::IPCResponse { public: typedef MyLib::BasicIPCResponse<MyLib::IPCProtocol::ResponseStatus::Common, MyLib::IPCProtocol::ResponseStatus::CommonToString_t, MyLib::IPCProtocol::ResponseArg::CommonHash_t, MyLib::IPCProtocol::ResponseArg::CommonToString_t> Common; typedef MyLib::BasicIPCResponse<MyLib::IPCProtocol::ResponseStatus::Common, MyLib::IPCProtocol::ResponseStatus::CommonToString_t, MyLib::IPCProtocol::ResponseArg::CommonHash_t, MyLib::IPCProtocol::ResponseArg::CommonToString_t> HandShake; }; template<typename _ResponseStatusT, typename _ResponseStatusToStringT, typename _ResponseArgT, typename _ResponseArgToStringT> class MyLib::BasicIPCResponse { private: std::string m_message; public: BasicIPCResponse(const _ResponseStatusT status, const _ResponseStatusToStringT &statusToString, const _ResponseArgT &args = _ResponseArgT(), const _ResponseArgToStringT &argsToStringT = _ResponseArgToStringT()) { boost::property_tree::ptree resTree; resTree.put("response.protocol.name", IPCProtocol::Name()); resTree.put("response.protocol.version", IPCProtocol::Version()); resTree.put("response.status", statusToString.at(status)); for (auto &arg : args) { resTree.put("response.args.key", argsToStringT.at(arg.first)); resTree.put("response.args.value", arg.second); } IPCProtocol::SetMessage(resTree, m_message); } public: const std::string &Message() const { return m_message; } }; #endif /* IPCRESPONSE_HPP */
30.608696
99
0.721117
NuLL3rr0r
ec9477e9408b79385b9b0df57aa2725c7c625653
589
hpp
C++
include/RED4ext/Scripting/Natives/Generated/audio/VoiceTriggerLimits.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/audio/VoiceTriggerLimits.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/audio/VoiceTriggerLimits.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> namespace RED4ext { namespace audio { struct VoiceTriggerLimits { static constexpr const char* NAME = "audioVoiceTriggerLimits"; static constexpr const char* ALIAS = NAME; float probability; // 00 float singleNpcMinRepeatTime; // 04 float allNpcsMinRepeatTime; // 08 float allNpcsSharingVoicesetMinRepeatTime; // 0C float combatVolume; // 10 }; RED4EXT_ASSERT_SIZE(VoiceTriggerLimits, 0x14); } // namespace audio } // namespace RED4ext
23.56
66
0.740238
jackhumbert
ec954d788768ad94ba2fd415232e4343a949df57
788
cpp
C++
src/Item.cpp
Miguel-EpicJS/state-rpg-tutorial
c909fe7ffee2cad4d3aac88afef9c5dc21b965ce
[ "MIT" ]
null
null
null
src/Item.cpp
Miguel-EpicJS/state-rpg-tutorial
c909fe7ffee2cad4d3aac88afef9c5dc21b965ce
[ "MIT" ]
null
null
null
src/Item.cpp
Miguel-EpicJS/state-rpg-tutorial
c909fe7ffee2cad4d3aac88afef9c5dc21b965ce
[ "MIT" ]
null
null
null
#include "../includes/Item.h" void Item::generate() { } Item::Item(std::string name, unsigned type, unsigned rarity, unsigned value) { this->name = name; this->type = type; this->rarity = rarity; this->value = value; } Item::~Item() { } const std::string& Item::getName() { return this->name; } const unsigned& Item::getType() { return this->type; } const unsigned& Item::getRarity() { return this->rarity; } const unsigned& Item::getValue() { return this->value; } const std::string Item::toString() const { std::stringstream ss; ss << " Name: " << this->name << " | Type: " << this->type << " | Rarity: " << this->rarity << " | Value: " << this->value << "\n"; return ss.str(); }
16.081633
76
0.549492
Miguel-EpicJS
ec9624f4536ab72f57b382583e849e0d3e439ec1
1,429
cpp
C++
FleetOptimizer/PortList.cpp
valerymo/fleet-optimizer
1657f853a990cea459377a9f4f457ada675b997c
[ "Apache-2.0" ]
null
null
null
FleetOptimizer/PortList.cpp
valerymo/fleet-optimizer
1657f853a990cea459377a9f4f457ada675b997c
[ "Apache-2.0" ]
null
null
null
FleetOptimizer/PortList.cpp
valerymo/fleet-optimizer
1657f853a990cea459377a9f4f457ada675b997c
[ "Apache-2.0" ]
null
null
null
// PortList.cpp: implementation of the CPortList class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "FleetOptimizer.h" #include "PortList.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif CPortList* CPortList::_instance = 0; CPortList* CPortList::Instance(){ if (_instance == 0){ _instance = new CPortList; } return _instance; } ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CPortList::CPortList() { PortList = 0; //MessageBox(NULL,"CPortList()","CPortList",MB_OK); POSITION pos = ((CFleetOptimizerApp*)AfxGetApp())->GetCurrFleetOptimizerDoc()->GetFirstViewPosition(); COutputView* pView = (COutputView*) ((CFleetOptimizerApp*)AfxGetApp())->GetCurrFleetOptimizerDoc()->GetNextView(pos); pView = (COutputView*) ((CFleetOptimizerApp*)AfxGetApp())->GetCurrFleetOptimizerDoc()->GetNextView(pos); pView->TextOut("CPortList()"); } CPortList::~CPortList() { } ////////// void CPortList::append(CPort *pPort) { if(CPortList::PortList == 0) PortList = pPort; else at_end->next = pPort; at_end = pPort; } int CPortList::is_empty() { return PortList == 0 ? 1 : 0; } CPort * CPortList::GetPortListHead() { return PortList; }
22.68254
118
0.578027
valerymo
ec96b45150edfa97c232188f358bc35342de42cb
408
cpp
C++
src/Tests/ActionBuildBruteforce.cpp
Matej-Chmel/hnsw-chm0065
ada0d367b0231caf94551a3fc760d22648c783c6
[ "MIT" ]
null
null
null
src/Tests/ActionBuildBruteforce.cpp
Matej-Chmel/hnsw-chm0065
ada0d367b0231caf94551a3fc760d22648c783c6
[ "MIT" ]
null
null
null
src/Tests/ActionBuildBruteforce.cpp
Matej-Chmel/hnsw-chm0065
ada0d367b0231caf94551a3fc760d22648c783c6
[ "MIT" ]
null
null
null
#include "ActionBuildBruteforce.hpp" #include "literals.hpp" namespace chm { ActionBuildBruteforce::ActionBuildBruteforce() : Action(false) {} void ActionBuildBruteforce::run() { this->s->bruteforce = new Bruteforce(this->s->nodeCoords->data(), DIM, NODE_COUNT); } std::string ActionBuildBruteforce::text(long long elapsedMS) { return ("Bruteforce built in "_f << elapsedMS << " ms.").str(); } }
27.2
85
0.715686
Matej-Chmel
ec9837c9fa78ae5d02004bb734ba57f4dfdeea5c
1,849
hxx
C++
main/cui/source/inc/bbdlg.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/cui/source/inc/bbdlg.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/cui/source/inc/bbdlg.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _SVX_BBDLG_HXX #define _SVX_BBDLG_HXX // include --------------------------------------------------------------- #include <sfx2/tabdlg.hxx> /*-------------------------------------------------------------------- Beschreibung: Border Background Pages buendeln --------------------------------------------------------------------*/ class SvxBorderBackgroundDlg: public SfxTabDialog { public: SvxBorderBackgroundDlg(Window *pParent, const SfxItemSet& rCoreSet, bool bEnableSelector = false, bool bEnableDrawingLayerFillStyles = false); ~SvxBorderBackgroundDlg(); protected: virtual void PageCreated(sal_uInt16 nPageId,SfxTabPage& rTabPage); private: /// bitfield bool mbEnableBackgroundSelector : 1; // fuer Border/Background-Dlg bool mbEnableDrawingLayerFillStyles : 1; // for full DrawingLayer FillStyles }; #endif
33.017857
91
0.601406
Grosskopf
ec9cdb1af9c522489dc45d61aa0133cdd007fb7f
366
cpp
C++
Biosphere/Source/bio/biotope/arm/Tick.cpp
PMArkive/Biosphere
baf62450b084ce327c3fc2eb0aa918e32462164e
[ "MIT" ]
1
2021-09-10T17:18:51.000Z
2021-09-10T17:18:51.000Z
Biosphere/Source/bio/biotope/arm/Tick.cpp
PMArkive/Biosphere
baf62450b084ce327c3fc2eb0aa918e32462164e
[ "MIT" ]
null
null
null
Biosphere/Source/bio/biotope/arm/Tick.cpp
PMArkive/Biosphere
baf62450b084ce327c3fc2eb0aa918e32462164e
[ "MIT" ]
null
null
null
#include <bio/biotope/arm/Tick.hpp> namespace bio::arm { u64 GetSystemTick() { u64 tick; __asm__ __volatile__ ("mrs %x[data], cntpct_el0" : [data] "=r" (tick)); return tick; } u64 GetSystemTickFrequency() { u64 freq; __asm__ ("mrs %x[data], cntfrq_el0" : [data] "=r" (freq)); return freq; } }
20.333333
79
0.538251
PMArkive
ec9cedbad08ac278a4bf7ba84485bfcbb276b951
1,879
cpp
C++
hiro/cocoa/widget/frame.cpp
kirwinia/ares-emu-v121
722aa227caf943a4a64f1678c1bdd07b38b15caa
[ "0BSD" ]
2
2021-06-28T06:04:56.000Z
2021-06-28T11:30:20.000Z
cocoa/widget/frame.cpp
ProtoByter/hiro
89972942430f5cc9c931afdc115a0db253fa339a
[ "0BSD" ]
1
2022-02-16T02:46:39.000Z
2022-02-16T04:30:29.000Z
cocoa/widget/frame.cpp
ProtoByter/hiro
89972942430f5cc9c931afdc115a0db253fa339a
[ "0BSD" ]
1
2021-12-25T11:34:57.000Z
2021-12-25T11:34:57.000Z
#if defined(Hiro_Frame) @implementation CocoaFrame : NSBox -(id) initWith:(hiro::mFrame&)frameReference { if(self = [super initWithFrame:NSMakeRect(0, 0, 0, 0)]) { frame = &frameReference; [self setTitle:@""]; } return self; } @end namespace hiro { auto pFrame::construct() -> void { @autoreleasepool { cocoaView = cocoaFrame = [[CocoaFrame alloc] initWith:self()]; pWidget::construct(); setText(state().text); } } auto pFrame::destruct() -> void { @autoreleasepool { [cocoaView removeFromSuperview]; [cocoaView release]; } } auto pFrame::append(sSizable sizable) -> void { } auto pFrame::remove(sSizable sizable) -> void { } auto pFrame::setEnabled(bool enabled) -> void { pWidget::setEnabled(enabled); if(auto& sizable = state().sizable) sizable->setEnabled(enabled); } auto pFrame::setFont(const Font& font) -> void { @autoreleasepool { [cocoaView setTitleFont:pFont::create(font)]; } if(auto& sizable = state().sizable) sizable->setFont(font); } auto pFrame::setGeometry(Geometry geometry) -> void { bool empty = !state().text; Size size = pFont::size(self().font(true), state().text); pWidget::setGeometry({ geometry.x() - 3, geometry.y() - (empty ? size.height() - 2 : 1), geometry.width() + 6, geometry.height() + (empty ? size.height() + 2 : 5) }); if(auto& sizable = state().sizable) { sizable->setGeometry({ geometry.x() + 1, geometry.y() + (empty ? 1 : size.height() - 2), geometry.width() - 2, geometry.height() - (empty ? 1 : size.height() - 1) }); } } auto pFrame::setText(const string& text) -> void { @autoreleasepool { [cocoaView setTitle:[NSString stringWithUTF8String:text]]; } } auto pFrame::setVisible(bool visible) -> void { pWidget::setVisible(visible); if(auto& sizable = state().sizable) sizable->setVisible(visible); } } #endif
23.197531
79
0.645556
kirwinia
ec9e388ab9231c80f35ad42808eee70f32e3ab75
919
cpp
C++
src/renderer/shaders/shaders.cpp
fantasiorona/LRender
5fb6f29c323df53986e39b4350ee8494e4642452
[ "MIT" ]
5
2019-11-22T05:31:33.000Z
2021-11-18T19:15:21.000Z
src/renderer/shaders/shaders.cpp
fantasiorona/LRender
5fb6f29c323df53986e39b4350ee8494e4642452
[ "MIT" ]
7
2019-02-21T11:26:38.000Z
2019-03-29T10:28:58.000Z
src/renderer/shaders/shaders.cpp
fantasiorona/LRender
5fb6f29c323df53986e39b4350ee8494e4642452
[ "MIT" ]
1
2021-04-22T17:03:04.000Z
2021-04-22T17:03:04.000Z
#include "shaders.h" using namespace LRender; Shaders::Shaders() : branches( "LRender/glsl/vertexGeometry.glsl", "LRender/glsl/fragmentGeometry.glsl"), leaves( "LRender/glsl/vertexGeometry.glsl", "LRender/glsl/fragmentLeaf.glsl"), shadows( "LRender/glsl/vertexShadows.glsl", "LRender/glsl/fragmentShadows.glsl"){ } const Shader &Shaders::getBranches() const { return branches; } const Shader &Shaders::getLeaves() const { return leaves; } const Shader &Shaders::getShadows() const { return shadows; } const ShaderExposure &Shaders::getExposure() const { return exposure; } const ShaderImage &Shaders::getImage() const { return image; } const ShaderInteger &Shaders::getInteger() const { return integer; } const ShaderGeometryShadows& Shaders::getGeometryShadows() const { return geometryShadows; } const ShaderLeavesShadows& Shaders::getLeavesShadows() const { return leavesShadows; }
18.755102
66
0.747552
fantasiorona
ec9f5f3be8e070fac73086b6e41122c7a5565047
2,525
cpp
C++
dev/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MotionEventExport.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
8
2019-10-07T16:33:47.000Z
2020-12-07T03:59:58.000Z
dev/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MotionEventExport.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
null
null
null
dev/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MotionEventExport.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
5
2020-08-27T20:44:18.000Z
2021-08-21T22:54:11.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "Exporter.h" #include <MCore/Source/ReflectionSerializer.h> #include <EMotionFX/Source/MotionEvent.h> #include <EMotionFX/Source/MotionEventTrack.h> #include <EMotionFX/Source/EventManager.h> #include <EMotionFX/Source/MotionEventTable.h> #include <EMotionFX/Source/Motion.h> #include <AzCore/Component/ComponentApplicationBus.h> #include <AzCore/Serialization/Utils.h> namespace ExporterLib { void SaveMotionEvents(MCore::Stream* file, EMotionFX::MotionEventTable* motionEventTable, MCore::Endian::EEndianType targetEndianType) { // get the number of motion event tracks and check if we have to save // any at all if (motionEventTable->GetNumTracks() == 0) { return; } AZ::Outcome<AZStd::string> serializedMotionEventTable = MCore::ReflectionSerializer::Serialize(motionEventTable); if (!serializedMotionEventTable.IsSuccess()) { return; } const size_t serializedTableSizeInBytes = serializedMotionEventTable.GetValue().size(); // the motion event table chunk header EMotionFX::FileFormat::FileChunk chunkHeader; chunkHeader.mChunkID = EMotionFX::FileFormat::SHARED_CHUNK_MOTIONEVENTTABLE; chunkHeader.mVersion = 2; chunkHeader.mSizeInBytes = static_cast<uint32>(serializedTableSizeInBytes + sizeof(EMotionFX::FileFormat::FileMotionEventTableSerialized)); EMotionFX::FileFormat::FileMotionEventTableSerialized tableHeader; tableHeader.m_size = serializedTableSizeInBytes; // endian conversion ConvertFileChunk(&chunkHeader, targetEndianType); // save the chunk header and the chunk file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk)); file->Write(&tableHeader, sizeof(EMotionFX::FileFormat::FileMotionEventTableSerialized)); file->Write(serializedMotionEventTable.GetValue().c_str(), serializedTableSizeInBytes); } } // namespace ExporterLib
41.393443
147
0.730297
jeikabu
eca25f6802bc201467789f170cfe8406b04d7dce
941
cc
C++
chainerx_cc/chainerx/routines/loss.cc
zaltoprofen/chainer
3b03f9afc80fd67f65d5e0395ef199e9506b6ee1
[ "MIT" ]
2
2019-08-12T21:48:04.000Z
2020-08-27T18:04:20.000Z
chainerx_cc/chainerx/routines/loss.cc
zaltoprofen/chainer
3b03f9afc80fd67f65d5e0395ef199e9506b6ee1
[ "MIT" ]
null
null
null
chainerx_cc/chainerx/routines/loss.cc
zaltoprofen/chainer
3b03f9afc80fd67f65d5e0395ef199e9506b6ee1
[ "MIT" ]
null
null
null
#include "chainerx/routines/loss.h" #include "chainerx/array.h" #include "chainerx/routines/creation.h" #include "chainerx/routines/explog.h" #include "chainerx/routines/indexing.h" #include "chainerx/routines/misc.h" #include "chainerx/scalar.h" namespace chainerx { Array AbsoluteError(const Array& x1, const Array& x2) { return Absolute(x1 - x2); } Array SquaredError(const Array& x1, const Array& x2) { return Square(x1 - x2); } Array GaussianKLDivergence(const Array& mean, const Array& ln_var) { return (Square(mean) + Exp(ln_var) - ln_var - 1) * 0.5; } Array HuberLoss(const Array& x1, const Array& x2, Scalar delta) { Array a = x1 - x2; Array abs_a = Absolute(a); Array delta_array = chainerx::FullLike(a, delta, a.device()); // TODO(kshitij12345) : use Array < Scalar when implemented. return Where(abs_a < delta_array, 0.5 * Square(a), delta * (abs_a - Scalar{0.5} * delta)); } } // namespace chainerx
33.607143
126
0.701382
zaltoprofen
eca66845ac5b6d5d2af240a45b2e3388b8dc1623
13,705
cpp
C++
Modules/Core/test/mitkDataNodeTest.cpp
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Modules/Core/test/mitkDataNodeTest.cpp
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Modules/Core/test/mitkDataNodeTest.cpp
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkDataNode.h" #include "mitkVtkPropRenderer.h" #include <vtkWindow.h> #include "mitkTestingMacros.h" #include <iostream> // Basedata Test #include <mitkGeometryData.h> #include <mitkImage.h> #include <mitkManufacturerLogo.h> #include <mitkPlaneGeometryData.h> #include <mitkPointSet.h> #include <mitkSurface.h> // Mapper Test #include <mitkImageVtkMapper2D.h> #include <mitkPlaneGeometryDataMapper2D.h> #include <mitkSurfaceVtkMapper2D.h> #include <mitkPlaneGeometryDataVtkMapper3D.h> #include <mitkPointSetVtkMapper2D.h> #include <mitkPointSetVtkMapper3D.h> #include <mitkSurfaceVtkMapper3D.h> // Interactors #include <mitkPointSetDataInteractor.h> // Property list Test #include <mitkImageGenerator.h> /** * Simple example for a test for the (non-existent) class "DataNode". * * argc and argv are the command line parameters which were passed to * the ADD_TEST command in the CMakeLists.txt file. For the automatic * tests, argv is either empty for the simple tests or contains the filename * of a test image for the image tests (see CMakeLists.txt). */ class mitkDataNodeTestClass { public: static void TestDataSetting(mitk::DataNode::Pointer dataNode) { mitk::BaseData::Pointer baseData; // NULL pointer Test dataNode->SetData(baseData); MITK_TEST_CONDITION(baseData == dataNode->GetData(), "Testing if a NULL pointer was set correctly") baseData = mitk::GeometryData::New(); dataNode->SetData(baseData); MITK_TEST_CONDITION(baseData == dataNode->GetData(), "Testing if a GeometryData object was set correctly") baseData = mitk::PlaneGeometryData::New(); dataNode->SetData(baseData); MITK_TEST_CONDITION(baseData == dataNode->GetData(), "Testing if a PlaneGeometryData object was set correctly") baseData = mitk::ManufacturerLogo::New(); dataNode->SetData(baseData); MITK_TEST_CONDITION(baseData == dataNode->GetData(), "Testing if a ManufacturerLogo object was set correctly") baseData = mitk::PointSet::New(); dataNode->SetData(baseData); MITK_TEST_CONDITION(baseData == dataNode->GetData(), "Testing if a PointSet object was set correctly") baseData = mitk::Image::New(); dataNode->SetData(baseData); MITK_TEST_CONDITION(baseData == dataNode->GetData(), "Testing if a Image object was set correctly") baseData = mitk::Surface::New(); dataNode->SetData(baseData); MITK_TEST_CONDITION(baseData == dataNode->GetData(), "Testing if a Surface object was set correctly") dataNode->SetData(nullptr); MITK_TEST_CONDITION(nullptr == dataNode->GetData(), "Testing if base data (already set) was replaced by a NULL pointer") } static void TestMapperSetting(mitk::DataNode::Pointer dataNode) { // tests the SetMapper() method // in dataNode is a mapper vector which can be accessed by index // in this test method we use only slot 0 (filled with null) and slot 1 // so we also test the destructor of the mapper classes mitk::Mapper::Pointer mapper; dataNode->SetMapper(0, mapper); MITK_TEST_CONDITION(mapper == dataNode->GetMapper(0), "Testing if a NULL pointer was set correctly") mapper = mitk::PlaneGeometryDataMapper2D::New(); dataNode->SetMapper(1, mapper); MITK_TEST_CONDITION(mapper == dataNode->GetMapper(1), "Testing if a PlaneGeometryDataMapper2D was set correctly") MITK_TEST_CONDITION(dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode") mapper = mitk::ImageVtkMapper2D::New(); dataNode->SetMapper(1, mapper); MITK_TEST_CONDITION(mapper == dataNode->GetMapper(1), "Testing if a ImageVtkMapper2D was set correctly") MITK_TEST_CONDITION(dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode") mapper = mitk::PointSetVtkMapper2D::New(); dataNode->SetMapper(1, mapper); MITK_TEST_CONDITION(mapper == dataNode->GetMapper(1), "Testing if a PointSetVtkMapper2D was set correctly") MITK_TEST_CONDITION(dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode") mapper = mitk::SurfaceVtkMapper2D::New(); dataNode->SetMapper(1, mapper); MITK_TEST_CONDITION(mapper == dataNode->GetMapper(1), "Testing if a SurfaceGLMapper2D was set correctly") MITK_TEST_CONDITION(dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode") mapper = mitk::PlaneGeometryDataVtkMapper3D::New(); dataNode->SetMapper(1, mapper); MITK_TEST_CONDITION(mapper == dataNode->GetMapper(1), "Testing if a PlaneGeometryDataVtkMapper3D was set correctly") MITK_TEST_CONDITION(dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode") mapper = mitk::PointSetVtkMapper3D::New(); dataNode->SetMapper(1, mapper); MITK_TEST_CONDITION(mapper == dataNode->GetMapper(1), "Testing if a PointSetVtkMapper3D was set correctly") MITK_TEST_CONDITION(dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode") mapper = mitk::SurfaceVtkMapper3D::New(); dataNode->SetMapper(1, mapper); MITK_TEST_CONDITION(mapper == dataNode->GetMapper(1), "Testing if a SurfaceVtkMapper3D was set correctly") MITK_TEST_CONDITION(dataNode == mapper->GetDataNode(), "Testing if the mapper returns the right DataNode") } static void TestInteractorSetting(mitk::DataNode::Pointer dataNode) { // this method tests the SetInteractor() and GetInteractor methods // the DataInteractor base class calls the DataNode->SetInteractor method mitk::DataInteractor::Pointer interactor; MITK_TEST_CONDITION(interactor == dataNode->GetDataInteractor(), "Testing if a NULL pointer was set correctly (DataInteractor)") interactor = mitk::PointSetDataInteractor::New(); interactor->SetEventConfig("PointSetConfig.xml"); interactor->SetDataNode(dataNode); MITK_TEST_CONDITION(interactor == dataNode->GetDataInteractor(), "Testing if a PointSetDataInteractor was set correctly") interactor = mitk::PointSetDataInteractor::New(); dataNode->SetDataInteractor(interactor); MITK_TEST_CONDITION(interactor == dataNode->GetDataInteractor(), "Testing if a PointSetDataInteractor was set correctly") } static void TestPropertyList(mitk::DataNode::Pointer dataNode) { mitk::PropertyList::Pointer propertyList = dataNode->GetPropertyList(); MITK_TEST_CONDITION(dataNode->GetPropertyList() != NULL, "Testing if the constructor set the propertylist") dataNode->SetIntProperty("int", -31337); int x; dataNode->GetIntProperty("int", x); MITK_TEST_CONDITION(x == -31337, "Testing Set/GetIntProperty"); dataNode->SetBoolProperty("bool", true); bool b; dataNode->GetBoolProperty("bool", b); MITK_TEST_CONDITION(b == true, "Testing Set/GetBoolProperty"); dataNode->SetFloatProperty("float", -31.337); float y; dataNode->GetFloatProperty("float", y); MITK_TEST_CONDITION(y - -31.337 < 0.01, "Testing Set/GetFloatProperty"); double yd = 0; dataNode->GetDoubleProperty("float", yd); MITK_TEST_CONDITION(mitk::Equal(yd, static_cast<double>(y)), "Testing GetDoubleProperty"); double d = sqrt(2.0); dataNode->SetDoubleProperty("double", d); double read_d; MITK_TEST_CONDITION(dataNode->GetDoubleProperty("double", read_d), "Testing GetDoubleProperty"); MITK_TEST_CONDITION(d == read_d, "Testing Set/GetDoubleProperty"); // Equal does not the same thing dataNode->SetStringProperty("string", "MITK"); std::string s = "GANZVIELPLATZ"; dataNode->GetStringProperty("string", s); MITK_TEST_CONDITION(s == "MITK", "Testing Set/GetStringProperty"); std::string name = "MyTestName"; dataNode->SetName(name.c_str()); MITK_TEST_CONDITION(dataNode->GetName() == name, "Testing Set/GetName"); name = "MySecondTestName"; dataNode->SetName(name); MITK_TEST_CONDITION(dataNode->GetName() == name, "Testing Set/GetName(std::string)"); MITK_TEST_CONDITION(propertyList == dataNode->GetPropertyList(), "Testing if the propertylist has changed during the last tests") } static void TestSelected(mitk::DataNode::Pointer dataNode) { vtkRenderWindow *renderWindow = vtkRenderWindow::New(); mitk::VtkPropRenderer::Pointer base = mitk::VtkPropRenderer::New("the first renderer", renderWindow, mitk::RenderingManager::GetInstance()); // with BaseRenderer==Null MITK_TEST_CONDITION(!dataNode->IsSelected(), "Testing if this node is not set as selected") dataNode->SetSelected(true); MITK_TEST_CONDITION(dataNode->IsSelected(), "Testing if this node is set as selected") dataNode->SetSelected(false); dataNode->SetSelected(true, base); MITK_TEST_CONDITION(dataNode->IsSelected(base), "Testing if this node with right base renderer is set as selected") // Delete RenderWindow correctly renderWindow->Delete(); } static void TestGetMTime(mitk::DataNode::Pointer dataNode) { unsigned long time; time = dataNode->GetMTime(); mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); dataNode->SetData(pointSet); MITK_TEST_CONDITION(time != dataNode->GetMTime(), "Testing if the node timestamp is updated after adding data to the node") mitk::Point3D point; point.Fill(3.0); pointSet->SetPoint(0, point); // less or equal because dataNode timestamp is little later then the basedata timestamp MITK_TEST_CONDITION(pointSet->GetMTime() <= dataNode->GetMTime(), "Testing if the node timestamp is updated after base data was modified") // testing if changing anything in the property list also sets the node in a modified state unsigned long lastModified = dataNode->GetMTime(); dataNode->SetIntProperty("testIntProp", 2344); MITK_TEST_CONDITION(lastModified <= dataNode->GetMTime(), "Testing if the node timestamp is updated after property list was modified") } static void TestSetDataUnderPropertyChange(void) { mitk::Image::Pointer image = mitk::Image::New(); mitk::Image::Pointer additionalImage = mitk::Image::New(); mitk::DataNode::Pointer dataNode = mitk::DataNode::New(); image = mitk::ImageGenerator::GenerateRandomImage<unsigned char>(3u, 3u); dataNode->SetData(image); const float defaultOutlineWidth = 1.0; float outlineWidth = 0; dataNode->GetPropertyValue("outline width", outlineWidth); MITK_TEST_CONDITION(mitk::Equal(outlineWidth, defaultOutlineWidth), "Testing if the SetData set the default property list") dataNode->SetProperty("outline width", mitk::FloatProperty::New(42.0)); dataNode->SetData(image); dataNode->GetPropertyValue("outline width", outlineWidth); MITK_TEST_CONDITION(mitk::Equal(outlineWidth, 42.0), "Testing if the SetData does not set anything if image data is identical") dataNode->SetData(additionalImage); dataNode->GetPropertyValue("outline width", outlineWidth); MITK_TEST_CONDITION(mitk::Equal(outlineWidth, 42.0), "Testing if the SetData does not set the default property list if image data is already set") mitk::Surface::Pointer surface = mitk::Surface::New(); dataNode->SetData(surface); MITK_TEST_CONDITION(dataNode->GetPropertyValue("outline width", outlineWidth) == false, "Testing if SetData cleared previous property list and set the default property list if data " "of different type has been set") } }; // mitkDataNodeTestClass int mitkDataNodeTest(int /* argc */, char * /*argv*/ []) { // always start with this! MITK_TEST_BEGIN("DataNode") // let's create an object of our class mitk::DataNode::Pointer myDataNode = mitk::DataNode::New(); // first test: did this work? // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since // it makes no sense to continue without an object. MITK_TEST_CONDITION_REQUIRED(myDataNode.IsNotNull(), "Testing instantiation") // test setData() Method mitkDataNodeTestClass::TestDataSetting(myDataNode); mitkDataNodeTestClass::TestMapperSetting(myDataNode); // // note, that no data is set to the dataNode mitkDataNodeTestClass::TestInteractorSetting(myDataNode); mitkDataNodeTestClass::TestPropertyList(myDataNode); mitkDataNodeTestClass::TestSelected(myDataNode); mitkDataNodeTestClass::TestGetMTime(myDataNode); mitkDataNodeTestClass::TestSetDataUnderPropertyChange(); // write your own tests here and use the macros from mitkTestingMacros.h !!! // do not write to std::cout and do not return from this function yourself! // always end with this! MITK_TEST_END() }
42.430341
121
0.69668
liu3xing3long
eca77704fa909959c221f87f6eac38ce13099852
15,387
cpp
C++
dynmedias/src/main/jni/utility/common/Profile.cpp
yunsean/SharedLibrary
e3236a8daa7677d93b0aa011881838ad0ff82f77
[ "MIT" ]
1
2019-02-27T10:00:16.000Z
2019-02-27T10:00:16.000Z
dynmedias/src/main/jni/utility/common/Profile.cpp
yunsean/SharedLibrary
e3236a8daa7677d93b0aa011881838ad0ff82f77
[ "MIT" ]
null
null
null
dynmedias/src/main/jni/utility/common/Profile.cpp
yunsean/SharedLibrary
e3236a8daa7677d93b0aa011881838ad0ff82f77
[ "MIT" ]
null
null
null
#include <iosfwd> #include <iostream> #include <fstream> #include "Profile.h" #include "Byte.h" #include "xsystem.h" #define INVALID_VALUE _T("(-~!@#$%^&*+)") ////////////////////////////////////////////////////////////////////////// //CProfile CProfile::CProfile(LPCTSTR lpszIniFile) : m_strIniFile(lpszIniFile) , m_strAppname() , m_strKeyName() , m_strValue() { } CProfile::CProfile(const CProfile& cParent, LPCTSTR lpszAppOrKey) : m_strIniFile(cParent.m_strIniFile) , m_strAppname(cParent.m_strAppname.IsEmpty() ? lpszAppOrKey : cParent.m_strAppname.c_str()) , m_strKeyName(cParent.m_strAppname.IsEmpty() ? _T("") : lpszAppOrKey) , m_strValue() { } CProfile::CProfile(const CProfile& cParent, LPCTSTR lpszAppname, LPCTSTR lpszKeyname) : m_strIniFile(cParent.m_strIniFile) , m_strAppname(lpszAppname) , m_strKeyName(lpszKeyname) , m_strValue() { } CProfile::CProfile(const CProfile& cParent, LPCTSTR lpszAppname, LPCTSTR lpszKeyname, LPCTSTR lpszDefault) : m_strIniFile(cParent.m_strIniFile) , m_strAppname(_tcslen(lpszAppname) ? lpszAppname : _T(".")) , m_strKeyName(lpszKeyname) , m_strValue() { std::xtstring strValue; getPrivateProfileString(m_strAppname, m_strKeyName, INVALID_VALUE, strValue.GetBuffer(1024), 1024, m_strIniFile); strValue.ReleaseBuffer(); if (strValue == INVALID_VALUE)writePrivateProfileString(m_strAppname, m_strKeyName, lpszDefault, m_strIniFile); } CProfile::CProfile(const CProfile& cParent, LPCTSTR lpszAppname, LPCTSTR lpszKeyname, LPCTSTR lpszDefault, LPCTSTR lpszRemark) : m_strIniFile(cParent.m_strIniFile) , m_strAppname(_tcslen(lpszAppname) ? lpszAppname : _T(".")) , m_strKeyName(lpszKeyname) , m_strValue() { std::xtstring strValue; getPrivateProfileString(m_strAppname, m_strKeyName, INVALID_VALUE, strValue.GetBuffer(1024), 1024, m_strIniFile); strValue.ReleaseBuffer(); if (strValue == INVALID_VALUE)writePrivateProfileString(m_strAppname, m_strKeyName, lpszDefault, m_strIniFile, lpszRemark); } CProfile CProfile::Default() { char exeFile[1024]; std::exefile(exeFile); std::xtstring iniFile(exeFile); iniFile += _T(".ini"); return CProfile(iniFile); } CProfile CProfile::Profile(LPCTSTR lpszIniFile) { return CProfile(lpszIniFile); } CProfile CProfile::operator [](LPCTSTR lpszKey) { return CProfile(*this, lpszKey); } CProfile CProfile::operator ()(LPCTSTR lpszKeyname) { return CProfile(*this, lpszKeyname); } CProfile CProfile::operator ()(LPCTSTR lpszAppname, LPCTSTR lpszKeyname) { return CProfile(*this, lpszAppname, lpszKeyname); } CProfile CProfile::operator ()(LPCTSTR lpszAppname, LPCTSTR lpszKeyname, LPCTSTR lpszDefault) { return CProfile(*this, lpszAppname, lpszKeyname, lpszDefault); } CProfile CProfile::operator ()(LPCTSTR lpszAppname, LPCTSTR lpszKeyname, LPCTSTR lpszDefault, LPCTSTR lpszRemark) { return CProfile(*this, lpszAppname, lpszKeyname, lpszDefault, lpszRemark); } int CProfile::Read(void* lpValue, const int nSize) { if (m_strKeyName.IsEmpty()) { m_strKeyName = m_strAppname; m_strAppname = _T("."); } if (m_strAppname.IsEmpty())m_strAppname = _T("."); if (m_strKeyName.IsEmpty())return 0; return getPrivateProfileStruct(m_strAppname, m_strKeyName, lpValue, nSize, m_strIniFile); } void CProfile::Write(void* lpValue, const int nSize) { if (m_strKeyName.IsEmpty()) { m_strKeyName = m_strAppname; m_strAppname = _T("."); } if (m_strAppname.IsEmpty())m_strAppname = _T("."); if (m_strKeyName.IsEmpty())return; writePrivateProfileStruct(m_strAppname, m_strKeyName, lpValue, nSize, m_strIniFile); } void CProfile::operator =(const int nValue) { if (m_strKeyName.IsEmpty()) { m_strKeyName = m_strAppname; m_strAppname = _T("."); } if (m_strAppname.IsEmpty())m_strAppname = _T("."); if (m_strKeyName.IsEmpty())return; std::xtstring strValue; strValue.Format(_T("%d"), nValue); writePrivateProfileString(m_strAppname, m_strKeyName, strValue, m_strIniFile); } void CProfile::operator =(const long long llValue) { if (m_strKeyName.IsEmpty()) { m_strKeyName = m_strAppname; m_strAppname = _T("."); } if (m_strAppname.IsEmpty())m_strAppname = _T("."); if (m_strKeyName.IsEmpty())return; std::xtstring strValue; strValue.Format(_T("%lld"), llValue); writePrivateProfileString(m_strAppname, m_strKeyName, strValue, m_strIniFile); } void CProfile::operator =(const double dValue) { if (m_strKeyName.IsEmpty()) { m_strKeyName = m_strAppname; m_strAppname = _T("."); } if (m_strAppname.IsEmpty())m_strAppname = _T("."); if (m_strKeyName.IsEmpty())return; std::xtstring strValue; strValue.Format(_T("%f"), dValue); writePrivateProfileString(m_strAppname, m_strKeyName, strValue, m_strIniFile); } void CProfile::operator=(const std::xtstring& strValue) { if (m_strKeyName.IsEmpty()) { m_strKeyName = m_strAppname; m_strAppname = _T("."); } if (m_strAppname.IsEmpty())m_strAppname = _T("."); if (m_strKeyName.IsEmpty())return; writePrivateProfileString(m_strAppname, m_strKeyName, strValue, m_strIniFile); } void CProfile::operator=(LPCTSTR lpszValue) { if (m_strKeyName.IsEmpty()) { m_strKeyName = m_strAppname; m_strAppname = _T("."); } if (m_strAppname.IsEmpty())m_strAppname = _T("."); if (m_strKeyName.IsEmpty())return; writePrivateProfileString(m_strAppname, m_strKeyName, lpszValue, m_strIniFile); } CProfile::operator short() { if (m_strKeyName.IsEmpty()) { m_strKeyName = m_strAppname; m_strAppname = _T("."); } if (m_strAppname.IsEmpty())m_strAppname = _T("."); if (m_strKeyName.IsEmpty())return 0; return (short)getPrivateProfileInt(m_strAppname, m_strKeyName, 0, m_strIniFile); } CProfile::operator int() { if (m_strKeyName.IsEmpty()) { m_strKeyName = m_strAppname; m_strAppname = _T("."); } if (m_strAppname.IsEmpty())m_strAppname = _T("."); if (m_strKeyName.IsEmpty())return 0; return getPrivateProfileInt(m_strAppname, m_strKeyName, 0, m_strIniFile); } CProfile::operator unsigned short() { if (m_strKeyName.IsEmpty()) { m_strKeyName = m_strAppname; m_strAppname = _T("."); } if (m_strAppname.IsEmpty())m_strAppname = _T("."); if (m_strKeyName.IsEmpty())return 0; return (unsigned short)getPrivateProfileInt(m_strAppname, m_strKeyName, 0, m_strIniFile); } CProfile::operator unsigned int() { if (m_strKeyName.IsEmpty()) { m_strKeyName = m_strAppname; m_strAppname = _T("."); } if (m_strAppname.IsEmpty())m_strAppname = _T("."); if (m_strKeyName.IsEmpty())return 0; return getPrivateProfileInt(m_strAppname, m_strKeyName, 0, m_strIniFile); } CProfile::operator long long() { if (m_strKeyName.IsEmpty()) { m_strKeyName = m_strAppname; m_strAppname = _T("."); } if (m_strAppname.IsEmpty())m_strAppname = _T("."); if (m_strKeyName.IsEmpty())return 0LL; std::xtstring strValue; getPrivateProfileString(m_strAppname, m_strKeyName, _T(""), strValue.GetBuffer(32), 32, m_strIniFile); strValue.ReleaseBuffer(); try{ return _ttoi64(strValue); } catch (...) { } return 0; } CProfile::operator double() { if (m_strKeyName.IsEmpty()) { m_strKeyName = m_strAppname; m_strAppname = _T("."); } if (m_strAppname.IsEmpty())m_strAppname = _T("."); if (m_strKeyName.IsEmpty())return 0; std::xtstring strValue; getPrivateProfileString(m_strAppname, m_strKeyName, _T(""), strValue.GetBuffer(32), 32, m_strIniFile); strValue.ReleaseBuffer(); try { return _tstof(strValue); } catch (...) { } return 0.0; } CProfile::operator LPCTSTR() { if (m_strKeyName.IsEmpty()) { m_strKeyName = m_strAppname; m_strAppname = _T("."); } if (m_strAppname.IsEmpty())m_strAppname = _T("."); if (m_strKeyName.IsEmpty())return _T(""); getPrivateProfileString(m_strAppname, m_strKeyName, _T(""), m_strValue.GetBuffer(1024), 1024, m_strIniFile); m_strValue.ReleaseBuffer(); return m_strValue; } bool CProfile::writePrivateProfileString(LPCTSTR lpAppName, LPCTSTR lpKeyName, LPCTSTR lpString, LPCTSTR lpFileName, LPCTSTR lpszRemark) { #ifdef WritePrivateProfileString1 return ::WritePrivateProfileString(lpAppName, lpKeyName, lpString, lpFileName) ? true : false; #else std::xstring<char> value(std::xstring<char>::convert(lpString)); return WriteIniFile(lpAppName, lpKeyName, value.c_str(), (int)value.length(), lpFileName, lpszRemark); #endif } unsigned int CProfile::getPrivateProfileString(LPCTSTR lpAppName, LPCTSTR lpKeyName, LPCTSTR lpDefault, LPTSTR lpReturnedString, unsigned int nSize, LPCTSTR lpFileName) { #ifdef GetPrivateProfileString1 return ::GetPrivateProfileString(lpAppName, lpKeyName, lpDefault, lpReturnedString, nSize, lpFileName); #else CSmartArr<char> saValue; int szValue(0); if (!ReadIniFile(lpAppName, lpKeyName, saValue, szValue, lpFileName)) { _tcscpy_s(lpReturnedString, nSize, lpDefault); return (unsigned int)_tcslen(lpDefault); } std::xtstring res(saValue.GetArr(), szValue); int count((int)res.length()); if (count > (int)nSize - 1) count = nSize - 1; _tcsncpy_s(lpReturnedString, nSize, res.c_str(), count); return count; #endif } unsigned int CProfile::getPrivateProfileInt(LPCTSTR lpAppName, LPCTSTR lpKeyName, int nDefault, LPCTSTR lpFileName) { #ifdef GetPrivateProfileInt1 return ::GetPrivateProfileInt(lpAppName, lpKeyName, nDefault, lpFileName); #else TCHAR szNumber[20]; if (getPrivateProfileString(lpAppName, lpKeyName, _T(""), szNumber, 20, lpFileName) < 1)return 0; return _ttoi(szNumber); #endif } bool CProfile::getPrivateProfileStruct(LPCTSTR lpszSection, LPCTSTR lpszKey, void* lpStruct, unsigned int uSizeStruct, LPCTSTR szFile) { #ifdef GetPrivateProfileStruct0 return ::GetPrivateProfileStruct(lpszSection, lpszKey, lpStruct, uSizeStruct, szFile) ? true : false; #else CSmartArr<char> saValue; int szValue(0); if (!ReadIniFile(lpszSection, lpszKey, saValue, szValue, szFile))return false; std::xtstring value(saValue.GetArr(), szValue); CByte byValue; byValue.fromBase64(value); byValue.GetData(lpStruct, (int)uSizeStruct); return true; #endif } bool CProfile::writePrivateProfileStruct(LPCTSTR lpszSection, LPCTSTR lpszKey, void* lpStruct, unsigned int uSizeStruct, LPCTSTR szFile) { #ifdef WritePrivateProfileStruct1 return ::WritePrivateProfileStruct(lpszSection, lpszKey, lpStruct, uSizeStruct, szFile) ? true : false; #else std::xtstring value(CByte::toBase64((CByte::BYTE*)lpStruct, uSizeStruct)); std::string str(value.toString()); return WriteIniFile(lpszSection, lpszKey, str.c_str(), (int)str.length(), szFile); #endif } bool CProfile::LoadIniFile(LPCSTR file, CSmartArr<char>& buf, int& len) { std::ifstream is(file, std::ios::in | std::ios::binary); if (!is.bad()) { is.seekg(0, std::ios::end); len = (int)is.tellg(); if (len > 0) { is.seekg(0, std::ios::beg); buf = new(std::nothrow) char[len * 2]; char* ptr(reinterpret_cast<char*>(buf.GetArr())); is.read(ptr, len); ptr[len] = '\0'; is.close(); return true; } } is.close(); std::ofstream os(file, std::ios::out); if (is.bad())return false; os.close(); len = 0; return true; } bool CProfile::ParseFile(LPCSTR section, LPCSTR key, char* buf, int& sec_s, int& sec_e, int& key_s, int& key_e, int& value_s, int& value_e) { if (buf == nullptr)return false; ASSERT(section != NULL && strlen(section)); ASSERT(key != NULL && strlen(key)); const char* p(buf); int i(0); sec_e = -1; sec_s = -1; key_e = -1; key_s = -1; value_s = -1; value_e = -1; while (p[i] != '\0') { if ((0 == i || (p[i - 1] == '\n' || p[i - 1] == 'r')) && (p[i] == '[')) { int section_start(i + 1); do { i++; } while((p[i] != ']') && (p[i] != '\0')); if (0 == strncmp(p + section_start, section, i-section_start)) { int newline_start(0); i++; while(isspace(p[i])) { i++; } sec_s = section_start; sec_e = i; while (!((p[i-1] == '\r' || p[i-1] == '\n') && (p[i] == '[')) && (p[i] != '\0') ) { int j(0); newline_start = i; while ((p[i] != '\r' && p[i] != '\n') && (p[i] != '\0')) { i++; } j = newline_start; if(';' != p[j]) { while(j < i && p[j] != '=') { j++; if('=' == p[j]) { if(strncmp(key, p + newline_start, j - newline_start) == 0) { key_s = newline_start; key_e = j-1; value_s = j+1; value_e = i; return true; } } } } i++; } } } else { i++; } } return false; } bool CProfile::ReadIniFile(LPCTSTR lpAppName, LPCTSTR lpKeyName, CSmartArr<char>& saData, int& szData, LPCTSTR lpFileName) { CSmartArr<char> buf; int len(0); std::xstring<char> fileName(std::xstring<char>::convert(lpFileName)); if (!LoadIniFile(fileName, buf, len))return false; int sec_s(-1); int sec_e(-1); int key_s(-1); int key_e(-1); int value_s(-1); int value_e(-1); std::xstring<char> appName(std::xstring<char>::convert(lpAppName)); std::xstring<char> keyName(std::xstring<char>::convert(lpKeyName)); if (!ParseFile(appName, keyName, buf, sec_s, sec_e, key_s, key_e, value_s, value_e))return false; int size(value_e - value_s); saData = new(std::nothrow) char[size + 1]; if (saData.GetArr() == NULL)return false; memcpy(saData, buf + value_s, size); saData[size] = '\0'; szData = value_e - value_s; return true; } bool CProfile::WriteIniFile(LPCTSTR lpszSection, LPCTSTR lpszKey, const void* lpData, unsigned int szData, LPCTSTR szFile, LPCTSTR szRemark) { CSmartArr<char> buf; int filesize(0); std::xstring<char> fileName(std::xstring<char>::convert(szFile)); if (!LoadIniFile(fileName, buf, filesize))return false; int sec_s(-1); int sec_e(-1); int key_s(-1); int key_e(-1); int value_s(-1); int value_e(-1); std::xstring<char> appName(std::xstring<char>::convert(lpszSection)); std::xstring<char> keyName(std::xstring<char>::convert(lpszKey)); ParseFile(appName, keyName, buf, sec_s, sec_e, key_s, key_e, value_s, value_e); try { std::ofstream os(fileName, std::ios::out | std::ios::binary | std::ios::trunc); if (sec_s == -1) { os.write(buf, filesize); if (filesize > 0)os << "\r\n"; os << "[" << appName << "]" << "\r\n"; if (szRemark != NULL && _tcslen(szRemark) > 0){ std::xstring<char> remark(szRemark); os << ";" << remark << "\r\n"; } os << keyName << "="; os.write((char*)lpData, szData); os << "\r\n"; } else if(key_s == -1) { os.write(buf, sec_e); if (szRemark != NULL && _tcslen(szRemark) > 0){ std::xstring<char> remark(szRemark); os << ";" << remark << "\r\n"; } os << keyName << "="; os.write((char*)lpData, szData); os << "\r\n"; os.write(buf + sec_e, filesize - sec_e); } else { os.write(buf, value_s); os.write((char*)lpData, szData); os.write(buf + value_e, filesize - value_e); } os.close(); return true; } catch (std::exception e){ return false; } }
33.966887
171
0.659388
yunsean
ecad377c4bb33c02980b43d57dfb348c63412371
1,949
cpp
C++
algorithms/cpp/Problems 901-1000/_934_ShortestBridge.cpp
shivamacs/LeetCode
f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a
[ "MIT" ]
null
null
null
algorithms/cpp/Problems 901-1000/_934_ShortestBridge.cpp
shivamacs/LeetCode
f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a
[ "MIT" ]
null
null
null
algorithms/cpp/Problems 901-1000/_934_ShortestBridge.cpp
shivamacs/LeetCode
f8f8b4e9872c47fbaaf9196c422f7e04986e6c3a
[ "MIT" ]
null
null
null
/* Source - https://leetcode.com/problems/shortest-bridge/ Author - Shivam Arora */ #include <bits/stdc++.h> using namespace std; struct Element { int x, y, d; Element(int a = -1, int b = -1, int c = -1) { x = a; y = b; d = c; } }; int xDir[4] = {1, 0, -1, 0}; int yDir[4] = {0, 1, 0, -1}; void dfs(int r, int c, vector<vector<int>>& A, queue<Element>& q) { A[r][c] = 2; q.push(Element(r, c, 0)); for(int k = 0; k < 4; k++) { int i = r + xDir[k], j = c + yDir[k]; if(i < 0 || i >= A.size() || j < 0 || j >= A.size() || A[i][j] != 1) continue; dfs(i, j, A, q); } } int shortestBridge(vector<vector<int>>& A) { int n = A.size(); queue<Element> q; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(A[i][j] == 1) { dfs(i, j, A, q); goto bfs; } } } bfs: while(!q.empty()) { Element front = q.front(); q.pop(); int r = front.x, c = front.y, flips = front.d; for(int k = 0; k < 4; k++) { int i = r + xDir[k], j = c + yDir[k]; if(i < 0 || i >= n || j < 0 || j >= n || A[i][j] == 2) continue; if(A[i][j] == 1) return flips; A[i][j] = 2; q.push(Element(i, j, flips + 1)); } } return 0; } int main() { int n; cout<<"Enter value of n (for array dimensions): "; cin>>n; vector<vector<int>> A(n, vector<int> (n)); cout<<"Enter values in array row-wise (0 or 1): "<<endl; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) cin>>A[i][j]; } cout<<"Smallest number of 0s to be flipped to connect the two islands: "<<shortestBridge(A)<<endl; }
22.402299
102
0.394048
shivamacs
ecad67077956783f7520353e5b75771a6c698c37
1,422
cpp
C++
third_party/spirv-tools/source/reduce/remove_function_reduction_opportunity.cpp
Alan-love/filament
87ee5783b7f72bb5b045d9334d719ea2de9f5247
[ "Apache-2.0" ]
1,570
2016-06-30T10:40:04.000Z
2022-03-31T01:47:33.000Z
source/reduce/remove_function_reduction_opportunity.cpp
indrarahul2013/SPIRV-Tools
636f449e1529a10d259eb7dc37d97192cf2820f8
[ "Apache-2.0" ]
132
2018-01-17T17:43:25.000Z
2020-09-01T07:41:17.000Z
source/reduce/remove_function_reduction_opportunity.cpp
indrarahul2013/SPIRV-Tools
636f449e1529a10d259eb7dc37d97192cf2820f8
[ "Apache-2.0" ]
253
2016-06-30T18:57:10.000Z
2022-03-25T03:57:40.000Z
// Copyright (c) 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "source/reduce/remove_function_reduction_opportunity.h" #include "source/opt/eliminate_dead_functions_util.h" namespace spvtools { namespace reduce { bool RemoveFunctionReductionOpportunity::PreconditionHolds() { // Removing one function cannot influence whether another function can be // removed. return true; } void RemoveFunctionReductionOpportunity::Apply() { for (opt::Module::iterator function_it = context_->module()->begin(); function_it != context_->module()->end(); ++function_it) { if (&*function_it == function_) { opt::eliminatedeadfunctionsutil::EliminateFunction(context_, &function_it); return; } } assert(0 && "Function to be removed was not found."); } } // namespace reduce } // namespace spvtools
33.857143
75
0.703938
Alan-love
ecb02ab8ad0b7187565edfbd3f234389c3873125
2,460
cpp
C++
acm/strStr.cpp
nkysg/Asenal
12444c7e50fae2be82d3c4737715a52e3693a3cd
[ "Apache-2.0" ]
5
2017-04-10T03:35:40.000Z
2020-11-26T10:00:57.000Z
acm/strStr.cpp
nkysg/Asenal
12444c7e50fae2be82d3c4737715a52e3693a3cd
[ "Apache-2.0" ]
1
2015-04-09T13:45:25.000Z
2015-04-09T13:45:25.000Z
acm/strStr.cpp
baotiao/Asenal
102170aa92ae72b1d589dd74e8bbbc9ae27a8d97
[ "Apache-2.0" ]
15
2015-03-10T04:15:10.000Z
2021-03-19T13:00:48.000Z
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<string> #include<cmath> #include<vector> #include<queue> #include<map> #include<ctime> #include<set> typedef long long lld; using namespace std; #ifdef DEBUG #define debug(x) cout<<__LINE__<<" "<<#x<<"="<<x<<endl; #else #define debug(x) #endif #define here cout<<"_______________here "<<endl; #define clr(NAME,VALUE) memset(NAME,VALUE,sizeof(NAME)) #define MAX 0x7f7f7f7f #define PRIME 999983 class Solution { public: int jump[160000]; void init_jump(char *needle) { jump[0] = -1; int k = -1; int hayLen = strlen(needle); int now = -1; for (int i = 1; i < hayLen; i++) { if (needle[jump[i - 1] + 1] == needle[i]) { jump[i] = jump[i - 1] + 1; } else { now = jump[i - 1]; while (now != -1 && needle[jump[now] + 1] != needle[i]) { now = jump[now]; } jump[i] = now; } } } char *match(char *haystack, char *needle) { int hayLen = strlen(haystack); int needLen = strlen(needle); int i = 0, j = 0; int now; while (i < hayLen && j < needLen) { if (haystack[i] == needle[j]) { i++; j++; } else { if (j == 0) { i++; } else { j = jump[j - 1] + 1; } } } if (j == needLen) { return haystack + i - needLen; } else { return NULL; } } char *strStr(char *haystack, char *needle) { if (haystack == NULL || needle == NULL) { return NULL; } int hayLen = strlen(haystack); int needLen = strlen(needle); if (needLen == 0) { return haystack; } if (hayLen == 0) { return NULL; } if (hayLen < needLen) { return NULL; } init_jump(needle); return match(haystack, needle); } }; int main() { #ifdef DEBUG freopen("a", "r", stdin); #endif int T; Solution s; char *haystack = "bbbbababbbaabbba"; char *needle = "abb"; //s.init_jump(needle); //s.match(haystack, needle); printf("%s\n", s.strStr(haystack, needle)); return 0; }
23.207547
73
0.460976
nkysg
ecb0b1904b41af755b79d53f07358f094b5b87c5
118,953
cpp
C++
applications/physbam/physbam-lib/Public_Library/PhysBAM_Dynamics/Level_Sets/PARTICLE_LEVELSET_UNIFORM.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
20
2017-07-03T19:09:09.000Z
2021-09-10T02:53:56.000Z
applications/physbam/physbam-lib/Public_Library/PhysBAM_Dynamics/Level_Sets/PARTICLE_LEVELSET_UNIFORM.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
null
null
null
applications/physbam/physbam-lib/Public_Library/PhysBAM_Dynamics/Level_Sets/PARTICLE_LEVELSET_UNIFORM.cpp
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
9
2017-09-17T02:05:06.000Z
2020-01-31T00:12:01.000Z
//##################################################################### // Copyright 2002-2007, Ronald Fedkiw, Eran Guendelman, Geoffrey Irving, Sergey Koltakov, Frank Losasso, Duc Nguyen, Nick Rasmussen, Avi Robinson-Mosher, Andrew Selle, Tamar Shinar, Jerry Talton. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### #include <PhysBAM_Tools/Arrays_Computations/HEAPIFY.h> #include <PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR_NODE.h> #include <PhysBAM_Tools/Grids_Uniform_Boundaries/BOUNDARY_UNIFORM.h> #include <PhysBAM_Tools/Math_Tools/pow.h> #include <PhysBAM_Tools/Parallel_Computation/DOMAIN_ITERATOR_THREADED.h> #include <PhysBAM_Tools/Parallel_Computation/MPI_UNIFORM_GRID.h> #include <PhysBAM_Geometry/Basic_Geometry/RAY.h> #include <PhysBAM_Geometry/Grids_Uniform_Collisions/GRID_BASED_COLLISION_GEOMETRY_UNIFORM.h> #include <PhysBAM_Geometry/Grids_Uniform_Interpolation_Collidable/LINEAR_INTERPOLATION_COLLIDABLE_FACE_UNIFORM.h> #include <PhysBAM_Geometry/Grids_Uniform_Level_Sets/FAST_LEVELSET.h> #include <PhysBAM_Geometry/Level_Sets/LEVELSET_UTILITIES.h> #include <PhysBAM_Dynamics/Level_Sets/LEVELSET_CALLBACKS.h> #include <PhysBAM_Dynamics/Level_Sets/PARTICLE_LEVELSET_UNIFORM.h> #include <PhysBAM_Dynamics/Level_Sets/VOF_ADVECTION.h> #include <PhysBAM_Dynamics/Parallel_Computation/MPI_UNIFORM_PARTICLES.h> #include <PhysBAM_Dynamics/Particles/PARTICLE_LEVELSET_PARTICLES.h> #include <PhysBAM_Dynamics/Particles/PARTICLE_LEVELSET_REMOVED_PARTICLES.h> #ifndef WIN32 #include <ext/atomicity.h> #endif using namespace PhysBAM; #ifndef WIN32 using namespace __gnu_cxx; #endif //##################################################################### // Constructor //##################################################################### template<class T_GRID> PARTICLE_LEVELSET_UNIFORM<T_GRID>:: PARTICLE_LEVELSET_UNIFORM(T_GRID& grid_input,T_ARRAYS_SCALAR& phi_input,const int number_of_ghost_cells_input) :PARTICLE_LEVELSET<T_GRID>(grid_input,phi_input,number_of_ghost_cells_input),mpi_grid(0),vof_advection(0),thread_queue(0) { #ifdef USE_PTHREADS pthread_mutex_init(&cell_lock,0); #endif } //##################################################################### // Destructor //##################################################################### template<class T_GRID> PARTICLE_LEVELSET_UNIFORM<T_GRID>:: ~PARTICLE_LEVELSET_UNIFORM() { #ifdef USE_PTHREADS pthread_mutex_destroy(&cell_lock); #endif delete vof_advection; for(NODE_ITERATOR iterator(levelset.grid,positive_particles.Domain_Indices());iterator.Valid();iterator.Next()) Delete_All_Particles_In_Cell(iterator.Node_Index()); } //##################################################################### // Function Consistency_Check //##################################################################### template<class T_GRID> template<class T_ARRAYS_PARTICLES> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Consistency_Check(RANGE<TV_INT> domain,T_ARRAYS_PARTICLES& particles) { // Remove consistency check for testing purposes. /* HASHTABLE<typename T_ARRAYS_PARTICLES::ELEMENT> hash; for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index(); typename T_ARRAYS_PARTICLES::ELEMENT cell_particles=particles(block); while(cell_particles){ assert(!hash.Contains(cell_particles));hash.Insert(cell_particles); assert(cell_particles->array_collection->Size()!=0); if(cell_particles->next)assert(cell_particles->array_collection->Size()==particle_pool.number_particles_per_cell); for(int k=1;k<=cell_particles->array_collection->Size();k++) assert(cell_particles->radius(k)>0); cell_particles=cell_particles->next;}} */ } //##################################################################### // Function Seed_Particles //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Seed_Particles(const T time,const bool verbose) { int n=Reseed_Add_Particles(negative_particles,positive_particles,-1,PARTICLE_LEVELSET_NEGATIVE,time,0); int p=0; if(!only_use_negative_particles){ p=Reseed_Add_Particles(positive_particles,negative_particles,1,PARTICLE_LEVELSET_POSITIVE,time,0);} if(verbose) {std::stringstream ss;ss<<n<<" negative particles and "<<p<<" positive particles"<<std::endl;LOG::filecout(ss.str());} } //##################################################################### // Function Attract_Individual_Particle_To_Interface //##################################################################### template<class T_GRID> bool PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Attract_Individual_Particle_To_Interface_And_Adjust_Radius(T_ARRAYS_PARTICLE_LEVELSET_PARTICLES& particles,PARTICLE_LEVELSET_PARTICLES<TV>& cell_particles,const T phi_min,const T phi_max,const BLOCK_UNIFORM<T_GRID>& block, const int index,const PARTICLE_LEVELSET_PARTICLE_TYPE particle_type,const T time,const bool delete_particles_that_leave_original_cell,RANDOM_NUMBERS<T>& local_random,ARRAY<ARRAY<TRIPLE<TV_INT,PARTICLE_LEVELSET_PARTICLES<TV>*,int> >,TV_INT>& list_to_process,const ARRAY<int,TV_INT>* domain_index) { T phi=levelset.Phi(cell_particles.X(index));bool inside=(phi>=phi_min && phi<=phi_max); TV_INT current_block_index=block.block_index; if(!inside){ T phi_goal=local_random.Get_Uniform_Number(phi_min,phi_max);TV X,N;int iteration=0; while(!inside && iteration<maximum_iterations_for_attraction){ N=levelset.Normal(cell_particles.X(index));T distance=phi_goal-phi,dt=1;bool inside_domain=false; while(!inside_domain && iteration<maximum_iterations_for_attraction){ X=cell_particles.X(index)+dt*distance*N; if(levelset.grid.Outside(X)){dt*=.5;iteration++;}else inside_domain=true;} if(!inside_domain) break; // ran out of iterations phi=levelset.Phi(X);inside=(phi>=phi_min && phi<=phi_max); if(!inside){ dt*=.5;iteration++;X=cell_particles.X(index)+dt*distance*N; phi=levelset.Phi(X);inside=(phi>=phi_min && phi<=phi_max);} cell_particles.X(index)=X;}} if(!inside){ assert(cell_particles.radius(index)>0); cell_particles.radius(index)=-1; return false;} else{ // TODO: the old collision aware code did not do this callback for fear that it would hamper collisions TV V_temp;levelset.levelset_callbacks->Adjust_Particle_For_Domain_Boundaries(cell_particles,index,V_temp,particle_type,0,time); if(levelset.collision_body_list) phi=levelset.Collision_Aware_Phi(cell_particles.X(index)); else phi=levelset.Phi(cell_particles.X(index)); if(phi<phi_min || phi>phi_max){ assert(cell_particles.radius(index)>0); cell_particles.radius(index)=-1; return false;} cell_particles.radius(index)=clamp(abs(phi),minimum_particle_radius,maximum_particle_radius); current_block_index=levelset.grid.Block_Index(cell_particles.X(index),1); if(delete_particles_that_leave_original_cell && block.block_index!=current_block_index){ assert(cell_particles.radius(index)>0); cell_particles.radius(index)=-1; return false;} //if(!particles(current_block_index)) particles(current_block_index)=Allocate_Particles(template_particles); //if(block.block_index!=current_block_index) Move_Particle(cell_particles,*particles(current_block_index),index); //move_particles(block.block_index).Append(TRIPLE<PARTICLE_LEVELSET_PARTICLES<TV>*,TV_INT,int>(&cell_particles,current_block_index,index)); list_to_process(current_block_index).Append(TRIPLE<TV_INT,PARTICLE_LEVELSET_PARTICLES<TV>*,int>(block.block_index,&cell_particles,index)); /*if(mutexes && thread_queue) pthread_mutex_lock(&(*mutexes)((*domain_index)(current_block_index))); if(!particles(current_block_index)) particles(current_block_index)=Allocate_Particles(template_particles); Copy_Particle(cell_particles,*particles(current_block_index),index); if(mutexes && thread_queue) pthread_mutex_unlock(&(*mutexes)((*domain_index)(current_block_index))); assert(cell_particles.radius(index)>0); cell_particles.radius(index)=-1;*/ return true;} } //##################################################################### // Function Adjust_Particle_Radii //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Adjust_Particle_Radii() { RANGE<TV_INT> domain(levelset.grid.Domain_Indices());domain.max_corner+=TV_INT::All_Ones_Vector(); Consistency_Check(domain,positive_particles); Consistency_Check(domain,negative_particles); DOMAIN_ITERATOR_THREADED_ALPHA<PARTICLE_LEVELSET_UNIFORM<T_GRID>,TV>(domain,thread_queue).Run(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Adjust_Particle_Radii_Threaded); Consistency_Check(domain,positive_particles); Consistency_Check(domain,negative_particles); } //##################################################################### // Function Adjust_Particle_Radii //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Adjust_Particle_Radii_Threaded(RANGE<TV_INT>& domain) { for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index(); if(negative_particles(block)) Adjust_Particle_Radii(BLOCK_UNIFORM<T_GRID>(levelset.grid,block),*negative_particles(block),-1);} for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index(); if(positive_particles(block)) Adjust_Particle_Radii(BLOCK_UNIFORM<T_GRID>(levelset.grid,block),*positive_particles(block),1);} } //##################################################################### // Function Adjust_Particle_Radii //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Adjust_Particle_Radii(const BLOCK_UNIFORM<T_GRID>& block,PARTICLE_LEVELSET_PARTICLES<TV>& particles,const int sign) { bool near_objects=levelset.collision_body_list?levelset.collision_body_list->Occupied_Block(block):false;if(near_objects) levelset.Enable_Collision_Aware_Interpolation(sign); // new radius is negative if the particle is on the wrong side of the interface PARTICLE_LEVELSET_PARTICLES<TV>* cell_particles=&particles; while(cell_particles){ if(sign==1) for(int k=1;k<=cell_particles->array_collection->Size();k++)cell_particles->radius(k)=max(minimum_particle_radius,min(maximum_particle_radius,levelset.Phi(particles.X(k)))); else for(int k=1;k<=cell_particles->array_collection->Size();k++)cell_particles->radius(k)=max(minimum_particle_radius,min(maximum_particle_radius,-levelset.Phi(particles.X(k)))); cell_particles=cell_particles->next;} if(near_objects) levelset.Disable_Collision_Aware_Interpolation(); } //##################################################################### // Function Modify_Levelset_Using_Escaped_Particles //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Modify_Levelset_Using_Escaped_Particles(T_FACE_ARRAYS_SCALAR* V,ARRAY<T_ARRAYS_PARTICLE_LEVELSET_PARTICLES*>* other_positive_particles) { if(bias_towards_negative_particles){ if(other_positive_particles)for(int i=1;i<=other_positive_particles->m;i++)Modify_Levelset_Using_Escaped_Particles(levelset.phi,*(*other_positive_particles)(i),0,1); Modify_Levelset_Using_Escaped_Particles(levelset.phi,positive_particles,0,1);Modify_Levelset_Using_Escaped_Particles(levelset.phi,negative_particles,0,-1); if(reincorporate_removed_particles_everywhere) Modify_Levelset_Using_Escaped_Particles(levelset.phi,removed_negative_particles,V,-1);} else{ T_ARRAYS_SCALAR phi_minus(levelset.phi),phi_plus(levelset.phi); Modify_Levelset_Using_Escaped_Particles(phi_minus,negative_particles,0,-1);Modify_Levelset_Using_Escaped_Particles(phi_plus,positive_particles,0,1); if(other_positive_particles)for(int i=1;i<=other_positive_particles->m;i++)Modify_Levelset_Using_Escaped_Particles(phi_plus,*(*other_positive_particles)(i),0,1); if(reincorporate_removed_particles_everywhere) Modify_Levelset_Using_Escaped_Particles(phi_minus,removed_negative_particles,V,-1); for(CELL_ITERATOR iterator(levelset.grid);iterator.Valid();iterator.Next()){TV_INT cell=iterator.Cell_Index();levelset.phi(cell)=minmag(phi_minus(cell),phi_plus(cell));}} } //##################################################################### // Function Modify_Levelset_Using_Escaped_Particles //##################################################################### template<class T_GRID> template<class T_ARRAYS_PARTICLES> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Modify_Levelset_Using_Escaped_Particles(T_ARRAYS_SCALAR& phi,T_ARRAYS_PARTICLES& particles,T_FACE_ARRAYS_SCALAR* V,const int sign) { T one_over_radius_multiplier=-sign/outside_particle_distance_multiplier; RANGE<TV_INT> domain(levelset.grid.Domain_Indices());domain.max_corner+=TV_INT::All_Ones_Vector(); Consistency_Check(domain,particles); DOMAIN_ITERATOR_THREADED_ALPHA<PARTICLE_LEVELSET_UNIFORM<T_GRID>,TV>(levelset.grid.Domain_Indices(),thread_queue).template Run<T_ARRAYS_SCALAR&,T_ARRAYS_PARTICLES&,T_FACE_ARRAYS_SCALAR*,int,T>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Modify_Levelset_Using_Escaped_Particles_Threaded,phi,particles,V,sign,one_over_radius_multiplier); Consistency_Check(domain,particles); } //##################################################################### // Function Modify_Levelset_Using_Escaped_Particles //##################################################################### template<class T_GRID> template<class T_ARRAYS_PARTICLES> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Modify_Levelset_Using_Escaped_Particles_Threaded(RANGE<TV_INT>& domain,T_ARRAYS_SCALAR& phi,T_ARRAYS_PARTICLES& particles,T_FACE_ARRAYS_SCALAR* V,const int sign,const T one_over_radius_multiplier) { RANGE<TV_INT> range_domain(domain);range_domain.max_corner+=TV_INT::All_Ones_Vector(); for(NODE_ITERATOR iterator(levelset.grid,range_domain);iterator.Valid();iterator.Next()){TV_INT block_index=iterator.Node_Index();if(particles(block_index)){ typename T_ARRAYS_PARTICLES::ELEMENT cell_particles=particles(block_index); BLOCK_UNIFORM<T_GRID> block(levelset.grid,block_index); bool near_objects=levelset.collision_body_list?levelset.collision_body_list->Occupied_Block(block):false;if(near_objects) levelset.Enable_Collision_Aware_Interpolation(sign); while(cell_particles){for(int k=1;k<=cell_particles->array_collection->Size();k++)if(one_over_radius_multiplier*levelset.Phi(cell_particles->X(k))>cell_particles->radius(k)){ for(int cell_index=0;cell_index<T_GRID::number_of_cells_per_block;cell_index++){TV_INT cell=block.Cell(cell_index);if(!domain.Lazy_Inside(cell)) continue; T radius_minus_sign_phi=cell_particles->radius(k)-sign*phi(cell); if(radius_minus_sign_phi>0){TV center=levelset.grid.Center(cell); T distance_squared=(center-cell_particles->X(k)).Magnitude_Squared(); if(distance_squared<sqr(radius_minus_sign_phi)){ static COLLISION_GEOMETRY_ID body_id;static int aggregate_id;static TV intersection_point; if(near_objects && levelset.collision_body_list->collision_geometry_collection.Intersection_Between_Points(center,cell_particles->X(k),body_id,aggregate_id,intersection_point)) continue; phi(cell)=sign*(cell_particles->radius(k)-sqrt(distance_squared)); /*if(V) (*V)(ii,jj,iijj)=cell_particles.V(k);*/}}}} cell_particles=cell_particles->next;} if(near_objects) levelset.Disable_Collision_Aware_Interpolation();}} } //##################################################################### // Function Update_Particles_To_Reflect_Mass_Conservation //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Update_Particles_To_Reflect_Mass_Conservation(T_ARRAYS_SCALAR& phi_old,const bool update_particle_cells,const bool verbose) { T_FAST_LEVELSET levelset_old(levelset.grid,phi_old); Update_Particles_To_Reflect_Mass_Conservation(levelset_old,negative_particles,PARTICLE_LEVELSET_NEGATIVE,update_particle_cells,verbose); Update_Particles_To_Reflect_Mass_Conservation(levelset_old,positive_particles,PARTICLE_LEVELSET_POSITIVE,update_particle_cells,verbose); Adjust_Particle_Radii(); } //##################################################################### // Function Update_Particles_To_Reflect_Mass_Conservation //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Update_Particles_To_Reflect_Mass_Conservation(const T_FAST_LEVELSET& levelset_old,T_ARRAYS_PARTICLE_LEVELSET_PARTICLES& particles, const PARTICLE_LEVELSET_PARTICLE_TYPE particle_type,const bool update_particle_cells,const bool verbose) { const int maximum_iterations=5; const T epsilon=levelset_old.grid.Minimum_Edge_Length()*(T)1e-2; for(NODE_ITERATOR iterator(levelset.grid);iterator.Valid();iterator.Next()){TV_INT block_index=iterator.Node_Index();if(particles(block_index)){ PARTICLE_LEVELSET_PARTICLES<TV>* cell_particles=particles(block_index); BLOCK_UNIFORM<T_GRID> block(levelset.grid,block_index); while(cell_particles){for(int k=cell_particles->array_collection->Size();k>=1;k--){ TV X_new=cell_particles->X(k); T phi_old=levelset_old.Phi(X_new); T phi_new=levelset.Phi(X_new); int iterations=0; while(abs(phi_old-phi_new)>epsilon && iterations<maximum_iterations){ // figure out how much phi has changed at this point, step that far in the normal direction TV normal=levelset.Normal(cell_particles->X(k)); TV destination_normal=levelset.Normal(cell_particles->X(k)+(phi_old-phi_new)*normal); X_new+=(T).5*(phi_old-phi_new)*(normal+destination_normal).Normalized(); // half TV velocity=X_new-cell_particles->X(k); levelset.levelset_callbacks->Adjust_Particle_For_Domain_Boundaries(*cell_particles,k,velocity,particle_type,1/*=dt*/,0); cell_particles->X(k)+=velocity; phi_new=levelset.Phi(X_new); X_new=cell_particles->X(k); iterations++;}} cell_particles=cell_particles->next;}}} if(update_particle_cells) Update_Particle_Cells(particles); } //##################################################################### // Function Euler_Step_Particles //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Euler_Step_Particles(const T_FACE_ARRAYS_SCALAR& V,const T dt,const T time,const bool use_second_order_for_nonremoved_particles,const bool update_particle_cells_after_euler_step, const bool verbose,const bool analytic_test,const bool default_to_forward_euler_outside) { if(use_second_order_for_nonremoved_particles){ Second_Order_Runge_Kutta_Step_Particles(V,negative_particles,PARTICLE_LEVELSET_NEGATIVE,dt,time,update_particle_cells_after_euler_step,verbose,default_to_forward_euler_outside); Second_Order_Runge_Kutta_Step_Particles(V,positive_particles,PARTICLE_LEVELSET_POSITIVE,dt,time,update_particle_cells_after_euler_step,verbose,default_to_forward_euler_outside);} else{ Euler_Step_Particles(V,negative_particles,PARTICLE_LEVELSET_NEGATIVE,dt,time,update_particle_cells_after_euler_step); Euler_Step_Particles(V,positive_particles,PARTICLE_LEVELSET_POSITIVE,dt,time,update_particle_cells_after_euler_step);} if(analytic_test){ Second_Order_Runge_Kutta_Step_Particles(V,removed_negative_particles,PARTICLE_LEVELSET_NEGATIVE,dt,time,update_particle_cells_after_euler_step,default_to_forward_euler_outside); Second_Order_Runge_Kutta_Step_Particles(V,removed_positive_particles,PARTICLE_LEVELSET_POSITIVE,dt,time,update_particle_cells_after_euler_step,default_to_forward_euler_outside);} else Euler_Step_Removed_Particles(dt,time,update_particle_cells_after_euler_step,verbose); } //##################################################################### // Function Euler_Step_Removed_Particles //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Euler_Step_Removed_Particles(const T dt,const T time,const bool update_particle_cells_after_euler_step,const bool verbose) { if(use_removed_negative_particles) Euler_Step_Removed_Particles(removed_negative_particles,PARTICLE_LEVELSET_REMOVED_NEGATIVE,dt,time,update_particle_cells_after_euler_step,verbose); if(use_removed_positive_particles) Euler_Step_Removed_Particles(removed_positive_particles,PARTICLE_LEVELSET_REMOVED_POSITIVE,dt,time,update_particle_cells_after_euler_step,verbose); } //##################################################################### // Function Euler_Step_Removed_Particles //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Euler_Step_Removed_Particles(T_ARRAYS_PARTICLE_LEVELSET_REMOVED_PARTICLES& particles,const PARTICLE_LEVELSET_PARTICLE_TYPE particle_type,const T dt,const T time, const bool update_particle_cells_after_euler_step,const bool verbose) { int number_of_deleted_particles=0,number_of_non_occupied_cells=0; for(NODE_ITERATOR iterator(levelset.grid);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index();if(particles(block)){ PARTICLE_LEVELSET_REMOVED_PARTICLES<TV>& cell_particles=*particles(block); if(!levelset.collision_body_list->Swept_Occupied_Block(T_BLOCK(levelset.grid,block))){ number_of_non_occupied_cells++; for(int k=cell_particles.array_collection->Size();k>=1;k--) // since not an occupied block, don't need to adjust for objects levelset.levelset_callbacks->Adjust_Particle_For_Domain_Boundaries(cell_particles,k,cell_particles.V(k),particle_type,dt,time);} else{ for(int k=cell_particles.array_collection->Size();k>=1;k--){ levelset.levelset_callbacks->Adjust_Particle_For_Domain_Boundaries(cell_particles,k,cell_particles.V(k),particle_type,dt,time); T collision_distance=Particle_Collision_Distance(cell_particles.quantized_collision_distance(k)); if(!Adjust_Particle_For_Objects(cell_particles.X(k),cell_particles.V(k),cell_particles.radius(k),collision_distance,particle_type,dt,time)){ Delete_Particle_And_Clean_Memory(particles(block),cell_particles,k);number_of_deleted_particles++;}}} cell_particles.Euler_Step_Position(dt); if(!cell_particles.array_collection->Size()) Free_Particle_And_Clear_Pointer(particles(block));}} if(verbose){ std::stringstream ss; if(number_of_deleted_particles) ss<<"Deleted "<<number_of_deleted_particles<<" "<<PARTICLE_LEVELSET<T_GRID>::Particle_Type_Name(particle_type)<<" due to crossover"<<std::endl; if(number_of_non_occupied_cells) ss<<"Skipped "<<number_of_non_occupied_cells<<" non occupied cells"<<std::endl; LOG::filecout(ss.str());} if(update_particle_cells_after_euler_step) Update_Particle_Cells(particles); } //##################################################################### // Function Euler_Step_Particles //##################################################################### template<class T_GRID> template<class T_ARRAYS_PARTICLES> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Euler_Step_Particles_Wrapper(const T_FACE_ARRAYS_SCALAR& V,T_ARRAYS_PARTICLES& particles,const PARTICLE_LEVELSET_PARTICLE_TYPE particle_type,const T dt,const T time, const bool update_particle_cells_after_euler_step,const bool assume_particles_in_correct_blocks,const bool enforce_domain_boundaries) { T_FACE_ARRAYS_SCALAR face_velocities_ghost;face_velocities_ghost.Resize(levelset.grid,number_of_ghost_cells,false); levelset.boundary->Fill_Ghost_Cells_Face(levelset.grid,V,face_velocities_ghost,time,number_of_ghost_cells); Euler_Step_Particles(face_velocities_ghost,particles,particle_type,dt,time,update_particle_cells_after_euler_step,assume_particles_in_correct_blocks,enforce_domain_boundaries); } //##################################################################### // Function Euler_Step_Particles //##################################################################### template<class T_GRID> template<class T_ARRAYS_PARTICLES> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Euler_Step_Particles(const T_FACE_ARRAYS_SCALAR& V,T_ARRAYS_PARTICLES& particles,const PARTICLE_LEVELSET_PARTICLE_TYPE particle_type,const T dt,const T time, const bool update_particle_cells_after_euler_step,const bool assume_particles_in_correct_blocks,const bool enforce_domain_boundaries) { RANGE<TV_INT> domain(levelset.grid.Domain_Indices());domain.max_corner+=TV_INT::All_Ones_Vector(); Consistency_Check(domain,particles); DOMAIN_ITERATOR_THREADED_ALPHA<PARTICLE_LEVELSET_UNIFORM<T_GRID>,TV>(domain,thread_queue).template Run<const T_FACE_ARRAYS_SCALAR&,T_ARRAYS_PARTICLES&,PARTICLE_LEVELSET_PARTICLE_TYPE,T,T,bool,bool>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Euler_Step_Particles_Threaded,V,particles,particle_type,dt,time,assume_particles_in_correct_blocks,enforce_domain_boundaries); Consistency_Check(domain,particles); if(update_particle_cells_after_euler_step) Update_Particle_Cells(particles); Consistency_Check(domain,particles); } //##################################################################### // Function Euler_Step_Particles //##################################################################### template<class T_GRID> template<class T_ARRAYS_PARTICLES> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Euler_Step_Particles_Threaded(RANGE<TV_INT>& domain,const T_FACE_ARRAYS_SCALAR& V,T_ARRAYS_PARTICLES& particles,const PARTICLE_LEVELSET_PARTICLE_TYPE particle_type,const T dt,const T time, const bool assume_particles_in_correct_blocks,const bool enforce_domain_boundaries) { if(assume_particles_in_correct_blocks){ for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index();if(particles(block)){ // TODO: optimize using slope precomputation typename T_ARRAYS_PARTICLES::ELEMENT cell_particles=particles(block); T_LINEAR_INTERPOLATION_MAC_HELPER linear_interpolation_mac_helper(BLOCK_UNIFORM<T_GRID>(levelset.grid,block),V); while(cell_particles){for(int k=1;k<=cell_particles->array_collection->Size();k++){ TV velocity=linear_interpolation_mac_helper.Interpolate_Face(cell_particles->X(k)); if(enforce_domain_boundaries) levelset.levelset_callbacks->Adjust_Particle_For_Domain_Boundaries(*cell_particles,k,velocity,particle_type,dt,time); T collision_distance=Particle_Collision_Distance(cell_particles->quantized_collision_distance(k)); Adjust_Particle_For_Objects(cell_particles->X(k),velocity,cell_particles->radius(k),collision_distance,particle_type,dt,time); cell_particles->X(k)+=dt*velocity;} cell_particles=cell_particles->next;}}}} else{ T_LINEAR_INTERPOLATION_SCALAR linear_interpolation;T_FACE_LOOKUP V_lookup(V); for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index();if(particles(block)){ typename T_ARRAYS_PARTICLES::ELEMENT cell_particles=particles(block); while(cell_particles){for(int k=1;k<=cell_particles->array_collection->Size();k++){ TV velocity=linear_interpolation.Clamped_To_Array_Face(levelset.grid,V_lookup,cell_particles->X(k)); if(enforce_domain_boundaries) levelset.levelset_callbacks->Adjust_Particle_For_Domain_Boundaries(*cell_particles,k,velocity,particle_type,dt,time); T collision_distance=Particle_Collision_Distance(cell_particles->quantized_collision_distance(k)); Adjust_Particle_For_Objects(cell_particles->X(k),velocity,cell_particles->radius(k),collision_distance,particle_type,dt,time); cell_particles->X(k)+=dt*velocity;} cell_particles=cell_particles->next;}}}} } //##################################################################### // Function Second_Order_Runge_Kutta_Step_Particles //##################################################################### template<class T_GRID> template<class T_ARRAYS_PARTICLES> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Second_Order_Runge_Kutta_Step_Particles(const T_FACE_ARRAYS_SCALAR& V,T_ARRAYS_PARTICLES& particles,const PARTICLE_LEVELSET_PARTICLE_TYPE particle_type,const T dt,const T time, const bool update_particle_cells_after_euler_step,const bool verbose,const bool default_to_forward_euler_outside) { RANGE<TV_INT> domain(levelset.grid.Domain_Indices());domain.max_corner+=TV_INT::All_Ones_Vector(); Consistency_Check(domain,particles); DOMAIN_ITERATOR_THREADED_ALPHA<PARTICLE_LEVELSET_UNIFORM<T_GRID>,TV>(domain,thread_queue).template Run<const T_FACE_ARRAYS_SCALAR&,T_ARRAYS_PARTICLES&,const PARTICLE_LEVELSET_PARTICLE_TYPE,T,T,bool,bool>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Second_Order_Runge_Kutta_Step_Particles_Threaded,V,particles,particle_type,dt,time,verbose,default_to_forward_euler_outside); Consistency_Check(domain,particles); if(update_particle_cells_after_euler_step) Update_Particle_Cells(particles); Consistency_Check(domain,particles); } //##################################################################### // Function Second_Order_Runge_Kutta_Step_Particles //##################################################################### template<class T_GRID> template<class T_ARRAYS_PARTICLES> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Second_Order_Runge_Kutta_Step_Particles_Threaded(RANGE<TV_INT>& domain,const T_FACE_ARRAYS_SCALAR& V,T_ARRAYS_PARTICLES& particles,const PARTICLE_LEVELSET_PARTICLE_TYPE particle_type,const T dt,const T time,const bool verbose,const bool default_to_forward_euler_outside) { T_FACE_LOOKUP V_lookup(V); T_FACE_LOOKUP_COLLIDABLE V_lookup_collidable(V_lookup,*levelset.collision_body_list,levelset.face_velocities_valid_mask_current); typename T_FACE_LOOKUP_COLLIDABLE::LOOKUP V_lookup_collidable_lookup(V_lookup_collidable,V_lookup); T_LINEAR_INTERPOLATION_SCALAR linear_interpolation; // use for second step since particle may not be in initial block T_LINEAR_INTERPOLATION_COLLIDABLE_FACE_SCALAR linear_interpolation_collidable; COLLISION_GEOMETRY_ID body_id;int aggregate_id;T start_phi,end_phi;TV body_normal,body_velocity;int number_of_deleted_particles=0,number_of_non_occupied_cells=0,number_of_occupied_cells=0; T_ARRAYS_SCALAR phi_ghost; if(default_to_forward_euler_outside){ phi_ghost.Resize(levelset.grid.Domain_Indices(number_of_ghost_cells)); levelset.boundary->Fill_Ghost_Cells(levelset.grid,levelset.phi,phi_ghost,dt,time,number_of_ghost_cells);} const T one_over_dt=1/dt; int max_particles=0; for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block_index=iterator.Node_Index();if(particles(block_index)){ typename T_ARRAYS_PARTICLES::ELEMENT cell_particles=particles(block_index); max_particles=max(max_particles,cell_particles->array_collection->Size()); BLOCK_UNIFORM<T_GRID> block(levelset.grid,block_index); while(cell_particles){ if(!levelset.collision_body_list || !levelset.collision_body_list->Swept_Occupied_Block(block)){ // not occupied, so advect ignoring objects number_of_non_occupied_cells++; T_LINEAR_INTERPOLATION_MAC_HELPER linear_interpolation_mac_helper(block,V); for(int k=1;k<=cell_particles->array_collection->Size();k++){ TV velocity=linear_interpolation_mac_helper.Interpolate_Face(cell_particles->X(k)); TV X_new=cell_particles->X(k)+dt*velocity; if(default_to_forward_euler_outside){ T phi_X_new=linear_interpolation.Clamped_To_Array(levelset.grid,phi_ghost,X_new); if(phi_X_new<3.0*levelset.grid.min_dX){ velocity=(T).5*(velocity+linear_interpolation.Clamped_To_Array_Face(levelset.grid,V_lookup,X_new));}} else{ velocity=(T).5*(velocity+linear_interpolation.Clamped_To_Array_Face(levelset.grid,V_lookup,X_new));} levelset.levelset_callbacks->Adjust_Particle_For_Domain_Boundaries(*cell_particles,k,velocity,particle_type,dt,time); cell_particles->X(k)+=dt*velocity;}} else{ // collision aware advection number_of_occupied_cells++; for(int k=cell_particles->array_collection->Size();k>=1;k--){ T collision_distance=Particle_Collision_Distance(cell_particles->quantized_collision_distance(k)); // first push particle out if(particle_type==PARTICLE_LEVELSET_NEGATIVE){bool particle_crossover; if(levelset.collision_body_list->Push_Out_Point(cell_particles->X(k),collision_distance,true,particle_crossover)&&particle_crossover){ Delete_Particle_And_Clean_Memory(particles(block_index),*cell_particles,k);number_of_deleted_particles++;continue;}} // delete due to crossover in push out // TODO: optimize by calling From_Base_Node (or something like that) since we know what cell we're in TV velocity=linear_interpolation_collidable.Clamped_To_Array_Face(levelset.grid,V_lookup_collidable_lookup,cell_particles->X(k)); // adjust normal component of velocity to not move into nearest body bool got_interaction_with_body=false; if(particle_type==PARTICLE_LEVELSET_NEGATIVE) got_interaction_with_body=levelset.collision_body_list->Get_Body_Penetration(cell_particles->X(k),cell_particles->X(k),collision_distance,dt,body_id,aggregate_id, start_phi,end_phi,body_normal,body_velocity); if(got_interaction_with_body){ T relative_normal_velocity=TV::Dot_Product(velocity-body_velocity,body_normal); if(relative_normal_velocity<0) velocity-=relative_normal_velocity*body_normal;} // compute position using velocity but clamp if intersects any body TV X_new=cell_particles->X(k)+dt*velocity; RAY<TV> ray; if(RAY<TV>::Create_Non_Degenerate_Ray(cell_particles->X(k),X_new-cell_particles->X(k),ray) && levelset.collision_body_list->Closest_Non_Intersecting_Point_Of_Any_Body(ray,body_id)) X_new=ray.Point(ray.t_max); // get average velocity if(default_to_forward_euler_outside){ T phi_X_new=linear_interpolation.Clamped_To_Array(levelset.grid,phi_ghost,X_new); if(phi_X_new<3.0*levelset.grid.min_dX){ velocity=(T).5*(velocity+linear_interpolation_collidable.Clamped_To_Array_Face(levelset.grid,V_lookup_collidable_lookup,X_new));}} else{ velocity=(T).5*(velocity+linear_interpolation_collidable.Clamped_To_Array_Face(levelset.grid,V_lookup_collidable_lookup,X_new));} // adjust normal component of velocity again if(got_interaction_with_body){ T relative_normal_velocity=TV::Dot_Product(velocity-body_velocity,body_normal); if(relative_normal_velocity<0) velocity-=relative_normal_velocity*body_normal;} levelset.levelset_callbacks->Adjust_Particle_For_Domain_Boundaries(*cell_particles,k,velocity,particle_type,dt,time); velocity=(X_new-cell_particles->X(k))*one_over_dt; if(!Adjust_Particle_For_Objects(cell_particles->X(k),velocity,cell_particles->radius(k),collision_distance,particle_type,dt,time)){ Delete_Particle_And_Clean_Memory(particles(block_index),*cell_particles,k);number_of_deleted_particles++;} else cell_particles->X(k)+=dt*velocity;}} cell_particles=cell_particles->next;} if(particles(block_index)->array_collection->Size()==0) Free_Particle_And_Clear_Pointer(particles(block_index)); }} if(verbose){ std::stringstream ss; ss<<"max_particles_per_cell "<<max_particles<<std::endl; if(number_of_deleted_particles) ss<<"Deleted "<<number_of_deleted_particles<<" "<<PARTICLE_LEVELSET<T_GRID>::Particle_Type_Name(particle_type)<<" due to crossover"<<std::endl; if(number_of_non_occupied_cells) ss<<number_of_occupied_cells<<" occupied_cells "<<", "<<number_of_non_occupied_cells<<" non occupied cells"<<std::endl; LOG::filecout(ss.str());} } //##################################################################### // Function Update_Particle_Cells //##################################################################### template<class T_GRID> template<class T_ARRAYS_PARTICLES> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Update_Particle_Cells(T_ARRAYS_PARTICLES& particles) { typedef typename REMOVE_POINTER<typename T_ARRAYS_PARTICLES::ELEMENT>::TYPE T_PARTICLES; const T_PARTICLES& template_particles=choice<(2-IS_SAME<T_PARTICLES,PARTICLE_LEVELSET_PARTICLES<TV> >::value)>(this->template_particles,this->template_removed_particles); RANGE<TV_INT> domain(levelset.grid.Domain_Indices());domain.max_corner+=TV_INT::All_Ones_Vector(); Consistency_Check(domain,particles); if(mpi_grid){ Exchange_Boundary_Particles(*mpi_grid,template_particles,particles,(int)(cfl_number+(T)1.5),*this);} Consistency_Check(domain,particles); if(thread_queue){ DOMAIN_ITERATOR_THREADED_ALPHA<PARTICLE_LEVELSET_UNIFORM<T_GRID>,TV> threaded_iterator(domain,thread_queue); ARRAY<ARRAY<int>,TV_INT> number_of_particles_per_block(levelset.grid.Block_Indices()); threaded_iterator.template Run<T_ARRAYS_PARTICLES&,ARRAY<ARRAY<int>,TV_INT>&>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Update_Particle_Cells_Part_One_Threaded,particles,number_of_particles_per_block); ARRAY<int,TV_INT> domain_index(domain.Thickened(1)); for(int i=1;i<=threaded_iterator.domains.m;i++) for(NODE_ITERATOR iterator(levelset.grid,threaded_iterator.domains(i));iterator.Valid();iterator.Next()) domain_index(iterator.Node_Index())=i; // TODO: thread ARRAY<ARRAY<TRIPLE<TV_INT,T_PARTICLES*,int> >,TV_INT> list_to_process(domain.Thickened(1)); Update_Particle_Cells_Find_List(domain,particles,number_of_particles_per_block,list_to_process); //This can not be threaded and be deterministic threaded_iterator.template Run<T_ARRAYS_PARTICLES&,const ARRAY<ARRAY<int>,TV_INT>&,ARRAY<ARRAY<TRIPLE<TV_INT,T_PARTICLES*,int> >,TV_INT>&,const ARRAY<int,TV_INT>*>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Update_Particle_Cells_Part_Two_Threaded,particles,number_of_particles_per_block,list_to_process,&domain_index); threaded_iterator.template Run<T_ARRAYS_PARTICLES&,const ARRAY<ARRAY<int>,TV_INT>&,ARRAY<ARRAY<TRIPLE<TV_INT,T_PARTICLES*,int> >,TV_INT>&,const ARRAY<int,TV_INT>*>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Update_Particle_Cells_Part_Three_Threaded,particles,number_of_particles_per_block,list_to_process,&domain_index); threaded_iterator.template Run<T_ARRAYS_PARTICLES&>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Delete_Marked_Particles,particles);} else{ ARRAY<ARRAY<int>,TV_INT> number_of_particles_per_block(levelset.grid.Block_Indices()); ARRAY<ARRAY<TRIPLE<TV_INT,T_PARTICLES*,int> >,TV_INT> list_to_process(domain.Thickened(1)); Update_Particle_Cells_Part_One_Threaded(domain,particles,number_of_particles_per_block); Update_Particle_Cells_Find_List(domain,particles,number_of_particles_per_block,list_to_process); Update_Particle_Cells_Part_Two_Threaded(domain,particles,number_of_particles_per_block,list_to_process,0); Update_Particle_Cells_Part_Three_Threaded(domain,particles,number_of_particles_per_block,list_to_process,0); Delete_Marked_Particles(domain,particles);} Consistency_Check(domain,particles); } //##################################################################### // Function Update_Particle_Cells_Threaded //##################################################################### template<class T_GRID> template<class T_ARRAYS_PARTICLES> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Update_Particle_Cells_Part_One_Threaded(RANGE<TV_INT>& domain,T_ARRAYS_PARTICLES& particles,ARRAY<ARRAY<int>,TV_INT>& number_of_particles_per_block) { typedef typename REMOVE_POINTER<typename T_ARRAYS_PARTICLES::ELEMENT>::TYPE T_PARTICLES; for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index(); typename T_ARRAYS_PARTICLES::ELEMENT cell_particles=particles(block); while(cell_particles){number_of_particles_per_block(block).Append(cell_particles->array_collection->Size());cell_particles=cell_particles->next;}} } //##################################################################### // Function Update_Particle_Cells_Threaded //##################################################################### template<class T_GRID> template<class T_ARRAYS_PARTICLES> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Update_Particle_Cells_Find_List(RANGE<TV_INT>& domain,T_ARRAYS_PARTICLES& particles,const ARRAY<ARRAY<int>,TV_INT>& number_of_particles_per_block,ARRAY<ARRAY<TRIPLE<TV_INT,typename T_ARRAYS_PARTICLES::ELEMENT,int> >,TV_INT>& list_to_process) { for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index(); typename T_ARRAYS_PARTICLES::ELEMENT cell_particles=particles(block); for(int i=1;i<=number_of_particles_per_block(block).m;i++){ for(int k=1;k<=number_of_particles_per_block(block)(i);k++){ TV_INT final_block=levelset.grid.Block_Index(cell_particles->X(k),1); if(final_block!=block){ list_to_process(final_block).Append(TRIPLE<TV_INT,typename T_ARRAYS_PARTICLES::ELEMENT,int>(block,cell_particles,k));}} cell_particles=cell_particles->next;}} } //##################################################################### // Function Update_Particle_Cells_Threaded //##################################################################### template<class T_GRID> template<class T_ARRAYS_PARTICLES> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Update_Particle_Cells_Part_Two_Threaded(RANGE<TV_INT>& domain,T_ARRAYS_PARTICLES& particles,const ARRAY<ARRAY<int>,TV_INT>& number_of_particles_per_block,ARRAY<ARRAY<TRIPLE<TV_INT,typename T_ARRAYS_PARTICLES::ELEMENT,int> >,TV_INT>& list_to_process,const ARRAY<int,TV_INT>* domain_index) { typedef typename REMOVE_POINTER<typename T_ARRAYS_PARTICLES::ELEMENT>::TYPE T_PARTICLES; const T_PARTICLES& template_particles=choice<(2-IS_SAME<T_PARTICLES,PARTICLE_LEVELSET_PARTICLES<TV> >::value)>(this->template_particles,this->template_removed_particles); for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT final_block=iterator.Node_Index(); for(int i=1;i<=list_to_process(final_block).m;i++){ T_PARTICLES* cell_particles=list_to_process(final_block)(i).y;int k=list_to_process(final_block)(i).z; if(!particles(final_block))particles(final_block)=Allocate_Particles(template_particles); Copy_Particle(*cell_particles,*particles(final_block),k);}} } //##################################################################### // Function Update_Particle_Cells_Threaded //##################################################################### template<class T_GRID> template<class T_ARRAYS_PARTICLES> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Update_Particle_Cells_Part_Three_Threaded(RANGE<TV_INT>& domain,T_ARRAYS_PARTICLES& particles,const ARRAY<ARRAY<int>,TV_INT>& number_of_particles_per_block,ARRAY<ARRAY<TRIPLE<TV_INT,typename T_ARRAYS_PARTICLES::ELEMENT,int> >,TV_INT>& list_to_process,const ARRAY<int,TV_INT>* domain_index) { typedef typename REMOVE_POINTER<typename T_ARRAYS_PARTICLES::ELEMENT>::TYPE T_PARTICLES; for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT final_block=iterator.Node_Index(); for(int i=1;i<=list_to_process(final_block).m;i++){ T_PARTICLES* cell_particles=list_to_process(final_block)(i).y;int k=list_to_process(final_block)(i).z; assert(cell_particles->radius(k)>0); cell_particles->radius(k)=-(T)1;}} } //##################################################################### // Function Delete_Marked_Particles //##################################################################### template<class T_GRID> template<class T_ARRAYS_PARTICLES> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Delete_Marked_Particles(RANGE<TV_INT>& domain,T_ARRAYS_PARTICLES& particles) { for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index();if(particles(block)){ typename T_ARRAYS_PARTICLES::ELEMENT cell_particles=particles(block); while(1){ for(int k=1;k<=cell_particles->array_collection->Size();k++) if(cell_particles->radius(k)<0){ Delete_Particle_And_Clean_Memory(particles(block),*cell_particles,k);k--;} if(!cell_particles->next)break; cell_particles=cell_particles->next;} if(particles(block)->array_collection->Size()==0) Free_Particle_And_Clear_Pointer(particles(block));}} } //##################################################################### // Function Advect_Particles_In_Ghost_Region //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Advect_Particles_In_Ghost_Region(T_GRID& grid,T_FACE_ARRAYS_SCALAR& V,T_ARRAYS_PARTICLE_LEVELSET_PARTICLES& particles,T dt,int number_of_ghost_cells) { // use second order Runge Kutta T_FACE_LOOKUP V_lookup(V); T_LINEAR_INTERPOLATION_SCALAR linear_interpolation; for(NODE_ITERATOR iterator(grid,number_of_ghost_cells-1,T_GRID::GHOST_REGION);iterator.Valid();iterator.Next()){ TV_INT block_index=iterator.Node_Index(); if(particles(block_index)){ PARTICLE_LEVELSET_PARTICLES<TV>* cell_particles=particles(block_index); BLOCK_UNIFORM<T_GRID> block(grid,block_index); while(cell_particles){ T_LINEAR_INTERPOLATION_MAC_HELPER linear_interpolation_mac_helper(block,V); for(int k=1;k<=cell_particles->array_collection->Size();k++){ TV velocity=linear_interpolation.Clamped_To_Array_Face(grid,V_lookup,cell_particles->X(k)); TV X_new=cell_particles->X(k)+dt*velocity; velocity=(T).5*(velocity+linear_interpolation.Clamped_To_Array_Face(grid,V_lookup,X_new)); cell_particles->X(k)+=dt*velocity; if(grid.Domain().Lazy_Inside(cell_particles->X(k))){ TV_INT to_block=grid.Block_Index(cell_particles->X(k),1); if(!particles(to_block))particles(to_block)=Allocate_Particles(template_particles); Copy_Particle(*cell_particles,*particles(to_block),k);}} cell_particles=cell_particles->next;} if(particles(block_index)->array_collection->Size()==0) Free_Particle_And_Clear_Pointer(particles(block_index));}} } //##################################################################### // Function Reseed_Particles_In_Ghost_Region //##################################################################### template<class T_GRID> int PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Reseed_Particles_In_Ghost_Region(const T time,int number_of_ghost_cells) { int new_particles=0; bool normals_defined=(levelset.normals!=0);levelset.Compute_Normals(); // make sure normals are accurate T_ARRAYS_BOOL cell_centered_mask(levelset.grid.Domain_Indices(number_of_ghost_cells)); cell_centered_mask.Fill(false); for(CELL_ITERATOR iterator(levelset.grid,number_of_ghost_cells,T_GRID::GHOST_REGION);iterator.Valid();iterator.Next()){ assert(!levelset.grid.domain.Lazy_Inside(iterator.Location())); cell_centered_mask(iterator.Cell_Index())=true;} new_particles-=Reseed_Delete_Particles_In_Whole_Region(number_of_ghost_cells-1,negative_particles,-1,&cell_centered_mask); new_particles+=Reseed_Add_Particles_In_Whole_Region(number_of_ghost_cells-1,negative_particles,positive_particles,-1,PARTICLE_LEVELSET_NEGATIVE,time,&cell_centered_mask); if(!only_use_negative_particles){ new_particles-=Reseed_Delete_Particles_In_Whole_Region(number_of_ghost_cells-1,positive_particles,1,&cell_centered_mask); new_particles+=Reseed_Add_Particles_In_Whole_Region(number_of_ghost_cells-1,positive_particles,negative_particles,1,PARTICLE_LEVELSET_POSITIVE,time,&cell_centered_mask); } if(normals_defined){delete levelset.normals;levelset.normals=0;} return new_particles; } //##################################################################### // Function Reseed_Delete_Particles_In_Whole_Region //##################################################################### template<class T_GRID> int PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Reseed_Delete_Particles_In_Whole_Region(int number_of_ghost_cells,T_ARRAYS_PARTICLE_LEVELSET_PARTICLES& particles,const int sign,T_ARRAYS_BOOL* cell_centered_mask) { int number_deleted=0; for(NODE_ITERATOR iterator(levelset.grid,number_of_ghost_cells,T_GRID::WHOLE_REGION);iterator.Valid();iterator.Next()){ TV_INT block_index=iterator.Node_Index(); if(particles(block_index)){ ARRAY<PAIR<PARTICLE_LEVELSET_PARTICLES<TV>*,int> > deletion_list; PARTICLE_LEVELSET_PARTICLES<TV>& cell_particles=*particles(block_index); BLOCK_UNIFORM<T_GRID> block(levelset.grid,block_index); for(int cell_index=0;cell_index<T_GRID::number_of_cells_per_block;cell_index++){ TV_INT cell=block.Cell(cell_index); if(!levelset.phi.domain.Lazy_Inside(cell)) continue; T unsigned_phi=sign*levelset.phi(cell); if(0<=unsigned_phi && unsigned_phi<=half_band_width && (!cell_centered_mask||(*cell_centered_mask)(cell))){ if(cell_particles.array_collection->Size()==0){Free_Particle_And_Clear_Pointer(particles(block_index));} else{ PARTICLE_LEVELSET_PARTICLES<TV>* local_cell_particles=&cell_particles; while(local_cell_particles){ for(int index=1;index<=local_cell_particles->array_collection->Size();index++) Add_Particle_To_Deletion_List(deletion_list,*local_cell_particles,index); local_cell_particles=local_cell_particles->next;} Delete_Particles_From_Deletion_List(deletion_list,cell_particles); if(cell_particles.array_collection->Size()==0) Free_Particle_And_Clear_Pointer(particles(block_index));}}}}} return number_deleted; } //##################################################################### // Function Reseed_Add_Particles_In_Whole_Region //##################################################################### template<class T_GRID> int PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Reseed_Add_Particles_In_Whole_Region(int number_of_ghost_cells,T_ARRAYS_PARTICLE_LEVELSET_PARTICLES& particles,T_ARRAYS_PARTICLE_LEVELSET_PARTICLES& other_particles,const int sign,const PARTICLE_LEVELSET_PARTICLE_TYPE particle_type, const T time,T_ARRAYS_BOOL* cell_centered_mask) { int number_added=0; RANGE<TV_INT> domain(levelset.grid.Domain_Indices(number_of_ghost_cells));domain.max_corner+=TV_INT::All_Ones_Vector(); Consistency_Check(domain,particles); ARRAY<int,TV_INT> number_of_particles_to_add(domain); ARRAY<ARRAY<TRIPLE<TV_INT,PARTICLE_LEVELSET_PARTICLES<TV>*,int> >,TV_INT> list_to_process(domain.Thickened(1)); for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){ TV_INT block_index=iterator.Node_Index(); BLOCK_UNIFORM<T_GRID> block(levelset.grid,block_index); for(int cell_index=0;cell_index<T_GRID::number_of_cells_per_block;cell_index++){ TV_INT cell=block.Cell(cell_index); if(!levelset.phi.domain.Lazy_Inside(cell)) continue; T unsigned_phi=sign*levelset.phi(cell); if(0<=unsigned_phi && unsigned_phi<=half_band_width && (!cell_centered_mask||(*cell_centered_mask)(cell))){ if(!particles(block_index)) particles(block_index)=Allocate_Particles(template_particles); int total_particles=0,total_other_particles=0; PARTICLE_LEVELSET_PARTICLES<TV>* cell_particles=particles(block_index); while(cell_particles){total_particles+=cell_particles->array_collection->Size();cell_particles=cell_particles->next;} cell_particles=other_particles(block_index); while(cell_particles){total_other_particles+=cell_particles->array_collection->Size();cell_particles=cell_particles->next;} if(total_particles+total_other_particles>=number_particles_per_cell){ if(particles(block_index)->array_collection->Size()==0) Free_Particle_And_Clear_Pointer(particles(block_index)); continue;} cell_particles=particles(block_index); number_of_particles_to_add(block_index)=number_particles_per_cell-total_particles-total_other_particles; if(sign==-1){ // we add the negative particles first, and don't want to add too many of them... if(total_other_particles) number_of_particles_to_add(block_index)=(int)((T)number_of_particles_to_add(block_index)*(T)total_particles/(T)(total_particles+total_other_particles)+1); else if(!total_particles) number_of_particles_to_add(block_index)=(number_of_particles_to_add(block_index)+1)/2;}}}} RANDOM_NUMBERS<T> local_random; for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){ TV_INT block_index=iterator.Node_Index(); if(!number_of_particles_to_add(block_index)) continue; VECTOR<T,TV::dimension+1> h;for(int axis=1;axis<=TV::dimension;++axis) h(axis)=(T)block_index(axis);h(TV::dimension+1) = time; local_random.Set_Seed(Hash(h)); ARRAY<PAIR<PARTICLE_LEVELSET_PARTICLES<TV>*,int> > deletion_list; BLOCK_UNIFORM<T_GRID> block(levelset.grid,block_index); PARTICLE_LEVELSET_PARTICLES<TV>* cell_particles=particles(block_index); T phi_min=sign*minimum_particle_radius,phi_max=sign*half_band_width;if(phi_min>phi_max) exchange(phi_min,phi_max); RANGE<TV> block_bounding_box=block.Bounding_Box(); //int attempts=0; ARRAY_VIEW<int>* id=store_unique_particle_id?cell_particles->array_collection->template Get_Array<int>(ATTRIBUTE_ID_ID):0; for(int k=1;k<=number_of_particles_to_add(block_index);k++){ PARTICLE_LEVELSET_PARTICLES<TV>* local_cell_particles=cell_particles; int index=Add_Particle(cell_particles); if(local_cell_particles!=cell_particles){ if(store_unique_particle_id) id=cell_particles->array_collection->template Get_Array<int>(ATTRIBUTE_ID_ID);} #ifndef WIN32 if(id) (*id)(index)= __exchange_and_add(&last_unique_particle_id,1); #else PHYSBAM_ASSERT(!thread_queue); if(id) (*id)(index)=++last_unique_particle_id; #endif cell_particles->quantized_collision_distance(index)=(unsigned short)(local_random.Get_Number()*USHRT_MAX); cell_particles->X(index)=local_random.Get_Uniform_Vector(block_bounding_box); //attract particles to the interface T phi=levelset.Phi(cell_particles->X(index));bool inside=(phi>=phi_min && phi<=phi_max); if(!inside){ T phi_goal=local_random.Get_Uniform_Number(phi_min,phi_max);TV X,N;int iteration=0; while(!inside && iteration<maximum_iterations_for_attraction){ N=levelset.Normal(cell_particles->X(index));T distance=phi_goal-phi,dt=1;bool inside_domain=false; while(!inside_domain && iteration<maximum_iterations_for_attraction){ X=cell_particles->X(index)+dt*distance*N; if(levelset.grid.Ghost_Domain(number_of_ghost_cells).Lazy_Outside(X)){dt*=.5;iteration++;}else inside_domain=true;} if(!inside_domain) break; // ran out of iterations phi=levelset.Phi(X);inside=(phi>=phi_min && phi<=phi_max); if(!inside){ dt*=.5;iteration++;X=cell_particles->X(index)+dt*distance*N; phi=levelset.Phi(X);inside=(phi>=phi_min && phi<=phi_max);} cell_particles->X(index)=X;}} if(!inside) Add_Particle_To_Deletion_List(deletion_list,*cell_particles,index); else cell_particles->radius(index)=clamp(abs(phi),minimum_particle_radius,maximum_particle_radius);} Delete_Particles_From_Deletion_List(deletion_list,*particles(block_index)); if(particles(block_index)->array_collection->Size()==0) Free_Particle_And_Clear_Pointer(particles(block_index));} for(NODE_ITERATOR iterator(levelset.grid);iterator.Valid();iterator.Next()) number_added+=number_of_particles_to_add(iterator.Node_Index()); return number_added; } //##################################################################### // Function Reseed_Particles //##################################################################### template<class T_GRID> int PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Reseed_Particles(const T time,T_ARRAYS_BOOL* cell_centered_mask) { int new_particles=0; bool normals_defined=(levelset.normals!=0);levelset.Compute_Normals(); // make sure normals are accurate if(!cell_centered_mask) new_particles-=Reseed_Delete_Particles(negative_particles,-1); new_particles+=Reseed_Add_Particles(negative_particles,positive_particles,-1,PARTICLE_LEVELSET_NEGATIVE,time,cell_centered_mask); if(!only_use_negative_particles){ if(!cell_centered_mask) new_particles-=Reseed_Delete_Particles(positive_particles,1); new_particles+=Reseed_Add_Particles(positive_particles,negative_particles,1,PARTICLE_LEVELSET_POSITIVE,time,cell_centered_mask);} if(!normals_defined){delete levelset.normals;levelset.normals=0;} return new_particles; } //##################################################################### // Function Reseed_Delete_Particles //##################################################################### template<class T_GRID> int PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Reseed_Delete_Particles(T_ARRAYS_PARTICLE_LEVELSET_PARTICLES& particles,const int sign) { int number_deleted=0;ARRAY<int> heap_particle_indices(number_particles_per_cell);ARRAY<T> heap_phi_minus_radius(number_particles_per_cell); for(NODE_ITERATOR iterator(levelset.grid);iterator.Valid();iterator.Next()){TV_INT block_index=iterator.Node_Index();if(particles(block_index)){ ARRAY<PAIR<PARTICLE_LEVELSET_PARTICLES<TV>*,int> > deletion_list; PARTICLE_LEVELSET_PARTICLES<TV>& cell_particles=*particles(block_index); BLOCK_UNIFORM<T_GRID> block(levelset.grid,block_index); for(int cell_index=0;cell_index<T_GRID::number_of_cells_per_block;cell_index++){TV_INT cell=block.Cell(cell_index); T unsigned_phi=sign*levelset.phi(cell);if(0<=unsigned_phi && unsigned_phi<=half_band_width) goto NEAR_THE_INTERFACE;} //TODO (mlentine): Is this right? if(cell_particles.array_collection->Size()==0){Free_Particle_And_Clear_Pointer(particles(block_index));} else{ // delete all non-escaped particles PARTICLE_LEVELSET_PARTICLES<TV>* local_cell_particles=&cell_particles; while(local_cell_particles){ ARRAY<bool> escaped;Identify_Escaped_Particles(block,*local_cell_particles,escaped,sign); for(int index=1;index<=local_cell_particles->array_collection->Size();index++) if(!escaped(index)) Add_Particle_To_Deletion_List(deletion_list,*local_cell_particles,index); local_cell_particles=local_cell_particles->next;} Delete_Particles_From_Deletion_List(deletion_list,cell_particles); if(cell_particles.array_collection->Size()==0){Free_Particle_And_Clear_Pointer(particles(block_index));}} continue; NEAR_THE_INTERFACE:; // can only get here via the goto if(cell_particles.array_collection->Size()<=number_particles_per_cell) continue; //This assumes particle_pool.number_particles_per_cell>number_particles_per_cell ARRAY<ARRAY<bool> > all_escaped; int number_of_escaped_particles=0,total_particles=0; PARTICLE_LEVELSET_PARTICLES<TV>* local_cell_particles=&cell_particles; while(local_cell_particles){ ARRAY<bool> escaped;Identify_Escaped_Particles(block,cell_particles,escaped,sign);number_of_escaped_particles+=escaped.Number_True();all_escaped.Append(escaped); total_particles+=local_cell_particles->array_collection->Size();local_cell_particles=local_cell_particles->next;} total_particles-=number_of_escaped_particles; if(total_particles>number_particles_per_cell){ // too many particles - delete particles with a heap sort number_deleted+=total_particles-number_particles_per_cell;int heap_size=0; local_cell_particles=&cell_particles; for(int i=1;local_cell_particles;i++){for(int index=1;index<=local_cell_particles->array_collection->Size();index++) if(!all_escaped(i)(index)){ T phi_minus_radius=sign*levelset.Phi(local_cell_particles->X(index))-local_cell_particles->radius(index); if(heap_size<number_particles_per_cell){ // add particle to heap heap_size++;heap_particle_indices(heap_size)=index+particle_pool.number_particles_per_cell*(i-1);heap_phi_minus_radius(heap_size)=phi_minus_radius; if(heap_size==number_particles_per_cell) ARRAYS_COMPUTATIONS::Heapify(heap_phi_minus_radius,heap_particle_indices);} // when heap is full, order values with largest on top else{ // excess particles don't fit in the heap if(phi_minus_radius<heap_phi_minus_radius(1)){ // delete particle on top of heap & add new particle int deletion_index; PARTICLE_LEVELSET_PARTICLES<TV>& deletion_particle_list=Get_Particle_Link(cell_particles,heap_particle_indices(1),deletion_index); Add_Particle_To_Deletion_List(deletion_list,deletion_particle_list,deletion_index); heap_phi_minus_radius(1)=phi_minus_radius;heap_particle_indices(1)=index+particle_pool.number_particles_per_cell*(i-1); ARRAYS_COMPUTATIONS::Heapify(heap_phi_minus_radius,heap_particle_indices,1,heap_phi_minus_radius.m);} else Add_Particle_To_Deletion_List(deletion_list,*local_cell_particles,index);}} // delete new particle, larger than top of heap local_cell_particles=local_cell_particles->next;} Delete_Particles_From_Deletion_List(deletion_list,cell_particles); if(cell_particles.array_collection->Size()==0){Free_Particle_And_Clear_Pointer(particles(block_index));}}}} return number_deleted; } //##################################################################### // Function Reseed_Add_Particles //##################################################################### template<class T_GRID> int PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Reseed_Add_Particles(T_ARRAYS_PARTICLE_LEVELSET_PARTICLES& particles,T_ARRAYS_PARTICLE_LEVELSET_PARTICLES& other_particles,const int sign,const PARTICLE_LEVELSET_PARTICLE_TYPE particle_type, const T time,T_ARRAYS_BOOL* cell_centered_mask) { int number_added=0; RANGE<TV_INT> domain(levelset.grid.Domain_Indices());domain.max_corner+=TV_INT::All_Ones_Vector(); //ARRAY<ARRAY<TRIPLE<PARTICLE_LEVELSET_PARTICLES<TV>*,TV_INT,int> >,TV_INT> move_particles(domain); Consistency_Check(domain,particles); ARRAY<int,TV_INT> number_of_particles_to_add(domain); if(thread_queue){ DOMAIN_ITERATOR_THREADED_ALPHA<PARTICLE_LEVELSET_UNIFORM<T_GRID>,TV> threaded_iterator(domain,thread_queue); threaded_iterator.template Run<T_ARRAYS_PARTICLE_LEVELSET_PARTICLES&,T_ARRAYS_PARTICLE_LEVELSET_PARTICLES&,int,T_ARRAYS_BOOL*,ARRAY<int,TV_INT>&>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Reseed_Add_Particles_Threaded_Part_One,particles,other_particles,sign,cell_centered_mask,number_of_particles_to_add); ARRAY<int,TV_INT> domain_index(domain); for(int i=1;i<=threaded_iterator.domains.m;i++) for(NODE_ITERATOR iterator(levelset.grid,threaded_iterator.domains(i));iterator.Valid();iterator.Next()) domain_index(iterator.Node_Index())=i; // TODO: thread ARRAY<ARRAY<int>,TV_INT> number_of_particles_per_block(levelset.grid.Block_Indices()); ARRAY<ARRAY<TRIPLE<TV_INT,PARTICLE_LEVELSET_PARTICLES<TV>*,int> >,TV_INT> list_to_process(domain.Thickened(1)); threaded_iterator.template Run<T_ARRAYS_PARTICLE_LEVELSET_PARTICLES&,int,const PARTICLE_LEVELSET_PARTICLE_TYPE,T,const ARRAY<int,TV_INT>&,ARRAY<ARRAY<TRIPLE<TV_INT,PARTICLE_LEVELSET_PARTICLES<TV>*,int> >,TV_INT>&,const ARRAY<int,TV_INT>*>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Reseed_Add_Particles_Threaded_Part_Two,particles,sign,particle_type,time,number_of_particles_to_add,list_to_process,&domain_index); threaded_iterator.template Run<T_ARRAYS_PARTICLE_LEVELSET_PARTICLES&,const ARRAY<ARRAY<int>,TV_INT>&,ARRAY<ARRAY<TRIPLE<TV_INT,PARTICLE_LEVELSET_PARTICLES<TV>*,int> >,TV_INT>&,const ARRAY<int,TV_INT>*>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Update_Particle_Cells_Part_Two_Threaded,particles,number_of_particles_per_block,list_to_process,&domain_index); threaded_iterator.template Run<T_ARRAYS_PARTICLE_LEVELSET_PARTICLES&,const ARRAY<ARRAY<int>,TV_INT>&,ARRAY<ARRAY<TRIPLE<TV_INT,PARTICLE_LEVELSET_PARTICLES<TV>*,int> >,TV_INT>&,const ARRAY<int,TV_INT>*>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Update_Particle_Cells_Part_Three_Threaded,particles,number_of_particles_per_block,list_to_process,&domain_index); threaded_iterator.template Run<T_ARRAYS_PARTICLE_LEVELSET_PARTICLES&>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Delete_Marked_Particles,particles);} else{ ARRAY<ARRAY<int>,TV_INT> number_of_particles_per_block(levelset.grid.Block_Indices()); ARRAY<ARRAY<TRIPLE<TV_INT,PARTICLE_LEVELSET_PARTICLES<TV>*,int> >,TV_INT> list_to_process(domain.Thickened(1)); Reseed_Add_Particles_Threaded_Part_One(domain,particles,other_particles,sign,cell_centered_mask,number_of_particles_to_add); Reseed_Add_Particles_Threaded_Part_Two(domain,particles,sign,particle_type,time,number_of_particles_to_add,list_to_process,0); Update_Particle_Cells_Part_Two_Threaded(domain,particles,number_of_particles_per_block,list_to_process,0); Update_Particle_Cells_Part_Three_Threaded(domain,particles,number_of_particles_per_block,list_to_process,0); Delete_Marked_Particles(domain,particles);} Consistency_Check(domain,particles); for(NODE_ITERATOR iterator(levelset.grid);iterator.Valid();iterator.Next()) number_added+=number_of_particles_to_add(iterator.Node_Index()); return number_added; } //##################################################################### // Function Reseed_Add_Particles //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Reseed_Add_Particles_Threaded_Part_One(RANGE<TV_INT>& domain,T_ARRAYS_PARTICLE_LEVELSET_PARTICLES& particles,T_ARRAYS_PARTICLE_LEVELSET_PARTICLES& other_particles,const int sign,T_ARRAYS_BOOL* cell_centered_mask,ARRAY<int,TV_INT>& number_of_particles_to_add) { for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block_index=iterator.Node_Index(); BLOCK_UNIFORM<T_GRID> block(levelset.grid,block_index); for(int cell_index=0;cell_index<T_GRID::number_of_cells_per_block;cell_index++){TV_INT cell=block.Cell(cell_index); T unsigned_phi=sign*levelset.phi(cell); if(0<=unsigned_phi && unsigned_phi<=half_band_width && (!cell_centered_mask||(*cell_centered_mask)(cell))) goto NEAR_THE_INTERFACE;} continue; NEAR_THE_INTERFACE:; // can only get here via the goto if(!particles(block_index)) particles(block_index)=Allocate_Particles(template_particles); int total_particles=0,total_other_particles=0; PARTICLE_LEVELSET_PARTICLES<TV>* cell_particles=particles(block_index); while(cell_particles){total_particles+=cell_particles->array_collection->Size();cell_particles=cell_particles->next;} cell_particles=other_particles(block_index); while(cell_particles){total_other_particles+=cell_particles->array_collection->Size();cell_particles=cell_particles->next;} if(total_particles+total_other_particles>=number_particles_per_cell) continue; cell_particles=particles(block_index); number_of_particles_to_add(block_index)=number_particles_per_cell-total_particles-total_other_particles; if(sign==-1){ // we add the negative particles first, and don't want to add too many of them... if(total_other_particles) number_of_particles_to_add(block_index)=(int)((T)number_of_particles_to_add(block_index)*(T)total_particles/(T)(total_particles+total_other_particles)+1); else if(!total_particles) number_of_particles_to_add(block_index)=(number_of_particles_to_add(block_index)+1)/2;}} } //##################################################################### // Function Reseed_Add_Particles //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Reseed_Add_Particles_Threaded_Part_Two(RANGE<TV_INT>& domain,T_ARRAYS_PARTICLE_LEVELSET_PARTICLES& particles,const int sign,const PARTICLE_LEVELSET_PARTICLE_TYPE particle_type,const T time,const ARRAY<int,TV_INT>& number_of_particles_to_add,ARRAY<ARRAY<TRIPLE<TV_INT,PARTICLE_LEVELSET_PARTICLES<TV>*,int> >,TV_INT>& list_to_process,const ARRAY<int,TV_INT>* domain_index) { RANDOM_NUMBERS<T> local_random; for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block_index=iterator.Node_Index(); if(!number_of_particles_to_add(block_index)) continue; VECTOR<T,TV::dimension+1> h;for(int axis=1;axis<=TV::dimension;++axis) h(axis)=(T)block_index(axis);h(TV::dimension+1) = time; local_random.Set_Seed(Hash(h)); BLOCK_UNIFORM<T_GRID> block(levelset.grid,block_index); PARTICLE_LEVELSET_PARTICLES<TV>* cell_particles=particles(block_index); T phi_min=sign*minimum_particle_radius,phi_max=sign*half_band_width;if(phi_min>phi_max) exchange(phi_min,phi_max); RANGE<TV> block_bounding_box=block.Bounding_Box(); int attempts=0; ARRAY_VIEW<int>* id=store_unique_particle_id?cell_particles->array_collection->template Get_Array<int>(ATTRIBUTE_ID_ID):0; ARRAY_VIEW<T>* material_volume=vof_advection?cell_particles->array_collection->template Get_Array<T>(ATTRIBUTE_ID_MATERIAL_VOLUME):0; for(int k=1;k<=number_of_particles_to_add(block_index);k++){ PARTICLE_LEVELSET_PARTICLES<TV>* local_cell_particles=cell_particles; int index=Add_Particle(cell_particles); if(local_cell_particles!=cell_particles){ if(store_unique_particle_id) id=cell_particles->array_collection->template Get_Array<int>(ATTRIBUTE_ID_ID); if(vof_advection) material_volume=cell_particles->array_collection->template Get_Array<T>(ATTRIBUTE_ID_MATERIAL_VOLUME);} #ifndef WIN32 if(id) (*id)(index)= __exchange_and_add(&last_unique_particle_id,1); #else PHYSBAM_ASSERT(!thread_queue); if(id) (*id)(index)=++last_unique_particle_id; #endif if(material_volume) (*material_volume)(index)=0; cell_particles->quantized_collision_distance(index)=(unsigned short)(local_random.Get_Number()*USHRT_MAX); cell_particles->X(index)=local_random.Get_Uniform_Vector(block_bounding_box); cell_particles->radius(index)=1;//Default value if(!Attract_Individual_Particle_To_Interface_And_Adjust_Radius(particles,*cell_particles,phi_min,phi_max,block,index,particle_type,time,true,local_random,list_to_process,domain_index) && ++attempts<=5) k--;}} } //##################################################################### // Function Identify_Escaped_Particles //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Identify_Escaped_Particles(RANGE<TV_INT>& domain,const int sign) { if(!sign || sign==1){ for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index(); if(positive_particles(block)) Identify_Escaped_Particles(BLOCK_UNIFORM<T_GRID>(levelset.grid,block),*positive_particles(block),escaped_positive_particles(block),1); else escaped_positive_particles(block).Resize(0);}} if(!sign || sign==-1){ for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index(); if(negative_particles(block)) Identify_Escaped_Particles(BLOCK_UNIFORM<T_GRID>(levelset.grid,block),*negative_particles(block),escaped_negative_particles(block),-1); else escaped_negative_particles(block).Resize(0);}} } //##################################################################### // Function Identify_Escaped_Particles //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Identify_Escaped_Particles(const BLOCK_UNIFORM<T_GRID>& block,PARTICLE_LEVELSET_PARTICLES<TV>& particles,ARRAY<bool>& escaped,const int sign) { bool near_objects=levelset.collision_body_list?levelset.collision_body_list->Occupied_Block(block):false; bool enable_collision_aware_already = (levelset.collision_unaware_interpolation)==0?false:true; if(near_objects && !enable_collision_aware_already) { levelset.Enable_Collision_Aware_Interpolation(sign);} escaped.Resize(particles.array_collection->Size());ARRAYS_COMPUTATIONS::Fill(escaped,false);T one_over_radius_multiplier=-sign/outside_particle_distance_multiplier; for(int k=1;k<=particles.array_collection->Size();k++) if(one_over_radius_multiplier*levelset.Phi(particles.X(k))>particles.radius(k)) escaped(k)=true; if(near_objects && !enable_collision_aware_already) { levelset.Disable_Collision_Aware_Interpolation();} } //##################################################################### // Function Delete_All_Particles_In_Cell //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Delete_All_Particles_In_Cell(const TV_INT& block) { if(positive_particles.Valid_Index(block)) Free_Particle_And_Clear_Pointer(positive_particles(block)); if(negative_particles.Valid_Index(block)) Free_Particle_And_Clear_Pointer(negative_particles(block)); if(use_removed_positive_particles && removed_positive_particles.Valid_Index(block)){delete removed_positive_particles(block);removed_positive_particles(block)=0;} if(use_removed_negative_particles && removed_negative_particles.Valid_Index(block)){delete removed_negative_particles(block);removed_negative_particles(block)=0;} } //##################################################################### // Function Delete_Positive_Particles_In_Cell //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Delete_Positive_Particles_In_Cell(const TV_INT& block) { if(positive_particles.Valid_Index(block)) Free_Particle_And_Clear_Pointer(positive_particles(block)); if(use_removed_positive_particles && removed_positive_particles.Valid_Index(block)){delete removed_positive_particles(block);removed_positive_particles(block)=0;} } //##################################################################### // Function Delete_Deep_Escaped_Particles //##################################################################### // delete those farther than radius_fraction too deep template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Delete_Deep_Escaped_Particles(const T radius_fraction,const bool need_to_identify_escaped_particles,const bool verbose) { std::stringstream ss; if(verbose) ss << "positive particles - ";int number_of_positive_particles_deleted=0; for(NODE_ITERATOR iterator(levelset.grid);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index();if(positive_particles(block)){ number_of_positive_particles_deleted+=Delete_Deep_Escaped_Particles(BLOCK_UNIFORM<T_GRID>(levelset.grid,block),*positive_particles(block),escaped_positive_particles(block),1,radius_fraction, need_to_identify_escaped_particles); if(positive_particles(block)->array_collection->Size()==0) Free_Particle_And_Clear_Pointer(positive_particles(block));}} if(verbose) ss << "deleted " << number_of_positive_particles_deleted << " particles" << std::endl; if(verbose) ss << "negative particles - ";int number_of_negative_particles_deleted=0; for(NODE_ITERATOR iterator(levelset.grid);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index();if(negative_particles(block)){ number_of_negative_particles_deleted+=Delete_Deep_Escaped_Particles(BLOCK_UNIFORM<T_GRID>(levelset.grid,block),*negative_particles(block),escaped_negative_particles(block),-1,radius_fraction, need_to_identify_escaped_particles); if(negative_particles(block)->array_collection->Size()==0) Free_Particle_And_Clear_Pointer(negative_particles(block));}} if(verbose) ss << "deleted " << number_of_negative_particles_deleted << " particles" << std::endl; LOG::filecout(ss.str()); for(NODE_ITERATOR iterator(levelset.grid);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index();assert(deletion_list(block).m==0);} } //##################################################################### // Function Delete_Deep_Escaped_Particles //##################################################################### // delete those farther than radius_fraction too deep template<class T_GRID> int PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Delete_Deep_Escaped_Particles(const BLOCK_UNIFORM<T_GRID>& block,PARTICLE_LEVELSET_PARTICLES<TV>& particles,ARRAY<bool>& escaped,const int sign,const T radius_fraction, const bool need_to_identify_escaped_particles) { PARTICLE_LEVELSET_PARTICLES<TV>* cell_particles=&particles; int deleted=0;int minus_sign=-sign; while(cell_particles){ if(need_to_identify_escaped_particles) Identify_Escaped_Particles(block,*cell_particles,escaped,sign); for(int k=cell_particles->array_collection->Size();k>=1;k--) if(escaped(k) && minus_sign*levelset.Phi(particles.X(k))>radius_fraction*particles.radius(k)){Add_Particle_To_Deletion_List(this->deletion_list(block.block_index),*cell_particles,k);deleted++;}} Delete_Particles_From_Deletion_List(this->deletion_list(block.block_index),particles); //TODO: Make these deletion list's per domain return deleted; } //##################################################################### // Function Delete_Particles_Outside_Grid //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Delete_Particles_Outside_Grid() { RANGE<TV_INT> local_domain(levelset.grid.Domain_Indices());local_domain.max_corner+=TV_INT::All_Ones_Vector(); Consistency_Check(local_domain,positive_particles); Consistency_Check(local_domain,negative_particles); RANGE<TV_INT> real_domain(levelset.grid.Domain_Indices());real_domain.max_corner+=TV_INT::All_Ones_Vector(); RANGE<TV_INT> domain(levelset.grid.Domain_Indices(3));domain.max_corner+=TV_INT::All_Ones_Vector(); for(int axis=1;axis<=TV::dimension;axis++) for(int side=1;side<=2;side++){ RANGE<TV_INT> ghost_domain(domain); if(side==1) ghost_domain.max_corner(axis)=real_domain.min_corner(axis)-1; else ghost_domain.min_corner(axis)=real_domain.max_corner(axis)+1; DOMAIN_ITERATOR_THREADED_ALPHA<PARTICLE_LEVELSET_UNIFORM<T_GRID>,TV>(ghost_domain,thread_queue).Run(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Delete_Particles_Far_Outside_Grid);} for(int axis=1;axis<=TV::dimension;axis++) for(int side=1;side<=2;side++){ RANGE<TV_INT> boundary_domain(real_domain); if(side==1) boundary_domain.max_corner(axis)=real_domain.min_corner(axis); else boundary_domain.min_corner(axis)=real_domain.max_corner(axis); DOMAIN_ITERATOR_THREADED_ALPHA<PARTICLE_LEVELSET_UNIFORM<T_GRID>,TV>(boundary_domain,thread_queue).template Run<int,int>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Delete_Particles_Near_Outside_Grid,axis,side);} Consistency_Check(local_domain,positive_particles); Consistency_Check(local_domain,negative_particles); } //##################################################################### // Function Delete_Particles_Far_Outside_Grid //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Delete_Particles_Far_Outside_Grid(RANGE<TV_INT>& domain) { for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()) Delete_All_Particles_In_Cell(iterator.Node_Index()); } //##################################################################### // Function Delete_Particles_Near_Outside_Grid //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Delete_Particles_Near_Outside_Grid(RANGE<TV_INT>& domain,int axis,int side) { // delete particles barely outside grid RANGE<TV> local_domain=levelset.grid.domain;TV domain_boundaries[2]={local_domain.Minimum_Corner(),local_domain.Maximum_Corner()}; for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index(); if(negative_particles(block)){ Delete_Particles_Outside_Grid(domain_boundaries[side-1][axis],axis,*negative_particles(block),2*side-3); if(!negative_particles(block)->array_collection->Size()) Free_Particle_And_Clear_Pointer(negative_particles(block));} if(positive_particles(block)){ Delete_Particles_Outside_Grid(domain_boundaries[side-1][axis],axis,*positive_particles(block),2*side-3); if(!positive_particles(block)->array_collection->Size()) Free_Particle_And_Clear_Pointer(positive_particles(block));} if(use_removed_negative_particles)if(removed_negative_particles(block)){ Delete_Particles_Outside_Grid(domain_boundaries[side-1][axis],axis,*removed_negative_particles(block),2*side-3); if(!removed_negative_particles(block)->array_collection->Size()) Free_Particle_And_Clear_Pointer(removed_negative_particles(block));} if(use_removed_positive_particles)if(removed_positive_particles(block)){ Delete_Particles_Outside_Grid(domain_boundaries[side-1][axis],axis,*removed_positive_particles(block),2*side-3); if(!removed_positive_particles(block)->array_collection->Size()) Free_Particle_And_Clear_Pointer(removed_positive_particles(block));}} } //##################################################################### // Function Delete_Particles_In_Local_Maximum_Phi_Cells //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Delete_Particles_In_Local_Maximum_Phi_Cells(const int sign) { RANGE<TV_INT> domain(levelset.grid.Domain_Indices());domain.max_corner+=TV_INT::All_Ones_Vector(); T tolerance=levelset.small_number*levelset.grid.Minimum_Edge_Length(); Consistency_Check(domain,positive_particles); Consistency_Check(domain,negative_particles); DOMAIN_ITERATOR_THREADED_ALPHA<PARTICLE_LEVELSET_UNIFORM<T_GRID>,TV>(levelset.grid.Domain_Indices(1),thread_queue).template Run<int,T>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Delete_Particles_In_Local_Maximum_Phi_Cells_Threaded,sign,tolerance); DOMAIN_ITERATOR_THREADED_ALPHA<PARTICLE_LEVELSET_UNIFORM<T_GRID>,TV> threaded_iterator(domain,thread_queue); threaded_iterator.template Run<T_ARRAYS_PARTICLE_LEVELSET_PARTICLES&>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Delete_Marked_Particles,positive_particles); threaded_iterator.template Run<T_ARRAYS_PARTICLE_LEVELSET_PARTICLES&>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Delete_Marked_Particles,negative_particles); Consistency_Check(domain,positive_particles); Consistency_Check(domain,negative_particles); } //##################################################################### // Function Delete_Particles_In_Local_Maximum_Phi_Cells //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Delete_Particles_In_Local_Maximum_Phi_Cells_Threaded(RANGE<TV_INT>& domain,const int sign,const T tolerance) { for(CELL_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT cell=iterator.Cell_Index(); bool local_minima=true; for(int axis=1;axis<=T_GRID::dimension;axis++){TV_INT axis_vector=TV_INT::Axis_Vector(axis); if(sign*levelset.phi(cell)<sign*levelset.phi(cell+axis_vector)-tolerance||sign*levelset.phi(cell)<sign*levelset.phi(cell-axis_vector)-tolerance){local_minima=false;break;}} if(!local_minima)continue; TV_INT blocks[T_GRID::number_of_nodes_per_cell];levelset.grid.Nodes_In_Cell_From_Minimum_Corner_Node(cell,blocks); for(int i=0;i<T_GRID::number_of_nodes_per_cell;i++){TV location=iterator.Location(); if(sign==-1&&negative_particles(blocks[i])){PARTICLE_LEVELSET_PARTICLES<TV>* particles=negative_particles(blocks[i]); while(particles){for(int k=1;k<=particles->array_collection->Size();k++) if(sqr(particles->radius(k))>=(particles->X(k)-location).Magnitude_Squared()){particles->radius(k)=-1;}particles=particles->next;}} else if(sign==1&&positive_particles(blocks[i])){PARTICLE_LEVELSET_PARTICLES<TV>* particles=positive_particles(blocks[i]); while(particles){for(int k=1;k<=particles->array_collection->Size();k++) if(sqr(particles->radius(k))>=(particles->X(k)-location).Magnitude_Squared()){particles->radius(k)=-1;}particles=particles->next;}}}} } //##################################################################### // Function Delete_Particles_Outside_Grid //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Delete_Particles_Outside_Grid(const T domain_boundary,const int axis,PARTICLE_LEVELSET_PARTICLES<TV>& particles,const int side) { PARTICLE_LEVELSET_PARTICLES<TV>* local_particles=&particles; while(local_particles){for(int k=1;k<=local_particles->array_collection->Size();k++) if(side*local_particles->X(k)[axis]>side*domain_boundary){ Delete_Particle_And_Clean_Memory(&particles,*local_particles,k);k--;} local_particles=local_particles->next;} // side should be -1 or 1 } //##################################################################### // Function Delete_Particles_Outside_Grid //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Delete_Particles_Outside_Grid(const T domain_boundary,const int axis,PARTICLE_LEVELSET_REMOVED_PARTICLES<TV>& particles,const int side) { for(int k=particles.array_collection->Size();k>=1;k--) if(side*particles.X(k)[axis]>side*domain_boundary) Delete_Particle_And_Clean_Memory(&particles,particles,k); } //##################################################################### // Function Identify_And_Remove_Escaped_Particles //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Identify_And_Remove_Escaped_Particles(const T_FACE_ARRAYS_SCALAR& V,const T radius_fraction,const T time,const bool verbose) { escaped_positive_particles.Resize(levelset.grid.Domain_Indices(3)); escaped_negative_particles.Resize(levelset.grid.Domain_Indices(3)); RANGE<TV_INT> domain(levelset.grid.Domain_Indices());domain.max_corner+=TV_INT::All_Ones_Vector(); Consistency_Check(domain,positive_particles); Consistency_Check(domain,negative_particles); DOMAIN_ITERATOR_THREADED_ALPHA<PARTICLE_LEVELSET_UNIFORM<T_GRID>,TV>(domain,thread_queue).template Run<const T_FACE_ARRAYS_SCALAR&,T,T,bool>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Identify_And_Remove_Escaped_Particles_Threaded,V,radius_fraction,time,verbose); Consistency_Check(domain,positive_particles); Consistency_Check(domain,negative_particles); } //##################################################################### // Function Identify_And_Remove_Escaped_Particles //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Identify_And_Remove_Escaped_Particles_Threaded(RANGE<TV_INT>& domain,const T_FACE_ARRAYS_SCALAR& V,const T radius_fraction,const T time,const bool verbose) { T_FACE_LOOKUP V_lookup(V); T_FACE_LOOKUP_COLLIDABLE V_lookup_collidable(V_lookup,*levelset.collision_body_list,levelset.face_velocities_valid_mask_current); typename T_FACE_LOOKUP_COLLIDABLE::LOOKUP V_lookup_collidable_lookup(V_lookup_collidable,V_lookup); Identify_Escaped_Particles(domain);int p=0,n=0; if(use_removed_positive_particles){ for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index();if(positive_particles(block)){ p+=Remove_Escaped_Particles(BLOCK_UNIFORM<T_GRID>(levelset.grid,block),*positive_particles(block),escaped_positive_particles(block),1,removed_positive_particles(block), V_lookup_collidable_lookup,radius_fraction,time); if(!positive_particles(block)->array_collection->Size()) Free_Particle_And_Clear_Pointer(positive_particles(block));}}} else{ for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index();if(positive_particles(block)){ p+=Remove_Escaped_Particles(BLOCK_UNIFORM<T_GRID>(levelset.grid,block),*positive_particles(block),escaped_positive_particles(block),1,radius_fraction); if(!positive_particles(block)->array_collection->Size()) Free_Particle_And_Clear_Pointer(positive_particles(block));}}} if(use_removed_negative_particles){ for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index();if(negative_particles(block)){ n+=Remove_Escaped_Particles(BLOCK_UNIFORM<T_GRID>(levelset.grid,block),*negative_particles(block),escaped_negative_particles(block),-1,removed_negative_particles(block), V_lookup_collidable_lookup,radius_fraction,time); if(!negative_particles(block)->array_collection->Size()) Free_Particle_And_Clear_Pointer(negative_particles(block));}}} else{ for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index();if(negative_particles(block)){ n+=Remove_Escaped_Particles(BLOCK_UNIFORM<T_GRID>(levelset.grid,block),*negative_particles(block),escaped_negative_particles(block),-1,radius_fraction); if(!negative_particles(block)->array_collection->Size()) Free_Particle_And_Clear_Pointer(negative_particles(block));}}} //LOG::cout << "new removed positive particles = " << p << std::endl;LOG::cout << "new removed negative particles = " << n << std::endl; } //##################################################################### // Function Identify_And_Remove_Escaped_Particles //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Identify_And_Remove_Escaped_Positive_Particles(const T_FACE_ARRAYS_SCALAR& V,const T radius_fraction,const T time,const bool verbose) { T_FACE_LOOKUP V_lookup(V); T_FACE_LOOKUP_COLLIDABLE V_lookup_collidable(V_lookup,*levelset.collision_body_list,levelset.face_velocities_valid_mask_current); typename T_FACE_LOOKUP_COLLIDABLE::LOOKUP V_lookup_collidable_lookup(V_lookup_collidable,V_lookup); RANGE<TV_INT> domain(levelset.grid.Domain_Indices());domain.max_corner+=TV_INT::All_Ones_Vector(); escaped_positive_particles.Resize(levelset.grid.Domain_Indices(3)); escaped_negative_particles.Resize(levelset.grid.Domain_Indices(3)); Identify_Escaped_Particles(domain);int p=0; if(use_removed_positive_particles){ for(NODE_ITERATOR iterator(levelset.grid);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index();if(positive_particles(block)) p+=Remove_Escaped_Particles(BLOCK_UNIFORM<T_GRID>(levelset.grid,block),*positive_particles(block),escaped_positive_particles(block),1,removed_positive_particles(block), V_lookup_collidable_lookup,radius_fraction,time);}} else{ for(NODE_ITERATOR iterator(levelset.grid);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index();if(positive_particles(block)) p+=Remove_Escaped_Particles(BLOCK_UNIFORM<T_GRID>(levelset.grid,block),*positive_particles(block),escaped_positive_particles(block),1,radius_fraction);}} } //##################################################################### // Function Remove_Escaped_Particles //##################################################################### template<class T_GRID> template<class T_FACE_LOOKUP_LOOKUP> int PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Remove_Escaped_Particles(const BLOCK_UNIFORM<T_GRID>& block,PARTICLE_LEVELSET_PARTICLES<TV>& particles,const ARRAY<bool>& escaped,const int sign, PARTICLE_LEVELSET_REMOVED_PARTICLES<TV>*& removed_particles,const T_FACE_LOOKUP_LOOKUP& V,const T radius_fraction,const T time) { T_LINEAR_INTERPOLATION_COLLIDABLE_FACE_SCALAR linear_interpolation_collidable; bool near_objects=levelset.collision_body_list?levelset.collision_body_list->Occupied_Block(block):false;if(near_objects) levelset.Enable_Collision_Aware_Interpolation(sign); int removed=0;T one_over_radius_multiplier=-sign/radius_fraction; // TODO: limit the amount of mass removed - don't let the particles just set their own radii ARRAY_VIEW<int>* id=save_removed_particle_times && store_unique_particle_id?particles.array_collection->template Get_Array<int>(ATTRIBUTE_ID_ID):0; ARRAY<PAIR<int,T> > removed_particle_times_local; ARRAY<bool> local_escaped(escaped); PARTICLE_LEVELSET_PARTICLES<TV>* cell_particles=&particles; while(cell_particles){for(int k=cell_particles->array_collection->Size();k>=1;k--) if(local_escaped(k) && one_over_radius_multiplier*levelset.Phi(cell_particles->X(k))>cell_particles->radius(k)){ if(!removed_particles) removed_particles=Allocate_Particles(template_removed_particles); removed++; if(id) removed_particle_times_local.Append(PAIR<int,T>((*id)(k),time)); Copy_Particle(*cell_particles,*removed_particles,k); Delete_Particle_And_Clean_Memory(&particles,*cell_particles,k); removed_particles->V.Last()=linear_interpolation_collidable.Clamped_To_Array_Face(levelset.grid,V,removed_particles->X.Last());} cell_particles=cell_particles->next; if(cell_particles) Identify_Escaped_Particles(block,*cell_particles,local_escaped,sign);} if(near_objects) levelset.Disable_Collision_Aware_Interpolation(); #ifdef USE_PTHREADS if(thread_queue) pthread_mutex_lock(&cell_lock); #endif removed_particle_times.Append_Elements(removed_particle_times_local); #ifdef USE_PTHREADS if(thread_queue) pthread_mutex_unlock(&cell_lock); #endif return removed; } //##################################################################### // Function Remove_Escaped_Particles //##################################################################### template<class T_GRID> bool PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Fix_Momentum_With_Escaped_Particles(const T_FACE_ARRAYS_SCALAR& V,const T_ARRAYS_SCALAR& momentum_lost,const T radius_fraction,const T mass_scaling,const T time,const bool force) { T_FACE_LOOKUP V_lookup(V); T_FACE_LOOKUP_COLLIDABLE V_lookup_collidable(V_lookup,*levelset.collision_body_list,levelset.face_velocities_valid_mask_current); typename T_FACE_LOOKUP_COLLIDABLE::LOOKUP V_lookup_collidable_lookup(V_lookup_collidable,V_lookup); bool done=true; T_LINEAR_INTERPOLATION_SCALAR linear_interpolation; T_LINEAR_INTERPOLATION_COLLIDABLE_FACE_SCALAR linear_interpolation_collidable; for(NODE_ITERATOR iterator(levelset.grid);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index();if(positive_particles(block)){ T local_momentum_lost=linear_interpolation.Clamped_To_Array(levelset.grid,momentum_lost,iterator.Location()); if(local_momentum_lost==0) continue; //Nothing to add BLOCK_UNIFORM<T_GRID> block_uniform(levelset.grid,block); PARTICLE_LEVELSET_REMOVED_PARTICLES<TV>*& removed_particles=removed_negative_particles(block); if(!removed_particles){ if(!force){done=false;continue;} else removed_particles=template_removed_particles.Clone();} T_LINEAR_INTERPOLATION_COLLIDABLE_FACE_SCALAR linear_interpolation_collidable; bool near_objects=levelset.collision_body_list?levelset.collision_body_list->Occupied_Block(block_uniform):false;if(near_objects) levelset.Enable_Collision_Aware_Interpolation(-1); for(int k=removed_particles->array_collection->Size();k>=1;k--){T fraction=local_momentum_lost/removed_particles->array_collection->Size(); removed_particles->V(k)+=fraction/mass_scaling;} if(!removed_particles->array_collection->Size() && force) Add_Negative_Particle(iterator.Location(),local_momentum_lost/mass_scaling*linear_interpolation_collidable.Clamped_To_Array_Face(levelset.grid,V_lookup_collidable_lookup,iterator.Location()).Normalized(),(unsigned short)(random.Get_Number()*USHRT_MAX)); if(!removed_particles->array_collection->Size()) done=false; if(near_objects) levelset.Disable_Collision_Aware_Interpolation();}} PHYSBAM_ASSERT(!force||done); return done; } //##################################################################### // Function Remove_Escaped_Particles //##################################################################### template<class T_GRID> bool PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Fix_Momentum_With_Escaped_Particles(const TV& location,const T_FACE_ARRAYS_SCALAR& V,const T momentum_lost,const T radius_fraction,const T mass_scaling,const T time,const bool force) { T_FACE_LOOKUP V_lookup(V); T_FACE_LOOKUP_COLLIDABLE V_lookup_collidable(V_lookup,*levelset.collision_body_list,levelset.face_velocities_valid_mask_current); typename T_FACE_LOOKUP_COLLIDABLE::LOOKUP V_lookup_collidable_lookup(V_lookup_collidable,V_lookup); T_LINEAR_INTERPOLATION_SCALAR linear_interpolation; T_LINEAR_INTERPOLATION_COLLIDABLE_FACE_SCALAR linear_interpolation_collidable; TV_INT block=levelset.grid.Closest_Node(location); BLOCK_UNIFORM<T_GRID> block_uniform(levelset.grid,block); PARTICLE_LEVELSET_REMOVED_PARTICLES<TV>*& removed_particles=removed_negative_particles(block); if(!removed_particles){ if(!force) return false; else removed_particles=template_removed_particles.Clone();} bool near_objects=levelset.collision_body_list?levelset.collision_body_list->Occupied_Block(block_uniform):false;if(near_objects) levelset.Enable_Collision_Aware_Interpolation(-1); for(int k=removed_particles->array_collection->Size();k>=1;k--){T fraction=momentum_lost/removed_particles->array_collection->Size(); removed_particles->V(k)+=fraction/mass_scaling;} if(!removed_particles->array_collection->Size() && force) Add_Negative_Particle(location,momentum_lost/mass_scaling*linear_interpolation_collidable.Clamped_To_Array_Face(levelset.grid,V_lookup_collidable_lookup,location).Normalized(),(unsigned short)(random.Get_Number()*USHRT_MAX)); if(near_objects) levelset.Disable_Collision_Aware_Interpolation(); PHYSBAM_ASSERT(!force||removed_particles->array_collection->Size()); return (removed_particles->array_collection->Size())==0?false:true; } //##################################################################### // Function Remove_Escaped_Particles //##################################################################### template<class T_GRID> int PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Remove_Escaped_Particles(const BLOCK_UNIFORM<T_GRID>& block,PARTICLE_LEVELSET_PARTICLES<TV>& particles,const ARRAY<bool>& escaped,const int sign,const T radius_fraction) { bool near_objects=levelset.collision_body_list?levelset.collision_body_list->Occupied_Block(block):false;if(near_objects) levelset.Enable_Collision_Aware_Interpolation(sign); int deleted=0;T one_over_radius_multiplier=-sign/radius_fraction; PARTICLE_LEVELSET_PARTICLES<TV>* cell_particles=&particles; while(cell_particles){for(int k=cell_particles->array_collection->Size();k>=1;k--) if(escaped(k) && one_over_radius_multiplier*levelset.Phi(cell_particles->X(k))>cell_particles->radius(k)){ Delete_Particle_And_Clean_Memory(&particles,*cell_particles,k);deleted++;k--;} cell_particles=cell_particles->next;} if(near_objects) levelset.Disable_Collision_Aware_Interpolation(); return deleted; } //##################################################################### // Function Reincorporate_Removed_Particles //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Reincorporate_Removed_Particles(const T radius_fraction,const T mass_scaling,T_FACE_ARRAYS_SCALAR* V,const bool conserve_momentum_for_removed_negative_particles) { RANGE<TV_INT> domain(levelset.grid.Domain_Indices());domain.max_corner+=TV_INT::All_Ones_Vector(); Consistency_Check(domain,positive_particles); Consistency_Check(domain,negative_particles); DOMAIN_ITERATOR_THREADED_ALPHA<PARTICLE_LEVELSET_UNIFORM<T_GRID>,TV>(domain,thread_queue).template Run<T,T,T_FACE_ARRAYS_SCALAR*>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Reincorporate_Removed_Particles_Threaded,radius_fraction,mass_scaling,conserve_momentum_for_removed_negative_particles?V:0); Consistency_Check(domain,positive_particles); Consistency_Check(domain,negative_particles); } //##################################################################### // Function Reincorporate_Removed_Particles //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Reincorporate_Removed_Particles_Threaded(RANGE<TV_INT>& domain,const T radius_fraction,const T mass_scaling,T_FACE_ARRAYS_SCALAR* V) { if(use_removed_positive_particles){ for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index();if(removed_positive_particles(block)) Reincorporate_Removed_Particles(BLOCK_UNIFORM<T_GRID>(levelset.grid,block),positive_particles(block),1,*removed_positive_particles(block),radius_fraction,mass_scaling,0);}} if(use_removed_negative_particles){ for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT block=iterator.Node_Index();if(removed_negative_particles(block)) Reincorporate_Removed_Particles(BLOCK_UNIFORM<T_GRID>(levelset.grid,block),negative_particles(block),-1,*removed_negative_particles(block),radius_fraction,mass_scaling,V);}} } //##################################################################### // Function Reincorporate_Removed_Particles //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Reincorporate_Removed_Particles(const BLOCK_UNIFORM<T_GRID>& block,PARTICLE_LEVELSET_PARTICLES<TV>*& particles,const int sign,PARTICLE_LEVELSET_REMOVED_PARTICLES<TV>& removed_particles, const T radius_fraction,const T mass_scaling,T_FACE_ARRAYS_SCALAR* V) { bool near_objects=levelset.collision_body_list?levelset.collision_body_list->Occupied_Block(block):false;if(near_objects) levelset.Enable_Collision_Aware_Interpolation(sign); T one_over_radius_multiplier=-sign/radius_fraction; T half_unit_sphere_size_over_cell_size=(T).5*(T)unit_sphere_size<TV::dimension>::value/levelset.grid.Cell_Size(); ARRAY_VIEW<T>* material_volume=vof_advection?removed_particles.array_collection->template Get_Array<T>(ATTRIBUTE_ID_MATERIAL_VOLUME):0; for(int k=removed_particles.array_collection->Size();k>=1;k--) if(reincorporate_removed_particles_everywhere || (one_over_radius_multiplier*levelset.Phi(removed_particles.X(k))<removed_particles.radius(k))){ if(!particles) particles=Allocate_Particles(template_particles); // rasterize the velocity onto the velocity field if(V){ TV_INT cell_index=levelset.grid.Cell(removed_particles.X(k),0); T r=removed_particles.radius(k); TV half_impulse; if(material_volume) half_impulse=removed_particles.V(k)*mass_scaling*(T).5*(*material_volume)(k); else half_impulse = removed_particles.V(k)*mass_scaling*pow<TV::dimension>(r)*half_unit_sphere_size_over_cell_size; for(int i=1;i<=T_GRID::dimension;++i){ TV_INT face_index(cell_index); typename GRID_ARRAYS_POLICY<T_GRID>::ARRAYS_BASE &face_velocity=V->Component(i); #ifdef USE_PTHREADS if(thread_queue) pthread_mutex_lock(&cell_lock); //TODO (mlentine) Remove this with thread_safe code #endif if(face_velocity.Valid_Index(face_index)) face_velocity(face_index)+=half_impulse[i]; face_index[i]+=1; if(face_velocity.Valid_Index(face_index)) face_velocity(face_index)+=half_impulse[i]; #ifdef USE_PTHREADS if(thread_queue) pthread_mutex_unlock(&cell_lock); #endif }} removed_particles.radius(k)=clamp(removed_particles.radius(k),minimum_particle_radius,maximum_particle_radius); Move_Particle(removed_particles,*particles,k);}// maybe recalculate radius to get rid of raining effect? if(near_objects) levelset.Disable_Collision_Aware_Interpolation(); } //##################################################################### // Function Delete_Particles_Far_From_Interface //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Delete_Particles_Far_From_Interface(const int discrete_band) { RANGE<TV_INT> domain(levelset.grid.Domain_Indices());domain.max_corner+=TV_INT::All_Ones_Vector(); assert(discrete_band<8); T_ARRAYS_CHAR near_interface(levelset.grid.Cell_Indices(3)); Consistency_Check(domain,positive_particles); Consistency_Check(domain,negative_particles); DOMAIN_ITERATOR_THREADED_ALPHA<PARTICLE_LEVELSET_UNIFORM<T_GRID>,TV>(levelset.grid.Domain_Indices(3),thread_queue).template Run<T_ARRAYS_CHAR&>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Delete_Particles_Far_From_Interface_Part_One,near_interface); DOMAIN_ITERATOR_THREADED_ALPHA<PARTICLE_LEVELSET_UNIFORM<T_GRID>,TV> part_two_iterator(levelset.grid.Domain_Indices(3),thread_queue); for(int distance=1;distance<=discrete_band;distance++){ part_two_iterator.template Run<T_ARRAYS_CHAR&,int>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Delete_Particles_Far_From_Interface_Part_Two,near_interface,distance);} DOMAIN_ITERATOR_THREADED_ALPHA<PARTICLE_LEVELSET_UNIFORM<T_GRID>,TV>(domain,thread_queue).template Run<T_ARRAYS_CHAR&>(*this,&PARTICLE_LEVELSET_UNIFORM<T_GRID>::Delete_Particles_Far_From_Interface_Part_Three,near_interface); Consistency_Check(domain,positive_particles); Consistency_Check(domain,negative_particles); } //##################################################################### // Function Delete_Particles_Far_From_Interface //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Delete_Particles_Far_From_Interface_Part_One(RANGE<TV_INT>& domain,T_ARRAYS_CHAR& near_interface) { const T_ARRAYS_BOOL_DIMENSION& cell_neighbors_visible=levelset.collision_body_list->cell_neighbors_visible; for(CELL_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT cell=iterator.Cell_Index(); for(int axis=1;axis<=T_GRID::dimension;axis++){TV_INT neighbor=cell+TV_INT::Axis_Vector(axis); if(near_interface.Valid_Index(neighbor) && cell_neighbors_visible(cell)(axis) && LEVELSET_UTILITIES<T>::Interface(levelset.phi(cell),levelset.phi(neighbor))){ near_interface(cell)=near_interface(neighbor)=1;}}} } //##################################################################### // Function Delete_Particles_Far_From_Interface //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Delete_Particles_Far_From_Interface_Part_Two(RANGE<TV_INT>& domain,T_ARRAYS_CHAR& near_interface,const int distance) { const T_ARRAYS_BOOL_DIMENSION& cell_neighbors_visible=levelset.collision_body_list->cell_neighbors_visible; RANGE<TV_INT> ghost_domain(domain);if(ghost_domain.min_corner.x>0) ghost_domain.min_corner.x-=1; char new_mask=1<<distance,old_mask=new_mask-1; for(CELL_ITERATOR iterator(levelset.grid,ghost_domain);iterator.Valid();iterator.Next()){TV_INT cell=iterator.Cell_Index(); for(int axis=1;axis<=T_GRID::dimension;axis++){TV_INT neighbor=cell+TV_INT::Axis_Vector(axis); if(near_interface.Valid_Index(neighbor) && cell_neighbors_visible(cell)(axis) && (near_interface(cell)|near_interface(neighbor))&old_mask){ if(domain.Lazy_Inside(cell)) near_interface(cell)|=new_mask;if(domain.Lazy_Inside(neighbor)) near_interface(neighbor)|=new_mask;}}} } //##################################################################### // Function Delete_Particles_Far_From_Interface //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Delete_Particles_Far_From_Interface_Part_Three(RANGE<TV_INT>& domain,T_ARRAYS_CHAR& near_interface) { for(NODE_ITERATOR iterator(levelset.grid,domain);iterator.Valid();iterator.Next()){TV_INT b=iterator.Node_Index();if(negative_particles(b) || positive_particles(b)){ T_BLOCK block(levelset.grid,b); for(int i=0;i<T_GRID::number_of_cells_per_block;i++)if(near_interface.Valid_Index(block.Cell(i))&&near_interface(block.Cell(i))) goto NEAR_INTERFACE; // if not near interface, delete particles Free_Particle_And_Clear_Pointer(negative_particles(b)); Free_Particle_And_Clear_Pointer(positive_particles(b)); NEAR_INTERFACE:;}} } //##################################################################### // Function Add_Negative_Particle //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Add_Negative_Particle(const TV& location,const TV& particle_velocity,const unsigned short quantized_collision_distance) { //PHYSBAM_NOT_IMPLEMENTED(); // TODO: figure out whether/how this should be collision aware // TODO: still need to figure out whether this should be collision aware, but for now I need it TV_INT block=levelset.grid.Block_Index(location,3); if(!negative_particles.Valid_Index(block)) return; if(levelset.Phi(location)<minimum_particle_radius){ if(!negative_particles(block)) negative_particles(block)=Allocate_Particles(template_particles); PARTICLE_LEVELSET_PARTICLES<TV>* cell_particles=negative_particles(block); int index=Add_Particle(cell_particles); cell_particles->X(index)=location;negative_particles(block)->radius(index)=minimum_particle_radius; cell_particles->quantized_collision_distance(index)=quantized_collision_distance; if(store_unique_particle_id){ ARRAY_VIEW<int>* id=cell_particles->array_collection->template Get_Array<int>(ATTRIBUTE_ID_ID); PHYSBAM_ASSERT(id); #ifndef WIN32 (*id)(index)=__exchange_and_add(&last_unique_particle_id,1);} #else PHYSBAM_ASSERT(!thread_queue); (*id)(index)=++last_unique_particle_id;} #endif if(vof_advection){ ARRAY_VIEW<T>* material_volume=cell_particles->array_collection->template Get_Array<T>(ATTRIBUTE_ID_MATERIAL_VOLUME); PHYSBAM_ASSERT(material_volume); (*material_volume)(index)=0;}} else{ if(!removed_negative_particles(block)) removed_negative_particles(block)=Allocate_Particles(template_removed_particles); int index=Add_Particle(removed_negative_particles(block)); removed_negative_particles(block)->X(index)=location;removed_negative_particles(block)->radius(index)=minimum_particle_radius; removed_negative_particles(block)->V(index)=particle_velocity;removed_negative_particles(block)->quantized_collision_distance(index)=quantized_collision_distance; if(store_unique_particle_id){ ARRAY_VIEW<int>* id=removed_negative_particles(block)->array_collection->template Get_Array<int>(ATTRIBUTE_ID_ID); PHYSBAM_ASSERT(id); #ifndef WIN32 (*id)(index)=__exchange_and_add(&last_unique_particle_id,1);}} #else PHYSBAM_ASSERT(!thread_queue); (*id)(index)=last_unique_particle_id++;}} #endif } //##################################################################### // Function Exchange_Overlap_Particles //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Exchange_Overlap_Particles() { if(mpi_grid){ Exchange_Overlapping_Block_Particles(*mpi_grid,template_particles,negative_particles,(int)(cfl_number+(T)3.5),*this); Exchange_Overlapping_Block_Particles(*mpi_grid,template_particles,positive_particles,(int)(cfl_number+(T)3.5),*this);} } //##################################################################### // Function Copy_From_Move_List_Threaded //##################################################################### template<class T_GRID> void PARTICLE_LEVELSET_UNIFORM<T_GRID>:: Copy_From_Move_List_Threaded(RANGE<TV_INT>& domain,T_ARRAYS_PARTICLE_LEVELSET_PARTICLES& particles,ARRAY<ARRAY<TRIPLE<PARTICLE_LEVELSET_PARTICLES<TV>*,TV_INT,int> >,TV_INT>& move_particles,const ARRAY<int,TV_INT>* domain_index) { PHYSBAM_NOT_IMPLEMENTED(); } //##################################################################### #define INSTANTIATION_HELPER(T_GRID) \ template class PARTICLE_LEVELSET_UNIFORM<T_GRID >; \ template void PARTICLE_LEVELSET_UNIFORM<T_GRID >::Euler_Step_Particles_Wrapper(const GRID_ARRAYS_POLICY<T_GRID>::FACE_ARRAYS& V,PARTICLE_LEVELSET_UNIFORM<T_GRID >::T_ARRAYS_PARTICLE_LEVELSET_PARTICLES& particles,const PARTICLE_LEVELSET_PARTICLE_TYPE particle_type,const T dt, \ const T time,const bool update_particle_cells_after_euler_step,const bool assume_particles_in_correct_blocks,const bool enforce_domain_boundaries); \ template void PARTICLE_LEVELSET_UNIFORM<T_GRID >::Euler_Step_Particles_Wrapper(const GRID_ARRAYS_POLICY<T_GRID>::FACE_ARRAYS& V,PARTICLE_LEVELSET_UNIFORM<T_GRID >::T_ARRAYS_PARTICLE_LEVELSET_REMOVED_PARTICLES& particles,const PARTICLE_LEVELSET_PARTICLE_TYPE particle_type,const T dt, \ const T time,const bool update_particle_cells_after_euler_step,const bool assume_particles_in_correct_blocks,const bool enforce_domain_boundaries); #define P(...) __VA_ARGS__ INSTANTIATION_HELPER(P(GRID<VECTOR<float,1> >)); INSTANTIATION_HELPER(P(GRID<VECTOR<float,2> >)); INSTANTIATION_HELPER(P(GRID<VECTOR<float,3> >)); #ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT INSTANTIATION_HELPER(P(GRID<VECTOR<double,1> >)); INSTANTIATION_HELPER(P(GRID<VECTOR<double,2> >)); INSTANTIATION_HELPER(P(GRID<VECTOR<double,3> >)); #endif
78.207101
420
0.711844
schinmayee
ecb43180b299e99d49622cf7f5b54071e6629eea
1,778
cpp
C++
src/samt.cpp
danieldeutsch/thrax2
68c60bab9f12788e16750b15eba6be5ac9e7df36
[ "MIT" ]
null
null
null
src/samt.cpp
danieldeutsch/thrax2
68c60bab9f12788e16750b15eba6be5ac9e7df36
[ "MIT" ]
null
null
null
src/samt.cpp
danieldeutsch/thrax2
68c60bab9f12788e16750b15eba6be5ac9e7df36
[ "MIT" ]
null
null
null
#include <future> #include <iostream> #include <memory> #include <mutex> #include <sstream> #include <vector> #include "filters.h" #include "label.h" #include "phrasalrule.h" #include "sentence.h" #include "tree.h" namespace { int count = 0; std::mutex countLock, inputLock, outputLock; bool valid(const jhu::thrax::PhrasalRule& rule) { return !isNonlexicalXRule(rule) && !isAbstract(rule) && withinTokenLimit(rule) && !isSlashedRule(rule) && !isConcatRule(rule) && !hasAnyXNT(rule); } bool process() { std::string line; { std::lock_guard g(inputLock); if (!std::getline(std::cin, line)) { return false; } } try { auto asp = jhu::thrax::readAlignedSentencePair<false, true>(line); auto initial = jhu::thrax::allConsistentPairs(asp, 20); auto tree = jhu::thrax::readTree(jhu::thrax::fields(line)[1]); auto label = jhu::thrax::SAMTLabeler{std::move(tree)}; std::ostringstream out; for (auto& rule : jhu::thrax::extract(label, asp, std::move(initial))) { if (valid(rule)) { out << std::move(rule) << '\n'; } } std::lock_guard g(outputLock); std::cout << out.str(); } catch (std::exception& e) { std::cerr << e.what() << ' ' << line << '\n'; } { std::lock_guard g(countLock); count++; if (count % 10000 == 0) { std::lock_guard g(outputLock); std::cerr << count << std::endl; } } return true; } } // namespace int main(int argc, char** argv) { int threads = 1; if (argc > 1) { threads = std::atoi(argv[1]); } if (threads < 2) { while (process()) {} return 0; } std::vector<std::future<void>> workers(threads); for (auto& t : workers) { t = std::async([]() { while (process()) {} }); } }
22.506329
76
0.584364
danieldeutsch
ecb6f0388bb8c17d82100f348490fc115945968b
48,794
cpp
C++
samples/cpp/SampleApp/src/Application.cpp
rtchagas/alexa-auto-sdk
f449ac4cee533a078056c926c08132b658781e0d
[ "Apache-2.0" ]
null
null
null
samples/cpp/SampleApp/src/Application.cpp
rtchagas/alexa-auto-sdk
f449ac4cee533a078056c926c08132b658781e0d
[ "Apache-2.0" ]
null
null
null
samples/cpp/SampleApp/src/Application.cpp
rtchagas/alexa-auto-sdk
f449ac4cee533a078056c926c08132b658781e0d
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2018-2020 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 "SampleApp/Application.h" #include "SampleApp/Extension.h" // Sample Text To Speech Platform Interfaces #include "SampleApp/TextToSpeech/TextToSpeechHandler.h" // C++ Standard Library #ifdef __linux__ #include <linux/limits.h> // PATH_MAX #endif #include <algorithm> // std::find, std::for_each #include <csignal> // std::signal and SIG_ERR macro #include <cstdlib> // EXIT_SUCCESS and EXIT_FAILURE macros, std::atexit // https://llvm.org/docs/CodingStandards.html#include-iostream-is-forbidden #include <iostream> // std::clog and std::cout #include <fstream> // #include <iomanip> // std::setw #include <regex> // std::regex #include <set> // std::set #include <sstream> // std::stringstream #include <vector> // std::vector // Guidelines Support Library #define GSL_THROW_ON_CONTRACT_VIOLATION #include <gsl/contracts.h> // JSON for Modern C++ #include <nlohmann/json.hpp> using json = nlohmann::json; namespace sampleApp { //////////////////////////////////////////////////////////////////////////////////////////////////// // // Application // //////////////////////////////////////////////////////////////////////////////////////////////////// using Level = logger::LoggerHandler::Level; Application::Application() = default; #ifdef MONITORAIRPLANEMODEEVENTS // Monitors airplane mode events and sends a network status changed event when the airplane mode changes void monitorAirplaneModeEvents( std::shared_ptr<Activity> activity, std::shared_ptr<logger::LoggerHandler> loggerHandler) { // # Tested on Linux Ubuntu 16.04 LTS // $ rfkill event // 1567307554.400006: idx 1 type 1 op 0 soft 0 hard 0 // 1567307554.400183: idx 2 type 2 op 0 soft 0 hard 0 // 1567307558.915117: idx 1 type 1 op 2 soft 1 hard 0 // 1567307558.924296: idx 2 type 2 op 2 soft 1 hard 0 std::unique_ptr<FILE, decltype(&pclose)> pipe(popen("/usr/sbin/rfkill event", "r"), pclose); if (!pipe || !pipe.get()) { loggerHandler->log(Level::ERROR, "monitorAirplaneModeEvents", "popen() failed"); if (auto console = activity->findViewById("id:console").lock()) { console->printLine("popen() failed"); } return; } auto currentNetworkStatus = network::NetworkInfoProviderHandler::NetworkStatus::UNKNOWN; std::array<char, 1024> buffer{}; while (fgets(buffer.data(), buffer.size(), pipe.get()) != NULL) { std::string value = buffer.data(); auto hard = (std::string::npos != value.find("hard 1")); auto soft = (std::string::npos != value.find("soft 1")); auto nextworkStatus = (soft || hard) ? network::NetworkInfoProviderHandler::NetworkStatus::DISCONNECTED : network::NetworkInfoProviderHandler::NetworkStatus::CONNECTED; // Send a network status changed event if the airplane mode changed if (currentNetworkStatus != nextworkStatus) { currentNetworkStatus = nextworkStatus; std::stringstream stream; stream << nextworkStatus; value = stream.str(); loggerHandler->log(Level::VERBOSE, "monitorAirplaneModeEvents", value); activity->notify(Event::onNetworkInfoProviderNetworkStatusChanged, value); } } } #endif // MONITORAIRPLANEMODEEVENTS // Parses config files so that handlers can check that required config is passed in void parseConfigurations(const std::vector<std::string>& configFilePaths, std::vector<json>& configs) { for (auto const& path : configFilePaths) { try { std::ifstream ifs(path); json j = json::parse(ifs); configs.push_back(j); } catch (std::exception& e) { } } } void Application::printMenu( std::shared_ptr<ApplicationContext> applicationContext, std::shared_ptr<aace::core::Engine> engine, std::shared_ptr<sampleApp::propertyManager::PropertyManagerHandler> propertyManagerHandler, std::shared_ptr<View> console, const std::string& id) { // ACTIONS: // AudioFile // GoBack // GoTo // Help // Login // Logout // Quit // Restart // Select // SetLocale // SetTimeZone // SetLoggerLevel // SetProperty // notify/* // FORMAT: // id <string> // index <integer> // item <array> // do <string> // key <string> // name <string> // note <string> // value <any> // name <string> // path <string> // text <object> auto menu = applicationContext->getMenu(id); Ensures(menu != nullptr); static const unsigned menuColumns = 80; auto titleRuler = std::string(menuColumns, '#'); auto titleSpacer = '#' + std::string(menuColumns - 2, ' ') + '#'; auto title = menu.count("name") ? menu.at("name").get<std::string>() : id; Ensures(menuColumns - 2 >= title.length()); int balance = menuColumns - 2 - title.length(); int left = balance > 1 ? balance / 2 : 0; int right = balance > 1 ? balance / 2 + balance % 2 : 0; std::stringstream stream; stream << std::endl << titleRuler << std::endl << titleSpacer << std::endl << '#' << std::string(left, ' ') << title << std::string(right, ' ') << '#' << std::endl << titleSpacer << std::endl << titleRuler << std::endl << std::endl; if (menu.count("item")) { unsigned keyMax = 0; for (auto& item : menu.at("item")) { if (!testMenuItem(applicationContext, item)) { continue; } auto key = item.at("key").get<std::string>(); // required item.key auto keyLength = key.length(); if (keyMax < keyLength) { keyMax = keyLength; } } unsigned index = 0; for (auto& item : menu.at("item")) { if (!testMenuItem(applicationContext, item)) { continue; } auto action = item.at("do").get<std::string>(); // required item.do auto key = item.at("key").get<std::string>(); // required item.key auto name = item.at("name").get<std::string>(); // required item.name auto keyLength = key.length(); auto underline = false; if (action == "Select") { underline = (menu.count("index") && menu.at("index").get<unsigned>() == index); } else if (action == "SetLocale") { auto locale = propertyManagerHandler->getProperty("aace.alexa.setting.locale"); underline = (item.count("value") && item.at("value").get<std::string>() == locale); } else if (action == "SetTimeZone") { auto timezone = propertyManagerHandler->getProperty("aace.alexa.timezone"); underline = (item.count("value") && item.at("value").get<std::string>() == timezone); } else if (action == "SetLoggerLevel") { if (applicationContext->isLogEnabled()) { auto level = applicationContext->getLevel(); std::stringstream ss; // Note: Fix stream issue // ss << level; switch (level) { case Level::VERBOSE: ss << "VERBOSE"; break; case Level::INFO: ss << "INFO"; break; case Level::METRIC: ss << "METRIC"; break; case Level::WARN: ss << "WARN"; break; case Level::ERROR: ss << "ERROR"; break; case Level::CRITICAL: ss << "CRITICAL"; break; } // underline = (item.count("value") && item.at("value").get<std::string>() == ss.str()); } } else if (action == "SetProperty") { auto value = item.at("value").get<std::string>(); // required item.value static std::regex r("^([^/]+)/(.+)", std::regex::optimize); std::smatch sm{}; if (std::regex_match(value, sm, r) || ((sm.size() - 1) == 2)) { underline = (propertyManagerHandler->getProperty(sm[1]) == sm[2]); } } if (underline) { stream << " [ " + key + " ] " << std::string(keyMax - keyLength, ' ') << "\e[4m" << name << "\e[0m" << std::endl; } else { stream << " [ " + key + " ] " << std::string(keyMax - keyLength, ' ') << name << std::endl; } index++; } } stream << std::endl << titleRuler << std::endl; if (menu.count("path")) { auto menuFilePath = menu.at("path").get<std::string>(); auto sdkVersion = propertyManagerHandler->getProperty(aace::core::property::VERSION); auto buildIdentifier = applicationContext->getBuildIdentifier(); std::string string; if (!buildIdentifier.empty()) { string = menuFilePath + " (v" + sdkVersion + "-" + buildIdentifier + ")"; } else { string = menuFilePath + " (v" + sdkVersion + ")"; } int balance = menuColumns - 2 - string.length(); int left = balance > 1 ? balance / 2 : 0; stream << std::string(left, ' ') << string << std::endl; } console->printLine(stream.str()); } void Application::printMenuText( std::shared_ptr<ApplicationContext> applicationContext, std::shared_ptr<View> console, const std::string& menuId, const std::string& textId, std::map<std::string, std::string> variables) { auto menu = applicationContext->getMenu(menuId); if ((menu != nullptr) && menu.count("text")) { auto text = menu.at("text"); if (text.is_object() && text.count(textId)) { text = text.at(textId); } if (text.is_primitive()) { text = json::array({text}); } if (text.is_array()) { for (auto& item : text) { printStringLine(console, item.get<std::string>(), variables); } } } } void Application::printStringLine( std::shared_ptr<View> console, const std::string& string, std::map<std::string, std::string> variables) { auto s = string; static std::regex r("\\$\\{([a-zA-Z]+)\\}", std::regex::optimize); std::smatch sm{}; std::stringstream stream; while (std::regex_search(s, sm, r)) { stream << sm.prefix(); stream << variables[sm[1]]; s = sm.suffix(); } stream << s << std::endl; console->print(stream.str()); } Status Application::run(std::shared_ptr<ApplicationContext> applicationContext) { std::mutex mutex; std::condition_variable conditionVariable; std::atomic<bool> connected{false}; std::atomic<bool> processed{false}; // Prepare the UI views std::vector<std::shared_ptr<View>> views{}; // Create the application card view auto card = ContentView::create("id:card"); views.push_back(card); // Create the application console view auto console = View::create("id:console"); views.push_back(console); // AlertsHandler view example views.push_back(TextView::create("id:AlertState")); // AlexaClientHandler view example views.push_back(TextView::create("id:AuthState")); views.push_back(TextView::create("id:ConnectionStatus")); views.push_back(TextView::create("id:DialogState")); // DoNotDisturbHandler view example views.push_back(TextView::create("id:DoNotDisturbState")); // NotificationsHandler view example views.push_back(TextView::create("id:IndicatorState")); // Create the activity object auto activity = Activity::create(applicationContext, views); Ensures(activity != nullptr); // Special case for test automation if (applicationContext->isTestAutomation()) { activity->registerObserver(Event::onTestAutomationConnect, [&](const std::string&) { connected = true; activity->notify(Event::onTestAutomationProcess); return true; }); activity->registerObserver(Event::onTestAutomationProcess, [&](const std::string&) { if (connected) { auto audioFilePath = applicationContext->popAudioFilePath(); if (!audioFilePath.empty()) { console->printLine("Process:", audioFilePath); if (activity->notify(Event::onSpeechRecognizerStartStreamingAudioFile, audioFilePath)) { return activity->notify(Event::onSpeechRecognizerTapToTalk); } return false; } processed = true; conditionVariable.notify_one(); } return false; }); } // Create the engine object auto engine = aace::core::Engine::create(); Ensures(engine != nullptr); // Logger (Important: Logger must be created before the other handlers) auto loggerHandler = logger::LoggerHandler::create(activity); Ensures(loggerHandler != nullptr); // Create car control handler auto carControlHandler = carControl::CarControlHandler::create(activity, loggerHandler); Ensures(carControlHandler != nullptr); // Create configuration files for --config files path passed from the command line std::vector<std::shared_ptr<aace::core::config::EngineConfiguration>> configurationFiles; auto configFilePaths = applicationContext->getConfigFilePaths(); for (auto& configFilePath : configFilePaths) { auto configurationFile = aace::core::config::ConfigurationFile::create(configFilePath); Ensures(configurationFile != nullptr); configurationFiles.push_back(configurationFile); } // Validate that configuration files are passed in std::vector<json> jsonConfigs; parseConfigurations(configFilePaths, jsonConfigs); // ------------------------------------------------------------------------ // In a production environment we recommend that the application builds // the car control configuration programatically. However, the configuration // can also be passed in to the application. This example builds a // configuration programatically if one is not passed in to the application. // ------------------------------------------------------------------------ if (!carControl::CarControlHandler::checkConfiguration(jsonConfigs)) { console->printRuler(); console->printLine("Car control configuration was created"); console->printRuler(); auto carControlConfig = carControl::CarControlDataProvider::generateCarControlConfig(); configurationFiles.push_back(carControlConfig); } else { console->printRuler(); console->printLine("Car control configuration found"); console->printRuler(); } // Initialize values for car control configuration controllers carControl::CarControlDataProvider::initialize(configurationFiles); // Validate extensions if (!extension::Manager::validateExtensions(jsonConfigs, console)) { console->printRuler(); console->printLine("Auto SDK extensions failed validation"); console->printRuler(); // Shutdown if (!engine->shutdown()) { console->printRuler(); console->printLine("Error: Engine could not be shutdown"); console->printRuler(); } return Status::Failure; } // Configure the engine auto configured = engine->configure(configurationFiles); if (!configured) { // Note: not logging anything here as loggerHandler is not available yet console->printLine("Error: could not be configured"); if (!engine->shutdown()) { console->printLine("Error: could not be shutdown"); } return Status::Failure; } // Important: Logger, Audio IO Providers, Location Provider, and Network Info Provider are // core module features and must be created and registered before the other handlers. // Register logger handler Ensures(engine->registerPlatformInterface(loggerHandler)); // Default Audio (Important: Audio implementation must be created before the other handlers) auto defaultAudioInputProvider = audio::AudioInputProviderHandler::create(activity, loggerHandler, false); Ensures(defaultAudioInputProvider != nullptr); // registering the default audio input provider can fail if another implementation // has already been registered by the engine... if (!engine->registerPlatformInterface(defaultAudioInputProvider)) { defaultAudioInputProvider.reset(); console->printLine("Default audio input provider will not be registered because audio support is available."); } else { // defer setup until after successful registration defaultAudioInputProvider->setupUI(); applicationContext->setAudioFileSupported(true); } auto defaultAudioOutputProvider = audio::AudioOutputProviderHandler::create(activity, loggerHandler, false); Ensures(defaultAudioOutputProvider != nullptr); // registering the default audio output provider can fail if another implementation // has already been registered by the engine... if (!engine->registerPlatformInterface(defaultAudioOutputProvider)) { defaultAudioOutputProvider.reset(); console->printLine("Default audio output provider will not be registered because audio support is available."); } else { // defer setup until after successful registration defaultAudioOutputProvider->setupUI(); } // Location Provider (Important: Location Provider must be created before the other handlers) auto locationProviderHandler = location::LocationProviderHandler::create(activity, loggerHandler); Ensures(locationProviderHandler != nullptr); Ensures(engine->registerPlatformInterface(locationProviderHandler)); // Network Info Provider (Important: Network Info Provider must be created before the other handlers) auto networkInfoProviderHandler = network::NetworkInfoProviderHandler::create(activity, loggerHandler); Ensures(networkInfoProviderHandler != nullptr); Ensures(engine->registerPlatformInterface(networkInfoProviderHandler)); // Alerts auto alertsHandler = alexa::AlertsHandler::create(activity, loggerHandler); Ensures(alertsHandler != nullptr); Ensures(engine->registerPlatformInterface(alertsHandler)); // Alexa Client auto alexaClientHandler = alexa::AlexaClientHandler::create(activity, loggerHandler); Ensures(alexaClientHandler != nullptr); Ensures(engine->registerPlatformInterface(alexaClientHandler)); // Audio Player auto audioPlayerHandler = alexa::AudioPlayerHandler::create(activity, loggerHandler); Ensures(audioPlayerHandler != nullptr); Ensures(engine->registerPlatformInterface(audioPlayerHandler)); // Authorization auto authorizationHandler = authorization::AuthorizationHandler::create(activity, loggerHandler); Ensures(authorizationHandler != nullptr); Ensures(engine->registerPlatformInterface(authorizationHandler)); authorizationHandler->saveDeviceInfo(jsonConfigs); // Alerts auto doNotDisturbHandler = alexa::DoNotDisturbHandler::create(activity, loggerHandler); Ensures(doNotDisturbHandler != nullptr); Ensures(engine->registerPlatformInterface(doNotDisturbHandler)); //Device Setup Handler auto deviceSetupHandler = alexa::DeviceSetupHandler::create(activity, loggerHandler); Ensures(deviceSetupHandler != nullptr); Ensures(engine->registerPlatformInterface(deviceSetupHandler)); #ifdef TEXT_TO_SPEECH // Text To Speech Handler auto textToSpeechHandler = textToSpeech::TextToSpeechHandler::create(activity, loggerHandler); Ensures(textToSpeechHandler != nullptr); Ensures(engine->registerPlatformInterface(textToSpeechHandler)); #endif // TEXT_TO_SPEECH // Equalizer Controller auto equalizerControllerHandler = alexa::EqualizerControllerHandler::create(activity, loggerHandler); Ensures(equalizerControllerHandler != nullptr); Ensures(engine->registerPlatformInterface(equalizerControllerHandler)); #ifdef CONNECTIVITY // Alexa Connectivity auto alexaConnectivityHandler = connectivity::AlexaConnectivityHandler::create(activity, loggerHandler); Ensures(alexaConnectivityHandler != nullptr); Ensures(engine->registerPlatformInterface(alexaConnectivityHandler)); #endif // CONNECTIVITY std::vector<std::pair<aace::alexa::LocalMediaSource::Source, std::shared_ptr<alexa::LocalMediaSourceHandler>>> LocalMediaSources = {{aace::alexa::LocalMediaSource::Source::BLUETOOTH, nullptr}, {aace::alexa::LocalMediaSource::Source::USB, nullptr}, {aace::alexa::LocalMediaSource::Source::FM_RADIO, nullptr}, {aace::alexa::LocalMediaSource::Source::AM_RADIO, nullptr}, {aace::alexa::LocalMediaSource::Source::SATELLITE_RADIO, nullptr}, {aace::alexa::LocalMediaSource::Source::LINE_IN, nullptr}, {aace::alexa::LocalMediaSource::Source::COMPACT_DISC, nullptr}, /*{ aace::alexa::LocalMediaSource::Source::SIRIUS_XM, nullptr },*/ {aace::alexa::LocalMediaSource::Source::DAB, nullptr}}; for (auto& source : LocalMediaSources) { source.second = alexa::LocalMediaSourceHandler::create(activity, loggerHandler, source.first); Ensures(source.second != nullptr); Ensures(engine->registerPlatformInterface(source.second)); } // Global Preset Handler auto globalPresetHandler = alexa::GlobalPresetHandler::create(activity, loggerHandler); Ensures(globalPresetHandler != nullptr); Ensures(engine->registerPlatformInterface(globalPresetHandler)); // Messaging auto messagingHandler = messaging::MessagingHandler::create(activity, loggerHandler); Ensures(messagingHandler != nullptr); Ensures(engine->registerPlatformInterface(messagingHandler)); // Navigation auto navigationHandler = navigation::NavigationHandler::create(activity, loggerHandler); Ensures(navigationHandler != nullptr); Ensures(engine->registerPlatformInterface(navigationHandler)); // Notifications auto notificationsHandler = alexa::NotificationsHandler::create(activity, loggerHandler); Ensures(notificationsHandler != nullptr); Ensures(engine->registerPlatformInterface(notificationsHandler)); // Phone Call Controller auto phoneCallControllerHandler = phoneControl::PhoneCallControllerHandler::create(activity, loggerHandler); Ensures(phoneCallControllerHandler != nullptr); Ensures(engine->registerPlatformInterface(phoneCallControllerHandler)); // Playback Controller auto playbackControllerHandler = alexa::PlaybackControllerHandler::create(activity, loggerHandler); Ensures(playbackControllerHandler != nullptr); Ensures(engine->registerPlatformInterface(playbackControllerHandler)); // Property Manager auto propertyManagerHandler = propertyManager::PropertyManagerHandler::create(loggerHandler); Ensures(propertyManagerHandler != nullptr); Ensures(engine->registerPlatformInterface(propertyManagerHandler)); // Speech Recognizer // Note : Expects PropertyManager to be not null. auto speechRecognizerHandler = alexa::SpeechRecognizerHandler::create(activity, loggerHandler, propertyManagerHandler); Ensures(speechRecognizerHandler != nullptr); Ensures(engine->registerPlatformInterface(speechRecognizerHandler)); Ensures(propertyManagerHandler->setProperty( aace::alexa::property::WAKEWORD_ENABLED, applicationContext->isWakeWordSupported() ? "true" : "false")); // Speech Synthesizer auto speechSynthesizerHandler = alexa::SpeechSynthesizerHandler::create(activity, loggerHandler); Ensures(speechSynthesizerHandler != nullptr); Ensures(engine->registerPlatformInterface(speechSynthesizerHandler)); // Template Runtime auto templateRuntimeHandler = alexa::TemplateRuntimeHandler::create(activity, loggerHandler); Ensures(templateRuntimeHandler != nullptr); Ensures(engine->registerPlatformInterface(templateRuntimeHandler)); // Text To Speech Handler auto textToSpeechHandler = textToSpeech::TextToSpeechHandler::create(activity, loggerHandler, defaultAudioOutputProvider); Ensures(textToSpeechHandler != nullptr); Ensures(engine->registerPlatformInterface(textToSpeechHandler)); auto addressBookHandler = addressBook::AddressBookHandler::create(activity, loggerHandler); Ensures(addressBookHandler != nullptr); if (!engine->registerPlatformInterface(addressBookHandler)) { loggerHandler->log(Level::INFO, "Application:Engine", "failed to register address book handler"); console->printLine("Error: could not register address book handler (check config)"); if (!engine->shutdown()) { console->printLine("Error: could not be shutdown"); } return Status::Failure; } // Alexa Speaker auto alexaSpeakerHandler = alexa::AlexaSpeakerHandler::create(activity, loggerHandler); Ensures(alexaSpeakerHandler != nullptr); Ensures(engine->registerPlatformInterface(alexaSpeakerHandler)); // Car Control Handler if (!engine->registerPlatformInterface(carControlHandler)) { loggerHandler->log(Level::INFO, "Application:Engine", "failed to register car control handler"); console->printLine("Error: could not register car control handler (check config)"); if (!engine->shutdown()) { console->printLine("Error: could not be shutdown"); } return Status::Failure; } bool extensionError = false; std::string extensionErrorMsg; // Initialize extension handlers if (!extension::Manager::initializeExtensions(activity, loggerHandler, propertyManagerHandler)) { extensionError = true; extensionErrorMsg = "Auto SDK extensions failed to initialize\n"; } // Register platform interfaces for extensions if (!extension::Manager::registerPlatformInterfaces(engine)) { extensionError = true; extensionErrorMsg += "Auto SDK extensions failed platform interface registration"; } // Exit on error if (extensionError) { console->printRuler(); console->printLine(extensionErrorMsg); console->printRuler(); // Shutdown if (!engine->shutdown()) { console->printRuler(); console->printLine("Error: Engine could not be shutdown"); console->printRuler(); } return Status::Failure; } // Start the engine if (engine->start()) { loggerHandler->log(Level::INFO, "Application:Engine", "started successfully"); } else { loggerHandler->log(Level::INFO, "Application:Engine", "failed to start"); console->printLine("Error: could not be started (check logs)"); if (engine->shutdown()) { loggerHandler->log(Level::INFO, "Application:Engine", "shutdown successfully"); } else { loggerHandler->log(Level::INFO, "Application:Engine", "failed to shutdown"); console->printLine("Error: could not be shutdown (check logs)"); } return Status::Failure; } #ifdef MONITORAIRPLANEMODEEVENTS // Start a thread to monitor airplane mode events std::thread monitorAirplaneModeEventsThread(monitorAirplaneModeEvents, activity, loggerHandler); monitorAirplaneModeEventsThread.detach(); #endif // MONITORAIRPLANEMODEEVENTS #ifdef ALEXACOMMS // Workaround: Enable Phone Connection since it is needed by Alexa Comms. This limitation will go away in the future. Refer to // Alexa Comms README for more information. phoneCallControllerHandler->connectionStateChanged( phoneControl::PhoneCallControllerHandler::ConnectionState::CONNECTED); #endif // ALEXACOMMS // Setup the interactive text based menu system setupMenu(applicationContext, engine, propertyManagerHandler, console); // Setup the SDK version number and print optional text for the main menu with variables auto VERSION = propertyManagerHandler->getProperty(aace::core::property::VERSION); // clang-format off std::map<std::string, std::string> variables{ {"VERSION", VERSION} }; // clang-format on console->printLine("Alexa Auto SDK", 'v' + VERSION); printMenuText(applicationContext, console, "main", "banner", variables); // Start the authorization if we were successfully authorized previously. // This can be disabled by supplying `disable-auto-authorization` command to sample app if (!applicationContext->isAutoAuthorizationDisabled()) { authorizationHandler->startAuth(); } // Run the program auto status = Status::Success; if (applicationContext->isTestAutomation()) { std::unique_lock<std::mutex> lock(mutex); conditionVariable.wait(lock, [&processed] { return processed.load(); }); } else { // Run the main loop (i.e. interactive text based menu system) auto id = std::string("main"); if (applicationContext->hasMenu("user")) { // If not logged in, and user menu is available, run it instead of main id = std::string("user"); } status = runMenu(applicationContext, engine, propertyManagerHandler, activity, console, id); } // Stop notifications activity->clearObservers(); // Stop the engine if (engine->stop()) { loggerHandler->log(Level::INFO, "Application:Engine", "stopped successfully"); } else { loggerHandler->log(Level::INFO, "Application:Engine", "failed to stop"); console->printLine("Error: could not be stopped (check logs)"); } // Shutdown the engine if (engine->shutdown()) { loggerHandler->log(Level::INFO, "Application:Engine", "shutdown successfully"); } else { loggerHandler->log(Level::INFO, "Application:Engine", "failed to shutdown"); console->printLine("Error: could not be shutdown (check logs)"); } // Releases the ownership of the managed objects for (auto& configurationFile : configurationFiles) { configurationFile.reset(); } // Print and return the application status console->printLine(status); return status; } Status Application::runMenu( std::shared_ptr<ApplicationContext> applicationContext, std::shared_ptr<aace::core::Engine> engine, std::shared_ptr<sampleApp::propertyManager::PropertyManagerHandler> propertyManagerHandler, std::shared_ptr<Activity> activity, std::shared_ptr<View> console, const std::string& id) { auto status = Status::Unknown; std::vector<std::string> stack{id}; auto ptr = applicationContext->getMenuPtr(id); auto menuPtr = ptr; Ensures(menuPtr != nullptr); auto menuFilePath = menuPtr->at("path").get<std::string>(); auto menuDirPath = applicationContext->getDirPath(menuFilePath); printMenu(applicationContext, engine, propertyManagerHandler, console, id); while (auto cin = fgetc(stdin)) { auto c = static_cast<unsigned char>(cin); static const unsigned char DELETE = 0x7F; static const unsigned char ENTER = '\n'; static const unsigned char ESC = '\e'; static const unsigned char HELP = '?'; static const unsigned char QUIT = 'q'; static const unsigned char STOP_ACTIVE_DOMAIN = 'x'; static const unsigned char STOP_FOREGROUND_ACTIVITY = '!'; static const unsigned char TALK = ' '; // clang-format off std::map<std::string, std::string> variables{ {"KEYCLOSE", " ]"}, {"KEYOPEN", "[ "} }; // clang-format on unsigned char k = '\0'; unsigned index = 0; // available on all menus switch (c) { case DELETE: // nothing variables["KEY"] = "delete"; break; case ENTER: // nothing variables["KEY"] = "enter"; break; case ESC: // go back variables["KEY"] = "esc"; break; case HELP: // print help variables["KEY"] = std::string({static_cast<char>(HELP)}); break; case QUIT: // quit app variables["KEY"] = std::string({static_cast<char>(std::toupper(QUIT))}); break; case STOP_ACTIVE_DOMAIN: // exit the active domain variables["KEY"] = std::string({static_cast<char>(std::toupper(STOP_ACTIVE_DOMAIN))}); break; case TALK: // tap-to-talk convenience variables["KEY"] = "space"; break; case STOP_FOREGROUND_ACTIVITY: variables["KEY"] = "!"; break; default: variables["KEY"] = std::string({static_cast<char>(std::toupper(c))}); // break range-based for loop for (auto& item : menuPtr->at("item")) { auto key = item.at("key").get<std::string>(); // required item.key if ((key == "delete") || (key == "DELETE")) { k = DELETE; } else if ((key == "enter") || (key == "ENTER")) { k = ENTER; } else if ((key == "esc") || (key == "ESC")) { k = ESC; } else { k = key[0]; } if (std::tolower(k) == std::tolower(c)) { break; } index++; } break; } if (index == menuPtr->at("item").size()) { printMenuText(applicationContext, console, "main", "keyTapError", variables); } else { printMenuText(applicationContext, console, "main", "keyTapped", variables); } if (menuPtr->count("item")) { unsigned char k = '\0'; unsigned index = 0; // break range-based for loop for (auto& item : menuPtr->at("item")) { if (!testMenuItem(applicationContext, item)) { continue; } auto key = item.at("key").get<std::string>(); // required item.key if (key == "esc" || key == "ESC") { k = ESC; } else { k = key[0]; } if (std::tolower(k) == std::tolower(c)) { if (item.count("note")) { // optional item.note printStringLine(console, "Note: " + item.at("note").get<std::string>(), variables); } auto action = item.at("do").get<std::string>(); // required item.do if (action.find("notify/") == 0) { auto eventId = action.substr(7); if (EventEnumerator.count(eventId)) { auto event = EventEnumerator.at(eventId); auto value = std::string{}; if (item.count("value")) { // optional item.value value = item.at("value").get<std::string>(); } if (event == Event::onAddAddressBookPhone || event == Event::onAddAddressBookAuto || event == Event::onLoadNavigationState || event == Event::onConversationsReport) { value = menuDirPath + '/' + value; } activity->notify(event, value); } else { console->printLine("Unknown eventId:", eventId); status = Status::Failure; } break; } else if (action == "AudioFile") { Ensures(item.count("name") == 1); // required item.name auto name = item.at("name").get<std::string>(); Ensures(item.count("value") == 1); // required item.value auto value = item.at("value").get<std::string>(); console->printLine(name); auto audioFilePath = menuDirPath + '/' + value; if (activity->notify(Event::onSpeechRecognizerStartStreamingAudioFile, audioFilePath)) { activity->notify(Event::onSpeechRecognizerTapToTalk); } break; } else if (action == "GoBack") { c = ESC; // go back break; } else if (action == "GoTo") { auto menuId = std::string{}; auto value = item.at("value"); // required item.value if (value.is_object()) { menuId = value.at("id").get<std::string>(); // required item.id } else { menuId = value.get<std::string>(); } stack.push_back(menuId); menuPtr = applicationContext->getMenuPtr(menuId); if (menuPtr && menuPtr->is_object()) { printMenu(applicationContext, engine, propertyManagerHandler, console, menuId); } else { console->printLine("Unknown menuId:", menuId); status = Status::Failure; } break; } else if (action == "Help") { c = HELP; // print help break; } else if (action == "Quit") { c = QUIT; // quit app break; } else if (action == "Restart") { console->printLine("Are you sure you want to restart Y/n?"); if ('Y' == static_cast<unsigned char>(fgetc(stdin))) { status = Status::Restart; } else { console->printLine("Aborted the restart"); } break; } else if (action == "Select") { menuPtr->at("index") = index; c = ESC; // go back break; } else if (action == "SetLocale") { auto value = item.at("value").get<std::string>(); // required item.value propertyManagerHandler->setProperty("aace.alexa.setting.locale", value); console->printLine("aace.alexa.setting.locale =", value); c = ESC; // go back break; } else if (action == "SetupCompleted") { activity->notify(Event::onDeviceSetupCompleted); break; } else if (action == "SetTimeZone") { auto value = item.at("value").get<std::string>(); // required item.value propertyManagerHandler->setProperty("aace.alexa.timezone", value); console->printLine("aace.alexa.timezone =", value); c = ESC; // go back break; } else if (action == "SetLoggerLevel") { // Note: Set level in logger handler (loggerHandler) auto value = item.at("value").get<std::string>(); // required item.value if (value == "VERBOSE") { applicationContext->setLevel(Level::VERBOSE); } else if (value == "INFO") { applicationContext->setLevel(Level::INFO); } else if (value == "METRIC") { applicationContext->setLevel(Level::METRIC); } else if (value == "WARN") { applicationContext->setLevel(Level::WARN); } else if (value == "ERROR") { applicationContext->setLevel(Level::ERROR); } else if (value == "CRITICAL") { applicationContext->setLevel(Level::CRITICAL); } else { applicationContext->clearLevel(); } c = ESC; // go back break; } else if (action == "SetProperty") { auto value = item.at("value").get<std::string>(); // required item.value static std::regex r("^([^/]+)/(.+)", std::regex::optimize); std::smatch sm{}; if (std::regex_match(value, sm, r) || ((sm.size() - 1) == 2)) { propertyManagerHandler->setProperty(sm[1], sm[2]); console->printLine(sm[1], "=", sm[2]); } c = ESC; // go back break; } else { console->printLine("Unknown action:", action); status = Status::Failure; break; } } index++; } // available on all menus switch (c) { case ESC: // go back if (stack.size() > 1) { stack.pop_back(); auto menuId = stack.back(); menuPtr = applicationContext->getMenuPtr(menuId); printMenu(applicationContext, engine, propertyManagerHandler, console, menuId); } break; case HELP: // print help printMenu(applicationContext, engine, propertyManagerHandler, console, stack.back()); break; case QUIT: // quit app status = Status::Success; break; case STOP_ACTIVE_DOMAIN: // exit the active domain activity->notify(Event::onStopActive); break; case TALK: // tap-to-talk convenience activity->notify(Event::onSpeechRecognizerTapToTalk); break; case STOP_FOREGROUND_ACTIVITY: activity->notify(Event::onStopForegroundActivity); break; default: break; } } if (status != Status::Unknown) { break; } } return status; } void Application::setupMenu( std::shared_ptr<ApplicationContext> applicationContext, std::shared_ptr<aace::core::Engine> engine, std::shared_ptr<sampleApp::propertyManager::PropertyManagerHandler> propertyManagerHandler, std::shared_ptr<View> console) { // recursive menu registration std::function<std::string( std::shared_ptr<ApplicationContext>, std::shared_ptr<aace::core::Engine>, std::shared_ptr<sampleApp::propertyManager::PropertyManagerHandler>, std::shared_ptr<View>, json&, std::string&)> f; f = [&f]( std::shared_ptr<ApplicationContext> applicationContext, std::shared_ptr<aace::core::Engine> engine, std::shared_ptr<sampleApp::propertyManager::PropertyManagerHandler> propertyManagerHandler, std::shared_ptr<View> console, json& menu, std::string& path) { menu["path"] = path; Ensures(menu.count("id") == 1); // required menu.id if (menu.at("id").get<std::string>() == "LOCALE") { // reserved id: LOCALE auto item = json::array(); /* * AVS-supported Locales: * https://developer.amazon.com/en-US/docs/alexa/alexa-voice-service/system.html#locales */ std::string supportedLocales = "de-DE,en-AU,en-CA,en-GB,en-IN,en-US,es-ES,es-MX,es-US,fr-CA,fr-FR,hi-IN,it-IT,ja-JP,pt-BR,en-CA/" "fr-CA,en-IN/hi-IN,en-US/es-US,es-US/en-US,fr-CA/en-CA,hi-IN/en-IN"; std::istringstream iss{supportedLocales}; auto token = std::string(); unsigned count = std::count(supportedLocales.begin(), supportedLocales.end(), ',') + 1; unsigned index = 0; while (std::getline(iss, token, ',')) { unsigned char k = '\0'; if (count < 10) { k = '1' + index; } else { // Note: 'Q' conflict k = 'A' + index; } auto key = std::string{static_cast<char>(k)}; item.push_back({{"do", "SetLocale"}, {"key", key}, {"name", token}, {"value", token}}); index++; } if (menu.count("item") && menu.at("item").is_array()) { // optional menu.item array item.insert(std::end(item), std::begin(menu.at("item")), std::end(menu.at("item"))); } menu.at("item") = item; } else if (menu.count("item") && menu.at("item").is_array()) { // optional menu.item array for (auto& item : menu.at("item")) { if (item.count("do") && item.at("do") == "GoTo") { if (item.count("value") && item.at("value").is_object()) { item.at("value") = f(applicationContext, engine, propertyManagerHandler, console, item.at("value"), path); } } } } auto id = menu.at("id").get<std::string>(); applicationContext->registerMenu(id, menu); return id; }; auto paths = applicationContext->getMenuFilePaths(); for (auto& path : paths) { // read a JSON file std::ifstream i(path); json menu; i >> menu; // // write prettified JSON to another file // std::ofstream o(path + ".json"); // o << std::setw(4) << menu << std::endl; if (menu.is_object()) { menu = json::array({menu}); } if (menu.is_array()) { for (auto& item : menu) { f(applicationContext, engine, propertyManagerHandler, console, item, path); } } else { console->printLine("Error: could not load menu", path); } } } bool Application::testMenuItem(std::shared_ptr<ApplicationContext> applicationContext, const json& item) { std::string name = item.count("test") ? "test" : item.count("when") ? "when" : ""; if (!name.empty()) { auto value = item.at(name).get<std::string>(); return applicationContext->testExpression(value); } return true; } } // namespace sampleApp
44.398544
130
0.574394
rtchagas
ecb7c6d66fe1eb824a85742af82296c143ad1762
355
cpp
C++
test/testUtil/testText/testXmlReader/main.cpp
wangsun1983/Obotcha
2464e53599305703f5150df72bf73579a39d8ef4
[ "MIT" ]
27
2019-04-27T00:51:22.000Z
2022-03-30T04:05:44.000Z
test/testUtil/testText/testXmlReader/main.cpp
wangsun1983/Obotcha
2464e53599305703f5150df72bf73579a39d8ef4
[ "MIT" ]
9
2020-05-03T12:17:50.000Z
2021-10-15T02:18:47.000Z
test/testUtil/testText/testXmlReader/main.cpp
wangsun1983/Obotcha
2464e53599305703f5150df72bf73579a39d8ef4
[ "MIT" ]
1
2019-04-16T01:45:36.000Z
2019-04-16T01:45:36.000Z
#include <stdio.h> #include <unistd.h> //#include "Thread.hpp" //#include "ArrayList.hpp" #include "Double.hpp" #include "XmlReader.hpp" #include "XmlValue.hpp" #include "XmlDocument.hpp" using namespace obotcha; extern void simpleattrtest(); extern void testsopenvreader(); int main() { simpleattrtest(); testsopenvreader(); return 0; }
16.136364
31
0.707042
wangsun1983
ecb83560d96c0efc06a2b37a053f835fe101b67b
4,356
cc
C++
modules/control/tools/control_tester.cc
Shokoofeh/apollo
71d6ea753b4595eb38cc54d6650c8de677b173df
[ "Apache-2.0" ]
7
2017-07-07T07:56:13.000Z
2019-03-06T06:27:00.000Z
modules/control/tools/control_tester.cc
Shokoofeh/apollo
71d6ea753b4595eb38cc54d6650c8de677b173df
[ "Apache-2.0" ]
null
null
null
modules/control/tools/control_tester.cc
Shokoofeh/apollo
71d6ea753b4595eb38cc54d6650c8de677b173df
[ "Apache-2.0" ]
2
2017-07-07T07:56:15.000Z
2018-08-10T17:13:34.000Z
/****************************************************************************** * Copyright 2017 The Apollo 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 "gflags/gflags.h" #include "cyber/cyber.h" #include "cyber/time/rate.h" #include "cyber/time/time.h" #include "cyber/common/log.h" #include "cyber/init.h" #include "modules/canbus/proto/chassis.pb.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/file.h" #include "modules/control/common/control_gflags.h" #include "modules/control/proto/pad_msg.pb.h" #include "modules/localization/proto/localization.pb.h" #include "modules/planning/proto/planning.pb.h" DEFINE_string( chassis_test_file, "/apollo/modules/control/testdata/control_tester/chassis.pb.txt", "Used for sending simulated Chassis content to the control node."); DEFINE_string( localization_test_file, "/apollo/modules/control/testdata/control_tester/localization.pb.txt", "Used for sending simulated localization to the control node."); DEFINE_string(pad_msg_test_file, "/apollo/modules/control/testdata/control_tester/pad_msg.pb.txt", "Used for sending simulated PadMsg content to the control node."); DEFINE_string( planning_test_file, "/apollo/modules/control/testdata/control_tester/planning.pb.txt", "Used for sending simulated Planning content to the control node."); DEFINE_int32(num_seconds, 10, "Length of execution."); DEFINE_int32(feed_frequency, 10, "Frequency with which protos are fed to control."); int main(int argc, char** argv) { using apollo::canbus::Chassis; using apollo::control::PadMessage; using apollo::cyber::Time; using apollo::localization::LocalizationEstimate; using apollo::planning::ADCTrajectory; using std::this_thread::sleep_for; google::ParseCommandLineFlags(&argc, &argv, true); apollo::cyber::Init(argv[0]); FLAGS_alsologtostderr = true; Chassis chassis; if (!apollo::common::util::GetProtoFromFile(FLAGS_chassis_test_file, &chassis)) { AERROR << "failed to load file: " << FLAGS_chassis_test_file; return -1; } LocalizationEstimate localization; if (!apollo::common::util::GetProtoFromFile(FLAGS_localization_test_file, &localization)) { AERROR << "failed to load file: " << FLAGS_localization_test_file; return -1; } PadMessage pad_msg; if (!apollo::common::util::GetProtoFromFile(FLAGS_pad_msg_test_file, &pad_msg)) { AERROR << "failed to load file: " << FLAGS_pad_msg_test_file; return -1; } ADCTrajectory trajectory; if (!apollo::common::util::GetProtoFromFile(FLAGS_planning_test_file, &trajectory)) { AERROR << "failed to load file: " << FLAGS_planning_test_file; return -1; } std::shared_ptr<apollo::cyber::Node> node( apollo::cyber::CreateNode("control_tester")); auto chassis_writer = node->CreateWriter<Chassis>(FLAGS_chassis_topic); auto localization_writer = node->CreateWriter<LocalizationEstimate>(FLAGS_localization_topic); auto pad_msg_writer = node->CreateWriter<PadMessage>(FLAGS_pad_topic); auto planning_writer = node->CreateWriter<ADCTrajectory>(FLAGS_planning_trajectory_topic); for (int i = 0; i < FLAGS_num_seconds * FLAGS_feed_frequency; ++i) { chassis_writer->Write(chassis); localization_writer->Write(localization); pad_msg_writer->Write(pad_msg); planning_writer->Write(trajectory); sleep_for(std::chrono::milliseconds(1000 / FLAGS_feed_frequency)); } AINFO << "Successfully fed proto files."; return 0; }
39.243243
80
0.682277
Shokoofeh
ecb8702fc4f218e0507758661ae4eb67c37f8ca8
2,141
cpp
C++
modules/task_1/chuvashov_a_frequency_symbol/frequency_symbol.cpp
ImKonstant/pp_2020_autumn_engineer
c8ac69681201b63f5cf8b6c6cd790f48f037532a
[ "BSD-3-Clause" ]
null
null
null
modules/task_1/chuvashov_a_frequency_symbol/frequency_symbol.cpp
ImKonstant/pp_2020_autumn_engineer
c8ac69681201b63f5cf8b6c6cd790f48f037532a
[ "BSD-3-Clause" ]
2
2020-11-14T18:00:55.000Z
2020-11-19T16:12:50.000Z
modules/task_1/chuvashov_a_frequency_symbol/frequency_symbol.cpp
ImKonstant/pp_2020_autumn_engineer
c8ac69681201b63f5cf8b6c6cd790f48f037532a
[ "BSD-3-Clause" ]
1
2020-10-10T09:54:14.000Z
2020-10-10T09:54:14.000Z
// Copyright 2020 Chuvashov Artem #include <mpi.h> #include <ctime> #include <random> #include <string> #include "../../../modules/task_1/chuvashov_a_frequency_symbol/frequency_symbol.h" std::string getString(int size) { std::mt19937 gen; gen.seed(static_cast<unsigned int>(time(0))); std::string str_res; str_res.resize(size); for (auto& smb : str_res) { smb = static_cast<char>(gen() % 100); } return str_res; } int parallelFrecSym(const std::string& general_str, char character, int size) { int frequency = 0; for (int j = 0; j < size; j++) { if (general_str[j] == character) { frequency++; } } return frequency; } int amountFrequencySymbol(const std::string& flow_str, char character, int Size) { int procsize, procrank; MPI_Comm_size(MPI_COMM_WORLD, &procsize); MPI_Comm_rank(MPI_COMM_WORLD, &procrank); if (Size < procsize) { if (procrank == 0) return parallelFrecSym(flow_str, character, Size); else return 0; } const int delta_ = Size / procsize; int Sizestr; if (procrank == procsize - 1) Sizestr = Size - (procsize - 1) * delta_; else Sizestr = delta_; if (procrank == 0 && procsize > 1) { for (int process = 1; process < procsize - 1; ++process) { MPI_Send(&flow_str[process * delta_], delta_, MPI_CHAR, process, 0, MPI_COMM_WORLD); } MPI_Send(&flow_str[(procsize - 1) * delta_], Size - (procsize - 1) * delta_, MPI_CHAR, procsize - 1, 0, MPI_COMM_WORLD); } int frequency_summa = 0; int local_summa = 0; std::string local_buf; local_buf.resize(delta_); if (procrank == 0) { local_summa = parallelFrecSym(flow_str, character, delta_); } else { MPI_Status status; MPI_Recv(&local_buf[0], Sizestr, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &status); local_summa = parallelFrecSym(local_buf, character, Sizestr); } MPI_Reduce(&local_summa, &frequency_summa, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); return frequency_summa; }
30.15493
87
0.6156
ImKonstant