blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6b3f86f9436aaf9d4925005a7717d355eae7e125 | e217eaf05d0dab8dd339032b6c58636841aa8815 | /IfcAlignment/src/OpenInfraPlatform/IfcAlignment/entity/IfcTypeObject.cpp | 8a05abd286a23974eac334afba40a681cbb0e20b | [] | no_license | bigdoods/OpenInfraPlatform | f7785ebe4cb46e24d7f636e1b4110679d78a4303 | 0266e86a9f25f2ea9ec837d8d340d31a58a83c8e | refs/heads/master | 2021-01-21T03:41:20.124443 | 2016-01-26T23:20:21 | 2016-01-26T23:20:21 | 57,377,206 | 0 | 1 | null | 2016-04-29T10:38:19 | 2016-04-29T10:38:19 | null | UTF-8 | C++ | false | false | 5,041 | cpp | /*! \verbatim
* \copyright Copyright (c) 2015 Julian Amann. All rights reserved.
* \author Julian Amann <julian.amann@tum.de> (https://www.cms.bgu.tum.de/en/team/amann)
* \brief This file is part of the BlueFramework.
* \endverbatim
*/
#include <sstream>
#include <limits>
#include "OpenInfraPlatform/IfcAlignment/model/IfcAlignmentP6Exception.h"
#include "OpenInfraPlatform/IfcAlignment/reader/ReaderUtil.h"
#include "OpenInfraPlatform/IfcAlignment/writer/WriterUtil.h"
#include "OpenInfraPlatform/IfcAlignment/IfcAlignmentP6EntityEnums.h"
#include "include/IfcGloballyUniqueId.h"
#include "include/IfcIdentifier.h"
#include "include/IfcLabel.h"
#include "include/IfcOwnerHistory.h"
#include "include/IfcPropertySetDefinition.h"
#include "include/IfcRelAggregates.h"
#include "include/IfcRelAssigns.h"
#include "include/IfcRelAssociates.h"
#include "include/IfcRelDeclares.h"
#include "include/IfcRelDefinesByType.h"
#include "include/IfcRelNests.h"
#include "include/IfcText.h"
#include "include/IfcTypeObject.h"
namespace OpenInfraPlatform
{
namespace IfcAlignment
{
// ENTITY IfcTypeObject
IfcTypeObject::IfcTypeObject() { m_entity_enum = IFCTYPEOBJECT; }
IfcTypeObject::IfcTypeObject( int id ) { m_id = id; m_entity_enum = IFCTYPEOBJECT; }
IfcTypeObject::~IfcTypeObject() {}
// method setEntity takes over all attributes from another instance of the class
void IfcTypeObject::setEntity( shared_ptr<IfcAlignmentP6Entity> other_entity )
{
shared_ptr<IfcTypeObject> other = dynamic_pointer_cast<IfcTypeObject>(other_entity);
if( !other) { return; }
m_GlobalId = other->m_GlobalId;
m_OwnerHistory = other->m_OwnerHistory;
m_Name = other->m_Name;
m_Description = other->m_Description;
m_ApplicableOccurrence = other->m_ApplicableOccurrence;
m_HasPropertySets = other->m_HasPropertySets;
}
void IfcTypeObject::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_id << "=IFCTYPEOBJECT" << "(";
if( m_GlobalId ) { m_GlobalId->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_OwnerHistory ) { stream << "#" << m_OwnerHistory->getId(); } else { stream << "$"; }
stream << ",";
if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_Description ) { m_Description->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
if( m_ApplicableOccurrence ) { m_ApplicableOccurrence->getStepParameter( stream ); } else { stream << "$"; }
stream << ",";
writeEntityList( stream, m_HasPropertySets );
stream << ");";
}
void IfcTypeObject::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_id; }
void IfcTypeObject::readStepData( std::vector<std::string>& args, const std::map<int,shared_ptr<IfcAlignmentP6Entity> >& map )
{
const int num_args = (int)args.size();
if( num_args<6 ){ std::stringstream strserr; strserr << "Wrong parameter count for entity IfcTypeObject, expecting 6, having " << num_args << ". Object id: " << getId() << std::endl; throw IfcAlignmentP6Exception( strserr.str().c_str() ); }
#ifdef _DEBUG
if( num_args>6 ){ std::cout << "Wrong parameter count for entity IfcTypeObject, expecting 6, having " << num_args << ". Object id: " << getId() << std::endl; }
#endif
m_GlobalId = IfcGloballyUniqueId::readStepData( args[0] );
readEntityReference( args[1], m_OwnerHistory, map );
m_Name = IfcLabel::readStepData( args[2] );
m_Description = IfcText::readStepData( args[3] );
m_ApplicableOccurrence = IfcIdentifier::readStepData( args[4] );
readEntityReferenceList( args[5], m_HasPropertySets, map );
}
void IfcTypeObject::setInverseCounterparts( shared_ptr<IfcAlignmentP6Entity> ptr_self_entity )
{
IfcObjectDefinition::setInverseCounterparts( ptr_self_entity );
shared_ptr<IfcTypeObject> ptr_self = dynamic_pointer_cast<IfcTypeObject>( ptr_self_entity );
if( !ptr_self ) { throw IfcAlignmentP6Exception( "IfcTypeObject::setInverseCounterparts: type mismatch" ); }
for( int i=0; i<m_HasPropertySets.size(); ++i )
{
if( m_HasPropertySets[i] )
{
m_HasPropertySets[i]->m_DefinesType_inverse.push_back( ptr_self );
}
}
}
void IfcTypeObject::unlinkSelf()
{
IfcObjectDefinition::unlinkSelf();
for( int i=0; i<m_HasPropertySets.size(); ++i )
{
if( m_HasPropertySets[i] )
{
std::vector<weak_ptr<IfcTypeObject> >& DefinesType_inverse = m_HasPropertySets[i]->m_DefinesType_inverse;
std::vector<weak_ptr<IfcTypeObject> >::iterator it_DefinesType_inverse;
for( it_DefinesType_inverse = DefinesType_inverse.begin(); it_DefinesType_inverse != DefinesType_inverse.end(); ++it_DefinesType_inverse)
{
shared_ptr<IfcTypeObject> self_candidate( *it_DefinesType_inverse );
if( self_candidate->getId() == this->getId() )
{
DefinesType_inverse.erase( it_DefinesType_inverse );
break;
}
}
}
}
}
} // end namespace IfcAlignment
} // end namespace OpenInfraPlatform
| [
"planung.cms.bv@tum.de"
] | planung.cms.bv@tum.de |
a666d2fbb36bbccf3e035d705f1f293522899592 | db84bf6382c21920c3649b184f20ea48f54c3048 | /mjdemonstrator/src/MJDemoJSONDet.cc | a5fe64b68b67bd32c0a1452f6f99c739b41ccad0 | [] | no_license | liebercanis/MaGeLAr | 85c540e3b4c5a48edea9bc0520c9d1a1dcbae73c | aa30b01f3c9c0f5de0f040d05681d358860a31b3 | refs/heads/master | 2020-09-20T12:48:38.106634 | 2020-03-06T18:43:19 | 2020-03-06T18:43:19 | 224,483,424 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,394 | cc | //---------------------------------------------------------------------------//
//bb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nu//
// //
// //
// MaGe Simulation //
// //
// This code implementation is the intellectual property of the //
// MAJORANA and Gerda Collaborations. It is based on Geant4, an //
// intellectual property of the RD44 GEANT4 collaboration. //
// //
// ********************* //
// //
// Neither the authors of this software system, nor their employing //
// institutes, nor the agencies providing financial support for this //
// work make any representation or warranty, express or implied, //
// regarding this software system or assume any liability for its use. //
// By copying, distributing or modifying the Program (or any work based //
// on on the Program) you indicate your acceptance of this statement, //
// and all its terms. //
// //
//bb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nubb0nu//
//---------------------------------------------------------------------------//
/**
* $Id: MGheadertemplate.hh,v 1.1 2004-12-09 08:58:35 pandola Exp $
*
* CLASS DECLARATION: MJDemoJSONDet.cc
*
*---------------------------------------------------------------------------//
*
* DESCRIPTION:
*
*/
// Begin description of class here
/**
*
*Creates a detector from parameters read in MGCrystalData
*
*
*/
// End class description
//
/**
* SPECIAL NOTES:
*
*/
//
// --------------------------------------------------------------------------//
/**
* AUTHOR: Kris Vorren
* CONTACT: krisvorren@unc.edu
* FIRST SUBMISSION: Oct 29, 2013
*
* REVISION:
*
* 10-29-2013, Created, K. Vorren
*/
// --------------------------------------------------------------------------//
#include "G4LogicalVolume.hh"
#include "G4LogicalVolumeStore.hh"
#include "G4UIcommand.hh"
//#include "G4Tubs.hh"
//#include "G4SubtractionSolid.hh"
#include "G4Material.hh"
#include "G4VisAttributes.hh"
#include "G4Color.hh"
#include "G4ThreeVector.hh"
#include "G4Polycone.hh"
//---------------------------------------------------------------------------//
#include "io/MGLogger.hh"
#include "mjio/MJJSONReader.hh"
#include "mjdemonstrator/MJDemoJSONDet.hh"
#include "mjdemonstrator/MJVDemoPart.hh"
//---------------------------------------------------------------------------//
using namespace CLHEP;
MJDemoJSONDet::MJDemoJSONDet(G4String partName, G4String serialNumber) :
MJVDemoDetector(partName, serialNumber, "MJ80-02-011", "Germanium-Enr")
{
ReadJSONFile();
}
MJDemoJSONDet::MJDemoJSONDet(const MJDemoJSONDet & rhs) :
MJVDemoDetector(rhs), fDetParameters(rhs.fDetParameters)
{;}
MJDemoJSONDet::~MJDemoJSONDet()
{;}
void MJDemoJSONDet::ReadJSONFile()
{
if(fDetParameters.size())
fDetParameters.clear();
MJJSONReader* reader = new MJJSONReader();
vector<double> r = reader->ReadDetectorRs(fSerialNumber);
vector<double> z = reader->ReadDetectorZs(fSerialNumber);
delete reader;
if(r.size() && z.size() && r.size() == z.size())
{
G4int numPlanes = r.size();
G4double maxZ = 0.0;
G4double minZ = 0.0;
G4double maxR = 0.0;
for(G4int i = 0; i < numPlanes; i++)
{
G4double tempZ = z.at(i);
G4double tempR = r.at(i);
maxR = (tempR > maxR) ? tempR : maxR;
maxZ = (tempZ > maxZ) ? tempZ : maxZ; //return the max of maxZ and temp
minZ = (tempZ < minZ) ? tempZ : minZ; //return the min of minZ and temp
G4ThreeVector tempVec = G4ThreeVector(r.at(i), tempZ);
fDetParameters.push_back(tempVec);
}
fCrystalDiameter = 2*maxR;
if((maxZ - minZ) > 0)
{
fCrystalHeight = maxZ - minZ;
MGLog(routine) << "Crystal height set to " << fCrystalHeight << "." << endlog;
}
else
MGLog(error) << "Error! Non-positive crystal height!" << endlog;
}
else
{
fDetParameters.clear();
fDetParameters.push_back(G4ThreeVector(77.0/2*mm, 33.0/2*mm));
fDetParameters.push_back(G4ThreeVector(77.0/2*mm, -33.0/2*mm));
fCrystalHeight = 33*mm;
}
}
G4LogicalVolume* MJDemoJSONDet::ConstructPart()
{
G4LogicalVolumeStore *storePtr = G4LogicalVolumeStore::GetInstance();
G4String logicalName = fPartName + "_JSON" + "_" + fPartMaterial;
G4LogicalVolume* pVol = storePtr->GetVolume(logicalName, false);
if (pVol == NULL){
G4int numPlanes = fDetParameters.size();
G4double *r = new G4double[numPlanes];
G4double *z = new G4double[numPlanes];
G4double *zeros = new G4double[numPlanes];
for(G4int i = 0; i<numPlanes; i++)
{
//originally this class was intended to read (r,z) pairs, now the G4ThreeVector is kept to ensure the r's and z's stay together
//crystal assembly rotates this for us
r[i] = fDetParameters.at(/*numPlanes - 1 - */i).getX(); //getR
z[i] = -fDetParameters.at(/*numPlanes - 1 - */i).getY(); //getZ
zeros[i] = 0;
}
//G4RotationMatrix* rotTest = new G4RotationMatrix(0, pi, 0)
G4Polycone *crystal = new G4Polycone("crystal", 0, 2.*pi, numPlanes, z, zeros ,r);
delete[] zeros;
delete[] r;
delete[] z;
G4VisAttributes* germaniumVisAtt = new G4VisAttributes(G4Colour(0.878,0.878,0.867)); // New germanium color
germaniumVisAtt->SetForceWireframe( false );
G4Material *material = G4Material::GetMaterial(this->GetMaterial());
pVol = new G4LogicalVolume(crystal, material, logicalName);
pVol->SetVisAttributes(germaniumVisAtt);
MGLog(debugging) << "Created crystal logical from JSON file." << endlog;
}
else MGLog(debugging) << "Using pre-existing JSON file geometry" << endlog;
return pVol;
}
| [
"mgold@unm.edu"
] | mgold@unm.edu |
2f48319f54521d3e13f6c84b278caede1db93b37 | 9c5a7750e380f9e882c8e2c0a379a7d2a933beae | /LDS/Global.cpp | 9a758db612c277efd2b60b844766e231ee0d08fb | [] | no_license | presscad/LDS | 973e8752affd1147982a7dd48350db5c318ed1f3 | e443ded9cb2fe679734dc17af8638adcf50465d4 | refs/heads/master | 2021-02-15T20:30:26.467280 | 2020-02-28T06:13:53 | 2020-02-28T06:13:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 633 | cpp | #include "stdafx.h"
#include "Global.h"
#include "Tower.h"
#include "SortFunc.h"
#ifdef __LDS_CONTEXT_
#include "..\StdComTempl\IStdComTempl.h"
#endif
#include ".\StdPartSolid\FittingLibrary.h"
CTower Ta;
Global globalVars;
Global::Global()
{
m_siVarCount=0;
}
Global::~Global()
{
}
Global::VAR* Global::RegisterGlobalVar(Global::VAR var)
{
m_siVarCount++;
xarrGlobalVars[m_siVarCount-1]=var;
return &xarrGlobalVars[m_siVarCount-1];
}
void Global::InitialzeGlobalVars()
{
CHeapSort<Global::VAR>::HeapSortClassic(xarrGlobalVars,m_siVarCount);
for (short i=0;i<m_siVarCount;i++)
xarrGlobalVars[i].pVar->GlobalInitialze();
}
| [
"wxc_sxy@163.com"
] | wxc_sxy@163.com |
da4daa3a8abe747f7b9d7fbe7b9e0a1970c4a6bc | ba73c355eaf88b2a4d984145e306b83cf53da9b8 | /controller/ironstack_types/openflow_flow_description.h | eb7182cc7c8a5783c12430031fb96ffb877874ad | [
"BSD-3-Clause"
] | permissive | zteo-phd-software/ironstack | cd0d10e2666fd0e829e8cfaea24fcd49cc2adaf0 | 649f82ddcbb82831796fa2a1e1d1b8cc0f94a8e0 | refs/heads/master | 2020-02-26T15:38:23.943187 | 2016-09-30T18:42:19 | 2016-09-30T18:42:19 | 69,498,904 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,105 | h | #pragma once
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <vector>
#include <memory>
#include <inttypes.h>
#include "../openflow_types/of_match.h"
#include "openflow_action_list.h"
using namespace std;
class openflow_flow_description {
public:
openflow_flow_description();
openflow_flow_description(const of_match& criteria_, const openflow_action_list& action_list_,
uint64_t cookie_, uint16_t priority_):criteria(criteria_),
action_list(action_list_),
cookie(cookie_),
priority(priority_) {}
void clear();
string to_string() const;
string to_string_summarized() const;
// matches criteria and action list
// priority and cookies are not checked!
bool operator==(const openflow_flow_description& other) const;
bool operator!=(const openflow_flow_description& other) const;
// user-accessible fields
of_match criteria;
openflow_action_list action_list;
uint64_t cookie;
uint16_t priority;
// for serialization
uint32_t serialize(autobuf& dest) const;
bool deserialize(const autobuf& content);
};
| [
"zhiyuan.teo@gmail.com"
] | zhiyuan.teo@gmail.com |
81f80a2d179d53de625ec23a1dc65a1bdd9a5528 | c67f449dc7187f154df7093a95ddcc14a3f0a18f | /youngseokcoin/src/consensus/merkle.h | 8035c3e6d2a54e7dd463f0f9b860c70ad17ea8ec | [
"MIT"
] | permissive | youngseokaaa-presentation/A_system_to_ensure_the_integrity_of_Internet_of_things_by_using_Blockchain | cee9ba19e9d029759fc2fe4a43235c56fd9abe43 | b2a47bc63386b5a115fc3ce62997034ebd8d4a1e | refs/heads/master | 2023-02-17T07:58:43.043470 | 2021-01-11T05:40:28 | 2021-01-11T05:40:28 | 295,317,246 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,345 | h | // Copyright (c) 2015 The Youngseokcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef YOUNGSEOKCOIN_MERKLE
#define YOUNGSEOKCOIN_MERKLE
#include <stdint.h>
#include <vector>
#include "primitives/transaction.h"
#include "primitives/block.h"
#include "uint256.h"
uint256 ComputeMerkleRoot(const std::vector<uint256>& leaves, bool* mutated = nullptr);
std::vector<uint256> ComputeMerkleBranch(const std::vector<uint256>& leaves, uint32_t position);
uint256 ComputeMerkleRootFromBranch(const uint256& leaf, const std::vector<uint256>& branch, uint32_t position);
/*
* Compute the Merkle root of the transactions in a block.
* *mutated is set to true if a duplicated subtree was found.
*/
uint256 BlockMerkleRoot(const CBlock& block, bool* mutated = nullptr);
/*
* Compute the Merkle root of the witness transactions in a block.
* *mutated is set to true if a duplicated subtree was found.
*/
uint256 BlockWitnessMerkleRoot(const CBlock& block, bool* mutated = nullptr);
/*
* Compute the Merkle branch for the tree of transactions in a block, for a
* given position.
* This can be verified using ComputeMerkleRootFromBranch.
*/
std::vector<uint256> BlockMerkleBranch(const CBlock& block, uint32_t position);
#endif
| [
"youngseokaaa@gmail.com"
] | youngseokaaa@gmail.com |
af936f435e707b6d47f937a20f99157dce34ca9f | 15cdb3b515171765c44815c199f54394301f8fd2 | /QTMap2.0/QTMap2.0/mw1.h | e456399a26575539383b521de0b4c789a5f4053f | [] | no_license | EvenLee2/QTMap_2.0 | 81cf5811f4d21b1f0601f725464814174e12ec9a | 03e6ed08e5df39bbc5d0860886217c59b1af8f39 | refs/heads/master | 2020-03-18T14:32:35.559044 | 2018-05-25T13:22:52 | 2018-05-25T13:22:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,017 | h | #ifndef MW1_H
#define MW1_H
#include<QPushButton>
#include <QMainWindow>
#include<QKeyEvent>
#include<QEvent>
#include <QImage>
#include <QPainter>
#include<QKeyEvent>
#include<string.h>
#include "rpgobj.h"
#include "world.h"
#include<QTime>
#include<QTimer>
namespace Ui {
class MW1;
}
class MW1 : public QMainWindow
{
Q_OBJECT
public:
QPushButton* startButton;
QPushButton* talkButton;
QPushButton* quitButton;
explicit MW1(QWidget *parent = 0);
~MW1();
void paintEvent(QPaintEvent *e);
void keyPressEvent(QKeyEvent *);
static int talkpass;
static int talknumber;
static int quitnumber;
static int createtalkboard;
static string rec[100];
private slots:
void on_pushButton_clicked();
private:
Ui::MW1 *ui;
World _game;
QTimer *timer1;
QTimer *timer2;
//时钟,控制玩家移动频率
public slots:
void start();
void starttalk();
void quit();
};
#endif // MW1_H
| [
"noreply@github.com"
] | noreply@github.com |
5e39e6229e9aba292bc27a573bcd52b0ac7b8386 | 6d208b06f33424778022008a24116609d7b0da93 | /src/options_ec2-describe-images.hpp | 19cf8cf8ed7261ad031abd6c1466c326c00c7681 | [
"BSD-4-Clause"
] | permissive | kaikrueger/ec2-api | 566b33fef2db0722ce5c1a934871f041f806daf9 | c53b7adcc83ae0c1ba758abe10ac8d4c41e05d69 | refs/heads/master | 2021-01-19T12:39:46.388780 | 2012-04-26T06:45:16 | 2012-04-26T06:45:16 | 2,599,117 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,365 | hpp | /*
* @file options_ec2-describe-images.hpp
* @date 2011-10-17
*
* Created by Kai Krueger <kai.krueger@itwm.fraunhofer.de>
*
* Copyright (c) 2011 Fraunhofer ITWM
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 _options_ec2_describe_images_hpp_
#define _options_ec2_describe_images_hpp_
#include "options.hpp"
namespace ec2 {
namespace options {
class ec2_describe_images : public ec2::options::optionCommand {
public:
typedef ec2::shared_ptr<ec2_describe_images> Ptr;
ec2_describe_images() : optionCommand("DescribeImages", "DescribeInstancesResponse") {
complete(specific());
}
virtual ~ec2_describe_images() {}
void setOptions(const po::variables_map &vm, const std::vector<std::string> rest, ec2::Map_Type &opt) {
for (unsigned int i = 0; i < rest.size(); ++i) {
std::stringstream key;
key << "ImageId."<< (i+1);
opt[key.str()] = rest[i];
}
if ( !vm.count("all")) {
opt["Owner.1"] = "self";
}
}
void help() {
std::cout<< "SYNOPSIS"<< std::endl;
std::cout<< " ec2-describe-images [GENERAL OPTIONS] [AMI [...]] [-a] [-o OWNER [...]] [-x USER [...]]"<< std::endl;
std::cout<< "DESCRIPTION"<< std::endl;
std::cout<< " List and describe registered AMIs and AMIs you have launch permissions for."<< std::endl;
std::cout<< " The AMI parameters, if specified, are the AMIs to describe."<< std::endl;
std::cout<< " The result set of AMIs described are the intersection of the AMIs specified,"<< std::endl;
std::cout<< " AMIs owned by the owners specified and AMIs with launch permissions as specified"<< std::endl;
std::cout<< " by the executable by options."<< std::endl;
std::cout << cmdline_options() << std::endl;
}
const po::options_description &specific() {
static po::options_description specific("SPECIFIC OPTIONS");
specific.add_options()
("all,a", "Describe all AMIs, public, private or owned, that the user has access to.")
("owner,o", po::value< std::string >(), "OWNER Only AMIs owned by the users specified are described. OWNER may either be a"
"user's account id for images owned by that user, 'self' for images owned by"
"you, or 'amazon' for images owned by Amazon.")
("executable-by,x",po::value< std::string >(), " USER"
"Only AMIs with launch permissions as specified are described. USER may either"
"be a user's account id for AMIs owned by you for which the user has explicit"
"launch permissions, 'self' for AMIs you have explicit launch permissions for,"
"or 'all' for AMIs with public launch permissions.")
;
return specific;
};
void printResponse(const ec2::xml::parse::type::EC2Response_t &response) {
std::cout << response;
};
//po::options_description operator &() { };
};
} //namespace options
} // namespace ec2
#endif /* _options_ec2-describe-images_hpp_ */
| [
"kai.krueger@itwm.fraunhofer.de"
] | kai.krueger@itwm.fraunhofer.de |
b180a41d1113f1b51414325cbc2f061a7f770747 | b9cf964b1f492619478986ed44308721c15b5fbf | /McKillasGorilla/src/mg/gsm/sprite/AnimatedSprite.h | aa8f1b050723a7d05824ce6755fda353ab5e5dd8 | [] | no_license | godsonkraju/Rebelle | 7e5b95f13fefc2e15bcfa45ade644906bf6a6b0a | 6a8215f51c1b197205d46ecbef6a10b6e4532b01 | refs/heads/master | 2021-01-10T10:47:37.301881 | 2016-04-02T20:03:01 | 2016-04-02T20:03:01 | 54,812,341 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,221 | h | /*
Author: Richard McKenna
Stony Brook University
Computer Science Department
AnimatedSprite.h
This class represents a sprite that can can
be used to animate a game character or object.
*/
#pragma once
#include "mg_VS\stdafx.h"
#include "mg\gsm\physics\CollidableObject.h"
#include "mg\gsm\physics\PhysicalProperties.h"
#include "mg\gsm\sprite\AnimatedSpriteType.h"
#include "mg\gui\Viewport.h"
class AnimatedSprite : public CollidableObject
{
protected:
// SPRITE TYPE FOR THIS SPRITE. THE SPRITE TYPE IS THE ID
// OF AN AnimatedSpriteType OBJECT AS STORED IN THE SpriteManager
AnimatedSpriteType *spriteType;
// TRANSPARENCY/OPACITY
int alpha;
// THE "current" STATE DICTATES WHICH ANIMATION SEQUENCE
// IS CURRENTLY IN USE, BUT IT MAP ALSO BE USED TO HELP
// WITH OTHER GAME ACTIVITIES, LIKE PHYSICS
wstring currentState;
// THE INDEX OF THE CURRENT FRAME IN THE ANIMATION SEQUENCE
// NOTE THAT WE WILL COUNT BY 2s FOR THIS SINCE THE VECTOR
// THAT STORES THIS DATA HAS (ID,DURATION) TUPLES
unsigned int frameIndex;
// USED TO ITERATE THROUGH THE CURRENT ANIMATION SEQUENCE
unsigned int animationCounter;
// USED TO RENDER A ROTATED SPRITE, NOT INVOLVED IN PHYSICS
float rotationInRadians;
// HELPS US KEEP TRACK OF WHEN TO REMOVE IT
bool markedForRemoval;
public:
// INLINED ACCESSOR METHODS
int getAlpha() { return alpha; }
wstring getCurrentState() { return currentState; }
unsigned int getFrameIndex() { return frameIndex; }
float getRotationInRadians() { return rotationInRadians; }
AnimatedSpriteType* getSpriteType() { return spriteType; }
bool isMarkedForRemoval() { return markedForRemoval; }
// INLINED MUTATOR METHODS
void setAlpha(int initAlpha)
{ alpha = initAlpha; }
void setRotationInRadians(float initRotation)
{ rotationInRadians = initRotation; }
void setSpriteType(AnimatedSpriteType *initSpriteType)
{ spriteType = initSpriteType; }
void markForRemoval()
{
markedForRemoval = true;
}
// METHODS DEFINED IN AnimatedSprite.cpp
AnimatedSprite();
virtual ~AnimatedSprite();
void changeFrame();
unsigned int getCurrentImageID();
void setCurrentState(wstring newState);
void updateSprite();
}; | [
"bongsung@stonybrook.edu"
] | bongsung@stonybrook.edu |
307da52f2070d9c93ee01083f0b2351ba51c2740 | 2d5599e958db10054be54a1ab0a8d249d05de8fe | /PROS_Code/include/globalFunctions.h | d2bad5095b67b299e0edef8ca66bc8c908a150f1 | [] | no_license | adityanarayanan03/RootProfile | d5a3f0d25169fe377c1fe5e0ada1a56901b44e17 | 6178389fc51fc2de3abd802f250db64600d2c362 | refs/heads/master | 2022-11-02T12:02:00.821305 | 2020-06-17T05:55:23 | 2020-06-17T05:55:23 | 268,678,800 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 564 | h | #include "main.h"
void plotterPrint(std::vector<double> elements){
/*
Takes vector of elements to print to plotter
{x_data, y1, y2, etc.}
*/
printf("%s", "{");
for (unsigned i=0; i<elements.size(); i++){
printf("%f", elements.at(i));
if (i != elements.size() -1){
printf("%s", ",");
}
}
printf("%s \n", "}");
}
void arcade(MotorGroup left, MotorGroup right, double joyVert, double joyHoriz){
left.moveVoltage(12000*(joyVert + joyHoriz));
right.moveVoltage(12000*(joyVert - joyHoriz));
} | [
"aditya.narayanan03@gmail.com"
] | aditya.narayanan03@gmail.com |
68a7ca10cc1e7e4c03dc5ad516c06c6eb6a52d1f | a7080f3541001fa61e8b08045b088d87b081a437 | /compilers/Ronald Mak/c++/prog03-2/tokeniz2.cpp | 7348252f0ec700feeae761110cfc40c8e52d7eb4 | [] | no_license | kaiyasa/codingbook | 91d427c42bd5c0f07da06b403b70efecb5c7ffbd | 78713cb0084be84bebac7f385a8bc3fbf7427ab8 | refs/heads/master | 2021-01-14T08:22:30.788620 | 2017-06-19T02:56:56 | 2017-06-19T02:56:56 | 53,602,207 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,847 | cpp | //fig 3-23
// *************************************************************
// * *
// * Program 3-2: Pascal Tokenizer *
// * *
// * List the source file. After each line, list the Pascal *
// * tokens that were extracted from that line. *
// * *
// * FILE: prog3-2/tokeniz2.cpp *
// * *
// * USAGE: tokeniz2 <source file> *
// * *
// * <source file> name of source file to *
// * tokenize *
// * *
// * Copyright (c) 1996 by Ronald Mak *
// * For instructional purposes only. No warranties. *
// * *
// *************************************************************
#include <iostream>
#include "error.h"
#include "buffer.h"
#include "parser.h"
using namespace std;
//--------------------------------------------------------------
// main
//--------------------------------------------------------------
int main(int argc, char *argv[])
{
//--Check the command line arguments.
if (argc != 2) {
cerr << "Usage: tokeniz2 <source file>" << endl;
AbortTranslation(abortInvalidCommandLineArgs);
}
//--Create the parser for the source file,
//--and then parse the file.
TParser parser(new TSourceBuffer(argv[1]));
parser.Parse();
}
//endfig
| [
"dan.miner@dish.com"
] | dan.miner@dish.com |
36a044f61f0bd7dbd60d3e575e0381dd2aa7abaf | c2e6ed870f2349ef1baf69881203a39b66c66fe5 | /Directx9/Tank/DeviceManager.cpp | 874a03055efa8b0794f81ebd07893b91adfde987 | [] | no_license | SeungHoons/Direct_x9 | deae9858b72bca380129ab896a24375aa784ebb8 | 04e9bde4dcfb04e6fd74385fe96e23bc6cf0d740 | refs/heads/master | 2020-08-17T20:17:35.531427 | 2019-10-30T08:52:29 | 2019-10-30T08:52:29 | 215,707,478 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,984 | cpp | #include "stdafx.h"
#include "DeviceManager.h"
DeviceManager::DeviceManager()
{
}
DeviceManager::~DeviceManager()
{
}
HRESULT DeviceManager::Init()
{
m_pD3D = Direct3DCreate9(D3D_SDK_VERSION);
if (m_pD3D == NULL) return E_FAIL;
D3DCAPS9 caps;
int vp;
//주 그래픽카드의 정보를 D3DCAPS9 에 받아온다.
if (FAILED(m_pD3D->GetDeviceCaps(D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL, &caps)))
return E_FAIL;
//하드웨어가 정점처리를 지원하는지 확인
if (caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
vp = D3DCREATE_HARDWARE_VERTEXPROCESSING;
else
vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory(&d3dpp, sizeof(D3DPRESENT_PARAMETERS));
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.Windowed = true;
d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
d3dpp.EnableAutoDepthStencil = TRUE; //Z(깊이)버퍼를 사용하겠다 설정
d3dpp.AutoDepthStencilFormat = D3DFMT_D16; //유효한 깊이 버퍼 포맷을 설정하는것 / 대입한 D3DFMT_D16은 16비트의 깊이 버퍼를 사용할수 있는 경우에 지정합니다.
//d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; //최대 초당 프레임이 해당 모니터 주사율과 동일하게 나오도록 디폴트 되어있는데 그것을 풀어주는 역할
d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT; //다이렉트가 적절한 값을 찾아 렌더링 간격을 조정한다.
/*if (FAILED(m_pD3D->CreateDevice(
D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL,
g_hWnd, vp, &d3dpp, &m_pD3DDevice)))
{
return E_FAIL;
}*/
if (FAILED(m_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, g_hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &m_pD3DDevice)))
return E_FAIL;
m_pD3DDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
m_pD3DDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
return S_OK;
}
LPDIRECT3DDEVICE9 DeviceManager::GetDevice()
{
return m_pD3DDevice;
}
void DeviceManager::Destroy()
{
}
| [
"Administrator@DESKTOP-UPBBAIM"
] | Administrator@DESKTOP-UPBBAIM |
6add7132c22cbad1eb146c9f79984af767781e5f | aa94350007127db6c1e0b2e4656759033dcb0885 | /r01/include/TimeModule.hpp | 2041ed6b5f9805ed7a780e63bdb249a69c107373 | [] | no_license | zer0nim/piscine_cpp | 795ebf1c8bfadd666bb3475181c5dc59b613a74b | b1be94bc42f9631c9da905693241280c30dc77d7 | refs/heads/master | 2020-06-01T01:04:41.709934 | 2020-02-10T12:36:04 | 2020-02-10T12:36:04 | 190,570,128 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 430 | hpp |
#ifndef TIMEMODULE_HPP
# define TIMEMODULE_HPP
# include "AModule.hpp"
class TimeModule : public AModule {
public:
TimeModule();
~TimeModule();
virtual void updateInfo(void);
virtual void displayTerminal(int *y);
virtual void displayGUI(GraphicalDisplay *graphDisp);
private:
TimeModule(TimeModule const &src);
TimeModule &operator=(TimeModule const &rhs);
std::string _date;
std::string _hour;
};
#endif
| [
"emarin@student.42.fr"
] | emarin@student.42.fr |
cb512796809f663fd1ea8fdc2df48dbb3fc47ebf | 4c4ac45dadd143c2de854a6b6087250a249f2706 | /src/cores/picodrive/3ds/3dsimpl_gpu.cpp | ec29cdb1e250d5fcae7417c0c0cfd1fc2f19e5bc | [] | no_license | TBirdSoars/VirtuaNES | 5cf9e5a88115e9d5dccfb7844ed26b00cfe50958 | cc4e5fa9e003f75d8b000bb22adb37961f33bf3e | refs/heads/master | 2023-05-29T13:33:35.601498 | 2023-05-03T03:30:47 | 2023-05-03T03:30:47 | 208,385,383 | 20 | 2 | null | 2020-05-08T00:52:14 | 2019-09-14T03:51:29 | C++ | UTF-8 | C++ | false | false | 2,642 | cpp |
#include <3ds.h>
#include "3dsgpu.h"
#include "3dsimpl.h"
#include "3dsimpl_gpu.h"
SGPU3DSExtended GPU3DSExt;
void gpu3dsDrawRectangle(int x0, int y0, int x1, int y1, int depth, u32 color)
{
gpu3dsAddRectangleVertexes (x0, y0, x1, y1, depth, color);
gpu3dsDrawVertexList(&GPU3DSExt.rectangleVertexes, GPU_TRIANGLES, false, -1, -1);
}
void gpu3dsAddRectangleVertexes(int x0, int y0, int x1, int y1, int depth, u32 color)
{
/*
if (emulator.isReal3DS)
{
SVertexColor *vertices = &((SVertexColor *) GPU3DSExt.rectangleVertexes.List)[GPU3DSExt.rectangleVertexes.Count];
vertices[0].Position = (SVector4i){x0, y0, depth, 1};
vertices[1].Position = (SVector4i){x1, y1, depth, 1};
u32 swappedColor = ((color & 0xff) << 24) | ((color & 0xff00) << 8) | ((color & 0xff0000) >> 8) | ((color & 0xff000000) >> 24);
vertices[0].Color = swappedColor;
vertices[1].Color = swappedColor;
GPU3DSExt.rectangleVertexes.Count += 2;
}
else*/
{
SVertexColor *vertices = &((SVertexColor *) GPU3DSExt.rectangleVertexes.List)[GPU3DSExt.rectangleVertexes.Count];
vertices[0].Position = (SVector4i){x0, y0, depth, 1};
vertices[1].Position = (SVector4i){x1, y0, depth, 1};
vertices[2].Position = (SVector4i){x0, y1, depth, 1};
vertices[3].Position = (SVector4i){x1, y1, depth, 1};
vertices[4].Position = (SVector4i){x1, y0, depth, 1};
vertices[5].Position = (SVector4i){x0, y1, depth, 1};
u32 swappedColor = ((color & 0xff) << 24) | ((color & 0xff00) << 8) | ((color & 0xff0000) >> 8) | ((color & 0xff000000) >> 24);
vertices[0].Color = swappedColor;
vertices[1].Color = swappedColor;
vertices[2].Color = swappedColor;
vertices[3].Color = swappedColor;
vertices[4].Color = swappedColor;
vertices[5].Color = swappedColor;
GPU3DSExt.rectangleVertexes.Count += 6;
}
}
void gpu3dsDrawVertexes(bool repeatLastDraw, int storeIndex)
{
gpu3dsDrawVertexList(&GPU3DSExt.quadVertexes, GPU_TRIANGLES, repeatLastDraw, 0, storeIndex);
gpu3dsDrawVertexList(&GPU3DSExt.tileVertexes, GPU_GEOMETRY_PRIM, repeatLastDraw, 1, storeIndex);
gpu3dsDrawVertexList(&GPU3DSExt.rectangleVertexes, GPU_TRIANGLES, repeatLastDraw, 2, storeIndex);
}
void gpu3dsBindTextureMainScreen(SGPUTexture *texture, GPU_TEXUNIT unit)
{
gpu3dsBindTextureWithParams(texture, unit,
GPU_TEXTURE_MAG_FILTER(GPU_LINEAR)
| GPU_TEXTURE_MIN_FILTER(GPU_LINEAR)
| GPU_TEXTURE_WRAP_S(GPU_CLAMP_TO_BORDER)
| GPU_TEXTURE_WRAP_T(GPU_CLAMP_TO_BORDER));
}
| [
"bubble2k16@gmail.com"
] | bubble2k16@gmail.com |
228d5c4681accf97590511382fb7b0e8b842ceca | 695255c177d9f522b6d9a9f414f79785f4935e4a | /Bloc2/Sessio2/ex1-3/MyGLWidget.h | ae4f17376d0a2cc9b1408510aef9a5d4456ff78a | [] | no_license | julsgasull/FIB-IDI | c75b70b220f209585352a5173ad5d4a9a29806bb | 39a8b9243de9ae20eb24306758ec38e3fdcd1caa | refs/heads/master | 2020-04-17T09:26:47.386433 | 2019-01-18T18:57:23 | 2019-01-18T18:57:23 | 166,457,947 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,363 | h | #define GLM_FORCE_RADIANS
#include <QOpenGLFunctions_3_3_Core>
#include <QOpenGLWidget>
#include <QOpenGLShader>
#include <QOpenGLShaderProgram>
#include <QKeyEvent>
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "./Model/model.h"
class MyGLWidget : public QOpenGLWidget, protected QOpenGLFunctions_3_3_Core
{
Q_OBJECT
public:
MyGLWidget (QWidget *parent=0);
~MyGLWidget ();
protected:
// initializeGL - Aqui incluim les inicialitzacions del contexte grafic.
virtual void initializeGL ( );
// paintGL - Mètode cridat cada cop que cal refrescar la finestra.
// Tot el que es dibuixa es dibuixa aqui.
virtual void paintGL ( );
// resizeGL - És cridat quan canvia la mida del widget
virtual void resizeGL (int width, int height);
// keyPressEvent - Es cridat quan es prem una tecla
virtual void keyPressEvent (QKeyEvent *event);
private:
/* -----------------------------------------*/
/* --------------- Functions ---------------*/
/* -----------------------------------------*/
// initializeGL
void carregaShaders ();
void createBuffers ();
void carregaHomer ();
void carregaTerra ();
void ini_camera ();
void viewTransform ();
void projectTransform ();
// paintGL
void modelTransformHomer ();
void modelTransformTerra ();
/* -----------------------------------------*/
/* -------------- Locations ---------------*/
/* -----------------------------------------*/
// attribute locations
GLuint vertexLoc, colorLoc;
// uniform locations
GLuint transLoc, projLoc, viewLoc;
/* -----------------------------------------*/
/* --------------- VAO, VBO ----------------*/
/* -----------------------------------------*/
// Homer
GLuint VAO_Homer, VBO_HomerPos, VBO_HomerCol;
// Terra
GLuint VAO_Terra, VBO_TerraPos, VBO_TerraCol;
// Program
QOpenGLShaderProgram *program;
/* -----------------------------------------*/
/* ------------- Internal vars -------------*/
/* -----------------------------------------*/
Model homer;
float scale;
glm::vec3 pos;
GLfloat angle = 0.0;
/* -----------------------------------------*/
/* -------------- Added vars --------------*/
/* -----------------------------------------*/
glm::vec3 Pmin, Pmax;
GLfloat r, d;
glm::vec3 VRP, OBS, UP;
GLfloat FOV, ra, znear, zfar;
};
| [
"juliagasull@icloud.com"
] | juliagasull@icloud.com |
048d1bf6fc1c8a36e570a5e88eacbf2b8af87fcb | 12cc723c31f4842f1f7e68e7c84c537bf2f5fce0 | /trunk/AGDP/UI/DXUT/SDKmesh.cpp | a33b3af03d017e4dd70dce81181ba4189063db8e | [] | no_license | damody/action-game-design-plaform | 98b01b956000a4623b595b5e6ef25687a0feafa7 | bb46fcb58f0d9076373e7eca80d2ad08bb26cb79 | refs/heads/master | 2021-01-01T04:45:17.630002 | 2015-01-26T12:35:04 | 2015-01-26T12:35:04 | 56,483,228 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 75,141 | cpp | //--------------------------------------------------------------------------------------
// File: SDKMesh.cpp
//
// The SDK Mesh format (.sdkmesh) is not a recommended file format for games.
// It was designed to meet the specific needs of the SDK samples. Any real-world
// applications should avoid this file format in favor of a destination format that
// meets the specific needs of the application.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "StdGame.h"
#include "DXUT.h"
#include "SDKMesh.h"
#include "SDKMisc.h"
//--------------------------------------------------------------------------------------
void CDXUTSDKMesh::LoadMaterials( ID3D11Device* pd3dDevice, SDKMESH_MATERIAL* pMaterials, UINT numMaterials,
SDKMESH_CALLBACKS11* pLoaderCallbacks )
{
char strPath[MAX_PATH];
if ( pLoaderCallbacks && pLoaderCallbacks->pCreateTextureFromFile )
{
for ( UINT m = 0; m < numMaterials; m++ )
{
pMaterials[m].pDiffuseTexture11 = NULL;
pMaterials[m].pNormalTexture11 = NULL;
pMaterials[m].pSpecularTexture11 = NULL;
pMaterials[m].pDiffuseRV11 = NULL;
pMaterials[m].pNormalRV11 = NULL;
pMaterials[m].pSpecularRV11 = NULL;
// load textures
if ( pMaterials[m].DiffuseTexture[0] != 0 )
{
pLoaderCallbacks->pCreateTextureFromFile( pd3dDevice,
pMaterials[m].DiffuseTexture, &pMaterials[m].pDiffuseRV11,
pLoaderCallbacks->pContext );
}
if ( pMaterials[m].NormalTexture[0] != 0 )
{
pLoaderCallbacks->pCreateTextureFromFile( pd3dDevice,
pMaterials[m].NormalTexture, &pMaterials[m].pNormalRV11,
pLoaderCallbacks->pContext );
}
if ( pMaterials[m].SpecularTexture[0] != 0 )
{
pLoaderCallbacks->pCreateTextureFromFile( pd3dDevice,
pMaterials[m].SpecularTexture, &pMaterials[m].pSpecularRV11,
pLoaderCallbacks->pContext );
}
}
}
else
{
for ( UINT m = 0; m < numMaterials; m++ )
{
pMaterials[m].pDiffuseTexture11 = NULL;
pMaterials[m].pNormalTexture11 = NULL;
pMaterials[m].pSpecularTexture11 = NULL;
pMaterials[m].pDiffuseRV11 = NULL;
pMaterials[m].pNormalRV11 = NULL;
pMaterials[m].pSpecularRV11 = NULL;
// load textures
if ( pMaterials[m].DiffuseTexture[0] != 0 )
{
sprintf_s( strPath, MAX_PATH, "%s%s", m_strPath, pMaterials[m].DiffuseTexture );
if ( FAILED( DXUTGetGlobalResourceCache().CreateTextureFromFile( pd3dDevice, DXUTGetD3D11DeviceContext(),
strPath, &pMaterials[m].pDiffuseRV11,
true ) ) )
{
pMaterials[m].pDiffuseRV11 = ( ID3D11ShaderResourceView* )ERROR_RESOURCE_VALUE;
}
}
if ( pMaterials[m].NormalTexture[0] != 0 )
{
sprintf_s( strPath, MAX_PATH, "%s%s", m_strPath, pMaterials[m].NormalTexture );
if ( FAILED( DXUTGetGlobalResourceCache().CreateTextureFromFile( pd3dDevice, DXUTGetD3D11DeviceContext(),
strPath,
&pMaterials[m].pNormalRV11 ) ) )
{
pMaterials[m].pNormalRV11 = ( ID3D11ShaderResourceView* )ERROR_RESOURCE_VALUE;
}
}
if ( pMaterials[m].SpecularTexture[0] != 0 )
{
sprintf_s( strPath, MAX_PATH, "%s%s", m_strPath, pMaterials[m].SpecularTexture );
if ( FAILED( DXUTGetGlobalResourceCache().CreateTextureFromFile( pd3dDevice, DXUTGetD3D11DeviceContext(),
strPath,
&pMaterials[m].pSpecularRV11 ) ) )
{
pMaterials[m].pSpecularRV11 = ( ID3D11ShaderResourceView* )ERROR_RESOURCE_VALUE;
}
}
}
}
}
//--------------------------------------------------------------------------------------
void CDXUTSDKMesh::LoadMaterials( IDirect3DDevice9* pd3dDevice, SDKMESH_MATERIAL* pMaterials, UINT numMaterials,
SDKMESH_CALLBACKS9* pLoaderCallbacks )
{
char strPath[MAX_PATH];
if ( pLoaderCallbacks && pLoaderCallbacks->pCreateTextureFromFile )
{
for ( UINT m = 0; m < numMaterials; m++ )
{
pMaterials[m].pDiffuseTexture9 = NULL;
pMaterials[m].pNormalTexture9 = NULL;
pMaterials[m].pSpecularTexture9 = NULL;
// load textures
if ( pMaterials[m].DiffuseTexture[0] != 0 )
{
pLoaderCallbacks->pCreateTextureFromFile( pd3dDevice,
pMaterials[m].DiffuseTexture,
&pMaterials[m].pDiffuseTexture9,
pLoaderCallbacks->pContext );
}
if ( pMaterials[m].NormalTexture[0] != 0 )
{
pLoaderCallbacks->pCreateTextureFromFile( pd3dDevice,
pMaterials[m].NormalTexture, &pMaterials[m].pNormalTexture9,
pLoaderCallbacks->pContext );
}
if ( pMaterials[m].SpecularTexture[0] != 0 )
{
pLoaderCallbacks->pCreateTextureFromFile( pd3dDevice,
pMaterials[m].SpecularTexture,
&pMaterials[m].pSpecularTexture9,
pLoaderCallbacks->pContext );
}
}
}
else
{
for ( UINT m = 0; m < numMaterials; m++ )
{
pMaterials[m].pDiffuseTexture9 = NULL;
pMaterials[m].pNormalTexture9 = NULL;
pMaterials[m].pSpecularTexture9 = NULL;
pMaterials[m].pDiffuseRV11 = NULL;
pMaterials[m].pNormalRV11 = NULL;
pMaterials[m].pSpecularRV11 = NULL;
// load textures
if ( pMaterials[m].DiffuseTexture[0] != 0 )
{
sprintf_s( strPath, MAX_PATH, "%s%s", m_strPath, pMaterials[m].DiffuseTexture );
if ( FAILED( DXUTGetGlobalResourceCache().CreateTextureFromFile( pd3dDevice,
strPath,
&pMaterials[m].pDiffuseTexture9 ) ) )
{
pMaterials[m].pDiffuseTexture9 = ( IDirect3DTexture9* )ERROR_RESOURCE_VALUE;
}
}
if ( pMaterials[m].NormalTexture[0] != 0 )
{
sprintf_s( strPath, MAX_PATH, "%s%s", m_strPath, pMaterials[m].NormalTexture );
if ( FAILED( DXUTGetGlobalResourceCache().CreateTextureFromFile( pd3dDevice,
strPath,
&pMaterials[m].pNormalTexture9 ) ) )
{
pMaterials[m].pNormalTexture9 = ( IDirect3DTexture9* )ERROR_RESOURCE_VALUE;
}
}
if ( pMaterials[m].SpecularTexture[0] != 0 )
{
sprintf_s( strPath, MAX_PATH, "%s%s", m_strPath, pMaterials[m].SpecularTexture );
if ( FAILED( DXUTGetGlobalResourceCache().CreateTextureFromFile( pd3dDevice,
strPath,
&pMaterials[m].pSpecularTexture9 ) ) )
{
pMaterials[m].pSpecularTexture9 = ( IDirect3DTexture9* )ERROR_RESOURCE_VALUE;
}
}
}
}
}
//--------------------------------------------------------------------------------------
HRESULT CDXUTSDKMesh::CreateVertexBuffer( ID3D11Device* pd3dDevice, SDKMESH_VERTEX_BUFFER_HEADER* pHeader,
void* pVertices, SDKMESH_CALLBACKS11* pLoaderCallbacks )
{
HRESULT hr = S_OK;
pHeader->DataOffset = 0;
//Vertex Buffer
D3D11_BUFFER_DESC bufferDesc;
bufferDesc.ByteWidth = ( UINT )( pHeader->SizeBytes );
bufferDesc.Usage = D3D11_USAGE_DEFAULT;
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufferDesc.CPUAccessFlags = 0;
bufferDesc.MiscFlags = 0;
if ( pLoaderCallbacks && pLoaderCallbacks->pCreateVertexBuffer )
{
pLoaderCallbacks->pCreateVertexBuffer( pd3dDevice, &pHeader->pVB11, bufferDesc, pVertices,
pLoaderCallbacks->pContext );
}
else
{
D3D11_SUBRESOURCE_DATA InitData;
InitData.pSysMem = pVertices;
hr = pd3dDevice->CreateBuffer( &bufferDesc, &InitData, &pHeader->pVB11 );
DXUT_SetDebugName( pHeader->pVB11, "CDXUTSDKMesh" );
}
return hr;
}
//--------------------------------------------------------------------------------------
HRESULT CDXUTSDKMesh::CreateIndexBuffer( ID3D11Device* pd3dDevice, SDKMESH_INDEX_BUFFER_HEADER* pHeader,
void* pIndices, SDKMESH_CALLBACKS11* pLoaderCallbacks )
{
HRESULT hr = S_OK;
pHeader->DataOffset = 0;
//Index Buffer
D3D11_BUFFER_DESC bufferDesc;
bufferDesc.ByteWidth = ( UINT )( pHeader->SizeBytes );
bufferDesc.Usage = D3D11_USAGE_DEFAULT;
bufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
bufferDesc.CPUAccessFlags = 0;
bufferDesc.MiscFlags = 0;
if ( pLoaderCallbacks && pLoaderCallbacks->pCreateIndexBuffer )
{
pLoaderCallbacks->pCreateIndexBuffer( pd3dDevice, &pHeader->pIB11, bufferDesc, pIndices,
pLoaderCallbacks->pContext );
}
else
{
D3D11_SUBRESOURCE_DATA InitData;
InitData.pSysMem = pIndices;
hr = pd3dDevice->CreateBuffer( &bufferDesc, &InitData, &pHeader->pIB11 );
DXUT_SetDebugName( pHeader->pIB11, "CDXUTSDKMesh" );
}
return hr;
}
//--------------------------------------------------------------------------------------
HRESULT CDXUTSDKMesh::CreateVertexBuffer( IDirect3DDevice9* pd3dDevice, SDKMESH_VERTEX_BUFFER_HEADER* pHeader,
void* pVertices, SDKMESH_CALLBACKS9* pLoaderCallbacks )
{
HRESULT hr = S_OK;
pHeader->DataOffset = 0;
if ( pLoaderCallbacks && pLoaderCallbacks->pCreateVertexBuffer )
{
pLoaderCallbacks->pCreateVertexBuffer( pd3dDevice, &pHeader->pVB9, ( UINT )pHeader->SizeBytes,
D3DUSAGE_WRITEONLY, 0, D3DPOOL_DEFAULT, pVertices,
pLoaderCallbacks->pContext );
}
else
{
hr = pd3dDevice->CreateVertexBuffer( ( UINT )pHeader->SizeBytes,
D3DUSAGE_WRITEONLY,
0,
D3DPOOL_DEFAULT,
&pHeader->pVB9,
NULL );
//lock
if ( SUCCEEDED( hr ) )
{
void* pLockedVerts = NULL;
V_RETURN( pHeader->pVB9->Lock( 0, 0, &pLockedVerts, 0 ) );
CopyMemory( pLockedVerts, pVertices, ( size_t )pHeader->SizeBytes );
pHeader->pVB9->Unlock();
}
}
return hr;
}
//--------------------------------------------------------------------------------------
HRESULT CDXUTSDKMesh::CreateIndexBuffer( IDirect3DDevice9* pd3dDevice, SDKMESH_INDEX_BUFFER_HEADER* pHeader,
void* pIndices, SDKMESH_CALLBACKS9* pLoaderCallbacks )
{
HRESULT hr = S_OK;
pHeader->DataOffset = 0;
D3DFORMAT ibFormat = D3DFMT_INDEX16;
switch ( pHeader->IndexType )
{
case IT_16BIT:
ibFormat = D3DFMT_INDEX16;
break;
case IT_32BIT:
ibFormat = D3DFMT_INDEX32;
break;
};
if ( pLoaderCallbacks && pLoaderCallbacks->pCreateIndexBuffer )
{
pLoaderCallbacks->pCreateIndexBuffer( pd3dDevice, &pHeader->pIB9, ( UINT )pHeader->SizeBytes,
D3DUSAGE_WRITEONLY, ibFormat, D3DPOOL_DEFAULT, pIndices,
pLoaderCallbacks->pContext );
}
else
{
hr = pd3dDevice->CreateIndexBuffer( ( UINT )( pHeader->SizeBytes ),
D3DUSAGE_WRITEONLY,
ibFormat,
D3DPOOL_DEFAULT,
&pHeader->pIB9,
NULL );
if ( SUCCEEDED( hr ) )
{
void* pLockedIndices = NULL;
V_RETURN( pHeader->pIB9->Lock( 0, 0, &pLockedIndices, 0 ) );
CopyMemory( pLockedIndices, pIndices, ( size_t )( pHeader->SizeBytes ) );
pHeader->pIB9->Unlock();
}
}
return hr;
}
//--------------------------------------------------------------------------------------
HRESULT CDXUTSDKMesh::CreateFromFile( ID3D11Device* pDev11,
IDirect3DDevice9* pDev9,
LPCTSTR szFileName,
bool bCreateAdjacencyIndices,
SDKMESH_CALLBACKS11* pLoaderCallbacks11,
SDKMESH_CALLBACKS9* pLoaderCallbacks9 )
{
HRESULT hr = S_OK;
// Find the path for the file
V_RETURN( DXUTFindDXSDKMediaFileCch( m_strPathW, sizeof( m_strPathW ) / sizeof( WCHAR ), szFileName ) );
// Open the file
m_hFile = CreateFile( m_strPathW, FILE_READ_DATA, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN,
NULL );
if ( INVALID_HANDLE_VALUE == m_hFile )
{
return DXUTERR_MEDIANOTFOUND;
}
// Change the path to just the directory
WCHAR* pLastBSlash = wcsrchr( m_strPathW, L'\\' );
if ( pLastBSlash )
{
*( pLastBSlash + 1 ) = L'\0';
}
else
{
*m_strPathW = L'\0';
}
WideCharToMultiByte( CP_ACP, 0, m_strPathW, -1, m_strPath, MAX_PATH, NULL, FALSE );
// Get the file size
LARGE_INTEGER FileSize;
GetFileSizeEx( m_hFile, &FileSize );
UINT cBytes = FileSize.LowPart;
// Allocate memory
m_pStaticMeshData = new BYTE[ cBytes ];
if ( !m_pStaticMeshData )
{
CloseHandle( m_hFile );
return E_OUTOFMEMORY;
}
// Read in the file
DWORD dwBytesRead;
if ( !ReadFile( m_hFile, m_pStaticMeshData, cBytes, &dwBytesRead, NULL ) )
{
hr = E_FAIL;
}
CloseHandle( m_hFile );
if ( SUCCEEDED( hr ) )
{
hr = CreateFromMemory( pDev11,
pDev9,
m_pStaticMeshData,
cBytes,
bCreateAdjacencyIndices,
false,
pLoaderCallbacks11,
pLoaderCallbacks9 );
if ( FAILED( hr ) )
{
delete []m_pStaticMeshData;
}
}
return hr;
}
HRESULT CDXUTSDKMesh::CreateFromMemory( ID3D11Device* pDev11,
IDirect3DDevice9* pDev9,
BYTE* pData,
UINT DataBytes,
bool bCreateAdjacencyIndices,
bool bCopyStatic,
SDKMESH_CALLBACKS11* pLoaderCallbacks11,
SDKMESH_CALLBACKS9* pLoaderCallbacks9 )
{
HRESULT hr = E_FAIL;
D3DXVECTOR3 lower;
D3DXVECTOR3 upper;
m_pDev9 = pDev9;
m_pDev11 = pDev11;
// Set outstanding resources to zero
m_NumOutstandingResources = 0;
if ( bCopyStatic )
{
SDKMESH_HEADER* pHeader = ( SDKMESH_HEADER* )pData;
SIZE_T StaticSize = ( SIZE_T )( pHeader->HeaderSize + pHeader->NonBufferDataSize );
m_pHeapData = new BYTE[ StaticSize ];
if ( !m_pHeapData )
{
return hr;
}
m_pStaticMeshData = m_pHeapData;
CopyMemory( m_pStaticMeshData, pData, StaticSize );
}
else
{
m_pHeapData = pData;
m_pStaticMeshData = pData;
}
// Pointer fixup
m_pMeshHeader = ( SDKMESH_HEADER* )m_pStaticMeshData;
m_pVertexBufferArray = ( SDKMESH_VERTEX_BUFFER_HEADER* )( m_pStaticMeshData +
m_pMeshHeader->VertexStreamHeadersOffset );
m_pIndexBufferArray = ( SDKMESH_INDEX_BUFFER_HEADER* )( m_pStaticMeshData +
m_pMeshHeader->IndexStreamHeadersOffset );
m_pMeshArray = ( SDKMESH_MESH* )( m_pStaticMeshData + m_pMeshHeader->MeshDataOffset );
m_pSubsetArray = ( SDKMESH_SUBSET* )( m_pStaticMeshData + m_pMeshHeader->SubsetDataOffset );
m_pFrameArray = ( SDKMESH_FRAME* )( m_pStaticMeshData + m_pMeshHeader->FrameDataOffset );
m_pMaterialArray = ( SDKMESH_MATERIAL* )( m_pStaticMeshData + m_pMeshHeader->MaterialDataOffset );
// Setup subsets
for ( UINT i = 0; i < m_pMeshHeader->NumMeshes; i++ )
{
m_pMeshArray[i].pSubsets = ( UINT* )( m_pStaticMeshData + m_pMeshArray[i].SubsetOffset );
m_pMeshArray[i].pFrameInfluences = ( UINT* )( m_pStaticMeshData + m_pMeshArray[i].FrameInfluenceOffset );
}
// error condition
if ( m_pMeshHeader->Version != SDKMESH_FILE_VERSION )
{
hr = E_NOINTERFACE;
goto Error;
}
// Setup buffer data pointer
BYTE* pBufferData = pData + m_pMeshHeader->HeaderSize + m_pMeshHeader->NonBufferDataSize;
// Get the start of the buffer data
UINT64 BufferDataStart = m_pMeshHeader->HeaderSize + m_pMeshHeader->NonBufferDataSize;
// Create VBs
m_ppVertices = new BYTE*[m_pMeshHeader->NumVertexBuffers];
for ( UINT i = 0; i < m_pMeshHeader->NumVertexBuffers; i++ )
{
BYTE* pVertices = NULL;
pVertices = ( BYTE* )( pBufferData + ( m_pVertexBufferArray[i].DataOffset - BufferDataStart ) );
if ( pDev11 )
{
CreateVertexBuffer( pDev11, &m_pVertexBufferArray[i], pVertices, pLoaderCallbacks11 );
}
else if ( pDev9 )
{
CreateVertexBuffer( pDev9, &m_pVertexBufferArray[i], pVertices, pLoaderCallbacks9 );
}
m_ppVertices[i] = pVertices;
}
// Create IBs
m_ppIndices = new BYTE*[m_pMeshHeader->NumIndexBuffers];
for ( UINT i = 0; i < m_pMeshHeader->NumIndexBuffers; i++ )
{
BYTE* pIndices = NULL;
pIndices = ( BYTE* )( pBufferData + ( m_pIndexBufferArray[i].DataOffset - BufferDataStart ) );
if ( pDev11 )
{
CreateIndexBuffer( pDev11, &m_pIndexBufferArray[i], pIndices, pLoaderCallbacks11 );
}
else if ( pDev9 )
{
CreateIndexBuffer( pDev9, &m_pIndexBufferArray[i], pIndices, pLoaderCallbacks9 );
}
m_ppIndices[i] = pIndices;
}
// Load Materials
if ( pDev11 )
{
LoadMaterials( pDev11, m_pMaterialArray, m_pMeshHeader->NumMaterials, pLoaderCallbacks11 );
}
else if ( pDev9 )
{
LoadMaterials( pDev9, m_pMaterialArray, m_pMeshHeader->NumMaterials, pLoaderCallbacks9 );
}
// Create a place to store our bind pose frame matrices
m_pBindPoseFrameMatrices = new D3DXMATRIX[ m_pMeshHeader->NumFrames ];
if ( !m_pBindPoseFrameMatrices )
{
goto Error;
}
// Create a place to store our transformed frame matrices
m_pTransformedFrameMatrices = new D3DXMATRIX[ m_pMeshHeader->NumFrames ];
if ( !m_pTransformedFrameMatrices )
{
goto Error;
}
m_pWorldPoseFrameMatrices = new D3DXMATRIX[ m_pMeshHeader->NumFrames ];
if ( !m_pWorldPoseFrameMatrices )
{
goto Error;
}
SDKMESH_SUBSET* pSubset = NULL;
D3D11_PRIMITIVE_TOPOLOGY PrimType;
// update bounding volume
SDKMESH_MESH* currentMesh = &m_pMeshArray[0];
int tris = 0;
for ( UINT meshi = 0; meshi < m_pMeshHeader->NumMeshes; ++meshi )
{
lower.x = FLT_MAX; lower.y = FLT_MAX; lower.z = FLT_MAX;
upper.x = -FLT_MAX; upper.y = -FLT_MAX; upper.z = -FLT_MAX;
currentMesh = GetMesh( meshi );
INT indsize;
if ( m_pIndexBufferArray[currentMesh->IndexBuffer].IndexType == IT_16BIT )
{
indsize = 2;
}
else
{
indsize = 4;
}
for ( UINT subset = 0; subset < currentMesh->NumSubsets; subset++ )
{
pSubset = GetSubset( meshi, subset ); //&m_pSubsetArray[ currentMesh->pSubsets[subset] ];
PrimType = GetPrimitiveType11( ( SDKMESH_PRIMITIVE_TYPE )pSubset->PrimitiveType );
assert( PrimType == D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );// only triangle lists are handled.
UINT IndexCount = ( UINT )pSubset->IndexCount;
UINT IndexStart = ( UINT )pSubset->IndexStart;
/*if( bAdjacent )
{
IndexCount *= 2;
IndexStart *= 2;
}*/
//BYTE* pIndices = NULL;
//m_ppIndices[i]
UINT* ind = ( UINT* )m_ppIndices[currentMesh->IndexBuffer];
FLOAT* verts = ( FLOAT* )m_ppVertices[currentMesh->VertexBuffers[0]];
UINT stride = ( UINT )m_pVertexBufferArray[currentMesh->VertexBuffers[0]].StrideBytes;
assert ( stride % 4 == 0 );
stride /= 4;
for ( UINT vertind = IndexStart; vertind < IndexStart + IndexCount; ++vertind )
{
UINT current_ind = 0;
if ( indsize == 2 )
{
UINT ind_div2 = vertind / 2;
current_ind = ind[ind_div2];
if ( vertind % 2 == 0 )
{
current_ind = current_ind << 16;
current_ind = current_ind >> 16;
}
else
{
current_ind = current_ind >> 16;
}
}
else
{
current_ind = ind[vertind];
}
tris++;
D3DXVECTOR3* pt = ( D3DXVECTOR3* ) & ( verts[stride * current_ind] );
if ( pt->x < lower.x )
{
lower.x = pt->x;
}
if ( pt->y < lower.y )
{
lower.y = pt->y;
}
if ( pt->z < lower.z )
{
lower.z = pt->z;
}
if ( pt->x > upper.x )
{
upper.x = pt->x;
}
if ( pt->y > upper.y )
{
upper.y = pt->y;
}
if ( pt->z > upper.z )
{
upper.z = pt->z;
}
//BYTE** m_ppVertices;
//BYTE** m_ppIndices;
}
//pd3dDeviceContext->DrawIndexed( IndexCount, IndexStart, VertexStart );
}
D3DXVECTOR3 half = upper - lower;
half *= 0.5f;
currentMesh->BoundingBoxCenter = lower + half;
currentMesh->BoundingBoxExtents = half;
}
// Update
hr = S_OK;
Error:
if ( !pLoaderCallbacks9 )
{
CheckLoadDone();
}
return hr;
}
//--------------------------------------------------------------------------------------
// transform bind pose frame using a recursive traversal
//--------------------------------------------------------------------------------------
void CDXUTSDKMesh::TransformBindPoseFrame( UINT iFrame, D3DXMATRIX* pParentWorld )
{
if ( !m_pBindPoseFrameMatrices )
{
return;
}
// Transform ourselves
D3DXMATRIX LocalWorld;
D3DXMatrixMultiply( &LocalWorld, &m_pFrameArray[iFrame].Matrix, pParentWorld );
m_pBindPoseFrameMatrices[iFrame] = LocalWorld;
// Transform our siblings
if ( m_pFrameArray[iFrame].SiblingFrame != INVALID_FRAME )
{
TransformBindPoseFrame( m_pFrameArray[iFrame].SiblingFrame, pParentWorld );
}
// Transform our children
if ( m_pFrameArray[iFrame].ChildFrame != INVALID_FRAME )
{
TransformBindPoseFrame( m_pFrameArray[iFrame].ChildFrame, &LocalWorld );
}
}
//--------------------------------------------------------------------------------------
// transform frame using a recursive traversal
//--------------------------------------------------------------------------------------
void CDXUTSDKMesh::TransformFrame( UINT iFrame, D3DXMATRIX* pParentWorld, double fTime )
{
// Get the tick data
D3DXMATRIX LocalTransform;
UINT iTick = GetAnimationKeyFromTime( fTime );
if ( INVALID_ANIMATION_DATA != m_pFrameArray[iFrame].AnimationDataIndex )
{
SDKANIMATION_FRAME_DATA* pFrameData = &m_pAnimationFrameData[ m_pFrameArray[iFrame].AnimationDataIndex ];
SDKANIMATION_DATA* pData = &pFrameData->pAnimationData[ iTick ];
// turn it into a matrix (Ignore scaling for now)
D3DXVECTOR3 parentPos = pData->Translation;
D3DXMATRIX mTranslate;
D3DXMatrixTranslation( &mTranslate, parentPos.x, parentPos.y, parentPos.z );
D3DXQUATERNION quat;
D3DXMATRIX mQuat;
quat.w = pData->Orientation.w;
quat.x = pData->Orientation.x;
quat.y = pData->Orientation.y;
quat.z = pData->Orientation.z;
if ( quat.w == 0 && quat.x == 0 && quat.y == 0 && quat.z == 0 )
{
D3DXQuaternionIdentity( &quat );
}
D3DXQuaternionNormalize( &quat, &quat );
D3DXMatrixRotationQuaternion( &mQuat, &quat );
LocalTransform = ( mQuat * mTranslate );
}
else
{
LocalTransform = m_pFrameArray[iFrame].Matrix;
}
// Transform ourselves
D3DXMATRIX LocalWorld;
D3DXMatrixMultiply( &LocalWorld, &LocalTransform, pParentWorld );
m_pTransformedFrameMatrices[iFrame] = LocalWorld;
m_pWorldPoseFrameMatrices[iFrame] = LocalWorld;
// Transform our siblings
if ( m_pFrameArray[iFrame].SiblingFrame != INVALID_FRAME )
{
TransformFrame( m_pFrameArray[iFrame].SiblingFrame, pParentWorld, fTime );
}
// Transform our children
if ( m_pFrameArray[iFrame].ChildFrame != INVALID_FRAME )
{
TransformFrame( m_pFrameArray[iFrame].ChildFrame, &LocalWorld, fTime );
}
}
//--------------------------------------------------------------------------------------
// transform frame assuming that it is an absolute transformation
//--------------------------------------------------------------------------------------
void CDXUTSDKMesh::TransformFrameAbsolute( UINT iFrame, double fTime )
{
D3DXMATRIX mTrans1;
D3DXMATRIX mTrans2;
D3DXMATRIX mRot1;
D3DXMATRIX mRot2;
D3DXQUATERNION quat1;
D3DXQUATERNION quat2;
D3DXMATRIX mTo;
D3DXMATRIX mInvTo;
D3DXMATRIX mFrom;
UINT iTick = GetAnimationKeyFromTime( fTime );
if ( INVALID_ANIMATION_DATA != m_pFrameArray[iFrame].AnimationDataIndex )
{
SDKANIMATION_FRAME_DATA* pFrameData = &m_pAnimationFrameData[ m_pFrameArray[iFrame].AnimationDataIndex ];
SDKANIMATION_DATA* pData = &pFrameData->pAnimationData[ iTick ];
SDKANIMATION_DATA* pDataOrig = &pFrameData->pAnimationData[ 0 ];
D3DXMatrixTranslation( &mTrans1, -pDataOrig->Translation.x,
-pDataOrig->Translation.y,
-pDataOrig->Translation.z );
D3DXMatrixTranslation( &mTrans2, pData->Translation.x,
pData->Translation.y,
pData->Translation.z );
quat1.x = pDataOrig->Orientation.x;
quat1.y = pDataOrig->Orientation.y;
quat1.z = pDataOrig->Orientation.z;
quat1.w = pDataOrig->Orientation.w;
D3DXQuaternionInverse( &quat1, &quat1 );
D3DXMatrixRotationQuaternion( &mRot1, &quat1 );
mInvTo = mTrans1 * mRot1;
quat2.x = pData->Orientation.x;
quat2.y = pData->Orientation.y;
quat2.z = pData->Orientation.z;
quat2.w = pData->Orientation.w;
D3DXMatrixRotationQuaternion( &mRot2, &quat2 );
mFrom = mRot2 * mTrans2;
D3DXMATRIX mOutput = mInvTo * mFrom;
m_pTransformedFrameMatrices[iFrame] = mOutput;
}
}
#define MAX_D3D11_VERTEX_STREAMS D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT
//--------------------------------------------------------------------------------------
void CDXUTSDKMesh::RenderMesh( UINT iMesh,
bool bAdjacent,
ID3D11DeviceContext* pd3dDeviceContext,
UINT iDiffuseSlot,
UINT iNormalSlot,
UINT iSpecularSlot )
{
if ( 0 < GetOutstandingBufferResources() )
{
return;
}
SDKMESH_MESH* pMesh = &m_pMeshArray[iMesh];
UINT Strides[MAX_D3D11_VERTEX_STREAMS];
UINT Offsets[MAX_D3D11_VERTEX_STREAMS];
ID3D11Buffer* pVB[MAX_D3D11_VERTEX_STREAMS];
if ( pMesh->NumVertexBuffers > MAX_D3D11_VERTEX_STREAMS )
{
return;
}
for ( UINT64 i = 0; i < pMesh->NumVertexBuffers; i++ )
{
pVB[i] = m_pVertexBufferArray[ pMesh->VertexBuffers[i] ].pVB11;
Strides[i] = ( UINT )m_pVertexBufferArray[ pMesh->VertexBuffers[i] ].StrideBytes;
Offsets[i] = 0;
}
SDKMESH_INDEX_BUFFER_HEADER* pIndexBufferArray;
if ( bAdjacent )
{
pIndexBufferArray = m_pAdjacencyIndexBufferArray;
}
else
{
pIndexBufferArray = m_pIndexBufferArray;
}
ID3D11Buffer* pIB = pIndexBufferArray[ pMesh->IndexBuffer ].pIB11;
DXGI_FORMAT ibFormat = DXGI_FORMAT_R16_UINT;
switch ( pIndexBufferArray[ pMesh->IndexBuffer ].IndexType )
{
case IT_16BIT:
ibFormat = DXGI_FORMAT_R16_UINT;
break;
case IT_32BIT:
ibFormat = DXGI_FORMAT_R32_UINT;
break;
};
pd3dDeviceContext->IASetVertexBuffers( 0, pMesh->NumVertexBuffers, pVB, Strides, Offsets );
pd3dDeviceContext->IASetIndexBuffer( pIB, ibFormat, 0 );
SDKMESH_SUBSET* pSubset = NULL;
SDKMESH_MATERIAL* pMat = NULL;
D3D11_PRIMITIVE_TOPOLOGY PrimType;
for ( UINT subset = 0; subset < pMesh->NumSubsets; subset++ )
{
pSubset = &m_pSubsetArray[ pMesh->pSubsets[subset] ];
PrimType = GetPrimitiveType11( ( SDKMESH_PRIMITIVE_TYPE )pSubset->PrimitiveType );
if ( bAdjacent )
{
switch ( PrimType )
{
case D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST:
PrimType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ;
break;
case D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP:
PrimType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ;
break;
case D3D11_PRIMITIVE_TOPOLOGY_LINELIST:
PrimType = D3D11_PRIMITIVE_TOPOLOGY_LINELIST_ADJ;
break;
case D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP:
PrimType = D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ;
break;
}
}
pd3dDeviceContext->IASetPrimitiveTopology( PrimType );
pMat = &m_pMaterialArray[ pSubset->MaterialID ];
if ( iDiffuseSlot != INVALID_SAMPLER_SLOT && !IsErrorResource( pMat->pDiffuseRV11 ) )
{
pd3dDeviceContext->PSSetShaderResources( iDiffuseSlot, 1, &pMat->pDiffuseRV11 );
}
if ( iNormalSlot != INVALID_SAMPLER_SLOT && !IsErrorResource( pMat->pNormalRV11 ) )
{
pd3dDeviceContext->PSSetShaderResources( iNormalSlot, 1, &pMat->pNormalRV11 );
}
if ( iSpecularSlot != INVALID_SAMPLER_SLOT && !IsErrorResource( pMat->pSpecularRV11 ) )
{
pd3dDeviceContext->PSSetShaderResources( iSpecularSlot, 1, &pMat->pSpecularRV11 );
}
UINT IndexCount = ( UINT )pSubset->IndexCount;
UINT IndexStart = ( UINT )pSubset->IndexStart;
UINT VertexStart = ( UINT )pSubset->VertexStart;
if ( bAdjacent )
{
IndexCount *= 2;
IndexStart *= 2;
}
pd3dDeviceContext->DrawIndexed( IndexCount, IndexStart, VertexStart );
}
}
//--------------------------------------------------------------------------------------
void CDXUTSDKMesh::RenderFrame( UINT iFrame,
bool bAdjacent,
ID3D11DeviceContext* pd3dDeviceContext,
UINT iDiffuseSlot,
UINT iNormalSlot,
UINT iSpecularSlot )
{
if ( !m_pStaticMeshData || !m_pFrameArray )
{
return;
}
if ( m_pFrameArray[iFrame].Mesh != INVALID_MESH )
{
RenderMesh( m_pFrameArray[iFrame].Mesh,
bAdjacent,
pd3dDeviceContext,
iDiffuseSlot,
iNormalSlot,
iSpecularSlot );
}
// Render our children
if ( m_pFrameArray[iFrame].ChildFrame != INVALID_FRAME )
RenderFrame( m_pFrameArray[iFrame].ChildFrame, bAdjacent, pd3dDeviceContext, iDiffuseSlot,
iNormalSlot, iSpecularSlot );
// Render our siblings
if ( m_pFrameArray[iFrame].SiblingFrame != INVALID_FRAME )
RenderFrame( m_pFrameArray[iFrame].SiblingFrame, bAdjacent, pd3dDeviceContext, iDiffuseSlot,
iNormalSlot, iSpecularSlot );
}
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
void CDXUTSDKMesh::RenderMesh( UINT iMesh,
LPDIRECT3DDEVICE9 pd3dDevice,
LPD3DXEFFECT pEffect,
D3DXHANDLE hTechnique,
D3DXHANDLE htxDiffuse,
D3DXHANDLE htxNormal,
D3DXHANDLE htxSpecular )
{
if ( 0 < GetOutstandingBufferResources() )
{
return;
}
SDKMESH_MESH* pMesh = &m_pMeshArray[iMesh];
// set vb streams
for ( UINT i = 0; i < ( UINT )pMesh->NumVertexBuffers; i++ )
{
pd3dDevice->SetStreamSource( i,
m_pVertexBufferArray[ pMesh->VertexBuffers[i] ].pVB9,
0,
( UINT )m_pVertexBufferArray[ pMesh->VertexBuffers[i] ].StrideBytes );
}
// Set our index buffer as well
pd3dDevice->SetIndices( m_pIndexBufferArray[ pMesh->IndexBuffer ].pIB9 );
// Render the scene with this technique
pEffect->SetTechnique( hTechnique );
SDKMESH_SUBSET* pSubset = NULL;
SDKMESH_MATERIAL* pMat = NULL;
D3DPRIMITIVETYPE PrimType;
UINT cPasses = 0;
pEffect->Begin( &cPasses, 0 );
for ( UINT p = 0; p < cPasses; ++p )
{
pEffect->BeginPass( p );
for ( UINT subset = 0; subset < pMesh->NumSubsets; subset++ )
{
pSubset = &m_pSubsetArray[ pMesh->pSubsets[subset] ];
PrimType = GetPrimitiveType9( ( SDKMESH_PRIMITIVE_TYPE )pSubset->PrimitiveType );
if ( INVALID_MATERIAL != pSubset->MaterialID && m_pMeshHeader->NumMaterials > 0 )
{
pMat = &m_pMaterialArray[ pSubset->MaterialID ];
if ( htxDiffuse && !IsErrorResource( pMat->pDiffuseTexture9 ) )
{
pEffect->SetTexture( htxDiffuse, pMat->pDiffuseTexture9 );
}
if ( htxNormal && !IsErrorResource( pMat->pNormalTexture9 ) )
{
pEffect->SetTexture( htxNormal, pMat->pNormalTexture9 );
}
if ( htxSpecular && !IsErrorResource( pMat->pSpecularTexture9 ) )
{
pEffect->SetTexture( htxSpecular, pMat->pSpecularTexture9 );
}
}
pEffect->CommitChanges();
UINT PrimCount = ( UINT )pSubset->IndexCount;
UINT IndexStart = ( UINT )pSubset->IndexStart;
UINT VertexStart = ( UINT )pSubset->VertexStart;
UINT VertexCount = ( UINT )pSubset->VertexCount;
if ( D3DPT_TRIANGLELIST == PrimType )
{
PrimCount /= 3;
}
if ( D3DPT_LINELIST == PrimType )
{
PrimCount /= 2;
}
if ( D3DPT_TRIANGLESTRIP == PrimType )
{
PrimCount = ( PrimCount - 3 ) + 1;
}
if ( D3DPT_LINESTRIP == PrimType )
{
PrimCount -= 1;
}
pd3dDevice->DrawIndexedPrimitive( PrimType, VertexStart, 0, VertexCount, IndexStart, PrimCount );
}
pEffect->EndPass();
}
pEffect->End();
}
//--------------------------------------------------------------------------------------
void CDXUTSDKMesh::RenderFrame( UINT iFrame,
LPDIRECT3DDEVICE9 pd3dDevice,
LPD3DXEFFECT pEffect,
D3DXHANDLE hTechnique,
D3DXHANDLE htxDiffuse,
D3DXHANDLE htxNormal,
D3DXHANDLE htxSpecular )
{
if ( !m_pStaticMeshData || !m_pFrameArray )
{
return;
}
if ( m_pFrameArray[iFrame].Mesh != INVALID_MESH )
{
RenderMesh( m_pFrameArray[iFrame].Mesh,
pd3dDevice,
pEffect,
hTechnique,
htxDiffuse,
htxNormal,
htxSpecular );
}
// Render our children
if ( m_pFrameArray[iFrame].ChildFrame != INVALID_FRAME )
RenderFrame( m_pFrameArray[iFrame].ChildFrame, pd3dDevice, pEffect, hTechnique, htxDiffuse, htxNormal,
htxSpecular );
// Render our siblings
if ( m_pFrameArray[iFrame].SiblingFrame != INVALID_FRAME )
RenderFrame( m_pFrameArray[iFrame].SiblingFrame, pd3dDevice, pEffect, hTechnique, htxDiffuse, htxNormal,
htxSpecular );
}
//--------------------------------------------------------------------------------------
CDXUTSDKMesh::CDXUTSDKMesh() : m_NumOutstandingResources( 0 ),
m_bLoading( false ),
m_hFile( 0 ),
m_hFileMappingObject( 0 ),
m_pMeshHeader( NULL ),
m_pStaticMeshData( NULL ),
m_pHeapData( NULL ),
m_pAdjacencyIndexBufferArray( NULL ),
m_pAnimationData( NULL ),
m_pAnimationHeader( NULL ),
m_ppVertices( NULL ),
m_ppIndices( NULL ),
m_pBindPoseFrameMatrices( NULL ),
m_pTransformedFrameMatrices( NULL ),
m_pWorldPoseFrameMatrices( NULL ),
m_pDev9( NULL ),
m_pDev11( NULL )
{
}
//--------------------------------------------------------------------------------------
CDXUTSDKMesh::~CDXUTSDKMesh()
{
Destroy();
}
//--------------------------------------------------------------------------------------
HRESULT CDXUTSDKMesh::Create( ID3D11Device* pDev11, LPCTSTR szFileName, bool bCreateAdjacencyIndices,
SDKMESH_CALLBACKS11* pLoaderCallbacks )
{
return CreateFromFile( pDev11, NULL, szFileName, bCreateAdjacencyIndices, pLoaderCallbacks, NULL );
}
//--------------------------------------------------------------------------------------
HRESULT CDXUTSDKMesh::Create( IDirect3DDevice9* pDev9, LPCTSTR szFileName, bool bCreateAdjacencyIndices,
SDKMESH_CALLBACKS9* pLoaderCallbacks )
{
return CreateFromFile( NULL, pDev9, szFileName, bCreateAdjacencyIndices, NULL, pLoaderCallbacks );
}
//--------------------------------------------------------------------------------------
HRESULT CDXUTSDKMesh::Create( ID3D11Device* pDev11, BYTE* pData, UINT DataBytes, bool bCreateAdjacencyIndices,
bool bCopyStatic, SDKMESH_CALLBACKS11* pLoaderCallbacks )
{
return CreateFromMemory( pDev11, NULL, pData, DataBytes, bCreateAdjacencyIndices, bCopyStatic,
pLoaderCallbacks, NULL );
}
//--------------------------------------------------------------------------------------
HRESULT CDXUTSDKMesh::Create( IDirect3DDevice9* pDev9, BYTE* pData, UINT DataBytes, bool bCreateAdjacencyIndices,
bool bCopyStatic, SDKMESH_CALLBACKS9* pLoaderCallbacks )
{
return CreateFromMemory( NULL, pDev9, pData, DataBytes, bCreateAdjacencyIndices, bCopyStatic, NULL,
pLoaderCallbacks );
}
//--------------------------------------------------------------------------------------
HRESULT CDXUTSDKMesh::LoadAnimation( WCHAR* szFileName )
{
HRESULT hr = E_FAIL;
DWORD dwBytesRead = 0;
LARGE_INTEGER liMove;
WCHAR strPath[MAX_PATH];
// Find the path for the file
V_RETURN( DXUTFindDXSDKMediaFileCch( strPath, MAX_PATH, szFileName ) );
// Open the file
HANDLE hFile = CreateFile( strPath, FILE_READ_DATA, FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN, NULL );
if ( INVALID_HANDLE_VALUE == hFile )
{
return DXUTERR_MEDIANOTFOUND;
}
/////////////////////////
// Header
SDKANIMATION_FILE_HEADER fileheader;
if ( !ReadFile( hFile, &fileheader, sizeof( SDKANIMATION_FILE_HEADER ), &dwBytesRead, NULL ) )
{
goto Error;
}
//allocate
m_pAnimationData = new BYTE[ ( size_t )( sizeof( SDKANIMATION_FILE_HEADER ) + fileheader.AnimationDataSize ) ];
if ( !m_pAnimationData )
{
hr = E_OUTOFMEMORY;
goto Error;
}
// read it all in
liMove.QuadPart = 0;
if ( !SetFilePointerEx( hFile, liMove, NULL, FILE_BEGIN ) )
{
goto Error;
}
if ( !ReadFile( hFile, m_pAnimationData, ( DWORD )( sizeof( SDKANIMATION_FILE_HEADER ) +
fileheader.AnimationDataSize ), &dwBytesRead, NULL ) )
{
goto Error;
}
// pointer fixup
m_pAnimationHeader = ( SDKANIMATION_FILE_HEADER* )m_pAnimationData;
m_pAnimationFrameData = ( SDKANIMATION_FRAME_DATA* )( m_pAnimationData + m_pAnimationHeader->AnimationDataOffset );
UINT64 BaseOffset = sizeof( SDKANIMATION_FILE_HEADER );
for ( UINT i = 0; i < m_pAnimationHeader->NumFrames; i++ )
{
m_pAnimationFrameData[i].pAnimationData = ( SDKANIMATION_DATA* )( m_pAnimationData +
m_pAnimationFrameData[i].DataOffset +
BaseOffset );
SDKMESH_FRAME* pFrame = FindFrame( m_pAnimationFrameData[i].FrameName );
if ( pFrame )
{
pFrame->AnimationDataIndex = i;
}
}
hr = S_OK;
Error:
CloseHandle( hFile );
return hr;
}
//--------------------------------------------------------------------------------------
void CDXUTSDKMesh::Destroy()
{
if ( !CheckLoadDone() )
{
return;
}
if ( m_pStaticMeshData )
{
if ( m_pMaterialArray )
{
for ( UINT64 m = 0; m < m_pMeshHeader->NumMaterials; m++ )
{
if ( m_pDev9 )
{
if ( !IsErrorResource( m_pMaterialArray[m].pDiffuseTexture9 ) )
{
SAFE_RELEASE( m_pMaterialArray[m].pDiffuseTexture9 );
}
if ( !IsErrorResource( m_pMaterialArray[m].pNormalTexture9 ) )
{
SAFE_RELEASE( m_pMaterialArray[m].pNormalTexture9 );
}
if ( !IsErrorResource( m_pMaterialArray[m].pSpecularTexture9 ) )
{
SAFE_RELEASE( m_pMaterialArray[m].pSpecularTexture9 );
}
}
else if ( m_pDev11 )
{
//ID3D11Resource* pRes = NULL;
if ( m_pMaterialArray[m].pDiffuseRV11 && !IsErrorResource( m_pMaterialArray[m].pDiffuseRV11 ) )
{
//m_pMaterialArray[m].pDiffuseRV11->GetResource( &pRes );
//SAFE_RELEASE( pRes );
SAFE_RELEASE( m_pMaterialArray[m].pDiffuseRV11 );
}
if ( m_pMaterialArray[m].pNormalRV11 && !IsErrorResource( m_pMaterialArray[m].pNormalRV11 ) )
{
//m_pMaterialArray[m].pNormalRV11->GetResource( &pRes );
//SAFE_RELEASE( pRes );
SAFE_RELEASE( m_pMaterialArray[m].pNormalRV11 );
}
if ( m_pMaterialArray[m].pSpecularRV11 && !IsErrorResource( m_pMaterialArray[m].pSpecularRV11 ) )
{
//m_pMaterialArray[m].pSpecularRV11->GetResource( &pRes );
//SAFE_RELEASE( pRes );
SAFE_RELEASE( m_pMaterialArray[m].pSpecularRV11 );
}
}
}
}
for ( UINT64 i = 0; i < m_pMeshHeader->NumVertexBuffers; i++ )
{
if ( !IsErrorResource( m_pVertexBufferArray[i].pVB9 ) )
{
SAFE_RELEASE( m_pVertexBufferArray[i].pVB9 );
}
}
for ( UINT64 i = 0; i < m_pMeshHeader->NumIndexBuffers; i++ )
{
if ( !IsErrorResource( m_pIndexBufferArray[i].pIB9 ) )
{
SAFE_RELEASE( m_pIndexBufferArray[i].pIB9 );
}
}
}
if ( m_pAdjacencyIndexBufferArray )
{
for ( UINT64 i = 0; i < m_pMeshHeader->NumIndexBuffers; i++ )
{
SAFE_RELEASE( m_pAdjacencyIndexBufferArray[i].pIB11 );
}
}
SAFE_DELETE_ARRAY( m_pAdjacencyIndexBufferArray );
SAFE_DELETE_ARRAY( m_pHeapData );
m_pStaticMeshData = NULL;
SAFE_DELETE_ARRAY( m_pAnimationData );
SAFE_DELETE_ARRAY( m_pBindPoseFrameMatrices );
SAFE_DELETE_ARRAY( m_pTransformedFrameMatrices );
SAFE_DELETE_ARRAY( m_pWorldPoseFrameMatrices );
SAFE_DELETE_ARRAY( m_ppVertices );
SAFE_DELETE_ARRAY( m_ppIndices );
m_pMeshHeader = NULL;
m_pVertexBufferArray = NULL;
m_pIndexBufferArray = NULL;
m_pMeshArray = NULL;
m_pSubsetArray = NULL;
m_pFrameArray = NULL;
m_pMaterialArray = NULL;
m_pAnimationHeader = NULL;
m_pAnimationFrameData = NULL;
}
//--------------------------------------------------------------------------------------
// transform the bind pose
//--------------------------------------------------------------------------------------
void CDXUTSDKMesh::TransformBindPose( D3DXMATRIX* pWorld )
{
TransformBindPoseFrame( 0, pWorld );
}
//--------------------------------------------------------------------------------------
// transform the mesh frames according to the animation for time fTime
//--------------------------------------------------------------------------------------
void CDXUTSDKMesh::TransformMesh( D3DXMATRIX* pWorld, double fTime )
{
if ( m_pAnimationHeader == NULL || FTT_RELATIVE == m_pAnimationHeader->FrameTransformType )
{
TransformFrame( 0, pWorld, fTime );
// For each frame, move the transform to the bind pose, then
// move it to the final position
D3DXMATRIX mInvBindPose;
D3DXMATRIX mFinal;
for ( UINT i = 0; i < m_pMeshHeader->NumFrames; i++ )
{
D3DXMatrixInverse( &mInvBindPose, NULL, &m_pBindPoseFrameMatrices[i] );
mFinal = mInvBindPose * m_pTransformedFrameMatrices[i];
m_pTransformedFrameMatrices[i] = mFinal;
}
}
else if ( FTT_ABSOLUTE == m_pAnimationHeader->FrameTransformType )
{
for ( UINT i = 0; i < m_pAnimationHeader->NumFrames; i++ )
{
TransformFrameAbsolute( i, fTime );
}
}
}
//--------------------------------------------------------------------------------------
void CDXUTSDKMesh::Render( ID3D11DeviceContext* pd3dDeviceContext,
UINT iDiffuseSlot,
UINT iNormalSlot,
UINT iSpecularSlot )
{
RenderFrame( 0, false, pd3dDeviceContext, iDiffuseSlot, iNormalSlot, iSpecularSlot );
}
//--------------------------------------------------------------------------------------
void CDXUTSDKMesh::RenderAdjacent( ID3D11DeviceContext* pd3dDeviceContext,
UINT iDiffuseSlot,
UINT iNormalSlot,
UINT iSpecularSlot )
{
RenderFrame( 0, true, pd3dDeviceContext, iDiffuseSlot, iNormalSlot, iSpecularSlot );
}
//--------------------------------------------------------------------------------------
void CDXUTSDKMesh::Render( LPDIRECT3DDEVICE9 pd3dDevice,
LPD3DXEFFECT pEffect,
D3DXHANDLE hTechnique,
D3DXHANDLE htxDiffuse,
D3DXHANDLE htxNormal,
D3DXHANDLE htxSpecular )
{
RenderFrame( 0, pd3dDevice, pEffect, hTechnique, htxDiffuse, htxNormal, htxSpecular );
}
//--------------------------------------------------------------------------------------
D3D11_PRIMITIVE_TOPOLOGY CDXUTSDKMesh::GetPrimitiveType11( SDKMESH_PRIMITIVE_TYPE PrimType )
{
D3D11_PRIMITIVE_TOPOLOGY retType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
switch ( PrimType )
{
case PT_TRIANGLE_LIST:
retType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
break;
case PT_TRIANGLE_STRIP:
retType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
break;
case PT_LINE_LIST:
retType = D3D11_PRIMITIVE_TOPOLOGY_LINELIST;
break;
case PT_LINE_STRIP:
retType = D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP;
break;
case PT_POINT_LIST:
retType = D3D11_PRIMITIVE_TOPOLOGY_POINTLIST;
break;
case PT_TRIANGLE_LIST_ADJ:
retType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ;
break;
case PT_TRIANGLE_STRIP_ADJ:
retType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ;
break;
case PT_LINE_LIST_ADJ:
retType = D3D11_PRIMITIVE_TOPOLOGY_LINELIST_ADJ;
break;
case PT_LINE_STRIP_ADJ:
retType = D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ;
break;
};
return retType;
}
//--------------------------------------------------------------------------------------
DXGI_FORMAT CDXUTSDKMesh::GetIBFormat11( UINT iMesh )
{
switch ( m_pIndexBufferArray[ m_pMeshArray[ iMesh ].IndexBuffer ].IndexType )
{
case IT_16BIT:
return DXGI_FORMAT_R16_UINT;
case IT_32BIT:
return DXGI_FORMAT_R32_UINT;
};
return DXGI_FORMAT_R16_UINT;
}
//--------------------------------------------------------------------------------------
ID3D11Buffer* CDXUTSDKMesh::GetVB11( UINT iMesh, UINT iVB )
{
return m_pVertexBufferArray[ m_pMeshArray[ iMesh ].VertexBuffers[iVB] ].pVB11;
}
//--------------------------------------------------------------------------------------
ID3D11Buffer* CDXUTSDKMesh::GetIB11( UINT iMesh )
{
return m_pIndexBufferArray[ m_pMeshArray[ iMesh ].IndexBuffer ].pIB11;
}
SDKMESH_INDEX_TYPE CDXUTSDKMesh::GetIndexType( UINT iMesh )
{
return ( SDKMESH_INDEX_TYPE ) m_pIndexBufferArray[m_pMeshArray[ iMesh ].IndexBuffer].IndexType;
}
//--------------------------------------------------------------------------------------
ID3D11Buffer* CDXUTSDKMesh::GetAdjIB11( UINT iMesh )
{
return m_pAdjacencyIndexBufferArray[ m_pMeshArray[ iMesh ].IndexBuffer ].pIB11;
}
//--------------------------------------------------------------------------------------
D3DPRIMITIVETYPE CDXUTSDKMesh::GetPrimitiveType9( SDKMESH_PRIMITIVE_TYPE PrimType )
{
D3DPRIMITIVETYPE retType = D3DPT_TRIANGLELIST;
switch ( PrimType )
{
case PT_TRIANGLE_LIST:
retType = D3DPT_TRIANGLELIST;
break;
case PT_TRIANGLE_STRIP:
retType = D3DPT_TRIANGLESTRIP;
break;
case PT_LINE_LIST:
retType = D3DPT_LINELIST;
break;
case PT_LINE_STRIP:
retType = D3DPT_LINESTRIP;
break;
case PT_POINT_LIST:
retType = D3DPT_POINTLIST;
break;
};
return retType;
}
//--------------------------------------------------------------------------------------
D3DFORMAT CDXUTSDKMesh::GetIBFormat9( UINT iMesh )
{
switch ( m_pIndexBufferArray[ m_pMeshArray[ iMesh ].IndexBuffer ].IndexType )
{
case IT_16BIT:
return D3DFMT_INDEX16;
case IT_32BIT:
return D3DFMT_INDEX32;
};
return D3DFMT_INDEX16;
}
//--------------------------------------------------------------------------------------
IDirect3DVertexBuffer9* CDXUTSDKMesh::GetVB9( UINT iMesh, UINT iVB )
{
return m_pVertexBufferArray[ m_pMeshArray[ iMesh ].VertexBuffers[iVB] ].pVB9;
}
//--------------------------------------------------------------------------------------
IDirect3DIndexBuffer9* CDXUTSDKMesh::GetIB9( UINT iMesh )
{
return m_pIndexBufferArray[ m_pMeshArray[ iMesh ].IndexBuffer ].pIB9;
}
//--------------------------------------------------------------------------------------
char* CDXUTSDKMesh::GetMeshPathA()
{
return m_strPath;
}
//--------------------------------------------------------------------------------------
WCHAR* CDXUTSDKMesh::GetMeshPathW()
{
return m_strPathW;
}
//--------------------------------------------------------------------------------------
UINT CDXUTSDKMesh::GetNumMeshes()
{
if ( !m_pMeshHeader )
{
return 0;
}
return m_pMeshHeader->NumMeshes;
}
//--------------------------------------------------------------------------------------
UINT CDXUTSDKMesh::GetNumMaterials()
{
if ( !m_pMeshHeader )
{
return 0;
}
return m_pMeshHeader->NumMaterials;
}
//--------------------------------------------------------------------------------------
UINT CDXUTSDKMesh::GetNumVBs()
{
if ( !m_pMeshHeader )
{
return 0;
}
return m_pMeshHeader->NumVertexBuffers;
}
//--------------------------------------------------------------------------------------
UINT CDXUTSDKMesh::GetNumIBs()
{
if ( !m_pMeshHeader )
{
return 0;
}
return m_pMeshHeader->NumIndexBuffers;
}
//--------------------------------------------------------------------------------------
ID3D11Buffer* CDXUTSDKMesh::GetVB11At( UINT iVB )
{
return m_pVertexBufferArray[ iVB ].pVB11;
}
//--------------------------------------------------------------------------------------
ID3D11Buffer* CDXUTSDKMesh::GetIB11At( UINT iIB )
{
return m_pIndexBufferArray[ iIB ].pIB11;
}
//--------------------------------------------------------------------------------------
IDirect3DVertexBuffer9* CDXUTSDKMesh::GetVB9At( UINT iVB )
{
return m_pVertexBufferArray[ iVB ].pVB9;
}
//--------------------------------------------------------------------------------------
IDirect3DIndexBuffer9* CDXUTSDKMesh::GetIB9At( UINT iIB )
{
return m_pIndexBufferArray[ iIB ].pIB9;
}
//--------------------------------------------------------------------------------------
BYTE* CDXUTSDKMesh::GetRawVerticesAt( UINT iVB )
{
return m_ppVertices[iVB];
}
//--------------------------------------------------------------------------------------
BYTE* CDXUTSDKMesh::GetRawIndicesAt( UINT iIB )
{
return m_ppIndices[iIB];
}
//--------------------------------------------------------------------------------------
SDKMESH_MATERIAL* CDXUTSDKMesh::GetMaterial( UINT iMaterial )
{
return &m_pMaterialArray[ iMaterial ];
}
//--------------------------------------------------------------------------------------
SDKMESH_MESH* CDXUTSDKMesh::GetMesh( UINT iMesh )
{
return &m_pMeshArray[ iMesh ];
}
//--------------------------------------------------------------------------------------
UINT CDXUTSDKMesh::GetNumSubsets( UINT iMesh )
{
return m_pMeshArray[ iMesh ].NumSubsets;
}
//--------------------------------------------------------------------------------------
SDKMESH_SUBSET* CDXUTSDKMesh::GetSubset( UINT iMesh, UINT iSubset )
{
return &m_pSubsetArray[ m_pMeshArray[ iMesh ].pSubsets[iSubset] ];
}
//--------------------------------------------------------------------------------------
UINT CDXUTSDKMesh::GetVertexStride( UINT iMesh, UINT iVB )
{
return ( UINT )m_pVertexBufferArray[ m_pMeshArray[ iMesh ].VertexBuffers[iVB] ].StrideBytes;
}
//--------------------------------------------------------------------------------------
UINT CDXUTSDKMesh::GetNumFrames()
{
return m_pMeshHeader->NumFrames;
}
//--------------------------------------------------------------------------------------
SDKMESH_FRAME* CDXUTSDKMesh::GetFrame( UINT iFrame )
{
assert( iFrame < m_pMeshHeader->NumFrames );
return &m_pFrameArray[ iFrame ];
}
//--------------------------------------------------------------------------------------
SDKMESH_FRAME* CDXUTSDKMesh::FindFrame( char* pszName )
{
for ( UINT i = 0; i < m_pMeshHeader->NumFrames; i++ )
{
if ( _stricmp( m_pFrameArray[i].Name, pszName ) == 0 )
{
return &m_pFrameArray[i];
}
}
return NULL;
}
//--------------------------------------------------------------------------------------
UINT64 CDXUTSDKMesh::GetNumVertices( UINT iMesh, UINT iVB )
{
return m_pVertexBufferArray[ m_pMeshArray[ iMesh ].VertexBuffers[iVB] ].NumVertices;
}
//--------------------------------------------------------------------------------------
UINT64 CDXUTSDKMesh::GetNumIndices( UINT iMesh )
{
return m_pIndexBufferArray[ m_pMeshArray[ iMesh ].IndexBuffer ].NumIndices;
}
//--------------------------------------------------------------------------------------
D3DXVECTOR3 CDXUTSDKMesh::GetMeshBBoxCenter( UINT iMesh )
{
return m_pMeshArray[iMesh].BoundingBoxCenter;
}
//--------------------------------------------------------------------------------------
D3DXVECTOR3 CDXUTSDKMesh::GetMeshBBoxExtents( UINT iMesh )
{
return m_pMeshArray[iMesh].BoundingBoxExtents;
}
//--------------------------------------------------------------------------------------
UINT CDXUTSDKMesh::GetOutstandingResources()
{
UINT outstandingResources = 0;
if ( !m_pMeshHeader )
{
return 1;
}
outstandingResources += GetOutstandingBufferResources();
if ( m_pDev11 )
{
for ( UINT i = 0; i < m_pMeshHeader->NumMaterials; i++ )
{
if ( m_pMaterialArray[i].DiffuseTexture[0] != 0 )
{
if ( !m_pMaterialArray[i].pDiffuseRV11 && !IsErrorResource( m_pMaterialArray[i].pDiffuseRV11 ) )
{
outstandingResources ++;
}
}
if ( m_pMaterialArray[i].NormalTexture[0] != 0 )
{
if ( !m_pMaterialArray[i].pNormalRV11 && !IsErrorResource( m_pMaterialArray[i].pNormalRV11 ) )
{
outstandingResources ++;
}
}
if ( m_pMaterialArray[i].SpecularTexture[0] != 0 )
{
if ( !m_pMaterialArray[i].pSpecularRV11 && !IsErrorResource( m_pMaterialArray[i].pSpecularRV11 ) )
{
outstandingResources ++;
}
}
}
}
else
{
for ( UINT i = 0; i < m_pMeshHeader->NumMaterials; i++ )
{
if ( m_pMaterialArray[i].DiffuseTexture[0] != 0 )
{
if ( !m_pMaterialArray[i].pDiffuseTexture9 && !IsErrorResource( m_pMaterialArray[i].pDiffuseTexture9 ) )
{
outstandingResources ++;
}
}
if ( m_pMaterialArray[i].NormalTexture[0] != 0 )
{
if ( !m_pMaterialArray[i].pNormalTexture9 && !IsErrorResource( m_pMaterialArray[i].pNormalTexture9 ) )
{
outstandingResources ++;
}
}
if ( m_pMaterialArray[i].SpecularTexture[0] != 0 )
{
if ( !m_pMaterialArray[i].pSpecularTexture9 &&
!IsErrorResource( m_pMaterialArray[i].pSpecularTexture9 ) )
{
outstandingResources ++;
}
}
}
}
return outstandingResources;
}
//--------------------------------------------------------------------------------------
UINT CDXUTSDKMesh::GetOutstandingBufferResources()
{
UINT outstandingResources = 0;
if ( !m_pMeshHeader )
{
return 1;
}
for ( UINT i = 0; i < m_pMeshHeader->NumVertexBuffers; i++ )
{
if ( !m_pVertexBufferArray[i].pVB9 && !IsErrorResource( m_pVertexBufferArray[i].pVB9 ) )
{
outstandingResources ++;
}
}
for ( UINT i = 0; i < m_pMeshHeader->NumIndexBuffers; i++ )
{
if ( !m_pIndexBufferArray[i].pIB9 && !IsErrorResource( m_pIndexBufferArray[i].pIB9 ) )
{
outstandingResources ++;
}
}
return outstandingResources;
}
//--------------------------------------------------------------------------------------
bool CDXUTSDKMesh::CheckLoadDone()
{
if ( 0 == GetOutstandingResources() )
{
m_bLoading = false;
return true;
}
return false;
}
//--------------------------------------------------------------------------------------
bool CDXUTSDKMesh::IsLoaded()
{
if ( m_pStaticMeshData && !m_bLoading )
{
return true;
}
return false;
}
//--------------------------------------------------------------------------------------
bool CDXUTSDKMesh::IsLoading()
{
return m_bLoading;
}
//--------------------------------------------------------------------------------------
void CDXUTSDKMesh::SetLoading( bool bLoading )
{
m_bLoading = bLoading;
}
//--------------------------------------------------------------------------------------
BOOL CDXUTSDKMesh::HadLoadingError()
{
if ( m_pMeshHeader )
{
for ( UINT i = 0; i < m_pMeshHeader->NumVertexBuffers; i++ )
{
if ( IsErrorResource( m_pVertexBufferArray[i].pVB9 ) )
{
return TRUE;
}
}
for ( UINT i = 0; i < m_pMeshHeader->NumIndexBuffers; i++ )
{
if ( IsErrorResource( m_pIndexBufferArray[i].pIB9 ) )
{
return TRUE;
}
}
}
return FALSE;
}
//--------------------------------------------------------------------------------------
UINT CDXUTSDKMesh::GetNumInfluences( UINT iMesh )
{
return m_pMeshArray[iMesh].NumFrameInfluences;
}
//--------------------------------------------------------------------------------------
const D3DXMATRIX* CDXUTSDKMesh::GetMeshInfluenceMatrix( UINT iMesh, UINT iInfluence )
{
UINT iFrame = m_pMeshArray[iMesh].pFrameInfluences[ iInfluence ];
return &m_pTransformedFrameMatrices[iFrame];
}
const D3DXMATRIX* CDXUTSDKMesh::GetWorldMatrix( UINT iFrameIndex )
{
return &m_pWorldPoseFrameMatrices[iFrameIndex];
}
const D3DXMATRIX* CDXUTSDKMesh::GetInfluenceMatrix( UINT iFrameIndex )
{
return &m_pTransformedFrameMatrices[iFrameIndex];
}
//--------------------------------------------------------------------------------------
UINT CDXUTSDKMesh::GetAnimationKeyFromTime( double fTime )
{
if ( m_pAnimationHeader == NULL )
{
return 0;
}
UINT iTick = ( UINT )( m_pAnimationHeader->AnimationFPS * fTime );
iTick = iTick % ( m_pAnimationHeader->NumAnimationKeys - 1 );
iTick ++;
return iTick;
}
bool CDXUTSDKMesh::GetAnimationProperties( UINT* pNumKeys, FLOAT* pFrameTime )
{
if ( m_pAnimationHeader == NULL )
{
return false;
}
*pNumKeys = m_pAnimationHeader->NumAnimationKeys;
*pFrameTime = 1.0f / ( FLOAT )m_pAnimationHeader->AnimationFPS;
return true;
}
//-------------------------------------------------------------------------------------
// CDXUTXFileMesh implementation.
//-------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------
CDXUTXFileMesh::CDXUTXFileMesh( LPCWSTR strName )
{
wcscpy_s( m_strName, 512, strName );
m_pMesh = NULL;
m_pMaterials = NULL;
m_pTextures = NULL;
m_bUseMaterials = TRUE;
m_pVB = NULL;
m_pIB = NULL;
m_pDecl = NULL;
m_strMaterials = NULL;
m_dwNumMaterials = 0;
m_dwNumVertices = 0;
m_dwNumFaces = 0;
m_dwBytesPerVertex = 0;
}
//-----------------------------------------------------------------------------
CDXUTXFileMesh::~CDXUTXFileMesh()
{
Destroy();
}
//-----------------------------------------------------------------------------
HRESULT CDXUTXFileMesh::Create( LPDIRECT3DDEVICE9 pd3dDevice, LPCWSTR strFilename )
{
WCHAR strPath[MAX_PATH];
LPD3DXBUFFER pAdjacencyBuffer = NULL;
LPD3DXBUFFER pMtrlBuffer = NULL;
HRESULT hr;
// Cleanup previous mesh if any
Destroy();
// Find the path for the file, and convert it to ANSI (for the D3DX API)
DXUTFindDXSDKMediaFileCch( strPath, sizeof( strPath ) / sizeof( WCHAR ), strFilename );
// Load the mesh
if ( FAILED( hr = D3DXLoadMeshFromX( strPath, D3DXMESH_MANAGED, pd3dDevice,
&pAdjacencyBuffer, &pMtrlBuffer, NULL,
&m_dwNumMaterials, &m_pMesh ) ) )
{
return hr;
}
// Optimize the mesh for performance
if ( FAILED( hr = m_pMesh->OptimizeInplace(
D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE,
( DWORD* )pAdjacencyBuffer->GetBufferPointer(), NULL, NULL, NULL ) ) )
{
SAFE_RELEASE( pAdjacencyBuffer );
SAFE_RELEASE( pMtrlBuffer );
return hr;
}
// Set strPath to the path of the mesh file
WCHAR* pLastBSlash = wcsrchr( strPath, L'\\' );
if ( pLastBSlash )
{
*( pLastBSlash + 1 ) = L'\0';
}
else
{
*strPath = L'\0';
}
D3DXMATERIAL* d3dxMtrls = ( D3DXMATERIAL* )pMtrlBuffer->GetBufferPointer();
hr = CreateMaterials( strPath, pd3dDevice, d3dxMtrls, m_dwNumMaterials );
SAFE_RELEASE( pAdjacencyBuffer );
SAFE_RELEASE( pMtrlBuffer );
// Extract data from m_pMesh for easy access
D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE];
m_dwNumVertices = m_pMesh->GetNumVertices();
m_dwNumFaces = m_pMesh->GetNumFaces();
m_dwBytesPerVertex = m_pMesh->GetNumBytesPerVertex();
m_pMesh->GetIndexBuffer( &m_pIB );
m_pMesh->GetVertexBuffer( &m_pVB );
m_pMesh->GetDeclaration( decl );
pd3dDevice->CreateVertexDeclaration( decl, &m_pDecl );
return hr;
}
//-----------------------------------------------------------------------------
HRESULT CDXUTXFileMesh::Create( LPDIRECT3DDEVICE9 pd3dDevice,
LPD3DXFILEDATA pFileData )
{
LPD3DXBUFFER pMtrlBuffer = NULL;
LPD3DXBUFFER pAdjacencyBuffer = NULL;
HRESULT hr;
// Cleanup previous mesh if any
Destroy();
// Load the mesh from the DXFILEDATA object
if ( FAILED( hr = D3DXLoadMeshFromXof( pFileData, D3DXMESH_MANAGED, pd3dDevice,
&pAdjacencyBuffer, &pMtrlBuffer, NULL,
&m_dwNumMaterials, &m_pMesh ) ) )
{
return hr;
}
// Optimize the mesh for performance
if ( FAILED( hr = m_pMesh->OptimizeInplace(
D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE,
( DWORD* )pAdjacencyBuffer->GetBufferPointer(), NULL, NULL, NULL ) ) )
{
SAFE_RELEASE( pAdjacencyBuffer );
SAFE_RELEASE( pMtrlBuffer );
return hr;
}
D3DXMATERIAL* d3dxMtrls = ( D3DXMATERIAL* )pMtrlBuffer->GetBufferPointer();
hr = CreateMaterials( L"", pd3dDevice, d3dxMtrls, m_dwNumMaterials );
SAFE_RELEASE( pAdjacencyBuffer );
SAFE_RELEASE( pMtrlBuffer );
// Extract data from m_pMesh for easy access
D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE];
m_dwNumVertices = m_pMesh->GetNumVertices();
m_dwNumFaces = m_pMesh->GetNumFaces();
m_dwBytesPerVertex = m_pMesh->GetNumBytesPerVertex();
m_pMesh->GetIndexBuffer( &m_pIB );
m_pMesh->GetVertexBuffer( &m_pVB );
m_pMesh->GetDeclaration( decl );
pd3dDevice->CreateVertexDeclaration( decl, &m_pDecl );
return hr;
}
//-----------------------------------------------------------------------------
HRESULT CDXUTXFileMesh::Create( LPDIRECT3DDEVICE9 pd3dDevice, ID3DXMesh* pInMesh,
D3DXMATERIAL* pd3dxMaterials, DWORD dwMaterials )
{
// Cleanup previous mesh if any
Destroy();
// Optimize the mesh for performance
DWORD* rgdwAdjacency = NULL;
rgdwAdjacency = new DWORD[pInMesh->GetNumFaces() * 3];
if ( rgdwAdjacency == NULL )
{
return E_OUTOFMEMORY;
}
pInMesh->GenerateAdjacency( 1e-6f, rgdwAdjacency );
D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE];
pInMesh->GetDeclaration( decl );
DWORD dwOptions = pInMesh->GetOptions();
dwOptions &= ~( D3DXMESH_32BIT | D3DXMESH_SYSTEMMEM | D3DXMESH_WRITEONLY );
dwOptions |= D3DXMESH_MANAGED;
dwOptions |= D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE;
ID3DXMesh* pTempMesh = NULL;
if ( FAILED( pInMesh->Optimize( dwOptions, rgdwAdjacency, NULL, NULL, NULL, &pTempMesh ) ) )
{
SAFE_DELETE_ARRAY( rgdwAdjacency );
return E_FAIL;
}
SAFE_DELETE_ARRAY( rgdwAdjacency );
SAFE_RELEASE( m_pMesh );
m_pMesh = pTempMesh;
HRESULT hr;
hr = CreateMaterials( L"", pd3dDevice, pd3dxMaterials, dwMaterials );
// Extract data from m_pMesh for easy access
m_dwNumVertices = m_pMesh->GetNumVertices();
m_dwNumFaces = m_pMesh->GetNumFaces();
m_dwBytesPerVertex = m_pMesh->GetNumBytesPerVertex();
m_pMesh->GetIndexBuffer( &m_pIB );
m_pMesh->GetVertexBuffer( &m_pVB );
m_pMesh->GetDeclaration( decl );
pd3dDevice->CreateVertexDeclaration( decl, &m_pDecl );
return hr;
}
//-----------------------------------------------------------------------------
HRESULT CDXUTXFileMesh::CreateMaterials( LPCWSTR strPath, IDirect3DDevice9* pd3dDevice, D3DXMATERIAL* d3dxMtrls,
DWORD dwNumMaterials )
{
// Get material info for the mesh
// Get the array of materials out of the buffer
m_dwNumMaterials = dwNumMaterials;
if ( d3dxMtrls && m_dwNumMaterials > 0 )
{
// Allocate memory for the materials and textures
m_pMaterials = new D3DMATERIAL9[m_dwNumMaterials];
if ( m_pMaterials == NULL )
{
return E_OUTOFMEMORY;
}
m_pTextures = new LPDIRECT3DBASETEXTURE9[m_dwNumMaterials];
if ( m_pTextures == NULL )
{
return E_OUTOFMEMORY;
}
m_strMaterials = new CHAR[m_dwNumMaterials][MAX_PATH];
if ( m_strMaterials == NULL )
{
return E_OUTOFMEMORY;
}
// Copy each material and create its texture
for ( DWORD i = 0; i < m_dwNumMaterials; i++ )
{
// Copy the material
m_pMaterials[i] = d3dxMtrls[i].MatD3D;
m_pTextures[i] = NULL;
// Create a texture
if ( d3dxMtrls[i].pTextureFilename )
{
strcpy_s( m_strMaterials[i], MAX_PATH, d3dxMtrls[i].pTextureFilename );
WCHAR strTexture[MAX_PATH];
WCHAR strTextureTemp[MAX_PATH];
D3DXIMAGE_INFO ImgInfo;
// First attempt to look for texture in the same folder as the input folder.
MultiByteToWideChar( CP_ACP, 0, d3dxMtrls[i].pTextureFilename, -1, strTextureTemp, MAX_PATH );
strTextureTemp[MAX_PATH - 1] = 0;
wcscpy_s( strTexture, MAX_PATH, strPath );
wcscat_s( strTexture, MAX_PATH, strTextureTemp );
// Inspect the texture file to determine the texture type.
if ( FAILED( D3DXGetImageInfoFromFile( strTexture, &ImgInfo ) ) )
{
// Search the media folder
if ( FAILED( DXUTFindDXSDKMediaFileCch( strTexture, MAX_PATH, strTextureTemp ) ) )
{
continue; // Can't find. Skip.
}
D3DXGetImageInfoFromFile( strTexture, &ImgInfo );
}
// Call the appropriate loader according to the texture type.
switch ( ImgInfo.ResourceType )
{
case D3DRTYPE_TEXTURE:
{
IDirect3DTexture9* pTex;
if ( SUCCEEDED( D3DXCreateTextureFromFile( pd3dDevice, strTexture, &pTex ) ) )
{
// Obtain the base texture interface
pTex->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&m_pTextures[i] );
// Release the specialized instance
pTex->Release();
}
break;
}
case D3DRTYPE_CUBETEXTURE:
{
IDirect3DCubeTexture9* pTex;
if ( SUCCEEDED( D3DXCreateCubeTextureFromFile( pd3dDevice, strTexture, &pTex ) ) )
{
// Obtain the base texture interface
pTex->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&m_pTextures[i] );
// Release the specialized instance
pTex->Release();
}
break;
}
case D3DRTYPE_VOLUMETEXTURE:
{
IDirect3DVolumeTexture9* pTex;
if ( SUCCEEDED( D3DXCreateVolumeTextureFromFile( pd3dDevice, strTexture, &pTex ) ) )
{
// Obtain the base texture interface
pTex->QueryInterface( IID_IDirect3DBaseTexture9, ( LPVOID* )&m_pTextures[i] );
// Release the specialized instance
pTex->Release();
}
break;
}
}
}
}
}
return S_OK;
}
//-----------------------------------------------------------------------------
HRESULT CDXUTXFileMesh::SetFVF( LPDIRECT3DDEVICE9 pd3dDevice, DWORD dwFVF )
{
LPD3DXMESH pTempMesh = NULL;
if ( m_pMesh )
{
if ( FAILED( m_pMesh->CloneMeshFVF( m_pMesh->GetOptions(), dwFVF,
pd3dDevice, &pTempMesh ) ) )
{
SAFE_RELEASE( pTempMesh );
return E_FAIL;
}
DWORD dwOldFVF = 0;
dwOldFVF = m_pMesh->GetFVF();
SAFE_RELEASE( m_pMesh );
m_pMesh = pTempMesh;
// Compute normals if they are being requested and
// the old mesh does not have them.
if ( !( dwOldFVF & D3DFVF_NORMAL ) && dwFVF & D3DFVF_NORMAL )
{
D3DXComputeNormals( m_pMesh, NULL );
}
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Convert the mesh to the format specified by the given vertex declarations.
//-----------------------------------------------------------------------------
HRESULT CDXUTXFileMesh::SetVertexDecl( LPDIRECT3DDEVICE9 pd3dDevice, const D3DVERTEXELEMENT9* pDecl,
bool bAutoComputeNormals, bool bAutoComputeTangents,
bool bSplitVertexForOptimalTangents )
{
LPD3DXMESH pTempMesh = NULL;
if ( m_pMesh )
{
if ( FAILED( m_pMesh->CloneMesh( m_pMesh->GetOptions(), pDecl,
pd3dDevice, &pTempMesh ) ) )
{
SAFE_RELEASE( pTempMesh );
return E_FAIL;
}
}
// Check if the old declaration contains a normal.
bool bHadNormal = false;
bool bHadTangent = false;
D3DVERTEXELEMENT9 aOldDecl[MAX_FVF_DECL_SIZE];
if ( m_pMesh && SUCCEEDED( m_pMesh->GetDeclaration( aOldDecl ) ) )
{
for ( UINT index = 0; index < D3DXGetDeclLength( aOldDecl ); ++index )
{
if ( aOldDecl[index].Usage == D3DDECLUSAGE_NORMAL )
{
bHadNormal = true;
}
if ( aOldDecl[index].Usage == D3DDECLUSAGE_TANGENT )
{
bHadTangent = true;
}
}
}
// Check if the new declaration contains a normal.
bool bHaveNormalNow = false;
bool bHaveTangentNow = false;
D3DVERTEXELEMENT9 aNewDecl[MAX_FVF_DECL_SIZE];
if ( pTempMesh && SUCCEEDED( pTempMesh->GetDeclaration( aNewDecl ) ) )
{
for ( UINT index = 0; index < D3DXGetDeclLength( aNewDecl ); ++index )
{
if ( aNewDecl[index].Usage == D3DDECLUSAGE_NORMAL )
{
bHaveNormalNow = true;
}
if ( aNewDecl[index].Usage == D3DDECLUSAGE_TANGENT )
{
bHaveTangentNow = true;
}
}
}
SAFE_RELEASE( m_pMesh );
if ( pTempMesh )
{
m_pMesh = pTempMesh;
if ( !bHadNormal && bHaveNormalNow && bAutoComputeNormals )
{
// Compute normals in case the meshes have them
D3DXComputeNormals( m_pMesh, NULL );
}
if ( bHaveNormalNow && !bHadTangent && bHaveTangentNow && bAutoComputeTangents )
{
ID3DXMesh* pNewMesh;
HRESULT hr;
DWORD* rgdwAdjacency = NULL;
rgdwAdjacency = new DWORD[m_pMesh->GetNumFaces() * 3];
if ( rgdwAdjacency == NULL )
{
return E_OUTOFMEMORY;
}
V_DX( m_pMesh->GenerateAdjacency( 1e-6f, rgdwAdjacency ) );
float fPartialEdgeThreshold;
float fSingularPointThreshold;
float fNormalEdgeThreshold;
if ( bSplitVertexForOptimalTangents )
{
fPartialEdgeThreshold = 0.01f;
fSingularPointThreshold = 0.25f;
fNormalEdgeThreshold = 0.01f;
}
else
{
fPartialEdgeThreshold = -1.01f;
fSingularPointThreshold = 0.01f;
fNormalEdgeThreshold = -1.01f;
}
// Compute tangents, which are required for normal mapping
hr = D3DXComputeTangentFrameEx( m_pMesh,
D3DDECLUSAGE_TEXCOORD, 0,
D3DDECLUSAGE_TANGENT, 0,
D3DX_DEFAULT, 0,
D3DDECLUSAGE_NORMAL, 0,
0, rgdwAdjacency,
fPartialEdgeThreshold, fSingularPointThreshold, fNormalEdgeThreshold,
&pNewMesh, NULL );
SAFE_DELETE_ARRAY( rgdwAdjacency );
if ( FAILED( hr ) )
{
return hr;
}
SAFE_RELEASE( m_pMesh );
m_pMesh = pNewMesh;
}
}
return S_OK;
}
//-----------------------------------------------------------------------------
HRESULT CDXUTXFileMesh::RestoreDeviceObjects( LPDIRECT3DDEVICE9 pd3dDevice )
{
return S_OK;
}
//-----------------------------------------------------------------------------
HRESULT CDXUTXFileMesh::InvalidateDeviceObjects()
{
SAFE_RELEASE( m_pIB );
SAFE_RELEASE( m_pVB );
SAFE_RELEASE( m_pDecl );
return S_OK;
}
//-----------------------------------------------------------------------------
HRESULT CDXUTXFileMesh::Destroy()
{
InvalidateDeviceObjects();
for ( UINT i = 0; i < m_dwNumMaterials; i++ )
{
SAFE_RELEASE( m_pTextures[i] );
}
SAFE_DELETE_ARRAY( m_pTextures );
SAFE_DELETE_ARRAY( m_pMaterials );
SAFE_DELETE_ARRAY( m_strMaterials );
SAFE_RELEASE( m_pMesh );
m_dwNumMaterials = 0L;
return S_OK;
}
//-----------------------------------------------------------------------------
HRESULT CDXUTXFileMesh::Render( LPDIRECT3DDEVICE9 pd3dDevice, bool bDrawOpaqueSubsets,
bool bDrawAlphaSubsets )
{
if ( NULL == m_pMesh )
{
return E_FAIL;
}
// Frist, draw the subsets without alpha
if ( bDrawOpaqueSubsets )
{
for ( DWORD i = 0; i < m_dwNumMaterials; i++ )
{
if ( m_bUseMaterials )
{
if ( m_pMaterials[i].Diffuse.a < 1.0f )
{
continue;
}
pd3dDevice->SetMaterial( &m_pMaterials[i] );
pd3dDevice->SetTexture( 0, m_pTextures[i] );
}
m_pMesh->DrawSubset( i );
}
}
// Then, draw the subsets with alpha
if ( bDrawAlphaSubsets && m_bUseMaterials )
{
for ( DWORD i = 0; i < m_dwNumMaterials; i++ )
{
if ( m_pMaterials[i].Diffuse.a == 1.0f )
{
continue;
}
// Set the material and texture
pd3dDevice->SetMaterial( &m_pMaterials[i] );
pd3dDevice->SetTexture( 0, m_pTextures[i] );
m_pMesh->DrawSubset( i );
}
}
return S_OK;
}
//-----------------------------------------------------------------------------
HRESULT CDXUTXFileMesh::Render( ID3DXEffect* pEffect,
D3DXHANDLE hTexture,
D3DXHANDLE hDiffuse,
D3DXHANDLE hAmbient,
D3DXHANDLE hSpecular,
D3DXHANDLE hEmissive,
D3DXHANDLE hPower,
bool bDrawOpaqueSubsets,
bool bDrawAlphaSubsets )
{
if ( NULL == m_pMesh )
{
return E_FAIL;
}
UINT cPasses;
// Frist, draw the subsets without alpha
if ( bDrawOpaqueSubsets )
{
pEffect->Begin( &cPasses, 0 );
for ( UINT p = 0; p < cPasses; ++p )
{
pEffect->BeginPass( p );
for ( DWORD i = 0; i < m_dwNumMaterials; i++ )
{
if ( m_bUseMaterials )
{
if ( m_pMaterials[i].Diffuse.a < 1.0f )
{
continue;
}
if ( hTexture )
{
pEffect->SetTexture( hTexture, m_pTextures[i] );
}
// D3DCOLORVALUE and D3DXVECTOR4 are data-wise identical.
// No conversion is needed.
if ( hDiffuse )
{
pEffect->SetVector( hDiffuse, ( D3DXVECTOR4* )&m_pMaterials[i].Diffuse );
}
if ( hAmbient )
{
pEffect->SetVector( hAmbient, ( D3DXVECTOR4* )&m_pMaterials[i].Ambient );
}
if ( hSpecular )
{
pEffect->SetVector( hSpecular, ( D3DXVECTOR4* )&m_pMaterials[i].Specular );
}
if ( hEmissive )
{
pEffect->SetVector( hEmissive, ( D3DXVECTOR4* )&m_pMaterials[i].Emissive );
}
if ( hPower )
{
pEffect->SetFloat( hPower, m_pMaterials[i].Power );
}
pEffect->CommitChanges();
}
m_pMesh->DrawSubset( i );
}
pEffect->EndPass();
}
pEffect->End();
}
// Then, draw the subsets with alpha
if ( bDrawAlphaSubsets && m_bUseMaterials )
{
pEffect->Begin( &cPasses, 0 );
for ( UINT p = 0; p < cPasses; ++p )
{
pEffect->BeginPass( p );
for ( DWORD i = 0; i < m_dwNumMaterials; i++ )
{
if ( m_bUseMaterials )
{
if ( m_pMaterials[i].Diffuse.a == 1.0f )
{
continue;
}
if ( hTexture )
{
pEffect->SetTexture( hTexture, m_pTextures[i] );
}
// D3DCOLORVALUE and D3DXVECTOR4 are data-wise identical.
// No conversion is needed.
if ( hDiffuse )
{
pEffect->SetVector( hDiffuse, ( D3DXVECTOR4* )&m_pMaterials[i].Diffuse );
}
if ( hAmbient )
{
pEffect->SetVector( hAmbient, ( D3DXVECTOR4* )&m_pMaterials[i].Ambient );
}
if ( hSpecular )
{
pEffect->SetVector( hSpecular, ( D3DXVECTOR4* )&m_pMaterials[i].Specular );
}
if ( hEmissive )
{
pEffect->SetVector( hEmissive, ( D3DXVECTOR4* )&m_pMaterials[i].Emissive );
}
if ( hPower )
{
pEffect->SetFloat( hPower, m_pMaterials[i].Power );
}
pEffect->CommitChanges();
}
m_pMesh->DrawSubset( i );
}
pEffect->EndPass();
}
pEffect->End();
}
return S_OK;
}
| [
"t1238142000@gmail.com"
] | t1238142000@gmail.com |
abf3da5b7e48d5d7d2f5f90b5e2185064a193d0c | 8533db616f489c7b48446fd6a4885799012728b8 | /Projet GL/src/Map.cpp | 79e7d88b3568fa39aaa8f4d0982e2abb85d8681f | [] | no_license | hamza-abidi/ProjetGl | 515c62608189f6ff7941ea9ce64b16cdbd640fcd | 346d30e51a7152857b0053ae863086a76b5d10fd | refs/heads/master | 2021-01-20T00:53:53.387627 | 2017-04-24T07:14:07 | 2017-04-24T07:14:07 | 89,210,108 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 797 | cpp | #define window_width 40
#define window_height 21
#include <string>
#include <iostream>
#include "../include/Map.h"
#include "../include/ManageFile.h"
using namespace std ;
Map::Map(string nameMap) : Colors(){
map = nameMap ;
matrixMap = new char*[window_height];
ManageFile file(nameMap , "r");
char c ;
for (int i = 0 ; i < window_height ; i++){
matrixMap[i] = new char[window_width];
for(int j = 0 ; j < window_width ; j++){
matrixMap[i][j] = file.readChar();
}
}
}
void Map::display(){
for (int i = 0 ; i < window_height ; i++){
for(int j = 0 ; j < window_width ; j++){
switch(matrixMap[i][j]){
case 'h' : displayColor(" ",'V');break;
case 'a' : displayColor(" ",'R');break;
case 'e' : displayColor(" ",'B');break;
}
}
cout<<'\n';
}
}
| [
"hamzus14@hotmail.com"
] | hamzus14@hotmail.com |
6c36b7a97c37b5ef767c2bdbc2d158d683d6011b | ef877b90c70e8c16944b2dd6c3a4080b91246225 | /src/base/crypt/base64.cpp | cacf9551f4672253312d3fc41398104035afd99f | [] | no_license | tyxbzgc/base_dll | a4d19d8e462d5cc1fc0d6c803d23cfecb51edc01 | 399f4912137b410015c34bf68f6ce2c7f2b855f8 | refs/heads/master | 2020-04-07T15:52:28.326939 | 2018-11-21T07:03:44 | 2018-11-21T07:03:44 | 158,504,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,942 | cpp | // Copyright (c) 2017 The TAL Authors.
// All rights reserved.
#include "base/crypt/base64.h"
#include <iostream>
namespace base {
namespace crypt {
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while(in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if(i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i < 4); i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if(i) {
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
std::string base64_decode(std::string const& encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while(in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if(i == 4) {
for(i = 0; i < 4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for(i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if(i) {
for(j = i; j < 4; j++)
char_array_4[j] = 0;
for(j = 0; j < 4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for(j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
}
}
| [
"zhangguangcan@100tal.com"
] | zhangguangcan@100tal.com |
bc0cd81797b8dc2a795e560acc9b6afc2815b123 | 3e553aefc4789da0c1c93013958f2a59c3faf0f9 | /src/idcard/idcard_module.cc | 17ac6f7a3fbd2dfc49766eaab976f68e6237587e | [] | no_license | woo-henry/idcard | 76b7ef50d2a48ec180532e51231449347cc03f88 | 40435150332485202f03fae28d39ccc0ada31b54 | refs/heads/master | 2020-09-21T04:07:12.788448 | 2019-11-28T15:24:35 | 2019-11-28T15:24:35 | 224,673,438 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,384 | cc | #include <shlwapi.h>
#include <boost/algorithm/string.hpp>
#include <lib_base/lib_base.h>
#include "idcard_error.h"
#include "idcard_module.h"
//////////////////////////////////////////////////////////////////////////
IdCardModule::IdCardModule(const IdCardConfigItem* config_item)
: _module_handle(nullptr)
, _config_item(config_item)
, _bitmap_size(0)
{
ZeroMemory(_bitmap_data, MAX_BITMAP_DATA_SIZE);
}
IdCardModule::~IdCardModule()
{
Close();
if (_module_handle)
{
FreeLibrary(_module_handle);
_module_handle = nullptr;
}
}
void IdCardModule::Dispose()
{
delete this;
}
int IdCardModule::Init()
{
int result = IDCARD_ERROR_SUCCESS;
char* sdk_path = nullptr;
char* module_file = nullptr;
do
{
sdk_path = (char*)BaseMemAlloc(MAX_PATH);
if (sdk_path == nullptr)
{
result = IDCARD_ERROR_MEMORY_ALLOCATE;
break;
}
#ifdef _DEBUG
if (!BaseFsGetAppPathA(sdk_path, "..\\modules"))
#else
if (!BaseFsGetAppPathA(sdk_path, "modules"))
#endif // _DEBUG
{
result = IDCARD_ERROR_GET_APP_PATH;
break;
}
PathAddBackslashA(sdk_path);
lstrcatA(sdk_path, _config_item->GetModulePath());
if (!BaseSysSetEnvironmentVariableA("PATH", sdk_path))
{
result = IDCARD_ERROR_PATH_SET_ENVIRONMENT;
break;
}
module_file = (char*)BaseMemAlloc(MAX_PATH);
if (module_file == nullptr)
{
result = IDCARD_ERROR_MEMORY_ALLOCATE;
break;
}
if (!BaseFsGetAppPathA(module_file, _config_item->GetModuleName()))
{
result = IDCARD_ERROR_GET_APP_PATH;
break;
}
if (!boost::iends_with(module_file, ".dll"))
{
lstrcatA(module_file, ".dll");
}
_module_handle = LoadLibraryA(module_file);
if (_module_handle == nullptr)
{
result = IDCARD_ERROR_MODULE_LOAD_FAILURE;
break;
}
_pfnIdCard_Init = (IdCard_Init)GetProcAddress(_module_handle, "IdCard_Init");
if (_pfnIdCard_Init == nullptr)
{
result = IDCARD_ERROR_NULL_FUNCTION;
break;
}
_pfnIdCard_Open = (IdCard_Open)GetProcAddress(_module_handle, "IdCard_Open");
if (_pfnIdCard_Open == nullptr)
{
result = IDCARD_ERROR_NULL_FUNCTION;
break;
}
_pfnIdCard_Close = (IdCard_Close)GetProcAddress(_module_handle, "IdCard_Close");
if (_pfnIdCard_Close == nullptr)
{
result = IDCARD_ERROR_NULL_FUNCTION;
break;
}
_pfnIdCard_ReadInfo = (IdCard_ReadInfo)GetProcAddress(_module_handle, "IdCard_ReadInfo");
if (_pfnIdCard_ReadInfo == nullptr)
{
result = IDCARD_ERROR_NULL_FUNCTION;
break;
}
_pfnIdCard_Close = (IdCard_Close)GetProcAddress(_module_handle, "IdCard_Close");
if (_pfnIdCard_Close == nullptr)
{
result = IDCARD_ERROR_NULL_FUNCTION;
break;
}
_pfnIdCard_GetPeopleName = (IdCard_GetPeopleName)GetProcAddress(_module_handle, "IdCard_GetPeopleName");
if (_pfnIdCard_GetPeopleName == nullptr)
{
result = IDCARD_ERROR_NULL_FUNCTION;
break;
}
_pfnIdCard_GetPeopleSex = (IdCard_GetPeopleSex)GetProcAddress(_module_handle, "IdCard_GetPeopleSex");
if (_pfnIdCard_GetPeopleSex == nullptr)
{
result = IDCARD_ERROR_NULL_FUNCTION;
break;
}
_pfnIdCard_GetPeopleNation = (IdCard_GetPeopleNation)GetProcAddress(_module_handle, "IdCard_GetPeopleNation");
if (_pfnIdCard_GetPeopleNation == nullptr)
{
result = IDCARD_ERROR_NULL_FUNCTION;
break;
}
_pfnIdCard_GetPeopleBirthday = (IdCard_GetPeopleBirthday)GetProcAddress(_module_handle, "IdCard_GetPeopleBirthday");
if (_pfnIdCard_GetPeopleBirthday == nullptr)
{
result = IDCARD_ERROR_NULL_FUNCTION;
break;
}
_pfnIdCard_GetPeopleAddress = (IdCard_GetPeopleAddress)GetProcAddress(_module_handle, "IdCard_GetPeopleAddress");
if (_pfnIdCard_GetPeopleAddress == nullptr)
{
result = IDCARD_ERROR_NULL_FUNCTION;
break;
}
_pfnIdCard_GetPeopleIdCode = (IdCard_GetPeopleIdCode)GetProcAddress(_module_handle, "IdCard_GetPeopleIdCode");
if (_pfnIdCard_GetPeopleIdCode == nullptr)
{
result = IDCARD_ERROR_NULL_FUNCTION;
break;
}
_pfnIdCard_GetSignDepartment = (IdCard_GetSignDepartment)GetProcAddress(_module_handle, "IdCard_GetSignDepartment");
if (_pfnIdCard_GetSignDepartment == nullptr)
{
result = IDCARD_ERROR_NULL_FUNCTION;
break;
}
_pfnIdCard_GetValidStartDate = (IdCard_GetValidStartDate)GetProcAddress(_module_handle, "IdCard_GetValidStartDate");
if (_pfnIdCard_GetValidStartDate == nullptr)
{
result = IDCARD_ERROR_NULL_FUNCTION;
break;
}
_pfnIdCard_GetValidEndDate = (IdCard_GetValidEndDate)GetProcAddress(_module_handle, "IdCard_GetValidEndDate");
if (_pfnIdCard_GetValidEndDate == nullptr)
{
result = IDCARD_ERROR_NULL_FUNCTION;
break;
}
_pfnIdCard_GetBitmapData = (IdCard_GetBitmapData)GetProcAddress(_module_handle, "IdCard_GetBitmapData");
if (_pfnIdCard_GetBitmapData == nullptr)
{
result = IDCARD_ERROR_NULL_FUNCTION;
break;
}
result = _pfnIdCard_Init(_config_item->GetModulePath());
} while (false);
if (module_file)
{
BaseMemFree(module_file);
module_file = nullptr;
}
if (sdk_path)
{
BaseMemFree(sdk_path);
sdk_path = nullptr;
}
return result;
}
int IdCardModule::Open(int* port)
{
if (_pfnIdCard_Open == nullptr)
return IDCARD_ERROR_NULL_POINTER;
return _pfnIdCard_Open(port);
}
int IdCardModule::Close()
{
int result = _pfnIdCard_Close();
_people_name.clear();
_people_sex.clear();
_people_nation.clear();
_people_birthday.clear();
_people_address.clear();
_people_id_code.clear();
_sign_department.clear();
_valid_start_date.clear();
_valid_end_date.clear();
ZeroMemory(_bitmap_data, MAX_BITMAP_DATA_SIZE);
_bitmap_size = 0;
return result;
}
int IdCardModule::ReadCardInfo(bool read_photo)
{
int result = IDCARD_ERROR_SUCCESS;
unsigned char content[MAX_PATH] = { 0 };
unsigned char bitmap_data[MAX_BITMAP_DATA_SIZE] = { 0 };
int length = 0;
do
{
int ret = _pfnIdCard_ReadInfo();
if (ret != 1)
{
result = IDCARD_ERROR_READ_INFO_FAILURE;
break;
}
ZeroMemory(content, MAX_PATH);
_people_name.clear();
ret = _pfnIdCard_GetPeopleName(content, &length);
if (ret != 1)
{
result = IDCARD_ERROR_READ_PEOPLE_NAME_FAILURE;
break;
}
_people_name.assign((char*)content);
ZeroMemory(content, MAX_PATH);
_people_sex.clear();
ret = _pfnIdCard_GetPeopleSex(content, &length);
if (ret != 1)
{
result = IDCARD_ERROR_READ_PEOPLE_SEX_FAILURE;
break;
}
_people_sex.assign((char*)content);
ZeroMemory(content, MAX_PATH);
_people_nation.clear();
ret = _pfnIdCard_GetPeopleNation(content, &length);
if (ret != 1)
{
result = IDCARD_ERROR_READ_PEOPLE_NATION_FAILURE;
break;
}
_people_nation.assign((char*)content);
ZeroMemory(content, MAX_PATH);
_people_birthday.clear();
ret = _pfnIdCard_GetPeopleBirthday(content, &length);
if (ret != 1)
{
result = IDCARD_ERROR_READ_PEOPLE_BIRTHDAY_FAILURE;
break;
}
_people_birthday.assign((char*)content);
ZeroMemory(content, MAX_PATH);
_people_address.clear();
ret = _pfnIdCard_GetPeopleAddress(content, &length);
if (ret != 1)
{
result = IDCARD_ERROR_READ_PEOPLE_ADDRESS_FAILURE;
break;
}
_people_address.assign((char*)content);
ZeroMemory(content, MAX_PATH);
_people_id_code.clear();
ret = _pfnIdCard_GetPeopleIdCode(content, &length);
if (ret != 1)
{
result = IDCARD_ERROR_READ_PEOPLE_ID_CODE_FAILURE;
break;
}
_people_id_code.assign((char*)content);
ZeroMemory(content, MAX_PATH);
_sign_department.clear();
ret = _pfnIdCard_GetSignDepartment(content, &length);
if (ret != 1)
{
result = IDCARD_ERROR_READ_SIGN_DEPARTMENT_FAILURE;
break;
}
_sign_department.assign((char*)content);
ZeroMemory(content, MAX_PATH);
_valid_start_date.clear();
ret = _pfnIdCard_GetValidStartDate(content, &length);
if (ret != 1)
{
result = IDCARD_ERROR_READ_VALID_START_DATE_FAILURE;
break;
}
_valid_start_date.assign((char*)content);
ZeroMemory(content, MAX_PATH);
_valid_end_date.clear();
ret = _pfnIdCard_GetValidEndDate(content, &length);
if (ret != 1)
{
result = IDCARD_ERROR_READ_VALID_END_DATE_FAILURE;
break;
}
_valid_end_date.assign((char*)content);
if (read_photo)
{
ZeroMemory(_bitmap_data, MAX_BITMAP_DATA_SIZE);
ret = _pfnIdCard_GetBitmapData((unsigned char*)_bitmap_data, &_bitmap_size);
if (ret != 1)
{
result = IDCARD_ERROR_READ_BITMAP_DATA_FAILURE;
break;
}
}
} while (false);
return result;
}
| [
"wuky@authine.com"
] | wuky@authine.com |
b00629ffecb1e2ed1ffdf260655ba1b5dad0cf96 | 59e364a4435534b9b6663519c87c556d8c7e8772 | /include/Model/Model.hpp | 69ea630cc1326cc816c34f7d1015eef75755ed63 | [
"BSD-3-Clause"
] | permissive | xubury/OpenGLApp | 14fe253717e82434a74b268539172946746edee0 | 60d199351ec0406b372dd0aeaaea0a5b1664a327 | refs/heads/master | 2023-07-03T19:23:02.520036 | 2021-08-05T02:41:50 | 2021-08-05T02:41:50 | 356,566,696 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,525 | hpp | #ifndef MODEL_HPP
#define MODEL_HPP
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include "Core/Export.hpp"
#include "Core/ResourceManager.hpp"
#include "Graphic/Drawable.hpp"
#include "Graphic/VertexArray.hpp"
#include "Model/Mesh.hpp"
#include "Model/Bone.hpp"
namespace te {
class TE_API Model : public Drawable {
public:
Model() = default;
bool loadFromFile(const std::string &path);
void draw(const Shader &shader, const glm::mat4 &transform) const override;
const std::vector<Mesh> &getMeshes() const;
std::vector<Mesh> &getMeshes();
const std::unordered_map<std::string, BoneInfo> &getBoneInfoMap() const {
return m_boneInfoMap;
}
std::unordered_map<std::string, BoneInfo> &getBoneInfoMap() {
return m_boneInfoMap;
}
uint32_t getBoneCounter() const { return m_boneCounter; }
void setBoneCounter(uint32_t counter) { m_boneCounter = counter; }
private:
void processNode(aiNode *node, const aiScene *scene);
void processMesh(aiMesh *mesh, const aiScene *scene);
void processBoneWeight(std::vector<Vertex> &vertices, aiMesh *mesh);
void processTextures(Material &textures, aiMaterial *mat,
aiTextureType type);
std::vector<Mesh> m_meshes;
std::string m_directory;
ResourceManager<std::string, Texture> m_loadedTexture;
std::unordered_map<std::string, BoneInfo> m_boneInfoMap;
uint32_t m_boneCounter;
};
} // namespace te
#endif
| [
"xubury97@gmail.com"
] | xubury97@gmail.com |
784ca06a095dfe8780342b69da384d0d73a1d3e1 | da99aeb9e445f5886331ec934e76be010460161e | /SFML_Projekti/RectCircleCollision.h | f888d8551a7405492517b4b89cca803d7e50f73b | [] | no_license | mouliii/shooter-game-sfml | dd134ddb0fa241a7052b691d0b571b0b96409f85 | c9f80673ddf4365fcea7ff3938c9adee80f08df7 | refs/heads/master | 2022-12-13T11:32:16.507417 | 2020-04-16T10:31:20 | 2020-04-16T10:31:20 | 293,033,328 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 487 | h | #pragma once
#include <SFML/Graphics.hpp>
#include <math.h>
class CRCollision
{
public:
CRCollision(const CRCollision&) = delete;
static CRCollision& Get();
static bool CircleRectCollision(sf::CircleShape c, sf::RectangleShape r);
static bool CircleRectCollision(sf::CircleShape c, sf::IntRect r);
private:
CRCollision() {}
bool I_CircleRectCollision(sf::CircleShape c, sf::RectangleShape r);
bool I_CircleRectCollision(sf::CircleShape c, sf::IntRect r);
}; | [
"rasanen.aleksi@hotmail.com"
] | rasanen.aleksi@hotmail.com |
cdb57a21d9d00256e12471a798bf668058e3ec82 | 93fbf65a76bbeb5d8e915c14e5601ae363b3057f | /Linkedin Internship 2020 Questions/ReachTheEndInTime.cpp | 2c1d31877892585943d13777b997d955ee60cb48 | [] | no_license | sauravjaiswa/Coding-Problems | fd864a7678a961a422902eef42a29218cdd2367f | cb978f90d7dcaec75af84cba05d141fdf4f243a0 | refs/heads/master | 2023-04-14T11:34:03.138424 | 2021-03-25T17:46:47 | 2021-03-25T17:46:47 | 309,085,423 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 445 | cpp | //Linkedin Question 2
//Reach the End in Time
//https://drive.google.com/drive/u/0/folders/1WZ9bpJdM_bM8-LzLF05eQMEqAc2nkPzL
/**/
#include<bits/stdc++.h>
using namespace std;
class Graph{
public:
int n
};
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int r,c,k;
cin>>r;
c=5;
char a[r][c];
for(i=0;i<r;i++){
for(j=0;j<c;j++)
cin>>a[i][j];
}
cin>>k;
return 0;
}
| [
"41826172+sauravjaiswa@users.noreply.github.com"
] | 41826172+sauravjaiswa@users.noreply.github.com |
da09471bda2685ac464f1b8d36cc83c7b1c7b325 | 4a7fdced0b079a0bcc0b2c1875acf409cd05712d | /d08/ex00/main.cpp | 6591a50c1f8e75c851e4a3e91e6eacc634a37c2f | [] | no_license | Soul-Bruteflow/cpp_pool | a2496b3d393f73c6943ffece39d716907c8f3438 | b5cc0bfcc6070ada1bf3c3fabaaf648cbcbc6b5d | refs/heads/master | 2020-12-25T18:32:47.919440 | 2018-10-11T11:03:13 | 2018-10-11T11:03:13 | 93,961,994 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,133 | cpp | //
// Created by bruteflow on 10/11/18.
//
#include <list>
#include <vector>
#include "easyfind.hpp"
int main()
{
std::list<int> testList;
testList.push_back(1);
testList.push_back(2);
testList.push_back(3);
testList.push_back(4);
std::cout << "\nList Tests:";
std::cout << "\nExisting value found:\n";
try
{
std::cout << easyfind(testList, 1) << std::endl;
}
catch (std::logic_error &e)
{
std::cout << e.what() << std::endl;
}
std::cout << "\nValue not found:\n";
try
{
std::cout << easyfind(testList, 5) << std::endl;
}
catch (std::logic_error &e)
{
std::cout << e.what() << std::endl;
}
std::vector<int> vec;
vec.push_back(5);
vec.push_back(6);
vec.push_back(7);
vec.push_back(8);
vec.push_back(9);
std::cout << "Vector Tests:";
std::cout << "\nExisting value found:\n";
try
{
std::cout << easyfind(vec, 5) << std::endl;
}
catch (std::logic_error &e)
{
std::cout << e.what() << std::endl;
}
std::cout << "\nValue not found:\n";
try
{
std::cout << easyfind(vec, 10) << std::endl;
}
catch (std::logic_error &e)
{
std::cout << e.what() << std::endl;
}
return 0;
} | [
"Soul-Bruteflow@users.noreply.github.com"
] | Soul-Bruteflow@users.noreply.github.com |
712dcd4a80c27da6f146730012bb5fa59c4d002f | b19d0d25823bb0e6f1f7362eea610ef9f67442e0 | /external/mockturtle/mockturtle/networks/events.hpp | ada70a7a96282318b5218449205850c599a434e9 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | boschmitt/tweedledum | c0278b5f0a94ce1b14b60fe6e30be430eed92c7d | 9d3a2fab17e8531e1edc0ab927397d449b9942a4 | refs/heads/master | 2023-07-19T20:59:19.871570 | 2022-11-03T14:30:01 | 2022-11-24T00:42:05 | 140,888,411 | 92 | 34 | MIT | 2023-07-13T00:34:12 | 2018-07-13T20:03:36 | C++ | UTF-8 | C++ | false | false | 4,742 | hpp | /* mockturtle: C++ logic network library
* Copyright (C) 2018-2021 EPFL
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/*!
\file events.hpp
\brief Event API for updating a logic network.
\author Heinz Riener
\author Mathias Soeken
*/
#pragma once
#include <functional>
#include <vector>
#include "../traits.hpp"
#include <iostream>
#include <memory>
namespace mockturtle
{
/*! \brief Network events.
*
* This data structure can be returned by a network. Clients can add functions
* to network events to call code whenever an event occurs. Events are adding
* a node, modifying a node, and deleting a node.
*/
template<class Ntk>
class network_events
{
public:
using add_event_type = std::function<void( node<Ntk> const& n )>;
using modified_event_type = std::function<void( node<Ntk> const& n, std::vector<signal<Ntk>> const& previous_children )>;
using delete_event_type = std::function<void( node<Ntk> const& n )>;
public:
std::shared_ptr<add_event_type> register_add_event( add_event_type const& fn )
{
auto pfn = std::make_shared<add_event_type>( fn );
on_add.emplace_back( pfn );
return pfn;
}
std::shared_ptr<modified_event_type> register_modified_event( modified_event_type const& fn )
{
auto pfn = std::make_shared<modified_event_type>( fn );
on_modified.emplace_back( pfn );
return pfn;
}
std::shared_ptr<delete_event_type> register_delete_event( delete_event_type const& fn )
{
auto pfn = std::make_shared<delete_event_type>( fn );
on_delete.emplace_back( pfn );
return pfn;
}
void release_add_event( std::shared_ptr<add_event_type>& fn )
{
/* first decrement the reference counter of the event */
auto fn_ptr = fn.get();
fn = nullptr;
/* erase the event if the only instance remains in the vector */
on_add.erase( std::remove_if( std::begin( on_add ), std::end( on_add ),
[&]( auto&& event ){
return event.get() == fn_ptr && event.use_count() <= 1u; } ),
std::end( on_add ) );
}
void release_modified_event( std::shared_ptr<modified_event_type>& fn )
{
/* first decrement the reference counter of the event */
auto fn_ptr = fn.get();
fn = nullptr;
/* erase the event if the only instance remains in the vector */
on_modified.erase( std::remove_if( std::begin( on_modified ), std::end( on_modified ),
[&]( auto&& event ){
return event.get() == fn_ptr && event.use_count() <= 1u; } ),
std::end( on_modified ) );
}
void release_delete_event( std::shared_ptr<delete_event_type>& fn )
{
/* first decrement the reference counter of the event */
auto fn_ptr = fn.get();
fn = nullptr;
/* erase the event if the only instance remains in the vector */
on_delete.erase( std::remove_if( std::begin( on_delete ), std::end( on_delete ),
[&]( auto&& event ){
return event.get() == fn_ptr && event.use_count() <= 1u; } ),
std::end( on_delete ) );
}
public:
/*! \brief Event when node `n` is added. */
std::vector<std::shared_ptr<add_event_type>> on_add;
/*! \brief Event when `n` is modified.
*
* The event also informs about the previous children. Note that the new
* children are already available at the time the event is triggered.
*/
std::vector<std::shared_ptr<modified_event_type>> on_modified;
/*! \brief Event when `n` is deleted. */
std::vector<std::shared_ptr<delete_event_type>> on_delete;
};
} // namespace mockturtle
| [
"bruno.schmitt@epfl.ch"
] | bruno.schmitt@epfl.ch |
abfa8f8c8bfa8ba2884da6908fb36ab530cf4f00 | 8b2c2bf4ac004be628d3091d163ea3bcdf5e7f19 | /util.cpp | c5e37a44ad0fa18a287ef4d5c6258cf58cd76e4c | [] | no_license | mrdakj2/tiger2 | c411efbdbbbb2cf9b568c01b7bb4ea06f9edbdc1 | dfe66e1b849ea65ae16ae6ef7c140d8ce338d43f | refs/heads/master | 2020-11-24T09:49:07.285797 | 2018-09-27T14:17:16 | 2018-09-27T14:17:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 274 | cpp | #include "util.hpp"
using namespace util;
BoolList::BoolList(bool head, BoolList* tail)
: m_head(head), m_tail(tail)
{}
BoolList::~BoolList()
{
// delete m_tail;
}
bool BoolList::head() const
{
return m_head;
}
BoolList* BoolList::tail() const
{
return m_tail;
}
| [
"mrdakj@gmail.com"
] | mrdakj@gmail.com |
f27eef7037e1bed39cfbc58648cecaa99005b5bd | 1d9c22c19dc6fb9c0bdf0c77a3f4646f6ca64d92 | /moui/ui/android/window_android.cc | 18bd39a230341d95f5ea4386039001fb43abc877 | [
"Apache-2.0"
] | permissive | ollix/moui | 83169723903705646175860ac7f7570a2a134358 | f6f574f3b1c45c8fb8fc7b44b4783d6c91fe49f7 | refs/heads/master | 2023-04-09T06:28:34.513187 | 2023-03-28T08:35:55 | 2023-03-28T08:35:55 | 16,637,370 | 67 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 3,673 | cc | // Copyright (c) 2014 Ollix. 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.
//
// ---
// Author: olliwang@ollix.com (Olli Wang)
#include "moui/ui/window.h"
#include <map>
#include "jni.h" // NOLINT
#include "moui/core/application.h"
#include "moui/native/native_view.h"
#include "moui/ui/base_window.h"
namespace {
std::map<JNIEnv*, jobject> global_windows;
// Returns the instance of the com.ollix.moui.Window class on the Java side.
jobject GetJavaWindow(JNIEnv* env) {
auto match = global_windows.find(env);
if (match != global_windows.end()) {
return match->second;
}
jclass window_class = env->FindClass("com/ollix/moui/Window");
jmethodID window_constructor = env->GetMethodID(
window_class, "<init>", "()V");
jobject window_obj = env->NewObject(window_class, window_constructor);
jobject global_window = env->NewGlobalRef(window_obj);
env->DeleteLocalRef(window_class);
env->DeleteLocalRef(window_obj);
global_windows[env] = global_window;
return global_window;
}
} // namespace
namespace moui {
// Instantiates the JAVA OpenGLView class and sets it as the native handle.
Window::Window(void* native_handle) : BaseWindow(nullptr) {
SetNativeHandle(native_handle,
true); // releases on demand
}
Window::~Window() {
}
// Calls com.ollix.moui.Window.getMainWindow() on the Java side.
std::unique_ptr<Window> Window::GetMainWindow() {
JNIEnv* env = moui::Application::GetJNIEnv();
jobject java_window = GetJavaWindow(env);
jclass window_class = env->GetObjectClass(java_window);
jmethodID get_main_window_method = env->GetMethodID(
window_class, "getWindow",
"(Landroid/app/Activity;)Landroid/view/Window;");
jobject window = env->CallObjectMethod(java_window, get_main_window_method,
moui::Application::GetMainActivity());
void* global_ref = reinterpret_cast<void*>(env->NewGlobalRef(window));
env->DeleteLocalRef(window);
env->DeleteLocalRef(window_class);
return std::unique_ptr<Window>(new Window(global_ref));
}
// Calls com.ollix.moui.Window.getRootView() on the Java side.
std::unique_ptr<NativeView> Window::GetRootView() const {
jobject native_window = reinterpret_cast<jobject>(native_handle());
JNIEnv* env = moui::Application::GetJNIEnv();
jobject java_window = GetJavaWindow(env);
jclass window_class = env->GetObjectClass(java_window);
jmethodID get_root_view_method = env->GetMethodID(
window_class, "getRootView",
"(Landroid/app/Activity;)Landroid/view/View;");
jobject view = env->CallObjectMethod(java_window, get_root_view_method,
moui::Application::GetMainActivity());
void* global_ref = reinterpret_cast<void*>(env->NewGlobalRef(view));
env->DeleteLocalRef(view);
env->DeleteLocalRef(window_class);
return std::unique_ptr<NativeView>(new NativeView(global_ref));
}
void Window::Reset() {
for (auto& pair : global_windows) {
JNIEnv* env = Application::GetJNIEnv();
jobject global_window = pair.second;
env->DeleteGlobalRef(global_window);
}
global_windows.clear();
}
} // namespace moui
| [
"olliwang@ollix.com"
] | olliwang@ollix.com |
bd211420e3083020f7cc499bf3cb6eff0c9ee50b | 13b4773b8815e8b88873d9480b98f72eabec7f7d | /Vetor/programa que faz decrementação de 15 vetores.cpp | 1b203b543c0a255ae708b6dad53cdc04af7b5bb6 | [] | no_license | George100Neres/Logica-de-Programacao | ed9139c2d3d6515b14cc51e90792ee8b655e40cb | 69941edeb489cad5cad272d05735d22fdf6cf602 | refs/heads/main | 2023-01-05T14:31:56.772829 | 2020-10-31T02:34:42 | 2020-10-31T02:34:42 | 308,498,768 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 269 | cpp | /*Faça um programa que faça a decrementação dos 15 vetores em ordem decrescente.*/
#include<stdio.h>
main()
{
int v[15];
for (i=0; i<15; i++){
printf("Digite um numero\n:");
scanf("%i",&v[i]);
}
for (i=14; i>-1; i--){
printf("%i",v[i]);
}
system("pause");
| [
"george.neres100@gmail.com"
] | george.neres100@gmail.com |
d62e24aff716c6cfc4bc626ac27cf37e6181c910 | 34c8a500fb9377f616a1f88de13b86a949210561 | /data_structures/pointRep.h | a119138c368ec938f74731b1cbdbb4346873b7b9 | [] | no_license | rajaditya-m/dynamic-texture | 0238f1c7244c626a23ca2e1cffa626002ded60ad | b22c2831e9be5e6bc954202b7c8368c3dc9b5a7f | refs/heads/master | 2020-04-18T01:55:51.546136 | 2013-09-01T03:46:35 | 2013-09-01T03:46:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 900 | h | #ifndef __DYNAMICTEXTURES_POINTREP_H_
#define __DYNAMICTEXTURES_POINTREP_H_
#include "mat.h"
#include "vec.h"
namespace DynamicTextures
{
class PointRep
{
public:
//Constructors
PointRep()
{
point_.x = point_.y = point_.z = 0.0;
point_.w = 1.0;
normal_.x = normal_.y = normal_.z = 0.0;
texture_.x = texture_.y = 0.0;
heightField_ = 0.0;
perturbed_ = false;
textureCoodsPopulated_ = false;
}
PointRep(Angel::vec4 _p,Angel::vec3 _n)
{
point_ = _p;
normal_ = _n;
texture_.x = texture_.y = 0.0;
heightField_ = 0.0;
perturbed_ = false;
textureCoodsPopulated_ = false;
}
public:
//Point Datastructure
Angel::vec4 point_;
Angel::vec3 normal_;
//Associated Texture Maps
Angel::vec2 texture_;
//Heighfield information
double heightField_;
//Other information
bool perturbed_;
bool textureCoodsPopulated_;
};
}
#endif | [
"rajadityamukherjee.osu@outlook.com"
] | rajadityamukherjee.osu@outlook.com |
78613910758e4a4f334d039a7dee4b8f7a216149 | c254b2a95e75742de366f0121d51f33b0c2de0a2 | /projeto/Client.cpp | 255998d3cfef808f7812b7607e43d350d079ef05 | [] | no_license | rodrigodmpa/http_server_proxy | 6fa088ba38e0bda2f5f2cf7574ff43bef0b7fe98 | 94073c4943013f2039f0f96fb0e9c4f7394a5dd6 | refs/heads/master | 2020-09-09T02:18:09.158254 | 2019-12-09T15:46:00 | 2019-12-09T15:46:00 | 221,316,161 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,841 | cpp | //
// Created by Matheus Feitosa de Castro on 29/11/19.
//
#include "Client.h"
#include "Utils.h"
#include <iostream>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <sys/types.h>
#include <netdb.h>
#define PORT 8228
#define BUFFER_SIZE 1024
int Client::myMethod(char* header) {
struct sockaddr_in address;
int sock = 0, valread;
struct sockaddr_in serv_addr;
char buffer[1024] = { 0 };
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if (inet_pton(AF_INET, "www.sisu.mec.gov.br/", &serv_addr.sin_addr) <= 0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
printf("Connecting to the server\n");
if (connect(sock, (struct sockaddr*) & serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
return -1;
}
printf("Successfully connected to server\n");
char* hello = "Hello from client";
printf("Sending message: \"%s\"\n", hello);
send(sock, header, strlen(header), 0);
printf("Receiving response from server\n");
valread = read(sock, buffer, 1024); //Blocked until message is sent from the server
printf("%s\n", buffer);
printf("Press any key to exit");
getchar();
return 0;
}
int Client::socket_connect(char *host, in_port_t port){
struct hostent *hp;
struct sockaddr_in addr;
int on = 1, sock;
if((hp = gethostbyname(host)) == NULL){
std::cout << "Erro host: " << host << std::endl;
herror("gethostbyname");
exit(1);
}
bcopy(hp->h_addr, &addr.sin_addr, hp->h_length);
addr.sin_port = htons(port);
addr.sin_family = AF_INET;
sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&on, sizeof(int));
if(sock == -1){
perror("setsockopt");
exit(1);
}
if(connect(sock, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) == -1){
perror("connect");
exit(1);
}
return sock;
}
std::vector <unsigned char> Client::result(int fd, std::string request) {
unsigned char buffer;
std::vector <unsigned char> response;
write(fd, request.c_str(), request.length()); // write(fd, char[]*, len);
while(read(fd, &buffer, 1) > 0){
response.push_back(buffer);
}
return response;
}
void Client::proxy() {
int fd, fd2;
int server_fd, new_socket; long valread;
struct sockaddr_in address;
int addrlen = sizeof(address);
Client client;
Utils utils;
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("In socket");
exit(EXIT_FAILURE);
}
int enable = 1;
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
perror("setsockopt(SO_REUSEADDR) failed");
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
memset(address.sin_zero, '\0', sizeof address.sin_zero);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0)
{
perror("In bind");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 10) < 0)
{
perror("In listen");
exit(EXIT_FAILURE);
}
while(1)
{
printf("\n+++++++ Waiting for new connection ++++++++\n\n");
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0)
{
perror("In accept");
exit(EXIT_FAILURE);
}
char buffer[30000] = {0};
valread = read(new_socket , buffer, 30000);
printf("%s\n",buffer);
std::string str(buffer);
std::string url = utils.getUrl(str);
int n = url.length();
char char_array[n + 1];
strcpy(char_array, url.c_str());
std::cout << "CREATING CONNECTION" << std::endl;
fd2 = client.socket_connect(char_array, 80);
std::cout << "MAKING REQUEST" << std::endl;
std::vector<unsigned char> response = client.result(fd2, str);
unsigned char buff[response.size()];
for(size_t i = 0; i < response.size(); ++i){
buff[i] = response[i];
}
std::cout << "SENDING REQUEST" << std::endl << std::endl;
std::cout << buff << std::endl;
write(new_socket , buff , int(response.size()));
shutdown(fd2, SHUT_RDWR);
close(new_socket);
}
} | [
"matheusfk74@gmail.com"
] | matheusfk74@gmail.com |
5eff84b2049ca9877c0f9514041be88eb571c809 | 11a20ac282fedba2a9034eb7cb570f009b19e004 | /CF580-D2-B/solution.cpp | 1a12da342415c230736c47741116747460b48aab | [] | no_license | aleung27/Competitive-Programming | b10b0c62e5cafbc783c580f2e2b3693c9f30ce3c | 561a8eb0309e2852c530ea93ee0e5678cc614a7c | refs/heads/master | 2022-03-14T15:55:37.467603 | 2022-03-06T12:47:23 | 2022-03-06T12:47:23 | 252,998,658 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,670 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define X real()
#define Y imag()
#define EPS 0.000000001
#define M_PI 3.14159265358979323846
#define CROSSPROD(a, b) (conj(a)*(b)).Y
#define DOTPROD(a, b) ((a).X*(b).X + (a).Y+(b).Y)
#define FASTIO ios::sync_with_stdio(false);
int dx[] = {1, -1, 0, 0, 1, -1, 1, -1};
int dy[] = {0, 0, 1, -1, 1, -1, -1, 1};
template <class T>
T gcd(T a, T b) {
if (b == 0) return a;
return gcd(b, a%b);
}
template <class T>
T modpow(T x, T n, T m) {
if(n == 0) return 1 % m;
ll u = modpow(x, n/2, m);
u = (u*u)%m;
if(n%2 == 1) u = (u*x)%m;
return u;
}
bool comp(const pair<int, int>&a, const pair<int, int>&b) {
if(a.first == b.first) return a.second > b.second;
return a.first < b.first;
}
int main () {
int n, diff, a, b;
scanf("%d %d", &n, &diff);
vector<pair<int, int>> vals;
while(n--) {
scanf("%d %d", &a, &b);
vals.push_back({a, b});
}
sort(vals.begin(), vals.end(), comp);
int start = 0, end = 0;
ll ans = 0, sum = 0;
while(end < vals.size()) {
if(end == 0) {
while(vals[end].first-vals[start].first < diff) {
sum += vals[end].second;
end++;
if(end == vals.size()) break;
}
ans = max(ans, sum);
continue;
}
sum += vals[end].second;
while(vals[end].first-vals[start].first >= diff) {
sum -= vals[start].second;
start++;
}
ans = max(ans, sum);
end++;
}
printf("%lld\n", ans);
return 0;
}
| [
"adamjleung123@gmail.com"
] | adamjleung123@gmail.com |
cfc126dc7fd15f35248fd9009a3678bad51b9710 | 561c9f4052be06694bbc953be34ffb7de8ee3937 | /Classes/PlayerCharacter.h | f8486302b9bddfa4dba08aefc10d6ccb06f88bb5 | [] | no_license | MrMysterioos/Project_0 | ee836d1dce2d7ba5f113ac4161b9df323f52ae33 | 844c7252880d62c0f8fa434a9767048923e728cd | refs/heads/master | 2021-04-27T00:12:14.541856 | 2018-06-06T08:55:51 | 2018-06-06T08:55:51 | 120,893,659 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,349 | h | #pragma once
#include "Character.h"
USING_NS_CC;
/**
* @brief Класс объекты которого являются управляемыми игровыми персонажами.
* Единовременно может существовать только один объект этого класса ( в доработке )
*
*/
class PlayerCharacter : public Character {
public:
/*
* @brief Создать новый экземпляр класса
*
* @return Ссылку на новый экземпляр
*/
static PlayerCharacter *create();
/*
* @brief Инициализация игрового персонажа, загрузка всех его основных параметров.
*
* @arguments ObjectInfo персонажа
*/
bool init(ObjectInfo playerInfo);
/*
* @brief Отправить персонажа в указанную точку
*
* @arguments Тайловые координаты точки назначения
*/
void goTo(Vec2);
/**
* @brief Функция мгновенной остановки перемещения персонажа
*
*/
void stopMoving();
private:
enum State { idle, walk, run } _state;
PlayerCharacter();
void update(float) override;
void changeState(State);
Team _team;
std::string _name;
std::deque<std::pair<MoveTo*, int> > _way;
}; | [
"V1997V@rambler.ru"
] | V1997V@rambler.ru |
02902e4f0350ac02601d66e94552f0cb0f4c695e | 1133a26bea1f9065b3517fb748b3b7e375ccc222 | /Augustus/Augustus/Level.h | ba26ff8399be7fce303e9c1dc4a1c28a6fbaf371 | [] | no_license | Gulsnotten/prog3 | c256b369f49aae3e80149595bd499bbdaf882b3b | f1ff06c3c2ce00097b0f00344c7e6221607bdfbd | refs/heads/master | 2020-06-29T03:29:54.162060 | 2017-01-15T20:53:55 | 2017-01-15T20:53:55 | 74,453,678 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,364 | h | #pragma once
#include <vector>
#include "Tile.h"
class DrawManager;
class Sprite;
class Vect2;
class PowerUp;
class ICollideable;
class Player;
class Level
{
private:
DrawManager* m_drawManagerwPtr;
Sprite* m_pelletSprite;
Sprite* m_powerupSprite;
Sprite* m_levelSpritewPtr;
int m_pelletsCount;
void DeletePowerUps();
std::vector<std::vector<Tile*>> m_tiles;
std::vector<PowerUp*> m_powerUps;
Tile* charToTile(char c, int p_x, int p_y);
void DrawPellets(const int &p_x, const int &p_y);
void EatTile(Tile* p_tile);
int CorrectTeleportAxis(const int & p_a, const int & p_max) const;
bool IsBanned(const Vect2& p_pos, const std::vector<Vect2>& p_banned) const;
public:
Level();
~Level();
void LoadLevel();
Tile* GetTile(Vect2 p_vect2);
Tile* GetTile(int p_x, int p_y);
bool PelletCollision(Player* p_player);
bool PowerUpCollision(ICollideable* p_other);
std::vector<Vect2> AvailableDirections(const Vect2& p_pos);
std::vector<Vect2> AvailableDirections(const int& p_x, const int& p_y);
//const bool& IsIntersection(Vect2 p_pos) const;
int NextIntersection(Vect2& p_pos, const Vect2& p_dir);
int NextIntersection(Vect2& p_pos, const Vect2& p_dir, const std::vector<Vect2>& p_banned);
bool IsIntersection(int p_x, int p_y) const;
int PelletsCount() const;
void ResetAnimation();
void Update(float p_delta);
void Draw();
};
| [
"eriksall1@gmail.com"
] | eriksall1@gmail.com |
dad5651a018c7b2ce836412d5c565dcca66f26db | 7b9e626cfc3aa45ff44f79b0fb31b782a17d6c98 | /src/dynamics/shanChenForcedPostProcessor3D.h | 05b68ac32097c07df0e963883db1d00450673e39 | [] | no_license | lex16000/LBv1.2 | e95b1b42925aaa892e6099be83496a0a56271dff | cee82cc6fe75d2f9b25a9f62ce8d50d3480c47ac | refs/heads/master | 2021-04-06T01:41:48.099885 | 2018-04-04T12:01:09 | 2018-04-04T12:01:09 | 125,254,173 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,154 | h | /* This file is part of the OpenLB library
*
* Copyright (C) 2008 Orestis Malaspinas, Andrea Parmigiani, Jonas Latt
* E-mail contact: info@openlb.net
* The most recent release of OpenLB can be downloaded at
* <http://www.openlb.net/>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef SHAN_CHEN_FORCED_POST_PROCESSOR_3D_H
#define SHAN_CHEN_FORCED_POST_PROCESSOR_3D_H
#include "core/spatiallyExtendedObject3D.h"
#include "core/postProcessing.h"
#include "core/blockLattice3D.h"
namespace olb {
/**
* Multiphysics class for coupling between different lattices.
*/
// =========================================================================//
// ===========Shan Chen coupling without wall interaction===================//
// =========================================================================//
template<typename T, template<typename U> class Lattice>
class ShanChenForcedPostProcessor3D : public LocalPostProcessor3D<T,Lattice> {
public:
ShanChenForcedPostProcessor3D (
int x0_, int x1_, int y0_, int y1_, int z0_, int z1_, T G_, std::vector<T> rho0_,
AnalyticalF1D<T,T>& iP_, std::vector<SpatiallyExtendedObject3D*> partners_);
ShanChenForcedPostProcessor3D (
T G_, std::vector<T> rho0_,
AnalyticalF1D<T,T>& iP_, std::vector<SpatiallyExtendedObject3D*> partners_);
int extent() const override
{
return 1;
}
int extent(int whichDirection) const override
{
return 1;
}
void process(BlockLattice3D<T,Lattice>& blockLattice) override;
void processSubDomain(BlockLattice3D<T,Lattice>& blockLattice,
int x0_, int x1_, int y0_, int y1_, int z0_, int z1_) override;
private:
int x0, x1, y0, y1, z0, z1;
T G;
std::vector<T> rho0;
AnalyticalF1D<T,T>& interactionPotential;
std::vector<SpatiallyExtendedObject3D*> partners;
};
template<typename T, template<typename U> class Lattice>
class ShanChenForcedGenerator3D : public LatticeCouplingGenerator3D<T,Lattice> {
public:
ShanChenForcedGenerator3D(int x0_, int x1_, int y0_, int y1_, int z0_, int z1_, T G_, std::vector<T> rho0_, AnalyticalF1D<T,T>& iP_);
ShanChenForcedGenerator3D(T G_, std::vector<T> rho0_, AnalyticalF1D<T,T>& iP_);
PostProcessor3D<T,Lattice>* generate(std::vector<SpatiallyExtendedObject3D*> partners) const override;
LatticeCouplingGenerator3D<T,Lattice>* clone() const override;
private:
T G;
std::vector<T> rho0;
AnalyticalF1D<T,T>& interactionPotential;
};
}
#endif
| [
"schulz_a_alexander@hotmail.com"
] | schulz_a_alexander@hotmail.com |
70af26bb128a0b2b9584e2a9864c8f1bdf3e9eab | 6665eef4e1895b282217a70440c03df5ec64b726 | /森林保卫战/ForestVsAnimal/ForestVsAnimal/Classes/AppDelegate.cpp | 22563955d30f0d050e25c11da3600eab1a35fc67 | [] | no_license | fanleesong/CocosGameDeveloper | 87f2f1dc2e08d70592bd3b2f00dc7ee564645361 | 1bec7239e759cf934e8967900d575bdace7f80f7 | refs/heads/master | 2020-05-26T08:00:18.262596 | 2014-02-21T06:13:37 | 2014-02-21T06:13:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,532 | cpp | //
// ForestVsAnimalAppDelegate.cpp
// ForestVsAnimal
//
// Created by OldHorse on 13-12-13.
// Copyright __MyCompanyName__ 2013年. All rights reserved.
//
#include "AppDelegate.h"
#include "cocos2d.h"
#include "SimpleAudioEngine.h"
#include "Welcome.h"
USING_NS_CC;
using namespace CocosDenshion;
AppDelegate::AppDelegate()
{
}
AppDelegate::~AppDelegate()
{
}
bool AppDelegate::applicationDidFinishLaunching()
{
// initialize director
CCDirector *pDirector = CCDirector::sharedDirector();
pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
// turn on display FPS
pDirector->setDisplayStats(true);
// set FPS. the default value is 1.0/60 if you don't call this
pDirector->setAnimationInterval(1.0 / 60);
// create a scene. it's an autorelease object
CCScene *pScene =Welcome::scene();
// run
pDirector->runWithScene(pScene);
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground()
{
CCDirector::sharedDirector()->stopAnimation();
SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
SimpleAudioEngine::sharedEngine()->pauseAllEffects();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground()
{
CCDirector::sharedDirector()->startAnimation();
SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
SimpleAudioEngine::sharedEngine()->resumeAllEffects();
}
| [
"781957672@qq.com"
] | 781957672@qq.com |
e0fa346ef15319beaafd38f458ae1c0e8799173f | 1c08c04bb2e21d6c255adc71ba3f3a3bf12c2e13 | /src/modules/cpu/multipole/multipole.cpp | c156cf6005749bfd9466b3641b2c2e53773962c6 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | denkisdeng/maglua | 0e0b9faeee92b266c4b0aa8aca82dda4e8f49d58 | 48a26a7bced05ae8d840a06afc6f0b3a686133b6 | refs/heads/master | 2020-03-24T22:40:43.935202 | 2016-08-02T00:37:23 | 2016-08-02T00:37:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | cpp | #include "multipole.h"
Multipole::Multipole(const int _count)
{
count = _count;
for(int i=0; i<count; i++)
values.push_back(0);
}
void Multipole::zero()
{
for(int i=0; i<count; i++)
values[i] = 0;
}
MultipoleCartesian::MultipoleCartesian(const int l)
: Multipole((l+1)*(l+2)*(l+3)/6)
{
}
MultipoleSphericalHarmonics::MultipoleSphericalHarmonics(const int l)
: Multipole((l+1)*(l+1))
{
}
| [
"jason.mercer@gmail.com"
] | jason.mercer@gmail.com |
040c6a0318c4e880a75c38f9a26d1bfa4385701c | aecef98758f9932b6bc369e18441790f7cc01b9c | /src/main.cpp | 6874e1d977fba86eebf4eb46259180340f5fc5f1 | [] | no_license | jullyfootman/BMX055 | 44c88241ab2959c58324afd3b62d6edb2a52e42d | 87ea60d50974cee3230c50c48380f8f8cfd21013 | refs/heads/main | 2023-09-01T15:27:40.358372 | 2021-09-24T17:48:04 | 2021-09-24T17:48:04 | 342,859,913 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,351 | cpp | #include <Arduino.h>
#include <Wire.h>
//JP1,JP2,JP3 = Open
#define ADD_ACC 0x19 //加速度センサのI2Cアドレス
#define ADD_YAW 0x69 //ジャイロセンサのI2Cアドレス
#define ADD_MAG 0x13 //磁気センサのI2Cアドレス
#define SDA_pin 26
#define SCL_pin 25
#define DATA_NUM 6// 読み取りデータ数 共通
#define SAMPLING_TIME 100 //読み取り周期 ms
#define ACC_LSB 0.0098// 加速度のLSB
#define YAW_LSB 0.0038// ヨーのLSB
//加速度
float f_xAcc, f_yAcc, f_zAcc;
int16_t s16_xAcc, s16_yAcc, s16_zAcc;
//ヨー
float f_xYaw, f_yYaw, f_zYaw;
int16_t s16_xYaw, s16_yYaw, s16_zYaw;
// 磁気
int16_t xMag, yMag, zMag;
int16_t s16_xMag, s16_yMag, s16_zMag;
//補正値
float f_xAcc_comp, f_yAcc_comp, f_zAcc_comp;
float f_xYaw_comp, f_yYaw_comp, f_zYaw_comp;
int16_t s16_xMag_comp, s16_yMag_comp, s16_zMag_comp;
// レジスタへの書き込み
void setRegister(int8_t i2cAdd, int8_t regAdd, int8_t value)
{
Wire.beginTransmission(i2cAdd);
Wire.write(regAdd); // register adrress
Wire.write(value); // value
Wire.endTransmission();
delay(100);
}
void BMX055_Init()
{
setRegister(ADD_ACC, 0x0F, 0x03); // Range = +/- 2g
setRegister(ADD_ACC, 0x10, 0x08); // Bandwidth = 7.81 Hz
setRegister(ADD_ACC, 0x11, 0x00); // Normal mode, Sleep duration = 0.5ms
setRegister(ADD_YAW, 0x0F, 0x04); // Full scale = +/- 125 degree/s
setRegister(ADD_YAW, 0x10, 0x07); // ODR = 100 Hz
setRegister(ADD_YAW, 0x11, 0x00); // Normal mode, Sleep duration = 2ms
setRegister(ADD_MAG, 0x4B, 0x83); // Soft reset
setRegister(ADD_MAG, 0x4B, 0x01); // Soft reset
setRegister(ADD_MAG, 0x4C, 0x00); // Normal Mode, ODR = 10 Hz
setRegister(ADD_MAG, 0x4E, 0x84); // X, Y, Z-Axis enabled
setRegister(ADD_MAG, 0x51, 0x04); // No. of Repetitions for X-Y Axis = 9
setRegister(ADD_MAG, 0x52, 0x16); // No. of Repetitions for Z-Axis = 15
}
//=====================================================================================//
void readAcc()
{
uint8_t data[DATA_NUM];
Wire.beginTransmission(ADD_ACC);
Wire.write(0x02); // Select data register
Wire.endTransmission();
Wire.requestFrom(ADD_ACC, DATA_NUM);
if (Wire.available() == DATA_NUM)
{
for (int i = 0; i < DATA_NUM; i++)
data[i] = Wire.read();
}
uint16_t u2_temp = 0;
s16_xAcc = 0;
u2_temp = ((data[1] << 8) + data[0]) >> 4; //12bit
//負数(2の補数)処理 bitを調整して(2の補数処理されているはずなので)int16-tに直接入れる
if (u2_temp >> 11) // 先頭bitが1であれば
s16_xAcc = u2_temp | 0b1111000000000000; // 上位を1で埋める 16bitの2の補数による負数
else
s16_xAcc = u2_temp;
u2_temp = 0;
s16_yAcc = 0;
u2_temp = ((data[3] << 8) + data[2]) >> 4; //12bit
if (u2_temp >> 11)
s16_yAcc = u2_temp | 0b1111000000000000;
else
s16_yAcc = u2_temp;
u2_temp = 0;
s16_zAcc = 0;
u2_temp = ((data[5] << 8) + data[4]) >> 4; //12bit
if (u2_temp >> 11)
s16_zAcc = u2_temp | 0b1111000000000000;
else
s16_zAcc = u2_temp;
f_xAcc = s16_xAcc * ACC_LSB + f_xAcc_comp; // renge +-2g
f_yAcc = s16_yAcc * ACC_LSB + f_yAcc_comp; // renge +-2g
f_zAcc = s16_zAcc * ACC_LSB + f_zAcc_comp; // renge +-2g
}
//=====================================================================================//
void readYaw()
{
uint8_t data[DATA_NUM];
Wire.beginTransmission(ADD_YAW);
Wire.write(0x02);
Wire.endTransmission();
Wire.requestFrom(ADD_YAW, DATA_NUM);
if (Wire.available() == DATA_NUM)
{
for (int i = 0; i < DATA_NUM; i++)
data[i] = Wire.read();
}
s16_xYaw = (data[1] << 8) + data[0];//16bit
s16_yYaw = (data[3] << 8) + data[2];//16bit
s16_zYaw = (data[5] << 8) + data[4];//16bit
f_xYaw = s16_xYaw * YAW_LSB;
f_yYaw = s16_yYaw * YAW_LSB;
f_zYaw = s16_zYaw * YAW_LSB;
f_xYaw += f_xYaw_comp; //オフセット補正
f_yYaw += f_yYaw_comp; //オフセット補正
f_zYaw += f_zYaw_comp; //オフセット補正
}
//=====================================================================================//
void readMag()
{
short int data[DATA_NUM];
Wire.beginTransmission(ADD_MAG);
Wire.write(0x42); // Select data register
Wire.endTransmission();
Wire.requestFrom(ADD_MAG, DATA_NUM);
if (Wire.available() == DATA_NUM)
{
for (int i = 0; i < DATA_NUM; i++){
data[i] = Wire.read();}
}
uint16_t u2_temp = 0;
s16_xMag = 0;
u2_temp = ((data[1] << 8) + data[0]) >> 3; //13bit
if (u2_temp >> 12) // 先頭bitが1であれば
s16_xMag = u2_temp | 0b1110000000000000; // 上位を1で埋める 16bitの2の補数による負数
else
s16_xMag = u2_temp;
u2_temp = 0;
s16_yMag = 0;
u2_temp = ((data[3] << 8) + data[2]) >> 3; //13bit
if (u2_temp >> 12) // 先頭bitが1であれば
s16_yMag = u2_temp | 0b1110000000000000; // 上位を1で埋める 16bitの2の補数による負数
else
s16_yMag = u2_temp;
u2_temp = 0;
s16_zMag = 0;
u2_temp = ((data[5] << 8) + data[4]) >> 1; //15bit
if (u2_temp >> 14) // 先頭bitが1であれば
s16_zMag = u2_temp | 0b1000000000000000; // 上位を1で埋める 16bitの2の補数による負数
else
s16_zMag = u2_temp;
xMag = s16_xMag + s16_xMag_comp; //オフセット補正
yMag = s16_yMag + s16_yMag_comp; //オフセット補正
zMag = s16_zMag + s16_zMag_comp; //オフセット補正
}
void setup()
{
pinMode(SDA_pin, INPUT_PULLUP); //デフォルトのPIN21,22を使用しない場合
pinMode(SCL_pin, INPUT_PULLUP);
Wire.begin(SDA_pin, SCL_pin);
Serial.begin(9600);
BMX055_Init();
delay(300);
}
void loop()
{
//BMX055 加速度の読み取り
readAcc();
Serial.print("Acc");
Serial.print(",");
Serial.print(f_xAcc);
Serial.print(",");
Serial.print(f_yAcc);
Serial.print(",");
Serial.println(f_zAcc);
// //BMX055 ジャイロの読み取り
readYaw();
Serial.print("Yaw");
Serial.print(",");
Serial.print(f_xYaw);
Serial.print(",");
Serial.print(f_yYaw);
Serial.print(",");
Serial.println(f_zYaw);
// //BMX055 磁気の読み取り
readMag();
Serial.print("Mag");
Serial.print(",");
Serial.print(xMag);
Serial.print(",");
Serial.print(yMag);
Serial.print(",");
Serial.println(zMag);
delay(SAMPLING_TIME);
}
| [
"jully.footman@gmail.com"
] | jully.footman@gmail.com |
43cf69c325cada0132670aa959869e5e34b266f0 | 05116e5e444e80476399ae6008a9986bd4510319 | /INF684T1/src/LK.cpp | 9ed5c3aefb03952aaf82101f4d44645bbc30cd12 | [] | no_license | dsaleixo/INF684T1 | 6954f8eee101a7091d77301ccdd57094dc045e64 | 7ffd652de034842ad8c8f138863f700d626b7af8 | refs/heads/master | 2023-02-19T04:44:29.299715 | 2021-01-22T19:11:24 | 2021-01-22T19:11:24 | 315,586,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,150 | cpp | #include "LK.h"
LK::LK( int alpha, int init,int n,int aceite){
this->alpha = alpha;
this->init = init;
if(aceite == 0)this->relax=1.0;
if(aceite == 1)this->relax=1.01;
if(aceite == 2)this->relax=1.05;
if(aceite == 3)this->relax=1.1;
if(aceite == 4)this->relax=1.2;
for(int i =0 ;i<n;i++)R.push_back(false);
}
void LK::inicia(vector<Vertice> &v, Dados d){
Glns g;
Nobank b(1,0.1,1);
Solucao T(d.n_locais);
if(this->init==0){
T.FrameworkInsertionHeuristics(d,0,0.0);
g.insert(T,d,b);
}
else if (this->init==1) T.NN(d);
else g.Constroi_Random(T,d);
T.Solucao_Vector(v);
}
void LK::cortar_ciclo(vector<Vertice> &best_s,vector<Vertice> &P, int i){
for(int j=0;j<best_s.size();j++){
P.push_back(best_s[(i+j)%best_s.size()]);
}
}
double LK::Gain(vector<Vertice> &v1,vector<Vertice> &v2,Dados &d){
d.Wco_Busca(v2);
double aux1 = d.Avalia_w(v1);
double aux2 = d.Avalia_w(v2);
return aux1 - aux2;
}
void LK::vira(vector<Vertice> &P, int i){
int n = (P.size() - i)/2;
int m = P.size() -1;
for(int j=0; j<n;j++ ){
Vertice aux = P[j+i];
P[j+i]=P[m-j];
P[m-j]= aux;
}
}
bool LK::GainIsAcceptable(vector<Vertice> &v1,vector<Vertice> &v2,Dados &d){
double a1 = d.Avalia_w(v1);
double a2 = d.Avalia_w(v2);
return a1 < a2*this->relax;
}
void LK::ImprovePath(vector<Vertice> &P,int depth,Dados &d){
if(depth>=this->alpha){
double gain = -1;
vector<Vertice> T=P;
for(int i = 1; i<P.size()-1;i++){
if(this->R[P[i].v])continue;
vector<Vertice> Aux = P;
this->vira(Aux,i);
double aux = this->Gain(P,Aux,d);
if(aux>gain){
T=Aux;
gain = aux;
}
}
if(this->GainIsAcceptable(T,P,d)){
d.CO(T);
double T_c = d.Avalia(T);
double P_c = d.Avalia(P);
if(T_c < P_c){
P=T;
}
}
}
else{
for(int i = 1; i<P.size()-1;i++){
if(this->R[P[i].v])continue;
vector<Vertice> Aux = P;
this->vira(Aux,i);
d.Wco_Busca(Aux);
if(this->GainIsAcceptable(Aux,P,d)){
d.CO(Aux);
double aux_c = d.Avalia(Aux);
double P_c = d.Avalia(P);
if(aux_c>=P_c){
this->R[P[i].v] = true;
this->ImprovePath(Aux,depth +1,d);
this->R[P[i].v] = false;
}
if(aux_c<P_c){
//this->ImprovePath(Aux,depth +1,d);
P=Aux;
return;
}
}
}
}
}
void LK::rodar(Dados &d){
cout<<this->alpha<<" "<<this->relax<<endl;
vector<Vertice> best_s;
this->inicia(best_s,d);
double melhor= d.Avalia(best_s);
int i=0;
int m = d.n_locais;
cout<<"melhorou "<<melhor<<endl;
d.imprimir(best_s);
while(i<m){
vector<Vertice> P;
cortar_ciclo(best_s,P,i);
this->ImprovePath(P,1,d);
double novo = d.Avalia(P);
// cout<<novo<<endl;
if(novo-melhor<-0.0005){
melhor = novo;
best_s = P;
cout<<"melhorou "<<novo<<endl;
i=0;
}else{
i++;
}
}
d.imprimir(best_s);
}
void LK::rodar2(vector<Vertice> &best_s,Dados &d){
double melhor= d.Avalia(best_s);
int i=0;
int m = d.n_locais;
while(i<m){
vector<Vertice> P;
cortar_ciclo(best_s,P,i);
this->ImprovePath2(P,1,d);
double novo = d.Avalia(P);
// cout<<novo<<endl;
if(novo-melhor<-0.0005){
melhor = novo;
best_s = P;
return;
i=0;
}else{
i++;
}
}
}
void LK::rodar3(vector<Vertice> &best_s,Dados &d){
double melhor= d.Avalia(best_s);
int i=0;
int m = d.n_locais;
while(i<m){
vector<Vertice> P;
cortar_ciclo(best_s,P,i);
this->ImprovePath(P,1,d);
double novo = d.Avalia(P);
// cout<<novo<<endl;
if(novo-melhor<-0.0005){
melhor = novo;
best_s = P;
i=0;
}else{
i++;
}
}
}
void LK::ImprovePath2(vector<Vertice> &P,int depth,Dados &d){
double c_p = d.Avalia(P);
vector<Vertice> T=P;
double mel =0;
for(int i = 1; i<P.size()-1;i++){
if(this->R[P[i].v])continue;
vector<Vertice> Aux = P;
this->vira(Aux,i);
double aux = c_p - d.Avalia(Aux);
if(aux>mel){
T=Aux;
mel=aux;
break;
}
}
if(mel>0)P=T;
} | [
"david_leixo@hotmail.com"
] | david_leixo@hotmail.com |
eba4e4c7e252e684a215a2b64f8c8939c322fa50 | 6de29b2b837dc3790d479e1023829b36f98cc4f8 | /mh2.h | c3038afc3a6cad31ac750ae9895600043a288e83 | [] | no_license | kkholst/weibullmm | 0d40b0d50609b962db6fb8106d6be456426befc1 | eb3e608a39acb265087ec38ef66272ee77ac9bcb | refs/heads/master | 2021-01-10T08:29:38.507066 | 2015-10-24T16:17:56 | 2015-10-24T16:17:56 | 44,874,181 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 607 | h | #ifndef _MH2_H
#define _MH2_H
//#include <R.h> // Rprintf()
//#include <R_ext/Utils.h> // user interrupts
//#include <Rdefines.h>
//#include <Rinternals.h>
#include <RcppArmadillo.h>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace Rcpp;
using namespace std;
using namespace arma;
RcppExport SEXP MH(SEXP data,
SEXP cluster,
// SEXP init,
SEXP etainit,
SEXP Sigma,
SEXP modelpar,
SEXP control);
RcppExport SEXP FastApprox(const SEXP a,
const SEXP t,
const SEXP z);
#endif /* _MH2_H */
| [
"kkho@biostat.ku.dk"
] | kkho@biostat.ku.dk |
ab8fe23d8d5611e0cb5246007ba27526c1503d5b | cbd022378f8c657cef7f0d239707c0ac0b27118a | /src/eedit/econtrolmanager.h | 7b1f2493aab8dcd61c8d21c769898c5056e3126a | [] | no_license | randomcoding/PlaneShift-PSAI | 57d3c1a2accdef11d494c523f3e2e99142d213af | 06c585452abf960e0fc964fe0b7502b9bd550d1f | refs/heads/master | 2016-09-10T01:58:01.360365 | 2011-09-07T23:13:48 | 2011-09-07T23:13:48 | 2,336,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,145 | h | /*
* Copyright (C) 2003 Atomic Blue (info@planeshift.it, http://www.atomicblue.org)
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation (version 2 of the 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
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#ifndef ECONTROLMANAGER_H
#define ECONTROLMANAGER_H
#include <csutil/csstring.h>
#include <iutil/event.h>
#include <csutil/array.h>
#define CMD_DECLARATION(func) static void func(eControlManager *obj, bool down)
struct iObjectRegistry;
class eControlManager
{
public:
/** Initialise the eControlManager with an object registry. The object
* registry will be searched for the keymap files and etc.
*/
eControlManager(iObjectRegistry* object_reg);
~eControlManager();
/** Handles the given even if it is a key even.
* @event The event to handle.
* @return True if the event has been handled, false otherwise.
*/
bool HandleEvent(iEvent &event);
/** Imports key mappings from the given files. Note that this adds to the
* current mappings.
* @filename Name of the file with the mappings to import.
* @return Returns true upon successfully loading the file, false
* otherwises.
*/
bool LoadKeyMap(const char* filename);
/** Removes all current key mappings
*/
void ClearKeyMap();
// Actions
CMD_DECLARATION( HandleForward );
CMD_DECLARATION( HandleBackward );
CMD_DECLARATION( HandleRotateLeft );
CMD_DECLARATION( HandleRotateRight );
CMD_DECLARATION( HandleLookUp );
CMD_DECLARATION( HandleLookDown );
private:
/** Executes the command mapped to the given key, if one exists.
* @key A csKeyEveentData structure describing the key.
*/
void ExecuteKeyCommand(csKeyEventData &key);
/** Adds a mapping between the given action and key to the keymap.
* @action Name of the action.
* @data csKeyEventData describing the key.
*/
void Map(const char *action, csKeyEventData &data);
/** Finds the index of the action with the given name in the keyMap array.
* @name Name of the action to search for.
* @return Returns the index of the action or -1 if not found.
*/
size_t StringToAction(const char *name);
// Holds the map between a key and its action.
struct ActionKeyMap
{
csString action; // Action name
csKeyEventData csKey; // Key
};
// An array of mappings between keys and actions
csArray<ActionKeyMap*> keyMap;
iObjectRegistry* object_reg;
};
#endif
| [
"whacko88@2752fbe2-5038-0410-9d0a-88578062bcef"
] | whacko88@2752fbe2-5038-0410-9d0a-88578062bcef |
826db180c5f04dec53442f5c5c2ef479a526a136 | ba225468ef163528ea48b091b5d5e3255ff888cb | /ToolCode/SortHeaderCtrl.h | f2cdbdae51b995eceb9e8e3e1c2173ce462fd041 | [] | no_license | presscad/ToolKits-1 | aef98bfbce74cfe999a6faa1da83502685366cc3 | 29c38e692d04a78ab5d31c28d9602cfb1a5db1b5 | refs/heads/master | 2021-02-15T20:00:57.339658 | 2020-03-04T08:12:02 | 2020-03-04T08:12:02 | 244,927,268 | 0 | 1 | null | 2020-03-04T14:52:44 | 2020-03-04T14:52:44 | null | GB18030 | C++ | false | false | 1,620 | h | #ifndef SORTHEADERCTRL_H
#define SORTHEADERCTRL_H
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CSortHeaderCtrl : public CHeaderCtrl
{
// Construction
public:
int m_R;
int m_G;
int m_B;
int m_Gradient; // 画立体背景,渐变系数
double m_heightCoef; //表头高度,这是倍数,
int m_fontHeight; //字体高度
int m_fontWidth; //字体宽度
COLORREF m_colorText;
CStringArray m_titleArr;
CString m_alignmentFormat; //表示对齐类型的整型数组,0表示左对齐,1表示中间对齐,2表示右对齐
BOOL m_bEnableSort;
BOOL m_bCustomDrawTitle;
public:
CSortHeaderCtrl();
// Attributes
public:
// Operations
public:
int GetCurrSortColumn(){return m_iSortColumn;}
BOOL IsSortCurrColAscending(){return m_bSortAscending;}
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CSortHeaderCtrl)
public:
virtual void Serialize(CArchive& ar);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CSortHeaderCtrl();
void SetSortArrow( const int iColumn, const BOOL bAscending );
// Generated message map functions
protected:
afx_msg void OnPaint();
void DrawItem( LPDRAWITEMSTRUCT lpDrawItemStruct );
LRESULT OnLayout( WPARAM wParam, LPARAM lParam );
int m_iSortColumn;
BOOL m_bSortAscending;
//{{AFX_MSG(CSortHeaderCtrl)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // SORTHEADERCTRL_H
| [
"wjzhwht@hotmail.com"
] | wjzhwht@hotmail.com |
9719b3b565f6a29a2cd82fef79bd26b6f6d4a758 | 57ad4cc874b18ec29e2ecd1917c88f2a551b9a88 | /CAN_com/arduino/libraries/arduino-library-nine-axes-motion-master/examples/Accelerometer/Accelerometer.ino | 824b33837bb8c555243472eb2c8adf3dd9d4a337 | [] | no_license | jeffykim/NJITSolarCarUI | fe12fe3ad70983a5842bf850e7b1e72b886e1fa4 | 5e81bae500f4948e9de29d6bbdbd30c558388bdf | refs/heads/master | 2018-12-26T23:43:43.573244 | 2018-10-22T21:23:28 | 2018-10-22T21:23:28 | 107,796,200 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 6,297 | ino | /****************************************************************************
* Copyright (C) 2011 - 2014 Bosch Sensortec GmbH
*
* Accelerometer.ino
* Date: 2014/09/09
* Revision: 3.0 $
*
* Usage: Example code to stream Accelerometer data
*
****************************************************************************
/***************************************************************************
* License:
*
* 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 the
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL COPYRIGHT 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
*
* The information provided is believed to be accurate and reliable.
* The copyright holder assumes no responsibility for the consequences of use
* of such information nor for any infringement of patents or
* other rights of third parties which may result from its use.
* No license is granted by implication or otherwise under any patent or
* patent rights of the copyright holder.
*/
#include "NineAxesMotion.h" //Contains the bridge code between the API and the Arduino Environment
#include <Wire.h>
NineAxesMotion mySensor; //Object that for the sensor
unsigned long lastStreamTime = 0; //To store the last streamed time stamp
const int streamPeriod = 40; //To stream at 25Hz without using additional timers (time period(ms) =1000/frequency(Hz))
bool updateSensorData = true; //Flag to update the sensor data. Default is true to perform the first read before the first stream
void setup() //This code is executed once
{
//Peripheral Initialization
Serial.begin(115200); //Initialize the Serial Port to view information on the Serial Monitor
I2C.begin(); //Initialize I2C communication to the let the library communicate with the sensor.
//Sensor Initialization
mySensor.initSensor(); //The I2C Address can be changed here inside this function in the library
mySensor.setOperationMode(OPERATION_MODE_NDOF); //Can be configured to other operation modes as desired
mySensor.setUpdateMode(MANUAL); //The default is AUTO. Changing to manual requires calling the relevant update functions prior to calling the read functions
//Setting to MANUAL requires lesser reads to the sensor
mySensor.updateAccelConfig();
updateSensorData = true;
Serial.println();
Serial.println("Default accelerometer configuration settings...");
Serial.print("Range: ");
Serial.println(mySensor.readAccelRange());
Serial.print("Bandwidth: ");
Serial.println(mySensor.readAccelBandwidth());
Serial.print("Power Mode: ");
Serial.println(mySensor.readAccelPowerMode());
Serial.println("Streaming in ..."); //Countdown
Serial.print("3...");
delay(1000); //Wait for a second
Serial.print("2...");
delay(1000); //Wait for a second
Serial.println("1...");
delay(1000); //Wait for a second
}
void loop() //This code is looped forever
{
if (updateSensorData) //Keep the updating of data as a separate task
{
mySensor.updateAccel(); //Update the Accelerometer data
mySensor.updateLinearAccel(); //Update the Linear Acceleration data
mySensor.updateGravAccel(); //Update the Gravity Acceleration data
mySensor.updateCalibStatus(); //Update the Calibration Status
updateSensorData = false;
}
if ((millis() - lastStreamTime) >= streamPeriod)
{
lastStreamTime = millis();
Serial.print("Time: ");
Serial.print(lastStreamTime);
Serial.print("ms ");
Serial.print(" aX: ");
Serial.print(mySensor.readAccelerometer(X_AXIS)); //Accelerometer X-Axis data
Serial.print("m/s2 ");
Serial.print(" aY: ");
Serial.print(mySensor.readAccelerometer(Y_AXIS)); //Accelerometer Y-Axis data
Serial.print("m/s2 ");
Serial.print(" aZ: ");
Serial.print(mySensor.readAccelerometer(Z_AXIS)); //Accelerometer Z-Axis data
Serial.print("m/s2 ");
Serial.print(" lX: ");
Serial.print(mySensor.readLinearAcceleration(X_AXIS)); //Linear Acceleration X-Axis data
Serial.print("m/s2 ");
Serial.print(" lY: ");
Serial.print(mySensor.readLinearAcceleration(Y_AXIS)); //Linear Acceleration Y-Axis data
Serial.print("m/s2 ");
Serial.print(" lZ: ");
Serial.print(mySensor.readLinearAcceleration(Z_AXIS)); //Linear Acceleration Z-Axis data
Serial.print("m/s2 ");
Serial.print(" gX: ");
Serial.print(mySensor.readGravAcceleration(X_AXIS)); //Gravity Acceleration X-Axis data
Serial.print("m/s2 ");
Serial.print(" gY: ");
Serial.print(mySensor.readGravAcceleration(Y_AXIS)); //Gravity Acceleration Y-Axis data
Serial.print("m/s2 ");
Serial.print(" gZ: ");
Serial.print(mySensor.readGravAcceleration(Z_AXIS)); //Gravity Acceleration Z-Axis data
Serial.print("m/s2 ");
Serial.print(" C: ");
Serial.print(mySensor.readAccelCalibStatus()); //Accelerometer Calibration Status (0 - 3)
Serial.println();
updateSensorData = true;
}
}
| [
"bduemmer1@gmail.com"
] | bduemmer1@gmail.com |
bbfc9f116d892b2242f7e537cc2d229335fc3eba | c0c6ccd59375199358c7cb423387306c7b19d78f | /serial/src/impl/unix.cc | 0b7ab42c26f9886ddd8991489491e64d3ba389ec | [
"BSD-3-Clause",
"MIT"
] | permissive | UbiquityRobotics/ubiquity_motor | a731fbe0cd648913c7a77407425d593490833b60 | 489912c28e47ed9d2044d041cbfb52dc49d425a0 | refs/heads/noetic-devel | 2023-08-03T03:04:05.519173 | 2022-03-21T13:09:18 | 2022-03-21T13:09:18 | 30,818,606 | 19 | 26 | BSD-3-Clause | 2022-03-21T13:09:20 | 2015-02-15T05:15:03 | C++ | UTF-8 | C++ | false | false | 25,930 | cc | /* Copyright 2012 William Woodall and John Harrison
*
* Additional Contributors: Christopher Baker @bakercp
*/
#if !defined(_WIN32)
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/signal.h>
#include <errno.h>
#include <paths.h>
#include <sysexits.h>
#include <termios.h>
#include <sys/param.h>
#include <pthread.h>
#if defined(__linux__)
# include <linux/serial.h>
#endif
#include <sys/select.h>
#include <sys/time.h>
#include <time.h>
#ifdef __MACH__
#include <AvailabilityMacros.h>
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#include "serial/impl/unix.h"
#ifndef TIOCINQ
#ifdef FIONREAD
#define TIOCINQ FIONREAD
#else
#define TIOCINQ 0x541B
#endif
#endif
#if defined(MAC_OS_X_VERSION_10_3) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3)
#include <IOKit/serial/ioss.h>
#endif
using std::string;
using std::stringstream;
using std::invalid_argument;
using serial::MillisecondTimer;
using serial::Serial;
using serial::SerialException;
using serial::PortNotOpenedException;
using serial::IOException;
MillisecondTimer::MillisecondTimer (const uint32_t millis)
: expiry(timespec_now())
{
int64_t tv_nsec = expiry.tv_nsec + (millis * 1e6);
if (tv_nsec >= 1e9) {
int64_t sec_diff = tv_nsec / static_cast<int> (1e9);
expiry.tv_nsec = tv_nsec - static_cast<int> (1e9 * sec_diff);
expiry.tv_sec += sec_diff;
} else {
expiry.tv_nsec = tv_nsec;
}
}
int64_t
MillisecondTimer::remaining ()
{
timespec now(timespec_now());
int64_t millis = (expiry.tv_sec - now.tv_sec) * 1e3;
millis += (expiry.tv_nsec - now.tv_nsec) / 1e6;
return millis;
}
timespec
MillisecondTimer::timespec_now ()
{
timespec time;
# ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
time.tv_sec = mts.tv_sec;
time.tv_nsec = mts.tv_nsec;
# else
clock_gettime(CLOCK_REALTIME, &time);
# endif
return time;
}
timespec
timespec_from_ms (const uint32_t millis)
{
timespec time;
time.tv_sec = millis / 1e3;
time.tv_nsec = (millis - (time.tv_sec * 1e3)) * 1e6;
return time;
}
Serial::SerialImpl::SerialImpl (const string &port, unsigned long baudrate,
bytesize_t bytesize,
parity_t parity, stopbits_t stopbits,
flowcontrol_t flowcontrol)
: port_ (port), fd_ (-1), is_open_ (false), xonxoff_ (false), rtscts_ (false),
baudrate_ (baudrate), parity_ (parity),
bytesize_ (bytesize), stopbits_ (stopbits), flowcontrol_ (flowcontrol)
{
pthread_mutex_init(&this->read_mutex, NULL);
pthread_mutex_init(&this->write_mutex, NULL);
if (port_.empty () == false)
open ();
}
Serial::SerialImpl::~SerialImpl ()
{
close();
pthread_mutex_destroy(&this->read_mutex);
pthread_mutex_destroy(&this->write_mutex);
}
void
Serial::SerialImpl::open ()
{
if (port_.empty ()) {
throw invalid_argument ("Empty port is invalid.");
}
if (is_open_ == true) {
throw SerialException ("Serial port already open.");
}
fd_ = ::open (port_.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd_ == -1) {
switch (errno) {
case EINTR:
// Recurse because this is a recoverable error.
open ();
return;
case ENFILE:
case EMFILE:
THROW (IOException, "Too many file handles open.");
default:
THROW (IOException, errno);
}
}
reconfigurePort();
is_open_ = true;
}
void
Serial::SerialImpl::reconfigurePort ()
{
if (fd_ == -1) {
// Can only operate on a valid file descriptor
THROW (IOException, "Invalid file descriptor, is the serial port open?");
}
struct termios options; // The options for the file descriptor
if (tcgetattr(fd_, &options) == -1) {
THROW (IOException, "::tcgetattr");
}
// set up raw mode / no echo / binary
options.c_cflag |= (tcflag_t) (CLOCAL | CREAD);
options.c_lflag &= (tcflag_t) ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL |
ISIG | IEXTEN); //|ECHOPRT
options.c_oflag &= (tcflag_t) ~(OPOST);
options.c_iflag &= (tcflag_t) ~(INLCR | IGNCR | ICRNL | IGNBRK);
#ifdef IUCLC
options.c_iflag &= (tcflag_t) ~IUCLC;
#endif
#ifdef PARMRK
options.c_iflag &= (tcflag_t) ~PARMRK;
#endif
// setup baud rate
bool custom_baud = false;
speed_t baud;
switch (baudrate_) {
#ifdef B0
case 0: baud = B0; break;
#endif
#ifdef B50
case 50: baud = B50; break;
#endif
#ifdef B75
case 75: baud = B75; break;
#endif
#ifdef B110
case 110: baud = B110; break;
#endif
#ifdef B134
case 134: baud = B134; break;
#endif
#ifdef B150
case 150: baud = B150; break;
#endif
#ifdef B200
case 200: baud = B200; break;
#endif
#ifdef B300
case 300: baud = B300; break;
#endif
#ifdef B600
case 600: baud = B600; break;
#endif
#ifdef B1200
case 1200: baud = B1200; break;
#endif
#ifdef B1800
case 1800: baud = B1800; break;
#endif
#ifdef B2400
case 2400: baud = B2400; break;
#endif
#ifdef B4800
case 4800: baud = B4800; break;
#endif
#ifdef B7200
case 7200: baud = B7200; break;
#endif
#ifdef B9600
case 9600: baud = B9600; break;
#endif
#ifdef B14400
case 14400: baud = B14400; break;
#endif
#ifdef B19200
case 19200: baud = B19200; break;
#endif
#ifdef B28800
case 28800: baud = B28800; break;
#endif
#ifdef B57600
case 57600: baud = B57600; break;
#endif
#ifdef B76800
case 76800: baud = B76800; break;
#endif
#ifdef B38400
case 38400: baud = B38400; break;
#endif
#ifdef B115200
case 115200: baud = B115200; break;
#endif
#ifdef B128000
case 128000: baud = B128000; break;
#endif
#ifdef B153600
case 153600: baud = B153600; break;
#endif
#ifdef B230400
case 230400: baud = B230400; break;
#endif
#ifdef B256000
case 256000: baud = B256000; break;
#endif
#ifdef B460800
case 460800: baud = B460800; break;
#endif
#ifdef B576000
case 576000: baud = B576000; break;
#endif
#ifdef B921600
case 921600: baud = B921600; break;
#endif
#ifdef B1000000
case 1000000: baud = B1000000; break;
#endif
#ifdef B1152000
case 1152000: baud = B1152000; break;
#endif
#ifdef B1500000
case 1500000: baud = B1500000; break;
#endif
#ifdef B2000000
case 2000000: baud = B2000000; break;
#endif
#ifdef B2500000
case 2500000: baud = B2500000; break;
#endif
#ifdef B3000000
case 3000000: baud = B3000000; break;
#endif
#ifdef B3500000
case 3500000: baud = B3500000; break;
#endif
#ifdef B4000000
case 4000000: baud = B4000000; break;
#endif
default:
custom_baud = true;
// OS X support
#if defined(MAC_OS_X_VERSION_10_4) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_4)
// Starting with Tiger, the IOSSIOSPEED ioctl can be used to set arbitrary baud rates
// other than those specified by POSIX. The driver for the underlying serial hardware
// ultimately determines which baud rates can be used. This ioctl sets both the input
// and output speed.
speed_t new_baud = static_cast<speed_t> (baudrate_);
if (-1 == ioctl (fd_, IOSSIOSPEED, &new_baud, 1)) {
THROW (IOException, errno);
}
// Linux Support
#elif defined(__linux__) && defined (TIOCSSERIAL)
struct serial_struct ser;
if (-1 == ioctl (fd_, TIOCGSERIAL, &ser)) {
THROW (IOException, errno);
}
// set custom divisor
ser.custom_divisor = ser.baud_base / static_cast<int> (baudrate_);
// update flags
ser.flags &= ~ASYNC_SPD_MASK;
ser.flags |= ASYNC_SPD_CUST;
if (-1 == ioctl (fd_, TIOCSSERIAL, &ser)) {
THROW (IOException, errno);
}
#else
throw invalid_argument ("OS does not currently support custom bauds");
#endif
}
if (custom_baud == false) {
#ifdef _BSD_SOURCE
::cfsetspeed(&options, baud);
#else
::cfsetispeed(&options, baud);
::cfsetospeed(&options, baud);
#endif
}
// setup char len
options.c_cflag &= (tcflag_t) ~CSIZE;
if (bytesize_ == eightbits)
options.c_cflag |= CS8;
else if (bytesize_ == sevenbits)
options.c_cflag |= CS7;
else if (bytesize_ == sixbits)
options.c_cflag |= CS6;
else if (bytesize_ == fivebits)
options.c_cflag |= CS5;
else
throw invalid_argument ("invalid char len");
// setup stopbits
if (stopbits_ == stopbits_one)
options.c_cflag &= (tcflag_t) ~(CSTOPB);
else if (stopbits_ == stopbits_one_point_five)
// ONE POINT FIVE same as TWO.. there is no POSIX support for 1.5
options.c_cflag |= (CSTOPB);
else if (stopbits_ == stopbits_two)
options.c_cflag |= (CSTOPB);
else
throw invalid_argument ("invalid stop bit");
// setup parity
options.c_iflag &= (tcflag_t) ~(INPCK | ISTRIP);
if (parity_ == parity_none) {
options.c_cflag &= (tcflag_t) ~(PARENB | PARODD);
} else if (parity_ == parity_even) {
options.c_cflag &= (tcflag_t) ~(PARODD);
options.c_cflag |= (PARENB);
} else if (parity_ == parity_odd) {
options.c_cflag |= (PARENB | PARODD);
}
#ifdef CMSPAR
else if (parity_ == parity_mark) {
options.c_cflag |= (PARENB | CMSPAR | PARODD);
}
else if (parity_ == parity_space) {
options.c_cflag |= (PARENB | CMSPAR);
options.c_cflag &= (tcflag_t) ~(PARODD);
}
#else
// CMSPAR is not defined on OSX. So do not support mark or space parity.
else if (parity_ == parity_mark || parity_ == parity_space) {
throw invalid_argument ("OS does not support mark or space parity");
}
#endif // ifdef CMSPAR
else {
throw invalid_argument ("invalid parity");
}
// setup flow control
if (flowcontrol_ == flowcontrol_none) {
xonxoff_ = false;
rtscts_ = false;
}
if (flowcontrol_ == flowcontrol_software) {
xonxoff_ = true;
rtscts_ = false;
}
if (flowcontrol_ == flowcontrol_hardware) {
xonxoff_ = false;
rtscts_ = true;
}
// xonxoff
#ifdef IXANY
if (xonxoff_)
options.c_iflag |= (IXON | IXOFF); //|IXANY)
else
options.c_iflag &= (tcflag_t) ~(IXON | IXOFF | IXANY);
#else
if (xonxoff_)
options.c_iflag |= (IXON | IXOFF);
else
options.c_iflag &= (tcflag_t) ~(IXON | IXOFF);
#endif
// rtscts
#ifdef CRTSCTS
if (rtscts_)
options.c_cflag |= (CRTSCTS);
else
options.c_cflag &= (unsigned long) ~(CRTSCTS);
#elif defined CNEW_RTSCTS
if (rtscts_)
options.c_cflag |= (CNEW_RTSCTS);
else
options.c_cflag &= (unsigned long) ~(CNEW_RTSCTS);
#else
#error "OS Support seems wrong."
#endif
// http://www.unixwiz.net/techtips/termios-vmin-vtime.html
// this basically sets the read call up to be a polling read,
// but we are using select to ensure there is data available
// to read before each call, so we should never needlessly poll
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 0;
// activate settings
::tcsetattr (fd_, TCSANOW, &options);
// Update byte_time_ based on the new settings.
uint32_t bit_time_ns = 1e9 / baudrate_;
byte_time_ns_ = bit_time_ns * (1 + bytesize_ + parity_ + stopbits_);
// Compensate for the stopbits_one_point_five enum being equal to int 3,
// and not 1.5.
if (stopbits_ == stopbits_one_point_five) {
byte_time_ns_ += ((1.5 - stopbits_one_point_five) * bit_time_ns);
}
}
void
Serial::SerialImpl::close ()
{
if (is_open_ == true) {
if (fd_ != -1) {
int ret;
ret = ::close (fd_);
if (ret == 0) {
fd_ = -1;
} else {
THROW (IOException, errno);
}
}
is_open_ = false;
}
}
bool
Serial::SerialImpl::isOpen () const
{
return is_open_;
}
size_t
Serial::SerialImpl::available ()
{
if (!is_open_) {
return 0;
}
int count = 0;
if (-1 == ioctl (fd_, TIOCINQ, &count)) {
THROW (IOException, errno);
} else {
return static_cast<size_t> (count);
}
}
bool
Serial::SerialImpl::waitReadable (uint32_t timeout)
{
// Setup a select call to block for serial data or a timeout
fd_set readfds;
FD_ZERO (&readfds);
FD_SET (fd_, &readfds);
timespec timeout_ts (timespec_from_ms (timeout));
int r = pselect (fd_ + 1, &readfds, NULL, NULL, &timeout_ts, NULL);
if (r < 0) {
// Select was interrupted
if (errno == EINTR) {
return false;
}
// Otherwise there was some error
THROW (IOException, errno);
}
// Timeout occurred
if (r == 0) {
return false;
}
// This shouldn't happen, if r > 0 our fd has to be in the list!
if (!FD_ISSET (fd_, &readfds)) {
THROW (IOException, "select reports ready to read, but our fd isn't"
" in the list, this shouldn't happen!");
}
// Data available to read.
return true;
}
void
Serial::SerialImpl::waitByteTimes (size_t count)
{
timespec wait_time = { 0, static_cast<long>(byte_time_ns_ * count)};
pselect (0, NULL, NULL, NULL, &wait_time, NULL);
}
size_t
Serial::SerialImpl::read (uint8_t *buf, size_t size)
{
// If the port is not open, throw
if (!is_open_) {
throw PortNotOpenedException ("Serial::read");
}
size_t bytes_read = 0;
// Calculate total timeout in milliseconds t_c + (t_m * N)
long total_timeout_ms = timeout_.read_timeout_constant;
total_timeout_ms += timeout_.read_timeout_multiplier * static_cast<long> (size);
MillisecondTimer total_timeout(total_timeout_ms);
// Pre-fill buffer with available bytes
{
ssize_t bytes_read_now = ::read (fd_, buf, size);
if (bytes_read_now > 0) {
bytes_read = bytes_read_now;
}
}
while (bytes_read < size) {
int64_t timeout_remaining_ms = total_timeout.remaining();
if (timeout_remaining_ms <= 0) {
// Timed out
break;
}
// Timeout for the next select is whichever is less of the remaining
// total read timeout and the inter-byte timeout.
uint32_t timeout = std::min(static_cast<uint32_t> (timeout_remaining_ms),
timeout_.inter_byte_timeout);
// Wait for the device to be readable, and then attempt to read.
if (waitReadable(timeout)) {
// If it's a fixed-length multi-byte read, insert a wait here so that
// we can attempt to grab the whole thing in a single IO call. Skip
// this wait if a non-max inter_byte_timeout is specified.
if (size > 1 && timeout_.inter_byte_timeout == Timeout::max()) {
size_t bytes_available = available();
if (bytes_available + bytes_read < size) {
waitByteTimes(size - (bytes_available + bytes_read));
}
}
// This should be non-blocking returning only what is available now
// Then returning so that select can block again.
ssize_t bytes_read_now =
::read (fd_, buf + bytes_read, size - bytes_read);
// read should always return some data as select reported it was
// ready to read when we get to this point.
if (bytes_read_now < 1) {
// Disconnected devices, at least on Linux, show the
// behavior that they are always ready to read immediately
// but reading returns nothing.
throw SerialException ("device reports readiness to read but "
"returned no data (device disconnected?)");
}
// Update bytes_read
bytes_read += static_cast<size_t> (bytes_read_now);
// If bytes_read == size then we have read everything we need
if (bytes_read == size) {
break;
}
// If bytes_read < size then we have more to read
if (bytes_read < size) {
continue;
}
// If bytes_read > size then we have over read, which shouldn't happen
if (bytes_read > size) {
throw SerialException ("read over read, too many bytes where "
"read, this shouldn't happen, might be "
"a logical error!");
}
}
}
return bytes_read;
}
size_t
Serial::SerialImpl::write (const uint8_t *data, size_t length)
{
if (is_open_ == false) {
throw PortNotOpenedException ("Serial::write");
}
fd_set writefds;
size_t bytes_written = 0;
// Calculate total timeout in milliseconds t_c + (t_m * N)
long total_timeout_ms = timeout_.write_timeout_constant;
total_timeout_ms += timeout_.write_timeout_multiplier * static_cast<long> (length);
MillisecondTimer total_timeout(total_timeout_ms);
while (bytes_written < length) {
int64_t timeout_remaining_ms = total_timeout.remaining();
if (timeout_remaining_ms <= 0) {
// Timed out
break;
}
timespec timeout(timespec_from_ms(timeout_remaining_ms));
FD_ZERO (&writefds);
FD_SET (fd_, &writefds);
// Do the select
int r = pselect (fd_ + 1, NULL, &writefds, NULL, &timeout, NULL);
// Figure out what happened by looking at select's response 'r'
/** Error **/
if (r < 0) {
// Select was interrupted, try again
if (errno == EINTR) {
continue;
}
// Otherwise there was some error
THROW (IOException, errno);
}
/** Timeout **/
if (r == 0) {
break;
}
/** Port ready to write **/
if (r > 0) {
// Make sure our file descriptor is in the ready to write list
if (FD_ISSET (fd_, &writefds)) {
// This will write some
ssize_t bytes_written_now =
::write (fd_, data + bytes_written, length - bytes_written);
// write should always return some data as select reported it was
// ready to write when we get to this point.
if (bytes_written_now < 1) {
// Disconnected devices, at least on Linux, show the
// behavior that they are always ready to write immediately
// but writing returns nothing.
throw SerialException ("device reports readiness to write but "
"returned no data (device disconnected?)");
}
// Update bytes_written
bytes_written += static_cast<size_t> (bytes_written_now);
// If bytes_written == size then we have written everything we need to
if (bytes_written == length) {
break;
}
// If bytes_written < size then we have more to write
if (bytes_written < length) {
continue;
}
// If bytes_written > size then we have over written, which shouldn't happen
if (bytes_written > length) {
throw SerialException ("write over wrote, too many bytes where "
"written, this shouldn't happen, might be "
"a logical error!");
}
}
// This shouldn't happen, if r > 0 our fd has to be in the list!
THROW (IOException, "select reports ready to write, but our fd isn't"
" in the list, this shouldn't happen!");
}
}
return bytes_written;
}
void
Serial::SerialImpl::setPort (const string &port)
{
port_ = port;
}
string
Serial::SerialImpl::getPort () const
{
return port_;
}
void
Serial::SerialImpl::setTimeout (serial::Timeout &timeout)
{
timeout_ = timeout;
}
serial::Timeout
Serial::SerialImpl::getTimeout () const
{
return timeout_;
}
void
Serial::SerialImpl::setBaudrate (unsigned long baudrate)
{
baudrate_ = baudrate;
if (is_open_)
reconfigurePort ();
}
unsigned long
Serial::SerialImpl::getBaudrate () const
{
return baudrate_;
}
void
Serial::SerialImpl::setBytesize (serial::bytesize_t bytesize)
{
bytesize_ = bytesize;
if (is_open_)
reconfigurePort ();
}
serial::bytesize_t
Serial::SerialImpl::getBytesize () const
{
return bytesize_;
}
void
Serial::SerialImpl::setParity (serial::parity_t parity)
{
parity_ = parity;
if (is_open_)
reconfigurePort ();
}
serial::parity_t
Serial::SerialImpl::getParity () const
{
return parity_;
}
void
Serial::SerialImpl::setStopbits (serial::stopbits_t stopbits)
{
stopbits_ = stopbits;
if (is_open_)
reconfigurePort ();
}
serial::stopbits_t
Serial::SerialImpl::getStopbits () const
{
return stopbits_;
}
void
Serial::SerialImpl::setFlowcontrol (serial::flowcontrol_t flowcontrol)
{
flowcontrol_ = flowcontrol;
if (is_open_)
reconfigurePort ();
}
serial::flowcontrol_t
Serial::SerialImpl::getFlowcontrol () const
{
return flowcontrol_;
}
void
Serial::SerialImpl::flush ()
{
if (is_open_ == false) {
throw PortNotOpenedException ("Serial::flush");
}
tcdrain (fd_);
}
void
Serial::SerialImpl::flushInput ()
{
if (is_open_ == false) {
throw PortNotOpenedException ("Serial::flushInput");
}
tcflush (fd_, TCIFLUSH);
}
void
Serial::SerialImpl::flushOutput ()
{
if (is_open_ == false) {
throw PortNotOpenedException ("Serial::flushOutput");
}
tcflush (fd_, TCOFLUSH);
}
void
Serial::SerialImpl::sendBreak (int duration)
{
if (is_open_ == false) {
throw PortNotOpenedException ("Serial::sendBreak");
}
tcsendbreak (fd_, static_cast<int> (duration / 4));
}
void
Serial::SerialImpl::setBreak (bool level)
{
if (is_open_ == false) {
throw PortNotOpenedException ("Serial::setBreak");
}
if (level) {
if (-1 == ioctl (fd_, TIOCSBRK))
{
stringstream ss;
ss << "setBreak failed on a call to ioctl(TIOCSBRK): " << errno << " " << strerror(errno);
throw(SerialException(ss.str().c_str()));
}
} else {
if (-1 == ioctl (fd_, TIOCCBRK))
{
stringstream ss;
ss << "setBreak failed on a call to ioctl(TIOCCBRK): " << errno << " " << strerror(errno);
throw(SerialException(ss.str().c_str()));
}
}
}
void
Serial::SerialImpl::setRTS (bool level)
{
if (is_open_ == false) {
throw PortNotOpenedException ("Serial::setRTS");
}
int command = TIOCM_RTS;
if (level) {
if (-1 == ioctl (fd_, TIOCMBIS, &command))
{
stringstream ss;
ss << "setRTS failed on a call to ioctl(TIOCMBIS): " << errno << " " << strerror(errno);
throw(SerialException(ss.str().c_str()));
}
} else {
if (-1 == ioctl (fd_, TIOCMBIC, &command))
{
stringstream ss;
ss << "setRTS failed on a call to ioctl(TIOCMBIC): " << errno << " " << strerror(errno);
throw(SerialException(ss.str().c_str()));
}
}
}
void
Serial::SerialImpl::setDTR (bool level)
{
if (is_open_ == false) {
throw PortNotOpenedException ("Serial::setDTR");
}
int command = TIOCM_DTR;
if (level) {
if (-1 == ioctl (fd_, TIOCMBIS, &command))
{
stringstream ss;
ss << "setDTR failed on a call to ioctl(TIOCMBIS): " << errno << " " << strerror(errno);
throw(SerialException(ss.str().c_str()));
}
} else {
if (-1 == ioctl (fd_, TIOCMBIC, &command))
{
stringstream ss;
ss << "setDTR failed on a call to ioctl(TIOCMBIC): " << errno << " " << strerror(errno);
throw(SerialException(ss.str().c_str()));
}
}
}
bool
Serial::SerialImpl::waitForChange ()
{
#ifndef TIOCMIWAIT
while (is_open_ == true) {
int status;
if (-1 == ioctl (fd_, TIOCMGET, &status))
{
stringstream ss;
ss << "waitForChange failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno);
throw(SerialException(ss.str().c_str()));
}
else
{
if (0 != (status & TIOCM_CTS)
|| 0 != (status & TIOCM_DSR)
|| 0 != (status & TIOCM_RI)
|| 0 != (status & TIOCM_CD))
{
return true;
}
}
usleep(1000);
}
return false;
#else
int command = (TIOCM_CD|TIOCM_DSR|TIOCM_RI|TIOCM_CTS);
if (-1 == ioctl (fd_, TIOCMIWAIT, &command)) {
stringstream ss;
ss << "waitForDSR failed on a call to ioctl(TIOCMIWAIT): "
<< errno << " " << strerror(errno);
throw(SerialException(ss.str().c_str()));
}
return true;
#endif
}
bool
Serial::SerialImpl::getCTS ()
{
if (is_open_ == false) {
throw PortNotOpenedException ("Serial::getCTS");
}
int status;
if (-1 == ioctl (fd_, TIOCMGET, &status))
{
stringstream ss;
ss << "getCTS failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno);
throw(SerialException(ss.str().c_str()));
}
else
{
return 0 != (status & TIOCM_CTS);
}
}
bool
Serial::SerialImpl::getDSR ()
{
if (is_open_ == false) {
throw PortNotOpenedException ("Serial::getDSR");
}
int status;
if (-1 == ioctl (fd_, TIOCMGET, &status))
{
stringstream ss;
ss << "getDSR failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno);
throw(SerialException(ss.str().c_str()));
}
else
{
return 0 != (status & TIOCM_DSR);
}
}
bool
Serial::SerialImpl::getRI ()
{
if (is_open_ == false) {
throw PortNotOpenedException ("Serial::getRI");
}
int status;
if (-1 == ioctl (fd_, TIOCMGET, &status))
{
stringstream ss;
ss << "getRI failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno);
throw(SerialException(ss.str().c_str()));
}
else
{
return 0 != (status & TIOCM_RI);
}
}
bool
Serial::SerialImpl::getCD ()
{
if (is_open_ == false) {
throw PortNotOpenedException ("Serial::getCD");
}
int status;
if (-1 == ioctl (fd_, TIOCMGET, &status))
{
stringstream ss;
ss << "getCD failed on a call to ioctl(TIOCMGET): " << errno << " " << strerror(errno);
throw(SerialException(ss.str().c_str()));
}
else
{
return 0 != (status & TIOCM_CD);
}
}
void
Serial::SerialImpl::readLock ()
{
int result = pthread_mutex_lock(&this->read_mutex);
if (result) {
THROW (IOException, result);
}
}
void
Serial::SerialImpl::readUnlock ()
{
int result = pthread_mutex_unlock(&this->read_mutex);
if (result) {
THROW (IOException, result);
}
}
void
Serial::SerialImpl::writeLock ()
{
int result = pthread_mutex_lock(&this->write_mutex);
if (result) {
THROW (IOException, result);
}
}
void
Serial::SerialImpl::writeUnlock ()
{
int result = pthread_mutex_unlock(&this->write_mutex);
if (result) {
THROW (IOException, result);
}
}
#endif // !defined(_WIN32)
| [
"send2arohan@gmail.com"
] | send2arohan@gmail.com |
cb538daa86b0b8918ff5688c5881bae34afd9512 | abf6824b5a2af7ef07bdddf1b70d34d6f1bec92b | /Le80RemoveDuplicatesFromSortedArrayII/Le80RemoveDuplicatesFromSortedArrayII/main.cpp | 384a1c0ead19b9d67228fdc41b0b83d12823229f | [] | no_license | zhouyu0615/MyLeetCode | f9442e51ce7995d51e66ee03deb70e9e29070c7d | 39b7e30d728e84649618ac9948164f90ac49bd00 | refs/heads/master | 2021-01-17T07:52:06.224984 | 2016-08-29T06:00:28 | 2016-08-29T06:00:28 | 47,877,402 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 747 | cpp | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
vector<int>::iterator pIter;
if (nums.size()<=1)
{
return nums.size();
}
int numCount = 0;
for (pIter = nums.begin()+1; pIter != nums.end();)
{
numCount++;
if (*pIter!=*(pIter-1))
{
numCount = 0;
++pIter;
}
else
{
if (numCount>=2)
{
pIter=nums.erase(pIter);
}
else
{
++pIter;
}
}
}
return nums.size();
}
};
int main()
{
vector<int> Nums = { 1, 1, 1, 2, 2, 3, 3, 3, 3 };
Solution testCase;
testCase.removeDuplicates(Nums);
for each (int var in Nums)
{
cout << var << " ";
}
cout << endl;
getchar();
return 0;
}
| [
"871211719@qq.com"
] | 871211719@qq.com |
71afa63d05131976004bde6ed59894536acf9103 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/65/ecb13b11f222e9/main.cpp | 104ea9cca44f30381ee701a2b2d411c99db7f8be | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,831 | cpp | #include <boost/graph/adjacency_list.hpp>
#include <boost/graph/iteration_macros.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/filtered_graph.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/iteration_macros.hpp>
#include <boost/graph/mcgregor_common_subgraphs.hpp>
#include <boost/property_map/shared_array_property_map.hpp>
#include <sstream>
#include <iterator>
#include <list>
#include <iostream>
typedef boost::adjacency_list<boost::setS, boost::vecS, boost::bidirectionalS,
boost::property<boost::vertex_name_t, std::string> > graph_type;
template <typename GraphFirst, typename GraphSecond>
struct print_callback {
print_callback(const GraphFirst& graph1, const GraphSecond& graph2) :
m_graph1(graph1), m_graph2(graph2) { }
template <typename CorrespondenceMapFirstToSecond, typename CorrespondenceMapSecondToFirst>
bool operator()(CorrespondenceMapFirstToSecond correspondence_map_1_to_2,
CorrespondenceMapSecondToFirst correspondence_map_2_to_1,
typename boost::graph_traits<GraphFirst>::vertices_size_type subgraph_size)
{
#if 0
auto name1 = boost::get(boost::vertex_name_t(), m_graph1);
auto name2 = boost::get(boost::vertex_name_t(), m_graph2);
BGL_FORALL_VERTICES_T(it, m_graph1, GraphFirst) { std::cout << name1[it] << "; "; }
std::cout << "\n";
print_edges(m_graph1, name1);
BGL_FORALL_VERTICES_T(it, m_graph2, GraphFirst) { std::cout << name2[it] << "; "; }
std::cout << "\n";
print_edges(m_graph2, name2);
#endif
// Print out correspondences between vertices
BGL_FORALL_VERTICES_T(vertex1, m_graph1, GraphFirst) {
// Skip unmapped vertices
if (get(correspondence_map_1_to_2, vertex1) != boost::graph_traits<GraphSecond>::null_vertex()) {
std::cout << vertex1 << " <-> " << get(correspondence_map_1_to_2, vertex1) << std::endl;
}
}
std::cout << "---" << std::endl;
return (true);
}
private:
const GraphFirst& m_graph1;
const GraphSecond& m_graph2;
};
graph_type dataset1() {
graph_type g;
auto node0 = add_vertex(std::string(""), g);
auto node1 = add_vertex(std::string("PlayerMoveStop::Create"), g);
auto node2 = add_vertex(std::string(""), g);
auto node3 = add_vertex(std::string(""), g);
auto node4 = add_vertex(std::string("PlayerMoveStartBackward::Create"), g);
auto node5 = add_vertex(std::string(""), g);
auto node6 = add_vertex(std::string(""), g);
auto node7 = add_vertex(std::string(""), g);
add_edge(node0, node6, g);
add_edge(node0, node7, g);
add_edge(node1, node5, g);
add_edge(node1, node7, g);
add_edge(node2, node4, g);
add_edge(node2, node5, g);
add_edge(node2, node6, g);
add_edge(node3, node4, g);
return g;
}
graph_type dataset2() {
graph_type g;
auto node0 = add_vertex(std::string("PlayerMoveStop::Create"), g);
auto node1 = add_vertex(std::string("PlayerMoveStop::Create"), g);
auto node2 = add_vertex(std::string("MoveFallLand_Destruct"), g);
auto node3 = add_vertex(std::string("PlayerMoveStop::Destroy"), g);
auto node4 = add_vertex(std::string("PlayerMoveStartBackward::Destroy"), g);
auto node5 = add_vertex(std::string("PlayerMoveStartBackward::Create"), g);
auto node6 = add_vertex(std::string("PlayerMoveHeartbeat::Destroy"), g);
auto node7 = add_vertex(std::string("PlayerMoveFallLand::CliPut"), g);
auto node8 = add_vertex(std::string("PlayerMoveStartForward::CliPut"), g);
add_edge(node0, node6, g);
add_edge(node0, node8, g);
add_edge(node1, node5, g);
add_edge(node1, node7, g);
add_edge(node2, node4, g);
add_edge(node2, node7, g);
add_edge(node2, node8, g);
add_edge(node3, node4, g);
add_edge(node3, node5, g);
add_edge(node3, node6, g);
return g;
}
graph_type dataset3() {
graph_type g;
auto node2 = add_vertex(std::string("zzzzz"), g);
auto node3 = add_vertex(std::string(""), g);
auto node4 = add_vertex(std::string("PlayerMoveStartBackward::Create"), g);
auto node5 = add_vertex(std::string(""), g);
auto node6 = add_vertex(std::string("eeeee"), g);
auto node7 = add_vertex(std::string("fffff"), g);
auto node0 = add_vertex(std::string(""), g);
auto node1 = add_vertex(std::string("PlayerMoveStop::Create"), g);
add_edge(node0, node6, g);
add_edge(node0, node7, g);
add_edge(node1, node5, g);
add_edge(node1, node7, g);
add_edge(node2, node4, g);
add_edge(node2, node5, g);
add_edge(node2, node6, g);
add_edge(node3, node4, g);
return g;
}
int main() {
using namespace boost;
// Create two graphs and put into them some vertex with property:
graph_type
g1 = dataset1(),
g2 = dataset3(); // dataset2();
// Create property_map:
typedef property_map<graph_type, vertex_name_t>::type NameMap;
NameMap name1 = boost::get(vertex_name_t(), g1);
NameMap name2 = boost::get(vertex_name_t(), g2);
print_callback<graph_type, graph_type> callback(g1, g2);
// And call algorithm:
mcgregor_common_subgraphs_unique(
g1, g2,
true,
callback,
vertices_equivalent(make_property_map_equivalent(name1, name2)));
}
| [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
4de97a57896ba6be2c0d8e0203a057eb9170c606 | 8bed40f56d1c390d4a8321597a3932a12999bc9d | /D3DHeplerFunction.h | b7d6c7c8817cbf38c80d0a961ba91d500e749546 | [] | no_license | stir001/DXR | b62aea5df7aeee8a5b03b9a3bccd10f32a54bb3a | 217fbfe24e680fe7b1d5e90ff036d7f267a09337 | refs/heads/master | 2020-08-10T09:29:37.179009 | 2019-12-18T05:03:17 | 2019-12-18T05:03:17 | 214,316,447 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 337 | h | #pragma once
#include "Comptr.h"
struct ID3D12GraphicsCommandList4;
struct ID3D12Resource;
enum D3D12_RESOURCE_STATES : int;
namespace d3d_helper_function
{
void TlansitoinBarrier(const MWCptr<ID3D12GraphicsCommandList4>& cmdList, const MWCptr<ID3D12Resource> resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after);
};
| [
"jba.baske.ichiro@gmail.com"
] | jba.baske.ichiro@gmail.com |
8df81cb8b83b00c020895716dd101dd088728353 | a7053519b6f4b1b6e998dc821b644dd57abc6320 | /UVA/UVa488 (2).cpp | 779e7f2d0daf607f6b9ec1079009ba8bf54ea357 | [] | no_license | Koios1143/Algorithm-Code-Saved | 97c7360e1928bbea12307524a8562b3f1c72d89d | 38706e0c08750ebdd0384534baa3226f850fb8b7 | refs/heads/master | 2023-02-08T00:33:56.881228 | 2020-12-12T05:09:16 | 2020-12-12T05:09:16 | 297,377,067 | 0 | 0 | null | null | null | null | BIG5 | C++ | false | false | 543 | cpp | //By Koios1143
#include<iostream>
using namespace std;
int t,f,a;
bool out=false;
int main(){
cin>>t;
while(t--){
if(out)
cout<<"\n";
else
out=true;
cin>>a>>f;
for(int i=0 ; i<f ; i++){
if(i!=0)
cout<<"\n";
// 上大三角
for(int j=1 ; j<=a ; j++){
for(int k=1 ; k<=j ; k++){
cout<<j;
}
cout<<'\n';
}
// 下小三角
for(int j=a-1,l=0 ; j>=1 ; j--, l++){
for(int k=a-1-l ; k>0 ; k--){
cout<<j;
}
cout<<"\n";
}
}
}
return 0;
}
| [
"ken1357924681010@gmail.com"
] | ken1357924681010@gmail.com |
f1ff84f531414fb08e43edc9ba2754b46983bf84 | 2e116f48b0c51ca440ef1c6c5fba5c8b16f108f2 | /Plugins/VRExpansionPlugin/VRExpansionPlugin/Intermediate/Build/Win64/UE4Editor/Inc/VRExpansionPlugin/VRExpansionPlugin.init.gen.cpp | 99361e4de90df0d944bf9e440a1b3cd922257195 | [
"MIT"
] | permissive | erebuswolf/mordentral-4.22-8-27-2019 | e240c983a29953aaf04e932514484e7f7328249f | 9cdc22717bfe4c932be2eac50cfe0170d8514096 | refs/heads/master | 2020-07-12T14:37:59.765313 | 2019-08-29T21:54:35 | 2019-08-29T21:54:35 | 204,841,616 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,553 | cpp | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeVRExpansionPlugin_init() {}
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VRVirtualStockModeChangedSignature__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VRGripControllerOnTrackingEventSignature__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VRGripControllerOnGripSignature__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VRGripControllerOnDropSignature__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VRGripControllerOnGripOutOfRange__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VRGripControllerOnProfileTransformChanged__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_DynamicBucketUpdateTickSignature__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VRLerpToHandFinishedSignature__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VROnMeleeIsLodged__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VRButtonStateChangedSignature__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VRButtonStartedInteractionSignature__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VRDialStateChangedSignature__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VRDialFinishedLerpingSignature__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VRLeverStateChangedSignature__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VRLeverFinishedLerpingSignature__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VRSliderHitPointSignature__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VRSliderFinishedLerpingSignature__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VROnPerformClimbingStepUp__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VRSeatThresholdChangedSignature__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VRPlayerStateReplicatedSignature__DelegateSignature();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UDelegateFunction_VRExpansionPlugin_VRGestureDetectedSignature__DelegateSignature();
UPackage* Z_Construct_UPackage__Script_VRExpansionPlugin()
{
static UPackage* ReturnPackage = nullptr;
if (!ReturnPackage)
{
static UObject* (*const SingletonFuncArray[])() = {
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VRVirtualStockModeChangedSignature__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VRGripControllerOnTrackingEventSignature__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VRGripControllerOnGripSignature__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VRGripControllerOnDropSignature__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VRGripControllerOnGripOutOfRange__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VRGripControllerOnProfileTransformChanged__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_DynamicBucketUpdateTickSignature__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VRLerpToHandFinishedSignature__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VROnMeleeIsLodged__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VRButtonStateChangedSignature__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VRButtonStartedInteractionSignature__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VRDialStateChangedSignature__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VRDialFinishedLerpingSignature__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VRLeverStateChangedSignature__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VRLeverFinishedLerpingSignature__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VRSliderHitPointSignature__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VRSliderFinishedLerpingSignature__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VROnPerformClimbingStepUp__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VRSeatThresholdChangedSignature__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VRPlayerStateReplicatedSignature__DelegateSignature,
(UObject* (*)())Z_Construct_UDelegateFunction_VRExpansionPlugin_VRGestureDetectedSignature__DelegateSignature,
};
static const UE4CodeGen_Private::FPackageParams PackageParams = {
"/Script/VRExpansionPlugin",
SingletonFuncArray,
ARRAY_COUNT(SingletonFuncArray),
PKG_CompiledIn | 0x00000000,
0x3AD3FE1B,
0x69E66A4C,
METADATA_PARAMS(nullptr, 0)
};
UE4CodeGen_Private::ConstructUPackage(ReturnPackage, PackageParams);
}
return ReturnPackage;
}
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| [
"jesfish@gmail.com"
] | jesfish@gmail.com |
d2e55f04509bf36fc53aed433d5d365e9b86d75d | 1a17167c38dc9a12c1f72dd0f3ae7288f5cd7da0 | /Source/ThirdParty/angle/src/libANGLE/renderer/vulkan/SamplerVk.h | 955763894ad581ab0797538afee56de8c6553c1b | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"Zlib",
"LicenseRef-scancode-khronos",
"BSL-1.0",
"BSD-2-Clause"
] | permissive | elix22/Urho3D | c57c7ecb58975f51fabb95bcc4330bc5b0812de7 | 99902ae2a867be0d6dbe4c575f9c8c318805ec64 | refs/heads/master | 2023-06-01T01:19:57.155566 | 2021-12-07T16:47:20 | 2021-12-07T17:46:58 | 165,504,739 | 21 | 4 | MIT | 2021-11-05T01:02:08 | 2019-01-13T12:51:17 | C++ | UTF-8 | C++ | false | false | 1,054 | h | //
// Copyright 2016 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// SamplerVk.h:
// Defines the class interface for SamplerVk, implementing SamplerImpl.
//
#ifndef LIBANGLE_RENDERER_VULKAN_SAMPLERVK_H_
#define LIBANGLE_RENDERER_VULKAN_SAMPLERVK_H_
#include "libANGLE/renderer/SamplerImpl.h"
#include "libANGLE/renderer/vulkan/ContextVk.h"
#include "libANGLE/renderer/vulkan/vk_helpers.h"
namespace rx
{
class SamplerVk : public SamplerImpl
{
public:
SamplerVk(const gl::SamplerState &state);
~SamplerVk() override;
void onDestroy(const gl::Context *context) override;
angle::Result syncState(const gl::Context *context, const bool dirty) override;
const vk::Sampler &getSampler() const;
Serial getSerial() const { return mSerial; }
private:
vk::Sampler mSampler;
// The serial is used for cache indexing.
Serial mSerial;
};
} // namespace rx
#endif // LIBANGLE_RENDERER_VULKAN_SAMPLERVK_H_
| [
"elix22@gmail.com"
] | elix22@gmail.com |
b561ad66536455cfb4b139f6171bbcd8e1708443 | 7e48d392300fbc123396c6a517dfe8ed1ea7179f | /RodentVR/Intermediate/Build/Win64/RodentVR/Inc/UMG/WidgetSwitcherSlot.generated.h | 6e31aecb4982c3f581a2a45f5b666bce861ac835 | [] | no_license | WestRyanK/Rodent-VR | f4920071b716df6a006b15c132bc72d3b0cba002 | 2033946f197a07b8c851b9a5075f0cb276033af6 | refs/heads/master | 2021-06-14T18:33:22.141793 | 2020-10-27T03:25:33 | 2020-10-27T03:25:33 | 154,956,842 | 1 | 1 | null | 2018-11-29T09:56:21 | 2018-10-27T11:23:11 | C++ | UTF-8 | C++ | false | false | 5,204 | h | // Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/ObjectMacros.h"
#include "UObject/ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
struct FMargin;
#ifdef UMG_WidgetSwitcherSlot_generated_h
#error "WidgetSwitcherSlot.generated.h already included, missing '#pragma once' in WidgetSwitcherSlot.h"
#endif
#define UMG_WidgetSwitcherSlot_generated_h
#define Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_SPARSE_DATA
#define Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_RPC_WRAPPERS \
\
DECLARE_FUNCTION(execSetVerticalAlignment); \
DECLARE_FUNCTION(execSetHorizontalAlignment); \
DECLARE_FUNCTION(execSetPadding);
#define Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_RPC_WRAPPERS_NO_PURE_DECLS \
\
DECLARE_FUNCTION(execSetVerticalAlignment); \
DECLARE_FUNCTION(execSetHorizontalAlignment); \
DECLARE_FUNCTION(execSetPadding);
#define Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesUWidgetSwitcherSlot(); \
friend struct Z_Construct_UClass_UWidgetSwitcherSlot_Statics; \
public: \
DECLARE_CLASS(UWidgetSwitcherSlot, UPanelSlot, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/UMG"), NO_API) \
DECLARE_SERIALIZER(UWidgetSwitcherSlot)
#define Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_INCLASS \
private: \
static void StaticRegisterNativesUWidgetSwitcherSlot(); \
friend struct Z_Construct_UClass_UWidgetSwitcherSlot_Statics; \
public: \
DECLARE_CLASS(UWidgetSwitcherSlot, UPanelSlot, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/UMG"), NO_API) \
DECLARE_SERIALIZER(UWidgetSwitcherSlot)
#define Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API UWidgetSwitcherSlot(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UWidgetSwitcherSlot) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UWidgetSwitcherSlot); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UWidgetSwitcherSlot); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API UWidgetSwitcherSlot(UWidgetSwitcherSlot&&); \
NO_API UWidgetSwitcherSlot(const UWidgetSwitcherSlot&); \
public:
#define Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_ENHANCED_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API UWidgetSwitcherSlot(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API UWidgetSwitcherSlot(UWidgetSwitcherSlot&&); \
NO_API UWidgetSwitcherSlot(const UWidgetSwitcherSlot&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UWidgetSwitcherSlot); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UWidgetSwitcherSlot); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UWidgetSwitcherSlot)
#define Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_PRIVATE_PROPERTY_OFFSET
#define Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_17_PROLOG
#define Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_PRIVATE_PROPERTY_OFFSET \
Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_SPARSE_DATA \
Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_RPC_WRAPPERS \
Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_INCLASS \
Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_PRIVATE_PROPERTY_OFFSET \
Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_SPARSE_DATA \
Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_RPC_WRAPPERS_NO_PURE_DECLS \
Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_INCLASS_NO_PURE_DECLS \
Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h_20_ENHANCED_CONSTRUCTORS \
static_assert(false, "Unknown access specifier for GENERATED_BODY() macro in class WidgetSwitcherSlot."); \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
template<> UMG_API UClass* StaticClass<class UWidgetSwitcherSlot>();
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID Engine_Source_Runtime_UMG_Public_Components_WidgetSwitcherSlot_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
| [
"west.ryan.k@gmail.com"
] | west.ryan.k@gmail.com |
d2d01620b75e0fedf72d9b4680d032847748bc82 | 7bb34b9837b6304ceac6ab45ce482b570526ed3c | /external/webkit/Source/WebKit2/PluginProcess/PluginProcess.cpp | 30504a291d5a2dfc3d940210718aa34f15f7ddc2 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.1-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft"
] | permissive | ghsecuritylab/android_platform_sony_nicki | 7533bca5c13d32a8d2a42696344cc10249bd2fd8 | 526381be7808e5202d7865aa10303cb5d249388a | refs/heads/master | 2021-02-28T20:27:31.390188 | 2013-10-15T07:57:51 | 2013-10-15T07:57:51 | 245,730,217 | 0 | 0 | Apache-2.0 | 2020-03-08T00:59:27 | 2020-03-08T00:59:26 | null | UTF-8 | C++ | false | false | 6,512 | cpp | /*
* Copyright (C) 2010 Apple 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:
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "PluginProcess.h"
#if ENABLE(PLUGIN_PROCESS)
#include "ArgumentCoders.h"
#include "NetscapePluginModule.h"
#include "PluginProcessProxyMessages.h"
#include "PluginProcessCreationParameters.h"
#include "WebProcessConnection.h"
#if PLATFORM(MAC)
#include "MachPort.h"
#endif
namespace WebKit {
static const double shutdownTimeout = 15.0;
PluginProcess& PluginProcess::shared()
{
DEFINE_STATIC_LOCAL(PluginProcess, pluginProcess, ());
return pluginProcess;
}
PluginProcess::PluginProcess()
: ChildProcess(shutdownTimeout)
#if PLATFORM(MAC)
, m_compositingRenderServerPort(MACH_PORT_NULL)
#endif
{
}
PluginProcess::~PluginProcess()
{
}
void PluginProcess::initialize(CoreIPC::Connection::Identifier serverIdentifier, RunLoop* runLoop)
{
ASSERT(!m_connection);
m_connection = CoreIPC::Connection::createClientConnection(serverIdentifier, this, runLoop);
m_connection->setDidCloseOnConnectionWorkQueueCallback(didCloseOnConnectionWorkQueue);
m_connection->open();
}
void PluginProcess::removeWebProcessConnection(WebProcessConnection* webProcessConnection)
{
size_t vectorIndex = m_webProcessConnections.find(webProcessConnection);
ASSERT(vectorIndex != notFound);
m_webProcessConnections.remove(vectorIndex);
if (m_webProcessConnections.isEmpty() && m_pluginModule) {
// Decrement the load count. This is balanced by a call to incrementLoadCount in createWebProcessConnection.
m_pluginModule->decrementLoadCount();
}
enableTermination();
}
NetscapePluginModule* PluginProcess::netscapePluginModule()
{
if (!m_pluginModule) {
ASSERT(!m_pluginPath.isNull());
m_pluginModule = NetscapePluginModule::getOrCreate(m_pluginPath);
#if PLATFORM(MAC)
if (m_pluginModule) {
if (m_pluginModule->pluginQuirks().contains(PluginQuirks::PrognameShouldBeWebKitPluginHost))
setprogname("WebKitPluginHost");
}
#endif
}
return m_pluginModule.get();
}
bool PluginProcess::shouldTerminate()
{
ASSERT(m_webProcessConnections.isEmpty());
return true;
}
void PluginProcess::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments)
{
didReceivePluginProcessMessage(connection, messageID, arguments);
}
void PluginProcess::didClose(CoreIPC::Connection*)
{
// The UI process has crashed, just go ahead and quit.
// FIXME: If the plug-in is spinning in the main loop, we'll never get this message.
RunLoop::current()->stop();
}
void PluginProcess::didReceiveInvalidMessage(CoreIPC::Connection*, CoreIPC::MessageID)
{
}
void PluginProcess::syncMessageSendTimedOut(CoreIPC::Connection*)
{
}
void PluginProcess::initializePluginProcess(const PluginProcessCreationParameters& parameters)
{
ASSERT(!m_pluginModule);
m_pluginPath = parameters.pluginPath;
platformInitialize(parameters);
}
void PluginProcess::createWebProcessConnection()
{
bool didHaveAnyWebProcessConnections = !m_webProcessConnections.isEmpty();
#if PLATFORM(MAC)
// Create the listening port.
mach_port_t listeningPort;
mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &listeningPort);
// Create a listening connection.
RefPtr<WebProcessConnection> connection = WebProcessConnection::create(listeningPort);
m_webProcessConnections.append(connection.release());
CoreIPC::MachPort clientPort(listeningPort, MACH_MSG_TYPE_MAKE_SEND);
m_connection->send(Messages::PluginProcessProxy::DidCreateWebProcessConnection(clientPort), 0);
#else
// FIXME: Implement.
ASSERT_NOT_REACHED();
#endif
if (NetscapePluginModule* module = netscapePluginModule()) {
if (!didHaveAnyWebProcessConnections) {
// Increment the load count. This is matched by a call to decrementLoadCount in removeWebProcessConnection.
// We do this so that the plug-in module's NP_Shutdown won't be called until right before exiting.
module->incrementLoadCount();
}
}
disableTermination();
}
void PluginProcess::getSitesWithData(uint64_t callbackID)
{
LocalTerminationDisabler terminationDisabler(*this);
Vector<String> sites;
if (NetscapePluginModule* module = netscapePluginModule())
sites = module->sitesWithData();
m_connection->send(Messages::PluginProcessProxy::DidGetSitesWithData(sites, callbackID), 0);
}
void PluginProcess::clearSiteData(const Vector<String>& sites, uint64_t flags, uint64_t maxAgeInSeconds, uint64_t callbackID)
{
LocalTerminationDisabler terminationDisabler(*this);
if (NetscapePluginModule* module = netscapePluginModule()) {
if (sites.isEmpty()) {
// Clear everything.
module->clearSiteData(String(), flags, maxAgeInSeconds);
} else {
for (size_t i = 0; i < sites.size(); ++i)
module->clearSiteData(sites[i], flags, maxAgeInSeconds);
}
}
m_connection->send(Messages::PluginProcessProxy::DidClearSiteData(callbackID), 0);
}
} // namespace WebKit
#endif // ENABLE(PLUGIN_PROCESS)
| [
"gahlotpercy@gmail.com"
] | gahlotpercy@gmail.com |
63b6b7fba58d3a4ed7f14944b98055278ec96c3d | c739604b61772be707f7a15d66125c5093cdfc76 | /src/spi_tft.cpp | 34bc1ed2843c33799842da100e54d7f7010d39bc | [] | no_license | weimingtom/spi_tft | 1d8e2375deaa7c52be2c5b28833472bb0408b67f | dbb43925a28b29983d42c4db4b1e27de338621d4 | refs/heads/master | 2023-05-24T20:36:29.134716 | 2019-04-30T06:01:40 | 2019-04-30T06:01:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 449 | cpp | #include <unistd.h>
#include <stdio.h>
#include "font.h"
#include "LCD.h"
#include "spi.h"
static const char *device = "/dev/spidev32766.1";
static uint8_t mode = 0; /* SPI通信使用全双工,设置CPOL=0,CPHA=0。 */
static uint8_t bits = 8; /* 8bits读写,MSB first。*/
static uint32_t speed = 96 * 1000 * 1000;/* 设置96M传输速度 */
//int g_SPI_Fd = 0;
int main()
{
Lcd_Init();
while(1)
{
test_color();
}
}
| [
"sunxueyiii@163.com"
] | sunxueyiii@163.com |
5e91eea9b07d46657ea57a36e03feaf9c2a91554 | 7435c4218f847c1145f2d8e60468fcb8abca1979 | /Vaango/src/Core/Grid/SimulationState.cc | f08f2ee84d129e14ac39e7cda57096f833b86b17 | [] | no_license | markguozhiming/ParSim | bb0d7162803279e499daf58dc8404440b50de38d | 6afe2608edd85ed25eafff6085adad553e9739bc | refs/heads/master | 2020-05-16T19:04:09.700317 | 2019-02-12T02:30:45 | 2019-02-12T02:30:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,431 | cc | /*
* The MIT License
*
* Copyright (c) 1997-2012 The University of Utah
* Copyright (c) 2013-2014 Callaghan Innovation, New Zealand
* Copyright (c) 2015- Parresia Research Limited, New Zealand
*
* 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 <Core/Exceptions/ProblemSetupException.h>
#include <Core/Grid/SimulationState.h>
#include <Core/Grid/Variables/VarLabel.h>
#include <Core/Grid/Variables/VarTypes.h>
#include <Core/Grid/Variables/ReductionVariable.h>
#include <Core/Grid/Variables/Reductions.h>
#include <Core/Grid/Variables/PerPatch.h>
#include <Core/Grid/Material.h>
#include <Core/Grid/Grid.h>
#include <Core/Grid/Level.h>
#include <Core/Grid/SimpleMaterial.h>
#include <CCA/Components/ICE/ICEMaterial.h>
#include <CCA/Components/MPM/ConstitutiveModel/MPMMaterial.h>
#include <CCA/Components/MPM/CohesiveZone/CZMaterial.h>
#include <CCA/Components/Peridynamics/PeridynamicsMaterial.h>
#include <Core/Containers/StringUtil.h>
#include <Core/Malloc/Allocator.h>
using namespace Uintah;
SimulationState::SimulationState(ProblemSpecP &ps)
{
VarLabel* nonconstDelt = VarLabel::create("delT",
delt_vartype::getTypeDescription() );
nonconstDelt->allowMultipleComputes();
delt_label = nonconstDelt;
refineFlag_label = VarLabel::create("refineFlag",
CCVariable<int>::getTypeDescription());
oldRefineFlag_label = VarLabel::create("oldRefineFlag",
CCVariable<int>::getTypeDescription());
refinePatchFlag_label = VarLabel::create("refinePatchFlag",
PerPatch<int>::getTypeDescription());
switch_label = VarLabel::create("switchFlag",
max_vartype::getTypeDescription());
//__________________________________
// These variables can be modified by a component.
VarLabel* nonconstOutputInv = // output timestep interval
VarLabel::create("outputInterval", min_vartype::getTypeDescription() );
VarLabel* nonconstCheckInv = // check point interval
VarLabel::create("checkpointInterval", min_vartype::getTypeDescription() );
nonconstOutputInv->allowMultipleComputes();
nonconstCheckInv->allowMultipleComputes();
outputInterval_label = nonconstOutputInv;
checkpointInterval_label = nonconstCheckInv;
//_____
d_elapsed_time = 0.0;
d_needAddMaterial = 0;
d_lockstepAMR = false;
d_updateOutputInterval = false;
d_updateCheckpointInterval = false;
ProblemSpecP amr = ps->findBlock("AMR");
if (amr) {
amr->get("useLockStep", d_lockstepAMR);
}
all_mpm_matls = 0;
all_cz_matls = 0;
all_ice_matls = 0;
all_peridynamics_matls = 0;
all_matls = 0;
orig_all_matls = 0;
allInOneMatl = 0;
max_matl_index = 0;
refine_flag_matls = 0;
d_isCopyDataTimestep = 0;
d_isRegridTimestep = 0;
d_simTime = 0;
d_numDims = 0;
d_isCopyDataTimestep = 0;
d_recompileTaskGraph = false;
d_switchState = false;
d_simTime = 0;
d_numDims = 0;
d_activeDims[0] = d_activeDims[1] = d_activeDims[2] = 0;
// Initialize the overhead percentage
overheadIndex=0;
overheadAvg=0;
for(int i=0; i<OVERHEAD_WINDOW; i++) {
double x=i/(OVERHEAD_WINDOW/2);
overheadWeights[i]=8-x*x*x;
overhead[i]=0;
}
clearStats();
}
void
SimulationState::registerMaterial(Material* matl)
{
matl->registerParticleState(this);
matl->setDWIndex((int)matls.size());
matls.push_back(matl);
if ((int)matls.size() > max_matl_index) {
max_matl_index = matls.size();
}
if (matl->hasName()) {
named_matls[matl->getName()] = matl;
}
}
void
SimulationState::registerMaterial(Material* matl,
unsigned int index)
{
matl->registerParticleState(this);
matl->setDWIndex(index);
if (matls.size() <= index) {
matls.resize(index+1);
}
matls[index]=matl;
if ((int)matls.size() > max_matl_index) {
max_matl_index = matls.size();
}
if (matl->hasName()) {
named_matls[matl->getName()] = matl;
}
}
void
SimulationState::registerMPMMaterial(MPMMaterial* matl)
{
mpm_matls.push_back(matl);
registerMaterial(matl);
}
void
SimulationState::registerMPMMaterial(MPMMaterial* matl,
unsigned int index)
{
mpm_matls.push_back(matl);
registerMaterial(matl,index);
}
void
SimulationState::registerPeridynamicsMaterial(Vaango::PeridynamicsMaterial* matl)
{
peridynamics_matls.push_back(matl);
registerMaterial(matl);
}
void
SimulationState::registerPeridynamicsMaterial(Vaango::PeridynamicsMaterial* matl,
unsigned int index)
{
peridynamics_matls.push_back(matl);
registerMaterial(matl, index);
}
void
SimulationState::registerCZMaterial(CZMaterial* matl)
{
cz_matls.push_back(matl);
registerMaterial(matl);
}
void
SimulationState::registerCZMaterial(CZMaterial* matl,
unsigned int index)
{
cz_matls.push_back(matl);
registerMaterial(matl,index);
}
void
SimulationState::registerICEMaterial(ICEMaterial* matl)
{
ice_matls.push_back(matl);
registerMaterial(matl);
}
void
SimulationState::registerICEMaterial(ICEMaterial* matl,
unsigned int index)
{
ice_matls.push_back(matl);
registerMaterial(matl,index);
}
void
SimulationState::registerSimpleMaterial(SimpleMaterial* matl)
{
simple_matls.push_back(matl);
registerMaterial(matl);
}
void
SimulationState::finalizeMaterials()
{
if (all_mpm_matls && all_mpm_matls->removeReference()) {
delete all_mpm_matls;
}
all_mpm_matls = scinew MaterialSet();
all_mpm_matls->addReference();
vector<int> tmp_mpm_matls(mpm_matls.size());
for( int i=0; i<(int)mpm_matls.size(); i++ ) {
tmp_mpm_matls[i] = mpm_matls[i]->getDWIndex();
}
all_mpm_matls->addAll(tmp_mpm_matls);
if (all_peridynamics_matls && all_peridynamics_matls->removeReference()) {
delete all_peridynamics_matls;
}
all_peridynamics_matls = scinew Uintah::MaterialSet();
all_peridynamics_matls->addReference();
std::vector<int> tmp_peridynamics_matls(peridynamics_matls.size());
for( int i=0; i<(int)peridynamics_matls.size(); i++ ) {
tmp_peridynamics_matls[i] = peridynamics_matls[i]->getDWIndex();
}
all_peridynamics_matls->addAll(tmp_peridynamics_matls);
if (all_cz_matls && all_cz_matls->removeReference()) {
delete all_cz_matls;
}
all_cz_matls = scinew MaterialSet();
all_cz_matls->addReference();
vector<int> tmp_cz_matls(cz_matls.size());
for( int i=0; i<(int)cz_matls.size(); i++ ) {
tmp_cz_matls[i] = cz_matls[i]->getDWIndex();
}
all_cz_matls->addAll(tmp_cz_matls);
if (all_ice_matls && all_ice_matls->removeReference()) {
delete all_ice_matls;
}
all_ice_matls = scinew MaterialSet();
all_ice_matls->addReference();
vector<int> tmp_ice_matls(ice_matls.size());
for(int i=0;i<(int)ice_matls.size();i++)
tmp_ice_matls[i] = ice_matls[i]->getDWIndex();
all_ice_matls->addAll(tmp_ice_matls);
if (all_matls && all_matls->removeReference()) {
delete all_matls;
}
all_matls = scinew MaterialSet();
all_matls->addReference();
vector<int> tmp_matls(matls.size());
for(int i=0; i<(int)matls.size(); i++) {
tmp_matls[i] = matls[i]->getDWIndex();
}
all_matls->addAll(tmp_matls);
if (orig_all_matls == 0) {
orig_all_matls = scinew MaterialSet();
orig_all_matls->addReference();
orig_all_matls->addAll(tmp_matls);
}
if (allInOneMatl && allInOneMatl->removeReference()) {
delete allInOneMatl;
}
allInOneMatl = scinew MaterialSubset();
allInOneMatl->addReference();
// a material that represents all materials
// (i.e. summed over all materials -- the whole enchilada)
allInOneMatl->add((int)matls.size());
//refine matl subset, only done on matl 0 (matl independent)
if (!refine_flag_matls) {
refine_flag_matls = scinew MaterialSubset();
refine_flag_matls->addReference();
refine_flag_matls->add(0);
}
}
void
SimulationState::clearMaterials()
{
for (int i = 0; i < (int)matls.size(); i++) {
old_matls.push_back(matls[i]);
}
if (all_matls && all_matls->removeReference()) {
delete all_matls;
}
if (all_mpm_matls && all_mpm_matls->removeReference()) {
delete all_mpm_matls;
}
if (all_cz_matls && all_cz_matls->removeReference()) {
delete all_cz_matls;
}
if (all_ice_matls && all_ice_matls->removeReference()) {
delete all_ice_matls;
}
if (allInOneMatl && allInOneMatl->removeReference()) {
delete allInOneMatl;
}
if(all_peridynamics_matls && all_peridynamics_matls->removeReference()) {
delete all_peridynamics_matls;
}
matls.clear();
mpm_matls.clear();
peridynamics_matls.clear();
cz_matls.clear();
ice_matls.clear();
simple_matls.clear();
named_matls.clear();
d_particleState.clear();
d_particleState_preReloc.clear();
d_cohesiveZoneState.clear();
d_cohesiveZoneState_preReloc.clear();
all_matls = 0;
all_mpm_matls = 0;
all_peridynamics_matls = 0;
all_cz_matls = 0;
all_ice_matls = 0;
allInOneMatl = 0;
}
SimulationState::~SimulationState()
{
VarLabel::destroy(delt_label);
VarLabel::destroy(refineFlag_label);
VarLabel::destroy(oldRefineFlag_label);
VarLabel::destroy(refinePatchFlag_label);
VarLabel::destroy(switch_label);
VarLabel::destroy(outputInterval_label);
VarLabel::destroy(checkpointInterval_label);
clearMaterials();
for (unsigned i = 0; i < old_matls.size(); i++) {
delete old_matls[i];
}
if (refine_flag_matls && refine_flag_matls->removeReference()) {
delete refine_flag_matls;
}
if (orig_all_matls && orig_all_matls->removeReference()) {
delete orig_all_matls;
}
}
const MaterialSet*
SimulationState::allMPMMaterials() const
{
ASSERT(all_mpm_matls != 0);
return all_mpm_matls;
}
const Uintah::MaterialSet*
SimulationState::allPeridynamicsMaterials() const
{
ASSERT(all_peridynamics_matls != 0);
return all_peridynamics_matls;
}
const MaterialSet*
SimulationState::allCZMaterials() const
{
ASSERT(all_cz_matls != 0);
return all_cz_matls;
}
const MaterialSet*
SimulationState::allICEMaterials() const
{
ASSERT(all_ice_matls != 0);
return all_ice_matls;
}
const MaterialSet*
SimulationState::allMaterials() const
{
ASSERT(all_matls != 0);
return all_matls;
}
const MaterialSet*
SimulationState::originalAllMaterials() const
{
ASSERT(orig_all_matls != 0);
return orig_all_matls;
}
void
SimulationState::setOriginalMatlsFromRestart(MaterialSet* matls)
{
if (orig_all_matls && orig_all_matls->removeReference())
delete orig_all_matls;
orig_all_matls = matls;
}
const MaterialSubset*
SimulationState::refineFlagMaterials() const
{
ASSERT(refine_flag_matls != 0);
return refine_flag_matls;
}
Material*
SimulationState::getMaterialByName(const std::string& name) const
{
map<string, Material*>::const_iterator iter = named_matls.find(name);
if(iter == named_matls.end())
return 0;
return iter->second;
}
//__________________________________
//
Material*
SimulationState::parseAndLookupMaterial(ProblemSpecP& params,
const std::string& name) const
{
// for single material problems return matl 0
Material* result = getMaterial(0);
if( getNumMatls() > 1){
string matlname;
if(!params->get(name, matlname)){
throw ProblemSetupException("Cannot find material section", __FILE__, __LINE__);
}
result = getMaterialByName(matlname);
if(!result){
throw ProblemSetupException("Cannot find a material named:"+matlname, __FILE__, __LINE__);
}
}
return result;
}
void
SimulationState::clearStats()
{
compilationTime = 0;
regriddingTime = 0;
regriddingCompilationTime = 0;
regriddingCopyDataTime = 0;
loadbalancerTime = 0;
taskExecTime = 0;
taskGlobalCommTime = 0;
taskLocalCommTime = 0;
taskWaitCommTime = 0;
taskWaitThreadTime = 0;
outputTime = 0;
}
void
SimulationState::setDimensionality(bool x, bool y, bool z)
{
d_numDims = 0;
int currentDim = 0;
bool args[3] = {x,y,z};
for (int i = 0; i < 3; i++) {
if (args[i]) {
d_numDims++;
d_activeDims[currentDim] = i;
currentDim++;
}
}
}
| [
"b.banerjee.nz@gmail.com"
] | b.banerjee.nz@gmail.com |
a461bb66f79b702d5c2a44258d39a78c1ca0405b | f86422e7c8896d06fe4c3db4b27608c51f90ddb6 | /War.cpp | de31582664c59524503d5673533cf021fd899f3b | [] | no_license | nicksica99/Warhorses | d9ecacfb87937281851e186ed0ce80d19066ef97 | 21fefc7fdff7fe7512b6f3506dc4e1843877d80a | refs/heads/main | 2023-02-24T23:34:19.950957 | 2021-01-26T21:23:57 | 2021-01-26T21:23:57 | 333,220,408 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,232 | cpp | /*****************************
** File: War.cpp
** Project: CMSC 202 Project 4, Spring 2019
** Author: Nick Sica
** Date: 4/8/19
** Section: 07
** E-mail: nsica1@umbc.edu
**
** This file contains the main code for the War.cpp file, it allows
** for the start of the program and the creation of the game and the user
** input
***************************/
#include "War.h"
#include "Horse.h"
#include "Untrained.h"
#include "Warhorse.h"
#include "Light.h"
#include "Medium.h"
#include "Heavy.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <fstream>
#include <vector>
#include <string>
const int SMALLWIDTH = 10;
const int WIDTH = 20;
const char SEPARATE = ' ';
//ints for other random stuff such as QUIT
const int LIGHT = 0;
const int MED = 1;
const int HEAVY = 2;
const int QUIT = 6;
// Default Constructor
// Preconditions: None
// Postconditions: Seeds srand only
War::War() {
srand(time(NULL));
//seeds
}
// Destructor
// Preconditions: m_myStable and/or m_enemyStable is populated
// Postconditions: Deallocates horse objects in all vectors
War::~War() {
//deletes the horses throughout both stables
for(int i = 0; i < (int) m_myStable.size(); i++) {
delete m_myStable.at(i);
}
for(int j = 0; j < (int) m_enemyStable.size(); j++) {
delete m_enemyStable.at(j);
}
}
// Name: loadHorses
// Desc - Loads each horse into m_enemyStable from file
// Preconditions - Requires file with valid horse data
// Postconditions - m_enemyStable is populated with enemy horse pointers
void War::loadHorses(char* filename) {
//variables to read in all of the variables
ifstream inputStream;
string name;
int size;
Size horseSize;
int health;
int speed;
int count = 0;
//opens file
inputStream.open(filename);
//while there is a name to read in
while(inputStream >> name) {
//reads in size
inputStream >> size;
//sets the size to the correct enum type
if(size == LIGHT) {
horseSize = SMALL;
}
else if(size == MED) {
horseSize = MEDIUM;
}
else if(size == HEAVY) {
horseSize = LARGE;
}
//reads in health and sped
inputStream >> health;
inputStream >> speed;
//if the size is small then it creates a new light horse
if(horseSize == SMALL) {
Horse* myLight = new Light(name,horseSize , health, speed);
m_enemyStable.push_back(myLight);
}
//if the size is medium then it creates a new medium horse
else if(horseSize == MEDIUM) {
Horse* myMedium = new Medium(name, horseSize, health, speed);
m_enemyStable.push_back(myMedium);
}
//if the size is large then it creates a new heavy horse
else if(horseSize == LARGE) {
Horse* myHeavy = new Heavy(name, horseSize, health, speed);
m_enemyStable.push_back(myHeavy);
}
//count just for the horses
count += 1;
}
//print statement to see if all of the horses loaded
cout << count << " enemy horses loaded" << endl;
//close file
inputStream.close();
}
// Name: MainMenu()
// Desc - Displays and manages menu
// Preconditions - m_enemyStable has been populated from file
// Postconditions - exits if user entered 6
void War::mainMenu() {
int choice;
//menu prints
do{
cout << "What would you like to do?" << endl;
cout << "1. Display Friendly Stable" << endl;
cout << "2. Display Enemy Stable" << endl;
cout << "3. Acquire Horse" << endl;
cout << "4. Train Horse" << endl;
cout << "5. Battle" << endl;
cout << "6. Quit" << endl;
//get input
cin >> choice;
//input validation and menu choice again
if(choice <= 0 || choice > QUIT) {
cout << "That was an invalid selection, try again" << endl;
cout << endl;
//menu again
cout << "What would you like to do?" << endl;
cout << "1. Display Friendly Stable" << endl;
cout << "2. Display Enemy Stable" << endl;
cout << "3. Acquire Horse" << endl;
cout << "4. Train Horse" << endl;
cout << "5. Battle" << endl;
cout << "6. Quit" << endl;
cin >> choice;
}
//switch statement for the choice
switch(choice) {
case 1:
//display your horses
displayMyHorses();
break;
case 2:
//display enemy horses
displayEnemyHorses();
break;
case 3:
//make a new horse
acquireHorse();
break;
case 4:
//train horse
trainHorse();
break;
case 5:
//start battle
startBattle();
break;
case 6:
//exit
cout << "Thank you for playing Warhorse" << endl;
}
//while the choice does not equal quit
} while(choice != QUIT);
}
// Name: acquireHorse()
// Desc - user randomly acquires a new untrained horse (random size)
// Preconditions - none
// Postconditions - new horse is added to m_myStable
void War::acquireHorse() {
//horse attributes
string nameHorse;
int speed;
int health;
Size horseSize;
//gets choice for the name of the horse
cout << "What would you like to name the horse?" << endl;
cin.ignore();
//allows for multiple name/spaces
getline(cin, nameHorse);
srand(time(NULL));
//randomizes if it is a heavy/medium/light horse
int random = rand() % (HEAVY + 1) + 1;
random = random - 1;
//if the horse is light randomize using the light constants
if(random == LIGHT) {
//health is random using light health constants- range is max to min
health = rand() % (LT_MAX_HEALTH - LT_MIN_HEALTH + 1) + LT_MIN_HEALTH;
//speed is randomized using light speed constants
speed = rand() % (LT_MAX_SPEED - LT_MIN_SPEED + 1) + LT_MIN_SPEED;
horseSize = SMALL;
}
else if(random == MED) {
//health is random using medium health constants- range is max to min
health = rand() % (MD_MAX_HEALTH - MD_MIN_HEALTH + 1) + MD_MIN_HEALTH;
//speed is randomized using light speed constants
speed = rand() % (MD_MAX_SPEED - MD_MIN_SPEED + 1) + MD_MIN_SPEED;
horseSize = MEDIUM;
}
else {
//health is random using heavy health constants- range is max to min
health = rand() % (HV_MAX_HEALTH - HV_MIN_HEALTH + 1) + HV_MIN_HEALTH;
//speed is randomized using light speed constants
speed = rand() % (HV_MAX_SPEED - HV_MIN_SPEED + 1) + HV_MIN_SPEED;
horseSize = LARGE;
}
///creates a new untrained horse object using the random attributes
Horse* myHorse = new Untrained(nameHorse, horseSize, health, speed);
//pushes it back into the vector
m_myStable.push_back(myHorse);
}
// Name: trainHorse()
// Desc - user randomly acquires a horse
// Preconditions - none
// Postconditions - new horse is added to m_stable
void War::trainHorse() {
//variables for the training
Horse* newHorse;
int trainChoice;
bool trained;
//gets users choice for which horse they want to train
trainChoice = chooseHorse();
//if the size is unknown then it specializes the horse into a
//warhorse and adds it into the vector
if(m_myStable.at(trainChoice)->toString() == "Unknown") {
newHorse = m_myStable.at(trainChoice)->specialize();
//deletes the old horse object
delete m_myStable.at(trainChoice);
m_myStable.at(trainChoice) = newHorse;
}
//if the size is not unknown
else {
//random boolean checks to see if the horse was trained
bool random = m_myStable.at(trainChoice)->train();
if(random == true) {
//if the horse was trained then increase the training level
trained = m_myStable.at(trainChoice)->increaseTraining();
if(trained == true) {
//print staement
cout << "Your horse has been trained" << endl;
}
else {
//max training statement
cout << "Your horse is at the max training" << endl;
}
}
else{
//didnt train
cout << "Your horse failed to be trained" << endl;
}
}
}
// Name: startBattle()
// Desc - user selects a horse to battle with and fights first horse in enemy
// m_enemyStable. Horse that loses is removed from their respective stable forever
// User must have at least ONE specialized horse at least training level 2 or higher
// Preconditions - Use has at least one horse and horse is specialized trained
// Postconditions - m_myStable or m_enemyStable has loser removed
void War::startBattle() {
//users choice
int battleChoice;
//counter
int counter = 0;
//bool if the user wins or loss
bool winLoss;
//user chooses horse for battle
battleChoice = chooseHorse();
//gets the original healths of both horses for the regeneration effect
int firstEnemyHealth = m_enemyStable.at(counter)->getHealth();
int firstUserHealth = m_myStable.at(battleChoice)->getHealth();
//if the horse cant battle because it is not trained
if(m_myStable.at(battleChoice)->getTraining() == (Training) 0) {
cout << "Untrained horses can't battle, the horse must be at least Saddle trained" << endl;
}
else {
//battles the horses -calls the warhorse.cpp function
winLoss = m_myStable.at(battleChoice)->battle(m_enemyStable.at(counter));
//if the users horse lost
if(winLoss == false) {
//print
cout << m_myStable.at(battleChoice)->getName() << " lost the battle" << endl;
//deletes the horse object
delete m_myStable.at(battleChoice);
//removes horse from vector
m_myStable.erase(m_myStable.begin() + battleChoice);
//resets enemy health
m_enemyStable.at(counter)->setHealth(firstEnemyHealth);
}//if users horse wins
else if(winLoss == true) {
//print statement
cout << m_myStable.at(battleChoice)->getName() << " won the battle" << endl;
//checks if the last horse was beaten
if(m_enemyStable.at(counter)->getName() == "Xanthos") {
//congrats statement
cout << "Congrats you have beaten all of the enemy Horses, go celebrate!!!" << endl;
}
//deletes enemy horse
delete m_enemyStable.at(counter);
//removes the enemy horse from vector
m_enemyStable.erase(m_enemyStable.begin());
//resets user horse health
m_myStable.at(battleChoice)->setHealth(firstUserHealth);
}
}
}
// Name: displayMyHorses()
// Desc - Displays all horses in m_myStable or empty message if no horses
// Preconditions - m_myStable is populated
// Postconditions - None
void War::displayMyHorses(){
//prints the users horse table stuff
//also sets the format as seen in the sample code output
cout << "My Horses" << endl;
cout << left << setw(SMALLWIDTH) << setfill(SEPARATE) << "Num"
<< setw(WIDTH) << setfill(SEPARATE) << "Horse"
<< setw(WIDTH) << setfill(SEPARATE) << "Size"
<< setw(SMALLWIDTH) << setfill(SEPARATE) << "Health"
<< setw(SMALLWIDTH) << setfill(SEPARATE) << "Speed"
<< setw(SMALLWIDTH) << setfill(SEPARATE) << "Training" << endl;
//goes through the loop and prints the users horses info
//sets format as seen in the sample code output
for(int i = 0; i < (int) m_myStable.size(); i++) {
cout << left << setw(SMALLWIDTH) << setfill(SEPARATE) << i + 1 //prints num;
<< *m_myStable.at(i);
}
}
// Name: displayEnemyHorses()
// Desc - Displays all horses in m_enemyStable or win message if empty
// Preconditions - m_enemyStable is populated
// Postconditions - None
void War::displayEnemyHorses() {
//displays the top of the table stuff
cout << "Enemy Horses" << endl;
cout << left << setw(SMALLWIDTH) << setfill(SEPARATE) << "Num" //num and sets the format
<< setw(WIDTH) << setfill(SEPARATE) << "Horse" //horse name and sets format
<< setw(WIDTH) << setfill(SEPARATE) << "Size" //size and sets format
<< setw(SMALLWIDTH) << setfill(SEPARATE) << "Health" //health and sets format
<< setw(SMALLWIDTH) << setfill(SEPARATE) << "Speed" //speed and sets format
<< setw(SMALLWIDTH) << setfill(SEPARATE) << "Training" << endl; //training and sets format
//goes through the stable and prints the horses data using the overloaded operator
for(int i = 0; i < (int) m_enemyStable.size(); i++) {
cout << setw(SMALLWIDTH) << setfill(SEPARATE) << i + 1 //prints num;
<< *m_enemyStable.at(i);
}
}
// Name: chooseHorse
// Desc - Helper that either displays that m_myStable is empty or allows user to
// choose a horse to use for training or battle. Returns index + 1
// Preconditions - None
// Postconditions - None
int War::chooseHorse() {
int choice;
//num horses equals the size of the vector
int numHorses = (int)m_myStable.size();
//checks if the stable is empty
if(numHorses == 0) {
cout << "Your stable is empty" << endl;
return -1;
}
//if the vector is not empty then it displays the horses and gets the user choice for horse
else {
cout << "Which horse would you like?" << endl;
displayMyHorses();
cin >> choice;
//input validation
if(choice <= 0 || choice > int(m_myStable.size())) {
cout << "Invalid selection try again" << endl;
cout << "Which horse would you like?" << endl;
cin >> choice;
}
//gets the choice - 1 as the index would be incorrect
choice = choice - 1;
}//returns the users choice
return choice;
}
| [
"noreply@github.com"
] | noreply@github.com |
8edd1870df5d24981c01ed1ba364a581f1701b19 | 88678d6377075eb1589fb53e59c908dbc7f26071 | /app_cole/include/Game.h | 54cbb26cb9246be3ccb8388a6750d2d329dd5f8b | [] | no_license | chrishaukap/GameDev | 89d76eacdae34ae96e83496f2c34c61e101d2600 | fb364cea6941e9b9074ecdd0d9569578efb0f937 | refs/heads/master | 2020-05-28T11:23:41.750257 | 2013-08-08T21:59:30 | 2013-08-08T21:59:30 | 2,401,748 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | h | #pragma once
#include "cdhBase.h"
#include <vector>
struct Vector2;
class PhysicsActor;
namespace CDH
{
namespace Cole
{
class Game
{
public:
Game(CHUint rows, CHUint cols);
~Game();
void update(float dt);
void cleanup();
void start();
void stop();
// debug draw
const class ColeAvatar* cole() const {return m_cole;}
private:
ColeAvatar* m_cole;
PhysicsActor* m_ground;
};
}
} | [
""
] | |
451f83c23cdcb234dea58b63ddf06b83a3311d42 | 06c1a1e3be43635f7beeb114b7003c9c12297f78 | /deps/v8/src/builtins/builtins-trace.cc | cd0f5a77d0a6177069bfa0bd83515f9ded92b491 | [
"SunPro",
"BSD-3-Clause",
"bzip2-1.0.6",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-unicode",
"Zlib",
"ISC",
"MIT",
"ICU",
"LicenseRef-scancode-public-domain",
"NAIST-2003",
"NTP",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause",
"Artistic-2.0"
] | permissive | TomerCohavi/node | 0b173a6e258ce6e247d43eaedef9fa5cdaa3103e | 0a3f829089a56b7e5544a956f04be3fc014cedb8 | refs/heads/master | 2020-03-28T12:44:05.493466 | 2019-09-21T21:11:30 | 2019-09-21T21:11:30 | 148,328,603 | 0 | 0 | NOASSERTION | 2019-09-21T21:12:19 | 2018-09-11T14:16:11 | JavaScript | UTF-8 | C++ | false | false | 6,710 | cc | // Copyright 2018 the V8 project 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 "src/api.h"
#include "src/builtins/builtins-utils.h"
#include "src/builtins/builtins.h"
#include "src/counters.h"
#include "src/json-stringifier.h"
#include "src/objects-inl.h"
namespace v8 {
namespace internal {
namespace {
using v8::tracing::TracedValue;
#define MAX_STACK_LENGTH 100
class MaybeUtf8 {
public:
explicit MaybeUtf8(Isolate* isolate, Handle<String> string) : buf_(data_) {
string = String::Flatten(isolate, string);
int len;
if (string->IsOneByteRepresentation()) {
// Technically this allows unescaped latin1 characters but the trace
// events mechanism currently does the same and the current consuming
// tools are tolerant of it. A more correct approach here would be to
// escape non-ascii characters but this is easier and faster.
len = string->length();
AllocateSufficientSpace(len);
if (len > 0) {
// Why copy? Well, the trace event mechanism requires null-terminated
// strings, the bytes we get from SeqOneByteString are not. buf_ is
// guaranteed to be null terminated.
memcpy(buf_, Handle<SeqOneByteString>::cast(string)->GetChars(), len);
}
} else {
Local<v8::String> local = Utils::ToLocal(string);
len = local->Utf8Length();
AllocateSufficientSpace(len);
if (len > 0) {
local->WriteUtf8(reinterpret_cast<char*>(buf_));
}
}
buf_[len] = 0;
}
const char* operator*() const { return reinterpret_cast<const char*>(buf_); }
private:
void AllocateSufficientSpace(int len) {
if (len + 1 > MAX_STACK_LENGTH) {
allocated_.reset(new uint8_t[len + 1]);
buf_ = allocated_.get();
}
}
// In the most common cases, the buffer here will be stack allocated.
// A heap allocation will only occur if the data is more than MAX_STACK_LENGTH
// Given that this is used primarily for trace event categories and names,
// the MAX_STACK_LENGTH should be more than enough.
uint8_t* buf_;
uint8_t data_[MAX_STACK_LENGTH];
std::unique_ptr<uint8_t> allocated_;
};
class JsonTraceValue : public ConvertableToTraceFormat {
public:
explicit JsonTraceValue(Isolate* isolate, Handle<String> object) {
// object is a JSON string serialized using JSON.stringify() from within
// the BUILTIN(Trace) method. This may (likely) contain UTF8 values so
// to grab the appropriate buffer data we have to serialize it out. We
// hold on to the bits until the AppendAsTraceFormat method is called.
MaybeUtf8 data(isolate, object);
data_ = *data;
}
void AppendAsTraceFormat(std::string* out) const override { *out += data_; }
private:
std::string data_;
};
const uint8_t* GetCategoryGroupEnabled(Isolate* isolate,
Handle<String> string) {
MaybeUtf8 category(isolate, string);
return TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED(*category);
}
#undef MAX_STACK_LENGTH
} // namespace
// Builins::kIsTraceCategoryEnabled(category) : bool
BUILTIN(IsTraceCategoryEnabled) {
HandleScope scope(isolate);
Handle<Object> category = args.atOrUndefined(isolate, 1);
if (!category->IsString()) {
THROW_NEW_ERROR_RETURN_FAILURE(
isolate, NewTypeError(MessageTemplate::kTraceEventCategoryError));
}
return isolate->heap()->ToBoolean(
*GetCategoryGroupEnabled(isolate, Handle<String>::cast(category)));
}
// Builtins::kTrace(phase, category, name, id, data) : bool
BUILTIN(Trace) {
HandleScope handle_scope(isolate);
Handle<Object> phase_arg = args.atOrUndefined(isolate, 1);
Handle<Object> category = args.atOrUndefined(isolate, 2);
Handle<Object> name_arg = args.atOrUndefined(isolate, 3);
Handle<Object> id_arg = args.atOrUndefined(isolate, 4);
Handle<Object> data_arg = args.atOrUndefined(isolate, 5);
const uint8_t* category_group_enabled =
GetCategoryGroupEnabled(isolate, Handle<String>::cast(category));
// Exit early if the category group is not enabled.
if (!*category_group_enabled) {
return ReadOnlyRoots(isolate).false_value();
}
if (!phase_arg->IsNumber()) {
THROW_NEW_ERROR_RETURN_FAILURE(
isolate, NewTypeError(MessageTemplate::kTraceEventPhaseError));
}
if (!category->IsString()) {
THROW_NEW_ERROR_RETURN_FAILURE(
isolate, NewTypeError(MessageTemplate::kTraceEventCategoryError));
}
if (!name_arg->IsString()) {
THROW_NEW_ERROR_RETURN_FAILURE(
isolate, NewTypeError(MessageTemplate::kTraceEventNameError));
}
uint32_t flags = TRACE_EVENT_FLAG_COPY;
int32_t id = 0;
if (!id_arg->IsNullOrUndefined(isolate)) {
if (!id_arg->IsNumber()) {
THROW_NEW_ERROR_RETURN_FAILURE(
isolate, NewTypeError(MessageTemplate::kTraceEventIDError));
}
flags |= TRACE_EVENT_FLAG_HAS_ID;
id = DoubleToInt32(id_arg->Number());
}
Handle<String> name_str = Handle<String>::cast(name_arg);
if (name_str->length() == 0) {
THROW_NEW_ERROR_RETURN_FAILURE(
isolate, NewTypeError(MessageTemplate::kTraceEventNameLengthError));
}
MaybeUtf8 name(isolate, name_str);
// We support passing one additional trace event argument with the
// name "data". Any JSON serializable value may be passed.
static const char* arg_name = "data";
int32_t num_args = 0;
uint8_t arg_type;
uint64_t arg_value;
if (!data_arg->IsUndefined(isolate)) {
// Serializes the data argument as a JSON string, which is then
// copied into an object. This eliminates duplicated code but
// could have perf costs. It is also subject to all the same
// limitations as JSON.stringify() as it relates to circular
// references and value limitations (e.g. BigInt is not supported).
JsonStringifier stringifier(isolate);
Handle<Object> result;
ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
isolate, result,
stringifier.Stringify(data_arg, isolate->factory()->undefined_value(),
isolate->factory()->undefined_value()));
std::unique_ptr<JsonTraceValue> traced_value;
traced_value.reset(
new JsonTraceValue(isolate, Handle<String>::cast(result)));
tracing::SetTraceValue(std::move(traced_value), &arg_type, &arg_value);
num_args++;
}
TRACE_EVENT_API_ADD_TRACE_EVENT(
static_cast<char>(DoubleToInt32(phase_arg->Number())),
category_group_enabled, *name, tracing::kGlobalScope, id, tracing::kNoId,
num_args, &arg_name, &arg_type, &arg_value, flags);
return ReadOnlyRoots(isolate).true_value();
}
} // namespace internal
} // namespace v8
| [
"targos@protonmail.com"
] | targos@protonmail.com |
19aafac686eaa41c928f36ba30cc7fcf66d737f2 | 10ecd7454a082e341eb60817341efa91d0c7fd0b | /SDK/BP_PromptActor_EmissarySunk_GH_parameters.h | 2bb2a52399e6b62ec252b4e625387697100cd911 | [] | no_license | Blackstate/Sot-SDK | 1dba56354524572894f09ed27d653ae5f367d95b | cd73724ce9b46e3eb5b075c468427aa5040daf45 | refs/heads/main | 2023-04-10T07:26:10.255489 | 2021-04-23T01:39:08 | 2021-04-23T01:39:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,469 | h | #pragma once
// Name: SoT, Version: 2.1.0.1
#include "../SDK.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function BP_PromptActor_EmissarySunk_GH.BP_PromptActor_EmissarySunk_GH_C.UserConstructionScript
struct ABP_PromptActor_EmissarySunk_GH_C_UserConstructionScript_Params
{
};
// Function BP_PromptActor_EmissarySunk_GH.BP_PromptActor_EmissarySunk_GH_C.ReceiveBeginPlay
struct ABP_PromptActor_EmissarySunk_GH_C_ReceiveBeginPlay_Params
{
};
// Function BP_PromptActor_EmissarySunk_GH.BP_PromptActor_EmissarySunk_GH_C.ReceiveEndPlay
struct ABP_PromptActor_EmissarySunk_GH_C_ReceiveEndPlay_Params
{
TEnumAsByte<Engine_EEndPlayReason> EndPlayReason; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
};
// Function BP_PromptActor_EmissarySunk_GH.BP_PromptActor_EmissarySunk_GH_C.ExecuteUbergraph_BP_PromptActor_EmissarySunk_GH
struct ABP_PromptActor_EmissarySunk_GH_C_ExecuteUbergraph_BP_PromptActor_EmissarySunk_GH_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"ploszjanos9844@gmail.com"
] | ploszjanos9844@gmail.com |
c0ee6243a2ec3105cf2e684860eaa3638f571da0 | 3a46c48d3eea7e8aefbf0421ebcf47a48470ae55 | /binary_tree/top_view_horizontal_dist_from_root.cpp | 206f316e859104d29fc50518ee70618382e9c4e9 | [] | no_license | thecreatorsir/coding-blocks-solutions | b8ce24293e8179a33741feed1f86d0e5e93fdc86 | 503b099452802bc831c4fb3650478509e54cd206 | refs/heads/master | 2023-02-09T01:32:27.994314 | 2020-12-27T16:18:50 | 2020-12-27T16:18:50 | 316,261,359 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,719 | cpp | #include<iostream>
#include<queue>
#include<map>
#include<climits>
#include<algorithm>
using namespace std;
class node {
public:
int data;
int h_dist;
node *left;
node *right;
node(int d){
data=d;
left = NULL;
right = NULL;
}
};
//building tree using bfs approach
node* buildtree(){
int d;
cin>>d;
node*root=new node(d);
queue<node*> q;
q.push(root);
while(!q.empty()){
node*f=q.front();
q.pop();
int c1,c2;
cin>>c1>>c2;
if(c1!=-1){
f->left=new node(c1);
q.push(f->left);
}
if(c2!=-1){
f->right=new node(c2);
q.push(f->right);
}
}
return root;
}
void bfs(node *root){
queue<node*> q;
q.push(root);
q.push(NULL);
while(!q.empty()){
node * temp = q.front();
cout<<temp->data<<" ";
q.pop();
if(temp->left){
q.push(temp->left);
}
if(temp->right){
q.push(temp->right);
}
if(q.front()==NULL){
q.pop();
cout<<endl;
if(!q.empty())
q.push(NULL);
}
}
}
void TopView(node *root){
if(root==NULL){
return;
}
int h_dist = 0;
queue<node *> q;
map<int,int> m;
root->h_dist = 0;
q.push(root);
while(!q.empty()){
node * temp = q.front();
h_dist = temp->h_dist;
q.pop();
if(m.count(h_dist)==0){
m[h_dist] = temp->data;
}
if(temp->left){
temp->left->h_dist = h_dist - 1;
q.push(temp->left);
}
if(temp->right){
temp->right->h_dist = h_dist+1;
q.push(temp->right);
}
}
for(auto it = m.begin();it!=m.end();it++){
cout<<it->second<<" ";
}
return;
}
int main(){
node * root = buildtree();
TopView(root);
return 0;
}
| [
"s.psharma887@gmail.com"
] | s.psharma887@gmail.com |
a629bb454cccb6d7a5f7ac04dbb3c737a5e60845 | fec81bfe0453c5646e00c5d69874a71c579a103d | /blazetest/src/mathtest/views/columns/DenseSymmetricTest.cpp | 00d3b8b8daa661b07c9a19c90bbc55a15ca09bf9 | [
"BSD-3-Clause"
] | permissive | parsa/blaze | 801b0f619a53f8c07454b80d0a665ac0a3cf561d | 6ce2d5d8951e9b367aad87cc55ac835b054b5964 | refs/heads/master | 2022-09-19T15:46:44.108364 | 2022-07-30T04:47:03 | 2022-07-30T04:47:03 | 105,918,096 | 52 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 220,024 | cpp | //=================================================================================================
/*!
// \file src/mathtest/views/columns/DenseSymmetricTest.cpp
// \brief Source file for the Columns dense symmetric test
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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 names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DynamicVector.h>
#include <blaze/math/Views.h>
#include <blazetest/mathtest/views/columns/DenseSymmetricTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
namespace blazetest {
namespace mathtest {
namespace views {
namespace columns {
//=================================================================================================
//
// CONSTRUCTORS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Constructor for the Columns dense symmetric test.
//
// \exception std::runtime_error Operation error detected.
*/
DenseSymmetricTest::DenseSymmetricTest()
: mat_ ( 4UL )
, tmat_( 4UL )
{
testConstructors();
testAssignment();
testFunctionCall();
testIterator();
testNonZeros();
testReset();
testClear();
testIsDefault();
testIsSame();
testSubmatrix();
testRow();
testRows();
testColumn();
testColumns();
testBand();
}
//*************************************************************************************************
//=================================================================================================
//
// TEST FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Test of the Columns constructors.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of all constructors of the Columns specialization. In case
// an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseSymmetricTest::testConstructors()
{
using blaze::index_sequence;
using blaze::initializer_list;
//=====================================================================================
// Row-major setup via index_sequence
//=====================================================================================
{
test_ = "Row-major Columns constructor (index_sequence)";
initialize();
// Setup of a regular column selection
{
auto cs = blaze::columns( mat_, index_sequence<0,3,2>() );
if( cs.rows() != mat_.rows() || cs.columns() != 3UL ||
cs(0,0) != mat_(0,0) || cs(0,1) != mat_(0,3) || cs(0,2) != mat_(0,2) ||
cs(1,0) != mat_(1,0) || cs(1,1) != mat_(1,3) || cs(1,2) != mat_(1,2) ||
cs(2,0) != mat_(2,0) || cs(2,1) != mat_(2,3) || cs(2,2) != mat_(2,2) ||
cs(3,0) != mat_(3,0) || cs(3,1) != mat_(3,3) || cs(3,2) != mat_(3,2) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds column selection
try {
auto cs = blaze::columns( mat_, index_sequence<5>() );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds column selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a column selection on a compile-time column selection
{
auto cs1 = blaze::columns( mat_, index_sequence<0,3,2>() );
auto cs2 = blaze::columns( cs1, index_sequence<2,1>() );
if( cs2.rows() != mat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != mat_(0,2) || cs2(0,1) != mat_(0,3) ||
cs2(1,0) != mat_(1,2) || cs2(1,1) != mat_(1,3) ||
cs2(2,0) != mat_(2,2) || cs2(2,1) != mat_(2,3) ||
cs2(3,0) != mat_(3,2) || cs2(3,1) != mat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an explicit column selection
{
auto cs1 = blaze::columns( mat_, { 0, 3, 2 } );
auto cs2 = blaze::columns( cs1, index_sequence<2,1>() );
if( cs2.rows() != mat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != mat_(0,2) || cs2(0,1) != mat_(0,3) ||
cs2(1,0) != mat_(1,2) || cs2(1,1) != mat_(1,3) ||
cs2(2,0) != mat_(2,2) || cs2(2,1) != mat_(2,3) ||
cs2(3,0) != mat_(3,2) || cs2(3,1) != mat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an implicit column selection
{
const std::array<size_t,3UL> indices{ 0, 3, 2 };
auto cs1 = blaze::columns( mat_, [indices]( size_t i ){ return indices[i]; }, 3UL );
auto cs2 = blaze::columns( cs1, index_sequence<2,1>() );
if( cs2.rows() != mat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != mat_(0,2) || cs2(0,1) != mat_(0,3) ||
cs2(1,0) != mat_(1,2) || cs2(1,1) != mat_(1,3) ||
cs2(2,0) != mat_(2,2) || cs2(2,1) != mat_(2,3) ||
cs2(3,0) != mat_(3,2) || cs2(3,1) != mat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Row-major setup via initializer_list
//=====================================================================================
{
test_ = "Row-major Columns constructor (initializer_list)";
initialize();
// Setup of empty column selection
{
std::initializer_list<size_t> indices{};
auto cs = blaze::columns( mat_, indices );
if( cs.rows() != mat_.rows() || cs.columns() != 0UL ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of empty column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a regular column selection
{
auto cs = blaze::columns( mat_, { 0, 3, 2 } );
if( cs.rows() != mat_.rows() || cs.columns() != 3UL ||
cs(0,0) != mat_(0,0) || cs(0,1) != mat_(0,3) || cs(0,2) != mat_(0,2) ||
cs(1,0) != mat_(1,0) || cs(1,1) != mat_(1,3) || cs(1,2) != mat_(1,2) ||
cs(2,0) != mat_(2,0) || cs(2,1) != mat_(2,3) || cs(2,2) != mat_(2,2) ||
cs(3,0) != mat_(3,0) || cs(3,1) != mat_(3,3) || cs(3,2) != mat_(3,2) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds column selection
try {
auto cs = blaze::columns( mat_, { 5 } );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds column selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a column selection on a compile-time column selection
{
auto cs1 = blaze::columns( mat_, index_sequence<0,3,2>() );
auto cs2 = blaze::columns( cs1, { 2, 1 } );
if( cs2.rows() != mat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != mat_(0,2) || cs2(0,1) != mat_(0,3) ||
cs2(1,0) != mat_(1,2) || cs2(1,1) != mat_(1,3) ||
cs2(2,0) != mat_(2,2) || cs2(2,1) != mat_(2,3) ||
cs2(3,0) != mat_(3,2) || cs2(3,1) != mat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an explicit column selection
{
auto cs1 = blaze::columns( mat_, { 0, 3, 2 } );
auto cs2 = blaze::columns( cs1, { 2, 1 } );
if( cs2.rows() != mat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != mat_(0,2) || cs2(0,1) != mat_(0,3) ||
cs2(1,0) != mat_(1,2) || cs2(1,1) != mat_(1,3) ||
cs2(2,0) != mat_(2,2) || cs2(2,1) != mat_(2,3) ||
cs2(3,0) != mat_(3,2) || cs2(3,1) != mat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an implicit column selection
{
const std::array<size_t,3UL> indices{ 0, 3, 2 };
auto cs1 = blaze::columns( mat_, [indices]( size_t i ){ return indices[i]; }, 3UL );
auto cs2 = blaze::columns( cs1, { 2, 1 } );
if( cs2.rows() != mat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != mat_(0,2) || cs2(0,1) != mat_(0,3) ||
cs2(1,0) != mat_(1,2) || cs2(1,1) != mat_(1,3) ||
cs2(2,0) != mat_(2,2) || cs2(2,1) != mat_(2,3) ||
cs2(3,0) != mat_(3,2) || cs2(3,1) != mat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Row-major setup via std::vector
//=====================================================================================
{
test_ = "Row-major Columns constructor (std::vector)";
initialize();
// Setup of empty column selection
{
std::vector<size_t> indices;
auto cs = blaze::columns( mat_, indices );
if( cs.rows() != mat_.rows() || cs.columns() != 0UL ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of empty column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a regular column selection
{
const std::vector<size_t> indices{ 0, 3, 2 };
auto cs = blaze::columns( mat_, indices );
if( cs.rows() != mat_.rows() || cs.columns() != 3UL ||
cs(0,0) != mat_(0,0) || cs(0,1) != mat_(0,3) || cs(0,2) != mat_(0,2) ||
cs(1,0) != mat_(1,0) || cs(1,1) != mat_(1,3) || cs(1,2) != mat_(1,2) ||
cs(2,0) != mat_(2,0) || cs(2,1) != mat_(2,3) || cs(2,2) != mat_(2,2) ||
cs(3,0) != mat_(3,0) || cs(3,1) != mat_(3,3) || cs(3,2) != mat_(3,2) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds column selection
try {
std::vector<size_t> indices{ 5 };
auto cs = blaze::columns( mat_, indices );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds column selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a column selection on a compile-time column selection
{
auto cs1 = blaze::columns( mat_, index_sequence<0,3,2>() );
const std::vector<size_t> indices{ 2, 1 };
auto cs2 = blaze::columns( cs1, indices );
if( cs2.rows() != mat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != mat_(0,2) || cs2(0,1) != mat_(0,3) ||
cs2(1,0) != mat_(1,2) || cs2(1,1) != mat_(1,3) ||
cs2(2,0) != mat_(2,2) || cs2(2,1) != mat_(2,3) ||
cs2(3,0) != mat_(3,2) || cs2(3,1) != mat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an explicit column selection
{
auto cs1 = blaze::columns( mat_, { 0, 3, 2 } );
const std::vector<size_t> indices{ 2, 1 };
auto cs2 = blaze::columns( cs1, indices );
if( cs2.rows() != mat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != mat_(0,2) || cs2(0,1) != mat_(0,3) ||
cs2(1,0) != mat_(1,2) || cs2(1,1) != mat_(1,3) ||
cs2(2,0) != mat_(2,2) || cs2(2,1) != mat_(2,3) ||
cs2(3,0) != mat_(3,2) || cs2(3,1) != mat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an implicit column selection
{
const std::array<size_t,3UL> indices1{ 0, 3, 2 };
auto cs1 = blaze::columns( mat_, [indices1]( size_t i ){ return indices1[i]; }, 3UL );
const std::vector<size_t> indices2{ 2, 1 };
auto cs2 = blaze::columns( cs1, indices2 );
if( cs2.rows() != mat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != mat_(0,2) || cs2(0,1) != mat_(0,3) ||
cs2(1,0) != mat_(1,2) || cs2(1,1) != mat_(1,3) ||
cs2(2,0) != mat_(2,2) || cs2(2,1) != mat_(2,3) ||
cs2(3,0) != mat_(3,2) || cs2(3,1) != mat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Row-major setup via std::array
//=====================================================================================
{
test_ = "Row-major Columns constructor (std::array)";
initialize();
// Setup of a regular column selection
{
const std::array<size_t,3UL> indices{ 0, 3, 2 };
auto cs = blaze::columns( mat_, indices );
if( cs.rows() != mat_.rows() || cs.columns() != 3UL ||
cs(0,0) != mat_(0,0) || cs(0,1) != mat_(0,3) || cs(0,2) != mat_(0,2) ||
cs(1,0) != mat_(1,0) || cs(1,1) != mat_(1,3) || cs(1,2) != mat_(1,2) ||
cs(2,0) != mat_(2,0) || cs(2,1) != mat_(2,3) || cs(2,2) != mat_(2,2) ||
cs(3,0) != mat_(3,0) || cs(3,1) != mat_(3,3) || cs(3,2) != mat_(3,2) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds column selection
try {
std::array<size_t,1UL> indices{ 5 };
auto cs = blaze::columns( mat_, indices );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds column selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a column selection on a compile-time column selection
{
auto cs1 = blaze::columns( mat_, index_sequence<0,3,2>() );
const std::array<size_t,2UL> indices{ 2, 1 };
auto cs2 = blaze::columns( cs1, indices );
if( cs2.rows() != mat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != mat_(0,2) || cs2(0,1) != mat_(0,3) ||
cs2(1,0) != mat_(1,2) || cs2(1,1) != mat_(1,3) ||
cs2(2,0) != mat_(2,2) || cs2(2,1) != mat_(2,3) ||
cs2(3,0) != mat_(3,2) || cs2(3,1) != mat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an explicit column selection
{
auto cs1 = blaze::columns( mat_, { 0, 3, 2 } );
const std::array<size_t,2UL> indices{ 2, 1 };
auto cs2 = blaze::columns( cs1, indices );
if( cs2.rows() != mat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != mat_(0,2) || cs2(0,1) != mat_(0,3) ||
cs2(1,0) != mat_(1,2) || cs2(1,1) != mat_(1,3) ||
cs2(2,0) != mat_(2,2) || cs2(2,1) != mat_(2,3) ||
cs2(3,0) != mat_(3,2) || cs2(3,1) != mat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an implicit column selection
{
const std::array<size_t,3UL> indices1{ 0, 3, 2 };
auto cs1 = blaze::columns( mat_, [indices1]( size_t i ){ return indices1[i]; }, 3UL );
const std::array<size_t,2UL> indices{ 2, 1 };
auto cs2 = blaze::columns( cs1, indices );
if( cs2.rows() != mat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != mat_(0,2) || cs2(0,1) != mat_(0,3) ||
cs2(1,0) != mat_(1,2) || cs2(1,1) != mat_(1,3) ||
cs2(2,0) != mat_(2,2) || cs2(2,1) != mat_(2,3) ||
cs2(3,0) != mat_(3,2) || cs2(3,1) != mat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Row-major setup via lambda expression
//=====================================================================================
{
test_ = "Row-major Columns constructor (lambda expression)";
initialize();
// Setup of empty column selection
{
auto cs = blaze::columns( mat_, []( size_t ){ return 0UL; }, 0UL );
if( cs.rows() != mat_.rows() || cs.columns() != 0UL ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of empty column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a regular column selection
{
const std::array<size_t,3UL> indices{ 0, 3, 2 };
auto cs = blaze::columns( mat_, [indices]( size_t i ){ return indices[i]; }, 3UL );
if( cs.rows() != mat_.rows() || cs.columns() != 3UL ||
cs(0,0) != mat_(0,0) || cs(0,1) != mat_(0,3) || cs(0,2) != mat_(0,2) ||
cs(1,0) != mat_(1,0) || cs(1,1) != mat_(1,3) || cs(1,2) != mat_(1,2) ||
cs(2,0) != mat_(2,0) || cs(2,1) != mat_(2,3) || cs(2,2) != mat_(2,2) ||
cs(3,0) != mat_(3,0) || cs(3,1) != mat_(3,3) || cs(3,2) != mat_(3,2) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds column selection
try {
auto cs = blaze::columns( mat_, []( size_t ){ return 5UL; }, 1UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds column selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a column selection on a compile-time column selection
{
auto cs1 = blaze::columns( mat_, index_sequence<0,3,2>() );
const std::array<size_t,2UL> indices{ 2, 1 };
auto cs2 = blaze::columns( cs1, [indices]( size_t i ){ return indices[i]; }, 2UL );
if( cs2.rows() != mat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != mat_(0,2) || cs2(0,1) != mat_(0,3) ||
cs2(1,0) != mat_(1,2) || cs2(1,1) != mat_(1,3) ||
cs2(2,0) != mat_(2,2) || cs2(2,1) != mat_(2,3) ||
cs2(3,0) != mat_(3,2) || cs2(3,1) != mat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an explicit column selection
{
auto cs1 = blaze::columns( mat_, { 0, 3, 2 } );
const std::array<size_t,2UL> indices{ 2, 1 };
auto cs2 = blaze::columns( cs1, [indices]( size_t i ){ return indices[i]; }, 2UL );
if( cs2.rows() != mat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != mat_(0,2) || cs2(0,1) != mat_(0,3) ||
cs2(1,0) != mat_(1,2) || cs2(1,1) != mat_(1,3) ||
cs2(2,0) != mat_(2,2) || cs2(2,1) != mat_(2,3) ||
cs2(3,0) != mat_(3,2) || cs2(3,1) != mat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an implicit column selection
{
const std::array<size_t,3UL> indices1{ 0, 3, 2 };
auto cs1 = blaze::columns( mat_, [indices1]( size_t i ){ return indices1[i]; }, 3UL );
const std::array<size_t,2UL> indices2{ 2, 1 };
auto cs2 = blaze::columns( cs1, [indices2]( size_t i ){ return indices2[i]; }, 2UL );
if( cs2.rows() != mat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != mat_(0,2) || cs2(0,1) != mat_(0,3) ||
cs2(1,0) != mat_(1,2) || cs2(1,1) != mat_(1,3) ||
cs2(2,0) != mat_(2,2) || cs2(2,1) != mat_(2,3) ||
cs2(3,0) != mat_(3,2) || cs2(3,1) != mat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Row-major setup of random in-bounds element selection
//=====================================================================================
{
test_ = "Column-major Columns constructor (stress test)";
initialize();
for( size_t rep=0UL; rep<100UL; ++rep )
{
blaze::DynamicVector<size_t> indices( blaze::rand<size_t>( 1UL, 20UL ) );
randomize( indices, 0UL, mat_.rows()-1UL );
auto cs = blaze::columns( mat_, indices.data(), indices.size() );
for( size_t i=0UL; i<cs.rows(); ++i ) {
for( size_t j=0UL; j<cs.columns(); ++j ) {
if( cs(i,j) != mat_(i,indices[j]) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Indices:\n" << indices << "\n"
<< " Column selection:\n" << cs << "\n"
<< " Matrix:\n" << mat_ << "\n";
throw std::runtime_error( oss.str() );
}
}
}
}
}
//=====================================================================================
// Column-major setup via index_sequence
//=====================================================================================
{
test_ = "Column-major Columns constructor (index_sequence)";
initialize();
// Setup of a regular column selection
{
auto cs = blaze::columns( tmat_, index_sequence<0,3,2>() );
if( cs.rows() != tmat_.rows() || cs.columns() != 3UL ||
cs(0,0) != tmat_(0,0) || cs(0,1) != tmat_(0,3) || cs(0,2) != tmat_(0,2) ||
cs(1,0) != tmat_(1,0) || cs(1,1) != tmat_(1,3) || cs(1,2) != tmat_(1,2) ||
cs(2,0) != tmat_(2,0) || cs(2,1) != tmat_(2,3) || cs(2,2) != tmat_(2,2) ||
cs(3,0) != tmat_(3,0) || cs(3,1) != tmat_(3,3) || cs(3,2) != tmat_(3,2) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds column selection
try {
auto cs = blaze::columns( tmat_, index_sequence<5>() );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds column selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a column selection on a compile-time column selection
{
auto cs1 = blaze::columns( tmat_, index_sequence<0,3,2>() );
auto cs2 = blaze::columns( cs1, index_sequence<2,1>() );
if( cs2.rows() != tmat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != tmat_(0,2) || cs2(0,1) != tmat_(0,3) ||
cs2(1,0) != tmat_(1,2) || cs2(1,1) != tmat_(1,3) ||
cs2(2,0) != tmat_(2,2) || cs2(2,1) != tmat_(2,3) ||
cs2(3,0) != tmat_(3,2) || cs2(3,1) != tmat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an explicit column selection
{
auto cs1 = blaze::columns( tmat_, { 0, 3, 2 } );
auto cs2 = blaze::columns( cs1, index_sequence<2,1>() );
if( cs2.rows() != tmat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != tmat_(0,2) || cs2(0,1) != tmat_(0,3) ||
cs2(1,0) != tmat_(1,2) || cs2(1,1) != tmat_(1,3) ||
cs2(2,0) != tmat_(2,2) || cs2(2,1) != tmat_(2,3) ||
cs2(3,0) != tmat_(3,2) || cs2(3,1) != tmat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an implicit column selection
{
const std::array<size_t,3UL> indices{ 0, 3, 2 };
auto cs1 = blaze::columns( tmat_, [indices]( size_t i ){ return indices[i]; }, 3UL );
auto cs2 = blaze::columns( cs1, index_sequence<2,1>() );
if( cs2.rows() != tmat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != tmat_(0,2) || cs2(0,1) != tmat_(0,3) ||
cs2(1,0) != tmat_(1,2) || cs2(1,1) != tmat_(1,3) ||
cs2(2,0) != tmat_(2,2) || cs2(2,1) != tmat_(2,3) ||
cs2(3,0) != tmat_(3,2) || cs2(3,1) != tmat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major setup via initializer_list
//=====================================================================================
{
test_ = "Column-major Columns constructor (initializer_list)";
initialize();
// Setup of empty column selection
{
std::initializer_list<size_t> indices{};
auto cs = blaze::columns( tmat_, indices );
if( cs.rows() != tmat_.rows() || cs.columns() != 0UL ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of empty column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a regular column selection
{
auto cs = blaze::columns( tmat_, { 0, 3, 2 } );
if( cs.rows() != tmat_.rows() || cs.columns() != 3UL ||
cs(0,0) != tmat_(0,0) || cs(0,1) != tmat_(0,3) || cs(0,2) != tmat_(0,2) ||
cs(1,0) != tmat_(1,0) || cs(1,1) != tmat_(1,3) || cs(1,2) != tmat_(1,2) ||
cs(2,0) != tmat_(2,0) || cs(2,1) != tmat_(2,3) || cs(2,2) != tmat_(2,2) ||
cs(3,0) != tmat_(3,0) || cs(3,1) != tmat_(3,3) || cs(3,2) != tmat_(3,2) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds column selection
try {
auto cs = blaze::columns( tmat_, { 5 } );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds column selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a column selection on a compile-time column selection
{
auto cs1 = blaze::columns( tmat_, index_sequence<0,3,2>() );
auto cs2 = blaze::columns( cs1, { 2, 1 } );
if( cs2.rows() != tmat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != tmat_(0,2) || cs2(0,1) != tmat_(0,3) ||
cs2(1,0) != tmat_(1,2) || cs2(1,1) != tmat_(1,3) ||
cs2(2,0) != tmat_(2,2) || cs2(2,1) != tmat_(2,3) ||
cs2(3,0) != tmat_(3,2) || cs2(3,1) != tmat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an explicit column selection
{
auto cs1 = blaze::columns( tmat_, { 0, 3, 2 } );
auto cs2 = blaze::columns( cs1, { 2, 1 } );
if( cs2.rows() != tmat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != tmat_(0,2) || cs2(0,1) != tmat_(0,3) ||
cs2(1,0) != tmat_(1,2) || cs2(1,1) != tmat_(1,3) ||
cs2(2,0) != tmat_(2,2) || cs2(2,1) != tmat_(2,3) ||
cs2(3,0) != tmat_(3,2) || cs2(3,1) != tmat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an implicit column selection
{
const std::array<size_t,3UL> indices{ 0, 3, 2 };
auto cs1 = blaze::columns( tmat_, [indices]( size_t i ){ return indices[i]; }, 3UL );
auto cs2 = blaze::columns( cs1, { 2, 1 } );
if( cs2.rows() != tmat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != tmat_(0,2) || cs2(0,1) != tmat_(0,3) ||
cs2(1,0) != tmat_(1,2) || cs2(1,1) != tmat_(1,3) ||
cs2(2,0) != tmat_(2,2) || cs2(2,1) != tmat_(2,3) ||
cs2(3,0) != tmat_(3,2) || cs2(3,1) != tmat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major setup via std::vector
//=====================================================================================
{
test_ = "Column-major Columns constructor (std::vector)";
initialize();
// Setup of empty column selection
{
std::vector<size_t> indices;
auto cs = blaze::columns( tmat_, indices );
if( cs.rows() != tmat_.rows() || cs.columns() != 0UL ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of empty column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a regular column selection
{
const std::vector<size_t> indices{ 0, 3, 2 };
auto cs = blaze::columns( tmat_, indices );
if( cs.rows() != tmat_.rows() || cs.columns() != 3UL ||
cs(0,0) != tmat_(0,0) || cs(0,1) != tmat_(0,3) || cs(0,2) != tmat_(0,2) ||
cs(1,0) != tmat_(1,0) || cs(1,1) != tmat_(1,3) || cs(1,2) != tmat_(1,2) ||
cs(2,0) != tmat_(2,0) || cs(2,1) != tmat_(2,3) || cs(2,2) != tmat_(2,2) ||
cs(3,0) != tmat_(3,0) || cs(3,1) != tmat_(3,3) || cs(3,2) != tmat_(3,2) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds column selection
try {
std::vector<size_t> indices{ 5 };
auto cs = blaze::columns( tmat_, indices );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds column selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a column selection on a compile-time column selection
{
auto cs1 = blaze::columns( tmat_, index_sequence<0,3,2>() );
const std::vector<size_t> indices{ 2, 1 };
auto cs2 = blaze::columns( cs1, indices );
if( cs2.rows() != tmat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != tmat_(0,2) || cs2(0,1) != tmat_(0,3) ||
cs2(1,0) != tmat_(1,2) || cs2(1,1) != tmat_(1,3) ||
cs2(2,0) != tmat_(2,2) || cs2(2,1) != tmat_(2,3) ||
cs2(3,0) != tmat_(3,2) || cs2(3,1) != tmat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an explicit column selection
{
auto cs1 = blaze::columns( tmat_, { 0, 3, 2 } );
const std::vector<size_t> indices{ 2, 1 };
auto cs2 = blaze::columns( cs1, indices );
if( cs2.rows() != tmat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != tmat_(0,2) || cs2(0,1) != tmat_(0,3) ||
cs2(1,0) != tmat_(1,2) || cs2(1,1) != tmat_(1,3) ||
cs2(2,0) != tmat_(2,2) || cs2(2,1) != tmat_(2,3) ||
cs2(3,0) != tmat_(3,2) || cs2(3,1) != tmat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an implicit column selection
{
const std::array<size_t,3UL> indices1{ 0, 3, 2 };
auto cs1 = blaze::columns( tmat_, [indices1]( size_t i ){ return indices1[i]; }, 3UL );
const std::vector<size_t> indices2{ 2, 1 };
auto cs2 = blaze::columns( cs1, indices2 );
if( cs2.rows() != tmat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != tmat_(0,2) || cs2(0,1) != tmat_(0,3) ||
cs2(1,0) != tmat_(1,2) || cs2(1,1) != tmat_(1,3) ||
cs2(2,0) != tmat_(2,2) || cs2(2,1) != tmat_(2,3) ||
cs2(3,0) != tmat_(3,2) || cs2(3,1) != tmat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major setup via std::array
//=====================================================================================
{
test_ = "Column-major Columns constructor (std::array)";
initialize();
// Setup of a regular column selection
{
const std::array<size_t,3UL> indices{ 0, 3, 2 };
auto cs = blaze::columns( tmat_, indices );
if( cs.rows() != tmat_.rows() || cs.columns() != 3UL ||
cs(0,0) != tmat_(0,0) || cs(0,1) != tmat_(0,3) || cs(0,2) != tmat_(0,2) ||
cs(1,0) != tmat_(1,0) || cs(1,1) != tmat_(1,3) || cs(1,2) != tmat_(1,2) ||
cs(2,0) != tmat_(2,0) || cs(2,1) != tmat_(2,3) || cs(2,2) != tmat_(2,2) ||
cs(3,0) != tmat_(3,0) || cs(3,1) != tmat_(3,3) || cs(3,2) != tmat_(3,2) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds column selection
try {
std::array<size_t,1UL> indices{ 5 };
auto cs = blaze::columns( tmat_, indices );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds column selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a column selection on a compile-time column selection
{
auto cs1 = blaze::columns( tmat_, index_sequence<0,3,2>() );
const std::array<size_t,2UL> indices{ 2, 1 };
auto cs2 = blaze::columns( cs1, indices );
if( cs2.rows() != tmat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != tmat_(0,2) || cs2(0,1) != tmat_(0,3) ||
cs2(1,0) != tmat_(1,2) || cs2(1,1) != tmat_(1,3) ||
cs2(2,0) != tmat_(2,2) || cs2(2,1) != tmat_(2,3) ||
cs2(3,0) != tmat_(3,2) || cs2(3,1) != tmat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an explicit column selection
{
auto cs1 = blaze::columns( tmat_, { 0, 3, 2 } );
const std::array<size_t,2UL> indices{ 2, 1 };
auto cs2 = blaze::columns( cs1, indices );
if( cs2.rows() != tmat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != tmat_(0,2) || cs2(0,1) != tmat_(0,3) ||
cs2(1,0) != tmat_(1,2) || cs2(1,1) != tmat_(1,3) ||
cs2(2,0) != tmat_(2,2) || cs2(2,1) != tmat_(2,3) ||
cs2(3,0) != tmat_(3,2) || cs2(3,1) != tmat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an implicit column selection
{
const std::array<size_t,3UL> indices1{ 0, 3, 2 };
auto cs1 = blaze::columns( tmat_, [indices1]( size_t i ){ return indices1[i]; }, 3UL );
const std::array<size_t,2UL> indices{ 2, 1 };
auto cs2 = blaze::columns( cs1, indices );
if( cs2.rows() != tmat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != tmat_(0,2) || cs2(0,1) != tmat_(0,3) ||
cs2(1,0) != tmat_(1,2) || cs2(1,1) != tmat_(1,3) ||
cs2(2,0) != tmat_(2,2) || cs2(2,1) != tmat_(2,3) ||
cs2(3,0) != tmat_(3,2) || cs2(3,1) != tmat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major setup via lambda expression
//=====================================================================================
{
test_ = "Column-major Columns constructor (lambda expression)";
initialize();
// Setup of empty column selection
{
auto cs = blaze::columns( tmat_, []( size_t ){ return 0UL; }, 0UL );
if( cs.rows() != tmat_.rows() || cs.columns() != 0UL ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of empty column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a regular column selection
{
const std::array<size_t,3UL> indices{ 0, 3, 2 };
auto cs = blaze::columns( tmat_, [indices]( size_t i ){ return indices[i]; }, 3UL );
if( cs.rows() != tmat_.rows() || cs.columns() != 3UL ||
cs(0,0) != tmat_(0,0) || cs(0,1) != tmat_(0,3) || cs(0,2) != tmat_(0,2) ||
cs(1,0) != tmat_(1,0) || cs(1,1) != tmat_(1,3) || cs(1,2) != tmat_(1,2) ||
cs(2,0) != tmat_(2,0) || cs(2,1) != tmat_(2,3) || cs(2,2) != tmat_(2,2) ||
cs(3,0) != tmat_(3,0) || cs(3,1) != tmat_(3,3) || cs(3,2) != tmat_(3,2) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// Trying to setup an out-of-bounds column selection
try {
auto cs = blaze::columns( tmat_, []( size_t ){ return 5UL; }, 1UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds column selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
// Setup of a column selection on a compile-time column selection
{
auto cs1 = blaze::columns( tmat_, index_sequence<0,3,2>() );
const std::array<size_t,2UL> indices{ 2, 1 };
auto cs2 = blaze::columns( cs1, [indices]( size_t i ){ return indices[i]; }, 2UL );
if( cs2.rows() != tmat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != tmat_(0,2) || cs2(0,1) != tmat_(0,3) ||
cs2(1,0) != tmat_(1,2) || cs2(1,1) != tmat_(1,3) ||
cs2(2,0) != tmat_(2,2) || cs2(2,1) != tmat_(2,3) ||
cs2(3,0) != tmat_(3,2) || cs2(3,1) != tmat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an explicit column selection
{
auto cs1 = blaze::columns( tmat_, { 0, 3, 2 } );
const std::array<size_t,2UL> indices{ 2, 1 };
auto cs2 = blaze::columns( cs1, [indices]( size_t i ){ return indices[i]; }, 2UL );
if( cs2.rows() != tmat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != tmat_(0,2) || cs2(0,1) != tmat_(0,3) ||
cs2(1,0) != tmat_(1,2) || cs2(1,1) != tmat_(1,3) ||
cs2(2,0) != tmat_(2,2) || cs2(2,1) != tmat_(2,3) ||
cs2(3,0) != tmat_(3,2) || cs2(3,1) != tmat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// Setup of a column selection on an implicit column selection
{
const std::array<size_t,3UL> indices1{ 0, 3, 2 };
auto cs1 = blaze::columns( tmat_, [indices1]( size_t i ){ return indices1[i]; }, 3UL );
const std::array<size_t,2UL> indices2{ 2, 1 };
auto cs2 = blaze::columns( cs1, [indices2]( size_t i ){ return indices2[i]; }, 2UL );
if( cs2.rows() != tmat_.rows() || cs2.columns() != 2UL ||
cs2(0,0) != tmat_(0,2) || cs2(0,1) != tmat_(0,3) ||
cs2(1,0) != tmat_(1,2) || cs2(1,1) != tmat_(1,3) ||
cs2(2,0) != tmat_(2,2) || cs2(2,1) != tmat_(2,3) ||
cs2(3,0) != tmat_(3,2) || cs2(3,1) != tmat_(3,3) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major setup of random in-bounds element selection
//=====================================================================================
{
test_ = "Column-major Columns constructor (stress test)";
initialize();
for( size_t rep=0UL; rep<100UL; ++rep )
{
blaze::DynamicVector<size_t> indices( blaze::rand<size_t>( 1UL, 20UL ) );
randomize( indices, 0UL, tmat_.rows()-1UL );
auto cs = blaze::columns( tmat_, indices.data(), indices.size() );
for( size_t i=0UL; i<cs.rows(); ++i ) {
for( size_t j=0UL; j<cs.columns(); ++j ) {
if( cs(i,j) != tmat_(i,indices[j]) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of column selection failed\n"
<< " Details:\n"
<< " Indices:\n" << indices << "\n"
<< " Column selection:\n" << cs << "\n"
<< " Matrix:\n" << tmat_ << "\n";
throw std::runtime_error( oss.str() );
}
}
}
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the Columns assignment operators.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of all assignment operators of the Columns specialization.
// In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseSymmetricTest::testAssignment()
{
//=====================================================================================
// Row-major homogeneous assignment
//=====================================================================================
{
test_ = "Row-major Columns homogeneous assignment";
initialize();
auto cs = blaze::columns( mat_, { 3UL, 1UL } );
cs = 12;
checkRows ( cs , 4UL );
checkColumns ( cs , 2UL );
checkNonZeros( cs , 8UL );
checkRows ( mat_, 4UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 13UL );
if( cs(0,0) != 12 || cs(0,1) != 12 ||
cs(1,0) != 12 || cs(1,1) != 12 ||
cs(2,0) != 12 || cs(2,1) != 12 ||
cs(3,0) != 12 || cs(3,1) != 12 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 12 12 )\n( 12 12 )\n( 12 12 )\n( 12 12 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 12 || mat_(0,2) != 0 || mat_(0,3) != 12 ||
mat_(1,0) != 12 || mat_(1,1) != 12 || mat_(1,2) != 12 || mat_(1,3) != 12 ||
mat_(2,0) != 0 || mat_(2,1) != 12 || mat_(2,2) != 3 || mat_(2,3) != 12 ||
mat_(3,0) != 12 || mat_(3,1) != 12 || mat_(3,2) != 12 || mat_(3,3) != 12 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 12 0 12 )\n"
"( 12 12 12 12 )\n"
"( 0 12 3 12 )\n"
"( 12 12 12 12 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major homogeneous assignment
//=====================================================================================
{
test_ = "Column-major Columns homogeneous assignment";
initialize();
auto cs = blaze::columns( tmat_, { 3UL, 1UL } );
cs = 12;
checkRows ( cs , 4UL );
checkColumns ( cs , 2UL );
checkNonZeros( cs , 8UL );
checkRows ( tmat_, 4UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 13UL );
if( cs(0,0) != 12 || cs(0,1) != 12 ||
cs(1,0) != 12 || cs(1,1) != 12 ||
cs(2,0) != 12 || cs(2,1) != 12 ||
cs(3,0) != 12 || cs(3,1) != 12 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 12 12 )\n( 12 12 )\n( 12 12 )\n( 12 12 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 12 || tmat_(0,2) != 0 || tmat_(0,3) != 12 ||
tmat_(1,0) != 12 || tmat_(1,1) != 12 || tmat_(1,2) != 12 || tmat_(1,3) != 12 ||
tmat_(2,0) != 0 || tmat_(2,1) != 12 || tmat_(2,2) != 3 || tmat_(2,3) != 12 ||
tmat_(3,0) != 12 || tmat_(3,1) != 12 || tmat_(3,2) != 12 || tmat_(3,3) != 12 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 12 0 12 )\n"
"( 12 12 12 12 )\n"
"( 0 12 3 12 )\n"
"( 12 12 12 12 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the Columns function call operator.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of adding and accessing elements via the function call operator
// of the Columns specialization. In case an error is detected, a \a std::runtime_error exception
// is thrown.
*/
void DenseSymmetricTest::testFunctionCall()
{
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
test_ = "Row-major Columns::operator()";
initialize();
auto cs = blaze::columns( mat_, { 1UL, 2UL, 3UL } );
// Assignment to the element (1,1)
{
cs(1,1) = 9;
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 9UL );
checkNonZeros( cs , 0UL, 3UL );
checkNonZeros( cs , 1UL, 3UL );
checkNonZeros( cs , 2UL, 3UL );
checkRows ( mat_, 4UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 9UL );
if( cs(0,0) != 0 || cs(0,1) != 0 || cs(0,2) != 0 ||
cs(1,0) != 1 || cs(1,1) != 9 || cs(1,2) != -2 ||
cs(2,0) != 9 || cs(2,1) != 3 || cs(2,2) != 4 ||
cs(3,0) != -2 || cs(3,1) != 4 || cs(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 1 9 -2 )\n( 9 3 4 )\n( -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 1 || mat_(1,2) != 9 || mat_(1,3) != -2 ||
mat_(2,0) != 0 || mat_(2,1) != 9 || mat_(2,2) != 3 || mat_(2,3) != 4 ||
mat_(3,0) != 0 || mat_(3,1) != -2 || mat_(3,2) != 4 || mat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 1 9 -2 )\n"
"( 0 9 3 4 )\n"
"( 0 -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Assignment to the element (1,2)
{
cs(1,2) = 0;
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 7UL );
checkNonZeros( cs , 0UL, 2UL );
checkNonZeros( cs , 1UL, 3UL );
checkNonZeros( cs , 2UL, 2UL );
checkRows ( mat_, 4UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 7UL );
if( cs(0,0) != 0 || cs(0,1) != 0 || cs(0,2) != 0 ||
cs(1,0) != 1 || cs(1,1) != 9 || cs(1,2) != 0 ||
cs(2,0) != 9 || cs(2,1) != 3 || cs(2,2) != 4 ||
cs(3,0) != 0 || cs(3,1) != 4 || cs(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 1 9 0 )\n( 9 3 4 )\n( 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 1 || mat_(1,2) != 9 || mat_(1,3) != 0 ||
mat_(2,0) != 0 || mat_(2,1) != 9 || mat_(2,2) != 3 || mat_(2,3) != 4 ||
mat_(3,0) != 0 || mat_(3,1) != 0 || mat_(3,2) != 4 || mat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 1 9 0 )\n"
"( 0 9 3 4 )\n"
"( 0 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Assignment to the element (2,1)
{
cs(2,1) = 11;
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 7UL );
checkNonZeros( cs , 0UL, 2UL );
checkNonZeros( cs , 1UL, 3UL );
checkNonZeros( cs , 2UL, 2UL );
checkRows ( mat_, 4UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 7UL );
if( cs(0,0) != 0 || cs(0,1) != 0 || cs(0,2) != 0 ||
cs(1,0) != 1 || cs(1,1) != 9 || cs(1,2) != 0 ||
cs(2,0) != 9 || cs(2,1) != 11 || cs(2,2) != 4 ||
cs(3,0) != 0 || cs(3,1) != 4 || cs(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 1 9 0 )\n( 9 11 4 )\n( 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 1 || mat_(1,2) != 9 || mat_(1,3) != 0 ||
mat_(2,0) != 0 || mat_(2,1) != 9 || mat_(2,2) != 11 || mat_(2,3) != 4 ||
mat_(3,0) != 0 || mat_(3,1) != 0 || mat_(3,2) != 4 || mat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 1 9 0 )\n"
"( 0 9 11 4 )\n"
"( 0 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Addition assignment to the element (1,0)
{
cs(1,0) += 3;
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 7UL );
checkNonZeros( cs , 0UL, 2UL );
checkNonZeros( cs , 1UL, 3UL );
checkNonZeros( cs , 2UL, 2UL );
checkRows ( mat_, 4UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 7UL );
if( cs(0,0) != 0 || cs(0,1) != 0 || cs(0,2) != 0 ||
cs(1,0) != 4 || cs(1,1) != 9 || cs(1,2) != 0 ||
cs(2,0) != 9 || cs(2,1) != 11 || cs(2,2) != 4 ||
cs(3,0) != 0 || cs(3,1) != 4 || cs(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 4 9 0 )\n( 9 11 4 )\n( 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 4 || mat_(1,2) != 9 || mat_(1,3) != 0 ||
mat_(2,0) != 0 || mat_(2,1) != 9 || mat_(2,2) != 11 || mat_(2,3) != 4 ||
mat_(3,0) != 0 || mat_(3,1) != 0 || mat_(3,2) != 4 || mat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 4 9 0 )\n"
"( 0 9 11 4 )\n"
"( 0 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Subtraction assignment to the element (2,0)
{
cs(2,0) -= 6;
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 7UL );
checkNonZeros( cs , 0UL, 2UL );
checkNonZeros( cs , 1UL, 3UL );
checkNonZeros( cs , 2UL, 2UL );
checkRows ( mat_, 4UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 7UL );
if( cs(0,0) != 0 || cs(0,1) != 0 || cs(0,2) != 0 ||
cs(1,0) != 4 || cs(1,1) != 3 || cs(1,2) != 0 ||
cs(2,0) != 3 || cs(2,1) != 11 || cs(2,2) != 4 ||
cs(3,0) != 0 || cs(3,1) != 4 || cs(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 4 3 0 )\n( 3 11 4 )\n( 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 4 || mat_(1,2) != 3 || mat_(1,3) != 0 ||
mat_(2,0) != 0 || mat_(2,1) != 3 || mat_(2,2) != 11 || mat_(2,3) != 4 ||
mat_(3,0) != 0 || mat_(3,1) != 0 || mat_(3,2) != 4 || mat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 4 3 0 )\n"
"( 0 3 11 4 )\n"
"( 0 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Multiplication assignment to the element (2,1)
{
cs(2,1) *= 2;
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 7UL );
checkNonZeros( cs , 0UL, 2UL );
checkNonZeros( cs , 1UL, 3UL );
checkNonZeros( cs , 2UL, 2UL );
checkRows ( mat_, 4UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 7UL );
if( cs(0,0) != 0 || cs(0,1) != 0 || cs(0,2) != 0 ||
cs(1,0) != 4 || cs(1,1) != 3 || cs(1,2) != 0 ||
cs(2,0) != 3 || cs(2,1) != 22 || cs(2,2) != 4 ||
cs(3,0) != 0 || cs(3,1) != 4 || cs(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 4 3 0 )\n( 3 22 4 )\n( 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 4 || mat_(1,2) != 3 || mat_(1,3) != 0 ||
mat_(2,0) != 0 || mat_(2,1) != 3 || mat_(2,2) != 22 || mat_(2,3) != 4 ||
mat_(3,0) != 0 || mat_(3,1) != 0 || mat_(3,2) != 4 || mat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 4 3 0 )\n"
"( 0 3 22 4 )\n"
"( 0 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Division assignment to the element (2,1)
{
cs(2,1) /= 2;
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 7UL );
checkNonZeros( cs , 0UL, 2UL );
checkNonZeros( cs , 1UL, 3UL );
checkNonZeros( cs , 2UL, 2UL );
checkRows ( mat_, 4UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 7UL );
if( cs(0,0) != 0 || cs(0,1) != 0 || cs(0,2) != 0 ||
cs(1,0) != 4 || cs(1,1) != 3 || cs(1,2) != 0 ||
cs(2,0) != 3 || cs(2,1) != 11 || cs(2,2) != 4 ||
cs(3,0) != 0 || cs(3,1) != 4 || cs(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 4 3 0 )\n( 3 11 4 )\n( 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 4 || mat_(1,2) != 3 || mat_(1,3) != 0 ||
mat_(2,0) != 0 || mat_(2,1) != 3 || mat_(2,2) != 11 || mat_(2,3) != 4 ||
mat_(3,0) != 0 || mat_(3,1) != 0 || mat_(3,2) != 4 || mat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 4 3 0 )\n"
"( 0 3 11 4 )\n"
"( 0 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
test_ = "Column-major Columns::operator()";
initialize();
auto cs = blaze::columns( tmat_, { 1UL, 2UL, 3UL } );
// Assignment to the element (1,1)
{
cs(1,1) = 9;
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 9UL );
checkNonZeros( cs , 0UL, 3UL );
checkNonZeros( cs , 1UL, 3UL );
checkNonZeros( cs , 2UL, 3UL );
checkRows ( tmat_, 4UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 9UL );
if( cs(0,0) != 0 || cs(0,1) != 0 || cs(0,2) != 0 ||
cs(1,0) != 1 || cs(1,1) != 9 || cs(1,2) != -2 ||
cs(2,0) != 9 || cs(2,1) != 3 || cs(2,2) != 4 ||
cs(3,0) != -2 || cs(3,1) != 4 || cs(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 1 9 -2 )\n( 9 3 4 )\n( -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 1 || tmat_(1,2) != 9 || tmat_(1,3) != -2 ||
tmat_(2,0) != 0 || tmat_(2,1) != 9 || tmat_(2,2) != 3 || tmat_(2,3) != 4 ||
tmat_(3,0) != 0 || tmat_(3,1) != -2 || tmat_(3,2) != 4 || tmat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 1 9 -2 )\n"
"( 0 9 3 4 )\n"
"( 0 -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Assignment to the element (1,2)
{
cs(1,2) = 0;
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 7UL );
checkNonZeros( cs , 0UL, 2UL );
checkNonZeros( cs , 1UL, 3UL );
checkNonZeros( cs , 2UL, 2UL );
checkRows ( tmat_, 4UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 7UL );
if( cs(0,0) != 0 || cs(0,1) != 0 || cs(0,2) != 0 ||
cs(1,0) != 1 || cs(1,1) != 9 || cs(1,2) != 0 ||
cs(2,0) != 9 || cs(2,1) != 3 || cs(2,2) != 4 ||
cs(3,0) != 0 || cs(3,1) != 4 || cs(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 1 9 0 )\n( 9 3 4 )\n( 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 1 || tmat_(1,2) != 9 || tmat_(1,3) != 0 ||
tmat_(2,0) != 0 || tmat_(2,1) != 9 || tmat_(2,2) != 3 || tmat_(2,3) != 4 ||
tmat_(3,0) != 0 || tmat_(3,1) != 0 || tmat_(3,2) != 4 || tmat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 1 9 0 )\n"
"( 0 9 3 4 )\n"
"( 0 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Assignment to the element (2,1)
{
cs(2,1) = 11;
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 7UL );
checkNonZeros( cs , 0UL, 2UL );
checkNonZeros( cs , 1UL, 3UL );
checkNonZeros( cs , 2UL, 2UL );
checkRows ( tmat_, 4UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 7UL );
if( cs(0,0) != 0 || cs(0,1) != 0 || cs(0,2) != 0 ||
cs(1,0) != 1 || cs(1,1) != 9 || cs(1,2) != 0 ||
cs(2,0) != 9 || cs(2,1) != 11 || cs(2,2) != 4 ||
cs(3,0) != 0 || cs(3,1) != 4 || cs(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 1 9 0 )\n( 9 11 4 )\n( 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 1 || tmat_(1,2) != 9 || tmat_(1,3) != 0 ||
tmat_(2,0) != 0 || tmat_(2,1) != 9 || tmat_(2,2) != 11 || tmat_(2,3) != 4 ||
tmat_(3,0) != 0 || tmat_(3,1) != 0 || tmat_(3,2) != 4 || tmat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 1 9 0 )\n"
"( 0 9 11 4 )\n"
"( 0 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Addition assignment to the element (1,0)
{
cs(1,0) += 3;
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 7UL );
checkNonZeros( cs , 0UL, 2UL );
checkNonZeros( cs , 1UL, 3UL );
checkNonZeros( cs , 2UL, 2UL );
checkRows ( tmat_, 4UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 7UL );
if( cs(0,0) != 0 || cs(0,1) != 0 || cs(0,2) != 0 ||
cs(1,0) != 4 || cs(1,1) != 9 || cs(1,2) != 0 ||
cs(2,0) != 9 || cs(2,1) != 11 || cs(2,2) != 4 ||
cs(3,0) != 0 || cs(3,1) != 4 || cs(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 4 9 0 )\n( 9 11 4 )\n( 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 4 || tmat_(1,2) != 9 || tmat_(1,3) != 0 ||
tmat_(2,0) != 0 || tmat_(2,1) != 9 || tmat_(2,2) != 11 || tmat_(2,3) != 4 ||
tmat_(3,0) != 0 || tmat_(3,1) != 0 || tmat_(3,2) != 4 || tmat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 4 9 0 )\n"
"( 0 9 11 4 )\n"
"( 0 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Subtraction assignment to the element (2,0)
{
cs(2,0) -= 6;
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 7UL );
checkNonZeros( cs , 0UL, 2UL );
checkNonZeros( cs , 1UL, 3UL );
checkNonZeros( cs , 2UL, 2UL );
checkRows ( tmat_, 4UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 7UL );
if( cs(0,0) != 0 || cs(0,1) != 0 || cs(0,2) != 0 ||
cs(1,0) != 4 || cs(1,1) != 3 || cs(1,2) != 0 ||
cs(2,0) != 3 || cs(2,1) != 11 || cs(2,2) != 4 ||
cs(3,0) != 0 || cs(3,1) != 4 || cs(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 4 3 0 )\n( 3 11 4 )\n( 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 4 || tmat_(1,2) != 3 || tmat_(1,3) != 0 ||
tmat_(2,0) != 0 || tmat_(2,1) != 3 || tmat_(2,2) != 11 || tmat_(2,3) != 4 ||
tmat_(3,0) != 0 || tmat_(3,1) != 0 || tmat_(3,2) != 4 || tmat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 4 3 0 )\n"
"( 0 3 11 4 )\n"
"( 0 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Multiplication assignment to the element (2,1)
{
cs(2,1) *= 2;
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 7UL );
checkNonZeros( cs , 0UL, 2UL );
checkNonZeros( cs , 1UL, 3UL );
checkNonZeros( cs , 2UL, 2UL );
checkRows ( tmat_, 4UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 7UL );
if( cs(0,0) != 0 || cs(0,1) != 0 || cs(0,2) != 0 ||
cs(1,0) != 4 || cs(1,1) != 3 || cs(1,2) != 0 ||
cs(2,0) != 3 || cs(2,1) != 22 || cs(2,2) != 4 ||
cs(3,0) != 0 || cs(3,1) != 4 || cs(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 4 3 0 )\n( 3 22 4 )\n( 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 4 || tmat_(1,2) != 3 || tmat_(1,3) != 0 ||
tmat_(2,0) != 0 || tmat_(2,1) != 3 || tmat_(2,2) != 22 || tmat_(2,3) != 4 ||
tmat_(3,0) != 0 || tmat_(3,1) != 0 || tmat_(3,2) != 4 || tmat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 4 3 0 )\n"
"( 0 3 22 4 )\n"
"( 0 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Division assignment to the element (2,1)
{
cs(2,1) /= 2;
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 7UL );
checkNonZeros( cs , 0UL, 2UL );
checkNonZeros( cs , 1UL, 3UL );
checkNonZeros( cs , 2UL, 2UL );
checkRows ( tmat_, 4UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 7UL );
if( cs(0,0) != 0 || cs(0,1) != 0 || cs(0,2) != 0 ||
cs(1,0) != 4 || cs(1,1) != 3 || cs(1,2) != 0 ||
cs(2,0) != 3 || cs(2,1) != 11 || cs(2,2) != 4 ||
cs(3,0) != 0 || cs(3,1) != 4 || cs(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 4 3 0 )\n( 3 11 4 )\n( 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 4 || tmat_(1,2) != 3 || tmat_(1,3) != 0 ||
tmat_(2,0) != 0 || tmat_(2,1) != 3 || tmat_(2,2) != 11 || tmat_(2,3) != 4 ||
tmat_(3,0) != 0 || tmat_(3,1) != 0 || tmat_(3,2) != 4 || tmat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 4 3 0 )\n"
"( 0 3 11 4 )\n"
"( 0 0 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the Columns iterator implementation.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the iterator implementation of the Columns specialization.
// In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseSymmetricTest::testIterator()
{
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
initialize();
// Testing the Iterator default constructor
{
test_ = "Row-major Iterator default constructor";
CT::Iterator it{};
if( it != CT::Iterator() ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed iterator default constructor\n";
throw std::runtime_error( oss.str() );
}
}
// Testing the ConstIterator default constructor
{
test_ = "Row-major ConstIterator default constructor";
CT::ConstIterator it{};
if( it != CT::ConstIterator() ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed iterator default constructor\n";
throw std::runtime_error( oss.str() );
}
}
// Testing conversion from Iterator to ConstIterator
{
test_ = "Row-major Iterator/ConstIterator conversion";
auto cs = blaze::columns( mat_, { 2UL } );
auto it( begin( cs, 0UL ) );
if( it == end( cs, 0UL ) || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed iterator conversion detected\n";
throw std::runtime_error( oss.str() );
}
}
// Counting the number of elements in 1st column via Iterator (end-begin)
{
test_ = "Row-major Iterator subtraction (end-begin)";
auto cs = blaze::columns( mat_, { 1UL } );
const ptrdiff_t number( end( cs, 0UL ) - begin( cs, 0UL ) );
if( number != 4L ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid number of elements detected\n"
<< " Details:\n"
<< " Number of elements : " << number << "\n"
<< " Expected number of elements: 4\n";
throw std::runtime_error( oss.str() );
}
}
// Counting the number of elements in 1st column via Iterator (begin-end)
{
test_ = "Row-major Iterator subtraction (begin-end)";
auto cs = blaze::columns( mat_, { 1UL } );
const ptrdiff_t number( begin( cs, 0UL ) - end( cs, 0UL ) );
if( number != -4L ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid number of elements detected\n"
<< " Details:\n"
<< " Number of elements : " << number << "\n"
<< " Expected number of elements: -4\n";
throw std::runtime_error( oss.str() );
}
}
// Counting the number of elements in 2nd column via ConstIterator (end-begin)
{
test_ = "Row-major ConstIterator subtraction (end-begin)";
auto cs = blaze::columns( mat_, { 2UL } );
const ptrdiff_t number( cend( cs, 0UL ) - cbegin( cs, 0UL ) );
if( number != 4L ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid number of elements detected\n"
<< " Details:\n"
<< " Number of elements : " << number << "\n"
<< " Expected number of elements: 4\n";
throw std::runtime_error( oss.str() );
}
}
// Counting the number of elements in 2nd column via ConstIterator (begin-end)
{
test_ = "Row-major ConstIterator subtraction (begin-end)";
auto cs = blaze::columns( mat_, { 2UL } );
const ptrdiff_t number( cbegin( cs, 0UL ) - cend( cs, 0UL ) );
if( number != -4L ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid number of elements detected\n"
<< " Details:\n"
<< " Number of elements : " << number << "\n"
<< " Expected number of elements: -4\n";
throw std::runtime_error( oss.str() );
}
}
// Testing read-only access via ConstIterator
{
test_ = "Row-major read-only access via ConstIterator";
auto cs = blaze::columns( mat_, { 3UL } );
auto it ( cbegin( cs, 0UL ) );
auto end( cend( cs, 0UL ) );
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid initial iterator detected\n";
throw std::runtime_error( oss.str() );
}
++it;
if( it == end || *it != -2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator pre-increment failed\n";
throw std::runtime_error( oss.str() );
}
--it;
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator pre-decrement failed\n";
throw std::runtime_error( oss.str() );
}
it++;
if( it == end || *it != -2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator post-increment failed\n";
throw std::runtime_error( oss.str() );
}
it--;
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator post-decrement failed\n";
throw std::runtime_error( oss.str() );
}
it += 2UL;
if( it == end || *it != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator addition assignment failed\n";
throw std::runtime_error( oss.str() );
}
it -= 2UL;
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator subtraction assignment failed\n";
throw std::runtime_error( oss.str() );
}
it = it + 3UL;
if( it == end || *it != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator/scalar addition failed\n";
throw std::runtime_error( oss.str() );
}
it = it - 3UL;
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator/scalar subtraction failed\n";
throw std::runtime_error( oss.str() );
}
it = 4UL + it;
if( it != end ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Scalar/iterator addition failed\n";
throw std::runtime_error( oss.str() );
}
}
// Testing assignment via Iterator
{
test_ = "Row-major assignment via Iterator";
auto cs = blaze::columns( mat_, { 0UL } );
int value = 6;
for( auto it=begin( cs, 0UL ); it!=end( cs, 0UL ); ++it ) {
*it = value++;
}
if( cs(0,0) != 6 || cs(1,0) != 7 || cs(2,0) != 8 || cs(3,0) != 9 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 6 7 8 9 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 6 || mat_(0,1) != 7 || mat_(0,2) != 8 || mat_(0,3) != 9 ||
mat_(1,0) != 7 || mat_(1,1) != 1 || mat_(1,2) != 0 || mat_(1,3) != -2 ||
mat_(2,0) != 8 || mat_(2,1) != 0 || mat_(2,2) != 3 || mat_(2,3) != 4 ||
mat_(3,0) != 9 || mat_(3,1) != -2 || mat_(3,2) != 4 || mat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 6 7 8 9 )\n"
"( 7 1 0 -2 )\n"
"( 8 0 3 4 )\n"
"( 9 -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Testing addition assignment via Iterator
{
test_ = "Row-major addition assignment via Iterator";
auto cs = blaze::columns( mat_, { 0UL } );
int value = 2;
for( auto it=begin( cs, 0UL ); it!=end( cs, 0UL ); ++it ) {
*it += value++;
}
if( cs(0,0) != 8 || cs(1,0) != 10 || cs(2,0) != 12 || cs(3,0) != 14 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 8 10 12 14 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 8 || mat_(0,1) != 10 || mat_(0,2) != 12 || mat_(0,3) != 14 ||
mat_(1,0) != 10 || mat_(1,1) != 1 || mat_(1,2) != 0 || mat_(1,3) != -2 ||
mat_(2,0) != 12 || mat_(2,1) != 0 || mat_(2,2) != 3 || mat_(2,3) != 4 ||
mat_(3,0) != 14 || mat_(3,1) != -2 || mat_(3,2) != 4 || mat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 8 10 12 14 )\n"
"( 10 1 0 -2 )\n"
"( 12 0 3 4 )\n"
"( 14 -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Testing subtraction assignment via Iterator
{
test_ = "Row-major subtraction assignment via Iterator";
auto cs = blaze::columns( mat_, { 0UL } );
int value = 2;
for( auto it=begin( cs, 0UL ); it!=end( cs, 0UL ); ++it ) {
*it -= value++;
}
if( cs(0,0) != 6 || cs(1,0) != 7 || cs(2,0) != 8 || cs(3,0) != 9 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 6 7 8 9 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 6 || mat_(0,1) != 7 || mat_(0,2) != 8 || mat_(0,3) != 9 ||
mat_(1,0) != 7 || mat_(1,1) != 1 || mat_(1,2) != 0 || mat_(1,3) != -2 ||
mat_(2,0) != 8 || mat_(2,1) != 0 || mat_(2,2) != 3 || mat_(2,3) != 4 ||
mat_(3,0) != 9 || mat_(3,1) != -2 || mat_(3,2) != 4 || mat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 6 7 8 9 )\n"
"( 7 1 0 -2 )\n"
"( 8 0 3 4 )\n"
"( 9 -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Testing multiplication assignment via Iterator
{
test_ = "Row-major multiplication assignment via Iterator";
auto cs = blaze::columns( mat_, { 0UL } );
int value = 1;
for( auto it=begin( cs, 0UL ); it!=end( cs, 0UL ); ++it ) {
*it *= value++;
}
if( cs(0,0) != 6 || cs(1,0) != 14 || cs(2,0) != 24 || cs(3,0) != 36 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 6 14 24 36 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 6 || mat_(0,1) != 14 || mat_(0,2) != 24 || mat_(0,3) != 36 ||
mat_(1,0) != 14 || mat_(1,1) != 1 || mat_(1,2) != 0 || mat_(1,3) != -2 ||
mat_(2,0) != 24 || mat_(2,1) != 0 || mat_(2,2) != 3 || mat_(2,3) != 4 ||
mat_(3,0) != 36 || mat_(3,1) != -2 || mat_(3,2) != 4 || mat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 6 14 24 36 )\n"
"( 14 1 0 -2 )\n"
"( 24 0 3 4 )\n"
"( 36 -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Testing division assignment via Iterator
{
test_ = "Row-major division assignment via Iterator";
auto cs = blaze::columns( mat_, { 0UL } );
for( auto it=begin( cs, 0UL ); it!=end( cs, 0UL ); ++it ) {
*it /= 2;
}
if( cs(0,0) != 3 || cs(1,0) != 7 || cs(2,0) != 12 || cs(3,0) != 18 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 6 14 24 36 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 3 || mat_(0,1) != 7 || mat_(0,2) != 12 || mat_(0,3) != 18 ||
mat_(1,0) != 7 || mat_(1,1) != 1 || mat_(1,2) != 0 || mat_(1,3) != -2 ||
mat_(2,0) != 12 || mat_(2,1) != 0 || mat_(2,2) != 3 || mat_(2,3) != 4 ||
mat_(3,0) != 18 || mat_(3,1) != -2 || mat_(3,2) != 4 || mat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 3 7 12 18 )\n"
"( 7 1 0 -2 )\n"
"( 12 0 3 4 )\n"
"( 18 -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
initialize();
// Testing the Iterator default constructor
{
test_ = "Row-major Iterator default constructor";
OCT::Iterator it{};
if( it != OCT::Iterator() ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed iterator default constructor\n";
throw std::runtime_error( oss.str() );
}
}
// Testing the ConstIterator default constructor
{
test_ = "Row-major ConstIterator default constructor";
OCT::ConstIterator it{};
if( it != OCT::ConstIterator() ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed iterator default constructor\n";
throw std::runtime_error( oss.str() );
}
}
// Testing conversion from Iterator to ConstIterator
{
test_ = "Row-major Iterator/ConstIterator conversion";
auto cs = blaze::columns( tmat_, { 2UL } );
auto it( begin( cs, 0UL ) );
if( it == end( cs, 0UL ) || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Failed iterator conversion detected\n";
throw std::runtime_error( oss.str() );
}
}
// Counting the number of elements in 1st column via Iterator (end-begin)
{
test_ = "Row-major Iterator subtraction (end-begin)";
auto cs = blaze::columns( tmat_, { 1UL } );
const ptrdiff_t number( end( cs, 0UL ) - begin( cs, 0UL ) );
if( number != 4L ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid number of elements detected\n"
<< " Details:\n"
<< " Number of elements : " << number << "\n"
<< " Expected number of elements: 4\n";
throw std::runtime_error( oss.str() );
}
}
// Counting the number of elements in 1st column via Iterator (begin-end)
{
test_ = "Row-major Iterator subtraction (begin-end)";
auto cs = blaze::columns( tmat_, { 1UL } );
const ptrdiff_t number( begin( cs, 0UL ) - end( cs, 0UL ) );
if( number != -4L ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid number of elements detected\n"
<< " Details:\n"
<< " Number of elements : " << number << "\n"
<< " Expected number of elements: -4\n";
throw std::runtime_error( oss.str() );
}
}
// Counting the number of elements in 2nd column via ConstIterator (end-begin)
{
test_ = "Row-major ConstIterator subtraction (end-begin)";
auto cs = blaze::columns( tmat_, { 2UL } );
const ptrdiff_t number( cend( cs, 0UL ) - cbegin( cs, 0UL ) );
if( number != 4L ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid number of elements detected\n"
<< " Details:\n"
<< " Number of elements : " << number << "\n"
<< " Expected number of elements: 4\n";
throw std::runtime_error( oss.str() );
}
}
// Counting the number of elements in 2nd column via ConstIterator (begin-end)
{
test_ = "Row-major ConstIterator subtraction (begin-end)";
auto cs = blaze::columns( tmat_, { 2UL } );
const ptrdiff_t number( cbegin( cs, 0UL ) - cend( cs, 0UL ) );
if( number != -4L ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid number of elements detected\n"
<< " Details:\n"
<< " Number of elements : " << number << "\n"
<< " Expected number of elements: -4\n";
throw std::runtime_error( oss.str() );
}
}
// Testing read-only access via ConstIterator
{
test_ = "Row-major read-only access via ConstIterator";
auto cs = blaze::columns( tmat_, { 3UL } );
auto it ( cbegin( cs, 0UL ) );
auto end( cend( cs, 0UL ) );
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid initial iterator detected\n";
throw std::runtime_error( oss.str() );
}
++it;
if( it == end || *it != -2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator pre-increment failed\n";
throw std::runtime_error( oss.str() );
}
--it;
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator pre-decrement failed\n";
throw std::runtime_error( oss.str() );
}
it++;
if( it == end || *it != -2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator post-increment failed\n";
throw std::runtime_error( oss.str() );
}
it--;
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator post-decrement failed\n";
throw std::runtime_error( oss.str() );
}
it += 2UL;
if( it == end || *it != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator addition assignment failed\n";
throw std::runtime_error( oss.str() );
}
it -= 2UL;
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator subtraction assignment failed\n";
throw std::runtime_error( oss.str() );
}
it = it + 3UL;
if( it == end || *it != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator/scalar addition failed\n";
throw std::runtime_error( oss.str() );
}
it = it - 3UL;
if( it == end || *it != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator/scalar subtraction failed\n";
throw std::runtime_error( oss.str() );
}
it = 4UL + it;
if( it != end ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Scalar/iterator addition failed\n";
throw std::runtime_error( oss.str() );
}
}
// Testing assignment via Iterator
{
test_ = "Row-major assignment via Iterator";
auto cs = blaze::columns( tmat_, { 0UL } );
int value = 6;
for( auto it=begin( cs, 0UL ); it!=end( cs, 0UL ); ++it ) {
*it = value++;
}
if( cs(0,0) != 6 || cs(1,0) != 7 || cs(2,0) != 8 || cs(3,0) != 9 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 6 7 8 9 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 6 || tmat_(0,1) != 7 || tmat_(0,2) != 8 || tmat_(0,3) != 9 ||
tmat_(1,0) != 7 || tmat_(1,1) != 1 || tmat_(1,2) != 0 || tmat_(1,3) != -2 ||
tmat_(2,0) != 8 || tmat_(2,1) != 0 || tmat_(2,2) != 3 || tmat_(2,3) != 4 ||
tmat_(3,0) != 9 || tmat_(3,1) != -2 || tmat_(3,2) != 4 || tmat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 6 7 8 9 )\n"
"( 7 1 0 -2 )\n"
"( 8 0 3 4 )\n"
"( 9 -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Testing addition assignment via Iterator
{
test_ = "Row-major addition assignment via Iterator";
auto cs = blaze::columns( tmat_, { 0UL } );
int value = 2;
for( auto it=begin( cs, 0UL ); it!=end( cs, 0UL ); ++it ) {
*it += value++;
}
if( cs(0,0) != 8 || cs(1,0) != 10 || cs(2,0) != 12 || cs(3,0) != 14 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 8 10 12 14 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 8 || tmat_(0,1) != 10 || tmat_(0,2) != 12 || tmat_(0,3) != 14 ||
tmat_(1,0) != 10 || tmat_(1,1) != 1 || tmat_(1,2) != 0 || tmat_(1,3) != -2 ||
tmat_(2,0) != 12 || tmat_(2,1) != 0 || tmat_(2,2) != 3 || tmat_(2,3) != 4 ||
tmat_(3,0) != 14 || tmat_(3,1) != -2 || tmat_(3,2) != 4 || tmat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 8 10 12 14 )\n"
"( 10 1 0 -2 )\n"
"( 12 0 3 4 )\n"
"( 14 -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Testing subtraction assignment via Iterator
{
test_ = "Row-major subtraction assignment via Iterator";
auto cs = blaze::columns( tmat_, { 0UL } );
int value = 2;
for( auto it=begin( cs, 0UL ); it!=end( cs, 0UL ); ++it ) {
*it -= value++;
}
if( cs(0,0) != 6 || cs(1,0) != 7 || cs(2,0) != 8 || cs(3,0) != 9 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 6 7 8 9 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 6 || tmat_(0,1) != 7 || tmat_(0,2) != 8 || tmat_(0,3) != 9 ||
tmat_(1,0) != 7 || tmat_(1,1) != 1 || tmat_(1,2) != 0 || tmat_(1,3) != -2 ||
tmat_(2,0) != 8 || tmat_(2,1) != 0 || tmat_(2,2) != 3 || tmat_(2,3) != 4 ||
tmat_(3,0) != 9 || tmat_(3,1) != -2 || tmat_(3,2) != 4 || tmat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 6 7 8 9 )\n"
"( 7 1 0 -2 )\n"
"( 8 0 3 4 )\n"
"( 9 -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Testing multiplication assignment via Iterator
{
test_ = "Row-major multiplication assignment via Iterator";
auto cs = blaze::columns( tmat_, { 0UL } );
int value = 1;
for( auto it=begin( cs, 0UL ); it!=end( cs, 0UL ); ++it ) {
*it *= value++;
}
if( cs(0,0) != 6 || cs(1,0) != 14 || cs(2,0) != 24 || cs(3,0) != 36 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 6 14 24 36 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 6 || tmat_(0,1) != 14 || tmat_(0,2) != 24 || tmat_(0,3) != 36 ||
tmat_(1,0) != 14 || tmat_(1,1) != 1 || tmat_(1,2) != 0 || tmat_(1,3) != -2 ||
tmat_(2,0) != 24 || tmat_(2,1) != 0 || tmat_(2,2) != 3 || tmat_(2,3) != 4 ||
tmat_(3,0) != 36 || tmat_(3,1) != -2 || tmat_(3,2) != 4 || tmat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 6 14 24 36 )\n"
"( 14 1 0 -2 )\n"
"( 24 0 3 4 )\n"
"( 36 -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
// Testing division assignment via Iterator
{
test_ = "Row-major division assignment via Iterator";
auto cs = blaze::columns( tmat_, { 0UL } );
for( auto it=begin( cs, 0UL ); it!=end( cs, 0UL ); ++it ) {
*it /= 2;
}
if( cs(0,0) != 3 || cs(1,0) != 7 || cs(2,0) != 12 || cs(3,0) != 18 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 6 14 24 36 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 3 || tmat_(0,1) != 7 || tmat_(0,2) != 12 || tmat_(0,3) != 18 ||
tmat_(1,0) != 7 || tmat_(1,1) != 1 || tmat_(1,2) != 0 || tmat_(1,3) != -2 ||
tmat_(2,0) != 12 || tmat_(2,1) != 0 || tmat_(2,2) != 3 || tmat_(2,3) != 4 ||
tmat_(3,0) != 18 || tmat_(3,1) != -2 || tmat_(3,2) != 4 || tmat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Assignment via iterator failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 3 7 12 18 )\n"
"( 7 1 0 -2 )\n"
"( 12 0 3 4 )\n"
"( 18 -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c nonZeros() member function of the Columns class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c nonZeros() member function of the Columns specialization.
// In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseSymmetricTest::testNonZeros()
{
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
test_ = "Row-major Columns::nonZeros()";
initialize();
// Initialization check
auto cs = blaze::columns( mat_, { 1UL, 2UL } );
checkRows ( cs, 4UL );
checkColumns ( cs, 2UL );
checkNonZeros( cs, 4UL );
checkNonZeros( cs, 0UL, 2UL );
checkNonZeros( cs, 1UL, 2UL );
if( cs(0,0) != 0 || cs(0,1) != 0 ||
cs(1,0) != 1 || cs(1,1) != 0 ||
cs(2,0) != 0 || cs(2,1) != 3 ||
cs(3,0) != -2 || cs(3,1) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 )\n( 1 0 )\n( 0 3 )\n( -2 4 )\n";
throw std::runtime_error( oss.str() );
}
// Changing the number of non-zeros via the column selection
cs(2,1) = 0;
checkRows ( cs, 4UL );
checkColumns ( cs, 2UL );
checkNonZeros( cs, 3UL );
checkNonZeros( cs, 0UL, 2UL );
checkNonZeros( cs, 1UL, 1UL );
if( cs(0,0) != 0 || cs(0,1) != 0 ||
cs(1,0) != 1 || cs(1,1) != 0 ||
cs(2,0) != 0 || cs(2,1) != 0 ||
cs(3,0) != -2 || cs(3,1) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 )\n( 1 0 )\n( 0 0 )\n( -2 4 )\n";
throw std::runtime_error( oss.str() );
}
// Changing the number of non-zeros via the dense matrix
mat_(3,2) = 5;
checkRows ( cs, 4UL );
checkColumns ( cs, 2UL );
checkNonZeros( cs, 3UL );
checkNonZeros( cs, 0UL, 2UL );
checkNonZeros( cs, 1UL, 1UL );
if( cs(0,0) != 0 || cs(0,1) != 0 ||
cs(1,0) != 1 || cs(1,1) != 0 ||
cs(2,0) != 0 || cs(2,1) != 0 ||
cs(3,0) != -2 || cs(3,1) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 )\n( 1 0 )\n( 0 0 )\n( -2 5 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
test_ = "Column-major Columns::nonZeros()";
initialize();
// Initialization check
auto cs = blaze::columns( tmat_, { 1UL, 2UL } );
checkRows ( cs, 4UL );
checkColumns ( cs, 2UL );
checkNonZeros( cs, 4UL );
checkNonZeros( cs, 0UL, 2UL );
checkNonZeros( cs, 1UL, 2UL );
if( cs(0,0) != 0 || cs(0,1) != 0 ||
cs(1,0) != 1 || cs(1,1) != 0 ||
cs(2,0) != 0 || cs(2,1) != 3 ||
cs(3,0) != -2 || cs(3,1) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 )\n( 1 0 )\n( 0 3 )\n( -2 4 )\n";
throw std::runtime_error( oss.str() );
}
// Changing the number of non-zeros via the column selection
cs(2,1) = 0;
checkRows ( cs, 4UL );
checkColumns ( cs, 2UL );
checkNonZeros( cs, 3UL );
checkNonZeros( cs, 0UL, 2UL );
checkNonZeros( cs, 1UL, 1UL );
if( cs(0,0) != 0 || cs(0,1) != 0 ||
cs(1,0) != 1 || cs(1,1) != 0 ||
cs(2,0) != 0 || cs(2,1) != 0 ||
cs(3,0) != -2 || cs(3,1) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 )\n( 1 0 )\n( 0 0 )\n( -2 4 )\n";
throw std::runtime_error( oss.str() );
}
// Changing the number of non-zeros via the dense matrix
tmat_(3,2) = 5;
checkRows ( cs, 4UL );
checkColumns ( cs, 2UL );
checkNonZeros( cs, 3UL );
checkNonZeros( cs, 0UL, 2UL );
checkNonZeros( cs, 1UL, 1UL );
if( cs(0,0) != 0 || cs(0,1) != 0 ||
cs(1,0) != 1 || cs(1,1) != 0 ||
cs(2,0) != 0 || cs(2,1) != 0 ||
cs(3,0) != -2 || cs(3,1) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Initialization failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 )\n( 1 0 )\n( 0 0 )\n( -2 5 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c reset() member function of the Columns class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c reset() member function of the Columns specialization.
// In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseSymmetricTest::testReset()
{
//=====================================================================================
// Row-major single element reset
//=====================================================================================
{
test_ = "Row-major reset() function";
using blaze::reset;
using blaze::isDefault;
initialize();
auto cs = blaze::columns( mat_, { 1UL, 2UL, 3UL } );
reset( cs(1,0) );
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 6UL );
checkRows ( mat_, 4UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 6UL );
if( !isDefault( cs(1,0) ) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Reset operation failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 -2 )\n( 0 3 4 )\n( -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 0 || mat_(1,2) != 0 || mat_(1,3) != -2 ||
mat_(2,0) != 0 || mat_(2,1) != 0 || mat_(2,2) != 3 || mat_(2,3) != 4 ||
mat_(3,0) != 0 || mat_(3,1) != -2 || mat_(3,2) != 4 || mat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Reset operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 0 0 -2 )\n"
"( 0 0 3 4 )\n"
"( 0 -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major reset
//=====================================================================================
{
test_ = "Row-major Columns::reset() (lvalue)";
initialize();
auto cs = blaze::columns( mat_, { 1UL, 2UL, 3UL } );
reset( cs );
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 0UL );
checkRows ( mat_, 4UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 0UL );
if( !isDefault( cs ) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Reset operation failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 0 )\n( 0 0 0 )\n( 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 0 || mat_(1,2) != 0 || mat_(1,3) != 0 ||
mat_(2,0) != 0 || mat_(2,1) != 0 || mat_(2,2) != 0 || mat_(2,3) != 0 ||
mat_(3,0) != 0 || mat_(3,1) != 0 || mat_(3,2) != 0 || mat_(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Reset operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major Columns::reset() (rvalue)";
initialize();
reset( blaze::columns( mat_, { 1UL, 2UL, 3UL } ) );
checkRows ( mat_, 4UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 0UL );
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 0 || mat_(1,2) != 0 || mat_(1,3) != 0 ||
mat_(2,0) != 0 || mat_(2,1) != 0 || mat_(2,2) != 0 || mat_(2,3) != 0 ||
mat_(3,0) != 0 || mat_(3,1) != 0 || mat_(3,2) != 0 || mat_(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Reset operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major single element reset
//=====================================================================================
{
test_ = "Column-major reset() function";
using blaze::reset;
using blaze::isDefault;
initialize();
auto cs = blaze::columns( tmat_, { 1UL, 2UL, 3UL } );
reset( cs(1,0) );
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 6UL );
checkRows ( tmat_, 4UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 6UL );
if( !isDefault( cs(1,0) ) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Reset operation failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 -2 )\n( 0 3 4 )\n( -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 0 || tmat_(1,2) != 0 || tmat_(1,3) != -2 ||
tmat_(2,0) != 0 || tmat_(2,1) != 0 || tmat_(2,2) != 3 || tmat_(2,3) != 4 ||
tmat_(3,0) != 0 || tmat_(3,1) != -2 || tmat_(3,2) != 4 || tmat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Reset operation failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 0 0 -2 )\n"
"( 0 0 3 4 )\n"
"( 0 -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major reset
//=====================================================================================
{
test_ = "Row-major Columns::reset() (lvalue)";
initialize();
auto cs = blaze::columns( tmat_, { 1UL, 2UL, 3UL } );
reset( cs );
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 0UL );
checkRows ( tmat_, 4UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 0UL );
if( !isDefault( cs ) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Reset operation failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 0 )\n( 0 0 0 )\n( 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 0 || tmat_(1,2) != 0 || tmat_(1,3) != 0 ||
tmat_(2,0) != 0 || tmat_(2,1) != 0 || tmat_(2,2) != 0 || tmat_(2,3) != 0 ||
tmat_(3,0) != 0 || tmat_(3,1) != 0 || tmat_(3,2) != 0 || tmat_(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Reset operation failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major Columns::reset() (rvalue)";
initialize();
reset( blaze::columns( tmat_, { 1UL, 2UL, 3UL } ) );
checkRows ( tmat_, 4UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 0UL );
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 0 || tmat_(1,2) != 0 || tmat_(1,3) != 0 ||
tmat_(2,0) != 0 || tmat_(2,1) != 0 || tmat_(2,2) != 0 || tmat_(2,3) != 0 ||
tmat_(3,0) != 0 || tmat_(3,1) != 0 || tmat_(3,2) != 0 || tmat_(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Reset operation failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c clear() function with the Columns class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c clear() function with the Columns specialization.
// In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseSymmetricTest::testClear()
{
//=====================================================================================
// Row-major single element clear
//=====================================================================================
{
test_ = "Row-major clear() function";
using blaze::clear;
using blaze::isDefault;
initialize();
auto cs = blaze::columns( mat_, { 1UL, 2UL, 3UL } );
clear( cs(1,0) );
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 6UL );
checkRows ( mat_, 4UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 6UL );
if( !isDefault( cs(1,0) ) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Clear operation failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 -2 )\n( 0 3 4 )\n( -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 0 || mat_(1,2) != 0 || mat_(1,3) != -2 ||
mat_(2,0) != 0 || mat_(2,1) != 0 || mat_(2,2) != 3 || mat_(2,3) != 4 ||
mat_(3,0) != 0 || mat_(3,1) != -2 || mat_(3,2) != 4 || mat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Clear operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 0 0 -2 )\n"
"( 0 0 3 4 )\n"
"( 0 -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Row-major clear
//=====================================================================================
{
test_ = "Row-major Columns::clear() (lvalue)";
initialize();
auto cs = blaze::columns( mat_, { 1UL, 2UL, 3UL } );
clear( cs );
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 0UL );
checkRows ( mat_, 4UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 0UL );
if( !isDefault( cs ) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Clear operation failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 0 )\n( 0 0 0 )\n( 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 0 || mat_(1,2) != 0 || mat_(1,3) != 0 ||
mat_(2,0) != 0 || mat_(2,1) != 0 || mat_(2,2) != 0 || mat_(2,3) != 0 ||
mat_(3,0) != 0 || mat_(3,1) != 0 || mat_(3,2) != 0 || mat_(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Clear operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major Columns::clear() (rvalue)";
initialize();
clear( blaze::columns( mat_, { 1UL, 2UL, 3UL } ) );
checkRows ( mat_, 4UL );
checkColumns ( mat_, 4UL );
checkNonZeros( mat_, 0UL );
if( mat_(0,0) != 0 || mat_(0,1) != 0 || mat_(0,2) != 0 || mat_(0,3) != 0 ||
mat_(1,0) != 0 || mat_(1,1) != 0 || mat_(1,2) != 0 || mat_(1,3) != 0 ||
mat_(2,0) != 0 || mat_(2,1) != 0 || mat_(2,2) != 0 || mat_(2,3) != 0 ||
mat_(3,0) != 0 || mat_(3,1) != 0 || mat_(3,2) != 0 || mat_(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Clear operation failed\n"
<< " Details:\n"
<< " Result:\n" << mat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major single element clear
//=====================================================================================
{
test_ = "Column-major clear() function";
using blaze::clear;
using blaze::isDefault;
initialize();
auto cs = blaze::columns( tmat_, { 1UL, 2UL, 3UL } );
clear( cs(1,0) );
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 6UL );
checkRows ( tmat_, 4UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 6UL );
if( !isDefault( cs(1,0) ) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Clear operation failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 -2 )\n( 0 3 4 )\n( -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 0 || tmat_(1,2) != 0 || tmat_(1,3) != -2 ||
tmat_(2,0) != 0 || tmat_(2,1) != 0 || tmat_(2,2) != 3 || tmat_(2,3) != 4 ||
tmat_(3,0) != 0 || tmat_(3,1) != -2 || tmat_(3,2) != 4 || tmat_(3,3) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Clear operation failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 0 0 -2 )\n"
"( 0 0 3 4 )\n"
"( 0 -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
}
//=====================================================================================
// Column-major clear
//=====================================================================================
{
test_ = "Row-major Columns::clear() (lvalue)";
initialize();
auto cs = blaze::columns( tmat_, { 1UL, 2UL, 3UL } );
clear( cs );
checkRows ( cs , 4UL );
checkColumns ( cs , 3UL );
checkNonZeros( cs , 0UL );
checkRows ( tmat_, 4UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 0UL );
if( !isDefault( cs ) ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Clear operation failed\n"
<< " Details:\n"
<< " Result:\n" << cs << "\n"
<< " Expected result:\n( 0 0 0 )\n( 0 0 0 )\n( 0 0 0 )\n( 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 0 || tmat_(1,2) != 0 || tmat_(1,3) != 0 ||
tmat_(2,0) != 0 || tmat_(2,1) != 0 || tmat_(2,2) != 0 || tmat_(2,3) != 0 ||
tmat_(3,0) != 0 || tmat_(3,1) != 0 || tmat_(3,2) != 0 || tmat_(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Clear operation failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
{
test_ = "Row-major Columns::clear() (rvalue)";
initialize();
clear( blaze::columns( tmat_, { 1UL, 2UL, 3UL } ) );
checkRows ( tmat_, 4UL );
checkColumns ( tmat_, 4UL );
checkNonZeros( tmat_, 0UL );
if( tmat_(0,0) != 0 || tmat_(0,1) != 0 || tmat_(0,2) != 0 || tmat_(0,3) != 0 ||
tmat_(1,0) != 0 || tmat_(1,1) != 0 || tmat_(1,2) != 0 || tmat_(1,3) != 0 ||
tmat_(2,0) != 0 || tmat_(2,1) != 0 || tmat_(2,2) != 0 || tmat_(2,3) != 0 ||
tmat_(3,0) != 0 || tmat_(3,1) != 0 || tmat_(3,2) != 0 || tmat_(3,3) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Clear operation failed\n"
<< " Details:\n"
<< " Result:\n" << tmat_ << "\n"
<< " Expected result:\n( 0 0 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 0 0 0 )\n"
"( 0 0 0 0 )\n";
throw std::runtime_error( oss.str() );
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c isDefault() function with the Columns class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c isDefault() function with the Columns specialization.
// In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseSymmetricTest::testIsDefault()
{
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
test_ = "Row-major isDefault() function";
using blaze::isDefault;
initialize();
// isDefault with default column selection
{
auto cs = blaze::columns( mat_, { 0UL } );
if( isDefault( cs(1,0) ) != true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isDefault evaluation\n"
<< " Details:\n"
<< " Column element: " << cs(1,0) << "\n";
throw std::runtime_error( oss.str() );
}
if( isDefault( cs ) != true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isDefault evaluation\n"
<< " Details:\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isDefault with non-default column selection
{
auto cs = blaze::columns( mat_, { 1UL } );
if( isDefault( cs(1,0) ) != false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isDefault evaluation\n"
<< " Details:\n"
<< " Column element: " << cs(1,0) << "\n";
throw std::runtime_error( oss.str() );
}
if( isDefault( cs ) != false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isDefault evaluation\n"
<< " Details:\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
test_ = "Column-major isDefault() function";
using blaze::isDefault;
initialize();
// isDefault with default column selection
{
auto cs = blaze::columns( tmat_, { 0UL } );
if( isDefault( cs(1,0) ) != true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isDefault evaluation\n"
<< " Details:\n"
<< " Column element: " << cs(1,0) << "\n";
throw std::runtime_error( oss.str() );
}
if( isDefault( cs ) != true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isDefault evaluation\n"
<< " Details:\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isDefault with non-default column selection
{
auto cs = blaze::columns( tmat_, { 1UL } );
if( isDefault( cs(1,0) ) != false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isDefault evaluation\n"
<< " Details:\n"
<< " Column element: " << cs(1,0) << "\n";
throw std::runtime_error( oss.str() );
}
if( isDefault( cs ) != false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isDefault evaluation\n"
<< " Details:\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c isSame() function with the Columns class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c isSame() function with the Columns specialization.
// In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseSymmetricTest::testIsSame()
{
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
test_ = "Row-major isSame() function";
// isSame with matrix and matching column selection
{
auto cs = blaze::columns( mat_, { 0UL, 1UL, 2UL, 3UL } );
if( blaze::isSame( cs, mat_ ) == false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << mat_ << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( mat_, cs ) == false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << mat_ << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with matrix and non-matching column selection (different number of columns)
{
auto cs = blaze::columns( mat_, { 0UL, 1UL, 2UL } );
if( blaze::isSame( cs, mat_ ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << mat_ << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( mat_, cs ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << mat_ << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with matrix and non-matching column selection (different order of columns)
{
auto cs = blaze::columns( mat_, { 0UL, 2UL, 1UL, 3UL } );
if( blaze::isSame( cs, mat_ ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << mat_ << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( mat_, cs ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << mat_ << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with matrix and non-matching column selection (repeating columns)
{
auto cs = blaze::columns( mat_, { 0UL, 1UL, 1UL, 3UL } );
if( blaze::isSame( cs, mat_ ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << mat_ << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( mat_, cs ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << mat_ << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with submatrix and matching column selection
{
auto cs = blaze::columns( mat_, { 1UL, 2UL, 3UL } );
auto sm = blaze::submatrix( mat_, 0UL, 1UL, 4UL, 3UL );
if( blaze::isSame( cs, sm ) == false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( sm, cs ) == false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with submatrix and non-matching column selection (different number of rows)
{
auto cs = blaze::columns( mat_, { 1UL, 2UL, 3UL } );
auto sm = blaze::submatrix( mat_, 0UL, 1UL, 3UL, 3UL );
if( blaze::isSame( cs, sm ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( sm, cs ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with submatrix and non-matching column selection (different number of columns)
{
auto cs = blaze::columns( mat_, { 1UL, 2UL, 3UL } );
auto sm = blaze::submatrix( mat_, 0UL, 1UL, 4UL, 2UL );
if( blaze::isSame( cs, sm ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( sm, cs ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with submatrix and non-matching column selection (different order of columns)
{
auto cs = blaze::columns( mat_, { 1UL, 3UL, 2UL } );
auto sm = blaze::submatrix( mat_, 0UL, 1UL, 4UL, 3UL );
if( blaze::isSame( cs, sm ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( sm, cs ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with submatrix and non-matching column selection (repeating columns)
{
auto cs = blaze::columns( mat_, { 1UL, 3UL, 3UL } );
auto sm = blaze::submatrix( mat_, 0UL, 1UL, 4UL, 3UL );
if( blaze::isSame( cs, sm ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( sm, cs ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with submatrix and non-matching column selection (different column index)
{
auto cs = blaze::columns( mat_, { 1UL, 2UL, 3UL } );
auto sm = blaze::submatrix( mat_, 0UL, 0UL, 4UL, 3UL );
if( blaze::isSame( cs, sm ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( sm, cs ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with matching column selections
{
auto cs1 = blaze::columns( mat_, { 0UL, 3UL, 1UL } );
auto cs2 = blaze::columns( mat_, { 0UL, 3UL, 1UL } );
if( blaze::isSame( cs1, cs2 ) == false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " First column selection:\n" << cs1 << "\n"
<< " Second column selection:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with non-matching column selections (different number of columns)
{
auto cs1 = blaze::columns( mat_, { 0UL, 3UL, 1UL } );
auto cs2 = blaze::columns( mat_, { 0UL, 3UL, 1UL, 2UL } );
if( blaze::isSame( cs1, cs2 ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " First column selection:\n" << cs1 << "\n"
<< " Second column selection:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with non-matching column selections (different order of columns)
{
auto cs1 = blaze::columns( mat_, { 0UL, 3UL, 1UL } );
auto cs2 = blaze::columns( mat_, { 0UL, 1UL, 3UL } );
if( blaze::isSame( cs1, cs2 ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " First column selection:\n" << cs1 << "\n"
<< " Second column selection:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with non-matching column selections (repeating columns)
{
auto cs1 = blaze::columns( mat_, { 0UL, 3UL, 1UL } );
auto cs2 = blaze::columns( mat_, { 0UL, 1UL, 1UL } );
if( blaze::isSame( cs1, cs2 ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " First column selection:\n" << cs1 << "\n"
<< " Second column selection:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
test_ = "Column-major isSame() function";
// isSame with matrix and matching column selection
{
auto cs = blaze::columns( tmat_, { 0UL, 1UL, 2UL, 3UL } );
if( blaze::isSame( cs, tmat_ ) == false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << tmat_ << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( tmat_, cs ) == false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << tmat_ << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with matrix and non-matching column selection (different number of columns)
{
auto cs = blaze::columns( tmat_, { 0UL, 1UL, 2UL } );
if( blaze::isSame( cs, tmat_ ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << tmat_ << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( tmat_, cs ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << tmat_ << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with matrix and non-matching column selection (different order of columns)
{
auto cs = blaze::columns( tmat_, { 0UL, 2UL, 1UL, 3UL } );
if( blaze::isSame( cs, tmat_ ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << tmat_ << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( tmat_, cs ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << tmat_ << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with matrix and non-matching column selection (repeating columns)
{
auto cs = blaze::columns( tmat_, { 0UL, 1UL, 1UL, 3UL } );
if( blaze::isSame( cs, tmat_ ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << tmat_ << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( tmat_, cs ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Matrix:\n" << tmat_ << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with submatrix and matching column selection
{
auto cs = blaze::columns( tmat_, { 1UL, 2UL, 3UL } );
auto sm = blaze::submatrix( tmat_, 0UL, 1UL, 4UL, 3UL );
if( blaze::isSame( cs, sm ) == false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( sm, cs ) == false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with submatrix and non-matching column selection (different number of rows)
{
auto cs = blaze::columns( tmat_, { 1UL, 2UL, 3UL } );
auto sm = blaze::submatrix( tmat_, 0UL, 1UL, 3UL, 3UL );
if( blaze::isSame( cs, sm ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( sm, cs ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with submatrix and non-matching column selection (different number of columns)
{
auto cs = blaze::columns( tmat_, { 1UL, 2UL, 3UL } );
auto sm = blaze::submatrix( tmat_, 0UL, 1UL, 4UL, 2UL );
if( blaze::isSame( cs, sm ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( sm, cs ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with submatrix and non-matching column selection (different order of columns)
{
auto cs = blaze::columns( tmat_, { 1UL, 3UL, 2UL } );
auto sm = blaze::submatrix( tmat_, 0UL, 1UL, 4UL, 3UL );
if( blaze::isSame( cs, sm ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( sm, cs ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with submatrix and non-matching column selection (repeating columns)
{
auto cs = blaze::columns( tmat_, { 1UL, 3UL, 3UL } );
auto sm = blaze::submatrix( tmat_, 0UL, 1UL, 4UL, 3UL );
if( blaze::isSame( cs, sm ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( sm, cs ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with submatrix and non-matching column selection (different column index)
{
auto cs = blaze::columns( tmat_, { 1UL, 2UL, 3UL } );
auto sm = blaze::submatrix( tmat_, 0UL, 0UL, 4UL, 3UL );
if( blaze::isSame( cs, sm ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
if( blaze::isSame( sm, cs ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " Submatrix:\n" << sm << "\n"
<< " Column selection:\n" << cs << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with matching column selections
{
auto cs1 = blaze::columns( tmat_, { 0UL, 3UL, 1UL } );
auto cs2 = blaze::columns( tmat_, { 0UL, 3UL, 1UL } );
if( blaze::isSame( cs1, cs2 ) == false ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " First column selection:\n" << cs1 << "\n"
<< " Second column selection:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with non-matching column selections (different number of columns)
{
auto cs1 = blaze::columns( tmat_, { 0UL, 3UL, 1UL } );
auto cs2 = blaze::columns( tmat_, { 0UL, 3UL, 1UL, 2UL } );
if( blaze::isSame( cs1, cs2 ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " First column selection:\n" << cs1 << "\n"
<< " Second column selection:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with non-matching column selections (different order of columns)
{
auto cs1 = blaze::columns( tmat_, { 0UL, 3UL, 1UL } );
auto cs2 = blaze::columns( tmat_, { 0UL, 1UL, 3UL } );
if( blaze::isSame( cs1, cs2 ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " First column selection:\n" << cs1 << "\n"
<< " Second column selection:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
// isSame with non-matching column selections (repeating columns)
{
auto cs1 = blaze::columns( tmat_, { 0UL, 3UL, 1UL } );
auto cs2 = blaze::columns( tmat_, { 0UL, 1UL, 1UL } );
if( blaze::isSame( cs1, cs2 ) == true ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Invalid isSame evaluation\n"
<< " Details:\n"
<< " First column selection:\n" << cs1 << "\n"
<< " Second column selection:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c submatrix() function with the Columns class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c submatrix() function with the Columns specialization.
// In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseSymmetricTest::testSubmatrix()
{
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
test_ = "Row-major submatrix() function";
initialize();
{
auto cs = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto sm = blaze::submatrix( cs, 1UL, 0UL, 2UL, 3UL );
if( sm(0,0) != 0 || sm(0,1) != 1 || sm(0,2) != -2 ||
sm(1,0) != 3 || sm(1,1) != 0 || sm(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator access failed\n"
<< " Details:\n"
<< " Result:\n" << sm << "\n"
<< " Expected result:\n( 0 1 -2 )\n"
"( 3 0 4 )\n";
throw std::runtime_error( oss.str() );
}
if( *sm.begin(1UL) != 1 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *sm.begin(1UL) << "\n"
<< " Expected result: 1\n";
throw std::runtime_error( oss.str() );
}
}
try {
auto cs = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto sm = blaze::submatrix( cs, 4UL, 0UL, 2UL, 3UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds submatrix succeeded\n"
<< " Details:\n"
<< " Result:\n" << sm << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
try {
auto cs = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto sm = blaze::submatrix( cs, 1UL, 3UL, 2UL, 3UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds submatrix succeeded\n"
<< " Details:\n"
<< " Result:\n" << sm << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
try {
auto cs = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto sm = blaze::submatrix( cs, 1UL, 0UL, 5UL, 3UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds submatrix succeeded\n"
<< " Details:\n"
<< " Result:\n" << sm << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
try {
auto cs = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto sm = blaze::submatrix( cs, 1UL, 0UL, 2UL, 4UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds submatrix succeeded\n"
<< " Details:\n"
<< " Result:\n" << sm << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
test_ = "Column-major submatrix() function";
initialize();
{
auto cs = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto sm = blaze::submatrix( cs, 1UL, 0UL, 2UL, 3UL );
if( sm(0,0) != 0 || sm(0,1) != 1 || sm(0,2) != -2 ||
sm(1,0) != 3 || sm(1,1) != 0 || sm(1,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator access failed\n"
<< " Details:\n"
<< " Result:\n" << sm << "\n"
<< " Expected result:\n( 0 1 -2 )\n"
"( 3 0 4 )\n";
throw std::runtime_error( oss.str() );
}
if( *sm.begin(1UL) != 1 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *sm.begin(1UL) << "\n"
<< " Expected result: 1\n";
throw std::runtime_error( oss.str() );
}
}
try {
auto cs = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto sm = blaze::submatrix( cs, 4UL, 0UL, 2UL, 3UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds submatrix succeeded\n"
<< " Details:\n"
<< " Result:\n" << sm << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
try {
auto cs = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto sm = blaze::submatrix( cs, 1UL, 3UL, 2UL, 3UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds submatrix succeeded\n"
<< " Details:\n"
<< " Result:\n" << sm << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
try {
auto cs = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto sm = blaze::submatrix( cs, 1UL, 0UL, 5UL, 3UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds submatrix succeeded\n"
<< " Details:\n"
<< " Result:\n" << sm << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
try {
auto cs = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto sm = blaze::submatrix( cs, 1UL, 0UL, 2UL, 4UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds submatrix succeeded\n"
<< " Details:\n"
<< " Result:\n" << sm << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c row() function with the Columns class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c row() function with the Columns specialization.
// In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseSymmetricTest::testRow()
{
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
test_ = "Row-major row() function";
initialize();
{
auto cs = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto row1 = row( cs, 1UL );
if( row1[0] != 0 || row1[1] != 1 || row1[2] != -2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subscript operator access failed\n"
<< " Details:\n"
<< " Result:\n" << row1 << "\n"
<< " Expected result:\n( 0 1 -2 )\n";
throw std::runtime_error( oss.str() );
}
if( *row1.begin() != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *row1.begin() << "\n"
<< " Expected result: 0\n";
throw std::runtime_error( oss.str() );
}
}
try {
auto cs = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto row4 = row( cs, 4UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds row succeeded\n"
<< " Details:\n"
<< " Result:\n" << row4 << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
test_ = "Column-major row() function";
initialize();
{
auto cs = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto row1 = row( cs, 1UL );
if( row1[0] != 0 || row1[1] != 1 || row1[2] != -2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subscript operator access failed\n"
<< " Details:\n"
<< " Result:\n" << row1 << "\n"
<< " Expected result:\n( 0 1 -2 )\n";
throw std::runtime_error( oss.str() );
}
if( *row1.begin() != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *row1.begin() << "\n"
<< " Expected result: 0\n";
throw std::runtime_error( oss.str() );
}
}
try {
auto cs = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto row4 = row( cs, 4UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds row succeeded\n"
<< " Details:\n"
<< " Result:\n" << row4 << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c rows() function with the Columns class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c rows() function with the Columns specialization.
// In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseSymmetricTest::testRows()
{
//=====================================================================================
// Row-major matrix tests (initializer_list)
//=====================================================================================
{
test_ = "Row-major rows() function (initializer_list)";
initialize();
{
auto cs = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto rs = blaze::rows( cs, { 1UL, 0UL, 2UL } );
if( rs(0,0) != 0 || rs(0,1) != 1 || rs(0,2) != -2 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 ||
rs(2,0) != 3 || rs(2,1) != 0 || rs(2,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator access failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 1 -2 )\n( 0 0 0 )\n( 3 0 4 )\n";
throw std::runtime_error( oss.str() );
}
if( *rs.begin( 2UL ) != 3 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *rs.begin( 2UL ) << "\n"
<< " Expected result: 3\n";
throw std::runtime_error( oss.str() );
}
}
try {
auto cs = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto rs = blaze::rows( cs, { 4UL } );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds row selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
//=====================================================================================
// Row-major matrix tests (std::array)
//=====================================================================================
{
test_ = "Row-major rows() function (std::array)";
initialize();
{
std::array<int,3UL> indices{ 1UL, 0UL, 2UL };
auto cs = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto rs = blaze::rows( cs, indices );
if( rs(0,0) != 0 || rs(0,1) != 1 || rs(0,2) != -2 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 ||
rs(2,0) != 3 || rs(2,1) != 0 || rs(2,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator access failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 1 -2 )\n( 0 0 0 )\n( 3 0 4 )\n";
throw std::runtime_error( oss.str() );
}
if( *rs.begin( 2UL ) != 3 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *rs.begin( 2UL ) << "\n"
<< " Expected result: 3\n";
throw std::runtime_error( oss.str() );
}
}
try {
std::array<int,1UL> indices{ 4UL };
auto cs = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto rs = blaze::rows( cs, indices );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds row selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
//=====================================================================================
// Row-major matrix tests (lambda expression)
//=====================================================================================
{
test_ = "Row-major rows() function (lambda expression)";
initialize();
{
auto cs = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto rs = blaze::rows( cs, []( size_t i ){ return (4UL-i)%3UL; }, 3UL );
if( rs(0,0) != 0 || rs(0,1) != 1 || rs(0,2) != -2 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 ||
rs(2,0) != 3 || rs(2,1) != 0 || rs(2,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator access failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 1 -2 )\n( 0 0 0 )\n( 3 0 4 )\n";
throw std::runtime_error( oss.str() );
}
if( *rs.begin( 2UL ) != 3 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *rs.begin( 2UL ) << "\n"
<< " Expected result: 3\n";
throw std::runtime_error( oss.str() );
}
}
try {
auto cs = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto rs = blaze::rows( cs, []( size_t ){ return 4UL; }, 1UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds row selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
//=====================================================================================
// Column-major matrix tests (initializer_list)
//=====================================================================================
{
test_ = "Column-major rows() function (initializer_list)";
initialize();
{
auto cs = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto rs = blaze::rows( cs, { 1UL, 0UL, 2UL } );
if( rs(0,0) != 0 || rs(0,1) != 1 || rs(0,2) != -2 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 ||
rs(2,0) != 3 || rs(2,1) != 0 || rs(2,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator access failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 1 -2 )\n( 0 0 0 )\n( 3 0 4 )\n";
throw std::runtime_error( oss.str() );
}
if( *rs.begin( 2UL ) != 3 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *rs.begin( 2UL ) << "\n"
<< " Expected result: 3\n";
throw std::runtime_error( oss.str() );
}
}
try {
auto cs = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto rs = blaze::rows( cs, { 4UL } );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds row selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
//=====================================================================================
// Column-major matrix tests (std::array)
//=====================================================================================
{
test_ = "Column-major rows() function (std::array)";
initialize();
{
std::array<int,3UL> indices{ 1UL, 0UL, 2UL };
auto cs = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto rs = blaze::rows( cs, indices );
if( rs(0,0) != 0 || rs(0,1) != 1 || rs(0,2) != -2 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 ||
rs(2,0) != 3 || rs(2,1) != 0 || rs(2,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator access failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 1 -2 )\n( 0 0 0 )\n( 3 0 4 )\n";
throw std::runtime_error( oss.str() );
}
if( *rs.begin( 2UL ) != 3 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *rs.begin( 2UL ) << "\n"
<< " Expected result: 3\n";
throw std::runtime_error( oss.str() );
}
}
try {
std::array<int,1UL> indices{ 4UL };
auto cs = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto rs = blaze::rows( cs, indices );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds row selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
//=====================================================================================
// Column-major matrix tests (lambda expression)
//=====================================================================================
{
test_ = "Column-major rows() function (lambda expression)";
initialize();
{
auto cs = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto rs = blaze::rows( cs, []( size_t i ){ return (4UL-i)%3UL; }, 3UL );
if( rs(0,0) != 0 || rs(0,1) != 1 || rs(0,2) != -2 ||
rs(1,0) != 0 || rs(1,1) != 0 || rs(1,2) != 0 ||
rs(2,0) != 3 || rs(2,1) != 0 || rs(2,2) != 4 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator access failed\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n"
<< " Expected result:\n( 0 1 -2 )\n( 0 0 0 )\n( 3 0 4 )\n";
throw std::runtime_error( oss.str() );
}
if( *rs.begin( 2UL ) != 3 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *rs.begin( 2UL ) << "\n"
<< " Expected result: 3\n";
throw std::runtime_error( oss.str() );
}
}
try {
auto cs = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto rs = blaze::rows( cs, []( size_t ){ return 4UL; }, 1UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds row selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << rs << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c column() function with the Columns class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c column() function with the Columns specialization.
// In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseSymmetricTest::testColumn()
{
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
test_ = "Row-major column() function";
initialize();
{
auto cs = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto col1 = blaze::column( cs, 1UL );
if( col1[0] != 0 || col1[1] != 1 || col1[2] != 0 || col1[3] != -2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subscript operator access failed\n"
<< " Details:\n"
<< " Result:\n" << col1 << "\n"
<< " Expected result:\n( 0 1 0 -2 )\n";
throw std::runtime_error( oss.str() );
}
if( *col1.begin() != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *col1.begin() << "\n"
<< " Expected result: 0\n";
throw std::runtime_error( oss.str() );
}
}
try {
auto cs = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto col3 = blaze::column( cs, 3UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds column succeeded\n"
<< " Details:\n"
<< " Result:\n" << col3 << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
test_ = "Column-major column() function";
initialize();
{
auto cs = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto col1 = blaze::column( cs, 1UL );
if( col1[0] != 0 || col1[1] != 1 || col1[2] != 0 || col1[3] != -2 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subscript operator access failed\n"
<< " Details:\n"
<< " Result:\n" << col1 << "\n"
<< " Expected result:\n( 0 1 0 -2 )\n";
throw std::runtime_error( oss.str() );
}
if( *col1.begin() != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *col1.begin() << "\n"
<< " Expected result: 0\n";
throw std::runtime_error( oss.str() );
}
}
try {
auto cs = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto col3 = blaze::column( cs, 3UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds column succeeded\n"
<< " Details:\n"
<< " Result:\n" << col3 << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c columns() function with the Columns class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c columns() function with the Columns specialization.
// In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseSymmetricTest::testColumns()
{
//=====================================================================================
// Row-major matrix tests (initializer_list)
//=====================================================================================
{
test_ = "Row-major columns() function (initializer_list)";
initialize();
{
auto cs1 = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto cs2 = blaze::columns( cs1, { 1UL, 0UL, 2UL } );
if( cs2(0,0) != 0 || cs2(0,1) != 0 || cs2(0,2) != 0 ||
cs2(1,0) != 1 || cs2(1,1) != 0 || cs2(1,2) != -2 ||
cs2(2,0) != 0 || cs2(2,1) != 3 || cs2(2,2) != 4 ||
cs2(3,0) != -2 || cs2(3,1) != 4 || cs2(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator access failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n"
<< " Expected result:\n( 0 0 0 )\n( 1 0 -2 )\n( 0 3 4 )\n( -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( *cs2.begin( 2UL ) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *cs2.begin( 2UL ) << "\n"
<< " Expected result: 0\n";
throw std::runtime_error( oss.str() );
}
}
try {
auto cs1 = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto cs2 = blaze::columns( cs1, { 3UL } );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds column selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
//=====================================================================================
// Row-major matrix tests (std::array)
//=====================================================================================
{
test_ = "Row-major columns() function (std::array)";
initialize();
{
std::array<int,3UL> indices{ 1UL, 0UL, 2UL };
auto cs1 = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto cs2 = blaze::columns( cs1, indices );
if( cs2(0,0) != 0 || cs2(0,1) != 0 || cs2(0,2) != 0 ||
cs2(1,0) != 1 || cs2(1,1) != 0 || cs2(1,2) != -2 ||
cs2(2,0) != 0 || cs2(2,1) != 3 || cs2(2,2) != 4 ||
cs2(3,0) != -2 || cs2(3,1) != 4 || cs2(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator access failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n"
<< " Expected result:\n( 0 0 0 )\n( 1 0 -2 )\n( 0 3 4 )\n( -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( *cs2.begin( 2UL ) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *cs2.begin( 2UL ) << "\n"
<< " Expected result: 0\n";
throw std::runtime_error( oss.str() );
}
}
try {
std::array<int,1UL> indices{ 3UL };
auto cs1 = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto cs2 = blaze::columns( cs1, indices );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds column selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
//=====================================================================================
// Row-major matrix tests (lambda expression)
//=====================================================================================
{
test_ = "Row-major columns() function (lambda expression)";
initialize();
{
auto cs1 = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto cs2 = blaze::columns( cs1, []( size_t i ){ return (4UL-i)%3UL; }, 3UL );
if( cs2(0,0) != 0 || cs2(0,1) != 0 || cs2(0,2) != 0 ||
cs2(1,0) != 1 || cs2(1,1) != 0 || cs2(1,2) != -2 ||
cs2(2,0) != 0 || cs2(2,1) != 3 || cs2(2,2) != 4 ||
cs2(3,0) != -2 || cs2(3,1) != 4 || cs2(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator access failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n"
<< " Expected result:\n( 0 0 0 )\n( 1 0 -2 )\n( 0 3 4 )\n( -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( *cs2.begin( 2UL ) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *cs2.begin( 2UL ) << "\n"
<< " Expected result: 0\n";
throw std::runtime_error( oss.str() );
}
}
try {
auto cs1 = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto cs2 = blaze::columns( cs1, []( size_t ){ return 3UL; }, 1UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds column selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
//=====================================================================================
// Column-major matrix tests (initializer_list)
//=====================================================================================
{
test_ = "Column-major columns() function (initializer_list)";
initialize();
{
auto cs1 = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto cs2 = blaze::columns( cs1, { 1UL, 0UL, 2UL } );
if( cs2(0,0) != 0 || cs2(0,1) != 0 || cs2(0,2) != 0 ||
cs2(1,0) != 1 || cs2(1,1) != 0 || cs2(1,2) != -2 ||
cs2(2,0) != 0 || cs2(2,1) != 3 || cs2(2,2) != 4 ||
cs2(3,0) != -2 || cs2(3,1) != 4 || cs2(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator access failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n"
<< " Expected result:\n( 0 0 0 )\n( 1 0 -2 )\n( 0 3 4 )\n( -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( *cs2.begin( 2UL ) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *cs2.begin( 2UL ) << "\n"
<< " Expected result: 0\n";
throw std::runtime_error( oss.str() );
}
}
try {
auto cs1 = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto cs2 = blaze::columns( cs1, { 3UL } );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds column selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
//=====================================================================================
// Column-major matrix tests (std::array)
//=====================================================================================
{
test_ = "Column-major columns() function (std::array)";
initialize();
{
std::array<int,3UL> indices{ 1UL, 0UL, 2UL };
auto cs1 = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto cs2 = blaze::columns( cs1, indices );
if( cs2(0,0) != 0 || cs2(0,1) != 0 || cs2(0,2) != 0 ||
cs2(1,0) != 1 || cs2(1,1) != 0 || cs2(1,2) != -2 ||
cs2(2,0) != 0 || cs2(2,1) != 3 || cs2(2,2) != 4 ||
cs2(3,0) != -2 || cs2(3,1) != 4 || cs2(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator access failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n"
<< " Expected result:\n( 0 0 0 )\n( 1 0 -2 )\n( 0 3 4 )\n( -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( *cs2.begin( 2UL ) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *cs2.begin( 2UL ) << "\n"
<< " Expected result: 0\n";
throw std::runtime_error( oss.str() );
}
}
try {
std::array<int,1UL> indices{ 3UL };
auto cs1 = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto cs2 = blaze::columns( cs1, indices );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds column selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
//=====================================================================================
// Column-major matrix tests (lambda expression)
//=====================================================================================
{
test_ = "Column-major columns() function (lambda expression)";
initialize();
{
auto cs1 = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto cs2 = blaze::columns( cs1, []( size_t i ){ return (4UL-i)%3UL; }, 3UL );
if( cs2(0,0) != 0 || cs2(0,1) != 0 || cs2(0,2) != 0 ||
cs2(1,0) != 1 || cs2(1,1) != 0 || cs2(1,2) != -2 ||
cs2(2,0) != 0 || cs2(2,1) != 3 || cs2(2,2) != 4 ||
cs2(3,0) != -2 || cs2(3,1) != 4 || cs2(3,2) != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Function call operator access failed\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n"
<< " Expected result:\n( 0 0 0 )\n( 1 0 -2 )\n( 0 3 4 )\n( -2 4 5 )\n";
throw std::runtime_error( oss.str() );
}
if( *cs2.begin( 2UL ) != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *cs2.begin( 2UL ) << "\n"
<< " Expected result: 0\n";
throw std::runtime_error( oss.str() );
}
}
try {
auto cs1 = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto cs2 = blaze::columns( cs1, []( size_t ){ return 3UL; }, 1UL );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds column selection succeeded\n"
<< " Details:\n"
<< " Result:\n" << cs2 << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
}
//*************************************************************************************************
//*************************************************************************************************
/*!\brief Test of the \c band() function with the Columns class template.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function performs a test of the \c band() function with the Columns specialization.
// In case an error is detected, a \a std::runtime_error exception is thrown.
*/
void DenseSymmetricTest::testBand()
{
//=====================================================================================
// Row-major matrix tests
//=====================================================================================
{
test_ = "Row-major band() function";
initialize();
{
auto cs = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto b1 = blaze::band( cs, -1L );
if( b1[0] != 0 || b1[1] != 0 || b1[2] != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subscript operator access failed\n"
<< " Details:\n"
<< " Result:\n" << b1 << "\n"
<< " Expected result\n: ( 0 0 5 )\n";
throw std::runtime_error( oss.str() );
}
if( *b1.begin() != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *b1.begin() << "\n"
<< " Expected result: 0\n";
throw std::runtime_error( oss.str() );
}
}
try {
auto cs = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto b3 = blaze::band( cs, 3L );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds band succeeded\n"
<< " Details:\n"
<< " Result:\n" << b3 << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
try {
auto cs = blaze::columns( mat_, { 2UL, 1UL, 3UL } );
auto b4 = blaze::band( cs, -4L );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds band succeeded\n"
<< " Details:\n"
<< " Result:\n" << b4 << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
//=====================================================================================
// Column-major matrix tests
//=====================================================================================
{
test_ = "Column-major band() function";
initialize();
{
auto cs = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto b1 = blaze::band( cs, -1L );
if( b1[0] != 0 || b1[1] != 0 || b1[2] != 5 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Subscript operator access failed\n"
<< " Details:\n"
<< " Result:\n" << b1 << "\n"
<< " Expected result\n: ( 0 0 5 )\n";
throw std::runtime_error( oss.str() );
}
if( *b1.begin() != 0 ) {
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Iterator access failed\n"
<< " Details:\n"
<< " Result: " << *b1.begin() << "\n"
<< " Expected result: 0\n";
throw std::runtime_error( oss.str() );
}
}
try {
auto cs = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto b3 = blaze::band( cs, 3L );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds band succeeded\n"
<< " Details:\n"
<< " Result:\n" << b3 << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
try {
auto cs = blaze::columns( tmat_, { 2UL, 1UL, 3UL } );
auto b4 = blaze::band( cs, -4L );
std::ostringstream oss;
oss << " Test: " << test_ << "\n"
<< " Error: Setup of out-of-bounds band succeeded\n"
<< " Details:\n"
<< " Result:\n" << b4 << "\n";
throw std::runtime_error( oss.str() );
}
catch( std::invalid_argument& ) {}
}
}
//*************************************************************************************************
//=================================================================================================
//
// UTILITY FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Initialization of all member matrices.
//
// \return void
// \exception std::runtime_error Error detected.
//
// This function initializes all member matrices to specific predetermined values.
*/
void DenseSymmetricTest::initialize()
{
// Initializing the symmetric row-major matrix
mat_.reset();
mat_(1,1) = 1;
mat_(1,3) = -2;
mat_(2,2) = 3;
mat_(2,3) = 4;
mat_(3,3) = 5;
// Initializing the symmetric column-major matrix
tmat_.reset();
tmat_(1,1) = 1;
tmat_(1,3) = -2;
tmat_(2,2) = 3;
tmat_(2,3) = 4;
tmat_(3,3) = 5;
}
//*************************************************************************************************
} // namespace columns
} // namespace views
} // namespace mathtest
} // namespace blazetest
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running Columns dense symmetric test..." << std::endl;
try
{
RUN_COLUMNS_DENSESYMMETRIC_TEST;
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during Columns dense symmetric test:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
aa0e575b95bb37e29f773dcd7775054a50c01e82 | 74af32d04639d5c442f0e94b425beb68a2544b3c | /LeetCode/Normal/900-999/940.cpp | 1a2790089455f5c69875a66cb6e0110db31f3d4e | [] | no_license | dlvguo/NoobOJCollection | 4e4bd570aa2744dfaa2924bacc34467a9eae8c9d | 596f6c578d18c7beebdb00fa3ce6d6d329647360 | refs/heads/master | 2023-05-01T07:42:33.479091 | 2023-04-20T11:09:15 | 2023-04-20T11:09:15 | 181,868,933 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 753 | cpp | #include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int distinctSubseqII(string s)
{
vector<int> last(26, -1);
int n = s.size();
vector<int> f(n, 1);
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < 26; ++j)
{
if (last[j] != -1)
{
f[i] = (f[i] + f[last[j]]) % mod;
}
}
last[s[i] - 'a'] = i;
}
int ans = 0;
for (int i = 0; i < 26; ++i)
{
if (last[i] != -1)
{
ans = (ans + f[last[i]]) % mod;
}
}
return ans;
}
private:
static constexpr int mod = 1000000007;
}; | [
"dlvguo@qq.com"
] | dlvguo@qq.com |
c9ba8b939b53481cec743154b0dced36cfbb38dd | 6a3b56616185b5107e2ef61780a75f8a42640d1c | /Source/Building_Escape/Building_EscapeGameModeBase.h | 057cc7ec29c78f177c5928d6ad854fa8eb368dcc | [] | no_license | berkeelustu/EscapeFromRoom | 653f305167465030edf79693ad748878bbdee4c2 | 3e601d489663d47c729257595679390282a073cf | refs/heads/main | 2023-05-22T02:08:53.598540 | 2021-06-04T14:49:41 | 2021-06-04T14:49:41 | 371,732,617 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 309 | h | // Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "Building_EscapeGameModeBase.generated.h"
UCLASS()
class BUILDING_ESCAPE_API ABuilding_EscapeGameModeBase : public AGameModeBase
{
GENERATED_BODY()
};
| [
"noreply@github.com"
] | noreply@github.com |
b18c1031529167649afad1f099687d9fd55bea3e | 2f51cf75094feaae1bbada78e1e00e410163f1cf | /src/runtime/tmp/run.cpp | 1309c24f9e56f75b0addfc4e78024b00002cf38b | [
"Zend-2.0",
"LicenseRef-scancode-unknown-license-reference",
"PHP-3.01"
] | permissive | burhan/hiphop-php | 44d7d7df0539bfeb2ce598ec060367557a42989c | 6e02d7072a02fbaad1856878c2515e35f7e529f0 | refs/heads/master | 2021-01-18T07:53:36.815101 | 2012-10-01T20:08:41 | 2012-10-02T02:37:57 | 6,041,737 | 0 | 0 | NOASSERTION | 2020-02-07T21:30:31 | 2012-10-02T07:51:18 | C++ | UTF-8 | C++ | false | false | 1,988 | cpp | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
| [
"macvicar@fb.com"
] | macvicar@fb.com |
6073efec7352f00a4b23c4129f0383e9f0bd1b92 | 09bb7d05f6e93891362f96bf95d7a777025af684 | /mapviewer/mapfile.cpp | 65d4533fffaff34854f35bb6e3c1bf41db1bba6d | [] | no_license | GitYub/QExpress | 7098bc8f35ef814c12ab10bbc2f88748f59303c9 | e2f0915d2d44f65f90abb6f83dd53080f98ed6f8 | refs/heads/master | 2021-01-12T15:44:49.266208 | 2016-10-25T08:05:09 | 2016-10-25T08:05:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,106 | cpp | #include "mapfile.h"
#include <QDebug>
#include <QTextCodec>
// 指定字符集
QTextCodec *codec = QTextCodec::codecForName("GBK");
MapFile::MapFile()
{
}
int MapFile::openFile(const char *fileName)
{
// 打开地图文件
if ((srcFile = IMapInfoFile::SmartOpen(fileName)) == NULL)
{
qDebug() << "cannot open file";
return -1;
}
return 0;
}
int MapFile::closeFile()
{
srcFile->Close();
delete srcFile;
}
// 获取图形信息
int MapFile::getLayerInfo(MapLayer *layer)
{
layer->getFeatureCount(srcFile->GetFeatureCount(TRUE));
srcFile->ResetReading();
MapShape *shape;
TABFeature *feature;
int featureId = -1;
while ((featureId = srcFile->GetNextFeatureId(featureId)) != -1)
{
feature = srcFile->GetFeatureRef(featureId);
if (feature)
{
TABFeatureClass featureClass = feature->GetFeatureClass();
if (featureClass == TABFCRegion)
{
shape = new Region;
}
else if(featureClass == TABFCPolyline)
{
shape = new Polyline;
}
else if(featureClass == TABFCPoint)
{
shape = new Point;
}
else
{
shape = new Region;
}
shape->setIndex(featureId);
// get coordinates of each vertexs of the feature
getStyle(feature, shape, featureClass);
getCoord(feature, shape, layer, featureClass);
// set boudingrect for every feature
shape->setBounds();
getField(feature, shape);
layer->addShape(shape, featureClass);
}
else
{
qDebug() << "cannot read feature";
return -1;
}
}
return 0;
}
void MapFile::getStyle(TABFeature *feature, MapShape *shape, TABFeatureClass featureClass)
{
switch(featureClass)
{
case TABFCPoint:
break;
case TABFCRegion:
{
QPen pen;
ITABFeaturePen *p = (TABRegion *)feature;
pen.setColor(p->GetPenColor());
pen.setWidth(p->GetPenWidthMIF());
if(p->GetPenPattern() == 2)
pen.setStyle(Qt::SolidLine);
else
pen.setStyle(Qt::DashLine);
shape->setPen(pen);
QBrush brush(Qt::white);
TABRegion *region = (TABRegion *)feature;
brush.setColor(region->GetBrushFGColor());
//b->GetBrushBGColor();
// b->GetBrushPattern();
shape->setBrush(brush);
break;
}
case TABFCPolyline:
{
QPen pen;
ITABFeaturePen *p = (TABPolyline *)feature;
pen.setColor(p->GetPenColor());
pen.setWidth(p->GetPenWidthMIF());
if(p->GetPenPattern() == 2)
pen.setStyle(Qt::SolidLine);
else
pen.setStyle(Qt::DashLine);
shape->setPen(pen);
break;
}
}
}
void MapFile::getCoord(TABFeature *feature, MapShape *shape, MapLayer *layer, TABFeatureClass featureClass)
{
switch(featureClass)
{
case TABFCRegion:
{
TABRegion *region = (TABRegion *)feature;
for (int ringId = 0; ringId < region->GetNumRings(); ++ringId)
{
OGRLinearRing *ring = region->GetRingRef(ringId);
for (int pointId = 0; pointId < ring->getNumPoints(); ++pointId)
{
double x = ring->getX(pointId);
double y = ring->getY(pointId);
layer->coordTransform(x, y);
shape->addPoint(x, y);
}
}
break;
}
case TABFCPolyline:
{
TABPolyline *polyline = (TABPolyline *)feature;
for (int partId = 0; partId < polyline->GetNumParts(); ++partId)
{
OGRLineString *line = polyline->GetPartRef(partId);
for (int pointId = 0; pointId < line->getNumPoints(); ++pointId)
{
double x = line->getX(pointId);
double y = line->getY(pointId);
layer->coordTransform(x, y);
shape->addPoint(x, y);
}
}
break;
}
case TABFCPoint:
{
OGRGeometry *geom = feature->GetGeometryRef();
OGRPoint *point = (OGRPoint *)geom;
double x = point->getX();
double y = point->getY();
layer->coordTransform(x, y);
shape->addPoint(x, y);
break;
}
}
}
void MapFile::getField(TABFeature *feature, MapShape *shape)
{
// 获取图层信息
QString fieldName, fieldType, fieldContent;
OGRFeatureDefn *featureDefn = srcFile->GetLayerDefn();
for (int fieldId = 0; fieldId < featureDefn->GetFieldCount(); ++fieldId)
{
OGRFieldDefn *fieldDefn = featureDefn->GetFieldDefn(fieldId);
fieldName = fieldDefn->GetNameRef();
fieldType = fieldDefn->GetFieldTypeName(fieldDefn->GetType());
fieldContent = codec->toUnicode(feature->GetFieldAsString(fieldId));
shape->addField(fieldName, fieldType, fieldContent);
}
}
| [
"616030437@qq.com"
] | 616030437@qq.com |
b0488f1b03d36e1f9816fbe5f333a46fd3eb4100 | 419e647f60639a5ae583a70052471d56d455e4ce | /arc025/a.cc | d9be6d18146b63020e780ef057a5eb394bad637d | [] | no_license | hnmx4/atcoder_answers | f98fcf864c8edb392d2f6dfd9128737115e1191b | 3259734a37820622f159c6a9a37671164f605d45 | refs/heads/master | 2021-01-25T04:20:29.179775 | 2018-07-01T12:53:14 | 2018-07-01T12:53:14 | 93,422,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 284 | cc | #include <iostream>
using namespace std;
int main()
{
int d[7], j[7], g=0;
for (int i=0;i<7;i++)
cin >> d[i];
for (int i=0;i<7;i++)
cin >> j[i];
for (int i=0;i<7;i++){
if (d[i]>j[i])
g+=d[i];
else
g+=j[i];
}
cout << g << endl;
return 0;
}
| [
"hnmnty@gmail.com"
] | hnmnty@gmail.com |
74f57f82297461b9c175844f22645c1132028d6a | 830dc91666c54765b7a341ca294d2a74318964ec | /Code/MainWidgets/DialogCreateGeoComponent.cpp | cf05ce3ed268c6bbbba0581985574a648c5a11dc | [
"BSD-3-Clause"
] | permissive | Zhengzhi-727/FastCAE | 4971a68ba43dd814cee85af3468b41467ea9736c | ab954d5de437bcca04938443957002c2c7fa1c5d | refs/heads/master | 2023-02-17T11:46:01.566067 | 2021-01-18T05:58:34 | 2021-01-18T05:58:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,976 | cpp | #include "preWindow.h"
#include "moduleBase/ModuleType.h"
#include "DialogCreateGeoComponent.h"
#include "ui_DialogCreateGeoComponent.h"
#include "geometry/geometryData.h"
#include "geometry/geometrySet.h"
#include "mainWindow/mainWindow.h"
#include "python/PyAgent.h"
#include <qpushbutton.h>
#include <qmessagebox.h>
#include <qdebug.h>
namespace MainWidget
{
CreateGeoComponentDialog::CreateGeoComponentDialog(GUI::MainWindow* mainwindow, PreWindow* prewindow) :
QFDialog(mainwindow), _preWindow(prewindow), _ui(new Ui::CreateGeoComponentDialog)
{
_ui->setupUi(this);
InitDialog();
_ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Ok"));
_ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel"));
connect(_ui->buttonBox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), this, SLOT(on_buttonOk()));
connect(this, SIGNAL(updataGeoComponentTree()), mainwindow, SIGNAL(updateGeometryTreeSig()));
}
CreateGeoComponentDialog::~CreateGeoComponentDialog()
{
delete _ui;
_ui = nullptr;
}
void CreateGeoComponentDialog::InitDialog()
{
_ui->typeLineEdit->setReadOnly(true);
int currMaxID = DataProperty::ComponentBase::getMaxID();
QString name = QString("GeoComponent_%1").arg(currMaxID + 1);
_ui->nameLineEdit->setPlaceholderText(name);
QString qtype{};
if (_preWindow)
{
switch (_preWindow->getSelectModel())
{
case ModuleBase::GeometryWinPoint: qtype = tr("Point"); _type = Geometry::GeoComponentType::Node; break;
case ModuleBase::GeometryWinCurve: qtype = tr("Line"); _type = Geometry::GeoComponentType::Line; break;
case ModuleBase::GeometryWinSurface: qtype = tr("Surface"); _type = Geometry::GeoComponentType::Surface; break;
case ModuleBase::GeometryWinBody: qtype = tr("Body"); _type = Geometry::GeoComponentType::Body; break;
default: break;
}
}
_ui->typeLineEdit->setText(qtype);
}
void CreateGeoComponentDialog::on_buttonOk()
{
auto selectedItems = _preWindow->getGeoSelectItems();
if (selectedItems == nullptr || selectedItems->isEmpty())
{
QMessageBox::warning(this, tr("Warning"), tr("No Point or Line Surface Body selected !"));
QDialog::reject();
return;
}
QStringList geoSetIDs, geoSetItemIDs;
QMutableHashIterator<Geometry::GeometrySet*, int> it(*selectedItems);
while (it.hasNext())
{
it.next();
geoSetIDs << QString::number(it.key()->getID());
geoSetItemIDs << QString::number(it.value());
}
QString qType = Geometry::GeoComponent::gcTypeToString(_type);
QString qGeoSetIDs = geoSetIDs.join(";");
QString qGeoSetItemIDs = geoSetItemIDs.join(";");
QString qGeoComponentName = _ui->nameLineEdit->text();
if (qGeoComponentName.isEmpty())
qGeoComponentName = _ui->nameLineEdit->placeholderText();
QString code = QString("MainWindow.createGeoComponent(\"%1\",\"%2\",\"%3\",\"%4\")").arg(qGeoComponentName).arg(qType).arg(qGeoSetIDs).arg(qGeoSetItemIDs);
Py::PythonAagent::getInstance()->submit(code);
}
}
| [
"l”ibaojunqd@foxmail.com“"
] | l”ibaojunqd@foxmail.com“ |
dabaddab84c607c71ec98a885cececbf79388fb9 | 02c5908b252bc351e30a4810258928fd27a192be | /Assignment3/Cache.h | 7a26c97e8388fa953652dab22ae987f1083c774a | [] | no_license | tam-ng0905/CS252 | 0e98d9cad4817f1f43720cec2989a5185e565d32 | d4c538e5dd1383798ba19b69af6d036db67db71a | refs/heads/master | 2021-05-28T14:53:42.687836 | 2013-03-29T22:12:42 | 2013-03-29T22:12:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 329 | h | #include <vector>
#include "Set.h"
class Cache {
private:
int physicalAddrBits;
int cacheSize;
int blockSize;
int blocksPerSet;
std::vector<Set*> sets;
public:
Cache(int m, int c, int b, int e);
~Cache();
int simulateRead(unsigned long addr);
int simulateWrite(unsigned long addr);
void display();
};
| [
"zforster@hotmail.com"
] | zforster@hotmail.com |
2f8ac6a3d5e9fea20554e03f80bad2f0e9e09d71 | 8ba3c856f705f0c6855bfab59b08f33b372ecdbc | /TeamTalk/msg_server/MsgConn.cpp | 91a0f23540b5be956899a642273a42bbe263a9e3 | [] | no_license | csgvsjay1000/workspace | e8ed140fd37dbba0a83231f3e07c3ad9e9d76bbd | 6bc2138330daa5bc99eb02a6a193f12523a8bc3b | refs/heads/master | 2021-01-18T15:37:26.997682 | 2017-05-02T09:59:05 | 2017-05-02T09:59:05 | 86,663,586 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 460 | cpp | #include "MsgConn.h"
#include "util.h"
static UserMap_t g_msg_conn_user_map;
static ConnMap_t g_msg_conn_map;
void CMsgConn::OnConnect(int handle)
{
m_handle = handle;
g_msg_conn_map.insert(make_pair(handle,this));
netlib_option(handle,NETLIB_OPT_SET_CALLBACK,(void*)imconn_callback);
netlib_option(handle,NETLIB_OPT_SET_CALLBACK_DATA,(void*)&g_msg_conn_map);
}
void CMsgConn::HandlePdu(CImPdu* pPdu)
{
loginfo("commandId: %d",pPdu->GetCommandId());
}
| [
"254633397@qq.com"
] | 254633397@qq.com |
b705086fdf1076da8e52e88b34ef9ba0e6f63292 | e05ee73f59fa33c462743b30cbc5d35263383e89 | /sparse/control/magma_smilustruct.cpp | 56f1add30321541d4ba57e52fbc79539b0cc6261 | [] | no_license | bhrnjica/magma | 33c9e8a89f9bc2352f70867a48ec2dab7f94a984 | 88c8ca1a668055859a1cb9a31a204b702b688df5 | refs/heads/master | 2021-10-09T18:49:50.396412 | 2019-01-02T13:51:33 | 2019-01-02T13:51:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,507 | cpp | /*
-- MAGMA (version 2.4.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date June 2018
@generated from sparse/control/magma_zmilustruct.cpp, normal z -> s, Mon Jun 25 18:24:28 2018
@author Hartwig Anzt
*/
// in this file, many routines are taken from
// the IO functions provided by MatrixMarket
#include "magmasparse_internal.h"
/******************************************************************************
* ILU mex function from MATLAB:
*
* [l, u] = ilu_mex(a, level, omega, storage);
*****************************************************************************/
#define mwIndex magma_index_t
void magma_sshell_sort(
const magma_int_t n, magma_index_t *x)
{
magma_int_t m, max, j, k, itemp;
m = n/2;
while (m > 0) {
max = n - m;
for (j=0; j<max; j++)
{
for (k=j; k>=0; k-=m)
{
if (x[k+m] >= x[k])
break;
itemp = x[k+m];
x[k+m] = x[k];
x[k] = itemp;
}
}
m = m/2;
}
}
/*
// symbolic level ILU
// factors magma_int_to separate upper and lower parts
// sorts the entries in each row of A by index
// assumes no zero rows
*/
extern "C"
magma_int_t
magma_ssymbolic_ilu(
const magma_int_t levfill, /* level of fill */
const magma_int_t n, /* order of matrix */
magma_int_t *nzl, /* input-output */
magma_int_t *nzu, /* input-output */
const mwIndex *ia,
const mwIndex *ja, /* input */
mwIndex *ial,
mwIndex *jal, /* output lower factor structure */
mwIndex *iau,
mwIndex *jau) /* output upper factor structure */
{
magma_int_t info = 0;
magma_int_t i;
magma_index_t *lnklst=NULL;
magma_index_t *curlev=NULL;
magma_index_t *levels=NULL;
magma_index_t *iwork=NULL;
magma_int_t knzl = 0;
magma_int_t knzu = 0;
CHECK( magma_index_malloc_cpu( &lnklst, n ));
CHECK( magma_index_malloc_cpu( &curlev, n ));
CHECK( magma_index_malloc_cpu( &levels, *nzu ));
CHECK( magma_index_malloc_cpu( &iwork, n ));
for(magma_int_t t=0; t<n; t++){
lnklst[t] = 0;
curlev[t] = 0;
iwork[t] = 0;
}
for(magma_int_t t=0; t<*nzu; t++){
levels[t] = 0;
}
ial[0] = 0;
iau[0] = 0;
for (i=0; i<n; i++) {
//printf("check line %d\n", i);
magma_int_t first, next, j;
/* copy column indices of row into workspace and sort them */
magma_int_t len = ia[i+1] - ia[i];
next = 0;
for (j=ia[i]; j<ia[i+1]; j++)
iwork[next++] = ja[j];
magma_sshell_sort(len, iwork);
//printf("check2 line %d\n", i);
/* construct implied linked list for row */
first = iwork[0];
curlev[first] = 0;
for (j=0; j<=len-2; j++)
{
lnklst[iwork[j]] = iwork[j+1];
curlev[iwork[j]] = 0;
}
// printf("check3 line %d iwork[len-1]:%d\n", i, iwork[len-1]);
lnklst[iwork[len-1]] = n;
curlev[iwork[len-1]] = 0;
/* merge with rows in U */
// printf("check4 line %d lnklst[iwork[len-1]]:%d\n", i, lnklst[iwork[len-1]]);
next = first;
// printf("next:%d (!<) first:%d\n", next, i);
while (next < i)
{
// printf("check line %d while %d\n", i, next);
magma_int_t oldlst = next;
magma_int_t nxtlst = lnklst[next];
magma_int_t row = next;
magma_int_t ii;
/* scan row */
for (ii=iau[row]+1; ii<iau[row+1]; /*nop*/)
{
if (jau[ii] < nxtlst)
{
/* new fill-in */
magma_int_t newlev = curlev[row] + levels[ii] + 1;
if (newlev <= levfill)
{
lnklst[oldlst] = jau[ii];
lnklst[jau[ii]] = nxtlst;
oldlst = jau[ii];
curlev[jau[ii]] = newlev;
}
ii++;
}
else if (jau[ii] == nxtlst)
{
magma_int_t newlev;
oldlst = nxtlst;
nxtlst = lnklst[oldlst];
newlev = curlev[row] + levels[ii] + 1;
curlev[jau[ii]] = min( curlev[jau[ii]], newlev );
ii++;
}
else /* (jau[ii] > nxtlst) */
{
oldlst = nxtlst;
nxtlst = lnklst[oldlst];
}
}
next = lnklst[next];
}
/* gather the pattern magma_int_to L and U */
// printf("check line5 %d\n", i);
next = first;
while (next < i)
{
if (knzl >= *nzl) {
printf("ILU: STORAGE parameter value %d<%d too small.\n", int(*nzl), int(knzl));
printf("Increase STORAGE parameter.\n");
info = -1;
goto cleanup;
}
jal[knzl++] = next;
next = lnklst[next];
}
ial[i+1] = knzl;
// printf("check line6 %d\n", i);
if (next != i)
{
printf("ILU structurally singular.\n");
/*
assert(knzu < *nzu);
levels[knzu] = 2*n;
jau[knzu++] = i;
*/
}
// printf("check line7 %d\n", i);
// printf("next:%d n:%d \n", next, n);
while (next < n)
{
if (knzu >= *nzu) {
printf("ILU: STORAGE parameter value %d < %d too small.\n", int(*nzu), int(knzu));
printf("Increase STORAGE parameter.\n");
info = -1;
goto cleanup;
}
// printf("1 knzu:%d next:%d \n", knzu, next );
levels[knzu] = curlev[next];
// printf("2 knzu:%d next:%d \n", knzu, next );
jau[knzu++] = next;
// printf("3 knzu:%d next:%d \n", knzu, next );
next = lnklst[next];
// printf("4 next:%d n:%d \n", next, n);
}
iau[i+1] = knzu;
}
*nzl = knzl;
*nzu = knzu;
// printf("ende\n");
#if 0
printf( "Actual nnz for ILU: %d\n", *nzl + *nzu );
#endif
cleanup:
magma_free_cpu(lnklst);
magma_free_cpu(curlev);
magma_free_cpu(levels);
magma_free_cpu(iwork);
return info;
}
/******************************************************************************
*
* MEX function
*
*****************************************************************************/
void magma_smexFunction(magma_int_t nlhs, magma_int_t n, float omega,
magma_int_t levfill, magma_int_t storage,
magma_index_t * ial, magma_index_t *jal, float *al,
magma_index_t * iau, magma_index_t *jau, float *au,
magma_int_t nrhs,
magma_index_t * ia, magma_index_t *ja, float *a )
{
/* matrix is stored in CSC format, 0-based */
magma_int_t nzl, nzu;
nzl = storage;
nzu = storage;
/* the following will fail and return to matlab if insufficient storage */
magma_ssymbolic_ilu(levfill, n, &nzl, &nzu, ia, ja, ial, jal, iau, jau);
}
/* shell sort
// stable, so it is fast if already sorted
// sorts x[0:n-1] in place, ascending order.
*/
/**
Purpose
-------
This routine performs a symbolic ILU factorization.
The algorithm is taken from an implementation written by Edmond Chow.
Arguments
---------
@param[in,out]
A magma_s_matrix*
matrix in magma sparse matrix format containing the original
matrix on input, and L,U on output
@param[in]
levels magma_magma_int_t_t
fill in level
@param[out]
L magma_s_matrix*
output lower triangular matrix in magma sparse matrix format
empty on function call
@param[out]
U magma_s_matrix*
output upper triangular matrix in magma sparse matrix format
empty on function call
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_saux
********************************************************************/
extern "C"
magma_int_t
magma_ssymbilu(
magma_s_matrix *A,
magma_int_t levels,
magma_s_matrix *L,
magma_s_matrix *U,
magma_queue_t queue )
{
magma_int_t info = 0;
magma_s_matrix A_copy={Magma_CSR}, B={Magma_CSR};
magma_s_matrix hA={Magma_CSR}, CSRCOOA={Magma_CSR};
// make sure the target structure is empty
magma_smfree( L, queue );
magma_smfree( U, queue );
if( A->memory_location == Magma_CPU && A->storage_type == Magma_CSR ){
CHECK( magma_smtransfer( *A, &A_copy, Magma_CPU, Magma_CPU, queue ));
CHECK( magma_smtransfer( *A, &B, Magma_CPU, Magma_CPU, queue ));
// possibility to scale to unit diagonal
//magma_smscale( &B, Magma_UNITDIAG );
CHECK( magma_smconvert( B, L, Magma_CSR, Magma_CSR , queue));
CHECK( magma_smconvert( B, U, Magma_CSR, Magma_CSR, queue ));
magma_int_t num_lnnz = (levels > 0 ) ? B.nnz/2*(2*levels+50) : B.nnz;
magma_int_t num_unnz = (levels > 0 ) ? B.nnz/2*(2*levels+50) : B.nnz;
magma_free_cpu( L->col );
magma_free_cpu( U->col );
CHECK( magma_index_malloc_cpu( &L->col, num_lnnz ));
CHECK( magma_index_malloc_cpu( &U->col, num_unnz ));
magma_ssymbolic_ilu( levels, A->num_rows, &num_lnnz, &num_unnz, B.row, B.col,
L->row, L->col, U->row, U->col );
L->nnz = num_lnnz;
U->nnz = num_unnz;
magma_free_cpu( L->val );
magma_free_cpu( U->val );
CHECK( magma_smalloc_cpu( &L->val, L->nnz ));
CHECK( magma_smalloc_cpu( &U->val, U->nnz ));
for( magma_int_t i=0; i<L->nnz; i++ )
L->val[i] = MAGMA_S_MAKE( 0.0, 0.0 );
for( magma_int_t i=0; i<U->nnz; i++ )
U->val[i] = MAGMA_S_MAKE( 0.0, 0.0 );
// take the original values (scaled) as initial guess for L
for(magma_int_t i=0; i<L->num_rows; i++){
for(magma_int_t j=B.row[i]; j<B.row[i+1]; j++){
magma_index_t lcol = B.col[j];
for(magma_int_t k=L->row[i]; k<L->row[i+1]; k++){
if( L->col[k] == lcol ){
L->val[k] = B.val[j];
}
}
}
}
// take the original values (scaled) as initial guess for U
for(magma_int_t i=0; i<U->num_rows; i++){
for(magma_int_t j=B.row[i]; j<B.row[i+1]; j++){
magma_index_t lcol = B.col[j];
for(magma_int_t k=U->row[i]; k<U->row[i+1]; k++){
if( U->col[k] == lcol ){
U->val[k] = B.val[j];
}
}
}
}
magma_smfree( &B, queue );
// fill A with the new structure;
magma_free_cpu( A->col );
magma_free_cpu( A->val );
CHECK( magma_index_malloc_cpu( &A->col, L->nnz+U->nnz ));
CHECK( magma_smalloc_cpu( &A->val, L->nnz+U->nnz ));
A->nnz = L->nnz+U->nnz;
magma_int_t z = 0;
for(magma_int_t i=0; i<A->num_rows; i++){
A->row[i] = z;
for(magma_int_t j=L->row[i]; j<L->row[i+1]; j++){
A->col[z] = L->col[j];
A->val[z] = L->val[j];
z++;
}
for(magma_int_t j=U->row[i]; j<U->row[i+1]; j++){
A->col[z] = U->col[j];
A->val[z] = U->val[j];
z++;
}
}
A->row[A->num_rows] = z;
// reset the values of A to the original entries
for(magma_int_t i=0; i<A->num_rows; i++){
for(magma_int_t j=A_copy.row[i]; j<A_copy.row[i+1]; j++){
magma_index_t lcol = A_copy.col[j];
for(magma_int_t k=A->row[i]; k<A->row[i+1]; k++){
if( A->col[k] == lcol ){
A->val[k] = A_copy.val[j];
}
}
}
}
}
else {
magma_storage_t A_storage = A->storage_type;
magma_location_t A_location = A->memory_location;
CHECK( magma_smtransfer( *A, &hA, A->memory_location, Magma_CPU, queue ));
CHECK( magma_smconvert( hA, &CSRCOOA, hA.storage_type, Magma_CSR, queue ));
CHECK( magma_ssymbilu( &CSRCOOA, levels, L, U, queue ));
magma_smfree( &hA, queue );
magma_smfree( A, queue );
CHECK( magma_smconvert( CSRCOOA, &hA, Magma_CSR, A_storage, queue ));
CHECK( magma_smtransfer( hA, A, Magma_CPU, A_location, queue ));
}
cleanup:
if( info != 0 ){
magma_smfree( L, queue );
magma_smfree( U, queue );
}
magma_smfree( &A_copy, queue );
magma_smfree( &B, queue );
magma_smfree( &hA, queue );
magma_smfree( &CSRCOOA, queue );
return info;
}
| [
"sinkingsugar@gmail.com"
] | sinkingsugar@gmail.com |
bfbb852272b5b27ba9ce82279f984eadbc208930 | 7874f467ba69855e4892021422d86a7501d89c50 | /Rotten_orange_code.cpp | c2a039f0a3ff43364e67f60d842bffcef41f36b7 | [] | no_license | lakshaywadhwacse/Leetcode-Solutions | 3e9d32cddb489d88476d1416ef6b0fa432411069 | 624b61fab72581bae2d42741d07e720e785f6ce7 | refs/heads/master | 2022-12-13T19:33:35.372679 | 2020-08-30T07:17:23 | 2020-08-30T07:17:23 | 291,414,820 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 997 | cpp | #include<bits/stdc++.h>
using namespace std;
class help{
public:
int r;
int c;
int depth;
help(int r,int c, int depth)
{
this->r=r;
this->c=c;
this->depth=depth;
}
};
int orangesRotting(vector<vector<int>>& grid) {
int row_index[5]={0,0,-1,1};
int col_index[5]={-1,1,0,0};
queue<help> q;
for(int i=0;i<grid.size();i++)
{
for(int j=0;j<grid[0].size();j++)
{
if(grid[i][j]==2)
{
q.push(help(i,j,0));
}
}
}
int ans=0;
while(!q.empty())
{
help x= q.pop();
int row=x.r;
int col=x.col;
int depth=x.depth;
ans=max(ans,depth);
for(int i=0;i<4;i++)
{
int new_row= row+ row_index[i];
int col_index=col+col_index[i];
if((new_row>=0 and new_row<r) and (new_col>=0 and new_col<c) and grid[new_row][new_col]==1)
{
grid[new_row][new_col]=2;
q.push(help(new_row,new_col,depth+1));
}
}
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
if(grid[i][j]==1) return -1;
}
}
return ans;
}
}
int main()
{
} | [
"noreply@github.com"
] | noreply@github.com |
7dd35fed8dbc23823f5a8ab016bffe0ff7209508 | 398e1e50593b3316c44de9237c22cfb14eee8147 | /5 hls/3ph_modulator_V2/src/three_ph_mod.cpp | 1fd4a840331d7e54c0e9e2d0aa9008ff44c261e2 | [] | no_license | PowerSmartControl/NV_GAE_HIL_Demostrador | 30f1f433fd838d3ed3900a5587cf064b8ff34a71 | 8fdaee779b7377fd8a414883d6a5091759e95a62 | refs/heads/master | 2020-06-24T00:00:49.978224 | 2019-07-25T08:24:01 | 2019-07-25T08:24:01 | 198,789,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,021 | cpp | // PSC | Power Smart Control | JRF | 2018
#include "three_ph_mod.h"
void three_ph_modu (
AP_18_18 mod_a, AP_18_18 mod_b, AP_18_18 mod_c,
bool enable, AP_12_12 counter_limit_tri,
AP_18_18 *tri, AP_18_18 *modu_a,
bool *T1, bool *T2, bool *T3, bool *T4, bool *T5, bool *T6
){
static AP_12_12 counter;
static AP_12_12 index_tri;
static AP_18_18 triangular;
if (counter>counter_limit_tri){ //this establish the grid frequency
counter=0;
if (index_tri>=999) //1023
index_tri=0;
else
index_tri++;
}
/*
if (index_tri>=999) //1023
index_tri=0;
else
index_tri++;
*/
counter=counter+1;
triangular = full_tri[index_tri];
if (enable==1){
if (mod_a> triangular){
*T1=1;
*T4=0;
}
else{
*T1=0;
*T4=1;
}
if (mod_b> triangular){
*T2=1;
*T5=0;
}
else{
*T2=0;
*T5=1;
}
if (mod_c> triangular){
*T3=1;
*T6=0;
}
else{
*T3=0;
*T6=1;
}
}
else{
*T1=0;
*T2=0;
*T3=0;
*T4=0;
*T5=0;
*T6=0;
}
*modu_a=mod_a;
*tri=triangular;
}
| [
"jorge.rodriguez@powersmartcontrol.com"
] | jorge.rodriguez@powersmartcontrol.com |
5f9736aa8f10cdb1c4a1b391362ba722e4d1b7dc | dcc2f91672ec020f937b9c6d0c644faded0b3dff | /calcu/main.cpp | 1542e514482f33777fa5c684cb269f71f1d1156f | [] | no_license | lidmir/freshman_cplusplus | 3b31e6dcdfa61a6386f2653bd4be44989e0a8883 | 157fcb7847e53cc9964a3084c2bf16ac2e7f9f1d | refs/heads/master | 2020-07-10T22:26:34.391524 | 2019-08-27T01:34:28 | 2019-08-27T01:34:28 | 204,385,458 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 329 | cpp | #include"calcu.h"
void main(){
calcu obj1("5+6*2=");
obj1.printexp();
obj1.processing_str();
calcu obj2("8-3*5+6=");
obj2.printexp();
obj2.processing_str();
calcu obj3("12.5-2.2*5/3+1.3*2=");
obj3.printexp();
obj3.processing_str();
calcu obj4("3+4*5-7=");
obj4.printexp();
obj4.processing_str();
}
| [
"noreply@github.com"
] | noreply@github.com |
aa8e655cd971ebf965c78108da362c33f98ee0ca | d8660ec1251f2dede1bba2124e6b350763d9210b | /practice_programs/sort_and_compares.cpp | a3bce3a2e2a05e8b56de6028af32aea815f80d4f | [] | no_license | Wyrine/Computer-Science-1010 | af6f1644658f87a0dc76f94cefdf6b66c476f649 | 431ad2e8297751581e997811c2f0bba8d96be6f4 | refs/heads/master | 2021-01-01T03:58:18.727893 | 2016-05-10T07:02:33 | 2016-05-10T07:02:33 | 58,437,166 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 953 | cpp | int strcmp(char random1[], char random2[]){
for (int i=0; random1[i] != '\0'; i++){
if(random1[i] != random2[i]){
break;
}
}
return (random1[i] - random2[i]);
}
-------------------------------------------
void strcpy(char target[], char source[]){
for (int i=0; source[i] !='\0'; i++){
target[i] = source[i];
}
target[i]= '\0';
}
-------------------------------------------
void strcat(char target[], char source[]){
int i = 0;
int j;
while (target[i] != '\0'){
i++;
}
for(j=0; source[j] != '\0'; j++){
target[i] = source[j];
i++;
}
target[i] = '\0';
}
------------------------------------------
void selectSort(char target[], int n){
int i, top, minI;
char temp;
for(top = 0; top<n-1; top++){
minI=top;
for(i=top+1; i<n; i++){
if(target[i]<target[top]){
minI=i;
}
}
temp= target[top];
target[top]=target[minI];
target[minI]=temp;
}
} | [
"kashahat@gmail.com"
] | kashahat@gmail.com |
ec363830dbffb0e4aca5913eea46585655d2e4e1 | 52291634c4df7cae544b5a5442440cefb012beeb | /addons/CBRN_vanillaMortar/cfgWeapons.hpp | 2a1e676aa0c360271f03d1645051bbbb2748b28b | [
"MIT"
] | permissive | ZluskeN/ChemicalWarfare | 3d2a40449ed2bdaca69260be37ae11958b391267 | 7fd26955ebb8580eeaad9f912929fd1ddccbc96d | refs/heads/master | 2022-11-19T04:31:19.216776 | 2020-07-18T03:17:00 | 2020-07-18T03:17:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 190 | hpp | class cfgWeapons
{
class CannonCore;
class mortar_82mm: CannonCore
{
magazines[] += {"4Rnd_82mm_Mo_Chemical_Type0", "4Rnd_82mm_Mo_Chemical_Type1", "4Rnd_82mm_Mo_Chemical_Type2"};
};
}; | [
"jromano269962@gmail.com"
] | jromano269962@gmail.com |
e5f090ce9e5335586e478d3c8620426a32a7131f | 6c27610ed4aa7c9e14491e0e25a782e0ea88b089 | /src/execpe.cc | 363a4b3d0b67cb799b2eeb403273d251ea509457 | [
"MIT"
] | permissive | jakubskopal/node-execpe | 35427959977df63f4b5b7b77e6c2792c4ad7b65d | 8a65959e1ced580ca8aa9c9793e732d15aaab177 | refs/heads/master | 2021-01-11T21:24:26.092259 | 2017-01-13T10:56:46 | 2017-01-13T10:56:46 | 78,779,080 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,906 | cc | #include <cstdio>
#include <stdlib.h>
#include <string.h>
#if defined(__NODE_V0_11_OR_12__) || defined(__NODE_GE_V4__)
#include <fcntl.h>
#endif
//#ifdef __POSIX__
#include <unistd.h>
/*#else
#include <process.h>
#endif*/
#include <nan.h>
using v8::Array;
using v8::FunctionTemplate;
using v8::Handle;
using v8::Integer;
using v8::Local;
using v8::Object;
using v8::String;
static int clear_cloexec (int desc)
{
int flags = fcntl (desc, F_GETFD, 0);
if (flags < 0)
return flags; //return if reading failed
flags &= ~FD_CLOEXEC; //clear FD_CLOEXEC bit
return fcntl (desc, F_SETFD, flags);
}
static int do_exec(char *argv[], char *env[])
{
clear_cloexec(0); //stdin
clear_cloexec(1); //stdout
clear_cloexec(2); //stderr
return execvpe(argv[0], argv, env);
}
NAN_METHOD(execpe) {
/*
* Interface changed to be:
* 1st argument is a path
* 2nd argument array of arguments
* 3rd argument map of environment
*
*/
if ( 3 != info.Length()
|| !info[0]->IsString()
|| !info[1]->IsArray()
|| !info[2]->IsArray()) {
return Nan::ThrowTypeError("execpe: invalid arguments");
}
String::Utf8Value file(info[0]->ToString());
int i;
// Copy second argument info[1] into a c-string array called argv.
// The array must be null terminated, and the first element must be
// the name of the executable -- hence the complication.
Local<Array> argv_handle = Local<Array>::Cast(info[1]);
int argc = argv_handle->Length();
int argv_length = argc + 1 + 1;
char **argv = new char*[argv_length]; // heap allocated to detect errors
argv[0] = strdup(*file); // + 1 for file
argv[argv_length-1] = NULL; // + 1 for NULL;
for (i = 0; i < argc; i++) {
String::Utf8Value arg(argv_handle->Get(Integer::New(info.GetIsolate(), i))->ToString());
argv[i+1] = strdup(*arg);
}
// Copy third argument, info[2], into a c-string array called env.
Local<Array> env_handle = Local<Array>::Cast(info[2]);
int envc = env_handle->Length();
char **env = new char*[envc+1]; // heap allocated to detect errors
env[envc] = NULL;
for (int i = 0; i < envc; i++) {
String::Utf8Value pair(env_handle->Get(Integer::New(info.GetIsolate(), i))->ToString());
env[i] = strdup(*pair);
}
int err = do_exec(argv, env);
for (int i = 0; i < argv_length - 1; i++)
free(argv[i]);
for (int i = 0; i < envc; i++)
free(env[i]);
delete [] argv;
delete [] env;
info.GetReturnValue().Set(Integer::New(info.GetIsolate(), err));
}
#define EXPORT(name, symbol) exports->Set( \
Nan::New<String>(name).ToLocalChecked(), \
Nan::New<FunctionTemplate>(symbol)->GetFunction() \
)
void init (Handle<Object> exports) {
EXPORT("execpe", execpe);
}
NODE_MODULE(execpe, init);
| [
"j@kubs.cz"
] | j@kubs.cz |
79ee09a69949b06214c685b69726fc9aa2552168 | 0125c15213fc41b9f73a27ba21543cc88cae4208 | /Framework/Common/Scene.hpp | d7811cd1ab90e44ae4c4f65fb4a0691fde15f169 | [
"MIT"
] | permissive | kiorisyshen/GameEngineFromScratch | a3aab68e8d33fe78830573f359b8b1ded377716c | c2760084c8f1dd853f489a681ab3280647a8ece2 | refs/heads/master | 2020-03-27T06:18:34.995553 | 2019-11-07T10:28:45 | 2019-11-07T10:28:45 | 146,095,861 | 0 | 0 | MIT | 2018-08-25T13:04:12 | 2018-08-25T13:04:12 | null | UTF-8 | C++ | false | false | 2,978 | hpp | #pragma once
#include <memory>
#include <string>
#include <unordered_map>
#include "SceneObject.hpp"
#include "SceneNode.hpp"
namespace My {
class Scene {
private:
std::shared_ptr<SceneObjectMaterial> m_pDefaultMaterial;
public:
std::shared_ptr<BaseSceneNode> SceneGraph;
std::unordered_map<std::string, std::shared_ptr<SceneObjectCamera>> Cameras;
std::unordered_map<std::string, std::shared_ptr<SceneObjectLight>> Lights;
std::unordered_map<std::string, std::shared_ptr<SceneObjectMaterial>> Materials;
std::unordered_map<std::string, std::shared_ptr<SceneObjectGeometry>> Geometries;
std::unordered_multimap<std::string, std::weak_ptr<SceneCameraNode>> CameraNodes;
std::unordered_multimap<std::string, std::weak_ptr<SceneLightNode>> LightNodes;
std::unordered_multimap<std::string, std::weak_ptr<SceneGeometryNode>> GeometryNodes;
std::unordered_map<std::string, std::weak_ptr<SceneBoneNode>> BoneNodes;
std::vector<std::weak_ptr<BaseSceneNode>> AnimatableNodes;
std::unordered_map<std::string, std::weak_ptr<SceneGeometryNode>> LUT_Name_GeometryNode;
std::shared_ptr<SceneObjectSkyBox> SkyBox;
std::shared_ptr<SceneObjectTerrain> Terrain;
public:
Scene() {
m_pDefaultMaterial = std::make_shared<SceneObjectMaterial>("default");
SkyBox = std::make_shared<SceneObjectSkyBox>();
SkyBox->SetName("Textures/hdr/spruit_sunrise", "dds");
Terrain = std::make_shared<SceneObjectTerrain>();
Terrain->SetName("Textures/terrain/area_1", "png");
}
Scene(const std::string& scene_name) :
SceneGraph(new BaseSceneNode(scene_name))
{
m_pDefaultMaterial = std::make_shared<SceneObjectMaterial>("default");
SkyBox = std::make_shared<SceneObjectSkyBox>();
SkyBox->SetName("Textures/hdr/spruit_sunrise", "dds");
Terrain = std::make_shared<SceneObjectTerrain>();
Terrain->SetName("Textures/terrain/area_1", "png");
}
~Scene() = default;
const std::shared_ptr<SceneObjectCamera> GetCamera(const std::string& key) const;
const std::shared_ptr<SceneCameraNode> GetFirstCameraNode() const;
const std::shared_ptr<SceneObjectLight> GetLight(const std::string& key) const;
const std::shared_ptr<SceneLightNode> GetFirstLightNode() const;
const std::shared_ptr<SceneObjectGeometry> GetGeometry(const std::string& key) const;
const std::shared_ptr<SceneGeometryNode> GetFirstGeometryNode() const;
const std::shared_ptr<SceneObjectMaterial> GetMaterial(const std::string& key) const;
const std::shared_ptr<SceneObjectMaterial> GetFirstMaterial() const;
void LoadResource(void);
};
}
| [
"chenwenli@chenwenli.com"
] | chenwenli@chenwenli.com |
4ee11a3928654cc48d9e4a93d966835aeefe7fbd | 1751eec1d2b4d703a690f9428dbcfe64425e242a | /BattleTank/Source/BattleTank/Private/SprungWheel.cpp | 34a59c821aabd2e13773caccd9f0b1db2cda8114 | [] | no_license | trikraig/Battle-Tank-UE4 | 8f6bd4e6733512981103a88bd74c2d3d4cf92704 | eed159ed34f452b327e4bf14cac338d78146ce7e | refs/heads/master | 2022-11-12T02:25:18.446492 | 2020-06-08T13:04:34 | 2020-06-08T13:04:34 | 267,599,778 | 0 | 0 | null | 2020-06-23T08:44:52 | 2020-05-28T13:38:18 | C++ | UTF-8 | C++ | false | false | 1,155 | cpp | // Copyright Craig Palmer 2020
#include "PhysicsEngine/PhysicsConstraintComponent.h"
#include "Components/StaticMeshComponent.h"
#include "SprungWheel.h"
// Sets default values
ASprungWheel::ASprungWheel()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
MassWheelConstraint = CreateDefaultSubobject<UPhysicsConstraintComponent>(FName("Physics Constraint"));
SetRootComponent(MassWheelConstraint);
Wheel = CreateDefaultSubobject<UStaticMeshComponent>(FName("Wheel"));
Wheel->SetupAttachment(MassWheelConstraint);
}
// Called when the game starts or when spawned
void ASprungWheel::BeginPlay()
{
Super::BeginPlay();
SetupConstraint();
}
void ASprungWheel::SetupConstraint()
{
if (!GetAttachParentActor()) { return; }
UPrimitiveComponent* BodyRoot = Cast<UPrimitiveComponent>(GetAttachParentActor()->GetRootComponent());
if (!BodyRoot) { return; }
MassWheelConstraint->SetConstrainedComponents(BodyRoot, NAME_None, Wheel, NAME_None);
}
// Called every frame
void ASprungWheel::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
| [
"craigplmr434@gmail.com"
] | craigplmr434@gmail.com |
d71f2bc0d2c830e1a8099ea58700d9c705462921 | c12dc233139fc8aa95877e6081e671c4a972b091 | /TARGET/IlcTARGETChannelSPD.h | 00c58bfdb971ca9958b32f91d3a8c4cdb5e0b186 | [] | no_license | yanqicw/ORKA-ILCRoot | b4be984cb9f1991b0c174da7428366af4973ef84 | 6e66c4cbae6835586274a385bee9bed254a63976 | refs/heads/master | 2020-04-01T02:27:50.942859 | 2012-12-03T17:51:10 | 2012-12-03T17:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,905 | h | #ifndef ILCTARGETCHANNELSPD_H
#define ILCTARGETCHANNELSPD_H
/* Copyright(c) 2005-2006, ILC Project Experiment, All rights reserved. *
* See cxx source for full Copyright notice */
/* $Id: IlcTARGETChannelSPD.h,v 1.1.1.1 2008/03/11 14:52:51 vitomeg Exp $ */
///////////////////////////////////////////////////////////////////////////
// IlcTARGETChannelSPD declaration by P. Nilsson 2005
// AUTHOR/CONTACT: Paul.Nilsson@cern.ch
//
// Objects of this class are stored in a TObjArray and should be
// interpreted as "bad" channels, i.e. either noisy or dead channels
// depending on where they are stored
///////////////////////////////////////////////////////////////////////////
#include <TObject.h>
class IlcTARGETChannelSPD: public TObject {
public:
IlcTARGETChannelSPD(void); // Default constructor
IlcTARGETChannelSPD(Int_t column, Int_t row); // Constructor for already existing "bad" channel
IlcTARGETChannelSPD(const IlcTARGETChannelSPD &ch); // Copy constructor
virtual ~IlcTARGETChannelSPD(void) { }; // Default destructor
IlcTARGETChannelSPD& operator=(const IlcTARGETChannelSPD &ch); // Assignment operator
Bool_t operator==(const IlcTARGETChannelSPD &channel) const; // Equivalence operator
// Getters and setters
Int_t GetColumn(void) const { return fColumn; }; // Get column
Int_t GetRow(void) const { return fRow; }; // Get row
void SetColumn(Int_t c) { fColumn = c; }; // Set column
void SetRow(Int_t r) { fRow = r; }; // Set row
protected:
Int_t fColumn; // SPD column (real range [0,31], but not checked)
Int_t fRow; // SPD row (real range [0,255] but not checked)
ClassDef(IlcTARGETChannelSPD,1)
};
#endif
| [
"anna@fbb65c11-2394-7148-9363-1d506dd39c89"
] | anna@fbb65c11-2394-7148-9363-1d506dd39c89 |
a83c8ef655bae469c27ba974958ace6c914b7223 | ac9099e352d722f4ce22683c78a1a5ad9f8a7105 | /Headquarter.h | 5d81e72d398f662b38bcbf9f4056134b3cac2a48 | [] | no_license | rlongying/Warcraft | 70a6cb6497721d3eb58d35f27fdb40fcc0be8d13 | b710c0e63113704b7ecd5916079e48055463be8e | refs/heads/master | 2020-11-27T15:03:16.647702 | 2019-12-22T07:24:58 | 2019-12-22T07:24:58 | 229,502,341 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,609 | h | //
// Created by Mengjun Wang on 2019-12-21.
//
#ifndef WARCRAFT_HEADQUARTER_H
#define WARCRAFT_HEADQUARTER_H
#include <string>
#include <utility>
#include <vector>
#include <map>
#include <cmath>
#include "Warrior.h"
#include "Constants.h"
using namespace std;
class Headquarter {
private:
string name;
string warriorSequence[WARRIOR_TYPES];
map<string, int> strengthMap;
map<string, vector<Warrior *>> warriors;
int totalStrength;
int warriorId = 1; // id of warriors starts from 1
Warrior *currentWarrior = nullptr;
bool stopped = false;
public:
/**
* create a headquarter
* @param name
* @param seq an array of 5 element specifying the order of creating warriors
* @param strengths an array of 5 element specifying strength of "dragon, ninja, iceman, lion, wolf" respectively
*/
Headquarter(string name, string seq[WARRIOR_TYPES], map<string, int> strengthMap, int total)
: name(std::move(name)), strengthMap(std::move(strengthMap)), totalStrength(total) {
for (int i = 0; i < WARRIOR_TYPES; ++i) {
warriorSequence[i] = seq[i];
}
}
bool produce(int time);
bool hasStopped() {return stopped;}
void createWarrior(const string&);
inline static double roundToTwoPoints(double val) {
return round( val * 100.0) / 100.0;
}
static string timeToString(int time);
~Headquarter(){
for(auto & warrior : warriors){
for(Warrior* p : warrior.second){
delete p;
}
}
}
};
#endif //WARCRAFT_HEADQUARTER_H
| [
"wmj900823@gmail.com"
] | wmj900823@gmail.com |
a6077a1af7807b8502cc1a0978db45df50234401 | 3b8dabfbb8e3090700bd74c97f3b8f9acb28816b | /src/statJostD_C.cpp | f25b537f44a525df0ca1c9e52ac0a7c607f68594 | [] | no_license | cran/strataG | 5856921d12bcd5645f352cb86da92b43db407408 | 94c21cf47fba3cf01bfa897e906ccf87d9b4027c | refs/heads/master | 2020-12-29T02:43:27.649581 | 2020-02-28T06:10:02 | 2020-02-28T06:10:02 | 28,669,211 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,716 | cpp | #include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector statJostD_C(IntegerMatrix loci, IntegerMatrix strataMat) {
// function declarations
IntegerMatrix table2D(IntegerVector, IntegerVector);
IntegerVector calcStrataN(IntegerVector, IntegerVector, int);
double harmonicMean_C(NumericVector);
NumericVector terms(loci.ncol());
NumericVector estVec(strataMat.ncol());
int ploidy(loci.nrow() / strataMat.nrow());
int numStrata(unique(strataMat(_, 0)).size());
for(int idx = 0; idx < estVec.size(); idx++) {
for(int i = 0; i < loci.ncol(); i++) {
IntegerMatrix alleleStrataFreq = table2D(loci(_, i), rep_each(strataMat(_, idx), ploidy));
NumericMatrix iTerms(2, alleleStrataFreq.nrow());
for(int a = 0; a < iTerms.ncol(); a++) {
NumericMatrix jTerms(3, alleleStrataFreq.ncol());
for(int s = 0; s < jTerms.ncol(); s++) {
double Nj = sum(alleleStrataFreq(_, s));
double Nij = alleleStrataFreq(a, s);
jTerms(0, s) = Nij / Nj;
jTerms(1, s) = pow(jTerms(0, s), 2);
jTerms(2, s) = Nij * (Nij - 1) / (Nj * (Nj - 1));
}
double aTerm1 = pow(sum(jTerms(0, _)), 2);
double aTerm2 = sum(jTerms(1, _));
iTerms(0, a) = (aTerm1 - aTerm2) / (numStrata - 1);
iTerms(1, a) = sum(jTerms(2, _));
}
terms[i] = 1 - sum(iTerms(0, _)) / sum(iTerms(1, _));
}
for(int i = 0; i < terms.size(); i++) {
if(terms[i] < 0) terms[i] = 0;
}
double est;
if(terms.size() > 1) {
est = harmonicMean_C(terms);
} else {
est = terms[0];
}
if(std::isnan(est)) est = NA_REAL;
estVec[idx] = est;
}
return estVec;
}
| [
"csardi.gabor+cran@gmail.com"
] | csardi.gabor+cran@gmail.com |
cfe07175d738e608c000248929241c199d24a930 | fcd9c2e29a76f49fe085458edeb58857b2f7b564 | /fusion/utils/sim/sim.cpp | 4e63fa31fbd3e7a126e010c18cd480ce40ac962a | [] | no_license | vicavo/fusion | d66bc907990876ee06810133f7eb3851044738af | ce865c42f8e3da6fafce9c204aa7806f679f755e | refs/heads/master | 2021-01-02T23:04:14.667225 | 2016-03-01T03:53:21 | 2016-03-01T03:53:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,384 | cpp | /*
* FUSION
* Copyright (c) 2012-2013 Alex Kosterin
*/
#include <stdio.h>
#include <string.h>
#include "include/nf.h" // FUSION
#include "include/nf_macros.h"
#include "include/mb.h" // FUSION MESSAGE BUS
#include "include/tsc.h"
#define NOGDI
#define _WINSOCKAPI_
#include <windows.h>
#include <wincon.h>
#include <vector>
#include <algorithm>
#define MAX_MESSAGES (16)
struct msg_t {
const char* name_; // message name
nf::mid_t mid_; // message descriptor
size_t size_; // message size, -1 if variable
FILE* fd_; // file descriptod for gicen message
// data section
int msecs_;
size_t len_; // used for variable size messages
void* data_;
};
static msg_t msgs[MAX_MESSAGES] = {};
static size_t msg_nr = 0;
static nf::msecs_t org;
static bool mycompare(int a, int b) {
return msgs[a].msecs_ < msgs[b].msecs_;
}
static bool stop = false;
static size_t msg_done = 0;
////////////////////////////////////////////////////////////////////////////////
//
// Reading next data associated with message in msgs[i] array
// Actual data will be kept in data section of msg_t struct
//
bool readmsg(size_t i) {
size_t sz = ::fread(&msgs[i].msecs_, sizeof msgs[i].msecs_, 1, msgs[i].fd_);
if (sz != 1)
return false;
if (msgs[i].size_ != -1) {
if (!msgs[i].data_)
msgs[i].data_ = ::malloc(msgs[i].size_);
}
else {
sz = ::fread(&msgs[i].len_, sizeof msgs[i].len_, 1, msgs[i].fd_);
if (sz != 1)
return false;
msgs[i].data_ = ::realloc(msgs[i].data_, msgs[i].size_);
}
sz = ::fread(msgs[i].data_, msgs[i].len_, 1, msgs[i].fd_);
if (sz != 1)
return false;
return true;
}
////////////////////////////////////////////////////////////////////////////////
//
// Write next data associated with message in msgs[i] array
// This is fusion callback function that is triggered when a message arrives.
//
nf::result_t __stdcall writemsg(nf::mid_t mid, size_t len, const void *data) {
static bool first_write = true;
nf::msecs_t now = nf::now_msecs();
// Find index into 'msgs[]' associated with given 'mid'.
for (size_t i = 0; i < msg_nr; ++i)
if (msgs[i].mid_ == mid) {
FUSION_ASSERT(msgs[i].size_ == -1 || msgs[i].size_ == len);
msgs[i].msecs_ = (int)(now - org);
size_t sz = ::fwrite(&msgs[i].msecs_, sizeof msgs[i].msecs_, 1, msgs[i].fd_);
FUSION_ASSERT(sz == 1);
if (msgs[i].size_ == -1) {
sz = ::fwrite(&len, sizeof len, 1, msgs[i].fd_);
FUSION_ASSERT(sz == 1);
}
if (len) {
sz = ::fwrite(data, len, 1, msgs[i].fd_);
FUSION_ASSERT(sz == 1);
}
break;
}
++msg_done;
return nf::ERR_OK;
}
////////////////////////////////////////////////////////////////////////////////
void usage(const char* prog) {
fprintf(stderr, "usage: %s --host=IP4ADDR --port=PORT [--dir=PATH] --mode=play|record --mssage=NAME [--message=NAME]...\n", prog);
exit(1);
}
////////////////////////////////////////////////////////////////////////////////
BOOL WINAPI on_break(DWORD CtrlType) {
stop = true;
return TRUE;
}
////////////////////////////////////////////////////////////////////////////////
int main(int argc, const char** argv) {
nf::client_t client("simple simulator: player/recorder");
const char* port = "3001";
const char* host = "127.0.0.1";
const char* profile = "unknown";
const char* dir = "./";
double rate = 1.;
char connect[250] = {};
bool play = true;
size_t err_nr = 0;
nf::result_t e;
//
// Parameter parsing
//
for (int i = 1; i < argc; ++i) {
size_t len;
if ( (len = 7) && ::strncmp(argv[i], "--port=", len) == 0)
port = argv[i] + len;
else if ((len = 7) && ::strncmp(argv[i], "--host=", len) == 0)
host = argv[i] + len;
else if ((len = 10) && ::strncmp(argv[i], "--profile=", len) == 0)
profile = argv[i] + len;
else if ((len = 13) && ::strncmp(argv[i],"--mode=record", len) == 0)
play = false;
else if ((len = 8) && ::strncmp(argv[i], "--record", len) == 0)
play = false;
else if ((len = 11) && ::strncmp(argv[i],"--mode=play", len) == 0)
play = true;
else if ((len = 6) && ::strncmp(argv[i], "--play", len) == 0)
play = true;
else if ((len = 6) && ::strncmp(argv[i], "--dir=", len) == 0)
dir = argv[i] + len;
else if ((len = 7) && ::strncmp(argv[i], "--rate=", len) == 0)
rate = ::atof(argv[i] + len);
else if (
((len = 6) && ::strncmp(argv[i], "--msg=", len) == 0) ||
((len =10) && ::strncmp(argv[i], "--message=", len) == 0)
) {
if (msg_nr >= MAX_MESSAGES) {
fprintf(stderr, "error: too many messages, max=%d\n", MAX_MESSAGES);
++err_nr;
}
char buff[MAX_PATH] = {0};
int sz = 0;
size_t nr = ::_snscanf(argv[i] + len, ::strlen(argv[i]) - len, "%" STRINGIFY(MAX_PATH) "[^:]:%d", buff, &sz);
if (nr != 2) {
fprintf(stderr, "error: message format=<message-name>:<size>\t\"%s\"\n", argv[i] + len);
++err_nr;
}
if (sz < -1 || sz > 32000) {
fprintf(stderr, "error: message size is out of range=-1..32000\t\"%s\"\n", argv[i] + len);
++err_nr;
}
msgs[msg_nr].name_ = ::strdup(buff);
msgs[msg_nr].size_ = sz;
++msg_nr;
}
else {
fprintf(stderr, "error: arg=%d\n", argv[i]);
++err_nr;
}
}
if (err_nr)
usage(argv[0]);
fprintf(stderr, "%s: using host=%s port=%s profile=%s dir=%s rate=%g messages=", argv[0], host, port, profile, dir, rate);
for (size_t i = 0; i < msg_nr; ++i)
fprintf(stderr, "\"%s:%d\"%s", msgs[i].name_, msgs[i].size_, i < msg_nr - 1 ? ", " : "");
fprintf(stderr, "\n");
if (!msg_nr) {
fprintf(stderr, "error: no messages given\n", MAX_MESSAGES);
usage(argv[0]);
}
if (rate < 0.) {
fprintf(stderr, "error: rate must be greater then 0.\n", MAX_MESSAGES);
usage(argv[0]);
}
::SetConsoleCtrlHandler(on_break, TRUE);
//
// Register with fusion
//
_snprintf(connect, sizeof connect - 1, "type=tcp host=%s port=%s", host, port);
if ((e = client.reg(connect, profile)) != nf::ERR_OK) {
fprintf(stderr, "error: reg=%d\n", e);
return 1;
}
FUSION_DEBUG("client id=%d", client.id());
err_nr = 0;
//
// Open messages
//
for (size_t i = 0; i < msg_nr; ++i) {
msgs[i].size_ = -1;
msgs[i].msecs_ = 0;
nf::mtype_t mt;
if ((e = client.mopen(msgs[i].name_, play ? nf::O_WRONLY : nf::O_RDONLY , mt, msgs[i].mid_, msgs[i].size_)) != nf::ERR_OK) {
fprintf(stderr, "error: mopen(%s)=%d\n", msgs[i].name_, e);
++err_nr;
continue;
}
if (msgs[i].size_ != -1)
msgs[i].len_ = msgs[i].size_;
}
//
// Open files to read/write message content
//
char buff[MAX_PATH + 1];
org = nf::now_msecs();
for (size_t i = 0; i < msg_nr; ++i) {
::_snprintf(buff, sizeof buff - 1, "%s/%s.data", dir, msgs[i].name_);
if (!(msgs[i].fd_ = ::fopen(buff, play ? "rb" : "wb"))) {
::fprintf(stderr, "error: fopen(%s)\n", msgs[i].name_);
++err_nr;
continue;
}
size_t sz;
if (play) {
sz = ::fread(&org, sizeof org, 1, msgs[i].fd_);
FUSION_ASSERT(sz == 1);
::fread(&sz, sizeof sz, 1, msgs[i].fd_);
FUSION_ASSERT(sz == 1);
if (sz != msgs[i].size_) {
::fprintf(stderr, "error: message size mismatch %s: fusion=%d vs file=%d)\n", msgs[i].name_, sz, msgs[i].size_);
++err_nr;
}
}
else {
sz = ::fwrite(&org, sizeof org, 1, msgs[i].fd_);
FUSION_ASSERT(sz == 1);
sz = ::fwrite(&msgs[i].size_, sizeof msgs[i].size_, 1, msgs[i].fd_);
FUSION_ASSERT(sz == 1);
}
}
if (!err_nr) {
if (play) {
// Paying work loop
std::vector<int> queue;
for (size_t i = 0; i < msg_nr; ++i)
if (readmsg(i))
queue.push_back(i);
while (!stop && !queue.empty()) {
std::sort(queue.begin(), queue.end(), mycompare);
size_t p = queue.front();
::Sleep((DWORD)((double)msgs[p].msecs_ / rate));
if (nf::ERR_OK == client.publish(msgs[p].mid_, msgs[p].len_, msgs[p].data_))
++msg_done;
for (size_t i = 1; i < queue.size(); ++i)
msgs[queue[i]].msecs_ -= msgs[p].msecs_;
if (!readmsg(p))
queue.erase(queue.begin());
}
}
else {
// Recording work loop
for (size_t i = 0; i < msg_nr; ++i)
if ((e = client.subscribe(msgs[i].mid_, nf::SF_PUBLISH, nf::CM_MANUAL, writemsg)) != nf::ERR_OK) {
fprintf(stderr, "warn: mclose(%s)=%d\n", msgs[i].name_, e);
goto done;
}
while (!stop && client.registered()) {
client.dispatch(true);
::Sleep(1); // do not goble all CPU
}
}
}
::Sleep(1); // @@
//
// Close messages
// note: mclose() also does unsubscribe()
//
for (size_t i = 0; i < msg_nr; ++i) {
fclose(msgs[i].fd_);
client.mclose(msgs[i].mid_);
if (msgs[i].data_)
free(msgs[i].data_);
}
//
// Unregister
//
done:
e = client.unreg();
if (e != nf::ERR_OK)
FUSION_DEBUG("unreg=%d", e);
fprintf(stderr, "%s messages %s: %d", argv[0], play ? "published": "received", msg_done);
return 0;
}
| [
"alex.kosterin@notgmail.com"
] | alex.kosterin@notgmail.com |
dccd41740b10282dc0bf7508ce30db146d136b68 | fae551eb54ab3a907ba13cf38aba1db288708d92 | /third_party/blink/renderer/modules/webcodecs/image_track.h | 391eed25232e37a85c575944e614aaccdbfcfd3a | [
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft"
] | permissive | xtblock/chromium | d4506722fc6e4c9bc04b54921a4382165d875f9a | 5fe0705b86e692c65684cdb067d9b452cc5f063f | refs/heads/main | 2023-04-26T18:34:42.207215 | 2021-05-27T04:45:24 | 2021-05-27T04:45:24 | 371,258,442 | 2 | 1 | BSD-3-Clause | 2021-05-27T05:36:28 | 2021-05-27T05:36:28 | null | UTF-8 | C++ | false | false | 1,649 | h | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_WEBCODECS_IMAGE_TRACK_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_WEBCODECS_IMAGE_TRACK_H_
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/modules/webcodecs/image_track_list.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/member.h"
namespace blink {
class MODULES_EXPORT ImageTrack final : public ScriptWrappable {
DEFINE_WRAPPERTYPEINFO();
public:
ImageTrack(ImageTrackList* image_track_list,
wtf_size_t id,
uint32_t frame_count,
int repetition_count,
bool selected);
~ImageTrack() override;
// image_track.idl implementation.
uint32_t frameCount() const;
bool animated() const;
float repetitionCount() const;
bool selected() const;
void setSelected(bool selected);
// Internal helpers for ImageTrackList.
void disconnect() { image_track_list_ = nullptr; }
void set_selected(bool selected) { selected_ = selected; }
void UpdateTrack(uint32_t frame_count, int repetition_count);
// GarbageCollected override
void Trace(Visitor* visitor) const override;
private:
const wtf_size_t id_;
Member<ImageTrackList> image_track_list_;
uint32_t frame_count_ = 0u;
int repetition_count_ = 0;
bool selected_ = false;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_WEBCODECS_IMAGE_TRACK_H_
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
fa41910a93c6146f507a33f0703a8e31b2de2120 | 693f6694c179ea26c34f4cfd366bcf875edd5511 | /trains/izho2012day2/G.cpp | ffc9ac9fc9320c99e9317f91b2937142e340a0b3 | [] | no_license | romanasa/olymp_codes | db4a2a6af72c5cc1f2e6340f485e5d96d8f0b218 | 52dc950496ab28c4003bf8c96cbcdb0350f0646a | refs/heads/master | 2020-05-07T18:54:47.966848 | 2019-05-22T19:41:38 | 2019-05-22T19:41:38 | 180,765,711 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,007 | cpp | #include <bits/stdc++.h>
#define err(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)
using namespace std;
typedef long long ll;
#define TASK "g"
/*struct segment {
int val, len, pos;
bool operator < (const segment &b) const {
return pos < b.pos;
}
};*/
typedef pair<int, pair<int, int> > segment;
#define val second.first
#define len second.second
#define pos first
set<segment> S;
priority_queue<pair<int, int> > T;
void calc(int pos, int mx, vector<int> &x) {
int n = (int)x.size();
vector<pair<int, int> > cur;
for (int i = 0; i < n; i++) {
int ind = (pos + i) % n;
if (cur.empty() || cur.back().first != x[ind]) cur.push_back({ x[ind], 1 });
else cur.back().second++;
}
for (int i = 0; i < (int)cur.size(); i++) {
auto c = cur[i];
int pr = cur[i ? i - 1 : (int)cur.size() - 1].first;
int nt = cur[(i + 1) % (int)cur.size()].first;
S.insert(make_pair(pos, c));
if (c.first < pr && c.first < nt) T.push({ -c.second, pos });
pos = (pos + c.second) % n;
}
}
void add(segment c) {
auto it = S.insert(c).first;
auto prv = it;
if (it == S.begin()) prv = --S.end();
else --prv;
auto nxt = it;
if (it == --S.end()) nxt = S.begin();
else ++nxt;
if (c.val < nxt->val && c.val < prv->val) T.push({ -c.len, c.pos });
}
int main() {
#ifndef HOME
freopen(TASK".in", "r", stdin), freopen(TASK".out", "w", stdout);
#endif
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, k;
cin >> n >> k;
vector<int> x(n);
for (int i = 0; i < n; i++) cin >> x[i];
int pos = -1;
for (int i = 0; i < n; i++) {
if (x[i] != x[(i + 1) % n]) pos = (i + 1) % n;
}
if (pos == -1) return 0 * puts("0");
int mx = *max_element(x.begin(), x.end());
calc(pos, mx, x);
int ans = 0;
while (T.size() && k >= -T.top().first) {
k -= (-T.top().first);
auto it = S.lower_bound(make_pair(T.top().second, make_pair(-1, -1)));
T.pop();
ans += 2;
if (S.size() == 1) break;
auto prv = it;
if (it == S.begin()) prv = --S.end();
else --prv;
auto nxt = it;
if (it == --S.end()) nxt = S.begin();
else ++nxt;
if (prv == nxt) {
if (it->val + 1 < prv->val) {
auto c = *it;
S.erase(it);
c.val++;
add(c);
} else {
auto c = *it;
c.val++;
c.len += prv->len;
S.erase(it);
S.erase(prv);
add(c);
}
} else {
if (it->val + 1 < prv->val && it->val + 1 < nxt->val) {
auto c = *it;
S.erase(it);
c.val++;
add(c);
} else if (it->val + 1 < prv->val) {
auto c = *it;
c.len += nxt->len;
c.val++;
S.erase(it);
S.erase(nxt);
add(c);
} else if (it->val + 1 < nxt->val) {
auto c = *it;
c.len += prv->len;
c.pos = prv->pos;
c.val++;
S.erase(it);
S.erase(prv);
add(c);
} else {
auto c = *it;
c.len += prv->len;
c.len += nxt->len;
c.pos = prv->pos;
c.val++;
S.erase(it);
S.erase(prv);
S.erase(nxt);
add(c);
}
}
}
cout << ans << "\n";
return 0;
} | [
"romanfml31@gmail.com"
] | romanfml31@gmail.com |
df55edab4c5d32218669251fc6e7ebba8f048928 | 1eb962b733ff89dddb01655c3986e2665bd1ffc2 | /192D/main.cpp | abc667cc568008b84b7712118b296498b68fe664 | [] | no_license | sh19910711/codeforces-solutions | b4d6affe8d9bb0298275f7d0e94657e5472f2276 | 5784408c23fd61b6fcf32e3dacc8a706f31ac96e | refs/heads/master | 2021-01-23T03:53:52.931042 | 2015-10-03T20:01:00 | 2015-10-03T20:03:22 | 8,685,265 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,307 | cpp |
// @snippet<sh19910711/contest:headers.cpp>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <algorithm>
#include <numeric>
#include <limits>
#include <complex>
#include <functional>
#include <iterator>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
// @snippet<sh19910711/contest:solution/interface.cpp>
namespace solution {
class SolutionInterface {
public:
virtual int run() = 0;
protected:
virtual void pre_calc() {}
virtual bool action() = 0;
virtual void init() {};
virtual bool input() { return false; };
virtual void output() {};
SolutionInterface() {}
private:
};
}
// @snippet<sh19910711/contest:solution/solution-base.cpp>
namespace solution {
class SolutionBase: public SolutionInterface {
public:
virtual int run() {
pre_calc();
while ( action() );
return 0;
}
};
}
// @snippet<sh19910711/contest:solution/typedef.cpp>
namespace solution {
typedef std::istringstream ISS;
typedef std::ostringstream OSS;
typedef std::vector<std::string> VS;
typedef long long LL;
typedef int INT;
typedef std::vector<INT> VI;
typedef std::vector<VI> VVI;
typedef std::pair<INT,INT> II;
typedef std::vector<II> VII;
}
// @snippet<sh19910711/contest:solution/namespace-area.cpp>
namespace solution {
// namespaces, types
using namespace std;
typedef std::priority_queue<LL, std::vector<LL>, std::greater<LL> > Queue;
}
// @snippet<sh19910711/contest:solution/variables-area.cpp>
namespace solution {
// constant vars
const int SIZE = 100000 + 11;
const int INF = std::numeric_limits<int>::max();
// storages
int n, k;
LL b;
LL A[SIZE];
Queue Q;
LL t;
int days;
int result;
}
// @snippet<sh19910711/contest:solution/solver-area.cpp>
namespace solution {
class Solver {
public:
void solve() {
result = find_minimum_number();
}
int find_minimum_number() {
int res = n;
t = 0;
days = 0;
for ( int i = n - 2; i >= 0; -- i ) {
if ( check(i) ) {
res = std::min(res, i + 1);
}
}
return res;
}
bool check( int ai ) {
bool res = false;
t += A[ai];
Q.push(A[ai]);
if ( t > b ) {
res = true;
}
days ++;
if ( days >= k ) {
days --;
t -= Q.top();
Q.pop();
}
return res;
}
private:
};
}
// @snippet<sh19910711/contest:solution/solution.cpp>
namespace solution {
class Solution: public SolutionBase {
public:
protected:
virtual bool action() {
init();
if ( ! input() )
return false;
solver.solve();
output();
return true;
}
void init() {
Q = Queue();
}
bool input() {
if ( ! ( cin >> n >> k ) )
return false;
cin >> b;
for ( int i = 0; i < n; ++ i ) {
cin >> A[i];
}
return true;
}
void output() {
cout << result << endl;
}
private:
Solver solver;
};
}
// @snippet<sh19910711/contest:main.cpp>
#ifndef __MY_UNIT_TEST__
int main() {
return solution::Solution().run();
}
#endif
| [
"sh19910711@gmail.com"
] | sh19910711@gmail.com |
61255064101eb9e8895db817388d359d03d13714 | 70cad1c98834ed6dc37e1e0746dd2915af9da332 | /boost/libs/type_traits/test/is_convertible_test.cpp | 7c04e91fd9a5fb06c249994e10864eb1c8dd6580 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | zchn/mcsema | 2ea5824a2662a7e33840aee9c79edb65ea547c54 | ca0340249359751611a64ab1255b9176050f3ee5 | refs/heads/master | 2020-12-31T06:47:39.263401 | 2015-10-23T23:38:08 | 2015-10-23T23:38:08 | 45,649,444 | 0 | 0 | NOASSERTION | 2020-10-13T23:29:58 | 2015-11-06T00:41:57 | C++ | UTF-8 | C++ | false | false | 9,595 | cpp |
// (C) Copyright John Maddock 2000.
// Use, modification and distribution are subject to 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 "test.hpp"
#include "check_integral_constant.hpp"
#ifdef TEST_STD
# include <type_traits>
#else
# include <boost/type_traits/is_convertible.hpp>
#endif
#include <boost/utility/enable_if.hpp>
template <class T>
struct convertible_from
{
convertible_from(T);
};
struct base2 { };
struct middle2 : public virtual base2 { };
struct derived2 : public middle2 { };
#if !defined(BOOST_NO_RVALUE_REFERENCES)
template<typename T>
struct test_bug_4530
{
template<typename A>
test_bug_4530(A&&, typename boost::enable_if<boost::is_convertible<A&&, T> >::type* =0);
};
struct A4530
{
template <class T>
A4530(T);
};
#endif
#ifdef BOOST_MSVC
struct bug_5271a
{
__declspec(align(16)) int value;
};
struct bug_5271b
{
__declspec(align(16)) int value;
bug_5271b(int v) : value(v) {}
};
#endif
TT_TEST_BEGIN(is_convertible)
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Derived,Base>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Derived,Derived>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Base,Base>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Base,Derived>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Derived,Derived>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<NonDerived,Base>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<virtual_inherit2,virtual_inherit1>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<VD,VB>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<polymorphic_derived1,polymorphic_base>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<polymorphic_derived2,polymorphic_base>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<polymorphic_base,polymorphic_derived1>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<polymorphic_base,polymorphic_derived2>::value), false);
#ifndef TEST_STD
// Ill-formed behaviour, supported by Boost as an extension:
#ifndef BOOST_NO_IS_ABSTRACT
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<test_abc1,test_abc1>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Base,test_abc1>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<polymorphic_derived2,test_abc1>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int,test_abc1>::value), false);
#endif
#endif
// The following four do not compile without member template support:
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,void>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<void,void>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<void,float>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<enum1, int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Derived*, Base*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Base*, Derived*>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Derived&, Base&>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<Base&, Derived&>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const Derived*, const Base*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const Base*, const Derived*>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const Derived&, const Base&>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const Base&, const Derived&>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const int *, int*>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const int&, int&>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const int*, int[3]>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const int&, int>::value), true);
#ifndef BOOST_NO_RVALUE_REFERENCES
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const int&&, int>::value), true);
#endif
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int(&)[4], const int*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int(&)(int), int(*)(int)>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int *, const int*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int&, const int&>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int[2], int*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int[2], const int*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<const int[2], int*>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int*, int[3]>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<test_abc3, const test_abc1&>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<non_pointer, void*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<non_pointer, int*>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<non_int_pointer, int*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<non_int_pointer, void*>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<test_abc1&, test_abc2&>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<test_abc1&, int_constructible>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int_constructible, test_abc1&>::value), false);
#if !defined(BOOST_NO_IS_ABSTRACT) && !(defined(__hppa) && defined(__HP_aCC))
//
// This doesn't work with aCC on PA RISC even though the is_abstract tests do
// all pass, this may indicate a deeper problem...
//
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<test_abc1&, test_abc2>::value), false);
#endif
//
// the following tests all involve user defined conversions which do
// not compile with Borland C++ Builder 5:
//
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int, int_constructible>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,convertible_from<float> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,convertible_from<float const&> >::value), true);
//
// These two tests give different results with different compilers, we used to require *true* results
// from these, but C++0x behaviour requires *false*:
//
//BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,convertible_from<float&> >::value), false);
//BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<char,convertible_from<char&> >::value), false);
#if !(defined(__GNUC__) && (__GNUC__ < 4))
// GCC 3.x emits warnings here, which causes the tests to fail when we compile with warnings-as-errors:
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,convertible_from<char> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,convertible_from<char const&> >::value), true);
#endif
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,convertible_from<char&> >::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<char,convertible_from<char> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<char,convertible_from<char const&> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float&,convertible_from<float> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float const&,convertible_from<float> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float&,convertible_from<float&> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float const&,convertible_from<float const&> >::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float&,convertible_from<float const&> >::value), true);
//
// the following all generate warnings unless we can find a way to
// suppress them:
//
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<float,int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<double,int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<double,float>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<long,int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int,char>::value), true);
#ifdef BOOST_HAS_LONG_LONG
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<boost::long_long_type,int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<boost::long_long_type,char>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<boost::long_long_type,float>::value), true);
#elif defined(BOOST_HAS_MS_INT64)
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<__int64,int>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<__int64,char>::value), true);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<__int64,float>::value), true);
#endif
#ifndef BOOST_NO_RVALUE_REFERENCES
// Test bug case 4530:
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<test_bug_4530<A4530>,A4530>::value), true);
#endif
#if defined(BOOST_MSVC) && (BOOST_MSVC > 1310)
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int, bug_5271a>::value), false);
BOOST_CHECK_INTEGRAL_CONSTANT((::tt::is_convertible<int, bug_5271b>::value), true);
#endif
TT_TEST_END
| [
"andrew@trailofbits.com"
] | andrew@trailofbits.com |
cef1dfcc60360458e07ad80cb6b11f7af31ee99b | 8948014ff8c1f8f664851b49e2d97b5d9a8363e5 | /code/xx.cpp | af541ed09c7436eaee5d114e2327e3423b027293 | [] | no_license | yjjieqc/Linux | 108d6adfc0247fbbeaeac3ade1fd42d3b17da12e | 946da3d8e535f26250a3a5074358e06b9d864434 | refs/heads/master | 2021-07-13T11:29:59.718169 | 2019-10-30T09:20:14 | 2019-10-30T09:20:14 | 97,217,648 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 172 | cpp | struct FlowEntry{
u64 key;
u32 src_ip;
u32 dst_ip;
u16 src_port;
u16 dst_port;
u8 priority;
u32 flowsize;
...
} | [
"lonelypiscesve@gmail.com"
] | lonelypiscesve@gmail.com |
611508c9b397ca258c8c8e6c26d68384736db70b | f785f72ca62115be56830c32cf3cb61d62cea7af | /shpreader2.5/CdbfManager.cpp | 18ed00989b42c2e0be771ce31fa5e65c97ff6e31 | [] | no_license | CHCDST-SY/shp | bb94963934e018ad63052795379752d2d8fdcf22 | f19611284d107960e0a5f01a082891fe582055ce | refs/heads/main | 2023-06-18T11:57:31.938020 | 2021-07-20T08:56:24 | 2021-07-20T08:56:24 | 387,636,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,245 | cpp | #include "CdbfManager.h"
CdbfManager::CdbfManager()
{
}
CdbfManager::~CdbfManager()
{
}
void CdbfManager::setDbfHeadValue(dbfHead &CdbfHead)
{
m_CdbfHead.cVersion=CdbfHead.cVersion;
for (int i = 0; i < 3; i++) {
m_CdbfHead.iDate[i]=CdbfHead.iDate[i];
}
m_CdbfHead.iRecordNumber=CdbfHead.iRecordNumber;
m_CdbfHead.nHeadLength=CdbfHead.nHeadLength;
m_CdbfHead.nOneRecordLength=CdbfHead.nOneRecordLength;
for (size_t i = 0; i < CdbfHead.vec_RecordDescription.size(); i++) {
m_CdbfHead.vec_RecordDescription.push_back(CdbfHead.vec_RecordDescription[i]);
}
// char cVersion; //版本信息
// //char acDate[3]; // 最后一次更新日期,YYMMDD
// int iDate[3];
// unsigned int iRecordNumber; //文件中记录条数
// unsigned short nHeadLength; // 文件头字节数
// unsigned short nOneRecordLength; //一条记录的字节长度
// char acReserved[20]; //0-1,添加新的说明信息性信息时使用,这里用0填写。2,未完成操作.3,dBASE IV编密码标记。。。。。。
// vector<CdbfFieldDefine> vec_RecordDescription;//记录项描述数组
// char cEndMarker;
}
void CdbfManager::obtainDbfRecord(CdbfRecord &CdbfRecord)
{
m_vecDbfRecord.push_back(CdbfRecord);
}
dbfHead &CdbfManager::getDbfHead()
{
return m_CdbfHead;
}
CdbfRecord &CdbfManager::operator[](int i)
{
return m_vecDbfRecord[i];
}
void CdbfManager::printRecords()
{
int iFieldNum=(m_CdbfHead.nHeadLength-33)/32; //字段的个数
char cDataType;
unsigned short cFieldPrecision;
unsigned short iOneFieldLength;
for (int iCyclic = 0; iCyclic < m_vecDbfRecord.size(); ++iCyclic) {
for (int j=0;j<iFieldNum;j++) {
cDataType=m_CdbfHead.vec_RecordDescription[j].getFieldDataType();
cFieldPrecision=m_CdbfHead.vec_RecordDescription[j].getFieldPrecision();
iOneFieldLength=m_CdbfHead.vec_RecordDescription[j].getFieldLength();
switch (cDataType) {
case 'D':
cout<<"date: ";
for(int k=0;k<3;k++){cout<<m_vecDbfRecord[iCyclic][j].m_Date[k]<<" "; }
cout<<endl;
break;
case 'B':
case 'C':
case 'G':
case 'L':
case 'M': //各类字符型字段值
cout<<"char: ";
for(int k=0;k<iOneFieldLength;k++){cout<<m_vecDbfRecord[iCyclic][j].m_cValues[k]; }
cout<<endl;
break;
case 'N':
if(cFieldPrecision==iOneFieldLength) //精度与长度相等,说明没有小数点位,为整型
{
cout<<"int: "<<m_vecDbfRecord[iCyclic][j].m_iNum<<" "<<endl;
}
else { //否则即为浮点型
cout<<"float: "<<m_vecDbfRecord[iCyclic][j].m_dNum<<" "<<endl;
}
break;
}
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
4edb54c373251d95d3dcc5d561abd8e2c46f0824 | 91cfe236ce7bdcd54effd7620528b9ac392bffd7 | /SearchThread.cpp | 4b39dd976d3d49965e031eedf691aea4d1d4cdb3 | [] | no_license | d-w-s-h/cluster-search | 3998fcc1cc6eb35083dfc394242803fcb64906ec | bc29ed61ba50b262c46ce04a9213451634d8dc12 | refs/heads/master | 2020-03-07T17:45:11.146672 | 2018-04-14T17:21:44 | 2018-04-14T17:21:44 | 127,619,697 | 5 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 4,000 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "SearchThread.h"
#include "Main.h"
#include <vector>
using namespace std;
typedef vector<BYTE> DiskCluster;
#pragma package(smart_init)
//---------------------------------------------------------------------------
// Important: Methods and properties of objects in VCL can only be
// used in a method called using Synchronize, for example:
//
// Synchronize(&UpdateCaption);
//
// where UpdateCaption could look like:
//
// void __fastcall SearchThread::UpdateCaption()
// {
// Form1->Caption = "Updated in a thread";
// }
//---------------------------------------------------------------------------
__fastcall SearchThread::SearchThread(DiskCluster *dataBufferPtr, int clusterSize, __int64 *progress, bool CreateSuspended)
: TThread(CreateSuspended)
{
FreeOnTerminate = true;
CurrentIteratorCluster = progress; //ссылка
NodeId=1;
BufferReadyEvent = new TEvent(NULL, true, false,"",false);
BufferCopiedEvent = new TEvent(NULL, true, false,"",false);
BufferAccessCS = new TCriticalSection;
Synchronize(&GetCheckedBoxes);
ClusterSize = clusterSize;
OutBufferPtr = dataBufferPtr;
// DataBuffer = new BYTE[clusterSize];
Signatures.resize(16);
Signatures[0]= "JFIF";
Signatures[1]= "Exif";
Signatures[2]= "PNG";
Signatures[3]= "BM";
}
//---------------------------------------------------------------------------
void __fastcall SearchThread::Execute()
{
while(true)
{
// Ждать, пока не будет подготовлен буфер для копирования
if(BufferReadyEvent->WaitFor(WaitDelayMs) == wrSignaled)
{
if(BufferAccessCS->TryEnter())
{
FixedCurrentCluster = *CurrentIteratorCluster; //чтобы не убежал
// Скопировать данные
CopyData();
// Отпустить буфер
BufferReadyEvent->ResetEvent();
BufferCopiedEvent->SetEvent();
BufferAccessCS->Leave();
// Запустить поиск
SearchData();
// CurrentCluster++;
}
}
if(Terminated) break;
}
// Удалить события
delete BufferReadyEvent;
delete BufferCopiedEvent;
delete BufferAccessCS;
// Удалить буфер
// delete[] DataBuffer;
//Synchronize(&CompleteSearch);
return;
}
//---------------------------------------------------------------------------
void SearchThread::CopyData()
{
// memcpy(DataBuffer, OutBufferPtr, ClusterSize);
// DataBuffer= OutBufferPtr;
DataBuffer = *OutBufferPtr;
}
//---------------------------------------------------------------------------
void SearchThread::SearchData()
{
// Проведем поиск
bool matchFound1 = memcmp(&DataBuffer[0]+6 , Signatures[0].c_str(), Signatures[0].length());
bool matchFound2 = memcmp(&DataBuffer[0]+6 , Signatures[1].c_str(), Signatures[1].length());
if(!matchFound1 ||!matchFound2 )
{
SignatureName = "jpeg";
Synchronize(&AddMatch);
}
if(this->isChecked[0])
{
if(!memcmp(&DataBuffer[0]+1 , Signatures[2].c_str(), Signatures[2].length()))
{
SignatureName = "png";
Synchronize(&AddMatch);
}
}
if(this->isChecked[1])
{
if(!memcmp(&DataBuffer[0] , Signatures[3].c_str(), Signatures[3].length()))
{
SignatureName = "bmp";
Synchronize(&AddMatch);
}
}
}
//---------------------------------------------------------------------------
void __fastcall SearchThread::AddMatch()
{
PVirtualNode newNode = MainForm->ResultTree->AddChild(MainForm->ResultTree->RootNode);
DBstruct *nodeData = (DBstruct*)MainForm->ResultTree->GetNodeData(newNode);
nodeData->id = NodeId;
nodeData->cluster = FixedCurrentCluster;
nodeData->type = SignatureName;
NodeId++;
}
void __fastcall SearchThread::GetCheckedBoxes()
{
this->isChecked[0] = MainForm->CheckPNG->Checked;
this->isChecked[1] = MainForm->CheckBMP->Checked;
}
//---------------------------------------------------------------------------
| [
"37116899+d-w-s-h@users.noreply.github.com"
] | 37116899+d-w-s-h@users.noreply.github.com |
2424785cb06751a0b64ff24a25cb674c84693b00 | 36e4dc8cde66312dfe70e4d13edccf1258970178 | /src/rpcmining.cpp | 9ca353525f6a2a38cbbea811e6496bcc8cdb0cbb | [
"MIT"
] | permissive | Alonewolf-123/DOMO-Core | bc355fc67cd1b91a0776302325b6b6cecf277fca | f67b6309212ee665f4aac33239cfecdf2afb4387 | refs/heads/master | 2021-09-22T21:04:49.957335 | 2018-09-16T11:04:19 | 2018-09-16T11:04:19 | 138,198,712 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,296 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2018 The PIVX developers
// Copyright (c) 2018 The DOMO developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "base58.h"
#include "chainparams.h"
#include "core_io.h"
#include "init.h"
#include "main.h"
#include "miner.h"
#include "net.h"
#include "pow.h"
#include "rpcserver.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "db.h"
#include "wallet.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include <univalue.h>
using namespace std;
/**
* Return average network hashes per second based on the last 'lookup' blocks,
* or from the last difficulty change if 'lookup' is nonpositive.
* If 'height' is nonnegative, compute the estimate at the time when a given block was found.
*/
UniValue GetNetworkHashPS(int lookup, int height)
{
CBlockIndex *pb = chainActive.Tip();
if (height >= 0 && height < chainActive.Height())
pb = chainActive[height];
if (pb == NULL || !pb->nHeight)
return 0;
// If lookup is -1, then use blocks since last difficulty change.
if (lookup <= 0)
lookup = pb->nHeight % 2016 + 1;
// If lookup is larger than chain, then set it to chain length.
if (lookup > pb->nHeight)
lookup = pb->nHeight;
CBlockIndex* pb0 = pb;
int64_t minTime = pb0->GetBlockTime();
int64_t maxTime = minTime;
for (int i = 0; i < lookup; i++) {
pb0 = pb0->pprev;
int64_t time = pb0->GetBlockTime();
minTime = std::min(time, minTime);
maxTime = std::max(time, maxTime);
}
// In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
if (minTime == maxTime)
return 0;
uint256 workDiff = pb->nChainWork - pb0->nChainWork;
int64_t timeDiff = maxTime - minTime;
return (int64_t)(workDiff.getdouble() / timeDiff);
}
UniValue getnetworkhashps(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getnetworkhashps ( blocks height )\n"
"\nReturns the estimated network hashes per second based on the last n blocks.\n"
"Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
"Pass in [height] to estimate the network speed at the time when a certain block was found.\n"
"\nArguments:\n"
"1. blocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n"
"2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
"\nResult:\n"
"x (numeric) Hashes per second estimated\n"
"\nExamples:\n" +
HelpExampleCli("getnetworkhashps", "") + HelpExampleRpc("getnetworkhashps", ""));
LOCK(cs_main);
return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1);
}
#ifdef ENABLE_WALLET
UniValue getgenerate(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getgenerate\n"
"\nReturn if the server is set to generate coins or not. The default is false.\n"
"It is set with the command line argument -gen (or domo.conf setting gen)\n"
"It can also be set with the setgenerate call.\n"
"\nResult\n"
"true|false (boolean) If the server is set to generate coins or not\n"
"\nExamples:\n" +
HelpExampleCli("getgenerate", "") + HelpExampleRpc("getgenerate", ""));
LOCK(cs_main);
return GetBoolArg("-gen", false);
}
UniValue setgenerate(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setgenerate generate ( genproclimit )\n"
"\nSet 'generate' true or false to turn generation on or off.\n"
"Generation is limited to 'genproclimit' processors, -1 is unlimited.\n"
"See the getgenerate call for the current setting.\n"
"\nArguments:\n"
"1. generate (boolean, required) Set to true to turn on generation, false to turn off.\n"
"2. genproclimit (numeric, optional) Set the processor limit for when generation is on. Can be -1 for unlimited.\n"
" Note: in -regtest mode, genproclimit controls how many blocks are generated immediately.\n"
"\nResult\n"
"[ blockhashes ] (array, -regtest only) hashes of blocks generated\n"
"\nExamples:\n"
"\nSet the generation on with a limit of one processor\n" +
HelpExampleCli("setgenerate", "true 1") +
"\nCheck the setting\n" + HelpExampleCli("getgenerate", "") +
"\nTurn off generation\n" + HelpExampleCli("setgenerate", "false") +
"\nUsing json rpc\n" + HelpExampleRpc("setgenerate", "true, 1"));
if (pwalletMain == NULL)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
bool fGenerate = true;
if (params.size() > 0)
fGenerate = params[0].get_bool();
int nGenProcLimit = -1;
if (params.size() > 1) {
nGenProcLimit = params[1].get_int();
if (nGenProcLimit == 0)
fGenerate = false;
}
// -regtest mode: don't return until nGenProcLimit blocks are generated
if (fGenerate && Params().MineBlocksOnDemand()) {
int nHeightStart = 0;
int nHeightEnd = 0;
int nHeight = 0;
int nGenerate = (nGenProcLimit > 0 ? nGenProcLimit : 1);
CReserveKey reservekey(pwalletMain);
{ // Don't keep cs_main locked
LOCK(cs_main);
nHeightStart = chainActive.Height();
nHeight = nHeightStart;
nHeightEnd = nHeightStart + nGenerate;
}
unsigned int nExtraNonce = 0;
UniValue blockHashes(UniValue::VARR);
while (nHeight < nHeightEnd) {
unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey, pwalletMain, false));
if (!pblocktemplate.get())
throw JSONRPCError(RPC_INTERNAL_ERROR, "Wallet keypool empty");
CBlock* pblock = &pblocktemplate->block;
{
LOCK(cs_main);
IncrementExtraNonce(pblock, chainActive.Tip(), nExtraNonce);
}
while (!CheckProofOfWork(pblock->GetHash(), pblock->nBits)) {
// Yes, there is a chance every nonce could fail to satisfy the -regtest
// target -- 1 in 2^(2^32). That ain't gonna happen.
++pblock->nNonce;
}
CValidationState state;
if (!ProcessNewBlock(state, NULL, pblock))
throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
++nHeight;
blockHashes.push_back(pblock->GetHash().GetHex());
}
return blockHashes;
} else // Not -regtest: start generate thread, return immediately
{
mapArgs["-gen"] = (fGenerate ? "1" : "0");
mapArgs["-genproclimit"] = itostr(nGenProcLimit);
GenerateBitcoins(fGenerate, pwalletMain, nGenProcLimit);
}
return NullUniValue;
}
UniValue gethashespersec(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"gethashespersec\n"
"\nReturns a recent hashes per second performance measurement while generating.\n"
"See the getgenerate and setgenerate calls to turn generation on and off.\n"
"\nResult:\n"
"n (numeric) The recent hashes per second when generation is on (will return 0 if generation is off)\n"
"\nExamples:\n" +
HelpExampleCli("gethashespersec", "") + HelpExampleRpc("gethashespersec", ""));
if (GetTimeMillis() - nHPSTimerStart > 8000)
return (int64_t)0;
return (int64_t)dHashesPerSec;
}
#endif
UniValue getmininginfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"\nReturns a json object containing mining-related information."
"\nResult:\n"
"{\n"
" \"blocks\": nnn, (numeric) The current block\n"
" \"currentblocksize\": nnn, (numeric) The last block size\n"
" \"currentblocktx\": nnn, (numeric) The last block transaction\n"
" \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
" \"errors\": \"...\" (string) Current errors\n"
" \"generate\": true|false (boolean) If the generation is on or off (see getgenerate or setgenerate calls)\n"
" \"genproclimit\": n (numeric) The processor limit for generation. -1 if no generation. (see getgenerate or setgenerate calls)\n"
" \"hashespersec\": n (numeric) The hashes per second of the generation, or 0 if no generation.\n"
" \"pooledtx\": n (numeric) The size of the mem pool\n"
" \"testnet\": true|false (boolean) If using testnet or not\n"
" \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getmininginfo", "") + HelpExampleRpc("getmininginfo", ""));
LOCK(cs_main);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("blocks", (int)chainActive.Height()));
obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
obj.push_back(Pair("networkhashps", getnetworkhashps(params, false)));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC()));
obj.push_back(Pair("chain", Params().NetworkIDString()));
#ifdef ENABLE_WALLET
obj.push_back(Pair("generate", getgenerate(params, false)));
obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
#endif
return obj;
}
// NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
UniValue prioritisetransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"prioritisetransaction <txid> <priority delta> <fee delta>\n"
"Accepts the transaction into mined blocks at a higher (or lower) priority\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id.\n"
"2. priority delta (numeric, required) The priority to add or subtract.\n"
" The transaction selection algorithm considers the tx as it would have a higher priority.\n"
" (priority of a transaction is calculated: coinage * value_in_upiv / txsize) \n"
"3. fee delta (numeric, required) The fee value (in upiv) to add (or subtract, if negative).\n"
" The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
" considers the transaction as it would have paid a higher (or lower) fee.\n"
"\nResult\n"
"true (boolean) Returns true\n"
"\nExamples:\n" +
HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000") + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000"));
LOCK(cs_main);
uint256 hash = ParseHashStr(params[0].get_str(), "txid");
CAmount nAmount = params[2].get_int64();
mempool.PrioritiseTransaction(hash, params[0].get_str(), params[1].get_real(), nAmount);
return true;
}
// NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
static UniValue BIP22ValidationResult(const CValidationState& state)
{
if (state.IsValid())
return NullUniValue;
std::string strRejectReason = state.GetRejectReason();
if (state.IsError())
throw JSONRPCError(RPC_VERIFY_ERROR, strRejectReason);
if (state.IsInvalid()) {
if (strRejectReason.empty())
return "rejected";
return strRejectReason;
}
// Should be impossible
return "valid?";
}
UniValue getblocktemplate(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getblocktemplate ( \"jsonrequestobject\" )\n"
"\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
"It returns data needed to construct a block to work on.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
"\nArguments:\n"
"1. \"jsonrequestobject\" (string, optional) A json object in the following spec\n"
" {\n"
" \"mode\":\"template\" (string, optional) This must be set to \"template\" or omitted\n"
" \"capabilities\":[ (array, optional) A list of strings\n"
" \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
" ,...\n"
" ]\n"
" }\n"
"\n"
"\nResult:\n"
"{\n"
" \"version\" : n, (numeric) The block version\n"
" \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
" \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
" {\n"
" \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
" \"hash\" : \"xxxx\", (string) hash/id encoded in little-endian hexadecimal\n"
" \"depends\" : [ (array) array of numbers \n"
" n (numeric) transactions before this one (by 1-based index in 'transactions' list) that must be present in the final block if this one is\n"
" ,...\n"
" ],\n"
" \"fee\": n, (numeric) difference in value between transaction inputs and outputs (in upiv); for coinbase transactions, this is a negative Number of the total collected block fees (ie, not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one\n"
" \"sigops\" : n, (numeric) total number of SigOps, as counted for purposes of block limits; if key is not present, sigop count is unknown and clients MUST NOT assume there aren't any\n"
" \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
" }\n"
" ,...\n"
" ],\n"
" \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
" \"flags\" : \"flags\" (string) \n"
" },\n"
" \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in upiv)\n"
" \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
" \"target\" : \"xxxx\", (string) The hash target\n"
" \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
" \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
" ,...\n"
" ],\n"
" \"noncerange\" : \"00000000ffffffff\", (string) A range of valid nonces\n"
" \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
" \"sizelimit\" : n, (numeric) limit of block size\n"
" \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
" \"bits\" : \"xxx\", (string) compressed target of next block\n"
" \"height\" : n (numeric) The height of the next block\n"
" \"payee\" : \"xxx\", (string) required payee for the next block\n"
" \"payee_amount\" : n, (numeric) required amount to pay\n"
" \"votes\" : [\n (array) show vote candidates\n"
" { ... } (json object) vote candidate\n"
" ,...\n"
" ],\n"
" \"masternode_payments\" : true|false, (boolean) true, if masternode payments are enabled\n"
" \"enforce_masternode_payments\" : true|false (boolean) true, if masternode payments are enforced\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getblocktemplate", "") + HelpExampleRpc("getblocktemplate", ""));
LOCK(cs_main);
std::string strMode = "template";
UniValue lpval = NullUniValue;
if (params.size() > 0) {
const UniValue& oparam = params[0].get_obj();
const UniValue& modeval = find_value(oparam, "mode");
if (modeval.isStr())
strMode = modeval.get_str();
else if (modeval.isNull()) {
/* Do nothing */
} else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
lpval = find_value(oparam, "longpollid");
if (strMode == "proposal") {
const UniValue& dataval = find_value(oparam, "data");
if (!dataval.isStr())
throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
CBlock block;
if (!DecodeHexBlk(block, dataval.get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
uint256 hash = block.GetHash();
BlockMap::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end()) {
CBlockIndex* pindex = mi->second;
if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
return "duplicate";
if (pindex->nStatus & BLOCK_FAILED_MASK)
return "duplicate-invalid";
return "duplicate-inconclusive";
}
CBlockIndex* const pindexPrev = chainActive.Tip();
// TestBlockValidity only supports blocks built on the current Tip
if (block.hashPrevBlock != pindexPrev->GetBlockHash())
return "inconclusive-not-best-prevblk";
CValidationState state;
TestBlockValidity(state, block, pindexPrev, false, true);
return BIP22ValidationResult(state);
}
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "DOMO is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "DOMO is downloading blocks...");
static unsigned int nTransactionsUpdatedLast;
if (!lpval.isNull()) {
// Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
uint256 hashWatchedChain;
boost::system_time checktxtime;
unsigned int nTransactionsUpdatedLastLP;
if (lpval.isStr()) {
// Format: <hashBestChain><nTransactionsUpdatedLast>
std::string lpstr = lpval.get_str();
hashWatchedChain.SetHex(lpstr.substr(0, 64));
nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
} else {
// NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
hashWatchedChain = chainActive.Tip()->GetBlockHash();
nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
}
// Release the wallet and main lock while waiting
LEAVE_CRITICAL_SECTION(cs_main);
{
checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);
boost::unique_lock<boost::mutex> lock(csBestBlock);
while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning()) {
if (!cvBlockChange.timed_wait(lock, checktxtime)) {
// Timeout: Check transactions for update
if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
break;
checktxtime += boost::posix_time::seconds(10);
}
}
}
ENTER_CRITICAL_SECTION(cs_main);
if (!IsRPCRunning())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
// TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
}
// Update block
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlockTemplate* pblocktemplate;
if (pindexPrev != chainActive.Tip() ||
(mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5)) {
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the chainActive.Tip() used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrevNew = chainActive.Tip();
nStart = GetTime();
// Create new block
if (pblocktemplate) {
delete pblocktemplate;
pblocktemplate = NULL;
}
CScript scriptDummy = CScript() << OP_TRUE;
pblocktemplate = CreateNewBlock(scriptDummy, pwalletMain, false);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
// Update nTime
UpdateTime(pblock, pindexPrev);
pblock->nNonce = 0;
UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
UniValue transactions(UniValue::VARR);
map<uint256, int64_t> setTxIndex;
int i = 0;
BOOST_FOREACH (CTransaction& tx, pblock->vtx) {
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase())
continue;
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("data", EncodeHexTx(tx)));
entry.push_back(Pair("hash", txHash.GetHex()));
UniValue deps(UniValue::VARR);
BOOST_FOREACH (const CTxIn& in, tx.vin) {
if (setTxIndex.count(in.prevout.hash))
deps.push_back(setTxIndex[in.prevout.hash]);
}
entry.push_back(Pair("depends", deps));
int index_in_template = i - 1;
entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
transactions.push_back(entry);
}
UniValue aux(UniValue::VOBJ);
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = uint256().SetCompact(pblock->nBits);
static UniValue aMutable(UniValue::VARR);
if (aMutable.empty()) {
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
UniValue aVotes(UniValue::VARR);
UniValue result(UniValue::VOBJ);
result.push_back(Pair("capabilities", aCaps));
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].GetValueOut()));
result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast() + 1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
// result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
// result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", pblock->GetBlockTime()));
result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight + 1)));
result.push_back(Pair("votes", aVotes));
if (pblock->payee != CScript()) {
CTxDestination address1;
ExtractDestination(pblock->payee, address1);
CBitcoinAddress address2(address1);
result.push_back(Pair("payee", address2.ToString().c_str()));
result.push_back(Pair("payee_amount", (int64_t)pblock->vtx[0].vout[1].nValue));
} else {
result.push_back(Pair("payee", ""));
result.push_back(Pair("payee_amount", ""));
}
result.push_back(Pair("masternode_payments", pblock->nTime > Params().StartMasternodePayments()));
result.push_back(Pair("enforce_masternode_payments", true));
return result;
}
class submitblock_StateCatcher : public CValidationInterface
{
public:
uint256 hash;
bool found;
CValidationState state;
submitblock_StateCatcher(const uint256& hashIn) : hash(hashIn), found(false), state(){};
protected:
virtual void BlockChecked(const CBlock& block, const CValidationState& stateIn)
{
if (block.GetHash() != hash)
return;
found = true;
state = stateIn;
};
};
UniValue submitblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"submitblock \"hexdata\" ( \"jsonparametersobject\" )\n"
"\nAttempts to submit new block to network.\n"
"The 'jsonparametersobject' parameter is currently ignored.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
"\nArguments\n"
"1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
"2. \"jsonparametersobject\" (string, optional) object of optional parameters\n"
" {\n"
" \"workid\" : \"id\" (string, optional) if the server provided a workid, it MUST be included with submissions\n"
" }\n"
"\nResult:\n"
"\nExamples:\n" +
HelpExampleCli("submitblock", "\"mydata\"") + HelpExampleRpc("submitblock", "\"mydata\""));
CBlock block;
if (!DecodeHexBlk(block, params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
uint256 hash = block.GetHash();
bool fBlockPresent = false;
{
LOCK(cs_main);
BlockMap::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end()) {
CBlockIndex* pindex = mi->second;
if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
return "duplicate";
if (pindex->nStatus & BLOCK_FAILED_MASK)
return "duplicate-invalid";
// Otherwise, we might only have the header - process the block before returning
fBlockPresent = true;
}
}
CValidationState state;
submitblock_StateCatcher sc(block.GetHash());
RegisterValidationInterface(&sc);
bool fAccepted = ProcessNewBlock(state, NULL, &block);
UnregisterValidationInterface(&sc);
if (fBlockPresent) {
if (fAccepted && !sc.found)
return "duplicate-inconclusive";
return "duplicate";
}
if (fAccepted) {
if (!sc.found)
return "inconclusive";
state = sc.state;
}
return BIP22ValidationResult(state);
}
UniValue estimatefee(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"estimatefee nblocks\n"
"\nEstimates the approximate fee per kilobyte\n"
"needed for a transaction to begin confirmation\n"
"within nblocks blocks.\n"
"\nArguments:\n"
"1. nblocks (numeric)\n"
"\nResult:\n"
"n : (numeric) estimated fee-per-kilobyte\n"
"\n"
"-1.0 is returned if not enough transactions and\n"
"blocks have been observed to make an estimate.\n"
"\nExample:\n" +
HelpExampleCli("estimatefee", "6"));
RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM));
int nBlocks = params[0].get_int();
if (nBlocks < 1)
nBlocks = 1;
CFeeRate feeRate = mempool.estimateFee(nBlocks);
if (feeRate == CFeeRate(0))
return -1.0;
return ValueFromAmount(feeRate.GetFeePerK());
}
UniValue estimatepriority(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"estimatepriority nblocks\n"
"\nEstimates the approximate priority\n"
"a zero-fee transaction needs to begin confirmation\n"
"within nblocks blocks.\n"
"\nArguments:\n"
"1. nblocks (numeric)\n"
"\nResult:\n"
"n : (numeric) estimated priority\n"
"\n"
"-1.0 is returned if not enough transactions and\n"
"blocks have been observed to make an estimate.\n"
"\nExample:\n" +
HelpExampleCli("estimatepriority", "6"));
RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM));
int nBlocks = params[0].get_int();
if (nBlocks < 1)
nBlocks = 1;
return mempool.estimatePriority(nBlocks);
}
| [
"alonewolf2ksk@gmail.com"
] | alonewolf2ksk@gmail.com |
0d164d4bdcfa6ef19fb0eb96ec7dbb5625289a4a | 2a937d0b83ba817530f84e8a68e8dbf86ad4004c | /go_straight/go_straight.ino | 4a0fdb32a160c0b7851f19cfff07e686d9f37d88 | [] | no_license | Sabrina-Sumona/Obstacle-Avoiding-Robot-Arduino-Codes | 2eba25a22872b5817c2544a4059dd3a2bf02a9ad | 74bb550804d56fa2c845c2ec7a3f834e8a5a6f1f | refs/heads/main | 2023-06-07T14:19:16.230997 | 2021-07-09T15:51:52 | 2021-07-09T15:51:52 | 384,484,473 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 869 | ino | #include <Servo.h> // this adds the "Servo" library to the program
// the following creates two servo objects
Servo leftMotor;
Servo rightMotor;
void setup()
{
leftMotor.attach(12); // if you accidentally switched up the pin numbers for your servos, you can swap the numbers here
rightMotor.attach(13);
}
void loop()
{
if(digitalRead(2) == HIGH) // this registers when the button is pressed on pin 2 of the Arduino
{
while(1)
{
leftMotor.write(90); // "90" is neutral position for the servos, which tells them to stop turning
rightMotor.write(90);
}
}
leftMotor.write(180); // with continuous rotation, 180 tells the servo to move at full speed "forward."
rightMotor. write(0); // if both of these are at 180, the robot will go in a circle because the servos are flipped. "0," tells it to move full speed "backward."
}
| [
"snsbauet04@gmail.com"
] | snsbauet04@gmail.com |
445d67a4e9835c3b3150215508bd3d48e88b884e | c1b43f2be18ac6268d7b46bb8bcbfe8cc10b6b46 | /algorithm/acm/calcuate_room.cpp | 7b7b9086892e56faacd32569504df5281f9c8373 | [] | no_license | Francis0121/homework.3.2 | a6f5d54db50e0f9ad5f5def6fd17cf1f27d66611 | 087043d66f15e4b0ba30151c235b3b52bdf884f7 | refs/heads/master | 2021-01-22T12:07:15.347421 | 2014-12-19T11:29:28 | 2014-12-19T11:29:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,006 | cpp | //#include <stdio.h>
//#include <string.h>
//#include <vector>
//#include <algorithm>
//
//#define MAX_ROOM_SIZE 102
//#define QUEUE_SIZE 100404
//
//#define TRUE 1
//#define FALSE 0
//
//using namespace std;
//
//char room[MAX_ROOM_SIZE][MAX_ROOM_SIZE] = {0};
//
//int front = 0, rear = 0;
//int queue[QUEUE_SIZE] = {0};
//
//void enqueue(int col, int row){
// if(rear > QUEUE_SIZE){
// printf("Enqueue Error\n %d", rear);
// return;
// }
// queue[rear++] = col;
// queue[rear++] = row;
//}
//
//void dequeue(int *col, int *row){
// if(front == rear){
// printf("Error!\n");
// return;
// }
// *col = queue[front++];
// *row = queue[front++];
//}
//
//bool desc (int i,int j) { return (i>j); }
//
//int main(void){
// FILE *in;
// int iTestCase, chTemp, i;
// int rowSize, colSize, row, col;
// int calRow, calCol;
//
// int roomCount, sizeCount;
// vector<int> vecRoomSize;
//
// in = fopen("input.txt", "r");
// fscanf(in, "%d", &iTestCase);
// while(iTestCase--){
// // ~ initial variable
// vecRoomSize.clear();
// roomCount = 0;
//
// memset(room, 0, sizeof(char)*MAX_ROOM_SIZE*MAX_ROOM_SIZE);
// fscanf(in, "%d %d", &rowSize, &colSize);
// fscanf(in, "%c", &chTemp); // Enter
// for(col=1; col<=colSize; col++){
// for(row=1; row<=rowSize; row++){
// fscanf(in, "%c", &chTemp);
// room[col][row] = chTemp;
// }
// fscanf(in, "%c", &chTemp); // Enter
// }
//
// for(col=1; col<=colSize; col++){
// for(row=1; row<=rowSize; row++){
// front = 0, rear = 0;
// chTemp = room[col][row];
// if(chTemp != '+' && chTemp != '.'){
// continue;
// }
//
// if(chTemp == '+'){
// room[col][row] = 0;
// continue;
// }
//
//
// sizeCount=1;
// roomCount++;
// enqueue(col, row);
// room[col][row] = roomCount;
// while(front != rear){
// dequeue(&calCol, &calRow);
// // ~ South
// if(room[calCol-1][calRow] == '.'){
// enqueue(calCol-1, calRow);
// room[calCol-1][calRow] = roomCount;
// sizeCount+=1;
// }
// // ~ North
// if(room[calCol+1][calRow] == '.'){
// enqueue(calCol+1, calRow);
// room[calCol+1][calRow] = roomCount;
// sizeCount+=1;
// }
// // ~ East
// if(room[calCol][calRow+1] == '.'){
// enqueue(calCol, calRow+1);
// room[calCol][calRow+1] = roomCount;
// sizeCount+=1;
// }
// // ~ West
// if(room[calCol][calRow-1] == '.'){
// enqueue(calCol, calRow-1);
// room[calCol][calRow-1] = roomCount;
// sizeCount+=1;
// }
// }
// vecRoomSize.push_back(sizeCount);
// }
// }
// sort(vecRoomSize.begin(), vecRoomSize.end(), desc);
//
// printf("%d\n", roomCount);
// for(i=0; i<vecRoomSize.size(); i++){
// printf("%d ", vecRoomSize[i]);
// }
// printf("\n");
//
// // ~ print
// /*printf("%d %d\n", rowSize, colSize);
// for(col=1; col<=colSize; col++){
// for(row=1; row<=rowSize; row++){
// printf("%d", room[col][row]);
// }
// printf("\n");
// }*/
// }
//
// return 0;
//} | [
"kims_0121@naver.com"
] | kims_0121@naver.com |
3193cbbc50fa85b30f991165051908d61d0faf57 | 2ad0ac3cf6fd3faf88e6fa2c2f20f41eeca88a0a | /Miner/dialog.h | 7e835edcac3eca95c2e586dd52ecd76cc7b75f20 | [] | no_license | ljue/Qt-practice | 7d84cf25050a45f353f411e964f69ad4d270616e | 72421972b98856dfe88587b4554254a6a4184dd6 | refs/heads/master | 2021-01-11T09:28:53.855231 | 2017-06-08T22:23:10 | 2017-06-08T22:23:10 | 81,201,018 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 280 | h | #ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog();
~Dialog();
QString getName();
private:
Ui::Dialog *ui;
};
#endif // DIALOG_H
| [
"noreply@github.com"
] | noreply@github.com |
f47ae52c6955695c806eac53850eef993a756f6c | 44ee6eaffb74bbbd1c3d01e004f757a1ea03b623 | /CPP/LightOjTopicWise/TelePortDMST.cpp | d6d3ace9d8eb4cc98dce8fa1cd6cf9e0fb0ff58a | [] | no_license | vikash047/Codes | ae7c5dc95ec91838e496c07de1c8fecb06a9019f | 36fae5f190a4befe3406a679632cb182a39a2f3a | refs/heads/master | 2021-06-23T22:39:43.412371 | 2019-10-06T16:58:12 | 2019-10-06T16:58:12 | 149,225,598 | 0 | 0 | null | 2020-10-13T06:47:33 | 2018-09-18T03:48:56 | C++ | UTF-8 | C++ | false | false | 3,375 | cpp | #include <bits/stdc++.h>
using namespace std;
#define frei(i,a,b) for (int i = (a), _b = (b); i <= _b; i++)
#define fred(i,a,b) for (int i = (a), _b = (b); i >= _b; i--)
#define fri(i,n) for (int i = 0, _n = (n); i < _n; i++)
#define frd(i,n) for (int i = (n) - 1; i >= 0; i--)
#define foreach(it, ar) for ( typeof(ar.begin()) it = ar.begin(); it != ar.end(); it++ )
#define fill(ar, val) memset(ar, val, sizeof(ar))
#define uint64 unsigned long long
#define int64 long long
#define all(ar) ar.begin(), ar.end()
#define pb push_back
#define pf push_front
#define mp make_pair
#define ff first
#define ss second
#define pr pair
#define BIT(n) (1<<(n))
#define AND(a,b) ((a) & (b))
#define OR(a,b) ((a) | (b))
#define XOR(a,b) ((a) ^ (b))
#define sqr(x) ((x) * (x))
typedef pair<int, int> pii;
typedef pair<int, pii> piii;
typedef vector<pii> vii;
typedef vector<int> vi;
#define PI 3.1415926535897932385
//#define INF 1000111222
#define eps 1e-7
#define maxN 5005
int n, m, k;
struct Edge {
int u, v, w;
Edge(int _u, int _v, int _w) : u(_u), v(_v), w(_w) {}
};
const int INF = 1<<29;
vector<Edge> adj;
int DMST() {
int vis[n];
int dis[n];
int nE = adj.size();
int nV = n;
int Idx[n];
int parent[n];
int Res = 0;
while(true) {
for(int i = 0; i < nV; i++) {
vis[i] = -1;
dis[i] = INF;
parent[i] = -1;
Idx[i] = -1;
}
for(int i = 0; i < nE; i++) {
int u = adj[i].u;
int v = adj[i].v;
int w = adj[i].w;
if(u != v && dis[v] > w) {
parent[v] = u;
dis[v] = w;
}
}
parent[k] = k;
dis[k] = 0;
for(int i = 0; i < nV; i++) {
if(dis[i] == INF) {
//cout << "Impossible" << endl;
return -1;
}
Res += dis[i];
}
int idx = 0;
for(int i = 0; i < nV; i++) {
if(vis[i] == -1) {
int curr = i;
while(vis[curr] == -1) {
vis[curr] = i;
curr = parent[curr];
}
if(curr == k || vis[curr] != i) continue; // no cycle
Idx[curr] = idx;
for(int u = parent[curr]; u != curr; u = parent[u]) Idx[u] = idx;
idx++;
}
}
if(idx == 0) break;
for(int i = 0; i < nV; i++) {
if(Idx[i] == -1) Idx[i] = idx++;
}
for(int i = 0; i < nE; i++) {
adj[i].u = Idx[adj[i].u];
adj[i].v = Idx[adj[i].v];
adj[i].w -= dis[adj[i].v];
}
nV = idx++;
k = Idx[k];
}
return Res;
}
// int main(int argc, char const *argv[])
// {
// /* code */
// int t;
// cin >> t;
// for(int ts = 1; ts <= t; ts++) {
// cin >> n >> m >> k;
// int x, y, c;
// adj.clear();
// for(int i = 0; i < m; i++) {
// cin >> x >> y >> c;
// adj.push_back(Edge(x, y, c));
// }
// cout << "Case " << ts << ": ";
// DMST();
// }
// return 0;
// }
int main(int argc, char const *argv[]) {
return 0;
}
| [
"vikash.ku0047@gmail.com"
] | vikash.ku0047@gmail.com |
bbed2878e0d875875efde610aaedf2d7a781cac5 | 97528ffe2960a8bc122eca00016cde2056f37054 | /reverse_array/reverse_array.cpp | 4b672e18aae68f0e47cf35adbc752425d1859d46 | [] | no_license | aravind-kumar/Coding | f5875161a2129fb8e2528da9ace42438282ee81b | d71438058fd39fe4bc7d642bd4b5d11333bfe848 | refs/heads/master | 2021-10-26T02:47:14.293087 | 2019-04-09T23:56:28 | 2019-04-09T23:56:28 | 71,275,972 | 0 | 0 | null | 2018-05-18T06:18:35 | 2016-10-18T17:55:38 | C++ | UTF-8 | C++ | false | false | 683 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void rotations(vector<int>& input,int num)
{
int n = input.size();
reverse(input.begin(),input.begin()+n-num-1);
reverse(input.begin()-n-num-1,input.end());
reverse(input.begin(),input.end());
}
int main()
{
vector<int> input;
int num;
cout<<"\n Enter the number of inputs";
cin>>num;
cout<<"\n Enter the inputs";
for(int i=0;i<num;++i)
{
int inputNum;
cin>>inputNum;
input.push_back(inputNum);
}
cout<<"\n Enter the number of rotations to be made ";
cin>>num;
rotations(input,num);
for(auto&& num : input)
cout<<num<<"--->"<<endl;
return 0;
}
| [
"karavindkumar1993@gmail.com"
] | karavindkumar1993@gmail.com |
7e93a594b5c55e84a90c79756a810bcd75d3f520 | 98f9f977a39843e5f7719062f43011ebfd169e42 | /Libs/Widgets/Plugins/ctkDoubleSliderPlugin.h | 0675da9f0d2028cf2e2de6ec71c806eb5c988191 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | txdy077345/CTK | 71cab2d77193d09340afe7a50e5dddc3ea66a06d | 7cd253376139ea73f0450e1bad75bab41aa1b507 | refs/heads/master | 2023-05-27T19:20:21.825916 | 2023-04-29T16:35:03 | 2023-04-29T16:35:03 | 276,658,777 | 1 | 0 | Apache-2.0 | 2020-07-02T13:50:30 | 2020-07-02T13:50:29 | null | UTF-8 | C++ | false | false | 1,248 | h | /*=========================================================================
Library: CTK
Copyright (c) Kitware 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.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#ifndef __ctkDoubleSliderPlugin_h
#define __ctkDoubleSliderPlugin_h
// CTK includes
#include "ctkWidgetsAbstractPlugin.h"
class CTK_WIDGETS_PLUGINS_EXPORT ctkDoubleSliderPlugin :
public QObject,
public ctkWidgetsAbstractPlugin
{
Q_OBJECT
public:
ctkDoubleSliderPlugin(QObject *_parent = 0);
QWidget *createWidget(QWidget *_parent);
QString domXml() const;
QIcon icon() const;
QString includeFile() const;
bool isContainer() const;
QString name() const;
};
#endif
| [
"jchris.fillionr@kitware.com"
] | jchris.fillionr@kitware.com |
971263132895656dbf103bf3f9aceb59d726facd | ed91c77afaeb0e075da38153aa89c6ee8382d3fc | /mediasoup-client/deps/webrtc/src/rtc_base/socket_server.h | face04dbc24d0f38befae4f9ba96e34bcfe51b8a | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-google-patent-license-webm",
"MIT"
] | permissive | whatisor/mediasoup-client-android | 37bf1aeaadc8db642cff449a26545bf15da27539 | dc3d812974991d9b94efbc303aa2deb358928546 | refs/heads/master | 2023-04-26T12:24:18.355241 | 2023-01-02T16:55:19 | 2023-01-02T16:55:19 | 243,833,549 | 0 | 0 | MIT | 2020-02-28T18:56:36 | 2020-02-28T18:56:36 | null | UTF-8 | C++ | false | false | 2,203 | h | /*
* Copyright 2004 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef RTC_BASE_SOCKET_SERVER_H_
#define RTC_BASE_SOCKET_SERVER_H_
#include <memory>
#include "rtc_base/socket_factory.h"
namespace rtc {
class Thread;
// Needs to be forward declared because there's a circular dependency between
// NetworkMonitor and Thread.
// TODO(deadbeef): Fix this.
class NetworkBinderInterface;
// Provides the ability to wait for activity on a set of sockets. The Thread
// class provides a nice wrapper on a socket server.
//
// The server is also a socket factory. The sockets it creates will be
// notified of asynchronous I/O from this server's Wait method.
class SocketServer : public SocketFactory {
public:
static const int kForever = -1;
static std::unique_ptr<SocketServer> CreateDefault();
// When the socket server is installed into a Thread, this function is called
// to allow the socket server to use the thread's message queue for any
// messaging that it might need to perform. It is also called with a null
// argument before the thread is destroyed.
virtual void SetMessageQueue(Thread* queue) {}
// Sleeps until:
// 1) cms milliseconds have elapsed (unless cms == kForever)
// 2) WakeUp() is called
// While sleeping, I/O is performed if process_io is true.
virtual bool Wait(int cms, bool process_io) = 0;
// Causes the current wait (if one is in progress) to wake up.
virtual void WakeUp() = 0;
// A network binder will bind the created sockets to a network.
// It is only used in PhysicalSocketServer.
void set_network_binder(NetworkBinderInterface* binder) {
network_binder_ = binder;
}
NetworkBinderInterface* network_binder() const { return network_binder_; }
private:
NetworkBinderInterface* network_binder_ = nullptr;
};
} // namespace rtc
#endif // RTC_BASE_SOCKET_SERVER_H_
| [
"wuhaiyang1213@gmail.com"
] | wuhaiyang1213@gmail.com |
e05bb79dfdddce7535fd2d00c50e91332981b91a | d0b9e6385148a6014b4323b8c416b29f38f9ecda | /include/account_factory.h | 882192e1d006709c5ac1e5194cd6f0dba8808d0c | [] | no_license | tuangu/bm | 325b71ea4c3ceb54b8a70a6fb669b8447d67ee2f | 3f6329cbfb0871330ebf37c46869a5202f356bba | refs/heads/master | 2020-04-29T09:12:13.249381 | 2019-04-17T13:00:07 | 2019-04-17T13:00:07 | 176,015,600 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 936 | h | /** \file account_factory.h
* \brief Account factory header
*/
#ifndef __ACCOUNT_FACTORY_H__
#define __ACCOUNT_FACTORY_H__
#include <memory>
#include <string>
#include "basic.h"
#include "customer.h"
#include "enterprise.h"
class AccountFactory {
public:
AccountFactory(const AccountFactory&) = delete;
AccountFactory(AccountFactory&&) = delete;
AccountFactory& operator=(const AccountFactory&) = delete;
AccountFactory& operator=(AccountFactory&&) = delete;
static std::shared_ptr<AccountFactory> getInstance();
std::shared_ptr<Basic> makeBasic(float initial);
std::shared_ptr<Basic> makeCustomer(float initial, std::string firstName, std::string lastName);
std::shared_ptr<Basic> makeEnterprise(float initial, std::string name, std::string y_tunnus);
private:
AccountFactory() {};
static std::shared_ptr<AccountFactory> factoryInstance;
};
#endif /* define __ACCOUNT_FACTORY_H__ */ | [
"tuangu@outlook.com"
] | tuangu@outlook.com |
c81954b1134fda52ef1bfe412f430f06a7e8db67 | 9c7321d876654afdf3ba17e165a8dca36a5ddb5c | /src/lib/dhtclient/jccommon.h | 36c8bddbab010accb072a1a34c2951519579119a | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | leofuxiaohui/SilverKing | 035119334408f572f6c28ba3b79dbe97a1a3f083 | 7910c7efbdcb4ebb145a63942fbff9a4ed916b42 | refs/heads/master | 2022-12-18T01:01:24.053824 | 2020-09-30T08:35:38 | 2020-09-30T08:35:38 | 294,789,161 | 0 | 0 | Apache-2.0 | 2020-09-11T19:03:58 | 2020-09-11T19:03:58 | null | UTF-8 | C++ | false | false | 19,860 | h | /**
*
* $Header: $
* $Change: $
* $DateTime: $
*/
#ifndef DHTCOMMON_H
#define DHTCOMMON_H
/////////////
// includes
#include "jace/Jace.h"
using jace::java_new;
using jace::java_cast;
using namespace jace;
#include "jace/StaticVmLoader.h"
using jace::StaticVmLoader;
#include "jace/JArray.h"
using jace::JArray;
#include "jace/JClass.h"
using jace::JClass;
#include "jace/JClassImpl.h"
using jace::JClassImpl;
#include "jace/JNIException.h"
using jace::JNIException;
#include "jace/OptionList.h"
using jace::OptionList;
#include "jace/VirtualMachineShutdownError.h"
using jace::VirtualMachineShutdownError;
#include "jace/proxy/types/JInt.h"
using jace::proxy::types::JInt;
#include "jace/proxy/types/JByte.h"
using jace::proxy::types::JByte;
#include "jace/proxy/types/JLong.h"
using jace::proxy::types::JLong;
#include "jace/proxy/JObject.h"
using jace::proxy::JObject;
#include "jace/proxy/types/JBoolean.h"
using jace::proxy::types::JBoolean;
#include "jace/proxy/java/lang/Class.h"
using jace::proxy::java::lang::Class;
#include "jace/proxy/java/lang/String.h"
using jace::proxy::java::lang::String;
#include "jace/proxy/java/lang/System.h"
using jace::proxy::java::lang::System;
#include "jace/proxy/java/lang/Object.h"
using ::jace::proxy::java::lang::Object;
#include "jace/proxy/java/lang/Throwable.h"
using jace::proxy::java::lang::Throwable;
#include "jace/proxy/java/io/PrintWriter.h"
#include "jace/proxy/java/io/IOException.h"
using ::jace::proxy::java::io::IOException;
#include "jace/proxy/java/io/PrintStream.h"
using ::jace::proxy::java::io::PrintStream;
using namespace jace::proxy::java::lang;
using namespace jace::proxy::java::io;
#include "jace/proxy/java/nio/ByteBuffer.h"
using ::jace::proxy::java::nio::ByteBuffer;
#include "jace/proxy/java/util/Set.h"
using jace::proxy::java::util::Set;
#include "jace/proxy/java/util/List.h"
using jace::proxy::java::util::List;
#include "jace/proxy/java/util/Map.h"
using jace::proxy::java::util::Map;
#include "jace/proxy/java/util/HashSet.h"
using jace::proxy::java::util::HashSet;
#include "jace/proxy/java/util/HashMap.h"
using jace::proxy::java::util::HashMap;
#include "jace/proxy/java/util/Map_Entry.h"
using jace::proxy::java::util::Map_Entry;
#include "jace/proxy/java/util/Iterator.h"
using jace::proxy::java::util::Iterator;
#include "jace/proxy/java/util/concurrent/TimeUnit.h"
using jace::proxy::java::util::concurrent::TimeUnit;
#include "jace/proxy/java/util/logging/Level.h"
using jace::proxy::java::util::logging::Level;
#include "jace/proxy/com/google/common/base/Throwables.h"
using jace::proxy::com::google::common::base::Throwables;
#include "jace/proxy/com/ms/silverking/log/Log.h"
using jace::proxy::com::ms::silverking::log::Log;
#include "jace/proxy/com/ms/silverking/cloud/dht/ConsistencyProtocol.h"
using jace::proxy::com::ms::silverking::cloud::dht::ConsistencyProtocol;
#include "jace/proxy/com/ms/silverking/cloud/dht/CreationTime.h"
using jace::proxy::com::ms::silverking::cloud::dht::CreationTime;
#include "jace/proxy/com/ms/silverking/cloud/dht/GetOptions.h"
using jace::proxy::com::ms::silverking::cloud::dht::GetOptions;
#include "jace/proxy/com/ms/silverking/cloud/dht/NamespaceCreationOptions.h"
using jace::proxy::com::ms::silverking::cloud::dht::NamespaceCreationOptions;
#include "jace/proxy/com/ms/silverking/cloud/dht/NamespaceCreationOptions_Mode.h"
using jace::proxy::com::ms::silverking::cloud::dht::NamespaceCreationOptions_Mode;
#include "jace/proxy/com/ms/silverking/cloud/dht/NamespacePerspectiveOptions.h"
using jace::proxy::com::ms::silverking::cloud::dht::NamespacePerspectiveOptions;
#include "jace/proxy/com/ms/silverking/cloud/dht/NamespaceOptions.h"
using jace::proxy::com::ms::silverking::cloud::dht::NamespaceOptions;
#include "jace/proxy/com/ms/silverking/cloud/dht/NamespaceVersionMode.h"
using jace::proxy::com::ms::silverking::cloud::dht::NamespaceVersionMode;
#include "jace/proxy/com/ms/silverking/cloud/dht/NodeID.h"
using jace::proxy::com::ms::silverking::cloud::dht::NodeID;
#include "jace/proxy/com/ms/silverking/cloud/dht/NonExistenceResponse.h"
using jace::proxy::com::ms::silverking::cloud::dht::NonExistenceResponse;
#include "jace/proxy/com/ms/silverking/cloud/dht/PutOptions.h"
using jace::proxy::com::ms::silverking::cloud::dht::PutOptions;
#include "jace/proxy/com/ms/silverking/cloud/dht/RetrievalType.h"
using jace::proxy::com::ms::silverking::cloud::dht::RetrievalType;
#include "jace/proxy/com/ms/silverking/cloud/dht/RetrievalOptions.h"
using jace::proxy::com::ms::silverking::cloud::dht::RetrievalOptions;
#include "jace/proxy/com/ms/silverking/cloud/dht/RevisionMode.h"
using jace::proxy::com::ms::silverking::cloud::dht::RevisionMode;
#include "jace/proxy/com/ms/silverking/cloud/dht/SessionOptions.h"
using jace::proxy::com::ms::silverking::cloud::dht::SessionOptions;
#include "jace/proxy/com/ms/silverking/cloud/dht/StorageType.h"
using jace::proxy::com::ms::silverking::cloud::dht::StorageType;
#include "jace/proxy/com/ms/silverking/cloud/dht/TimeoutResponse.h"
using jace::proxy::com::ms::silverking::cloud::dht::TimeoutResponse;
#include "jace/proxy/com/ms/silverking/cloud/dht/ValueCreator.h"
using jace::proxy::com::ms::silverking::cloud::dht::ValueCreator;
#include "jace/proxy/com/ms/silverking/cloud/dht/VersionConstraint.h"
using jace::proxy::com::ms::silverking::cloud::dht::VersionConstraint;
#include "jace/proxy/com/ms/silverking/cloud/dht/VersionConstraint_Mode.h"
using jace::proxy::com::ms::silverking::cloud::dht::VersionConstraint_Mode;
#include "jace/proxy/com/ms/silverking/cloud/dht/WaitMode.h"
using jace::proxy::com::ms::silverking::cloud::dht::WaitMode;
#include "jace/proxy/com/ms/silverking/cloud/dht/WaitOptions.h"
using jace::proxy::com::ms::silverking::cloud::dht::WaitOptions;
#include "jace/proxy/com/ms/silverking/cloud/dht/SecondaryTarget.h"
using jace::proxy::com::ms::silverking::cloud::dht::SecondaryTarget;
#include "jace/proxy/com/ms/silverking/cloud/dht/common/NamespaceOptionsClient.h"
using jace::proxy::com::ms::silverking::cloud::dht::common::NamespaceOptionsClient;
#include "jace/proxy/com/ms/silverking/cloud/dht/common/DHTUtil.h"
using jace::proxy::com::ms::silverking::cloud::dht::common::DHTUtil;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/AbsMillisVersionProvider.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::AbsMillisVersionProvider;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/AsynchronousNamespacePerspective.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::AsynchronousNamespacePerspective;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/AsynchronousReadableNamespacePerspective.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::AsynchronousReadableNamespacePerspective;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/AsynchronousWritableNamespacePerspective.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::AsynchronousWritableNamespacePerspective;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/AsyncKeyedOperation.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::AsyncKeyedOperation;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/AsyncOperation.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::AsyncOperation;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/AsyncPut.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::AsyncPut;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/AsyncValueRetrieval.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::AsyncValueRetrieval;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/AsyncRetrieval.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::AsyncRetrieval;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/AsyncSingleRetrieval.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::AsyncSingleRetrieval;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/AsyncSingleValueRetrieval.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::AsyncSingleValueRetrieval;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/AsyncSyncRequest.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::AsyncSyncRequest;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/AsyncSnapshot.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::AsyncSnapshot;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/BaseNamespacePerspective.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::BaseNamespacePerspective;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/ChecksumType.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::ChecksumType;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/ClientDHTConfiguration.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::ClientDHTConfiguration;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/ClientDHTConfigurationProvider.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::ClientDHTConfigurationProvider;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/ClientException.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::ClientException;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/Compression.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::Compression;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/DHTClient.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::DHTClient;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/DHTSession.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::DHTSession;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/FailureCause.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::FailureCause;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/KeyDigestType.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::KeyDigestType;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/KeyedOperationException.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::KeyedOperationException;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/OperationException.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::OperationException;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/OperationState.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::OperationState;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/MetaData.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::MetaData;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/Namespace.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::Namespace;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/NamespaceCreationException.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::NamespaceCreationException;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/NamespaceLinkException.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::NamespaceLinkException;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/PutException.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::PutException;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/RelNanosVersionProvider.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::RelNanosVersionProvider;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/RetrievalException.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::RetrievalException;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/SnapshotException.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::SnapshotException;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/SyncRequestException.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::SyncRequestException;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/WaitForCompletionException.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::WaitForCompletionException;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/StoredValue.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::StoredValue;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/StoredValueBase.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::StoredValueBase;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/SynchronousReadableNamespacePerspective.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::SynchronousReadableNamespacePerspective;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/SynchronousWritableNamespacePerspective.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::SynchronousWritableNamespacePerspective;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/SynchronousNamespacePerspective.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::SynchronousNamespacePerspective;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/VersionProvider.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::VersionProvider;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/OpTimeoutController.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::OpTimeoutController;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/SimpleTimeoutController.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::SimpleTimeoutController;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/OpSizeBasedTimeoutController.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::OpSizeBasedTimeoutController;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/WaitForTimeoutController.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::WaitForTimeoutController;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/SecondaryTargetType.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::SecondaryTargetType;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/NamespaceDeletionException.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::NamespaceDeletionException;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/NamespaceRecoverException.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::NamespaceRecoverException;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/SessionEstablishmentTimeoutController.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::SessionEstablishmentTimeoutController;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/SimpleSessionEstablishmentTimeoutController.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::SimpleSessionEstablishmentTimeoutController;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/impl/DHTSessionImpl.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::impl::DHTSessionImpl;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/impl/AsynchronousNamespacePerspectiveImpl.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::impl::AsynchronousNamespacePerspectiveImpl;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/impl/SynchronousNamespacePerspectiveImpl.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::impl::SynchronousNamespacePerspectiveImpl;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/impl/PutExceptionImpl.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::impl::PutExceptionImpl;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/impl/RetrievalExceptionImpl.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::impl::RetrievalExceptionImpl;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/impl/SyncRequestExceptionImpl.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::impl::SyncRequestExceptionImpl;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/serialization/BufferDestSerializer.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::serialization::BufferDestSerializer;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/serialization/BufferSerDes.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::serialization::BufferSerDes;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/serialization/BufferSourceDeserializer.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::serialization::BufferSourceDeserializer;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/serialization/ByteArraySerDes.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::serialization::ByteArraySerDes;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/serialization/ObjectSerDes.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::serialization::ObjectSerDes;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/serialization/RawByteArraySerDes.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::serialization::RawByteArraySerDes;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/serialization/SerializationRegistry.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::serialization::SerializationRegistry;
#include "jace/proxy/com/ms/silverking/cloud/dht/client/serialization/StringSerDes.h"
using jace::proxy::com::ms::silverking::cloud::dht::client::serialization::StringSerDes;
#include "jace/proxy/com/ms/silverking/cloud/dht/gridconfig/SKGridConfiguration.h"
using jace::proxy::com::ms::silverking::cloud::dht::gridconfig::SKGridConfiguration;
#include "jace/proxy/com/ms/silverking/cloud/dht/net/ForwardingMode.h"
using jace::proxy::com::ms::silverking::cloud::dht::net::ForwardingMode;
#include "jace/proxy/com/ms/silverking/net/HostAndPort.h"
using jace::proxy::com::ms::silverking::net::HostAndPort;
#include "jace/proxy/com/ms/silverking/net/AddrAndPort.h"
using jace::proxy::com::ms::silverking::net::AddrAndPort;
#include "jace/proxy/com/ms/silverking/net/IPAndPort.h"
using jace::proxy::com::ms::silverking::net::IPAndPort;
#include "jace/proxy/com/ms/silverking/thread/lwt/LWTPoolProvider.h"
using jace::proxy::com::ms::silverking::thread::lwt::LWTPoolProvider;
#include "jace/proxy/com/ms/silverking/thread/lwt/DefaultWorkPoolParameters.h"
using jace::proxy::com::ms::silverking::thread::lwt::DefaultWorkPoolParameters;
#include "jace/proxy/com/ms/silverking/time/AbsMillisTimeSource.h"
using jace::proxy::com::ms::silverking::time::AbsMillisTimeSource;
#include "jace/proxy/com/ms/silverking/time/RelNanosAbsMillisTimeSource.h"
using jace::proxy::com::ms::silverking::time::RelNanosAbsMillisTimeSource;
#include "jace/proxy/com/ms/silverking/time/RelNanosTimeSource.h"
using jace::proxy::com::ms::silverking::time::RelNanosTimeSource;
#include "jace/proxy/com/ms/silverking/time/Stopwatch.h"
using jace::proxy::com::ms::silverking::time::Stopwatch;
#include "jace/proxy/com/ms/silverking/time/ConstantAbsMillisTimeSource.h"
using jace::proxy::com::ms::silverking::time::ConstantAbsMillisTimeSource;
#include "jace/proxy/com/ms/silverking/time/SimpleNamedStopwatch.h"
using jace::proxy::com::ms::silverking::time::SimpleNamedStopwatch;
#include "jace/proxy/com/ms/silverking/time/SimpleStopwatch.h"
using jace::proxy::com::ms::silverking::time::SimpleStopwatch;
#include "jace/proxy/com/ms/silverking/time/StopwatchBase.h"
using jace::proxy::com::ms::silverking::time::StopwatchBase;
#include "jace/proxy/com/ms/silverking/time/SystemTimeSource.h"
using jace::proxy::com::ms::silverking::time::SystemTimeSource;
#include "jace/proxy/com/ms/silverking/time/TimerDrivenTimeSource.h"
using jace::proxy::com::ms::silverking::time::TimerDrivenTimeSource;
#include "jace/proxy/com/ms/silverking/time/Stopwatch_State.h"
using jace::proxy::com::ms::silverking::time::Stopwatch_State;
//using namespace jace::proxy::com::ms::silverking::cloud::dht;
//using namespace jace::proxy::com::ms::silverking::cloud::dht::client;
//using namespace jace::proxy::com::ms::silverking::cloud::dht::client::impl;
typedef JArray< jace::proxy::types::JByte > ByteArray;
#endif //DHTCOMMON_H
| [
"glenn.judd@morganstanley.com"
] | glenn.judd@morganstanley.com |
aa6282c46b6197ca60c85f2411fabfeeb24bf1b7 | 4bccb70f8351c01a33feaccf6f5299a027a59847 | /code/cc/bench/t_cond.cc | d057d05da95c90461306306e7a96ec3b2695af0b | [] | no_license | ichengzi/sperm | 012a6581d1b1ee7f9089a41227005051b086fc48 | f6f9d1aeca158ed42554295155fd218a926aaa37 | refs/heads/master | 2020-03-15T06:16:54.431036 | 2018-05-03T14:17:36 | 2018-05-03T14:17:36 | 132,003,931 | 0 | 0 | null | 2018-05-03T14:04:40 | 2018-05-03T14:04:40 | null | UTF-8 | C++ | false | false | 5,880 | cc | /*
* Copyright (C) dirlt
*/
#include "bench/perf_base.h"
#include "bench/define.h"
using namespace bench::perf_base;
// ------------------------------------------------------------
// pthread_cond
typedef PerfBase < ConditionWait > PBConditionWait;
static void* PBConditionWait_callback(void* arg) {
PBConditionWait* p = static_cast<PBConditionWait*>(arg);
p->perf();
return NULL;
}
typedef PerfBase < ConditionSignal > PBConditionSignal;
static void* PBConditionSignal_callback(void* arg) {
PBConditionSignal* p = static_cast<PBConditionSignal*>(arg);
p->perf();
return NULL;
}
void test_pthread_cond() {
static const int kReadThreadNumber = 8;
static const int kWriteThreadNumber = 8;
pthread_t rtid[kReadThreadNumber];
pthread_t wtid[kWriteThreadNumber];
static const int kDelayMillSeconds = 2000;
common::MutexLock lock;
common::Condition cond(lock);
ConditionWait wc(&cond, &lock, kDelayMillSeconds);
ConditionSignal sc(&cond, &lock);
PBConditionWait wp(&wc);
PBConditionSignal sp(&sc);
RTC(PBConditionWait_callback, &wp);
WTC(PBConditionSignal_callback, &sp);
wp.start();
sp.start();
sleep_ms(kDelayMillSeconds);
wp.stop();
sp.stop();
RTJ();
WTJ();
wp.stat();
sp.stat();
}
// ------------------------------------------------------------
// pipe_pair_cond
typedef PerfBase < PipePairCondWait > PBPipePairCondWait;
static void* PBPipePairCondWait_callback(void* arg) {
PBPipePairCondWait* p = static_cast<PBPipePairCondWait*>(arg);
p->perf();
return NULL;
}
typedef PerfBase < PipePairCondSignal > PBPipePairCondSignal;
static void* PBPipePairCondSignal_callback(void* arg) {
PBPipePairCondSignal* p = static_cast<PBPipePairCondSignal*>(arg);
p->perf();
return NULL;
}
void test_pipe_pair_cond() {
static const int kReadThreadNumber = 8;
static const int kWriteThreadNumber = 8;
pthread_t rtid[kReadThreadNumber];
pthread_t wtid[kWriteThreadNumber];
static const int kDelayMillSeconds = 2000;
common::PipePairCondition cond;
PipePairCondWait wc(&cond, kDelayMillSeconds);
PipePairCondSignal sc(&cond);
PBPipePairCondWait wp(&wc);
PBPipePairCondSignal sp(&sc);
RTC(PBPipePairCondWait_callback, &wp);
WTC(PBPipePairCondSignal_callback, &sp);
wp.start();
sp.start();
sleep_ms(kDelayMillSeconds);
wp.stop();
sp.stop();
RTJ();
WTJ();
wp.stat();
sp.stat();
}
// ------------------------------------------------------------
// socket_pair_cond
typedef PerfBase < SocketPairCondWait > PBSocketPairCondWait;
static void* PBSocketPairCondWait_callback(void* arg) {
PBSocketPairCondWait* p = static_cast<PBSocketPairCondWait*>(arg);
p->perf();
return NULL;
}
typedef PerfBase < SocketPairCondSignal > PBSocketPairCondSignal;
static void* PBSocketPairCondSignal_callback(void* arg) {
PBSocketPairCondSignal* p = static_cast<PBSocketPairCondSignal*>(arg);
p->perf();
return NULL;
}
void test_socket_pair_cond() {
static const int kReadThreadNumber = 8;
static const int kWriteThreadNumber = 8;
pthread_t rtid[kReadThreadNumber];
pthread_t wtid[kWriteThreadNumber];
static const int kDelayMillSeconds = 2000;
common::SocketPairCondition cond;
SocketPairCondWait wc(&cond, kDelayMillSeconds);
SocketPairCondSignal sc(&cond);
PBSocketPairCondWait wp(&wc);
PBSocketPairCondSignal sp(&sc);
RTC(PBSocketPairCondWait_callback, &wp);
WTC(PBSocketPairCondSignal_callback, &sp);
wp.start();
sp.start();
sleep_ms(kDelayMillSeconds);
wp.stop();
sp.stop();
RTJ();
WTJ();
wp.stat();
sp.stat();
}
// ------------------------------------------------------------
// tcp_pair_cond
typedef PerfBase < TcpPairCondWait > PBTcpPairCondWait;
static void* PBTcpPairCondWait_callback(void* arg) {
PBTcpPairCondWait* p = static_cast<PBTcpPairCondWait*>(arg);
p->perf();
return NULL;
}
typedef PerfBase < TcpPairCondSignal > PBTcpPairCondSignal;
static void* PBTcpPairCondSignal_callback(void* arg) {
PBTcpPairCondSignal* p = static_cast<PBTcpPairCondSignal*>(arg);
p->perf();
return NULL;
}
void test_tcp_pair_cond() {
static const int kReadThreadNumber = 8;
static const int kWriteThreadNumber = 8;
pthread_t rtid[kReadThreadNumber];
pthread_t wtid[kWriteThreadNumber];
static const int kDelayMillSeconds = 2000;
common::TcpPairCondition cond;
TcpPairCondWait wc(&cond, kDelayMillSeconds);
TcpPairCondSignal sc(&cond);
PBTcpPairCondWait wp(&wc);
PBTcpPairCondSignal sp(&sc);
RTC(PBTcpPairCondWait_callback, &wp);
WTC(PBTcpPairCondSignal_callback, &sp);
wp.start();
sp.start();
sleep_ms(kDelayMillSeconds);
wp.stop();
sp.stop();
RTJ();
WTJ();
wp.stat();
sp.stat();
}
// ------------------------------------------------------------
// futex cond
typedef PerfBase < FutexCondWait > PBFutexCondWait;
static void* PBFutexCondWait_callback(void* arg) {
PBFutexCondWait* p = static_cast<PBFutexCondWait*>(arg);
p->perf();
return NULL;
}
typedef PerfBase < FutexCondSignal > PBFutexCondSignal;
static void* PBFutexCondSignal_callback(void* arg) {
PBFutexCondSignal* p = static_cast<PBFutexCondSignal*>(arg);
p->perf();
return NULL;
}
void test_futex_cond() {
static const int kReadThreadNumber = 8;
static const int kWriteThreadNumber = 8;
pthread_t rtid[kReadThreadNumber];
pthread_t wtid[kWriteThreadNumber];
static const int kDelayMillSeconds = 2000;
common::FutexCondition cond;
FutexCondWait wc(&cond, kDelayMillSeconds);
FutexCondSignal sc(&cond);
PBFutexCondWait wp(&wc);
PBFutexCondSignal sp(&sc);
RTC(PBFutexCondWait_callback, &wp);
WTC(PBFutexCondSignal_callback, &sp);
wp.start();
sp.start();
sleep_ms(kDelayMillSeconds);
wp.stop();
sp.stop();
RTJ();
WTJ();
wp.stat();
sp.stat();
}
int main() {
test_pthread_cond();
test_pipe_pair_cond();
test_socket_pair_cond();
test_tcp_pair_cond();
test_futex_cond();
return 0;
}
| [
"dirtysalt1987@gmail.com"
] | dirtysalt1987@gmail.com |
c7f804ca9d03ac73e84de8ce6190506bb54b4c75 | bd498cbbb28e33370298a84b693f93a3058d3138 | /Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/src/operator/nn/mkldnn/mkldnn_base-inl.h | 9763c4243f179eded3ae39fbcadd98b5f144ce4a | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"Zlib",
"BSD-2-Clause-Views",
"NCSA",
"OFL-1.0",
"Unlicense",
"BSL-1.0",
"BSD-2-Clause",
"MIT"
] | permissive | piyushghai/training_results_v0.7 | afb303446e75e3e9789b0f6c40ce330b6b83a70c | e017c9359f66e2d814c6990d1ffa56654a73f5b0 | refs/heads/master | 2022-12-19T16:50:17.372320 | 2020-09-24T01:02:00 | 2020-09-24T18:01:01 | 298,127,245 | 0 | 1 | Apache-2.0 | 2020-09-24T00:27:21 | 2020-09-24T00:27:21 | null | UTF-8 | C++ | false | false | 23,203 | h | /*
* 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.
*/
/*******************************************************************************
* Copyright 2016-2017 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* \file mkldnn_base-inl.h
* \brief
* \author young.jin.kim@intel.com
* ashok.emani@intel.com
* deepthi.karkada@intel.com
* louis.feng@intel.com
* adam.d.straw@intel.com
* zhengda1936@gmail.com
*
*******************************************************************************/
#ifndef MXNET_OPERATOR_NN_MKLDNN_MKLDNN_BASE_INL_H_
#define MXNET_OPERATOR_NN_MKLDNN_MKLDNN_BASE_INL_H_
#if MXNET_USE_MKLDNN == 1
#include <algorithm>
#include <iterator>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "mkldnn.hpp"
#include "mxnet/graph_attr_types.h"
#include "mxnet/ndarray.h"
#include "mxnet/op_attr_types.h"
#include "mxnet/resource.h"
namespace mxnet {
// ===== CpuEngine =======================================
// cpu_engine singleton
class CpuEngine {
public:
static CpuEngine *Get() {
// I's thread-safe in C++11.
// ensure same mkldnn engine is used across threads
static CpuEngine myInstance;
return &myInstance;
}
CpuEngine(CpuEngine const &) = delete; // Copy construct
CpuEngine(CpuEngine &&) = delete; // Move construct
CpuEngine &operator=(CpuEngine const &) = delete; // Copy assign
CpuEngine &operator=(CpuEngine &&) = delete; // Move assign
mkldnn::engine &get_engine() { return _cpu_engine; }
protected:
CpuEngine() : _cpu_engine(mkldnn::engine::kind::cpu, 0) {}
~CpuEngine() {}
private:
mkldnn::engine _cpu_engine;
};
// type enumerator
template <typename T>
struct data_type_enum {};
template <>
struct data_type_enum<float> {
enum { type = static_cast<unsigned int>(mkldnn::memory::data_type::f32) };
};
template <>
struct data_type_enum<int32_t> {
enum { type = static_cast<unsigned int>(mkldnn::memory::data_type::s32) };
};
template <>
struct data_type_enum<int8_t> {
enum { type = static_cast<unsigned int>(mkldnn::memory::data_type::s8) };
};
template <>
struct data_type_enum<uint8_t> {
enum { type = static_cast<unsigned int>(mkldnn::memory::data_type::u8) };
};
static inline bool SupportMKLDNNArray(int dtype, const mxnet::TShape &shape) {
int ndim = shape.ndim();
bool support = ndim == 1 || ndim == 2 || ndim == 4;
support = support && (dtype == mshadow::kFloat32 || dtype == mshadow::kInt32
|| dtype == mshadow::kInt8 || dtype == mshadow::kUint8);
return support;
}
static inline bool SupportStorageMKLDNN(int stype) {
return stype == kDefaultStorage;
}
static inline bool SupportMKLDNN(int dtype, const mxnet::TShape &shape) {
int ndim = shape.ndim();
if (ndim == 0 || shape.Size() == 0) {
// MKLDNN currently does not support 0-dim Tensor and 0-size Tensor
return false;
}
return dtype == mshadow::kFloat32 && (ndim == 1 || ndim == 2 || ndim == 4);
}
static inline bool SupportMKLDNNRnn(const NDArray &input) {
if (input.dtype() == mshadow::kFloat32 && input.shape().ndim() == 3
&& dmlc::GetEnv("MXNET_USE_MKLDNN_RNN", 1)) {
return true;
}
return false;
}
static inline bool SupportMKLDNNQuantize(int dtype) {
return dtype == mshadow::kFloat32 || dtype == mshadow::kInt8 ||
dtype == mshadow::kUint8;
}
static inline bool SupportMKLDNN(const NDArray &input) {
return SupportMKLDNN(input.dtype(), input.shape())
&& SupportStorageMKLDNN(input.storage_type());
}
static inline bool MKLDNNEnvSet() {
static bool is_mkldnn_enabled = dmlc::GetEnv("MXNET_MKLDNN_ENABLED", true);
return is_mkldnn_enabled;
}
static inline int GetMKLDNNCacheSize() {
static int mkldnn_cache_size = dmlc::GetEnv("MXNET_MKLDNN_CACHE_NUM", -1);
return mkldnn_cache_size;
}
// TODO(alex): (MXNET-1075) Will remove env variable and calculate cache size during runtime
template<typename S, typename I, typename H>
static typename std::unordered_map<S, I, H>::iterator AddToCache(
std::unordered_map<S, I, H>* cache, const S &key, const I &item) {
int mkldnn_cache_size = GetMKLDNNCacheSize();
if (mkldnn_cache_size != -1 && static_cast<int>(cache->size()) > mkldnn_cache_size)
cache->erase(cache->begin());
auto ins_return = cache->insert(std::pair<S, I>(key, item));
CHECK(ins_return.second);
return ins_return.first;
}
/*
* This is to align address to a certain alignment.
*/
void *AlignMem(void *mem, size_t size, size_t alignment, size_t *space);
namespace op {
struct ActivationParam;
struct LeakyReLUParam;
struct ConvolutionParam;
struct DeconvolutionParam;
struct SoftmaxParam;
struct SoftmaxOutputParam;
struct TransposeParam;
struct ReshapeParam;
bool SupportMKLDNNAct(const ActivationParam& param);
bool SupportMKLDNNAct(const ActivationParam& param, const NDArray &input);
bool SupportMKLDNNLeakyRelu(const LeakyReLUParam& param);
bool SupportMKLDNNLeakyRelu(const LeakyReLUParam& param, const NDArray &input);
bool SupportQuantizedMKLDNNAct(const ActivationParam ¶m);
bool SupportMKLDNNConv(const ConvolutionParam ¶ms, const NDArray &input);
bool SupportMKLDNNDeconv(const DeconvolutionParam& params, const NDArray &input);
bool SupportMKLDNNSoftmax(const SoftmaxParam& param, const NDArray &input, const NDArray &output);
bool SupportMKLDNNSoftmaxOutput(const SoftmaxOutputParam ¶m);
bool SupportMKLDNNTranspose(const TransposeParam& param, const NDArray &data);
} // namespace op
static int GetTypeSize(int dtype) {
int size = -1;
MSHADOW_TYPE_SWITCH(dtype, DType, {
size = sizeof(DType);
});
return size;
}
static inline size_t GetArraySize(const NDArray &arr) {
if (arr.IsMKLDNNData()) {
return arr.GetMKLDNNData()->get_desc().get_size();
}
return arr.shape().Size() * GetTypeSize(arr.dtype());
}
static inline mkldnn::memory::data_type get_mkldnn_type(int dtype) {
switch (dtype) {
case mshadow::kFloat32:
return mkldnn::memory::data_type::f32;
case mshadow::kInt32:
return mkldnn::memory::data_type::s32;
case mshadow::kInt8:
return mkldnn::memory::data_type::s8;
case mshadow::kUint8:
return mkldnn::memory::data_type::u8;
default:
LOG(FATAL) << "unknown type for MKLDNN";
return mkldnn::memory::data_type::undef;
}
}
template<typename T>
static inline mkldnn::memory::data_type get_mkldnn_type() {
return static_cast<mkldnn::memory::data_type>(data_type_enum<T>::type);
}
static inline mkldnn_data_type_t get_mkldnn_type_t(int dtype) {
return static_cast<mkldnn_data_type_t>(get_mkldnn_type(dtype));
}
template<typename T>
static inline mkldnn_data_type_t get_mkldnn_type_t() {
return static_cast<mkldnn_data_type_t>(data_type_enum<T>::type);
}
static inline int get_mxnet_type(mkldnn_data_type_t dtype) {
auto mkldnn_dtype = static_cast<mkldnn::memory::data_type>(dtype);
switch (mkldnn_dtype) {
case mkldnn::memory::data_type::f32:
return mshadow::kFloat32;
case mkldnn::memory::data_type::s32:
return mshadow::kInt32;
case mkldnn::memory::data_type::s8:
return mshadow::kInt8;
case mkldnn::memory::data_type::u8:
return mshadow::kUint8;
default:
LOG(FATAL) << "unknown MKLDNN type";
return mshadow::kFloat32;
}
}
static inline size_t GetMemDescSize(const mkldnn::memory::desc &md) {
if (md.data.ndims == 0) return 0;
size_t ret = 1;
for (int i = 0; i < md.data.ndims; i++) {
ret *= md.data.dims[i];
}
ret *= mshadow::mshadow_sizeof(get_mxnet_type(md.data.data_type));
return ret;
}
inline static mkldnn::memory::desc GetMemDesc(const NDArray &arr, int dtype = -1) {
int ndim = arr.shape().ndim();
mkldnn::memory::dims dims(ndim);
dtype = (dtype == -1) ? arr.dtype() : dtype;
for (size_t i = 0; i < dims.size(); i++) dims[i] = arr.shape()[i];
return mkldnn::memory::desc{dims, get_mkldnn_type(dtype), mkldnn::memory::format_tag::any};
}
inline static mkldnn::memory::desc GetFCWeightDesc(const NDArray &arr, int dtype = -1) {
int ndim = arr.shape().ndim();
mkldnn::memory::dims dims(ndim);
dtype = (dtype == -1) ? arr.dtype() : dtype;
for (size_t i = 0; i < dims.size(); i++) dims[i] = arr.shape()[i];
auto format = mkldnn::memory::format_tag::any;
// for batch 256 alexnet benchmark test
if (dims.size() == 2) {
format = mkldnn::memory::format_tag::ab;
}
return mkldnn::memory::desc{dims, get_mkldnn_type(dtype), format};
}
inline static mkldnn::memory::desc GetWeightDesc(const NDArray &arr,
int num_groups,
bool quantized = false) {
int dtype = quantized ? mshadow::kInt8 : arr.dtype();
if (num_groups == 1) {
return GetMemDesc(arr, dtype);
} else {
auto ndim = arr.shape().ndim();
CHECK((ndim == 3) || (ndim == 4))
<< "MKL-DNN weight currectly supports 3d and 4d layout";
auto tz = mkldnn::memory::dims{0};
const int N = 0, H = 2, W = 3, C = 1;
if (ndim == 3) {
tz = mkldnn::memory::dims{
num_groups, static_cast<int>(arr.shape()[N] / num_groups),
static_cast<int>(arr.shape()[C]), static_cast<int>(arr.shape()[H])};
} else {
tz = mkldnn::memory::dims{
num_groups, static_cast<int>(arr.shape()[N] / num_groups),
static_cast<int>(arr.shape()[C]), static_cast<int>(arr.shape()[H]),
static_cast<int>(arr.shape()[W])};
}
return mkldnn::memory::desc{tz, get_mkldnn_type(dtype), mkldnn::memory::format_tag::any};
}
}
inline static bool CheckMKLDNNInputArrayIsView(const std::vector<NDArray> &inputs) {
for (const auto &in : inputs) {
if (in.IsView() && in.IsMKLDNNData()) {
return true;
}
}
return false;
}
typedef std::shared_ptr<mkldnn::memory> mkldnn_mem_ptr;
typedef std::shared_ptr<const mkldnn::memory> mkldnn_mem_const_ptr;
/*
* This is to manage the temporary memory provided by MXNet for operators.
* The temp memory is mainly used to keep the reordered data. In an operator, we
* may need multiple pieces of memory for them. But MXNet can only provide
* a single piece of memory. This class is to help break the temporary memory
* from MXNet to store the reordered data.
* The amount of temporary memory used in an operator depends on the layout of
* input arrays and the operator. It's difficult to calculate it manually, so
* the class also estimate the amount of memory automatically.
*/
class TmpMemMgr {
// This points to the memory buffer where we can allocate temp memory.
char *curr_mem;
// The total size of the temp memory.
size_t mem_size;
// This contains the current available memory size.
size_t curr_size;
// This estimate the required temp memory size in an operator.
size_t est_size;
const size_t alignment = kMKLDNNAlign;
public:
static TmpMemMgr *Get() {
#if DMLC_CXX11_THREAD_LOCAL
static thread_local TmpMemMgr mgr;
#else
static MX_THREAD_LOCAL TmpMemMgr mgr;
#endif
return &mgr;
}
TmpMemMgr() {
Reset();
est_size = 0;
mem_size = 0;
}
void Reset() {
curr_mem = nullptr;
curr_size = 0;
// We don't reset est_size and mem_size because est_size contains the
// estimated temp memory size from the last run and mem_size contains the
// memroy size allocated in the last run.
}
void Init(const Resource &r) {
// If the last time, if we estimate that we need more memory, we should the
// larger memory size.
mem_size = std::max(mem_size, est_size);
if (mem_size > 0) {
// Let's allocate some extra memory. If we don't use some of them all the time,
// the OS won't physically allocate pages for them any way.
this->curr_size = mem_size * 2;
this->curr_mem = static_cast<char *>(r.get_host_space_internal(this->curr_size));
}
// reset est_size, so we can start to estimate the temp memory size.
this->est_size = 0;
}
mkldnn::memory *Alloc(const mkldnn::memory::desc &md);
};
typedef std::unordered_map<int, mkldnn::memory> mkldnn_args_map_t;
class MKLDNNStream {
std::vector<std::pair<mkldnn::primitive, mkldnn_args_map_t> > net_prim_args;
// Here we hold all memory related to the operators in the stream.
std::vector<std::shared_ptr<const mkldnn::memory> > mem_holder;
mkldnn::stream s;
public:
static MKLDNNStream *Get();
MKLDNNStream(): s(CpuEngine::Get()->get_engine()) {}
void RegisterPrimArgs(const mkldnn::primitive &prim,
const mkldnn_args_map_t &args) {
net_prim_args.emplace_back(prim, args);
}
void RegisterMem(std::shared_ptr<const mkldnn::memory> mem) {
mem_holder.push_back(mem);
}
bool HasOps() const {
return !net_prim_args.empty();
}
/*
* After submitting mkldnn operations for execution, we need to
* clean up memory held by the stream. However, sometimes users
* might want to separate mkldnn execution and memory cleanup.
*/
void Submit(bool cleanup = true) {
if (!net_prim_args.empty()) {
for (auto &v : net_prim_args) {
v.first.execute(s, v.second);
}
net_prim_args.clear();
}
if (cleanup)
Cleanup();
}
void Cleanup() {
mem_holder.clear();
TmpMemMgr::Get()->Reset();
}
};
enum OutDataOp {
Noop,
CopyBack,
AddBack,
};
typedef std::pair<OutDataOp, mkldnn::memory *> mkldnn_output_t;
void MKLDNNCopy(const mkldnn::memory &mem, const mkldnn::memory* this_mem);
/*
* Here we want to get MKLDNN memory whose desc is exactly the same as
* the given one. operator== can't guarantee that. == can return true even if
* the formats are different. I need to double check its format.
*/
static inline mkldnn::memory *GetMKLDNNExact(
const mkldnn::memory *mem, const mkldnn::memory::desc &desc) {
mkldnn::memory::desc src_desc = mem->get_desc();
if (desc == src_desc) {
return const_cast<mkldnn::memory *>(mem);
} else {
std::shared_ptr<mkldnn::memory> ret(new mkldnn::memory(
desc, CpuEngine::Get()->get_engine(), mem->get_data_handle()));
MKLDNNStream::Get()->RegisterMem(ret);
return ret.get();
}
}
/*
* These two functions try to create MKLDNN memory in an NDArray based on `req'.
* The difference is that the first function can create MKLDNN memory with
* special layouts in an NDArray, while the second one can only create MKLDNN
* memory with default layouts.
* Also an optional in_arr parameter can be passed in the first function with
* the kWriteInPlace req to validate if mkldnn can support write in place;
* otherwise new memory will be written to an copied back onto out_arr.
* If these two functions are used, we have to call CommitOutput to write
* the output back to the output NDArray.
*/
mkldnn_output_t CreateMKLDNNMem(const NDArray &out_arr,
const mkldnn::memory::desc &desc,
OpReqType req, const NDArray* in_arr = nullptr);
mkldnn_output_t CreateMKLDNNWeightGrad(const NDArray &out_arr,
const mkldnn::memory::desc &desc,
OpReqType req);
/* This function has to be used with one of the functions above. */
void CommitOutput(const NDArray &arr, const mkldnn_output_t &res);
static inline void InvalidateOutputs(const std::vector<NDArray> &arrs,
const std::vector<OpReqType> &reqs) {
for (size_t i = 0; i < arrs.size(); i++) {
if (reqs[i] == kWriteTo || reqs[i] == kNullOp) {
const_cast<NDArray &>(arrs[i]).InvalidateMKLDNNData();
}
}
}
// TODO(alexzai): (MXNET-856) Remove helper function after subgraph feature added
static inline void CreateDefaultInputs(const std::vector<NDArray> &arrs,
std::vector<NDArray> *out_arrs) {
out_arrs->clear();
for (size_t i = 0; i < arrs.size(); ++i) {
if (arrs[i].IsMKLDNNData())
out_arrs->push_back(arrs[i].Reorder2Default());
else
out_arrs->push_back(arrs[i]);
}
}
const mkldnn::memory *GetWeights(const NDArray &arr, int num_groups);
const mkldnn::memory *GetWeights(const NDArray &arr,
const mkldnn::memory::desc &target_md,
int num_groups);
bool IsDefaultFormat(const mkldnn::memory::desc &desc);
bool IsMKLDNN(const mkldnn::memory::desc &desc);
mkldnn_format_tag_t GetDefaultFormat(const mkldnn::memory::desc &md);
mkldnn_format_tag_t GetDefaultFormat(int num_dims);
mkldnn::memory::desc GetDesc(const mkldnn::memory::desc &md, const mkldnn_format_tag_t &format);
inline bool same_shape(const mxnet::TShape &shape, const mkldnn_dims_t dims, int ndims) {
if (shape.ndim() != ndims)
return false;
for (int i = 0; i < ndims; i++)
if (shape[i] != dims[i])
return false;
return true;
}
inline bool same_shape(const mkldnn::memory::desc &desc1,
const mkldnn::memory::desc &desc2) {
if (desc1.data.ndims != desc2.data.ndims)
return false;
for (int i = 0; i < desc1.data.ndims; i++)
if (desc1.data.dims[i] != desc2.data.dims[i])
return false;
return true;
}
inline bool same_shape(const mxnet::TShape &shape, int dtype,
const mkldnn::memory::desc &desc) {
return same_shape(shape, desc.data.dims, desc.data.ndims)
&& get_mkldnn_type(dtype) == desc.data.data_type;
}
/*
* There is a large overhead of getting mkldnn::memory::desc from
* mkldnn::memory. This class is created to cache the metadata of mkldnn memory
* to provide a much more lightweight method to access them.
*/
class MKLDNNMemory {
std::shared_ptr<mkldnn::memory> mem;
mkldnn::memory::desc desc;
size_t size; // The number of bytes.
public:
MKLDNNMemory(mkldnn::memory::desc md, void *addr): desc(md) {
mem.reset(new mkldnn::memory(md, CpuEngine::Get()->get_engine(), addr));
size = desc.get_size();
}
explicit MKLDNNMemory(std::shared_ptr<mkldnn::memory> mem): desc(
mem->get_desc()) {
this->mem = mem;
size = desc.get_size();
}
void SetDataHandle(void *handle) {
mem->set_data_handle(handle);
}
void *GetDataHandle() const {
return mem->get_data_handle();
}
std::shared_ptr<mkldnn::memory> GetMem() const {
return mem;
}
mkldnn::memory *GetRaw() const {
return mem.get();
}
size_t GetSize() const {
return size;
}
mkldnn::memory::desc GetDesc() const {
return mem->get_desc();
}
mkldnn::memory::desc GetDesc(mkldnn_format_tag_t format) const {
mkldnn::memory::dims dims(desc.data.dims, desc.data.dims + desc.data.ndims);
mkldnn::memory::data_type cpp_type =
static_cast<mkldnn::memory::data_type>(desc.data.data_type);
mkldnn::memory::desc data_md(dims, cpp_type,
static_cast<mkldnn::memory::format_tag>(format));
return data_md;
}
mkldnn_format_tag_t GetDefaultFormat() const {
return mxnet::GetDefaultFormat(desc);
}
bool IsMKLDNN() const {
return mxnet::IsMKLDNN(desc);
}
bool SameFormat(mkldnn::memory::desc md) const {
return mem->get_desc() == md;
}
bool SameFormat(const mxnet::TShape &shape, int dtype) const {
return same_shape(shape, dtype, desc);
}
void ReorderTo(mkldnn::memory *other) const {
mkldnn::stream s(CpuEngine::Get()->get_engine());
mkldnn::reorder(*mem, *other).execute(s, *mem, *other);
}
};
template <typename Compute, typename AttrState>
void FallBackCompute(Compute fn, const AttrState &attrs,
const OpContext &ctx,
const std::vector<NDArray> &inputs,
const std::vector<OpReqType> &req,
const std::vector<NDArray> &outputs);
/*
* This class is used to check the correctness of MKLDNN operators.
*/
class OpCheck {
std::vector<mxnet::NDArray> inputs;
std::vector<mxnet::NDArray> outputs;
bool backward;
size_t num_checks;
public:
OpCheck(bool backward, size_t num_checks) {
this->backward = backward;
this->num_checks = num_checks;
}
void Init(const std::vector<mxnet::NDArray> &inputs_,
const std::vector<mxnet::NDArray> &outputs_);
void Run(mxnet::FCompute fn, const nnvm::NodeAttrs &attrs,
const mxnet::OpContext &ctx,
const std::vector<mxnet::NDArray> &inputs_,
const std::vector<mxnet::OpReqType> &req,
const std::vector<mxnet::NDArray> &outputs_);
void CopyResult(const std::vector<mxnet::NDArray> &outputs_,
const std::vector<size_t>& indice);
};
bool MKLDNNStorageType(const nnvm::NodeAttrs &attrs,
const int dev_mask,
bool support_mkldnn,
DispatchMode *dispatch_mode,
std::vector<int> *in_attrs,
std::vector<int> *out_attrs);
#define MKLDNN_OPCHECK_INIT(backward, num_checks, inputs, outputs) \
static bool debug = dmlc::GetEnv("MXNET_MKLDNN_DEBUG", false); \
OpCheck check(backward, num_checks); \
if (debug) check.Init(inputs, outputs);
#define MKLDNN_OPCHECK_RUN(fn, attrs, ctx, inputs, req, outputs) \
if (debug) check.Run(fn, attrs, ctx, inputs, req, outputs);
#define MKLDNN_OPCHECK_COPY_RESULT(outputs, indice) \
if (debug) check.CopyResult(outputs, indice);
struct MKLDNNPostEltwiseParam {
mkldnn::algorithm alg = mkldnn::algorithm::undef;
float scale = 1.f;
float alpha = 0.f;
float beta = 1.f;
};
void MKLDNNRun(mxnet::FComputeEx fn,
const nnvm::NodeAttrs &attrs,
const mxnet::OpContext &ctx,
const std::vector<mxnet::NDArray> &inputs_,
const std::vector<mxnet::OpReqType> &req,
const std::vector<mxnet::NDArray> &outputs_);
} // namespace mxnet
#endif
#endif // MXNET_OPERATOR_NN_MKLDNN_MKLDNN_BASE_INL_H_
| [
"vbittorf@google.com"
] | vbittorf@google.com |
31c6045a3743605376340dcae7dd6cd32ed85db9 | 295f63009c42b5650d164e47bc48c90f28e4371c | /src/test/netbase_tests.cpp | 6ba7d2858ad05af615cf0ed3b0573be2793aff20 | [
"MIT"
] | permissive | Hawkkit/HawkkitCore | 648310a232256c3941df6314e025a228165599d6 | a7eac11a706259088c60bb1b9cfc16b20d6ee17c | refs/heads/master | 2020-11-25T11:57:39.307751 | 2019-12-17T15:30:11 | 2019-12-17T15:30:11 | 220,800,053 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,620 | cpp | // Copyright (c) 2012-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "netbase.h"
#include "test/test_hawkkit.h"
#include <string>
#include <boost/assign/list_of.hpp>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(netbase_tests, BasicTestingSetup)
static CNetAddr ResolveIP(const char* ip)
{
CNetAddr addr;
LookupHost(ip, addr, false);
return addr;
}
static CSubNet ResolveSubNet(const char* subnet)
{
CSubNet ret;
LookupSubNet(subnet, ret);
return ret;
}
BOOST_AUTO_TEST_CASE(netbase_networks)
{
BOOST_CHECK(ResolveIP("127.0.0.1").GetNetwork() == NET_UNROUTABLE);
BOOST_CHECK(ResolveIP("::1").GetNetwork() == NET_UNROUTABLE);
BOOST_CHECK(ResolveIP("8.8.8.8").GetNetwork() == NET_IPV4);
BOOST_CHECK(ResolveIP("2001::8888").GetNetwork() == NET_IPV6);
BOOST_CHECK(ResolveIP("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").GetNetwork() == NET_TOR);
}
BOOST_AUTO_TEST_CASE(netbase_properties)
{
BOOST_CHECK(ResolveIP("127.0.0.1").IsIPv4());
BOOST_CHECK(ResolveIP("::FFFF:192.168.1.1").IsIPv4());
BOOST_CHECK(ResolveIP("::1").IsIPv6());
BOOST_CHECK(ResolveIP("10.0.0.1").IsRFC1918());
BOOST_CHECK(ResolveIP("192.168.1.1").IsRFC1918());
BOOST_CHECK(ResolveIP("172.31.255.255").IsRFC1918());
BOOST_CHECK(ResolveIP("2001:0DB8::").IsRFC3849());
BOOST_CHECK(ResolveIP("169.254.1.1").IsRFC3927());
BOOST_CHECK(ResolveIP("2002::1").IsRFC3964());
BOOST_CHECK(ResolveIP("FC00::").IsRFC4193());
BOOST_CHECK(ResolveIP("2001::2").IsRFC4380());
BOOST_CHECK(ResolveIP("2001:10::").IsRFC4843());
BOOST_CHECK(ResolveIP("FE80::").IsRFC4862());
BOOST_CHECK(ResolveIP("64:FF9B::").IsRFC6052());
BOOST_CHECK(ResolveIP("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").IsTor());
BOOST_CHECK(ResolveIP("127.0.0.1").IsLocal());
BOOST_CHECK(ResolveIP("::1").IsLocal());
BOOST_CHECK(ResolveIP("8.8.8.8").IsRoutable());
BOOST_CHECK(ResolveIP("2001::1").IsRoutable());
BOOST_CHECK(ResolveIP("127.0.0.1").IsValid());
}
bool static TestSplitHost(std::string test, std::string host, int port)
{
std::string hostOut;
int portOut = -1;
SplitHostPort(test, portOut, hostOut);
return hostOut == host && port == portOut;
}
BOOST_AUTO_TEST_CASE(netbase_splithost)
{
BOOST_CHECK(TestSplitHost("www.bitcoin.org", "www.bitcoin.org", -1));
BOOST_CHECK(TestSplitHost("[www.bitcoin.org]", "www.bitcoin.org", -1));
BOOST_CHECK(TestSplitHost("www.bitcoin.org:80", "www.bitcoin.org", 80));
BOOST_CHECK(TestSplitHost("[www.bitcoin.org]:80", "www.bitcoin.org", 80));
BOOST_CHECK(TestSplitHost("127.0.0.1", "127.0.0.1", -1));
BOOST_CHECK(TestSplitHost("127.0.0.1:13636", "127.0.0.1", 13636));
BOOST_CHECK(TestSplitHost("[127.0.0.1]", "127.0.0.1", -1));
BOOST_CHECK(TestSplitHost("[127.0.0.1]:13636", "127.0.0.1", 13636));
BOOST_CHECK(TestSplitHost("::ffff:127.0.0.1", "::ffff:127.0.0.1", -1));
BOOST_CHECK(TestSplitHost("[::ffff:127.0.0.1]:13636", "::ffff:127.0.0.1", 13636));
BOOST_CHECK(TestSplitHost("[::]:13636", "::", 13636));
BOOST_CHECK(TestSplitHost("::13636", "::13636", -1));
BOOST_CHECK(TestSplitHost(":13636", "", 13636));
BOOST_CHECK(TestSplitHost("[]:13636", "", 13636));
BOOST_CHECK(TestSplitHost("", "", -1));
}
bool static TestParse(std::string src, std::string canon)
{
CService addr(LookupNumeric(src.c_str(), 65535));
return canon == addr.ToString();
}
BOOST_AUTO_TEST_CASE(netbase_lookupnumeric)
{
BOOST_CHECK(TestParse("127.0.0.1", "127.0.0.1:65535"));
BOOST_CHECK(TestParse("127.0.0.1:13636", "127.0.0.1:13636"));
BOOST_CHECK(TestParse("::ffff:127.0.0.1", "127.0.0.1:65535"));
BOOST_CHECK(TestParse("::", "[::]:65535"));
BOOST_CHECK(TestParse("[::]:13636", "[::]:13636"));
BOOST_CHECK(TestParse("[127.0.0.1]", "127.0.0.1:65535"));
BOOST_CHECK(TestParse(":::", "[::]:0"));
}
BOOST_AUTO_TEST_CASE(onioncat_test)
{
// values from https://web.archive.org/web/20121122003543/http://www.cypherpunk.at/onioncat/wiki/OnionCat
CNetAddr addr1(ResolveIP("5wyqrzbvrdsumnok.onion"));
CNetAddr addr2(ResolveIP("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca"));
BOOST_CHECK(addr1 == addr2);
BOOST_CHECK(addr1.IsTor());
BOOST_CHECK(addr1.ToStringIP() == "5wyqrzbvrdsumnok.onion");
BOOST_CHECK(addr1.IsRoutable());
}
BOOST_AUTO_TEST_CASE(subnet_test)
{
BOOST_CHECK(ResolveSubNet("1.2.3.0/24") == ResolveSubNet("1.2.3.0/255.255.255.0"));
BOOST_CHECK(ResolveSubNet("1.2.3.0/24") != ResolveSubNet("1.2.4.0/255.255.255.0"));
BOOST_CHECK(ResolveSubNet("1.2.3.0/24").Match(ResolveIP("1.2.3.4")));
BOOST_CHECK(!ResolveSubNet("1.2.2.0/24").Match(ResolveIP("1.2.3.4")));
BOOST_CHECK(ResolveSubNet("1.2.3.4").Match(ResolveIP("1.2.3.4")));
BOOST_CHECK(ResolveSubNet("1.2.3.4/32").Match(ResolveIP("1.2.3.4")));
BOOST_CHECK(!ResolveSubNet("1.2.3.4").Match(ResolveIP("5.6.7.8")));
BOOST_CHECK(!ResolveSubNet("1.2.3.4/32").Match(ResolveIP("5.6.7.8")));
BOOST_CHECK(ResolveSubNet("::ffff:127.0.0.1").Match(ResolveIP("127.0.0.1")));
BOOST_CHECK(ResolveSubNet("1:2:3:4:5:6:7:8").Match(ResolveIP("1:2:3:4:5:6:7:8")));
BOOST_CHECK(!ResolveSubNet("1:2:3:4:5:6:7:8").Match(ResolveIP("1:2:3:4:5:6:7:9")));
BOOST_CHECK(ResolveSubNet("1:2:3:4:5:6:7:0/112").Match(ResolveIP("1:2:3:4:5:6:7:1234")));
BOOST_CHECK(ResolveSubNet("192.168.0.1/24").Match(ResolveIP("192.168.0.2")));
BOOST_CHECK(ResolveSubNet("192.168.0.20/29").Match(ResolveIP("192.168.0.18")));
BOOST_CHECK(ResolveSubNet("1.2.2.1/24").Match(ResolveIP("1.2.2.4")));
BOOST_CHECK(ResolveSubNet("1.2.2.110/31").Match(ResolveIP("1.2.2.111")));
BOOST_CHECK(ResolveSubNet("1.2.2.20/26").Match(ResolveIP("1.2.2.63")));
// All-Matching IPv6 Matches arbitrary IPv4 and IPv6
BOOST_CHECK(ResolveSubNet("::/0").Match(ResolveIP("1:2:3:4:5:6:7:1234")));
BOOST_CHECK(ResolveSubNet("::/0").Match(ResolveIP("1.2.3.4")));
// All-Matching IPv4 does not Match IPv6
BOOST_CHECK(!ResolveSubNet("0.0.0.0/0").Match(ResolveIP("1:2:3:4:5:6:7:1234")));
// Invalid subnets Match nothing (not even invalid addresses)
BOOST_CHECK(!CSubNet().Match(ResolveIP("1.2.3.4")));
BOOST_CHECK(!ResolveSubNet("").Match(ResolveIP("4.5.6.7")));
BOOST_CHECK(!ResolveSubNet("bloop").Match(ResolveIP("0.0.0.0")));
BOOST_CHECK(!ResolveSubNet("bloop").Match(ResolveIP("hab")));
// Check valid/invalid
BOOST_CHECK(ResolveSubNet("1.2.3.0/0").IsValid());
BOOST_CHECK(!ResolveSubNet("1.2.3.0/-1").IsValid());
BOOST_CHECK(ResolveSubNet("1.2.3.0/32").IsValid());
BOOST_CHECK(!ResolveSubNet("1.2.3.0/33").IsValid());
BOOST_CHECK(ResolveSubNet("1:2:3:4:5:6:7:8/0").IsValid());
BOOST_CHECK(ResolveSubNet("1:2:3:4:5:6:7:8/33").IsValid());
BOOST_CHECK(!ResolveSubNet("1:2:3:4:5:6:7:8/-1").IsValid());
BOOST_CHECK(ResolveSubNet("1:2:3:4:5:6:7:8/128").IsValid());
BOOST_CHECK(!ResolveSubNet("1:2:3:4:5:6:7:8/129").IsValid());
BOOST_CHECK(!ResolveSubNet("fuzzy").IsValid());
//CNetAddr constructor test
BOOST_CHECK(CSubNet(ResolveIP("127.0.0.1")).IsValid());
BOOST_CHECK(CSubNet(ResolveIP("127.0.0.1")).Match(ResolveIP("127.0.0.1")));
BOOST_CHECK(!CSubNet(ResolveIP("127.0.0.1")).Match(ResolveIP("127.0.0.2")));
BOOST_CHECK(CSubNet(ResolveIP("127.0.0.1")).ToString() == "127.0.0.1/32");
CSubNet subnet = CSubNet(ResolveIP("1.2.3.4"), 32);
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/32");
subnet = CSubNet(ResolveIP("1.2.3.4"), 8);
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/8");
subnet = CSubNet(ResolveIP("1.2.3.4"), 0);
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/0");
subnet = CSubNet(ResolveIP("1.2.3.4"), ResolveIP("255.255.255.255"));
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/32");
subnet = CSubNet(ResolveIP("1.2.3.4"), ResolveIP("255.0.0.0"));
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/8");
subnet = CSubNet(ResolveIP("1.2.3.4"), ResolveIP("0.0.0.0"));
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/0");
BOOST_CHECK(CSubNet(ResolveIP("1:2:3:4:5:6:7:8")).IsValid());
BOOST_CHECK(CSubNet(ResolveIP("1:2:3:4:5:6:7:8")).Match(ResolveIP("1:2:3:4:5:6:7:8")));
BOOST_CHECK(!CSubNet(ResolveIP("1:2:3:4:5:6:7:8")).Match(ResolveIP("1:2:3:4:5:6:7:9")));
BOOST_CHECK(CSubNet(ResolveIP("1:2:3:4:5:6:7:8")).ToString() == "1:2:3:4:5:6:7:8/128");
subnet = ResolveSubNet("1.2.3.4/255.255.255.255");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/32");
subnet = ResolveSubNet("1.2.3.4/255.255.255.254");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/31");
subnet = ResolveSubNet("1.2.3.4/255.255.255.252");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/30");
subnet = ResolveSubNet("1.2.3.4/255.255.255.248");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/29");
subnet = ResolveSubNet("1.2.3.4/255.255.255.240");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/28");
subnet = ResolveSubNet("1.2.3.4/255.255.255.224");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/27");
subnet = ResolveSubNet("1.2.3.4/255.255.255.192");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/26");
subnet = ResolveSubNet("1.2.3.4/255.255.255.128");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/25");
subnet = ResolveSubNet("1.2.3.4/255.255.255.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/24");
subnet = ResolveSubNet("1.2.3.4/255.255.254.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.2.0/23");
subnet = ResolveSubNet("1.2.3.4/255.255.252.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/22");
subnet = ResolveSubNet("1.2.3.4/255.255.248.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/21");
subnet = ResolveSubNet("1.2.3.4/255.255.240.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/20");
subnet = ResolveSubNet("1.2.3.4/255.255.224.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/19");
subnet = ResolveSubNet("1.2.3.4/255.255.192.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/18");
subnet = ResolveSubNet("1.2.3.4/255.255.128.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/17");
subnet = ResolveSubNet("1.2.3.4/255.255.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/16");
subnet = ResolveSubNet("1.2.3.4/255.254.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/15");
subnet = ResolveSubNet("1.2.3.4/255.252.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/14");
subnet = ResolveSubNet("1.2.3.4/255.248.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/13");
subnet = ResolveSubNet("1.2.3.4/255.240.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/12");
subnet = ResolveSubNet("1.2.3.4/255.224.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/11");
subnet = ResolveSubNet("1.2.3.4/255.192.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/10");
subnet = ResolveSubNet("1.2.3.4/255.128.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/9");
subnet = ResolveSubNet("1.2.3.4/255.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/8");
subnet = ResolveSubNet("1.2.3.4/254.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/7");
subnet = ResolveSubNet("1.2.3.4/252.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/6");
subnet = ResolveSubNet("1.2.3.4/248.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/5");
subnet = ResolveSubNet("1.2.3.4/240.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/4");
subnet = ResolveSubNet("1.2.3.4/224.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/3");
subnet = ResolveSubNet("1.2.3.4/192.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/2");
subnet = ResolveSubNet("1.2.3.4/128.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/1");
subnet = ResolveSubNet("1.2.3.4/0.0.0.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/0");
subnet = ResolveSubNet("1:2:3:4:5:6:7:8/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff");
BOOST_CHECK_EQUAL(subnet.ToString(), "1:2:3:4:5:6:7:8/128");
subnet = ResolveSubNet("1:2:3:4:5:6:7:8/ffff:0000:0000:0000:0000:0000:0000:0000");
BOOST_CHECK_EQUAL(subnet.ToString(), "1::/16");
subnet = ResolveSubNet("1:2:3:4:5:6:7:8/0000:0000:0000:0000:0000:0000:0000:0000");
BOOST_CHECK_EQUAL(subnet.ToString(), "::/0");
subnet = ResolveSubNet("1.2.3.4/255.255.232.0");
BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/255.255.232.0");
subnet = ResolveSubNet("1:2:3:4:5:6:7:8/ffff:ffff:ffff:fffe:ffff:ffff:ffff:ff0f");
BOOST_CHECK_EQUAL(subnet.ToString(), "1:2:3:4:5:6:7:8/ffff:ffff:ffff:fffe:ffff:ffff:ffff:ff0f");
}
BOOST_AUTO_TEST_CASE(netbase_getgroup)
{
BOOST_CHECK(ResolveIP("127.0.0.1").GetGroup() == boost::assign::list_of(0)); // Local -> !Routable()
BOOST_CHECK(ResolveIP("257.0.0.1").GetGroup() == boost::assign::list_of(0)); // !Valid -> !Routable()
BOOST_CHECK(ResolveIP("10.0.0.1").GetGroup() == boost::assign::list_of(0)); // RFC1918 -> !Routable()
BOOST_CHECK(ResolveIP("169.254.1.1").GetGroup() == boost::assign::list_of(0)); // RFC3927 -> !Routable()
BOOST_CHECK(ResolveIP("1.2.3.4").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); // IPv4
BOOST_CHECK(ResolveIP("::FFFF:0:102:304").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); // RFC6145
BOOST_CHECK(ResolveIP("64:FF9B::102:304").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); // RFC6052
BOOST_CHECK(ResolveIP("2002:102:304:9999:9999:9999:9999:9999").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); // RFC3964
BOOST_CHECK(ResolveIP("2001:0:9999:9999:9999:9999:FEFD:FCFB").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV4)(1)(2)); // RFC4380
BOOST_CHECK(ResolveIP("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").GetGroup() == boost::assign::list_of((unsigned char)NET_TOR)(239)); // Tor
BOOST_CHECK(ResolveIP("2001:470:abcd:9999:9999:9999:9999:9999").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV6)(32)(1)(4)(112)(175)); //he.net
BOOST_CHECK(ResolveIP("2001:2001:9999:9999:9999:9999:9999:9999").GetGroup() == boost::assign::list_of((unsigned char)NET_IPV6)(32)(1)(32)(1)); //IPv6
}
BOOST_AUTO_TEST_SUITE_END()
| [
"hawkkithub@gmail.com"
] | hawkkithub@gmail.com |
ee6cf7a54991a1adc1dcdc09c69607b2e60bc53e | fc880c58005973b1eb6bd48a57bc399b41faf3f3 | /Creational/Factory Method/Factory Method/FictionBook.cpp | d36f2e7f09ad4383038b0a3b99d7ca5d5957a005 | [
"MIT"
] | permissive | septimomend/DesignPatterns-empl | 0e6e4645e233889bee33506de852ae12b55b3e59 | 327b8bd0a40d814802d4c92944c07ecbb1822e2e | refs/heads/master | 2021-09-06T16:05:21.829690 | 2018-02-08T10:17:08 | 2018-02-08T10:17:08 | 104,627,720 | 2 | 1 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 574 | cpp | // 2017 © Chapkailo Ivan (septimomend) / MIT License
// You can copy, use and share examples of this code. But do not post it and do not report it as your own.
#include "stdafx.h"
#include "FictionBook.h"
FictionBook::FictionBook()
{
}
FictionBook::~FictionBook()
{
}
void FictionBook::readBook()
{
cout << "You are reading the fiction book." << endl;
}
void FictionBook::buyBook()
{
cout << "You bought the fiction book. And now you are bankrupting." << endl;
}
void FictionBook::bookName()
{
cout << "The fiction book \"Wolves\" by Kapusnyakovskiy." << endl;
} | [
"chapkailo.ivan@gmail.com"
] | chapkailo.ivan@gmail.com |
ee04c028144a94441eafe28c7eae9aaac53fbde8 | 382164d6719a17bbbfcc0f5fc54537bfc865707c | /influxdb_dht_moisture/influxdb_dht_moisture.ino | b9c9fdc6ba94a6379032ab9c0861fc82d971dc6a | [] | no_license | strmark/arduino | c75b4f420425d6219ebeff525a6eace8bbf526fa | 9d41d1deff0f4430c817a589cd18c0c16d604330 | refs/heads/main | 2023-07-31T09:19:01.590814 | 2021-09-17T20:06:37 | 2021-09-17T20:06:37 | 389,396,677 | 0 | 0 | null | 2021-09-17T20:06:38 | 2021-07-25T16:49:57 | C++ | UTF-8 | C++ | false | false | 2,847 | ino | #include <ESP8266WiFiMulti.h>
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>
#include "DHTesp.h"
#include <arduino_wifi_secrets.h>
#include <arduino_influxdb_secrets.h>
#define TZ_INFO "CET-1CEST,M3.5.0,M10.5.0/3"
// Digital pin connected to the DHT sensor
#define DHTPIN D3
#define DHTSWITCH D2
#define MOISTPIN A0
#define MOISTSWITCH D5
// adjust value while testing the sensor
static const int dry_sensor = 721;
static const int wet_sensor = 296;
ESP8266WiFiMulti wifiMulti;
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
Point sensor("DHT_MOISTURE");
DHTesp dht;
void setup() {
Serial.begin(115200);
// Setup wifi
WiFi.mode(WIFI_STA);
wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to wifi");
while (wifiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(100);
}
Serial.println();
pinMode(DHTSWITCH, OUTPUT);
pinMode(MOISTSWITCH, OUTPUT);
dht.setup(DHTPIN, DHTesp::DHT11);
timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov");
if (client.validateConnection()) {
Serial.print("Connected to InfluxDB: ");
Serial.println(client.getServerUrl());
} else {
Serial.print("InfluxDB connection failed: ");
Serial.println(client.getLastErrorMessage());
}
}
void getTemperatureData() {
digitalWrite(DHTSWITCH, HIGH);
// bug in de DHT11 sampling samplingPeriod * 2
delay(dht.getMinimumSamplingPeriod() * 2);
float humidity = dht.getHumidity();
float temperature = dht.getTemperature();
String statusSensor = dht.getStatusString();
Serial.printf("Status: %s \n", statusSensor);
Serial.printf("Humidity: %f \n", humidity);
Serial.printf("Temperature: %f \n", temperature);
sensor.addField("statusTemp", statusSensor);
sensor.addField("humidity", humidity);
sensor.addField("temperature", temperature);
digitalWrite(DHTSWITCH, LOW);
}
void getMoistureData() {
digitalWrite(MOISTSWITCH, HIGH);
delay(1000);
int moisture = analogRead(MOISTPIN);
Serial.printf("Moisture: %i \n", moisture);
int percentageHumidity = map(moisture, wet_sensor, dry_sensor, 100, 0);
sensor.addField("moisture", moisture);
sensor.addField("percentage", percentageHumidity);
digitalWrite(MOISTSWITCH, LOW);
}
void loop() {
sensor.clearFields();
getTemperatureData();
getMoistureData();
Serial.print("Writing: ");
Serial.println(sensor.toLineProtocol());
if (!client.writePoint(sensor)) {
Serial.print("InfluxDB write failed: ");
Serial.println(client.getLastErrorMessage());
}
Serial.println("Wait....");
delay(60 * 60 * 1000);
}
| [
"strmark@hotmail.com"
] | strmark@hotmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.