hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
23466e263dde9ef46a3cf9510159df9fb3509fe5 | 3,518 | hpp | C++ | src/solvers/gecode/inspectors/dataflowinspector.hpp | castor-software/unison | 9f8caf78230f956a57b50a327f8d1dca5839bf64 | [
"BSD-3-Clause"
] | 88 | 2016-09-27T15:20:07.000Z | 2022-03-24T15:23:06.000Z | src/solvers/gecode/inspectors/dataflowinspector.hpp | castor-software/unison | 9f8caf78230f956a57b50a327f8d1dca5839bf64 | [
"BSD-3-Clause"
] | 55 | 2017-02-14T15:21:03.000Z | 2021-09-11T11:12:25.000Z | src/solvers/gecode/inspectors/dataflowinspector.hpp | castor-software/unison | 9f8caf78230f956a57b50a327f8d1dca5839bf64 | [
"BSD-3-Clause"
] | 10 | 2016-11-22T15:03:46.000Z | 2020-07-13T21:34:31.000Z | /*
* Main authors:
* Roberto Castaneda Lozano <rcas@acm.org>
*
* This file is part of Unison, see http://unison-code.github.io
*
* Copyright (c) 2016, RISE SICS AB
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __DATAFLOW_INSPECTOR__
#define __DATAFLOW_INSPECTOR__
#include <QtGui>
#include <gecode/gist.hh>
#include <graphviz/gvc.h>
#include "modelinspector.hpp"
#include "models/localmodel.hpp"
#include "dot.hpp"
enum NodeType {INACTIVE, UNDECIDEDACTIVENESS, ACTIVE};
enum EdgeType {FIXED, DISCARDED, POSSIBLE, ASSIGNED};
enum EdgeLabelType {DEAD, UNDECIDEDLIVENESS, LIVE};
class DataFlowGraph {
public:
Dot * graph;
map<EdgeId, EdgeType > edgeType;
map<EdgeId, EdgeLabelType > edgeLabelType;
map<EdgeId, QString > edgeLabel;
map<operation, NodeType > nodeType;
map<operation, vector<QString> > initialInstructions;
map<operation, vector<QString> > instructions;
DataFlowGraph() {
graph = new Dot();
}
~DataFlowGraph() {}
QString nodeLabel(operation o, bool ini = false) {
return "o" + QString::number(o) + ": " + showDomain(ops(o, ini));
}
QSize nodeLabelSize(operation o, double DPI) {
QFont f;
// TODO: set f to the right default font dynamically
f.setPointSize(28);
QFontMetrics fm(f);
QRect labRect = fm.boundingRect(nodeLabel(o, true));
double w = std::max((double)labRect.width(), DPI),
h = std::max((double)labRect.height(), DPI / 2);
return QSize(w, h);
}
vector<QString> ops(operation o, bool ini = false) {
return ini ? initialInstructions[o] : instructions[o];
}
};
class DataFlowInspector : public ModelInspector {
public:
std::string name(void);
DataFlowGraph dataFlowGraph(const Model& m, block b);
void draw(const Model& m, DataFlowGraph& dfg, const QPointF& topLeft);
};
class GlobalDataFlowInspector : public DataFlowInspector {
void inspect(const Space& s);
};
class LocalDataFlowInspector : public DataFlowInspector {
void inspect(const Space& s);
};
#endif
| 35.18 | 80 | 0.727686 | [
"vector",
"model"
] |
23480700825b4dc86684628a7f57ae87a8df20a1 | 2,619 | cpp | C++ | src/guidance.v2.02/libs/phylogeny/tests/bootstrap_test.cpp | jlanga/smsk_selection | 08070c6d4a6fbd9320265e1e698c95ba80f81123 | [
"MIT"
] | 4 | 2021-07-18T05:20:20.000Z | 2022-01-03T10:22:33.000Z | src/guidance.v2.02/libs/phylogeny/tests/bootstrap_test.cpp | jlanga/smsk_selection | 08070c6d4a6fbd9320265e1e698c95ba80f81123 | [
"MIT"
] | 1 | 2017-08-21T07:26:13.000Z | 2018-11-08T13:59:48.000Z | src/guidance.v2.02/libs/phylogeny/tests/bootstrap_test.cpp | jlanga/smsk_orthofinder | 08070c6d4a6fbd9320265e1e698c95ba80f81123 | [
"MIT"
] | 2 | 2021-07-18T05:20:26.000Z | 2022-03-31T18:23:31.000Z | #include "bootstrap.h"
#include "treeUtil.h"
#include "someUtil.h"
using namespace std;
int main()
{
cout << "creating a bootstrap object from a file"<<endl;
string filename("bootstrap_test.txt");
vector<tree> tv(getStartingTreeVecFromFile(filename));
// first constractor
cout << " first constractor"<<endl;
bootstrap b1(filename);
b1.print();
cout <<endl;
// secound constractor
cout << " secound constractor" <<endl;
bootstrap b2(tv);
b2.print();
cout <<endl;
cout << "getting weights from a tree" << endl;
map<int,MDOUBLE> v1(b1.getWeightsForTree(tv[0])) ;
for (map<int,MDOUBLE>::iterator i = v1.begin();i!=v1.end();++i)
cout << " "<<i->second;
cout << endl;
cout << "print the support of a tree" <<endl;
b1.printTreeWithBPvalues(cout, tv[0], v1);
cout <<endl <<endl;
cout<< "remove the first tree from the list, and use is as bases for additional computation"<<endl;
tree t(tv[0]);
cout<< "use the secound tree twice"<<endl;
tv[0]=tv[1];
// secound constractor
bootstrap b3(tv);
b3.print_names(cout);
b3.print();
map<int,MDOUBLE> v3(b3.getWeightsForTree(t)) ;
// for (map<int,MDOUBLE>::iterator i = v3.begin();i!=v3.end();++i)
// cout << " "<<i->second;
//cout << endl;
cout << "print the support of the removed tree"<<endl;
b3.printTreeWithBPvalues(cout, t, v3);
cout <<endl;
cout <<endl<<endl<<endl<<"compatability"<<endl;
tree t2(b3.consensusTree());
// cout << t2<<endl;
map<int,MDOUBLE> support(b3.getWeightsForTree(t2));
b3.printTreeWithBPvalues(cout, t2, support);
cout <<endl;
// for (map<int,MDOUBLE>::const_iterator ii= support.begin(); ii != support.end();++ii)
// cout << ii->second <<" ";
// cout << endl;
cout <<"compatability 0.0"<<endl;
t=b3.consensusTree(0.);
support=b3.getWeightsForTree(t);
b3.printTreeWithBPvalues(cout, t, support);
cout <<endl;
// for (map<int,MDOUBLE>::iterator i=support.begin();i!=support.end();++i)
// {
// cout << "<"<<i->first<<","<<i->second <<">:"<<support[i->first]<<endl;
// }
double c=0.8;
cout <<"compatability "<<c<<endl;
t=b3.consensusTree(c);
support=b3.getWeightsForTree(t);
b3.printTreeWithBPvalues(cout, t, support);
cout <<endl;
// for (map<int,MDOUBLE>::iterator i=support.begin();i!=support.end();++i)
// {
// cout << "<"<<i->first<<","<<i->second <<">:"<<support[i->first]<<endl;
// }
// for (map<int,MDOUBLE>::const_iterator i=support.begin();i!=support.end();++i)
// {
// cout << "<"<<i->first<<","<<">:"<<support[i->first]<<endl;
// }
return (0);
}
| 26.72449 | 101 | 0.607866 | [
"object",
"vector"
] |
234a6424bddcebc5b555aba84f40bf95460dc09e | 3,467 | cpp | C++ | tests/FileWritingTests.cpp | heartofrain/AudioFile | 004065d01e9b7338580390d4fdbfbaa46adede4e | [
"MIT"
] | 1 | 2022-03-31T14:30:22.000Z | 2022-03-31T14:30:22.000Z | AudioFile/tests/FileWritingTests.cpp | DGoldDragon28/fir1 | 69209f13e453d24290750851345b38f38c657782 | [
"MIT"
] | null | null | null | AudioFile/tests/FileWritingTests.cpp | DGoldDragon28/fir1 | 69209f13e453d24290750851345b38f38c657782 | [
"MIT"
] | null | null | null | #include "doctest.h"
#include <iostream>
#include <vector>
#include <cmath>
#include <AudioFile.h>
//=============================================================
const std::string projectBuildDirectory = PROJECT_BINARY_DIR;
//=============================================================
// Writes an audio file with a given number of channels, sample rate, bit deoth and format
// Returns true if it was successful
bool writeTestAudioFile (int numChannels, int sampleRate, int bitDepth, AudioFileFormat format)
{
float sampleRateAsFloat = (float) sampleRate;
AudioFile<float> audioFile;
audioFile.setAudioBufferSize (numChannels, sampleRate * 4);
for (int i = 0; i < audioFile.getNumSamplesPerChannel(); i++)
{
float sample = sinf (2. * M_PI * ((float) i / sampleRateAsFloat) * 440.) ;
for (int k = 0; k < audioFile.getNumChannels(); k++)
audioFile.samples[k][i] = sample * 0.5;
}
audioFile.setSampleRate (sampleRate);
audioFile.setBitDepth (bitDepth);
std::string numChannelsAsString;
if (numChannels == 1)
numChannelsAsString = "mono";
else if (numChannels == 2)
numChannelsAsString = "stereo";
else
numChannelsAsString = std::to_string (numChannels) + " channels";
std::string bitDepthAsString = std::to_string (bitDepth);
std::string sampleRateAsString = std::to_string (sampleRate);
if (format == AudioFileFormat::Wave)
{
return audioFile.save (projectBuildDirectory + "/audio-write-tests/" + numChannelsAsString + "_" + sampleRateAsString + "_" + bitDepthAsString + "bit" + ".wav", format);
}
else if (format == AudioFileFormat::Aiff)
{
return audioFile.save (projectBuildDirectory + "/audio-write-tests/" + numChannelsAsString + "_" + sampleRateAsString + "_" + bitDepthAsString + "bit" + ".aif", format);
}
return false;
}
//=============================================================
TEST_SUITE ("Writing Tests")
{
#if PEFORM_TEST_WRITE_TO_ALL_FORMATS
//=============================================================
TEST_CASE ("WritingTest::WriteSineToneToManyFormats")
{
std::vector<int> sampleRates = {22050, 44100, 48000, 96000};
std::vector<int> bitDepths = {8, 16, 24, 32};
std::vector<int> numChannels = {1, 2, 8};
std::vector<AudioFileFormat> audioFormats = {AudioFileFormat::Wave, AudioFileFormat::Aiff};
for (auto& sampleRate : sampleRates)
{
for (auto& bitDepth : bitDepths)
{
for (auto& channels : numChannels)
{
for (auto& format : audioFormats)
{
CHECK (writeTestAudioFile (channels, sampleRate, bitDepth, format));
}
}
}
}
}
#endif
//=============================================================
TEST_CASE ("WritingTest::WriteFromCopiedSampleBuffer")
{
AudioFile<float> audioFile1, audioFile2;
bool loadedOK = audioFile1.load (projectBuildDirectory + "/test-audio/wav_stereo_16bit_44100.wav");
CHECK (loadedOK);
audioFile2.setAudioBuffer (audioFile1.samples);
bool savedOK = audioFile2.save (projectBuildDirectory + "/audio-write-tests/copied_audio_file.aif", AudioFileFormat::Aiff);
CHECK (savedOK);
}
}
| 35.020202 | 177 | 0.563311 | [
"vector"
] |
054c11863ade986b46b4a0fe4b5cf42ab75ff7c5 | 3,690 | cpp | C++ | src/base/cef/cef_app.cpp | devcxx/zephyros | 3ba2c63c5d11bfab66b896e8e09287e222f645a2 | [
"Unlicense",
"MIT"
] | null | null | null | src/base/cef/cef_app.cpp | devcxx/zephyros | 3ba2c63c5d11bfab66b896e8e09287e222f645a2 | [
"Unlicense",
"MIT"
] | null | null | null | src/base/cef/cef_app.cpp | devcxx/zephyros | 3ba2c63c5d11bfab66b896e8e09287e222f645a2 | [
"Unlicense",
"MIT"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2015-2017 Vanamco AG, http://www.vanamco.com
*
* The MIT License (MIT)
* 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.
*
* Contributors:
* Matthias Christen, Vanamco AG
*******************************************************************************/
#include <stdio.h>
#include <cstdlib>
#include <sstream>
#include <string>
#include "lib/cef/include/cef_app.h"
#include "lib/cef/include/cef_browser.h"
#include "lib/cef/include/cef_command_line.h"
#include "lib/cef/include/cef_frame.h"
#include "lib/cef/include/cef_web_plugin.h"
#include "base/app.h"
#include "base/cef/client_handler.h"
CefRefPtr<Zephyros::ClientHandler> g_handler;
CefRefPtr<CefCommandLine> g_command_line;
WindowCreatedCallback g_windowCreatedCallback;
namespace Zephyros {
namespace App {
CefRefPtr<CefBrowser> GetBrowser()
{
if (!g_handler.get())
return NULL;
return g_handler->GetBrowser();
}
ClientWindowHandle GetMainHwnd()
{
if (!g_handler.get())
return NULL;
return g_handler->GetMainHwnd();
}
void InitCommandLine(int argc, const char* const* argv)
{
g_command_line = CefCommandLine::CreateCommandLine();
#if defined(OS_WIN)
g_command_line->InitFromString(::GetCommandLineW());
#else
g_command_line->InitFromArgv(argc, argv);
#endif
}
/**
* Returns the application command line object.
*/
CefRefPtr<CefCommandLine> GetCommandLine()
{
return g_command_line;
}
/**
* Returns the application settings based on command line arguments.
*/
void GetSettings(CefSettings& settings)
{
DCHECK(g_command_line.get());
if (!g_command_line.get())
return;
settings.no_sandbox = true;
#ifdef OS_MACOSX
settings.single_process = true;
#endif
#if defined(OS_WIN)
settings.multi_threaded_message_loop = false;
#endif
// CefString(&settings.cache_path) = g_command_line->GetSwitchValue(cefclient::kCachePath);
#if !defined(NDEBUG) && !defined(ZEPHYROS_NDEBUG)
// Specify a port to enable DevTools if one isn't already specified.
if (!g_command_line->HasSwitch("remote-debugging-port"))
settings.remote_debugging_port = 19384;
#else
settings.remote_debugging_port = 0;
#endif
// set the logging severity
#if !defined(NDEBUG) && !defined(ZEPHYROS_NDEBUG)
settings.log_severity = LOGSEVERITY_VERBOSE;
#else
settings.log_severity = LOGSEVERITY_WARNING;
//settings.log_severity = LOGSEVERITY_VERBOSE;
#endif
}
void SetWindowCreatedCallback(const WindowCreatedCallback& callback)
{
g_windowCreatedCallback = callback;
}
} // namespace App
} // namespace Zephyros
| 29.055118 | 95 | 0.711653 | [
"object"
] |
0550307d006883915b379fc85a627d1bbd13d69a | 23,572 | hpp | C++ | src/AST/AST.hpp | Naios/swy | c48f7eb4322aa7fd44a3bb82259787b89292733b | [
"Apache-2.0"
] | 19 | 2017-06-04T09:39:51.000Z | 2021-11-16T10:14:45.000Z | src/AST/AST.hpp | Naios/swy | c48f7eb4322aa7fd44a3bb82259787b89292733b | [
"Apache-2.0"
] | null | null | null | src/AST/AST.hpp | Naios/swy | c48f7eb4322aa7fd44a3bb82259787b89292733b | [
"Apache-2.0"
] | 1 | 2019-03-19T02:24:40.000Z | 2019-03-19T02:24:40.000Z |
/**
Copyright(c) 2016 - 2017 Denis Blank <denis.blank at outlook dot com>
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.
**/
#ifndef AST_HPP_INCLUDED__
#define AST_HPP_INCLUDED__
#include <array>
#include <cstdint>
#include <vector>
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Casting.h"
#include "ASTFragment.hpp"
#include "Nullable.hpp"
#include "SourceAnnotated.hpp"
#include "SourceLocation.hpp"
class ASTNode;
class StmtASTNode;
class ExprASTNode;
#define FOR_EACH_AST_NODE(NAME) class NAME##ASTNode;
#include "AST.inl"
class ConsistentASTScope;
class ConstantExprASTNode;
/// Defines the kind of the ASTNode which is one of the basic types
enum class ASTKind {
#define FOR_EACH_AST_NODE(NAME) Kind##NAME,
#include "AST.inl"
};
/// A sequence to iterate of the children of the ASTNode
using ASTChildSequence = llvm::SmallVector<ASTNode*, 10>;
/// A const sequence to iterate of the children of the ASTNode
using ConstASTChildSequence = llvm::SmallVector<ASTNode const*, 10>;
/// Represents the base class of an every AST node
class ASTNode : public ASTFragment {
ASTKind const kind_;
public:
explicit ASTNode(ASTKind kind) : kind_(kind) {}
/// Returns the kind of the ASTNode
ASTKind getKind() const { return kind_; }
/// Returns true when the ASTNode is of the given type
bool isKind(ASTKind kind) const { return getKind() == kind; }
};
/// Provides access to a name declaring node
class NamedDeclContext {
Identifier name_;
public:
explicit NamedDeclContext(Identifier const& name) : name_(name) {}
virtual ~NamedDeclContext() = default;
/// Returns the identifier of the node that represents the name
Identifier const& getName() const { return name_; }
/// Returns the name associated to the name
virtual ASTNode* getDeclaringNode() = 0;
/// Returns the name associated to the name
virtual ASTNode const* getDeclaringNode() const = 0;
/// Returns true when the declaration is a function
bool isFunctionDecl() const;
/// Returns true when the declaration is a variable
bool isVarDecl() const;
/// Returns true when the declaration is a meta decl
bool isMetaDecl() const;
/// Returns true when the declaration is a global constant
bool isGlobalConstant() const;
};
/// Generalized base class for all top level container ASTNode's such as:
/// - CompilationUnitASTNode
/// - MetaUnitASTNode
class UnitASTNode {
NonNull<ConsistentASTScope*> scope_;
std::vector<ASTNode*> children_;
public:
UnitASTNode() = default;
virtual ~UnitASTNode() = default;
void setScope(ConsistentASTScope* scope) { scope_ = scope; }
ConsistentASTScope const* getScope() const { return *scope_; }
void addChild(ASTNode* child) { children_.push_back(child); }
llvm::ArrayRef<ASTNode*> children() { return children_; }
llvm::ArrayRef<ASTNode const*> children() const { return children_; }
};
/// Generalized base class for top level ASTNodes which are
/// contained in a UnitASTNode such as:
/// - MetaUnitASTNode
/// - FunctionDeclASTNode
/// - MetaDeclASTNode
class TopLevelASTNode {
NonNull<ASTNode const*> containingUnit_;
public:
TopLevelASTNode() = default;
virtual ~TopLevelASTNode() = default;
void setContainingUnit(ASTNode const* node) { containingUnit_ = node; }
ASTNode const* getContainingUnit() const { return *containingUnit_; }
};
/// Represents a compilation unit of a source file
class CompilationUnitASTNode : public ASTNode, public UnitASTNode {
public:
explicit CompilationUnitASTNode() : ASTNode(ASTKind::KindCompilationUnit) {}
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindCompilationUnit);
}
};
/// Represents the result of an evaluation of a MetaDecl
class MetaUnitASTNode : public ASTNode,
public UnitASTNode,
public TopLevelASTNode,
public IntermediateNode {
NonNull<MetaInstantiationExprASTNode const*> instantiation_;
Nullable<ASTNode*> exportedNode_;
public:
explicit MetaUnitASTNode(MetaInstantiationExprASTNode const* instantiation)
: ASTNode(ASTKind::KindMetaUnit), instantiation_(instantiation) {}
MetaInstantiationExprASTNode const* getInstantiation() const {
return *instantiation_;
}
void setExportedNode(ASTNode* node) { exportedNode_ = node; }
Nullable<ASTNode*> getExportedNode() { return exportedNode_; }
Nullable<ASTNode const*> getExportedNode() const { return exportedNode_; }
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindMetaUnit);
}
};
/// Represents the declaration of a function
class FunctionDeclASTNode : public ASTNode,
public TopLevelASTNode,
public NamedDeclContext {
NonNull<ArgumentDeclListASTNode*> arguments_;
Nullable<AnonymousArgumentDeclASTNode*> returnType_;
StmtASTNode* body_ = nullptr;
public:
explicit FunctionDeclASTNode(Identifier const& name)
: ASTNode(ASTKind::KindFunctionDecl), NamedDeclContext(name) {}
void setArgDeclList(ArgumentDeclListASTNode* arguments) {
arguments_ = arguments;
}
ArgumentDeclListASTNode* getArgDeclList() { return *arguments_; }
ArgumentDeclListASTNode* getArgDeclList() const { return *arguments_; }
void setReturnType(AnonymousArgumentDeclASTNode* returnType) {
assert(!returnType_ && "Return Type already set!");
returnType_ = returnType;
}
Nullable<AnonymousArgumentDeclASTNode*> getReturnType() {
return returnType_;
}
Nullable<AnonymousArgumentDeclASTNode const*> getReturnType() const {
return returnType_;
}
void setBody(StmtASTNode* body) { body_ = body; }
StmtASTNode* getBody() { return body_; }
StmtASTNode const* getBody() const { return body_; }
ASTNode* getDeclaringNode() override { return this; }
ASTNode const* getDeclaringNode() const override { return this; }
llvm::SmallVector<ASTNode*, 3> children();
llvm::SmallVector<ASTNode const*, 3> children() const;
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindFunctionDecl);
}
};
/// Represents a list of AnonymousArgumentDeclASTNode
class ArgumentDeclListASTNode : public ASTNode {
llvm::SmallVector<AnonymousArgumentDeclASTNode*, 2> arguments_;
public:
explicit ArgumentDeclListASTNode() : ASTNode(ASTKind::KindArgumentDeclList) {}
void addArgument(AnonymousArgumentDeclASTNode* argument) {
arguments_.push_back(argument);
}
llvm::ArrayRef<AnonymousArgumentDeclASTNode*> children() {
return arguments_;
}
llvm::ArrayRef<AnonymousArgumentDeclASTNode const*> children() const {
return arguments_;
}
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindArgumentDeclList);
}
};
/// Represents the definition of a function argument or
/// return type which is not named (anonymous).
class AnonymousArgumentDeclASTNode : public ASTNode {
// Type isn't stored because we only allow int
// NamedDeclASTNode* type_;
public:
explicit AnonymousArgumentDeclASTNode(
ASTKind kind = ASTKind::KindAnonymousArgumentDecl)
: ASTNode(kind) {}
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindAnonymousArgumentDecl) ||
node->isKind(ASTKind::KindNamedArgumentDecl);
}
};
/// Represents the definition of a function argument or
/// return type which is named.
class NamedArgumentDeclASTNode : public AnonymousArgumentDeclASTNode,
public NamedDeclContext {
public:
explicit NamedArgumentDeclASTNode(Identifier const& name)
: AnonymousArgumentDeclASTNode(ASTKind::KindNamedArgumentDecl),
NamedDeclContext(name) {}
ASTNode* getDeclaringNode() override { return this; }
ASTNode const* getDeclaringNode() const override { return this; }
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindNamedArgumentDecl);
}
};
/// Represents the declaration of a meta scope
class MetaDeclASTNode : public ASTNode,
public TopLevelASTNode,
public NamedDeclContext,
public IntermediateNode {
NonNull<ArgumentDeclListASTNode*> arguments_;
Nullable<MetaContributionASTNode*> contribution_;
public:
explicit MetaDeclASTNode(Identifier const& name)
: ASTNode(ASTKind::KindMetaDecl), NamedDeclContext(name) {}
void setArgDeclList(ArgumentDeclListASTNode* arguments) {
arguments_ = arguments;
}
ArgumentDeclListASTNode* getArgDeclList() { return *arguments_; }
ArgumentDeclListASTNode* getArgDeclList() const { return *arguments_; }
/// Sets the meta contribution of this node
void setMetaContribution(MetaContributionASTNode* contribution) {
contribution_ = contribution;
}
/// Returns the meta contribution of this node
MetaContributionASTNode* getContribution() { return *contribution_; }
/// Returns the meta contribution of this node
MetaContributionASTNode const* getContribution() const {
return *contribution_;
}
ASTNode* getDeclaringNode() override { return this; }
ASTNode const* getDeclaringNode() const override { return this; }
std::array<ASTNode*, 2> children();
std::array<ASTNode const*, 2> children() const;
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindMetaDecl);
}
};
/// Represents a global constant declaration
class GlobalConstantDeclASTNode : public ASTNode,
public TopLevelASTNode,
public NamedDeclContext {
NonNull<ConstantExprASTNode*> expression_;
public:
explicit GlobalConstantDeclASTNode(Identifier const& name)
: ASTNode(ASTKind::KindGlobalConstantDecl), NamedDeclContext(name) {}
void setExpression(ConstantExprASTNode* expression) {
expression_ = expression;
}
ConstantExprASTNode* getExpression() { return *expression_; }
ConstantExprASTNode const* getExpression() const { return *expression_; }
ASTNode* getDeclaringNode() override { return this; }
ASTNode const* getDeclaringNode() const override { return this; }
std::array<ConstantExprASTNode*, 1> children() { return {{*expression_}}; }
std::array<ConstantExprASTNode const*, 1> children() const {
return {{*expression_}};
}
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindGlobalConstantDecl);
}
};
/// Represents a node which contributes it's child nodes when
/// instantiated in a meta declaration.
class MetaContributionASTNode : public ASTNode, public IntermediateNode {
SourceRange range_;
ASTChildSequence children_;
public:
explicit MetaContributionASTNode(SourceRange range)
: ASTNode(ASTKind::KindMetaContribution), range_(range) {}
SourceRange getSourceRange() const { return range_; }
/// Adds a ASTNode as child
void addChild(ASTNode* node) { children_.push_back(node); }
llvm::ArrayRef<ASTNode*> children() { return children_; }
llvm::ArrayRef<ASTNode const*> children() const { return children_; }
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindMetaContribution);
}
};
/// Represents a single (one line) statement
class StmtASTNode : public ASTNode {
public:
explicit StmtASTNode(ASTKind kind) : ASTNode(kind) {}
static bool classof(ASTNode const* node);
};
class BasicCompoundStmtASTNode : public StmtASTNode {
llvm::SmallVector<StmtASTNode*, 12> statements_;
public:
explicit BasicCompoundStmtASTNode(ASTKind kind) : StmtASTNode(kind) {}
void addStatement(StmtASTNode* statement) {
statements_.push_back(statement);
}
llvm::ArrayRef<StmtASTNode*> children() { return statements_; }
llvm::ArrayRef<StmtASTNode const*> children() const { return statements_; }
};
/// Represents multiple statements which lie in it's own scope
class CompoundStmtASTNode : public BasicCompoundStmtASTNode {
public:
CompoundStmtASTNode() : BasicCompoundStmtASTNode(ASTKind::KindCompoundStmt) {}
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindCompoundStmt);
}
};
/// Statements that are stored together which rely in the same scope as
/// it's neighbors.
class UnscopedCompoundStmtASTNode : public BasicCompoundStmtASTNode {
public:
UnscopedCompoundStmtASTNode()
: BasicCompoundStmtASTNode(ASTKind::KindUnscopedCompoundStmt) {}
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindUnscopedCompoundStmt);
}
};
/// A return statement which returns a certain expression
class ReturnStmtASTNode : public StmtASTNode {
Nullable<ExprASTNode*> expression_;
public:
explicit ReturnStmtASTNode() : StmtASTNode(ASTKind::KindReturnStmt) {}
void setExpression(ExprASTNode* expr) { expression_ = expr; }
Nullable<ExprASTNode*> getExpression() { return expression_; }
Nullable<ExprASTNode const*> getExpression() const { return expression_; }
Nullable<ExprASTNode*> children() { return expression_; }
Nullable<ExprASTNode const*> children() const { return expression_; }
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindReturnStmt);
}
};
template <typename T> class BasicIfStmtASTNode : public StmtASTNode {
NonNull<ExprASTNode*> expression_;
NonNull<T*> trueBranch_;
Nullable<T*> falseBranch_;
public:
explicit BasicIfStmtASTNode(ASTKind kind) : StmtASTNode(kind) {}
void setExpression(ExprASTNode* expression) { expression_ = expression; }
ExprASTNode* getExpression() { return *expression_; }
ExprASTNode const* getExpression() const { return *expression_; }
void setTrueBranch(T* trueBranch) { trueBranch_ = trueBranch; }
T* getTrueBranch() { return *trueBranch_; }
T const* getTrueBranch() const { return *trueBranch_; }
void setFalseBranch(T* falseBranch) { falseBranch_ = falseBranch; }
Nullable<T*> getFalseBranch() { return falseBranch_; }
Nullable<T const*> getFalseBranch() const { return falseBranch_; }
llvm::SmallVector<ASTNode*, 3> children() {
llvm::SmallVector<ASTNode*, 3> seq{*expression_, *trueBranch_};
if (falseBranch_) {
seq.push_back(*falseBranch_);
}
return seq;
}
llvm::SmallVector<ASTNode const*, 3> children() const {
llvm::SmallVector<ASTNode const*, 3> seq{*expression_, *trueBranch_};
if (falseBranch_) {
seq.push_back(*falseBranch_);
}
return seq;
}
};
/// A conditional if statement
class IfStmtASTNode : public BasicIfStmtASTNode<StmtASTNode> {
public:
explicit IfStmtASTNode() : BasicIfStmtASTNode(ASTKind::KindIfStmt) {}
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindIfStmt);
}
};
/// A conditional meta if statement which makes it's AST children available
/// dependent on the given expression
class MetaIfStmtASTNode : public BasicIfStmtASTNode<MetaContributionASTNode>,
public IntermediateNode {
public:
explicit MetaIfStmtASTNode() : BasicIfStmtASTNode(ASTKind::KindMetaIfStmt) {}
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindMetaIfStmt);
}
};
/// A statement which evaluates an expression with dropping the result
class ExpressionStmtASTNode : public StmtASTNode {
NonNull<ExprASTNode*> expression_;
public:
explicit ExpressionStmtASTNode() : StmtASTNode(ASTKind::KindExpressionStmt) {}
void setExpression(ExprASTNode* expression) { expression_ = expression; }
ExprASTNode* getExpression() { return *expression_; }
ExprASTNode const* getExpression() const { return *expression_; }
std::array<ExprASTNode*, 1> children();
std::array<ExprASTNode const*, 1> children() const;
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindExpressionStmt);
}
};
/// Represents a variable declaration
class DeclStmtASTNode : public StmtASTNode, public NamedDeclContext {
NonNull<ExprASTNode*> expression_;
public:
explicit DeclStmtASTNode(Identifier const& name)
: StmtASTNode(ASTKind::KindDeclStmt), NamedDeclContext(name) {}
void setExpression(ExprASTNode* expression) { expression_ = expression; }
ExprASTNode* getExpression() { return *expression_; }
ExprASTNode const* getExpression() const { return *expression_; }
ASTNode* getDeclaringNode() override { return this; }
ASTNode const* getDeclaringNode() const override { return this; }
std::array<ExprASTNode*, 1> children();
std::array<ExprASTNode const*, 1> children() const;
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindDeclStmt);
}
};
/// A statement which is evaluated at compile-time and that makes
/// it's variables available to scopes below.
class MetaCalculationStmtASTNode : public StmtASTNode, public IntermediateNode {
NonNull<StmtASTNode*> stmt_;
llvm::SmallVector<NamedDeclContext*, 5> exportedDecls_;
public:
explicit MetaCalculationStmtASTNode()
: StmtASTNode(ASTKind::KindMetaCalculationStmt) {}
void setStmt(StmtASTNode* stmt) { stmt_ = stmt; }
StmtASTNode* getStmt() { return *stmt_; }
StmtASTNode const* getStmt() const { return *stmt_; }
std::array<StmtASTNode*, 1> children();
std::array<StmtASTNode const*, 1> children() const;
void addExportedDecl(NamedDeclContext* decl) {
exportedDecls_.push_back(decl);
}
llvm::ArrayRef<NamedDeclContext*> getExportedDecls() {
return exportedDecls_;
}
llvm::ArrayRef<NamedDeclContext const*> getExportedDecls() const {
return exportedDecls_;
}
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindMetaCalculationStmt);
}
};
/// An expression which can be composed from other expressions
class ExprASTNode : public ASTNode {
public:
explicit ExprASTNode(ASTKind kind) : ASTNode(kind) {}
static bool classof(ASTNode const* node);
};
/// References a visible declaration
class DeclRefExprASTNode : public ExprASTNode {
Identifier name_;
Nullable<NamedDeclContext*> decl_;
public:
explicit DeclRefExprASTNode(Identifier const& name)
: ExprASTNode(ASTKind::KindDeclRefExpr), name_(name) {}
Identifier const& getName() const { return name_; }
void setDecl(NamedDeclContext* decl) { decl_ = decl; }
Nullable<NamedDeclContext*> getDecl() const { return decl_; }
/// Returns true when the decl ref is resolved
bool isResolved() const { return bool(decl_); }
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindDeclRefExpr);
}
};
class MetaInstantiationExprASTNode : public ExprASTNode {
NonNull<DeclRefExprASTNode*> decl_;
llvm::SmallVector<ExprASTNode*, 3> arguments_;
SourceRange range_;
public:
explicit MetaInstantiationExprASTNode(SourceRange range)
: ExprASTNode(ASTKind::KindMetaInstantiationExpr), range_(range) {}
void setDecl(DeclRefExprASTNode* decl) { decl_ = decl; }
DeclRefExprASTNode* getDecl() { return *decl_; }
DeclRefExprASTNode const* getDecl() const { return *decl_; }
void addArgument(ExprASTNode* node) { arguments_.push_back(node); }
llvm::ArrayRef<ExprASTNode*> getArguments() { return arguments_; }
llvm::ArrayRef<ExprASTNode const*> getArguments() const { return arguments_; }
llvm::SmallVector<ExprASTNode*, 4> children();
llvm::SmallVector<ExprASTNode const*, 4> children() const;
SourceRange getSourceRange() const { return range_; }
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindMetaInstantiationExpr);
}
};
/// References a constant expression
class ConstantExprASTNode : public ExprASTNode {
public:
explicit ConstantExprASTNode(ASTKind kind) : ExprASTNode(kind) {}
};
/// References an integer literal
class IntegerLiteralExprASTNode : public ConstantExprASTNode {
RangeAnnotated<std::int32_t> literal_;
public:
explicit IntegerLiteralExprASTNode(
RangeAnnotated<std::int32_t> const& literal)
: ConstantExprASTNode(ASTKind::KindIntegerLiteralExpr),
literal_(literal) {}
RangeAnnotated<std::int32_t> getLiteral() const { return literal_; }
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindIntegerLiteralExpr);
}
};
/// References an integer literal
class BooleanLiteralExprASTNode : public ConstantExprASTNode {
RangeAnnotated<bool> literal_;
public:
explicit BooleanLiteralExprASTNode(RangeAnnotated<bool> literal)
: ConstantExprASTNode(ASTKind::KindBooleanLiteralExpr),
literal_(literal) {}
RangeAnnotated<bool> getLiteral() const { return literal_; }
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindBooleanLiteralExpr);
}
};
/// Represents an error expression to keep the AST valid
class ErroneousExprASTNode : public ExprASTNode {
public:
ErroneousExprASTNode() : ExprASTNode(ASTKind::KindErroneousExpr) {}
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindErroneousExpr);
}
};
/// Represents the operator of a binary operation
enum class ExprBinaryOperator {
#define EXPR_BINARY_OPERATOR(NAME, REP, ...) Operator##NAME,
#include "AST.inl"
};
/// References a binary operator call
class BinaryOperatorExprASTNode : public ExprASTNode {
RangeAnnotated<ExprBinaryOperator> binaryOperator_;
NonNull<ExprASTNode*> left_;
NonNull<ExprASTNode*> right_;
public:
explicit BinaryOperatorExprASTNode(
RangeAnnotated<ExprBinaryOperator> binaryOperator)
: ExprASTNode(ASTKind::KindBinaryOperatorExpr),
binaryOperator_(binaryOperator) {}
RangeAnnotated<ExprBinaryOperator> const& getBinaryOperator() const {
return binaryOperator_;
}
void setLeftExpr(ExprASTNode* left) { left_ = left; }
ExprASTNode* getLeftExpr() { return *left_; }
ExprASTNode const* getLeftExpr() const { return *left_; }
void setRightExpr(ExprASTNode* right) { right_ = right; }
ExprASTNode* getRightExpr() { return *right_; }
ExprASTNode const* getRightExpr() const { return *right_; }
std::array<ExprASTNode*, 2> children();
std::array<ExprASTNode const*, 2> children() const;
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindBinaryOperatorExpr);
}
};
/// References a call operator
class CallOperatorExprASTNode : public ExprASTNode {
NonNull<ExprASTNode*> callee_;
llvm::SmallVector<ExprASTNode*, 3> expressions_;
public:
CallOperatorExprASTNode() : ExprASTNode(ASTKind::KindCallOperatorExpr) {}
void setCallee(ExprASTNode* callee) { callee_ = callee; }
ExprASTNode* getCallee() { return *callee_; }
ExprASTNode const* getCallee() const { return *callee_; }
void addExpression(ExprASTNode* expr) { expressions_.push_back(expr); }
llvm::ArrayRef<ExprASTNode*> getExpressions() { return expressions_; }
llvm::ArrayRef<ExprASTNode const*> getExpressions() const {
return expressions_;
}
ASTChildSequence children();
ConstASTChildSequence children() const;
static bool classof(ASTNode const* node) {
return node->isKind(ASTKind::KindCallOperatorExpr);
}
};
// AST.hpp
// ASTNode.hpp
// ASTDeclNode.hpp
// ASTStmtNode.hpp
// ASTExprNode.hpp
#endif // #ifndef AST_HPP_INCLUDED__
| 32.246238 | 80 | 0.735746 | [
"vector"
] |
055343f08e96bcf37c112c39ad28c690abf9955d | 17,215 | cpp | C++ | Direct3D/StateManager/EffectStateManager.cpp | walbourn/directx-sdk-legacy-samples | 93e8cc554b5ecb5cd574a06071ed784b6cb73fc5 | [
"MIT"
] | 27 | 2021-03-01T23:50:39.000Z | 2022-03-04T03:27:17.000Z | Direct3D/StateManager/EffectStateManager.cpp | walbourn/directx-sdk-legacy-samples | 93e8cc554b5ecb5cd574a06071ed784b6cb73fc5 | [
"MIT"
] | 3 | 2021-03-02T00:39:56.000Z | 2021-12-02T19:50:03.000Z | Direct3D/StateManager/EffectStateManager.cpp | walbourn/directx-sdk-legacy-samples | 93e8cc554b5ecb5cd574a06071ed784b6cb73fc5 | [
"MIT"
] | 3 | 2021-03-29T16:23:54.000Z | 2022-03-05T08:35:05.000Z | //--------------------------------------------------------------------------------------
// File: EffectStateManager.h
//
// Implementation of a custom ID3DXEffectStateManager interface.
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License (MIT).
//--------------------------------------------------------------------------------------
#include "DXUT.h"
#pragma warning(disable: 4995)
#include "EffectStateManager.h"
//--------------------------------------------------------------------------------------
// STL dependancies
//--------------------------------------------------------------------------------------
#pragma warning ( push )
#pragma warning ( disable : 4512 ) // 'class' : assignment operator could not be generated
#pragma warning ( disable : 4702 ) // unreachable code
#include <map>
#include <vector>
#pragma warning ( pop )
using std::map;
using std::vector;
#pragma warning(default: 4995)
//--------------------------------------------------------------------------------------
// Base implementation of a custom ID3DXEffectStateManager interface
// This implementation does nothing more than forward all state change commands to the
// appropriate D3D handler.
// An interface that implements custom state change handling may be derived from this
// (such as statistical collection, or filtering of redundant state change commands for
// a subset of states)
//--------------------------------------------------------------------------------------
class CBaseStateManager :
public CStateManagerInterface
{
protected:
LPDIRECT3DDEVICE9 m_pDevice;
LONG m_lRef;
UINT m_nTotalStateChanges;
UINT m_nTotalStateChangesPerFrame;
WCHAR m_wszFrameStats[256];
public:
CBaseStateManager( LPDIRECT3DDEVICE9 pDevice )
: m_lRef( 1UL ),
m_pDevice( pDevice ),
m_nTotalStateChanges( 0 ),
m_nTotalStateChangesPerFrame( 0 )
{
// Increment the reference count on the device, because a pointer to it has
// been copied for later use
m_pDevice->AddRef();
m_wszFrameStats[0] = 0;
}
virtual ~CBaseStateManager()
{
// Release the reference count held from the constructor
m_pDevice->Release();
}
// Must be invoked by the application anytime it allows state to be
// changed outside of the D3DX Effect system.
// An entry-point for this should be provided if implementing custom filtering of redundant
// state changes.
virtual void DirtyCachedValues()
{
}
virtual LPCWSTR EndFrameStats()
{
if( m_nTotalStateChangesPerFrame != m_nTotalStateChanges )
{
swprintf_s( m_wszFrameStats,
256,
L"Frame Stats:\nTotal State Changes (Per Frame): %d",
m_nTotalStateChanges );
m_wszFrameStats[255] = 0;
m_nTotalStateChangesPerFrame = m_nTotalStateChanges;
}
m_nTotalStateChanges = 0;
return m_wszFrameStats;
}
// methods inherited from ID3DXEffectStateManager
STDMETHOD( QueryInterface )( THIS_ REFIID iid, LPVOID *ppv )
{
if( iid == IID_IUnknown || iid == IID_ID3DXEffectStateManager )
{
*ppv = static_cast<ID3DXEffectStateManager*>( this );
}
else
{
*ppv = NULL;
return E_NOINTERFACE;
}
reinterpret_cast<IUnknown*>( this )->AddRef();
return S_OK;
}
STDMETHOD_( ULONG, AddRef )( THIS )
{
return ( ULONG )InterlockedIncrement( &m_lRef );
}
STDMETHOD_( ULONG, Release )( THIS )
{
if( 0L == InterlockedDecrement( &m_lRef ) )
{
delete this;
return 0L;
}
return m_lRef;
}
STDMETHOD( SetRenderState )( THIS_ D3DRENDERSTATETYPE d3dRenderState, DWORD dwValue )
{
m_nTotalStateChanges++;
return m_pDevice->SetRenderState( d3dRenderState, dwValue );
}
STDMETHOD( SetSamplerState )( THIS_ DWORD dwStage, D3DSAMPLERSTATETYPE d3dSamplerState, DWORD dwValue )
{
m_nTotalStateChanges++;
return m_pDevice->SetSamplerState( dwStage, d3dSamplerState, dwValue );
}
STDMETHOD( SetTextureStageState )( THIS_ DWORD dwStage, D3DTEXTURESTAGESTATETYPE d3dTextureStageState, DWORD dwValue )
{
m_nTotalStateChanges++;
return m_pDevice->SetTextureStageState( dwStage, d3dTextureStageState, dwValue );
}
STDMETHOD( SetTexture )( THIS_ DWORD dwStage, LPDIRECT3DBASETEXTURE9 pTexture )
{
m_nTotalStateChanges++;
return m_pDevice->SetTexture( dwStage, pTexture );
}
STDMETHOD( SetVertexShader )( THIS_ LPDIRECT3DVERTEXSHADER9 pShader )
{
m_nTotalStateChanges++;
return m_pDevice->SetVertexShader( pShader );
}
STDMETHOD( SetPixelShader )( THIS_ LPDIRECT3DPIXELSHADER9 pShader )
{
m_nTotalStateChanges++;
return m_pDevice->SetPixelShader( pShader );
}
STDMETHOD( SetFVF )( THIS_ DWORD dwFVF )
{
m_nTotalStateChanges++;
return m_pDevice->SetFVF( dwFVF );
}
STDMETHOD( SetTransform )( THIS_ D3DTRANSFORMSTATETYPE State, CONST D3DMATRIX *pMatrix )
{
m_nTotalStateChanges++;
return m_pDevice->SetTransform( State, pMatrix );
}
STDMETHOD( SetMaterial )( THIS_ CONST D3DMATERIAL9 *pMaterial )
{
m_nTotalStateChanges++;
return m_pDevice->SetMaterial( pMaterial );
}
STDMETHOD( SetLight )( THIS_ DWORD Index, CONST D3DLIGHT9 *pLight )
{
m_nTotalStateChanges++;
return m_pDevice->SetLight( Index, pLight );
}
STDMETHOD( LightEnable )( THIS_ DWORD Index, BOOL Enable )
{
m_nTotalStateChanges++;
return m_pDevice->LightEnable( Index, Enable );
}
STDMETHOD( SetNPatchMode )( THIS_ FLOAT NumSegments )
{
m_nTotalStateChanges++;
return m_pDevice->SetNPatchMode( NumSegments );
}
STDMETHOD( SetVertexShaderConstantF )( THIS_ UINT RegisterIndex,
CONST FLOAT *pConstantData,
UINT RegisterCount )
{
m_nTotalStateChanges++;
return m_pDevice->SetVertexShaderConstantF( RegisterIndex,
pConstantData,
RegisterCount );
}
STDMETHOD( SetVertexShaderConstantI )( THIS_ UINT RegisterIndex,
CONST INT *pConstantData,
UINT RegisterCount )
{
m_nTotalStateChanges++;
return m_pDevice->SetVertexShaderConstantI( RegisterIndex,
pConstantData,
RegisterCount );
}
STDMETHOD( SetVertexShaderConstantB )( THIS_ UINT RegisterIndex,
CONST BOOL *pConstantData,
UINT RegisterCount )
{
m_nTotalStateChanges++;
return m_pDevice->SetVertexShaderConstantB( RegisterIndex,
pConstantData,
RegisterCount );
}
STDMETHOD( SetPixelShaderConstantF )( THIS_ UINT RegisterIndex,
CONST FLOAT *pConstantData,
UINT RegisterCount )
{
m_nTotalStateChanges++;
return m_pDevice->SetPixelShaderConstantF( RegisterIndex,
pConstantData,
RegisterCount );
}
STDMETHOD( SetPixelShaderConstantI )( THIS_ UINT RegisterIndex,
CONST INT *pConstantData,
UINT RegisterCount )
{
m_nTotalStateChanges++;
return m_pDevice->SetPixelShaderConstantI( RegisterIndex,
pConstantData,
RegisterCount );
}
STDMETHOD( SetPixelShaderConstantB )( THIS_ UINT RegisterIndex,
CONST BOOL *pConstantData,
UINT RegisterCount )
{
m_nTotalStateChanges++;
return m_pDevice->SetPixelShaderConstantB( RegisterIndex,
pConstantData,
RegisterCount );
}
};
//--------------------------------------------------------------------------------------
// Templated class for caching and duplicate state change filtering of paired types
// (such as D3DRENDERSTATETYPE/DWORD value types)
//--------------------------------------------------------------------------------------
template <typename _Kty, typename _Ty> class multicache
{
protected:
map <_Kty, _Ty> cache; // A map provides a fast look-up of contained states
// and furthermore ensures that duplicate key values
// are not present.
// Additionally, dirtying the cache can be done by
// clear()ing the container.
public:
// Command to dirty all cached values
inline void dirtyall()
{
cache.clear();
}
// Command to dirty one key value
inline void dirty( _Kty key )
{
map <_Kty, _Ty>::iterator it = cache.find( key );
if( cache.end() != it )
cache.erase( it );
}
// Called to update the cache
// The return value indicates whether or not the update was a redundant change.
// A value of 'true' indicates the new state was unique, and must be submitted
// to the D3D Runtime.
inline bool set_val( _Kty key, _Ty value )
{
map <_Kty, _Ty>::iterator it = cache.find( key );
if( cache.end() == it )
{
cache.insert( map <_Kty, _Ty>::value_type( key, value ) );
return true;
}
if( it->second == value )
return false;
it->second = value;
return true;
}
};
//--------------------------------------------------------------------------------------
// Implementation of a state manager that filters redundant state change commands.
// This implementation is useful on PURE devices.
// PURE HWVP devices do not implement redundant state change filtering.
// States that may be useful to filter on PURE device are:
// Render States
// Texture Stage States
// Sampler States
// See the Direct3D SDK Documentation for further details on pure device state change
// behavior.
//--------------------------------------------------------------------------------------
#define CACHED_STAGES 2 // The number of stages to cache
// Remaining stages are simply passed through with no
// redundancy filtering.
// For this sample, the first two stages are cached, while
// the remainder are passed through
class CPureDeviceStateManager :
public CBaseStateManager
{
protected:
typedef multicache <D3DSAMPLERSTATETYPE, DWORD> samplerStageCache;
typedef multicache <D3DTEXTURESTAGESTATETYPE, DWORD> textureStateStageCache;
protected:
multicache <D3DRENDERSTATETYPE, DWORD> cacheRenderStates; // cached Render-States
vector <samplerStageCache> vecCacheSamplerStates; // cached Sampler States
vector <textureStateStageCache> vecCacheTextureStates; // cached Texture Stage States
UINT m_nFilteredStateChanges; // Statistics -- # of redundant
// states actually filtered
UINT m_nFilteredStateChangesPerFrame;
public:
CPureDeviceStateManager( LPDIRECT3DDEVICE9 pDevice )
: CBaseStateManager( pDevice ),
cacheRenderStates(),
vecCacheSamplerStates( CACHED_STAGES ),
vecCacheTextureStates( CACHED_STAGES ),
m_nFilteredStateChanges( 0 ),
m_nFilteredStateChangesPerFrame( 0 )
{
}
virtual LPCWSTR EndFrameStats()
{
// If either the 'total' state changes or the 'filtered' state changes
// has changed, re-compute the frame statistics string
if( 0 != ( ( m_nTotalStateChangesPerFrame - m_nTotalStateChanges )
| ( m_nFilteredStateChangesPerFrame - m_nFilteredStateChanges ) ) )
{
swprintf_s( m_wszFrameStats,
256,
L"Frame Stats:\nTotal State Changes (Per Frame): %d\nRedundants Filtered (Per Frame): %d",
m_nTotalStateChanges, m_nFilteredStateChanges );
m_wszFrameStats[255] = 0;
m_nTotalStateChangesPerFrame = m_nTotalStateChanges;
m_nFilteredStateChangesPerFrame = m_nFilteredStateChanges;
}
m_nTotalStateChanges = 0;
m_nFilteredStateChanges = 0;
return m_wszFrameStats;
}
// More targeted 'Dirty' commands may be useful.
void DirtyCachedValues()
{
cacheRenderStates.dirtyall();
vector <samplerStageCache>::iterator it_samplerStages;
for( it_samplerStages = vecCacheSamplerStates.begin();
it_samplerStages != vecCacheSamplerStates.end();
it_samplerStages++ )
( *it_samplerStages ).dirtyall();
vector <textureStateStageCache>::iterator it_textureStages;
for( it_textureStages = vecCacheTextureStates.begin();
it_textureStages != vecCacheTextureStates.end();
it_textureStages++ )
( *it_textureStages ).dirtyall();
}
// methods inherited from ID3DXEffectStateManager
STDMETHOD( SetRenderState )( THIS_ D3DRENDERSTATETYPE d3dRenderState, DWORD dwValue )
{
m_nTotalStateChanges++;
// Update the render state cache
// If the return value is 'true', the command must be forwarded to
// the D3D Runtime.
if( cacheRenderStates.set_val( d3dRenderState, dwValue ) )
return m_pDevice->SetRenderState( d3dRenderState, dwValue );
m_nFilteredStateChanges++;
return S_OK;
}
STDMETHOD( SetSamplerState )( THIS_ DWORD dwStage, D3DSAMPLERSTATETYPE d3dSamplerState, DWORD dwValue )
{
m_nTotalStateChanges++;
// If this dwStage is not cached, pass the value through and exit.
// Otherwise, update the sampler state cache and if the return value is 'true', the
// command must be forwarded to the D3D Runtime.
if( dwStage >= CACHED_STAGES || vecCacheSamplerStates[dwStage].set_val( d3dSamplerState, dwValue ) )
return m_pDevice->SetSamplerState( dwStage, d3dSamplerState, dwValue );
m_nFilteredStateChanges++;
return S_OK;
}
STDMETHOD( SetTextureStageState )( THIS_ DWORD dwStage, D3DTEXTURESTAGESTATETYPE d3dTextureStageState, DWORD dwValue )
{
m_nTotalStateChanges++;
// If this dwStage is not cached, pass the value through and exit.
// Otherwise, update the texture stage state cache and if the return value is 'true', the
// command must be forwarded to the D3D Runtime.
if( dwStage >= CACHED_STAGES || vecCacheTextureStates[dwStage].set_val( d3dTextureStageState, dwValue ) )
return m_pDevice->SetTextureStageState( dwStage, d3dTextureStageState, dwValue );
m_nFilteredStateChanges++;
return S_OK;
}
};
//--------------------------------------------------------------------------------------
// Create an extended ID3DXEffectStateManager instance
//--------------------------------------------------------------------------------------
CStateManagerInterface* CStateManagerInterface::Create( LPDIRECT3DDEVICE9 pDevice )
{
CStateManagerInterface* pStateManager = NULL;
D3DDEVICE_CREATION_PARAMETERS cp;
memset( &cp, 0, sizeof cp );
if( SUCCEEDED( pDevice->GetCreationParameters( &cp ) ) )
{
// A PURE device does not attempt to filter duplicate state changes (with some
// exceptions) from the driver. Such duplicate state changes can be expensive
// on the CPU. To create the proper state manager, the application determines
// whether or not it is executing on a PURE device.
bool bPureDevice = ( cp.BehaviorFlags & D3DCREATE_PUREDEVICE ) != 0;
if( bPureDevice )
pStateManager = new CPureDeviceStateManager( pDevice );
else
pStateManager = new CBaseStateManager( pDevice );
}
if( NULL == pStateManager )
{
DXUT_ERR_MSGBOX( L"Failed to Create State Manager", E_OUTOFMEMORY );
}
return pStateManager;
}
| 38.598655 | 123 | 0.565205 | [
"render",
"vector"
] |
0553b07910e9102f4a5838dfc5e614b157ef1124 | 2,404 | hpp | C++ | example/doc_generator/src/translator/method_builder.hpp | sal-vage/d-injection | 85289edba0f7f91ef7ebccb8b3ab7f24d89ac79f | [
"BSL-1.0"
] | null | null | null | example/doc_generator/src/translator/method_builder.hpp | sal-vage/d-injection | 85289edba0f7f91ef7ebccb8b3ab7f24d89ac79f | [
"BSL-1.0"
] | 6 | 2016-01-24T18:07:34.000Z | 2016-01-24T18:10:52.000Z | example/doc_generator/src/translator/method_builder.hpp | sal-vage/d-injection | 85289edba0f7f91ef7ebccb8b3ab7f24d89ac79f | [
"BSL-1.0"
] | null | null | null | // Copyright Adam Lach 2013
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef METHOD_BUILDER_HPP
#define METHOD_BUILDER_HPP
#include "doxygen_input/xml_node.hpp"
#include "translator/common_tags.hpp"
#include "model/method.hpp"
namespace translator {
class MethodBuilder {
public:
void assemble(model::Method& method, doxygen_input::XmlNode& node) {
method.description = readDescription(method.description, node);
method.name = node.getChild("name").getValue();
method.signature = node.getChild("definition").getValue();
method.signature += node.getChild("argsstring").getValue();
}
private:
model::Method::Description readDescription(model::Method::Description& description, doxygen_input::XmlNode& xmlNode) {
if(xmlNode.hasChild(BRIEF)) {
description.brief = xmlNode.getChild(BRIEF).getValue();
}
if(xmlNode.hasChild(DETAIL)) {
description.detailed = xmlNode.getChild(DETAIL).getValue();
for(auto&& childNode : xmlNode.getChildren(std::string(DETAIL) + ".simplesect")) {
std::string kind = std::move(childNode.getAttribute("kind"));
if(kind == "pre") {
description.precondition = childNode.getChild("para").getValue();
}
else if(kind == "post") {
description.postcondition = childNode.getChild("para").getValue();
}
else if(kind == "return") {
description.returns = childNode.getChild("para").getValue();
}
}
readThrows(description, xmlNode);
}
return std::move(description);
}
void readThrows(model::Method::Description& description, doxygen_input::XmlNode& xmlNode) {
if(xmlNode.hasChild(PARAMS)) {
for(auto&& childNode : xmlNode.getChildren(PARAMS)) {
std::string kind = std::move(childNode.getAttribute("kind"));
if(kind == "exception") {
description.throws = childNode.getChild("parameteritem.parameternamelist.parametername").getValue() + " ";
description.throws += childNode.getChild("parameteritem.parameterdescription.para").getValue();
}
}
}
}
};
} //namespace translator
#endif // METHOD_BUILDER_HPP
| 37.5625 | 122 | 0.638103 | [
"model"
] |
055421c6698d2dfdca6d379976501358c617aa53 | 3,992 | cpp | C++ | libs/cppdap/src/typeof.cpp | Scriptkiddi/SHADERed | bf9e1d4a770b6d710b3cac33051320c0f0ad9436 | [
"MIT"
] | 3,513 | 2019-06-28T15:02:24.000Z | 2022-03-31T14:48:51.000Z | libs/cppdap/src/typeof.cpp | Scriptkiddi/SHADERed | bf9e1d4a770b6d710b3cac33051320c0f0ad9436 | [
"MIT"
] | 258 | 2019-07-01T13:18:19.000Z | 2022-03-09T02:23:13.000Z | libs/cppdap/src/typeof.cpp | Scriptkiddi/SHADERed | bf9e1d4a770b6d710b3cac33051320c0f0ad9436 | [
"MIT"
] | 223 | 2019-06-29T18:09:42.000Z | 2022-03-29T05:33:34.000Z | // Copyright 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "dap/typeof.h"
#include <atomic>
#include <memory>
#include <vector>
namespace {
// TypeInfos owns all the dap::TypeInfo instances.
struct TypeInfos {
// get() returns the TypeInfos singleton pointer.
// TypeInfos is constructed with an internal reference count of 1.
static TypeInfos* get();
// reference() increments the TypeInfos reference count.
inline void reference() {
assert(refcount.load() > 0);
refcount++;
}
// release() decrements the TypeInfos reference count.
// If the reference count becomes 0, then the TypeInfos is destructed.
inline void release() {
if (--refcount == 0) {
this->~TypeInfos();
}
}
struct NullTI : public dap::TypeInfo {
using null = dap::null;
inline std::string name() const override { return "null"; }
inline size_t size() const override { return sizeof(null); }
inline size_t alignment() const override { return alignof(null); }
inline void construct(void* ptr) const override { new (ptr) null(); }
inline void copyConstruct(void* dst, const void* src) const override {
new (dst) null(*reinterpret_cast<const null*>(src));
}
inline void destruct(void* ptr) const override {
reinterpret_cast<null*>(ptr)->~null();
}
inline bool deserialize(const dap::Deserializer*, void*) const override {
return true;
}
inline bool serialize(dap::Serializer*, const void*) const override {
return true;
}
};
dap::BasicTypeInfo<dap::boolean> boolean = {"boolean"};
dap::BasicTypeInfo<dap::string> string = {"string"};
dap::BasicTypeInfo<dap::integer> integer = {"integer"};
dap::BasicTypeInfo<dap::number> number = {"number"};
dap::BasicTypeInfo<dap::object> object = {"object"};
dap::BasicTypeInfo<dap::any> any = {"any"};
NullTI null;
std::vector<std::unique_ptr<dap::TypeInfo>> types;
private:
TypeInfos() = default;
~TypeInfos() = default;
std::atomic<uint64_t> refcount = {1};
};
// aligned_storage() is a replacement for std::aligned_storage that isn't busted
// on older versions of MSVC.
template <size_t SIZE, size_t ALIGNMENT>
struct aligned_storage {
struct alignas(ALIGNMENT) type {
unsigned char data[SIZE];
};
};
TypeInfos* TypeInfos::get() {
static aligned_storage<sizeof(TypeInfos), alignof(TypeInfos)>::type memory;
struct Instance {
TypeInfos* ptr() { return reinterpret_cast<TypeInfos*>(memory.data); }
Instance() { new (ptr()) TypeInfos(); }
~Instance() { ptr()->release(); }
};
static Instance instance;
return instance.ptr();
}
} // namespace
namespace dap {
const TypeInfo* TypeOf<boolean>::type() {
return &TypeInfos::get()->boolean;
}
const TypeInfo* TypeOf<string>::type() {
return &TypeInfos::get()->string;
}
const TypeInfo* TypeOf<integer>::type() {
return &TypeInfos::get()->integer;
}
const TypeInfo* TypeOf<number>::type() {
return &TypeInfos::get()->number;
}
const TypeInfo* TypeOf<object>::type() {
return &TypeInfos::get()->object;
}
const TypeInfo* TypeOf<any>::type() {
return &TypeInfos::get()->any;
}
const TypeInfo* TypeOf<null>::type() {
return &TypeInfos::get()->null;
}
void TypeInfo::deleteOnExit(TypeInfo* ti) {
TypeInfos::get()->types.emplace_back(std::unique_ptr<TypeInfo>(ti));
}
void initialize() {
TypeInfos::get()->reference();
}
void terminate() {
TypeInfos::get()->release();
}
} // namespace dap
| 27.531034 | 80 | 0.680611 | [
"object",
"vector"
] |
0554738920bc567d58a54d2173241295bbda0f2c | 10,882 | cpp | C++ | cpp/plugins/cucim.kit.cuslide/src/cuslide/cuslide.cpp | dillon-cullinan/cucim | 8da6ca9d5a644783fc6e68c8d11c93c542e49d2f | [
"Apache-2.0"
] | null | null | null | cpp/plugins/cucim.kit.cuslide/src/cuslide/cuslide.cpp | dillon-cullinan/cucim | 8da6ca9d5a644783fc6e68c8d11c93c542e49d2f | [
"Apache-2.0"
] | null | null | null | cpp/plugins/cucim.kit.cuslide/src/cuslide/cuslide.cpp | dillon-cullinan/cucim | 8da6ca9d5a644783fc6e68c8d11c93c542e49d2f | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define CUCIM_EXPORTS
#include "cuslide.h"
#include "cucim/core/framework.h"
#include "cucim/core/plugin_util.h"
#include "cucim/io/format/image_format.h"
#include "tiff/tiff.h"
#include <fmt/format.h>
#include <nlohmann/json.hpp>
#include <array>
#include <cassert>
#include <cstring>
#include <fcntl.h>
#include <memory>
using json = nlohmann::json;
const struct cucim::PluginImplDesc kPluginImpl = {
"cucim.kit.cuslide", // name
{ 0, 1, 0 }, // version
"dev", // build
"clara team", // author
"cuslide", // description
"cuslide plugin", // long_description
"Apache-2.0", // license
"https://github.com/rapidsai/cucim", // url
"linux", // platforms,
cucim::PluginHotReload::kDisabled, // hot_reload
};
// Using CARB_PLUGIN_IMPL_MINIMAL instead of CARB_PLUGIN_IMPL
// This minimal macro doesn't define global variables for logging, profiler, crash reporting,
// and also doesn't call for the client registration for those systems
CUCIM_PLUGIN_IMPL_MINIMAL(kPluginImpl, cucim::io::format::IImageFormat)
CUCIM_PLUGIN_IMPL_NO_DEPS()
static void set_enabled(bool val)
{
(void)val;
}
static bool is_enabled()
{
return true;
}
static const char* get_format_name()
{
return "Generic TIFF";
}
static bool CUCIM_ABI checker_is_valid(const char* file_name, const char* buf) // TODO: need buffer size parameter
{
// TODO implement this
(void)file_name;
(void)buf;
return true;
}
static CuCIMFileHandle CUCIM_ABI parser_open(const char* file_path)
{
auto tif = new cuslide::tiff::TIFF(file_path, O_RDONLY);
tif->construct_ifds();
return tif->file_handle();
}
static bool CUCIM_ABI parser_parse(CuCIMFileHandle* handle, cucim::io::format::ImageMetadataDesc* out_metadata_desc)
{
if (!out_metadata_desc || !out_metadata_desc->handle)
{
throw std::runtime_error("out_metadata_desc shouldn't be nullptr!");
}
cucim::io::format::ImageMetadata& out_metadata =
*reinterpret_cast<cucim::io::format::ImageMetadata*>(out_metadata_desc->handle);
auto tif = static_cast<cuslide::tiff::TIFF*>(handle->client_data);
std::vector<size_t> main_ifd_list;
size_t ifd_count = tif->ifd_count();
size_t level_count = tif->level_count();
for (size_t i = 0; i < ifd_count; i++)
{
const std::shared_ptr<cuslide::tiff::IFD>& ifd = tif->ifd(i);
// const char* char_ptr = ifd->model().c_str();
// uint32_t width = ifd->width();
// uint32_t height = ifd->height();
// uint32_t bits_per_sample = ifd->bits_per_sample();
// uint32_t samples_per_pixel = ifd->samples_per_pixel();
uint64_t subfile_type = ifd->subfile_type();
// printf("image_description:\n%s\n", ifd->image_description().c_str());
// printf("model=%s, width=%u, height=%u, model=%p bits_per_sample:%u, samples_per_pixel=%u, %lu \n",
// char_ptr,
// width, height, char_ptr, bits_per_sample, samples_per_pixel, subfile_type);
if (subfile_type == 0)
{
main_ifd_list.push_back(i);
}
}
// Assume that the image has only one main (high resolution) image.
if (main_ifd_list.size() != 1)
{
throw std::runtime_error(
fmt::format("This format has more than one image with Subfile Type 0 so cannot be loaded!"));
}
// Explicitly forbid loading SVS format (#17)
if (tif->ifd(0)->image_description().rfind("Aperio", 0) == 0)
{
throw std::runtime_error(
fmt::format("cuCIM doesn't support Aperio SVS for now (https://github.com/rapidsai/cucim/issues/17)."));
}
//
// Metadata Setup
//
// Note: int-> uint16_t due to type differences between ImageMetadataDesc.ndim and DLTensor.ndim
const uint16_t ndim = 3;
auto& resource = out_metadata.get_resource();
std::string_view dims{ "YXC" };
const auto& level0_ifd = tif->level_ifd(0);
std::pmr::vector<int64_t> shape(
{ level0_ifd->height(), level0_ifd->width(), level0_ifd->samples_per_pixel() }, &resource);
DLDataType dtype{ kDLUInt, 8, 1 };
// TODO: Fill correct values for cucim::io::format::ImageMetadataDesc
// TODO: Do not assume channel names as 'RGB'
std::pmr::vector<std::string_view> channel_names(
{ std::string_view{ "R" }, std::string_view{ "G" }, std::string_view{ "B" } }, &resource);
// TODO: Set correct spacing value
std::pmr::vector<float> spacing(&resource);
spacing.reserve(ndim);
spacing.insert(spacing.end(), ndim, 1.0);
// TODO: Set correct spacing units
std::pmr::vector<std::string_view> spacing_units(&resource);
spacing_units.reserve(ndim);
spacing_units.emplace_back(std::string_view{ "micrometer" });
spacing_units.emplace_back(std::string_view{ "micrometer" });
spacing_units.emplace_back(std::string_view{ "color" });
std::pmr::vector<float> origin({ 0.0, 0.0, 0.0 }, &resource);
// Direction cosines (size is always 3x3)
// clang-format off
std::pmr::vector<float> direction({ 1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0}, &resource);
// clang-format on
// The coordinate frame in which the direction cosines are measured (either 'LPS'(ITK/DICOM) or 'RAS'(NIfTI/3D
// Slicer))
std::string_view coord_sys{ "LPS" };
const uint16_t level_ndim = 2;
std::pmr::vector<int64_t> level_dimensions(&resource);
level_dimensions.reserve(level_count * 2);
for (size_t i = 0; i < level_count; ++i)
{
const auto& level_ifd = tif->level_ifd(i);
level_dimensions.emplace_back(level_ifd->width());
level_dimensions.emplace_back(level_ifd->height());
}
std::pmr::vector<float> level_downsamples(&resource);
float orig_width = static_cast<float>(shape[1]);
float orig_height = static_cast<float>(shape[0]);
for (size_t i = 0; i < level_count; ++i)
{
const auto& level_ifd = tif->level_ifd(i);
level_downsamples.emplace_back(((orig_width / level_ifd->width()) + (orig_height / level_ifd->height())) / 2);
}
std::pmr::vector<uint32_t> level_tile_sizes(&resource);
level_tile_sizes.reserve(level_count * 2);
for (size_t i = 0; i < level_count; ++i)
{
const auto& level_ifd = tif->level_ifd(i);
level_tile_sizes.emplace_back(level_ifd->tile_width());
level_tile_sizes.emplace_back(level_ifd->tile_height());
}
const size_t associated_image_count = tif->associated_image_count();
std::pmr::vector<std::string_view> associated_image_names(&resource);
for (const auto& associated_image : tif->associated_images())
{
associated_image_names.emplace_back(std::string_view{ associated_image.first.c_str() });
}
auto& image_description = level0_ifd->image_description();
std::string_view raw_data{ image_description.empty() ? "" : image_description.c_str() };
// Dynamically allocate memory for json_data (need to be freed manually);
const std::string& json_str = tif->metadata();
char* json_data_ptr = static_cast<char*>(cucim_malloc(json_str.size() + 1));
memcpy(json_data_ptr, json_str.data(), json_str.size() + 1);
std::string_view json_data{ json_data_ptr, json_str.size() };
out_metadata.ndim(ndim);
out_metadata.dims(std::move(dims));
out_metadata.shape(std::move(shape));
out_metadata.dtype(dtype);
out_metadata.channel_names(std::move(channel_names));
out_metadata.spacing(std::move(spacing));
out_metadata.spacing_units(std::move(spacing_units));
out_metadata.origin(std::move(origin));
out_metadata.direction(std::move(direction));
out_metadata.coord_sys(std::move(coord_sys));
out_metadata.level_count(level_count);
out_metadata.level_ndim(level_ndim);
out_metadata.level_dimensions(std::move(level_dimensions));
out_metadata.level_downsamples(std::move(level_downsamples));
out_metadata.level_tile_sizes(std::move(level_tile_sizes));
out_metadata.image_count(associated_image_count);
out_metadata.image_names(std::move(associated_image_names));
out_metadata.raw_data(raw_data);
out_metadata.json_data(json_data);
return true;
}
static bool CUCIM_ABI parser_close(CuCIMFileHandle* handle)
{
auto tif = static_cast<cuslide::tiff::TIFF*>(handle->client_data);
delete tif;
handle->client_data = nullptr;
return true;
}
static bool CUCIM_ABI reader_read(const CuCIMFileHandle* handle,
const cucim::io::format::ImageMetadataDesc* metadata,
const cucim::io::format::ImageReaderRegionRequestDesc* request,
cucim::io::format::ImageDataDesc* out_image_data,
cucim::io::format::ImageMetadataDesc* out_metadata = nullptr)
{
auto tif = static_cast<cuslide::tiff::TIFF*>(handle->client_data);
bool result = tif->read(metadata, request, out_image_data, out_metadata);
return result;
}
static bool CUCIM_ABI writer_write(const CuCIMFileHandle* handle,
const cucim::io::format::ImageMetadataDesc* metadata,
const cucim::io::format::ImageDataDesc* image_data)
{
(void)handle;
(void)metadata;
(void)image_data;
return true;
}
void fill_interface(cucim::io::format::IImageFormat& iface)
{
static cucim::io::format::ImageCheckerDesc image_checker = { 0, 80, checker_is_valid };
static cucim::io::format::ImageParserDesc image_parser = { parser_open, parser_parse, parser_close };
static cucim::io::format::ImageReaderDesc image_reader = { reader_read };
static cucim::io::format::ImageWriterDesc image_writer = { writer_write };
// clang-format off
static cucim::io::format::ImageFormatDesc image_format_desc = {
set_enabled,
is_enabled,
get_format_name,
image_checker,
image_parser,
image_reader,
image_writer
};
// clang-format on
// clang-format off
iface =
{
&image_format_desc,
1
};
// clang-format on
}
| 35.562092 | 118 | 0.661827 | [
"shape",
"vector",
"model",
"3d"
] |
055c8c39289f0b595ac14fca8b11fc854705cc80 | 6,302 | cpp | C++ | pwiz/utility/chemistry/parse_isotopes.cpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | pwiz/utility/chemistry/parse_isotopes.cpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | pwiz/utility/chemistry/parse_isotopes.cpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | //
// $Id$
//
// 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 "pwiz/utility/misc/Std.hpp"
struct TextRecord
{
int atomicNumber;
string symbol;
double relativeAtomicMass;
double isotopicComposition;
double standardAtomicWeight;
};
istream& operator>>(istream& is, TextRecord& tr)
{
vector<string> lines(7);
while (is && lines[0].find("Atomic Number") != 0)
getline(is, lines[0]);
if (!is) return is;
for (int i=1; i<7; i++)
getline(is, lines[i]);
for (int i=0; i<7; i++)
{
istringstream iss(lines[i]);
vector<string> tokens;
copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(tokens));
if (tokens.empty()) throw runtime_error("blech");
const string& value = tokens[tokens.size()-1];
switch (i)
{
case 0:
tr.atomicNumber = atoi(value.c_str());
break;
case 1:
tr.symbol = value;
break;
case 3:
tr.relativeAtomicMass = atof(value.c_str());
break;
case 4:
tr.isotopicComposition = atof(value.c_str());
break;
case 5:
tr.standardAtomicWeight = atof(value.c_str());
break;
}
}
return is;
}
ostream& operator<<(ostream& os, const TextRecord& tr)
{
os <<
tr.atomicNumber << " " <<
tr.symbol << " " <<
tr.relativeAtomicMass << " " <<
tr.isotopicComposition << " " <<
tr.standardAtomicWeight;
return os;
}
struct Isotope
{
double mass;
double abundance;
};
ostream& operator<<(ostream& os, const Isotope& isotope)
{
os << "{" << isotope.mass << ", " << isotope.abundance << "}";
return os;
}
struct Info
{
int atomicNumber;
string symbol;
double standardAtomicWeight;
vector<Isotope> isotopes;
};
ostream& operator<<(ostream& os, const Info& info)
{
os <<
info.atomicNumber << " " <<
info.symbol << " " <<
info.standardAtomicWeight << " ";
copy(info.isotopes.begin(), info.isotopes.end(), ostream_iterator<Isotope>(os, " "));
return os;
}
void textRecordsToInfo(const vector<TextRecord>& textRecords, map<int, Info>& infos)
{
for (vector<TextRecord>::const_iterator it=textRecords.begin(); it!=textRecords.end(); ++it)
{
if (it->atomicNumber == 0) continue;
if (infos.count(it->atomicNumber) == 0)
{
// add new info
Info info;
info.atomicNumber = it->atomicNumber;
info.symbol = it->symbol;
info.standardAtomicWeight = it->standardAtomicWeight;
infos[it->atomicNumber] = info;
}
// add isotope
Isotope isotope;
isotope.mass = it->relativeAtomicMass;
isotope.abundance = it->isotopicComposition / 100;
infos[it->atomicNumber].isotopes.push_back(isotope);
}
}
void printCode(const vector<TextRecord>& textRecords)
{
map<int, Info> infos;
textRecordsToInfo(textRecords, infos);
// enumeration of symbols
cout << "enum Type\n{";
for (map<int,Info>::iterator it=infos.begin(); it!=infos.end(); ++it)
{
static int count = 0;
const Info& info = it->second;
if (count++%10 == 0) cout << "\n ";
cout << info.symbol;
if (count!=(int)infos.size()) cout << ", ";
}
cout << "\n};\n\n";
// isotope data
for (map<int,Info>::iterator it=infos.begin(); it!=infos.end(); ++it)
{
const Info& info = it->second;
cout << "Isotope isotopes_" << info.symbol << "[] = { ";
copy(info.isotopes.begin(), info.isotopes.end(), ostream_iterator<Isotope>(cout, ", "));
cout << "};\n";
cout << "const int isotopes_" << info.symbol << "_size = sizeof(isotopes_" << info.symbol <<
")/sizeof(Isotope);\n\n";
}
cout << endl;
// element data
cout << "Element elements[] =\n{\n";
for (map<int,Info>::iterator it=infos.begin(); it!=infos.end(); ++it)
{
const Info& info = it->second;
cout << " { " <<
info.symbol << ", " <<
"\"" << info.symbol << "\", " <<
info.atomicNumber << ", " <<
info.standardAtomicWeight << ", " <<
"isotopes_" << info.symbol << ", " <<
"isotopes_" << info.symbol << "_size },\n";
}
cout << "};\n";
cout << "const int elementsSize = sizeof(elements)/sizeof(Element);\n";
}
void parse_isotopes(const string& filename)
{
ifstream is(filename.c_str());
if (!is)
throw runtime_error(("Unable to open file: " + filename).c_str());
// read in the records
vector<TextRecord> textRecords;
copy(istream_iterator<TextRecord>(is), istream_iterator<TextRecord>(), back_inserter(textRecords));
// print out the records
cout.precision(12);
copy(textRecords.begin(), textRecords.end(), ostream_iterator<TextRecord>(cout, "\n"));
cout << endl;
// print out some code
printCode(textRecords);
}
int main(int argc, char* argv[])
{
try
{
if (argc < 2)
throw runtime_error("Usage: parse_isotopes filename");
const string& filename = argv[1];
parse_isotopes(filename);
return 0;
}
catch (exception& e)
{
cerr << e.what() << endl;
return 1;
}
}
| 26.478992 | 104 | 0.538083 | [
"vector"
] |
055ec2e0d95e372c04d91b9c08e820b8131e5893 | 1,053 | cc | C++ | 19/TwoDArray.cc | sandeep-krishnamurthy/cpp_from_scratch | e1c5f339c3c6ff81ff3e460edc942acbcf834582 | [
"Apache-2.0"
] | 2 | 2018-11-30T17:57:35.000Z | 2018-11-30T18:13:09.000Z | 19/TwoDArray.cc | sandeep-krishnamurthy/cpp_from_scratch | e1c5f339c3c6ff81ff3e460edc942acbcf834582 | [
"Apache-2.0"
] | null | null | null | 19/TwoDArray.cc | sandeep-krishnamurthy/cpp_from_scratch | e1c5f339c3c6ff81ff3e460edc942acbcf834582 | [
"Apache-2.0"
] | 1 | 2018-11-30T18:13:14.000Z | 2018-11-30T18:13:14.000Z | #include <iostream>
#include "TwoDArray.h"
TwoDArray::TwoDArray() {
this->m_data = new std::vector<std::vector<int> >();
}
TwoDArray::TwoDArray(const std::vector<std::vector<int> >& data) {
this->m_data = new std::vector<std::vector<int> >(data.size());
for(std::vector<int> row : data) {
this->m_data->push_back(row);
}
}
TwoDArray::TwoDArray(const int dim1, const int dim2) {
this->m_data = new std::vector<std::vector<int> >();
this->m_data->resize(dim1);
for(std::vector<int> &row : *(this->m_data)) {
row.resize(dim2);
}
}
TwoDArray::~TwoDArray() {
delete this->m_data;
}
int TwoDArray::getAt(const int dim1, const int dim2) {
return this->m_data->at(dim1).at(dim2);
}
void TwoDArray::setAt(const int dim1, const int dim2, const int value) {
this->m_data->at(dim1).at(dim2) = value;
}
void TwoDArray::print() {
for(std::vector<int> &row : *(this->m_data)) {
for(int data : row) {
std::cout << data << " ";
}
std::cout << std::endl;
}
} | 24.488372 | 72 | 0.592593 | [
"vector"
] |
05638c1ddb67c1802319f7f1ea81d2bcc5a6dd74 | 12,188 | cpp | C++ | frameworks/compile/mclinker/tools/bcc/main.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | 1 | 2022-01-07T01:53:19.000Z | 2022-01-07T01:53:19.000Z | frameworks/compile/mclinker/tools/bcc/main.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | null | null | null | frameworks/compile/mclinker/tools/bcc/main.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | 1 | 2020-02-28T02:48:42.000Z | 2020-02-28T02:48:42.000Z | //===- mcld.cpp -----------------------------------------------------------===//
//
// The MCLinker Project
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <stdlib.h>
#include <string>
#include <llvm/ADT/SmallString.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/Path.h>
#include <mcld/Config/Config.h>
#include <bcc/Config/Config.h>
#include <bcc/Support/LinkerConfig.h>
#include <bcc/Support/Initialization.h>
#include <bcc/Support/TargetLinkerConfigs.h>
#include <bcc/Linker.h>
using namespace bcc;
//===----------------------------------------------------------------------===//
// Compiler Options
//===----------------------------------------------------------------------===//
#ifdef TARGET_BUILD
static const std::string OptTargetTriple(DEFAULT_TARGET_TRIPLE_STRING);
#else
static llvm::cl::opt<std::string>
OptTargetTriple("mtriple",
llvm::cl::desc("Specify the target triple (default: "
DEFAULT_TARGET_TRIPLE_STRING ")"),
llvm::cl::init(DEFAULT_TARGET_TRIPLE_STRING),
llvm::cl::value_desc("triple"));
static llvm::cl::alias OptTargetTripleC("C", llvm::cl::NotHidden,
llvm::cl::desc("Alias for -mtriple"),
llvm::cl::aliasopt(OptTargetTriple));
#endif
//===----------------------------------------------------------------------===//
// Command Line Options
// There are four kinds of command line options:
// 1. input, (may be a file, such as -m and /tmp/XXXX.o.)
// 2. scripting options, (represent a subset of link scripting language, such
// as --defsym.)
// 3. and general options. (the rest of options)
//===----------------------------------------------------------------------===//
// General Options
//===----------------------------------------------------------------------===//
static llvm::cl::opt<std::string>
OptOutputFilename("o",
llvm::cl::desc("Output filename"),
llvm::cl::value_desc("filename"));
static llvm::cl::opt<std::string>
OptSysRoot("sysroot", llvm::cl::desc("Use directory as the location of the "
"sysroot, overriding the configure-time "
"default."),
llvm::cl::value_desc("directory"),
llvm::cl::ValueRequired);
static llvm::cl::list<std::string>
OptSearchDirList("L",
llvm::cl::ZeroOrMore,
llvm::cl::desc("Add path searchdir to the list of paths that "
"mcld will search for archive libraries and "
"mcld control scripts."),
llvm::cl::value_desc("searchdir"),
llvm::cl::Prefix);
static llvm::cl::opt<std::string>
OptSOName("soname",
llvm::cl::desc("Set internal name of shared library"),
llvm::cl::value_desc("name"));
static llvm::cl::opt<bool>
OptShared("shared",
llvm::cl::desc("Create a shared library."),
llvm::cl::init(false));
static llvm::cl::opt<bool>
OptBsymbolic("Bsymbolic",
llvm::cl::desc("Bind references within the shared library."),
llvm::cl::init(true));
static llvm::cl::opt<std::string>
OptDyld("dynamic-linker",
llvm::cl::desc("Set the name of the dynamic linker."),
llvm::cl::value_desc("Program"));
static llvm::cl::opt<bool>
OptRelocatable("relocatable",
llvm::cl::desc("Generate relocatable output"),
llvm::cl::init(false));
static llvm::cl::alias
OptRelocatableAlias("r",
llvm::cl::desc("alias for --relocatable"),
llvm::cl::aliasopt(OptRelocatable));
static llvm::cl::opt<bool>
OptDefineCommon("d",
llvm::cl::ZeroOrMore,
llvm::cl::desc("Define common symbol"),
llvm::cl::init(false));
static llvm::cl::alias
OptDefineCommonAlias1("dc",
llvm::cl::desc("alias for -d"),
llvm::cl::aliasopt(OptDefineCommon));
static llvm::cl::alias
OptDefineCommonAlias2("dp",
llvm::cl::desc("alias for -d"),
llvm::cl::aliasopt(OptDefineCommon));
//===----------------------------------------------------------------------===//
// Inputs
//===----------------------------------------------------------------------===//
static llvm::cl::list<std::string>
OptInputObjectFiles(llvm::cl::Positional,
llvm::cl::desc("[input object files]"),
llvm::cl::OneOrMore);
static llvm::cl::list<std::string>
OptNameSpecList("l",
llvm::cl::ZeroOrMore,
llvm::cl::desc("Add the archive or object file specified by "
"namespec to the list of files to link."),
llvm::cl::value_desc("namespec"),
llvm::cl::Prefix);
//===----------------------------------------------------------------------===//
// Scripting Options
//===----------------------------------------------------------------------===//
static llvm::cl::list<std::string>
OptWrapList("wrap",
llvm::cl::ZeroOrMore,
llvm::cl::desc("Use a wrap function fo symbol."),
llvm::cl::value_desc("symbol"));
static llvm::cl::list<std::string>
OptPortableList("portable",
llvm::cl::ZeroOrMore,
llvm::cl::desc("Use a portable function to symbol."),
llvm::cl::value_desc("symbol"));
//===----------------------------------------------------------------------===//
// Helper Functions
//===----------------------------------------------------------------------===//
// Override "mcld -version"
static void MCLDVersionPrinter() {
llvm::raw_ostream &os = llvm::outs();
os << "mcld (The MCLinker Project, http://mclinker.googlecode.com/):\n"
<< " version: " MCLD_VERSION "\n"
<< " Default target: " << DEFAULT_TARGET_TRIPLE_STRING << "\n";
os << "\n";
os << "LLVM (http://llvm.org/):\n";
return;
}
#define DEFAULT_OUTPUT_PATH "a.out"
static inline
std::string DetermineOutputFilename(const std::string &pOutputPath) {
if (!pOutputPath.empty()) {
return pOutputPath;
}
// User does't specify the value to -o
if (OptInputObjectFiles.size() > 1) {
llvm::errs() << "Use " DEFAULT_OUTPUT_PATH " for output file!\n";
return DEFAULT_OUTPUT_PATH;
}
// There's only one input file
const std::string &input_path = OptInputObjectFiles[0];
llvm::SmallString<200> output_path(input_path);
llvm::error_code err = llvm::sys::fs::make_absolute(output_path);
if (llvm::errc::success != err) {
llvm::errs() << "Failed to determine the absolute path of `" << input_path
<< "'! (detail: " << err.message() << ")\n";
return "";
}
llvm::sys::path::remove_filename(output_path);
llvm::sys::path::append(output_path, "a.out");
return output_path.c_str();
}
static inline
bool ConfigLinker(Linker &pLinker, const std::string &pOutputFilename) {
LinkerConfig* config = NULL;
#ifdef TARGET_BUILD
config = new (std::nothrow) DefaultLinkerConfig();
#else
config = new (std::nothrow) GeneralLinkerConfig(OptTargetTriple);
#endif
if (config == NULL) {
llvm::errs() << "Out of memory when create the linker configuration!\n";
return false;
}
// Setup the configuration accroding to the command line options.
// 1. Set up soname.
if (!OptSOName.empty()) {
config->setSOName(OptSOName);
} else {
config->setSOName(pOutputFilename);
}
// 2. If given, set up sysroot.
if (!OptSysRoot.empty()) {
config->setSysRoot(OptSysRoot);
}
// 3. If given, set up dynamic linker path.
if (!OptDyld.empty()) {
config->setDyld(OptDyld);
}
// 4. If given, set up wrapped symbols.
llvm::cl::list<std::string>::iterator wrap, wrap_end = OptWrapList.end();
for (wrap = OptWrapList.begin(); wrap != wrap_end; ++wrap) {
config->addWrap(*wrap);
}
// 5. If given, set up portable symbols.
llvm::cl::list<std::string>::iterator portable, portable_end = OptPortableList.end();
for (portable = OptPortableList.begin(); portable != portable_end; ++portable) {
config->addPortable(*portable);
}
// 6. if given, set up search directories.
llvm::cl::list<std::string>::iterator sdir, sdir_end = OptSearchDirList.end();
for (sdir = OptSearchDirList.begin(); sdir != sdir_end; ++sdir) {
config->addSearchDir(*sdir);
}
// 7. Set up output's type.
config->setShared(OptShared);
// 8. Set up -Bsymbolic.
config->setBsymbolic(OptBsymbolic);
// 9. Set up -d (define common symbols)
config->setDefineCommon(OptDefineCommon);
Linker::ErrorCode result = pLinker.config(*config);
if (Linker::kSuccess != result) {
llvm::errs() << "Failed to configure the linker! (detail: "
<< Linker::GetErrorString(result) << ")\n";
return false;
}
return true;
}
static inline
bool PrepareInputOutput(Linker &pLinker, const std::string &pOutputPath) {
// ----- Set output ----- //
// FIXME: Current MCLinker requires one to set up output before inputs. The
// constraint will be relaxed in the furture.
Linker::ErrorCode result = pLinker.setOutput(pOutputPath);
if (Linker::kSuccess != result) {
llvm::errs() << "Failed to open the output file! (detail: "
<< pOutputPath << ": "
<< Linker::GetErrorString(result) << ")\n";
return false;
}
// ----- Set inputs ----- //
llvm::cl::list<std::string>::iterator file_it = OptInputObjectFiles.begin();
llvm::cl::list<std::string>::iterator lib_it = OptNameSpecList.begin();
llvm::cl::list<std::string>::iterator file_begin = OptInputObjectFiles.begin();
llvm::cl::list<std::string>::iterator lib_begin = OptNameSpecList.begin();
llvm::cl::list<std::string>::iterator file_end = OptInputObjectFiles.end();
llvm::cl::list<std::string>::iterator lib_end = OptNameSpecList.end();
unsigned lib_pos = 0, file_pos = 0;
while (true) {
if (lib_it != lib_end) {
lib_pos = OptNameSpecList.getPosition(lib_it - lib_begin);
} else {
lib_pos = 0;
}
if (file_it != file_end) {
file_pos = OptInputObjectFiles.getPosition(file_it - file_begin);
} else {
file_pos = 0;
}
if ((file_pos != 0) && ((lib_pos == 0) || (file_pos < lib_pos))) {
result = pLinker.addObject(*file_it);
if (Linker::kSuccess != result) {
llvm::errs() << "Failed to open the input file! (detail: " << *file_it
<< ": " << Linker::GetErrorString(result) << ")\n";
return false;
}
++file_it;
} else if ((lib_pos != 0) && ((file_pos == 0) || (lib_pos < file_pos))) {
result = pLinker.addNameSpec(*lib_it);
if (Linker::kSuccess != result) {
llvm::errs() << "Failed to open the namespec! (detail: " << *lib_it
<< ": " << Linker::GetErrorString(result) << ")\n";
return false;
}
++lib_it;
} else {
break; // we're done with the list
}
}
return true;
}
static inline bool LinkFiles(Linker &pLinker) {
Linker::ErrorCode result = pLinker.link();
if (Linker::kSuccess != result) {
llvm::errs() << "Failed to linking! (detail: "
<< Linker::GetErrorString(result) << "\n";
return false;
}
return true;
}
int main(int argc, char** argv) {
llvm::cl::SetVersionPrinter(MCLDVersionPrinter);
llvm::cl::ParseCommandLineOptions(argc, argv);
init::Initialize();
std::string OutputFilename = DetermineOutputFilename(OptOutputFilename);
if (OutputFilename.empty()) {
return EXIT_FAILURE;
}
Linker linker;
if (!ConfigLinker(linker, OutputFilename)) {
return EXIT_FAILURE;
}
if (!PrepareInputOutput(linker, OutputFilename)) {
return EXIT_FAILURE;
}
if (!LinkFiles(linker)) {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 32.851752 | 87 | 0.557351 | [
"object"
] |
056d4d5c6c87ad01ff0957938ee538631cdf63f9 | 9,366 | cpp | C++ | hardware_interface/test/test_resource_manager.cpp | suab321321/ros2_control | a8242055b006e757717d379509cf5f4fee33f992 | [
"Apache-2.0"
] | null | null | null | hardware_interface/test/test_resource_manager.cpp | suab321321/ros2_control | a8242055b006e757717d379509cf5f4fee33f992 | [
"Apache-2.0"
] | null | null | null | hardware_interface/test/test_resource_manager.cpp | suab321321/ros2_control | a8242055b006e757717d379509cf5f4fee33f992 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#include <unordered_map>
#include "hardware_interface/actuator_interface.hpp"
#include "hardware_interface/resource_manager.hpp"
#include "ros2_control_test_assets/descriptions.hpp"
class TestResourceManager : public ::testing::Test
{
public:
static void SetUpTestCase()
{
}
void SetUp()
{
}
};
TEST_F(TestResourceManager, initialization_empty) {
ASSERT_ANY_THROW(hardware_interface::ResourceManager rm(""));
}
TEST_F(TestResourceManager, initialization_with_urdf) {
ASSERT_NO_THROW(
hardware_interface::ResourceManager rm(ros2_control_test_assets::minimal_robot_urdf));
}
TEST_F(TestResourceManager, post_initialization_with_urdf) {
hardware_interface::ResourceManager rm;
ASSERT_NO_THROW(rm.load_urdf(ros2_control_test_assets::minimal_robot_urdf));
}
TEST_F(TestResourceManager, initialization_with_urdf_manual_validation) {
// we validate the results manually
hardware_interface::ResourceManager rm(ros2_control_test_assets::minimal_robot_urdf, false);
EXPECT_EQ(1u, rm.actuator_components_size());
EXPECT_EQ(1u, rm.sensor_components_size());
EXPECT_EQ(1u, rm.system_components_size());
auto state_interface_keys = rm.state_interface_keys();
ASSERT_EQ(10u, state_interface_keys.size());
EXPECT_TRUE(rm.state_interface_exists("joint1/position"));
EXPECT_TRUE(rm.state_interface_exists("joint1/velocity"));
EXPECT_TRUE(rm.state_interface_exists("sensor1/velocity"));
EXPECT_TRUE(rm.state_interface_exists("joint2/position"));
EXPECT_TRUE(rm.state_interface_exists("joint3/position"));
auto command_interface_keys = rm.command_interface_keys();
ASSERT_EQ(3u, command_interface_keys.size());
EXPECT_TRUE(rm.command_interface_exists("joint1/position"));
EXPECT_TRUE(rm.command_interface_exists("joint2/velocity"));
EXPECT_TRUE(rm.command_interface_exists("joint3/velocity"));
}
TEST_F(TestResourceManager, initialization_with_wrong_urdf) {
// missing state keys
{
EXPECT_THROW(
hardware_interface::ResourceManager rm(
ros2_control_test_assets::minimal_robot_missing_state_keys_urdf), std::exception);
}
// missing command keys
{
EXPECT_THROW(
hardware_interface::ResourceManager rm(
ros2_control_test_assets::minimal_robot_missing_command_keys_urdf), std::exception);
}
}
TEST_F(TestResourceManager, initialization_with_urdf_unclaimed) {
// we validate the results manually
hardware_interface::ResourceManager rm(ros2_control_test_assets::minimal_robot_urdf);
auto command_interface_keys = rm.command_interface_keys();
for (const auto & key : command_interface_keys) {
EXPECT_FALSE(rm.command_interface_is_claimed(key));
}
// state interfaces don't have to be locked, hence any arbitrary key
// should return false.
auto state_interface_keys = rm.state_interface_keys();
for (const auto & key : state_interface_keys) {
EXPECT_FALSE(rm.command_interface_is_claimed(key));
}
}
TEST_F(TestResourceManager, resource_status) {
hardware_interface::ResourceManager rm(ros2_control_test_assets::minimal_robot_urdf);
std::unordered_map<std::string, hardware_interface::status> status_map;
status_map = rm.get_components_status();
EXPECT_EQ(status_map["TestActuatorHardware"], hardware_interface::status::CONFIGURED);
EXPECT_EQ(status_map["TestSensorHardware"], hardware_interface::status::CONFIGURED);
EXPECT_EQ(status_map["TestSystemHardware"], hardware_interface::status::CONFIGURED);
}
TEST_F(TestResourceManager, starting_and_stopping_resources) {
hardware_interface::ResourceManager rm(ros2_control_test_assets::minimal_robot_urdf);
std::unordered_map<std::string, hardware_interface::status> status_map;
rm.start_components();
status_map = rm.get_components_status();
EXPECT_EQ(status_map["TestActuatorHardware"], hardware_interface::status::STARTED);
EXPECT_EQ(status_map["TestSensorHardware"], hardware_interface::status::STARTED);
EXPECT_EQ(status_map["TestSystemHardware"], hardware_interface::status::STARTED);
rm.stop_components();
status_map = rm.get_components_status();
EXPECT_EQ(status_map["TestActuatorHardware"], hardware_interface::status::STOPPED);
EXPECT_EQ(status_map["TestSensorHardware"], hardware_interface::status::STOPPED);
EXPECT_EQ(status_map["TestSystemHardware"], hardware_interface::status::STOPPED);
}
TEST_F(TestResourceManager, resource_claiming) {
hardware_interface::ResourceManager rm(ros2_control_test_assets::minimal_robot_urdf);
const auto key = "joint1/position";
EXPECT_FALSE(rm.command_interface_is_claimed(key));
{
auto position_command_interface = rm.claim_command_interface(key);
EXPECT_TRUE(rm.command_interface_is_claimed(key));
{
EXPECT_ANY_THROW(rm.claim_command_interface(key));
}
}
EXPECT_FALSE(rm.command_interface_is_claimed(key));
// command interfaces can only be claimed once
for (const auto & key :
{"joint1/position", "joint1/position", "joint1/position", "joint2/velocity",
"joint3/velocity"})
{
{
auto interface = rm.claim_command_interface(key);
EXPECT_TRUE(rm.command_interface_is_claimed(key));
{
EXPECT_ANY_THROW(rm.claim_command_interface(key));
}
}
EXPECT_FALSE(rm.command_interface_is_claimed(key));
}
// state interfaces can be claimed multiple times
for (const auto & key :
{"joint1/position", "joint1/velocity", "sensor1/velocity", "joint2/position",
"joint3/position"})
{
{
auto interface = rm.claim_state_interface(key);
{
EXPECT_NO_THROW(rm.claim_state_interface(key));
}
}
}
std::vector<hardware_interface::LoanedCommandInterface> interfaces;
const auto interface_names = {"joint1/position", "joint2/velocity", "joint3/velocity"};
for (const auto & key : interface_names) {
interfaces.emplace_back(rm.claim_command_interface(key));
}
for (const auto & key : interface_names) {
EXPECT_TRUE(rm.command_interface_is_claimed(key));
}
interfaces.clear();
for (const auto & key : interface_names) {
EXPECT_FALSE(rm.command_interface_is_claimed(key));
}
}
class ExternalComponent : public hardware_interface::ActuatorInterface
{
hardware_interface::return_type configure(const hardware_interface::HardwareInfo &) override
{
return hardware_interface::return_type::OK;
}
std::vector<hardware_interface::StateInterface> export_state_interfaces() override
{
std::vector<hardware_interface::StateInterface> state_interfaces;
state_interfaces.emplace_back(
hardware_interface::StateInterface(
"external_joint", "external_state_interface", nullptr));
return state_interfaces;
}
std::vector<hardware_interface::CommandInterface> export_command_interfaces() override
{
std::vector<hardware_interface::CommandInterface> command_interfaces;
command_interfaces.emplace_back(
hardware_interface::CommandInterface(
"external_joint", "external_command_interface", nullptr));
return command_interfaces;
}
hardware_interface::return_type start() override
{
return hardware_interface::return_type::OK;
}
hardware_interface::return_type stop() override
{
return hardware_interface::return_type::OK;
}
std::string get_name() const override
{
return "ExternalComponent";
}
hardware_interface::status get_status() const override
{
return hardware_interface::status::UNKNOWN;
}
hardware_interface::return_type read() override
{
return hardware_interface::return_type::OK;
}
hardware_interface::return_type write() override
{
return hardware_interface::return_type::OK;
}
};
TEST_F(TestResourceManager, post_initialization_add_components) {
// we validate the results manually
hardware_interface::ResourceManager rm(ros2_control_test_assets::minimal_robot_urdf, false);
EXPECT_EQ(1u, rm.actuator_components_size());
EXPECT_EQ(1u, rm.sensor_components_size());
EXPECT_EQ(1u, rm.system_components_size());
ASSERT_EQ(10u, rm.state_interface_keys().size());
ASSERT_EQ(3u, rm.command_interface_keys().size());
rm.import_component(std::make_unique<ExternalComponent>());
EXPECT_EQ(2u, rm.actuator_components_size());
ASSERT_EQ(11u, rm.state_interface_keys().size());
EXPECT_TRUE(rm.state_interface_exists("external_joint/external_state_interface"));
ASSERT_EQ(4u, rm.command_interface_keys().size());
EXPECT_TRUE(rm.command_interface_exists("external_joint/external_command_interface"));
EXPECT_NO_THROW(rm.claim_state_interface("external_joint/external_state_interface"));
EXPECT_NO_THROW(rm.claim_command_interface("external_joint/external_command_interface"));
}
| 34.307692 | 94 | 0.768738 | [
"vector"
] |
0570508d321968f9a90c711b30d79eb58da1d137 | 83,277 | cpp | C++ | modules/gles31/functional/es31fSampleVariableTests.cpp | TinkerBoard-Android/external_deqp | fbf76f4e30a964813b9cdfa0dd36dadc25220939 | [
"Apache-2.0"
] | 2 | 2020-12-29T08:00:51.000Z | 2021-08-30T06:32:10.000Z | modules/gles31/functional/es31fSampleVariableTests.cpp | TinkerBoard-Android/external_deqp | fbf76f4e30a964813b9cdfa0dd36dadc25220939 | [
"Apache-2.0"
] | null | null | null | modules/gles31/functional/es31fSampleVariableTests.cpp | TinkerBoard-Android/external_deqp | fbf76f4e30a964813b9cdfa0dd36dadc25220939 | [
"Apache-2.0"
] | 3 | 2017-01-21T00:56:25.000Z | 2020-10-31T12:00:02.000Z | /*-------------------------------------------------------------------------
* drawElements Quality Program OpenGL ES 3.1 Module
* -------------------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Sample variable tests
*//*--------------------------------------------------------------------*/
#include "es31fSampleVariableTests.hpp"
#include "es31fMultisampleShaderRenderCase.hpp"
#include "tcuSurface.hpp"
#include "tcuTestLog.hpp"
#include "tcuRenderTarget.hpp"
#include "tcuTextureUtil.hpp"
#include "tcuVectorUtil.hpp"
#include "tcuFormatUtil.hpp"
#include "tcuStringTemplate.hpp"
#include "gluContextInfo.hpp"
#include "gluShaderProgram.hpp"
#include "gluRenderContext.hpp"
#include "glwFunctions.hpp"
#include "glwEnums.hpp"
#include "deStringUtil.hpp"
namespace deqp
{
using std::map;
using std::string;
namespace gles31
{
namespace Functional
{
namespace
{
class Verifier
{
public:
virtual bool verify (const tcu::RGBA& testColor, const tcu::IVec2& position) const = 0;
virtual void logInfo (tcu::TestLog& log) const = 0;
};
class ColorVerifier : public Verifier
{
public:
ColorVerifier (const tcu::Vec3& _color, int _threshold = 8)
: m_color (tcu::Vec4(_color.x(), _color.y(), _color.z(), 1.0f))
, m_threshold (tcu::IVec3(_threshold))
{
}
ColorVerifier (const tcu::Vec3& _color, tcu::IVec3 _threshold)
: m_color (tcu::Vec4(_color.x(), _color.y(), _color.z(), 1.0f))
, m_threshold (_threshold)
{
}
bool verify (const tcu::RGBA& testColor, const tcu::IVec2& position) const
{
DE_UNREF(position);
return !tcu::boolAny(tcu::greaterThan(tcu::abs(m_color.toIVec().swizzle(0, 1, 2) - testColor.toIVec().swizzle(0, 1, 2)), tcu::IVec3(m_threshold)));
}
void logInfo (tcu::TestLog& log) const
{
// full threshold? print * for clarity
log << tcu::TestLog::Message
<< "Expecting unicolored image, color = RGB("
<< ((m_threshold[0] >= 255) ? ("*") : (de::toString(m_color.getRed()))) << ", "
<< ((m_threshold[1] >= 255) ? ("*") : (de::toString(m_color.getGreen()))) << ", "
<< ((m_threshold[2] >= 255) ? ("*") : (de::toString(m_color.getBlue()))) << ")"
<< tcu::TestLog::EndMessage;
}
const tcu::RGBA m_color;
const tcu::IVec3 m_threshold;
};
class FullBlueSomeGreenVerifier : public Verifier
{
public:
FullBlueSomeGreenVerifier (void)
{
}
bool verify (const tcu::RGBA& testColor, const tcu::IVec2& position) const
{
DE_UNREF(position);
// Values from 0.0 and 1.0 are accurate
if (testColor.getRed() != 0)
return false;
if (testColor.getGreen() == 0)
return false;
if (testColor.getBlue() != 255)
return false;
return true;
}
void logInfo (tcu::TestLog& log) const
{
log << tcu::TestLog::Message << "Expecting color c = (0.0, x, 1.0), x > 0.0" << tcu::TestLog::EndMessage;
}
};
class NoRedVerifier : public Verifier
{
public:
NoRedVerifier (void)
{
}
bool verify (const tcu::RGBA& testColor, const tcu::IVec2& position) const
{
DE_UNREF(position);
return testColor.getRed() == 0;
}
void logInfo (tcu::TestLog& log) const
{
log << tcu::TestLog::Message << "Expecting zero-valued red channel." << tcu::TestLog::EndMessage;
}
};
class SampleAverageVerifier : public Verifier
{
public:
SampleAverageVerifier (int _numSamples);
bool verify (const tcu::RGBA& testColor, const tcu::IVec2& position) const;
void logInfo (tcu::TestLog& log) const;
const int m_numSamples;
const bool m_isStatisticallySignificant;
float m_distanceThreshold;
};
SampleAverageVerifier::SampleAverageVerifier (int _numSamples)
: m_numSamples (_numSamples)
, m_isStatisticallySignificant (_numSamples >= 4)
, m_distanceThreshold (0.0f)
{
// approximate Bates distribution as normal
const float variance = (1.0f / (12.0f * (float)m_numSamples));
const float standardDeviation = deFloatSqrt(variance);
// 95% of means of sample positions are within 2 standard deviations if
// they were randomly assigned. Sample patterns are expected to be more
// uniform than a random pattern.
m_distanceThreshold = 2 * standardDeviation;
}
bool SampleAverageVerifier::verify (const tcu::RGBA& testColor, const tcu::IVec2& position) const
{
DE_UNREF(position);
DE_ASSERT(m_isStatisticallySignificant);
const tcu::Vec2 avgPosition ((float)testColor.getGreen() / 255.0f, (float)testColor.getBlue() / 255.0f);
const tcu::Vec2 distanceFromCenter = tcu::abs(avgPosition - tcu::Vec2(0.5f, 0.5f));
return distanceFromCenter.x() < m_distanceThreshold && distanceFromCenter.y() < m_distanceThreshold;
}
void SampleAverageVerifier::logInfo (tcu::TestLog& log) const
{
log << tcu::TestLog::Message << "Expecting average sample position to be near the pixel center. Maximum per-axis distance " << m_distanceThreshold << tcu::TestLog::EndMessage;
}
class PartialDiscardVerifier : public Verifier
{
public:
PartialDiscardVerifier (void)
{
}
bool verify (const tcu::RGBA& testColor, const tcu::IVec2& position) const
{
DE_UNREF(position);
return (testColor.getGreen() != 0) && (testColor.getGreen() != 255);
}
void logInfo (tcu::TestLog& log) const
{
log << tcu::TestLog::Message << "Expecting color non-zero and non-saturated green channel" << tcu::TestLog::EndMessage;
}
};
static bool verifyImageWithVerifier (const tcu::Surface& resultImage, tcu::TestLog& log, const Verifier& verifier, bool logOnSuccess = true)
{
tcu::Surface errorMask (resultImage.getWidth(), resultImage.getHeight());
bool error = false;
tcu::clear(errorMask.getAccess(), tcu::Vec4(0.0f, 1.0f, 0.0f, 1.0f));
if (logOnSuccess)
{
log << tcu::TestLog::Message << "Verifying image." << tcu::TestLog::EndMessage;
verifier.logInfo(log);
}
for (int y = 0; y < resultImage.getHeight(); ++y)
for (int x = 0; x < resultImage.getWidth(); ++x)
{
const tcu::RGBA color = resultImage.getPixel(x, y);
// verify color value is valid for this pixel position
if (!verifier.verify(color, tcu::IVec2(x,y)))
{
error = true;
errorMask.setPixel(x, y, tcu::RGBA::red());
}
}
if (error)
{
// describe the verification logic if we haven't already
if (!logOnSuccess)
verifier.logInfo(log);
log << tcu::TestLog::Message << "Image verification failed." << tcu::TestLog::EndMessage
<< tcu::TestLog::ImageSet("Verification", "Image Verification")
<< tcu::TestLog::Image("Result", "Result image", resultImage.getAccess())
<< tcu::TestLog::Image("ErrorMask", "Error Mask", errorMask.getAccess())
<< tcu::TestLog::EndImageSet;
}
else if (logOnSuccess)
{
log << tcu::TestLog::Message << "Image verification passed." << tcu::TestLog::EndMessage
<< tcu::TestLog::ImageSet("Verification", "Image Verification")
<< tcu::TestLog::Image("Result", "Result image", resultImage.getAccess())
<< tcu::TestLog::EndImageSet;
}
return !error;
}
class MultisampleRenderCase : public MultisampleShaderRenderUtil::MultisampleRenderCase
{
public:
MultisampleRenderCase (Context& context, const char* name, const char* desc, int numSamples, RenderTarget target, int renderSize, int flags = 0);
virtual ~MultisampleRenderCase (void);
virtual void init (void);
};
MultisampleRenderCase::MultisampleRenderCase (Context& context, const char* name, const char* desc, int numSamples, RenderTarget target, int renderSize, int flags)
: MultisampleShaderRenderUtil::MultisampleRenderCase(context, name, desc, numSamples, target, renderSize, flags)
{
DE_ASSERT(target < TARGET_LAST);
}
MultisampleRenderCase::~MultisampleRenderCase (void)
{
MultisampleRenderCase::deinit();
}
void MultisampleRenderCase::init (void)
{
const bool isES32 = glu::contextSupports(m_context.getRenderContext().getType(), glu::ApiType::es(3, 2));
if (!isES32 && !m_context.getContextInfo().isExtensionSupported("GL_OES_sample_variables"))
TCU_THROW(NotSupportedError, "Test requires GL_OES_sample_variables extension or a context version 3.2 or higher.");
MultisampleShaderRenderUtil::MultisampleRenderCase::init();
}
class NumSamplesCase : public MultisampleRenderCase
{
public:
NumSamplesCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target);
~NumSamplesCase (void);
std::string genFragmentSource (int numTargetSamples) const;
bool verifyImage (const tcu::Surface& resultImage);
private:
enum
{
RENDER_SIZE = 64
};
};
NumSamplesCase::NumSamplesCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target)
: MultisampleRenderCase(context, name, desc, sampleCount, target, RENDER_SIZE)
{
}
NumSamplesCase::~NumSamplesCase (void)
{
}
std::string NumSamplesCase::genFragmentSource (int numTargetSamples) const
{
std::ostringstream buf;
const bool isES32 = glu::contextSupports(m_context.getRenderContext().getType(), glu::ApiType::es(3, 2));
map<string, string> args;
args["GLSL_VERSION_DECL"] = isES32 ? getGLSLVersionDeclaration(glu::GLSL_VERSION_320_ES) : getGLSLVersionDeclaration(glu::GLSL_VERSION_310_ES);
args["GLSL_EXTENSION"] = isES32 ? "" : "#extension GL_OES_sample_variables : require";
buf << "${GLSL_VERSION_DECL}\n"
"${GLSL_EXTENSION}\n"
"layout(location = 0) out mediump vec4 fragColor;\n"
"void main (void)\n"
"{\n"
" fragColor = vec4(1.0, 0.0, 0.0, 1.0);\n"
" if (gl_NumSamples == " << numTargetSamples << ")\n"
" fragColor = vec4(0.0, 1.0, 0.0, 1.0);\n"
"}\n";
return tcu::StringTemplate(buf.str()).specialize(args);
}
bool NumSamplesCase::verifyImage (const tcu::Surface& resultImage)
{
return verifyImageWithVerifier(resultImage, m_testCtx.getLog(), NoRedVerifier());
}
class MaxSamplesCase : public MultisampleRenderCase
{
public:
MaxSamplesCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target);
~MaxSamplesCase (void);
private:
void preDraw (void);
std::string genFragmentSource (int numTargetSamples) const;
bool verifyImage (const tcu::Surface& resultImage);
enum
{
RENDER_SIZE = 64
};
};
MaxSamplesCase::MaxSamplesCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target)
: MultisampleRenderCase(context, name, desc, sampleCount, target, RENDER_SIZE)
{
}
MaxSamplesCase::~MaxSamplesCase (void)
{
}
void MaxSamplesCase::preDraw (void)
{
const glw::Functions& gl = m_context.getRenderContext().getFunctions();
deInt32 maxSamples = -1;
// query samples
{
gl.getIntegerv(GL_MAX_SAMPLES, &maxSamples);
GLU_EXPECT_NO_ERROR(gl.getError(), "query GL_MAX_SAMPLES");
m_testCtx.getLog() << tcu::TestLog::Message << "GL_MAX_SAMPLES = " << maxSamples << tcu::TestLog::EndMessage;
}
// set samples
{
const int maxSampleLoc = gl.getUniformLocation(m_program->getProgram(), "u_maxSamples");
if (maxSampleLoc == -1)
throw tcu::TestError("Location of u_maxSamples was -1");
gl.uniform1i(maxSampleLoc, maxSamples);
GLU_EXPECT_NO_ERROR(gl.getError(), "set u_maxSamples uniform");
m_testCtx.getLog() << tcu::TestLog::Message << "Set u_maxSamples = " << maxSamples << tcu::TestLog::EndMessage;
}
}
std::string MaxSamplesCase::genFragmentSource (int numTargetSamples) const
{
DE_UNREF(numTargetSamples);
std::ostringstream buf;
const bool isES32 = glu::contextSupports(m_context.getRenderContext().getType(), glu::ApiType::es(3, 2));
map<string, string> args;
args["GLSL_VERSION_DECL"] = isES32 ? getGLSLVersionDeclaration(glu::GLSL_VERSION_320_ES) : getGLSLVersionDeclaration(glu::GLSL_VERSION_310_ES);
args["GLSL_EXTENSION"] = isES32 ? "" : "#extension GL_OES_sample_variables : require";
buf << "${GLSL_VERSION_DECL}\n"
"${GLSL_EXTENSION}\n"
"layout(location = 0) out mediump vec4 fragColor;\n"
"uniform mediump int u_maxSamples;\n"
"void main (void)\n"
"{\n"
" fragColor = vec4(1.0, 0.0, 0.0, 1.0);\n"
" if (gl_MaxSamples == u_maxSamples)\n"
" fragColor = vec4(0.0, 1.0, 0.0, 1.0);\n"
"}\n";
return tcu::StringTemplate(buf.str()).specialize(args);
}
bool MaxSamplesCase::verifyImage (const tcu::Surface& resultImage)
{
return verifyImageWithVerifier(resultImage, m_testCtx.getLog(), NoRedVerifier());
}
class SampleIDCase : public MultisampleRenderCase
{
public:
SampleIDCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target);
~SampleIDCase (void);
void init (void);
private:
std::string genFragmentSource (int numTargetSamples) const;
bool verifyImage (const tcu::Surface& resultImage);
bool verifySampleBuffers (const std::vector<tcu::Surface>& resultBuffers);
enum
{
RENDER_SIZE = 64
};
enum VerificationMode
{
VERIFY_USING_SAMPLES,
VERIFY_USING_SELECTION,
};
const VerificationMode m_vericationMode;
};
SampleIDCase::SampleIDCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target)
: MultisampleRenderCase (context, name, desc, sampleCount, target, RENDER_SIZE, MultisampleShaderRenderUtil::MultisampleRenderCase::FLAG_VERIFY_MSAA_TEXTURE_SAMPLE_BUFFERS)
, m_vericationMode ((target == TARGET_TEXTURE) ? (VERIFY_USING_SAMPLES) : (VERIFY_USING_SELECTION))
{
}
SampleIDCase::~SampleIDCase (void)
{
}
void SampleIDCase::init (void)
{
// log the test method and expectations
if (m_vericationMode == VERIFY_USING_SAMPLES)
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Writing gl_SampleID to the green channel of the texture and verifying texture values, expecting:\n"
<< " 1) 0 with non-multisample targets.\n"
<< " 2) value N at sample index N of a multisample texture\n"
<< tcu::TestLog::EndMessage;
else if (m_vericationMode == VERIFY_USING_SELECTION)
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Selecting a single sample id for each pixel and writing color only if gl_SampleID == selected.\n"
<< "Expecting all output pixels to be partially (multisample) or fully (singlesample) colored.\n"
<< tcu::TestLog::EndMessage;
else
DE_ASSERT(false);
MultisampleRenderCase::init();
}
std::string SampleIDCase::genFragmentSource (int numTargetSamples) const
{
DE_ASSERT(numTargetSamples != 0);
std::ostringstream buf;
const bool isES32 = glu::contextSupports(m_context.getRenderContext().getType(), glu::ApiType::es(3, 2));
map<string, string> args;
args["GLSL_VERSION_DECL"] = isES32 ? getGLSLVersionDeclaration(glu::GLSL_VERSION_320_ES) : getGLSLVersionDeclaration(glu::GLSL_VERSION_310_ES);
args["GLSL_EXTENSION"] = isES32 ? "" : "#extension GL_OES_sample_variables : require";
if (m_vericationMode == VERIFY_USING_SAMPLES)
{
// encode the id to the output, and then verify it during sampling
buf << "${GLSL_VERSION_DECL}\n"
"${GLSL_EXTENSION}\n"
"layout(location = 0) out mediump vec4 fragColor;\n"
"void main (void)\n"
"{\n"
" highp float normalizedSample = float(gl_SampleID) / float(" << numTargetSamples << ");\n"
" fragColor = vec4(0.0, normalizedSample, 1.0, 1.0);\n"
"}\n";
}
else if (m_vericationMode == VERIFY_USING_SELECTION)
{
if (numTargetSamples == 1)
{
// single sample, just verify value is 0
buf << "${GLSL_VERSION_DECL}\n"
"${GLSL_EXTENSION}\n"
"layout(location = 0) out mediump vec4 fragColor;\n"
"void main (void)\n"
"{\n"
" if (gl_SampleID == 0)\n"
" fragColor = vec4(0.0, 1.0, 1.0, 1.0);\n"
" else\n"
" fragColor = vec4(0.0, 0.0, 1.0, 1.0);\n"
"}\n";
}
else
{
// select only one sample per PIXEL
buf << "${GLSL_VERSION_DECL}\n"
"${GLSL_EXTENSION}\n"
"in highp vec4 v_position;\n"
"layout(location = 0) out mediump vec4 fragColor;\n"
"void main (void)\n"
"{\n"
" highp vec2 relPosition = (v_position.xy + vec2(1.0, 1.0)) / 2.0;\n"
" highp ivec2 pixelPos = ivec2(floor(relPosition * " << (int)RENDER_SIZE << ".0));\n"
" highp int selectedID = abs(pixelPos.x + 17 * pixelPos.y) % " << numTargetSamples << ";\n"
"\n"
" if (gl_SampleID == selectedID)\n"
" fragColor = vec4(0.0, 1.0, 1.0, 1.0);\n"
" else\n"
" fragColor = vec4(0.0, 0.0, 1.0, 1.0);\n"
"}\n";
}
}
else
DE_ASSERT(false);
return tcu::StringTemplate(buf.str()).specialize(args);
}
bool SampleIDCase::verifyImage (const tcu::Surface& resultImage)
{
if (m_vericationMode == VERIFY_USING_SAMPLES)
{
// never happens
DE_ASSERT(false);
return false;
}
else if (m_vericationMode == VERIFY_USING_SELECTION)
{
// should result in full blue and some green everywhere
return verifyImageWithVerifier(resultImage, m_testCtx.getLog(), FullBlueSomeGreenVerifier());
}
else
{
DE_ASSERT(false);
return false;
}
}
bool SampleIDCase::verifySampleBuffers (const std::vector<tcu::Surface>& resultBuffers)
{
// Verify all sample buffers
bool allOk = true;
// Log layers
{
m_testCtx.getLog() << tcu::TestLog::ImageSet("SampleBuffers", "Image sample buffers");
for (int sampleNdx = 0; sampleNdx < (int)resultBuffers.size(); ++sampleNdx)
m_testCtx.getLog() << tcu::TestLog::Image("Buffer" + de::toString(sampleNdx), "Sample " + de::toString(sampleNdx), resultBuffers[sampleNdx].getAccess());
m_testCtx.getLog() << tcu::TestLog::EndImageSet;
}
m_testCtx.getLog() << tcu::TestLog::Message << "Verifying sample buffers" << tcu::TestLog::EndMessage;
for (int sampleNdx = 0; sampleNdx < (int)resultBuffers.size(); ++sampleNdx)
{
// sample id should be sample index
const int threshold = 255 / 4 / m_numTargetSamples + 1;
const float sampleIdColor = (float)sampleNdx / (float)m_numTargetSamples;
m_testCtx.getLog() << tcu::TestLog::Message << "Verifying sample " << (sampleNdx+1) << "/" << (int)resultBuffers.size() << tcu::TestLog::EndMessage;
allOk &= verifyImageWithVerifier(resultBuffers[sampleNdx], m_testCtx.getLog(), ColorVerifier(tcu::Vec3(0.0f, sampleIdColor, 1.0f), tcu::IVec3(1, threshold, 1)), false);
}
if (!allOk)
m_testCtx.getLog() << tcu::TestLog::Message << "Sample buffer verification failed" << tcu::TestLog::EndMessage;
return allOk;
}
class SamplePosDistributionCase : public MultisampleRenderCase
{
public:
SamplePosDistributionCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target);
~SamplePosDistributionCase (void);
void init (void);
private:
enum
{
RENDER_SIZE = 64
};
std::string genFragmentSource (int numTargetSamples) const;
bool verifyImage (const tcu::Surface& resultImage);
bool verifySampleBuffers (const std::vector<tcu::Surface>& resultBuffers);
};
SamplePosDistributionCase::SamplePosDistributionCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target)
: MultisampleRenderCase(context, name, desc, sampleCount, target, RENDER_SIZE, MultisampleShaderRenderUtil::MultisampleRenderCase::FLAG_VERIFY_MSAA_TEXTURE_SAMPLE_BUFFERS)
{
}
SamplePosDistributionCase::~SamplePosDistributionCase (void)
{
}
void SamplePosDistributionCase::init (void)
{
// log the test method and expectations
if (m_renderTarget == TARGET_TEXTURE)
{
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Verifying gl_SamplePosition value:\n"
<< " 1) With non-multisample targets: Expect the center of the pixel.\n"
<< " 2) With multisample targets:\n"
<< " a) Expect legal sample position.\n"
<< " b) Sample position is unique within the set of all sample positions of a pixel.\n"
<< " c) Sample position distribution is uniform or almost uniform.\n"
<< tcu::TestLog::EndMessage;
}
else
{
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Verifying gl_SamplePosition value:\n"
<< " 1) With non-multisample targets: Expect the center of the pixel.\n"
<< " 2) With multisample targets:\n"
<< " a) Expect legal sample position.\n"
<< " b) Sample position distribution is uniform or almost uniform.\n"
<< tcu::TestLog::EndMessage;
}
MultisampleRenderCase::init();
}
std::string SamplePosDistributionCase::genFragmentSource (int numTargetSamples) const
{
DE_ASSERT(numTargetSamples != 0);
DE_UNREF(numTargetSamples);
const bool multisampleTarget = (m_numRequestedSamples > 0) || (m_renderTarget == TARGET_DEFAULT && m_context.getRenderTarget().getNumSamples() > 1);
std::ostringstream buf;
const bool isES32 = glu::contextSupports(m_context.getRenderContext().getType(), glu::ApiType::es(3, 2));
map<string, string> args;
args["GLSL_VERSION_DECL"] = isES32 ? getGLSLVersionDeclaration(glu::GLSL_VERSION_320_ES) : getGLSLVersionDeclaration(glu::GLSL_VERSION_310_ES);
args["GLSL_EXTENSION"] = isES32 ? "\n" : "#extension GL_OES_sample_variables : require\n";
if (multisampleTarget)
{
// encode the position to the output, use red channel as error channel
buf << "${GLSL_VERSION_DECL}\n"
"${GLSL_EXTENSION}\n"
"layout(location = 0) out mediump vec4 fragColor;\n"
"void main (void)\n"
"{\n"
" if (gl_SamplePosition.x < 0.0 || gl_SamplePosition.x > 1.0 || gl_SamplePosition.y < 0.0 || gl_SamplePosition.y > 1.0)\n"
" fragColor = vec4(1.0, 0.0, 0.0, 1.0);\n"
" else\n"
" fragColor = vec4(0.0, gl_SamplePosition.x, gl_SamplePosition.y, 1.0);\n"
"}\n";
}
else
{
// verify value is ok
buf << "${GLSL_VERSION_DECL}\n"
"${GLSL_EXTENSION}\n"
"layout(location = 0) out mediump vec4 fragColor;\n"
"void main (void)\n"
"{\n"
" if (gl_SamplePosition.x != 0.5 || gl_SamplePosition.y != 0.5)\n"
" fragColor = vec4(1.0, 0.0, 0.0, 1.0);\n"
" else\n"
" fragColor = vec4(0.0, gl_SamplePosition.x, gl_SamplePosition.y, 1.0);\n"
"}\n";
}
return tcu::StringTemplate(buf.str()).specialize(args);
}
bool SamplePosDistributionCase::verifyImage (const tcu::Surface& resultImage)
{
const int sampleCount = (m_renderTarget == TARGET_DEFAULT) ? (m_context.getRenderTarget().getNumSamples()) : (m_numRequestedSamples);
SampleAverageVerifier verifier (sampleCount);
// check there is nothing in the error channel
if (!verifyImageWithVerifier(resultImage, m_testCtx.getLog(), NoRedVerifier()))
return false;
// position average should be around 0.5, 0.5
if (verifier.m_isStatisticallySignificant && !verifyImageWithVerifier(resultImage, m_testCtx.getLog(), verifier))
throw MultisampleShaderRenderUtil::QualityWarning("Bias detected, sample positions are not uniformly distributed within the pixel");
return true;
}
bool SamplePosDistributionCase::verifySampleBuffers (const std::vector<tcu::Surface>& resultBuffers)
{
const int width = resultBuffers[0].getWidth();
const int height = resultBuffers[0].getHeight();
bool allOk = true;
bool distibutionError = false;
// Check sample range, uniqueness, and distribution, log layers
{
m_testCtx.getLog() << tcu::TestLog::ImageSet("SampleBuffers", "Image sample buffers");
for (int sampleNdx = 0; sampleNdx < (int)resultBuffers.size(); ++sampleNdx)
m_testCtx.getLog() << tcu::TestLog::Image("Buffer" + de::toString(sampleNdx), "Sample " + de::toString(sampleNdx), resultBuffers[sampleNdx].getAccess());
m_testCtx.getLog() << tcu::TestLog::EndImageSet;
}
// verify range
{
bool rangeOk = true;
m_testCtx.getLog() << tcu::TestLog::Message << "Verifying sample position range" << tcu::TestLog::EndMessage;
for (int sampleNdx = 0; sampleNdx < (int)resultBuffers.size(); ++sampleNdx)
{
// shader does the check, just check the shader error output (red)
m_testCtx.getLog() << tcu::TestLog::Message << "Verifying sample " << (sampleNdx+1) << "/" << (int)resultBuffers.size() << tcu::TestLog::EndMessage;
rangeOk &= verifyImageWithVerifier(resultBuffers[sampleNdx], m_testCtx.getLog(), NoRedVerifier(), false);
}
if (!rangeOk)
{
allOk = false;
m_testCtx.getLog() << tcu::TestLog::Message << "Sample position verification failed." << tcu::TestLog::EndMessage;
}
}
// Verify uniqueness
{
bool uniquenessOk = true;
tcu::Surface errorMask (width, height);
std::vector<tcu::Vec2> samplePositions (resultBuffers.size());
int printCount = 0;
const int printFloodLimit = 5;
tcu::clear(errorMask.getAccess(), tcu::Vec4(0.0f, 1.0f, 0.0f, 1.0f));
m_testCtx.getLog() << tcu::TestLog::Message << "Verifying sample position uniqueness." << tcu::TestLog::EndMessage;
for (int y = 0; y < height; ++y)
for (int x = 0; x < width; ++x)
{
bool samplePosNotUnique = false;
for (int sampleNdx = 0; sampleNdx < (int)resultBuffers.size(); ++sampleNdx)
{
const tcu::RGBA color = resultBuffers[sampleNdx].getPixel(x, y);
samplePositions[sampleNdx] = tcu::Vec2((float)color.getGreen() / 255.0f, (float)color.getBlue() / 255.0f);
}
// Just check there are no two samples with same positions
for (int sampleNdxA = 0; sampleNdxA < (int)resultBuffers.size() && (!samplePosNotUnique || printCount < printFloodLimit); ++sampleNdxA)
for (int sampleNdxB = sampleNdxA+1; sampleNdxB < (int)resultBuffers.size() && (!samplePosNotUnique || printCount < printFloodLimit); ++sampleNdxB)
{
if (samplePositions[sampleNdxA] == samplePositions[sampleNdxB])
{
if (++printCount <= printFloodLimit)
{
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Pixel (" << x << ", " << y << "): Samples " << sampleNdxA << " and " << sampleNdxB << " have the same position."
<< tcu::TestLog::EndMessage;
}
samplePosNotUnique = true;
uniquenessOk = false;
errorMask.setPixel(x, y, tcu::RGBA::red());
}
}
}
// end result
if (!uniquenessOk)
{
if (printCount > printFloodLimit)
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "...\n"
<< "Omitted " << (printCount-printFloodLimit) << " error descriptions."
<< tcu::TestLog::EndMessage;
m_testCtx.getLog()
<< tcu::TestLog::Message << "Image verification failed." << tcu::TestLog::EndMessage
<< tcu::TestLog::ImageSet("Verification", "Image Verification")
<< tcu::TestLog::Image("ErrorMask", "Error Mask", errorMask.getAccess())
<< tcu::TestLog::EndImageSet;
allOk = false;
}
}
// check distribution
{
const SampleAverageVerifier verifier (m_numTargetSamples);
tcu::Surface errorMask (width, height);
int printCount = 0;
const int printFloodLimit = 5;
tcu::clear(errorMask.getAccess(), tcu::Vec4(0.0f, 1.0f, 0.0f, 1.0f));
// don't bother with small sample counts
if (verifier.m_isStatisticallySignificant)
{
m_testCtx.getLog() << tcu::TestLog::Message << "Verifying sample position distribution is (nearly) unbiased." << tcu::TestLog::EndMessage;
verifier.logInfo(m_testCtx.getLog());
for (int y = 0; y < height; ++y)
for (int x = 0; x < width; ++x)
{
tcu::IVec3 colorSum(0, 0, 0);
// color average
for (int sampleNdx = 0; sampleNdx < (int)resultBuffers.size(); ++sampleNdx)
{
const tcu::RGBA color = resultBuffers[sampleNdx].getPixel(x, y);
colorSum.x() += color.getRed();
colorSum.y() += color.getBlue();
colorSum.z() += color.getGreen();
}
colorSum.x() /= m_numTargetSamples;
colorSum.y() /= m_numTargetSamples;
colorSum.z() /= m_numTargetSamples;
// verify average sample position
if (!verifier.verify(tcu::RGBA(colorSum.x(), colorSum.y(), colorSum.z(), 0), tcu::IVec2(x, y)))
{
if (++printCount <= printFloodLimit)
{
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Pixel (" << x << ", " << y << "): Sample distribution is biased."
<< tcu::TestLog::EndMessage;
}
distibutionError = true;
errorMask.setPixel(x, y, tcu::RGBA::red());
}
}
// sub-verification result
if (distibutionError)
{
if (printCount > printFloodLimit)
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "...\n"
<< "Omitted " << (printCount-printFloodLimit) << " error descriptions."
<< tcu::TestLog::EndMessage;
m_testCtx.getLog()
<< tcu::TestLog::Message << "Image verification failed." << tcu::TestLog::EndMessage
<< tcu::TestLog::ImageSet("Verification", "Image Verification")
<< tcu::TestLog::Image("ErrorMask", "Error Mask", errorMask.getAccess())
<< tcu::TestLog::EndImageSet;
}
}
}
// results
if (!allOk)
return false;
else if (distibutionError)
throw MultisampleShaderRenderUtil::QualityWarning("Bias detected, sample positions are not uniformly distributed within the pixel");
else
{
m_testCtx.getLog() << tcu::TestLog::Message << "Verification ok." << tcu::TestLog::EndMessage;
return true;
}
}
class SamplePosCorrectnessCase : public MultisampleRenderCase
{
public:
SamplePosCorrectnessCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target);
~SamplePosCorrectnessCase (void);
void init (void);
private:
enum
{
RENDER_SIZE = 32
};
void preDraw (void);
void postDraw (void);
std::string genVertexSource (int numTargetSamples) const;
std::string genFragmentSource (int numTargetSamples) const;
bool verifyImage (const tcu::Surface& resultImage);
bool m_useSampleQualifier;
};
SamplePosCorrectnessCase::SamplePosCorrectnessCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target)
: MultisampleRenderCase (context, name, desc, sampleCount, target, RENDER_SIZE)
, m_useSampleQualifier (false)
{
}
SamplePosCorrectnessCase::~SamplePosCorrectnessCase (void)
{
}
void SamplePosCorrectnessCase::init (void)
{
const bool isES32 = glu::contextSupports(m_context.getRenderContext().getType(), glu::ApiType::es(3, 2));
// requirements: per-invocation interpolation required
if (!isES32 && !m_context.getContextInfo().isExtensionSupported("GL_OES_shader_multisample_interpolation") &&
!m_context.getContextInfo().isExtensionSupported("GL_OES_sample_shading"))
TCU_THROW(NotSupportedError, "Test requires GL_OES_shader_multisample_interpolation or GL_OES_sample_shading extension or a context version 3.2 or higher.");
// prefer to use the sample qualifier path
m_useSampleQualifier = m_context.getContextInfo().isExtensionSupported("GL_OES_shader_multisample_interpolation");
// log the test method and expectations
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Verifying gl_SamplePosition correctness:\n"
<< " 1) Varying values should be sampled at the sample position.\n"
<< " => fract(screenSpacePosition) == gl_SamplePosition\n"
<< tcu::TestLog::EndMessage;
MultisampleRenderCase::init();
}
void SamplePosCorrectnessCase::preDraw (void)
{
if (!m_useSampleQualifier)
{
const glw::Functions& gl = m_context.getRenderContext().getFunctions();
// use GL_OES_sample_shading to set per fragment sample invocation interpolation
gl.enable(GL_SAMPLE_SHADING);
gl.minSampleShading(1.0f);
GLU_EXPECT_NO_ERROR(gl.getError(), "set ratio");
m_testCtx.getLog() << tcu::TestLog::Message << "Enabling per-sample interpolation with GL_SAMPLE_SHADING." << tcu::TestLog::EndMessage;
}
}
void SamplePosCorrectnessCase::postDraw (void)
{
if (!m_useSampleQualifier)
{
const glw::Functions& gl = m_context.getRenderContext().getFunctions();
gl.disable(GL_SAMPLE_SHADING);
gl.minSampleShading(1.0f);
GLU_EXPECT_NO_ERROR(gl.getError(), "set ratio");
}
}
std::string SamplePosCorrectnessCase::genVertexSource (int numTargetSamples) const
{
DE_UNREF(numTargetSamples);
std::ostringstream buf;
const bool isES32 = glu::contextSupports(m_context.getRenderContext().getType(), glu::ApiType::es(3, 2));
map<string, string> args;
args["GLSL_VERSION_DECL"] = isES32 ? getGLSLVersionDeclaration(glu::GLSL_VERSION_320_ES) : getGLSLVersionDeclaration(glu::GLSL_VERSION_310_ES);
args["GLSL_EXTENSION"] = isES32 ? "" : m_useSampleQualifier ? "#extension GL_OES_shader_multisample_interpolation : require" : "";
buf << "${GLSL_VERSION_DECL}\n"
"${GLSL_EXTENSION}\n"
<< "in highp vec4 a_position;\n"
<< ((m_useSampleQualifier) ? ("sample ") : ("")) << "out highp vec4 v_position;\n"
"void main (void)\n"
"{\n"
" gl_Position = a_position;\n"
" v_position = a_position;\n"
"}\n";
return tcu::StringTemplate(buf.str()).specialize(args);
}
std::string SamplePosCorrectnessCase::genFragmentSource (int numTargetSamples) const
{
DE_UNREF(numTargetSamples);
std::ostringstream buf;
const bool isES32 = glu::contextSupports(m_context.getRenderContext().getType(), glu::ApiType::es(3, 2));
map<string, string> args;
args["GLSL_VERSION_DECL"] = isES32 ? getGLSLVersionDeclaration(glu::GLSL_VERSION_320_ES) : getGLSLVersionDeclaration(glu::GLSL_VERSION_310_ES);
args["GLSL_SAMPLE_EXTENSION"] = isES32 ? "" : "#extension GL_OES_sample_variables : require";
args["GLSL_MULTISAMPLE_EXTENSION"] = isES32 ? "" : m_useSampleQualifier ? "#extension GL_OES_shader_multisample_interpolation : require" : "";
// encode the position to the output, use red channel as error channel
buf << "${GLSL_VERSION_DECL}\n"
"${GLSL_SAMPLE_EXTENSION}\n"
"${GLSL_MULTISAMPLE_EXTENSION}\n"
<< ((m_useSampleQualifier) ? ("sample ") : ("")) << "in highp vec4 v_position;\n"
"layout(location = 0) out mediump vec4 fragColor;\n"
"void main (void)\n"
"{\n"
" const highp float maxDistance = 0.15625; // 4 subpixel bits. Assume 3 accurate bits + 0.03125 for other errors\n" // 0.03125 = mediump epsilon when value = 32 (RENDER_SIZE)
"\n"
" highp vec2 screenSpacePosition = (v_position.xy + vec2(1.0, 1.0)) / 2.0 * " << (int)RENDER_SIZE << ".0;\n"
" highp ivec2 nearbyPixel = ivec2(floor(screenSpacePosition));\n"
" bool allOk = false;\n"
"\n"
" // sample at edge + inaccuaries may cause us to round to any neighboring pixel\n"
" // check all neighbors for any match\n"
" for (highp int dy = -1; dy <= 1; ++dy)\n"
" for (highp int dx = -1; dx <= 1; ++dx)\n"
" {\n"
" highp ivec2 currentPixel = nearbyPixel + ivec2(dx, dy);\n"
" highp vec2 candidateSamplingPos = vec2(currentPixel) + gl_SamplePosition.xy;\n"
" highp vec2 positionDiff = abs(candidateSamplingPos - screenSpacePosition);\n"
" if (positionDiff.x < maxDistance && positionDiff.y < maxDistance)\n"
" allOk = true;\n"
" }\n"
"\n"
" if (allOk)\n"
" fragColor = vec4(0.0, 1.0, 0.0, 1.0);\n"
" else\n"
" fragColor = vec4(1.0, 0.0, 0.0, 1.0);\n"
"}\n";
return tcu::StringTemplate(buf.str()).specialize(args);
}
bool SamplePosCorrectnessCase::verifyImage (const tcu::Surface& resultImage)
{
return verifyImageWithVerifier(resultImage, m_testCtx.getLog(), NoRedVerifier());
}
class SampleMaskBaseCase : public MultisampleRenderCase
{
public:
enum ShaderRunMode
{
RUN_PER_PIXEL = 0,
RUN_PER_SAMPLE,
RUN_PER_TWO_SAMPLES,
RUN_LAST
};
SampleMaskBaseCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target, int renderSize, ShaderRunMode runMode, int flags = 0);
virtual ~SampleMaskBaseCase (void);
protected:
virtual void init (void);
virtual void preDraw (void);
virtual void postDraw (void);
virtual bool verifyImage (const tcu::Surface& resultImage);
const ShaderRunMode m_runMode;
};
SampleMaskBaseCase::SampleMaskBaseCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target, int renderSize, ShaderRunMode runMode, int flags)
: MultisampleRenderCase (context, name, desc, sampleCount, target, renderSize, flags)
, m_runMode (runMode)
{
DE_ASSERT(runMode < RUN_LAST);
}
SampleMaskBaseCase::~SampleMaskBaseCase (void)
{
}
void SampleMaskBaseCase::init (void)
{
const bool isES32 = glu::contextSupports(m_context.getRenderContext().getType(), glu::ApiType::es(3, 2));
// required extra extension
if (m_runMode == RUN_PER_TWO_SAMPLES && !isES32 && !m_context.getContextInfo().isExtensionSupported("GL_OES_sample_shading"))
TCU_THROW(NotSupportedError, "Test requires GL_OES_sample_shading extension or a context version 3.2 or higher.");
MultisampleRenderCase::init();
}
void SampleMaskBaseCase::preDraw (void)
{
const glw::Functions& gl = m_context.getRenderContext().getFunctions();
if (m_runMode == RUN_PER_TWO_SAMPLES)
{
gl.enable(GL_SAMPLE_SHADING);
gl.minSampleShading(0.5f);
GLU_EXPECT_NO_ERROR(gl.getError(), "enable sample shading");
m_testCtx.getLog() << tcu::TestLog::Message << "Enabled GL_SAMPLE_SHADING, value = 0.5" << tcu::TestLog::EndMessage;
}
}
void SampleMaskBaseCase::postDraw (void)
{
const glw::Functions& gl = m_context.getRenderContext().getFunctions();
if (m_runMode == RUN_PER_TWO_SAMPLES)
{
gl.disable(GL_SAMPLE_SHADING);
gl.minSampleShading(1.0f);
GLU_EXPECT_NO_ERROR(gl.getError(), "disable sample shading");
}
}
bool SampleMaskBaseCase::verifyImage (const tcu::Surface& resultImage)
{
// shader does the verification
return verifyImageWithVerifier(resultImage, m_testCtx.getLog(), NoRedVerifier());
}
class SampleMaskCase : public SampleMaskBaseCase
{
public:
SampleMaskCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target);
~SampleMaskCase (void);
void init (void);
void preDraw (void);
void postDraw (void);
private:
enum
{
RENDER_SIZE = 64
};
std::string genFragmentSource (int numTargetSamples) const;
};
SampleMaskCase::SampleMaskCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target)
: SampleMaskBaseCase(context, name, desc, sampleCount, target, RENDER_SIZE, RUN_PER_PIXEL)
{
}
SampleMaskCase::~SampleMaskCase (void)
{
}
void SampleMaskCase::init (void)
{
// log the test method and expectations
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Verifying gl_SampleMaskIn value with SAMPLE_MASK state. gl_SampleMaskIn does not contain any bits set that are have been killed by SAMPLE_MASK state. Expecting:\n"
<< " 1) With multisample targets: gl_SampleMaskIn AND ~(SAMPLE_MASK) should be zero.\n"
<< " 2) With non-multisample targets: SAMPLE_MASK state is only ANDed as a multisample operation. gl_SampleMaskIn should only have its last bit set regardless of SAMPLE_MASK state.\n"
<< tcu::TestLog::EndMessage;
SampleMaskBaseCase::init();
}
void SampleMaskCase::preDraw (void)
{
const glw::Functions& gl = m_context.getRenderContext().getFunctions();
const bool multisampleTarget = (m_numRequestedSamples > 0) || (m_renderTarget == TARGET_DEFAULT && m_context.getRenderTarget().getNumSamples() > 1);
const deUint32 fullMask = (deUint32)0xAAAAAAAAUL;
const deUint32 maskMask = (1U << m_numTargetSamples) - 1;
const deUint32 effectiveMask = fullMask & maskMask;
// set test mask
gl.enable(GL_SAMPLE_MASK);
gl.sampleMaski(0, effectiveMask);
GLU_EXPECT_NO_ERROR(gl.getError(), "set mask");
m_testCtx.getLog() << tcu::TestLog::Message << "Setting sample mask " << tcu::Format::Hex<4>(effectiveMask) << tcu::TestLog::EndMessage;
// set multisample case uniforms
if (multisampleTarget)
{
const int maskLoc = gl.getUniformLocation(m_program->getProgram(), "u_sampleMask");
if (maskLoc == -1)
throw tcu::TestError("Location of u_mask was -1");
gl.uniform1ui(maskLoc, effectiveMask);
GLU_EXPECT_NO_ERROR(gl.getError(), "set mask uniform");
}
// base class logic
SampleMaskBaseCase::preDraw();
}
void SampleMaskCase::postDraw (void)
{
const glw::Functions& gl = m_context.getRenderContext().getFunctions();
const deUint32 fullMask = (1U << m_numTargetSamples) - 1;
gl.disable(GL_SAMPLE_MASK);
gl.sampleMaski(0, fullMask);
GLU_EXPECT_NO_ERROR(gl.getError(), "set mask");
// base class logic
SampleMaskBaseCase::postDraw();
}
std::string SampleMaskCase::genFragmentSource (int numTargetSamples) const
{
DE_ASSERT(numTargetSamples != 0);
const bool multisampleTarget = (m_numRequestedSamples > 0) || (m_renderTarget == TARGET_DEFAULT && m_context.getRenderTarget().getNumSamples() > 1);
std::ostringstream buf;
const bool isES32 = glu::contextSupports(m_context.getRenderContext().getType(), glu::ApiType::es(3, 2));
map<string, string> args;
args["GLSL_VERSION_DECL"] = isES32 ? getGLSLVersionDeclaration(glu::GLSL_VERSION_320_ES) : getGLSLVersionDeclaration(glu::GLSL_VERSION_310_ES);
args["GLSL_EXTENSION"] = isES32 ? "" : "#extension GL_OES_sample_variables : require";
// test supports only one sample mask word
if (numTargetSamples > 32)
TCU_THROW(NotSupportedError, "Sample count larger than 32 is not supported.");
if (multisampleTarget)
{
buf << "${GLSL_VERSION_DECL}\n"
"${GLSL_EXTENSION}\n"
"layout(location = 0) out mediump vec4 fragColor;\n"
"uniform highp uint u_sampleMask;\n"
"void main (void)\n"
"{\n"
" if ((uint(gl_SampleMaskIn[0]) & (~u_sampleMask)) != 0u)\n"
" fragColor = vec4(1.0, 0.0, 0.0, 1.0);\n"
" else\n"
" fragColor = vec4(0.0, 1.0, 0.0, 1.0);\n"
"}\n";
}
else
{
// non-multisample targets don't get multisample operations like ANDing with mask
buf << "${GLSL_VERSION_DECL}\n"
"${GLSL_EXTENSION}\n"
"layout(location = 0) out mediump vec4 fragColor;\n"
"uniform highp uint u_sampleMask;\n"
"void main (void)\n"
"{\n"
" if (gl_SampleMaskIn[0] != 1)\n"
" fragColor = vec4(1.0, 0.0, 0.0, 1.0);\n"
" else\n"
" fragColor = vec4(0.0, 1.0, 0.0, 1.0);\n"
"}\n";
}
return tcu::StringTemplate(buf.str()).specialize(args);
}
class SampleMaskCountCase : public SampleMaskBaseCase
{
public:
SampleMaskCountCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target, ShaderRunMode runMode);
~SampleMaskCountCase (void);
void init (void);
void preDraw (void);
void postDraw (void);
private:
enum
{
RENDER_SIZE = 64
};
std::string genFragmentSource (int numTargetSamples) const;
};
SampleMaskCountCase::SampleMaskCountCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target, ShaderRunMode runMode)
: SampleMaskBaseCase(context, name, desc, sampleCount, target, RENDER_SIZE, runMode)
{
DE_ASSERT(runMode < RUN_LAST);
}
SampleMaskCountCase::~SampleMaskCountCase (void)
{
}
void SampleMaskCountCase::init (void)
{
// log the test method and expectations
if (m_runMode == RUN_PER_PIXEL)
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Verifying gl_SampleMaskIn.\n"
<< " Fragment shader may be invoked [1, numSamples] times.\n"
<< " => gl_SampleMaskIn should have the number of bits set in range [1, numSamples]\n"
<< tcu::TestLog::EndMessage;
else if (m_runMode == RUN_PER_SAMPLE)
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Verifying gl_SampleMaskIn.\n"
<< " Fragment will be invoked numSamples times.\n"
<< " => gl_SampleMaskIn should have only one bit set.\n"
<< tcu::TestLog::EndMessage;
else if (m_runMode == RUN_PER_TWO_SAMPLES)
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Verifying gl_SampleMaskIn.\n"
<< " Fragment shader may be invoked [ceil(numSamples/2), numSamples] times.\n"
<< " => gl_SampleMaskIn should have the number of bits set in range [1, numSamples - ceil(numSamples/2) + 1]:\n"
<< tcu::TestLog::EndMessage;
else
DE_ASSERT(false);
SampleMaskBaseCase::init();
}
void SampleMaskCountCase::preDraw (void)
{
const glw::Functions& gl = m_context.getRenderContext().getFunctions();
if (m_runMode == RUN_PER_PIXEL)
{
const int maxLoc = gl.getUniformLocation(m_program->getProgram(), "u_maxBitCount");
const int minLoc = gl.getUniformLocation(m_program->getProgram(), "u_minBitCount");
const int minBitCount = 1;
const int maxBitCount = m_numTargetSamples;
if (maxLoc == -1)
throw tcu::TestError("Location of u_maxBitCount was -1");
if (minLoc == -1)
throw tcu::TestError("Location of u_minBitCount was -1");
gl.uniform1i(minLoc, minBitCount);
gl.uniform1i(maxLoc, maxBitCount);
GLU_EXPECT_NO_ERROR(gl.getError(), "set limits");
m_testCtx.getLog() << tcu::TestLog::Message << "Setting minBitCount = " << minBitCount << ", maxBitCount = " << maxBitCount << tcu::TestLog::EndMessage;
}
else if (m_runMode == RUN_PER_TWO_SAMPLES)
{
const int maxLoc = gl.getUniformLocation(m_program->getProgram(), "u_maxBitCount");
const int minLoc = gl.getUniformLocation(m_program->getProgram(), "u_minBitCount");
// Worst case: all but one shader invocations get one sample, one shader invocation the rest of the samples
const int minInvocationCount = ((m_numTargetSamples + 1) / 2);
const int minBitCount = 1;
const int maxBitCount = m_numTargetSamples - ((minInvocationCount-1) * minBitCount);
if (maxLoc == -1)
throw tcu::TestError("Location of u_maxBitCount was -1");
if (minLoc == -1)
throw tcu::TestError("Location of u_minBitCount was -1");
gl.uniform1i(minLoc, minBitCount);
gl.uniform1i(maxLoc, maxBitCount);
GLU_EXPECT_NO_ERROR(gl.getError(), "set limits");
m_testCtx.getLog() << tcu::TestLog::Message << "Setting minBitCount = " << minBitCount << ", maxBitCount = " << maxBitCount << tcu::TestLog::EndMessage;
}
SampleMaskBaseCase::preDraw();
}
void SampleMaskCountCase::postDraw (void)
{
SampleMaskBaseCase::postDraw();
}
std::string SampleMaskCountCase::genFragmentSource (int numTargetSamples) const
{
DE_ASSERT(numTargetSamples != 0);
std::ostringstream buf;
const bool isES32 = glu::contextSupports(m_context.getRenderContext().getType(), glu::ApiType::es(3, 2));
map<string, string> args;
args["GLSL_VERSION_DECL"] = isES32 ? getGLSLVersionDeclaration(glu::GLSL_VERSION_320_ES) : getGLSLVersionDeclaration(glu::GLSL_VERSION_310_ES);
args["GLSL_EXTENSION"] = isES32 ? "" : "#extension GL_OES_sample_variables : require";
// test supports only one sample mask word
if (numTargetSamples > 32)
TCU_THROW(NotSupportedError, "Sample count larger than 32 is not supported.");
// count the number of the bits in gl_SampleMask
buf << "${GLSL_VERSION_DECL}\n"
"${GLSL_EXTENSION}\n"
"layout(location = 0) out mediump vec4 fragColor;\n";
if (m_runMode != RUN_PER_SAMPLE)
buf << "uniform highp int u_minBitCount;\n"
"uniform highp int u_maxBitCount;\n";
buf << "void main (void)\n"
"{\n"
" mediump int maskBitCount = 0;\n"
" for (int i = 0; i < 32; ++i)\n"
" if (((gl_SampleMaskIn[0] >> i) & 0x01) == 0x01)\n"
" ++maskBitCount;\n"
"\n";
if (m_runMode == RUN_PER_SAMPLE)
{
// check the validity here
buf << " // force per-sample shading\n"
" highp float blue = float(gl_SampleID);\n"
"\n"
" if (maskBitCount != 1)\n"
" fragColor = vec4(1.0, 0.0, blue, 1.0);\n"
" else\n"
" fragColor = vec4(0.0, 1.0, blue, 1.0);\n"
"}\n";
}
else
{
// check the validity here
buf << " if (maskBitCount < u_minBitCount || maskBitCount > u_maxBitCount)\n"
" fragColor = vec4(1.0, 0.0, 0.0, 1.0);\n"
" else\n"
" fragColor = vec4(0.0, 1.0, 0.0, 1.0);\n"
"}\n";
}
return tcu::StringTemplate(buf.str()).specialize(args);
}
class SampleMaskUniqueCase : public SampleMaskBaseCase
{
public:
SampleMaskUniqueCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target, ShaderRunMode runMode);
~SampleMaskUniqueCase (void);
void init (void);
private:
enum
{
RENDER_SIZE = 64
};
std::string genFragmentSource (int numTargetSamples) const;
bool verifySampleBuffers (const std::vector<tcu::Surface>& resultBuffers);
};
SampleMaskUniqueCase::SampleMaskUniqueCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target, ShaderRunMode runMode)
: SampleMaskBaseCase(context, name, desc, sampleCount, target, RENDER_SIZE, runMode, MultisampleShaderRenderUtil::MultisampleRenderCase::FLAG_VERIFY_MSAA_TEXTURE_SAMPLE_BUFFERS)
{
DE_ASSERT(runMode == RUN_PER_SAMPLE);
DE_ASSERT(target == TARGET_TEXTURE);
}
SampleMaskUniqueCase::~SampleMaskUniqueCase (void)
{
}
void SampleMaskUniqueCase::init (void)
{
// log the test method and expectations
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Verifying gl_SampleMaskIn.\n"
<< " Fragment will be invoked numSamples times.\n"
<< " => gl_SampleMaskIn should have only one bit set\n"
<< " => and that bit index should be unique within other fragment shader invocations of that pixel.\n"
<< " Writing sampleMask bit index to green channel in render shader. Verifying uniqueness in sampler shader.\n"
<< tcu::TestLog::EndMessage;
SampleMaskBaseCase::init();
}
std::string SampleMaskUniqueCase::genFragmentSource (int numTargetSamples) const
{
DE_ASSERT(numTargetSamples != 0);
std::ostringstream buf;
const bool isES32 = glu::contextSupports(m_context.getRenderContext().getType(), glu::ApiType::es(3, 2));
map<string, string> args;
args["GLSL_VERSION_DECL"] = isES32 ? getGLSLVersionDeclaration(glu::GLSL_VERSION_320_ES) : getGLSLVersionDeclaration(glu::GLSL_VERSION_310_ES);
args["GLSL_EXTENSION"] = isES32 ? "" : "#extension GL_OES_sample_variables : require";
// test supports only one sample mask word
if (numTargetSamples > 32)
TCU_THROW(NotSupportedError, "Sample count larger than 32 is not supported.");
// find our sampleID by searching for unique bit.
buf << "${GLSL_VERSION_DECL}\n"
"${GLSL_EXTENSION}\n"
"layout(location = 0) out mediump vec4 fragColor;\n"
"void main (void)\n"
"{\n"
" mediump int firstIndex = -1;\n"
" for (int i = 0; i < 32; ++i)\n"
" {\n"
" if (((gl_SampleMaskIn[0] >> i) & 0x01) == 0x01)\n"
" {\n"
" firstIndex = i;\n"
" break;\n"
" }\n"
" }\n"
"\n"
" bool notUniqueError = false;\n"
" for (int i = firstIndex + 1; i < 32; ++i)\n"
" if (((gl_SampleMaskIn[0] >> i) & 0x01) == 0x01)\n"
" notUniqueError = true;\n"
"\n"
" highp float encodedSampleId = float(firstIndex) / " << numTargetSamples <<".0;\n"
"\n"
" // force per-sample shading\n"
" highp float blue = float(gl_SampleID);\n"
"\n"
" if (notUniqueError)\n"
" fragColor = vec4(1.0, 0.0, blue, 1.0);\n"
" else\n"
" fragColor = vec4(0.0, encodedSampleId, blue, 1.0);\n"
"}\n";
return tcu::StringTemplate(buf.str()).specialize(args);
}
bool SampleMaskUniqueCase::verifySampleBuffers (const std::vector<tcu::Surface>& resultBuffers)
{
const int width = resultBuffers[0].getWidth();
const int height = resultBuffers[0].getHeight();
bool allOk = true;
// Log samples
{
m_testCtx.getLog() << tcu::TestLog::ImageSet("SampleBuffers", "Image sample buffers");
for (int sampleNdx = 0; sampleNdx < (int)resultBuffers.size(); ++sampleNdx)
m_testCtx.getLog() << tcu::TestLog::Image("Buffer" + de::toString(sampleNdx), "Sample " + de::toString(sampleNdx), resultBuffers[sampleNdx].getAccess());
m_testCtx.getLog() << tcu::TestLog::EndImageSet;
}
// check for earlier errors (in fragment shader)
{
m_testCtx.getLog() << tcu::TestLog::Message << "Verifying fragment shader invocation found only one set sample mask bit." << tcu::TestLog::EndMessage;
for (int sampleNdx = 0; sampleNdx < (int)resultBuffers.size(); ++sampleNdx)
{
// shader does the check, just check the shader error output (red)
m_testCtx.getLog() << tcu::TestLog::Message << "Verifying sample " << (sampleNdx+1) << "/" << (int)resultBuffers.size() << tcu::TestLog::EndMessage;
allOk &= verifyImageWithVerifier(resultBuffers[sampleNdx], m_testCtx.getLog(), NoRedVerifier(), false);
}
if (!allOk)
{
// can't check the uniqueness if the masks don't work at all
m_testCtx.getLog() << tcu::TestLog::Message << "Could not get mask information from the rendered image, cannot continue verification." << tcu::TestLog::EndMessage;
return false;
}
}
// verify index / index ranges
if (m_numRequestedSamples == 0)
{
// single sample target, expect index=0
m_testCtx.getLog() << tcu::TestLog::Message << "Verifying sample mask bit index is 0." << tcu::TestLog::EndMessage;
// only check the mask index
allOk &= verifyImageWithVerifier(resultBuffers[0], m_testCtx.getLog(), ColorVerifier(tcu::Vec3(0.0f, 0.0f, 0.0f), tcu::IVec3(255, 8, 255)), false);
}
else
{
// check uniqueness
tcu::Surface errorMask (width, height);
bool uniquenessOk = true;
int printCount = 0;
const int printFloodLimit = 5;
std::vector<int> maskBitIndices (resultBuffers.size());
tcu::clear(errorMask.getAccess(), tcu::Vec4(0.0f, 1.0f, 0.0f, 1.0f));
m_testCtx.getLog() << tcu::TestLog::Message << "Verifying per-invocation sample mask bit is unique." << tcu::TestLog::EndMessage;
for (int y = 0; y < height; ++y)
for (int x = 0; x < width; ++x)
{
bool maskNdxNotUnique = false;
// decode index
for (int sampleNdx = 0; sampleNdx < (int)resultBuffers.size(); ++sampleNdx)
{
const tcu::RGBA color = resultBuffers[sampleNdx].getPixel(x, y);
maskBitIndices[sampleNdx] = (int)deFloatRound((float)color.getGreen() / 255.0f * (float)m_numTargetSamples);
}
// just check there are no two invocations with the same bit index
for (int sampleNdxA = 0; sampleNdxA < (int)resultBuffers.size() && (!maskNdxNotUnique || printCount < printFloodLimit); ++sampleNdxA)
for (int sampleNdxB = sampleNdxA+1; sampleNdxB < (int)resultBuffers.size() && (!maskNdxNotUnique || printCount < printFloodLimit); ++sampleNdxB)
{
if (maskBitIndices[sampleNdxA] == maskBitIndices[sampleNdxB])
{
if (++printCount <= printFloodLimit)
{
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Pixel (" << x << ", " << y << "): Samples " << sampleNdxA << " and " << sampleNdxB << " have the same sample mask. (Single bit at index " << maskBitIndices[sampleNdxA] << ")"
<< tcu::TestLog::EndMessage;
}
maskNdxNotUnique = true;
uniquenessOk = false;
errorMask.setPixel(x, y, tcu::RGBA::red());
}
}
}
// end result
if (!uniquenessOk)
{
if (printCount > printFloodLimit)
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "...\n"
<< "Omitted " << (printCount-printFloodLimit) << " error descriptions."
<< tcu::TestLog::EndMessage;
m_testCtx.getLog()
<< tcu::TestLog::Message << "Image verification failed." << tcu::TestLog::EndMessage
<< tcu::TestLog::ImageSet("Verification", "Image Verification")
<< tcu::TestLog::Image("ErrorMask", "Error Mask", errorMask.getAccess())
<< tcu::TestLog::EndImageSet;
allOk = false;
}
}
return allOk;
}
class SampleMaskUniqueSetCase : public SampleMaskBaseCase
{
public:
SampleMaskUniqueSetCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target, ShaderRunMode runMode);
~SampleMaskUniqueSetCase (void);
void init (void);
void deinit (void);
private:
enum
{
RENDER_SIZE = 64
};
void preDraw (void);
void postDraw (void);
std::string genFragmentSource (int numTargetSamples) const;
bool verifySampleBuffers (const std::vector<tcu::Surface>& resultBuffers);
std::string getIterationDescription (int iteration) const;
void preTest (void);
void postTest (void);
std::vector<tcu::Surface> m_iterationSampleBuffers;
};
SampleMaskUniqueSetCase::SampleMaskUniqueSetCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target, ShaderRunMode runMode)
: SampleMaskBaseCase(context, name, desc, sampleCount, target, RENDER_SIZE, runMode, MultisampleShaderRenderUtil::MultisampleRenderCase::FLAG_VERIFY_MSAA_TEXTURE_SAMPLE_BUFFERS)
{
DE_ASSERT(runMode == RUN_PER_TWO_SAMPLES);
DE_ASSERT(target == TARGET_TEXTURE);
// high and low bits
m_numIterations = 2;
}
SampleMaskUniqueSetCase::~SampleMaskUniqueSetCase (void)
{
}
void SampleMaskUniqueSetCase::init (void)
{
// log the test method and expectations
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Verifying gl_SampleMaskIn.\n"
<< " Fragment shader may be invoked [ceil(numSamples/2), numSamples] times.\n"
<< " => Each invocation should have unique bit set\n"
<< " Writing highest and lowest bit index to color channels in render shader. Verifying:\n"
<< " 1) no other invocation contains these bits in sampler shader.\n"
<< " 2) number of invocations is at least ceil(numSamples/2).\n"
<< tcu::TestLog::EndMessage;
SampleMaskBaseCase::init();
}
void SampleMaskUniqueSetCase::deinit (void)
{
m_iterationSampleBuffers.clear();
}
void SampleMaskUniqueSetCase::preDraw (void)
{
const glw::Functions& gl = m_context.getRenderContext().getFunctions();
const int selectorLoc = gl.getUniformLocation(m_program->getProgram(), "u_bitSelector");
gl.uniform1ui(selectorLoc, (deUint32)m_iteration);
GLU_EXPECT_NO_ERROR(gl.getError(), "set u_bitSelector");
m_testCtx.getLog() << tcu::TestLog::Message << "Setting u_bitSelector = " << m_iteration << tcu::TestLog::EndMessage;
SampleMaskBaseCase::preDraw();
}
void SampleMaskUniqueSetCase::postDraw (void)
{
SampleMaskBaseCase::postDraw();
}
std::string SampleMaskUniqueSetCase::genFragmentSource (int numTargetSamples) const
{
DE_ASSERT(numTargetSamples != 0);
std::ostringstream buf;
const bool isES32 = glu::contextSupports(m_context.getRenderContext().getType(), glu::ApiType::es(3, 2));
map<string, string> args;
args["GLSL_VERSION_DECL"] = isES32 ? getGLSLVersionDeclaration(glu::GLSL_VERSION_320_ES) : getGLSLVersionDeclaration(glu::GLSL_VERSION_310_ES);
args["GLSL_EXTENSION"] = isES32 ? "" : "#extension GL_OES_sample_variables : require";
// test supports only one sample mask word
if (numTargetSamples > 32)
TCU_THROW(NotSupportedError, "Sample count larger than 32 is not supported.");
// output min and max sample id
buf << "${GLSL_VERSION_DECL}\n"
"${GLSL_EXTENSION}\n"
"uniform highp uint u_bitSelector;\n"
"layout(location = 0) out mediump vec4 fragColor;\n"
"void main (void)\n"
"{\n"
" highp int selectedBits;\n"
" if (u_bitSelector == 0u)\n"
" selectedBits = (gl_SampleMaskIn[0] & 0xFFFF);\n"
" else\n"
" selectedBits = ((gl_SampleMaskIn[0] >> 16) & 0xFFFF);\n"
"\n"
" // encode bits to color\n"
" highp int redBits = selectedBits & 31;\n"
" highp int greenBits = (selectedBits >> 5) & 63;\n"
" highp int blueBits = (selectedBits >> 11) & 31;\n"
"\n"
" fragColor = vec4(float(redBits) / float(31), float(greenBits) / float(63), float(blueBits) / float(31), 1.0);\n"
"}\n";
return tcu::StringTemplate(buf.str()).specialize(args);
}
bool SampleMaskUniqueSetCase::verifySampleBuffers (const std::vector<tcu::Surface>& resultBuffers)
{
// we need results from all passes to do verification. Store results and verify later (at postTest).
DE_ASSERT(m_numTargetSamples == (int)resultBuffers.size());
for (int ndx = 0; ndx < m_numTargetSamples; ++ndx)
m_iterationSampleBuffers[m_iteration * m_numTargetSamples + ndx] = resultBuffers[ndx];
return true;
}
std::string SampleMaskUniqueSetCase::getIterationDescription (int iteration) const
{
if (iteration == 0)
return "Reading low bits";
else if (iteration == 1)
return "Reading high bits";
else
DE_ASSERT(false);
return "";
}
void SampleMaskUniqueSetCase::preTest (void)
{
m_iterationSampleBuffers.resize(m_numTargetSamples * 2);
}
void SampleMaskUniqueSetCase::postTest (void)
{
DE_ASSERT((m_iterationSampleBuffers.size() % 2) == 0);
DE_ASSERT((int)m_iterationSampleBuffers.size() / 2 == m_numTargetSamples);
const int width = m_iterationSampleBuffers[0].getWidth();
const int height = m_iterationSampleBuffers[0].getHeight();
bool allOk = true;
std::vector<tcu::TextureLevel> sampleCoverage (m_numTargetSamples);
const tcu::ScopedLogSection section (m_testCtx.getLog(), "Verify", "Verify masks");
// convert color layers to 32 bit coverage masks, 2 passes per coverage
for (int sampleNdx = 0; sampleNdx < (int)sampleCoverage.size(); ++sampleNdx)
{
sampleCoverage[sampleNdx].setStorage(tcu::TextureFormat(tcu::TextureFormat::R, tcu::TextureFormat::UNSIGNED_INT32), width, height);
for (int y = 0; y < height; ++y)
for (int x = 0; x < width; ++x)
{
const tcu::RGBA lowColor = m_iterationSampleBuffers[sampleNdx].getPixel(x, y);
const tcu::RGBA highColor = m_iterationSampleBuffers[sampleNdx + (int)sampleCoverage.size()].getPixel(x, y);
deUint16 low;
deUint16 high;
{
int redBits = (int)deFloatRound((float)lowColor.getRed() / 255.0f * 31);
int greenBits = (int)deFloatRound((float)lowColor.getGreen() / 255.0f * 63);
int blueBits = (int)deFloatRound((float)lowColor.getBlue() / 255.0f * 31);
low = (deUint16)(redBits | (greenBits << 5) | (blueBits << 11));
}
{
int redBits = (int)deFloatRound((float)highColor.getRed() / 255.0f * 31);
int greenBits = (int)deFloatRound((float)highColor.getGreen() / 255.0f * 63);
int blueBits = (int)deFloatRound((float)highColor.getBlue() / 255.0f * 31);
high = (deUint16)(redBits | (greenBits << 5) | (blueBits << 11));
}
sampleCoverage[sampleNdx].getAccess().setPixel(tcu::UVec4((((deUint32)high) << 16) | low, 0, 0, 0), x, y);
}
}
// verify masks
if (m_numRequestedSamples == 0)
{
// single sample target, expect mask = 0x01
const int printFloodLimit = 5;
int printCount = 0;
m_testCtx.getLog() << tcu::TestLog::Message << "Verifying sample mask is 0x00000001." << tcu::TestLog::EndMessage;
for (int y = 0; y < height; ++y)
for (int x = 0; x < width; ++x)
{
deUint32 mask = sampleCoverage[0].getAccess().getPixelUint(x, y).x();
if (mask != 0x01)
{
allOk = false;
if (++printCount <= printFloodLimit)
{
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Pixel (" << x << ", " << y << "): Invalid mask, got " << tcu::Format::Hex<8>(mask) << ", expected " << tcu::Format::Hex<8>(0x01) << "\n"
<< tcu::TestLog::EndMessage;
}
}
}
if (!allOk && printCount > printFloodLimit)
{
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "...\n"
<< "Omitted " << (printCount-printFloodLimit) << " error descriptions."
<< tcu::TestLog::EndMessage;
}
}
else
{
// check uniqueness
{
bool uniquenessOk = true;
int printCount = 0;
const int printFloodLimit = 5;
m_testCtx.getLog() << tcu::TestLog::Message << "Verifying invocation sample masks do not share bits." << tcu::TestLog::EndMessage;
for (int y = 0; y < height; ++y)
for (int x = 0; x < width; ++x)
{
bool maskBitsNotUnique = false;
for (int sampleNdxA = 0; sampleNdxA < m_numTargetSamples && (!maskBitsNotUnique || printCount < printFloodLimit); ++sampleNdxA)
for (int sampleNdxB = sampleNdxA+1; sampleNdxB < m_numTargetSamples && (!maskBitsNotUnique || printCount < printFloodLimit); ++sampleNdxB)
{
const deUint32 maskA = sampleCoverage[sampleNdxA].getAccess().getPixelUint(x, y).x();
const deUint32 maskB = sampleCoverage[sampleNdxB].getAccess().getPixelUint(x, y).x();
// equal mask == emitted by the same invocation
if (maskA != maskB)
{
// shares samples?
if (maskA & maskB)
{
maskBitsNotUnique = true;
uniquenessOk = false;
if (++printCount <= printFloodLimit)
{
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Pixel (" << x << ", " << y << "):\n"
<< "\tSamples " << sampleNdxA << " and " << sampleNdxB << " share mask bits\n"
<< "\tMask" << sampleNdxA << " = " << tcu::Format::Hex<8>(maskA) << "\n"
<< "\tMask" << sampleNdxB << " = " << tcu::Format::Hex<8>(maskB) << "\n"
<< tcu::TestLog::EndMessage;
}
}
}
}
}
if (!uniquenessOk)
{
allOk = false;
if (printCount > printFloodLimit)
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "...\n"
<< "Omitted " << (printCount-printFloodLimit) << " error descriptions."
<< tcu::TestLog::EndMessage;
}
}
// check number of sample mask bit groups is valid ( == number of invocations )
{
const deUint32 minNumInvocations = (deUint32)de::max(1, (m_numTargetSamples+1)/2);
bool countOk = true;
int printCount = 0;
const int printFloodLimit = 5;
m_testCtx.getLog() << tcu::TestLog::Message << "Verifying cardinality of separate sample mask bit sets. Expecting equal to the number of invocations, (greater or equal to " << minNumInvocations << ")" << tcu::TestLog::EndMessage;
for (int y = 0; y < height; ++y)
for (int x = 0; x < width; ++x)
{
std::set<deUint32> masks;
for (int maskNdx = 0; maskNdx < m_numTargetSamples; ++maskNdx)
{
const deUint32 mask = sampleCoverage[maskNdx].getAccess().getPixelUint(x, y).x();
masks.insert(mask);
}
if ((int)masks.size() < (int)minNumInvocations)
{
if (++printCount <= printFloodLimit)
{
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Pixel (" << x << ", " << y << "): Pixel invocations had only " << (int)masks.size() << " separate mask sets. Expected " << minNumInvocations << " or more. Found masks:"
<< tcu::TestLog::EndMessage;
for (std::set<deUint32>::iterator it = masks.begin(); it != masks.end(); ++it)
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "\tMask: " << tcu::Format::Hex<8>(*it) << "\n"
<< tcu::TestLog::EndMessage;
}
countOk = false;
}
}
if (!countOk)
{
allOk = false;
if (printCount > printFloodLimit)
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "...\n"
<< "Omitted " << (printCount-printFloodLimit) << " error descriptions."
<< tcu::TestLog::EndMessage;
}
}
}
if (!allOk)
m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Image verification failed");
}
class SampleMaskWriteCase : public SampleMaskBaseCase
{
public:
enum TestMode
{
TEST_DISCARD = 0,
TEST_INVERSE,
TEST_LAST
};
SampleMaskWriteCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target, ShaderRunMode runMode, TestMode testMode);
~SampleMaskWriteCase (void);
void init (void);
void preDraw (void);
void postDraw (void);
private:
enum
{
RENDER_SIZE = 64
};
std::string genFragmentSource (int numTargetSamples) const;
bool verifyImage (const tcu::Surface& resultImage);
const TestMode m_testMode;
};
SampleMaskWriteCase::SampleMaskWriteCase (Context& context, const char* name, const char* desc, int sampleCount, RenderTarget target, ShaderRunMode runMode, TestMode testMode)
: SampleMaskBaseCase (context, name, desc, sampleCount, target, RENDER_SIZE, runMode)
, m_testMode (testMode)
{
DE_ASSERT(testMode < TEST_LAST);
}
SampleMaskWriteCase::~SampleMaskWriteCase (void)
{
}
void SampleMaskWriteCase::init (void)
{
// log the test method and expectations
if (m_testMode == TEST_DISCARD)
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Discarding half of the samples using gl_SampleMask, expecting:\n"
<< " 1) half intensity on multisample targets (numSamples > 1)\n"
<< " 2) full discard on multisample targets (numSamples == 1)\n"
<< " 3) full intensity (no discard) on singlesample targets. (Mask is only applied as a multisample operation.)\n"
<< tcu::TestLog::EndMessage;
else if (m_testMode == TEST_INVERSE)
m_testCtx.getLog()
<< tcu::TestLog::Message
<< "Discarding half of the samples using GL_SAMPLE_MASK, setting inverse mask in fragment shader using gl_SampleMask, expecting:\n"
<< " 1) full discard on multisample targets (mask & modifiedCoverge == 0)\n"
<< " 2) full intensity (no discard) on singlesample targets. (Mask and coverage is only applied as a multisample operation.)\n"
<< tcu::TestLog::EndMessage;
else
DE_ASSERT(false);
SampleMaskBaseCase::init();
}
void SampleMaskWriteCase::preDraw (void)
{
const glw::Functions& gl = m_context.getRenderContext().getFunctions();
if (m_testMode == TEST_INVERSE)
{
// set mask to 0xAAAA.., set inverse mask bit coverage in shader
const int maskLoc = gl.getUniformLocation(m_program->getProgram(), "u_mask");
const deUint32 mask = (deUint32)0xAAAAAAAAUL;
if (maskLoc == -1)
throw tcu::TestError("Location of u_mask was -1");
gl.enable(GL_SAMPLE_MASK);
gl.sampleMaski(0, mask);
GLU_EXPECT_NO_ERROR(gl.getError(), "set mask");
gl.uniform1ui(maskLoc, mask);
GLU_EXPECT_NO_ERROR(gl.getError(), "set mask uniform");
m_testCtx.getLog() << tcu::TestLog::Message << "Setting sample mask " << tcu::Format::Hex<4>(mask) << tcu::TestLog::EndMessage;
}
SampleMaskBaseCase::preDraw();
}
void SampleMaskWriteCase::postDraw (void)
{
const glw::Functions& gl = m_context.getRenderContext().getFunctions();
if (m_testMode == TEST_INVERSE)
{
const deUint32 fullMask = (1U << m_numTargetSamples) - 1;
gl.disable(GL_SAMPLE_MASK);
gl.sampleMaski(0, fullMask);
GLU_EXPECT_NO_ERROR(gl.getError(), "set mask");
}
SampleMaskBaseCase::postDraw();
}
std::string SampleMaskWriteCase::genFragmentSource (int numTargetSamples) const
{
DE_ASSERT(numTargetSamples != 0);
DE_UNREF(numTargetSamples);
std::ostringstream buf;
const bool isES32 = glu::contextSupports(m_context.getRenderContext().getType(), glu::ApiType::es(3, 2));
map<string, string> args;
args["GLSL_VERSION_DECL"] = isES32 ? getGLSLVersionDeclaration(glu::GLSL_VERSION_320_ES) : getGLSLVersionDeclaration(glu::GLSL_VERSION_310_ES);
args["GLSL_EXTENSION"] = isES32 ? "" : "#extension GL_OES_sample_variables : require";
if (m_testMode == TEST_DISCARD)
{
// mask out every other coverage bit
buf << "${GLSL_VERSION_DECL}\n"
"${GLSL_EXTENSION}\n"
"layout(location = 0) out mediump vec4 fragColor;\n"
"void main (void)\n"
"{\n"
" for (int i = 0; i < gl_SampleMask.length(); ++i)\n"
" gl_SampleMask[i] = int(0xAAAAAAAA);\n"
"\n";
if (m_runMode == RUN_PER_SAMPLE)
buf << " // force per-sample shading\n"
" highp float blue = float(gl_SampleID);\n"
"\n"
" fragColor = vec4(0.0, 1.0, blue, 1.0);\n"
"}\n";
else
buf << " fragColor = vec4(0.0, 1.0, 0.0, 1.0);\n"
"}\n";
}
else if (m_testMode == TEST_INVERSE)
{
// inverse every coverage bit
buf << "${GLSL_VERSION_DECL}\n"
"${GLSL_EXTENSION}\n"
"layout(location = 0) out mediump vec4 fragColor;\n"
"uniform highp uint u_mask;\n"
"void main (void)\n"
"{\n"
" gl_SampleMask[0] = int(~u_mask);\n"
"\n";
if (m_runMode == RUN_PER_SAMPLE)
buf << " // force per-sample shading\n"
" highp float blue = float(gl_SampleID);\n"
"\n"
" fragColor = vec4(0.0, 1.0, blue, 1.0);\n"
"}\n";
else
buf << " fragColor = vec4(0.0, 1.0, 0.0, 1.0);\n"
"}\n";
}
else
DE_ASSERT(false);
return tcu::StringTemplate(buf.str()).specialize(args);
}
bool SampleMaskWriteCase::verifyImage (const tcu::Surface& resultImage)
{
const bool singleSampleTarget = m_numRequestedSamples == 0 && !(m_renderTarget == TARGET_DEFAULT && m_context.getRenderTarget().getNumSamples() > 1);
if (m_testMode == TEST_DISCARD)
{
if (singleSampleTarget)
{
// single sample case => multisample operations are not effective => don't discard anything
// expect green
return verifyImageWithVerifier(resultImage, m_testCtx.getLog(), ColorVerifier(tcu::Vec3(0.0f, 1.0f, 0.0f)));
}
else if (m_numTargetSamples == 1)
{
// total discard, expect black
return verifyImageWithVerifier(resultImage, m_testCtx.getLog(), ColorVerifier(tcu::Vec3(0.0f, 0.0f, 0.0f)));
}
else
{
// partial discard, expect something between black and green
return verifyImageWithVerifier(resultImage, m_testCtx.getLog(), PartialDiscardVerifier());
}
}
else if (m_testMode == TEST_INVERSE)
{
if (singleSampleTarget)
{
// single sample case => multisample operations are not effective => don't discard anything
// expect green
return verifyImageWithVerifier(resultImage, m_testCtx.getLog(), ColorVerifier(tcu::Vec3(0.0f, 1.0f, 0.0f)));
}
else
{
// total discard, expect black
return verifyImageWithVerifier(resultImage, m_testCtx.getLog(), ColorVerifier(tcu::Vec3(0.0f, 0.0f, 0.0f)));
}
}
else
{
DE_ASSERT(false);
return false;
}
}
} // anonymous
SampleVariableTests::SampleVariableTests (Context& context)
: TestCaseGroup(context, "sample_variables", "Test sample variables")
{
}
SampleVariableTests::~SampleVariableTests (void)
{
}
void SampleVariableTests::init (void)
{
tcu::TestCaseGroup* const numSampleGroup = new tcu::TestCaseGroup(m_testCtx, "num_samples", "Test NumSamples");
tcu::TestCaseGroup* const maxSampleGroup = new tcu::TestCaseGroup(m_testCtx, "max_samples", "Test MaxSamples");
tcu::TestCaseGroup* const sampleIDGroup = new tcu::TestCaseGroup(m_testCtx, "sample_id", "Test SampleID");
tcu::TestCaseGroup* const samplePosGroup = new tcu::TestCaseGroup(m_testCtx, "sample_pos", "Test SamplePosition");
tcu::TestCaseGroup* const sampleMaskInGroup = new tcu::TestCaseGroup(m_testCtx, "sample_mask_in", "Test SampleMaskIn");
tcu::TestCaseGroup* const sampleMaskGroup = new tcu::TestCaseGroup(m_testCtx, "sample_mask", "Test SampleMask");
addChild(numSampleGroup);
addChild(maxSampleGroup);
addChild(sampleIDGroup);
addChild(samplePosGroup);
addChild(sampleMaskInGroup);
addChild(sampleMaskGroup);
static const struct RenderTarget
{
const char* name;
const char* desc;
int numSamples;
MultisampleRenderCase::RenderTarget target;
} targets[] =
{
{ "default_framebuffer", "Test with default framebuffer", 0, MultisampleRenderCase::TARGET_DEFAULT },
{ "singlesample_texture", "Test with singlesample texture", 0, MultisampleRenderCase::TARGET_TEXTURE },
{ "multisample_texture_1", "Test with multisample texture", 1, MultisampleRenderCase::TARGET_TEXTURE },
{ "multisample_texture_2", "Test with multisample texture", 2, MultisampleRenderCase::TARGET_TEXTURE },
{ "multisample_texture_4", "Test with multisample texture", 4, MultisampleRenderCase::TARGET_TEXTURE },
{ "multisample_texture_8", "Test with multisample texture", 8, MultisampleRenderCase::TARGET_TEXTURE },
{ "multisample_texture_16", "Test with multisample texture", 16, MultisampleRenderCase::TARGET_TEXTURE },
{ "singlesample_rbo", "Test with singlesample rbo", 0, MultisampleRenderCase::TARGET_RENDERBUFFER },
{ "multisample_rbo_1", "Test with multisample rbo", 1, MultisampleRenderCase::TARGET_RENDERBUFFER },
{ "multisample_rbo_2", "Test with multisample rbo", 2, MultisampleRenderCase::TARGET_RENDERBUFFER },
{ "multisample_rbo_4", "Test with multisample rbo", 4, MultisampleRenderCase::TARGET_RENDERBUFFER },
{ "multisample_rbo_8", "Test with multisample rbo", 8, MultisampleRenderCase::TARGET_RENDERBUFFER },
{ "multisample_rbo_16", "Test with multisample rbo", 16, MultisampleRenderCase::TARGET_RENDERBUFFER },
};
// .num_samples
{
for (int targetNdx = 0; targetNdx < DE_LENGTH_OF_ARRAY(targets); ++targetNdx)
numSampleGroup->addChild(new NumSamplesCase(m_context, targets[targetNdx].name, targets[targetNdx].desc, targets[targetNdx].numSamples, targets[targetNdx].target));
}
// .max_samples
{
for (int targetNdx = 0; targetNdx < DE_LENGTH_OF_ARRAY(targets); ++targetNdx)
maxSampleGroup->addChild(new MaxSamplesCase(m_context, targets[targetNdx].name, targets[targetNdx].desc, targets[targetNdx].numSamples, targets[targetNdx].target));
}
// .sample_ID
{
for (int targetNdx = 0; targetNdx < DE_LENGTH_OF_ARRAY(targets); ++targetNdx)
sampleIDGroup->addChild(new SampleIDCase(m_context, targets[targetNdx].name, targets[targetNdx].desc, targets[targetNdx].numSamples, targets[targetNdx].target));
}
// .sample_pos
{
{
tcu::TestCaseGroup* const group = new tcu::TestCaseGroup(m_testCtx, "correctness", "Test SamplePos correctness");
samplePosGroup->addChild(group);
for (int targetNdx = 0; targetNdx < DE_LENGTH_OF_ARRAY(targets); ++targetNdx)
group->addChild(new SamplePosCorrectnessCase(m_context, targets[targetNdx].name, targets[targetNdx].desc, targets[targetNdx].numSamples, targets[targetNdx].target));
}
{
tcu::TestCaseGroup* const group = new tcu::TestCaseGroup(m_testCtx, "distribution", "Test SamplePos distribution");
samplePosGroup->addChild(group);
for (int targetNdx = 0; targetNdx < DE_LENGTH_OF_ARRAY(targets); ++targetNdx)
group->addChild(new SamplePosDistributionCase(m_context, targets[targetNdx].name, targets[targetNdx].desc, targets[targetNdx].numSamples, targets[targetNdx].target));
}
}
// .sample_mask_in
{
// .sample_mask
{
tcu::TestCaseGroup* const group = new tcu::TestCaseGroup(m_testCtx, "sample_mask", "Test with GL_SAMPLE_MASK");
sampleMaskInGroup->addChild(group);
for (int targetNdx = 0; targetNdx < DE_LENGTH_OF_ARRAY(targets); ++targetNdx)
group->addChild(new SampleMaskCase(m_context, targets[targetNdx].name, targets[targetNdx].desc, targets[targetNdx].numSamples, targets[targetNdx].target));
}
// .bit_count_per_pixel
{
tcu::TestCaseGroup* const group = new tcu::TestCaseGroup(m_testCtx, "bit_count_per_pixel", "Test number of coverage bits");
sampleMaskInGroup->addChild(group);
for (int targetNdx = 0; targetNdx < DE_LENGTH_OF_ARRAY(targets); ++targetNdx)
group->addChild(new SampleMaskCountCase(m_context, targets[targetNdx].name, targets[targetNdx].desc, targets[targetNdx].numSamples, targets[targetNdx].target, SampleMaskCountCase::RUN_PER_PIXEL));
}
// .bit_count_per_sample
{
tcu::TestCaseGroup* const group = new tcu::TestCaseGroup(m_testCtx, "bit_count_per_sample", "Test number of coverage bits");
sampleMaskInGroup->addChild(group);
for (int targetNdx = 0; targetNdx < DE_LENGTH_OF_ARRAY(targets); ++targetNdx)
group->addChild(new SampleMaskCountCase(m_context, targets[targetNdx].name, targets[targetNdx].desc, targets[targetNdx].numSamples, targets[targetNdx].target, SampleMaskCountCase::RUN_PER_SAMPLE));
}
// .bit_count_per_two_samples
{
tcu::TestCaseGroup* const group = new tcu::TestCaseGroup(m_testCtx, "bit_count_per_two_samples", "Test number of coverage bits");
sampleMaskInGroup->addChild(group);
for (int targetNdx = 0; targetNdx < DE_LENGTH_OF_ARRAY(targets); ++targetNdx)
group->addChild(new SampleMaskCountCase(m_context, targets[targetNdx].name, targets[targetNdx].desc, targets[targetNdx].numSamples, targets[targetNdx].target, SampleMaskCountCase::RUN_PER_TWO_SAMPLES));
}
// .bits_unique_per_sample
{
tcu::TestCaseGroup* const group = new tcu::TestCaseGroup(m_testCtx, "bits_unique_per_sample", "Test coverage bits");
sampleMaskInGroup->addChild(group);
for (int targetNdx = 0; targetNdx < DE_LENGTH_OF_ARRAY(targets); ++targetNdx)
if (targets[targetNdx].target == MultisampleRenderCase::TARGET_TEXTURE)
group->addChild(new SampleMaskUniqueCase(m_context, targets[targetNdx].name, targets[targetNdx].desc, targets[targetNdx].numSamples, targets[targetNdx].target, SampleMaskUniqueCase::RUN_PER_SAMPLE));
}
// .bits_unique_per_two_samples
{
tcu::TestCaseGroup* const group = new tcu::TestCaseGroup(m_testCtx, "bits_unique_per_two_samples", "Test coverage bits");
sampleMaskInGroup->addChild(group);
for (int targetNdx = 0; targetNdx < DE_LENGTH_OF_ARRAY(targets); ++targetNdx)
if (targets[targetNdx].target == MultisampleRenderCase::TARGET_TEXTURE)
group->addChild(new SampleMaskUniqueSetCase(m_context, targets[targetNdx].name, targets[targetNdx].desc, targets[targetNdx].numSamples, targets[targetNdx].target, SampleMaskUniqueCase::RUN_PER_TWO_SAMPLES));
}
}
// .sample_mask
{
// .discard_half_per_pixel
{
tcu::TestCaseGroup* const group = new tcu::TestCaseGroup(m_testCtx, "discard_half_per_pixel", "Test coverage bits");
sampleMaskGroup->addChild(group);
for (int targetNdx = 0; targetNdx < DE_LENGTH_OF_ARRAY(targets); ++targetNdx)
group->addChild(new SampleMaskWriteCase(m_context, targets[targetNdx].name, targets[targetNdx].desc, targets[targetNdx].numSamples, targets[targetNdx].target, SampleMaskWriteCase::RUN_PER_PIXEL, SampleMaskWriteCase::TEST_DISCARD));
}
// .discard_half_per_sample
{
tcu::TestCaseGroup* const group = new tcu::TestCaseGroup(m_testCtx, "discard_half_per_sample", "Test coverage bits");
sampleMaskGroup->addChild(group);
for (int targetNdx = 0; targetNdx < DE_LENGTH_OF_ARRAY(targets); ++targetNdx)
group->addChild(new SampleMaskWriteCase(m_context, targets[targetNdx].name, targets[targetNdx].desc, targets[targetNdx].numSamples, targets[targetNdx].target, SampleMaskWriteCase::RUN_PER_SAMPLE, SampleMaskWriteCase::TEST_DISCARD));
}
// .discard_half_per_two_samples
{
tcu::TestCaseGroup* const group = new tcu::TestCaseGroup(m_testCtx, "discard_half_per_two_samples", "Test coverage bits");
sampleMaskGroup->addChild(group);
for (int targetNdx = 0; targetNdx < DE_LENGTH_OF_ARRAY(targets); ++targetNdx)
group->addChild(new SampleMaskWriteCase(m_context, targets[targetNdx].name, targets[targetNdx].desc, targets[targetNdx].numSamples, targets[targetNdx].target, SampleMaskWriteCase::RUN_PER_TWO_SAMPLES, SampleMaskWriteCase::TEST_DISCARD));
}
// .discard_half_per_two_samples
{
tcu::TestCaseGroup* const group = new tcu::TestCaseGroup(m_testCtx, "inverse_per_pixel", "Test coverage bits");
sampleMaskGroup->addChild(group);
for (int targetNdx = 0; targetNdx < DE_LENGTH_OF_ARRAY(targets); ++targetNdx)
group->addChild(new SampleMaskWriteCase(m_context, targets[targetNdx].name, targets[targetNdx].desc, targets[targetNdx].numSamples, targets[targetNdx].target, SampleMaskWriteCase::RUN_PER_PIXEL, SampleMaskWriteCase::TEST_INVERSE));
}
// .inverse_per_sample
{
tcu::TestCaseGroup* const group = new tcu::TestCaseGroup(m_testCtx, "inverse_per_sample", "Test coverage bits");
sampleMaskGroup->addChild(group);
for (int targetNdx = 0; targetNdx < DE_LENGTH_OF_ARRAY(targets); ++targetNdx)
group->addChild(new SampleMaskWriteCase(m_context, targets[targetNdx].name, targets[targetNdx].desc, targets[targetNdx].numSamples, targets[targetNdx].target, SampleMaskWriteCase::RUN_PER_SAMPLE, SampleMaskWriteCase::TEST_INVERSE));
}
// .inverse_per_two_samples
{
tcu::TestCaseGroup* const group = new tcu::TestCaseGroup(m_testCtx, "inverse_per_two_samples", "Test coverage bits");
sampleMaskGroup->addChild(group);
for (int targetNdx = 0; targetNdx < DE_LENGTH_OF_ARRAY(targets); ++targetNdx)
group->addChild(new SampleMaskWriteCase(m_context, targets[targetNdx].name, targets[targetNdx].desc, targets[targetNdx].numSamples, targets[targetNdx].target, SampleMaskWriteCase::RUN_PER_TWO_SAMPLES, SampleMaskWriteCase::TEST_INVERSE));
}
}
}
} // Functional
} // gles31
} // deqp
| 34.946286 | 241 | 0.694874 | [
"render",
"vector"
] |
0576bda33ef0288dfc85be9a59382c9152f0ee16 | 953 | cpp | C++ | 1101-9999/1298. Maximum Candies You Can Get from Boxes.cpp | erichuang1994/leetcode-solution | d5b3bb3ce2a428a3108f7369715a3700e2ba699d | [
"MIT"
] | null | null | null | 1101-9999/1298. Maximum Candies You Can Get from Boxes.cpp | erichuang1994/leetcode-solution | d5b3bb3ce2a428a3108f7369715a3700e2ba699d | [
"MIT"
] | null | null | null | 1101-9999/1298. Maximum Candies You Can Get from Boxes.cpp | erichuang1994/leetcode-solution | d5b3bb3ce2a428a3108f7369715a3700e2ba699d | [
"MIT"
] | null | null | null | class Solution
{
public:
int maxCandies(vector<int> &status, vector<int> &candies, vector<vector<int>> &keys, vector<vector<int>> &contain, vector<int> &init)
{
vector<bool> have(status.size());
deque<int> dq;
long ret = 0;
for (auto i : init)
{
have[i] = true;
if (status[i])
{
dq.emplace_back(i);
}
}
while (!dq.empty())
{
int sz = dq.size();
for (int i = 0; i < sz; ++i)
{
auto back = dq.front();
dq.pop_front();
ret += candies[back];
for (auto b : contain[back])
{
have[b] = true;
if (status[b])
{
dq.emplace_back(b);
}
}
for (auto k : keys[back])
{
if (status[k])
continue;
status[k] = 1;
if (have[k])
{
dq.emplace_back(k);
}
}
}
}
return ret;
}
}; | 20.276596 | 135 | 0.422875 | [
"vector"
] |
0580a77268c76ded873536dae75d0769be8143c8 | 2,526 | cpp | C++ | PHKControllerRecord.cpp | gerarddejong/home-kit-service | c338828fd15d62e436b932b616b7a06742a60b19 | [
"MIT"
] | 181 | 2015-06-24T17:16:13.000Z | 2022-01-30T19:02:29.000Z | PHKControllerRecord.cpp | gerarddejong/home-kit-service | c338828fd15d62e436b932b616b7a06742a60b19 | [
"MIT"
] | 33 | 2015-06-26T09:36:30.000Z | 2021-09-08T07:35:10.000Z | PHKControllerRecord.cpp | gerarddejong/home-kit-service | c338828fd15d62e436b932b616b7a06742a60b19 | [
"MIT"
] | 68 | 2015-06-24T20:06:37.000Z | 2021-06-01T02:07:56.000Z | //
// PHKKeyRecord.cpp
// Workbench
//
// Created by Wai Man Chan on 9/23/14.
//
//
#include "PHKControllerRecord.h"
#include "Configuration.h"
#include <vector>
#include <strings.h>
#if MCU
#else
#include <fstream>
#endif
using namespace std;
vector<PHKKeyRecord>readIn();
vector<PHKKeyRecord>controllerRecords = readIn();
vector<PHKKeyRecord>readIn() {
ifstream fs;
#if MCU
#else
fs.open(controllerRecordsAddress, std::ifstream::in);
#endif
char buffer[70];
bzero(buffer, 70);
PHKKeyRecord record;
vector<PHKKeyRecord> results;
#if MCU
#else
bool isEmpty = fs.peek() == EOF;
while (!isEmpty&&fs.is_open()&&fs.good()&&!fs.eof()) {
fs.get(buffer, 69);
#endif
bcopy(buffer, record.controllerID, 36);
bcopy(&buffer[36], record.publicKey, 32);
results.push_back(record);
}
#if MCU
#else
fs.close();
#endif
return results;
}
void resetControllerRecord() {
ofstream fs;
fs.open(controllerRecordsAddress, std::ofstream::out|std::ofstream::trunc);
}
bool hasController() {
return controllerRecords.size() > 0;
}
void addControllerKey(PHKKeyRecord record) {
if (doControllerKeyExist(record) == false) {
controllerRecords.push_back(record);
#if MCU
#else
ofstream fs;
fs.open(controllerRecordsAddress, std::ofstream::trunc);
#endif
for (vector<PHKKeyRecord>::iterator it = controllerRecords.begin(); it != controllerRecords.end(); it++) {
#if MCU
#else
fs.write(it->controllerID, 36);
fs.write(it->publicKey, 32);
#endif
}
fs.close();
}
}
bool doControllerKeyExist(PHKKeyRecord record) {
for (vector<PHKKeyRecord>::iterator it = controllerRecords.begin(); it != controllerRecords.end(); it++) {
if (bcmp((*it).controllerID, record.controllerID, 32) == 0) return true;
}
return false;
}
void removeControllerKey(PHKKeyRecord record) {
for (vector<PHKKeyRecord>::iterator it = controllerRecords.begin(); it != controllerRecords.end(); it++) {
if (bcmp((*it).controllerID, record.controllerID, 32) == 0) {
controllerRecords.push_back(record);
return;
}
}
}
PHKKeyRecord getControllerKey(char key[32]) {
for (vector<PHKKeyRecord>::iterator it = controllerRecords.begin(); it != controllerRecords.end(); it++) {
if (bcmp(key, it->controllerID, 32) == 0) return *it;
}
PHKKeyRecord emptyRecord;
bzero(emptyRecord.controllerID, 32);
return emptyRecord;
}
| 22.553571 | 114 | 0.649644 | [
"vector"
] |
05859d674e00e6b624f79f3cadc307eda26ba371 | 8,068 | cpp | C++ | copasi/utilities/CUnitDefinitionDB.cpp | tobiaselsaesser/COPASI | 7e61c1b1667b0f4acf8f3865fe557603f221c472 | [
"Artistic-2.0"
] | null | null | null | copasi/utilities/CUnitDefinitionDB.cpp | tobiaselsaesser/COPASI | 7e61c1b1667b0f4acf8f3865fe557603f221c472 | [
"Artistic-2.0"
] | null | null | null | copasi/utilities/CUnitDefinitionDB.cpp | tobiaselsaesser/COPASI | 7e61c1b1667b0f4acf8f3865fe557603f221c472 | [
"Artistic-2.0"
] | null | null | null | // Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
#include "utilities/CUnitDefinitionDB.h"
#include "utilities/CUnitDefinition.h"
#include "utilities/CCopasiMessage.h"
#include "copasi/core/CRootContainer.h"
CUnitDefinitionDB::CUnitDefinitionDB(const std::string & name,
const CDataContainer * pParent):
CDataVectorN< CUnitDefinition >(name, pParent),
mSymbolToUnitDefinitions()
{}
//virtual
bool CUnitDefinitionDB::add(const CUnitDefinition & src)
{
// This form will construct a copy, before adding (inherited
// from CDataVectorN). When the CUnitDefinition
// copy constructor is called, an exception will be thrown if
// the symbol is already in use.
// If it's symbol is already present, this form will not add
// a pointer to the src object, and will return false.
if (containsSymbol(src.getSymbol()) ||
getIndex(src.getObjectName()) != C_INVALID_INDEX)
{
return false;
}
CUnitDefinition * pCopy = NULL;
try
{
pCopy = new CUnitDefinition(src, this);
}
catch (...)
{
return false;
}
return true;
}
//virtual
bool CUnitDefinitionDB::add(CUnitDefinition * src, bool adopt)
{
// If it's symbol is already present, this form will not add
// a pointer to the src object, and will return false.
if (containsSymbol(src->getSymbol()) ||
getIndex(src->getObjectName()) != C_INVALID_INDEX)
{
return false;
}
CDataVectorN< CUnitDefinition >::add(src, adopt);
mSymbolToUnitDefinitions[src->getSymbol()] = src;
if (src->getSymbol() == "\xCE\xA9")
{
mSymbolToUnitDefinitions["O"] = src;
}
return true;
}
//virtual
void CUnitDefinitionDB::remove(const size_t & index)
{
remove(&operator [](index));
}
//virtual
bool CUnitDefinitionDB::remove(CDataObject * pObject)
{
CUnitDefinition * pUnitDef = dynamic_cast< CUnitDefinition * >(pObject);
if (pUnitDef)
{
mSymbolToUnitDefinitions.erase(pUnitDef->getSymbol());
}
return CDataVector< CUnitDefinition >::remove(pObject);
}
//virtual
void CUnitDefinitionDB::remove(const std::string & name)
{
remove(&operator [](name));
}
bool CUnitDefinitionDB::containsSymbol(std::string symbol)
{
return (symbol == "?" ||
mSymbolToUnitDefinitions.count(symbol) > 0);
}
const CUnitDefinition * CUnitDefinitionDB::getUnitDefFromSymbol(std::string symbol) const
{
std::map<std::string, CUnitDefinition *>::const_iterator found = mSymbolToUnitDefinitions.find(unQuote(symbol));
if (found != mSymbolToUnitDefinitions.end())
{
return found->second;
}
return NULL;
}
bool CUnitDefinitionDB::changeSymbol(CUnitDefinition *pUnitDef, const std::string & symbol)
{
if (pUnitDef->getObjectParent() != this) return true;
std::map<std::string, CUnitDefinition *>::iterator New = mSymbolToUnitDefinitions.find(symbol);
std::map<std::string, CUnitDefinition *>::iterator Old = mSymbolToUnitDefinitions.find(pUnitDef->getSymbol());
if (New == mSymbolToUnitDefinitions.end())
{
if (New != Old)
{
mSymbolToUnitDefinitions.insert(std::make_pair(symbol, pUnitDef));
replaceSymbol(pUnitDef->getSymbol(), symbol);
mSymbolToUnitDefinitions.erase(Old);
return true;
}
else
{
mSymbolToUnitDefinitions.insert(std::make_pair(symbol, pUnitDef));
return true;
}
}
else
{
if (New == Old)
{
replaceSymbol(pUnitDef->getSymbol(), symbol);
return true;
}
else
{
return false;
}
}
return true;
}
std::string CUnitDefinitionDB::quoteSymbol(const std::string & symbol) const
{
const CUnitDefinition * pUnitDef = getUnitDefFromSymbol(symbol);
if (pUnitDef == NULL ||
CUnit(symbol) == *pUnitDef) return symbol;
return quote(" " + symbol).erase(1, 1);
}
void CUnitDefinitionDB::replaceSymbol(const std::string & oldSymbol,
const std::string & newSymbol)
{
iterator it = begin();
iterator end = this->end();
for (; it != end; ++it)
{
it->replaceSymbol(oldSymbol, newSymbol);
}
if (getObjectParent() == CRootContainer::getRoot())
{
CRootContainer::replaceSymbol(oldSymbol, newSymbol);
}
}
std::vector< CUnit > CUnitDefinitionDB::getAllValidUnits(const std::string & symbol,
const C_FLOAT64 & exponent) const
{
std::vector< CUnit > ValidUnits;
if (getUnitDefFromSymbol(symbol) == NULL)
{
return ValidUnits;
}
std::set< CUnit > ValidUnitSet;
CUnit Base(symbol);
CUnit Power = Base.exponentiate(exponent);
// dimensionless is always valid
ValidUnitSet.insert(CUnit(CBaseUnit::dimensionless));
const_iterator it = begin();
const_iterator itEnd = end();
for (; it != itEnd; ++it)
{
if (it->isEquivalent(Power) ||
it->isEquivalent(Base))
{
if ((it->getComponents().begin()->getMultiplier() == 1.0 ||
it->getSymbol() == "l") &&
!it->CUnit::operator==(CBaseUnit::item))
{
for (C_INT32 scale = -18; scale < 18; scale += 3)
{
CUnit Scale;
Scale.addComponent(CUnitComponent(CBaseUnit::dimensionless, 1.0, scale, 0));
CUnit ScaledUnit(Scale * CUnit(it->getSymbol()));
if (it->isEquivalent(Base))
{
ScaledUnit = ScaledUnit.exponentiate(exponent);
}
ScaledUnit.buildExpression();
ValidUnitSet.insert(ScaledUnit);
}
}
else
{
CUnit ScaledUnit(it->getSymbol());
if (it->isEquivalent(Base))
{
ScaledUnit = ScaledUnit.exponentiate(exponent);
}
ScaledUnit.buildExpression();
ValidUnitSet.insert(ScaledUnit);
}
}
}
ValidUnits.insert(ValidUnits.begin(), ValidUnitSet.begin(), ValidUnitSet.end());
return ValidUnits;
}
bool CUnitDefinitionDB::appendDependentUnits(std::set< const CDataObject * > candidates,
std::set< const CDataObject * > & dependentUnits) const
{
std::set< std::string > DeletedSymbols;
std::set< const CDataObject * >::const_iterator itCandidate = candidates.begin();
std::set< const CDataObject * >::const_iterator endCandidate = candidates.end();
for (; itCandidate != endCandidate; ++itCandidate)
{
const CUnitDefinition * pUnit = dynamic_cast< const CUnitDefinition * >(*itCandidate);
if (pUnit)
{
DeletedSymbols.insert(pUnit->getSymbol());
}
}
CDataVectorN< CUnitDefinition >::const_iterator it = begin();
CDataVectorN< CUnitDefinition >::const_iterator itEnd = end();
for (; it != itEnd; ++it)
{
std::set< std::string >::const_iterator itUsedSymbols = it->getUsedSymbols().begin();
std::set< std::string >::const_iterator endUsedSymbols = it->getUsedSymbols().end();
std::set< std::string >::const_iterator itDeletedSymbols = DeletedSymbols.begin();
std::set< std::string >::const_iterator endDeletedSymbols = DeletedSymbols.end();
while (itUsedSymbols != endUsedSymbols && itDeletedSymbols != endDeletedSymbols)
{
if (*itUsedSymbols < *itDeletedSymbols)
{
++itUsedSymbols;
continue;
}
if (*itDeletedSymbols < *itUsedSymbols)
{
++itDeletedSymbols;
continue;
}
dependentUnits.insert(&*it);
break;
}
}
return dependentUnits.size() > 0;
}
| 26.803987 | 114 | 0.620972 | [
"object",
"vector"
] |
0589115901ff4a16a2eca106e107e35c1c3b27be | 5,648 | cpp | C++ | qt-creator-opensource-src-4.6.1/tests/unit/unittest/projectupdater-test.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 5 | 2018-12-22T14:49:13.000Z | 2022-01-13T07:21:46.000Z | qt-creator-opensource-src-4.6.1/tests/unit/unittest/projectupdater-test.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | null | null | null | qt-creator-opensource-src-4.6.1/tests/unit/unittest/projectupdater-test.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 8 | 2018-07-17T03:55:48.000Z | 2021-12-22T06:37:53.000Z | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "googletest.h"
#include "mockpchmanagerclient.h"
#include "mockpchmanagernotifier.h"
#include "mockpchmanagerserver.h"
#include <pchmanagerprojectupdater.h>
#include <pchmanagerclient.h>
#include <precompiledheadersupdatedmessage.h>
#include <removepchprojectpartsmessage.h>
#include <updatepchprojectpartsmessage.h>
#include <cpptools/compileroptionsbuilder.h>
#include <cpptools/projectpart.h>
namespace {
using testing::_;
using testing::ElementsAre;
using testing::SizeIs;
using testing::NiceMock;
using testing::AnyNumber;
using ClangBackEnd::V2::FileContainer;
using ClangBackEnd::V2::ProjectPartContainer;
using CppTools::CompilerOptionsBuilder;
class ProjectUpdater : public testing::Test
{
protected:
void SetUp() override;
protected:
ClangPchManager::PchManagerClient pchManagerClient;
MockPchManagerNotifier mockPchManagerNotifier{pchManagerClient};
NiceMock<MockPchManagerServer> mockPchManagerServer;
ClangPchManager::ProjectUpdater updater{mockPchManagerServer};
Utils::SmallString projectPartId{"project1"};
Utils::SmallString projectPartId2{"project2"};
Utils::PathStringVector headerPaths = {"/path/to/header1.h", "/path/to/header2.h"};
Utils::PathStringVector sourcePaths = {"/path/to/source1.cpp", "/path/to/source2.cpp"};
CppTools::ProjectFile header1ProjectFile{QString(headerPaths[0]), CppTools::ProjectFile::CXXHeader};
CppTools::ProjectFile header2ProjectFile{QString(headerPaths[1]), CppTools::ProjectFile::CXXHeader};
CppTools::ProjectFile source1ProjectFile{QString(sourcePaths[0]), CppTools::ProjectFile::CXXSource};
CppTools::ProjectFile source2ProjectFile{QString(sourcePaths[1]), CppTools::ProjectFile::CXXSource};
CppTools::ProjectPart projectPart;
ProjectPartContainer expectedContainer;
FileContainer generatedFile{{"/path/to", "header1.h"}, "content", {}};
};
TEST_F(ProjectUpdater, CallUpdatePchProjectParts)
{
std::vector<CppTools::ProjectPart*> projectParts = {&projectPart, &projectPart};
ClangBackEnd::UpdatePchProjectPartsMessage message{{expectedContainer.clone(), expectedContainer.clone()},
{generatedFile}};
EXPECT_CALL(mockPchManagerServer, updatePchProjectParts(message));
updater.updateProjectParts(projectParts, {generatedFile});
}
TEST_F(ProjectUpdater, CallRemovePchProjectParts)
{
ClangBackEnd::RemovePchProjectPartsMessage message{{projectPartId, projectPartId2}};
EXPECT_CALL(mockPchManagerServer, removePchProjectParts(message));
updater.removeProjectParts({QString(projectPartId), QString(projectPartId2)});
}
TEST_F(ProjectUpdater, CallPrecompiledHeaderRemovedInPchManagerProjectUpdater)
{
ClangPchManager::PchManagerProjectUpdater pchUpdater{mockPchManagerServer, pchManagerClient};
ClangBackEnd::RemovePchProjectPartsMessage message{{projectPartId, projectPartId2}};
EXPECT_CALL(mockPchManagerNotifier, precompiledHeaderRemoved(projectPartId.toQString()));
EXPECT_CALL(mockPchManagerNotifier, precompiledHeaderRemoved(projectPartId2.toQString()));
pchUpdater.removeProjectParts({QString(projectPartId), QString(projectPartId2)});
}
TEST_F(ProjectUpdater, ConvertProjectPartToProjectPartContainer)
{
updater.setExcludedPaths({"/path/to/header1.h"});
auto container = updater.toProjectPartContainer(&projectPart);
ASSERT_THAT(container, expectedContainer);
}
TEST_F(ProjectUpdater, ConvertProjectPartToProjectPartContainersHaveSameSizeLikeProjectParts)
{
auto containers = updater.toProjectPartContainers({&projectPart, &projectPart});
ASSERT_THAT(containers, SizeIs(2));
}
TEST_F(ProjectUpdater, CreateExcludedPaths)
{
auto excludedPaths = updater.createExcludedPaths({generatedFile});
ASSERT_THAT(excludedPaths, ElementsAre("/path/to/header1.h"));
}
void ProjectUpdater::SetUp()
{
projectPart.files.push_back(header1ProjectFile);
projectPart.files.push_back(header2ProjectFile);
projectPart.files.push_back(source1ProjectFile);
projectPart.files.push_back(source2ProjectFile);
projectPart.displayName = QString(projectPartId);
Utils::SmallStringVector arguments{ClangPchManager::ProjectUpdater::compilerArguments(
&projectPart)};
expectedContainer = {projectPartId.clone(),
arguments.clone(),
{headerPaths[1]},
sourcePaths.clone()};
}
}
| 37.653333 | 110 | 0.745042 | [
"vector"
] |
058c1431352586a82bb975682252bbd8b4c458f4 | 988 | hpp | C++ | stan/math/rev/mat/fun/grad.hpp | jrmie/math | 2850ec262181075a5843968e805dc9ad1654e069 | [
"BSD-3-Clause"
] | null | null | null | stan/math/rev/mat/fun/grad.hpp | jrmie/math | 2850ec262181075a5843968e805dc9ad1654e069 | [
"BSD-3-Clause"
] | null | null | null | stan/math/rev/mat/fun/grad.hpp | jrmie/math | 2850ec262181075a5843968e805dc9ad1654e069 | [
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_MATH_REV_MAT_FUN_GRAD_HPP
#define STAN_MATH_REV_MAT_FUN_GRAD_HPP
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/rev/mat/fun/Eigen_NumTraits.hpp>
#include <stan/math/rev/core.hpp>
namespace stan {
namespace math {
/**
* Propagate chain rule to calculate gradients starting from
* the specified variable. Resizes the input vector to be the
* correct size.
*
* The grad() function does not itself recover any memory. use
* <code>recover_memory()</code> or
* <code>recover_memory_nested()</code> to recover memory.
*
* @param[in] v Value of function being differentiated
* @param[in] x Variables being differentiated with respect to
* @param[out] g Gradient, d/dx v, evaluated at x.
*/
inline void grad(var& v, Eigen::Matrix<var, Eigen::Dynamic, 1>& x,
Eigen::VectorXd& g) {
grad(v.vi_);
g.resize(x.size());
for (int i = 0; i < x.size(); ++i)
g(i) = x(i).vi_->adj_;
}
} // namespace math
} // namespace stan
#endif
| 28.228571 | 66 | 0.691296 | [
"vector"
] |
059008b673063ca6d077b966277bd180564abdbf | 8,145 | cpp | C++ | Common/MdfModel/Path.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 2 | 2017-04-19T01:38:30.000Z | 2020-07-31T03:05:32.000Z | Common/MdfModel/Path.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | null | null | null | Common/MdfModel/Path.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 1 | 2021-12-29T10:46:12.000Z | 2021-12-29T10:46:12.000Z | //
// Copyright (C) 2007-2011 by Autodesk, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of version 2.1 of the GNU Lesser
// General Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
//-------------------------------------------------------------------------
// DESCRIPTION:
// The Path class implementation.
//-------------------------------------------------------------------------
#include "stdafx.h"
#include "Path.h"
using namespace MDFMODEL_NAMESPACE;
// initialize values for string properties
const wchar_t* Path::sLineCapDefault = L"'Round'"; // NOXLATE
const wchar_t* Path::sLineCapValues = L"None|Round|Triangle|Square"; // NOXLATE
const wchar_t* Path::sLineJoinDefault = L"'Round'"; // NOXLATE
const wchar_t* Path::sLineJoinValues = L"None|Bevel|Round|Miter"; // NOXLATE
//-------------------------------------------------------------------------
// PURPOSE: Initialize an instance of the Path class.
//-------------------------------------------------------------------------
Path::Path()
{
// default values
// NOTE: values used in IOPath::Write must match these
// this->m_sGeometry = L""; // NOXLATE
// this->m_sFillColor = L""; // NOXLATE
// this->m_sLineColor = L""; // NOXLATE
this->m_sLineWeight = L"0.0"; // NOXLATE
this->m_sLineWeightScalable = L"true"; // NOXLATE
this->m_sLineCap = Path::sLineCapDefault;
this->m_sLineJoin = Path::sLineJoinDefault;
this->m_sLineMiterLimit = L"5.0"; // NOXLATE
this->m_sScaleX = L"1.0"; // NOXLATE
this->m_sScaleY = L"1.0"; // NOXLATE
}
//-------------------------------------------------------------------------
// PURPOSE: Destructor. Delete all objects that have been created on the
// heap or have been adopted.
//-------------------------------------------------------------------------
Path::~Path()
{
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
const MdfString& Path::GetGeometry() const
{
return this->m_sGeometry;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
void Path::SetGeometry(const MdfString& geometry)
{
this->m_sGeometry = geometry;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
const MdfString& Path::GetFillColor() const
{
return this->m_sFillColor;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
void Path::SetFillColor(const MdfString& fillColor)
{
this->m_sFillColor = fillColor;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
const MdfString& Path::GetLineColor() const
{
return this->m_sLineColor;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
void Path::SetLineColor(const MdfString& lineColor)
{
this->m_sLineColor = lineColor;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
const MdfString& Path::GetLineWeight() const
{
return this->m_sLineWeight;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
void Path::SetLineWeight(const MdfString& lineWeight)
{
this->m_sLineWeight = lineWeight;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
const MdfString& Path::GetLineWeightScalable() const
{
return this->m_sLineWeightScalable;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
void Path::SetLineWeightScalable(const MdfString& lineWeightScalable)
{
this->m_sLineWeightScalable = lineWeightScalable;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
const MdfString& Path::GetLineCap() const
{
return this->m_sLineCap;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
void Path::SetLineCap(const MdfString& lineCap)
{
this->m_sLineCap = lineCap;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
const MdfString& Path::GetLineJoin() const
{
return this->m_sLineJoin;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
void Path::SetLineJoin(const MdfString& lineJoin)
{
this->m_sLineJoin = lineJoin;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
const MdfString& Path::GetLineMiterLimit() const
{
return this->m_sLineMiterLimit;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
void Path::SetLineMiterLimit(const MdfString& lineMiterLimit)
{
this->m_sLineMiterLimit = lineMiterLimit;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
const MdfString& Path::GetScaleX() const
{
return this->m_sScaleX;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
void Path::SetScaleX(const MdfString& scaleX)
{
this->m_sScaleX = scaleX;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
const MdfString& Path::GetScaleY() const
{
return this->m_sScaleY;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
void Path::SetScaleY(const MdfString& scaleY)
{
this->m_sScaleY = scaleY;
}
//-------------------------------------------------------------------------
// PURPOSE:
// PARAMETERS:
//-------------------------------------------------------------------------
void Path::AcceptVisitor(IGraphicElementVisitor& igeVisitor)
{
igeVisitor.VisitPath(*this);
}
| 32.58 | 81 | 0.376182 | [
"geometry"
] |
059284030b0e1161f6e8df9d67e1e821d21d0310 | 2,378 | cpp | C++ | fuzztest/main.cpp | ExternalRepositories/charls | 482417c66d34b0d015cf9ecdb55de7c9a76ef0c9 | [
"BSD-3-Clause"
] | 133 | 2015-10-19T05:01:49.000Z | 2022-03-01T08:46:03.000Z | fuzztest/main.cpp | ExternalRepositories/charls | 482417c66d34b0d015cf9ecdb55de7c9a76ef0c9 | [
"BSD-3-Clause"
] | 110 | 2015-12-14T09:43:15.000Z | 2022-03-20T22:51:14.000Z | fuzztest/main.cpp | ExternalRepositories/charls | 482417c66d34b0d015cf9ecdb55de7c9a76ef0c9 | [
"BSD-3-Clause"
] | 64 | 2015-09-28T07:59:32.000Z | 2022-03-19T22:57:04.000Z | // Copyright (c) Team CharLS.
// SPDX-License-Identifier: BSD-3-Clause
#include <charls/charls.h>
#ifdef _MSC_VER
#include <io.h>
#else
#include <unistd.h>
#define _write write
#define _read read
#define _open open
#endif
#include <fcntl.h>
#include <cstring>
#include <iostream>
#include <vector>
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#ifndef __AFL_INIT
#define __AFL_INIT() // NOLINT(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#endif
#ifndef __AFL_LOOP
#define __AFL_LOOP(a) true // NOLINT(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp)
#endif
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
namespace {
auto generate_once()
{
const std::vector<uint8_t> source(3);
return charls::jpegls_encoder::encode(source, {1, 1, 8, 3});
}
} // namespace
int main(const int argc, const char* const argv[]) // NOLINT(bugprone-exception-escape)
{
int fd{};
if (argc == 2)
{
if (argv[1][0] == '\0')
{
try
{
// Write some small-ish JPEG-LS file to stdout
auto encoded_data{generate_once()};
const int result{
static_cast<int>(_write(1, encoded_data.data(), static_cast<unsigned int>(encoded_data.size())))};
return result != -1 && result == static_cast<int>(encoded_data.size()) ? EXIT_SUCCESS : EXIT_FAILURE;
}
catch (const std::exception& error)
{
std::cerr << "Failed to create the once: " << error.what() << '\n';
}
return EXIT_FAILURE;
}
fd = _open(argv[1], O_RDONLY);
if (fd < 0)
{
std::cerr << "Failed to open: " << argv[1] << strerror(errno) << '\n';
return EXIT_FAILURE;
}
}
__AFL_INIT();
while (__AFL_LOOP(100))
{
std::vector<uint8_t> source(1024 * 1024);
const size_t input_length = _read(fd, source.data(), static_cast<unsigned int>(source.size()));
source.resize(input_length);
try
{
std::vector<uint8_t> destination;
charls::jpegls_decoder::decode(source, destination);
}
catch (const charls::jpegls_error&)
{
}
}
return EXIT_SUCCESS;
}
| 22.865385 | 118 | 0.589992 | [
"vector"
] |
05937ee1e83e1122f8074e62b30d3eeafb940a77 | 1,263 | cc | C++ | topcoder/SRM/SRM-647-DIV-2/500/TravellingSalesmanEasy.cc | mathemage/CompetitiveProgramming | fe39017e3b017f9259f9c1e6385549270940be64 | [
"MIT"
] | 2 | 2015-08-18T09:51:19.000Z | 2019-01-29T03:18:10.000Z | topcoder/SRM/SRM-647-DIV-2/500/TravellingSalesmanEasy.cc | mathemage/CompetitiveProgramming | fe39017e3b017f9259f9c1e6385549270940be64 | [
"MIT"
] | null | null | null | topcoder/SRM/SRM-647-DIV-2/500/TravellingSalesmanEasy.cc | mathemage/CompetitiveProgramming | fe39017e3b017f9259f9c1e6385549270940be64 | [
"MIT"
] | null | null | null | /* ========================================
* Points : 289.99
* Total : 500
* Status : AC
==========================================*/
#include <bits/stdc++.h>
using namespace std;
#define FOR(I,A,B) for(int I = (A); I < (B); ++I)
#define REP(I,N) FOR(I,0,N)
#define ALL(A) (A).begin(), (A).end()
#define MSG(a) cout << #a << " == " << a << endl;
class TravellingSalesmanEasy {
public:
int getMaxProfit(int M, vector <int> profit, vector <int> city, vector <int> visit) {
int g = profit.size();
vector<pair<int, int>> goods(g);
REP(i,g) {
goods[i] = {city[i], -1 * profit[i]};
}
sort(ALL(goods));
sort(ALL(visit));
REP(i,g) {
MSG(goods[i].first)
MSG(goods[i].second)
}
for (int i = 0; i < visit.size(); ++i) {
MSG(visit[i])
}
vector<int> cnt(M);
for (auto & x : visit) {
cnt[x-1]++;
}
int result = 0;
REP(i,M) {
if (cnt[i] > 0) {
MSG(i+1) MSG(cnt[i])
int j = 0;
while (j < g && goods[j].first != i+1) j++;
MSG(j)
while (cnt[i]-- > 0 && j < g && goods[j].first == i+1) {
result -= goods[j].second;
j++;
}
MSG(result) cout << endl;
}
}
return result;
}
};
| 21.775862 | 87 | 0.433888 | [
"vector"
] |
0593f5a19dd623b182d97849d5b0aa8e83da80d4 | 2,112 | cpp | C++ | tools/benchmark/lib/asaga_sparse.cpp | sumau/tick | 1b56924a35463e12f7775bc0aec182364f26f2c6 | [
"BSD-3-Clause"
] | 411 | 2017-03-30T15:22:05.000Z | 2022-03-27T01:58:34.000Z | tools/benchmark/lib/asaga_sparse.cpp | saurabhdash/tick | bbc561804eb1fdcb4c71b9e3e2d83a66e7b13a48 | [
"BSD-3-Clause"
] | 345 | 2017-04-13T14:53:20.000Z | 2022-03-26T00:46:22.000Z | tools/benchmark/lib/asaga_sparse.cpp | saurabhdash/tick | bbc561804eb1fdcb4c71b9e3e2d83a66e7b13a48 | [
"BSD-3-Clause"
] | 102 | 2017-04-25T11:47:53.000Z | 2022-02-15T11:45:49.000Z | #include <vector>
#include "tick/solver/asaga.h"
#include "tick/linear_model/model_logreg.h"
#include "tick/prox/prox_elasticnet.h"
#include "shared_saga.ipp"
//
// Benchmark asaga performances
// The command lines arguments are the following
// dataset : a sparse dataset (for example generated with benchmark_utils.py
// n_threads : the number of threads to be used
// n_iter : the number of passes on the data
// record_every : how often metrics are computed
// verbose : verbose results on the fly if true, only summary if false
//
// Example
// First get the data ready
// python -c "from benchmark_util import save_url_dataset_for_cpp_benchmarks; save_url_dataset_for_cpp_benchmarks(5)"
// Then run asaga on url dataset with 5 days, 1 thread, 25 iterations, record every 5 and no verbose
// ./tick_asaga_sparse url.5 1 25 5 0
//
const constexpr int SEED = 42;
std::tuple<std::vector<double>, std::vector<double>> run_asaga_solver(
SBaseArrayDouble2dPtr features, SArrayDoublePtr labels, ulong n_iter, int n_threads,
int record_every, double strength, double ratio) {
const auto n_samples = features->n_rows();
auto model = std::make_shared<TModelLogReg<double> >(features, labels, false);
AtomicSAGA<double> asaga(
n_samples, 0,
RandType::unif,
1. / model->get_lip_max(),
record_every,
SEED,
n_threads
);
asaga.set_rand_max(n_samples);
asaga.set_model(model);
auto prox = std::make_shared<TProxElasticNet<double> >(
strength, ratio, 0, model->get_n_coeffs(), 0);
asaga.set_prox(prox);
asaga.solve((int) n_iter); // single solve call as iterations happen within threads
const auto &history = asaga.get_time_history();
const auto &iterates = asaga.get_iterate_history();
std::vector<double> objectives(iterates.size());
for (int i = 0; i < iterates.size(); ++i) {
objectives[i] = model->loss(*iterates[i]) + prox->value(*iterates[i]);
}
return std::make_tuple(history, objectives);
}
int main(int argc, char *argv[]) {
std::cout << "ASAGA" << std::endl;
submain(argc, argv, run_asaga_solver);
return 0;
}
| 31.522388 | 117 | 0.713542 | [
"vector",
"model"
] |
0595c7d0b19d0e260c5b2c991103daaeaf5eebac | 792 | cpp | C++ | problems/maximum_area_of_a_piece_of_cake_after_horizontal_and_vertical_cuts/solution.cpp | sauravchandra1/Leetcode | be89c7d8d93083326a94906a28bfad2342aa1dfe | [
"MIT"
] | null | null | null | problems/maximum_area_of_a_piece_of_cake_after_horizontal_and_vertical_cuts/solution.cpp | sauravchandra1/Leetcode | be89c7d8d93083326a94906a28bfad2342aa1dfe | [
"MIT"
] | null | null | null | problems/maximum_area_of_a_piece_of_cake_after_horizontal_and_vertical_cuts/solution.cpp | sauravchandra1/Leetcode | be89c7d8d93083326a94906a28bfad2342aa1dfe | [
"MIT"
] | null | null | null | class Solution {
public:
int maxArea(int h, int w, vector<int>& horizontalCuts, vector<int>& verticalCuts) {
sort(horizontalCuts.begin(), horizontalCuts.end());
sort(verticalCuts.begin(), verticalCuts.end());
int lh = horizontalCuts.size();
int lw = verticalCuts.size();
long long int H = horizontalCuts[0], W = verticalCuts[0];
for (int i = 1; i < lh; i++)
H = max((int)H, horizontalCuts[i] - horizontalCuts[i - 1]);
H = max((int)H, h - horizontalCuts[lh - 1]);
for (int i = 1; i < lw; i++)
W = max((int)W, verticalCuts[i] - verticalCuts[i - 1]);
W = max((int)W, w - verticalCuts[lw - 1]);
const int mod = 1e9 + 7;
long long ans = (H * W) % mod;
return ans;
}
}; | 41.684211 | 87 | 0.542929 | [
"vector"
] |
059a0ec89096ef9fa0fe5a5860e6c37eced4c813 | 20,991 | cpp | C++ | src/vi/addressrange.cpp | antonvw/wex | c4c41c660c9967623093a1b407af034c59a56be8 | [
"MIT"
] | 3 | 2020-03-01T06:30:30.000Z | 2021-05-01T05:11:48.000Z | src/vi/addressrange.cpp | antonvw/wex | c4c41c660c9967623093a1b407af034c59a56be8 | [
"MIT"
] | 96 | 2020-01-18T18:25:48.000Z | 2022-03-26T12:26:50.000Z | src/vi/addressrange.cpp | antonvw/wex | c4c41c660c9967623093a1b407af034c59a56be8 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// Name: addressrange.cpp
// Purpose: Implementation of class wex::addressrange
// Author: Anton van Wezenbeek
// Copyright: (c) 2015-2021 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <boost/algorithm/string.hpp>
#include <boost/tokenizer.hpp>
#include <wex/addressrange.h>
#include <wex/core.h>
#include <wex/ex-stream.h>
#include <wex/ex.h>
#include <wex/factory/process.h>
#include <wex/factory/stc.h>
#include <wex/file.h>
#include <wex/frame.h>
#include <wex/frd.h>
#include <wex/log.h>
#include <wex/macros.h>
#include <wex/regex.h>
#include <wex/sort.h>
#include <wex/temp-filename.h>
#include <wex/util.h>
namespace wex
{
class global_env
{
public:
explicit global_env(const addressrange* ar)
: m_ex(ar->m_ex)
, m_ar(ar)
{
m_ex->get_stc()->set_search_flags(m_ex->search_flags());
m_ex->get_stc()->BeginUndoAction();
for (const auto& it : boost::tokenizer<boost::char_separator<char>>(
addressrange::data().commands(),
boost::char_separator<char>("|")))
{
// Prevent recursive global.
if (it[0] != 'g' && it[0] != 'v')
{
if (it[0] == 'd' || it[0] == 'm')
{
m_changes++;
}
m_commands.emplace_back(it);
}
}
}
~global_env()
{
m_ex->get_stc()->EndUndoAction();
m_ex->marker_delete('%');
}
auto changes() const { return m_changes; }
bool commands() const { return !m_commands.empty(); }
bool for_each(int line) const
{
if (!commands())
{
m_ex->get_stc()->set_indicator(
m_ar->m_find_indicator,
m_ex->get_stc()->GetTargetStart(),
m_ex->get_stc()->GetTargetEnd());
return true;
}
else
{
return std::all_of(
m_commands.begin(),
m_commands.end(),
[this, line](const std::string& it)
{
if (!m_ex->command(":" + std::to_string(line + 1) + it))
{
m_ex->frame()->show_ex_message(
m_ex->get_command().command() + " failed");
return false;
}
return true;
});
}
}
bool for_each(int start, int& end, int& hits) const
{
if (start < end)
{
for (int i = start; i < end && i < m_ex->get_stc()->get_line_count() - 1;)
{
if (commands())
{
if (!for_each(i))
return false;
}
else
{
m_ex->get_stc()->set_indicator(
m_ar->m_find_indicator,
m_ex->get_stc()->PositionFromLine(i),
m_ex->get_stc()->GetLineEndPosition(i));
}
if (m_changes == 0)
{
i++;
}
else
{
end -= m_changes;
}
hits++;
}
}
else
{
end++;
}
return true;
}
private:
const addressrange* m_ar;
std::vector<std::string> m_commands;
int m_changes{0};
ex* m_ex;
};
void convert_case(factory::stc* stc, std::string& target, char c)
{
c == 'U' ? boost::algorithm::to_upper(target) :
boost::algorithm::to_lower(target);
stc->Replace(stc->GetTargetStart(), stc->GetTargetEnd(), target);
}
}; // namespace wex
wex::addressrange::addressrange(wex::ex* ex, int lines)
: m_begin(ex)
, m_end(ex)
, m_ex(ex)
, m_stc(ex->get_stc())
{
if (lines > 0)
{
set(m_begin, m_end, lines);
}
else if (lines < 0)
{
set(m_end, m_begin, lines);
}
}
wex::addressrange::addressrange(wex::ex* ex, const std::string& range)
: m_begin(ex)
, m_end(ex)
, m_ex(ex)
, m_stc(ex->get_stc())
{
if (range == "%")
{
set("1", "$");
}
else if (range == "*")
{
set(
m_stc->GetFirstVisibleLine() + 1,
m_stc->GetFirstVisibleLine() + m_stc->LinesOnScreen() + 1);
}
else if (range.find(",") != std::string::npos)
{
set(range.substr(0, range.find(",")), range.substr(range.find(",") + 1));
}
else
{
set(range, range);
}
}
const std::string
wex::addressrange::build_replacement(const std::string& text) const
{
if (
text.find("&") == std::string::npos && text.find("\0") == std::string::npos)
{
return text;
}
std::string target(
m_stc->GetTextRange(m_stc->GetTargetStart(), m_stc->GetTargetEnd())),
replacement;
bool backslash = false;
for (const auto& c : text)
{
switch (c)
{
case '&':
if (!backslash)
replacement += target;
else
replacement += c;
backslash = false;
break;
case '0':
if (backslash)
replacement += target;
else
replacement += c;
backslash = false;
break;
case 'L':
case 'U':
if (backslash)
{
convert_case(m_stc, target, c);
}
else
replacement += c;
backslash = false;
break;
case '\\':
if (backslash)
replacement += c;
backslash = !backslash;
break;
default:
replacement += c;
backslash = false;
}
}
return replacement;
}
bool wex::addressrange::change(const std::string& text) const
{
if (!erase())
{
return false;
}
m_stc->add_text(text);
return true;
}
int wex::addressrange::confirm(
const std::string& pattern,
const std::string& replacement) const
{
wxMessageDialog msgDialog(
m_stc,
_("Replace") + " " + pattern + " " + _("with") + " " + replacement,
_("Replace"),
wxCANCEL | wxYES_NO);
const auto line = m_stc->LineFromPosition(m_stc->GetTargetStart());
msgDialog.SetExtendedMessage(
"Line " + std::to_string(line + 1) + ": " + m_stc->GetLineText(line));
m_stc->goto_line(line);
m_stc->set_indicator(
m_find_indicator,
m_stc->GetTargetStart(),
m_stc->GetTargetEnd());
return msgDialog.ShowModal();
}
bool wex::addressrange::copy(const wex::address& destination) const
{
return general(
destination,
[=, this]()
{
return yank();
});
}
bool wex::addressrange::erase() const
{
if (!m_stc->is_visual())
{
return m_ex->ex_stream()->erase(*this);
}
if (m_stc->GetReadOnly() || m_stc->is_hexmode() || !set_selection())
{
return false;
}
m_ex->cut();
m_begin.marker_delete();
m_end.marker_delete();
return true;
}
bool wex::addressrange::escape(const std::string& command)
{
if (m_begin.m_address.empty() && m_end.m_address.empty())
{
if (auto expanded(command);
!marker_and_register_expansion(m_ex, expanded) ||
!shell_expansion(expanded))
{
return false;
}
else
{
return m_ex->frame()->process_async_system(
expanded,
m_stc->path().parent_path());
}
}
if (!is_ok())
{
return false;
}
if (temp_filename tmp(true);
m_stc->GetReadOnly() || m_stc->is_hexmode() || !write(tmp.name()))
{
return false;
}
else if (factory::process process;
process.system(command + " " + tmp.name()) == 0)
{
if (!process.get_stdout().empty())
{
m_stc->BeginUndoAction();
if (erase())
{
m_stc->add_text(process.get_stdout());
}
m_stc->EndUndoAction();
return true;
}
else if (!process.get_stderr().empty())
{
m_ex->frame()->show_ex_message(process.get_stderr());
log("escape") << process.get_stderr();
}
}
return false;
}
bool wex::addressrange::execute(const std::string& reg) const
{
if (!is_ok() || !ex::get_macros().is_recorded_macro(reg))
{
return false;
}
bool error = false;
m_stc->BeginUndoAction();
for (auto i = m_begin.get_line() - 1; i < m_end.get_line() && !error; i++)
{
if (!m_ex->command("@" + reg))
{
error = true;
}
}
m_stc->EndUndoAction();
return !error;
}
bool wex::addressrange::general(
const address& destination,
std::function<bool()> f) const
{
const auto dest_line = destination.get_line();
if (
m_stc->GetReadOnly() || m_stc->is_hexmode() || !is_ok() || dest_line == 0 ||
(dest_line >= m_begin.get_line() && dest_line <= m_end.get_line()))
{
return false;
}
m_stc->BeginUndoAction();
if (f())
{
m_stc->goto_line(dest_line - 1);
m_stc->add_text(m_ex->register_text());
}
m_stc->EndUndoAction();
return true;
}
bool wex::addressrange::global(const std::string& text, bool inverse) const
{
if (!m_substitute.set_global(text))
{
return false;
}
if (m_substitute.pattern().empty())
{
return true;
}
const std::string& commands(m_substitute.commands());
m_stc->IndicatorClearRange(0, m_stc->GetTextLength() - 1);
const global_env g(this);
m_ex->marker_add('%', m_end.get_line() - 1);
m_stc->SetTargetRange(
m_stc->PositionFromLine(m_begin.get_line() - 1),
m_stc->GetLineEndPosition(m_ex->marker_line('%')));
const bool infinite =
(g.changes() > 0 && commands != "$" && commands != "1" && commands != "d");
int hits = 0;
int start = 0;
while (m_stc->SearchInTarget(m_substitute.pattern()) != -1)
{
auto match = m_stc->LineFromPosition(m_stc->GetTargetStart());
if (!inverse)
{
if (!g.for_each(match))
return false;
hits++;
}
else
{
if (!g.for_each(start, match, hits))
return false;
start = match + 1;
}
if (hits > 50 && infinite)
{
m_ex->frame()->show_ex_message(
"possible infinite loop at " + std::to_string(match));
return false;
}
m_stc->SetTargetRange(
g.changes() > 0 ? m_stc->PositionFromLine(match) : m_stc->GetTargetEnd(),
m_stc->GetLineEndPosition(m_ex->marker_line('%')));
if (m_stc->GetTargetStart() >= m_stc->GetTargetEnd())
{
break;
}
}
if (inverse)
{
if (auto match = m_stc->get_line_count(); !g.for_each(start, match, hits))
{
return false;
}
}
if (hits > 0)
{
if (g.commands())
m_ex->frame()->show_ex_message(
"executed: " + std::to_string(hits) + " commands");
else
m_ex->frame()->show_ex_message(
"found: " + std::to_string(hits) + " matches");
}
return true;
}
bool wex::addressrange::indent(bool forward) const
{
if (
m_stc->GetReadOnly() || m_stc->is_hexmode() || !is_ok() || !set_selection())
{
return false;
}
m_stc->BeginUndoAction();
m_stc->SendMsg(forward ? wxSTC_CMD_TAB : wxSTC_CMD_BACKTAB);
m_stc->EndUndoAction();
return true;
}
bool wex::addressrange::is_ok() const
{
return m_begin.get_line() > 0 && m_end.get_line() > 0 &&
m_begin.get_line() <= m_end.get_line();
}
bool wex::addressrange::join() const
{
if (!m_stc->is_visual())
{
return m_ex->ex_stream()->join(*this);
}
if (m_stc->GetReadOnly() || m_stc->is_hexmode() || !is_ok())
{
return false;
}
m_stc->BeginUndoAction();
m_stc->SetTargetRange(
m_stc->PositionFromLine(m_begin.get_line() - 1),
m_stc->PositionFromLine(m_end.get_line() - 1));
m_stc->LinesJoin();
m_stc->EndUndoAction();
return true;
}
bool wex::addressrange::move(const address& destination) const
{
return general(
destination,
[=, this]()
{
return erase();
});
}
bool wex::addressrange::parse(
const std::string& command,
const std::string& text,
info_message_t& im)
{
im = info_message_t::NONE;
switch (command[0])
{
case 0:
return false;
case 'c':
if (text.find('|') != std::string::npos)
{
return change(after(text, '|'));
}
else
{
return m_ex->frame()->show_ex_input(m_ex->get_stc(), command[0]);
}
case 'd':
im = info_message_t::DEL;
return erase();
case 'v':
case 'g':
return global(text, command[0] == 'v');
case 'j':
return join();
case 'm':
im = info_message_t::MOVE;
return move(address(m_ex, text));
case 'l':
case 'p':
return (m_stc->GetName() != "Print" ? print(text) : false);
case 's':
case '&':
case '~':
return substitute(text, command[0]);
case 'S':
return sort(text);
case 't':
im = info_message_t::COPY;
return copy(address(m_ex, text));
case 'w':
if (!text.empty())
{
return write(text);
}
else
{
wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, wxID_SAVE);
wxPostEvent(wxTheApp->GetTopWindow(), event);
return true;
}
case 'y':
im = info_message_t::YANK;
return yank(text.empty() ? '0' : static_cast<char>(text[0]));
case '>':
return shift_right();
case '<':
return shift_left();
case '!':
return escape(text);
case '@':
return execute(text);
case '#':
return (m_stc->GetName() != "Print" ? print("#" + text) : false);
default:
log::status("Unknown range command") << command;
return false;
}
}
bool wex::addressrange::print(const std::string& flags) const
{
if (!is_ok() || !m_begin.flags_supported(flags))
{
return false;
}
std::string text;
for (auto i = m_begin.get_line() - 1; i < m_end.get_line(); i++)
{
char buffer[8];
snprintf(buffer, sizeof(buffer), "%6d ", i + 1);
text += (flags.find("#") != std::string::npos ? buffer : std::string()) +
m_stc->GetLine(i);
}
m_ex->print(text);
return true;
}
const std::string wex::addressrange::regex_commands() const
{
// 2addr commands
return std::string("(change\\b|"
"copy\\b|co\\b|"
"delete\\b|"
"global\\b|"
"join\\b|"
"list\\b|"
"move\\b|"
"number\\b|nu\\b|"
"print\\b|"
"substitute\\b|"
"write\\b|"
"yank\\b|ya\\b|"
"[cdgjlmpsStvwy<>\\!&~@#])([\\s\\S]*)");
}
void wex::addressrange::set(int begin, int end)
{
m_begin.set_line(begin);
m_end.set_line(end);
}
void wex::addressrange::set(const std::string& begin, const std::string& end)
{
m_begin.m_address = begin;
if (const auto begin_line = m_begin.get_line(); begin_line > 0)
{
m_begin.set_line(begin_line);
}
m_end.m_address = end;
if (const auto end_line = m_end.get_line(); end_line > 0)
{
m_end.set_line(end_line);
}
}
void wex::addressrange::set(address& begin, address& end, int lines) const
{
begin.set_line(m_stc->LineFromPosition(m_stc->GetCurrentPos()) + 1);
end.set_line(begin.get_line() + lines - 1);
}
bool wex::addressrange::set_selection() const
{
if (!m_stc->GetSelectedText().empty())
{
return true;
}
else if (!is_ok())
{
return false;
}
m_stc->SetSelection(
m_stc->PositionFromLine(m_begin.get_line() - 1),
m_stc->PositionFromLine(m_end.get_line()));
return true;
}
bool wex::addressrange::sort(const std::string& parameters) const
{
if (m_stc->GetReadOnly() || m_stc->is_hexmode() || !set_selection())
{
return false;
}
sort::sort_t sort_t = 0;
size_t pos = 0, len = std::string::npos;
if (m_stc->SelectionIsRectangle())
{
pos = m_stc->GetColumn(m_stc->GetSelectionStart());
len = m_stc->GetColumn(m_stc->GetSelectionEnd() - pos);
}
if (!parameters.empty())
{
/// -u to sort unique lines
/// -r to sort reversed (descending)
if (
(parameters[0] == '0') ||
(!parameters.starts_with("u") && !parameters.starts_with("r") &&
!isdigit(parameters[0])))
{
return false;
}
if (parameters.find("r") != std::string::npos)
sort_t.set(sort::SORT_DESCENDING);
if (parameters.find("u") != std::string::npos)
sort_t.set(sort::SORT_UNIQUE);
if (isdigit(parameters[0]))
{
try
{
pos = (std::stoi(parameters) > 0 ? std::stoi(parameters) - 1 : 0);
if (parameters.find(",") != std::string::npos)
{
len =
std::stoi(parameters.substr(parameters.find(',') + 1)) - pos + 1;
}
}
catch (...)
{
}
}
}
return wex::sort(sort_t, pos, len).selection(m_stc);
}
bool wex::addressrange::substitute(const std::string& text, char cmd)
{
if ((m_stc->is_visual() && m_stc->GetReadOnly()) || !is_ok())
{
return false;
}
data::substitute data(m_substitute);
switch (cmd)
{
case 's':
if (!data.set(text))
{
return false;
}
break;
case '&':
case '~':
data.set_options(text);
break;
default:
log::debug("substitute unhandled command") << cmd;
return false;
}
if (data.pattern().empty())
{
log::status("Pattern is empty");
log::debug("substitute") << cmd << "empty pattern" << text;
return false;
}
auto searchFlags = m_ex->search_flags();
if (data.is_ignore_case())
searchFlags &= ~wxSTC_FIND_MATCHCASE;
if (
(searchFlags & wxSTC_FIND_REGEXP) && data.pattern().size() == 2 &&
data.pattern().back() == '*' && data.replacement().empty())
{
log::status("Replacement leads to infinite loop");
return false;
}
if (!m_stc->is_visual())
{
return m_ex->ex_stream()->substitute(*this, data);
}
if (!m_ex->marker_add('#', m_begin.get_line() - 1))
{
log::debug("substitute could not add marker");
return false;
}
int corrected = 0;
auto end_line = m_end.get_line() - 1;
if (!m_stc->GetSelectedText().empty())
{
if (
m_stc->GetLineSelEndPosition(end_line) ==
m_stc->PositionFromLine(end_line))
{
end_line--;
corrected = 1;
}
}
if (!m_ex->marker_add('$', end_line))
{
log::debug("substitute could not add marker");
return false;
}
m_substitute = data;
m_stc->set_search_flags(searchFlags);
m_stc->BeginUndoAction();
m_stc->SetTargetRange(
m_stc->PositionFromLine(m_ex->marker_line('#')),
m_stc->GetLineEndPosition(m_ex->marker_line('$')));
int nr_replacements = 0;
int result = wxID_YES;
const bool build =
(data.replacement().find_first_of("&0LU\\") != std::string::npos);
auto replacement(data.replacement());
while (m_stc->SearchInTarget(data.pattern()) != -1 && result != wxID_CANCEL)
{
if (build)
{
replacement = build_replacement(data.replacement());
}
if (data.is_confirmed())
{
result = confirm(data.pattern(), replacement);
}
if (result == wxID_YES)
{
if (m_stc->is_hexmode())
{
m_stc->get_hexmode_replace_target(replacement, false);
}
else
{
(searchFlags & wxSTC_FIND_REGEXP) ?
m_stc->ReplaceTargetRE(replacement) :
m_stc->ReplaceTarget(replacement);
}
nr_replacements++;
}
m_stc->SetTargetRange(
data.is_global() ? m_stc->GetTargetEnd() :
m_stc->GetLineEndPosition(
m_stc->LineFromPosition(m_stc->GetTargetEnd())),
m_stc->GetLineEndPosition(m_ex->marker_line('$')));
if (m_stc->GetTargetStart() >= m_stc->GetTargetEnd())
{
break;
}
}
if (m_stc->is_hexmode())
{
m_stc->get_hexmode_sync();
}
m_stc->EndUndoAction();
if (m_begin.m_address == "'<" && m_end.m_address == "'>")
{
m_stc->SetSelection(
m_stc->PositionFromLine(m_ex->marker_line('#')),
m_stc->PositionFromLine(m_ex->marker_line('$') + corrected));
}
m_ex->marker_delete('#');
m_ex->marker_delete('$');
m_ex->frame()->show_ex_message(
"Replaced: " + std::to_string(nr_replacements) +
" occurrences of: " + data.pattern());
m_stc->IndicatorClearRange(0, m_stc->GetTextLength() - 1);
return true;
}
bool wex::addressrange::write(const std::string& text) const
{
if (!set_selection())
{
return false;
}
auto filename(boost::algorithm::trim_left_copy(
text.find(">>") != std::string::npos ? wex::after(text, '>', false) :
text));
#ifdef __UNIX__
if (filename.find("~") != std::string::npos)
{
filename.replace(filename.find("~"), 1, wxGetHomeDir());
}
#endif
if (!m_stc->is_visual())
{
return m_ex->ex_stream()->write(
*this,
filename,
text.find(">>") != std::string::npos);
}
else
{
return wex::file(
path(filename),
text.find(">>") != std::string::npos ?
std::ios::out | std::ios_base::app :
std::ios::out)
.write(m_stc->get_selected_text());
}
}
bool wex::addressrange::yank(char name) const
{
if (!m_stc->is_visual())
{
return m_ex->ex_stream()->yank(*this, name);
}
else
{
return set_selection() && m_ex->yank(name);
}
}
| 20.97003 | 80 | 0.556762 | [
"vector"
] |
05a5d6b9e4401041084e3feb2b66dc1cf6c32577 | 5,731 | cxx | C++ | modules/ardrivo/src/String.cxx | platisd/group-09 | a905c8c6409c0a3d73f53884e167571d8f482667 | [
"Apache-2.0"
] | 4 | 2020-04-03T08:30:37.000Z | 2020-07-08T08:55:30.000Z | modules/ardrivo/src/String.cxx | platisd/group-09 | a905c8c6409c0a3d73f53884e167571d8f482667 | [
"Apache-2.0"
] | 76 | 2020-04-03T09:15:45.000Z | 2020-12-17T16:55:14.000Z | modules/ardrivo/src/String.cxx | platisd/group-09 | a905c8c6409c0a3d73f53884e167571d8f482667 | [
"Apache-2.0"
] | 1 | 2020-06-02T15:52:31.000Z | 2020-06-02T15:52:31.000Z | /*
* String.cxx
* Copyright 2020 ItJustWorksTM
*
* 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 <range/v3/algorithm/transform.hpp>
#include "WString.h"
[[nodiscard]] const char* String::c_str() const noexcept { return m_u.c_str(); }
[[nodiscard]] std::size_t String::length() const noexcept { return m_u.length(); }
[[nodiscard]] auto String::charAt(unsigned idx) const noexcept { return m_u.at(idx); }
[[nodiscard]] auto& String::charAt(unsigned idx) noexcept { return m_u.at(idx); }
[[nodiscard]] auto String::operator[](unsigned idx) const noexcept { return m_u[idx]; }
[[nodiscard]] auto& String::operator[](unsigned idx) noexcept { return m_u[idx]; }
[[nodiscard]] int String::compareTo(const String& s) const noexcept {
return std::memcmp(m_u.c_str(), s.m_u.c_str(), (std::min)(s.m_u.size(), m_u.size()));
}
[[nodiscard]] bool String::startsWith(const String& s) const noexcept {
if (s.m_u.size() > m_u.size())
return false;
return std::memcmp(m_u.c_str(), s.m_u.c_str(), s.m_u.size()) == 0;
}
[[nodiscard]] bool String::endsWith(const String& s) const noexcept {
if (s.m_u.size() > m_u.size())
return false;
return (m_u.compare(m_u.length() - s.m_u.length(), s.m_u.length(), s.m_u) == 0);
}
void String::getBytes(byte* buffer, unsigned length) const noexcept{
std::transform(m_u.begin(), (length > m_u.length()) ? m_u.end() : m_u.begin() + length, buffer, [](unsigned char c) -> byte { return c; });
}
[[nodiscard]] int String::indexOf(const char* c) const noexcept { return m_u.find(c); }
[[nodiscard]] int String::indexOf(const char* c, unsigned index) const noexcept { return m_u.find(c, index); }
[[nodiscard]] int String::indexOf(const String& str) const noexcept { return m_u.find(str.m_u); }
[[nodiscard]] int String::indexOf(const String& str, unsigned index) const noexcept { return m_u.find(str.m_u, index); }
void String::remove(unsigned idx) { m_u.erase(idx); }
void String::remove(unsigned idx, unsigned count) { m_u.erase(idx, idx + count - 1); }
void String::replace(const String& substring1, const String& substring2) {
size_t position = m_u.find(substring1.m_u);
while (position != std::string::npos) {
m_u.replace(position, m_u.size(), substring2.m_u);
position = m_u.find(substring1.m_u, position + substring2.m_u.size());
}
}
void String::reserve(unsigned size) { m_u.reserve(size); }
void String::setCharAt(unsigned index, char c) { m_u[index] = c; }
[[nodiscard]] String String::substring(unsigned from) const { return m_u.substr(from); }
[[nodiscard]] String String::substring(unsigned from, unsigned to) const { return m_u.substr(from, to - from); }
void String::toCharArray(char* buffer, unsigned length) noexcept {
std::memcpy(buffer, m_u.c_str(), (std::min)(static_cast<std::size_t>(length), m_u.length()));
}
[[nodiscard]] long String::toInt() const noexcept try { return std::stoi(m_u); } catch (const std::exception& e) {
return 0;
}
[[nodiscard]] double String::toDouble() const noexcept try { return std::stod(m_u); } catch (const std::exception& e) {
return 0;
}
[[nodiscard]] float String::toFloat() const noexcept try { return std::stof(m_u); } catch (const std::exception& e) {
return 0;
}
void String::toLowerCase() noexcept{ std::transform(m_u.begin(), m_u.end(), m_u.begin(),
[] (char c) { return static_cast<char>(std::tolower(+c)); });
}
void String::toUpperCase() noexcept{ std::transform(m_u.begin(), m_u.end(), m_u.begin(),
[](char c) { return static_cast<char>(std::toupper(+c)); });
}
void String::trim() {
if (const auto spos = m_u.find_first_not_of(' '); spos != std::string::npos && spos != 0)
m_u.erase(m_u.begin(), m_u.begin() + spos);
if (const auto lpos = m_u.find_last_not_of(' '); lpos != std::string::npos)
m_u.erase(m_u.begin() + lpos + 1, m_u.end());
}
[[nodiscard]] bool String::equals(const String& s) const noexcept { return m_u == s.m_u; }
[[nodiscard]] bool String::equalsIgnoreCase(const String& s) const noexcept {
std::string str_a = m_u;
std::string str_b = s.m_u;
ranges::transform(str_a, str_a.begin(), [] (char c) { return static_cast<char>(std::tolower(+c)); });
ranges::transform(str_b, str_b.begin(), [] (char c) { return static_cast<char>(std::tolower(+c)); });
return str_a == str_b;
}
[[nodiscard]] bool String::operator==(const String& s) const noexcept { return m_u == s.m_u; }
[[nodiscard]] bool String::operator!=(const String& s) const noexcept { return m_u != s.m_u; }
[[nodiscard]] bool String::operator<(const String& s) const noexcept { return m_u < s.m_u; }
[[nodiscard]] bool String::operator<=(const String& s) const noexcept { return m_u <= s.m_u; }
[[nodiscard]] bool String::operator>(const String& s) const noexcept { return m_u > s.m_u; }
[[nodiscard]] bool String::operator>=(const String& s) const noexcept { return m_u >= s.m_u; }
[[nodiscard]] String operator+(const String& lhs, const String& rhs) { return {lhs.m_u + rhs.m_u}; }
[[nodiscard]] String operator+(const String& lhs, const char* rhs) { return {lhs.m_u + rhs}; }
[[nodiscard]] String operator+(const char* lhs, const String& rhs) { return {lhs + rhs.m_u}; } | 45.125984 | 143 | 0.673006 | [
"transform"
] |
05a9c9ae53156d2b98637097b7e4a1d6d9407c5a | 2,620 | cpp | C++ | android-31/android/view/textservice/SpellCheckerInfo.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/view/textservice/SpellCheckerInfo.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/android/view/textservice/SpellCheckerInfo.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../content/ComponentName.hpp"
#include "../../content/pm/PackageManager.hpp"
#include "../../content/pm/ServiceInfo.hpp"
#include "../../graphics/drawable/Drawable.hpp"
#include "../../os/Parcel.hpp"
#include "./SpellCheckerSubtype.hpp"
#include "../../../JString.hpp"
#include "../../../JString.hpp"
#include "./SpellCheckerInfo.hpp"
namespace android::view::textservice
{
// Fields
JObject SpellCheckerInfo::CREATOR()
{
return getStaticObjectField(
"android.view.textservice.SpellCheckerInfo",
"CREATOR",
"Landroid/os/Parcelable$Creator;"
);
}
// QJniObject forward
SpellCheckerInfo::SpellCheckerInfo(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
jint SpellCheckerInfo::describeContents() const
{
return callMethod<jint>(
"describeContents",
"()I"
);
}
android::content::ComponentName SpellCheckerInfo::getComponent() const
{
return callObjectMethod(
"getComponent",
"()Landroid/content/ComponentName;"
);
}
JString SpellCheckerInfo::getId() const
{
return callObjectMethod(
"getId",
"()Ljava/lang/String;"
);
}
JString SpellCheckerInfo::getPackageName() const
{
return callObjectMethod(
"getPackageName",
"()Ljava/lang/String;"
);
}
android::content::pm::ServiceInfo SpellCheckerInfo::getServiceInfo() const
{
return callObjectMethod(
"getServiceInfo",
"()Landroid/content/pm/ServiceInfo;"
);
}
JString SpellCheckerInfo::getSettingsActivity() const
{
return callObjectMethod(
"getSettingsActivity",
"()Ljava/lang/String;"
);
}
android::view::textservice::SpellCheckerSubtype SpellCheckerInfo::getSubtypeAt(jint arg0) const
{
return callObjectMethod(
"getSubtypeAt",
"(I)Landroid/view/textservice/SpellCheckerSubtype;",
arg0
);
}
jint SpellCheckerInfo::getSubtypeCount() const
{
return callMethod<jint>(
"getSubtypeCount",
"()I"
);
}
android::graphics::drawable::Drawable SpellCheckerInfo::loadIcon(android::content::pm::PackageManager arg0) const
{
return callObjectMethod(
"loadIcon",
"(Landroid/content/pm/PackageManager;)Landroid/graphics/drawable/Drawable;",
arg0.object()
);
}
JString SpellCheckerInfo::loadLabel(android::content::pm::PackageManager arg0) const
{
return callObjectMethod(
"loadLabel",
"(Landroid/content/pm/PackageManager;)Ljava/lang/CharSequence;",
arg0.object()
);
}
void SpellCheckerInfo::writeToParcel(android::os::Parcel arg0, jint arg1) const
{
callMethod<void>(
"writeToParcel",
"(Landroid/os/Parcel;I)V",
arg0.object(),
arg1
);
}
} // namespace android::view::textservice
| 23.185841 | 114 | 0.703053 | [
"object"
] |
05ae4cf736c28f1966ad472a0e8b3a865ab62bcc | 23,272 | cpp | C++ | wms/State.cpp | fmidev/smartmet-plugin-wms | 908027c3dbe604c2e220718fd4926aa03673a8d6 | [
"MIT"
] | null | null | null | wms/State.cpp | fmidev/smartmet-plugin-wms | 908027c3dbe604c2e220718fd4926aa03673a8d6 | [
"MIT"
] | 6 | 2017-01-05T07:19:43.000Z | 2019-10-23T06:21:48.000Z | wms/State.cpp | fmidev/smartmet-plugin-wms | 908027c3dbe604c2e220718fd4926aa03673a8d6 | [
"MIT"
] | 1 | 2016-12-30T11:10:58.000Z | 2016-12-30T11:10:58.000Z | // ======================================================================
#include "State.h"
#include "Plugin.h"
#include <ctpp2/CDT.hpp>
#include <macgyver/Exception.h>
#include <macgyver/Hash.h>
#include <macgyver/StringConversion.h>
#include <stdexcept>
namespace SmartMet
{
namespace Plugin
{
namespace Dali
{
// ----------------------------------------------------------------------
/*!
* \brief Set the state of the plugin
*
* The alternative would be to have queries which would always have
* as input both the State object and the plugin object, which means
* we would have to either make QEngine a public member of the plugin,
* provide an accessor for it, or provide an accessor for a model.
* Initializing the state with the QEngine clarifies usage - you
* use only one variable with a state, and you cannot bypass it.
* We MUST use the same Q object throughout the generation of
* the product, even if the latest Q for the chosen model is updated
* during the generation of the product.
*/
// ----------------------------------------------------------------------
State::State(Plugin& thePlugin, const Spine::HTTP::Request& theRequest)
: itsPlugin(thePlugin),
itsInDefs(false),
itUsesTimer(false),
itUsesWms(false),
itsRequest(theRequest),
itsLocalTimePool(boost::make_shared<SmartMet::Spine::TimeSeries::LocalTimePool>())
{
}
// ----------------------------------------------------------------------
/*!
* \brief Get the contour engine
*/
// ----------------------------------------------------------------------
const Engine::Contour::Engine& State::getContourEngine() const
{
try
{
return itsPlugin.getContourEngine();
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Get the grid engine
*/
// ----------------------------------------------------------------------
const Engine::Grid::Engine* State::getGridEngine() const
{
try
{
return itsPlugin.getGridEngine();
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Get the querydata engine
*/
// ----------------------------------------------------------------------
const Engine::Querydata::Engine& State::getQEngine() const
{
try
{
return itsPlugin.getQEngine();
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Get the GIS engine
*/
// ----------------------------------------------------------------------
const Engine::Gis::Engine& State::getGisEngine() const
{
try
{
return itsPlugin.getGisEngine();
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Get the GEO engine
*/
// ----------------------------------------------------------------------
const Engine::Geonames::Engine& State::getGeoEngine() const
{
try
{
return itsPlugin.getGeoEngine();
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Get the OBS engine
*/
// ----------------------------------------------------------------------
#ifndef WITHOUT_OBSERVATION
Engine::Observation::Engine& State::getObsEngine() const
{
try
{
return itsPlugin.getObsEngine();
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
#endif
// ----------------------------------------------------------------------
/*!
* \brief Get the configuration object
*/
// ----------------------------------------------------------------------
const Config& State::getConfig() const
{
try
{
return itsPlugin.getConfig();
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Get cached Q
*
* We want to use the same Q in all layers even though a newer one
* might become available while the product is being generated.
* Hence we cache all Q requests to the QEngine to make sure
* we use the same data all the time.
*
* If a specific origin time is requested, there is no need to
* use a cache, but expiration time estimation would have to
* be updated.
*/
// ----------------------------------------------------------------------
Engine::Querydata::Q State::get(const Engine::Querydata::Producer& theProducer) const
{
try
{
// Use cached Q if there is one
auto res = itsQCache.find(theProducer);
if (res != itsQCache.end())
return res->second;
// Get the data from the engine
auto q = itsPlugin.getQEngine().get(theProducer);
// Update estimated expiration time for the product
updateExpirationTime(q->expirationTime());
// Cache the obtained data and return it. The cache is
// request specific, no need for mutexes here.
itsQCache.insert(std::make_pair(theProducer, q));
return q;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Get Q with origintime
*/
// ----------------------------------------------------------------------
Engine::Querydata::Q State::get(const Engine::Querydata::Producer& theProducer,
const boost::posix_time::ptime& theOriginTime) const
{
try
{
return itsPlugin.getQEngine().get(theProducer, theOriginTime);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Require the given ID to be free
*/
// ----------------------------------------------------------------------
void State::requireId(const std::string& theID) const
{
try
{
if (!addId(theID))
throw Fmi::Exception(BCP, ("ID '" + theID + "' is defined more than once"));
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Add ID to registry of used names
*/
// ----------------------------------------------------------------------
bool State::addId(const std::string& theID) const
{
try
{
if (itsUsedIds.find(theID) != itsUsedIds.end())
return false;
itsUsedIds.insert(theID);
return true;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Add attributes to the generated CDT at the global level
*/
// ----------------------------------------------------------------------
void State::addAttributes(CTPP::CDT& theGlobals, const Attributes& theAttributes) const
{
try
{
addAttributes(theGlobals, theGlobals, theAttributes);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Add attributes to the generated CDT
*
* Adding attributes involves:
*
* - Adding attribute names and values to the local CDT
* - Including necessary definitions from url(#id) references to globals
*
* Section "17.1.4 Processing of IRI references" list multiple tags
* which can reference external data. The ones which may cause
* an include into the defs section are:
*
* filters : filter
* markers : marker, marker-start, marker-mid, marker-end
* patterns : pattern
* gradients : linearGradient, radialGradient
*
* The include is done if the value of the attribute is of the form
* "url(#elementID) *AND* elementID has not been defined so far.
* This allows the user to define a component in the defs section
* instead of including if from an external file.
*
* The reference may in SVG be also be an xpointer, but we do not
* support that form in generating SVG from JSON configs.
*/
// ----------------------------------------------------------------------
void State::addAttributes(CTPP::CDT& theGlobals,
CTPP::CDT& theLocals,
const Attributes& theAttributes) const
{
try
{
// The locals are easily handled by inserting them to the CDT
theAttributes.generate(theLocals, *this);
// See also Attributes::hash_value!
// Now process the globals
auto iri = theAttributes.getLocalIri("filter");
if (iri && addId(*iri))
theGlobals["includes"][*iri] = itsPlugin.getFilter(itsCustomer, *iri, itUsesWms);
iri = theAttributes.getLocalIri("marker");
if (iri && addId(*iri))
theGlobals["includes"][*iri] = itsPlugin.getMarker(itsCustomer, *iri, itUsesWms);
iri = theAttributes.getLocalIri("marker-start");
if (iri && addId(*iri))
theGlobals["includes"][*iri] = itsPlugin.getMarker(itsCustomer, *iri, itUsesWms);
iri = theAttributes.getLocalIri("marker-mid");
if (iri && addId(*iri))
theGlobals["includes"][*iri] = itsPlugin.getMarker(itsCustomer, *iri, itUsesWms);
iri = theAttributes.getLocalIri("marker-end");
if (iri && addId(*iri))
theGlobals["includes"][*iri] = itsPlugin.getMarker(itsCustomer, *iri, itUsesWms);
iri = theAttributes.getLocalIri("fill");
if (iri && addId(*iri))
theGlobals["includes"][*iri] = itsPlugin.getPattern(itsCustomer, *iri, itUsesWms);
iri = theAttributes.getLocalIri("linearGradient");
if (iri && addId(*iri))
theGlobals["includes"][*iri] = itsPlugin.getGradient(itsCustomer, *iri, itUsesWms);
iri = theAttributes.getLocalIri("radialGradient");
if (iri && addId(*iri))
theGlobals["includes"][*iri] = itsPlugin.getGradient(itsCustomer, *iri, itUsesWms);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Add presentation attributes to the CDT
*/
// ----------------------------------------------------------------------
void State::addPresentationAttributes(CTPP::CDT& theLayer,
const boost::optional<std::string>& theCSS,
const Attributes& theAttributes) const
{
try
{
if (theCSS)
theAttributes.generatePresentation(theLayer, *this, getStyle(*theCSS));
else
theAttributes.generatePresentation(theLayer, *this);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/*!
* \brief Add presentation attributes to the CDT
*/
// ----------------------------------------------------------------------
void State::addPresentationAttributes(CTPP::CDT& theLayer,
const boost::optional<std::string>& theCSS,
const Attributes& theLayerAttributes,
const Attributes& theObjectAttributes) const
{
try
{
// Note: Object attributes override layer attributes
if (theCSS)
{
const auto css = getStyle(*theCSS);
theLayerAttributes.generatePresentation(theLayer, *this, css);
theObjectAttributes.generatePresentation(theLayer, *this, css);
}
else
{
theLayerAttributes.generatePresentation(theLayer, *this);
theObjectAttributes.generatePresentation(theLayer, *this);
}
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Fetch CSS from the cache
*/
// ----------------------------------------------------------------------
std::string State::getStyle(const std::string& theCSS) const
{
try
{
return itsPlugin.getStyle(itsCustomer, theCSS, itUsesWms);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Store symbol SVG to state object, overriding any lower layer data
*/
// ----------------------------------------------------------------------
bool State::setSymbol(const std::string& theName, const std::string& theValue) const
{
try
{
if (itsSymbols.count(theName) > 0)
{
itsSymbols[theName] = theValue;
return false; // Overriding symbols already in there
}
itsSymbols[theName] = theValue;
return true;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Store filter SVG to state object, overriding any lower layer data
*/
// ----------------------------------------------------------------------
bool State::setFilter(const std::string& theName, const std::string& theValue) const
{
try
{
if (itsFilters.count(theName) > 0)
{
itsFilters[theName] = theValue;
return false; // Overriding filters already in there
}
itsFilters[theName] = theValue;
return true;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Store marker SVG to state object, overriding any lower layer data
*/
// ----------------------------------------------------------------------
bool State::setMarker(const std::string& theName, const std::string& theValue) const
{
try
{
if (itsMarkers.count(theName) > 0)
{
itsMarkers[theName] = theValue;
return false; // Overriding markers already in there
}
itsMarkers[theName] = theValue;
return true;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Store pattern SVG to state object, overriding any lower layer data
*/
// ----------------------------------------------------------------------
bool State::setPattern(const std::string& theName, const std::string& theValue) const
{
try
{
if (itsPatterns.count(theName) > 0)
{
itsPatterns[theName] = theValue;
return false; // Overriding patterns already in there
}
itsPatterns[theName] = theValue;
return true;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Store gradient SVG to state object, overriding any lower layer data
*/
// ----------------------------------------------------------------------
bool State::setGradient(const std::string& theName, const std::string& theValue) const
{
try
{
if (itsGradients.count(theName) > 0)
{
itsGradients[theName] = theValue;
return false; // Overriding gradients already in there
}
itsGradients[theName] = theValue;
return true;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Fetch symbol SVG from the cache
*/
// ----------------------------------------------------------------------
std::string State::getSymbol(const std::string& theName) const
{
try
{
if (itsSymbols.count(theName) > 0)
return itsSymbols[theName];
return itsPlugin.getSymbol(itsCustomer, theName, itUsesWms);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Fetch symbol hash value
*/
// ----------------------------------------------------------------------
std::size_t State::getSymbolHash(const std::string& theName) const
{
try
{
if (itsSymbols.count(theName) > 0)
return Fmi::hash_value(itsSymbols[theName]);
return itsPlugin.getSymbolHash(itsCustomer, theName, itUsesWms);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Fetch filter SVG from the cache
*/
// ----------------------------------------------------------------------
std::string State::getFilter(const std::string& theName) const
{
try
{
if (itsFilters.count(theName) > 0)
return itsFilters[theName];
return itsPlugin.getFilter(itsCustomer, theName, itUsesWms);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Fetch filter hash value
*/
// ----------------------------------------------------------------------
std::size_t State::getFilterHash(const std::string& theName) const
{
try
{
if (itsFilters.count(theName) > 0)
return Fmi::hash_value(itsFilters[theName]);
return itsPlugin.getFilterHash(itsCustomer, theName, itUsesWms);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Fetch pattern SVG from the cache
*/
// ----------------------------------------------------------------------
std::string State::getPattern(const std::string& theName) const
{
try
{
if (itsPatterns.count(theName) > 0)
return itsPatterns[theName];
return itsPlugin.getPattern(itsCustomer, theName, itUsesWms);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Fetch pattern hash from the cache
*/
// ----------------------------------------------------------------------
std::size_t State::getPatternHash(const std::string& theName) const
{
try
{
if (itsPatterns.count(theName) > 0)
return Fmi::hash_value(itsPatterns[theName]);
return itsPlugin.getPatternHash(itsCustomer, theName, itUsesWms);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Fetch marker SVG from the cache
*/
// ----------------------------------------------------------------------
std::string State::getMarker(const std::string& theName) const
{
try
{
if (itsMarkers.count(theName) > 0)
return itsMarkers[theName];
return itsPlugin.getMarker(itsCustomer, theName, itUsesWms);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Fetch marker hash
*/
// ----------------------------------------------------------------------
std::size_t State::getMarkerHash(const std::string& theName) const
{
try
{
if (itsMarkers.count(theName) > 0)
return Fmi::hash_value(itsMarkers[theName]);
return itsPlugin.getMarkerHash(itsCustomer, theName, itUsesWms);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Fetch gradient SVG from the cache
*/
// ----------------------------------------------------------------------
std::string State::getGradient(const std::string& theName) const
{
try
{
if (itsGradients.count(theName) > 0)
return itsGradients[theName];
return itsPlugin.getGradient(itsCustomer, theName, itUsesWms);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Fetch gradient hash value
*/
// ----------------------------------------------------------------------
std::size_t State::getGradientHash(const std::string& theName) const
{
try
{
if (itsGradients.count(theName) > 0)
return Fmi::hash_value(itsGradients[theName]);
return itsPlugin.getGradientHash(itsCustomer, theName, itUsesWms);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Generate a new unique ID valid for SVG
*/
//----------------------------------------------------------------------
std::string State::generateUniqueId() const
{
std::string ret = "generated_id_";
ret += Fmi::to_string(itsNextId++);
return ret;
}
// ----------------------------------------------------------------------
/*!
* \brief Get the estimated expiration time
*/
// ----------------------------------------------------------------------
const boost::optional<boost::posix_time::ptime>& State::getExpirationTime() const
{
return itsExpirationTime;
}
// ----------------------------------------------------------------------
/*!
* \brief Update the estimated expiration time if necessary
*
* The final expiration time is the one estimated to be first in the
* future out of all the data used in the layers of the product.
*/
// ----------------------------------------------------------------------
void State::updateExpirationTime(const boost::posix_time::ptime& theTime) const
{
if (!itsExpirationTime)
itsExpirationTime = theTime;
else
itsExpirationTime = std::min(*itsExpirationTime, theTime);
}
// ----------------------------------------------------------------------
/*!
* \brief Return a generated QID for the given prefix
*
* We simply count the number of times each prefix has been used and
* appends the counter to the prefix.
*/
// ----------------------------------------------------------------------
std::string State::makeQid(const std::string& thePrefix) const
{
auto num = ++itsQids[thePrefix];
return thePrefix + Fmi::to_string(num);
}
// ----------------------------------------------------------------------
/*!
* \brief Return true if the producer is for observations
*/
// ----------------------------------------------------------------------
bool State::isObservation(const boost::optional<std::string>& theProducer) const
{
std::string model = (theProducer ? *theProducer : getConfig().defaultModel());
return isObservation(model);
}
// ----------------------------------------------------------------------
/*!
* \brief Return true if the producer is for observations
*/
// ----------------------------------------------------------------------
bool State::isObservation(const std::string& theProducer) const
{
#ifdef WITHOUT_OBSERVATION
return false;
#else
if (getConfig().obsEngineDisabled())
return false;
auto observers = getObsEngine().getValidStationTypes();
return (observers.find(theProducer) != observers.end());
#endif
}
} // namespace Dali
} // namespace Plugin
} // namespace SmartMet
| 27.411072 | 89 | 0.493383 | [
"object",
"model"
] |
05af15d90e1ed2e961d72eb5aecc07579bc5d276 | 6,747 | cpp | C++ | tc 160+/AlphabetPaths.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/AlphabetPaths.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/AlphabetPaths.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
const int MASK_ALL = (1<<21)-1;
int bc[1<<21];
int ind[256];
int A[21][21];
int m, n;
const int di[] = { -1, 0, 1, 0 };
const int dj[] = { 0, 1, 0, -1 };
int cnt[1<<21];
int active[1<<21];
int counter;
void gen(int i, int j, int mask) {
if (bc[mask] == 11) {
if (cnt[mask] == 0) {
active[counter++] = mask;
}
++cnt[mask];
return;
}
for (int d=0; d<4; ++d) {
const int r = i + di[d];
const int c = j + dj[d];
if (r<0 || c<0 || r>=m || c>=n || A[r][c]==-1 || (mask & (1<<A[r][c]))) {
continue;
}
gen(r, c, mask | (1<<(A[r][c])));
}
}
class AlphabetPaths {
public:
long long count(vector <string> letterMaze) {
bc[0] = 0;
for (int i=1; i<=MASK_ALL; ++i) {
bc[i] = bc[i>>1] + (i&1);
}
m = letterMaze.size();
n = letterMaze[0].size();
int letter = 0;
memset(ind, 0xff, sizeof ind);
for (int i=0; i<m; ++i) {
for (int j=0; j<n; ++j) {
if (letterMaze[i][j] == '.') {
A[i][j] = -1;
} else {
if (ind[letterMaze[i][j]] == -1) {
ind[letterMaze[i][j]] = letter++;
}
A[i][j] = ind[letterMaze[i][j]];
}
}
}
long long sol = 0;
for (int i=0; i<m; ++i) {
for (int j=0; j<n; ++j) {
if (A[i][j] != -1) {
counter = 0;
gen(i, j, 1<<A[i][j]);
for (int k=0; k<counter; ++k) {
const int mask = active[k];
const int other = (MASK_ALL ^ mask) | (1<<A[i][j]);
sol += (long long)cnt[mask]*cnt[other];
}
for (int k=0; k<counter; ++k) {
cnt[active[k]] = 0;
}
}
}
}
return sol;
}
};
// BEGIN CUT HERE
namespace moj_harness {
int run_test_case(int);
void run_test(int casenum = -1, bool quiet = false) {
if (casenum != -1) {
if (run_test_case(casenum) == -1 && !quiet) {
cerr << "Illegal input! Test case " << casenum << " does not exist." << endl;
}
return;
}
int correct = 0, total = 0;
for (int i=0;; ++i) {
int x = run_test_case(i);
if (x == -1) {
if (i >= 100) break;
continue;
}
correct += x;
++total;
}
if (total == 0) {
cerr << "No test cases run." << endl;
} else if (correct < total) {
cerr << "Some cases FAILED (passed " << correct << " of " << total << ")." << endl;
} else {
cerr << "All " << total << " tests passed!" << endl;
}
}
int verify_case(int casenum, const long long &expected, const long long &received, clock_t elapsed) {
cerr << "Example " << casenum << "... ";
string verdict;
vector<string> info;
char buf[100];
if (elapsed > CLOCKS_PER_SEC / 200) {
sprintf(buf, "time %.2fs", elapsed * (1.0/CLOCKS_PER_SEC));
info.push_back(buf);
}
if (expected == received) {
verdict = "PASSED";
} else {
verdict = "FAILED";
}
cerr << verdict;
if (!info.empty()) {
cerr << " (";
for (int i=0; i<(int)info.size(); ++i) {
if (i > 0) cerr << ", ";
cerr << info[i];
}
cerr << ")";
}
cerr << endl;
if (verdict == "FAILED") {
cerr << " Expected: " << expected << endl;
cerr << " Received: " << received << endl;
}
return verdict == "PASSED";
}
int run_test_case(int casenum) {
switch (casenum) {
case 0: {
string letterMaze[] = {"ABCDEFZHIXKLMNOPQRST", "...................V"};
long long expected__ = 2;
clock_t start__ = clock();
long long received__ = AlphabetPaths().count(vector <string>(letterMaze, letterMaze + (sizeof letterMaze / sizeof letterMaze[0])));
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 1: {
string letterMaze[] = {".................VT.", "....................", "ABCDEFZHIXKLMNOPQRS.", "..................S.", ".................VT."};
long long expected__ = 0;
clock_t start__ = clock();
long long received__ = AlphabetPaths().count(vector <string>(letterMaze, letterMaze + (sizeof letterMaze / sizeof letterMaze[0])));
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 2: {
string letterMaze[] = {"TBCDE.PQRSA", "FZHIXKLMNOV"};
long long expected__ = 50;
clock_t start__ = clock();
long long received__ = AlphabetPaths().count(vector <string>(letterMaze, letterMaze + (sizeof letterMaze / sizeof letterMaze[0])));
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 3: {
string letterMaze[] = {"ABCDEF.", "V....Z.", "T....H.", "S....I.", "R....X.", "KLMNOPQ"};
long long expected__ = 4;
clock_t start__ = clock();
long long received__ = AlphabetPaths().count(vector <string>(letterMaze, letterMaze + (sizeof letterMaze / sizeof letterMaze[0])));
return verify_case(casenum, expected__, received__, clock()-start__);
}
// custom cases
/* case 4: {
string letterMaze[] = ;
long long expected__ = ;
clock_t start__ = clock();
long long received__ = AlphabetPaths().count(vector <string>(letterMaze, letterMaze + (sizeof letterMaze / sizeof letterMaze[0])));
return verify_case(casenum, expected__, received__, clock()-start__);
}*/
/* case 5: {
string letterMaze[] = ;
long long expected__ = ;
clock_t start__ = clock();
long long received__ = AlphabetPaths().count(vector <string>(letterMaze, letterMaze + (sizeof letterMaze / sizeof letterMaze[0])));
return verify_case(casenum, expected__, received__, clock()-start__);
}*/
/* case 6: {
string letterMaze[] = ;
long long expected__ = ;
clock_t start__ = clock();
long long received__ = AlphabetPaths().count(vector <string>(letterMaze, letterMaze + (sizeof letterMaze / sizeof letterMaze[0])));
return verify_case(casenum, expected__, received__, clock()-start__);
}*/
default:
return -1;
}
}
}
int main(int argc, char *argv[]) {
if (argc == 1) {
moj_harness::run_test();
} else {
for (int i=1; i<argc; ++i)
moj_harness::run_test(atoi(argv[i]));
}
}
// END CUT HERE
| 29.081897 | 152 | 0.507781 | [
"vector"
] |
05b07958f6c7d712352af75ff06f0241d6b86594 | 9,759 | cpp | C++ | src/p2p/node.cpp | nondejus/WaykiChain | dddd2b882f380e416b3069155bb3431fd5627258 | [
"MIT"
] | 1 | 2020-02-27T00:29:05.000Z | 2020-02-27T00:29:05.000Z | src/p2p/node.cpp | nondejus/WaykiChain | dddd2b882f380e416b3069155bb3431fd5627258 | [
"MIT"
] | null | null | null | src/p2p/node.cpp | nondejus/WaykiChain | dddd2b882f380e416b3069155bb3431fd5627258 | [
"MIT"
] | null | null | null | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2017-2019 The WaykiChain Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "node.h"
#include "netmessage.h"
#include <openssl/rand.h>
uint64_t CNode::nTotalBytesRecv = 0;
uint64_t CNode::nTotalBytesSent = 0;
CCriticalSection CNode::cs_totalBytesRecv;
CCriticalSection CNode::cs_totalBytesSent;
CCriticalSection cs_nLastNodeId;
uint64_t nLocalServices = NODE_NETWORK;
uint64_t nLocalHostNonce = 0;
extern map<CNetAddr, LocalServiceInfo> mapLocalHost;
// Map maintaining per-node state. Requires cs_mapNodeState.
map<NodeId, CNodeState> mapNodeState;
CCriticalSection cs_mapNodeState;
NodeId nLastNodeId = 0;
limitedmap<CInv, int64_t> mapAlreadyAskedFor(MAX_INV_SZ);
CNode* pnodeSync = nullptr;
// Requires cs_mapNodeState.
CNodeState *State(NodeId pNode) {
AssertLockHeld(cs_mapNodeState);
map<NodeId, CNodeState>::iterator it = mapNodeState.find(pNode);
if (it == mapNodeState.end())
return nullptr;
return &it->second;
}
// requires LOCK(cs_vSend)
void CNode::SocketSendData() {
deque<CSerializeData>::iterator it = vSendMsg.begin();
while (it != vSendMsg.end()) {
const CSerializeData& data = *it;
assert(data.size() > nSendOffset);
int32_t nBytes = send(hSocket, &data[nSendOffset], data.size() - nSendOffset,
MSG_NOSIGNAL | MSG_DONTWAIT);
if (nBytes > 0) {
nLastSend = GetTime();
nSendBytes += nBytes;
nSendOffset += nBytes;
RecordBytesSent(nBytes);
if (nSendOffset == data.size()) {
nSendOffset = 0;
nSendSize -= data.size();
it++;
} else {
// could not send full message; stop sending more
break;
}
} else {
if (nBytes < 0) {
// error
int32_t nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
LogPrint(BCLog::INFO, "socket send error %s\n", NetworkErrorString(nErr));
CloseSocketDisconnect();
}
}
// couldn't send anything at all
break;
}
}
if (it == vSendMsg.end()) {
assert(nSendOffset == 0);
assert(nSendSize == 0);
}
vSendMsg.erase(vSendMsg.begin(), it);
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr* paddrPeer) {
if (fNoListen)
return false;
int32_t nBestScore = -1;
int32_t nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) {
int32_t nScore = (*it).second.nScore;
int32_t nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) {
addr = CService((*it).first, (*it).second.nPort);
nBestReachability = nReachability;
nBestScore = nScore;
}
}
}
return nBestScore >= 0;
}
// get best local address for a particular peer as a CAddress
CAddress GetLocalAddress(const CNetAddr* paddrPeer) {
CAddress ret(CService("0.0.0.0", 0), 0);
CService addr;
if (GetLocal(addr, paddrPeer)) {
ret = CAddress(addr);
ret.nServices = nLocalServices;
ret.nTime = GetAdjustedTime();
}
return ret;
}
void CNode::CloseSocketDisconnect() {
fDisconnect = true;
if (hSocket != INVALID_SOCKET) {
LogPrint(BCLog::NET, "disconnecting node %s\n", addrName);
closesocket(hSocket);
hSocket = INVALID_SOCKET;
}
// in case this fails, we'll empty the recv buffer when the CNode is deleted
TRY_LOCK(cs_vRecvMsg, lockRecv);
if (lockRecv) vRecvMsg.clear();
// if this was the sync node, we'll need a new one
if (this == pnodeSync)
pnodeSync = nullptr;
}
void CNode::Cleanup() {}
void CNode::PushVersion() {
int32_t nBestHeight = GetNodeSignals().GetHeight().get_value_or(0);
#ifdef WIN32
string os("windows");
#else
string os("linux");
#endif
vector<string> comments;
comments.push_back(os);
/// when NTP implemented, change to just nTime = GetAdjustedTime()
int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0", 0)));
CAddress addrMe = GetLocalAddress(&addr);
RAND_bytes((uint8_t*)&nLocalHostNonce, sizeof(nLocalHostNonce));
LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION,
nBestHeight, addrMe.ToString(), addrYou.ToString(), addr.ToString());
PushMessage(NetMsgType::VERSION, PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce,
FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, comments), nBestHeight, true);
}
map<CNetAddr, int64_t> CNode::setBanned;
CCriticalSection CNode::cs_setBanned;
void CNode::ClearBanned() { setBanned.clear(); }
bool CNode::IsBanned(CNetAddr ip) {
bool fResult = false;
{
LOCK(cs_setBanned);
map<CNetAddr, int64_t>::iterator i = setBanned.find(ip);
if (i != setBanned.end()) {
int64_t t = (*i).second;
if (GetTime() < t)
fResult = true;
}
}
return fResult;
}
bool CNode::Ban(const CNetAddr& addr) {
int64_t banTime = GetTime() + SysCfg().GetArg("-bantime", 60 * 60 * 24); // Default 24-hour ban
{
LOCK(cs_setBanned);
if (setBanned[addr] < banTime)
setBanned[addr] = banTime;
}
return true;
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats& stats) {
stats.nodeid = this->GetId();
X(nServices);
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(addrName);
X(nVersion);
X(cleanSubVer);
X(fInbound);
X(nStartingHeight);
X(nSendBytes);
X(nRecvBytes);
stats.fSyncNode = (this == pnodeSync);
// It is common for nodes with good ping times to suddenly become lagged,
// due to a new block arriving or other large transfer.
// Merely reporting pingtime might fool the caller into thinking the node was still responsive,
// since pingtime does not update until the ping is complete, which might take a while.
// So, if a ping is taking an unusually long time in flight,
// the caller can immediately detect that this is happening.
int64_t nPingUsecWait = 0;
if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
nPingUsecWait = GetTimeMicros() - nPingUsecStart;
}
// Raw ping time is in microseconds, but show it to user as whole seconds (Coin users should be well used to small
// numbers with many decimal places by now :)
stats.dPingTime = (((double)nPingUsecTime) / 1e6);
stats.dPingWait = (((double)nPingUsecWait) / 1e6);
// Leave string empty if addrLocal invalid (not filled in yet)
stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : "";
}
#undef X
// requires LOCK(cs_vRecvMsg)
bool CNode::ReceiveMsgBytes(const char* pch, uint32_t nBytes) {
while (nBytes > 0) {
// get current incomplete message, or create a new one
if (vRecvMsg.empty() || vRecvMsg.back().complete()) vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion));
CNetMessage& msg = vRecvMsg.back();
// absorb network data
int32_t handled;
if (!msg.in_data)
handled = msg.readHeader(pch, nBytes);
else
handled = msg.readData(pch, nBytes);
if (handled < 0)
return false;
pch += handled;
nBytes -= handled;
}
return true;
}
void CNode::RecordBytesRecv(uint64_t bytes) {
LOCK(cs_totalBytesRecv);
nTotalBytesRecv += bytes;
}
void CNode::RecordBytesSent(uint64_t bytes) {
LOCK(cs_totalBytesSent);
nTotalBytesSent += bytes;
}
uint64_t CNode::GetTotalBytesRecv() {
LOCK(cs_totalBytesRecv);
return nTotalBytesRecv;
}
uint64_t CNode::GetTotalBytesSent() {
LOCK(cs_totalBytesSent);
return nTotalBytesSent;
}
void CNode::Fuzz(int32_t nChance) {
if (!fSuccessfullyConnected)
return; // Don't fuzz initial handshake
if (GetRand(nChance) != 0)
return; // Fuzz 1 of every nChance messages
switch (GetRand(3)) {
case 0:
// xor a random byte with a random value:
if (!ssSend.empty()) {
CDataStream::size_type pos = GetRand(ssSend.size());
ssSend[pos] ^= (uint8_t)(GetRand(256));
}
break;
case 1:
// delete a random byte:
if (!ssSend.empty()) {
CDataStream::size_type pos = GetRand(ssSend.size());
ssSend.erase(ssSend.begin() + pos);
}
break;
case 2:
// insert a random byte at a random position
{
CDataStream::size_type pos = GetRand(ssSend.size());
char ch = (char)GetRand(256);
ssSend.insert(ssSend.begin() + pos, ch);
}
break;
}
// Chance of more than one change half the time:
// (more changes exponentially less likely):
Fuzz(2);
}
| 31.892157 | 119 | 0.61328 | [
"vector"
] |
05b81a1ca2fefd83010c1103d81c863bf4d208cf | 1,797 | hpp | C++ | MiningSimulation/miner.hpp | ysyesilyurt/OperatingSystems | 9ebdf363670d17ef232435ebe4f974f2ac9f8a7a | [
"MIT"
] | null | null | null | MiningSimulation/miner.hpp | ysyesilyurt/OperatingSystems | 9ebdf363670d17ef232435ebe4f974f2ac9f8a7a | [
"MIT"
] | 1 | 2019-06-08T20:31:12.000Z | 2019-06-08T20:31:12.000Z | MiningSimulation/miner.hpp | ysyesilyurt/OperatingSystems | 9ebdf363670d17ef232435ebe4f974f2ac9f8a7a | [
"MIT"
] | 2 | 2021-06-19T18:04:33.000Z | 2022-02-27T10:24:20.000Z | #ifndef _OS_2019_MINER_HPP
#define _OS_2019_MINER_HPP
#include "monitor.hpp"
class Miner: public Monitor {
int oreCount;
int minerID;
unsigned int minerPeriod;
unsigned int capacity;
unsigned int totalAmount;
OreType oreType;
bool quit;
Condition cv;
std::vector<Ore> storage;
public:
Miner(int mID, unsigned int mP, unsigned int cap, OreType oT, unsigned int tA) : cv(this) {
oreCount = 0;
minerID = mID;
minerPeriod = mP;
capacity = cap;
oreType = oT;
totalAmount = tA;
quit = false;
}
void mineOre() {
__synchronized__;
Ore ore;
ore.type = oreType;
storage.emplace_back(ore);
oreCount++;
}
void removeOre() {
__synchronized__;
storage.pop_back();
}
void setQuit() {
__synchronized__;
quit = true;
}
void wait() {
__synchronized__;
cv.wait();
}
void notify() {
__synchronized__;
cv.notify();
}
bool isFull() {
__synchronized__;
return storage.size() == capacity;
}
bool isEmpty() {
__synchronized__;
return storage.empty();
}
bool checkQuit() {
__synchronized__;
return ((oreCount == totalAmount) || quit);
}
int getPeriod() {
__synchronized__;
return minerPeriod;
}
int getMinerId() {
__synchronized__;
return minerID;
}
int getCapacity() {
__synchronized__;
return capacity;
}
int getCurrOreCount() {
__synchronized__;
return storage.size();
}
OreType getOreType() {
__synchronized__;
return oreType;
}
};
#endif /* _OS_2019_MINER_HPP */
| 17.97 | 95 | 0.553701 | [
"vector"
] |
05c0455d55893cc2c8e604230448116013f5998a | 6,914 | cc | C++ | ppapi/native_client/src/trusted/plugin/scriptable_plugin.cc | bluedump/BHO | 4ffead78823c4d655f05b0bc84cdb3c71ff4a1b2 | [
"Apache-2.0"
] | 2 | 2015-03-04T02:36:53.000Z | 2016-06-25T11:22:17.000Z | ppapi/native_client/src/trusted/plugin/scriptable_plugin.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ppapi/native_client/src/trusted/plugin/scriptable_plugin.cc | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4 | 2015-02-09T08:49:30.000Z | 2017-08-26T02:03:34.000Z | // Copyright (c) 2012 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.
// Scriptable plugin implementation.
#include "ppapi/native_client/src/trusted/plugin/scriptable_plugin.h"
#include <string.h>
#include <sstream>
#include <string>
#include <vector>
#include "native_client/src/include/nacl_macros.h"
#include "native_client/src/include/nacl_string.h"
#include "native_client/src/include/portability.h"
#include "native_client/src/shared/platform/nacl_check.h"
#include "native_client/src/shared/srpc/nacl_srpc.h"
#include "ppapi/native_client/src/trusted/plugin/plugin.h"
#include "ppapi/native_client/src/trusted/plugin/utility.h"
namespace plugin {
namespace {
pp::Var Error(const nacl::string& call_name, const char* caller,
const char* error, pp::Var* exception) {
nacl::stringstream error_stream;
error_stream << call_name << ": " << error;
if (!exception->is_undefined()) {
error_stream << " - " + exception->AsString();
}
// Get the error string in 2 steps; otherwise, the temporary string returned
// by the stream is destructed, causing a dangling pointer.
std::string str = error_stream.str();
const char* e = str.c_str();
PLUGIN_PRINTF(("ScriptablePlugin::%s (%s)\n", caller, e));
*exception = pp::Var(e);
return pp::Var();
}
} // namespace
ScriptablePlugin::ScriptablePlugin(Plugin* plugin)
: var_(NULL), num_unref_calls_(0), plugin_(plugin) {
PLUGIN_PRINTF(("ScriptablePlugin::ScriptablePlugin (this=%p, plugin=%p)\n",
static_cast<void*>(this),
static_cast<void*>(plugin)));
}
ScriptablePlugin::~ScriptablePlugin() {
PLUGIN_PRINTF(("ScriptablePlugin::~ScriptablePlugin (this=%p)\n",
static_cast<void*>(this)));
PLUGIN_PRINTF(("ScriptablePlugin::~ScriptablePlugin (this=%p, return)\n",
static_cast<void*>(this)));
}
void ScriptablePlugin::Unref(ScriptablePlugin** handle) {
if (*handle != NULL) {
(*handle)->Unref();
*handle = NULL;
}
}
ScriptablePlugin* ScriptablePlugin::NewPlugin(Plugin* plugin) {
PLUGIN_PRINTF(("ScriptablePlugin::NewPlugin (plugin=%p)\n",
static_cast<void*>(plugin)));
if (plugin == NULL) {
return NULL;
}
ScriptablePlugin* scriptable_plugin = new ScriptablePlugin(plugin);
if (scriptable_plugin == NULL) {
return NULL;
}
PLUGIN_PRINTF(("ScriptablePlugin::NewPlugin (return %p)\n",
static_cast<void*>(scriptable_plugin)));
return scriptable_plugin;
}
bool ScriptablePlugin::HasProperty(const pp::Var& name, pp::Var* exception) {
UNREFERENCED_PARAMETER(exception);
PLUGIN_PRINTF(("ScriptablePlugin::HasProperty (this=%p, name=%s)\n",
static_cast<void*>(this), name.DebugString().c_str()));
return false;
}
bool ScriptablePlugin::HasMethod(const pp::Var& name, pp::Var* exception) {
UNREFERENCED_PARAMETER(exception);
PLUGIN_PRINTF(("ScriptablePlugin::HasMethod (this=%p, name='%s')\n",
static_cast<void*>(this), name.DebugString().c_str()));
return false;
}
pp::Var ScriptablePlugin::GetProperty(const pp::Var& name,
pp::Var* exception) {
PLUGIN_PRINTF(("ScriptablePlugin::GetProperty (name=%s)\n",
name.DebugString().c_str()));
Error("GetProperty", name.DebugString().c_str(),
"property getting is not supported", exception);
return pp::Var();
}
void ScriptablePlugin::SetProperty(const pp::Var& name,
const pp::Var& value,
pp::Var* exception) {
PLUGIN_PRINTF(("ScriptablePlugin::SetProperty (name=%s, value=%s)\n",
name.DebugString().c_str(), value.DebugString().c_str()));
Error("SetProperty", name.DebugString().c_str(),
"property setting is not supported", exception);
}
void ScriptablePlugin::RemoveProperty(const pp::Var& name,
pp::Var* exception) {
PLUGIN_PRINTF(("ScriptablePlugin::RemoveProperty (name=%s)\n",
name.DebugString().c_str()));
Error("RemoveProperty", name.DebugString().c_str(),
"property removal is not supported", exception);
}
void ScriptablePlugin::GetAllPropertyNames(std::vector<pp::Var>* properties,
pp::Var* exception) {
PLUGIN_PRINTF(("ScriptablePlugin::GetAllPropertyNames ()\n"));
UNREFERENCED_PARAMETER(properties);
UNREFERENCED_PARAMETER(exception);
Error("GetAllPropertyNames", "", "GetAllPropertyNames is not supported",
exception);
}
pp::Var ScriptablePlugin::Call(const pp::Var& name,
const std::vector<pp::Var>& args,
pp::Var* exception) {
PLUGIN_PRINTF(("ScriptablePlugin::Call (name=%s, %" NACL_PRIuS
" args)\n", name.DebugString().c_str(), args.size()));
return Error("Call", name.DebugString().c_str(),
"method invocation is not supported", exception);
}
pp::Var ScriptablePlugin::Construct(const std::vector<pp::Var>& args,
pp::Var* exception) {
PLUGIN_PRINTF(("ScriptablePlugin::Construct (%" NACL_PRIuS
" args)\n", args.size()));
return Error("constructor", "Construct", "constructor is not supported",
exception);
}
ScriptablePlugin* ScriptablePlugin::AddRef() {
// This is called when we are about to share this object with the browser,
// and we need to make sure we have an internal plugin reference, so this
// object doesn't get deallocated when the browser discards its references.
if (var_ == NULL) {
var_ = new pp::VarPrivate(plugin_, this);
CHECK(var_ != NULL);
}
PLUGIN_PRINTF(("ScriptablePlugin::AddRef (this=%p, var=%p)\n",
static_cast<void*>(this), static_cast<void*>(var_)));
return this;
}
void ScriptablePlugin::Unref() {
// We should have no more than one internal owner of this object, so this
// should be called no more than once.
CHECK(++num_unref_calls_ == 1);
PLUGIN_PRINTF(("ScriptablePlugin::Unref (this=%p, var=%p)\n",
static_cast<void*>(this), static_cast<void*>(var_)));
if (var_ != NULL) {
// We have shared this with the browser while keeping our own var
// reference, but we no longer need ours. If the browser has copies,
// it will clean things up later, otherwise this object will get
// deallocated right away.
PLUGIN_PRINTF(("ScriptablePlugin::Unref (delete var)\n"));
pp::Var* var = var_;
var_ = NULL;
delete var;
} else {
// Neither the browser nor plugin ever var referenced this object,
// so it can safely discarded.
PLUGIN_PRINTF(("ScriptablePlugin::Unref (delete this)\n"));
CHECK(var_ == NULL);
delete this;
}
}
} // namespace plugin
| 36.010417 | 78 | 0.649696 | [
"object",
"vector"
] |
05c18e33b8579c083c2e492808300bab1ddc9074 | 22,478 | cpp | C++ | enduser/netmeeting/av/nac/datapump.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | enduser/netmeeting/av/nac/datapump.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | enduser/netmeeting/av/nac/datapump.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*
DATAPUMP.C
*/
#include "precomp.h"
#include "confreg.h"
#include "mixer.h"
#include "dscStream.h"
extern UINT g_MinDSEmulAudioDelayMs; // minimum millisecs of introduced playback delay (DirectSound on emulated drivers)
extern UINT g_MinWaveAudioDelayMs; // minimum millisecs of introduced playback delay (Wave)
extern UINT g_MaxAudioDelayMs; // maximum milliesecs of introduced playback delay
extern UINT g_AudioPacketDurationMs; // preferred packet duration
extern int g_wavein_prepare, g_waveout_prepare;
extern int g_videoin_prepare, g_videoout_prepare;
#define RSVP_KEY TEXT("RSVP")
HANDLE g_hEventHalfDuplex = NULL;
HWND DataPump::m_hAppWnd = NULL;
HINSTANCE DataPump::m_hAppInst = NULL;
HRESULT WINAPI CreateStreamProvider(IMediaChannelBuilder **lplpSP)
{
DataPump * pDataPump;
if(!lplpSP)
return DPR_INVALID_PARAMETER;
DBG_SAVE_FILE_LINE
pDataPump = new DataPump;
if(NULL == pDataPump)
return DPR_OUT_OF_MEMORY;
// the refcount of DataPump is 1. Don't call pDataPump->QueryInterface(),
// just do what QueryInterface() would do except don't increment refcount
*lplpSP = (IMediaChannelBuilder *)pDataPump;
return hrSuccess;
}
DataPump::DataPump(void)
:m_uRef(1)
{
ClearStruct( &m_Audio );
ClearStruct( &m_Video );
InitializeCriticalSection(&m_crs);
// Create performance counters
InitCountersAndReports();
}
DataPump::~DataPump(void)
{
ReleaseResources();
WSACleanup();
DeleteCriticalSection(&m_crs);
// We're done with performance counters
DoneCountersAndReports();
}
HRESULT __stdcall DataPump::Initialize(HWND hWnd, HINSTANCE hInst)
{
HRESULT hr = DPR_OUT_OF_MEMORY;
FX_ENTRY ("DP::Init")
WSADATA WSAData;
int status;
BOOL fDisableWS2;
UINT uMinDelay;
TCHAR *szKey = NACOBJECT_KEY TEXT("\\") RSVP_KEY;
RegEntry reRSVP(szKey, HKEY_LOCAL_MACHINE, FALSE);
if((NULL == hWnd) || (NULL == hInst))
goto InitError;
m_hAppInst = hInst;
m_hAppWnd = hWnd;
status = WSAStartup(MAKEWORD(1,1), &WSAData);
if(status !=0)
{
ERRORMESSAGE(("CNac::Init:WSAStartup failed\r\n"));
goto InitError;
}
// Introduce scope to allow creation of object after goto statements
{
// get settings from registry
RegEntry reNac(szRegInternetPhone TEXT("\\") szRegInternetPhoneNac,
HKEY_LOCAL_MACHINE,
FALSE,
KEY_READ);
g_MaxAudioDelayMs = reNac.GetNumberIniStyle(TEXT ("MaxAudioDelayMs"), g_MaxAudioDelayMs);
uMinDelay = reNac.GetNumberIniStyle(TEXT ("MinAudioDelayMs"), 0);
if (uMinDelay != 0)
{
g_MinWaveAudioDelayMs = uMinDelay;
g_MinDSEmulAudioDelayMs = uMinDelay;
}
fDisableWS2 = reNac.GetNumberIniStyle(TEXT ("DisableWinsock2"), 0);
}
#ifdef OLDSTUFF
// to be safe, only try loading WS2_32 if WSOCK32 is passing
// thru to it. Once we make sure that we link to the same DLL for all
// Winsock calls to a socket, this check can possibly be removed.
if (LOBYTE(WSAData.wHighVersion) >= 2 && !fDisableWS2)
TryLoadWinsock2();
#endif
// Initialize data (should be in constructor)
g_hEventHalfDuplex = CreateEvent (NULL, FALSE, TRUE, __TEXT ("AVC:HalfDuplex"));
if (g_hEventHalfDuplex == NULL)
{
DEBUGMSG (ZONE_DP, ("%s: CreateEvent failed, LastErr=%lu\r\n", _fx_, GetLastError ()));
hr = DPR_CANT_CREATE_EVENT;
return hr;
}
// Initialize QoS. If it fails, that's Ok, we'll do without it.
// No need to set the resource ourselves, this now done by the UI
hr = CreateQoS (NULL, IID_IQoS, (void **)&m_pIQoS);
if (hr != DPR_SUCCESS)
m_pIQoS = (LPIQOS)NULL;
m_bDisableRSVP = reRSVP.GetNumber("DisableRSVP", FALSE);
LogInit(); // Initialize log
//No receive channels yet
m_nReceivers=0;
// IVideoDevice initialize
m_uVideoCaptureId = -1; // (VIDEO_MAPPER)
// IAudioDevice initialize
m_uWaveInID = WAVE_MAPPER;
m_uWaveOutID = WAVE_MAPPER;
m_bFullDuplex = FALSE;
m_uSilenceLevel = 1000; // automatic silence detection
m_bAutoMix = FALSE;
m_bDirectSound = FALSE;
return DPR_SUCCESS;
InitError:
ERRORMESSAGE( ("DataPump::Initialize: exit, hr=0x%lX\r\n", hr));
return hr;
}
STDMETHODIMP
DataPump::CreateMediaChannel( UINT flags, IMediaChannel **ppIMC)
{
IUnknown *pUnkOuter = NULL;
IMediaChannel *pStream = NULL;
HRESULT hr = E_FAIL;
// try to be consistant about which parent classes we cast to
*ppIMC = NULL;
if (flags & MCF_AUDIO)
{
if ((flags & MCF_SEND) && !m_Audio.pSendStream)
{
if (m_bDirectSound && (DSC_Manager::Initialize() == S_OK))
{
DBG_SAVE_FILE_LINE
pStream = (IMediaChannel*)(SendMediaStream*)new SendDSCStream;
}
else
{
DBG_SAVE_FILE_LINE
pStream = (IMediaChannel*)(SendMediaStream*)new SendAudioStream;
}
}
else if ((flags & MCF_RECV) && !m_Audio.pRecvStream)
{
if (m_bDirectSound && (DirectSoundMgr::Initialize() == S_OK))
{
DBG_SAVE_FILE_LINE
pStream = (IMediaChannel*)(RecvMediaStream*)new RecvDSAudioStream;
}
else
{
DBG_SAVE_FILE_LINE
pStream = (IMediaChannel*)(RecvMediaStream*)new RecvAudioStream;
}
}
}
else if (flags & MCF_VIDEO)
{
if ((flags & MCF_SEND) && !m_Video.pSendStream)
{
DBG_SAVE_FILE_LINE
pStream = (IMediaChannel*)(SendMediaStream*) new SendVideoStream;
}
else if ((flags & MCF_RECV) && !m_Video.pRecvStream)
{
DBG_SAVE_FILE_LINE
pStream = (IMediaChannel*)(RecvMediaStream*) new RecvVideoStream;
}
}
else
hr = E_INVALIDARG;
if (pStream != NULL) {
// need to inc the refCount of the object
pStream->AddRef();
hr = (flags & MCF_SEND) ?
((SendMediaStream *)pStream)->Initialize( this)
: ((RecvMediaStream *)pStream)->Initialize(this);
if (hr == S_OK)
{
hr = pStream->QueryInterface(IID_IMediaChannel, (void **)ppIMC);
}
if (hr == S_OK)
{
AddMediaChannel(flags, pStream);
}
// calling to the IVideoDevice and IAudioDevice methods
// prior to creating the corresponding channel object
// require when they get created
// video only needs it's device ID set
if ((flags & MCF_SEND) && (flags & MCF_VIDEO))
{
SetCurrCapDevID(m_uVideoCaptureId);
}
// audio streams need several properties set
if (flags & MCF_AUDIO)
{
if (flags & MCF_SEND)
{
SetSilenceLevel(m_uSilenceLevel);
SetAutoMix(m_bAutoMix);
SetRecordID(m_uWaveInID);
}
else if (flags & MCF_RECV)
{
SetPlaybackID(m_uWaveOutID);
}
SetStreamDuplex(pStream, m_bFullDuplex);
}
// to avoid a circular ref-count,
// dont keep a hard reference to MediaChannel objects
// MediaChannel will call RemoveMediaChannel before it goes away..
pStream->Release();
pStream = NULL;
}
return hr;
}
STDMETHODIMP DataPump::SetStreamEventObj(IStreamEventNotify *pNotify)
{
EnterCriticalSection(&m_crs);
if (m_pTEP)
{
delete m_pTEP;
m_pTEP = NULL;
}
if (pNotify)
{
DBG_SAVE_FILE_LINE
m_pTEP = new ThreadEventProxy(pNotify, m_hAppInst);
}
LeaveCriticalSection(&m_crs);
return S_OK;
}
// this function gets called by the stream threads when an event occurs
STDMETHODIMP DataPump::StreamEvent(UINT uDirection, UINT uMediaType,
UINT uEventType, UINT uSubCode)
{
BOOL bRet = FALSE;
EnterCriticalSection(&m_crs);
if (m_pTEP)
{
bRet = m_pTEP->ThreadEvent(uDirection, uMediaType, uEventType, uSubCode);
}
LeaveCriticalSection(&m_crs);
return bRet ? DPR_INVALID_PARAMETER : DPR_SUCCESS;
}
void
DataPump::AddMediaChannel(UINT flags, IMediaChannel *pMediaChannel)
{
EnterCriticalSection(&m_crs);
if (flags & MCF_SEND)
{
SendMediaStream *pS = static_cast<SendMediaStream *> (pMediaChannel);
if (flags & MCF_AUDIO)
m_Audio.pSendStream = pS;
else if (flags & MCF_VIDEO)
m_Video.pSendStream = pS;
}
else if (flags & MCF_RECV)
{
RecvMediaStream *pR = static_cast<RecvMediaStream *> (pMediaChannel);
if (flags & MCF_AUDIO)
m_Audio.pRecvStream = pR;
else if (flags & MCF_VIDEO)
m_Video.pRecvStream = pR;
}
LeaveCriticalSection(&m_crs);
}
void
DataPump::RemoveMediaChannel(UINT flags, IMediaChannel *pMediaChannel)
{
EnterCriticalSection(&m_crs);
if (flags & MCF_SEND)
{
if (flags & MCF_AUDIO)
{
ASSERT(pMediaChannel == m_Audio.pSendStream);
if (pMediaChannel == m_Audio.pSendStream)
m_Audio.pSendStream = NULL;
}
else if (flags & MCF_VIDEO)
{
ASSERT(pMediaChannel == m_Video.pSendStream);
m_Video.pSendStream = NULL;
}
}
else if (flags & MCF_RECV)
{
if (flags & MCF_AUDIO)
{
ASSERT(pMediaChannel == m_Audio.pRecvStream);
m_Audio.pRecvStream = NULL;
}
else if (flags & MCF_VIDEO)
{
ASSERT(pMediaChannel == m_Video.pRecvStream);
m_Video.pRecvStream = NULL;
}
}
LeaveCriticalSection(&m_crs);
}
// called by Record Thread and Receive Thread, usually to get the
// opposite channel
HRESULT DataPump::GetMediaChannelInterface( UINT flags, IMediaChannel **ppI)
{
// extern IID IID_IMediaChannel;
IMediaChannel *pStream = NULL;
HRESULT hr;
EnterCriticalSection(&m_crs);
if (flags & MCF_AUDIO) {
if (flags & MCF_SEND) {
pStream = m_Audio.pSendStream;
} else if (flags & MCF_RECV) {
pStream = m_Audio.pRecvStream;
}
}
else if (flags & MCF_VIDEO) {
if (flags & MCF_SEND) {
pStream = m_Video.pSendStream;
} else if (flags & MCF_RECV) {
pStream = m_Video.pRecvStream;
}
} else
hr = DPR_INVALID_PARAMETER;
if (pStream) {
// need to inc the refCount of the object
hr = (pStream)->QueryInterface(IID_IMediaChannel, (PVOID *)ppI);
} else
hr = E_NOINTERFACE;
LeaveCriticalSection(&m_crs);
return hr;
}
DWORD __stdcall StartDPRecvThread(PVOID pVoid)
{
DataPump *pDP = (DataPump*)pVoid;
return pDP->CommonWS2RecvThread();
}
STDMETHODIMP DataPump::QueryInterface( REFIID iid, void ** ppvObject)
{
// this breaks the rules for the official COM QueryInterface because
// the interfaces that are queried for are not necessarily real COM
// interfaces. The reflexive property of QueryInterface would be broken in
// that case.
HRESULT hr = E_NOINTERFACE;
if(!ppvObject)
return hr;
*ppvObject = NULL;
if(iid == IID_IUnknown)// satisfy symmetric property of QI
{
*ppvObject = this;
hr = hrSuccess;
AddRef();
}
else if(iid == IID_IMediaChannelBuilder)
{
*ppvObject = (IMediaChannelBuilder *)this;
hr = hrSuccess;
AddRef();
}
else if (iid == IID_IVideoDevice)
{
*ppvObject = (IVideoDevice *)this;
hr = hrSuccess;
AddRef();
}
else if (iid == IID_IAudioDevice)
{
*ppvObject = (IAudioDevice*)this;
hr = hrSuccess;
AddRef();
}
return (hr);
}
ULONG DataPump::AddRef()
{
m_uRef++;
return m_uRef;
}
ULONG DataPump::Release()
{
m_uRef--;
if(m_uRef == 0)
{
m_hAppWnd = NULL;
m_hAppInst = NULL;
delete this;
return 0;
}
return m_uRef;
}
void
DataPump::ReleaseResources()
{
FX_ENTRY ("DP::ReleaseResources")
#ifdef DEBUG
if (m_Audio.pSendStream)
ERRORMESSAGE(("%s: Audio Send stream still around => Ref count LEAK!\n", _fx_));
if (m_Audio.pRecvStream)
ERRORMESSAGE(("%s: Audio Recv stream still around => Ref count LEAK!\n", _fx_));
if (m_Video.pSendStream)
ERRORMESSAGE(("%s: Video Send stream still around => Ref count LEAK!\n", _fx_));
if (m_Video.pRecvStream)
ERRORMESSAGE(("%s: Video Recv stream still around => Ref count LEAK!\n", _fx_));
#endif
// close debug log
LogClose();
// Free QoS resources
if (m_pIQoS)
{
m_pIQoS->Release();
m_pIQoS = (LPIQOS)NULL;
}
// Close the receive and transmit streams
if (g_hEventHalfDuplex)
{
CloseHandle (g_hEventHalfDuplex);
g_hEventHalfDuplex = NULL;
}
}
HRESULT DataPump::SetStreamDuplex(IMediaChannel *pStream, BOOL bFullDuplex)
{
BOOL fOn = (pStream->GetState() == MSSTATE_STARTED);
BOOL bStreamFullDuplex;
UINT uSize = sizeof(BOOL);
pStream->GetProperty(PROP_DUPLEX_TYPE, &bStreamFullDuplex, &uSize);
if (bStreamFullDuplex != bFullDuplex)
{
if (fOn)
{
pStream->Stop();
}
pStream->SetProperty(DP_PROP_DUPLEX_TYPE, &bFullDuplex, sizeof(BOOL));
if (fOn)
{
pStream->Start();
}
}
return S_OK;
}
HRESULT __stdcall DataPump::SetDuplex(BOOL bFullDuplex)
{
IMediaChannel *pS = m_Audio.pSendStream;
IMediaChannel *pR = m_Audio.pRecvStream;
IMediaChannel *pStream;
BOOL fPlayOn = FALSE;
BOOL fRecOn = FALSE;
UINT uSize;
BOOL bRecDuplex, bPlayDuplex;
m_bFullDuplex = bFullDuplex ? TRUE : FALSE;
UPDATE_REPORT_ENTRY(g_prptSystemSettings, (m_bFullDuplex) ? 1 : 0, REP_SYS_AUDIO_DUPLEX);
RETAILMSG(("NAC: Audio Duplex Type: %s",(m_bFullDuplex) ? "Full Duplex" : "Half Duplex"));
// no streams ? No problem.
if ((pS == NULL) && (pR == NULL))
{
return S_OK;
}
// only one stream
if ((pS || pR) && !(pS && pR))
{
if (pS)
pStream = pS;
else
pStream = pR;
return SetStreamDuplex(pStream, m_bFullDuplex);
}
// assert - pS && pR
// both streams exist
// try to avoid the whole start/stop sequence if the duplex
// is the same
uSize=sizeof(BOOL);
pR->GetProperty(PROP_DUPLEX_TYPE, &bRecDuplex, &uSize);
uSize=sizeof(BOOL);
pS->GetProperty(PROP_DUPLEX_TYPE, &bPlayDuplex, &uSize);
if ( (bPlayDuplex == m_bFullDuplex) &&
(bRecDuplex == m_bFullDuplex))
{
return S_OK;
}
// save the old thread flags
fPlayOn = (pR->GetState() == MSSTATE_STARTED);
fRecOn = (pS->GetState() == MSSTATE_STARTED);
// Ensure the record and playback threads are stopped
pR->Stop();
pS->Stop();
SetStreamDuplex(pR, m_bFullDuplex);
SetStreamDuplex(pS, m_bFullDuplex);
// Resume the record/playback
// Try to let play start before record - DirectS and SB16 prefer that!
if (fPlayOn)
{
pR->Start();
}
if (fRecOn)
{
pS->Start();
}
return DPR_SUCCESS;
}
#define LONGTIME 60000 // 60 seconds
// utility function to synchronously communicate a
// a state change to the recv thread
HRESULT DataPump::RecvThreadMessage(UINT msg, RecvMediaStream *pMS)
{
BOOL fSignaled;
DWORD dwWaitStatus;
HANDLE handle;
// Unfortunately cant use PostThreadMessage to signal the thread
// because it doesnt have a message loop
m_pCurRecvStream = pMS;
m_CurRecvMsg = msg;
fSignaled = SetEvent(m_hRecvThreadSignalEvent);
if (fSignaled) {
handle = (msg == MSG_EXIT_RECV ? m_hRecvThread : m_hRecvThreadAckEvent);
dwWaitStatus = WaitForSingleObject(handle, LONGTIME);
ASSERT(dwWaitStatus == WAIT_OBJECT_0);
if (dwWaitStatus != WAIT_OBJECT_0)
return GetLastError();
} else
return GetLastError();
return S_OK;
}
// start receiving on this stream
// will create the receive thread if necessary.
HRESULT
DataPump::StartReceiving(RecvMediaStream *pMS)
{
DWORD dwWaitStatus;
FX_ENTRY("DP::StartReceiving")
// one more stream
m_nReceivers++;
if (!m_hRecvThread) {
ASSERT(m_nReceivers==1);
ASSERT(!m_hRecvThreadAckEvent);
//Use this for thread event notifications. I.e. Video started/stopped, audio stopped, et al.
//m_hRecvThreadChangeEvent=CreateEvent (NULL,FALSE,FALSE,NULL);
//create the stopping sync event
m_hRecvThreadAckEvent=CreateEvent (NULL,FALSE,FALSE,NULL);
m_hRecvThreadSignalEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
m_hRecvThread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)StartDPRecvThread,(PVOID)this,0,&m_RecvThId);
DEBUGMSG(ZONE_DP,("%s: RecvThread Id=%x\n",_fx_,m_RecvThId));
// thread will signal event soon as its message loop is ready
dwWaitStatus = WaitForSingleObject(m_hRecvThreadAckEvent, LONGTIME);
ASSERT(dwWaitStatus == WAIT_OBJECT_0);
}
//Tell the recv Thread to start receiving on this MediaStream
return RecvThreadMessage(MSG_START_RECV,pMS);
}
// Stop receiving on the stream
// will stop the receive thread if necessary
HRESULT
DataPump::StopReceiving(RecvMediaStream *pMS)
{
HANDLE rgh[2];
ASSERT(m_nReceivers > 0);
ASSERT(m_hRecvThread);
if (m_nReceivers > 0)
m_nReceivers--;
RecvThreadMessage(MSG_STOP_RECV, pMS);
if (!m_nReceivers && m_hRecvThread) {
// kill the receive thread
RecvThreadMessage(MSG_EXIT_RECV,NULL);
CloseHandle(m_hRecvThread);
CloseHandle(m_hRecvThreadAckEvent);
m_hRecvThread = NULL;
m_hRecvThreadAckEvent = NULL;
if (m_hRecvThreadSignalEvent) {
CloseHandle(m_hRecvThreadSignalEvent);
m_hRecvThreadSignalEvent = NULL;
}
}
return S_OK;
}
//
// IVideoDevice Methods
//
// Capture device methods
// Gets the number of enabled capture devices
// Returns -1L on error
HRESULT __stdcall DataPump::GetNumCapDev()
{
FINDCAPTUREDEVICE fcd;
// scan for broken or unplugged devices
FindFirstCaptureDevice(&fcd, NULL);
return (GetNumCaptureDevices());
}
// Gets the max size of the captuire device name
// Returns -1L on error
HRESULT __stdcall DataPump::GetMaxCapDevNameLen()
{
return (MAX_CAPDEV_NAME + MAX_CAPDEV_DESCRIPTION);
}
// Enum list of enabled capture devices
// Fills up 1st buffer with device IDs, 2nd buffer with device names
// Third parameter is the max number of devices to enum
// Returns number of devices enum-ed
HRESULT __stdcall DataPump::EnumCapDev(DWORD *pdwCapDevIDs, TCHAR *pszCapDevNames, DWORD dwNumCapDev)
{
FINDCAPTUREDEVICE fcd;
DWORD dwNumCapDevFound = 0;
fcd.dwSize = sizeof (FINDCAPTUREDEVICE);
if (FindFirstCaptureDevice(&fcd, NULL))
{
do
{
pdwCapDevIDs[dwNumCapDevFound] = fcd.nDeviceIndex;
// Build device name out of the capture device strings
if (fcd.szDeviceDescription && fcd.szDeviceDescription[0] != '\0')
lstrcpy(pszCapDevNames + dwNumCapDevFound * (MAX_CAPDEV_NAME + MAX_CAPDEV_DESCRIPTION), fcd.szDeviceDescription);
else
lstrcpy(pszCapDevNames + dwNumCapDevFound * (MAX_CAPDEV_NAME + MAX_CAPDEV_DESCRIPTION), fcd.szDeviceName);
if (fcd.szDeviceVersion && fcd.szDeviceVersion[0] != '\0')
{
lstrcat(pszCapDevNames + dwNumCapDevFound * (MAX_CAPDEV_NAME + MAX_CAPDEV_DESCRIPTION), ", ");
lstrcat(pszCapDevNames + dwNumCapDevFound * (MAX_CAPDEV_NAME + MAX_CAPDEV_DESCRIPTION), fcd.szDeviceVersion);
}
dwNumCapDevFound++;
} while ((dwNumCapDevFound < dwNumCapDev) && FindNextCaptureDevice(&fcd));
}
return (dwNumCapDevFound);
}
HRESULT __stdcall DataPump::GetCurrCapDevID()
{
UINT uCapID;
UINT uSize = sizeof(UINT);
// even though we know the value of the last call
// to SetCurrCapDevID, the stream may have resulted in using
// wave_mapper (-1). We want to be able to return -1, if this
// is the case. However, the channel objects don't do this yet.
// (they still return the same value as m_uVideoCaptureId)
if (m_Video.pSendStream)
{
m_Video.pSendStream->GetProperty(PROP_CAPTURE_DEVICE, &uCapID, &uSize);
#ifdef DEBUG
if (uCapID != m_uVideoCaptureId)
{
DEBUGMSG(ZONE_DP,("Video capture stream had to revert to MAPPER or some other device"));
}
#endif
return uCapID;
}
return m_uVideoCaptureId;
}
HRESULT __stdcall DataPump::SetCurrCapDevID(int nCapDevID)
{
m_uVideoCaptureId = (UINT)nCapDevID;
if (m_Video.pSendStream)
{
m_Video.pSendStream->SetProperty(PROP_CAPTURE_DEVICE, &m_uVideoCaptureId, sizeof(m_uVideoCaptureId));
}
return S_OK;
}
// IAudioDevice methods
HRESULT __stdcall DataPump::GetRecordID(UINT *puWaveDevID)
{
*puWaveDevID = m_uWaveInID;
return S_OK;
}
HRESULT __stdcall DataPump::SetRecordID(UINT uWaveDevID)
{
m_uWaveInID = uWaveDevID;
if (m_Audio.pSendStream)
{
m_Audio.pSendStream->SetProperty(PROP_RECORD_DEVICE, &m_uWaveInID, sizeof(m_uWaveInID));
}
return S_OK;
}
HRESULT __stdcall DataPump::GetPlaybackID(UINT *puWaveDevID)
{
// like video, the audio device may have resorted to using
// WAVE_MAPPER. We'd like to be able to detect that
*puWaveDevID = m_uWaveOutID;
return S_OK;
}
HRESULT __stdcall DataPump::SetPlaybackID(UINT uWaveDevID)
{
m_uWaveOutID = uWaveDevID;
if (m_Audio.pRecvStream)
{
m_Audio.pRecvStream->SetProperty(PROP_PLAYBACK_DEVICE, &m_uWaveOutID, sizeof(m_uWaveOutID));
}
return S_OK;
}
HRESULT __stdcall DataPump::GetSilenceLevel(UINT *puLevel)
{
*puLevel = m_uSilenceLevel;
return S_OK;
}
HRESULT __stdcall DataPump::SetSilenceLevel(UINT uLevel)
{
m_uSilenceLevel = uLevel;
if (m_Audio.pSendStream)
{
m_Audio.pSendStream->SetProperty(PROP_SILENCE_LEVEL, &m_uSilenceLevel, sizeof(m_uSilenceLevel));
}
return S_OK;
}
HRESULT __stdcall DataPump::GetDuplex(BOOL *pbFullDuplex)
{
*pbFullDuplex = m_bFullDuplex;
return S_OK;
}
HRESULT __stdcall DataPump::GetMixer(HWND hwnd, BOOL bPlayback, IMixer **ppMixer)
{
CMixerDevice *pMixerDevice = NULL;
DWORD dwFlags;
HRESULT hr = E_NOINTERFACE;
// unfortunately, trying to create a mixer when WAVE_MAPPER
// has been specified as the device ID results in a mixer
// that doesn't work on Win95.
*ppMixer = NULL;
if ((bPlayback) && (m_uWaveOutID != WAVE_MAPPER))
{
pMixerDevice = CMixerDevice::GetMixerForWaveDevice(hwnd, m_uWaveOutID, MIXER_OBJECTF_WAVEOUT);
}
else if (m_uWaveInID != WAVE_MAPPER)
{
pMixerDevice = CMixerDevice::GetMixerForWaveDevice(hwnd, m_uWaveInID, MIXER_OBJECTF_WAVEIN);
}
if (pMixerDevice)
{
hr = pMixerDevice->QueryInterface(IID_IMixer, (void**)ppMixer);
}
return hr;
}
HRESULT __stdcall DataPump::GetAutoMix(BOOL *pbAutoMix)
{
*pbAutoMix = m_bAutoMix;
return S_OK;
}
HRESULT __stdcall DataPump::SetAutoMix(BOOL bAutoMix)
{
m_bAutoMix = bAutoMix;
if (m_Audio.pSendStream)
{
m_Audio.pSendStream->SetProperty(PROP_AUDIO_AUTOMIX, &m_bAutoMix, sizeof(m_bAutoMix));
}
return S_OK;
}
HRESULT __stdcall DataPump::GetDirectSound(BOOL *pbDS)
{
*pbDS = m_bDirectSound;
return S_OK;
}
HRESULT __stdcall DataPump::SetDirectSound(BOOL bDS)
{
m_bDirectSound = bDS;
return S_OK;
}
| 24.040642 | 121 | 0.682267 | [
"object"
] |
05cbaec0cf0800ae794b090e6985d26a25fe637e | 2,598 | cpp | C++ | dev/Basic/shared/geospatial/network/Link.cpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 50 | 2018-12-21T08:21:38.000Z | 2022-01-24T09:47:59.000Z | dev/Basic/shared/geospatial/network/Link.cpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 2 | 2018-12-19T13:42:47.000Z | 2019-05-13T04:11:45.000Z | dev/Basic/shared/geospatial/network/Link.cpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 27 | 2018-11-28T07:30:34.000Z | 2022-02-05T02:22:26.000Z | //Copyright (c) 2013 Singapore-MIT Alliance for Research and Technology
//Licensed under the terms of the MIT License, as described in the file:
// license.txt (http://opensource.org/licenses/MIT)
#include <algorithm>
#include "Link.hpp"
#include "util/LangHelpers.hpp"
using namespace sim_mob;
Link::Link() :
length(0), linkId(0), fromNode(NULL), fromNodeId(0), linkCategory(LINK_CATEGORY_A), linkType(LINK_TYPE_DEFAULT), roadName(""), toNode(nullptr),
toNodeId(0)
{
}
Link::~Link()
{
//Delete the road segment in the link
clear_delete_vector(roadSegments);
}
unsigned int Link::getLinkId() const
{
return linkId;
}
void Link::setLinkId(unsigned int linkId)
{
this->linkId = linkId;
}
const Node* Link::getFromNode() const
{
return fromNode;
}
void Link::setFromNode(Node *fromNode)
{
this->fromNode = fromNode;
}
unsigned int Link::getFromNodeId() const
{
return fromNodeId;
}
void Link::setFromNodeId(unsigned int fromNodeId)
{
this->fromNodeId = fromNodeId;
}
LinkCategory Link::getLinkCategory() const
{
return linkCategory;
}
void Link::setLinkCategory(LinkCategory linkCategory)
{
this->linkCategory = linkCategory;
}
LinkType Link::getLinkType() const
{
return linkType;
}
void Link::setLinkType(LinkType linkType)
{
this->linkType = linkType;
}
std::string Link::getRoadName() const
{
return roadName;
}
void Link::setRoadName(std::string roadName)
{
this->roadName = roadName;
}
const std::vector<RoadSegment*>& Link::getRoadSegments() const
{
return roadSegments;
}
const RoadSegment* Link::getRoadSegment(int index) const
{
return roadSegments.at(index);
}
int Link::getRoadSegmentIndex(const RoadSegment * seg)const
{
int index = -1;
std::vector<RoadSegment *>::const_iterator it = std::find(roadSegments.begin(), roadSegments.end(), seg);
if (it != roadSegments.end()) {
index = std::distance(roadSegments.begin(), it);
}
return index;
}
const Node* Link::getToNode() const
{
return toNode;
}
void Link::setToNode(Node *toNode)
{
this->toNode = toNode;
}
unsigned int Link::getToNodeId() const
{
return toNodeId;
}
void Link::setToNodeId(unsigned int toNodeId)
{
this->toNodeId = toNodeId;
}
double Link::getLength() const
{
return length;
}
void Link::addRoadSegment(RoadSegment *roadSegment)
{
this->roadSegments.push_back(roadSegment);
}
void Link::calculateLength()
{
if(length == 0)
{
for (int i = 0; i < roadSegments.size(); ++i)
{
length += roadSegments.at(i)->getLength();
}
}
}
| 18.167832 | 143 | 0.684373 | [
"vector"
] |
fe4d81085c3b3cc3af1cdac33bf82aa907ba78c9 | 25,620 | cpp | C++ | src/qt/qtbase/tests/auto/corelib/tools/qset/tst_qset.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | src/qt/qtbase/tests/auto/corelib/tools/qset/tst_qset.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/tests/auto/corelib/tools/qset/tst_qset.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
//#define QT_STRICT_ITERATORS
#include <QtTest/QtTest>
#include <qset.h>
#include <qdebug.h>
int toNumber(const QString &str)
{
int res = 0;
for (int i = 0; i < str.length(); ++i)
res = (res * 10) + str[i].digitValue();
return res;
}
class tst_QSet : public QObject
{
Q_OBJECT
private slots:
void operator_eq();
void swap();
void size();
void capacity();
void reserve();
void squeeze();
void detach();
void isDetached();
void clear();
void remove();
void contains();
void containsSet();
void begin();
void end();
void insert();
void reverseIterators();
void setOperations();
void stlIterator();
void stlMutableIterator();
void javaIterator();
void javaMutableIterator();
void makeSureTheComfortFunctionsCompile();
void initializerList();
void qhash();
void intersects();
};
struct IdentityTracker {
int value, id;
};
inline uint qHash(IdentityTracker key) { return qHash(key.value); }
inline bool operator==(IdentityTracker lhs, IdentityTracker rhs) { return lhs.value == rhs.value; }
void tst_QSet::operator_eq()
{
{
QSet<int> set1, set2;
QVERIFY(set1 == set2);
QVERIFY(!(set1 != set2));
set1.insert(1);
QVERIFY(set1 != set2);
QVERIFY(!(set1 == set2));
set2.insert(1);
QVERIFY(set1 == set2);
QVERIFY(!(set1 != set2));
set2.insert(1);
QVERIFY(set1 == set2);
QVERIFY(!(set1 != set2));
set1.insert(2);
QVERIFY(set1 != set2);
QVERIFY(!(set1 == set2));
}
{
QSet<QString> set1, set2;
QVERIFY(set1 == set2);
QVERIFY(!(set1 != set2));
set1.insert("one");
QVERIFY(set1 != set2);
QVERIFY(!(set1 == set2));
set2.insert("one");
QVERIFY(set1 == set2);
QVERIFY(!(set1 != set2));
set2.insert("one");
QVERIFY(set1 == set2);
QVERIFY(!(set1 != set2));
set1.insert("two");
QVERIFY(set1 != set2);
QVERIFY(!(set1 == set2));
}
{
QSet<QString> a;
QSet<QString> b;
a += "otto";
b += "willy";
QVERIFY(a != b);
QVERIFY(!(a == b));
}
{
QSet<int> s1, s2;
s1.reserve(100);
s2.reserve(4);
QVERIFY(s1 == s2);
s1 << 100 << 200 << 300 << 400;
s2 << 400 << 300 << 200 << 100;
QVERIFY(s1 == s2);
}
}
void tst_QSet::swap()
{
QSet<int> s1, s2;
s1.insert(1);
s2.insert(2);
s1.swap(s2);
QCOMPARE(*s1.begin(),2);
QCOMPARE(*s2.begin(),1);
}
void tst_QSet::size()
{
QSet<int> set;
QVERIFY(set.size() == 0);
QVERIFY(set.isEmpty());
QVERIFY(set.count() == set.size());
QVERIFY(set.isEmpty() == set.empty());
set.insert(1);
QVERIFY(set.size() == 1);
QVERIFY(!set.isEmpty());
QVERIFY(set.count() == set.size());
QVERIFY(set.isEmpty() == set.empty());
set.insert(1);
QVERIFY(set.size() == 1);
QVERIFY(!set.isEmpty());
QVERIFY(set.count() == set.size());
QVERIFY(set.isEmpty() == set.empty());
set.insert(2);
QVERIFY(set.size() == 2);
QVERIFY(!set.isEmpty());
QVERIFY(set.count() == set.size());
QVERIFY(set.isEmpty() == set.empty());
set.remove(1);
QVERIFY(set.size() == 1);
QVERIFY(!set.isEmpty());
QVERIFY(set.count() == set.size());
QVERIFY(set.isEmpty() == set.empty());
set.remove(1);
QVERIFY(set.size() == 1);
QVERIFY(!set.isEmpty());
QVERIFY(set.count() == set.size());
QVERIFY(set.isEmpty() == set.empty());
set.remove(2);
QVERIFY(set.size() == 0);
QVERIFY(set.isEmpty());
QVERIFY(set.count() == set.size());
QVERIFY(set.isEmpty() == set.empty());
}
void tst_QSet::capacity()
{
QSet<int> set;
int n = set.capacity();
QVERIFY(n == 0);
for (int i = 0; i < 1000; ++i) {
set.insert(i);
QVERIFY(set.capacity() >= set.size());
}
}
void tst_QSet::reserve()
{
QSet<int> set;
int n = set.capacity();
QVERIFY(n == 0);
set.reserve(1000);
QVERIFY(set.capacity() >= 1000);
for (int i = 0; i < 500; ++i)
set.insert(i);
QVERIFY(set.capacity() >= 1000);
for (int j = 0; j < 500; ++j)
set.remove(j);
QVERIFY(set.capacity() >= 1000);
set.clear();
QVERIFY(set.capacity() == 0);
}
void tst_QSet::squeeze()
{
QSet<int> set;
int n = set.capacity();
QVERIFY(n == 0);
set.reserve(1000);
QVERIFY(set.capacity() >= 1000);
set.squeeze();
QVERIFY(set.capacity() < 100);
for (int i = 0; i < 500; ++i)
set.insert(i);
QVERIFY(set.capacity() >= 500 && set.capacity() < 10000);
set.reserve(50000);
QVERIFY(set.capacity() >= 50000);
set.squeeze();
QVERIFY(set.capacity() < 500);
set.remove(499);
QVERIFY(set.capacity() < 500);
set.insert(499);
QVERIFY(set.capacity() >= 500);
for (int i = 0; i < 500; ++i)
set.remove(i);
set.squeeze();
QVERIFY(set.capacity() < 100);
}
void tst_QSet::detach()
{
QSet<int> set;
set.detach();
set.insert(1);
set.insert(2);
set.detach();
QSet<int> copy = set;
set.detach();
}
void tst_QSet::isDetached()
{
QSet<int> set1, set2;
QVERIFY(!set1.isDetached()); // shared_null
QVERIFY(!set2.isDetached()); // shared_null
set1.insert(1);
QVERIFY(set1.isDetached());
QVERIFY(!set2.isDetached()); // shared_null
set2 = set1;
QVERIFY(!set1.isDetached());
QVERIFY(!set2.isDetached());
set1.detach();
QVERIFY(set1.isDetached());
QVERIFY(set2.isDetached());
}
void tst_QSet::clear()
{
QSet<QString> set1, set2;
QVERIFY(set1.size() == 0);
set1.clear();
QVERIFY(set1.size() == 0);
set1.insert("foo");
QVERIFY(set1.size() != 0);
set2 = set1;
set1.clear();
QVERIFY(set1.size() == 0);
QVERIFY(set2.size() != 0);
set2.clear();
QVERIFY(set1.size() == 0);
QVERIFY(set2.size() == 0);
}
void tst_QSet::remove()
{
QSet<QString> set1;
for (int i = 0; i < 500; ++i)
set1.insert(QString::number(i));
QCOMPARE(set1.size(), 500);
for (int j = 0; j < 500; ++j) {
set1.remove(QString::number((j * 17) % 500));
QCOMPARE(set1.size(), 500 - j - 1);
}
}
void tst_QSet::contains()
{
QSet<QString> set1;
for (int i = 0; i < 500; ++i) {
QVERIFY(!set1.contains(QString::number(i)));
set1.insert(QString::number(i));
QVERIFY(set1.contains(QString::number(i)));
}
QCOMPARE(set1.size(), 500);
for (int j = 0; j < 500; ++j) {
int i = (j * 17) % 500;
QVERIFY(set1.contains(QString::number(i)));
set1.remove(QString::number(i));
QVERIFY(!set1.contains(QString::number(i)));
}
}
void tst_QSet::containsSet()
{
QSet<QString> set1;
QSet<QString> set2;
// empty set contains the empty set
QVERIFY(set1.contains(set2));
for (int i = 0; i < 500; ++i) {
set1.insert(QString::number(i));
set2.insert(QString::number(i));
}
QVERIFY(set1.contains(set2));
set2.remove(QString::number(19));
set2.remove(QString::number(82));
set2.remove(QString::number(7));
QVERIFY(set1.contains(set2));
set1.remove(QString::number(23));
QVERIFY(!set1.contains(set2));
// filled set contains the empty set as well
QSet<QString> set3;
QVERIFY(set1.contains(set3));
// the empty set doesn't contain a filled set
QVERIFY(!set3.contains(set1));
// verify const signature
const QSet<QString> set4;
QVERIFY(set3.contains(set4));
}
void tst_QSet::begin()
{
QSet<int> set1;
QSet<int> set2 = set1;
{
QSet<int>::const_iterator i = set1.constBegin();
QSet<int>::const_iterator j = set1.cbegin();
QSet<int>::const_iterator k = set2.constBegin();
QSet<int>::const_iterator ell = set2.cbegin();
QVERIFY(i == j);
QVERIFY(k == ell);
QVERIFY(i == k);
QVERIFY(j == ell);
}
set1.insert(44);
{
QSet<int>::const_iterator i = set1.constBegin();
QSet<int>::const_iterator j = set1.cbegin();
QSet<int>::const_iterator k = set2.constBegin();
QSet<int>::const_iterator ell = set2.cbegin();
QVERIFY(i == j);
QVERIFY(k == ell);
QVERIFY(i != k);
QVERIFY(j != ell);
}
set2 = set1;
{
QSet<int>::const_iterator i = set1.constBegin();
QSet<int>::const_iterator j = set1.cbegin();
QSet<int>::const_iterator k = set2.constBegin();
QSet<int>::const_iterator ell = set2.cbegin();
QVERIFY(i == j);
QVERIFY(k == ell);
QVERIFY(i == k);
QVERIFY(j == ell);
}
}
void tst_QSet::end()
{
QSet<int> set1;
QSet<int> set2 = set1;
{
QSet<int>::const_iterator i = set1.constEnd();
QSet<int>::const_iterator j = set1.cend();
QSet<int>::const_iterator k = set2.constEnd();
QSet<int>::const_iterator ell = set2.cend();
QVERIFY(i == j);
QVERIFY(k == ell);
QVERIFY(i == k);
QVERIFY(j == ell);
QVERIFY(set1.constBegin() == set1.constEnd());
QVERIFY(set2.constBegin() == set2.constEnd());
}
set1.insert(44);
{
QSet<int>::const_iterator i = set1.constEnd();
QSet<int>::const_iterator j = set1.cend();
QSet<int>::const_iterator k = set2.constEnd();
QSet<int>::const_iterator ell = set2.cend();
QVERIFY(i == j);
QVERIFY(k == ell);
QVERIFY(i != k);
QVERIFY(j != ell);
QVERIFY(set1.constBegin() != set1.constEnd());
QVERIFY(set2.constBegin() == set2.constEnd());
}
set2 = set1;
{
QSet<int>::const_iterator i = set1.constEnd();
QSet<int>::const_iterator j = set1.cend();
QSet<int>::const_iterator k = set2.constEnd();
QSet<int>::const_iterator ell = set2.cend();
QVERIFY(i == j);
QVERIFY(k == ell);
QVERIFY(i == k);
QVERIFY(j == ell);
QVERIFY(set1.constBegin() != set1.constEnd());
QVERIFY(set2.constBegin() != set2.constEnd());
}
set1.clear();
set2.clear();
QVERIFY(set1.constBegin() == set1.constEnd());
QVERIFY(set2.constBegin() == set2.constEnd());
}
void tst_QSet::insert()
{
{
QSet<int> set1;
QVERIFY(set1.size() == 0);
set1.insert(1);
QVERIFY(set1.size() == 1);
set1.insert(2);
QVERIFY(set1.size() == 2);
set1.insert(2);
QVERIFY(set1.size() == 2);
QVERIFY(set1.contains(2));
set1.remove(2);
QVERIFY(set1.size() == 1);
QVERIFY(!set1.contains(2));
set1.insert(2);
QVERIFY(set1.size() == 2);
QVERIFY(set1.contains(2));
}
{
QSet<int> set1;
QVERIFY(set1.size() == 0);
set1 << 1;
QVERIFY(set1.size() == 1);
set1 << 2;
QVERIFY(set1.size() == 2);
set1 << 2;
QVERIFY(set1.size() == 2);
QVERIFY(set1.contains(2));
set1.remove(2);
QVERIFY(set1.size() == 1);
QVERIFY(!set1.contains(2));
set1 << 2;
QVERIFY(set1.size() == 2);
QVERIFY(set1.contains(2));
}
{
QSet<IdentityTracker> set;
QCOMPARE(set.size(), 0);
const int dummy = -1;
IdentityTracker id00 = {0, 0}, id01 = {0, 1}, searchKey = {0, dummy};
QCOMPARE(set.insert(id00)->id, id00.id);
QCOMPARE(set.size(), 1);
QCOMPARE(set.insert(id01)->id, id00.id); // first inserted is kept
QCOMPARE(set.size(), 1);
QCOMPARE(set.find(searchKey)->id, id00.id);
}
}
void tst_QSet::reverseIterators()
{
QSet<int> s;
s << 1 << 17 << 61 << 127 << 911;
std::vector<int> v(s.begin(), s.end());
std::reverse(v.begin(), v.end());
const QSet<int> &cs = s;
QVERIFY(std::equal(v.begin(), v.end(), s.rbegin()));
QVERIFY(std::equal(v.begin(), v.end(), s.crbegin()));
QVERIFY(std::equal(v.begin(), v.end(), cs.rbegin()));
QVERIFY(std::equal(s.rbegin(), s.rend(), v.begin()));
QVERIFY(std::equal(s.crbegin(), s.crend(), v.begin()));
QVERIFY(std::equal(cs.rbegin(), cs.rend(), v.begin()));
}
void tst_QSet::setOperations()
{
QSet<QString> set1, set2;
set1 << "alpha" << "beta" << "gamma" << "delta" << "zeta" << "omega";
set2 << "beta" << "gamma" << "delta" << "epsilon" << "iota" << "omega";
QSet<QString> set3 = set1;
set3.unite(set2);
QVERIFY(set3.size() == 8);
QVERIFY(set3.contains("alpha"));
QVERIFY(set3.contains("beta"));
QVERIFY(set3.contains("gamma"));
QVERIFY(set3.contains("delta"));
QVERIFY(set3.contains("epsilon"));
QVERIFY(set3.contains("zeta"));
QVERIFY(set3.contains("iota"));
QVERIFY(set3.contains("omega"));
QSet<QString> set4 = set2;
set4.unite(set1);
QVERIFY(set4.size() == 8);
QVERIFY(set4.contains("alpha"));
QVERIFY(set4.contains("beta"));
QVERIFY(set4.contains("gamma"));
QVERIFY(set4.contains("delta"));
QVERIFY(set4.contains("epsilon"));
QVERIFY(set4.contains("zeta"));
QVERIFY(set4.contains("iota"));
QVERIFY(set4.contains("omega"));
QVERIFY(set3 == set4);
QSet<QString> set5 = set1;
set5.intersect(set2);
QVERIFY(set5.size() == 4);
QVERIFY(set5.contains("beta"));
QVERIFY(set5.contains("gamma"));
QVERIFY(set5.contains("delta"));
QVERIFY(set5.contains("omega"));
QSet<QString> set6 = set2;
set6.intersect(set1);
QVERIFY(set6.size() == 4);
QVERIFY(set6.contains("beta"));
QVERIFY(set6.contains("gamma"));
QVERIFY(set6.contains("delta"));
QVERIFY(set6.contains("omega"));
QVERIFY(set5 == set6);
QSet<QString> set7 = set1;
set7.subtract(set2);
QVERIFY(set7.size() == 2);
QVERIFY(set7.contains("alpha"));
QVERIFY(set7.contains("zeta"));
QSet<QString> set8 = set2;
set8.subtract(set1);
QVERIFY(set8.size() == 2);
QVERIFY(set8.contains("epsilon"));
QVERIFY(set8.contains("iota"));
QSet<QString> set9 = set1 | set2;
QVERIFY(set9 == set3);
QSet<QString> set10 = set1 & set2;
QVERIFY(set10 == set5);
QSet<QString> set11 = set1 + set2;
QVERIFY(set11 == set3);
QSet<QString> set12 = set1 - set2;
QVERIFY(set12 == set7);
QSet<QString> set13 = set2 - set1;
QVERIFY(set13 == set8);
QSet<QString> set14 = set1;
set14 |= set2;
QVERIFY(set14 == set3);
QSet<QString> set15 = set1;
set15 &= set2;
QVERIFY(set15 == set5);
QSet<QString> set16 = set1;
set16 += set2;
QVERIFY(set16 == set3);
QSet<QString> set17 = set1;
set17 -= set2;
QVERIFY(set17 == set7);
QSet<QString> set18 = set2;
set18 -= set1;
QVERIFY(set18 == set8);
}
void tst_QSet::stlIterator()
{
QSet<QString> set1;
for (int i = 0; i < 25000; ++i)
set1.insert(QString::number(i));
{
int sum = 0;
QSet<QString>::const_iterator i = set1.begin();
while (i != set1.end()) {
sum += toNumber(*i);
++i;
}
QVERIFY(sum == 24999 * 25000 / 2);
}
{
int sum = 0;
QSet<QString>::const_iterator i = set1.end();
while (i != set1.begin()) {
--i;
sum += toNumber(*i);
}
QVERIFY(sum == 24999 * 25000 / 2);
}
}
void tst_QSet::stlMutableIterator()
{
QSet<QString> set1;
for (int i = 0; i < 25000; ++i)
set1.insert(QString::number(i));
{
int sum = 0;
QSet<QString>::iterator i = set1.begin();
while (i != set1.end()) {
sum += toNumber(*i);
++i;
}
QVERIFY(sum == 24999 * 25000 / 2);
}
{
int sum = 0;
QSet<QString>::iterator i = set1.end();
while (i != set1.begin()) {
--i;
sum += toNumber(*i);
}
QVERIFY(sum == 24999 * 25000 / 2);
}
{
QSet<QString> set2 = set1;
QSet<QString> set3 = set2;
QSet<QString>::iterator i = set2.begin();
QSet<QString>::iterator j = set3.begin();
while (i != set2.end()) {
i = set2.erase(i);
}
QVERIFY(set2.isEmpty());
QVERIFY(!set3.isEmpty());
j = set3.end();
while (j != set3.begin()) {
j--;
if (j + 1 != set3.end())
set3.erase(j + 1);
}
if (set3.begin() != set3.end())
set3.erase(set3.begin());
QVERIFY(set2.isEmpty());
QVERIFY(set3.isEmpty());
// #if QT_VERSION >= 0x050000
// i = set2.insert("foo");
// #else
QSet<QString>::const_iterator k = set2.insert("foo");
i = reinterpret_cast<QSet<QString>::iterator &>(k);
// #endif
QVERIFY(*i == "foo");
}
}
void tst_QSet::javaIterator()
{
QSet<QString> set1;
for (int k = 0; k < 25000; ++k)
set1.insert(QString::number(k));
{
int sum = 0;
QSetIterator<QString> i(set1);
while (i.hasNext())
sum += toNumber(i.next());
QVERIFY(sum == 24999 * 25000 / 2);
}
{
int sum = 0;
QSetIterator<QString> i(set1);
while (i.hasNext()) {
sum += toNumber(i.peekNext());
i.next();
}
QVERIFY(sum == 24999 * 25000 / 2);
}
{
int sum = 0;
QSetIterator<QString> i(set1);
while (i.hasNext()) {
i.next();
sum += toNumber(i.peekPrevious());
}
QVERIFY(sum == 24999 * 25000 / 2);
}
{
int sum = 0;
QSetIterator<QString> i(set1);
i.toBack();
while (i.hasPrevious())
sum += toNumber(i.previous());
QVERIFY(sum == 24999 * 25000 / 2);
}
{
int sum = 0;
QSetIterator<QString> i(set1);
i.toBack();
while (i.hasPrevious()) {
sum += toNumber(i.peekPrevious());
i.previous();
}
QVERIFY(sum == 24999 * 25000 / 2);
}
{
int sum = 0;
QSetIterator<QString> i(set1);
i.toBack();
while (i.hasPrevious()) {
i.previous();
sum += toNumber(i.peekNext());
}
QVERIFY(sum == 24999 * 25000 / 2);
}
int sum1 = 0;
int sum2 = 0;
QSetIterator<QString> i(set1);
QSetIterator<QString> j(set1);
int n = 0;
while (i.hasNext()) {
QVERIFY(j.hasNext());
set1.remove(i.peekNext());
sum1 += toNumber(i.next());
sum2 += toNumber(j.next());
++n;
}
QVERIFY(!j.hasNext());
QVERIFY(sum1 == 24999 * 25000 / 2);
QVERIFY(sum2 == sum1);
QVERIFY(set1.isEmpty());
}
void tst_QSet::javaMutableIterator()
{
QSet<QString> set1;
for (int k = 0; k < 25000; ++k)
set1.insert(QString::number(k));
{
int sum = 0;
QMutableSetIterator<QString> i(set1);
while (i.hasNext())
sum += toNumber(i.next());
QVERIFY(sum == 24999 * 25000 / 2);
}
{
int sum = 0;
QMutableSetIterator<QString> i(set1);
while (i.hasNext()) {
i.next();
sum += toNumber(i.value());
}
QVERIFY(sum == 24999 * 25000 / 2);
}
{
int sum = 0;
QMutableSetIterator<QString> i(set1);
while (i.hasNext()) {
sum += toNumber(i.peekNext());
i.next();
}
QVERIFY(sum == 24999 * 25000 / 2);
}
{
int sum = 0;
QMutableSetIterator<QString> i(set1);
while (i.hasNext()) {
i.next();
sum += toNumber(i.peekPrevious());
}
QVERIFY(sum == 24999 * 25000 / 2);
}
{
int sum = 0;
QMutableSetIterator<QString> i(set1);
i.toBack();
while (i.hasPrevious())
sum += toNumber(i.previous());
QVERIFY(sum == 24999 * 25000 / 2);
}
{
int sum = 0;
QMutableSetIterator<QString> i(set1);
i.toBack();
while (i.hasPrevious()) {
sum += toNumber(i.peekPrevious());
i.previous();
}
QVERIFY(sum == 24999 * 25000 / 2);
}
{
int sum = 0;
QMutableSetIterator<QString> i(set1);
i.toBack();
while (i.hasPrevious()) {
i.previous();
sum += toNumber(i.peekNext());
}
QVERIFY(sum == 24999 * 25000 / 2);
}
{
QSet<QString> set2 = set1;
QSet<QString> set3 = set2;
QMutableSetIterator<QString> i(set2);
QMutableSetIterator<QString> j(set3);
while (i.hasNext()) {
i.next();
i.remove();
}
QVERIFY(set2.isEmpty());
QVERIFY(!set3.isEmpty());
j.toBack();
while (j.hasPrevious()) {
j.previous();
j.remove();
}
QVERIFY(set2.isEmpty());
QVERIFY(set3.isEmpty());
}
}
void tst_QSet::makeSureTheComfortFunctionsCompile()
{
QSet<int> set1, set2, set3;
set1 << 5;
set1 |= set2;
set1 |= 5;
set1 &= set2;
set1 &= 5;
set1 += set2;
set1 += 5;
set1 -= set2;
set1 -= 5;
set1 = set2 | set3;
set1 = set2 & set3;
set1 = set2 + set3;
set1 = set2 - set3;
}
void tst_QSet::initializerList()
{
#ifdef Q_COMPILER_INITIALIZER_LISTS
QSet<int> set = {1, 1, 2, 3, 4, 5};
QCOMPARE(set.count(), 5);
QVERIFY(set.contains(1));
QVERIFY(set.contains(2));
QVERIFY(set.contains(3));
QVERIFY(set.contains(4));
QVERIFY(set.contains(5));
// check _which_ of the equal elements gets inserted (in the QHash/QMap case, it's the last):
const QSet<IdentityTracker> set2 = {{1, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
QCOMPARE(set2.count(), 5);
const int dummy = -1;
const IdentityTracker searchKey = {1, dummy};
QCOMPARE(set2.find(searchKey)->id, 0);
QSet<int> emptySet{};
QVERIFY(emptySet.isEmpty());
QSet<int> set3{{}, {}, {}};
QVERIFY(!set3.isEmpty());
#else
QSKIP("Compiler doesn't support initializer lists");
#endif
}
void tst_QSet::qhash()
{
//
// check that sets containing the same elements hash to the same value
//
{
// create some deterministic initial state:
qSetGlobalQHashSeed(0);
QSet<int> s1;
s1.reserve(4);
s1 << 400 << 300 << 200 << 100;
// also change the seed:
qSetGlobalQHashSeed(0x10101010);
QSet<int> s2;
s2.reserve(100); // provoke different bucket counts
s2 << 100 << 200 << 300 << 400; // and insert elements in different order, too
QVERIFY(s1.capacity() != s2.capacity());
QCOMPARE(s1, s2);
QVERIFY(!std::equal(s1.cbegin(), s1.cend(), s2.cbegin())); // verify that the order _is_ different
QCOMPARE(qHash(s1), qHash(s2));
}
//
// check that sets of sets work:
//
{
#ifdef Q_COMPILER_INITIALIZER_LISTS
QSet<QSet<int> > intSetSet = { { 0, 1, 2 }, { 0, 1 }, { 1, 2 } };
#else
QSet<QSet<int> > intSetSet;
QSet<int> intSet01, intSet12;
intSet01 << 0 << 1;
intSet12 << 1 << 2;
intSetSet << intSet01 << intSet12 << (intSet01|intSet12);
#endif
QCOMPARE(intSetSet.size(), 3);
}
}
void tst_QSet::intersects()
{
QSet<int> s1;
QSet<int> s2;
QVERIFY(!s1.intersects(s1));
QVERIFY(!s1.intersects(s2));
s1 << 100;
QVERIFY(s1.intersects(s1));
QVERIFY(!s1.intersects(s2));
s2 << 200;
QVERIFY(!s1.intersects(s2));
s1 << 200;
QVERIFY(s1.intersects(s2));
qSetGlobalQHashSeed(0x10101010);
QSet<int> s3;
s3 << 500;
QVERIFY(!s1.intersects(s3));
s3 << 200;
QVERIFY(s1.intersects(s3));
}
QTEST_APPLESS_MAIN(tst_QSet)
#include "tst_qset.moc"
| 24.147031 | 106 | 0.535051 | [
"vector"
] |
fe4fbc89fdac6274b5b4d08497c6c99067f1dbb3 | 827 | cpp | C++ | 307.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | 8 | 2018-10-31T11:00:19.000Z | 2020-07-31T05:25:06.000Z | 307.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | null | null | null | 307.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | 2 | 2018-05-31T11:29:22.000Z | 2019-09-11T06:34:40.000Z | class NumArray {
public:
vector<int> pre;
vector<int> cop;
vector<int> c;
NumArray(vector<int> nums) {
if(nums.size()==0) return;
pre.push_back(nums[0]);
cop.push_back(nums[0]);
c.push_back(0);
for(int i=1;i<nums.size();i++){
c.push_back(0);
cop.push_back(nums[i]);
pre.push_back(pre[i-1]+nums[i]);
}
}
void update(int i, int val) {
c[i]=val-cop[i];
}
int sumRange(int i, int j) {
int ret;
if(i==0) ret=pre[j];
else ret=pre[j]-pre[i-1];
for(int k=i;k<=j;k++) ret+=c[k];
return ret;
}
};
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* obj.update(i,val);
* int param_2 = obj.sumRange(i,j);
*/
| 22.351351 | 64 | 0.511487 | [
"object",
"vector"
] |
fe516001fbfdc93e39f298088b101745cc795674 | 171 | cpp | C++ | src/domain/model/remote-account/RemoteAccount.cpp | agiledragon/transfer-money | 7656bf8803afe6545b1461e493e1b1995fe6d1e2 | [
"MIT"
] | 11 | 2019-06-20T11:56:35.000Z | 2021-05-26T16:03:50.000Z | src/domain/model/remote-account/RemoteAccount.cpp | agiledragon/transfer-money | 7656bf8803afe6545b1461e493e1b1995fe6d1e2 | [
"MIT"
] | null | null | null | src/domain/model/remote-account/RemoteAccount.cpp | agiledragon/transfer-money | 7656bf8803afe6545b1461e493e1b1995fe6d1e2 | [
"MIT"
] | 4 | 2019-08-25T12:35:34.000Z | 2022-03-26T20:06:06.000Z | #include <domain/model/remote-account/RemoteAccount.h>
RemoteAccount::RemoteAccount(const std::string& accountId)
: AggregateRoot(accountId), AccountInfo(accountId)
{
}
| 21.375 | 58 | 0.795322 | [
"model"
] |
fe525dc9cb72b69a872ecd4784bcf67c6adb2106 | 18,907 | cpp | C++ | src/app.cpp | cainiaoDJ/netplus | 03350d507830b3a39620374225d16c0b57623ef1 | [
"MIT"
] | null | null | null | src/app.cpp | cainiaoDJ/netplus | 03350d507830b3a39620374225d16c0b57623ef1 | [
"MIT"
] | null | null | null | src/app.cpp | cainiaoDJ/netplus | 03350d507830b3a39620374225d16c0b57623ef1 | [
"MIT"
] | null | null | null | #include <signal.h>
#include <netp/CPUID.hpp>
#include <netp/logger_broker.hpp>
#include <netp/io_event_loop.hpp>
#include <netp/dns_resolver.hpp>
#include <netp/socket.hpp>
#include <netp/logger/console_logger.hpp>
#include <netp/logger/file_logger.hpp>
#include <netp/os/api_wrapper.hpp>
#include <netp/signal_broker.hpp>
#include <netp/security/crc.hpp>
#include <netp/security/fletcher.hpp>
#include <netp/benchmark.hpp>
#ifdef _NETP_WIN
#include <netp/os/winsock_helper.hpp>
#endif
#include <netp/app.hpp>
namespace netp {
NRP<netp::signal_broker> g_sigbroker;
static void signal_broker_init() {
NETP_ASSERT(g_sigbroker == nullptr);
g_sigbroker = netp::make_ref<netp::signal_broker>();
}
static void signal_broker_deinit() {
NETP_ASSERT(g_sigbroker != nullptr);
g_sigbroker = nullptr;
}
static void signal_void(int) {}
static void signal_from_system(int signo) {
NETP_ASSERT(g_sigbroker != nullptr);
g_sigbroker->signal_raise(signo);
}
i64_t signal_register(int signo, netp::fn_signal_handler_t&& H) {
if (H == nullptr) {
NETP_WARN("[signal_broker]register_signal, ignore: %d", signo);
::signal(signo, SIG_IGN);
return -1;
}
::signal(signo, &signal_from_system);
return g_sigbroker->bind(signo, std::forward<netp::fn_signal_handler_t>(H));
}
void signal_unregister(int signo, i64_t handle_id) {
::signal(signo, &signal_void);
g_sigbroker->unbind(handle_id);
}
app::app(app_cfg const& cfg) :
m_should_exit(false),
m_cfg(cfg),
m_app_startup_prev(cfg.app_startup_prev),
m_app_startup_post(cfg.app_startup_post),
m_app_exit_prev(cfg.app_exit_prev),
m_app_exit_post(cfg.app_exit_post),
m_app_event_loop_init_prev(cfg.app_event_loop_init_prev),
m_app_event_loop_init_post(cfg.app_event_loop_init_post),
m_app_event_loop_deinit_prev(cfg.app_event_loop_deinit_prev),
m_app_event_loop_deinit_post(cfg.app_event_loop_deinit_post)
{
if (m_app_startup_prev) {
m_app_startup_prev();
}
_startup();
if (m_app_startup_post ) {
m_app_startup_post();
}
}
app::~app()
{
if (m_app_exit_prev ) {
m_app_exit_prev();
}
_exit();
if (m_app_exit_post ) {
m_app_exit_post();
}
}
void app::_init() {
__log_init();
#ifdef _NETP_DEBUG
dump_arch_info();
#endif
#ifdef NETP_DEBUG_OBJECT_SIZE
__dump_sizeof();
#endif
NRP<app_test_unit> apptest = netp::make_ref<app_test_unit>();
if (!apptest->run()) {
NETP_INFO("apptest failed");
exit(-2);
}
__signal_init();
__net_init();
}
void app::_deinit() {
__net_deinit();
__signal_deinit();
__log_deinit();
}
void app::__log_init() {
netp::logger_broker::instance()->init();
#ifdef NETP_ENABLE_CONSOLE_LOGGER
NRP<logger::console_logger> clg = netp::make_ref <logger::console_logger>();
clg->set_mask_by_level(NETP_CONSOLE_LOGGER_LEVEL);
netp::logger_broker::instance()->add(clg);
#endif
string_t logfilepath = "./netp.log";
if (m_cfg.logfilepathname.length()) {
logfilepath = netp::string_t(m_cfg.logfilepathname.c_str());
}
NRP<logger::file_logger> filelogger = netp::make_ref<netp::logger::file_logger>(logfilepath);
filelogger->set_mask_by_level(NETP_FILE_LOGGER_LEVEL);
netp::logger_broker::instance()->add(filelogger);
#ifdef NETP_ENABLE_ANDROID_LOG
NRP<android_log_print> alp = netp::make_ref<android_log_print>();
alp->set_mask_by_level(NETP_CONSOLE_LOGGER_LEVEL);
__android_log_print(ANDROID_LOG_INFO, "[NETP]", "add android_log_print done");
netp::logger_broker::instance()->add(alp);
#endif
}
void app::__log_deinit() {
netp::logger_broker::instance()->deinit();
}
void app::_startup() {
static_assert(sizeof(netp::i8_t) == 1, "assert sizeof(i8_t) failed");
static_assert(sizeof(netp::u8_t) == 1, "assert sizeof(u8_t) failed");
static_assert(sizeof(netp::i16_t) == 2, "assert sizeof(i16_t) failed");
static_assert(sizeof(netp::u16_t) == 2, "assert sizeof(u16_t) failed");
static_assert(sizeof(netp::i32_t) == 4, "assert sizeof(i32_t) failed");
static_assert(sizeof(netp::u32_t) == 4, "assert sizeof(u32_t) failed");
static_assert(sizeof(netp::i64_t) == 8, "assert sizeof(i64_t) failed");
static_assert(sizeof(netp::u64_t) == 8, "assert sizeof(u64_t) failed");
#if __NETP_IS_BIG_ENDIAN
static_assert(netp::is_big_endian())
#endif
#ifdef _NETP_WIN
//CPU ia-64 is big endian, but windows run on a little endian mode on ia-64
static_assert(!(__NETP_IS_BIG_ENDIAN), "windows always run on little endian");
NETP_ASSERT(netp::is_little_endian());
#endif
netp::random_init_seed();
netp::tls_create< netp::impl::thread_data>();
#ifdef NETP_MEMORY_USE_TLS_POOL
netp::global_pool_aligned_allocator::instance();
netp::tls_create<netp::pool_aligned_allocator_t>();
#endif
#if defined(_DEBUG_MUTEX) || defined(_DEBUG_SHARED_MUTEX)
//for mutex/lock deubg
netp::tls_create<netp::mutex_set_t>();
#endif
_init();
}
void app::_exit() {
_deinit();
#if defined(_DEBUG_MUTEX) || defined(_DEBUG_SHARED_MUTEX)
tls_destroy<mutex_set_t>();
#endif
netp::tls_destroy< netp::impl::thread_data>();
#ifdef NETP_MEMORY_USE_TLS_POOL
netp::tls_destroy< netp::pool_aligned_allocator_t>();
netp::global_pool_aligned_allocator::instance()->destroy_instance();
#endif
}
void app::dump_arch_info() {
std::string arch_info = "";
arch_info += "vender: " + netp::CPUID::Vendor() + "\n";
arch_info += "brand: " + netp::CPUID::Brand() + "\n";
arch_info += "instructions:";
auto support_message = [](std::string& archinfo, const char* isa_feature, bool is_supported) {
if (is_supported) {
archinfo += std::string(" ") + isa_feature ;
}
};
support_message(arch_info, "3DNOW", netp::CPUID::_3DNOW());
support_message(arch_info, "3DNOWEXT", netp::CPUID::_3DNOWEXT());
support_message(arch_info, "ABM", netp::CPUID::ABM());
support_message(arch_info, "ADX", netp::CPUID::ADX());
support_message(arch_info, "AES", netp::CPUID::AES());
support_message(arch_info, "AVX", netp::CPUID::AVX());
support_message(arch_info, "AVX2", netp::CPUID::AVX2());
support_message(arch_info, "AVX512CD", netp::CPUID::AVX512CD());
support_message(arch_info, "AVX512ER", netp::CPUID::AVX512ER());
support_message(arch_info, "AVX512F", netp::CPUID::AVX512F());
support_message(arch_info, "AVX512PF", netp::CPUID::AVX512PF());
support_message(arch_info, "BMI1", netp::CPUID::BMI1());
support_message(arch_info, "BMI2", netp::CPUID::BMI2());
support_message(arch_info, "CLFSH", netp::CPUID::CLFSH());
support_message(arch_info, "CMPXCHG16B", netp::CPUID::CMPXCHG16B());
support_message(arch_info, "CX8", netp::CPUID::CX8());
support_message(arch_info, "ERMS", netp::CPUID::ERMS());
support_message(arch_info, "F16C", netp::CPUID::F16C());
support_message(arch_info, "FMA", netp::CPUID::FMA());
support_message(arch_info, "FSGSBASE", netp::CPUID::FSGSBASE());
support_message(arch_info, "FXSR", netp::CPUID::FXSR());
support_message(arch_info, "HLE", netp::CPUID::HLE());
support_message(arch_info, "INVPCID", netp::CPUID::INVPCID());
support_message(arch_info, "LAHF", netp::CPUID::LAHF());
support_message(arch_info, "LZCNT", netp::CPUID::LZCNT());
support_message(arch_info, "MMX", netp::CPUID::MMX());
support_message(arch_info, "MMXEXT", netp::CPUID::MMXEXT());
support_message(arch_info, "MONITOR", netp::CPUID::MONITOR());
support_message(arch_info, "MOVBE", netp::CPUID::MOVBE());
support_message(arch_info, "MSR", netp::CPUID::MSR());
support_message(arch_info, "OSXSAVE", netp::CPUID::OSXSAVE());
support_message(arch_info, "PCLMULQDQ", netp::CPUID::PCLMULQDQ());
support_message(arch_info, "POPCNT", netp::CPUID::POPCNT());
support_message(arch_info, "PREFETCHWT1", netp::CPUID::PREFETCHWT1());
support_message(arch_info, "RDRAND", netp::CPUID::RDRAND());
support_message(arch_info, "RDSEED", netp::CPUID::RDSEED());
support_message(arch_info, "RDTSCP", netp::CPUID::RDTSCP());
support_message(arch_info, "RTM", netp::CPUID::RTM());
support_message(arch_info, "SEP", netp::CPUID::SEP());
support_message(arch_info, "SHA", netp::CPUID::SHA());
support_message(arch_info, "SSE", netp::CPUID::SSE());
support_message(arch_info, "SSE2", netp::CPUID::SSE2());
support_message(arch_info, "SSE3", netp::CPUID::SSE3());
support_message(arch_info, "SSSE3", netp::CPUID::SSSE3());
support_message(arch_info, "SSE4.1", netp::CPUID::SSE41());
support_message(arch_info, "SSE4.2", netp::CPUID::SSE42());
support_message(arch_info, "SSE4a", netp::CPUID::SSE4a());
support_message(arch_info, "SYSCALL", netp::CPUID::SYSCALL());
support_message(arch_info, "TBM", netp::CPUID::TBM());
support_message(arch_info, "XOP", netp::CPUID::XOP());
support_message(arch_info, "XSAVE", netp::CPUID::XSAVE());
support_message(arch_info, "NEON", netp::CPUID::NEON());
NETP_INFO("ARCH INFO: %s\n", arch_info.c_str());
NETP_INFO("alignof(std::max_align_t): %d\n", alignof(std::max_align_t) );
}
#if defined(NETP_DEBUG_OBJECT_SIZE)
void app::__dump_sizeof() {
NETP_INFO("sizeof(void*): %u", sizeof(void*));
NETP_INFO("sizeof(std::atomic<long>): %u", sizeof(std::atomic<long>));
NETP_INFO("sizeof(netp::__atomic_counter): %u", sizeof(netp::__atomic_counter));
NETP_INFO("sizeof(netp::__non_atomic_counter): %u", sizeof(netp::__non_atomic_counter));
NETP_INFO("sizeof(netp::ref_base): %u", sizeof(netp::ref_base));
NETP_INFO("sizeof(netp::non_atomic_ref_base): %u", sizeof(netp::non_atomic_ref_base));
NETP_INFO("sizeof(netp::packet): %u", sizeof(netp::packet));
NETP_INFO("sizeof(ref_ptr<netp::packet>): %u", sizeof(NRP<netp::packet>));
NETP_INFO("sizeof(address): %u", sizeof(netp::address));
NETP_INFO("sizeof(netp::channel): %u", sizeof(netp::channel));
NETP_INFO("sizeof(netp::io_ctx): %u", sizeof(netp::io_ctx));
NETP_INFO("sizeof(netp::fn_io_event_t): %u", sizeof(netp::fn_io_event_t));
NETP_INFO("sizeof(std::function<void(int)>): %u", sizeof(std::function<void(int)>));
NETP_INFO("sizeof(std::function<void(int, int)>): %u", sizeof(std::function<void(int, int)>));
NETP_INFO("sizeof(std::deque<socket_outbound_entry, netp::allocator<socket_outbound_entry>>): %u", sizeof(std::deque<socket_outbound_entry, netp::allocator<socket_outbound_entry>>));
NETP_INFO("sizeof(netp::socket): %u", sizeof(netp::socket_channel));
NETP_INFO("sizeof(std::vector<int>): %u", sizeof(std::vector<int>));
NETP_INFO("sizeof(std::vector<std::function<void(int)>): %u", sizeof(std::vector<std::function<void(int)>>));
NETP_INFO("sizeof(std::vector<std::function<void(int, int)>>): %u", sizeof(std::vector<std::function<void(int, int)>>));
NETP_INFO("sizeof(netp::promise<int>): %u", sizeof(netp::promise<int>));
NETP_INFO("sizeof(netp::promise<tuple<int,NRP<socket>>>): %u", sizeof(netp::promise<std::tuple<int, NRP<netp::socket_channel>>>));
NETP_INFO("sizeof(netp::event_broker_promise): %u", sizeof(netp::event_broker_promise<int>));
NETP_INFO("sizeof(netp::spin_mutex): %u", sizeof(netp::spin_mutex));
NETP_INFO("sizeof(netp::mutex): %u", sizeof(netp::mutex));
NETP_INFO("sizeof(netp::condition): %u", sizeof(netp::condition));
NETP_INFO("sizeof(std::condition_variable): %u", sizeof(std::condition_variable));
NETP_INFO("sizeof(netp::condition_any): %u", sizeof(netp::condition_any));
NETP_INFO("sizeof(std::condition_variable_any): %u", sizeof(std::condition_variable_any));
}
#endif
void app::__signal_init() {
netp::unique_lock<netp::mutex> ulk(m_mutex);
signal_broker_init();
#if defined(_NETP_GNU_LINUX) || defined(_NETP_ANDROID) || defined(_NETP_APPLE)
signal_register(SIGPIPE, nullptr);
#endif
i64_t id_int =signal_register(SIGINT, std::bind(&app::handle_signal, this, std::placeholders::_1));
if (id_int > 0) {
m_signo_tuple_vec.push_back(std::make_tuple(SIGINT, id_int));
}
i64_t id_term = signal_register(SIGTERM, std::bind(&app::handle_signal, this, std::placeholders::_1));
if (id_term > 0) {
m_signo_tuple_vec.push_back(std::make_tuple(SIGTERM, id_term));
}
}
void app::__signal_deinit() {
netp::unique_lock<netp::mutex> ulk(m_mutex);
while (m_signo_tuple_vec.size()) {
std::tuple<int, i64_t>& pair = m_signo_tuple_vec.back();
signal_unregister(std::get<0>(pair), std::get<1>(pair));
m_signo_tuple_vec.pop_back();
}
signal_broker_deinit();
NETP_INFO("deinit signal end");
}
void app::__net_init() {
NETP_INFO("net init begin");
#ifdef _NETP_WIN
netp::os::winsock_init();
#endif
if (m_app_event_loop_init_prev) {
m_app_event_loop_init_prev();
}
___event_loop_init();
if (m_app_event_loop_init_post) {
m_app_event_loop_init_post();
}
NETP_INFO("net init end");
}
void app::__net_deinit() {
NETP_INFO("net deinit begin");
if (m_app_event_loop_deinit_prev) {
m_app_event_loop_deinit_prev();
}
___event_loop_deinit();
if (m_app_event_loop_deinit_post) {
m_app_event_loop_deinit_post();
}
#ifdef _NETP_WIN
netp::os::winsock_deinit();
#endif
NETP_INFO("net deinit end");
}
void app::___event_loop_init() {
netp::io_event_loop_group::instance()->init(m_cfg.poller_count, m_cfg.event_loop_cfgs);
NETP_INFO("[app]init loop done");
#ifdef _NETP_WIN
if (m_cfg.dnsnses.size() == 0) {
vector_ipv4_t dnslist;
netp::os::get_local_dns_server_list(dnslist);
for (std::size_t i = 0; i < dnslist.size(); ++i) {
NETP_INFO("[app]add dns: %s", netp::ipv4todotip(dnslist[i]).c_str());
m_cfg.dnsnses.push_back( std::string(netp::ipv4todotip(dnslist[i]).c_str()));
}
}
if (m_cfg.dnsnses.size() == 0) {
NETP_ERR("[app]no dns nameserver");
}
#endif
netp::dns_resolver::instance()->reset(io_event_loop_group::instance()->internal_next());
if (m_cfg.dnsnses.size()) {
netp::dns_resolver::instance()->add_name_server(m_cfg.dnsnses);
}
NRP<netp::promise<int>> dnsp = netp::dns_resolver::instance()->start();
if (dnsp->get() != netp::OK) {
NETP_ERR("[app]start dnsresolver failed: %d, exit", dnsp->get());
_exit();
exit(dnsp->get());
}
NETP_INFO("[app]init dns done");
}
void app::___event_loop_deinit() {
netp::dns_resolver::instance()->stop();
//reset loop after all loop reference dattached from business code
netp::io_event_loop_group::instance()->deinit();
netp::dns_resolver::instance()->reset(nullptr);
netp::dns_resolver::destroy_instance();
}
//ISSUE: if the waken thread is main thread, we would get stuck here
void app::handle_signal(int signo) {
netp::unique_lock<netp::mutex> ulk(m_mutex);
//NETP_ASSERT(false);
NETP_INFO("[APP]receive signo: %d", signo);
m_cond.notify_one();
#if defined(_NETP_GNU_LINUX) || defined(_NETP_ANDROID) || defined(_NETP_APPLE)
if (signo == SIGPIPE) {
return;//IGN
}
#endif
switch (signo) {
case SIGINT:
case SIGTERM:
{
m_should_exit = true;
}
break;
}
}
bool app::should_exit() const {
return m_should_exit;
}
void app_test_unit::test_memory() {
NRP<packet>* p = netp::allocator<NRP<packet>>::make();
netp::allocator<NRP<packet>>::trash(p);
NRP<packet>* pn = netp::allocator<NRP<packet>>::make_array(10);
netp::allocator<NRP<packet>>::trash_array(pn,10);
u8_t* u8ptr = netp::allocator<u8_t>::malloc(14, 16);
netp::allocator<u8_t>::free(u8ptr);
}
void app_test_unit::test_packet() {
{
NRP<netp::packet> p = netp::make_ref<netp::packet>();
for (size_t i = 0; i <= 1024 * 1024*2; ++i) {
p->write<u8_t>(u8_t(1));
}
NRP<netp::packet> p2 = netp::make_ref<netp::packet>();
for (size_t i = 0; i <= 1024 * 1024*2; ++i) {
p2->write_left<u8_t>(u8_t(1));
}
NETP_ASSERT(*p == *p2);
}
NRP<netp::packet> tmp = netp::make_ref<netp::packet>(1024 * 1024);
}
#ifdef _NETP_DEBUG
#define POOL_CACHE_MAX_SIZE (16*1024)
#else
#define POOL_CACHE_MAX_SIZE (64*1024)
#endif
template <class vec_T, size_t size_max>
void test_vector_pushback(size_t loop) {
for (size_t k = 0; k < loop; ++k) {
vec_T vector_int;
for (size_t i = 0; i < size_max; ++i) {
//NETP_INFO("vec.capacity(): %u", vector_int.capacity());
vector_int.push_back(i);
}
}
}
struct __nonpod :
public netp::non_atomic_ref_base
{};
template <class vec_T, size_t size_max>
void test_vector_pushback_nonpod(size_t loop) {
for (size_t k = 0; k < loop; ++k) {
vec_T vector_int;
for (size_t i = 0; i < size_max; ++i) {
//NETP_INFO("vec.capacity(): %u", vector_int.capacity());
vector_int.push_back(netp::make_ref<__nonpod>());
}
}
}
void app_test_unit::test_netp_allocator(size_t loop) {
{
netp::benchmark mk("std::vector<size_t,netp::allocator<size_t>");
test_vector_pushback<std::vector<size_t,netp::allocator<size_t>>, POOL_CACHE_MAX_SIZE>(loop);
}
{
netp::benchmark mk("std::vector<size_t,netp::allocator<size_t>");
test_vector_pushback<std::vector<size_t,netp::allocator<size_t>>, POOL_CACHE_MAX_SIZE>(loop);
}
{
netp::benchmark mk("std::vector<NRP<__nonpod>,netp::allocator<NRP<__nonpod>>");
test_vector_pushback_nonpod<std::vector<NRP<__nonpod>, netp::allocator<NRP<__nonpod>>>, POOL_CACHE_MAX_SIZE>(loop);
}
{
netp::benchmark mk("std::vector<NRP<__nonpod>,netp::allocator<NRP<__nonpod>>");
test_vector_pushback_nonpod<std::vector<NRP<__nonpod>, netp::allocator<NRP<__nonpod>>>, POOL_CACHE_MAX_SIZE>(loop);
}
}
void app_test_unit::test_std_allocator(size_t loop) {
{
netp::benchmark mk("std::vector<size_t,std::allocator<size_t>");
test_vector_pushback<std::vector<size_t, std::allocator<size_t>>, POOL_CACHE_MAX_SIZE>(loop);
}
{
netp::benchmark mk("std::vector<size_t,std::allocator<size_t>");
test_vector_pushback<std::vector<size_t, std::allocator<size_t>>, POOL_CACHE_MAX_SIZE>(loop);
}
{
netp::benchmark mk("std::vector<NRP<__nonpod>,std::allocator<NRP<__nonpod>>");
test_vector_pushback_nonpod<std::vector<NRP<__nonpod>, std::allocator<NRP<__nonpod>>>, POOL_CACHE_MAX_SIZE>(loop);
}
{
netp::benchmark mk("std::vector<NRP<__nonpod>,std::allocator<NRP<__nonpod>>");
test_vector_pushback_nonpod<std::vector<NRP<__nonpod>, std::allocator<NRP<__nonpod>>>, POOL_CACHE_MAX_SIZE>(loop);
}
}
void app_test_unit::benchmark_hash() {
int total = 100000;
NRP<netp::packet> p = netp::make_ref<netp::packet>();
for (int j = 0; j < 1500; ++j) {
p->write<byte_t>(j%10);
}
{
netp::benchmark mk("f16");
for (int i = 0; i < total; ++i) {
volatile u16_t h1 = netp::security::fletcher16((const uint8_t*)p->head(), p->len());
}
}
{
netp::benchmark mk("crc16");
for (int i = 0; i < total; ++i) {
volatile u16_t h2 = netp::security::crc16(p->head(), p->len());
}
}
{
NETP_INFO("crc16: %u", netp::security::crc16(p->head(), p->len()));
}
}
bool app_test_unit::run() {
test_memory();
test_packet();
size_t loop = 2;
#ifdef _NETP_DEBUG
loop = 1;
#endif
test_netp_allocator(loop);
test_std_allocator(loop);
#ifdef _NETP_DEBUG
benchmark_hash();
#endif
return true;
}
} | 32.711073 | 184 | 0.696832 | [
"vector"
] |
fe530b683481daa9fb70f64321e223b9c2706300 | 4,278 | hpp | C++ | src/support/DP_functions.hpp | apeterson91/rndpp | b1e2c5a440a4e403abd5f2801296d84264e8922f | [
"MIT"
] | 1 | 2020-08-04T13:27:05.000Z | 2020-08-04T13:27:05.000Z | src/support/DP_functions.hpp | apeterson91/rndpp | b1e2c5a440a4e403abd5f2801296d84264e8922f | [
"MIT"
] | 3 | 2020-08-27T21:01:12.000Z | 2020-09-10T21:54:59.000Z | src/support/DP_functions.hpp | apeterson91/bendr | b1e2c5a440a4e403abd5f2801296d84264e8922f | [
"MIT"
] | null | null | null | #include "beta_rng.hpp"
Eigen::ArrayXXd initialize_mu(const int& L, const int& K, const double& mu_0,
const double& kappa_0, std::mt19937& rng){
Eigen::ArrayXXd out(L,K);
std::normal_distribution<double> rnorm(mu_0,sqrt(kappa_0));
for(int l = 0; l < L; l ++){
for( int k = 0; k < K; k ++)
out(l,k) = rnorm(rng);
}
return(out);
}
Eigen::ArrayXXd initialize_tau(const int &L, const int &K, const double &sigma_0, const int &nu_0){
Eigen::ArrayXXd out(L,K);
for(int l = 0; l < L; l ++){
for(int k = 0; k < K; k++)
out(l,k) = (sigma_0 * nu_0) / R::rchisq(nu_0);
}
return(out);
}
//' returns stick breaking atoms (not weights) for a vector with constant beta parameters alpha, beta across all vector elements
//' @param n length of vector
//' @param alpha
Eigen::ArrayXd stick_break(const int& n, const double& alpha, const double& beta, std::mt19937& rng){
Eigen::ArrayXd v(n);
sftrabbit::beta_distribution<> rbeta(alpha,beta);
for(int i = 0; i < (n-1); i++)
v(i) = rbeta(rng);
v(n-1) = 1;
return(v);
}
//' stick breaking atoms (not weights) for a vector with alpha fixed at 1 and constant beta across vector elements
//' @param n length of vector
//' @param beta parameter for stick breaking process
//' @param rng random number generator engine
Eigen::ArrayXd stick_break(const int n,const double beta, std::mt19937& rng){
Eigen::ArrayXd v(n);
sftrabbit::beta_distribution<> rbeta(1,beta);
for(int i = 0; i < (n-1); i++)
v(i) = rbeta(rng);
v(n-1) = 1;
return(v);
}
//' stick breaking atoms (not weights) for a vector with alpha,beta variable across vector elements
//' n length of vector
//' alpha vector of alpha parameters for posterior beta distribution
//' beta vector of beta parameters for posterior beta distribution
Eigen::ArrayXd stick_break(const int n, Eigen::ArrayXd& alpha,Eigen::ArrayXd& beta, std::mt19937& rng){
Eigen::ArrayXd v(n);
v = Eigen::ArrayXd::Zero(n);
Eigen::ArrayXd w(n);
w = Eigen::ArrayXd::Zero(n);
for(int i = 0; i < (n-1); i++){
sftrabbit::beta_distribution<> rbeta(alpha(i),beta(i));
v(i) = rbeta(rng);
}
v(n-1) = 1;
return(v);
}
//' stick breaking atoms (not weights) for a vector with constant alpha (1) and beta across atoms - returns a matrix of size L x K
//' @param
Eigen::ArrayXXd stick_break(const int& rows, const int& cols, const double& beta, std::mt19937& rng){
Eigen::ArrayXXd out(rows,cols);
sftrabbit::beta_distribution<> rbeta(1,beta);
for(int row_ix = 0; row_ix < rows; row_ix ++){
for(int col_ix = 0; col_ix < cols; col_ix ++)
out(row_ix,col_ix) = row_ix == (rows-1) ? 1.0 : rbeta(rng);
}
return(out);
}
//' stick breaking
Eigen::ArrayXXd stick_break(Eigen::ArrayXXd& alpha, Eigen::ArrayXXd& beta, std::mt19937& rng){
const int rows = alpha.rows();
const int cols = alpha.cols();
Eigen::ArrayXXd out(rows,cols);
for(int row_ix = 0; row_ix < rows; row_ix ++){
for(int col_ix = 0; col_ix < cols; col_ix ++){
sftrabbit::beta_distribution<> rbeta(alpha(row_ix,col_ix),beta(row_ix,col_ix));
out(row_ix,col_ix) = row_ix == (rows-1) ? 1.0 : rbeta(rng);
}
}
return(out);
}
Eigen::ArrayXd stick_break_weights(const int n, Eigen::ArrayXd& v){
Eigen::ArrayXd w(n);
for(int i = 0; i < (n-1); i++)
w(i) = i == 0 ? v(i) : v(i) * (Eigen::ArrayXd::Ones(i) - v.head(i)).prod();
w(n-1) = v(n-1) * (1 - v.head(n-1)).prod();
return(w);
}
Eigen::ArrayXd stick_break_weights(Eigen::ArrayXd& v){
const int n = v.rows();
Eigen::ArrayXd w(n);
for(int i = 0; i < (n-1); i++)
w(i) = i == 0 ? v(i) : v(i) * (1 - v.head(i)).prod();
w(n-1) = v(n-1) * (1 - v.head(n-1)).prod();
return(w);
}
Eigen::ArrayXXd stick_break_weights(Eigen::ArrayXXd& u){
const int rows = u.rows();
const int cols = u.cols();
Eigen::ArrayXXd w(rows,cols);
for(int col_ix = 0; col_ix < cols; col_ix ++){
for(int row_ix = 0; row_ix < rows ; row_ix ++)
w(row_ix,col_ix) = row_ix == 0 ? u(row_ix,col_ix) : u(row_ix,col_ix) * (1 - u.block(0,col_ix,row_ix,1)).prod();
}
return(w);
}
| 30.126761 | 130 | 0.602852 | [
"vector"
] |
fe540044a0330b0977b3f45ed4edad9e3c6c90d1 | 3,402 | cxx | C++ | Filters/Core/Testing/Cxx/TestResampleWithDataSet2.cxx | inviCRO/VTK | a2dc2e79d4ecb8f6da900535b32e1a2a702c7f48 | [
"BSD-3-Clause"
] | null | null | null | Filters/Core/Testing/Cxx/TestResampleWithDataSet2.cxx | inviCRO/VTK | a2dc2e79d4ecb8f6da900535b32e1a2a702c7f48 | [
"BSD-3-Clause"
] | null | null | null | Filters/Core/Testing/Cxx/TestResampleWithDataSet2.cxx | inviCRO/VTK | a2dc2e79d4ecb8f6da900535b32e1a2a702c7f48 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Visualization Toolkit
Module: TestResampleWithDataset2.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkResampleWithDataSet.h"
#include "vtkActor.h"
#include "vtkArrayCalculator.h"
#include "vtkCamera.h"
#include "vtkContourFilter.h"
#include "vtkDataSet.h"
#include "vtkExodusIIReader.h"
#include "vtkImageData.h"
#include "vtkPointData.h"
#include "vtkPolyDataMapper.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkTestUtilities.h"
enum
{
TEST_PASSED_RETVAL = 0,
TEST_FAILED_RETVAL = 1
};
int TestResampleWithDataSet2(int argc, char *argv[])
{
vtkNew<vtkExodusIIReader> reader;
char *fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/can.ex2");
reader->SetFileName(fname);
delete [] fname;
reader->UpdateInformation();
reader->SetObjectArrayStatus(vtkExodusIIReader::NODAL, "VEL", 1);
reader->Update();
// based on can.ex2 bounds
double origin[3] = {-7.8, -1.0, -15};
double spacing[3] = {0.127, 0.072, 0.084};
int dims[3] = { 128, 128, 128 };
vtkNew<vtkImageData> input;
input->SetExtent(0, dims[0] - 1, 0, dims[1] - 1, 0, dims[2] - 1);
input->SetOrigin(origin);
input->SetSpacing(spacing);
vtkNew<vtkResampleWithDataSet> resample;
resample->SetInputData(input.GetPointer());
resample->SetSourceConnection(reader->GetOutputPort());
resample->UpdateTimeStep(0.00199999);
vtkDataSet *result = static_cast<vtkDataSet*>(resample->GetOutput());
// Render
vtkNew<vtkContourFilter> toPoly;
toPoly->SetInputData(result);
toPoly->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS,
"vtkValidPointMask");
toPoly->SetValue(0, 0.5);
vtkNew<vtkArrayCalculator> calculator;
calculator->SetInputConnection(toPoly->GetOutputPort());
calculator->AddVectorArrayName("VEL");
calculator->SetFunction("mag(VEL)");
calculator->SetResultArrayName("VEL_MAG");
calculator->Update();
double range[2];
calculator->GetOutput()->GetPointData()->GetArray("VEL_MAG")->GetRange(range);
vtkNew<vtkPolyDataMapper> mapper;
mapper->SetInputConnection(calculator->GetOutputPort());
mapper->SetScalarRange(range);
vtkNew<vtkActor> actor;
actor->SetMapper(mapper.GetPointer());
vtkNew<vtkRenderer> renderer;
renderer->AddActor(actor.GetPointer());
renderer->GetActiveCamera()->SetPosition(0.0, -1.0, 0.0);
renderer->GetActiveCamera()->SetViewUp(0.0, 0.0, 1.0);
renderer->ResetCamera();
vtkNew<vtkRenderWindow> renWin;
renWin->AddRenderer(renderer.GetPointer());
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow(renWin.GetPointer());
iren->Initialize();
renWin->Render();
int retVal = vtkRegressionTestImage(renWin.GetPointer());
if (retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
return !retVal;
}
| 29.076923 | 82 | 0.692828 | [
"render"
] |
fe548d7b7fb90bb99f79630f63a1cdca798dbcda | 5,577 | cpp | C++ | aws-cpp-sdk-elasticmapreduce/source/model/InstanceFleet.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-elasticmapreduce/source/model/InstanceFleet.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-elasticmapreduce/source/model/InstanceFleet.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/elasticmapreduce/model/InstanceFleet.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace EMR
{
namespace Model
{
InstanceFleet::InstanceFleet() :
m_idHasBeenSet(false),
m_nameHasBeenSet(false),
m_statusHasBeenSet(false),
m_instanceFleetType(InstanceFleetType::NOT_SET),
m_instanceFleetTypeHasBeenSet(false),
m_targetOnDemandCapacity(0),
m_targetOnDemandCapacityHasBeenSet(false),
m_targetSpotCapacity(0),
m_targetSpotCapacityHasBeenSet(false),
m_provisionedOnDemandCapacity(0),
m_provisionedOnDemandCapacityHasBeenSet(false),
m_provisionedSpotCapacity(0),
m_provisionedSpotCapacityHasBeenSet(false),
m_instanceTypeSpecificationsHasBeenSet(false),
m_launchSpecificationsHasBeenSet(false)
{
}
InstanceFleet::InstanceFleet(JsonView jsonValue) :
m_idHasBeenSet(false),
m_nameHasBeenSet(false),
m_statusHasBeenSet(false),
m_instanceFleetType(InstanceFleetType::NOT_SET),
m_instanceFleetTypeHasBeenSet(false),
m_targetOnDemandCapacity(0),
m_targetOnDemandCapacityHasBeenSet(false),
m_targetSpotCapacity(0),
m_targetSpotCapacityHasBeenSet(false),
m_provisionedOnDemandCapacity(0),
m_provisionedOnDemandCapacityHasBeenSet(false),
m_provisionedSpotCapacity(0),
m_provisionedSpotCapacityHasBeenSet(false),
m_instanceTypeSpecificationsHasBeenSet(false),
m_launchSpecificationsHasBeenSet(false)
{
*this = jsonValue;
}
InstanceFleet& InstanceFleet::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Id"))
{
m_id = jsonValue.GetString("Id");
m_idHasBeenSet = true;
}
if(jsonValue.ValueExists("Name"))
{
m_name = jsonValue.GetString("Name");
m_nameHasBeenSet = true;
}
if(jsonValue.ValueExists("Status"))
{
m_status = jsonValue.GetObject("Status");
m_statusHasBeenSet = true;
}
if(jsonValue.ValueExists("InstanceFleetType"))
{
m_instanceFleetType = InstanceFleetTypeMapper::GetInstanceFleetTypeForName(jsonValue.GetString("InstanceFleetType"));
m_instanceFleetTypeHasBeenSet = true;
}
if(jsonValue.ValueExists("TargetOnDemandCapacity"))
{
m_targetOnDemandCapacity = jsonValue.GetInteger("TargetOnDemandCapacity");
m_targetOnDemandCapacityHasBeenSet = true;
}
if(jsonValue.ValueExists("TargetSpotCapacity"))
{
m_targetSpotCapacity = jsonValue.GetInteger("TargetSpotCapacity");
m_targetSpotCapacityHasBeenSet = true;
}
if(jsonValue.ValueExists("ProvisionedOnDemandCapacity"))
{
m_provisionedOnDemandCapacity = jsonValue.GetInteger("ProvisionedOnDemandCapacity");
m_provisionedOnDemandCapacityHasBeenSet = true;
}
if(jsonValue.ValueExists("ProvisionedSpotCapacity"))
{
m_provisionedSpotCapacity = jsonValue.GetInteger("ProvisionedSpotCapacity");
m_provisionedSpotCapacityHasBeenSet = true;
}
if(jsonValue.ValueExists("InstanceTypeSpecifications"))
{
Array<JsonView> instanceTypeSpecificationsJsonList = jsonValue.GetArray("InstanceTypeSpecifications");
for(unsigned instanceTypeSpecificationsIndex = 0; instanceTypeSpecificationsIndex < instanceTypeSpecificationsJsonList.GetLength(); ++instanceTypeSpecificationsIndex)
{
m_instanceTypeSpecifications.push_back(instanceTypeSpecificationsJsonList[instanceTypeSpecificationsIndex].AsObject());
}
m_instanceTypeSpecificationsHasBeenSet = true;
}
if(jsonValue.ValueExists("LaunchSpecifications"))
{
m_launchSpecifications = jsonValue.GetObject("LaunchSpecifications");
m_launchSpecificationsHasBeenSet = true;
}
return *this;
}
JsonValue InstanceFleet::Jsonize() const
{
JsonValue payload;
if(m_idHasBeenSet)
{
payload.WithString("Id", m_id);
}
if(m_nameHasBeenSet)
{
payload.WithString("Name", m_name);
}
if(m_statusHasBeenSet)
{
payload.WithObject("Status", m_status.Jsonize());
}
if(m_instanceFleetTypeHasBeenSet)
{
payload.WithString("InstanceFleetType", InstanceFleetTypeMapper::GetNameForInstanceFleetType(m_instanceFleetType));
}
if(m_targetOnDemandCapacityHasBeenSet)
{
payload.WithInteger("TargetOnDemandCapacity", m_targetOnDemandCapacity);
}
if(m_targetSpotCapacityHasBeenSet)
{
payload.WithInteger("TargetSpotCapacity", m_targetSpotCapacity);
}
if(m_provisionedOnDemandCapacityHasBeenSet)
{
payload.WithInteger("ProvisionedOnDemandCapacity", m_provisionedOnDemandCapacity);
}
if(m_provisionedSpotCapacityHasBeenSet)
{
payload.WithInteger("ProvisionedSpotCapacity", m_provisionedSpotCapacity);
}
if(m_instanceTypeSpecificationsHasBeenSet)
{
Array<JsonValue> instanceTypeSpecificationsJsonList(m_instanceTypeSpecifications.size());
for(unsigned instanceTypeSpecificationsIndex = 0; instanceTypeSpecificationsIndex < instanceTypeSpecificationsJsonList.GetLength(); ++instanceTypeSpecificationsIndex)
{
instanceTypeSpecificationsJsonList[instanceTypeSpecificationsIndex].AsObject(m_instanceTypeSpecifications[instanceTypeSpecificationsIndex].Jsonize());
}
payload.WithArray("InstanceTypeSpecifications", std::move(instanceTypeSpecificationsJsonList));
}
if(m_launchSpecificationsHasBeenSet)
{
payload.WithObject("LaunchSpecifications", m_launchSpecifications.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace EMR
} // namespace Aws
| 26.306604 | 170 | 0.772996 | [
"model"
] |
fe5a70e436016e778a53d1c9c85cbcdf9f5aa226 | 4,748 | hpp | C++ | include/bohrium/jitk/graph.hpp | bh107/bohrium | 5b83e7117285fefc7779ed0e9acb0f8e74c7e068 | [
"Apache-2.0"
] | 236 | 2015-03-31T15:39:30.000Z | 2022-03-24T01:43:14.000Z | include/bohrium/jitk/graph.hpp | bh107/bohrium | 5b83e7117285fefc7779ed0e9acb0f8e74c7e068 | [
"Apache-2.0"
] | 324 | 2015-05-27T10:35:38.000Z | 2021-12-10T07:34:10.000Z | include/bohrium/jitk/graph.hpp | bh107/bohrium | 5b83e7117285fefc7779ed0e9acb0f8e74c7e068 | [
"Apache-2.0"
] | 41 | 2015-05-26T12:38:42.000Z | 2022-01-10T15:16:37.000Z | /*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <set>
#include <vector>
#include <string>
#include <bohrium/jitk/block.hpp>
#include <bohrium/bh_instruction.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/foreach.hpp>
namespace bohrium {
namespace jitk {
namespace graph {
//The type declaration of the boost graphs, vertices and edges.
typedef boost::adjacency_list<boost::setS, boost::vecS, boost::bidirectionalS, Block> DAG;
typedef typename boost::graph_traits<DAG>::edge_descriptor Edge;
typedef uint64_t Vertex;
// Validate the 'dag'
bool validate(DAG &dag);
/* Merge vertices 'a' and 'b' (in that order) into 'a'
* If 'remove_b==false' than the 'b' vertex is only cleared not removed from graph 'dag'.
* NB: 'a' and 'b' MUST be fusible
*
* 'min_threading' is the minimum amount of threading acceptable in the merged block (ignored if
* neither 'a' or 'b' have the requested amount)
*
* Complexity: O(V)
*
*/
void merge_vertices(DAG &dag, Vertex a, Vertex b, const bool remove_b=true);
/* Transitive reduce the 'dag', i.e. remove all redundant edges,
*
* Complexity: O(E * (E + V))
*
*/
void transitive_reduction(DAG &dag);
// Merge pendant vertices that are system only
void merge_system_pendants(DAG &dag);
// Pretty print the DAG. A "-<id>.dot" is append the filename. Set `id` to -1 for a default unique id
void pprint(const DAG &dag, const char *filename, bool avoid_rank0_sweep, int id=-1);
// Create a dag based on the 'block_list'
DAG from_block_list(const std::vector <Block> &block_list);
// Create a block list based on the 'dag'
std::vector<Block> fill_block_list(const DAG &dag);
// Merges the vertices in 'dag' topologically using 'Queue' as the Vertex queue.
// 'Queue' is a collection of 'Vertex' that is constructed with the DAG and supports push(), pop(), and empty()
// 'avoid_rank0_sweep' will avoid fusion of sweeped and non-sweeped blocks at the root level
template <typename Queue>
std::vector<Block> topological(DAG &dag, bool avoid_rank0_sweep) {
using namespace std;
vector<Block> ret;
Queue roots(dag); // The root vertices
// Initiate 'roots'
BOOST_FOREACH (Vertex v, boost::vertices(dag)) {
if (boost::in_degree(v, dag) == 0) {
roots.push(v);
}
}
// Each iteration creates a new block
while (not roots.empty()) {
const Vertex vertex = roots.pop();
ret.emplace_back(dag[vertex]);
Block &block = ret.back();
// Add adjacent vertices and remove the block from 'dag'
BOOST_FOREACH (const Vertex v, boost::adjacent_vertices(vertex, dag)) {
if (boost::in_degree(v, dag) <= 1) {
roots.push(v);
}
}
boost::clear_vertex(vertex, dag);
// Instruction blocks should never be merged
if (block.isInstr()) {
continue;
}
// Roots not fusible with 'block'
Queue nonfusible_roots(dag);
// Search for fusible blocks within the root blocks
while (not roots.empty()) {
const Vertex v = roots.pop();
if (!dag[v].isInstr() and mergeable(block, dag[v], avoid_rank0_sweep)) {
block = reshape_and_merge(block.getLoop(), dag[v].getLoop());
assert(block.validation());
// Add adjacent vertices and remove the block 'b' from 'dag'
BOOST_FOREACH (const Vertex adj, boost::adjacent_vertices(v, dag)) {
if (boost::in_degree(adj, dag) <= 1) {
roots.push(adj);
}
}
boost::clear_vertex(v, dag);
} else {
nonfusible_roots.push(v);
}
}
roots = std::move(nonfusible_roots);
}
return ret;
}
// Merges the vertices in 'dag' greedily.
// 'avoid_rank0_sweep' will avoid fusion of sweeped and non-sweeped blocks at the root level
void greedy(DAG &dag, bool avoid_rank0_sweep);
} // graph
} // jit
} // bohrium
| 33.202797 | 111 | 0.657751 | [
"vector"
] |
fe5b936edaeb4f8652296025f1a51a6aface0138 | 1,213 | cpp | C++ | plugins/d3d9/src/state/core/rasterizer/make_states.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | plugins/d3d9/src/state/core/rasterizer/make_states.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | plugins/d3d9/src/state/core/rasterizer/make_states.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sge/d3d9/d3dinclude.hpp>
#include <sge/d3d9/state/render.hpp>
#include <sge/d3d9/state/render_vector.hpp>
#include <sge/d3d9/state/convert/bool_to_dword.hpp>
#include <sge/d3d9/state/convert/cull_mode.hpp>
#include <sge/d3d9/state/convert/fill_mode.hpp>
#include <sge/d3d9/state/core/rasterizer/make_states.hpp>
#include <sge/renderer/state/core/rasterizer/parameters.hpp>
sge::d3d9::state::render_vector sge::d3d9::state::core::rasterizer::make_states(
sge::renderer::state::core::rasterizer::parameters const &_parameters)
{
return sge::d3d9::state::render_vector{
sge::d3d9::state::render(
D3DRS_CULLMODE, sge::d3d9::state::convert::cull_mode(_parameters.cull_mode())),
sge::d3d9::state::render(
D3DRS_FILLMODE, sge::d3d9::state::convert::fill_mode(_parameters.fill_mode())),
sge::d3d9::state::render(
D3DRS_SCISSORTESTENABLE,
sge::d3d9::state::convert::bool_to_dword(_parameters.enable_scissor_test().get()))};
}
| 44.925926 | 94 | 0.716406 | [
"render"
] |
fe5c74d497c8a5ff86dd2e08e1a99d5df7ea53cb | 48,756 | cpp | C++ | src/support_data/ossimGmlSupportData.cpp | vladislav-horbatiuk/ossim | 82417ad868fac022672335e1684bdd91d662c18c | [
"MIT"
] | 251 | 2015-10-20T09:08:11.000Z | 2022-03-22T18:16:38.000Z | src/support_data/ossimGmlSupportData.cpp | vladislav-horbatiuk/ossim | 82417ad868fac022672335e1684bdd91d662c18c | [
"MIT"
] | 73 | 2015-11-02T17:12:36.000Z | 2021-11-15T17:41:47.000Z | src/support_data/ossimGmlSupportData.cpp | vladislav-horbatiuk/ossim | 82417ad868fac022672335e1684bdd91d662c18c | [
"MIT"
] | 146 | 2015-10-15T16:00:15.000Z | 2022-03-22T12:37:14.000Z | //---
//
// License: MIT
//
// See LICENSE.txt file in the top level directory for more details.
//
// Author: David Burken
//
// Description: GML support data object.
//
//---
// $Id$
#include <ossim/support_data/ossimGmlSupportData.h>
#include <ossim/base/ossimDrect.h>
#include <ossim/base/ossimGrect.h>
#include <ossim/base/ossimIpt.h>
#include <ossim/base/ossimIrect.h>
#include <ossim/base/ossimKeywordlist.h>
#include <ossim/base/ossimKeywordNames.h>
#include <ossim/base/ossimNotify.h>
#include <ossim/base/ossimTrace.h>
#include <ossim/base/ossimXmlAttribute.h>
#include <ossim/base/ossimXmlDocument.h>
#include <ossim/base/ossimXmlNode.h>
#include <ossim/imaging/ossimImageGeometry.h>
#include <ossim/projection/ossimMapProjection.h>
#include <ossim/projection/ossimProjection.h>
#include <ossim/projection/ossimEpsgProjectionFactory.h>
#include <ossim/projection/ossimProjectionFactoryRegistry.h>
#include <ossim/projection/ossimSensorModel.h>
#include <iomanip>
#include <sstream>
using namespace std;
static ossimTrace traceDebug("ossimGmlSupportData:debug");
#define UNKNOWN_PCSCODE 32767
ossimGmlSupportData::ossimGmlSupportData()
:
m_xmlDocument(0),
// m_use_gmljp2_version2(true),
m_pcsCodeMap(UNKNOWN_PCSCODE),
m_pcsCodeGeo(UNKNOWN_PCSCODE),
m_srsNameStringMap("http://www.opengis.net/def/crs/EPSG/0/32767"),
m_srsNameStringGeo("http://www.opengis.net/def/crs/EPSG/0/32767"),
m_srsDimensionString("2"),
m_axisLabelsStringMap("X Y"),
m_axisLabelsStringGeo("Lat Long"),
m_uomLabelsStringMap("m m"),
m_uomLabelsStringGeo("deg deg")
{
}
ossimGmlSupportData::~ossimGmlSupportData()
{
}
bool ossimGmlSupportData::initialize( std::istream& in )
{
bool status = false;
if ( in.good() )
{
m_xmlDocument = new ossimXmlDocument();
m_xmlDocument->read( in );
status = true;
}
else
{
m_xmlDocument = 0;
}
return status;
}
bool ossimGmlSupportData::initialize( const ossimImageGeometry* geom,
const ossimIrect& rect )
{
static const char MODULE[] = "ossimGmlSupportData::initialize(geom)";
bool status = false;
if ( geom )
{
// ossim_uint32 code = UNKNOWN_PCSCODE; // unknown code
ossimRefPtr<const ossimMapProjection> mapProj = geom->getAsMapProjection();
if ( mapProj.valid() )
{
// Get the PCS code:
m_pcsCodeMap = mapProj->getPcsCode();
m_pcsCodeGeo = mapProj->getPcsCode();
// Create an SRS Name for the map projection
std::ostringstream os;
os << "http://www.opengis.net/def/crs/EPSG/0/" << m_pcsCodeMap;
m_srsNameStringMap = os.str();
// Create an SRS Name for the projection datum
std::ostringstream os2;
os2 << "http://www.opengis.net/def/crs/EPSG/0/" << m_pcsCodeGeo;
m_srsNameStringGeo = os2.str();
m_xmlDocument = new ossimXmlDocument(ossimFilename::NIL);
// if ( m_use_gmljp2_version2 == true )
// {
ossimRefPtr<ossimXmlNode> rootNode = getGmljp2V2RootNode();
m_xmlDocument->initRoot( rootNode );
status = configureGmljp2V2( rootNode, geom, rect );
// }
#if 0
else
{
ossimRefPtr<ossimXmlNode> rootNode = getGmljp2V1RootNode();
m_xmlDocument->initRoot( rootNode );
status = configureGmljp2V1( rootNode, geom, rect );
}
#endif
// cout << "gmljp2Node: " << *(gmljp2Node.get()) << endl;
// cout << "xmlDoc: " << *(m_xmlDocument.get()) << endl;
}
}
if ( status == false )
{
ossimNotify(ossimNotifyLevel_DEBUG)
<< MODULE << " DEBUG Entered...\n";
}
return status;
} // End: ossimGmlSupportData::initialize( geom, mapProj )
#if 0
bool ossimGmlSupportData::configureGmljp2V1( ossimRefPtr<ossimXmlNode> node0,
const ossimImageGeometry* geom )
{
bool success = true;
const ossimString BLANK = "";
ossimString gridHighString;
ossimString gridLowString;
getLimits( geom, gridHighString, gridLowString );
configureBounds( node0, geom );
ossimString path = "rectifiedGridDomain";
ossimRefPtr<ossimXmlNode> node2 = node0->addChildNode( path, BLANK );
path = "RectifiedGrid";
ossimRefPtr<ossimXmlNode> node2a = node2->addChildNode( path, BLANK );
ossimRefPtr<ossimXmlAttribute> attr1 = new ossimXmlAttribute();
ossimString name = "dimension";
ossimString value = "2";
attr1->setNameValue( name, value );
node2a->addAttribute( attr1 );
path = "limit";
ossimRefPtr<ossimXmlNode> node2a1 = node2a->addChildNode( path, BLANK );
path = "GridEnvelope";
ossimRefPtr<ossimXmlNode> node2a1a = node2a1->addChildNode( path, BLANK );
path = "low";
ossimRefPtr<ossimXmlNode> node2a1a1 = node2a1a->addChildNode( path, gridLowString );
path = "high";
ossimRefPtr<ossimXmlNode> node2a1a2 = node2a1a->addChildNode( path, gridHighString );
return success;
}
#endif
bool ossimGmlSupportData::configureGmljp2V2( ossimRefPtr<ossimXmlNode> node0,
const ossimImageGeometry* geom,
const ossimIrect& rect )
{
bool success = false;
ossimRefPtr<const ossimMapProjection> mapProj = geom->getAsMapProjection();
if ( mapProj.valid() )
{
bool isGeographic = mapProj->isGeographic();
const ossimString BLANK = "";
ossimRefPtr<ossimXmlAttribute> attr(0);
ossimString name;
ossimString value;
ossimString gridHighString;
ossimString gridLowString;
getLimits( rect, gridHighString, gridLowString );
configureBounds( node0, geom, rect );
ossimString path = "domainSet";
ossimRefPtr<ossimXmlNode> node2 =
node0->addChildNode( path, BLANK );
path = "rangeSet";
ossimRefPtr<ossimXmlNode> node3 =
node0->addChildNode( path, BLANK );
path = "File";
ossimRefPtr<ossimXmlNode> node3a =
node3->addChildNode( path, BLANK );
path = "rangeParameters";
ossimRefPtr<ossimXmlNode> node3a1 =
node3a->addChildNode( path, BLANK );
path = "fileName";
ossimRefPtr<ossimXmlNode> node3a2 =
node3a->addChildNode( path, "gmljp2://codestream" );
path = "fileStructure";
ossimRefPtr<ossimXmlNode> node3a3 =
node3a->addChildNode( path, "inapplicable" );
path = "gmlcov:rangeType";
ossimRefPtr<ossimXmlNode> node4 =
node0->addChildNode( path, BLANK );
path = "gmljp2:featureMember";
ossimRefPtr<ossimXmlNode> node5 =
node0->addChildNode( path, BLANK );
path = "gmljp2:GMLJP2RectifiedGridCoverage";
ossimRefPtr<ossimXmlNode> node5a =
node5->addChildNode( path, BLANK );
attr = new ossimXmlAttribute();
name = "gml:id";
value = "CodeStream_0";
attr->setNameValue( name, value );
node5a->addAttribute( attr );
path = "domainSet";
ossimRefPtr<ossimXmlNode> node5a1 =
node5a->addChildNode( path, BLANK );
path = "RectifiedGrid";
ossimRefPtr<ossimXmlNode> node5a1a =
node5a1->addChildNode( path, BLANK );
attr = new ossimXmlAttribute();
name = "gml:id";
value = "RG0001";
attr->setNameValue( name, value );
node5a1a->addAttribute( attr );
attr = new ossimXmlAttribute();
name = "dimension";
value = "2";
attr->setNameValue( name, value );
node5a1a->addAttribute( attr );
attr = new ossimXmlAttribute();
name = "srsName";
attr->setNameValue( name, m_srsNameStringMap );
node5a1a->addAttribute( attr );
path = "limits";
ossimRefPtr<ossimXmlNode> node5a1a1 =
node5a1a->addChildNode( path, BLANK );
path = "GridEnvelope";
ossimRefPtr<ossimXmlNode> node5a1a1a =
node5a1a1->addChildNode( path, BLANK );
path = "low";
ossimRefPtr<ossimXmlNode> node5a1a1a1 =
node5a1a1a->addChildNode( path, gridLowString );
path = "high";
ossimRefPtr<ossimXmlNode> node5a1a1a2 =
node5a1a1a->addChildNode( path, gridHighString );
path = "axisLabels";
ossimRefPtr<ossimXmlNode> node5a1a2 =
node5a1a->addChildNode( path,
mapProj->isGeographic() ?
m_axisLabelsStringGeo : m_axisLabelsStringMap );
path = "origin";
ossimRefPtr<ossimXmlNode> node5a1a3 =
node5a1a->addChildNode( path, BLANK );
path = "Point";
ossimRefPtr<ossimXmlNode> node5a1a3a =
node5a1a3->addChildNode( path, BLANK );
attr = new ossimXmlAttribute();
name = "gml:id";
value = "P0001";
attr->setNameValue( name, value );
node5a1a3a->addAttribute( attr );
attr = new ossimXmlAttribute();
name = "srsName";
attr->setNameValue( name, m_srsNameStringMap );
node5a1a3a->addAttribute( attr );
ossimString originString;
ossimString offsetVector1String;
ossimString offsetVector2String;
if ( isGeographic )
{
getGeoOrigin( geom, rect.ul(), originString,
offsetVector1String, offsetVector2String );
}
else
{
getMapOrigin( geom, rect.ul(), originString,
offsetVector1String, offsetVector2String );
}
path = "pos";
ossimRefPtr<ossimXmlNode> node5a1a3a1 =
node5a1a3a->addChildNode( path, originString );
path = "offsetVector";
ossimRefPtr<ossimXmlNode> node5a1a4 =
node5a1a->addChildNode( path, offsetVector1String );
attr = new ossimXmlAttribute();
name = "srsName";
attr->setNameValue( name,
(isGeographic ? m_srsNameStringGeo : m_srsNameStringMap ) );
node5a1a4->addAttribute( attr );
path = "offsetVector";
ossimRefPtr<ossimXmlNode> node5a1a5 =
node5a1a->addChildNode( path, offsetVector2String );
attr = new ossimXmlAttribute();
name = "srsName";
attr->setNameValue( name, (isGeographic ? m_srsNameStringGeo : m_srsNameStringMap) );
node5a1a5->addAttribute( attr );
path = "rangeSet";
ossimRefPtr<ossimXmlNode> node5a2 =
node5a->addChildNode( path, BLANK );
path = "File";
ossimRefPtr<ossimXmlNode> node5a2a =
node5a2->addChildNode( path, BLANK );
path = "rangeParameters";
ossimRefPtr<ossimXmlNode> node5a2a1 =
node5a2a->addChildNode( path, BLANK );
path = "fileName";
ossimRefPtr<ossimXmlNode> node5a2a2 =
node5a2a->addChildNode( path, "gmljp2://codestream" );
path = "fileStructure";
ossimRefPtr<ossimXmlNode> node5a2a3 =
node5a2a->addChildNode( path, "inapplicable" );
success = true;
}
return success;
}
bool ossimGmlSupportData::configureBounds(
ossimRefPtr<ossimXmlNode> node0,
const ossimImageGeometry* geom,
const ossimIrect& rect)
{
bool success = true;
const ossimString BLANK = "";
ossimString upperCornerString;
ossimString lowerCornerString;
getGeoBounds( geom, rect, upperCornerString, lowerCornerString );
ossimString path = "boundedBy";
ossimRefPtr<ossimXmlNode> node1 = node0->addChildNode( path, BLANK );
path = "Envelope";
ossimRefPtr<ossimXmlNode> node1a = node1->addChildNode( path, BLANK );
ossimRefPtr<ossimXmlAttribute> attr( 0 );
ossimString name;
attr = new ossimXmlAttribute();
name = "srsName";
attr->setNameValue( name, m_srsNameStringGeo );
node1a->addAttribute( attr );
attr = new ossimXmlAttribute();
name = "axisLabels";
attr->setNameValue( name, m_axisLabelsStringGeo );
node1a->addAttribute( attr );
attr = new ossimXmlAttribute();
name = "uomLabels";
attr->setNameValue( name, m_uomLabelsStringGeo );
node1a->addAttribute( attr );
attr = new ossimXmlAttribute();
name = "srsDimension";
attr->setNameValue( name, m_srsDimensionString );
node1a->addAttribute( attr );
path = "lowerCorner";
ossimRefPtr<ossimXmlNode> node1a1 =
node1a->addChildNode( path, lowerCornerString );
path = "upperCorner";
ossimRefPtr<ossimXmlNode> node1a2 =
node1a->addChildNode( path, upperCornerString );
return success;
}
ossimRefPtr<ossimXmlNode> ossimGmlSupportData::getGmljp2V2RootNode() const
{
ossimRefPtr<ossimXmlNode> node = new ossimXmlNode();
ossimString os = "gmljp2:GMLJP2CoverageCollection";
node->setTag( os );
ossimRefPtr<ossimXmlAttribute> attr( 0 );
ossimString name;
ossimString value;
attr = new ossimXmlAttribute();
name = "gml:id";
value = "JPEG2000_0";
attr->setNameValue( name, value );
node->addAttribute( attr );
attr = new ossimXmlAttribute();
name = "xmlns";
value = "http://www.opengis.net/gml/3.2";
attr->setNameValue( name, value );
node->addAttribute( attr );
attr = new ossimXmlAttribute();
name = "xmlns:gml";
value = "http://www.opengis.net/gml/3.2";
attr->setNameValue( name, value );
node->addAttribute( attr );
attr = new ossimXmlAttribute();
name = "xmlns:gmlcov";
value = "http://www.opengis.net/gmlcov/1.0";
attr->setNameValue( name, value );
node->addAttribute( attr );
attr = new ossimXmlAttribute();
name = "xmlns:gmljp2";
value = "http://www.opengis.net/gmljp2/2.0";
attr->setNameValue( name, value );
node->addAttribute( attr );
attr = new ossimXmlAttribute();
name = "xmlns:xsi";
value = "http://www.w3.org/2001/XMLSchema-instance";
attr->setNameValue( name, value );
node->addAttribute( attr );
attr = new ossimXmlAttribute();
name = "xsi:schemaLocation";
value = "http://www.opengis.net/gmljp2/2.0 http://schemas.opengis.net/gmljp2/2.0/gmljp2.xsd";
attr->setNameValue( name, value );
node->addAttribute( attr );
return node;
} // ossimGmlSupportData::getGmljp2V2Node()
ossimRefPtr<ossimXmlNode> ossimGmlSupportData::getGmljp2V1RootNode() const
{
ossimRefPtr<ossimXmlNode> node = new ossimXmlNode();
ossimString os = "gml:FeatureCollection";
node->setTag( os );
ossimRefPtr<ossimXmlAttribute> attr(0);
ossimString name;
ossimString value;
attr = new ossimXmlAttribute();
name = "xmlns";
value = "http://www.opengis.net/gml";
attr->setNameValue( name, value );
node->addAttribute( attr );
attr = new ossimXmlAttribute();
name = "xmlns:gml";
value = "http://www.opengis.net/gml";
attr->setNameValue( name, value );
node->addAttribute( attr );
attr = new ossimXmlAttribute();
name = "xmlns:xsi";
value = "http://www.w3.org/2001/XMLSchema-instance";
attr->setNameValue( name, value );
node->addAttribute( attr );
attr = new ossimXmlAttribute();
name = "xsi:schemaLocation";
value = "http://www.opengis.net/gml gmlJP2Profile.xsd";
attr->setNameValue( name, value );
node->addAttribute( attr );
return node;
} // ossimGmlSupportData::getGmljp2V1Node()
bool ossimGmlSupportData::write(std::ostream& os)
{
bool status = false;
if ( m_xmlDocument.valid() )
{
os << *(m_xmlDocument.get());
status = true;
}
return status;
}
ossimRefPtr<ossimXmlDocument> ossimGmlSupportData::getXmlDoc() const
{
return m_xmlDocument;
}
bool ossimGmlSupportData::getImageGeometry( ossimKeywordlist& geomKwl ) const
{
// Try for map projected geometry first...
bool success = getImageGeometryFromRectifiedGrid( geomKwl );
if ( !success )
{
// Look for sensor model block.
getImageGeometryFromSeonsorModel( geomKwl );
}
return success;
}
#if 0 /* Please leave. (drb) */
bool ossimGmlSupportData::getImageGeometry( ossimKeywordlist& geomKwl ) const
{
if ( m_xmlDocument.valid() )
{
vector< ossimRefPtr<ossimXmlNode> > xml_nodes;
bool gotSensorImage = false;
bool gotRectifiedImage = false;
ossim_uint32 pcsCodeGrid = 32767; // only applies to rectified
// Check the GMLJP2CoverageCollection attributes for the default namespace.
ossimString defaultNamespaceStr( "" );
ossimString xpath_root = "/gmljp2:GMLJP2CoverageCollection";
xml_nodes.clear();
m_xmlDocument->findNodes( xpath_root, xml_nodes );
if ( xml_nodes.size() == 0 )
{
// check if the default namespace is gmljp2
xpath_root = "/GMLJP2CoverageCollection";
m_xmlDocument->findNodes( xpath_root, xml_nodes );
}
if ( xml_nodes.size() >= 1 )
{
const ossimString defaultNamespaceIdentifierStr( "xmlns" );
ossimString defaultNamespacePrependStr = defaultNamespaceIdentifierStr + ":";
const ossimRefPtr<ossimXmlAttribute> defaultNamespaceAttribute = xml_nodes[0]->findAttribute( defaultNamespaceIdentifierStr );
ossimString defaultNamespaceSettingStr = defaultNamespaceAttribute->getValue();
// search for the attribute value in the other attributes
const ossimXmlNode::AttributeListType& attributeList = xml_nodes[0]->getAttributes();
size_t nAttributes = attributeList.size();
for ( size_t i=0; i<nAttributes; ++i )
{
const ossimRefPtr<ossimXmlAttribute> attribute = attributeList[i];
const ossimString& attribute_name = attribute->getName();
const ossimString& attribute_value = attribute->getValue();
if ( attribute_name != defaultNamespaceIdentifierStr &&
attribute_value == defaultNamespaceSettingStr )
{
defaultNamespaceStr = attribute_name.after( defaultNamespacePrependStr );
defaultNamespaceStr += ":";
}
}
}
// Check for a sensor image
ossimString xpath0 = "/gmljp2:GMLJP2CoverageCollection/gmljp2:featureMember/gmljp2:GMLJP2ReferenceableGridCoverage/gml:domainSet/gmlcov:ReferenceableGridBySensorModel";
xpath0 = xpath0.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" );
xml_nodes.clear();
m_xmlDocument->findNodes( xpath0, xml_nodes );
if ( xml_nodes.size() >= 1 )
{
// we've got a sensor model image
gotSensorImage = true;
}
else
{
const ossimString srsNameStr( "srsName" );
ossimString pcsCodeDefinitionStr( "http://www.opengis.net/def/crs/EPSG/0/" );
xpath0 = "/gmljp2:GMLJP2CoverageCollection/gmljp2:featureMember/gmljp2:GMLJP2RectifiedGridCoverage/gml:domainSet/gml:RectifiedGrid";
xpath0 = xpath0.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" );
xml_nodes.clear();
m_xmlDocument->findNodes( xpath0, xml_nodes );
if ( xml_nodes.size() >= 1 )
{
// we've got a rectified image
gotRectifiedImage = true;
const ossimRefPtr<ossimXmlAttribute> hrefAttribute = xml_nodes[0]->findAttribute( srsNameStr );
const ossimString& originSrsName = hrefAttribute->getValue();
ossimString pcsCodeGridStr = originSrsName.after( pcsCodeDefinitionStr.string() );
pcsCodeGrid = pcsCodeGridStr.toUInt32();
if ( pcsCodeGrid != 32767 )
{
//---
// The ossimEpsgProjectionFactory will not pick up the origin latitude if code is
// 4326 (geographic) so we use the projection name; else, the origin_latitude will
// always be 0. This is so the gsd comes out correct for scale.
//---
if ( pcsCodeGrid != 4326 ) // map projection
{
// Add the pcs code.
geomKwl.add( ossimKeywordNames::PCS_CODE_KW,
pcsCodeGridStr.c_str() );
}
else // geographic
{
geomKwl.add( ossimKeywordNames::TYPE_KW,
ossimString( "ossimEquDistCylProjection" ) );
}
}
}
}
// Number of lines & samples, for either sensor or rectified imagery
ossimString xpath_limits_low = "/gml:limits/gml:GridEnvelope/gml:low";
ossimString xpath_limits_high = "/gml:limits/gml:GridEnvelope/gml:high";
xpath_limits_low = xpath_limits_low.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" );
xpath_limits_high = xpath_limits_high.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" );
bool gotLow = false;
ossim_int32 lowX, lowY;
ossimString xpath = xpath0 + xpath_limits_low;
xml_nodes.clear();
m_xmlDocument->findNodes( xpath, xml_nodes );
if ( xml_nodes.size() == 1 )
{
const ossimString& lowerCorner = xml_nodes[0]->getText();
size_t spacePos = lowerCorner.find( ' ' );
ossimString lowerXString = lowerCorner.beforePos( spacePos );
ossimString lowerYString = lowerCorner.afterPos ( spacePos );
lowX = lowerXString.toInt32();
lowY = lowerYString.toInt32();
gotLow = true;
}
bool gotHigh = false;
ossim_int32 highX = 0;
ossim_int32 highY = 0;
xpath = xpath0 + xpath_limits_high;
xml_nodes.clear();
m_xmlDocument->findNodes( xpath, xml_nodes );
if ( xml_nodes.size() == 1 )
{
const ossimString& higherCorner = xml_nodes[0]->getText();
size_t spacePos = higherCorner.find( ' ' );
ossimString higherXString = higherCorner.beforePos( spacePos );
ossimString higherYString = higherCorner.afterPos ( spacePos );
highX = higherXString.toInt32();
highY = higherYString.toInt32();
gotHigh = true;
}
if ( gotHigh && gotLow )
{
geomKwl.add( ossimKeywordNames::NUMBER_LINES_KW, highY - lowY + 1 );
geomKwl.add( ossimKeywordNames::NUMBER_SAMPLES_KW, highX - lowX + 1 );
}
if ( gotSensorImage )
{
const ossimString hrefStr( "xlink:href" );
const ossimString codeSpaceStr( "codeSpace" );
ossimString sensorModelHref( "" );
ossimString xpath_sensor_model = "/gmlcov:sensorModel";
xpath_sensor_model = xpath_sensor_model.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" );
xpath = xpath0 + xpath_sensor_model;
xml_nodes.clear();
m_xmlDocument->findNodes( xpath, xml_nodes );
if ( xml_nodes.size() == 1 )
{
const ossimRefPtr<ossimXmlAttribute> hrefAttribute = xml_nodes[0]->findAttribute( hrefStr );
sensorModelHref = hrefAttribute->getValue();
}
ossimString sensorInstanceHref( "" );
ossimString xpath_sensor_typeOf = "/gmlcov:sensorInstance/sml:SimpleProcess/sml:typeOf";
xpath_sensor_typeOf = xpath_sensor_typeOf.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" );
xpath = xpath0 + xpath_sensor_typeOf;
xml_nodes.clear();
m_xmlDocument->findNodes( xpath, xml_nodes );
if ( xml_nodes.size() == 1 )
{
const ossimRefPtr<ossimXmlAttribute> hrefAttribute = xml_nodes[0]->findAttribute( hrefStr );
sensorInstanceHref = hrefAttribute->getValue();
}
ossimRefPtr<ossimSensorModel> sensor_model = 0;
ossimString xpath_sensor_name = "/gmlcov:sensorInstance/sml:SimpleProcess/gml:name";
xpath_sensor_name = xpath_sensor_name.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" );
xpath = xpath0 + xpath_sensor_name;
xml_nodes.clear();
m_xmlDocument->findNodes( xpath, xml_nodes );
int nSensorNames = (int)xml_nodes.size();
for ( int i=0; i<nSensorNames; ++i )
{
const ossimString& sensorName = xml_nodes[i]->getText();
ossimProjectionFactoryRegistry* registry = ossimProjectionFactoryRegistry::instance();
ossimProjection* proj = registry->createProjection( sensorName );
// Is it a sensor model ?
sensor_model = dynamic_cast<ossimSensorModel*>( proj );
if ( sensor_model.valid() )
{
geomKwl.add( ossimKeywordNames::TYPE_KW, sensorName.c_str() );
break;
}
}
if ( !sensor_model.valid() )
{
// Add debug message
return false;
}
// Check if the sensor instance is typeOf the sensor model
if ( sensorModelHref == sensorInstanceHref )
{
const ossimString refStr( "ref" );
// sml:setValue
ossimString xpath_setValue = "/gmlcov:sensorInstance/sml:SimpleProcess/sml:configuration/sml:Settings/sml:setValue";
xpath_setValue = xpath_setValue.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" );
xpath = xpath0 + xpath_setValue;
xml_nodes.clear();
m_xmlDocument->findNodes( xpath, xml_nodes );
size_t nXmlNodes = xml_nodes.size();
for( size_t i=0; i<nXmlNodes; ++i )
{
const ossimString& elementValue = xml_nodes[i]->getText();
const ossimRefPtr<ossimXmlAttribute> refAttribute = xml_nodes[i]->findAttribute( refStr );
const ossimString& settingsRef = refAttribute->getValue();
bool successSetValue = sensor_model->getImageGeometry( settingsRef, elementValue, geomKwl );
success &= successSetValue;
if ( !successSetValue )
{
// Add debug message
}
}
/* sml:setArrayValues */
ossimString xpath_setArrayValues = "/gmlcov:sensorInstance/sml:SimpleProcess/sml:configuration/sml:Settings/sml:setArrayValues";
xpath_setArrayValues = xpath_setArrayValues.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" );
xpath = xpath0 + xpath_setArrayValues;
xml_nodes.clear();
m_xmlDocument->findNodes( xpath, xml_nodes );
nXmlNodes = xml_nodes.size();
for( size_t i=0; i<nXmlNodes; ++i )
{
ossimString elementValue( "" );
const ossimRefPtr<ossimXmlAttribute> refAttribute = xml_nodes[i]->findAttribute( refStr );
const ossimString& settingsRef = refAttribute->getValue();
const ossimXmlNode::ChildListType& children = xml_nodes[i]->getChildNodes();
if ( children.size() > 0 )
{
const ossimXmlNode::ChildListType& grandchildren = children[0]->getChildNodes();
if ( (grandchildren.size() > 1) && (grandchildren[1]->getTag() == ossimString( "sml:value")) )
{
elementValue = grandchildren[1]->getText();
}
}
bool successSetArrayValues = sensor_model->getImageGeometry( settingsRef, elementValue, geomKwl );
success &= successSetArrayValues;
if ( !successSetArrayValues )
{
// Add debug message
}
}
}
}
else if ( gotRectifiedImage )
{
const ossimString srsNameStr( "srsName" );
ossimString pcsCodeDefinitionStr( "http://www.opengis.net/def/crs/EPSG/0/" );
/* axis labels for rectified imagery */
ossimString xpath_axisLabels = "/gml:axisLabels";
xpath_axisLabels = xpath_axisLabels.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" );
ossimString firstAxisLabelString( "" );
ossimString secondAxisLabelString( "" );
ossimString xpath = xpath0 + xpath_axisLabels;
xml_nodes.clear();
m_xmlDocument->findNodes( xpath, xml_nodes );
if ( xml_nodes.size() == 1 )
{
ossimString axisLabelsString = xml_nodes[0]->getText();
size_t spacePos = axisLabelsString.find( ' ' );
firstAxisLabelString = axisLabelsString.beforePos( spacePos );
secondAxisLabelString = axisLabelsString.afterPos ( spacePos );
}
success = addTieAndScale( geomKwl );
//---
// origin:
// Note: In GML the origin is the tie point, NOT the projection origin.
//---
ossim_uint32 pcsCodeOrigin = 32767;
ossimString xpath_originPoint = "/gml:origin/gml:Point";
xpath_originPoint = xpath_originPoint.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" );
xpath = xpath0 + xpath_originPoint;
xml_nodes.clear();
m_xmlDocument->findNodes( xpath, xml_nodes );
if ( xml_nodes.size() == 1 )
{
const ossimString& originString = xml_nodes[0]->getChildTextValue( ossimString( "pos" ) );
size_t spacePos = originString.find( ' ' );
ossimString firstOriginString = originString.beforePos( spacePos );
ossimString secondOriginString = originString.afterPos ( spacePos );
const ossimRefPtr<ossimXmlAttribute> hrefAttribute = xml_nodes[0]->findAttribute( srsNameStr );
const ossimString& originSrsName = hrefAttribute->getValue();
ossimString pcsCodeOriginStr = originSrsName.after( pcsCodeDefinitionStr.string() );
pcsCodeOrigin = pcsCodeOriginStr.toUInt32();
if ( pcsCodeOrigin != 32767 )
{
std::string tie_point_xy;
std::string tie_point_units;
if ( pcsCodeOrigin == 4326 ) // map projection
{
// Longitude first, e.g. (lon,lat)
tie_point_units = "degrees";
}
else
{
tie_point_units = "meters";
}
if ( ( tie_point_units == "degrees" ) &&
( firstAxisLabelString == "Lat" ) )
{
tie_point_xy = "(";
tie_point_xy += secondOriginString.string();
tie_point_xy += ",";
tie_point_xy += firstOriginString.string();
tie_point_xy += ")";
}
else
{
tie_point_xy = "(";
tie_point_xy += firstOriginString.string();
tie_point_xy += ",";
tie_point_xy += secondOriginString.string();
tie_point_xy += ")";
}
geomKwl.add( ossimKeywordNames::TIE_POINT_XY_KW, tie_point_xy.c_str() );
geomKwl.add( ossimKeywordNames::TIE_POINT_UNITS_KW, tie_point_units.c_str() );
}
}
//---
// offset vector
// Note this is the scale:
ossimString xpath_offsetVector = "/gml:offsetVector";
xpath_offsetVector = xpath_offsetVector.replaceAllThatMatch( defaultNamespaceStr.c_str(), "" );
xpath = xpath0 + xpath_offsetVector;
xml_nodes.clear();
m_xmlDocument->findNodes( xpath, xml_nodes );
if ( xml_nodes.size() )
{
const ossimString& offsetVectorString = xml_nodes[0]->getText();
size_t spacePos = offsetVectorString.find( ' ' );
ossimString firstOffsetVectorString = offsetVectorString.beforePos( spacePos );
ossimString secondOffsetVectorString = offsetVectorString.afterPos ( spacePos );
const ossimRefPtr<ossimXmlAttribute> hrefAttribute = xml_nodes[0]->findAttribute( srsNameStr );
const ossimString& offsetVectorSrsName = hrefAttribute->getValue();
ossimString pcsCodeOffsetVectorStr = offsetVectorSrsName.after( pcsCodeDefinitionStr.string() );
ossim_uint32 pcsCodeOffsetVector = pcsCodeOffsetVectorStr.toUInt32();
if ( pcsCodeOffsetVector != 32767 )
{
std::string scale_xy;
std::string scale_units;
if ( pcsCodeOffsetVector == 4326 )
{
scale_units = "degrees";
}
else
{
scale_units = "meters";
}
if ( ( scale_units == "degrees" ) && ( firstAxisLabelString == "Lat" ) )
{
scale_xy = "(";
scale_xy += secondOffsetVectorString.c_str();
scale_xy += ",";
scale_xy += firstOffsetVectorString.c_str();
scale_xy += ")";
}
else
{
scale_xy = "(";
scale_xy += firstOffsetVectorString.c_str();
scale_xy += ",";
scale_xy += secondOffsetVectorString.c_str();
scale_xy += ")";
}
geomKwl.add( ossimKeywordNames::PIXEL_SCALE_XY_KW, scale_xy.c_str() );
geomKwl.add( ossimKeywordNames::PIXEL_SCALE_UNITS_KW, scale_units.c_str() );
}
}
}
}
return success;
} // End: ossimGmlSupportData::getImageGeometry( geomKwl )
#endif
void ossimGmlSupportData::getGeoOrigin(
const ossimImageGeometry* geom,
const ossimIpt& ul,
ossimString& originString,
ossimString& offsetVector1String,
ossimString& offsetVector2String ) const
{
if ( geom )
{
// Get the gsd:
ossimDpt gsd;
geom->getDegreesPerPixel( gsd );
// Get tie point:
ossimGpt tie;
geom->localToWorld( ul, tie );
std::ostringstream os;
os.precision(15);
os << tie.lat << " " << tie.lon;
originString = os.str();
std::ostringstream os2;
os2.precision(15);
os2 << -gsd.y << " " << "0.0";
offsetVector1String = os2.str();
std::ostringstream os3;
os3.precision(15);
os3 << "0.0" << " " << gsd.x;
offsetVector2String = os3.str();
}
} // End: ossimGmlSupportData::getGeoOrigin
void ossimGmlSupportData::getMapOrigin(
const ossimImageGeometry* geom,
const ossimIpt& ul,
ossimString& originString,
ossimString& offsetVector1String,
ossimString& offsetVector2String ) const
{
if ( geom )
{
ossimRefPtr<const ossimMapProjection> mapProj = geom->getAsMapProjection();
if ( mapProj.valid() != 0 )
{
// Get the tie point:
ossimGpt gpt;
geom->localToWorld( ul, gpt );
ossimDpt tie = mapProj->forward( gpt );
std::ostringstream os;
os.precision(15);
os << tie.x << " " << tie.y;
originString = os.str();
}
// Get the projected CS gsd:
ossimDpt gsdMap;
geom->getMetersPerPixel( gsdMap );
std::ostringstream os2;
os2.precision(15);
os2 << gsdMap.x << " " << "0.0";
offsetVector1String = os2.str();
std::ostringstream os3;
os3.precision(15);
os3 << "0.0" << " " << -gsdMap.y;
offsetVector2String = os3.str();
}
} // End: ossimGmlSupportData::getMapBounds
void ossimGmlSupportData::getGeoBounds( const ossimImageGeometry* geom,
const ossimIrect& rect,
ossimString& upperCornerString,
ossimString& lowerCornerString ) const
{
if ( geom )
{
ossimRefPtr<const ossimMapProjection> mapProj = geom->getAsMapProjection();
if ( mapProj.valid() )
{
// Get the bounding rect. This assumes North up.
ossimGpt ulGpt;
ossimGpt lrGpt;
geom->localToWorld( rect.ul(), ulGpt );
geom->localToWorld( rect.lr(), lrGpt );
std::ostringstream os;
os.precision(15);
os << ulGpt.lat << " " << ulGpt.lon;
upperCornerString = os.str();
std::ostringstream os2;
os2.precision(15);
os2 << lrGpt.lat << " " << lrGpt.lon;
lowerCornerString = os2.str();
}
}
} // End: ossimGmlSupportData::getGeoBounds
void ossimGmlSupportData::getLimits( const ossimIrect& rect,
ossimString& gridHighString,
ossimString& gridLowString ) const
{
if ( rect.hasNans() == false )
{
// Zero based image rect.
gridLowString = "0 0";
ossim_uint32 w = rect.width();
ossim_uint32 h = rect.height();
std::ostringstream os;
os << (w-1) << " " << (h-1);
gridHighString = os.str();
}
}
bool ossimGmlSupportData::getImageGeometryFromSeonsorModel( ossimKeywordlist& /* geomKwl */) const
{
bool status = false;
if ( m_xmlDocument.valid() )
{
vector< ossimRefPtr<ossimXmlNode> > xml_nodes;
ossimString xpath0 = "/gmljp2:GMLJP2CoverageCollection/gmljp2:featureMember/gmljp2:GMLJP2ReferenceableGridCoverage/gml:domainSet/gmlcov:ReferenceableGridBySensorModel";
m_xmlDocument->findNodes( xpath0, xml_nodes );
if ( xml_nodes.size() >= 1 )
{
// Put sensor model code here...
status = true;
}
}
return status;
}
bool ossimGmlSupportData::getImageGeometryFromRectifiedGrid( ossimKeywordlist& geomKwl ) const
{
bool status = false;
if ( m_xmlDocument.valid() )
{
bool useGmlPrefix = false;
vector< ossimRefPtr<ossimXmlNode> > xml_nodes;
ossimString xpath0 = "/gmljp2:GMLJP2CoverageCollection/gmljp2:featureMember/gmljp2:GMLJP2RectifiedGridCoverage/domainSet/RectifiedGrid";
m_xmlDocument->findNodes( xpath0, xml_nodes );
if ( !xml_nodes.size() )
{
xpath0 = "/gmljp2:GMLJP2CoverageCollection/gmljp2:featureMember/gmljp2:GMLJP2RectifiedGridCoverage/gml:domainSet/gml:RectifiedGrid";
m_xmlDocument->findNodes( xpath0, xml_nodes );
if ( xml_nodes.size() )
{
useGmlPrefix = true;
}
}
if ( xml_nodes.size() )
{
const ossimString SRS_NAME( "srsName" );
const ossimString PCS_CODE_DEFINITION_STR( "http://www.opengis.net/def/crs/EPSG/0/" );
const ossimRefPtr<ossimXmlAttribute> hrefAttribute =
xml_nodes[0]->findAttribute( SRS_NAME );
const ossimString& originSrsName = hrefAttribute->getValue();
ossimString pcsCodeStr = originSrsName.after( PCS_CODE_DEFINITION_STR.string() );
ossim_uint32 pcsCode = pcsCodeStr.toUInt32();
if ( pcsCode != 32767 )
{
// Add the pcs code.
geomKwl.add( ossimKeywordNames::PCS_CODE_KW, pcsCodeStr.c_str() );
if ( pcsCode == 4326 )
{
ossimString srsName = "EPSG:";
srsName += pcsCodeStr;
geomKwl.add( ossimKeywordNames::SRS_NAME_KW, srsName.c_str() );
geomKwl.add( ossimKeywordNames::TYPE_KW, "ossimEquDistCylProjection");
}
if ( addLineSamps( xpath0, useGmlPrefix, geomKwl ) )
{
if ( addTie( xpath0, useGmlPrefix, pcsCode, geomKwl ) )
{
status = addScale( xpath0, useGmlPrefix, pcsCode, geomKwl );
}
}
}
}
}
return status;
}
bool ossimGmlSupportData::addLineSamps( const ossimString& xpath0,
bool useGmlPrefix,
ossimKeywordlist& geomKwl ) const
{
bool status = false;
if ( m_xmlDocument.valid() )
{
vector< ossimRefPtr<ossimXmlNode> > xml_nodes;
// Number of lines & samples, for either sensor or rectified imagery:
ossimString xpath_limits_low;
if (useGmlPrefix)
{
xpath_limits_low = "/gml:limits/gml:GridEnvelope/gml:low";
}
else
{
xpath_limits_low = "/limits/GridEnvelope/low";
}
ossimString xpath = xpath0 + xpath_limits_low;
m_xmlDocument->findNodes( xpath, xml_nodes );
if ( xml_nodes.size() == 1 )
{
const ossimString& lowerCorner = xml_nodes[0]->getText();
size_t spacePos = lowerCorner.find( ' ' );
ossimString lowerXString = lowerCorner.beforePos( spacePos );
ossimString lowerYString = lowerCorner.afterPos ( spacePos );
ossim_uint32 lowX = lowerXString.toInt32();
ossim_uint32 lowY = lowerYString.toInt32();
ossimString xpath_limits_high;
if ( useGmlPrefix )
{
xpath_limits_high = "/gml:limits/gml:GridEnvelope/gml:high";
}
else
{
xpath_limits_high = "/limits/GridEnvelope/high";
}
xpath = xpath0 + xpath_limits_high;
xml_nodes.clear();
m_xmlDocument->findNodes( xpath, xml_nodes );
if ( xml_nodes.size() == 1 )
{
const ossimString& higherCorner = xml_nodes[0]->getText();
size_t spacePos = higherCorner.find( ' ' );
ossimString higherXString = higherCorner.beforePos( spacePos );
ossimString higherYString = higherCorner.afterPos ( spacePos );
ossim_uint32 highX = higherXString.toInt32();
ossim_uint32 highY = higherYString.toInt32();
geomKwl.add( ossimKeywordNames::NUMBER_LINES_KW, highY - lowY + 1 );
geomKwl.add( ossimKeywordNames::NUMBER_SAMPLES_KW, highX - lowX + 1 );
status = true;
}
}
}
return status;
} // ossimGmlSupportData::addLineSamps
bool ossimGmlSupportData::addTie( const ossimString& xpath0,
bool useGmlPrefix,
ossim_uint32 pcsCode,
ossimKeywordlist& geomKwl ) const
{
bool status = false;
if ( m_xmlDocument.valid() && (pcsCode != 32767 ) )
{
vector< ossimRefPtr<ossimXmlNode> > xml_nodes;
//---
// origin:
// Note: In GML the origin is the tie point, NOT the projection origin.
//---
// axis labels for rectified imagery:
ossimString xpath_axisLabels;
if ( useGmlPrefix )
{
xpath_axisLabels = "/gml:axisLabels";
}
else
{
xpath_axisLabels = "/axisLabels";
}
ossimString xpath = xpath0 + xpath_axisLabels;
m_xmlDocument->findNodes( xpath, xml_nodes );
if ( xml_nodes.size() == 1 )
{
ossimString axisLabelsString = xml_nodes[0]->getText();
ossimString xpath_originPoint;
if ( useGmlPrefix )
{
xpath_originPoint = "/gml:origin/gml:Point";
}
else
{
xpath_originPoint = "/origin/Point";
}
xpath = xpath0 + xpath_originPoint;
xml_nodes.clear();
m_xmlDocument->findNodes( xpath, xml_nodes );
if ( xml_nodes.size() == 1 )
{
const ossimString& originString = xml_nodes[0]->getChildTextValue( ossimString( "pos" ) );
size_t spacePos = originString.find( ' ' );
ossimString firstOriginString = originString.beforePos( spacePos );
ossimString secondOriginString = originString.afterPos ( spacePos );
std::string tie_point_xy;
std::string tie_point_units;
if ( pcsCode == 4326 ) // map projection
{
// Longitude first, e.g. (lon,lat)
tie_point_units = "degrees";
}
else
{
tie_point_units = "meters";
}
if ( ( tie_point_units == "degrees" ) &&
( axisLabelsString == "Lat Long" ) )
{
tie_point_xy = "(";
tie_point_xy += secondOriginString.string();
tie_point_xy += ",";
tie_point_xy += firstOriginString.string();
tie_point_xy += ")";
}
else
{
tie_point_xy = "(";
tie_point_xy += firstOriginString.string();
tie_point_xy += ",";
tie_point_xy += secondOriginString.string();
tie_point_xy += ")";
}
geomKwl.add( ossimKeywordNames::TIE_POINT_XY_KW, tie_point_xy.c_str() );
geomKwl.add( ossimKeywordNames::TIE_POINT_UNITS_KW, tie_point_units.c_str() );
status = true;
}
}
} // Matches: if ( m_xmlDocument.valid() && (pscCode != 32767 ) )
return status;
} // End: ossimGmlSupportData::addTie( ... )
bool ossimGmlSupportData::addScale( const ossimString& xpath0,
bool useGmlPrefix,
ossim_uint32 pcsCode,
ossimKeywordlist& geomKwl ) const
{
bool status = false;
if ( m_xmlDocument.valid() && (pcsCode != 32767 ) )
{
vector< ossimRefPtr<ossimXmlNode> > xml_nodes;
//---
// origin:
// Note: In GML the origin is the tie point, NOT the projection origin.
//---
// axis labels for rectified imagery:
ossimString xpath_axisLabels;
if ( useGmlPrefix )
{
xpath_axisLabels = "/gml:axisLabels";
}
else
{
xpath_axisLabels = "/axisLabels";
}
ossimString xpath = xpath0 + xpath_axisLabels;
m_xmlDocument->findNodes( xpath, xml_nodes );
if ( xml_nodes.size() == 1 )
{
ossimString axisLabelsString = xml_nodes[0]->getText();
ossimString xpath_offsetVector;
if ( useGmlPrefix )
{
xpath_offsetVector = "/gml:offsetVector";
}
else
{
xpath_offsetVector = "/offsetVector";
}
xpath = xpath0 + xpath_offsetVector;
xml_nodes.clear();
m_xmlDocument->findNodes( xpath, xml_nodes );
if ( xml_nodes.size() == 2 )
{
const ossimString& offsetVectorString0 = xml_nodes[0]->getText();
const ossimString& offsetVectorString1 = xml_nodes[1]->getText();
size_t spacePos0 = offsetVectorString0.find( ' ' );
size_t spacePos1 = offsetVectorString1.find( ' ' );
ossimString firstOffsetVectorString0 = offsetVectorString0.beforePos( spacePos0 );
ossimString secondOffsetVectorString0 = offsetVectorString0.afterPos ( spacePos0 );
ossimString firstOffsetVectorString1 = offsetVectorString1.beforePos( spacePos1 );
ossimString secondOffsetVectorString1 = offsetVectorString1.afterPos ( spacePos1 );
// TODO: Add for rotational matrix:
std::string scale_xy;
std::string scale_units;
if ( pcsCode == 4326 )
{
scale_units = "degrees";
}
else
{
scale_units = "meters";
}
ossimDpt scale;
if ( ( scale_units == "degrees" ) &&
( axisLabelsString == "Lat Long" ) )
{
scale.x = secondOffsetVectorString1.toFloat64();
scale.y = firstOffsetVectorString0.toFloat64();
}
else
{
scale.x = firstOffsetVectorString0.toFloat64();
scale.y = secondOffsetVectorString1.toFloat64();
}
if ( scale.y < 0.0 )
{
scale.y *= -1.0; // make positive
}
if ( ( scale_units == "degrees" ) && ( scale.x != scale.y ) )
{
// Compute/add the origin latitude of true scale.
ossim_float64 origin_lat = ossim::acosd(scale.y/scale.x);
geomKwl.add( ossimKeywordNames::ORIGIN_LATITUDE_KW, origin_lat );
}
geomKwl.add( ossimKeywordNames::PIXEL_SCALE_XY_KW, scale.toString().c_str() );
geomKwl.add( ossimKeywordNames::PIXEL_SCALE_UNITS_KW, scale_units.c_str() );
status = true;
}
}
} // Matches: if ( m_xmlDocument.valid() && (pscCode != 32767 ) )
return status;
} // End: ossimGmlSupportData::addScale( ... )
| 33.671271 | 175 | 0.590697 | [
"geometry",
"object",
"vector",
"model"
] |
fe5f47f70dabf063c1267e1302da74892684813b | 1,940 | cc | C++ | RAVL2/Math/Optimisation/Ransac.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/Math/Optimisation/Ransac.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | RAVL2/Math/Optimisation/Ransac.cc | isuhao/ravl2 | 317e0ae1cb51e320b877c3bad6a362447b5e52ec | [
"BSD-Source-Code"
] | null | null | null | // This file is part of RAVL, Recognition And Vision Library
// Copyright (C) 2002, University of Surrey
// This code may be redistributed under the terms of the GNU Lesser
// General Public License (LGPL). See the lgpl.licence file for details or
// see http://www.gnu.org/copyleft/lesser.html
// file-header-ends-here
//! rcsid="$Id: Ransac.cc 4578 2004-09-27 11:05:16Z ees1wc $"
//! lib=RavlOptimise
//! file="Ravl/Math/Optimisation/Ransac.cc"
#include "Ravl/Ransac.hh"
#include "Ravl/StdConst.hh"
namespace RavlN {
//: Constructor for RANSAC
RansacC::RansacC(ObservationManagerC &nobsManager,
FitToSampleC &nmodelFitter,
EvaluateSolutionC &nevaluator)
: obsManager(nobsManager),
modelFitter(nmodelFitter),
evaluator(nevaluator)
{
highestVote = RavlConstN::minReal;
}
//: Generate sample, compute vote and update best solution and vote
bool RansacC::ProcessSample(UIntT minNumConstraints)
{
// reset "selected" flags
obsManager.UnselectAllObservations();
// generate sample and abort if it can't be generated
DListC<ObservationC> sample;
try {
sample = obsManager.RandomSample(minNumConstraints);
}
catch(ExceptionC) {
return false;
}
// fit model and abort on any numerical errors found
StateVectorC sv;
try {
sv = modelFitter.FitModel(sample);
}
catch(ExceptionNumericalC) {
return false;
}
// generate list of observations to be evaluated
DListC<ObservationC> obsList = obsManager.ObservationList(sv);
RealT newVote;
try {
newVote = evaluator.SolutionScore(sv, obsList);
}
catch (ExceptionNumericalC) {
return false;
}
if ( newVote > highestVote ) {
stateVec = sv.Copy();
highestVote = newVote;
}
return true;
}
//: Return the highest vote found so far
RealT RansacC::GetHighestVote() const
{
return highestVote;
}
}
| 26.216216 | 74 | 0.678351 | [
"model"
] |
fe61bf2bc11af8d0f8ad9ba2a85bf96c465c2db7 | 1,917 | cpp | C++ | sources/Video/BufferFormat/VertexFormat.cpp | LukasBanana/ForkENGINE | 8b575bd1d47741ad5025a499cb87909dbabc3492 | [
"BSD-3-Clause"
] | 13 | 2017-03-21T22:46:18.000Z | 2020-07-30T01:31:57.000Z | sources/Video/BufferFormat/VertexFormat.cpp | LukasBanana/ForkENGINE | 8b575bd1d47741ad5025a499cb87909dbabc3492 | [
"BSD-3-Clause"
] | null | null | null | sources/Video/BufferFormat/VertexFormat.cpp | LukasBanana/ForkENGINE | 8b575bd1d47741ad5025a499cb87909dbabc3492 | [
"BSD-3-Clause"
] | 2 | 2018-07-23T19:56:41.000Z | 2020-07-30T01:32:01.000Z | /*
* Vertex format file
*
* This file is part of the "ForkENGINE" (Copyright (c) 2014 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "Video/BufferFormat/VertexFormat.h"
#include "Video/BufferFormat/InvalidVertexFormatException.h"
#include "Core/StringModifier.h"
namespace Fork
{
namespace Video
{
/*
* Attribute class
*/
VertexFormat::Attribute::Attribute(
const std::string& name, const RendererDataTypes dataType, unsigned int numComponents) :
name { name },
dataType_ { dataType },
numComponents_ { numComponents }
{
if (numComponents < 1 || numComponents > 4)
{
throw InvalidVertexFormatException(
nullptr,
"Invalid number of components for vertex attribute (Must be 1, 2, 3 or 4 but given " + ToStr(numComponents) + ")"
);
}
}
size_t VertexFormat::Attribute::Size() const
{
return GetDataTypeSize(GetDataType()) * GetNumComponents();
}
/*
* VertexFormat class
*/
void VertexFormat::SetupAttributes(const std::vector<Attribute>& attributes)
{
/* Store new attribute list */
attributes_ = attributes;
/* Compute new offsets and track increasing format size */
formatSize_ = 0;
for (auto& attr : attributes_)
{
attr.offset_ = formatSize_;
formatSize_ += attr.Size();
}
}
void VertexFormat::AddAttribute(const Attribute& attribute)
{
/* Add new attribute entry */
attributes_.push_back(attribute);
/* Setup attribute's offset and track increasing format size */
auto& attr = attributes_.back();
attr.offset_ = formatSize_;
formatSize_ += attr.Size();
}
void VertexFormat::ClearAttributes()
{
/* Clear attribute list and format size information */
attributes_.clear();
formatSize_ = 0;
}
} // /namespace Video
} // /namespace Fork
// ======================== | 21.3 | 125 | 0.645801 | [
"vector"
] |
fe6aae13aa2c545e1cb3d82795c30c7c54057357 | 20,144 | cpp | C++ | src/SourceTable.cpp | sofea-model/sofea | a6ee54b59c6f96929592118ee77e286f71238c9e | [
"Apache-2.0"
] | null | null | null | src/SourceTable.cpp | sofea-model/sofea | a6ee54b59c6f96929592118ee77e286f71238c9e | [
"Apache-2.0"
] | 2 | 2020-01-31T06:21:44.000Z | 2020-01-31T06:26:52.000Z | src/SourceTable.cpp | sofea-model/sofea | a6ee54b59c6f96929592118ee77e286f71238c9e | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 Dow, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include <QColorDialog>
#include <QDialog>
#include <QDialogButtonBox>
#include <QHeaderView>
#include <QIcon>
#include <QMenu>
#include <QSplitter>
#include <QVBoxLayout>
#include <QDebug>
#include <algorithm>
#include "AppStyle.h"
#include "SourceGeometryEditor.h"
#include "SourceTable.h"
#include "FluxProfilePlot.h"
#include "core/Common.h"
#include "core/Projection.h"
#include "delegates/ComboBoxDelegate.h"
#include "delegates/DateTimeEditDelegate.h"
#include "delegates/DoubleItemDelegate.h"
#include "delegates/DoubleSpinBoxDelegate.h"
#include "delegates/SpinBoxDelegate.h"
#include "models/FluxProfileModel.h"
#include "models/SourceModel.h"
#include "widgets/FilterHeaderView.h"
#include "widgets/FilterProxyModel.h"
#include "widgets/StandardTableView.h"
class SymbolHeaderView : public QHeaderView
{
public:
SymbolHeaderView(Qt::Orientation orientation, QWidget *parent = nullptr)
: QHeaderView(orientation, parent)
{
setSectionsClickable(true);
setSectionResizeMode(QHeaderView::Fixed);
setDefaultSectionSize(24);
setFixedWidth(36);
}
protected:
void paintSection(QPainter *painter, const QRect &rect, int section) const override
{
painter->save();
QStyleOptionHeader opt;
initStyleOption(&opt);
opt.section = section;
opt.rect = rect;
style()->drawControl(QStyle::CE_HeaderSection, &opt, painter, this);
painter->restore();
static const QPointF polygon[6] = {
QPointF(0.1875, 0.5000),
QPointF(0.4375, 0.1875),
QPointF(0.8125, 0.3750),
QPointF(0.6250, 0.5625),
QPointF(0.8125, 0.8125),
QPointF(0.3125, 0.8125)
};
QAbstractItemModel *m = qobject_cast<QAbstractItemModel *>(model());
if (m && orientation() == Qt::Vertical) {
if (section >= m->rowCount() || section < 0)
return;
QVariant sourceTypeVar = m->headerData(section, Qt::Vertical, Qt::UserRole);
QVariant foregroundVar = m->headerData(section, Qt::Vertical, Qt::ForegroundRole);
QVariant backgroundVar = m->headerData(section, Qt::Vertical, Qt::BackgroundRole);
SourceType sourceType = sourceTypeVar.value<SourceType>();
QPen pen = foregroundVar.value<QPen>();
QBrush brush = backgroundVar.value<QBrush>();
pen.setCosmetic(true);
int iconSize = style()->pixelMetric(QStyle::PM_SmallIconSize, nullptr, this);
const int x = rect.center().x() - iconSize / 2;
const int y = rect.center().y() - iconSize / 2;
painter->save();
painter->translate(x, y);
painter->scale(iconSize, iconSize);
painter->setRenderHint(QPainter::Antialiasing, true);
painter->setPen(pen);
painter->setBrush(brush);
switch (sourceType) {
case SourceType::POINT:
case SourceType::POINTCAP:
case SourceType::POINTHOR:
case SourceType::VOLUME:
break;
case SourceType::AREA:
painter->drawRect(QRectF{0.1875, 0.1875, 0.625, 0.625});
break;
case SourceType::AREAPOLY:
painter->drawPolygon(polygon, sizeof polygon / sizeof polygon[0], Qt::WindingFill);
break;
case SourceType::AREACIRC:
painter->drawEllipse(QPointF{0.5, 0.5}, 0.3125, 0.3125);
break;
case SourceType::OPENPIT:
case SourceType::LINE:
case SourceType::BUOYLINE:
case SourceType::RLINE:
case SourceType::RLINEXT:
default:
break;
}
painter->restore();
}
}
};
SourceTable::SourceTable(Scenario *s, SourceGroup *sg, QWidget *parent)
: QWidget(parent), sPtr(s), sgPtr(sg)
{
using namespace sofea::constants;
model = new SourceModel(s, sgPtr, this);
geometryEditor = new SourceGeometryEditor;
geometryEditor->setModel(model);
proxyModel = new FilterProxyModel(this);
proxyModel->setSourceModel(model);
table = new StandardTableView;
table->setSelectionBehavior(QAbstractItemView::SelectRows);
table->setSelectionMode(QAbstractItemView::ExtendedSelection);
table->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
table->setFrameStyle(QFrame::NoFrame);
table->setContextMenuPolicy(Qt::CustomContextMenu);
table->setModel(proxyModel);
table->setAutoFilterEnabled(true);
QHeaderView *horizontalHeader = table->horizontalHeader();
horizontalHeader->setStretchLastSection(false);
horizontalHeader->setContextMenuPolicy(Qt::CustomContextMenu);
horizontalHeader->setVisible(true);
QHeaderView *verticalHeader = new SymbolHeaderView(Qt::Vertical, table);
table->setVerticalHeader(verticalHeader);
verticalHeader->setVisible(true);
// NOTE: Format should be the same as ReceptorDialog and SourceGroupPages
table->setItemDelegateForColumn(SourceModel::Column::X, new DoubleItemDelegate(MIN_X_COORDINATE, MAX_X_COORDINATE, X_COORDINATE_PRECISION, true));
table->setItemDelegateForColumn(SourceModel::Column::Y, new DoubleItemDelegate(MIN_Y_COORDINATE, MAX_Y_COORDINATE, Y_COORDINATE_PRECISION, true));
table->setItemDelegateForColumn(SourceModel::Column::Z, new DoubleItemDelegate(MIN_Z_COORDINATE, MAX_Z_COORDINATE, Z_COORDINATE_PRECISION, true));
table->setItemDelegateForColumn(SourceModel::Column::Longitude, new DoubleItemDelegate(-180.0, 180.0, 5, true));
table->setItemDelegateForColumn(SourceModel::Column::Latitude, new DoubleItemDelegate(-90.0, 90.0, 5, true));
table->setItemDelegateForColumn(SourceModel::Column::Start, new DateTimeEditDelegate);
table->setItemDelegateForColumn(SourceModel::Column::AppRate, new DoubleSpinBoxDelegate(0, 10000000, 2, 1));
table->setItemDelegateForColumn(SourceModel::Column::IncDepth, new DoubleSpinBoxDelegate(0, 100, 2, 1));
table->setItemDelegateForColumn(SourceModel::Column::XInit, new DoubleItemDelegate(MIN_X_DIMENSION, MAX_X_DIMENSION, X_DIMENSION_PRECISION, true));
table->setItemDelegateForColumn(SourceModel::Column::YInit, new DoubleItemDelegate(MIN_Y_DIMENSION, MAX_Y_DIMENSION, Y_DIMENSION_PRECISION, true));
fpEditorModel = new FluxProfileModel(this);
ComboBoxDelegate *fpEditorDelegate = new ComboBoxDelegate(fpEditorModel, 0);
table->setItemDelegateForColumn(SourceModel::Column::FluxProfile, fpEditorDelegate);
massLabel = new QLabel;
// Context Menu Actions
static const QIcon icoArea = this->style()->standardIcon(static_cast<QStyle::StandardPixmap>(AppStyle::CP_ActionAddArea));
static const QIcon icoAreaCirc = this->style()->standardIcon(static_cast<QStyle::StandardPixmap>(AppStyle::CP_ActionAddCircular));
static const QIcon icoAreaPoly = this->style()->standardIcon(static_cast<QStyle::StandardPixmap>(AppStyle::CP_ActionAddPolygon));
static const QIcon icoImport = this->style()->standardIcon(static_cast<QStyle::StandardPixmap>(AppStyle::CP_ActionImport));
static const QIcon icoEdit = this->style()->standardIcon(static_cast<QStyle::StandardPixmap>(AppStyle::CP_ActionEdit));
static const QIcon icoColor = this->style()->standardIcon(static_cast<QStyle::StandardPixmap>(AppStyle::CP_ActionColorPalette));
static const QIcon icoFlux = this->style()->standardIcon(static_cast<QStyle::StandardPixmap>(AppStyle::CP_ActionStepChart));
actAddArea = new QAction(icoArea, "Area", this);
actAddAreaCirc = new QAction(icoAreaCirc, "Circular", this);
actAddAreaPoly = new QAction(icoAreaPoly, "Polygon", this);
actImport = new QAction(icoImport, "Import...", this);
actEdit = new QAction(icoEdit, tr("Edit Geometry..."), this);
actColor = new QAction(icoColor, tr("Edit Color..."), this);
actFlux = new QAction(icoFlux, tr("Plot Flux Profile..."), this);
actRemove = new QAction(tr("Remove"), this);
actResampleAppStart = new QAction(tr("Application Start"), this);
actResampleAppRate = new QAction(tr("Application Rate"), this);
actResampleIncorpDepth = new QAction(tr("Incorporation Depth"), this);
actResampleFluxProfile = new QAction(tr("Flux Profile"), this);
// Connections
connect(table, &QTableView::customContextMenuRequested,
this, &SourceTable::contextMenuRequested);
connect(horizontalHeader, &QHeaderView::customContextMenuRequested,
this, &SourceTable::headerContextMenuRequested);
connect(verticalHeader, &QHeaderView::sectionDoubleClicked, [=](int section) {
QModelIndex proxyIndex = proxyModel->index(section, 0);
QModelIndex index = proxyModel->mapToSource(proxyIndex);
QModelIndexList selection;
selection.push_back(index);
openColorDialog(selection);
});
connect(table->selectionModel(), &QItemSelectionModel::selectionChanged,
this, &SourceTable::onSelectionChanged);
connect(model, &SourceModel::dataChanged, this, &SourceTable::onDataChanged);
connect(model, &SourceModel::rowsInserted, this, &SourceTable::onRowsInserted);
connect(model, &SourceModel::rowsRemoved, this, &SourceTable::onRowsRemoved);
FilterHeaderView *filterHeader = qobject_cast<FilterHeaderView *>(horizontalHeader);
if (filterHeader) {
connect(filterHeader, &FilterHeaderView::filterStateChanged, [=]() {
proxyModel->setFilteredRows(filterHeader->filteredRows());
});
}
// Layout
QSplitter *splitter = new QSplitter(Qt::Horizontal, this);
splitter->setContentsMargins(0, 0, 0, 0);
splitter->setHandleWidth(0);
splitter->addWidget(table);
splitter->addWidget(geometryEditor);
splitter->setStretchFactor(0, 1);
splitter->setStretchFactor(1, 0);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->setContentsMargins(0, 0, 0, 5);
mainLayout->addWidget(splitter, 1);
mainLayout->addWidget(massLabel);
setLayout(mainLayout);
refresh();
}
double SourceTable::getTotalMass() const
{
// Calculate the total mass with AF.
double total = 0;
for (const Source &s : sgPtr->sources)
total += sgPtr->appFactor * s.appRate * sPtr->areaToHectares(s.area());
return total;
}
void SourceTable::refresh()
{
model->setProjection(sPtr->conversionCode, sPtr->hDatumCode, sPtr->hUnitsCode);
fpEditorModel->load(sPtr->fluxProfiles);
massLabel->setText(QString(" Total applied mass with AF: %1 kg").arg(getTotalMass()));
}
void SourceTable::headerContextMenuRequested(const QPoint &pos)
{
QMenu *contextMenu = new QMenu(this);
for (int col = 0; col < model->columnCount(); ++col) {
QString headerText = model->headerData(col, Qt::Horizontal, Qt::DisplayRole).toString();
QAction *visibilityAct = new QAction(headerText);
visibilityAct->setCheckable(true);
visibilityAct->setChecked(isColumnVisible(col));
contextMenu->addAction(visibilityAct);
}
QHeaderView *header = table->horizontalHeader();
QPoint globalPos = header->viewport()->mapToGlobal(pos);
QAction *selectedItem = contextMenu->exec(globalPos);
if (selectedItem) {
int selectedCol = contextMenu->actions().indexOf(selectedItem);
setColumnVisible(selectedCol, selectedItem->isChecked());
}
contextMenu->deleteLater();
}
void SourceTable::contextMenuRequested(const QPoint &pos)
{
static const QIcon icoAdd = this->style()->standardIcon(static_cast<QStyle::StandardPixmap>(AppStyle::CP_ActionAdd));
static const QIcon icoResample = this->style()->standardIcon(static_cast<QStyle::StandardPixmap>(AppStyle::CP_ActionRefresh));
QMenu *contextMenu = new QMenu(this);
QMenu *addSourceMenu = contextMenu->addMenu(icoAdd, "Add Source");
addSourceMenu->addAction(actAddArea);
addSourceMenu->addAction(actAddAreaCirc);
addSourceMenu->addAction(actAddAreaPoly);
QMenu *resampleMenu = contextMenu->addMenu(icoResample, "Resample");
resampleMenu->addAction(actResampleAppStart);
resampleMenu->addAction(actResampleAppRate);
resampleMenu->addAction(actResampleIncorpDepth);
resampleMenu->addAction(actResampleFluxProfile);
contextMenu->addAction(actImport);
contextMenu->addAction(actColor);
contextMenu->addAction(actFlux);
contextMenu->addSeparator();
contextMenu->addAction(actRemove);
QModelIndexList selected = table->selectionModel()->selectedIndexes();
QModelIndexList selectedRows = table->selectionModel()->selectedRows();
QModelIndex proxyIndex = table->indexAt(pos);
QModelIndex index = proxyModel->mapToSource(proxyIndex);
// Enable or disable actions depending on selection state.
bool validSelection = proxyIndex.isValid() && selected.contains(proxyIndex);
bool singleSelection = selectedRows.size() == 1;
bool validFlux = false;
Source *currentSource = model->sourceFromIndex(index);
if (currentSource) {
auto fp = currentSource->fluxProfile.lock();
validFlux = fp && !fp->refFlux.empty();
}
resampleMenu->setEnabled(validSelection);
actRemove->setEnabled(validSelection);
actColor->setEnabled(validSelection);
actFlux->setEnabled(validSelection && singleSelection && validFlux);
// Execute the context menu.
QPoint globalPos = table->viewport()->mapToGlobal(pos);
QAction *selectedItem = contextMenu->exec(globalPos);
if (selectedItem)
{
if (selectedItem == actAddArea) {
model->addAreaSource();
}
else if (selectedItem == actAddAreaCirc) {
model->addAreaCircSource();
}
else if (selectedItem == actAddAreaPoly) {
model->addAreaPolySource();
}
else if (selectedItem == actResampleAppStart) {
for (const QModelIndex& pi : selectedRows) {
QModelIndex i = proxyModel->mapToSource(pi);
Source *s = model->sourceFromIndex(i);
sgPtr->initSourceAppStart(s);
}
}
else if (selectedItem == actResampleAppRate) {
for (const QModelIndex& pi : selectedRows) {
QModelIndex i = proxyModel->mapToSource(pi);
Source *s = model->sourceFromIndex(i);
sgPtr->initSourceAppRate(s);
}
}
else if (selectedItem == actResampleIncorpDepth) {
for (const QModelIndex& pi : selectedRows) {
QModelIndex i = proxyModel->mapToSource(pi);
Source *s = model->sourceFromIndex(i);
sgPtr->initSourceIncorpDepth(s);
}
}
else if (selectedItem == actResampleFluxProfile) {
for (const QModelIndex& pi : selectedRows) {
QModelIndex i = proxyModel->mapToSource(pi);
Source *s = model->sourceFromIndex(i);
sgPtr->initSourceFluxProfile(s);
}
}
else if (selectedItem == actImport) {
model->import();
}
else if (selectedItem == actColor) {
for (QModelIndex& i : selectedRows) {
i = proxyModel->mapToSource(i);
}
openColorDialog(selectedRows);
}
else if (selectedItem == actFlux) {
plotFluxProfile(currentSource);
}
else if (selectedItem == actRemove) {
table->removeSelectedRows();
}
}
contextMenu->deleteLater();
}
void SourceTable::onSelectionChanged(const QItemSelection&, const QItemSelection&)
{
QModelIndexList selectedRows;
for (const QModelIndex& proxyIndex : table->selectionModel()->selectedRows())
selectedRows.push_back(proxyModel->mapToSource(proxyIndex));
geometryEditor->setIndexes(selectedRows);
}
QColor SourceTable::colorFromIndex(const QModelIndex &index) const
{
QVariant background = model->headerData(index.row(), Qt::Vertical, Qt::BackgroundRole);
if (background.canConvert<QBrush>()) {
QBrush brush = qvariant_cast<QBrush>(background);
return brush.color();
}
else {
return QColor();
}
}
void SourceTable::openColorDialog(const QModelIndexList& selection)
{
if (model == nullptr)
return;
if (selection.size() == 0)
return;
// Set the initial color, using a default value if the selection has different colors.
QColor color;
if (selection.size() == 1) {
color = colorFromIndex(selection.front());
}
else if (selection.size() > 1) {
auto it = std::adjacent_find(selection.cbegin(), selection.cend(),
[=](const QModelIndex& a, const QModelIndex& b) {
return colorFromIndex(a) != colorFromIndex(b);
});
if (it == selection.end()) {
color = colorFromIndex(selection.front());
}
}
QColorDialog dialog;
dialog.setOptions(QColorDialog::ShowAlphaChannel | QColorDialog::DontUseNativeDialog);
dialog.setCurrentColor(color);
int rc = dialog.exec();
if (rc != QDialog::Accepted)
return;
for (const QModelIndex& index : selection) {
QVariant background = model->headerData(index.row(), Qt::Vertical, Qt::BackgroundRole);
QBrush brush;
if (background.canConvert<QBrush>())
brush = qvariant_cast<QBrush>(background);
brush.setColor(dialog.currentColor());
if (brush.style() == Qt::NoBrush)
brush.setStyle(Qt::SolidPattern);
model->setHeaderData(index.row(), Qt::Vertical, brush, Qt::BackgroundRole);
}
}
void SourceTable::plotFluxProfile(const Source *s)
{
std::shared_ptr<FluxProfile> fp = s->fluxProfile.lock();
if (!fp)
return;
FluxProfilePlot *plotWidget = new FluxProfilePlot(*fp);
plotWidget->setAppStart(s->appStart);
plotWidget->setAppRate(s->appRate);
plotWidget->setIncorpDepth(s->incorpDepth);
plotWidget->setControlsEnabled(false);
plotWidget->setupConnections();
plotWidget->updatePlot();
QDialog *plotDialog = new QDialog(this);
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close);
connect(buttonBox, &QDialogButtonBox::rejected, plotDialog, &QDialog::reject);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(plotWidget);
mainLayout->addWidget(buttonBox);
plotDialog->setWindowTitle(QString::fromStdString(s->srcid));
plotDialog->setWindowFlag(Qt::Tool);
plotDialog->setAttribute(Qt::WA_DeleteOnClose);
plotDialog->setLayout(mainLayout);
plotDialog->exec();
}
void SourceTable::onDataChanged(const QModelIndex &, const QModelIndex &, const QVector<int> &)
{
massLabel->setText(QString(" Total applied mass with AF: %1 kg").arg(getTotalMass()));
emit dataChanged();
}
void SourceTable::onRowsInserted(const QModelIndex &, int, int)
{
massLabel->setText(QString(" Total applied mass with AF: %1 kg").arg(getTotalMass()));
emit dataChanged();
}
void SourceTable::onRowsRemoved(const QModelIndex &, int, int)
{
massLabel->setText(QString(" Total applied mass with AF: %1 kg").arg(getTotalMass()));
emit dataChanged();
}
void SourceTable::setColumnVisible(int column, bool visible)
{
table->setColumnHidden(column, !visible);
model->setColumnHidden(column, !visible);
}
bool SourceTable::isColumnVisible(int column) const
{
return !model->isColumnHidden(column);
}
| 38.96325 | 151 | 0.677571 | [
"geometry",
"model"
] |
fe6af685c7cf6f41090ca48c6f20eee594fed5ff | 2,455 | cpp | C++ | rosbag2_transport/test/rosbag2_transport/test_record.cpp | kurcha01-arm/rosbag2 | 2ad74a4d7a81bcb82e084d5d26c60415c644766e | [
"Apache-2.0"
] | null | null | null | rosbag2_transport/test/rosbag2_transport/test_record.cpp | kurcha01-arm/rosbag2 | 2ad74a4d7a81bcb82e084d5d26c60415c644766e | [
"Apache-2.0"
] | 1 | 2019-12-13T17:33:12.000Z | 2019-12-17T12:41:20.000Z | rosbag2_transport/test/rosbag2_transport/test_record.cpp | sriramster/rosbag2 | 86b0b86af134be871285c0a6e5a17e2a4b85f64c | [
"Apache-2.0"
] | null | null | null | // Copyright 2018, Bosch Software Innovations GmbH.
//
// 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 <gmock/gmock.h>
#include <memory>
#include <string>
#include <vector>
#include "rclcpp/rclcpp.hpp"
#include "record_integration_fixture.hpp"
#include "rosbag2_transport/rosbag2_transport.hpp"
#include "rosbag2/types.hpp"
#include "test_msgs/msg/arrays.hpp"
#include "test_msgs/msg/basic_types.hpp"
#include "test_msgs/message_fixtures.hpp"
TEST_F(RecordIntegrationTestFixture, published_messages_from_multiple_topics_are_recorded)
{
auto array_message = get_messages_arrays()[0];
std::string array_topic = "/array_topic";
auto string_message = get_messages_strings()[1];
std::string string_topic = "/string_topic";
start_recording({false, false, {string_topic, array_topic}, "rmw_format", 100ms});
pub_man_.add_publisher<test_msgs::msg::Strings>(
string_topic, string_message, 2);
pub_man_.add_publisher<test_msgs::msg::Arrays>(
array_topic, array_message, 2);
run_publishers();
stop_recording();
auto recorded_messages = writer_->get_messages();
auto recorded_topics = writer_->get_topics();
ASSERT_THAT(recorded_topics, SizeIs(2));
EXPECT_THAT(recorded_topics.at(string_topic).serialization_format, Eq("rmw_format"));
EXPECT_THAT(recorded_topics.at(array_topic).serialization_format, Eq("rmw_format"));
ASSERT_THAT(recorded_messages, SizeIs(4));
auto string_messages = filter_messages<test_msgs::msg::Strings>(
recorded_messages, string_topic);
auto array_messages = filter_messages<test_msgs::msg::Arrays>(
recorded_messages, array_topic);
ASSERT_THAT(string_messages, SizeIs(2));
ASSERT_THAT(array_messages, SizeIs(2));
EXPECT_THAT(string_messages[0]->string_value, Eq(string_message->string_value));
EXPECT_THAT(array_messages[0]->bool_values, Eq(array_message->bool_values));
EXPECT_THAT(array_messages[0]->float32_values, Eq(array_message->float32_values));
}
| 38.968254 | 90 | 0.771487 | [
"vector"
] |
fe6bfe873a399d056c454c27a6ddc046774fcb76 | 26,849 | cpp | C++ | inetsrv/msmq/src/apps/mqforgn/mqforgn.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/msmq/src/apps/mqforgn/mqforgn.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/msmq/src/apps/mqforgn/mqforgn.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1995-99 Microsoft Corporation. All rights reserved
Module Name:
mqforgn.cpp
Abstract:
Command line utility to create a foreign computer and foreign CN (Site)
Author:
RaphiR
Environment:
Platform-independent.
--*/
#define FORGN_EXPIRATION_MONTH 10
#pragma warning(disable: 4201)
#pragma warning(disable: 4514)
#include "_stdafx.h"
//#define INITGUID
#include <string.h>
#include <stdio.h>
#include <windows.h>
#include <assert.h>
#include "cmnquery.h"
#include "dsquery.h"
#include "mqsymbls.h"
#include "mqprops.h"
#include "mqtypes.h"
#include "mqcrypt.h"
#include "mqsec.h"
#include "_propvar.h"
#include "_rstrct.h"
#include "ds.h"
#include "_mqdef.h"
#include "rt.h"
#include "_guid.h"
#include "admcomnd.h"
#include "mqfrgnky.h"
#include "..\..\inc\version.h"
HRESULT CreateEveryoneSD( PSECURITY_DESCRIPTOR *ppSD ) ;
/*=================================================
T I M E B O M B
==================================================*/
#include <time.h>
void TimeBomb()
{
//
// Get Current time
//
time_t utcTime = time( NULL );
struct tm BetaRTM = { 0, 0, 0, 15, 2 -1, 99 }; // Feb. 15, 1999
struct tm BetaExp = { 0, 0, 0, 15, FORGN_EXPIRATION_MONTH -1, 99 }; // oct 15, 1999
struct tm Warning = { 0, 0, 0, 1, FORGN_EXPIRATION_MONTH -1, 99 }; // Oct 1, 1999
time_t utcBetaRTM = mktime(&BetaRTM);
time_t utcBetaExp = mktime(&BetaExp);
time_t utcWarning = mktime(&Warning);
if(utcTime > utcBetaExp)
{
printf("This demo program has expired\n");
exit(0);
}
else if(utcTime > utcWarning)
{
printf("*** Warning - This demo program will expire on Oct 15, 1999 ***\n\n");
}
}
//-------------------------------
//
//CheckNT4Enterprise()
//
// Check that we run in an NT4 enterprise.
// Exit if fail.
//
//-------------------------------
void CheckNT4Enterprise()
{
HANDLE hQuery;
HRESULT rc;
PROPVARIANT result[2];
DWORD dwPropCount = 2;
CColumns AttributeColumns;
AttributeColumns.Add(PROPID_E_NAME);
AttributeColumns.Add(PROPID_E_VERSION);
rc = DSLookupBegin(0, NULL, AttributeColumns.CastToStruct(), 0, &hQuery);
if (SUCCEEDED(rc))
{
rc = DSLookupNext( hQuery, &dwPropCount, result);
if (SUCCEEDED(rc))
{
DWORD version = result[1].uiVal;
if(version != 3)
{
printf("Error - this utility can be run only in a Windows NT4 MSMQ environment.\n");
exit(0);
}
}
DSLookupEnd(hQuery);
}
}
//-------------------------------
//
//Usage()
//
//-------------------------------
void Usage()
{
printf(
"Usage:\n mqforgn [ -crcn | -opce | -rmcn | -addcn | -crcomp | -rmcomp | -pbkey ]\n\n");
printf("Arguments:\n");
printf("-crcn <CN Name>\tCreate a foreign CN (connected netword)\n");
printf("-opce <CN Name>\n\tGrant everyone the permission to open the connector queue.\n");
printf("-rmcn <CN Name>\tRemove a foreign CN \n");
printf("-addcn <CompName> <CN Name>\n") ;
printf("\tAdd a foreign CN to a computer (Routing Server or foreign computer)\n");
printf("-delcn <CompName> <CN Name> \tRemove the foreign CN from the computer\n");
printf("-crcomp <CompName> <SiteName> <CN Name>\tAdd a foreign computer\n");
printf("-rmcomp <CompName>\tRemove the foreign computer\n");
printf("-pbkey <Machine Name> <Key Name>\n") ;
printf("\tInsert public key in msmqConfiguration object of a foreign machine.\n");
printf("-? \tprint this help\n\n");
printf("e.g., mqforgn -crcomp MyComp ThisSite ForCN\n");
printf("Creates a foreign computer named \"MyComp\" in the site \"ThisSite\", and connected to the foreign CN \"ForCN\"\n");
printf("...or: mqforgn -crcomp MyComp {Site-Guid} {CN-Guid}\n");
exit(-1);
}
//-------------------------------
//
//CheckArgNo()
//
// Exits if wrong number of arguments
//
//-------------------------------
void CheckArgNo(DWORD argno, DWORD dwRequiredArg)
{
if(argno != dwRequiredArg + 2)
{
printf("*** Error: Wrong number of arguments\n\n");
exit(-1);
}
}
//-------------------------------
//
//ErrorExit()
//
// Display a user-readable error and exit
//
//-------------------------------
void ErrorExit(char *pszErrorMsg, HRESULT hr)
{
HINSTANCE hLib = LoadLibrary(L"MQUTIL.DLL");
if(hLib == NULL)
{
exit(-1);
}
WCHAR * pText;
DWORD rc;
rc = FormatMessage(
FORMAT_MESSAGE_FROM_HMODULE |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_MAX_WIDTH_MASK,
hLib,
hr,
0,
reinterpret_cast<WCHAR *>(&pText),
0,
NULL
);
if(rc == 0)
{
printf ("Error (0x%x)\n", hr) ;
exit(-1);
}
printf ("Error (0x%x): %S\n", hr, pText);
exit(hr);
}
//-------------------------------
//
//GetSiteGuid()
//
// Retrieve a Site Guid based on its name
//
//-------------------------------
HRESULT GetSiteGuid(LPWSTR pwszSiteName, GUID * * ppGuid)
{
PROPID aProp[] = {PROPID_S_PATHNAME,
PROPID_S_SITEID};
PROPVARIANT apVar[sizeof(aProp) / sizeof(aProp[0])];
UINT uiPropIndex = 0;
//
// PROPID_S_PATHNAME
//
ASSERT(aProp[uiPropIndex] == PROPID_S_PATHNAME);
apVar[uiPropIndex].vt = VT_NULL;
uiPropIndex++;
//
// PROPID_S_SITEID
//
ASSERT(aProp[uiPropIndex] == PROPID_S_SITEID);
apVar[uiPropIndex].vt = VT_NULL;
uiPropIndex++;
HRESULT hr = DSGetObjectProperties(MQDS_SITE, pwszSiteName, uiPropIndex,aProp,apVar);
if(FAILED(hr))
return(hr);
ASSERT(aProp[1] == PROPID_S_SITEID);
*ppGuid = apVar[1].puuid;
return hr;
}
//-------------------------------
//
//GetCNGuid()
//
// Retrieve a CN Foreign Guid based on its NAME
//
//-------------------------------
HRESULT GetCNGuid(LPWSTR pwszCNName, GUID * * ppGuid)
{
PROPID aProp[] = { PROPID_CN_NAME,
PROPID_CN_GUID,
PROPID_CN_PROTOCOLID } ;
PROPVARIANT apVar[sizeof(aProp) / sizeof(aProp[0])];
UINT uiPropIndex = 0;
//
// PROPID_CN_NAME
//
ASSERT(aProp[uiPropIndex] == PROPID_CN_NAME);
apVar[uiPropIndex].vt = VT_NULL;
uiPropIndex++;
//
// PROPID_CN_GUID
//
ASSERT(aProp[uiPropIndex] == PROPID_CN_GUID);
apVar[uiPropIndex].vt = VT_NULL;
UINT uiGuidIndex = uiPropIndex ;
uiPropIndex++;
//
// PROPID_CN_PROTOCOLID
//
ASSERT(aProp[uiPropIndex] == PROPID_CN_PROTOCOLID);
apVar[uiPropIndex].vt = VT_NULL;
UINT uiProtocolIdIndex = uiPropIndex ;
uiPropIndex++;
HRESULT hr = DSGetObjectProperties(MQDS_CN,pwszCNName, uiPropIndex,aProp,apVar);
if (FAILED(hr))
{
return(hr);
}
//
// Check if foreign GUID
//
ASSERT(aProp[ uiProtocolIdIndex ] == PROPID_CN_PROTOCOLID);
if (apVar[ uiProtocolIdIndex ].bVal != FOREIGN_ADDRESS_TYPE)
{
return(MQ_ERROR_ILLEGAL_OPERATION);
}
ASSERT( aProp[uiGuidIndex ] == PROPID_CN_GUID);
*ppGuid = apVar[ uiGuidIndex ].puuid;
return hr;
}
//-------------------------------
//
// OpenConnectorToEveryone()
//
//-------------------------------
HRESULT OpenConnectorToEveryone( IN LPWSTR pwszForeignCN )
{
PSECURITY_DESCRIPTOR pSD = NULL ;
HRESULT hr = CreateEveryoneSD( &pSD ) ;
if (FAILED(hr))
{
return hr ;
}
hr = DSSetObjectSecurity( MQDS_CN,
pwszForeignCN,
DACL_SECURITY_INFORMATION,
pSD ) ;
return hr ;
}
//-------------------------------
//
//CreateForeignCN()
//
//-------------------------------
HRESULT CreateForeignCN( IN LPWSTR pwszForeignCN )
{
PROPID aProp[] = {PROPID_CN_GUID, PROPID_CN_NAME, PROPID_CN_PROTOCOLID};
PROPVARIANT apVar[sizeof(aProp) / sizeof(aProp[0])];
HRESULT hr = MQ_OK;
UINT uiCurVar = 0;
//
// PROPID_CN_GUID
//
GUID guidInstance;
apVar[uiCurVar].vt = VT_CLSID;
UuidCreate(&guidInstance);
apVar[uiCurVar++].puuid = &guidInstance;
//
// PROPID_CN_NAME
//
apVar[uiCurVar].vt = VT_LPWSTR;
apVar[uiCurVar++].pwszVal = pwszForeignCN;
//
// PROPID_CN_PROTOCOLID
//
apVar[uiCurVar].vt = VT_UI1;
apVar[uiCurVar++].uiVal = FOREIGN_ADDRESS_TYPE;
hr = DSCreateObject( MQDS_CN,
pwszForeignCN,
NULL,
sizeof(aProp) / sizeof(aProp[0]),
aProp,
apVar,
NULL ) ;
return hr;
}
//-------------------------------
//
//AddForeignCN()
//
//-------------------------------
HRESULT AddForeignCN(LPWSTR pwszCompName, LPWSTR pwszCNName)
{
PROPID aProp[] = {PROPID_QM_PATHNAME, PROPID_QM_MACHINE_ID,
PROPID_QM_SERVICE, PROPID_QM_CNS, PROPID_QM_ADDRESS,
PROPID_QM_FOREIGN, PROPID_QM_OS};
PROPVARIANT apVar[sizeof(aProp) / sizeof(aProp[0])];
UINT uiPropIndex = 0;
HRESULT hr = MQ_OK;
GUID *pguidCN;
hr = GetCNGuid(pwszCNName, &pguidCN);
if(FAILED(hr))
return(hr);
//
// PROPID_QM_PATHNAME
//
apVar[uiPropIndex].vt = VT_NULL;
uiPropIndex++;
//
// PROPID_QM_MACHINE_ID
//
apVar[uiPropIndex].vt = VT_NULL;
uiPropIndex++;
//
// PROPID_QM_SERVICE
//
apVar[uiPropIndex].vt = VT_NULL;
uiPropIndex++;
//
// PROPID_QM_CNS
//
apVar[uiPropIndex].vt = VT_NULL;
uiPropIndex++;
//
// PROPID_QM_ADDRESS
//
apVar[uiPropIndex].vt = VT_NULL;
uiPropIndex++;
//
// PROPID_QM_FOREIGN
//
apVar[uiPropIndex].vt = VT_NULL;
uiPropIndex++;
//
// PROPID_QM_OS
//
apVar[uiPropIndex].vt = VT_NULL;
uiPropIndex++;
hr = DSGetObjectProperties(MQDS_MACHINE,pwszCompName, uiPropIndex,aProp,apVar);
//
// Check foreign machine of FRS
//
ASSERT(aProp[5] == PROPID_QM_FOREIGN);
ASSERT(aProp[2] == PROPID_QM_SERVICE);
if(apVar[5].bVal != 1 && apVar[2].ulVal < SERVICE_SRV)
return(MQ_ERROR_ILLEGAL_OPERATION);
//
// Add the CN to list of existing CN
//
ASSERT(aProp[4] == PROPID_QM_ADDRESS);
ASSERT(aProp[3] == PROPID_QM_CNS);
DWORD dwCnCount = apVar[3].cauuid.cElems + 1;
GUID * aguidCns = new GUID[dwCnCount];
for(DWORD i = 0; i < dwCnCount - 1; i++)
{
aguidCns[i] = apVar[3].cauuid.pElems[i];
}
aguidCns[i] = *pguidCN;
//
// Add address to list of existing addresses
//
DWORD dwAddressSize = apVar[4].blob.cbSize + (TA_ADDRESS_SIZE + FOREIGN_ADDRESS_LEN);
BYTE * blobAddress = new BYTE[dwAddressSize];
memcpy(blobAddress, apVar[4].blob.pBlobData, apVar[4].blob.cbSize);
BYTE * pAddress = blobAddress + apVar[4].blob.cbSize;
((TA_ADDRESS *)pAddress)->AddressLength = FOREIGN_ADDRESS_LEN;
((TA_ADDRESS *)pAddress)->AddressType = FOREIGN_ADDRESS_TYPE;
*(GUID *)&((TA_ADDRESS *)pAddress)->Address = *pguidCN;
//
// Set the new CN/Address properties
//
PROPID aPropSet[] = {PROPID_QM_CNS, PROPID_QM_ADDRESS};
PROPVARIANT apVarSet[sizeof(aPropSet) / sizeof(aPropSet[0])];
uiPropIndex = 0;
//
// PROPID_QM_CNS
//
apVarSet[uiPropIndex].vt = VT_CLSID|VT_VECTOR;
apVarSet[uiPropIndex].cauuid.cElems = dwCnCount;
apVarSet[uiPropIndex].cauuid.pElems = aguidCns;
uiPropIndex++;
//
// PROPID_QM_ADDRESS - Updated only in case of foreign,
// and then contains the foreign CN guids.
//
apVarSet[uiPropIndex].vt = VT_BLOB;
apVarSet[uiPropIndex].blob.cbSize = dwAddressSize;
apVarSet[uiPropIndex].blob.pBlobData = blobAddress;
uiPropIndex++;
hr = DSSetObjectProperties(MQDS_MACHINE, pwszCompName, uiPropIndex, aPropSet,apVarSet);
return hr;
}
//-------------------------------
//
//DelForeignCN()
//
//-------------------------------
HRESULT DelForeignCN(LPWSTR pwszCompName, LPWSTR pwszCNName)
{
PROPID aProp[] = {PROPID_QM_PATHNAME, PROPID_QM_MACHINE_ID,
PROPID_QM_SERVICE, PROPID_QM_CNS, PROPID_QM_ADDRESS,
PROPID_QM_FOREIGN, PROPID_QM_OS};
PROPVARIANT apVar[sizeof(aProp) / sizeof(aProp[0])];
UINT uiPropIndex = 0;
HRESULT hr = MQ_OK;
GUID *pguidCN;
hr = GetCNGuid(pwszCNName, &pguidCN);
if(FAILED(hr))
return(hr);
//
// PROPID_QM_PATHNAME
//
apVar[uiPropIndex].vt = VT_NULL;
uiPropIndex++;
//
// PROPID_QM_MACHINE_ID
//
apVar[uiPropIndex].vt = VT_NULL;
uiPropIndex++;
//
// PROPID_QM_SERVICE
//
apVar[uiPropIndex].vt = VT_NULL;
uiPropIndex++;
//
// PROPID_QM_CNS
//
apVar[uiPropIndex].vt = VT_NULL;
uiPropIndex++;
//
// PROPID_QM_ADDRESS
//
apVar[uiPropIndex].vt = VT_NULL;
uiPropIndex++;
//
// PROPID_QM_FOREIGN
//
apVar[uiPropIndex].vt = VT_NULL;
uiPropIndex++;
//
// PROPID_QM_OS
//
apVar[uiPropIndex].vt = VT_NULL;
uiPropIndex++;
hr = DSGetObjectProperties(MQDS_MACHINE,pwszCompName, uiPropIndex,aProp,apVar);
//
// Check foreign machine or FRS
//
ASSERT(aProp[5] == PROPID_QM_FOREIGN);
ASSERT(aProp[2] == PROPID_QM_SERVICE);
if(apVar[5].bVal != 1 && apVar[2].ulVal < SERVICE_SRV)
return(MQ_ERROR_ILLEGAL_OPERATION);
//
// If last CN refuse the operation
//
ASSERT(aProp[3] == PROPID_QM_CNS);
if(apVar[3].cauuid.cElems <= 1)
return(MQ_ERROR);
//
// Delete the CN to list of existing CN and addresses
//
ASSERT(aProp[4] == PROPID_QM_ADDRESS);
ASSERT(aProp[3] == PROPID_QM_CNS);
GUID * aguidCns = new GUID[apVar[3].cauuid.cElems];
BYTE * blobAddress = new BYTE[apVar[4].blob.cbSize];
BYTE * pSrcAddress = apVar[4].blob.pBlobData;
BYTE * pDstAddress = blobAddress;
for(DWORD i = 0, j = 0; i < apVar[3].cauuid.cElems; i++)
{
DWORD dwAddrSize = TA_ADDRESS_SIZE + ((TA_ADDRESS *)pSrcAddress)->AddressLength;
if(apVar[3].cauuid.pElems[i] == *pguidCN)
{
pSrcAddress += dwAddrSize;
continue;
}
aguidCns[j] = apVar[3].cauuid.pElems[i];
j++;
memcpy(pDstAddress, pSrcAddress, dwAddrSize);
pDstAddress += dwAddrSize;
pSrcAddress += dwAddrSize;
}
if(i == j)
{
//
// The CN is not in the list
//
return(MQ_ERROR_ILLEGAL_OPERATION);
}
DWORD dwCnCount = j;
DWORD dwAddressSize = pDstAddress - blobAddress;
//
// Set the new CN/Address properties
//
PROPID aPropSet[] = {PROPID_QM_CNS, PROPID_QM_ADDRESS};
PROPVARIANT apVarSet[sizeof(aPropSet) / sizeof(aPropSet[0])];
uiPropIndex = 0;
//
// PROPID_QM_CNS
//
apVarSet[uiPropIndex].vt = VT_CLSID|VT_VECTOR;
apVarSet[uiPropIndex].cauuid.cElems = dwCnCount;
apVarSet[uiPropIndex].cauuid.pElems = aguidCns;
uiPropIndex++;
//
// PROPID_QM_ADDRESS - Updated only in case of foreign,
// and then contains the foreign CN guids.
//
apVarSet[uiPropIndex].vt = VT_BLOB;
apVarSet[uiPropIndex].blob.cbSize = dwAddressSize;
apVarSet[uiPropIndex].blob.pBlobData = blobAddress;
uiPropIndex++;
hr = DSSetObjectProperties(MQDS_MACHINE, pwszCompName, uiPropIndex, aPropSet,apVarSet);
return hr;
}
//-------------------------------
//
//CreateForeignComputer()
//
//-------------------------------
HRESULT CreateForeignComputer( LPWSTR pwszCompName,
LPWSTR pwszSiteName,
LPWSTR pwszCNName )
{
PROPID aProp[] = { PROPID_QM_PATHNAME,
PROPID_QM_MACHINE_ID,
PROPID_QM_SITE_ID,
PROPID_QM_SERVICE,
PROPID_QM_CNS,
PROPID_QM_ADDRESS,
PROPID_QM_INFRS,
PROPID_QM_OUTFRS,
PROPID_QM_FOREIGN,
PROPID_QM_OS };
PROPVARIANT apVar[sizeof(aProp) / sizeof(aProp[0])];
UINT uiPropIndex = 0;
HRESULT hr = MQ_OK;
WCHAR wszGuid[ 128 ] ;
GUID SiteGuid ;
GUID *pguidSite;
GUID CNGuid ;
GUID *pguidCN;
BYTE Address[TA_ADDRESS_SIZE + FOREIGN_ADDRESS_LEN];
if ((pwszSiteName[0] == L'{') && (wcslen(pwszSiteName) < 100))
{
wcscpy( wszGuid, &pwszSiteName[1] ) ;
ULONG ul = wcslen(wszGuid) ;
wszGuid[ ul-1 ] = 0 ;
RPC_STATUS status = UuidFromString( wszGuid, &SiteGuid ) ;
if (status != RPC_S_OK)
{
return HRESULT_FROM_WIN32(status) ;
}
pguidSite = &SiteGuid ;
}
else
{
hr = GetSiteGuid(pwszSiteName, &pguidSite);
if(FAILED(hr))
return(hr);
}
if ((pwszCNName[0] == L'{') && (wcslen(pwszCNName) < 100))
{
wcscpy( wszGuid, &pwszCNName[1] ) ;
ULONG ul = wcslen(wszGuid) ;
wszGuid[ ul-1 ] = 0 ;
RPC_STATUS status = UuidFromString( wszGuid, &CNGuid ) ;
if (status != RPC_S_OK)
{
return HRESULT_FROM_WIN32(status) ;
}
pguidCN = &CNGuid ;
}
else
{
hr = GetCNGuid(pwszCNName, &pguidCN);
if(FAILED(hr))
return(hr);
}
((TA_ADDRESS *)Address)->AddressLength = FOREIGN_ADDRESS_LEN;
((TA_ADDRESS *)Address)->AddressType = FOREIGN_ADDRESS_TYPE;
*(GUID *)&((TA_ADDRESS *)Address)->Address = *pguidCN;
//
// PROPID_QM_PATHNAME
//
apVar[uiPropIndex].vt = VT_LPWSTR;
apVar[uiPropIndex].pwszVal = pwszCompName;
uiPropIndex++;
//
// PROPID_QM_MACHINE_ID
//
GUID guidInstance;
apVar[uiPropIndex].vt = VT_CLSID;
UuidCreate(&guidInstance);
apVar[uiPropIndex].puuid = &guidInstance;
uiPropIndex++;
//
// PROPID_QM_SITE_ID
//
apVar[uiPropIndex].vt = VT_CLSID;
apVar[uiPropIndex].puuid = pguidSite;
uiPropIndex++;
//
// PROPID_QM_SERVICE
//
apVar[uiPropIndex].vt = VT_UI4;
apVar[uiPropIndex].ulVal = SERVICE_NONE;
uiPropIndex++;
//
// PROPID_QM_CNS - has value only for foreign machine
//
apVar[uiPropIndex].vt = VT_CLSID|VT_VECTOR;
apVar[uiPropIndex].cauuid.cElems = 1;
apVar[uiPropIndex].cauuid.pElems = pguidCN;
uiPropIndex++;
//
// PROPID_QM_ADDRESS - Updated only in case of foreign,
// and then contains the foreign CN guids. Update of "real" machine
// is done only by changing the machine's properties.
//
apVar[uiPropIndex].vt = VT_BLOB;
apVar[uiPropIndex].blob.cbSize = sizeof(Address);
apVar[uiPropIndex].blob.pBlobData = &Address[0];
uiPropIndex++;
//
// PROPID_QM_INFRS
//
apVar[uiPropIndex].vt = VT_CLSID | VT_VECTOR;
apVar[uiPropIndex].cauuid.cElems = 0;
apVar[uiPropIndex].cauuid.pElems = NULL;
uiPropIndex++;
//
// PROPID_QM_OUTFRS
//
apVar[uiPropIndex].vt = VT_CLSID | VT_VECTOR;
apVar[uiPropIndex].cauuid.cElems = 0;
apVar[uiPropIndex].cauuid.pElems = NULL;
uiPropIndex++;
//
// PROPID_QM_FOREIGN
//
apVar[uiPropIndex].vt = VT_UI1;
apVar[uiPropIndex].bVal = TRUE;
uiPropIndex++;
//
// PROPID_QM_OS
//
apVar[uiPropIndex].vt = VT_UI4;
apVar[uiPropIndex].ulVal = MSMQ_OS_FOREIGN;
uiPropIndex++;
hr = DSCreateObject( MQDS_MACHINE,
pwszCompName,
0,
sizeof(aProp) / sizeof(aProp[0]),
aProp,
apVar,
NULL );
return hr;
}
//-------------------------------
//
//DeleteForeignCN()
//
//-------------------------------
HRESULT DeleteForeignCN(LPWSTR pwszCNName)
{
HRESULT hr;
hr = DSDeleteObject(MQDS_CN,pwszCNName);
return(hr);
}
//-------------------------------
//
//DeleteForeignComputer()
//
//-------------------------------
HRESULT DeleteForeignComputer(LPWSTR pwszSiteName)
{
HRESULT hr;
hr = DSDeleteObject(MQDS_MACHINE, pwszSiteName);
return(hr);
}
//+-----------------------------------------------------
//
// HRESULT StorePbkeyOnForeignMachine()
//
//+-----------------------------------------------------
HRESULT StorePbkeyOnForeignMachine( WCHAR *pwszMachineName,
WCHAR *pwszKeyName )
{
HINSTANCE hLib = LoadLibrary(TEXT("mqfrgnky.dll")) ;
if (!hLib)
{
DWORD dwErr = GetLastError() ;
return HRESULT_FROM_WIN32(dwErr) ;
}
MQFrgn_StorePubKeysInDS_ROUTINE pfnStore =
(MQFrgn_StorePubKeysInDS_ROUTINE)
GetProcAddress(hLib, "MQFrgn_StorePubKeysInDS") ;
if (!pfnStore)
{
FreeLibrary(hLib) ;
DWORD dwErr = GetLastError() ;
return HRESULT_FROM_WIN32(dwErr) ;
}
HRESULT hr = (*pfnStore) ( pwszMachineName,
pwszKeyName,
TRUE ) ;
FreeLibrary(hLib) ;
return hr ;
}
#define CREATE_CN 1
#define REMOVE_CN 2
#define ADD_CN 3
#define DEL_CN 4
#define CREATE_COMP 5
#define REMOVE_COMP 6
#define STORE_FORGN_PBKEY 7
#define OPEN_CONNECOTR_EVERYONE 8
//-------------------------------
//
//main()
//
//-------------------------------
void main(int argc, char * * argv)
{
DWORD gAction = 0;
WCHAR szCNName[100], szMachineName[100], szSiteName[100];
WCHAR wszKeyName[ 100 ] ;
HRESULT hr = 0;
BOOL fCheckNt4Ver = TRUE ;
//
// Print Title
//
printf("MSMQ Foreign objects utility. Release Version, 1.0.%u\n\n", rup);
//
// Check Time Bomb
//
// TimeBomb();
//
// Parse parameters
//
for(int i=1; i < argc; i++)
{
if(_stricmp(argv[i], "-crcn") == 0)
{
CheckArgNo(argc, 1);
gAction = CREATE_CN;
i++;
swprintf(szCNName, L"%S", argv[i]);
fCheckNt4Ver = FALSE ;
continue;
}
if(_stricmp(argv[i], "-opce") == 0)
{
CheckArgNo(argc, 1);
gAction = OPEN_CONNECOTR_EVERYONE ;
i++;
swprintf(szCNName, L"%S", argv[i]);
fCheckNt4Ver = FALSE ;
continue;
}
if(_stricmp(argv[i], "-rmcn") == 0)
{
CheckArgNo(argc, 1);
gAction = REMOVE_CN;
i++;
swprintf(szCNName, L"%S", argv[i]);
continue;
}
if(_stricmp(argv[i], "-addcn") == 0)
{
CheckArgNo(argc, 2);
gAction = ADD_CN;
i++;
swprintf(szMachineName, L"%S", argv[i]);
i++;
swprintf(szCNName, L"%S", argv[i]);
continue;
}
if(_stricmp(argv[i], "-delcn") == 0)
{
CheckArgNo(argc, 2);
gAction = DEL_CN;
i++;
swprintf(szMachineName, L"%S", argv[i]);
i++;
swprintf(szCNName, L"%S", argv[i]);
continue;
}
if(_stricmp(argv[i], "-rmcomp") == 0)
{
CheckArgNo(argc, 1);
gAction = REMOVE_COMP;
i++;
swprintf(szMachineName, L"%S", argv[i]);
continue;
}
if(_stricmp(argv[i], "-crcomp") == 0)
{
CheckArgNo(argc, 3);
gAction = CREATE_COMP;
i++;
swprintf(szMachineName, L"%S", argv[i]);
i++;
swprintf(szSiteName, L"%S", argv[i]);
i++;
swprintf(szCNName, L"%S", argv[i]);
fCheckNt4Ver = FALSE ;
continue;
}
if(_stricmp(argv[i], "-pbkey") == 0)
{
CheckArgNo(argc, 2);
gAction = STORE_FORGN_PBKEY ;
i++;
swprintf(szMachineName, L"%S", argv[i]);
i++;
swprintf(wszKeyName, L"%S", argv[i]);
fCheckNt4Ver = FALSE ;
continue;
}
if(_stricmp(argv[i], "-?") == 0)
{
Usage();
continue;
}
if(_stricmp(argv[i], "/?") == 0)
{
Usage();
continue;
}
printf("\n*** Error - Unknown switch: %s\n\n", argv[i]);
exit(-1);
}
if(gAction == 0)
{
printf("\n*** Error - no action specified\n\n");
exit(-1);
}
//
// Run this utility on NT4 enterprise only
//
if (fCheckNt4Ver)
{
CheckNT4Enterprise();
}
//
// Perform the action according to params
//
switch(gAction)
{
case CREATE_CN:
printf("Creating foreign CN %S...\n", szCNName);
hr = CreateForeignCN(szCNName) ;
break;
case OPEN_CONNECOTR_EVERYONE:
printf("Opening connector queue %S to everyone...\n", szCNName);
hr = OpenConnectorToEveryone( szCNName ) ;
break ;
case REMOVE_CN:
printf("Removing foreign CN %S...\n", szCNName);
hr = DeleteForeignCN(szCNName);
break;
case ADD_CN:
printf("Adding foreign CN %S to computer %S....\n", szCNName, szMachineName);
hr = AddForeignCN(szMachineName, szCNName);
break;
case DEL_CN:
printf("Deleting foreign CN %S from computer %S....\n", szCNName, szMachineName);
hr = DelForeignCN(szMachineName, szCNName);
break;
case CREATE_COMP:
printf("Creating foreign computer %S - Site: %S - CN: %S...\n",szMachineName,szSiteName,szCNName);
hr = CreateForeignComputer(szMachineName, szSiteName, szCNName);
break;
case REMOVE_COMP:
printf("Removing foreign computer %S...\n", szMachineName);
hr = DeleteForeignComputer(szMachineName);
break;
case STORE_FORGN_PBKEY:
printf("Storing Public Key for computer %S...\n", szMachineName) ;
hr = StorePbkeyOnForeignMachine( szMachineName, wszKeyName ) ;
break ;
default:
Usage();
break;
}
if(FAILED(hr))
ErrorExit("",hr);
printf("Done.\n");
exit(hr);
}
| 22.71489 | 126 | 0.542851 | [
"object"
] |
fe6d31b19d8194b60e5a678a619a89c67cce9520 | 20,098 | cpp | C++ | src/ga/GAStatistics.cpp | yuriyvolkov/galib | f3ca97f74f8a0318f3c0068006ea6cc0ae2adcd9 | [
"BSD-3-Clause"
] | 6 | 2017-12-07T16:19:08.000Z | 2022-03-23T09:22:11.000Z | src/ga/GAStatistics.cpp | yuriyvolkov/galib | f3ca97f74f8a0318f3c0068006ea6cc0ae2adcd9 | [
"BSD-3-Clause"
] | 3 | 2016-11-12T17:36:02.000Z | 2018-07-13T09:07:07.000Z | src/ga/GAStatistics.cpp | yuriyvolkov/galib | f3ca97f74f8a0318f3c0068006ea6cc0ae2adcd9 | [
"BSD-3-Clause"
] | 4 | 2015-09-20T18:24:39.000Z | 2021-04-09T18:26:55.000Z | // $Header$
/* ----------------------------------------------------------------------------
statistics.C
mbwall 28jul94
Copyright (c) 1995 Massachusetts Institute of Technology
all rights reserved
DESCRIPTION:
Definition of the statistics object.
---------------------------------------------------------------------------- */
#include <string.h>
#include <ga/gaerror.h>
#include <ga/GAStatistics.h>
// Default settings and their names.
int gaDefNumBestGenomes = 1;
int gaDefScoreFrequency1 = 1;
int gaDefScoreFrequency2 = 100;
int gaDefFlushFrequency = 0;
char gaDefScoreFilename[] = "generations.dat";
GAStatistics::GAStatistics()
{
curgen = 0;
numsel = numcro = nummut = numrep = numeval = numpeval = 0;
maxever = minever = 0.0;
on = offmax = offmin = 0.0;
aveInit = maxInit = minInit = devInit = 0.0;
divInit = -1.0;
aveCur = maxCur = minCur = devCur = 0.0;
divCur = -1.0;
scoreFreq = gaDefScoreFrequency1;
dodiv = gaFalse; // default is do not calculate diversity
nconv = 0;
Nconv = 10;
cscore = new float[Nconv];
memset(cscore, 0, Nconv * sizeof(float));
nscrs = 0;
Nscrs = gaDefFlushFrequency;
gen = new int[Nscrs];
memset(gen, 0, Nscrs * sizeof(int));
aveScore = new float[Nscrs];
memset(aveScore, 0, Nscrs * sizeof(float));
maxScore = new float[Nscrs];
memset(maxScore, 0, Nscrs * sizeof(float));
minScore = new float[Nscrs];
memset(minScore, 0, Nscrs * sizeof(float));
devScore = new float[Nscrs];
memset(devScore, 0, Nscrs * sizeof(float));
divScore = new float[Nscrs];
memset(divScore, 0, Nscrs * sizeof(float));
scorefile = new char[strlen(gaDefScoreFilename) + 1];
strcpy(scorefile, gaDefScoreFilename);
which = Maximum;
boa = (GAPopulation *)0;
}
GAStatistics::GAStatistics(const GAStatistics &orig)
{
cscore = (float *)0;
gen = (int *)0;
aveScore = (float *)0;
maxScore = (float *)0;
minScore = (float *)0;
devScore = (float *)0;
divScore = (float *)0;
scorefile = (char *)0;
boa = (GAPopulation *)0;
copy(orig);
}
GAStatistics::~GAStatistics()
{
delete[] cscore;
delete[] gen;
delete[] aveScore;
delete[] maxScore;
delete[] minScore;
delete[] devScore;
delete[] divScore;
delete[] scorefile;
delete boa;
}
void GAStatistics::copy(const GAStatistics &orig)
{
if (&orig == this)
return;
curgen = orig.curgen;
numsel = orig.numsel;
numcro = orig.numcro;
nummut = orig.nummut;
numrep = orig.numrep;
numeval = orig.numeval;
numpeval = orig.numpeval;
maxever = orig.maxever;
minever = orig.minever;
on = orig.on;
offmax = orig.offmax;
offmin = orig.offmin;
aveInit = orig.aveInit;
maxInit = orig.maxInit;
minInit = orig.minInit;
devInit = orig.devInit;
divInit = orig.divInit;
aveCur = orig.aveCur;
maxCur = orig.maxCur;
minCur = orig.minCur;
devCur = orig.devCur;
divCur = orig.divCur;
scoreFreq = orig.scoreFreq;
dodiv = orig.dodiv;
nconv = orig.nconv;
Nconv = orig.Nconv;
delete[] cscore;
cscore = new float[Nconv];
memcpy(cscore, orig.cscore, Nconv * sizeof(float));
nscrs = orig.nscrs;
Nscrs = orig.Nscrs;
delete[] gen;
gen = new int[Nscrs];
memcpy(gen, orig.gen, Nscrs * sizeof(int));
delete[] aveScore;
aveScore = new float[Nscrs];
memcpy(aveScore, orig.aveScore, Nscrs * sizeof(float));
delete[] maxScore;
maxScore = new float[Nscrs];
memcpy(maxScore, orig.maxScore, Nscrs * sizeof(float));
delete[] minScore;
minScore = new float[Nscrs];
memcpy(minScore, orig.minScore, Nscrs * sizeof(float));
delete[] devScore;
devScore = new float[Nscrs];
memcpy(devScore, orig.devScore, Nscrs * sizeof(float));
delete[] divScore;
divScore = new float[Nscrs];
memcpy(divScore, orig.divScore, Nscrs * sizeof(float));
delete[] scorefile;
if (orig.scorefile) {
scorefile = new char[strlen(orig.scorefile) + 1];
strcpy(scorefile, orig.scorefile);
} else
scorefile = (char *)0;
which = orig.which;
delete boa;
if (orig.boa)
boa = orig.boa->clone();
}
// Update the genomes in the 'best of all' population to reflect any
// changes made to the current population. We just grab the genomes with
// the highest scores from the current population, and if they are higher than
// those of the genomes in the boa population, they get copied. Note that
// the bigger the boa array, the bigger your running performance hit because
// we have to look through all of the boa to figure out which are better than
// those in the population. The fastest way to use the boa is to keep only
// one genome in the boa population. A flag of 'True' will reset the boa
// population so that it is filled with the best of the current population.
// Unfortunately it could take a long time to update the boa array using the
// copy method. We'd like to simply keep pointers to the best genomes, but
// the genomes change from generation to generation, so we can't depend on
// that.
// Notice that keeping boa is useful even for overlapping populations. The
// boa keeps individuals that are different from each other - the overlapping
// population may not. However, keeping boa is most useful for populations
// with little overlap.
// When we check to see if a potentially better member is already in our
// best-of-all population, we use the operator== comparator not the genome
// comparator to do the comparison.
void GAStatistics::updateBestIndividual(const GAPopulation &pop, GABoolean flag)
{
if (boa == (GAPopulation *)0 || boa->size() == 0)
return; // do nothing
if (pop.order() != boa->order())
boa->order(pop.order());
if (flag == gaTrue) { // reset the BOA array
int j = 0;
for (int i = 0; i < boa->size(); i++) {
boa->best(i).copy(pop.best(j));
if (j < pop.size() - 1)
j++;
}
return;
}
if (boa->size() == 1) { // there's only one boa so replace it with bop
if (boa->order() == GAPopulation::HIGH_IS_BEST && pop.best().score() > boa->best().score())
boa->best().copy(pop.best());
if (boa->order() == GAPopulation::LOW_IS_BEST && pop.best().score() < boa->best().score())
boa->best().copy(pop.best());
} else {
int i = 0, j, k;
if (boa->order() == GAPopulation::HIGH_IS_BEST) {
while (i < pop.size() && pop.best(i).score() > boa->worst().score()) {
for (k = 0; pop.best(i).score() < boa->best(k).score() && k < boa->size(); k++)
;
for (j = k; j < boa->size(); j++) {
if (pop.best(i) == boa->best(j))
break;
if (pop.best(i).score() > boa->best(j).score()) {
boa->worst().copy(pop.best(i)); // replace worst individual
boa->sort(gaTrue, GAPopulation::RAW); // re-sort the population
break;
}
}
i++;
}
}
if (boa->order() == GAPopulation::LOW_IS_BEST) {
while (i < pop.size() && pop.best(i).score() < boa->worst().score()) {
for (k = 0; pop.best(i).score() > boa->best(k).score() && k < boa->size(); k++)
;
for (j = k; j < boa->size(); j++) {
if (pop.best(i) == boa->best(j))
break;
if (pop.best(i).score() < boa->best(j).score()) {
boa->worst().copy(pop.best(i)); // replace worst individual
boa->sort(gaTrue, GAPopulation::RAW); // re-sort the population
break;
}
}
i++;
}
}
}
return;
}
// Use this method to update the statistics to account for the current
// population. This routine increments the generation counter and assumes that
// the population that gets passed is the current population.
// If we are supposed to flush the scores, then we dump them to the specified
// file. If no flushing frequency has been specified then we don't record.
void GAStatistics::update(const GAPopulation &pop)
{
++curgen; // must do this first so no divide-by-zero
if (scoreFreq > 0 && (curgen % scoreFreq == 0))
setScore(pop);
if (Nscrs > 0 && nscrs >= Nscrs)
flushScores();
maxever = (pop.max() > maxever) ? pop.max() : maxever;
minever = (pop.min() < minever) ? pop.min() : minever;
float tmpval;
tmpval = (on * (curgen - 1) + pop.ave()) / curgen;
on = tmpval;
tmpval = (offmax * (curgen - 1) + pop.max()) / curgen;
offmax = tmpval;
tmpval = (offmin * (curgen - 1) + pop.min()) / curgen;
offmin = tmpval;
setConvergence((pop.order() == GAPopulation::HIGH_IS_BEST) ? pop.max() : pop.min());
updateBestIndividual(pop);
numpeval = pop.nevals();
}
// Reset the GA's statistics based on the population. To do this right you
// should initialize the population before you pass it to this routine. If you
// don't, the stats will be based on a non-initialized population.
void GAStatistics::reset(const GAPopulation &pop)
{
curgen = 0;
numsel = numcro = nummut = numrep = numeval = numpeval = 0;
memset(gen, 0, Nscrs * sizeof(int));
memset(aveScore, 0, Nscrs * sizeof(float));
memset(maxScore, 0, Nscrs * sizeof(float));
memset(minScore, 0, Nscrs * sizeof(float));
memset(devScore, 0, Nscrs * sizeof(float));
memset(divScore, 0, Nscrs * sizeof(float));
nscrs = 0;
setScore(pop);
if (Nscrs > 0)
flushScores();
memset(cscore, 0, Nconv * sizeof(float));
nconv = 0; // should set to -1 then call setConv
cscore[0] = ((pop.order() == GAPopulation::HIGH_IS_BEST) ? pop.max() : pop.min());
// cscore[0] = pop.max();
// setConvergence(maxScore[0]);
updateBestIndividual(pop, gaTrue);
aveCur = aveInit = pop.ave();
maxCur = maxInit = maxever = pop.max();
minCur = minInit = minever = pop.min();
devCur = devInit = pop.dev();
divCur = divInit = ((dodiv == gaTrue) ? pop.div() : (float)-1.0);
on = pop.ave();
offmax = pop.max();
offmin = pop.min();
numpeval = pop.nevals();
for (int i = 0; i < pop.size(); i++)
numeval += pop.individual(i).nevals();
}
void GAStatistics::flushScores()
{
if (nscrs == 0)
return;
writeScores();
memset(gen, 0, Nscrs * sizeof(int));
memset(aveScore, 0, Nscrs * sizeof(float));
memset(maxScore, 0, Nscrs * sizeof(float));
memset(minScore, 0, Nscrs * sizeof(float));
memset(devScore, 0, Nscrs * sizeof(float));
memset(divScore, 0, Nscrs * sizeof(float));
nscrs = 0;
}
// Set the score info to the appropriate values. Update the score count.
void GAStatistics::setScore(const GAPopulation &pop)
{
aveCur = pop.ave();
maxCur = pop.max();
minCur = pop.min();
devCur = pop.dev();
divCur = ((dodiv == gaTrue) ? pop.div() : (float)-1.0);
if (Nscrs == 0)
return;
gen[nscrs] = curgen;
aveScore[nscrs] = aveCur;
maxScore[nscrs] = maxCur;
minScore[nscrs] = minCur;
devScore[nscrs] = devCur;
divScore[nscrs] = divCur;
nscrs++;
}
// For recording the convergence we have to keep a running list of the past N
// best scores. We just keep looping around and around the array of past
// scores. nconv keeps track of which one is the current one. The current
// item is thus nconv%Nconv. The oldest is nconv%Nconv+1 or 0.
void GAStatistics::setConvergence(float s)
{
nconv++;
cscore[nconv % Nconv] = s;
}
// When a new number of gens to conv is specified, keep all the data that we
// can in the transfer. Make sure we do it in the right order! Then just
// continue on as before.
// If someone passes us a zero then we set to 1.
int GAStatistics::nConvergence(unsigned int n)
{
if (n == 0)
n = 1;
float *tmp = cscore;
cscore = new float[n];
if (Nconv < n) {
if (nconv < Nconv) {
memcpy(cscore, tmp, (nconv + 1) * sizeof(float));
} else {
memcpy(&(cscore[Nconv - (nconv % Nconv) - 1]), tmp, ((nconv % Nconv) + 1) * sizeof(float));
memcpy(cscore, &(tmp[(nconv % Nconv) + 1]), (Nconv - (nconv % Nconv) - 1) * sizeof(float));
}
} else {
if (nconv < n) {
memcpy(cscore, tmp, (nconv + 1) * sizeof(float));
} else {
if ((nconv % Nconv) + 1 < n) {
memcpy(&(cscore[n - (nconv % Nconv) - 1]), tmp, ((nconv % Nconv) + 1) * sizeof(float));
memcpy(cscore, &(tmp[Nconv - (1 + n - (nconv % Nconv))]), sizeof(float));
} else {
memcpy(cscore, &(tmp[1 + (nconv % Nconv) - n]), n * sizeof(float));
}
}
}
Nconv = n;
delete[] tmp;
return Nconv;
}
int GAStatistics::nBestGenomes(const GAGenome &genome, unsigned int n)
{
if (n == 0) {
delete boa;
boa = (GAPopulation *)0;
} else if (boa == (GAPopulation *)0) {
boa = new GAPopulation(genome, n);
} else {
boa->size(n);
}
return n;
}
const GAGenome &GAStatistics::bestIndividual(unsigned int n) const
{
if (boa == 0 || (int)n >= boa->size()) {
GAErr(GA_LOC, "GAStatistics", "bestIndividual", gaErrBadPopIndex);
n = 0;
}
return boa->best(n); // this will crash if no boa
}
// Adjust the scores buffers to match the specified amount. If someone
// specifies zero then we don't keep the scores, so set all to NULL.
int GAStatistics::flushFrequency(unsigned int freq)
{
if (freq == 0) {
if (nscrs > 0)
flushScores();
resizeScores(freq);
} else if (freq > Nscrs) {
resizeScores(freq);
} else if (freq < Nscrs) {
if (nscrs > freq)
flushScores();
resizeScores(freq);
}
Nscrs = freq;
return freq;
}
// Resize the scores vectors to the specified amount. Copy any scores that
// exist.
void GAStatistics::resizeScores(unsigned int n)
{
int *tmpi;
float *tmpf;
if (n == 0) {
delete[] gen;
gen = (int *)0;
delete[] aveScore;
aveScore = (float *)0;
delete[] maxScore;
maxScore = (float *)0;
delete[] minScore;
minScore = (float *)0;
delete[] devScore;
devScore = (float *)0;
delete[] divScore;
divScore = (float *)0;
nscrs = n;
} else {
tmpi = gen;
gen = new int[n];
memcpy(gen, tmpi, (n < Nscrs ? n : Nscrs) * sizeof(int));
delete[] tmpi;
tmpf = aveScore;
aveScore = new float[n];
memcpy(aveScore, tmpf, (n < Nscrs ? n : Nscrs) * sizeof(float));
delete[] tmpf;
tmpf = maxScore;
maxScore = new float[n];
memcpy(maxScore, tmpf, (n < Nscrs ? n : Nscrs) * sizeof(float));
delete[] tmpf;
tmpf = minScore;
minScore = new float[n];
memcpy(minScore, tmpf, (n < Nscrs ? n : Nscrs) * sizeof(float));
delete[] tmpf;
tmpf = devScore;
devScore = new float[n];
memcpy(devScore, tmpf, (n < Nscrs ? n : Nscrs) * sizeof(float));
delete[] tmpf;
tmpf = divScore;
divScore = new float[n];
memcpy(divScore, tmpf, (n < Nscrs ? n : Nscrs) * sizeof(float));
delete[] tmpf;
if (nscrs > n)
nscrs = n;
}
Nscrs = n;
}
// Write the current scores to file. If this is the first chunk (ie gen[0]
// is 0) then we create a new file. Otherwise we append to an existing file.
// We give no notice that we're overwriting the existing file!!
void GAStatistics::writeScores()
{
if (!scorefile)
return;
#ifdef GALIB_USE_STREAMS
STD_OFSTREAM outfile(scorefile, ((gen[0] == 0) ? (STD_IOS_OUT | STD_IOS_TRUNC) : (STD_IOS_OUT | STD_IOS_APP)));
// should be done this way, but SGI systems (and others?) don't do it right...
// if(! outfile.is_open()){
if (outfile.fail()) {
GAErr(GA_LOC, "GAStatistics", "writeScores", gaErrWriteError, scorefile);
return;
}
scores(outfile, which);
outfile.close();
#endif
}
#ifdef GALIB_USE_STREAMS
int GAStatistics::write(const char *filename) const
{
STD_OFSTREAM outfile(filename, (STD_IOS_OUT | STD_IOS_TRUNC));
// should be done this way, but SGI systems (and others?) don't do it right...
// if(! outfile.is_open()){
if (outfile.fail()) {
GAErr(GA_LOC, "GAStatistics", "write", gaErrWriteError, filename);
return 1;
}
write(outfile);
outfile.close();
return 0;
}
int GAStatistics::write(STD_OSTREAM &os) const
{
os << curgen << "\t# current generation\n";
os << convergence() << "\t# current convergence\n";
os << numsel << "\t# number of selections since initialization\n";
os << numcro << "\t# number of crossovers since initialization\n";
os << nummut << "\t# number of mutations since initialization\n";
os << numrep << "\t# number of replacements since initialization\n";
os << numeval << "\t# number of genome evaluations since initialization\n";
os << numpeval << "\t# number of population evaluations since initialization\n";
os << maxever << "\t# maximum score since initialization\n";
os << minever << "\t# minimum score since initialization\n";
os << on << "\t# average of all scores ('on-line' performance)\n";
os << offmax << "\t# average of maximum scores ('off-line' performance)\n";
os << offmin << "\t# average of minimum scores ('off-line' performance)\n";
os << "\n";
os << aveInit << "\t# mean score in initial population\n";
os << maxInit << "\t# maximum score in initial population\n";
os << minInit << "\t# minimum score in initial population\n";
os << devInit << "\t# standard deviation of initial population\n";
os << divInit << "\t# diversity of initial population (0=identical,-1=unset)\n";
os << "\n";
os << aveCur << "\t# mean score in current population\n";
os << maxCur << "\t# maximum score in current population\n";
os << minCur << "\t# minimum score in current population\n";
os << devCur << "\t# standard deviation of current population\n";
os << divCur << "\t# diversity of current population (0=identical,-1=unset)\n";
os << "\n";
os << Nconv << "\t# how far back to look for convergence\n";
os << scoreFreq << "\t# how often to record scores\n";
os << Nscrs << "\t# how often to write scores to file\n";
os << scorefile << "\t# name of file to which scores are written\n";
return 0;
}
// You can specify the data that you want to dump out when you call this
// routine, or you can just let it use the selection from the object. If you
// specify a data set, that will be used rather than the 'which' in the object.
int GAStatistics::scores(const char *filename, int w)
{
STD_OFSTREAM outfile(filename, (STD_IOS_OUT | STD_IOS_TRUNC));
// should be done this way, but SGI systems (and others?) don't do it right...
// if(! outfile.is_open()){
if (outfile.fail()) {
GAErr(GA_LOC, "GAStatistics", "scores", gaErrWriteError, filename);
return 1;
}
scores(outfile, w);
outfile.close();
return 0;
}
int GAStatistics::scores(STD_OSTREAM &os, int w)
{
if (w == NoScores)
w = which;
for (unsigned int i = 0; i < nscrs; i++) {
os << gen[i];
if (w & Mean)
os << "\t" << aveScore[i];
if (w & Maximum)
os << "\t" << maxScore[i];
if (w & Minimum)
os << "\t" << minScore[i];
if (w & Deviation)
os << "\t" << devScore[i];
if (w & Diversity)
os << "\t" << divScore[i];
os << "\n";
}
return 0;
}
#endif
| 33.949324 | 115 | 0.581302 | [
"object"
] |
fe6f51ea38aa06b39ae6a483648be9363b56d917 | 6,307 | cpp | C++ | Source/Foundation/bsfCore/Managers/BsHardwareBufferManager.cpp | bsf2dev/bsf | b318cd4eb1b0299773d625e6c870b8d503cf539e | [
"MIT"
] | 1,745 | 2018-03-16T02:10:28.000Z | 2022-03-26T17:34:21.000Z | Source/Foundation/bsfCore/Managers/BsHardwareBufferManager.cpp | bsf2dev/bsf | b318cd4eb1b0299773d625e6c870b8d503cf539e | [
"MIT"
] | 395 | 2018-03-16T10:18:20.000Z | 2021-08-04T16:52:08.000Z | Source/Foundation/bsfCore/Managers/BsHardwareBufferManager.cpp | bsf2dev/bsf | b318cd4eb1b0299773d625e6c870b8d503cf539e | [
"MIT"
] | 267 | 2018-03-17T19:32:54.000Z | 2022-02-17T16:55:50.000Z | //************************************ bs::framework - Copyright 2018 Marko Pintera **************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#include "Managers/BsHardwareBufferManager.h"
#include "RenderAPI/BsVertexData.h"
#include "RenderAPI/BsGpuBuffer.h"
#include "RenderAPI/BsVertexDeclaration.h"
#include "RenderAPI/BsGpuParamBlockBuffer.h"
#include "RenderAPI/BsVertexDataDesc.h"
#include "RenderAPI/BsGpuParams.h"
namespace bs
{
SPtr<VertexDeclaration> HardwareBufferManager::createVertexDeclaration(const SPtr<VertexDataDesc>& desc)
{
VertexDeclaration* decl = new (bs_alloc<VertexDeclaration>()) VertexDeclaration(desc->createElements());
SPtr<VertexDeclaration> declPtr = bs_core_ptr<VertexDeclaration>(decl);
declPtr->_setThisPtr(declPtr);
declPtr->initialize();
return declPtr;
}
SPtr<VertexBuffer> HardwareBufferManager::createVertexBuffer(const VERTEX_BUFFER_DESC& desc)
{
SPtr<VertexBuffer> vbuf = bs_core_ptr<VertexBuffer>(new (bs_alloc<VertexBuffer>()) VertexBuffer(desc));
vbuf->_setThisPtr(vbuf);
vbuf->initialize();
return vbuf;
}
SPtr<IndexBuffer> HardwareBufferManager::createIndexBuffer(const INDEX_BUFFER_DESC& desc)
{
SPtr<IndexBuffer> ibuf = bs_core_ptr<IndexBuffer>(new (bs_alloc<IndexBuffer>()) IndexBuffer(desc));
ibuf->_setThisPtr(ibuf);
ibuf->initialize();
return ibuf;
}
SPtr<GpuParamBlockBuffer> HardwareBufferManager::createGpuParamBlockBuffer(UINT32 size, GpuBufferUsage usage)
{
SPtr<GpuParamBlockBuffer> paramBlockPtr = bs_core_ptr<GpuParamBlockBuffer>(new (bs_alloc<GpuParamBlockBuffer>()) GpuParamBlockBuffer(size, usage));
paramBlockPtr->_setThisPtr(paramBlockPtr);
paramBlockPtr->initialize();
return paramBlockPtr;
}
SPtr<GpuBuffer> HardwareBufferManager::createGpuBuffer(const GPU_BUFFER_DESC& desc)
{
SPtr<GpuBuffer> gbuf = bs_core_ptr<GpuBuffer>(new (bs_alloc<GpuBuffer>()) GpuBuffer(desc));
gbuf->_setThisPtr(gbuf);
gbuf->initialize();
return gbuf;
}
SPtr<GpuParams> HardwareBufferManager::createGpuParams(const SPtr<GpuPipelineParamInfo>& paramInfo)
{
GpuParams* params = new (bs_alloc<GpuParams>()) GpuParams(paramInfo);
SPtr<GpuParams> paramsPtr = bs_core_ptr<GpuParams>(params);
paramsPtr->_setThisPtr(paramsPtr);
paramsPtr->initialize();
return paramsPtr;
}
namespace ct
{
HardwareBufferManager::VertexDeclarationKey::VertexDeclarationKey(const Vector<VertexElement>& elements)
:elements(elements)
{ }
size_t HardwareBufferManager::VertexDeclarationKey::HashFunction::operator()(const VertexDeclarationKey& v) const
{
size_t hash = 0;
for(auto& entry : v.elements)
bs_hash_combine(hash, VertexElement::getHash(entry));
return hash;
}
bool HardwareBufferManager::VertexDeclarationKey::EqualFunction::operator()(const VertexDeclarationKey& lhs,
const VertexDeclarationKey& rhs) const
{
if (lhs.elements.size() != rhs.elements.size())
return false;
size_t numElements = lhs.elements.size();
auto iterLeft = lhs.elements.begin();
auto iterRight = rhs.elements.begin();
for(size_t i = 0; i < numElements; i++)
{
if (*iterLeft != *iterRight)
return false;
++iterLeft;
++iterRight;
}
return true;
}
SPtr<IndexBuffer> HardwareBufferManager::createIndexBuffer(const INDEX_BUFFER_DESC& desc,
GpuDeviceFlags deviceMask)
{
SPtr<IndexBuffer> ibuf = createIndexBufferInternal(desc, deviceMask);
ibuf->initialize();
return ibuf;
}
SPtr<VertexBuffer> HardwareBufferManager::createVertexBuffer(const VERTEX_BUFFER_DESC& desc,
GpuDeviceFlags deviceMask)
{
SPtr<VertexBuffer> vbuf = createVertexBufferInternal(desc, deviceMask);
vbuf->initialize();
return vbuf;
}
SPtr<VertexDeclaration> HardwareBufferManager::createVertexDeclaration(const SPtr<VertexDataDesc>& desc,
GpuDeviceFlags deviceMask)
{
Vector<VertexElement> elements = desc->createElements();
return createVertexDeclaration(elements, deviceMask);
}
SPtr<GpuParams> HardwareBufferManager::createGpuParams(const SPtr<GpuPipelineParamInfo>& paramInfo,
GpuDeviceFlags deviceMask)
{
SPtr<GpuParams> params = createGpuParamsInternal(paramInfo, deviceMask);
params->initialize();
return params;
}
SPtr<VertexDeclaration> HardwareBufferManager::createVertexDeclaration(const Vector<VertexElement>& elements,
GpuDeviceFlags deviceMask)
{
VertexDeclarationKey key(elements);
auto iterFind = mCachedDeclarations.find(key);
if (iterFind != mCachedDeclarations.end())
return iterFind->second;
SPtr<VertexDeclaration> declPtr = createVertexDeclarationInternal(elements, deviceMask);
declPtr->initialize();
mCachedDeclarations[key] = declPtr;
return declPtr;
}
SPtr<GpuParamBlockBuffer> HardwareBufferManager::createGpuParamBlockBuffer(UINT32 size,
GpuBufferUsage usage, GpuDeviceFlags deviceMask)
{
SPtr<GpuParamBlockBuffer> paramBlockPtr = createGpuParamBlockBufferInternal(size, usage, deviceMask);
paramBlockPtr->initialize();
return paramBlockPtr;
}
SPtr<GpuBuffer> HardwareBufferManager::createGpuBuffer(const GPU_BUFFER_DESC& desc,
GpuDeviceFlags deviceMask)
{
SPtr<GpuBuffer> gbuf = createGpuBufferInternal(desc, deviceMask);
gbuf->initialize();
return gbuf;
}
SPtr<GpuBuffer> HardwareBufferManager::createGpuBuffer(const GPU_BUFFER_DESC& desc,
SPtr<HardwareBuffer> underlyingBuffer)
{
SPtr<GpuBuffer> gbuf = createGpuBufferInternal(desc, std::move(underlyingBuffer));
gbuf->initialize();
return gbuf;
}
SPtr<VertexDeclaration> HardwareBufferManager::createVertexDeclarationInternal(
const Vector<VertexElement>& elements, GpuDeviceFlags deviceMask)
{
VertexDeclaration* decl = new (bs_alloc<VertexDeclaration>()) VertexDeclaration(elements, deviceMask);
SPtr<VertexDeclaration> ret = bs_shared_ptr<VertexDeclaration>(decl);
ret->_setThisPtr(ret);
return ret;
}
SPtr<GpuParams> HardwareBufferManager::createGpuParamsInternal(
const SPtr<GpuPipelineParamInfo>& paramInfo, GpuDeviceFlags deviceMask)
{
GpuParams* params = new (bs_alloc<GpuParams>()) GpuParams(paramInfo, deviceMask);
SPtr<GpuParams> paramsPtr = bs_shared_ptr<GpuParams>(params);
paramsPtr->_setThisPtr(paramsPtr);
return paramsPtr;
}
}
}
| 30.765854 | 149 | 0.759949 | [
"vector"
] |
fe7afe29b80423cb86a9eadc914ab99fa9ae399f | 15,855 | cc | C++ | src/host/Host.cc | rene-bayer/one | a61f4dea6d0868d6fd3a5cd097ee50a24c6b856f | [
"Apache-2.0"
] | 819 | 2015-01-06T20:49:04.000Z | 2022-03-29T17:07:27.000Z | src/host/Host.cc | rene-bayer/one | a61f4dea6d0868d6fd3a5cd097ee50a24c6b856f | [
"Apache-2.0"
] | 3,510 | 2015-02-11T17:42:16.000Z | 2022-03-31T17:28:22.000Z | src/host/Host.cc | rene-bayer/one | a61f4dea6d0868d6fd3a5cd097ee50a24c6b856f | [
"Apache-2.0"
] | 420 | 2015-01-06T17:44:19.000Z | 2022-03-24T09:02:02.000Z | /* ------------------------------------------------------------------------ */
/* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 "Host.h"
#include "HostPool.h"
#include "Nebula.h"
#include "ClusterPool.h"
#include "InformationManager.h"
#include "VirtualMachinePool.h"
#include <sstream>
using namespace std;
/* ************************************************************************ */
/* Host :: Constructor/Destructor */
/* ************************************************************************ */
Host::Host(
int id,
const string& _hostname,
const string& _im_mad_name,
const string& _vmm_mad_name,
int _cluster_id,
const string& _cluster_name):
PoolObjectSQL(id, HOST, _hostname, -1, -1, "", "", one_db::host_table),
ClusterableSingle(_cluster_id, _cluster_name),
state(INIT),
prev_state(INIT),
im_mad_name(_im_mad_name),
vmm_mad_name(_vmm_mad_name),
vm_collection("VMS")
{
obj_template = make_unique<HostTemplate>();
add_template_attribute("RESERVED_CPU", "");
add_template_attribute("RESERVED_MEM", "");
replace_template_attribute("IM_MAD", im_mad_name);
replace_template_attribute("VM_MAD", vmm_mad_name);
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::insert_replace(SqlDB *db, bool replace, string& error_str)
{
ostringstream oss;
int rc;
string xml_body;
char * sql_hostname;
char * sql_xml;
// Set the owner and group to oneadmin
set_user(0, "");
set_group(GroupPool::ONEADMIN_ID, GroupPool::ONEADMIN_NAME);
// Update the Host
sql_hostname = db->escape_str(name);
if ( sql_hostname == 0 )
{
goto error_hostname;
}
sql_xml = db->escape_str(to_xml(xml_body));
if ( sql_xml == 0 )
{
goto error_body;
}
if ( validate_xml(sql_xml) != 0 )
{
goto error_xml;
}
if (replace)
{
oss << "UPDATE " << one_db::host_table << " SET "
<< "name = '" << sql_hostname << "', "
<< "body = '" << sql_xml << "', "
<< "state = " << state << ", "
<< "uid = " << uid << ", "
<< "gid = " << gid << ", "
<< "owner_u = " << owner_u << ", "
<< "group_u = " << group_u << ", "
<< "other_u = " << other_u << ", "
<< "cid = " << cluster_id
<< " WHERE oid = " << oid;
}
else
{
// Construct the SQL statement to Insert or Replace
oss << "INSERT INTO "<< one_db::host_table
<<" ("<< one_db::host_db_names <<") VALUES ("
<< oid << ","
<< "'" << sql_hostname << "',"
<< "'" << sql_xml << "',"
<< state << ","
<< uid << ","
<< gid << ","
<< owner_u << ","
<< group_u << ","
<< other_u << ","
<< cluster_id << ")";
}
rc = db->exec_wr(oss);
db->free_str(sql_hostname);
db->free_str(sql_xml);
return rc;
error_xml:
db->free_str(sql_hostname);
db->free_str(sql_xml);
error_str = "Error transforming the Host to XML.";
goto error_common;
error_body:
db->free_str(sql_hostname);
goto error_generic;
error_hostname:
goto error_generic;
error_generic:
error_str = "Error inserting Host in DB.";
error_common:
return -1;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::update_info(Template &tmpl)
{
if ( state == OFFLINE )
{
return -1;
}
// -------------------------------------------------------------------------
// Remove expired information from current template
// -------------------------------------------------------------------------
clear_template_error_message();
remove_template_attribute("VM");
remove_template_attribute("VM_POLL");
// -------------------------------------------------------------------------
// Copy monitor, extract share info & update state
// -------------------------------------------------------------------------
obj_template->merge(&tmpl);
if ( state != OFFLINE && state != DISABLED )
{
state = MONITORED;
}
update_wilds();
// Update host_share
long long total_cpu, total_mem;
obj_template->get("TOTALCPU", total_cpu);
obj_template->get("TOTALMEMORY", total_mem);
if (host_share.get_total_cpu() == total_cpu &&
host_share.get_total_mem() == total_mem)
{
// No need to update cpu and memory values
obj_template->erase("TOTALCPU");
obj_template->erase("TOTALMEMORY");
host_share.set_monitorization(*obj_template);
}
else
{
// Total memory or cpu has changed, update
// reservation (may access cluster object, which is slow)
string rcpu;
string rmem;
reserved_capacity(rcpu, rmem);
host_share.set_monitorization(*obj_template, rcpu, rmem);
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
void Host::update_zombies(const set<int>& zombies)
{
remove_template_attribute("ZOMBIES");
remove_template_attribute("TOTAL_ZOMBIES");
if (zombies.empty())
{
return;
}
ostringstream zombie_str;
int num_zombies = 0;
for (auto& it: zombies)
{
if (num_zombies++ > 0)
{
zombie_str << ", ";
}
zombie_str << it;
}
add_template_attribute("TOTAL_ZOMBIES", num_zombies);
add_template_attribute("ZOMBIES", zombie_str.str());
}
/* ------------------------------------------------------------------------ */
void Host::update_wilds()
{
remove_template_attribute("WILDS");
remove_template_attribute("TOTAL_WILDS");
int num_wilds = 0;
ostringstream wild;
vector<Attribute*> vm_att;
obj_template->remove("VM", vm_att);
for (auto att : vm_att)
{
auto vatt = dynamic_cast<VectorAttribute*>(att);
if (vatt == 0)
{
delete att;
continue;
}
int vmid = -1;
int rc = vatt->vector_value("ID", vmid);
if (rc != 0)
{
delete att;
continue;
}
if (vmid == -1) //Check if it is an imported
{
VirtualMachinePool * vmpool = Nebula::instance().get_vmpool();
vmid = vmpool->get_vmid(vatt->vector_value("DEPLOY_ID"));
}
if (vmid == -1)
{
if (num_wilds++ > 0)
{
wild << ", ";
}
string wname;
wname = vatt->vector_value("VM_NAME");
if (wname.empty())
{
wname = vatt->vector_value("DEPLOY_ID");
}
wild << wname;
obj_template->set(att);
}
else
{
delete att;
}
}
if (num_wilds > 0)
{
add_template_attribute("TOTAL_WILDS", num_wilds);
add_template_attribute("WILDS", wild.str());
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Host::enable()
{
if (state == DISABLED && host_share.get_total_cpu() > 0)
{
state = MONITORED;
}
else
{
state = INIT;
}
};
/* -------------------------------------------------------------------------- */
void Host::disable()
{
state = DISABLED;
};
/* -------------------------------------------------------------------------- */
void Host::offline()
{
state = OFFLINE;
host_share.reset_capacity();
remove_template_attribute("TOTALCPU");
remove_template_attribute("TOTALMEMORY");
remove_template_attribute("FREECPU");
remove_template_attribute("FREEMEMORY");
remove_template_attribute("USEDCPU");
remove_template_attribute("USEDMEMORY");
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Host::error(const string& message)
{
ostringstream oss;
oss << "Error monitoring Host " << get_name() << " (" << get_oid() << ")"
<< ": " << message;
NebulaLog::log("ONE", Log::ERROR, oss);
if ( state != OFFLINE && state != DISABLED )
{
state = ERROR;
}
set_template_error_message(oss.str());
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
bool Host::is_public_cloud() const
{
bool is_public_cloud = false;
get_template_attribute("PUBLIC_CLOUD", is_public_cloud);
return is_public_cloud;
}
/* ************************************************************************ */
/* Host :: Misc */
/* ************************************************************************ */
string& Host::to_xml(string& xml) const
{
string template_xml;
string share_xml;
ostringstream oss;
string vm_collection_xml;
oss <<
"<HOST>"
"<ID>" << oid << "</ID>" <<
"<NAME>" << name << "</NAME>" <<
"<STATE>" << state << "</STATE>" <<
"<PREV_STATE>" << prev_state << "</PREV_STATE>" <<
"<IM_MAD>" << one_util::escape_xml(im_mad_name) << "</IM_MAD>" <<
"<VM_MAD>" << one_util::escape_xml(vmm_mad_name) << "</VM_MAD>" <<
"<CLUSTER_ID>" << cluster_id << "</CLUSTER_ID>" <<
"<CLUSTER>" << cluster << "</CLUSTER>" <<
host_share.to_xml(share_xml) <<
vm_collection.to_xml(vm_collection_xml) <<
obj_template->to_xml(template_xml) <<
monitoring.to_xml() <<
"</HOST>";
xml = oss.str();
return xml;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::from_xml(const string& xml)
{
vector<xmlNodePtr> content;
int int_state;
int int_prev_state;
int rc = 0;
// Initialize the internal XML object
update_from_str(xml);
// Get class base attributes
rc += xpath(oid, "/HOST/ID", -1);
rc += xpath(name, "/HOST/NAME", "not_found");
rc += xpath(int_state, "/HOST/STATE", 0);
rc += xpath(int_prev_state, "/HOST/PREV_STATE", 0);
rc += xpath(im_mad_name, "/HOST/IM_MAD", "not_found");
rc += xpath(vmm_mad_name, "/HOST/VM_MAD", "not_found");
rc += xpath(cluster_id, "/HOST/CLUSTER_ID", -1);
rc += xpath(cluster, "/HOST/CLUSTER", "not_found");
state = static_cast<HostState>( int_state );
prev_state = static_cast<HostState>( int_prev_state );
// Set the owner and group to oneadmin
set_user(0, "");
set_group(GroupPool::ONEADMIN_ID, GroupPool::ONEADMIN_NAME);
// ------------ Host Share ---------------
ObjectXML::get_nodes("/HOST/HOST_SHARE", content);
if (content.empty())
{
return -1;
}
rc += host_share.from_xml_node(content[0]);
ObjectXML::free_nodes(content);
content.clear();
// ------------ Host Template ---------------
ObjectXML::get_nodes("/HOST/TEMPLATE", content);
if (content.empty())
{
return -1;
}
rc += obj_template->from_xml_node(content[0]);
ObjectXML::free_nodes(content);
content.clear();
// ------------ VMS collection ---------------
rc += vm_collection.from_xml(this, "/HOST/");
if (rc != 0)
{
return -1;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Host::reserved_capacity(string& rcpu, string& rmem) const
{
get_template_attribute("RESERVED_CPU", rcpu);
get_template_attribute("RESERVED_MEM", rmem);
if (!rcpu.empty() && !rmem.empty())
{
return;
}
string cluster_rcpu = "";
string cluster_rmem = "";
if (cluster_id != -1)
{
auto cpool = Nebula::instance().get_clpool();
if (auto cluster = cpool->get_ro(cluster_id))
{
cluster->get_reserved_capacity(cluster_rcpu, cluster_rmem);
}
}
if (rcpu.empty())
{
rcpu = cluster_rcpu;
}
if (rmem.empty())
{
rmem = cluster_rmem;
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
bool Host::update_reserved_capacity(const string& ccpu, const string& cmem)
{
string rcpu;
string rmem;
get_template_attribute("RESERVED_CPU", rcpu);
get_template_attribute("RESERVED_MEM", rmem);
if (!rcpu.empty() && !rmem.empty())
{
// Do not update reserved capacity from cluster, it's defined in host
return false;
}
if (rcpu.empty())
{
rcpu = ccpu;
}
if (rmem.empty())
{
rmem = cmem;
}
host_share.update_capacity(*obj_template, rcpu, rmem);
return true;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Host::post_update_template(string& error)
{
string new_im_mad;
string new_vm_mad;
string rcpu;
string rmem;
get_template_attribute("IM_MAD", new_im_mad);
get_template_attribute("VM_MAD", new_vm_mad);
if (!new_im_mad.empty())
{
im_mad_name = new_im_mad;
}
if (!new_im_mad.empty())
{
vmm_mad_name = new_vm_mad;
}
replace_template_attribute("IM_MAD", im_mad_name);
replace_template_attribute("VM_MAD", vmm_mad_name);
reserved_capacity(rcpu, rmem);
host_share.update_capacity(*obj_template, rcpu, rmem);
return 0;
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Host::load_monitoring()
{
auto hpool = Nebula::instance().get_hpool();
monitoring = hpool->get_monitoring(oid);
}
| 26.25 | 80 | 0.446295 | [
"object",
"vector"
] |
fe7dee5b15b3ee0f62e0a6512632c27087d1b0d0 | 34,307 | cpp | C++ | MachineLearning/Entity101/opennn/simulated_annealing_order.cpp | CJBuchel/Entity101 | b868ffff4ca99e240a0bf1248d5c5ebb45019426 | [
"MIT"
] | null | null | null | MachineLearning/Entity101/opennn/simulated_annealing_order.cpp | CJBuchel/Entity101 | b868ffff4ca99e240a0bf1248d5c5ebb45019426 | [
"MIT"
] | null | null | null | MachineLearning/Entity101/opennn/simulated_annealing_order.cpp | CJBuchel/Entity101 | b868ffff4ca99e240a0bf1248d5c5ebb45019426 | [
"MIT"
] | null | null | null | /****************************************************************************************************************/
/* */
/* OpenNN: Open Neural Networks Library */
/* www.opennn.net */
/* */
/* S I M U L A T E D A N N E A L I N G O R D E R C L A S S */
/* */
/* Fernando Gomez */
/* Artelnics - Making intelligent use of data */
/* fernandogomez@artelnics.com */
/* */
/****************************************************************************************************************/
// OpenNN includes
#include "simulated_annealing_order.h"
namespace OpenNN
{
// DEFAULT CONSTRUCTOR
/// Default constructor.
SimulatedAnnealingOrder::SimulatedAnnealingOrder(void)
: OrderSelectionAlgorithm()
{
set_default();
}
// TRAINING STRATEGY CONSTRUCTOR
/// Training strategy constructor.
/// @param new_training_strategy_pointer Pointer to a training strategy object.
SimulatedAnnealingOrder::SimulatedAnnealingOrder(TrainingStrategy* new_training_strategy_pointer)
: OrderSelectionAlgorithm(new_training_strategy_pointer)
{
set_default();
}
// FILE CONSTRUCTOR
/// File constructor.
/// @param file_name Name of XML simulated annealing order file.
SimulatedAnnealingOrder::SimulatedAnnealingOrder(const std::string& file_name)
: OrderSelectionAlgorithm(file_name)
{
load(file_name);
}
// XML CONSTRUCTOR
/// XML constructor.
/// @param simulated_annealing_order_document Pointer to a TinyXML document containing the simulated annealing order data.
SimulatedAnnealingOrder::SimulatedAnnealingOrder(const tinyxml2::XMLDocument& simulated_annealing_order_document)
: OrderSelectionAlgorithm(simulated_annealing_order_document)
{
from_XML(simulated_annealing_order_document);
}
// DESTRUCTOR
/// Destructor.
SimulatedAnnealingOrder::~SimulatedAnnealingOrder(void)
{
}
// METHODS
// const double& get_cooling_rate(void) const method
/// Returns the temperature reduction factor for the simulated annealing method.
const double& SimulatedAnnealingOrder::get_cooling_rate(void) const
{
return(cooling_rate);
}
// const double& get_minimum_temperature(void) const method
/// Returns the minimum temperature reached in the simulated annealing model order selection algorithm.
const double& SimulatedAnnealingOrder::get_minimum_temperature(void) const
{
return(minimum_temperature);
}
// void set_default(void) method
/// Sets the members of the model selection object to their default values.
void SimulatedAnnealingOrder::set_default(void)
{
cooling_rate = 0.5;
minimum_temperature = 1.0e-3;
}
// void set_cooling_rate(const double&) method
/// Sets the cooling rate for the simulated annealing.
/// @param new_cooling_rate Temperature reduction factor.
void SimulatedAnnealingOrder::set_cooling_rate(const double& new_cooling_rate)
{
#ifdef __OPENNN_DEBUG__
if(new_cooling_rate <= 0)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: SimulatedAnnealingOrder class.\n"
<< "void set_cooling_rate(const size_t&) method.\n"
<< "Cooling rate must be greater than 0.\n";
throw std::logic_error(buffer.str());
}
if(new_cooling_rate >= 1)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: SimulatedAnnealingOrder class.\n"
<< "void set_cooling_rate(const size_t&) method.\n"
<< "Cooling rate must be less than 1.\n";
throw std::logic_error(buffer.str());
}
#endif
cooling_rate = new_cooling_rate;
}
// void set_minimum_temperature(const double&) method
/// Sets the minimum temperature for the simulated annealing order selection algorithm.
/// @param new_minimum_temperature Value of the minimum temperature.
void SimulatedAnnealingOrder::set_minimum_temperature(const double& new_minimum_temperature)
{
#ifdef __OPENNN_DEBUG__
if(new_minimum_temperature < 0)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: SimulatedAnnealingOrder class.\n"
<< "void set_minimum_temperature(const double&) method.\n"
<< "Minimum temperature must be equal or greater than 0.\n";
throw std::logic_error(buffer.str());
}
#endif
minimum_temperature = new_minimum_temperature;
}
// size_t get_optimal_selection_loss_index(void) const method
/// Return the index of the optimal individual of the history considering the tolerance.
size_t SimulatedAnnealingOrder::get_optimal_selection_loss_index(void) const
{
size_t index = 0;
size_t optimal_order = order_history[0];
double optimum_error = selection_loss_history[0];
size_t current_order;
double current_error;
for (size_t i = 1; i < order_history.size(); i++)
{
current_order = order_history[i];
current_error = selection_loss_history[i];
if((fabs(optimum_error-current_error) < tolerance &&
optimal_order > current_order) ||
(fabs(optimum_error-current_error) >= tolerance &&
current_error < optimum_error) )
{
optimal_order = current_order;
optimum_error = current_error;
index = i;
}
}
return(index);
}
// SimulatedAnnealingOrderResults* perform_order_selection(void) method
/// Perform the order selection with the simulated annealing method.
SimulatedAnnealingOrder::SimulatedAnnealingOrderResults* SimulatedAnnealingOrder::perform_order_selection(void)
{
SimulatedAnnealingOrderResults* results = new SimulatedAnnealingOrderResults();
NeuralNetwork* neural_network_pointer = training_strategy_pointer->get_loss_index_pointer()->get_neural_network_pointer();
MultilayerPerceptron* multilayer_perceptron_pointer = neural_network_pointer->get_multilayer_perceptron_pointer();
size_t optimal_order, current_order;
Vector<double> optimum_loss(2);
Vector<double> current_order_loss(2);
Vector<double> optimum_parameters, current_parameters;
double current_training_loss, current_selection_loss;
bool end = false;
size_t iterations = 0;
size_t random_failures = 0;
size_t upper_bound;
size_t lower_bound;
time_t beginning_time, current_time;
double elapsed_time;
double temperature;
double boltzmann_probability;
double random_uniform;
if(display)
{
std::cout << "Performing order selection with simulated annealing method..." << std::endl;
}
time(&beginning_time);
optimal_order = (size_t)(minimum_order +
calculate_random_uniform(0.,1.)*(maximum_order - minimum_order));
optimum_loss = perform_model_evaluation(optimal_order);
optimum_parameters = get_parameters_order(optimal_order);
current_training_loss = optimum_loss[0];
current_selection_loss = optimum_loss[1];
temperature = current_selection_loss;
results->order_data.push_back(optimal_order);
if(reserve_loss_data)
{
results->loss_data.push_back(current_training_loss);
}
if(reserve_selection_loss_data)
{
results->selection_loss_data.push_back(current_selection_loss);
}
if(reserve_parameters_data)
{
results->parameters_data.push_back(optimum_parameters);
}
time(¤t_time);
elapsed_time = difftime(current_time, beginning_time);
if(display)
{
std::cout << "Initial values : " << std::endl;
std::cout << "Hidden perceptrons : " << optimal_order << std::endl;
std::cout << "Final selection loss : " << optimum_loss[1] << std::endl;
std::cout << "Final Training loss : " << optimum_loss[0] << std::endl;
std::cout << "Temperature : " << temperature << std::endl;
std::cout << "Elapsed time : " << elapsed_time << std::endl;
}
while (!end){
upper_bound = std::min(maximum_order, optimal_order + (maximum_order-minimum_order)/3);
if(optimal_order <= (maximum_order-minimum_order)/3)
{
lower_bound = minimum_order;
}
else
{
lower_bound = optimal_order - (maximum_order-minimum_order)/3;
}
current_order = (size_t)(lower_bound + calculate_random_uniform(0.,1.)*(upper_bound - lower_bound));
while (current_order == optimal_order)
{
current_order = (size_t)(lower_bound + calculate_random_uniform(0.,1.)*(upper_bound - lower_bound));
random_failures++;
if(random_failures >= 5 && optimal_order != minimum_order)
{
current_order = optimal_order - 1;
}
else if(random_failures >= 5 && optimal_order != maximum_order)
{
current_order = optimal_order + 1;
}
}
#ifdef __OPENNN_MPI__
int order_int = (int)current_order;
MPI_Bcast(&order_int, 1, MPI_INT, 0, MPI_COMM_WORLD);
current_order = order_int;
#endif
random_failures = 0;
current_order_loss = perform_model_evaluation(current_order);
current_training_loss = current_order_loss[0];
current_selection_loss = current_order_loss[1];
current_parameters = get_parameters_order(current_order);
boltzmann_probability = std::min(1.0, exp(-(current_selection_loss-optimum_loss[1])/temperature));
random_uniform = calculate_random_uniform(0.,1.);
#ifdef __OPENNN_MPI__
MPI_Bcast(&random_uniform, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
if(boltzmann_probability > random_uniform)
{
optimal_order = current_order;
optimum_loss = current_order_loss;
optimum_parameters = get_parameters_order(optimal_order);
}
time(¤t_time);
elapsed_time = difftime(current_time, beginning_time);
results->order_data.push_back(current_order);
if(reserve_loss_data)
{
results->loss_data.push_back(current_training_loss);
}
if(reserve_selection_loss_data)
{
results->selection_loss_data.push_back(current_selection_loss);
}
if(reserve_parameters_data)
{
results->parameters_data.push_back(current_parameters);
}
temperature = cooling_rate*temperature;
iterations++;
// Stopping criteria
if(temperature <= minimum_temperature)
{
end = true;
if(display)
{
std::cout << "Minimum temperature reached." << std::endl;
}
results->stopping_condition = SimulatedAnnealingOrder::MinimumTemperature;
}
else if(elapsed_time > maximum_time)
{
end = true;
if(display)
{
std::cout << "Maximum time reached." << std::endl;
}
results->stopping_condition = SimulatedAnnealingOrder::MaximumTime;
}
else if(optimum_loss[1] <= selection_loss_goal)
{
end = true;
if(display)
{
std::cout << "Selection loss reached." << std::endl;
}
results->stopping_condition = SimulatedAnnealingOrder::SelectionLossGoal;
}
else if(iterations >= maximum_iterations_number)
{
end = true;
if(display)
{
std::cout << "Maximum number of iterations reached." << std::endl;
}
results->stopping_condition = SimulatedAnnealingOrder::MaximumIterations;
}
if(display)
{
std::cout << "Iteration : " << iterations << std::endl;
std::cout << "Hidden neurons number : " << optimal_order << std::endl;
std::cout << "Selection loss : " << optimum_loss[1] << std::endl;
std::cout << "Training loss : " << optimum_loss[0] << std::endl;
std::cout << "Current temperature : " << temperature << std::endl;
std::cout << "Elapsed time : " << elapsed_time << std::endl;
}
}
size_t optimal_index = get_optimal_selection_loss_index();
optimal_order = order_history[optimal_index] ;
optimum_loss[0] = loss_history[optimal_index];
optimum_loss[1] = selection_loss_history[optimal_index];
optimum_parameters = get_parameters_order(optimal_order);
if(display)
{
std::cout << "Optimal order : " << optimal_order << std::endl;
std::cout << "Optimum selection loss : " << optimum_loss[1] << std::endl;
std::cout << "Corresponding training loss : " << optimum_loss[0] << std::endl;
}
const size_t last_hidden_layer = multilayer_perceptron_pointer->get_layers_number()-2;
const size_t perceptrons_number = multilayer_perceptron_pointer->get_layer_pointer(last_hidden_layer)->get_perceptrons_number();
if(optimal_order > perceptrons_number)
{
multilayer_perceptron_pointer->grow_layer_perceptron(last_hidden_layer,optimal_order-perceptrons_number);
}
else
{
for (size_t i = 0; i < (perceptrons_number-optimal_order); i++)
{
multilayer_perceptron_pointer->prune_layer_perceptron(last_hidden_layer,0);
}
}
multilayer_perceptron_pointer->set_parameters(optimum_parameters);
#ifdef __OPENNN_MPI__
neural_network_pointer->set_multilayer_perceptron_pointer(multilayer_perceptron_pointer);
#endif
if(reserve_minimal_parameters)
{
results->minimal_parameters = optimum_parameters;
}
results->optimal_order = optimal_order;
results->final_loss = optimum_loss[0];
results->final_selection_loss = optimum_loss[1];
results->elapsed_time = elapsed_time;
results->iterations_number = iterations;
return(results);
}
// Matrix<std::string> to_string_matrix(void) const method
/// Writes as matrix of strings the most representative atributes.
Matrix<std::string> SimulatedAnnealingOrder::to_string_matrix(void) const
{
std::ostringstream buffer;
Vector<std::string> labels;
Vector<std::string> values;
// Minimum order
labels.push_back("Minimum order");
buffer.str("");
buffer << minimum_order;
values.push_back(buffer.str());
// Maximum order
labels.push_back("Maximum order");
buffer.str("");
buffer << maximum_order;
values.push_back(buffer.str());
// Step
labels.push_back("Cooling Rate");
buffer.str("");
buffer << cooling_rate;
values.push_back(buffer.str());
// Trials number
labels.push_back("Trials number");
buffer.str("");
buffer << trials_number;
values.push_back(buffer.str());
// Tolerance
labels.push_back("Tolerance");
buffer.str("");
buffer << tolerance;
values.push_back(buffer.str());
// selection loss goal
labels.push_back("Selection loss goal");
buffer.str("");
buffer << selection_loss_goal;
values.push_back(buffer.str());
// Minimum temperature
labels.push_back("Minimum temperature");
buffer.str("");
buffer << minimum_temperature;
values.push_back(buffer.str());
// Maximum iterations number
labels.push_back("Maximum iterations number");
buffer.str("");
buffer << maximum_iterations_number;
values.push_back(buffer.str());
// Maximum time
labels.push_back("Maximum time");
buffer.str("");
buffer << maximum_time;
values.push_back(buffer.str());
// Plot training loss history
labels.push_back("Plot training loss history");
buffer.str("");
if(reserve_loss_data)
{
buffer << "true";
}
else
{
buffer << "false";
}
values.push_back(buffer.str());
// Plot selection loss history
labels.push_back("Plot selection loss history");
buffer.str("");
if(reserve_selection_loss_data)
{
buffer << "true";
}
else
{
buffer << "false";
}
values.push_back(buffer.str());
const size_t rows_number = labels.size();
const size_t columns_number = 2;
Matrix<std::string> string_matrix(rows_number, columns_number);
string_matrix.set_column(0, labels);
string_matrix.set_column(1, values);
return(string_matrix);
}
// tinyxml2::XMLDocument* to_XML(void) const method
/// Prints to the screen the simulated annealing order parameters, the stopping criteria
/// and other user stuff concerning the simulated annealing order object.
tinyxml2::XMLDocument* SimulatedAnnealingOrder::to_XML(void) const
{
std::ostringstream buffer;
tinyxml2::XMLDocument* document = new tinyxml2::XMLDocument;
// Order Selection algorithm
tinyxml2::XMLElement* root_element = document->NewElement("SimulatedAnnealingOrder");
document->InsertFirstChild(root_element);
tinyxml2::XMLElement* element = NULL;
tinyxml2::XMLText* text = NULL;
// Minimum order
{
element = document->NewElement("MinimumOrder");
root_element->LinkEndChild(element);
buffer.str("");
buffer << minimum_order;
text = document->NewText(buffer.str().c_str());
element->LinkEndChild(text);
}
// Maximum order
{
element = document->NewElement("MaximumOrder");
root_element->LinkEndChild(element);
buffer.str("");
buffer << maximum_order;
text = document->NewText(buffer.str().c_str());
element->LinkEndChild(text);
}
// Cooling rate
{
element = document->NewElement("CoolingRate");
root_element->LinkEndChild(element);
buffer.str("");
buffer << cooling_rate;
text = document->NewText(buffer.str().c_str());
element->LinkEndChild(text);
}
// Trials number
{
element = document->NewElement("TrialsNumber");
root_element->LinkEndChild(element);
buffer.str("");
buffer << trials_number;
text = document->NewText(buffer.str().c_str());
element->LinkEndChild(text);
}
// Tolerance
{
element = document->NewElement("Tolerance");
root_element->LinkEndChild(element);
buffer.str("");
buffer << tolerance;
text = document->NewText(buffer.str().c_str());
element->LinkEndChild(text);
}
// selection loss goal
{
element = document->NewElement("SelectionLossGoal");
root_element->LinkEndChild(element);
buffer.str("");
buffer << selection_loss_goal;
text = document->NewText(buffer.str().c_str());
element->LinkEndChild(text);
}
// Minimum temperature
{
element = document->NewElement("MinimumTemperature");
root_element->LinkEndChild(element);
buffer.str("");
buffer << minimum_temperature;
text = document->NewText(buffer.str().c_str());
element->LinkEndChild(text);
}
// Maximum iterations
{
element = document->NewElement("MaximumIterationsNumber");
root_element->LinkEndChild(element);
buffer.str("");
buffer << maximum_iterations_number;
text = document->NewText(buffer.str().c_str());
element->LinkEndChild(text);
}
// Maximum time
{
element = document->NewElement("MaximumTime");
root_element->LinkEndChild(element);
buffer.str("");
buffer << maximum_time;
text = document->NewText(buffer.str().c_str());
element->LinkEndChild(text);
}
// Reserve loss data
{
element = document->NewElement("ReservePerformanceHistory");
root_element->LinkEndChild(element);
buffer.str("");
buffer << reserve_loss_data;
text = document->NewText(buffer.str().c_str());
element->LinkEndChild(text);
}
// Reserve selection loss data
{
element = document->NewElement("ReserveSelectionLossHistory");
root_element->LinkEndChild(element);
buffer.str("");
buffer << reserve_selection_loss_data;
text = document->NewText(buffer.str().c_str());
element->LinkEndChild(text);
}
// Performance calculation method
// {
// element = document->NewElement("PerformanceCalculationMethod");
// root_element->LinkEndChild(element);
// text = document->NewText(write_loss_calculation_method().c_str());
// element->LinkEndChild(text);
// }
// Reserve parameters data
// {
// element = document->NewElement("ReserveParametersData");
// root_element->LinkEndChild(element);
// buffer.str("");
// buffer << reserve_parameters_data;
// text = document->NewText(buffer.str().c_str());
// element->LinkEndChild(text);
// }
// Reserve minimal parameters
// {
// element = document->NewElement("ReserveMinimalParameters");
// root_element->LinkEndChild(element);
// buffer.str("");
// buffer << reserve_minimal_parameters;
// text = document->NewText(buffer.str().c_str());
// element->LinkEndChild(text);
// }
// Display
// {
// element = document->NewElement("Display");
// root_element->LinkEndChild(element);
// buffer.str("");
// buffer << display;
// text = document->NewText(buffer.str().c_str());
// element->LinkEndChild(text);
// }
return(document);
}
// void write_XML(tinyxml2::XMLPrinter&) const method
/// Serializes the simulated annealing order object into a XML document of the TinyXML library without keep the DOM tree in memory.
/// See the OpenNN manual for more information about the format of this document.
void SimulatedAnnealingOrder::write_XML(tinyxml2::XMLPrinter& file_stream) const
{
std::ostringstream buffer;
//file_stream.OpenElement("SimulatedAnnealingOrder");
// Minimum order
file_stream.OpenElement("MinimumOrder");
buffer.str("");
buffer << minimum_order;
file_stream.PushText(buffer.str().c_str());
file_stream.CloseElement();
// Maximum order
file_stream.OpenElement("MaximumOrder");
buffer.str("");
buffer << maximum_order;
file_stream.PushText(buffer.str().c_str());
file_stream.CloseElement();
// Cooling rate
file_stream.OpenElement("CoolingRate");
buffer.str("");
buffer << cooling_rate;
file_stream.PushText(buffer.str().c_str());
file_stream.CloseElement();
// Trials number
file_stream.OpenElement("TrialsNumber");
buffer.str("");
buffer << trials_number;
file_stream.PushText(buffer.str().c_str());
file_stream.CloseElement();
// Tolerance
file_stream.OpenElement("Tolerance");
buffer.str("");
buffer << tolerance;
file_stream.PushText(buffer.str().c_str());
file_stream.CloseElement();
// selection loss goal
file_stream.OpenElement("SelectionLossGoal");
buffer.str("");
buffer << selection_loss_goal;
file_stream.PushText(buffer.str().c_str());
file_stream.CloseElement();
// Minimum temperature
file_stream.OpenElement("MinimumTemperature");
buffer.str("");
buffer << minimum_temperature;
file_stream.PushText(buffer.str().c_str());
file_stream.CloseElement();
// Maximum iterations
file_stream.OpenElement("MaximumIterationsNumber");
buffer.str("");
buffer << maximum_iterations_number;
file_stream.PushText(buffer.str().c_str());
file_stream.CloseElement();
// Maximum time
file_stream.OpenElement("MaximumTime");
buffer.str("");
buffer << maximum_time;
file_stream.PushText(buffer.str().c_str());
file_stream.CloseElement();
// Reserve loss data
file_stream.OpenElement("ReservePerformanceHistory");
buffer.str("");
buffer << reserve_loss_data;
file_stream.PushText(buffer.str().c_str());
file_stream.CloseElement();
// Reserve selection loss data
file_stream.OpenElement("ReserveSelectionLossHistory");
buffer.str("");
buffer << reserve_selection_loss_data;
file_stream.PushText(buffer.str().c_str());
file_stream.CloseElement();
//file_stream.CloseElement();
}
// void from_XML(const tinyxml2::XMLDocument&) method
/// Deserializes a TinyXML document into this simulated annealing order object.
/// @param document TinyXML document containing the member data.
void SimulatedAnnealingOrder::from_XML(const tinyxml2::XMLDocument& document)
{
const tinyxml2::XMLElement* root_element = document.FirstChildElement("SimulatedAnnealingOrder");
if(!root_element)
{
std::ostringstream buffer;
buffer << "OpenNN Exception: IncrementalOrder class.\n"
<< "void from_XML(const tinyxml2::XMLDocument&) method.\n"
<< "SimulatedAnnealingOrder element is NULL.\n";
throw std::logic_error(buffer.str());
}
// Minimum order
{
const tinyxml2::XMLElement* element = root_element->FirstChildElement("MinimumOrder");
if(element)
{
const size_t new_minimum_order = atoi(element->GetText());
try
{
minimum_order = new_minimum_order;
}
catch(const std::logic_error& e)
{
std::cout << e.what() << std::endl;
}
}
}
// Maximum order
{
const tinyxml2::XMLElement* element = root_element->FirstChildElement("MaximumOrder");
if(element)
{
const size_t new_maximum_order = atoi(element->GetText());
try
{
maximum_order = new_maximum_order;
}
catch(const std::logic_error& e)
{
std::cout << e.what() << std::endl;
}
}
}
// Parameters assays number
{
const tinyxml2::XMLElement* element = root_element->FirstChildElement("TrialsNumber");
if(element)
{
const size_t new_trials_number = atoi(element->GetText());
try
{
set_trials_number(new_trials_number);
}
catch(const std::logic_error& e)
{
std::cout << e.what() << std::endl;
}
}
}
// Performance calculation method
{
const tinyxml2::XMLElement* element = root_element->FirstChildElement("PerformanceCalculationMethod");
if(element)
{
const std::string new_loss_calculation_method = element->GetText();
try
{
set_loss_calculation_method(new_loss_calculation_method);
}
catch(const std::logic_error& e)
{
std::cout << e.what() << std::endl;
}
}
}
// Cooling rate
{
const tinyxml2::XMLElement* element = root_element->FirstChildElement("CoolingRate");
if(element)
{
const double new_cooling_rate = atof(element->GetText());
try
{
set_cooling_rate(new_cooling_rate);
}
catch(const std::logic_error& e)
{
std::cout << e.what() << std::endl;
}
}
}
// Reserve parameters data
{
const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveParametersData");
if(element)
{
const std::string new_reserve_parameters_data = element->GetText();
try
{
set_reserve_parameters_data(new_reserve_parameters_data != "0");
}
catch(const std::logic_error& e)
{
std::cout << e.what() << std::endl;
}
}
}
// Reserve loss data
{
const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReservePerformanceHistory");
if(element)
{
const std::string new_reserve_loss_data = element->GetText();
try
{
set_reserve_loss_data(new_reserve_loss_data != "0");
}
catch(const std::logic_error& e)
{
std::cout << e.what() << std::endl;
}
}
}
// Reserve selection loss data
{
const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveSelectionLossHistory");
if(element)
{
const std::string new_reserve_selection_loss_data = element->GetText();
try
{
set_reserve_selection_loss_data(new_reserve_selection_loss_data != "0");
}
catch(const std::logic_error& e)
{
std::cout << e.what() << std::endl;
}
}
}
// Reserve minimal parameters
{
const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveMinimalParameters");
if(element)
{
const std::string new_reserve_minimal_parameters = element->GetText();
try
{
set_reserve_minimal_parameters(new_reserve_minimal_parameters != "0");
}
catch(const std::logic_error& e)
{
std::cout << e.what() << std::endl;
}
}
}
// Display
{
const tinyxml2::XMLElement* element = root_element->FirstChildElement("Display");
if(element)
{
const std::string new_display = element->GetText();
try
{
set_display(new_display != "0");
}
catch(const std::logic_error& e)
{
std::cout << e.what() << std::endl;
}
}
}
// selection loss goal
{
const tinyxml2::XMLElement* element = root_element->FirstChildElement("SelectionLossGoal");
if(element)
{
const double new_selection_loss_goal = atof(element->GetText());
try
{
set_selection_loss_goal(new_selection_loss_goal);
}
catch(const std::logic_error& e)
{
std::cout << e.what() << std::endl;
}
}
}
// Maximum iterations number
{
const tinyxml2::XMLElement* element = root_element->FirstChildElement("MaximumIterationsNumber");
if(element)
{
const size_t new_maximum_iterations_number = atoi(element->GetText());
try
{
set_maximum_iterations_number(new_maximum_iterations_number);
}
catch(const std::logic_error& e)
{
std::cout << e.what() << std::endl;
}
}
}
// Maximum time
{
const tinyxml2::XMLElement* element = root_element->FirstChildElement("MaximumTime");
if(element)
{
const double new_maximum_time = atoi(element->GetText());
try
{
set_maximum_time(new_maximum_time);
}
catch(const std::logic_error& e)
{
std::cout << e.what() << std::endl;
}
}
}
// Tolerance
{
const tinyxml2::XMLElement* element = root_element->FirstChildElement("Tolerance");
if(element)
{
const double new_tolerance = atof(element->GetText());
try
{
set_tolerance(new_tolerance);
}
catch(const std::logic_error& e)
{
std::cout << e.what() << std::endl;
}
}
}
// Minimum temperature
{
const tinyxml2::XMLElement* element = root_element->FirstChildElement("MinimumTemperature");
if(element)
{
const double new_minimum_temperature = atof(element->GetText());
try
{
set_minimum_temperature(new_minimum_temperature);
}
catch(const std::logic_error& e)
{
std::cout << e.what() << std::endl;
}
}
}
}
// void save(const std::string&) const method
/// Saves to a XML-type file the members of the simulated annealing order object.
/// @param file_name Name of simulated annealing order XML-type file.
void SimulatedAnnealingOrder::save(const std::string& file_name) const
{
tinyxml2::XMLDocument* document = to_XML();
document->SaveFile(file_name.c_str());
delete document;
}
// void load(const std::string&) method
/// Loads a simulated annealing order object from a XML-type file.
/// @param file_name Name of simulated annealing order XML-type file.
void SimulatedAnnealingOrder::load(const std::string& file_name)
{
set_default();
tinyxml2::XMLDocument document;
if(document.LoadFile(file_name.c_str()))
{
std::ostringstream buffer;
buffer << "OpenNN Exception: SimulatedAnnealingOrder class.\n"
<< "void load(const std::string&) method.\n"
<< "Cannot load XML file " << file_name << ".\n";
throw std::logic_error(buffer.str());
}
from_XML(document);
}
}
// OpenNN: Open Neural Networks Library.
// Copyright (c) 2005-2016 Roberto Lopez.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
| 26.248661 | 132 | 0.615268 | [
"object",
"vector",
"model"
] |
fe812d8ae0b7da9164bf5349c56d4147a7748de6 | 4,504 | hxx | C++ | opencascade/IFSelect_Transformer.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/IFSelect_Transformer.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/IFSelect_Transformer.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | // Created on: 1994-05-27
// Created by: Christian CAILLET
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IFSelect_Transformer_HeaderFile
#define _IFSelect_Transformer_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Transient.hxx>
#include <Standard_Boolean.hxx>
class Interface_Graph;
class Interface_Protocol;
class Interface_CheckIterator;
class Interface_InterfaceModel;
class TCollection_AsciiString;
class IFSelect_Transformer;
DEFINE_STANDARD_HANDLE(IFSelect_Transformer, Standard_Transient)
//! A Transformer defines the way an InterfaceModel is transformed
//! (without sending it to a file).
//! In order to work, each type of Transformer defines it method
//! Perform, it can be parametred as needed.
//!
//! It receives a Model (the data set) as input. It then can :
//! - edit this Model on the spot
//! (i.e. alter its content: by editing entities, or adding/replacing some ...)
//! - produce a copied Model, which detains the needed changes
//! (typically on the same type, but some or all entities being
//! rebuilt or converted; or converted from a protocol to another one)
class IFSelect_Transformer : public Standard_Transient
{
public:
//! Performs a Transformation (defined by each sub-class) :
//! <G> gives the input data (especially the starting model) and
//! can be used for queries (by Selections, etc...)
//! <protocol> allows to work with General Services as necessary
//! (it applies to input data)
//! If the change corresponds to a conversion to a new protocol,
//! see also the method ChangeProtocol
//! <checks> stores produced checks messages if any
//! <newmod> gives the result of the transformation :
//! - if it is Null (i.e. has not been affected), the transformation
//! has been made on the spot, it is assumed to cause no change
//! to the graph of dependances
//! - if it equates the starting Model, it has been transformed on
//! the spot (possibiliy some entities were replaced inside it)
//! - if it is new, it corresponds to a new data set which replaces
//! the starting one
//!
//! <me> is mutable to allow results for ChangeProtocol to be
//! memorized if needed, and to store information useful for
//! the method Updated
//!
//! Returns True if Done, False if an Error occurred:
//! in this case, if a new data set has been produced, the transformation is ignored,
//! else data may be corrupted.
Standard_EXPORT virtual Standard_Boolean Perform (const Interface_Graph& G, const Handle(Interface_Protocol)& protocol, Interface_CheckIterator& checks, Handle(Interface_InterfaceModel)& newmod) = 0;
//! This methods allows to declare that the Protocol applied to
//! the new Model has changed. It applies to the last call to
//! Perform.
//!
//! Returns True if the Protocol has changed, False else.
//! The provided default keeps the starting Protocol. This method
//! should be redefined as required by the effect of Perform.
Standard_EXPORT virtual Standard_Boolean ChangeProtocol (Handle(Interface_Protocol)& newproto) const;
//! This method allows to know what happened to a starting
//! entity after the last Perform. If <entfrom> (from starting
//! model) has one and only one known item which corresponds in
//! the new produced model, this method must return True and
//! fill the argument <entto>. Else, it returns False.
Standard_EXPORT virtual Standard_Boolean Updated (const Handle(Standard_Transient)& entfrom, Handle(Standard_Transient)& entto) const = 0;
//! Returns a text which defines the way a Transformer works
//! (to identify the transformation it performs)
Standard_EXPORT virtual TCollection_AsciiString Label() const = 0;
DEFINE_STANDARD_RTTIEXT(IFSelect_Transformer,Standard_Transient)
};
#endif // _IFSelect_Transformer_HeaderFile
| 44.156863 | 201 | 0.750444 | [
"model"
] |
fe8af4d0475dcf9e11e2922ab4ac95fe99a167bf | 920 | cpp | C++ | Contests/Weekly Contest 112/Most Stones Removed with Same Row or Column.cpp | shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress | 0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166 | [
"MIT"
] | 4 | 2019-12-12T19:59:50.000Z | 2020-01-20T15:44:44.000Z | Contests/Weekly Contest 112/Most Stones Removed with Same Row or Column.cpp | shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress | 0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166 | [
"MIT"
] | null | null | null | Contests/Weekly Contest 112/Most Stones Removed with Same Row or Column.cpp | shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress | 0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166 | [
"MIT"
] | null | null | null | // Question Link ---> https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/
class Solution {
public:
int removeStones(vector<vector<int>>& stones) {
queue<pair<int, int>> nodes;
int largestPossibleNumOfMoves = 0, curMaxMoves;
for (int i = 0; i < stones.size(); i++) {
if (stones[i][0] != -1) {
nodes.push({ stones[i][0], stones[i][1] });
stones[i][0] = -1; // Mark As Visited
}
curMaxMoves = 0;
while (!nodes.empty()) {
auto cur = nodes.front(); nodes.pop();
for (int i = 0; i < stones.size(); i++) {
int nx = stones[i][0], ny = stones[i][1];
if (nx != -1 && (nx == cur.first || ny == cur.second)) {
nodes.push({ stones[i][0], stones[i][1] });
stones[i][0] = -1; // Mark as visited
curMaxMoves += 1;
}
}
}
largestPossibleNumOfMoves += curMaxMoves;
}
return largestPossibleNumOfMoves;
}
}; | 32.857143 | 98 | 0.556522 | [
"vector"
] |
fe8c5e7f42f8d8e96d157d8a088631bde870f59f | 8,147 | hpp | C++ | include/antlr/Parser.hpp | zstars/booledeusto | fdc110a9add4a5946fabc2055a533593932a2003 | [
"BSD-3-Clause"
] | 6 | 2018-06-11T18:50:20.000Z | 2021-09-07T23:55:01.000Z | include/antlr/Parser.hpp | zstars/booledeusto | fdc110a9add4a5946fabc2055a533593932a2003 | [
"BSD-3-Clause"
] | null | null | null | include/antlr/Parser.hpp | zstars/booledeusto | fdc110a9add4a5946fabc2055a533593932a2003 | [
"BSD-3-Clause"
] | 2 | 2021-03-16T16:12:32.000Z | 2022-01-15T01:34:40.000Z | #ifndef INC_Parser_hpp__
#define INC_Parser_hpp__
/*
* <b>SOFTWARE RIGHTS</b>
* <p>
* ANTLR 2.7.1 MageLang Insitute, 1999, 2000, 2001
* <p>
* We reserve no legal rights to the ANTLR--it is fully in the
* public domain. An individual or company may do whatever
* they wish with source code distributed with ANTLR or the
* code generated by ANTLR, including the incorporation of
* ANTLR, or its output, into commercial software.
* <p>
* We encourage users to develop software with ANTLR. However,
* we do ask that credit is given to us for developing
* ANTLR. By "credit", we mean that if you use ANTLR or
* incorporate any source code into one of your programs
* (commercial product, research project, or otherwise) that
* you acknowledge this fact somewhere in the documentation,
* research report, etc... If you like ANTLR and have
* developed a nice tool with the output, please mention that
* you developed it using ANTLR. In addition, we ask that the
* headers remain intact in our source code. As long as these
* guidelines are kept, we expect to continue enhancing this
* system and expect to make other tools available as they are
* completed.
* <p>
* The ANTLR gang:
* @version ANTLR 2.7.1 MageLang Insitute, 1999, 2000, 2001
* @author Terence Parr, <a href=http://www.MageLang.com>MageLang Institute</a>
* @author <br>John Lilley, <a href=http://www.Empathy.com>Empathy Software</a>
* @author <br><a href="mailto:pete@yamuna.demon.co.uk">Pete Wells</a>
*/
#include <antlr/config.hpp>
#include <antlr/BitSet.hpp>
#include <antlr/TokenBuffer.hpp>
#include <antlr/RecognitionException.hpp>
#include <antlr/ASTFactory.hpp>
#include <antlr/ParserSharedInputState.hpp>
#include <exception>
#ifdef ANTLR_CXX_SUPPORTS_NAMESPACE
namespace antlr {
#endif
extern bool DEBUG_PARSER;
/** A generic ANTLR parser (LL(k) for k>=1) containing a bunch of
* utility routines useful at any lookahead depth. We distinguish between
* the LL(1) and LL(k) parsers because of efficiency. This may not be
* necessary in the near future.
*
* Each parser object contains the state of the parse including a lookahead
* cache (the form of which is determined by the subclass), whether or
* not the parser is in guess mode, where tokens come from, etc...
*
* <p>
* During <b>guess</b> mode, the current lookahead token(s) and token type(s)
* cache must be saved because the token stream may not have been informed
* to save the token (via <tt>mark</tt>) before the <tt>try</tt> block.
* Guessing is started by:
* <ol>
* <li>saving the lookahead cache.
* <li>marking the current position in the TokenBuffer.
* <li>increasing the guessing level.
* </ol>
*
* After guessing, the parser state is restored by:
* <ol>
* <li>restoring the lookahead cache.
* <li>rewinding the TokenBuffer.
* <li>decreasing the guessing level.
* </ol>
*
* @see antlr.Token
* @see antlr.TokenBuffer
* @see antlr.TokenStream
* @see antlr.LL1Parser
* @see antlr.LLkParser
*
* @todo add constructors with ASTFactory.
*/
class ANTLR_API Parser {
protected:
Parser(TokenBuffer& input_);
Parser(TokenBuffer* input_);
Parser(const ParserSharedInputState& state);
public:
virtual ~Parser();
/** Return the token type of the ith token of lookahead where i=1
* is the current token being examined by the parser (i.e., it
* has not been matched yet).
*/
virtual int LA(int i)=0;
/// Return the i-th token of lookahead
virtual RefToken LT(int i)=0;
/** DEPRECATED! Specify the factory to be used during tree building. (Compulsory)
* Setting the factory is nowadays compulsory.
* @see setASTFactory
*/
virtual void setASTNodeFactory( ASTFactory *factory )
{
astFactory = factory;
}
/** Specify the factory to be used during tree building. (Compulsory)
* Setting the factory is nowadays compulsory.
*/
virtual void setASTFactory( ASTFactory *factory )
{
astFactory = factory;
}
/** Return a pointer to the ASTFactory used.
* So you might use it in subsequent treewalkers or to reload AST's
* from disk.
*/
virtual ASTFactory* getASTFactory()
{
return astFactory;
}
/// Get the root AST node of the generated AST.
inline RefAST getAST()
{
return returnAST;
}
/// Return the filename of the input file.
virtual inline ANTLR_USE_NAMESPACE(std)string getFilename() const
{
return inputState->filename;
}
/// Set the filename of the input file (used for error reporting).
virtual void setFilename(const ANTLR_USE_NAMESPACE(std)string& f)
{
inputState->filename = f;
}
virtual void setInputState(ParserSharedInputState state)
{
inputState = state;
}
virtual inline ParserSharedInputState getInputState() const
{
return inputState;
}
/// Get another token object from the token stream
virtual void consume()=0;
/// Consume tokens until one matches the given token
virtual void consumeUntil(int tokenType);
/// Consume tokens until one matches the given token set
virtual void consumeUntil(const BitSet& set);
/** Make sure current lookahead symbol matches token type <tt>t</tt>.
* Throw an exception upon mismatch, which is catch by either the
* error handler or by the syntactic predicate.
*/
virtual void match(int t);
virtual void matchNot(int t);
/** Make sure current lookahead symbol matches the given set
* Throw an exception upon mismatch, which is catch by either the
* error handler or by the syntactic predicate.
*/
virtual void match(const BitSet& b);
/** Mark a spot in the input and return the position.
* Forwarded to TokenBuffer.
*/
virtual inline int mark()
{
return inputState->getInput().mark();
}
/// rewind to a previously marked position
virtual inline void rewind(int pos)
{
inputState->getInput().rewind(pos);
}
/// Parser error-reporting function can be overridden in subclass
virtual void reportError(const RecognitionException& ex);
/// Parser error-reporting function can be overridden in subclass
virtual void reportError(const ANTLR_USE_NAMESPACE(std)string& s);
/// Parser warning-reporting function can be overridden in subclass
virtual void reportWarning(const ANTLR_USE_NAMESPACE(std)string& s);
static void panic();
/// get the token name for the token number 'num'
virtual const char* getTokenName(int num) const = 0;
/// get a vector with all token names
virtual const char* const* getTokenNames() const = 0;
/// get the number of tokens defined
/** get the max token number
* This one should be overridden in subclasses.
*/
virtual int getNumTokens(void) const = 0;
/** Set or change the input token buffer */
// void setTokenBuffer(TokenBuffer<Token>* t);
virtual void traceIndent();
virtual void traceIn(const char* rname);
virtual void traceOut(const char* rname);
protected:
// void setTokenNames(const char** tokenNames_);
ParserSharedInputState inputState;
/// AST return value for a rule is squirreled away here
RefAST returnAST;
/// AST support code; parser and treeparser delegate to this object
ASTFactory *astFactory;
// used to keep track of the indentation for the trace
int traceDepth;
/** Utility class which allows tracing to work even when exceptions are
* thrown.
*/
class Tracer { /*{{{*/
private:
Parser* parser;
const char* text;
public:
Tracer(Parser* p,const char * t)
: parser(p), text(t)
{
parser->traceIn(text);
}
~Tracer()
{
#ifdef ANTLR_CXX_SUPPORTS_UNCAUGHT_EXCEPTION
// Only give trace if there's no uncaught exception..
if(!ANTLR_USE_NAMESPACE(std)uncaught_exception())
#endif
parser->traceOut(text);
}
private:
Tracer(const Tracer&); // undefined
const Tracer& operator=(const Tracer&); // undefined
/*}}}*/
};
private:
Parser(const Parser&); // undefined
const Parser& operator=(const Parser&); // undefined
};
#ifdef ANTLR_CXX_SUPPORTS_NAMESPACE
}
#endif
#endif //INC_Parser_hpp__
| 31.334615 | 83 | 0.701976 | [
"object",
"vector"
] |
fe8d553780264ebeb5b3341946fd5f88e7ce5625 | 10,528 | cpp | C++ | Gems/TextureAtlas/Code/Source/TextureAtlasSystemComponent.cpp | Schneidex69/o3de | d9ec159f0e07ff86957e15212232413c4ff4d1dc | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-19T23:54:05.000Z | 2021-07-19T23:54:05.000Z | Gems/TextureAtlas/Code/Source/TextureAtlasSystemComponent.cpp | Schneidex69/o3de | d9ec159f0e07ff86957e15212232413c4ff4d1dc | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/TextureAtlas/Code/Source/TextureAtlasSystemComponent.cpp | Schneidex69/o3de | d9ec159f0e07ff86957e15212232413c4ff4d1dc | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "TextureAtlas_precompiled.h"
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
#include <AzCore/IO/FileIO.h>
#include <AzFramework/API/ApplicationAPI.h>
#include "TextureAtlasSystemComponent.h"
#include "TextureAtlasImpl.h"
#include <AzCore/Asset/AssetManagerBus.h>
#include <AzFramework/StringFunc/StringFunc.h>
#include <Atom/RPI.Public/Image/StreamingImage.h>
namespace
{
AZ::Data::Instance<AZ::RPI::Image> LoadAtlasImage(const AZStd::string& imagePath)
{
// The file may not be in the AssetCatalog at this point if it is still processing or doesn't exist on disk.
// Use GenerateAssetIdTEMP instead of GetAssetIdByPath so that it will return a valid AssetId anyways
AZ::Data::AssetId streamingImageAssetId;
AZ::Data::AssetCatalogRequestBus::BroadcastResult(
streamingImageAssetId, &AZ::Data::AssetCatalogRequestBus::Events::GenerateAssetIdTEMP,
imagePath.c_str());
streamingImageAssetId.m_subId = AZ::RPI::StreamingImageAsset::GetImageAssetSubId();
auto streamingImageAsset = AZ::Data::AssetManager::Instance().FindOrCreateAsset<AZ::RPI::StreamingImageAsset>(streamingImageAssetId, AZ::Data::AssetLoadBehavior::PreLoad);
AZ::Data::Instance<AZ::RPI::Image> image = AZ::RPI::StreamingImage::FindOrCreate(streamingImageAsset);
return image;
}
}
namespace TextureAtlasNamespace
{
void TextureAtlasSystemComponent::Reflect(AZ::ReflectContext* context)
{
if (AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context))
{
serialize->Class<TextureAtlasSystemComponent, AZ::Component>()
->Version(0)
->Attribute(AZ::Edit::Attributes::SystemComponentTags, AZStd::vector<AZ::Crc32>({ AZ_CRC("AssetBuilder", 0xc739c7d7) }));
;
if (AZ::EditContext* ec = serialize->GetEditContext())
{
ec->Class<TextureAtlasSystemComponent>(
"TextureAtlas", "This component loads and manages TextureAtlases")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System"))
->Attribute(AZ::Edit::Attributes::AutoExpand, true);
}
}
TextureAtlasImpl::Reflect(context);
}
void TextureAtlasSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
{
provided.push_back(AZ_CRC("TextureAtlasService"));
}
void
TextureAtlasSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
{
incompatible.push_back(AZ_CRC("TextureAtlasService"));
}
void TextureAtlasSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
{
(void)required;
}
void TextureAtlasSystemComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent)
{
(void)dependent;
}
void TextureAtlasSystemComponent::Init() { }
void TextureAtlasSystemComponent::Activate()
{
TextureAtlasRequestBus::Handler::BusConnect();
AzFramework::AssetCatalogEventBus::Handler::BusConnect();
}
void TextureAtlasSystemComponent::Deactivate()
{
TextureAtlasRequestBus::Handler::BusDisconnect();
AzFramework::AssetCatalogEventBus::Handler::BusDisconnect();
}
void TextureAtlasSystemComponent::OnCatalogAssetChanged(const AZ::Data::AssetId& assetId)
{
for (auto iterator = m_atlases.begin(); iterator != m_atlases.end(); ++iterator)
{
if (iterator->second.m_atlasAssetId == assetId)
{
TextureAtlasImpl* input = AZ::Utils::LoadObjectFromFile<TextureAtlasImpl>(iterator->second.m_path);
reinterpret_cast<TextureAtlasImpl*>(iterator->second.m_atlas)->OverwriteMappings(input);
delete input;
// We reload the image here to prevent stuttering in the editor
if (iterator->second.m_atlas && iterator->second.m_atlas->GetTexture())
{
iterator->second.m_atlas->GetTexture().reset();
}
AZStd::string imagePath = iterator->second.m_path;
AZ::Data::Instance<AZ::RPI::Image> texture = LoadAtlasImage(imagePath);
if (!texture)
{
AZ_Error("TextureAtlasSystemComponent",
false,
"Failed to find or create an image instance for texture atlas '%s'"
"NOTE: File must be in current project or a gem.",
imagePath.c_str());
TextureAtlas* temp = iterator->second.m_atlas;
m_atlases.erase(iterator->first);
TextureAtlasNotificationBus::Broadcast(&TextureAtlasNotifications::OnAtlasUnloaded, temp);
return;
}
iterator->second.m_atlas->SetTexture(texture);
TextureAtlasNotificationBus::Broadcast(&TextureAtlasNotifications::OnAtlasReloaded, iterator->second.m_atlas);
break;
}
}
}
void TextureAtlasSystemComponent::SaveAtlasToFile(
const AZStd::string& outputPath,
AtlasCoordinateSets& handles,
int width,
int height)
{
TextureAtlasImpl atlas(handles);
atlas.SetWidth(width);
atlas.SetHeight(height);
AZ::Utils::SaveObjectToFile(outputPath, AZ::DataStream::StreamType::ST_XML, &(atlas));
}
// Attempts to load an atlas from file
TextureAtlas* TextureAtlasSystemComponent::LoadAtlas(const AZStd::string& filePath)
{
// Dont use an empty string as a path
if (filePath.empty())
{
return nullptr;
}
// Normalize the file path
AZStd::string path = filePath;
AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::NormalizePath, path);
// Check if the atlas is already loaded
AZStd::string assetPath = path;
AzFramework::StringFunc::Path::ReplaceExtension(assetPath, "texatlasidx");
auto iterator = m_atlases.find(assetPath);
if (iterator != m_atlases.end())
{
iterator->second.m_refs++;
return iterator->second.m_atlas;
}
// If it isn't loaded, load it
// Open the file
AZ::IO::FileIOBase* input = AZ::IO::FileIOBase::GetInstance();
AZ::IO::HandleType handle;
input->Open(assetPath.c_str(), AZ::IO::OpenMode::ModeRead, handle);
// Read the file
AZ::u64 size;
input->Size(handle, size);
char* buffer = new char[size + 1];
input->Read(handle, buffer, size);
buffer[size] = 0;
// Close the file
input->Close(handle);
TextureAtlas* loadedAtlas = AZ::Utils::LoadObjectFromBuffer<TextureAtlasImpl>(buffer, size);
delete[] buffer;
if (loadedAtlas)
{
// Convert to image path based on the atlas path
AZStd::string imagePath = path;
AzFramework::StringFunc::Path::ReplaceExtension(imagePath, "texatlas");
AZ::Data::Instance<AZ::RPI::Image> texture = LoadAtlasImage(imagePath);
if (!texture)
{
AZ_Error("TextureAtlasSystemComponent",
false,
"Failed to find or create an image instance for texture atlas '%s'"
"NOTE: File must be in current project or a gem.",
path.c_str());
delete loadedAtlas;
return nullptr;
}
else
{
// Add the atlas to the list
AtlasInfo info(loadedAtlas, assetPath);
++info.m_refs;
loadedAtlas->SetTexture(texture);
AZ::Data::AssetCatalogRequestBus::BroadcastResult(info.m_atlasAssetId, &AZ::Data::AssetCatalogRequests::GetAssetIdByPath, assetPath.c_str(),
info.m_atlasAssetId.TYPEINFO_Uuid(), false);
m_atlases[assetPath] = info;
TextureAtlasNotificationBus::Broadcast(&TextureAtlasNotifications::OnAtlasLoaded, loadedAtlas);
}
}
return loadedAtlas;
}
// Lowers the ref count on an atlas. If the ref count it less than one, deletes the atlas
void TextureAtlasSystemComponent::UnloadAtlas(TextureAtlas* atlas)
{
// Check if the atlas is loaded
for (auto iterator = m_atlases.begin(); iterator != m_atlases.end(); ++iterator)
{
if (iterator->second.m_atlas == atlas)
{
--iterator->second.m_refs;
if (iterator->second.m_refs < 1 && iterator->second.m_atlas->GetTexture())
{
AtlasInfo temp = iterator->second;
m_atlases.erase(iterator->first);
TextureAtlasNotificationBus::Broadcast(&TextureAtlasNotifications::OnAtlasUnloaded, temp.m_atlas);
// Tell the renderer to release the texture.
if (temp.m_atlas && temp.m_atlas->GetTexture())
{
temp.m_atlas->GetTexture().reset();
}
// Delete the atlas
SAFE_DELETE(temp.m_atlas);
}
return;
}
}
}
// Searches for an atlas that contains an image
TextureAtlas* TextureAtlasSystemComponent::FindAtlasContainingImage(const AZStd::string& filePath)
{
// Check all atlases
for (auto iterator = m_atlases.begin(); iterator != m_atlases.end(); ++iterator)
{
if (iterator->second.m_atlas->GetAtlasCoordinates(filePath).GetWidth() > 0)
{
// If we we found the image return the pointer to the atlas
return iterator->second.m_atlas;
}
}
return nullptr;
}
}
| 39.728302 | 179 | 0.608568 | [
"vector",
"3d"
] |
fe8fbbae4b90a23b24f0f3621da2f52e887c31d2 | 2,596 | cc | C++ | src/base64.cc | StevenYCChou/metadata-agent | 31fe5ca0cc6075fb233c3609cab91747503e54e2 | [
"Apache-2.0"
] | 15 | 2018-02-05T19:44:40.000Z | 2021-07-10T01:38:38.000Z | src/base64.cc | Stackdriver/metadata-agent | 85d4f5a570911ddbc2cd0be2a87fa186694140d3 | [
"Apache-2.0"
] | 61 | 2018-01-31T22:04:29.000Z | 2019-07-29T12:07:10.000Z | src/base64.cc | StevenYCChou/metadata-agent | 31fe5ca0cc6075fb233c3609cab91747503e54e2 | [
"Apache-2.0"
] | 11 | 2018-01-25T17:03:49.000Z | 2022-01-15T10:09:06.000Z | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
#include "base64.h"
#include <vector>
namespace base64 {
namespace {
constexpr const unsigned char base64url_chars[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
}
// See http://stackoverflow.com/questions/180947.
std::string Encode(const std::string &source) {
std::string result;
#if 0
const std::size_t remainder = (source.size() - 1) % 3;
for (std::size_t i = 0; i < source.size(); i += 3) {
const bool one_more = i < source.size() - 3 || remainder > 0;
const bool two_more = i < source.size() - 3 || remainder > 1;
const unsigned char c0 = source[i];
const unsigned char c1 = one_more ? source[i + 1] : 0u;
const unsigned char c2 = two_more ? source[i + 2] : 0u;
result.push_back(base64url_chars[0x3f & c0 >> 2]);
result.push_back(base64url_chars[(0x3f & c0 << 4) | c1 >> 4]);
if (one_more) {
result.push_back(base64url_chars[(0x3f & c1 << 2) | c2 >> 6]);
}
if (two_more) {
result.push_back(base64url_chars[0x3f & c2]);
}
}
#else
unsigned int code_buffer = 0;
int code_buffer_size = -6;
for (unsigned char c : source) {
code_buffer = (code_buffer << 8) | c;
code_buffer_size += 8;
while (code_buffer_size >= 0) {
result.push_back(base64url_chars[(code_buffer >> code_buffer_size) & 0x3f]);
code_buffer_size -= 6;
}
}
if (code_buffer_size > -6) {
code_buffer = (code_buffer << 8);
code_buffer_size += 8;
result.push_back(base64url_chars[(code_buffer >> code_buffer_size) & 0x3f]);
}
#endif
// No padding needed.
return result;
}
std::string Decode(const std::string &source) {
std::string result;
std::vector<int> T(256, -1);
for (int i = 0; i < 64; i++) T[base64url_chars[i]] = i;
int val = 0, shift = -8;
for (char c : source) {
if (T[c] == -1) break;
val = (val << 6) + T[c];
shift += 6;
if (shift >= 0) {
result.push_back(char((val >> shift) & 0xFF));
shift -= 8;
}
}
return result;
}
}
| 28.844444 | 82 | 0.641371 | [
"vector"
] |
fe928aaf457dae6d18a25eb1e7c67dd1847151c5 | 6,742 | hpp | C++ | openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/include/xyz/openbmc_project/User/AccountPolicy/server.hpp | sotaoverride/backup | ca53a10b72295387ef4948a9289cb78ab70bc449 | [
"Apache-2.0"
] | null | null | null | openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/include/xyz/openbmc_project/User/AccountPolicy/server.hpp | sotaoverride/backup | ca53a10b72295387ef4948a9289cb78ab70bc449 | [
"Apache-2.0"
] | null | null | null | openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/include/xyz/openbmc_project/User/AccountPolicy/server.hpp | sotaoverride/backup | ca53a10b72295387ef4948a9289cb78ab70bc449 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <map>
#include <string>
#include <sdbusplus/sdbus.hpp>
#include <sdbusplus/server.hpp>
#include <systemd/sd-bus.h>
#include <tuple>
#include <variant>
namespace sdbusplus
{
namespace xyz
{
namespace openbmc_project
{
namespace User
{
namespace server
{
class AccountPolicy
{
public:
/* Define all of the basic class operations:
* Not allowed:
* - Default constructor to avoid nullptrs.
* - Copy operations due to internal unique_ptr.
* - Move operations due to 'this' being registered as the
* 'context' with sdbus.
* Allowed:
* - Destructor.
*/
AccountPolicy() = delete;
AccountPolicy(const AccountPolicy&) = delete;
AccountPolicy& operator=(const AccountPolicy&) = delete;
AccountPolicy(AccountPolicy&&) = delete;
AccountPolicy& operator=(AccountPolicy&&) = delete;
virtual ~AccountPolicy() = default;
/** @brief Constructor to put object onto bus at a dbus path.
* @param[in] bus - Bus to attach to.
* @param[in] path - Path to attach at.
*/
AccountPolicy(bus::bus& bus, const char* path);
using PropertiesVariant = std::variant<
uint16_t,
uint8_t,
uint32_t>;
/** @brief Constructor to initialize the object from a map of
* properties.
*
* @param[in] bus - Bus to attach to.
* @param[in] path - Path to attach at.
* @param[in] vals - Map of property name to value for initialization.
*/
AccountPolicy(bus::bus& bus, const char* path,
const std::map<std::string, PropertiesVariant>& vals,
bool skipSignal = false);
/** Get value of MaxLoginAttemptBeforeLockout */
virtual uint16_t maxLoginAttemptBeforeLockout() const;
/** Set value of MaxLoginAttemptBeforeLockout with option to skip sending signal */
virtual uint16_t maxLoginAttemptBeforeLockout(uint16_t value,
bool skipSignal);
/** Set value of MaxLoginAttemptBeforeLockout */
virtual uint16_t maxLoginAttemptBeforeLockout(uint16_t value);
/** Get value of AccountUnlockTimeout */
virtual uint32_t accountUnlockTimeout() const;
/** Set value of AccountUnlockTimeout with option to skip sending signal */
virtual uint32_t accountUnlockTimeout(uint32_t value,
bool skipSignal);
/** Set value of AccountUnlockTimeout */
virtual uint32_t accountUnlockTimeout(uint32_t value);
/** Get value of MinPasswordLength */
virtual uint8_t minPasswordLength() const;
/** Set value of MinPasswordLength with option to skip sending signal */
virtual uint8_t minPasswordLength(uint8_t value,
bool skipSignal);
/** Set value of MinPasswordLength */
virtual uint8_t minPasswordLength(uint8_t value);
/** Get value of RememberOldPasswordTimes */
virtual uint8_t rememberOldPasswordTimes() const;
/** Set value of RememberOldPasswordTimes with option to skip sending signal */
virtual uint8_t rememberOldPasswordTimes(uint8_t value,
bool skipSignal);
/** Set value of RememberOldPasswordTimes */
virtual uint8_t rememberOldPasswordTimes(uint8_t value);
/** @brief Sets a property by name.
* @param[in] _name - A string representation of the property name.
* @param[in] val - A variant containing the value to set.
*/
void setPropertyByName(const std::string& _name,
const PropertiesVariant& val,
bool skipSignal = false);
/** @brief Gets a property by name.
* @param[in] _name - A string representation of the property name.
* @return - A variant containing the value of the property.
*/
PropertiesVariant getPropertyByName(const std::string& _name);
private:
/** @brief sd-bus callback for get-property 'MaxLoginAttemptBeforeLockout' */
static int _callback_get_MaxLoginAttemptBeforeLockout(
sd_bus*, const char*, const char*, const char*,
sd_bus_message*, void*, sd_bus_error*);
/** @brief sd-bus callback for set-property 'MaxLoginAttemptBeforeLockout' */
static int _callback_set_MaxLoginAttemptBeforeLockout(
sd_bus*, const char*, const char*, const char*,
sd_bus_message*, void*, sd_bus_error*);
/** @brief sd-bus callback for get-property 'AccountUnlockTimeout' */
static int _callback_get_AccountUnlockTimeout(
sd_bus*, const char*, const char*, const char*,
sd_bus_message*, void*, sd_bus_error*);
/** @brief sd-bus callback for set-property 'AccountUnlockTimeout' */
static int _callback_set_AccountUnlockTimeout(
sd_bus*, const char*, const char*, const char*,
sd_bus_message*, void*, sd_bus_error*);
/** @brief sd-bus callback for get-property 'MinPasswordLength' */
static int _callback_get_MinPasswordLength(
sd_bus*, const char*, const char*, const char*,
sd_bus_message*, void*, sd_bus_error*);
/** @brief sd-bus callback for set-property 'MinPasswordLength' */
static int _callback_set_MinPasswordLength(
sd_bus*, const char*, const char*, const char*,
sd_bus_message*, void*, sd_bus_error*);
/** @brief sd-bus callback for get-property 'RememberOldPasswordTimes' */
static int _callback_get_RememberOldPasswordTimes(
sd_bus*, const char*, const char*, const char*,
sd_bus_message*, void*, sd_bus_error*);
/** @brief sd-bus callback for set-property 'RememberOldPasswordTimes' */
static int _callback_set_RememberOldPasswordTimes(
sd_bus*, const char*, const char*, const char*,
sd_bus_message*, void*, sd_bus_error*);
static constexpr auto _interface = "xyz.openbmc_project.User.AccountPolicy";
static const vtable::vtable_t _vtable[];
sdbusplus::server::interface::interface
_xyz_openbmc_project_User_AccountPolicy_interface;
sdbusplus::SdBusInterface *_intf;
uint16_t _maxLoginAttemptBeforeLockout{};
uint32_t _accountUnlockTimeout{};
uint8_t _minPasswordLength{};
uint8_t _rememberOldPasswordTimes{};
};
} // namespace server
} // namespace User
} // namespace openbmc_project
} // namespace xyz
} // namespace sdbusplus
| 39.197674 | 91 | 0.633047 | [
"object"
] |
fe92c1d84c63da1a9ce4b3ae92076b8769b565c0 | 783 | cpp | C++ | Grade_10/Second_Semester/dijsktra_permutation.cpp | MagicWinnie/SESC_IT | 934ac49a177bfa5d02fc3234d31c929aad3c60c2 | [
"MIT"
] | 2 | 2020-10-10T10:21:49.000Z | 2021-05-28T18:10:42.000Z | Grade_10/Second_Semester/dijsktra_permutation.cpp | MagicWinnie/SESC_IT | 934ac49a177bfa5d02fc3234d31c929aad3c60c2 | [
"MIT"
] | null | null | null | Grade_10/Second_Semester/dijsktra_permutation.cpp | MagicWinnie/SESC_IT | 934ac49a177bfa5d02fc3234d31c929aad3c60c2 | [
"MIT"
] | null | null | null | // Generate next alphabetic permutation using dijsktra algorithm
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void print_vec(vector<int> arr)
{
for (auto &c: arr) cout << c << " ";
cout << endl;
}
int main()
{
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++) cin >> arr[i];
for (int i = n - 2; i >= 0; i--)
{
if (arr[i] < arr[i + 1])
{
int m = arr[i + 1];
int ind = i + 1;
for (int j = i + 1; j < n; j++)
if (arr[i] < arr[j] && arr[j] < m) { m = arr[j]; ind = j; }
swap(arr[i], arr[ind]);
sort(arr.begin() + (i + 1), arr.end());
print_vec(arr);
break;
}
}
} | 19.575 | 75 | 0.431673 | [
"vector"
] |
fe963407c5ab163227a4b46eb86b66b581b9606c | 4,412 | cpp | C++ | portal/src/levelsettingsdialog.cpp | zfrye06/Loque | bbb0e7a0a5d5374c27b83bba5b13bc191b03ebb0 | [
"MIT"
] | null | null | null | portal/src/levelsettingsdialog.cpp | zfrye06/Loque | bbb0e7a0a5d5374c27b83bba5b13bc191b03ebb0 | [
"MIT"
] | null | null | null | portal/src/levelsettingsdialog.cpp | zfrye06/Loque | bbb0e7a0a5d5374c27b83bba5b13bc191b03ebb0 | [
"MIT"
] | null | null | null | #include <QListView>
#include "levelsettingsdialog.h"
#include "launchgame.h"
LevelSettingsDialog::LevelSettingsDialog(int teacherId, int classId,
const std::vector<LevelInfo>& enabledLevels,
const std::vector<LevelInfo>& allLevels,
QWidget *parent) :
QDialog(parent),
teacherId(teacherId),
classId(classId),
ui(new Ui::LevelSettingsDialog),
mapper(new QSignalMapper)
{
ui->setupUi(this);
for (auto& level : enabledLevels) {
enabledIds.push_back(level.id);
}
connect(this, &LevelSettingsDialog::clicked, this, &LevelSettingsDialog::toggleLevel);
connect(mapper, SIGNAL(mapped(int)), this, SIGNAL(clicked(int)));
connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &LevelSettingsDialog::submitLevels);
ui->scrollArea->setWidgetResizable(true);
QFrame *frame = new QFrame(ui->scrollArea);
ui->scrollArea->setWidget(frame);
ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
QGridLayout *layout = new QGridLayout(frame);
int row = 0;
int col = 0;
for(size_t i = 0; i < allLevels.size(); i++){
auto enabled = std::find(enabledIds.begin(), enabledIds.end(), allLevels[i].id) != enabledIds.end();
layout->addWidget(addLevel(allLevels[i], enabled), row, col++);
if(col > 1){
row++;
col = 0;
}
}
frame->setLayout(layout);
}
LevelSettingsDialog::~LevelSettingsDialog() {
delete ui;
}
QGroupBox* LevelSettingsDialog::addLevel(const LevelInfo& lvlInfo, bool enabled){
QGroupBox *box = new QGroupBox;
QHBoxLayout *hLayout = new QHBoxLayout;
QVBoxLayout *vLayout = new QVBoxLayout;
QPixmap img;
for(size_t i = 0; i < MapCount; i++) {
if (Maps[i].id == lvlInfo.id) {
img = QPixmap(Maps[i].thumbnail.c_str());
}
}
QLabel *imgLabel = new QLabel;
imgLabel->setPixmap(img.scaled(250, 250, Qt::KeepAspectRatio));
QLabel *nameLabel = new QLabel(QString::fromStdString(lvlInfo.name));
QFont font = nameLabel->font();
font.setPointSize(20);
font.setBold(true);
nameLabel->setFont(font);
QLabel *descriptionLabel = new QLabel(QString::fromStdString(lvlInfo.description));
QFont dfont = descriptionLabel->font();
dfont.setPointSize(16);
descriptionLabel->setFont(dfont);
descriptionLabel->setWordWrap(true);
QPushButton *playButton = new QPushButton("Play");
QPushButton *toggleButton = new QPushButton(enabled ? "Disable Level" : "Enable Level");
btns[lvlInfo.id] = toggleButton;
connect(toggleButton, SIGNAL(clicked()), mapper, SLOT(map()));
mapper->setMapping(toggleButton, lvlInfo.id);
int lid = lvlInfo.id;
int tid = this->teacherId;
connect(playButton, &QPushButton::clicked,
this, [lid, tid] { launchGame(lid, tid); });
vLayout->addWidget(nameLabel);
vLayout->addWidget(descriptionLabel);
vLayout->addWidget(playButton);
vLayout->addWidget(toggleButton);
hLayout->addWidget(imgLabel);
hLayout->addLayout(vLayout);
box->setLayout(hLayout);
box->setFixedSize(QSize(500, 250));
return box;
}
void LevelSettingsDialog::toggleLevel(const int &levelID){
// std::cout << levelID << std::endl;
// if(std::find(enabledIds.begin(), enabledIds.end(), levelID) != enabledIds.end()){
// } else{
// }
QPushButton* btn = btns[levelID];
if(btn->text() == "Disable Level"){
btn->setText("Enable Level");
enabledIds.erase(std::remove(enabledIds.begin(), enabledIds.end(), levelID), enabledIds.end());
levelsToEnable.erase(std::remove(levelsToEnable.begin(), levelsToEnable.end(), levelID), levelsToEnable.end());
levelsToDisable.push_back(levelID);
} else{
levelsToDisable.erase(std::remove(levelsToDisable.begin(), levelsToDisable.end(), levelID), levelsToDisable.end());
levelsToEnable.push_back(levelID);
enabledIds.push_back(levelID);
btn->setText("Disable Level");
}
}
void LevelSettingsDialog::submitLevels() {
LoqueClient client;
for(int id : levelsToDisable){
client.disableLevel(teacherId, classId, id);
}
for(int id : levelsToEnable){
client.enableLevel(teacherId, classId, id);
}
emit refresh();
}
| 35.580645 | 123 | 0.646192 | [
"vector"
] |
fe9c85860b8255ef6926a81ed5a242fd20c407a8 | 3,340 | cpp | C++ | open3d_conversions_examples/src/ex_plane_segmentation.cpp | UrbanMachine/perception_open3d | a08beb8569691c6094628402e42918beb5835006 | [
"Apache-2.0"
] | 84 | 2020-07-27T20:21:56.000Z | 2022-03-05T11:06:39.000Z | open3d_conversions_examples/src/ex_plane_segmentation.cpp | UrbanMachine/perception_open3d | a08beb8569691c6094628402e42918beb5835006 | [
"Apache-2.0"
] | 17 | 2020-07-27T19:31:23.000Z | 2022-03-27T22:32:56.000Z | open3d_conversions_examples/src/ex_plane_segmentation.cpp | UrbanMachine/perception_open3d | a08beb8569691c6094628402e42918beb5835006 | [
"Apache-2.0"
] | 19 | 2020-07-27T18:44:28.000Z | 2022-03-22T13:11:50.000Z | // Copyright 2020 Autonomous Robots Lab, University of Nevada, Reno
// 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.
// Open3D
#include <open3d/Open3D.h>
// ROS
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
// open3d_conversions
#include "open3d_conversions/open3d_conversions.h"
class SubscribeFilterPublish
{
private:
ros::NodeHandle nh_;
ros::NodeHandle pnh_;
ros::Publisher pub_inlier_;
ros::Publisher pub_outlier_;
ros::Subscriber sub_;
double distance_threshold_ = 0.01;
int ransac_n_ = 3;
int num_iterations_ = 1000;
public:
SubscribeFilterPublish(ros::NodeHandle& nh, ros::NodeHandle& pnh) : nh_(nh), pnh_(pnh)
{
pub_inlier_ = nh_.advertise<sensor_msgs::PointCloud2>("pointcloud_out/inlier_cloud", 1);
pub_outlier_ = nh_.advertise<sensor_msgs::PointCloud2>("pointcloud_out/outlier_cloud", 1);
sub_ = nh_.subscribe("pointcloud_in", 1, &SubscribeFilterPublish::cloud_callback, this);
pnh_.getParam("distance_threshold", distance_threshold_);
pnh_.getParam("ransac_n", ransac_n_);
pnh_.getParam("num_iterations", num_iterations_);
ROS_INFO("Waiting for pointclouds...");
}
~SubscribeFilterPublish()
{
}
void cloud_callback(const sensor_msgs::PointCloud2ConstPtr& cloud_data)
{
ROS_INFO("Recieved pointcloud with sequence number: %i", cloud_data->header.seq);
open3d::geometry::PointCloud pcd;
open3d_conversions::rosToOpen3d(cloud_data, pcd);
Eigen::Vector4d plane_model;
std::vector<size_t, std::allocator<size_t>> inliers;
std::tie(plane_model, inliers) = pcd.SegmentPlane(distance_threshold_, ransac_n_, num_iterations_);
ROS_INFO("Plane equation: %.2fx + %.2fy + %.2fz + %.2f = 0", plane_model[0], plane_model[1], plane_model[2],
plane_model[3]);
std::shared_ptr<open3d::geometry::PointCloud> inlier_cloud = pcd.SelectByIndex(inliers);
Eigen::Vector3d inlier_color{ 1.0, 0, 0 };
open3d::geometry::PointCloud painted_cloud = inlier_cloud->PaintUniformColor(inlier_color);
std::shared_ptr<open3d::geometry::PointCloud> outlier_cloud = pcd.SelectByIndex(inliers, true);
ROS_INFO("Number of inliers/outliers: %lu/%lu", inlier_cloud->points_.size(), outlier_cloud->points_.size());
sensor_msgs::PointCloud2 ros_pc2_inlier, ros_pc2_outlier;
open3d_conversions::open3dToRos(painted_cloud, ros_pc2_inlier, cloud_data->header.frame_id);
pub_inlier_.publish(ros_pc2_inlier);
open3d_conversions::open3dToRos(*outlier_cloud, ros_pc2_outlier, cloud_data->header.frame_id);
pub_outlier_.publish(ros_pc2_outlier);
ROS_INFO("Published inlier and outlier clouds");
}
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "open3d_conversions_ex_plane_segmentation");
ros::NodeHandle nh;
ros::NodeHandle pnh("~");
SubscribeFilterPublish sfp(nh, pnh);
ros::spin();
} | 39.761905 | 113 | 0.742216 | [
"geometry",
"vector"
] |
fe9e730f8896b215b032f8c7f4c2ab386345cd54 | 1,679 | cpp | C++ | code/hydrasheads.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | 8 | 2020-02-21T22:21:01.000Z | 2022-02-16T05:30:54.000Z | code/hydrasheads.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | null | null | null | code/hydrasheads.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | 3 | 2020-08-05T05:42:35.000Z | 2021-08-30T05:39:51.000Z | #define _USE_MATH_DEFINES
#include <iostream>
#include <stdio.h>
#include <cmath>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_set>
#include <ctype.h>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <unordered_map>
#define EPSILON 0.00001
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
ll i, j, k;
//nothing
// tails + 1
// heads + 1, tails - 2
// heads - 2,
//3 3
//3 4
//3 5
//3 6
//4 4
//5 2
//6 0
//4 0
//2 0
//0 0
ll steps;
ll heads, tails;
while(cin >> heads >> tails && (heads != 0 || tails != 0))
{
if(tails == 0)
{
cout << "-1\n";
continue;
}
steps = 0;
while(heads != 0 || tails != 0)
{
if(tails % 2 != 0)
{
//cout << "added one to tails\n";
tails++;
steps++;
}
else if((heads + tails / 2) % 2 != 0)
{
//cout << "added 2 to tails\n";
tails += 2;
steps += 2;
}
else
{
//cout << "chopped off all heads\n";
heads += (tails / 2);
steps += (tails / 2);
tails = 0;
steps += heads/2;
heads = 0;
}
}
cout << steps << "\n";
}
return 0;
}
| 19.079545 | 62 | 0.408577 | [
"vector"
] |
fea1d3d5e4ba8cf51138bc9114c5cbefeaf69929 | 25,849 | cc | C++ | src/kudu/common/partition_pruner.cc | Kekdeng/kudu | 958248adf3ea70f12ab033e0041bfc5c922956af | [
"Apache-2.0"
] | 1,538 | 2016-08-08T22:34:30.000Z | 2022-03-29T05:23:36.000Z | src/kudu/common/partition_pruner.cc | Kekdeng/kudu | 958248adf3ea70f12ab033e0041bfc5c922956af | [
"Apache-2.0"
] | 17 | 2017-05-18T16:05:14.000Z | 2022-03-18T22:17:13.000Z | src/kudu/common/partition_pruner.cc | Kekdeng/kudu | 958248adf3ea70f12ab033e0041bfc5c922956af | [
"Apache-2.0"
] | 612 | 2016-08-12T04:09:37.000Z | 2022-03-29T16:57:46.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.
#include "kudu/common/partition_pruner.h"
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <iterator>
#include <memory>
#include <numeric>
#include <string>
#include <unordered_map>
#include <vector>
#include <glog/logging.h>
#include "kudu/common/column_predicate.h"
#include "kudu/common/common.pb.h"
#include "kudu/common/encoded_key.h"
#include "kudu/common/key_encoder.h"
#include "kudu/common/key_util.h"
#include "kudu/common/partition.h"
#include "kudu/common/row.h"
#include "kudu/common/scan_spec.h"
#include "kudu/common/schema.h"
#include "kudu/common/types.h"
#include "kudu/gutil/map-util.h"
#include "kudu/gutil/strings/join.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/util/array_view.h"
#include "kudu/util/memory/arena.h"
#include "kudu/util/slice.h"
using std::distance;
using std::find;
using std::iota;
using std::lower_bound;
using std::memcpy;
using std::move;
using std::string;
using std::unique_ptr;
using std::unordered_map;
using std::vector;
namespace kudu {
namespace {
// Returns true if the partition schema's range columns are a prefix of the
// primary key columns.
bool AreRangeColumnsPrefixOfPrimaryKey(const Schema& schema,
const vector<ColumnId>& range_columns) {
CHECK(range_columns.size() <= schema.num_key_columns());
for (int32_t col_idx = 0; col_idx < range_columns.size(); ++col_idx) {
if (schema.column_id(col_idx) != range_columns[col_idx]) {
return false;
}
}
return true;
}
// Translates the scan primary key bounds into range keys. This should only be
// used when the range columns are a prefix of the primary key columns.
void EncodeRangeKeysFromPrimaryKeyBounds(const Schema& schema,
const ScanSpec& scan_spec,
size_t num_range_columns,
string* range_key_start,
string* range_key_end) {
if (scan_spec.lower_bound_key() == nullptr && scan_spec.exclusive_upper_bound_key() == nullptr) {
// Don't bother if there are no lower and upper PK bounds
return;
}
if (num_range_columns == schema.num_key_columns()) {
// The range columns are the primary key columns, so the range key is the
// primary key.
if (scan_spec.lower_bound_key() != nullptr) {
*range_key_start = scan_spec.lower_bound_key()->encoded_key().ToString();
}
if (scan_spec.exclusive_upper_bound_key() != nullptr) {
*range_key_end = scan_spec.exclusive_upper_bound_key()->encoded_key().ToString();
}
} else {
// The range-partition key columns are a prefix of the primary key columns.
// Copy the column values over to a row, and then encode the row as a range
// key.
vector<int32_t> col_idxs(num_range_columns);
iota(col_idxs.begin(), col_idxs.end(), 0);
unique_ptr<uint8_t[]> buf(new uint8_t[schema.key_byte_size()]);
ContiguousRow row(&schema, buf.get());
if (scan_spec.lower_bound_key() != nullptr) {
for (int32_t idx : col_idxs) {
memcpy(row.mutable_cell_ptr(idx),
scan_spec.lower_bound_key()->raw_keys()[idx],
schema.column(idx).type_info()->size());
}
key_util::EncodeKey(col_idxs, row, range_key_start);
}
if (scan_spec.exclusive_upper_bound_key() != nullptr) {
for (int32_t idx : col_idxs) {
memcpy(row.mutable_cell_ptr(idx),
scan_spec.exclusive_upper_bound_key()->raw_keys()[idx],
schema.column(idx).type_info()->size());
}
// Determine if the upper bound primary key columns which aren't in the
// range-partition key are all set to the minimum value. If so, the
// range-partition key prefix of the primary key is already effectively an
// exclusive bound. If not, then we increment the range-key prefix in
// order to transform it from inclusive to exclusive.
bool min_suffix = true;
for (int32_t idx = num_range_columns; idx < schema.num_key_columns(); ++idx) {
min_suffix &= schema.column(idx)
.type_info()
->IsMinValue(scan_spec.exclusive_upper_bound_key()->raw_keys()[idx]);
}
Arena arena(std::max<size_t>(Arena::kMinimumChunkSize, schema.key_byte_size()));
if (!min_suffix) {
if (!key_util::IncrementPrimaryKey(&row, num_range_columns, &arena)) {
// The range-partition key upper bound can't be incremented, which
// means it's an inclusive bound on the maximum possible value, so
// skip it.
return;
}
}
key_util::EncodeKey(col_idxs, row, range_key_end);
}
}
}
// Push the scan predicates into the range keys.
void EncodeRangeKeysFromPredicates(const Schema& schema,
const unordered_map<string, ColumnPredicate>& predicates,
const vector<ColumnId>& range_columns,
string* range_key_start,
string* range_key_end) {
// Find the column indexes of the range columns.
vector<int32_t> col_idxs;
col_idxs.reserve(range_columns.size());
for (const auto& column : range_columns) {
int32_t col_idx = schema.find_column_by_id(column);
CHECK_NE(Schema::kColumnNotFound, col_idx);
CHECK_LT(col_idx, schema.num_key_columns());
col_idxs.push_back(col_idx);
}
// Arenas must be at least the minimum chunk size, and we require at least
// enough space for the range key columns.
Arena arena(std::max<size_t>(Arena::kMinimumChunkSize, schema.key_byte_size()));
uint8_t* buf = static_cast<uint8_t*>(CHECK_NOTNULL(arena.AllocateBytes(schema.key_byte_size())));
ContiguousRow row(&schema, buf);
if (key_util::PushLowerBoundKeyPredicates(col_idxs, predicates, &row, &arena) > 0) {
key_util::EncodeKey(col_idxs, row, range_key_start);
}
if (key_util::PushUpperBoundKeyPredicates(col_idxs, predicates, &row, &arena) > 0) {
key_util::EncodeKey(col_idxs, row, range_key_end);
}
}
} // anonymous namespace
vector<bool> PartitionPruner::PruneHashComponent(
const PartitionSchema::HashDimension& hash_dimension,
const Schema& schema,
const ScanSpec& scan_spec) {
vector<bool> hash_bucket_bitset(hash_dimension.num_buckets, false);
vector<string> encoded_strings(1, "");
for (size_t col_offset = 0; col_offset < hash_dimension.column_ids.size(); ++col_offset) {
vector<string> new_encoded_strings;
const ColumnSchema& column = schema.column_by_id(hash_dimension.column_ids[col_offset]);
const ColumnPredicate& predicate = FindOrDie(scan_spec.predicates(), column.name());
const KeyEncoder<string>& encoder = GetKeyEncoder<string>(column.type_info());
vector<const void*> predicate_values;
if (predicate.predicate_type() == PredicateType::Equality) {
predicate_values.push_back(predicate.raw_lower());
} else {
CHECK(predicate.predicate_type() == PredicateType::InList);
predicate_values.insert(predicate_values.end(),
predicate.raw_values().begin(),
predicate.raw_values().end());
}
// For each of the encoded string, replicate it by the number of values in
// equality and in-list predicate.
for (const string& encoded_string : encoded_strings) {
for (const void* predicate_value : predicate_values) {
string new_encoded_string = encoded_string;
encoder.Encode(predicate_value,
col_offset + 1 == hash_dimension.column_ids.size(),
&new_encoded_string);
new_encoded_strings.emplace_back(new_encoded_string);
}
}
encoded_strings.swap(new_encoded_strings);
}
for (const string& encoded_string : encoded_strings) {
uint32_t hash_value = PartitionSchema::HashValueForEncodedColumns(
encoded_string, hash_dimension);
hash_bucket_bitset[hash_value] = true;
}
return hash_bucket_bitset;
}
vector<PartitionPruner::PartitionKeyRange> PartitionPruner::ConstructPartitionKeyRanges(
const Schema& schema,
const ScanSpec& scan_spec,
const PartitionSchema::HashSchema& hash_schema,
const RangeBounds& range_bounds) {
// Create the hash bucket portion of the partition key.
// The list of hash buckets bitset per hash component
vector<vector<bool>> hash_bucket_bitsets;
hash_bucket_bitsets.reserve(hash_schema.size());
for (const auto& hash_dimension : hash_schema) {
bool can_prune = true;
for (const auto& column_id : hash_dimension.column_ids) {
const ColumnSchema& column = schema.column_by_id(column_id);
const ColumnPredicate* predicate = FindOrNull(scan_spec.predicates(), column.name());
if (predicate == nullptr ||
(predicate->predicate_type() != PredicateType::Equality &&
predicate->predicate_type() != PredicateType::InList)) {
can_prune = false;
break;
}
}
if (can_prune) {
auto hash_bucket_bitset = PruneHashComponent(
hash_dimension, schema, scan_spec);
hash_bucket_bitsets.emplace_back(std::move(hash_bucket_bitset));
} else {
hash_bucket_bitsets.emplace_back(hash_dimension.num_buckets, true);
}
}
// The index of the final constrained component in the partition key.
size_t constrained_index;
if (!range_bounds.lower.empty() || !range_bounds.upper.empty()) {
// The range component is constrained.
constrained_index = hash_schema.size();
} else {
// Search the hash bucket constraints from right to left, looking for the
// first constrained component.
constrained_index = hash_schema.size() -
distance(hash_bucket_bitsets.rbegin(),
find_if(hash_bucket_bitsets.rbegin(),
hash_bucket_bitsets.rend(),
[] (const vector<bool>& x) {
return std::find(x.begin(), x.end(), false) != x.end();
}));
}
// Build up a set of partition key ranges out of the hash components.
//
// Each hash component simply appends its bucket number to the
// partition key ranges (possibly incrementing the upper bound by one bucket
// number if this is the final constraint, see note 2 in the example above).
vector<PartitionKeyRange> partition_key_ranges(1);
const KeyEncoder<string>& hash_encoder = GetKeyEncoder<string>(GetTypeInfo(UINT32));
for (size_t hash_idx = 0; hash_idx < constrained_index; ++hash_idx) {
// This is the final partition key component if this is the final constrained
// bucket, and the range upper bound is empty. In this case we need to
// increment the bucket on the upper bound to convert from inclusive to
// exclusive.
bool is_last = hash_idx + 1 == constrained_index && range_bounds.upper.empty();
vector<PartitionKeyRange> new_partition_key_ranges;
for (const auto& key_range : partition_key_ranges) {
const vector<bool>& buckets_bitset = hash_bucket_bitsets[hash_idx];
for (uint32_t bucket = 0; bucket < buckets_bitset.size(); ++bucket) {
if (!buckets_bitset[bucket]) {
continue;
}
uint32_t bucket_upper = is_last ? bucket + 1 : bucket;
auto lower = key_range.start.hash_key();
auto upper = key_range.end.hash_key();
hash_encoder.Encode(&bucket, &lower);
hash_encoder.Encode(&bucket_upper, &upper);
new_partition_key_ranges.emplace_back(PartitionKeyRange{
{ lower, key_range.start.range_key() },
{ upper, key_range.end.range_key() }});
}
}
partition_key_ranges.swap(new_partition_key_ranges);
}
// Append the (possibly empty) range bounds to the partition key ranges.
for (auto& range : partition_key_ranges) {
range.start.mutable_range_key()->append(range_bounds.lower);
range.end.mutable_range_key()->append(range_bounds.upper);
}
// Remove all partition key ranges past the scan spec's upper bound partition key.
if (!scan_spec.exclusive_upper_bound_partition_key().empty()) {
for (auto range = partition_key_ranges.rbegin();
range != partition_key_ranges.rend();
++range) {
if (!(*range).end.empty() &&
scan_spec.exclusive_upper_bound_partition_key() >= (*range).end) {
break;
}
if (scan_spec.exclusive_upper_bound_partition_key() <= (*range).start) {
partition_key_ranges.pop_back();
} else {
(*range).end = scan_spec.exclusive_upper_bound_partition_key();
}
}
}
return partition_key_ranges;
}
void PartitionPruner::Init(const Schema& schema,
const PartitionSchema& partition_schema,
const ScanSpec& scan_spec) {
// If we can already short circuit the scan, we don't need to bother with
// partition pruning. This also allows us to assume some invariants of the
// scan spec, such as no None predicates and that the lower bound PK < upper
// bound PK.
if (scan_spec.CanShortCircuit()) { return; }
// Build a set of partition key ranges which cover the tablets necessary for
// the scan.
//
// Example predicate sets and resulting partition key ranges, based on the
// following tablet schema:
//
// CREATE TABLE t (a INT32, b INT32, c INT32) PRIMARY KEY (a, b, c)
// DISTRIBUTE BY RANGE (c)
// HASH (a) INTO 2 BUCKETS
// HASH (b) INTO 3 BUCKETS;
//
// Assume that hash(0) = 0 and hash(2) = 2.
//
// | Predicates | Partition Key Ranges |
// +------------+--------------------------------------------------------+
// | a = 0 | [(bucket=0, bucket=2, c=0), (bucket=0, bucket=2, c=1)) |
// | b = 2 | |
// | c = 0 | |
// +------------+--------------------------------------------------------+
// | a = 0 | [(bucket=0, bucket=2), (bucket=0, bucket=3)) |
// | b = 2 | |
// +------------+--------------------------------------------------------+
// | a = 0 | [(bucket=0, bucket=0, c=0), (bucket=0, bucket=0, c=1)) |
// | c = 0 | [(bucket=0, bucket=1, c=0), (bucket=0, bucket=1, c=1)) |
// | | [(bucket=0, bucket=2, c=0), (bucket=0, bucket=2, c=1)) |
// +------------+--------------------------------------------------------+
// | b = 2 | [(bucket=0, bucket=2, c=0), (bucket=0, bucket=2, c=1)) |
// | c = 0 | [(bucket=1, bucket=2, c=0), (bucket=1, bucket=2, c=1)) |
// +------------+--------------------------------------------------------+
// | a = 0 | [(bucket=0), (bucket=1)) |
// +------------+--------------------------------------------------------+
// | b = 2 | [(bucket=0, bucket=2), (bucket=0, bucket=3)) |
// | | [(bucket=1, bucket=2), (bucket=1, bucket=3)) |
// +------------+--------------------------------------------------------+
// | c = 0 | [(bucket=0, bucket=0, c=0), (bucket=0, bucket=0, c=1)) |
// | | [(bucket=0, bucket=1, c=0), (bucket=0, bucket=1, c=1)) |
// | | [(bucket=0, bucket=2, c=0), (bucket=0, bucket=2, c=1)) |
// | | [(bucket=1, bucket=0, c=0), (bucket=1, bucket=0, c=1)) |
// | | [(bucket=1, bucket=1, c=0), (bucket=1, bucket=1, c=1)) |
// | | [(bucket=1, bucket=2, c=0), (bucket=1, bucket=2, c=1)) |
// +------------+--------------------------------------------------------+
// | None | [(), ()) |
//
// If the partition key is considered as a sequence of the hash bucket
// components and a range component, then a few patterns emerge from the
// examples above:
//
// 1) The partition keys are truncated after the final constrained component.
// Hash bucket components are constrained when the scan is limited to a
// subset of buckets via equality or in-list predicates on that component.
// Range components are constrained if they have an upper or lower bound
// via range or equality predicates on that component.
//
// 2) If the final constrained component is a hash bucket, then the
// corresponding bucket in the upper bound is incremented in order to make
// it an exclusive key.
//
// 3) The number of partition key ranges in the result is equal to the product
// of the number of buckets of each unconstrained hash component which come
// before a final constrained component. If there are no unconstrained hash
// components, then the number of resulting partition key ranges is one. Note
// that this can be a lot of ranges, and we may find we need to limit the
// algorithm to give up on pruning if the number of ranges exceeds a limit.
// Until this becomes a problem in practice, we'll continue always pruning,
// since it is precisely these highly-hash-partitioned tables which get the
// most benefit from pruning.
// Build the range portion of the partition key by using
// the lower and upper bounds specified by the scan.
string scan_range_lower_bound;
string scan_range_upper_bound;
const vector<ColumnId>& range_columns = partition_schema.range_schema_.column_ids;
if (!range_columns.empty()) {
if (AreRangeColumnsPrefixOfPrimaryKey(schema, range_columns)) {
EncodeRangeKeysFromPrimaryKeyBounds(schema,
scan_spec,
range_columns.size(),
&scan_range_lower_bound,
&scan_range_upper_bound);
} else {
EncodeRangeKeysFromPredicates(schema,
scan_spec.predicates(),
range_columns,
&scan_range_lower_bound,
&scan_range_upper_bound);
}
}
// Store ranges and their corresponding hash schemas if they fall within
// the range bounds specified by the scan.
if (partition_schema.ranges_with_hash_schemas_.empty()) {
auto partition_key_ranges = ConstructPartitionKeyRanges(
schema, scan_spec, partition_schema.hash_schema_,
{scan_range_lower_bound, scan_range_upper_bound});
// Reverse the order of the partition key ranges, so that it is efficient
// to remove the partition key ranges from the vector in ascending order.
range_bounds_to_partition_key_ranges_.resize(1);
auto& first_range = range_bounds_to_partition_key_ranges_[0];
first_range.partition_key_ranges.resize(partition_key_ranges.size());
move(partition_key_ranges.rbegin(), partition_key_ranges.rend(),
first_range.partition_key_ranges.begin());
} else {
vector<RangeBounds> range_bounds;
vector<PartitionSchema::HashSchema> hash_schemas_per_range;
for (const auto& range : partition_schema.ranges_with_hash_schemas_) {
const auto& hash_schema = range.hash_schema;
// Both lower and upper bounds of the scan are unbounded.
if (scan_range_lower_bound.empty() && scan_range_upper_bound.empty()) {
range_bounds.emplace_back(RangeBounds{range.lower, range.upper});
hash_schemas_per_range.emplace_back(hash_schema);
continue;
}
// Only one of the lower/upper bounds of the scan is unbounded.
if (scan_range_lower_bound.empty()) {
if (scan_range_upper_bound > range.lower) {
range_bounds.emplace_back(RangeBounds{range.lower, range.upper});
hash_schemas_per_range.emplace_back(hash_schema);
}
continue;
}
if (scan_range_upper_bound.empty()) {
if (range.upper.empty() || scan_range_lower_bound < range.upper) {
range_bounds.emplace_back(RangeBounds{range.lower, range.upper});
hash_schemas_per_range.emplace_back(hash_schema);
}
continue;
}
// Both lower and upper ranges of the scan are bounded.
if ((range.upper.empty() || scan_range_lower_bound < range.upper) &&
scan_range_upper_bound > range.lower) {
range_bounds.emplace_back(RangeBounds{range.lower, range.upper});
hash_schemas_per_range.emplace_back(hash_schema);
}
}
DCHECK_EQ(range_bounds.size(), hash_schemas_per_range.size());
range_bounds_to_partition_key_ranges_.resize(hash_schemas_per_range.size());
// Construct partition key ranges from the ranges and their respective hash schemas
// that falls within the scan's bounds.
for (size_t i = 0; i < hash_schemas_per_range.size(); ++i) {
const auto& hash_schema = hash_schemas_per_range[i];
const auto bounds =
scan_range_lower_bound.empty() && scan_range_upper_bound.empty()
? RangeBounds{range_bounds[i].lower, range_bounds[i].upper}
: RangeBounds{scan_range_lower_bound, scan_range_upper_bound};
auto partition_key_ranges = ConstructPartitionKeyRanges(
schema, scan_spec, hash_schema, bounds);
auto& current_range = range_bounds_to_partition_key_ranges_[i];
current_range.range_bounds = range_bounds[i];
current_range.partition_key_ranges.resize(partition_key_ranges.size());
move(partition_key_ranges.rbegin(), partition_key_ranges.rend(),
current_range.partition_key_ranges.begin());
}
}
// Remove all partition key ranges before the scan spec's lower bound partition key.
if (!scan_spec.lower_bound_partition_key().empty()) {
RemovePartitionKeyRange(scan_spec.lower_bound_partition_key());
}
}
bool PartitionPruner::HasMorePartitionKeyRanges() const {
return NumRangesRemaining() != 0;
}
const PartitionKey& PartitionPruner::NextPartitionKey() const {
CHECK(HasMorePartitionKeyRanges());
return range_bounds_to_partition_key_ranges_.back().partition_key_ranges.back().start;
}
void PartitionPruner::RemovePartitionKeyRange(const PartitionKey& upper_bound) {
if (upper_bound.empty()) {
range_bounds_to_partition_key_ranges_.clear();
return;
}
for (auto& range_bounds_and_partition_key_range : range_bounds_to_partition_key_ranges_) {
auto& partition_key_range = range_bounds_and_partition_key_range.partition_key_ranges;
for (auto range_it = partition_key_range.rbegin();
range_it != partition_key_range.rend();
++range_it) {
if (upper_bound <= (*range_it).start) { break; }
if ((*range_it).end.empty() || upper_bound < (*range_it).end) {
(*range_it).start = upper_bound;
} else {
partition_key_range.pop_back();
}
}
}
}
bool PartitionPruner::ShouldPrune(const Partition& partition) const {
for (const auto& [range_bounds, partition_key_ranges] : range_bounds_to_partition_key_ranges_) {
// Check if the partition belongs to the same range as the partition key range.
if (!range_bounds.lower.empty() && partition.begin().range_key() != range_bounds.lower &&
!range_bounds.upper.empty() && partition.end().range_key() != range_bounds.upper) {
continue;
}
// range is an iterator that points to the first partition key range which
// overlaps or is greater than the partition.
auto range = lower_bound(partition_key_ranges.rbegin(), partition_key_ranges.rend(),
partition, [] (const PartitionKeyRange& scan_range,
const Partition& partition) {
// return true if scan_range < partition
const auto& scan_upper = scan_range.end;
return !scan_upper.empty()
&& scan_upper <= partition.begin();
});
if (range == partition_key_ranges.rend()) {
continue;
}
if (partition.end().empty() || (*range).start < partition.end()) {
return false;
}
}
return true;
}
string PartitionPruner::ToString(const Schema& schema,
const PartitionSchema& partition_schema) const {
vector<string> strings;
for (const auto& partition_key_range : range_bounds_to_partition_key_ranges_) {
for (auto range = partition_key_range.partition_key_ranges.rbegin();
range != partition_key_range.partition_key_ranges.rend();
++range) {
strings.push_back(strings::Substitute(
"[($0), ($1))",
(*range).start.empty() ? "<start>" :
partition_schema.PartitionKeyDebugString((*range).start, schema),
(*range).end.empty() ? "<end>" :
partition_schema.PartitionKeyDebugString((*range).end, schema)));
}
}
return JoinStrings(strings, ", ");
}
} // namespace kudu
| 44.721453 | 99 | 0.634763 | [
"vector",
"transform"
] |
fea277c6ff883939c7f44cc9c891f244fe0936ea | 2,218 | hpp | C++ | stereo_utils/include/stereo_utils/NumPyIO.hpp | huyaoyu/Tutorial2020_Stereo_ROS | 32f7427b597ac01674a36a19b8439844d1ea291b | [
"BSD-3-Clause"
] | 4 | 2020-10-27T03:12:39.000Z | 2022-02-01T07:04:34.000Z | stereo_utils/include/stereo_utils/NumPyIO.hpp | huyaoyu/Tutorial2020_Stereo_ROS | 32f7427b597ac01674a36a19b8439844d1ea291b | [
"BSD-3-Clause"
] | null | null | null | stereo_utils/include/stereo_utils/NumPyIO.hpp | huyaoyu/Tutorial2020_Stereo_ROS | 32f7427b597ac01674a36a19b8439844d1ea291b | [
"BSD-3-Clause"
] | 3 | 2021-08-14T23:05:10.000Z | 2022-02-02T11:31:22.000Z | //
// Created by yaoyu on 4/8/20.
//
#ifndef NUMPYIO_HPP
#define NUMPYIO_HPP
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cnpy.h>
#include <Eigen/Dense>
namespace stereo_utils
{
template < typename rT >
void write_depth_map_2_npy( const std::string &fn,
const Eigen::MatrixX<rT> &mat,
rT minLimit = 0 ) {
const std::size_t rows = mat.rows();
const std::size_t cols = mat.cols();
std::vector<rT> data;
for ( std::size_t j = 0; j < cols; ++j ) {
for ( std::size_t i = 0; i < rows; ++i ) {
const rT value = mat( i, j );
if ( value > minLimit ) {
data.push_back(static_cast<rT>(j));
data.push_back(static_cast<rT>(i));
data.push_back(value);
}
}
}
const std::size_t N = data.size();
if ( 0 == N ) {
std::stringstream ss;
ss << "No pixels have depth over the limit of " << minLimit;
throw( std::runtime_error( ss.str() ) );
}
cnpy::npy_save( fn, &data[0], { N/3, 3 }, "w" );
}
template < typename rT >
void write_eigen_matrix_2_npy( const std::string &fn,
const Eigen::MatrixX<rT> &mat ) {
const std::size_t rows = mat.rows();
const std::size_t cols = mat.cols();
if ( mat.IsRowMajor ) {
cnpy::npy_save( fn, mat.data(), { rows, cols }, "w" );
} else {
Eigen::MatrixX<rT> temp = mat.transpose();
cnpy::npy_save( fn, temp.data(), { rows, cols }, "w" );
}
}
template < typename rT >
void read_npy_2_eigen_matrix( const std::string &fn,
Eigen::MatrixX<rT> &mat ) {
// Load the .npy file.
cnpy::NpyArray arr = cnpy::npy_load(fn);
rT* data = arr.data<rT>();
assert( 2 == arr.shape.size() );
const int dim0 = arr.shape[0];
const int dim1 = arr.shape[1];
mat.resize( dim0, dim1 );
Eigen::Matrix<rT, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> temp =
Eigen::Map< Eigen::Matrix<rT, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > (
data, dim0, dim1 );
// Convert the row major matrix to column major?
mat = temp;
}
} // namespace stereo_utils
#endif //NUMPYIO_HPP
| 24.644444 | 94 | 0.566727 | [
"shape",
"vector"
] |
fea3b26d0f6cf3c56a98d7029811211d9820dba5 | 8,819 | cc | C++ | chrome/browser/browsing_data_indexed_db_helper.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | 1 | 2016-03-10T09:13:57.000Z | 2016-03-10T09:13:57.000Z | chrome/browser/browsing_data_indexed_db_helper.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | 1 | 2022-03-13T08:39:05.000Z | 2022-03-13T08:39:05.000Z | chrome/browser/browsing_data_indexed_db_helper.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2011 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/browsing_data_indexed_db_helper.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/indexed_db_context.h"
#include "webkit/database/database_util.h"
#include "webkit/glue/webkit_glue.h"
using content::BrowserContext;
using content::BrowserThread;
using content::IndexedDBContext;
using webkit_database::DatabaseUtil;
namespace {
class BrowsingDataIndexedDBHelperImpl : public BrowsingDataIndexedDBHelper {
public:
explicit BrowsingDataIndexedDBHelperImpl(Profile* profile);
virtual void StartFetching(
const base::Callback<void(const std::list<IndexedDBInfo>&)>&
callback) OVERRIDE;
virtual void CancelNotification() OVERRIDE;
virtual void DeleteIndexedDB(const GURL& origin) OVERRIDE;
private:
virtual ~BrowsingDataIndexedDBHelperImpl();
// Enumerates all indexed database files in the WEBKIT thread.
void FetchIndexedDBInfoInWebKitThread();
// Notifies the completion callback in the UI thread.
void NotifyInUIThread();
// Delete a single indexed database in the WEBKIT thread.
void DeleteIndexedDBInWebKitThread(const GURL& origin);
scoped_refptr<IndexedDBContext> indexed_db_context_;
// This only mutates in the WEBKIT thread.
std::list<IndexedDBInfo> indexed_db_info_;
// This only mutates on the UI thread.
base::Callback<void(const std::list<IndexedDBInfo>&)> completion_callback_;
// Indicates whether or not we're currently fetching information:
// it's true when StartFetching() is called in the UI thread, and it's reset
// after we notified the callback in the UI thread.
// This only mutates on the UI thread.
bool is_fetching_;
DISALLOW_COPY_AND_ASSIGN(BrowsingDataIndexedDBHelperImpl);
};
BrowsingDataIndexedDBHelperImpl::BrowsingDataIndexedDBHelperImpl(
Profile* profile)
: indexed_db_context_(BrowserContext::GetIndexedDBContext(profile)),
is_fetching_(false) {
DCHECK(indexed_db_context_.get());
}
BrowsingDataIndexedDBHelperImpl::~BrowsingDataIndexedDBHelperImpl() {
}
void BrowsingDataIndexedDBHelperImpl::StartFetching(
const base::Callback<void(const std::list<IndexedDBInfo>&)>& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!is_fetching_);
DCHECK_EQ(false, callback.is_null());
is_fetching_ = true;
completion_callback_ = callback;
BrowserThread::PostTask(
BrowserThread::WEBKIT_DEPRECATED, FROM_HERE,
base::Bind(
&BrowsingDataIndexedDBHelperImpl::FetchIndexedDBInfoInWebKitThread,
this));
}
void BrowsingDataIndexedDBHelperImpl::CancelNotification() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
completion_callback_.Reset();
}
void BrowsingDataIndexedDBHelperImpl::DeleteIndexedDB(
const GURL& origin) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
BrowserThread::PostTask(
BrowserThread::WEBKIT_DEPRECATED, FROM_HERE,
base::Bind(
&BrowsingDataIndexedDBHelperImpl::DeleteIndexedDBInWebKitThread, this,
origin));
}
void BrowsingDataIndexedDBHelperImpl::FetchIndexedDBInfoInWebKitThread() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
std::vector<GURL> origins = indexed_db_context_->GetAllOrigins();
for (std::vector<GURL>::const_iterator iter = origins.begin();
iter != origins.end(); ++iter) {
const GURL& origin = *iter;
if (origin.SchemeIs(chrome::kExtensionScheme))
continue; // Extension state is not considered browsing data.
indexed_db_info_.push_back(IndexedDBInfo(
origin,
indexed_db_context_->GetOriginDiskUsage(origin),
indexed_db_context_->GetOriginLastModified(origin)));
}
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&BrowsingDataIndexedDBHelperImpl::NotifyInUIThread, this));
}
void BrowsingDataIndexedDBHelperImpl::NotifyInUIThread() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(is_fetching_);
// Note: completion_callback_ mutates only in the UI thread, so it's safe to
// test it here.
if (!completion_callback_.is_null()) {
completion_callback_.Run(indexed_db_info_);
completion_callback_.Reset();
}
is_fetching_ = false;
}
void BrowsingDataIndexedDBHelperImpl::DeleteIndexedDBInWebKitThread(
const GURL& origin) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
indexed_db_context_->DeleteForOrigin(origin);
}
} // namespace
BrowsingDataIndexedDBHelper::IndexedDBInfo::IndexedDBInfo(
const GURL& origin,
int64 size,
base::Time last_modified)
: origin(origin),
size(size),
last_modified(last_modified) {
}
BrowsingDataIndexedDBHelper::IndexedDBInfo::~IndexedDBInfo() {}
// static
BrowsingDataIndexedDBHelper* BrowsingDataIndexedDBHelper::Create(
Profile* profile) {
return new BrowsingDataIndexedDBHelperImpl(profile);
}
CannedBrowsingDataIndexedDBHelper::
PendingIndexedDBInfo::PendingIndexedDBInfo() {
}
CannedBrowsingDataIndexedDBHelper::
PendingIndexedDBInfo::PendingIndexedDBInfo(const GURL& origin,
const string16& description)
: origin(origin),
description(description) {
}
CannedBrowsingDataIndexedDBHelper::
PendingIndexedDBInfo::~PendingIndexedDBInfo() {
}
CannedBrowsingDataIndexedDBHelper::CannedBrowsingDataIndexedDBHelper()
: is_fetching_(false) {
}
CannedBrowsingDataIndexedDBHelper* CannedBrowsingDataIndexedDBHelper::Clone() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
CannedBrowsingDataIndexedDBHelper* clone =
new CannedBrowsingDataIndexedDBHelper();
base::AutoLock auto_lock(lock_);
clone->pending_indexed_db_info_ = pending_indexed_db_info_;
clone->indexed_db_info_ = indexed_db_info_;
return clone;
}
void CannedBrowsingDataIndexedDBHelper::AddIndexedDB(
const GURL& origin, const string16& description) {
base::AutoLock auto_lock(lock_);
pending_indexed_db_info_.push_back(PendingIndexedDBInfo(origin, description));
}
void CannedBrowsingDataIndexedDBHelper::Reset() {
base::AutoLock auto_lock(lock_);
indexed_db_info_.clear();
pending_indexed_db_info_.clear();
}
bool CannedBrowsingDataIndexedDBHelper::empty() const {
base::AutoLock auto_lock(lock_);
return indexed_db_info_.empty() && pending_indexed_db_info_.empty();
}
void CannedBrowsingDataIndexedDBHelper::StartFetching(
const base::Callback<void(const std::list<IndexedDBInfo>&)>& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(!is_fetching_);
DCHECK_EQ(false, callback.is_null());
is_fetching_ = true;
completion_callback_ = callback;
BrowserThread::PostTask(
BrowserThread::WEBKIT_DEPRECATED, FROM_HERE,
base::Bind(
&CannedBrowsingDataIndexedDBHelper::ConvertPendingInfoInWebKitThread,
this));
}
CannedBrowsingDataIndexedDBHelper::~CannedBrowsingDataIndexedDBHelper() {}
void CannedBrowsingDataIndexedDBHelper::ConvertPendingInfoInWebKitThread() {
base::AutoLock auto_lock(lock_);
for (std::list<PendingIndexedDBInfo>::const_iterator
info = pending_indexed_db_info_.begin();
info != pending_indexed_db_info_.end(); ++info) {
bool duplicate = false;
for (std::list<IndexedDBInfo>::iterator
indexed_db = indexed_db_info_.begin();
indexed_db != indexed_db_info_.end(); ++indexed_db) {
if (indexed_db->origin == info->origin) {
duplicate = true;
break;
}
}
if (duplicate)
continue;
indexed_db_info_.push_back(IndexedDBInfo(
info->origin,
0,
base::Time()));
}
pending_indexed_db_info_.clear();
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&CannedBrowsingDataIndexedDBHelper::NotifyInUIThread, this));
}
void CannedBrowsingDataIndexedDBHelper::NotifyInUIThread() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK(is_fetching_);
// Completion_callback_ mutates only in the UI thread, so it's safe to test it
// here.
if (!completion_callback_.is_null()) {
completion_callback_.Run(indexed_db_info_);
completion_callback_.Reset();
}
is_fetching_ = false;
}
void CannedBrowsingDataIndexedDBHelper::CancelNotification() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
completion_callback_.Reset();
}
| 32.542435 | 80 | 0.755301 | [
"vector"
] |
fea4d965b20665cbeb223617a74d435d265064f0 | 3,695 | cpp | C++ | leetcode/problems/medium/2043-simple-bank-system.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 18 | 2020-08-27T05:27:50.000Z | 2022-03-08T02:56:48.000Z | leetcode/problems/medium/2043-simple-bank-system.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | null | null | null | leetcode/problems/medium/2043-simple-bank-system.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 1 | 2020-10-13T05:23:58.000Z | 2020-10-13T05:23:58.000Z | /*
Simple Bank System
https://leetcode.com/problems/simple-bank-system/
You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initial balance of balance[i].
Execute all the valid transactions. A transaction is valid if:
The given account number(s) are between 1 and n, and
The amount of money withdrawn or transferred from is less than or equal to the balance of the account.
Implement the Bank class:
Bank(long[] balance) Initializes the object with the 0-indexed integer array balance.
boolean transfer(int account1, int account2, long money) Transfers money dollars from the account numbered account1 to the account numbered account2. Return true if the transaction was successful, false otherwise.
boolean deposit(int account, long money) Deposit money dollars into the account numbered account. Return true if the transaction was successful, false otherwise.
boolean withdraw(int account, long money) Withdraw money dollars from the account numbered account. Return true if the transaction was successful, false otherwise.
Example 1:
Input
["Bank", "withdraw", "transfer", "deposit", "transfer", "withdraw"]
[[[10, 100, 20, 50, 30]], [3, 10], [5, 1, 20], [5, 20], [3, 4, 15], [10, 50]]
Output
[null, true, true, true, false, false]
Explanation
Bank bank = new Bank([10, 100, 20, 50, 30]);
bank.withdraw(3, 10); // return true, account 3 has a balance of $20, so it is valid to withdraw $10.
// Account 3 has $20 - $10 = $10.
bank.transfer(5, 1, 20); // return true, account 5 has a balance of $30, so it is valid to transfer $20.
// Account 5 has $30 - $20 = $10, and account 1 has $10 + $20 = $30.
bank.deposit(5, 20); // return true, it is valid to deposit $20 to account 5.
// Account 5 has $10 + $20 = $30.
bank.transfer(3, 4, 15); // return false, the current balance of account 3 is $10,
// so it is invalid to transfer $15 from it.
bank.withdraw(10, 50); // return false, it is invalid because account 10 does not exist.
Constraints:
n == balance.length
1 <= n, account, account1, account2 <= 105
0 <= balance[i], money <= 1012
At most 104 calls will be made to each function transfer, deposit, withdraw.
*/
class Bank {
public:
map<int, long long> m;
int n;
Bank(vector<long long>& balance) {
n = balance.size();
for(int i = 1; i <= n; i++) m[i] = balance[i - 1];
}
bool transfer(int account1, int account2, long long money) {
if(1 <= account1 && account1 <= n && 1 <= account2 && account2 <= n) {
if(withdraw(account1, money)) {
return deposit(account2, money);
}
}
return false;
}
bool deposit(int account, long long money) {
if(1 <= account && account <= n) {
m[account] += money;
return true;
}
return false;
}
bool withdraw(int account, long long money) {
if(1 <= account && account <= n) {
if(m[account] >= money) {
m[account] -= money;
return true;
}
}
return false;
}
};
/**
* Your Bank object will be instantiated and called as such:
* Bank* obj = new Bank(balance);
* bool param_1 = obj->transfer(account1,account2,money);
* bool param_2 = obj->deposit(account,money);
* bool param_3 = obj->withdraw(account,money);
*/ | 40.604396 | 344 | 0.636806 | [
"object",
"vector"
] |
fea7582bc95d8424d432870d5bb8939927e277a2 | 6,789 | cc | C++ | pytorch/pytorch-native/src/main/native/ai_djl_pytorch_jni_PyTorchLibrary_ivalue.cc | goswamig/djl | f63d5f6a1cea10e8600b7362aaa196fc771ae108 | [
"Apache-2.0"
] | 1 | 2021-04-03T16:29:16.000Z | 2021-04-03T16:29:16.000Z | pytorch/pytorch-native/src/main/native/ai_djl_pytorch_jni_PyTorchLibrary_ivalue.cc | goswamig/djl | f63d5f6a1cea10e8600b7362aaa196fc771ae108 | [
"Apache-2.0"
] | 1 | 2021-02-24T20:56:01.000Z | 2021-02-24T20:56:01.000Z | pytorch/pytorch-native/src/main/native/ai_djl_pytorch_jni_PyTorchLibrary_ivalue.cc | goswamig/djl | f63d5f6a1cea10e8600b7362aaa196fc771ae108 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 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 <djl/utils.h>
#include <torch/script.h>
#include "ai_djl_pytorch_jni_PyTorchLibrary.h"
#include "djl_pytorch_jni_exception.h"
#include "djl_pytorch_utils.h"
JNIEXPORT jlong JNICALL Java_ai_djl_pytorch_jni_PyTorchLibrary_iValueFromTensor(
JNIEnv* env, jobject jthis, jlong jhandle) {
API_BEGIN()
const auto* ivalue_ptr = new torch::IValue(*reinterpret_cast<torch::Tensor*>(jhandle));
return reinterpret_cast<uintptr_t>(ivalue_ptr);
API_END_RETURN()
}
JNIEXPORT jlong JNICALL Java_ai_djl_pytorch_jni_PyTorchLibrary_iValueFromList(
JNIEnv* env, jobject jthis, jlongArray jtensor_ptrs) {
jsize len = env->GetArrayLength(jtensor_ptrs);
jlong* jptrs = env->GetLongArrayElements(jtensor_ptrs, JNI_FALSE);
torch::List<torch::Tensor> list;
list.reserve(len);
for (size_t i = 0; i < len; ++i) {
list.emplace_back(*reinterpret_cast<torch::Tensor*>(jptrs[i]));
}
env->ReleaseLongArrayElements(jtensor_ptrs, jptrs, JNI_ABORT);
auto* result_ptr = new torch::IValue(list);
return reinterpret_cast<uintptr_t>(result_ptr);
}
JNIEXPORT jlong JNICALL Java_ai_djl_pytorch_jni_PyTorchLibrary_iValueFromDict(
JNIEnv* env, jobject jthis, jlongArray jtensor_ptrs, jobjectArray jnames) {
auto len = static_cast<size_t>(env->GetArrayLength(jtensor_ptrs));
jlong* jptrs = env->GetLongArrayElements(jtensor_ptrs, JNI_FALSE);
torch::Dict<std::string, torch::Tensor> dict;
dict.reserve(len);
for (size_t i = 0; i < len; ++i) {
auto jname = (jstring) env->GetObjectArrayElement(jnames, i);
std::string name = djl::utils::jni::GetStringFromJString(env, jname);
dict.insert(name, *reinterpret_cast<torch::Tensor*>(jptrs[i]));
}
env->ReleaseLongArrayElements(jtensor_ptrs, jptrs, JNI_ABORT);
env->DeleteLocalRef(jnames);
auto* result_ptr = new torch::IValue(dict);
return reinterpret_cast<uintptr_t>(result_ptr);
}
JNIEXPORT jlong JNICALL Java_ai_djl_pytorch_jni_PyTorchLibrary_iValueToTensor(
JNIEnv* env, jobject jthis, jlong jhandle) {
API_BEGIN()
auto* tensor_ptr = new torch::Tensor(reinterpret_cast<torch::IValue*>(jhandle)->toTensor());
return reinterpret_cast<uintptr_t>(tensor_ptr);
API_END_RETURN()
}
JNIEXPORT jlongArray JNICALL Java_ai_djl_pytorch_jni_PyTorchLibrary_iValueToListFromTuple(
JNIEnv* env, jobject jthis, jlong jhandle) {
API_BEGIN()
auto* ivalue_ptr = reinterpret_cast<torch::IValue*>(jhandle);
std::vector<torch::IValue> ivalue_vec = ivalue_ptr->toTuple()->elements();
return djl::utils::jni::GetPtrArrayFromContainer<std::vector<torch::IValue>, torch::IValue>(env, ivalue_vec);
API_END_RETURN()
}
JNIEXPORT jlongArray JNICALL Java_ai_djl_pytorch_jni_PyTorchLibrary_iValueToTensorList(
JNIEnv* env, jobject jthis, jlong jhandle) {
API_BEGIN()
auto* ivalue_ptr = reinterpret_cast<torch::IValue*>(jhandle);
torch::List<torch::Tensor> tensor_list = ivalue_ptr->toTensorList();
return djl::utils::jni::GetPtrArrayFromContainer<torch::List<torch::Tensor>, torch::Tensor>(env, tensor_list);
API_END_RETURN()
}
JNIEXPORT jlongArray JNICALL Java_ai_djl_pytorch_jni_PyTorchLibrary_iValueToList(
JNIEnv* env, jobject jthis, jlong jhandle) {
API_BEGIN()
auto* ivalue_ptr = reinterpret_cast<torch::IValue*>(jhandle);
torch::List<torch::IValue> ivalue_list = ivalue_ptr->toList();
return djl::utils::jni::GetPtrArrayFromContainer<torch::List<torch::IValue>, torch::IValue>(env, ivalue_list);
API_END_RETURN()
}
JNIEXPORT jlongArray JNICALL Java_ai_djl_pytorch_jni_PyTorchLibrary_iValueToMap(
JNIEnv* env, jobject jthis, jlong jhandle) {
API_BEGIN()
auto* ivalue_ptr = reinterpret_cast<torch::IValue*>(jhandle);
torch::Dict<torch::IValue, torch::IValue> dict = ivalue_ptr->toGenericDict();
size_t len = dict.size() * 2;
jlongArray jarray = env->NewLongArray(len);
std::vector<jlong> jptrs;
jptrs.reserve(len);
size_t array_iter = 0;
for (auto it = dict.begin(); it != dict.end(); ++it) {
const auto* key_ptr = new torch::IValue(it->key());
jptrs[array_iter++] = reinterpret_cast<uintptr_t>(key_ptr);
const auto* value_ptr = new torch::IValue(it->value());
jptrs[array_iter++] = reinterpret_cast<uintptr_t>(value_ptr);
}
env->SetLongArrayRegion(jarray, 0, len, jptrs.data());
return jarray;
API_END_RETURN()
}
JNIEXPORT jstring JNICALL Java_ai_djl_pytorch_jni_PyTorchLibrary_iValueToString(
JNIEnv* env, jobject jthis, jlong jhandle) {
API_BEGIN()
auto* ivalue_ptr = reinterpret_cast<torch::IValue*>(jhandle);
return env->NewStringUTF(ivalue_ptr->toString()->string().c_str());
API_END_RETURN()
}
JNIEXPORT jboolean JNICALL Java_ai_djl_pytorch_jni_PyTorchLibrary_iValueIsString(
JNIEnv* env, jobject jthis, jlong jhandle) {
API_BEGIN()
return reinterpret_cast<torch::IValue*>(jhandle)->isString();
API_END_RETURN()
}
JNIEXPORT jboolean JNICALL Java_ai_djl_pytorch_jni_PyTorchLibrary_iValueIsTensor(
JNIEnv* env, jobject jthis, jlong jhandle) {
API_BEGIN()
return reinterpret_cast<torch::IValue*>(jhandle)->isTensor();
API_END_RETURN()
}
JNIEXPORT jboolean JNICALL Java_ai_djl_pytorch_jni_PyTorchLibrary_iValueIsTensorList(
JNIEnv* env, jobject jthis, jlong jhandle) {
API_BEGIN()
return reinterpret_cast<torch::IValue*>(jhandle)->isTensorList();
API_END_RETURN()
}
JNIEXPORT jboolean JNICALL Java_ai_djl_pytorch_jni_PyTorchLibrary_iValueIsList(
JNIEnv* env, jobject jthis, jlong jhandle) {
API_BEGIN()
return reinterpret_cast<torch::IValue*>(jhandle)->isList();
API_END_RETURN()
}
JNIEXPORT jboolean JNICALL Java_ai_djl_pytorch_jni_PyTorchLibrary_iValueIsMap(
JNIEnv* env, jobject jthis, jlong jhandle) {
API_BEGIN()
return reinterpret_cast<torch::IValue*>(jhandle)->isGenericDict();
API_END_RETURN()
}
JNIEXPORT jboolean JNICALL Java_ai_djl_pytorch_jni_PyTorchLibrary_iValueIsTuple(
JNIEnv* env, jobject jthis, jlong jhandle) {
API_BEGIN()
return reinterpret_cast<torch::IValue*>(jhandle)->isTuple();
API_END_RETURN()
}
JNIEXPORT void JNICALL Java_ai_djl_pytorch_jni_PyTorchLibrary_torchDeleteIValue(
JNIEnv* env, jobject jthis, jlong jhandle) {
API_BEGIN()
auto* ivalue_ptr = reinterpret_cast<torch::IValue*>(jhandle);
delete ivalue_ptr;
API_END()
}
| 39.242775 | 120 | 0.758285 | [
"vector"
] |
fea7e038ad80842fcb3abd6728161e6acf73d1b5 | 6,805 | hpp | C++ | source/problem/SWE/discretization_EHDG/kernels_processor/ehdg_swe_proc_ompi_step.hpp | kentonwho/dgswemv2 | 917da15ebf1ba4f511b6735a632e58e3e0499076 | [
"MIT"
] | null | null | null | source/problem/SWE/discretization_EHDG/kernels_processor/ehdg_swe_proc_ompi_step.hpp | kentonwho/dgswemv2 | 917da15ebf1ba4f511b6735a632e58e3e0499076 | [
"MIT"
] | null | null | null | source/problem/SWE/discretization_EHDG/kernels_processor/ehdg_swe_proc_ompi_step.hpp | kentonwho/dgswemv2 | 917da15ebf1ba4f511b6735a632e58e3e0499076 | [
"MIT"
] | null | null | null | #ifndef EHDG_SWE_PROC_OMPI_STEP_HPP
#define EHDG_SWE_PROC_OMPI_STEP_HPP
#include "ehdg_swe_kernels_processor.hpp"
namespace SWE {
namespace EHDG {
template <typename OMPISimType>
void Problem::step_ompi(OMPISimType* sim, uint begin_sim_id, uint end_sim_id) {
auto& sim_units = sim->sim_units;
// Here one assumes that there is at lease one sim unit present
// This is of course not always true
for (uint stage = 0; stage < sim_units[0]->stepper.GetNumStages(); ++stage) {
for (uint su_id = begin_sim_id; su_id < end_sim_id; ++su_id) {
if (sim_units[su_id]->parser.ParsingInput()) {
sim_units[su_id]->parser.ParseInput(sim_units[su_id]->stepper, sim_units[su_id]->discretization.mesh);
}
}
Problem::stage_ompi(sim, begin_sim_id, end_sim_id);
}
for (uint su_id = begin_sim_id; su_id < end_sim_id; ++su_id) {
if (sim_units[su_id]->writer.WritingOutput()) {
sim_units[su_id]->writer.WriteOutput(sim_units[su_id]->stepper, sim_units[su_id]->discretization.mesh);
}
}
}
template <typename OMPISimType>
void Problem::stage_ompi(OMPISimType* sim, uint begin_sim_id, uint end_sim_id) {
auto& sim_units = sim->sim_units;
for (uint su_id = begin_sim_id; su_id < end_sim_id; ++su_id) {
if (sim_units[su_id]->writer.WritingVerboseLog()) {
sim_units[su_id]->writer.GetLogFile()
<< "Current (time, stage): (" << sim_units[su_id]->stepper.GetTimeAtCurrentStage() << ','
<< sim_units[su_id]->stepper.GetStage() << ')' << std::endl;
sim_units[su_id]->writer.GetLogFile() << "Exchanging data" << std::endl;
}
sim_units[su_id]->communicator.ReceiveAll(CommTypes::bound_state, sim_units[su_id]->stepper.GetTimestamp());
sim_units[su_id]->discretization.mesh.CallForEachDistributedBoundary([&sim_units, su_id](auto& dbound) {
Problem::global_distributed_boundary_kernel(sim_units[su_id]->stepper, dbound);
});
sim_units[su_id]->communicator.SendAll(CommTypes::bound_state, sim_units[su_id]->stepper.GetTimestamp());
}
for (uint su_id = begin_sim_id; su_id < end_sim_id; ++su_id) {
if (sim_units[su_id]->writer.WritingVerboseLog()) {
sim_units[su_id]->writer.GetLogFile() << "Starting work before receive" << std::endl;
}
/* Global Pre Receive Step */
sim_units[su_id]->discretization.mesh.CallForEachInterface([&sim_units, su_id](auto& intface) {
Problem::global_interface_kernel(sim_units[su_id]->stepper, intface);
});
sim_units[su_id]->discretization.mesh.CallForEachBoundary(
[&sim_units, su_id](auto& bound) { Problem::global_boundary_kernel(sim_units[su_id]->stepper, bound); });
sim_units[su_id]->discretization.mesh_skeleton.CallForEachEdgeInterface([&sim_units, su_id](auto& edge_int) {
Problem::global_edge_interface_kernel(sim_units[su_id]->stepper, edge_int);
});
sim_units[su_id]->discretization.mesh_skeleton.CallForEachEdgeBoundary([&sim_units, su_id](auto& edge_bound) {
Problem::global_edge_boundary_kernel(sim_units[su_id]->stepper, edge_bound);
});
/* Global Pre Receive Step */
/* Local Pre Receive Step */
sim_units[su_id]->discretization.mesh.CallForEachElement(
[&sim_units, su_id](auto& elt) { Problem::local_volume_kernel(sim_units[su_id]->stepper, elt); });
sim_units[su_id]->discretization.mesh.CallForEachElement(
[&sim_units, su_id](auto& elt) { Problem::local_source_kernel(sim_units[su_id]->stepper, elt); });
sim_units[su_id]->discretization.mesh.CallForEachInterface([&sim_units, su_id](auto& intface) {
Problem::local_interface_kernel(sim_units[su_id]->stepper, intface);
});
sim_units[su_id]->discretization.mesh.CallForEachBoundary(
[&sim_units, su_id](auto& bound) { Problem::local_boundary_kernel(sim_units[su_id]->stepper, bound); });
/* Local Pre Receive Step */
if (sim_units[su_id]->writer.WritingVerboseLog()) {
sim_units[su_id]->writer.GetLogFile() << "Finished work before receive" << std::endl;
}
}
for (uint su_id = begin_sim_id; su_id < end_sim_id; ++su_id) {
if (sim_units[su_id]->writer.WritingVerboseLog()) {
sim_units[su_id]->writer.GetLogFile()
<< "Starting to wait on receive with timestamp: " << sim_units[su_id]->stepper.GetTimestamp()
<< std::endl;
}
sim_units[su_id]->communicator.WaitAllReceives(CommTypes::bound_state,
sim_units[su_id]->stepper.GetTimestamp());
if (sim_units[su_id]->writer.WritingVerboseLog()) {
sim_units[su_id]->writer.GetLogFile() << "Starting work after receive" << std::endl;
}
/* Global Post Receive Step */
sim_units[su_id]->discretization.mesh_skeleton.CallForEachEdgeDistributed(
[&sim_units, su_id](auto& edge_dbound) {
Problem::global_edge_distributed_kernel(sim_units[su_id]->stepper, edge_dbound);
});
/* Global Post Receive Step */
/* Local Post Receive Step */
sim_units[su_id]->discretization.mesh.CallForEachDistributedBoundary([&sim_units, su_id](auto& dbound) {
Problem::local_distributed_boundary_kernel(sim_units[su_id]->stepper, dbound);
});
sim_units[su_id]->discretization.mesh.CallForEachElement([&sim_units, su_id](auto& elt) {
auto& state = elt.data.state[sim_units[su_id]->stepper.GetStage()];
state.solution = elt.ApplyMinv(state.rhs);
sim_units[su_id]->stepper.UpdateState(elt);
});
++(sim_units[su_id]->stepper);
/* Local Post Receive Step */
if (sim_units[su_id]->writer.WritingVerboseLog()) {
sim_units[su_id]->writer.GetLogFile() << "Finished work after receive" << std::endl << std::endl;
}
}
if (SWE::PostProcessing::slope_limiting) {
CS_slope_limiter_ompi(sim_units, begin_sim_id, end_sim_id, CommTypes::baryctr_state);
}
for (uint su_id = begin_sim_id; su_id < end_sim_id; ++su_id) {
sim_units[su_id]->discretization.mesh.CallForEachElement([&sim_units, su_id](auto& elt) {
bool nan_found = SWE::scrutinize_solution(sim_units[su_id]->stepper, elt);
if (nan_found)
MPI_Abort(MPI_COMM_WORLD, 0);
});
}
for (uint su_id = begin_sim_id; su_id < end_sim_id; ++su_id) {
sim_units[su_id]->communicator.WaitAllSends(CommTypes::bound_state, sim_units[su_id]->stepper.GetTimestamp());
}
}
}
}
#endif
| 43.343949 | 118 | 0.64673 | [
"mesh"
] |
fea9fbe03a7ab5dbf9a36d714251e925d473a3b3 | 4,275 | cpp | C++ | FireRender.Maya.Src/frWrap.cpp | V-Gorash/RadeonProRenderMayaPlugin | 3b844ad4602177eeb413c0708bd75c4439d97a7d | [
"Apache-2.0"
] | 22 | 2020-05-15T14:07:40.000Z | 2022-03-17T08:10:42.000Z | FireRender.Maya.Src/frWrap.cpp | V-Gorash/RadeonProRenderMayaPlugin | 3b844ad4602177eeb413c0708bd75c4439d97a7d | [
"Apache-2.0"
] | 38 | 2020-05-13T23:24:21.000Z | 2022-02-28T12:16:51.000Z | FireRender.Maya.Src/frWrap.cpp | V-Gorash/RadeonProRenderMayaPlugin | 3b844ad4602177eeb413c0708bd75c4439d97a7d | [
"Apache-2.0"
] | 19 | 2020-05-13T15:24:09.000Z | 2022-03-29T13:36:02.000Z | /**********************************************************************
Copyright 2020 Advanced Micro Devices, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
********************************************************************/
#include <GL/glew.h>
#include <iostream>
#include "frWrap.h"
namespace frw
{
Value Value::unknown = Value(1, 0, 1);
FrameBuffer::FrameBuffer(const Context& context, rpr_GLuint* glTextureId) :
Object(nullptr, context)
{
FRW_PRINT_DEBUG("CreateGLInteropFrameBuffer()");
rpr_framebuffer h = nullptr;
auto res = rprContextCreateFramebufferFromGLTexture2D(context.Handle(), GL_TEXTURE_2D, 0, *glTextureId, &h);
checkStatusThrow(res);
m->Attach(h);
}
Value Value::Inverse() const
{
return Value(1) / *this;
}
template <typename... Args>
inline void DebugPrint(const char* format, const Args&... args)
{
#ifdef _DEBUG
#ifdef _WIN32
static char buf[0x10000] = {};
sprintf_s(buf, 0x10000, format, args...);
OutputDebugStringA(buf);
#elif defined(__linux__)
static char buf[0x10000] = {};
snprintf(buf, 0x10000, format, args...);
std::clog << buf;
#else
// other platforms?
#endif
#endif
}
#define NODE_ENTRY(a) { frw::a, #a }
void Context::DumpParameterInfo()
{
int stackSize = GetMaterialStackSize();
DebugPrint("Radeon ProRender Context Information\n");
DebugPrint("\tMaterial Stack Size: %d\n", stackSize);
DebugPrint("\tContext Parameters: \n");
for (int i = 0, n = GetParameterCount(); i < n; i++)
{
auto info = GetParameterInfo(i);
DebugPrint("\t + %s; id 0x%X; type 0x%X; // %s\n", info.name.c_str(), info.id, info.type, info.description.c_str());
}
MaterialSystem ms(*this);
struct { int type; const char* typeName; } nodeTypes[] =
{
NODE_ENTRY(ValueTypeArithmetic),
NODE_ENTRY(ValueTypeFresnel),
NODE_ENTRY(ValueTypeNormalMap),
NODE_ENTRY(ValueTypeBumpMap),
NODE_ENTRY(ValueTypeImageMap),
NODE_ENTRY(ValueTypeNoiseMap),
NODE_ENTRY(ValueTypeDotMap),
NODE_ENTRY(ValueTypeGradientMap),
NODE_ENTRY(ValueTypeCheckerMap),
NODE_ENTRY(ValueTypeConstant),
NODE_ENTRY(ValueTypeLookup),
NODE_ENTRY(ValueTypeBlend),
NODE_ENTRY(ValueTypeFresnelSchlick),
NODE_ENTRY(ValueTypePassthrough),
NODE_ENTRY(ShaderTypeDiffuse),
NODE_ENTRY(ShaderTypeMicrofacet),
NODE_ENTRY(ShaderTypeReflection),
NODE_ENTRY(ShaderTypeRefraction),
NODE_ENTRY(ShaderTypeMicrofacetRefraction),
NODE_ENTRY(ShaderTypeTransparent),
NODE_ENTRY(ShaderTypeEmissive),
NODE_ENTRY(ShaderTypeWard),
NODE_ENTRY(ShaderTypeBlend),
NODE_ENTRY(ShaderTypeOrenNayer),
NODE_ENTRY(ShaderTypeDiffuseRefraction),
NODE_ENTRY(ShaderTypeAdd),
NODE_ENTRY(ShaderTypeVolume),
};
DebugPrint("Material Nodes: \n");
for (auto it : nodeTypes)
{
if (auto node = frw::Node(ms, it.type))
{
DebugPrint("\t\tMaterial Node %s (0x%X):\n", it.typeName, it.type);
for (int i = 0, n = node.GetParameterCount(); i < n; i++)
{
auto info = node.GetParameterInfo(i);
DebugPrint("\t\t + %s; id 0x%X; type 0x%X;\n", info.name.c_str(), info.id, info.type);
}
}
}
}
void UVProceduralNode::SetOrigin(const frw::Value& value)
{
SetValue(NodeInputOrigin, value);
}
void UVTriplanarNode::SetOrigin(const frw::Value& value)
{
SetValue(NodeInputOffsset, value);
}
void BaseUVNode::SetInputZAxis(const frw::Value& value)
{
SetValue(NodeInputZAxis, value);
}
void BaseUVNode::SetInputXAxis(const frw::Value& value)
{
SetValue(NodeInputXAxis, value);
}
void BaseUVNode::SetInputUVScale(const frw::Value& value)
{
SetValue(NodeInputUVScale, value);
}
void Node::_SetInputNode(rpr_material_node_input key, const Shader& shader)
{
if (shader)
{
AddReference(shader);
shader.AttachToMaterialInput(Handle(), key);
}
}
}
| 27.75974 | 119 | 0.693801 | [
"object"
] |
feb31b6755f0dcf4104427529259eeb739d0bc2b | 1,268 | hpp | C++ | include/spl/group.hpp | momokrono/spl | 36c2e2ceb6c0d51a57423e5422054aae09c58f83 | [
"MIT"
] | 5 | 2020-04-25T15:42:31.000Z | 2022-03-31T09:11:45.000Z | include/spl/group.hpp | momokrono/spl | 36c2e2ceb6c0d51a57423e5422054aae09c58f83 | [
"MIT"
] | 6 | 2020-04-24T17:09:22.000Z | 2020-07-31T13:43:09.000Z | include/spl/group.hpp | momokrono/spl | 36c2e2ceb6c0d51a57423e5422054aae09c58f83 | [
"MIT"
] | null | null | null | /**
* @author : rbrugo, momokrono
* @file : renderer
* @created : Tuesday Nov 10, 2020 10:54:18 CET
* @license : MIT
* */
#ifndef RENDERER_HPP
#define RENDERER_HPP
#include <vector>
#include "spl/any_drawable.hpp"
#include "spl/viewport.hpp"
#include "spl/primitives/vertex.hpp"
namespace spl::graphics
{
class group
{
std::vector<any_drawable> _buffer;
vertex _origin{0, 0};
public:
void render_on(graphics::viewport img) const noexcept;
template <drawable T>
group & push(T obj) noexcept;
void clear() noexcept { _buffer.clear(); }
void reserve(std::size_t n) { _buffer.reserve(n); }
auto position() noexcept -> vertex & { return _origin; }
auto position() const noexcept -> vertex { return _origin; }
auto & translate(int_fast32_t x, int_fast32_t y) { _origin += {x, y}; return *this; }
};
inline
void group::render_on(graphics::viewport img) const noexcept
{
auto view = viewport{img, _origin.x, _origin.y};
for (auto const & obj : _buffer) {
obj.render_on(view);
}
}
template <drawable T>
inline
auto group::push(T obj) noexcept -> group &
{
_buffer.emplace_back(std::move(obj));
return *this;
}
} // namespace spl::graphics
#endif /* RENDERER_HPP */
| 22.245614 | 89 | 0.650631 | [
"vector"
] |
feb60d4270d7e8112940f4302c5f364da06af30a | 6,274 | cpp | C++ | src/SketchSolver/NumericalSynthesis/Utils/GradUtil.cpp | natebragg/sketch-backend | 6ecbb6f724149d50d290997fef5e2e1e92ab3d9e | [
"X11"
] | 17 | 2020-08-20T14:54:11.000Z | 2022-03-31T00:28:40.000Z | src/SketchSolver/NumericalSynthesis/Utils/GradUtil.cpp | natebragg/sketch-backend | 6ecbb6f724149d50d290997fef5e2e1e92ab3d9e | [
"X11"
] | 1 | 2022-03-01T16:53:05.000Z | 2022-03-04T04:02:09.000Z | src/SketchSolver/NumericalSynthesis/Utils/GradUtil.cpp | natebragg/sketch-backend | 6ecbb6f724149d50d290997fef5e2e1e92ab3d9e | [
"X11"
] | 2 | 2020-12-04T20:47:51.000Z | 2020-12-06T01:45:04.000Z | #include "IntervalGrad.h"
gsl_vector* GradUtil::tmp;
gsl_vector* GradUtil::tmp1;
gsl_vector* GradUtil::tmp2;
gsl_vector* GradUtil::tmp3;
gsl_vector* GradUtil::tmpT;
double GradUtil::BETA;
double GradUtil::ALPHA;
void GradUtil::allocateTempVectors(int size) {
tmp = gsl_vector_alloc(size);
tmp1 = gsl_vector_alloc(size);
tmp2 = gsl_vector_alloc(size);
tmp3 = gsl_vector_alloc(size);
tmpT = gsl_vector_alloc(size);
}
void GradUtil::clearTempVectors() {
gsl_vector_free(tmp);
gsl_vector_free(tmp1);
gsl_vector_free(tmp2);
gsl_vector_free(tmp3);
gsl_vector_free(tmpT);
}
double GradUtil::findMin(double val1, double val2, gsl_vector* grad1, gsl_vector* grad2, gsl_vector* l) {
vector<double> vals;
vector<gsl_vector*> grads;
vals.push_back(val1);
vals.push_back(val2);
grads.push_back(grad1);
grads.push_back(grad2);
return findMin(vals, grads, l);
}
double GradUtil::findMin(const vector<double>& vals, const vector<gsl_vector*>& grads, gsl_vector* l) {
double minv = MAXVAL;
for (int i = 0; i < vals.size(); i++) {
if (vals[i] < minv) {
minv = vals[i];
}
}
return softMinMax(vals, grads, l, -ALPHA, minv);
//return minv;
}
double GradUtil::findMax(double val1, double val2, gsl_vector* grad1, gsl_vector* grad2, gsl_vector* h) {
vector<double> vals;
vector<gsl_vector*> grads;
vals.push_back(val1);
vals.push_back(val2);
grads.push_back(grad1);
grads.push_back(grad2);
return findMax(vals, grads, h);
}
double GradUtil::findMax(const vector<double>& vals, const vector<gsl_vector*>& grads, gsl_vector* h) {
double maxv = MINVAL;
for (int i = 0; i < vals.size(); i++) {
if (vals[i] > maxv) {
maxv = vals[i];
}
}
return softMinMax(vals, grads, h, ALPHA, maxv);
//return maxv;
}
double GradUtil::findMax(const vector<double>& vals) {
double maxv = MINVAL;
for (int i = 0; i < vals.size(); i++) {
if (vals[i] > maxv) {
maxv = vals[i];
}
}
return softMinMax(vals, ALPHA, maxv);
}
double GradUtil::sigmoid(double x, gsl_vector* grads, gsl_vector* out) {
double scale = BETA;
double v = 1.0/(1.0 + exp(scale * x));
double d = -1.0*scale*v*(1-v);
if (d > 1e3) {
cout << "LARGE GRADIENT FACTOR in sigmoid " << d << endl;
}
gsl_blas_dcopy(grads, out);
gsl_blas_dscal(d, out);
return v;
}
double GradUtil::sigmoid(double x) {
double scale = BETA;
double v = 1.0/(1.0 + exp(scale * x));
return v;
}
/* Computes the gradient of log(e^(alpha*(v1 - t)) + e^(alpha*(v2 - t)) ... )
If alpha > 0, the result is the soft max of the values
If alpha < 0, the result is the soft min of the values */
double GradUtil::softMinMax(const vector<double>& vals, const vector<gsl_vector*>& grads, gsl_vector* l, double alpha, double t) {
double expval = 0.0;
for (int i = 0; i < vals.size(); i++) {
expval += exp(alpha * (vals[i] - t));
}
gsl_vector_set_zero(l);
for (int i = 0; i < vals.size(); i++) {
if (exp(alpha * (vals[i] - t)) / expval > 1e3) {
cout << "LARGE GRADIENT FACTOR in softMinMax" << endl;
}
gsl_blas_daxpy(exp(alpha*(vals[i] - t)), grads[i], l);
}
gsl_blas_dscal(1.0/expval, l);
return (log(expval) + alpha * t)/alpha;
}
double GradUtil::softMinMax(const vector<double>& vals, double alpha, double t) {
double expval = 0.0;
for (int i = 0; i < vals.size(); i++) {
expval += exp(alpha * (vals[i] - t));
}
return (log(expval) + alpha * t)/alpha;
}
void GradUtil::default_grad(gsl_vector* out) {
gsl_vector_set_zero(out);
}
// computes the grad of mval + fval i.e. mgrads + fgrads
void GradUtil::compute_plus_grad(gsl_vector* mgrads, gsl_vector* fgrads, gsl_vector* out) {
#ifdef _NOGSL
int sz = out->size;
alignas(64) double* __restrict oo = out->data;
alignas(64) double* __restrict fg = fgrads->data;
alignas(64) double* __restrict mg = mgrads->data;
for (int i = 0; i < sz; ++i) {
*oo =(*fg) + (*mg);
++fg; ++mg; ++oo;
}
#else
gsl_blas_dcopy(mgrads, out);
gsl_blas_daxpy(1.0, fgrads, out);
#endif
}
// computes the grad of mval * fval i.e. mval*fgrads + fval*mgrads
void GradUtil::compute_mult_grad(double mval, double fval, gsl_vector* mgrads, gsl_vector* fgrads, gsl_vector* out) {
#ifdef _NOGSL
int sz = out->size;
double* __restrict oo = out->data;
double* __restrict fg = fgrads->data;
double* __restrict mg = mgrads->data;
for (int i = 0; i < sz; ++i) {
*oo = mval*(*fg) + fval*(*mg);
++fg; ++mg; ++oo;
}
#else
gsl_blas_dcopy(mgrads, out);
gsl_blas_dscal(fval, out);
gsl_blas_daxpy(mval, fgrads, out);
#endif
}
// computes the grad of mval / fval i.e (fval * mgrads - mval * fgrads) / (fval * fval)
void GradUtil::compute_div_grad(double mval, double fval, gsl_vector* mgrads, gsl_vector* fgrads, gsl_vector* out) {
Assert(mgrads != tmpT && fgrads != tmpT, "Error: tmp will be overwritten");
gsl_blas_dcopy(mgrads, out);
gsl_blas_dscal(fval, out);
gsl_blas_daxpy(-mval, fgrads, out);
gsl_blas_dscal(1.0/(fval*fval), out);
}
void GradUtil::compute_neg_grad(gsl_vector* mgrads, gsl_vector* out) {
gsl_blas_dcopy(mgrads, out);
gsl_blas_dscal(-1.0, out);
}
void GradUtil::compute_square_grad(double mval, gsl_vector* mgrads, gsl_vector* out) {
double dm = 2.0 * mval;
gsl_blas_dcopy(mgrads, out);
gsl_blas_dscal(dm, out);
}
void GradUtil::compute_arctan_grad(double mval, gsl_vector* mgrads, gsl_vector* out) {
double dm = 1.0/(mval * mval + 1.0);
gsl_blas_dcopy(mgrads, out);
gsl_blas_dscal(dm, out);
}
void GradUtil::compute_sin_grad(double mval, gsl_vector* mgrads, gsl_vector* out) {
double dm = cos(mval);
gsl_blas_dcopy(mgrads, out);
gsl_blas_dscal(dm, out);
}
void GradUtil::compute_cos_grad(double mval, gsl_vector* mgrads, gsl_vector* out) {
double dm = -sin(mval);
gsl_blas_dcopy(mgrads, out);
gsl_blas_dscal(dm, out);
}
void GradUtil::compute_tan_grad(double mval, gsl_vector* mgrads, gsl_vector* out) {
double dm = 1.0/(cos(mval)*cos(mval));
gsl_blas_dcopy(mgrads, out);
gsl_blas_dscal(dm, out);
}
void GradUtil::compute_sqrt_grad(double mval, gsl_vector* mgrads, gsl_vector* out) {
double dm = 0.5/sqrt(mval);
gsl_blas_dcopy(mgrads, out);
gsl_blas_dscal(dm, out);
}
void GradUtil::compute_exp_grad(double mval, gsl_vector* mgrads, gsl_vector* out) {
double dm = exp(mval);
gsl_blas_dcopy(mgrads, out);
gsl_blas_dscal(dm, out);
}
| 28.38914 | 130 | 0.677558 | [
"vector"
] |
feb7f50b7da7dcfad6ad7cb4638321a0ea008d55 | 8,126 | cc | C++ | src/rime/gear/simplifier.cc | mengzhisuoliu/librime | 9eeeffcc0fa24d9dbfd6d58f936eb9fe60be3e70 | [
"BSD-3-Clause"
] | 2,326 | 2015-01-26T13:34:46.000Z | 2022-03-30T06:53:47.000Z | src/rime/gear/simplifier.cc | mengzhisuoliu/librime | 9eeeffcc0fa24d9dbfd6d58f936eb9fe60be3e70 | [
"BSD-3-Clause"
] | 440 | 2015-01-26T12:29:17.000Z | 2022-03-31T13:21:59.000Z | src/rime/gear/simplifier.cc | mengzhisuoliu/librime | 9eeeffcc0fa24d9dbfd6d58f936eb9fe60be3e70 | [
"BSD-3-Clause"
] | 491 | 2015-01-24T17:58:21.000Z | 2022-03-27T21:17:37.000Z | //
// Copyright RIME Developers
// Distributed under the BSD License
//
// 2011-12-12 GONG Chen <chen.sst@gmail.com>
//
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <stdint.h>
#include <utf8.h>
#include <utility>
#include <rime/candidate.h>
#include <rime/common.h>
#include <rime/config.h>
#include <rime/context.h>
#include <rime/engine.h>
#include <rime/schema.h>
#include <rime/service.h>
#include <rime/translation.h>
#include <rime/gear/simplifier.h>
#include <opencc/Config.hpp> // Place OpenCC #includes here to avoid VS2015 compilation errors
#include <opencc/Converter.hpp>
#include <opencc/Conversion.hpp>
#include <opencc/ConversionChain.hpp>
#include <opencc/Dict.hpp>
#include <opencc/DictEntry.hpp>
static const char* quote_left = "\xe3\x80\x94"; //"\xef\xbc\x88";
static const char* quote_right = "\xe3\x80\x95"; //"\xef\xbc\x89";
namespace rime {
class Opencc {
public:
Opencc(const string& config_path) {
LOG(INFO) << "initializing opencc: " << config_path;
opencc::Config config;
try {
converter_ = config.NewFromFile(config_path);
const list<opencc::ConversionPtr> conversions =
converter_->GetConversionChain()->GetConversions();
dict_ = conversions.front()->GetDict();
}
catch (...) {
LOG(ERROR) << "opencc config not found: " << config_path;
}
}
bool ConvertWord(const string& text, vector<string>* forms) {
if (dict_ == nullptr) return false;
opencc::Optional<const opencc::DictEntry*> item = dict_->Match(text);
if (item.IsNull()) {
// Match not found
return false;
} else {
const opencc::DictEntry* entry = item.Get();
for (auto&& value : entry->Values()) {
forms->push_back(std::move(value));
}
return forms->size() > 0;
}
}
bool RandomConvertText(const string& text, string* simplified) {
if (dict_ == nullptr) return false;
const char *phrase = text.c_str();
std::ostringstream buffer;
for (const char* pstr = phrase; *pstr != '\0';) {
opencc::Optional<const opencc::DictEntry*> matched = dict_->MatchPrefix(pstr);
size_t matchedLength;
if (matched.IsNull()) {
matchedLength = opencc::UTF8Util::NextCharLength(pstr);
buffer << opencc::UTF8Util::FromSubstr(pstr, matchedLength);
} else {
matchedLength = matched.Get()->KeyLength();
size_t i = rand() % (matched.Get()->NumValues());
buffer << matched.Get()->Values().at(i);
}
pstr += matchedLength;
}
*simplified = buffer.str();
return *simplified != text;
}
bool ConvertText(const string& text, string* simplified) {
if (converter_ == nullptr) return false;
*simplified = converter_->Convert(text);
return *simplified != text;
}
private:
opencc::ConverterPtr converter_;
opencc::DictPtr dict_;
};
// Simplifier
Simplifier::Simplifier(const Ticket& ticket) : Filter(ticket),
TagMatching(ticket) {
if (name_space_ == "filter") {
name_space_ = "simplifier";
}
if (Config* config = engine_->schema()->config()) {
string tips;
if (config->GetString(name_space_ + "/tips", &tips) ||
config->GetString(name_space_ + "/tip", &tips)) {
tips_level_ = (tips == "all") ? kTipsAll :
(tips == "char") ? kTipsChar : kTipsNone;
}
config->GetBool(name_space_ + "/show_in_comment", &show_in_comment_);
comment_formatter_.Load(config->GetList(name_space_ + "/comment_format"));
config->GetBool(name_space_ + "/random", &random_);
config->GetString(name_space_ + "/option_name", &option_name_);
config->GetString(name_space_ + "/opencc_config", &opencc_config_);
if (auto types = config->GetList(name_space_ + "/excluded_types")) {
for (auto it = types->begin(); it != types->end(); ++it) {
if (auto value = As<ConfigValue>(*it)) {
excluded_types_.insert(value->str());
}
}
}
}
if (option_name_.empty()) {
option_name_ = "simplification"; // default switcher option
}
if (opencc_config_.empty()) {
opencc_config_ = "t2s.json"; // default opencc config file
}
if (random_) {
srand((unsigned)time(NULL));
}
}
void Simplifier::Initialize() {
using namespace boost::filesystem;
initialized_ = true; // no retry
path opencc_config_path = opencc_config_;
if (opencc_config_path.extension().string() == ".ini") {
LOG(ERROR) << "please upgrade opencc_config to an opencc 1.0 config file.";
return;
}
if (opencc_config_path.is_relative()) {
path user_config_path = Service::instance().deployer().user_data_dir;
path shared_config_path = Service::instance().deployer().shared_data_dir;
(user_config_path /= "opencc") /= opencc_config_path;
(shared_config_path /= "opencc") /= opencc_config_path;
if (exists(user_config_path)) {
opencc_config_path = user_config_path;
}
else if (exists(shared_config_path)) {
opencc_config_path = shared_config_path;
}
}
try {
opencc_.reset(new Opencc(opencc_config_path.string()));
}
catch (opencc::Exception& e) {
LOG(ERROR) << "Error initializing opencc: " << e.what();
}
}
class SimplifiedTranslation : public PrefetchTranslation {
public:
SimplifiedTranslation(an<Translation> translation,
Simplifier* simplifier)
: PrefetchTranslation(translation), simplifier_(simplifier) {
}
protected:
virtual bool Replenish();
Simplifier* simplifier_;
};
bool SimplifiedTranslation::Replenish() {
auto next = translation_->Peek();
translation_->Next();
if (next && !simplifier_->Convert(next, &cache_)) {
cache_.push_back(next);
}
return !cache_.empty();
}
an<Translation> Simplifier::Apply(an<Translation> translation,
CandidateList* candidates) {
if (!engine_->context()->get_option(option_name_)) { // off
return translation;
}
if (!initialized_) {
Initialize();
}
if (!opencc_) {
return translation;
}
return New<SimplifiedTranslation>(translation, this);
}
void Simplifier::PushBack(const an<Candidate>& original,
CandidateQueue* result, const string& simplified) {
string tips;
string text;
size_t length = utf8::unchecked::distance(original->text().c_str(),
original->text().c_str()
+ original->text().length());
bool show_tips = (tips_level_ == kTipsChar && length == 1) || tips_level_ == kTipsAll;
if (show_in_comment_) {
text = original->text();
if (show_tips) {
tips = simplified;
comment_formatter_.Apply(&tips);
}
} else {
text = simplified;
if (show_tips) {
tips = original->text();
bool modified = comment_formatter_.Apply(&tips);
if (!modified) {
tips = quote_left + original->text() + quote_right;
}
}
}
result->push_back(
New<ShadowCandidate>(
original,
"simplified",
text,
tips));
}
bool Simplifier::Convert(const an<Candidate>& original,
CandidateQueue* result) {
if (excluded_types_.find(original->type()) != excluded_types_.end()) {
return false;
}
bool success = false;
if (random_) {
string simplified;
success = opencc_->RandomConvertText(original->text(), &simplified);
if (success) {
PushBack(original, result, simplified);
}
} else { //!random_
vector<string> forms;
success = opencc_->ConvertWord(original->text(), &forms);
if (success) {
for (size_t i = 0; i < forms.size(); ++i) {
if (forms[i] == original->text()) {
result->push_back(original);
} else {
PushBack(original, result, forms[i]);
}
}
} else {
string simplified;
success = opencc_->ConvertText(original->text(), &simplified);
if (success) {
PushBack(original, result, simplified);
}
}
}
return success;
}
} // namespace rime
| 30.548872 | 94 | 0.624169 | [
"vector"
] |
feb824e9ef98ea17c15443239b33798108bbcd93 | 4,651 | inl | C++ | include/IECorePython/TypedParameterBinding.inl | gcodebackups/cortex-vfx | 72fa6c6eb3327fce4faf01361c8fcc2e1e892672 | [
"BSD-3-Clause"
] | 5 | 2016-07-26T06:09:28.000Z | 2022-03-07T03:58:51.000Z | include/IECorePython/TypedParameterBinding.inl | turbosun/cortex | 4bdc01a692652cd562f3bfa85f3dae99d07c0b15 | [
"BSD-3-Clause"
] | null | null | null | include/IECorePython/TypedParameterBinding.inl | turbosun/cortex | 4bdc01a692652cd562f3bfa85f3dae99d07c0b15 | [
"BSD-3-Clause"
] | 3 | 2015-03-25T18:45:24.000Z | 2020-02-15T15:37:18.000Z | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#ifndef IECOREPYTHON_TYPEDPARAMETERBINDING_INL
#define IECOREPYTHON_TYPEDPARAMETERBINDING_INL
#include "IECore/TypedParameter.h"
#include "IECore/CompoundObject.h"
#include "IECorePython/RunTimeTypedBinding.h"
#include "IECorePython/ParameterBinding.h"
#include "IECorePython/Wrapper.h"
namespace IECorePython
{
template<typename T>
class TypedParameterWrap : public IECore::TypedParameter<T>, public Wrapper< IECore::TypedParameter<T> >
{
public:
IE_CORE_DECLAREMEMBERPTR( TypedParameterWrap<T> );
protected:
static typename IECore::TypedParameter<T>::ObjectType::Ptr makeDefault( boost::python::object defaultValue )
{
typename IECore::TypedParameter<T>::ObjectType::Ptr defaultData;
boost::python::extract<T> de( defaultValue );
if( de.check() )
{
defaultData = new typename IECore::TypedParameter<T>::ObjectType( de() );
}
else
{
defaultData = boost::python::extract<typename IECore::TypedParameter<T>::ObjectType *>( defaultValue )();
}
return defaultData;
}
public :
TypedParameterWrap( PyObject *self, const std::string &n, const std::string &d, boost::python::object dv, const boost::python::object &p = boost::python::tuple(), bool po = false, IECore::CompoundObjectPtr ud = 0 )
: IECore::TypedParameter<T>( n, d, makeDefault( dv ), parameterPresets<typename IECore::TypedParameter<T>::ObjectPresetsContainer>( p ), po, ud ), Wrapper< IECore::TypedParameter<T> >( self, this ) {};
IECOREPYTHON_PARAMETERWRAPPERFNS( IECore::TypedParameter<T> );
};
template<typename T>
void bindTypedParameter()
{
using boost::python::arg;
RunTimeTypedClass<IECore::TypedParameter<T>, typename TypedParameterWrap<T>::Ptr>()
.def(
boost::python::init< const std::string &, const std::string &, boost::python::object, boost::python::optional<const boost::python::object &, bool, IECore::CompoundObjectPtr > >
(
(
arg( "name" ),
arg( "description" ),
arg( "defaultValue" ),
arg( "presets" ) = boost::python::tuple(),
arg( "presetsOnly" ) = false ,
arg( "userData" ) = IECore::CompoundObject::Ptr( 0 )
)
)
)
/// \todo This is a property to match the NumericParameter::numericDefaultValue, but I think they would both be better as functions.
.add_property( "typedDefaultValue", boost::python::make_function( &IECore::TypedParameter<T>::typedDefaultValue, boost::python::return_value_policy<boost::python::copy_const_reference>() ) )
.def( "setTypedValue", &IECore::TypedParameter<T>::setTypedValue )
.def( "getTypedValue", (const T &(IECore::TypedParameter<T>::* )() const)&IECore::TypedParameter<T>::getTypedValue, boost::python::return_value_policy<boost::python::copy_const_reference>() )
.IECOREPYTHON_DEFPARAMETERWRAPPERFNS( IECore::TypedParameter<T> )
;
}
}
#endif // IECOREPYTHON_TYPEDPARAMETERBINDING_INL
| 41.900901 | 216 | 0.706085 | [
"object"
] |
fecc35a1de8aec4b3a07372c4cf1180f83fdac6e | 1,644 | hh | C++ | src/runner/sneaker.hh | jcbaillie/urbi | fb17359b2838cdf8d3c0858abb141e167a9d4bdb | [
"BSD-3-Clause"
] | 16 | 2016-05-10T05:50:58.000Z | 2021-10-05T22:16:13.000Z | src/runner/sneaker.hh | jcbaillie/urbi | fb17359b2838cdf8d3c0858abb141e167a9d4bdb | [
"BSD-3-Clause"
] | 7 | 2016-09-05T10:08:33.000Z | 2019-02-13T10:51:07.000Z | src/runner/sneaker.hh | jcbaillie/urbi | fb17359b2838cdf8d3c0858abb141e167a9d4bdb | [
"BSD-3-Clause"
] | 15 | 2015-01-28T20:27:02.000Z | 2021-09-28T19:26:08.000Z | /*
* Copyright (C) 2008-2012, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#ifndef RUNNER_SNEAKER_HH
# define RUNNER_SNEAKER_HH
# include <ast/ast.hh>
# include <runner/job.hh>
# include <sched/scheduler.hh>
namespace dbg
{
/// Create the sneaker if it hasn't been created yet.
///
/// \param lobby Any lobby.
///
/// \param scheduler The current scheduler.
void create_sneaker_if_needed(object::rLobby lobby,
sched::Scheduler& scheduler);
/// Retrieve the current runner or the sneaker. This should be used
/// only when debugging, when we really need a runner of some kind
/// to execute code.
///
/// \return A runner.
runner::Job& runner_or_sneaker_get();
/// Compare the current Job and determine if this is the sneaker. This is
/// unlikely unless you are debugging.
///
/// \return A runner.
bool is_sneaker(runner::Job& job);
/// The following functions will be called from the debugger. Here
/// are some example uses:
///
/// (gdb) call dbg::dump(object::system_class, 1)
///
/// (gdb) call dbg::eval("System")
///
/// (gdb) call dbg::evalp("6*7")
///
/// (gdb) call dbg::ps()
void dump(const object::rObject& o, int depth);
object::rObject eval(const char* command);
void evalp(const char* command);
void ps();
void pp(ast::rAst);
} // namespace dbg
#endif // RUNNER_SNEAKER_HH
| 26.516129 | 75 | 0.645985 | [
"object"
] |
feccd3893a504ca84334f357e497237d28eda2b9 | 40,507 | cpp | C++ | core/io/marshalls.cpp | Segs/Engine | 754aabfc2708a46f764979a604871633152ce479 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 8 | 2019-09-03T19:58:19.000Z | 2021-06-18T07:11:26.000Z | core/io/marshalls.cpp | Segs/Engine | 754aabfc2708a46f764979a604871633152ce479 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 24 | 2019-09-03T17:35:45.000Z | 2020-10-27T14:36:02.000Z | core/io/marshalls.cpp | nemerle/SegsEngine | b9dd0b5481b92d956befa72c746758d33a1a08c9 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | 6 | 2019-09-27T15:44:35.000Z | 2021-01-23T18:52:51.000Z | /*************************************************************************/
/* marshalls.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "marshalls.h"
#include "core/os/keyboard.h"
#include "core/print_string.h"
#include "core/reference.h"
#include "core/object_db.h"
#include "core/method_bind.h"
#include "core/math/vector2.h"
#include "core/math/transform.h"
#include "core/math/transform_2d.h"
#include "core/math/quat.h"
#include "core/node_path.h"
#include "core/color.h"
#include "core/rid.h"
#include "core/pool_vector.h"
#include "core/dictionary.h"
#include "core/string_utils.inl"
#include <climits>
#include <cstdio>
IMPL_GDCLASS(EncodedObjectAsID)
void EncodedObjectAsID::_bind_methods() {
MethodBinder::bind_method(D_METHOD("set_object_id", {"id"}), &EncodedObjectAsID::set_object_id);
MethodBinder::bind_method(D_METHOD("get_object_id"), &EncodedObjectAsID::get_object_id);
ADD_PROPERTY(PropertyInfo(VariantType::INT, "object_id"), "set_object_id", "get_object_id");
}
void EncodedObjectAsID::set_object_id(ObjectID p_id) {
id = p_id;
}
ObjectID EncodedObjectAsID::get_object_id() const {
return id;
}
#define _S(a) ((int32_t)a)
#define ERR_FAIL_ADD_OF(a, b, err) ERR_FAIL_COND_V(_S(b) < 0 || _S(a) < 0 || _S(a) > INT_MAX - _S(b), err);
#define ERR_FAIL_MUL_OF(a, b, err) ERR_FAIL_COND_V(_S(a) < 0 || _S(b) <= 0 || _S(a) > INT_MAX / _S(b), err);
#define ENCODE_MASK 0xFF
#define ENCODE_FLAG_64 1 << 16
#define ENCODE_FLAG_OBJECT_AS_ID 1 << 16
static Error _decode_string(const uint8_t *&buf, int &len, int *r_len, String &r_string) {
ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
int32_t strlen = decode_uint32(buf);
int32_t pad = 0;
// Handle padding
if (strlen % 4) {
pad = 4 - strlen % 4;
}
buf += 4;
len -= 4;
// Ensure buffer is big enough
ERR_FAIL_ADD_OF(strlen, pad, ERR_FILE_EOF);
ERR_FAIL_COND_V(strlen > (1<<24), ERR_INVALID_DATA);
ERR_FAIL_COND_V(strlen < 0 || strlen + pad > len, ERR_FILE_EOF);
String str((const char *)buf, strlen);
r_string = str;
// Add padding
strlen += pad;
// Update buffer pos, left data count, and return size
buf += strlen;
len -= strlen;
if (r_len) {
(*r_len) += 4 + strlen;
}
return OK;
}
Error decode_variant(Variant &r_variant, const uint8_t *p_buffer, int p_len, int *r_len, bool p_allow_objects) {
const uint8_t *buf = p_buffer;
int len = p_len;
ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
uint32_t type = decode_uint32(buf);
ERR_FAIL_COND_V((type & ENCODE_MASK) >= int(VariantType::VARIANT_MAX), ERR_INVALID_DATA);
buf += 4;
len -= 4;
if (r_len)
*r_len = 4;
VariantType vt = VariantType(type & ENCODE_MASK);
switch (vt) {
case VariantType::NIL: {
r_variant = Variant();
} break;
case VariantType::BOOL: {
ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
bool val = decode_uint32(buf);
r_variant = val;
if (r_len)
(*r_len) += 4;
} break;
case VariantType::INT: {
if (type & ENCODE_FLAG_64) {
ERR_FAIL_COND_V(len < 8, ERR_INVALID_DATA);
int64_t val = decode_uint64(buf);
r_variant = val;
if (r_len)
(*r_len) += 8;
} else {
ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
int32_t val = decode_uint32(buf);
r_variant = val;
if (r_len)
(*r_len) += 4;
}
} break;
case VariantType::FLOAT: {
if (type & ENCODE_FLAG_64) {
ERR_FAIL_COND_V(len < 8, ERR_INVALID_DATA);
double val = decode_double(buf);
r_variant = val;
if (r_len)
(*r_len) += 8;
} else {
ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
float val = decode_float(buf);
r_variant = val;
if (r_len)
(*r_len) += 4;
}
} break;
case VariantType::STRING: {
String str;
Error err = _decode_string(buf, len, r_len, str);
if (err)
return err;
r_variant = str;
} break;
// math types
case VariantType::VECTOR2: {
ERR_FAIL_COND_V(len < 4 * 2, ERR_INVALID_DATA);
Vector2 val;
val.x = decode_float(&buf[0]);
val.y = decode_float(&buf[4]);
r_variant = val;
if (r_len)
(*r_len) += 4 * 2;
} break; // 5
case VariantType::RECT2: {
ERR_FAIL_COND_V(len < 4 * 4, ERR_INVALID_DATA);
Rect2 val;
val.position.x = decode_float(&buf[0]);
val.position.y = decode_float(&buf[4]);
val.size.x = decode_float(&buf[8]);
val.size.y = decode_float(&buf[12]);
r_variant = val;
if (r_len)
(*r_len) += 4 * 4;
} break;
case VariantType::VECTOR3: {
ERR_FAIL_COND_V(len < 4 * 3, ERR_INVALID_DATA);
Vector3 val;
val.x = decode_float(&buf[0]);
val.y = decode_float(&buf[4]);
val.z = decode_float(&buf[8]);
r_variant = val;
if (r_len)
(*r_len) += 4 * 3;
} break;
case VariantType::TRANSFORM2D: {
ERR_FAIL_COND_V(len < 4 * 6, ERR_INVALID_DATA);
Transform2D val;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
val.elements[i][j] = decode_float(&buf[(i * 2 + j) * 4]);
}
}
r_variant = val;
if (r_len)
(*r_len) += 4 * 6;
} break;
case VariantType::PLANE: {
ERR_FAIL_COND_V(len < 4 * 4, ERR_INVALID_DATA);
Plane val;
val.normal.x = decode_float(&buf[0]);
val.normal.y = decode_float(&buf[4]);
val.normal.z = decode_float(&buf[8]);
val.d = decode_float(&buf[12]);
r_variant = val;
if (r_len)
(*r_len) += 4 * 4;
} break;
case VariantType::QUAT: {
ERR_FAIL_COND_V(len < 4 * 4, ERR_INVALID_DATA);
Quat val;
val.x = decode_float(&buf[0]);
val.y = decode_float(&buf[4]);
val.z = decode_float(&buf[8]);
val.w = decode_float(&buf[12]);
r_variant = val;
if (r_len)
(*r_len) += 4 * 4;
} break;
case VariantType::AABB: {
ERR_FAIL_COND_V(len < 4 * 6, ERR_INVALID_DATA);
AABB val;
val.position.x = decode_float(&buf[0]);
val.position.y = decode_float(&buf[4]);
val.position.z = decode_float(&buf[8]);
val.size.x = decode_float(&buf[12]);
val.size.y = decode_float(&buf[16]);
val.size.z = decode_float(&buf[20]);
r_variant = val;
if (r_len)
(*r_len) += 4 * 6;
} break;
case VariantType::BASIS: {
ERR_FAIL_COND_V(len < 4 * 9, ERR_INVALID_DATA);
Basis val;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
val.elements[i][j] = decode_float(&buf[(i * 3 + j) * 4]);
}
}
r_variant = val;
if (r_len)
(*r_len) += 4 * 9;
} break;
case VariantType::TRANSFORM: {
ERR_FAIL_COND_V(len < 4 * 12, ERR_INVALID_DATA);
Transform val;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
val.basis.elements[i][j] = decode_float(&buf[(i * 3 + j) * 4]);
}
}
val.origin[0] = decode_float(&buf[36]);
val.origin[1] = decode_float(&buf[40]);
val.origin[2] = decode_float(&buf[44]);
r_variant = val;
if (r_len)
(*r_len) += 4 * 12;
} break;
// misc types
case VariantType::COLOR: {
ERR_FAIL_COND_V(len < 4 * 4, ERR_INVALID_DATA);
Color val;
val.r = decode_float(&buf[0]);
val.g = decode_float(&buf[4]);
val.b = decode_float(&buf[8]);
val.a = decode_float(&buf[12]);
r_variant = val;
if (r_len)
(*r_len) += 4 * 4;
} break;
case VariantType::STRING_NAME: {
String str;
Error err = _decode_string(buf, len, r_len, str);
if (err) {
return err;
}
r_variant = StringName(str);
} break;
case VariantType::NODE_PATH: {
ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
uint32_t inc_strlen = decode_uint32(buf);
if (inc_strlen & 0x80000000) {
//new format
ERR_FAIL_COND_V(len < 12, ERR_INVALID_DATA);
Vector<StringName> names;
Vector<StringName> subnames;
uint32_t namecount = inc_strlen & 0x7FFFFFFF;
uint32_t subnamecount = decode_uint32(buf + 4);
uint32_t flags = decode_uint32(buf + 8);
len -= 12;
buf += 12;
if (flags & 2) // Obsolete format with property separate from subpath
subnamecount++;
uint32_t total = namecount + subnamecount;
if (r_len)
(*r_len) += 12;
for (uint32_t i = 0; i < total; i++) {
String str;
Error err = _decode_string(buf, len, r_len, str);
if (err)
return err;
StringName sname(str);
if (i < namecount)
names.push_back(sname);
else
subnames.push_back(sname);
}
r_variant = NodePath(eastl::move(names), eastl::move(subnames), flags & 1);
} else {
//old format, just a string
ERR_FAIL_V(ERR_INVALID_DATA);
}
} break;
case VariantType::_RID: {
r_variant = RID();
} break;
case VariantType::OBJECT: {
if (type & ENCODE_FLAG_OBJECT_AS_ID) {
//this _is_ allowed
ERR_FAIL_COND_V(len < 8, ERR_INVALID_DATA);
ObjectID val {decode_uint64(buf)};
if (r_len)
(*r_len) += 8;
if (val.is_null()) {
r_variant = Variant((Object *)nullptr);
} else {
Ref<EncodedObjectAsID> obj_as_id(make_ref_counted<EncodedObjectAsID>());
obj_as_id->set_object_id(val);
r_variant = obj_as_id;
}
} else {
ERR_FAIL_COND_V(!p_allow_objects, ERR_UNAUTHORIZED);
String str;
Error err = _decode_string(buf, len, r_len, str);
if (err)
return err;
if (str.empty()) {
r_variant = Variant((Object *)nullptr);
} else {
Object *obj = ClassDB::instance(StringName(str));
ERR_FAIL_COND_V(!obj, ERR_UNAVAILABLE);
ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
int32_t count = decode_uint32(buf);
buf += 4;
len -= 4;
if (r_len) {
(*r_len) += 4;
}
for (int i = 0; i < count; i++) {
str.clear();
err = _decode_string(buf, len, r_len, str);
if (err)
return err;
Variant value;
int used;
err = decode_variant(value, buf, len, &used, p_allow_objects);
if (err)
return err;
buf += used;
len -= used;
if (r_len) {
(*r_len) += used;
}
obj->set(StringName(str), value);
}
if (object_cast<RefCounted>(obj)) {
REF ref = REF(object_cast<RefCounted>(obj));
r_variant = ref;
} else {
r_variant = Variant(obj);
}
}
}
} break;
case VariantType::DICTIONARY: {
ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
int32_t count = decode_uint32(buf);
// bool shared = count&0x80000000;
count &= 0x7FFFFFFF;
buf += 4;
len -= 4;
if (r_len) {
(*r_len) += 4;
}
Dictionary d;
for (int i = 0; i < count; i++) {
Variant key, value;
int used;
Error err = decode_variant(key, buf, len, &used, p_allow_objects);
ERR_FAIL_COND_V_MSG(err != OK, err, "Error when trying to decode Variant.");
buf += used;
len -= used;
if (r_len) {
(*r_len) += used;
}
err = decode_variant(value, buf, len, &used, p_allow_objects);
ERR_FAIL_COND_V_MSG(err != OK, err, "Error when trying to decode Variant.");
buf += used;
len -= used;
if (r_len) {
(*r_len) += used;
}
d[key] = value;
}
r_variant = d;
} break;
case VariantType::ARRAY: {
ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
int32_t count = decode_uint32(buf);
// bool shared = count&0x80000000;
count &= 0x7FFFFFFF;
buf += 4;
len -= 4;
if (r_len) {
(*r_len) += 4;
}
Array varr;
for (int i = 0; i < count; i++) {
int used = 0;
Variant v;
Error err = decode_variant(v, buf, len, &used, p_allow_objects);
ERR_FAIL_COND_V_MSG(err != OK, err, "Error when trying to decode Variant.");
buf += used;
len -= used;
varr.push_back(v);
if (r_len) {
(*r_len) += used;
}
}
r_variant = varr;
} break;
// arrays
case VariantType::POOL_BYTE_ARRAY: {
ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
int32_t count = decode_uint32(buf);
buf += 4;
len -= 4;
ERR_FAIL_COND_V(count < 0 || count > len, ERR_INVALID_DATA);
PoolVector<uint8_t> data;
if (count) {
data.resize(count);
PoolVector<uint8_t>::Write w = data.write();
for (int32_t i = 0; i < count; i++) {
w[i] = buf[i];
}
}
r_variant = data;
if (r_len) {
if (count % 4)
(*r_len) += 4 - count % 4;
(*r_len) += 4 + count;
}
} break;
case VariantType::POOL_INT_ARRAY: {
ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
int32_t count = decode_uint32(buf);
buf += 4;
len -= 4;
ERR_FAIL_MUL_OF(count, 4, ERR_INVALID_DATA);
ERR_FAIL_COND_V(count < 0 || count * 4 > len, ERR_INVALID_DATA);
PoolVector<int> data;
if (count) {
//const int*rbuf=(const int*)buf;
data.resize(count);
PoolVector<int>::Write w = data.write();
for (int32_t i = 0; i < count; i++) {
w[i] = decode_uint32(&buf[i * 4]);
}
}
r_variant = Variant(data);
if (r_len) {
(*r_len) += 4 + count * sizeof(int);
}
} break;
case VariantType::POOL_REAL_ARRAY: {
ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
int32_t count = decode_uint32(buf);
buf += 4;
len -= 4;
ERR_FAIL_MUL_OF(count, 4, ERR_INVALID_DATA);
ERR_FAIL_COND_V(count < 0 || count * 4 > len, ERR_INVALID_DATA);
PoolVector<float> data;
if (count) {
//const float*rbuf=(const float*)buf;
data.resize(count);
PoolVector<float>::Write w = data.write();
for (int32_t i = 0; i < count; i++) {
w[i] = decode_float(&buf[i * 4]);
}
}
r_variant = data;
if (r_len) {
(*r_len) += 4 + count * sizeof(float);
}
} break;
case VariantType::POOL_STRING_ARRAY: {
ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
int32_t count = decode_uint32(buf);
PoolVector<String> strings;
buf += 4;
len -= 4;
if (r_len)
(*r_len) += 4;
//printf("string count: %i\n",count);
for (int32_t i = 0; i < count; i++) {
String str;
Error err = _decode_string(buf, len, r_len, str);
if (err)
return err;
strings.push_back(str);
}
r_variant = strings;
} break;
case VariantType::POOL_VECTOR2_ARRAY: {
ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
int32_t count = decode_uint32(buf);
buf += 4;
len -= 4;
ERR_FAIL_MUL_OF(count, 4 * 2, ERR_INVALID_DATA);
ERR_FAIL_COND_V(count < 0 || count * 4 * 2 > len, ERR_INVALID_DATA);
PoolVector<Vector2> varray;
if (r_len) {
(*r_len) += 4;
}
if (count) {
varray.resize(count);
PoolVector<Vector2>::Write w = varray.write();
for (int32_t i = 0; i < count; i++) {
w[i].x = decode_float(buf + i * 4 * 2 + 4 * 0);
w[i].y = decode_float(buf + i * 4 * 2 + 4 * 1);
}
int adv = 4 * 2 * count;
if (r_len)
(*r_len) += adv;
}
r_variant = Variant(varray);
} break;
case VariantType::POOL_VECTOR3_ARRAY: {
ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
int32_t count = decode_uint32(buf);
buf += 4;
len -= 4;
ERR_FAIL_MUL_OF(count, 4 * 3, ERR_INVALID_DATA);
ERR_FAIL_COND_V(count < 0 || count * 4 * 3 > len, ERR_INVALID_DATA);
PoolVector<Vector3> varray;
if (r_len) {
(*r_len) += 4;
}
if (count) {
varray.resize(count);
PoolVector<Vector3>::Write w = varray.write();
for (int32_t i = 0; i < count; i++) {
w[i].x = decode_float(buf + i * 4 * 3 + 4 * 0);
w[i].y = decode_float(buf + i * 4 * 3 + 4 * 1);
w[i].z = decode_float(buf + i * 4 * 3 + 4 * 2);
}
int adv = 4 * 3 * count;
if (r_len)
(*r_len) += adv;
}
r_variant = varray;
} break;
case VariantType::POOL_COLOR_ARRAY: {
ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
int32_t count = decode_uint32(buf);
buf += 4;
len -= 4;
ERR_FAIL_MUL_OF(count, 4 * 4, ERR_INVALID_DATA);
ERR_FAIL_COND_V(count < 0 || count * 4 * 4 > len, ERR_INVALID_DATA);
PoolVector<Color> carray;
if (r_len) {
(*r_len) += 4;
}
if (count) {
carray.resize(count);
PoolVector<Color>::Write w = carray.write();
for (int32_t i = 0; i < count; i++) {
w[i].r = decode_float(buf + i * 4 * 4 + 4 * 0);
w[i].g = decode_float(buf + i * 4 * 4 + 4 * 1);
w[i].b = decode_float(buf + i * 4 * 4 + 4 * 2);
w[i].a = decode_float(buf + i * 4 * 4 + 4 * 3);
}
int adv = 4 * 4 * count;
if (r_len)
(*r_len) += adv;
}
r_variant = carray;
} break;
default: {
ERR_FAIL_V(ERR_BUG);
}
}
return OK;
}
static void _encode_string(StringView p_string, uint8_t *&buf, int &r_len) {
size_t len=p_string.size();
if (buf) {
encode_uint32(len, buf);
buf += 4;
memcpy(buf, p_string.data(), len);
buf += len;
}
r_len += 4 + len;
while (r_len % 4) {
r_len++; //pad
if (buf) {
*(buf++) = 0;
}
}
}
Error encode_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len, bool p_full_objects) {
uint8_t *buf = r_buffer;
r_len = 0;
uint32_t flags = 0;
switch (p_variant.get_type()) {
case VariantType::INT: {
int64_t val = p_variant.as<int64_t>();
if (val > (int64_t)INT_MAX || val < (int64_t)INT_MIN) {
flags |= ENCODE_FLAG_64;
}
} break;
case VariantType::FLOAT: {
double d = p_variant.as<float>();
float f = d;
if (double(f) != d) {
flags |= ENCODE_FLAG_64; //always encode real as double
}
} break;
case VariantType::OBJECT: {
#ifdef DEBUG_ENABLED
// Test for potential wrong values sent by the debugger when it breaks.
Object *obj = p_variant.as<Object *>();
if (!obj || !ObjectDB::instance_validate(obj)) {
// Object is invalid, send a NULL instead.
if (buf) {
encode_uint32((uint32_t)VariantType::NIL, buf);
}
r_len += 4;
return OK;
}
#endif // DEBUG_ENABLED
if (!p_full_objects) {
flags |= ENCODE_FLAG_OBJECT_AS_ID;
}
} break;
default: {
} // nothing to do at this stage
}
if (buf) {
encode_uint32(uint32_t(p_variant.get_type()) | flags, buf);
buf += 4;
}
r_len += 4;
switch (p_variant.get_type()) {
case VariantType::NIL: {
//nothing to do
} break;
case VariantType::BOOL: {
if (buf) {
encode_uint32(p_variant.as<bool>(), buf);
}
r_len += 4;
} break;
case VariantType::INT: {
if (flags & ENCODE_FLAG_64) {
//64 bits
if (buf) {
encode_uint64(p_variant.as<int64_t>(), buf);
}
r_len += 8;
} else {
if (buf) {
encode_uint32(p_variant.as<int32_t>(), buf);
}
r_len += 4;
}
} break;
case VariantType::FLOAT: {
if (flags & ENCODE_FLAG_64) {
if (buf) {
encode_double(p_variant.as<double>(), buf);
}
r_len += 8;
} else {
if (buf) {
encode_float(p_variant.as<float>(), buf);
}
r_len += 4;
}
} break;
case VariantType::NODE_PATH: {
NodePath np = p_variant.as<NodePath>();
if (buf) {
encode_uint32(uint32_t(np.get_name_count()) | 0x80000000, buf); //for compatibility with the old format
encode_uint32(np.get_subname_count(), buf + 4);
uint32_t np_flags = 0;
if (np.is_absolute())
np_flags |= 1;
encode_uint32(np_flags, buf + 8);
buf += 12;
}
r_len += 12;
int total = np.get_name_count() + np.get_subname_count();
for (int i = 0; i < total; i++) {
StringView str;
if (i < np.get_name_count())
str = np.get_name(i);
else
str = np.get_subname(i - np.get_name_count());
int pad = 0;
if (str.length() % 4)
pad = 4 - str.length() % 4;
if (buf) {
encode_uint32(str.length(), buf);
buf += 4;
memcpy(buf, str.data(), str.length());
buf += pad + str.length();
}
r_len += 4 + str.length() + pad;
}
} break;
case VariantType::STRING: {
_encode_string(p_variant.as<String>(), buf, r_len);
} break;
// math types
case VariantType::VECTOR2: {
if (buf) {
Vector2 v2 = p_variant.as<Vector2>();
encode_float(v2.x, &buf[0]);
encode_float(v2.y, &buf[4]);
}
r_len += 2 * 4;
} break; // 5
case VariantType::RECT2: {
if (buf) {
Rect2 r2 = p_variant.as<Rect2>();
encode_float(r2.position.x, &buf[0]);
encode_float(r2.position.y, &buf[4]);
encode_float(r2.size.x, &buf[8]);
encode_float(r2.size.y, &buf[12]);
}
r_len += 4 * 4;
} break;
case VariantType::VECTOR3: {
if (buf) {
Vector3 v3 = p_variant.as<Vector3>();
encode_float(v3.x, &buf[0]);
encode_float(v3.y, &buf[4]);
encode_float(v3.z, &buf[8]);
}
r_len += 3 * 4;
} break;
case VariantType::TRANSFORM2D: {
if (buf) {
Transform2D val = p_variant.as<Transform2D>();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
memcpy(&buf[(i * 2 + j) * 4], &val.elements[i][j], sizeof(float));
}
}
}
r_len += 6 * 4;
} break;
case VariantType::PLANE: {
if (buf) {
Plane p = p_variant.as<Plane>();
encode_float(p.normal.x, &buf[0]);
encode_float(p.normal.y, &buf[4]);
encode_float(p.normal.z, &buf[8]);
encode_float(p.d, &buf[12]);
}
r_len += 4 * 4;
} break;
case VariantType::QUAT: {
if (buf) {
Quat q = p_variant.as<Quat>();
encode_float(q.x, &buf[0]);
encode_float(q.y, &buf[4]);
encode_float(q.z, &buf[8]);
encode_float(q.w, &buf[12]);
}
r_len += 4 * 4;
} break;
case VariantType::AABB: {
if (buf) {
AABB aabb = p_variant.as<AABB>();
encode_float(aabb.position.x, &buf[0]);
encode_float(aabb.position.y, &buf[4]);
encode_float(aabb.position.z, &buf[8]);
encode_float(aabb.size.x, &buf[12]);
encode_float(aabb.size.y, &buf[16]);
encode_float(aabb.size.z, &buf[20]);
}
r_len += 6 * 4;
} break;
case VariantType::BASIS: {
if (buf) {
Basis val = p_variant.as<Basis>();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
memcpy(&buf[(i * 3 + j) * 4], &val.elements[i][j], sizeof(float));
}
}
}
r_len += 9 * 4;
} break;
case VariantType::TRANSFORM: {
if (buf) {
Transform val = p_variant.as<Transform>();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
memcpy(&buf[(i * 3 + j) * 4], &val.basis.elements[i][j], sizeof(float));
}
}
encode_float(val.origin.x, &buf[36]);
encode_float(val.origin.y, &buf[40]);
encode_float(val.origin.z, &buf[44]);
}
r_len += 12 * 4;
} break;
// misc types
case VariantType::COLOR: {
if (buf) {
Color c = p_variant.as<Color>();
encode_float(c.r, &buf[0]);
encode_float(c.g, &buf[4]);
encode_float(c.b, &buf[8]);
encode_float(c.a, &buf[12]);
}
r_len += 4 * 4;
} break;
case VariantType::STRING_NAME: {
_encode_string((StringName)p_variant, buf, r_len);
} break;
case VariantType::_RID: {
} break;
case VariantType::OBJECT: {
if (p_full_objects) {
Object *obj = p_variant.as<Object *>();
if (!obj) {
if (buf) {
encode_uint32(0, buf);
}
r_len += 4;
} else {
_encode_string(StringView(obj->get_class()), buf, r_len);
Vector<PropertyInfo> props;
obj->get_property_list(&props);
int pc = 0;
for(PropertyInfo &E : props ) {
if (!(E.usage & PROPERTY_USAGE_STORAGE))
continue;
pc++;
}
if (buf) {
encode_uint32(pc, buf);
buf += 4;
}
r_len += 4;
for(PropertyInfo &E : props ) {
if (!(E.usage & PROPERTY_USAGE_STORAGE))
continue;
_encode_string(E.name, buf, r_len);
int len;
Error err = encode_variant(obj->get(E.name), buf, len, p_full_objects);
if (err)
return err;
ERR_FAIL_COND_V(len % 4, ERR_BUG);
r_len += len;
if (buf)
buf += len;
}
}
} else {
if (buf) {
Object *obj = p_variant.as<Object *>();
ObjectID id {0ULL};
if (obj && ObjectDB::instance_validate(obj)) {
id = obj->get_instance_id();
}
encode_uint64(id, buf);
}
r_len += 8;
}
} break;
case VariantType::DICTIONARY: {
Dictionary d = p_variant.as<Dictionary>();
if (buf) {
encode_uint32(uint32_t(d.size()), buf);
buf += 4;
}
r_len += 4;
Vector<Variant> keys(d.get_key_list());
for(Variant &E : keys ) {
/*
CharString utf8 = E->->utf8();
if (buf) {
encode_uint32(utf8.length()+1,buf);
buf+=4;
copymem(buf,utf8.get_data(),utf8.length()+1);
}
r_len+=4+utf8.length()+1;
while (r_len%4)
r_len++; //pad
*/
Variant *v = d.getptr(E);
int len;
encode_variant(v ? E : Variant("[Deleted Object]"), buf, len, p_full_objects);
ERR_FAIL_COND_V(len % 4, ERR_BUG);
r_len += len;
if (buf)
buf += len;
encode_variant(v ? *v : Variant(), buf, len, p_full_objects);
ERR_FAIL_COND_V(len % 4, ERR_BUG);
r_len += len;
if (buf)
buf += len;
}
} break;
case VariantType::ARRAY: {
Array v = p_variant.as<Array>();
if (buf) {
encode_uint32(uint32_t(v.size()), buf);
buf += 4;
}
r_len += 4;
for (int i = 0; i < v.size(); i++) {
int len;
encode_variant(v.get(i), buf, len, p_full_objects);
ERR_FAIL_COND_V(len % 4, ERR_BUG);
r_len += len;
if (buf)
buf += len;
}
} break;
// arrays
case VariantType::POOL_BYTE_ARRAY: {
PoolVector<uint8_t> data = p_variant.as<PoolVector<uint8_t>>();
int datalen = data.size();
int datasize = sizeof(uint8_t);
if (buf) {
encode_uint32(datalen, buf);
buf += 4;
PoolVector<uint8_t>::Read r = data.read();
memcpy(buf, &r[0], datalen * datasize);
buf += datalen * datasize;
}
r_len += 4 + datalen * datasize;
while (r_len % 4) {
r_len++;
if (buf)
*(buf++) = 0;
}
} break;
case VariantType::POOL_INT_ARRAY: {
PoolVector<int> data = p_variant.as<PoolVector<int>>();
int datalen = data.size();
int datasize = sizeof(int32_t);
if (buf) {
encode_uint32(datalen, buf);
buf += 4;
PoolVector<int>::Read r = data.read();
for (int i = 0; i < datalen; i++)
encode_uint32(r[i], &buf[i * datasize]);
}
r_len += 4 + datalen * datasize;
} break;
case VariantType::POOL_REAL_ARRAY: {
PoolVector<real_t> data = p_variant.as<PoolVector<real_t>>();
int datalen = data.size();
int datasize = sizeof(real_t);
if (buf) {
encode_uint32(datalen, buf);
buf += 4;
PoolVector<real_t>::Read r = data.read();
for (int i = 0; i < datalen; i++)
encode_float(r[i], &buf[i * datasize]);
}
r_len += 4 + datalen * datasize;
} break;
case VariantType::POOL_STRING_ARRAY: {
PoolVector<String> data = p_variant.as<PoolVector<String>>();
int len = data.size();
if (buf) {
encode_uint32(len, buf);
buf += 4;
}
r_len += 4;
for (int i = 0; i < len; i++) {
String utf8(data.get(i));
if (buf) {
encode_uint32(utf8.length(), buf);
buf += 4;
memcpy(buf, utf8.data(), utf8.length());
buf += utf8.length();
}
r_len += 4 + utf8.length() + 1;
while (r_len % 4) {
r_len++; //pad
if (buf)
*(buf++) = 0;
}
}
} break;
case VariantType::POOL_VECTOR2_ARRAY: {
PoolVector<Vector2> data = p_variant.as<PoolVector<Vector2>>();
int len = data.size();
if (buf) {
encode_uint32(len, buf);
buf += 4;
}
r_len += 4;
if (buf) {
for (int i = 0; i < len; i++) {
Vector2 v = data.get(i);
encode_float(v.x, &buf[0]);
encode_float(v.y, &buf[4]);
buf += 4 * 2;
}
}
r_len += 4 * 2 * len;
} break;
case VariantType::POOL_VECTOR3_ARRAY: {
PoolVector<Vector3> data = p_variant.as<PoolVector<Vector3>>();
int len = data.size();
if (buf) {
encode_uint32(len, buf);
buf += 4;
}
r_len += 4;
if (buf) {
for (int i = 0; i < len; i++) {
Vector3 v = data.get(i);
encode_float(v.x, &buf[0]);
encode_float(v.y, &buf[4]);
encode_float(v.z, &buf[8]);
buf += 4 * 3;
}
}
r_len += 4 * 3 * len;
} break;
case VariantType::POOL_COLOR_ARRAY: {
PoolVector<Color> data = p_variant.as<PoolVector<Color>>();
int len = data.size();
if (buf) {
encode_uint32(len, buf);
buf += 4;
}
r_len += 4;
if (buf) {
for (int i = 0; i < len; i++) {
Color c = data.get(i);
encode_float(c.r, &buf[0]);
encode_float(c.g, &buf[4]);
encode_float(c.b, &buf[8]);
encode_float(c.a, &buf[12]);
buf += 4 * 4;
}
}
r_len += 4 * 4 * len;
} break;
default: {
ERR_FAIL_V(ERR_BUG);
}
}
return OK;
}
| 28.708009 | 119 | 0.423334 | [
"object",
"vector",
"transform"
] |
fecdc677690e5afbbd9fe722e5248c42742554dc | 6,836 | cpp | C++ | contracts/eos/BancorConverter/src/reserves.cpp | EOS-Nation/contracts_eos | 25b88b9d299e692d2f7a420531002b21baa9495c | [
"Apache-2.0"
] | 118 | 2018-09-20T03:58:07.000Z | 2022-02-15T23:10:27.000Z | contracts/eos/BancorConverter/src/reserves.cpp | EOS-Nation/contracts_eos | 25b88b9d299e692d2f7a420531002b21baa9495c | [
"Apache-2.0"
] | 11 | 2018-11-21T11:33:12.000Z | 2020-05-07T03:46:13.000Z | contracts/eos/BancorConverter/src/reserves.cpp | bancorprotocol/contracts_eos | e46b6225898da9c72db7d754e99f04a911513da5 | [
"Apache-2.0"
] | 62 | 2018-09-20T12:49:46.000Z | 2022-02-11T17:31:16.000Z | [[eosio::action]]
void BancorConverter::setreserve( const symbol_code converter_currency_code, const symbol currency, const name contract, const uint64_t ratio ) {
BancorConverter::converters _converters( get_self(), get_self().value );
const auto converter = _converters.find( converter_currency_code.raw() );
// validate input
require_auth( converter->owner );
check( converter != _converters.end(), "converter does not exist");
check( ratio > 0 && ratio <= PPM_RESOLUTION, "weight must be between 1 and " + std::to_string(PPM_RESOLUTION));
check( is_account(contract), "token contract is not an account");
check( currency.is_valid(), "invalid reserve symbol");
check( !converter->reserve_balances.count( currency.code() ), "reserve already exists");
_converters.modify(converter, same_payer, [&](auto& row) {
row.reserve_balances[currency.code()] = {{0, currency}, contract};
row.reserve_weights[currency.code()] = ratio;
double total_ratio = 0.0;
for ( const auto item : row.reserve_weights ) {
total_ratio += item.second;
}
check(total_ratio <= PPM_RESOLUTION, "total ratio cannot exceed the maximum ratio");
});
}
[[eosio::action]]
void BancorConverter::delreserve( const symbol_code converter, const symbol_code reserve ) {
check(!is_converter_active(converter), "a reserve can only be deleted if it's converter is inactive");
BancorConverter::converters _converters( get_self(), get_self().value );
const auto itr = _converters.find( converter.raw() );
check( itr != _converters.end(), "converter not found");
check( itr->reserve_balances.count( reserve ), "reserve balance not found");
_converters.modify(itr, same_payer, [&](auto& row) {
row.reserve_balances.erase( reserve );
row.reserve_weights.erase( reserve );
});
}
[[eosio::action]]
void BancorConverter::fund( const name sender, const asset quantity ) {
require_auth( sender );
// tables
BancorConverter::converters _converters( get_self(), get_self().value );
BancorConverter::settings _settings( get_self(), get_self().value );
// settings
const name multi_token = _settings.get().multi_token;
// converter
const symbol_code converter = quantity.symbol.code();
const auto itr = _converters.find( converter.raw() );
// validate input
check( quantity.is_valid() && quantity.amount > 0, "invalid quantity");
check( itr != _converters.end(), "converter does not exist");
check( itr->currency == quantity.symbol, "quantity symbol mismatch converter");
// reserves
std::vector<BancorConverter::reserve> reserves = BancorConverter::get_reserves( converter );
const asset supply = get_supply( multi_token, converter );
double total_weight = 0.0;
// calculate total weights
for ( const BancorConverter::reserve reserve : reserves ) {
total_weight += reserve.weight;
}
// modify balance
for ( const BancorConverter::reserve reserve : reserves ) {
double amount = calculate_fund_cost( quantity.amount, supply.amount, reserve.balance.amount, total_weight );
asset reserve_amount = asset( ceil(amount), reserve.balance.symbol );
mod_account_balance(sender, quantity.symbol.code(), -reserve_amount);
mod_reserve_balance(quantity.symbol, reserve_amount);
}
// issue new smart tokens to the issuer
Token::issue_action issue( multi_token, { get_self(), "active"_n });
issue.send(get_self(), quantity, "fund");
Token::transfer_action transfer( multi_token, { get_self(), "active"_n });
transfer.send(get_self(), sender, quantity, "fund");
}
[[eosio::action]]
void BancorConverter::withdraw(name sender, asset quantity, symbol_code converter_currency_code) {
require_auth(sender);
check(quantity.is_valid() && quantity.amount > 0, "invalid quantity");
mod_balances(sender, -quantity, converter_currency_code, get_self());
}
double BancorConverter::calculate_fund_cost(double funding_amount, double supply, double reserve_balance, double total_ratio) {
check(supply > 0, "supply must be greater than zero");
check(reserve_balance > 0, "reserve_balance must be greater than zero");
check(total_ratio > 1 && total_ratio <= MAX_RATIO * 2, "total_ratio not in range");
if (funding_amount == 0)
return 0;
if (total_ratio == MAX_RATIO)
return reserve_balance * funding_amount / supply;
return reserve_balance * (pow(((supply + funding_amount) / supply), (MAX_RATIO / total_ratio)) - 1.0);
}
void BancorConverter::liquidate( const name sender, const asset quantity) {
BancorConverter::settings _settings(get_self(), get_self().value);
const name multi_token = _settings.get().multi_token;
check( get_first_receiver() == multi_token, "bad origin for this transfer");
const symbol_code converter = quantity.symbol.code();
const asset supply = get_supply( multi_token, converter );
std::vector<BancorConverter::reserve> reserves = BancorConverter::get_reserves( converter );
double total_weight = 0.0;
for (const BancorConverter::reserve reserve : reserves ) {
total_weight += reserve.weight;
}
for (const BancorConverter::reserve reserve : reserves ) {
double amount = calculate_liquidate_return(quantity.amount, supply.amount, reserve.balance.amount, total_weight);
check(amount > 0, "cannot liquidate amounts less than or equal to 0");
asset reserve_amount = asset(amount, reserve.balance.symbol);
mod_reserve_balance(quantity.symbol, -reserve_amount);
Token::transfer_action transfer( reserve.contract, { get_self(), "active"_n });
transfer.send(get_self(), sender, reserve_amount, "liquidation");
}
// remove smart tokens from circulation
Token::retire_action retire( multi_token, { get_self(), "active"_n });
retire.send(quantity, "liquidation");
}
double BancorConverter::calculate_liquidate_return( const double liquidation_amount, const double supply, const double reserve_balance, const double total_weight) {
check(supply > 0, "supply must be greater than zero");
check(reserve_balance > 0, "reserve_balance must be greater than zero");
check(liquidation_amount <= supply, "liquidation_amount must be less than or equal to the supply");
check(total_weight > 1 && total_weight <= PPM_RESOLUTION * 2, "total_weight not in range");
if (liquidation_amount == 0)
return 0;
if (liquidation_amount == supply)
return reserve_balance;
if (total_weight == PPM_RESOLUTION)
return liquidation_amount * reserve_balance / supply;
return reserve_balance * (1.0 - pow(((supply - liquidation_amount) / supply), (PPM_RESOLUTION / total_weight)));
} | 43.820513 | 164 | 0.701872 | [
"vector"
] |
fecde7fde4507da69942d7ce6c1b144b5a2aa36e | 498 | cpp | C++ | AtCoder/abc117/c/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | AtCoder/abc117/c/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | 1 | 2021-10-19T08:47:23.000Z | 2022-03-07T05:23:56.000Z | AtCoder/abc117/c/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int n, m; cin >> n >> m;
vector<int> x(m, 0);
for (int i = 0; i < m; i++) cin >> x[i];
vector<int> d;
sort(x.begin(), x.end());
for (int i = 0; i < m - 1; i++) d.push_back(abs(x[i] - x[i + 1]));
sort(d.begin(), d.end()); reverse(d.begin(), d.end());
long long int sum = 0;
for (int i = n - 1; i < d.size(); i++) sum += d[i];
cout << sum << endl;
}
| 27.666667 | 70 | 0.502008 | [
"vector"
] |
fece5766831438ab1427336aa242c3eae4556dbe | 8,317 | cpp | C++ | Official Windows Platform Sample/Windows 8.1 Store app samples/[C++]-Windows 8.1 Store app samples/DirectWrite hello world sample/C++/DWriteHelloWorld.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 2 | 2022-01-21T01:40:58.000Z | 2022-01-21T01:41:10.000Z | Official Windows Platform Sample/Windows 8.1 Store app samples/[C++]-Windows 8.1 Store app samples/DirectWrite hello world sample/C++/DWriteHelloWorld.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 1 | 2022-03-15T04:21:41.000Z | 2022-03-15T04:21:41.000Z | Official Windows Platform Sample/Windows 8.1 Store app samples/[C++]-Windows 8.1 Store app samples/DirectWrite hello world sample/C++/DWriteHelloWorld.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | null | null | null | //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//// PARTICULAR PURPOSE.
////
//// Copyright (c) Microsoft Corporation. All rights reserved
#include "pch.h"
#include "DWriteHelloWorld.h"
using namespace Microsoft::WRL;
using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::UI::Core;
using namespace Windows::UI::Input;
using namespace Windows::System;
using namespace Windows::Foundation;
using namespace Windows::Graphics::Display;
DWriteHelloWorld::DWriteHelloWorld()
{
}
void DWriteHelloWorld::CreateDeviceIndependentResources()
{
DirectXBase::CreateDeviceIndependentResources();
// Create a DirectWrite text format object.
DX::ThrowIfFailed(
m_dwriteFactory->CreateTextFormat(
L"Gabriola",
nullptr,
DWRITE_FONT_WEIGHT_REGULAR,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
64.0f,
L"en-US", // locale
&m_textFormat
)
);
// Center the text horizontally.
DX::ThrowIfFailed(
m_textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER)
);
// Center the text vertically.
DX::ThrowIfFailed(
m_textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER)
);
}
void DWriteHelloWorld::CreateDeviceResources()
{
DirectXBase::CreateDeviceResources();
m_sampleOverlay = ref new SampleOverlay();
m_sampleOverlay->Initialize(
m_d2dDevice.Get(),
m_d2dContext.Get(),
m_wicFactory.Get(),
m_dwriteFactory.Get(),
"DirectWrite Hello World sample"
);
DX::ThrowIfFailed(
m_d2dContext->CreateSolidColorBrush(
D2D1::ColorF(D2D1::ColorF::Black),
&m_blackBrush
)
);
}
void DWriteHelloWorld::CreateWindowSizeDependentResources()
{
DirectXBase::CreateWindowSizeDependentResources();
Platform::String^ text = "Hello World From ... DirectWrite!";
D2D1_SIZE_F size = m_d2dContext->GetSize();
// Create a DirectWrite Text Layout object
DX::ThrowIfFailed(
m_dwriteFactory->CreateTextLayout(
text->Data(), // Text to be displayed
text->Length(), // Length of the text
m_textFormat.Get(), // DirectWrite Text Format object
size.width, // Width of the Text Layout
size.height, // Height of the Text Layout
&m_textLayout
)
);
// Text range for the "DirectWrite!" at the end of the string
DWRITE_TEXT_RANGE textRange = {21, 12}; // 21 references the "D" in DirectWrite! and 12 is the number of characters in the word
// Set the font size on that text range to 100
DX::ThrowIfFailed(
m_textLayout->SetFontSize(100.0f, textRange)
);
// Create a DirectWrite Typography object
DX::ThrowIfFailed(
m_dwriteFactory->CreateTypography(
&m_textTypography
)
);
// Enumerate a stylistic set 6 font feature for application to our text layout
DWRITE_FONT_FEATURE fontFeature = {DWRITE_FONT_FEATURE_TAG_STYLISTIC_SET_6, 1};
// Apply the previously enumerated font feature to our Text Typography object
DX::ThrowIfFailed(
m_textTypography->AddFontFeature(fontFeature)
);
// Move our text range to the entire length of the string
textRange.length = text->Length();
textRange.startPosition = 0;
// Apply our recently defined typography to our entire text range
DX::ThrowIfFailed(
m_textLayout->SetTypography(
m_textTypography.Get(),
textRange
)
);
// Move the text range to the end again
textRange.length = 12;
textRange.startPosition = 21;
// Set the underline on the text range
DX::ThrowIfFailed(
m_textLayout->SetUnderline(TRUE, textRange)
);
// Set the font weight on the text range
DX::ThrowIfFailed(
m_textLayout->SetFontWeight(DWRITE_FONT_WEIGHT_BOLD, textRange)
);
}
void DWriteHelloWorld::Render()
{
m_d2dContext->BeginDraw();
m_d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::CornflowerBlue));
m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity());
m_d2dContext->DrawTextLayout(
D2D1::Point2F(0.0f, 0.0f),
m_textLayout.Get(),
m_blackBrush.Get()
);
// We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
// is lost. It will be handled during the next call to Present.
HRESULT hr = m_d2dContext->EndDraw();
if (hr != D2DERR_RECREATE_TARGET)
{
DX::ThrowIfFailed(hr);
}
m_sampleOverlay->Render();
}
void DWriteHelloWorld::Initialize(
_In_ CoreApplicationView^ applicationView
)
{
applicationView->Activated +=
ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DWriteHelloWorld::OnActivated);
CoreApplication::Suspending +=
ref new EventHandler<SuspendingEventArgs^>(this, &DWriteHelloWorld::OnSuspending);
CoreApplication::Resuming +=
ref new EventHandler<Platform::Object^>(this, &DWriteHelloWorld::OnResuming);
}
void DWriteHelloWorld::SetWindow(
_In_ CoreWindow^ window
)
{
window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
window->SizeChanged +=
ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DWriteHelloWorld::OnWindowSizeChanged);
DisplayInformation::GetForCurrentView()->DpiChanged +=
ref new TypedEventHandler<DisplayInformation^, Platform::Object^>(this, &DWriteHelloWorld::OnDpiChanged);
DisplayInformation::DisplayContentsInvalidated +=
ref new TypedEventHandler<DisplayInformation^, Platform::Object^>(this, &DWriteHelloWorld::OnDisplayContentsInvalidated);
// Disable all pointer visual feedback for better performance when touching.
auto pointerVisualizationSettings = PointerVisualizationSettings::GetForCurrentView();
pointerVisualizationSettings->IsContactFeedbackEnabled = false;
pointerVisualizationSettings->IsBarrelButtonFeedbackEnabled = false;
DirectXBase::Initialize(window, DisplayInformation::GetForCurrentView()->LogicalDpi);
}
void DWriteHelloWorld::Load(
_In_ Platform::String^ entryPoint
)
{
}
void DWriteHelloWorld::Run()
{
Render();
Present();
m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit);
}
void DWriteHelloWorld::Uninitialize()
{
}
void DWriteHelloWorld::OnWindowSizeChanged(
_In_ CoreWindow^ sender,
_In_ WindowSizeChangedEventArgs^ args
)
{
UpdateForWindowSizeChange();
m_sampleOverlay->UpdateForWindowSizeChange();
Render();
Present();
}
void DWriteHelloWorld::OnDpiChanged(_In_ DisplayInformation^ sender, _In_ Platform::Object^ args)
{
SetDpi(sender->LogicalDpi);
Render();
Present();
}
void DWriteHelloWorld::OnDisplayContentsInvalidated(_In_ DisplayInformation^ sender, _In_ Platform::Object^ args)
{
// Ensure the D3D Device is available for rendering.
ValidateDevice();
Render();
Present();
}
void DWriteHelloWorld::OnActivated(
_In_ CoreApplicationView^ applicationView,
_In_ IActivatedEventArgs^ args
)
{
m_window->Activate();
}
void DWriteHelloWorld::OnSuspending(
_In_ Platform::Object^ sender,
_In_ SuspendingEventArgs^ args
)
{
// Hint to the driver that the app is entering an idle state and that its memory
// can be temporarily used for other apps.
Trim();
}
void DWriteHelloWorld::OnResuming(
_In_ Platform::Object^ sender,
_In_ Platform::Object^ args
)
{
}
IFrameworkView^ DirectXAppSource::CreateView()
{
return ref new DWriteHelloWorld();
}
[Platform::MTAThread]
int main(Platform::Array<Platform::String^>^)
{
auto directXAppSource = ref new DirectXAppSource();
CoreApplication::Run(directXAppSource);
return 0;
}
| 28.778547 | 131 | 0.683179 | [
"render",
"object"
] |
fed0f26d197cc1d9e6adbc00a60165e421acb971 | 8,026 | cpp | C++ | tests/regression/test_flatten_barrier_subs.cpp | jansol/pocl | 07c1519715ec1675a480022f25d8bf907470530b | [
"MIT"
] | null | null | null | tests/regression/test_flatten_barrier_subs.cpp | jansol/pocl | 07c1519715ec1675a480022f25d8bf907470530b | [
"MIT"
] | null | null | null | tests/regression/test_flatten_barrier_subs.cpp | jansol/pocl | 07c1519715ec1675a480022f25d8bf907470530b | [
"MIT"
] | null | null | null | /* Tests a kernel create with binary.
Copyright (c) 2018 Julius Ikkala / TUT
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 "pocl_opencl.h"
#define CL_HPP_TARGET_OPENCL_VERSION 120
#define CL_HPP_MINIMUM_OPENCL_VERSION 120
#include <CL/cl2.hpp>
#include <iostream>
#include <numeric>
#ifdef _WIN32
# include "vccompat.hpp"
#endif
std::string read_text_file(const std::string& path)
{
FILE* f = fopen(path.c_str(), "rb");
if(!f)
{
throw std::runtime_error("Unable to open " + path);
}
fseek(f, 0, SEEK_END);
size_t sz = ftell(f);
fseek(f, 0, SEEK_SET);
char* data = new char[sz];
if(fread(data, 1, sz, f) != sz)
{
delete [] data;
throw std::runtime_error("Unable to read " + path);
}
fclose(f);
std::string ret(data, sz);
delete [] data;
return ret;
}
cl::Platform get_platform(unsigned force_platform = 0)
{
std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
if(platforms.empty())
throw std::runtime_error("No platforms found!");
for(unsigned i = 0; i < platforms.size(); ++i)
{
cl::Platform& p = platforms[i];
std::string name = p.getInfo<CL_PLATFORM_NAME>();
std::cout << i << ": " << name << std::endl;
}
if(force_platform >= platforms.size()) force_platform = 0;
return platforms[force_platform];
}
cl::Device get_device(cl::Platform pl, unsigned force_device = 0)
{
std::vector<cl::Device> devices;
pl.getDevices(CL_DEVICE_TYPE_ALL, &devices);
if(devices.empty())
throw std::runtime_error("No devices found!");
return devices[0];
}
void exclusive_scan_cpu(const std::vector<int>& input, std::vector<int>& output)
{
output.resize(input.size());
int a = 0;
for(unsigned i = 0; i < input.size(); ++i)
{
output[i] = a;
a += input[i];
}
}
void exclusive_scan_cl(const std::vector<int>& input, std::vector<int>& output)
{
// Fails on POCL, works with AMDGPU-PRO
cl::Platform p = get_platform(0);
cl::Device d = get_device(p);
cl::Context ctx(d);
std::string src = read_text_file(SRCDIR "/test_flatten_barrier_subs.cl");
cl::Program::Sources sources;
sources.push_back({src.c_str(), src.length()});
cl::Program program(ctx, sources);
if(program.build({d}) != CL_SUCCESS)
{
throw std::runtime_error(program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(d));
}
cl::Buffer input_buf(ctx, CL_MEM_READ_WRITE, sizeof(int)*input.size());
cl::Buffer output_buf(ctx, CL_MEM_READ_WRITE, sizeof(int)*input.size());
cl::CommandQueue q(ctx, d);
q.enqueueWriteBuffer(
input_buf, CL_TRUE, 0, sizeof(int)*input.size(), input.data()
);
int numElems = input.size();
#define WG_SIZE 64
int GROUP_BLOCK_SIZE_SCAN = (WG_SIZE << 3);
int GROUP_BLOCK_SIZE_DISTRIBUTE = (WG_SIZE << 2);
int NUM_GROUPS_BOTTOM_LEVEL_SCAN = (numElems + GROUP_BLOCK_SIZE_SCAN - 1) / GROUP_BLOCK_SIZE_SCAN;
int NUM_GROUPS_MID_LEVEL_SCAN = (NUM_GROUPS_BOTTOM_LEVEL_SCAN + GROUP_BLOCK_SIZE_SCAN - 1) / GROUP_BLOCK_SIZE_SCAN;
int NUM_GROUPS_TOP_LEVEL_SCAN = (NUM_GROUPS_MID_LEVEL_SCAN + GROUP_BLOCK_SIZE_SCAN - 1) / GROUP_BLOCK_SIZE_SCAN;
int NUM_GROUPS_BOTTOM_LEVEL_DISTRIBUTE = (numElems + GROUP_BLOCK_SIZE_DISTRIBUTE - 1) / GROUP_BLOCK_SIZE_DISTRIBUTE;
int NUM_GROUPS_MID_LEVEL_DISTRIBUTE = (NUM_GROUPS_BOTTOM_LEVEL_DISTRIBUTE + GROUP_BLOCK_SIZE_DISTRIBUTE - 1) / GROUP_BLOCK_SIZE_DISTRIBUTE;
cl::Buffer devicePartSumsBottomLevel(
ctx, CL_MEM_READ_WRITE, sizeof(int)*NUM_GROUPS_BOTTOM_LEVEL_SCAN
);
cl::Buffer devicePartSumsMidLevel(
ctx, CL_MEM_READ_WRITE, sizeof(int)*NUM_GROUPS_MID_LEVEL_SCAN
);
cl::Kernel bottomLevelScan(program, "scan_exclusive_part_int4");
cl::Kernel topLevelScan(program, "scan_exclusive_int4");
cl::Kernel distributeSums(program, "distribute_part_sum_int4");
bottomLevelScan.setArg(0, input_buf);
bottomLevelScan.setArg(1, output_buf);
bottomLevelScan.setArg(2, numElems);
bottomLevelScan.setArg(3, devicePartSumsBottomLevel);
bottomLevelScan.setArg(4, WG_SIZE * sizeof(cl_int), nullptr);
q.enqueueNDRangeKernel(
bottomLevelScan,
cl::NullRange,
cl::NDRange(NUM_GROUPS_BOTTOM_LEVEL_SCAN * WG_SIZE),
cl::NDRange(WG_SIZE)
);
bottomLevelScan.setArg(0, devicePartSumsBottomLevel);
bottomLevelScan.setArg(1, devicePartSumsBottomLevel);
bottomLevelScan.setArg(2, (cl_uint)NUM_GROUPS_BOTTOM_LEVEL_SCAN);
bottomLevelScan.setArg(3, devicePartSumsMidLevel);
bottomLevelScan.setArg(4, WG_SIZE * sizeof(cl_int), nullptr);
q.enqueueNDRangeKernel(
bottomLevelScan,
cl::NullRange,
cl::NDRange(NUM_GROUPS_MID_LEVEL_SCAN * WG_SIZE),
cl::NDRange(WG_SIZE)
);
topLevelScan.setArg(0, devicePartSumsMidLevel);
topLevelScan.setArg(1, devicePartSumsMidLevel);
topLevelScan.setArg(2, (cl_uint)NUM_GROUPS_MID_LEVEL_SCAN);
topLevelScan.setArg(3, WG_SIZE * sizeof(cl_int), nullptr);
q.enqueueNDRangeKernel(
topLevelScan,
cl::NullRange,
cl::NDRange(NUM_GROUPS_TOP_LEVEL_SCAN * WG_SIZE),
cl::NDRange(WG_SIZE)
);
distributeSums.setArg(0, devicePartSumsMidLevel);
distributeSums.setArg(1, devicePartSumsBottomLevel);
distributeSums.setArg(2, (cl_uint)NUM_GROUPS_BOTTOM_LEVEL_SCAN);
q.enqueueNDRangeKernel(
distributeSums,
cl::NullRange,
cl::NDRange(NUM_GROUPS_MID_LEVEL_DISTRIBUTE * WG_SIZE),
cl::NDRange(WG_SIZE)
);
distributeSums.setArg(0, devicePartSumsBottomLevel);
distributeSums.setArg(1, output_buf);
distributeSums.setArg(2, (cl_uint)numElems);
q.enqueueNDRangeKernel(
distributeSums,
cl::NullRange,
cl::NDRange(NUM_GROUPS_BOTTOM_LEVEL_DISTRIBUTE * WG_SIZE),
cl::NDRange(WG_SIZE)
);
output.resize(input.size());
q.enqueueReadBuffer(
output_buf, CL_TRUE, 0, sizeof(int)*input.size(), output.data()
);
}
std::vector<int> generate_hits(unsigned n)
{
std::vector<int> res;
res.reserve(n);
for(unsigned i = 0; i < n; ++i) res.push_back(random()&1);
return res;
}
template<typename T>
void print_vec(const std::vector<T>& t)
{
for(unsigned i = 0; i < t.size(); ++i)
{
if(i != 0) std::cout << ", ";
std::cout << t[i];
}
std::cout << std::endl;
}
int main()
{
std::vector<int> hits = generate_hits(100);
std::vector<int> indices;
exclusive_scan_cpu(hits, indices);
print_vec(hits);
print_vec(indices);
std::vector<int> cl_indices;
exclusive_scan_cl(hits, cl_indices);
if(indices == cl_indices)
std::cout << "CL gave correct results" << std::endl;
else
{
std::cout << "CL gave wrong results" << std::endl;
print_vec(cl_indices);
return EXIT_FAILURE;
}
std::cout << "OK" << std::endl;
return EXIT_SUCCESS;
}
| 31.976096 | 143 | 0.68166 | [
"vector"
] |
fed3a62591e84e0ac31099a59f0cb380f3c1144f | 2,658 | cpp | C++ | system/lib/wasmfs/backends/memory_backend.cpp | KDr2/emscripten | 79e872c7938774b8eb72bf3c072b5442a3586abc | [
"MIT"
] | 9,724 | 2015-01-01T02:06:30.000Z | 2019-01-17T15:13:51.000Z | system/lib/wasmfs/backends/memory_backend.cpp | KDr2/emscripten | 79e872c7938774b8eb72bf3c072b5442a3586abc | [
"MIT"
] | 4,273 | 2015-01-01T04:10:11.000Z | 2019-01-17T19:37:37.000Z | system/lib/wasmfs/backends/memory_backend.cpp | AIEdX/emscripten | 5bcd268db583d0ac7de4aedcd29e439d69553176 | [
"MIT"
] | 1,519 | 2015-01-01T18:11:12.000Z | 2019-01-17T14:16:02.000Z | // Copyright 2021 The Emscripten Authors. All rights reserved.
// Emscripten is available under two separate licenses, the MIT license and the
// University of Illinois/NCSA Open Source License. Both these licenses can be
// found in the LICENSE file.
// This file defines the memory file backend of the new file system.
// Current Status: Work in Progress.
// See https://github.com/emscripten-core/emscripten/issues/15041.
#include "backend.h"
#include "memory_backend.h"
#include "wasmfs.h"
namespace wasmfs {
ssize_t MemoryFile::write(const uint8_t* buf, size_t len, off_t offset) {
if (offset + len > buffer.size()) {
buffer.resize(offset + len);
}
std::memcpy(&buffer[offset], buf, len);
return len;
}
ssize_t MemoryFile::read(uint8_t* buf, size_t len, off_t offset) {
if (offset >= buffer.size()) {
len = 0;
} else if (offset + len >= buffer.size()) {
len = buffer.size() - offset;
}
std::memcpy(buf, &buffer[offset], len);
return len;
}
std::vector<MemoryDirectory::ChildEntry>::iterator
MemoryDirectory::findEntry(const std::string& name) {
return std::find_if(entries.begin(), entries.end(), [&](const auto& entry) {
return entry.name == name;
});
}
bool MemoryDirectory::removeChild(const std::string& name) {
auto entry = findEntry(name);
if (entry != entries.end()) {
entries.erase(entry);
}
return true;
}
std::vector<Directory::Entry> MemoryDirectory::getEntries() {
std::vector<Directory::Entry> result;
result.reserve(entries.size());
for (auto& [name, child] : entries) {
result.push_back({name, child->kind, child->getIno()});
}
return result;
}
bool MemoryDirectory::insertMove(const std::string& name,
std::shared_ptr<File> file) {
auto& oldEntries =
std::static_pointer_cast<MemoryDirectory>(file->locked().getParent())
->entries;
for (auto it = oldEntries.begin(); it != oldEntries.end(); ++it) {
if (it->child == file) {
oldEntries.erase(it);
break;
}
}
removeChild(name);
insertChild(name, file);
return true;
}
class MemoryFileBackend : public Backend {
public:
std::shared_ptr<DataFile> createFile(mode_t mode) override {
return std::make_shared<MemoryFile>(mode, this);
}
std::shared_ptr<Directory> createDirectory(mode_t mode) override {
return std::make_shared<MemoryDirectory>(mode, this);
}
std::shared_ptr<Symlink> createSymlink(std::string target) override {
return std::make_shared<MemorySymlink>(target, this);
}
};
backend_t createMemoryFileBackend() {
return wasmFS.addBackend(std::make_unique<MemoryFileBackend>());
}
} // namespace wasmfs
| 28.891304 | 79 | 0.683973 | [
"vector"
] |
fee2d1d99137c1c009bec25fcaeafcf471eb293f | 715 | cpp | C++ | src/particle-system/core/newtonlaw.cpp | semitro/Particle-system | f29e4f6d45132f98b3089f39e0d6c76a1bd63e86 | [
"MIT"
] | null | null | null | src/particle-system/core/newtonlaw.cpp | semitro/Particle-system | f29e4f6d45132f98b3089f39e0d6c76a1bd63e86 | [
"MIT"
] | null | null | null | src/particle-system/core/newtonlaw.cpp | semitro/Particle-system | f29e4f6d45132f98b3089f39e0d6c76a1bd63e86 | [
"MIT"
] | null | null | null | #include "particle-system/core/newtonlaw.hpp"
void newtonLaw(vector<Particle> &particles, float dT)
{
for(size_t i = 0; i < particles.size(); i++)
// for(size_t j = 0; i < particles.size(); i++){
// float dx = particles[j].x - particles[i].x;
// float dy = particles[j].y - particles[i].y;
// float distance = sqrtf(dx*dx + dy*dy);
// if(distance < 0.00000000001f)
// continue;
// float force = G/(distance*distance);
// particles[i].vx += force*dx;
// particles[i].vy += force*dy;
// particles[j].vx -= force*dx;
// particles[j].vy -= force*dy;
// }
for(size_t i = 0; i < particles.size(); i++){
particles[i].x += particles[i].vx * dT;
particles[i].y += particles[i].vy * dT;
}
}
| 27.5 | 53 | 0.595804 | [
"vector"
] |
fee3eff695b2125e72b3fb51e982a00c18fad82c | 2,299 | hpp | C++ | modules/clients/cpp/main/include/gridgain/impl/hash/gridclientboolhasheableobject.hpp | cybernetics/gridgain | 39f3819c9769b04caca62b263581c0458f21c4d6 | [
"Apache-2.0"
] | 1 | 2019-04-22T08:48:55.000Z | 2019-04-22T08:48:55.000Z | modules/clients/cpp/main/include/gridgain/impl/hash/gridclientboolhasheableobject.hpp | cybernetics/gridgain | 39f3819c9769b04caca62b263581c0458f21c4d6 | [
"Apache-2.0"
] | null | null | null | modules/clients/cpp/main/include/gridgain/impl/hash/gridclientboolhasheableobject.hpp | cybernetics/gridgain | 39f3819c9769b04caca62b263581c0458f21c4d6 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (C) GridGain Systems. 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.
*/
/* _________ _____ __________________ _____
* __ ____/___________(_)______ /__ ____/______ ____(_)_______
* _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \
* / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /
* \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/
*/
#ifndef GRID_CLIENT_BOOL_HASHEABLE_OBJECT_HPP_INCLUDED
#define GRID_CLIENT_BOOL_HASHEABLE_OBJECT_HPP_INCLUDED
#include "gridgain/gridhasheableobject.hpp"
#include "gridgain/impl/utils/gridclientbyteutils.hpp"
/**
* Hashable object wrapping boolean value.
*/
class GridBoolHasheableObject : public GridClientHasheableObject {
public:
/**
* Public constructor.
*
* @param pVal Value to hold.
*/
GridBoolHasheableObject(bool pVal);
/**
* Return hash code for the contained value.
*
* @return Java-like boolean hash code.
*/
virtual int32_t hashCode() const { return hashCode_; }
/**
* Converts contained object to byte vector.
*
* @param bytes Vector to fill.
*/
virtual void convertToBytes(std::vector<int8_t>& opBytes) const { opBytes = bytes; }
protected:
/** Stored hash code. */
int32_t hashCode_;
/** Byte representation of the object. */
std::vector<int8_t> bytes;
};
/**
* Public constructor.
*
* @param pVal Value to hold.
*/
inline GridBoolHasheableObject::GridBoolHasheableObject(bool pVal) {
hashCode_ = pVal ? 1231 : 1237;
bytes.resize(sizeof(hashCode_));
memset(&bytes[0], 0, sizeof(hashCode_));
GridClientByteUtils::valueToBytes(hashCode_, &bytes[0], sizeof(hashCode_), GridClientByteUtils::LITTLE_ENDIAN_ORDER);
}
#endif
| 29.101266 | 121 | 0.669421 | [
"object",
"vector"
] |
fee80380fb9891f36060a49ae506764b03be398b | 18,165 | cpp | C++ | components/scream/src/physics/rrtmgp/tests/rrtmgp_unit_tests.cpp | ambrad/scream | 52da60f65e870b8a3994bdbf4a6022fdcac7cab5 | [
"BSD-3-Clause"
] | null | null | null | components/scream/src/physics/rrtmgp/tests/rrtmgp_unit_tests.cpp | ambrad/scream | 52da60f65e870b8a3994bdbf4a6022fdcac7cab5 | [
"BSD-3-Clause"
] | null | null | null | components/scream/src/physics/rrtmgp/tests/rrtmgp_unit_tests.cpp | ambrad/scream | 52da60f65e870b8a3994bdbf4a6022fdcac7cab5 | [
"BSD-3-Clause"
] | null | null | null | #include "catch2/catch.hpp"
#include "physics/rrtmgp/rrtmgp_utils.hpp"
#include "physics/rrtmgp/scream_rrtmgp_interface.hpp"
#include "YAKL.h"
#include "physics/share/physics_constants.hpp"
#include "physics/rrtmgp/share/shr_orb_mod_c2f.hpp"
TEST_CASE("rrtmgp_test_heating") {
// Initialize YAKL
if (!yakl::isInitialized()) { yakl::init(); }
// Test heating rate function by passing simple inputs
auto dp = real2d("dp", 1, 1);
auto flux_up = real2d("flux_up", 1, 2);
auto flux_dn = real2d("flux_dn", 1, 2);
auto heating = real2d("heating", 1, 1);
// Simple no-heating test
// NOTE: parallel_for because we need to do these in a kernel on the device
parallel_for(1, YAKL_LAMBDA(int /* dummy */) {
dp(1, 1) = 10;
flux_up(1, 1) = 1.0;
flux_up(1, 2) = 1.0;
flux_dn(1, 1) = 1.0;
flux_dn(1, 2) = 1.0;
});
scream::rrtmgp::compute_heating_rate(flux_up, flux_dn, dp, heating);
REQUIRE(heating.createHostCopy()(1,1) == 0);
// Simple net postive heating; net flux into layer should be 1.0
// NOTE: parallel_for because we need to do these in a kernel on the device
parallel_for(1, YAKL_LAMBDA(int /* dummy */) {
flux_up(1, 1) = 1.0;
flux_up(1, 2) = 1.0;
flux_dn(1, 1) = 1.5;
flux_dn(1, 2) = 0.5;
});
using physconst = scream::physics::Constants<double>;
auto g = physconst::gravit; //9.81;
auto cp_air = physconst::Cpair; //1005.0;
auto pdel = dp.createHostCopy()(1,1);
auto heating_ref = 1.0 * g / (cp_air * pdel);
scream::rrtmgp::compute_heating_rate(flux_up, flux_dn, dp, heating);
REQUIRE(heating.createHostCopy()(1,1) == heating_ref);
// Simple net negative heating; net flux into layer should be -1.0
// NOTE: parallel_for because we need to do these in a kernel on the device
parallel_for(1, YAKL_LAMBDA(int /* dummy */) {
flux_up(1,1) = 1.5;
flux_up(1,2) = 0.5;
flux_dn(1,1) = 1.0;
flux_dn(1,2) = 1.0;
});
heating_ref = -1.0 * g / (cp_air * pdel);
scream::rrtmgp::compute_heating_rate(flux_up, flux_dn, dp, heating);
REQUIRE(heating.createHostCopy()(1,1) == heating_ref);
// Clean up
dp.deallocate();
flux_up.deallocate();
flux_dn.deallocate();
heating.deallocate();
yakl::finalize();
}
TEST_CASE("rrtmgp_test_mixing_ratio_to_cloud_mass") {
// Initialize YAKL
if (!yakl::isInitialized()) { yakl::init(); }
using physconst = scream::physics::Constants<double>;
// Test mixing ratio to cloud mass function by passing simple inputs
auto dp = real2d("dp", 1, 1);
auto mixing_ratio = real2d("mixing_ratio", 1, 1);
auto cloud_fraction = real2d("cloud_fration", 1, 1);
auto cloud_mass = real2d("cloud_mass", 1, 1);
// Test with cell completely filled with cloud
parallel_for(1, YAKL_LAMBDA(int /* dummy */) {
dp(1,1) = 10.0;
mixing_ratio(1,1) = 0.0001;
cloud_fraction(1,1) = 1.0;
});
auto cloud_mass_ref = mixing_ratio.createHostCopy()(1,1) / cloud_fraction.createHostCopy()(1,1) * dp.createHostCopy()(1,1) / physconst::gravit;
scream::rrtmgp::mixing_ratio_to_cloud_mass(mixing_ratio, cloud_fraction, dp, cloud_mass);
REQUIRE(cloud_mass.createHostCopy()(1,1) == cloud_mass_ref);
// Test with no cloud
parallel_for(1, YAKL_LAMBDA(int /* dummy */) {
dp(1,1) = 10.0;
mixing_ratio(1,1) = 0.0;
cloud_fraction(1,1) = 0.0;
});
cloud_mass_ref = 0.0;
scream::rrtmgp::mixing_ratio_to_cloud_mass(mixing_ratio, cloud_fraction, dp, cloud_mass);
REQUIRE(cloud_mass.createHostCopy()(1,1) == cloud_mass_ref);
// Test with empty clouds (cloud fraction but with no associated mixing ratio)
// This case could happen if we use a total cloud fraction, but compute layer
// cloud mass separately for liquid and ice.
parallel_for(1, YAKL_LAMBDA(int /* dummy */) {
dp(1,1) = 10.0;
mixing_ratio(1,1) = 0.0;
cloud_fraction(1,1) = 0.1;
});
cloud_mass_ref = 0.0;
scream::rrtmgp::mixing_ratio_to_cloud_mass(mixing_ratio, cloud_fraction, dp, cloud_mass);
REQUIRE(cloud_mass.createHostCopy()(1,1) == cloud_mass_ref);
// Test with cell half filled with cloud
parallel_for(1, YAKL_LAMBDA(int /* dummy */) {
dp(1,1) = 10.0;
mixing_ratio(1,1) = 0.0001;
cloud_fraction(1,1) = 0.5;
});
cloud_mass_ref = mixing_ratio.createHostCopy()(1,1) / cloud_fraction.createHostCopy()(1,1) * dp.createHostCopy()(1,1) / physconst::gravit;
scream::rrtmgp::mixing_ratio_to_cloud_mass(mixing_ratio, cloud_fraction, dp, cloud_mass);
REQUIRE(cloud_mass.createHostCopy()(1,1) == cloud_mass_ref);
// Clean up
dp.deallocate();
mixing_ratio.deallocate();
cloud_fraction.deallocate();
cloud_mass.deallocate();
yakl::finalize();
}
TEST_CASE("rrtmgp_test_limit_to_bounds") {
// Initialize YAKL
if (!yakl::isInitialized()) { yakl::init(); }
// Test limiter function
auto arr = real2d("arr", 2, 2);
auto arr_limited = real2d("arr_limited", 2, 2);
// Setup dummy array
parallel_for(1, YAKL_LAMBDA(int /* dummy */) {
arr(1,1) = 1.0;
arr(1,2) = 2.0;
arr(2,1) = 3.0;
arr(2,2) = 4.0;
});
// Limit to bounds that contain the data; should be no change in values
scream::rrtmgp::limit_to_bounds(arr, 0.0, 5.0, arr_limited);
REQUIRE(arr.createHostCopy()(1,1) == arr_limited.createHostCopy()(1,1));
REQUIRE(arr.createHostCopy()(1,2) == arr_limited.createHostCopy()(1,2));
REQUIRE(arr.createHostCopy()(2,1) == arr_limited.createHostCopy()(2,1));
REQUIRE(arr.createHostCopy()(2,2) == arr_limited.createHostCopy()(2,2));
// Limit to bounds that do not completely contain the data; should be a change in values!
scream::rrtmgp::limit_to_bounds(arr, 1.5, 3.5, arr_limited);
REQUIRE(arr_limited.createHostCopy()(1,1) == 1.5);
REQUIRE(arr_limited.createHostCopy()(1,2) == 2.0);
REQUIRE(arr_limited.createHostCopy()(2,1) == 3.0);
REQUIRE(arr_limited.createHostCopy()(2,2) == 3.5);
arr.deallocate();
arr_limited.deallocate();
yakl::finalize();
}
TEST_CASE("rrtmgp_test_zenith") {
// Create some dummy data
int orbital_year = 1990;
double calday = 1.0000000000000000;
double eccen_ref = 1.6707719799280658E-002;
double mvelpp_ref = 4.9344679089867318;
double lambm0_ref = -3.2503635878519378E-002;
double obliqr_ref = 0.40912382465788016;
double delta_ref = -0.40302893695478670;
double eccf_ref = 1.0342222039093694;
double lat = -7.7397590528644963E-002;
double lon = 2.2584340271163548;
double coszrs_ref = 0.61243613606766745;
// Test shr_orb_params()
// Get orbital parameters based on calendar day
double eccen;
double obliq; // obliquity in degrees
double mvelp; // moving vernal equinox long of perihelion; degrees?
double obliqr;
double lambm0;
double mvelpp;
// bool flag_print = false;
shr_orb_params_c2f(&orbital_year, &eccen, &obliq, &mvelp,
&obliqr, &lambm0, &mvelpp); //, flag_print); // Note fortran code has optional arg
REQUIRE(eccen == eccen_ref);
REQUIRE(obliqr == obliqr_ref);
REQUIRE(mvelpp == mvelpp_ref);
REQUIRE(lambm0 == lambm0_ref);
REQUIRE(mvelpp == mvelpp_ref);
// Test shr_orb_decl()
double delta;
double eccf;
shr_orb_decl_c2f(calday, eccen, mvelpp, lambm0,
obliqr, &delta, &eccf);
REQUIRE(delta == delta_ref);
REQUIRE(eccf == eccf_ref );
double dt_avg = 0.; //3600.0000000000000;
double coszrs = shr_orb_cosz_c2f(calday, lat, lon, delta, dt_avg);
REQUIRE(std::abs(coszrs-coszrs_ref)<1e-14);
// Another case, this time WITH dt_avg flag:
calday = 1.0833333333333333;
eccen = 1.6707719799280658E-002;
mvelpp = 4.9344679089867318;
lambm0 = -3.2503635878519378E-002;
obliqr = 0.40912382465788016;
delta = -0.40292121709083456;
eccf = 1.0342248931660425;
lat = -1.0724153591027763;
lon = 4.5284876076962712;
dt_avg = 3600.0000000000000;
coszrs_ref = 0.14559973262047626;
coszrs = shr_orb_cosz_c2f(calday, lat, lon, delta, dt_avg);
REQUIRE(std::abs(coszrs-coszrs_ref)<1e-14);
}
TEST_CASE("rrtmgp_test_compute_broadband_surface_flux") {
using namespace ekat::logger;
using logger_t = Logger<LogNoFile,LogRootRank>;
ekat::Comm comm(MPI_COMM_WORLD);
auto logger = std::make_shared<logger_t>("",LogLevel::info,comm);
// Initialize YAKL
if (!yakl::isInitialized()) { yakl::init(); }
// Create arrays
const int ncol = 1;
const int nlay = 1;
const int nbnd = 14;
const int kbot = nlay + 1;
auto sfc_flux_dir_nir = real1d("sfc_flux_dir_nir", ncol);
auto sfc_flux_dir_vis = real1d("sfc_flux_dir_vis", ncol);
auto sfc_flux_dif_nir = real1d("sfc_flux_dif_nir", ncol);
auto sfc_flux_dif_vis = real1d("sfc_flux_dif_vis", ncol);
// Need to initialize RRTMGP with dummy gases
logger->info("Init gases...\n");
GasConcs gas_concs;
int ngas = 8;
string1d gas_names("gas_names",ngas);
gas_names(1) = std::string("h2o");
gas_names(2) = std::string("co2");
gas_names(3) = std::string("o3" );
gas_names(4) = std::string("n2o");
gas_names(5) = std::string("co" );
gas_names(6) = std::string("ch4");
gas_names(7) = std::string("o2" );
gas_names(8) = std::string("n2" );
gas_concs.init(gas_names,ncol,nlay);
logger->info("Init RRTMGP...\n");
scream::rrtmgp::rrtmgp_initialize(gas_concs,logger);
// Create simple test cases; We expect, given the input data, that band 10
// will straddle the NIR and VIS, bands 1-9 will be purely NIR, and bands 11-14
// will be purely VIS. The implementation in EAMF90 was hard-coded with this
// band information, but our implementation of compute_broadband_surface_fluxes
// actually checks the wavenumber limits. These tests will mostly check to make
// sure our implementation of that is doing what we think it is.
// ---------------------------------
// Test case: flux only in straddled band
auto sw_bnd_flux_dir = real3d("sw_bnd_flux_dir", ncol, nlay+1, nbnd);
auto sw_bnd_flux_dif = real3d("sw_bnd_flux_dif", ncol, nlay+1, nbnd);
logger->info("Populate band-resolved 3d fluxes for test case with only transition band flux...\n");
parallel_for(Bounds<3>(nbnd,nlay+1,ncol), YAKL_LAMBDA(int ibnd, int ilay, int icol) {
if (ibnd < 10) {
sw_bnd_flux_dir(icol,ilay,ibnd) = 0;
sw_bnd_flux_dif(icol,ilay,ibnd) = 0;
} else if (ibnd == 10) {
sw_bnd_flux_dir(icol,ilay,ibnd) = 1;
sw_bnd_flux_dif(icol,ilay,ibnd) = 1;
} else {
sw_bnd_flux_dir(icol,ilay,ibnd) = 0;
sw_bnd_flux_dif(icol,ilay,ibnd) = 0;
}
});
// Compute surface fluxes
logger->info("Compute broadband surface fluxes...\n");
scream::rrtmgp::compute_broadband_surface_fluxes(
ncol, kbot, nbnd,
sw_bnd_flux_dir, sw_bnd_flux_dif,
sfc_flux_dir_vis, sfc_flux_dir_nir,
sfc_flux_dif_vis, sfc_flux_dif_nir
);
// Check computed surface fluxes
logger->info("Check computed fluxes...\n");
const double tol = 1e-10; // tolerance on floating point inequality for assertions
REQUIRE(std::abs(sfc_flux_dir_nir.createHostCopy()(1) - 0.5) < tol);
REQUIRE(std::abs(sfc_flux_dir_vis.createHostCopy()(1) - 0.5) < tol);
REQUIRE(std::abs(sfc_flux_dif_nir.createHostCopy()(1) - 0.5) < tol);
REQUIRE(std::abs(sfc_flux_dif_vis.createHostCopy()(1) - 0.5) < tol);
// ---------------------------------
// ---------------------------------
// Test case, only flux in NIR bands
logger->info("Populate band-resolved 3d fluxes for test case with only NIR flux...\n");
parallel_for(Bounds<3>(nbnd,nlay+1,ncol), YAKL_LAMBDA(int ibnd, int ilay, int icol) {
if (ibnd < 10) {
sw_bnd_flux_dir(icol,ilay,ibnd) = 1;
sw_bnd_flux_dif(icol,ilay,ibnd) = 1;
} else if (ibnd == 10) {
sw_bnd_flux_dir(icol,ilay,ibnd) = 0;
sw_bnd_flux_dif(icol,ilay,ibnd) = 0;
} else {
sw_bnd_flux_dir(icol,ilay,ibnd) = 0;
sw_bnd_flux_dif(icol,ilay,ibnd) = 0;
}
});
// Compute surface fluxes
logger->info("Compute broadband surface fluxes...\n");
scream::rrtmgp::compute_broadband_surface_fluxes(
ncol, kbot, nbnd,
sw_bnd_flux_dir, sw_bnd_flux_dif,
sfc_flux_dir_vis, sfc_flux_dir_nir,
sfc_flux_dif_vis, sfc_flux_dif_nir
);
// Check computed surface fluxes
logger->info("Check computed fluxes...\n");
REQUIRE(std::abs(sfc_flux_dir_nir.createHostCopy()(1) - 9.0) < tol);
REQUIRE(std::abs(sfc_flux_dir_vis.createHostCopy()(1) - 0.0) < tol);
REQUIRE(std::abs(sfc_flux_dif_nir.createHostCopy()(1) - 9.0) < tol);
REQUIRE(std::abs(sfc_flux_dif_vis.createHostCopy()(1) - 0.0) < tol);
// ---------------------------------
// ---------------------------------
// Test case, only flux in VIS bands
logger->info("Populate band-resolved 3d fluxes for test case with only VIS/UV flux...\n");
parallel_for(Bounds<3>(nbnd,nlay+1,ncol), YAKL_LAMBDA(int ibnd, int ilay, int icol) {
if (ibnd < 10) {
sw_bnd_flux_dir(icol,ilay,ibnd) = 0;
sw_bnd_flux_dif(icol,ilay,ibnd) = 0;
} else if (ibnd == 10) {
sw_bnd_flux_dir(icol,ilay,ibnd) = 0;
sw_bnd_flux_dif(icol,ilay,ibnd) = 0;
} else {
sw_bnd_flux_dir(icol,ilay,ibnd) = 1;
sw_bnd_flux_dif(icol,ilay,ibnd) = 1;
}
});
// Compute surface fluxes
logger->info("Compute broadband surface fluxes...\n");
scream::rrtmgp::compute_broadband_surface_fluxes(
ncol, kbot, nbnd,
sw_bnd_flux_dir, sw_bnd_flux_dif,
sfc_flux_dir_vis, sfc_flux_dir_nir,
sfc_flux_dif_vis, sfc_flux_dif_nir
);
// Check computed surface fluxes
logger->info("Check computed fluxes...\n");
REQUIRE(std::abs(sfc_flux_dir_nir.createHostCopy()(1) - 0.0) < tol);
REQUIRE(std::abs(sfc_flux_dir_vis.createHostCopy()(1) - 4.0) < tol);
REQUIRE(std::abs(sfc_flux_dif_nir.createHostCopy()(1) - 0.0) < tol);
REQUIRE(std::abs(sfc_flux_dif_vis.createHostCopy()(1) - 4.0) < tol);
// ---------------------------------
// ---------------------------------
// Test case, only flux in all bands
logger->info("Populate band-resolved 3d fluxes for test with non-zero flux in all bands...\n");
parallel_for(Bounds<3>(nbnd,nlay+1,ncol), YAKL_LAMBDA(int ibnd, int ilay, int icol) {
if (ibnd < 10) {
sw_bnd_flux_dir(icol,ilay,ibnd) = 1.0;
sw_bnd_flux_dif(icol,ilay,ibnd) = 2.0;
} else if (ibnd == 10) {
sw_bnd_flux_dir(icol,ilay,ibnd) = 3.0;
sw_bnd_flux_dif(icol,ilay,ibnd) = 4.0;
} else {
sw_bnd_flux_dir(icol,ilay,ibnd) = 5.0;
sw_bnd_flux_dif(icol,ilay,ibnd) = 6.0;
}
});
// Compute surface fluxes
logger->info("Compute broadband surface fluxes...\n");
scream::rrtmgp::compute_broadband_surface_fluxes(
ncol, kbot, nbnd,
sw_bnd_flux_dir, sw_bnd_flux_dif,
sfc_flux_dir_vis, sfc_flux_dir_nir,
sfc_flux_dif_vis, sfc_flux_dif_nir
);
// Check computed surface fluxes
logger->info("Check computed fluxes...\n");
REQUIRE(std::abs(sfc_flux_dir_nir.createHostCopy()(1) - 10.5) < tol);
REQUIRE(std::abs(sfc_flux_dir_vis.createHostCopy()(1) - 21.5) < tol);
REQUIRE(std::abs(sfc_flux_dif_nir.createHostCopy()(1) - 20.0) < tol);
REQUIRE(std::abs(sfc_flux_dif_vis.createHostCopy()(1) - 26.0) < tol);
// ---------------------------------
// Finalize YAKL
logger->info("Free memory...\n");
scream::rrtmgp::rrtmgp_finalize();
gas_concs.reset();
gas_names.deallocate();
sw_bnd_flux_dir.deallocate();
sw_bnd_flux_dif.deallocate();
sfc_flux_dir_nir.deallocate();
sfc_flux_dir_vis.deallocate();
sfc_flux_dif_nir.deallocate();
sfc_flux_dif_vis.deallocate();
if (yakl::isInitialized()) { yakl::finalize(); }
}
TEST_CASE("rrtmgp_test_radiation_do") {
// If we specify rad every step, radiation_do should always be true
REQUIRE(scream::rrtmgp::radiation_do(1, 0) == true);
REQUIRE(scream::rrtmgp::radiation_do(1, 1) == true);
REQUIRE(scream::rrtmgp::radiation_do(1, 2) == true);
// Test cases where we want rad called every other step
REQUIRE(scream::rrtmgp::radiation_do(2, 0) == true);
REQUIRE(scream::rrtmgp::radiation_do(2, 1) == false);
REQUIRE(scream::rrtmgp::radiation_do(2, 2) == true);
REQUIRE(scream::rrtmgp::radiation_do(2, 3) == false);
// Test cases where we want rad every third step
REQUIRE(scream::rrtmgp::radiation_do(3, 0) == true);
REQUIRE(scream::rrtmgp::radiation_do(3, 1) == false);
REQUIRE(scream::rrtmgp::radiation_do(3, 2) == false);
REQUIRE(scream::rrtmgp::radiation_do(3, 3) == true);
REQUIRE(scream::rrtmgp::radiation_do(3, 4) == false);
REQUIRE(scream::rrtmgp::radiation_do(3, 5) == false);
REQUIRE(scream::rrtmgp::radiation_do(3, 6) == true);
}
TEST_CASE("rrtmgp_test_check_range") {
// Initialize YAKL
if (!yakl::isInitialized()) { yakl::init(); }
// Create some dummy data and test with both values inside valid range and outside
auto dummy = real2d("dummy", 2, 1);
// All values within range
memset(dummy, 0.1);
REQUIRE(scream::rrtmgp::check_range(dummy, 0.0, 1.0, "dummy") == true);
// At least one value below lower bound
parallel_for(1, YAKL_LAMBDA (int i) {dummy(i, 1) = -0.1;});
REQUIRE(scream::rrtmgp::check_range(dummy, 0.0, 1.0, "dummy") == false);
// At least one value above upper bound
parallel_for(1, YAKL_LAMBDA (int i) {dummy(i, 1) = 1.1;});
REQUIRE(scream::rrtmgp::check_range(dummy, 0.0, 1.0, "dummy") == false);
dummy.deallocate();
if (yakl::isInitialized()) { yakl::finalize(); }
}
| 40.7287 | 147 | 0.635618 | [
"3d"
] |
6793a892026aa25e921ae974d5df4b2922b46492 | 71,082 | cc | C++ | jlist/jlist.cc | llllllllll/jlist | 07b1df2ed026ca009e51f23f6f369d198b9712c8 | [
"Apache-2.0",
"CNRI-Python-GPL-Compatible"
] | 44 | 2019-05-26T16:28:47.000Z | 2021-11-10T01:04:44.000Z | jlist/jlist.cc | llllllllll/jlist | 07b1df2ed026ca009e51f23f6f369d198b9712c8 | [
"Apache-2.0",
"CNRI-Python-GPL-Compatible"
] | 3 | 2019-07-31T17:32:46.000Z | 2019-10-31T20:48:44.000Z | jlist/jlist.cc | llllllllll/jlist | 07b1df2ed026ca009e51f23f6f369d198b9712c8 | [
"Apache-2.0",
"CNRI-Python-GPL-Compatible"
] | 1 | 2019-12-10T17:26:37.000Z | 2019-12-10T17:26:37.000Z | #include <algorithm>
#include <array>
#include <charconv>
#include <cstdint>
#include <string>
#include <vector>
#include <Python.h>
#include <structmember.h>
#include "jlist/jlist.h"
#include "jlist/scope_guard.h"
#if PY_MINOR_VERSION >= 7
#define JL_FASTCALL_FLAGS (METH_FASTCALL | METH_KEYWORDS)
#else
#define JL_FASTCALL_FLAGS METH_FASTCALL
#endif
namespace jl {
extern PyTypeObject jlist_type;
template<typename UnboxedType>
bool box_values(jlist& list) {
bool unwind = false;
Py_ssize_t ix = 0;
for (; ix < list.size(); ++ix) {
UnboxedType unboxed = entry_value<UnboxedType>(list.entries[ix]);
PyObject* as_ob = box_value(unboxed);
if (!as_ob) {
unwind = true;
break;
}
// move the new reference into the list
list.entries[ix].as_ob = as_ob;
}
if (unwind) {
for (Py_ssize_t unwind_ix = 0; unwind_ix < ix; ++unwind_ix) {
PyObject* boxed = list.entries[ix].as_ob;
UnboxedType unboxed = unbox_value<UnboxedType>(boxed);
Py_DECREF(boxed);
entry_value<UnboxedType>(list.entries[ix]) = unboxed;
}
}
list.homogeneous_type_ptr(entry_pytype<UnboxedType>);
return unwind;
}
bool maybe_box_values(jlist& list) {
switch (list.tag()) {
case entry_tag::unset:
case entry_tag::as_homogeneous_ob:
case entry_tag::as_heterogeneous_ob:
return false;
case entry_tag::as_int:
return box_values<std::int64_t>(list);
case entry_tag::as_double:
return box_values<double>(list);
default:
__builtin_unreachable();
}
}
namespace detail {
Py_ssize_t adjust_ix(Py_ssize_t ix, Py_ssize_t size, bool clamp) {
if (ix < 0) {
ix += size;
}
if (clamp) {
ix = std::clamp<Py_ssize_t>(ix, 0, size);
}
return ix;
}
} // namespace detail
namespace methods {
namespace detail {
bool setitem_helper(jlist& self, entry& entry, PyObject* ob, bool clear) {
auto add_object = [&] {
if (clear) {
Py_DECREF(entry.as_ob);
}
Py_INCREF(ob);
entry.as_ob = ob;
};
auto add_unboxed = [&](auto type) {
using T = decltype(type);
auto maybe_unboxed = maybe_unbox<T>(ob);
if (!maybe_unboxed) {
if (box_values<T>(self)) {
return true;
}
if (Py_TYPE(ob) != self.homogeneous_type_ptr()) {
self.tag(entry_tag::as_heterogeneous_ob);
}
add_object();
return false;
}
entry_value<T>(entry) = *maybe_unboxed;
return false;
};
PyTypeObject* tp = Py_TYPE(ob);
int overflow = 0;
switch (self.tag()) {
case entry_tag::unset:
if (tp == &PyFloat_Type) {
self.tag(entry_tag::as_double);
entry.as_double = PyFloat_AsDouble(ob);
return false;
}
if (tp == &PyLong_Type) {
entry.as_int = PyLong_AsLongLongAndOverflow(ob, &overflow);
if (!overflow) {
self.tag(entry_tag::as_int);
return false;
}
}
// fallthrough
self.homogeneous_type_ptr(tp);
add_object();
return false;
case entry_tag::as_homogeneous_ob:
if (Py_TYPE(ob) != self.homogeneous_type_ptr()) {
self.tag(entry_tag::as_heterogeneous_ob);
}
[[fallthrough]];
case entry_tag::as_heterogeneous_ob:
add_object();
return false;
case entry_tag::as_int:
return add_unboxed(std::int64_t{});
case entry_tag::as_double:
return add_unboxed(double{});
default:
__builtin_unreachable();
}
}
entry* get_entry(jlist& self, Py_ssize_t ix) {
if (ix < 0 || ix >= self.size()) {
return nullptr;
}
return &self.entries[ix];
}
template<typename T>
bool box_and_extend(jlist& self, jlist& other) {
std::size_t original_size = self.entries.size();
self.entries.resize(original_size + other.size());
Py_ssize_t ix = 0;
auto unwind = [&] {
for (std::size_t ix = original_size; ix < self.entries.size(); ++ix) {
Py_DECREF(self.entries[ix].as_ob);
}
self.entries.erase(self.entries.begin() + original_size, self.entries.end());
return true;
};
for (entry& e : other.entries) {
PyObject* boxed = box_value(entry_value<T>(e));
if (!boxed) {
return unwind();
}
bool err = detail::setitem_helper(self,
self.entries[original_size + ix++],
boxed,
false);
Py_DECREF(boxed);
if (err) {
return unwind();
}
}
return false;
}
bool extend_helper(jlist& self, jlist& other) {
if (!other.size()) {
// don't start boxing if there are no entries in `other`
return false;
}
if (self.tag() == other.tag() || self.tag() == entry_tag::unset) {
// the types are the same, just use vector insert to add all the items
self.entries.insert(self.entries.end(),
other.entries.begin(),
other.entries.end());
if (self.boxed()) {
// the type is object, so we need to add a new reference to all the
// items
for (entry& e : other.entries) {
Py_INCREF(e.as_ob);
}
}
if (self.tag() == entry_tag::as_homogeneous_ob) {
if (self.homogeneous_type_ptr() != other.homogeneous_type_ptr()) {
self.tag(entry_tag::as_heterogeneous_ob);
}
}
else {
// update in case `tag` was `unset`
self.tag(other.tag());
}
return false;
}
// the types are difference, we may need to box the lhs into objects so
// that we can add all the items into a single list
if (maybe_box_values(self)) {
return true;
}
switch (other.tag()) {
case entry_tag::as_homogeneous_ob:
case entry_tag::as_heterogeneous_ob:
return box_and_extend<PyObject*>(self, other);
case entry_tag::as_int:
return box_and_extend<std::int64_t>(self, other);
case entry_tag::as_double:
return box_and_extend<double>(self, other);
default:
__builtin_unreachable();
}
}
bool extend_fast_sequence(jlist& self, PyObject* other) {
Py_ssize_t size = PySequence_Fast_GET_SIZE(other);
if (!size) {
// don't do anything if the sequence is empty
return false;
}
std::size_t original_size = self.entries.size();
self.entries.resize(original_size + size);
PyObject** items = PySequence_Fast_ITEMS(other);
for (Py_ssize_t ix = 0; ix < size; ++ix) {
if (detail::setitem_helper(self,
self.entries[original_size + ix],
items[ix],
false)) {
if (self.boxed()) {
for (std::size_t ix = original_size; ix < self.entries.size(); ++ix) {
Py_DECREF(self.entries[ix].as_ob);
}
}
self.entries.erase(self.entries.begin() + original_size, self.entries.end());
return true;
}
}
return false;
}
bool extend_iterable(jlist& self, PyObject* other) {
PyObject* it = PyObject_GetIter(other);
if (!it) {
return true;
}
Py_ssize_t maybe_size = PySequence_Size(other);
if (maybe_size > 0) {
self.entries.reserve(self.size() + maybe_size);
}
else {
PyErr_Clear();
}
Py_ssize_t ix = 0;
PyObject* ob;
while ((ob = PyIter_Next(it))) {
entry& e = self.entries.emplace_back();
bool err = detail::setitem_helper(self, e, ob, false);
Py_DECREF(ob);
if (err) {
if (self.boxed()) {
for (Py_ssize_t unwind_ix = 0; unwind_ix < ix; ++unwind_ix) {
Py_DECREF(self.entries[unwind_ix].as_ob);
}
}
Py_DECREF(it);
return true;
}
++ix;
}
Py_DECREF(it);
return PyErr_Occurred();
}
bool extend_range(jlist& self, PyObject* other) {
PyObject* start_ob = PyObject_GetAttrString(other, "start");
if (!start_ob) {
return true;
}
scope_guard start_sg([&] { Py_DECREF(start_ob); });
Py_ssize_t start = PyLong_AsSsize_t(start_ob);
if (start == -1) {
PyErr_Clear();
return extend_iterable(self, other);
}
PyObject* stop_ob = PyObject_GetAttrString(other, "stop");
if (!stop_ob) {
return true;
}
scope_guard stop_sg([&] { Py_DECREF(stop_ob); });
Py_ssize_t stop = PyLong_AsSsize_t(stop_ob);
if (stop == -1) {
PyErr_Clear();
return extend_iterable(self, other);
}
PyObject* step_ob = PyObject_GetAttrString(other, "step");
if (!step_ob) {
return true;
}
scope_guard step_sg([&] { Py_DECREF(step_ob); });
Py_ssize_t step = PyLong_AsSsize_t(step_ob);
if (step == -1) {
PyErr_Clear();
return extend_iterable(self, other);
}
auto compute_size =
[&](Py_ssize_t low, Py_ssize_t high, Py_ssize_t step) -> Py_ssize_t {
if (low >= high) {
return 0;
}
return (high - low - 1) / step + 1;
};
if (self.tag() == entry_tag::as_int || self.tag() == entry_tag::unset) {
self.tag(entry_tag::as_int);
auto fill = [&](Py_ssize_t size, auto cmp) {
Py_ssize_t out_ix = self.size();
self.entries.resize(out_ix + size);
for (Py_ssize_t ix = start; cmp(ix, stop); ix += step) {
self.entries[out_ix++].as_int = ix;
}
};
if (step > 0) {
fill(compute_size(start, stop, step), [](auto a, auto b) { return a < b; });
}
else {
fill(compute_size(stop, start, -step), [](auto a, auto b) { return a > b; });
}
}
else {
if (maybe_box_values(self)) {
return true;
}
auto fill = [&](Py_ssize_t size, auto cmp) {
Py_ssize_t original_size = self.size();
Py_ssize_t out_ix = original_size;
self.entries.resize(out_ix + size);
for (Py_ssize_t ix = start; cmp(ix, stop); ix += step) {
PyObject* tmp = PyLong_FromSsize_t(ix);
if (!tmp) {
for (Py_ssize_t unwind_ix = 0; unwind_ix < ix; ++unwind_ix) {
Py_DECREF(self.entries[unwind_ix].as_ob);
}
self.entries.erase(self.entries.begin() + original_size,
self.entries.end());
return true;
}
self.entries[out_ix++].as_ob = tmp;
}
return false;
};
if (step > 0) {
return fill(compute_size(start, stop, step),
[](auto a, auto b) { return a < b; });
}
else {
return fill(compute_size(stop, start, -step),
[](auto a, auto b) { return a > b; });
}
}
return false;
}
bool extend_helper(jlist& self, PyObject* other) {
if (Py_TYPE(other) == &jlist_type) {
// fast path code when we know the rhs is also a jlist
return extend_helper(self, *reinterpret_cast<jlist*>(other));
}
if (PyList_CheckExact(other) || PyTuple_CheckExact(other)) {
return extend_fast_sequence(self, other);
}
if (PyRange_Check(other)) {
return extend_range(self, other);
}
return extend_iterable(self, other);
}
template<typename I>
jlist* new_jlist(entry_tag tag, I begin, I end, PyTypeObject* cls = &jlist_type) {
jlist* out = PyObject_GC_New(jlist, cls);
if (!out) {
return nullptr;
}
out->tag(tag);
new (&out->entries) std::vector<entry>(begin, end);
if (is_object_tag(tag)) {
for (entry e : out->entries) {
Py_INCREF(e.as_ob);
}
}
PyObject_GC_Track(out);
return out;
}
jlist* new_jlist(entry_tag tag, PyTypeObject* cls = &jlist_type) {
jlist* out = PyObject_GC_New(jlist, cls);
if (!out) {
return nullptr;
}
out->tag(tag);
new (&out->entries) std::vector<entry>();
PyObject_GC_Track(out);
return out;
}
void clear_helper(jlist& self) {
if (self.boxed()) {
for (entry e : self.entries) {
Py_DECREF(e.as_ob);
}
}
self.entries.clear();
}
} // namespace detail
PyObject* new_(PyTypeObject* cls, PyObject*, PyObject*) {
return reinterpret_cast<PyObject*>(detail::new_jlist(entry_tag::unset, cls));
}
int init(PyObject* _self, PyObject* args, PyObject* kwargs) {
jlist& self = *reinterpret_cast<jlist*>(_self);
if (kwargs && PyDict_Size(kwargs)) {
PyErr_SetString(PyExc_TypeError, "jlist doesn't accept keywords");
return -1;
}
// you can manually call `jlist.__init__` on an existing list, which should reset
// the state
detail::clear_helper(self);
if (PyTuple_GET_SIZE(args) == 0) {
return 0;
}
else if (PyTuple_GET_SIZE(args) == 1) {
if (detail::extend_helper(self, PyTuple_GET_ITEM(args, 0))) {
return -1;
}
return 0;
}
PyErr_SetString(PyExc_TypeError, "jlist accepts either 0 or 1 positional argument");
return -1;
}
void deallocate(PyObject* _self) {
jlist& self = *reinterpret_cast<jlist*>(_self);
PyObject_GC_UnTrack(_self);
if (self.boxed()) {
for (entry& e : self.entries) {
Py_DECREF(e.as_ob);
}
}
self.entries.~vector();
PyObject_GC_Del(_self);
}
PyDoc_STRVAR(_from_starargs_doc,
"Create a jlist from *args. This is used to efficiently implement jlist "
"literal construction when patching list literals.");
PyObject* _from_starargs(PyObject* _cls, PyObject** args, int nargs, PyObject*) {
PyTypeObject* cls = reinterpret_cast<PyTypeObject*>(_cls);
jlist* self = detail::new_jlist(entry_tag::unset, cls);
if (!self) {
return nullptr;
}
self->entries.resize(nargs);
for (Py_ssize_t ix = 0; ix < nargs; ++ix) {
if (detail::setitem_helper(*self, self->entries[ix], args[ix], false)) {
if (self->boxed()) {
for (Py_ssize_t unwind_ix = 0; unwind_ix < ix; ++unwind_ix) {
Py_DECREF(self->entries[unwind_ix].as_ob);
}
}
self->entries.clear();
Py_DECREF(self);
return nullptr;
}
}
return reinterpret_cast<PyObject*>(self);
}
PyMethodDef _from_starargs_method = {"_from_starargs",
unsafe_cast_to_pycfunction(_from_starargs),
JL_FASTCALL_FLAGS | METH_CLASS,
_from_starargs_doc};
PyDoc_STRVAR(_reserve_doc,
"Reserve space for elements. Does not change the length of the jlist.");
PyObject* _reserve(PyObject* _self, PyObject* size_ob) {
jlist& self = *reinterpret_cast<jlist*>(_self);
Py_ssize_t size = PyNumber_AsSsize_t(size_ob, PyExc_OverflowError);
if (size == -1) {
return nullptr;
}
self.entries.reserve(size);
Py_RETURN_NONE;
}
PyMethodDef _reserve_method = {"_reserve", _reserve, METH_O, _reserve_doc};
PyObject* repr(PyObject* _self) {
Py_ssize_t rc = Py_ReprEnter(_self);
if (rc != 0) {
if (rc > 0) {
return PyUnicode_FromString("jlist([...])");
}
return nullptr;
}
scope_guard repr([&] { Py_ReprLeave(_self); });
jlist& self = *reinterpret_cast<jlist*>(_self);
if (!self.size()) {
return PyUnicode_FromString("jlist([])");
}
_PyUnicodeWriter writer;
_PyUnicodeWriter_Init(&writer);
scope_guard cleanup_writer([&] { _PyUnicodeWriter_Dealloc(&writer); });
writer.overallocate = 1;
writer.min_length = 7 + 1 + 1 + (2 + 1) * (self.size() - 1) + 1;
if (_PyUnicodeWriter_WriteASCIIString(&writer, "jlist([", 7) < 0) {
return nullptr;
}
Py_ssize_t ix = 0;
switch (self.tag()) {
case entry_tag::as_homogeneous_ob:
case entry_tag::as_heterogeneous_ob:
for (entry e : self.entries) {
if (ix > 0) {
if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0) {
return nullptr;
}
}
PyObject* repr = PyObject_Repr(e.as_ob);
if (!repr) {
return nullptr;
}
int err = _PyUnicodeWriter_WriteStr(&writer, repr);
Py_DECREF(repr);
if (err < 0) {
return nullptr;
}
++ix;
}
break;
case entry_tag::as_int:
std::array<char, 20> buffer;
for (entry e : self.entries) {
if (ix > 0) {
if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0) {
return nullptr;
}
}
auto [p, ec] = std::to_chars(buffer.begin(), buffer.end(), e.as_int);
if (_PyUnicodeWriter_WriteASCIIString(&writer,
buffer.begin(),
p - buffer.begin()) < 0) {
return nullptr;
}
++ix;
}
break;
case entry_tag::as_double:
for (entry e : self.entries) {
if (ix > 0) {
if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0) {
return nullptr;
}
}
std::string str = std::to_string(e.as_double);
if (_PyUnicodeWriter_WriteASCIIString(&writer, str.data(), str.size()) < 0) {
return nullptr;
}
++ix;
}
break;
default:
__builtin_unreachable();
}
writer.overallocate = 0;
if (_PyUnicodeWriter_WriteASCIIString(&writer, "])", 2) < 0) {
return nullptr;
}
cleanup_writer.dismiss();
return _PyUnicodeWriter_Finish(&writer);
}
PyObject* richcompare(PyObject* _self, PyObject* _other, int cmp) {
jlist& self = *reinterpret_cast<jlist*>(_self);
if (!(cmp == Py_EQ || cmp == Py_NE)) {
Py_RETURN_NOTIMPLEMENTED;
}
if (Py_TYPE(_other) != &jlist_type) {
Py_RETURN_NOTIMPLEMENTED;
}
jlist& other = *reinterpret_cast<jlist*>(_other);
if (self.size() != other.size()) {
return PyBool_FromLong(cmp == Py_NE);
}
if (!self.size()) {
return PyBool_FromLong(cmp == Py_EQ);
}
auto box_lhs_loop = [&](auto type) -> PyObject* {
using T = decltype(type);
for (Py_ssize_t ix = 0; ix < self.size(); ++ix) {
T unboxed_lhs = entry_value<T>(self.entries[ix]);
PyObject* lhs = box_value(unboxed_lhs);
if (!lhs) {
return nullptr;
}
PyObject* rhs = other.entries[ix].as_ob;
int r = PyObject_RichCompareBool(lhs, rhs, Py_EQ);
Py_DECREF(lhs);
if (r < 0) {
return nullptr;
}
if (!r) {
return PyBool_FromLong(cmp == Py_NE);
}
}
return PyBool_FromLong(cmp == Py_EQ);
};
auto box_rhs_loop = [&](auto type) -> PyObject* {
using T = decltype(type);
for (Py_ssize_t ix = 0; ix < self.size(); ++ix) {
PyObject* lhs = self.entries[ix].as_ob;
T unboxed_rhs = entry_value<T>(other.entries[ix]);
PyObject* rhs = box_value(unboxed_rhs);
if (!rhs) {
return nullptr;
}
int r = PyObject_RichCompareBool(lhs, rhs, Py_EQ);
Py_DECREF(rhs);
if (r < 0) {
return nullptr;
}
if (!r) {
return PyBool_FromLong(cmp == Py_NE);
}
}
return PyBool_FromLong(cmp == Py_EQ);
};
auto prim_loop = [&](auto lhs_type, auto rhs_type) {
using LHS = decltype(lhs_type);
using RHS = decltype(rhs_type);
for (Py_ssize_t ix = 0; ix < self.size(); ++ix) {
LHS lhs = entry_value<LHS>(self.entries[ix]);
RHS rhs = entry_value<RHS>(other.entries[ix]);
if (lhs != rhs) {
return PyBool_FromLong(cmp == Py_NE);
}
}
return PyBool_FromLong(cmp == Py_EQ);
};
switch (self.tag()) {
case entry_tag::as_homogeneous_ob:
if (other.tag() == entry_tag::as_homogeneous_ob &&
self.homogeneous_type_ptr() == other.homogeneous_type_ptr()) {
auto richcompare = self.homogeneous_type_ptr()->tp_richcompare;
if (!richcompare) {
return PyBool_FromLong(self.size() == 0 && other.size() == 0);
}
for (Py_ssize_t ix = 0; ix < self.size(); ++ix) {
PyObject* lhs = self.entries[ix].as_ob;
PyObject* rhs = other.entries[ix].as_ob;
PyObject* result_ob = richcompare(lhs, rhs, Py_EQ);
if (!result_ob) {
return nullptr;
}
int r;
if (result_ob == Py_NotImplemented) {
r = lhs == rhs;
}
else {
r = PyObject_IsTrue(result_ob);
if (r < 0) {
Py_DECREF(result_ob);
return nullptr;
}
}
Py_DECREF(result_ob);
if (!r) {
return PyBool_FromLong(cmp == Py_NE);
}
}
return PyBool_FromLong(cmp == Py_EQ);
}
[[fallthrough]];
case entry_tag::as_heterogeneous_ob:
switch (other.tag()) {
case entry_tag::as_homogeneous_ob:
case entry_tag::as_heterogeneous_ob:
for (Py_ssize_t ix = 0; ix < self.size(); ++ix) {
PyObject* lhs = self.entries[ix].as_ob;
PyObject* rhs = other.entries[ix].as_ob;
int r = PyObject_RichCompareBool(lhs, rhs, Py_EQ);
if (r < 0) {
return nullptr;
}
if (!r) {
return PyBool_FromLong(cmp == Py_NE);
}
}
return PyBool_FromLong(cmp == Py_EQ);
case entry_tag::as_int:
return box_rhs_loop(std::int64_t{});
case entry_tag::as_double:
return box_rhs_loop(double{});
default:
__builtin_unreachable();
}
case entry_tag::as_int:
switch (other.tag()) {
case entry_tag::as_homogeneous_ob:
case entry_tag::as_heterogeneous_ob:
return box_lhs_loop(std::int64_t{});
case entry_tag::as_int:
return prim_loop(std::int64_t{}, std::int64_t{});
case entry_tag::as_double:
return prim_loop(std::int64_t{}, double{});
default:
__builtin_unreachable();
}
case entry_tag::as_double:
switch (other.tag()) {
case entry_tag::as_homogeneous_ob:
case entry_tag::as_heterogeneous_ob:
return box_lhs_loop(double{});
case entry_tag::as_int:
return prim_loop(double{}, std::int64_t{});
case entry_tag::as_double:
return prim_loop(double{}, double{});
default:
__builtin_unreachable();
}
default:
__builtin_unreachable();
}
__builtin_unreachable();
}
PyDoc_STRVAR(append_doc, "Append object to the end of the jlist.h");
PyObject* append(PyObject* _self, PyObject* ob) {
jlist& self = *reinterpret_cast<jlist*>(_self);
entry& e = self.entries.emplace_back();
if (detail::setitem_helper(self, e, ob, false)) {
return nullptr;
}
Py_RETURN_NONE;
}
PyMethodDef append_method = {"append", append, METH_O, append_doc};
PyDoc_STRVAR(clear_doc, "Remove all items from self.");
PyObject* clear(PyObject* _self, PyObject*) {
jlist& self = *reinterpret_cast<jlist*>(_self);
detail::clear_helper(self);
Py_RETURN_NONE;
}
PyMethodDef clear_method = {"clear", clear, METH_NOARGS, clear_doc};
PyDoc_STRVAR(count_doc, "Return the number of occurrences of value in self.");
PyObject* count(PyObject* _self, PyObject* value) {
jlist& self = *reinterpret_cast<jlist*>(_self);
if (!self.size()) {
return PyLong_FromLong(0);
}
Py_ssize_t count = 0;
auto boxing_count = [&](auto type) {
using T = decltype(type);
for (entry e : self.entries) {
PyObject* boxed = box_value(entry_value<T>(e));
if (!boxed) {
return true;
}
int r = PyObject_RichCompareBool(boxed, value, Py_EQ);
Py_DECREF(boxed);
if (r < 0) {
return true;
}
count += r;
}
return false;
};
switch (self.tag()) {
case entry_tag::as_homogeneous_ob:
if (self.homogeneous_type_ptr() == Py_TYPE(value)) {
auto richcompare = self.homogeneous_type_ptr()->tp_richcompare;
if (!richcompare) {
for (entry e : self.entries) {
count += e.as_ob == value;
}
}
else {
for (entry e : self.entries) {
PyObject* result_ob = richcompare(e.as_ob, value, Py_EQ);
if (!result_ob) {
return nullptr;
}
int r = PyObject_IsTrue(result_ob);
Py_DECREF(result_ob);
if (r < 0) {
return nullptr;
}
count += r;
}
}
break;
}
[[fallthrough]];
case entry_tag::as_heterogeneous_ob:
for (entry e : self.entries) {
int r = PyObject_RichCompareBool(e.as_ob, value, Py_EQ);
if (r < 0) {
return nullptr;
}
count += r;
}
break;
case entry_tag::as_int: {
auto maybe_unboxed = maybe_unbox<std::int64_t>(value);
if (!maybe_unboxed) {
if (boxing_count(std::int64_t{})) {
return nullptr;
}
}
else {
std::int64_t rhs = *maybe_unboxed;
for (entry e : self.entries) {
count += e.as_int == rhs;
}
}
break;
}
case entry_tag::as_double: {
auto maybe_unboxed = maybe_unbox<double>(value);
if (!maybe_unboxed) {
if (boxing_count(double{})) {
return nullptr;
}
}
else {
std::int64_t rhs = *maybe_unboxed;
for (entry e : self.entries) {
count += e.as_double == rhs;
}
}
break;
}
default:
__builtin_unreachable();
}
return PyLong_FromSsize_t(count);
}
PyMethodDef count_method = {"count", count, METH_O, count_doc};
PyDoc_STRVAR(copy_doc, "Return a shallow copy of the jlist.");
PyObject* copy(PyObject* _self, PyObject*) {
jlist& self = *reinterpret_cast<jlist*>(_self);
return reinterpret_cast<PyObject*>(
detail::new_jlist(self.tag(), self.entries.begin(), self.entries.end()));
}
PyMethodDef copy_method = {"copy", copy, METH_NOARGS, copy_doc};
PyDoc_STRVAR(extend_doc, "Extend jlist by appending elements from the iterable.");
PyObject* extend(PyObject* _self, PyObject* ob) {
jlist& self = *reinterpret_cast<jlist*>(_self);
if (detail::extend_helper(self, ob)) {
return nullptr;
}
Py_RETURN_NONE;
}
PyMethodDef extend_method = {"extend", extend, METH_O, extend_doc};
PyDoc_STRVAR(index_doc, "Return the first index of value in self.");
namespace detail {
Py_ssize_t index_helper(jlist& self,
PyObject* value,
Py_ssize_t start = 0,
Py_ssize_t stop = 9223372036854775807L) {
if (!self.size()) {
return -1;
}
start = jl::detail::adjust_ix(start, self.size(), true);
stop = jl::detail::adjust_ix(stop, self.size(), true);
auto boxing_index = [&](auto type) -> Py_ssize_t {
using T = decltype(type);
// the comparison can cause the list to resize
for (Py_ssize_t ix = start; ix < stop && ix < self.size(); ++ix) {
PyObject* boxed = box_value(entry_value<T>(self.entries[ix]));
if (!boxed) {
return -2;
}
int r = PyObject_RichCompareBool(boxed, value, Py_EQ);
Py_DECREF(boxed);
if (r < 0) {
return -2;
}
if (r) {
return ix;
}
}
return -1;
};
switch (self.tag()) {
case entry_tag::as_homogeneous_ob:
if (self.homogeneous_type_ptr() == Py_TYPE(value)) {
auto richcompare = self.homogeneous_type_ptr()->tp_richcompare;
if (!richcompare) {
for (Py_ssize_t ix = start; ix < stop && ix < self.size(); ++ix) {
if (self.entries[ix].as_ob == value) {
return ix;
}
}
}
else {
for (Py_ssize_t ix = start; ix < stop && ix < self.size(); ++ix) {
PyObject* result_ob =
richcompare(self.entries[ix].as_ob, value, Py_EQ);
if (!result_ob) {
return -2;
}
int r;
if (result_ob == Py_NotImplemented) {
r = self.entries[ix].as_ob == value;
}
else {
r = PyObject_IsTrue(result_ob);
if (r < 0) {
Py_DECREF(result_ob);
return -2;
}
}
Py_DECREF(result_ob);
if (r) {
return ix;
}
}
}
return -1;
}
[[fallthrough]];
case entry_tag::as_heterogeneous_ob:
// the comparison can cause the list to resize
for (Py_ssize_t ix = start; ix < stop && ix < self.size(); ++ix) {
int r = PyObject_RichCompareBool(self.entries[ix].as_ob, value, Py_EQ);
if (r < 0) {
return -2;
}
if (r) {
return ix;
}
}
return -1;
case entry_tag::as_int: {
auto maybe_unboxed = maybe_unbox<std::int64_t>(value);
if (!maybe_unboxed) {
return boxing_index(std::int64_t{});
}
else {
std::int64_t rhs = *maybe_unboxed;
for (Py_ssize_t ix = start; ix < stop; ++ix) {
if (self.entries[ix].as_int == rhs) {
return ix;
}
}
return -1;
}
}
case entry_tag::as_double: {
auto maybe_unboxed = maybe_unbox<double>(value);
if (!maybe_unboxed) {
return boxing_index(double{});
}
else {
double rhs = *maybe_unboxed;
for (Py_ssize_t ix = start; ix < stop; ++ix) {
if (self.entries[ix].as_double == rhs) {
return ix;
}
}
return -1;
}
}
default:
__builtin_unreachable();
}
__builtin_unreachable();
}
} // namespace detail
PyObject* index(PyObject* _self, PyObject** args, int nargs, PyObject* kwnames) {
jlist& self = *reinterpret_cast<jlist*>(_self);
PyObject* value = nullptr;
Py_ssize_t start = 0;
Py_ssize_t stop = self.size();
if (kwnames && PyTuple_GET_SIZE(kwnames)) {
PyErr_SetString(PyExc_TypeError, "index() takes no keyword arguments");
return nullptr;
}
auto clamp_bound = [&](PyObject* ob, Py_ssize_t& value) {
value = PyNumber_AsSsize_t(ob, PyExc_OverflowError);
if (value == -1) {
if (PyErr_Occurred() == PyExc_OverflowError) {
PyErr_Clear();
PyObject* zero = PyLong_FromSsize_t(0);
if (!zero) {
return true;
}
int r = PyObject_RichCompareBool(ob, zero, Py_LE);
Py_DECREF(zero);
if (r < 0) {
return true;
}
if (r) {
value = 0;
}
else {
value = self.size();
}
}
else {
return true;
}
}
return false;
};
if (!nargs) {
PyErr_SetString(PyExc_TypeError, "index() takes at least 1 argument (0 given)");
return nullptr;
}
if (nargs >= 1) {
value = args[0];
}
if (nargs >= 2) {
if (clamp_bound(args[1], start)) {
return nullptr;
}
}
if (nargs >= 3) {
if (clamp_bound(args[2], stop)) {
return nullptr;
}
}
if (nargs > 3) {
PyErr_Format(PyExc_TypeError,
"index() takes at most 3 arguments (%zd given)",
nargs);
return nullptr;
}
Py_ssize_t ix = detail::index_helper(self, value, start, stop);
if (ix == -2) {
return nullptr;
}
else if (ix == -1) {
PyErr_Format(PyExc_ValueError, "%R is not in jlist", value);
return nullptr;
}
return PyLong_FromSsize_t(ix);
}
PyMethodDef index_method = {"index",
unsafe_cast_to_pycfunction(index),
JL_FASTCALL_FLAGS,
index_doc};
PyDoc_STRVAR(insert_doc, "Insert object before index into self.");
PyObject* insert(PyObject* _self, PyObject** args, int nargs, PyObject* kwnames) {
jlist& self = *reinterpret_cast<jlist*>(_self);
if (kwnames && PyTuple_GET_SIZE(kwnames)) {
PyErr_SetString(PyExc_TypeError, "insert() takes no keyword arguments");
}
if (nargs != 2) {
PyErr_Format(PyExc_TypeError,
"jlist.insert expects exactly 2 arguments, got: %zd",
PyTuple_GET_SIZE(args));
return nullptr;
}
PyObject* index_ob = args[0];
PyObject* value = args[1];
Py_ssize_t index = PyNumber_AsSsize_t(index_ob, PyExc_IndexError);
if (index == -1 && PyErr_Occurred()) {
return nullptr;
}
index = jl::detail::adjust_ix(index, self.size(), true);
if (index >= self.size()) {
return append(_self, value);
}
auto it = self.entries.emplace(self.entries.begin() + index);
if (detail::setitem_helper(self, *it, value, false)) {
return nullptr;
}
Py_RETURN_NONE;
}
PyMethodDef insert_method = {"insert",
unsafe_cast_to_pycfunction(insert),
JL_FASTCALL_FLAGS,
insert_doc};
PyDoc_STRVAR(pop_doc, "Remove and return item at index (default last).");
PyObject* pop(PyObject* _self, PyObject** args, int nargs, PyObject* kwnames) {
jlist& self = *reinterpret_cast<jlist*>(_self);
if (kwnames && PyTuple_GET_SIZE(kwnames)) {
PyErr_SetString(PyExc_TypeError, "pop() takes no keyword arguments");
}
Py_ssize_t ix = 0;
if (nargs == 0) {
ix = self.size() - 1;
}
else if (nargs == 1) {
ix = PyNumber_AsSsize_t(args[0], PyExc_IndexError);
if (ix == -1 && PyErr_Occurred()) {
return nullptr;
}
}
else {
PyErr_Format(PyExc_TypeError,
"pop() takes at most 1 argument (%zd given)",
nargs);
return nullptr;
}
if (!self.size()) {
PyErr_SetString(PyExc_IndexError, "pop from empty jlist");
return nullptr;
}
entry* maybe_e = detail::get_entry(self, ix);
if (!maybe_e) {
PyErr_SetString(PyExc_IndexError, "pop index out of range");
return nullptr;
}
entry& e = *maybe_e;
PyObject* out;
switch (self.tag()) {
case entry_tag::as_homogeneous_ob:
case entry_tag::as_heterogeneous_ob:
out = e.as_ob;
break;
case entry_tag::as_int:
out = box_value(e.as_int);
break;
case entry_tag::as_double:
out = box_value(e.as_double);
break;
default:
__builtin_unreachable();
}
self.entries.erase(self.entries.begin() + ix);
return out;
}
PyMethodDef pop_method = {"pop",
unsafe_cast_to_pycfunction(pop),
JL_FASTCALL_FLAGS,
pop_doc};
PyDoc_STRVAR(remove_doc, "Remove first occurrence of value.");
PyObject* remove(PyObject* _self, PyObject* value) {
jlist& self = *reinterpret_cast<jlist*>(_self);
Py_ssize_t ix = detail::index_helper(self, value);
if (ix == -2) {
return nullptr;
}
else if (ix == -1) {
PyErr_SetString(PyExc_ValueError, "jlist.remove(x): x not in list");
return nullptr;
}
if (self.boxed()) {
Py_DECREF(self.entries[ix].as_ob);
}
self.entries.erase(self.entries.begin() + ix);
Py_RETURN_NONE;
}
PyMethodDef remove_method = {"remove", remove, METH_O, remove_doc};
PyDoc_STRVAR(reverse_doc, "Reverse *IN PLACE*.");
PyObject* reverse(PyObject* _self, PyObject*) {
jlist& self = *reinterpret_cast<jlist*>(_self);
std::reverse(self.entries.begin(), self.entries.end());
Py_RETURN_NONE;
}
PyMethodDef reverse_method = {"reverse", reverse, METH_NOARGS, reverse_doc};
PyDoc_STRVAR(sort_doc, "Stable sort *IN PLACE*.");
namespace detail {
bool sort_without_key(jlist& self) {
try {
switch (self.tag()) {
case entry_tag::as_homogeneous_ob: {
auto richcompare = self.homogeneous_type_ptr()->tp_richcompare;
auto unsupported = [&] {
PyErr_Format(
PyExc_TypeError,
"'<' not supported between instances of '%.200s' and '%.200s'",
self.homogeneous_type_ptr()->tp_name,
self.homogeneous_type_ptr()->tp_name);
};
if (!richcompare && self.size()) {
unsupported();
return true;
}
// Python builtin.list gives a stability contract here.
std::stable_sort(self.entries.begin(),
self.entries.end(),
[richcompare, unsupported](entry a, entry b) {
PyObject* result_ob =
richcompare(a.as_ob, b.as_ob, Py_LT);
if (!result_ob) {
throw std::runtime_error("bad compare");
}
if (result_ob == Py_NotImplemented) {
Py_DECREF(result_ob);
unsupported();
throw std::runtime_error("bad compare");
}
int r = PyObject_IsTrue(result_ob);
Py_DECREF(result_ob);
if (r < 0) {
throw std::runtime_error("bad compare");
}
return r;
});
break;
}
case entry_tag::as_heterogeneous_ob:
// Python builtin.list gives a stability contract here.
std::stable_sort(self.entries.begin(),
self.entries.end(),
[](entry a, entry b) {
int r =
PyObject_RichCompareBool(a.as_ob, b.as_ob, Py_LT);
if (r < 0) {
throw std::runtime_error("bad compare");
}
return r;
});
break;
case entry_tag::as_int:
// Python builtin.list gives a stability contract here, but since we are
// erasing the identity of the stored ints, we can use a non-stable sort.
std::sort(self.entries.begin(), self.entries.end(), [](entry a, entry b) {
return a.as_int < b.as_int;
});
break;
case entry_tag::as_double:
// Python builtin.list gives a stability contract here, but since we are
// erasing the identity of the stored doubles, we can use a non-stable sort.
std::sort(self.entries.begin(), self.entries.end(), [](entry a, entry b) {
return a.as_double < b.as_double;
});
break;
default:
__builtin_unreachable();
}
}
catch (...) {
return true;
}
return false;
}
bool sort_with_key(jlist& self, PyObject* key) {
auto compare_objects = [&](PyObject* a, PyObject* b) {
PyObject* lhs = PyObject_CallFunctionObjArgs(key, a, nullptr);
if (!lhs) {
throw std::runtime_error("bad compare");
}
PyObject* rhs = PyObject_CallFunctionObjArgs(key, b, nullptr);
if (!rhs) {
Py_DECREF(lhs);
throw std::runtime_error("bad compare");
}
int r = PyObject_RichCompareBool(lhs, rhs, Py_LT);
Py_DECREF(lhs);
Py_DECREF(rhs);
if (r < 0) {
throw std::runtime_error("bad compare");
}
return r;
};
auto box_and_compare = [&](auto type, entry a, entry b) {
using T = decltype(type);
PyObject* lhs = box_value(entry_value<T>(a));
if (!lhs) {
throw std::runtime_error("bad compare");
}
PyObject* rhs = box_value(entry_value<T>(b));
if (!rhs) {
throw std::runtime_error("bad compare");
}
int out = compare_objects(lhs, rhs);
Py_DECREF(lhs);
Py_DECREF(rhs);
return out;
};
try {
switch (self.tag()) {
case entry_tag::as_homogeneous_ob:
case entry_tag::as_heterogeneous_ob:
// Python builtin.list gives a stability contract here.
std::stable_sort(self.entries.begin(),
self.entries.end(),
[&](entry a, entry b) {
return compare_objects(a.as_ob, b.as_ob);
});
break;
case entry_tag::as_int:
// Python builtin.list gives a stability contract here, but since we are
// erasing the identity of the stored ints, we can use a non-stable sort.
std::sort(self.entries.begin(), self.entries.end(), [&](entry a, entry b) {
return box_and_compare(std::int64_t{}, a, b);
});
break;
case entry_tag::as_double:
// Python builtin.list gives a stability contract here, but since we are
// erasing the identity of the stored doubles, we can use a non-stable sort.
std::sort(self.entries.begin(), self.entries.end(), [&](entry a, entry b) {
return box_and_compare(double{}, a, b);
});
break;
default:
__builtin_unreachable();
}
}
catch (...) {
return true;
}
return false;
}
} // namespace detail
PyObject* sort(PyObject* _self, PyObject** args, int nargs, PyObject* kwnames) {
jlist& self = *reinterpret_cast<jlist*>(_self);
if (nargs) {
PyErr_SetString(PyExc_TypeError, "sort() takes no positional arguments");
return nullptr;
}
if (!self.size()) {
Py_RETURN_NONE;
}
PyObject* key = nullptr;
if (kwnames) {
if (PyTuple_GET_SIZE(kwnames) == 1) {
const char* data = PyUnicode_AsUTF8(PyTuple_GET_ITEM(kwnames, 0));
if (!data) {
return nullptr;
}
if (std::strncmp(data, "key", 3)) {
PyErr_SetString(PyExc_TypeError,
"sort() only takes a \"key\" keyword argument");
return nullptr;
}
key = args[0];
}
else if (PyTuple_GET_SIZE(kwnames) > 1) {
PyErr_SetString(PyExc_TypeError,
"sort() only takes a \"key\" keyword argument");
return nullptr;
}
}
if (key) {
if (detail::sort_with_key(self, key)) {
return nullptr;
}
}
else if (detail::sort_without_key(self)) {
return nullptr;
}
Py_RETURN_NONE;
}
PyMethodDef sort_method = {"sort",
unsafe_cast_to_pycfunction(sort),
JL_FASTCALL_FLAGS,
sort_doc};
PyObject* reduce(PyObject* self, PyObject*) {
PyObject* as_list = PySequence_List(self);
if (!as_list) {
return nullptr;
}
PyObject* out =
Py_BuildValue("(O(O))", reinterpret_cast<PyObject*>(&jlist_type), as_list);
Py_DECREF(as_list);
return out;
}
PyMethodDef reduce_method = {"__reduce__", reduce, METH_NOARGS, nullptr};
PyMethodDef methods[] = {
_from_starargs_method,
_reserve_method,
append_method,
clear_method,
copy_method,
count_method,
extend_method,
index_method,
insert_method,
pop_method,
remove_method,
reverse_method,
sort_method,
reduce_method,
{nullptr, nullptr, 0, nullptr},
};
Py_ssize_t length(PyObject* _self) {
jlist& self = *reinterpret_cast<jlist*>(_self);
return self.size();
}
PyObject* concat(PyObject* self, PyObject* ob) {
PyObject* out = copy(self, nullptr);
if (out) {
jlist& out_ref = *reinterpret_cast<jlist*>(out);
if (detail::extend_helper(out_ref, ob)) {
Py_DECREF(out);
return nullptr;
}
}
return out;
}
PyObject* repeat(PyObject* _self, Py_ssize_t times) {
jlist& self = *reinterpret_cast<jlist*>(_self);
jlist* out = detail::new_jlist(self.tag());
if (!out) {
return nullptr;
}
if (times > 0) {
out->entries.reserve(self.size() * times);
if (self.boxed()) {
for (entry e : self.entries) {
for (Py_ssize_t ix = 0; ix < times; ++ix) {
Py_INCREF(e.as_ob);
}
}
}
if (self.size() == 1) {
out->entries.insert(out->entries.end(), times, self.entries[0]);
}
else {
for (Py_ssize_t ix = 0; ix < times; ++ix) {
out->entries.insert(out->entries.end(),
self.entries.begin(),
self.entries.end());
}
}
}
return reinterpret_cast<PyObject*>(out);
}
PyObject* getitem(PyObject* _self, Py_ssize_t ix) {
jlist& self = *reinterpret_cast<jlist*>(_self);
entry* maybe_e = detail::get_entry(self, ix);
if (!maybe_e) {
PyErr_SetString(PyExc_IndexError, "jlist index out of range");
return nullptr;
}
const entry& e = *maybe_e;
switch (self.tag()) {
case entry_tag::as_homogeneous_ob:
case entry_tag::as_heterogeneous_ob:
Py_INCREF(e.as_ob);
return e.as_ob;
case entry_tag::as_int:
return box_value(e.as_int);
case entry_tag::as_double:
return box_value(e.as_double);
default:
// we don't need to handle entry_tag::unset because that means the
// size is 0 and we will have already returned `nullptr` in the bounds
// check
__builtin_unreachable();
}
}
int setitem(PyObject* _self, Py_ssize_t ix, PyObject* ob) {
jlist& self = *reinterpret_cast<jlist*>(_self);
entry* maybe_e = detail::get_entry(self, ix);
if (!maybe_e) {
PyErr_SetString(PyExc_IndexError, "jlist index out of range");
return -1;
}
if (!ob) {
if (self.boxed()) {
Py_DECREF(maybe_e->as_ob);
}
self.entries.erase(self.entries.begin() + ix);
return 0;
}
if (detail::setitem_helper(self, *maybe_e, ob, true)) {
return -1;
}
return 0;
}
int contains(PyObject* _self, PyObject* ob) {
jlist& self = *reinterpret_cast<jlist*>(_self);
Py_ssize_t ix = detail::index_helper(self, ob);
if (ix == -2) {
return -1;
}
return ix > -1;
}
PyObject* inplace_concat(PyObject* _self, PyObject* ob) {
jlist& self = *reinterpret_cast<jlist*>(_self);
if (detail::extend_helper(self, ob)) {
return nullptr;
}
Py_INCREF(_self);
return _self;
}
PyObject* inplace_repeat(PyObject* _self, Py_ssize_t times) {
jlist& self = *reinterpret_cast<jlist*>(_self);
if (times <= 0) {
detail::clear_helper(self);
}
else {
Py_ssize_t original_size = self.size();
self.entries.reserve(original_size * times);
if (self.boxed()) {
for (entry e : self.entries) {
for (Py_ssize_t ix = 0; ix < times; ++ix) {
Py_INCREF(e.as_ob);
}
}
}
for (Py_ssize_t ix = 1; ix < times; ++ix) {
self.entries.insert(self.entries.end(),
self.entries.begin(),
self.entries.begin() + original_size);
}
}
Py_INCREF(_self);
return _self;
}
PySequenceMethods sq_methods = {
length, // sq_length
concat, // sq_concat
repeat, // sq_repeat
getitem, // sq_item
nullptr, // sq_slice
setitem, // sq_ass_item
nullptr, // sq_ass_slice
contains, // sq_contains
inplace_concat, // sq_inplace_concat
inplace_repeat, // inplace_repeat
};
PyObject* subscript(PyObject* _self, PyObject* item) {
jlist& self = *reinterpret_cast<jlist*>(_self);
if (PyIndex_Check(item)) {
Py_ssize_t ix = PyNumber_AsSsize_t(item, PyExc_IndexError);
if (ix == -1 && PyErr_Occurred()) {
return nullptr;
}
ix = jl::detail::adjust_ix(ix, self.size(), false);
return getitem(_self, ix);
}
else if (!PySlice_Check(item)) {
PyErr_Format(PyExc_TypeError,
"jlist indices must be integers or slices, not %.200s",
item->ob_type->tp_name);
return nullptr;
}
Py_ssize_t start;
Py_ssize_t stop;
Py_ssize_t step;
if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
return nullptr;
}
Py_ssize_t slicelength = PySlice_AdjustIndices(self.size(), &start, &stop, step);
if (slicelength < 0) {
return reinterpret_cast<PyObject*>(detail::new_jlist(entry_tag::unset));
}
else if (step == 1) {
if (start > stop) {
start = stop;
}
return reinterpret_cast<PyObject*>(
detail::new_jlist(self.tag(),
self.entries.begin() + start,
self.entries.begin() + stop));
}
jlist* out = detail::new_jlist(self.tag());
if (!out) {
return nullptr;
}
out->entries.reserve(slicelength);
if (step > 0) {
for (Py_ssize_t ix = start; ix < stop; ix += step) {
out->entries.emplace_back(self.entries[ix]);
}
}
else {
for (Py_ssize_t ix = start; ix > stop; ix += step) {
out->entries.emplace_back(self.entries[ix]);
}
}
if (out->boxed()) {
for (entry e : out->entries) {
Py_INCREF(e.as_ob);
}
}
return reinterpret_cast<PyObject*>(out);
}
void delete_loop_ob(jlist& self,
Py_ssize_t start,
Py_ssize_t stop,
Py_ssize_t step,
Py_ssize_t slicelength) {
std::vector<PyObject*> garbage(slicelength);
std::size_t cur = start;
for (Py_ssize_t ix = 0; cur < static_cast<std::size_t>(stop); cur += step, ++ix) {
Py_ssize_t lim = step - 1;
garbage[ix] = self.entries[cur].as_ob;
if (cur + step >= self.entries.size()) {
lim = self.size() - cur - 1;
}
std::copy_backward(self.entries.begin() + cur + 1,
self.entries.begin() + cur + 1 + lim,
self.entries.begin() + cur - ix + lim);
}
cur = start + slicelength * step;
if (cur < self.entries.size()) {
std::copy_backward(self.entries.begin() + cur,
self.entries.end(),
self.entries.begin() + self.size() - slicelength);
}
self.entries.erase(self.entries.end() - slicelength, self.entries.end());
for (PyObject* p : garbage) {
Py_DECREF(p);
}
}
void delete_loop_prim(jlist& self,
Py_ssize_t start,
Py_ssize_t stop,
Py_ssize_t step,
Py_ssize_t slicelength) {
std::size_t cur = start;
for (Py_ssize_t ix = 0; cur < static_cast<std::size_t>(stop); cur += step, ix++) {
Py_ssize_t lim = step - 1;
if (cur + step >= self.entries.size()) {
lim = self.size() - cur - 1;
}
std::copy_backward(self.entries.begin() + cur + 1,
self.entries.begin() + cur + 1 + lim,
self.entries.begin() + cur - ix + lim);
}
cur = start + slicelength * step;
if (cur < self.entries.size()) {
std::copy_backward(self.entries.begin() + cur,
self.entries.end(),
self.entries.begin() + self.size() - slicelength);
}
self.entries.erase(self.entries.end() - slicelength, self.entries.end());
}
namespace detail {
int delete_slice(jlist& self,
Py_ssize_t start,
Py_ssize_t stop,
Py_ssize_t step,
Py_ssize_t slicelength) {
if (!slicelength) {
return 0;
}
if (step == 1) {
self.entries.erase(self.entries.begin() + start, self.entries.begin() + stop);
if (self.boxed()) {
for (Py_ssize_t ix = start; ix < stop; ix += stop) {
Py_DECREF(self.entries[ix].as_ob);
}
}
}
else {
if (step < 0) {
stop = start + 1;
start = stop + step * (slicelength - 1) - 1;
step = -step;
}
switch (self.tag()) {
case entry_tag::as_homogeneous_ob:
case entry_tag::as_heterogeneous_ob:
delete_loop_ob(self, start, stop, step, slicelength);
break;
case entry_tag::as_int:
case entry_tag::as_double:
delete_loop_prim(self, start, stop, step, slicelength);
break;
default:
__builtin_unreachable();
}
}
return 0;
}
void set_loop_ob(jlist& self, Py_ssize_t start, Py_ssize_t step, jlist& other) {
std::vector<PyObject*> garbage(other.size());
for (Py_ssize_t cur = start, ix = 0; ix < other.size(); cur += step, ix++) {
garbage[ix] = self.entries[cur].as_ob;
entry ins = other.entries[ix];
Py_INCREF(ins.as_ob);
self.entries[cur] = ins;
}
for (PyObject* p : garbage) {
Py_DECREF(p);
}
}
void set_loop_prim(jlist& self, Py_ssize_t start, Py_ssize_t step, jlist& other) {
for (Py_ssize_t cur = start, ix = 0; ix < other.size(); cur += step, ix++) {
entry ins = other.entries[ix];
self.entries[cur] = ins;
}
}
int set_slice(jlist& self,
Py_ssize_t start,
Py_ssize_t step,
Py_ssize_t slicelength,
jlist* other) {
if (&self == other) {
other = new_jlist(self.tag(), self.entries.begin(), self.entries.end());
}
else if (self.size() == 0) {
self.tag(other->tag());
}
else if (other->size() == 0 && slicelength == 0) {
return 0;
}
else if (self.tag() != other->tag()) {
if (maybe_box_values(self)) {
return -1;
}
if (!other->boxed()) {
other = new_jlist(self.tag(), other->entries.begin(), other->entries.end());
if (!other || maybe_box_values(*other)) {
return -1;
}
}
else {
Py_INCREF(other);
}
}
else {
Py_INCREF(other);
}
if (step == 1) {
if (slicelength > other->size()) {
if (self.boxed()) {
for (Py_ssize_t ix = other->size(); ix < slicelength; ++ix) {
Py_DECREF(self.entries[ix].as_ob);
}
}
self.entries.erase(self.entries.begin() + other->size(),
self.entries.begin() + slicelength);
}
else if (slicelength > self.size() || other->size() > slicelength) {
Py_ssize_t count = std::max(slicelength - self.size(),
other->size() - slicelength);
entry e;
if (self.boxed()) {
e.as_ob = Py_None;
for (Py_ssize_t ix = 0; ix < count; ++ix) {
Py_INCREF(Py_None);
}
}
self.entries.insert(self.entries.begin() + start, count, e);
}
}
else if (slicelength != other->size()) {
PyErr_Format(PyExc_ValueError,
"attempt to assign sequence of "
"size %zd to extended slice of "
"size %zd",
other->size(),
slicelength);
return -1;
}
if (other->size() == 0) {
return 0;
}
switch (self.tag()) {
case entry_tag::as_homogeneous_ob:
case entry_tag::as_heterogeneous_ob:
set_loop_ob(self, start, step, *other);
break;
case entry_tag::as_int:
case entry_tag::as_double:
set_loop_prim(self, start, step, *other);
break;
default:
__builtin_unreachable();
}
Py_DECREF(other);
return 0;
}
int set_slice(jlist& self,
Py_ssize_t start,
Py_ssize_t step,
Py_ssize_t slicelength,
PyObject* other) {
jlist* rhs = new_jlist(entry_tag::unset);
if (!rhs) {
return -1;
}
if (extend_helper(*rhs, other)) {
return -1;
}
int out = set_slice(self, start, step, slicelength, rhs);
Py_DECREF(rhs);
return out;
}
} // namespace detail
int set_subscript(PyObject* _self, PyObject* item, PyObject* value) {
jlist& self = *reinterpret_cast<jlist*>(_self);
if (PyIndex_Check(item)) {
Py_ssize_t ix = PyNumber_AsSsize_t(item, PyExc_IndexError);
if (ix == -1 && PyErr_Occurred()) {
return -1;
}
ix = jl::detail::adjust_ix(ix, self.size(), false);
return setitem(_self, ix, value);
}
else if (!PySlice_Check(item)) {
PyErr_Format(PyExc_TypeError,
"jlist indices must be integers or slices, not %.200s",
item->ob_type->tp_name);
return -1;
}
Py_ssize_t start;
Py_ssize_t stop;
Py_ssize_t step;
if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
return -1;
}
Py_ssize_t slicelength = PySlice_AdjustIndices(self.size(), &start, &stop, step);
// Make sure s[5:2] = [..] inserts at the right place: before 5, not before 2.
if ((step < 0 && start < stop) || (step > 0 && start > stop)) {
stop = start;
}
if (!value) {
return detail::delete_slice(self, start, stop, step, slicelength);
}
else if (Py_TYPE(value) == &jlist_type) {
return detail::set_slice(self,
start,
step,
slicelength,
reinterpret_cast<jlist*>(value));
}
return detail::set_slice(self, start, step, slicelength, value);
}
PyMappingMethods as_mapping = {
length, // mp_length
subscript, // mp_subscript
set_subscript, // mp_ass_subscript
};
PyDoc_STRVAR(tag_doc, "The type tag for the sequence.");
PyObject* get_tag(PyObject* _self, void*) {
jlist& self = *reinterpret_cast<jlist*>(_self);
switch (self.tag()) {
case entry_tag::as_homogeneous_ob:
return PyUnicode_FromString("homogeneous_ob");
case entry_tag::as_heterogeneous_ob:
return PyUnicode_FromString("heterogeneous_ob");
case entry_tag::as_int:
return PyUnicode_FromString("int");
case entry_tag::as_double:
return PyUnicode_FromString("double");
case entry_tag::unset:
return PyUnicode_FromString("unset");
default:
__builtin_unreachable();
}
}
PyGetSetDef tag_getset = {const_cast<char*>("tag"), get_tag, nullptr, tag_doc, nullptr};
PyGetSetDef getsets[] = {
tag_getset,
{nullptr, 0, 0, 0, nullptr},
};
int traverse(PyObject* _self, visitproc visit, void* arg) {
jlist& self = *reinterpret_cast<jlist*>(_self);
if (self.boxed()) {
for (entry e : self.entries) {
Py_VISIT(e.as_ob);
}
}
return 0;
}
int gc_clear(PyObject* _self) {
jlist& self = *reinterpret_cast<jlist*>(_self);
detail::clear_helper(self);
return 0;
}
} // namespace methods
namespace iterobject {
struct jlist_iter {
PyObject base;
Py_ssize_t ix;
jlist* list;
};
void deallocate(PyObject* _self) {
jlist_iter& self = *reinterpret_cast<jlist_iter*>(_self);
PyObject_GC_UnTrack(_self);
Py_XDECREF(self.list);
PyObject_GC_Del(_self);
}
PyObject* next(PyObject* _self) {
jlist_iter& self = *reinterpret_cast<jlist_iter*>(_self);
if (!self.list) {
return nullptr;
}
if (self.ix >= self.list->size()) {
Py_CLEAR(self.list);
return nullptr;
}
return methods::getitem(reinterpret_cast<PyObject*>(self.list), self.ix++);
}
PyObject* length(PyObject* _self, PyObject*) {
jlist_iter& self = *reinterpret_cast<jlist_iter*>(_self);
if (!self.list) {
return PyLong_FromSsize_t(0);
}
return PyLong_FromSsize_t(self.list->size() - self.ix);
}
PyMethodDef length_method = {"__length_hint__", length, METH_NOARGS, nullptr};
PyObject* reduce(PyObject* _self, PyObject*) {
jlist_iter& self = *reinterpret_cast<jlist_iter*>(_self);
PyObject* builtins = PyImport_ImportModule("builtins");
if (!builtins) {
return nullptr;
}
PyObject* iter = PyObject_GetAttrString(builtins, "iter");
Py_DECREF(builtins);
if (!iter) {
return nullptr;
}
PyObject* list = reinterpret_cast<PyObject*>(self.list);
if (!list) {
if (!(list = PyList_New(0))) {
return nullptr;
}
}
else {
Py_INCREF(list);
}
PyObject* out = Py_BuildValue("(O(O)n)", iter, list, self.ix);
Py_DECREF(list);
Py_DECREF(iter);
return out;
}
PyMethodDef reduce_method = {"__reduce__", reduce, METH_NOARGS, nullptr};
PyObject* setstate(PyObject* _self, PyObject* _ix) {
jlist_iter& self = *reinterpret_cast<jlist_iter*>(_self);
Py_ssize_t ix = PyNumber_AsSsize_t(_ix, PyExc_TypeError);
if (ix == -1 && PyErr_Occurred()) {
return nullptr;
}
self.ix = ix;
Py_RETURN_NONE;
}
PyMethodDef setstate_method = {"__setstate__", setstate, METH_O, nullptr};
PyMethodDef methods[] = {
length_method,
reduce_method,
setstate_method,
{nullptr, nullptr, 0, nullptr},
};
int traverse(PyObject* _self, visitproc visit, void* arg) {
jlist_iter& self = *reinterpret_cast<jlist_iter*>(_self);
if (self.list) {
Py_VISIT(self.list);
}
return 0;
}
PyTypeObject type = {
// clang-format: off
PyVarObject_HEAD_INIT(&PyType_Type, 0)
// clang-format: on
"jlist.jlist_iterator", // tp_name
sizeof(jlist), // tp_basicsize
0, // tp_itemsize
deallocate, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_reserved
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, // tp_flags
0, // tp_doc
traverse, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
PyObject_SelfIter, // tp_iter
next, // tp_iternext
methods, // tp_methods,
};
} // namespace iterobject
namespace methods {
PyObject* iter(PyObject* _self) {
jlist& self = *reinterpret_cast<jlist*>(_self);
iterobject::jlist_iter* out = PyObject_GC_New(iterobject::jlist_iter,
&iterobject::type);
if (!out) {
return nullptr;
}
Py_INCREF(_self);
out->list = &self;
out->ix = 0;
PyObject_GC_Track(out);
return reinterpret_cast<PyObject*>(out);
}
} // namespace methods
PyTypeObject jlist_type = {
// clang-format: off
PyVarObject_HEAD_INIT(&PyType_Type, 0)
// clang-format: on
"jlist.jlist", // tp_name
sizeof(jlist), // tp_basicsize
0, // tp_itemsize
methods::deallocate, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_reserved
methods::repr, // tp_repr
0, // tp_as_number
&methods::sq_methods, // tp_as_sequence
&methods::as_mapping, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, // tp_flags
0, // tp_doc
methods::traverse, // tp_traverse
methods::gc_clear, // tp_clear
methods::richcompare, // tp_richcompare
0, // tp_weaklistoffset
methods::iter, // tp_iter
0, // tp_iternext
methods::methods, // tp_methods,
0, // tp_members
methods::getsets, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
methods::init, // tp_init
0, // tp_alloc
methods::new_, // tp_new
};
PyModuleDef module = {
PyModuleDef_HEAD_INIT,
"jlist.jlist",
nullptr,
-1,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
};
PyMODINIT_FUNC PyInit_jlist() {
if (PyType_Ready(&jlist_type) < 0) {
return nullptr;
}
if (PyType_Ready(&iterobject::type) < 0) {
return nullptr;
}
PyObject* m = PyModule_Create(&module);
if (!m) {
return nullptr;
}
if (PyObject_SetAttrString(m, "jlist", reinterpret_cast<PyObject*>(&jlist_type))) {
Py_DECREF(m);
return nullptr;
}
return m;
}
} // namespace jl
| 30.507296 | 89 | 0.507414 | [
"object",
"vector"
] |
679bf91a8c75551c7875f5ddb24c543511c5f156 | 77,366 | cpp | C++ | src/chrono_vehicle/wheeled_vehicle/tire/ChPacejkaTire.cpp | IsymtecAi/chrono | 53b05f7586e0fc644ee05f5533a8b88cb81ec5b3 | [
"BSD-3-Clause"
] | null | null | null | src/chrono_vehicle/wheeled_vehicle/tire/ChPacejkaTire.cpp | IsymtecAi/chrono | 53b05f7586e0fc644ee05f5533a8b88cb81ec5b3 | [
"BSD-3-Clause"
] | null | null | null | src/chrono_vehicle/wheeled_vehicle/tire/ChPacejkaTire.cpp | IsymtecAi/chrono | 53b05f7586e0fc644ee05f5533a8b88cb81ec5b3 | [
"BSD-3-Clause"
] | null | null | null | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen, Markus Schmid
// =============================================================================
//
// Base class for a Pacejka type Magic formula 2002 tire model
//
// =============================================================================
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include "chrono/core/ChTimer.h"
#include "chrono/physics/ChGlobal.h"
#include "chrono_vehicle/wheeled_vehicle/tire/ChPacejkaTire.h"
namespace chrono {
namespace vehicle {
// -----------------------------------------------------------------------------
// Static variables
// -----------------------------------------------------------------------------
// Threshold value for small forward tangential velocity.
// static const double v_x_threshold = 0.2;
// large Fz leads to large m_dF_z, leads to large Fx, Fy, etc.
static double Fz_thresh = 30000;
// max reaction threshold
static double Fx_thresh = 20000.0;
static double Fy_thresh = 20000.0;
static double Mx_thresh = Fz_thresh / 20.0;
static double My_thresh = Fx_thresh / 20.0;
static double Mz_thresh = Fz_thresh / 20.0;
static double kappaP_thresh = 0.01;
static double alphaP_thresh = 0.1;
static double gammaP_thresh = 0.05;
static double phiP_thresh = 99;
static double phiT_thresh = 99;
// -----------------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------------
ChPacejkaTire::ChPacejkaTire(const std::string& name, const std::string& pacTire_paramFile)
: ChTire(name),
m_paramFile(pacTire_paramFile),
m_params_defined(false),
m_use_transient_slip(true),
m_use_Fz_override(false),
m_driven(false),
m_mu0(0.8) {}
ChPacejkaTire::ChPacejkaTire(const std::string& name,
const std::string& pacTire_paramFile,
double Fz_override,
bool use_transient_slip)
: ChTire(name),
m_paramFile(pacTire_paramFile),
m_params_defined(false),
m_use_transient_slip(use_transient_slip),
m_use_Fz_override(Fz_override > 0),
m_Fz_override(Fz_override),
m_driven(false),
m_mu0(0.8) {}
// -----------------------------------------------------------------------------
// Destructor
//
// Delete private structures
// -----------------------------------------------------------------------------
ChPacejkaTire::~ChPacejkaTire() {
delete m_slip;
delete m_params;
delete m_pureLong;
delete m_pureLat;
delete m_pureTorque;
delete m_combinedLong;
delete m_combinedLat;
delete m_combinedTorque;
delete m_zeta;
delete m_relaxation;
delete m_bessel;
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// NOTE: no initial conditions passed in at this point, e.g. m_tireState is empty
void ChPacejkaTire::Initialize(std::shared_ptr<ChBody> wheel, VehicleSide side) {
ChTire::Initialize(wheel, side);
// Create private structures
m_slip = new slips;
m_params = new Pac2002_data;
m_pureLong = new pureLongCoefs;
m_pureLat = new pureLatCoefs;
m_pureTorque = new pureTorqueCoefs;
m_combinedLong = new combinedLongCoefs;
m_combinedLat = new combinedLatCoefs;
m_combinedTorque = new combinedTorqueCoefs;
// m_combinedTorque->M_zr = 0;
// m_combinedTorque->M_z_x = 0;
// m_combinedTorque->M_z_y = 0;
m_zeta = new zetaCoefs;
m_relaxation = new relaxationL;
m_bessel = new bessel;
// negative number indicates no steps have been taken yet
m_time_since_last_step = 0;
m_initial_step = false; // have not taken a step at time = 0 yet
m_num_ODE_calls = 0;
m_sum_ODE_time = 0.0;
m_num_Advance_calls = 0;
m_sum_Advance_time = 0.0;
// load all the empirical tire parameters from *.tir file
loadPacTireParamFile();
//// TODO: Need to figure out a better way of indicating errors
//// Right now, we cannot have this function throw an exception since
//// it's called from the constructor! Must fix this...
if (!m_params_defined) {
GetLog() << " couldn't load pacTire parameters from file, not updating initial quantities \n\n";
return;
}
// LEFT or RIGHT side of the vehicle?
if (m_side == LEFT) {
m_sameSide = (!m_params->model.tyreside.compare("LEFT")) ? 1 : -1;
} else {
// on right
m_sameSide = (!m_params->model.tyreside.compare("RIGHT")) ? 1 : -1;
}
// any variables that are calculated once
m_R0 = m_params->dimension.unloaded_radius;
//// TODO: why do we have to initialize m_R_l and m_R_eff here?
//// This is done in Synchronize(), when we have a proper wheel state.
m_R_l = m_R0 - 8000.0 / m_params->vertical.vertical_stiffness;
double qV1 = 1.5;
double rho = (m_R0 - m_R_l) * exp(-qV1 * m_R0 * pow(1.05 * m_params->model.longvl / m_params->model.longvl, 2));
m_R_eff = m_R0 - rho;
// Build the lookup table for penetration depth as function of intersection area
// (used only with the ChTire::ENVELOPE method for terrain-tire collision detection)
ConstructAreaDepthTable(m_R0, m_areaDep);
m_Fz = 0;
m_dF_z = 0;
// spin slip coefficients, unused for now
{
zetaCoefs tmp = {1, 1, 1, 1, 1, 1, 1, 1, 1};
*m_zeta = tmp;
}
m_combinedTorque->alpha_r_eq = 0.0;
m_pureLat->D_y = m_params->vertical.fnomin; // initial approximation
m_C_Fx = 161000; // calibrated, sigma_kappa = sigma_kappa_ref = 1.29
m_C_Fy = 144000; // calibrated, sigma_alpha = sigma_alpha_ref = 0.725
// Initialize all other variables
m_Num_WriteOutData = 0;
zero_slips(); // zeros slips, and some other vars
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ChPacejkaTire::AddVisualizationAssets(VisualizationType vis) {
if (vis == VisualizationType::NONE)
return;
m_cyl_shape = std::make_shared<ChCylinderShape>();
m_cyl_shape->GetCylinderGeometry().rad = GetRadius();
m_cyl_shape->GetCylinderGeometry().p1 = ChVector<>(0, GetVisualizationWidth() / 2, 0);
m_cyl_shape->GetCylinderGeometry().p2 = ChVector<>(0, -GetVisualizationWidth() / 2, 0);
m_wheel->AddAsset(m_cyl_shape);
m_texture = std::make_shared<ChTexture>();
m_texture->SetTextureFilename(GetChronoDataFile("greenwhite.png"));
m_wheel->AddAsset(m_texture);
}
void ChPacejkaTire::RemoveVisualizationAssets() {
// Make sure we only remove the assets added by ChPacejkaTire::AddVisualizationAssets.
// This is important for the ChTire object because a wheel may add its own assets
// to the same body (the spindle/wheel).
{
auto it = std::find(m_wheel->GetAssets().begin(), m_wheel->GetAssets().end(), m_cyl_shape);
if (it != m_wheel->GetAssets().end())
m_wheel->GetAssets().erase(it);
}
{
auto it = std::find(m_wheel->GetAssets().begin(), m_wheel->GetAssets().end(), m_texture);
if (it != m_wheel->GetAssets().end())
m_wheel->GetAssets().erase(it);
}
}
// -----------------------------------------------------------------------------
// Return computed tire forces and moment (pure slip or combined slip and in
// local or global frame). The main GetTireForce() function returns the combined
// slip tire forces, expressed in the global frame.
// -----------------------------------------------------------------------------
TerrainForce ChPacejkaTire::GetTireForce() const {
return GetTireForce_combinedSlip(false);
}
TerrainForce ChPacejkaTire::ReportTireForce(ChTerrain* terrain) const {
return GetTireForce_combinedSlip(false);
}
TerrainForce ChPacejkaTire::GetTireForce_pureSlip(const bool local) const {
if (local)
return m_FM_pure;
// reactions are on wheel CM
TerrainForce m_FM_global;
m_FM_global.point = m_tireState.pos;
// only transform the directions of the forces, moments, from local to global
m_FM_global.force = m_W_frame.TransformDirectionLocalToParent(m_FM_pure.force);
m_FM_global.moment = m_W_frame.TransformDirectionLocalToParent(m_FM_pure.moment);
return m_FM_global;
}
/// Return the reactions for the combined slip EQs, in local or global coordinates
TerrainForce ChPacejkaTire::GetTireForce_combinedSlip(const bool local) const {
if (local)
return m_FM_combined;
// reactions are on wheel CM
TerrainForce m_FM_global;
m_FM_global.point = m_W_frame.pos;
// only transform the directions of the forces, moments, from local to global
m_FM_global.force = m_W_frame.TransformDirectionLocalToParent(m_FM_combined.force);
m_FM_global.moment = m_W_frame.TransformDirectionLocalToParent(m_FM_combined.moment);
return m_FM_global;
}
// -----------------------------------------------------------------------------
// Update the internal state of this tire using the specified wheel state. The
// quantities calculated here will be kept constant until the next call to the
// Synchronize() function.
// -----------------------------------------------------------------------------
void ChPacejkaTire::Synchronize(double time,
const WheelState& state,
const ChTerrain& terrain,
CollisionType collision_type) {
//// TODO: This must be removed from here. A tire with unspecified or
//// incorrect parameters should have been invalidate at initialization.
// Check that input tire model parameters are defined
if (!m_params_defined) {
GetLog() << " ERROR: cannot update tire w/o setting the model parameters first! \n\n\n";
return;
}
// Invoke the base class function.
ChTire::Synchronize(time, state, terrain);
// Cache the wheel state and update the tire coordinate system.
m_tireState = state;
m_simTime = time;
update_W_frame(terrain, collision_type);
// If not using the transient slip model, check that the tangential forward
// velocity is not too small.
ChVector<> V = m_W_frame.TransformDirectionParentToLocal(m_tireState.lin_vel);
if (!m_use_transient_slip && std::abs(V.x()) < 0.1) {
GetLog() << " ERROR: tangential forward velocity below threshold.... \n\n";
return;
}
// keep the last calculated reaction force or moment, to use later
m_FM_pure_last = m_FM_pure;
m_FM_combined_last = m_FM_combined;
// Initialize the output tire forces to ensure that we do not report any tire
// forces if the wheel does not contact the terrain.
m_FM_pure.point = ChVector<>();
m_FM_pure.force = ChVector<>();
m_FM_pure.moment = ChVector<>();
m_FM_combined.point = ChVector<>();
m_FM_combined.force = ChVector<>();
m_FM_combined.moment = ChVector<>();
}
// -----------------------------------------------------------------------------
// Advance the state of this tire by the specified time step. If using the
// transient slip model, perform integration taking as many integration steps
// as needed.
// -----------------------------------------------------------------------------
void ChPacejkaTire::Advance(double step) {
// increment the counter
ChTimer<double> advance_time;
m_num_Advance_calls++;
// Do nothing if the wheel does not contact the terrain. In this case, all
// reported tire forces will be zero. Still have to update slip quantities, since
// displacements won't go to zero immediately
/*
if (!m_in_contact)
{
zero_slips();
return;
}
*/
// If using single point contact model, slips are calculated from compliance
// between tire and contact patch.
if (m_use_transient_slip) {
// 1 of 2 ways to deal with user input time step increment
// 1) ...
// a) step <= m_stepsize, so integrate using input step
// b) step > m_stepsize, use m_stepsize until step <= m_stepsize
double remaining_time = step;
// only count the time take to do actual calculations in Advance time
advance_time.start();
// keep track of the ODE calculation time
ChTimer<double> ODE_timer;
ODE_timer.start();
while (remaining_time > m_stepsize) {
advance_tire(m_stepsize);
remaining_time -= m_stepsize;
}
// take one final step to reach the specified time.
advance_tire(remaining_time);
// stop the timers
ODE_timer.stop();
m_num_ODE_calls++;
m_sum_ODE_time += ODE_timer();
/*
// ... or, 2)
// assume input step is smaller than it has to be. Then, take x steps
// until actually re-calculating reactions.
m_time_since_last_step =+ step;
// enough time has accumulated to do a macro step, OR, it's the first step
if( m_time_since_last_step >= m_stepsize || !m_initial_step)
{
// only count the time take to do actual calculations in Advance time
advance_time.start();
// keep track of the ODE calculation time
ChTimer<double> ODE_timer;
ODE_timer.start();
advance_slip_transient(m_time_since_last_step);
ODE_timer.stop();
// increment the timer, counter
m_num_ODE_calls++;
m_sum_ODE_time += ODE_timer();
m_time_since_last_step = 0;
m_initial_step = true; // 2nd term in if() above will always be false
} else {
return;
}
*/
} else {
// Calculate the vertical load and update tire deflection and rolling radius
update_verticalLoad(step);
// Calculate kinematic slip quantities
slip_kinematic();
}
// Calculate the force and moment reaction, pure slip case
pureSlipReactions();
// Update m_FM_combined.forces, m_FM_combined.moment.z
combinedSlipReactions();
// Update M_x, apply to both m_FM and m_FM_combined
// gamma should already be corrected for L/R side, so need to swap Fy if on opposite side
double Mx = m_sameSide * calc_Mx(m_sameSide * m_FM_combined.force.y(), m_slip->gammaP);
m_FM_pure.moment.x() = Mx;
m_FM_combined.moment.x() = Mx;
// Update M_y, apply to both m_FM and m_FM_combined
// be sure signs ARE THE SAME, else it becomes self-energizing on one side
double My = calc_My(m_FM_combined.force.x());
m_FM_pure.moment.y() = My;
m_FM_combined.moment.y() = My;
// all the reactions have been calculated, stop the advance timer
advance_time.stop();
m_sum_Advance_time += advance_time();
// DEBUGGING
// m_FM_combined.moment.y() = 0;
// m_FM_combined.moment.z() = 0;
// evaluate the reaction forces calculated
evaluate_reactions(false, false);
}
void ChPacejkaTire::advance_tire(double step) {
// Calculate the vertical load and update tire deflection and tire rolling
// radius.
update_verticalLoad(step);
// Calculate kinematic slip quantities, based on specified wheel state. This
// assumes that the inputs to wheel spindle instantly affect tire contact.
// Note: kappaP, alphaP, gammaP may be overridden in Advance
slip_kinematic();
advance_slip_transient(step);
}
// Calculate the tire contact coordinate system.
// TYDEX W-axis system is at the contact point "C", Z-axis normal to the terrain
// and X-axis along the wheel centerline.
// Local frame transforms output forces/moments to global frame, to be applied
// to the wheel body CM.
// Pacejka (2006), Fig 2.3, all forces are calculated at the contact point "C"
void ChPacejkaTire::update_W_frame(const ChTerrain& terrain, CollisionType collision_type) {
// Check contact with terrain, using a disc of radius R0.
ChCoordsys<> contact_frame;
m_mu = terrain.GetCoefficientFriction(m_tireState.pos.x(), m_tireState.pos.y());
double depth;
double dum_cam;
switch (collision_type) {
case CollisionType::SINGLE_POINT:
m_in_contact =
DiscTerrainCollision(terrain, m_tireState.pos, m_tireState.rot.GetYaxis(), m_R0, contact_frame, depth);
break;
case CollisionType::FOUR_POINTS:
m_in_contact = DiscTerrainCollision4pt(terrain, m_tireState.pos, m_tireState.rot.GetYaxis(), m_R0,
m_params->dimension.width, contact_frame, depth, dum_cam);
break;
case CollisionType::ENVELOPE:
m_in_contact = DiscTerrainCollisionEnvelope(terrain, m_tireState.pos, m_tireState.rot.GetYaxis(), m_R0,
m_areaDep, contact_frame, depth);
break;
}
// set the depth if there is contact with terrain
m_depth = (m_in_contact) ? depth : 0;
// Wheel normal (expressed in global frame)
ChVector<> wheel_normal = m_tireState.rot.GetYaxis();
// Terrain normal at wheel center location (expressed in global frame)
ChVector<> Z_dir = terrain.GetNormal(m_tireState.pos.x(), m_tireState.pos.y());
// Longitudinal (heading) and lateral directions, in the terrain plane.
ChVector<> X_dir = Vcross(wheel_normal, Z_dir);
X_dir.Normalize();
ChVector<> Y_dir = Vcross(Z_dir, X_dir);
// Create a rotation matrix from the three unit vectors
ChMatrix33<> rot;
rot.Set_A_axis(X_dir, Y_dir, Z_dir);
// W-Axis system position at the contact point
m_W_frame.pos = contact_frame.pos;
m_W_frame.rot = rot.Get_A_quaternion();
}
// -----------------------------------------------------------------------------
// Calculate the tire vertical load at the current configuration and update the
// tire deflection and tire rolling radius.
// -----------------------------------------------------------------------------
void ChPacejkaTire::update_verticalLoad(double step) {
double Fz;
if (m_use_Fz_override) {
// Vertical load specified as input.
Fz = m_Fz_override;
m_Fz = m_Fz_override;
// Estimate the tire deformation and set the statically loaded radius
// (assuming static loading).
m_R_l = m_R0 - Fz / m_params->vertical.vertical_stiffness;
// In this case, the tire is always assumed to be in contact with the
// terrain.
m_in_contact = true;
} else {
// Calculate the tire vertical load using a spring-damper model. Note that
// this also sets the statically loaded radius m_R_l, as well as the boolean
// flag m_in_contact.
Fz = calc_Fz();
// assert( Fz >= m_params->vertical_force_range.fzmin);
double capped_Fz = 0;
// use the vertical load in the reaction to the wheel, but not in the Magic Formula Eqs
if (Fz > Fz_thresh) {
// large Fz leads to large m_dF_z, leads to large Fx, Fy, etc.
capped_Fz = Fz_thresh;
} else {
capped_Fz = Fz;
}
// damp the change in Fz
m_Fz = capped_Fz; // - delta_Fz_damped;
// if( Fz_damp * delta_Fz_damped > capped_Fz)
// {
// m_Fz = m_params->vertical_force_range.fzmin;
// GetLog() << " \n **** \n the damper on m_Fz should not cause it to go negative !!!! \n\n\n";
// }
}
assert(m_Fz > 0);
// ratio of actual load to nominal
m_dF_z = (m_Fz - m_params->vertical.fnomin) / m_params->vertical.fnomin;
// Calculate tire vertical deflection, rho.
double qV1 = 0.000071; // from example
double K1 = pow(m_tireState.omega * m_R0 / m_params->model.longvl, 2);
double rho = m_R0 - m_R_l + qV1 * m_R0 * K1;
double rho_Fz0 = m_params->vertical.fnomin / (m_params->vertical.vertical_stiffness);
double rho_d = rho / rho_Fz0;
// Calculate tire rolling radius, R_eff. Clamp this value to R0.
m_R_eff = m_R0 + qV1 * m_R0 * K1 -
rho_Fz0 * (m_params->vertical.dreff * std::atan(m_params->vertical.breff * rho_d) +
m_params->vertical.freff * rho_d);
if (m_R_eff > m_R0)
m_R_eff = m_R0;
if (m_in_contact) {
// Load vertical component of tire force
m_FM_pure.force.z() = Fz;
m_FM_combined.force.z() = Fz;
}
}
// NOTE: must
double ChPacejkaTire::calc_Fz() {
// Initialize the statically loaded radius to R0. This is the returned value
// if no vertical force is generated.
m_R_l = m_R0;
if (!m_in_contact)
return m_params->vertical_force_range.fzmin;
// Calculate relative velocity (wheel - terrain) at contact point, in the
// global frame and then express it in the contact frame.
ChVector<> relvel_abs = m_tireState.lin_vel + Vcross(m_tireState.ang_vel, m_W_frame.pos - m_tireState.pos);
ChVector<> relvel_loc = m_W_frame.TransformDirectionParentToLocal(relvel_abs);
// Calculate normal contact force, using a spring-damper model.
// Note: depth is always positive, so the damping should always subtract
double Fz = m_params->vertical.vertical_stiffness * m_depth - m_params->vertical.vertical_damping * relvel_loc.z();
// Adams reference, Fz = Fz(omega, Fx, Fy, gamma, m_depth, relvel_loc.z)
double q_v2 = 2.0; // linear stiffness increase with spin
double q_Fcx = 0.2; // Fx stiffness reduction
double q_Fcy = 0.35; // Fy stiffness reduction
double q_FcG = 0.001; // camber stiffness increase
double C_Fz = m_params->vertical.vertical_damping; // damping
double q_Fz1 = m_params->vertical.vertical_stiffness; // linear stiffness
double q_Fz2 = 500.0; // 2nd order stiffness
// scale the stiffness by considering forces and spin rate
double force_term = 1.0 + q_v2 * std::abs(m_tireState.omega) * m_R0 / m_params->model.longvl -
pow(q_Fcx * m_FM_combined_last.force.x() / m_params->vertical.fnomin, 2) -
pow(q_Fcy * m_FM_combined_last.force.y() / m_params->vertical.fnomin, 2) +
q_FcG * pow(m_slip->gammaP, 2);
double rho_term = q_Fz1 * m_depth + q_Fz2 * pow(m_depth, 2);
// Fz = force_term*rho_term*Fz0 + C_Fz * v_z
double Fz_adams = force_term * rho_term - C_Fz * relvel_loc.z();
// for a 37x12.5 R16.5 Wrangler MT @ 30 psi
// double k1 = 550000.0;
// double k2 = 1e5;
// vertical_damping can be some small percentage of vertical_stiffness (e.g., 2%)
// double c = 0.001 * k1;
// double Fz = k1 * m_depth - c * relvel_loc.z(); // + k2 * pow(m_depth,2);
// if (Fz < m_params->vertical_force_range.fzmin)
if (Fz_adams < m_params->vertical_force_range.fzmin)
return m_params->vertical_force_range.fzmin;
m_R_l = m_R0 - m_depth;
return Fz;
// return Fz_adams;
}
// -----------------------------------------------------------------------------
// Calculate kinematic slip quantities from the current wheel state.
// Note: when not in contact, all slips are assumed zero, but velocities still set
// The wheel state structure contains the following member variables:
// ChVector<> pos; global position
// ChQuaternion<> rot; orientation with respect to global frame
// ChVector<> lin_vel; linear velocity, expressed in the global frame
// ChVector<> ang_vel; angular velocity, expressed in the global frame
// double omega; wheel angular speed about its rotation axis
// -----------------------------------------------------------------------------
void ChPacejkaTire::slip_kinematic() {
// Express the wheel velocity in the tire coordinate system and calculate the
// slip angle alpha. (Override V.x if too small)
ChVector<> V = m_W_frame.TransformDirectionParentToLocal(m_tireState.lin_vel);
// regardless of contact
m_slip->V_cx = V.x(); // tire center x-vel, tire c-sys
m_slip->V_cy = V.y(); // tire center y-vel, tire c-sys
if (m_in_contact) {
m_slip->V_sx = V.x() - m_tireState.omega * m_R_eff; // x-slip vel, tire c-sys
m_slip->V_sy = V.y(); // approx.
// ensure V_x is not too small, else scale V_x to the threshold
if (std::abs(V.x()) < m_params->model.vxlow) {
V.x() = (V.x() < 0) ? -m_params->model.vxlow : m_params->model.vxlow;
}
double V_x_abs = std::abs(V.x());
// lateral slip angle, in the range: (-pi/2 ,pi/2)
double alpha = std::atan(V.y() / V_x_abs);
// Express the wheel normal in the tire coordinate system and calculate the
// wheel camber angle gamma.
ChVector<> n = m_W_frame.TransformDirectionParentToLocal(m_tireState.rot.GetYaxis());
double gamma = std::atan2(n.z(), n.y());
double kappa = -m_slip->V_sx / V_x_abs;
// alpha_star = tan(alpha) = v_y / v_x
double alpha_star = m_slip->V_sy / V_x_abs;
// Set the struct data members, input slips to wheel
m_slip->kappa = kappa;
m_slip->alpha = alpha;
m_slip->alpha_star = alpha_star;
m_slip->gamma = gamma;
// Express the wheel angular velocity in the tire coordinate system and
// extract the turn slip velocity, psi_dot
ChVector<> w = m_W_frame.TransformDirectionParentToLocal(m_tireState.ang_vel);
m_slip->psi_dot = w.z();
// For aligning torque, to handle large slips, and backwards operation
double V_mag = std::sqrt(V.x() * V.x() + V.y() * V.y());
m_slip->cosPrime_alpha = V.x() / V_mag;
// Finally, if non-transient, use wheel slips as input to Magic Formula.
// These get over-written if enable transient slips to be calculated
m_slip->kappaP = kappa;
m_slip->alphaP = alpha_star;
m_slip->gammaP = std::sin(gamma);
} else {
// not in contact, set input slips to 0
m_slip->V_sx = 0;
m_slip->V_sy = 0;
m_slip->kappa = 0;
m_slip->alpha = 0;
m_slip->alpha_star = 0;
m_slip->gamma = 0;
// further, set the slips used in the MF eqs. to zero
m_slip->kappaP = 0;
m_slip->alphaP = 0;
m_slip->gammaP = 0;
// slip velocities should likely be zero also
m_slip->cosPrime_alpha = 1;
// Express the wheel angular velocity in the tire coordinate system and
// extract the turn slip velocity, psi_dot
ChVector<> w = m_W_frame.TransformDirectionParentToLocal(m_tireState.ang_vel);
m_slip->psi_dot = w.z();
}
}
void ChPacejkaTire::zero_slips() {
// reset relevant slip variables here
slips zero_slip = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
*m_slip = zero_slip;
}
// -----------------------------------------------------------------------------
// Calculate transient slip properties, using first order ODEs to find slip
// displacements from velocities.
// -----------------------------------------------------------------------------
void ChPacejkaTire::advance_slip_transient(double step_size) {
// hard-coded, for now
double EPS_GAMMA = 0.6;
// update relaxation lengths
relaxationLengths();
// local c-sys velocities
double V_cx = m_slip->V_cx;
double V_cx_abs = std::abs(V_cx);
double V_cx_low = 2.5; // cut-off for low velocity zone
double V_sx = m_slip->V_sx;
double V_sy = m_slip->V_sy * m_sameSide; // due to asymmetry about centerline
double gamma = m_slip->gamma * m_sameSide; // due to asymmetry
// see if low velocity considerations should be made
double alpha_sl = std::abs(3.0 * m_pureLat->D_y / m_relaxation->C_Falpha);
// Eq. 7.25 from Pacejka (2006), solve du_dt and dvalpha_dt
if ((std::abs(m_combinedTorque->alpha_r_eq) > alpha_sl) && (V_cx_abs < V_cx_low)) {
// Eq. 7.9, else du/dt = 0 and u remains unchanged
if ((V_sx + V_cx_abs * m_slip->u / m_relaxation->sigma_kappa) * m_slip->u >= 0) {
// solve the ODE using RK - 45 integration
m_slip->Idu_dt = ODE_RK_uv(V_sx, m_relaxation->sigma_kappa, V_cx, step_size, m_slip->u);
m_slip->u += m_slip->Idu_dt;
} else {
m_slip->Idu_dt = 0;
}
// Eq. 7.7, else dv/dt = 0 and v remains unchanged
if ((V_sy + std::abs(V_cx) * m_slip->v_alpha / m_relaxation->sigma_alpha) * m_slip->v_alpha >= 0) {
m_slip->Idv_alpha_dt = ODE_RK_uv(V_sy, m_relaxation->sigma_alpha, V_cx, step_size, m_slip->v_alpha);
m_slip->v_alpha += m_slip->Idv_alpha_dt;
} else {
m_slip->Idv_alpha_dt = 0;
}
} else {
// don't check for du/dt =0 or dv/dt = 0
// Eq 7.9
m_slip->Idu_dt = ODE_RK_uv(V_sx, m_relaxation->sigma_kappa, V_cx, step_size, m_slip->u);
m_slip->u += m_slip->Idu_dt;
// Eq. 7.7
m_slip->Idv_alpha_dt = ODE_RK_uv(V_sy, m_relaxation->sigma_alpha, V_cx, step_size, m_slip->v_alpha);
m_slip->v_alpha += m_slip->Idv_alpha_dt;
}
// Eq. 7.11, lateral force from wheel camber
m_slip->Idv_gamma_dt = ODE_RK_gamma(m_relaxation->C_Fgamma, m_relaxation->C_Falpha, m_relaxation->sigma_alpha, V_cx,
step_size, gamma, m_slip->v_gamma);
m_slip->v_gamma += m_slip->Idv_gamma_dt;
// Eq. 7.12, total spin, phi, including slip and camber
m_slip->Idv_phi_dt =
ODE_RK_phi(m_relaxation->C_Fphi, m_relaxation->C_Falpha, V_cx, m_slip->psi_dot, m_tireState.omega, gamma,
m_relaxation->sigma_alpha, m_slip->v_phi, EPS_GAMMA, step_size);
m_slip->v_phi += m_slip->Idv_phi_dt;
// calculate slips from contact point deflections u and v
slip_from_uv(m_in_contact, 600.0, 100.0, 2.0);
}
// don't have to call this each advance_tire(), but once per macro-step (at least)
void ChPacejkaTire::evaluate_slips() {
if (std::abs(m_slip->kappaP) > kappaP_thresh) {
GetLog() << "\n ~~~~~~~~~ kappaP exceeded threshold:, tire " << m_name << ", = " << m_slip->kappaP << "\n";
}
if (std::abs(m_slip->alphaP) > alphaP_thresh) {
GetLog() << "\n ~~~~~~~~~ alphaP exceeded threshold:, tire " << m_name << ", = " << m_slip->alphaP << "\n";
}
if (std::abs(m_slip->gammaP) > gammaP_thresh) {
GetLog() << "\n ~~~~~~~~~ gammaP exceeded threshold:, tire " << m_name << ", = " << m_slip->gammaP << "\n";
}
if (std::abs(m_slip->phiP) > phiP_thresh) {
GetLog() << "\n ~~~~~~~~~ phiP exceeded threshold:, tire " << m_name << ", = " << m_slip->phiP << "\n";
}
if (std::abs(m_slip->phiT) > phiT_thresh) {
GetLog() << "\n ~~~~~~~~~ phiT exceeded threshold:, tire " << m_name << ", = " << m_slip->phiT << "\n";
}
}
// after calculating all the reactions, evaluate output for any fishy business
void ChPacejkaTire::evaluate_reactions(bool write_violations, bool enforce_threshold) {
// any thresholds exceeded? then print some details about slip state
bool output_slip_to_console = false;
if (std::abs(m_FM_combined.force.x()) > Fx_thresh) {
output_slip_to_console = true;
if (enforce_threshold)
m_FM_combined.force.x() = m_FM_combined.force.x() * (Fx_thresh / std::abs(m_FM_combined.force.x()));
}
if (std::abs(m_FM_combined.force.y()) > Fy_thresh) {
output_slip_to_console = true;
if (enforce_threshold)
m_FM_combined.force.y() = m_FM_combined.force.y() * (Fy_thresh / std::abs(m_FM_combined.force.y()));
}
// m_Fz, the Fz input to the tire model, must be limited based on the Fz_threshold
// e.g., should never need t;his
if (std::abs(m_Fz) > Fz_thresh) {
////GetLog() << "\n *** !!! *** Fz exceeded threshold:, tire " << m_name << ", = " << m_Fz << "\n";
output_slip_to_console = true;
}
if (std::abs(m_FM_combined.moment.x()) > Mx_thresh) {
if (enforce_threshold)
m_FM_combined.moment.x() = m_FM_combined.moment.x() * (Mx_thresh / std::abs(m_FM_combined.moment.x()));
output_slip_to_console = true;
}
if (std::abs(m_FM_combined.moment.y()) > My_thresh) {
if (enforce_threshold)
m_FM_combined.moment.y() = m_FM_combined.moment.y() * (My_thresh / std::abs(m_FM_combined.moment.y()));
output_slip_to_console = true;
}
if (std::abs(m_FM_combined.moment.z()) > Mz_thresh) {
if (enforce_threshold)
m_FM_combined.moment.z() = m_FM_combined.moment.z() * (Mz_thresh / std::abs(m_FM_combined.moment.z()));
////GetLog() << " *** !!! *** Mz exceeded threshold, tire " << m_name << ", = " << m_FM_combined.moment.z()
//// << "\n";
output_slip_to_console = true;
}
if (write_violations) {
GetLog() << " *********** time = " << m_simTime << ", slip data: \n(u,v_alpha,v_gamma) = " << m_slip->u
<< ", " << m_slip->v_alpha << ", " << m_slip->v_gamma << "\n velocity, center (x,y) = " << m_slip->V_cx
<< ", " << m_slip->V_cy << "\n velocity, slip (x,y) = " << m_slip->V_sx << ", " << m_slip->V_sy
<< "\n\n";
}
}
// these are both for the linear case, small alpha
double ChPacejkaTire::ODE_RK_uv(double V_s, double sigma, double V_cx, double step_size, double x_curr) {
double V_cx_abs = std::abs(V_cx);
double k1 = -V_s - (V_cx_abs / sigma) * x_curr;
double k2 = -V_s - (V_cx_abs / sigma) * (x_curr + 0.5 * step_size * k1);
double k3 = -V_s - (V_cx_abs / sigma) * (x_curr + 0.5 * step_size * k2);
double k4 = -V_s - (V_cx_abs / sigma) * (x_curr + step_size * k3);
double delta_x = (step_size / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4);
return delta_x;
}
double ChPacejkaTire::get_dFy_dtan_alphaP(double x_curr) {
// I suppose I could do a diff(Fx_c, alphaP) w/ a symbolic toolkit.
// for now, just use forward differencing
double dx = 0.01; // x_curr is tan(alpha'), range (-1,1) over x < (-pi/2,pi/2)
// changing tan(alpha') has no effect on kappa', gamma'
double Fy_x_dx = Fy_combined(m_slip->alphaP + dx, m_slip->gammaP, m_slip->kappaP, m_FM_combined.force.y());
// dFy_dx = (f(x+dx) - f(x)) / dx
double d_Fy = Fy_x_dx - m_FM_combined.force.y();
return d_Fy / dx;
}
// non-linear model, just use alphaP = alpha'
// small alpha, use Eq. 7.37
// here, we integrate d[tan(alphaP)]/dt for the step size
// returns delta_v_alpha = delta_tan_alphaP * sigma_a
double ChPacejkaTire::ODE_RK_kappaAlpha(double V_s, double sigma, double V_cx, double step_size, double x_curr) {
double V_cx_abs = std::abs(V_cx);
// double sigma_alpha = get_dFy_dtan_alphaP(x_curr) / C_Fy;
double k1 = (-V_s - V_cx_abs * x_curr) / sigma;
double k2 = (-V_s - V_cx_abs * (x_curr + 0.5 * step_size * k1)) / sigma;
double k3 = (-V_s - V_cx_abs * (x_curr + 0.5 * step_size * k2)) / sigma;
double k4 = (-V_s - V_cx_abs * (x_curr + step_size * k3)) / sigma;
double delta_x = (step_size / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4);
return delta_x;
}
double ChPacejkaTire::ODE_RK_gamma(double C_Fgamma,
double C_Falpha,
double sigma_alpha,
double V_cx,
double step_size,
double gamma,
double v_gamma) {
double V_cx_abs = std::abs(V_cx);
double g0 = C_Fgamma / C_Falpha * V_cx_abs * gamma;
double g1 = V_cx_abs / sigma_alpha;
double k1 = g0 - g1 * v_gamma;
double k2 = g0 - g1 * (v_gamma + 0.5 * step_size * k1);
double k3 = g0 - g1 * (v_gamma + 0.5 * step_size * k2);
double k4 = g0 - g1 * (v_gamma + step_size * k3);
double delta_g = (step_size / 6.0) * (k1 + 2 * k2 + 2 * k3 + k4);
return delta_g;
}
double ChPacejkaTire::ODE_RK_phi(double C_Fphi,
double C_Falpha,
double V_cx,
double psi_dot,
double omega,
double gamma,
double sigma_alpha,
double v_phi,
double eps_gamma,
double step_size) {
int sign_Vcx = 0;
if (V_cx < 0)
sign_Vcx = -1;
else
sign_Vcx = 1;
double p0 = (C_Fphi / C_Falpha) * sign_Vcx * (psi_dot - (1.0 - eps_gamma) * omega * std::sin(gamma));
double p1 = (1.0 / sigma_alpha) * std::abs(V_cx);
double k1 = -p0 - p1 * v_phi;
double k2 = -p0 - p1 * (v_phi + 0.5 * step_size * k1);
double k3 = -p0 - p1 * (v_phi + 0.5 * step_size * k2);
double k4 = -p0 - p1 * (v_phi + step_size * k3);
double delta_phi = (step_size / 6.0) * (k1 + 2 * k2 + 2 * k3 + k4);
return delta_phi;
}
void ChPacejkaTire::slip_from_uv(bool use_besselink, double bessel_Cx, double bessel_Cy, double V_low) {
// separate long and lateral damping components
double d_Vxlow = 0;
double d_Vylow = 0;
double V_cx_abs = std::abs(m_slip->V_cx);
// damp gradually to zero velocity at low velocity
if (V_cx_abs <= V_low && use_besselink) {
// d_vlow = bessel_c * (1.0 + std::cos(CH_C_PI * V_cx_abs / V_low));
// damp between C * (2, 1) for V_cx (0,V_low)
d_Vxlow = bessel_Cx * (1.0 + std::cos(CH_C_PI * V_cx_abs / 2.0 * V_low));
d_Vylow = bessel_Cy * (1.0 + std::cos(CH_C_PI * V_cx_abs / 2.0 * V_low));
} else {
// also damp if not a driven wheel (can linger around slip = 0)
// if(!m_driven && use_besselink)
{
d_Vxlow = bessel_Cx * (std::exp(-(V_cx_abs - V_low) / m_params->model.longvl));
d_Vylow = bessel_Cy * (std::exp(-(V_cx_abs - V_low) / m_params->model.longvl));
}
}
// Besselink is RH term in kappa_p, alpha_p
double u_sigma = m_slip->u / m_relaxation->sigma_kappa;
double u_Bessel = d_Vxlow * m_slip->V_sx / m_relaxation->C_Fkappa;
// either u_Bessel or u_tow should be zero (or both)
double kappa_p = u_sigma - u_Bessel;
// don't allow damping to switch sign of kappa, clamp to zero
if (u_sigma * kappa_p < 0)
kappa_p = 0;
// tan(alpha') ~= alpha' for small slip
double v_sigma = -m_slip->v_alpha / m_relaxation->sigma_alpha;
// double v_sigma = std::atan(m_slip->v_alpha / m_relaxation->sigma_alpha);
double v_Bessel = -d_Vylow * m_slip->V_sy * m_sameSide / m_relaxation->C_Falpha;
double alpha_p = v_sigma - v_Bessel; // - v_tow;
// don't allow damping to switch sign of alpha
if (v_sigma * alpha_p < 0)
alpha_p = 0;
// gammaP, phiP, phiT not effected by Besselink
double gamma_p = m_relaxation->C_Falpha * m_slip->v_gamma / (m_relaxation->C_Fgamma * m_relaxation->sigma_alpha);
double phi_p =
(m_relaxation->C_Falpha * m_slip->v_phi) / (m_relaxation->C_Fphi * m_relaxation->sigma_alpha); // turn slip
double phi_t = -m_slip->psi_dot / m_slip->V_cx; // for turn slip
// set transient slips
m_slip->alphaP = alpha_p;
m_slip->kappaP = kappa_p;
m_slip->gammaP = gamma_p;
m_slip->phiP = phi_p;
m_slip->phiT = phi_t;
bessel tmp = {u_Bessel, u_sigma, v_Bessel, v_sigma};
*m_bessel = tmp;
}
// -----------------------------------------------------------------------------
// Calculate tire reactions.
// -----------------------------------------------------------------------------
// pure slip reactions, if the tire is in contact with the ground, in the TYDEX W-Axis system.
// calcFx alphaP ~= 0
// calcFy and calcMz kappaP ~= 0
// NOTE: alphaP, gammaP and kappaP defined with respect to tire side specified from *.tir input file.
// e.g., positive alpha = turn wheel toward vehicle centerline
// e.g., positive gamma = wheel vertical axis top pointing toward vehicle center
void ChPacejkaTire::pureSlipReactions() {
if (!m_in_contact)
return;
double mu_scale = m_mu / m_mu0;
// calculate Fx, pure long. slip condition
m_FM_pure.force.x() = mu_scale * Fx_pureLong(m_slip->gammaP, m_slip->kappaP);
// calc. Fy, pure lateral slip.
m_FM_pure.force.y() = m_sameSide * mu_scale * Fy_pureLat(m_slip->alphaP, m_slip->gammaP);
// calc Mz, pure lateral slip. Negative y-input force, and also the output Mz.
m_FM_pure.moment.z() = m_sameSide * Mz_pureLat(m_slip->alphaP, m_slip->gammaP, m_sameSide * m_FM_pure.force.y());
}
// combined slip reactions, if the tire is in contact with the ground
// MUST call pureSlipReactions() first, as these functions rely on intermediate values
// NOTE: alphaP and gammaP have already been modified for being on the L/R side
// e.g., positive alpha = turn wheel toward vehicle centerline
// e.g., positive gamma = wheel vertical axis top pointing toward vehicle center
void ChPacejkaTire::combinedSlipReactions() {
if (!m_in_contact)
return;
// calculate Fx for combined slip
m_FM_combined.force.x() = Fx_combined(m_slip->alphaP, m_slip->gammaP, m_slip->kappaP, m_FM_pure.force.x());
// calc Fy for combined slip.
m_FM_combined.force.y() =
m_sameSide * Fy_combined(m_slip->alphaP, m_slip->gammaP, m_slip->kappaP, m_sameSide * m_FM_pure.force.y());
// calc Mz for combined slip
m_FM_combined.moment.z() =
m_sameSide * Mz_combined(m_pureTorque->alpha_r, m_pureTorque->alpha_t, m_slip->gammaP, m_slip->kappaP,
m_FM_combined.force.x(), m_sameSide * m_FM_combined.force.y());
}
void ChPacejkaTire::relaxationLengths() {
double p_Ky4 = 2; // according to Pac2002 model
double p_Ky5 = 0;
double p_Ky6 = 2.5; // 0.92;
double p_Ky7 = 0.24;
// NOTE: C_Falpha is positive according to Pacejka, negative in Pac2002.
// Positive stiffness makes sense, so ensure all these are positive
double C_Falpha =
std::abs(m_params->lateral.pky1 * m_params->vertical.fnomin *
std::sin(p_Ky4 * std::atan(m_Fz / (m_params->lateral.pky2 * m_params->vertical.fnomin))) * m_zeta->z3 *
m_params->scaling.lyka);
double sigma_alpha = C_Falpha / m_C_Fy;
double C_Fkappa = m_Fz * (m_params->longitudinal.pkx1 + m_params->longitudinal.pkx2 * m_dF_z) *
exp(m_params->longitudinal.pkx3 * m_dF_z) * m_params->scaling.lky;
double sigma_kappa = C_Fkappa / m_C_Fx;
double C_Fgamma = m_Fz * (p_Ky6 + p_Ky7 * m_dF_z) * m_params->scaling.lgay;
double C_Fphi = 2.0 * (C_Fgamma * m_R0);
assert(C_Falpha > 0);
assert(sigma_alpha > 0);
assert(C_Fkappa > 0);
assert(sigma_kappa > 0);
assert(C_Fgamma > 0);
assert(C_Fphi > 0);
// NOTE: reference does not include the negative in the exponent for sigma_kappa_ref
// double sigma_kappa_ref = m_Fz * (m_params->longitudinal.ptx1 + m_params->longitudinal.ptx2 *
// m_dF_z)*(m_R0*m_params->scaling.lsgkp / m_params->vertical.fnomin) * exp( -m_params->longitudinal.ptx3 * m_dF_z);
// double sigma_alpha_ref = m_params->lateral.pty1 * (1.0 - m_params->lateral.pky3 * std::abs( m_slip->gammaP ) ) *
// m_R0 * m_params->scaling.lsgal * sin(p_Ky4 * atan(m_Fz / (m_params->lateral.pty2 * m_params->vertical.fnomin) )
// );
{
relaxationL tmp = {C_Falpha, sigma_alpha, C_Fkappa, sigma_kappa, C_Fgamma, C_Fphi};
*m_relaxation = tmp;
}
}
double ChPacejkaTire::Fx_pureLong(double gamma, double kappa) {
// double eps_Vx = 0.6;
double eps_x = 0;
// Fx, pure long slip
double S_Hx = (m_params->longitudinal.phx1 + m_params->longitudinal.phx2 * m_dF_z) * m_params->scaling.lhx;
double kappa_x = kappa + S_Hx; // * 0.1;
double mu_x = (m_params->longitudinal.pdx1 + m_params->longitudinal.pdx2 * m_dF_z) *
(1.0 - m_params->longitudinal.pdx3 * pow(gamma, 2)) * m_params->scaling.lmux; // >0
double K_x = m_Fz * (m_params->longitudinal.pkx1 + m_params->longitudinal.pkx2 * m_dF_z) *
exp(m_params->longitudinal.pkx3 * m_dF_z) * m_params->scaling.lkx;
double C_x = m_params->longitudinal.pcx1 * m_params->scaling.lcx; // >0
double D_x = mu_x * m_Fz * m_zeta->z1; // >0
double B_x = K_x / (C_x * D_x + eps_x);
double sign_kap = (kappa_x >= 0) ? 1 : -1;
double E_x = (m_params->longitudinal.pex1 + m_params->longitudinal.pex2 * m_dF_z +
m_params->longitudinal.pex3 * pow(m_dF_z, 2)) *
(1.0 - m_params->longitudinal.pex4 * sign_kap) * m_params->scaling.lex;
double S_Vx = m_Fz * (m_params->longitudinal.pvx1 + m_params->longitudinal.pvx2 * m_dF_z) * m_params->scaling.lvx *
m_params->scaling.lmux * m_zeta->z1;
double F_x =
D_x * std::sin(C_x * std::atan(B_x * kappa_x - E_x * (B_x * kappa_x - std::atan(B_x * kappa_x)))) - S_Vx;
// hold onto these coefs
{
pureLongCoefs tmp = {S_Hx, kappa_x, mu_x, K_x, B_x, C_x, D_x, E_x, F_x, S_Vx};
*m_pureLong = tmp;
}
return F_x;
}
double ChPacejkaTire::Fy_pureLat(double alpha, double gamma) {
double C_y = m_params->lateral.pcy1 * m_params->scaling.lcy; // > 0
double mu_y = (m_params->lateral.pdy1 + m_params->lateral.pdy2 * m_dF_z) *
(1.0 - m_params->lateral.pdy3 * pow(gamma, 2)) * m_params->scaling.lmuy; // > 0
double D_y = mu_y * m_Fz * m_zeta->z2;
// doesn't make sense to ever have K_y be negative (it can be interpreted as lateral stiffness)
double K_y = m_params->lateral.pky1 * m_params->vertical.fnomin *
std::sin(2.0 * std::atan(m_Fz / (m_params->lateral.pky2 * m_params->vertical.fnomin))) *
(1.0 - m_params->lateral.pky3 * std::abs(gamma)) * m_zeta->z3 * m_params->scaling.lyka;
double B_y = K_y / (C_y * D_y);
// double S_Hy = (m_params->lateral.phy1 + m_params->lateral.phy2 * m_dF_z) * m_params->scaling.lhy + (K_yGamma_0 *
// m_slip->gammaP - S_VyGamma) * m_zeta->z0 / (K_yAlpha + 0.1) + m_zeta->z4 - 1.0;
// Adams S_Hy is a bit different
double S_Hy = (m_params->lateral.phy1 + m_params->lateral.phy2 * m_dF_z) * m_params->scaling.lhy +
(m_params->lateral.phy3 * gamma * m_zeta->z0) + m_zeta->z4 - 1;
double alpha_y = alpha + S_Hy;
int sign_alpha = (alpha_y >= 0) ? 1 : -1;
double E_y = (m_params->lateral.pey1 + m_params->lateral.pey2 * m_dF_z) *
(1.0 - (m_params->lateral.pey3 + m_params->lateral.pey4 * gamma) * sign_alpha) *
m_params->scaling.ley; // + p_Ey5 * pow(gamma,2)
double S_Vy = m_Fz * ((m_params->lateral.pvy1 + m_params->lateral.pvy2 * m_dF_z) * m_params->scaling.lvy +
(m_params->lateral.pvy3 + m_params->lateral.pvy4 * m_dF_z) * gamma) *
m_params->scaling.lmuy * m_zeta->z2;
double F_y =
D_y * std::sin(C_y * std::atan(B_y * alpha_y - E_y * (B_y * alpha_y - std::atan(B_y * alpha_y)))) + S_Vy;
// hold onto coefs
{
pureLatCoefs tmp = {S_Hy, alpha_y, mu_y, K_y, S_Vy, B_y, C_y, D_y, E_y};
*m_pureLat = tmp;
}
return F_y;
}
double ChPacejkaTire::Mz_pureLat(double alpha, double gamma, double Fy_pureSlip) {
// some constants
int sign_Vx = (m_slip->V_cx >= 0) ? 1 : -1;
double S_Hf = m_pureLat->S_Hy + m_pureLat->S_Vy / m_pureLat->K_y;
double alpha_r = alpha + S_Hf;
double S_Ht = m_params->aligning.qhz1 + m_params->aligning.qhz2 * m_dF_z +
(m_params->aligning.qhz3 + m_params->aligning.qhz4 * m_dF_z) * gamma;
double alpha_t = alpha + S_Ht;
double B_r = (m_params->aligning.qbz9 * (m_params->scaling.lky / m_params->scaling.lmuy) +
m_params->aligning.qbz10 * m_pureLat->B_y * m_pureLat->C_y) *
m_zeta->z6;
double C_r = m_zeta->z7;
// no terms (Dz10, Dz11) for gamma^2 term seen in Pacejka
// double D_r = m_Fz*m_R0 * ((m_params->aligning.qdz6 + m_params->aligning.qdz7 *
// m_dF_z)*m_params->scaling.lres*m_zeta->z2 + (m_params->aligning.qdz8 + m_params->aligning.qdz9 *
// m_dF_z)*gamma*m_params->scaling.lgaz*m_zeta->z0) * m_slip->cosPrime_alpha*m_params->scaling.lmuy*sign_Vx +
// m_zeta->z8 - 1.0;
// reference
double D_r = m_Fz * m_R0 * ((m_params->aligning.qdz6 + m_params->aligning.qdz7 * m_dF_z) * m_params->scaling.lres +
(m_params->aligning.qdz8 + m_params->aligning.qdz9 * m_dF_z) * gamma) *
m_params->scaling.lmuy * m_slip->cosPrime_alpha * sign_Vx +
m_zeta->z8 - 1.0;
// qbz4 is not in Pacejka
double B_t =
(m_params->aligning.qbz1 + m_params->aligning.qbz2 * m_dF_z + m_params->aligning.qbz3 * pow(m_dF_z, 2)) *
(1.0 + m_params->aligning.qbz4 * gamma + m_params->aligning.qbz5 * std::abs(gamma)) * m_params->scaling.lvyka /
m_params->scaling.lmuy;
double C_t = m_params->aligning.qcz1;
double D_t0 = m_Fz * (m_R0 / m_params->vertical.fnomin) *
(m_params->aligning.qdz1 + m_params->aligning.qdz2 * m_dF_z) * sign_Vx;
// no abs on qdz3 gamma in reference
double D_t = D_t0 * (1.0 + m_params->aligning.qdz3 * std::abs(gamma) + m_params->aligning.qdz4 * pow(gamma, 2)) *
m_zeta->z5 * m_params->scaling.ltr;
double E_t =
(m_params->aligning.qez1 + m_params->aligning.qez2 * m_dF_z + m_params->aligning.qez3 * pow(m_dF_z, 2)) *
(1.0 +
(m_params->aligning.qez4 + m_params->aligning.qez5 * gamma) * (2.0 / chrono::CH_C_PI) *
std::atan(B_t * C_t * alpha_t));
double t = D_t * std::cos(C_t * std::atan(B_t * alpha_t - E_t * (B_t * alpha_t - std::atan(B_t * alpha_t)))) *
m_slip->cosPrime_alpha;
double MP_z = -t * Fy_pureSlip;
double M_zr = D_r * std::cos(C_r * std::atan(B_r * alpha_r)); // this is in the D_r term: * m_slip->cosPrime_alpha;
double M_z = MP_z + M_zr;
// hold onto coefs
{
pureTorqueCoefs tmp = {
S_Hf, alpha_r, S_Ht, alpha_t, m_slip->cosPrime_alpha, m_pureLat->K_y, B_r, C_r, D_r, B_t, C_t, D_t0, D_t,
E_t, t, MP_z, M_zr};
*m_pureTorque = tmp;
}
return M_z;
}
double ChPacejkaTire::Fx_combined(double alpha, double gamma, double kappa, double Fx_pureSlip) {
double rbx3 = 1.0;
double S_HxAlpha = m_params->longitudinal.rhx1;
double alpha_S = alpha + S_HxAlpha;
double B_xAlpha = (m_params->longitudinal.rbx1 + rbx3 * pow(gamma, 2)) *
std::cos(std::atan(m_params->longitudinal.rbx2 * kappa)) * m_params->scaling.lxal;
double C_xAlpha = m_params->longitudinal.rcx1;
double E_xAlpha = m_params->longitudinal.rex1 + m_params->longitudinal.rex2 * m_dF_z;
// double G_xAlpha0 = std::cos(C_xAlpha * std::atan(B_xAlpha * S_HxAlpha - E_xAlpha * (B_xAlpha * S_HxAlpha -
// std::atan(B_xAlpha * S_HxAlpha)) ) );
double G_xAlpha0 =
std::cos(C_xAlpha *
std::atan(B_xAlpha * S_HxAlpha - E_xAlpha * (B_xAlpha * S_HxAlpha - std::atan(B_xAlpha * S_HxAlpha))));
// double G_xAlpha = std::cos(C_xAlpha * std::atan(B_xAlpha * alpha_S - E_xAlpha * (B_xAlpha * alpha_S -
// std::atan(B_xAlpha * alpha_S)) ) ) / G_xAlpha0;
double G_xAlpha = std::cos(C_xAlpha * std::atan(B_xAlpha * alpha_S -
E_xAlpha * (B_xAlpha * alpha_S - std::atan(B_xAlpha * alpha_S)))) /
G_xAlpha0;
double F_x = G_xAlpha * Fx_pureSlip;
{
combinedLongCoefs tmp = {S_HxAlpha, alpha_S, B_xAlpha, C_xAlpha, E_xAlpha, G_xAlpha0, G_xAlpha};
*m_combinedLong = tmp;
}
return F_x;
}
double ChPacejkaTire::Fy_combined(double alpha, double gamma, double kappa, double Fy_pureSlip) {
double rby4 = 0;
double S_HyKappa = m_params->lateral.rhy1 + m_params->lateral.rhy2 * m_dF_z;
double kappa_S = kappa + S_HyKappa;
double B_yKappa = (m_params->lateral.rby1 + rby4 * pow(gamma, 2)) *
std::cos(std::atan(m_params->lateral.rby2 * (alpha - m_params->lateral.rby3))) *
m_params->scaling.lyka;
double C_yKappa = m_params->lateral.rcy1;
double E_yKappa = m_params->lateral.rey1 + m_params->lateral.rey2 * m_dF_z;
double D_VyKappa = m_pureLat->mu_y * m_Fz *
(m_params->lateral.rvy1 + m_params->lateral.rvy2 * m_dF_z + m_params->lateral.rvy3 * gamma) *
std::cos(std::atan(m_params->lateral.rvy4 * alpha)) * m_zeta->z2;
double S_VyKappa = D_VyKappa * std::sin(m_params->lateral.rvy5 * std::atan(m_params->lateral.rvy6 * kappa)) *
m_params->scaling.lvyka;
double G_yKappa0 =
std::cos(C_yKappa *
std::atan(B_yKappa * S_HyKappa - E_yKappa * (B_yKappa * S_HyKappa - std::atan(B_yKappa * S_HyKappa))));
double G_yKappa = std::cos(C_yKappa * std::atan(B_yKappa * kappa_S -
E_yKappa * (B_yKappa * kappa_S - std::atan(B_yKappa * kappa_S)))) /
G_yKappa0;
double F_y = G_yKappa * Fy_pureSlip + S_VyKappa;
{
combinedLatCoefs tmp = {S_HyKappa, kappa_S, B_yKappa, C_yKappa, E_yKappa,
D_VyKappa, S_VyKappa, G_yKappa0, G_yKappa};
*m_combinedLat = tmp;
}
return F_y;
}
double ChPacejkaTire::Mz_combined(double alpha_r,
double alpha_t,
double gamma,
double kappa,
double Fx_combined,
double Fy_combined) {
double FP_y = Fy_combined - m_combinedLat->S_VyKappa;
double s = m_R0 * (m_params->aligning.ssz1 + m_params->aligning.ssz2 * (Fy_combined / m_params->vertical.fnomin) +
(m_params->aligning.ssz3 + m_params->aligning.ssz4 * m_dF_z) * gamma) *
m_params->scaling.ls;
int sign_alpha_t = (alpha_t >= 0) ? 1 : -1;
int sign_alpha_r = (alpha_r >= 0) ? 1 : -1;
double alpha_t_eq =
sign_alpha_t * sqrt(pow(alpha_t, 2) + pow(m_pureLong->K_x / m_pureTorque->K_y, 2) * pow(kappa, 2));
double alpha_r_eq =
sign_alpha_r * sqrt(pow(alpha_r, 2) + pow(m_pureLong->K_x / m_pureTorque->K_y, 2) * pow(kappa, 2));
double M_zr = m_pureTorque->D_r * std::cos(m_pureTorque->C_r * std::atan(m_pureTorque->B_r * alpha_r_eq)) *
m_slip->cosPrime_alpha;
double t =
m_pureTorque->D_t *
std::cos(m_pureTorque->C_t * std::atan(m_pureTorque->B_t * alpha_t_eq -
m_pureTorque->E_t * (m_pureTorque->B_t * alpha_t_eq -
std::atan(m_pureTorque->B_t * alpha_t_eq)))) *
m_slip->cosPrime_alpha;
double M_z_y = -t * FP_y;
double M_z_x = s * Fx_combined;
double M_z = M_z_y + M_zr + M_z_x;
{
combinedTorqueCoefs tmp = {m_slip->cosPrime_alpha, FP_y, s, alpha_t_eq, alpha_r_eq, M_zr, t, M_z_x, M_z_y};
*m_combinedTorque = tmp;
}
return M_z;
}
double ChPacejkaTire::calc_Mx(double gamma, double Fy_combined) {
double M_x = 0;
if (m_in_contact) {
// according to Pacejka
M_x = m_Fz * m_R0 * (m_params->overturning.qsx1 - m_params->overturning.qsx2 * gamma +
m_params->overturning.qsx3 * (Fy_combined / m_params->vertical.fnomin)) *
m_params->scaling.lmx;
}
return M_x;
}
double ChPacejkaTire::calc_My(double Fx_combined) {
double M_y = 0;
if (m_in_contact) {
double V_r = m_tireState.omega * m_R_eff;
M_y = -m_Fz * m_R0 * (m_params->rolling.qsy1 * std::atan(V_r / m_params->model.longvl) +
m_params->rolling.qsy2 * (Fx_combined / m_params->vertical.fnomin)) *
m_params->scaling.lmy;
// reference calc
// M_y = m_R0*m_Fz * (m_params->rolling.qsy1 + m_params->rolling.qsy2*Fx_combined/m_params->vertical.fnomin +
// m_params->rolling.qsy3*std::abs(m_slip->V_cx/m_params->model.longvl) +
// m_params->rolling.qsy4*pow(m_slip->V_cx/m_params->model.longvl,4));
}
return M_y;
}
// -----------------------------------------------------------------------------
// Load a PacTire specification file.
//
// For an example, see the file data/vehicle/hmmwv/tire/HMMWV_pacejka.tir
// -----------------------------------------------------------------------------
void ChPacejkaTire::loadPacTireParamFile() {
// try to load the file
std::ifstream inFile(this->getPacTireParamFile().c_str(), std::ios::in);
// if not loaded, say something and exit
if (!inFile.is_open()) {
GetLog() << "\n\n !!!!!!! couldn't load the pac tire file: " << getPacTireParamFile().c_str() << "\n\n";
GetLog() << " pacTire param file opened in a text editor somewhere ??? \n\n\n";
return;
}
// success in opening file, load the data, broken down into sections
// according to what is found in the PacTire input file
readPacTireInput(inFile);
// this bool will allow you to query the pac tire for output
// Forces, moments based on wheel state info.
m_params_defined = true;
}
void ChPacejkaTire::readPacTireInput(std::ifstream& inFile) {
// advance to the first part of the file with data we need to read
std::string tline;
while (std::getline(inFile, tline)) {
// first main break
if (tline[0] == '$')
break;
}
// to keep things sane (and somewhat orderly), create a function to read
// each subsection. there may be overlap between different PacTire versions,
// where these section read functions can be reused
// 0: [UNITS], all token values are strings
readSection_UNITS(inFile);
// 1: [MODEL]
readSection_MODEL(inFile);
// 2: [DIMENSION]
readSection_DIMENSION(inFile);
// 3: [SHAPE]
readSection_SHAPE(inFile);
// 4: [VERTICAL]
readSection_VERTICAL(inFile);
// 5-8, ranges for: LONG_SLIP, SLIP_ANGLE, INCLINATION_ANGLE, VETRICAL_FORCE,
// in that order
readSection_RANGES(inFile);
// 9: [scaling]
readSection_scaling(inFile);
// 10: [longitudinal]
readSection_longitudinal(inFile);
// 11: [overturning]
readSection_overturning(inFile);
// 12: [lateral]
readSection_lateral(inFile);
// 13: [rolling]
readSection_rolling(inFile);
// 14: [aligning]
readSection_aligning(inFile);
}
void ChPacejkaTire::readSection_UNITS(std::ifstream& inFile) {
// skip the first line
std::string tline;
std::getline(inFile, tline);
// string util stuff
std::string tok; // name of token
std::string val_str; // temp for string token values
std::vector<std::string> split;
while (std::getline(inFile, tline)) {
// made it to the next section
if (tline[0] == '$')
break;
}
}
void ChPacejkaTire::readSection_MODEL(std::ifstream& inFile) {
// skip the first line
std::string tline;
std::getline(inFile, tline);
// string util stuff
std::vector<std::string> split;
std::string val_str; // string token values
// token value changes type in this section, do it manually
std::getline(inFile, tline);
// get the token / value
split = splitStr(tline, '=');
m_params->model.property_file_format = splitStr(split[1], '\'')[1];
std::getline(inFile, tline);
m_params->model.use_mode = fromTline<int>(tline);
std::getline(inFile, tline);
m_params->model.vxlow = fromTline<double>(tline);
std::getline(inFile, tline);
m_params->model.longvl = fromTline<double>(tline);
std::getline(inFile, tline);
split = splitStr(tline, '=');
m_params->model.tyreside = splitStr(split[1], '\'')[1];
}
void ChPacejkaTire::readSection_DIMENSION(std::ifstream& inFile) {
// skip the first two lines
std::string tline;
std::getline(inFile, tline);
std::getline(inFile, tline);
// if all the data types are the same in a subsection, life is a little easier
// push each token value to this vector, check the # of items added, then
// create the struct by hand only
std::vector<double> dat;
while (std::getline(inFile, tline)) {
// made it to the next section
if (tline[0] == '$')
break;
dat.push_back(fromTline<double>(tline));
}
if (dat.size() != 5) {
GetLog() << " error reading DIMENSION section of pactire input file!!! \n\n";
return;
}
// right size, create the struct
struct dimension dim = {dat[0], dat[1], dat[2], dat[3], dat[4]};
m_params->dimension = dim;
}
void ChPacejkaTire::readSection_SHAPE(std::ifstream& inFile) {
// skip the first two lines
std::string tline;
std::getline(inFile, tline);
std::getline(inFile, tline);
// if all the data types are the same in a subsection, life is a little easier
// push each token value to this vector, check the # of items added, then
// create the struct by hand only
std::vector<double> rad;
std::vector<double> wid;
std::vector<std::string> split;
while (std::getline(inFile, tline)) {
// made it to the next section
if (tline[0] == '$')
break;
split = splitStr(tline, ' ');
rad.push_back(std::atof(split[1].c_str()));
wid.push_back(std::atof(split[5].c_str()));
}
m_params->shape.radial = rad;
m_params->shape.width = wid;
}
void ChPacejkaTire::readSection_VERTICAL(std::ifstream& inFile) {
// skip the first line
std::string tline;
std::getline(inFile, tline);
// push each token value to this vector, check the # of items added
std::vector<double> dat;
while (std::getline(inFile, tline)) {
// made it to the next section
if (tline[0] == '$')
break;
dat.push_back(fromTline<double>(tline));
}
if (dat.size() != 6) {
GetLog() << " error reading VERTICAL section of pactire input file!!! \n\n";
return;
}
// right size, create the struct
struct vertical vert = {dat[0], dat[1], dat[2], dat[3], dat[4], dat[5]};
m_params->vertical = vert;
}
void ChPacejkaTire::readSection_RANGES(std::ifstream& inFile) {
// skip the first line
std::string tline;
std::getline(inFile, tline);
// if all the data types are the same in a subsection, life is a little easier
// push each token value to this vector, check the # of items added, then
// create the struct by hand only
std::vector<double> dat;
// LONG_SLIP_RANGE
while (std::getline(inFile, tline)) {
// made it to the next section
if (tline[0] == '$')
break;
dat.push_back(fromTline<double>(tline));
}
if (dat.size() != 2) {
GetLog() << " error reading LONG_SLIP_RANGE section of pactire input file!!! \n\n";
return;
}
// right size, create the struct
struct long_slip_range long_slip = {dat[0], dat[1]};
m_params->long_slip_range = long_slip;
dat.clear();
std::getline(inFile, tline);
// SLIP_ANGLE_RANGE
while (std::getline(inFile, tline)) {
// made it to the next section
if (tline[0] == '$')
break;
dat.push_back(fromTline<double>(tline));
}
if (dat.size() != 2) {
GetLog() << " error reading LONG_SLIP_RANGE section of pactire input file!!! \n\n";
return;
}
// right size, create the struct
struct slip_angle_range slip_ang = {dat[0], dat[1]};
m_params->slip_angle_range = slip_ang;
dat.clear();
std::getline(inFile, tline);
// INCLINATION_ANGLE_RANGE
while (std::getline(inFile, tline)) {
// made it to the next section
if (tline[0] == '$')
break;
dat.push_back(fromTline<double>(tline));
}
if (dat.size() != 2) {
GetLog() << " error reading INCLINATION_ANGLE_RANGE section of pactire input file!!! \n\n";
return;
}
struct inclination_angle_range incl_ang = {dat[0], dat[1]};
m_params->inclination_angle_range = incl_ang;
dat.clear();
std::getline(inFile, tline);
// VERTICAL_FORCE_RANGE
while (std::getline(inFile, tline)) {
// made it to the next section
if (tline[0] == '$')
break;
dat.push_back(fromTline<double>(tline));
}
if (dat.size() != 2) {
GetLog() << " error reading VERTICAL_FORCE_RANGE section of pactire input file!!! \n\n";
return;
}
struct vertical_force_range vert_range = {dat[0], dat[1]};
m_params->vertical_force_range = vert_range;
}
void ChPacejkaTire::readSection_scaling(std::ifstream& inFile) {
std::string tline;
std::getline(inFile, tline);
// if all the data types are the same in a subsection, life is a little easier
// push each token value to this vector, check the # of items added, then
// create the struct by hand only
std::vector<double> dat;
while (std::getline(inFile, tline)) {
// made it to the next section
if (tline[0] == '$')
break;
dat.push_back(fromTline<double>(tline));
}
if (dat.size() != 28) {
GetLog() << " error reading scaling section of pactire input file!!! \n\n";
return;
}
struct scaling_coefficients coefs = {dat[0], dat[1], dat[2], dat[3], dat[4], dat[5], dat[6],
dat[7], dat[8], dat[9], dat[10], dat[11], dat[12], dat[13],
dat[14], dat[15], dat[16], dat[17], dat[18], dat[19], dat[20],
dat[21], dat[22], dat[23], dat[24], dat[25], dat[26], dat[27]};
m_params->scaling = coefs;
}
void ChPacejkaTire::readSection_longitudinal(std::ifstream& inFile) {
std::string tline;
std::getline(inFile, tline);
std::vector<double> dat;
while (std::getline(inFile, tline)) {
// made it to the next section
if (tline[0] == '$')
break;
dat.push_back(fromTline<double>(tline));
}
if (dat.size() != 24) {
GetLog() << " error reading longitudinal section of pactire input file!!! \n\n";
return;
}
struct longitudinal_coefficients coefs = {dat[0], dat[1], dat[2], dat[3], dat[4], dat[5], dat[6], dat[7],
dat[8], dat[9], dat[10], dat[11], dat[12], dat[13], dat[14], dat[15],
dat[16], dat[17], dat[18], dat[19], dat[20], dat[21], dat[22], dat[23]};
m_params->longitudinal = coefs;
}
void ChPacejkaTire::readSection_overturning(std::ifstream& inFile) {
std::string tline;
std::getline(inFile, tline);
std::vector<double> dat;
while (std::getline(inFile, tline)) {
// made it to the next section
if (tline[0] == '$')
break;
dat.push_back(fromTline<double>(tline));
}
if (dat.size() != 3) {
GetLog() << " error reading overturning section of pactire input file!!! \n\n";
return;
}
struct overturning_coefficients coefs = {dat[0], dat[1], dat[2]};
m_params->overturning = coefs;
}
void ChPacejkaTire::readSection_lateral(std::ifstream& inFile) {
std::string tline;
std::getline(inFile, tline);
std::vector<double> dat;
while (std::getline(inFile, tline)) {
// made it to the next section
if (tline[0] == '$')
break;
dat.push_back(fromTline<double>(tline));
}
if (dat.size() != 34) {
GetLog() << " error reading lateral section of pactire input file!!! \n\n";
return;
}
struct lateral_coefficients coefs = {
dat[0], dat[1], dat[2], dat[3], dat[4], dat[5], dat[6], dat[7], dat[8], dat[9], dat[10], dat[11],
dat[12], dat[13], dat[14], dat[15], dat[16], dat[17], dat[18], dat[19], dat[20], dat[21], dat[22], dat[23],
dat[24], dat[25], dat[26], dat[27], dat[28], dat[29], dat[30], dat[31], dat[32], dat[33]};
m_params->lateral = coefs;
}
void ChPacejkaTire::readSection_rolling(std::ifstream& inFile) {
std::string tline;
std::getline(inFile, tline);
std::vector<double> dat;
while (std::getline(inFile, tline)) {
// made it to the next section
if (tline[0] == '$')
break;
dat.push_back(fromTline<double>(tline));
}
if (dat.size() != 4) {
GetLog() << " error reading rolling section of pactire input file!!! \n\n";
return;
}
struct rolling_coefficients coefs = {dat[0], dat[1], dat[2], dat[3]};
m_params->rolling = coefs;
}
void ChPacejkaTire::readSection_aligning(std::ifstream& inFile) {
std::string tline;
std::getline(inFile, tline);
std::vector<double> dat;
while (std::getline(inFile, tline)) {
// made it to the next section
if (tline[0] == '$')
break;
dat.push_back(fromTline<double>(tline));
}
if (dat.size() != 31) {
GetLog() << " error reading LONG_SLIP_RANGE section of pactire input file!!! \n\n";
return;
}
struct aligning_coefficients coefs = {dat[0], dat[1], dat[2], dat[3], dat[4], dat[5], dat[6], dat[7],
dat[8], dat[9], dat[10], dat[11], dat[12], dat[13], dat[14], dat[15],
dat[16], dat[17], dat[18], dat[19], dat[20], dat[21], dat[22], dat[23],
dat[24], dat[25], dat[26], dat[27], dat[28], dat[29], dat[30]};
m_params->aligning = coefs;
}
// -----------------------------------------------------------------------------
// Functions providing access to private structures
// -----------------------------------------------------------------------------
double ChPacejkaTire::get_kappa() const {
return m_slip->kappa;
}
double ChPacejkaTire::get_alpha() const {
return m_slip->alpha;
}
double ChPacejkaTire::get_gamma() const {
return m_slip->gamma;
}
double ChPacejkaTire::get_kappaPrime() const {
return m_slip->kappaP;
}
double ChPacejkaTire::get_alphaPrime() const {
return m_slip->alphaP;
}
double ChPacejkaTire::get_gammaPrime() const {
return m_slip->gammaP;
}
double ChPacejkaTire::get_min_long_slip() const {
return m_params->long_slip_range.kpumin;
}
double ChPacejkaTire::get_max_long_slip() const {
return m_params->long_slip_range.kpumax;
}
double ChPacejkaTire::get_min_lat_slip() const {
return m_params->slip_angle_range.alpmin;
}
double ChPacejkaTire::get_max_lat_slip() const {
return m_params->slip_angle_range.alpmax;
}
double ChPacejkaTire::get_longvl() const {
return m_params->model.longvl;
}
// -----------------------------------------------------------------------------
// Write output file for post-processing with the Python pandas module.
// -----------------------------------------------------------------------------
void ChPacejkaTire::WriteOutData(double time, const std::string& outFilename) {
// first time thru, write headers
if (m_Num_WriteOutData == 0) {
m_outFilename = outFilename;
std::ofstream oFile(outFilename.c_str(), std::ios_base::out);
if (!oFile.is_open()) {
std::cout << " couldn't open file for writing: " << outFilename << " \n\n";
return;
} else {
// write the headers, Fx, Fy are pure forces, Fxc and Fyc are the combined forces
oFile << "time,kappa,alpha,gamma,kappaP,alphaP,gammaP,Vx,Vy,omega,Fx,Fy,Fz,Mx,My,Mz,Fxc,Fyc,Mzc,Mzx,Mzy,M_"
"zrc,contact,m_Fz,m_dF_z,u,valpha,vgamma,vphi,du,dvalpha,dvgamma,dvphi,R0,R_l,Reff,MP_z,M_zr,t,s,"
"FX,FY,FZ,MX,MY,MZ,u_Bessel,u_sigma,v_Bessel,v_sigma"
<< std::endl;
m_Num_WriteOutData++;
oFile.close();
}
} else {
// already written the headers, just increment the function counter
m_Num_WriteOutData++;
}
// ensure file was able to be opened, headers are written
if (m_Num_WriteOutData > 0) {
// open file, append
std::ofstream appFile(outFilename.c_str(), std::ios_base::app);
// global force/moments applied to wheel rigid body
TerrainForce global_FM = GetTireForce_combinedSlip(false);
// write the slip info, reaction forces for pure & combined slip cases
appFile << time << "," << m_slip->kappa << "," << m_slip->alpha * 180. / 3.14159 << "," << m_slip->gamma << ","
<< m_slip->kappaP << "," << m_slip->alphaP << "," << m_slip->gammaP << "," << m_slip->V_cx << ","
<< m_slip->V_cy << "," << m_tireState.omega
<< "," // m_tireState.lin_vel.x() <<","<< m_tireState.lin_vel.y() <<","
<< m_FM_pure.force.x() << "," << m_FM_pure.force.y() << "," << m_FM_pure.force.z() << ","
<< m_FM_pure.moment.x() << "," << m_FM_pure.moment.y() << "," << m_FM_pure.moment.z() << ","
<< m_FM_combined.force.x() << "," << m_FM_combined.force.y() << "," << m_FM_combined.moment.z() << ","
<< m_combinedTorque->M_z_x << "," << m_combinedTorque->M_z_y << "," << m_combinedTorque->M_zr << ","
<< (int)m_in_contact << "," << m_Fz << "," << m_dF_z << "," << m_slip->u << "," << m_slip->v_alpha
<< "," << m_slip->v_gamma << "," << m_slip->v_phi << "," << m_slip->Idu_dt << ","
<< m_slip->Idv_alpha_dt << "," << m_slip->Idv_gamma_dt << "," << m_slip->Idv_phi_dt << "," << m_R0
<< "," << m_R_l << "," << m_R_eff << "," << m_pureTorque->MP_z << "," << m_pureTorque->M_zr << ","
<< m_combinedTorque->t << "," << m_combinedTorque->s << "," << global_FM.force.x() << ","
<< global_FM.force.y() << "," << global_FM.force.z() << "," << global_FM.moment.x() << ","
<< global_FM.moment.y() << "," << global_FM.moment.z() << "," << m_bessel->u_Bessel << ","
<< m_bessel->u_sigma << "," << m_bessel->v_Bessel << "," << m_bessel->v_sigma << std::endl;
// close the file
appFile.close();
}
}
// -----------------------------------------------------------------------------
// Utility function for validation studies.
//
// Calculate a wheel state consistent with the specified kinematic slip
// quantities (kappa, alpha, and gamma) and magnitude of tangential velocity.
// Out of the infinitely many consistent wheel states, we
// - set position at origin
// - set linear velocity along global X direction with given magnitude
// - set orientation based on given alpha and gamma
// - set omega from given kappa and using current R_eff
// - set angular velocity along the local wheel Y axis
// -----------------------------------------------------------------------------
WheelState ChPacejkaTire::getState_from_KAG(double kappa, double alpha, double gamma, double Vx) {
WheelState state;
// Set wheel position at origin.
state.pos = ChVector<>(0, 0, 0);
// Set the wheel velocity aligned with the global X axis.
state.lin_vel = ChVector<>(Vx, 0, 0);
// Rotate wheel to satisfy specified camber angle and slip angle. For this,
// we first rotate the wheel about the global Z-axis by an angle (-alpha),
// followed by a rotation about the new X-axis by an angle gamma.
state.rot = Q_from_AngZ(-alpha) * Q_from_AngX(gamma);
// Calculate forward tangential velocity.
double Vcx = Vx * std::cos(alpha);
// Set the wheel angular velocity about its axis, calculated from the given
// value kappa and using the current value m_R_eff.
// Note that here we assume that the specified velocity is such that Vcx is
// larger than the threshold model.vxlow.
state.omega = (kappa * std::abs(Vcx) + Vcx) / m_R_eff;
// Set the wheel angular velocity (expressed in global frame).
state.ang_vel = state.rot.RotateBack(ChVector<>(0, state.omega, 0));
return state;
}
} // end namespace vehicle
} // end namespace chrono
| 41.217901 | 120 | 0.59384 | [
"object",
"shape",
"vector",
"model",
"transform"
] |
679ca4bc531fe487d507d7d0f5c245624a1f9ace | 7,544 | hpp | C++ | src/atlas/graphics/Node.hpp | Groutcho/atlas | b69b7759be0361ffdcbbba64501e07feb79143be | [
"MIT"
] | 5 | 2018-12-13T03:41:12.000Z | 2020-08-27T04:45:11.000Z | src/atlas/graphics/Node.hpp | Groutcho/atlas | b69b7759be0361ffdcbbba64501e07feb79143be | [
"MIT"
] | 1 | 2020-09-08T07:26:59.000Z | 2020-09-08T09:21:44.000Z | src/atlas/graphics/Node.hpp | Groutcho/atlas | b69b7759be0361ffdcbbba64501e07feb79143be | [
"MIT"
] | 5 | 2018-12-20T10:31:09.000Z | 2021-09-07T07:38:49.000Z | #ifndef ATLAS_GRAPHICS_NODE_HPP
#define ATLAS_GRAPHICS_NODE_HPP
#include "AtlasGraphics.hpp"
#include <unordered_set>
namespace atlas
{
namespace graphics
{
class Camera;
class Node;
struct DrawContext
{
vk::CommandBuffer cmdBuffer;
Transform viewMatrix;
Transform projectionMatrix;
};
struct UpdateContext
{
Node* camera;
};
enum class NodeFlags
{
None = 0U,
Drawable = 1U,
Debug = 2U,
Compositing = 4U,
};
enum class SceneGraphEvent
{
MeshAdded = 1U,
MeshDeleted = 2U
};
enum class Signal
{
WindowResized = 1
};
/**
* @brief Provides preorder traversal functionality for nodes.
*/
class NodeIterator
{
public:
NodeIterator(Node* current);
/**
* @brief Moves to the next Node in the preorder traversal.
*
* @return The next Node
*/
Node* operator++();
/**
* @brief Returns the current Node before moving to the
* next Node in the preorder traversal.
*
* @return the Node before the current Node.
*/
Node* operator++(int);
/**
* @brief Returns the current Node.
*
* @return the current Node.
*/
inline Node* operator*() const
{
return _current;
}
bool operator==(const NodeIterator& rhs)
{
return _current == rhs._current;
}
bool operator!=(const NodeIterator& rhs)
{
return _current != rhs._current;
}
private:
Node * _current;
};
/**
* @brief Represents an element of a scene graph.
*/
class Node
{
public:
/**
* @brief Constructs a Node.
*/
Node();
virtual ~Node();
/**
* @brief Returns the number of elements in this Node, recursively.
*
* @return The number of elements in this Node.
*/
size_t size() const noexcept;
/**
* @brief Adds a child to this Node. The new child becomes
* the rightmost child.
*
* @param Child the value to add as a child.
*/
void add_child(Node* child);
/**
* @brief Returns the number of children in this Node.
*
* @return The number of children.
*/
inline size_t child_count() const noexcept
{
return _children.size();
}
/**
* @brief returns the parent of this Node, if any,
* otherwise returns the nullptr.
*
* @return the parent, or the nullptr.
*/
inline Node* parent() const noexcept
{
return _parent;
}
/**
* @brief returns the right sibling of this Node, if any,
* otherwise returns the nullptr.
*
* @return the right sibling, or the nullptr.
*/
inline Node* right() const noexcept
{
return _rightSibling;
}
/**
* @brief removes all children from this Node.
*/
inline void clear_children() noexcept
{
_children.clear();
}
/**
* @brief Returns the child at index pos.
*
* @param[in] pos The child index.
*
*
* @throw std::invalid_argument if pos is out of bounds.
* @return The child.
*/
Node* get_child(size_t pos) const;
/**
* @brief Removes the child at index pos.
*
* @param[in] pos The child index.
*
* @throw std::invalid_argument if pos is out of bounds.
*/
void remove_child(size_t pos);
virtual void Update(UpdateContext ctx) {}
virtual void SendSignal(Signal signal);
/**************************************************************/
/* operators */
/**************************************************************/
// friend std::ostream& operator<< (
// std::ostream& os,
// const Node& g)
// {
// return os;
// //return os << "(" << *g.data << ")";
// }
//bool operator ==(const Node& rhs)
//{
// return mValue == rhs.mValue
// && _parent == rhs._parent
// && _rightSibling == rhs._rightSibling
// && _children == rhs._children;
//}
//bool operator !=(const Node& rhs)
//{
// return mValue != rhs
// || _parent != rhs._parent
// || _rightSibling != rhs._rightSibling
// || _children != rhs._children;
//}
/**
* @brief Returns an iterator starting at this Node.
*
* @return the iterator for this Node.
*/
NodeIterator begin() noexcept;
/**
* @brief Returns an iterator at the end of the preorder
* traversal, i.e at the right of the rightmost branch.
*
* @return the iterator for the end.
*/
NodeIterator end() noexcept;
inline const uint32_t flags() const noexcept { return _flags; }
inline uint32_t pendingEvents() const noexcept { return _pendingEvents; }
inline void ClearPendingEvents() noexcept { _pendingEvents = 0; }
/**************************************************************/
/* transform */
/**************************************************************/
inline void setTransform(Transform t) noexcept { _transform = t; }
inline void setLocalTransform(Transform t) noexcept { _localTransform = t; }
inline Transform localTransform() const noexcept { return _localTransform; }
inline Transform transform() const noexcept { return _transform; }
protected:
glm::mat4 _transform;
glm::mat4 _localTransform;
Node* _parent;
Node* _rightSibling;
std::vector<Node*> _children;
uint32_t _flags;
uint32_t _pendingEvents;
void BubbleEvent(SceneGraphEvent event);
void throw_if_out_of_range(size_t child_pos) const;
};
}
}
#endif // !ATLAS_GRAPHICS_SCENEGRAPH_HPP
| 29.015385 | 88 | 0.421925 | [
"vector",
"transform"
] |
67a017e9f8b1d346952bc543a8d6aa736b973384 | 1,445 | cpp | C++ | leetcode/leetcode207.cpp | KevinYang515/C-Projects | 1bf95a09a0ffc18102f12263c9163619ce6dba55 | [
"MIT"
] | null | null | null | leetcode/leetcode207.cpp | KevinYang515/C-Projects | 1bf95a09a0ffc18102f12263c9163619ce6dba55 | [
"MIT"
] | null | null | null | leetcode/leetcode207.cpp | KevinYang515/C-Projects | 1bf95a09a0ffc18102f12263c9163619ce6dba55 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <map>
#include <queue>
using namespace std;
bool canFinish(int numCourses, vector<vector<int>>& prerequisites);
int main(){
vector<int> numCourses_v = {2, 2};
vector<vector<vector<int>>> prerequisites_v = {{{1, 0}}, {{1, 0}, {0, 1}}};
// True, False
for (int i = 0; i < numCourses_v.size(); i++){
printf("%s, ", canFinish(numCourses_v[i], prerequisites_v[i]) ? "True" : "False");
}
return 0;
}
// Time Complexity: O(n)
// Space Complextiy: O(n)
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
queue<int> q;
map<int, vector<int>> schedule;
vector<int> indegree(numCourses, 0);
for (vector<int> prerequire : prerequisites){
indegree[prerequire[0]] ++;
if (schedule.find(prerequire[1]) != schedule.end()){
schedule[prerequire[1]].push_back(prerequire[0]);
}else {
schedule[prerequire[1]] = vector<int> {prerequire[0]};
}
}
for (int i = 0; i < numCourses; i++){
if (indegree[i] == 0) q.push(i);
}
while (!q.empty()){
int course = q.front();
q.pop();
vector<int> current = schedule[course];
for (int c : current){
indegree[c] --;
if (indegree[c] == 0) q.push(c);
}
}
for (int i = 0; i < numCourses; i++){
if (indegree[i] > 0) return false;
}
return true;
}
| 27.264151 | 90 | 0.553633 | [
"vector"
] |
67a31460172114fb00b920352155747c9fd25dd4 | 7,660 | hpp | C++ | src/mahjong/types/yaku.hpp | happapa/mahjong-cpp | a392a9a48cd790dbcf4ee31463c3a431c9a614c5 | [
"MIT"
] | 9 | 2020-12-30T08:53:37.000Z | 2022-03-30T11:27:40.000Z | src/mahjong/types/yaku.hpp | happapa/mahjong-cpp | a392a9a48cd790dbcf4ee31463c3a431c9a614c5 | [
"MIT"
] | 2 | 2021-12-07T06:53:12.000Z | 2022-01-13T03:30:04.000Z | src/mahjong/types/yaku.hpp | happapa/mahjong-cpp | a392a9a48cd790dbcf4ee31463c3a431c9a614c5 | [
"MIT"
] | 2 | 2021-05-14T19:25:14.000Z | 2021-12-21T13:11:04.000Z | #ifndef MAHJONG_CPP_YAKU
#define MAHJONG_CPP_YAKU
#include <array>
#include <map>
#include <string>
namespace mahjong
{
using YakuList = unsigned long long;
/**
* @brief 役
*/
struct Yaku
{
/**
* @brief 役の種類
*/
enum Type : YakuList
{
Null = 0ull,
Tumo = 1ull, /* 門前清自摸和 */
Reach = 1ull << 1, /* 立直 */
Ippatu = 1ull << 2, /* 一発 */
Tanyao = 1ull << 3, /* 断幺九 */
Pinhu = 1ull << 4, /* 平和 */
Ipeko = 1ull << 5, /* 一盃口 */
Tyankan = 1ull << 6, /* 槍槓 */
Rinsyankaiho = 1ull << 7, /* 嶺上開花 */
Haiteitumo = 1ull << 8, /* 海底摸月 */
Hoteiron = 1ull << 9, /* 河底撈魚 */
Dora = 1ull << 10, /* ドラ */
UraDora = 1ull << 11, /* 裏ドラ */
AkaDora = 1ull << 12, /* 赤ドラ */
SangenhaiHaku = 1ull << 13, /* 三元牌 (白) */
SangenhaiHatu = 1ull << 14, /* 三元牌 (發) */
SangenhaiTyun = 1ull << 15, /* 三元牌 (中) */
ZikazeTon = 1ull << 16, /* 自風 (東) */
ZikazeNan = 1ull << 17, /* 自風 (南) */
ZikazeSya = 1ull << 18, /* 自風 (西) */
ZikazePe = 1ull << 19, /* 自風 (北) */
BakazeTon = 1ull << 20, /* 場風 (東) */
BakazeNan = 1ull << 21, /* 場風 (南) */
BakazeSya = 1ull << 22, /* 場風 (西) */
BakazePe = 1ull << 23, /* 場風 (北) */
DoubleReach = 1ull << 24, /* ダブル立直 */
Tiitoitu = 1ull << 25, /* 七対子 */
Toitoiho = 1ull << 26, /* 対々和 */
Sananko = 1ull << 27, /* 三暗刻 */
SansyokuDoko = 1ull << 28, /* 三色同刻 */
SansyokuDozyun = 1ull << 29, /* 三色同順 */
Honroto = 1ull << 30, /* 混老頭 */
IkkiTukan = 1ull << 31, /* 一気通貫 */
Tyanta = 1ull << 32, /* 混全帯幺九 */
Syosangen = 1ull << 33, /* 小三元 */
Sankantu = 1ull << 34, /* 三槓子 */
Honiso = 1ull << 35, /* 混一色 */
Zyuntyanta = 1ull << 36, /* 純全帯幺九 */
Ryanpeko = 1ull << 37, /* 二盃口 */
NagasiMangan = 1ull << 38, /* 流し満貫 */
Tiniso = 1ull << 39, /* 清一色 */
Tenho = 1ull << 40, /* 天和 */
Tiho = 1ull << 41, /* 地和 */
Renho = 1ull << 42, /* 人和 */
Ryuiso = 1ull << 43, /* 緑一色 */
Daisangen = 1ull << 44, /* 大三元 */
Syosusi = 1ull << 45, /* 小四喜 */
Tuiso = 1ull << 46, /* 字一色 */
Kokusimuso = 1ull << 47, /* 国士無双 */
Tyurenpoto = 1ull << 48, /* 九連宝燈 */
Suanko = 1ull << 49, /* 四暗刻 */
Tinroto = 1ull << 50, /* 清老頭 */
Sukantu = 1ull << 51, /* 四槓子 */
SuankoTanki = 1ull << 52, /* 四暗刻単騎 */
Daisusi = 1ull << 53, /* 大四喜 */
Tyurenpoto9 = 1ull << 54, /* 純正九連宝燈 */
Kokusimuso13 = 1ull << 55, /* 国士無双13面待ち */
Length = 56ull,
};
struct YakuInfo
{
/* 名前 */
std::string name;
/* 通常役: (門前の飜数, 非門前の飜数)、役満: (何倍役満か, 未使用) */
std::array<int, 2> han;
};
static inline std::vector<YakuList> NormalYaku = {
Tumo, Reach, Ippatu, Tanyao, Pinhu, Ipeko,
Tyankan, Rinsyankaiho, Haiteitumo, Hoteiron, SangenhaiHaku, SangenhaiHatu,
SangenhaiTyun, ZikazeTon, ZikazeNan, ZikazeSya, ZikazePe, BakazeTon,
BakazeNan, BakazeSya, BakazePe, DoubleReach, Tiitoitu, Toitoiho,
Sananko, SansyokuDoko, SansyokuDozyun, Honroto, IkkiTukan, Tyanta,
Syosangen, Sankantu, Honiso, Zyuntyanta, Ryanpeko, Tiniso,
};
static inline std::vector<YakuList> Yakuman = {
Tenho, Tiho, Renho, Ryuiso, Daisangen, Syosusi, Tuiso, Kokusimuso,
Tyurenpoto, Suanko, Tinroto, Sukantu, SuankoTanki, Daisusi, Tyurenpoto9, Kokusimuso13,
};
/**
* @brief 役の情報
*/
// clang-format off
static inline std::map<YakuList, YakuInfo> Info = {
{Null, {"役なし", {0, 0}}},
{Tumo, {"門前清自摸和", {1, 0}}}, // 門前限定
{Reach, {"立直", {1, 0}}}, // 門前限定
{Ippatu, {"一発", {1, 0}}}, // 門前限定
{Tanyao, {"断幺九", {1, 1}}},
{Pinhu, {"平和", {1, 0}}}, // 門前限定
{Ipeko, {"一盃口", {1, 0}}}, // 門前限定
{Tyankan, {"槍槓", {1, 1}}},
{Rinsyankaiho, {"嶺上開花", {1, 1}}},
{Haiteitumo, {"海底摸月", {1, 1}}},
{Hoteiron, {"河底撈魚", {1, 1}}},
{Dora, {"ドラ", {0, 0}}},
{UraDora, {"裏ドラ", {0, 0}}},
{AkaDora, {"赤ドラ", {0, 0}}},
{SangenhaiHaku, {"三元牌 (白)", {1, 1}}},
{SangenhaiHatu, {"三元牌 (發)", {1, 1}}},
{SangenhaiTyun, {"三元牌 (中)", {1, 1}}},
{ZikazeTon, {"自風 (東)", {1, 1}}},
{ZikazeNan, {"自風 (南)", {1, 1}}},
{ZikazeSya, {"自風 (西)", {1, 1}}},
{ZikazePe, {"自風 (北)", {1, 1}}},
{BakazeTon, {"場風 (東)", {1, 1}}},
{BakazeNan, {"場風 (南)", {1, 1}}},
{BakazeSya, {"場風 (西)", {1, 1}}},
{BakazePe, {"場風 (北)", {1, 1}}},
{DoubleReach, {"ダブル立直", {2, 0}}}, // 門前限定
{Tiitoitu, {"七対子", {2, 0}}}, // 門前限定
{Toitoiho, {"対々和", {2, 2}}},
{Sananko, {"三暗刻", {2, 2}}},
{SansyokuDoko, {"三色同刻", {2, 2}}},
{SansyokuDozyun, {"三色同順", {2, 1}}}, // 喰い下がり
{Honroto, {"混老頭", {2, 2}}},
{IkkiTukan, {"一気通貫", {2, 1}}}, // 喰い下がり
{Tyanta, {"混全帯幺九", {2, 1}}}, // 喰い下がり
{Syosangen, {"小三元", {2, 2}}},
{Sankantu, {"三槓子", {2, 2}}},
{Honiso, {"混一色", {3, 2}}}, // 喰い下がり
{Zyuntyanta, {"純全帯幺九", {3, 2}}}, // 喰い下がり
{Ryanpeko, {"二盃口", {3, 0}}}, // 門前限定
{NagasiMangan, {"流し満貫", {0, 0}}}, // 満貫扱い
{Tiniso, {"清一色", {6, 5}}}, // 喰い下がり
{Tenho, {"天和", {1, 0}}}, // 役満
{Tiho, {"地和", {1, 0}}}, // 役満
{Renho, {"人和", {1, 0}}}, // 役満
{Ryuiso, {"緑一色", {1, 0}}}, // 役満
{Daisangen, {"大三元", {1, 0}}}, // 役満
{Syosusi, {"小四喜", {1, 0}}}, // 役満
{Tuiso, {"字一色", {1, 0}}}, // 役満
{Kokusimuso, {"国士無双", {1, 0}}}, // 役満
{Tyurenpoto, {"九連宝燈", {1, 0}}}, // 役満
{Suanko, {"四暗刻", {1, 0}}}, // 役満
{Tinroto, {"清老頭", {1, 0}}}, // 役満
{Sukantu, {"四槓子", {1, 0}}}, // 役満
{SuankoTanki, {"四暗刻単騎", {2, 0}}}, // ダブル役満
{Daisusi, {"大四喜", {2, 0}}}, // ダブル役満
{Tyurenpoto9, {"純正九連宝燈", {2, 0}}}, // ダブル役満
{Kokusimuso13, {"国士無双13面待ち", {2, 0}}}, // ダブル役満
};
// clang-format on
};
} // namespace mahjong
#endif /* MAHJONG_CPP_YAKU */
| 44.022989 | 96 | 0.355352 | [
"vector"
] |
67a657df820eb88e9c88d146b5cf7385871f93ec | 32,133 | cpp | C++ | src/trunk/libs/seiscomp3/communication/systemconnection.cpp | yannikbehr/seiscomp3 | ebb44c77092555eef7786493d00ac4efc679055f | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 94 | 2015-02-04T13:57:34.000Z | 2021-11-01T15:10:06.000Z | src/trunk/libs/seiscomp3/communication/systemconnection.cpp | yannikbehr/seiscomp3 | ebb44c77092555eef7786493d00ac4efc679055f | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 233 | 2015-01-28T15:16:46.000Z | 2021-08-23T11:31:37.000Z | src/trunk/libs/seiscomp3/communication/systemconnection.cpp | yannikbehr/seiscomp3 | ebb44c77092555eef7786493d00ac4efc679055f | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 95 | 2015-02-13T15:53:30.000Z | 2021-11-02T14:54:54.000Z | /***************************************************************************
* Copyright (C) by GFZ Potsdam *
* *
* You can redistribute and/or modify this program under the *
* terms of the SeisComP Public License. *
* *
* 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 *
* SeisComP Public License for more details. *
***************************************************************************/
// logging
#define SEISCOMP_COMPONENT Communication
#include <seiscomp3/logging/log.h>
#include <boost/utility.hpp>
#include <boost/bind.hpp>
#include <boost/version.hpp>
#include <seiscomp3/communication/systemconnection.h>
#include <seiscomp3/communication/networkinterface.h>
#include <seiscomp3/communication/connectioninfo.h>
#include <seiscomp3/system/environment.h>
#include <seiscomp3/core/strings.h>
#include <seiscomp3/core/system.h>
#include <seiscomp3/utils/timer.h>
#include <seiscomp3/datamodel/version.h>
namespace Seiscomp {
namespace Communication {
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
SystemConnection::SystemConnection(NetworkInterface* networkInterface) :
_networkInterface(networkInterface),
_schemaVersion(0),
_type(Protocol::TYPE_DEFAULT),
_priority(Protocol::PRIORITY_DEFAULT),
_archiveRequested(false),
_archiveMsgLen(0),
_subscribedArchiveGroups(),
_groups(),
_subscriptions(),
_stopRequested(false),
_isConnected(false)
{
_messageStat = std::auto_ptr<MessageStat>(new MessageStat);
_connectionInfo = ConnectionInfo::Instance();
if (_connectionInfo)
_connectionInfo->registerConnection(this);
if (networkInterface == NULL)
_networkInterface = NetworkInterface::Create("spread");
if (_networkInterface.get() == NULL)
SEISCOMP_DEBUG("communication interface is NULL");
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
SystemConnection::~SystemConnection()
{
if (_connectionInfo)
_connectionInfo->unregisterConnection(this);
disconnect();
const Seiscomp::Environment* env = Seiscomp::Environment::Instance();
std::string archiveFilePath = env->archiveFileName(_clientName.c_str());
std::fstream archiveFile(archiveFilePath.c_str(),
std::ios::trunc | std::ios::in | std::ios::out);
if (_archiveMsgLen > 0)
archiveFile.write(_archiveMsg, _archiveMsgLen);
archiveFile.close();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int SystemConnection::handshake(const std::string &protocolVersion,
std::string *supportedVersion) {
// Ok, send request to the master client.
SEISCOMP_INFO("Sending connect message to server: %s", _masterAddress.c_str());
ServiceMessage synMsg(Protocol::CONNECT_GROUP_MSG, _type, _priority);
synMsg.setPeerGroup(_peerGroup);
synMsg.setPrivateSenderGroup(_networkInterface->privateGroup());
synMsg.setProtocolVersion(protocolVersion);
synMsg.setDestination(Protocol::MASTER_GROUP);
synMsg.setPassword(password());
synMsg.setData(_connectionInfo->info(this));
int ret = send(Protocol::MASTER_GROUP.c_str(), Protocol::CONNECT_GROUP_MSG, &synMsg);
if ( ret != Core::Status::SEISCOMP_SUCCESS ) {
SEISCOMP_ERROR("Could not send connect message to server: %s due to error %i",
_masterAddress.c_str(), ret);
SEISCOMP_ERROR("%s", Protocol::MsgTypeToString(ret));
return ret;
}
Util::StopWatch timer;
double fTimeOut = (double)_timeOut * 0.001;
NetworkMessagePtr ackMessage = NULL;
int error = 0;
// Read the response from the server on the private channel
do {
if ( _networkInterface->poll() ) {
ackMessage = _networkInterface->receive(&error);
if ( ackMessage ) {
if ( ackMessage->destination() != _networkInterface->privateGroup() ) {
ackMessage = NULL;
continue;
}
if ( error < 0 ) {
SEISCOMP_ERROR("Could not read acknowledgment message");
return error;
}
}
}
else {
if ( (double)timer.elapsed() >= fTimeOut ) {
SEISCOMP_ERROR( "Timeout while waiting for acknowledgment message" );
return Core::Status::SEISCOMP_TIMEOUT_ERROR;
}
// Sleep 200 milliseconds
Core::msleep(200);
}
} while ( !ackMessage.get() );
if ( ackMessage->type() == Protocol::CONNECT_GROUP_OK_MSG ) {
//Copy the private group name of the master
_privateMasterGroup = _networkInterface->groupOfLastSender();
_groups.clear();
if ( static_cast<ServiceMessage*>(ackMessage.get())->protocolVersion() == Protocol::PROTOCOL_VERSION_V1_0 ) {
Core::split(_groups, ackMessage->data().c_str(), ",");
_schemaVersion = 0;
}
else if ( static_cast<ServiceMessage*>(ackMessage.get())->protocolVersion() == Protocol::PROTOCOL_VERSION_V1_1 ) {
size_t pos;
std::vector<std::string> lines;
Core::split(lines, ackMessage->data().c_str(), "\n");
for ( size_t i = 0; i < lines.size(); ++i ) {
pos = lines[i].find(':');
if ( pos == std::string::npos ) continue;
if ( lines[i].compare(0, pos, Protocol::HEADER_GROUP_TAG) == 0 ) {
lines[i].erase(0,pos+1);
Core::split(_groups, Core::trim(lines[i]).c_str(), ",");
}
else if ( lines[i].compare(0, pos, Protocol::HEADER_SCHEMA_VERSION_TAG) == 0 ) {
lines[i].erase(0,pos+1);
if ( !_schemaVersion.fromString(lines[i]) ) {
SEISCOMP_WARNING("Invalid Schema-Version content: %s", lines[i].c_str());
continue;
}
}
else if ( lines[i].compare(0, pos, Protocol::HEADER_SERVER_VERSION_TAG) == 0 ) {
pos = lines[i].find_first_not_of(' ', pos+1);
SEISCOMP_INFO("Server version is '%s'", lines[i].c_str() + pos);
}
}
}
else
return Core::Status::SEISCOMP_WRONG_SERVER_VERSION;
if ( std::find(_groups.begin(), _groups.end(), Protocol::IMPORT_GROUP) == _groups.end() )
_groups.insert(_groups.begin(), Protocol::IMPORT_GROUP);
if ( std::find(_groups.begin(), _groups.end(), Protocol::STATUS_GROUP) == _groups.end() )
_groups.insert(_groups.begin(), Protocol::STATUS_GROUP);
}
else if ( ackMessage->type() == Protocol::INVALID_PROTOCOL_MSG ) {
SEISCOMP_INFO("The master protocol v%s is not compatible with client v%s",
static_cast<ServiceMessage*>(ackMessage.get())->protocolVersion().c_str(),
Protocol::PROTOCOL_VERSION_V1_1);
if ( supportedVersion ) *supportedVersion = static_cast<ServiceMessage*>(ackMessage.get())->protocolVersion();
return Core::Status::SEISCOMP_WRONG_SERVER_VERSION;
}
else {
SEISCOMP_INFO("Could not connect to the master due to message: %s",
Protocol::MsgTypeToString(ackMessage->type()));
return Core::Status::SEISCOMP_CONNECT_ERROR;
}
Core::Version maxVersion = Core::Version(DataModel::Version::Major, DataModel::Version::Minor);
if ( _schemaVersion > maxVersion ) {
SEISCOMP_INFO("Outgoing messages are encoded to match schema version %d.%d, "
"although server supports %d.%d",
maxVersion.majorTag(), maxVersion.minorTag(),
_schemaVersion.majorTag(), _schemaVersion.minorTag());
_schemaVersion = maxVersion;
}
else
SEISCOMP_INFO("Outgoing messages are encoded to match schema version %d.%d",
_schemaVersion.majorTag(), _schemaVersion.minorTag());
return Core::Status::SEISCOMP_SUCCESS;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int SystemConnection::connect(const std::string &masterAddress,
const std::string &clientName,
const std::string &peerGroup,
Protocol::ClientType type,
Protocol::ClientPriority priority,
int timeOut)
{
boost::try_mutex::scoped_try_lock l(_readBufferMutex);
_timeOut = timeOut;
_schemaVersion = 0;
if ( isConnected() )
return Core::Status::SEISCOMP_SUCCESS;
if ( peerGroup == Protocol::MASTER_GROUP ) {
SEISCOMP_ERROR("You cannot be a regular member of group: %s", peerGroup.c_str());
return Core::Status::SEISCOMP_INVALID_GROUP_ERROR;
}
_peerGroup = peerGroup;
if (!clientName.empty())
_clientName = clientName;
_masterAddress = masterAddress;
_type = type;
_priority = priority;
// Connect to the server
SEISCOMP_INFO("Connecting to server: %s", _masterAddress.c_str());
int ret = _networkInterface->connect(_masterAddress, _clientName);
if ( ret != Core::Status::SEISCOMP_SUCCESS ) {
SEISCOMP_ERROR("Could not connect to server: %s, internal error: %d", _masterAddress.c_str(), ret);
return ret;
}
SEISCOMP_INFO("Connected to message server: %s", _masterAddress.c_str());
// Clear previously requested archive groups
_subscribedArchiveGroups.clear();
// IMPORTANT: Once we are connected to the messaging system (currently spread)
// we subscribe to the messaging group. On account of this the master receives
// membership message for this client because he is also a member of this group.
// Otherwise, in case of an error, the client activities will not reported to
// the master.
SEISCOMP_INFO("Joining %s group", Protocol::MASTER_GROUP.c_str());
ret = _networkInterface->subscribe(Protocol::MASTER_GROUP);
if ( ret != Core::Status::SEISCOMP_SUCCESS ) {
SEISCOMP_ERROR("Could not join %s", Protocol::MASTER_GROUP.c_str());
shutdown();
return ret;
}
std::string masterProtocolVersion;
ret = handshake(Protocol::PROTOCOL_VERSION_V1_1, &masterProtocolVersion);
if ( ret == Core::Status::SEISCOMP_WRONG_SERVER_VERSION ) {
if ( masterProtocolVersion == Protocol::PROTOCOL_VERSION_V1_0 ) {
SEISCOMP_INFO("Falling back to master protocol v%s",
masterProtocolVersion.c_str());
ret = handshake(Protocol::PROTOCOL_VERSION_V1_0);
}
else {
SEISCOMP_ERROR("Unsupported master protocol v%s",
masterProtocolVersion.c_str());
}
}
if ( ret != Core::Status::SEISCOMP_SUCCESS ) {
shutdown();
return ret;
}
_isConnected = true;
if ( _connectionInfo ) _connectionInfo->start();
return Core::Status::SEISCOMP_SUCCESS;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int SystemConnection::reconnect()
{
if (isConnected())
disconnect();
int ret = connect(_masterAddress, _clientName, _peerGroup,
_type, _priority, _timeOut);
if (ret == Core::Status::SEISCOMP_SUCCESS )
{
for (std::set<std::string>::iterator it = _subscriptions.begin(); it != _subscriptions.end(); it++)
subscribe(*it);
SEISCOMP_INFO("Client is reconnected to master client");
}
return ret;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int SystemConnection::disconnect()
{
if (!isConnected())
return Core::Status::SEISCOMP_NOT_CONNECTED_ERROR;
// Ok, send disconnect request to the master client.
ServiceMessage disconnectMsg(Protocol::CLIENT_DISCONNECTED_MSG, _type, _priority,
_networkInterface->privateGroup());
if (send(_privateMasterGroup, Protocol::CLIENT_DISCONNECTED_MSG, &disconnectMsg) < 0)
SEISCOMP_ERROR("Could not send disconnect message to server");
_groups.clear();
// Clear the message queue and delete all remaining messages
while (!_messageQueue.empty())
{
delete _messageQueue.front();
_messageQueue.pop();
}
return shutdown();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool SystemConnection::isConnected()
{
return _networkInterface->isConnected() && _isConnected;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int SystemConnection::subscribe(const std::string& group)
{
if (!isConnected())
return Core::Status::SEISCOMP_NOT_CONNECTED_ERROR;
_archiveRequested = true;
int ret = 0;
if (!isGroupAvailable(group))
{
SEISCOMP_ERROR("Group: %s does not exits!", group.c_str());
return Core::Status::SEISCOMP_INVALID_GROUP_ERROR;
}
if (group == Protocol::MASTER_GROUP)
{
SEISCOMP_INFO("Group is solely for private communication: %s", group.c_str());
return Core::Status::SEISCOMP_INVALID_GROUP_ERROR;
}
_subscriptions.insert(group);
SEISCOMP_INFO("Joining group: %s", group.c_str());
ret = _networkInterface->subscribe(group);
if (ret != Core::Status::SEISCOMP_SUCCESS)
{
SEISCOMP_ERROR("Could not subscribe to group: %s", group.c_str());
return ret;
}
return Core::Status::SEISCOMP_SUCCESS;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int SystemConnection::unsubscribe(const std::string& group)
{
if (!isConnected())
return Core::Status::SEISCOMP_NOT_CONNECTED_ERROR;
int ret = 0;
if (!isGroupAvailable(group))
{
SEISCOMP_ERROR("Group: %s does not exits!", group.c_str());
return Core::Status::SEISCOMP_INVALID_GROUP_ERROR;
}
if (group == Protocol::MASTER_GROUP)
{
SEISCOMP_INFO("Group is solely for private communication: %s", group.c_str());
return Core::Status::SEISCOMP_INVALID_GROUP_ERROR;
}
_subscriptions.erase(group);
ret = _networkInterface->unsubscribe(group);
if (ret != Core::Status::SEISCOMP_SUCCESS)
{
SEISCOMP_ERROR("Could not unsubscribe group: %s", group.c_str());
return ret;
}
return Core::Status::SEISCOMP_SUCCESS;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int SystemConnection::subscribeArchive(const std::string& group)
{
if (!isConnected())
return Core::Status::SEISCOMP_NOT_CONNECTED_ERROR;
if (!isGroupAvailable(group))
{
SEISCOMP_ERROR("Group: %s does not exits!", group.c_str());
return Core::Status::SEISCOMP_INVALID_GROUP_ERROR;
}
if (group == Protocol::MASTER_GROUP)
{
SEISCOMP_INFO("Group is solely for private communication: %s", group.c_str());
return Core::Status::SEISCOMP_INVALID_GROUP_ERROR;
}
_subscribedArchiveGroups.insert(group);
return Core::Status::SEISCOMP_SUCCESS;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int SystemConnection::unsubscribeArchive(const std::string& group)
{
if (!isConnected())
return Core::Status::SEISCOMP_NOT_CONNECTED_ERROR;
if (!isGroupAvailable(group))
{
SEISCOMP_ERROR("Group: %s does not exits!", group.c_str());
return Core::Status::SEISCOMP_INVALID_GROUP_ERROR;
}
if (group == Protocol::MASTER_GROUP)
{
SEISCOMP_INFO("Group is solely for private communication: %s", group.c_str());
return Core::Status::SEISCOMP_INVALID_GROUP_ERROR;
}
_subscribedArchiveGroups.erase(group);
return Core::Status::SEISCOMP_SUCCESS;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool SystemConnection::poll() const
{
return _networkInterface->poll();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
const std::string& SystemConnection::peerGroup() const
{
return _peerGroup;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
const std::string& SystemConnection::masterAddress() const
{
return _masterAddress;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
std::string SystemConnection::privateGroup() const
{
return _networkInterface->privateGroup();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Seiscomp::Communication::Protocol::ClientType SystemConnection::type() const
{
return _type;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Seiscomp::Communication::Protocol::ClientPriority SystemConnection::priority() const
{
return _priority;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int SystemConnection::readNetworkMessage(bool blocking)
{
while (true)
{
std::auto_ptr<NetworkMessage> message;
int error = 0;
{
#if (BOOST_VERSION >= 103500)
boost::try_mutex::scoped_try_lock l(_readBufferMutex, boost::defer_lock);
#else
boost::try_mutex::scoped_try_lock l(_readBufferMutex, false);
#endif
if ( !blocking ) {
if ( !l.try_lock() || !poll())
return Core::Status::SEISCOMP_FAILURE;
}
else
l.lock();
message = std::auto_ptr<NetworkMessage>(_networkInterface->receive(&error));
}
if (message.get() == NULL)
{
if (error == Core::Status::SEISCOMP_NOT_CONNECTED_ERROR)
{
SEISCOMP_DEBUG("Connection has been closed while reading from network");
return Core::Status::SEISCOMP_NOT_CONNECTED_ERROR;
}
else if (error == Core::Status::SEISCOMP_NETWORKING_ERROR)
{
if ( _networkInterface->isConnected() ) {
SEISCOMP_ERROR("Error during reading attempt: (%i)", error);
shutdown();
}
return Core::Status::SEISCOMP_NETWORKING_ERROR;
}
else
continue;
}
//SEISCOMP_DEBUG("= seiscomp message =");
// Data message
if (message->type() > 0)
{
// NOTE: This can be done automatically by a flag of the the connect call
if (message->privateSenderGroup() == _networkInterface->privateGroup())
{
/*
SEISCOMP_INFO("Sender is myself: %s -> Skipping message!",
message->privateSenderGroup().c_str());
*/
}
else if (message->type() == Protocol::ARCHIVE_MSG)
{
std::string dest = message->destination();
if (_subscribedArchiveGroups.find(dest) != _subscribedArchiveGroups.end())
{
//boost::mutex::scoped_lock l(messageQueueMutex);
queueMessage(message);
return Core::Status::SEISCOMP_SUCCESS;
}
}
else
{
//boost::mutex::scoped_lock l(messageQueueMutex);
queueMessage(message);
return Core::Status::SEISCOMP_SUCCESS;
}
}
// Service message
else if (message->type() < 0)
{
ServiceMessage *sm = static_cast<ServiceMessage*>(message.get());
switch (sm->type())
{
case Protocol::MASTER_DISCONNECTED_MSG:
SEISCOMP_INFO("Received %s msg - Shutting down connection", Protocol::MsgTypeToString(sm->type()));
shutdown();
return Core::Status::SEISCOMP_NOT_CONNECTED_ERROR;
case Protocol::CLIENT_DISCONNECTED_MSG:
case Protocol::JOIN_GROUP_MSG:
queueMessage(message);
return Core::Status::SEISCOMP_SUCCESS;
case Protocol::LEAVE_GROUP_MSG:
queueMessage(message);
return Core::Status::SEISCOMP_SUCCESS;
case Protocol::INVAlID_ARCHIVE_REQUEST_MSG:
break;
case Protocol::CLIENT_DISCONNECT_CMD_MSG:
SEISCOMP_INFO("Received %s Closing application...", Protocol::MsgTypeToString(sm->type()));
disconnect();
exit(Core::Status::SEISCOMP_SUCCESS);
case Protocol::STATE_OF_HEALTH_CMD_MSG:
// sm->setData(sm->privateSenderGroup());
sm->setData(ConnectionInfo::Instance()->info(this));
sm->setType(Protocol::STATE_OF_HEALTH_RESPONSE_MSG);
SEISCOMP_DEBUG("Sending SOH response message to %s", sm->privateSenderGroup().c_str());
send(sm->privateSenderGroup(), sm);
break;
case Protocol::STATE_OF_HEALTH_RESPONSE_MSG:
{
queueMessage(message);
return Core::Status::SEISCOMP_SUCCESS;
}
case Protocol::LIST_CONNECTED_CLIENTS_RESPONSE_MSG:
{
queueMessage(message);
return Core::Status::SEISCOMP_SUCCESS;
}
case Protocol::REJECTED_CMD_MSG:
{
queueMessage(message);
return Core::Status::SEISCOMP_SUCCESS;
}
default:
break;
}
}
else
SEISCOMP_INFO("Undefined message received!");
}
return Core::Status::SEISCOMP_FAILURE;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int SystemConnection::send(NetworkMessage* msg)
{
return send(_peerGroup, msg);
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int SystemConnection::send(const std::string& groupname, NetworkMessage* msg)
{
if (!isConnected())
return Core::Status::SEISCOMP_NOT_CONNECTED_ERROR;
if (groupname == Protocol::MASTER_GROUP)
{
SEISCOMP_ERROR("You cannot be a regular member of group: %s", groupname.c_str());
return Core::Status::SEISCOMP_INVALID_GROUP_ERROR;
}
if ( (isGroupAvailable(groupname) == false &&
groupname != _privateMasterGroup) ||
(groupname == Protocol::ADMIN_GROUP && _peerGroup != Protocol::ADMIN_GROUP) )
{
if (groupname == Protocol::LISTENER_GROUP)
SEISCOMP_ERROR("You cannot send to %s!", Protocol::LISTENER_GROUP.c_str());
else
SEISCOMP_ERROR("Group: %s does not exist!", groupname.c_str());
return Core::Status::SEISCOMP_INVALID_GROUP_ERROR;
}
// Before we send this message, read (nonblocking) all available messages from
// the queue to make sure not to miss a service message which we should react upon.
while (readNetworkMessage(false) == Core::Status::SEISCOMP_SUCCESS);
if (!isConnected())
return Core::Status::SEISCOMP_NOT_CONNECTED_ERROR;
msg->setPrivateSenderGroup(_networkInterface->privateGroup());
msg->setDestination(groupname);
return (int)send(_privateMasterGroup, msg->type(), msg);
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int SystemConnection::send(const std::string& group, int type, NetworkMessage* msg)
{
boost::mutex::scoped_lock l(_writeBufferMutex);
int ret = _networkInterface->send(group, type, msg);
if (ret != Core::Status::SEISCOMP_SUCCESS)
{
SEISCOMP_ERROR("Could not send message to server: %s, due to error: %d", _masterAddress.c_str(), ret);
return ret;
}
++_messageStat->totalSentMessages;
_messageStat->summedMessageSize += msg->size();
return Core::Status::SEISCOMP_SUCCESS;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int SystemConnection::queuedMessageCount() const
{
boost::mutex::scoped_lock l(_messageQueueMutex);
return _messageQueue.size();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int SystemConnection::shutdown()
{
_archiveRequested = false;
_isConnected = false;
if (_networkInterface->isConnected())
{
int ret = _networkInterface->disconnect();
if (ret != Core::Status::SEISCOMP_SUCCESS)
{
SEISCOMP_ERROR("Could not properly disconnect!");
return Core::Status::SEISCOMP_NETWORKING_ERROR;
}
}
return Core::Status::SEISCOMP_SUCCESS;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool SystemConnection::isGroupAvailable(const std::string& group)
{
std::vector<std::string>::iterator found;
found = find(_groups.begin(), _groups.end(), group);
return (found != _groups.end() ||
group == Protocol::STATUS_GROUP ||
group == Protocol::ADMIN_GROUP);
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void SystemConnection::queueMessage(NetworkMessage *message)
{
boost::mutex::scoped_lock l(_messageQueueMutex);
_messageQueue.push(message);
++_messageStat->totalReceivedMessages;
_messageStat->summedMessageQueueSize += _messageQueue.size();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void SystemConnection::queueMessage(std::auto_ptr<NetworkMessage>& message)
{
queueMessage(message.release());
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
NetworkMessage* SystemConnection::receive(bool blocking, int *error)
{
if (error)
*error = Core::Status::SEISCOMP_SUCCESS;
if (/*blocking == true && */queuedMessageCount() == 0)
{
int ret = readNetworkMessage(blocking);
if (error) *error = ret;
if (ret != Core::Status::SEISCOMP_SUCCESS)
return NULL;
}
NetworkMessage* message = readLocalMessage();
// Archive message to have a possibility to start an archive request
// later on.
if (message != NULL)
_archiveMsgLen = message->write(_archiveMsg, Protocol::STD_MSG_LEN);
return message;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
NetworkMessage* SystemConnection::readLocalMessage()
{
boost::mutex::scoped_lock l(_messageQueueMutex);
NetworkMessage *msg = NULL;
if (!_messageQueue.empty())
{
msg = _messageQueue.front();
_messageQueue.pop();
}
return msg;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int SystemConnection::archiveRequest()
{
if (_archiveRequested)
{
SEISCOMP_INFO( "Archived messages have been requested before or\n\
this call has not been placed directly after connect!\n\
To set another request connect again to the server!" );
return Core::Status::SEISCOMP_ARCHIVE_REQUEST_ERROR;
}
_archiveRequested = true;
// Read backup message (Last message read from the queue)
const Seiscomp::Environment* env = Seiscomp::Environment::Instance();
std::string archiveFilePath = env->archiveFileName( _clientName.c_str() );
std::fstream archiveFile( archiveFilePath.c_str(), std::ios::in );
std::string line;
if (archiveFile.is_open())
getline( archiveFile, line, '\0' );
else
{
SEISCOMP_ERROR( "Could not open file: %s", archiveFilePath.c_str( ) );
return Core::Status::SEISCOMP_ARCHIVE_REQUEST_ERROR;
}
if (line.empty())
{
SEISCOMP_INFO("Archive file was empty: %s", archiveFilePath.c_str());
return Core::Status::SEISCOMP_ARCHIVE_REQUEST_ERROR;
}
archiveFile.close();
NetworkMessage msg;
msg.read(line.c_str(), line.size());
ServiceMessage sm(Protocol::ARCHIVE_REQUEST_MSG);
sm.setArchiveTimestamp(msg.timestamp());
sm.setArchiveSeqNum(msg.seqNum());
SEISCOMP_DEBUG("Message: %s MessageID: %d seqNum: %d timestamp: %d",
Protocol::MsgTypeToString(sm.type()),
sm.type(),
sm.archiveSeqNum(),
(int) sm.archiveTimestamp());
if (poll() || queuedMessageCount() > 0)
std::cout << "There are messages in the queue!" << std::endl;
send(_privateMasterGroup, &sm);
return Core::Status::SEISCOMP_SUCCESS;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int SystemConnection::groupCount() const
{
return _groups.size();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
const char* SystemConnection::group(int i) const
{
if ( i >= groupCount() || i < 0 )
return NULL;
return _groups[i].c_str();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
std::vector<std::string> SystemConnection::groups() const
{
return _groups;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
const std::string& SystemConnection::password() const
{
return _password;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void SystemConnection::setPassword(const std::string& password)
{
_password = password;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int SystemConnection::listen(ListenMode mode)
{
int ret = 0;
if (isListening())
{
SEISCOMP_DEBUG("Already listening");
return 0;
}
if (!isConnected())
return 0;
if (mode == THREADED)
{
SEISCOMP_DEBUG("Creating worker thread");
boost::thread thrd(boost::bind(&SystemConnection::listen, this, NON_THREADED));
boost::thread::yield();
return 0;
}
SEISCOMP_DEBUG("Entering listening state");
_isListening = true;
_stopRequested = false;
while (!_stopRequested)
ret += readNetworkMessage(true);
_isListening = false;
SEISCOMP_DEBUG("Leaving listening state");
return ret;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void SystemConnection::stopListening()
{
_stopRequested = true;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool SystemConnection::isListening() const
{
return _isListening;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
const MessageStat& SystemConnection::messageStat() const
{
return *_messageStat;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
const NetworkInterface* SystemConnection::networkInterface() const
{
return _networkInterface.get();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
void SystemConnection::setSequenceNumber(int64_t seq)
{
_networkInterface->setSequenceNumber(seq);
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int64_t SystemConnection::getSequenceNumber() const
{
return _networkInterface->getSequenceNumber();
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Core::Version SystemConnection::schemaVersion() const
{
return _schemaVersion;
}
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
} // namespace Communication
} // namespace Seiscomp
| 29.506887 | 116 | 0.549809 | [
"vector"
] |
67a664e35f20eecb4a08b82c0deade4cecb5fbe8 | 3,612 | hpp | C++ | frame/common.hpp | joydit/solidframe | 0539b0a1e77663ac4c701a88f56723d3e3688e8c | [
"BSL-1.0"
] | null | null | null | frame/common.hpp | joydit/solidframe | 0539b0a1e77663ac4c701a88f56723d3e3688e8c | [
"BSL-1.0"
] | null | null | null | frame/common.hpp | joydit/solidframe | 0539b0a1e77663ac4c701a88f56723d3e3688e8c | [
"BSL-1.0"
] | null | null | null | // frame/common.hpp
//
// Copyright (c) 2007, 2008, 2013 Valentin Palade (vipalade @ gmail . com)
//
// This file is part of SolidFrame framework.
//
// 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 SOLID_FRAME_COMMON_HPP
#define SOLID_FRAME_COMMON_HPP
#include <utility>
#include "utility/common.hpp"
#include "system/convertors.hpp"
namespace solid{
namespace frame{
//! Some return values
// enum RetValEx {
// LEAVE = CONTINUE + 1,
// REGISTER, UNREGISTER, RTOUT, WTOUT, DONE
// };
//! Some signals
enum SignalE{
//simple:
S_RAISE = 1,
S_UPDATE = 2,
S_SIG = 4,
S_KILL = 1<<8,
S_IDLE = 1<<9,
S_ERR = 1<<10,
S_STOP = 1<<11,
};
//! Some events
enum EventE{
EventNone = 0,
EventDoneSuccess = 1, //Successfull asynchrounous completion
EventDoneError = 2,//Unsuccessfull asynchrounous completion
EventDoneRecv = 4,//Successfull input asynchrounous completion
EventDoneSend = 8,//Successfull output asynchrounous completion
EventTimeout = 16,//Unsuccessfull asynchrounous completion due to timeout
EventSignal = 32,
EventDoneIO = EventDoneRecv | EventDoneSend,
EventReschedule = 128,
EventTimeoutRecv = 256,
EventTimeoutSend = 512,
};
enum ConstE{
MAXTIMEOUT = (0xffffffffUL>>1)/1000
};
#ifdef UINDEX32
typedef uint32 IndexT;
#elif defined(UINDEX64)
typedef uint64 IndexT;
#else
typedef size_t IndexT;
#endif
#define ID_MASK ((frame::IndexT)-1)
#define INVALID_INDEX ID_MASK
typedef std::pair<IndexT, uint32> UidT;
typedef UidT ObjectUidT;
typedef UidT MessageUidT;
typedef UidT FileUidT;
typedef UidT RequestUidT;
enum{
IndexBitCount = sizeof(IndexT) * 8,
};
inline const UidT& invalid_uid(){
static const UidT u(INVALID_INDEX, 0xffffffff);
return u;
}
inline bool is_valid_index(const IndexT &_idx){
return _idx != INVALID_INDEX;
}
inline bool is_invalid_index(const IndexT &_idx){
return _idx == INVALID_INDEX;
}
inline bool is_valid_uid(const UidT &_ruid){
return is_invalid_index(_ruid.first);
}
inline bool is_invalid_uid(const UidT &_ruid){
return is_invalid_index(_ruid.first);
}
template <typename T>
T unite_index(T _hi, const T &_lo, const int _hibitcnt);
template <typename T>
void split_index(T &_hi, T &_lo, const int _hibitcnt, const T &_v);
template <>
inline uint32 unite_index<uint32>(uint32 _hi, const uint32 &_lo, const int /*_hibitcnt*/){
return bit_revert(_hi) | _lo;
}
template <>
inline uint64 unite_index<uint64>(uint64 _hi, const uint64 &_lo, const int /*_hibitcnt*/){
return bit_revert(_hi) | _lo;
}
template <>
inline void split_index<uint32>(uint32 &_hi, uint32 &_lo, const int _hibitcnt, const uint32 &_v){
const uint32 lomsk = bitsToMask(32 - _hibitcnt);//(1 << (32 - _hibitcnt)) - 1;
_lo = _v & lomsk;
_hi = bit_revert(_v & (~lomsk));
}
template <>
inline void split_index<uint64>(uint64 &_hi, uint64 &_lo, const int _hibitcnt, const uint64 &_v){
const uint64 lomsk = bitsToMask(64 - _hibitcnt);//(1ULL << (64 - _hibitcnt)) - 1;
_lo = _v & lomsk;
_hi = bit_revert(_v & (~lomsk));
}
template <class V>
typename V::value_type& safe_at(V &_v, uint _pos){
if(_pos < _v.size()){
return _v[_pos];
}else{
_v.resize(_pos + 1);
return _v[_pos];
}
}
template <class V>
IndexT smart_resize(V &_rv, const IndexT &_rby){
_rv.resize(((_rv.size() / _rby) + 1) * _rby);
return _rv.size();
}
template <class V>
IndexT fast_smart_resize(V &_rv, const size_t _bitby){
_rv.resize(((_rv.size() >> _bitby) + 1) << _bitby);
return _rv.size();
}
}//namespace frame
}//namespace solid
#endif
| 22.716981 | 97 | 0.712625 | [
"solid"
] |
67a770efdde6c87c700baef78b0e67d5a12d3565 | 15,143 | cpp | C++ | src/main/cpp/auton/primitives/DrivePath.cpp | Team302/2021Year1 | ca674e3a001893da40b8b36173cbe96cc3cb027f | [
"BSD-3-Clause",
"MIT"
] | null | null | null | src/main/cpp/auton/primitives/DrivePath.cpp | Team302/2021Year1 | ca674e3a001893da40b8b36173cbe96cc3cb027f | [
"BSD-3-Clause",
"MIT"
] | null | null | null | src/main/cpp/auton/primitives/DrivePath.cpp | Team302/2021Year1 | ca674e3a001893da40b8b36173cbe96cc3cb027f | [
"BSD-3-Clause",
"MIT"
] | null | null | null | //====================================================================================================================================================
// Copyright 2020 Lake Orion Robotics FIRST Team 302
//
// 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.
//====================================================================================================================================================
//C++
#include <string>
#include <iostream>
//FRC Includes
#include <frc/controller/PIDController.h>
#include <frc/controller/ProfiledPIDController.h>
#include <units/angular_velocity.h>
// 302 Includes
#include <auton/primitives/DrivePath.h>
#include <utils/Logger.h>
#include <wpi/fs.h>
using namespace std;
using namespace frc;
using namespace wpi::math;
DrivePath::DrivePath() : m_chassis(ChassisFactory::GetChassisFactory()->GetIChassis()),
m_timer(make_unique<Timer>()),
m_currentChassisPosition(m_chassis.get()->GetPose()),
m_trajectory(),
m_runHoloController(false),
m_ramseteController(),
m_holoController(frc2::PIDController{1, 0, 0},
frc2::PIDController{1, 0, 0},
frc::ProfiledPIDController<units::radian>{1, 0, 0,
frc::TrapezoidProfile<units::radian>::Constraints{6.28_rad_per_s, 3.14_rad_per_s / 1_s}}),
//max velocity of 1 rotation per second and a max acceleration of 180 degrees per second squared.
m_PrevPos(m_chassis.get()->GetPose()),
m_PosChgTimer(make_unique<Timer>()),
m_timesRun(0),
m_targetPose(),
m_deltaX(0.0),
m_deltaY(0.0),
m_trajectoryStates(),
m_desiredState()
{
m_trajectoryStates.clear();
}
void DrivePath::Init(PrimitiveParams *params)
{
auto m_pathname = params->GetPathName(); //Grabs path name from auton xml
Logger::GetLogger()->ToNtTable("DrivePath" + m_pathname, "Initialized", "False");
Logger::GetLogger()->ToNtTable("DrivePath" + m_pathname, "Running", "False");
Logger::GetLogger()->ToNtTable("DrivePath" + m_pathname, "Done", "False");
Logger::GetLogger()->ToNtTable("DrivePath" + m_pathname, "WhyDone", "Not done");
Logger::GetLogger()->ToNtTable("DrivePath" + m_pathname, "Times Ran", 0);
m_trajectoryStates.clear(); //Clears the primitive of previous path/trajectory
m_wasMoving = false;
Logger::GetLogger()->ToNtTable("DrivePath" + m_pathname, "Initialized", "True"); //Signals that drive path is initialized in the console
GetTrajectory(params->GetPathName()); //Parses path from json file based on path name given in xml
Logger::GetLogger()->ToNtTable(m_pathname + "Trajectory", "Time", m_trajectory.TotalTime().to<double>());// Debugging
if (!m_trajectoryStates.empty()) // only go if path name found
{
m_desiredState = m_trajectoryStates.front(); //m_desiredState is the first state, or starting position
m_timer.get()->Reset(); //Restarts and starts timer
m_timer.get()->Start();
Logger::GetLogger()->ToNtTable("DrivePathValues", "CurrentPosX", m_currentChassisPosition.X().to<double>());
Logger::GetLogger()->ToNtTable("DrivePathValues", "CurrentPosY", m_currentChassisPosition.Y().to<double>());
Logger::GetLogger()->ToNtTable("Deltas", "iDeltaX", "0");
Logger::GetLogger()->ToNtTable("Deltas", "iDeltaX", "0");
//A timer used for position change detection
m_PosChgTimer.get()->Reset();
m_PosChgTimer.get()->Start(); // start scan timer to detect motion
//Is used to determine what controller/ "drive mode" pathweaver will run in
//Holo / Holonomic = Swerve X, y, z movement Ramsete = Differential / Tank x, y movement
if (m_runHoloController)
{
m_holoController.SetEnabled(true);
}
else
{
m_ramseteController.SetEnabled(true);
}
//Sampling means to grab a state based on the time, if we want to know what state we should be running at 5 seconds,
//we will sample the 5 second state.
auto targetState = m_trajectory.Sample(m_trajectory.TotalTime()); //"Samples" or grabs the position we should be at based on time
m_targetPose = targetState.pose; //Target pose represents the pose that we want to be at, based on the target state from above
auto currPose = m_chassis.get()->GetPose(); //Grabs the current pose of the robot to compare to the target pose
auto trans = m_targetPose - currPose; //Translation / Delta of the target pose and current pose
m_deltaX = trans.X().to<double>(); //Separates the delta "trans" from above into two variables for x and y
m_deltaY = trans.Y().to<double>();
//m_chassis.get()->RunWPIAlgorithm(true); //Determines what pose estimation method we will use, we have a few using different methods/equations
}
m_timesRun = 0;
}
void DrivePath::Run()
{
Logger::GetLogger()->ToNtTable("DrivePath" + m_pathname, "Running", "True");
if (!m_trajectoryStates.empty()) //If we have a path parsed / have states to run
{
// debugging
m_timesRun++;
Logger::GetLogger()->ToNtTable("DrivePath" + m_pathname, "Times Ran", m_timesRun);
// calculate where we are and where we want to be
CalcCurrentAndDesiredStates();
// Use the controller to calculate the chassis speeds for getting there
auto refChassisSpeeds = m_runHoloController ? m_holoController.Calculate(m_currentChassisPosition, m_desiredState, m_desiredState.pose.Rotation()) :
m_ramseteController.Calculate(m_currentChassisPosition, m_desiredState);
// debugging
Logger::GetLogger()->ToNtTable("DrivePathValues", "ChassisSpeedsX", refChassisSpeeds.vx());
Logger::GetLogger()->ToNtTable("DrivePathValues", "ChassisSpeedsY", refChassisSpeeds.vy());
Logger::GetLogger()->ToNtTable("DrivePathValues", "ChassisSpeedsZ", units::degrees_per_second_t(refChassisSpeeds.omega()).to<double>());
// Run the chassis
m_chassis->Drive(refChassisSpeeds);
}
else //If we don't have states to run, don't move the robot
{
ChassisSpeeds speeds;
speeds.vx = 0_mps;
speeds.vy = 0_mps;
speeds.omega = units::angular_velocity::radians_per_second_t(0);
m_chassis->Drive(speeds);
}
}
bool DrivePath::IsDone() //Default primitive function to determine if the primitive is done running
{
bool isDone = false;
string whyDone = ""; //debugging variable that we used to determine why the path was stopping
if (!m_trajectoryStates.empty()) //If we have states...
{
// Check if the current pose and the trajectory's final pose are the same
auto curPos = m_chassis.get()->GetPose();
//isDone = IsSamePose(curPos, m_targetPose, 100.0);
if (IsSamePose(curPos, m_targetPose, 100.0))
{
isDone = true;
whyDone = "Current Pose = Trajectory final pose";
}
if ( !isDone )
{
// Now check if the current pose is getting closer or farther from the target pose
auto trans = m_targetPose - curPos;
auto thisDeltaX = trans.X().to<double>();
auto thisDeltaY = trans.Y().to<double>();
if (abs(thisDeltaX) < m_deltaX && abs(thisDeltaY) < m_deltaY)
{ // Getting closer so just update the deltas
m_deltaX = thisDeltaX;
m_deltaY = thisDeltaY;
}
else
{ // Getting farther away: determine if it is because of the path curvature (not straight line between start and the end)
// or because we went past the target (in this case, we are done)
// Assume that once we get within a tenth of a meter (just under 4 inches), if we get
// farther away we are passing the target, so we should stop. Otherwise, keep trying.
isDone = ((abs(m_deltaX) < 0.1 && abs(m_deltaY) < 0.1));
if ((abs(m_deltaX) < 0.1 && abs(m_deltaY) < 0.1))
{
whyDone = "Within 4 inches of target or getting farther away from target";
}
}
}
if (m_PosChgTimer.get()->Get() > 1_s)//This if statement makes sure that we aren't checking for position change right at the start
{ //caused problems that would signal we are done when the path hasn't started
//auto moving = !IsSamePose(curPos, m_PrevPos, 7.5);
auto moving = m_chassis.get()->IsMoving(); //Is moving checks to make sure we are moving
if (!moving && m_wasMoving) //If we aren't moving and last state we were moving, then...
{
isDone = true;
whyDone = "Stopped moving";
}
m_PrevPos = curPos;
m_wasMoving = moving;
}
// finally, do it based on time (we have no more states); if we want to keep
// going, we need to understand where in the trajectory we are, so we can generate
// a new state.
if (!isDone)
{
//return (units::second_t(m_timer.get()->Get()) >= m_trajectory.TotalTime());
}
}
else
{
Logger::GetLogger()->ToNtTable("DrivePath" + m_pathname, "Done", "True");
return true;
}
if (isDone)
{ //debugging
Logger::GetLogger()->ToNtTable("DrivePath" + m_pathname, "Done", "True");
Logger::GetLogger()->ToNtTable("DrivePath" + m_pathname, "WhyDone", whyDone);
Logger::GetLogger()->LogError(Logger::LOGGER_LEVEL::PRINT, "DrivePath" + m_pathname, "Is done because: " + whyDone);
}
return isDone;
}
bool DrivePath::IsSamePose(frc::Pose2d lCurPos, frc::Pose2d lPrevPos, double tolerance) //position checking functions
{
// Detect if the two poses are the same within a tolerance
double dCurPosX = lCurPos.X().to<double>() * 1000; //cm
double dCurPosY = lCurPos.Y().to<double>() * 1000;
double dPrevPosX = lPrevPos.X().to<double>() * 1000;
double dPrevPosY = lPrevPos.Y().to<double>() * 1000;
double dDeltaX = abs(dPrevPosX - dCurPosX);
double dDeltaY = abs(dPrevPosY - dCurPosY);
Logger::GetLogger()->ToNtTable("Deltas", "iDeltaX", to_string(dDeltaX));
Logger::GetLogger()->ToNtTable("Deltas", "iDeltaY", to_string(dDeltaY));
// If Position of X or Y has moved since last scan.. Using Delta X/Y
return (dDeltaX <= tolerance && dDeltaY <= tolerance);
}
void DrivePath::GetTrajectory //Parses pathweaver json to create a series of points that we can drive the robot to
(
string path
)
{
if (!path.empty()) // only go if path name found
{
Logger::GetLogger()->LogError(string("DrivePath" + m_pathname), string("Finding Deploy Directory"));
// Read path into trajectory for deploy directory. JSON File ex. Bounce1.wpilid.json
wpi::SmallString<64> deployDir; //creates a string variable
//frc::filesystem::GetDeployDirectory(deployDir); //grabs the deploy directory: "/lvuser/deploy" on roborio
//wpi::sys::path::append(deployDir, "paths"); //goes into "/lvuser/deploy/paths" on roborio
//wpi::sys::path::append(deployDir, path); // load path from deploy directory
deployDir = "/users/lvuser/deploy/paths/" + m_pathname;
Logger::GetLogger()->LogError(string("Deploy path is "), deployDir.c_str()); //Debugging
m_trajectory = frc::TrajectoryUtil::FromPathweaverJson(deployDir); //Creates a trajectory or path that can be used in the code, parsed from pathweaver json
m_trajectoryStates = m_trajectory.States(); //Creates a vector of all the states or "waypoints" the robot needs to get to
Logger::GetLogger()->LogError(string("DrivePath - Loaded = "), path);
Logger::GetLogger()->ToNtTable("DrivePathValues", "TrajectoryTotalTime", m_trajectory.TotalTime().to<double>());
}
}
void DrivePath::CalcCurrentAndDesiredStates()
{
m_currentChassisPosition = m_chassis.get()->GetPose(); //Grabs current pose / position
auto sampleTime = units::time::second_t(m_timer.get()->Get()); //+ 0.02 //Grabs the time that we should sample a state from
m_desiredState = m_trajectory.Sample(sampleTime); //Gets the target state based on the current time
// May need to do our own sampling based on position and time
Logger::GetLogger()->ToNtTable("DrivePathValues", "DesiredPoseX", m_desiredState.pose.X().to<double>());
Logger::GetLogger()->ToNtTable("DrivePathValues", "DesiredPoseY", m_desiredState.pose.Y().to<double>());
Logger::GetLogger()->ToNtTable("DrivePathValues", "DesiredPoseOmega", m_desiredState.pose.Rotation().Degrees().to<double>());
Logger::GetLogger()->ToNtTable("DrivePathValues", "CurrentPosX", m_currentChassisPosition.X().to<double>());
Logger::GetLogger()->ToNtTable("DrivePathValues", "CurrentPosY", m_currentChassisPosition.Y().to<double>());
Logger::GetLogger()->ToNtTable("DrivePathValues", "CurrentPosOmega", m_desiredState.pose.Rotation().Degrees().to<double>());
Logger::GetLogger()->ToNtTable("DeltaValues", "DeltaX", m_desiredState.pose.X().to<double>() - m_currentChassisPosition.X().to<double>());
Logger::GetLogger()->ToNtTable("DeltaValues", "DeltaY", m_desiredState.pose.Y().to<double>() - m_currentChassisPosition.Y().to<double>());
Logger::GetLogger()->ToNtTable("DrivePathValues", "CurrentTime", m_timer.get()->Get().to<double>());
} | 49.165584 | 174 | 0.623721 | [
"vector"
] |
67ac2918a056d236dc883c1c9808ffb3f5990126 | 4,163 | cpp | C++ | IET/RigidBodyModel.cpp | anokta/CS7055-CS7057 | c1512eac8a9680f6e53ab3b70ce02492246211f4 | [
"MIT"
] | 5 | 2016-11-02T13:25:43.000Z | 2019-01-16T16:46:13.000Z | IET/RigidBodyModel.cpp | anokta/CS7055-CS7057 | c1512eac8a9680f6e53ab3b70ce02492246211f4 | [
"MIT"
] | null | null | null | IET/RigidBodyModel.cpp | anokta/CS7055-CS7057 | c1512eac8a9680f6e53ab3b70ce02492246211f4 | [
"MIT"
] | 1 | 2021-08-24T06:05:04.000Z | 2021-08-24T06:05:04.000Z | #include "RigidBodyModel.h"
#include "EntityManager.h"
#include "glm\gtx\quaternion.hpp"
#include "glm\gtx\transform.hpp"
using namespace glm;
bool RigidBodyModel::gizmo = false;
RigidBodyModel::RigidBodyModel(RigidBody *b, GenericShader * s, GenericShader * gs)
{
body = b;
modelShader = s;
lineShader = gs;
switch(body->GetType())
{
case RigidBody::BODY_TYPE::BOX:
modelMesh = MeshLoader::GenerateTexturedCubeMesh("..\\IET\\res\\box.jpg");
//MeshLoader::LoadMesh("..\\IET\\res\\block.dae", "..\\IET\\res\\block.tga");
textured = false;
break;
case RigidBody::BODY_TYPE::BALL:
modelMesh = MeshLoader::LoadBumpedMesh("..\\IET\\res\\Earth.dae", "..\\IET\\res\\Earth_D.tga", "..\\IET\\res\\Earth_N.tga");
textured = true;
break;
case RigidBody::BODY_TYPE::ELLIPSOID:
modelMesh = MeshLoader::GenerateSphereMesh(15); //MeshLoader::LoadMesh("..\\IET\\res\\teapot.off");//MeshLoader::GenerateSphereMesh(15);
textured = false;
//MeshLoader::LoadMesh("..\\IET\\res\\Mountain Bike.obj");//MeshLoader::GenerateSphereMesh(25);
break;
case RigidBody::BODY_TYPE::PLANE:
modelMesh = MeshLoader::GenerateCubeMesh();
textured = false;
break;
case RigidBody::BODY_TYPE::TETRAHEDRON:
modelMesh = MeshLoader::GenerateTetrahedron();//MeshLoader::GeneratePlaneMesh();
textured = false;
break;
case RigidBody::BODY_TYPE::TRIANGLE:
modelMesh = MeshLoader::GenerateTriangle();
textured = false;
break;
case RigidBody::BODY_TYPE::CAT:
modelMesh = MeshLoader::LoadMesh("..\\IET\\res\\block.dae", "..\\IET\\res\\block.tga");
//MeshLoader::LoadBumpedMesh("..\\IET\\res\\Apple_Of_Eden.dae", "..\\IET\\res\\AppleOfEden_D.tga", "..\\IET\\res\\AppleOfEden_N.tga");
textured = true;
break;
}
modelMesh->SetShader(modelShader);
body->SetPoints(modelMesh->GetVertices());
gizmos["BoundingBox"] = MeshLoader::GenerateBoundingBox();
gizmos["BoundingBox"]->SetShader(lineShader);
//gizmos["FurthestPoint"] = MeshLoader::GenerateBoundingSphere();
//gizmos["FurthestPoint"]->SetShader(lineShader);
gizmos["BetweenLine"] = MeshLoader::GenerateLine(vec4(1,0,1,1));
gizmos["BetweenLine"]->SetShader(lineShader);
EntityManager::GetInstance()->AddDrawable(this);
EntityManager::GetInstance()->AddUpdatable(this);
}
RigidBodyModel::~RigidBodyModel()
{
EntityManager::GetInstance()->RemoveDrawable(this);
EntityManager::GetInstance()->RemoveUpdatable(this);
delete body;
delete modelMesh;
for(auto gizmo : gizmos)
delete gizmo.second;
gizmos.clear();
}
void RigidBodyModel::ChangeShader(GenericShader * s)
{
modelShader = s;
modelMesh->SetShader(modelShader);
}
void RigidBodyModel::Draw()
{
// Render object
mat4 M = modelShader->GetModelMatrix();
modelShader->SetModelMatrix(M * body->GetTransformationMatrix());
modelMesh->Render(modelShader);
modelShader->SetModelMatrix(M);
// Render gizmos
if(gizmo)
{
gizmos["BetweenLine"]->Render(lineShader);
//gizmos["FurthestPoint"]->Render(lineShader);
M = lineShader->GetModelMatrix();
lineShader->SetModelMatrix(M * body->GetTransformationMatrix());
gizmos["BoundingBox"]->Render(lineShader);
lineShader->SetModelMatrix(M);
}
}
void RigidBodyModel::Update(float deltaTime)
{
body->Update(deltaTime);
}
bool RigidBodyModel::ResolveCollision(RigidBodyModel * rigidBodyModel)
{
if(body->CheckCollisionBroad(rigidBodyModel->GetBody()))
{
if(gizmoColor.r == 0)
gizmoColor = vec4(1,1,0,1);
if(rigidBodyModel->GetGizmoColor().r == 0)
rigidBodyModel->SetGizmoColor(vec4(1,1,0,1));
//std::cout << "Broad Collided. . . ";
RigidBody::Contact * contact = body->CheckCollisionNarrow(rigidBodyModel->GetBody());
if(contact != NULL)
{
//std::cout << "CP: " << contact->cA.x << "\t" << contact->cA.y << "\t" << contact->cA.z << std::endl;
body->RespondCollision(rigidBodyModel->GetBody(), contact->cA, contact->cB, contact->normal);
gizmos["BetweenLine"]->SetFromTo(vec3(), contact->normal);
delete contact;
//std::cout << "CP: " << contactNormal.x << "\t" << contactNormal.y << "\t" << contactNormal.z << std::endl;
//std::cout << "NARROW Collided. . . ";
return true;
}
}
return false;
} | 27.753333 | 138 | 0.696853 | [
"render",
"object",
"transform"
] |
67b1098fb458be72a1aead5d628e1058ca1a7f5a | 584 | cpp | C++ | codes/Leetcode/leetcode093.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/Leetcode/leetcode093.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/Leetcode/leetcode093.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
void dfs(int d, int p, string s, string c, vector<string>& ans) {
if (d == 4) {
if (p == s.size()) ans.push_back(c.substr(0, c.size()-1));
return;
}
int n = s[p] - '0';
c = c + s[p++];
dfs(d + 1, p, s, c + ".", ans);
if (n == 0) return;
while (p < s.size()) {
n = n * 10 + s[p] - '0';
if (n >= 0 && n <= 255) {
c = c + s[p++];
dfs(d + 1, p, s, c + ".", ans);
} else break;
}
}
vector<string> restoreIpAddresses(string s) {
vector<string> ans;
dfs(0, 0, s, "", ans);
return ans;
}
};
| 19.466667 | 67 | 0.443493 | [
"vector"
] |
67b2cd813230278613f87be28b3f68f84679ed3c | 79,393 | cpp | C++ | modules/3d/src/dls.cpp | GerHobbelt/opencv | 7b083a1a6481ffbff315c87248d56466cb806d8f | [
"Apache-2.0"
] | null | null | null | modules/3d/src/dls.cpp | GerHobbelt/opencv | 7b083a1a6481ffbff315c87248d56466cb806d8f | [
"Apache-2.0"
] | null | null | null | modules/3d/src/dls.cpp | GerHobbelt/opencv | 7b083a1a6481ffbff315c87248d56466cb806d8f | [
"Apache-2.0"
] | null | null | null | #include "precomp.hpp"
#include "dls.h"
#include <iostream>
#ifdef HAVE_EIGEN
# if defined __GNUC__ && defined __APPLE__
# pragma GCC diagnostic ignored "-Wshadow"
# endif
# if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable:4701) // potentially uninitialized local variable
# pragma warning(disable:4702) // unreachable code
# pragma warning(disable:4714) // const marked as __forceinline not inlined
# endif
# include <Eigen/Core>
# include <Eigen/Eigenvalues>
# if defined(_MSC_VER)
# pragma warning(pop)
# endif
# include "opencv2/core/eigen.hpp"
#endif
namespace cv {
dls::dls(const Mat& opoints, const Mat& ipoints)
{
N = std::max(opoints.checkVector(3, CV_32F), opoints.checkVector(3, CV_64F));
p = Mat(3, N, CV_64F);
z = Mat(3, N, CV_64F);
mn = Mat::zeros(3, 1, CV_64F);
cost__ = 9999;
f1coeff.resize(21);
f2coeff.resize(21);
f3coeff.resize(21);
if (opoints.depth() == ipoints.depth())
{
if (opoints.depth() == CV_32F)
init_points<Point3f, Point2f>(opoints, ipoints);
else
init_points<Point3d, Point2d>(opoints, ipoints);
}
else if (opoints.depth() == CV_32F)
init_points<Point3f, Point2d>(opoints, ipoints);
else
init_points<Point3d, Point2f>(opoints, ipoints);
}
dls::~dls()
{
// TODO Auto-generated destructor stub
}
bool dls::compute_pose(Mat& R, Mat& t)
{
std::vector<Mat> R_;
R_.push_back(rotx(CV_PI/2));
R_.push_back(roty(CV_PI/2));
R_.push_back(rotz(CV_PI/2));
// version that calls dls 3 times, to avoid Cayley singularity
for (int i = 0; i < 3; ++i)
{
// Make a random rotation
Mat pp = R_[i] * ( p - repeat(mn, 1, p.cols) );
// clear for new data
C_est_.clear();
t_est_.clear();
cost_.clear();
this->run_kernel(pp); // run dls_pnp()
// find global minimum
for (unsigned int j = 0; j < cost_.size(); ++j)
{
if( cost_[j] < cost__ )
{
t_est__ = t_est_[j] - C_est_[j] * R_[i] * mn;
C_est__ = C_est_[j] * R_[i];
cost__ = cost_[j];
}
}
}
if(C_est__.cols > 0 && C_est__.rows > 0)
{
C_est__.copyTo(R);
t_est__.copyTo(t);
return true;
}
return false;
}
void dls::run_kernel(const Mat& pp)
{
Mat Mtilde(27, 27, CV_64F);
Mat D = Mat::zeros(9, 9, CV_64F);
build_coeff_matrix(pp, Mtilde, D);
Mat eigenval_r, eigenval_i, eigenvec_r, eigenvec_i;
compute_eigenvec(Mtilde, eigenval_r, eigenval_i, eigenvec_r, eigenvec_i);
/*
* Now check the solutions
*/
// extract the optimal solutions from the eigen decomposition of the
// Multiplication matrix
Mat sols = Mat::zeros(3, 27, CV_64F);
std::vector<double> cost;
int count = 0;
for (int k = 0; k < 27; ++k)
{
// V(:,k) = V(:,k)/V(1,k);
Mat V_kA = eigenvec_r.col(k); // 27x1
Mat V_kB = Mat(1, 1, z.depth(), V_kA.at<double>(0)); // 1x1
Mat V_k; solve(V_kB.t(), V_kA.t(), V_k); // A/B = B'\A'
Mat( V_k.t()).copyTo( eigenvec_r.col(k) );
//if (imag(V(2,k)) == 0)
#ifdef HAVE_EIGEN
const double epsilon = 1e-4;
if( eigenval_i.at<double>(k,0) >= -epsilon && eigenval_i.at<double>(k,0) <= epsilon )
#endif
{
double stmp[3];
stmp[0] = eigenvec_r.at<double>(9, k);
stmp[1] = eigenvec_r.at<double>(3, k);
stmp[2] = eigenvec_r.at<double>(1, k);
Mat H = Hessian(stmp);
Mat eigenvalues, eigenvectors;
eigen(H, eigenvalues, eigenvectors);
if(positive_eigenvalues(&eigenvalues))
{
// sols(:,i) = stmp;
Mat stmp_mat(3, 1, CV_64F, &stmp);
stmp_mat.copyTo( sols.col(count) );
Mat Cbar = cayley2rotbar(stmp_mat);
Mat Cbarvec = Cbar.reshape(1,1).t();
// cost(i) = CbarVec' * D * CbarVec;
Mat cost_mat = Cbarvec.t() * D * Cbarvec;
cost.push_back( cost_mat.at<double>(0) );
count++;
}
}
}
// extract solutions
sols = sols.clone().colRange(0, count);
std::vector<Mat> C_est, t_est;
for (int j = 0; j < sols.cols; ++j)
{
// recover the optimal orientation
// C_est(:,:,j) = 1/(1 + sols(:,j)' * sols(:,j)) * cayley2rotbar(sols(:,j));
Mat sols_j = sols.col(j);
double sols_mult = 1./(1.+Mat( sols_j.t() * sols_j ).at<double>(0));
Mat C_est_j = cayley2rotbar(sols_j).mul(sols_mult);
C_est.push_back( C_est_j );
Mat A2 = Mat::zeros(3, 3, CV_64F);
Mat b2 = Mat::zeros(3, 1, CV_64F);
for (int i = 0; i < N; ++i)
{
Mat eye = Mat::eye(3, 3, CV_64F);
Mat z_mul = z.col(i)*z.col(i).t();
A2 += eye - z_mul;
b2 += (z_mul - eye) * C_est_j * pp.col(i);
}
// recover the optimal translation
Mat X2; solve(A2, b2, X2); // A\B
t_est.push_back(X2);
}
// check that the points are infront of the center of perspectivity
for (int k = 0; k < sols.cols; ++k)
{
Mat cam_points = C_est[k] * pp + repeat(t_est[k], 1, pp.cols);
Mat cam_points_k = cam_points.row(2);
if(is_empty(&cam_points_k))
{
Mat C_valid = C_est[k], t_valid = t_est[k];
double cost_valid = cost[k];
C_est_.push_back(C_valid);
t_est_.push_back(t_valid);
cost_.push_back(cost_valid);
}
}
}
void dls::build_coeff_matrix(const Mat& pp, Mat& Mtilde, Mat& D)
{
CV_Assert(!pp.empty() && N > 0);
Mat eye = Mat::eye(3, 3, CV_64F);
// build coeff matrix
// An intermediate matrix, the inverse of what is called "H" in the paper
// (see eq. 25)
Mat H = Mat::zeros(3, 3, CV_64F);
Mat A = Mat::zeros(3, 9, CV_64F);
Mat pp_i(3, 1, CV_64F);
Mat z_i(3, 1, CV_64F);
for (int i = 0; i < N; ++i)
{
z.col(i).copyTo(z_i);
A += ( z_i*z_i.t() - eye ) * LeftMultVec(pp.col(i));
}
H = eye.mul(N) - z * z.t();
// A\B
solve(H, A, A, DECOMP_NORMAL);
H.release();
Mat ppi_A(3, 1, CV_64F);
for (int i = 0; i < N; ++i)
{
z.col(i).copyTo(z_i);
ppi_A = LeftMultVec(pp.col(i)) + A;
D += ppi_A.t() * ( eye - z_i*z_i.t() ) * ppi_A;
}
A.release();
// fill the coefficients
fill_coeff(&D);
// generate random samples
std::vector<double> u(5);
randn(u, 0, 200);
Mat M2 = cayley_LS_M(f1coeff, f2coeff, f3coeff, u);
Mat M2_1 = M2(Range(0,27), Range(0,27));
Mat M2_2 = M2(Range(0,27), Range(27,120));
Mat M2_3 = M2(Range(27,120), Range(27,120));
Mat M2_4 = M2(Range(27,120), Range(0,27));
M2.release();
// A/B = B'\A'
Mat M2_5; solve(M2_3.t(), M2_2.t(), M2_5);
M2_2.release(); M2_3.release();
// construct the multiplication matrix via schur compliment of the Macaulay
// matrix
Mtilde = M2_1 - M2_5.t()*M2_4;
}
void dls::compute_eigenvec(const Mat& Mtilde, Mat& eigenval_real, Mat& eigenval_imag,
Mat& eigenvec_real, Mat& eigenvec_imag)
{
#ifdef HAVE_EIGEN
Eigen::MatrixXd Mtilde_eig, zeros_eig;
cv2eigen(Mtilde, Mtilde_eig);
cv2eigen(Mat::zeros(27, 27, CV_64F), zeros_eig);
Eigen::MatrixXcd Mtilde_eig_cmplx(27, 27);
Mtilde_eig_cmplx.real() = Mtilde_eig;
Mtilde_eig_cmplx.imag() = zeros_eig;
Eigen::ComplexEigenSolver<Eigen::MatrixXcd> ces;
ces.compute(Mtilde_eig_cmplx);
Eigen::MatrixXd eigval_real = ces.eigenvalues().real();
Eigen::MatrixXd eigval_imag = ces.eigenvalues().imag();
Eigen::MatrixXd eigvec_real = ces.eigenvectors().real();
Eigen::MatrixXd eigvec_imag = ces.eigenvectors().imag();
eigen2cv(eigval_real, eigenval_real);
eigen2cv(eigval_imag, eigenval_imag);
eigen2cv(eigvec_real, eigenvec_real);
eigen2cv(eigvec_imag, eigenvec_imag);
#else
EigenvalueDecomposition es(Mtilde);
eigenval_real = es.eigenvalues();
eigenvec_real = es.eigenvectors();
eigenval_imag = eigenvec_imag = Mat();
#endif
}
void dls::fill_coeff(const Mat * D_mat)
{
// TODO: shift D and coefficients one position to left
double D[10][10]; // put D_mat into array
for (int i = 0; i < D_mat->rows; ++i)
{
const double* Di = D_mat->ptr<double>(i);
for (int j = 0; j < D_mat->cols; ++j)
{
D[i+1][j+1] = Di[j];
}
}
// F1 COEFFICIENT
f1coeff[1] = 2*D[1][6] - 2*D[1][8] + 2*D[5][6] - 2*D[5][8] + 2*D[6][1] + 2*D[6][5] + 2*D[6][9] - 2*D[8][1] - 2*D[8][5] - 2*D[8][9] + 2*D[9][6] - 2*D[9][8]; // constant term
f1coeff[2] = 6*D[1][2] + 6*D[1][4] + 6*D[2][1] - 6*D[2][5] - 6*D[2][9] + 6*D[4][1] - 6*D[4][5] - 6*D[4][9] - 6*D[5][2] - 6*D[5][4] - 6*D[9][2] - 6*D[9][4]; // s1^2 * s2
f1coeff[3] = 4*D[1][7] - 4*D[1][3] + 8*D[2][6] - 8*D[2][8] - 4*D[3][1] + 4*D[3][5] + 4*D[3][9] + 8*D[4][6] - 8*D[4][8] + 4*D[5][3] - 4*D[5][7] + 8*D[6][2] + 8*D[6][4] + 4*D[7][1] - 4*D[7][5] - 4*D[7][9] - 8*D[8][2] - 8*D[8][4] + 4*D[9][3] - 4*D[9][7]; // s1 * s2
f1coeff[4] = 4*D[1][2] - 4*D[1][4] + 4*D[2][1] - 4*D[2][5] - 4*D[2][9] + 8*D[3][6] - 8*D[3][8] - 4*D[4][1] + 4*D[4][5] + 4*D[4][9] - 4*D[5][2] + 4*D[5][4] + 8*D[6][3] + 8*D[6][7] + 8*D[7][6] - 8*D[7][8] - 8*D[8][3] - 8*D[8][7] - 4*D[9][2] + 4*D[9][4]; //s1 * s3
f1coeff[5] = 8*D[2][2] - 8*D[3][3] - 8*D[4][4] + 8*D[6][6] + 8*D[7][7] - 8*D[8][8]; // s2 * s3
f1coeff[6] = 4*D[2][6] - 2*D[1][7] - 2*D[1][3] + 4*D[2][8] - 2*D[3][1] + 2*D[3][5] - 2*D[3][9] + 4*D[4][6] + 4*D[4][8] + 2*D[5][3] + 2*D[5][7] + 4*D[6][2] + 4*D[6][4] - 2*D[7][1] + 2*D[7][5] - 2*D[7][9] + 4*D[8][2] + 4*D[8][4] - 2*D[9][3] - 2*D[9][7]; // s2^2 * s3
f1coeff[7] = 2*D[2][5] - 2*D[1][4] - 2*D[2][1] - 2*D[1][2] - 2*D[2][9] - 2*D[4][1] + 2*D[4][5] - 2*D[4][9] + 2*D[5][2] + 2*D[5][4] - 2*D[9][2] - 2*D[9][4]; //s2^3
f1coeff[8] = 4*D[1][9] - 4*D[1][1] + 8*D[3][3] + 8*D[3][7] + 4*D[5][5] + 8*D[7][3] + 8*D[7][7] + 4*D[9][1] - 4*D[9][9]; // s1 * s3^2
f1coeff[9] = 4*D[1][1] - 4*D[5][5] - 4*D[5][9] + 8*D[6][6] - 8*D[6][8] - 8*D[8][6] + 8*D[8][8] - 4*D[9][5] - 4*D[9][9]; // s1
f1coeff[10] = 2*D[1][3] + 2*D[1][7] + 4*D[2][6] - 4*D[2][8] + 2*D[3][1] + 2*D[3][5] + 2*D[3][9] - 4*D[4][6] + 4*D[4][8] + 2*D[5][3] + 2*D[5][7] + 4*D[6][2] - 4*D[6][4] + 2*D[7][1] + 2*D[7][5] + 2*D[7][9] - 4*D[8][2] + 4*D[8][4] + 2*D[9][3] + 2*D[9][7]; // s3
f1coeff[11] = 2*D[1][2] + 2*D[1][4] + 2*D[2][1] + 2*D[2][5] + 2*D[2][9] - 4*D[3][6] + 4*D[3][8] + 2*D[4][1] + 2*D[4][5] + 2*D[4][9] + 2*D[5][2] + 2*D[5][4] - 4*D[6][3] + 4*D[6][7] + 4*D[7][6] - 4*D[7][8] + 4*D[8][3] - 4*D[8][7] + 2*D[9][2] + 2*D[9][4]; // s2
f1coeff[12] = 2*D[2][9] - 2*D[1][4] - 2*D[2][1] - 2*D[2][5] - 2*D[1][2] + 4*D[3][6] + 4*D[3][8] - 2*D[4][1] - 2*D[4][5] + 2*D[4][9] - 2*D[5][2] - 2*D[5][4] + 4*D[6][3] + 4*D[6][7] + 4*D[7][6] + 4*D[7][8] + 4*D[8][3] + 4*D[8][7] + 2*D[9][2] + 2*D[9][4]; // s2 * s3^2
f1coeff[13] = 6*D[1][6] - 6*D[1][8] - 6*D[5][6] + 6*D[5][8] + 6*D[6][1] - 6*D[6][5] - 6*D[6][9] - 6*D[8][1] + 6*D[8][5] + 6*D[8][9] - 6*D[9][6] + 6*D[9][8]; // s1^2
f1coeff[14] = 2*D[1][8] - 2*D[1][6] + 4*D[2][3] + 4*D[2][7] + 4*D[3][2] - 4*D[3][4] - 4*D[4][3] - 4*D[4][7] - 2*D[5][6] + 2*D[5][8] - 2*D[6][1] - 2*D[6][5] + 2*D[6][9] + 4*D[7][2] - 4*D[7][4] + 2*D[8][1] + 2*D[8][5] - 2*D[8][9] + 2*D[9][6] - 2*D[9][8]; // s3^2
f1coeff[15] = 2*D[1][8] - 2*D[1][6] - 4*D[2][3] + 4*D[2][7] - 4*D[3][2] - 4*D[3][4] - 4*D[4][3] + 4*D[4][7] + 2*D[5][6] - 2*D[5][8] - 2*D[6][1] + 2*D[6][5] - 2*D[6][9] + 4*D[7][2] + 4*D[7][4] + 2*D[8][1] - 2*D[8][5] + 2*D[8][9] - 2*D[9][6] + 2*D[9][8]; // s2^2
f1coeff[16] = 2*D[3][9] - 2*D[1][7] - 2*D[3][1] - 2*D[3][5] - 2*D[1][3] - 2*D[5][3] - 2*D[5][7] - 2*D[7][1] - 2*D[7][5] + 2*D[7][9] + 2*D[9][3] + 2*D[9][7]; // s3^3
f1coeff[17] = 4*D[1][6] + 4*D[1][8] + 8*D[2][3] + 8*D[2][7] + 8*D[3][2] + 8*D[3][4] + 8*D[4][3] + 8*D[4][7] - 4*D[5][6] - 4*D[5][8] + 4*D[6][1] - 4*D[6][5] - 4*D[6][9] + 8*D[7][2] + 8*D[7][4] + 4*D[8][1] - 4*D[8][5] - 4*D[8][9] - 4*D[9][6] - 4*D[9][8]; // s1 * s2 * s3
f1coeff[18] = 4*D[1][5] - 4*D[1][1] + 8*D[2][2] + 8*D[2][4] + 8*D[4][2] + 8*D[4][4] + 4*D[5][1] - 4*D[5][5] + 4*D[9][9]; // s1 * s2^2
f1coeff[19] = 6*D[1][3] + 6*D[1][7] + 6*D[3][1] - 6*D[3][5] - 6*D[3][9] - 6*D[5][3] - 6*D[5][7] + 6*D[7][1] - 6*D[7][5] - 6*D[7][9] - 6*D[9][3] - 6*D[9][7]; // s1^2 * s3
f1coeff[20] = 4*D[1][1] - 4*D[1][5] - 4*D[1][9] - 4*D[5][1] + 4*D[5][5] + 4*D[5][9] - 4*D[9][1] + 4*D[9][5] + 4*D[9][9]; // s1^3
// F2 COEFFICIENT
f2coeff[1] = - 2*D[1][3] + 2*D[1][7] - 2*D[3][1] - 2*D[3][5] - 2*D[3][9] - 2*D[5][3] + 2*D[5][7] + 2*D[7][1] + 2*D[7][5] + 2*D[7][9] - 2*D[9][3] + 2*D[9][7]; // constant term
f2coeff[2] = 4*D[1][5] - 4*D[1][1] + 8*D[2][2] + 8*D[2][4] + 8*D[4][2] + 8*D[4][4] + 4*D[5][1] - 4*D[5][5] + 4*D[9][9]; // s1^2 * s2
f2coeff[3] = 4*D[1][8] - 4*D[1][6] - 8*D[2][3] + 8*D[2][7] - 8*D[3][2] - 8*D[3][4] - 8*D[4][3] + 8*D[4][7] + 4*D[5][6] - 4*D[5][8] - 4*D[6][1] + 4*D[6][5] - 4*D[6][9] + 8*D[7][2] + 8*D[7][4] + 4*D[8][1] - 4*D[8][5] + 4*D[8][9] - 4*D[9][6] + 4*D[9][8]; // s1 * s2
f2coeff[4] = 8*D[2][2] - 8*D[3][3] - 8*D[4][4] + 8*D[6][6] + 8*D[7][7] - 8*D[8][8]; // s1 * s3
f2coeff[5] = 4*D[1][4] - 4*D[1][2] - 4*D[2][1] + 4*D[2][5] - 4*D[2][9] - 8*D[3][6] - 8*D[3][8] + 4*D[4][1] - 4*D[4][5] + 4*D[4][9] + 4*D[5][2] - 4*D[5][4] - 8*D[6][3] + 8*D[6][7] + 8*D[7][6] + 8*D[7][8] - 8*D[8][3] + 8*D[8][7] - 4*D[9][2] + 4*D[9][4]; // s2 * s3
f2coeff[6] = 6*D[5][6] - 6*D[1][8] - 6*D[1][6] + 6*D[5][8] - 6*D[6][1] + 6*D[6][5] - 6*D[6][9] - 6*D[8][1] + 6*D[8][5] - 6*D[8][9] - 6*D[9][6] - 6*D[9][8]; // s2^2 * s3
f2coeff[7] = 4*D[1][1] - 4*D[1][5] + 4*D[1][9] - 4*D[5][1] + 4*D[5][5] - 4*D[5][9] + 4*D[9][1] - 4*D[9][5] + 4*D[9][9]; // s2^3
f2coeff[8] = 2*D[2][9] - 2*D[1][4] - 2*D[2][1] - 2*D[2][5] - 2*D[1][2] + 4*D[3][6] + 4*D[3][8] - 2*D[4][1] - 2*D[4][5] + 2*D[4][9] - 2*D[5][2] - 2*D[5][4] + 4*D[6][3] + 4*D[6][7] + 4*D[7][6] + 4*D[7][8] + 4*D[8][3] + 4*D[8][7] + 2*D[9][2] + 2*D[9][4]; // s1 * s3^2
f2coeff[9] = 2*D[1][2] + 2*D[1][4] + 2*D[2][1] + 2*D[2][5] + 2*D[2][9] - 4*D[3][6] + 4*D[3][8] + 2*D[4][1] + 2*D[4][5] + 2*D[4][9] + 2*D[5][2] + 2*D[5][4] - 4*D[6][3] + 4*D[6][7] + 4*D[7][6] - 4*D[7][8] + 4*D[8][3] - 4*D[8][7] + 2*D[9][2] + 2*D[9][4]; // s1
f2coeff[10] = 2*D[1][6] + 2*D[1][8] - 4*D[2][3] + 4*D[2][7] - 4*D[3][2] + 4*D[3][4] + 4*D[4][3] - 4*D[4][7] + 2*D[5][6] + 2*D[5][8] + 2*D[6][1] + 2*D[6][5] + 2*D[6][9] + 4*D[7][2] - 4*D[7][4] + 2*D[8][1] + 2*D[8][5] + 2*D[8][9] + 2*D[9][6] + 2*D[9][8]; // s3
f2coeff[11] = 8*D[3][3] - 4*D[1][9] - 4*D[1][1] - 8*D[3][7] + 4*D[5][5] - 8*D[7][3] + 8*D[7][7] - 4*D[9][1] - 4*D[9][9]; // s2
f2coeff[12] = 4*D[1][1] - 4*D[5][5] + 4*D[5][9] + 8*D[6][6] + 8*D[6][8] + 8*D[8][6] + 8*D[8][8] + 4*D[9][5] - 4*D[9][9]; // s2 * s3^2
f2coeff[13] = 2*D[1][7] - 2*D[1][3] + 4*D[2][6] - 4*D[2][8] - 2*D[3][1] + 2*D[3][5] + 2*D[3][9] + 4*D[4][6] - 4*D[4][8] + 2*D[5][3] - 2*D[5][7] + 4*D[6][2] + 4*D[6][4] + 2*D[7][1] - 2*D[7][5] - 2*D[7][9] - 4*D[8][2] - 4*D[8][4] + 2*D[9][3] - 2*D[9][7]; // s1^2
f2coeff[14] = 2*D[1][3] - 2*D[1][7] + 4*D[2][6] + 4*D[2][8] + 2*D[3][1] + 2*D[3][5] - 2*D[3][9] - 4*D[4][6] - 4*D[4][8] + 2*D[5][3] - 2*D[5][7] + 4*D[6][2] - 4*D[6][4] - 2*D[7][1] - 2*D[7][5] + 2*D[7][9] + 4*D[8][2] - 4*D[8][4] - 2*D[9][3] + 2*D[9][7]; // s3^2
f2coeff[15] = 6*D[1][3] - 6*D[1][7] + 6*D[3][1] - 6*D[3][5] + 6*D[3][9] - 6*D[5][3] + 6*D[5][7] - 6*D[7][1] + 6*D[7][5] - 6*D[7][9] + 6*D[9][3] - 6*D[9][7]; // s2^2
f2coeff[16] = 2*D[6][9] - 2*D[1][8] - 2*D[5][6] - 2*D[5][8] - 2*D[6][1] - 2*D[6][5] - 2*D[1][6] - 2*D[8][1] - 2*D[8][5] + 2*D[8][9] + 2*D[9][6] + 2*D[9][8]; // s3^3
f2coeff[17] = 8*D[2][6] - 4*D[1][7] - 4*D[1][3] + 8*D[2][8] - 4*D[3][1] + 4*D[3][5] - 4*D[3][9] + 8*D[4][6] + 8*D[4][8] + 4*D[5][3] + 4*D[5][7] + 8*D[6][2] + 8*D[6][4] - 4*D[7][1] + 4*D[7][5] - 4*D[7][9] + 8*D[8][2] + 8*D[8][4] - 4*D[9][3] - 4*D[9][7]; // s1 * s2 * s3
f2coeff[18] = 6*D[2][5] - 6*D[1][4] - 6*D[2][1] - 6*D[1][2] - 6*D[2][9] - 6*D[4][1] + 6*D[4][5] - 6*D[4][9] + 6*D[5][2] + 6*D[5][4] - 6*D[9][2] - 6*D[9][4]; // s1 * s2^2
f2coeff[19] = 2*D[1][6] + 2*D[1][8] + 4*D[2][3] + 4*D[2][7] + 4*D[3][2] + 4*D[3][4] + 4*D[4][3] + 4*D[4][7] - 2*D[5][6] - 2*D[5][8] + 2*D[6][1] - 2*D[6][5] - 2*D[6][9] + 4*D[7][2] + 4*D[7][4] + 2*D[8][1] - 2*D[8][5] - 2*D[8][9] - 2*D[9][6] - 2*D[9][8]; // s1^2 * s3
f2coeff[20] = 2*D[1][2] + 2*D[1][4] + 2*D[2][1] - 2*D[2][5] - 2*D[2][9] + 2*D[4][1] - 2*D[4][5] - 2*D[4][9] - 2*D[5][2] - 2*D[5][4] - 2*D[9][2] - 2*D[9][4]; // s1^3
// F3 COEFFICIENT
f3coeff[1] = 2*D[1][2] - 2*D[1][4] + 2*D[2][1] + 2*D[2][5] + 2*D[2][9] - 2*D[4][1] - 2*D[4][5] - 2*D[4][9] + 2*D[5][2] - 2*D[5][4] + 2*D[9][2] - 2*D[9][4]; // constant term
f3coeff[2] = 2*D[1][6] + 2*D[1][8] + 4*D[2][3] + 4*D[2][7] + 4*D[3][2] + 4*D[3][4] + 4*D[4][3] + 4*D[4][7] - 2*D[5][6] - 2*D[5][8] + 2*D[6][1] - 2*D[6][5] - 2*D[6][9] + 4*D[7][2] + 4*D[7][4] + 2*D[8][1] - 2*D[8][5] - 2*D[8][9] - 2*D[9][6] - 2*D[9][8]; // s1^2 * s2
f3coeff[3] = 8*D[2][2] - 8*D[3][3] - 8*D[4][4] + 8*D[6][6] + 8*D[7][7] - 8*D[8][8]; // s1 * s2
f3coeff[4] = 4*D[1][8] - 4*D[1][6] + 8*D[2][3] + 8*D[2][7] + 8*D[3][2] - 8*D[3][4] - 8*D[4][3] - 8*D[4][7] - 4*D[5][6] + 4*D[5][8] - 4*D[6][1] - 4*D[6][5] + 4*D[6][9] + 8*D[7][2] - 8*D[7][4] + 4*D[8][1] + 4*D[8][5] - 4*D[8][9] + 4*D[9][6] - 4*D[9][8]; // s1 * s3
f3coeff[5] = 4*D[1][3] - 4*D[1][7] + 8*D[2][6] + 8*D[2][8] + 4*D[3][1] + 4*D[3][5] - 4*D[3][9] - 8*D[4][6] - 8*D[4][8] + 4*D[5][3] - 4*D[5][7] + 8*D[6][2] - 8*D[6][4] - 4*D[7][1] - 4*D[7][5] + 4*D[7][9] + 8*D[8][2] - 8*D[8][4] - 4*D[9][3] + 4*D[9][7]; // s2 * s3
f3coeff[6] = 4*D[1][1] - 4*D[5][5] + 4*D[5][9] + 8*D[6][6] + 8*D[6][8] + 8*D[8][6] + 8*D[8][8] + 4*D[9][5] - 4*D[9][9]; // s2^2 * s3
f3coeff[7] = 2*D[5][6] - 2*D[1][8] - 2*D[1][6] + 2*D[5][8] - 2*D[6][1] + 2*D[6][5] - 2*D[6][9] - 2*D[8][1] + 2*D[8][5] - 2*D[8][9] - 2*D[9][6] - 2*D[9][8]; // s2^3
f3coeff[8] = 6*D[3][9] - 6*D[1][7] - 6*D[3][1] - 6*D[3][5] - 6*D[1][3] - 6*D[5][3] - 6*D[5][7] - 6*D[7][1] - 6*D[7][5] + 6*D[7][9] + 6*D[9][3] + 6*D[9][7]; // s1 * s3^2
f3coeff[9] = 2*D[1][3] + 2*D[1][7] + 4*D[2][6] - 4*D[2][8] + 2*D[3][1] + 2*D[3][5] + 2*D[3][9] - 4*D[4][6] + 4*D[4][8] + 2*D[5][3] + 2*D[5][7] + 4*D[6][2] - 4*D[6][4] + 2*D[7][1] + 2*D[7][5] + 2*D[7][9] - 4*D[8][2] + 4*D[8][4] + 2*D[9][3] + 2*D[9][7]; // s1
f3coeff[10] = 8*D[2][2] - 4*D[1][5] - 4*D[1][1] - 8*D[2][4] - 8*D[4][2] + 8*D[4][4] - 4*D[5][1] - 4*D[5][5] + 4*D[9][9]; // s3
f3coeff[11] = 2*D[1][6] + 2*D[1][8] - 4*D[2][3] + 4*D[2][7] - 4*D[3][2] + 4*D[3][4] + 4*D[4][3] - 4*D[4][7] + 2*D[5][6] + 2*D[5][8] + 2*D[6][1] + 2*D[6][5] + 2*D[6][9] + 4*D[7][2] - 4*D[7][4] + 2*D[8][1] + 2*D[8][5] + 2*D[8][9] + 2*D[9][6] + 2*D[9][8]; // s2
f3coeff[12] = 6*D[6][9] - 6*D[1][8] - 6*D[5][6] - 6*D[5][8] - 6*D[6][1] - 6*D[6][5] - 6*D[1][6] - 6*D[8][1] - 6*D[8][5] + 6*D[8][9] + 6*D[9][6] + 6*D[9][8]; // s2 * s3^2
f3coeff[13] = 2*D[1][2] - 2*D[1][4] + 2*D[2][1] - 2*D[2][5] - 2*D[2][9] + 4*D[3][6] - 4*D[3][8] - 2*D[4][1] + 2*D[4][5] + 2*D[4][9] - 2*D[5][2] + 2*D[5][4] + 4*D[6][3] + 4*D[6][7] + 4*D[7][6] - 4*D[7][8] - 4*D[8][3] - 4*D[8][7] - 2*D[9][2] + 2*D[9][4]; // s1^2
f3coeff[14] = 6*D[1][4] - 6*D[1][2] - 6*D[2][1] - 6*D[2][5] + 6*D[2][9] + 6*D[4][1] + 6*D[4][5] - 6*D[4][9] - 6*D[5][2] + 6*D[5][4] + 6*D[9][2] - 6*D[9][4]; // s3^2
f3coeff[15] = 2*D[1][4] - 2*D[1][2] - 2*D[2][1] + 2*D[2][5] - 2*D[2][9] - 4*D[3][6] - 4*D[3][8] + 2*D[4][1] - 2*D[4][5] + 2*D[4][9] + 2*D[5][2] - 2*D[5][4] - 4*D[6][3] + 4*D[6][7] + 4*D[7][6] + 4*D[7][8] - 4*D[8][3] + 4*D[8][7] - 2*D[9][2] + 2*D[9][4]; // s2^2
f3coeff[16] = 4*D[1][1] + 4*D[1][5] - 4*D[1][9] + 4*D[5][1] + 4*D[5][5] - 4*D[5][9] - 4*D[9][1] - 4*D[9][5] + 4*D[9][9]; // s3^3
f3coeff[17] = 4*D[2][9] - 4*D[1][4] - 4*D[2][1] - 4*D[2][5] - 4*D[1][2] + 8*D[3][6] + 8*D[3][8] - 4*D[4][1] - 4*D[4][5] + 4*D[4][9] - 4*D[5][2] - 4*D[5][4] + 8*D[6][3] + 8*D[6][7] + 8*D[7][6] + 8*D[7][8] + 8*D[8][3] + 8*D[8][7] + 4*D[9][2] + 4*D[9][4]; // s1 * s2 * s3
f3coeff[18] = 4*D[2][6] - 2*D[1][7] - 2*D[1][3] + 4*D[2][8] - 2*D[3][1] + 2*D[3][5] - 2*D[3][9] + 4*D[4][6] + 4*D[4][8] + 2*D[5][3] + 2*D[5][7] + 4*D[6][2] + 4*D[6][4] - 2*D[7][1] + 2*D[7][5] - 2*D[7][9] + 4*D[8][2] + 4*D[8][4] - 2*D[9][3] - 2*D[9][7]; // s1 * s2^2
f3coeff[19] = 4*D[1][9] - 4*D[1][1] + 8*D[3][3] + 8*D[3][7] + 4*D[5][5] + 8*D[7][3] + 8*D[7][7] + 4*D[9][1] - 4*D[9][9]; // s1^2 * s3
f3coeff[20] = 2*D[1][3] + 2*D[1][7] + 2*D[3][1] - 2*D[3][5] - 2*D[3][9] - 2*D[5][3] - 2*D[5][7] + 2*D[7][1] - 2*D[7][5] - 2*D[7][9] - 2*D[9][3] - 2*D[9][7]; // s1^3
}
Mat dls::LeftMultVec(const Mat& v)
{
Mat mat_ = Mat::zeros(3, 9, CV_64F);
for (int i = 0; i < 3; ++i)
{
mat_.at<double>(i, 3*i + 0) = v.at<double>(0);
mat_.at<double>(i, 3*i + 1) = v.at<double>(1);
mat_.at<double>(i, 3*i + 2) = v.at<double>(2);
}
return mat_;
}
Mat dls::cayley_LS_M(const std::vector<double>& a, const std::vector<double>& b, const std::vector<double>& c, const std::vector<double>& u)
{
// TODO: input matrix pointer
// TODO: shift coefficients one position to left
Mat M = Mat::zeros(120, 120, CV_64F);
M.at<double>(0,0)=u[1]; M.at<double>(0,35)=a[1]; M.at<double>(0,83)=b[1]; M.at<double>(0,118)=c[1];
M.at<double>(1,0)=u[4]; M.at<double>(1,1)=u[1]; M.at<double>(1,34)=a[1]; M.at<double>(1,35)=a[10]; M.at<double>(1,54)=b[1]; M.at<double>(1,83)=b[10]; M.at<double>(1,99)=c[1]; M.at<double>(1,118)=c[10];
M.at<double>(2,1)=u[4]; M.at<double>(2,2)=u[1]; M.at<double>(2,34)=a[10]; M.at<double>(2,35)=a[14]; M.at<double>(2,51)=a[1]; M.at<double>(2,54)=b[10]; M.at<double>(2,65)=b[1]; M.at<double>(2,83)=b[14]; M.at<double>(2,89)=c[1]; M.at<double>(2,99)=c[10]; M.at<double>(2,118)=c[14];
M.at<double>(3,0)=u[3]; M.at<double>(3,3)=u[1]; M.at<double>(3,35)=a[11]; M.at<double>(3,49)=a[1]; M.at<double>(3,76)=b[1]; M.at<double>(3,83)=b[11]; M.at<double>(3,118)=c[11]; M.at<double>(3,119)=c[1];
M.at<double>(4,1)=u[3]; M.at<double>(4,3)=u[4]; M.at<double>(4,4)=u[1]; M.at<double>(4,34)=a[11]; M.at<double>(4,35)=a[5]; M.at<double>(4,43)=a[1]; M.at<double>(4,49)=a[10]; M.at<double>(4,54)=b[11]; M.at<double>(4,71)=b[1]; M.at<double>(4,76)=b[10]; M.at<double>(4,83)=b[5]; M.at<double>(4,99)=c[11]; M.at<double>(4,100)=c[1]; M.at<double>(4,118)=c[5]; M.at<double>(4,119)=c[10];
M.at<double>(5,2)=u[3]; M.at<double>(5,4)=u[4]; M.at<double>(5,5)=u[1]; M.at<double>(5,34)=a[5]; M.at<double>(5,35)=a[12]; M.at<double>(5,41)=a[1]; M.at<double>(5,43)=a[10]; M.at<double>(5,49)=a[14]; M.at<double>(5,51)=a[11]; M.at<double>(5,54)=b[5]; M.at<double>(5,62)=b[1]; M.at<double>(5,65)=b[11]; M.at<double>(5,71)=b[10]; M.at<double>(5,76)=b[14]; M.at<double>(5,83)=b[12]; M.at<double>(5,89)=c[11]; M.at<double>(5,99)=c[5]; M.at<double>(5,100)=c[10]; M.at<double>(5,111)=c[1]; M.at<double>(5,118)=c[12]; M.at<double>(5,119)=c[14];
M.at<double>(6,3)=u[3]; M.at<double>(6,6)=u[1]; M.at<double>(6,30)=a[1]; M.at<double>(6,35)=a[15]; M.at<double>(6,49)=a[11]; M.at<double>(6,75)=b[1]; M.at<double>(6,76)=b[11]; M.at<double>(6,83)=b[15]; M.at<double>(6,107)=c[1]; M.at<double>(6,118)=c[15]; M.at<double>(6,119)=c[11];
M.at<double>(7,4)=u[3]; M.at<double>(7,6)=u[4]; M.at<double>(7,7)=u[1]; M.at<double>(7,30)=a[10]; M.at<double>(7,34)=a[15]; M.at<double>(7,35)=a[6]; M.at<double>(7,43)=a[11]; M.at<double>(7,45)=a[1]; M.at<double>(7,49)=a[5]; M.at<double>(7,54)=b[15]; M.at<double>(7,63)=b[1]; M.at<double>(7,71)=b[11]; M.at<double>(7,75)=b[10]; M.at<double>(7,76)=b[5]; M.at<double>(7,83)=b[6]; M.at<double>(7,99)=c[15]; M.at<double>(7,100)=c[11]; M.at<double>(7,107)=c[10]; M.at<double>(7,112)=c[1]; M.at<double>(7,118)=c[6]; M.at<double>(7,119)=c[5];
M.at<double>(8,5)=u[3]; M.at<double>(8,7)=u[4]; M.at<double>(8,8)=u[1]; M.at<double>(8,30)=a[14]; M.at<double>(8,34)=a[6]; M.at<double>(8,41)=a[11]; M.at<double>(8,43)=a[5]; M.at<double>(8,45)=a[10]; M.at<double>(8,46)=a[1]; M.at<double>(8,49)=a[12]; M.at<double>(8,51)=a[15]; M.at<double>(8,54)=b[6]; M.at<double>(8,62)=b[11]; M.at<double>(8,63)=b[10]; M.at<double>(8,65)=b[15]; M.at<double>(8,66)=b[1]; M.at<double>(8,71)=b[5]; M.at<double>(8,75)=b[14]; M.at<double>(8,76)=b[12]; M.at<double>(8,89)=c[15]; M.at<double>(8,99)=c[6]; M.at<double>(8,100)=c[5]; M.at<double>(8,102)=c[1]; M.at<double>(8,107)=c[14]; M.at<double>(8,111)=c[11]; M.at<double>(8,112)=c[10]; M.at<double>(8,119)=c[12];
M.at<double>(9,0)=u[2]; M.at<double>(9,9)=u[1]; M.at<double>(9,35)=a[9]; M.at<double>(9,36)=a[1]; M.at<double>(9,83)=b[9]; M.at<double>(9,84)=b[1]; M.at<double>(9,88)=c[1]; M.at<double>(9,118)=c[9];
M.at<double>(10,1)=u[2]; M.at<double>(10,9)=u[4]; M.at<double>(10,10)=u[1]; M.at<double>(10,33)=a[1]; M.at<double>(10,34)=a[9]; M.at<double>(10,35)=a[4]; M.at<double>(10,36)=a[10]; M.at<double>(10,54)=b[9]; M.at<double>(10,59)=b[1]; M.at<double>(10,83)=b[4]; M.at<double>(10,84)=b[10]; M.at<double>(10,88)=c[10]; M.at<double>(10,99)=c[9]; M.at<double>(10,117)=c[1]; M.at<double>(10,118)=c[4];
M.at<double>(11,2)=u[2]; M.at<double>(11,10)=u[4]; M.at<double>(11,11)=u[1]; M.at<double>(11,28)=a[1]; M.at<double>(11,33)=a[10]; M.at<double>(11,34)=a[4]; M.at<double>(11,35)=a[8]; M.at<double>(11,36)=a[14]; M.at<double>(11,51)=a[9]; M.at<double>(11,54)=b[4]; M.at<double>(11,57)=b[1]; M.at<double>(11,59)=b[10]; M.at<double>(11,65)=b[9]; M.at<double>(11,83)=b[8]; M.at<double>(11,84)=b[14]; M.at<double>(11,88)=c[14]; M.at<double>(11,89)=c[9]; M.at<double>(11,99)=c[4]; M.at<double>(11,114)=c[1]; M.at<double>(11,117)=c[10]; M.at<double>(11,118)=c[8];
M.at<double>(12,3)=u[2]; M.at<double>(12,9)=u[3]; M.at<double>(12,12)=u[1]; M.at<double>(12,35)=a[3]; M.at<double>(12,36)=a[11]; M.at<double>(12,39)=a[1]; M.at<double>(12,49)=a[9]; M.at<double>(12,76)=b[9]; M.at<double>(12,79)=b[1]; M.at<double>(12,83)=b[3]; M.at<double>(12,84)=b[11]; M.at<double>(12,88)=c[11]; M.at<double>(12,96)=c[1]; M.at<double>(12,118)=c[3]; M.at<double>(12,119)=c[9];
M.at<double>(13,4)=u[2]; M.at<double>(13,10)=u[3]; M.at<double>(13,12)=u[4]; M.at<double>(13,13)=u[1]; M.at<double>(13,33)=a[11]; M.at<double>(13,34)=a[3]; M.at<double>(13,35)=a[17]; M.at<double>(13,36)=a[5]; M.at<double>(13,39)=a[10]; M.at<double>(13,43)=a[9]; M.at<double>(13,47)=a[1]; M.at<double>(13,49)=a[4]; M.at<double>(13,54)=b[3]; M.at<double>(13,59)=b[11]; M.at<double>(13,60)=b[1]; M.at<double>(13,71)=b[9]; M.at<double>(13,76)=b[4]; M.at<double>(13,79)=b[10]; M.at<double>(13,83)=b[17]; M.at<double>(13,84)=b[5]; M.at<double>(13,88)=c[5]; M.at<double>(13,90)=c[1]; M.at<double>(13,96)=c[10]; M.at<double>(13,99)=c[3]; M.at<double>(13,100)=c[9]; M.at<double>(13,117)=c[11]; M.at<double>(13,118)=c[17]; M.at<double>(13,119)=c[4];
M.at<double>(14,5)=u[2]; M.at<double>(14,11)=u[3]; M.at<double>(14,13)=u[4]; M.at<double>(14,14)=u[1]; M.at<double>(14,28)=a[11]; M.at<double>(14,33)=a[5]; M.at<double>(14,34)=a[17]; M.at<double>(14,36)=a[12]; M.at<double>(14,39)=a[14]; M.at<double>(14,41)=a[9]; M.at<double>(14,42)=a[1]; M.at<double>(14,43)=a[4]; M.at<double>(14,47)=a[10]; M.at<double>(14,49)=a[8]; M.at<double>(14,51)=a[3]; M.at<double>(14,54)=b[17]; M.at<double>(14,56)=b[1]; M.at<double>(14,57)=b[11]; M.at<double>(14,59)=b[5]; M.at<double>(14,60)=b[10]; M.at<double>(14,62)=b[9]; M.at<double>(14,65)=b[3]; M.at<double>(14,71)=b[4]; M.at<double>(14,76)=b[8]; M.at<double>(14,79)=b[14]; M.at<double>(14,84)=b[12]; M.at<double>(14,88)=c[12]; M.at<double>(14,89)=c[3]; M.at<double>(14,90)=c[10]; M.at<double>(14,96)=c[14]; M.at<double>(14,99)=c[17]; M.at<double>(14,100)=c[4]; M.at<double>(14,106)=c[1]; M.at<double>(14,111)=c[9]; M.at<double>(14,114)=c[11]; M.at<double>(14,117)=c[5]; M.at<double>(14,119)=c[8];
M.at<double>(15,6)=u[2]; M.at<double>(15,12)=u[3]; M.at<double>(15,15)=u[1]; M.at<double>(15,29)=a[1]; M.at<double>(15,30)=a[9]; M.at<double>(15,35)=a[18]; M.at<double>(15,36)=a[15]; M.at<double>(15,39)=a[11]; M.at<double>(15,49)=a[3]; M.at<double>(15,74)=b[1]; M.at<double>(15,75)=b[9]; M.at<double>(15,76)=b[3]; M.at<double>(15,79)=b[11]; M.at<double>(15,83)=b[18]; M.at<double>(15,84)=b[15]; M.at<double>(15,88)=c[15]; M.at<double>(15,94)=c[1]; M.at<double>(15,96)=c[11]; M.at<double>(15,107)=c[9]; M.at<double>(15,118)=c[18]; M.at<double>(15,119)=c[3];
M.at<double>(16,7)=u[2]; M.at<double>(16,13)=u[3]; M.at<double>(16,15)=u[4]; M.at<double>(16,16)=u[1]; M.at<double>(16,29)=a[10]; M.at<double>(16,30)=a[4]; M.at<double>(16,33)=a[15]; M.at<double>(16,34)=a[18]; M.at<double>(16,36)=a[6]; M.at<double>(16,39)=a[5]; M.at<double>(16,43)=a[3]; M.at<double>(16,44)=a[1]; M.at<double>(16,45)=a[9]; M.at<double>(16,47)=a[11]; M.at<double>(16,49)=a[17]; M.at<double>(16,54)=b[18]; M.at<double>(16,59)=b[15]; M.at<double>(16,60)=b[11]; M.at<double>(16,63)=b[9]; M.at<double>(16,68)=b[1]; M.at<double>(16,71)=b[3]; M.at<double>(16,74)=b[10]; M.at<double>(16,75)=b[4]; M.at<double>(16,76)=b[17]; M.at<double>(16,79)=b[5]; M.at<double>(16,84)=b[6]; M.at<double>(16,88)=c[6]; M.at<double>(16,90)=c[11]; M.at<double>(16,94)=c[10]; M.at<double>(16,96)=c[5]; M.at<double>(16,97)=c[1]; M.at<double>(16,99)=c[18]; M.at<double>(16,100)=c[3]; M.at<double>(16,107)=c[4]; M.at<double>(16,112)=c[9]; M.at<double>(16,117)=c[15]; M.at<double>(16,119)=c[17];
M.at<double>(17,8)=u[2]; M.at<double>(17,14)=u[3]; M.at<double>(17,16)=u[4]; M.at<double>(17,17)=u[1]; M.at<double>(17,28)=a[15]; M.at<double>(17,29)=a[14]; M.at<double>(17,30)=a[8]; M.at<double>(17,33)=a[6]; M.at<double>(17,39)=a[12]; M.at<double>(17,41)=a[3]; M.at<double>(17,42)=a[11]; M.at<double>(17,43)=a[17]; M.at<double>(17,44)=a[10]; M.at<double>(17,45)=a[4]; M.at<double>(17,46)=a[9]; M.at<double>(17,47)=a[5]; M.at<double>(17,51)=a[18]; M.at<double>(17,56)=b[11]; M.at<double>(17,57)=b[15]; M.at<double>(17,59)=b[6]; M.at<double>(17,60)=b[5]; M.at<double>(17,62)=b[3]; M.at<double>(17,63)=b[4]; M.at<double>(17,65)=b[18]; M.at<double>(17,66)=b[9]; M.at<double>(17,68)=b[10]; M.at<double>(17,71)=b[17]; M.at<double>(17,74)=b[14]; M.at<double>(17,75)=b[8]; M.at<double>(17,79)=b[12]; M.at<double>(17,89)=c[18]; M.at<double>(17,90)=c[5]; M.at<double>(17,94)=c[14]; M.at<double>(17,96)=c[12]; M.at<double>(17,97)=c[10]; M.at<double>(17,100)=c[17]; M.at<double>(17,102)=c[9]; M.at<double>(17,106)=c[11]; M.at<double>(17,107)=c[8]; M.at<double>(17,111)=c[3]; M.at<double>(17,112)=c[4]; M.at<double>(17,114)=c[15]; M.at<double>(17,117)=c[6];
M.at<double>(18,9)=u[2]; M.at<double>(18,18)=u[1]; M.at<double>(18,35)=a[13]; M.at<double>(18,36)=a[9]; M.at<double>(18,53)=a[1]; M.at<double>(18,82)=b[1]; M.at<double>(18,83)=b[13]; M.at<double>(18,84)=b[9]; M.at<double>(18,87)=c[1]; M.at<double>(18,88)=c[9]; M.at<double>(18,118)=c[13];
M.at<double>(19,10)=u[2]; M.at<double>(19,18)=u[4]; M.at<double>(19,19)=u[1]; M.at<double>(19,32)=a[1]; M.at<double>(19,33)=a[9]; M.at<double>(19,34)=a[13]; M.at<double>(19,35)=a[19]; M.at<double>(19,36)=a[4]; M.at<double>(19,53)=a[10]; M.at<double>(19,54)=b[13]; M.at<double>(19,59)=b[9]; M.at<double>(19,61)=b[1]; M.at<double>(19,82)=b[10]; M.at<double>(19,83)=b[19]; M.at<double>(19,84)=b[4]; M.at<double>(19,87)=c[10]; M.at<double>(19,88)=c[4]; M.at<double>(19,99)=c[13]; M.at<double>(19,116)=c[1]; M.at<double>(19,117)=c[9]; M.at<double>(19,118)=c[19];
M.at<double>(20,11)=u[2]; M.at<double>(20,19)=u[4]; M.at<double>(20,20)=u[1]; M.at<double>(20,27)=a[1]; M.at<double>(20,28)=a[9]; M.at<double>(20,32)=a[10]; M.at<double>(20,33)=a[4]; M.at<double>(20,34)=a[19]; M.at<double>(20,36)=a[8]; M.at<double>(20,51)=a[13]; M.at<double>(20,53)=a[14]; M.at<double>(20,54)=b[19]; M.at<double>(20,55)=b[1]; M.at<double>(20,57)=b[9]; M.at<double>(20,59)=b[4]; M.at<double>(20,61)=b[10]; M.at<double>(20,65)=b[13]; M.at<double>(20,82)=b[14]; M.at<double>(20,84)=b[8]; M.at<double>(20,87)=c[14]; M.at<double>(20,88)=c[8]; M.at<double>(20,89)=c[13]; M.at<double>(20,99)=c[19]; M.at<double>(20,113)=c[1]; M.at<double>(20,114)=c[9]; M.at<double>(20,116)=c[10]; M.at<double>(20,117)=c[4];
M.at<double>(21,12)=u[2]; M.at<double>(21,18)=u[3]; M.at<double>(21,21)=u[1]; M.at<double>(21,35)=a[2]; M.at<double>(21,36)=a[3]; M.at<double>(21,38)=a[1]; M.at<double>(21,39)=a[9]; M.at<double>(21,49)=a[13]; M.at<double>(21,53)=a[11]; M.at<double>(21,76)=b[13]; M.at<double>(21,78)=b[1]; M.at<double>(21,79)=b[9]; M.at<double>(21,82)=b[11]; M.at<double>(21,83)=b[2]; M.at<double>(21,84)=b[3]; M.at<double>(21,87)=c[11]; M.at<double>(21,88)=c[3]; M.at<double>(21,92)=c[1]; M.at<double>(21,96)=c[9]; M.at<double>(21,118)=c[2]; M.at<double>(21,119)=c[13];
M.at<double>(22,13)=u[2]; M.at<double>(22,19)=u[3]; M.at<double>(22,21)=u[4]; M.at<double>(22,22)=u[1]; M.at<double>(22,32)=a[11]; M.at<double>(22,33)=a[3]; M.at<double>(22,34)=a[2]; M.at<double>(22,36)=a[17]; M.at<double>(22,38)=a[10]; M.at<double>(22,39)=a[4]; M.at<double>(22,40)=a[1]; M.at<double>(22,43)=a[13]; M.at<double>(22,47)=a[9]; M.at<double>(22,49)=a[19]; M.at<double>(22,53)=a[5]; M.at<double>(22,54)=b[2]; M.at<double>(22,59)=b[3]; M.at<double>(22,60)=b[9]; M.at<double>(22,61)=b[11]; M.at<double>(22,71)=b[13]; M.at<double>(22,72)=b[1]; M.at<double>(22,76)=b[19]; M.at<double>(22,78)=b[10]; M.at<double>(22,79)=b[4]; M.at<double>(22,82)=b[5]; M.at<double>(22,84)=b[17]; M.at<double>(22,87)=c[5]; M.at<double>(22,88)=c[17]; M.at<double>(22,90)=c[9]; M.at<double>(22,92)=c[10]; M.at<double>(22,95)=c[1]; M.at<double>(22,96)=c[4]; M.at<double>(22,99)=c[2]; M.at<double>(22,100)=c[13]; M.at<double>(22,116)=c[11]; M.at<double>(22,117)=c[3]; M.at<double>(22,119)=c[19];
M.at<double>(23,14)=u[2]; M.at<double>(23,20)=u[3]; M.at<double>(23,22)=u[4]; M.at<double>(23,23)=u[1]; M.at<double>(23,27)=a[11]; M.at<double>(23,28)=a[3]; M.at<double>(23,32)=a[5]; M.at<double>(23,33)=a[17]; M.at<double>(23,38)=a[14]; M.at<double>(23,39)=a[8]; M.at<double>(23,40)=a[10]; M.at<double>(23,41)=a[13]; M.at<double>(23,42)=a[9]; M.at<double>(23,43)=a[19]; M.at<double>(23,47)=a[4]; M.at<double>(23,51)=a[2]; M.at<double>(23,53)=a[12]; M.at<double>(23,55)=b[11]; M.at<double>(23,56)=b[9]; M.at<double>(23,57)=b[3]; M.at<double>(23,59)=b[17]; M.at<double>(23,60)=b[4]; M.at<double>(23,61)=b[5]; M.at<double>(23,62)=b[13]; M.at<double>(23,65)=b[2]; M.at<double>(23,71)=b[19]; M.at<double>(23,72)=b[10]; M.at<double>(23,78)=b[14]; M.at<double>(23,79)=b[8]; M.at<double>(23,82)=b[12]; M.at<double>(23,87)=c[12]; M.at<double>(23,89)=c[2]; M.at<double>(23,90)=c[4]; M.at<double>(23,92)=c[14]; M.at<double>(23,95)=c[10]; M.at<double>(23,96)=c[8]; M.at<double>(23,100)=c[19]; M.at<double>(23,106)=c[9]; M.at<double>(23,111)=c[13]; M.at<double>(23,113)=c[11]; M.at<double>(23,114)=c[3]; M.at<double>(23,116)=c[5]; M.at<double>(23,117)=c[17];
M.at<double>(24,15)=u[2]; M.at<double>(24,21)=u[3]; M.at<double>(24,24)=u[1]; M.at<double>(24,29)=a[9]; M.at<double>(24,30)=a[13]; M.at<double>(24,36)=a[18]; M.at<double>(24,38)=a[11]; M.at<double>(24,39)=a[3]; M.at<double>(24,49)=a[2]; M.at<double>(24,52)=a[1]; M.at<double>(24,53)=a[15]; M.at<double>(24,73)=b[1]; M.at<double>(24,74)=b[9]; M.at<double>(24,75)=b[13]; M.at<double>(24,76)=b[2]; M.at<double>(24,78)=b[11]; M.at<double>(24,79)=b[3]; M.at<double>(24,82)=b[15]; M.at<double>(24,84)=b[18]; M.at<double>(24,87)=c[15]; M.at<double>(24,88)=c[18]; M.at<double>(24,92)=c[11]; M.at<double>(24,93)=c[1]; M.at<double>(24,94)=c[9]; M.at<double>(24,96)=c[3]; M.at<double>(24,107)=c[13]; M.at<double>(24,119)=c[2];
M.at<double>(25,16)=u[2]; M.at<double>(25,22)=u[3]; M.at<double>(25,24)=u[4]; M.at<double>(25,25)=u[1]; M.at<double>(25,29)=a[4]; M.at<double>(25,30)=a[19]; M.at<double>(25,32)=a[15]; M.at<double>(25,33)=a[18]; M.at<double>(25,38)=a[5]; M.at<double>(25,39)=a[17]; M.at<double>(25,40)=a[11]; M.at<double>(25,43)=a[2]; M.at<double>(25,44)=a[9]; M.at<double>(25,45)=a[13]; M.at<double>(25,47)=a[3]; M.at<double>(25,52)=a[10]; M.at<double>(25,53)=a[6]; M.at<double>(25,59)=b[18]; M.at<double>(25,60)=b[3]; M.at<double>(25,61)=b[15]; M.at<double>(25,63)=b[13]; M.at<double>(25,68)=b[9]; M.at<double>(25,71)=b[2]; M.at<double>(25,72)=b[11]; M.at<double>(25,73)=b[10]; M.at<double>(25,74)=b[4]; M.at<double>(25,75)=b[19]; M.at<double>(25,78)=b[5]; M.at<double>(25,79)=b[17]; M.at<double>(25,82)=b[6]; M.at<double>(25,87)=c[6]; M.at<double>(25,90)=c[3]; M.at<double>(25,92)=c[5]; M.at<double>(25,93)=c[10]; M.at<double>(25,94)=c[4]; M.at<double>(25,95)=c[11]; M.at<double>(25,96)=c[17]; M.at<double>(25,97)=c[9]; M.at<double>(25,100)=c[2]; M.at<double>(25,107)=c[19]; M.at<double>(25,112)=c[13]; M.at<double>(25,116)=c[15]; M.at<double>(25,117)=c[18];
M.at<double>(26,17)=u[2]; M.at<double>(26,23)=u[3]; M.at<double>(26,25)=u[4]; M.at<double>(26,26)=u[1]; M.at<double>(26,27)=a[15]; M.at<double>(26,28)=a[18]; M.at<double>(26,29)=a[8]; M.at<double>(26,32)=a[6]; M.at<double>(26,38)=a[12]; M.at<double>(26,40)=a[5]; M.at<double>(26,41)=a[2]; M.at<double>(26,42)=a[3]; M.at<double>(26,44)=a[4]; M.at<double>(26,45)=a[19]; M.at<double>(26,46)=a[13]; M.at<double>(26,47)=a[17]; M.at<double>(26,52)=a[14]; M.at<double>(26,55)=b[15]; M.at<double>(26,56)=b[3]; M.at<double>(26,57)=b[18]; M.at<double>(26,60)=b[17]; M.at<double>(26,61)=b[6]; M.at<double>(26,62)=b[2]; M.at<double>(26,63)=b[19]; M.at<double>(26,66)=b[13]; M.at<double>(26,68)=b[4]; M.at<double>(26,72)=b[5]; M.at<double>(26,73)=b[14]; M.at<double>(26,74)=b[8]; M.at<double>(26,78)=b[12]; M.at<double>(26,90)=c[17]; M.at<double>(26,92)=c[12]; M.at<double>(26,93)=c[14]; M.at<double>(26,94)=c[8]; M.at<double>(26,95)=c[5]; M.at<double>(26,97)=c[4]; M.at<double>(26,102)=c[13]; M.at<double>(26,106)=c[3]; M.at<double>(26,111)=c[2]; M.at<double>(26,112)=c[19]; M.at<double>(26,113)=c[15]; M.at<double>(26,114)=c[18]; M.at<double>(26,116)=c[6];
M.at<double>(27,15)=u[3]; M.at<double>(27,29)=a[11]; M.at<double>(27,30)=a[3]; M.at<double>(27,36)=a[7]; M.at<double>(27,39)=a[15]; M.at<double>(27,49)=a[18]; M.at<double>(27,69)=b[9]; M.at<double>(27,70)=b[1]; M.at<double>(27,74)=b[11]; M.at<double>(27,75)=b[3]; M.at<double>(27,76)=b[18]; M.at<double>(27,79)=b[15]; M.at<double>(27,84)=b[7]; M.at<double>(27,88)=c[7]; M.at<double>(27,91)=c[1]; M.at<double>(27,94)=c[11]; M.at<double>(27,96)=c[15]; M.at<double>(27,107)=c[3]; M.at<double>(27,110)=c[9]; M.at<double>(27,119)=c[18];
M.at<double>(28,6)=u[3]; M.at<double>(28,30)=a[11]; M.at<double>(28,35)=a[7]; M.at<double>(28,49)=a[15]; M.at<double>(28,69)=b[1]; M.at<double>(28,75)=b[11]; M.at<double>(28,76)=b[15]; M.at<double>(28,83)=b[7]; M.at<double>(28,107)=c[11]; M.at<double>(28,110)=c[1]; M.at<double>(28,118)=c[7]; M.at<double>(28,119)=c[15];
M.at<double>(29,24)=u[3]; M.at<double>(29,29)=a[3]; M.at<double>(29,30)=a[2]; M.at<double>(29,38)=a[15]; M.at<double>(29,39)=a[18]; M.at<double>(29,52)=a[11]; M.at<double>(29,53)=a[7]; M.at<double>(29,69)=b[13]; M.at<double>(29,70)=b[9]; M.at<double>(29,73)=b[11]; M.at<double>(29,74)=b[3]; M.at<double>(29,75)=b[2]; M.at<double>(29,78)=b[15]; M.at<double>(29,79)=b[18]; M.at<double>(29,82)=b[7]; M.at<double>(29,87)=c[7]; M.at<double>(29,91)=c[9]; M.at<double>(29,92)=c[15]; M.at<double>(29,93)=c[11]; M.at<double>(29,94)=c[3]; M.at<double>(29,96)=c[18]; M.at<double>(29,107)=c[2]; M.at<double>(29,110)=c[13];
M.at<double>(30,37)=a[18]; M.at<double>(30,48)=a[7]; M.at<double>(30,52)=a[2]; M.at<double>(30,70)=b[20]; M.at<double>(30,73)=b[2]; M.at<double>(30,77)=b[18]; M.at<double>(30,81)=b[7]; M.at<double>(30,85)=c[7]; M.at<double>(30,91)=c[20]; M.at<double>(30,93)=c[2]; M.at<double>(30,98)=c[18];
M.at<double>(31,29)=a[2]; M.at<double>(31,37)=a[15]; M.at<double>(31,38)=a[18]; M.at<double>(31,50)=a[7]; M.at<double>(31,52)=a[3]; M.at<double>(31,69)=b[20]; M.at<double>(31,70)=b[13]; M.at<double>(31,73)=b[3]; M.at<double>(31,74)=b[2]; M.at<double>(31,77)=b[15]; M.at<double>(31,78)=b[18]; M.at<double>(31,80)=b[7]; M.at<double>(31,86)=c[7]; M.at<double>(31,91)=c[13]; M.at<double>(31,92)=c[18]; M.at<double>(31,93)=c[3]; M.at<double>(31,94)=c[2]; M.at<double>(31,98)=c[15]; M.at<double>(31,110)=c[20];
M.at<double>(32,48)=a[9]; M.at<double>(32,50)=a[13]; M.at<double>(32,53)=a[20]; M.at<double>(32,80)=b[13]; M.at<double>(32,81)=b[9]; M.at<double>(32,82)=b[20]; M.at<double>(32,85)=c[9]; M.at<double>(32,86)=c[13]; M.at<double>(32,87)=c[20];
M.at<double>(33,29)=a[15]; M.at<double>(33,30)=a[18]; M.at<double>(33,39)=a[7]; M.at<double>(33,64)=b[9]; M.at<double>(33,69)=b[3]; M.at<double>(33,70)=b[11]; M.at<double>(33,74)=b[15]; M.at<double>(33,75)=b[18]; M.at<double>(33,79)=b[7]; M.at<double>(33,91)=c[11]; M.at<double>(33,94)=c[15]; M.at<double>(33,96)=c[7]; M.at<double>(33,103)=c[9]; M.at<double>(33,107)=c[18]; M.at<double>(33,110)=c[3];
M.at<double>(34,29)=a[18]; M.at<double>(34,38)=a[7]; M.at<double>(34,52)=a[15]; M.at<double>(34,64)=b[13]; M.at<double>(34,69)=b[2]; M.at<double>(34,70)=b[3]; M.at<double>(34,73)=b[15]; M.at<double>(34,74)=b[18]; M.at<double>(34,78)=b[7]; M.at<double>(34,91)=c[3]; M.at<double>(34,92)=c[7]; M.at<double>(34,93)=c[15]; M.at<double>(34,94)=c[18]; M.at<double>(34,103)=c[13]; M.at<double>(34,110)=c[2];
M.at<double>(35,37)=a[7]; M.at<double>(35,52)=a[18]; M.at<double>(35,64)=b[20]; M.at<double>(35,70)=b[2]; M.at<double>(35,73)=b[18]; M.at<double>(35,77)=b[7]; M.at<double>(35,91)=c[2]; M.at<double>(35,93)=c[18]; M.at<double>(35,98)=c[7]; M.at<double>(35,103)=c[20];
M.at<double>(36,5)=u[4]; M.at<double>(36,34)=a[12]; M.at<double>(36,41)=a[10]; M.at<double>(36,43)=a[14]; M.at<double>(36,49)=a[16]; M.at<double>(36,51)=a[5]; M.at<double>(36,54)=b[12]; M.at<double>(36,62)=b[10]; M.at<double>(36,65)=b[5]; M.at<double>(36,71)=b[14]; M.at<double>(36,76)=b[16]; M.at<double>(36,89)=c[5]; M.at<double>(36,99)=c[12]; M.at<double>(36,100)=c[14]; M.at<double>(36,101)=c[1]; M.at<double>(36,109)=c[11]; M.at<double>(36,111)=c[10]; M.at<double>(36,119)=c[16];
M.at<double>(37,2)=u[4]; M.at<double>(37,34)=a[14]; M.at<double>(37,35)=a[16]; M.at<double>(37,51)=a[10]; M.at<double>(37,54)=b[14]; M.at<double>(37,65)=b[10]; M.at<double>(37,83)=b[16]; M.at<double>(37,89)=c[10]; M.at<double>(37,99)=c[14]; M.at<double>(37,109)=c[1]; M.at<double>(37,118)=c[16];
M.at<double>(38,30)=a[15]; M.at<double>(38,49)=a[7]; M.at<double>(38,64)=b[1]; M.at<double>(38,69)=b[11]; M.at<double>(38,75)=b[15]; M.at<double>(38,76)=b[7]; M.at<double>(38,103)=c[1]; M.at<double>(38,107)=c[15]; M.at<double>(38,110)=c[11]; M.at<double>(38,119)=c[7];
M.at<double>(39,28)=a[14]; M.at<double>(39,33)=a[16]; M.at<double>(39,51)=a[8]; M.at<double>(39,57)=b[14]; M.at<double>(39,59)=b[16]; M.at<double>(39,65)=b[8]; M.at<double>(39,89)=c[8]; M.at<double>(39,105)=c[9]; M.at<double>(39,108)=c[10]; M.at<double>(39,109)=c[4]; M.at<double>(39,114)=c[14]; M.at<double>(39,117)=c[16];
M.at<double>(40,27)=a[14]; M.at<double>(40,28)=a[8]; M.at<double>(40,32)=a[16]; M.at<double>(40,55)=b[14]; M.at<double>(40,57)=b[8]; M.at<double>(40,61)=b[16]; M.at<double>(40,105)=c[13]; M.at<double>(40,108)=c[4]; M.at<double>(40,109)=c[19]; M.at<double>(40,113)=c[14]; M.at<double>(40,114)=c[8]; M.at<double>(40,116)=c[16];
M.at<double>(41,30)=a[7]; M.at<double>(41,64)=b[11]; M.at<double>(41,69)=b[15]; M.at<double>(41,75)=b[7]; M.at<double>(41,103)=c[11]; M.at<double>(41,107)=c[7]; M.at<double>(41,110)=c[15];
M.at<double>(42,27)=a[8]; M.at<double>(42,31)=a[16]; M.at<double>(42,55)=b[8]; M.at<double>(42,58)=b[16]; M.at<double>(42,105)=c[20]; M.at<double>(42,108)=c[19]; M.at<double>(42,113)=c[8]; M.at<double>(42,115)=c[16];
M.at<double>(43,29)=a[7]; M.at<double>(43,64)=b[3]; M.at<double>(43,69)=b[18]; M.at<double>(43,70)=b[15]; M.at<double>(43,74)=b[7]; M.at<double>(43,91)=c[15]; M.at<double>(43,94)=c[7]; M.at<double>(43,103)=c[3]; M.at<double>(43,110)=c[18];
M.at<double>(44,28)=a[16]; M.at<double>(44,57)=b[16]; M.at<double>(44,105)=c[4]; M.at<double>(44,108)=c[14]; M.at<double>(44,109)=c[8]; M.at<double>(44,114)=c[16];
M.at<double>(45,27)=a[16]; M.at<double>(45,55)=b[16]; M.at<double>(45,105)=c[19]; M.at<double>(45,108)=c[8]; M.at<double>(45,113)=c[16];
M.at<double>(46,52)=a[7]; M.at<double>(46,64)=b[2]; M.at<double>(46,70)=b[18]; M.at<double>(46,73)=b[7]; M.at<double>(46,91)=c[18]; M.at<double>(46,93)=c[7]; M.at<double>(46,103)=c[2];
M.at<double>(47,40)=a[7]; M.at<double>(47,44)=a[18]; M.at<double>(47,52)=a[6]; M.at<double>(47,64)=b[19]; M.at<double>(47,67)=b[2]; M.at<double>(47,68)=b[18]; M.at<double>(47,70)=b[17]; M.at<double>(47,72)=b[7]; M.at<double>(47,73)=b[6]; M.at<double>(47,91)=c[17]; M.at<double>(47,93)=c[6]; M.at<double>(47,95)=c[7]; M.at<double>(47,97)=c[18]; M.at<double>(47,103)=c[19]; M.at<double>(47,104)=c[2];
M.at<double>(48,30)=a[6]; M.at<double>(48,43)=a[7]; M.at<double>(48,45)=a[15]; M.at<double>(48,63)=b[15]; M.at<double>(48,64)=b[10]; M.at<double>(48,67)=b[11]; M.at<double>(48,69)=b[5]; M.at<double>(48,71)=b[7]; M.at<double>(48,75)=b[6]; M.at<double>(48,100)=c[7]; M.at<double>(48,103)=c[10]; M.at<double>(48,104)=c[11]; M.at<double>(48,107)=c[6]; M.at<double>(48,110)=c[5]; M.at<double>(48,112)=c[15];
M.at<double>(49,41)=a[12]; M.at<double>(49,45)=a[16]; M.at<double>(49,46)=a[14]; M.at<double>(49,62)=b[12]; M.at<double>(49,63)=b[16]; M.at<double>(49,66)=b[14]; M.at<double>(49,101)=c[5]; M.at<double>(49,102)=c[14]; M.at<double>(49,105)=c[15]; M.at<double>(49,109)=c[6]; M.at<double>(49,111)=c[12]; M.at<double>(49,112)=c[16];
M.at<double>(50,41)=a[16]; M.at<double>(50,62)=b[16]; M.at<double>(50,101)=c[14]; M.at<double>(50,105)=c[5]; M.at<double>(50,109)=c[12]; M.at<double>(50,111)=c[16];
M.at<double>(51,64)=b[18]; M.at<double>(51,70)=b[7]; M.at<double>(51,91)=c[7]; M.at<double>(51,103)=c[18];
M.at<double>(52,41)=a[6]; M.at<double>(52,45)=a[12]; M.at<double>(52,46)=a[5]; M.at<double>(52,62)=b[6]; M.at<double>(52,63)=b[12]; M.at<double>(52,66)=b[5]; M.at<double>(52,67)=b[14]; M.at<double>(52,69)=b[16]; M.at<double>(52,101)=c[15]; M.at<double>(52,102)=c[5]; M.at<double>(52,104)=c[14]; M.at<double>(52,109)=c[7]; M.at<double>(52,110)=c[16]; M.at<double>(52,111)=c[6]; M.at<double>(52,112)=c[12];
M.at<double>(53,64)=b[15]; M.at<double>(53,69)=b[7]; M.at<double>(53,103)=c[15]; M.at<double>(53,110)=c[7];
M.at<double>(54,105)=c[14]; M.at<double>(54,109)=c[16];
M.at<double>(55,44)=a[7]; M.at<double>(55,64)=b[17]; M.at<double>(55,67)=b[18]; M.at<double>(55,68)=b[7]; M.at<double>(55,70)=b[6]; M.at<double>(55,91)=c[6]; M.at<double>(55,97)=c[7]; M.at<double>(55,103)=c[17]; M.at<double>(55,104)=c[18];
M.at<double>(56,105)=c[8]; M.at<double>(56,108)=c[16];
M.at<double>(57,64)=b[6]; M.at<double>(57,67)=b[7]; M.at<double>(57,103)=c[6]; M.at<double>(57,104)=c[7];
M.at<double>(58,46)=a[7]; M.at<double>(58,64)=b[12]; M.at<double>(58,66)=b[7]; M.at<double>(58,67)=b[6]; M.at<double>(58,102)=c[7]; M.at<double>(58,103)=c[12]; M.at<double>(58,104)=c[6];
M.at<double>(59,8)=u[4]; M.at<double>(59,30)=a[16]; M.at<double>(59,41)=a[5]; M.at<double>(59,43)=a[12]; M.at<double>(59,45)=a[14]; M.at<double>(59,46)=a[10]; M.at<double>(59,51)=a[6]; M.at<double>(59,62)=b[5]; M.at<double>(59,63)=b[14]; M.at<double>(59,65)=b[6]; M.at<double>(59,66)=b[10]; M.at<double>(59,71)=b[12]; M.at<double>(59,75)=b[16]; M.at<double>(59,89)=c[6]; M.at<double>(59,100)=c[12]; M.at<double>(59,101)=c[11]; M.at<double>(59,102)=c[10]; M.at<double>(59,107)=c[16]; M.at<double>(59,109)=c[15]; M.at<double>(59,111)=c[5]; M.at<double>(59,112)=c[14];
M.at<double>(60,8)=u[3]; M.at<double>(60,30)=a[12]; M.at<double>(60,41)=a[15]; M.at<double>(60,43)=a[6]; M.at<double>(60,45)=a[5]; M.at<double>(60,46)=a[11]; M.at<double>(60,51)=a[7]; M.at<double>(60,62)=b[15]; M.at<double>(60,63)=b[5]; M.at<double>(60,65)=b[7]; M.at<double>(60,66)=b[11]; M.at<double>(60,67)=b[10]; M.at<double>(60,69)=b[14]; M.at<double>(60,71)=b[6]; M.at<double>(60,75)=b[12]; M.at<double>(60,89)=c[7]; M.at<double>(60,100)=c[6]; M.at<double>(60,102)=c[11]; M.at<double>(60,104)=c[10]; M.at<double>(60,107)=c[12]; M.at<double>(60,110)=c[14]; M.at<double>(60,111)=c[15]; M.at<double>(60,112)=c[5];
M.at<double>(61,42)=a[16]; M.at<double>(61,56)=b[16]; M.at<double>(61,101)=c[8]; M.at<double>(61,105)=c[17]; M.at<double>(61,106)=c[16]; M.at<double>(61,108)=c[12];
M.at<double>(62,64)=b[7]; M.at<double>(62,103)=c[7];
M.at<double>(63,105)=c[16];
M.at<double>(64,46)=a[12]; M.at<double>(64,66)=b[12]; M.at<double>(64,67)=b[16]; M.at<double>(64,101)=c[6]; M.at<double>(64,102)=c[12]; M.at<double>(64,104)=c[16]; M.at<double>(64,105)=c[7];
M.at<double>(65,46)=a[6]; M.at<double>(65,64)=b[16]; M.at<double>(65,66)=b[6]; M.at<double>(65,67)=b[12]; M.at<double>(65,101)=c[7]; M.at<double>(65,102)=c[6]; M.at<double>(65,103)=c[16]; M.at<double>(65,104)=c[12];
M.at<double>(66,46)=a[16]; M.at<double>(66,66)=b[16]; M.at<double>(66,101)=c[12]; M.at<double>(66,102)=c[16]; M.at<double>(66,105)=c[6];
M.at<double>(67,101)=c[16]; M.at<double>(67,105)=c[12];
M.at<double>(68,41)=a[14]; M.at<double>(68,43)=a[16]; M.at<double>(68,51)=a[12]; M.at<double>(68,62)=b[14]; M.at<double>(68,65)=b[12]; M.at<double>(68,71)=b[16]; M.at<double>(68,89)=c[12]; M.at<double>(68,100)=c[16]; M.at<double>(68,101)=c[10]; M.at<double>(68,105)=c[11]; M.at<double>(68,109)=c[5]; M.at<double>(68,111)=c[14];
M.at<double>(69,37)=a[2]; M.at<double>(69,48)=a[18]; M.at<double>(69,52)=a[20]; M.at<double>(69,73)=b[20]; M.at<double>(69,77)=b[2]; M.at<double>(69,81)=b[18]; M.at<double>(69,85)=c[18]; M.at<double>(69,93)=c[20]; M.at<double>(69,98)=c[2];
M.at<double>(70,20)=u[2]; M.at<double>(70,27)=a[9]; M.at<double>(70,28)=a[13]; M.at<double>(70,31)=a[10]; M.at<double>(70,32)=a[4]; M.at<double>(70,33)=a[19]; M.at<double>(70,50)=a[14]; M.at<double>(70,51)=a[20]; M.at<double>(70,53)=a[8]; M.at<double>(70,55)=b[9]; M.at<double>(70,57)=b[13]; M.at<double>(70,58)=b[10]; M.at<double>(70,59)=b[19]; M.at<double>(70,61)=b[4]; M.at<double>(70,65)=b[20]; M.at<double>(70,80)=b[14]; M.at<double>(70,82)=b[8]; M.at<double>(70,86)=c[14]; M.at<double>(70,87)=c[8]; M.at<double>(70,89)=c[20]; M.at<double>(70,113)=c[9]; M.at<double>(70,114)=c[13]; M.at<double>(70,115)=c[10]; M.at<double>(70,116)=c[4]; M.at<double>(70,117)=c[19];
M.at<double>(71,45)=a[7]; M.at<double>(71,63)=b[7]; M.at<double>(71,64)=b[5]; M.at<double>(71,67)=b[15]; M.at<double>(71,69)=b[6]; M.at<double>(71,103)=c[5]; M.at<double>(71,104)=c[15]; M.at<double>(71,110)=c[6]; M.at<double>(71,112)=c[7];
M.at<double>(72,41)=a[7]; M.at<double>(72,45)=a[6]; M.at<double>(72,46)=a[15]; M.at<double>(72,62)=b[7]; M.at<double>(72,63)=b[6]; M.at<double>(72,64)=b[14]; M.at<double>(72,66)=b[15]; M.at<double>(72,67)=b[5]; M.at<double>(72,69)=b[12]; M.at<double>(72,102)=c[15]; M.at<double>(72,103)=c[14]; M.at<double>(72,104)=c[5]; M.at<double>(72,110)=c[12]; M.at<double>(72,111)=c[7]; M.at<double>(72,112)=c[6];
M.at<double>(73,48)=a[13]; M.at<double>(73,50)=a[20]; M.at<double>(73,80)=b[20]; M.at<double>(73,81)=b[13]; M.at<double>(73,85)=c[13]; M.at<double>(73,86)=c[20];
M.at<double>(74,25)=u[3]; M.at<double>(74,29)=a[17]; M.at<double>(74,32)=a[7]; M.at<double>(74,38)=a[6]; M.at<double>(74,40)=a[15]; M.at<double>(74,44)=a[3]; M.at<double>(74,45)=a[2]; M.at<double>(74,47)=a[18]; M.at<double>(74,52)=a[5]; M.at<double>(74,60)=b[18]; M.at<double>(74,61)=b[7]; M.at<double>(74,63)=b[2]; M.at<double>(74,67)=b[13]; M.at<double>(74,68)=b[3]; M.at<double>(74,69)=b[19]; M.at<double>(74,70)=b[4]; M.at<double>(74,72)=b[15]; M.at<double>(74,73)=b[5]; M.at<double>(74,74)=b[17]; M.at<double>(74,78)=b[6]; M.at<double>(74,90)=c[18]; M.at<double>(74,91)=c[4]; M.at<double>(74,92)=c[6]; M.at<double>(74,93)=c[5]; M.at<double>(74,94)=c[17]; M.at<double>(74,95)=c[15]; M.at<double>(74,97)=c[3]; M.at<double>(74,104)=c[13]; M.at<double>(74,110)=c[19]; M.at<double>(74,112)=c[2]; M.at<double>(74,116)=c[7];
M.at<double>(75,21)=u[2]; M.at<double>(75,36)=a[2]; M.at<double>(75,37)=a[1]; M.at<double>(75,38)=a[9]; M.at<double>(75,39)=a[13]; M.at<double>(75,49)=a[20]; M.at<double>(75,50)=a[11]; M.at<double>(75,53)=a[3]; M.at<double>(75,76)=b[20]; M.at<double>(75,77)=b[1]; M.at<double>(75,78)=b[9]; M.at<double>(75,79)=b[13]; M.at<double>(75,80)=b[11]; M.at<double>(75,82)=b[3]; M.at<double>(75,84)=b[2]; M.at<double>(75,86)=c[11]; M.at<double>(75,87)=c[3]; M.at<double>(75,88)=c[2]; M.at<double>(75,92)=c[9]; M.at<double>(75,96)=c[13]; M.at<double>(75,98)=c[1]; M.at<double>(75,119)=c[20];
M.at<double>(76,48)=a[20]; M.at<double>(76,81)=b[20]; M.at<double>(76,85)=c[20];
M.at<double>(77,34)=a[16]; M.at<double>(77,51)=a[14]; M.at<double>(77,54)=b[16]; M.at<double>(77,65)=b[14]; M.at<double>(77,89)=c[14]; M.at<double>(77,99)=c[16]; M.at<double>(77,105)=c[1]; M.at<double>(77,109)=c[10];
M.at<double>(78,27)=a[17]; M.at<double>(78,31)=a[12]; M.at<double>(78,37)=a[16]; M.at<double>(78,40)=a[8]; M.at<double>(78,42)=a[19]; M.at<double>(78,55)=b[17]; M.at<double>(78,56)=b[19]; M.at<double>(78,58)=b[12]; M.at<double>(78,72)=b[8]; M.at<double>(78,77)=b[16]; M.at<double>(78,95)=c[8]; M.at<double>(78,98)=c[16]; M.at<double>(78,101)=c[20]; M.at<double>(78,106)=c[19]; M.at<double>(78,108)=c[2]; M.at<double>(78,113)=c[17]; M.at<double>(78,115)=c[12];
M.at<double>(79,42)=a[12]; M.at<double>(79,44)=a[16]; M.at<double>(79,46)=a[8]; M.at<double>(79,56)=b[12]; M.at<double>(79,66)=b[8]; M.at<double>(79,68)=b[16]; M.at<double>(79,97)=c[16]; M.at<double>(79,101)=c[17]; M.at<double>(79,102)=c[8]; M.at<double>(79,105)=c[18]; M.at<double>(79,106)=c[12]; M.at<double>(79,108)=c[6];
M.at<double>(80,14)=u[4]; M.at<double>(80,28)=a[5]; M.at<double>(80,33)=a[12]; M.at<double>(80,39)=a[16]; M.at<double>(80,41)=a[4]; M.at<double>(80,42)=a[10]; M.at<double>(80,43)=a[8]; M.at<double>(80,47)=a[14]; M.at<double>(80,51)=a[17]; M.at<double>(80,56)=b[10]; M.at<double>(80,57)=b[5]; M.at<double>(80,59)=b[12]; M.at<double>(80,60)=b[14]; M.at<double>(80,62)=b[4]; M.at<double>(80,65)=b[17]; M.at<double>(80,71)=b[8]; M.at<double>(80,79)=b[16]; M.at<double>(80,89)=c[17]; M.at<double>(80,90)=c[14]; M.at<double>(80,96)=c[16]; M.at<double>(80,100)=c[8]; M.at<double>(80,101)=c[9]; M.at<double>(80,106)=c[10]; M.at<double>(80,108)=c[11]; M.at<double>(80,109)=c[3]; M.at<double>(80,111)=c[4]; M.at<double>(80,114)=c[5]; M.at<double>(80,117)=c[12];
M.at<double>(81,31)=a[3]; M.at<double>(81,32)=a[2]; M.at<double>(81,37)=a[4]; M.at<double>(81,38)=a[19]; M.at<double>(81,40)=a[13]; M.at<double>(81,47)=a[20]; M.at<double>(81,48)=a[5]; M.at<double>(81,50)=a[17]; M.at<double>(81,58)=b[3]; M.at<double>(81,60)=b[20]; M.at<double>(81,61)=b[2]; M.at<double>(81,72)=b[13]; M.at<double>(81,77)=b[4]; M.at<double>(81,78)=b[19]; M.at<double>(81,80)=b[17]; M.at<double>(81,81)=b[5]; M.at<double>(81,85)=c[5]; M.at<double>(81,86)=c[17]; M.at<double>(81,90)=c[20]; M.at<double>(81,92)=c[19]; M.at<double>(81,95)=c[13]; M.at<double>(81,98)=c[4]; M.at<double>(81,115)=c[3]; M.at<double>(81,116)=c[2];
M.at<double>(82,29)=a[6]; M.at<double>(82,44)=a[15]; M.at<double>(82,45)=a[18]; M.at<double>(82,47)=a[7]; M.at<double>(82,60)=b[7]; M.at<double>(82,63)=b[18]; M.at<double>(82,64)=b[4]; M.at<double>(82,67)=b[3]; M.at<double>(82,68)=b[15]; M.at<double>(82,69)=b[17]; M.at<double>(82,70)=b[5]; M.at<double>(82,74)=b[6]; M.at<double>(82,90)=c[7]; M.at<double>(82,91)=c[5]; M.at<double>(82,94)=c[6]; M.at<double>(82,97)=c[15]; M.at<double>(82,103)=c[4]; M.at<double>(82,104)=c[3]; M.at<double>(82,110)=c[17]; M.at<double>(82,112)=c[18];
M.at<double>(83,26)=u[2]; M.at<double>(83,27)=a[18]; M.at<double>(83,31)=a[6]; M.at<double>(83,37)=a[12]; M.at<double>(83,40)=a[17]; M.at<double>(83,42)=a[2]; M.at<double>(83,44)=a[19]; M.at<double>(83,46)=a[20]; M.at<double>(83,52)=a[8]; M.at<double>(83,55)=b[18]; M.at<double>(83,56)=b[2]; M.at<double>(83,58)=b[6]; M.at<double>(83,66)=b[20]; M.at<double>(83,68)=b[19]; M.at<double>(83,72)=b[17]; M.at<double>(83,73)=b[8]; M.at<double>(83,77)=b[12]; M.at<double>(83,93)=c[8]; M.at<double>(83,95)=c[17]; M.at<double>(83,97)=c[19]; M.at<double>(83,98)=c[12]; M.at<double>(83,102)=c[20]; M.at<double>(83,106)=c[2]; M.at<double>(83,113)=c[18]; M.at<double>(83,115)=c[6];
M.at<double>(84,16)=u[3]; M.at<double>(84,29)=a[5]; M.at<double>(84,30)=a[17]; M.at<double>(84,33)=a[7]; M.at<double>(84,39)=a[6]; M.at<double>(84,43)=a[18]; M.at<double>(84,44)=a[11]; M.at<double>(84,45)=a[3]; M.at<double>(84,47)=a[15]; M.at<double>(84,59)=b[7]; M.at<double>(84,60)=b[15]; M.at<double>(84,63)=b[3]; M.at<double>(84,67)=b[9]; M.at<double>(84,68)=b[11]; M.at<double>(84,69)=b[4]; M.at<double>(84,70)=b[10]; M.at<double>(84,71)=b[18]; M.at<double>(84,74)=b[5]; M.at<double>(84,75)=b[17]; M.at<double>(84,79)=b[6]; M.at<double>(84,90)=c[15]; M.at<double>(84,91)=c[10]; M.at<double>(84,94)=c[5]; M.at<double>(84,96)=c[6]; M.at<double>(84,97)=c[11]; M.at<double>(84,100)=c[18]; M.at<double>(84,104)=c[9]; M.at<double>(84,107)=c[17]; M.at<double>(84,110)=c[4]; M.at<double>(84,112)=c[3]; M.at<double>(84,117)=c[7];
M.at<double>(85,25)=u[2]; M.at<double>(85,29)=a[19]; M.at<double>(85,31)=a[15]; M.at<double>(85,32)=a[18]; M.at<double>(85,37)=a[5]; M.at<double>(85,38)=a[17]; M.at<double>(85,40)=a[3]; M.at<double>(85,44)=a[13]; M.at<double>(85,45)=a[20]; M.at<double>(85,47)=a[2]; M.at<double>(85,50)=a[6]; M.at<double>(85,52)=a[4]; M.at<double>(85,58)=b[15]; M.at<double>(85,60)=b[2]; M.at<double>(85,61)=b[18]; M.at<double>(85,63)=b[20]; M.at<double>(85,68)=b[13]; M.at<double>(85,72)=b[3]; M.at<double>(85,73)=b[4]; M.at<double>(85,74)=b[19]; M.at<double>(85,77)=b[5]; M.at<double>(85,78)=b[17]; M.at<double>(85,80)=b[6]; M.at<double>(85,86)=c[6]; M.at<double>(85,90)=c[2]; M.at<double>(85,92)=c[17]; M.at<double>(85,93)=c[4]; M.at<double>(85,94)=c[19]; M.at<double>(85,95)=c[3]; M.at<double>(85,97)=c[13]; M.at<double>(85,98)=c[5]; M.at<double>(85,112)=c[20]; M.at<double>(85,115)=c[15]; M.at<double>(85,116)=c[18];
M.at<double>(86,31)=a[18]; M.at<double>(86,37)=a[17]; M.at<double>(86,40)=a[2]; M.at<double>(86,44)=a[20]; M.at<double>(86,48)=a[6]; M.at<double>(86,52)=a[19]; M.at<double>(86,58)=b[18]; M.at<double>(86,68)=b[20]; M.at<double>(86,72)=b[2]; M.at<double>(86,73)=b[19]; M.at<double>(86,77)=b[17]; M.at<double>(86,81)=b[6]; M.at<double>(86,85)=c[6]; M.at<double>(86,93)=c[19]; M.at<double>(86,95)=c[2]; M.at<double>(86,97)=c[20]; M.at<double>(86,98)=c[17]; M.at<double>(86,115)=c[18];
M.at<double>(87,22)=u[2]; M.at<double>(87,31)=a[11]; M.at<double>(87,32)=a[3]; M.at<double>(87,33)=a[2]; M.at<double>(87,37)=a[10]; M.at<double>(87,38)=a[4]; M.at<double>(87,39)=a[19]; M.at<double>(87,40)=a[9]; M.at<double>(87,43)=a[20]; M.at<double>(87,47)=a[13]; M.at<double>(87,50)=a[5]; M.at<double>(87,53)=a[17]; M.at<double>(87,58)=b[11]; M.at<double>(87,59)=b[2]; M.at<double>(87,60)=b[13]; M.at<double>(87,61)=b[3]; M.at<double>(87,71)=b[20]; M.at<double>(87,72)=b[9]; M.at<double>(87,77)=b[10]; M.at<double>(87,78)=b[4]; M.at<double>(87,79)=b[19]; M.at<double>(87,80)=b[5]; M.at<double>(87,82)=b[17]; M.at<double>(87,86)=c[5]; M.at<double>(87,87)=c[17]; M.at<double>(87,90)=c[13]; M.at<double>(87,92)=c[4]; M.at<double>(87,95)=c[9]; M.at<double>(87,96)=c[19]; M.at<double>(87,98)=c[10]; M.at<double>(87,100)=c[20]; M.at<double>(87,115)=c[11]; M.at<double>(87,116)=c[3]; M.at<double>(87,117)=c[2];
M.at<double>(88,27)=a[2]; M.at<double>(88,31)=a[17]; M.at<double>(88,37)=a[8]; M.at<double>(88,40)=a[19]; M.at<double>(88,42)=a[20]; M.at<double>(88,48)=a[12]; M.at<double>(88,55)=b[2]; M.at<double>(88,56)=b[20]; M.at<double>(88,58)=b[17]; M.at<double>(88,72)=b[19]; M.at<double>(88,77)=b[8]; M.at<double>(88,81)=b[12]; M.at<double>(88,85)=c[12]; M.at<double>(88,95)=c[19]; M.at<double>(88,98)=c[8]; M.at<double>(88,106)=c[20]; M.at<double>(88,113)=c[2]; M.at<double>(88,115)=c[17];
M.at<double>(89,31)=a[7]; M.at<double>(89,37)=a[6]; M.at<double>(89,40)=a[18]; M.at<double>(89,44)=a[2]; M.at<double>(89,52)=a[17]; M.at<double>(89,58)=b[7]; M.at<double>(89,67)=b[20]; M.at<double>(89,68)=b[2]; M.at<double>(89,70)=b[19]; M.at<double>(89,72)=b[18]; M.at<double>(89,73)=b[17]; M.at<double>(89,77)=b[6]; M.at<double>(89,91)=c[19]; M.at<double>(89,93)=c[17]; M.at<double>(89,95)=c[18]; M.at<double>(89,97)=c[2]; M.at<double>(89,98)=c[6]; M.at<double>(89,104)=c[20]; M.at<double>(89,115)=c[7];
M.at<double>(90,27)=a[12]; M.at<double>(90,40)=a[16]; M.at<double>(90,42)=a[8]; M.at<double>(90,55)=b[12]; M.at<double>(90,56)=b[8]; M.at<double>(90,72)=b[16]; M.at<double>(90,95)=c[16]; M.at<double>(90,101)=c[19]; M.at<double>(90,105)=c[2]; M.at<double>(90,106)=c[8]; M.at<double>(90,108)=c[17]; M.at<double>(90,113)=c[12];
M.at<double>(91,23)=u[2]; M.at<double>(91,27)=a[3]; M.at<double>(91,28)=a[2]; M.at<double>(91,31)=a[5]; M.at<double>(91,32)=a[17]; M.at<double>(91,37)=a[14]; M.at<double>(91,38)=a[8]; M.at<double>(91,40)=a[4]; M.at<double>(91,41)=a[20]; M.at<double>(91,42)=a[13]; M.at<double>(91,47)=a[19]; M.at<double>(91,50)=a[12]; M.at<double>(91,55)=b[3]; M.at<double>(91,56)=b[13]; M.at<double>(91,57)=b[2]; M.at<double>(91,58)=b[5]; M.at<double>(91,60)=b[19]; M.at<double>(91,61)=b[17]; M.at<double>(91,62)=b[20]; M.at<double>(91,72)=b[4]; M.at<double>(91,77)=b[14]; M.at<double>(91,78)=b[8]; M.at<double>(91,80)=b[12]; M.at<double>(91,86)=c[12]; M.at<double>(91,90)=c[19]; M.at<double>(91,92)=c[8]; M.at<double>(91,95)=c[4]; M.at<double>(91,98)=c[14]; M.at<double>(91,106)=c[13]; M.at<double>(91,111)=c[20]; M.at<double>(91,113)=c[3]; M.at<double>(91,114)=c[2]; M.at<double>(91,115)=c[5]; M.at<double>(91,116)=c[17];
M.at<double>(92,17)=u[4]; M.at<double>(92,28)=a[6]; M.at<double>(92,29)=a[16]; M.at<double>(92,41)=a[17]; M.at<double>(92,42)=a[5]; M.at<double>(92,44)=a[14]; M.at<double>(92,45)=a[8]; M.at<double>(92,46)=a[4]; M.at<double>(92,47)=a[12]; M.at<double>(92,56)=b[5]; M.at<double>(92,57)=b[6]; M.at<double>(92,60)=b[12]; M.at<double>(92,62)=b[17]; M.at<double>(92,63)=b[8]; M.at<double>(92,66)=b[4]; M.at<double>(92,68)=b[14]; M.at<double>(92,74)=b[16]; M.at<double>(92,90)=c[12]; M.at<double>(92,94)=c[16]; M.at<double>(92,97)=c[14]; M.at<double>(92,101)=c[3]; M.at<double>(92,102)=c[4]; M.at<double>(92,106)=c[5]; M.at<double>(92,108)=c[15]; M.at<double>(92,109)=c[18]; M.at<double>(92,111)=c[17]; M.at<double>(92,112)=c[8]; M.at<double>(92,114)=c[6];
M.at<double>(93,17)=u[3]; M.at<double>(93,28)=a[7]; M.at<double>(93,29)=a[12]; M.at<double>(93,41)=a[18]; M.at<double>(93,42)=a[15]; M.at<double>(93,44)=a[5]; M.at<double>(93,45)=a[17]; M.at<double>(93,46)=a[3]; M.at<double>(93,47)=a[6]; M.at<double>(93,56)=b[15]; M.at<double>(93,57)=b[7]; M.at<double>(93,60)=b[6]; M.at<double>(93,62)=b[18]; M.at<double>(93,63)=b[17]; M.at<double>(93,66)=b[3]; M.at<double>(93,67)=b[4]; M.at<double>(93,68)=b[5]; M.at<double>(93,69)=b[8]; M.at<double>(93,70)=b[14]; M.at<double>(93,74)=b[12]; M.at<double>(93,90)=c[6]; M.at<double>(93,91)=c[14]; M.at<double>(93,94)=c[12]; M.at<double>(93,97)=c[5]; M.at<double>(93,102)=c[3]; M.at<double>(93,104)=c[4]; M.at<double>(93,106)=c[15]; M.at<double>(93,110)=c[8]; M.at<double>(93,111)=c[18]; M.at<double>(93,112)=c[17]; M.at<double>(93,114)=c[7];
M.at<double>(94,31)=a[2]; M.at<double>(94,37)=a[19]; M.at<double>(94,40)=a[20]; M.at<double>(94,48)=a[17]; M.at<double>(94,58)=b[2]; M.at<double>(94,72)=b[20]; M.at<double>(94,77)=b[19]; M.at<double>(94,81)=b[17]; M.at<double>(94,85)=c[17]; M.at<double>(94,95)=c[20]; M.at<double>(94,98)=c[19]; M.at<double>(94,115)=c[2];
M.at<double>(95,26)=u[4]; M.at<double>(95,27)=a[6]; M.at<double>(95,40)=a[12]; M.at<double>(95,42)=a[17]; M.at<double>(95,44)=a[8]; M.at<double>(95,46)=a[19]; M.at<double>(95,52)=a[16]; M.at<double>(95,55)=b[6]; M.at<double>(95,56)=b[17]; M.at<double>(95,66)=b[19]; M.at<double>(95,68)=b[8]; M.at<double>(95,72)=b[12]; M.at<double>(95,73)=b[16]; M.at<double>(95,93)=c[16]; M.at<double>(95,95)=c[12]; M.at<double>(95,97)=c[8]; M.at<double>(95,101)=c[2]; M.at<double>(95,102)=c[19]; M.at<double>(95,106)=c[17]; M.at<double>(95,108)=c[18]; M.at<double>(95,113)=c[6];
M.at<double>(96,23)=u[4]; M.at<double>(96,27)=a[5]; M.at<double>(96,28)=a[17]; M.at<double>(96,32)=a[12]; M.at<double>(96,38)=a[16]; M.at<double>(96,40)=a[14]; M.at<double>(96,41)=a[19]; M.at<double>(96,42)=a[4]; M.at<double>(96,47)=a[8]; M.at<double>(96,55)=b[5]; M.at<double>(96,56)=b[4]; M.at<double>(96,57)=b[17]; M.at<double>(96,60)=b[8]; M.at<double>(96,61)=b[12]; M.at<double>(96,62)=b[19]; M.at<double>(96,72)=b[14]; M.at<double>(96,78)=b[16]; M.at<double>(96,90)=c[8]; M.at<double>(96,92)=c[16]; M.at<double>(96,95)=c[14]; M.at<double>(96,101)=c[13]; M.at<double>(96,106)=c[4]; M.at<double>(96,108)=c[3]; M.at<double>(96,109)=c[2]; M.at<double>(96,111)=c[19]; M.at<double>(96,113)=c[5]; M.at<double>(96,114)=c[17]; M.at<double>(96,116)=c[12];
M.at<double>(97,42)=a[6]; M.at<double>(97,44)=a[12]; M.at<double>(97,46)=a[17]; M.at<double>(97,56)=b[6]; M.at<double>(97,66)=b[17]; M.at<double>(97,67)=b[8]; M.at<double>(97,68)=b[12]; M.at<double>(97,70)=b[16]; M.at<double>(97,91)=c[16]; M.at<double>(97,97)=c[12]; M.at<double>(97,101)=c[18]; M.at<double>(97,102)=c[17]; M.at<double>(97,104)=c[8]; M.at<double>(97,106)=c[6]; M.at<double>(97,108)=c[7];
M.at<double>(98,28)=a[12]; M.at<double>(98,41)=a[8]; M.at<double>(98,42)=a[14]; M.at<double>(98,47)=a[16]; M.at<double>(98,56)=b[14]; M.at<double>(98,57)=b[12]; M.at<double>(98,60)=b[16]; M.at<double>(98,62)=b[8]; M.at<double>(98,90)=c[16]; M.at<double>(98,101)=c[4]; M.at<double>(98,105)=c[3]; M.at<double>(98,106)=c[14]; M.at<double>(98,108)=c[5]; M.at<double>(98,109)=c[17]; M.at<double>(98,111)=c[8]; M.at<double>(98,114)=c[12];
M.at<double>(99,42)=a[7]; M.at<double>(99,44)=a[6]; M.at<double>(99,46)=a[18]; M.at<double>(99,56)=b[7]; M.at<double>(99,64)=b[8]; M.at<double>(99,66)=b[18]; M.at<double>(99,67)=b[17]; M.at<double>(99,68)=b[6]; M.at<double>(99,70)=b[12]; M.at<double>(99,91)=c[12]; M.at<double>(99,97)=c[6]; M.at<double>(99,102)=c[18]; M.at<double>(99,103)=c[8]; M.at<double>(99,104)=c[17]; M.at<double>(99,106)=c[7];
M.at<double>(100,51)=a[16]; M.at<double>(100,65)=b[16]; M.at<double>(100,89)=c[16]; M.at<double>(100,105)=c[10]; M.at<double>(100,109)=c[14];
M.at<double>(101,37)=a[9]; M.at<double>(101,38)=a[13]; M.at<double>(101,39)=a[20]; M.at<double>(101,48)=a[11]; M.at<double>(101,50)=a[3]; M.at<double>(101,53)=a[2]; M.at<double>(101,77)=b[9]; M.at<double>(101,78)=b[13]; M.at<double>(101,79)=b[20]; M.at<double>(101,80)=b[3]; M.at<double>(101,81)=b[11]; M.at<double>(101,82)=b[2]; M.at<double>(101,85)=c[11]; M.at<double>(101,86)=c[3]; M.at<double>(101,87)=c[2]; M.at<double>(101,92)=c[13]; M.at<double>(101,96)=c[20]; M.at<double>(101,98)=c[9];
M.at<double>(102,37)=a[13]; M.at<double>(102,38)=a[20]; M.at<double>(102,48)=a[3]; M.at<double>(102,50)=a[2]; M.at<double>(102,77)=b[13]; M.at<double>(102,78)=b[20]; M.at<double>(102,80)=b[2]; M.at<double>(102,81)=b[3]; M.at<double>(102,85)=c[3]; M.at<double>(102,86)=c[2]; M.at<double>(102,92)=c[20]; M.at<double>(102,98)=c[13];
M.at<double>(103,37)=a[20]; M.at<double>(103,48)=a[2]; M.at<double>(103,77)=b[20]; M.at<double>(103,81)=b[2]; M.at<double>(103,85)=c[2]; M.at<double>(103,98)=c[20];
M.at<double>(104,11)=u[4]; M.at<double>(104,28)=a[10]; M.at<double>(104,33)=a[14]; M.at<double>(104,34)=a[8]; M.at<double>(104,36)=a[16]; M.at<double>(104,51)=a[4]; M.at<double>(104,54)=b[8]; M.at<double>(104,57)=b[10]; M.at<double>(104,59)=b[14]; M.at<double>(104,65)=b[4]; M.at<double>(104,84)=b[16]; M.at<double>(104,88)=c[16]; M.at<double>(104,89)=c[4]; M.at<double>(104,99)=c[8]; M.at<double>(104,108)=c[1]; M.at<double>(104,109)=c[9]; M.at<double>(104,114)=c[10]; M.at<double>(104,117)=c[14];
M.at<double>(105,20)=u[4]; M.at<double>(105,27)=a[10]; M.at<double>(105,28)=a[4]; M.at<double>(105,32)=a[14]; M.at<double>(105,33)=a[8]; M.at<double>(105,51)=a[19]; M.at<double>(105,53)=a[16]; M.at<double>(105,55)=b[10]; M.at<double>(105,57)=b[4]; M.at<double>(105,59)=b[8]; M.at<double>(105,61)=b[14]; M.at<double>(105,65)=b[19]; M.at<double>(105,82)=b[16]; M.at<double>(105,87)=c[16]; M.at<double>(105,89)=c[19]; M.at<double>(105,108)=c[9]; M.at<double>(105,109)=c[13]; M.at<double>(105,113)=c[10]; M.at<double>(105,114)=c[4]; M.at<double>(105,116)=c[14]; M.at<double>(105,117)=c[8];
M.at<double>(106,27)=a[4]; M.at<double>(106,28)=a[19]; M.at<double>(106,31)=a[14]; M.at<double>(106,32)=a[8]; M.at<double>(106,50)=a[16]; M.at<double>(106,55)=b[4]; M.at<double>(106,57)=b[19]; M.at<double>(106,58)=b[14]; M.at<double>(106,61)=b[8]; M.at<double>(106,80)=b[16]; M.at<double>(106,86)=c[16]; M.at<double>(106,108)=c[13]; M.at<double>(106,109)=c[20]; M.at<double>(106,113)=c[4]; M.at<double>(106,114)=c[19]; M.at<double>(106,115)=c[14]; M.at<double>(106,116)=c[8];
M.at<double>(107,27)=a[19]; M.at<double>(107,31)=a[8]; M.at<double>(107,48)=a[16]; M.at<double>(107,55)=b[19]; M.at<double>(107,58)=b[8]; M.at<double>(107,81)=b[16]; M.at<double>(107,85)=c[16]; M.at<double>(107,108)=c[20]; M.at<double>(107,113)=c[19]; M.at<double>(107,115)=c[8];
M.at<double>(108,36)=a[20]; M.at<double>(108,48)=a[1]; M.at<double>(108,50)=a[9]; M.at<double>(108,53)=a[13]; M.at<double>(108,80)=b[9]; M.at<double>(108,81)=b[1]; M.at<double>(108,82)=b[13]; M.at<double>(108,84)=b[20]; M.at<double>(108,85)=c[1]; M.at<double>(108,86)=c[9]; M.at<double>(108,87)=c[13]; M.at<double>(108,88)=c[20];
M.at<double>(109,26)=u[3]; M.at<double>(109,27)=a[7]; M.at<double>(109,40)=a[6]; M.at<double>(109,42)=a[18]; M.at<double>(109,44)=a[17]; M.at<double>(109,46)=a[2]; M.at<double>(109,52)=a[12]; M.at<double>(109,55)=b[7]; M.at<double>(109,56)=b[18]; M.at<double>(109,66)=b[2]; M.at<double>(109,67)=b[19]; M.at<double>(109,68)=b[17]; M.at<double>(109,70)=b[8]; M.at<double>(109,72)=b[6]; M.at<double>(109,73)=b[12]; M.at<double>(109,91)=c[8]; M.at<double>(109,93)=c[12]; M.at<double>(109,95)=c[6]; M.at<double>(109,97)=c[17]; M.at<double>(109,102)=c[2]; M.at<double>(109,104)=c[19]; M.at<double>(109,106)=c[18]; M.at<double>(109,113)=c[7];
M.at<double>(110,7)=u[3]; M.at<double>(110,30)=a[5]; M.at<double>(110,34)=a[7]; M.at<double>(110,43)=a[15]; M.at<double>(110,45)=a[11]; M.at<double>(110,49)=a[6]; M.at<double>(110,54)=b[7]; M.at<double>(110,63)=b[11]; M.at<double>(110,67)=b[1]; M.at<double>(110,69)=b[10]; M.at<double>(110,71)=b[15]; M.at<double>(110,75)=b[5]; M.at<double>(110,76)=b[6]; M.at<double>(110,99)=c[7]; M.at<double>(110,100)=c[15]; M.at<double>(110,104)=c[1]; M.at<double>(110,107)=c[5]; M.at<double>(110,110)=c[10]; M.at<double>(110,112)=c[11]; M.at<double>(110,119)=c[6];
M.at<double>(111,18)=u[2]; M.at<double>(111,35)=a[20]; M.at<double>(111,36)=a[13]; M.at<double>(111,50)=a[1]; M.at<double>(111,53)=a[9]; M.at<double>(111,80)=b[1]; M.at<double>(111,82)=b[9]; M.at<double>(111,83)=b[20]; M.at<double>(111,84)=b[13]; M.at<double>(111,86)=c[1]; M.at<double>(111,87)=c[9]; M.at<double>(111,88)=c[13]; M.at<double>(111,118)=c[20];
M.at<double>(112,19)=u[2]; M.at<double>(112,31)=a[1]; M.at<double>(112,32)=a[9]; M.at<double>(112,33)=a[13]; M.at<double>(112,34)=a[20]; M.at<double>(112,36)=a[19]; M.at<double>(112,50)=a[10]; M.at<double>(112,53)=a[4]; M.at<double>(112,54)=b[20]; M.at<double>(112,58)=b[1]; M.at<double>(112,59)=b[13]; M.at<double>(112,61)=b[9]; M.at<double>(112,80)=b[10]; M.at<double>(112,82)=b[4]; M.at<double>(112,84)=b[19]; M.at<double>(112,86)=c[10]; M.at<double>(112,87)=c[4]; M.at<double>(112,88)=c[19]; M.at<double>(112,99)=c[20]; M.at<double>(112,115)=c[1]; M.at<double>(112,116)=c[9]; M.at<double>(112,117)=c[13];
M.at<double>(113,31)=a[9]; M.at<double>(113,32)=a[13]; M.at<double>(113,33)=a[20]; M.at<double>(113,48)=a[10]; M.at<double>(113,50)=a[4]; M.at<double>(113,53)=a[19]; M.at<double>(113,58)=b[9]; M.at<double>(113,59)=b[20]; M.at<double>(113,61)=b[13]; M.at<double>(113,80)=b[4]; M.at<double>(113,81)=b[10]; M.at<double>(113,82)=b[19]; M.at<double>(113,85)=c[10]; M.at<double>(113,86)=c[4]; M.at<double>(113,87)=c[19]; M.at<double>(113,115)=c[9]; M.at<double>(113,116)=c[13]; M.at<double>(113,117)=c[20];
M.at<double>(114,31)=a[13]; M.at<double>(114,32)=a[20]; M.at<double>(114,48)=a[4]; M.at<double>(114,50)=a[19]; M.at<double>(114,58)=b[13]; M.at<double>(114,61)=b[20]; M.at<double>(114,80)=b[19]; M.at<double>(114,81)=b[4]; M.at<double>(114,85)=c[4]; M.at<double>(114,86)=c[19]; M.at<double>(114,115)=c[13]; M.at<double>(114,116)=c[20];
M.at<double>(115,31)=a[20]; M.at<double>(115,48)=a[19]; M.at<double>(115,58)=b[20]; M.at<double>(115,81)=b[19]; M.at<double>(115,85)=c[19]; M.at<double>(115,115)=c[20];
M.at<double>(116,24)=u[2]; M.at<double>(116,29)=a[13]; M.at<double>(116,30)=a[20]; M.at<double>(116,37)=a[11]; M.at<double>(116,38)=a[3]; M.at<double>(116,39)=a[2]; M.at<double>(116,50)=a[15]; M.at<double>(116,52)=a[9]; M.at<double>(116,53)=a[18]; M.at<double>(116,73)=b[9]; M.at<double>(116,74)=b[13]; M.at<double>(116,75)=b[20]; M.at<double>(116,77)=b[11]; M.at<double>(116,78)=b[3]; M.at<double>(116,79)=b[2]; M.at<double>(116,80)=b[15]; M.at<double>(116,82)=b[18]; M.at<double>(116,86)=c[15]; M.at<double>(116,87)=c[18]; M.at<double>(116,92)=c[3]; M.at<double>(116,93)=c[9]; M.at<double>(116,94)=c[13]; M.at<double>(116,96)=c[2]; M.at<double>(116,98)=c[11]; M.at<double>(116,107)=c[20];
M.at<double>(117,29)=a[20]; M.at<double>(117,37)=a[3]; M.at<double>(117,38)=a[2]; M.at<double>(117,48)=a[15]; M.at<double>(117,50)=a[18]; M.at<double>(117,52)=a[13]; M.at<double>(117,73)=b[13]; M.at<double>(117,74)=b[20]; M.at<double>(117,77)=b[3]; M.at<double>(117,78)=b[2]; M.at<double>(117,80)=b[18]; M.at<double>(117,81)=b[15]; M.at<double>(117,85)=c[15]; M.at<double>(117,86)=c[18]; M.at<double>(117,92)=c[2]; M.at<double>(117,93)=c[13]; M.at<double>(117,94)=c[20]; M.at<double>(117,98)=c[3];
M.at<double>(118,27)=a[13]; M.at<double>(118,28)=a[20]; M.at<double>(118,31)=a[4]; M.at<double>(118,32)=a[19]; M.at<double>(118,48)=a[14]; M.at<double>(118,50)=a[8]; M.at<double>(118,55)=b[13]; M.at<double>(118,57)=b[20]; M.at<double>(118,58)=b[4]; M.at<double>(118,61)=b[19]; M.at<double>(118,80)=b[8]; M.at<double>(118,81)=b[14]; M.at<double>(118,85)=c[14]; M.at<double>(118,86)=c[8]; M.at<double>(118,113)=c[13]; M.at<double>(118,114)=c[20]; M.at<double>(118,115)=c[4]; M.at<double>(118,116)=c[19];
M.at<double>(119,27)=a[20]; M.at<double>(119,31)=a[19]; M.at<double>(119,48)=a[8]; M.at<double>(119,55)=b[20]; M.at<double>(119,58)=b[19]; M.at<double>(119,81)=b[8]; M.at<double>(119,85)=c[8]; M.at<double>(119,113)=c[20]; M.at<double>(119,115)=c[19];
return M.t();
}
Mat dls::Hessian(const double s[])
{
// the vector of monomials is
// m = [ const ; s1^2 * s2 ; s1 * s2 ; s1 * s3 ; s2 * s3 ; s2^2 * s3 ; s2^3 ; ...
// s1 * s3^2 ; s1 ; s3 ; s2 ; s2 * s3^2 ; s1^2 ; s3^2 ; s2^2 ; s3^3 ; ...
// s1 * s2 * s3 ; s1 * s2^2 ; s1^2 * s3 ; s1^3]
//
// deriv of m w.r.t. s1
//Hs3 = [0 ; 2 * s(1) * s(2) ; s(2) ; s(3) ; 0 ; 0 ; 0 ; ...
// s(3)^2 ; 1 ; 0 ; 0 ; 0 ; 2 * s(1) ; 0 ; 0 ; 0 ; ...
// s(2) * s(3) ; s(2)^2 ; 2*s(1)*s(3); 3 * s(1)^2];
double Hs1[20];
Hs1[0]=0; Hs1[1]=2*s[0]*s[1]; Hs1[2]=s[1]; Hs1[3]=s[2]; Hs1[4]=0; Hs1[5]=0; Hs1[6]=0;
Hs1[7]=s[2]*s[2]; Hs1[8]=1; Hs1[9]=0; Hs1[10]=0; Hs1[11]=0; Hs1[12]=2*s[0]; Hs1[13]=0;
Hs1[14]=0; Hs1[15]=0; Hs1[16]=s[1]*s[2]; Hs1[17]=s[1]*s[1]; Hs1[18]=2*s[0]*s[2]; Hs1[19]=3*s[0]*s[0];
// deriv of m w.r.t. s2
//Hs2 = [0 ; s(1)^2 ; s(1) ; 0 ; s(3) ; 2 * s(2) * s(3) ; 3 * s(2)^2 ; ...
// 0 ; 0 ; 0 ; 1 ; s(3)^2 ; 0 ; 0 ; 2 * s(2) ; 0 ; ...
// s(1) * s(3) ; s(1) * 2 * s(2) ; 0 ; 0];
double Hs2[20];
Hs2[0]=0; Hs2[1]=s[0]*s[0]; Hs2[2]=s[0]; Hs2[3]=0; Hs2[4]=s[2]; Hs2[5]=2*s[1]*s[2]; Hs2[6]=3*s[1]*s[1];
Hs2[7]=0; Hs2[8]=0; Hs2[9]=0; Hs2[10]=1; Hs2[11]=s[2]*s[2]; Hs2[12]=0; Hs2[13]=0;
Hs2[14]=2*s[1]; Hs2[15]=0; Hs2[16]=s[0]*s[2]; Hs2[17]=2*s[0]*s[1]; Hs2[18]=0; Hs2[19]=0;
// deriv of m w.r.t. s3
//Hs3 = [0 ; 0 ; 0 ; s(1) ; s(2) ; s(2)^2 ; 0 ; ...
// s(1) * 2 * s(3) ; 0 ; 1 ; 0 ; s(2) * 2 * s(3) ; 0 ; 2 * s(3) ; 0 ; 3 * s(3)^2 ; ...
// s(1) * s(2) ; 0 ; s(1)^2 ; 0];
double Hs3[20];
Hs3[0]=0; Hs3[1]=0; Hs3[2]=0; Hs3[3]=s[0]; Hs3[4]=s[1]; Hs3[5]=s[1]*s[1]; Hs3[6]=0;
Hs3[7]=2*s[0]*s[2]; Hs3[8]=0; Hs3[9]=1; Hs3[10]=0; Hs3[11]=2*s[1]*s[2]; Hs3[12]=0; Hs3[13]=2*s[2];
Hs3[14]=0; Hs3[15]=3*s[2]*s[2]; Hs3[16]=s[0]*s[1]; Hs3[17]=0; Hs3[18]=s[0]*s[0]; Hs3[19]=0;
// fill Hessian matrix
Mat H(3, 3, CV_64F);
H.at<double>(0,0) = Mat(Mat(f1coeff).rowRange(1,21).t()*Mat(20, 1, CV_64F, &Hs1)).at<double>(0,0);
H.at<double>(0,1) = Mat(Mat(f1coeff).rowRange(1,21).t()*Mat(20, 1, CV_64F, &Hs2)).at<double>(0,0);
H.at<double>(0,2) = Mat(Mat(f1coeff).rowRange(1,21).t()*Mat(20, 1, CV_64F, &Hs3)).at<double>(0,0);
H.at<double>(1,0) = Mat(Mat(f2coeff).rowRange(1,21).t()*Mat(20, 1, CV_64F, &Hs1)).at<double>(0,0);
H.at<double>(1,1) = Mat(Mat(f2coeff).rowRange(1,21).t()*Mat(20, 1, CV_64F, &Hs2)).at<double>(0,0);
H.at<double>(1,2) = Mat(Mat(f2coeff).rowRange(1,21).t()*Mat(20, 1, CV_64F, &Hs3)).at<double>(0,0);
H.at<double>(2,0) = Mat(Mat(f3coeff).rowRange(1,21).t()*Mat(20, 1, CV_64F, &Hs1)).at<double>(0,0);
H.at<double>(2,1) = Mat(Mat(f3coeff).rowRange(1,21).t()*Mat(20, 1, CV_64F, &Hs2)).at<double>(0,0);
H.at<double>(2,2) = Mat(Mat(f3coeff).rowRange(1,21).t()*Mat(20, 1, CV_64F, &Hs3)).at<double>(0,0);
return H;
}
Mat dls::cayley2rotbar(const Mat& s)
{
double s_mul1 = Mat(s.t()*s).at<double>(0,0);
Mat s_mul2 = s*s.t();
Mat eye = Mat::eye(3, 3, CV_64F);
return Mat( eye.mul(1.-s_mul1) + skewsymm(&s).mul(2.) + s_mul2.mul(2.) ).t();
}
Mat dls::skewsymm(const Mat * X1)
{
MatConstIterator_<double> it = X1->begin<double>();
return (Mat_<double>(3,3) << 0, -*(it+2), *(it+1),
*(it+2), 0, -*(it+0),
-*(it+1), *(it+0), 0);
}
Mat dls::rotx(const double t)
{
// rotx: rotation about y-axis
double ct = cos(t);
double st = sin(t);
return (Mat_<double>(3,3) << 1, 0, 0, 0, ct, -st, 0, st, ct);
}
Mat dls::roty(const double t)
{
// roty: rotation about y-axis
double ct = cos(t);
double st = sin(t);
return (Mat_<double>(3,3) << ct, 0, st, 0, 1, 0, -st, 0, ct);
}
Mat dls::rotz(const double t)
{
// rotz: rotation about y-axis
double ct = cos(t);
double st = sin(t);
return (Mat_<double>(3,3) << ct, -st, 0, st, ct, 0, 0, 0, 1);
}
Mat dls::mean(const Mat& M)
{
Mat m = Mat::zeros(3, 1, CV_64F);
for (int i = 0; i < M.cols; ++i) m += M.col(i);
return m.mul(1./(double)M.cols);
}
bool dls::is_empty(const Mat * M)
{
MatConstIterator_<double> it = M->begin<double>(), it_end = M->end<double>();
for(; it != it_end; ++it)
{
if(*it < 0) return false;
}
return true;
}
bool dls::positive_eigenvalues(const Mat * eigenvalues)
{
CV_Assert(eigenvalues && !eigenvalues->empty());
MatConstIterator_<double> it = eigenvalues->begin<double>();
return *(it) > 0 && *(it+1) > 0 && *(it+2) > 0;
}
}
| 119.929003 | 1,149 | 0.538788 | [
"vector"
] |
67b54d0b56fc616c6d64659765b51a3010ecc93e | 13,274 | hpp | C++ | include/basalt/camera/generic_camera.hpp | VladyslavUsenko/basalt-headers-mirror | a585db348a84e6f2219b8619e2fc26e8ad04e037 | [
"BSD-3-Clause"
] | 12 | 2020-05-02T11:40:39.000Z | 2022-01-05T13:39:38.000Z | include/basalt/camera/generic_camera.hpp | VladyslavUsenko/basalt-headers-mirror | a585db348a84e6f2219b8619e2fc26e8ad04e037 | [
"BSD-3-Clause"
] | null | null | null | include/basalt/camera/generic_camera.hpp | VladyslavUsenko/basalt-headers-mirror | a585db348a84e6f2219b8619e2fc26e8ad04e037 | [
"BSD-3-Clause"
] | 6 | 2020-06-02T12:52:14.000Z | 2021-12-27T02:49:35.000Z | /**
BSD 3-Clause License
This file is part of the Basalt project.
https://gitlab.com/VladyslavUsenko/basalt-headers.git
Copyright (c) 2019, Vladyslav Usenko and Nikolaus Demmel.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@file
@brief Implementation of generic camera model
*/
#pragma once
#include <basalt/camera/bal_camera.hpp>
#include <basalt/camera/double_sphere_camera.hpp>
#include <basalt/camera/extended_camera.hpp>
#include <basalt/camera/fov_camera.hpp>
#include <basalt/camera/kannala_brandt_camera4.hpp>
#include <basalt/camera/pinhole_camera.hpp>
#include <basalt/camera/unified_camera.hpp>
#include <variant>
namespace basalt {
using std::sqrt;
/// @brief Generic camera model that can store different camera models
///
/// Particular class of camera model is stored as \ref variant and can be casted
/// to specific type using std::visit.
template <typename Scalar_>
class GenericCamera {
using Scalar = Scalar_;
using Vec2 = Eigen::Matrix<Scalar, 2, 1>;
using Vec3 = Eigen::Matrix<Scalar, 3, 1>;
using Vec4 = Eigen::Matrix<Scalar, 4, 1>;
using VecX = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;
using Mat24 = Eigen::Matrix<Scalar, 2, 4>;
using Mat42 = Eigen::Matrix<Scalar, 4, 2>;
using Mat4 = Eigen::Matrix<Scalar, 4, 4>;
using VariantT =
std::variant<ExtendedUnifiedCamera<Scalar>, DoubleSphereCamera<Scalar>,
KannalaBrandtCamera4<Scalar>, UnifiedCamera<Scalar>,
PinholeCamera<Scalar>>; ///< Possible variants of camera
///< models.
public:
/// @brief Cast to different scalar type
template <typename Scalar2>
inline GenericCamera<Scalar2> cast() const {
GenericCamera<Scalar2> res;
std::visit([&](const auto& v) { res.variant = v.template cast<Scalar2>(); },
variant);
return res;
}
/// @brief Number of intrinsic parameters
inline int getN() const {
int res;
std::visit([&](const auto& v) { res = v.N; }, variant);
return res;
}
/// @brief Camera model name
inline std::string getName() const {
std::string res;
std::visit([&](const auto& v) { res = v.getName(); }, variant);
return res;
}
/// @brief Set parameters from initialization
///
/// @param[in] init vector [fx, fy, cx, cy]
inline void setFromInit(const Vec4& init) {
std::visit([&](auto& v) { return v.setFromInit(init); }, variant);
}
/// @brief Increment intrinsic parameters by inc and if necessary clamp the
/// values to the valid range
inline void applyInc(const VecX& inc) {
std::visit([&](auto& v) { return v += inc; }, variant);
}
/// @brief Returns a vector of intrinsic parameters
///
/// The order of parameters depends on the stored model.
/// @return vector of intrinsic parameters vector
inline VecX getParam() const {
VecX res;
std::visit([&](const auto& cam) { res = cam.getParam(); }, variant);
return res;
}
/// @brief Project a single point and optionally compute Jacobian
///
/// **SLOW** function, as it requires vtable lookup for every projection.
///
/// @param[in] p3d point to project
/// @param[out] proj result of projection
/// @param[out] d_proj_d_p3d if not nullptr computed Jacobian of projection
/// with respect to p3d
/// @return if projection is valid
template <typename DerivedJ3DPtr = std::nullptr_t>
inline bool project(const Vec4& p3d, Vec2& proj,
DerivedJ3DPtr d_proj_d_p3d = nullptr) const {
if constexpr (!std::is_same_v<DerivedJ3DPtr, std::nullptr_t>) {
static_assert(std::is_pointer_v<DerivedJ3DPtr>);
using DerivedJ3D = typename std::remove_pointer<DerivedJ3DPtr>::type;
EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(DerivedJ3D, 2, 4);
}
bool res;
std::visit(
[&](const auto& cam) { res = cam.project(p3d, proj, d_proj_d_p3d); },
variant);
return res;
}
/// @brief Unproject a single point and optionally compute Jacobian
///
/// **SLOW** function, as it requires vtable lookup for every unprojection.
///
/// @param[in] proj point to unproject
/// @param[out] p3d result of unprojection
/// @param[out] d_p3d_d_proj if not nullptr computed Jacobian of unprojection
/// with respect to proj
/// @return if unprojection is valid
template <typename DerivedJ2DPtr = std::nullptr_t>
inline bool unproject(const Vec2& proj, Vec4& p3d,
DerivedJ2DPtr d_p3d_d_proj = nullptr) const {
if constexpr (!std::is_same_v<DerivedJ2DPtr, std::nullptr_t>) {
static_assert(std::is_pointer_v<DerivedJ2DPtr>);
using DerivedJ2D = typename std::remove_pointer<DerivedJ2DPtr>::type;
EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(DerivedJ2D, 4, 2);
}
bool res;
std::visit(
[&](const auto& cam) { res = cam.unproject(proj, p3d, d_p3d_d_proj); },
variant);
return res;
}
/// @brief Project a single point and optionally compute Jacobian
///
/// **SLOW** function, as it requires vtable lookup for every projection.
///
/// @param[in] p3d point to project
/// @param[out] proj result of projection
/// @param[out] d_proj_d_p3d if not nullptr computed Jacobian of projection
/// with respect to p3d
/// @return if projection is valid
template <typename DerivedJ3DPtr = std::nullptr_t>
inline bool project(const Vec3& p3d, Vec2& proj,
DerivedJ3DPtr d_proj_d_p3d = nullptr) const {
if constexpr (!std::is_same_v<DerivedJ3DPtr, std::nullptr_t>) {
static_assert(std::is_pointer_v<DerivedJ3DPtr>);
using DerivedJ3D = typename std::remove_pointer<DerivedJ3DPtr>::type;
EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(DerivedJ3D, 2, 3);
}
bool res;
std::visit(
[&](const auto& cam) { res = cam.project(p3d, proj, d_proj_d_p3d); },
variant);
return res;
}
/// @brief Unproject a single point and optionally compute Jacobian
///
/// **SLOW** function, as it requires vtable lookup for every unprojection.
///
/// @param[in] proj point to unproject
/// @param[out] p3d result of unprojection
/// @param[out] d_p3d_d_proj if not nullptr computed Jacobian of unprojection
/// with respect to proj
/// @return if unprojection is valid
template <typename DerivedJ2DPtr = std::nullptr_t>
inline bool unproject(const Vec2& proj, Vec3& p3d,
DerivedJ2DPtr d_p3d_d_proj = nullptr) const {
if constexpr (!std::is_same_v<DerivedJ2DPtr, std::nullptr_t>) {
static_assert(std::is_pointer_v<DerivedJ2DPtr>);
using DerivedJ2D = typename std::remove_pointer<DerivedJ2DPtr>::type;
EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(DerivedJ2D, 3, 2);
}
bool res;
std::visit(
[&](const auto& cam) { res = cam.unproject(proj, p3d, d_p3d_d_proj); },
variant);
return res;
}
/// @brief Project a vector of points
///
/// @param[in] p3d points to project
/// @param[in] T_c_w transformation from world to camera frame that should be
/// applied to points before projection
/// @param[out] proj results of projection
/// @param[out] proj_success if projection is valid
inline void project(const Eigen::aligned_vector<Vec3>& p3d, const Mat4& T_c_w,
Eigen::aligned_vector<Vec2>& proj,
std::vector<bool>& proj_success) const {
std::visit(
[&](const auto& cam) {
proj.resize(p3d.size());
proj_success.resize(p3d.size());
for (size_t i = 0; i < p3d.size(); i++) {
proj_success[i] =
cam.project(T_c_w * p3d[i].homogeneous(), proj[i]);
}
},
variant);
}
/// @brief Project a vector of points
///
/// @param[in] p3d points to project
/// @param[in] T_c_w transformation from world to camera frame that should be
/// applied to points before projection
/// @param[out] proj results of projection
/// @param[out] proj_success if projection is valid
inline void project(const Eigen::aligned_vector<Vec4>& p3d, const Mat4& T_c_w,
Eigen::aligned_vector<Vec2>& proj,
std::vector<bool>& proj_success) const {
std::visit(
[&](const auto& cam) {
proj.resize(p3d.size());
proj_success.resize(p3d.size());
for (size_t i = 0; i < p3d.size(); i++) {
proj_success[i] = cam.project(T_c_w * p3d[i], proj[i]);
}
},
variant);
}
/// @brief Project a vector of points
///
/// @param[in] p3d points to project
/// @param[out] proj results of projection
/// @param[out] proj_success if projection is valid
inline void project(const Eigen::aligned_vector<Vec4>& p3d,
Eigen::aligned_vector<Vec2>& proj,
std::vector<bool>& proj_success) const {
std::visit(
[&](const auto& cam) {
proj.resize(p3d.size());
proj_success.resize(p3d.size());
for (size_t i = 0; i < p3d.size(); i++) {
proj_success[i] = cam.project(p3d[i], proj[i]);
}
},
variant);
}
/// @brief Project a vector of points, compute polar and azimuthal angles
///
/// @param[in] p3d points to project
/// @param[in] T_c_w transformation from world to camera frame that should be
/// applied to points before projection
/// @param[out] proj results of projection
/// @param[out] proj_success if projection is valid
inline void project(
const Eigen::aligned_vector<Vec4>& p3d, const Mat4& T_c_w,
Eigen::aligned_vector<Vec2>& proj, std::vector<bool>& proj_success,
Eigen::aligned_vector<Vec2>& polar_azimuthal_angle) const {
std::visit(
[&](const auto& cam) {
proj.resize(p3d.size());
proj_success.resize(p3d.size());
polar_azimuthal_angle.resize(p3d.size());
for (size_t i = 0; i < p3d.size(); i++) {
Vec4 p3dt = T_c_w * p3d[i];
proj_success[i] = cam.project(p3dt, proj[i]);
Scalar r2 = p3dt[0] * p3dt[0] + p3dt[1] * p3dt[1];
Scalar r = std::sqrt(r2);
polar_azimuthal_angle[i][0] = std::atan2(r, p3dt[2]);
polar_azimuthal_angle[i][1] = std::atan2(p3dt[0], p3dt[1]);
}
},
variant);
}
/// @brief Unproject a vector of points
///
/// @param[in] proj points to unproject
/// @param[out] p3d results of unprojection
/// @param[out] unproj_success if unprojection is valid
inline void unproject(const Eigen::aligned_vector<Vec2>& proj,
Eigen::aligned_vector<Vec4>& p3d,
std::vector<bool>& unproj_success) const {
std::visit(
[&](const auto& cam) {
p3d.resize(proj.size());
unproj_success.resize(proj.size());
for (size_t i = 0; i < p3d.size(); i++) {
unproj_success[i] = cam.unproject(proj[i], p3d[i]);
}
},
variant);
}
/// @brief Construct a particular type of camera model from name
static GenericCamera<Scalar> fromString(const std::string& name) {
GenericCamera<Scalar> res;
constexpr size_t VARIANT_SIZE = std::variant_size<VariantT>::value;
visitAllTypes<VARIANT_SIZE - 1>(res, name);
return res;
}
VariantT variant;
private:
/// @brief Iterate over all possible types of the variant and construct that
/// type that has a matching name
template <int I>
static void visitAllTypes(GenericCamera<Scalar>& res,
const std::string& name) {
if constexpr (I >= 0) {
using cam_t = typename std::variant_alternative<I, VariantT>::type;
if (cam_t::getName() == name) {
cam_t val;
res.variant = val;
}
visitAllTypes<I - 1>(res, name);
}
}
};
} // namespace basalt
| 36.367123 | 80 | 0.65067 | [
"vector",
"model"
] |
67b550b21cbc52da67d9bfe1b4ab2d2b7a4b9c5b | 5,677 | cpp | C++ | Lamp/src/Lamp/Physics/CookingFactory.cpp | SGS-Ivar/Lamp | e81195bbfb73b6b4bd2c6d4604e2e3aa532aecb2 | [
"MIT"
] | 2 | 2021-09-13T17:37:34.000Z | 2021-11-17T18:52:42.000Z | Lamp/src/Lamp/Physics/CookingFactory.cpp | SGS-Ivar/Lamp | e81195bbfb73b6b4bd2c6d4604e2e3aa532aecb2 | [
"MIT"
] | 20 | 2020-09-30T13:44:46.000Z | 2021-12-03T14:30:04.000Z | Lamp/src/Lamp/Physics/CookingFactory.cpp | ChunkTreasure1/Lamp | 65be1544322949d6640e1fd108ed5a018387d0eb | [
"MIT"
] | null | null | null | #include "lppch.h"
#include "CookingFactory.h"
#include "PhysXInternal.h"
#include "Lamp/Core/Buffer.h"
namespace Lamp
{
struct CookingData
{
physx::PxCooking* CookingSDK;
physx::PxCookingParams CookingParams;
CookingData(const physx::PxTolerancesScale& scale)
: CookingSDK(nullptr), CookingParams(scale)
{}
};
static CookingData* s_CookingData = nullptr;
void CookingFactory::Initialize()
{
s_CookingData = new CookingData(PhysXInternal::GetPhysXSDK().getTolerancesScale());
s_CookingData->CookingParams.meshWeldTolerance = 0.1f;
s_CookingData->CookingParams.meshPreprocessParams = physx::PxMeshPreprocessingFlag::eWELD_VERTICES;
s_CookingData->CookingParams.midphaseDesc = physx::PxMeshMidPhase::eBVH34;
s_CookingData->CookingSDK = PxCreateCooking(PX_PHYSICS_VERSION, PhysXInternal::GetFoundation(), s_CookingData->CookingParams);
LP_CORE_ASSERT(s_CookingData->CookingSDK, "Couldn't initialize PhysX Cooking SDK");
}
void CookingFactory::Shutdown()
{
s_CookingData->CookingSDK->release();
s_CookingData->CookingSDK = nullptr;
delete s_CookingData;
}
namespace Utils
{
static std::filesystem::path GetCacheDirectory()
{
return std::filesystem::path("Cache") / std::filesystem::path("Colliders");
}
static void CreateCacheDirectoryIfNeeded()
{
std::filesystem::path cacheDirectory = GetCacheDirectory();
if (!std::filesystem::exists(cacheDirectory))
{
std::filesystem::create_directories(cacheDirectory);
}
}
}
CookingResult CookingFactory::CookMesh(Ref<MeshColliderComponent> component, bool invalidateOld, std::vector<MeshColliderData>& outData)
{
Utils::CreateCacheDirectoryIfNeeded();
auto& collisionMesh = component->GetSpecification().CollisionMesh;
if (!collisionMesh->IsValid())
{
LP_CORE_ERROR("Invalid mesh!");
return CookingResult::Failure;
}
CookingResult result = CookingResult::Failure;
std::filesystem::path filepath = Utils::GetCacheDirectory() / (collisionMesh->Path.stem().string() + (component->GetSpecification().IsConvex ? "_convex.pxm" : "_tri.pxm"));
if (invalidateOld)
{
component->GetSpecification().ProcessedMeshes.clear();
bool removedCached = std::filesystem::remove(filepath);
if (!removedCached)
{
LP_CORE_WARN("Could not delete cached collider data for {0}", filepath);
}
}
if (!std::filesystem::exists(filepath))
{
result = component->GetSpecification().IsConvex ? CookConvexMesh(collisionMesh, outData) : CookTriangleMesh(collisionMesh, outData);
if (result == CookingResult::Success)
{
//Serialize collider
uint32_t bufferSize = 0;
uint32_t offset = 0;
for (auto& colliderData : outData)
{
bufferSize += sizeof(uint32_t);
bufferSize += colliderData.Size;
}
Buffer colliderBuffer;
colliderBuffer.Allocate(bufferSize);
for (auto& colliderData : outData)
{
colliderBuffer.Write((void*)&colliderData.Size, sizeof(uint32_t), offset);
offset += sizeof(uint32_t);
colliderBuffer.Write(colliderData.Data, colliderData.Size, offset);
offset += colliderData.Size;
}
bool success = FileSystem::WriteBytes(filepath, colliderBuffer);
colliderBuffer.Release();
if (!success)
{
LP_CORE_ERROR("Failed to write collider to {0}", filepath.string());
return CookingResult::Failure;
}
}
}
else
{
Buffer colliderBuffer = FileSystem::ReadBytes(filepath);
if (colliderBuffer.Size > 0)
{
uint32_t offset = 0;
const auto& submeshes = collisionMesh->GetSubMeshes();
for (const auto& submesh : submeshes)
{
MeshColliderData& data = outData.emplace_back();
data.Size = colliderBuffer.Read<uint32_t>(offset);
offset += sizeof(uint32_t);
data.Data = colliderBuffer.ReadBytes(data.Size, offset);
offset += data.Size;
data.Transform = glm::mat4(0.f);
}
colliderBuffer.Release();
result = CookingResult::Success;
}
}
if (result == CookingResult::Success && component->GetSpecification().ProcessedMeshes.size() == 0)
{
for (const auto& colliderData : outData)
{
GenerateDebugMesh(component, colliderData);
}
}
return result;
}
CookingResult CookingFactory::CookConvexMesh(const Ref<Mesh>& mesh, std::vector<MeshColliderData>& outData)
{
return CookingResult::Failure;
}
CookingResult CookingFactory::CookTriangleMesh(const Ref<Mesh>& mesh, std::vector<MeshColliderData>& outData)
{
return CookingResult();
}
void CookingFactory::GenerateDebugMesh(Ref<MeshColliderComponent> component, const MeshColliderData& colliderData)
{
}
} | 33.394118 | 180 | 0.581117 | [
"mesh",
"vector",
"transform"
] |
67b5c0abdf217d866cc898137e390d9ab2a6f883 | 285 | hpp | C++ | src/render/MaterialView.hpp | Yousazoe/Solar | 349c75f7a61b1727aa0c6d581cf75124b2502a57 | [
"Apache-2.0"
] | 1 | 2021-08-07T13:02:01.000Z | 2021-08-07T13:02:01.000Z | src/render/MaterialView.hpp | Yousazoe/Solar | 349c75f7a61b1727aa0c6d581cf75124b2502a57 | [
"Apache-2.0"
] | null | null | null | src/render/MaterialView.hpp | Yousazoe/Solar | 349c75f7a61b1727aa0c6d581cf75124b2502a57 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include<render/MaterialBlueprint.hpp>
namespace tutorial::graphics
{
class MaterialView final
{
public:
MaterialView(MaterialInstance& material) noexcept : _material{ material } {}
public:
auto on_gui() -> bool;
private:
MaterialInstance& _material;
};
}
| 15 | 78 | 0.733333 | [
"render"
] |
67b79d45dbb503a8fc5d5b189d3c788514ea48f8 | 4,719 | cc | C++ | runtime/module_exclusion_test.cc | Paschalis/android-llvm | 317f7fd4b736a0511a2273a2487915c34cf8933e | [
"Apache-2.0"
] | 20 | 2021-06-24T16:38:42.000Z | 2022-01-20T16:15:57.000Z | runtime/module_exclusion_test.cc | Paschalis/android-llvm | 317f7fd4b736a0511a2273a2487915c34cf8933e | [
"Apache-2.0"
] | null | null | null | runtime/module_exclusion_test.cc | Paschalis/android-llvm | 317f7fd4b736a0511a2273a2487915c34cf8933e | [
"Apache-2.0"
] | 4 | 2021-11-03T06:01:12.000Z | 2022-02-24T02:57:31.000Z | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common_compiler_test.h"
#include "class_linker-inl.h"
#include "handle.h"
#include "handle_scope-inl.h"
#include "mirror/class_loader-inl.h"
#include "mirror/dex_cache.h"
#include "mirror/object-inl.h"
#include "runtime.h"
#include "scoped_thread_state_change-inl.h"
#include "thread-current-inl.h"
#include "well_known_classes.h"
namespace art {
class ModuleExclusionTest : public CommonCompilerTest {
public:
explicit ModuleExclusionTest(const std::string& module)
: CommonCompilerTest(),
module_(module) {}
std::vector<std::string> GetLibCoreModuleNames() const override {
std::vector<std::string> modules = CommonCompilerTest::GetLibCoreModuleNames();
// Exclude `module_` from boot class path.
auto it = std::find(modules.begin(), modules.end(), module_);
if (it != modules.end()) {
modules.erase(it);
}
return modules;
}
void DoTest() {
Thread* self = Thread::Current();
ScopedObjectAccess soa(self);
StackHandleScope<2u> hs(self);
Runtime* runtime = Runtime::Current();
ASSERT_TRUE(runtime->IsAotCompiler());
ClassLinker* class_linker = runtime->GetClassLinker();
CHECK(loaded_dex_files_.empty());
Handle<mirror::ClassLoader> class_loader = hs.NewHandle(LoadModule(soa, class_linker));
MutableHandle<mirror::DexCache> dex_cache = hs.NewHandle<mirror::DexCache>(nullptr);
CHECK(!loaded_dex_files_.empty());
// Verify that classes defined in the loaded dex files cannot be resolved.
for (const std::unique_ptr<const DexFile>& dex_file : loaded_dex_files_) {
dex_cache.Assign(class_linker->RegisterDexFile(*dex_file, class_loader.Get()));
for (size_t i = 0u, size = dex_file->NumClassDefs(); i != size; ++i) {
const dex::ClassDef& class_def = dex_file->GetClassDef(i);
ObjPtr<mirror::Class> resolved_type =
class_linker->ResolveType(class_def.class_idx_, dex_cache, class_loader);
ASSERT_TRUE(resolved_type == nullptr) << resolved_type->PrettyDescriptor();
ASSERT_TRUE(self->IsExceptionPending());
self->ClearException();
}
}
}
private:
std::string GetModuleFileName() const {
std::vector<std::string> filename = GetLibCoreDexFileNames({ module_ });
CHECK_EQ(filename.size(), 1u);
return filename[0];
}
// Load the module as an app, i.e. in a class loader other than the boot class loader.
ObjPtr<mirror::ClassLoader> LoadModule(ScopedObjectAccess& soa, ClassLinker* class_linker)
REQUIRES_SHARED(Locks::mutator_lock_) {
std::string filename = GetModuleFileName();
std::vector<std::unique_ptr<const DexFile>> dex_files = OpenDexFiles(filename.c_str());
std::vector<const DexFile*> class_path;
CHECK_NE(0U, dex_files.size());
for (auto& dex_file : dex_files) {
class_path.push_back(dex_file.get());
loaded_dex_files_.push_back(std::move(dex_file));
}
StackHandleScope<1u> hs(soa.Self());
Handle<mirror::Class> loader_class(hs.NewHandle(
soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader)));
ScopedNullHandle<mirror::ClassLoader> parent_loader;
ScopedNullHandle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries;
ObjPtr<mirror::ClassLoader> result = class_linker->CreateWellKnownClassLoader(
soa.Self(),
class_path,
loader_class,
parent_loader,
shared_libraries);
// Verify that the result has the correct class.
CHECK_EQ(loader_class.Get(), result->GetClass());
// Verify that the parent is not null. The boot class loader will be set up as a
// proper BootClassLoader object.
ObjPtr<mirror::ClassLoader> actual_parent(result->GetParent());
CHECK(actual_parent != nullptr);
CHECK(class_linker->IsBootClassLoader(soa, actual_parent));
return result;
}
const std::string module_;
};
class ConscryptExclusionTest : public ModuleExclusionTest {
public:
ConscryptExclusionTest() : ModuleExclusionTest("conscrypt") {}
};
TEST_F(ConscryptExclusionTest, Test) {
DoTest();
}
} // namespace art
| 36.022901 | 92 | 0.709472 | [
"object",
"vector"
] |
67b7e80b06ca9eeea2b261ff964eb4e85695c386 | 2,635 | cc | C++ | hoomd/dem/SWCAPotential.cc | pabloferz/hoomd-blue | 9a27f63b9243b8a3a04ccd3047f686cb0e12ec31 | [
"BSD-3-Clause"
] | null | null | null | hoomd/dem/SWCAPotential.cc | pabloferz/hoomd-blue | 9a27f63b9243b8a3a04ccd3047f686cb0e12ec31 | [
"BSD-3-Clause"
] | null | null | null | hoomd/dem/SWCAPotential.cc | pabloferz/hoomd-blue | 9a27f63b9243b8a3a04ccd3047f686cb0e12ec31 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009-2022 The Regents of the University of Michigan.
// Part of HOOMD-blue, released under the BSD 3-Clause License.
#ifndef __SWCAPOTENTIAL_CC__
#define __SWCAPOTENTIAL_CC__
#include "SWCAPotential.h"
#include "DEMEvaluator.h"
#include <algorithm>
using namespace std;
namespace hoomd
{
namespace dem
{
/*! evaluate the potential between two points */
// rij: vector from particle i's COM to particle j's
// r0: vector from particle i's COM to the interaction point on particle i
// rPrime: vector from particle i's COM to the interaction point on particle j
template<typename Real, typename Real4, typename FrictionModel>
template<typename Vec, typename Torque>
DEVICE inline void SWCAPotential<Real, Real4, FrictionModel>::evaluate(const Vec& rij,
const Vec& r0,
const Vec& rPrime,
Real& potential,
Vec& force_i,
Torque& torque_i,
Vec& force_j,
Torque& torque_j,
float modFactor) const
{
const Vec r0Prime(rPrime - r0);
// Use rmd to calculate SWCA force
const Real magr(sqrt(dot(r0Prime, r0Prime)));
const Real rmd(magr - m_delta);
if (rmd * rmd <= m_rcutsq)
{
const Real rmdsqInv(Real(1.0) / (rmd * rmd));
const Real rmdsq3Inv(rmdsqInv * rmdsqInv * rmdsqInv);
// Force between r0 and rPrime is prefactor*r0Prime
const Real prefactor(modFactor * 24 * m_sigma6 * rmdsq3Inv * rmdsqInv
* (1 - 2 * m_sigma6 * rmdsq3Inv));
const Vec conservativeForce(prefactor * r0Prime);
const Vec force(m_frictionParams.modifiedForce(r0Prime, conservativeForce));
potential += modFactor * (4 * m_sigma6 * rmdsq3Inv * (m_sigma6 * rmdsq3Inv - 1) + 1);
// potential = m_delta;
// rjPrime is rPrime relative to particle j's COM
const Vec rjPrime(rPrime - rij);
// Add forces and torques
force_i += force;
torque_i += cross(r0, force);
force_j -= force;
torque_j += cross(rjPrime, -force);
}
}
} // end namespace dem
} // end namespace hoomd
#endif
| 38.75 | 93 | 0.52296 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.