hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
11e16ae95944f217abbf49a85be73cd7d74d783f | 5,878 | hpp | C++ | include/caffe/parallel.hpp | matex-org/caffe-intel | 8435dc0803542d2b0a5524c3a3c7d2ea9f99da1c | [
"Intel",
"BSD-2-Clause"
] | 1 | 2019-08-16T13:09:38.000Z | 2019-08-16T13:09:38.000Z | include/caffe/parallel.hpp | matex-org/caffe-intel | 8435dc0803542d2b0a5524c3a3c7d2ea9f99da1c | [
"Intel",
"BSD-2-Clause"
] | null | null | null | include/caffe/parallel.hpp | matex-org/caffe-intel | 8435dc0803542d2b0a5524c3a3c7d2ea9f99da1c | [
"Intel",
"BSD-2-Clause"
] | null | null | null | /*
All modification made by Intel Corporation: © 2016 Intel Corporation
All contributions by the University of California:
Copyright (c) 2014, 2015, The Regents of the University of California (Regents)
All rights reserved.
All other contributions:
Copyright (c) 2014, 2015, the respective contributors
All rights reserved.
For the list of contributors go to https://github.com/BVLC/caffe/blob/master/CONTRIBUTORS.md
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 Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CAFFE_PARALLEL_HPP_
#define CAFFE_PARALLEL_HPP_
#include <boost/date_time/posix_time/posix_time.hpp>
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/internal_thread.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/solver.hpp"
#include "caffe/syncedmem.hpp"
#include "caffe/util/blocking_queue.hpp"
namespace caffe {
enum Op {
copy,
replace_cpu,
replace_gpu,
replace_cpu_diff,
replace_gpu_diff
};
template<typename Dtype>
static void apply_buffers(const vector<Blob<Dtype>*>& blobs,
Dtype* buffer, size_t total_size, Op op) {
Dtype* ptr = buffer;
for (int i = 0; i < blobs.size(); ++i) {
int size = blobs[i]->count();
switch (op) {
case copy: {
// Init buffer to current values of blobs
caffe_copy(size,
reinterpret_cast<const Dtype*>(blobs[i]->data()->cpu_data()),
ptr);
break;
}
case replace_cpu:
blobs[i]->data()->set_cpu_data(ptr);
break;
case replace_gpu:
blobs[i]->data()->set_gpu_data(ptr);
break;
case replace_cpu_diff:
blobs[i]->diff()->set_cpu_data(ptr);
break;
case replace_gpu_diff:
blobs[i]->diff()->set_gpu_data(ptr);
break;
}
ptr += size;
}
// total_size is at least one byte
CHECK_EQ(total_size, (ptr == buffer ? 1 : ptr - buffer));
}
// Represents a net parameters. Once a net is created, its parameter buffers can
// be replaced by ones from Params, to allow parallelization. Params ensures
// parameters are allocated in one consecutive array.
template<typename Dtype>
class Params {
public:
explicit Params(shared_ptr<Solver<Dtype> > root_solver);
virtual ~Params() {
}
inline size_t size() const {
return size_;
}
inline Dtype* data() const {
return data_;
}
inline Dtype* diff() const {
return diff_;
}
protected:
const size_t size_; // Size of buffers
Dtype* data_; // Network parameters
Dtype* diff_; // Gradient
DISABLE_COPY_AND_ASSIGN(Params);
};
// Params stored in GPU memory.
template<typename Dtype>
class GPUParams : public Params<Dtype> {
public:
GPUParams(shared_ptr<Solver<Dtype> > root_solver, int device);
virtual ~GPUParams();
void configure(Solver<Dtype>* solver) const;
protected:
using Params<Dtype>::size_;
using Params<Dtype>::data_;
using Params<Dtype>::diff_;
};
class DevicePair {
public:
DevicePair(int parent, int device)
: parent_(parent),
device_(device) {
}
inline int parent() {
return parent_;
}
inline int device() {
return device_;
}
// Group GPUs in pairs, by proximity depending on machine's topology
static void compute(const vector<int> devices, vector<DevicePair>* pairs);
protected:
int parent_;
int device_;
};
// Synchronous data parallelism using map-reduce between local GPUs.
template<typename Dtype>
class P2PSync : public GPUParams<Dtype>, public Solver<Dtype>::Callback,
public InternalThread {
public:
explicit P2PSync(shared_ptr<Solver<Dtype> > root_solver,
P2PSync<Dtype>* parent, const SolverParameter& param);
virtual ~P2PSync();
inline const shared_ptr<Solver<Dtype> >& solver() const {
return solver_;
}
void Run(const vector<int>& gpus);
void Prepare(const vector<int>& gpus,
vector<shared_ptr<P2PSync<Dtype> > >* syncs);
inline const int initial_iter() const { return initial_iter_; }
protected:
void on_start();
void on_gradients_ready();
void InternalThreadEntry();
P2PSync<Dtype>* parent_;
vector<P2PSync<Dtype>*> children_;
BlockingQueue<P2PSync<Dtype>*> queue_;
const int initial_iter_;
Dtype* parent_grads_;
shared_ptr<Solver<Dtype> > solver_;
using Params<Dtype>::size_;
using Params<Dtype>::data_;
using Params<Dtype>::diff_;
};
} // namespace caffe
#endif
| 29.39 | 92 | 0.705682 | [
"vector"
] |
11e20d854b85b4dcabe435997c752fa64d86c01a | 4,187 | cpp | C++ | Code/Editor/TrackView/TimeRangeKeyUIControls.cpp | LB-KatarzynaDylska/o3de | d8d273697ea8e1beeb698f62b84904a192b0ab76 | [
"Apache-2.0",
"MIT"
] | 1 | 2022-03-28T08:06:58.000Z | 2022-03-28T08:06:58.000Z | Code/Editor/TrackView/TimeRangeKeyUIControls.cpp | LB-KatarzynaDylska/o3de | d8d273697ea8e1beeb698f62b84904a192b0ab76 | [
"Apache-2.0",
"MIT"
] | null | null | null | Code/Editor/TrackView/TimeRangeKeyUIControls.cpp | LB-KatarzynaDylska/o3de | d8d273697ea8e1beeb698f62b84904a192b0ab76 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "EditorDefs.h"
// CryCommon
#include <CryCommon/Maestro/Types/AnimParamType.h> // for AnimParamType
// Editor
#include "TrackViewKeyPropertiesDlg.h" // for CTrackViewKeyUIControls// Editor
//////////////////////////////////////////////////////////////////////////
class CTimeRangeKeyUIControls
: public CTrackViewKeyUIControls
{
public:
CSmartVariableArray mv_table;
CSmartVariable<float> mv_startTime;
CSmartVariable<float> mv_endTime;
CSmartVariable<float> mv_timeScale;
CSmartVariable<bool> mv_bLoop;
void OnCreateVars() override
{
AddVariable(mv_table, "Key Properties");
AddVariable(mv_table, mv_startTime, "Start Time");
AddVariable(mv_table, mv_endTime, "End Time");
AddVariable(mv_table, mv_timeScale, "Time Scale");
AddVariable(mv_table, mv_bLoop, "Loop");
mv_timeScale->SetLimits(0.001f, 100.f);
}
bool SupportTrackType(const CAnimParamType& paramType, [[maybe_unused]] EAnimCurveType trackType, [[maybe_unused]] AnimValueType valueType) const override
{
return paramType == AnimParamType::TimeRanges;
}
bool OnKeySelectionChange(CTrackViewKeyBundle& selectedKeys) override;
void OnUIChange(IVariable* pVar, CTrackViewKeyBundle& selectedKeys) override;
unsigned int GetPriority() const override { return 1; }
static const GUID& GetClassID()
{
// {E977A6F4-CEC1-4c67-8735-28721B3F6FEF}
static const GUID guid = {
0xe977a6f4, 0xcec1, 0x4c67, { 0x87, 0x35, 0x28, 0x72, 0x1b, 0x3f, 0x6f, 0xef }
};
return guid;
}
};
//////////////////////////////////////////////////////////////////////////
bool CTimeRangeKeyUIControls::OnKeySelectionChange(CTrackViewKeyBundle& selectedKeys)
{
if (!selectedKeys.AreAllKeysOfSameType())
{
return false;
}
bool bAssigned = false;
if (selectedKeys.GetKeyCount() == 1)
{
const CTrackViewKeyHandle& keyHandle = selectedKeys.GetKey(0);
CAnimParamType paramType = keyHandle.GetTrack()->GetParameterType();
if (paramType == AnimParamType::TimeRanges)
{
ICharacterKey timeRangeKey;
keyHandle.GetKey(&timeRangeKey);
mv_endTime = timeRangeKey.m_endTime;
mv_startTime = timeRangeKey.m_startTime;
mv_timeScale = timeRangeKey.m_speed;
mv_bLoop = timeRangeKey.m_bLoop;
bAssigned = true;
}
}
return bAssigned;
}
// Called when UI variable changes.
void CTimeRangeKeyUIControls::OnUIChange(IVariable* pVar, CTrackViewKeyBundle& selectedKeys)
{
CTrackViewSequence* pSequence = GetIEditor()->GetAnimation()->GetSequence();
if (!pSequence || !selectedKeys.AreAllKeysOfSameType())
{
return;
}
for (unsigned int keyIndex = 0, num = (int)selectedKeys.GetKeyCount(); keyIndex < num; keyIndex++)
{
CTrackViewKeyHandle keyHandle = selectedKeys.GetKey(keyIndex);
CAnimParamType paramType = keyHandle.GetTrack()->GetParameterType();
if (paramType == AnimParamType::TimeRanges)
{
ITimeRangeKey timeRangeKey;
keyHandle.GetKey(&timeRangeKey);
SyncValue(mv_startTime, timeRangeKey.m_startTime, false, pVar);
SyncValue(mv_endTime, timeRangeKey.m_endTime, false, pVar);
SyncValue(mv_timeScale, timeRangeKey.m_speed, false, pVar);
SyncValue(mv_bLoop, timeRangeKey.m_bLoop, false, pVar);
// Clamp values
if (!timeRangeKey.m_bLoop)
{
timeRangeKey.m_endTime = std::min(timeRangeKey.m_duration, timeRangeKey.m_endTime);
}
timeRangeKey.m_startTime = std::min(timeRangeKey.m_duration, timeRangeKey.m_startTime);
timeRangeKey.m_startTime = std::min(timeRangeKey.m_endTime, timeRangeKey.m_startTime);
keyHandle.SetKey(&timeRangeKey);
}
}
}
| 33.496 | 158 | 0.646047 | [
"3d"
] |
11e4d2749fa6435bb65118f58bde8ea4e0886c12 | 1,036 | cpp | C++ | Algorithm/Sorting/Heap sort.cpp | Leoyuseu/Code | 34edfbbfb7875b3ed06de393c192c1f13a5074f4 | [
"BSD-Source-Code"
] | null | null | null | Algorithm/Sorting/Heap sort.cpp | Leoyuseu/Code | 34edfbbfb7875b3ed06de393c192c1f13a5074f4 | [
"BSD-Source-Code"
] | null | null | null | Algorithm/Sorting/Heap sort.cpp | Leoyuseu/Code | 34edfbbfb7875b3ed06de393c192c1f13a5074f4 | [
"BSD-Source-Code"
] | null | null | null | #include <iostream>
#include <vector>
//#include <algorithm> //swap
using namespace std;
void show(const vector<int> &ivec){
for(auto it = ivec.begin() + 1; it !=ivec.end(); ++it){
cout << *it <<" ";
}
cout << endl;
}
void heapAdjust(vector<int> &ivec, int pos, int end){ //调整堆
int posnum = ivec[pos];
for(int j = 2 * pos; j <= end; j *= 2){
if(j < end && ivec[j] < ivec[j+1]){ //沿着值较大的孩子节点向下筛选,下沉
++j; //j为值较大的记录的下标
}
if(posnum >= ivec[j]){
break; //posnum应插入在更新之后的位置pos上
}
ivec[pos] = ivec[j];
pos = j;
}
ivec[pos] = posnum; //插入原来pos位置的数字
}
void heapsort(vector<int> &ivec){
for(int i = ivec.size() / 2; i > 0; --i){
heapAdjust(ivec ,i, ivec.size()-1); //建立最大堆,让每个节点都是堆,因为大于n/2的点都是叶子节点,已是堆
show(ivec);
}
cout<<endl;
for(int i = ivec.size() - 1; i > 1; --i){
swap(ivec[1], ivec[i]);
heapAdjust(ivec, 1, i - 1); //调整无序区
show(ivec);
}
}
int main(){
vector<int> ivec = {0 ,2, 7, 5, 9, 1, 4, 6, 3 ,8}; //0占第0位作用,
//如果从0开始存储数据,则左右孩子分别为2*i+1和2*i+2
heapsort(ivec);
}
| 22.521739 | 76 | 0.565637 | [
"vector"
] |
11e5323d0b7e866ade245c09813738a416ea6299 | 6,201 | cpp | C++ | DemoFramework/FslBase/source/FslBase/Math/Ray.cpp | alejandrolozano2/OpenGL_DemoFramework | 5fd85f05c98cc3d0c0a68bac438035df8cabaee7 | [
"MIT",
"BSD-3-Clause"
] | 3 | 2019-01-19T20:21:24.000Z | 2021-08-10T02:11:32.000Z | DemoFramework/FslBase/source/FslBase/Math/Ray.cpp | alejandrolozano2/OpenGL_DemoFramework | 5fd85f05c98cc3d0c0a68bac438035df8cabaee7 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | DemoFramework/FslBase/source/FslBase/Math/Ray.cpp | alejandrolozano2/OpenGL_DemoFramework | 5fd85f05c98cc3d0c0a68bac438035df8cabaee7 | [
"MIT",
"BSD-3-Clause"
] | 1 | 2021-08-10T02:11:33.000Z | 2021-08-10T02:11:33.000Z | /*
MIT License
Copyright (C) 2006 The Mono.Xna Team
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// The functions in this file are a port of an MIT licensed library: MonoGame - Ray.cs.
#include <FslBase/Math/Ray.hpp>
#include <FslBase/Exceptions.hpp>
#include <FslBase/Math/BoundingBox.hpp>
#include <FslBase/Math/BoundingSphere.hpp>
#include <FslBase/Math/MathHelper.hpp>
#include <FslBase/Math/Plane.hpp>
#include <cassert>
#include <cmath>
#include <cstddef>
#include <limits>
namespace Fsl
{
// adapted from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
bool Ray::Intersects(const BoundingBox& box, float& rResult) const
{
const float Epsilon = 1e-6f;
bool hasMin = false;
bool hasMax = false;
float tMin = 0.0f;
float tMax = 0.0f;
if (std::abs(Direction.X) < Epsilon)
{
if (Position.X < box.Min.X || Position.X > box.Max.X)
{
rResult = 0.0f;
return false;
}
}
else
{
tMin = (box.Min.X - Position.X) / Direction.X;
tMax = (box.Max.X - Position.X) / Direction.X;
hasMin = true;
hasMax = true;
if (tMin > tMax)
{
auto temp = tMin;
tMin = tMax;
tMax = temp;
}
}
if (std::abs(Direction.Y) < Epsilon)
{
if (Position.Y < box.Min.Y || Position.Y > box.Max.Y)
{
rResult = 0.0f;
return false;
}
}
else
{
auto tMinY = (box.Min.Y - Position.Y) / Direction.Y;
auto tMaxY = (box.Max.Y - Position.Y) / Direction.Y;
if (tMinY > tMaxY)
{
auto temp = tMinY;
tMinY = tMaxY;
tMaxY = temp;
}
if ((hasMin && tMin > tMaxY) || (hasMax && tMinY > tMax))
{
rResult = 0.0f;
return false;
}
if (!hasMin || tMinY > tMin)
{
tMin = tMinY;
hasMin = true;
}
if (!hasMax || tMaxY < tMax)
{
tMax = tMaxY;
hasMax = true;
}
}
if (std::abs(Direction.Z) < Epsilon)
{
if (Position.Z < box.Min.Z || Position.Z > box.Max.Z)
{
rResult = 0.0f;
return false;
}
}
else
{
auto tMinZ = (box.Min.Z - Position.Z) / Direction.Z;
auto tMaxZ = (box.Max.Z - Position.Z) / Direction.Z;
if (tMinZ > tMaxZ)
{
auto temp = tMinZ;
tMinZ = tMaxZ;
tMaxZ = temp;
}
if ((hasMin && tMin > tMaxZ) || (hasMax && tMinZ > tMax))
{
rResult = 0.0f;
return false;
}
if (!hasMin || tMinZ > tMin)
{
tMin = tMinZ;
hasMin = true;
}
if (!hasMax || tMaxZ < tMax)
{
tMax = tMaxZ;
// Disabled since no one checks it below
//hasMax = true;
}
}
// having a positive tMin and a negative tMax means the ray is inside the box
// we expect the intersection distance to be 0 in that case
if ((hasMin && tMin < 0) && tMax > 0)
{
rResult = 0.0f;
return true;
}
// a negative tMin means that the intersection point is behind the ray's origin
// we discard these as not hitting the AABB
if (tMin < 0)
{
rResult = 0.0f;
return false;
}
rResult = tMin;
return true;
}
bool Ray::Intersects(const BoundingSphere& sphere, float& rResult) const
{
// Find the vector between where the ray starts the the sphere's center
Vector3 difference = sphere.Center - Position;
float differenceLengthSquared = difference.LengthSquared();
float sphereRadiusSquared = sphere.Radius * sphere.Radius;
float distanceAlongRay;
// If the distance between the ray start and the sphere's center is less than
// the radius of the sphere, it means we've intersected. N.B. checking the LengthSquared is faster.
if (differenceLengthSquared < sphereRadiusSquared)
{
rResult = 0.0f;
return true;
}
distanceAlongRay = Vector3::Dot(Direction, difference);
// If the ray is pointing away from the sphere then we don't ever intersect
if (distanceAlongRay < 0)
{
rResult = 0.0f;
return false;
}
// Next we kinda use Pythagoras to check if we are within the bounds of the sphere
// if x = radius of sphere
// if y = distance between ray position and sphere center
// if z = the distance we've traveled along the ray
// if x^2 + z^2 - y^2 < 0, we do not intersect
float dist = sphereRadiusSquared + distanceAlongRay * distanceAlongRay - differenceLengthSquared;
if (dist < 0)
{
rResult = 0.0f;
return false;
}
rResult = distanceAlongRay - std::sqrt(dist);
return true;
}
bool Ray::Intersects(const Plane& plane, float& rResult) const
{
auto den = Vector3::Dot(Direction, plane.Normal);
if (std::abs(den) < 0.00001f)
{
rResult = 0;
return false;
}
rResult = (-plane.D - Vector3::Dot(plane.Normal, Position)) / den;
if (rResult < 0.0f)
{
if (rResult < -0.00001f)
{
rResult = 0.0f;
return false;
}
rResult = 0.0f;
}
return true;
}
}
| 26.275424 | 129 | 0.609579 | [
"vector",
"3d"
] |
eb19b5e21dcf04f1c8828abe160fb67f52e835a2 | 16,321 | cpp | C++ | src/Libraries/ARB/ARBConfigMultiQ.cpp | dconnet/AgilityBook | 4804c79079d6109294a6d377fb6ebda70bcb30a1 | [
"MIT"
] | 1 | 2020-11-23T20:33:41.000Z | 2020-11-23T20:33:41.000Z | src/Libraries/ARB/ARBConfigMultiQ.cpp | dconnet/AgilityBook | 4804c79079d6109294a6d377fb6ebda70bcb30a1 | [
"MIT"
] | null | null | null | src/Libraries/ARB/ARBConfigMultiQ.cpp | dconnet/AgilityBook | 4804c79079d6109294a6d377fb6ebda70bcb30a1 | [
"MIT"
] | 3 | 2020-05-04T19:42:26.000Z | 2022-03-08T09:36:54.000Z | /*
* Copyright (c) David Connet. All Rights Reserved.
*
* License: See License.txt
*/
/**
* @file
* @brief The classes that make up the configuration information.
* @author David Connet
*
* Revision History
* 2009-09-13 Add support for wxWidgets 2.9, deprecate tstring.
* 2006-02-16 Cleaned up memory usage with smart pointers.
* 2005-07-15 Created.
*/
#include "stdafx.h"
#include "ARB/ARBConfigMultiQ.h"
#include "ARB/ARBAgilityRecordBook.h"
#include "ARB/ARBLocalization.h"
#include "ARBCommon/Element.h"
#include <algorithm>
#ifdef __WXMSW__
#include <wx/msw/msvcrt.h>
#endif
/////////////////////////////////////////////////////////////////////////////
namespace
{
class ARBConfigMultiQ_concrete : public ARBConfigMultiQ
{
public:
ARBConfigMultiQ_concrete()
{
}
ARBConfigMultiQ_concrete(ARBConfigMultiQ const& rhs)
: ARBConfigMultiQ(rhs)
{
}
};
}; // namespace
ARBConfigMultiQPtr ARBConfigMultiQ::New()
{
return std::make_shared<ARBConfigMultiQ_concrete>();
}
ARBConfigMultiQ::ARBConfigMultiQ()
: m_Name()
, m_ShortName()
, m_ValidFrom()
, m_ValidTo()
, m_Items()
{
}
ARBConfigMultiQ::ARBConfigMultiQ(ARBConfigMultiQ const& rhs)
: m_Name(rhs.m_Name)
, m_ShortName(rhs.m_ShortName)
, m_ValidFrom(rhs.m_ValidFrom)
, m_ValidTo(rhs.m_ValidTo)
, m_Items(rhs.m_Items)
{
}
ARBConfigMultiQ::ARBConfigMultiQ(ARBConfigMultiQ&& rhs)
: m_Name(std::move(rhs.m_Name))
, m_ShortName(std::move(rhs.m_ShortName))
, m_ValidFrom(std::move(rhs.m_ValidFrom))
, m_ValidTo(std::move(rhs.m_ValidTo))
, m_Items(std::move(rhs.m_Items))
{
}
ARBConfigMultiQ::~ARBConfigMultiQ()
{
}
ARBConfigMultiQPtr ARBConfigMultiQ::Clone() const
{
return std::make_shared<ARBConfigMultiQ_concrete>(*this);
}
ARBConfigMultiQ& ARBConfigMultiQ::operator=(ARBConfigMultiQ const& rhs)
{
if (this != &rhs)
{
m_Name = rhs.m_Name;
m_ShortName = rhs.m_ShortName;
m_ValidFrom = rhs.m_ValidFrom;
m_ValidTo = rhs.m_ValidTo;
m_Items = rhs.m_Items;
}
return *this;
}
ARBConfigMultiQ& ARBConfigMultiQ::operator=(ARBConfigMultiQ&& rhs)
{
if (this != &rhs)
{
m_Name = std::move(rhs.m_Name);
m_ShortName = std::move(rhs.m_ShortName);
m_ValidFrom = std::move(rhs.m_ValidFrom);
m_ValidTo = std::move(rhs.m_ValidTo);
m_Items = std::move(rhs.m_Items);
}
return *this;
}
bool ARBConfigMultiQ::operator==(ARBConfigMultiQ const& rhs) const
{
// clang-format off
return m_Name == rhs.m_Name
&& m_ShortName == rhs.m_ShortName
&& m_ValidFrom == rhs.m_ValidFrom
&& m_ValidTo == rhs.m_ValidTo
&& m_Items == rhs.m_Items;
// clang-format on
}
bool ARBConfigMultiQ::Load(
ARBConfigVenue const& inVenue,
ElementNodePtr const& inTree,
ARBVersion const& inVersion,
ARBErrorCallback& ioCallback)
{
assert(inTree);
if (!inTree || inTree->GetName() != TREE_MULTIQ)
return false;
if (ARBAttribLookup::Found != inTree->GetAttrib(ATTRIB_MULTIQ_NAME, m_Name))
{
ioCallback.LogMessage(Localization()->ErrorMissingAttribute(TREE_MULTIQ_ITEM, ATTRIB_MULTIQ_NAME));
return false;
}
if (ARBAttribLookup::Found != inTree->GetAttrib(ATTRIB_MULTIQ_SHORTNAME, m_ShortName))
{
ioCallback.LogMessage(Localization()->ErrorMissingAttribute(TREE_MULTIQ_ITEM, ATTRIB_MULTIQ_SHORTNAME));
return false;
}
if (ARBAttribLookup::Invalid == inTree->GetAttrib(ATTRIB_MULTIQ_VALID_FROM, m_ValidFrom))
{
std::wstring attrib;
inTree->GetAttrib(ATTRIB_MULTIQ_VALID_FROM, attrib);
std::wstring msg(Localization()->InvalidDate());
msg += attrib;
ioCallback.LogMessage(
Localization()->ErrorInvalidAttributeValue(TREE_MULTIQ, ATTRIB_MULTIQ_VALID_FROM, msg.c_str()));
return false;
}
if (ARBAttribLookup::Invalid == inTree->GetAttrib(ATTRIB_MULTIQ_VALID_TO, m_ValidTo))
{
std::wstring attrib;
inTree->GetAttrib(ATTRIB_MULTIQ_VALID_TO, attrib);
std::wstring msg(Localization()->InvalidDate());
msg += attrib;
ioCallback.LogMessage(
Localization()->ErrorInvalidAttributeValue(TREE_MULTIQ, ATTRIB_MULTIQ_VALID_TO, msg.c_str()));
return false;
}
for (int i = 0; i < inTree->GetElementCount(); ++i)
{
ElementNodePtr element = inTree->GetElementNode(i);
if (!element)
continue;
if (element->GetName() == TREE_MULTIQ_ITEM)
{
MultiQItem item;
// Read the data.
if (ARBAttribLookup::Found != element->GetAttrib(ATTRIB_MULTIQ_ITEM_DIV, item.m_Div)
|| 0 == item.m_Div.length())
{
ioCallback.LogMessage(Localization()->ErrorMissingAttribute(TREE_MULTIQ_ITEM, ATTRIB_MULTIQ_ITEM_DIV));
return false;
}
if (ARBAttribLookup::Found != element->GetAttrib(ATTRIB_MULTIQ_ITEM_LEVEL, item.m_Level)
|| 0 == item.m_Level.length())
{
ioCallback.LogMessage(
Localization()->ErrorMissingAttribute(TREE_MULTIQ_ITEM, ATTRIB_MULTIQ_ITEM_LEVEL));
return false;
}
if (ARBAttribLookup::Found != element->GetAttrib(ATTRIB_MULTIQ_ITEM_EVENT, item.m_Event)
|| 0 == item.m_Event.length())
{
ioCallback.LogMessage(
Localization()->ErrorMissingAttribute(TREE_MULTIQ_ITEM, ATTRIB_MULTIQ_ITEM_EVENT));
return false;
}
// Now verify it.
ARBConfigDivisionPtr pDiv;
if (!inVenue.GetDivisions().FindDivision(item.m_Div, &pDiv))
{
std::wstring msg(Localization()->InvalidDivName());
msg += item.m_Div;
ioCallback.LogMessage(
Localization()->ErrorInvalidAttributeValue(TREE_MULTIQ_ITEM, ATTRIB_MULTIQ_ITEM_DIV, msg.c_str()));
return false;
}
// Translate the sublevel to level.
ARBConfigLevelPtr pLevel;
if (!pDiv->GetLevels().FindSubLevel(item.m_Level, &pLevel))
{
std::wstring msg(Localization()->InvalidDivLevel());
msg += item.m_Div;
msg += L"/";
msg += item.m_Level;
ioCallback.LogMessage(Localization()->ErrorInvalidAttributeValue(
TREE_MULTIQ_ITEM,
ATTRIB_MULTIQ_ITEM_LEVEL,
msg.c_str()));
return false;
}
pDiv.reset();
std::wstring level = pLevel->GetName();
pLevel.reset();
// Now we can verify the event.
if (!inVenue.GetEvents().VerifyEvent(item.m_Event, item.m_Div, level, ARBDate()))
{
std::wstring msg(Localization()->InvalidEventName());
msg += item.m_Div;
msg += L"/";
msg += item.m_Level;
msg += L"/";
msg += item.m_Event;
ioCallback.LogMessage(Localization()->ErrorInvalidAttributeValue(
TREE_MULTIQ_ITEM,
ATTRIB_MULTIQ_ITEM_EVENT,
msg.c_str()));
return false;
}
m_Items.insert(item);
}
}
return true;
}
bool ARBConfigMultiQ::Save(ElementNodePtr const& ioTree) const
{
assert(ioTree);
if (!ioTree)
return false;
ElementNodePtr multiQ = ioTree->AddElementNode(TREE_MULTIQ);
multiQ->AddAttrib(ATTRIB_MULTIQ_NAME, m_Name);
multiQ->AddAttrib(ATTRIB_MULTIQ_SHORTNAME, m_ShortName);
if (m_ValidFrom.IsValid())
multiQ->AddAttrib(ATTRIB_MULTIQ_VALID_FROM, m_ValidFrom);
if (m_ValidTo.IsValid())
multiQ->AddAttrib(ATTRIB_MULTIQ_VALID_TO, m_ValidTo);
for (std::set<MultiQItem>::const_iterator iter = m_Items.begin(); iter != m_Items.end(); ++iter)
{
ElementNodePtr item = multiQ->AddElementNode(TREE_MULTIQ_ITEM);
item->AddAttrib(ATTRIB_MULTIQ_ITEM_DIV, (*iter).m_Div);
item->AddAttrib(ATTRIB_MULTIQ_ITEM_LEVEL, (*iter).m_Level);
item->AddAttrib(ATTRIB_MULTIQ_ITEM_EVENT, (*iter).m_Event);
}
return true;
}
// Note, this is only called from ARBDogTrial
bool ARBConfigMultiQ::Match(std::vector<ARBDogRunPtr> const& inRuns, std::vector<ARBDogRunPtr>& outRuns) const
{
outRuns.clear();
if (inRuns.size() < m_Items.size())
return false;
// One assumption we are making is that a given run can only match one
// multi-q definition.
std::vector<bool> bItems;
std::vector<ARBDogRunPtr> runs(inRuns);
bItems.insert(bItems.begin(), m_Items.size(), false);
for (std::vector<ARBDogRunPtr>::iterator iterR = runs.begin(); iterR != runs.end(); ++iterR)
{
if (m_ValidFrom.IsValid() && (*iterR)->GetDate() < m_ValidFrom)
continue;
if (m_ValidTo.IsValid() && (*iterR)->GetDate() > m_ValidTo)
continue;
int idx = 0;
for (std::set<MultiQItem>::const_iterator iter = m_Items.begin(); iter != m_Items.end(); ++idx, ++iter)
{
if ((*iter).m_Div == (*iterR)->GetDivision() && (*iter).m_Level == (*iterR)->GetLevel()
&& (*iter).m_Event == (*iterR)->GetEvent())
{
bItems[idx] = true;
}
}
}
size_t nMatch = 0;
for (std::vector<bool>::iterator iterB = bItems.begin(); iterB != bItems.end(); ++iterB)
if (*iterB)
++nMatch;
bool bOk = false;
if (nMatch == m_Items.size())
{
bOk = true;
for (std::vector<ARBDogRunPtr>::iterator iterR = runs.begin(); iterR != runs.end();)
{
bool bInc = true;
if (m_ValidFrom.IsValid() && (*iterR)->GetDate() < m_ValidFrom)
continue;
if (m_ValidTo.IsValid() && (*iterR)->GetDate() > m_ValidTo)
continue;
int idx = 0;
for (std::set<MultiQItem>::const_iterator iter = m_Items.begin(); iter != m_Items.end(); ++idx, ++iter)
{
if ((*iter).m_Div == (*iterR)->GetDivision() && (*iter).m_Level == (*iterR)->GetLevel()
&& (*iter).m_Event == (*iterR)->GetEvent())
{
bInc = false;
outRuns.push_back(*iterR);
iterR = runs.erase(iterR);
break;
}
}
if (bInc)
++iterR;
}
}
return bOk;
}
int ARBConfigMultiQ::RenameDivision(std::wstring const& inOldDiv, std::wstring const& inNewDiv)
{
if (inOldDiv == inNewDiv)
return 0;
int count = 0;
for (std::set<MultiQItem>::iterator iter = m_Items.begin(); iter != m_Items.end();)
{
if ((*iter).m_Div == inOldDiv)
{
MultiQItem item = *iter;
item.m_Div = inNewDiv;
m_Items.erase(iter);
m_Items.insert(item);
iter = m_Items.begin();
++count;
}
else
++iter;
}
return count;
}
int ARBConfigMultiQ::DeleteDivision(std::wstring const& inDiv)
{
int count = 0;
for (std::set<MultiQItem>::iterator iter = m_Items.begin(); iter != m_Items.end();)
{
if ((*iter).m_Div == inDiv)
{
++count;
#ifdef ARB_SET_ERASE_RETURNS_ITERATOR
iter = m_Items.erase(iter);
#else
m_Items.erase(iter++);
#endif
}
else
++iter;
}
return count;
}
int ARBConfigMultiQ::RenameLevel(
std::wstring const& inDiv,
std::wstring const& inOldLevel,
std::wstring const& inNewLevel)
{
if (inOldLevel == inNewLevel)
return 0;
int count = 0;
for (std::set<MultiQItem>::iterator iter = m_Items.begin(); iter != m_Items.end(); ++iter)
{
if ((*iter).m_Div == inDiv && (*iter).m_Level == inOldLevel)
{
MultiQItem item = *iter;
item.m_Level = inNewLevel;
m_Items.erase(iter);
m_Items.insert(item);
iter = m_Items.begin();
++count;
}
}
return count;
}
int ARBConfigMultiQ::DeleteLevel(std::wstring const& inLevel)
{
int count = 0;
for (std::set<MultiQItem>::iterator iter = m_Items.begin(); iter != m_Items.end();)
{
if ((*iter).m_Level == inLevel)
{
++count;
#ifdef ARB_SET_ERASE_RETURNS_ITERATOR
iter = m_Items.erase(iter);
#else
m_Items.erase(iter++);
#endif
}
else
++iter;
}
return count;
}
int ARBConfigMultiQ::RenameEvent(std::wstring const& inOldEvent, std::wstring const& inNewEvent)
{
if (inOldEvent == inNewEvent)
return 0;
int count = 0;
for (std::set<MultiQItem>::iterator iter = m_Items.begin(); iter != m_Items.end(); ++iter)
{
if ((*iter).m_Event == inOldEvent)
{
MultiQItem item = *iter;
item.m_Event = inNewEvent;
m_Items.erase(iter);
m_Items.insert(item);
iter = m_Items.begin();
++count;
}
}
return count;
}
int ARBConfigMultiQ::DeleteEvent(std::wstring const& inEvent)
{
int count = 0;
for (std::set<MultiQItem>::iterator iter = m_Items.begin(); iter != m_Items.end();)
{
if ((*iter).m_Event == inEvent)
{
++count;
#ifdef ARB_SET_ERASE_RETURNS_ITERATOR
iter = m_Items.erase(iter);
#else
m_Items.erase(iter++);
#endif
}
else
++iter;
}
return count;
}
bool ARBConfigMultiQ::AddItem(std::wstring const& inDiv, std::wstring const& inLevel, std::wstring const& inEvent)
{
bool bInserted = false;
if (0 < inDiv.length() && 0 < inLevel.length() && 0 < inEvent.length())
{
MultiQItem item;
item.m_Div = inDiv;
item.m_Level = inLevel;
item.m_Event = inEvent;
bInserted = m_Items.insert(item).second;
}
return bInserted;
}
bool ARBConfigMultiQ::RemoveItem(std::wstring const& inDiv, std::wstring const& inLevel, std::wstring const& inEvent)
{
bool bRemoved = false;
if (0 < inDiv.length() && 0 < inLevel.length() && 0 < inEvent.length())
{
MultiQItem item;
item.m_Div = inDiv;
item.m_Level = inLevel;
item.m_Event = inEvent;
std::set<MultiQItem>::iterator iter = std::find(m_Items.begin(), m_Items.end(), item);
if (iter != m_Items.end())
{
bRemoved = true;
m_Items.erase(iter);
}
}
return bRemoved;
}
bool ARBConfigMultiQ::RemoveAllItems()
{
if (0 < m_Items.size())
{
m_Items.clear();
return true;
}
else
return false;
}
bool ARBConfigMultiQ::GetItem(size_t inIndex, std::wstring& outDivision, std::wstring& outLevel, std::wstring& outEvent)
const
{
if (inIndex >= m_Items.size())
return false;
std::set<MultiQItem>::const_iterator iter = m_Items.begin();
size_t n = 0;
for (; n < inIndex && iter != m_Items.end(); ++n, ++iter)
;
if (iter == m_Items.end())
return false;
outDivision = (*iter).m_Div;
outLevel = (*iter).m_Level;
outEvent = (*iter).m_Event;
return true;
}
/////////////////////////////////////////////////////////////////////////////
bool ARBConfigMultiQList::Load(
ARBConfigVenue const& inVenue,
ElementNodePtr const& inTree,
ARBVersion const& inVersion,
ARBErrorCallback& ioCallback)
{
ARBConfigMultiQPtr thing(ARBConfigMultiQ::New());
if (!thing->Load(inVenue, inTree, inVersion, ioCallback))
return false;
push_back(thing);
return true;
}
bool ARBConfigMultiQList::FindMultiQ(std::wstring const& inName, bool inUseShortName, ARBConfigMultiQPtr* outMultiQ)
const
{
if (outMultiQ)
outMultiQ->reset();
for (const_iterator iter = begin(); iter != end(); ++iter)
{
if ((!inUseShortName && *iter && (*iter)->GetName() == inName)
|| (inUseShortName && *iter && (*iter)->GetShortName() == inName))
{
if (outMultiQ)
*outMultiQ = *iter;
return true;
}
}
return false;
}
bool ARBConfigMultiQList::FindMultiQ(ARBConfigMultiQ const& inMultiQ, ARBConfigMultiQPtr* outMultiQ) const
{
if (outMultiQ)
outMultiQ->reset();
for (const_iterator iter = begin(); iter != end(); ++iter)
{
if (*iter && *(*iter) == inMultiQ)
{
if (outMultiQ)
*outMultiQ = *iter;
return true;
}
}
return false;
}
int ARBConfigMultiQList::RenameDivision(std::wstring const& inOldDiv, std::wstring const& inNewDiv)
{
if (inOldDiv == inNewDiv)
return 0;
int count = 0;
for (iterator iter = begin(); iter != end(); ++iter)
{
count += (*iter)->RenameDivision(inOldDiv, inNewDiv);
}
return count;
}
int ARBConfigMultiQList::DeleteDivision(std::wstring const& inDiv)
{
int count = 0;
for (iterator iter = begin(); iter != end(); ++iter)
{
count += (*iter)->DeleteDivision(inDiv);
}
return count;
}
int ARBConfigMultiQList::RenameLevel(
std::wstring const& inDiv,
std::wstring const& inOldLevel,
std::wstring const& inNewLevel)
{
if (inOldLevel == inNewLevel)
return 0;
int count = 0;
for (iterator iter = begin(); iter != end(); ++iter)
{
count += (*iter)->RenameLevel(inDiv, inOldLevel, inNewLevel);
}
return count;
}
int ARBConfigMultiQList::DeleteLevel(std::wstring const& inLevel)
{
int count = 0;
for (iterator iter = begin(); iter != end(); ++iter)
{
count += (*iter)->DeleteLevel(inLevel);
}
return count;
}
int ARBConfigMultiQList::RenameEvent(std::wstring const& inOldEvent, std::wstring const& inNewEvent)
{
if (inOldEvent == inNewEvent)
return 0;
int count = 0;
for (iterator iter = begin(); iter != end(); ++iter)
{
count += (*iter)->RenameEvent(inOldEvent, inNewEvent);
}
return count;
}
int ARBConfigMultiQList::DeleteEvent(std::wstring const& inEvent)
{
int count = 0;
for (iterator iter = begin(); iter != end(); ++iter)
{
count += (*iter)->DeleteEvent(inEvent);
}
return count;
}
bool ARBConfigMultiQList::AddMultiQ(ARBConfigMultiQPtr const& inMultiQ)
{
if (!inMultiQ || FindMultiQ(*inMultiQ))
return false;
push_back(inMultiQ);
return true;
}
bool ARBConfigMultiQList::DeleteMultiQ(ARBConfigMultiQPtr const& inMultiQ)
{
if (inMultiQ)
{
for (iterator iter = begin(); iter != end(); ++iter)
{
if (*(*iter) == *inMultiQ)
{
erase(iter);
return true;
}
}
}
return false;
}
| 23.687954 | 120 | 0.674775 | [
"vector"
] |
eb1a570d3933be9bda5c9c06d7d05f21da49801d | 2,392 | cpp | C++ | esercizi_prove/esercizi_seconda_intercorso/chef_wedding.cpp | AntonioEmmanuele/asd_homework_esercizi | 7eaad2ae78f0ada90d1c6264cd02a05f26c31941 | [
"Apache-2.0"
] | null | null | null | esercizi_prove/esercizi_seconda_intercorso/chef_wedding.cpp | AntonioEmmanuele/asd_homework_esercizi | 7eaad2ae78f0ada90d1c6264cd02a05f26c31941 | [
"Apache-2.0"
] | null | null | null | esercizi_prove/esercizi_seconda_intercorso/chef_wedding.cpp | AntonioEmmanuele/asd_homework_esercizi | 7eaad2ae78f0ada90d1c6264cd02a05f26c31941 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <vector>
#include <map>
/*
https://www.codechef.com/problems/CHEFWED
*/
using namespace std;
//O(n)*O(n-i), dovrebbe essere Theta(n), alla finne ti trovi sempre a ciclare al max su n i=n-1
void calc_ineff(vector<unsigned int> guests,unsigned int& idx,unsigned int& actual_ineff,const unsigned int table_price){
map<unsigned int,unsigned int> table_occurrences;
if(actual_ineff==0)
actual_ineff=table_price;
unsigned int ineff_hold=actual_ineff,ineff_split=actual_ineff,original=actual_ineff;
while (idx<guests.size()){
table_occurrences[guests[idx]]++;
if (table_occurrences[guests[idx]]<=1) //valore di default //O(1), non ci sono ripetizioni
idx++;
else{
ineff_hold=original+table_occurrences[guests[idx]];
ineff_split+=2*table_price;
//Se mi conviene momentaneamente mantenere allora vai solo ad incrementare il valore dell'inefficienza
if(ineff_hold< ineff_split){
actual_ineff=ineff_hold;
idx++;
}
else {
actual_ineff=ineff_split;
idx++;
break;
}
// idx++;
}
}
if(idx<guests.size())
calc_ineff(guests,idx,actual_ineff,table_price);
}
int main() {
unsigned int tests,guests_num,table_price,i;
//ineff_hold è l'inefficienza che si ha spezzando il tavolo,mentre inefficienza
cin>>tests;
while(tests>0){
cin>>guests_num;
cin>>table_price;
unsigned int actual_ineff=0;
vector<unsigned int> guests(guests_num,0);
//andiamo con un approccio bottom up
//Sottoproblemi: numero di persone* tempo sottoproblema O(1)
//Indovinare ultima persona del tavolo in base lal calcolo
//delle inefficienze, possibile anche vedere la complessità totale come la somma
//delle complessità di ogni singolo tavolo che è Theta(n)
//FUNZIONA PERCHE' OTTIMO LOCALE (soluzione migliore per un tavolo) unito ad altri ottimi
//DA risultato totale ottimo (sottostruttura ottima del problema)
for(i=0;i<guests_num;i++)
cin>>guests[i];
i=0;
calc_ineff(guests,i,actual_ineff,table_price);
cout<< actual_ineff<<endl;
tests--;
}
return 0;
}
| 35.176471 | 121 | 0.629181 | [
"vector"
] |
eb1a849048ae0ce4247b97949878d82be9e3f8ba | 22,023 | cpp | C++ | app/archive/commsdsl2old/src/BundleField.cpp | arobenko/commsdsl | e0f0bf42a455445d0a266d3540b008e0dc24cd15 | [
"Apache-2.0"
] | 4 | 2018-12-18T09:51:48.000Z | 2019-07-31T20:21:57.000Z | app/archive/commsdsl2old/src/BundleField.cpp | arobenko/commsdsl | e0f0bf42a455445d0a266d3540b008e0dc24cd15 | [
"Apache-2.0"
] | 4 | 2019-08-02T06:59:58.000Z | 2020-06-01T22:10:02.000Z | app/archive/commsdsl2old/src/BundleField.cpp | arobenko/commsdsl | e0f0bf42a455445d0a266d3540b008e0dc24cd15 | [
"Apache-2.0"
] | 2 | 2019-06-05T15:37:03.000Z | 2020-01-30T11:47:59.000Z | //
// Copyright 2018 - 2021 (C). Alex Robenko. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "BundleField.h"
#include <type_traits>
#include <numeric>
#include <boost/algorithm/string.hpp>
#include "Generator.h"
#include "common.h"
#include "IntField.h"
namespace ba = boost::algorithm;
namespace commsdsl2old
{
namespace
{
const std::string MembersDefTemplate =
"/// @brief Scope for all the member fields of\n"
"/// @ref #^#CLASS_NAME#$# bundle.\n"
"#^#EXTRA_PREFIX#$#\n"
"struct #^#CLASS_NAME#$#Members\n"
"{\n"
" #^#MEMBERS_DEFS#$#\n"
" /// @brief All members bundled in @b std::tuple.\n"
" using All =\n"
" std::tuple<\n"
" #^#MEMBERS#$#\n"
" >;\n"
"};\n";
const std::string MembersOptionsTemplate =
"/// @brief Extra options for all the member fields of\n"
"/// @ref #^#SCOPE#$##^#CLASS_NAME#$# bundle.\n"
"struct #^#CLASS_NAME#$#Members#^#EXT#$#\n"
"{\n"
" #^#OPTIONS#$#\n"
"};\n";
const std::string ClassTemplate(
"#^#MEMBERS_STRUCT_DEF#$#\n"
"#^#PREFIX#$#"
"class #^#CLASS_NAME#$# : public\n"
" comms::field::Bundle<\n"
" #^#PROT_NAMESPACE#$#::field::FieldBase<>,\n"
" typename #^#ORIG_CLASS_NAME#$#Members#^#MEMBERS_OPT#$#::All#^#COMMA#$#\n"
" #^#FIELD_OPTS#$#\n"
" >\n"
"{\n"
" using Base = \n"
" comms::field::Bundle<\n"
" #^#PROT_NAMESPACE#$#::field::FieldBase<>,\n"
" typename #^#ORIG_CLASS_NAME#$#Members#^#MEMBERS_OPT#$#::All#^#COMMA#$#\n"
" #^#FIELD_OPTS#$#\n"
" >;\n"
"public:\n"
" #^#ACCESS#$#\n"
" #^#ALIASES#$#\n"
" #^#PUBLIC#$#\n"
" #^#NAME#$#\n"
" #^#READ#$#\n"
" #^#WRITE#$#\n"
" #^#LENGTH#$#\n"
" #^#VALID#$#\n"
" #^#REFRESH#$#\n"
"#^#PROTECTED#$#\n"
"#^#PRIVATE#$#\n"
"};\n"
);
} // namespace
bool BundleField::startsWithValidPropKey() const
{
if (m_members.empty()) {
return false;
}
auto& first = m_members.front();
if (first->kind() != commsdsl::parse::Field::Kind::Int) {
return false;
}
auto& keyField = static_cast<const IntField&>(*first);
if (!keyField.isValidPropKey()) {
return false;
}
// Valid only if there is no non-default read
return getRead().empty();
}
std::string BundleField::getPropKeyType() const
{
if (m_members.empty()) {
return common::emptyString();
}
auto& first = m_members.front();
if (first->kind() != commsdsl::parse::Field::Kind::Int) {
return common::emptyString();
}
auto& keyField = static_cast<const IntField&>(*first);
return keyField.getPropKeyType();
}
std::string BundleField::getFirstMemberName() const
{
if (m_members.empty()) {
return common::emptyString();
}
return m_members.front()->name();
}
std::string BundleField::getPropKeyValueStr(bool asHex) const
{
if (m_members.empty()) {
return common::emptyString();
}
auto& first = m_members.front();
if (first->kind() != commsdsl::parse::Field::Kind::Int) {
return common::emptyString();
}
auto& keyField = static_cast<const IntField&>(*first);
return keyField.getPropKeyValueStr(asHex);
}
bool BundleField::prepareImpl()
{
auto obj = bundleFieldDslObj();
auto members = obj.members();
m_members.reserve(members.size());
for (auto& m : members) {
auto ptr = create(generator(), m);
if (!ptr) {
static constexpr bool Should_not_happen = false;
static_cast<void>(Should_not_happen);
assert(Should_not_happen);
return false;
}
ptr->setMemberChild();
if (!ptr->prepare(obj.sinceVersion())) {
return false;
}
m_members.push_back(std::move(ptr));
}
return true;
}
void BundleField::updateIncludesImpl(IncludesList& includes) const
{
static const IncludesList List = {
"comms/field/Bundle.h",
"<tuple>"
};
common::mergeIncludes(List, includes);
for (auto& m : m_members) {
m->updateIncludes(includes);
}
}
void BundleField::updateIncludesCommonImpl(IncludesList& includes) const
{
for (auto& m : m_members) {
m->updateIncludesCommon(includes);
}
}
void BundleField::updatePluginIncludesImpl(Field::IncludesList& includes) const
{
for (auto& m : m_members) {
m->updatePluginIncludes(includes);
}
}
std::size_t BundleField::minLengthImpl() const
{
return
std::accumulate(
m_members.begin(), m_members.end(), std::size_t(0),
[](std::size_t soFar, auto& m)
{
return soFar + m->minLength();
});
}
std::size_t BundleField::maxLengthImpl() const
{
return
std::accumulate(
m_members.begin(), m_members.end(), std::size_t(0),
[](std::size_t soFar, auto& m)
{
return common::addLength(soFar, m->maxLength());
});
}
std::string BundleField::getClassDefinitionImpl(
const std::string& scope,
const std::string& className) const
{
common::ReplacementMap replacements;
replacements.insert(std::make_pair("PREFIX", getClassPrefix(className)));
replacements.insert(std::make_pair("CLASS_NAME", className));
replacements.insert(std::make_pair("ORIG_CLASS_NAME", common::nameToClassCopy(name())));
replacements.insert(std::make_pair("PROT_NAMESPACE", generator().mainNamespace()));
replacements.insert(std::make_pair("FIELD_OPTS", getFieldOpts(scope)));
replacements.insert(std::make_pair("NAME", getNameCommonWrapFunc(adjustScopeWithNamespace(scope))));
replacements.insert(std::make_pair("READ", getRead()));
replacements.insert(std::make_pair("WRITE", getCustomWrite()));
replacements.insert(std::make_pair("LENGTH", getCustomLength()));
replacements.insert(std::make_pair("VALID", getCustomValid()));
replacements.insert(std::make_pair("REFRESH", getRefresh()));
replacements.insert(std::make_pair("MEMBERS_STRUCT_DEF", getMembersDef(scope)));
replacements.insert(std::make_pair("ACCESS", getAccess()));
replacements.insert(std::make_pair("ALIASES", getAliases()));
replacements.insert(std::make_pair("PRIVATE", getPrivate()));
replacements.insert(std::make_pair("PUBLIC", getExtraPublic()));
replacements.insert(std::make_pair("PROTECTED", getFullProtected()));
if (!replacements["FIELD_OPTS"].empty()) {
replacements["COMMA"] = ',';
}
if (!externalRef().empty()) {
replacements.insert(std::make_pair("MEMBERS_OPT", "<TOpt>"));
}
return common::processTemplate(ClassTemplate, replacements);
}
std::string BundleField::getExtraDefaultOptionsImpl(const std::string& scope) const
{
return getExtraOptions(scope, &Field::getDefaultOptions, std::string());
}
std::string BundleField::getExtraBareMetalDefaultOptionsImpl(const std::string& base, const std::string& scope) const
{
return getExtraOptions(scope, &Field::getBareMetalDefaultOptions, base);
}
std::string BundleField::getExtraDataViewDefaultOptionsImpl(const std::string& base, const std::string& scope) const
{
return getExtraOptions(scope, &Field::getDataViewDefaultOptions, base);
}
std::string BundleField::getPluginAnonNamespaceImpl(
const std::string& scope,
bool forcedSerialisedHidden,
bool serHiddenParam) const
{
auto fullScope = scope + common::nameToClassCopy(name()) + common::membersSuffixStr();
if (!externalRef().empty()) {
fullScope += "<>";
}
fullScope += "::";
common::StringsList props;
for (auto& f : m_members) {
props.push_back(f->getPluginCreatePropsFunc(fullScope, forcedSerialisedHidden, serHiddenParam));
}
static const std::string Templ =
"struct #^#CLASS_NAME#$#Members\n"
"{\n"
" #^#PROPS#$#\n"
"};\n";
common::ReplacementMap replacements;
replacements.insert(std::make_pair("CLASS_NAME", common::nameToClassCopy(name())));
replacements.insert(std::make_pair("PROPS", common::listToString(props, "\n", common::emptyString())));
return common::processTemplate(Templ, replacements);
}
std::string BundleField::getPluginPropertiesImpl(bool serHiddenParam) const
{
common::StringsList props;
props.reserve(m_members.size());
auto prefix =
common::nameToClassCopy(name()) + common::membersSuffixStr() +
"::createProps_";
for (auto& f : m_members) {
auto str = ".add(" + prefix + common::nameToAccessCopy(f->name()) + "(";
if (serHiddenParam) {
str += common::serHiddenStr();
}
str += "))";
props.push_back(std::move(str));
}
return common::listToString(props, "\n", common::emptyString());
}
void BundleField::setForcedPseudoImpl()
{
for (auto& m : m_members) {
m->setForcedPseudo();
}
}
void BundleField::setForcedNoOptionsConfigImpl()
{
for (auto& m : m_members) {
m->setForcedNoOptionsConfig();
}
}
bool BundleField::isVersionDependentImpl() const
{
return
std::any_of(
m_members.begin(), m_members.end(),
[](auto& m)
{
return m->isVersionDependent();
});
}
std::string BundleField::getCommonDefinitionImpl(const std::string& fullScope) const
{
common::StringsList defs;
auto updatedScope =
fullScope + common::membersSuffixStr() + "::";
for (auto& m : m_members) {
auto str = m->getCommonDefinition(updatedScope);
if (!str.empty()) {
defs.emplace_back(std::move(str));
}
}
std::string membersCommon;
if (!defs.empty()) {
static const std::string Templ =
"/// @brief Scope for all the common definitions of the member fields of\n"
"/// @ref #^#SCOPE#$# field.\n"
"struct #^#CLASS_NAME#$#MembersCommon\n"
"{\n"
" #^#DEFS#$#\n"
"};\n";
common::ReplacementMap repl;
repl.insert(std::make_pair("CLASS_NAME", common::nameToClassCopy(name())));
repl.insert(std::make_pair("SCOPE", fullScope));
repl.insert(std::make_pair("DEFS", common::listToString(defs, "\n", common::emptyString())));
membersCommon = common::processTemplate(Templ, repl);
}
static const std::string Templ =
"#^#COMMON#$#\n"
"/// @brief Scope for all the common definitions of the\n"
"/// @ref #^#SCOPE#$# field.\n"
"struct #^#CLASS_NAME#$#Common\n"
"{\n"
" #^#NAME_FUNC#$#\n"
"};\n\n";
common::ReplacementMap repl;
repl.insert(std::make_pair("COMMON", std::move(membersCommon)));
repl.insert(std::make_pair("CLASS_NAME", common::nameToClassCopy(name())));
repl.insert(std::make_pair("SCOPE", fullScope));
repl.insert(std::make_pair("NAME_FUNC", getCommonNameFunc(fullScope)));
return common::processTemplate(Templ, repl);
}
std::string BundleField::getExtraRefToCommonDefinitionImpl(const std::string& fullScope) const
{
static const std::string Templ =
"/// @brief Common types and functions for members of\n"
"/// @ref #^#SCOPE#$# field.\n"
"using #^#CLASS_NAME#$#MembersCommon = #^#COMMON_SCOPE#$#MembersCommon;\n\n";
auto commonScope = scopeForCommon(generator().scopeForField(externalRef(), true, true));
std::string className = classNameFromFullScope(fullScope);
common::ReplacementMap repl;
repl.insert(std::make_pair("SCOPE", fullScope));
repl.insert(std::make_pair("CLASS_NAME", std::move(className)));
repl.insert(std::make_pair("COMMON_SCOPE", std::move(commonScope)));
return common::processTemplate(Templ, repl);
}
bool BundleField::verifyAliasImpl(const std::string& fieldName) const
{
assert(!fieldName.empty());
auto dotPos = fieldName.find('.');
std::string firstFieldName(fieldName, 0, dotPos);
auto iter =
std::find_if(
m_members.begin(), m_members.end(),
[&firstFieldName](auto& f)
{
return firstFieldName == f->name();
});
if (iter == m_members.end()) {
return false;
}
if (dotPos == std::string::npos) {
return true;
}
std::string restFieldName(fieldName, dotPos + 1);
return (*iter)->verifyAlias(restFieldName);
}
std::string BundleField::getFieldOpts(const std::string& scope) const
{
StringsList options;
updateExtraOptions(scope, options);
bool membersHaveCustomReadRefresh =
std::any_of(
m_members.begin(), m_members.end(),
[](auto& m) {
assert(m);
return m->hasCustomReadRefresh();
});
if (membersHaveCustomReadRefresh) {
common::addToList("comms::option::def::HasCustomRead", options);
common::addToList("comms::option::def::HasCustomRefresh", options);
}
auto lengthFieldIter =
std::find_if(
m_members.begin(), m_members.end(),
[](auto& m) {
assert(m);
return m->semanticType() == commsdsl::parse::Field::SemanticType::Length;
});
if (lengthFieldIter != m_members.end()) {
auto idx = static_cast<unsigned>(std::distance(m_members.begin(), lengthFieldIter));
auto optStr = "comms::option::def::RemLengthMemberField<" + common::numToString(idx) + '>';
common::addToList(optStr, options);
}
return common::listToString(options, ",\n", common::emptyString());
}
std::string BundleField::getMembersDef(const std::string& scope) const
{
auto className = common::nameToClassCopy(name());
std::string memberScope;
if (!scope.empty()) {
memberScope = scope + className + common::membersSuffixStr() + "::";
}
StringsList membersDefs;
StringsList membersNames;
membersDefs.reserve(m_members.size());
membersNames.reserve(m_members.size());
for (auto& m : m_members) {
membersDefs.push_back(m->getClassDefinition(memberScope));
membersNames.push_back(common::nameToClassCopy(m->name()));
}
std::string prefix;
if (!externalRef().empty()) {
prefix += "/// @tparam TOpt Protocol options.\n";
prefix += "template <typename TOpt = " + generator().scopeForOptions(common::defaultOptionsStr(), true, true) + ">";
}
common::ReplacementMap replacements;
replacements.insert(std::make_pair("CLASS_NAME", className));
replacements.insert(std::make_pair("EXTRA_PREFIX", std::move(prefix)));
replacements.insert(std::make_pair("MEMBERS_DEFS", common::listToString(membersDefs, "\n", common::emptyString())));
replacements.insert(std::make_pair("MEMBERS", common::listToString(membersNames, ",\n", common::emptyString())));
return common::processTemplate(MembersDefTemplate, replacements);
}
std::string BundleField::getAccess() const
{
static const std::string Templ =
"/// @brief Allow access to internal fields.\n"
"/// @details See definition of @b COMMS_FIELD_MEMBERS_NAMES macro\n"
"/// related to @b comms::field::Bundle class from COMMS library\n"
"/// for details.\n"
"///\n"
"/// The generated values, types and accesss functions are:\n"
"#^#ACCESS_DOC#$#\n"
"COMMS_FIELD_MEMBERS_NAMES(\n"
" #^#NAMES#$#\n"
");\n";
StringsList accessDocList;
StringsList namesList;
accessDocList.reserve(m_members.size());
namesList.reserve(m_members.size());
auto scope = common::nameToClassCopy(name()) + common::membersSuffixStr() + "::";
for (auto& m : m_members) {
namesList.push_back(common::nameToAccessCopy(m->name()));
std::string accessStr =
"/// @li @b FieldIdx_" + namesList.back() +
"index, @b Field_" + namesList.back() +
"type and @b field_" + namesList.back() +
"() access function -\n"
"/// for " + scope +
common::nameToClassCopy(m->name()) + " member field.";
accessDocList.push_back(std::move(accessStr));
}
common::ReplacementMap replacements;
replacements.insert(std::make_pair("ACCESS_DOC", common::listToString(accessDocList, "\n", common::emptyString())));
replacements.insert(std::make_pair("NAMES", common::listToString(namesList, ",\n", common::emptyString())));
return common::processTemplate(Templ, replacements);
}
std::string BundleField::getAliases() const
{
auto obj = bundleFieldDslObj();
auto aliases = obj.aliases();
if (aliases.empty()) {
return common::emptyString();
}
common::StringsList result;
for (auto& a : aliases) {
auto& fieldName = a.fieldName();
assert(!fieldName.empty());
auto dotPos = fieldName.find('.');
std::string firstFieldName(fieldName, 0, dotPos);
auto iter =
std::find_if(
m_members.begin(), m_members.end(),
[&firstFieldName](auto& f)
{
return firstFieldName == f->name();
});
if (iter == m_members.end()) {
continue;
}
std::string restFieldName;
if (dotPos != std::string::npos) {
restFieldName.assign(fieldName, dotPos + 1, fieldName.size());
}
if (!restFieldName.empty() && (!(*iter)->verifyAlias(restFieldName))) {
continue;
}
static const std::string Templ =
"/// @brief Alias to a member field.\n"
"/// @details\n"
"#^#ALIAS_DESC#$#\n"
"/// Generates field access alias function(s):\n"
"/// @b field_#^#ALIAS_NAME#$#() -> <b>#^#ALIASED_FIELD_DOC#$#</b>\n"
"COMMS_FIELD_ALIAS(#^#ALIAS_NAME#$#, #^#ALIASED_FIELD#$#);\n";
std::vector<std::string> aliasedFields;
ba::split(aliasedFields, fieldName, ba::is_any_of("."));
std::string aliasedFieldDocStr;
std::string aliasedFieldStr;
for (auto& f : aliasedFields) {
common::nameToAccess(f);
if (!aliasedFieldDocStr.empty()) {
aliasedFieldDocStr += '.';
}
aliasedFieldDocStr += "field_" + f + "()";
if (!aliasedFieldStr.empty()) {
aliasedFieldStr += ", ";
}
aliasedFieldStr += f;
}
auto desc = common::makeDoxygenMultilineCopy(a.description());
if (!desc.empty()) {
desc = common::doxygenPrefixStr() + common::indentStr() + desc + " @n";
}
common::ReplacementMap repl;
repl.insert(std::make_pair("ALIAS_NAME", common::nameToAccessCopy(a.name())));
repl.insert(std::make_pair("ALIASED_FIELD_DOC", std::move(aliasedFieldDocStr)));
repl.insert(std::make_pair("ALIASED_FIELD", std::move(aliasedFieldStr)));
repl.insert(std::make_pair("ALIAS_DESC", std::move(desc)));
result.push_back(common::processTemplate(Templ, repl));
}
if (result.empty()) {
return common::emptyString();
}
return common::listToString(result, "\n", common::emptyString());
}
std::string BundleField::getRead() const
{
auto customRead = getCustomRead();
if (!customRead.empty()) {
return customRead;
}
return getReadForFields(m_members);
}
std::string BundleField::getRefresh() const
{
auto customRefresh = getCustomRefresh();
if (!customRefresh.empty()) {
return customRefresh;
}
return getPublicRefreshForFields(m_members, false);
}
std::string BundleField::getPrivate() const
{
auto str = getExtraPrivate();
auto refreshStr = getPrivateRefreshForFields(m_members);
if ((!str.empty()) && (refreshStr.empty())) {
str += '\n';
}
str += refreshStr;
if (str.empty()) {
return str;
}
common::insertIndent(str);
static const std::string Prefix("private:\n");
return Prefix + str;
}
std::string BundleField::getExtraOptions(
const std::string& scope,
GetExtraOptionsFunc func,
const std::string& base) const
{
std::string nextBase;
std::string ext;
if (!base.empty()) {
nextBase = base + "::" + common::nameToClassCopy(name()) + common::membersSuffixStr();
ext = " : public " + nextBase;
}
std::string memberScope = scope + common::nameToClassCopy(name()) + common::membersSuffixStr() + "::";
StringsList options;
options.reserve(m_members.size());
for (auto& m : m_members) {
assert(m);
auto opt = (m.get()->*func)(nextBase, memberScope);
if (!opt.empty()) {
options.push_back(std::move(opt));
}
}
if (options.empty()) {
return common::emptyString();
}
common::ReplacementMap replacements;
replacements.insert(std::make_pair("CLASS_NAME", common::nameToClassCopy(name())));
replacements.insert(std::make_pair("SCOPE", scope));
replacements.insert(std::make_pair("EXT", std::move(ext)));
replacements.insert(std::make_pair("OPTIONS", common::listToString(options, "\n", common::emptyString())));
return common::processTemplate(MembersOptionsTemplate, replacements);
}
} // namespace commsdsl2old | 31.642241 | 124 | 0.607955 | [
"vector"
] |
eb1f0ac30808fbe8895b8e2b99de5a7579b66b76 | 6,005 | cpp | C++ | testpng.cpp | TimSC/drawlib | c51f1331203a30fb5736fca9c85d5f5c41b5f8ba | [
"BSD-2-Clause"
] | null | null | null | testpng.cpp | TimSC/drawlib | c51f1331203a30fb5736fca9c85d5f5c41b5f8ba | [
"BSD-2-Clause"
] | null | null | null | testpng.cpp | TimSC/drawlib | c51f1331203a30fb5736fca9c85d5f5c41b5f8ba | [
"BSD-2-Clause"
] | 4 | 2016-05-26T15:11:48.000Z | 2021-03-02T16:02:48.000Z | #include "drawlibcairo.h"
#include <iostream>
using namespace std;
void DrawTestPatterns(class IDrawLib *drawLib)
{
Contour outer;
outer.push_back(Point(50, 50));
outer.push_back(Point(150, 50));
outer.push_back(Point(150, 150));
outer.push_back(Point(50, 150));
Contours inners;
Polygon polygon(outer, inners);
Contour outer2;
outer2.push_back(Point(51, 51));
outer2.push_back(Point(149, 51));
outer2.push_back(Point(149, 149));
outer2.push_back(Point(51, 149));
Contours inners2;
Polygon polygon2(outer2, inners2);
std::vector<Polygon> polygons;
polygons.push_back(polygon);
class ShapeProperties prop(1.0, 0.0, 0.0);
drawLib->AddDrawPolygonsCmd(polygons, prop);
std::vector<Polygon> polygons2;
polygons2.push_back(polygon2);
class ShapeProperties prop2(0.5, 0.0, 0.0);
drawLib->AddDrawPolygonsCmd(polygons2, prop2);
Contour line1;
line1.push_back(Point(100, 100));
line1.push_back(Point(160, 110));
line1.push_back(Point(60, 50));
class LineProperties lineProp1(0.0, 0.9, 0.0, 1.0);
lineProp1.closedLoop = true;
Contours lines1;
lines1.push_back(line1);
drawLib->AddDrawLinesCmd(lines1, lineProp1);
//Text labels
std::vector<class TextLabel> textStrs;
TwistedTriangles triangles;
const char *hello = "Hello";
const char *arabic = "السلام عليكم";
class TextLabel label(hello, 60.0, 50.0);
class TextLabel interlLabel(arabic, 50.0, 200.0);
class TextProperties properties;
properties.fontSize = 30.0;
drawLib->GetTriangleBoundsText(label, properties,
triangles);
drawLib->GetTriangleBoundsText(interlLabel, properties,
triangles);
textStrs.push_back(label);
textStrs.push_back(interlLabel);
drawLib->AddDrawTextCmd(textStrs, properties);
//Draw origin point
Contour cross1;
cross1.push_back(Point(55, 50));
cross1.push_back(Point(65, 50));
Contour cross2;
cross2.push_back(Point(60, 45));
cross2.push_back(Point(60, 55));
class LineProperties lineProp2(0.0, 0.0, 1.0, 1.0);
Contours lines2;
lines2.push_back(cross1);
lines2.push_back(cross2);
drawLib->AddDrawLinesCmd(lines2, lineProp2);
//More label tests
textStrs.clear();
class TextLabel label2("world", 170.0, 50.0);
class TextProperties properties2;
properties2.fontSize = 25.0;
properties2.outline = true;
properties2.fill = false;
properties2.lr = 1.0;
properties2.lg = 0.5;
properties2.lb = 0.1;
textStrs.push_back(label2);
drawLib->AddDrawTextCmd(textStrs, properties2);
textStrs.clear();
class TextLabel label3("rotated", 60.0, 100.0, 0.5);
textStrs.push_back(label3);
drawLib->AddDrawTextCmd(textStrs, properties2);
textStrs.clear();
class TextLabel label4("rotated", 60.0, 100.0, 0.6);
class TextLabel label5("foo", 180.0, 100.0, 0.0);
properties.fa = 0.5;
textStrs.push_back(label4);
textStrs.push_back(label5);
drawLib->AddDrawTextCmd(textStrs, properties);
drawLib->GetTriangleBoundsText(label4, properties,
triangles);
//Twisted text
std::vector<class TwistedTextLabel> twistedTextStrs;
std::vector<TwistedCurveCmd> pathCmds;
pathCmds.push_back(NewTwistedCurveCmd(MoveTo, 2, 320.0, 100.0));
pathCmds.push_back(NewTwistedCurveCmd(RelCurveTo, 6, 50.0, -50.0, 150.0, -50.0, 200.0, 0.0));
twistedTextStrs.push_back(TwistedTextLabel(arabic, pathCmds));
properties2.valign = 0.5;
drawLib->AddDrawTwistedTextCmd(twistedTextStrs, properties2);
//Test triangles for twisted text
double pathLen = -1.0, textLen = -1.0;
drawLib->GetTriangleBoundsTwistedText(TwistedTextLabel(arabic, pathCmds),
properties2,
triangles, pathLen, textLen);
Contour line3;
line3.push_back(Point(320.0, 150.0));
line3.push_back(Point(380.0, 210.0));
line3.push_back(Point(440.0, 150.0));
line3.push_back(Point(460.0, 150.0));
line3.push_back(Point(460.0, 220.0));
line3.push_back(Point(480.0, 240.0));
line3.push_back(Point(550.0, 240.0));
line3.push_back(Point(550.0, 200.0));
line3.push_back(Point(560.0, 150.0));
line3.push_back(Point(600.0, 170.0));
class LineProperties lineProp3(0.0, 0.9, 0.0, 1.0);
Contours lines3;
lines3.push_back(line3);
drawLib->AddDrawLinesCmd(lines3, lineProp3);
//Test fitting Bezier to set of points
const char *rooms = "All the rooms renumbered. All the rooms renumbered.";
std::vector<TwistedCurveCmd> pathCmds2;
FixBezierToPoints(line3, pathCmds2);
class TextProperties properties3;
properties3.fontSize = 15.0;
properties3.valign = 0.8;
std::vector<class TwistedTextLabel> twistedTextStrs2;
twistedTextStrs2.push_back(TwistedTextLabel(rooms, pathCmds2));
drawLib->AddDrawTwistedTextCmd(twistedTextStrs2, properties3);
//Check resource dimensions
unsigned resWidth=0, resHeight=0;
int resSizeRet = drawLib->GetResourceDimensionsFromFilename("tests/letterr.png", resWidth, resHeight);
cout << "Check resource size:" << resSizeRet << "," << resWidth << "," << resHeight << endl;
//Load image resources
std::map<std::string, std::string> loadIdToFilenameMapping;
loadIdToFilenameMapping["letterR"] = "tests/letterr.png";
drawLib->AddLoadImageResourcesCmd(loadIdToFilenameMapping);
//Draw image to canvas
class ShapeProperties prop3(1.0, 1.0, 1.0);
prop3.imageId = "letterR";
prop3.texx=-340.0;
prop3.texy=-200.0;
Contour outer3;
outer3.push_back(Point(340, 200));
outer3.push_back(Point(404, 200));
outer3.push_back(Point(404, 264));
outer3.push_back(Point(340, 264));
Contour inner3;
inner3.push_back(Point(360, 220));
inner3.push_back(Point(384, 220));
inner3.push_back(Point(384, 244));
inner3.push_back(Point(360, 244));
Contours inners3;
inners3.push_back(inner3);
Polygon polygon3(outer3, inners3);
std::vector<Polygon> polygons3;
polygons3.push_back(polygon3);
drawLib->AddDrawPolygonsCmd(polygons3, prop3);
drawLib->Draw();
}
int main(void)
{
cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 640, 480);
class DrawLibCairoPango drawlib(surface);
//class DrawLibCairo drawlib(surface);
DrawTestPatterns(&drawlib);
cairo_surface_write_to_png(surface, "image.png");
cairo_surface_destroy(surface);
return 0;
}
| 30.482234 | 103 | 0.747211 | [
"vector"
] |
eb2027dc0cd73c60eb1b2d09757bbf9386360fc3 | 5,797 | cpp | C++ | Source/Utility/MythForest/Component/Stream/StreamComponent.cpp | paintdream/paintsnow | 3a1cbc9e571eaa2e62a3a2d60f75817b45f0c781 | [
"MIT"
] | null | null | null | Source/Utility/MythForest/Component/Stream/StreamComponent.cpp | paintdream/paintsnow | 3a1cbc9e571eaa2e62a3a2d60f75817b45f0c781 | [
"MIT"
] | null | null | null | Source/Utility/MythForest/Component/Stream/StreamComponent.cpp | paintdream/paintsnow | 3a1cbc9e571eaa2e62a3a2d60f75817b45f0c781 | [
"MIT"
] | null | null | null | #include "StreamComponent.h"
#include "../../../BridgeSunset/BridgeSunset.h"
#include "../../../../Core/Driver/Profiler/Optick/optick.h"
#include <utility>
using namespace PaintsNow;
StreamComponent::StreamComponent(const UShort3& dim, uint16_t cacheCount) : dimension(dim), recycleStart(0) {
assert(dim.x() != 0 && dim.y() != 0 && dim.z() != 0);
idGrids.resize(dim.x() * dim.y() * dim.z(), (uint16_t)~0);
grids.resize(cacheCount);
recycleQueue.resize(cacheCount);
for (uint16_t i = 0; i < cacheCount; i++) {
recycleQueue[i] = i;
}
}
UShort3 StreamComponent::ComputeWrapCoordinate(const Int3& pos) const {
return UShort3(
verify_cast<uint16_t>((pos.x() % dimension.x() + dimension.x()) % dimension.x()),
verify_cast<uint16_t>((pos.y() % dimension.y() + dimension.y()) % dimension.y()),
verify_cast<uint16_t>((pos.z() % dimension.z() + dimension.z()) % dimension.z()));
}
uint16_t StreamComponent::GetCacheCount() const {
return verify_cast<uint16_t>(grids.size());
}
void StreamComponent::Unload(Engine& engine, const UShort3& coord, const TShared<SharedTiny>&context) {
uint16_t id = idGrids[(coord.z() * dimension.y() + coord.y()) * dimension.x() + coord.x()];
if (id == (uint16_t)~0) return;
UnloadInternal(engine, grids[id], context);
}
void StreamComponent::UnloadInternal(Engine& engine, Grid& grid, const TShared<SharedTiny>&context) {
OPTICK_EVENT();
if (unloadHandler.script) {
IScript::Request& request = *engine.bridgeSunset.requestPool.AcquireSafe();
IScript::Delegate<SharedTiny> w;
request.DoLock();
request.Push();
request.Call(unloadHandler.script, grid.coord, grid.object, context);
request >> w;
request.Pop();
request.UnLock();
grid.object = w.Get();
engine.bridgeSunset.requestPool.ReleaseSafe(&request);
} else if (unloadHandler.native) {
grid.object = unloadHandler.native(engine, grid.coord, grid.object, context);
}
}
SharedTiny* StreamComponent::Load(Engine& engine, const UShort3& coord, const TShared<SharedTiny>& context) {
OPTICK_EVENT();
size_t offset = (coord.z() * dimension.y() + coord.y()) * dimension.x() + coord.x();
uint16_t id = idGrids[offset];
SharedTiny* object = nullptr;
while (true) {
if (id == (uint16_t)~0) {
// allocate id ...
id = recycleQueue[recycleStart];
Grid& grid = grids[id];
if (grid.object) {
UnloadInternal(engine, grid, context);
}
TShared<SharedTiny> last = grid.object;
grid.recycleIndex = recycleStart;
assert(recycleQueue[grid.recycleIndex] == id);
recycleStart = (recycleStart + 1) % verify_cast<uint16_t>(recycleQueue.size());
if (loadHandler.script) {
IScript::Request& request = *engine.bridgeSunset.requestPool.AcquireSafe();
IScript::Delegate<SharedTiny> w;
request.DoLock();
request.Push();
request.Call(loadHandler.script, coord, last, context);
request >> w;
request.Pop();
request.UnLock();
assert(w);
grid.object = w.Get();
engine.bridgeSunset.requestPool.ReleaseSafe(&request);
} else {
assert(loadHandler.native);
grid.object = loadHandler.native(engine, coord, last, context);
}
grid.coord = coord;
object = grid.object();
idGrids[offset] = id;
break;
} else {
Grid& grid = grids[id];
if (grid.coord == coord) {
if ((grid.recycleIndex + 1) % verify_cast<uint16_t>(recycleQueue.size()) != recycleStart) {
std::swap(recycleQueue[recycleStart], recycleQueue[grid.recycleIndex]);
std::swap(grids[recycleStart].recycleIndex, grid.recycleIndex);
recycleStart = (recycleStart + 1) % verify_cast<uint16_t>(recycleQueue.size());
}
object = grid.object();
break;
} else {
id = (uint16_t)~0; // invalid, must reload
}
}
}
if (refreshHandler.script) {
IScript::Request& request = *engine.bridgeSunset.requestPool.AcquireSafe();
request.DoLock();
request.Push();
request.Call(refreshHandler.script, coord, object, context);
request.Pop();
request.UnLock();
engine.bridgeSunset.requestPool.ReleaseSafe(&request);
} else if (refreshHandler.native) {
refreshHandler.native(engine, coord, object, context);
}
return object;
}
const UShort3& StreamComponent::GetDimension() const {
return dimension;
}
void StreamComponent::Uninitialize(Engine& engine, Entity* entity) {
if (!engine.interfaces.script.IsResetting()) {
IScript::Request& request = engine.interfaces.script.GetDefaultRequest();
SetLoadHandler(request, IScript::Request::Ref());
SetRefreshHandler(request, IScript::Request::Ref());
SetUnloadHandler(request, IScript::Request::Ref());
} else {
loadHandler.script = IScript::Request::Ref();
refreshHandler.script = IScript::Request::Ref();
unloadHandler.script = IScript::Request::Ref();
}
BaseClass::Uninitialize(engine, entity);
}
void StreamComponent::SetLoadHandler(IScript::Request& request, IScript::Request::Ref ref) {
loadHandler.ReplaceScript(request, ref);
}
void StreamComponent::SetRefreshHandler(IScript::Request& request, IScript::Request::Ref ref) {
refreshHandler.ReplaceScript(request, ref);
}
void StreamComponent::SetUnloadHandler(IScript::Request& request, IScript::Request::Ref ref) {
unloadHandler.ReplaceScript(request, ref);
}
void StreamComponent::SetLoadHandler(const TWrapper<TShared<SharedTiny>, Engine&, const UShort3&, const TShared<SharedTiny>&, const TShared<SharedTiny>& >& handler) {
loadHandler.native = handler;
}
void StreamComponent::SetRefreshHandler(const TWrapper<void, Engine&, const UShort3&, const TShared<SharedTiny>&, const TShared<SharedTiny>& >& handler) {
refreshHandler.native = handler;
}
void StreamComponent::SetUnloadHandler(const TWrapper<TShared<SharedTiny>, Engine&, const UShort3&, const TShared<SharedTiny>&, const TShared<SharedTiny>& >& handler) {
unloadHandler.native = handler;
}
| 32.9375 | 168 | 0.705192 | [
"object"
] |
eb27b63ea843478889768ea7dda63d0c54deab2d | 857 | cpp | C++ | src/bindings/URL.cpp | mchiasson/PhaserNative | f867454602c395484bf730a7c43b9c586c102ac2 | [
"MIT"
] | null | null | null | src/bindings/URL.cpp | mchiasson/PhaserNative | f867454602c395484bf730a7c43b9c586c102ac2 | [
"MIT"
] | null | null | null | src/bindings/URL.cpp | mchiasson/PhaserNative | f867454602c395484bf730a7c43b9c586c102ac2 | [
"MIT"
] | 1 | 2019-01-25T13:55:25.000Z | 2019-01-25T13:55:25.000Z | #include "URL.h"
void URL::RegisterClass() {
JSC::Object url = JSC::Object::MakeFunctionWithCallback("URL", URL::url);
JSC::Object createObjectURL = JSC::Object::MakeFunctionWithCallback("createObjectURL", URL::createObjectURL);
JSC::Object revokeObjectURL = JSC::Object::MakeFunctionWithCallback("revokeObjectURL", URL::revokeObjectURL);
url.setProperty("createObjectURL", createObjectURL);
url.setProperty("revokeObjectURL", revokeObjectURL);
JSC_GLOBAL_OBJECT.setProperty("URL", url);
}
JSC_FUNCTION(URL::url)
{
return JSC::Value::MakeUndefined();
}
JSC_FUNCTION(URL::createObjectURL)
{
// not sure how this is supposed to be implemented, but I'll just return the
// Blob itself for now.
return JSC::Value(argv[0]).toObject();
}
JSC_FUNCTION(URL::revokeObjectURL) {
return JSC::Value::MakeUndefined();
}
| 29.551724 | 113 | 0.723454 | [
"object"
] |
eb27d72e06fa1d0ca444081fec0ac40b0c286dce | 1,363 | hpp | C++ | include/xml_writer.hpp | saby1101/planet-dump-ng | c049dd4cc9d04586ece1b9fbb6d18bed2c6ac42c | [
"BSD-2-Clause"
] | 24 | 2015-03-23T11:01:01.000Z | 2021-03-24T04:10:05.000Z | include/xml_writer.hpp | saby1101/planet-dump-ng | c049dd4cc9d04586ece1b9fbb6d18bed2c6ac42c | [
"BSD-2-Clause"
] | 19 | 2015-02-10T09:14:12.000Z | 2022-03-26T15:21:03.000Z | include/xml_writer.hpp | saby1101/planet-dump-ng | c049dd4cc9d04586ece1b9fbb6d18bed2c6ac42c | [
"BSD-2-Clause"
] | 8 | 2015-02-21T10:30:22.000Z | 2020-12-03T01:49:35.000Z | #ifndef XML_WRITER_HPP
#define XML_WRITER_HPP
#include "output_writer.hpp"
#include "changeset_map.hpp"
#include <ostream>
#include <boost/scoped_ptr.hpp>
#include <boost/date_time/posix_time/ptime.hpp>
#include <boost/program_options.hpp>
#include <map>
#include <string>
class xml_writer : public output_writer {
public:
typedef changeset_map changeset_map_t;
xml_writer(const std::string &, const boost::program_options::variables_map &, const user_map_t &,
const boost::posix_time::ptime &max_time,
user_info_level, historical_versions, changeset_discussions);
virtual ~xml_writer();
void changesets(const std::vector<changeset> &,
const std::vector<current_tag> &,
const std::vector<changeset_comment> &);
void nodes(const std::vector<node> &, const std::vector<old_tag> &);
void ways(const std::vector<way> &, const std::vector<way_node> &, const std::vector<old_tag> &);
void relations(const std::vector<relation> &, const std::vector<relation_member> &, const std::vector<old_tag> &);
void finish();
struct pimpl;
private:
boost::scoped_ptr<pimpl> m_impl;
const user_map_t &m_users;
changeset_discussions m_changeset_discussions;
user_info_level m_user_info_level;
std::string m_generator_name;
changeset_map_t m_changesets;
};
#endif /* XML_WRITER_HPP */
| 32.452381 | 116 | 0.727073 | [
"vector"
] |
eb30105722758e31d5e9c84f04854d48aca15e99 | 918 | cpp | C++ | A_problems/IQtest.cpp | tarek99samy/code_forces_problems | a2e6fd1ad762843a4fa1e4a2561299a21ec2bb2e | [
"MIT"
] | null | null | null | A_problems/IQtest.cpp | tarek99samy/code_forces_problems | a2e6fd1ad762843a4fa1e4a2561299a21ec2bb2e | [
"MIT"
] | null | null | null | A_problems/IQtest.cpp | tarek99samy/code_forces_problems | a2e6fd1ad762843a4fa1e4a2561299a21ec2bb2e | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
//#include<windows.h>
#include<cstring>
#include<string>
#include<algorithm>
#include<stack>
#include<vector>
#include<cmath>
#include<list>
#include<cstdlib>
long long GCD(long long A, long long B)
{
if (B > A)
{
swap(A, B);
}
long long gcd = A % B;
if (gcd == 0)
{
return B;
}
long long next;
while (gcd!=0)
{
next = gcd;
A=B;
B = gcd;
gcd = A % B;
}
return next;
}
int main()
{
int size;
cin >> size;
int * arr = new int[size];
int countodd = 0, countenven = 0;
for (int i = 0; i < size; i++)
{
cin >> arr[i];
if (arr[i] % 2 != 0)
{
countodd++;
}
else
countenven++;
}
if (countenven > countodd)
{
for (int i = 0; i < size; i++)
{
if (arr[i] % 2 != 0)
cout << i + 1 << " ";
}
}
else
{
for (int i = 0; i < size; i++)
if (arr[i] % 2 == 0)
cout << i + 1 << " ";
}
system("pause ");
return 0;
} | 13.114286 | 40 | 0.517429 | [
"vector"
] |
eb30ea971c7b5b732507f9f6a31720376f03aa5e | 13,296 | cpp | C++ | src/engine/gfx/gfxsystem.cpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | src/engine/gfx/gfxsystem.cpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | src/engine/gfx/gfxsystem.cpp | eXl-Nic/eXl | a5a0f77f47db3179365c107a184bb38b80280279 | [
"MIT"
] | null | null | null | /*
Copyright 2009-2021 Nicolas Colombe
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 <engine/gfx/gfxsystem.hpp>
#include "gfxdebugdrawer.hpp"
#include "gfxcomponentrendernode.hpp"
#include "gfxspriterendernode.hpp"
#include <ogl/renderer/oglrendercontext.hpp>
#include <ogl/renderer/ogldisplaylist.hpp>
#include <ogl/renderer/oglcompiledprogram.hpp>
#include <ogl/oglutils.hpp>
#include <engine/common/transforms.hpp>
#include <math/mathtools.hpp>
#include <core/type/tagtype.hpp>
namespace eXl
{
IMPLEMENT_RTTI(GfxSystem);
IMPLEMENT_RTTI(GfxRenderNode);
class GfxSystem::Impl
{
public:
Impl(Transforms& iTrans)
: m_Transforms(iTrans)
{
}
Vector2i m_ViewportSize;
float m_NearP;
float m_FarP;
Vector4f m_ClearColor;
float m_ClearDepth;
CameraMatrix m_Camera;
GfxDebugDrawer* m_DebugDrawer;
GfxComponentRenderNode* m_ComponentsNode;
GfxSpriteRenderNode* m_SpriteNode;
IntrusivePtr<OGLBuffer> m_CameraBuffer;
Transforms& m_Transforms;
OGLSemanticManager m_Semantics;
struct RenderNodeEntry
{
UniquePtr<GfxRenderNode> m_Node;
GfxRenderNode::TransformUpdateCallback m_OnTransform;
GfxRenderNode::UpdateCallback m_OnDelete;
Vector<ObjectHandle> m_UpdateArray;
Vector<Matrix4f const*> m_TransUpdateArray;
};
using RenderNodes = ObjectTable<RenderNodeEntry>;
using RenderNodeHandle = RenderNodes::Handle;
RenderNodes m_Nodes;
RenderNodeHandle m_DebugDrawerHandle;
RenderNodeHandle m_SpriteHandle;
Vector<RenderNodeHandle> m_ObjectToNode;
};
OGLSemanticManager& GfxSystem::GetSemanticManager()
{
return m_Impl->m_Semantics;
}
void GfxSystem::ScreenToWorld(Vector2i const& iScreenPos, Vector3f& oWorldPos, Vector3f& oViewDir)
{
Vector2f screenSpacePos(( 2.0 * float(iScreenPos.X()) / m_Impl->m_ViewportSize.X() - 1.0),
((1.0 - 2.0 * float(iScreenPos.Y()) / m_Impl->m_ViewportSize.Y())));
Vector4f screenPos(screenSpacePos.X(), screenSpacePos.Y(), m_Impl->m_NearP, 1.0);
Vector4f screenPosF(screenSpacePos.X(), screenSpacePos.Y(), m_Impl->m_NearP + (m_Impl->m_FarP - m_Impl->m_NearP) * 0.1, 1.0);
Matrix4f invMat = m_Impl->m_Camera.projMatrix * m_Impl->m_Camera.viewMatrix;
invMat = invMat.Inverse();
Vector4f worldPt = invMat * screenPos;
Vector4f worldPtF = invMat * screenPosF;
oWorldPos = reinterpret_cast<Vector3f&>(worldPt);
oViewDir = reinterpret_cast<Vector3f&>(worldPtF) - oWorldPos;
oViewDir.Normalize();
}
Vector2i GfxSystem::WorldToScreen(Vector3f const& iWorldPos)
{
Vector4f worldPos(iWorldPos.X(), iWorldPos.Y(), iWorldPos.Z(), 1.0);
Vector4f projectedPt = m_Impl->m_Camera.projMatrix * m_Impl->m_Camera.viewMatrix * worldPos;
return Vector2i(((projectedPt.X() * 0.5) + 0.5) * m_Impl->m_ViewportSize.X()
, (0.5 - ((projectedPt.Y() * 0.5))) * m_Impl->m_ViewportSize.Y());
}
void GfxSystem::StaticInit()
{
static bool s_StaticInitDone = false;
if (!s_StaticInitDone)
{
OGLUtils::Init();
OGLProgramInterface::InitStaticData();
s_StaticInitDone = true;
}
}
GfxSystem::GfxSystem(Transforms& iTransforms)
: m_Impl(new Impl(iTransforms))
{
OGLBaseAlgo::Init(m_Impl->m_Semantics);
m_Impl->m_DebugDrawer = eXl_NEW GfxDebugDrawer;
m_Impl->m_DebugDrawerHandle = Impl::RenderNodeHandle(AddRenderNode(UniquePtr<GfxRenderNode>(m_Impl->m_DebugDrawer)));
m_Impl->m_ComponentsNode = eXl_NEW GfxComponentRenderNode;
AddRenderNode(UniquePtr<GfxRenderNode>(m_Impl->m_ComponentsNode));
m_Impl->m_SpriteNode = eXl_NEW GfxSpriteRenderNode;
m_Impl->m_SpriteHandle = Impl::RenderNodeHandle(AddRenderNode(UniquePtr<GfxRenderNode>(m_Impl->m_SpriteNode)));
}
GfxRenderNodeHandle GfxSystem::GetDebugDrawerHandle()
{
return m_Impl->m_DebugDrawerHandle;
}
GfxRenderNodeHandle GfxSystem::GetSpriteHandle()
{
return m_Impl->m_SpriteHandle;
}
OGLCompiledProgram const* GfxSystem::GetSpriteProgram()
{
return m_Impl->m_SpriteNode->GetSpriteProgram();
}
OGLCompiledProgram const* GfxSystem::GetLineProgram()
{
return m_Impl->m_DebugDrawer->GetLineProgram();
}
GfxSystem::~GfxSystem() = default;
Transforms& GfxSystem::GetTransforms()
{
return m_Impl->m_Transforms;
}
DebugTool::Drawer* GfxSystem::GetDebugDrawer()
{
return m_Impl->m_DebugDrawer;
}
void GfxSystem::EnableDebugDraw()
{
DebugTool::SetDrawer(m_Impl->m_DebugDrawer);
}
void GfxSystem::DisableDebugDraw()
{
DebugTool::SetDrawer(nullptr);
}
GfxComponent& GfxSystem::CreateComponent(ObjectHandle iObject)
{
m_Impl->m_ComponentsNode->AddObject(iObject);
return *m_Impl->m_ComponentsNode->GetComponent(iObject);
}
GfxComponent* GfxSystem::GetComponent(ObjectHandle iObject)
{
if (GetWorld().IsObjectValid(iObject))
{
return m_Impl->m_ComponentsNode->GetComponent(iObject);
}
return nullptr;
}
GfxSpriteComponent& GfxSystem::CreateSpriteComponent(ObjectHandle iObject)
{
eXl_ASSERT(GetWorld().IsObjectValid(iObject));
m_Impl->m_SpriteNode->AddObject(iObject);
return *m_Impl->m_SpriteNode->GetComponent(iObject);
}
GfxSpriteComponent* GfxSystem::GetSpriteComponent(ObjectHandle iObject)
{
if (GetWorld().IsObjectValid(iObject))
{
return m_Impl->m_SpriteNode->GetComponent(iObject);
}
return nullptr;
}
void GfxSystem::DeleteComponent(ObjectHandle iObject)
{
if(m_Impl->m_ObjectToNode.size() > iObject.GetId()
&& m_Impl->m_ObjectToNode[iObject.GetId()].IsAssigned())
{
auto const& nodeEntry = m_Impl->m_Nodes.Get(m_Impl->m_ObjectToNode[iObject.GetId()]);
if (nodeEntry.m_OnDelete)
{
nodeEntry.m_OnDelete(&iObject, 1);
}
m_Impl->m_ObjectToNode[iObject.GetId()] = Impl::RenderNodeHandle();
}
ComponentManager::DeleteComponent(iObject);
}
Vector2i GfxSystem::GetViewportSize() const
{
return m_Impl->m_ViewportSize;
}
void GfxSystem::SynchronizeTransforms()
{
m_Impl->m_Transforms.IterateOverDirtyTransforms([this](Matrix4f const& iMat, ObjectHandle iObj)
{
if (m_Impl->m_ObjectToNode.size() > iObj.GetId()
&& m_Impl->m_ObjectToNode[iObj.GetId()].IsAssigned())
{
auto& nodeEntry = m_Impl->m_Nodes.Get(m_Impl->m_ObjectToNode[iObj.GetId()]);
if (nodeEntry.m_OnTransform)
{
nodeEntry.m_UpdateArray.push_back(iObj);
nodeEntry.m_TransUpdateArray.push_back(&iMat);
}
}
});
m_Impl->m_Nodes.Iterate([](Impl::RenderNodeEntry& iNode, Impl::RenderNodeHandle)
{
if (!iNode.m_UpdateArray.empty())
{
iNode.m_OnTransform(iNode.m_UpdateArray.data(), iNode.m_TransUpdateArray.data(), iNode.m_UpdateArray.size());
iNode.m_UpdateArray.clear();
iNode.m_TransUpdateArray.clear();
}
});
}
CameraMatrix const& GfxSystem::GetCurrentCamera()
{
return m_Impl->m_Camera;
}
void GfxSystem::SetView(ViewInfo const& iInfo)
{
m_Impl->m_ViewportSize = iInfo.viewportSize;
m_Impl->m_Camera.projMatrix.MakeZero();
m_Impl->m_Camera.viewInverseMatrix.MakeIdentity();
float screenRatio = float(m_Impl->m_ViewportSize.X()) / float(m_Impl->m_ViewportSize.Y());
bool ortho = iInfo.projection == Orthographic;
if (ortho)
{
m_Impl->m_NearP = 0.0001;
m_Impl->m_FarP = iInfo.displayedSize * 100.0;
m_Impl->m_Camera.projMatrix.m_Data[0] = 2.0 / (iInfo.displayedSize * screenRatio);
m_Impl->m_Camera.projMatrix.m_Data[5] = 2.0 / iInfo.displayedSize;
m_Impl->m_Camera.projMatrix.m_Data[10] = -2.0 / (m_Impl->m_FarP - m_Impl->m_NearP);
m_Impl->m_Camera.projMatrix.m_Data[14] = -(m_Impl->m_FarP + m_Impl->m_NearP) / (m_Impl->m_FarP - m_Impl->m_NearP);
m_Impl->m_Camera.projMatrix.m_Data[15] = 1.0;
}
else
{
m_Impl->m_NearP = iInfo.displayedSize * 0.5 / tan(iInfo.fov * 0.5);
m_Impl->m_FarP = iInfo.displayedSize * 1000;
m_Impl->m_Camera.projMatrix.m_Data[0] = 2.0 * m_Impl->m_NearP / screenRatio;
m_Impl->m_Camera.projMatrix.m_Data[5] = 2.0 * m_Impl->m_NearP;
m_Impl->m_Camera.projMatrix.m_Data[10] = -1.0* (m_Impl->m_NearP + m_Impl->m_FarP) / (m_Impl->m_FarP - m_Impl->m_NearP);
m_Impl->m_Camera.projMatrix.m_Data[14] = -2.0 * m_Impl->m_NearP * m_Impl->m_FarP / (m_Impl->m_FarP - m_Impl->m_NearP);
m_Impl->m_Camera.projMatrix.m_Data[11] = -1.0;
}
Vector3f basisX = iInfo.basis[0];
Vector3f basisY = iInfo.basis[1];
Vector3f basisZ = iInfo.basis[2];
memcpy(m_Impl->m_Camera.viewInverseMatrix.m_Data + 0, &basisX, sizeof(Vector3f));
memcpy(m_Impl->m_Camera.viewInverseMatrix.m_Data + 4, &basisY, sizeof(Vector3f));
memcpy(m_Impl->m_Camera.viewInverseMatrix.m_Data + 8, &basisZ, sizeof(Vector3f));
//Vector3f transPos = basisX * (-iInfo.pos.X()) + basisY * (-iInfo.pos.Y()) + basisZ * (-iInfo.pos.Z());
m_Impl->m_Camera.viewInverseMatrix.m_Data[12] = iInfo.pos.X();
m_Impl->m_Camera.viewInverseMatrix.m_Data[13] = iInfo.pos.Y();
m_Impl->m_Camera.viewInverseMatrix.m_Data[14] = iInfo.pos.Z();
m_Impl->m_Camera.viewMatrix = m_Impl->m_Camera.viewInverseMatrix.Inverse();
// Will work for ortho, but not persp.
m_Impl->m_DebugDrawer->m_CurrentScreenSize = iInfo.displayedSize;
m_Impl->m_ClearColor = iInfo.backgroundColor;
//m_Impl->m_ClearDepth = 1.0;
}
void GfxSystem::RenderFrame(float iDelta)
{
if (!m_Impl->m_CameraBuffer)
{
m_Impl->m_CameraBuffer = OGLBuffer::CreateBuffer(OGLBufferUsage::UNIFORM_BUFFER, CameraMatrix::GetType()->GetSize(), nullptr);
}
m_Impl->m_Nodes.Iterate([&](Impl::RenderNodeEntry& iNode, Impl::RenderNodeHandle iNodeHandle)
{
if (iNode.m_Node->m_Sys == nullptr)
{
iNode.m_Node->Init(*this, iNodeHandle);
}
});
OGLDisplayList list(GetSemanticManager());
list.SetDefaultViewport(Vector2i::ZERO, m_Impl->m_ViewportSize);
list.SetDefaultDepth(true, true);
list.SetDefaultScissor(Vector2i(0,0),Vector2i(-1,-1));
list.SetDefaultBlend(true, OGLBlend::SRC_ALPHA, OGLBlend::ONE_MINUS_SRC_ALPHA);
list.InitForPush();
list.Clear(0,true,true, m_Impl->m_ClearColor);
OGLShaderData camData;
//camData.AddData(OGLBaseAlgo::GetCameraUniform(), &m_Impl->m_Camera);
m_Impl->m_CameraBuffer->SetData(0, sizeof(m_Impl->m_Camera), &m_Impl->m_Camera);
camData.SetDataBuffer(OGLBaseAlgo::GetCameraUniform(), m_Impl->m_CameraBuffer);
list.PushData(&camData);
List<GfxComponent*> toDelete;
m_Impl->m_Nodes.Iterate([&](Impl::RenderNodeEntry& iNode, Impl::RenderNodeHandle)
{
iNode.m_Node->Push(list, iDelta);
});
OGLRenderContext renderContext(GetSemanticManager());
list.Render(&renderContext);
}
GfxRenderNodeHandle GfxSystem::AddRenderNode(UniquePtr<GfxRenderNode> iNode)
{
if (!iNode)
{
return GfxRenderNodeHandle();
}
Impl::RenderNodeHandle nodeHandle = m_Impl->m_Nodes.Alloc();
auto& entry = m_Impl->m_Nodes.Get(nodeHandle);
entry.m_Node = std::move(iNode);
entry.m_OnTransform = entry.m_Node->GetTransformUpdateCallback();
entry.m_OnDelete = entry.m_Node->GetDeleteCallback();
return nodeHandle;
}
GfxRenderNode* GfxSystem::GetRenderNode(GfxRenderNodeHandle iNodeHandle)
{
Impl::RenderNodeEntry* entry = m_Impl->m_Nodes.TryGet(Impl::RenderNodeHandle(iNodeHandle));
if (entry != nullptr)
{
return entry->m_Node.get();
}
return nullptr;
}
void GfxRenderNode::AddObject(ObjectHandle iObject)
{
eXl_ASSERT_REPAIR_RET(m_Sys != nullptr, void());
eXl_ASSERT_REPAIR_RET(m_Sys->GetWorld().IsObjectValid(iObject), void());
auto& nodeAssocArray = m_Sys->GetImpl().m_ObjectToNode;
while (nodeAssocArray.size() <= iObject.GetId())
{
nodeAssocArray.push_back(GfxSystem::Impl::RenderNodeHandle());
}
GfxSystem::Impl::RenderNodeHandle& entry = nodeAssocArray[iObject.GetId()];
eXl_ASSERT_REPAIR_RET(!entry.IsAssigned() || entry == m_NodeHandle, void());
entry = GfxSystem::Impl::RenderNodeHandle(m_NodeHandle);
m_Sys->ComponentManager::CreateComponent(iObject);
}
} | 33.157107 | 460 | 0.705024 | [
"render",
"vector"
] |
eb32e931b12bab43fb441c04ce50eef6b967bb78 | 11,624 | cpp | C++ | debugger.cpp | 5cript/debugger-interface | 61d6fd73275b2240f61f19a3978015d9bb0c1e3c | [
"MIT"
] | null | null | null | debugger.cpp | 5cript/debugger-interface | 61d6fd73275b2240f61f19a3978015d9bb0c1e3c | [
"MIT"
] | null | null | null | debugger.cpp | 5cript/debugger-interface | 61d6fd73275b2240f61f19a3978015d9bb0c1e3c | [
"MIT"
] | null | null | null | #include "debugger.hpp"
#include "process/process.hpp"
#include "input_parser.hpp"
#include "input/stream_record.hpp"
#include "input/async_record.hpp"
#include "distributing_listener.hpp"
#include <sstream>
#include <string>
#include <iostream>
using namespace std::string_literals;
namespace DebuggerInterface
{
//#####################################################################################################################
struct DebuggerImpl
{
std::unique_ptr <Process> process;
std::vector <ListenerInterface*> listeners;
DistributingListener distributor;
DebuggerImpl()
: process{}
, listeners{}
, distributor{&listeners}
{
}
~DebuggerImpl() = default;
};
//#####################################################################################################################
Debugger::Debugger(GdbRunArguments args)
: args_{std::move(args)}
, impl_{new DebuggerImpl}
{
}
//---------------------------------------------------------------------------------------------------------------------
Debugger::Debugger(LldbRunArguments args)
: args_{std::move(args)}
, impl_{new DebuggerImpl}
{
}
//---------------------------------------------------------------------------------------------------------------------
Debugger::Debugger(UserDefinedArguments args)
: args_{std::move(args)}
, impl_{new DebuggerImpl}
{
}
//---------------------------------------------------------------------------------------------------------------------
Debugger::~Debugger() = default;
//---------------------------------------------------------------------------------------------------------------------
std::string Debugger::constructCommand(GdbRunArguments const& args) const
{
std::stringstream command;
// gdb executable
command << args.debuggerExecuteable << ' ';
// options
if (args.sourceDirectory)
command << "--directory=" << args.sourceDirectory.value() << ' ';
if (args.symbols)
command << "--symbols=" << args.symbols.value() << ' ';
if (args.fullyReadSymbols)
command << "--readnow ";
if (args.neverReadSymbols)
command << "--readnever ";
if (args.write)
command << "--write ";
if (args.initCommandFile)
command << "--init-command=" << args.initCommandFile.value() << ' ';
if (args.commandFile)
command << "--command=" << args.commandFile.value() << ' ';
if (args.ignoreHomeGdbInit)
command << "--nh ";
if (args.ignoreAllGdbInit)
command << "--nx ";
if (args.returnChildResult)
command << "--return-child-result ";
if (args.quiet)
command << "-q ";
if (args.gdbDataDirectory)
command << "--data-directory=" << args.gdbDataDirectory.value() << ' ';
// gdb mi
command << "--interpreter=mi ";
// args
if (args.args)
command << "--args ";
// executable
if (args.program)
command << args.program.value() << ' ';
if (args.args)
command << args.args.value();
else
{
// core dump or pid
if (args.core)
command << args.core.value();
else if (args.pid)
command << args.pid.value();
}
return command.str();
}
//---------------------------------------------------------------------------------------------------------------------
std::string Debugger::constructCommand(LldbRunArguments const& args) const
{
std::stringstream command;
// gdb executable
command << args.debuggerExecuteable << ' ';
if (args.program)
command << args.program.value() << ' ';
return command.str();
}
//---------------------------------------------------------------------------------------------------------------------
std::string Debugger::constructCommand(UserDefinedArguments const& args) const
{
std::string com = args.debuggerExecuteable;
if (args.program)
com += " "s + args.program.value();
com += " --interpreter=mi ";
com += args.commandline;
return com;
}
//---------------------------------------------------------------------------------------------------------------------
std::string Debugger::constructCommand() const
{
std::string res;
std::visit([this, &res](auto const& args) {
res = constructCommand(args);
}, args_);
return res;
}
//---------------------------------------------------------------------------------------------------------------------
void Debugger::start()
{
std::visit([this](auto const& args)
{
std::string path = args.directory ? args.directory.value() : "";
std::cout << constructCommand() << "\n";
if (args.environment)
{
impl_->process.reset(new Process{
constructCommand(),
path,
args.environment.value(),
[this](char const* c, auto count){stdoutConsumer(std::string{c, count});},
[this](char const* c, auto count){stderrConsumer(std::string{c, count});},
true
});
}
else
{
impl_->process.reset(new Process{
constructCommand(),
path,
[this](char const* c, auto count){stdoutConsumer(std::string{c, count});},
[this](char const* c, auto count){stderrConsumer(std::string{c, count});},
true
});
}
}, args_);
}
//---------------------------------------------------------------------------------------------------------------------
std::optional<long long> Debugger::tryGetExitStatus() const
{
if (!impl_->process)
return std::nullopt;
int status = -100'000;
if (!impl_->process->try_get_exit_status(status))
return std::nullopt;
return static_cast <long long>(status);
}
//---------------------------------------------------------------------------------------------------------------------
void Debugger::feed(std::string const& str)
{
stdoutConsumer(str);
}
//---------------------------------------------------------------------------------------------------------------------
void Debugger::stdoutConsumer(std::string const& instream)
{
auto& sender = impl_->distributor;
sender.onRawData(instream);
try
{
bool partialParse = false;
int amountConsumed = 0;
auto message = parse(instream, partialParse, amountConsumed);
if (partialParse)
{
sender.onPartialRemain(instream.substr(amountConsumed, instream.size() - amountConsumed), instream);
}
if (message.result)
sender.onResult(message.result.value());
for (auto const& i : message.oobRecords)
{
StreamRecord* srecord = dynamic_cast <StreamRecord*> (i.get());
if (srecord)
{
switch(srecord->type)
{
case(StreamRecordType::Console):
{
sender.onConsoleStream(srecord->data);
break;
}
case(StreamRecordType::Target):
{
sender.onTargetStream(srecord->data);
break;
}
case(StreamRecordType::Log):
{
sender.onLogStream(srecord->data);
break;
}
}
}
else
{
AsyncRecord* arecord = dynamic_cast <AsyncRecord*> (i.get());
if (arecord)
{
switch(arecord->type)
{
case(AsyncRecordType::Exec):
{
sender.onExec(*arecord);
break;
}
case(AsyncRecordType::Notify):
{
sender.onNotify(*arecord);
break;
}
case(AsyncRecordType::Status):
{
sender.onStatus(*arecord);
break;
}
}
}
else
{
sender.onParserError("unknown record received?");
}
}
}
}
catch (std::exception const& exc)
{
sender.onParserError(exc.what());
}
}
//---------------------------------------------------------------------------------------------------------------------
void Debugger::stderrConsumer(std::string const& instream)
{
impl_->distributor.onStdErr(instream);
}
//---------------------------------------------------------------------------------------------------------------------
void Debugger::registerListener(ListenerInterface* listener)
{
impl_->listeners.push_back(listener);
}
//---------------------------------------------------------------------------------------------------------------------
void Debugger::sendCommand(MiCommand const& command)
{
auto com = synthesize(command);
std::cout << "synthesized command: " << com << "\n";
impl_->process->write(com);
}
//---------------------------------------------------------------------------------------------------------------------
void Debugger::sendCommand(std::string const& command)
{
impl_->process->write(command);
}
//---------------------------------------------------------------------------------------------------------------------
void Debugger::stop()
{
sendCommand(MiCommand{"quit"});
}
//---------------------------------------------------------------------------------------------------------------------
long long Debugger::waitForProcess() const
{
return impl_->process->get_exit_status();
}
//---------------------------------------------------------------------------------------------------------------------
void Debugger::forceKill()
{
impl_->process->kill(true);
}
//#####################################################################################################################
}
| 37.25641 | 120 | 0.356074 | [
"vector"
] |
eb350a3c10972ef34dee0e424334e4f09ec0a8fb | 9,427 | cpp | C++ | UAlbertaBot/Source/BaseLocation.cpp | KristianRungo/SneakBot | 77bd3f4b31a0a9281089a93d4817d9741d942348 | [
"MIT"
] | null | null | null | UAlbertaBot/Source/BaseLocation.cpp | KristianRungo/SneakBot | 77bd3f4b31a0a9281089a93d4817d9741d942348 | [
"MIT"
] | null | null | null | UAlbertaBot/Source/BaseLocation.cpp | KristianRungo/SneakBot | 77bd3f4b31a0a9281089a93d4817d9741d942348 | [
"MIT"
] | null | null | null |
#include "Common.h"
#include "BaseLocation.h"
#include "MapTools.h"
#include "Global.h"
#include <sstream>
#include <iostream>
using namespace UAlbertaBot;
const int NearBaseLocationTileDistance = 20;
BaseLocation::BaseLocation(int baseID, const std::vector<BWAPI::Unit> & resources)
: m_baseID(baseID)
{
PROFILE_FUNCTION();
m_isPlayerStartLocation[BWAPI::Broodwar->self()] = false;
m_isPlayerStartLocation[BWAPI::Broodwar->enemy()] = false;
m_isPlayerOccupying[BWAPI::Broodwar->self()] = false;
m_isPlayerOccupying[BWAPI::Broodwar->enemy()] = false;
int resourceCenterX = 0;
int resourceCenterY = 0;
// add each of the resources to its corresponding container
for (auto & resource : resources)
{
if (resource->getType().isMineralField())
{
m_minerals.push_back(resource);
m_mineralPositions.push_back(resource->getPosition());
// add the position of the minerals to the center
resourceCenterX += resource->getPosition().x;
resourceCenterY += resource->getPosition().y;
}
else
{
m_geysers.push_back(resource);
m_geyserPositions.push_back(resource->getPosition());
// pull the resource center toward the geyser if it exists
resourceCenterX += resource->getPosition().x;
resourceCenterY += resource->getPosition().y;
}
// set the limits of the base location bounding box
const int resWidth = 32;
const int resHeight = 32;
m_left = std::min(m_left, resource->getPosition().x - resWidth);
m_right = std::max(m_right, resource->getPosition().x + resWidth);
m_top = std::max(m_top, resource->getPosition().y + resHeight);
m_bottom = std::min(m_bottom, resource->getPosition().y - resHeight);
}
// calculate the center of the resources
const size_t numResources = m_minerals.size() + m_geysers.size();
m_centerOfResources = BWAPI::Position(m_left + (m_right-m_left)/2, m_top + (m_bottom-m_top)/2);
// compute this BaseLocation's DistanceMap, which will compute the ground distance
// from the center of its recourses to every other tile on the map
m_distanceMap = DistanceMap();
m_distanceMap.computeDistanceMap(BWAPI::TilePosition(m_centerOfResources));
// check to see if this is a start location for the map
for (auto & startTilePos : BWAPI::Broodwar->getStartLocations())
{
auto groundDistance = getGroundDistance(startTilePos);
if (containsPosition(BWAPI::Position(startTilePos)))
{
m_isStartLocation = true;
m_depotPosition = BWAPI::TilePosition(startTilePos);
m_startPosition = startTilePos;
break;
}
}
// if this base location position is near our own resource depot, it's our start location
for (auto & unit : BWAPI::Broodwar->getAllUnits())
{
if (unit->getPlayer() == BWAPI::Broodwar->self() && unit->getType().isResourceDepot())
{
if (containsPosition(unit->getPosition()))
{
m_isPlayerStartLocation[BWAPI::Broodwar->self()] = true;
m_isStartLocation = true;
m_isPlayerOccupying[BWAPI::Broodwar->self()] = true;
break;
}
}
}
// if it's not a start location, we need to calculate the depot position
if (!isStartLocation())
{
const BWAPI::UnitType depot = BWAPI::Broodwar->self()->getRace().getResourceDepot();
const int offsetX = 1;
const int offsetY = 1;
// the position of the depot will be the closest spot we can build one from the resource center
for (auto & tile : getClosestTiles())
{
// the build position will be up-left of where this tile is
// this means we are positioning the center of the resouce depot
const BWAPI::TilePosition buildTile(tile.x - offsetX, tile.y - offsetY);
if (BWAPI::Broodwar->canBuildHere(buildTile, depot))
{
m_depotPosition = buildTile;
break;
}
}
}
}
// TODO: calculate the actual depot position
const BWAPI::TilePosition & BaseLocation::getDepotPosition() const
{
return m_depotPosition;
}
void BaseLocation::setPlayerOccupying(BWAPI::Player player, bool occupying)
{
m_isPlayerOccupying[player] = occupying;
// if this base is a start location that's occupied by the enemy, it's that enemy's start location
if (occupying && player == BWAPI::Broodwar->enemy() && isStartLocation() && m_isPlayerStartLocation[player] == false)
{
m_isPlayerStartLocation[player] = true;
}
}
bool BaseLocation::isInResourceBox(int tileX, int tileY) const
{
const int px = tileX * 32;
const int py = tileY * 32;
return px >= m_left && px < m_right && py < m_top && py >= m_bottom;
}
bool BaseLocation::isOccupiedByPlayer(BWAPI::Player player) const
{
return m_isPlayerOccupying.at(player);
}
bool BaseLocation::isExplored() const
{
return BWAPI::Broodwar->isExplored(BWAPI::TilePosition(m_centerOfResources));
}
bool BaseLocation::isPlayerStartLocation(BWAPI::Player player) const
{
return m_isPlayerStartLocation.at(player);
}
bool BaseLocation::isConnected(const BWAPI::Position& pos) const
{
return getGroundDistance(pos) >= 0;
}
bool BaseLocation::containsPosition(const BWAPI::Position & pos) const
{
if (!pos.isValid() || (pos.x == 0 && pos.y == 0) || !isConnected(pos))
{
return false;
}
return (getGroundDistance(pos) < NearBaseLocationTileDistance);
}
const std::vector<BWAPI::Unit> & BaseLocation::getGeysers() const
{
return m_geysers;
}
const std::vector<BWAPI::Unit> & BaseLocation::getMinerals() const
{
return m_minerals;
}
const BWAPI::Position & BaseLocation::getPosition() const
{
return m_centerOfResources;
}
int BaseLocation::getGroundDistance(const BWAPI::Position & pos) const
{
return m_distanceMap.getDistance(pos);
}
int BaseLocation::getGroundDistance(const BWAPI::TilePosition & pos) const
{
return m_distanceMap.getDistance(pos);
}
bool BaseLocation::isStartLocation() const
{
return m_isStartLocation;
}
const std::vector<BWAPI::TilePosition> & BaseLocation::getClosestTiles() const
{
return m_distanceMap.getSortedTiles();
}
void BaseLocation::draw()
{
int radius = 16;
BWAPI::Broodwar->drawCircleMap(m_centerOfResources, 16, BWAPI::Color(255, 255, 0), true);
if (m_startPosition.x != 0)
{
BWAPI::Broodwar->drawLineMap(m_centerOfResources, BWAPI::Position(m_startPosition), BWAPI::Colors::Red);
}
std::stringstream ss;
ss << "BaseLocation: " << m_baseID << "\n";
ss << "Start Loc: " << (isStartLocation() ? "true" : "false") << "\n";
ss << "Minerals: " << m_mineralPositions.size() << "\n";
ss << "Geysers: " << m_geyserPositions.size() << "\n";
ss << "Occupied By: ";
if (isOccupiedByPlayer(BWAPI::Broodwar->self()))
{
ss << "Self ";
}
if (isOccupiedByPlayer(BWAPI::Broodwar->enemy()))
{
ss << "Enemy ";
}
BWAPI::Broodwar->drawTextMap(BWAPI::Position(m_left, m_top + 3), ss.str().c_str());
BWAPI::Broodwar->drawTextMap(BWAPI::Position(m_left, m_bottom), ss.str().c_str());
// draw the base bounding box
BWAPI::Broodwar->drawLineMap(m_left, m_top, m_right, m_top, BWAPI::Colors::White);
BWAPI::Broodwar->drawLineMap(m_right, m_top, m_right, m_bottom, BWAPI::Colors::White);
BWAPI::Broodwar->drawLineMap(m_right, m_bottom, m_left, m_bottom, BWAPI::Colors::White);
BWAPI::Broodwar->drawLineMap(m_left, m_bottom, m_left, m_top, BWAPI::Colors::White);
for (auto & mineralPos : m_mineralPositions)
{
const BWAPI::TilePosition mineralTile(mineralPos);
(mineralTile.x, mineralTile.y, BWAPI::Color(0, 255, 255));
Global::Map().drawTile(mineralTile.x-1, mineralTile.y, BWAPI::Color(0, 255, 255));
}
for (auto & geyserPos : m_geyserPositions)
{
const BWAPI::TilePosition geyserTile(geyserPos);
Global::Map().drawTile(geyserTile.x, geyserTile.y, BWAPI::Color(0, 255, 0));
Global::Map().drawTile(geyserTile.x+1, geyserTile.y, BWAPI::Color(0, 255, 0));
Global::Map().drawTile(geyserTile.x-1, geyserTile.y, BWAPI::Color(0, 255, 0));
Global::Map().drawTile(geyserTile.x-2, geyserTile.y, BWAPI::Color(0, 255, 0));
Global::Map().drawTile(geyserTile.x, geyserTile.y-1, BWAPI::Color(0, 255, 0));
Global::Map().drawTile(geyserTile.x+1, geyserTile.y-1, BWAPI::Color(0, 255, 0));
Global::Map().drawTile(geyserTile.x-1, geyserTile.y-1, BWAPI::Color(0, 255, 0));
Global::Map().drawTile(geyserTile.x-2, geyserTile.y-1, BWAPI::Color(0, 255, 0));
BWAPI::Broodwar->drawCircleMap(geyserPos, radius, BWAPI::Color(0, 255, 0), true);
}
if (m_isStartLocation)
{
BWAPI::Broodwar->drawCircleMap(BWAPI::Position(m_depotPosition), radius, BWAPI::Color(255, 0, 0));
}
BWAPI::Broodwar->drawBoxMap(m_depotPosition.x, m_depotPosition.y, m_depotPosition.x+32, m_depotPosition.y+32, BWAPI::Color(0, 0, 255));
//m_distanceMap.draw();
}
bool BaseLocation::isMineralOnly() const
{
return getGeysers().empty();
} | 33.193662 | 139 | 0.647608 | [
"vector"
] |
eb362a83ac8b0fb406ae472a5bbc6c4235053613 | 10,647 | hxx | C++ | Modules/Segmentation/LevelSetsv4/include/itkLevelSetEvolutionComputeIterationThreader.hxx | rdsouza10/ITK | 07cb23f9866768b5f4ee48ebec8766b6e19efc69 | [
"Apache-2.0"
] | 3 | 2019-11-19T09:47:25.000Z | 2022-02-24T00:32:31.000Z | Modules/Segmentation/LevelSetsv4/include/itkLevelSetEvolutionComputeIterationThreader.hxx | JamesLinus/ITK | 01fb2f2a97ae7767b7835dd92b40b6cc2c82e750 | [
"Apache-2.0"
] | 1 | 2019-03-18T14:19:49.000Z | 2020-01-11T13:54:33.000Z | Modules/Segmentation/LevelSetsv4/include/itkLevelSetEvolutionComputeIterationThreader.hxx | JamesLinus/ITK | 01fb2f2a97ae7767b7835dd92b40b6cc2c82e750 | [
"Apache-2.0"
] | 1 | 2022-02-24T00:32:36.000Z | 2022-02-24T00:32:36.000Z | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkLevelSetEvolutionComputeIterationThreader_hxx
#define itkLevelSetEvolutionComputeIterationThreader_hxx
#include "itkLevelSetEvolutionComputeIterationThreader.h"
#include "itkImageRegionConstIteratorWithIndex.h"
namespace itk
{
template< typename TImage, typename TLevelSetEvolution >
LevelSetEvolutionComputeIterationThreader< LevelSetDenseImage< TImage >, ThreadedImageRegionPartitioner< TImage::ImageDimension >, TLevelSetEvolution >
::LevelSetEvolutionComputeIterationThreader()
{
}
template< typename TImage, typename TLevelSetEvolution >
void
LevelSetEvolutionComputeIterationThreader< LevelSetDenseImage< TImage >, ThreadedImageRegionPartitioner< TImage::ImageDimension >, TLevelSetEvolution >
::ThreadedExecution( const DomainType & imageSubRegion,
const ThreadIdType itkNotUsed(threadId) )
{
typename LevelSetContainerType::Iterator levelSetContainerIt = this->m_Associate->m_LevelSetContainer->Begin();
typename LevelSetType::Pointer levelSet = levelSetContainerIt->GetLevelSet();
typename LevelSetImageType::ConstPointer levelSetImage = levelSet->GetImage();
// Identify the level-set region
OffsetType offset = levelSet->GetDomainOffset();
IndexType index = imageSubRegion.GetIndex() - offset;
RegionType subRegion;
subRegion.SetSize( imageSubRegion.GetSize() );
subRegion.SetIndex( index );
ImageRegionConstIteratorWithIndex< LevelSetImageType > imageIt( levelSetImage, subRegion );
imageIt.GoToBegin();
if( this->m_Associate->m_LevelSetContainer->HasDomainMap() )
{
const IdListType * idList = this->m_Associate->m_IdListToProcessWhenThreading;
// Avoid repeated map lookups.
const size_t numberOfLevelSets = idList->size();
std::vector< LevelSetImageType * > levelSetUpdateImages( numberOfLevelSets );
std::vector< TermContainerType * > termContainers( numberOfLevelSets );
IdListConstIterator idListIt = idList->begin();
unsigned int idListIdx = 0;
while( idListIt != idList->end() )
{
//! \todo Fix me for string identifiers
LevelSetType * levelSetUpdate = this->m_Associate->m_UpdateBuffer->GetLevelSet( *idListIt - 1 );
levelSetUpdateImages[idListIdx] = levelSetUpdate->GetModifiableImage();
termContainers[idListIdx] = this->m_Associate->m_EquationContainer->GetEquation( *idListIt - 1 );
++idListIt;
++idListIdx;
}
while( !imageIt.IsAtEnd() )
{
const IndexType levelSetIndex = imageIt.GetIndex();
const IndexType inputIndex = imageIt.GetIndex() + offset;
for( idListIdx = 0; idListIdx < numberOfLevelSets; ++idListIdx )
{
LevelSetDataType characteristics;
termContainers[idListIdx]->ComputeRequiredData( inputIndex, characteristics );
LevelSetOutputRealType temp_update = termContainers[idListIdx]->Evaluate( inputIndex, characteristics );
levelSetUpdateImages[idListIdx]->SetPixel( levelSetIndex, temp_update );
}
++imageIt;
}
}
else
{
// This is for single level set analysis, so we only process the first level
// set.
typename LevelSetContainerType::ConstIterator levelSetUpdateContainerIt = this->m_Associate->m_UpdateBuffer->Begin();
typename LevelSetType::Pointer levelSetUpdate = levelSetUpdateContainerIt->GetLevelSet();
typename LevelSetImageType::Pointer levelSetUpdateImage = levelSetUpdate->GetModifiableImage();
typename EquationContainerType::Iterator equationContainerIt = this->m_Associate->m_EquationContainer->Begin();
typename TermContainerType::Pointer termContainer = equationContainerIt->GetEquation();
imageIt.GoToBegin();
while( !imageIt.IsAtEnd() )
{
const IndexType levelSetIndex = imageIt.GetIndex();
const IndexType inputIndex = imageIt.GetIndex() + offset;
LevelSetDataType characteristics;
termContainer->ComputeRequiredData( inputIndex, characteristics );
LevelSetOutputRealType temp_update = termContainer->Evaluate( inputIndex, characteristics );
levelSetUpdateImage->SetPixel( levelSetIndex, temp_update );
++imageIt;
}
}
}
template< typename TImage, typename TLevelSetEvolution >
LevelSetEvolutionComputeIterationThreader<
LevelSetDenseImage< TImage >,
ThreadedIteratorRangePartitioner< typename TLevelSetEvolution::DomainMapImageFilterType::DomainMapType::const_iterator >,
TLevelSetEvolution >
::LevelSetEvolutionComputeIterationThreader()
{
}
template< typename TImage, typename TLevelSetEvolution >
void
LevelSetEvolutionComputeIterationThreader<
LevelSetDenseImage< TImage >,
ThreadedIteratorRangePartitioner< typename TLevelSetEvolution::DomainMapImageFilterType::DomainMapType::const_iterator >,
TLevelSetEvolution >
::ThreadedExecution( const DomainType & imageSubDomain,
const ThreadIdType itkNotUsed(threadId) )
{
typename InputImageType::ConstPointer inputImage = this->m_Associate->m_EquationContainer->GetInput();
typename DomainType::IteratorType mapIt = imageSubDomain.Begin();
while( mapIt != imageSubDomain.End() )
{
ImageRegionConstIteratorWithIndex< InputImageType > it( inputImage, *(mapIt->second.GetRegion()) );
it.GoToBegin();
while( !it.IsAtEnd() )
{
const IdListType idList = *(mapIt->second.GetIdList());
//itkAssertInDebugOrThrowInReleaseMacro( !idList.empty() );
for( IdListConstIterator idListIt = idList.begin(); idListIt != idList.end(); ++idListIt )
{
typename LevelSetType::Pointer levelSetUpdate = this->m_Associate->m_UpdateBuffer->GetLevelSet( *idListIt - 1 );
OffsetType offset = levelSetUpdate->GetDomainOffset();
IndexType levelSetIndex = it.GetIndex() - offset;
LevelSetDataType characteristics;
typename TermContainerType::Pointer termContainer = this->m_Associate->m_EquationContainer->GetEquation( *idListIt - 1 );
termContainer->ComputeRequiredData( it.GetIndex(), characteristics );
LevelSetOutputRealType tempUpdate = termContainer->Evaluate( it.GetIndex(), characteristics );
LevelSetImageType * levelSetImage = levelSetUpdate->GetModifiableImage();
levelSetImage->SetPixel( levelSetIndex, tempUpdate );
}
++it;
}
++mapIt;
}
}
template< typename TOutput, unsigned int VDimension, typename TLevelSetEvolution >
LevelSetEvolutionComputeIterationThreader<
WhitakerSparseLevelSetImage< TOutput, VDimension >,
ThreadedIteratorRangePartitioner< typename WhitakerSparseLevelSetImage< TOutput, VDimension >::LayerConstIterator >,
TLevelSetEvolution >
::LevelSetEvolutionComputeIterationThreader()
{
}
template< typename TOutput, unsigned int VDimension, typename TLevelSetEvolution >
void
LevelSetEvolutionComputeIterationThreader<
WhitakerSparseLevelSetImage< TOutput, VDimension >,
ThreadedIteratorRangePartitioner< typename WhitakerSparseLevelSetImage< TOutput, VDimension >::LayerConstIterator >,
TLevelSetEvolution >
::BeforeThreadedExecution()
{
const ThreadIdType numberOfThreads = this->GetNumberOfThreadsUsed();
this->m_NodePairsPerThread.resize( numberOfThreads );
for( ThreadIdType ii = 0; ii < numberOfThreads; ++ii )
{
this->m_NodePairsPerThread[ii].clear();
}
}
template< typename TOutput, unsigned int VDimension, typename TLevelSetEvolution >
void
LevelSetEvolutionComputeIterationThreader<
WhitakerSparseLevelSetImage< TOutput, VDimension >,
ThreadedIteratorRangePartitioner< typename WhitakerSparseLevelSetImage< TOutput, VDimension >::LayerConstIterator >,
TLevelSetEvolution >
::ThreadedExecution( const DomainType & iteratorSubRange,
const ThreadIdType threadId )
{
typename LevelSetContainerType::Iterator it = this->m_Associate->m_LevelSetContainerIteratorToProcessWhenThreading;
typename LevelSetType::ConstPointer levelSet = it->GetLevelSet();
LevelSetIdentifierType levelSetId = it->GetIdentifier();
OffsetType offset = levelSet->GetDomainOffset();
typename TermContainerType::Pointer termContainer = this->m_Associate->m_EquationContainer->GetEquation( levelSetId );
typename LevelSetType::LayerConstIterator listIt = iteratorSubRange.Begin();
while( listIt != iteratorSubRange.End() )
{
const LevelSetInputType levelsetIndex = listIt->first;
LevelSetInputType inputIndex = listIt->first + offset;
LevelSetDataType characteristics;
termContainer->ComputeRequiredData( inputIndex, characteristics );
const LevelSetOutputType temp_update =
static_cast< LevelSetOutputType >( termContainer->Evaluate( inputIndex, characteristics ) );
this->m_NodePairsPerThread[threadId].push_back( NodePairType( levelsetIndex, temp_update ) );
++listIt;
}
}
template< typename TOutput, unsigned int VDimension, typename TLevelSetEvolution >
void
LevelSetEvolutionComputeIterationThreader<
WhitakerSparseLevelSetImage< TOutput, VDimension >,
ThreadedIteratorRangePartitioner< typename WhitakerSparseLevelSetImage< TOutput, VDimension >::LayerConstIterator >,
TLevelSetEvolution >
::AfterThreadedExecution()
{
typename LevelSetContainerType::Iterator it = this->m_Associate->m_LevelSetContainerIteratorToProcessWhenThreading;
LevelSetIdentifierType levelSetId = it->GetIdentifier();
typename LevelSetEvolutionType::LevelSetLayerType * levelSetLayerUpdateBuffer = this->m_Associate->m_UpdateBuffer[ levelSetId ];
const ThreadIdType numberOfThreads = this->GetNumberOfThreadsUsed();
for( ThreadIdType ii = 0; ii < numberOfThreads; ++ii )
{
typename std::vector< NodePairType >::const_iterator pairIt = this->m_NodePairsPerThread[ii].begin();
while( pairIt != this->m_NodePairsPerThread[ii].end() )
{
levelSetLayerUpdateBuffer->insert( *pairIt );
++pairIt;
}
}
}
} // end namespace itk
#endif
| 41.589844 | 151 | 0.743872 | [
"vector"
] |
eb369dd1211204f474d98324a1623b1c2bcb9e2a | 28,406 | hpp | C++ | RCEngine.hpp | rainstormstudio/RCEngine | 54c7e4064af56264be89d3a5e4ea1d85a66047de | [
"MIT"
] | null | null | null | RCEngine.hpp | rainstormstudio/RCEngine | 54c7e4064af56264be89d3a5e4ea1d85a66047de | [
"MIT"
] | null | null | null | RCEngine.hpp | rainstormstudio/RCEngine | 54c7e4064af56264be89d3a5e4ea1d85a66047de | [
"MIT"
] | null | null | null | /**
* @file RCEngine.hpp
* @author Daniel Hongyu Ding
* @brief
* @version 0.1
* @date 2020-12-25
*
* @copyright Copyright (c) 2020
*
*/
/* --------------------------------------------------------------------------------
* Author: Daniel Hongyu Ding
* ██████╗ █████╗ ██╗███╗ ██╗███████╗████████╗ ██████╗ ██████╗ ███╗ ███╗
* ██╔══██╗██╔══██╗██║████╗ ██║██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗████╗ ████║
* ██████╔╝███████║██║██╔██╗ ██║███████╗ ██║ ██║ ██║██████╔╝██╔████╔██║
* ██╔══██╗██╔══██║██║██║╚██╗██║╚════██║ ██║ ██║ ██║██╔══██╗██║╚██╔╝██║
* ██║ ██║██║ ██║██║██║ ╚████║███████║ ██║ ╚██████╔╝██║ ██║██║ ╚═╝ ██║
* ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝
*
* ███████╗████████╗██╗ ██╗██████╗ ██╗ ██████╗
* ██╔════╝╚══██╔══╝██║ ██║██╔══██╗██║██╔═══██╗
* ███████╗ ██║ ██║ ██║██║ ██║██║██║ ██║
* ╚════██║ ██║ ██║ ██║██║ ██║██║██║ ██║
* ███████║ ██║ ╚██████╔╝██████╔╝██║╚██████╔╝
* ╚══════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═════╝ ANSI Shadow.
*/
// --------------------------------------------------------------------------------
/*
The MIT License (MIT)
Copyright (c) 2020 Daniel Hongyu Ding
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.
This file can be found at https://github.com/rainstormstudio/RCEngine
Some concepts are based on the olcConsoleGameEngine.h by OneLoneCoder
----------------------------------------------------------------------------------
Usage:
class Demo : public RCEngine {
...
public:
Demo() {
windowTitle = "title of the window";
}
bool start() override {
...
return true;
}
bool update(double deltaTime) override {
...
return true;
}
bool render(double deltaTime) override {
...
return true;
}
// and optional destroy
bool destroy() override {
...
return true;
}
};
int main() {
Demo demo;
if (demo.createConsole()) {
demo.init();
}
return 0;
}
Note that keyboard and mouse events are supported
The tileset of this engine must be included, and the default one
is RCE_tileset.png, which can also be found at
https://github.com/rainstormstudio/RCEngine
*/
#pragma once
#ifndef RC_ENGINE_HPP
#define RC_ENGINE_HPP
#ifdef __linux__
#include "SDL2/SDL.h"
#include "SDL2/SDL_image.h"
#include "SDL2/SDL_mixer.h"
#include "SDL2/SDL_ttf.h"
#elif _WIN32
#include "SDL.h"
#include "SDL_image.h"
#include "SDL_mixer.h"
#include "SDL_ttf.h"
#endif
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <chrono>
class CellTexture {
SDL_Texture* texture; // texture of the cell
Uint8 ch;
int numSrcRows; // number of rows in src texture
int numSrcCols; // number of columns in src texture
SDL_Rect srcRect;
SDL_Rect destRect;
SDL_Color foreColor;
SDL_Color backColor;
public:
/**
* @brief Construct a new Cell
*
* @param texture the texture created from the tileset
* @param numSrcRows number of rows in the tileset
* @param numSrcCols number of columns in the tileset
* @param srcCellWidth the width of the character in the tileset
* @param srcCellHeight the height of the character in the tileset
* @param destCellWidth the width of the cell
* @param destCellHeight the height of the cell
*/
CellTexture(SDL_Texture* texture, int numSrcRows, int numSrcCols,
int srcCellWidth, int srcCellHeight, int destCellWidth, int destCellHeight)
: texture{texture}, numSrcRows{numSrcRows}, numSrcCols{numSrcCols} {
srcRect = {0, 0, srcCellWidth, srcCellHeight};
destRect = {0, 0, destCellWidth, destCellHeight};
foreColor = {255, 255, 255, 255};
backColor = {0, 0, 0, 255};
ch = 0;
}
/**
* @brief Set the character of the cell
*
* @param ch
*/
inline void setCh(Uint8 ch) {
this->ch = ch;
srcRect.x = (ch % numSrcCols) * srcRect.w;
srcRect.y = (ch / numSrcCols) * srcRect.h;
}
/**
* @brief Set the coordinate of the destRect
*
* @param x x-coordinate
* @param y y-coordinate
*/
inline void setDestPosition(int x, int y) {
destRect.x = x;
destRect.y = y;
}
/**
* @brief Set the coordinate of the srcRect
*
* @param x
* @param y
*/
inline void setSrcPosition(int x, int y) {
srcRect.x = x;
srcRect.y = y;
}
/**
* @brief Set the Fore Color of the cell
*
* @param r red
* @param g green
* @param b blue
* @param a alpha
*/
inline void setForeColor(Uint8 r, Uint8 g, Uint8 b, Uint8 a) {
foreColor = {r, g, b, a};
}
/**
* @brief Set the Fore Color of the cell
*
* @param color (r, g, b, a)
*/
inline void setForeColor(SDL_Color color) {
foreColor = color;
}
/**
* @brief Set the Back Color of the cell
*
* @param r red
* @param g green
* @param b blue
* @param a alpha
*/
inline void setBackColor(Uint8 r, Uint8 g, Uint8 b, Uint8 a) {
backColor = {r, g, b, a};
}
/**
* @brief Set the Back Color of the cell
*
* @param color (r, g, b, a)
*/
inline void setBackColor(SDL_Color color) {
backColor = color;
}
/**
* @brief Get the charactor of the cell
*
* @return Uint8
*/
Uint8 getCh() const {
return ch;
}
/**
* @brief Get the Fore Color of the cell
*
* @return SDL_Color
*/
SDL_Color getForeColor() const {
return foreColor;
}
/**
* @brief Get the Back Color of the cell
*
* @return SDL_Color
*/
SDL_Color getBackColor() const {
return backColor;
}
/**
* @brief renders the cell to the screen
*
* @param renderer
*/
void render(SDL_Renderer* renderer) {
SDL_SetTextureColorMod(texture, backColor.r, backColor.g, backColor.b);
SDL_SetTextureAlphaMod(texture, backColor.a);
SDL_Rect backSrcRect = {static_cast<int>((219 % numSrcCols) * srcRect.w), static_cast<int>((219 / numSrcCols) * srcRect.h), srcRect.w, srcRect.h};
SDL_RenderCopyEx(renderer, texture, &backSrcRect, &destRect, 0.0, nullptr, SDL_FLIP_NONE);
SDL_SetTextureColorMod(texture, foreColor.r, foreColor.g, foreColor.b);
SDL_SetTextureAlphaMod(texture, foreColor.a);
SDL_RenderCopyEx(renderer, texture, &srcRect, &destRect, 0.0, nullptr, SDL_FLIP_NONE);
}
};
class RCEngine {
protected:
// graphics info
int cellRows; // number of rows of cells
int cellCols; // number of columns of cells
int cellWidth; // the width of the cell
int cellHeight; // the height of the cell
int screenWidth; // the width of the screen
int screenHeight; // the height of the screen
std::string windowTitle; // the title of the window
// inputs
struct KeyState {
bool pressed;
bool released;
bool hold;
};
std::vector<bool> keyInput;
std::vector<bool> prevKeyInput;
std::vector<KeyState> keyState;
std::vector<bool> cursorInput;
std::vector<bool> prevCursorInput;
std::vector<KeyState> cursorState;
int cursorPosX;
int cursorPosY;
private:
SDL_Window* window;
SDL_Renderer* renderer;
SDL_Texture* tileset;
std::vector<std::vector<std::shared_ptr<CellTexture>>> buffer;
// events info
SDL_Event event;
// inputs
const int TOTAL_KEYS = 332;
const int TOTAL_CURSOR_STATES = 5;
// game info
bool loop;
public:
RCEngine() {
cellRows = 0;
cellCols = 0;
screenWidth = 0;
screenHeight = 0;
windowTitle = "RCEngine";
keyInput = std::vector<bool>(TOTAL_KEYS, false);
prevKeyInput = std::vector<bool>(TOTAL_KEYS, false);
keyState = std::vector<KeyState>(TOTAL_KEYS, {false, false, false});
cursorInput = std::vector<bool>(TOTAL_CURSOR_STATES, false);
prevCursorInput = std::vector<bool>(TOTAL_CURSOR_STATES, false);
cursorState = std::vector<KeyState>(TOTAL_CURSOR_STATES, {false, false, false});
}
~RCEngine() {}
/**
* @brief Creates the console window
*
* @param tilesetPath the path to the tileset
* @param rows number of rows of cells
* @param cols number of columns of cells
* @param fontWidth the width of the cell
* @param fontHeight the height of the cell
* @return true
* @return false
*/
bool createConsole(std::string tilesetPath = "./RCE_tileset.png", int rows = 30, int cols = 40, int fontWidth = 20, int fontHeight = 20) {
cellRows = rows;
cellCols = cols;
cellWidth = fontWidth;
cellHeight = fontHeight;
int numSrcRows = 16;
int numSrcCols = 16;
screenWidth = cellCols * cellWidth;
screenHeight = cellRows * cellHeight;
window = nullptr;
renderer = nullptr;
tileset = nullptr;
loop = false;
int tileWidth = 0;
int tileHeight = 0;
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_AUDIO) < 0) {
std::cerr << "SDL initialization failed: " << SDL_GetError() << std::endl;
return false;
} else {
window = SDL_CreateWindow(windowTitle.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screenWidth, screenHeight, SDL_WINDOW_SHOWN);
SDL_SetWindowFullscreen(window, 0);
SDL_RaiseWindow(window);
if (!window) {
std::cerr << "Failed to create window: " << SDL_GetError() << std::endl;
return false;
} else {
renderer = SDL_CreateRenderer(window, -1, 0);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
if (!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) {
std::cerr << "Failed to load SDL_image: " << IMG_GetError() << std::endl;
return false;
}
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) {
std::cerr << "Failed to load SDL_mixer: " << Mix_GetError() << std::endl;
return false;
}
}
}
SDL_Surface* surface = IMG_Load(tilesetPath.c_str());
if (!surface) {
std::cerr << "Error initializing SDL surface: " << IMG_GetError() << std::endl;
return false;
} else {
SDL_SetColorKey(surface, SDL_TRUE, SDL_MapRGB(surface->format, 255, 0, 255));
tileset = SDL_CreateTextureFromSurface(renderer, surface);
if (tileset == nullptr) {
std::cerr << "Error creating texture from " << tilesetPath << ": " << SDL_GetError() << std::endl;
return false;
} else {
tileWidth = surface->w / numSrcCols;
tileHeight = surface->h / numSrcRows;
}
SDL_FreeSurface(surface);
}
buffer = std::vector<std::vector<std::shared_ptr<CellTexture>>>(cellRows);
for (int i = 0; i < cellRows; i ++) {
buffer[i] = std::vector<std::shared_ptr<CellTexture>>(cellCols);
for (int j = 0; j < cellCols; j ++) {
buffer[i][j] = std::make_shared<CellTexture>(tileset, numSrcRows, numSrcCols, tileWidth, tileHeight, cellWidth, cellHeight);
buffer[i][j]->setDestPosition(j * cellWidth, i * cellHeight);
}
}
return true;
}
/**
* @brief blends two colors
*
* @param color1 (r, g, b, a)
* @param color2 (r, g, b, a)
* @return SDL_Color
*/
SDL_Color blendColor(SDL_Color color1, SDL_Color color2) {
double red = color1.r;
double green = color1.g;
double blue = color1.b;
double alpha = color1.a;
red = red * (alpha / 255.0);
green = green * (alpha / 255.0);
blue = blue * (alpha / 255.0);
alpha = 0.0;
double newRed = color2.r;
double newGreen = color2.g;
double newBlue = color2.b;
double newAlpha = color2.a;
red = newRed * (newAlpha / 255.0) + red * (1.0 - newAlpha / 255.0);
green = newGreen * (newAlpha / 255.0) + green * (1.0 - newAlpha / 255.0);
blue = newBlue * (newAlpha / 255.0) + blue * (1.0 - newAlpha / 255.0);
alpha = 255.0;
SDL_Color blended = {0, 0, 0, 0};
blended.r = static_cast<Uint8>(round(red));
blended.g = static_cast<Uint8>(round(green));
blended.b = static_cast<Uint8>(round(blue));
blended.a = static_cast<Uint8>(round(alpha));
return blended;
}
/**
* @brief draws a charactor ch at (x, y) width foreColor and backColor
*
* @param x x-coordinate (the index of column)
* @param y y-coordinate (the index of row)
* @param ch charactor
* @param foreColor (r, g, b, a)
* @param backColor (r, g, b, a)
*/
void draw(int x, int y, Uint8 ch = ' ', SDL_Color foreColor = {255, 255, 255, 255}, SDL_Color backColor = {0, 0, 0, 255}) {
if (0 <= x && x < cellCols && 0 <= y && y < cellRows) {
buffer[y][x]->setCh(ch);
buffer[y][x]->setForeColor(blendColor(buffer[y][x]->getForeColor(), foreColor));
buffer[y][x]->setBackColor(blendColor(buffer[y][x]->getBackColor(), backColor));
}
}
/**
* @brief draws a line from (x1, y1) to (x2, y2)
*
* @param x1
* @param y1
* @param x2
* @param y2
* @param ch
* @param foreColor
* @param backColor
*/
void drawLine(int x1, int y1, int x2, int y2, Uint8 ch = ' ', SDL_Color foreColor = {255, 255, 255, 255}, SDL_Color backColor = {0, 0, 0, 255}) {
if (0 <= x1 && x1 < cellCols && 0 <= y1 && y1 < cellRows
&& 0 <= x2 && x2 < cellCols && 0 <= y2 && y2 < cellRows) {
int dx = abs(x2 - x1);
int dy = -abs(y2 - y1);
// straight line optimization
if (dx == 0) { // vertical
if (y1 > y2) {
std::swap(y1, y2);
}
for (int y = y1; y <= y2; y ++) {
draw(x1, y, ch, foreColor, backColor);
}
} else if (dy == 0) { // horizontal
if (x1 > x2) {
std::swap(x1, x2);
}
for (int x = x1; x <= x2; x ++) {
draw(x, y1, ch, foreColor, backColor);
}
} else {
int sx = x1 < x2 ? 1 : -1;
int sy = y1 < y2 ? 1 : -1;
int error = dx + dy;
while (1) {
draw(x1, y1, ch, foreColor, backColor);
if (x1 == x2 && y1 == y2) {
break;
}
int error2 = 2 * error;
if (error2 >= dy) {
error += dy;
x1 += sx;
}
if (error2 <= dx) {
error += dx;
y1 += sy;
}
}
}
}
}
/**
* @brief Get the character at (x, y)
*
* @param x x-coordinate (the index of column)
* @param y y-coordinate (the index of row)
* @return Uint8
*/
Uint8 getCh(int x, int y) const {
if (0 <= x && x < cellCols && 0 <= y && y < cellRows) {
return buffer[y][x]->getCh();
} else {
return 0;
}
}
/**
* @brief Get the Fore Color at (x, y)
*
* @param x x-coordinate (the index of column)
* @param y y-coordinate (the index of row)
* @return SDL_Color
*/
SDL_Color getForeColor(int x, int y) const {
if (0 <= x && x < cellCols && 0 <= y && y < cellRows) {
return buffer[y][x]->getForeColor();
} else {
return {0, 0, 0, 0};
}
}
/**
* @brief Get the Back Color at (x, y)
*
* @param x x-coordinate (the index of column)
* @param y y-coordinate (the index of row)
* @return SDL_Color
*/
SDL_Color getBackColor(int x, int y) const {
if (0 <= x && x < cellCols && 0 <= y && y < cellRows) {
return buffer[y][x]->getBackColor();
} else {
return {0, 0, 0, 0};
}
}
/**
* @brief write a string to the screen starting at (x, y)
*
* @param x x-coordinate (the index of column)
* @param y y-coordinate (the index of row)
* @param content
* @param foreColor (r, g, b, a)
* @param backColor (r, g, b, a)
*/
void write(int x, int y, std::string content, SDL_Color foreColor = {0, 0, 0, 0}, SDL_Color backColor = {0, 0, 0, 0}) {
if (0 <= x && x < cellCols && 0 <= y && y < cellRows) {
int len = content.length();
for (int i = 0; i < len && x + i < cellCols; i ++) {
if (content[i] == ' ') continue;
buffer[y][x + i]->setCh(content[i]);
buffer[y][x + i]->setForeColor(blendColor(buffer[y][x + i]->getForeColor(), foreColor));
buffer[y][x + i]->setBackColor(blendColor(buffer[y][x + i]->getBackColor(), backColor));
}
}
}
/**
* @brief fills a rectangle region
*
* @param dest (x, y, w, h)
* @param ch character
* @param foreColor (r, g, b, a)
* @param backColor (r, g, b, a)
*/
void fill(SDL_Rect dest, Uint8 ch = ' ', SDL_Color foreColor = {0, 0, 0, 0}, SDL_Color backColor = {0, 0, 0, 0}) {
if (0 <= dest.x && dest.x < cellCols && 0 <= dest.y && dest.y < cellRows) {
for (int i = dest.y; i < dest.y + dest.h && i < cellRows; i ++) {
for (int j = dest.x; j < dest.x + dest.w && j < cellCols; j ++) {
buffer[i][j]->setCh(ch);
buffer[i][j]->setForeColor(blendColor(buffer[i][j]->getForeColor(), foreColor));
buffer[i][j]->setBackColor(blendColor(buffer[i][j]->getBackColor(), backColor));
}
}
}
}
/**
* @brief start the game loop
*
*/
void init() {
loop = true;
gameLoop();
}
/**
* @brief clear buffer
*
*/
void clearBuffer() {
for (int i = 0; i < cellRows; i ++) {
for (int j = 0; j < cellCols; j ++) {
buffer[i][j]->setCh(' ');
buffer[i][j]->setForeColor(255, 255, 255, 255);
buffer[i][j]->setBackColor(0, 0, 0, 255);
}
}
SDL_RenderClear(renderer);
}
/**
* @brief render to the screen
*
*/
void renderBuffer() {
for (int i = 0; i < cellRows; i ++) {
for (int j = 0; j < cellCols; j ++) {
buffer[i][j]->render(renderer);
}
}
SDL_RenderPresent(renderer);
}
private:
/**
* @brief game loop
*
*/
void gameLoop() {
if (!start()) {
loop = false;
}
auto time_a = std::chrono::high_resolution_clock::now();
auto time_b = std::chrono::high_resolution_clock::now();
while (loop) {
while (loop) {
time_b = std::chrono::high_resolution_clock::now();
double deltaTime = std::chrono::duration_cast<std::chrono::microseconds>(time_b - time_a).count() / 1000000.0f;
time_a = time_b;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT: {
loop = false;
break;
}
case SDL_KEYDOWN: {
keyInput[event.key.keysym.sym] = true;
break;
}
case SDL_KEYUP: {
keyInput[event.key.keysym.sym] = false;
break;
}
case SDL_MOUSEMOTION: {
cursorPosX = event.motion.x / cellWidth;
cursorPosY = event.motion.y / cellHeight;
break;
}
case SDL_MOUSEBUTTONDOWN: {
switch (event.button.button) {
case SDL_BUTTON_LEFT: {
cursorInput[0] = true;
break;
}
case SDL_BUTTON_RIGHT: {
cursorInput[1] = true;
break;
}
case SDL_BUTTON_MIDDLE: {
cursorInput[2] = true;
break;
}
case SDL_BUTTON_X1: {
cursorInput[3] = true;
break;
}
case SDL_BUTTON_X2: {
cursorInput[4] = true;
break;
}
}
break;
}
case SDL_MOUSEBUTTONUP: {
switch (event.button.button) {
case SDL_BUTTON_LEFT: {
cursorInput[0] = false;
break;
}
case SDL_BUTTON_RIGHT: {
cursorInput[1] = false;
break;
}
case SDL_BUTTON_MIDDLE: {
cursorInput[2] = false;
break;
}
case SDL_BUTTON_X1: {
cursorInput[3] = false;
break;
}
case SDL_BUTTON_X2: {
cursorInput[4] = false;
break;
}
}
break;
}
}
}
for (int i = 0; i < TOTAL_KEYS; i ++) {
keyState[i].pressed = false;
keyState[i].released = false;
if (keyInput[i] != prevKeyInput[i]) {
if (keyInput[i]) {
keyState[i].pressed = !keyState[i].hold;
keyState[i].hold = true;
} else {
keyState[i].released = true;
keyState[i].hold = false;
}
}
prevKeyInput[i] = keyInput[i];
}
for (int i = 0; i < TOTAL_CURSOR_STATES; i ++) {
cursorState[i].pressed = false;
cursorState[i].released = false;
if (cursorInput[i] != prevCursorInput[i]) {
if (cursorInput[i]) {
cursorState[i].pressed = true;
cursorState[i].hold = true;
} else {
cursorState[i].released = true;
cursorState[i].hold = false;
}
}
prevCursorInput[i] = cursorInput[i];
}
if (!update(deltaTime)) {
loop = false;
}
clearBuffer();
if (!render(deltaTime)) {
loop = false;
}
renderBuffer();
std::string title = windowTitle + " - FPS: " + std::to_string(1.0f / deltaTime);
SDL_SetWindowTitle(window, title.c_str());
}
if (destroy()) {
if (!tileset) {
SDL_DestroyTexture(tileset);
tileset = nullptr;
}
SDL_DestroyWindow(window);
SDL_DestroyRenderer(renderer);
Mix_Quit();
IMG_Quit();
SDL_Quit();
} else {
loop = true;
}
}
}
public:
/**
* @brief called when the game starts
*
* @return true
* @return false
*/
virtual bool start() = 0;
/**
* @brief called every frame
*
* @param deltaTime elapse time between frames
* @return true
* @return false
*/
virtual bool update(double deltaTime) = 0;
/**
* @brief called every frame after update and renders
* things to the buffer
*
* @param deltaTime
* @return true
* @return false
*/
virtual bool render(double deltaTime) = 0;
/**
* @brief called when the game loop stops
*
* @return true
* @return false
*/
virtual bool destroy() {
return true;
}
public:
/**
* @brief Get the x coordinate of the cursor
*
* @return int
*/
int getCursorX() const {
return cursorPosX;
}
/**
* @brief Get the y coordinate of the cursor
*
* @return int
*/
int getCursorY() const {
return cursorPosY;
}
/**
* @brief Get the Key State of key
*
* @param key
* @return KeyState
*/
KeyState getKeyState(int key) const {
return keyState[key];
}
/**
* @brief Get the Cursor State of cursor
*
* @param cursor
* @return KeyState
*/
KeyState getCursorState(int cursor) const {
return cursorState[cursor];
}
protected:
/**
* @brief write debug message to standard error
*
* @param msg
* @param level
*/
void debugMsg(std::string msg, int level = 0) {
for (int i = 0; i < level; i ++) {
std::cerr << " ";
}
std::cerr << "| " << msg << std::endl;
}
/**
* @brief write a line to standard error
*
* @param level
*/
void debugLine(int level = 0) {
for (int i = 0; i < level; i ++) {
std::cerr << " ";
}
for (int i = 0; i < 50; i ++) {
std::cerr << "-";
}
std::cerr << std::endl;
}
};
#endif
| 31.284141 | 154 | 0.46638 | [
"render",
"vector"
] |
eb3a82a47a261303b0c36863544d7792557f0288 | 7,219 | cpp | C++ | kattis_done/doorman.cpp | heiseish/Competitive-Programming | e4dd4db83c38e8837914562bc84bc8c102e68e34 | [
"MIT"
] | 5 | 2019-03-17T01:33:19.000Z | 2021-06-25T09:50:45.000Z | kattis_done/doorman.cpp | heiseish/Competitive-Programming | e4dd4db83c38e8837914562bc84bc8c102e68e34 | [
"MIT"
] | null | null | null | kattis_done/doorman.cpp | heiseish/Competitive-Programming | e4dd4db83c38e8837914562bc84bc8c102e68e34 | [
"MIT"
] | null | null | null | /**
Justice isn’t something that you can just proclaim. It’s a feeling you should keep near your heart.
*/
//,*************,,*/(((((//,,*(#%%%%%%%%%%%%%%%#(*,,,****************************************************,*/(((((((((/((((////****/((##%%%%%%
//,*************,,//((((((//,,*(%%%%%%%%%%%%%%%%%##/*****************************************************,,*/(///(//////****//((##%%%%%%%%%%%
//,************,,*/(((((((//***/#%%%%%%%%%%%%%%%%%%%#(/***************************************************,*//////////*//((#%%%%%%%%%%%%%%%%%
//,***********,,*////////////***/##%%%%%%%%%%%%%%%%%%%##(*,***********************************************,,*////////(###%%%%%%%%%%%%%%%%%%%%
//,**********,,,*/*******//////**/(#%%%%%%%%%%%%%%%%%%%%%#(/**********************************************,,,***/(##%%%%%%%%%%%%%%%%%%%%%%%%%
//,*********,,,,*************///***/(#%%%%%%%%%%%%%%%%%%%%%%#(/***********************************,****,****/((#%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
//,*********,,,***************//****/(##%%%%%%%%%%%%%%%%%%%%%%##//**************//////////////////////((#####%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#(
//,********,,,,***********************/(#%%%%%%%%%%%%%%%%%%%%%%%##################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%##(/
//,*******,..,***********************,,*/##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%###((//
//,*******,.,,***********************,,,,*(#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%##(//**//
//,******,.,,,************************,,,,*/(#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#(//*******
//,*****,,,,,********,***,,,,,,,,,,,,*,,,,,,*/(######%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%##(/**********
//,*****,..,*******,,,,,,,,,,,,,,,,,,,,,,*,,,,*///((#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%###(/************
//,*****,,,*******,,,,,*,,,,,,,,,,,,,,,,,****,,,*/(#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#######(//**************
//,****,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,**,,,/(%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#((//******************
//,***,..,,,,,,,,,,,,,,,,,,,,,,,,,,,,,..,,,,,,,*(#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#(/*******************
//,**,,.,,,,,,,,,,,,,,,,,,,,,,,,,,.......,,,,,,/#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#####%%%%%%%%%%%%%%%%#(/******************
//,**,..,,,,,,,,,,,,,,,,,,,,,,,,,......,,,*,,,*(#%%%%%%%%##(((/(##%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%##(((/*/((#%%%%%%%%%%%%%%#(/*****************
//,*,..,,,,,,,,,,,,,,,,,,,,,,,,,,,.....,,**,,*/#%%%%%%%##((((*,**/#%%%%%%%%%%%%%%%%%%%%%%%%%%%%##((##/,,,*(#%%%%%%%%%%%%%%#(*****************
//.*,.,,,**,,,,,,,,,,,,,,,,,,,,,,,,,,*****,,,/(%%%%%%%%#(//(#/,..*/#%%%%%%%%%%%%%%%%%%%%%%%%%%%#(//(#/,..,/(#%%%%%%%%%%%%%%#/*****///////////
//.,..,,,,,,,,,,,,,,,,,,,,,,,,,,*,,*******,,,(#%%%%%%%%#(*,,,....,/#%%%%%%%%%%%%%%%%%%%%%%%%%%%#(*,,,....,/(#%%%%%%%%%%%%%%#(*,**////////////
//.,..,,,,,,,,,...........,,,,,,*,********,,*(#%%%%%%%%%#(/*,,...,/#%%%%%%%%%%%%%%%%%%%%%%%%%%%%#(/*,,..,*/##%%%%%%%%%%%%%%%#(***////////////
//...,,,,,,,................,,*,**********,,/#%%%%%%%%%%%%#((////((#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%##((///(#%%%%%%%%%%%%%%%%%%(/**////////////
// ..,,,,,,.................,,,**********,,*(#%%%%%%%%%%%%%%%%%%#%%%%%%%%#((///((#%%%%%%%%%%%%%%%%%%%%%#%%%%%%%%%%%%%%%%%%%%%#/**////////////
//.,,,,,,,,.................,,***********,,/(####%%%%%%%%%%%%%%%%%%%%%%%%#(/*,,,*(#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#(/*////////////
//.,***,,,,,,..............,,,**********,..,***//((##%%%%%%%%%%%%%%%%%%%%%%%##((##%%%%%%%%%%%%%%%%%%%%%%%%%##(((((((((###%%%%%#/**///////////
//.*****,,,,,,,,,,,,,,,,,,,*************,..,*******/(#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%##///*//////((#%%%%%#(**///////////
//.****************/******/***////*****,.,*///////**/#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#(////////////(#%%%%%#/**//////////
//.***********************/////*******,..,*//////////(#%%%%%%%%%%%%%%%%%%%%##########%%%%%%%%%%%%%%%%%%%%#(///////////*/(#%%%%%#(***/////////
//.************************///********,..,*//////////#%%%%%%%%%%%%%%%%%%#(//*****///(((##%%%%%%%%%%%%%%%%#(///////////**/##%%%%##/***////////
//.***********************************,.,,***///////(#%%%%%%%%%%%%%%%%#(/*,,,*//((((////(#%%%%%%%%%%%%%%%#((////////////(#%%%%%%#(*********//
//,***********,,,*,,*,,**************,,,*//******//(#%%%%%%%%%%%%%%%%%#(*,,*/(((#####(((((#%%%%%%%%%%%%%%%##///////////(#%%%%%%%%#(***///////
//,*************,,**,,,************,,,,,/(##((((####%%%%%%%%%%%%%%%%%%%(/**/(((#((((#((//(#%%%%%%%%%%%%%%%%%#(((((((((##%%%%%%%%%%#/**///////
//,******************************,,,,,,,*(#%#%%%%%%%%%%%%%%%%%%%%%%%%%%#(**/((#(#(((#((//(#%%%%%%%%%%%%%%%%%%%%%%%#%#%%%%%%%%%%%%%#(**///////
//,*************,**************,****,,,,,/(#%%%%%%%%%%%%%%%%%%%%%%%%%%%%#(/*/((((#((((///(#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%(/*///////
//,*************************************,*/#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%##(////////////(#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#/**/////*
//,******////****///////////////////////***/#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%####(((((((###%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#(********
//.,*,****///////////////////////////////***/#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#(/*******
//.,,,,*****//////////////////////////*******(#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%##(*******
//.,,,,,,***********/////////////////********/(#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%(*******
#include <bits/stdc++.h>
#define forn(i, l, r) for(int i=l;i<=r;i++)
#define all(v) v.begin(),v.end()
#define pb push_back
#define nd second
#define st first
#define debug(x) cout<<#x<<" -> "<<x<< endl
#define rsa(x, y) memset(x, y, sizeof x);
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<bool> vb;
typedef vector<string> vs;
typedef vector<double> vd;
typedef vector<long long> vll;
typedef vector<vector<int> > vvi;
typedef vector<vll> vvll;
typedef vector<pair<int, int> > vpi;
typedef vector<vpi> vvpi;
typedef pair<int, int> pi;
typedef pair<ll, ll> pll;
typedef vector<pll> vpll;
const int inf = 1 << 30;
/**
Start coding from here
*/
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
int x;
cin >> x;
int ct = 0;
string q;
cin >> q;
int f = 0, s = 1;
int fe = 0, ma = 0;
while(s <= q.length() - 1 || f <= q.length() - 1) {
bool can = false;
if (f < q.length()) {
if (q[f] == 'M' && abs(ma + 1 - fe) <= x) {
can = true;
f = s;
s++;
ma++;
}
if (q[f] == 'W' && abs(fe + 1 - ma) <= x) {
can = true;
f = s;
s++;
fe++;
}
}
if (s < q.length()) {
if (q[s] == 'M' && abs(ma + 1 - fe) <= x) {
can = true;
s++;
ma++;
}
if (q[s] == 'W' && abs(fe + 1 - ma) <= x) {
can = true;
s++;
fe++;
}
}
if (!can) break;
}
cout << fe + ma << '\n';
return 0;
}
| 60.158333 | 141 | 0.115251 | [
"vector"
] |
eb3c75cdd1a6f9d628389ffe2241b09920f6f590 | 54,162 | cc | C++ | master/kismet-2018-08-BETA1/kismet-2018-08-BETA1/legacy_code/legacy_client/kis_panel_device.cc | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 4 | 2018-09-07T15:35:24.000Z | 2019-03-27T09:48:12.000Z | master/kismet-2018-08-BETA1/kismet-2018-08-BETA1/legacy_code/legacy_client/kis_panel_device.cc | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 371 | 2020-03-04T21:51:56.000Z | 2022-03-31T20:59:11.000Z | master/kismet-2018-08-BETA1/kismet-2018-08-BETA1/legacy_code/legacy_client/kis_panel_device.cc | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 3 | 2019-06-18T19:57:17.000Z | 2020-11-06T03:55:08.000Z | /*
This file is part of Kismet
Kismet 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.
Kismet 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 Kismet; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "config.h"
// Panel has to be here to pass configure, so just test these
#if (defined(HAVE_LIBNCURSES) || defined (HAVE_LIBCURSES))
#include "kis_panel_device.h"
#include "kis_panel_windows.h"
#include "kis_panel_frontend.h"
#include "kis_panel_widgets.h"
#include "kis_devicelist_sort.h"
#include "soundcontrol.h"
void KDL_TIME(CLIPROTO_CB_PARMS) {
((Kis_Devicelist *) auxptr)->Proto_TIME();
}
void KDL_AddCli(KPI_ADDCLI_CB_PARMS) {
((Kis_Devicelist *) auxptr)->NetClientAdd(netcli, add);
}
void KDL_ConfigureCli(CLICONF_CB_PARMS) {
((Kis_Devicelist *) auxptr)->NetClientConfigure(kcli, recon);
}
void KDL_DeviceRX(DEVICERX_PARMS) {
((Kis_Devicelist *) aux)->DeviceRX(device);
}
void KDL_PhyRX(PHYRX_PARMS) {
((Kis_Devicelist *) aux)->PhyRX(phy_id);
}
void KDL_FilterMenuCB(MENUITEM_CB_PARMS) {
((Kis_Devicelist *) auxptr)->FilterMenuAction(menuitem);
}
void KDL_ColorMenuCB(MENUITEM_CB_PARMS) {
((Kis_Devicelist *) auxptr)->SpawnColorPrefWindow();
}
void KDL_ViewMenuCB(MENUITEM_CB_PARMS) {
((Kis_Devicelist *) auxptr)->ViewMenuAction(menuitem);
}
void KDL_ColumnMenuCB(MENUITEM_CB_PARMS) {
((Kis_Devicelist *) auxptr)->SpawnColumnPrefWindow(false);
}
void KDL_ExtraMenuCB(MENUITEM_CB_PARMS) {
((Kis_Devicelist *) auxptr)->SpawnColumnPrefWindow(true);
}
void KDL_SortMenuCB(MENUITEM_CB_PARMS) {
((Kis_Devicelist *) auxptr)->SortMenuAction(menuitem);
}
void KDL_ColumnRefresh(KISPANEL_COMPLETECB_PARMS) {
if (rc)
((Kis_Devicelist *) auxptr)->ParseColumnConfig();
}
string KDL_Common_Column_Cb(KDL_COLUMN_PARMS) {
return ((Kis_Devicelist *) aux)->CommonColumn(device, columnid, header);
}
string KDL_Common_Subcolumn_Cb(KDL_COLUMN_PARMS) {
return ((Kis_Devicelist *) aux)->CommonSubColumn(device, columnid, header);
}
void KDL_Common_Sort(KDL_SORT_PARMS) {
stable_sort(dev_vec->begin(), dev_vec->end(),
KDL_Sort_Proxy(*((KDL_Sort_Abstract *) aux)));
}
Kis_Devicelist::Kis_Devicelist(GlobalRegistry *in_globalreg, Kis_Panel *in_panel) :
Kis_Panel_Component(in_globalreg, in_panel) {
globalreg->InsertGlobal("MAIN_DEVICELIST", this);
kpinterface = in_panel->FetchPanelInterface();
devicetracker = (Client_Devicetracker *) globalreg->FetchGlobal("CLIENT_DEVICE_TRACKER");
if (devicetracker == NULL) {
fprintf(stderr, "FATAL OOPS: Missing devicetracker in devicelist\n");
exit(1);
}
cli_addref = kpinterface->Add_NetCli_AddCli_CB(KDL_AddCli, (void *) this);
devcomp_ref_common = devicetracker->RegisterDeviceComponent("COMMON");
draw_dirty = false;
// Get new devices
newdevref = devicetracker->RegisterDevicerxCallback(KDL_DeviceRX, this);
// Get new phys but not phy updates
newphyref = devicetracker->RegisterPhyrxCallback(KDL_PhyRX, this, false);
viewable_lines = 0;
viewable_cols = 0;
first_line = last_line = selected_line = hpos = 0;
next_column_id = 1;
next_sort_id = 1;
// Register all our local columns
col_active = RegisterColumn("Active", "Recently active", 1,
LABEL_POS_LEFT, KDL_Common_Column_Cb, this, false);
col_name = RegisterColumn("Name", "Name", 20,
LABEL_POS_LEFT, KDL_Common_Column_Cb, this, false);
col_phy = RegisterColumn("Phy", "Phy", 10,
LABEL_POS_LEFT, KDL_Common_Column_Cb, this, false);
col_addr = RegisterColumn("Address", "MAC or Identifier", 17,
LABEL_POS_LEFT, KDL_Common_Column_Cb, this, false);
col_type = RegisterColumn("Typestring", "Device type", 10,
LABEL_POS_LEFT, KDL_Common_Column_Cb, this, false);
col_basictype = RegisterColumn("BasicType", "Basic type", 10,
LABEL_POS_LEFT, KDL_Common_Column_Cb, this, false);
col_cryptstr = RegisterColumn("Cryptstring", "Device encryption", 4,
LABEL_POS_LEFT, KDL_Common_Column_Cb, this, false);
col_basiccrypt = RegisterColumn("BasicCrypt", "Basic encryption", 1,
LABEL_POS_LEFT, KDL_Common_Column_Cb, this, false);
col_packets = RegisterColumn("Packets", "Packets", 5,
LABEL_POS_RIGHT, KDL_Common_Column_Cb, this, false);
col_llc = RegisterColumn("LinkPackets", "Link packets", 5,
LABEL_POS_RIGHT, KDL_Common_Column_Cb, this, false);
col_error = RegisterColumn("ErrorPackets", "Error packets", 5,
LABEL_POS_RIGHT, KDL_Common_Column_Cb, this, false);
col_data = RegisterColumn("DataPackets", "Data packets", 5,
LABEL_POS_RIGHT, KDL_Common_Column_Cb, this, false);
col_crypt = RegisterColumn("CryptPackets", "Encrypted packets", 5,
LABEL_POS_RIGHT, KDL_Common_Column_Cb, this, false);
col_datasize = RegisterColumn("Datasize", "Data size", 6,
LABEL_POS_RIGHT, KDL_Common_Column_Cb, this, false);
col_newpackets = RegisterColumn("Packetrate", "Packet rate", 5,
LABEL_POS_RIGHT, KDL_Common_Column_Cb, this, false);
col_channel = RegisterColumn("Channel", "Channel", 4,
LABEL_POS_RIGHT, KDL_Common_Column_Cb, this, false);
col_freq = RegisterColumn("Frequency", "Frequency", 4,
LABEL_POS_RIGHT, KDL_Common_Column_Cb, this, false);
col_alerts = RegisterColumn("Alerts", "Number of alerts", 3,
LABEL_POS_RIGHT, KDL_Common_Column_Cb, this, false);
col_manuf = RegisterColumn("Manuf", "Manufacturer", 12,
LABEL_POS_LEFT, KDL_Common_Column_Cb, this, false);
// Subcolumns take as much room as they want, it's not fixed
col_sub_lastseen = RegisterColumn("LastSeen", "Last seen time", 0,
LABEL_POS_LEFT, KDL_Common_Subcolumn_Cb,
this, true);
col_sub_addr = RegisterColumn("Address", "MAC or identifier", 0,
LABEL_POS_LEFT, KDL_Common_Subcolumn_Cb, this, true);
col_sub_basiccrypt = RegisterColumn("BasicCrypt", "Basic encryption info", 0,
LABEL_POS_LEFT, KDL_Common_Subcolumn_Cb,
this, true);
col_sub_ip = RegisterColumn("IP", "IP data", 0,
LABEL_POS_LEFT, KDL_Common_Subcolumn_Cb, this, true);
col_sub_manuf = RegisterColumn("Manuf", "Manufacturer type", 0,
LABEL_POS_LEFT, KDL_Common_Subcolumn_Cb, this, true);
col_sub_seenby = RegisterColumn("Seenby", "Capture sources list", 0,
LABEL_POS_LEFT, KDL_Common_Subcolumn_Cb, this, true);
col_sub_phy = RegisterColumn("Phyname", "Phy layer name", 0,
LABEL_POS_LEFT, KDL_Common_Subcolumn_Cb, this, true);
// We now resolve via the globalreg name-resolution
menu = (Kis_Menu *) globalreg->FetchGlobal("KISUI_MAIN_MENU");
mn_filter = menu->FindMenu("Filter");
// Don't show the filter menu until we have multiple phy types
menu->SetMenuVis(mn_filter, 0);
mn_preferences = menu->FindMenu("Preferences");
mi_colorpref =
menu->AddMenuItem("Device Colors", mn_preferences, 'c');
mi_columnpref =
menu->AddMenuItem("Device Columns", mn_preferences, 'd');
mi_extrapref =
menu->AddMenuItem("Device Extras", mn_preferences, 'e');
menu->SetMenuItemCallback(mi_colorpref, KDL_ColorMenuCB, this);
menu->SetMenuItemCallback(mi_columnpref, KDL_ColumnMenuCB, this);
menu->SetMenuItemCallback(mi_extrapref,KDL_ExtraMenuCB, this);
for (int x = 0; x < KDL_COLOR_MAX; x++)
color_map[x] = 0;
color_inactive = 0;
mn_sort = menu->FindMenu("Sort");
RegisterSort("First time", "Sort by first time seen",
KDL_Common_Sort, new KDL_Sort_First(devcomp_ref_common));
RegisterSort("First time (desc)", "Sort by first time (descending)",
KDL_Common_Sort, new KDL_Sort_FirstDesc(devcomp_ref_common));
RegisterSort("Last time", "Sort by last time seen",
KDL_Common_Sort, new KDL_Sort_Last(devcomp_ref_common));
RegisterSort("Last time (desc)", "Sort by last time (descending)",
KDL_Common_Sort, new KDL_Sort_LastDesc(devcomp_ref_common));
RegisterSort("Basic crypt", "Sort by basic encryption",
KDL_Common_Sort, new KDL_Sort_Crypt(devcomp_ref_common));
RegisterSort("Basic Type", "Sort by type",
KDL_Common_Sort, new KDL_Sort_Type(devcomp_ref_common));
RegisterSort("Channel", "Sort by channel",
KDL_Common_Sort, new KDL_Sort_Channel(devcomp_ref_common));
RegisterSort("Packets", "Sort by number of packets",
KDL_Common_Sort, new KDL_Sort_Packets(devcomp_ref_common));
RegisterSort("Packets (desc)", "Sort by number of packets (descending)",
KDL_Common_Sort, new KDL_Sort_PacketsDesc(devcomp_ref_common));
RegisterSort("Phy type", "Sort by Phy layer type",
KDL_Common_Sort, new KDL_Sort_Phy(devcomp_ref_common));
Kis_Main_Panel *mainp = (Kis_Main_Panel *) globalreg->FetchGlobal("KISUI_MAIN_PANEL");
int mi_next = mainp->FetchLastViewMenuItem();
mn_view = menu->FindMenu("View");
mi_next = mi_view_network =
menu->AddMenuItem("Display Networks", mn_view, 'e', mi_next);
mi_next = mi_view_wireless =
menu->AddMenuItem("Display Wireless", mn_view, 'w', mi_next);
mi_next = mi_view_devices =
menu->AddMenuItem("Display Devices", mn_view, 'd', mi_next);
menu->SetMenuItemCheckSymbol(mi_view_network, '*');
menu->SetMenuItemCheckSymbol(mi_view_wireless, '*');
menu->SetMenuItemCheckSymbol(mi_view_devices, '*');
menu->SetMenuItemCallback(mi_view_network, KDL_ViewMenuCB, this);
menu->SetMenuItemCallback(mi_view_wireless, KDL_ViewMenuCB, this);
menu->SetMenuItemCallback(mi_view_devices, KDL_ViewMenuCB, this);
mainp->SetLastViewMenuItem(mi_next);
string viewmode = StrLower(kpinterface->prefs->FetchOpt("MAIN_VIEWSTYLE"));
if (viewmode == "network") {
mi_lastview = mi_view_network;
menu->SetMenuItemChecked(mi_view_network, 1);
display_mode = KDL_DISPLAY_NETWORKS;
} else if (viewmode == "device") {
mi_lastview = mi_view_devices;
menu->SetMenuItemChecked(mi_view_devices, 1);
display_mode = KDL_DISPLAY_DEVICES;
} else if (viewmode == "wirelessdevice") {
mi_lastview = mi_view_wireless;
menu->SetMenuItemChecked(mi_view_wireless, 1);
display_mode = KDL_DISPLAY_WIRELESSDEVICES;
} else {
mi_lastview = mi_view_network;
menu->SetMenuItemChecked(mi_view_network, 1);
display_mode = KDL_DISPLAY_NETWORKS;
}
devicetracker->PanelInitialized();
ParseColumnConfig();
}
void Kis_Devicelist::ParseColumnConfig() {
string cols =
kpinterface->prefs->FetchOpt("devlist_columns");
string extcols =
kpinterface->prefs->FetchOpt("devlist_extline");
if (cols == "") {
cols = "active,phy,name,type,basiccrypt,address,"
"packets,datasize,channel,alerts";
kpinterface->prefs->SetOpt("devlist_columns", cols, 1);
}
if (extcols == "") {
extcols = "lastseen,basiccrypt,manuf,seenby,phyname";
kpinterface->prefs->SetOpt("devlist_extline", extcols, 1);
}
vector<string> toks = StrTokenize(cols, ",");
string t;
configured_column_vec.clear();
for (unsigned int x = 0; x < toks.size(); x++) {
t = StrLower(toks[x]);
bool set = 0;
// Sucks but only happens rarely
for (map<int, kdl_column *>::iterator i = registered_column_map.begin();
i != registered_column_map.end(); ++i) {
if (StrLower(i->second->name) == t && !i->second->subcolumn) {
set = true;
configured_column_vec.push_back(i->second);
break;
}
}
if (!set) {
_MSG("Unknown column '" + t + "'", MSGFLAG_INFO);
}
}
toks = StrTokenize(extcols, ",");
configured_subcolumn_vec.clear();
for (unsigned int x = 0; x < toks.size(); x++) {
t = StrLower(toks[x]);
bool set = 0;
// Sucks but only happens rarely
for (map<int, kdl_column *>::iterator i = registered_column_map.begin();
i != registered_column_map.end(); ++i) {
if (StrLower(i->second->name) == t && i->second->subcolumn) {
set = true;
configured_subcolumn_vec.push_back(i->second);
break;
}
}
if (!set) {
_MSG("Unknown extraline option '" + t + "'", MSGFLAG_INFO);
}
}
for (unsigned int x = 0; x < draw_vec.size(); x++)
draw_vec[x]->dirty = true;
draw_dirty = true;
colheadercache = "";
}
Kis_Devicelist::~Kis_Devicelist() {
globalreg->InsertGlobal("MAIN_DEVICELIST", NULL);
devicetracker->RemoveDevicerxCallback(newdevref);
devicetracker->RemovePhyrxCallback(newphyref);
kpinterface->Remove_Netcli_AddCli_CB(cli_addref);
kpinterface->Remove_All_Netcli_Conf_CB(KDL_ConfigureCli);
}
void Kis_Devicelist::SetViewMode(int in_mode) {
string mode = "network";
if (in_mode != display_mode) {
if (in_mode == KDL_DISPLAY_NETWORKS)
mode = "network";
else if (in_mode == KDL_DISPLAY_WIRELESSDEVICES)
mode = "wirelessdevice";
else if (in_mode == KDL_DISPLAY_DEVICES)
mode = "device";
kpinterface->prefs->SetOpt("MAIN_VIEWSTYLE", mode, 1);
display_mode = in_mode;
draw_dirty = true;
RefreshDisplayList();
}
}
void Kis_Devicelist::NetClientAdd(KisNetClient *in_cli, int add) {
// TODO figure out how to resolve PHY#s on reconnect
if (add == 0)
return;
in_cli->AddConfCallback(KDL_ConfigureCli, 1, this);
}
void Kis_Devicelist::NetClientConfigure(KisNetClient *in_cli, int in_recon) {
if (in_cli->RegisterProtoHandler("TIME", "timesec",
KDL_TIME, this) < 0) {
_MSG("KDL couldn't register *TIME? Something is broken, badly.",
MSGFLAG_ERROR);
in_cli->KillConnection();
return;
}
}
void Kis_Devicelist::DeviceRX(kis_tracked_device *device) {
map<mac_addr, kdl_display_device *>::iterator ddmi =
display_dev_map.find(device->key);
// Updated devices force us to re-sort
draw_dirty = true;
// TODO - intelligent add to display list, etc
if (ddmi == display_dev_map.end()) {
kdl_display_device *dd = new kdl_display_device;
dd->device = device;
dd->dirty = true;
display_dev_map[device->key] = dd;
display_dev_vec.push_back(dd);
// Determine if we put it in our draw vec
kis_device_common *common =
(kis_device_common *) device->fetch(devcomp_ref_common);
// No common? Fail
if (common == NULL) {
// fprintf(stderr, "debug - DeviceRX no common\n");
return;
}
// Don't add it to our device list if it's not a network
// If we're in device mode we get everything so don't filter
if (display_mode == KDL_DISPLAY_NETWORKS &&
(common->basic_type_set & KIS_DEVICE_BASICTYPE_AP) == 0) {
// fprintf(stderr, "debug - Devicerx display network, type not network\n");
return;
}
// Don't add it to our device list if it's flagged as wired
if (display_mode == KDL_DISPLAY_WIRELESSDEVICES &&
(common->basic_type_set & (KIS_DEVICE_BASICTYPE_WIRED)) != 0)
return;
// See if we're filtered, but only if we have more than one phy
if (filter_phy_map.size() > 1) {
map<int, bool>::iterator fpmi =
filter_phy_map.find(device->phy_type);
if (fpmi != filter_phy_map.end() &&
fpmi->second)
return;
}
// Add it to the list of networks we consider for display
draw_vec.push_back(dd);
} else {
ddmi->second->dirty = 1;
}
}
void Kis_Devicelist::PhyRX(int phy_id) {
string phyname = devicetracker->FetchPhyName(phy_id);
if (phyname == "") {
_MSG("KDL got new phy but empty phyname", MSGFLAG_ERROR);
return;
}
// If we've never seen this phyname or we want to show it, set the
// filter map to 0 to allow it
if (kpinterface->prefs->FetchOptBoolean("DEVICEFILTER_" + phyname, 1)) {
filter_phy_map[phy_id] = false;
} else {
filter_phy_map[phy_id] = true;
}
if (filter_phy_map.size() > 1)
menu->SetMenuVis(mn_filter, 1);
int mi_filteritem =
menu->AddMenuItem(phyname, mn_filter, 0);
menu->SetMenuItemChecked(mi_filteritem, !(filter_phy_map[phy_id]));
menu->SetMenuItemCallback(mi_filteritem, KDL_FilterMenuCB, this);
// Link menu ID to phy ID
menu_phy_map[mi_filteritem] = phy_id;
}
int Kis_Devicelist::RegisterSort(string in_name, string in_desc,
KDL_Sort_Callback in_cb, void *in_aux) {
for (map<int, kdl_sort *>::iterator x = sort_map.begin();
x != sort_map.end(); ++x) {
if (StrLower(x->second->name) == StrLower(in_name))
return x->first;
}
next_sort_id++;
kdl_sort *news = new kdl_sort;
news->name = in_name;
news->description = in_desc;
news->id = next_sort_id;
news->callback = in_cb;
news->cb_aux = in_aux;
news->menu_id =
menu->AddMenuItem(news->name, mn_sort, 0);
menu->SetMenuItemCallback(news->menu_id, KDL_SortMenuCB, this);
menu->SetMenuItemCheckSymbol(news->menu_id, '*');
if (StrLower(kpinterface->prefs->FetchOpt("MAIN_SORT")) == StrLower(in_name)) {
current_sort = news;
menu->SetMenuItemChecked(news->menu_id, 1);
}
sort_map[news->id] = news;
return news->id;
}
void Kis_Devicelist::RemoveSort(int in_id) {
if (sort_map.find(in_id) != sort_map.end()) {
kdl_sort *s = sort_map[in_id];
// Make the menu item invisible
menu->SetMenuItemVis(s->menu_id, 0);
delete(s);
sort_map.erase(in_id);
}
}
int Kis_Devicelist::RegisterColumn(string in_name, string in_desc,
int in_width, KisWidget_LabelPos in_align,
KDL_Column_Callback in_cb, void *in_aux,
bool in_sub) {
kdl_column *newc = NULL;
for (map<int, kdl_column *>::iterator x = registered_column_map.begin();
x != registered_column_map.end(); ++x) {
if (StrLower(x->second->name) == StrLower(in_name) &&
x->second->subcolumn == in_sub) {
// If we don't match auxptr we need to overwrite this column
if (x->second->cb_aux != in_aux)
newc = x->second;
else
return x->first;
}
}
// Otherwise we're replacing a column
if (newc == NULL) {
newc = new kdl_column;
next_column_id++;
}
newc->name = in_name;
newc->description = in_desc;
newc->width = in_width;
newc->subcolumn = in_sub;
newc->id = next_column_id;
newc->callback = in_cb;
newc->cb_aux = in_aux;
registered_column_map[newc->id] = newc;
return newc->id;
}
void Kis_Devicelist::RemoveColumn(int in_id) {
if (registered_column_map.find(in_id) != registered_column_map.end()) {
kdl_column *c = registered_column_map[in_id];
for (unsigned int x = 0; x < configured_column_vec.size(); x++) {
if (configured_column_vec[x] == c) {
configured_column_vec.erase(configured_column_vec.begin() + x);
x = 0;
}
}
for (unsigned int x = 0; x < configured_subcolumn_vec.size(); x++) {
if (configured_subcolumn_vec[x] == c) {
configured_subcolumn_vec.erase(configured_subcolumn_vec.begin() + x);
x = 0;
}
}
delete registered_column_map[in_id];
registered_column_map.erase(in_id);
}
}
kdl_column *Kis_Devicelist::FetchColumn(int in_id) {
map<int, kdl_column *>::iterator ci = registered_column_map.find(in_id);
if (ci == registered_column_map.end())
return NULL;
return ci->second;
}
void Kis_Devicelist::DrawComponent() {
if (visible == 0)
return;
parent_panel->ColorFromPref(color_inactive, "panel_textdis_color");
parent_panel->InitColorPref("devlist_normal_color", "green,black");
parent_panel->ColorFromPref(color_map[KDL_COLOR_NORMAL],
"devlist_normal_color");
parent_panel->InitColorPref("devlist_crypt_color", "yellow,black");
parent_panel->ColorFromPref(color_map[KDL_COLOR_CRYPT],
"devlist_crypt_color");
parent_panel->InitColorPref("devlist_decrypt_color", "hi-magenta,black");
parent_panel->ColorFromPref(color_map[KDL_COLOR_DECRYPT],
"devlist_decrypt_color");
parent_panel->InitColorPref("devlist_header_color", "blue,black");
parent_panel->ColorFromPref(color_map[KDL_COLOR_HEADER],
"devlist_header_color");
parent_panel->InitColorPref("devlist_insecure_color", "red,black");
parent_panel->ColorFromPref(color_map[KDL_COLOR_INSECURE],
"devlist_insecure_color");
string hdr = colheadercache;
if (hdr == "") {
hdr = " ";
for (unsigned int x = hpos; x < configured_column_vec.size(); x++) {
/*
if (hdr.length() + configured_column_vec[x]->width > viewable_cols)
break;
*/
hdr += "\004u" +
(*(configured_column_vec[x]->callback))(
NULL,
configured_column_vec[x]->cb_aux,
globalreg,
configured_column_vec[x]->id,
true) +
"\004U ";
}
colheadercache = hdr;
} else {
// hdr[0] = 'C';
}
if (active)
wattrset(window, color_map[KDL_COLOR_HEADER]);
Kis_Panel_Specialtext::Mvwaddnstr(window, sy, sx, hdr.c_str(),
lx - 1, parent_panel);
if (active)
wattrset(window, color_map[KDL_COLOR_NORMAL]);
if (kpinterface->FetchNetClient() == NULL ||
(kpinterface->FetchNetClient() != NULL && !kpinterface->FetchNetClient()->Valid())) {
mvwaddnstr(window, sy + 2, sx + 1,
"[ --- Not connected to a Kismet server --- ]", lx);
return;
} else if (display_dev_vec.size() == 0) {
mvwaddnstr(window, sy + 2, sx + 1,
"[ --- No devices seen by Kismet --- ]",
ex - sx);
return;
}
if (draw_vec.size() == 0 && display_dev_vec.size() != 0) {
Kis_Panel_Specialtext::Mvwaddnstr(window, sy + 2, sx + 1,
"[ --- All devices filtered, change filtering with View->Filter --- ]",
lx - 1, parent_panel);
return;
}
if (draw_dirty && current_sort != NULL) {
(*(current_sort->callback))(&draw_vec, current_sort->cb_aux,
current_sort, globalreg);
draw_dirty = false;
}
int dy = 0;
string display_line;
string extra_line;
for (unsigned int x = first_line; dy < viewable_lines &&
x < draw_vec.size(); x++) {
kis_device_common *common = NULL;
common =
(kis_device_common *) draw_vec[x]->device->fetch(devcomp_ref_common);
if (common == NULL)
continue;
int oft = globalreg->timestamp.tv_sec - common->last_time;
if (!draw_vec[x]->dirty && draw_vec[x]->columncache != "" && oft > 6) {
display_line = draw_vec[x]->columncache;
extra_line = draw_vec[x]->extcache;
// display_line[0] = 'C';
} else {
display_line = " ";
for (unsigned int c = hpos; c < configured_column_vec.size(); c++) {
if ((int) (display_line.length() +
configured_column_vec[c]->width) > viewable_cols)
break;
display_line +=
(*(configured_column_vec[c]->callback))(
draw_vec[x],
configured_column_vec[c]->cb_aux,
globalreg,
configured_column_vec[c]->id,
false) +
" ";
}
if ((int) display_line.length() < viewable_cols)
display_line += string(viewable_cols - display_line.length(), ' ');
// Clear the extra cache if we knew we were dirtied
extra_line = "";
draw_vec[x]->dirty = false;
draw_vec[x]->columncache = display_line;
}
dy++;
// We have to look at the device status for coloring here, external
// of columns. Only color if active.
if (active) {
wattrset(window, color_map[KDL_COLOR_NORMAL]);
if (common != NULL) {
if (common->basic_crypt_set) {
// fprintf(stderr, "draw %s cryptset %d\n", draw_vec[x]->device->key.Mac2String().c_str(), common->basic_crypt_set);
wattrset(window, color_map[KDL_COLOR_CRYPT]);
}
}
}
if (selected_line == (int) x && active) {
wattron(window, WA_REVERSE);
// Recompute the extra line
if (extra_line == "") {
extra_line = " ";
for (unsigned int c = 0; c < configured_subcolumn_vec.size(); c++) {
if ((int) extra_line.length() > viewable_cols)
break;
string f =
(*(configured_subcolumn_vec[c]->callback))(
draw_vec[x],
configured_subcolumn_vec[c]->cb_aux,
globalreg,
configured_subcolumn_vec[c]->id,
false);
if (f != "")
extra_line += " [" + f + "]";
}
if ((int) extra_line.length() < viewable_cols)
extra_line += string(viewable_cols - extra_line.length(), ' ');
draw_vec[x]->extcache = extra_line;
}
}
Kis_Panel_Specialtext::Mvwaddnstr(window, sy + dy, sx,
display_line,
lx - 1, parent_panel);
if (selected_line == (int) x && active) {
dy++;
Kis_Panel_Specialtext::Mvwaddnstr(window, sy + dy, sx,
extra_line,
lx - 1, parent_panel);
wattroff(window, WA_REVERSE);
}
last_line = x;
}
}
void Kis_Devicelist::Activate(int subcomponent) {
// _MSG("Activate devlist", MSGFLAG_INFO);
active = 1;
}
void Kis_Devicelist::Deactivate() {
active = 0;
}
void Kis_Devicelist::Proto_TIME() {
DrawComponent();
for (unsigned int x = 0; x < display_dev_vec.size(); x++) {
display_dev_vec[x]->dirty = false;
}
}
int Kis_Devicelist::KeyPress(int in_key) {
if (visible == 0)
return 0;
// _MSG("Keypress devlist", MSGFLAG_INFO);
if (in_key == KEY_DOWN || in_key == '+') {
if (selected_line < first_line || selected_line > last_line) {
selected_line = first_line;
return 0;
}
// If we're at the bottom and can go further, slide the selection
// and the first line down
if (selected_line == last_line &&
last_line < (int) draw_vec.size() - 1) {
selected_line++;
first_line++;
} else if (selected_line != last_line) {
// Otherwise we just slide the selected line down
selected_line++;
}
} else if (in_key == KEY_UP || in_key == '-') {
if (selected_line < first_line || selected_line > last_line) {
selected_line = first_line;
return 0;
}
// if we're at the top and can go further, slide the selection
// and first line of our view up
if (selected_line == first_line && first_line > 0) {
selected_line--;
first_line--;
} else if (selected_line != first_line) {
// just move the selected line up
selected_line--;
}
} else if (in_key == KEY_PPAGE) {
if (selected_line < 0 || selected_line > last_line) {
selected_line = first_line;
_MSG("OOB, selected=first, " + IntToString(selected_line), MSGFLAG_INFO);
return 0;
}
_MSG("setting first, " + IntToString( kismax(0, first_line - viewable_lines)) + " first: " + IntToString(first_line) + " viewable: " + IntToString(viewable_lines), MSGFLAG_INFO);
first_line = kismax(0, first_line - viewable_lines);
selected_line = first_line;
} else if (in_key == KEY_NPAGE) {
if (selected_line < 0 || selected_line > last_line) {
selected_line = first_line;
return 0;
}
first_line = kismin((int) draw_vec.size() - 1,
first_line + viewable_lines);
selected_line = first_line;
} else if (in_key == KEY_ENTER || in_key == '\n') {
Kis_DevDetails_Panel *dp =
new Kis_DevDetails_Panel(globalreg, kpinterface);
dp->Position(WIN_CENTER(LINES, COLS));
if (selected_line >= 0 && selected_line < (int) display_dev_vec.size()) {
kdl_display_device *dd = draw_vec[selected_line];
kis_tracked_device *sd = dd->device;
dp->SetTargetDevice(dd);
if (sd != NULL) {
Client_Phy_Handler *cliphy =
devicetracker->FetchPhyHandler(sd->phy_type);
if (cliphy != NULL)
cliphy->PanelDetails(dp, sd);
}
}
kpinterface->AddPanel(dp);
}
return 0;
}
int Kis_Devicelist::MouseEvent(MEVENT *mevent) {
int mwx, mwy;
getbegyx(window, mwy, mwx);
mwx = mevent->x - mwx;
mwy = mevent->y - mwy;
// Not in our bounds at all
if ((mevent->bstate != 4 && mevent->bstate != 8) ||
mwy < sy || mwy > ey || mwx < sx || mwx > ex)
return 0;
// Not in a selectable mode, we consume it but do nothing
// if (sort_mode == netsort_autofit)
// return 1;
//
// Modify coordinates to be inside the widget
mwy -= sy;
int vpos = first_line + mwy - 1;
if ((int) selected_line < vpos)
vpos--;
if (vpos < 0 || vpos > (int) draw_vec.size())
return 1;
// Double-click, trigger the activation callback
/*
if ((last_mouse_click - globalreg->timestamp.tv_sec < 1 &&
selected_line == vpos) || mevent->bstate == 8) {
if (cb_activate != NULL)
(*cb_activate)(this, 1, cb_activate_aux, globalreg);
return 1;
}
*/
last_mouse_click = globalreg->timestamp.tv_sec;
// Otherwise select it and center the network list on it
selected_line = vpos;
first_line = selected_line - (ly / 2);
if (first_line < 0)
first_line = 0;
return 1;
}
void Kis_Devicelist::SetPosition(int isx, int isy, int iex, int iey) {
Kis_Panel_Component::SetPosition(isx, isy, iex, iey);
viewable_lines = ly - 1;
viewable_cols = ex;
colheadercache = "";
RefreshDisplayList();
}
string Kis_Devicelist::CommonColumn(kdl_display_device *in_dev, int in_columnid,
bool header) {
char hdr[16];
char buf[64];
kdl_column *col = NULL;
map<int, kdl_column *>::iterator ci = registered_column_map.find(in_columnid);
if (ci == registered_column_map.end())
return "[INVALID]";
kis_device_common *common = NULL;
col = ci->second;
if (col->alignment == LABEL_POS_LEFT)
snprintf(hdr, 16, "%%%ds", col->width);
else
snprintf(hdr, 16, "%%-%d.%ds", col->width, col->width);
snprintf(buf, 64, hdr, "Unk");
if (!header) {
if (in_dev != NULL && in_dev->device != NULL)
common = (kis_device_common *) in_dev->device->fetch(devcomp_ref_common);
if (common == NULL) {
snprintf(buf, 64, hdr, "NULL");
return buf;
}
}
if (in_columnid == col_active) {
if (header) {
snprintf(buf, 64, "A");
} else {
int oft = globalreg->timestamp.tv_sec - common->last_time;
if (oft < 3)
snprintf(buf, 64, "!");
else if (oft < 6)
snprintf(buf, 64, ".");
else
snprintf(buf, 64, " ");
}
} else if (in_columnid == col_phy) {
if (header) {
snprintf(buf, 64, hdr, "Phy");
} else {
snprintf(buf, 64, hdr, devicetracker->FetchPhyName(in_dev->device->phy_type).c_str());
}
} else if (in_columnid == col_addr) {
if (header) {
snprintf(buf, 64, hdr, "Addr");
} else {
snprintf(buf, 64, hdr, in_dev->device->key.Mac2String().c_str());
}
} else if (in_columnid == col_name) {
if (header) {
snprintf(buf, 64, hdr, "Name");
} else {
snprintf(buf, 64, hdr, common->name.c_str());
}
} else if (in_columnid == col_type) {
if (header) {
snprintf(buf, 64, hdr, "Type");
} else {
if (common->type_string != "") {
snprintf(buf, 64, hdr, common->type_string.c_str());
} else {
if (common->basic_type_set & KIS_DEVICE_BASICTYPE_PEER)
snprintf(buf, 64, hdr, "Peer");
else if (common->basic_type_set & KIS_DEVICE_BASICTYPE_AP)
snprintf(buf, 64, hdr, "AP");
else if (common->basic_type_set & KIS_DEVICE_BASICTYPE_WIRED)
snprintf(buf, 64, hdr, "Wired");
else if (common->basic_type_set & KIS_DEVICE_BASICTYPE_CLIENT)
snprintf(buf, 64, hdr, "Client");
}
}
} else if (in_columnid == col_basictype) {
if (header) {
snprintf(buf, 64, hdr, "Basic");
} else {
if (common->basic_type_set == KIS_DEVICE_BASICTYPE_DEVICE)
snprintf(buf, 64, hdr, "Device");
// Order important for display
if (common->basic_type_set & KIS_DEVICE_BASICTYPE_PEER)
snprintf(buf, 64, hdr, "Peer");
else if (common->basic_type_set & KIS_DEVICE_BASICTYPE_AP)
snprintf(buf, 64, hdr, "AP");
else if (common->basic_type_set & KIS_DEVICE_BASICTYPE_WIRED)
snprintf(buf, 64, hdr, "Wired");
else if (common->basic_type_set & KIS_DEVICE_BASICTYPE_CLIENT)
snprintf(buf, 64, hdr, "Client");
}
} else if (in_columnid == col_cryptstr) {
if (header) {
snprintf(buf, 64, hdr, "Crpt");
} else {
if (common->crypt_string != "") {
snprintf(buf, 64, hdr, common->crypt_string.c_str());
} else {
if (common->basic_crypt_set & KIS_DEVICE_BASICCRYPT_L2)
snprintf(buf, 64, hdr, "L2");
else if (common->basic_crypt_set & KIS_DEVICE_BASICCRYPT_L3)
snprintf(buf, 64, hdr, "L3");
else if (common->basic_crypt_set == 0)
snprintf(buf, 64, hdr, "None");
}
}
} else if (in_columnid == col_basiccrypt) {
if (header) {
snprintf(buf, 64, hdr, "C");
} else {
// Default to yes for less interesting l2/l3/etc
if (common->basic_crypt_set == KIS_DEVICE_BASICCRYPT_NONE)
snprintf(buf, 64, hdr, "N");
else if (common->basic_crypt_set & KIS_DEVICE_BASICCRYPT_DECRYPTED)
snprintf(buf, 64, hdr, "D");
else if (common->basic_crypt_set & KIS_DEVICE_BASICCRYPT_WEAKCRYPT)
snprintf(buf, 64, hdr, "!");
else if (common->basic_crypt_set & KIS_DEVICE_BASICCRYPT_ENCRYPTED)
snprintf(buf, 64, hdr, "Y");
}
} else if (in_columnid == col_packets) {
if (header) {
snprintf(buf, 64, hdr, "Pkts");
} else {
snprintf(buf, 64, hdr, IntToString(common->packets).c_str());
}
} else if (in_columnid == col_llc) {
if (header) {
snprintf(buf, 64, hdr, "Link");
} else {
snprintf(buf, 64, hdr, IntToString(common->llc_packets).c_str());
}
} else if (in_columnid == col_error) {
if (header) {
snprintf(buf, 64, hdr, "Err");
} else {
snprintf(buf, 64, hdr, IntToString(common->error_packets).c_str());
}
} else if (in_columnid == col_data) {
if (header) {
snprintf(buf, 64, hdr, "Data");
} else {
snprintf(buf, 64, hdr, IntToString(common->data_packets).c_str());
}
} else if (in_columnid == col_crypt) {
if (header) {
snprintf(buf, 64, hdr, "Crypt");
} else {
snprintf(buf, 64, hdr, IntToString(common->crypt_packets).c_str());
}
} else if (in_columnid == col_datasize) {
if (header) {
snprintf(buf, 64, hdr, "Size");
} else {
if (common->datasize < 1024)
snprintf(buf, 64, hdr,
string(IntToString(common->datasize) + "B").c_str());
else if (common->datasize < (1024 * 1024))
snprintf(buf, 64, hdr,
string(IntToString(common->datasize / 1024) + "K").c_str());
else if (common->datasize < (1024 * 1024 * 1024))
snprintf(buf, 64, hdr,
string(IntToString(common->datasize / 1024 / 1024) +
"M").c_str());
else
snprintf(buf, 64, hdr,
string(IntToString(common->datasize / 1024 / 1024 / 1024) +
"G").c_str());
}
} else if (in_columnid == col_newpackets) {
if (header)
snprintf(buf, 64, hdr, "New");
else
snprintf(buf, 64, hdr, IntToString(common->new_packets).c_str());
} else if (in_columnid == col_channel) {
if (header)
snprintf(buf, 64, hdr, "Chan");
else
snprintf(buf, 64, hdr, IntToString(common->channel).c_str());
} else if (in_columnid == col_freq) {
if (header)
snprintf(buf, 64, hdr, "Freq");
else
snprintf(buf, 64, hdr, IntToString(common->frequency).c_str());
} else if (in_columnid == col_alerts) {
if (header)
snprintf(buf, 64, hdr, "Alrt");
else
snprintf(buf, 64, hdr, IntToString(common->alert).c_str());
} else if (in_columnid == col_manuf) {
if (header)
snprintf(buf, 64, hdr, "Manuf");
else
snprintf(buf, 64, hdr, common->manuf.c_str());
} else if (in_columnid == col_signal) {
if (header) {
snprintf(buf, 64, hdr, "Sig");
} else {
}
}
return buf;
}
string Kis_Devicelist::CommonSubColumn(kdl_display_device *in_dev, int in_columnid,
bool header) {
char buf[64];
int offt = 0;
if (header)
return "";
map<int, kdl_column *>::iterator ci = registered_column_map.find(in_columnid);
if (ci == registered_column_map.end())
return "[INVALID]";
kis_device_common *common = NULL;
buf[0] = '\0';
if (in_dev != NULL && in_dev->device != NULL)
common = (kis_device_common *) in_dev->device->fetch(devcomp_ref_common);
if (common == NULL) {
return "NULL";
}
if (in_columnid == col_sub_lastseen) {
snprintf(buf, 64, "Last seen: %.15s",
ctime((const time_t *) &(common->last_time)) + 4);
} else if (in_columnid == col_sub_addr) {
snprintf(buf, 64, "%s", in_dev->device->key.Mac2String().c_str());
} else if (in_columnid == col_sub_basiccrypt) {
snprintf(buf, 64, "Crypt:");
offt = 6;
if (common->basic_crypt_set == KIS_DEVICE_BASICCRYPT_NONE) {
snprintf(buf + offt, 64-offt, " None");
} else {
if (common->basic_crypt_set & KIS_DEVICE_BASICCRYPT_L2) {
snprintf(buf + offt, 64 - offt, " L2");
offt += 3;
}
if (common->basic_crypt_set & KIS_DEVICE_BASICCRYPT_L3) {
snprintf(buf + offt, 64 - offt, " L3");
offt += 3;
}
if (common->basic_crypt_set & KIS_DEVICE_BASICCRYPT_WEAKCRYPT) {
snprintf(buf + offt, 64 - offt, " Weak");
offt += 5;
}
if (common->basic_crypt_set & KIS_DEVICE_BASICCRYPT_DECRYPTED) {
snprintf(buf + offt, 64 - offt, " Decrypted");
offt += 10;
}
}
} else if (in_columnid == col_sub_manuf) {
snprintf(buf, 64, "%s", common->manuf.c_str());
} else if (in_columnid == col_sub_seenby) {
map<uuid, KisPanelInterface::knc_card *> *cardmap =
kpinterface->FetchNetCardMap();
map<uuid, KisPanelInterface::knc_card *>::iterator kci;
offt = 0;
for (map<uuid, kis_seenby_data *>::iterator smi = common->seenby_map.begin();
smi != common->seenby_map.end(); ++smi) {
if ((kci = cardmap->find(smi->first)) != cardmap->end()) {
snprintf(buf + offt, 64 - offt, "%s ",
kci->second->name.c_str());
offt += kci->second->name.length() + 1;
}
}
buf[offt] = '\0';
} else if (in_columnid == col_sub_phy) {
snprintf(buf, 64, "%s",
devicetracker->FetchPhyName(in_dev->device->phy_type).c_str());
}
return buf;
}
void Kis_Devicelist::RefreshDisplayList() {
// _MSG("refresh display\n", MSGFLAG_INFO);
draw_vec.clear();
draw_dirty = 1;
// fprintf(stderr, "debug - refreshing display list for view mode %d\n", display_mode);
first_line = selected_line = 0;
for (unsigned int x = 0; x < display_dev_vec.size(); x++) {
// Determine if we put it in our draw vec
kis_device_common *common =
(kis_device_common *) display_dev_vec[x]->device->fetch(devcomp_ref_common);
// No common? Fail
if (common == NULL) {
// fprintf(stderr, "debug - refresh, no common, skipping\n");
continue;
}
// Don't add it to our device list if it's not a network
// Devices get everything
if (display_mode == KDL_DISPLAY_NETWORKS &&
!(common->basic_type_set & KIS_DEVICE_BASICTYPE_AP)) {
// fprintf(stderr, "debug - network refresh, not an AP, skipping\n");
continue;
}
// Don't add it to our device list if it's flagged as wired
if (display_mode == KDL_DISPLAY_WIRELESSDEVICES &&
(common->basic_type_set & (KIS_DEVICE_BASICTYPE_WIRED)) != 0) {
continue;
}
// See if we're filtered, but only if we have more than one phy
// so we can't filter the only phy the server has
if (filter_phy_map.size() > 1) {
map<int, bool>::iterator fpmi =
filter_phy_map.find(display_dev_vec[x]->device->phy_type);
if (fpmi != filter_phy_map.end() &&
fpmi->second)
continue;
}
draw_vec.push_back(display_dev_vec[x]);
display_dev_vec[x]->dirty = 1;
}
}
void Kis_Devicelist::FilterMenuAction(int menuitem) {
map<int, int>::iterator mpmi =
menu_phy_map.find(menuitem);
menu->SetMenuItemChecked(menuitem, !(menu->GetMenuItemChecked(menuitem)));
if (mpmi != menu_phy_map.end()) {
_MSG("Filter menu Phy# " + IntToString(mpmi->second), MSGFLAG_INFO);
int set;
set = filter_phy_map[mpmi->second] = !(menu->GetMenuItemChecked(menuitem));
string phyname = devicetracker->FetchPhyName(mpmi->second);
if (phyname == "") {
_MSG("KDL filter menu empty phyname", MSGFLAG_ERROR);
return;
}
// Set the preference
kpinterface->prefs->SetOpt("DEVICEFILTER_" + phyname,
set ? "false" : "true", 1);
RefreshDisplayList();
}
}
void Kis_Devicelist::SortMenuAction(int menuitem) {
map<int, kdl_sort *>::iterator i;
if (current_sort != NULL && current_sort->menu_id == menuitem)
return;
// This is dumb but happens rarely
for (i = sort_map.begin(); i != sort_map.end(); ++i) {
if ((int) i->second->menu_id == menuitem) {
// _MSG("Found sort option", MSGFLAG_INFO);
// Uncheck the old menu
if (current_sort != NULL)
menu->SetMenuItemChecked(current_sort->menu_id, 0);
menu->SetMenuItemChecked(menuitem, 1);
// Check the new
current_sort = i->second;
kpinterface->prefs->SetOpt("MAIN_SORT", StrLower(i->second->name), 1);
break;
}
}
RefreshDisplayList();
}
void Kis_Devicelist::ViewMenuAction(int menuitem) {
_MSG("In item " + IntToString(menuitem) + " last " + IntToString(mi_lastview), MSGFLAG_INFO);
if (menuitem == mi_lastview)
return;
menu->SetMenuItemChecked(mi_lastview, 0);
menu->SetMenuItemChecked(menuitem, 1);
mi_lastview = menuitem;
_MSG("trigger " + IntToString(menuitem) + " network item " + IntToString(mi_view_network), MSGFLAG_INFO);
if (menuitem == mi_view_network) {
_MSG("View network", MSGFLAG_INFO);
SetViewMode(KDL_DISPLAY_NETWORKS);
} else if (menuitem == mi_view_wireless) {
_MSG("View wireless", MSGFLAG_INFO);
SetViewMode(KDL_DISPLAY_WIRELESSDEVICES);
} else if (menuitem == mi_view_devices) {
_MSG("View devices", MSGFLAG_INFO);
SetViewMode(KDL_DISPLAY_DEVICES);
}
}
void Kis_Devicelist::SpawnColorPrefWindow() {
Kis_ColorPref_Panel *cpp = new Kis_ColorPref_Panel(globalreg, kpinterface);
cpp->AddColorPref("devlist_normal_color", "Normal device");
cpp->AddColorPref("devlist_crypt_color", "Encrypted device");
cpp->AddColorPref("devlist_decrypt_color", "Decrypted device");
cpp->AddColorPref("devlist_header_color", "Column titles");
cpp->AddColorPref("devlist_insecure_color", "Insecure device");
kpinterface->AddPanel(cpp);
}
void Kis_Devicelist::SpawnColumnPrefWindow(bool extracols) {
Kis_ColumnPref_Panel *cpp = new Kis_ColumnPref_Panel(globalreg, kpinterface);
for (map<int, kdl_column *>::iterator x = registered_column_map.begin();
x != registered_column_map.end(); ++x) {
if (x->second->subcolumn == extracols)
cpp->AddColumn(x->second->name, x->second->description);
}
if (!extracols)
cpp->ColumnPref("devlist_columns", "Device List Columns");
else
cpp->ColumnPref("devlist_extline", "Device List Extras");
cpp->SetCompleteCallback(KDL_ColumnRefresh, this);
kpinterface->AddPanel(cpp);
}
int KDLD_MenuCB(COMPONENT_CALLBACK_PARMS) {
((Kis_DevDetails_Panel *) aux)->MenuAction(status);
return 1;
}
int KDLD_GraphTimer(TIMEEVENT_PARMS) {
return ((Kis_DevDetails_Panel *) auxptr)->GraphTimer();
}
Kis_DevDetails_Panel::Kis_DevDetails_Panel(GlobalRegistry *in_globalreg,
KisPanelInterface *in_intf) :
Kis_Panel(in_globalreg, in_intf) {
devicetracker =
(Client_Devicetracker *) globalreg->FetchGlobal("CLIENT_DEVICE_TRACKER");
devcomp_ref_common = devicetracker->RegisterDeviceComponent("COMMON");
grapheventid =
globalreg->timetracker->RegisterTimer(SERVER_TIMESLICES_SEC, NULL, 1,
KDLD_GraphTimer, (void *) this);
// Make the menu, default cb us
menu = new Kis_Menu(globalreg, this);
menu->SetCallback(COMPONENT_CBTYPE_ACTIVATED, KDLD_MenuCB, (void *) this);
mn_device = menu->AddMenu("Device", 0);
mi_addnote = menu->AddMenuItem("Device Note...", mn_device, 'N');
menu->AddMenuItem("-", mn_device, 0);
mi_close = menu->AddMenuItem("Close window", mn_device, 'w');
mn_view = menu->AddMenu("View", 0);
mi_dev = menu->AddMenuItem("Device details", mn_view, 'd');
menu->AddMenuItem("-", mn_view, 0);
mi_graphsig = menu->AddMenuItem("Signal Level", mn_view, 's');
mi_graphpacket = menu->AddMenuItem("Packet Rate", mn_view, 'p');
menu->Show();
AddComponentVec(menu, KIS_PANEL_COMP_EVT);
netdetailt = new Kis_Free_Text(globalreg, this);
AddComponentVec(netdetailt, (KIS_PANEL_COMP_DRAW | KIS_PANEL_COMP_EVT |
KIS_PANEL_COMP_TAB));
siggraph = new Kis_IntGraph(globalreg, this);
siggraph->SetName("DETAIL_SIG");
siggraph->SetPreferredSize(0, 8);
siggraph->SetScale(-110, -40);
siggraph->SetInterpolation(1);
siggraph->SetMode(0);
siggraph->Show();
siggraph->AddExtDataVec("Signal", 4, "graph_detail_sig", "yellow,yellow",
' ', ' ', 1, &sigpoints);
AddComponentVec(siggraph, KIS_PANEL_COMP_EVT);
packetgraph = new Kis_IntGraph(globalreg, this);
packetgraph->SetName("DETAIL_PPS");
packetgraph->SetPreferredSize(0, 8);
packetgraph->SetScale(0, 0);
packetgraph->SetInterpolation(1);
packetgraph->SetMode(0);
packetgraph->Show();
packetgraph->AddExtDataVec("Packet Rate", 4, "graph_detail_pps", "green,green",
' ', ' ', 1, &packetpps);
AddComponentVec(packetgraph, KIS_PANEL_COMP_EVT);
ClearGraphVectors();
SetTitle("");
vbox = new Kis_Panel_Packbox(globalreg, this);
vbox->SetPackV();
vbox->SetHomogenous(0);
vbox->SetSpacing(0);
vbox->Show();
vbox->Pack_End(siggraph, 0, 0);
vbox->Pack_End(packetgraph, 0, 0);
vbox->Pack_End(netdetailt, 1, 0);
AddComponentVec(vbox, KIS_PANEL_COMP_DRAW);
last_dirty = 0;
last_mac = mac_addr(0);
displaydev = NULL;
displaycommon = NULL;
vector<string> td;
td.push_back("");
td.push_back("No device selected");
td.push_back("Change sort order to anything other than \"Auto Fit\"");
td.push_back("and highlight a device.");
netdetailt->SetText(td);
UpdateViewMenu(-1);
SetActiveComponent(netdetailt);
main_component = vbox;
Position(WIN_CENTER(LINES, COLS));
}
Kis_DevDetails_Panel::~Kis_DevDetails_Panel() {
if (grapheventid >= 0 && globalreg != NULL)
globalreg->timetracker->RemoveTimer(grapheventid);
}
void Kis_DevDetails_Panel::SetTargetDevice(kdl_display_device *in_device) {
displaydev = in_device;
if (displaydev == NULL) {
displaycommon = NULL;
return;
}
if (displaydev->device != NULL) {
displaycommon =
(kis_device_common *) displaydev->device->fetch(devcomp_ref_common);
} else {
displaycommon = NULL;
}
}
void Kis_DevDetails_Panel::ClearGraphVectors() {
lastpackets = 0;
sigpoints.clear();
packetpps.clear();
for (unsigned int x = 0; x < 120; x++) {
sigpoints.push_back(-256);
packetpps.push_back(0);
}
}
void Kis_DevDetails_Panel::UpdateGraphVectors(int signal, int pps) {
sigpoints.push_back(signal);
if (sigpoints.size() > 120)
sigpoints.erase(sigpoints.begin(), sigpoints.begin() + sigpoints.size() - 120);
if (lastpackets == 0)
lastpackets = pps;
packetpps.push_back(pps - lastpackets);
lastpackets = pps;
if (packetpps.size() > 120)
packetpps.erase(packetpps.begin(), packetpps.begin() + packetpps.size() - 120);
}
void Kis_DevDetails_Panel::UpdateViewMenu(int mi) {
if (mi == mi_dev) {
if (kpinterface->prefs->FetchOptBoolean("DETAILS_SHOWDEV", 1)) {
kpinterface->prefs->SetOpt("DETAILS_SHOWDEV", "false", 1);
menu->SetMenuItemChecked(mi_dev, 0);
netdetailt->Hide();
} else {
kpinterface->prefs->SetOpt("DETAILS_SHOWDEV", "true", 1);
menu->SetMenuItemChecked(mi_dev, 1);
netdetailt->Show();
}
} else if (mi == mi_graphsig) {
if (kpinterface->prefs->FetchOptBoolean("DETAILS_SHOWGRAPHSIG", 0)) {
kpinterface->prefs->SetOpt("DETAILS_SHOWGRAPHSIG", "false", 1);
menu->SetMenuItemChecked(mi_graphsig, 0);
siggraph->Hide();
} else {
kpinterface->prefs->SetOpt("DETAILS_SHOWGRAPHSIG", "true", 1);
menu->SetMenuItemChecked(mi_graphsig, 1);
siggraph->Show();
}
} else if (mi == mi_graphpacket) {
if (kpinterface->prefs->FetchOptBoolean("DETAILS_SHOWGRAPHPACKET", 1)) {
kpinterface->prefs->SetOpt("DETAILS_SHOWGRAPHPACKET", "false", 1);
menu->SetMenuItemChecked(mi_graphpacket, 0);
packetgraph->Hide();
} else {
kpinterface->prefs->SetOpt("DETAILS_SHOWGRAPHPACKET", "true", 1);
menu->SetMenuItemChecked(mi_graphpacket, 1);
packetgraph->Show();
}
} else if (mi == -1) {
if (kpinterface->prefs->FetchOptBoolean("DETAILS_SHOWDEV", 1)) {
menu->SetMenuItemChecked(mi_dev, 1);
netdetailt->Show();
} else {
menu->SetMenuItemChecked(mi_dev, 0);
netdetailt->Hide();
}
if (kpinterface->prefs->FetchOptBoolean("DETAILS_SHOWGRAPHSIG", 0)) {
menu->SetMenuItemChecked(mi_graphsig, 1);
siggraph->Show();
} else {
menu->SetMenuItemChecked(mi_graphsig, 0);
siggraph->Hide();
}
if (kpinterface->prefs->FetchOptBoolean("DETAILS_SHOWGRAPHPACKET", 0)) {
menu->SetMenuItemChecked(mi_graphpacket, 1);
packetgraph->Show();
} else {
menu->SetMenuItemChecked(mi_graphpacket, 0);
packetgraph->Hide();
}
}
}
void Kis_DevDetails_Panel::MenuAction(int opt) {
if (opt == mi_close) {
globalreg->panel_interface->KillPanel(this);
return;
}
if (opt == mi_addnote) {
// TODO fix adding notes
return;
}
if (opt == mi_dev || opt == mi_graphsig || opt == mi_graphpacket) {
UpdateViewMenu(opt);
return;
}
}
int Kis_DevDetails_Panel::GraphTimer() {
if (displaycommon != NULL) {
if (displaycommon->last_time != last_dirty) {
last_dirty = displaycommon->last_time;
UpdateGraphVectors(displaycommon->snrdata.last_signal_dbm == -256 ?
displaycommon->snrdata.last_signal_rssi :
displaycommon->snrdata.last_signal_dbm,
displaycommon->packets);
}
}
return 1;
}
void Kis_DevDetails_Panel::DrawPanel() {
ColorFromPref(text_color, "panel_text_color");
ColorFromPref(border_color, "panel_border_color");
wbkgdset(win, text_color);
werase(win);
DrawTitleBorder();
vector<string> td;
if (displaycommon == NULL) {
td.push_back("No common tracking data for selected device");
} else {
td.push_back(AlignString("Name: ", ' ', 2, 16) + displaycommon->name);
td.push_back("");
td.push_back(AlignString("First time: ", ' ', 2, 16) +
string(ctime((const time_t *)
&(displaycommon->first_time)) + 4).substr(0, 15));
td.push_back(AlignString("Last time: ", ' ', 2, 16) +
string(ctime((const time_t *)
&(displaycommon->last_time)) + 4).substr(0, 15));
td.push_back("");
td.push_back(AlignString("MAC: ", ' ', 2, 16) +
displaycommon->device->key.Mac2String());
td.push_back(AlignString("Phy: ", ' ', 2, 16) +
devicetracker->FetchPhyName(displaycommon->device->phy_type));
td.push_back("");
if (displaycommon->snrdata.last_signal_dbm == KIS_SIGNAL_DBM_BOGUS_MIN &&
displaycommon->snrdata.last_signal_rssi == KIS_SIGNAL_RSSI_BOGUS_MIN) {
td.push_back(AlignString("Signal: ", ' ', 2, 16) +
"No signal data reported");
}
if (displaycommon->snrdata.last_signal_dbm != KIS_SIGNAL_DBM_BOGUS_MIN)
td.push_back(AlignString("Signal: ", ' ', 2, 16) +
IntToString(displaycommon->snrdata.last_signal_dbm) + "dBm");
if (displaycommon->snrdata.last_signal_rssi != KIS_SIGNAL_RSSI_BOGUS_MIN)
td.push_back(AlignString("Signal: ", ' ', 2, 16) +
IntToString(displaycommon->snrdata.last_signal_dbm) + "RSSI");
if (displaycommon->snrdata.last_noise_dbm == KIS_SIGNAL_DBM_BOGUS_MIN &&
displaycommon->snrdata.last_noise_rssi == KIS_SIGNAL_RSSI_BOGUS_MIN)
td.push_back(AlignString("Noise: ", ' ', 2, 16) +
"No noise data reported");
if (displaycommon->snrdata.last_noise_dbm != KIS_SIGNAL_DBM_BOGUS_MIN)
td.push_back(AlignString("Noise: ", ' ', 2, 16) +
IntToString(displaycommon->snrdata.last_noise_dbm) + "dBm");
if (displaycommon->snrdata.last_noise_rssi != KIS_SIGNAL_RSSI_BOGUS_MIN)
td.push_back(AlignString("Noise: ", ' ', 2, 16) +
IntToString(displaycommon->snrdata.last_noise_rssi) + "RSSI");
td.push_back("");
if (displaycommon->type_string != "")
td.push_back(AlignString("Type: ", ' ', 2, 16) +
displaycommon->type_string);
else
td.push_back(AlignString("Type: ", ' ', 2, 16) + "Device");
if (displaycommon->basic_type_set & KIS_DEVICE_BASICTYPE_AP)
td.push_back(AlignString("", ' ', 2, 16) + "AP/Coordinator");
if (displaycommon->basic_type_set & KIS_DEVICE_BASICTYPE_CLIENT)
td.push_back(AlignString("", ' ', 2, 16) + "Wireless client");
if (displaycommon->basic_type_set & KIS_DEVICE_BASICTYPE_WIRED)
td.push_back(AlignString("", ' ', 2, 16) + "Wired bridge");
if (displaycommon->basic_type_set & KIS_DEVICE_BASICTYPE_PEER)
td.push_back(AlignString("", ' ', 2, 16) + "Ad-Hoc/Peer");
td.push_back("");
if (displaycommon->crypt_string != "")
td.push_back(AlignString("Encryption: ", ' ', 2, 16) +
displaycommon->crypt_string);
else
td.push_back(AlignString("Encryption: ", ' ', 2, 16) + "None");
if (displaycommon->basic_crypt_set & KIS_DEVICE_BASICCRYPT_L2)
td.push_back(AlignString("", ' ', 2, 16) + "L2 / Phy link encryption");
if (displaycommon->basic_crypt_set & KIS_DEVICE_BASICCRYPT_L3)
td.push_back(AlignString("", ' ', 2, 16) + "L3 / Data link encryption");
if (displaycommon->basic_crypt_set & KIS_DEVICE_BASICCRYPT_WEAKCRYPT)
td.push_back(AlignString("", ' ', 2, 16) + "Known weak encryption");
if (displaycommon->basic_crypt_set & KIS_DEVICE_BASICCRYPT_DECRYPTED)
td.push_back(AlignString("", ' ', 2, 16) + "Decrypted");
td.push_back(AlignString("Channel: ", ' ', 2, 16) +
IntToString(displaycommon->channel));
td.push_back("");
td.push_back(AlignString("Packets: ", ' ', 2, 16) +
IntToString(displaycommon->packets));
if (displaycommon->tx_packets != 0 || displaycommon->rx_packets != 0) {
td.push_back(AlignString("Packets (tx): ", ' ', 2, 18) +
IntToString(displaycommon->tx_packets));
td.push_back(AlignString("Packets (rx): ", ' ', 2, 18) +
IntToString(displaycommon->tx_packets));
}
td.push_back(AlignString("Phy/LLC: ", ' ', 2, 18) +
IntToString(displaycommon->llc_packets));
td.push_back(AlignString("Error: ", ' ', 2, 18) +
IntToString(displaycommon->error_packets));
td.push_back(AlignString("Data: ", ' ', 2, 18) +
IntToString(displaycommon->data_packets));
td.push_back(AlignString("Encrypted: ", ' ', 2, 18) +
IntToString(displaycommon->crypt_packets));
td.push_back(AlignString("Filtered: ", ' ', 2, 18) +
IntToString(displaycommon->filter_packets));
td.push_back("");
if (displaycommon->datasize < 1024)
td.push_back(AlignString("Data: ", ' ', 2, 16) +
LongIntToString(displaycommon->datasize) + "B");
else if (displaycommon->datasize < (1024 * 1024))
td.push_back(AlignString("Data: ", ' ', 2, 16) +
LongIntToString(displaycommon->datasize / 1024) + "KB");
else if (displaycommon->datasize < (1024 * 1024 * 1024))
td.push_back(AlignString("Data: ", ' ', 2, 16) +
LongIntToString(displaycommon->datasize / 1024 / 1024) + "MB");
}
netdetailt->SetText(td);
if (displaydev != NULL && displaydev->device != NULL) {
Client_Phy_Handler *cliphy =
devicetracker->FetchPhyHandler(displaydev->device->phy_type);
if (cliphy != NULL)
cliphy->PanelDetailsText(netdetailt, displaydev->device);
}
DrawComponentVec();
wmove(win, 0, 0);
}
#endif // ncurses
| 30.207474 | 181 | 0.6802 | [
"vector"
] |
eb3cfa19f885e6bde643cf18ebad3b17fc87afbd | 798 | cpp | C++ | leetcode/410_Split-Array-Largest-Sum/SplitArrayLargestSum2.cpp | chasingegg/Online_Judge | 8a3f4b5b207cbeda921c743a527a25bf9c7b6248 | [
"MIT"
] | 1 | 2017-10-13T10:34:46.000Z | 2017-10-13T10:34:46.000Z | leetcode/410_Split-Array-Largest-Sum/SplitArrayLargestSum2.cpp | chasingegg/Online_Judge | 8a3f4b5b207cbeda921c743a527a25bf9c7b6248 | [
"MIT"
] | null | null | null | leetcode/410_Split-Array-Largest-Sum/SplitArrayLargestSum2.cpp | chasingegg/Online_Judge | 8a3f4b5b207cbeda921c743a527a25bf9c7b6248 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include <cstdio>
#include <cstring>
using namespace std;
class Solution {
public:
bool is_reach(vector<int> &nums, int m, long target_num) {
long cur_sum = nums[0];
int section = 1;
for (int i = 1; i < nums.size(); ++i) {
cur_sum += nums[i];
if (cur_sum > target_num) {
++section;
cur_sum = nums[i];
}
}
if (section > m) return false;
return true;
}
int splitArray(vector<int>& nums, int m) {
int n = nums.size();
long low = nums[0], high = nums[0];
for (int i = 1; i < n; ++i) {
low = max(low, long(nums[i]));
high += nums[i];
}
while (low < high) {
long mid = (low + high) / 2;
if (is_reach(nums, m, mid)) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}
}; | 19.463415 | 59 | 0.558897 | [
"vector"
] |
eb3d122256b42e4220e10696a0553fe172132d70 | 1,868 | cpp | C++ | Codeforces/1360E_Polygon.cpp | a3X3k/Competitive-programing-hacktoberfest-2021 | bc3997997318af4c5eafad7348abdd9bf5067b4f | [
"Unlicense"
] | 12 | 2021-06-05T09:40:10.000Z | 2021-10-07T17:59:51.000Z | Codeforces/1360E_Polygon.cpp | a3X3k/Competitive-programing-hacktoberfest-2021 | bc3997997318af4c5eafad7348abdd9bf5067b4f | [
"Unlicense"
] | 21 | 2021-09-30T22:25:03.000Z | 2021-10-05T18:23:25.000Z | Codeforces/1360E_Polygon.cpp | a3X3k/Competitive-programing-hacktoberfest-2021 | bc3997997318af4c5eafad7348abdd9bf5067b4f | [
"Unlicense"
] | 67 | 2021-08-01T10:04:52.000Z | 2021-10-10T00:25:04.000Z | // Problem Link: https://codeforces.com/contest/1360/problem/E
// Solution:
#include<bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int modulo = 998244353;
#define deb(...) logger(#__VA_ARGS__, __VA_ARGS__)
template<typename ...Args>
void logger(string vars, Args&&... values) {
cout << vars << " = ";
string delim = "";
(..., (cout << delim << values, delim = ", "));
}
typedef unsigned long long int ull;
typedef long long int ll;
ll power(ll a, ll b)
{
ll ans = 1;
while(b != 0)
{
if((b % 2) == 0)
{
a = ((a % mod) * (a % mod)) % mod;
b /= 2;
}
else
{
ans = ((ans % mod) * (a % mod)) % mod;
b--;
}
}
return (ans % mod);
}
void read_input_from_file()
{
#ifndef ONLINE_JUDGE
freopen("input_file.txt","r",stdin);
freopen("output_file.txt","w",stdout);
#endif
}
void sushovan()
{
int n;
cin>>n;
vector<string> s;
for(int i=0;i<n;i++)
{
string t;
cin>>t;
s.push_back(t);
}
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-1;j++)
{
if(s[i][j] == '1')
{
if(s[i + 1][j] == '0' && s[i][j + 1] == '0')
{
cout<<"NO\n";
return;
}
}
}
}
cout<<"YES\n";
}
int main()
{
auto begin = std::chrono::high_resolution_clock::now();
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// read_input_from_file();
ll t = 1;
cin>>t;
for(ll i=1;i<=t;i++)
{
sushovan();
}
auto end = std::chrono::high_resolution_clock::now();
//cout <<"\nExecution time: " << std::chrono::duration_cast<std::chrono::duration<double>>(end - begin).count() << " seconds "<<"\n";
return 0;
} | 20.304348 | 137 | 0.46788 | [
"vector"
] |
eb3d2431652bb84efd844b571a282bd84339e2c8 | 3,177 | cc | C++ | MagneticField/GeomBuilder/src/bRod.cc | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 1 | 2020-02-07T11:20:02.000Z | 2020-02-07T11:20:02.000Z | MagneticField/GeomBuilder/src/bRod.cc | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 7 | 2016-07-17T02:34:54.000Z | 2019-08-13T07:58:37.000Z | MagneticField/GeomBuilder/src/bRod.cc | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 2 | 2019-09-27T08:33:22.000Z | 2019-11-14T10:52:30.000Z | // #include "Utilities/Configuration/interface/Architecture.h"
/*
* See header file for a description of this class.
*
* \author N. Amapane - INFN Torino
*/
#include "MagneticField/GeomBuilder/src/bRod.h"
#include "Utilities/BinningTools/interface/ClusterizingHistogram.h"
#include "MagneticField/Layers/interface/MagBRod.h"
#include "MagneticField/Layers/interface/MagVerbosity.h"
#include "Utilities/General/interface/precomputed_value_sort.h"
using namespace SurfaceOrientation;
MagGeoBuilderFromDDD::bRod::~bRod() {}
//The ctor is in charge of finding slabs inside the rod.
MagGeoBuilderFromDDD::bRod::bRod(handles::const_iterator begin, handles::const_iterator end)
: volumes(begin, end), mrod(nullptr) {
precomputed_value_sort(volumes.begin(), volumes.end(), ExtractZ());
// Clusterize in Z
const float resolution = 5.; // cm
float zmin = volumes.front()->center().z() - resolution;
float zmax = volumes.back()->center().z() + resolution;
ClusterizingHistogram hisZ(int((zmax - zmin) / resolution) + 1, zmin, zmax);
if (MagGeoBuilderFromDDD::debug)
std::cout << " Z slabs: " << zmin << " " << zmax << std::endl;
handles::const_iterator first = volumes.begin();
handles::const_iterator last = volumes.end();
for (handles::const_iterator i = first; i != last; ++i) {
hisZ.fill((*i)->center().z());
}
std::vector<float> zClust = hisZ.clusterize(resolution);
if (MagGeoBuilderFromDDD::debug)
std::cout << " Found " << zClust.size() << " clusters in Z, "
<< " slabs: " << std::endl;
handles::const_iterator slabStart = first;
handles::const_iterator separ = first;
for (unsigned int i = 0; i < zClust.size() - 1; ++i) {
float zSepar = (zClust[i] + zClust[i + 1]) / 2.f;
while ((*separ)->center().z() < zSepar)
++separ;
if (MagGeoBuilderFromDDD::debug) {
std::cout << " Slab at: " << zClust[i] << " elements: " << separ - slabStart << " unique volumes: ";
volumeHandle::printUniqueNames(slabStart, separ);
}
slabs.push_back(bSlab(slabStart, separ));
slabStart = separ;
}
{
if (MagGeoBuilderFromDDD::debug) {
std::cout << " Slab at: " << zClust.back() << " elements: " << last - separ << " unique volumes: ";
volumeHandle::printUniqueNames(separ, last);
}
slabs.push_back(bSlab(separ, last));
}
// Check that all slabs have the same dphi.
std::vector<bSlab>::const_iterator i = slabs.begin();
Geom::Phi<float> phimax = (*i).maxPhi();
Geom::Phi<float> phimin = (*i).minPhi();
for (++i; i != slabs.end(); ++i) {
if (fabs(phimax - (*i).maxPhi()) > 0.001 || fabs(phimin - (*i).minPhi()) > 0.001) {
if (MagGeoBuilderFromDDD::debug)
std::cout << "*** WARNING: slabs in this rod have different dphi!" << std::endl;
}
}
}
MagBRod* MagGeoBuilderFromDDD::bRod::buildMagBRod() const {
if (mrod == nullptr) {
std::vector<MagBSlab*> mSlabs;
for (std::vector<bSlab>::const_iterator slab = slabs.begin(); slab != slabs.end(); ++slab) {
mSlabs.push_back((*slab).buildMagBSlab());
}
mrod = new MagBRod(mSlabs, slabs.front().minPhi()); //FIXME
}
return mrod;
}
| 35.3 | 110 | 0.639597 | [
"vector"
] |
eb42b27153f4a090a9e1d3dcd1fd4db758c3bff6 | 986 | cpp | C++ | testing/coordinate/point/fill_constructor.cpp | nerikhman/agency | 966ac59101f2fc3561a86b11874fbe8de361d0e4 | [
"BSD-3-Clause"
] | 129 | 2016-08-18T23:24:15.000Z | 2022-03-25T12:06:05.000Z | testing/coordinate/point/fill_constructor.cpp | nerikhman/agency | 966ac59101f2fc3561a86b11874fbe8de361d0e4 | [
"BSD-3-Clause"
] | 86 | 2016-08-19T03:43:33.000Z | 2020-07-20T14:27:41.000Z | testing/coordinate/point/fill_constructor.cpp | nerikhman/agency | 966ac59101f2fc3561a86b11874fbe8de361d0e4 | [
"BSD-3-Clause"
] | 23 | 2016-08-18T23:52:13.000Z | 2022-02-28T16:28:20.000Z | #include <iostream>
#include <cassert>
#include <algorithm>
#include <agency/coordinate.hpp>
void test_fill_constructor()
{
using namespace agency;
{
// test fill construct 1D point
constexpr size_t num_elements = 1;
point<int,num_elements> p(13);
ptrdiff_t expected_difference = num_elements;
assert(std::count(p.begin(), p.end(), 13) == expected_difference);
}
{
// test fill construct 2D point
constexpr size_t num_elements = 2;
point<int,num_elements> p(13);
ptrdiff_t expected_difference = num_elements;
assert(std::count(p.begin(), p.end(), 13) == expected_difference);
}
{
// test fill construct 3D point
constexpr size_t num_elements = 3;
point<int,num_elements> p(13);
ptrdiff_t expected_difference = num_elements;
assert(std::count(p.begin(), p.end(), 13) == expected_difference);
}
}
int main()
{
test_fill_constructor();
std::cout << "OK" << std::endl;
return 0;
}
| 18.603774 | 70 | 0.656187 | [
"3d"
] |
eb480a170e7550204d206feccaab4d3e58b3b517 | 28,158 | cc | C++ | sw/device/tests/dif/dif_spi_device_unittest.cc | danaagur/opentitan | 29b07c2e8ef829f9220e6ada3bdfc072fb9e1256 | [
"Apache-2.0"
] | 1 | 2021-07-16T09:16:42.000Z | 2021-07-16T09:16:42.000Z | sw/device/tests/dif/dif_spi_device_unittest.cc | danaagur/opentitan | 29b07c2e8ef829f9220e6ada3bdfc072fb9e1256 | [
"Apache-2.0"
] | 1 | 2020-12-13T08:49:01.000Z | 2021-08-08T21:15:14.000Z | sw/device/tests/dif/dif_spi_device_unittest.cc | danaagur/opentitan | 29b07c2e8ef829f9220e6ada3bdfc072fb9e1256 | [
"Apache-2.0"
] | null | null | null | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
#include "sw/device/lib/dif/dif_spi_device.h"
#include <limits>
#include "gtest/gtest.h"
#include "sw/device/lib/base/mmio.h"
#include "sw/device/lib/testing/mock_mmio.h"
#include "spi_device_regs.h" // Generated.
namespace dif_spi_device_unittest {
namespace {
using ::mock_mmio::LeInt;
using ::mock_mmio::MmioTest;
using ::mock_mmio::MockDevice;
// Convenience function for assembling a phased FIFO pointer.
uintptr_t FifoPtr(uintptr_t offset, bool phase) {
return offset | (static_cast<uintptr_t>(phase) << 11);
}
// Convenience function for generating a vector full of noisy data.
std::vector<char> MakeBlob(size_t len) {
std::vector<char> buf;
buf.resize(len);
uint8_t val = 1;
for (auto &c : buf) {
c = val;
val *= 31;
}
return buf;
}
class SpiTest : public testing::Test, public MmioTest {
protected:
static const uint16_t kFifoLen = 0x400;
dif_spi_device_t spi_ = {
.params = {.base_addr = dev().region()},
.rx_fifo_len = kFifoLen,
.tx_fifo_len = kFifoLen,
};
dif_spi_device_config_t config_ = {
.clock_polarity = kDifSpiDeviceEdgePositive,
.data_phase = kDifSpiDeviceEdgeNegative,
.tx_order = kDifSpiDeviceBitOrderMsbToLsb,
.rx_order = kDifSpiDeviceBitOrderMsbToLsb,
.rx_fifo_timeout = 63,
.rx_fifo_len = kFifoLen,
.tx_fifo_len = kFifoLen,
};
};
class AbortTest : public SpiTest {};
TEST_F(AbortTest, Immediate) {
EXPECT_MASK32(SPI_DEVICE_CONTROL_REG_OFFSET,
{{SPI_DEVICE_CONTROL_ABORT_BIT, 0x1, 0x1}});
EXPECT_READ32(SPI_DEVICE_STATUS_REG_OFFSET,
{{SPI_DEVICE_STATUS_ABORT_DONE_BIT, 0x1}});
EXPECT_EQ(dif_spi_device_abort(&spi_), kDifSpiDeviceOk);
}
TEST_F(AbortTest, Delayed) {
EXPECT_MASK32(SPI_DEVICE_CONTROL_REG_OFFSET,
{{SPI_DEVICE_CONTROL_ABORT_BIT, 0x1, 0x1}});
EXPECT_READ32(SPI_DEVICE_STATUS_REG_OFFSET, 0);
EXPECT_READ32(SPI_DEVICE_STATUS_REG_OFFSET, 0);
EXPECT_READ32(SPI_DEVICE_STATUS_REG_OFFSET, 0);
EXPECT_READ32(SPI_DEVICE_STATUS_REG_OFFSET, 0);
EXPECT_READ32(SPI_DEVICE_STATUS_REG_OFFSET, 0);
EXPECT_READ32(SPI_DEVICE_STATUS_REG_OFFSET, 0);
EXPECT_READ32(SPI_DEVICE_STATUS_REG_OFFSET,
{{SPI_DEVICE_STATUS_ABORT_DONE_BIT, 0x1}});
EXPECT_EQ(dif_spi_device_abort(&spi_), kDifSpiDeviceOk);
}
TEST_F(AbortTest, NullArgs) {
EXPECT_EQ(dif_spi_device_abort(nullptr), kDifSpiDeviceBadArg);
}
class ConfigTest : public SpiTest {};
TEST_F(ConfigTest, BasicInit) {
EXPECT_WRITE32(SPI_DEVICE_CFG_REG_OFFSET,
{
{SPI_DEVICE_CFG_CPOL_BIT, 0},
{SPI_DEVICE_CFG_CPHA_BIT, 0},
{SPI_DEVICE_CFG_TX_ORDER_BIT, 0},
{SPI_DEVICE_CFG_RX_ORDER_BIT, 0},
{SPI_DEVICE_CFG_TIMER_V_OFFSET, config_.rx_fifo_timeout},
});
EXPECT_WRITE32(SPI_DEVICE_RXF_ADDR_REG_OFFSET,
{
{SPI_DEVICE_RXF_ADDR_BASE_OFFSET, 0x000},
{SPI_DEVICE_RXF_ADDR_LIMIT_OFFSET, 0x400 - 1},
});
EXPECT_WRITE32(SPI_DEVICE_TXF_ADDR_REG_OFFSET,
{
{SPI_DEVICE_TXF_ADDR_BASE_OFFSET, 0x400},
{SPI_DEVICE_TXF_ADDR_LIMIT_OFFSET, 0x800 - 1},
});
EXPECT_EQ(dif_spi_device_configure(&spi_, config_), kDifSpiDeviceOk);
}
TEST_F(ConfigTest, ComplexInit) {
config_ = {
.clock_polarity = kDifSpiDeviceEdgeNegative,
.data_phase = kDifSpiDeviceEdgePositive,
.tx_order = kDifSpiDeviceBitOrderLsbToMsb,
.rx_order = kDifSpiDeviceBitOrderMsbToLsb,
.rx_fifo_timeout = 42,
.rx_fifo_len = 0x24,
.tx_fifo_len = kFifoLen,
};
EXPECT_WRITE32(SPI_DEVICE_CFG_REG_OFFSET,
{
{SPI_DEVICE_CFG_CPOL_BIT, 1},
{SPI_DEVICE_CFG_CPHA_BIT, 1},
{SPI_DEVICE_CFG_TX_ORDER_BIT, 1},
{SPI_DEVICE_CFG_RX_ORDER_BIT, 0},
{SPI_DEVICE_CFG_TIMER_V_OFFSET, config_.rx_fifo_timeout},
});
EXPECT_WRITE32(SPI_DEVICE_RXF_ADDR_REG_OFFSET,
{
{SPI_DEVICE_RXF_ADDR_BASE_OFFSET, 0x000},
{SPI_DEVICE_RXF_ADDR_LIMIT_OFFSET, 0x023},
});
EXPECT_WRITE32(SPI_DEVICE_TXF_ADDR_REG_OFFSET,
{
{SPI_DEVICE_TXF_ADDR_BASE_OFFSET, 0x024},
{SPI_DEVICE_TXF_ADDR_LIMIT_OFFSET, 0x423},
});
EXPECT_EQ(dif_spi_device_configure(&spi_, config_), kDifSpiDeviceOk);
}
TEST_F(ConfigTest, NullArgs) {
EXPECT_EQ(dif_spi_device_configure(nullptr, config_), kDifSpiDeviceBadArg);
}
TEST_F(ConfigTest, InitSramOverflow) {
config_.rx_fifo_len = 0x1000;
EXPECT_EQ(dif_spi_device_configure(&spi_, config_), kDifSpiDeviceBadArg);
}
class IrqTest : public SpiTest {};
TEST_F(IrqTest, Get) {
bool out;
EXPECT_READ32(SPI_DEVICE_INTR_STATE_REG_OFFSET,
{{SPI_DEVICE_INTR_STATE_RXF_BIT, 1}});
EXPECT_EQ(dif_spi_device_irq_is_pending(&spi_, kDifSpiDeviceIrqRxFull, &out),
kDifSpiDeviceOk);
EXPECT_TRUE(out);
EXPECT_READ32(SPI_DEVICE_INTR_STATE_REG_OFFSET,
{{SPI_DEVICE_INTR_STATE_RXERR_BIT, 0},
{SPI_DEVICE_INTR_STATE_RXF_BIT, 1}});
EXPECT_EQ(dif_spi_device_irq_is_pending(&spi_, kDifSpiDeviceIrqRxError, &out),
kDifSpiDeviceOk);
EXPECT_FALSE(out);
EXPECT_READ32(SPI_DEVICE_INTR_STATE_REG_OFFSET,
{{SPI_DEVICE_INTR_STATE_TXUNDERFLOW_BIT, 1}});
EXPECT_EQ(
dif_spi_device_irq_is_pending(&spi_, kDifSpiDeviceIrqTxUnderflow, &out),
kDifSpiDeviceOk);
EXPECT_TRUE(out);
EXPECT_READ32(SPI_DEVICE_INTR_STATE_REG_OFFSET,
{{SPI_DEVICE_INTR_STATE_TXLVL_BIT, 0}});
EXPECT_EQ(
dif_spi_device_irq_is_pending(&spi_, kDifSpiDeviceIrqTxBelowLevel, &out),
kDifSpiDeviceOk);
EXPECT_FALSE(out);
}
TEST_F(IrqTest, GetNull) {
bool out;
EXPECT_EQ(
dif_spi_device_irq_is_pending(nullptr, kDifSpiDeviceIrqRxFull, &out),
kDifSpiDeviceBadArg);
EXPECT_EQ(
dif_spi_device_irq_is_pending(&spi_, kDifSpiDeviceIrqRxFull, nullptr),
kDifSpiDeviceBadArg);
}
TEST_F(IrqTest, Enable) {
EXPECT_MASK32(SPI_DEVICE_INTR_ENABLE_REG_OFFSET,
{{SPI_DEVICE_INTR_ENABLE_RXF_BIT, 0x1, 1}});
EXPECT_EQ(dif_spi_device_irq_set_enabled(&spi_, kDifSpiDeviceIrqRxFull,
kDifSpiDeviceToggleEnabled),
kDifSpiDeviceOk);
EXPECT_MASK32(SPI_DEVICE_INTR_ENABLE_REG_OFFSET,
{{SPI_DEVICE_INTR_ENABLE_RXERR_BIT, 0x1, 0}});
EXPECT_EQ(dif_spi_device_irq_set_enabled(&spi_, kDifSpiDeviceIrqRxError,
kDifSpiDeviceToggleDisabled),
kDifSpiDeviceOk);
EXPECT_MASK32(SPI_DEVICE_INTR_ENABLE_REG_OFFSET,
{{SPI_DEVICE_INTR_ENABLE_TXUNDERFLOW_BIT, 0x1, 1}});
EXPECT_EQ(dif_spi_device_irq_set_enabled(&spi_, kDifSpiDeviceIrqTxUnderflow,
kDifSpiDeviceToggleEnabled),
kDifSpiDeviceOk);
EXPECT_MASK32(SPI_DEVICE_INTR_ENABLE_REG_OFFSET,
{{SPI_DEVICE_INTR_ENABLE_TXLVL_BIT, 0x1, 0}});
EXPECT_EQ(dif_spi_device_irq_set_enabled(&spi_, kDifSpiDeviceIrqTxBelowLevel,
kDifSpiDeviceToggleDisabled),
kDifSpiDeviceOk);
}
TEST_F(IrqTest, EnableNull) {
EXPECT_EQ(dif_spi_device_irq_set_enabled(nullptr, kDifSpiDeviceIrqRxFull,
kDifSpiDeviceToggleEnabled),
kDifSpiDeviceBadArg);
}
TEST_F(IrqTest, Force) {
EXPECT_WRITE32(SPI_DEVICE_INTR_TEST_REG_OFFSET,
{{SPI_DEVICE_INTR_TEST_RXF_BIT, 1}});
EXPECT_EQ(dif_spi_device_irq_force(&spi_, kDifSpiDeviceIrqRxFull),
kDifSpiDeviceOk);
EXPECT_WRITE32(SPI_DEVICE_INTR_TEST_REG_OFFSET,
{{SPI_DEVICE_INTR_TEST_RXERR_BIT, 1}});
EXPECT_EQ(dif_spi_device_irq_force(&spi_, kDifSpiDeviceIrqRxError),
kDifSpiDeviceOk);
EXPECT_WRITE32(SPI_DEVICE_INTR_TEST_REG_OFFSET,
{{SPI_DEVICE_INTR_TEST_TXUNDERFLOW_BIT, 1}});
EXPECT_EQ(dif_spi_device_irq_force(&spi_, kDifSpiDeviceIrqTxUnderflow),
kDifSpiDeviceOk);
EXPECT_WRITE32(SPI_DEVICE_INTR_TEST_REG_OFFSET,
{{SPI_DEVICE_INTR_TEST_TXLVL_BIT, 1}});
EXPECT_EQ(dif_spi_device_irq_force(&spi_, kDifSpiDeviceIrqTxBelowLevel),
kDifSpiDeviceOk);
}
TEST_F(IrqTest, ForceNull) {
EXPECT_EQ(dif_spi_device_irq_force(nullptr, kDifSpiDeviceIrqRxFull),
kDifSpiDeviceBadArg);
}
TEST_F(IrqTest, Levels) {
EXPECT_WRITE32(SPI_DEVICE_FIFO_LEVEL_REG_OFFSET,
{{SPI_DEVICE_FIFO_LEVEL_RXLVL_OFFSET, 42},
{SPI_DEVICE_FIFO_LEVEL_TXLVL_OFFSET, 123}});
EXPECT_EQ(dif_spi_device_set_irq_levels(&spi_, 42, 123), kDifSpiDeviceOk);
}
TEST_F(IrqTest, LevelsNull) {
EXPECT_EQ(dif_spi_device_set_irq_levels(nullptr, 123, 456),
kDifSpiDeviceBadArg);
}
class RxPendingTest : public SpiTest {};
TEST_F(RxPendingTest, BothZero) {
EXPECT_READ32(SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, 0x0},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, 0x0}});
size_t bytes_remaining;
EXPECT_EQ(dif_spi_device_rx_pending(&spi_, &bytes_remaining),
kDifSpiDeviceOk);
EXPECT_EQ(bytes_remaining, 0);
}
TEST_F(RxPendingTest, InPhaseEmpty) {
EXPECT_READ32(SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, FifoPtr(0x42, true)},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, FifoPtr(0x42, true)}});
size_t bytes_remaining;
EXPECT_EQ(dif_spi_device_rx_pending(&spi_, &bytes_remaining),
kDifSpiDeviceOk);
EXPECT_EQ(bytes_remaining, 0);
}
TEST_F(RxPendingTest, InPhase) {
EXPECT_READ32(SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, FifoPtr(0x57, true)},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, FifoPtr(0x42, true)}});
size_t bytes_remaining;
EXPECT_EQ(dif_spi_device_rx_pending(&spi_, &bytes_remaining),
kDifSpiDeviceOk);
EXPECT_EQ(bytes_remaining, 0x15);
}
TEST_F(RxPendingTest, OutOfPhaseFull) {
EXPECT_READ32(SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, FifoPtr(0x42, false)},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, FifoPtr(0x42, true)}});
size_t bytes_remaining;
EXPECT_EQ(dif_spi_device_rx_pending(&spi_, &bytes_remaining),
kDifSpiDeviceOk);
EXPECT_EQ(bytes_remaining, 0x400);
}
TEST_F(RxPendingTest, OutOfPhase) {
EXPECT_READ32(SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, FifoPtr(0x42, false)},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, FifoPtr(0x57, true)}});
size_t bytes_remaining;
EXPECT_EQ(dif_spi_device_rx_pending(&spi_, &bytes_remaining),
kDifSpiDeviceOk);
EXPECT_EQ(bytes_remaining, 0x3eb);
}
TEST_F(RxPendingTest, NullArgs) {
size_t bytes_remaining;
EXPECT_EQ(dif_spi_device_rx_pending(nullptr, &bytes_remaining),
kDifSpiDeviceBadArg);
EXPECT_EQ(dif_spi_device_rx_pending(&spi_, nullptr), kDifSpiDeviceBadArg);
}
class TxPendingTest : public SpiTest {};
TEST_F(TxPendingTest, BothZero) {
EXPECT_READ32(SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET, 0x0},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, 0x0}});
size_t bytes_remaining;
EXPECT_EQ(dif_spi_device_tx_pending(&spi_, &bytes_remaining),
kDifSpiDeviceOk);
EXPECT_EQ(bytes_remaining, 0);
}
TEST_F(TxPendingTest, InPhaseEmpty) {
EXPECT_READ32(SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET, FifoPtr(0x42, true)},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, FifoPtr(0x42, true)}});
size_t bytes_remaining;
EXPECT_EQ(dif_spi_device_tx_pending(&spi_, &bytes_remaining),
kDifSpiDeviceOk);
EXPECT_EQ(bytes_remaining, 0);
}
TEST_F(TxPendingTest, InPhase) {
EXPECT_READ32(SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET, FifoPtr(0x57, true)},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, FifoPtr(0x42, true)}});
size_t bytes_remaining;
EXPECT_EQ(dif_spi_device_tx_pending(&spi_, &bytes_remaining),
kDifSpiDeviceOk);
EXPECT_EQ(bytes_remaining, 0x15);
}
TEST_F(TxPendingTest, OutOfPhaseFull) {
EXPECT_READ32(SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET, FifoPtr(0x42, false)},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, FifoPtr(0x42, true)}});
size_t bytes_remaining;
EXPECT_EQ(dif_spi_device_tx_pending(&spi_, &bytes_remaining),
kDifSpiDeviceOk);
EXPECT_EQ(bytes_remaining, 0x400);
}
TEST_F(TxPendingTest, OutOfPhase) {
EXPECT_READ32(SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET, FifoPtr(0x42, false)},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, FifoPtr(0x57, true)}});
size_t bytes_remaining;
EXPECT_EQ(dif_spi_device_tx_pending(&spi_, &bytes_remaining),
kDifSpiDeviceOk);
EXPECT_EQ(bytes_remaining, 0x3eb);
}
TEST_F(TxPendingTest, NullArgs) {
size_t bytes_remaining;
EXPECT_EQ(dif_spi_device_tx_pending(nullptr, &bytes_remaining),
kDifSpiDeviceBadArg);
EXPECT_EQ(dif_spi_device_tx_pending(&spi_, nullptr), kDifSpiDeviceBadArg);
}
class RecvTest : public SpiTest {};
TEST_F(RecvTest, EmptyFifo) {
EXPECT_READ32(SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, FifoPtr(0x5a, false)},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, FifoPtr(0x5a, false)}});
std::string buf(16, '\0');
size_t recv_len = 0;
EXPECT_EQ(dif_spi_device_recv(&spi_, const_cast<char *>(buf.data()),
buf.size(), &recv_len),
kDifSpiDeviceOk);
EXPECT_EQ(recv_len, 0);
buf.resize(recv_len);
EXPECT_EQ(buf, "");
}
TEST_F(RecvTest, FullFifoAligned) {
EXPECT_READ32(SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, FifoPtr(0x50, true)},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, FifoPtr(0x50, false)}});
auto message = MakeBlob(kFifoLen);
auto fifo_base = SPI_DEVICE_BUFFER_REG_OFFSET;
for (int i = 0; i < kFifoLen; i += 4) {
auto idx = fifo_base + (i + 0x50) % kFifoLen;
EXPECT_READ32(idx, LeInt(&message[i]));
}
EXPECT_WRITE32(SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, FifoPtr(0x50, true)},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, FifoPtr(0x50, true)}});
std::vector<char> buf;
buf.resize(message.size() * 2);
size_t recv_len = 0;
EXPECT_EQ(dif_spi_device_recv(&spi_, buf.data(), buf.size(), &recv_len),
kDifSpiDeviceOk);
EXPECT_EQ(recv_len, message.size());
buf.resize(recv_len);
EXPECT_EQ(buf, message);
}
TEST_F(RecvTest, FullFifoSmallBuf) {
size_t buf_len = 0x22;
EXPECT_READ32(SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, FifoPtr(0x50, true)},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, FifoPtr(0x50, false)}});
auto message = MakeBlob(kFifoLen);
auto fifo_base = SPI_DEVICE_BUFFER_REG_OFFSET;
for (size_t i = 0; i < buf_len; i += 4) {
auto idx = fifo_base + (i + 0x50) % kFifoLen;
EXPECT_READ32(idx, LeInt(&message[i]));
}
EXPECT_WRITE32(
SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, FifoPtr(0x50, true)},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, FifoPtr(0x50 + buf_len, false)}});
std::vector<char> buf;
buf.resize(buf_len);
size_t recv_len = 0;
EXPECT_EQ(dif_spi_device_recv(&spi_, buf.data(), buf.size(), &recv_len),
kDifSpiDeviceOk);
EXPECT_EQ(recv_len, buf_len);
buf.resize(recv_len);
message.resize(recv_len);
EXPECT_EQ(buf, message);
}
TEST_F(RecvTest, FullyAligned) {
std::string message = "Hello, SPI!!";
ASSERT_EQ(message.size() % 4, 0);
EXPECT_READ32(
SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, FifoPtr(message.size(), false)},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, FifoPtr(0x00, false)}});
auto fifo_base = SPI_DEVICE_BUFFER_REG_OFFSET;
EXPECT_READ32(fifo_base + 0x0, LeInt(&message[0x0]));
EXPECT_READ32(fifo_base + 0x4, LeInt(&message[0x4]));
EXPECT_READ32(fifo_base + 0x8, LeInt(&message[0x8]));
EXPECT_WRITE32(
SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, FifoPtr(message.size(), false)},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, FifoPtr(message.size(), false)}});
std::string buf(message.size() * 2, '\0');
size_t recv_len = 0;
EXPECT_EQ(dif_spi_device_recv(&spi_, const_cast<char *>(buf.data()),
buf.size(), &recv_len),
kDifSpiDeviceOk);
EXPECT_EQ(recv_len, message.size());
buf.resize(recv_len);
EXPECT_EQ(buf, message);
}
TEST_F(RecvTest, UnalignedMessage) {
std::string message = "Hello, SPI!!";
ASSERT_EQ(message.size() % 4, 0);
uintptr_t cropped_len = 9;
EXPECT_READ32(SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, FifoPtr(cropped_len, false)},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, FifoPtr(0x00, false)}});
auto fifo_base = SPI_DEVICE_BUFFER_REG_OFFSET;
EXPECT_READ32(fifo_base + 0x0, LeInt(&message[0x0]));
EXPECT_READ32(fifo_base + 0x4, LeInt(&message[0x4]));
EXPECT_READ32(fifo_base + 0x8, LeInt(&message[0x8]));
EXPECT_WRITE32(
SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, FifoPtr(cropped_len, false)},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, FifoPtr(cropped_len, false)}});
std::string buf(message.size() * 2, '\0');
size_t recv_len = 0;
EXPECT_EQ(dif_spi_device_recv(&spi_, const_cast<char *>(buf.data()),
buf.size(), &recv_len),
kDifSpiDeviceOk);
EXPECT_EQ(recv_len, cropped_len);
buf.resize(message.size());
EXPECT_NE(buf, message);
buf.resize(recv_len);
EXPECT_EQ(buf, message.substr(0, cropped_len));
}
TEST_F(RecvTest, UnalignedStart) {
std::string message = "Hello, SPI!!";
ASSERT_EQ(message.size() % 4, 0);
uintptr_t cropped_start = 1;
uintptr_t cropped_len = 9;
EXPECT_READ32(
SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, FifoPtr(cropped_len, false)},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, FifoPtr(cropped_start, false)}});
auto fifo_base = SPI_DEVICE_BUFFER_REG_OFFSET;
EXPECT_READ32(fifo_base + 0x0, LeInt(&message[0x0]));
EXPECT_READ32(fifo_base + 0x4, LeInt(&message[0x4]));
EXPECT_READ32(fifo_base + 0x8, LeInt(&message[0x8]));
EXPECT_WRITE32(
SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, FifoPtr(cropped_len, false)},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, FifoPtr(cropped_len, false)}});
std::string buf(message.size() * 2, '\0');
size_t recv_len = 0;
EXPECT_EQ(dif_spi_device_recv(&spi_, const_cast<char *>(buf.data()),
buf.size(), &recv_len),
kDifSpiDeviceOk);
EXPECT_EQ(recv_len, cropped_len - cropped_start);
buf.resize(message.size());
EXPECT_NE(buf, message);
buf.resize(recv_len);
EXPECT_EQ(buf, message.substr(cropped_start, cropped_len - cropped_start));
}
TEST_F(RecvTest, UnalignedSmall) {
std::string message = "Hello, SPI!!";
ASSERT_EQ(message.size() % 4, 0);
uintptr_t cropped_start = 1;
uintptr_t cropped_len = 3;
EXPECT_READ32(
SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, FifoPtr(cropped_len, false)},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, FifoPtr(cropped_start, false)}});
auto fifo_base = SPI_DEVICE_BUFFER_REG_OFFSET;
EXPECT_READ32(fifo_base + 0x0, LeInt(&message[0x0]));
EXPECT_WRITE32(
SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, FifoPtr(cropped_len, false)},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, FifoPtr(cropped_len, false)}});
std::string buf(message.size() * 2, '\0');
size_t recv_len = 0;
EXPECT_EQ(dif_spi_device_recv(&spi_, const_cast<char *>(buf.data()),
buf.size(), &recv_len),
kDifSpiDeviceOk);
EXPECT_EQ(recv_len, cropped_len - cropped_start);
buf.resize(message.size());
EXPECT_NE(buf, message);
buf.resize(recv_len);
EXPECT_EQ(buf, message.substr(cropped_start, cropped_len - cropped_start));
}
TEST_F(RecvTest, NullArgs) {
std::string buf(16, '\0');
size_t recv_len;
EXPECT_EQ(dif_spi_device_recv(nullptr, const_cast<char *>(buf.data()),
buf.size(), &recv_len),
kDifSpiDeviceBadArg);
EXPECT_EQ(dif_spi_device_recv(&spi_, nullptr, buf.size(), &recv_len),
kDifSpiDeviceBadArg);
EXPECT_READ32(SPI_DEVICE_RXF_PTR_REG_OFFSET,
{{SPI_DEVICE_RXF_PTR_WPTR_OFFSET, FifoPtr(0x5a, false)},
{SPI_DEVICE_RXF_PTR_RPTR_OFFSET, FifoPtr(0x5a, false)}});
EXPECT_EQ(dif_spi_device_recv(&spi_, const_cast<char *>(buf.data()),
buf.size(), nullptr),
kDifSpiDeviceOk);
}
class SendTest : public SpiTest {};
TEST_F(SendTest, FullFifo) {
EXPECT_READ32(SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET, FifoPtr(0x5a, true)},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, FifoPtr(0x5a, false)}});
std::string message = "Hello, SPI!!";
size_t send_len = 0;
EXPECT_EQ(
dif_spi_device_send(&spi_, message.data(), message.size(), &send_len),
kDifSpiDeviceOk);
EXPECT_EQ(send_len, 0);
}
TEST_F(SendTest, EmptyToFull) {
EXPECT_READ32(SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET, FifoPtr(0x50, true)},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, FifoPtr(0x50, true)}});
auto message = MakeBlob(kFifoLen);
auto fifo_base = SPI_DEVICE_BUFFER_REG_OFFSET + spi_.rx_fifo_len;
for (int i = 0; i < kFifoLen; i += 4) {
auto idx = fifo_base + (i + 0x50) % kFifoLen;
EXPECT_WRITE32(idx, LeInt(&message[i]));
}
EXPECT_WRITE32(SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET, FifoPtr(0x50, false)},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, FifoPtr(0x50, true)}});
size_t sent_len = 0;
EXPECT_EQ(
dif_spi_device_send(&spi_, message.data(), message.size(), &sent_len),
kDifSpiDeviceOk);
EXPECT_EQ(sent_len, message.size());
}
TEST_F(SendTest, AlmostFull) {
EXPECT_READ32(SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET, FifoPtr(0x4e, true)},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, FifoPtr(0x50, false)}});
std::string message = "Hello, world!";
uintptr_t value = 0;
memcpy(&value, message.data(), 2);
auto fifo_base = SPI_DEVICE_BUFFER_REG_OFFSET + spi_.rx_fifo_len;
EXPECT_MASK32(fifo_base + 0x4c, {{0x10, 0xffff, value}});
EXPECT_WRITE32(SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET, FifoPtr(0x50, true)},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, FifoPtr(0x50, false)}});
size_t sent_len = 0;
EXPECT_EQ(
dif_spi_device_send(&spi_, message.data(), message.size(), &sent_len),
kDifSpiDeviceOk);
EXPECT_EQ(sent_len, 2);
}
TEST_F(SendTest, FullyAligned) {
std::string message = "Hello, SPI!!";
ASSERT_EQ(message.size() % 4, 0);
EXPECT_READ32(SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET, FifoPtr(0x00, false)},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, FifoPtr(0x00, false)}});
auto fifo_base = SPI_DEVICE_BUFFER_REG_OFFSET + spi_.rx_fifo_len;
EXPECT_WRITE32(fifo_base + 0x0, LeInt(&message[0x0]));
EXPECT_WRITE32(fifo_base + 0x4, LeInt(&message[0x4]));
EXPECT_WRITE32(fifo_base + 0x8, LeInt(&message[0x8]));
EXPECT_WRITE32(
SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET, FifoPtr(message.size(), false)},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, FifoPtr(0x0, false)}});
size_t send_len = 0;
EXPECT_EQ(
dif_spi_device_send(&spi_, message.data(), message.size(), &send_len),
kDifSpiDeviceOk);
EXPECT_EQ(send_len, message.size());
}
TEST_F(SendTest, UnalignedMessage) {
std::string message = "Hello, SPI!!";
ASSERT_EQ(message.size() % 4, 0);
uintptr_t cropped_len = 9;
EXPECT_READ32(SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET, FifoPtr(0x00, false)},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, FifoPtr(0x00, false)}});
auto fifo_base = SPI_DEVICE_BUFFER_REG_OFFSET + spi_.rx_fifo_len;
EXPECT_WRITE32(fifo_base + 0x0, LeInt(&message[0x0]));
EXPECT_WRITE32(fifo_base + 0x4, LeInt(&message[0x4]));
uintptr_t value = 0;
memcpy(&value, &message[0x8], 1);
EXPECT_MASK32(fifo_base + 0x8, {{0x0, 0xff, value}});
EXPECT_WRITE32(SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET, FifoPtr(cropped_len, false)},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, FifoPtr(0x0, false)}});
size_t send_len = 0;
EXPECT_EQ(dif_spi_device_send(&spi_, message.data(), cropped_len, &send_len),
kDifSpiDeviceOk);
EXPECT_EQ(send_len, cropped_len);
}
TEST_F(SendTest, UnalignedStart) {
std::string message = "Hello, SPI!!";
ASSERT_EQ(message.size() % 4, 0);
uintptr_t cropped_start = 1;
uintptr_t cropped_len = 9;
EXPECT_READ32(
SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET, FifoPtr(cropped_start, false)},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, FifoPtr(cropped_start, false)}});
auto fifo_base = SPI_DEVICE_BUFFER_REG_OFFSET + spi_.rx_fifo_len;
uintptr_t start_value = 0;
memcpy(&start_value, &message[0x0], 3);
EXPECT_MASK32(fifo_base + 0x0, {{0x8, 0xffffff, start_value}});
EXPECT_WRITE32(fifo_base + 0x4, LeInt(&message[0x3]));
uintptr_t end_value = 0;
memcpy(&end_value, &message[0x7], 2);
EXPECT_MASK32(fifo_base + 0x8, {{0x0, 0xffff, end_value}});
EXPECT_WRITE32(
SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET,
FifoPtr(cropped_len + cropped_start, false)},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, FifoPtr(cropped_start, false)}});
size_t send_len = 0;
EXPECT_EQ(dif_spi_device_send(&spi_, message.data(), cropped_len, &send_len),
kDifSpiDeviceOk);
EXPECT_EQ(send_len, cropped_len);
}
TEST_F(SendTest, UnalignedSmall) {
std::string message = "Hello, SPI!!";
ASSERT_EQ(message.size() % 4, 0);
uintptr_t cropped_start = 1;
uintptr_t cropped_len = 2;
EXPECT_READ32(
SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET, FifoPtr(cropped_start, false)},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, FifoPtr(cropped_start, false)}});
auto fifo_base = SPI_DEVICE_BUFFER_REG_OFFSET + spi_.rx_fifo_len;
uintptr_t start_value = 0;
memcpy(&start_value, &message[0x0], 2);
EXPECT_MASK32(fifo_base + 0x0, {{0x8, 0xffff, start_value}});
EXPECT_WRITE32(
SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET,
FifoPtr(cropped_len + cropped_start, false)},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, FifoPtr(cropped_start, false)}});
size_t send_len = 0;
EXPECT_EQ(dif_spi_device_send(&spi_, message.data(), cropped_len, &send_len),
kDifSpiDeviceOk);
EXPECT_EQ(send_len, cropped_len);
}
TEST_F(SendTest, NullArgs) {
std::string buf(16, '\0');
size_t recv_len;
EXPECT_EQ(dif_spi_device_send(nullptr, buf.data(), buf.size(), &recv_len),
kDifSpiDeviceBadArg);
EXPECT_EQ(dif_spi_device_send(&spi_, nullptr, buf.size(), &recv_len),
kDifSpiDeviceBadArg);
EXPECT_READ32(SPI_DEVICE_TXF_PTR_REG_OFFSET,
{{SPI_DEVICE_TXF_PTR_WPTR_OFFSET, FifoPtr(0x5a, true)},
{SPI_DEVICE_TXF_PTR_RPTR_OFFSET, FifoPtr(0x5a, false)}});
EXPECT_EQ(dif_spi_device_send(&spi_, buf.data(), buf.size(), nullptr),
kDifSpiDeviceOk);
}
} // namespace
} // namespace dif_spi_device_unittest
| 35.109726 | 80 | 0.690248 | [
"vector"
] |
eb4f009b84036f77445c6450cf3af809177da141 | 2,554 | cpp | C++ | src/mexpr_test.cpp | haptork/pawn | b0c2431118de05eda59343fb98118dba54222133 | [
"BSL-1.0"
] | 2 | 2019-06-02T06:39:04.000Z | 2020-03-09T07:38:20.000Z | src/mexpr_test.cpp | haptork/pawn | b0c2431118de05eda59343fb98118dba54222133 | [
"BSL-1.0"
] | null | null | null | src/mexpr_test.cpp | haptork/pawn | b0c2431118de05eda59343fb98118dba54222133 | [
"BSL-1.0"
] | null | null | null | #include <iostream>
#include <map>
#include <numeric>
#include <mast.hpp>
#include <mexpr.hpp>
#include <helper.hpp>
int testMath() {
std::cout << "/////////////////////////////////////////////////////////\n\n";
std::cout << "Math Expression parser...\n\n";
std::cout << "/////////////////////////////////////////////////////////\n\n";
std::cout << "Type an expression...or [q or Q] to quit\n\n";
typedef std::string::const_iterator iterator_type;
typedef client::math::parser::expression<iterator_type> parser;
typedef client::math::ast::expr ast_expression;
typedef client::math::ast::printer ast_printer;
typedef client::math::ast::evaluator ast_evaluator;
std::string str;
while (std::getline(std::cin, str))
{
if (str.empty() || str[0] == 'q' || str[0] == 'Q')
break;
std::vector<size_t> colIndices;
colIndices.resize(9);
std::iota(std::begin(colIndices), std::end(colIndices), 1);
std::vector<std::string> vars {"xyz"};
ast_printer print;
client::helper::Global g;
client::helper::ColIndices cl;
cl.num = colIndices;
cl.var = vars;
ast_evaluator eval{client::helper::positionTeller{cl}, g};
std::string::const_iterator iter = str.begin();
std::string::const_iterator end = str.end();
client::error_handler<iterator_type> error_handler;//(iter, end); // Our error handler
parser calc{error_handler}; // Our grammar
ast_expression expression; // Our program (AST)
boost::spirit::ascii::space_type space;
bool r = phrase_parse(iter, end, calc, space, expression);
if (r && iter == end) {
std::cout << "-------------------------\n";
std::cout << "Parsing succeeded\n";
print(expression);
std::cout << "\n";
auto e = eval(expression);
std::cout << "\n function evaluated \n" << std::flush;
std::vector<double> v;
v.resize(10);
std::iota(std::begin(v), std::end(v), 0);
std::cout << "result: " << e(v);
std::cout << "-------------------------\n";
}
else {
std::string rest(iter, end);
std::cout << "-------------------------\n";
std::cout << "Parsing failed\n";
std::cout << "at: " << rest << '\n';
std::cout << "-------------------------\n";
}
}
std::cout << "Bye... :-) \n\n";
return 0;
}
| 34.513514 | 94 | 0.490603 | [
"vector"
] |
eb4f5d5aa6599bafb0785bf0c5fdc3d475446354 | 1,848 | cpp | C++ | data/transcoder_evaluation_gfg/cpp/SEARCH_INSERT_AND_DELETE_IN_A_SORTED_ARRAY_1.cpp | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 241 | 2021-07-20T08:35:20.000Z | 2022-03-31T02:39:08.000Z | data/transcoder_evaluation_gfg/cpp/SEARCH_INSERT_AND_DELETE_IN_A_SORTED_ARRAY_1.cpp | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 49 | 2021-07-22T23:18:42.000Z | 2022-03-24T09:15:26.000Z | data/transcoder_evaluation_gfg/cpp/SEARCH_INSERT_AND_DELETE_IN_A_SORTED_ARRAY_1.cpp | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 71 | 2021-07-21T05:17:52.000Z | 2022-03-29T23:49:28.000Z | // Copyright (c) 2019-present, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the license found in the
// LICENSE file in the root directory of this source tree.
//
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <fstream>
#include <iomanip>
#include <bits/stdc++.h>
using namespace std;
int f_gold ( int arr [ ], int n, int key, int capacity ) {
if ( n >= capacity ) return n;
int i;
for ( i = n - 1;
( i >= 0 && arr [ i ] > key );
i -- ) arr [ i + 1 ] = arr [ i ];
arr [ i + 1 ] = key;
return ( n + 1 );
}
//TOFILL
int main() {
int n_success = 0;
vector<vector<int>> param0 {{69},{-34,-38,-72,90,-84,-40,-40,-52,-12,80,-4,-58},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1},{96,34,11,1,36,79,64,75,75,96,32,18,25,79,63,80,90,75,44,71,48,1,62,53,17,98},{-98,-92,-92,-84,-82,-80,-80,-74,-70,-60,-48,-42,-36,-34,-34,-34,-30,-28,-16,-6,-2,-2,2,12,14,20,24,40,46,50,60,66,70,72,78,82,88,92,94,94,96},{1,0,1,1,0,0,1,0,0,0,1,1,0},{10,12,12,19,20,21,24,27,37,47,50,54,55,58,61,63,63,68,73,75,87,90,90,92,92},{-74,62,74,92,-38,-28,-26,4,88,-68,-76,-20,-4,12,72,6,42,36,88,-96,-80,90,80,-26,-36,-72,-62,38,-20,40,-10,-22,-20,38,82,-84,8,-60,86,-26,44,-72,-70,-16,-22,18,-16,76,-50},{1,1,1,1,1},{64,80,47,58,41,3,85,96,51,4,22,89,67,54,88,15,83,31,19,28,40,67,37,13,63,38,27,14,7,68}};
vector<int> param1 {0,6,13,21,30,12,12,37,3,23};
vector<int> param2 {0,6,19,20,32,9,13,26,4,24};
vector<int> param3 {0,9,11,13,28,10,21,42,2,25};
for(int i = 0; i < param0.size(); ++i)
{
if(f_filled(¶m0[i].front(),param1[i],param2[i],param3[i]) == f_gold(¶m0[i].front(),param1[i],param2[i],param3[i]))
{
n_success+=1;
}
}
cout << "#Results:" << " " << n_success << ", " << param0.size();
return 0;
} | 42 | 732 | 0.564935 | [
"vector"
] |
eb56493859263e619a2b783c40283600ab496501 | 636 | hpp | C++ | Biosphere/Include/bio/biocoenosis/flora/account/Types.hpp | PMArkive/Biosphere | baf62450b084ce327c3fc2eb0aa918e32462164e | [
"MIT"
] | 1 | 2021-09-10T17:18:51.000Z | 2021-09-10T17:18:51.000Z | Biosphere/Include/bio/biocoenosis/flora/account/Types.hpp | PMArkive/Biosphere | baf62450b084ce327c3fc2eb0aa918e32462164e | [
"MIT"
] | null | null | null | Biosphere/Include/bio/biocoenosis/flora/account/Types.hpp | PMArkive/Biosphere | baf62450b084ce327c3fc2eb0aa918e32462164e | [
"MIT"
] | null | null | null |
#pragma once
#include <bio/biocoenosis/fauna/sm.hpp>
namespace bio::account
{
typedef u128 Uid;
struct UserData
{
u32 Unknown;
u32 IconId;
u8 IconBgColorId;
u8 Unknown2[0x7];
u8 MiiData[0x10];
u8 Unknown3[0x60];
} BIO_PACKED;
struct ProfileBase
{
Uid UserId;
u64 LastEditTimeStamp;
char Nickname[0x20];
} BIO_PACKED;
class Profile : public hipc::Object
{
public:
using Object::Object;
};
class ProfileEditor : public hipc::Object
{
public:
using Object::Object;
};
} | 17.189189 | 45 | 0.553459 | [
"object"
] |
eb59538ad82d182a3f3b2505d1abaa2a63e56506 | 14,949 | cc | C++ | src/envoy/http/authn/authenticator_base_test.cc | knrc/proxy | 102e286f1ff6a95195f2bb45a0cda78911884f0b | [
"Apache-2.0"
] | null | null | null | src/envoy/http/authn/authenticator_base_test.cc | knrc/proxy | 102e286f1ff6a95195f2bb45a0cda78911884f0b | [
"Apache-2.0"
] | null | null | null | src/envoy/http/authn/authenticator_base_test.cc | knrc/proxy | 102e286f1ff6a95195f2bb45a0cda78911884f0b | [
"Apache-2.0"
] | 1 | 2022-03-08T09:23:19.000Z | 2022-03-08T09:23:19.000Z | /* Copyright 2018 Istio Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/envoy/http/authn/authenticator_base.h"
#include "common/common/base64.h"
#include "common/protobuf/protobuf.h"
#include "envoy/api/v2/core/base.pb.h"
#include "envoy/config/filter/http/authn/v2alpha1/config.pb.h"
#include "gmock/gmock.h"
#include "src/envoy/http/authn/test_utils.h"
#include "src/envoy/utils/filter_names.h"
#include "test/mocks/network/mocks.h"
#include "test/mocks/ssl/mocks.h"
using google::protobuf::util::MessageDifferencer;
using istio::authn::Payload;
using istio::envoy::config::filter::http::authn::v2alpha1::FilterConfig;
using testing::NiceMock;
using testing::Return;
using testing::StrictMock;
namespace iaapi = istio::authentication::v1alpha1;
namespace Envoy {
namespace Http {
namespace Istio {
namespace AuthN {
namespace {
const std::string kSecIstioAuthUserinfoHeaderValue =
R"(
{
"iss": "issuer@foo.com",
"sub": "sub@foo.com",
"aud": ["aud1", "aud2"],
"non-string-will-be-ignored": 1512754205,
"some-other-string-claims": "some-claims-kept"
}
)";
const std::string kExchangedTokenHeaderName = "ingress-authorization";
const std::string kExchangedTokenPayload =
R"(
{
"iss": "token-service",
"sub": "subject",
"aud": ["aud1", "aud2"],
"original_claims": {
"iss": "https://accounts.example.com",
"sub": "example-subject",
"email": "user@example.com"
}
}
)";
const std::string kExchangedTokenPayloadNoOriginalClaims =
R"(
{
"iss": "token-service",
"sub": "subject",
"aud": ["aud1", "aud2"]
}
)";
class MockAuthenticatorBase : public AuthenticatorBase {
public:
MockAuthenticatorBase(FilterContext* filter_context)
: AuthenticatorBase(filter_context) {}
MOCK_METHOD1(run, bool(Payload*));
};
class ValidateX509Test : public testing::TestWithParam<iaapi::MutualTls::Mode>,
public Logger::Loggable<Logger::Id::filter> {
public:
virtual ~ValidateX509Test() {}
NiceMock<Envoy::Network::MockConnection> connection_{};
NiceMock<Envoy::Ssl::MockConnectionInfo> ssl_{};
Envoy::Http::HeaderMapImpl header_{};
FilterConfig filter_config_{};
FilterContext filter_context_{
envoy::api::v2::core::Metadata::default_instance(), header_, &connection_,
istio::envoy::config::filter::http::authn::v2alpha1::FilterConfig::
default_instance()};
MockAuthenticatorBase authenticator_{&filter_context_};
void SetUp() override {
mtls_params_.set_mode(GetParam());
payload_ = new Payload();
}
void TearDown() override { delete (payload_); }
protected:
iaapi::MutualTls mtls_params_;
iaapi::Jwt jwt_;
Payload* payload_;
Payload default_payload_;
};
TEST_P(ValidateX509Test, PlaintextConnection) {
// Should return false except mode is PERMISSIVE (accept plaintext)
if (GetParam() == iaapi::MutualTls::PERMISSIVE) {
EXPECT_TRUE(authenticator_.validateX509(mtls_params_, payload_));
} else {
EXPECT_FALSE(authenticator_.validateX509(mtls_params_, payload_));
}
EXPECT_TRUE(MessageDifferencer::Equals(*payload_, default_payload_));
}
TEST_P(ValidateX509Test, SslConnectionWithNoPeerCert) {
EXPECT_CALL(Const(connection_), ssl()).WillRepeatedly(Return(&ssl_));
EXPECT_CALL(Const(ssl_), peerCertificatePresented())
.Times(1)
.WillOnce(Return(false));
// Should return false except mode is PERMISSIVE (accept plaintext).
if (GetParam() == iaapi::MutualTls::PERMISSIVE) {
EXPECT_TRUE(authenticator_.validateX509(mtls_params_, payload_));
} else {
EXPECT_FALSE(authenticator_.validateX509(mtls_params_, payload_));
}
EXPECT_TRUE(MessageDifferencer::Equals(*payload_, default_payload_));
}
TEST_P(ValidateX509Test, SslConnectionWithPeerCert) {
EXPECT_CALL(Const(connection_), ssl()).WillRepeatedly(Return(&ssl_));
EXPECT_CALL(Const(ssl_), peerCertificatePresented())
.Times(1)
.WillOnce(Return(true));
EXPECT_CALL(ssl_, uriSanPeerCertificate())
.Times(1)
.WillOnce(Return(std::vector<std::string>{"foo"}));
EXPECT_TRUE(authenticator_.validateX509(mtls_params_, payload_));
// When client certificate is present on mTLS, authenticated attribute should
// be extracted.
EXPECT_EQ(payload_->x509().user(), "foo");
}
TEST_P(ValidateX509Test, SslConnectionWithPeerSpiffeCert) {
EXPECT_CALL(Const(connection_), ssl()).WillRepeatedly(Return(&ssl_));
EXPECT_CALL(Const(ssl_), peerCertificatePresented())
.Times(1)
.WillOnce(Return(true));
EXPECT_CALL(ssl_, uriSanPeerCertificate())
.Times(1)
.WillOnce(Return(std::vector<std::string>{"spiffe://foo"}));
EXPECT_TRUE(authenticator_.validateX509(mtls_params_, payload_));
// When client certificate is present on mTLS, authenticated attribute should
// be extracted.
EXPECT_EQ(payload_->x509().user(), "foo");
}
TEST_P(ValidateX509Test, SslConnectionWithPeerMalformedSpiffeCert) {
EXPECT_CALL(Const(connection_), ssl()).WillRepeatedly(Return(&ssl_));
EXPECT_CALL(Const(ssl_), peerCertificatePresented())
.Times(1)
.WillOnce(Return(true));
EXPECT_CALL(ssl_, uriSanPeerCertificate())
.Times(1)
.WillOnce(Return(std::vector<std::string>{"spiffe:foo"}));
EXPECT_TRUE(authenticator_.validateX509(mtls_params_, payload_));
// When client certificate is present on mTLS and the spiffe subject format is
// wrong
// ("spiffe:foo" instead of "spiffe://foo"), the user attribute should be
// extracted.
EXPECT_EQ(payload_->x509().user(), "spiffe:foo");
}
INSTANTIATE_TEST_CASE_P(ValidateX509Tests, ValidateX509Test,
testing::Values(iaapi::MutualTls::STRICT,
iaapi::MutualTls::PERMISSIVE));
class ValidateJwtTest : public testing::Test,
public Logger::Loggable<Logger::Id::filter> {
public:
virtual ~ValidateJwtTest() {}
// StrictMock<Envoy::RequestInfo::MockRequestInfo> request_info_{};
envoy::api::v2::core::Metadata dynamic_metadata_;
NiceMock<Envoy::Network::MockConnection> connection_{};
// NiceMock<Envoy::Ssl::MockConnectionInfo> ssl_{};
Envoy::Http::HeaderMapImpl header_{};
FilterConfig filter_config_{};
FilterContext filter_context_{dynamic_metadata_, header_, &connection_,
filter_config_};
MockAuthenticatorBase authenticator_{&filter_context_};
void SetUp() override { payload_ = new Payload(); }
void TearDown() override { delete (payload_); }
protected:
iaapi::MutualTls mtls_params_;
iaapi::Jwt jwt_;
Payload* payload_;
Payload default_payload_;
};
TEST_F(ValidateJwtTest, NoIstioAuthnConfig) {
jwt_.set_issuer("issuer@foo.com");
// authenticator_ has empty Istio authn config
// When there is empty Istio authn config, validateJwt() should return
// nullptr and failure.
EXPECT_FALSE(authenticator_.validateJwt(jwt_, payload_));
EXPECT_TRUE(MessageDifferencer::Equals(*payload_, default_payload_));
}
TEST_F(ValidateJwtTest, NoIssuer) {
// no issuer in jwt
google::protobuf::util::JsonParseOptions options;
JsonStringToMessage(
R"({
"jwt_output_payload_locations":
{
"issuer@foo.com": "sec-istio-auth-userinfo"
}
}
)",
&filter_config_, options);
// When there is no issuer in the JWT config, validateJwt() should return
// nullptr and failure.
EXPECT_FALSE(authenticator_.validateJwt(jwt_, payload_));
EXPECT_TRUE(MessageDifferencer::Equals(*payload_, default_payload_));
}
TEST_F(ValidateJwtTest, OutputPayloadLocationNotDefine) {
jwt_.set_issuer("issuer@foo.com");
google::protobuf::util::JsonParseOptions options;
JsonStringToMessage(
R"({
"jwt_output_payload_locations":
{
}
}
)",
&filter_config_, options);
// authenticator has empty jwt_output_payload_locations in Istio authn config
// When there is no matching jwt_output_payload_locations for the issuer in
// the Istio authn config, validateJwt() should return nullptr and failure.
EXPECT_FALSE(authenticator_.validateJwt(jwt_, payload_));
EXPECT_TRUE(MessageDifferencer::Equals(*payload_, default_payload_));
}
TEST_F(ValidateJwtTest, NoJwtPayloadOutput) {
jwt_.set_issuer("issuer@foo.com");
// When there is no JWT in request info dynamic metadata, validateJwt() should
// return nullptr and failure.
EXPECT_FALSE(authenticator_.validateJwt(jwt_, payload_));
EXPECT_TRUE(MessageDifferencer::Equals(*payload_, default_payload_));
}
TEST_F(ValidateJwtTest, HasJwtPayloadOutputButNoDataForKey) {
jwt_.set_issuer("issuer@foo.com");
(*dynamic_metadata_.mutable_filter_metadata())[Utils::IstioFilterName::kJwt]
.MergeFrom(MessageUtil::keyValueStruct("foo", "bar"));
// When there is no JWT payload for given issuer in request info dynamic
// metadata, validateJwt() should return nullptr and failure.
EXPECT_FALSE(authenticator_.validateJwt(jwt_, payload_));
EXPECT_TRUE(MessageDifferencer::Equals(*payload_, default_payload_));
}
TEST_F(ValidateJwtTest, JwtPayloadAvailableWithBadData) {
jwt_.set_issuer("issuer@foo.com");
(*dynamic_metadata_.mutable_filter_metadata())[Utils::IstioFilterName::kJwt]
.MergeFrom(MessageUtil::keyValueStruct("issuer@foo.com", "bad-data"));
// EXPECT_CALL(request_info_, dynamicMetadata());
EXPECT_FALSE(authenticator_.validateJwt(jwt_, payload_));
EXPECT_TRUE(MessageDifferencer::Equivalent(*payload_, default_payload_));
}
TEST_F(ValidateJwtTest, JwtPayloadAvailable) {
jwt_.set_issuer("issuer@foo.com");
(*dynamic_metadata_.mutable_filter_metadata())[Utils::IstioFilterName::kJwt]
.MergeFrom(MessageUtil::keyValueStruct("issuer@foo.com",
kSecIstioAuthUserinfoHeaderValue));
Payload expected_payload;
JsonStringToMessage(
R"({
"jwt": {
"user": "issuer@foo.com/sub@foo.com",
"audiences": ["aud1", "aud2"],
"presenter": "",
"claims": {
"aud": ["aud1", "aud2"],
"iss": ["issuer@foo.com"],
"some-other-string-claims": ["some-claims-kept"],
"sub": ["sub@foo.com"],
},
"raw_claims": "\n {\n \"iss\": \"issuer@foo.com\",\n \"sub\": \"sub@foo.com\",\n \"aud\": [\"aud1\", \"aud2\"],\n \"non-string-will-be-ignored\": 1512754205,\n \"some-other-string-claims\": \"some-claims-kept\"\n }\n ",
}
}
)",
&expected_payload, google::protobuf::util::JsonParseOptions{});
EXPECT_TRUE(authenticator_.validateJwt(jwt_, payload_));
EXPECT_TRUE(MessageDifferencer::Equals(expected_payload, *payload_));
}
TEST_F(ValidateJwtTest, OriginalPayloadOfExchangedToken) {
jwt_.set_issuer("token-service");
jwt_.add_jwt_headers(kExchangedTokenHeaderName);
(*dynamic_metadata_.mutable_filter_metadata())[Utils::IstioFilterName::kJwt]
.MergeFrom(
MessageUtil::keyValueStruct("token-service", kExchangedTokenPayload));
Payload expected_payload;
JsonStringToMessage(
R"({
"jwt": {
"user": "https://accounts.example.com/example-subject",
"claims": {
"iss": ["https://accounts.example.com"],
"sub": ["example-subject"],
"email": ["user@example.com"]
},
"raw_claims": "{\"email\":\"user@example.com\",\"iss\":\"https://accounts.example.com\",\"sub\":\"example-subject\"}"
}
}
)",
&expected_payload, google::protobuf::util::JsonParseOptions{});
EXPECT_TRUE(authenticator_.validateJwt(jwt_, payload_));
// On different platforms, the order of fields in raw_claims may be
// different. E.g., on MacOs, the raw_claims in the payload_ can be:
// raw_claims:
// "{\"email\":\"user@example.com\",\"sub\":\"example-subject\",\"iss\":\"https://accounts.example.com\"}"
// Therefore, raw_claims is skipped to avoid a flaky test.
MessageDifferencer diff;
const google::protobuf::FieldDescriptor* field =
expected_payload.jwt().GetDescriptor()->FindFieldByName("raw_claims");
diff.IgnoreField(field);
EXPECT_TRUE(diff.Compare(expected_payload, *payload_));
}
TEST_F(ValidateJwtTest, OriginalPayloadOfExchangedTokenMissing) {
jwt_.set_issuer("token-service");
jwt_.add_jwt_headers(kExchangedTokenHeaderName);
(*dynamic_metadata_.mutable_filter_metadata())[Utils::IstioFilterName::kJwt]
.MergeFrom(MessageUtil::keyValueStruct(
"token-service", kExchangedTokenPayloadNoOriginalClaims));
// When no original_claims in an exchanged token, the token
// is treated as invalid.
EXPECT_FALSE(authenticator_.validateJwt(jwt_, payload_));
}
TEST_F(ValidateJwtTest, OriginalPayloadOfExchangedTokenNotInIntendedHeader) {
jwt_.set_issuer("token-service");
(*dynamic_metadata_.mutable_filter_metadata())[Utils::IstioFilterName::kJwt]
.MergeFrom(
MessageUtil::keyValueStruct("token-service", kExchangedTokenPayload));
Payload expected_payload;
JsonStringToMessage(
R"({
"jwt": {
"user": "token-service/subject",
"audiences": ["aud1", "aud2"],
"claims": {
"iss": ["token-service"],
"sub": ["subject"],
"aud": ["aud1", "aud2"]
},
"raw_claims":"\n {\n \"iss\": \"token-service\",\n \"sub\": \"subject\",\n \"aud\": [\"aud1\", \"aud2\"],\n \"original_claims\": {\n \"iss\": \"https://accounts.example.com\",\n \"sub\": \"example-subject\",\n \"email\": \"user@example.com\"\n }\n }\n "
}
}
)",
&expected_payload, google::protobuf::util::JsonParseOptions{});
// When an exchanged token is not in the intended header, the token
// is treated as a normal token with its claims extracted.
EXPECT_TRUE(authenticator_.validateJwt(jwt_, payload_));
EXPECT_TRUE(MessageDifferencer::Equals(expected_payload, *payload_));
}
} // namespace
} // namespace AuthN
} // namespace Istio
} // namespace Http
} // namespace Envoy
| 36.639706 | 332 | 0.673958 | [
"vector"
] |
eb5a03b1b850b8e35af94b7a78c619c81514766d | 5,378 | hpp | C++ | if_data_utils/include/if_data_utils/IFDataFileWriter.hpp | mfkiwl/PNT-Integrity | 3d79cf4eb6b78a7234bbdcef0577ea847f141039 | [
"Unlicense"
] | 37 | 2021-02-23T14:46:32.000Z | 2022-03-01T08:41:45.000Z | if_data_utils/include/if_data_utils/IFDataFileWriter.hpp | yxw027/PNT-Integrity | 3549855a8ab4c5937d109b60ee70a6a5a9ca2d6a | [
"Unlicense"
] | 2 | 2022-03-23T23:13:15.000Z | 2022-03-24T09:42:01.000Z | if_data_utils/include/if_data_utils/IFDataFileWriter.hpp | yxw027/PNT-Integrity | 3549855a8ab4c5937d109b60ee70a6a5a9ca2d6a | [
"Unlicense"
] | 15 | 2021-02-18T08:15:39.000Z | 2022-03-01T08:41:50.000Z | //============================================================================//
//------------------- if_data_utils/IFDataFileWriter.hpp -------*- C++ -*-----//
//============================================================================//
// BSD 3-Clause License
//
// Copyright (C) 2019 Integrated Solutions for Systems, Inc
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file contains the declaration of the IFDataFileWriter class.
/// \details
/// \author Josh Clanton <josh.clanton@is4s.com>
/// \date August 29, 2019
///
//===----------------------------------------------------------------------===//
#ifndef IF_DATA_UTILS__IF_DATA_FILE_WRITER_HPP
#define IF_DATA_UTILS__IF_DATA_FILE_WRITER_HPP
// only define the file functions on unix platforms
// this effectively renders the class useless on a win platform
#ifndef _WIN32
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
#include <memory>
#include <sstream>
#include <vector>
#include "logutils/logutils.hpp"
namespace if_data_utils
{
using write_element = std::vector<char>;
/// \brief A class object for writing IF data to files
template <typename samp_type>
class IFDataFileWriter
{
public:
/// \brief Constructor for the file writer class
///
/// \param writeBufferSize The size of each buffer element in bytes
IFDataFileWriter(
const ssize_t& writeBufferSize = 4096,
const logutils::LogCallback& log = logutils::printLogToStdOut);
bool createFile(const std::string& filename);
size_t getWriteBufferSize() { return writeBufferSize_; };
bool writeSamplesToFile(const write_element& writeBuffer);
size_t getTotalBytesWritten() { return totalBytesWritten_; };
private:
ssize_t writeBufferSize_;
int fileDescriptor_;
// local storage of the log callback
logutils::LogCallback log_;
size_t totalBytesWritten_;
};
template <typename samp_type>
IFDataFileWriter<samp_type>::IFDataFileWriter(const ssize_t& writeBufferSize,
const logutils::LogCallback& log)
: writeBufferSize_(writeBufferSize), log_(log), totalBytesWritten_(0)
{
const size_t samps_per_element = writeBufferSize / sizeof(samp_type);
if (writeBufferSize % sizeof(samp_type) != 0)
{
std::stringstream errStr;
errStr << "Element size " << writeBufferSize
<< " not an integer # of samples";
log_(errStr.str(), logutils::LogLevel::Error);
}
std::stringstream sizeMsg;
sizeMsg << "Elements are " << writeBufferSize << " bytes, "
<< samps_per_element << " samples/element";
log_(sizeMsg.str(), logutils::LogLevel::Info);
}
template <class samp_type>
bool IFDataFileWriter<samp_type>::createFile(const std::string& filename)
{
if ((fileDescriptor_ = open(filename.c_str(),
O_WRONLY | O_CREAT | O_TRUNC | O_NONBLOCK,
S_IRWXU | S_IRWXG | S_IRWXO)) < 0)
{
std::stringstream errStr;
errStr << "File open failed: " << filename.c_str();
log_(errStr.str(), logutils::LogLevel::Error);
std::cerr << std::endl;
return false;
}
return true;
}
template <class samp_type>
bool IFDataFileWriter<samp_type>::writeSamplesToFile(
const write_element& writeBuffer)
{
auto bytes_written =
write(fileDescriptor_, (void*)(&writeBuffer), writeBufferSize_);
totalBytesWritten_ += bytes_written;
if (bytes_written != writeBufferSize_)
{
std::stringstream errStr;
if (bytes_written < 0)
{
errStr << "Problem writing: " << strerror(errno);
}
else
{
errStr << "Wrote " << bytes_written << "/" << (int)writeBufferSize_
<< " bytes";
}
log_(errStr.str(), logutils::LogLevel::Error);
return false;
}
return true;
}
} // end namespace if_data_utils
#endif
#endif | 34.037975 | 80 | 0.662328 | [
"object",
"vector"
] |
eb5e1a1d2d30efa9504314b496a1f34f51d70e16 | 8,222 | cc | C++ | src/matchers/annotation_matcher.cc | blockspacer/flexlib | 92c957d4cf8f172769c204962733dafbdfc71bd9 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-03-25T16:32:53.000Z | 2021-03-25T16:32:53.000Z | src/matchers/annotation_matcher.cc | blockspacer/flexlib | 92c957d4cf8f172769c204962733dafbdfc71bd9 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/matchers/annotation_matcher.cc | blockspacer/flexlib | 92c957d4cf8f172769c204962733dafbdfc71bd9 | [
"Apache-2.0",
"MIT"
] | 1 | 2020-05-19T01:00:50.000Z | 2020-05-19T01:00:50.000Z | #include "flexlib/matchers/annotation_matcher.hpp" // IWYU pragma: associated
#include "flexlib/clangUtils.hpp"
#if __has_include(<filesystem>)
#include <filesystem>
#else
#include <experimental/filesystem>
#endif // __has_include
#include <clang/Rewrite/Core/Rewriter.h>
#include <clang/ASTMatchers/ASTMatchers.h>
#include <clang/AST/ASTContext.h>
#include <clang/ASTMatchers/ASTMatchFinder.h>
#include <clang/ASTMatchers/ASTMatchersMacros.h>
#include <clang/AST/Type.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Sema/Sema.h>
#include <clang/Basic/FileManager.h>
#include <clang/Basic/LangOptions.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Sema/Sema.h>
#include <clang/Lex/Lexer.h>
#include <clang/Frontend/FrontendAction.h>
#include <clang/Frontend/ASTConsumers.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Tooling/Tooling.h>
#include <clang/Rewrite/Core/Rewriter.h>
#include <clang/Driver/Options.h>
#include <clang/AST/AST.h>
#include <clang/AST/ASTContext.h>
#include <clang/AST/ASTConsumer.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Frontend/ASTConsumers.h>
#include <clang/Frontend/FrontendActions.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Tooling/Tooling.h>
#include <clang/Rewrite/Core/Rewriter.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Sema/Sema.h>
#include <clang/Lex/Lexer.h>
#include <clang/Frontend/FrontendAction.h>
#include <clang/Frontend/ASTConsumers.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Tooling/Tooling.h>
#include <clang/Rewrite/Core/Rewriter.h>
#include <clang/Driver/Options.h>
#include <clang/AST/AST.h>
#include <clang/AST/ASTContext.h>
#include <clang/AST/ASTConsumer.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/Frontend/ASTConsumers.h>
#include <clang/Frontend/FrontendActions.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Tooling/Tooling.h>
#include <clang/Rewrite/Core/Rewriter.h>
#include <clang/Basic/DiagnosticOptions.h>
#include <clang/Frontend/TextDiagnosticPrinter.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Basic/TargetOptions.h>
#include <clang/Basic/TargetInfo.h>
#include <clang/Basic/FileManager.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Lex/Preprocessor.h>
#include <clang/Lex/Lexer.h>
#include <clang/Basic/Diagnostic.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/AST/ASTConsumer.h>
#include <clang/Parse/ParseAST.h>
#include <clang/Rewrite/Frontend/Rewriters.h>
#include <clang/Rewrite/Core/Rewriter.h>
#include <llvm/Support/Host.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/ADT/IntrusiveRefCntPtr.h>
#include <llvm/ADT/StringRef.h>
#include <llvm/Support/FileSystem.h>
#include <base/logging.h>
#include <base/check.h>
#if __has_include(<filesystem>)
namespace fs = std::filesystem;
#else
namespace fs = std::experimental::filesystem;
#endif // __has_include
namespace clang_utils {
AnnotationMatchOptions::AnnotationMatchOptions(
std::string annotateName
, AnnotationMatchCallback&& annotationMatchCallback
, EndSourceFileActionCallback&& endSourceFileAction)
: annotateName(annotateName)
, annotationMatchCallback(std::move(annotationMatchCallback))
, endSourceFileAction(std::move(endSourceFileAction))
{}
AnnotateMatchCallback::AnnotateMatchCallback(
clang::Rewriter &rewriter
, scoped_refptr<AnnotationMatchOptions> annotateOptions)
: rewriter_(rewriter)
, annotateOptions_(annotateOptions)
{
DETACH_FROM_SEQUENCE(sequence_checker_);
}
void AnnotateMatchCallback::run(
const MatchResult& matchResult)
{
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(annotateOptions_);
DVLOG(9)
<< "AnnotateMatchCallback::run...";
const clang::Decl* nodeDecl
= matchResult.Nodes.getNodeAs<clang::Decl>(
annotateOptions_->annotateName);
if (!nodeDecl || nodeDecl->isInvalidDecl()) {
DVLOG(10)
<< "skipped nodeDecl for "
<< annotateOptions_->annotateName;
return;
}
// When there is a #include <vector> in the source file,
// our find-decl will print out all the declarations
// in that included file, because these included files are parsed
// and consumed as a whole with our source file.
// To fix this, we need to check if the declarations
// are defined in our source file
{
clang::SourceManager& SM = rewriter_.getSourceMgr();
const clang::FileID& mainFileID = SM.getMainFileID();
const auto& FileID = SM.getFileID(nodeDecl->getLocation());
if (FileID != mainFileID) {
DVLOG(10)
<< "decl in included file: "
<< nodeDecl->getLocation().printToString(SM).substr(0, 1000)
<< " for annotation name: "
<< annotateOptions_->annotateName;
}
}
clang::AnnotateAttr* annotateAttr
= nodeDecl->getAttr<clang::AnnotateAttr>();
if (!annotateAttr) {
DVLOG(10)
<< "skipped getAttr for "
<< annotateOptions_->annotateName;
return;
}
DVLOG(9)
<< "found annotation: "
<< annotateAttr->getAnnotation().str();
annotateOptions_->annotationMatchCallback.Run(
annotateAttr, matchResult, rewriter_, nodeDecl);
}
AnnotateConsumer::AnnotateConsumer(
clang::Rewriter& rewriter
, scoped_refptr<AnnotationMatchOptions> annotateOptions)
: annotateMatchCallback_(rewriter, annotateOptions)
, annotateOptions_(annotateOptions)
{
DETACH_FROM_SEQUENCE(sequence_checker_);
DCHECK(annotateOptions_);
using namespace clang::ast_matchers;
auto hasAnnotateMatcher
= clang::ast_matchers::hasAttr(clang::attr::Annotate);
//In Clang, there are two basic types of AST classes:
// Decl and Stmt, which have many subclasses
// that covers all the AST nodes we will meet in a source file.
auto finderMatcher
= clang::ast_matchers::decl(hasAnnotateMatcher)
.bind(annotateOptions->annotateName);
matchFinder.addMatcher(finderMatcher, &annotateMatchCallback_);
}
void AnnotateConsumer::HandleTranslationUnit(
clang::ASTContext &Context)
{
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DVLOG(9)
<< "Started AST matcher...";
matchFinder.matchAST(Context);
}
AnnotationMatchAction::AnnotationMatchAction(
scoped_refptr<AnnotationMatchOptions> annotateOptions)
: annotateOptions_(annotateOptions)
{
DETACH_FROM_SEQUENCE(sequence_checker_);
DCHECK(annotateOptions_);
}
AnnotationMatchAction::ASTConsumerPointer
AnnotationMatchAction::CreateASTConsumer(
clang::CompilerInstance& compilerInstance
, llvm::StringRef filename)
{
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
ignore_result(filename);
DVLOG(9)
<< "Created AST consumer...";
rewriter_.setSourceMgr(
compilerInstance.getSourceManager()
, compilerInstance.getLangOpts());
DCHECK(annotateOptions_);
return std::make_unique<AnnotateConsumer>(
rewriter_, annotateOptions_);
}
bool AnnotationMatchAction::BeginSourceFileAction(
clang::CompilerInstance&)
{
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DVLOG(9)
<< "Processing file: " << getCurrentFile().str();
return true;
}
void AnnotationMatchAction::EndSourceFileAction()
{
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
ASTFrontendAction::EndSourceFileAction();
clang::SourceManager& SM = rewriter_.getSourceMgr();
const clang::FileID& mainFileID = SM.getMainFileID();
const clang::FileEntry* fileEntry
= SM.getFileEntryForID(mainFileID);
if(!fileEntry) {
NOTREACHED();
}
DCHECK(annotateOptions_);
annotateOptions_->endSourceFileAction.Run(
mainFileID, fileEntry, rewriter_);
}
AnnotationMatchFactory::AnnotationMatchFactory(
scoped_refptr<AnnotationMatchOptions> annotateOptions)
: FrontendActionFactory()
, annotateOptions_(annotateOptions)
{
DETACH_FROM_SEQUENCE(sequence_checker_);
DCHECK(annotateOptions_);
}
clang::FrontendAction*
AnnotationMatchFactory::create()
{
DETACH_FROM_SEQUENCE(sequence_checker_);
DCHECK(annotateOptions_);
return new AnnotationMatchAction(annotateOptions_);
}
} // namespace clang_utils
| 28.950704 | 78 | 0.761129 | [
"vector"
] |
eb60edd0f5dcf5b23d74483255064bf29b3347cf | 12,798 | cpp | C++ | matsim/bio.cpp | Tom83B/matsim | dec413a1279476c9d50a81582feee8da3e12861d | [
"MIT"
] | null | null | null | matsim/bio.cpp | Tom83B/matsim | dec413a1279476c9d50a81582feee8da3e12861d | [
"MIT"
] | null | null | null | matsim/bio.cpp | Tom83B/matsim | dec413a1279476c9d50a81582feee8da3e12861d | [
"MIT"
] | 1 | 2020-10-06T05:59:06.000Z | 2020-10-06T05:59:06.000Z | #include <iostream>
#include <cstdlib>
#include <vector>
#include <cmath>
#include <ctime>
#include "bio.h"
using namespace std;
#define PI 3.14159265358979323846 /* pi */
int poisson_rand(double rate) {
double randu = ((double) rand() / (RAND_MAX));
double cummulation = 0;
double pmf = exp(-rate);
int poisson_rand = 0;
// cout << endl << "randu: " << randu << endl;
while (randu > cummulation) {
// cout << "cummulation" << cummulation << endl;
cummulation += pmf;
poisson_rand += 1;
pmf *= rate / poisson_rand;
}
// cout << "finished with " << cummulation << endl;
return poisson_rand - 1;
}
double normal_rand() {
double randu1 = ((double) rand() / (RAND_MAX));
double randu2 = ((double) rand() / (RAND_MAX));
// cout << randu1 << endl << randu2 << endl << log(randu1) << endl;
// cout << cos(2 * PI * randu2) << endl;
// cout << -2 * log(randu1) * cos(2 * PI * randu2) << endl << endl;
return sqrt(-2 * log(randu1)) * cos(2 * PI * randu2);
}
void Conductance::update(double dt) { }
void Conductance::set_rate(double rate) { }
double Conductance::get_g() {return 0;}
void Conductance::set_g(double g) { }
double Conductance::get_reversal() {return 0;}
void Conductance::activate() { }
ConstantConductance::ConstantConductance() {}
double ConstantConductance::get_g() {return this->g;}
void ConstantConductance::set_g(double g) {this->g = g;}
double ConstantConductance::get_reversal() {return this->reversal;}
ConstantConductance::ConstantConductance(double g, double reversal) {
this->g = g;
this->reversal = reversal;
}
void ConstantConductance::update(double dt) { }
ExponentialConductance::ExponentialConductance() {}
double ExponentialConductance::get_g() {return this->g;}
void ExponentialConductance::set_g(double g) {this->g = g;}
double ExponentialConductance::get_reversal() {return this->reversal;}
ExponentialConductance::ExponentialConductance(double g_peak, double reversal, double decay) {
this->g_peak = g_peak;
this->reversal = reversal;
this->decay = decay;
this->g = 0;
}
void ExponentialConductance::update(double dt) {
g *= exp(-dt / decay);
}
void ExponentialConductance::activate() {
g += g_peak;
}
ShotNoiseConductance::ShotNoiseConductance() {}
double ShotNoiseConductance::get_g() {return this->g;}
void ShotNoiseConductance::set_g(double g) {this->g = g;}
double ShotNoiseConductance::get_reversal() {return this->reversal;}
void ShotNoiseConductance::activate() { }
ShotNoiseConductance::ShotNoiseConductance(double rate, double g_peak, double reversal, double decay) {
srand(std::time(nullptr));
this->rate = rate;
this->g_peak = g_peak;
this->reversal = reversal;
this->decay = decay;
this->g = 0;
}
void ShotNoiseConductance::update(double dt) {
int n_spikes = poisson_rand(rate * dt);
g *= exp(-dt / decay);
g += n_spikes * g_peak * decay * (1 - exp(-dt / decay)) / dt;
}
void ShotNoiseConductance::set_rate(double rate) {
this->rate = rate;
}
OUConductance::OUConductance() {}
double OUConductance::get_g() {return this->g;}
void OUConductance::set_g(double g) {this->g = g;}
double OUConductance::get_reversal() {return this->reversal;}
void OUConductance::activate() { }
OUConductance::OUConductance(double rate, double g_peak, double reversal, double decay) {
srand(std::time(nullptr));
this->rate = rate;
this->g_peak = g_peak;
this->reversal = reversal;
this->decay = decay;
this->set_rate(rate);
this->g = this->mean;
// cout << normal_rand() << endl;
// cout << g << endl;
}
double OUConductance::get_A(double dt) {
double A = sqrt(D * decay / 2 * (1 - exp(-2 * dt / decay)));
return A;
}
void OUConductance::update(double dt) {
double A = this->get_A(dt);
// cout << g << " " << mean << endl;
g = mean + (g - mean) * exp(-dt / decay) + A * normal_rand();
}
void OUConductance::set_rate(double rate) {
// cout << "funguju?";
this->mean = decay * g_peak * rate;
this->sigma = sqrt(decay * rate / 2) * g_peak;
this->D = 2 * (sigma * sigma) / decay;
}
MATThresholds::MATThresholds(double alpha1, double alpha2, double tau1, double tau2,\
double omega, double refractory_period, bool resetting = false) {
this->alpha1 = alpha1;
this->alpha2 = alpha2;
this->tau1 = tau1;
this->tau2 = tau2;
this->omega = omega;
this->refractory_period = refractory_period;
this->resetting = resetting;
t1 = 0;
t2 = 0;
threshold = t1 + t2 + omega;
past_spike_time = refractory_period;
}
void MATThresholds::fire(double time) {
if (past_spike_time >= refractory_period) {
t1 += alpha1;
t2 += alpha2;
spike_times.push_back(time);
past_spike_time = 0;
}
}
void MATThresholds::update(double dt) {
past_spike_time += dt;
t1 *= exp(-dt / tau1);
t2 *= exp(-dt / tau2);
threshold = t1 + t2 + omega;
}
vector<double> MATThresholds::get_spike_times() {
return spike_times;
}
void MATThresholds::reset_spike_times() {
vector<double> spike_times;
this->spike_times = spike_times;
}
Neuron::Neuron() {}
Neuron::Neuron(double resting_potential, double membrane_resistance, double membrane_capacitance, vector<MATThresholds*> mats,
double reset_potential) {
this->resting_potential = resting_potential;
this->membrane_resistance = membrane_resistance;
this->membrane_capacitance = membrane_capacitance;
this->mats = mats;
this->reset_potential = reset_potential;
voltage = resting_potential;
time_constant = membrane_capacitance * membrane_resistance;
time = 0;
}
void Neuron::append_conductance(Conductance* conductance) {
conductances.push_back(conductance);
}
void Neuron::integrate_voltage(double dt) {
double tot_conductance = 1. / membrane_resistance;
double tot_gr = resting_potential / membrane_resistance;
double tot_current = 0;
double factor, v_bar, tau;
double rev;
for (auto c : conductances) {
rev = c->get_reversal();
if (rev > 999) {
tot_gr += c->get_g();
}
else {
tot_conductance += c->get_g();
tot_gr += c->get_g() * rev;
}
}
v_bar = tot_gr / tot_conductance;
// cout<<v_bar<<endl;
// tau = time_constant / (1 + membrane_resistance * tot_conductance);
tau = membrane_capacitance / tot_conductance;
voltage = v_bar + (voltage - v_bar) * exp(-dt / tau);
}
void Neuron::timestep(double dt) {
time += dt;
for (auto c : conductances) {
c->update(dt);
}
this->integrate_voltage(dt);
for (auto mat : mats) {
mat->update(dt);
if (mat->threshold <= voltage) {
mat->fire(time);
if (mat->resetting == true) {
this->voltage = this->reset_potential;
}
for (auto c : conductances) {
c->activate();
}
}
}
}
MCNeuron::MCNeuron() {}
MCNeuron::MCNeuron(double resting_potential, double membrane_resistance, double membrane_capacitance, vector<MATThresholds*> mats,
double reset_potential, double coupling_conductance) {
this->resting_potential = resting_potential;
this->membrane_resistance = membrane_resistance;
this->membrane_capacitance = membrane_capacitance;
this->mats = mats;
this->reset_potential = reset_potential;
this->leaky_conductance = 1 / membrane_resistance;
this->coupling_conductance = coupling_conductance;
voltageSoma = resting_potential;
voltageDendrite = resting_potential;
time_constant = membrane_capacitance * membrane_resistance;
time = 0;
}
void MCNeuron::append_conductance(Conductance* conductance, int compartment) {
if (compartment == 0) {
conductances_soma.push_back(conductance);
}
else {
conductances_dendrite.push_back(conductance);
}
}
void MCNeuron::integrate_voltage(double dt) {
double tot_conductance_soma = 0;
double tot_gr_soma = 0;
double tot_conductance_dendrite = 0;
double tot_gr_dendrite = 0;
double factor, v_barS, v_barD, tauS, tauD;
for (auto c : conductances_soma) {
tot_conductance_soma += c->get_g();
tot_gr_soma += c->get_g() * c->get_reversal();
}
v_barS = (leaky_conductance*resting_potential + coupling_conductance*voltageDendrite + tot_gr_soma) / (leaky_conductance + coupling_conductance + tot_conductance_soma);
tauS = membrane_capacitance / (leaky_conductance + coupling_conductance + tot_conductance_soma);
for (auto c : conductances_dendrite) {
tot_conductance_dendrite += c->get_g();
tot_gr_dendrite += c->get_g() * c->get_reversal();
}
v_barD = (leaky_conductance * resting_potential + coupling_conductance * voltageSoma + tot_gr_dendrite) / (leaky_conductance + coupling_conductance + tot_conductance_dendrite);
tauD = membrane_capacitance / (leaky_conductance + coupling_conductance + tot_conductance_dendrite);
voltageSoma = v_barS + (voltageSoma - v_barS) * exp(-dt / tauS);
voltageDendrite = v_barD + (voltageDendrite - v_barD) * exp(-dt / tauD);
}
void MCNeuron::timestep(double dt) {
time += dt;
for (auto c : conductances_soma) {
c->update(dt);
}
for (auto c : conductances_dendrite) {
c->update(dt);
}
this->integrate_voltage(dt);
for (auto mat : mats) {
mat->update(dt);
if (mat->threshold <= voltageSoma) {
mat->fire(time);
if (mat->resetting == true) {
this->voltageSoma = this->reset_potential;
}
for (auto c : conductances_soma) {
c->activate();
}
for (auto c : conductances_dendrite) {
c->activate();
}
}
}
}
HHNeuron::HHNeuron() {}
HHNeuron::HHNeuron(double adaptation, double VS, double Ah,
double m = 0, double h = 0, double n = 0, double p = 0, double V = 200) {
double A = 1e-4;
this->g_l = 0.045 * 1000 * A;
this->E_l = -80;
this->c_m = 1 * A * 1000.;
this->E_na = 50;
this->g_na = 50 * 1000. * A;
this->E_k = -90;
this->g_k = 5 * 1000 * A;
this->g_m = adaptation * 1000 * A;
this->VS = VS;
this->Ah = Ah;
if (V > 100) {
this->V = E_l;
}
else {
this->V = V;
}
this->time = 0;
this->m = m;
this->h = h;
this->n = n;
this->p = p;
this->i_na = 0;
this->i_k = 0;
this->i_l = 0;
this->i_m = 0;
}
void HHNeuron::append_conductance(Conductance* conductance) {
conductances.push_back(conductance);
}
void HHNeuron::integrate_voltage(double dt) {
double i_syn = 0;
double am, ah, an, ap, bm, bh, bn, bp;
double tot_conductance = 0;
double E0, g_na_t, g_k_t, tau;
double dVdt;
double VT = -58;
am = -0.32 * (V - VT - 13) / (exp(-(V - VT - 13) / 4) - 1);
bm = 0.28 * (V - VT - 40) / (exp((V - VT - 40) / 5) - 1);
ah = this->Ah * exp(-(V - VT - this->VS - 17) / 18);
bh = 4 / (1 + exp(-(V - VT - this->VS - 40) / 5));
an = -0.032 * (V - VT - 15) / (exp(-(V - VT - 15) / 5) - 1);
bn = 0.5 * exp(-(V - VT - 10) / 40);
ap = 0.0001 * (V + 30) / (1 - exp(-(V + 30) / 9));
bp = -0.0001 * (V + 30) / (1 - exp((V + 30) / 9));
// am = (0.182 * (V + 35)) / (1 - exp(-(V + 35) / 9));
// bm = -(0.124 * (V + 35)) / (1 - exp((V + 35) / 9));
// ah = 0.25 * exp(-(V + 90.) / 12.);
// bh = 0.25 * exp((V + 62.) / 6.) / exp((V + 90.) / 12.);
// an = (0.02 * (V - 25.) / 9.) / (1 - exp(-(V - 25.) / 9.));
// bn = -0.002 * (V - 25.) / (1 - exp((V - 25.) / 9));
tot_conductance += this->g_l;
E0 += this->g_l * this->E_l;
for (auto c : conductances) {
tot_conductance += c->get_g();
E0 += c->get_g() * c->get_reversal();
i_syn += c->get_g() * (V - c->get_reversal());
}
g_na_t = g_na * m * m * m * h;
g_k_t = g_k * n * n * n * n;
tot_conductance += g_na_t + g_k_t;
E0 += g_na_t * E_na + g_k_t * E_k;
E0 = E0 / tot_conductance;
tau = c_m / tot_conductance;
this->i_na = g_na * m * m * m * h * (V - E_na);
this->i_k = g_k * n * n * n * n * (V - E_k);
this->i_l = g_l * (V - E_l);
this->i_m = g_m * p * (V - E_k);
dVdt = (-this->i_l - this->i_na - this->i_k - this->i_m - i_syn) / c_m;
this->V += dVdt * dt;
this->m += dt * (am * (1 - m) - bm * m);
this->h += dt * (ah * (1 - h) - bh * h);
this->n += dt * (an * (1 - n) - bn * n);
this->p += dt * (ap * (1 - p) - bp * p);
// cout << endl;
// cout << "i_na: " << i_na << endl;
// cout << "i_k: " << i_k << endl;
// cout << "i_l: " << i_l << endl;
// cout << "i_s: " << i_syn << endl;
// cout << "V: " << V << endl;
// cout << endl;
// cout << endl;
// cout << "m: " << m << endl;
// cout << "h: " << h << endl;
// cout << "n: " << n << endl;
// cout << endl;
}
void HHNeuron::timestep(double dt) {
time += dt;
for (auto c : conductances) {
c->update(dt);
}
this->integrate_voltage(dt);
}
// int main(int argc, char const *argv[])
// {
// srand(time(nullptr));
// HHNeuron neuron;
// ShotNoiseConductance exc (10, 0.0015, 0, 3);
// ShotNoiseConductance inh (5, 0.0015, -75, 10);
// neuron.append_conductance(&inh);
// neuron.append_conductance(&exc);
// for (int i=0; i<10000; i++) {
// neuron.timestep(0.025);
// cout << i << endl;
// // if (i % 10000 == 0) cout << i << endl;
// // cout << neuron.voltage << " " << neuron.mats[0]->threshold << endl;
// }
// // cout << mat.get_spike_times().size();
// return 0;
// }
| 26.012195 | 177 | 0.636115 | [
"vector"
] |
eb6111f7c39fd786b65df42a8d3c8dc044a1cb84 | 2,507 | cpp | C++ | src/modules/MaNGOSBot/playerbot/strategy/actions/PositionAction.cpp | MaNGOSBot/Uno | e5c95da966c367f1425d0d1d737bfdfc14362964 | [
"PostgreSQL",
"Zlib",
"OpenSSL"
] | 1 | 2018-05-06T12:13:04.000Z | 2018-05-06T12:13:04.000Z | src/modules/Bots/playerbot/strategy/actions/PositionAction.cpp | Lidocian/ZeroBots | 297072e07f85fc661e1b0e9a34c09580e3bfef14 | [
"PostgreSQL",
"Zlib",
"OpenSSL"
] | null | null | null | src/modules/Bots/playerbot/strategy/actions/PositionAction.cpp | Lidocian/ZeroBots | 297072e07f85fc661e1b0e9a34c09580e3bfef14 | [
"PostgreSQL",
"Zlib",
"OpenSSL"
] | null | null | null | #include "botpch.h"
#include "../../playerbot.h"
#include "../values/PositionValue.h"
#include "PositionAction.h"
using namespace ai;
void TellPosition(PlayerbotAI* ai, string name, ai::Position pos)
{
ostringstream out; out << "Position " << name;
if (pos.isSet())
{
float x = pos.x, y = pos.y;
Map2ZoneCoordinates(x, y, ai->GetBot()->GetZoneId());
out << " is set to " << x << "," << y;
}
else
out << " is not set";
ai->TellMaster(out);
}
bool PositionAction::Execute(Event event)
{
string param = event.getParam();
if (param.empty())
return false;
Player* master = GetMaster();
if (!master)
return false;
ai::PositionMap& posMap = context->GetValue<ai::PositionMap&>("position")->Get();
if (param == "?")
{
for (ai::PositionMap::iterator i = posMap.begin(); i != posMap.end(); ++i)
{
if (i->second.isSet())
TellPosition(ai, i->first, i->second);
}
return true;
}
vector<string> params = split(param, ' ');
if (params.size() != 2)
{
ai->TellMaster("Whisper position <name> ?/set/reset");
return false;
}
string name = params[0];
string action = params[1];
ai::Position pos = posMap[name];
if (action == "?")
{
TellPosition(ai, name, pos);
return true;
}
vector<string> coords = split(action, ',');
if (coords.size() == 3)
{
pos.Set(atoi(coords[0].c_str()), atoi(coords[1].c_str()), atoi(coords[2].c_str()));
posMap[name] = pos;
ostringstream out; out << "Position " << name << " is set";
ai->TellMaster(out);
return true;
}
if (action == "set")
{
pos.Set( bot->GetPositionX(), bot->GetPositionY(), bot->GetPositionZ());
posMap[name] = pos;
ostringstream out; out << "Position " << name << " is set";
ai->TellMaster(out);
return true;
}
if (action == "reset")
{
pos.Reset();
posMap[name] = pos;
ostringstream out; out << "Position " << name << " is reset";
ai->TellMaster(out);
return true;
}
return false;
}
bool MoveToPositionAction::Execute(Event event)
{
ai::Position pos = context->GetValue<ai::PositionMap&>("position")->Get()[qualifier];
if (!pos.isSet())
{
ostringstream out; out << "Position " << qualifier << " is not set";
ai->TellMaster(out);
return false;
}
return MoveTo(bot->GetMapId(), pos.x, pos.y, pos.z);
}
| 23.650943 | 91 | 0.554049 | [
"vector"
] |
eb6292cf4441f5f2a9ac0bbf938ec6a6b4a61807 | 13,747 | cpp | C++ | src/algorithm/graph/connectivity.cpp | allison-group/indigox | 22657cb3ceb888049cc231e73d18fb2eac099604 | [
"MIT"
] | 7 | 2019-11-24T15:51:37.000Z | 2021-10-02T05:18:42.000Z | src/algorithm/graph/connectivity.cpp | allison-group/indigox | 22657cb3ceb888049cc231e73d18fb2eac099604 | [
"MIT"
] | 2 | 2018-12-17T00:55:32.000Z | 2019-10-11T01:47:04.000Z | src/algorithm/graph/connectivity.cpp | allison-group/indigox | 22657cb3ceb888049cc231e73d18fb2eac099604 | [
"MIT"
] | 2 | 2019-10-21T01:26:56.000Z | 2019-12-02T00:00:42.000Z | #include <indigox/algorithm/access.hpp>
#include <indigox/algorithm/graph/connectivity.hpp>
#include <indigox/classes/atom.hpp>
#include <indigox/classes/molecule.hpp>
#include <indigox/graph/condensed.hpp>
#include <indigox/graph/molecular.hpp>
#include <indigox/utils/common.hpp>
#include <indigox/utils/triple.hpp>
#include <boost/dynamic_bitset.hpp>
#include <boost/graph/connected_components.hpp>
#include <EASTL/bitset.h>
#include <EASTL/vector_map.h>
#include <memory>
#include <vector>
namespace indigox::algorithm {
using namespace indigox::graph;
// ===========================================================================
// == Connected components implementation ====================================
// ===========================================================================
template <class V, class E, class S, class D, class VP, class EP,
class Container>
int64_t ConnectedComponents(BaseGraph<V, E, S, D, VP, EP> &G,
Container &bits) {
static_assert(!D::is_directed, "Connectivity requires an undirected graph");
using GraphType = BaseGraph<V, E, S, D, VP, EP>;
using BaseType = typename GraphType::graph_type;
using VertIdxMap = eastl::vector_map<typename GraphType::VertType, int>;
using namespace boost;
BaseType &g = access::GetGraph(G);
VertIdxMap data;
associative_property_map<VertIdxMap> indexMap(data);
typename GraphType::VertIter begin, end;
std::tie(begin, end) = boost::vertices(g);
for (int i = 0; begin != end; ++begin, ++i) put(indexMap, *begin, i);
size_t num = connected_components(g, get(&VP::component, g),
vertex_index_map(indexMap));
bits.clear();
bits.assign(num, typename GraphType::VertContain());
for (auto &v : access::GetVertexMap(G).right)
bits[g[v.first].component].emplace_back(v.second);
return bits.size();
}
template int64_t
ConnectedComponents(CondensedMolecularGraph::graph_type &,
CondensedMolecularGraph::ComponentContain &);
template int64_t ConnectedComponents(MolecularGraph::graph_type &,
MolecularGraph::ComponentContain &);
// =======================================================================
// == Connected subgraphs implementation =================================
// =======================================================================
template <class GraphType> struct ConnectedSubgraphs<GraphType>::Impl {
using vert_contain = typename GraphType::VertContain;
using BitSet = boost::dynamic_bitset<>;
using StackItem = stdx::triple<BitSet>;
GraphType graph;
size_t min_subgraph_size;
size_t max_subgraph_size;
vert_contain vertices;
eastl::vector_map<size_t, BitSet> neighbours;
std::vector<StackItem> stack;
Impl(GraphType &G, size_t min, size_t max)
: graph(G), min_subgraph_size(min), max_subgraph_size(max),
vertices(G.GetVertices()) {}
~Impl() { }
void BuildNeighboursBitsets() {
for (size_t i = 0; i < vertices.size(); ++i) {
auto &v_nbrs = graph.GetNeighbours(vertices[i]);
BitSet nbrs(vertices.size());
nbrs.reset();
for (auto &v : v_nbrs) {
auto pos = std::find(vertices.begin(), vertices.end(), v);
nbrs.set(std::distance(vertices.begin(), pos));
}
neighbours.emplace(i, nbrs);
}
}
void Initialise() {
BuildNeighboursBitsets();
BitSet bag(vertices.size());
bag.reset();
for (size_t i = 0; i < vertices.size(); ++i) bag.set(i);
BitSet initial(vertices.size());
initial.reset();
BitSet nbrs(bag);
nbrs.reset();
size_t pos = initial.find_first();
while (pos < neighbours.size()) {
auto test = neighbours.find(pos);
if (test == neighbours.end()) break;
nbrs |= test->second;
pos = initial.find_next(pos);
}
stack.emplace_back(bag, initial, nbrs);
}
bool NextSubgraph(GraphType &subgraph) {
while (stack.size()) {
StackItem item = stack.back();
stack.pop_back();
BitSet cur_bag = item.first;
BitSet cur_subg = item.second;
BitSet cur_nbrs = item.third;
BitSet possible;
if (cur_subg.none())
possible = cur_bag;
else
possible = cur_bag & cur_nbrs;
if (possible.none() && cur_subg.any() &&
cur_subg.count() <= max_subgraph_size &&
cur_subg.count() >= min_subgraph_size) {
std::vector<typename GraphType::VertexType> verts;
verts.reserve(cur_subg.count());
size_t pos = cur_subg.find_first();
while (pos < vertices.size()) {
verts.emplace_back(vertices[pos]);
pos = cur_subg.find_next(pos);
}
GraphType subg = graph.Subgraph(verts);
subgraph = subg;
return true;
} else if (possible.any()) {
BitSet v = possible;
v.reset();
v.set(possible.find_first());
if (cur_subg.count() <= max_subgraph_size) {
BitSet bag_minus_v = cur_bag;
bag_minus_v.reset(v.find_first());
stack.emplace_back(bag_minus_v, cur_subg, cur_nbrs);
stack.emplace_back(bag_minus_v, cur_subg | v,
cur_nbrs | neighbours.at(v.find_first()));
}
}
}
return false;
}
};
template <class GraphType>
ConnectedSubgraphs<GraphType>::ConnectedSubgraphs(GraphType &G, size_t min,
size_t max)
: implementation(std::make_unique<Impl>(G, min, max)) {
implementation->Initialise();
}
template <class GraphType>
ConnectedSubgraphs<GraphType>::~ConnectedSubgraphs() = default;
template <class GraphType>
bool ConnectedSubgraphs<GraphType>::operator()(GraphType &subgraph) {
return implementation->NextSubgraph(subgraph);
}
template class ConnectedSubgraphs<graph::MolecularGraph>;
template class ConnectedSubgraphs<graph::CondensedMolecularGraph>;
// =======================================================================
// == Optimal charge groups implementation ===============================
// =======================================================================
struct ChargeGroupOptimiser {
using BitSet = boost::dynamic_bitset<>;
using Score = double;
using Division = std::vector<BitSet>;
using ScoredDivisions = std::map<Division, Score>;
using OptimalDivision = std::map<BitSet, Division>;
graph::MolecularGraph full_graph, leafless;
int32_t size_limit;
std::vector<graph::MGVertex> non_leaf_vertices, leaf_vertices;
std::vector<int32_t> weights;
std::map<BitSet::size_type, Score> position_scores;
std::map<BitSet::size_type, BitSet> neighbours;
ScoredDivisions seen_division_scores;
OptimalDivision optimal_seen_divisions;
ChargeGroupOptimiser(const Molecule &mol, int32_t limit);
double PenaltyScore(BitSet group);
void Initalise();
std::vector<std::vector<graph::MGVertex>> Optimise();
Division &Divisions(BitSet bag);
void ConnectedSubgraphs(BitSet bag, BitSet current, BitSet nbrs,
std::vector<BitSet> &subgraphs);
};
std::vector<std::vector<Atom>> OptimalChargeGroups(const Molecule &mol,
int32_t limit) {
ChargeGroupOptimiser optimiser(mol, limit);
optimiser.Initalise();
std::vector<std::vector<graph::MGVertex>> v_cgs = optimiser.Optimise();
std::vector<std::vector<Atom>> charge_groups;
for (std::vector<graph::MGVertex> grp : v_cgs) {
charge_groups.emplace_back(std::vector<Atom>());
for (graph::MGVertex v : grp) {
charge_groups.back().emplace_back(v.GetAtom());
}
}
return charge_groups;
}
ChargeGroupOptimiser::ChargeGroupOptimiser(const Molecule &mol, int32_t limit)
: full_graph(mol.GetGraph()), size_limit(limit) {}
double ChargeGroupOptimiser::PenaltyScore(BitSet group) {
double score = 0.;
BitSet::size_type pos = group.find_first();
while (pos < group.size()) {
score += position_scores[pos];
pos = group.find_next(pos);
}
return abs(score);
}
void ChargeGroupOptimiser::Initalise() {
// Vertices identify and sort
for (graph::MGVertex v : full_graph.GetVertices()) {
if (full_graph.Degree(v) == 1) {
leaf_vertices.push_back(v);
} else {
non_leaf_vertices.push_back(v);
}
}
leafless = full_graph.Subgraph(non_leaf_vertices);
BitSet::size_type v_pos = 0;
for (graph::MGVertex v : non_leaf_vertices) {
// Neighbours generation
BitSet nbrs(non_leaf_vertices.size());
for (graph::MGVertex n : leafless.GetNeighbours(v)) {
BitSet::size_type n_pos = std::distance(
non_leaf_vertices.begin(),
std::find(non_leaf_vertices.begin(), non_leaf_vertices.end(), n));
nbrs.set(n_pos);
}
neighbours.emplace(v_pos, nbrs);
// Scores per vertex pre calculation
int32_t weight = 1;
Atom atm = v.GetAtom();
double score = atm.GetFormalCharge() - atm.GetPartialCharge();
for (graph::MGVertex u : full_graph.GetNeighbours(v)) {
if (std::find(non_leaf_vertices.begin(), non_leaf_vertices.end(), u) ==
non_leaf_vertices.end()) {
atm = u.GetAtom();
score += atm.GetFormalCharge() - atm.GetPartialCharge();
++weight;
}
}
position_scores.emplace(v_pos, score);
weights.emplace_back(weight);
++v_pos;
// Terminal case seen score
seen_division_scores.emplace(Division(), 0.0);
optimal_seen_divisions.emplace(BitSet(non_leaf_vertices.size()),
Division());
}
}
std::vector<std::vector<graph::MGVertex>> ChargeGroupOptimiser::Optimise() {
BitSet bag(non_leaf_vertices.size());
bag.set();
Division optimal_division = Divisions(bag);
std::vector<std::vector<graph::MGVertex>> charge_groups;
for (BitSet div : optimal_division) {
charge_groups.emplace_back(std::vector<graph::MGVertex>());
charge_groups.back().reserve(div.count());
BitSet::size_type pos = div.find_first();
while (pos < div.size()) {
charge_groups.back().emplace_back(non_leaf_vertices[pos]);
for (graph::MGVertex nbr :
full_graph.GetNeighbours(non_leaf_vertices[pos])) {
if (full_graph.Degree(nbr) == 1) {
charge_groups.back().emplace_back(nbr);
}
}
pos = div.find_next(pos);
}
}
return charge_groups;
}
ChargeGroupOptimiser::Division &ChargeGroupOptimiser::Divisions(BitSet bag) {
auto seen_pos = optimal_seen_divisions.find(bag);
if (seen_pos != optimal_seen_divisions.end()) { return seen_pos->second; }
BitSet::size_type v = bag.find_first();
std::vector<BitSet> subgraphs;
BitSet bag_minus_v(bag);
bag_minus_v.reset(v);
BitSet current(bag.size()), nbrs(neighbours.at(v));
current.set(v);
ConnectedSubgraphs(bag_minus_v, current, nbrs, subgraphs);
for (BitSet g : subgraphs) {
BitSet bag_minus_g = bag - g;
Division new_div = Divisions(bag_minus_g);
Score new_score = seen_division_scores.at(new_div);
Score cur_score = PenaltyScore(g);
auto seen_position = optimal_seen_divisions.find(bag);
Division optimal_div(new_div);
optimal_div.emplace_back(g);
Score optimal_score = cur_score + new_score;
if (seen_position == optimal_seen_divisions.end()) {
seen_division_scores.emplace(optimal_div, optimal_score);
optimal_seen_divisions.emplace(bag, optimal_div);
} else if ((seen_division_scores.at(seen_position->second) >
(optimal_score))) {
seen_position->second = optimal_div;
seen_division_scores[optimal_div] = optimal_score;
}
if (-1e-10 < optimal_score && 1e-10 > optimal_score) break;
}
return optimal_seen_divisions.at(bag);
}
void ChargeGroupOptimiser::ConnectedSubgraphs(
BitSet bag, BitSet current, BitSet nbrs, std::vector<BitSet> &subgraphs) {
subgraphs.clear();
using StackItem = stdx::triple<BitSet>;
std::vector<StackItem> stack;
stack.emplace_back(bag, current, nbrs);
while (!stack.empty()) {
StackItem item = stack.back();
stack.pop_back();
BitSet possibles = item.first;
if (item.second.any()) possibles = item.first & item.third;
if (possibles.none() && item.second.any()) {
subgraphs.emplace_back(item.second);
} else if (possibles.any()) {
BitSet::size_type v = possibles.find_first();
int32_t v_weight = 0;
BitSet::size_type pos = item.second.find_first();
while (pos < item.second.size()) {
v_weight += weights[pos];
pos = item.second.find_next(pos);
}
if (v_weight < size_limit) {
BitSet bag_minus_v(item.first);
bag_minus_v.reset(v);
BitSet g_and_v(item.second);
g_and_v.set(v);
BitSet new_nbrs = item.third | neighbours.at(v);
stack.emplace_back(bag_minus_v, item.second, item.third);
stack.emplace_back(bag_minus_v, g_and_v, new_nbrs);
} else {
subgraphs.emplace_back(item.second);
}
}
}
std::sort(subgraphs.begin(), subgraphs.end(),
[](BitSet &a, BitSet &b) { return a.count() < b.count(); });
}
} // namespace indigox::algorithm
| 35.521964 | 80 | 0.605223 | [
"vector"
] |
eb7802d528f3de0a3bd84ee215618444fbe82c48 | 2,921 | cpp | C++ | src/hc_sr04_node.cpp | matpalm/ros-hc-sr04-node | e64b5678169732b705510d0911b5ba8775964292 | [
"MIT"
] | 19 | 2017-02-13T19:36:16.000Z | 2021-01-07T21:58:56.000Z | src/hc_sr04_node.cpp | Desoky01/ros-hc-sr04-node | e64b5678169732b705510d0911b5ba8775964292 | [
"MIT"
] | null | null | null | src/hc_sr04_node.cpp | Desoky01/ros-hc-sr04-node | e64b5678169732b705510d0911b5ba8775964292 | [
"MIT"
] | 12 | 2016-12-08T11:27:19.000Z | 2020-01-23T13:03:51.000Z | #include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <ros/ros.h>
#include <sensor_msgs/Range.h>
#include <wiringPi.h>
using namespace std;
namespace hc_sr04_node {
// Maximum distance reported. Values over this distance
// report MAX_DISTANCE. TODO make this a property.
const static float MAX_DISTANCE = 30;
const static float DIST_SCALE = 58.0;
const static float TRAVEL_TIME_MAX = MAX_DISTANCE * DIST_SCALE;
class Sonar {
public:
Sonar(int t, int e) : trigger_(t), echo_(e) {
pinMode(trigger_, OUTPUT);
pinMode(echo_, INPUT);
digitalWrite(trigger_, LOW);
delay(1000);
}
float distance(bool* error) {
// Send trig pulse
digitalWrite(trigger_, HIGH);
delayMicroseconds(20);
digitalWrite(trigger_, LOW);
// Wait for echo. Very rarely (2 of 12K at 20Hz)
// see ECHO never go HIGH so we include a way to
// bail.
int bail = 1000;
while(digitalRead(echo_) == LOW) {
if (--bail == 0) {
*error = true;
return 0;
}
}
// Measure time for echo. Return early if the
// pulse is appearing to take too long. Note:
// error case of never going LOW results in
// MAX reading :/
long startTime = micros();
long travelTime = 0;
while(digitalRead(echo_) == HIGH) {
travelTime = micros() - startTime;
if (travelTime > TRAVEL_TIME_MAX) {
travelTime = TRAVEL_TIME_MAX;
break;
}
delayMicroseconds(100);
}
// Return distance in cm
*error = false;
return travelTime / 58.0;
}
private:
int trigger_;
int echo_;
};
} // namespace hc_sr04_node
int main(int argc, char **argv) {
// Start ROS node.
ROS_INFO("Starting node");
ros::init(argc, argv, "hc_sr04s");
ros::NodeHandle node;
ros::Rate rate(10); // 10 hz
// Build N sonars.
wiringPiSetupSys(); // uses gpio pin numbering
// TODO: config these
vector<hc_sr04_node::Sonar> sonars;
sonars.push_back(hc_sr04_node::Sonar(24, 25));
sonars.push_back(hc_sr04_node::Sonar(22, 23));
sonars.push_back(hc_sr04_node::Sonar(18, 27));
// Build a publisher for each sonar.
vector<ros::Publisher> sonar_pubs;
for (int i = 0; i < sonars.size(); ++i) {
stringstream ss;
ss << "sonar_" << i;
sonar_pubs.push_back(node.advertise<sensor_msgs::Range>(ss.str(), 10));
}
// Build base range message that will be used for
// each time a msg is published.
sensor_msgs::Range range;
range.radiation_type = sensor_msgs::Range::ULTRASOUND;
range.min_range = 0.0;
range.max_range = hc_sr04_node::MAX_DISTANCE;
float distance;
bool error;
while(ros::ok()) {
for (int i = 0; i < sonars.size(); ++i) {
range.header.stamp = ros::Time::now();
range.range = sonars[i].distance(&error);
if (error)
ROS_WARN("Error on sonar %d", i);
else
sonar_pubs[i].publish(range);
}
ros::spinOnce();
rate.sleep();
}
return 0;
}
| 24.754237 | 75 | 0.641561 | [
"vector"
] |
eb791e08d46c5e89753f622ade0566e5c4e6b3f2 | 1,784 | cpp | C++ | server/Encoder/NvidiaEncoder.cpp | traies/sunshine | c49d3d976b1c26f9ddda7805073ed688383719bf | [
"MIT"
] | 1 | 2021-04-08T14:23:43.000Z | 2021-04-08T14:23:43.000Z | server/Encoder/NvidiaEncoder.cpp | traies/sunshine | c49d3d976b1c26f9ddda7805073ed688383719bf | [
"MIT"
] | null | null | null | server/Encoder/NvidiaEncoder.cpp | traies/sunshine | c49d3d976b1c26f9ddda7805073ed688383719bf | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "NvidiaEncoder.h"
using namespace std;
NvidiaEncoder::NvidiaEncoder()
{
}
NvidiaEncoder::~NvidiaEncoder()
{
}
bool NvidiaEncoder::EncodeFrame(ID3D11Texture2D * frame)
{
if (_encoder == nullptr) {
if (!InitEncoder(frame)) {
return false;
}
}
ID3D11Texture2D * inputFrame = reinterpret_cast<ID3D11Texture2D * >(_encoder->GetNextInputFrame()->inputPtr);
ID3D11DeviceContext * context;
ID3D11Device * device;
frame->GetDevice(&device);
device->GetImmediateContext(&context);
context->CopyResource(inputFrame, frame);
vector<vector<uint8_t>> buffer;
_encoder->EncodeFrame(buffer);
_queue.push(make_unique<NvidiaFrameBuffer>(buffer));
return true;
}
unique_ptr<FrameBuffer> NvidiaEncoder::PullFrame()
{
if (!_queue.empty()) {
auto packet = move(_queue.front());
_queue.pop();
return packet;
}
else {
return nullptr;
}
}
bool NvidiaEncoder::InitEncoder(ID3D11Texture2D * frame)
{
D3D11_TEXTURE2D_DESC desc;
ZeroMemory(&desc, sizeof(desc));
frame->GetDesc(&desc);
int width = desc.Width, height = desc.Width;
auto d3df = desc.Format;
ID3D11Device * device;
frame->GetDevice(&device);
NV_ENC_BUFFER_FORMAT format = NV_ENC_BUFFER_FORMAT_ABGR;
_encoder = make_unique<NvEncoderD3D11>(
device,
desc.Width,
desc.Height,
format,
desc.Format,
0,
false
);
NV_ENC_INITIALIZE_PARAMS initParams;
ZeroMemory(&initParams, sizeof(initParams));
NV_ENC_CONFIG config = {NV_ENC_CONFIG_VER};
initParams.encodeConfig = &config;
_encoder->CreateDefaultEncoderParams(
&initParams,
NV_ENC_CODEC_H264_GUID,
NV_ENC_PRESET_LOW_LATENCY_HP_GUID
);
/*config.*/
try {
_encoder->CreateEncoder(&initParams);
}
catch (exception & ex) {
cout << ex.what() << endl;
return false;
}
return true;
}
| 18.778947 | 110 | 0.725897 | [
"vector"
] |
eb79416c6ca9690f0e190dde5d072d6062cda225 | 5,888 | cpp | C++ | Spatial_searching/test/Spatial_searching/Splitters.cpp | ffteja/cgal | c1c7f4ad9a4cd669e33ca07a299062a461581812 | [
"CC0-1.0"
] | 3,227 | 2015-03-05T00:19:18.000Z | 2022-03-31T08:20:35.000Z | Spatial_searching/test/Spatial_searching/Splitters.cpp | ffteja/cgal | c1c7f4ad9a4cd669e33ca07a299062a461581812 | [
"CC0-1.0"
] | 5,574 | 2015-03-05T00:01:56.000Z | 2022-03-31T15:08:11.000Z | Spatial_searching/test/Spatial_searching/Splitters.cpp | ffteja/cgal | c1c7f4ad9a4cd669e33ca07a299062a461581812 | [
"CC0-1.0"
] | 1,274 | 2015-03-05T00:01:12.000Z | 2022-03-31T14:47:56.000Z |
#include <CGAL/Simple_cartesian.h>
#include <cassert>
#include <CGAL/point_generators_2.h>
#include <CGAL/point_generators_3.h>
#include <CGAL/Random.h>
#include <CGAL/Search_traits_2.h>
#include <CGAL/Search_traits_3.h>
#include <CGAL/Search_traits_adapter.h>
#include <CGAL/Orthogonal_incremental_neighbor_search.h>
#include <CGAL/algorithm.h>
#include "Point_with_info.h"
#ifdef TWO
typedef CGAL::Simple_cartesian<double> K;
typedef K::Point_2 Point;
typedef CGAL::Creator_uniform_2<double,Point> Creator;
typedef CGAL::Random_points_in_disc_2<Point,Creator> Random_points;
typedef CGAL::Search_traits_2<K> TreeTraits;
typedef CGAL::Euclidean_distance<TreeTraits> Distance;
#else
typedef CGAL::Simple_cartesian<double> K;
typedef K::Point_3 Point;
typedef CGAL::Creator_uniform_3<double,Point> Creator;
typedef CGAL::Random_points_in_sphere_3<Point,Creator> Random_points;
typedef CGAL::Search_traits_3<K> TreeTraits;
typedef CGAL::Euclidean_distance<TreeTraits> Distance;
#endif
typedef Point_with_info_helper<Point>::type Point_with_info;
typedef Point_property_map<Point> Ppmap;
typedef CGAL::Search_traits_adapter<Point_with_info,Ppmap,TreeTraits> Traits_with_info;
typedef CGAL::Distance_adapter <Point_with_info,Ppmap,Distance> Distance_adapter;
typedef std::vector<Point> Vector;
template <class Traits,class S,class Distance>
struct Splitter_test {
typedef CGAL::Orthogonal_incremental_neighbor_search<Traits,Distance,S> Orthogonal_incremental_neighbor_search;
typedef typename Orthogonal_incremental_neighbor_search::iterator NN_iterator;
typedef typename Orthogonal_incremental_neighbor_search::Tree Tree;
typedef typename Orthogonal_incremental_neighbor_search::Point_with_transformed_distance Point_with_transformed_distance;
bool operator()(Vector points, Point query) {
Vector points2;
Tree t(
boost::make_transform_iterator(points.begin(),Create_point_with_info<typename Traits::Point_d>()),
boost::make_transform_iterator(points.end(),Create_point_with_info<typename Traits::Point_d>())
);
Orthogonal_incremental_neighbor_search oins(t, query, 0.0, true);
typename Orthogonal_incremental_neighbor_search::iterator it = oins.begin();
Point_with_transformed_distance pd = *it;
points2.push_back(get_point(pd.first));
if(CGAL::squared_distance(query,get_point(pd.first)) != pd.second){
std::cout << CGAL::squared_distance(query,get_point(pd.first)) << " != " << pd.second << std::endl;
}
assert(CGAL_IA_FORCE_TO_DOUBLE(CGAL::squared_distance(query,get_point(pd.first))) == pd.second);
it++;
for(; it != oins.end();it++){
Point_with_transformed_distance qd = *it;
assert(pd.second <= qd.second);
pd = qd;
points2.push_back(get_point(pd.first));
if(CGAL_IA_FORCE_TO_DOUBLE(CGAL::squared_distance(query,get_point(pd.first))) != pd.second){
std::cout << CGAL::squared_distance(query,get_point(pd.first)) << " != " << pd.second << std::endl;
}
assert(CGAL_IA_FORCE_TO_DOUBLE(CGAL::squared_distance(query,get_point(pd.first))) == pd.second);
}
std::sort(points.begin(),points.end());
std::sort(points2.begin(),points2.end());
assert(points.size() == points2.size());
assert(points == points2);
return true;
}
};
int
main() {
// We enforce IEEE double precision as we compare a distance
// in a register with a distance in memory
CGAL::Set_ieee_double_precision pfr;
Vector points;
Random_points g( 150.0);
std::copy_n( g, 1000, std::back_inserter(points));
g++;
Point query = *g;
{
std::cout << "Testing Sliding_midpoint" << std::endl;
Splitter_test<TreeTraits,CGAL::Sliding_midpoint<TreeTraits>,Distance > st;
st(points,query);
Splitter_test<Traits_with_info,CGAL::Sliding_midpoint<Traits_with_info>,Distance_adapter > sti;
sti(points,query);
}
{
std::cout << "Testing Sliding_fair" << std::endl;
Splitter_test<TreeTraits,CGAL::Sliding_fair<TreeTraits>,Distance > st;
st(points,query);
Splitter_test<Traits_with_info,CGAL::Sliding_fair<Traits_with_info>,Distance_adapter > sti;
sti(points,query);
}
{
std::cout << "Testing Fair" << std::endl;
Splitter_test<TreeTraits,CGAL::Fair<TreeTraits>,Distance > st;
st(points,query);
Splitter_test<Traits_with_info,CGAL::Fair<Traits_with_info>,Distance_adapter > sti;
sti(points,query);
}
{
std::cout << "Testing Median_of_rectangle" << std::endl;
Splitter_test<TreeTraits,CGAL::Median_of_rectangle<TreeTraits>,Distance > st;
st(points,query);
Splitter_test<Traits_with_info,CGAL::Median_of_rectangle<Traits_with_info>,Distance_adapter > sti;
sti(points,query);
}
{
std::cout << "Testing Midpoint_of_rectangle" << std::endl;
Splitter_test<TreeTraits,CGAL::Midpoint_of_rectangle<TreeTraits>,Distance > st;
st(points,query);
Splitter_test<Traits_with_info,CGAL::Midpoint_of_rectangle<Traits_with_info>,Distance_adapter > sti;
sti(points,query);
}
{
std::cout << "Testing Midpoint_of_max_spread" << std::endl;
Splitter_test<TreeTraits,CGAL::Midpoint_of_max_spread<TreeTraits>,Distance > st;
st(points,query);
Splitter_test<Traits_with_info,CGAL::Midpoint_of_max_spread<Traits_with_info>,Distance_adapter > sti;
sti(points,query);
}
{
std::cout << "Testing Median_of_max_spread" << std::endl;
Splitter_test<TreeTraits,CGAL::Median_of_max_spread<TreeTraits>,Distance > st;
st(points,query);
Splitter_test<Traits_with_info,CGAL::Median_of_max_spread<Traits_with_info>,Distance_adapter > sti;
sti(points,query);
}
std::cout << "done" << std::endl;
return 0;
}
| 37.265823 | 123 | 0.715014 | [
"vector"
] |
eb7988706f6d7ae922b774ee3cd6220d8c1c6534 | 23,337 | cpp | C++ | test/blackbox/common/DDSBlackboxTestsDiscovery.cpp | timmylinux/Fast-DDS | e6e7eac5a642f606fdaa40a0a2a16617ae9384da | [
"Apache-2.0"
] | 575 | 2015-01-22T20:05:04.000Z | 2020-06-01T10:06:12.000Z | test/blackbox/common/DDSBlackboxTestsDiscovery.cpp | timmylinux/Fast-DDS | e6e7eac5a642f606fdaa40a0a2a16617ae9384da | [
"Apache-2.0"
] | 1,110 | 2015-04-20T19:30:34.000Z | 2020-06-01T08:13:52.000Z | test/blackbox/common/DDSBlackboxTestsDiscovery.cpp | timmylinux/Fast-DDS | e6e7eac5a642f606fdaa40a0a2a16617ae9384da | [
"Apache-2.0"
] | 273 | 2015-08-10T23:34:42.000Z | 2020-05-28T13:03:32.000Z | // Copyright 2020 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cstdlib>
#include <ctime>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include "BlackboxTests.hpp"
#include "PubSubParticipant.hpp"
#include "PubSubReader.hpp"
#include "PubSubWriter.hpp"
#include <fastdds/dds/core/policy/ParameterTypes.hpp>
#include <fastdds/dds/core/policy/QosPolicies.hpp>
#include <fastdds/dds/domain/DomainParticipant.hpp>
#include <fastdds/dds/domain/DomainParticipantFactory.hpp>
#include <fastdds/dds/domain/DomainParticipantListener.hpp>
#include <fastdds/dds/domain/qos/DomainParticipantQos.hpp>
#include <fastdds/rtps/common/Locator.h>
#include <fastdds/rtps/participant/ParticipantDiscoveryInfo.h>
#include <fastdds/rtps/transport/test_UDPv4TransportDescriptor.h>
#include <rtps/transport/test_UDPv4Transport.h>
#include <utils/SystemInfo.hpp>
// Regression test for redmine issue 11857
TEST(DDSDiscovery, IgnoreParticipantFlags)
{
// This participant is created with:
// - ignoreParticipantFlags = FILTER_SAME_PROCESS (will avoid discovery of p2)
// - metatrafficUnicastLocatorList = 127.0.0.1:7399, 127.0.0.1:7398 (to ensure two listening threads are created)
PubSubReader<HelloWorldPubSubType> p1(TEST_TOPIC_NAME);
p1.set_xml_filename("discovery_participant_flags.xml");
p1.set_participant_profile("participant_1");
p1.init();
EXPECT_TRUE(p1.isInitialized());
// This participant is created with initialPeersList = 127.0.0.1:7399
// When the announcements of this participant arrive to p1, they will be ignored, and thus p1 will not
// announce itself back to p2.
PubSubReader<HelloWorldPubSubType> p2(TEST_TOPIC_NAME);
p2.set_xml_filename("discovery_participant_flags.xml");
p2.set_participant_profile("participant_2");
p2.init();
EXPECT_TRUE(p2.isInitialized());
EXPECT_FALSE(p2.wait_participant_discovery(1, std::chrono::seconds(1)));
EXPECT_FALSE(p1.wait_participant_discovery(1, std::chrono::seconds(1)));
// This participant is created with:
// - initialPeersList = 127.0.0.1:7398
// - a custom guid prefix
// The announcements of this participant will arrive to p1 on a different listening thread.
// Due to the custom prefix, they should not be ignored, and mutual discovery should happen
PubSubReader<HelloWorldPubSubType> p3(TEST_TOPIC_NAME);
p3.set_xml_filename("discovery_participant_flags.xml");
p3.set_participant_profile("participant_3");
p3.init();
EXPECT_TRUE(p1.wait_participant_discovery());
EXPECT_TRUE(p3.wait_participant_discovery());
}
/**
* This test checks that adding servers to the Discovery Server list results in discovering those participants.
* It does so by:
* 1. Creating two servers and one client that is only connected to one server. At this point check discovery
* state.
* 2. Then, connect the client to the other server and check discovery again.
* 3. Finally connect the two servers by adding one of them to the others list
*/
TEST(DDSDiscovery, AddDiscoveryServerToList)
{
using namespace eprosima;
using namespace eprosima::fastdds::dds;
using namespace eprosima::fastrtps::rtps;
/* Get random port from the environment */
std::string value;
if (eprosima::ReturnCode_t::RETCODE_OK != SystemInfo::get_env("W_UNICAST_PORT_RANDOM_NUMBER", value))
{
value = std::string("11811");
}
/* Create first server */
PubSubParticipant<HelloWorldPubSubType> server_1(0u, 0u, 0u, 0u);
// Set participant as server
WireProtocolConfigQos server_1_qos;
server_1_qos.builtin.discovery_config.discoveryProtocol = DiscoveryProtocol_t::SERVER;
// Generate random GUID prefix
srand(static_cast<unsigned>(time(nullptr)));
GuidPrefix_t server_1_prefix;
for (auto i = 0; i < 12; i++)
{
server_1_prefix.value[i] = eprosima::fastrtps::rtps::octet(rand() % 254);
}
server_1_qos.prefix = server_1_prefix;
// Generate server's listening locator
Locator_t locator_server_1;
IPLocator::setIPv4(locator_server_1, 127, 0, 0, 1);
uint32_t server_1_port = atol(value.c_str());
locator_server_1.port = server_1_port;
server_1_qos.builtin.metatrafficUnicastLocatorList.push_back(locator_server_1);
// Init server
ASSERT_TRUE(server_1.wire_protocol(server_1_qos).init_participant());
/* Create second server */
PubSubParticipant<HelloWorldPubSubType> server_2(0u, 0u, 0u, 0u);
// Set participant as server
WireProtocolConfigQos server_2_qos;
server_2_qos.builtin.discovery_config.discoveryProtocol = DiscoveryProtocol_t::SERVER;
// Generate random GUID prefix
GuidPrefix_t server_2_prefix = server_1_prefix;
server_2_prefix.value[11]++;
server_2_qos.prefix = server_2_prefix;
// Generate server's listening locator
Locator_t locator_server_2;
IPLocator::setIPv4(locator_server_2, 127, 0, 0, 1);
uint32_t server_2_port = atol(value.c_str()) + 1;
locator_server_2.port = server_2_port;
server_2_qos.builtin.metatrafficUnicastLocatorList.push_back(locator_server_2);
// Init server
ASSERT_TRUE(server_2.wire_protocol(server_2_qos).init_participant());
/* Create a client that connects to the first server from the beginning */
PubSubParticipant<HelloWorldPubSubType> client(0u, 0u, 0u, 0u);
// Set participant as client
WireProtocolConfigQos client_qos;
client_qos.builtin.discovery_config.discoveryProtocol = DiscoveryProtocol_t::CLIENT;
// Connect to first server
RemoteServerAttributes server_1_att;
server_1_att.guidPrefix = server_1_prefix;
server_1_att.metatrafficUnicastLocatorList.push_back(Locator_t(locator_server_1));
client_qos.builtin.discovery_config.m_DiscoveryServers.push_back(server_1_att);
// Init client
ASSERT_TRUE(client.wire_protocol(client_qos).init_participant());
/**
* Check that server_1 and client_1 only know each other, and that server_2 does has not
* discovered anyone
*/
server_1.wait_discovery(std::chrono::seconds::zero(), 1, true);
client.wait_discovery(std::chrono::seconds::zero(), 1, true);
server_2.wait_discovery(std::chrono::seconds::zero(), 0, true);
/* Add server_2 to client */
RemoteServerAttributes server_2_att;
server_2_att.guidPrefix = server_2_prefix;
server_2_att.metatrafficUnicastLocatorList.push_back(Locator_t(locator_server_2));
client_qos.builtin.discovery_config.m_DiscoveryServers.push_back(server_2_att);
// Update client's servers list
ASSERT_TRUE(client.update_wire_protocol(client_qos));
/* Check that the servers only know about the client, and that the client known about both servers */
server_1.wait_discovery(std::chrono::seconds::zero(), 1, true);
client.wait_discovery(std::chrono::seconds::zero(), 2, true);
server_2.wait_discovery(std::chrono::seconds::zero(), 1, true);
/* Add server_2 to server_1 */
server_1_qos.builtin.discovery_config.m_DiscoveryServers.push_back(server_2_att);
ASSERT_TRUE(server_1.update_wire_protocol(server_1_qos));
/* Check that they all know each other */
server_1.wait_discovery(std::chrono::seconds::zero(), 2, true);
client.wait_discovery(std::chrono::seconds::zero(), 2, true);
server_2.wait_discovery(std::chrono::seconds::zero(), 2, true);
}
/**
* This test checks the addition of network interfaces at run-time.
*
* After launching the reader with the network interfaces enabled,
* the writer is launched with the transport simulating that there
* are no interfaces.
* No participant discovery occurs, nor is communication established.
*
* In a second step, the flag to simulate no interfaces is disabled and
* DomainParticipant::set_qos() called to add the "new" interfaces.
* Discovery is succesful and communication is established.
*/
TEST(DDSDiscovery, DDSNetworkInterfaceChangesAtRunTime)
{
using namespace eprosima::fastdds::rtps;
PubSubWriter<HelloWorldPubSubType> datawriter(TEST_TOPIC_NAME);
PubSubReader<HelloWorldPubSubType> datareader(TEST_TOPIC_NAME);
// datareader is initialized with all the network interfaces
datareader.durability_kind(eprosima::fastrtps::TRANSIENT_LOCAL_DURABILITY_QOS).history_depth(100).
reliability(eprosima::fastrtps::RELIABLE_RELIABILITY_QOS).init();
ASSERT_TRUE(datareader.isInitialized());
// datawriter: launch without interfaces
test_UDPv4Transport::simulate_no_interfaces = true;
auto test_transport = std::make_shared<test_UDPv4TransportDescriptor>();
datawriter.disable_builtin_transport().add_user_transport_to_pparams(test_transport).history_depth(100).init();
ASSERT_TRUE(datawriter.isInitialized());
// no discovery
datawriter.wait_discovery(std::chrono::seconds(3));
datareader.wait_discovery(std::chrono::seconds(3));
EXPECT_EQ(datawriter.get_matched(), 0u);
EXPECT_EQ(datareader.get_matched(), 0u);
// send data
auto complete_data = default_helloworld_data_generator();
size_t samples = complete_data.size();
datareader.startReception(complete_data);
datawriter.send(complete_data);
EXPECT_TRUE(complete_data.empty());
// no data received
EXPECT_EQ(datareader.block_for_all(std::chrono::seconds(3)), 0u);
// enable interfaces
test_UDPv4Transport::simulate_no_interfaces = false;
datawriter.participant_set_qos();
// Wait for discovery
datawriter.wait_discovery(std::chrono::seconds(3));
datareader.wait_discovery(std::chrono::seconds(3));
ASSERT_EQ(datawriter.get_matched(), 1u);
ASSERT_EQ(datareader.get_matched(), 1u);
// data received
EXPECT_EQ(datareader.block_for_all(std::chrono::seconds(3)), samples);
datareader.destroy();
datawriter.destroy();
}
/*
* This tests checks that DataReader::get_subscription_matched_status() and
* DataWriter::get_publication_matched_status() return the correct last_publication_handle
* and last_subscription_handle respectively; that is, the handle to the last DataWriter/DataReader which
* discovery/un-discovery triggered a change in the DataReader/DataWriter MatchedStatus.
*
* It does so by creating two pairs of DataReader-DataWriter at different times, waiting for matching/unmatching
* and check the last_publication_handle and last_subscription_handle respectively:
*
* 1. Create a DR and DW in the same partition and wait for discovery
* 2. Check that the last_*_handle is the correct one
* 3. Create another DR and DW in the same partition and wait for discovery
* 4. Check that old DR and DW report the new DW and DR as last_*_handle
* 5. Change old DW to a different partition and wait for undiscovery
* 6. Check that both DR report the old DW as last_publication_handle
* 7. Change old DR to a partition different than the other two and wait for undiscovery
* 8. Check that old DR and new DW report each other as last_*_handle
*/
TEST(DDSDiscovery, UpdateMatchedStatus)
{
/* Create DataReaders and DataWriters */
PubSubWriter<HelloWorldPubSubType> datawriter_1(TEST_TOPIC_NAME);
PubSubReader<HelloWorldPubSubType> datareader_1(TEST_TOPIC_NAME);
PubSubWriter<HelloWorldPubSubType> datawriter_2(TEST_TOPIC_NAME);
PubSubReader<HelloWorldPubSubType> datareader_2(TEST_TOPIC_NAME);
/* Init first pair of DataReader-DataWriter */
datareader_1
.partition("A")
.init();
ASSERT_TRUE(datareader_1.isInitialized());
datawriter_1
.partition("A")
.init();
ASSERT_TRUE(datawriter_1.isInitialized());
/* Wait for discovery */
datareader_1.wait_discovery(std::chrono::seconds(3), 1);
datawriter_1.wait_discovery(1, std::chrono::seconds(3));
ASSERT_EQ(datareader_1.get_matched(), 1u);
ASSERT_EQ(datawriter_1.get_matched(), 1u);
/* Check that the reported last_*_handle are correct */
ASSERT_EQ(datareader_1.get_subscription_matched_status().last_publication_handle,
datawriter_1.datawriter_ihandle());
ASSERT_EQ(datawriter_1.get_publication_matched_status().last_subscription_handle,
datareader_1.datareader_ihandle());
/* Init second pair of DataReader-DataWriter */
datareader_2
.partition("A")
.init();
ASSERT_TRUE(datareader_2.isInitialized());
datawriter_2
.partition("A")
.init();
ASSERT_TRUE(datawriter_2.isInitialized());
/*
* Wait for discovery:
* - DR_1: DW_1, DW_2
* - DR_2: DW_1, DW_2
* - DW_1: DR_1, DR_2
* - DW_2: DR_1, DR_2
*/
datareader_1.wait_discovery(std::chrono::seconds(3), 2);
datawriter_1.wait_discovery(2, std::chrono::seconds(3));
datareader_2.wait_discovery(std::chrono::seconds(3), 2);
datawriter_2.wait_discovery(2, std::chrono::seconds(3));
ASSERT_EQ(datareader_1.get_matched(), 2u);
ASSERT_EQ(datawriter_1.get_matched(), 2u);
ASSERT_EQ(datareader_2.get_matched(), 2u);
ASSERT_EQ(datawriter_2.get_matched(), 2u);
/* Check that the reported last_*_handle are correct */
ASSERT_EQ(datareader_1.get_subscription_matched_status().last_publication_handle,
datawriter_2.datawriter_ihandle());
ASSERT_EQ(datawriter_1.get_publication_matched_status().last_subscription_handle,
datareader_2.datareader_ihandle());
/*
* Change DW_1's partition and wait for undiscovery:
* - DR_1: DW_2
* - DR_2: DW_2
* - DW_1:
* - DW_2: DR_1, DR_2
*/
datawriter_1.update_partition("B");
datawriter_1.wait_reader_undiscovery(0);
datareader_1.wait_writer_undiscovery(1);
datareader_2.wait_writer_undiscovery(1);
/* Check that the reported last_*_handle are correct */
ASSERT_EQ(datareader_1.get_subscription_matched_status().last_publication_handle,
datawriter_1.datawriter_ihandle());
ASSERT_EQ(datareader_2.get_subscription_matched_status().last_publication_handle,
datawriter_1.datawriter_ihandle());
/*
* Change DR_1 partition and wait for undiscovery:
* - DR_1:
* - DR_2: DW_2
* - DW_1:
* - DW_2: DR_2
*/
datareader_1.update_partition("C");
datareader_1.wait_writer_undiscovery(0);
datawriter_2.wait_reader_undiscovery(1);
/* Check that the reported last_*_handle are correct */
ASSERT_EQ(datareader_1.get_subscription_matched_status().last_publication_handle,
datawriter_2.datawriter_ihandle());
ASSERT_EQ(datawriter_2.get_publication_matched_status().last_subscription_handle,
datareader_1.datareader_ihandle());
/* Clean up entities */
datareader_1.destroy();
datareader_2.destroy();
datawriter_1.destroy();
datawriter_2.destroy();
}
/**
* This test checks that the physical properties are correctly sent on the DATA[p], and that the
* ParticipantProxyData on the receiver side has the correct values.
*
* This is done by creating two different participants, one of them overloading
* DomainParticipantListener::on_participant_discovery(). This callback is used to check the
* ParticipantProxyData from the other participant, asserting that the received physical information
* is the same as the one in the sending participant.
*
* Additionally, it checks that whenever the properties are not in the QoS, they are not in the
* received ParticipantProxyData either.
*
*/
TEST(DDSDiscovery, ParticipantProxyPhysicalData)
{
using namespace eprosima::fastdds::dds;
using namespace eprosima::fastrtps::rtps;
class CustomDomainParticipantListener : public DomainParticipantListener
{
public:
CustomDomainParticipantListener(
std::condition_variable* cv,
std::mutex* mtx,
std::atomic<bool>* found)
: remote_participant_info(nullptr)
, cv_(cv)
, mtx_(mtx)
, found_(found)
{
}
~CustomDomainParticipantListener()
{
if (nullptr != remote_participant_info)
{
delete remote_participant_info;
}
remote_participant_info = nullptr;
cv_ = nullptr;
mtx_ = nullptr;
found_ = nullptr;
}
void on_participant_discovery(
DomainParticipant* participant,
ParticipantDiscoveryInfo&& info)
{
std::unique_lock<std::mutex> lck(*mtx_);
static_cast<void>(participant);
if (nullptr != remote_participant_info)
{
delete remote_participant_info;
}
remote_participant_info = new ParticipantDiscoveryInfo(info);
found_->store(true);
cv_->notify_one();
}
ParticipantDiscoveryInfo* remote_participant_info;
private:
std::condition_variable* cv_;
std::mutex* mtx_;
std::atomic<bool>* found_;
};
std::srand(static_cast<unsigned int>(std::time(nullptr)));
int domain_id = std::rand() % 100;
std::vector<std::string> physical_property_names =
{
parameter_policy_physical_data_host,
parameter_policy_physical_data_user,
parameter_policy_physical_data_process
};
DomainParticipantQos qos;
#ifndef FASTDDS_STATISTICS
// Make sure the physical properties are there even when there are no statistics
for (auto physical_property_name : physical_property_names)
{
qos.properties().properties().emplace_back(physical_property_name, "");
}
#endif // ifndef FASTDDS_STATISTICS
std::atomic<bool> participant_found = {false};
std::condition_variable cv;
std::mutex listener_mutex;
CustomDomainParticipantListener listener(&cv, &listener_mutex, &participant_found);
/* Positive case, i.e. the properties are in the QoS and thus in the ParticipantProxyData */
DomainParticipant* part_1 = DomainParticipantFactory::get_instance()->create_participant(domain_id, qos);
DomainParticipant* part_2 = DomainParticipantFactory::get_instance()->create_participant(domain_id, qos, &listener);
// This loops runs until part_2 receives a on_participant_discovery holding information about part_1
while (true)
{
// Wait until some participant is found
std::unique_lock<std::mutex> lck(listener_mutex);
cv.wait(lck, [&]
{
return participant_found.load() == true;
});
// Reset participant found flag
participant_found.store(false);
// Prevent assertion on spurious discovery of a participant from elsewhere
if (part_1->guid() == listener.remote_participant_info->info.m_guid)
{
// Check that all three properties are present in the ParticipantProxyData, and that their value
// is that of the property in part_1 (the original property value)
for (auto physical_property_name : physical_property_names)
{
// Find property in ParticipantProxyData
auto received_property = std::find_if(
listener.remote_participant_info->info.m_properties.begin(),
listener.remote_participant_info->info.m_properties.end(),
[&](const ParameterProperty_t& property)
{
return property.first() == physical_property_name;
});
ASSERT_NE(received_property, listener.remote_participant_info->info.m_properties.end());
// Find property in first participant
auto part_1_property = PropertyPolicyHelper::find_property(
part_1->get_qos().properties(), physical_property_name);
ASSERT_NE(nullptr, part_1_property);
// Check that the property in the first participant has the same value as the one in
// the ParticipantProxyData representing the first participant in the second one
ASSERT_EQ(received_property->second(), *part_1_property);
}
break;
}
}
DomainParticipantFactory::get_instance()->delete_participant(part_1);
DomainParticipantFactory::get_instance()->delete_participant(part_2);
/* Negative case, i.e. the properties are in not the QoS and thus not in the ParticipantProxyData */
// Remove properties from QoS
qos.properties().properties().clear();
part_1 = DomainParticipantFactory::get_instance()->create_participant(domain_id, qos);
part_2 = DomainParticipantFactory::get_instance()->create_participant(domain_id, qos, &listener);
// Check that first participant does not have the properties
for (auto physical_property_name : physical_property_names)
{
// Find property in first participant
auto part_1_property = PropertyPolicyHelper::find_property(
part_1->get_qos().properties(), physical_property_name);
ASSERT_EQ(nullptr, part_1_property);
}
// This loops runs until part_2 receives a on_participant_discovery holding information about part_1
while (true)
{
// Wait until some participant is found
std::unique_lock<std::mutex> lck(listener_mutex);
cv.wait(lck, [&]
{
return participant_found.load() == true;
});
// Reset participant found flag
participant_found.store(false);
// Prevent assertion on spurious discovery of a participant from elsewhere
if (part_1->guid() == listener.remote_participant_info->info.m_guid)
{
// Check that none of the three properties are present in the ParticipantProxyData.
for (auto physical_property_name : physical_property_names)
{
// Look for property in ParticipantProxyData
auto received_property = std::find_if(
listener.remote_participant_info->info.m_properties.begin(),
listener.remote_participant_info->info.m_properties.end(),
[&](const ParameterProperty_t& property)
{
return property.first() == physical_property_name;
});
ASSERT_EQ(received_property, listener.remote_participant_info->info.m_properties.end());
}
break;
}
}
DomainParticipantFactory::get_instance()->delete_participant(part_1);
DomainParticipantFactory::get_instance()->delete_participant(part_2);
}
| 40.942105 | 120 | 0.704461 | [
"vector"
] |
eb8154cf5c2ee3f90eaeb4391230e9c053b2a3b7 | 12,104 | cpp | C++ | Source/WebCore/svg/SVGDocumentExtensions.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | null | null | null | Source/WebCore/svg/SVGDocumentExtensions.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | 9 | 2020-04-18T18:47:18.000Z | 2020-04-18T18:52:41.000Z | Source/WebCore/svg/SVGDocumentExtensions.cpp | ijsf/DeniseEmbeddableWebKit | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2006 Apple Inc. All rights reserved.
* Copyright (C) 2006 Nikolas Zimmermann <zimmermann@kde.org>
* Copyright (C) 2007 Rob Buis <buis@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "SVGDocumentExtensions.h"
#include "DOMWindow.h"
#include "Document.h"
#include "EventListener.h"
#include "Frame.h"
#include "FrameLoader.h"
#include "Page.h"
#include "SMILTimeContainer.h"
#include "SVGElement.h"
#include "SVGResourcesCache.h"
#include "SVGSMILElement.h"
#include "SVGSVGElement.h"
#include "ScriptableDocumentParser.h"
#include "ShadowRoot.h"
#include "XLinkNames.h"
#include <wtf/text/AtomicString.h>
namespace WebCore {
SVGDocumentExtensions::SVGDocumentExtensions(Document& document)
: m_document(document)
, m_resourcesCache(std::make_unique<SVGResourcesCache>())
, m_areAnimationsPaused(!document.page() || !document.page()->isVisible())
{
}
SVGDocumentExtensions::~SVGDocumentExtensions()
{
}
void SVGDocumentExtensions::addTimeContainer(SVGSVGElement* element)
{
m_timeContainers.add(element);
if (m_areAnimationsPaused)
element->pauseAnimations();
}
void SVGDocumentExtensions::removeTimeContainer(SVGSVGElement* element)
{
m_timeContainers.remove(element);
}
void SVGDocumentExtensions::addResource(const AtomicString& id, RenderSVGResourceContainer* resource)
{
ASSERT(resource);
if (id.isEmpty())
return;
// Replaces resource if already present, to handle potential id changes
m_resources.set(id, resource);
}
void SVGDocumentExtensions::removeResource(const AtomicString& id)
{
if (id.isEmpty())
return;
m_resources.remove(id);
}
RenderSVGResourceContainer* SVGDocumentExtensions::resourceById(const AtomicString& id) const
{
if (id.isEmpty())
return 0;
return m_resources.get(id);
}
void SVGDocumentExtensions::startAnimations()
{
// FIXME: Eventually every "Time Container" will need a way to latch on to some global timer
// starting animations for a document will do this "latching"
// FIXME: We hold a ref pointers to prevent a shadow tree from getting removed out from underneath us.
// In the future we should refactor the use-element to avoid this. See https://webkit.org/b/53704
Vector<RefPtr<SVGSVGElement>> timeContainers;
timeContainers.appendRange(m_timeContainers.begin(), m_timeContainers.end());
for (auto& element : timeContainers)
element->timeContainer().begin();
}
void SVGDocumentExtensions::pauseAnimations()
{
for (auto& container : m_timeContainers)
container->pauseAnimations();
m_areAnimationsPaused = true;
}
void SVGDocumentExtensions::unpauseAnimations()
{
for (auto& container : m_timeContainers)
container->unpauseAnimations();
m_areAnimationsPaused = false;
}
void SVGDocumentExtensions::dispatchSVGLoadEventToOutermostSVGElements()
{
Vector<RefPtr<SVGSVGElement>> timeContainers;
timeContainers.appendRange(m_timeContainers.begin(), m_timeContainers.end());
for (auto& container : timeContainers) {
if (!container->isOutermostSVGSVGElement())
continue;
container->sendSVGLoadEventIfPossible();
}
}
static void reportMessage(Document& document, MessageLevel level, const String& message)
{
if (document.frame())
document.addConsoleMessage(MessageSource::Rendering, level, message);
}
void SVGDocumentExtensions::reportWarning(const String& message)
{
reportMessage(m_document, MessageLevel::Warning, "Warning: " + message);
}
void SVGDocumentExtensions::reportError(const String& message)
{
reportMessage(m_document, MessageLevel::Error, "Error: " + message);
}
void SVGDocumentExtensions::addPendingResource(const AtomicString& id, Element* element)
{
ASSERT(element);
if (id.isEmpty())
return;
auto result = m_pendingResources.add(id, nullptr);
if (result.isNewEntry)
result.iterator->value = std::make_unique<PendingElements>();
result.iterator->value->add(element);
element->setHasPendingResources();
}
bool SVGDocumentExtensions::isIdOfPendingResource(const AtomicString& id) const
{
if (id.isEmpty())
return false;
return m_pendingResources.contains(id);
}
bool SVGDocumentExtensions::isElementWithPendingResources(Element* element) const
{
// This algorithm takes time proportional to the number of pending resources and need not.
// If performance becomes an issue we can keep a counted set of elements and answer the question efficiently.
ASSERT(element);
for (auto& elements : m_pendingResources.values()) {
ASSERT(elements);
if (elements->contains(element))
return true;
}
return false;
}
bool SVGDocumentExtensions::isPendingResource(Element* element, const AtomicString& id) const
{
ASSERT(element);
if (!isIdOfPendingResource(id))
return false;
return m_pendingResources.get(id)->contains(element);
}
void SVGDocumentExtensions::clearHasPendingResourcesIfPossible(Element* element)
{
if (!isElementWithPendingResources(element))
element->clearHasPendingResources();
}
void SVGDocumentExtensions::removeElementFromPendingResources(Element* element)
{
ASSERT(element);
// Remove the element from pending resources.
if (!m_pendingResources.isEmpty() && element->hasPendingResources()) {
Vector<AtomicString> toBeRemoved;
for (auto& resource : m_pendingResources) {
PendingElements* elements = resource.value.get();
ASSERT(elements);
ASSERT(!elements->isEmpty());
elements->remove(element);
if (elements->isEmpty())
toBeRemoved.append(resource.key);
}
clearHasPendingResourcesIfPossible(element);
// We use the removePendingResource function here because it deals with set lifetime correctly.
for (auto& resource : toBeRemoved)
removePendingResource(resource);
}
// Remove the element from pending resources that were scheduled for removal.
if (!m_pendingResourcesForRemoval.isEmpty()) {
Vector<AtomicString> toBeRemoved;
for (auto& resource : m_pendingResourcesForRemoval) {
PendingElements* elements = resource.value.get();
ASSERT(elements);
ASSERT(!elements->isEmpty());
elements->remove(element);
if (elements->isEmpty())
toBeRemoved.append(resource.key);
}
// We use the removePendingResourceForRemoval function here because it deals with set lifetime correctly.
for (auto& resource : toBeRemoved)
removePendingResourceForRemoval(resource);
}
}
std::unique_ptr<SVGDocumentExtensions::PendingElements> SVGDocumentExtensions::removePendingResource(const AtomicString& id)
{
ASSERT(m_pendingResources.contains(id));
return m_pendingResources.take(id);
}
std::unique_ptr<SVGDocumentExtensions::PendingElements> SVGDocumentExtensions::removePendingResourceForRemoval(const AtomicString& id)
{
ASSERT(m_pendingResourcesForRemoval.contains(id));
return m_pendingResourcesForRemoval.take(id);
}
void SVGDocumentExtensions::markPendingResourcesForRemoval(const AtomicString& id)
{
if (id.isEmpty())
return;
ASSERT(!m_pendingResourcesForRemoval.contains(id));
std::unique_ptr<PendingElements> existing = m_pendingResources.take(id);
if (existing && !existing->isEmpty())
m_pendingResourcesForRemoval.add(id, WTFMove(existing));
}
Element* SVGDocumentExtensions::removeElementFromPendingResourcesForRemovalMap(const AtomicString& id)
{
if (id.isEmpty())
return 0;
PendingElements* resourceSet = m_pendingResourcesForRemoval.get(id);
if (!resourceSet || resourceSet->isEmpty())
return 0;
auto firstElement = resourceSet->begin();
Element* element = *firstElement;
resourceSet->remove(firstElement);
if (resourceSet->isEmpty())
removePendingResourceForRemoval(id);
return element;
}
HashSet<SVGElement*>* SVGDocumentExtensions::setOfElementsReferencingTarget(SVGElement* referencedElement) const
{
ASSERT(referencedElement);
const auto it = m_elementDependencies.find(referencedElement);
if (it == m_elementDependencies.end())
return 0;
return it->value.get();
}
void SVGDocumentExtensions::addElementReferencingTarget(SVGElement* referencingElement, SVGElement* referencedElement)
{
ASSERT(referencingElement);
ASSERT(referencedElement);
if (HashSet<SVGElement*>* elements = m_elementDependencies.get(referencedElement)) {
elements->add(referencingElement);
return;
}
auto elements = std::make_unique<HashSet<SVGElement*>>();
elements->add(referencingElement);
m_elementDependencies.set(referencedElement, WTFMove(elements));
}
void SVGDocumentExtensions::removeAllTargetReferencesForElement(SVGElement* referencingElement)
{
Vector<SVGElement*> toBeRemoved;
for (auto& dependency : m_elementDependencies) {
SVGElement* referencedElement = dependency.key;
HashSet<SVGElement*>& referencingElements = *dependency.value;
referencingElements.remove(referencingElement);
if (referencingElements.isEmpty())
toBeRemoved.append(referencedElement);
}
for (auto& element : toBeRemoved)
m_elementDependencies.remove(element);
}
void SVGDocumentExtensions::rebuildElements()
{
Vector<SVGElement*> shadowRebuildElements = WTFMove(m_rebuildElements);
for (auto* element : shadowRebuildElements)
element->svgAttributeChanged(XLinkNames::hrefAttr);
}
void SVGDocumentExtensions::clearTargetDependencies(SVGElement& referencedElement)
{
auto it = m_elementDependencies.find(&referencedElement);
if (it == m_elementDependencies.end())
return;
ASSERT(it->key == &referencedElement);
HashSet<SVGElement*>* referencingElements = it->value.get();
for (auto* element : *referencingElements) {
m_rebuildElements.append(element);
element->callClearTarget();
}
}
void SVGDocumentExtensions::rebuildAllElementReferencesForTarget(SVGElement& referencedElement)
{
auto it = m_elementDependencies.find(&referencedElement);
if (it == m_elementDependencies.end())
return;
ASSERT(it->key == &referencedElement);
HashSet<SVGElement*>* referencingElements = it->value.get();
Vector<SVGElement*> elementsToRebuild;
elementsToRebuild.reserveInitialCapacity(referencingElements->size());
for (auto* element : *referencingElements)
elementsToRebuild.uncheckedAppend(element);
for (auto* element : elementsToRebuild)
element->svgAttributeChanged(XLinkNames::hrefAttr);
}
void SVGDocumentExtensions::removeAllElementReferencesForTarget(SVGElement* referencedElement)
{
m_elementDependencies.remove(referencedElement);
m_rebuildElements.removeFirst(referencedElement);
}
#if ENABLE(SVG_FONTS)
void SVGDocumentExtensions::registerSVGFontFaceElement(SVGFontFaceElement* element)
{
m_svgFontFaceElements.add(element);
}
void SVGDocumentExtensions::unregisterSVGFontFaceElement(SVGFontFaceElement* element)
{
ASSERT(m_svgFontFaceElements.contains(element));
m_svgFontFaceElements.remove(element);
}
#endif
}
| 31.520833 | 134 | 0.729594 | [
"vector"
] |
eb879308cf8253c60970b0243de18c02ece49836 | 49,458 | cxx | C++ | main/sfx2/source/toolbox/tbxitem.cxx | jimjag/openoffice | 74746a22d8cc22b031b00fcd106f4496bf936c77 | [
"Apache-2.0"
] | 1 | 2019-12-27T19:25:34.000Z | 2019-12-27T19:25:34.000Z | main/sfx2/source/toolbox/tbxitem.cxx | ackza/openoffice | d49dfe9c625750e261c7ed8d6ccac8d361bf3418 | [
"Apache-2.0"
] | 1 | 2019-11-25T03:08:58.000Z | 2019-11-25T03:08:58.000Z | main/sfx2/source/toolbox/tbxitem.cxx | ackza/openoffice | d49dfe9c625750e261c7ed8d6ccac8d361bf3418 | [
"Apache-2.0"
] | 6 | 2019-11-19T00:28:25.000Z | 2019-11-22T06:48:49.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#ifdef SOLARIS
// HACK: prevent conflict between STLPORT and Workshop headers on Solaris 8
#include <ctime>
#endif
#include <string> // prevent conflict with STL includes
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/awt/XWindow.hpp>
#include <com/sun/star/util/URL.hpp>
#include <com/sun/star/util/XURLTransformer.hpp>
#include <com/sun/star/frame/XController.hpp>
#include <com/sun/star/lang/XUnoTunnel.hpp>
#include <com/sun/star/document/MacroExecMode.hpp>
#include <com/sun/star/document/UpdateDocMode.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/frame/XLayoutManager.hpp>
#include <com/sun/star/frame/status/ItemStatus.hpp>
#include <com/sun/star/frame/status/ItemState.hpp>
#include <com/sun/star/ui/XUIElementFactory.hpp>
#include <com/sun/star/frame/XModuleManager.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/ui/XUIFunctionListener.hpp>
#include <com/sun/star/frame/status/Visibility.hpp>
#include <com/sun/star/document/CorruptedFilterConfigurationException.hpp>
#include <svl/eitem.hxx>
#include <svl/stritem.hxx>
#include <svl/intitem.hxx>
#include <svl/imageitm.hxx>
#include <svl/visitem.hxx>
#include <svl/urlbmk.hxx>
#include <vcl/toolbox.hxx>
#include <unotools/moduleoptions.hxx>
#include <svtools/imagemgr.hxx>
#include <comphelper/processfactory.hxx>
#include <framework/addonmenu.hxx>
#include <framework/addonsoptions.hxx>
#include <framework/menuconfiguration.hxx>
#include <framework/sfxhelperfunctions.hxx>
#include <vcl/taskpanelist.hxx>
#ifndef _TOOLKIT_UNOHLP_HXX
#include <toolkit/helper/vclunohelper.hxx>
#endif
#include <svtools/menuoptions.hxx>
#include <svtools/miscopt.hxx>
#ifndef GCC
#endif
#include <sfx2/tbxctrl.hxx>
#include <sfx2/mnumgr.hxx>
#include <sfx2/dispatch.hxx>
#include "fltfnc.hxx"
#include <sfx2/msg.hxx>
#include <sfx2/msgpool.hxx>
#include "statcach.hxx"
#include <sfx2/viewfrm.hxx>
#include "arrdecl.hxx"
#include "sfxtypes.hxx"
#include <sfx2/genlink.hxx>
#include "sfx2/sfxresid.hxx"
#include <sfx2/sfx.hrc>
#include <sfx2/module.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/docfac.hxx>
#include "referers.hxx"
#include <sfx2/frmhtmlw.hxx>
#include <sfx2/app.hxx>
#include <sfx2/unoctitm.hxx>
#include "helpid.hrc"
#include "workwin.hxx"
#include "sfx2/imgmgr.hxx"
#include "virtmenu.hxx"
#include <sfx2/viewfrm.hxx>
#include <sfx2/module.hxx>
#include "sfx2/imagemgr.hxx"
#include <comphelper/uieventslogger.hxx>
#include <com/sun/star/frame/XModuleManager.hpp>
//using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::frame::status;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::ui;
//====================================================================
SFX_IMPL_TOOLBOX_CONTROL_ARG(SfxToolBoxControl, SfxStringItem, sal_True);
static Window* GetTopMostParentSystemWindow( Window* pWindow )
{
OSL_ASSERT( pWindow );
if ( pWindow )
{
// ->manually search topmost system window
// required because their might be another system window between this and the top window
pWindow = pWindow->GetParent();
SystemWindow* pTopMostSysWin = NULL;
while ( pWindow )
{
if ( pWindow->IsSystemWindow() )
pTopMostSysWin = (SystemWindow*)pWindow;
pWindow = pWindow->GetParent();
}
pWindow = pTopMostSysWin;
OSL_ASSERT( pWindow );
return pWindow;
}
return NULL;
}
svt::ToolboxController* SAL_CALL SfxToolBoxControllerFactory( const Reference< XFrame >& rFrame, ToolBox* pToolbox, unsigned short nID, const ::rtl::OUString& aCommandURL )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
URL aTargetURL;
aTargetURL.Complete = aCommandURL;
Reference < XURLTransformer > xTrans( ::comphelper::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer" )), UNO_QUERY );
xTrans->parseStrict( aTargetURL );
if ( aTargetURL.Arguments.getLength() )
return NULL;
SfxObjectShell* pObjShell = NULL;
Reference < XController > xController;
Reference < XModel > xModel;
if ( rFrame.is() )
{
xController = rFrame->getController();
if ( xController.is() )
xModel = xController->getModel();
}
if ( xModel.is() )
{
// Get tunnel from model to retrieve the SfxObjectShell pointer from it
::com::sun::star::uno::Reference < ::com::sun::star::lang::XUnoTunnel > xObj( xModel, UNO_QUERY );
if ( xObj.is() )
{
::com::sun::star::uno::Sequence < sal_Int8 > aSeq = SvGlobalName( SFX_GLOBAL_CLASSID ).GetByteSequence();
sal_Int64 nHandle = xObj->getSomething( aSeq );
if ( nHandle )
pObjShell = reinterpret_cast< SfxObjectShell* >( sal::static_int_cast< sal_IntPtr >( nHandle ));
}
}
SfxModule* pModule = pObjShell ? pObjShell->GetModule() : NULL;
SfxSlotPool* pSlotPool = 0;
if ( pModule )
pSlotPool = pModule->GetSlotPool();
else
pSlotPool = &(SfxSlotPool::GetSlotPool( NULL ));
const SfxSlot* pSlot = pSlotPool->GetUnoSlot( aTargetURL.Path );
if ( pSlot )
{
sal_uInt16 nSlotId = pSlot->GetSlotId();
if ( nSlotId > 0 )
return SfxToolBoxControl::CreateControl( nSlotId, nID, pToolbox, pModule );
}
return NULL;
}
struct SfxToolBoxControl_Impl
{
ToolBox* pBox;
sal_Bool bShowString;
sal_uInt16 nSelectModifier;
SfxTbxCtrlFactory* pFact;
sal_uInt16 nTbxId;
sal_uInt16 nSlotId;
SfxPopupWindow* mpFloatingWindow;
SfxPopupWindow* mpPopupWindow;
Reference< XUIElement > mxUIElement;
DECL_LINK( WindowEventListener, VclSimpleEvent* );
};
IMPL_LINK( SfxToolBoxControl_Impl, WindowEventListener, VclSimpleEvent*, pEvent )
{
if ( pEvent &&
pEvent->ISA( VclWindowEvent ) &&
(( pEvent->GetId() == VCLEVENT_WINDOW_MOVE ) ||
( pEvent->GetId() == VCLEVENT_WINDOW_ACTIVATE )))
{
Window* pWindow( ((VclWindowEvent*)pEvent)->GetWindow() );
if (( pWindow == mpFloatingWindow ) &&
( mpPopupWindow != 0 ))
{
delete mpPopupWindow;
mpPopupWindow = 0;
}
}
return 1;
}
//--------------------------------------------------------------------
SfxToolBoxControl::SfxToolBoxControl(
sal_uInt16 nSlotID,
sal_uInt16 nID,
ToolBox& rBox,
sal_Bool bShowStringItems )
: svt::ToolboxController()
{
pImpl = new SfxToolBoxControl_Impl;
pImpl->pBox = &rBox;
pImpl->bShowString = bShowStringItems;
pImpl->nSelectModifier = 0;
pImpl->pFact = 0;
pImpl->nTbxId = nID;
pImpl->nSlotId = nSlotID;
pImpl->mpFloatingWindow = 0;
pImpl->mpPopupWindow = 0;
}
//--------------------------------------------------------------------
SfxToolBoxControl::~SfxToolBoxControl()
{
if ( pImpl->mxUIElement.is() )
{
Reference< XComponent > xComponent( pImpl->mxUIElement, UNO_QUERY );
xComponent->dispose();
}
pImpl->mxUIElement = 0;
delete pImpl;
}
//--------------------------------------------------------------------
ToolBox& SfxToolBoxControl::GetToolBox() const
{
return *pImpl->pBox;
}
unsigned short SfxToolBoxControl::GetId() const
{
return pImpl->nTbxId;
}
unsigned short SfxToolBoxControl::GetSlotId() const
{
return pImpl->nSlotId;
}
//--------------------------------------------------------------------
void SAL_CALL SfxToolBoxControl::dispose() throw (::com::sun::star::uno::RuntimeException)
{
if ( m_bDisposed )
return;
svt::ToolboxController::dispose();
// Remove and destroy our item window at our toolbox
::vos::OGuard aGuard( Application::GetSolarMutex() );
Window* pWindow = pImpl->pBox->GetItemWindow( pImpl->nTbxId );
pImpl->pBox->SetItemWindow( pImpl->nTbxId, 0 );
delete pWindow;
// Dispose an open sub toolbar. It's possible that we have an open
// sub toolbar while we get disposed. Therefore we have to dispose
// it now! Not doing so would result in a crash. The sub toolbar
// gets destroyed asynchronously and would access a non-existing
// parent toolbar! See #126569#
if ( pImpl->mxUIElement.is() )
{
Reference< XComponent > xComponent( pImpl->mxUIElement, UNO_QUERY );
xComponent->dispose();
}
pImpl->mxUIElement = 0;
// Delete my popup windows
delete pImpl->mpFloatingWindow;
delete pImpl->mpPopupWindow;
pImpl->mpFloatingWindow = 0;
pImpl->mpPopupWindow = 0;
}
//--------------------------------------------------------------------
void SfxToolBoxControl::RegisterToolBoxControl( SfxModule* pMod, SfxTbxCtrlFactory* pFact)
{
SFX_APP()->RegisterToolBoxControl_Impl( pMod, pFact );
}
SfxToolBoxControl* SfxToolBoxControl::CreateControl( sal_uInt16 nSlotId, sal_uInt16 nTbxId, ToolBox *pBox, SfxModule* pMod )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
SfxToolBoxControl *pCtrl;
SfxApplication *pApp = SFX_APP();
SfxSlotPool *pSlotPool;
if ( pMod )
pSlotPool = pMod->GetSlotPool();
else
pSlotPool = &SfxSlotPool::GetSlotPool();
TypeId aSlotType = pSlotPool->GetSlotType( nSlotId );
if ( aSlotType )
{
if ( pMod )
{
SfxTbxCtrlFactArr_Impl *pFactories = pMod->GetTbxCtrlFactories_Impl();
if ( pFactories )
{
SfxTbxCtrlFactArr_Impl &rFactories = *pFactories;
sal_uInt16 nFactory;
const sal_uInt16 nCount = rFactories.Count();
// search for a factory with the given slot id
for( nFactory = 0; nFactory < nCount; ++nFactory )
if( (rFactories[nFactory]->nTypeId == aSlotType) && (rFactories[nFactory]->nSlotId == nSlotId) )
break;
if( nFactory == nCount )
{
// if no factory exists for the given slot id, see if we
// have a generic factory with the correct slot type and slot id == 0
for ( nFactory = 0; nFactory < nCount; ++nFactory )
if( (rFactories[nFactory]->nTypeId == aSlotType) && (rFactories[nFactory]->nSlotId == 0) )
break;
}
if( nFactory < nCount )
{
pCtrl = rFactories[nFactory]->pCtor( nSlotId, nTbxId, *pBox );
pCtrl->pImpl->pFact = rFactories[nFactory];
return pCtrl;
}
}
}
SfxTbxCtrlFactArr_Impl &rFactories = pApp->GetTbxCtrlFactories_Impl();
sal_uInt16 nFactory;
const sal_uInt16 nCount = rFactories.Count();
for( nFactory = 0; nFactory < nCount; ++nFactory )
if( (rFactories[nFactory]->nTypeId == aSlotType) && (rFactories[nFactory]->nSlotId == nSlotId) )
break;
if( nFactory == nCount )
{
// if no factory exists for the given slot id, see if we
// have a generic factory with the correct slot type and slot id == 0
for( nFactory = 0; nFactory < nCount; ++nFactory )
if( (rFactories[nFactory]->nTypeId == aSlotType) && (rFactories[nFactory]->nSlotId == 0) )
break;
}
if( nFactory < nCount )
{
pCtrl = rFactories[nFactory]->pCtor( nSlotId, nTbxId, *pBox );
pCtrl->pImpl->pFact = rFactories[nFactory];
return pCtrl;
}
}
return NULL;
}
SfxItemState SfxToolBoxControl::GetItemState(
const SfxPoolItem* pState )
/* [Beschreibung]
Statische Methode zum Ermitteln des Status des SfxPoolItem-Pointers,
in der Methode <SfxControllerItem::StateChanged(const SfxPoolItem*)>
zu verwenden.
[R"uckgabewert]
SfxItemState SFX_ITEM_UNKNOWN
Enabled, aber keine weitere Statusinformation
verf"ugbar. Typisch f"ur <Slot>s, die allenfalls
zeitweise disabled sind, aber ihre Darstellung sonst
nicht "andern.
SFX_ITEM_DISABLED
Disabled und keine weiter Statusinformation
verf"ugbar. Alle anderen ggf. angezeigten Werte sollten
auf den Default zur"uckgesetzt werden.
SFX_ITEM_DONTCARE
Enabled aber es waren nur uneindeutige Werte
verf"ugbar (also keine, die abgefragt werden k"onnen).
SFX_ITEM_AVAILABLE
Enabled und mit verf"ugbarem Wert, der von 'pState'
erfragbar ist. Der Typ ist dabei im gesamten
Programm eindeutig und durch den Slot festgelegt.
*/
{
return !pState
? SFX_ITEM_DISABLED
: IsInvalidItem(pState)
? SFX_ITEM_DONTCARE
: pState->ISA(SfxVoidItem) && !pState->Which()
? SFX_ITEM_UNKNOWN
: SFX_ITEM_AVAILABLE;
}
void SfxToolBoxControl::Dispatch(
const Reference< XDispatchProvider >& rProvider,
const rtl::OUString& rCommand,
Sequence< ::PropertyValue >& aArgs )
{
if ( rProvider.is() )
{
::com::sun::star::util::URL aTargetURL;
aTargetURL.Complete = rCommand;
Reference < XURLTransformer > xTrans( ::comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer" )),
UNO_QUERY );
xTrans->parseStrict( aTargetURL );
Reference < XDispatch > xDispatch = rProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 );
if ( xDispatch.is() )
xDispatch->dispatch( aTargetURL, aArgs );
}
}
void SfxToolBoxControl::Dispatch( const ::rtl::OUString& aCommand, ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs )
{
Reference < XController > xController;
::vos::OGuard aGuard( Application::GetSolarMutex() );
if ( getFrameInterface().is() )
xController = getFrameInterface()->getController();
Reference < XDispatchProvider > xProvider( xController, UNO_QUERY );
if ( xProvider.is() )
{
::com::sun::star::util::URL aTargetURL;
aTargetURL.Complete = aCommand;
getURLTransformer()->parseStrict( aTargetURL );
Reference < XDispatch > xDispatch = xProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 );
if ( xDispatch.is() )
{
if(::comphelper::UiEventsLogger::isEnabled()) //#i88653#
{
::rtl::OUString sAppName;
try
{
static ::rtl::OUString our_aModuleManagerName = ::rtl::OUString::createFromAscii("com.sun.star.frame.ModuleManager");
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceManager =
::comphelper::getProcessServiceFactory();
::com::sun::star::uno::Reference< ::com::sun::star::frame::XModuleManager > xModuleManager(
xServiceManager->createInstance(our_aModuleManagerName)
, ::com::sun::star::uno::UNO_QUERY_THROW);
::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame > xFrame(
getFrameInterface(), UNO_QUERY_THROW);
sAppName = xModuleManager->identify(xFrame);
} catch(::com::sun::star::uno::Exception&) {}
Sequence<PropertyValue> source;
::comphelper::UiEventsLogger::appendDispatchOrigin(source, sAppName, ::rtl::OUString::createFromAscii("SfxToolBoxControl"));
::comphelper::UiEventsLogger::logDispatch(aTargetURL, source);
}
xDispatch->dispatch( aTargetURL, aArgs );
}
}
}
// XInterface
Any SAL_CALL SfxToolBoxControl::queryInterface( const Type & rType )
throw(::com::sun::star::uno::RuntimeException)
{
::com::sun::star::uno::Any aRet = ::cppu::queryInterface( rType,
SAL_STATIC_CAST( ::com::sun::star::awt::XDockableWindowListener*, this ),
SAL_STATIC_CAST( ::com::sun::star::frame::XSubToolbarController*, this ));
return (aRet.hasValue() ? aRet : svt::ToolboxController::queryInterface( rType ));
}
void SAL_CALL SfxToolBoxControl::acquire() throw()
{
OWeakObject::acquire();
}
void SAL_CALL SfxToolBoxControl::release() throw()
{
OWeakObject::release();
}
void SAL_CALL SfxToolBoxControl::disposing( const ::com::sun::star::lang::EventObject& aEvent )
throw( ::com::sun::star::uno::RuntimeException )
{
svt::ToolboxController::disposing( aEvent );
}
// XStatusListener
void SAL_CALL SfxToolBoxControl::statusChanged( const FeatureStateEvent& rEvent )
throw ( ::com::sun::star::uno::RuntimeException )
{
SfxViewFrame* pViewFrame = NULL;
Reference < XController > xController;
::vos::OGuard aGuard( Application::GetSolarMutex() );
if ( getFrameInterface().is() )
xController = getFrameInterface()->getController();
Reference < XDispatchProvider > xProvider( xController, UNO_QUERY );
if ( xProvider.is() )
{
Reference < XDispatch > xDisp = xProvider->queryDispatch( rEvent.FeatureURL, ::rtl::OUString(), 0 );
if ( xDisp.is() )
{
Reference< XUnoTunnel > xTunnel( xDisp, UNO_QUERY );
SfxOfficeDispatch* pDisp = NULL;
if ( xTunnel.is() )
{
sal_Int64 nImplementation = xTunnel->getSomething(SfxOfficeDispatch::impl_getStaticIdentifier());
pDisp = reinterpret_cast< SfxOfficeDispatch* >( sal::static_int_cast< sal_IntPtr >( nImplementation ));
}
if ( pDisp )
pViewFrame = pDisp->GetDispatcher_Impl()->GetFrame();
}
}
sal_uInt16 nSlotId = 0;
SfxSlotPool& rPool = SfxSlotPool::GetSlotPool( pViewFrame );
const SfxSlot* pSlot = rPool.GetUnoSlot( rEvent.FeatureURL.Path );
if ( pSlot )
nSlotId = pSlot->GetSlotId();
else if ( m_aCommandURL == rEvent.FeatureURL.Path )
nSlotId = GetSlotId();
if ( nSlotId > 0 )
{
if ( rEvent.Requery )
svt::ToolboxController::statusChanged( rEvent );
else
{
SfxItemState eState = SFX_ITEM_DISABLED;
SfxPoolItem* pItem = NULL;
if ( rEvent.IsEnabled )
{
eState = SFX_ITEM_AVAILABLE;
::com::sun::star::uno::Type pType = rEvent.State.getValueType();
if ( pType == ::getVoidCppuType() )
{
pItem = new SfxVoidItem( nSlotId );
eState = SFX_ITEM_UNKNOWN;
}
else if ( pType == ::getBooleanCppuType() )
{
sal_Bool bTemp = false;
rEvent.State >>= bTemp ;
pItem = new SfxBoolItem( nSlotId, bTemp );
}
else if ( pType == ::getCppuType((const sal_uInt16*)0) )
{
sal_uInt16 nTemp = 0;
rEvent.State >>= nTemp ;
pItem = new SfxUInt16Item( nSlotId, nTemp );
}
else if ( pType == ::getCppuType((const sal_uInt32*)0) )
{
sal_uInt32 nTemp = 0;
rEvent.State >>= nTemp ;
pItem = new SfxUInt32Item( nSlotId, nTemp );
}
else if ( pType == ::getCppuType((const ::rtl::OUString*)0) )
{
::rtl::OUString sTemp ;
rEvent.State >>= sTemp ;
pItem = new SfxStringItem( nSlotId, sTemp );
}
else if ( pType == ::getCppuType((const ::com::sun::star::frame::status::ItemStatus*)0) )
{
ItemStatus aItemStatus;
rEvent.State >>= aItemStatus;
eState = aItemStatus.State;
pItem = new SfxVoidItem( nSlotId );
}
else if ( pType == ::getCppuType((const ::com::sun::star::frame::status::Visibility*)0) )
{
Visibility aVisibilityStatus;
rEvent.State >>= aVisibilityStatus;
pItem = new SfxVisibilityItem( nSlotId, aVisibilityStatus.bVisible );
}
else
{
if ( pSlot )
pItem = pSlot->GetType()->CreateItem();
if ( pItem )
{
pItem->SetWhich( nSlotId );
pItem->PutValue( rEvent.State );
}
else
pItem = new SfxVoidItem( nSlotId );
}
}
StateChanged( nSlotId, eState, pItem );
delete pItem;
}
}
}
// XSubToolbarController
::sal_Bool SAL_CALL SfxToolBoxControl::opensSubToolbar() throw (::com::sun::star::uno::RuntimeException)
{
return sal_False;
}
::rtl::OUString SAL_CALL SfxToolBoxControl::getSubToolbarName() throw (::com::sun::star::uno::RuntimeException)
{
return rtl::OUString();
}
void SAL_CALL SfxToolBoxControl::functionSelected( const ::rtl::OUString& /*aCommand*/ ) throw (::com::sun::star::uno::RuntimeException)
{
// must be implemented by sub-class
}
void SAL_CALL SfxToolBoxControl::updateImage() throw (::com::sun::star::uno::RuntimeException)
{
// must be implemented by sub-class
}
// XToolbarController
void SAL_CALL SfxToolBoxControl::execute( sal_Int16 KeyModifier ) throw (::com::sun::star::uno::RuntimeException)
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
Select( (sal_uInt16)KeyModifier );
}
void SAL_CALL SfxToolBoxControl::click() throw (::com::sun::star::uno::RuntimeException)
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
Click();
}
void SAL_CALL SfxToolBoxControl::doubleClick() throw (::com::sun::star::uno::RuntimeException)
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
DoubleClick();
}
Reference< ::com::sun::star::awt::XWindow > SAL_CALL SfxToolBoxControl::createPopupWindow() throw (::com::sun::star::uno::RuntimeException)
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
Window* pWindow = CreatePopupWindow();
if ( pWindow )
return VCLUnoHelper::GetInterface( pWindow );
else
return Reference< ::com::sun::star::awt::XWindow >();
}
Reference< ::com::sun::star::awt::XWindow > SAL_CALL SfxToolBoxControl::createItemWindow( const Reference< ::com::sun::star::awt::XWindow >& rParent ) throw (::com::sun::star::uno::RuntimeException)
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
return VCLUnoHelper::GetInterface( CreateItemWindow( VCLUnoHelper::GetWindow( rParent )));
}
// XDockableWindowListener
void SAL_CALL SfxToolBoxControl::startDocking( const ::com::sun::star::awt::DockingEvent& )
throw (::com::sun::star::uno::RuntimeException)
{
}
::com::sun::star::awt::DockingData SAL_CALL SfxToolBoxControl::docking( const ::com::sun::star::awt::DockingEvent& )
throw (::com::sun::star::uno::RuntimeException)
{
return ::com::sun::star::awt::DockingData();
}
void SAL_CALL SfxToolBoxControl::endDocking( const ::com::sun::star::awt::EndDockingEvent& )
throw (::com::sun::star::uno::RuntimeException)
{
}
sal_Bool SAL_CALL SfxToolBoxControl::prepareToggleFloatingMode( const ::com::sun::star::lang::EventObject& )
throw (::com::sun::star::uno::RuntimeException)
{
return sal_False;
}
void SAL_CALL SfxToolBoxControl::toggleFloatingMode( const ::com::sun::star::lang::EventObject& )
throw (::com::sun::star::uno::RuntimeException)
{
}
void SAL_CALL SfxToolBoxControl::closed( const ::com::sun::star::lang::EventObject& )
throw (::com::sun::star::uno::RuntimeException)
{
}
void SAL_CALL SfxToolBoxControl::endPopupMode( const ::com::sun::star::awt::EndPopupModeEvent& aEvent )
throw (::com::sun::star::uno::RuntimeException)
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
::rtl::OUString aSubToolBarResName;
if ( pImpl->mxUIElement.is() )
{
Reference< XPropertySet > xPropSet( pImpl->mxUIElement, UNO_QUERY );
if ( xPropSet.is() )
{
try
{
xPropSet->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ResourceURL" ))) >>= aSubToolBarResName;
}
catch ( com::sun::star::beans::UnknownPropertyException& )
{
}
catch ( com::sun::star::lang::WrappedTargetException& )
{
}
}
Reference< XComponent > xComponent( pImpl->mxUIElement, UNO_QUERY );
xComponent->dispose();
}
pImpl->mxUIElement = 0;
// if the toolbar was teared-off recreate it and place it at the given position
if( aEvent.bTearoff )
{
Reference< XUIElement > xUIElement;
Reference< XLayoutManager > xLayoutManager = getLayoutManager();
if ( !xLayoutManager.is() )
return;
xLayoutManager->createElement( aSubToolBarResName );
xUIElement = xLayoutManager->getElement( aSubToolBarResName );
if ( xUIElement.is() )
{
Reference< ::com::sun::star::awt::XWindow > xParent = getFrameInterface()->getContainerWindow();
Reference< ::com::sun::star::awt::XWindow > xSubToolBar( xUIElement->getRealInterface(), UNO_QUERY );
Reference< ::com::sun::star::beans::XPropertySet > xProp( xUIElement, UNO_QUERY );
if ( xSubToolBar.is() && xProp.is() )
{
rtl::OUString aPersistentString( RTL_CONSTASCII_USTRINGPARAM( "Persistent" ));
try
{
Window* pTbxWindow = VCLUnoHelper::GetWindow( xSubToolBar );
ToolBox* pToolBar( 0 );
if ( pTbxWindow && pTbxWindow->GetType() == WINDOW_TOOLBOX )
{
pToolBar = (ToolBox *)pTbxWindow;
Any a;
a = xProp->getPropertyValue( aPersistentString );
xProp->setPropertyValue( aPersistentString, makeAny( sal_False ));
xLayoutManager->hideElement( aSubToolBarResName );
xLayoutManager->floatWindow( aSubToolBarResName );
xLayoutManager->setElementPos( aSubToolBarResName, aEvent.FloatingPosition );
xLayoutManager->showElement( aSubToolBarResName );
xProp->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Persistent" )), a );
}
}
catch ( ::com::sun::star::uno::RuntimeException& )
{
throw;
}
catch ( ::com::sun::star::uno::Exception& )
{
}
}
}
}
}
::Size SfxToolBoxControl::getPersistentFloatingSize( const Reference< XFrame >& /*xFrame*/, const ::rtl::OUString& /*rSubToolBarResName*/ )
{
::Size aToolboxSize;
return aToolboxSize;
}
void SfxToolBoxControl::createAndPositionSubToolBar( const ::rtl::OUString& rSubToolBarResName )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
if ( pImpl->pBox )
{
static WeakReference< XUIElementFactory > xWeakUIElementFactory;
sal_uInt16 nItemId = pImpl->pBox->GetDownItemId();
if ( !nItemId )
return;
// create element with factory
Reference< XMultiServiceFactory > xServiceManager = getServiceManager();
Reference< XFrame > xFrame = getFrameInterface();
Reference< XUIElement > xUIElement;
Reference< XUIElementFactory > xUIEementFactory;
xUIEementFactory = xWeakUIElementFactory;
if ( !xUIEementFactory.is() )
{
xUIEementFactory = Reference< XUIElementFactory >(
xServiceManager->createInstance(
rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.ui.UIElementFactoryManager" ))),
UNO_QUERY );
xWeakUIElementFactory = xUIEementFactory;
}
Sequence< PropertyValue > aPropSeq( 3 );
aPropSeq[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Frame" ));
aPropSeq[0].Value <<= xFrame;
aPropSeq[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Persistent" ));
aPropSeq[1].Value <<= sal_False;
aPropSeq[2].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PopupMode" ));
aPropSeq[2].Value <<= sal_True;
try
{
xUIElement = xUIEementFactory->createUIElement( rSubToolBarResName, aPropSeq );
}
catch ( ::com::sun::star::container::NoSuchElementException& )
{
}
catch ( IllegalArgumentException& )
{
}
if ( xUIElement.is() )
{
Reference< ::com::sun::star::awt::XWindow > xParent = getFrameInterface()->getContainerWindow();
Reference< ::com::sun::star::awt::XWindow > xSubToolBar( xUIElement->getRealInterface(), UNO_QUERY );
if ( xSubToolBar.is() )
{
Reference< ::com::sun::star::awt::XDockableWindow > xDockWindow( xSubToolBar, UNO_QUERY );
xDockWindow->addDockableWindowListener( Reference< ::com::sun::star::awt::XDockableWindowListener >(
static_cast< OWeakObject * >( this ), UNO_QUERY ));
xDockWindow->enableDocking( sal_True );
// keep refererence to UIElement to avoid its destruction
if ( pImpl->mxUIElement.is() )
{
Reference< XComponent > xComponent( pImpl->mxUIElement, UNO_QUERY );
xComponent->dispose();
}
pImpl->mxUIElement = xUIElement;
Window* pParentTbxWindow( pImpl->pBox );
Window* pTbxWindow = VCLUnoHelper::GetWindow( xSubToolBar );
ToolBox* pToolBar( 0 );
if ( pTbxWindow && pTbxWindow->GetType() == WINDOW_TOOLBOX )
pToolBar = (ToolBox *)pTbxWindow;
if ( pToolBar )
{
pToolBar->SetParent( pParentTbxWindow );
::Size aSize = getPersistentFloatingSize( xFrame, rSubToolBarResName );
if ( aSize.Width() == 0 || aSize.Height() == 0 )
{
// calc and set size for popup mode
aSize = pToolBar->CalcPopupWindowSizePixel();
}
pToolBar->SetSizePixel( aSize );
// open subtoolbox in popup mode
Window::GetDockingManager()->StartPopupMode( pImpl->pBox, pToolBar );
}
}
}
}
}
//--------------------------------------------------------------------
void SfxToolBoxControl::SetPopupWindow( SfxPopupWindow* pWindow )
{
pImpl->mpPopupWindow = pWindow;
pImpl->mpPopupWindow->SetPopupModeEndHdl( LINK( this, SfxToolBoxControl, PopupModeEndHdl ));
pImpl->mpPopupWindow->SetDeleteLink_Impl( LINK( this, SfxToolBoxControl, ClosePopupWindow ));
}
//--------------------------------------------------------------------
IMPL_LINK( SfxToolBoxControl, PopupModeEndHdl, void *, EMPTYARG )
{
if ( pImpl->mpPopupWindow->IsVisible() )
{
// Replace floating window with popup window and destroy
// floating window instance.
delete pImpl->mpFloatingWindow;
pImpl->mpFloatingWindow = pImpl->mpPopupWindow;
pImpl->mpPopupWindow = 0;
// We also need to know when the user tries to use the
// floating window.
pImpl->mpFloatingWindow->AddEventListener( LINK( pImpl, SfxToolBoxControl_Impl, WindowEventListener ));
}
else
{
// Popup window has been closed by the user. No replacement, instance
// will destroy itself.
pImpl->mpPopupWindow = 0;
}
return 1;
}
//--------------------------------------------------------------------
IMPL_LINK( SfxToolBoxControl, ClosePopupWindow, SfxPopupWindow *, pWindow )
{
if ( pWindow == pImpl->mpFloatingWindow )
pImpl->mpFloatingWindow = 0;
else
pImpl->mpPopupWindow = 0;
return 1;
}
//--------------------------------------------------------------------
void SfxToolBoxControl::StateChanged
(
sal_uInt16 nId,
SfxItemState eState,
const SfxPoolItem* pState
)
{
DBG_MEMTEST();
DBG_ASSERT( pImpl->pBox != 0, "setting state to dangling ToolBox" );
if ( GetId() >= SID_OBJECTMENU0 && GetId() <= SID_OBJECTMENU_LAST )
return;
// enabled/disabled-Flag pauschal korrigieren
pImpl->pBox->EnableItem( GetId(), eState != SFX_ITEM_DISABLED );
sal_uInt16 nItemBits = pImpl->pBox->GetItemBits( GetId() );
nItemBits &= ~TIB_CHECKABLE;
TriState eTri = STATE_NOCHECK;
switch ( eState )
{
case SFX_ITEM_AVAILABLE:
{
if ( pState->ISA(SfxBoolItem) )
{
// BoolItem fuer checken
if ( ((const SfxBoolItem*)pState)->GetValue() )
eTri = STATE_CHECK;
nItemBits |= TIB_CHECKABLE;
}
else if ( pState->ISA(SfxEnumItemInterface) &&
((SfxEnumItemInterface *)pState)->HasBoolValue())
{
// EnumItem wie Bool behandeln
if ( ((const SfxEnumItemInterface *)pState)->GetBoolValue() )
eTri = STATE_CHECK;
nItemBits |= TIB_CHECKABLE;
}
else if ( pImpl->bShowString && pState->ISA(SfxStringItem) )
pImpl->pBox->SetItemText(nId, ((const SfxStringItem*)pState)->GetValue() );
break;
}
case SFX_ITEM_DONTCARE:
{
eTri = STATE_DONTKNOW;
nItemBits |= TIB_CHECKABLE;
}
}
pImpl->pBox->SetItemState( GetId(), eTri );
pImpl->pBox->SetItemBits( GetId(), nItemBits );
}
//--------------------------------------------------------------------
void SfxToolBoxControl::Select( sal_uInt16 nModifier )
{
pImpl->nSelectModifier = nModifier;
Select( sal_Bool((nModifier & KEY_MOD1)!=0) );
}
//--------------------------------------------------------------------
void SfxToolBoxControl::Select( sal_Bool /*bMod1*/ )
{
if(::comphelper::UiEventsLogger::isEnabled()) //#i88653# #i102805#
{
::rtl::OUString sAppName;
try
{
static ::rtl::OUString our_aModuleManagerName = ::rtl::OUString::createFromAscii("com.sun.star.frame.ModuleManager");
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceManager =
::comphelper::getProcessServiceFactory();
::com::sun::star::uno::Reference< ::com::sun::star::frame::XModuleManager > xModuleManager(
xServiceManager->createInstance(our_aModuleManagerName)
, ::com::sun::star::uno::UNO_QUERY_THROW);
sAppName = xModuleManager->identify(m_xFrame);
} catch(::com::sun::star::uno::Exception&) {}
Sequence<PropertyValue> vSource;
::comphelper::UiEventsLogger::appendDispatchOrigin(vSource, sAppName, ::rtl::OUString::createFromAscii("SfxToolBoxControl"));
URL aURL;
aURL.Complete = m_aCommandURL;
::comphelper::UiEventsLogger::logDispatch(aURL, vSource);
}
svt::ToolboxController::execute( pImpl->nSelectModifier );
}
//--------------------------------------------------------------------
void SfxToolBoxControl::DoubleClick()
{
}
//--------------------------------------------------------------------
void SfxToolBoxControl::Click()
{
}
//--------------------------------------------------------------------
SfxPopupWindowType SfxToolBoxControl::GetPopupWindowType() const
{
return SFX_POPUPWINDOW_NONE;
}
//--------------------------------------------------------------------
SfxPopupWindow* SfxToolBoxControl::CreatePopupWindow()
{
return 0;
}
SfxPopupWindow* SfxToolBoxControl::CreatePopupWindowCascading()
{
return 0;
}
//--------------------------------------------------------------------
Window* SfxToolBoxControl::CreateItemWindow( Window * )
{
return 0;
}
//--------------------------------------------------------------------
SfxFrameStatusListener::SfxFrameStatusListener(
const Reference< XMultiServiceFactory >& rServiceManager,
const Reference< XFrame >& xFrame,
SfxStatusListenerInterface* pCallee ) :
svt::FrameStatusListener( rServiceManager, xFrame ),
m_pCallee( pCallee )
{
}
//--------------------------------------------------------------------
SfxFrameStatusListener::~SfxFrameStatusListener()
{
}
//--------------------------------------------------------------------
// XStatusListener
void SAL_CALL SfxFrameStatusListener::statusChanged( const ::com::sun::star::frame::FeatureStateEvent& rEvent )
throw ( ::com::sun::star::uno::RuntimeException )
{
SfxViewFrame* pViewFrame = NULL;
Reference < XController > xController;
::vos::OGuard aGuard( Application::GetSolarMutex() );
if ( m_xFrame.is() )
xController = m_xFrame->getController();
Reference < XDispatchProvider > xProvider( xController, UNO_QUERY );
if ( xProvider.is() )
{
Reference < XDispatch > xDisp = xProvider->queryDispatch( rEvent.FeatureURL, ::rtl::OUString(), 0 );
if ( xDisp.is() )
{
Reference< XUnoTunnel > xTunnel( xDisp, UNO_QUERY );
SfxOfficeDispatch* pDisp = NULL;
if ( xTunnel.is() )
{
sal_Int64 nImplementation = xTunnel->getSomething(SfxOfficeDispatch::impl_getStaticIdentifier());
pDisp = reinterpret_cast< SfxOfficeDispatch* >( sal::static_int_cast< sal_IntPtr >( nImplementation ));
}
if ( pDisp )
pViewFrame = pDisp->GetDispatcher_Impl()->GetFrame();
}
}
sal_uInt16 nSlotId = 0;
SfxSlotPool& rPool = SfxSlotPool::GetSlotPool( pViewFrame );
const SfxSlot* pSlot = rPool.GetUnoSlot( rEvent.FeatureURL.Path );
if ( pSlot )
nSlotId = pSlot->GetSlotId();
if ( nSlotId > 0 )
{
if ( rEvent.Requery )
{
// requery for the notified state
addStatusListener( rEvent.FeatureURL.Complete );
}
else
{
SfxItemState eState = SFX_ITEM_DISABLED;
SfxPoolItem* pItem = NULL;
if ( rEvent.IsEnabled )
{
eState = SFX_ITEM_AVAILABLE;
::com::sun::star::uno::Type pType = rEvent.State.getValueType();
if ( pType == ::getVoidCppuType() )
{
pItem = new SfxVoidItem( nSlotId );
eState = SFX_ITEM_UNKNOWN;
}
else if ( pType == ::getBooleanCppuType() )
{
sal_Bool bTemp = false;
rEvent.State >>= bTemp ;
pItem = new SfxBoolItem( nSlotId, bTemp );
}
else if ( pType == ::getCppuType((const sal_uInt16*)0) )
{
sal_uInt16 nTemp = 0;
rEvent.State >>= nTemp ;
pItem = new SfxUInt16Item( nSlotId, nTemp );
}
else if ( pType == ::getCppuType((const sal_uInt32*)0) )
{
sal_uInt32 nTemp = 0;
rEvent.State >>= nTemp ;
pItem = new SfxUInt32Item( nSlotId, nTemp );
}
else if ( pType == ::getCppuType((const ::rtl::OUString*)0) )
{
::rtl::OUString sTemp ;
rEvent.State >>= sTemp ;
pItem = new SfxStringItem( nSlotId, sTemp );
}
else if ( pType == ::getCppuType((const ::com::sun::star::frame::status::ItemStatus*)0) )
{
ItemStatus aItemStatus;
rEvent.State >>= aItemStatus;
eState = aItemStatus.State;
pItem = new SfxVoidItem( nSlotId );
}
else if ( pType == ::getCppuType((const ::com::sun::star::frame::status::Visibility*)0) )
{
Visibility aVisibilityStatus;
rEvent.State >>= aVisibilityStatus;
pItem = new SfxVisibilityItem( nSlotId, aVisibilityStatus.bVisible );
}
else
{
if ( pSlot )
pItem = pSlot->GetType()->CreateItem();
if ( pItem )
{
pItem->SetWhich( nSlotId );
pItem->PutValue( rEvent.State );
}
else
pItem = new SfxVoidItem( nSlotId );
}
}
if ( m_pCallee )
m_pCallee->StateChanged( nSlotId, eState, pItem );
delete pItem;
}
}
}
//--------------------------------------------------------------------
SfxPopupWindow::SfxPopupWindow(
sal_uInt16 nId,
const Reference< XFrame >& rFrame,
WinBits nBits ) :
FloatingWindow( SFX_APP()->GetTopWindow(), nBits )
, m_bFloating(sal_False)
, m_bCascading( sal_False )
, m_nId( nId )
, m_xFrame( rFrame )
, m_pStatusListener( 0 )
{
m_xServiceManager = ::comphelper::getProcessServiceFactory();
Window* pWindow = GetTopMostParentSystemWindow( this );
if ( pWindow )
((SystemWindow *)pWindow)->GetTaskPaneList()->AddWindow( this );
}
//--------------------------------------------------------------------
SfxPopupWindow::SfxPopupWindow(
sal_uInt16 nId,
const Reference< XFrame >& rFrame,
const ResId &rId ) :
FloatingWindow( SFX_APP()->GetTopWindow(), rId )
, m_bFloating(sal_False)
, m_bCascading( sal_False )
, m_nId( nId )
, m_xFrame( rFrame )
, m_pStatusListener( 0 )
{
m_xServiceManager = ::comphelper::getProcessServiceFactory();
Window* pWindow = GetTopMostParentSystemWindow( this );
if ( pWindow )
((SystemWindow *)pWindow)->GetTaskPaneList()->AddWindow( this );
}
//--------------------------------------------------------------------
SfxPopupWindow::SfxPopupWindow(
sal_uInt16 nId,
const Reference< XFrame >& rFrame,
Window* pParentWindow,
WinBits nBits ) :
FloatingWindow( pParentWindow, nBits )
, m_bFloating(sal_False)
, m_bCascading( sal_False )
, m_nId( nId )
, m_xFrame( rFrame )
, m_pStatusListener( 0 )
{
m_xServiceManager = ::comphelper::getProcessServiceFactory();
Window* pWindow = GetTopMostParentSystemWindow( this );
if ( pWindow )
((SystemWindow *)pWindow)->GetTaskPaneList()->AddWindow( this );
}
//--------------------------------------------------------------------
SfxPopupWindow::SfxPopupWindow(
sal_uInt16 nId,
const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
Window* pParentWindow,
const ResId &rId ) :
FloatingWindow( pParentWindow, rId )
, m_bFloating(sal_False)
, m_bCascading( sal_False )
, m_nId( nId )
, m_xFrame( rFrame )
, m_pStatusListener( 0 )
{
m_xServiceManager = ::comphelper::getProcessServiceFactory();
Window* pWindow = GetTopMostParentSystemWindow( this );
if ( pWindow )
((SystemWindow *)pWindow)->GetTaskPaneList()->AddWindow( this );
}
//--------------------------------------------------------------------
SfxPopupWindow::~SfxPopupWindow()
{
if ( m_xStatusListener.is() )
{
m_xStatusListener->dispose();
m_xStatusListener.clear();
}
Window* pWindow = GetTopMostParentSystemWindow( this );
if ( pWindow )
((SystemWindow *)pWindow)->GetTaskPaneList()->RemoveWindow( this );
}
//--------------------------------------------------------------------
SfxFrameStatusListener* SfxPopupWindow::GetOrCreateStatusListener()
{
if ( !m_xStatusListener.is() )
{
m_pStatusListener = new SfxFrameStatusListener(
m_xServiceManager,
m_xFrame,
this );
m_xStatusListener = Reference< XComponent >( static_cast< cppu::OWeakObject* >(
m_pStatusListener ), UNO_QUERY );
}
return m_pStatusListener;
}
//--------------------------------------------------------------------
void SfxPopupWindow::BindListener()
{
GetOrCreateStatusListener();
if ( m_xStatusListener.is() )
m_pStatusListener->bindListener();
}
//--------------------------------------------------------------------
void SfxPopupWindow::UnbindListener()
{
GetOrCreateStatusListener();
if ( m_xStatusListener.is() )
m_pStatusListener->unbindListener();
}
//--------------------------------------------------------------------
void SfxPopupWindow::AddStatusListener( const rtl::OUString& rCommandURL )
{
GetOrCreateStatusListener();
if ( m_xStatusListener.is() )
m_pStatusListener->addStatusListener( rCommandURL );
}
//--------------------------------------------------------------------
void SfxPopupWindow::RemoveStatusListener( const rtl::OUString& rCommandURL )
{
GetOrCreateStatusListener();
if ( m_xStatusListener.is() )
m_pStatusListener->removeStatusListener( rCommandURL );
}
//--------------------------------------------------------------------
void SfxPopupWindow::UpdateStatus( const rtl::OUString& rCommandURL )
{
GetOrCreateStatusListener();
if ( m_xStatusListener.is() )
m_pStatusListener->updateStatus( rCommandURL );
}
//--------------------------------------------------------------------
sal_Bool SfxPopupWindow::Close()
{
m_bFloating = sal_False;
FloatingWindow::Close();
Delete(0);
return sal_True;
}
//--------------------------------------------------------------------
void SfxPopupWindow::PopupModeEnd()
{
//! to allow PopupModeEndHdl to be called
FloatingWindow::PopupModeEnd();
if ( IsVisible() )
{
// wurde abgerissen
DeleteFloatingWindow();
m_bFloating = sal_True;
}
else
Close();
}
//--------------------------------------------------------------------
void SfxPopupWindow::DeleteFloatingWindow()
{
if ( m_bFloating )
{
Hide();
Delete(0);
}
}
//--------------------------------------------------------------------
void SfxPopupWindow::MouseMove( const ::MouseEvent& rMEvt )
{
if ( m_bCascading == sal_False )
FloatingWindow::MouseMove( rMEvt );
else
{
// MouseMove-Event an die Children forwarden
::Point aPos = rMEvt.GetPosPixel();
::Point aScrPos = OutputToScreenPixel( aPos );
sal_uInt16 i = 0;
Window* pWindow = GetChild( i );
while ( pWindow )
{
::MouseEvent aMEvt( pWindow->ScreenToOutputPixel( aScrPos ),
rMEvt.GetClicks(), rMEvt.GetMode(),
rMEvt.GetButtons(), rMEvt.GetModifier() );
pWindow->MouseMove( rMEvt );
pWindow->Update();
i++;
pWindow = GetChild( i );
}
}
}
//--------------------------------------------------------------------
void SfxPopupWindow::StartCascading()
{
m_bCascading= sal_True;
}
void SfxPopupWindow::EndCascading()
{
m_bCascading = sal_False;
}
//--------------------------------------------------------------------
SfxPopupWindow* SfxPopupWindow::Clone() const
/* [Beschreibung]
Diese Methode mu\s "uberladen werden, um dieses Popup auch im
Presentations-Modus anzuzeigen. Sie wird gerufen, wenn ein Show()
sinnlos w"are, da der Parent nicht das Presentations-Window ist.
Beim neu erzeugen wird automatisch das neue Top-Window verwendet, so
da\s der Parent das Presentations-Window ist und das neue Popup somit
sichtbar ist.
*/
{
return 0;
}
//--------------------------------------------------------------------
void SfxPopupWindow::StateChanged(
sal_uInt16 /*nSID*/,
SfxItemState eState,
const SfxPoolItem* /*pState*/ )
/* [Bescheibung]
Siehe auch <SfxControllerItem::StateChanged()>. Au\serdem wird
bei eState==SFX_ITEM_DISABLED das Popup gehided und in allen anderen
F"allen, falls es floating ist, wieder angezeigt. Daher mu\s die
Basisklasse i.d.R. gerufen werden.
Es findet wegen des Parents eine Sonderbehandlung f"ur den
Presentationsmodus statt.
*/
{
if ( SFX_ITEM_DISABLED == eState )
{
Hide();
}
else if ( m_bFloating )
{
Show( sal_True, SHOW_NOFOCUSCHANGE | SHOW_NOACTIVATE );
}
}
//--------------------------------------------------------------------
IMPL_LINK( SfxPopupWindow, Delete, void *, EMPTYARG )
{
if ( m_aDeleteLink.IsSet() )
m_aDeleteLink.Call( this );
delete this;
return 0;
}
//--------------------------------------------------------------------
| 32.710317 | 198 | 0.589227 | [
"model"
] |
eb9039fd1aad1a522434936b266210556056a9d6 | 12,625 | cpp | C++ | cam/src/v20190116/model/AttachPolicyInfo.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | cam/src/v20190116/model/AttachPolicyInfo.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | cam/src/v20190116/model/AttachPolicyInfo.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/cam/v20190116/model/AttachPolicyInfo.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cam::V20190116::Model;
using namespace std;
AttachPolicyInfo::AttachPolicyInfo() :
m_policyIdHasBeenSet(false),
m_policyNameHasBeenSet(false),
m_addTimeHasBeenSet(false),
m_createModeHasBeenSet(false),
m_policyTypeHasBeenSet(false),
m_remarkHasBeenSet(false),
m_operateOwnerUinHasBeenSet(false),
m_operateUinHasBeenSet(false),
m_operateUinTypeHasBeenSet(false),
m_deactivedHasBeenSet(false),
m_deactivedDetailHasBeenSet(false)
{
}
CoreInternalOutcome AttachPolicyInfo::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("PolicyId") && !value["PolicyId"].IsNull())
{
if (!value["PolicyId"].IsUint64())
{
return CoreInternalOutcome(Core::Error("response `AttachPolicyInfo.PolicyId` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_policyId = value["PolicyId"].GetUint64();
m_policyIdHasBeenSet = true;
}
if (value.HasMember("PolicyName") && !value["PolicyName"].IsNull())
{
if (!value["PolicyName"].IsString())
{
return CoreInternalOutcome(Core::Error("response `AttachPolicyInfo.PolicyName` IsString=false incorrectly").SetRequestId(requestId));
}
m_policyName = string(value["PolicyName"].GetString());
m_policyNameHasBeenSet = true;
}
if (value.HasMember("AddTime") && !value["AddTime"].IsNull())
{
if (!value["AddTime"].IsString())
{
return CoreInternalOutcome(Core::Error("response `AttachPolicyInfo.AddTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_addTime = string(value["AddTime"].GetString());
m_addTimeHasBeenSet = true;
}
if (value.HasMember("CreateMode") && !value["CreateMode"].IsNull())
{
if (!value["CreateMode"].IsUint64())
{
return CoreInternalOutcome(Core::Error("response `AttachPolicyInfo.CreateMode` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_createMode = value["CreateMode"].GetUint64();
m_createModeHasBeenSet = true;
}
if (value.HasMember("PolicyType") && !value["PolicyType"].IsNull())
{
if (!value["PolicyType"].IsString())
{
return CoreInternalOutcome(Core::Error("response `AttachPolicyInfo.PolicyType` IsString=false incorrectly").SetRequestId(requestId));
}
m_policyType = string(value["PolicyType"].GetString());
m_policyTypeHasBeenSet = true;
}
if (value.HasMember("Remark") && !value["Remark"].IsNull())
{
if (!value["Remark"].IsString())
{
return CoreInternalOutcome(Core::Error("response `AttachPolicyInfo.Remark` IsString=false incorrectly").SetRequestId(requestId));
}
m_remark = string(value["Remark"].GetString());
m_remarkHasBeenSet = true;
}
if (value.HasMember("OperateOwnerUin") && !value["OperateOwnerUin"].IsNull())
{
if (!value["OperateOwnerUin"].IsString())
{
return CoreInternalOutcome(Core::Error("response `AttachPolicyInfo.OperateOwnerUin` IsString=false incorrectly").SetRequestId(requestId));
}
m_operateOwnerUin = string(value["OperateOwnerUin"].GetString());
m_operateOwnerUinHasBeenSet = true;
}
if (value.HasMember("OperateUin") && !value["OperateUin"].IsNull())
{
if (!value["OperateUin"].IsString())
{
return CoreInternalOutcome(Core::Error("response `AttachPolicyInfo.OperateUin` IsString=false incorrectly").SetRequestId(requestId));
}
m_operateUin = string(value["OperateUin"].GetString());
m_operateUinHasBeenSet = true;
}
if (value.HasMember("OperateUinType") && !value["OperateUinType"].IsNull())
{
if (!value["OperateUinType"].IsUint64())
{
return CoreInternalOutcome(Core::Error("response `AttachPolicyInfo.OperateUinType` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_operateUinType = value["OperateUinType"].GetUint64();
m_operateUinTypeHasBeenSet = true;
}
if (value.HasMember("Deactived") && !value["Deactived"].IsNull())
{
if (!value["Deactived"].IsUint64())
{
return CoreInternalOutcome(Core::Error("response `AttachPolicyInfo.Deactived` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_deactived = value["Deactived"].GetUint64();
m_deactivedHasBeenSet = true;
}
if (value.HasMember("DeactivedDetail") && !value["DeactivedDetail"].IsNull())
{
if (!value["DeactivedDetail"].IsArray())
return CoreInternalOutcome(Core::Error("response `AttachPolicyInfo.DeactivedDetail` is not array type"));
const rapidjson::Value &tmpValue = value["DeactivedDetail"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
m_deactivedDetail.push_back((*itr).GetString());
}
m_deactivedDetailHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void AttachPolicyInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_policyIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PolicyId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_policyId, allocator);
}
if (m_policyNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PolicyName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_policyName.c_str(), allocator).Move(), allocator);
}
if (m_addTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "AddTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_addTime.c_str(), allocator).Move(), allocator);
}
if (m_createModeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "CreateMode";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_createMode, allocator);
}
if (m_policyTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PolicyType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_policyType.c_str(), allocator).Move(), allocator);
}
if (m_remarkHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Remark";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_remark.c_str(), allocator).Move(), allocator);
}
if (m_operateOwnerUinHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "OperateOwnerUin";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_operateOwnerUin.c_str(), allocator).Move(), allocator);
}
if (m_operateUinHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "OperateUin";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_operateUin.c_str(), allocator).Move(), allocator);
}
if (m_operateUinTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "OperateUinType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_operateUinType, allocator);
}
if (m_deactivedHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Deactived";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_deactived, allocator);
}
if (m_deactivedDetailHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DeactivedDetail";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_deactivedDetail.begin(); itr != m_deactivedDetail.end(); ++itr)
{
value[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
}
uint64_t AttachPolicyInfo::GetPolicyId() const
{
return m_policyId;
}
void AttachPolicyInfo::SetPolicyId(const uint64_t& _policyId)
{
m_policyId = _policyId;
m_policyIdHasBeenSet = true;
}
bool AttachPolicyInfo::PolicyIdHasBeenSet() const
{
return m_policyIdHasBeenSet;
}
string AttachPolicyInfo::GetPolicyName() const
{
return m_policyName;
}
void AttachPolicyInfo::SetPolicyName(const string& _policyName)
{
m_policyName = _policyName;
m_policyNameHasBeenSet = true;
}
bool AttachPolicyInfo::PolicyNameHasBeenSet() const
{
return m_policyNameHasBeenSet;
}
string AttachPolicyInfo::GetAddTime() const
{
return m_addTime;
}
void AttachPolicyInfo::SetAddTime(const string& _addTime)
{
m_addTime = _addTime;
m_addTimeHasBeenSet = true;
}
bool AttachPolicyInfo::AddTimeHasBeenSet() const
{
return m_addTimeHasBeenSet;
}
uint64_t AttachPolicyInfo::GetCreateMode() const
{
return m_createMode;
}
void AttachPolicyInfo::SetCreateMode(const uint64_t& _createMode)
{
m_createMode = _createMode;
m_createModeHasBeenSet = true;
}
bool AttachPolicyInfo::CreateModeHasBeenSet() const
{
return m_createModeHasBeenSet;
}
string AttachPolicyInfo::GetPolicyType() const
{
return m_policyType;
}
void AttachPolicyInfo::SetPolicyType(const string& _policyType)
{
m_policyType = _policyType;
m_policyTypeHasBeenSet = true;
}
bool AttachPolicyInfo::PolicyTypeHasBeenSet() const
{
return m_policyTypeHasBeenSet;
}
string AttachPolicyInfo::GetRemark() const
{
return m_remark;
}
void AttachPolicyInfo::SetRemark(const string& _remark)
{
m_remark = _remark;
m_remarkHasBeenSet = true;
}
bool AttachPolicyInfo::RemarkHasBeenSet() const
{
return m_remarkHasBeenSet;
}
string AttachPolicyInfo::GetOperateOwnerUin() const
{
return m_operateOwnerUin;
}
void AttachPolicyInfo::SetOperateOwnerUin(const string& _operateOwnerUin)
{
m_operateOwnerUin = _operateOwnerUin;
m_operateOwnerUinHasBeenSet = true;
}
bool AttachPolicyInfo::OperateOwnerUinHasBeenSet() const
{
return m_operateOwnerUinHasBeenSet;
}
string AttachPolicyInfo::GetOperateUin() const
{
return m_operateUin;
}
void AttachPolicyInfo::SetOperateUin(const string& _operateUin)
{
m_operateUin = _operateUin;
m_operateUinHasBeenSet = true;
}
bool AttachPolicyInfo::OperateUinHasBeenSet() const
{
return m_operateUinHasBeenSet;
}
uint64_t AttachPolicyInfo::GetOperateUinType() const
{
return m_operateUinType;
}
void AttachPolicyInfo::SetOperateUinType(const uint64_t& _operateUinType)
{
m_operateUinType = _operateUinType;
m_operateUinTypeHasBeenSet = true;
}
bool AttachPolicyInfo::OperateUinTypeHasBeenSet() const
{
return m_operateUinTypeHasBeenSet;
}
uint64_t AttachPolicyInfo::GetDeactived() const
{
return m_deactived;
}
void AttachPolicyInfo::SetDeactived(const uint64_t& _deactived)
{
m_deactived = _deactived;
m_deactivedHasBeenSet = true;
}
bool AttachPolicyInfo::DeactivedHasBeenSet() const
{
return m_deactivedHasBeenSet;
}
vector<string> AttachPolicyInfo::GetDeactivedDetail() const
{
return m_deactivedDetail;
}
void AttachPolicyInfo::SetDeactivedDetail(const vector<string>& _deactivedDetail)
{
m_deactivedDetail = _deactivedDetail;
m_deactivedDetailHasBeenSet = true;
}
bool AttachPolicyInfo::DeactivedDetailHasBeenSet() const
{
return m_deactivedDetailHasBeenSet;
}
| 29.022989 | 150 | 0.687287 | [
"vector",
"model"
] |
eb911b1d0c9fca9c125accba096f438b306c69db | 4,221 | cpp | C++ | Runtime_and_System_Optimization/Design_Tutorials/02-ivas-ml/sw_src/ivas-kernel-libs/ivas_xdpuinfer/src/ivas_xyolov3.cpp | mkolod/Vitis-Tutorials | 33d6cf9686398ef1179778dc0da163291c68b465 | [
"Apache-2.0"
] | 1 | 2022-03-15T22:07:18.000Z | 2022-03-15T22:07:18.000Z | Runtime_and_System_Optimization/Design_Tutorials/02-ivas-ml/sw_src/ivas-kernel-libs/ivas_xdpuinfer/src/ivas_xyolov3.cpp | mkolod/Vitis-Tutorials | 33d6cf9686398ef1179778dc0da163291c68b465 | [
"Apache-2.0"
] | null | null | null | Runtime_and_System_Optimization/Design_Tutorials/02-ivas-ml/sw_src/ivas-kernel-libs/ivas_xdpuinfer/src/ivas_xyolov3.cpp | mkolod/Vitis-Tutorials | 33d6cf9686398ef1179778dc0da163291c68b465 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2020 - 2021 Xilinx, Inc. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
* KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
* EVENT SHALL XILINX 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. Except as contained in this notice, the name of the Xilinx shall
* not be used in advertising or otherwise to promote the sale, use or other
* dealings in this Software without prior written authorization from Xilinx.
*/
#include "ivas_xyolov3.hpp"
ivas_xyolov3::ivas_xyolov3 (ivas_xkpriv * kpriv, const std::string & model_name,
bool need_preprocess)
{
log_level = kpriv->log_level;
kpriv->labelflags = IVAS_XLABEL_REQUIRED;
LOG_MESSAGE (LOG_LEVEL_DEBUG, kpriv->log_level, "enter");
if (kpriv->labelptr == NULL) {
LOG_MESSAGE (LOG_LEVEL_ERROR, kpriv->log_level, "label not found");
kpriv->labelflags |= IVAS_XLABEL_NOT_FOUND;
} else
kpriv->labelflags |= IVAS_XLABEL_FOUND;
model = vitis::ai::YOLOv3::create (model_name, need_preprocess);
}
int
ivas_xyolov3::run (ivas_xkpriv * kpriv, const cv::Mat & image,
GstIvasMeta * ivas_meta)
{
LOG_MESSAGE (LOG_LEVEL_DEBUG, kpriv->log_level, "enter");
auto result = model->run (image);
labels *lptr;
int cols = image.cols;
int rows = image.rows;
if (kpriv->labelptr == NULL) {
LOG_MESSAGE (LOG_LEVEL_ERROR, kpriv->log_level, "label not found");
return false;
}
for (auto & box:result.bboxes) {
int label = box.label;
float xmin = box.x * cols + 1;
float ymin = box.y * rows + 1;
float xmax = xmin + box.width * cols;
float ymax = ymin + box.height * rows;
if (xmin < 0.)
xmin = 1.;
if (ymin < 0.)
ymin = 1.;
if (xmax > cols)
xmax = cols;
if (ymax > rows)
ymax = rows;
float confidence = box.score;
IvasObjectMetadata *xva_obj =
(IvasObjectMetadata *) calloc (1, sizeof (IvasObjectMetadata));
if (xva_obj == NULL) {
LOG_MESSAGE (LOG_LEVEL_ERROR, kpriv->log_level,
"failed to allocate memory");
return false;
}
if (label > kpriv->max_labels) {
LOG_MESSAGE (LOG_LEVEL_WARNING, kpriv->log_level,
"%d label not found\n", label);
strcpy ((char *) xva_obj->obj_class, "WRONG_LABEL");
} else {
lptr = kpriv->labelptr + label;
strcpy ((char *) xva_obj->obj_class, lptr->display_name.c_str ());
}
xva_obj->bbox_meta.xmin = xmin;
xva_obj->bbox_meta.ymin = ymin;
xva_obj->bbox_meta.xmax = xmax;
xva_obj->bbox_meta.ymax = ymax;
xva_obj->obj_prob = confidence;
ivas_meta->xmeta.objects =
g_list_append (ivas_meta->xmeta.objects, xva_obj);
LOG_MESSAGE (LOG_LEVEL_INFO, kpriv->log_level,
"RESULT: %s(%d) %f %f %f %f %f", lptr->display_name.c_str (), label,
xmin, ymin, xmax, ymax, confidence);
}
LOG_MESSAGE (LOG_LEVEL_INFO, kpriv->log_level, " ");
return true;
}
int
ivas_xyolov3::requiredwidth (void)
{
LOG_MESSAGE (LOG_LEVEL_DEBUG, log_level, "enter");
return model->getInputWidth ();
}
int
ivas_xyolov3::requiredheight (void)
{
LOG_MESSAGE (LOG_LEVEL_DEBUG, log_level, "enter");
return model->getInputHeight ();
}
int
ivas_xyolov3::close (void)
{
LOG_MESSAGE (LOG_LEVEL_DEBUG, log_level, "enter");
return true;
}
ivas_xyolov3::~ivas_xyolov3 ()
{
LOG_MESSAGE (LOG_LEVEL_DEBUG, log_level, "enter");
}
| 31.036765 | 80 | 0.690832 | [
"model"
] |
eb933e683efc2e70b95d1f00475441b92ba1130b | 54,401 | cc | C++ | src/experiment.cc | zonghuaxiansheng/Parallel | 8c9bbcef519b957a4ce34829f67527d3eb2a5f57 | [
"Apache-2.0"
] | null | null | null | src/experiment.cc | zonghuaxiansheng/Parallel | 8c9bbcef519b957a4ce34829f67527d3eb2a5f57 | [
"Apache-2.0"
] | null | null | null | src/experiment.cc | zonghuaxiansheng/Parallel | 8c9bbcef519b957a4ce34829f67527d3eb2a5f57 | [
"Apache-2.0"
] | null | null | null | #include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include "mpi.h"
#include "experiment.h"
#ifdef WINDOWS_PLATFORM
#include <Windows.h>
#else
#include <unistd.h>
#endif // WINDOWS_PLATFORM
namespace ustc_parallel {
struct Node
{
int key_;
int color_;
};
void inline gethostname(int my_rank, char* hostname, int len) {
char tname[16];
int group = my_rank % 3;
if (group == 0) {
strcpy(tname, "Node0");
} else if (group == 1) {
strcpy(tname, "Node1");
} else {
strcpy(tname, "Node2");
}
strcpy(hostname, tname);
}
void CreatePipeLine(int& my_rank, int& psize, MPI_Comm my_comm) {
MPI_Request request_r, request_s;
MPI_Status status_r;
int pre_rank = my_rank - 1;
int next_rank = my_rank + 1;
int tag = 10;
char next_rbuf[128];
char cur_rbuf[128];
char pre_sbuf[128] = "A";
char cur_sbuf[128] = "A";
int buf_len = 1;
int rcnt = 0;
while (rcnt < 10) {
if (my_rank == 0) {
// MPI_Send(sbuf, 128, MPI_CHAR, next_rank, tag, my_comm);
MPI_Isend(pre_sbuf, 128, MPI_CHAR, next_rank, tag, my_comm, &request_s);
// MPI_Wait(&request_s, &status_s);
std::cout << "Rank: " << my_rank
<< " Sbuf: " << pre_sbuf << " Dst Rank: " << next_rank << std::endl;
} else if (my_rank == psize - 1) {
MPI_Irecv(next_rbuf, 128, MPI_CHAR, pre_rank, tag, my_comm, &request_r);
MPI_Wait(&request_r, &status_r);
std::cout << "Rank: " << my_rank
<< " Rbuf: " << next_rbuf << " Src Rank: " << status_r.MPI_SOURCE << std::endl;
} else {
MPI_Irecv(next_rbuf, 128, MPI_CHAR, pre_rank, tag, my_comm, &request_r);
MPI_Isend(pre_sbuf, 128, MPI_CHAR, next_rank, tag, my_comm, &request_s);
MPI_Wait(&request_r, &status_r);
// MPI_Wait(&request_s, &status_s);
std::cout << "Rank: " << my_rank
<< " Rbuf: " << next_rbuf << " Src Rank: " << status_r.MPI_SOURCE << std::endl;
strcpy(cur_rbuf, next_rbuf);
for (int i = 0; i < buf_len; i++) {
cur_sbuf[i] = cur_rbuf[i] + 1;
}
cur_sbuf[buf_len] = '\0';
strcpy(pre_sbuf, cur_sbuf);
// MPI_Send(sbuf, 128, MPI_CHAR, next_rank, tag, my_comm);
std::cout << "Rank: " << my_rank
<< " Sbuf: " << pre_sbuf << " Dst Rank: " << next_rank << std::endl;
}
rcnt ++;
}
}
void CreateSimAlltoAll(int& my_rank, int& psize, MPI_Comm my_comm) {
MPI_Status status;
int tag = 10;
char sbuf[16] = "abc";
char* rbuf = new char[psize*16];
memset(rbuf, '\0', psize * 16);
for (int i = 0; i < psize; i++) {
if (my_rank != i) {
MPI_Send(sbuf, 16, MPI_CHAR, i, tag, my_comm);
}
}
for (int i = 0; i < psize; i++) {
if (my_rank != i) {
MPI_Recv(rbuf + i * 16, 16, MPI_CHAR, i, tag, my_comm, &status);
}
}
strcpy(rbuf + my_rank * 16, sbuf);
for (int i = 0; i < psize; i++) {
char tbuf[16];
strcpy(tbuf, rbuf + i * 16);
std::cout << "Rank: " << my_rank
<< " Buf[" << i << "]: " << tbuf << std::endl;
}
delete [] rbuf;
}
void CreateSimBcast(int& my_rank, int& psize, MPI_Comm my_comm) {
char hostname[16];
gethostname(my_rank, hostname, 16);
char* allname = new char[psize * 16];
Node* nodes = new Node[psize];
memset(allname, '\0', psize * 16);
MPI_Gather(hostname, 16, MPI_CHAR, allname, 16, MPI_CHAR, 0, MPI_COMM_WORLD);
int sub_color = 0, sub_key = 0;
int color_tag = 10, key_tag = 20;
if (my_rank == 0) {
std::map<std::string, std::pair<int, int>> name_map;
int sub_color = 0;
for (int i = 0; i < psize; i++) {
char tname[16];
strcpy(tname, allname + i * 16);
std::string name_str(tname);
// std::cout << tname << std::endl;
std::map<std::string, std::pair<int, int>>::iterator iter = name_map.find(name_str);
if (iter != name_map.end()) {
nodes[i].color_ = iter->second.first;
nodes[i].key_ = ++ iter->second.second;
}
else {
nodes[i].color_ = sub_color;
nodes[i].key_ = 0;
name_map.insert(std::make_pair(name_str, std::make_pair(sub_color++, 0)));
}
}
for (int i = 0; i < psize; i++) {
// std::cout << "Node: " << i << " " << nodes[i].color_ << " " << nodes[i].key_ << std::endl;
if (my_rank != i) {
MPI_Send(&nodes[i].color_, 1, MPI_INT, i, color_tag, my_comm);
MPI_Send(&nodes[i].key_, 1, MPI_INT, i, key_tag, my_comm);
}
}
sub_color = nodes[0].color_;
sub_key = nodes[0].key_;
} else {
MPI_Status status;
MPI_Recv(&sub_color, 1, MPI_INT, 0, color_tag, my_comm, &status);
MPI_Recv(&sub_key, 1, MPI_INT, 0, key_tag, my_comm, &status);
}
std::cout << "Rank: " << my_rank << " Sub Color: " << sub_color << " Sub Key: " << sub_key << std::endl;
MPI_Barrier(my_comm);
MPI_Comm leader_comm = MPI_COMM_WORLD, inside_comm = MPI_COMM_WORLD;
MPI_Comm_split(my_comm, sub_color, sub_key, &inside_comm);
MPI_Comm_split(my_comm, sub_key, sub_color, &leader_comm);
char sbuf[16];
if (my_rank == 0) {
strcpy(sbuf, "sim_bcast");
} else {
strcpy(sbuf, "");
}
std::cout << "Before Split -> Rank: " << my_rank << " Sbuf: " << sbuf << std::endl;
MPI_Barrier(my_comm);
MPI_Bcast(sbuf, 16, MPI_CHAR, 0, leader_comm);
std::cout << "Leader Split -> Rank: " << my_rank << " Sbuf: " << sbuf << std::endl;
MPI_Barrier(my_comm);
MPI_Bcast(sbuf, 16, MPI_CHAR, 0, inside_comm);
std::cout << "Inside Split -> Rank: " << my_rank << " Sbuf: " << sbuf << std::endl;
}
// 4. LU Split
template<typename T>
void DumpMatrix(T** *mptr_, std::string mname, int matrix_size) {
std::ofstream ofile;
ofile.open(mname, std::ios::out);
if (!ofile.is_open()) {
std::cout << "* Open file failed!" << std::endl;
exit(1);
}
auto& mptr = *(mptr_);
for (int i = 0; i < matrix_size; i++) {
for (int j = 0; j < matrix_size; j++) {
ofile << mptr[i][j] << " ";
}
}
ofile.close();
}
template<typename T>
void LoadMatrix(T** *mptr_, std::string mname, int matrix_size) {
std::ifstream ifile;
ifile.open(mname, std::ios::in);
if (!ifile.is_open()) {
std::cerr << "* Open file failed!" << std::endl;
exit(1);
} else {
std::cout << "* Open file " << mname << std::endl;
}
auto& mptr = *(mptr_);
for (int i = 0; i < matrix_size; i++) {
for (int j = 0; j < matrix_size; j++) {
ifile >> mptr[i][j];
}
}
ifile.close();
}
template<typename T>
void PrintMatrix(T** mptr, std::string name, int matrix_size) {
std::cout << std::endl << "* Matrix " << name << " ..." << std::endl;
for (int i = 0; i < matrix_size; i++) {
for (int j = 0; j < matrix_size; j++) {
std::cout << std::setw(5) << mptr[i][j] << " ";
}
std::cout << std::endl;
}
}
template<typename T>
void CreateLuMatrix(T** *L, T** *U, T** *A, int matrix_size) {
auto& lptr = *(L);
auto& uptr = *(U);
auto& luptr = *(A);
lptr = new T * [matrix_size];
uptr = new T * [matrix_size];
luptr = new T * [matrix_size];
for (int i = 0; i < matrix_size; i++) {
lptr[i] = new T[matrix_size];
uptr[i] = new T[matrix_size];
luptr[i] = new T[matrix_size];
memset(luptr[i], 0, matrix_size * sizeof(T));
}
for (int i = 0; i < matrix_size; i++) {
for (int j = 0; j < matrix_size; j++) {
if (i < j) {
uptr[i][j] = rand() % 50 + 1;
lptr[i][j] = 0;
} else if (i == j) {
uptr[i][j] = rand() % 50 + 1;
lptr[i][j] = 1;
} else {
uptr[i][j] = 0;
lptr[i][j] = rand() % 50 + 1;
}
}
}
for (int i = 0; i < matrix_size; i++) {
for (int j = 0; j < matrix_size; j++) {
for (int k = 0; k < matrix_size; k++) {
luptr[i][j] += lptr[i][k] * uptr[k][j];
}
}
}
}
template<typename T>
void SlpitA2LU(T** *A, T** *L, T** *U, int matrix_size) {
auto& lptr = *(L);
auto& uptr = *(U);
auto& luptr = *(A);
for (int i = 0; i < matrix_size; i++) {
for (int j = 0; j < matrix_size; j++) {
if (i < j) {
uptr[i][j] = luptr[i][j];
lptr[i][j] = 0;
}
else if (i == j) {
uptr[i][j] = luptr[i][j];
lptr[i][j] = 1;
}
else {
uptr[i][j] = 0;
lptr[i][j] = luptr[i][j];
}
}
}
}
template<typename T>
void ReleaseLuMatrix(T** lptr, T** uptr, T** luptr, int matrix_size) {
for (int i = 0; i < matrix_size; i++) {
delete[] lptr[i];
delete[] uptr[i];
delete[] luptr[i];
}
delete[] lptr;
delete[] uptr;
delete[] luptr;
}
void CreateLUSplit(int& my_rank, int& psize, MPI_Comm my_comm) {
int **A = nullptr, **L = nullptr, **U = nullptr;
int matrix_size = 500;
CreateLuMatrix<int>(&L, &U, &A, matrix_size);
// if (my_rank == 0) {
// DumpMatrix<int>(&L, "Matrix_L", matrix_size);
// DumpMatrix<int>(&U, "Matrix_U", matrix_size);
// DumpMatrix<int>(&A, "Matrix_A", matrix_size);
// PrintMatrix<int>(L, "L", matrix_size);
// PrintMatrix<int>(U, "U", matrix_size);
// PrintMatrix<int>(A, "A", matrix_size);
// }
// MPI_Barrier(my_comm);
for (int i = 0; i < psize; i++) {
if (my_rank == i) {
LoadMatrix<int>(&L, "Matrix_L", matrix_size);
LoadMatrix<int>(&U, "Matrix_U", matrix_size);
LoadMatrix<int>(&A, "Matrix_A", matrix_size);
}
MPI_Barrier(my_comm);
}
int turn = ceil((float)(matrix_size) / (float)(psize));
int* mainPtr = new int[matrix_size];
memset(mainPtr, 0, matrix_size * sizeof(int));
// For each trun
for (int t = 0; t < turn; t++) {
// For each processor
for (int p = 0; p < psize; p++) {
// My trun
auto mainLine = t * psize + p;
if (mainLine < matrix_size) {
if (my_rank == p) {
std::cout << std::endl << "* Main Line " << mainLine << ": ";
for (int k = 0; k < matrix_size; k++) {
mainPtr[k] = A[mainLine][k];
std::cout << mainPtr[k] << " ";
}
std::cout << std::endl;
}
MPI_Bcast(mainPtr, matrix_size, MPI_INT, p, my_comm);
MPI_Barrier(my_comm);
for (int j = t; j < turn; j++) {
int curLine = j * psize + my_rank;
if (curLine > mainLine && curLine < matrix_size) {
A[curLine][mainLine] /= mainPtr[mainLine];
for (int i = mainLine + 1; i < matrix_size; i++) {
A[curLine][i] -= A[curLine][mainLine] * mainPtr[i];
}
}
}
if (my_rank != p) {
for (int i = 0; i < matrix_size; i++) {
A[mainLine][i] = mainPtr[i];
}
}
}
}
}
MPI_Barrier(my_comm);
if (my_rank == 0) {
PrintMatrix<int>(A, "Final A", matrix_size);
int** AS = nullptr, ** LS = nullptr, ** US = nullptr;
CreateLuMatrix<int>(&LS, &US, &AS, matrix_size);
SlpitA2LU<int>(&A, &LS, &US, matrix_size);
for (int i = 0; i < matrix_size; i++) {
for (int j = 0; j < matrix_size; j++) {
if (L[i][j] != LS[i][j]) {
std::cerr << "LU Split error with L<" << i << "," << j << ">("
<< L[i][j] << "," << LS[i][j] << ")" << std::endl;
exit(1);
}
if (U[i][j] != US[i][j]) {
std::cerr << "LU Split error with U<" << i << "," << j << ">("
<< U[i][j] << "," << US[i][j] << ")" << std::endl;
exit(1);
}
}
}
PrintMatrix<int>(LS, "Final L", matrix_size);
PrintMatrix<int>(US, "Final U", matrix_size);
}
// ReleaseLuMatrix<int>(L, U, A, matrix_size);
}
// 1. Sum
// 1.1. Dish
void CreateDishSum(int& my_rank, int& psize, MPI_Comm my_comm) {
auto& n = psize;
int* sumArray = new int[n];
int check_sum = 0;
for (int i = 0; i < n; i++) {
sumArray[i] = i;
check_sum += i;
}
clock_t start_t = clock();
// Step
for (int s = 0; pow(2, s + 1) <= n; s ++) {
int barrier = pow(2, s);
int group = pow(2, s + 1);
auto index = my_rank % group;
if (index < barrier) {
int dest = my_rank + barrier;
MPI_Send(&sumArray[my_rank], 1, MPI_INT, dest, s, my_comm);
}
else {
int dest = my_rank - barrier;
MPI_Send(&sumArray[my_rank], 1, MPI_INT, dest, s, my_comm);
}
// MPI_Barrier(my_comm);
MPI_Status status;
if (index < barrier) {
int dest = my_rank + barrier;
MPI_Recv(&sumArray[dest], 1, MPI_INT, dest, s, my_comm, &status);
sumArray[my_rank] += sumArray[dest];
}
else {
int dest = my_rank - barrier;
MPI_Recv(&sumArray[dest], 1, MPI_INT, dest, s, my_comm, &status);
sumArray[my_rank] += sumArray[dest];
}
// MPI_Barrier(my_comm);
}
clock_t end_t = clock();
int use_t = (end_t - start_t);
int* use_time_arr = new int[psize];
MPI_Gather(&use_t, 1, MPI_INT, use_time_arr, 1, MPI_INT, 0, my_comm);
if (my_rank == 0) {
float mpi_sum_t = 0.0;
for (int i = 0; i < psize; i ++) {
mpi_sum_t += use_time_arr[i];
}
mpi_sum_t = mpi_sum_t / (float)psize;
std::cerr << n << "\t" << mpi_sum_t << std::endl;
}
for (int i = 0; i < n; i++) {
if (my_rank == i ) {
if (sumArray[i] != check_sum) {
std::cout << "* Rank: " << my_rank << " Sum Check failed !" << std::endl;
}
}
}
}
// 1.2. Binary Tree
void CreateBinaryTreeSum(int& my_rank, int& psize, MPI_Comm my_comm) {
auto& n = psize;
int* sumArray = new int[n];
int check_sum = 0;
for (int i = 0; i < n; i++) {
sumArray[i] = i;
check_sum += i;
}
clock_t start_t = clock();
// Step
for (int s = 0; pow(2, s + 1) <= n; s++) {
int div = pow(2, s + 1);
int sub = pow(2, s);
if ((my_rank % sub) == 0) {
if ((my_rank % div) != 0) {
int dest = my_rank - sub;
MPI_Send(&sumArray[my_rank], 1, MPI_INT, dest, s, my_comm);
} else {
int src = my_rank + sub;
MPI_Status status;
MPI_Recv(&sumArray[src], 1, MPI_INT, src, s, my_comm, &status);
sumArray[my_rank] += sumArray[src];
}
}
}
MPI_Bcast(&sumArray[0], 1, MPI_INT, 0, my_comm);
clock_t end_t = clock();
int use_t = (end_t - start_t);
int* use_time_arr = new int[psize];
MPI_Gather(&use_t, 1, MPI_INT, use_time_arr, 1, MPI_INT, 0, my_comm);
if (my_rank == 0) {
float mpi_sum_t = 0.0;
for (int i = 0; i < psize; i ++) {
mpi_sum_t += use_time_arr[i];
}
mpi_sum_t = mpi_sum_t / (float)psize;
std::cerr << n << "\t" << mpi_sum_t << std::endl;
}
if (sumArray[0] != check_sum) {
std::cout << "* Rank: " << my_rank << " Sum Check failed !" << std::endl;
}
}
template<typename T>
void MatrixMult(T*** X, T*** Y,T*** OUT, int matrix_size) {
auto& xptr = *(X);
auto& yptr = *(Y);
auto& optr = *(OUT);
for (int i = 0; i < matrix_size; i ++) {
for (int j = 0; j < matrix_size; j ++) {
optr[i][j] = 0;
for (int k = 0; k < matrix_size; k ++) {
optr[i][j] += xptr[i][k] * yptr[k][j];
}
}
}
}
template<typename T>
void MatrixAdd(T*** X, T*** Y,T*** OUT, int matrix_size) {
auto& xptr = *(X);
auto& yptr = *(Y);
auto& optr = *(OUT);
for (int i = 0; i < matrix_size; i ++) {
for (int j = 0; j < matrix_size; j ++) {
optr[i][j] = xptr[i][j] + yptr[i][j];
}
}
}
template<typename T>
void MatrixPrint(T*** X, std::string name, int row_size, int col_size=0) {
auto& xptr = *(X);
std::cout << "* MatrixPrint " << name << std::endl;
col_size = (col_size == 0) ? row_size : col_size;
for (int i = 0; i < row_size; i ++) {
for (int j = 0; j < col_size; j ++) {
std::cout << xptr[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
template<typename T>
void MatrixCompare(T*** X, T*** Y, int matrix_size) {
auto& xptr = *(X);
auto& yptr = *(Y);
for (int i = 0; i < matrix_size; i ++) {
for (int j = 0; j < matrix_size; j ++) {
if (xptr[i][j] != yptr[i][j]) {
std::cout << "* Matrix compare failed with "
<< xptr[i][j] << "," << yptr[i][j] << std::endl;
}
}
}
}
template<typename T>
void MatrixCopy(int copy_type,
T*** X,
T*** Y,
int length,
int start_xr = 0,
int start_xc = 0,
int start_yr = 0,
int start_yc = 0) {
auto& xptr = *(X);
auto& yptr = *(Y);
if (copy_type) { // from X to Y (X > Y)
for (int i = start_xr; i < start_xr + length; i ++) {
for (int j = start_xc; j < start_xc + length; j ++) {
yptr[i - start_xr + start_yr][j - start_xc + start_yc] = xptr[i][j];
}
}
} else { // from Y to X (X > Y)
for (int i = start_yr; i < start_yr + length; i ++) {
for (int j = start_yc; j < start_yc + length; j ++) {
xptr[i - start_yr + start_xr][j - start_yc + start_xc] = yptr[i][j];
}
}
}
}
template<typename T>
void CreateFoxMatrix(T*** A, int matrix_size, int init_type=1) {
auto& aptr = *(A);
aptr = new T* [matrix_size];
for (int i = 0; i < matrix_size; i ++) {
aptr[i] = new T [matrix_size];
for (int j = 0; j < matrix_size; j ++) {
if (init_type) {
aptr[i][j] = rand() % 100;
} else {
aptr[i][j] = 0;
}
}
}
}
template<typename T>
void ReleaseFoxMatrix(T*** A, int matrix_size) {
auto& aptr = *(A);
for (int i = 0; i < matrix_size; i ++) {
delete [] aptr[i];
}
delete [] aptr;
}
// 2. FOX Matrix Multiple
void CreateFoxMatrixSingle(int& my_rank, int& psize, MPI_Comm my_comm, int matrix_size) {
int** A = nullptr;
int** B = nullptr;
int** C = nullptr;
srand(0);
CreateFoxMatrix<int>(&A, matrix_size);
CreateFoxMatrix<int>(&B, matrix_size);
CreateFoxMatrix<int>(&C, matrix_size, 0);
MatrixPrint<int>(&A, "A", matrix_size);
MatrixPrint<int>(&B, "B", matrix_size);
MatrixMult<int>(&A, &B, &C, matrix_size);
MatrixPrint<int>(&C, "Normal-C", matrix_size);
ReleaseFoxMatrix<int>(&A, matrix_size);
ReleaseFoxMatrix<int>(&B, matrix_size);
ReleaseFoxMatrix<int>(&C, matrix_size);
}
void CreateFoxMatrixMult(int& my_rank, int& psize, MPI_Comm my_comm) {
int** A = nullptr;
int** B = nullptr;
int** C = nullptr;
int** MA = nullptr;
int** MB = nullptr;
int sub_matrix_size = 256;
int sqrt_size = (int)sqrt(psize);
int matrix_size = sub_matrix_size * sqrt_size;
srand(0);
CreateFoxMatrix<int>(&A, matrix_size);
CreateFoxMatrix<int>(&B, matrix_size);
if (my_rank == 0) {
MatrixPrint<int>(&A, "A", matrix_size);
MatrixPrint<int>(&B, "B", matrix_size);
}
CreateFoxMatrix<int>(&C, matrix_size, 0);
CreateFoxMatrix<int>(&MA, sub_matrix_size);
CreateFoxMatrix<int>(&MB, sub_matrix_size);
int row = (int)(my_rank / sqrt_size);
int col = (int)(my_rank % sqrt_size);
MPI_Comm row_comm;
MPI_Comm col_comm;
MPI_Comm_split(my_comm, row, col, &row_comm);
MPI_Comm_split(my_comm, col, row, &col_comm);
MatrixCopy<int>(1,
&A,
&MA,
sub_matrix_size,
row * sub_matrix_size,
col * sub_matrix_size);
MatrixCopy<int>(1,
&B,
&MB,
sub_matrix_size,
row * sub_matrix_size,
col * sub_matrix_size);
int** CopyMA = nullptr;
int** MultC = nullptr;
CreateFoxMatrix<int>(&CopyMA, sub_matrix_size);
CreateFoxMatrix<int>(&MultC, sub_matrix_size);
MPI_Barrier(my_comm);
clock_t start_t = clock();
// Fox multiple
for (int i = 0; i < sqrt_size; i ++) {
MatrixCopy<int>(1,
&MA,
&CopyMA,
sub_matrix_size);
for (int j = 0; j < sub_matrix_size; j ++) {
MPI_Bcast(CopyMA[j], sub_matrix_size, MPI_INT, (i + row) % sqrt_size, row_comm);
}
MatrixMult<int>(&CopyMA, &MB, &MultC, sub_matrix_size);
MatrixAdd<int>(&C, &MultC, &C, sub_matrix_size);
// Shift MB
MPI_Barrier(col_comm);
for (int j = 0; j < sub_matrix_size; j ++) {
MPI_Request request_s, request_r;
MPI_Status status;
int dest = (row == 0) ? sqrt_size - 1 : row - 1;
int src = (row == (sqrt_size - 1)) ? 0 : row + 1;
MPI_Isend(MB[j], sub_matrix_size, MPI_INT, dest, dest, col_comm, &request_s);
MPI_Irecv(MB[j], sub_matrix_size, MPI_INT, src, row, col_comm, &request_r);
MPI_Wait(&request_s, &status);
MPI_Wait(&request_r, &status);
}
}
// Collect matrix C
if (my_rank != 0) {
std::vector<MPI_Request> req_vec;
for (int j = 0; j < sub_matrix_size; j ++) {
MPI_Request request;
// MPI_Status status;
MPI_Isend(C[j], sub_matrix_size, MPI_INT, 0, my_rank, my_comm, &request);
req_vec.push_back(request);
// MPI_Wait(&request, &status);
}
MPI_Status status;
for(auto iter = req_vec.begin(); iter != req_vec.end(); iter ++) {
MPI_Wait(&(*iter), &status);
}
} else {
std::vector<MPI_Request> req_vec;
for (int i = 1; i < psize; i ++) {
int row = (int)(i / sqrt_size);
int col = (int)(i % sqrt_size);
for (int j = 0; j < sub_matrix_size; j ++) {
MPI_Request request;
// MPI_Status status;
MPI_Irecv(&C[row * sub_matrix_size + j][col * sub_matrix_size],
sub_matrix_size, MPI_INT, i, i, my_comm, &request);
// MPI_Wait(&request, &status);
req_vec.push_back(request);
}
}
MPI_Status status;
for(auto iter = req_vec.begin(); iter != req_vec.end(); iter ++) {
MPI_Wait(&(*iter), &status);
}
}
clock_t end_t = clock();
int use_t = (end_t - start_t);
int* use_time_arr = new int[psize];
MPI_Gather(&use_t, 1, MPI_INT, use_time_arr, 1, MPI_INT, 0, my_comm);
if (my_rank == 0) {
float mpi_sum_t = 0.0;
for (int i = 0; i < psize; i ++) {
mpi_sum_t += use_time_arr[i];
}
mpi_sum_t = mpi_sum_t / (float)psize;
// MatrixPrint<int>(&C, "MPI-Fox-C", matrix_size);
// Normal fox multpile
int** NC = nullptr;
CreateFoxMatrix<int>(&NC, matrix_size, 0);
start_t = clock();
MatrixMult<int>(&A, &B, &NC, matrix_size);
end_t = clock();
use_t = (end_t - start_t);
MatrixCompare(&C, &NC, matrix_size);
// MatrixPrint<int>(&NC, "Normal-Fox-C", matrix_size);
std::cerr << matrix_size << "-" << sub_matrix_size << "-MPI-Fox-Avg-Time: " << mpi_sum_t << std::endl
<< matrix_size << "-" << sub_matrix_size << "-Normal-Fox-Time: " << use_t << std::endl;
}
ReleaseFoxMatrix<int>(&A, matrix_size);
ReleaseFoxMatrix<int>(&B, matrix_size);
ReleaseFoxMatrix<int>(&C, matrix_size);
ReleaseFoxMatrix<int>(&MA, sub_matrix_size);
ReleaseFoxMatrix<int>(&MB, sub_matrix_size);
ReleaseFoxMatrix<int>(&CopyMA, sub_matrix_size);
ReleaseFoxMatrix<int>(&MultC, sub_matrix_size);
delete [] use_time_arr;
}
// 3. Parameter Server
void CreateParameterServer(int& my_rank, int& psize, MPI_Comm my_comm) {
int pServerNum = 2;
// int wServerNum = psize - pServerNum;
int pColor = my_rank / pServerNum;
int pKey = my_rank % pServerNum;
MPI_Comm param_comm;
MPI_Comm_split(my_comm, pColor, pKey, ¶m_comm);
if (my_rank >= pServerNum) {
srand(my_rank);
while (true) {
int sdata = rand() % 1000;
int rdata = 0;
int dest = my_rank % pServerNum;
MPI_Status status;
MPI_Request request;
#ifdef WINDOWS_PLATFORM
int stime = rand() % 1000 + 2000;
Sleep(stime);
#else
int stime = rand() % 10;
sleep(stime);
#endif // WINDOWS_PLATFROM
std::cout << "* wServer " << my_rank << " Send to " << dest << " sData " << sdata << std::endl;
MPI_Isend(&sdata, 1, MPI_INT, dest, my_rank, my_comm, &request);
MPI_Wait(&request, &status);
MPI_Irecv(&rdata, 1, MPI_INT, dest, my_rank, my_comm, &request);
MPI_Wait(&request, &status);
std::cout << "* wServer " << my_rank << " Recv from " << dest << " avg data " << rdata << std::endl;
}
} else {
srand(my_rank);
while (true) {
int rNum = (psize - 1) / pServerNum - 1;
if ((psize - 1) % pServerNum >= my_rank) {
rNum++;
}
int* rData = new int[rNum];
for (int i = 1; i <= rNum; i++) {
int src = i * pServerNum + my_rank;
MPI_Request request;
MPI_Status status;
MPI_Irecv(&rData[i], 1, MPI_INT, src, src, my_comm, &request);
MPI_Wait(&request, &status);
std::cout << "* pServer " << my_rank << " Recv from " << src << " rData " << rData[i] << std::endl;
}
for (int i = 2; i <= rNum; i++) {
rData[1] += rData[i];
}
std::cout << "* pServer " << my_rank << " Compute data " << rData[1] << std::endl;
int* gData = new int[pServerNum];
MPI_Gather(&rData[1], 1, MPI_INT, gData, 1, MPI_INT, 0, param_comm);
int avgData = 0;
if (my_rank == 0) {
std::cout << "* PServer rData: ";
for (int i = 0; i < pServerNum; i ++) {
std::cout << gData[i] << " ";
avgData += gData[i];
}
avgData /= pServerNum;
std::cout << std::endl;
}
MPI_Bcast(&avgData, 1, MPI_INT, 0, param_comm);
std::cout << "* pServer " << my_rank << " Get avg data " << avgData << std::endl;
#ifdef WINDOWS_PLATFORM
int stime = rand() % 1000 + 2000;
Sleep(stime);
#else
int stime = rand() % 10;
sleep(stime);
#endif // WINDOWS_PLATFROM
for (int i = 1; i <= rNum; i++) {
int dest = i * pServerNum + my_rank;
MPI_Request request;
MPI_Status status;
MPI_Isend(&avgData, 1, MPI_INT, dest, dest, my_comm, &request);
MPI_Wait(&request, &status);
std::cout << "* pServer " << my_rank << " Send to " << dest << " avg data " << avgData << std::endl;
}
}
}
}
int NormalMod(int x, int y, int z) {
// pow(x, y) % z
int out = 1;
for (int i = 0; i < y; i ++) {
out *= x;
out = out % z;
}
return out;
}
int FastMod(int x, int y, int z) {
int ans = 1;
int base = x % z;
while (y) {
if (y & 1) {
ans = (ans * base) % z;
}
base = (base * base) % z;
y >>= 1;
}
return ans;
}
// 4. MC Algorithm
bool Btest(int& a, int& n, bool debug=false) {
auto s = 0;
auto t = n - 1;
while (t % 2 == 0) {
s ++;
t = t / 2;
}
if (debug) {
std::cout << "* n,a,t,s=" << n << "," << a << "," << t << "," << s << std::endl;
}
auto x = FastMod(a, t, n);
if (debug) {
std::cout << "* x=" << x << std::endl;
}
if (x == 1 || x == n - 1) {
return true;
}
for (int i = 1; i < s; i ++) {
x = FastMod(x, 2, n);
if (debug) {
std::cout << "* x=" << x << std::endl;
}
if (x == n - 1) {
return true;
}
}
return false;
}
bool MillerRabin(int& n, bool debug=false) {
int a = rand() % ( n - 3) + 2;
// std::cout << "* Rand choose: " << a << std::endl;
return Btest(a, n, debug);
}
bool RepeatMillerRabin(int& n, int& repeat_num, bool debug=false) {
// std::cout << "* MR: n,r=" << n << "," << repeat_num << std::endl;
for (int i = 0; i < repeat_num; i ++) {
if (!MillerRabin(n, debug)) {
return false;
}
}
return true;
}
bool PrimeJudge(int& n) {
int sqrt_n = sqrt(n);
// int sqrt_n = n;
for (int i = 2; i <= sqrt_n; i ++) {
if (n % i == 0) {
return false;
}
}
return true;
}
void CreateMonteCarloSingle(int& my_rank, int& psize, MPI_Comm my_comm) {
int floor_n = 100000;
std::vector<int> pj_vec;
std::vector<int> mr_vec;
srand(time(NULL));
clock_t start_t = clock();
for (int i = 5; i < floor_n; i += 2) {
if (PrimeJudge(i)) {
pj_vec.push_back(i);
}
}
clock_t end_t = clock();
// std::cout << "* PJ use time: " << (end_t - start_t) << "s" << std::endl;
std::cerr << "1<PJ>Prime-size:" << pj_vec.size() << std::endl;
std::cerr << "1<PJ>Avg-time-use(s):" << (end_t - start_t) << std::endl;
start_t = clock();
for (int i = 5; i < floor_n; i += 2) {
int log_i = ceil(log(i));
log_i = (int)ceil(sqrt(log_i));
// int log_i = 10;
if (RepeatMillerRabin(i, log_i)) {
mr_vec.push_back(i);
}
// } else if (RepeatMillerRabin(i, log_i)) {
// mr_vec.push_back(i);
// }
}
end_t = clock();
// std::cout << "* MR use time: " << (end_t - start_t) << "s" << std::endl;
if (pj_vec.size() != mr_vec.size()) {
std::cout << "* There is some difference" << std::endl;
}
// int j = 0;
// int diff_cnt = 0;
// for (int i = 0; i < pj_vec.size(); i ++) {
// if (pj_vec[i] != mr_vec[j]) {
// std::cout << "* Different " << pj_vec[i] << "," << mr_vec[j] << std::endl;
// int log_i = ceil(log(pj_vec[i]));
// RepeatMillerRabin(pj_vec[i], log_i, true);
// diff_cnt ++;
// // break;
// } else {
// j ++;
// }
// if (diff_cnt > 5) break;
// }
std::cerr << "1<MC>Prime-size:" << mr_vec.size() << std::endl;
std::cerr << "1<MC>Avg-time-use(s):" << (end_t - start_t) << std::endl;
}
void CreateMonteCarloParallel(int& my_rank, int& psize, MPI_Comm my_comm) {
typedef char bool_t;
int floor_n = 100000000;
int pn = ceil((float)(floor_n / 2) / (float)psize);
int sum_pn = pn * psize;
bool_t* prime_arr = new bool_t[pn];
srand(time(NULL));
clock_t start_t = clock();
for (int i = 5 + my_rank * 2; i < floor_n; i += (psize * 2)) {
int log_i = ceil(log(i));
prime_arr[(i - 5) / (psize * 2)] = RepeatMillerRabin(i, log_i) ? '1' : '0';
}
bool_t* prime_sum_arr = new bool_t[sum_pn];
MPI_Gather(prime_arr, pn, MPI_CHAR, prime_sum_arr, pn, MPI_CHAR, 0, my_comm);
std::vector<int> prime_vec;
if (my_rank == 0) {
prime_vec.push_back(2);
prime_vec.push_back(3);
for (int p = 0; p < psize; p ++) {
for (int i = 0; i < pn; i ++) {
if (prime_sum_arr[p * pn + i] == '1') {
prime_vec.push_back(5 + (p * 2) + (i * psize * 2));
}
}
}
}
clock_t end_t = clock();
int use_t = (int)(end_t - start_t);
// std::cout << "* MR " << my_rank << " use time: " << use_t << "s" << std::endl;
int* time_sum_arr = new int[psize];
MPI_Gather(&use_t, 1, MPI_INT, time_sum_arr, 1, MPI_INT, 0, my_comm);
if (my_rank == 0) {
int time_sum = 0;
for (int p = 0; p < psize; p ++) {
time_sum += time_sum_arr[p];
}
// std::sort(prime_vec.begin(), prime_vec.end(), [] (int x, int y) {return x < y;});
// std::cout << "* Prime array: ";
// for (auto iter = prime_vec.begin(); iter != prime_vec.end(); iter ++) {
// std::cout << *iter << ",";
// }
// std::cout << std::endl;
std::cerr << psize << ">Prime-size:" << prime_vec.size() << std::endl;
std::cerr << psize << ">Avg-time-use(s):" << (float)time_sum / (float)psize << std::endl;
}
delete [] prime_arr;
delete [] prime_sum_arr;
}
enum init_t {TC, GS};
// 15.1
template<typename T>
void CreateMatrix(T*** A, int row_size, int col_size, init_t init_type=init_t::TC) {
auto& aptr = *(A);
aptr = new T* [row_size];
for (int i = 0; i < row_size; i ++) {
aptr[i] = new T [col_size];
for (int j = 0; j < col_size; j ++) {
if (init_type == init_t::TC) {
if (i != j) {
int tmp = rand() % 10;
aptr[i][j] = tmp / 8;
} else {
aptr[i][j] = 1;
}
} else if (init_type == init_t::GS) {
aptr[i][j] = rand() % 20 + 1;
}
}
}
}
template<typename T>
void MatrixCopy(T*** A, T*** B, int row_size, int col_size) {
auto& aptr = *(A);
auto& bptr = *(B);
for (int r = 0; r < row_size; r ++) {
for (int c = 0; c < col_size; c ++) {
bptr[r][c] = aptr[r][c];
}
}
}
template<typename T>
void ReleaseMatrix(T*** A, int row_size) {
auto& aptr = *(A);
for (int r = 0; r < row_size; r ++) {
delete [] aptr[r];
}
delete [] aptr;
}
template<typename T>
void VectorPrint(T** X, std::string name, int vector_size) {
auto& xptr = *(X);
std::cout << "* VectorPrint " << name << std::endl;
for (int i = 0; i < vector_size; i ++) {
std::cout << xptr[i] << " ";
}
std::cout << std::endl;
}
template<typename T>
void VectorCopy(T** X, T** Y, int vector_size) {
auto& xptr = *(X);
auto& yptr = *(Y);
for (int i = 0; i < vector_size; i ++) {
yptr[i] = xptr[i];
}
}
template<typename T>
bool VectorCompare(T** X, T** Y, int vector_size) {
auto& xptr = *(X);
auto& yptr = *(Y);
for (int i = 0; i < vector_size; i ++) {
auto diff = fabs(xptr[i] - yptr[i]);
if (diff >= 0.003) {
std::cout << "* Vector compare failed with "
<< xptr[i] << "," << yptr[i] << std::endl;
return false;
}
}
return true;
}
template<typename T>
void CreateVector(T** X, int vector_size, init_t init_type=init_t::GS) {
auto& xptr = *(X);
xptr = new T[vector_size];
for (int i = 0; i < vector_size; i ++) {
if (init_type == init_t::GS) {
xptr[i] = rand() % 20;
} else {
xptr[i] = 0;
}
}
}
template<typename T>
void ReleaseVector(T** X) {
auto& xptr = *(X);
delete [] xptr;
}
template<typename T>
void RunTransitiveClosureSerial(T*** A, T*** M, int matrix_size) {
auto& aptr = *(A);
auto& mptr = *(M);
for (int k = 1; k <= log(matrix_size); k ++) {
for (int i = 0; i < matrix_size; i ++) {
for (int j = 0; j < matrix_size; j ++) {
int s = 0;
while (s < matrix_size && (aptr[i][s] == 0 || aptr[s][j] == 0)) {
s ++;
}
if (s < matrix_size) {
mptr[i][j] = 1;
} else {
mptr[i][j] = 0;
}
}
}
for (int i = 0; i < matrix_size; i ++) {
for (int j = 0; j < matrix_size; j ++) {
aptr[i][j] = mptr[i][j];
}
}
// MatrixPrint<int>(&aptr, "Loop-A", matrix_size);
}
}
void CreateTransitiveClosureParallel(int& my_rank, int& psize, MPI_Comm my_comm) {
int** SA = nullptr;
int** PA = nullptr;
int** M = nullptr;
int sub_matrix_size = 64;
int matrix_size = sub_matrix_size * psize;
srand(time(NULL));
CreateMatrix<int>(&SA, matrix_size, matrix_size);
CreateMatrix<int>(&PA, matrix_size, matrix_size);
MatrixCopy<int>(&SA, &PA, matrix_size, matrix_size);
CreateMatrix<int>(&M, matrix_size, matrix_size);
int serial_use_t = 0;
int parallel_use_t = 0;
if (my_rank == 0) {
// MatrixPrint<int>(&SA, "Initial-A", matrix_size);
clock_t start_t = clock();
RunTransitiveClosureSerial<int>(&SA, &M, matrix_size);
clock_t end_t = clock();
serial_use_t = (end_t - start_t);
// MatrixPrint<int>(&SA, "Serial-A", matrix_size);
}
int** LocalA = nullptr;
int** LocalB = nullptr;
int** TmpB = nullptr;
int row_size = matrix_size / psize;
int col_size = row_size;
if (matrix_size % psize != 0) {
std::cout << "* Unsupport matrix_size % psize != 0 now !" << std::endl;
}
CreateMatrix<int>(&LocalA, row_size, matrix_size);
CreateMatrix<int>(&LocalB, matrix_size, col_size);
CreateMatrix<int>(&TmpB, matrix_size, col_size);
clock_t start_t = clock();
for (int i = 1; i <= log(matrix_size); i ++) {
// 1. Root send sub_rows and sub_cols to each processor
if (my_rank == 0) {
std::vector<MPI_Request> req_vec;
for (int p = 1; p < psize; p ++) {
for (int r = 0; r < row_size; r ++) {
MPI_Request request;
MPI_Isend(PA[p * row_size + r], matrix_size, MPI_INT, p, p, my_comm, &request);
req_vec.push_back(request);
}
for (int r = 0; r < matrix_size; r ++) {
MPI_Request request;
MPI_Isend(&PA[r][p * col_size], col_size, MPI_INT, p, p + psize, my_comm, &request);
req_vec.push_back(request);
}
}
for (int r = 0; r < row_size; r ++) {
for (int c = 0; c < matrix_size; c ++) {
LocalA[r][c] = PA[r][c];
}
}
for (int r = 0; r < matrix_size; r ++) {
for (int c = 0; c < col_size; c ++) {
LocalB[r][c] = PA[r][c];
}
}
MPI_Status status;
for (auto iter = req_vec.begin(); iter != req_vec.end(); iter ++) {
MPI_Wait(&(*iter), &status);
}
} else {
MPI_Request request;
MPI_Status status;
for (int r = 0; r < row_size; r ++) {
MPI_Irecv(LocalA[r], matrix_size, MPI_INT, 0, my_rank, my_comm, &request);
MPI_Wait(&request, &status);
}
for (int r = 0; r < matrix_size; r ++) {
MPI_Irecv(LocalB[r], col_size, MPI_INT, 0, my_rank + psize, my_comm, &request);
MPI_Wait(&request, &status);
}
}
// 2. Start compute for each processor
for (int j = 0; j < psize; j ++) {
for (int r = 0; r < row_size; r ++) {
for (int c = 0; c < col_size; c ++) {
int s = 0;
while (s < matrix_size && (LocalA[r][s] == 0 || LocalB[s][c] == 0)) {
s ++;
}
int start_col = (my_rank + j) % psize;
M[my_rank * row_size + r][start_col * col_size + c] = (s < matrix_size) ? 1 : 0;
}
}
// Shift LocalB
std::vector<MPI_Request> req_vec_r;
std::vector<MPI_Request> req_vec_s;
MatrixCopy<int>(&LocalB, &TmpB, matrix_size, col_size);
for (int r = 0; r < matrix_size; r ++) {
int src = (my_rank + 1) % psize;
int dest = (my_rank == 0) ? psize - 1 : (my_rank - 1);
MPI_Request request_s, request_r;
// MPI_Status status;
MPI_Isend(TmpB[r], col_size, MPI_INT, dest, my_rank, my_comm, &request_s);
MPI_Irecv(LocalB[r], col_size, MPI_INT, src, src, my_comm, &request_r);
req_vec_s.push_back(request_s);
req_vec_r.push_back(request_r);
// MPI_Wait(&request_s, &status);
// MPI_Wait(&request_r, &status);
// MPI_Status status;
// MatrixCopy<int>(&LocalB, &TmpB, matrix_size, col_size);
// if (my_rank == 0) {
// MPI_Recv(LocalB[r], col_size, MPI_INT, src, src, my_comm, &status);
// MPI_Send(TmpB[r], col_size, MPI_INT, dest, my_rank, my_comm);
// } else {
// MPI_Send(TmpB[r], col_size, MPI_INT, dest, my_rank, my_comm);
// MPI_Recv(LocalB[r], col_size, MPI_INT, src, src, my_comm, &status);
// }
}
MPI_Status status;
for (auto iter = req_vec_s.begin(); iter != req_vec_s.end(); iter ++) {
MPI_Wait(&(*iter), &status);
}
for (auto iter = req_vec_r.begin(); iter != req_vec_r.end(); iter ++) {
MPI_Wait(&(*iter), &status);
}
}
// 3. Collect compute output
if (my_rank != 0) {
// Send sub_rows to root
for (int r = 0; r < row_size; r ++) {
MPI_Send(M[my_rank * row_size + r], matrix_size, MPI_INT, 0, my_rank, my_comm);
}
} else {
// Recv sub_rows from other processors
for (int p = 1; p < psize; p ++) {
for (int r = 0; r < row_size; r ++) {
MPI_Status status;
MPI_Recv(M[p * row_size + r], matrix_size, MPI_INT, p, p, my_comm, &status);
}
}
}
// 4. Copy M to A
if (my_rank == 0) {
for (int i = 0; i < matrix_size; i ++) {
for (int j = 0; j < matrix_size; j ++) {
PA[i][j] = M[i][j];
}
}
}
}
clock_t end_t = clock();
// Root show matrix A
if (my_rank == 0) {
// MatrixPrint<int>(&PA, "Parallel-A", matrix_size);
MatrixCompare<int>(&SA, &PA, matrix_size);
}
// Compute use time
parallel_use_t = (end_t - start_t);
int* use_time_arr = new int[psize];
MPI_Gather(¶llel_use_t, 1, MPI_INT, use_time_arr, 1, MPI_INT, 0, my_comm);
if (my_rank == 0) {
float mpi_sum_t = 0.0;
for (int i = 0; i < psize; i ++) {
mpi_sum_t += use_time_arr[i];
}
mpi_sum_t = mpi_sum_t / (float)psize;
std::cerr << psize << "\t" << sub_matrix_size << "\t" << serial_use_t << "\t" << mpi_sum_t << std::endl;
}
ReleaseMatrix<int>(&SA, matrix_size);
ReleaseMatrix<int>(&PA, matrix_size);
ReleaseMatrix<int>(&M, matrix_size);
ReleaseMatrix<int>(&LocalA, row_size);
ReleaseMatrix<int>(&LocalB, matrix_size);
ReleaseMatrix<int>(&TmpB, matrix_size);
}
// 19.1 Gauss Elimination
template<typename T>
void RunGaussEliminSerial(T*** A, T** B, T** X, int row_size, int col_size) {
auto& aptr = *(A);
auto& bptr = *(B);
auto& xptr = *(X);
int* shift = new int[col_size];
for (int i = 0; i < col_size; i ++) {
shift[i] = i;
}
for (int k = 0; k < row_size; k ++) {
T max_elem = 0;
int elem_row = 0;
int elem_col = 0;
// Select max item
for (int r = k; r < row_size; r ++) {
for (int c = k; c < col_size; c ++) {
if (fabs(aptr[r][c]) > max_elem) {
max_elem = fabs(aptr[r][c]);
elem_row = r;
elem_col = c;
}
}
}
// Switch max col
if (elem_col != k) {
for (int r = 0; r < row_size; r ++) {
auto buf = aptr[r][k];
aptr[r][k] = aptr[r][elem_col];
aptr[r][elem_col] = buf;
}
auto buf = shift[k];
shift[k] = shift[elem_col];
shift[elem_col] = buf;
}
// Switch max row
if (elem_row != k) {
for (int c = 0; c < col_size; c ++) {
auto buf = aptr[k][c];
aptr[k][c] = aptr[elem_row][c];
aptr[elem_row][c] = buf;
}
auto buf = bptr[k];
bptr[k] = bptr[elem_row];
bptr[elem_row] = buf;
}
// MatrixPrint<T>(&aptr, "Swith-A", matrix_size);
// VectorPrint<T>(&bptr, "Swith-B", matrix_size);
// Div current line
for (int c = k + 1; c < col_size; c ++) {
aptr[k][c] = aptr[k][c] / aptr[k][k];
}
bptr[k] = bptr[k] / aptr[k][k];
aptr[k][k] = 1;
// MatrixPrint<T>(&aptr, "DIV-A", matrix_size);
// VectorPrint<T>(&bptr, "DIV-B", matrix_size);
// Start eliminate
for (int r = k + 1; r < row_size; r ++) {
for (int c = k + 1; c < col_size; c ++) {
aptr[r][c] -= aptr[r][k] * aptr[k][c];
}
bptr[r] -= aptr[r][k] * bptr[k];
aptr[r][k] = 0;
}
// MatrixPrint<T>(&aptr, "GSE-A", row_size, col_size);
// VectorPrint<T>(&bptr, "GSE-B", row_size);
}
// MatrixPrint<T>(&aptr, "GSE-A", row_size, col_size);
// VectorPrint<T>(&bptr, "GSE-B", row_size);
for (int c = col_size - 1; c >= 0; c --) {
if (c == col_size - 1) {
xptr[c] = bptr[c] / aptr[c][c];
} else {
float sub_sum = 0;
for (int c1 = c + 1; c1 < col_size; c1 ++) {
sub_sum += aptr[c][c1] * xptr[c1];
}
xptr[c] = (bptr[c] - sub_sum) / aptr[c][c];
}
}
T* SortX = nullptr;
CreateVector<T>(&SortX, col_size);
for (int r = 0; r < col_size; r ++) {
for (int i = 0; i < col_size; i ++) {
if (shift[i] == r) {
SortX[r] = xptr[i];
}
}
}
VectorCopy<T>(&SortX, &xptr, col_size);
// VectorPrint<T>(&xptr, "Serial-X", col_size);
ReleaseVector<T>(&SortX);
}
void CreateGaussEliminParallel(int& my_rank, int& psize, MPI_Comm my_comm) {
float** SA = nullptr;
float** PA = nullptr;
float* SB = nullptr;
float* PB = nullptr;
float* SX = nullptr;
float* PX = nullptr;
int sub_matrix_size = 64;
int row_size = sub_matrix_size * psize;
int col_size = sub_matrix_size * psize;
CreateMatrix<float>(&PA, row_size, col_size, init_t::GS);
CreateVector<float>(&PB, row_size, init_t::GS);
CreateVector<float>(&PX, col_size);
if (my_rank == 0) {
CreateMatrix<float>(&SA, row_size, col_size, init_t::GS);
CreateVector<float>(&SB, row_size, init_t::GS);
CreateVector<float>(&SX, col_size);
MatrixCopy<float>(&PA, &SA, row_size, col_size);
VectorCopy<float>(&PB, &SB, row_size);
// MatrixPrint<float>(&SA, "Initial-A", row_size, col_size);
// VectorPrint<float>(&SB, "Initial-B", row_size);
RunGaussEliminSerial<float>(&SA, &SB, &SX, row_size, col_size);
ReleaseMatrix<float>(&SA, row_size);
ReleaseVector<float>(&SB);
// ReleaseVector<float>(&SX);
}
MPI_Barrier(my_comm);
float** LocalA = nullptr;
float* LocalB = nullptr;
float* GlobalF = nullptr;
CreateMatrix<float>(&LocalA, sub_matrix_size, col_size);
CreateVector<float>(&LocalB, sub_matrix_size);
CreateVector<float>(&GlobalF, col_size + 1);
for (int r = 0; r < sub_matrix_size; r ++) {
VectorCopy<float>(&PA[r * psize + my_rank], &LocalA[r], col_size);
LocalB[r] = PB[r * psize + my_rank];
}
int* shift = new int[col_size];
for (int i = 0; i < col_size; i ++) {
shift[i] = i;
}
float lmax[4] = {0};
float* lmax_all_put = new float[psize * 4];
float* lmax_all_get = new float[psize * 4];
// 1. forward
for (int s = 0; s < sub_matrix_size; s ++) {
for (int p = 0; p < psize; p ++) {
// 1.1 find local max item
int mainIdx = s * psize + p;
if (my_rank < p) {
lmax[0] = 0;
for (int ss = s + 1; ss < sub_matrix_size; ss ++) {
for (int sc = mainIdx; sc < col_size; sc ++) {
if (fabs(LocalA[ss][sc]) > lmax[0]) {
lmax[0] = fabs(LocalA[ss][sc]);
lmax[1] = ss;
lmax[2] = sc;
lmax[3] = my_rank;
}
}
}
} else {
lmax[0] = 0;
for (int ss = s; ss < sub_matrix_size; ss ++) {
for (int sc = mainIdx; sc < col_size; sc ++) {
if (fabs(LocalA[ss][sc]) > lmax[0]) {
lmax[0] = fabs(LocalA[ss][sc]);
lmax[1] = ss;
lmax[2] = sc;
lmax[3] = my_rank;
}
}
}
}
// 1.3 copy local max item
for (int i = 0; i < psize; i ++) {
for (int j = 0; j < 4; j ++) {
lmax_all_put[i * 4 + j] = lmax[j];
}
}
MPI_Alltoall(lmax_all_put, 4, MPI_FLOAT, lmax_all_get, 4, MPI_FLOAT, my_comm);
// 1.4 compute global max item
lmax[0] = 0;
for (int i = 0; i < psize; i ++) {
if (fabs(lmax_all_get[i * 4]) > fabs(lmax[0])) {
for (int j = 0; j < 4; j ++) {
lmax[j] = lmax_all_get[i * 4 + j];
}
}
}
// 1.5 switch col
if ((int)lmax[2] != mainIdx) {
for (int r = 0; r < sub_matrix_size; r ++) {
auto buf = LocalA[r][mainIdx];
LocalA[r][mainIdx] = LocalA[r][(int)lmax[2]];
LocalA[r][(int)lmax[2]] = buf;
}
auto buf = shift[mainIdx];
shift[mainIdx] = shift[(int)lmax[2]];
shift[(int)lmax[2]] = buf;
}
// 1.6 switch row
if ((my_rank == p) && (lmax[3] == p)) {
if ((int)lmax[1] != s) {
for (int c = 0; c < col_size; c ++) {
auto buf = LocalA[s][c];
LocalA[s][c] = LocalA[(int)lmax[1]][c];
LocalA[(int)lmax[1]][c] = buf;
}
auto buf = LocalB[s];
LocalB[s] = LocalB[(int)lmax[1]];
LocalB[(int)lmax[1]] = buf;
}
} else if (my_rank == p || my_rank == (int)lmax[3]) {
float* putTmpA = nullptr;
float* getTmpA = nullptr;
CreateVector<float>(&putTmpA, col_size + 1);
CreateVector<float>(&getTmpA, col_size + 1);
MPI_Status status;
if (my_rank == p) {
// recv
VectorCopy<float>(&LocalA[s], &putTmpA, col_size);
putTmpA[col_size] = LocalB[s];
MPI_Recv(getTmpA, col_size + 1, MPI_FLOAT, (int)lmax[3], (int)lmax[3], my_comm, &status);
MPI_Send(putTmpA, col_size + 1, MPI_FLOAT, (int)lmax[3], my_rank, my_comm);
VectorCopy<float>(&getTmpA, &LocalA[s], col_size);
LocalB[s] = getTmpA[col_size];
}
if (my_rank == (int)lmax[3]) {
// send
VectorCopy<float>(&LocalA[(int)lmax[1]], &putTmpA, col_size);
putTmpA[col_size] = LocalB[(int)lmax[1]];
MPI_Send(putTmpA, col_size + 1, MPI_FLOAT, p, my_rank, my_comm);
MPI_Recv(getTmpA, col_size + 1, MPI_FLOAT, p, p, my_comm, &status);
VectorCopy<float>(&getTmpA, &LocalA[(int)lmax[1]], col_size);
LocalB[(int)lmax[1]] = getTmpA[col_size];
}
ReleaseVector<float>(&putTmpA);
ReleaseVector<float>(&getTmpA);
}
// 1.7 compute main line
if (my_rank == p) {
for (int c = mainIdx + 1; c < col_size; c ++) {
LocalA[s][c] = LocalA[s][c] / LocalA[s][mainIdx];
}
LocalB[s] = LocalB[s] / LocalA[s][mainIdx];
LocalA[s][mainIdx] = 1;
VectorCopy<float>(&LocalA[s], &GlobalF, col_size);
GlobalF[col_size] = LocalB[s];
}
MPI_Bcast(GlobalF, col_size + 1, MPI_FLOAT, p, my_comm);
// 1.8 compute sub matrix
int start_row = (my_rank <= p) ? s + 1 : s;
for (int r = start_row; r < sub_matrix_size; r ++) {
for (int c = mainIdx + 1; c < col_size; c ++) {
LocalA[r][c] -= GlobalF[c] * LocalA[r][mainIdx];
}
LocalB[r] -= GlobalF[col_size] * LocalA[r][mainIdx];
LocalA[r][mainIdx] = 0;
}
}
}
MPI_Barrier(my_comm);
// 2. backward
float* sum = new float[sub_matrix_size];
for (int s = 0; s < sub_matrix_size; s ++) {
sum[s] = 0.0;
}
for (int s = sub_matrix_size - 1; s >= 0; s --) {
for (int p = psize - 1; p >= 0; p --) {
if (my_rank == p) {
PX[s * psize + p] = (LocalB[s] - sum[s]) / LocalA[s][s * psize + p];
MPI_Bcast(&PX[s * psize + p], 1, MPI_FLOAT, p, my_comm);
for (int ss = 0; ss < sub_matrix_size; ss ++) {
sum[ss] += LocalA[ss][s * psize + p] * PX[s * psize + p];
}
} else {
MPI_Bcast(&PX[s * psize + p], 1, MPI_FLOAT, p, my_comm);
int end_row = (my_rank > p) ? s - 1 : s;
for (int ss = 0; ss <= end_row; ss ++) {
sum[ss] += LocalA[ss][s * psize + p] * PX[s * psize + p];
}
// std::cout << "* PX=" << PX[s * psize + p] << " end_row:" << end_row
// << " sum=" << sum[end_row - 1] << std::endl;
}
MPI_Barrier(my_comm);
}
}
// VectorPrint<float>(&PX, "Parallel-X", col_size);
if (my_rank == 0) {
float* SortX = nullptr;
CreateVector<float>(&SortX, col_size);
for (int r = 0; r < col_size; r ++) {
for (int i = 0; i < col_size; i ++) {
if (shift[i] == r) {
SortX[r] = PX[i];
}
}
}
VectorCopy<float>(&SortX, &PX, col_size);
// VectorPrint<float>(&PX, "Parallel-X", col_size);
if (VectorCompare<float>(&SX, &PX, col_size)) {
std::cout << "* Serial vs Parallel pass !" << std::endl;
}
ReleaseVector<float>(&SX);
ReleaseVector<float>(&SortX);
}
delete [] shift;
delete [] lmax_all_get;
delete [] lmax_all_put;
delete [] sum;
ReleaseMatrix<float>(&PA, row_size);
ReleaseMatrix<float>(&LocalA, sub_matrix_size);
ReleaseVector<float>(&PB);
ReleaseVector<float>(&LocalB);
ReleaseVector<float>(&PX);
ReleaseVector<float>(&GlobalF);
}
// 22.1 FFT
typedef struct {
double r;
double i;
} complex_t;
complex_t ComplexMult(complex_t comp_a, complex_t comp_b) {
complex_t comp_c;
comp_c.r = comp_a.r * comp_b.r - comp_a.i * comp_b.i;
comp_c.i = comp_a.r * comp_b.i + comp_a.i * comp_b.r;
return comp_c;
}
complex_t ComplexAdd(complex_t comp_a, complex_t comp_b) {
complex_t comp_c;
comp_c.r = comp_a.r + comp_b.r;
comp_c.i = comp_a.i + comp_b.i;
return comp_c;
}
complex_t ComplexSub(complex_t comp_a, complex_t comp_b) {
complex_t comp_c;
comp_c.r = comp_a.r - comp_b.r;
comp_c.i = comp_a.i - comp_b.i;
return comp_c;
}
void ComplexInit(complex_t** comp_a, int vec_size, int init_type=0) {
auto& vec_a = *(comp_a);
for (int c = 0; c < vec_size; c ++) {
if (init_type == 1) {
vec_a[c].r = rand() % 10 + 1;
vec_a[c].i = 0;
} else {
vec_a[c].r = cos((c * 2 * PI) / vec_size);
vec_a[c].i = sin((c * 2 * PI) / vec_size);
}
}
}
void ComplexCopy(complex_t** comp_a, complex_t** comp_b, int vec_size) {
auto& vec_a = *(comp_a);
auto& vec_b = *(comp_b);
for (int c = 0; c < vec_size; c ++) {
vec_b[c].r = vec_a[c].r;
vec_b[c].i = vec_a[c].i;
}
}
void ComplexPrint(complex_t** comp_a, std::string name, int vec_size) {
auto& vec_a = *(comp_a);
std::cout << "* ComplexPrint " << name << std::endl;
for (int c = 0; c < vec_size; c ++) {
std::cout << "(" << vec_a[c].r << "," << vec_a[c].i << ") ";
}
std::cout << std::endl;
}
bool ComplexCompare(complex_t** comp_a, complex_t** comp_b, int vec_size) {
auto& vec_a = *(comp_a);
auto& vec_b = *(comp_b);
for (int c = 0; c < vec_size; c ++) {
if ((vec_a[c].r != vec_b[c].r) || (vec_a[c].i != vec_b[c].i)) {
std::cout << "* Vector compare failed with "
<< "(" << vec_a[c].r << "," << vec_a[c].i << ") "
<< "(" << vec_b[c].r << "," << vec_b[c].i << ") " << std::endl;
return false;
}
}
return true;
}
void CreateFftParallel(int& my_rank, int& psize, MPI_Comm my_comm) {
int n = 1024;
complex_t* comp_vec_a = new complex_t[n];
complex_t* comp_vec_pa = new complex_t[n];
complex_t* comp_vec_b = new complex_t[n];
complex_t* comp_vec_w = new complex_t[n * 2];
ComplexInit(&comp_vec_a, n, 1);
ComplexCopy(&comp_vec_a, &comp_vec_pa, n);
ComplexInit(&comp_vec_w, 2 * n);
if (my_rank == 0) {
// ComplexPrint(&comp_vec_a, "Init-A", n);
// ComplexPrint(&comp_vec_w, "Init-W", 2 * n);
for (int s = log(n) / log(2) - 1; s >= 0; s --) {
int part = pow(2, s);
int heap = n / part;
int index_w = heap / 2;
// std::cout << "* Part " << s << " " << part << std::endl;
for (int c = 0; c < n; c ++) {
int mod_p = c % part;
int mod_2p = c % (2 * part);
if (mod_p == mod_2p) {
int sub_index_w = c % part;
complex_t tmp_a = comp_vec_a[c];
comp_vec_a[c] = ComplexAdd(comp_vec_a[c], comp_vec_a[c + part]);
comp_vec_a[c + part] = ComplexSub(tmp_a, comp_vec_a[c + part]);
comp_vec_a[c + part] = ComplexMult(comp_vec_a[c + part], comp_vec_w[sub_index_w * index_w]);
}
}
}
// ComplexPrint(&comp_vec_a, "Serial-A", n);
}
MPI_Barrier(my_comm);
int m = n / psize;
// 1.
for (int s = log(n) / log(2) - 1; s >= log(m) / log(2); s --) {
int part = pow(2, s);
int heap = n / part;
int index_w = heap / 2;
int startPos = my_rank * m;
int mod_p = startPos % part;
int mod_2p = startPos % (2 * part);
// std::cout << "* Rank " << my_rank << " Part " << s << " " << part << std::endl;
if (mod_p == mod_2p) {
MPI_Status status;
int backPos = (my_rank * m + part);
MPI_Send(&comp_vec_pa[startPos], m * 2, MPI_DOUBLE, backPos / m, my_rank, my_comm);
MPI_Recv(&comp_vec_pa[backPos], m * 2, MPI_DOUBLE, backPos / m, backPos / m, my_comm, &status);
for (int c = startPos; c < startPos + m; c ++) {
comp_vec_pa[c] = ComplexAdd(comp_vec_pa[c], comp_vec_pa[c + part]);
}
} else {
MPI_Status status;
int frontPos = (my_rank * m - part);
MPI_Recv(&comp_vec_pa[frontPos], m * 2, MPI_DOUBLE, frontPos / m, frontPos / m, my_comm, &status);
MPI_Send(&comp_vec_pa[startPos], m * 2, MPI_DOUBLE, frontPos / m, my_rank, my_comm);
for (int c = startPos; c < startPos + m; c ++) {
int sub_index_w = c % part;
comp_vec_pa[c] = ComplexSub(comp_vec_pa[c - part], comp_vec_pa[c]);
comp_vec_pa[c] = ComplexMult(comp_vec_pa[c], comp_vec_w[sub_index_w * index_w]);
}
}
}
// 2.
for (int s = log(m) / log(2) - 1; s >= 0; s --) {
int part = pow(2, s);
int heap = n / part;
int index_w = heap / 2;
int startPos = my_rank * m;
// std::cout << "* Rank " << my_rank << " Part " << s << " " << part << std::endl;
for (int c = startPos; c < startPos + m; c ++) {
int mod_p = c % part;
int mod_2p = c % (2 * part);
if (mod_p == mod_2p) {
int sub_index_w = c % part;
complex_t tmp_a = comp_vec_pa[c];
comp_vec_pa[c] = ComplexAdd(comp_vec_pa[c], comp_vec_pa[c + part]);
comp_vec_pa[c + part] = ComplexSub(tmp_a, comp_vec_pa[c + part]);
comp_vec_pa[c + part] = ComplexMult(comp_vec_pa[c + part], comp_vec_w[sub_index_w * index_w]);
}
}
}
// 3.
MPI_Gather(&comp_vec_pa[my_rank * m], m * 2, MPI_DOUBLE, comp_vec_b, m * 2, MPI_DOUBLE, 0, my_comm);
if (my_rank == 0) {
// ComplexPrint(&comp_vec_b, "Parallel-A", n);
if (ComplexCompare(&comp_vec_a, &comp_vec_b, n)) {
std::cout << "* Serial vs. Parallel pass !" << std::endl;
}
}
delete [] comp_vec_a;
delete [] comp_vec_pa;
delete [] comp_vec_b;
delete [] comp_vec_w;
}
}
| 29.326685 | 107 | 0.55635 | [
"vector"
] |
eb9401a645ee60acbd545bbdf88bdd8fb37cbf31 | 3,131 | hpp | C++ | function.hpp | KaixoCode/utilities | c1818fbd2d7904b19c5ea8cd52b62a76c398d1c9 | [
"MIT"
] | 2 | 2021-10-10T20:14:14.000Z | 2022-02-25T23:01:09.000Z | function.hpp | KaixoCode/utilities | c1818fbd2d7904b19c5ea8cd52b62a76c398d1c9 | [
"MIT"
] | null | null | null | function.hpp | KaixoCode/utilities | c1818fbd2d7904b19c5ea8cd52b62a76c398d1c9 | [
"MIT"
] | null | null | null | #pragma once
#include "utils.hpp"
namespace kaixo {
template<class Return, class ...Args>
class function_storage {
public:
constexpr virtual Return call(Args&&...) = 0;
std::size_t ref_count = 1;
};
template<class, class>
class typed_function_storage;
template<class Func, class Return, class ...Args>
class typed_function_storage<Func, Return(Args...)> : public function_storage<Return, Args...> {
public:
Func function;
constexpr typed_function_storage(Func&& f)
: function(std::forward<Func>(f)) {}
constexpr Return call(Args&&...args) override {
return function(std::forward<Args>(args)...);
}
};
template<class, class>
class member_function_storage;
template<class Object, class Return, class ...Args>
class member_function_storage<Object, Return(Args...)> : public function_storage<Return, Args...> {
public:
Return(Object::* function)(Args...);
Object& obj;
constexpr member_function_storage(Return(Object::* function)(Args...), Object& obj)
: function(function), obj(obj) {}
constexpr Return call(Args&&...args) override {
return (obj.*function)(std::forward<Args>(args)...);
}
};
template<class T>
class function;
template<class Return, class ...Args>
class function<Return(Args...)> {
public:
using result_type = Return;
using argument_types = std::tuple<Args...>;
constexpr function() = default;
template<class Type>
constexpr function(result_type(Type::* a)(Args...), Type& t)
: storage(new member_function_storage<Type, result_type(Args...)>{ a, t }) {}
template<std::invocable<Args...> Func>
constexpr function(Func&& t)
: storage(new typed_function_storage<Func, result_type(Args...)>{ std::forward<Func>(t) }) {}
constexpr function(const function& f)
: storage(f.storage) {
if (storage) storage->ref_count++;
}
constexpr function(function&& f)
: storage(f.storage) {
f.storage = nullptr;
}
constexpr ~function() { clean(); }
constexpr auto& operator=(const function& f) {
clean();
storage = f.storage;
if (storage)
storage->ref_count++;
return *this;
}
constexpr auto& operator=(function&& f) {
clean();
storage = f.storage;
f.storage = nullptr;
return *this;
}
constexpr inline result_type operator()(Args ...args) const {
return storage->call(std::forward<Args>(args)...);
}
constexpr inline operator bool() const { return storage; }
function_storage<result_type, Args...>* storage = nullptr;
private:
constexpr void clean() {
if (storage) {
storage->ref_count--;
if (storage->ref_count == 0)
delete storage;
}
}
};
} | 29.819048 | 105 | 0.561482 | [
"object"
] |
eb956a7e41afa545ee06d082f8f02b68db3f84bf | 6,815 | cpp | C++ | oneEngine/oneGame/source/after/terrain/edit/CTerrainAccessor.cpp | jonting/1Engine | f22ba31f08fa96fe6405ebecec4f374138283803 | [
"BSD-3-Clause"
] | 8 | 2017-12-08T02:59:31.000Z | 2022-02-02T04:30:03.000Z | oneEngine/oneGame/source/after/terrain/edit/CTerrainAccessor.cpp | jonting/1Engine | f22ba31f08fa96fe6405ebecec4f374138283803 | [
"BSD-3-Clause"
] | 2 | 2021-04-16T03:44:42.000Z | 2021-08-30T06:48:44.000Z | oneEngine/oneGame/source/after/terrain/edit/CTerrainAccessor.cpp | jonting/1Engine | f22ba31f08fa96fe6405ebecec4f374138283803 | [
"BSD-3-Clause"
] | 1 | 2021-04-16T02:09:54.000Z | 2021-04-16T02:09:54.000Z | #include "CTerrainAccessor.h"
#include "after/terrain/VoxelTerrain.h"
#include "after/terrain/system/TerrainRenderer.h"
#include "after/terrain/data/GameState.h"
#include "after/types/terrain/BlockType.h"
#include "after/entities/item/system/ItemTerraBlok.h"
#include "after/renderer/objects/grass/CTerraGrass.h"
using namespace Terrain;
CTerrainAccessor::CTerrainAccessor ( void )
{
m_terrain = CVoxelTerrain::GetActive();
if ( m_terrain == NULL ) {
//throw Core::NullReferenceException();
}
}
CTerrainAccessor::~CTerrainAccessor ( void )
{
}
//=========================================//
// Block Grabbers
//=========================================//
void CTerrainAccessor::GetBlockAtPosition( Vector3d const&, BlockTrackInfo & o_blockInfo )
{
if ( m_terrain ) {
// use terrain->Sampler for the block grabbing
throw Core::NotYetImplementedException();
}
else {
o_blockInfo.block.raw = 0;
o_blockInfo.block.block = EB_STONE;
o_blockInfo.valid = false;
}
}
void CTerrainAccessor::GetBlockAtPosition( RaycastHit const&, BlockTrackInfo & o_blockInfo )
{
if ( m_terrain ) {
// use terrain->Sampler for the block grabbing
throw Core::NotYetImplementedException();
}
else {
o_blockInfo.block.raw = 0;
o_blockInfo.block.block = EB_STONE;
o_blockInfo.valid = false;
}
}
Terrain::terra_b CTerrainAccessor::GetBlockAtPosition ( Vector3d const& )
{
if ( m_terrain ) {
// use terrain->Sampler for the block grabbing
throw Core::NotYetImplementedException();
}
else {
Terrain::terra_b block;
block.raw = 0;
block.block = EB_STONE;
return block;
}
}
Terrain::terra_b CTerrainAccessor::GetBlockAtPosition ( RaycastHit const& )
{
if ( m_terrain ) {
// use terrain->Sampler for the block grabbing
throw Core::NotYetImplementedException();
}
else {
Terrain::terra_b block;
block.raw = 0;
block.block = EB_STONE;
return block;
}
}
//=========================================//
// Block Setters
//=========================================//
bool CTerrainAccessor::SetBlockAtPosition ( Vector3d const&, const ushort )
{
// use terrain->Sampler for the block grabbing
throw Core::NotYetImplementedException();
}
bool CTerrainAccessor::SetBlockAtPosition ( Vector3d const&, const Terrain::terra_b )
{
// use terrain->Sampler for the block grabbing
throw Core::NotYetImplementedException();
}
bool CTerrainAccessor::SetBlockAtPosition ( BlockTrackInfo const&, const ushort )
{
// use terrain->Sampler for the block grabbing
throw Core::NotYetImplementedException();
}
bool CTerrainAccessor::SetBlockAtPosition ( BlockTrackInfo const&, const Terrain::terra_b )
{
// use terrain->Sampler for the block grabbing
throw Core::NotYetImplementedException();
}
//=========================================//
// Query
//=========================================//
bool CTerrainAccessor::BlockHasComponent ( const BlockTrackInfo& targetBlock )
{
return false;
}
bool CTerrainAccessor::BlockHasFoliage ( const BlockTrackInfo& targetBlock )
{
return false;
}
bool CTerrainAccessor::BlockHasGrass ( const BlockTrackInfo& targetBlock )
{
if ( !targetBlock.valid ) {
throw std::invalid_argument( "Invalid block passed in!" );
}
//
// Take block position, request a sector
uint32_t t_index;
Terrain::AreaGameState* t_data = NULL;
while ( t_data == NULL )
{
// Keep trying to grab the area for edit
try {
t_data = m_terrain->AquireAreaGamestate( targetBlock.center, t_index );
}
catch ( const std::exception& ) {
t_data = NULL;
}
}
// Break grass
bool result = t_data->grass_renderer->HasGrass( targetBlock.pBlock );
// Release working reference
m_terrain->ReleaseAreaGamestate( t_data, t_index );
// Return result
return result;
}
//=========================================//
// Editors
//=========================================//
void CTerrainAccessor::CompressBlock ( const BlockTrackInfo& targetBlock )
{
if ( !targetBlock.valid ) {
throw std::invalid_argument( "Invalid block passed in!" );
}
//
switch ( targetBlock.block.block ) {
case EB_SAND:
targetBlock.pBlock->block = EB_SANDSTONE;
break;
case EB_SNOW:
targetBlock.pBlock->block = EB_ICE;
break;
case EB_ASH:
targetBlock.pBlock->block = EB_CLAY;
break;
case EB_STONE:
targetBlock.pBlock->block = EB_GRAVEL;
break;
case EB_DEADSTONE:
targetBlock.pBlock->block = EB_CURSED_DEADSTONE; // nice try assholes :D
break;
}
m_terrain->Renderer->InvalidateAreaAt( targetBlock.center );
}
void CTerrainAccessor::DestroyBlock ( const BlockTrackInfo& targetBlock )
{
if ( !targetBlock.valid ) {
throw std::invalid_argument( "Invalid block passed in!" );
}
//
ItemTerraBlok* newBlok = NULL;
// Check for certain blocks that need to be changed
if ( targetBlock.pBlock->block == EB_GRASS )
targetBlock.pBlock->block = EB_DIRT;
// Now itemize it
if ( targetBlock.pBlock->block != EB_NONE )
newBlok = new ItemTerraBlok ( NULL, targetBlock.pBlock->block );
if ( newBlok )
{
newBlok->transform.position = targetBlock.center + Vector3d(1,1,1);
/*= (infoes.pBoob->position) - Vector3d(31,31,31) + (Vector3d(
ftype( ((infoes.b16index%2)*16)+((infoes.b8index%2)*8)+(infoes.b1index%8) ),
ftype( (((infoes.b16index/2)%2)*16)+(((infoes.b8index/2)%2)*8)+((infoes.b1index/8)%8) ),
ftype( ((infoes.b16index/4)*16)+((infoes.b8index/4)*8)+(infoes.b1index/64) ) ) * 2.0f );*/
newBlok->transform.SetDirty();
}
// And then turn the block to air
//SetBlock( infoes, EB_NONE );
//return (CWeaponItem*)(newBlok);
targetBlock.pBlock->block = EB_NONE;
m_terrain->Renderer->InvalidateAreaAt( targetBlock.center );
}
void CTerrainAccessor::TillBlock ( const BlockTrackInfo& targetBlock )
{
if ( !targetBlock.valid ) {
throw std::invalid_argument( "Invalid block passed in!" );
}
//
switch ( targetBlock.block.block ) {
case EB_DIRT:
targetBlock.pBlock->block = EB_TILLED_DIRT;
targetBlock.pBlock->normal_z_x = Terrain::_normal_unbias(0);
targetBlock.pBlock->normal_z_y = Terrain::_normal_unbias(0);
break;
case EB_GRASS:
targetBlock.pBlock->block = EB_DIRT;
break;
}
m_terrain->Renderer->InvalidateAreaAt( targetBlock.center );
}
void CTerrainAccessor::DestroyGrass ( const BlockTrackInfo& targetBlock )
{
if ( !targetBlock.valid ) {
throw std::invalid_argument( "Invalid block passed in!" );
}
//
// Take block position, request a sector
uint32_t t_index;
Terrain::AreaGameState* t_data = NULL;
while ( t_data == NULL )
{
// Keep trying to grab the area for edit
try {
t_data = m_terrain->AquireAreaGamestate( targetBlock.center, t_index );
}
catch ( const std::exception& ) {
t_data = NULL;
}
}
// Break grass
t_data->grass_renderer->BreakGrass( targetBlock.pBlock );
// Release working reference
m_terrain->ReleaseAreaGamestate( t_data, t_index );
}
| 26.830709 | 93 | 0.680411 | [
"transform"
] |
eb97f917c96fe5d46a76a78557dfbd1bb26accec | 3,640 | cpp | C++ | sysc/netlist.cpp | dcblack/technology_demonstrator | c8f3d2fc9a51fba0db3ed9a44c540f1249b59b10 | [
"Apache-2.0"
] | 4 | 2018-10-12T01:06:32.000Z | 2022-01-11T19:14:20.000Z | sysc/netlist.cpp | dcblack/technology_demonstrator | c8f3d2fc9a51fba0db3ed9a44c540f1249b59b10 | [
"Apache-2.0"
] | 1 | 2017-06-13T05:08:35.000Z | 2019-01-03T14:14:34.000Z | sysc/netlist.cpp | dcblack/technology_demonstrator | c8f3d2fc9a51fba0db3ed9a44c540f1249b59b10 | [
"Apache-2.0"
] | 1 | 2015-04-29T08:42:17.000Z | 2015-04-29T08:42:17.000Z | //BEGIN netlist.cpp (systemc)
///////////////////////////////////////////////////////////////////////////////
// $Info: Netlisting utility $
#include "netlist.h"
#include "report.h"
#include <typeinfo>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <vector>
#include <string>
using namespace sc_core;
using namespace std;
namespace {
// Declare string used as message identifier in SC_REPORT_* calls
char const * const MSGID = "/Doulos/example/netlist";
// Embed file version information into object to help forensics
char const * const RCSID = "(@)$Id: netlist.cpp 1.0 09/02/12 10:00 dcblack $";
// FILENAME VER DATE TIME USERNAME
////////////////////////////////////////////////////////////////////////////>>/
// Traverse the entire object subhierarchy
// below a given object
void scan_hierarchy(sc_object* obj,string indent) {
std::vector<sc_object*> child = obj->get_child_objects();
for ( unsigned int i=0; i != child.size(); i++ ) {
sc_port_base* iport = dynamic_cast<sc_port_base*>(child[i]);
if (iport != 0) {
for (size_t p=0; p!=iport->size(); ++p) {
sc_channel* chan = dynamic_cast<sc_channel*>(iport->get_interface(p));
if (chan != 0) {
REPORT_INFO( indent << ' ' << child[i]->basename() << ":" << child[i]->kind() << " -> " << chan->name());
}//endif
sc_prim_channel* prim = dynamic_cast<sc_prim_channel*>(iport->get_interface(p));
if (prim != 0) {
REPORT_INFO( indent << ' ' << child[i]->basename() << ":" << child[i]->kind() << " -> " << prim->name());
}//endif
sc_port_base* tiport = dynamic_cast<sc_port_base*>(iport->get_interface(p));
if (tiport != 0) {
REPORT_INFO( indent << ' ' << child[i]->basename() << ":" << child[i]->kind() << " -> " << tiport->name());
}//endif
sc_export_base* txport = dynamic_cast<sc_export_base*>(iport->get_interface(p));
if (txport != 0) {
REPORT_INFO( indent << ' ' << child[i]->basename() << ":" << child[i]->kind() << " -> " << txport->name());
}//endif
}//endfor
} else {
REPORT_INFO( indent << ' ' << child[i]->basename() << ":" << child[i]->kind() );
if ( child[i] ) {
scan_hierarchy(child[i],string("| ")+indent);
}//endif
}//endif
}//endfor
}//end scan_hierarchy()
}//endnamespace
namespace util {
void netlist(void) {
// Traverse the object hierarchy below each top-level object
std::vector<sc_object*> tops = sc_get_top_level_objects();
REPORT_INFO("Netlist:");
for ( unsigned int i=0; i != tops.size(); i++ ) {
if ( tops[i] ) {
REPORT_INFO( tops[i]->name() << ":" << tops[i]->kind() );
scan_hierarchy(tops[i],"+-");
}//endif
}//endfor
REPORT_INFO("End netlist");
}//end netlist()
}//endnamespace util
//------------------------------------------------------------------------------
//
// 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
//
// L<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.
//
//------------------------------------------------------------------------------
// The end!
| 39.139785 | 117 | 0.55 | [
"object",
"vector"
] |
eb98363f32cadeac58d6f63c6da23f33b186a431 | 1,650 | cpp | C++ | main.cpp | bartoszbielawski/convolution-benchmark | 749c05c8ddd7ce90ba0b979fb6f87a6f8308c049 | [
"MIT"
] | null | null | null | main.cpp | bartoszbielawski/convolution-benchmark | 749c05c8ddd7ce90ba0b979fb6f87a6f8308c049 | [
"MIT"
] | null | null | null | main.cpp | bartoszbielawski/convolution-benchmark | 749c05c8ddd7ce90ba0b979fb6f87a6f8308c049 | [
"MIT"
] | null | null | null | #include <vector>
#include <random>
#include <algorithm>
#include <array>
#include <cstdio>
#include "timediff.h"
#include "types.h"
using namespace std;
struct TestData
{
TestData(size_t noOfSamples): data(noOfSamples, 0), coeffs(noOfSamples, 0.0)
{
mt19937 mt;
uniform_real_distribution<sample> rng(-1.0, 1.0);
for_each(data.begin(), data.end(), [&](sample& x) {x = rng(mt);});
for_each(coeffs.begin(), coeffs.end(), [&](sample& x) {x = rng(mt);});
}
std::vector<sample> data;
std::vector<sample> coeffs;
};
const int iterations = 10000;
const int coeffs = 499;
double MACs = iterations * (double)coeffs * (double)coeffs;
void printInfo()
{
if (sizeof(int*) == 4)
printf("Mode: 32b\n");
if (sizeof(int*) == 8)
printf("Mode: 64b\n");
printf("sizeof(sample) = %d, sizeof(longSample) = %d\n", (int)sizeof(sample), (int)sizeof(longSample));
printf("Iterations: %d\n", iterations);
printf("Coeffs: %d\n", coeffs);
printf("MMACs: %9.3f\n", MACs / 1e6);
}
int main()
{
printInfo();
TestData t(coeffs);
for (auto& impl: Implementations::getInstance().getImplementations())
{
timediff td;
longSample result = 0.0;
for (int j = 0; j < iterations; ++j)
for (int i = 0; i < t.data.size(); ++i)
result += impl.function(t.data.data(), t.coeffs.data(), t.data.size(), i);
double t = td.get_diff();
printf("%s:\tUnrolled: %d SR: %d ForcedLong: %d\n", impl.name.c_str(), impl.unrolled, impl.separated, impl.forcedLong);
printf("\tTime: % 3.4f\tMMACs/s: % 9.3f\tResult: % 30.15Lf\n", t, MACs / t / 1e6, result);
}
}
| 24.626866 | 122 | 0.604242 | [
"vector"
] |
eb9977b11cc53c7bba3460064ab8c726670f08c7 | 6,430 | cpp | C++ | src/renderer.cpp | vikaschoudharycs097/SnakeGame | 63b30519a674340cb055824d08561639759c2949 | [
"MIT"
] | null | null | null | src/renderer.cpp | vikaschoudharycs097/SnakeGame | 63b30519a674340cb055824d08561639759c2949 | [
"MIT"
] | null | null | null | src/renderer.cpp | vikaschoudharycs097/SnakeGame | 63b30519a674340cb055824d08561639759c2949 | [
"MIT"
] | null | null | null | #include <iostream>
#include "renderer.h"
// Constructor
Renderer::Renderer(int w_width, int w_height, int g_width, int g_height):
_window_width(w_width), _window_height(w_height), _grid_width(g_width), _grid_height(g_height)
{
// Initilizating all subsystem of SDL
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
std::cerr << "SDL Error: " << SDL_GetError() << "\n";
}
// Creating SDL window
_window = SDL_CreateWindow("Snake Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
w_width, w_height, 0);
if (_window == nullptr)
{
std::cerr << "SDL Error: " << SDL_GetError() << "\n";
}
// Creating SDL renderer
_renderer = SDL_CreateRenderer(_window, -1, 0);
if (_renderer == nullptr)
{
std::cerr << "SDL Error: " << SDL_GetError() << "\n";
}
// Initilizating ttf
if (TTF_Init() == -1)
{
std::cerr << "TTF Error: " << TTF_GetError() << "\n";
}
}
// Copy Constructor
Renderer::Renderer(const Renderer &renderer):
_window_width(renderer._window_width), _window_height(renderer._window_height),
_grid_width(renderer._grid_width), _grid_height(renderer._grid_height)
{
// Creating SDL window
_window = SDL_CreateWindow("Snake Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
_window_width, _window_height, SDL_GetWindowFlags(renderer._window));
if (_window == nullptr)
{
std::cerr << "SDL Error: " << SDL_GetError() << "\n";
}
// Creating SDL renderer
_renderer = SDL_CreateRenderer(_window, -1, 0);
if (_renderer == nullptr)
{
std::cerr << "SDL Error: " << SDL_GetError() << "\n";
}
// Initilizating ttf
if (TTF_Init() == -1)
{
std::cerr << "TTF Error: " << TTF_GetError() << "\n";
}
}
// Move Constructor
Renderer::Renderer(Renderer &&renderer):
_window_width(renderer._window_width), _window_height(renderer._window_height),
_grid_width(renderer._grid_width), _grid_height(renderer._grid_height)
{
_window = renderer._window;
_renderer = renderer._renderer;
// Setting nullptr to dynamic part of renderer
renderer._window = nullptr;
renderer._renderer = nullptr;
}
// Destructor
Renderer::~Renderer()
{
// Cleaning font system
TTF_Quit();
// Destorying window
SDL_DestroyWindow(_window);
// Cleaning all subsystem
SDL_Quit();
}
void Renderer::renderWindow(Snake *snake, Rat *rat, const std::vector<Point<int>> &obstacle)
{
SDL_Rect rect;
rect.w = _grid_width;
rect.h = _grid_height;
// Clearing window
SDL_SetRenderDrawColor(_renderer, 0X1E, 0X1E, 0X1E, 0XFF);
SDL_RenderClear(_renderer);
// Render the food
rect.x = rat->getX() * rect.w; // Converting grid number into pixel
rect.y = rat->getY() * rect.h;
SDL_SetRenderDrawColor(_renderer, 0xFF, 0xCC, 0x00, 0xFF);
SDL_RenderFillRect(_renderer, &rect);
// Render the snake body
SDL_SetRenderDrawColor(_renderer, 0XFF, 0XFF, 0XFF, 0XFF);
for (auto &point: snake->getBody())
{
rect.x = point.x * rect.w;
rect.y = point.y * rect.h;
SDL_RenderFillRect(_renderer, &rect);
}
// Render the snake head
auto head = snake->getHead();
rect.x = static_cast<int>(head.x) * rect.w;
rect.y = static_cast<int>(head.y) * rect.h;
if (snake->isAlive())
{
SDL_SetRenderDrawColor(_renderer, 0X0, 0x7A, 0xCC, 0xFF);
}
else
{
SDL_SetRenderDrawColor(_renderer, 0XFF, 0X0, 0X0, 0XFF);
}
SDL_RenderFillRect(_renderer, &rect);
// Display obstacle
SDL_SetRenderDrawColor(_renderer, 0X0, 0x00, 0xCC, 0x44);
for (auto &point: obstacle)
{
rect.x = point.x * rect.w;
rect.y = point.y * rect.h;
SDL_RenderFillRect(_renderer, &rect);
}
// Update screen
SDL_RenderPresent(_renderer);
}
void Renderer::renderFont(const char *font_name, const char *text, int size)
{
// Clearing the window
SDL_SetRenderDrawColor(_renderer, 0X1E, 0X1E, 0X1E, 0XFF);
SDL_RenderClear(_renderer);
// Load font
TTF_Font *font = TTF_OpenFont(font_name, size);
if (font == nullptr)
{
std::cerr << "TTF Error: " << TTF_GetError() << "\n";
}
SDL_Color color = {255, 255, 255};
SDL_Surface *surface = TTF_RenderText_Solid(font, text, color);
if (surface == nullptr)
{
std::cerr << "SDL Error: " << SDL_GetError() << "\n";
}
SDL_Texture *texture = SDL_CreateTextureFromSurface(_renderer, surface);
if (texture == nullptr)
{
std::cerr << "SDL Error: " << SDL_GetError() << "\n";
}
SDL_Rect coor;
coor.x = _window_width / 5;
coor.y = _window_height / 5;
coor.w = _window_width - 2 * coor.x;
coor.h = _window_height - 2 * coor.y;
SDL_RenderCopy(_renderer, texture, NULL, &coor);
SDL_RenderPresent(_renderer);
SDL_Delay(3000);
SDL_FreeSurface(surface);
SDL_DestroyTexture(texture);
// Pointer to the TTF_Font to free
TTF_CloseFont(font);
}
void Renderer::updateWindowTitle(int score)
{
std::string title{"Score: " + std::to_string(score)};
SDL_SetWindowTitle(_window, title.c_str());
}
// Copy assignment operator
Renderer& Renderer::operator=(const Renderer &renderer)
{
_window_width = renderer._window_width;
_window_height = renderer._window_height;
_grid_width = renderer._grid_width;
_grid_height = renderer._grid_height;
// Creating SDL window
_window = SDL_CreateWindow("Snake Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
_window_width, _window_height, SDL_GetWindowFlags(renderer._window));
if (_window == nullptr)
{
std::cerr << "SDL Error: " << SDL_GetError() << "\n";
}
// Creating SDL renderer
_renderer = SDL_CreateRenderer(_window, -1, 0);
if (_renderer == nullptr)
{
std::cerr << "SDL Error: " << SDL_GetError() << "\n";
}
return *this;
}
// Move assignment operator
Renderer& Renderer::operator=(Renderer &&renderer)
{
_window_width = renderer._window_width;
_window_height = renderer._window_height;
_grid_width = renderer._grid_width;
_grid_height = renderer._grid_height;
_window = renderer._window;
_renderer = renderer._renderer;
renderer._window = nullptr;
renderer._renderer = nullptr;
return *this;
} | 27.835498 | 99 | 0.637792 | [
"render",
"vector"
] |
eb9ab48cae7c3c058a34545981919ff1bbe626dc | 5,517 | hpp | C++ | include/coruja/support/type_traits.hpp | romariorios/coruja | 275d1b05cdefd4d8e7665bb7bb37dbe15de3e9af | [
"BSL-1.0"
] | 13 | 2017-10-24T07:13:28.000Z | 2020-10-07T02:51:31.000Z | include/coruja/support/type_traits.hpp | romariorios/coruja | 275d1b05cdefd4d8e7665bb7bb37dbe15de3e9af | [
"BSL-1.0"
] | 1 | 2019-10-30T21:50:44.000Z | 2019-11-06T19:35:23.000Z | include/coruja/support/type_traits.hpp | romariorios/coruja | 275d1b05cdefd4d8e7665bb7bb37dbe15de3e9af | [
"BSL-1.0"
] | 5 | 2018-09-19T20:29:07.000Z | 2020-03-20T18:12:09.000Z |
// Copyright Ricardo Calheiros de Miranda Cosme 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <type_traits>
#include <boost/hof/is_invocable.hpp>
#include <range/v3/range_concepts.hpp>
namespace coruja {
//For std < c++17
template<typename... Ts> struct make_void { typedef void type;};
template<typename... Ts> using void_t = typename make_void<Ts...>::type;
template<typename Ret, typename F, typename... Args>
using enable_if_is_invocable_t = typename std::enable_if<
boost::hof::is_invocable<F, Args...>::value,
Ret>::type;
template<typename Ret, typename F, typename... Args>
using enable_if_is_not_invocable_t = typename std::enable_if<
!boost::hof::is_invocable<F, Args...>::value,
Ret>::type;
//For std < c++14
template<typename T>
using remove_reference_t = typename std::remove_reference<T>::type;
template<bool v, typename T = void>
using enable_if_t = typename std::enable_if<v, T>::type;
template<typename T>
using result_of_t = typename std::result_of<T>::type;
template<typename T, typename = void>
struct is_observable : std::false_type {};
/*
Observable
Immediately notifies observers interested in a specific action that
changes the state of an object of type T. There has to be at least one
observable action.
Requirements:
`Observable::observed_t`
Type of the object to be observed.
`observed_t observed() const noexcept`
Returns the observed object.
For each observable action, there has to be a method like below to
register a callback 'cbk' to be called when the action occurs. An
object that represents the connection between callback and
observable must be returned.
template<typename Callable>
connection action(Callable cbk)
`Connection` represents a connection between a callback and an
Observable. Requirements:
void disconnect()
Disconnect the callback from the Observable.
An observable must be default constructible.
*/
template<typename T>
struct is_observable<T, void_t<
typename T::observed_t,
decltype(
// std::declval<typename T::observed_t&>() =
std::declval<const T>().observed(),
(void)0)
>
> : std::integral_constant<bool,
std::is_default_constructible<T>::value>
{};
/*
ObservableObject
Refines the Observable concept and represents an observable object of
type `T` that has one general observable action: `after_change`.
Requirements:
template<typename Callable>
after_change_connection_t after_change(Callable cbk)
Registers a callback `cbk` to be notified when a convertible object
to `T` is assigned to the Observable. The signature of callback
should be equivalent to the following:
void(const Observable::observed_t&)
`Observable::after_change_connection_t`
Type of the connection returned by `after_change`.
*/
template<typename T, typename = void>
struct _is_observable_object : std::false_type {};
template<typename T>
struct _is_observable_object<T, void_t<
typename T::after_change_connection_t,
decltype(
std::declval<typename T::after_change_connection_t&>() =
std::declval<T&>().after_change(std::declval<void(*)(const typename T::observed_t&)>()),
(void)0)
>
> : std::integral_constant<bool,
is_observable<T>::value>
{};
template<typename T>
using is_observable_object = _is_observable_object<remove_reference_t<T>>;
/*
ObservableErasableRange
Refines the Observable and Range concept allowing to observe
insertion and removal of elements.
Requirements:
template<typename Callable>
for_each_connection_t for_each(Callable cbk)
Registers a callback `cbk` to be called for each element in the
container. The signature of callback should be equivalent to the
following:
void(Observable&, Observable::iterator)
or
void(ranges::range_reference_t<Observable>)
Registers a callback `cbk` to be called when an element in the
container is erased. The signature of callback should be equivalent
to the following:
void(Observable&, Observable::iterator)
or
void(ranges::range_reference_t<Observable>)
`Observable::before_erase_connection_t`
Type of the connection returned by `before_erase`.
*/
template<typename T, typename = void>
struct is_observable_erasable_range : std::false_type {};
template<typename T>
struct is_observable_erasable_range<T, void_t<
typename T::for_each_connection_t,
typename T::before_erase_connection_t,
decltype(
std::declval<typename T::for_each_connection_t&>() =
std::declval<T&>().for_each
(std::declval<void(*)(T&, decltype(begin(std::declval<T>())))>()),
std::declval<typename T::for_each_connection_t&>() =
std::declval<T&>().for_each
(std::declval<void(*)(decltype(*begin(std::declval<T>())))>()),
std::declval<typename T::before_erase_connection_t&>() =
std::declval<T>().before_erase
(std::declval<void(*)(T&, decltype(begin(std::declval<T>())))>()),
std::declval<typename T::before_erase_connection_t&>() =
std::declval<T&>().before_erase
(std::declval<void(*)(decltype(*begin(std::declval<T>())))>()),
(void)0)
>
> : std::integral_constant<bool,
is_observable<T>::value &&
ranges::Range<T>::value>
{};
}
| 30.994382 | 96 | 0.703281 | [
"object"
] |
eba63551dfaceb516c4ea8314a7b5ce3dd1dea49 | 2,485 | cxx | C++ | Wrapping/CSwig/CommonA/wrap_itkDenseFiniteDifferenceImageFilter_3D.cxx | kiranhs/ITKv4FEM-Kiran | 0e4ab3b61b5fc4c736f04a73dd19e41390f20152 | [
"BSD-3-Clause"
] | 1 | 2018-04-15T13:32:43.000Z | 2018-04-15T13:32:43.000Z | Wrapping/CSwig/CommonA/wrap_itkDenseFiniteDifferenceImageFilter_3D.cxx | kiranhs/ITKv4FEM-Kiran | 0e4ab3b61b5fc4c736f04a73dd19e41390f20152 | [
"BSD-3-Clause"
] | null | null | null | Wrapping/CSwig/CommonA/wrap_itkDenseFiniteDifferenceImageFilter_3D.cxx | kiranhs/ITKv4FEM-Kiran | 0e4ab3b61b5fc4c736f04a73dd19e41390f20152 | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: wrap_itkDenseFiniteDifferenceImageFilter_3D.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkImage.h"
#include "itkDenseFiniteDifferenceImageFilter.h"
#include "itkVector.h"
#ifdef CABLE_CONFIGURATION
#include "itkCSwigImages.h"
#include "itkCSwigMacros.h"
namespace _cable_
{
const char* const group =
ITK_WRAP_GROUP(itkDenseFiniteDifferenceImageFilter_3D);
namespace wrappers
{
// vector image wrapped Filters
ITK_WRAP_OBJECT2(DenseFiniteDifferenceImageFilter,
image::VF3, image::VF3,
itkDenseFiniteDifferenceImageFilterVF3VF3);
//===========3D Wrapped Filters==============
ITK_WRAP_OBJECT2(DenseFiniteDifferenceImageFilter, image::F3 , image::F3 , itkDenseFiniteDifferenceImageFilterF3F3 );
ITK_WRAP_OBJECT2(DenseFiniteDifferenceImageFilter, image::D3 , image::D3 , itkDenseFiniteDifferenceImageFilterD3D3 );
ITK_WRAP_OBJECT2(DenseFiniteDifferenceImageFilter, image::UC3, image::F3, itkDenseFiniteDifferenceImageFilterUC3F3);
ITK_WRAP_OBJECT2(DenseFiniteDifferenceImageFilter, image::US3, image::F3, itkDenseFiniteDifferenceImageFilterUS3F3);
ITK_WRAP_OBJECT2(DenseFiniteDifferenceImageFilter, image::UI3, image::F3, itkDenseFiniteDifferenceImageFilterUI3F3);
ITK_WRAP_OBJECT2(DenseFiniteDifferenceImageFilter, image::SC3, image::F3, itkDenseFiniteDifferenceImageFilterSC3F3);
ITK_WRAP_OBJECT2(DenseFiniteDifferenceImageFilter, image::SS3, image::F3, itkDenseFiniteDifferenceImageFilterSS3F3);
ITK_WRAP_OBJECT2(DenseFiniteDifferenceImageFilter, image::SI3, image::F3, itkDenseFiniteDifferenceImageFilterSI3F3);
ITK_WRAP_OBJECT2(DenseFiniteDifferenceImageFilter, image::F3 , image::VF3 ,itkDenseFiniteDifferenceImageFilterF3VF3);
ITK_WRAP_OBJECT2(DenseFiniteDifferenceImageFilter, image::US3, image::VF3, itkDenseFiniteDifferenceImageFilterUS3VF3);
}
}
#endif
| 48.72549 | 122 | 0.736821 | [
"vector",
"3d"
] |
ebacb223a5ed2449049e336270d94b5728cb305a | 10,658 | cc | C++ | views/controls/table/native_table_gtk.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | 11 | 2015-03-20T04:08:08.000Z | 2021-11-15T15:51:36.000Z | views/controls/table/native_table_gtk.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | views/controls/table/native_table_gtk.cc | rwatson/chromium-capsicum | b03da8e897f897c6ad2cda03ceda217b760fd528 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009 The Chromium Authors. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.
#include "views/controls/table/native_table_gtk.h"
#include "app/gfx/gtk_util.h"
#include "base/string_util.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "views/controls/table/table_view2.h"
#include "views/controls/table/table_view_observer.h"
#include "views/widget/widget.h"
namespace views {
////////////////////////////////////////////////////////////////////////////////
// NativeTableGtk, public:
NativeTableGtk::NativeTableGtk(TableView2* table)
: table_(table),
gtk_model_(NULL),
tree_view_(NULL),
tree_selection_(NULL) {
// Associates the actual GtkWidget with the table so the table is the one
// considered as having the focus (not the wrapper) when the HWND is
// focused directly (with a click for example).
set_focus_view(table);
}
NativeTableGtk::~NativeTableGtk() {
}
////////////////////////////////////////////////////////////////////////////////
// NativeTableGtk, NativeTableWrapper implementation:
int NativeTableGtk::GetRowCount() const {
if (!tree_view_)
return 0;
GtkTreeIter iter;
if (!gtk_tree_model_get_iter_first(GTK_TREE_MODEL(gtk_model_), &iter))
return 0; // Empty tree.
int count = 1;
while (gtk_tree_model_iter_next(GTK_TREE_MODEL(gtk_model_), &iter))
count++;
return count;
}
View* NativeTableGtk::GetView() {
return this;
}
void NativeTableGtk::SetFocus() {
// Focus the associated widget.
Focus();
}
gfx::NativeView NativeTableGtk::GetTestingHandle() const {
// Note that we are returning the tree view, not the scrolled window as
// arguably the tests need to access the tree view.
return GTK_WIDGET(tree_view_);
}
void NativeTableGtk::InsertColumn(const TableColumn& column, int index) {
NOTIMPLEMENTED();
}
void NativeTableGtk::RemoveColumn(int index) {
NOTIMPLEMENTED();
}
int NativeTableGtk::GetColumnWidth(int column_index) const {
NOTIMPLEMENTED();
return -1;
}
void NativeTableGtk::SetColumnWidth(int column_index, int width) {
NOTIMPLEMENTED();
}
int NativeTableGtk::GetSelectedRowCount() const {
return gtk_tree_selection_count_selected_rows(tree_selection_);
}
int NativeTableGtk::GetFirstSelectedRow() const {
int result = -1;
GList* selected_rows =
gtk_tree_selection_get_selected_rows(tree_selection_, NULL);
if (g_list_length(selected_rows) > 0) {
GtkTreePath* tree_path =
static_cast<GtkTreePath*>(g_list_first(selected_rows)->data);
gint* indices = gtk_tree_path_get_indices(tree_path);
CHECK(indices);
result = indices[0];
}
g_list_foreach(selected_rows, reinterpret_cast<GFunc>(gtk_tree_path_free),
NULL);
g_list_free(selected_rows);
return result;
}
int NativeTableGtk::GetFirstFocusedRow() const {
NOTIMPLEMENTED();
return -1;
}
bool NativeTableGtk::IsRowFocused(int model_row) const {
NOTIMPLEMENTED();
return false;
}
void NativeTableGtk::ClearRowFocus() {
NOTIMPLEMENTED();
}
void NativeTableGtk::ClearSelection() {
gtk_tree_selection_unselect_all(tree_selection_);
}
void NativeTableGtk::SetSelectedState(int model_row, bool state) {
GtkTreeIter iter;
if (!gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(gtk_model_), &iter, NULL,
model_row)) {
NOTREACHED();
return;
}
if (state)
gtk_tree_selection_select_iter(tree_selection_, &iter);
else
gtk_tree_selection_unselect_iter(tree_selection_, &iter);
}
void NativeTableGtk::SetFocusState(int model_row, bool state) {
NOTIMPLEMENTED();
}
bool NativeTableGtk::IsRowSelected(int model_row) const {
GtkTreeIter iter;
if (!gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(gtk_model_), &iter, NULL,
model_row)) {
NOTREACHED();
return false;
}
return gtk_tree_selection_iter_is_selected(tree_selection_, &iter);
}
void NativeTableGtk::OnRowsChanged(int start, int length) {
GtkTreeIter iter;
if (!gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(gtk_model_), &iter, NULL,
start)) {
NOTREACHED();
return;
}
for (int i = start; i < start + length; i++) {
GtkTreePath* tree_path =
gtk_tree_model_get_path(GTK_TREE_MODEL(gtk_model_), &iter);
gtk_tree_model_row_changed(GTK_TREE_MODEL(gtk_model_), tree_path, &iter);
gtk_tree_path_free(tree_path);
SetRowData(i, &iter);
gboolean r = gtk_tree_model_iter_next(GTK_TREE_MODEL(gtk_model_), &iter);
DCHECK(r || i == start + length - 1); // (start + length - 1) might be the
// last item, in which case we won't
// get a next iterator.
}
}
void NativeTableGtk::OnRowsAdded(int start, int length) {
GtkTreeIter iter;
gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(gtk_model_), &iter,
NULL, start);
for (int i = start; i < start + length; i++) {
gtk_list_store_append(gtk_model_, &iter);
SetRowData(i, &iter);
}
}
void NativeTableGtk::OnRowsRemoved(int start, int length) {
GtkTreeIter iter;
gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(gtk_model_), &iter,
NULL, start);
for (int i = start; i < start + length; i++) {
gboolean r = gtk_list_store_remove(gtk_model_, &iter);
DCHECK(r || i == start + length - 1); // (start + length - 1) might be the
// last item, in which case we won't
// get a next iterator.
}
}
gfx::Rect NativeTableGtk::GetBounds() const {
NOTIMPLEMENTED();
return gfx::Rect();
}
void NativeTableGtk::CreateNativeControl() {
if (table_->type() == CHECK_BOX_AND_TEXT) {
// We are not supporting checkbox in tables on Gtk yet, as it is not used
// in Chrome at this point in time
NOTREACHED();
}
tree_view_ = GTK_TREE_VIEW(gtk_tree_view_new());
// The tree view must be wrapped in a scroll-view to be scrollable.
GtkWidget* scrolled = gtk_scrolled_window_new(NULL, NULL);
gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolled),
GTK_SHADOW_ETCHED_IN);
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
gtk_container_add(GTK_CONTAINER(scrolled), GTK_WIDGET(tree_view_));
NativeControlCreated(scrolled);
// native_view() is now available.
// Set the selection mode, single or multiple.
tree_selection_ = gtk_tree_view_get_selection(tree_view_);
gtk_tree_selection_set_mode(
tree_selection_, table_->single_selection() ? GTK_SELECTION_SINGLE :
GTK_SELECTION_MULTIPLE);
// Don't make the header clickable until we support sorting.
gtk_tree_view_set_headers_clickable(tree_view_, FALSE);
// Show horizontal separator lines only.
gtk_tree_view_set_grid_lines(tree_view_, GTK_TREE_VIEW_GRID_LINES_HORIZONTAL);
int gtk_column_index = 0;
size_t column_index = 0;
if (table_->type() == ICON_AND_TEXT) {
InsertIconAndTextColumn(table_->GetVisibleColumnAt(0), 0);
column_index = 1;
gtk_column_index = 2;
}
for (; column_index < table_->GetVisibleColumnCount();
++column_index, gtk_column_index++) {
InsertTextColumn(table_->GetVisibleColumnAt(column_index),
gtk_column_index);
}
// Now create the model.
int column_count = table_->GetVisibleColumnCount();
scoped_array<GType> types(
new GType[column_count + 1]); // One extra column for the icon (if any).
for (int i = 0; i < column_count + 1; i++)
types[i] = G_TYPE_STRING;
if (table_->type() == ICON_AND_TEXT) {
types[0] = GDK_TYPE_PIXBUF;
gtk_model_ = gtk_list_store_newv(column_count + 1, types.get());
} else {
gtk_model_ = gtk_list_store_newv(column_count, types.get());
}
gtk_tree_view_set_model(tree_view_, GTK_TREE_MODEL(gtk_model_));
g_object_unref(gtk_model_); // Now the tree owns the model.
// Updates the gtk model with the actual model.
if (table_->model())
OnRowsAdded(0, table_->model()->RowCount());
}
void NativeTableGtk::InsertTextColumn(const TableColumn& column, int index) {
GtkCellRenderer* renderer = gtk_cell_renderer_text_new();
gtk_tree_view_insert_column_with_attributes(tree_view_, -1,
WideToUTF8(column.title).c_str(),
renderer, "text", index, NULL);
}
void NativeTableGtk::InsertIconAndTextColumn(const TableColumn& column,
int index) {
// If necessary we could support more than 1 icon and text column and we could
// make it so it does not have to be the 1st column.
DCHECK(index == 0) << "The icon and text column can only be the first column "
"at this point.";
GtkTreeViewColumn* gtk_column = gtk_tree_view_column_new();
gtk_tree_view_column_set_title(gtk_column, WideToUTF8(column.title).c_str());
GtkCellRenderer* renderer = gtk_cell_renderer_pixbuf_new();
gtk_tree_view_column_pack_start(gtk_column, renderer, FALSE);
// First we set the icon renderer at index 0.
gtk_tree_view_column_set_attributes(gtk_column, renderer, "pixbuf", 0, NULL);
renderer = gtk_cell_renderer_text_new();
gtk_tree_view_column_pack_start(gtk_column, renderer, TRUE);
// Then we set the text renderer at index 1.
gtk_tree_view_column_set_attributes(gtk_column, renderer, "text", 1, NULL);
gtk_tree_view_append_column(tree_view_, gtk_column);
}
void NativeTableGtk::SetRowData(int row_index, GtkTreeIter* iter) {
int gtk_column_index = 0;
if (table_->type() == ICON_AND_TEXT) {
GdkPixbuf* icon = GetModelIcon(row_index);
gtk_list_store_set(gtk_model_, iter, 0, icon, -1);
g_object_unref(icon);
gtk_column_index++;
}
for (size_t i = 0; i < table_->GetVisibleColumnCount();
++i, ++gtk_column_index) {
std::string text =
WideToUTF8(table_->model()->GetText(row_index,
table_->GetVisibleColumnAt(i).id));
gtk_list_store_set(gtk_model_, iter, gtk_column_index, text.c_str(), -1);
}
}
GdkPixbuf* NativeTableGtk::GetModelIcon(int row) {
SkBitmap icon = table_->model()->GetIcon(row);
return gfx::GdkPixbufFromSkBitmap(&icon);
}
// static
NativeTableWrapper* NativeTableWrapper::CreateNativeWrapper(TableView2* table) {
return new NativeTableGtk(table);
}
} // namespace views
| 33.410658 | 80 | 0.676956 | [
"model"
] |
ebada41d865aacd98776102bf396c530f07abdf9 | 255 | cpp | C++ | src/animation/composite.cpp | AnisimoffNikita/course_project_cg | 257e3dae1e92c80d1495df1f3e83b2bf2de61af9 | [
"Apache-2.0"
] | null | null | null | src/animation/composite.cpp | AnisimoffNikita/course_project_cg | 257e3dae1e92c80d1495df1f3e83b2bf2de61af9 | [
"Apache-2.0"
] | null | null | null | src/animation/composite.cpp | AnisimoffNikita/course_project_cg | 257e3dae1e92c80d1495df1f3e83b2bf2de61af9 | [
"Apache-2.0"
] | null | null | null | #include "composite.h"
Composite::Composite()
{
}
void Composite::draw(std::unique_ptr<Renderer> &)
{
}
void Composite::transform(Transformation &)
{
}
bool Composite::isCamera()
{
return false;
}
bool Composite::isLight()
{
return false;
}
| 10.2 | 49 | 0.67451 | [
"transform"
] |
ebb1fdcb072cd558e9c26f0987cecde0f754a260 | 32,599 | cpp | C++ | C++/JPClassification.cpp | hai-vr/Japanese-Handwriting-vrware | 82ad60e9853585e5483266a9b3691636eb773b92 | [
"MIT"
] | 8 | 2021-11-21T18:53:09.000Z | 2022-02-21T22:53:54.000Z | C++/JPClassification.cpp | hai-vr/Japanese-Handwriting-vrware | 82ad60e9853585e5483266a9b3691636eb773b92 | [
"MIT"
] | null | null | null | C++/JPClassification.cpp | hai-vr/Japanese-Handwriting-vrware | 82ad60e9853585e5483266a9b3691636eb773b92 | [
"MIT"
] | 1 | 2021-11-22T16:53:38.000Z | 2021-11-22T16:53:38.000Z | /*
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
input_1 (InputLayer) [(None, 64, 64, 1)] 0
__________________________________________________________________________________________________
rescaling (Rescaling) (None, 64, 64, 1) 0 input_1[0][0]
__________________________________________________________________________________________________
conv2d (Conv2D) (None, 32, 32, 144) 720 rescaling[0][0]
__________________________________________________________________________________________________
activation (Activation) (None, 32, 32, 144) 0 conv2d[0][0]
__________________________________________________________________________________________________
batch_normalization (BatchNorma (None, 32, 32, 144) 576 activation[0][0]
__________________________________________________________________________________________________
dropout (Dropout) (None, 32, 32, 144) 0 batch_normalization[0][0]
__________________________________________________________________________________________________
depthwise_conv2d (DepthwiseConv (None, 32, 32, 144) 3744 dropout[0][0]
__________________________________________________________________________________________________
activation_1 (Activation) (None, 32, 32, 144) 0 depthwise_conv2d[0][0]
__________________________________________________________________________________________________
batch_normalization_1 (BatchNor (None, 32, 32, 144) 576 activation_1[0][0]
__________________________________________________________________________________________________
dropout_1 (Dropout) (None, 32, 32, 144) 0 batch_normalization_1[0][0]
__________________________________________________________________________________________________
add (Add) (None, 32, 32, 144) 0 dropout_1[0][0]
dropout[0][0]
__________________________________________________________________________________________________
conv2d_1 (Conv2D) (None, 32, 32, 144) 20880 add[0][0]
__________________________________________________________________________________________________
activation_2 (Activation) (None, 32, 32, 144) 0 conv2d_1[0][0]
__________________________________________________________________________________________________
batch_normalization_2 (BatchNor (None, 32, 32, 144) 576 activation_2[0][0]
__________________________________________________________________________________________________
dropout_2 (Dropout) (None, 32, 32, 144) 0 batch_normalization_2[0][0]
__________________________________________________________________________________________________
depthwise_conv2d_1 (DepthwiseCo (None, 32, 32, 144) 3744 dropout_2[0][0]
__________________________________________________________________________________________________
activation_3 (Activation) (None, 32, 32, 144) 0 depthwise_conv2d_1[0][0]
__________________________________________________________________________________________________
batch_normalization_3 (BatchNor (None, 32, 32, 144) 576 activation_3[0][0]
__________________________________________________________________________________________________
dropout_3 (Dropout) (None, 32, 32, 144) 0 batch_normalization_3[0][0]
__________________________________________________________________________________________________
add_1 (Add) (None, 32, 32, 144) 0 dropout_3[0][0]
dropout_2[0][0]
__________________________________________________________________________________________________
conv2d_2 (Conv2D) (None, 32, 32, 144) 20880 add_1[0][0]
__________________________________________________________________________________________________
activation_4 (Activation) (None, 32, 32, 144) 0 conv2d_2[0][0]
__________________________________________________________________________________________________
batch_normalization_4 (BatchNor (None, 32, 32, 144) 576 activation_4[0][0]
__________________________________________________________________________________________________
dropout_4 (Dropout) (None, 32, 32, 144) 0 batch_normalization_4[0][0]
__________________________________________________________________________________________________
depthwise_conv2d_2 (DepthwiseCo (None, 32, 32, 144) 3744 dropout_4[0][0]
__________________________________________________________________________________________________
activation_5 (Activation) (None, 32, 32, 144) 0 depthwise_conv2d_2[0][0]
__________________________________________________________________________________________________
batch_normalization_5 (BatchNor (None, 32, 32, 144) 576 activation_5[0][0]
__________________________________________________________________________________________________
dropout_5 (Dropout) (None, 32, 32, 144) 0 batch_normalization_5[0][0]
__________________________________________________________________________________________________
add_2 (Add) (None, 32, 32, 144) 0 dropout_5[0][0]
dropout_4[0][0]
__________________________________________________________________________________________________
conv2d_3 (Conv2D) (None, 32, 32, 144) 20880 add_2[0][0]
__________________________________________________________________________________________________
activation_6 (Activation) (None, 32, 32, 144) 0 conv2d_3[0][0]
__________________________________________________________________________________________________
batch_normalization_6 (BatchNor (None, 32, 32, 144) 576 activation_6[0][0]
__________________________________________________________________________________________________
dropout_6 (Dropout) (None, 32, 32, 144) 0 batch_normalization_6[0][0]
__________________________________________________________________________________________________
depthwise_conv2d_3 (DepthwiseCo (None, 32, 32, 144) 3744 dropout_6[0][0]
__________________________________________________________________________________________________
activation_7 (Activation) (None, 32, 32, 144) 0 depthwise_conv2d_3[0][0]
__________________________________________________________________________________________________
batch_normalization_7 (BatchNor (None, 32, 32, 144) 576 activation_7[0][0]
__________________________________________________________________________________________________
dropout_7 (Dropout) (None, 32, 32, 144) 0 batch_normalization_7[0][0]
__________________________________________________________________________________________________
add_3 (Add) (None, 32, 32, 144) 0 dropout_7[0][0]
dropout_6[0][0]
__________________________________________________________________________________________________
conv2d_4 (Conv2D) (None, 32, 32, 144) 20880 add_3[0][0]
__________________________________________________________________________________________________
activation_8 (Activation) (None, 32, 32, 144) 0 conv2d_4[0][0]
__________________________________________________________________________________________________
batch_normalization_8 (BatchNor (None, 32, 32, 144) 576 activation_8[0][0]
__________________________________________________________________________________________________
dropout_8 (Dropout) (None, 32, 32, 144) 0 batch_normalization_8[0][0]
__________________________________________________________________________________________________
global_average_pooling2d (Globa (None, 144) 0 dropout_8[0][0]
__________________________________________________________________________________________________
dense (Dense) (None, 3225) 467625 global_average_pooling2d[0][0]
==================================================================================================
Total params: 572,025
Trainable params: 569,433
Non-trainable params: 2,592
__________________________________________________________________________________________________
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <thread>
#include <cmath>
#include <string>
#include <codecvt>
#include <Windows.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
using namespace std;
class jp_classifier
{
private:
const float eps = 0.001f;
// jp character map
vector<wstring> jpMap;
float** input;
// weights
float**** const0, **** const6, **** const12, **** const18, **** const24, **** const30,
**** const36, **** const42, **** const48;
float** const54;
// bias/normalization
float* const1, * const2, * const3, * const4, * const5, * const7, * const8, * const9,
* const10, * const11, * const13, * const14, * const15, * const16, * const17,
* const19, * const20, * const21, * const22, * const23, * const25, * const26,
* const27, * const28, * const29, * const31, * const32, * const33, * const34,
* const35, * const37, * const38, * const39, * const40, * const41, * const43,
* const44, * const45, * const46, * const47, * const49, * const50, * const51,
* const52, * const53, * const55;
float*** l0, *** l1, *** l2, *** l3, *** l4, *** l5, *** l6, *** l7, *** l8;
float* l9, *l10;
float**** getArray(ifstream* fin, int mi, int mj, int mk, int ml)
{
float**** buff = (float****)createArray(mi, mj, mk, ml, sizeof(float));
for (int i = 0; i < mi; i++) {
for (int j = 0; j < mj; j++) {
for (int k = 0; k < mk; k++) {
fin->read(reinterpret_cast<char*>(buff[i][j][k]), sizeof(float) * ml);
}
}
}
return buff;
}
float*** getArray(ifstream* fin, int mi, int mj, int mk)
{
float*** buff = (float***)createArray(mi, mj, mk, sizeof(float));
for (int i = 0; i < mi; i++) {
for (int j = 0; j < mj; j++) {
fin->read(reinterpret_cast<char*>(buff[i][j]), sizeof(float) * mk);
}
}
return buff;
}
float** getArray(ifstream* fin, int mi, int mj)
{
float** buff = (float**)createArray(mi, mj, sizeof(float));
for (int i = 0; i < mi; i++) {
fin->read(reinterpret_cast<char*>(buff[i]), sizeof(float) * mj);
}
return buff;
}
float* getArray(ifstream* fin, int mi)
{
float* buff = (float*)malloc(mi * sizeof(float));
fin->read(reinterpret_cast<char*>(buff), sizeof(float) * mi);
return buff;
}
// https://www.johndcook.com/blog/cpp_erf/
float erf(float x)
{
// constants
float a1 = 0.254829592;
float a2 = -0.284496736;
float a3 = 1.421413741;
float a4 = -1.453152027;
float a5 = 1.061405429;
float p = 0.3275911;
// Save the sign of x
int sign = 1;
if (x < 0)
sign = -1;
x = fabs(x);
// A&S formula 7.1.26
float t = 1.0 / (1.0 + p * x);
float y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * exp(-x * x);
return sign * y;
}
void testErf()
{
// Select a few input values
float x[] =
{
-3,
-1,
0.0,
0.5,
2.1
};
// Output computed by Mathematica
// y = Erf[x]
float y[] =
{
-0.999977909503,
-0.842700792950,
0.0,
0.520499877813,
0.997020533344
};
int numTests = sizeof(x) / sizeof(float);
float maxError = 0.0;
for (int i = 0; i < numTests; ++i) {
float error = fabs(y[i] - erf(x[i]));
if (error > maxError)
maxError = error;
}
std::cout << "Maximum error: " << maxError << "\n";
}
inline float GELU(float x)
{
//// APROX
//x = x + 0.044715f * powf(x, 3);
//// 1 + tanh(sqrt(2/pi) * x)
//x = (1.0f + tanhf(0.79788456f * x)) * 0.5f * x;
//return x;
// poly approx
return 0.5f * x * (1.0f + erf(x / 1.4142135624f));
}
inline float batchNorm(float x, float gamma, float beta, float mean, float var)
{
//z1_hat = (x - pop_mean) / sqrt(pop_var + epsilon)
// BN1 = gamma * z1_hat + beta
return ((x - mean) / sqrtf(var + eps)) * gamma + beta;
}
inline float padLayerEven(float*** layer, int x, int y, int z, int xm, int ym)
{
if (x < 2 || y < 2 || x > xm + 1 || y > ym + 1) return 0.0f;
return layer[x - 2][y - 2][z];
}
public:
// Annoying mallocs
static float** createArray(int i, int j, size_t size)
{
float** r = new float* [i * sizeof(float*)];
for (int x = 0; x < i; x++) {
r[x] = new float[j * size];
}
return r;
}
static float*** createArray(int i, int j, int k, size_t size)
{
float*** r = new float** [i * sizeof(float*)];
for (int x = 0; x < i; x++) {
r[x] = new float* [j * sizeof(float*)];
for (int y = 0; y < j; y++) {
r[x][y] = new float[k * size];
}
}
return r;
}
static float**** createArray(int i, int j, int k, int l, size_t size)
{
float**** r = new float*** [i * sizeof(float*)];
for (int x = 0; x < i; x++) {
r[x] = new float** [j * sizeof(float*)];
for (int y = 0; y < j; y++) {
r[x][y] = new float* [k * sizeof(float*)];
for (int z = 0; z < k; z++) {
r[x][y][z] = new float[l * size];
}
}
}
return r;
}
// Annoying malloc frees
static void freeArray(int i, float* a)
{
delete[] a;
}
static void freeArray(int i, int j, float** a)
{
for (int x = 0; x < i; x++) {
delete[] a[x];
}
delete[] a;
}
static void freeArray(int i, int j, int k, float*** a)
{
for (int x = 0; x < i; x++) {
for (int y = 0; y < j; y++) {
delete[] a[x][y];
}
delete[] a[x];
}
delete[] a;
}
static void freeArray(int i, int j, int k, int l, float**** a)
{
for (int x = 0; x < i; x++) {
for (int y = 0; y < j; y++) {
for (int z = 0; z < k; z++) {
delete[] a[x][y][z];
}
delete[] a[x][y];
}
delete[] a[x];
}
delete[] a;
}
float** loadAsArray(string path, int* width, int* height, int* channels)
{
// Not HDR, just need raw float values
stbi_ldr_to_hdr_gamma(1.0f);
float* img = stbi_loadf(path.c_str(), width, height, channels, 0);
if (img == NULL) {
cout << "Error loading " << path << endl;
exit(1);
}
printf("Loaded image with a width of %dpx, a height of %dpx and %d channels\n", *width, *height, *channels);
float** img_array = createArray(*width, *height, sizeof(float));
for (int h = 0; h < *height; h++)
for (int w = 0; w < *width; w++)
img_array[h][w] = img[h * *height + w];
stbi_image_free(img);
return img_array;
}
jp_classifier(string path, string pathSeq2Text)
{
wifstream fin3(pathSeq2Text);
if (!fin3) {
cout << "error opening jp file" << endl;
exit(-1);
}
for (int i = 0; i < 3; i++) jpMap.push_back(L"");
wstring wline;
wstring wtoken;
while (std::getline(fin3, wline))
{
wstringstream ss(wline);
getline(ss, wtoken, L'\t');
jpMap.push_back(wtoken);
}
fin3.close();
ifstream fin(path, ios::binary);
if (!fin) {
cout << "error opening stream" << endl;
exit(-1);
}
// read weights
const0 = getArray(&fin, 2, 2, 1, 144);
const1 = getArray(&fin, 144);
const2 = getArray(&fin, 144);
const3 = getArray(&fin, 144);
const4 = getArray(&fin, 144);
const5 = getArray(&fin, 144);
const6 = getArray(&fin, 5, 5, 144, 1);
const7 = getArray(&fin, 144);
const8 = getArray(&fin, 144);
const9 = getArray(&fin, 144);
const10 = getArray(&fin, 144);
const11 = getArray(&fin, 144);
const12 = getArray(&fin, 1, 1, 144, 144);
const13 = getArray(&fin, 144);
const14 = getArray(&fin, 144);
const15 = getArray(&fin, 144);
const16 = getArray(&fin, 144);
const17 = getArray(&fin, 144);
const18 = getArray(&fin, 5, 5, 144, 1);
const19 = getArray(&fin, 144);
const20 = getArray(&fin, 144);
const21 = getArray(&fin, 144);
const22 = getArray(&fin, 144);
const23 = getArray(&fin, 144);
const24 = getArray(&fin, 1, 1, 144, 144);
const25 = getArray(&fin, 144);
const26 = getArray(&fin, 144);
const27 = getArray(&fin, 144);
const28 = getArray(&fin, 144);
const29 = getArray(&fin, 144);
const30 = getArray(&fin, 5, 5, 144, 1);
const31 = getArray(&fin, 144);
const32 = getArray(&fin, 144);
const33 = getArray(&fin, 144);
const34 = getArray(&fin, 144);
const35 = getArray(&fin, 144);
const36 = getArray(&fin, 1, 1, 144, 144);
const37 = getArray(&fin, 144);
const38 = getArray(&fin, 144);
const39 = getArray(&fin, 144);
const40 = getArray(&fin, 144);
const41 = getArray(&fin, 144);
const42 = getArray(&fin, 5, 5, 144, 1);
const43 = getArray(&fin, 144);
const44 = getArray(&fin, 144);
const45 = getArray(&fin, 144);
const46 = getArray(&fin, 144);
const47 = getArray(&fin, 144);
const48 = getArray(&fin, 1, 1, 144, 144);
const49 = getArray(&fin, 144);
const50 = getArray(&fin, 144);
const51 = getArray(&fin, 144);
const52 = getArray(&fin, 144);
const53 = getArray(&fin, 144);
const54 = getArray(&fin, 144, 3225);
const55 = getArray(&fin, 3225);
fin.close();
// allocate outputs
l0 = (float***)createArray(32, 32, 144, sizeof(float));
l1 = (float***)createArray(32, 32, 144, sizeof(float));
l2 = (float***)createArray(32, 32, 144, sizeof(float));
l3 = (float***)createArray(32, 32, 144, sizeof(float));
l4 = (float***)createArray(32, 32, 144, sizeof(float));
l5 = (float***)createArray(32, 32, 144, sizeof(float));
l6 = (float***)createArray(32, 32, 144, sizeof(float));
l7 = (float***)createArray(32, 32, 144, sizeof(float));
l8 = (float***)createArray(32, 32, 144, sizeof(float));
l9 = new float[144];
l10 = new float[3225];
}
~jp_classifier()
{
freeArray(2, 2, 1, 144, const0);
freeArray(144, const1);
freeArray(144, const2);
freeArray(144, const3);
freeArray(144, const4);
freeArray(144, const5);
freeArray(5, 5, 144, 1, const6);
freeArray(144, const7);
freeArray(144, const8);
freeArray(144, const9);
freeArray(144, const10);
freeArray(144, const11);
freeArray(1, 1, 144, 144, const12);
freeArray(144, const13);
freeArray(144, const14);
freeArray(144, const15);
freeArray(144, const16);
freeArray(144, const17);
freeArray(5, 5, 144, 1, const18);
freeArray(144, const19);
freeArray(144, const20);
freeArray(144, const21);
freeArray(144, const22);
freeArray(144, const23);
freeArray(1, 1, 144, 144, const24);
freeArray(144, const25);
freeArray(144, const26);
freeArray(144, const27);
freeArray(144, const28);
freeArray(144, const29);
freeArray(5, 5, 144, 1, const30);
freeArray(144, const31);
freeArray(144, const32);
freeArray(144, const33);
freeArray(144, const34);
freeArray(144, const35);
freeArray(1, 1, 144, 144, const36);
freeArray(144, const37);
freeArray(144, const38);
freeArray(144, const39);
freeArray(144, const40);
freeArray(144, const41);
freeArray(5, 5, 144, 1, const42);
freeArray(144, const43);
freeArray(144, const44);
freeArray(144, const45);
freeArray(144, const46);
freeArray(144, const47);
freeArray(1, 1, 144, 144, const48);
freeArray(144, const49);
freeArray(144, const50);
freeArray(144, const51);
freeArray(144, const52);
freeArray(144, const53);
freeArray(144, 3225, const54);
freeArray(3225, const55);
freeArray(32, 32, 144, l0);
freeArray(32, 32, 144, l1);
freeArray(32, 32, 144, l2);
freeArray(32, 32, 144, l3);
freeArray(32, 32, 144, l4);
freeArray(32, 32, 144, l5);
freeArray(32, 32, 144, l6);
freeArray(32, 32, 144, l7);
freeArray(32, 32, 144, l8);
delete[] l9;
delete[] l10;
}
// convnet "patches"
void kernelPaddedEvenL0(float*** cl, float**** cw, float* bias,
float* gamma, float* beta, float* mm, float* mv, float** pl, int im, int jm, int k)
{
for (int i = 0; i < im; i++) {
for (int j = 0; j < jm; j++) {
cl[i][j][k] = 0.0f;
int i0 = i * 2, i1 = i0 + 1;
int j0 = j * 2, j1 = j0 + 1;
// kernel
cl[i][j][k] +=
pl[i0][j0] * cw[0][0][0][k] +
pl[i0][j1] * cw[0][1][0][k] +
pl[i1][j0] * cw[1][0][0][k] +
pl[i1][j1] * cw[1][1][0][k];
// bias
cl[i][j][k] = cl[i][j][k] + bias[k];
// activation
cl[i][j][k] = GELU(cl[i][j][k]);
// batch norm
cl[i][j][k] = batchNorm(cl[i][j][k], gamma[k], beta[k], mm[k], mv[k]);
}
}
}
// depth wise convolution
void depthConv5x5(float*** cl, float**** cw, float* bias,
float* gamma, float* beta, float* mm, float* mv, float*** pl, int im, int jm, int k)
{
for (int i = 0; i < im; i++) {
for (int j = 0; j < jm; j++) {
int i0 = i, i1 = i0 + 1, i2 = i0 + 2, i3 = i0 + 3, i4 = i0 + 4;
int j0 = j, j1 = j0 + 1, j2 = j0 + 2, j3 = j0 + 3, j4 = j0 + 4;
// 5x5 depth wise kernel
cl[i][j][k] =
padLayerEven(pl, i0, j0, k, im, jm) * cw[0][0][k][0] +
padLayerEven(pl, i0, j1, k, im, jm) * cw[0][1][k][0] +
padLayerEven(pl, i0, j2, k, im, jm) * cw[0][2][k][0] +
padLayerEven(pl, i0, j3, k, im, jm) * cw[0][3][k][0] +
padLayerEven(pl, i0, j4, k, im, jm) * cw[0][4][k][0] +
padLayerEven(pl, i1, j0, k, im, jm) * cw[1][0][k][0] +
padLayerEven(pl, i1, j1, k, im, jm) * cw[1][1][k][0] +
padLayerEven(pl, i1, j2, k, im, jm) * cw[1][2][k][0] +
padLayerEven(pl, i1, j3, k, im, jm) * cw[1][3][k][0] +
padLayerEven(pl, i1, j4, k, im, jm) * cw[1][4][k][0] +
padLayerEven(pl, i2, j0, k, im, jm) * cw[2][0][k][0] +
padLayerEven(pl, i2, j1, k, im, jm) * cw[2][1][k][0] +
padLayerEven(pl, i2, j2, k, im, jm) * cw[2][2][k][0] +
padLayerEven(pl, i2, j3, k, im, jm) * cw[2][3][k][0] +
padLayerEven(pl, i2, j4, k, im, jm) * cw[2][4][k][0] +
padLayerEven(pl, i3, j0, k, im, jm) * cw[3][0][k][0] +
padLayerEven(pl, i3, j1, k, im, jm) * cw[3][1][k][0] +
padLayerEven(pl, i3, j2, k, im, jm) * cw[3][2][k][0] +
padLayerEven(pl, i3, j3, k, im, jm) * cw[3][3][k][0] +
padLayerEven(pl, i3, j4, k, im, jm) * cw[3][4][k][0] +
padLayerEven(pl, i4, j0, k, im, jm) * cw[4][0][k][0] +
padLayerEven(pl, i4, j1, k, im, jm) * cw[4][1][k][0] +
padLayerEven(pl, i4, j2, k, im, jm) * cw[4][2][k][0] +
padLayerEven(pl, i4, j3, k, im, jm) * cw[4][3][k][0] +
padLayerEven(pl, i4, j4, k, im, jm) * cw[4][4][k][0];
// bias
cl[i][j][k] = cl[i][j][k] + bias[k];
// activation
cl[i][j][k] = GELU(cl[i][j][k]);
// batch norm
cl[i][j][k] = batchNorm(cl[i][j][k], gamma[k], beta[k], mm[k], mv[k]);
}
}
}
// point wise convolution
void pointConv1x1(float*** cl, float**** cw, float* bias,
float* gamma, float* beta, float* mm, float* mv, float*** pl1, float*** pl2,
int im, int jm, int k, int lm)
{
for (int i = 0; i < im; i++) {
for (int j = 0; j < jm; j++) {
cl[i][j][k] = 0.0f;
// 1x1 kernel
for (int l = 0; l < lm; l++) {
cl[i][j][k] += (pl1[i][j][l] + pl2[i][j][l]) * cw[0][0][l][k];
}
// bias
cl[i][j][k] = cl[i][j][k] + bias[k];
// activation
cl[i][j][k] = GELU(cl[i][j][k]);
// batch norm
cl[i][j][k] = batchNorm(cl[i][j][k], gamma[k], beta[k], mm[k], mv[k]);
}
}
}
// average layers
void globalPool(float* cl, float*** pl, int im, int jm, int k)
{
cl[k] = 0.0f;
for (int i = 0; i < im; i++) {
for (int j = 0; j < jm; j++) {
cl[k] += pl[i][j][k];
}
}
cl[k] /= 1024.0f;
}
// dense layer with softmax
void denseLayer(float* cl, float** cw, float* bias, float* pl, int k, int lm)
{
cl[k] = 0.0f;
for (int l = 0; l < lm; l++) {
cl[k] += pl[l] * cw[l][k];
}
cl[k] = cl[k] + bias[k];
// softmax at the end to get the % but it can be ommited for prediction
}
void forwardProp(float** imgIn)
{
input = imgIn;
vector<thread> threads;
// L0, kernel=2x2, stride=2, padding=even, batch norm
for (int k = 0; k < 144; k++) {
thread t(&jp_classifier::kernelPaddedEvenL0, this, l0, const0, const1,
const2, const3, const4, const5, input, 32, 32, k);
threads.push_back(move(t));
}
for (auto& th : threads) th.join();
threads.clear();
//// Same depthwise/pointwise convolutions looped but I kept the functions seperate
// L1, depthwise conv=5x5x144, stride=1, padding=even, batch norm
for (int k = 0; k < 144; k++) {
thread t(&jp_classifier::depthConv5x5, this, l1, const6, const7,
const8, const9, const10, const11, l0, 32, 32, k);
threads.push_back(move(t));
}
for (auto& th : threads) th.join();
threads.clear();
// L2, kernel=1x1, stride=1, padding=even, add in L0
for (int k = 0; k < 144; k++) {
thread t(&jp_classifier::pointConv1x1, this, l2, const12, const13,
const14, const15, const16, const17, l1, l0, 32, 32, k, 144);
threads.push_back(move(t));
}
for (auto& th : threads) th.join();
threads.clear();
// L3, depthwise conv=5x5x144, stride=1, padding=even, batch norm
for (int k = 0; k < 144; k++) {
thread t(&jp_classifier::depthConv5x5, this, l3, const18, const19,
const20, const21, const22, const23, l2, 32, 32, k);
threads.push_back(move(t));
}
for (auto& th : threads) th.join();
threads.clear();
// L4, kernel=1x1, stride=1, padding=even, add in L2
for (int k = 0; k < 144; k++) {
thread t(&jp_classifier::pointConv1x1, this, l4, const24, const25,
const26, const27, const28, const29, l3, l2, 32, 32, k, 144);
threads.push_back(move(t));
}
for (auto& th : threads) th.join();
threads.clear();
// L5, depthwise conv=5x5x144, stride=1, padding=even, batch norm
for (int k = 0; k < 144; k++) {
thread t(&jp_classifier::depthConv5x5, this, l5, const30, const31,
const32, const33, const34, const35, l4, 32, 32, k);
threads.push_back(move(t));
}
for (auto& th : threads) th.join();
threads.clear();
// L6, kernel=1x1, stride=1, padding=even, add in L4
for (int k = 0; k < 144; k++) {
thread t(&jp_classifier::pointConv1x1, this, l6, const36, const37,
const38, const39, const40, const41, l5, l4, 32, 32, k, 144);
threads.push_back(move(t));
}
for (auto& th : threads) th.join();
threads.clear();
// L7, depthwise conv=5x5x144, stride=1, padding=even, batch norm
for (int k = 0; k < 144; k++) {
thread t(&jp_classifier::depthConv5x5, this, l7, const42, const43,
const44, const45, const46, const47, l6, 32, 32, k);
threads.push_back(move(t));
}
for (auto& th : threads) th.join();
threads.clear();
// L8, kernel=1x1, stride=1, padding=even, add in L6
for (int k = 0; k < 144; k++) {
thread t(&jp_classifier::pointConv1x1, this, l8, const48, const49,
const50, const51, const52, const53, l7, l6, 32, 32, k, 144);
threads.push_back(move(t));
}
for (auto& th : threads) th.join();
threads.clear();
// L9, global pooling
for (int k = 0; k < 144; k++) {
thread t(&jp_classifier::globalPool, this, l9, l8, 32, 32, k);
threads.push_back(move(t));
}
for (auto& th : threads) th.join();
threads.clear();
// L10, classify
for (int k = 0; k < 3225; k++) {
thread t(&jp_classifier::denseLayer, this, l10, const54, const55, l9, k, 144);
threads.push_back(move(t));
}
for (auto& th : threads) th.join();
threads.clear();
float maxNum = FLT_MIN;
int maxInd = 0;
for (int i = 0; i < 3225; i++)
{
float score = l10[i];
maxInd = score > maxNum ? i : maxInd;
maxNum = score > maxNum ? score : maxNum;
}
wcout << L"Predicted: " << jpMap[maxInd + 3];
}
};
int main()
{
SetConsoleOutputCP(CP_UTF8);
// yes it's hardcoded cause i'm too lazy
string BAKED_PATH = "D:\\Storage\\Python\\convmixer\\model\\jp_convmixer.bytes";
string IMG_PATH = "D:\\Storage\\Python\\convmixer\\input\\input1.jpg";
string PATHSEQ2TEXT = ".\\jp_seq2text.tsv";
jp_classifier classifier = jp_classifier(BAKED_PATH, PATHSEQ2TEXT);
int width, height, channels;
float** imgin = classifier.loadAsArray(IMG_PATH, &width, &height, &channels);
//for (int i = 0; i < 64; i++) {
// for (int j = 0; j < 64; j++) {
// imgin[i][j] = (i / 63.0f) * (j / (63.0f * 0.5));
// }
//}
if (width != 64 || height != 64 || channels != 1) exit(1);
classifier.forwardProp(imgin);
// wait for input
getc(stdin);
classifier.freeArray(64, 64, imgin);
return 0;
} | 40.345297 | 116 | 0.548452 | [
"shape",
"vector",
"model"
] |
ebb2ea8021b7ca3ca66c2641feedadc86e8b8894 | 2,915 | cpp | C++ | engine/audio/PcmClip.cpp | wzhengsen/ouzel | b3b99c42b39efd2998c03967ee8d5b3e91305167 | [
"Unlicense"
] | 923 | 2016-05-30T15:11:16.000Z | 2022-03-30T20:26:24.000Z | engine/audio/PcmClip.cpp | wzhengsen/ouzel | b3b99c42b39efd2998c03967ee8d5b3e91305167 | [
"Unlicense"
] | 46 | 2016-05-31T18:32:23.000Z | 2022-01-18T02:26:06.000Z | engine/audio/PcmClip.cpp | wzhengsen/ouzel | b3b99c42b39efd2998c03967ee8d5b3e91305167 | [
"Unlicense"
] | 131 | 2016-05-30T20:20:07.000Z | 2022-03-10T10:56:08.000Z | // Ouzel by Elviss Strazdins
#include <iterator>
#include <stdexcept>
#include "PcmClip.hpp"
#include "Audio.hpp"
#include "mixer/Data.hpp"
#include "mixer/Stream.hpp"
namespace ouzel::audio
{
class PcmData;
class PcmStream final: public mixer::Stream
{
public:
explicit PcmStream(PcmData& pcmData);
void reset() override
{
position = 0;
}
void generateSamples(std::uint32_t frames, std::vector<float>& samples) override;
private:
std::uint32_t position = 0;
};
class PcmData final: public mixer::Data
{
public:
PcmData(std::uint32_t initChannels, std::uint32_t initSampleRate,
const std::vector<float>& initData):
Data{initChannels, initSampleRate},
data{initData}
{
}
auto& getData() const noexcept { return data; }
std::unique_ptr<mixer::Stream> createStream() override
{
return std::make_unique<PcmStream>(*this);
}
private:
std::vector<float> data;
};
PcmStream::PcmStream(PcmData& pcmData):
Stream(pcmData)
{
}
void PcmStream::generateSamples(std::uint32_t frames, std::vector<float>& samples)
{
const std::uint32_t neededSize = frames * data.getChannels();
samples.resize(neededSize);
const auto& pcmData = static_cast<PcmData&>(data);
const auto& dataSamples = pcmData.getData();
const auto sourceFrames = static_cast<std::uint32_t>(dataSamples.size() / pcmData.getChannels());
const std::uint32_t copyFrames = (frames > sourceFrames - position) ? sourceFrames - position : frames;
for (std::uint32_t channel = 0; channel < pcmData.getChannels(); ++channel)
{
const auto sourceChannel = &dataSamples[channel * sourceFrames];
const auto outputChannel = &samples[channel * frames];
for (std::uint32_t frame = 0; frame < copyFrames; ++frame)
outputChannel[frame] = sourceChannel[frame + position];
}
position += copyFrames;
for (std::uint32_t channel = 0; channel < pcmData.getChannels(); ++channel)
{
const auto outputChannel = &samples[channel * frames];
for (std::uint32_t frame = copyFrames; frame < frames; ++frame)
outputChannel[frame] = 0.0F;
}
if ((sourceFrames - position) == 0)
{
playing = false; // TODO: fire event
reset();
}
}
PcmClip::PcmClip(Audio& initAudio, std::uint32_t channels, std::uint32_t sampleRate,
const std::vector<float>& samples):
Sound{
initAudio,
initAudio.initData(std::unique_ptr<mixer::Data>(data = new PcmData(channels, sampleRate, samples))),
Sound::Format::pcm
}
{
}
}
| 28.300971 | 112 | 0.589022 | [
"vector"
] |
ebb372949d93d2706f8aedf045837984b0caf377 | 3,190 | hpp | C++ | include/posix/sockets.hpp | incoder1/libio | fbfd83fe31ca59a69670e5269f5847b2b4c6c553 | [
"BSL-1.0"
] | 14 | 2018-06-12T15:42:43.000Z | 2022-02-28T16:19:20.000Z | include/posix/sockets.hpp | incoder1/libio | fbfd83fe31ca59a69670e5269f5847b2b4c6c553 | [
"BSL-1.0"
] | null | null | null | include/posix/sockets.hpp | incoder1/libio | fbfd83fe31ca59a69670e5269f5847b2b4c6c553 | [
"BSL-1.0"
] | null | null | null | /*
*
* Copyright (c) 2017
* Viktor Gubin
*
* 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)
*
*/
#ifndef __IO_POSIX_SOCKETS_HPP_INCLUDED__
#define __IO_POSIX_SOCKETS_HPP_INCLUDED__
#include <config.hpp>
#ifndef HAS_PRAGMA_ONCE
#pragma once
#endif // HAS_PRAGMA_ONCE
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <atomic>
#include <channels.hpp>
#include "criticalsection.hpp"
#include "conststring.hpp"
namespace io {
namespace net {
enum class transport {
tcp = IPPROTO_TCP,
udp = IPPROTO_UDP,
icmp = IPPROTO_ICMP,
icmp6 = IPPROTO_ICMPV6
};
enum class ip_family {
ip_v4 = AF_INET,
ip_v6 = AF_INET6,
};
inline std::ostream& operator<<(std::ostream& os, ip_family ipf)
{
switch(ipf) {
case ip_family::ip_v4:
os << "TCP/IP version 4";
break;
case ip_family::ip_v6:
os << "TCP/IP version 6";
break;
}
return os;
}
inline std::ostream& operator<<(std::ostream& os, transport prot)
{
switch(prot) {
case transport::tcp:
os << "TCP";
break;
case transport::udp:
os << "UDP";
break;
case transport::icmp:
case transport::icmp6:
os << "ICMP";
break;
}
return os;
}
class IO_PUBLIC_SYMBOL endpoint {
private:
static void do_nothing(void const *p) noexcept
{}
endpoint(::addrinfo* const info) noexcept:
addr_info_(info, &endpoint::do_nothing )
{}
public:
endpoint() noexcept:
addr_info_()
{}
bool has_next() const noexcept {
return addr_info_ && nullptr != addr_info_->ai_next;
}
endpoint next() const noexcept {
return has_next() ? endpoint( addr_info_->ai_next ) : endpoint();
}
endpoint(std::shared_ptr<::addrinfo>&& info) noexcept;
endpoint(const std::shared_ptr<::addrinfo>& info) noexcept;
const_string ip_address() const noexcept;
uint16_t port() const noexcept;
void set_port(uint16_t port) noexcept;
ip_family family() const noexcept;
const void* native() const noexcept;
private:
std::shared_ptr<::addrinfo> addr_info_;
};
class IO_PUBLIC_SYMBOL socket:public virtual object {
protected:
socket() noexcept;
public:
virtual bool connected() const noexcept = 0;
virtual transport transport_protocol() const noexcept = 0;
virtual endpoint get_endpoint() const noexcept = 0;
virtual s_read_write_channel connect(std::error_code& ec) const noexcept = 0;
};
DECLARE_IPTR(socket);
class IO_PUBLIC_SYMBOL socket_factory {
socket_factory(const socket_factory&) = delete;
socket_factory& operator=(const socket_factory&) = delete;
private:
friend class nobadalloc<socket_factory>;
static void do_release() noexcept;
constexpr socket_factory() noexcept
{}
public:
~socket_factory() noexcept;
static const socket_factory* instance(std::error_code& ec) noexcept;
s_socket client_tcp_socket(std::error_code& ec, const char* host, uint16_t port) const noexcept;
s_socket client_udp_socket(std::error_code& ec, const char* host, uint16_t port) const noexcept;
private:
static std::atomic<socket_factory*> _instance;
static critical_section _init_cs;
};
} // namespace net
} // namespace io
#endif // __IO_POSIX_SOCKETS_HPP_INCLUDED__
| 23.115942 | 97 | 0.73605 | [
"object"
] |
ebb5166f83418fa363fdf5fd9cd182406b8e598f | 29,029 | cpp | C++ | generated/src/FileServerAsyncClient.cpp | madMAx43v3r/vnx-addon | cf9709ccc29e5bb7503468eb38f781947f2bcd85 | [
"MIT"
] | null | null | null | generated/src/FileServerAsyncClient.cpp | madMAx43v3r/vnx-addon | cf9709ccc29e5bb7503468eb38f781947f2bcd85 | [
"MIT"
] | null | null | null | generated/src/FileServerAsyncClient.cpp | madMAx43v3r/vnx-addon | cf9709ccc29e5bb7503468eb38f781947f2bcd85 | [
"MIT"
] | null | null | null |
// AUTO GENERATED by vnxcppcodegen
#include <vnx/addons/package.hxx>
#include <vnx/addons/FileServerAsyncClient.hxx>
#include <vnx/Buffer.hpp>
#include <vnx/Module.h>
#include <vnx/ModuleInterface_vnx_get_config.hxx>
#include <vnx/ModuleInterface_vnx_get_config_return.hxx>
#include <vnx/ModuleInterface_vnx_get_config_object.hxx>
#include <vnx/ModuleInterface_vnx_get_config_object_return.hxx>
#include <vnx/ModuleInterface_vnx_get_module_info.hxx>
#include <vnx/ModuleInterface_vnx_get_module_info_return.hxx>
#include <vnx/ModuleInterface_vnx_get_type_code.hxx>
#include <vnx/ModuleInterface_vnx_get_type_code_return.hxx>
#include <vnx/ModuleInterface_vnx_restart.hxx>
#include <vnx/ModuleInterface_vnx_restart_return.hxx>
#include <vnx/ModuleInterface_vnx_self_test.hxx>
#include <vnx/ModuleInterface_vnx_self_test_return.hxx>
#include <vnx/ModuleInterface_vnx_set_config.hxx>
#include <vnx/ModuleInterface_vnx_set_config_return.hxx>
#include <vnx/ModuleInterface_vnx_set_config_object.hxx>
#include <vnx/ModuleInterface_vnx_set_config_object_return.hxx>
#include <vnx/ModuleInterface_vnx_stop.hxx>
#include <vnx/ModuleInterface_vnx_stop_return.hxx>
#include <vnx/addons/FileServer_delete_file.hxx>
#include <vnx/addons/FileServer_delete_file_return.hxx>
#include <vnx/addons/FileServer_get_file_info.hxx>
#include <vnx/addons/FileServer_get_file_info_return.hxx>
#include <vnx/addons/FileServer_read_directory.hxx>
#include <vnx/addons/FileServer_read_directory_return.hxx>
#include <vnx/addons/FileServer_read_file.hxx>
#include <vnx/addons/FileServer_read_file_return.hxx>
#include <vnx/addons/FileServer_read_file_range.hxx>
#include <vnx/addons/FileServer_read_file_range_return.hxx>
#include <vnx/addons/FileServer_write_file.hxx>
#include <vnx/addons/FileServer_write_file_return.hxx>
#include <vnx/addons/HttpComponent_http_request.hxx>
#include <vnx/addons/HttpComponent_http_request_return.hxx>
#include <vnx/addons/HttpComponent_http_request_chunk.hxx>
#include <vnx/addons/HttpComponent_http_request_chunk_return.hxx>
#include <vnx/addons/HttpData.hxx>
#include <vnx/addons/HttpRequest.hxx>
#include <vnx/addons/HttpResponse.hxx>
#include <vnx/addons/file_info_t.hxx>
#include <vnx/Generic.hxx>
#include <vnx/vnx.h>
namespace vnx {
namespace addons {
FileServerAsyncClient::FileServerAsyncClient(const std::string& service_name)
: AsyncClient::AsyncClient(vnx::Hash64(service_name))
{
}
FileServerAsyncClient::FileServerAsyncClient(vnx::Hash64 service_addr)
: AsyncClient::AsyncClient(service_addr)
{
}
uint64_t FileServerAsyncClient::read_file(const std::string& path, const std::function<void(const ::vnx::Buffer&)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) {
auto _method = ::vnx::addons::FileServer_read_file::create();
_method->path = path;
const auto _request_id = ++vnx_next_id;
{
std::lock_guard<std::mutex> _lock(vnx_mutex);
vnx_pending[_request_id] = 0;
vnx_queue_read_file[_request_id] = std::make_pair(_callback, _error_callback);
}
vnx_request(_method, _request_id);
return _request_id;
}
uint64_t FileServerAsyncClient::read_file_range(const std::string& path, const int64_t& offset, const int64_t& length, const std::function<void(const ::vnx::Buffer&)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) {
auto _method = ::vnx::addons::FileServer_read_file_range::create();
_method->path = path;
_method->offset = offset;
_method->length = length;
const auto _request_id = ++vnx_next_id;
{
std::lock_guard<std::mutex> _lock(vnx_mutex);
vnx_pending[_request_id] = 1;
vnx_queue_read_file_range[_request_id] = std::make_pair(_callback, _error_callback);
}
vnx_request(_method, _request_id);
return _request_id;
}
uint64_t FileServerAsyncClient::get_file_info(const std::string& path, const std::function<void(const ::vnx::addons::file_info_t&)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) {
auto _method = ::vnx::addons::FileServer_get_file_info::create();
_method->path = path;
const auto _request_id = ++vnx_next_id;
{
std::lock_guard<std::mutex> _lock(vnx_mutex);
vnx_pending[_request_id] = 2;
vnx_queue_get_file_info[_request_id] = std::make_pair(_callback, _error_callback);
}
vnx_request(_method, _request_id);
return _request_id;
}
uint64_t FileServerAsyncClient::read_directory(const std::string& path, const std::function<void(const std::vector<::vnx::addons::file_info_t>&)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) {
auto _method = ::vnx::addons::FileServer_read_directory::create();
_method->path = path;
const auto _request_id = ++vnx_next_id;
{
std::lock_guard<std::mutex> _lock(vnx_mutex);
vnx_pending[_request_id] = 3;
vnx_queue_read_directory[_request_id] = std::make_pair(_callback, _error_callback);
}
vnx_request(_method, _request_id);
return _request_id;
}
uint64_t FileServerAsyncClient::write_file(const std::string& path, const ::vnx::Buffer& data, const std::function<void()>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) {
auto _method = ::vnx::addons::FileServer_write_file::create();
_method->path = path;
_method->data = data;
const auto _request_id = ++vnx_next_id;
{
std::lock_guard<std::mutex> _lock(vnx_mutex);
vnx_pending[_request_id] = 4;
vnx_queue_write_file[_request_id] = std::make_pair(_callback, _error_callback);
}
vnx_request(_method, _request_id);
return _request_id;
}
uint64_t FileServerAsyncClient::delete_file(const std::string& path, const std::function<void()>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) {
auto _method = ::vnx::addons::FileServer_delete_file::create();
_method->path = path;
const auto _request_id = ++vnx_next_id;
{
std::lock_guard<std::mutex> _lock(vnx_mutex);
vnx_pending[_request_id] = 5;
vnx_queue_delete_file[_request_id] = std::make_pair(_callback, _error_callback);
}
vnx_request(_method, _request_id);
return _request_id;
}
uint64_t FileServerAsyncClient::http_request(std::shared_ptr<const ::vnx::addons::HttpRequest> request, const std::string& sub_path, const std::function<void(std::shared_ptr<const ::vnx::addons::HttpResponse>)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) {
auto _method = ::vnx::addons::HttpComponent_http_request::create();
_method->request = request;
_method->sub_path = sub_path;
const auto _request_id = ++vnx_next_id;
{
std::lock_guard<std::mutex> _lock(vnx_mutex);
vnx_pending[_request_id] = 6;
vnx_queue_http_request[_request_id] = std::make_pair(_callback, _error_callback);
}
vnx_request(_method, _request_id);
return _request_id;
}
uint64_t FileServerAsyncClient::http_request_chunk(std::shared_ptr<const ::vnx::addons::HttpRequest> request, const std::string& sub_path, const int64_t& offset, const int64_t& max_bytes, const std::function<void(std::shared_ptr<const ::vnx::addons::HttpData>)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) {
auto _method = ::vnx::addons::HttpComponent_http_request_chunk::create();
_method->request = request;
_method->sub_path = sub_path;
_method->offset = offset;
_method->max_bytes = max_bytes;
const auto _request_id = ++vnx_next_id;
{
std::lock_guard<std::mutex> _lock(vnx_mutex);
vnx_pending[_request_id] = 7;
vnx_queue_http_request_chunk[_request_id] = std::make_pair(_callback, _error_callback);
}
vnx_request(_method, _request_id);
return _request_id;
}
uint64_t FileServerAsyncClient::vnx_get_config_object(const std::function<void(const ::vnx::Object&)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) {
auto _method = ::vnx::ModuleInterface_vnx_get_config_object::create();
const auto _request_id = ++vnx_next_id;
{
std::lock_guard<std::mutex> _lock(vnx_mutex);
vnx_pending[_request_id] = 8;
vnx_queue_vnx_get_config_object[_request_id] = std::make_pair(_callback, _error_callback);
}
vnx_request(_method, _request_id);
return _request_id;
}
uint64_t FileServerAsyncClient::vnx_get_config(const std::string& name, const std::function<void(const ::vnx::Variant&)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) {
auto _method = ::vnx::ModuleInterface_vnx_get_config::create();
_method->name = name;
const auto _request_id = ++vnx_next_id;
{
std::lock_guard<std::mutex> _lock(vnx_mutex);
vnx_pending[_request_id] = 9;
vnx_queue_vnx_get_config[_request_id] = std::make_pair(_callback, _error_callback);
}
vnx_request(_method, _request_id);
return _request_id;
}
uint64_t FileServerAsyncClient::vnx_set_config_object(const ::vnx::Object& config, const std::function<void()>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) {
auto _method = ::vnx::ModuleInterface_vnx_set_config_object::create();
_method->config = config;
const auto _request_id = ++vnx_next_id;
{
std::lock_guard<std::mutex> _lock(vnx_mutex);
vnx_pending[_request_id] = 10;
vnx_queue_vnx_set_config_object[_request_id] = std::make_pair(_callback, _error_callback);
}
vnx_request(_method, _request_id);
return _request_id;
}
uint64_t FileServerAsyncClient::vnx_set_config(const std::string& name, const ::vnx::Variant& value, const std::function<void()>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) {
auto _method = ::vnx::ModuleInterface_vnx_set_config::create();
_method->name = name;
_method->value = value;
const auto _request_id = ++vnx_next_id;
{
std::lock_guard<std::mutex> _lock(vnx_mutex);
vnx_pending[_request_id] = 11;
vnx_queue_vnx_set_config[_request_id] = std::make_pair(_callback, _error_callback);
}
vnx_request(_method, _request_id);
return _request_id;
}
uint64_t FileServerAsyncClient::vnx_get_type_code(const std::function<void(const ::vnx::TypeCode&)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) {
auto _method = ::vnx::ModuleInterface_vnx_get_type_code::create();
const auto _request_id = ++vnx_next_id;
{
std::lock_guard<std::mutex> _lock(vnx_mutex);
vnx_pending[_request_id] = 12;
vnx_queue_vnx_get_type_code[_request_id] = std::make_pair(_callback, _error_callback);
}
vnx_request(_method, _request_id);
return _request_id;
}
uint64_t FileServerAsyncClient::vnx_get_module_info(const std::function<void(std::shared_ptr<const ::vnx::ModuleInfo>)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) {
auto _method = ::vnx::ModuleInterface_vnx_get_module_info::create();
const auto _request_id = ++vnx_next_id;
{
std::lock_guard<std::mutex> _lock(vnx_mutex);
vnx_pending[_request_id] = 13;
vnx_queue_vnx_get_module_info[_request_id] = std::make_pair(_callback, _error_callback);
}
vnx_request(_method, _request_id);
return _request_id;
}
uint64_t FileServerAsyncClient::vnx_restart(const std::function<void()>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) {
auto _method = ::vnx::ModuleInterface_vnx_restart::create();
const auto _request_id = ++vnx_next_id;
{
std::lock_guard<std::mutex> _lock(vnx_mutex);
vnx_pending[_request_id] = 14;
vnx_queue_vnx_restart[_request_id] = std::make_pair(_callback, _error_callback);
}
vnx_request(_method, _request_id);
return _request_id;
}
uint64_t FileServerAsyncClient::vnx_stop(const std::function<void()>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) {
auto _method = ::vnx::ModuleInterface_vnx_stop::create();
const auto _request_id = ++vnx_next_id;
{
std::lock_guard<std::mutex> _lock(vnx_mutex);
vnx_pending[_request_id] = 15;
vnx_queue_vnx_stop[_request_id] = std::make_pair(_callback, _error_callback);
}
vnx_request(_method, _request_id);
return _request_id;
}
uint64_t FileServerAsyncClient::vnx_self_test(const std::function<void(const vnx::bool_t&)>& _callback, const std::function<void(const vnx::exception&)>& _error_callback) {
auto _method = ::vnx::ModuleInterface_vnx_self_test::create();
const auto _request_id = ++vnx_next_id;
{
std::lock_guard<std::mutex> _lock(vnx_mutex);
vnx_pending[_request_id] = 16;
vnx_queue_vnx_self_test[_request_id] = std::make_pair(_callback, _error_callback);
}
vnx_request(_method, _request_id);
return _request_id;
}
int32_t FileServerAsyncClient::vnx_purge_request(uint64_t _request_id, const vnx::exception& _ex) {
std::unique_lock<std::mutex> _lock(vnx_mutex);
const auto _iter = vnx_pending.find(_request_id);
if(_iter == vnx_pending.end()) {
return -1;
}
const auto _index = _iter->second;
vnx_pending.erase(_iter);
switch(_index) {
case 0: {
const auto _iter = vnx_queue_read_file.find(_request_id);
if(_iter != vnx_queue_read_file.end()) {
const auto _callback = std::move(_iter->second.second);
vnx_queue_read_file.erase(_iter);
_lock.unlock();
if(_callback) {
_callback(_ex);
}
}
break;
}
case 1: {
const auto _iter = vnx_queue_read_file_range.find(_request_id);
if(_iter != vnx_queue_read_file_range.end()) {
const auto _callback = std::move(_iter->second.second);
vnx_queue_read_file_range.erase(_iter);
_lock.unlock();
if(_callback) {
_callback(_ex);
}
}
break;
}
case 2: {
const auto _iter = vnx_queue_get_file_info.find(_request_id);
if(_iter != vnx_queue_get_file_info.end()) {
const auto _callback = std::move(_iter->second.second);
vnx_queue_get_file_info.erase(_iter);
_lock.unlock();
if(_callback) {
_callback(_ex);
}
}
break;
}
case 3: {
const auto _iter = vnx_queue_read_directory.find(_request_id);
if(_iter != vnx_queue_read_directory.end()) {
const auto _callback = std::move(_iter->second.second);
vnx_queue_read_directory.erase(_iter);
_lock.unlock();
if(_callback) {
_callback(_ex);
}
}
break;
}
case 4: {
const auto _iter = vnx_queue_write_file.find(_request_id);
if(_iter != vnx_queue_write_file.end()) {
const auto _callback = std::move(_iter->second.second);
vnx_queue_write_file.erase(_iter);
_lock.unlock();
if(_callback) {
_callback(_ex);
}
}
break;
}
case 5: {
const auto _iter = vnx_queue_delete_file.find(_request_id);
if(_iter != vnx_queue_delete_file.end()) {
const auto _callback = std::move(_iter->second.second);
vnx_queue_delete_file.erase(_iter);
_lock.unlock();
if(_callback) {
_callback(_ex);
}
}
break;
}
case 6: {
const auto _iter = vnx_queue_http_request.find(_request_id);
if(_iter != vnx_queue_http_request.end()) {
const auto _callback = std::move(_iter->second.second);
vnx_queue_http_request.erase(_iter);
_lock.unlock();
if(_callback) {
_callback(_ex);
}
}
break;
}
case 7: {
const auto _iter = vnx_queue_http_request_chunk.find(_request_id);
if(_iter != vnx_queue_http_request_chunk.end()) {
const auto _callback = std::move(_iter->second.second);
vnx_queue_http_request_chunk.erase(_iter);
_lock.unlock();
if(_callback) {
_callback(_ex);
}
}
break;
}
case 8: {
const auto _iter = vnx_queue_vnx_get_config_object.find(_request_id);
if(_iter != vnx_queue_vnx_get_config_object.end()) {
const auto _callback = std::move(_iter->second.second);
vnx_queue_vnx_get_config_object.erase(_iter);
_lock.unlock();
if(_callback) {
_callback(_ex);
}
}
break;
}
case 9: {
const auto _iter = vnx_queue_vnx_get_config.find(_request_id);
if(_iter != vnx_queue_vnx_get_config.end()) {
const auto _callback = std::move(_iter->second.second);
vnx_queue_vnx_get_config.erase(_iter);
_lock.unlock();
if(_callback) {
_callback(_ex);
}
}
break;
}
case 10: {
const auto _iter = vnx_queue_vnx_set_config_object.find(_request_id);
if(_iter != vnx_queue_vnx_set_config_object.end()) {
const auto _callback = std::move(_iter->second.second);
vnx_queue_vnx_set_config_object.erase(_iter);
_lock.unlock();
if(_callback) {
_callback(_ex);
}
}
break;
}
case 11: {
const auto _iter = vnx_queue_vnx_set_config.find(_request_id);
if(_iter != vnx_queue_vnx_set_config.end()) {
const auto _callback = std::move(_iter->second.second);
vnx_queue_vnx_set_config.erase(_iter);
_lock.unlock();
if(_callback) {
_callback(_ex);
}
}
break;
}
case 12: {
const auto _iter = vnx_queue_vnx_get_type_code.find(_request_id);
if(_iter != vnx_queue_vnx_get_type_code.end()) {
const auto _callback = std::move(_iter->second.second);
vnx_queue_vnx_get_type_code.erase(_iter);
_lock.unlock();
if(_callback) {
_callback(_ex);
}
}
break;
}
case 13: {
const auto _iter = vnx_queue_vnx_get_module_info.find(_request_id);
if(_iter != vnx_queue_vnx_get_module_info.end()) {
const auto _callback = std::move(_iter->second.second);
vnx_queue_vnx_get_module_info.erase(_iter);
_lock.unlock();
if(_callback) {
_callback(_ex);
}
}
break;
}
case 14: {
const auto _iter = vnx_queue_vnx_restart.find(_request_id);
if(_iter != vnx_queue_vnx_restart.end()) {
const auto _callback = std::move(_iter->second.second);
vnx_queue_vnx_restart.erase(_iter);
_lock.unlock();
if(_callback) {
_callback(_ex);
}
}
break;
}
case 15: {
const auto _iter = vnx_queue_vnx_stop.find(_request_id);
if(_iter != vnx_queue_vnx_stop.end()) {
const auto _callback = std::move(_iter->second.second);
vnx_queue_vnx_stop.erase(_iter);
_lock.unlock();
if(_callback) {
_callback(_ex);
}
}
break;
}
case 16: {
const auto _iter = vnx_queue_vnx_self_test.find(_request_id);
if(_iter != vnx_queue_vnx_self_test.end()) {
const auto _callback = std::move(_iter->second.second);
vnx_queue_vnx_self_test.erase(_iter);
_lock.unlock();
if(_callback) {
_callback(_ex);
}
}
break;
}
}
return _index;
}
int32_t FileServerAsyncClient::vnx_callback_switch(uint64_t _request_id, std::shared_ptr<const vnx::Value> _value) {
std::unique_lock<std::mutex> _lock(vnx_mutex);
const auto _iter = vnx_pending.find(_request_id);
if(_iter == vnx_pending.end()) {
throw std::runtime_error("FileServerAsyncClient: received unknown return");
}
const auto _index = _iter->second;
vnx_pending.erase(_iter);
switch(_index) {
case 0: {
const auto _iter = vnx_queue_read_file.find(_request_id);
if(_iter == vnx_queue_read_file.end()) {
throw std::runtime_error("FileServerAsyncClient: callback not found");
}
const auto _callback = std::move(_iter->second.first);
vnx_queue_read_file.erase(_iter);
_lock.unlock();
if(_callback) {
if(auto _result = std::dynamic_pointer_cast<const ::vnx::addons::FileServer_read_file_return>(_value)) {
_callback(_result->_ret_0);
} else if(_value && !_value->is_void()) {
_callback(_value->get_field_by_index(0).to<::vnx::Buffer>());
} else {
throw std::logic_error("FileServerAsyncClient: invalid return value");
}
}
break;
}
case 1: {
const auto _iter = vnx_queue_read_file_range.find(_request_id);
if(_iter == vnx_queue_read_file_range.end()) {
throw std::runtime_error("FileServerAsyncClient: callback not found");
}
const auto _callback = std::move(_iter->second.first);
vnx_queue_read_file_range.erase(_iter);
_lock.unlock();
if(_callback) {
if(auto _result = std::dynamic_pointer_cast<const ::vnx::addons::FileServer_read_file_range_return>(_value)) {
_callback(_result->_ret_0);
} else if(_value && !_value->is_void()) {
_callback(_value->get_field_by_index(0).to<::vnx::Buffer>());
} else {
throw std::logic_error("FileServerAsyncClient: invalid return value");
}
}
break;
}
case 2: {
const auto _iter = vnx_queue_get_file_info.find(_request_id);
if(_iter == vnx_queue_get_file_info.end()) {
throw std::runtime_error("FileServerAsyncClient: callback not found");
}
const auto _callback = std::move(_iter->second.first);
vnx_queue_get_file_info.erase(_iter);
_lock.unlock();
if(_callback) {
if(auto _result = std::dynamic_pointer_cast<const ::vnx::addons::FileServer_get_file_info_return>(_value)) {
_callback(_result->_ret_0);
} else if(_value && !_value->is_void()) {
_callback(_value->get_field_by_index(0).to<::vnx::addons::file_info_t>());
} else {
throw std::logic_error("FileServerAsyncClient: invalid return value");
}
}
break;
}
case 3: {
const auto _iter = vnx_queue_read_directory.find(_request_id);
if(_iter == vnx_queue_read_directory.end()) {
throw std::runtime_error("FileServerAsyncClient: callback not found");
}
const auto _callback = std::move(_iter->second.first);
vnx_queue_read_directory.erase(_iter);
_lock.unlock();
if(_callback) {
if(auto _result = std::dynamic_pointer_cast<const ::vnx::addons::FileServer_read_directory_return>(_value)) {
_callback(_result->_ret_0);
} else if(_value && !_value->is_void()) {
_callback(_value->get_field_by_index(0).to<std::vector<::vnx::addons::file_info_t>>());
} else {
throw std::logic_error("FileServerAsyncClient: invalid return value");
}
}
break;
}
case 4: {
const auto _iter = vnx_queue_write_file.find(_request_id);
if(_iter == vnx_queue_write_file.end()) {
throw std::runtime_error("FileServerAsyncClient: callback not found");
}
const auto _callback = std::move(_iter->second.first);
vnx_queue_write_file.erase(_iter);
_lock.unlock();
if(_callback) {
_callback();
}
break;
}
case 5: {
const auto _iter = vnx_queue_delete_file.find(_request_id);
if(_iter == vnx_queue_delete_file.end()) {
throw std::runtime_error("FileServerAsyncClient: callback not found");
}
const auto _callback = std::move(_iter->second.first);
vnx_queue_delete_file.erase(_iter);
_lock.unlock();
if(_callback) {
_callback();
}
break;
}
case 6: {
const auto _iter = vnx_queue_http_request.find(_request_id);
if(_iter == vnx_queue_http_request.end()) {
throw std::runtime_error("FileServerAsyncClient: callback not found");
}
const auto _callback = std::move(_iter->second.first);
vnx_queue_http_request.erase(_iter);
_lock.unlock();
if(_callback) {
if(auto _result = std::dynamic_pointer_cast<const ::vnx::addons::HttpComponent_http_request_return>(_value)) {
_callback(_result->_ret_0);
} else if(_value && !_value->is_void()) {
_callback(_value->get_field_by_index(0).to<std::shared_ptr<const ::vnx::addons::HttpResponse>>());
} else {
throw std::logic_error("FileServerAsyncClient: invalid return value");
}
}
break;
}
case 7: {
const auto _iter = vnx_queue_http_request_chunk.find(_request_id);
if(_iter == vnx_queue_http_request_chunk.end()) {
throw std::runtime_error("FileServerAsyncClient: callback not found");
}
const auto _callback = std::move(_iter->second.first);
vnx_queue_http_request_chunk.erase(_iter);
_lock.unlock();
if(_callback) {
if(auto _result = std::dynamic_pointer_cast<const ::vnx::addons::HttpComponent_http_request_chunk_return>(_value)) {
_callback(_result->_ret_0);
} else if(_value && !_value->is_void()) {
_callback(_value->get_field_by_index(0).to<std::shared_ptr<const ::vnx::addons::HttpData>>());
} else {
throw std::logic_error("FileServerAsyncClient: invalid return value");
}
}
break;
}
case 8: {
const auto _iter = vnx_queue_vnx_get_config_object.find(_request_id);
if(_iter == vnx_queue_vnx_get_config_object.end()) {
throw std::runtime_error("FileServerAsyncClient: callback not found");
}
const auto _callback = std::move(_iter->second.first);
vnx_queue_vnx_get_config_object.erase(_iter);
_lock.unlock();
if(_callback) {
if(auto _result = std::dynamic_pointer_cast<const ::vnx::ModuleInterface_vnx_get_config_object_return>(_value)) {
_callback(_result->_ret_0);
} else if(_value && !_value->is_void()) {
_callback(_value->get_field_by_index(0).to<::vnx::Object>());
} else {
throw std::logic_error("FileServerAsyncClient: invalid return value");
}
}
break;
}
case 9: {
const auto _iter = vnx_queue_vnx_get_config.find(_request_id);
if(_iter == vnx_queue_vnx_get_config.end()) {
throw std::runtime_error("FileServerAsyncClient: callback not found");
}
const auto _callback = std::move(_iter->second.first);
vnx_queue_vnx_get_config.erase(_iter);
_lock.unlock();
if(_callback) {
if(auto _result = std::dynamic_pointer_cast<const ::vnx::ModuleInterface_vnx_get_config_return>(_value)) {
_callback(_result->_ret_0);
} else if(_value && !_value->is_void()) {
_callback(_value->get_field_by_index(0).to<::vnx::Variant>());
} else {
throw std::logic_error("FileServerAsyncClient: invalid return value");
}
}
break;
}
case 10: {
const auto _iter = vnx_queue_vnx_set_config_object.find(_request_id);
if(_iter == vnx_queue_vnx_set_config_object.end()) {
throw std::runtime_error("FileServerAsyncClient: callback not found");
}
const auto _callback = std::move(_iter->second.first);
vnx_queue_vnx_set_config_object.erase(_iter);
_lock.unlock();
if(_callback) {
_callback();
}
break;
}
case 11: {
const auto _iter = vnx_queue_vnx_set_config.find(_request_id);
if(_iter == vnx_queue_vnx_set_config.end()) {
throw std::runtime_error("FileServerAsyncClient: callback not found");
}
const auto _callback = std::move(_iter->second.first);
vnx_queue_vnx_set_config.erase(_iter);
_lock.unlock();
if(_callback) {
_callback();
}
break;
}
case 12: {
const auto _iter = vnx_queue_vnx_get_type_code.find(_request_id);
if(_iter == vnx_queue_vnx_get_type_code.end()) {
throw std::runtime_error("FileServerAsyncClient: callback not found");
}
const auto _callback = std::move(_iter->second.first);
vnx_queue_vnx_get_type_code.erase(_iter);
_lock.unlock();
if(_callback) {
if(auto _result = std::dynamic_pointer_cast<const ::vnx::ModuleInterface_vnx_get_type_code_return>(_value)) {
_callback(_result->_ret_0);
} else if(_value && !_value->is_void()) {
_callback(_value->get_field_by_index(0).to<::vnx::TypeCode>());
} else {
throw std::logic_error("FileServerAsyncClient: invalid return value");
}
}
break;
}
case 13: {
const auto _iter = vnx_queue_vnx_get_module_info.find(_request_id);
if(_iter == vnx_queue_vnx_get_module_info.end()) {
throw std::runtime_error("FileServerAsyncClient: callback not found");
}
const auto _callback = std::move(_iter->second.first);
vnx_queue_vnx_get_module_info.erase(_iter);
_lock.unlock();
if(_callback) {
if(auto _result = std::dynamic_pointer_cast<const ::vnx::ModuleInterface_vnx_get_module_info_return>(_value)) {
_callback(_result->_ret_0);
} else if(_value && !_value->is_void()) {
_callback(_value->get_field_by_index(0).to<std::shared_ptr<const ::vnx::ModuleInfo>>());
} else {
throw std::logic_error("FileServerAsyncClient: invalid return value");
}
}
break;
}
case 14: {
const auto _iter = vnx_queue_vnx_restart.find(_request_id);
if(_iter == vnx_queue_vnx_restart.end()) {
throw std::runtime_error("FileServerAsyncClient: callback not found");
}
const auto _callback = std::move(_iter->second.first);
vnx_queue_vnx_restart.erase(_iter);
_lock.unlock();
if(_callback) {
_callback();
}
break;
}
case 15: {
const auto _iter = vnx_queue_vnx_stop.find(_request_id);
if(_iter == vnx_queue_vnx_stop.end()) {
throw std::runtime_error("FileServerAsyncClient: callback not found");
}
const auto _callback = std::move(_iter->second.first);
vnx_queue_vnx_stop.erase(_iter);
_lock.unlock();
if(_callback) {
_callback();
}
break;
}
case 16: {
const auto _iter = vnx_queue_vnx_self_test.find(_request_id);
if(_iter == vnx_queue_vnx_self_test.end()) {
throw std::runtime_error("FileServerAsyncClient: callback not found");
}
const auto _callback = std::move(_iter->second.first);
vnx_queue_vnx_self_test.erase(_iter);
_lock.unlock();
if(_callback) {
if(auto _result = std::dynamic_pointer_cast<const ::vnx::ModuleInterface_vnx_self_test_return>(_value)) {
_callback(_result->_ret_0);
} else if(_value && !_value->is_void()) {
_callback(_value->get_field_by_index(0).to<vnx::bool_t>());
} else {
throw std::logic_error("FileServerAsyncClient: invalid return value");
}
}
break;
}
default:
if(_index >= 0) {
throw std::logic_error("FileServerAsyncClient: invalid callback index");
}
}
return _index;
}
} // namespace vnx
} // namespace addons
| 35.794081 | 342 | 0.722726 | [
"object",
"vector"
] |
ebb891514b08b2ee48a7fd42c3168aaf6b87e409 | 8,030 | cpp | C++ | src/shendk/files/image/pvr/vector_quantizer.cpp | Shenmue-Mods/ShenmueDK | feca9c937fe5cf6fb99b11336792f33d9797aca7 | [
"MIT"
] | 4 | 2019-05-27T21:15:38.000Z | 2021-07-25T10:42:30.000Z | src/shendk/files/image/pvr/vector_quantizer.cpp | Shenmue-Mods/ShenmueDK | feca9c937fe5cf6fb99b11336792f33d9797aca7 | [
"MIT"
] | null | null | null | src/shendk/files/image/pvr/vector_quantizer.cpp | Shenmue-Mods/ShenmueDK | feca9c937fe5cf6fb99b11336792f33d9797aca7 | [
"MIT"
] | null | null | null | #include "shendk/files/image/pvr/vector_quantizer.h"
#include <cstring>
#include <algorithm>
#include <limits>
#include <Eigen/Dense>
#include "shendk/utils/math.h"
#include "shendk/files/image/pvr/twiddle.h"
namespace shendk {
namespace pvr {
struct VQBlock {
VQBlock()
: pixels(Eigen::MatrixXf(4, 4))
{}
VQBlock(uint8_t blockSize, uint8_t pixelSize)
: pixels(Eigen::MatrixXf(blockSize, pixelSize))
{}
inline void zero() {
pixels = pixels.Zero(pixels.rows(), pixels.cols());
}
inline void add(VQBlock& block) {
pixels += block.pixels;
}
inline void div(int group) {
pixels /= group;
}
inline float distance(const VQBlock& block) const {
return std::abs((pixels - block.pixels).sum());
}
uint8_t* toArrayTwiddled() {
// TODO: only works with RGBA blocks
uint8_t* array = new uint8_t[pixels.rows() * 4];
uint64_t destinationIndex = 0;
int64_t sourceIndex = 0;
uint64_t* twiddleMap = createTwiddleMap(pixels.rows());
uint32_t blockHeight, blockWidth;
blockHeight = blockWidth = pixels.rows() / 2;
for (uint32_t y = 0; y < blockHeight; y++) {
for (uint32_t x = 0; x < blockWidth; x++) {
destinationIndex = (twiddleMap[x] << 1) | twiddleMap[y];
array[destinationIndex * 4] = static_cast<uint8_t>(pixels(sourceIndex));
array[destinationIndex * 4 + 1] = static_cast<uint8_t>(pixels(sourceIndex + 1));
array[destinationIndex * 4 + 2] = static_cast<uint8_t>(pixels(sourceIndex + 2));
array[destinationIndex * 4 + 3] = static_cast<uint8_t>(pixels(sourceIndex + 3));
sourceIndex += 4;
}
}
delete[] twiddleMap;
return array;
}
uint8_t* toArray() {
Eigen::Matrix<uint8_t, Eigen::Dynamic, Eigen::Dynamic> matrix = pixels.cast<uint8_t>();
uint8_t* array = new uint8_t(pixels.size());
memcpy(array, matrix.data(), pixels.size());
return array;
return nullptr;
}
uint32_t group = 0;
Eigen::MatrixXf pixels;
};
int nearest(const VQBlock& block, VQBlock* cluster, int clusterSize, double& nearestDistance) {
int i = 0;
int nearestIndex = 0;
double distance = 0;
double minDistance = 0;
for (i = 0; i < clusterSize; i++) {
minDistance = std::numeric_limits<double>::infinity();
nearestIndex = block.group;
for (i = 0; i < clusterSize; i++) {
if (minDistance > (distance = cluster[i].distance(block))) {
minDistance = distance;
nearestIndex = i;
}
}
}
nearestDistance = minDistance;
return nearestIndex;
}
std::vector<VQBlock> createBlocks(Image& image, int blockWidth, int blockHeight) {
//Convert bitmap to blocks
int width = image.width() / blockWidth;
int height = image.height() / blockHeight;
int blockSize = blockWidth * blockHeight * 4;
int blockCount = width * height;
std::vector<VQBlock> blocks(blockCount);
for (int y = 0; y < height - 1; y += blockHeight) {
for (int x = 0; x < width - 1; x += blockWidth) {
int blockIndex = (y / blockHeight) * width + (x / blockWidth);
blocks[blockIndex] = VQBlock(blockWidth * blockHeight, 4);
for (int k = 0; k < blockHeight; k++) {
for (int l = 0; l < blockWidth; l++) {
int imageIndex = ((y + k) * width + (x + l)) * 4;
int subVectorIndex = k * blockWidth + l;
blocks[blockIndex].pixels(subVectorIndex * 4) = image[imageIndex].b;
blocks[blockIndex].pixels(subVectorIndex * 4 + 1) = image[imageIndex].g;
blocks[blockIndex].pixels(subVectorIndex * 4 + 2) = image[imageIndex].r;
blocks[blockIndex].pixels(subVectorIndex * 4 + 3) = image[imageIndex].a;
}
}
}
}
return blocks;
}
std::vector<VQBlock> initializeCodeBook(std::vector<VQBlock> imageBlocks, int codeBookSize, bool fastInitialization) {
std::vector<VQBlock> codeBook(codeBookSize);
if (fastInitialization) {
int i = 0;
for (i = 0; i < codeBookSize; i++)
{
codeBook[i % codeBookSize] = VQBlock(imageBlocks[i]);
}
for (i = 0; i < imageBlocks.size(); i++)
{
imageBlocks[i].group = i % codeBookSize;
}
return codeBook;
} else {
int i = 0;
int imageLength = imageBlocks.size();
double sum = 0.0;
double* distances = new double[imageBlocks.size()];
codeBook[0] = VQBlock(imageBlocks[std::rand() % imageBlocks.size()]);
for (int cluster = 1; cluster < codeBookSize; cluster++) {
sum = 0;
for (i = 0; i < imageLength; i++) {
nearest(imageBlocks[i], codeBook.data(), cluster, distances[i]);
sum += distances[i];
}
sum = sum * std::clamp(std::rand(), 0, 0x7fff) / (0x7fff - 1.0);
for (i = 0; i < imageLength; i++) {
if ((sum -= distances[i]) > 0) continue;
codeBook[cluster] = VQBlock(imageBlocks[i]);
break;
}
}
double dump = 0.0;
for (i = 0; i < imageLength; i++) {
imageBlocks[i].group = nearest(imageBlocks[i], codeBook.data(), codeBookSize, dump);
}
return codeBook;
}
}
std::vector<VQBlock> createCodebook(Image& image, int codeBookSize, int blockWidth, int blockHeight)
{
if (image.width() % blockWidth != 0 || image.height() % blockHeight != 0) {
throw std::runtime_error("The image can't be devided by the given block size!");
}
std::vector<VQBlock> imageBlocks = createBlocks(image, blockWidth, blockHeight);
std::vector<VQBlock> codeBookBlocks = initializeCodeBook(imageBlocks, codeBookSize);
int i = 0;
int j = 0;
int changed = 0;
int nearestIndex = 0;
VQBlock imageBlock;
VQBlock codeBookBlock;
double dump = 0.0;
int runs = 0;
do {
for (i = 0; i < codeBookSize; i++) {
codeBookBlock = codeBookBlocks[i];
codeBookBlock.group = 0;
codeBookBlock.zero();
}
for (j = 0; j < imageBlocks.size(); j++) {
imageBlock = imageBlocks[j];
codeBookBlock = codeBookBlocks[imageBlock.group];
codeBookBlock.group += 1;
codeBookBlock.add(imageBlock);
}
for (i = 0; i < codeBookSize; i++) {
codeBookBlock = codeBookBlocks[i];
codeBookBlock.div(codeBookBlock.group);
}
changed = 0;
for (j = 0; j < imageBlocks.size(); j++) {
imageBlock = imageBlocks[j];
nearestIndex = nearest(imageBlock, codeBookBlocks.data(), codeBookSize, dump);
if (nearestIndex != imageBlock.group)
{
changed++;
imageBlock.group = nearestIndex;
}
}
runs++;
} while (changed > (imageBlocks.size() >> 10));
for (i = 0; i < codeBookSize; i++) {
codeBookBlock = codeBookBlocks[i];
codeBookBlock.group = i;
}
return codeBookBlocks;
}
uint8_t* quantizeImage(Image& image, std::vector<VQBlock> codeBook, uint8_t blockSize) {
std::vector<VQBlock> blocks = createBlocks(image, blockSize, blockSize);
uint8_t* result = new uint8_t[blocks.size()];
double dump = 0.0;
for (int i = 0; i < blocks.size(); i++) {
VQBlock block = blocks[i];
result[i] = nearest(block, codeBook.data(), codeBook.size(), dump);
}
return result;
}
uint8_t* quantizeImage(Image& image, uint32_t codeBookSize, uint8_t blockSize, uint8_t pixelSize) {
std::vector<VQBlock> codeBook = createCodebook(image, codeBookSize);
return quantizeImage(image, codeBook, blockSize);
}
}
}
| 34.463519 | 118 | 0.568742 | [
"vector"
] |
ebbcd76ea99ea07426855a5aadd5c34b5d54ac6a | 956 | cpp | C++ | LuoguCodes/P1515.cpp | Anguei/OI-Codes | 0ef271e9af0619d4c236e314cd6d8708d356536a | [
"MIT"
] | null | null | null | LuoguCodes/P1515.cpp | Anguei/OI-Codes | 0ef271e9af0619d4c236e314cd6d8708d356536a | [
"MIT"
] | null | null | null | LuoguCodes/P1515.cpp | Anguei/OI-Codes | 0ef271e9af0619d4c236e314cd6d8708d356536a | [
"MIT"
] | null | null | null | //【P1515】旅行 - 洛谷 - 0
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
int a, b, n;
std::cin >> a >> b >> n;
std::vector<int> vec;
void init(std::vector<int> &vec);
init(vec);
while (n--) {
int t;
std::cin >> t;
vec.push_back(t);
}
std::sort(vec.begin(), vec.end());
std::vector<int> ans(vec.size(), 0);
//for (auto i : ans)std::cout << i << std::endl;
ans[0] = 1;
for (int i = 1; i < vec.size(); ++i) {
for (int j = 0; j < i; ++j) {
int dis = vec[i] - vec[j];
if (dis >= a && dis <= b) {
ans[i] += ans[j];
}
}
}
std::cout << ans.back() << std::endl;
}
void init(std::vector<int> &vec) {
vec.push_back(0);
vec.push_back(990);
vec.push_back(1010);
vec.push_back(1970);
vec.push_back(2030);
vec.push_back(2940);
vec.push_back(3060);
vec.push_back(3930);
vec.push_back(4060);
vec.push_back(4970);
vec.push_back(5030);
vec.push_back(5990);
vec.push_back(6010);
vec.push_back(7000);
} | 20.340426 | 49 | 0.575314 | [
"vector"
] |
ebc2300ee4613503c27ba7403f781bb3294c3fd2 | 4,037 | hpp | C++ | src/sf2cute/riff_phdr_chunk.hpp | gocha/sf2cc | b42f23c75667d414ac024858f5303fb7dc17e0fd | [
"Zlib"
] | 31 | 2016-07-20T23:23:17.000Z | 2022-03-12T13:23:06.000Z | src/sf2cute/riff_phdr_chunk.hpp | gocha/sf2cc | b42f23c75667d414ac024858f5303fb7dc17e0fd | [
"Zlib"
] | 6 | 2017-09-18T02:16:29.000Z | 2020-08-30T13:24:39.000Z | src/sf2cute/riff_phdr_chunk.hpp | gocha/sf2cc | b42f23c75667d414ac024858f5303fb7dc17e0fd | [
"Zlib"
] | 7 | 2016-11-03T03:27:06.000Z | 2021-06-07T11:02:56.000Z | /// @file
/// SoundFont "phdr" RIFF chunk header
///
/// @author gocha <https://github.com/gocha>
#ifndef SF2CUTE_RIFF_PHDR_CHUNK_HPP_
#define SF2CUTE_RIFF_PHDR_CHUNK_HPP_
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#include <ostream>
#include "riff.hpp"
namespace sf2cute {
class SFPreset;
/// The SFRIFFPhdrChunk class represents a SoundFont 2 "phdr" chunk.
class SFRIFFPhdrChunk : public RIFFChunkInterface {
public:
/// Unsigned integer type for the chunk size.
using size_type = RIFFChunkInterface::size_type;
/// The item size of phdr chunk, in terms of bytes.
static constexpr size_type kItemSize = 38;
/// Constructs a new empty SFRIFFPhdrChunk.
SFRIFFPhdrChunk();
/// Constructs a new SFRIFFPhdrChunk using the specified presets.
/// @param presets The presets of the chunk.
/// @throws std::length_error Too many presets.
SFRIFFPhdrChunk(
const std::vector<std::shared_ptr<SFPreset>> & presets);
/// Constructs a new copy of specified SFRIFFPhdrChunk.
/// @param origin a SFRIFFPhdrChunk object.
SFRIFFPhdrChunk(const SFRIFFPhdrChunk & origin) = default;
/// Copy-assigns a new value to the SFRIFFPhdrChunk, replacing its current contents.
/// @param origin a SFRIFFPhdrChunk object.
SFRIFFPhdrChunk & operator=(const SFRIFFPhdrChunk & origin) = default;
/// Acquires the contents of specified SFRIFFPhdrChunk.
/// @param origin a SFRIFFPhdrChunk object.
SFRIFFPhdrChunk(SFRIFFPhdrChunk && origin) = default;
/// Move-assigns a new value to the SFRIFFPhdrChunk, replacing its current contents.
/// @param origin a SFRIFFPhdrChunk object.
SFRIFFPhdrChunk & operator=(SFRIFFPhdrChunk && origin) = default;
/// Destructs the SFRIFFPhdrChunk.
virtual ~SFRIFFPhdrChunk() = default;
/// @copydoc RIFFChunkInterface::name()
virtual std::string name() const override {
return "phdr";
}
/// Returns the presets of this chunk.
/// @return the presets of this chunk.
const std::vector<std::shared_ptr<SFPreset>> &
presets() const {
return *presets_;
}
/// Sets the presets of this chunk.
/// @param presets the presets of this chunk.
/// @throws std::length_error Too many presets.
void set_presets(
const std::vector<std::shared_ptr<SFPreset>> & presets) {
presets_ = &presets;
size_ = kItemSize * NumItems();
}
/// Returns the whole length of this chunk.
/// @return the length of this chunk including a chunk header, in terms of bytes.
virtual size_type size() const noexcept override {
return 8 + size_;
}
/// Writes this chunk to the specified output stream.
/// @param out the output stream.
/// @throws std::length_error The chunk size exceeds the maximum.
/// @throws std::ios_base::failure An I/O error occurred.
virtual void Write(std::ostream & out) const override;
private:
/// Returns the number of preset items.
/// @return the number of preset items, including the terminator item.
/// @throws std::length_error Too many presets.
uint16_t NumItems() const;
/// Writes an item of phdr chunk.
/// @param out the output stream.
/// @param name the name of preset.
/// @param preset_number the preset number.
/// @param bank the bank number.
/// @param preset_bag_index the preset bag index starting from 0.
/// @param library the library.
/// @param genre the genre.
/// @param morphology the morphology.
/// @return the output stream.
/// @throws std::ios_base::failure An I/O error occurred.
static std::ostream & WriteItem(std::ostream & out,
const std::string & name,
uint16_t preset_number,
uint16_t bank,
uint16_t preset_bag_index,
uint32_t library,
uint32_t genre,
uint32_t morphology);
/// The name of the chunk.
std::string name_;
/// The size of the chunk (excluding header).
size_type size_;
/// The presets of the chunk.
const std::vector<std::shared_ptr<SFPreset>> * presets_;
};
} // namespace sf2cute
#endif // SF2CUTE_RIFF_PHDR_CHUNK_HPP_
| 31.053846 | 86 | 0.704484 | [
"object",
"vector"
] |
ebc2ca3a56d272ea7f27258047e365369cc0a3f9 | 3,547 | cpp | C++ | src/pke/unittest/UnitTestBVDCRT.cpp | mattdano/palisade | 6e49bc3a850672a142eea209e6d71505e689cb81 | [
"BSD-2-Clause"
] | null | null | null | src/pke/unittest/UnitTestBVDCRT.cpp | mattdano/palisade | 6e49bc3a850672a142eea209e6d71505e689cb81 | [
"BSD-2-Clause"
] | null | null | null | src/pke/unittest/UnitTestBVDCRT.cpp | mattdano/palisade | 6e49bc3a850672a142eea209e6d71505e689cb81 | [
"BSD-2-Clause"
] | null | null | null | /*
* @file
* @author TPOC: contact@palisade-crypto.org
*
* @copyright Copyright (c) 2019, New Jersey Institute of Technology (NJIT)
* 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 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.
*
*/
#include "include/gtest/gtest.h"
#include <iostream>
#include <vector>
#include "../lib/cryptocontext.h"
#include "encoding/encodings.h"
#include "utils/debug.h"
#include "utils/parmfactory.h"
using namespace std;
using namespace lbcrypto;
class UTBGVDCRT : public ::testing::Test {
protected:
void SetUp() {}
void TearDown() {
CryptoContextFactory<Poly>::ReleaseAllContexts();
CryptoContextFactory<DCRTPoly>::ReleaseAllContexts();
}
public:
};
//FIXME this test might be redundant in other files; perhaps this entire file can go
#if !defined(_MSC_VER)
TEST_F(UTBGVDCRT, Poly_bgv_DCRT_MODREDUCE) {
usint m = 8;
usint numOfTower = 3;
PlaintextModulus plaintextModulus = 8;
float stdDev = 4;
shared_ptr<ILDCRTParams<BigInteger>> params = GenerateDCRTParams<BigInteger>(m, numOfTower, 48);
CryptoContext<DCRTPoly> cc = CryptoContextFactory<DCRTPoly>::genCryptoContextBGV(params, plaintextModulus, m, stdDev);
cc->Enable(ENCRYPTION);
cc->Enable(SHE);
cc->Enable(LEVELEDSHE);
// Initialize the public key containers.
LPKeyPair<DCRTPoly> kp = cc->KeyGen();
std::vector<int64_t> vectorOfInts1 = { 4,1,2,3 };
Plaintext intArray1 = cc->MakeCoefPackedPlaintext(vectorOfInts1);
Plaintext intArrayNew;
////////////////////////////////////////////////////////////
//Encryption
////////////////////////////////////////////////////////////
Ciphertext<DCRTPoly> ciphertext = cc->Encrypt(kp.publicKey, intArray1);
cc->Decrypt(kp.secretKey, ciphertext, &intArrayNew);
EXPECT_EQ(intArray1->GetCoefPackedValue(), intArrayNew->GetCoefPackedValue()) << "Decrypt without ModReduce fails";
Ciphertext<DCRTPoly> ciphertextR = cc->ModReduce(ciphertext);
//drop a tower from the secret key
auto skEl(kp.secretKey->GetPrivateElement());
skEl.DropLastElement();
kp.secretKey->SetPrivateElement(skEl);
Plaintext intArrayNew2;
cc->Decrypt(kp.secretKey, ciphertextR, &intArrayNew2);
intArrayNew2->SetLength(intArray1->GetLength());
EXPECT_EQ(intArray1->GetCoefPackedValue(), intArrayNew2->GetCoefPackedValue()) << "Decrypt after ModReduce fails";;
}
#endif
| 32.245455 | 119 | 0.735551 | [
"vector"
] |
ebc886830342bfc43b612564a35467dc77747429 | 2,499 | cpp | C++ | src/geo_bsd/hpgl/median_ik.cpp | hpgl/hpgl | 72d8c4113c242295de740513093f5779c94ba84a | [
"BSD-3-Clause"
] | 70 | 2015-01-21T12:24:50.000Z | 2022-03-16T02:10:45.000Z | src/geo_bsd/hpgl/median_ik.cpp | hpgl/hpgl | 72d8c4113c242295de740513093f5779c94ba84a | [
"BSD-3-Clause"
] | 8 | 2015-04-22T13:14:30.000Z | 2021-11-23T12:16:32.000Z | src/geo_bsd/hpgl/median_ik.cpp | hpgl/hpgl | 72d8c4113c242295de740513093f5779c94ba84a | [
"BSD-3-Clause"
] | 18 | 2015-02-15T18:04:31.000Z | 2021-01-16T08:54:32.000Z | #include "stdafx.h"
#include "median_ik.h"
#include "covariance_field.h"
#include "progress_reporter.h"
#include "my_kriging_weights.h"
#include "kriging_interpolation.h"
#include "sugarbox_indexed_neighbour_lookup.h"
#include "is_informed_predicate.h"
#include "mean_provider.h"
#include "output.h"
namespace hpgl
{
inline indicator_index_t choose_indicator(indicator_probability_t prob)
{
if (prob <= 0.5)
return 0;
else
return 1;
}
void median_ik_for_two_indicators(
const median_ik_params & params,
const sugarbox_grid_t & grid,
const indicator_property_array_t & input_property,
indicator_property_array_t & output_property
)
{
typedef sugarbox_grid_t grid_t;
progress_reporter_t report(grid.size());
assert(input_property.size() == output_property.size());
if (input_property.size() != output_property.size())
{
throw hpgl_exception(
"median_ik_for_two_indicators",
boost::format("Input property size %1% is not equal output property size %2%") % input_property.size() % output_property.size());
}
if (input_property.size() != grid.size())
throw hpgl_exception("median_ik_for_two_indicators", boost::format("Properties size '%s' is not equal to grid size '%s'") % input_property.size() % grid.size());
size_t prop_size = input_property.size();
covariance_field_t cov_field(params.m_radiuses, cov_model_t(params));
std::vector<node_index_t> indices;
indicator_array_adapter_t prop_adapter(&input_property, 1);
typedef indexed_neighbour_lookup_t<grid_t, covariance_field_t> nl_t;
nl_t nl(&grid, &cov_field, params);
for (node_index_t node = 0; node < input_property.size(); ++node)
{
if (input_property.is_informed(node))
nl.add_node(node);
}
report.start();
#pragma omp parallel
{
#pragma omp for
for (node_index_t idx = 0; idx < prop_size; ++idx)
{
double prob;
indicator_index_t ind_index;
kriging_interpolation(
prop_adapter,
is_informed_predicate_t<indicator_property_array_t>(input_property),
idx,
cov_field,
single_mean_t(params.m_marginal_probs[1]),
nl, sk_weight_calculator_t(), prob);
ind_index = choose_indicator(prob);
output_property.set_at(idx, ind_index);
#pragma omp critical
{
report.next_lap();
}
}
}
report.stop();
write(boost::format("Done. Average speed: %1% point/sec.\n")
% report.iterations_per_second());
}
}
| 26.03125 | 164 | 0.70068 | [
"vector"
] |
ebc88f104c49d7db6c4de63e213c18f429c3e18a | 8,745 | cpp | C++ | src/Crash/Modules/ModuleHandler.cpp | Ryan-rsm-McKenzie/CrashLoggerSSE | 76965c32456c981e516ddc3576bfe626c104a78e | [
"MIT"
] | 4 | 2021-12-06T05:52:36.000Z | 2022-01-12T23:30:45.000Z | src/Crash/Modules/ModuleHandler.cpp | Ryan-rsm-McKenzie/CrashLoggerSSE | 76965c32456c981e516ddc3576bfe626c104a78e | [
"MIT"
] | null | null | null | src/Crash/Modules/ModuleHandler.cpp | Ryan-rsm-McKenzie/CrashLoggerSSE | 76965c32456c981e516ddc3576bfe626c104a78e | [
"MIT"
] | 3 | 2021-12-10T04:01:21.000Z | 2022-01-12T23:30:47.000Z | #include "Crash/Modules/ModuleHandler.h"
#define WIN32_LEAN_AND_MEAN
#define NOGDICAPMASKS
#define NOVIRTUALKEYCODES
#define NOWINMESSAGES
#define NOWINSTYLES
#define NOSYSMETRICS
#define NOMENUS
#define NOICONS
#define NOKEYSTATES
#define NOSYSCOMMANDS
#define NORASTEROPS
#define NOSHOWWINDOW
#define OEMRESOURCE
#define NOATOM
#define NOCLIPBOARD
#define NOCOLOR
#define NOCTLMGR
#define NODRAWTEXT
#define NOGDI
#define NOKERNEL
//#define NOUSER
#define NONLS
#define NOMB
#define NOMEMMGR
#define NOMETAFILE
#define NOMINMAX
//#define NOMSG
#define NOOPENFILE
#define NOSCROLL
#define NOSERVICE
#define NOSOUND
#define NOTEXTMETRIC
#define NOWH
#define NOWINOFFSETS
#define NOCOMM
#define NOKANJI
#define NOHELP
#define NOPROFILER
#define NODEFERWINDOWPOS
#define NOMCX
#include <Windows.h>
#include <Psapi.h>
#undef max
#undef min
namespace Crash::Modules
{
namespace detail
{
class VTable
{
public:
VTable(
std::string_view a_name,
std::span<const std::byte> a_module,
std::span<const std::byte> a_data,
std::span<const std::byte> a_rdata)
{
const auto typeDesc = type_descriptor(a_name, a_data);
const auto col = typeDesc ? complete_object_locator(typeDesc, a_module, a_rdata) : nullptr;
_vtable = col ? virtual_table(col, a_rdata) : nullptr;
}
[[nodiscard]] const void* get() const noexcept { return _vtable; }
private:
[[nodiscard]] static auto type_descriptor(
std::string_view a_name,
std::span<const std::byte> a_data)
-> const RE::RTTI::TypeDescriptor*
{
constexpr std::size_t offset = 0x10; // offset of name into type descriptor
std::boyer_moore_horspool_searcher search(a_name.cbegin(), a_name.cend());
const auto& [first, last] = search(
reinterpret_cast<const char*>(a_data.data()),
reinterpret_cast<const char*>(a_data.data() + a_data.size()));
return first != last ?
reinterpret_cast<const RE::RTTI::TypeDescriptor*>(first - offset) :
nullptr;
}
[[nodiscard]] static auto complete_object_locator(
const RE::RTTI::TypeDescriptor* a_typeDesc,
std::span<const std::byte> a_module,
std::span<const std::byte> a_rdata)
-> const RE::RTTI::CompleteObjectLocator*
{
assert(a_typeDesc != nullptr);
const auto typeDesc = reinterpret_cast<std::uintptr_t>(a_typeDesc);
const auto rva = static_cast<std::uint32_t>(typeDesc - reinterpret_cast<std::uintptr_t>(a_module.data()));
const auto offset = static_cast<std::size_t>(a_rdata.data() - a_module.data());
const auto base = a_rdata.data();
const auto start = reinterpret_cast<const std::uint32_t*>(base);
const auto end = reinterpret_cast<const std::uint32_t*>(base + a_rdata.size());
for (auto iter = start; iter < end; ++iter) {
if (*iter == rva) {
// both base class desc and col can point to the type desc so we check
// the next int to see if it can be an rva to decide which type it is
if ((iter[1] < offset) || (offset + a_rdata.size() <= iter[1])) {
continue;
}
const auto ptr = reinterpret_cast<const std::byte*>(iter);
const auto col = reinterpret_cast<const RE::RTTI::CompleteObjectLocator*>(ptr - offsetof(RE::RTTI::CompleteObjectLocator, typeDescriptor));
if (col->offset != 0) {
continue;
}
return col;
}
}
return nullptr;
}
[[nodiscard]] static const void* virtual_table(
const RE::RTTI::CompleteObjectLocator* a_col,
std::span<const std::byte> a_rdata)
{
assert(a_col != nullptr);
const auto col = reinterpret_cast<std::uintptr_t>(a_col);
const auto base = a_rdata.data();
const auto start = reinterpret_cast<const std::uintptr_t*>(base);
const auto end = reinterpret_cast<const std::uintptr_t*>(base + a_rdata.size());
for (auto iter = start; iter < end; ++iter) {
if (*iter == col) {
return iter + 1;
}
}
return nullptr;
}
const void* _vtable{ nullptr };
};
class Fallout4 final :
public Module
{
private:
using super = Module;
protected:
friend class Factory;
using super::super;
[[nodiscard]] std::string get_frame_info(const boost::stacktrace::frame& a_frame) const override
{
const auto offset = reinterpret_cast<std::uintptr_t>(a_frame.address()) - address();
const auto it = std::lower_bound(
_offset2ID.rbegin(),
_offset2ID.rend(),
offset,
[](auto&& a_lhs, auto&& a_rhs) noexcept {
return a_lhs.offset >= a_rhs;
});
auto result = super::get_frame_info(a_frame);
if (it != _offset2ID.rend()) {
result += fmt::format(
" -> {}+0x{:X}"sv,
it->id,
offset - it->offset);
}
return result;
}
private:
REL::IDDatabase::Offset2ID _offset2ID{ std::execution::par_unseq };
};
class Factory
{
public:
[[nodiscard]] static std::unique_ptr<Module> create(::HMODULE a_module)
{
using result_t = std::unique_ptr<Module>;
auto name = get_name(a_module);
const auto image = get_image(a_module);
if (_stricmp(name.c_str(), util::module_name().c_str()) == 0) {
return result_t{ new Fallout4(std::move(name), image) };
} else {
return result_t{ new Module(std::move(name), image) };
}
}
private:
[[nodiscard]] static std::span<const std::byte> get_image(::HMODULE a_module)
{
const auto dosHeader = reinterpret_cast<const ::IMAGE_DOS_HEADER*>(a_module);
const auto ntHeader = util::adjust_pointer<::IMAGE_NT_HEADERS64>(dosHeader, dosHeader->e_lfanew);
return { reinterpret_cast<const std::byte*>(a_module), ntHeader->OptionalHeader.SizeOfImage };
}
[[nodiscard]] static std::string get_name(::HMODULE a_module)
{
std::vector<wchar_t> buf;
buf.reserve(MAX_PATH);
buf.resize(MAX_PATH / 2);
std::uint32_t result = 0;
do {
buf.resize(buf.size() * 2);
result = ::GetModuleFileNameW(
a_module,
buf.data(),
static_cast<std::uint32_t>(buf.size()));
} while (result && result == buf.size() && buf.size() <= std::numeric_limits<std::uint32_t>::max());
const std::filesystem::path p = buf.data();
return p.filename().generic_string();
}
};
}
std::string Module::frame_info(const boost::stacktrace::frame& a_frame) const
{
assert(in_range(a_frame.address()));
return get_frame_info(a_frame);
}
Module::Module(std::string a_name, std::span<const std::byte> a_image) :
_name(std::move(a_name)),
_image(a_image)
{
auto dosHeader = reinterpret_cast<const ::IMAGE_DOS_HEADER*>(_image.data());
auto ntHeader = util::adjust_pointer<::IMAGE_NT_HEADERS64>(dosHeader, dosHeader->e_lfanew);
std::span sections(
IMAGE_FIRST_SECTION(ntHeader),
ntHeader->FileHeader.NumberOfSections);
const std::array todo{
std::make_pair(".data"sv, std::ref(_data)),
std::make_pair(".rdata"sv, std::ref(_rdata)),
};
for (auto& [name, section] : todo) {
const auto it = std::find_if(
sections.begin(),
sections.end(),
[&](auto&& a_elem) {
constexpr auto size = std::extent_v<decltype(a_elem.Name)>;
const auto len = std::min(name.size(), size);
return std::memcmp(name.data(), a_elem.Name, len) == 0;
});
if (it != sections.end()) {
section = std::span{ it->VirtualAddress + _image.data(), it->SizeOfRawData };
}
}
if (!_image.empty() &&
!_data.empty() &&
!_rdata.empty()) {
detail::VTable v{ ".?AVtype_info@@"sv, _image, _data, _rdata };
_typeInfo = static_cast<const RE::msvc::type_info*>(v.get());
}
}
std::string Module::get_frame_info(const boost::stacktrace::frame& a_frame) const
{
const auto offset = reinterpret_cast<std::uintptr_t>(a_frame.address()) - address();
return fmt::format(
"+{:07X}"sv,
offset);
}
auto get_loaded_modules()
-> std::vector<std::unique_ptr<Module>>
{
const auto proc = ::GetCurrentProcess();
std::vector<::HMODULE> modules;
std::uint32_t needed = 0;
do {
modules.resize(needed / sizeof(::HMODULE));
::K32EnumProcessModules(
proc,
modules.data(),
static_cast<::DWORD>(modules.size() * sizeof(::HMODULE)),
reinterpret_cast<::DWORD*>(&needed));
} while ((modules.size() * sizeof(::HMODULE)) < needed);
decltype(get_loaded_modules()) results;
results.resize(modules.size());
std::for_each(
std::execution::par_unseq,
modules.begin(),
modules.end(),
[&](auto&& a_elem) {
const auto pos = std::addressof(a_elem) - modules.data();
results[pos] = detail::Factory::create(a_elem);
});
std::sort(
results.begin(),
results.end(),
[](auto&& a_lhs, auto&& a_rhs) noexcept {
return a_lhs->address() < a_rhs->address();
});
return results;
}
}
| 27.939297 | 145 | 0.656947 | [
"vector"
] |
1b12020c902114dbfee5fec581fbf74b2bfb2bad | 12,740 | cpp | C++ | ContextManager/src/ContextManager.cpp | merdahl/avs-device-sdk | 2cc16d8cc472afc9b7a736a8c1169f12b71dd229 | [
"Apache-2.0"
] | 1 | 2022-01-09T21:26:04.000Z | 2022-01-09T21:26:04.000Z | ContextManager/src/ContextManager.cpp | justdoGIT/avs-device-sdk | 2cc16d8cc472afc9b7a736a8c1169f12b71dd229 | [
"Apache-2.0"
] | null | null | null | ContextManager/src/ContextManager.cpp | justdoGIT/avs-device-sdk | 2cc16d8cc472afc9b7a736a8c1169f12b71dd229 | [
"Apache-2.0"
] | 1 | 2018-10-12T07:58:44.000Z | 2018-10-12T07:58:44.000Z | /*
* ContextManager.cpp
*
* Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <string>
#include <AVSCommon/Utils/Logger/Logger.h>
#include "ContextManager/ContextManager.h"
/// A state provider is expected to respond to a @c provideState request within this timeout period.
static const std::chrono::seconds PROVIDE_STATE_DEFAULT_TIMEOUT = std::chrono::seconds(2);
namespace alexaClientSDK {
namespace contextManager {
using namespace rapidjson;
using namespace avsCommon;
using namespace avsCommon::avs;
using namespace avsCommon::sdkInterfaces;
using namespace avsCommon::utils;
/// String to identify log entries originating from this file.
static const std::string TAG("ContextManager");
/**
* Create a LogEntry using this file's TAG and the specified event string.
*
* @param The event string for this @c LogEntry.
*/
#define LX(event) alexaClientSDK::avsCommon::utils::logger::LogEntry(TAG, event)
/// The namespace json key in the header of the state.
static const std::string NAMESPACE_JSON_KEY = "namespace";
/// The name json key in the header of the state.
static const std::string NAME_JSON_KEY = "name";
/// The header json key in the state.
static const std::string HEADER_JSON_KEY = "header";
/// The payload json key in the state.
static const std::string PAYLOAD_JSON_KEY = "payload";
/// The context json key.
static const std::string CONTEXT_JSON_KEY = "context";
std::shared_ptr<ContextManager> ContextManager::create() {
std::shared_ptr<ContextManager> contextManager(new ContextManager());
contextManager->init();
return contextManager;
}
ContextManager::~ContextManager() {
std::unique_lock<std::mutex> lock(m_contextRequesterMutex);
m_shutdown = true;
lock.unlock();
m_contextLoopNotifier.notify_one();
if (m_updateStatesThread.joinable()) {
m_updateStatesThread.join();
}
}
void ContextManager::setStateProvider(
const NamespaceAndName& stateProviderName,
std::shared_ptr<StateProviderInterface> stateProvider) {
std::lock_guard<std::mutex> stateProviderLock(m_stateProviderMutex);
if (!stateProvider) {
m_namespaceNameToStateInfo.erase(stateProviderName);
ACSDK_DEBUG(LX("setStateProvider")
.d("action", "removedStateProvider")
.d("namespace", stateProviderName.nameSpace)
.d("name", stateProviderName.name));
return;
}
auto stateInfoMappingIt = m_namespaceNameToStateInfo.find(stateProviderName);
if (m_namespaceNameToStateInfo.end() == stateInfoMappingIt) {
m_namespaceNameToStateInfo[stateProviderName] = std::make_shared<StateInfo>(stateProvider);
} else {
stateInfoMappingIt->second->stateProvider = stateProvider;
}
}
SetStateResult ContextManager::setState(
const NamespaceAndName& stateProviderName,
const std::string& jsonState,
const StateRefreshPolicy& refreshPolicy,
const unsigned int stateRequestToken) {
std::lock_guard<std::mutex> stateProviderLock(m_stateProviderMutex);
if (0 == stateRequestToken) {
return updateStateLocked(stateProviderName, jsonState, refreshPolicy);
}
if (stateRequestToken != m_stateRequestToken) {
ACSDK_ERROR(LX("setStateFailed")
.d("reason", "outdatedStateToken")
.d("namespace", stateProviderName.nameSpace)
.d("name", stateProviderName.name)
.sensitive("suppliedToken", stateRequestToken)
.sensitive("expectedToken", m_stateRequestToken));
return SetStateResult::STATE_TOKEN_OUTDATED;
}
SetStateResult status = updateStateLocked(stateProviderName, jsonState, refreshPolicy);
if (SetStateResult::SUCCESS == status) {
auto it = m_pendingOnStateProviders.find(stateProviderName);
if (it != m_pendingOnStateProviders.end()) {
m_pendingOnStateProviders.erase(it);
}
/*
* Once the m_pendingOnStateProviders is empty, it implies that the ContextManager has received the state
* from all the StateProviderInterfaces it sent provideState requests to, and updateStatesLoop should be
* notified.
*/
if (m_pendingOnStateProviders.empty()) {
m_setStateCompleteNotifier.notify_one();
}
}
return status;
}
void ContextManager::getContext(std::shared_ptr<ContextRequesterInterface> contextRequester) {
std::lock_guard<std::mutex> contextRequesterLock(m_contextRequesterMutex);
m_contextRequesterQueue.push(contextRequester);
/*
* The updateStatesLoop needs to be notified only when the first entry is added to the m_contextRequesterQueue.
* Once the states are updated, all the context requesters are updated with the latest context.
*/
if (m_contextRequesterQueue.size() > 0) {
m_contextLoopNotifier.notify_one();
}
}
ContextManager::StateInfo::StateInfo(
std::shared_ptr<avsCommon::sdkInterfaces::StateProviderInterface> initStateProvider,
std::string initJsonState,
avsCommon::avs::StateRefreshPolicy initRefreshPolicy) :
stateProvider{initStateProvider},
jsonState{initJsonState},
refreshPolicy{initRefreshPolicy} {
}
ContextManager::ContextManager() : m_stateRequestToken{0}, m_shutdown{false} {
}
void ContextManager::init() {
m_updateStatesThread = std::thread(&ContextManager::updateStatesLoop, this);
}
SetStateResult ContextManager::updateStateLocked(
const NamespaceAndName& stateProviderName,
const std::string& jsonState,
const StateRefreshPolicy& refreshPolicy) {
auto stateInfoMappingIt = m_namespaceNameToStateInfo.find(stateProviderName);
if (m_namespaceNameToStateInfo.end() == stateInfoMappingIt) {
if (StateRefreshPolicy::ALWAYS == refreshPolicy) {
ACSDK_ERROR(LX("updateStateLockedFailed")
.d("reason", "unregisteredStateProvider")
.d("namespace", stateProviderName.nameSpace)
.d("name", stateProviderName.name));
return SetStateResult::STATE_PROVIDER_NOT_REGISTERED;
}
m_namespaceNameToStateInfo[stateProviderName] = std::make_shared<StateInfo>(nullptr, jsonState, refreshPolicy);
} else {
stateInfoMappingIt->second->jsonState = jsonState;
stateInfoMappingIt->second->refreshPolicy = refreshPolicy;
ACSDK_DEBUG(LX("updateStateLocked")
.d("action", "updatedState")
.d("state", jsonState)
.d("namespace", stateProviderName.nameSpace)
.d("name", stateProviderName.name));
}
return SetStateResult::SUCCESS;
}
void ContextManager::requestStatesLocked(std::unique_lock<std::mutex>& stateProviderLock) {
m_stateRequestToken++;
/*
* If the token has wrapped around and token is 0, increment again. 0 is reserved for when the
* stateProviderInterface does not send a token.
*/
if (0 == m_stateRequestToken) {
m_stateRequestToken++;
}
unsigned int curStateReqToken(m_stateRequestToken);
for (auto it = m_namespaceNameToStateInfo.begin(); it != m_namespaceNameToStateInfo.end(); ++it) {
auto& stateInfo = it->second;
if (StateRefreshPolicy::ALWAYS == stateInfo->refreshPolicy) {
m_pendingOnStateProviders.insert(it->first);
stateProviderLock.unlock();
stateInfo->stateProvider->provideState(curStateReqToken);
stateProviderLock.lock();
}
}
}
void ContextManager::sendContextAndClearQueue(
const std::string& context,
const ContextRequestError& contextRequestError) {
std::unique_lock<std::mutex> contextRequesterLock(m_contextRequesterMutex);
while (!m_contextRequesterQueue.empty()) {
auto currentContextRequester = m_contextRequesterQueue.front();
contextRequesterLock.unlock();
if (!context.empty()) {
currentContextRequester->onContextAvailable(context);
} else {
currentContextRequester->onContextFailure(contextRequestError);
}
contextRequesterLock.lock();
m_contextRequesterQueue.pop();
}
}
void ContextManager::updateStatesLoop() {
while (true) {
{
std::unique_lock<std::mutex> lock(m_contextRequesterMutex);
m_contextLoopNotifier.wait(lock, [this]() { return (!m_contextRequesterQueue.empty() || m_shutdown); });
if (m_shutdown) {
return;
}
}
std::unique_lock<std::mutex> stateProviderLock(m_stateProviderMutex);
requestStatesLocked(stateProviderLock);
if (!m_pendingOnStateProviders.empty()) {
if (!m_setStateCompleteNotifier.wait_for(stateProviderLock, PROVIDE_STATE_DEFAULT_TIMEOUT, [this]() {
return m_pendingOnStateProviders.empty();
})) {
stateProviderLock.unlock();
ACSDK_ERROR(LX("updateStatesLoopFailed").d("reason", "stateProviderTimedOut"));
sendContextAndClearQueue("", ContextRequestError::STATE_PROVIDER_TIMEDOUT);
continue;
}
}
stateProviderLock.unlock();
sendContextToRequesters();
}
}
Value ContextManager::buildHeader(const NamespaceAndName& namespaceAndName, Document::AllocatorType& allocator) {
Value header(kObjectType);
header.AddMember(StringRef(NAMESPACE_JSON_KEY), namespaceAndName.nameSpace, allocator);
header.AddMember(StringRef(NAME_JSON_KEY), namespaceAndName.name, allocator);
return header;
}
Value ContextManager::buildState(
const NamespaceAndName& namespaceAndName,
const std::string jsonPayloadValue,
Document::AllocatorType& allocator) {
Document payload;
Value state(kObjectType);
Value header = buildHeader(namespaceAndName, allocator);
// If the header is an empty object or during parsing the payload, an error occurs, return an empty event value.
if (header.ObjectEmpty()) {
ACSDK_ERROR(LX("buildStateFailed").d("reason", "emptyHeader"));
return state;
}
if (payload.Parse(jsonPayloadValue).HasParseError()) {
ACSDK_ERROR(LX("buildStateFailed").d("reason", "parseError").d("payload", jsonPayloadValue));
return state;
}
state.AddMember(StringRef(HEADER_JSON_KEY), header, allocator);
state.AddMember(StringRef(PAYLOAD_JSON_KEY), Value(payload, allocator), allocator);
return state;
}
void ContextManager::sendContextToRequesters() {
bool errorBuildingContext = false;
Document jsonContext;
StringBuffer jsonContextBuf;
jsonContext.SetObject();
Value statesArray(kArrayType);
Document::AllocatorType& allocator = jsonContext.GetAllocator();
std::unique_lock<std::mutex> stateProviderLock(m_stateProviderMutex);
for (auto it = m_namespaceNameToStateInfo.begin(); it != m_namespaceNameToStateInfo.end(); ++it) {
auto& stateInfo = it->second;
Value jsonState = buildState(it->first, stateInfo->jsonState, allocator);
if (jsonState.ObjectEmpty()) {
ACSDK_ERROR(LX("buildContextFailed").d("reason", "buildStateFailed"));
errorBuildingContext = true;
break;
}
statesArray.PushBack(Value(jsonState, allocator).Move(), allocator);
}
stateProviderLock.unlock();
if (!errorBuildingContext) {
jsonContext.AddMember(StringRef(CONTEXT_JSON_KEY), statesArray, allocator);
Writer<StringBuffer> writer(jsonContextBuf);
if (!jsonContext.Accept(writer)) {
ACSDK_ERROR(LX("buildContextFailed").d("reason", "convertingJsonToStringFailed"));
errorBuildingContext = true;
}
}
if (errorBuildingContext) {
sendContextAndClearQueue("", ContextRequestError::BUILD_CONTEXT_ERROR);
} else {
ACSDK_DEBUG(LX("buildContextSuccessful").d("context", jsonContextBuf.GetString()));
sendContextAndClearQueue(jsonContextBuf.GetString());
}
}
} // namespace contextManager
} // namespace alexaClientSDK
| 38.373494 | 119 | 0.688854 | [
"object"
] |
1b12a3406f01e683844df871bdca658d70fcae0f | 7,171 | hpp | C++ | ThirdParty-mod/java2cpp/java/util/concurrent/FutureTask.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | 1 | 2019-04-03T01:53:28.000Z | 2019-04-03T01:53:28.000Z | ThirdParty-mod/java2cpp/java/util/concurrent/FutureTask.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | ThirdParty-mod/java2cpp/java/util/concurrent/FutureTask.hpp | kakashidinho/HQEngine | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | [
"MIT"
] | null | null | null | /*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: java.util.concurrent.FutureTask
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVA_UTIL_CONCURRENT_FUTURETASK_HPP_DECL
#define J2CPP_JAVA_UTIL_CONCURRENT_FUTURETASK_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace lang { class Runnable; } } }
namespace j2cpp { namespace java { namespace util { namespace concurrent { class Callable; } } } }
namespace j2cpp { namespace java { namespace util { namespace concurrent { class Future; } } } }
namespace j2cpp { namespace java { namespace util { namespace concurrent { class TimeUnit; } } } }
#include <java/lang/Object.hpp>
#include <java/lang/Runnable.hpp>
#include <java/util/concurrent/Callable.hpp>
#include <java/util/concurrent/Future.hpp>
#include <java/util/concurrent/TimeUnit.hpp>
namespace j2cpp {
namespace java { namespace util { namespace concurrent {
class FutureTask;
class FutureTask
: public object<FutureTask>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_METHOD(3)
J2CPP_DECLARE_METHOD(4)
J2CPP_DECLARE_METHOD(5)
J2CPP_DECLARE_METHOD(6)
J2CPP_DECLARE_METHOD(7)
J2CPP_DECLARE_METHOD(8)
J2CPP_DECLARE_METHOD(9)
J2CPP_DECLARE_METHOD(10)
J2CPP_DECLARE_METHOD(11)
explicit FutureTask(jobject jobj)
: object<FutureTask>(jobj)
{
}
operator local_ref<java::lang::Object>() const;
operator local_ref<java::util::concurrent::Future>() const;
operator local_ref<java::lang::Runnable>() const;
FutureTask(local_ref< java::util::concurrent::Callable > const&);
FutureTask(local_ref< java::lang::Runnable > const&, local_ref< java::lang::Object > const&);
jboolean isCancelled();
jboolean isDone();
jboolean cancel(jboolean);
local_ref< java::lang::Object > get();
local_ref< java::lang::Object > get(jlong, local_ref< java::util::concurrent::TimeUnit > const&);
void run();
}; //class FutureTask
} //namespace concurrent
} //namespace util
} //namespace java
} //namespace j2cpp
#endif //J2CPP_JAVA_UTIL_CONCURRENT_FUTURETASK_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVA_UTIL_CONCURRENT_FUTURETASK_HPP_IMPL
#define J2CPP_JAVA_UTIL_CONCURRENT_FUTURETASK_HPP_IMPL
namespace j2cpp {
java::util::concurrent::FutureTask::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
java::util::concurrent::FutureTask::operator local_ref<java::util::concurrent::Future>() const
{
return local_ref<java::util::concurrent::Future>(get_jobject());
}
java::util::concurrent::FutureTask::operator local_ref<java::lang::Runnable>() const
{
return local_ref<java::lang::Runnable>(get_jobject());
}
java::util::concurrent::FutureTask::FutureTask(local_ref< java::util::concurrent::Callable > const &a0)
: object<java::util::concurrent::FutureTask>(
call_new_object<
java::util::concurrent::FutureTask::J2CPP_CLASS_NAME,
java::util::concurrent::FutureTask::J2CPP_METHOD_NAME(0),
java::util::concurrent::FutureTask::J2CPP_METHOD_SIGNATURE(0)
>(a0)
)
{
}
java::util::concurrent::FutureTask::FutureTask(local_ref< java::lang::Runnable > const &a0, local_ref< java::lang::Object > const &a1)
: object<java::util::concurrent::FutureTask>(
call_new_object<
java::util::concurrent::FutureTask::J2CPP_CLASS_NAME,
java::util::concurrent::FutureTask::J2CPP_METHOD_NAME(1),
java::util::concurrent::FutureTask::J2CPP_METHOD_SIGNATURE(1)
>(a0, a1)
)
{
}
jboolean java::util::concurrent::FutureTask::isCancelled()
{
return call_method<
java::util::concurrent::FutureTask::J2CPP_CLASS_NAME,
java::util::concurrent::FutureTask::J2CPP_METHOD_NAME(2),
java::util::concurrent::FutureTask::J2CPP_METHOD_SIGNATURE(2),
jboolean
>(get_jobject());
}
jboolean java::util::concurrent::FutureTask::isDone()
{
return call_method<
java::util::concurrent::FutureTask::J2CPP_CLASS_NAME,
java::util::concurrent::FutureTask::J2CPP_METHOD_NAME(3),
java::util::concurrent::FutureTask::J2CPP_METHOD_SIGNATURE(3),
jboolean
>(get_jobject());
}
jboolean java::util::concurrent::FutureTask::cancel(jboolean a0)
{
return call_method<
java::util::concurrent::FutureTask::J2CPP_CLASS_NAME,
java::util::concurrent::FutureTask::J2CPP_METHOD_NAME(4),
java::util::concurrent::FutureTask::J2CPP_METHOD_SIGNATURE(4),
jboolean
>(get_jobject(), a0);
}
local_ref< java::lang::Object > java::util::concurrent::FutureTask::get()
{
return call_method<
java::util::concurrent::FutureTask::J2CPP_CLASS_NAME,
java::util::concurrent::FutureTask::J2CPP_METHOD_NAME(5),
java::util::concurrent::FutureTask::J2CPP_METHOD_SIGNATURE(5),
local_ref< java::lang::Object >
>(get_jobject());
}
local_ref< java::lang::Object > java::util::concurrent::FutureTask::get(jlong a0, local_ref< java::util::concurrent::TimeUnit > const &a1)
{
return call_method<
java::util::concurrent::FutureTask::J2CPP_CLASS_NAME,
java::util::concurrent::FutureTask::J2CPP_METHOD_NAME(6),
java::util::concurrent::FutureTask::J2CPP_METHOD_SIGNATURE(6),
local_ref< java::lang::Object >
>(get_jobject(), a0, a1);
}
void java::util::concurrent::FutureTask::run()
{
return call_method<
java::util::concurrent::FutureTask::J2CPP_CLASS_NAME,
java::util::concurrent::FutureTask::J2CPP_METHOD_NAME(10),
java::util::concurrent::FutureTask::J2CPP_METHOD_SIGNATURE(10),
void
>(get_jobject());
}
J2CPP_DEFINE_CLASS(java::util::concurrent::FutureTask,"java/util/concurrent/FutureTask")
J2CPP_DEFINE_METHOD(java::util::concurrent::FutureTask,0,"<init>","(Ljava/util/concurrent/Callable;)V")
J2CPP_DEFINE_METHOD(java::util::concurrent::FutureTask,1,"<init>","(Ljava/lang/Runnable;Ljava/lang/Object;)V")
J2CPP_DEFINE_METHOD(java::util::concurrent::FutureTask,2,"isCancelled","()Z")
J2CPP_DEFINE_METHOD(java::util::concurrent::FutureTask,3,"isDone","()Z")
J2CPP_DEFINE_METHOD(java::util::concurrent::FutureTask,4,"cancel","(Z)Z")
J2CPP_DEFINE_METHOD(java::util::concurrent::FutureTask,5,"get","()Ljava/lang/Object;")
J2CPP_DEFINE_METHOD(java::util::concurrent::FutureTask,6,"get","(JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object;")
J2CPP_DEFINE_METHOD(java::util::concurrent::FutureTask,7,"done","()V")
J2CPP_DEFINE_METHOD(java::util::concurrent::FutureTask,8,"set","(Ljava/lang/Object;)V")
J2CPP_DEFINE_METHOD(java::util::concurrent::FutureTask,9,"setException","(Ljava/lang/Throwable;)V")
J2CPP_DEFINE_METHOD(java::util::concurrent::FutureTask,10,"run","()V")
J2CPP_DEFINE_METHOD(java::util::concurrent::FutureTask,11,"runAndReset","()Z")
} //namespace j2cpp
#endif //J2CPP_JAVA_UTIL_CONCURRENT_FUTURETASK_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| 33.353488 | 139 | 0.715381 | [
"object"
] |
1b14f49870d1196b41258c325a98c35ccbc1eb18 | 12,144 | cpp | C++ | testsuite/adapters/schwartz_adapter_fixed_sorters.cpp | ChandanKSingh/cpp-sort | ce9b49e77eec7fe44a18da937bea0807d6c3e5f4 | [
"MIT"
] | 519 | 2015-08-01T12:25:41.000Z | 2022-03-27T09:02:37.000Z | testsuite/adapters/schwartz_adapter_fixed_sorters.cpp | ChandanKSingh/cpp-sort | ce9b49e77eec7fe44a18da937bea0807d6c3e5f4 | [
"MIT"
] | 148 | 2015-09-20T10:24:15.000Z | 2022-03-03T19:07:20.000Z | testsuite/adapters/schwartz_adapter_fixed_sorters.cpp | ChandanKSingh/cpp-sort | ce9b49e77eec7fe44a18da937bea0807d6c3e5f4 | [
"MIT"
] | 52 | 2015-11-10T14:40:13.000Z | 2022-03-20T02:35:23.000Z | /*
* Copyright (c) 2016-2021 Morwenn
* SPDX-License-Identifier: MIT
*/
#include <algorithm>
#include <array>
#include <iterator>
#include <catch2/catch.hpp>
#include <cpp-sort/adapters/schwartz_adapter.h>
#include <cpp-sort/adapters/small_array_adapter.h>
#include <cpp-sort/fixed_sorters.h>
#include <testing-tools/algorithm.h>
#include <testing-tools/random.h>
#include <testing-tools/wrapper.h>
using wrapper = generic_wrapper<double>;
TEST_CASE( "Schwartzian transform adapter with fixed-size sorters",
"[schwartz_adapter]" )
{
auto&& low_comparisons_sort = cppsort::schwartz_adapter<
cppsort::small_array_adapter<
cppsort::low_comparisons_sorter
>
>{};
auto&& low_moves_sort = cppsort::schwartz_adapter<
cppsort::small_array_adapter<
cppsort::low_moves_sorter
>
>{};
auto&& merge_exchange_sort = cppsort::schwartz_adapter<
cppsort::small_array_adapter<
cppsort::merge_exchange_network_sorter
>
>{};
auto&& odd_even_merge_sort = cppsort::schwartz_adapter<
cppsort::small_array_adapter<
cppsort::odd_even_merge_network_sorter
>
>{};
auto&& sorting_network_sort = cppsort::schwartz_adapter<
cppsort::small_array_adapter<
cppsort::sorting_network_sorter
>
>{};
SECTION( "size 0" )
{
std::array<wrapper, 0> collection;
low_comparisons_sort(collection, &wrapper::value);
low_moves_sort(collection, &wrapper::value);
merge_exchange_sort(collection, &wrapper::value);
odd_even_merge_sort(collection, &wrapper::value);
sorting_network_sort(collection, &wrapper::value);
}
SECTION( "size 1" )
{
std::array<wrapper, 1> collection;
low_comparisons_sort(collection, &wrapper::value);
low_moves_sort(collection, &wrapper::value);
merge_exchange_sort(collection, &wrapper::value);
odd_even_merge_sort(collection, &wrapper::value);
sorting_network_sort(collection, &wrapper::value);
}
SECTION( "size 2" )
{
std::array<wrapper, 2> collection;
helpers::iota(std::begin(collection), std::end(collection), -10.0, &wrapper::value);
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
low_comparisons_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
low_moves_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
merge_exchange_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
odd_even_merge_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
sorting_network_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
}
SECTION( "size 3" )
{
std::array<wrapper, 3> collection;
helpers::iota(std::begin(collection), std::end(collection), -10.0, &wrapper::value);
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
low_comparisons_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
low_moves_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
merge_exchange_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
sorting_network_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
}
SECTION( "size 4" )
{
std::array<wrapper, 4> collection;
helpers::iota(std::begin(collection), std::end(collection), -10.0, &wrapper::value);
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
low_comparisons_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
low_moves_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
merge_exchange_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
odd_even_merge_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
sorting_network_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
}
SECTION( "size 5" )
{
std::array<wrapper, 5> collection;
helpers::iota(std::begin(collection), std::end(collection), -10.0, &wrapper::value);
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
low_comparisons_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
low_moves_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
merge_exchange_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
sorting_network_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
}
SECTION( "size 6" )
{
std::array<wrapper, 6> collection;
helpers::iota(std::begin(collection), std::end(collection), -10.0, &wrapper::value);
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
low_comparisons_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
low_moves_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
merge_exchange_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
std::shuffle(std::begin(collection), std::end(collection), hasard::engine());
sorting_network_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(std::begin(collection), std::end(collection),
std::less<>{}, &wrapper::value) );
}
SECTION( "size 31" )
{
std::array<wrapper, 31> collection;
helpers::iota(collection.begin(), collection.end(), -10.0, &wrapper::value);
std::shuffle(collection.begin(), collection.end(), hasard::engine());
low_moves_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(collection.begin(), collection.end(),
std::less<>{}, &wrapper::value) );
std::shuffle(collection.begin(), collection.end(), hasard::engine());
merge_exchange_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(collection.begin(), collection.end(),
std::less<>{}, &wrapper::value) );
std::shuffle(collection.begin(), collection.end(), hasard::engine());
sorting_network_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(collection.begin(), collection.end(),
std::less<>{}, &wrapper::value) );
}
SECTION( "size 32" )
{
std::array<wrapper, 32> collection;
helpers::iota(collection.begin(), collection.end(), -10.0, &wrapper::value);
std::shuffle(collection.begin(), collection.end(), hasard::engine());
low_moves_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(collection.begin(), collection.end(),
std::less<>{}, &wrapper::value) );
std::shuffle(collection.begin(), collection.end(), hasard::engine());
merge_exchange_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(collection.begin(), collection.end(),
std::less<>{}, &wrapper::value) );
std::shuffle(collection.begin(), collection.end(), hasard::engine());
odd_even_merge_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(collection.begin(), collection.end(),
std::less<>{}, &wrapper::value) );
std::shuffle(collection.begin(), collection.end(), hasard::engine());
sorting_network_sort(collection, &wrapper::value);
CHECK( helpers::is_sorted(collection.begin(), collection.end(),
std::less<>{}, &wrapper::value) );
}
}
TEST_CASE( "stability of Schwartzian transform adapter with fixed-size sorters",
"[schwartz_adapter][is_stable]" )
{
using namespace cppsort;
using sorter = schwartz_adapter<
small_array_adapter<
low_moves_sorter
>
>;
SECTION( "is_always_stable" )
{
CHECK( not is_always_stable<small_array_adapter<low_moves_sorter>>::value );
CHECK( not is_always_stable<sorter>::value );
}
}
| 44.483516 | 92 | 0.595026 | [
"transform"
] |
1b1eba3ab705afebbae4d7a3a44d2da4c9bd8aea | 6,596 | cpp | C++ | es-core/src/components/NinePatchComponent.cpp | PascalLeroi/emulstation | c874c506d98252b6564fd42b22d62865d6f4a676 | [
"Apache-2.0",
"MIT"
] | 1,550 | 2015-01-01T09:04:26.000Z | 2022-03-31T16:38:15.000Z | es-core/src/components/NinePatchComponent.cpp | PascalLeroi/emulstation | c874c506d98252b6564fd42b22d62865d6f4a676 | [
"Apache-2.0",
"MIT"
] | 567 | 2015-01-01T05:20:50.000Z | 2022-03-27T19:22:07.000Z | es-core/src/components/NinePatchComponent.cpp | PascalLeroi/emulstation | c874c506d98252b6564fd42b22d62865d6f4a676 | [
"Apache-2.0",
"MIT"
] | 637 | 2015-01-01T15:53:55.000Z | 2022-03-30T06:38:18.000Z | #include "components/NinePatchComponent.h"
#include "Window.h"
#include "Log.h"
#include "Renderer.h"
#include "ThemeData.h"
#include "Util.h"
NinePatchComponent::NinePatchComponent(Window* window, const std::string& path, unsigned int edgeColor, unsigned int centerColor) : GuiComponent(window),
mEdgeColor(edgeColor), mCenterColor(centerColor),
mPath(path),
mVertices(NULL), mColors(NULL)
{
if(!mPath.empty())
buildVertices();
}
NinePatchComponent::~NinePatchComponent()
{
if (mVertices != NULL)
delete[] mVertices;
if (mColors != NULL)
delete[] mColors;
}
void NinePatchComponent::updateColors()
{
Renderer::buildGLColorArray(mColors, mEdgeColor, 6 * 9);
Renderer::buildGLColorArray(&mColors[4 * 6 * 4], mCenterColor, 6);
}
void NinePatchComponent::buildVertices()
{
if(mVertices != NULL)
delete[] mVertices;
if(mColors != NULL)
delete[] mColors;
mTexture = TextureResource::get(mPath);
if(mTexture->getSize() == Eigen::Vector2i::Zero())
{
mVertices = NULL;
mColors = NULL;
LOG(LogWarning) << "NinePatchComponent missing texture!";
return;
}
mVertices = new Vertex[6 * 9];
mColors = new GLubyte[6 * 9 * 4];
updateColors();
const Eigen::Vector2f ts = mTexture->getSize().cast<float>();
//coordinates on the image in pixels, top left origin
const Eigen::Vector2f pieceCoords[9] = {
Eigen::Vector2f(0, 0),
Eigen::Vector2f(16, 0),
Eigen::Vector2f(32, 0),
Eigen::Vector2f(0, 16),
Eigen::Vector2f(16, 16),
Eigen::Vector2f(32, 16),
Eigen::Vector2f(0, 32),
Eigen::Vector2f(16, 32),
Eigen::Vector2f(32, 32),
};
const Eigen::Vector2f pieceSizes = getCornerSize();
//corners never stretch, so we calculate a width and height for slices 1, 3, 5, and 7
float borderWidth = mSize.x() - (pieceSizes.x() * 2); //should be pieceSizes[0] and pieceSizes[2]
//if(borderWidth < pieceSizes.x())
// borderWidth = pieceSizes.x();
float borderHeight = mSize.y() - (pieceSizes.y() * 2); //should be pieceSizes[0] and pieceSizes[6]
//if(borderHeight < pieceSizes.y())
// borderHeight = pieceSizes.y();
mVertices[0 * 6].pos = pieceCoords[0]; //top left
mVertices[1 * 6].pos = pieceCoords[1]; //top middle
mVertices[2 * 6].pos = pieceCoords[1] + Eigen::Vector2f(borderWidth, 0); //top right
mVertices[3 * 6].pos = mVertices[0 * 6].pos + Eigen::Vector2f(0, pieceSizes.y()); //mid left
mVertices[4 * 6].pos = mVertices[3 * 6].pos + Eigen::Vector2f(pieceSizes.x(), 0); //mid middle
mVertices[5 * 6].pos = mVertices[4 * 6].pos + Eigen::Vector2f(borderWidth, 0); //mid right
mVertices[6 * 6].pos = mVertices[3 * 6].pos + Eigen::Vector2f(0, borderHeight); //bot left
mVertices[7 * 6].pos = mVertices[6 * 6].pos + Eigen::Vector2f(pieceSizes.x(), 0); //bot middle
mVertices[8 * 6].pos = mVertices[7 * 6].pos + Eigen::Vector2f(borderWidth, 0); //bot right
int v = 0;
for(int slice = 0; slice < 9; slice++)
{
Eigen::Vector2f size;
//corners
if(slice == 0 || slice == 2 || slice == 6 || slice == 8)
size = pieceSizes;
//vertical borders
if(slice == 1 || slice == 7)
size << borderWidth, pieceSizes.y();
//horizontal borders
if(slice == 3 || slice == 5)
size << pieceSizes.x(), borderHeight;
//center
if(slice == 4)
size << borderWidth, borderHeight;
//no resizing will be necessary
//mVertices[v + 0] is already correct
mVertices[v + 1].pos = mVertices[v + 0].pos + size;
mVertices[v + 2].pos << mVertices[v + 0].pos.x(), mVertices[v + 1].pos.y();
mVertices[v + 3].pos << mVertices[v + 1].pos.x(), mVertices[v + 0].pos.y();
mVertices[v + 4].pos = mVertices[v + 1].pos;
mVertices[v + 5].pos = mVertices[v + 0].pos;
//texture coordinates
//the y = (1 - y) is to deal with texture coordinates having a bottom left corner origin vs. verticies having a top left origin
mVertices[v + 0].tex << pieceCoords[slice].x() / ts.x(), 1 - (pieceCoords[slice].y() / ts.y());
mVertices[v + 1].tex << (pieceCoords[slice].x() + pieceSizes.x()) / ts.x(), 1 - ((pieceCoords[slice].y() + pieceSizes.y()) / ts.y());
mVertices[v + 2].tex << mVertices[v + 0].tex.x(), mVertices[v + 1].tex.y();
mVertices[v + 3].tex << mVertices[v + 1].tex.x(), mVertices[v + 0].tex.y();
mVertices[v + 4].tex = mVertices[v + 1].tex;
mVertices[v + 5].tex = mVertices[v + 0].tex;
v += 6;
}
// round vertices
for(int i = 0; i < 6*9; i++)
{
mVertices[i].pos = roundVector(mVertices[i].pos);
}
}
void NinePatchComponent::render(const Eigen::Affine3f& parentTrans)
{
Eigen::Affine3f trans = roundMatrix(parentTrans * getTransform());
if(mTexture && mVertices != NULL)
{
Renderer::setMatrix(trans);
mTexture->bind();
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(2, GL_FLOAT, sizeof(Vertex), &mVertices[0].pos);
glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), &mVertices[0].tex);
glColorPointer(4, GL_UNSIGNED_BYTE, 0, mColors);
glDrawArrays(GL_TRIANGLES, 0, 6 * 9);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
}
renderChildren(trans);
}
void NinePatchComponent::onSizeChanged()
{
buildVertices();
}
Eigen::Vector2f NinePatchComponent::getCornerSize() const
{
return Eigen::Vector2f(16, 16);
}
void NinePatchComponent::fitTo(Eigen::Vector2f size, Eigen::Vector3f position, Eigen::Vector2f padding)
{
size += padding;
position[0] -= padding.x() / 2;
position[1] -= padding.y() / 2;
setSize(size + Eigen::Vector2f(getCornerSize().x() * 2, getCornerSize().y() * 2));
setPosition(-getCornerSize().x() + position.x(), -getCornerSize().y() + position.y());
}
void NinePatchComponent::setImagePath(const std::string& path)
{
mPath = path;
buildVertices();
}
void NinePatchComponent::setEdgeColor(unsigned int edgeColor)
{
mEdgeColor = edgeColor;
updateColors();
}
void NinePatchComponent::setCenterColor(unsigned int centerColor)
{
mCenterColor = centerColor;
updateColors();
}
void NinePatchComponent::applyTheme(const std::shared_ptr<ThemeData>& theme, const std::string& view, const std::string& element, unsigned int properties)
{
GuiComponent::applyTheme(theme, view, element, properties);
using namespace ThemeFlags;
const ThemeData::ThemeElement* elem = theme->getElement(view, element, "ninepatch");
if(!elem)
return;
if(properties & PATH && elem->has("path"))
setImagePath(elem->get<std::string>("path"));
}
| 28.929825 | 154 | 0.680564 | [
"render"
] |
1b24c34f67fcece107ab8af01162937292046552 | 902 | cpp | C++ | Dataset/Leetcode/valid/70/593.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/valid/70/593.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/valid/70/593.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<vector<int>> arr;
vector<vector<int>> juzhen_mul(vector<vector<int>> a,vector<vector<int>>b){
int a1,a2,a3,a4;
a1=a[0][0]*b[0][0]+a[0][1]*b[1][0];
a2=a[0][0]*b[0][1]+a[0][1]*b[1][1];
a3=a[1][0]*b[0][0]+a[1][1]*b[1][0];
a4=a[1][0]*b[0][1]+a[1][1]*b[1][1];
return{{a1,a2},{a3,a4}};
}
vector<vector<int>> QuickPow(int n){
if(n==1) return arr;
if(n%2==0){
vector<vector<int>> ans=QuickPow(n/2);
return juzhen_mul(ans,ans);
}
else{
vector<vector<int>> ans=QuickPow(n/2);
return juzhen_mul(arr,juzhen_mul(ans,ans));
}
}
int XXX(int n) {
if(n<2) return 1;
arr.push_back({1,1});
arr.push_back({1,0});
vector<vector<int>> tmp=QuickPow(n-1);
return tmp[0][0]+tmp[0][1];
}
};
| 28.1875 | 79 | 0.476718 | [
"vector"
] |
1b2a52ea2c57f5fc7bb17f50d735d77d2d6e2211 | 26,636 | cpp | C++ | gaap/src/v20180529/model/ProxyInfo.cpp | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | null | null | null | gaap/src/v20180529/model/ProxyInfo.cpp | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | null | null | null | gaap/src/v20180529/model/ProxyInfo.cpp | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/gaap/v20180529/model/ProxyInfo.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Gaap::V20180529::Model;
using namespace rapidjson;
using namespace std;
ProxyInfo::ProxyInfo() :
m_instanceIdHasBeenSet(false),
m_createTimeHasBeenSet(false),
m_projectIdHasBeenSet(false),
m_proxyNameHasBeenSet(false),
m_accessRegionHasBeenSet(false),
m_realServerRegionHasBeenSet(false),
m_bandwidthHasBeenSet(false),
m_concurrentHasBeenSet(false),
m_statusHasBeenSet(false),
m_domainHasBeenSet(false),
m_iPHasBeenSet(false),
m_versionHasBeenSet(false),
m_proxyIdHasBeenSet(false),
m_scalarableHasBeenSet(false),
m_supportProtocolsHasBeenSet(false),
m_groupIdHasBeenSet(false),
m_policyIdHasBeenSet(false),
m_accessRegionInfoHasBeenSet(false),
m_realServerRegionInfoHasBeenSet(false),
m_forwardIPHasBeenSet(false),
m_tagSetHasBeenSet(false),
m_supportSecurityHasBeenSet(false),
m_billingTypeHasBeenSet(false),
m_relatedGlobalDomainsHasBeenSet(false),
m_modifyConfigTimeHasBeenSet(false)
{
}
CoreInternalOutcome ProxyInfo::Deserialize(const Value &value)
{
string requestId = "";
if (value.HasMember("InstanceId") && !value["InstanceId"].IsNull())
{
if (!value["InstanceId"].IsString())
{
return CoreInternalOutcome(Error("response `ProxyInfo.InstanceId` IsString=false incorrectly").SetRequestId(requestId));
}
m_instanceId = string(value["InstanceId"].GetString());
m_instanceIdHasBeenSet = true;
}
if (value.HasMember("CreateTime") && !value["CreateTime"].IsNull())
{
if (!value["CreateTime"].IsUint64())
{
return CoreInternalOutcome(Error("response `ProxyInfo.CreateTime` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_createTime = value["CreateTime"].GetUint64();
m_createTimeHasBeenSet = true;
}
if (value.HasMember("ProjectId") && !value["ProjectId"].IsNull())
{
if (!value["ProjectId"].IsInt64())
{
return CoreInternalOutcome(Error("response `ProxyInfo.ProjectId` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_projectId = value["ProjectId"].GetInt64();
m_projectIdHasBeenSet = true;
}
if (value.HasMember("ProxyName") && !value["ProxyName"].IsNull())
{
if (!value["ProxyName"].IsString())
{
return CoreInternalOutcome(Error("response `ProxyInfo.ProxyName` IsString=false incorrectly").SetRequestId(requestId));
}
m_proxyName = string(value["ProxyName"].GetString());
m_proxyNameHasBeenSet = true;
}
if (value.HasMember("AccessRegion") && !value["AccessRegion"].IsNull())
{
if (!value["AccessRegion"].IsString())
{
return CoreInternalOutcome(Error("response `ProxyInfo.AccessRegion` IsString=false incorrectly").SetRequestId(requestId));
}
m_accessRegion = string(value["AccessRegion"].GetString());
m_accessRegionHasBeenSet = true;
}
if (value.HasMember("RealServerRegion") && !value["RealServerRegion"].IsNull())
{
if (!value["RealServerRegion"].IsString())
{
return CoreInternalOutcome(Error("response `ProxyInfo.RealServerRegion` IsString=false incorrectly").SetRequestId(requestId));
}
m_realServerRegion = string(value["RealServerRegion"].GetString());
m_realServerRegionHasBeenSet = true;
}
if (value.HasMember("Bandwidth") && !value["Bandwidth"].IsNull())
{
if (!value["Bandwidth"].IsInt64())
{
return CoreInternalOutcome(Error("response `ProxyInfo.Bandwidth` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_bandwidth = value["Bandwidth"].GetInt64();
m_bandwidthHasBeenSet = true;
}
if (value.HasMember("Concurrent") && !value["Concurrent"].IsNull())
{
if (!value["Concurrent"].IsInt64())
{
return CoreInternalOutcome(Error("response `ProxyInfo.Concurrent` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_concurrent = value["Concurrent"].GetInt64();
m_concurrentHasBeenSet = true;
}
if (value.HasMember("Status") && !value["Status"].IsNull())
{
if (!value["Status"].IsString())
{
return CoreInternalOutcome(Error("response `ProxyInfo.Status` IsString=false incorrectly").SetRequestId(requestId));
}
m_status = string(value["Status"].GetString());
m_statusHasBeenSet = true;
}
if (value.HasMember("Domain") && !value["Domain"].IsNull())
{
if (!value["Domain"].IsString())
{
return CoreInternalOutcome(Error("response `ProxyInfo.Domain` IsString=false incorrectly").SetRequestId(requestId));
}
m_domain = string(value["Domain"].GetString());
m_domainHasBeenSet = true;
}
if (value.HasMember("IP") && !value["IP"].IsNull())
{
if (!value["IP"].IsString())
{
return CoreInternalOutcome(Error("response `ProxyInfo.IP` IsString=false incorrectly").SetRequestId(requestId));
}
m_iP = string(value["IP"].GetString());
m_iPHasBeenSet = true;
}
if (value.HasMember("Version") && !value["Version"].IsNull())
{
if (!value["Version"].IsString())
{
return CoreInternalOutcome(Error("response `ProxyInfo.Version` IsString=false incorrectly").SetRequestId(requestId));
}
m_version = string(value["Version"].GetString());
m_versionHasBeenSet = true;
}
if (value.HasMember("ProxyId") && !value["ProxyId"].IsNull())
{
if (!value["ProxyId"].IsString())
{
return CoreInternalOutcome(Error("response `ProxyInfo.ProxyId` IsString=false incorrectly").SetRequestId(requestId));
}
m_proxyId = string(value["ProxyId"].GetString());
m_proxyIdHasBeenSet = true;
}
if (value.HasMember("Scalarable") && !value["Scalarable"].IsNull())
{
if (!value["Scalarable"].IsInt64())
{
return CoreInternalOutcome(Error("response `ProxyInfo.Scalarable` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_scalarable = value["Scalarable"].GetInt64();
m_scalarableHasBeenSet = true;
}
if (value.HasMember("SupportProtocols") && !value["SupportProtocols"].IsNull())
{
if (!value["SupportProtocols"].IsArray())
return CoreInternalOutcome(Error("response `ProxyInfo.SupportProtocols` is not array type"));
const Value &tmpValue = value["SupportProtocols"];
for (Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
m_supportProtocols.push_back((*itr).GetString());
}
m_supportProtocolsHasBeenSet = true;
}
if (value.HasMember("GroupId") && !value["GroupId"].IsNull())
{
if (!value["GroupId"].IsString())
{
return CoreInternalOutcome(Error("response `ProxyInfo.GroupId` IsString=false incorrectly").SetRequestId(requestId));
}
m_groupId = string(value["GroupId"].GetString());
m_groupIdHasBeenSet = true;
}
if (value.HasMember("PolicyId") && !value["PolicyId"].IsNull())
{
if (!value["PolicyId"].IsString())
{
return CoreInternalOutcome(Error("response `ProxyInfo.PolicyId` IsString=false incorrectly").SetRequestId(requestId));
}
m_policyId = string(value["PolicyId"].GetString());
m_policyIdHasBeenSet = true;
}
if (value.HasMember("AccessRegionInfo") && !value["AccessRegionInfo"].IsNull())
{
if (!value["AccessRegionInfo"].IsObject())
{
return CoreInternalOutcome(Error("response `ProxyInfo.AccessRegionInfo` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_accessRegionInfo.Deserialize(value["AccessRegionInfo"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_accessRegionInfoHasBeenSet = true;
}
if (value.HasMember("RealServerRegionInfo") && !value["RealServerRegionInfo"].IsNull())
{
if (!value["RealServerRegionInfo"].IsObject())
{
return CoreInternalOutcome(Error("response `ProxyInfo.RealServerRegionInfo` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_realServerRegionInfo.Deserialize(value["RealServerRegionInfo"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_realServerRegionInfoHasBeenSet = true;
}
if (value.HasMember("ForwardIP") && !value["ForwardIP"].IsNull())
{
if (!value["ForwardIP"].IsString())
{
return CoreInternalOutcome(Error("response `ProxyInfo.ForwardIP` IsString=false incorrectly").SetRequestId(requestId));
}
m_forwardIP = string(value["ForwardIP"].GetString());
m_forwardIPHasBeenSet = true;
}
if (value.HasMember("TagSet") && !value["TagSet"].IsNull())
{
if (!value["TagSet"].IsArray())
return CoreInternalOutcome(Error("response `ProxyInfo.TagSet` is not array type"));
const Value &tmpValue = value["TagSet"];
for (Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
TagPair item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_tagSet.push_back(item);
}
m_tagSetHasBeenSet = true;
}
if (value.HasMember("SupportSecurity") && !value["SupportSecurity"].IsNull())
{
if (!value["SupportSecurity"].IsInt64())
{
return CoreInternalOutcome(Error("response `ProxyInfo.SupportSecurity` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_supportSecurity = value["SupportSecurity"].GetInt64();
m_supportSecurityHasBeenSet = true;
}
if (value.HasMember("BillingType") && !value["BillingType"].IsNull())
{
if (!value["BillingType"].IsInt64())
{
return CoreInternalOutcome(Error("response `ProxyInfo.BillingType` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_billingType = value["BillingType"].GetInt64();
m_billingTypeHasBeenSet = true;
}
if (value.HasMember("RelatedGlobalDomains") && !value["RelatedGlobalDomains"].IsNull())
{
if (!value["RelatedGlobalDomains"].IsArray())
return CoreInternalOutcome(Error("response `ProxyInfo.RelatedGlobalDomains` is not array type"));
const Value &tmpValue = value["RelatedGlobalDomains"];
for (Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
m_relatedGlobalDomains.push_back((*itr).GetString());
}
m_relatedGlobalDomainsHasBeenSet = true;
}
if (value.HasMember("ModifyConfigTime") && !value["ModifyConfigTime"].IsNull())
{
if (!value["ModifyConfigTime"].IsUint64())
{
return CoreInternalOutcome(Error("response `ProxyInfo.ModifyConfigTime` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_modifyConfigTime = value["ModifyConfigTime"].GetUint64();
m_modifyConfigTimeHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void ProxyInfo::ToJsonObject(Value &value, Document::AllocatorType& allocator) const
{
if (m_instanceIdHasBeenSet)
{
Value iKey(kStringType);
string key = "InstanceId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_instanceId.c_str(), allocator).Move(), allocator);
}
if (m_createTimeHasBeenSet)
{
Value iKey(kStringType);
string key = "CreateTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_createTime, allocator);
}
if (m_projectIdHasBeenSet)
{
Value iKey(kStringType);
string key = "ProjectId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_projectId, allocator);
}
if (m_proxyNameHasBeenSet)
{
Value iKey(kStringType);
string key = "ProxyName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_proxyName.c_str(), allocator).Move(), allocator);
}
if (m_accessRegionHasBeenSet)
{
Value iKey(kStringType);
string key = "AccessRegion";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_accessRegion.c_str(), allocator).Move(), allocator);
}
if (m_realServerRegionHasBeenSet)
{
Value iKey(kStringType);
string key = "RealServerRegion";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_realServerRegion.c_str(), allocator).Move(), allocator);
}
if (m_bandwidthHasBeenSet)
{
Value iKey(kStringType);
string key = "Bandwidth";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_bandwidth, allocator);
}
if (m_concurrentHasBeenSet)
{
Value iKey(kStringType);
string key = "Concurrent";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_concurrent, allocator);
}
if (m_statusHasBeenSet)
{
Value iKey(kStringType);
string key = "Status";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_status.c_str(), allocator).Move(), allocator);
}
if (m_domainHasBeenSet)
{
Value iKey(kStringType);
string key = "Domain";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_domain.c_str(), allocator).Move(), allocator);
}
if (m_iPHasBeenSet)
{
Value iKey(kStringType);
string key = "IP";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_iP.c_str(), allocator).Move(), allocator);
}
if (m_versionHasBeenSet)
{
Value iKey(kStringType);
string key = "Version";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_version.c_str(), allocator).Move(), allocator);
}
if (m_proxyIdHasBeenSet)
{
Value iKey(kStringType);
string key = "ProxyId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_proxyId.c_str(), allocator).Move(), allocator);
}
if (m_scalarableHasBeenSet)
{
Value iKey(kStringType);
string key = "Scalarable";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_scalarable, allocator);
}
if (m_supportProtocolsHasBeenSet)
{
Value iKey(kStringType);
string key = "SupportProtocols";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(kArrayType).Move(), allocator);
for (auto itr = m_supportProtocols.begin(); itr != m_supportProtocols.end(); ++itr)
{
value[key.c_str()].PushBack(Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_groupIdHasBeenSet)
{
Value iKey(kStringType);
string key = "GroupId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_groupId.c_str(), allocator).Move(), allocator);
}
if (m_policyIdHasBeenSet)
{
Value iKey(kStringType);
string key = "PolicyId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_policyId.c_str(), allocator).Move(), allocator);
}
if (m_accessRegionInfoHasBeenSet)
{
Value iKey(kStringType);
string key = "AccessRegionInfo";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(kObjectType).Move(), allocator);
m_accessRegionInfo.ToJsonObject(value[key.c_str()], allocator);
}
if (m_realServerRegionInfoHasBeenSet)
{
Value iKey(kStringType);
string key = "RealServerRegionInfo";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(kObjectType).Move(), allocator);
m_realServerRegionInfo.ToJsonObject(value[key.c_str()], allocator);
}
if (m_forwardIPHasBeenSet)
{
Value iKey(kStringType);
string key = "ForwardIP";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_forwardIP.c_str(), allocator).Move(), allocator);
}
if (m_tagSetHasBeenSet)
{
Value iKey(kStringType);
string key = "TagSet";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_tagSet.begin(); itr != m_tagSet.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(Value(kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
if (m_supportSecurityHasBeenSet)
{
Value iKey(kStringType);
string key = "SupportSecurity";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_supportSecurity, allocator);
}
if (m_billingTypeHasBeenSet)
{
Value iKey(kStringType);
string key = "BillingType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_billingType, allocator);
}
if (m_relatedGlobalDomainsHasBeenSet)
{
Value iKey(kStringType);
string key = "RelatedGlobalDomains";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(kArrayType).Move(), allocator);
for (auto itr = m_relatedGlobalDomains.begin(); itr != m_relatedGlobalDomains.end(); ++itr)
{
value[key.c_str()].PushBack(Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_modifyConfigTimeHasBeenSet)
{
Value iKey(kStringType);
string key = "ModifyConfigTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_modifyConfigTime, allocator);
}
}
string ProxyInfo::GetInstanceId() const
{
return m_instanceId;
}
void ProxyInfo::SetInstanceId(const string& _instanceId)
{
m_instanceId = _instanceId;
m_instanceIdHasBeenSet = true;
}
bool ProxyInfo::InstanceIdHasBeenSet() const
{
return m_instanceIdHasBeenSet;
}
uint64_t ProxyInfo::GetCreateTime() const
{
return m_createTime;
}
void ProxyInfo::SetCreateTime(const uint64_t& _createTime)
{
m_createTime = _createTime;
m_createTimeHasBeenSet = true;
}
bool ProxyInfo::CreateTimeHasBeenSet() const
{
return m_createTimeHasBeenSet;
}
int64_t ProxyInfo::GetProjectId() const
{
return m_projectId;
}
void ProxyInfo::SetProjectId(const int64_t& _projectId)
{
m_projectId = _projectId;
m_projectIdHasBeenSet = true;
}
bool ProxyInfo::ProjectIdHasBeenSet() const
{
return m_projectIdHasBeenSet;
}
string ProxyInfo::GetProxyName() const
{
return m_proxyName;
}
void ProxyInfo::SetProxyName(const string& _proxyName)
{
m_proxyName = _proxyName;
m_proxyNameHasBeenSet = true;
}
bool ProxyInfo::ProxyNameHasBeenSet() const
{
return m_proxyNameHasBeenSet;
}
string ProxyInfo::GetAccessRegion() const
{
return m_accessRegion;
}
void ProxyInfo::SetAccessRegion(const string& _accessRegion)
{
m_accessRegion = _accessRegion;
m_accessRegionHasBeenSet = true;
}
bool ProxyInfo::AccessRegionHasBeenSet() const
{
return m_accessRegionHasBeenSet;
}
string ProxyInfo::GetRealServerRegion() const
{
return m_realServerRegion;
}
void ProxyInfo::SetRealServerRegion(const string& _realServerRegion)
{
m_realServerRegion = _realServerRegion;
m_realServerRegionHasBeenSet = true;
}
bool ProxyInfo::RealServerRegionHasBeenSet() const
{
return m_realServerRegionHasBeenSet;
}
int64_t ProxyInfo::GetBandwidth() const
{
return m_bandwidth;
}
void ProxyInfo::SetBandwidth(const int64_t& _bandwidth)
{
m_bandwidth = _bandwidth;
m_bandwidthHasBeenSet = true;
}
bool ProxyInfo::BandwidthHasBeenSet() const
{
return m_bandwidthHasBeenSet;
}
int64_t ProxyInfo::GetConcurrent() const
{
return m_concurrent;
}
void ProxyInfo::SetConcurrent(const int64_t& _concurrent)
{
m_concurrent = _concurrent;
m_concurrentHasBeenSet = true;
}
bool ProxyInfo::ConcurrentHasBeenSet() const
{
return m_concurrentHasBeenSet;
}
string ProxyInfo::GetStatus() const
{
return m_status;
}
void ProxyInfo::SetStatus(const string& _status)
{
m_status = _status;
m_statusHasBeenSet = true;
}
bool ProxyInfo::StatusHasBeenSet() const
{
return m_statusHasBeenSet;
}
string ProxyInfo::GetDomain() const
{
return m_domain;
}
void ProxyInfo::SetDomain(const string& _domain)
{
m_domain = _domain;
m_domainHasBeenSet = true;
}
bool ProxyInfo::DomainHasBeenSet() const
{
return m_domainHasBeenSet;
}
string ProxyInfo::GetIP() const
{
return m_iP;
}
void ProxyInfo::SetIP(const string& _iP)
{
m_iP = _iP;
m_iPHasBeenSet = true;
}
bool ProxyInfo::IPHasBeenSet() const
{
return m_iPHasBeenSet;
}
string ProxyInfo::GetVersion() const
{
return m_version;
}
void ProxyInfo::SetVersion(const string& _version)
{
m_version = _version;
m_versionHasBeenSet = true;
}
bool ProxyInfo::VersionHasBeenSet() const
{
return m_versionHasBeenSet;
}
string ProxyInfo::GetProxyId() const
{
return m_proxyId;
}
void ProxyInfo::SetProxyId(const string& _proxyId)
{
m_proxyId = _proxyId;
m_proxyIdHasBeenSet = true;
}
bool ProxyInfo::ProxyIdHasBeenSet() const
{
return m_proxyIdHasBeenSet;
}
int64_t ProxyInfo::GetScalarable() const
{
return m_scalarable;
}
void ProxyInfo::SetScalarable(const int64_t& _scalarable)
{
m_scalarable = _scalarable;
m_scalarableHasBeenSet = true;
}
bool ProxyInfo::ScalarableHasBeenSet() const
{
return m_scalarableHasBeenSet;
}
vector<string> ProxyInfo::GetSupportProtocols() const
{
return m_supportProtocols;
}
void ProxyInfo::SetSupportProtocols(const vector<string>& _supportProtocols)
{
m_supportProtocols = _supportProtocols;
m_supportProtocolsHasBeenSet = true;
}
bool ProxyInfo::SupportProtocolsHasBeenSet() const
{
return m_supportProtocolsHasBeenSet;
}
string ProxyInfo::GetGroupId() const
{
return m_groupId;
}
void ProxyInfo::SetGroupId(const string& _groupId)
{
m_groupId = _groupId;
m_groupIdHasBeenSet = true;
}
bool ProxyInfo::GroupIdHasBeenSet() const
{
return m_groupIdHasBeenSet;
}
string ProxyInfo::GetPolicyId() const
{
return m_policyId;
}
void ProxyInfo::SetPolicyId(const string& _policyId)
{
m_policyId = _policyId;
m_policyIdHasBeenSet = true;
}
bool ProxyInfo::PolicyIdHasBeenSet() const
{
return m_policyIdHasBeenSet;
}
RegionDetail ProxyInfo::GetAccessRegionInfo() const
{
return m_accessRegionInfo;
}
void ProxyInfo::SetAccessRegionInfo(const RegionDetail& _accessRegionInfo)
{
m_accessRegionInfo = _accessRegionInfo;
m_accessRegionInfoHasBeenSet = true;
}
bool ProxyInfo::AccessRegionInfoHasBeenSet() const
{
return m_accessRegionInfoHasBeenSet;
}
RegionDetail ProxyInfo::GetRealServerRegionInfo() const
{
return m_realServerRegionInfo;
}
void ProxyInfo::SetRealServerRegionInfo(const RegionDetail& _realServerRegionInfo)
{
m_realServerRegionInfo = _realServerRegionInfo;
m_realServerRegionInfoHasBeenSet = true;
}
bool ProxyInfo::RealServerRegionInfoHasBeenSet() const
{
return m_realServerRegionInfoHasBeenSet;
}
string ProxyInfo::GetForwardIP() const
{
return m_forwardIP;
}
void ProxyInfo::SetForwardIP(const string& _forwardIP)
{
m_forwardIP = _forwardIP;
m_forwardIPHasBeenSet = true;
}
bool ProxyInfo::ForwardIPHasBeenSet() const
{
return m_forwardIPHasBeenSet;
}
vector<TagPair> ProxyInfo::GetTagSet() const
{
return m_tagSet;
}
void ProxyInfo::SetTagSet(const vector<TagPair>& _tagSet)
{
m_tagSet = _tagSet;
m_tagSetHasBeenSet = true;
}
bool ProxyInfo::TagSetHasBeenSet() const
{
return m_tagSetHasBeenSet;
}
int64_t ProxyInfo::GetSupportSecurity() const
{
return m_supportSecurity;
}
void ProxyInfo::SetSupportSecurity(const int64_t& _supportSecurity)
{
m_supportSecurity = _supportSecurity;
m_supportSecurityHasBeenSet = true;
}
bool ProxyInfo::SupportSecurityHasBeenSet() const
{
return m_supportSecurityHasBeenSet;
}
int64_t ProxyInfo::GetBillingType() const
{
return m_billingType;
}
void ProxyInfo::SetBillingType(const int64_t& _billingType)
{
m_billingType = _billingType;
m_billingTypeHasBeenSet = true;
}
bool ProxyInfo::BillingTypeHasBeenSet() const
{
return m_billingTypeHasBeenSet;
}
vector<string> ProxyInfo::GetRelatedGlobalDomains() const
{
return m_relatedGlobalDomains;
}
void ProxyInfo::SetRelatedGlobalDomains(const vector<string>& _relatedGlobalDomains)
{
m_relatedGlobalDomains = _relatedGlobalDomains;
m_relatedGlobalDomainsHasBeenSet = true;
}
bool ProxyInfo::RelatedGlobalDomainsHasBeenSet() const
{
return m_relatedGlobalDomainsHasBeenSet;
}
uint64_t ProxyInfo::GetModifyConfigTime() const
{
return m_modifyConfigTime;
}
void ProxyInfo::SetModifyConfigTime(const uint64_t& _modifyConfigTime)
{
m_modifyConfigTime = _modifyConfigTime;
m_modifyConfigTimeHasBeenSet = true;
}
bool ProxyInfo::ModifyConfigTimeHasBeenSet() const
{
return m_modifyConfigTimeHasBeenSet;
}
| 27.544984 | 138 | 0.66703 | [
"object",
"vector",
"model"
] |
1b2e49244a79b795613ae4e8eeb60f6f82b70bcd | 1,673 | hpp | C++ | core/result_collector.hpp | BowenforGit/Grasper | 268468d6eb0a56e9a4815c0c1d7660b06bf8a1f7 | [
"Apache-2.0"
] | 29 | 2019-11-18T14:25:05.000Z | 2022-02-10T07:21:48.000Z | core/result_collector.hpp | BowenforGit/Grasper | 268468d6eb0a56e9a4815c0c1d7660b06bf8a1f7 | [
"Apache-2.0"
] | 2 | 2021-03-17T03:17:38.000Z | 2021-04-11T04:06:23.000Z | core/result_collector.hpp | BowenforGit/Grasper | 268468d6eb0a56e9a4815c0c1d7660b06bf8a1f7 | [
"Apache-2.0"
] | 6 | 2019-11-21T18:04:15.000Z | 2022-03-01T02:48:50.000Z | /* Copyright 2019 Husky Data Lab, CUHK
Authors: Hongzhi Chen (hzchen@cse.cuhk.edu.hk)
*/
#ifndef RESULT_COLLECTOR_HPP_
#define RESULT_COLLECTOR_HPP_
#include <ext/hash_map>
#include <algorithm>
#include <iostream>
#include <list>
#include <vector>
#include <mutex>
#include <queue>
#include <string>
#include "base/type.hpp"
#include "base/thread_safe_queue.hpp"
using __gnu_cxx::hash_map;
using namespace std;
struct reply {
string hostname;
uint64_t qid;
vector<value_t> results;
};
class Result_Collector {
public:
void Register(uint64_t qid, string hostname) {
lock_guard<mutex> lck(m_mutex_);
reply_list_.push_front(move(hostname));
mp_[qid] = reply_list_.begin();
}
void InsertResult(uint64_t qid, vector<value_t> & data) {
m_mutex_.lock();
indexItr it = mp_.find(qid);
if (it == mp_.end()) {
cout << "ERROR: Impossible branch in Result_Collector!\n";
exit(-1);
}
itemItr re_pos = it->second;
reply re;
re.hostname = move(*re_pos);
re.results = move(data);
re.qid = qid;
reply_list_.erase(re_pos);
mp_.erase(it);
m_mutex_.unlock();
reply_queue_.Push(move(re));
}
void Pop(reply & result) {
reply_queue_.WaitAndPop(result);
}
private:
// hostname, result;
typedef string item;
typedef list<item>::iterator itemItr;
typedef hash_map<uint64_t, itemItr> index;
typedef index::iterator indexItr;
mutex m_mutex_;
list<item> reply_list_;
ThreadSafeQueue<reply> reply_queue_;
index mp_;
};
#endif /* RESULT_COLLECTOR_HPP_ */
| 21.448718 | 70 | 0.638972 | [
"vector"
] |
1b318858d8437ca6be9dd38d8a9fd92871d94cf6 | 800 | hh | C++ | src/poll.hh | thanhbinh89/uvgRTP-cross-compile | 77de0952f63f621cb44af55574f83d6da87b9780 | [
"BSD-2-Clause"
] | null | null | null | src/poll.hh | thanhbinh89/uvgRTP-cross-compile | 77de0952f63f621cb44af55574f83d6da87b9780 | [
"BSD-2-Clause"
] | null | null | null | src/poll.hh | thanhbinh89/uvgRTP-cross-compile | 77de0952f63f621cb44af55574f83d6da87b9780 | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include "uvgrtp/util.hh"
#include <vector>
namespace uvgrtp {
class socket;
namespace poll {
/* Cross-platform poll implementation for listening to a socket for a period of time
*
* This is used by RTCP to listen to socket RTCP_MIN_TIMEOUT (5s for now).
*
* "timeout" is in milliseconds
*
* If some actions happens with the socket, return status
* If the timeout is exceeded, return RTP_INTERRUPTED */
rtp_error_t poll(std::vector<uvgrtp::socket>& sockets, uint8_t *buf, size_t buf_len, int timeout, int *bytes_read);
/* TODO: */
rtp_error_t blocked_recv(uvgrtp::socket *socket, uint8_t *buf, size_t buf_len, int timeout, int *bytes_read);
}
}
namespace uvg_rtp = uvgrtp;
| 29.62963 | 123 | 0.6475 | [
"vector"
] |
1b32b14cfba10b99981eeeaf95f380e637e8e684 | 5,109 | hpp | C++ | src/treelearner/cuda/cuda_single_gpu_tree_learner.hpp | TremaMiguel/LightGBM | da9072fde2b5cd7160866e7e9e49a14e7fba8bf3 | [
"MIT"
] | 8,890 | 2016-10-12T05:25:23.000Z | 2019-05-06T17:42:23.000Z | src/treelearner/cuda/cuda_single_gpu_tree_learner.hpp | TremaMiguel/LightGBM | da9072fde2b5cd7160866e7e9e49a14e7fba8bf3 | [
"MIT"
] | 1,784 | 2016-10-16T14:18:34.000Z | 2019-05-06T12:15:22.000Z | src/treelearner/cuda/cuda_single_gpu_tree_learner.hpp | TremaMiguel/LightGBM | da9072fde2b5cd7160866e7e9e49a14e7fba8bf3 | [
"MIT"
] | 2,599 | 2016-10-11T07:13:27.000Z | 2019-05-06T12:17:38.000Z | /*!
* Copyright (c) 2021 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for
* license information.
*/
#ifndef LIGHTGBM_TREELEARNER_CUDA_CUDA_SINGLE_GPU_TREE_LEARNER_HPP_
#define LIGHTGBM_TREELEARNER_CUDA_CUDA_SINGLE_GPU_TREE_LEARNER_HPP_
#include <memory>
#include <vector>
#ifdef USE_CUDA_EXP
#include "cuda_leaf_splits.hpp"
#include "cuda_histogram_constructor.hpp"
#include "cuda_data_partition.hpp"
#include "cuda_best_split_finder.hpp"
#include "../serial_tree_learner.h"
namespace LightGBM {
#define CUDA_SINGLE_GPU_TREE_LEARNER_BLOCK_SIZE (1024)
class CUDASingleGPUTreeLearner: public SerialTreeLearner {
public:
explicit CUDASingleGPUTreeLearner(const Config* config);
~CUDASingleGPUTreeLearner();
void Init(const Dataset* train_data, bool is_constant_hessian) override;
void ResetTrainingData(const Dataset* train_data,
bool is_constant_hessian) override;
Tree* Train(const score_t* gradients, const score_t *hessians, bool is_first_tree) override;
void SetBaggingData(const Dataset* subset, const data_size_t* used_indices, data_size_t num_data) override;
void AddPredictionToScore(const Tree* tree, double* out_score) const override;
void RenewTreeOutput(Tree* tree, const ObjectiveFunction* obj, std::function<double(const label_t*, int)> residual_getter,
data_size_t total_num_data, const data_size_t* bag_indices, data_size_t bag_cnt) const override;
void ResetConfig(const Config* config) override;
Tree* FitByExistingTree(const Tree* old_tree, const score_t* gradients, const score_t* hessians) const override;
Tree* FitByExistingTree(const Tree* old_tree, const std::vector<int>& leaf_pred,
const score_t* gradients, const score_t* hessians) const override;
protected:
void BeforeTrain() override;
void ReduceLeafStat(CUDATree* old_tree, const score_t* gradients, const score_t* hessians, const data_size_t* num_data_in_leaf) const;
void LaunchReduceLeafStatKernel(const score_t* gradients, const score_t* hessians, const data_size_t* num_data_in_leaf,
const int* leaf_parent, const int* left_child, const int* right_child,
const int num_leaves, const data_size_t num_data, double* cuda_leaf_value, const double shrinkage_rate) const;
void ConstructBitsetForCategoricalSplit(const CUDASplitInfo* best_split_info);
void LaunchConstructBitsetForCategoricalSplitKernel(const CUDASplitInfo* best_split_info);
void AllocateBitset();
#ifdef DEUBG
void CheckSplitValid(
const int left_leaf, const int right_leaf,
const double sum_left_gradients, const double sum_right_gradients);
#endif // DEBUG
// GPU device ID
int gpu_device_id_;
// number of threads on CPU
int num_threads_;
// CUDA components for tree training
// leaf splits information for smaller and larger leaves
std::unique_ptr<CUDALeafSplits> cuda_smaller_leaf_splits_;
std::unique_ptr<CUDALeafSplits> cuda_larger_leaf_splits_;
// data partition that partitions data indices into different leaves
std::unique_ptr<CUDADataPartition> cuda_data_partition_;
// for histogram construction
std::unique_ptr<CUDAHistogramConstructor> cuda_histogram_constructor_;
// for best split information finding, given the histograms
std::unique_ptr<CUDABestSplitFinder> cuda_best_split_finder_;
std::vector<int> leaf_best_split_feature_;
std::vector<uint32_t> leaf_best_split_threshold_;
std::vector<uint8_t> leaf_best_split_default_left_;
std::vector<data_size_t> leaf_num_data_;
std::vector<data_size_t> leaf_data_start_;
std::vector<double> leaf_sum_hessians_;
int smaller_leaf_index_;
int larger_leaf_index_;
int best_leaf_index_;
int num_cat_threshold_;
bool has_categorical_feature_;
std::vector<int> categorical_bin_to_value_;
std::vector<int> categorical_bin_offsets_;
mutable double* cuda_leaf_gradient_stat_buffer_;
mutable double* cuda_leaf_hessian_stat_buffer_;
mutable data_size_t leaf_stat_buffer_size_;
mutable data_size_t refit_num_data_;
uint32_t* cuda_bitset_;
size_t cuda_bitset_len_;
uint32_t* cuda_bitset_inner_;
size_t cuda_bitset_inner_len_;
size_t* cuda_block_bitset_len_buffer_;
int* cuda_categorical_bin_to_value_;
int* cuda_categorical_bin_offsets_;
/*! \brief gradients on CUDA */
score_t* cuda_gradients_;
/*! \brief hessians on CUDA */
score_t* cuda_hessians_;
};
} // namespace LightGBM
#else // USE_CUDA_EXP
// When GPU support is not compiled in, quit with an error message
namespace LightGBM {
class CUDASingleGPUTreeLearner: public SerialTreeLearner {
public:
#pragma warning(disable : 4702)
explicit CUDASingleGPUTreeLearner(const Config* tree_config) : SerialTreeLearner(tree_config) {
Log::Fatal("CUDA Tree Learner experimental version was not enabled in this build.\n"
"Please recompile with CMake option -DUSE_CUDA_EXP=1");
}
};
} // namespace LightGBM
#endif // USE_CUDA_EXP
#endif // LIGHTGBM_TREELEARNER_CUDA_CUDA_SINGLE_GPU_TREE_LEARNER_HPP_
| 35.479167 | 136 | 0.784694 | [
"vector"
] |
1b3457fa809570e58939725af563cc8bb9e5999d | 41,583 | cpp | C++ | src/roadnet/roadnet.cpp | xcb990105/CityFlow | 3d0a23b4c234220a016bbc035ea25d7c7b9949e5 | [
"Apache-2.0"
] | 1 | 2020-04-29T13:10:54.000Z | 2020-04-29T13:10:54.000Z | src/roadnet/roadnet.cpp | wingsweihua/CityFlow | c45712a67f7c8c28b39bb9b9658133a537096010 | [
"Apache-2.0"
] | null | null | null | src/roadnet/roadnet.cpp | wingsweihua/CityFlow | c45712a67f7c8c28b39bb9b9658133a537096010 | [
"Apache-2.0"
] | 1 | 2021-11-26T01:54:40.000Z | 2021-11-26T01:54:40.000Z | #include "roadnet/roadnet.h"
#include "utility/config.h"
#include "vehicle/vehicle.h"
#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include <iostream>
#include <algorithm>
using std::map;
using std::string;
namespace CityFlow {
static double getLengthOfPoints(const std::vector<Point> &points);
static Point getPointByDistance(const std::vector<Point> &points, double dis) {
dis = min2double(max2double(dis, 0), getLengthOfPoints(points));
if (dis <= 0.0)
return points[0];
for (size_t i = 1; i < points.size(); i++) {
double len = (points[i - 1] - points[i]).len();
if (dis > len)
dis -= len;
else
return points[i - 1] + (points[i] - points[i - 1]) * (dis / len);
}
return points.back();
}
static double getLengthOfPoints(const std::vector<Point> &points) {
double length = 0.0;
for (size_t i = 0; i + 1 < points.size(); i++)
length += (points[i + 1] - points[i]).len();
return length;
}
Point RoadNet::getPoint(const Point &p1, const Point &p2, double a) {
return Point((p2.x - p1.x) * a + p1.x, (p2.y - p1.y) * a + p1.y);
}
bool RoadNet::loadFromJson(std::string jsonFileName) {
rapidjson::Document document;
if (!readJsonFromFile(jsonFileName, document)) {
std::cerr << "cannot open roadnet file" << std::endl;
return false;
}
//std::clog << root << std::endl;
std::list<std::string> path;
if (!document.IsObject())
throw JsonTypeError("roadnet config file", "object");
try {
const rapidjson::Value &interValues = getJsonMemberArray("intersections", document);
const rapidjson::Value &roadValues = getJsonMemberArray("roads", document);
// build mapping
roads.resize(roadValues.Size());
intersections.resize(interValues.Size());
for (rapidjson::SizeType i = 0; i < roadValues.Size(); i++) {
path.emplace_back("road[" + std::to_string(i) + "]");
std::string id = getJsonMember<const char*>("id", roadValues[i]);
roadMap[id] = &roads[i];
roads[i].id = id;
path.pop_back();
}
assert(path.empty());
for (rapidjson::SizeType i = 0; i < interValues.Size(); i++) {
path.emplace_back("intersection[" + std::to_string(i) + "]");
std::string id = getJsonMember<const char*>("id", interValues[i]);;
interMap[id] = &intersections[i];
intersections[i].id = id;
path.pop_back();
}
assert(path.empty());
// read roads
path.emplace_back("roads");
for (rapidjson::SizeType i = 0; i < roadValues.Size(); i++) {
// read startIntersection, endIntersection
path.emplace_back(roads[i].getId());
const auto &curRoadValue = roadValues[i];
if (!curRoadValue.IsObject()) {
throw JsonTypeError("road[" + std::to_string(i) + "]", "object");
}
roads[i].startIntersection = interMap[getJsonMember<const char*>("startIntersection", curRoadValue)];
roads[i].endIntersection = interMap[getJsonMember<const char*>("endIntersection", curRoadValue)];
// read lanes
const auto &lanesValue = getJsonMemberArray("lanes", curRoadValue);
int laneIndex = 0;
for (const auto &laneValue : lanesValue.GetArray()) {
path.emplace_back("lane[" + std::to_string(laneIndex) + "]");
if (!laneValue.IsObject())
throw JsonTypeError("lane", "object");
double width = getJsonMember<double>("width", laneValue);
double maxSpeed = getJsonMember<double>("maxSpeed", laneValue);
roads[i].lanes.emplace_back(width, maxSpeed, laneIndex, &roads[i]);
laneIndex++;
path.pop_back();
}
for (auto &lane : roads[i].lanes) {
drivableMap[lane.getId()] = &lane;
}
// read points
const auto &pointsValue = getJsonMemberArray("points", curRoadValue);
for (const auto &pointValue : pointsValue.GetArray()) {
path.emplace_back("point[" + std::to_string(roads[i].points.size()) + "]");
if (!pointValue.IsObject())
throw JsonTypeError("point of road", "object");
double x = getJsonMember<double>("x", pointValue);
double y = getJsonMember<double>("y", pointValue);
roads[i].points.emplace_back(x, y);
path.pop_back();
}
path.pop_back();
}
path.pop_back();
assert(path.empty());
for (rapidjson::SizeType i = 0; i < roadValues.Size(); i++) {
roads[i].initLanesPoints();
}
// read intersections
std::map<std::string, RoadLinkType> typeMap = {{"turn_left", turn_left},
{"turn_right", turn_right},
{"go_straight", go_straight}};
path.emplace_back("intersections");
for (rapidjson::SizeType i = 0; i < interValues.Size(); i++) {
path.emplace_back(intersections[i].getId());
const auto &curInterValue = interValues[i];
if (!curInterValue.IsObject()) {
throw JsonTypeError("intersection", "object");
return false;
}
// read point
const auto &pointValue = getJsonMemberObject("point", curInterValue);
intersections[i].isVirtual = getJsonMember<bool>("virtual", curInterValue);
double x = getJsonMember<double>("x", pointValue);
double y = getJsonMember<double>("y", pointValue);
intersections[i].point = Point(x, y);
// read roads
const auto &roadsValue = getJsonMemberArray("roads", curInterValue);
for (auto &roadNameValue : roadsValue.GetArray()) {
path.emplace_back("roads[" + std::to_string(intersections[i].roads.size()) + "]");
std::string roadName = roadNameValue.GetString();
if (!roadMap.count(roadName))
throw JsonFormatError("No such road: " + roadName);
intersections[i].roads.push_back(roadMap[roadName]);
path.pop_back();
}
// skip other information if intersection is virtual
intersections[i].trafficLight.intersection = &intersections[i];
if (intersections[i].isVirtual) {
path.pop_back();
continue;
}
// read width
intersections[i].width = getJsonMember<double>("width", curInterValue);
// read laneLinks
const auto &roadLinksValue = getJsonMemberArray("roadLinks", curInterValue);
intersections[i].roadLinks.resize(roadLinksValue.Size());
int roadLinkIndex = 0;
for (const auto &roadLinkValue : roadLinksValue.GetArray()) {
path.emplace_back("roadLinks[" + std::to_string(roadLinkIndex) + "]");
if (!roadLinkValue.IsObject())
throw JsonTypeError("roadLink", "object");
RoadLink &roadLink = intersections[i].roadLinks[roadLinkIndex];
roadLink.index = roadLinkIndex++;
roadLink.type = typeMap[getJsonMember<const char*>("type", roadLinkValue)];
roadLink.startRoad = roadMap[getJsonMember<const char*>("startRoad", roadLinkValue)];
roadLink.endRoad = roadMap[getJsonMember<const char*>("endRoad", roadLinkValue)];
const auto &laneLinksValue = getJsonMemberArray("laneLinks", roadLinkValue);
roadLink.laneLinks.resize(laneLinksValue.Size());
int laneLinkIndex = 0;
for (const auto &laneLinkValue : laneLinksValue.GetArray()) {
path.emplace_back("laneLinks[" + std::to_string(laneLinkIndex) + "]");
if (!laneLinkValue.IsObject())
throw JsonTypeError("laneLink", "object");
LaneLink &laneLink = roadLink.laneLinks[laneLinkIndex++];
int startLaneIndex = getJsonMember<int>("startLaneIndex", laneLinkValue);
int endLaneIndex = getJsonMember<int>("endLaneIndex", laneLinkValue);
if (startLaneIndex >= static_cast<int>(roadLink.startRoad->lanes.size()) || startLaneIndex < 0)
throw JsonFormatError("startLaneIndex out of range");
if (endLaneIndex >= static_cast<int>(roadLink.endRoad->lanes.size()) || endLaneIndex < 0)
throw JsonFormatError("startLaneIndex out of range");
Lane *startLane = &roadLink.startRoad->lanes[startLaneIndex];
Lane *endLane = &roadLink.endRoad->lanes[endLaneIndex];
auto iter = laneLinkValue.FindMember("points");
if (iter != laneLinkValue.MemberEnd() && !iter->value.IsArray())
throw JsonTypeError("points in laneLink", "array");
if (iter != laneLinkValue.MemberEnd() && !iter->value.Empty())
for (const auto &pValue : iter->value.GetArray()) {
laneLink.points.emplace_back(getJsonMember<double>("x", pValue),
getJsonMember<double>("y", pValue));
}
else {
Point start = Point(startLane->getPointByDistance(
startLane->getLength() - startLane->getEndIntersection()->width));
Point end = Point(
endLane->getPointByDistance(0.0 + endLane->getStartIntersection()->width));
double len = (Point(end.x - start.x, end.y - start.y)).len();
Point startDirection = startLane->getDirectionByDistance(
startLane->getLength() - startLane->getEndIntersection()->width);
Point endDirection = endLane->getDirectionByDistance(
0.0 + endLane->getStartIntersection()->width);
double minGap = 5;
double gap1X = startDirection.x * len * 0.5;
double gap1Y = startDirection.y * len * 0.5;
double gap2X = -endDirection.x * len * 0.5;
double gap2Y = -endDirection.y * len * 0.5;
if (gap1X * gap1X + gap1Y * gap1Y < 25 && startLane->getEndIntersection()->width >= 5) {
gap1X = minGap * startDirection.x;
gap1Y = minGap * startDirection.y;
}
if (gap2X * gap2X + gap2Y * gap2Y < 25 && endLane->getStartIntersection()->width >= 5) {
gap2X = minGap * endDirection.x;
gap2Y = minGap * endDirection.y;
}
Point mid1 = Point(start.x + gap1X,start.y + gap1Y);
Point mid2 = Point(end.x + gap2X,end.y + gap2Y);
int numPoints = 10;
for (int i = 0; i <= numPoints; i++) {
Point p1 = getPoint(start, mid1, i / double(numPoints));
Point p2 = getPoint(mid1, mid2, i / double(numPoints));
Point p3 = getPoint(mid2, end, i / double(numPoints));
Point p4 = getPoint(p1, p2, i / double(numPoints));
Point p5 = getPoint(p2, p3, i / double(numPoints));
Point p6 = getPoint(p4, p5, i / double(numPoints));
laneLink.points.emplace_back(p6.x, p6.y);
}
}
laneLink.roadLink = &roadLink;
laneLink.startLane = startLane;
laneLink.endLane = endLane;
laneLink.length = getLengthOfPoints(laneLink.points);
startLane->laneLinks.push_back(&laneLink);
drivableMap.emplace(laneLink.getId(), &laneLink);
path.pop_back();
}
roadLink.intersection = &intersections[i];
path.pop_back();
}
// read trafficLight
const auto &trafficLightValue = getJsonMemberObject("trafficLight", curInterValue);
path.emplace_back("trafficLight");
const auto &lightPhasesValue = getJsonMemberArray("lightphases", trafficLightValue);
for (const auto &lightPhaseValue : lightPhasesValue.GetArray()) {
path.emplace_back("lightphases[" + std::to_string(intersections[i].trafficLight.phases.size()) + "]");
if (!lightPhaseValue.IsObject())
throw JsonTypeError("lightphase", "object");
LightPhase lightPhase;
lightPhase.time = getJsonMember<double>("time", lightPhaseValue);
lightPhase.roadLinkAvailable = std::vector<bool>(intersections[i].roadLinks.size(), false);
const auto& availableRoadLinksValue =
getJsonMemberArray("availableRoadLinks", lightPhaseValue);
for (rapidjson::SizeType index = 0; index < availableRoadLinksValue.Size(); index++) {
path.emplace_back("availableRoadLinks[" + std::to_string(index) + "]");
if (!availableRoadLinksValue[index].IsInt())
throw JsonTypeError("availableRoadLink", "int");
size_t indexInRoadLinks = availableRoadLinksValue[index].GetUint();
if (indexInRoadLinks >= lightPhase.roadLinkAvailable.size())
throw JsonFormatError("index out of range");
lightPhase.roadLinkAvailable[indexInRoadLinks] = true;
path.pop_back();
}
intersections[i].trafficLight.phases.push_back(lightPhase);
path.pop_back();
}
path.pop_back(); // End of traffic light
intersections[i].trafficLight.init(0);
path.pop_back(); // End of intersection
}
path.pop_back();
assert(path.empty());
}catch (const JsonFormatError &e) {
std::cerr << "Error occurred when reading the roadnet file: " << std::endl;
for (const auto &node : path) {
std::cerr << "/" << node;
}
std::cerr << " " << e.what() << std::endl;
return false;
}
for (auto &intersection : intersections)
intersection.initCrosses();
VehicleInfo vehicleTemplate;
for (auto &road : roads)
road.initLanesPoints();
for (auto &road : roads) {
road.buildSegmentationByInterval((vehicleTemplate.len + vehicleTemplate.minGap) * MAX_NUM_CARS_ON_SEGMENT);
}
for (auto &road : roads) {
auto &roadLanes = road.getLanePointers();
lanes.insert(lanes.end(), roadLanes.begin(), roadLanes.end());
drivables.insert(drivables.end(), roadLanes.begin(), roadLanes.end());
}
for (auto &intersection : intersections) {
auto &intersectionLaneLinks = intersection.getLaneLinks();
laneLinks.insert(laneLinks.end(), intersectionLaneLinks.begin(), intersectionLaneLinks.end());
drivables.insert(drivables.end(), intersectionLaneLinks.begin(), intersectionLaneLinks.end());
}
return true;
}
rapidjson::Value RoadNet::convertToJson(rapidjson::Document::AllocatorType &allocator) {
rapidjson::Value jsonRoot(rapidjson::kObjectType);
// write nodes
rapidjson::Value jsonNodes(rapidjson::kArrayType);
for (size_t i = 0; i < intersections.size(); ++i) {
rapidjson::Value jsonNode(rapidjson::kObjectType), jsonPoint(rapidjson::kArrayType);
rapidjson::Value idValue;
idValue.SetString(rapidjson::StringRef(intersections[i].id.c_str()));
jsonNode.AddMember("id", idValue, allocator);
jsonPoint.PushBack(intersections[i].point.x, allocator);
jsonPoint.PushBack(intersections[i].point.y, allocator);
jsonNode.AddMember("point", jsonPoint, allocator);
jsonNode.AddMember("virtual", intersections[i].isVirtual, allocator);
if (!intersections[i].isVirtual) {
jsonNode.AddMember("width", intersections[i].width, allocator);
}
rapidjson::Value jsonOutline(rapidjson::kArrayType);
for (auto &point: intersections[i].getOutline()) {
jsonOutline.PushBack(point.x, allocator);
jsonOutline.PushBack(point.y, allocator);
}
jsonNode.AddMember("outline", jsonOutline, allocator);
jsonNodes.PushBack(jsonNode, allocator);
}
jsonRoot.AddMember("nodes", jsonNodes, allocator);
//write edges
rapidjson::Value jsonEdges(rapidjson::kArrayType);
for (size_t i = 0; i < roads.size(); ++i) {
rapidjson::Value jsonEdge(rapidjson::kObjectType);
rapidjson::Value jsonPoints(rapidjson::kArrayType);
rapidjson::Value jsonLaneWidths(rapidjson::kArrayType);
rapidjson::Value jsonDirs(rapidjson::kArrayType);
rapidjson::Value idValue;
idValue.SetString(rapidjson::StringRef(roads[i].id.c_str()));
jsonEdge.AddMember("id", idValue, allocator);
rapidjson::Value startValue;
if (roads[i].startIntersection)
startValue.SetString(rapidjson::StringRef(roads[i].startIntersection->id.c_str()));
else
startValue.SetString("null");
jsonEdge.AddMember("from", startValue, allocator);
rapidjson::Value endValue;
if (roads[i].endIntersection)
endValue.SetString(rapidjson::StringRef(roads[i].endIntersection->id.c_str()));
else
endValue.SetString("null");
jsonEdge.AddMember("to", endValue, allocator);
for (size_t j = 0; j < roads[i].points.size(); ++j) {
rapidjson::Value jsonPoint(rapidjson::kArrayType);
jsonPoint.PushBack(roads[i].points[j].x, allocator);
jsonPoint.PushBack(roads[i].points[j].y, allocator);
jsonPoints.PushBack(jsonPoint, allocator);
}
jsonEdge.AddMember("points", jsonPoints, allocator);
jsonEdge.AddMember("nLane", static_cast<int>(roads[i].lanes.size()), allocator);
for (size_t j = 0; j < roads[i].lanes.size(); ++j) {
jsonLaneWidths.PushBack(roads[i].lanes[j].width, allocator);
}
jsonEdge.AddMember("laneWidths", jsonLaneWidths, allocator);
jsonEdges.PushBack(jsonEdge, allocator);
}
jsonRoot.AddMember("edges", jsonEdges, allocator);
return jsonRoot;
}
Point Drivable::getPointByDistance(double dis) const {
return CityFlow::getPointByDistance(points, dis);
}
Point Drivable::getDirectionByDistance(double dis) const {
double remain = dis;
for (int i = 0; i + 1 < (int) points.size(); i++) {
double len = (points[i + 1] - points[i]).len();
if (remain < len)
return (points[i + 1] - points[i]).unit();
else
remain -= len;
}
return (points[points.size() - 1] - points[points.size() - 2]).unit();
}
Lane::Lane() {
width = 0;
maxSpeed = 0;
laneIndex = -1;
belongRoad = 0;
drivableType = LANE;
}
Lane::Lane(double width, double maxSpeed, int laneIndex, Road *belongRoad) {
this->width = width;
this->maxSpeed = maxSpeed;
this->laneIndex = laneIndex;
this->belongRoad = belongRoad;
drivableType = LANE;
}
bool Lane::available(const Vehicle *vehicle) const {
if (!vehicles.empty()) {
Vehicle *tail = vehicles.back();
return tail->getDistance() > tail->getLen() + vehicle->getMinGap();
} else {
return true;
}
}
bool Lane::canEnter(const Vehicle *vehicle) const {
if (!vehicles.empty()) {
Vehicle *tail = vehicles.back();
return tail->getDistance() > tail->getLen() + vehicle->getLen() ||
tail->getSpeed() >= 2; //todo: speed > 2 or?
} else {
return true;
}
}
std::vector<LaneLink *> Lane::getLaneLinksToRoad(const Road *road) const {
std::vector<LaneLink *> ret;
for (auto &laneLink : laneLinks) {
if (laneLink->getEndLane()->getBelongRoad() == road)
ret.push_back(laneLink);
}
return ret;
}
void Road::initLanesPoints() {
double dsum = 0.0;
std::vector<Point> roadPoints = this->points;
assert(roadPoints.size() >= 2);
if (!startIntersection->isVirtualIntersection()) {
double width = startIntersection->width;
Point p1 = roadPoints[0];
Point p2 = roadPoints[1];
roadPoints[0] = p1 + (p2 - p1).unit() * width;
}
if (!endIntersection->isVirtualIntersection()) {
double width = endIntersection->width;
Point p1 = roadPoints[roadPoints.size() - 2];
Point p2 = roadPoints[roadPoints.size() - 1];
roadPoints[roadPoints.size() - 1] = p2 - (p2 - p1).unit() * width;
}
for (Lane &lane : lanes) {
double dmin = dsum;
double dmax = dsum + lane.width;
lane.points.clear();
for (int j = 0; j < (int) roadPoints.size(); j++) {
// TODO: the '(dmin + dmax) / 2.0' is wrong
std::vector<Point> &lanePoints = lane.points;
if (j == 0) {
Vector u = (roadPoints[1] - roadPoints[0]).unit();
Vector v = -u.normal();
Point startPoint = roadPoints[j] + v * ((dmin + dmax) / 2.0);
lanePoints.push_back(startPoint);
} else if (j + 1 == (int) roadPoints.size()) {
Vector u = (roadPoints[j] - roadPoints[j - 1]).unit();
Vector v = -u.normal();
Point endPoint = roadPoints[j] + v * ((dmin + dmax) / 2.0);
lanePoints.push_back(endPoint);
} else {
Vector u1 = (roadPoints[j + 1] - roadPoints[j]).unit();
Vector u2 = (roadPoints[j] - roadPoints[j - 1]).unit();
Vector u = (u1 + u2).unit();
Vector v = -u.normal();
Point interPoint = roadPoints[j] + v * ((dmin + dmax) / 2.0);
lanePoints.push_back(interPoint);
}
}
lane.length = getLengthOfPoints(lane.points);
dsum += lane.width;
}
}
const std::vector<Lane *> &Road::getLanePointers() {
if (lanePointers.size()) return lanePointers;
for (auto &lane : lanes) {
lanePointers.push_back(&lane);
}
return lanePointers;
}
void Intersection::initCrosses() {
std::vector<LaneLink *> allLaneLinks;
for (auto &roadLink : roadLinks) {
for (auto &laneLink : roadLink.getLaneLinks())
allLaneLinks.push_back(&laneLink);
}
int n = (int) allLaneLinks.size();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
LaneLink *la = allLaneLinks[i];
LaneLink *lb = allLaneLinks[j];
std::vector<Point> &va = la->points;
std::vector<Point> &vb = lb->points;
double disa = 0.0;
for (int ia = 0; ia + 1 < (int) va.size(); ia++) {
double disb = 0.0;
for (int ib = 0; ib + 1 < (int) vb.size(); ib++) {
Point A1 = va[ia], A2 = va[ia + 1];
Point B1 = vb[ib], B2 = vb[ib + 1];
if (Point::sign(crossMultiply(A2 - A1, B2 - B1)) == 0) continue;
Point P = calcIntersectPoint(A1, A2, B1, B2);
if (onSegment(A1, A2, P) && onSegment(B1, B2, P)) {
Cross cross;
cross.laneLinks[0] = la;
cross.laneLinks[1] = lb;
cross.notifyVehicles[0] = nullptr;
cross.notifyVehicles[1] = nullptr;
cross.distanceOnLane[0] = disa + (P - A1).len();
cross.distanceOnLane[1] = disb + (P - B1).len();
cross.ang = calcAng(A2 - A1, B2 - B1);
//assert(cross.ang > 0 && cross.ang < M_PI / 2); // assert cannot pass why?
double w1 = la->getWidth();
double w2 = lb->getWidth();
double c1 = w1 / sin(cross.ang);
double c2 = w2 / sin(cross.ang);
double diag = (c1 * c1 + c2 * c2 + 2 * c1 * c2 * cos(cross.ang)) / 4;
cross.safeDistances[0] = sqrt(diag - w2 * w2 / 4);
cross.safeDistances[1] = sqrt(diag - w1 * w1 / 4);
this->crosses.push_back(cross);
goto FOUND;
}
disb += (vb[ib + 1] - vb[ib]).len();
}
disa += (va[ia + 1] - va[ia]).len();
}
FOUND:;
}
}
for (Cross &cross : this->crosses) {
cross.laneLinks[0]->getCrosses().push_back(&cross);
cross.laneLinks[1]->getCrosses().push_back(&cross);
}
for (auto laneLink : allLaneLinks) {
std::vector<Cross *> &crosses = laneLink->getCrosses();
sort(crosses.begin(), crosses.end(), [laneLink](Cross *ca, Cross *cb) -> bool {
double da = ca->distanceOnLane[ca->laneLinks[0] != laneLink];
double db = cb->distanceOnLane[cb->laneLinks[0] != laneLink];
return da < db;
});
}
}
const std::vector<LaneLink *> &Intersection::getLaneLinks() {
if (laneLinks.size() > 0) return laneLinks;
for (auto &roadLink : roadLinks) {
auto &roadLaneLinks = roadLink.getLaneLinkPointers();
laneLinks.insert(laneLinks.end(), roadLaneLinks.begin(), roadLaneLinks.end());
}
return laneLinks;
}
const std::vector<LaneLink *> &RoadLink::getLaneLinkPointers() {
if (laneLinkPointers.size() > 0) return laneLinkPointers;
for (auto &laneLink : laneLinks) {
laneLinkPointers.push_back(&laneLink);
}
return laneLinkPointers;
}
void Cross::notify(LaneLink *laneLink, Vehicle *vehicle, double notifyDistance) {
assert(laneLink == laneLinks[0] || laneLink == laneLinks[1]);
int i = (laneLink == laneLinks[0]) ? 0 : 1;
assert(notifyVehicles[i] == nullptr);
notifyVehicles[i] = vehicle;
notifyDistances[i] = notifyDistance;
}
bool Cross::canPass(const Vehicle *vehicle, const LaneLink *laneLink, double distanceToLaneLinkStart) const {
// TODO: should be improved
assert(laneLink == laneLinks[0] || laneLink == laneLinks[1]);
int i = (laneLink == laneLinks[0]) ? 0 : 1;
Vehicle *foeVehicle = notifyVehicles[1 - i];
RoadLinkType t1 = laneLinks[i]->getRoadLinkType();
RoadLinkType t2 = laneLinks[1 - i]->getRoadLinkType();
double d1 = distanceOnLane[i] - distanceToLaneLinkStart, d2 = notifyDistances[1 - i];
if (foeVehicle == nullptr) return true;
if (!vehicle->canYield(d1)) return true;
int yield = 0;
if (!foeVehicle->canYield(d2)) yield = 1;
if (yield == 0) {
if (t1 > t2) {
yield = -1;
} else if (t1 < t2) {
if (d2 > 0) {
// todo: can be improved, check if higher priority vehicle is blocked by other vehicles, hard!
int foeVehicleReachSteps = foeVehicle->getReachStepsOnLaneLink(d2, laneLinks[1 - i]);
int reachSteps = vehicle->getReachStepsOnLaneLink(d1, laneLinks[i]);
if (foeVehicleReachSteps > reachSteps) {
yield = -1;
}
} else {
if (d2 + foeVehicle->getLen() < 0) {
yield = -1;
}
}
if (yield == 0) yield = 1;
} else {
if (d2 > 0) {
int foeVehicleReachSteps = foeVehicle->getReachStepsOnLaneLink(d2, laneLinks[1 - i]);
int reachSteps = vehicle->getReachStepsOnLaneLink(d1, laneLinks[i]);
if (foeVehicleReachSteps > reachSteps) {
yield = -1;
} else if (foeVehicleReachSteps < reachSteps) {
yield = 1;
} else {
if (vehicle->getEnterLaneLinkTime() == foeVehicle->getEnterLaneLinkTime()) {
if (d1 == d2) {
yield = vehicle->getPriority() > foeVehicle->getPriority() ? -1 : 1;
} else {
yield = d1 < d2 ? -1 : 1;
}
} else {
yield = vehicle->getEnterLaneLinkTime() < foeVehicle->getEnterLaneLinkTime() ? -1 : 1;
}
}
} else {
yield = d2 + foeVehicle->getLen() < 0 ? -1 : 1;
}
}
}
assert(yield != 0);
if (yield == 1) {
Vehicle *fastPointer = foeVehicle;
Vehicle *slowPointer = foeVehicle;
while (fastPointer != nullptr && fastPointer->getBlocker() != nullptr) {
slowPointer = slowPointer->getBlocker();
fastPointer = fastPointer->getBlocker()->getBlocker();
if (slowPointer == fastPointer) {
// deadlock detected
yield = -1;
break;
}
}
}
return yield == -1;
}
void RoadNet::reset() {
for (auto &road : roads) road.reset();
for (auto &intersection : intersections) intersection.reset();
}
void Road::reset() {
for (auto &lane : lanes) lane.reset();
}
void Road::buildSegmentationByInterval(double interval) {
size_t numSegs = std::max((size_t) ceil(getLengthOfPoints(this->points) / interval), (size_t) 1);
for (Lane &lane : lanes)
lane.buildSegmentation(numSegs);
}
double Road::getWidth() const{
double width = 0;
for (const auto &lane : getLanes()){
width += lane.getWidth();
}
return width;
}
double Road::getLength() const{
double length = 0;
for (const auto &lane : getLanes()){
length += lane.getLength();
}
return length;
}
double Road::averageLength() const{
double sum = 0;
size_t laneNum = getLanes().size();
if (laneNum == 0) return 0;
for (const auto &lane : getLanes()){
sum += lane.getLength();
}
return sum / laneNum;
}
double Road::getAverageSpeed() const{
int vehicleNum = 0;
double speedSum = 0;
for (const auto &lane : lanes) {
vehicleNum += lane.getHistoryVehicleNum();
speedSum += lane.getHistoryAverageSpeed() * lane.getHistoryVehicleNum();
}
return vehicleNum ? speedSum / vehicleNum : -1;
// If no vehicles in history, return -1
}
double Road::getAverageDuration() const{
double averageSpeed = getAverageSpeed();
if (averageSpeed < 0) return -1;
return averageLength() / averageSpeed;
}
bool Road::connectedToRoad(const Road *road) const{
for (const auto &lane : getLanes()) {
if (lane.getLaneLinksToRoad(road).size())
return true;
}
return false;
}
void Intersection::reset() {
trafficLight.reset();
for (auto &roadLink : roadLinks) roadLink.reset();
for (auto &cross : crosses) cross.reset();
}
std::vector<Point> Intersection::getOutline() {
// Calculate the convex hull as the outline of the intersection
std::vector<Point> points;
points.push_back(getPosition());
for (auto road : getRoads()){
Vector roadDirect = road->getEndIntersection().getPosition() - road->getStartIntersection().getPosition();
roadDirect = roadDirect.unit();
Vector pDirect = roadDirect.normal();
if (&road->getStartIntersection() == this) {
roadDirect = -roadDirect;
}
/* <deltaWidth>
* [pointB *]------[pointB1 *]--------
* |
* v
* [pDirect] <- roadDirect <- Road
* |
* v
* [intersection]----[pointA *]------[pointA1 *]--------
*/
double roadWidth = road->getWidth();
double deltaWidth = 0.5 * min2double(width, roadWidth);
deltaWidth = max2double(deltaWidth, 5);
Point pointA = getPosition() - roadDirect * width;
Point pointB = pointA - pDirect * roadWidth;
points.push_back(pointA);
points.push_back(pointB);
if (deltaWidth < road->averageLength()) {
Point pointA1 = pointA - roadDirect * deltaWidth;
Point pointB1 = pointB - roadDirect * deltaWidth;
points.push_back(pointA1);
points.push_back(pointB1);
}
}
auto minIter = std::min_element(points.begin(), points.end(),
[](const Point &a, const Point &b){ return a.y < b.y; });
Point p0 = *minIter;
std::vector<Point> stack;
stack.push_back(p0);
points.erase(minIter);
std::sort(points.begin(), points.end(),
[&p0](const Point &a, const Point &b)
{return (a - p0).ang() < (b - p0).ang(); });
for (size_t i = 0 ; i < points.size(); ++i) {
Point &point = points[i];
Point p2 = stack[stack.size() - 1];
if (stack.size() < 2) {
if (point.x != p2.x || point.y != p2.y)
stack.emplace_back(point);
continue;
}
Point p1 = stack[stack.size() - 2];
while (stack.size() > 1 && crossMultiply(point - p2, p2 - p1) >= 0) {
p2 = p1;
stack.pop_back();
if (stack.size() > 1) p1 = stack[stack.size() - 2];
}
stack.emplace_back(point);
}
return stack;
}
bool Intersection::isImplicitIntersection() {
return trafficLight.getPhases().size() <= 1;
}
void RoadLink::reset() {
for (auto &laneLink : laneLinks) laneLink.reset();
}
void LaneLink::reset() {
vehicles.clear();
}
void Lane::reset() {
waitingBuffer.clear();
vehicles.clear();
}
std::vector<Vehicle *> Lane::getVehiclesBeforeDistance(double dis, size_t segmentIndex, double deltaDis) {
std::vector<Vehicle *> ret;
for (int i = segmentIndex; i >=0 ;i--) {
Segment * segment = getSegment(i);
auto &vehicles = segment->getVehicles();
for(auto it = vehicles.begin(); it != vehicles.end(); ++it) {
Vehicle *vehicle = *(*it);
if (vehicle->getDistance() < dis - deltaDis) return ret;
if (vehicle->getDistance() < dis) ret.emplace_back(vehicle);
}
}
return ret;
}
void Lane::buildSegmentation(size_t numSegs) {
this->segments.resize((unsigned) numSegs);
for (size_t i = 0; i < numSegs; i++) {
segments[i].index = i;
segments[i].vehicles.clear();
segments[i].belongLane = this;
segments[i].startPos = i * this->length / numSegs;
segments[i].endPos = (i + 1) * this->length / numSegs;
}
}
void Lane::initSegments() {
auto iter = this->vehicles.begin();
auto end = this->vehicles.end();
for (int i = (int) segments.size() - 1; i >= 0; i--) {
Segment &seg = segments[i];
seg.vehicles.clear();
while (iter != end && (*iter)->getDistance() >= seg.getStartPos()) {
seg.vehicles.push_back(iter);
(*iter)->setSegmentIndex(seg.index);
++iter;
}
}
}
Vehicle *Lane::getVehicleBeforeDistance(double dis, size_t segmentIndex) const{
for (int i = segmentIndex ; i >= 0 ; --i){
auto vehs = getSegment(i)->getVehicles();
for (auto itr = vehs.begin() ; itr != vehs.end(); ++itr){
auto &vehicle = **itr;
if (vehicle->getDistance() < dis) return **itr;
}
}
return nullptr;
}
Vehicle *Lane::getVehicleAfterDistance(double dis, size_t segmentIndex) const{
for (size_t i = segmentIndex ; i < getSegmentNum() ; ++i){
auto vehs = getSegment(i)->getVehicles();
for (auto itr = vehs.rbegin() ; itr != vehs.rend(); ++itr){
auto &vehicle = **itr;
if (vehicle->getDistance() >= dis) return **itr;
}
}
return nullptr;
}
void Lane::updateHistory() {
double speedSum = historyVehicleNum * historyAverageSpeed;
while (history.size() > historyLen){
historyVehicleNum -= history.front().vehicleNum;
speedSum -= history.front().vehicleNum * history.front().averageSpeed;
history.pop_front();
}
double curSpeedSum = 0;
int vehicleNum = getVehicles().size();
historyVehicleNum += vehicleNum;
for (auto vehicle : getVehicles())
curSpeedSum += vehicle->getSpeed();
speedSum += curSpeedSum;
history.emplace_back(vehicleNum, vehicleNum ? curSpeedSum / vehicleNum : 0);
historyAverageSpeed = historyVehicleNum ? speedSum / historyVehicleNum : 0;
}
int Lane::getHistoryVehicleNum() const{
return historyVehicleNum;
}
double Lane::getHistoryAverageSpeed() const{
return historyAverageSpeed;
}
void Cross::reset() { }
std::list<Vehicle *>::iterator Segment::findVehicle(Vehicle *vehicle) {
for (auto itr = vehicles.begin() ; itr != vehicles.end() ; ++itr)
if (**itr == vehicle) {
return *itr;
}
return belongLane->getVehicles().end();
}
void Segment::removeVehicle(Vehicle *vehicle) {
for (auto itr = vehicles.begin() ; itr != vehicles.end() ; ++itr)
if (**itr == vehicle) {
vehicles.erase(itr);
return;
}
}
void Segment::insertVehicle(std::list<Vehicle *>::iterator &vehicle) {
auto itr = vehicles.begin();
for (; itr != vehicles.end() && (**itr)->getDistance() > (*vehicle)->getDistance() ; ++itr);
vehicles.insert(itr, vehicle);
}
}
| 43.910243 | 122 | 0.507443 | [
"object",
"vector"
] |
1b3b5f7abea92791964b7869bf775d6b10e9975f | 31,338 | cc | C++ | chrome/browser/sessions/session_restore.cc | SlimKatLegacy/android_external_chromium | bc611cda58cc18d0dbaa8a7aee05eb3c0742e573 | [
"BSD-3-Clause"
] | 2 | 2017-02-20T14:25:04.000Z | 2019-12-13T13:58:28.000Z | chrome/browser/sessions/session_restore.cc | SlimKatLegacy/android_external_chromium | bc611cda58cc18d0dbaa8a7aee05eb3c0742e573 | [
"BSD-3-Clause"
] | 2 | 2017-07-25T09:37:22.000Z | 2017-08-04T07:18:56.000Z | chrome/browser/sessions/session_restore.cc | SlimKatLegacy/android_external_chromium | bc611cda58cc18d0dbaa8a7aee05eb3c0742e573 | [
"BSD-3-Clause"
] | 2 | 2020-01-12T00:55:53.000Z | 2020-11-04T06:36:41.000Z | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sessions/session_restore.h"
#include <algorithm>
#include <list>
#include <set>
#include <vector>
#include "base/callback.h"
#include "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "base/metrics/histogram.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/session_service.h"
#include "chrome/browser/sessions/session_types.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/browser_window.h"
#include "content/browser/renderer_host/render_widget_host.h"
#include "content/browser/renderer_host/render_widget_host_view.h"
#include "content/browser/tab_contents/navigation_controller.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/tab_contents/tab_contents_view.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_service.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/boot_times_loader.h"
#include "chrome/browser/chromeos/network_state_notifier.h"
#endif
// Are we in the process of restoring?
static bool restoring = false;
namespace {
// TabLoader ------------------------------------------------------------------
// Initial delay (see class decription for details).
static const int kInitialDelayTimerMS = 100;
// TabLoader is responsible for loading tabs after session restore creates
// tabs. New tabs are loaded after the current tab finishes loading, or a delay
// is reached (initially kInitialDelayTimerMS). If the delay is reached before
// a tab finishes loading a new tab is loaded and the time of the delay
// doubled. When all tabs are loading TabLoader deletes itself.
//
// This is not part of SessionRestoreImpl so that synchronous destruction
// of SessionRestoreImpl doesn't have timing problems.
class TabLoader : public NotificationObserver {
public:
explicit TabLoader(base::TimeTicks restore_started);
~TabLoader();
// Schedules a tab for loading.
void ScheduleLoad(NavigationController* controller);
// Notifies the loader that a tab has been scheduled for loading through
// some other mechanism.
void TabIsLoading(NavigationController* controller);
// Invokes |LoadNextTab| to load a tab.
//
// This must be invoked once to start loading.
void StartLoading();
private:
typedef std::set<NavigationController*> TabsLoading;
typedef std::list<NavigationController*> TabsToLoad;
typedef std::set<RenderWidgetHost*> RenderWidgetHostSet;
// Loads the next tab. If there are no more tabs to load this deletes itself,
// otherwise |force_load_timer_| is restarted.
void LoadNextTab();
// NotificationObserver method. Removes the specified tab and loads the next
// tab.
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details);
// Removes the listeners from the specified tab and removes the tab from
// the set of tabs to load and list of tabs we're waiting to get a load
// from.
void RemoveTab(NavigationController* tab);
// Invoked from |force_load_timer_|. Doubles |force_load_delay_| and invokes
// |LoadNextTab| to load the next tab
void ForceLoadTimerFired();
// Returns the RenderWidgetHost associated with a tab if there is one,
// NULL otherwise.
static RenderWidgetHost* GetRenderWidgetHost(NavigationController* tab);
// Register for necessary notificaitons on a tab navigation controller.
void RegisterForNotifications(NavigationController* controller);
// Called when a tab goes away or a load completes.
void HandleTabClosedOrLoaded(NavigationController* controller);
NotificationRegistrar registrar_;
// Current delay before a new tab is loaded. See class description for
// details.
int64 force_load_delay_;
// Has Load been invoked?
bool loading_;
// Have we recorded the times for a tab paint?
bool got_first_paint_;
// The set of tabs we've initiated loading on. This does NOT include the
// selected tabs.
TabsLoading tabs_loading_;
// The tabs we need to load.
TabsToLoad tabs_to_load_;
// The renderers we have started loading into.
RenderWidgetHostSet render_widget_hosts_loading_;
// The renderers we have loaded and are waiting on to paint.
RenderWidgetHostSet render_widget_hosts_to_paint_;
// The number of tabs that have been restored.
int tab_count_;
base::OneShotTimer<TabLoader> force_load_timer_;
// The time the restore process started.
base::TimeTicks restore_started_;
DISALLOW_COPY_AND_ASSIGN(TabLoader);
};
TabLoader::TabLoader(base::TimeTicks restore_started)
: force_load_delay_(kInitialDelayTimerMS),
loading_(false),
got_first_paint_(false),
tab_count_(0),
restore_started_(restore_started) {
}
TabLoader::~TabLoader() {
DCHECK((got_first_paint_ || render_widget_hosts_to_paint_.empty()) &&
tabs_loading_.empty() && tabs_to_load_.empty());
}
void TabLoader::ScheduleLoad(NavigationController* controller) {
DCHECK(controller);
DCHECK(find(tabs_to_load_.begin(), tabs_to_load_.end(), controller) ==
tabs_to_load_.end());
tabs_to_load_.push_back(controller);
RegisterForNotifications(controller);
}
void TabLoader::TabIsLoading(NavigationController* controller) {
DCHECK(controller);
DCHECK(find(tabs_loading_.begin(), tabs_loading_.end(), controller) ==
tabs_loading_.end());
tabs_loading_.insert(controller);
RenderWidgetHost* render_widget_host = GetRenderWidgetHost(controller);
DCHECK(render_widget_host);
render_widget_hosts_loading_.insert(render_widget_host);
RegisterForNotifications(controller);
}
void TabLoader::StartLoading() {
registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DID_PAINT,
NotificationService::AllSources());
#if defined(OS_CHROMEOS)
if (chromeos::NetworkStateNotifier::is_connected()) {
loading_ = true;
LoadNextTab();
} else {
// Start listening to network state notification now.
registrar_.Add(this, NotificationType::NETWORK_STATE_CHANGED,
NotificationService::AllSources());
}
#else
loading_ = true;
LoadNextTab();
#endif
}
void TabLoader::LoadNextTab() {
if (!tabs_to_load_.empty()) {
NavigationController* tab = tabs_to_load_.front();
DCHECK(tab);
tabs_loading_.insert(tab);
tabs_to_load_.pop_front();
tab->LoadIfNecessary();
if (tab->tab_contents()) {
int tab_index;
Browser* browser = Browser::GetBrowserForController(tab, &tab_index);
if (browser && browser->active_index() != tab_index) {
// By default tabs are marked as visible. As only the active tab is
// visible we need to explicitly tell non-active tabs they are hidden.
// Without this call non-active tabs are not marked as backgrounded.
//
// NOTE: We need to do this here rather than when the tab is added to
// the Browser as at that time not everything has been created, so that
// the call would do nothing.
tab->tab_contents()->WasHidden();
}
}
}
if (!tabs_to_load_.empty()) {
force_load_timer_.Stop();
// Each time we load a tab we also set a timer to force us to start loading
// the next tab if this one doesn't load quickly enough.
force_load_timer_.Start(
base::TimeDelta::FromMilliseconds(force_load_delay_),
this, &TabLoader::ForceLoadTimerFired);
}
}
void TabLoader::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
#if defined(OS_CHROMEOS)
case NotificationType::NETWORK_STATE_CHANGED: {
chromeos::NetworkStateDetails* state_details =
Details<chromeos::NetworkStateDetails>(details).ptr();
switch (state_details->state()) {
case chromeos::NetworkStateDetails::CONNECTED:
if (!loading_) {
loading_ = true;
LoadNextTab();
}
// Start loading
break;
case chromeos::NetworkStateDetails::CONNECTING:
case chromeos::NetworkStateDetails::DISCONNECTED:
// Disconnected while loading. Set loading_ false so
// that it stops trying to load next tab.
loading_ = false;
break;
default:
NOTREACHED() << "Unknown nework state notification:"
<< state_details->state();
}
break;
}
#endif
case NotificationType::LOAD_START: {
// Add this render_widget_host to the set of those we're waiting for
// paints on. We want to only record stats for paints that occur after
// a load has finished.
NavigationController* tab = Source<NavigationController>(source).ptr();
RenderWidgetHost* render_widget_host = GetRenderWidgetHost(tab);
DCHECK(render_widget_host);
render_widget_hosts_loading_.insert(render_widget_host);
break;
}
case NotificationType::TAB_CONTENTS_DESTROYED: {
TabContents* tab_contents = Source<TabContents>(source).ptr();
if (!got_first_paint_) {
RenderWidgetHost* render_widget_host =
GetRenderWidgetHost(&tab_contents->controller());
render_widget_hosts_loading_.erase(render_widget_host);
}
HandleTabClosedOrLoaded(&tab_contents->controller());
break;
}
case NotificationType::LOAD_STOP: {
NavigationController* tab = Source<NavigationController>(source).ptr();
render_widget_hosts_to_paint_.insert(GetRenderWidgetHost(tab));
HandleTabClosedOrLoaded(tab);
break;
}
case NotificationType::RENDER_WIDGET_HOST_DID_PAINT: {
if (!got_first_paint_) {
RenderWidgetHost* render_widget_host =
Source<RenderWidgetHost>(source).ptr();
if (render_widget_hosts_to_paint_.find(render_widget_host) !=
render_widget_hosts_to_paint_.end()) {
// Got a paint for one of our renderers, so record time.
got_first_paint_ = true;
base::TimeDelta time_to_paint =
base::TimeTicks::Now() - restore_started_;
UMA_HISTOGRAM_CUSTOM_TIMES(
"SessionRestore.FirstTabPainted",
time_to_paint,
base::TimeDelta::FromMilliseconds(10),
base::TimeDelta::FromSeconds(100),
100);
// Record a time for the number of tabs, to help track down
// contention.
std::string time_for_count =
StringPrintf("SessionRestore.FirstTabPainted_%d", tab_count_);
base::Histogram* counter_for_count =
base::Histogram::FactoryTimeGet(
time_for_count,
base::TimeDelta::FromMilliseconds(10),
base::TimeDelta::FromSeconds(100),
100,
base::Histogram::kUmaTargetedHistogramFlag);
counter_for_count->AddTime(time_to_paint);
} else if (render_widget_hosts_loading_.find(render_widget_host) ==
render_widget_hosts_loading_.end()) {
// If this is a host for a tab we're not loading some other tab
// has rendered and there's no point tracking the time. This could
// happen because the user opened a different tab or restored tabs
// to an already existing browser and an existing tab painted.
got_first_paint_ = true;
}
}
break;
}
default:
NOTREACHED() << "Unknown notification received:" << type.value;
}
// Delete ourselves when we're not waiting for any more notifications.
if ((got_first_paint_ || render_widget_hosts_to_paint_.empty()) &&
tabs_loading_.empty() && tabs_to_load_.empty())
delete this;
}
void TabLoader::RemoveTab(NavigationController* tab) {
registrar_.Remove(this, NotificationType::TAB_CONTENTS_DESTROYED,
Source<TabContents>(tab->tab_contents()));
registrar_.Remove(this, NotificationType::LOAD_STOP,
Source<NavigationController>(tab));
registrar_.Remove(this, NotificationType::LOAD_START,
Source<NavigationController>(tab));
TabsLoading::iterator i = tabs_loading_.find(tab);
if (i != tabs_loading_.end())
tabs_loading_.erase(i);
TabsToLoad::iterator j =
find(tabs_to_load_.begin(), tabs_to_load_.end(), tab);
if (j != tabs_to_load_.end())
tabs_to_load_.erase(j);
}
void TabLoader::ForceLoadTimerFired() {
force_load_delay_ *= 2;
LoadNextTab();
}
RenderWidgetHost* TabLoader::GetRenderWidgetHost(NavigationController* tab) {
TabContents* tab_contents = tab->tab_contents();
if (tab_contents) {
RenderWidgetHostView* render_widget_host_view =
tab_contents->GetRenderWidgetHostView();
if (render_widget_host_view)
return render_widget_host_view->GetRenderWidgetHost();
}
return NULL;
}
void TabLoader::RegisterForNotifications(NavigationController* controller) {
registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED,
Source<TabContents>(controller->tab_contents()));
registrar_.Add(this, NotificationType::LOAD_STOP,
Source<NavigationController>(controller));
registrar_.Add(this, NotificationType::LOAD_START,
Source<NavigationController>(controller));
++tab_count_;
}
void TabLoader::HandleTabClosedOrLoaded(NavigationController* tab) {
RemoveTab(tab);
if (loading_)
LoadNextTab();
if (tabs_loading_.empty() && tabs_to_load_.empty()) {
base::TimeDelta time_to_load =
base::TimeTicks::Now() - restore_started_;
UMA_HISTOGRAM_CUSTOM_TIMES(
"SessionRestore.AllTabsLoaded",
time_to_load,
base::TimeDelta::FromMilliseconds(10),
base::TimeDelta::FromSeconds(100),
100);
// Record a time for the number of tabs, to help track down contention.
std::string time_for_count =
StringPrintf("SessionRestore.AllTabsLoaded_%d", tab_count_);
base::Histogram* counter_for_count =
base::Histogram::FactoryTimeGet(
time_for_count,
base::TimeDelta::FromMilliseconds(10),
base::TimeDelta::FromSeconds(100),
100,
base::Histogram::kUmaTargetedHistogramFlag);
counter_for_count->AddTime(time_to_load);
}
}
// SessionRestoreImpl ---------------------------------------------------------
// SessionRestoreImpl is responsible for fetching the set of tabs to create
// from SessionService. SessionRestoreImpl deletes itself when done.
class SessionRestoreImpl : public NotificationObserver {
public:
SessionRestoreImpl(Profile* profile,
Browser* browser,
bool synchronous,
bool clobber_existing_window,
bool always_create_tabbed_browser,
const std::vector<GURL>& urls_to_open)
: profile_(profile),
browser_(browser),
synchronous_(synchronous),
clobber_existing_window_(clobber_existing_window),
always_create_tabbed_browser_(always_create_tabbed_browser),
urls_to_open_(urls_to_open),
restore_started_(base::TimeTicks::Now()) {
}
Browser* Restore() {
SessionService* session_service = profile_->GetSessionService();
DCHECK(session_service);
SessionService::SessionCallback* callback =
NewCallback(this, &SessionRestoreImpl::OnGotSession);
session_service->GetLastSession(&request_consumer_, callback);
if (synchronous_) {
bool old_state = MessageLoop::current()->NestableTasksAllowed();
MessageLoop::current()->SetNestableTasksAllowed(true);
MessageLoop::current()->Run();
MessageLoop::current()->SetNestableTasksAllowed(old_state);
Browser* browser = ProcessSessionWindows(&windows_);
delete this;
return browser;
}
if (browser_) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser_));
}
return browser_;
}
// Restore window(s) from a foreign session.
void RestoreForeignSession(
std::vector<SessionWindow*>::const_iterator begin,
std::vector<SessionWindow*>::const_iterator end) {
StartTabCreation();
// Create a browser instance to put the restored tabs in.
for (std::vector<SessionWindow*>::const_iterator i = begin;
i != end; ++i) {
Browser* browser = CreateRestoredBrowser(
static_cast<Browser::Type>((*i)->type),
(*i)->bounds,
(*i)->is_maximized);
// Restore and show the browser.
const int initial_tab_count = browser->tab_count();
int selected_tab_index = (*i)->selected_tab_index;
RestoreTabsToBrowser(*(*i), browser, selected_tab_index);
ShowBrowser(browser, initial_tab_count, selected_tab_index);
tab_loader_->TabIsLoading(
&browser->GetSelectedTabContents()->controller());
NotifySessionServiceOfRestoredTabs(browser, initial_tab_count);
}
// Always create in a new window
FinishedTabCreation(true, true);
}
// Restore a single tab from a foreign session.
// Note: we currently restore the tab to the last active browser.
void RestoreForeignTab(const SessionTab& tab) {
StartTabCreation();
Browser* current_browser =
browser_ ? browser_ : BrowserList::GetLastActive();
RestoreTab(tab, current_browser->tab_count(), current_browser, true);
NotifySessionServiceOfRestoredTabs(current_browser,
current_browser->tab_count());
FinishedTabCreation(true, true);
}
~SessionRestoreImpl() {
STLDeleteElements(&windows_);
restoring = false;
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::BROWSER_CLOSED:
delete this;
return;
default:
NOTREACHED();
break;
}
}
private:
// Invoked when beginning to create new tabs. Resets the tab_loader_.
void StartTabCreation() {
tab_loader_.reset(new TabLoader(restore_started_));
}
// Invoked when done with creating all the tabs/browsers.
//
// |created_tabbed_browser| indicates whether a tabbed browser was created,
// or we used an existing tabbed browser.
//
// If successful, this begins loading tabs and deletes itself when all tabs
// have been loaded.
//
// Returns the Browser that was created, if any.
Browser* FinishedTabCreation(bool succeeded, bool created_tabbed_browser) {
Browser* browser = NULL;
if (!created_tabbed_browser && always_create_tabbed_browser_) {
browser = Browser::Create(profile_);
if (urls_to_open_.empty()) {
// No tab browsers were created and no URLs were supplied on the command
// line. Add an empty URL, which is treated as opening the users home
// page.
urls_to_open_.push_back(GURL());
}
AppendURLsToBrowser(browser, urls_to_open_);
browser->window()->Show();
}
if (succeeded) {
DCHECK(tab_loader_.get());
// TabLoader delets itself when done loading.
tab_loader_.release()->StartLoading();
}
if (!synchronous_) {
// If we're not synchronous we need to delete ourself.
// NOTE: we must use DeleteLater here as most likely we're in a callback
// from the history service which doesn't deal well with deleting the
// object it is notifying.
MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}
return browser;
}
void OnGotSession(SessionService::Handle handle,
std::vector<SessionWindow*>* windows) {
if (synchronous_) {
// See comment above windows_ as to why we don't process immediately.
windows_.swap(*windows);
MessageLoop::current()->Quit();
return;
}
ProcessSessionWindows(windows);
}
Browser* ProcessSessionWindows(std::vector<SessionWindow*>* windows) {
if (windows->empty()) {
// Restore was unsuccessful.
return FinishedTabCreation(false, false);
}
StartTabCreation();
Browser* current_browser =
browser_ ? browser_ : BrowserList::GetLastActive();
// After the for loop this contains the last TABBED_BROWSER. Is null if no
// tabbed browsers exist.
Browser* last_browser = NULL;
bool has_tabbed_browser = false;
for (std::vector<SessionWindow*>::iterator i = windows->begin();
i != windows->end(); ++i) {
Browser* browser = NULL;
if (!has_tabbed_browser && (*i)->type == Browser::TYPE_NORMAL)
has_tabbed_browser = true;
if (i == windows->begin() && (*i)->type == Browser::TYPE_NORMAL &&
!clobber_existing_window_) {
// If there is an open tabbed browser window, use it. Otherwise fall
// through and create a new one.
browser = current_browser;
if (browser && (browser->type() != Browser::TYPE_NORMAL ||
browser->profile()->IsOffTheRecord())) {
browser = NULL;
}
}
if (!browser) {
browser = CreateRestoredBrowser(
static_cast<Browser::Type>((*i)->type),
(*i)->bounds,
(*i)->is_maximized);
}
if ((*i)->type == Browser::TYPE_NORMAL)
last_browser = browser;
const int initial_tab_count = browser->tab_count();
int selected_tab_index = (*i)->selected_tab_index;
RestoreTabsToBrowser(*(*i), browser, selected_tab_index);
ShowBrowser(browser, initial_tab_count, selected_tab_index);
tab_loader_->TabIsLoading(
&browser->GetSelectedTabContents()->controller());
NotifySessionServiceOfRestoredTabs(browser, initial_tab_count);
}
// If we're restoring a session as the result of a crash and the session
// included at least one tabbed browser, then close the browser window
// that was opened when the user clicked to restore the session.
if (clobber_existing_window_ && current_browser && has_tabbed_browser &&
current_browser->type() == Browser::TYPE_NORMAL) {
current_browser->CloseAllTabs();
}
if (last_browser && !urls_to_open_.empty())
AppendURLsToBrowser(last_browser, urls_to_open_);
// If last_browser is NULL and urls_to_open_ is non-empty,
// FinishedTabCreation will create a new TabbedBrowser and add the urls to
// it.
Browser* finished_browser = FinishedTabCreation(true, has_tabbed_browser);
if (finished_browser)
last_browser = finished_browser;
return last_browser;
}
void RestoreTabsToBrowser(const SessionWindow& window,
Browser* browser,
int selected_tab_index) {
DCHECK(!window.tabs.empty());
for (std::vector<SessionTab*>::const_iterator i = window.tabs.begin();
i != window.tabs.end(); ++i) {
const SessionTab& tab = *(*i);
const int tab_index = static_cast<int>(i - window.tabs.begin());
// Don't schedule a load for the selected tab, as ShowBrowser() will
// already have done that.
RestoreTab(tab, tab_index, browser, tab_index != selected_tab_index);
}
}
void RestoreTab(const SessionTab& tab,
const int tab_index,
Browser* browser,
bool schedule_load) {
DCHECK(!tab.navigations.empty());
int selected_index = tab.current_navigation_index;
selected_index = std::max(
0,
std::min(selected_index,
static_cast<int>(tab.navigations.size() - 1)));
// Record an app launch, if applicable.
GURL url = tab.navigations.at(tab.current_navigation_index).virtual_url();
if (
#if defined(OS_CHROMEOS)
browser->profile()->GetExtensionService() &&
#endif
browser->profile()->GetExtensionService()->IsInstalledApp(url)) {
UMA_HISTOGRAM_ENUMERATION(extension_misc::kAppLaunchHistogram,
extension_misc::APP_LAUNCH_SESSION_RESTORE,
extension_misc::APP_LAUNCH_BUCKET_BOUNDARY);
}
TabContents* tab_contents =
browser->AddRestoredTab(tab.navigations,
tab_index,
selected_index,
tab.extension_app_id,
false,
tab.pinned,
true,
NULL);
if (schedule_load)
tab_loader_->ScheduleLoad(&tab_contents->controller());
}
Browser* CreateRestoredBrowser(Browser::Type type,
gfx::Rect bounds,
bool is_maximized) {
Browser* browser = new Browser(type, profile_);
browser->set_override_bounds(bounds);
browser->set_maximized_state(is_maximized ?
Browser::MAXIMIZED_STATE_MAXIMIZED :
Browser::MAXIMIZED_STATE_UNMAXIMIZED);
browser->InitBrowserWindow();
return browser;
}
void ShowBrowser(Browser* browser,
int initial_tab_count,
int selected_session_index) {
if (browser_ == browser) {
browser->ActivateTabAt(browser->tab_count() - 1, true);
return;
}
DCHECK(browser);
DCHECK(browser->tab_count());
browser->ActivateTabAt(
std::min(initial_tab_count + std::max(0, selected_session_index),
browser->tab_count() - 1), true);
browser->window()->Show();
// TODO(jcampan): http://crbug.com/8123 we should not need to set the
// initial focus explicitly.
browser->GetSelectedTabContents()->view()->SetInitialFocus();
}
// Appends the urls in |urls| to |browser|.
void AppendURLsToBrowser(Browser* browser,
const std::vector<GURL>& urls) {
for (size_t i = 0; i < urls.size(); ++i) {
int add_types = TabStripModel::ADD_FORCE_INDEX;
if (i == 0)
add_types |= TabStripModel::ADD_ACTIVE;
int index = browser->GetIndexForInsertionDuringRestore(i);
browser::NavigateParams params(browser, urls[i],
PageTransition::START_PAGE);
params.disposition = i == 0 ? NEW_FOREGROUND_TAB : NEW_BACKGROUND_TAB;
params.tabstrip_index = index;
params.tabstrip_add_types = add_types;
browser::Navigate(¶ms);
}
}
// Invokes TabRestored on the SessionService for all tabs in browser after
// initial_count.
void NotifySessionServiceOfRestoredTabs(Browser* browser, int initial_count) {
SessionService* session_service = profile_->GetSessionService();
for (int i = initial_count; i < browser->tab_count(); ++i)
session_service->TabRestored(&browser->GetTabContentsAt(i)->controller(),
browser->tabstrip_model()->IsTabPinned(i));
}
// The profile to create the sessions for.
Profile* profile_;
// The first browser to restore to, may be null.
Browser* browser_;
// Whether or not restore is synchronous.
const bool synchronous_;
// See description in RestoreSession (in .h).
const bool clobber_existing_window_;
// If true and there is an error or there are no windows to restore, we
// create a tabbed browser anyway. This is used on startup to make sure at
// at least one window is created.
const bool always_create_tabbed_browser_;
// Set of URLs to open in addition to those restored from the session.
std::vector<GURL> urls_to_open_;
// Used to get the session.
CancelableRequestConsumer request_consumer_;
// Responsible for loading the tabs.
scoped_ptr<TabLoader> tab_loader_;
// When synchronous we run a nested message loop. To avoid creating windows
// from the nested message loop (which can make exiting the nested message
// loop take a while) we cache the SessionWindows here and create the actual
// windows when the nested message loop exits.
std::vector<SessionWindow*> windows_;
NotificationRegistrar registrar_;
// The time we started the restore.
base::TimeTicks restore_started_;
};
} // namespace
// SessionRestore -------------------------------------------------------------
static Browser* Restore(Profile* profile,
Browser* browser,
bool synchronous,
bool clobber_existing_window,
bool always_create_tabbed_browser,
const std::vector<GURL>& urls_to_open) {
#if defined(OS_CHROMEOS)
chromeos::BootTimesLoader::Get()->AddLoginTimeMarker(
"SessionRestoreStarted", false);
#endif
DCHECK(profile);
// Always restore from the original profile (incognito profiles have no
// session service).
profile = profile->GetOriginalProfile();
if (!profile->GetSessionService()) {
NOTREACHED();
return NULL;
}
restoring = true;
profile->set_restored_last_session(true);
// SessionRestoreImpl takes care of deleting itself when done.
SessionRestoreImpl* restorer =
new SessionRestoreImpl(profile, browser, synchronous,
clobber_existing_window,
always_create_tabbed_browser, urls_to_open);
return restorer->Restore();
}
// static
void SessionRestore::RestoreSession(Profile* profile,
Browser* browser,
bool clobber_existing_window,
bool always_create_tabbed_browser,
const std::vector<GURL>& urls_to_open) {
Restore(profile, browser, false, clobber_existing_window,
always_create_tabbed_browser, urls_to_open);
}
// static
void SessionRestore::RestoreForeignSessionWindows(
Profile* profile,
std::vector<SessionWindow*>::const_iterator begin,
std::vector<SessionWindow*>::const_iterator end) {
// Create a SessionRestore object to eventually restore the tabs.
std::vector<GURL> gurls;
SessionRestoreImpl restorer(profile,
static_cast<Browser*>(NULL), true, false, true, gurls);
restorer.RestoreForeignSession(begin, end);
}
// static
void SessionRestore::RestoreForeignSessionTab(Profile* profile,
const SessionTab& tab) {
// Create a SessionRestore object to eventually restore the tabs.
std::vector<GURL> gurls;
SessionRestoreImpl restorer(profile,
static_cast<Browser*>(NULL), true, false, true, gurls);
restorer.RestoreForeignTab(tab);
}
// static
Browser* SessionRestore::RestoreSessionSynchronously(
Profile* profile,
const std::vector<GURL>& urls_to_open) {
return Restore(profile, NULL, true, false, true, urls_to_open);
}
// static
bool SessionRestore::IsRestoring() {
return restoring;
}
| 36.911661 | 80 | 0.669794 | [
"object",
"vector"
] |
1b44d19d6551138568f9993cc8f10a19214f715c | 43,289 | cpp | C++ | okvis_ceres/src/Map.cpp | wbl1997/okvis | 65e30d6ab25380d65c96c665485148e2ab55e93e | [
"BSD-3-Clause"
] | 1 | 2022-03-26T15:31:53.000Z | 2022-03-26T15:31:53.000Z | okvis_ceres/src/Map.cpp | wbl1997/okvis | 65e30d6ab25380d65c96c665485148e2ab55e93e | [
"BSD-3-Clause"
] | null | null | null | okvis_ceres/src/Map.cpp | wbl1997/okvis | 65e30d6ab25380d65c96c665485148e2ab55e93e | [
"BSD-3-Clause"
] | 2 | 2021-08-01T16:49:17.000Z | 2021-09-14T09:00:03.000Z | /*********************************************************************************
* OKVIS - Open Keyframe-based Visual-Inertial SLAM
* Copyright (c) 2015, Autonomous Systems Lab / ETH Zurich
*
* 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 Autonomous Systems Lab / ETH Zurich nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Created on: Sep 8, 2013
* Author: Stefan Leutenegger (s.leutenegger@imperial.ac.uk)
* Modified: Andreas Forster (an.forster@gmail.com)
*********************************************************************************/
/**
* @file Map.cpp
* @brief Source file for the Map class.
* @author Stefan Leutenegger
* @author Andreas Forster
*/
#include <okvis/ceres/Map.hpp>
#include <ceres/ordered_groups.h>
#include <okvis/ceres/HomogeneousPointParameterBlock.hpp>
#include <okvis/ceres/MarginalizationError.hpp>
#include <okvis/kinematics/MatrixPseudoInverse.hpp>
/// \brief okvis Main namespace of this package.
namespace okvis {
/// \brief ceres Namespace for ceres-related functionality implemented in okvis.
namespace ceres {
// Constructor.
Map::Map(::ceres::EvaluationCallback* evaluation_callback)
: residualCounter_(0) {
::ceres::Problem::Options problemOptions;
problemOptions.evaluation_callback = evaluation_callback;
problemOptions.local_parameterization_ownership =
::ceres::Ownership::DO_NOT_TAKE_OWNERSHIP;
problemOptions.loss_function_ownership =
::ceres::Ownership::DO_NOT_TAKE_OWNERSHIP;
problemOptions.cost_function_ownership =
::ceres::Ownership::DO_NOT_TAKE_OWNERSHIP;
//problemOptions.enable_fast_parameter_block_removal = true;
problem_.reset(new ::ceres::Problem(problemOptions));
//options.linear_solver_ordering = new ::ceres::ParameterBlockOrdering;
}
// Check whether a certain parameter block is part of the map.
bool Map::parameterBlockExists(uint64_t parameterBlockId) const {
if (id2ParameterBlock_Map_.find(parameterBlockId)
== id2ParameterBlock_Map_.end())
return false;
return true;
}
// Log information on a parameter block.
void Map::printParameterBlockInfo(uint64_t parameterBlockId) const {
ResidualBlockCollection residualCollection = residuals(parameterBlockId);
LOG(INFO) << "parameter info" << std::endl << "----------------------------"
<< std::endl << " - block Id: " << parameterBlockId << std::endl
<< " - type: " << parameterBlockPtr(parameterBlockId)->typeInfo()
<< std::endl << " - residuals (" << residualCollection.size()
<< "):";
for (size_t i = 0; i < residualCollection.size(); ++i) {
LOG(INFO)
<< " - id: "
<< residualCollection.at(i).residualBlockId
<< std::endl
<< " - type: "
<< errorInterfacePtr(residualCollection.at(i).residualBlockId)->typeInfo();
}
LOG(INFO) << "============================";
}
// Log information on a residual block.
void Map::printResidualBlockInfo(
::ceres::ResidualBlockId residualBlockId) const {
LOG(INFO) << " - id: " << residualBlockId << std::endl << " - type: "
<< errorInterfacePtr(residualBlockId)->typeInfo();
}
// Obtain the Hessian block for a specific parameter block.
void Map::getLhs(uint64_t parameterBlockId, Eigen::MatrixXd& H) {
OKVIS_ASSERT_TRUE_DBG(Exception,parameterBlockExists(parameterBlockId),"parameter block not in map.");
ResidualBlockCollection res = residuals(parameterBlockId);
H.setZero();
for (size_t i = 0; i < res.size(); ++i) {
// parameters:
ParameterBlockCollection pars = parameters(res[i].residualBlockId);
double** parametersRaw = new double*[pars.size()];
Eigen::VectorXd residualsEigen(res[i].errorInterfacePtr->residualDim());
double* residualsRaw = residualsEigen.data();
double** jacobiansRaw = new double*[pars.size()];
std::vector<
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>,
Eigen::aligned_allocator<
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic,
Eigen::RowMajor> > > jacobiansEigen(pars.size());
double** jacobiansMinimalRaw = new double*[pars.size()];
std::vector<
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>,
Eigen::aligned_allocator<
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic,
Eigen::RowMajor> > > jacobiansMinimalEigen(pars.size());
int J = -1;
for (size_t j = 0; j < pars.size(); ++j) {
// determine which is the relevant block
if (pars[j].second->id() == parameterBlockId)
J = j;
parametersRaw[j] = pars[j].second->parameters();
jacobiansEigen[j].resize(res[i].errorInterfacePtr->residualDim(),
pars[j].second->dimension());
jacobiansRaw[j] = jacobiansEigen[j].data();
jacobiansMinimalEigen[j].resize(res[i].errorInterfacePtr->residualDim(),
pars[j].second->minimalDimension());
jacobiansMinimalRaw[j] = jacobiansMinimalEigen[j].data();
}
// evaluate residual block
res[i].errorInterfacePtr->EvaluateWithMinimalJacobians(parametersRaw,
residualsRaw,
jacobiansRaw,
jacobiansMinimalRaw);
// get block
H += jacobiansMinimalEigen[J].transpose() * jacobiansMinimalEigen[J];
// cleanup
delete[] parametersRaw;
delete[] jacobiansRaw;
delete[] jacobiansMinimalRaw;
}
}
// Check a Jacobian with numeric differences.
bool Map::isJacobianCorrect(::ceres::ResidualBlockId residualBlockId,
double relTol) const {
std::shared_ptr<const okvis::ceres::ErrorInterface> errorInterface_ptr =
errorInterfacePtr(residualBlockId);
ParameterBlockCollection parametersBlocks = parameters(residualBlockId);
// set up data structures for storage
std::vector<
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>,
Eigen::aligned_allocator<
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > > J(
parametersBlocks.size());
std::vector<
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>,
Eigen::aligned_allocator<
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > > J_min(
parametersBlocks.size());
std::vector<
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>,
Eigen::aligned_allocator<
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > > J_numDiff(
parametersBlocks.size());
std::vector<
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>,
Eigen::aligned_allocator<
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > > J_min_numDiff(
parametersBlocks.size());
double **parameters, **jacobians, **jacobiansMinimal;
parameters = new double*[parametersBlocks.size()];
jacobians = new double*[parametersBlocks.size()];
jacobiansMinimal = new double*[parametersBlocks.size()];
for (size_t i = 0; i < parametersBlocks.size(); ++i) {
// set up the analytic Jacobians
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Ji(
errorInterface_ptr->residualDim(),
parametersBlocks[i].second->dimension());
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Ji_min(
errorInterface_ptr->residualDim(),
parametersBlocks[i].second->minimalDimension());
// set up the numeric ones
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Ji_numDiff(
errorInterface_ptr->residualDim(),
parametersBlocks[i].second->dimension());
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Ji_min_numDiff(
errorInterface_ptr->residualDim(),
parametersBlocks[i].second->minimalDimension());
// fill in
J[i].resize(errorInterface_ptr->residualDim(),
parametersBlocks[i].second->dimension());
J_min[i].resize(errorInterface_ptr->residualDim(),
parametersBlocks[i].second->minimalDimension());
J_numDiff[i].resize(errorInterface_ptr->residualDim(),
parametersBlocks[i].second->dimension());
J_min_numDiff[i].resize(errorInterface_ptr->residualDim(),
parametersBlocks[i].second->minimalDimension());
parameters[i] = parametersBlocks[i].second->parameters();
jacobians[i] = J[i].data();
jacobiansMinimal[i] = J_min[i].data();
}
// calculate num diff Jacobians
const double delta = 1e-8;
for (size_t i = 0; i < parametersBlocks.size(); ++i) {
for (size_t j = 0; j < parametersBlocks[i].second->minimalDimension();
++j) {
Eigen::VectorXd residuals_p(errorInterface_ptr->residualDim());
Eigen::VectorXd residuals_m(errorInterface_ptr->residualDim());
// apply positive delta
Eigen::VectorXd parameters_p(parametersBlocks[i].second->dimension());
Eigen::VectorXd parameters_m(parametersBlocks[i].second->dimension());
Eigen::VectorXd plus(parametersBlocks[i].second->minimalDimension());
plus.setZero();
plus[j] = delta;
parametersBlocks[i].second->plus(parameters[i], plus.data(),
parameters_p.data());
parameters[i] = parameters_p.data();
errorInterface_ptr->EvaluateWithMinimalJacobians(parameters,
residuals_p.data(), NULL,
NULL);
parameters[i] = parametersBlocks[i].second->parameters(); // reset
// apply negative delta
plus.setZero();
plus[j] = -delta;
parametersBlocks[i].second->plus(parameters[i], plus.data(),
parameters_m.data());
parameters[i] = parameters_m.data();
errorInterface_ptr->EvaluateWithMinimalJacobians(parameters,
residuals_m.data(), NULL,
NULL);
parameters[i] = parametersBlocks[i].second->parameters(); // reset
// calculate numeric difference
J_min_numDiff[i].col(j) = (residuals_p - residuals_m) * 1.0
/ (2.0 * delta);
}
}
// calculate analytic Jacobians and compare
bool isCorrect = true;
Eigen::VectorXd residuals(errorInterface_ptr->residualDim());
for (size_t i = 0; i < parametersBlocks.size(); ++i) {
// calc
errorInterface_ptr->EvaluateWithMinimalJacobians(parameters,
residuals.data(),
jacobians,
jacobiansMinimal);
// check
double norm = J_min_numDiff[i].norm();
Eigen::MatrixXd J_diff = J_min_numDiff[i] - J_min[i];
double maxDiff = std::max(-J_diff.minCoeff(), J_diff.maxCoeff());
if (maxDiff / norm > relTol) {
LOG(INFO) << "Jacobian inconsistent: " << errorInterface_ptr->typeInfo();
LOG(INFO) << "num diff Jacobian[" << i << "]:";
LOG(INFO) << J_min_numDiff[i];
LOG(INFO) << "provided Jacobian[" << i << "]:";
LOG(INFO) << J_min[i];
LOG(INFO) << "relative error: " << maxDiff / norm
<< ", relative tolerance: " << relTol;
isCorrect = false;
}
}
delete[] parameters;
delete[] jacobians;
delete[] jacobiansMinimal;
return isCorrect;
}
// Add a parameter block to the map
bool Map::addParameterBlock(
std::shared_ptr<okvis::ceres::ParameterBlock> parameterBlock,
int parameterization, const int /*group*/) {
// check Id availability
if (parameterBlockExists(parameterBlock->id())) {
return false;
}
id2ParameterBlock_Map_.insert(
std::pair<uint64_t, std::shared_ptr<okvis::ceres::ParameterBlock> >(
parameterBlock->id(), parameterBlock));
// also add to ceres problem
switch (parameterization) {
case Parameterization::Trivial: {
problem_->AddParameterBlock(parameterBlock->parameters(),
parameterBlock->dimension());
break;
}
case Parameterization::HomogeneousPoint: {
problem_->AddParameterBlock(parameterBlock->parameters(),
parameterBlock->dimension(),
&homogeneousPointLocalParameterization_);
parameterBlock->setLocalParameterizationPtr(
&homogeneousPointLocalParameterization_);
break;
}
case Parameterization::Pose6d: {
problem_->AddParameterBlock(parameterBlock->parameters(),
parameterBlock->dimension(),
&poseLocalParameterization_);
parameterBlock->setLocalParameterizationPtr(&poseLocalParameterization_);
break;
}
case Parameterization::Pose3d: {
problem_->AddParameterBlock(parameterBlock->parameters(),
parameterBlock->dimension(),
&poseLocalParameterization3d_);
parameterBlock->setLocalParameterizationPtr(&poseLocalParameterization3d_);
break;
}
case Parameterization::Pose4d: {
problem_->AddParameterBlock(parameterBlock->parameters(),
parameterBlock->dimension(),
&poseLocalParameterization4d_);
parameterBlock->setLocalParameterizationPtr(&poseLocalParameterization4d_);
break;
}
case Parameterization::Pose2d: {
problem_->AddParameterBlock(parameterBlock->parameters(),
parameterBlock->dimension(),
&poseLocalParameterization2d_);
parameterBlock->setLocalParameterizationPtr(&poseLocalParameterization2d_);
break;
}
default: {
return false;
break; // just for consistency...
}
}
/*const okvis::ceres::LocalParamizationAdditionalInterfaces* ptr =
dynamic_cast<const okvis::ceres::LocalParamizationAdditionalInterfaces*>(
parameterBlock->localParameterizationPtr());
if(ptr)
std::cout<<"verify local size "<< parameterBlock->localParameterizationPtr()->LocalSize() << " = "<<
int(ptr->verify(parameterBlock->parameters()))<<
std::endl;*/
return true;
}
// Remove a parameter block from the map.
bool Map::removeParameterBlock(uint64_t parameterBlockId) {
if (!parameterBlockExists(parameterBlockId))
return false;
// remove all connected residuals
const ResidualBlockCollection res = residuals(parameterBlockId);
for (size_t i = 0; i < res.size(); ++i) {
removeResidualBlock(res[i].residualBlockId); // remove in ceres and book-keeping
}
problem_->RemoveParameterBlock(
parameterBlockPtr(parameterBlockId)->parameters()); // remove parameter block
id2ParameterBlock_Map_.erase(parameterBlockId); // remove book-keeping
return true;
}
// Remove a parameter block from the map.
bool Map::removeParameterBlock(
std::shared_ptr<okvis::ceres::ParameterBlock> parameterBlock) {
return removeParameterBlock(parameterBlock->id());
}
// Adds a residual block.
::ceres::ResidualBlockId Map::addResidualBlock(
std::shared_ptr< ::ceres::CostFunction> cost_function,
::ceres::LossFunction* loss_function,
std::vector<std::shared_ptr<okvis::ceres::ParameterBlock> >& parameterBlockPtrs) {
::ceres::ResidualBlockId return_id;
std::vector<double*> parameter_blocks;
ParameterBlockCollection parameterBlockCollection;
for (size_t i = 0; i < parameterBlockPtrs.size(); ++i) {
parameter_blocks.push_back(parameterBlockPtrs.at(i)->parameters());
parameterBlockCollection.push_back(
ParameterBlockSpec(parameterBlockPtrs.at(i)->id(),
parameterBlockPtrs.at(i)));
}
// add in ceres
return_id = problem_->AddResidualBlock(cost_function.get(), loss_function,
parameter_blocks);
// add in book-keeping
std::shared_ptr<ErrorInterface> errorInterfacePtr = std::dynamic_pointer_cast<
ErrorInterface>(cost_function);
OKVIS_ASSERT_TRUE_DBG(Exception,errorInterfacePtr!=0,"Supplied a cost function without okvis::ceres::ErrorInterface");
residualBlockId2ResidualBlockSpec_Map_.insert(
std::pair< ::ceres::ResidualBlockId, ResidualBlockSpec>(
return_id,
ResidualBlockSpec(return_id, loss_function, errorInterfacePtr)));
// update book-keeping
std::pair<ResidualBlockId2ParameterBlockCollection_Map::iterator, bool> insertion =
residualBlockId2ParameterBlockCollection_Map_.insert(
std::pair< ::ceres::ResidualBlockId, ParameterBlockCollection>(
return_id, parameterBlockCollection));
if (insertion.second == false)
return ::ceres::ResidualBlockId(0);
// update ResidualBlock pointers on involved ParameterBlocks
for (uint64_t parameter_id = 0;
parameter_id < parameterBlockCollection.size(); ++parameter_id) {
id2ResidualBlock_Multimap_.insert(
std::pair<uint64_t, ResidualBlockSpec>(
parameterBlockCollection[parameter_id].first,
ResidualBlockSpec(return_id, loss_function, errorInterfacePtr)));
}
return return_id;
}
// Add a residual block. See respective ceres docu. If more are needed, see other interface.
::ceres::ResidualBlockId Map::addResidualBlock(
std::shared_ptr< ::ceres::CostFunction> cost_function,
::ceres::LossFunction* loss_function,
std::shared_ptr<okvis::ceres::ParameterBlock> x0,
std::shared_ptr<okvis::ceres::ParameterBlock> x1,
std::shared_ptr<okvis::ceres::ParameterBlock> x2,
std::shared_ptr<okvis::ceres::ParameterBlock> x3,
std::shared_ptr<okvis::ceres::ParameterBlock> x4,
std::shared_ptr<okvis::ceres::ParameterBlock> x5,
std::shared_ptr<okvis::ceres::ParameterBlock> x6,
std::shared_ptr<okvis::ceres::ParameterBlock> x7,
std::shared_ptr<okvis::ceres::ParameterBlock> x8,
std::shared_ptr<okvis::ceres::ParameterBlock> x9) {
std::vector<std::shared_ptr<okvis::ceres::ParameterBlock> > parameterBlockPtrs;
if (x0 != 0) {
parameterBlockPtrs.push_back(x0);
}
if (x1 != 0) {
parameterBlockPtrs.push_back(x1);
}
if (x2 != 0) {
parameterBlockPtrs.push_back(x2);
}
if (x3 != 0) {
parameterBlockPtrs.push_back(x3);
}
if (x4 != 0) {
parameterBlockPtrs.push_back(x4);
}
if (x5 != 0) {
parameterBlockPtrs.push_back(x5);
}
if (x6 != 0) {
parameterBlockPtrs.push_back(x6);
}
if (x7 != 0) {
parameterBlockPtrs.push_back(x7);
}
if (x8 != 0) {
parameterBlockPtrs.push_back(x8);
}
if (x9 != 0) {
parameterBlockPtrs.push_back(x9);
}
return Map::addResidualBlock(cost_function, loss_function, parameterBlockPtrs);
}
// Replace the parameters connected to a residual block ID.
void Map::resetResidualBlock(
::ceres::ResidualBlockId residualBlockId,
std::vector<std::shared_ptr<okvis::ceres::ParameterBlock> >& parameterBlockPtrs) {
// remember the residual block spec:
ResidualBlockSpec spec =
residualBlockId2ResidualBlockSpec_Map_[residualBlockId];
// remove residual from old parameter set
ResidualBlockId2ParameterBlockCollection_Map::iterator it =
residualBlockId2ParameterBlockCollection_Map_.find(residualBlockId);
OKVIS_ASSERT_TRUE_DBG(Exception,it!=residualBlockId2ParameterBlockCollection_Map_.end(),
"residual block not in map.");
for (ParameterBlockCollection::iterator parameter_it = it->second.begin();
parameter_it != it->second.end(); ++parameter_it) {
uint64_t parameterId = parameter_it->second->id();
std::pair<Id2ResidualBlock_Multimap::iterator,
Id2ResidualBlock_Multimap::iterator> range = id2ResidualBlock_Multimap_
.equal_range(parameterId);
OKVIS_ASSERT_FALSE_DBG(Exception,range.first==id2ResidualBlock_Multimap_.end(),"book-keeping is broken");
for (Id2ResidualBlock_Multimap::iterator it2 = range.first;
it2 != range.second;) {
if (residualBlockId == it2->second.residualBlockId) {
it2 = id2ResidualBlock_Multimap_.erase(it2); // remove book-keeping
} else {
it2++;
}
}
}
ParameterBlockCollection parameterBlockCollection;
for (size_t i = 0; i < parameterBlockPtrs.size(); ++i) {
parameterBlockCollection.push_back(
ParameterBlockSpec(parameterBlockPtrs.at(i)->id(),
parameterBlockPtrs.at(i)));
}
// update book-keeping
it->second = parameterBlockCollection;
// update ResidualBlock pointers on involved ParameterBlocks
for (uint64_t parameter_id = 0;
parameter_id < parameterBlockCollection.size(); ++parameter_id) {
id2ResidualBlock_Multimap_.insert(
std::pair<uint64_t, ResidualBlockSpec>(
parameterBlockCollection[parameter_id].first, spec));
}
}
// Remove a residual block.
bool Map::removeResidualBlock(::ceres::ResidualBlockId residualBlockId) {
problem_->RemoveResidualBlock(residualBlockId); // remove in ceres
ResidualBlockId2ParameterBlockCollection_Map::iterator it =
residualBlockId2ParameterBlockCollection_Map_.find(residualBlockId);
if (it == residualBlockId2ParameterBlockCollection_Map_.end())
return false;
for (ParameterBlockCollection::iterator parameter_it = it->second.begin();
parameter_it != it->second.end(); ++parameter_it) {
uint64_t parameterId = parameter_it->second->id();
std::pair<Id2ResidualBlock_Multimap::iterator,
Id2ResidualBlock_Multimap::iterator> range = id2ResidualBlock_Multimap_
.equal_range(parameterId);
OKVIS_ASSERT_FALSE_DBG(Exception,range.first==id2ResidualBlock_Multimap_.end(),"book-keeping is broken");
for (Id2ResidualBlock_Multimap::iterator it2 = range.first;
it2 != range.second;) {
if (residualBlockId == it2->second.residualBlockId) {
it2 = id2ResidualBlock_Multimap_.erase(it2); // remove book-keeping
} else {
it2++;
}
}
}
residualBlockId2ParameterBlockCollection_Map_.erase(it); // remove book-keeping
residualBlockId2ResidualBlockSpec_Map_.erase(residualBlockId); // remove book-keeping
return true;
}
// Do not optimise a certain parameter block.
bool Map::setParameterBlockConstant(uint64_t parameterBlockId) {
if (!parameterBlockExists(parameterBlockId))
return false;
std::shared_ptr<ParameterBlock> parameterBlock = id2ParameterBlock_Map_.find(
parameterBlockId)->second;
parameterBlock->setFixed(true);
problem_->SetParameterBlockConstant(parameterBlock->parameters());
return true;
}
// Optimise a certain parameter block (this is the default).
bool Map::setParameterBlockVariable(uint64_t parameterBlockId) {
if (!parameterBlockExists(parameterBlockId))
return false;
std::shared_ptr<ParameterBlock> parameterBlock = id2ParameterBlock_Map_.find(
parameterBlockId)->second;
parameterBlock->setFixed(false);
problem_->SetParameterBlockVariable(parameterBlock->parameters());
return true;
}
// Reset the (local) parameterisation of a parameter block.
bool Map::resetParameterization(uint64_t parameterBlockId,
int parameterization) {
if (!parameterBlockExists(parameterBlockId))
return false;
// the ceres documentation states that a parameterization may never be changed on.
// therefore, we have to remove the parameter block in question and re-add it.
ResidualBlockCollection res = residuals(parameterBlockId);
std::shared_ptr<ParameterBlock> parBlockPtr = parameterBlockPtr(
parameterBlockId);
// get parameter block pointers
std::vector<std::vector<std::shared_ptr<okvis::ceres::ParameterBlock> > > parameterBlockPtrs(
res.size());
for (size_t r = 0; r < res.size(); ++r) {
ParameterBlockCollection pspec = parameters(res[r].residualBlockId);
for (size_t p = 0; p < pspec.size(); ++p) {
parameterBlockPtrs[r].push_back(pspec[p].second);
}
}
// remove
// int group = options.linear_solver_ordering->GroupId(parBlockPtr->parameters());
removeParameterBlock(parameterBlockId);
// add with new parameterization
addParameterBlock(parBlockPtr, parameterization/*,group*/);
// re-assemble
for (size_t r = 0; r < res.size(); ++r) {
addResidualBlock(
std::dynamic_pointer_cast< ::ceres::CostFunction>(
res[r].errorInterfacePtr),
res[r].lossFunctionPtr, parameterBlockPtrs[r]);
}
return true;
}
// Set the (local) parameterisation of a parameter block.
bool Map::setParameterization(
uint64_t parameterBlockId,
::ceres::LocalParameterization* local_parameterization) {
if (!parameterBlockExists(parameterBlockId))
return false;
problem_->SetParameterization(
id2ParameterBlock_Map_.find(parameterBlockId)->second->parameters(),
local_parameterization);
id2ParameterBlock_Map_.find(parameterBlockId)->second
->setLocalParameterizationPtr(local_parameterization);
return true;
}
// getters
// Get a shared pointer to a parameter block.
std::shared_ptr<okvis::ceres::ParameterBlock> Map::parameterBlockPtr(
uint64_t parameterBlockId) {
// get a parameterBlock
OKVIS_ASSERT_TRUE(
Exception, parameterBlockExists(parameterBlockId),
"parameterBlock with id "<<parameterBlockId<<" does not exist");
if (parameterBlockExists(parameterBlockId)) {
return id2ParameterBlock_Map_.find(parameterBlockId)->second;
}
return std::shared_ptr<okvis::ceres::ParameterBlock>(); // NULL
}
// Get a shared pointer to a parameter block.
std::shared_ptr<const okvis::ceres::ParameterBlock> Map::parameterBlockPtr(
uint64_t parameterBlockId) const {
// get a parameterBlock
if (parameterBlockExists(parameterBlockId)) {
return id2ParameterBlock_Map_.find(parameterBlockId)->second;
}
return std::shared_ptr<const okvis::ceres::ParameterBlock>(); // NULL
}
// Get the residual blocks of a parameter block.
Map::ResidualBlockCollection Map::residuals(uint64_t parameterBlockId) const {
// get the residual blocks of a parameter block
Id2ResidualBlock_Multimap::const_iterator it1 = id2ResidualBlock_Multimap_
.find(parameterBlockId);
if (it1 == id2ResidualBlock_Multimap_.end())
return Map::ResidualBlockCollection(); // empty
ResidualBlockCollection returnResiduals;
std::pair<Id2ResidualBlock_Multimap::const_iterator,
Id2ResidualBlock_Multimap::const_iterator> range =
id2ResidualBlock_Multimap_.equal_range(parameterBlockId);
for (Id2ResidualBlock_Multimap::const_iterator it = range.first;
it != range.second; ++it) {
returnResiduals.push_back(it->second);
}
return returnResiduals;
}
// Get a shared pointer to an error term.
std::shared_ptr<okvis::ceres::ErrorInterface> Map::errorInterfacePtr(
::ceres::ResidualBlockId residualBlockId) { // get a vertex
ResidualBlockId2ResidualBlockSpec_Map::iterator it =
residualBlockId2ResidualBlockSpec_Map_.find(residualBlockId);
if (it == residualBlockId2ResidualBlockSpec_Map_.end()) {
return std::shared_ptr<okvis::ceres::ErrorInterface>(); // NULL
}
return it->second.errorInterfacePtr;
}
// Get a shared pointer to an error term.
std::shared_ptr<const okvis::ceres::ErrorInterface> Map::errorInterfacePtr(
::ceres::ResidualBlockId residualBlockId) const { // get a vertex
ResidualBlockId2ResidualBlockSpec_Map::const_iterator it =
residualBlockId2ResidualBlockSpec_Map_.find(residualBlockId);
if (it == residualBlockId2ResidualBlockSpec_Map_.end()) {
return std::shared_ptr<okvis::ceres::ErrorInterface>(); // NULL
}
return it->second.errorInterfacePtr;
}
// Get the parameters of a residual block.
Map::ParameterBlockCollection Map::parameters(
::ceres::ResidualBlockId residualBlockId) const { // get the parameter blocks connected
ResidualBlockId2ParameterBlockCollection_Map::const_iterator it =
residualBlockId2ParameterBlockCollection_Map_.find(residualBlockId);
if (it == residualBlockId2ParameterBlockCollection_Map_.end()) {
ParameterBlockCollection empty;
return empty; // empty vector
}
return it->second;
}
::ceres::LocalParameterization* Map::selectLocalParameterization(
const ::ceres::LocalParameterization* query) {
std::vector<::ceres::LocalParameterization*> pool{
&homogeneousPointLocalParameterization_, &poseLocalParameterization_,
&poseLocalParameterization3d_, &poseLocalParameterization4d_,
&poseLocalParameterization2d_};
for (::ceres::LocalParameterization* pointer : pool) {
if (query == pointer) {
return pointer;
}
}
LOG(WARNING) << "Local parameterization pointer not matched!";
return nullptr;
}
std::shared_ptr<ParameterBlock> Map::internalAddParameterBlockById(
uint64_t id, std::shared_ptr<::ceres::Problem> problem) {
std::shared_ptr<ParameterBlock> parameterBlock = id2ParameterBlock_Map_[id];
const ::ceres::LocalParameterization* parameterizationPtr =
parameterBlock->localParameterizationPtr();
std::shared_ptr<ParameterBlock> parameterBlockCopy;
switch (parameterBlock->dimension()) {
case 7:
parameterBlockCopy.reset(new PoseParameterBlock(
*std::static_pointer_cast<PoseParameterBlock>(parameterBlock)));
break;
case 4:
parameterBlockCopy.reset(new HomogeneousPointParameterBlock(
*std::static_pointer_cast<HomogeneousPointParameterBlock>(
parameterBlock)));
break;
case 9:
parameterBlockCopy.reset(new SpeedAndBiasParameterBlock(
*std::static_pointer_cast<SpeedAndBiasParameterBlock>(
parameterBlock)));
break;
default:
LOG(WARNING) << "Parameter block of dim " << parameterBlock->dimension()
<< " not recognized!";
break;
}
if (parameterizationPtr) {
problem->AddParameterBlock(
parameterBlockCopy->parameters(), parameterBlockCopy->dimension(),
selectLocalParameterization(parameterizationPtr));
} else {
problem->AddParameterBlock(parameterBlockCopy->parameters(),
parameterBlockCopy->dimension());
}
if (parameterBlock->fixed()) {
problem->SetParameterBlockConstant(parameterBlockCopy->parameters());
} // else pass as parameters are default to be variable.
return parameterBlockCopy;
}
std::shared_ptr<::ceres::Problem> Map::cloneProblem(
std::unordered_map<uint64_t, std::shared_ptr<okvis::ceres::ParameterBlock>>*
blockId2BlockCopyPtr) {
::ceres::Problem::Options problemOptions;
problemOptions.local_parameterization_ownership =
::ceres::Ownership::DO_NOT_TAKE_OWNERSHIP;
problemOptions.loss_function_ownership =
::ceres::Ownership::DO_NOT_TAKE_OWNERSHIP;
problemOptions.cost_function_ownership =
::ceres::Ownership::DO_NOT_TAKE_OWNERSHIP;
std::shared_ptr<::ceres::Problem> problem(
new ::ceres::Problem(problemOptions));
// add parameter blocks in the order of {constants}, {camera pose, speed and
// bias, extrinsics}, lastly {landmarks}.
std::vector<uint64_t> nonlmkIds;
nonlmkIds.reserve(20);
std::vector<uint64_t> constIds;
constIds.reserve(5);
std::vector<uint64_t> lmkIds;
lmkIds.reserve(id2ParameterBlock_Map_.size());
for (auto parameterBlockIdToPointer : id2ParameterBlock_Map_) {
std::shared_ptr<ParameterBlock> parameterBlock =
parameterBlockIdToPointer.second;
if (parameterBlock->dimension() == 4) {
lmkIds.push_back(parameterBlockIdToPointer.first);
} else {
if (parameterBlock->fixed()) {
constIds.push_back(parameterBlockIdToPointer.first);
} else {
nonlmkIds.push_back(parameterBlockIdToPointer.first);
}
}
}
for (auto id : constIds) {
std::shared_ptr<ParameterBlock> blockCopyPtr =
internalAddParameterBlockById(id, problem);
blockId2BlockCopyPtr->emplace(id, blockCopyPtr);
}
for (auto id : nonlmkIds) {
std::shared_ptr<ParameterBlock> blockCopyPtr =
internalAddParameterBlockById(id, problem);
blockId2BlockCopyPtr->emplace(id, blockCopyPtr);
}
for (auto id : lmkIds) {
std::shared_ptr<ParameterBlock> blockCopyPtr =
internalAddParameterBlockById(id, problem);
blockId2BlockCopyPtr->emplace(id, blockCopyPtr);
}
// add residual blocks.
for (auto residualIdToSpec : residualBlockId2ResidualBlockSpec_Map_) {
const ::ceres::ResidualBlockId& residualId = residualIdToSpec.first;
const ResidualBlockSpec& spec = residualIdToSpec.second;
std::shared_ptr<::ceres::CostFunction> costFunctionPtr =
std::dynamic_pointer_cast<::ceres::CostFunction>(
spec.errorInterfacePtr);
OKVIS_ASSERT_TRUE_DBG(Exception, costFunctionPtr != 0,
"An okvis::ceres::ErrorInterface not derived from "
"ceres::CostFunction!");
auto iter = residualBlockId2ParameterBlockCollection_Map_.find(residualId);
OKVIS_ASSERT_TRUE_DBG(
Exception, iter != residualBlockId2ParameterBlockCollection_Map_.end(),
"Parameter block connection not found for a residual block!");
const ParameterBlockCollection& collection = iter->second;
std::vector<double*> parameter_blocks;
parameter_blocks.reserve(collection.size());
for (const ParameterBlockSpec& blockSpec : collection) {
std::shared_ptr<ParameterBlock> blockCopyPtr = blockId2BlockCopyPtr->at(blockSpec.second->id());
parameter_blocks.push_back(blockCopyPtr->parameters());
}
problem->AddResidualBlock(costFunctionPtr.get(), spec.lossFunctionPtr,
parameter_blocks);
}
return problem;
}
void Map::printMapInfo() const {
std::stringstream ss;
ss << "Overall parameter global dim " << problem_->NumParameters()
<< ", overall residual dim " << problem_->NumResiduals();
std::vector<size_t> numberVariables(10, 0u);
std::vector<size_t> numberConstants(10, 0u);
for (auto iter = id2ParameterBlock_Map_.begin(); iter != id2ParameterBlock_Map_.end(); ++iter) {
size_t minDim = iter->second->minimalDimension();
bool fixed = iter->second->fixed();
if (fixed) {
numberConstants[minDim - 1]++;
} else {
numberVariables[minDim - 1]++;
}
}
std::vector<size_t> numberResiduals(20, 0u);
for (auto iter = residualBlockId2ResidualBlockSpec_Map_.begin();
iter != residualBlockId2ResidualBlockSpec_Map_.end(); ++iter) {
size_t resDim = iter->second.errorInterfacePtr->residualDim();
resDim = resDim + 1 > numberResiduals.size() ? numberResiduals.size() - 1
: resDim;
numberResiduals[resDim - 1]++;
}
ss << "\n#Constant parameter at each minimal dimension:";
int index = 1;
for (auto val : numberConstants) {
if (val) ss << " (" << index << ":" << val << ")";
++index;
}
ss << "\n#Variable parameter at each minimal dimension:";
index = 1;
for (auto val : numberVariables) {
if (val) ss << " (" << index << ":" << val << ")";
++index;
}
ss << "\n#Residual at each residual dimension:";
index = 1;
for (auto val : numberResiduals) {
if (val) ss << " (" << index << ":" << val << ")";
++index;
}
LOG(INFO) << ss.str();
}
bool Map::getParameterBlockMinimalCovariance(
uint64_t parameterBlockId, ::ceres::Problem* problem,
Eigen::Matrix<double, -1, -1, Eigen::RowMajor>* param_covariance,
::ceres::CovarianceAlgorithmType covAlgorithm) const {
if (!parameterBlockExists(parameterBlockId)) return false;
std::shared_ptr<ParameterBlock> parameterBlock =
id2ParameterBlock_Map_.find(parameterBlockId)->second;
::ceres::Covariance::Options covariance_options;
// covariance_options.sparse_linear_algebra_library_type = ::ceres::EIGEN_SPARSE;
covariance_options.algorithm_type = covAlgorithm;
covariance_options.num_threads = 1; // common::getNumHardwareThreads();
covariance_options.min_reciprocal_condition_number = 1e-32;
covariance_options.apply_loss_function = true;
::ceres::Covariance covariance(covariance_options);
std::vector<std::pair<const double*, const double*> > covariance_blocks;
covariance_blocks.push_back(std::make_pair(parameterBlock->parameters(),
parameterBlock->parameters()));
if (!covariance.Compute(covariance_blocks, problem)) {
return false;
}
size_t rows = parameterBlock->minimalDimension();
param_covariance->resize(rows, rows);
covariance.GetCovarianceBlockInTangentSpace(parameterBlock->parameters(),
parameterBlock->parameters(),
param_covariance->data());
return true;
}
bool Map::getParameterBlockMinimalCovariance(
const std::vector<uint64_t>& parameterBlockIdList,
::ceres::Problem* problem,
std::vector<Eigen::Matrix<double, -1, -1, Eigen::RowMajor>,
Eigen::aligned_allocator<
Eigen::Matrix<double, -1, -1, Eigen::RowMajor>>>*
covarianceBlockList,
::ceres::CovarianceAlgorithmType covAlgorithm) const {
for (uint64_t blockId : parameterBlockIdList) {
if (!parameterBlockExists(blockId)) {
return false;
}
}
::ceres::Covariance::Options covariance_options;
covariance_options.algorithm_type = covAlgorithm;
covariance_options.null_space_rank = -1;
covariance_options.num_threads = 1;
covariance_options.min_reciprocal_condition_number = 1e-32;
covariance_options.apply_loss_function = true;
::ceres::Covariance covariance(covariance_options);
std::vector<std::pair<const double*, const double*>> covariance_blocks;
for (std::vector<uint64_t>::const_iterator cit = parameterBlockIdList.begin();
cit != parameterBlockIdList.end(); ++cit) {
std::shared_ptr<ParameterBlock> blocki =
id2ParameterBlock_Map_.find(*cit)->second;
for (std::vector<uint64_t>::const_iterator icit = cit;
icit != parameterBlockIdList.end(); ++icit) {
std::shared_ptr<ParameterBlock> blockj =
id2ParameterBlock_Map_.find(*icit)->second;
covariance_blocks.push_back(
std::make_pair(blocki->parameters(), blockj->parameters()));
}
}
if (!covariance.Compute(covariance_blocks, problem)) {
printMapInfo();
return false;
}
covarianceBlockList->resize(parameterBlockIdList.size() *
(parameterBlockIdList.size() + 1) / 2);
size_t covBlockIndex = 0u;
for (std::vector<uint64_t>::const_iterator cit = parameterBlockIdList.begin();
cit != parameterBlockIdList.end(); ++cit) {
std::shared_ptr<ParameterBlock> blocki =
id2ParameterBlock_Map_.find(*cit)->second;
size_t rows = blocki->minimalDimension();
for (std::vector<uint64_t>::const_iterator icit = cit;
icit != parameterBlockIdList.end(); ++icit, ++covBlockIndex) {
std::shared_ptr<ParameterBlock> blockj =
id2ParameterBlock_Map_.find(*icit)->second;
size_t cols = blockj->minimalDimension();
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>
param_covariance(rows, cols);
covariance.GetCovarianceBlockInTangentSpace(
blocki->parameters(), blockj->parameters(), param_covariance.data());
covarianceBlockList->at(covBlockIndex) = param_covariance;
}
}
return true;
}
bool Map::computeNavStateCovariance(uint64_t poseId, uint64_t speedAndBiasId,
::ceres::ResidualBlockId marginalResidualId,
Eigen::MatrixXd* cov) {
ceres::MarginalizationError marginalizer(*this);
if (marginalResidualId) {
// Add the marginalization residual first so that variables have proper first estimates.
marginalizer.addResidualBlock(marginalResidualId, true);
}
Map::ResidualBlockCollection poseResiduals = residuals(poseId);
// Add a residual for the pose first to ensure that the pose precedes
// speed and biases in the covariance matrix.
const ::ceres::ResidualBlockId& priorityResidualId = poseResiduals.begin()->residualBlockId;
marginalizer.addResidualBlock(priorityResidualId, true);
for (auto residualIdToSpec : residualBlockId2ResidualBlockSpec_Map_) {
const ::ceres::ResidualBlockId& residualId = residualIdToSpec.first;
if (residualId == priorityResidualId || residualId == marginalResidualId) {
continue;
}
marginalizer.addResidualBlock(residualId, true);
}
std::set<uint64_t> paramBlockIdSet;
for (auto parameterBlockIdToPointer : id2ParameterBlock_Map_) {
if (parameterBlockIdToPointer.second->fixed()) {
continue;
}
// only use parameters that have at least one residual block.
if (id2ResidualBlock_Multimap_.count(parameterBlockIdToPointer.first))
paramBlockIdSet.insert(parameterBlockIdToPointer.first);
}
size_t foundPose = paramBlockIdSet.erase(poseId);
size_t foundSpeedAndBias = paramBlockIdSet.erase(speedAndBiasId);
OKVIS_ASSERT_EQ(Exception, foundPose + foundSpeedAndBias, 2u,
"Pose or SpeedAndBias not found in parameter block list!");
std::vector<uint64_t> allParamBlockIds(paramBlockIdSet.begin(),
paramBlockIdSet.end());
std::vector<bool> keepBlocks(allParamBlockIds.size(), true);
marginalizer.marginalizeOut(allParamBlockIds, keepBlocks);
OKVIS_ASSERT_EQ(Exception, marginalizer.H().rows(), 15,
"The only block left in H should has 15 rows!");
MatrixPseudoInverse::pseudoInverseSymm(marginalizer.H(), *cov);
return true;
}
} //namespace okvis
} //namespace ceres
| 41.624038 | 120 | 0.684562 | [
"vector"
] |
1b450d982e6c2e3ac8396f780949aa126e2fc03d | 597 | cpp | C++ | Physx.NetCore/Source/SphereGeometry.cpp | ronbrogan/Physx.NetCore | ac788494b6aefc4b6633c46e857f199e6ab0a47a | [
"MIT"
] | 187 | 2015-01-02T15:58:10.000Z | 2022-02-20T05:23:13.000Z | PhysX.Net-3.4/PhysX.Net-3/Source/SphereGeometry.cpp | Golangltd/PhysX.Net | fb71e0422d441a16a05ed51348d8afb0328d4b90 | [
"MIT"
] | 37 | 2015-01-10T04:38:23.000Z | 2022-03-18T00:52:27.000Z | PhysX.Net-3.4/PhysX.Net-3/Source/SphereGeometry.cpp | Golangltd/PhysX.Net | fb71e0422d441a16a05ed51348d8afb0328d4b90 | [
"MIT"
] | 63 | 2015-01-11T12:12:44.000Z | 2022-02-05T14:12:49.000Z | #include "StdAfx.h"
#include "SphereGeometry.h"
using namespace PhysX;
SphereGeometry::SphereGeometry()
: Geometry(GeometryType::Sphere)
{
this->Radius = 0;
}
SphereGeometry::SphereGeometry(float radius)
: Geometry(GeometryType::Sphere)
{
this->Radius = radius;
}
SphereGeometry::SphereGeometry(PxSphereGeometry geom)
: Geometry(GeometryType::Sphere)
{
this->Radius = geom.radius;
}
PxGeometry* SphereGeometry::ToUnmanaged()
{
return new PxSphereGeometry(this->Radius);
}
SphereGeometry^ SphereGeometry::ToManaged(PxSphereGeometry sphere)
{
return gcnew SphereGeometry(sphere.radius);
} | 20.586207 | 66 | 0.772194 | [
"geometry"
] |
1b49d78422de113a9d5757478f09be4278282244 | 5,971 | cpp | C++ | libs/mesh/src/meshCubatureNodesHex3D.cpp | MalachiTimothyPhillips/libparanumal | f3fd4505df56207b05aa86164124ab6bad83f92a | [
"MIT"
] | null | null | null | libs/mesh/src/meshCubatureNodesHex3D.cpp | MalachiTimothyPhillips/libparanumal | f3fd4505df56207b05aa86164124ab6bad83f92a | [
"MIT"
] | null | null | null | libs/mesh/src/meshCubatureNodesHex3D.cpp | MalachiTimothyPhillips/libparanumal | f3fd4505df56207b05aa86164124ab6bad83f92a | [
"MIT"
] | null | null | null | /*
The MIT License (MIT)
Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus
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 "mesh.hpp"
#include "mesh3D.hpp"
void meshHex3D::CubatureNodes(){
cubx = (dfloat*) calloc(Nelements*cubNp,sizeof(dfloat));
cuby = (dfloat*) calloc(Nelements*cubNp,sizeof(dfloat));
cubz = (dfloat*) calloc(Nelements*cubNp,sizeof(dfloat));
//temp arrays
dfloat *Ix1 = (dfloat*) calloc(Nq*Nq*cubNq, sizeof(dfloat));
dfloat *Iy1 = (dfloat*) calloc(Nq*Nq*cubNq, sizeof(dfloat));
dfloat *Iz1 = (dfloat*) calloc(Nq*Nq*cubNq, sizeof(dfloat));
dfloat *Ix2 = (dfloat*) calloc(Nq*cubNq*cubNq, sizeof(dfloat));
dfloat *Iy2 = (dfloat*) calloc(Nq*cubNq*cubNq, sizeof(dfloat));
dfloat *Iz2 = (dfloat*) calloc(Nq*cubNq*cubNq, sizeof(dfloat));
for(dlong e=0;e<Nelements;++e){ /* for each element */
dfloat *xe = x + e*Np;
dfloat *ye = y + e*Np;
dfloat *ze = z + e*Np;
dfloat *cubxe = cubx + e*cubNp;
dfloat *cubye = cuby + e*cubNp;
dfloat *cubze = cubz + e*cubNp;
//interpolate physical coordinates to cubature
for(int k=0;k<Nq;++k){
for(int j=0;j<Nq;++j){
for(int i=0;i<cubNq;++i){
Ix1[k*Nq*cubNq+j*cubNq+i] = 0;
Iy1[k*Nq*cubNq+j*cubNq+i] = 0;
Iz1[k*Nq*cubNq+j*cubNq+i] = 0;
for(int n=0;n<Nq;++n){
Ix1[k*Nq*cubNq+j*cubNq+i] += cubInterp[i*Nq + n]*xe[k*Nq*Nq+j*Nq+n];
Iy1[k*Nq*cubNq+j*cubNq+i] += cubInterp[i*Nq + n]*ye[k*Nq*Nq+j*Nq+n];
Iz1[k*Nq*cubNq+j*cubNq+i] += cubInterp[i*Nq + n]*ze[k*Nq*Nq+j*Nq+n];
}
}
}
}
for(int k=0;k<Nq;++k){
for(int j=0;j<cubNq;++j){
for(int i=0;i<cubNq;++i){
Ix2[k*cubNq*cubNq+j*cubNq+i] = 0;
Iy2[k*cubNq*cubNq+j*cubNq+i] = 0;
Iz2[k*cubNq*cubNq+j*cubNq+i] = 0;
for(int n=0;n<Nq;++n){
Ix2[k*cubNq*cubNq+j*cubNq+i] += cubInterp[j*Nq + n]*Ix1[k*Nq*cubNq+n*cubNq+i];
Iy2[k*cubNq*cubNq+j*cubNq+i] += cubInterp[j*Nq + n]*Iy1[k*Nq*cubNq+n*cubNq+i];
Iz2[k*cubNq*cubNq+j*cubNq+i] += cubInterp[j*Nq + n]*Iz1[k*Nq*cubNq+n*cubNq+i];
}
}
}
}
for(int k=0;k<cubNq;++k){
for(int j=0;j<cubNq;++j){
for(int i=0;i<cubNq;++i){
cubxe[k*cubNq*cubNq+j*cubNq+i] = 0;
cubye[k*cubNq*cubNq+j*cubNq+i] = 0;
cubze[k*cubNq*cubNq+j*cubNq+i] = 0;
for(int n=0;n<Nq;++n){
cubxe[k*cubNq*cubNq+j*cubNq+i] += cubInterp[k*Nq + n]*Ix2[n*cubNq*cubNq+j*cubNq+i];
cubye[k*cubNq*cubNq+j*cubNq+i] += cubInterp[k*Nq + n]*Iy2[n*cubNq*cubNq+j*cubNq+i];
cubze[k*cubNq*cubNq+j*cubNq+i] += cubInterp[k*Nq + n]*Iz2[n*cubNq*cubNq+j*cubNq+i];
}
}
}
}
}
free(Ix1); free(Iy1); free(Iz1);
free(Ix2); free(Iy2); free(Iz2);
o_cubx = device.malloc(Nelements*cubNp*sizeof(dfloat), cubx);
o_cuby = device.malloc(Nelements*cubNp*sizeof(dfloat), cuby);
o_cubz = device.malloc(Nelements*cubNp*sizeof(dfloat), cubz);
//Face cubature
intx = (dfloat*) calloc(Nelements*Nfaces*cubNfp, sizeof(dfloat));
inty = (dfloat*) calloc(Nelements*Nfaces*cubNfp, sizeof(dfloat));
intz = (dfloat*) calloc(Nelements*Nfaces*cubNfp, sizeof(dfloat));
dfloat *ix = (dfloat *) calloc(cubNq*Nq,sizeof(dfloat));
dfloat *iy = (dfloat *) calloc(cubNq*Nq,sizeof(dfloat));
dfloat *iz = (dfloat *) calloc(cubNq*Nq,sizeof(dfloat));
for(dlong e=0;e<Nelements;++e){
for(int f=0;f<Nfaces;++f){
//interpolate in i
for(int ny=0;ny<Nq;++ny){
for(int nx=0;nx<cubNq;++nx){
ix[nx+cubNq*ny] = 0;
iy[nx+cubNq*ny] = 0;
iz[nx+cubNq*ny] = 0;
for(int m=0;m<Nq;++m){
dlong vid = m+ny*Nq+f*Nfp+e*Nfp*Nfaces;
dlong idM = vmapM[vid];
dfloat xm = x[idM];
dfloat ym = y[idM];
dfloat zm = z[idM];
dfloat Inm = cubInterp[m+nx*Nq];
ix[nx+cubNq*ny] += Inm*xm;
iy[nx+cubNq*ny] += Inm*ym;
iz[nx+cubNq*ny] += Inm*zm;
}
}
}
//interpolate in j and store
for(int ny=0;ny<cubNq;++ny){
for(int nx=0;nx<cubNq;++nx){
dfloat xn=0.0, yn=0.0, zn=0.0;
for(int m=0;m<Nq;++m){
dfloat xm = ix[nx + m*cubNq];
dfloat ym = iy[nx + m*cubNq];
dfloat zm = iz[nx + m*cubNq];
dfloat Inm = cubInterp[m+ny*Nq];
xn += Inm*xm;
yn += Inm*ym;
zn += Inm*zm;
}
dlong id = nx + ny*cubNq + f*cubNfp + e*Nfaces*cubNfp;
intx[id] = xn;
inty[id] = yn;
intz[id] = zn;
}
}
}
}
free(ix); free(iy); free(iz);
o_intx = device.malloc(Nelements*Nfaces*cubNfp*sizeof(dfloat), intx);
o_inty = device.malloc(Nelements*Nfaces*cubNfp*sizeof(dfloat), inty);
o_intz = device.malloc(Nelements*Nfaces*cubNfp*sizeof(dfloat), intz);
}
| 34.918129 | 95 | 0.587674 | [
"mesh"
] |
1b52af74c0cfd284a666e042582716469b6fa0ac | 6,844 | cpp | C++ | weex_core/Source/android/jsengine/bridge/script/script_bridge_in_multi_so.cpp | Blankdlh/incubator-weex | 8bcd48dff97046e444f5cd4dff34baad6a4b0850 | [
"Apache-2.0"
] | 1 | 2019-08-07T14:59:20.000Z | 2019-08-07T14:59:20.000Z | weex_core/Source/android/jsengine/bridge/script/script_bridge_in_multi_so.cpp | Blankdlh/incubator-weex | 8bcd48dff97046e444f5cd4dff34baad6a4b0850 | [
"Apache-2.0"
] | 12 | 2019-07-09T05:55:28.000Z | 2019-07-31T01:12:28.000Z | weex_core/Source/android/jsengine/bridge/script/script_bridge_in_multi_so.cpp | wrmswindmill/incubator-weex | 4fbb51e8162940c342101aebaa28ad7ab01d35db | [
"Apache-2.0"
] | 1 | 2019-08-09T05:17:42.000Z | 2019-08-09T05:17:42.000Z | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
//
// Created by yxp on 2018/6/15.
//
#include "android/jsengine/bridge/script/script_bridge_in_multi_so.h"
#include "android/jsengine/bridge/platform/platform_bridge_in_multi_so.h"
#include "android/jsengine/bridge/script/core_side_in_multi_process.h"
#include "android/jsengine/bridge/script/core_side_in_multi_so.h"
#include "android/jsengine/bridge/script/core_side_in_simple.h"
#include "android/jsengine/bridge/script/script_side_in_simple.h"
#include "android/jsengine/bridge/script/script_side_in_queue.h"
#include "android/jsengine/object/weex_env.h"
#include "android/jsengine/weex_runtime.h"
#include "core/manager/weex_core_manager.h"
static FunctionsExposedByCore *g_functions_exposed_by_core = nullptr;
extern "C" FunctionsExposedByJS *ExchangeJSBridgeFunctions(
FunctionsExposedByCore *functions) {
g_functions_exposed_by_core = functions;
return weex::bridge::js::ScriptBridgeInMultiSo::GetExposedFunctions();
}
namespace weex {
namespace bridge {
namespace js {
ScriptBridgeInMultiSo *ScriptBridgeInMultiSo::g_instance = NULL;
ScriptBridgeInMultiSo::ScriptBridgeInMultiSo() {
set_script_side(new ScriptSideInQueue());
// set_core_side(new CoreSideInSimple());
set_core_side(new CoreSideInMultiSo(g_functions_exposed_by_core));
// set_core_side(new MultiProcessCoreSide());
}
ScriptBridgeInMultiSo::~ScriptBridgeInMultiSo() {}
FunctionsExposedByJS *ScriptBridgeInMultiSo::GetExposedFunctions() {
FunctionsExposedByJS temp = {
InitFramework, InitAppFramework, CreateAppContext,
ExecJSOnAppWithResult, CallJSOnAppContext, DestroyAppContext,
ExecJSService, ExecTimeCallback, ExecJS,
ExecJSWithResult, ExecJSWithCallback, CreateInstance, ExecJSOnInstance,
DestroyInstance, UpdateGlobalConfig, UpdateInitFrameworkParams};
auto functions = (FunctionsExposedByJS *)malloc(sizeof(FunctionsExposedByJS));
memset(functions, 0, sizeof(FunctionsExposedByJS));
memcpy(functions, &temp, sizeof(FunctionsExposedByJS));
return functions;
}
int ScriptBridgeInMultiSo::InitFramework(
const char *script, std::vector<INIT_FRAMEWORK_PARAMS *> ¶ms) {
static_cast<ScriptSideInQueue *>(Instance()->script_side())
->setTaskQueue(new WeexTaskQueue(false));
WeexEnv::getEnv()->setScriptBridge(Instance());
return Instance()->script_side()->InitFramework(script, params);
}
int ScriptBridgeInMultiSo::InitAppFramework(
const char *instanceId, const char *appFramework,
std::vector<INIT_FRAMEWORK_PARAMS *> ¶ms) {
return Instance()->script_side()->InitAppFramework(instanceId, appFramework,
params);
}
int ScriptBridgeInMultiSo::CreateAppContext(const char *instanceId,
const char *jsBundle) {
return Instance()->script_side()->CreateAppContext(instanceId, jsBundle);
}
std::unique_ptr<WeexJSResult> ScriptBridgeInMultiSo::ExecJSOnAppWithResult(const char *instanceId,
const char *jsBundle) {
return Instance()->script_side()->ExecJSOnAppWithResult(instanceId, jsBundle);
}
int ScriptBridgeInMultiSo::CallJSOnAppContext(
const char *instanceId, const char *func,
std::vector<VALUE_WITH_TYPE *> ¶ms) {
return Instance()->script_side()->CallJSOnAppContext(instanceId, func, params);
}
int ScriptBridgeInMultiSo::DestroyAppContext(const char *instanceId) {
return Instance()->script_side()->DestroyAppContext(instanceId);
}
int ScriptBridgeInMultiSo::ExecJSService(const char *source) {
return Instance()->script_side()->ExecJsService(source);
}
int ScriptBridgeInMultiSo::ExecTimeCallback(const char *source) {
return Instance()->script_side()->ExecTimeCallback(source);
}
int ScriptBridgeInMultiSo::ExecJS(const char *instanceId, const char *nameSpace,
const char *func,
std::vector<VALUE_WITH_TYPE *> ¶ms) {
return Instance()->script_side()->ExecJS(instanceId, nameSpace, func, params);
}
std::unique_ptr<WeexJSResult> ScriptBridgeInMultiSo::ExecJSWithResult(
const char *instanceId, const char *nameSpace, const char *func,
std::vector<VALUE_WITH_TYPE *> ¶ms) {
return Instance()->script_side()->ExecJSWithResult(instanceId, nameSpace, func,
params);
}
void ScriptBridgeInMultiSo::ExecJSWithCallback(
const char *instanceId, const char *nameSpace, const char *func,
std::vector<VALUE_WITH_TYPE *> ¶ms, long callback_id) {
Instance()->script_side()->ExecJSWithCallback(instanceId, nameSpace, func, params, callback_id);
}
int ScriptBridgeInMultiSo::CreateInstance(const char *instanceId,
const char *func, const char *script,
const char *opts,
const char *initData,
const char *extendsApi, std::vector<INIT_FRAMEWORK_PARAMS*>& params) {
return Instance()->script_side()->CreateInstance(instanceId, func, script, opts,
initData, extendsApi, params);
}
std::unique_ptr<WeexJSResult> ScriptBridgeInMultiSo::ExecJSOnInstance(const char *instanceId,
const char *script,int type) {
return Instance()->script_side()->ExecJSOnInstance(instanceId, script,type);
}
int ScriptBridgeInMultiSo::DestroyInstance(const char *instanceId) {
return Instance()->script_side()->DestroyInstance(instanceId);
}
int ScriptBridgeInMultiSo::UpdateGlobalConfig(const char *config) {
return Instance()->script_side()->UpdateGlobalConfig(config);
}
int ScriptBridgeInMultiSo::UpdateInitFrameworkParams(const std::string& key, const std::string& value, const std::string& desc){
return Instance()->script_side()->UpdateInitFrameworkParams(key, value, desc);
}
} // namespace js
} // namespace bridge
} // namespace weex
| 41.731707 | 128 | 0.71391 | [
"object",
"vector"
] |
1b5539c8e9033060e547a6881a3cfac6ddbbfd24 | 1,935 | hpp | C++ | samples/qt/photo-book/face_rectangles.hpp | intel/umf | 3103e3b0ab63a0f60f4d8d83ebf4dc39a61552aa | [
"Apache-2.0"
] | 13 | 2018-01-23T22:05:21.000Z | 2020-04-21T15:19:29.000Z | samples/qt/photo-book/face_rectangles.hpp | intel/umf | 3103e3b0ab63a0f60f4d8d83ebf4dc39a61552aa | [
"Apache-2.0"
] | 10 | 2015-08-25T22:20:23.000Z | 2016-06-08T10:13:26.000Z | samples/qt/photo-book/face_rectangles.hpp | 01org/vmf | 3103e3b0ab63a0f60f4d8d83ebf4dc39a61552aa | [
"Apache-2.0"
] | 10 | 2015-11-16T14:19:31.000Z | 2016-08-18T21:44:07.000Z | // Copyright (C) 2013, Intel Corporation, all rights reserved.
#ifndef __FACE_RECTANGLES_H__
#define __FACE_RECTANGLES_H__
#include <QGraphicsRectItem>
#include <QPen>
#include <vector>
#include "corner_grabber.hpp"
#include "photo_book.hpp"
class FaceRectBase : public QGraphicsRectItem
{
public:
FaceRectBase(const FaceRect& r,
QGraphicsItem * parent = 0);
virtual int type() const;
void setMoveArea(const QRectF& ma);
FaceRect getModelRect();
static const int MIN_REGION_WIDTH;
static const int MIN_REGION_HEIGHT;
protected:
void mouseMoveEvent(QGraphicsSceneMouseEvent *me);
void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event);
bool sceneEventFilter(QGraphicsItem* watched, QEvent* me);
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
private:
void setCornerPositions();
bool processResize(CornerGrabber* corner, QGraphicsSceneMouseEvent* mevent);
void notifyResize();
bool processSceneEvent(QGraphicsItem* watched, QEvent* me);
private:
std::vector<CornerGrabber*> rectCorners;
qreal mouseDownX;
qreal mouseDownY;
bool boldPen;
QRectF moveArea;
FaceRect modelRect;
};
class UnAssociatedFaceRect : public FaceRectBase
{
private:
enum ContextMenuActions
{
deleteRegionAction
};
public:
UnAssociatedFaceRect(const FaceRect& r,
QGraphicsItem * parent = 0);
protected:
void contextMenuEvent(QGraphicsSceneContextMenuEvent *me);
};
class AssociatedFaceRect : public FaceRectBase
{
private:
enum ContextMenuActions
{
deleteRegionAction,
removeAssociationAction
};
public:
AssociatedFaceRect(const FaceRect& r,
QGraphicsItem * parent = 0);
protected:
void contextMenuEvent(QGraphicsSceneContextMenuEvent *me);
};
#endif /* __FACE_RECTANGLES_H__ */
| 23.035714 | 91 | 0.734367 | [
"vector"
] |
1b59993568080796e3b2b424f914fd75f092167f | 4,224 | cc | C++ | src/rendering/ContactVisual.cc | nherment/gazebo | fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2016-01-17T20:41:39.000Z | 2018-05-01T12:02:58.000Z | src/rendering/ContactVisual.cc | nherment/gazebo | fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/rendering/ContactVisual.cc | nherment/gazebo | fff0aa30b4b5748e43c2b0aa54ffcd366e9f042a | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2015-09-29T02:30:16.000Z | 2022-03-30T12:11:22.000Z | /*
* Copyright 2011 Nate Koenig & Andrew Howard
*
* 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.
*
*/
/* Desc: Contact Visualization Class
* Author: Nate Koenig
*/
#include "rendering/ogre.h"
#include "common/MeshManager.hh"
#include "transport/Node.hh"
#include "transport/Subscriber.hh"
#include "msgs/msgs.h"
#include "rendering/Conversions.hh"
#include "rendering/Scene.hh"
#include "rendering/DynamicLines.hh"
#include "rendering/ContactVisual.hh"
using namespace gazebo;
using namespace rendering;
/////////////////////////////////////////////////
ContactVisual::ContactVisual(const std::string &_name, VisualPtr _vis,
const std::string &_topicName)
: Visual(_name, _vis)
{
this->node = transport::NodePtr(new transport::Node());
this->node->Init(this->scene->GetName());
this->contactsSub = this->node->Subscribe(_topicName,
&ContactVisual::OnContact, this);
common::MeshManager::Instance()->CreateSphere("contact_sphere", 0.05, 10, 10);
// Add the mesh into OGRE
if (!this->sceneNode->getCreator()->hasEntity("contact_sphere") &&
common::MeshManager::Instance()->HasMesh("contact_sphere"))
{
const common::Mesh *mesh =
common::MeshManager::Instance()->GetMesh("contact_sphere");
this->InsertMesh(mesh);
}
for (unsigned int i = 0; i < 10; i++)
{
std::string objName = this->GetName() +
"_contactpoint_" + boost::lexical_cast<std::string>(i);
Ogre::Entity *obj = this->scene->GetManager()->createEntity(
objName, "contact_sphere");
obj->setMaterialName("Gazebo/BlueLaser");
ContactVisual::ContactPoint *cp = new ContactVisual::ContactPoint();
cp->sceneNode = this->sceneNode->createChildSceneNode(objName + "_node");
cp->sceneNode->attachObject(obj);
cp->normal = new DynamicLines(RENDERING_LINE_LIST);
cp->depth = new DynamicLines(RENDERING_LINE_LIST);
cp->normal->AddPoint(math::Vector3(0, 0, 0));
cp->normal->AddPoint(math::Vector3(0, 0, 0.1));
cp->depth->AddPoint(math::Vector3(0, 0, 0));
cp->depth->AddPoint(math::Vector3(0, 0, -1));
cp->sceneNode->attachObject(cp->depth);
cp->sceneNode->attachObject(cp->normal);
cp->sceneNode->setVisible(false);
this->points.push_back(cp);
}
this->connections.push_back(
event::Events::ConnectPreRender(
boost::bind(&ContactVisual::Update, this)));
}
/////////////////////////////////////////////////
ContactVisual::~ContactVisual()
{
}
/////////////////////////////////////////////////
void ContactVisual::Update()
{
int c = 0;
if (!this->contactsMsg)
return;
for (int i = 0; i < this->contactsMsg->contact_size(); i++)
{
for (int j = 0;
c < 10 && j < this->contactsMsg->contact(i).position_size(); j++)
{
math::Vector3 pos = msgs::Convert(
this->contactsMsg->contact(i).position(j));
math::Vector3 normal = msgs::Convert(
this->contactsMsg->contact(i).normal(j));
double depth = this->contactsMsg->contact(i).depth(j);
this->points[c]->sceneNode->setVisible(true);
this->points[c]->sceneNode->setPosition(Conversions::Convert(pos));
this->points[c]->normal->SetPoint(1, normal*0.1);
this->points[c]->depth->SetPoint(1, normal*-depth*10);
this->points[c]->normal->setMaterial("Gazebo/LightOn");
this->points[c]->depth->setMaterial("Gazebo/LightOff");
this->points[c]->depth->Update();
this->points[c]->normal->Update();
c++;
}
}
for ( ; c < 10; c++)
this->points[c]->sceneNode->setVisible(false);
}
/////////////////////////////////////////////////
void ContactVisual::OnContact(ConstContactsPtr &_msg)
{
this->contactsMsg = _msg;
}
| 31.288889 | 80 | 0.633996 | [
"mesh"
] |
1b5db2a64206f0fc1b15baba01b55e0d36e82876 | 4,449 | cpp | C++ | openstudiocore/src/openstudio_app/test/Resources_GTest.cpp | Acidburn0zzz/OpenStudio | 8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd | [
"MIT"
] | null | null | null | openstudiocore/src/openstudio_app/test/Resources_GTest.cpp | Acidburn0zzz/OpenStudio | 8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd | [
"MIT"
] | null | null | null | openstudiocore/src/openstudio_app/test/Resources_GTest.cpp | Acidburn0zzz/OpenStudio | 8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd | [
"MIT"
] | null | null | null | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 <gtest/gtest.h>
#include "OpenStudioAppFixture.hpp"
#include "../../osversion/VersionTranslator.hpp"
#include "../../model/Model.hpp"
#include "../../model/SpaceLoad.hpp"
#include "../../model/SpaceLoad_Impl.hpp"
#include "../../model/SpaceType.hpp"
#include "../../utilities/core/ApplicationPathHelpers.hpp"
#include "../../utilities/core/PathHelpers.hpp"
#include <QDir>
#include <QFileInfo>
using namespace openstudio;
TEST_F(OpenStudioAppFixture, Resources_Templates)
{
openstudio::path resourcesPath = getApplicationSourceDirectory() / openstudio::toPath("src/openstudio_app/Resources");
ASSERT_TRUE(openstudio::filesystem::exists(resourcesPath));
ASSERT_FALSE(isEmptyDirectory(resourcesPath));
QDir resourcesDir(toQString(resourcesPath));
QStringList filters;
filters << QString("*.osm");
QFileInfoList files = resourcesDir.entryInfoList(filters, QDir::Files, QDir::NoSort);
EXPECT_FALSE(files.empty());
for (const QFileInfo& file : files) {
openstudio::path path = toPath(file.absoluteFilePath());
EXPECT_TRUE(openstudio::filesystem::exists(path));
osversion::VersionTranslator vt;
boost::optional<model::Model> model = vt.loadModel(path);
ASSERT_TRUE(model);
// check that each space load has a parent space type
std::vector<model::SpaceLoad> spaceLoads;
for (const model::SpaceLoad& spaceLoad : spaceLoads){
EXPECT_TRUE(spaceLoad.spaceType());
}
// uncomment this to save the version translated file to the original path
// DO NOT leave this in the test execution when you commit!
//model->save(path, true);
}
}
TEST_F(OpenStudioAppFixture, Resources_HVACLibrary)
{
openstudio::path hvacPath = getApplicationSourceDirectory() / openstudio::toPath("src/openstudio_app/Resources/default/hvac_library.osm");
ASSERT_TRUE(openstudio::filesystem::exists(hvacPath));
osversion::VersionTranslator vt;
boost::optional<model::Model> model = vt.loadModel(hvacPath);
ASSERT_TRUE(model);
// uncomment this to save the version translated file to the original path
// DO NOT leave this in the test execution when you commit!
//model->save(hvacPath, true);
}
| 46.831579 | 140 | 0.717465 | [
"vector",
"model"
] |
1b6fe90765fccb2085a4a65b8a29578c91a466b9 | 377 | cpp | C++ | HackerRank/Challenges/simple-array-sum.cpp | Diggzinc/solutions-spoj | eb552311011e466039e059cce07894fea0817613 | [
"MIT"
] | null | null | null | HackerRank/Challenges/simple-array-sum.cpp | Diggzinc/solutions-spoj | eb552311011e466039e059cce07894fea0817613 | [
"MIT"
] | null | null | null | HackerRank/Challenges/simple-array-sum.cpp | Diggzinc/solutions-spoj | eb552311011e466039e059cce07894fea0817613 | [
"MIT"
] | null | null | null | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int nCases, nCase, sum = 0;
cin >> nCases;
do{
cin >> nCase;
sum += nCase;
}while(--nCases);
cout << sum << endl;
return 0;
}
| 18.85 | 80 | 0.586207 | [
"vector"
] |
1b74338a247bcc32f1f8304b718f7ce87f01fd1c | 3,314 | hxx | C++ | generated/include/vnl/TcpUplinkSupport.hxx | madMAx43v3r/virtual-network-layers-cpp | cd0306b7edb38d5f43fa4fac198562ff38f4276a | [
"MIT"
] | 3 | 2021-06-12T21:26:47.000Z | 2021-09-11T04:06:04.000Z | generated/include/vnl/TcpUplinkSupport.hxx | madMAx43v3r/virtual-network-layers-cpp | cd0306b7edb38d5f43fa4fac198562ff38f4276a | [
"MIT"
] | 30 | 2016-08-17T02:16:56.000Z | 2017-06-30T04:57:50.000Z | generated/include/vnl/TcpUplinkSupport.hxx | madMAx43v3r/virtual-network-tools | 6fd7a5630ead319f6db07856c1164f7c8c09377c | [
"MIT"
] | null | null | null |
#ifndef INCLUDE_VNI_GENERATED_vnl_TcpUplinkBase_HXX_
#define INCLUDE_VNI_GENERATED_vnl_TcpUplinkBase_HXX_
// AUTO GENERATED by virtual-network-interface codegen
#include <vnl/Address.h>
#include <vnl/Object.h>
#include <vnl/String.h>
#include <vnl/Topic.hxx>
#include <vnl/info/RemoteInfo.hxx>
#include <vnl/Type.hxx>
namespace vnl {
class TcpUplinkBase : public vnl::Object {
public:
static const uint32_t VNI_HASH = 0xb681b3d8;
static const uint32_t NUM_FIELDS = 10;
typedef vnl::Object Super;
int32_t error_interval;
bool are_connected;
int64_t num_read;
int64_t num_write;
int64_t num_flush;
int64_t num_bytes_read;
int64_t num_bytes_write;
TcpUplinkBase(const vnl::String& domain_, const vnl::String& topic_);
virtual uint32_t get_vni_hash() const { return VNI_HASH; }
virtual const char* get_type_name() const { return "vnl.TcpUplink"; }
virtual int get_num_fields() const { return NUM_FIELDS; }
virtual int get_field_index(vnl::Hash32 _hash) const;
virtual const char* get_field_name(int _index) const;
virtual void get_field(int _index, vnl::String& _str) const;
virtual void set_field(int _index, const vnl::String& _str);
virtual void get_field(int _index, vnl::io::TypeOutput& _out) const;
virtual void set_field(int _index, vnl::io::TypeInput& _in);
virtual void get_field(int _index, vnl::Var& _var) const;
virtual void set_field(int _index, const vnl::Var& _var);
protected:
virtual void publish(const vnl::Address& addr) = 0;
virtual void handle(const vnl::info::RemoteInfo& sample, const vnl::Packet& packet) { handle(sample); }
virtual void handle(const vnl::info::RemoteInfo& sample, vnl::Basic* input) { handle(sample); }
virtual void handle(const vnl::info::RemoteInfo& sample) {}
virtual void unsubscribe(const vnl::String& domain, const vnl::String& topic) = 0;
virtual void handle(const vnl::Topic& sample, const vnl::Packet& packet) { handle(sample); }
virtual void handle(const vnl::Topic& sample, vnl::Basic* input) { handle(sample); }
virtual void handle(const vnl::Topic& sample) {}
virtual void subscribe(const vnl::String& domain, const vnl::String& topic) = 0;
virtual void reset() = 0;
virtual void publish(const vnl::String& domain, const vnl::String& topic) = 0;
virtual vnl::info::RemoteInfo get_remote_info() const = 0;
virtual void unpublish(const vnl::String& domain, const vnl::String& topic) = 0;
virtual bool vni_call(vnl::io::TypeInput& _in, uint32_t _hash, int _num_args);
virtual bool vni_const_call(vnl::io::TypeInput& _in, uint32_t _hash, int _num_args, vnl::io::TypeOutput& _out);
virtual bool handle_switch(vnl::Value* _sample, vnl::Packet* _packet);
virtual bool handle_switch(vnl::Value* _sample, vnl::Basic* _input);
template<class W>
void write_fields(W& _writer) const {
_writer.set_vnl_log_level(vnl_log_level);
_writer.set_vnl_msg_timeout(vnl_msg_timeout);
_writer.set_vnl_heartbeat_interval(vnl_heartbeat_interval);
_writer.set_error_interval(error_interval);
_writer.set_are_connected(are_connected);
_writer.set_num_read(num_read);
_writer.set_num_write(num_write);
_writer.set_num_flush(num_flush);
_writer.set_num_bytes_read(num_bytes_read);
_writer.set_num_bytes_write(num_bytes_write);
}
};
} // namespace
#endif // INCLUDE_VNI_GENERATED_vnl_TcpUplinkBase_HXX_
| 37.659091 | 112 | 0.763126 | [
"object"
] |
1b777adf2efae82e5b51073ea314354c74b08749 | 1,887 | hpp | C++ | tizen/MapsWithMe/inc/TouchProcessor.hpp | bowlofstew/omim | 8045157c95244aa8f862d47324df42a19b87e335 | [
"Apache-2.0"
] | 2 | 2019-01-24T15:36:20.000Z | 2019-12-26T10:03:48.000Z | tizen/MapsWithMe/inc/TouchProcessor.hpp | bowlofstew/omim | 8045157c95244aa8f862d47324df42a19b87e335 | [
"Apache-2.0"
] | 13 | 2015-09-28T13:59:23.000Z | 2015-10-08T20:12:45.000Z | tizen/MapsWithMe/inc/TouchProcessor.hpp | bowlofstew/omim | 8045157c95244aa8f862d47324df42a19b87e335 | [
"Apache-2.0"
] | 1 | 2019-08-09T21:31:29.000Z | 2019-08-09T21:31:29.000Z | #pragma once
#include <FUiITouchEventListener.h>
#include "../../../std/utility.hpp"
#include "../../../std/vector.hpp"
#include "../../../map/user_mark.hpp"
class MapsWithMeForm;
class TouchProcessor: public Tizen::Ui::ITouchEventListener
, public Tizen::Base::Runtime::ITimerEventListener
{
public:
TouchProcessor(MapsWithMeForm * pForm);
// ITouchEventListener
virtual void OnTouchFocusIn (Tizen::Ui::Control const & source,
Tizen::Graphics::Point const & currentPosition,
Tizen::Ui::TouchEventInfo const & touchInfo){}
virtual void OnTouchFocusOut (Tizen::Ui::Control const & source,
Tizen::Graphics::Point const & currentPosition,
Tizen::Ui::TouchEventInfo const & touchInfo){}
virtual void OnTouchMoved (Tizen::Ui::Control const & source,
Tizen::Graphics::Point const & currentPosition,
Tizen::Ui::TouchEventInfo const & touchInfo);
virtual void OnTouchPressed (Tizen::Ui::Control const & source,
Tizen::Graphics::Point const & currentPosition,
Tizen::Ui::TouchEventInfo const & touchInfo);
virtual void OnTouchReleased (Tizen::Ui::Control const & source,
Tizen::Graphics::Point const & currentPosition,
Tizen::Ui::TouchEventInfo const & touchInfo);
virtual void OnTouchLongPressed(Tizen::Ui::Control const & source,
Tizen::Graphics::Point const & currentPosition,
Tizen::Ui::TouchEventInfo const & touchInfo);
// ITimerEventListener
virtual void OnTimerExpired (Tizen::Base::Runtime::Timer & timer);
typedef vector<m2::PointD> TPointPairs;
private:
void StartMove(TPointPairs const & pts);
enum EState
{
ST_WAIT_TIMER,
ST_MOVING,
ST_ROTATING,
ST_EMPTY
};
EState m_state;
MapsWithMeForm * m_pForm;
bool m_wasLongPress;
bool m_bWasReleased;
m2::PointD m_startTouchPoint;
TPointPairs m_prev_pts;
Tizen::Base::Runtime::Timer m_timer;
};
| 32.534483 | 69 | 0.714361 | [
"vector"
] |
1b7b0ddbdd90a1f210fce8e6802b26d90b4a4fe4 | 1,162 | cc | C++ | content/browser/ssl_private_key_impl.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | content/browser/ssl_private_key_impl.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | content/browser/ssl_private_key_impl.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/ssl_private_key_impl.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/callback_helpers.h"
namespace content {
SSLPrivateKeyImpl::SSLPrivateKeyImpl(
scoped_refptr<net::SSLPrivateKey> ssl_private_key)
: ssl_private_key_(std::move(ssl_private_key)) {}
SSLPrivateKeyImpl::~SSLPrivateKeyImpl() = default;
void SSLPrivateKeyImpl::Sign(
uint16_t algorithm,
const std::vector<uint8_t>& input,
network::mojom::SSLPrivateKey::SignCallback callback) {
base::span<const uint8_t> input_span(input);
ssl_private_key_->Sign(
algorithm, input_span,
base::BindOnce(&SSLPrivateKeyImpl::Callback, base::Unretained(this),
std::move(callback)));
}
void SSLPrivateKeyImpl::Callback(
network::mojom::SSLPrivateKey::SignCallback callback,
net::Error net_error,
const std::vector<uint8_t>& signature) {
std::move(callback).Run(static_cast<int32_t>(net_error), signature);
}
} // namespace content
| 30.578947 | 74 | 0.733219 | [
"vector"
] |
1b7c12d465a222a97dc150c18ef15ceeacca32f2 | 3,701 | cpp | C++ | Code/MainWidgets/projectSolveDialog.cpp | jiaguobing/FastCAE | 2348ab87e83fe5c704e4c998cf391229c25ac5d5 | [
"BSD-3-Clause"
] | 2 | 2020-02-21T01:04:35.000Z | 2020-02-21T03:35:37.000Z | Code/MainWidgets/projectSolveDialog.cpp | Sunqia/FastCAE | cbc023fe07b6e306ceefae8b8bd7c12bc1562acb | [
"BSD-3-Clause"
] | 1 | 2020-03-06T04:49:42.000Z | 2020-03-06T04:49:42.000Z | Code/MainWidgets/projectSolveDialog.cpp | Sunqia/FastCAE | cbc023fe07b6e306ceefae8b8bd7c12bc1562acb | [
"BSD-3-Clause"
] | 1 | 2021-11-21T13:03:26.000Z | 2021-11-21T13:03:26.000Z | #include "projectSolveDialog.h"
#include "ui_projectSolveDialog.h"
#include "settings/busAPI.h"
#include "moduleBase/processBar.h"
//#include "SolverControl/solverControler.h"
#include "mainWindow/mainWindow.h"
// #include "settings/SolverManager.h"
// #include "settings/SolverInfo.h"
#include "ConfigOptions/ConfigOptions.h"
#include "ConfigOptions/SolverConfig.h"
#include "ConfigOptions/SolverInfo.h"
#include "ModelData/modelDataSingleton.h"
#include "ModelData/modelDataBase.h"
#include <QFile>
#include <assert.h>
#include <QMessageBox>
namespace MainWidget
{
ProjcctSolveDialog::ProjcctSolveDialog(GUI::MainWindow* mainwindow, bool &showDlg, int proid) : QFDialog(mainwindow),
_ui(new Ui::projectSolveDialog), _mainWindow(mainwindow), _showDlg(showDlg), _proID(proid)
{
_ui->setupUi(this);
connect(this, SIGNAL(solveProject(int, int)), mainwindow, SIGNAL(solveProjectSig(int, int)));
connect(this, SIGNAL(sig_display_message(ModuleBase::Message)), _mainWindow, SIGNAL(printMessageToMessageWindow(ModuleBase::Message)));
init();
}
ProjcctSolveDialog::~ProjcctSolveDialog()
{
delete _ui;
}
void ProjcctSolveDialog::init()
{
ModelData::ModelDataSingleton* modelData = ModelData::ModelDataSingleton::getinstance();
const int modelCount = modelData->getModelCount();
int index = -1;
for (int i = 0; i < modelCount; ++i)
{
ModelData::ModelDataBase* model = modelData->getModelAt(i);
const QString proname = model->getName();
_ui->projectComboBox->addItem(proname);
if (_proID == model->getID()) index = i;
}
if (_proID > 0)
{
_ui->projectComboBox->setCurrentIndex(index);
_ui->projectComboBox->setEnabled(false);
}
// Setting::SolverManager *manager = Setting::BusAPI::instance()->getSolverManager();
// const int sn = manager->getSolverCount();
// for (int i = 0; i < sn; ++i)
// {
// Setting::SolverInfo* info = manager->getSolverAt(i);
// QString name = info->getName();
// _ui->solverComboBox->addItem(name);
// }
ConfigOption::SolverOption* solveroption = ConfigOption::ConfigOption::getInstance()->getSolverOption();
const int sn = solveroption->getSolverCount();
for (int i = 0; i < sn; ++i)
{
ConfigOption::SolverInfo* solver = solveroption->getSolverAt(i);
QString name = solver->getName();
_ui->solverComboBox->addItem(name);
}
if (_proID > 0 && sn == 1)
{
_showDlg = false;
on_solveButton_clicked();
}
else if (modelCount == 1 && sn == 1)
{
_showDlg = false;
on_solveButton_clicked();
}
}
void ProjcctSolveDialog::on_solveButton_clicked()
{
const int modelIndex = _ui->projectComboBox->currentIndex();
if (modelIndex < 0) return;
const int solverIndex = _ui->solverComboBox->currentIndex();
if (solverIndex < 0) return;
ModelData::ModelDataBase* mb = ModelData::ModelDataSingleton::getinstance()->getModelAt(modelIndex);
QVector<ModuleBase::Message> messages;
if (!mb->checkSolveableStatus(messages))
{
//QMessageBox::warning(this, tr("Warning"), tr("This project can not be solved !"));
for (ModuleBase::Message message : messages)
{
emit sig_display_message(message);
}
this->close();
return;
}
emit solveProject(modelIndex, solverIndex);
this->accept();
close();
}
void ProjcctSolveDialog::on_cancleButton_clicked()
{
// _startSolve = false;
this->rejected();
close();
}
// void ProjcctSolveDialog::changeCurrentIndex(int index)
// {
// _currentIndex = index;
// }
void ProjcctSolveDialog::closeEvent(QCloseEvent *event)
{
// if (!_startSolve)
// emit solveFailed();
}
} | 31.364407 | 138 | 0.681708 | [
"model"
] |
1b7c2bf92922c34ff6c1b51ef657bc3865b91456 | 845 | hpp | C++ | src/domain/mesh/tests/mesh_mock.hpp | SlaybaughLab/Transport | 8eb32cb8ae50c92875526a7540350ef9a85bc050 | [
"MIT"
] | 12 | 2018-03-14T12:30:53.000Z | 2022-01-23T14:46:44.000Z | src/domain/mesh/tests/mesh_mock.hpp | SlaybaughLab/Transport | 8eb32cb8ae50c92875526a7540350ef9a85bc050 | [
"MIT"
] | 194 | 2017-07-07T01:38:15.000Z | 2021-05-19T18:21:19.000Z | src/domain/mesh/tests/mesh_mock.hpp | SlaybaughLab/Transport | 8eb32cb8ae50c92875526a7540350ef9a85bc050 | [
"MIT"
] | 10 | 2017-07-06T22:58:59.000Z | 2021-03-15T07:01:21.000Z | #ifndef BART_SRC_DOMAIN_MESH_MOCK_HPP_
#define BART_SRC_DOMAIN_MESH_MOCK_HPP_
#include "domain/mesh/mesh_i.hpp"
#include <array>
#include <deal.II/grid/tria.h>
#include "test_helpers/gmock_wrapper.h"
namespace bart::domain::mesh {
template <int dim>
class MeshMock : public MeshI<dim> {
public:
MOCK_METHOD(void, FillTriangulation, (dealii::Triangulation<dim>&), (override));
MOCK_METHOD(void, FillMaterialID, (dealii::Triangulation<dim>&), (override));
MOCK_METHOD(void, FillBoundaryID, (dealii::Triangulation<dim>&), (override));
MOCK_METHOD(bool, has_material_mapping, (), (override, const));
MOCK_METHOD((std::array<double, dim>), spatial_max, (), (override, const));
MOCK_METHOD((std::array<int, dim>), n_cells, (), (override, const));
};
} // namespace bart::domain::mesh
#endif // BART_SRC_DOMAIN_MESH_MOCK_HPP_
| 25.606061 | 82 | 0.731361 | [
"mesh"
] |
1b7d83f035fa5259c1638fe095f30926ae9caeaa | 6,662 | cc | C++ | tbfc.cc | qookei/tbfc | 5735cceaba013e1c127e54d20281efaf390dfa64 | [
"Zlib"
] | null | null | null | tbfc.cc | qookei/tbfc | 5735cceaba013e1c127e54d20281efaf390dfa64 | [
"Zlib"
] | null | null | null | tbfc.cc | qookei/tbfc | 5735cceaba013e1c127e54d20281efaf390dfa64 | [
"Zlib"
] | null | null | null | #include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <variant>
#include <stack>
#include <algorithm>
struct ir_op {
enum class op_type {
add,
sub,
tape_next,
tape_prev,
print,
read,
peek_tape,
jmp_zero,
jmp_not_zero,
loop_begin,
loop_end,
};
op_type type;
std::variant<std::string, int> arg;
};
struct ir_generator {
ir_generator() :loop_stack{}, loop_counter{0} {}
void generate_ir(char c, std::vector<ir_op> &dest) {
switch(c) {
case '+': dest.push_back(ir_op{ir_op::op_type::add, 1}); break;
case '-': dest.push_back(ir_op{ir_op::op_type::sub, 1}); break;
case '>': dest.push_back(ir_op{ir_op::op_type::tape_next, 1}); break;
case '<': dest.push_back(ir_op{ir_op::op_type::tape_prev, 1}); break;
case '.':
dest.push_back(ir_op{ir_op::op_type::print, 0});
break;
case ',':
dest.push_back(ir_op{ir_op::op_type::read, 0});
break;
case '[':
loop_stack.push(loop_counter);
loop_counter++;
dest.push_back(ir_op{ir_op::op_type::peek_tape, 0});
dest.push_back(ir_op{ir_op::op_type::jmp_zero, "end_" + std::to_string(loop_stack.top())});
dest.push_back(ir_op{ir_op::op_type::loop_begin, loop_stack.top()});
break;
case ']':
dest.push_back(ir_op{ir_op::op_type::peek_tape, 0});
dest.push_back(ir_op{ir_op::op_type::jmp_not_zero, "begin_" + std::to_string(loop_stack.top())});
dest.push_back(ir_op{ir_op::op_type::loop_end, loop_stack.top()});
loop_stack.pop();
break;
}
}
private:
int loop_counter;
std::stack<int> loop_stack;
};
std::vector<ir_op> optimizer_pass_reduce_add_sub(const std::vector<ir_op> &ir){
size_t i = 0;
int add_counter = 0, sub_counter = 0;
std::vector<ir_op> new_ir;
while(i < ir.size()) {
if (ir[i].type != ir_op::op_type::add
&& ir[i].type != ir_op::op_type::sub) {
new_ir.push_back(ir[i]);
i++;
continue;
}
if (ir[i].type == ir_op::op_type::add)
add_counter++;
else if (ir[i].type == ir_op::op_type::sub)
sub_counter++;
if ((i == ir.size() - 1) || (ir[i + 1].type != ir_op::op_type::add
&& ir[i + 1].type != ir_op::op_type::sub)) {
int diff = add_counter - sub_counter;
if (diff < 0)
new_ir.push_back(ir_op{ir_op::op_type::sub, -diff});
else if (diff > 0)
new_ir.push_back(ir_op{ir_op::op_type::add, diff});
add_counter = 0;
sub_counter = 0;
}
i++;
}
return new_ir;
}
std::vector<ir_op> optimizer_pass_reduce_next_prev(const std::vector<ir_op> &ir){
size_t i = 0;
int next_counter = 0, prev_counter = 0;
std::vector<ir_op> new_ir;
while(i < ir.size()) {
if (ir[i].type != ir_op::op_type::tape_next
&& ir[i].type != ir_op::op_type::tape_prev) {
new_ir.push_back(ir[i]);
i++;
continue;
}
if (ir[i].type == ir_op::op_type::tape_next)
next_counter++;
else if (ir[i].type == ir_op::op_type::tape_prev)
prev_counter++;
if ((i == ir.size() - 1) || (ir[i + 1].type != ir_op::op_type::tape_next
&& ir[i + 1].type != ir_op::op_type::tape_prev)) {
int diff = next_counter - prev_counter;
if (diff < 0)
new_ir.push_back(ir_op{ir_op::op_type::tape_prev, -diff});
else if (diff > 0)
new_ir.push_back(ir_op{ir_op::op_type::tape_next, diff});
next_counter = 0;
prev_counter = 0;
}
i++;
}
return new_ir;
}
// ebx - tape offset
// ecx - tape pointer
// esi - tape size
void emit_asm_ir(ir_op op) {
static size_t branch_counter = 0;
switch(op.type) {
case ir_op::op_type::add:
fprintf(stderr, "\tadd byte [ebx + ecx], %d\n", std::get<int>(op.arg));
break;
case ir_op::op_type::sub:
fprintf(stderr, "\tsub byte [ebx + ecx], %d\n", std::get<int>(op.arg));
break;
case ir_op::op_type::loop_begin:
fprintf(stderr, "begin_%d:\n", std::get<int>(op.arg));
break;
case ir_op::op_type::loop_end:
fprintf(stderr, "end_%d:\n", std::get<int>(op.arg));
break;
case ir_op::op_type::tape_next:
fprintf(stderr, "\tadd ebx, %d\n", std::get<int>(op.arg));
fprintf(stderr, "\txor edx, edx\n");
fprintf(stderr, "\tmov eax, ebx\n");
fprintf(stderr, "\tdiv esi\n");
fprintf(stderr, "\tmov ebx, edx\n");
break;
case ir_op::op_type::tape_prev:
fprintf(stderr, "\tsub ebx, %d\n", std::get<int>(op.arg));
fprintf(stderr, "\ttest ebx, ebx\n");
fprintf(stderr, "\tjns .L%lu\n", branch_counter);
fprintf(stderr, "\tadd ebx, 30000\n");
fprintf(stderr, ".L%lu:\n", branch_counter);
branch_counter++;
break;
case ir_op::op_type::peek_tape:
fprintf(stderr, "\tmov al, [ebx + ecx]\n");
fprintf(stderr, "\ttest al, al\n");
break;
case ir_op::op_type::read:
fprintf(stderr, "\tcall impl_read\n");
break;
case ir_op::op_type::print:
fprintf(stderr, "\tcall impl_print\n");
break;
case ir_op::op_type::jmp_not_zero:
fprintf(stderr, "\tjnz %s\n", std::get<std::string>(op.arg).c_str());
break;
case ir_op::op_type::jmp_zero:
fprintf(stderr, "\tjz %s\n", std::get<std::string>(op.arg).c_str());
break;
}
}
void emit_asm_prologue() {
fprintf(stderr, "bits 32\n");
fprintf(stderr, "global _start\n");
fprintf(stderr, "section .data\n");
fprintf(stderr, "_tape:\n");
fprintf(stderr, "\ttimes 30000 db 0\n\n");
fprintf(stderr, "section .text\n");
fprintf(stderr, "_start:\n");
fprintf(stderr, "\txor ebx, ebx\n");
fprintf(stderr, "\tmov ecx, _tape\n");
fprintf(stderr, "\tmov esi, 30000\n");
}
void emit_asm_epilogue() {
fprintf(stderr, "\tmov eax, 1\n");
fprintf(stderr, "\txor ebx, ebx\n");
fprintf(stderr, "\tint 0x80\n\n");
fprintf(stderr, "impl_print:\n");
fprintf(stderr, "\tpushad\n");
fprintf(stderr, "\tmov eax, 4\n");
fprintf(stderr, "\tmov edx, 1\n");
fprintf(stderr, "\tadd ecx, ebx\n");
fprintf(stderr, "\tmov ebx, 1\n");
fprintf(stderr, "\tint 0x80\n");
fprintf(stderr, "\tpopad\n");
fprintf(stderr, "\tret\n\n");
fprintf(stderr, "impl_read:\n");
fprintf(stderr, "\tpushad\n");
fprintf(stderr, "\tmov eax, 3\n");
fprintf(stderr, "\tmov edx, 1\n");
fprintf(stderr, "\tadd ecx, ebx\n");
fprintf(stderr, "\tmov ebx, 1\n");
fprintf(stderr, "\tint 0x80\n");
fprintf(stderr, "\tpopad\n");
fprintf(stderr, "\tret\n");
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "usage: <file>\n");
return 1;
}
ir_generator gen;
std::vector<ir_op> ir;
std::ifstream file(argv[1]);
std::stringstream buffer;
buffer << file.rdbuf();
std::string source = buffer.str();
for (char c : source) {
gen.generate_ir(c, ir);
}
ir = optimizer_pass_reduce_add_sub(ir);
ir = optimizer_pass_reduce_next_prev(ir);
emit_asm_prologue();
for (auto &op : ir)
emit_asm_ir(op);
emit_asm_epilogue();
return 0;
}
| 24.674074 | 101 | 0.634344 | [
"vector"
] |
1b7eb83bf40810b71dde93585284ab72afeedba4 | 8,154 | hxx | C++ | opencascade/BRepOffset_Analyse.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/BRepOffset_Analyse.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/BRepOffset_Analyse.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | // Created on: 1995-10-20
// Created by: Yves FRICAUD
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRepOffset_Analyse_HeaderFile
#define _BRepOffset_Analyse_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Boolean.hxx>
#include <TopoDS_Shape.hxx>
#include <BRepOffset_DataMapOfShapeListOfInterval.hxx>
#include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
#include <Standard_Real.hxx>
#include <BRepOffset_ListOfInterval.hxx>
#include <ChFiDS_TypeOfConcavity.hxx>
#include <TopTools_DataMapOfShapeListOfShape.hxx>
#include <TopTools_DataMapOfShapeReal.hxx>
#include <TopTools_DataMapOfShapeShape.hxx>
#include <TopTools_ListOfShape.hxx>
#include <TopTools_MapOfShape.hxx>
#include <Message_ProgressRange.hxx>
class TopoDS_Edge;
class TopoDS_Vertex;
class TopoDS_Face;
class TopoDS_Compound;
//! Analyses the shape to find the parts of edges
//! connecting the convex, concave or tangent faces.
class BRepOffset_Analyse
{
public:
DEFINE_STANDARD_ALLOC
public: //! @name Constructors
//! Empty c-tor
Standard_EXPORT BRepOffset_Analyse();
//! C-tor performing the job inside
Standard_EXPORT BRepOffset_Analyse (const TopoDS_Shape& theS,
const Standard_Real theAngle);
public: //! @name Performing analysis
//! Performs the analysis
Standard_EXPORT void Perform (const TopoDS_Shape& theS,
const Standard_Real theAngle,
const Message_ProgressRange& theRange = Message_ProgressRange());
public: //! @name Results
//! Returns status of the algorithm
Standard_Boolean IsDone() const
{
return myDone;
}
//! Returns the connectivity type of the edge
Standard_EXPORT const BRepOffset_ListOfInterval& Type (const TopoDS_Edge& theE) const;
//! Stores in <L> all the edges of Type <T>
//! on the vertex <V>.
Standard_EXPORT void Edges (const TopoDS_Vertex& theV,
const ChFiDS_TypeOfConcavity theType,
TopTools_ListOfShape& theL) const;
//! Stores in <L> all the edges of Type <T>
//! on the face <F>.
Standard_EXPORT void Edges (const TopoDS_Face& theF,
const ChFiDS_TypeOfConcavity theType,
TopTools_ListOfShape& theL) const;
//! set in <Edges> all the Edges of <Shape> which are
//! tangent to <Edge> at the vertex <Vertex>.
Standard_EXPORT void TangentEdges (const TopoDS_Edge& theEdge,
const TopoDS_Vertex& theVertex,
TopTools_ListOfShape& theEdges) const;
//! Checks if the given shape has ancestors
Standard_Boolean HasAncestor (const TopoDS_Shape& theS) const
{
return myAncestors.Contains (theS);
}
//! Returns ancestors for the shape
const TopTools_ListOfShape& Ancestors (const TopoDS_Shape& theS) const
{
return myAncestors.FindFromKey (theS);
}
//! Explode in compounds of faces where
//! all the connex edges are of type <Side>
Standard_EXPORT void Explode (TopTools_ListOfShape& theL,
const ChFiDS_TypeOfConcavity theType) const;
//! Explode in compounds of faces where
//! all the connex edges are of type <Side1> or <Side2>
Standard_EXPORT void Explode (TopTools_ListOfShape& theL,
const ChFiDS_TypeOfConcavity theType1,
const ChFiDS_TypeOfConcavity theType2) const;
//! Add in <CO> the faces of the shell containing <Face>
//! where all the connex edges are of type <Side>.
Standard_EXPORT void AddFaces (const TopoDS_Face& theFace,
TopoDS_Compound& theCo,
TopTools_MapOfShape& theMap,
const ChFiDS_TypeOfConcavity theType) const;
//! Add in <CO> the faces of the shell containing <Face>
//! where all the connex edges are of type <Side1> or <Side2>.
Standard_EXPORT void AddFaces (const TopoDS_Face& theFace,
TopoDS_Compound& theCo,
TopTools_MapOfShape& theMap,
const ChFiDS_TypeOfConcavity theType1,
const ChFiDS_TypeOfConcavity theType2) const;
void SetOffsetValue (const Standard_Real theOffset)
{
myOffset = theOffset;
}
//! Sets the face-offset data map to analyze tangential cases
void SetFaceOffsetMap (const TopTools_DataMapOfShapeReal& theMap)
{
myFaceOffsetMap = theMap;
}
//! Returns the new faces constructed between tangent faces
//! having different offset values on the shape
const TopTools_ListOfShape& NewFaces() const { return myNewFaces; }
//! Returns the new face constructed for the edge connecting
//! the two tangent faces having different offset values
Standard_EXPORT TopoDS_Shape Generated (const TopoDS_Shape& theS) const;
//! Checks if the edge has generated a new face.
Standard_Boolean HasGenerated (const TopoDS_Shape& theS) const
{
return myGenerated.Seek (theS) != NULL;
}
//! Returns the replacement of the edge in the face.
//! If no replacement exists, returns the edge
Standard_EXPORT const TopoDS_Edge& EdgeReplacement (const TopoDS_Face& theFace,
const TopoDS_Edge& theEdge) const;
//! Returns the shape descendants.
Standard_EXPORT const TopTools_ListOfShape* Descendants (const TopoDS_Shape& theS,
const Standard_Boolean theUpdate = Standard_False) const;
public: //! @name Clearing the content
//! Clears the content of the algorithm
Standard_EXPORT void Clear();
private: //! @name Treatment of tangential cases
//! Treatment of the tangential cases.
//! @param theEdges List of edges connecting tangent faces
Standard_EXPORT void TreatTangentFaces (const TopTools_ListOfShape& theEdges, const Message_ProgressRange& theRange);
private: //! @name Fields
// Inputs
TopoDS_Shape myShape; //!< Input shape to analyze
Standard_Real myAngle; //!< Criteria angle to check tangency
Standard_Real myOffset; //!< Offset value
TopTools_DataMapOfShapeReal myFaceOffsetMap; //!< Map to store offset values for the faces.
//! Should be set by the calling algorithm.
// Results
Standard_Boolean myDone; //!< Status of the algorithm
BRepOffset_DataMapOfShapeListOfInterval myMapEdgeType; //!< Map containing the list of intervals on the edge
TopTools_IndexedDataMapOfShapeListOfShape myAncestors; //!< Ancestors map
NCollection_DataMap<TopoDS_Shape,
TopTools_DataMapOfShapeShape,
TopTools_ShapeMapHasher> myReplacement; //!< Replacement of an edge in the face
mutable TopTools_DataMapOfShapeListOfShape myDescendants; //!< Map of shapes descendants built on the base of
//!< Ancestors map. Filled on the first query.
TopTools_ListOfShape myNewFaces; //!< New faces generated to close the gaps between adjacent
//! tangential faces having different offset values
TopTools_DataMapOfShapeShape myGenerated; //!< Binding between edge and face generated from the edge
};
#endif // _BRepOffset_Analyse_HeaderFile
| 39.582524 | 119 | 0.681629 | [
"shape"
] |
1b806a24cfaa85576ba3fe8d5846fb0c09a439f1 | 1,574 | cc | C++ | voicenavigator/src/model/QueryPerformanceIndicatorsRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | null | null | null | voicenavigator/src/model/QueryPerformanceIndicatorsRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | null | null | null | voicenavigator/src/model/QueryPerformanceIndicatorsRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 1 | 2020-11-27T09:13:12.000Z | 2020-11-27T09:13:12.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/voicenavigator/model/QueryPerformanceIndicatorsRequest.h>
using AlibabaCloud::VoiceNavigator::Model::QueryPerformanceIndicatorsRequest;
QueryPerformanceIndicatorsRequest::QueryPerformanceIndicatorsRequest() :
RpcServiceRequest("voicenavigator", "2018-06-12", "QueryPerformanceIndicators")
{
setMethod(HttpRequest::Method::Get);
}
QueryPerformanceIndicatorsRequest::~QueryPerformanceIndicatorsRequest()
{}
std::string QueryPerformanceIndicatorsRequest::getInstanceId()const
{
return instanceId_;
}
void QueryPerformanceIndicatorsRequest::setInstanceId(const std::string& instanceId)
{
instanceId_ = instanceId;
setParameter("InstanceId", instanceId);
}
std::string QueryPerformanceIndicatorsRequest::getDateUnit()const
{
return dateUnit_;
}
void QueryPerformanceIndicatorsRequest::setDateUnit(const std::string& dateUnit)
{
dateUnit_ = dateUnit;
setParameter("DateUnit", dateUnit);
}
| 30.269231 | 85 | 0.775731 | [
"model"
] |
1b80d661ad1cee9e1bb20f28d87c47bdcbd8660d | 4,592 | cpp | C++ | unit/src/SimplexTest.cpp | volkerschmidts/titania | 1ad441a7f9481392e21216a2be86b20b1d090a97 | [
"MIT"
] | null | null | null | unit/src/SimplexTest.cpp | volkerschmidts/titania | 1ad441a7f9481392e21216a2be86b20b1d090a97 | [
"MIT"
] | 1 | 2022-03-24T03:54:06.000Z | 2022-03-25T15:32:09.000Z | unit/src/SimplexTest.cpp | volkerschmidts/titania | 1ad441a7f9481392e21216a2be86b20b1d090a97 | [
"MIT"
] | null | null | null | #include <Simplex.hpp>
#include <SimplexTest.hpp>
// there is still some weird include ordering dependence hidden in
// Declarations.hpp
// clang-format off
#include <Declarations.hpp>
// clang-format on
#include <cmath>
#include <main.h>
#include <nlopt.hpp>
#include <vector>
typedef struct {
double a, b;
} my_constraint_data;
double
myvfunc(const std::vector<double> &x,
std::vector<double> &grad,
void *my_func_data)
{
if (!grad.empty())
{
grad[0] = 0.0;
grad[1] = 0.5 / sqrt(x[1]);
}
return sqrt(x[1]);
}
double
myvconstraint(const std::vector<double> &x,
std::vector<double> &grad,
void *data)
{
my_constraint_data *d = reinterpret_cast<my_constraint_data *>(data);
double a = d->a, b = d->b;
if (!grad.empty())
{
grad[0] = 3 * a * (a * x[0] + b) * (a * x[0] + b);
grad[1] = -1.0;
}
return ((a * x[0] + b) * (a * x[0] + b) * (a * x[0] + b) - x[1]);
}
typedef struct {
double a, b;
unsigned int count;
} Rosenbrock_par;
double
Rosenbrock2D(const std::vector<double> &x,
std::vector<double> &grad,
void *func_data)
{
Rosenbrock_par *r_par = reinterpret_cast<Rosenbrock_par *>(func_data);
double a = r_par->a;
double b = r_par->b;
r_par->count++;
if (!grad.empty())
{
grad[0] = 2 * (x[0] * (2 * b * (pow(x[0], 2) - x[1]) + 1) - a);
grad[1] = 2 * b * (-pow(x[0], 2) + x[1]);
}
double val = pow(a - x[0], 2) + b * pow(x[1] - pow(x[0], 2), 2);
// fprintf(stderr, "count %d x[0] %.14f x[1] %.14f val %.14f\n", r_par->count,
// x[0], x[1], val);
return val;
}
CPPUNIT_TEST_SUITE_REGISTRATION(SimplexTest);
SimplexTest::SimplexTest()
{
;
}
SimplexTest::~SimplexTest()
{
;
}
void
SimplexTest::testNLoptExample()
{
nlopt::opt opt(nlopt::LD_MMA, 2);
std::vector<double> lb(2);
lb[0] = -HUGE_VAL;
lb[1] = 0;
opt.set_lower_bounds(lb);
opt.set_min_objective(myvfunc, NULL);
my_constraint_data data[2] = {{2, 0}, {-1, 1}};
opt.add_inequality_constraint(myvconstraint, &data[0], 1e-8);
opt.add_inequality_constraint(myvconstraint, &data[1], 1e-8);
opt.set_xtol_rel(1e-4);
std::vector<double> x(2);
x[0] = 1.234;
x[1] = 5.678;
std::vector<double> x_expected(2);
x_expected[0] = 0.3333333348;
x_expected[1] = 0.2962962891;
double minf;
double minf_expected = 0.5443310474;
try
{
nlopt::result result = opt.optimize(x, minf);
CPPUNIT_ASSERT_DOUBLES_EQUAL(x_expected[0], x[0], 1e-8);
CPPUNIT_ASSERT_DOUBLES_EQUAL(x_expected[1], x[1], 1e-8);
CPPUNIT_ASSERT_DOUBLES_EQUAL(minf_expected, minf, 1e-8);
}
catch (std::exception &e)
{
std::cout << "nlopt failed: " << e.what() << std::endl;
}
}
void
SimplexTest::testNLoptRosenbrock2D_NM()
{
Rosenbrock_par r_par;
r_par.a = 1;
r_par.b = 100;
r_par.count = 0;
double xtol = 1e-8;
double ftol = 1e-4;
nlopt::opt opt(nlopt::LN_NELDERMEAD, 2);
opt.set_min_objective(Rosenbrock2D, &r_par);
opt.set_xtol_rel(xtol);
std::vector<double> x(2);
x[0] = -1.9;
x[1] = 2;
double minf;
std::vector<double> x_expected(2);
x_expected[0] = x_expected[1] = 1.0;
double minf_expected = 0.0;
try
{
nlopt::result result = opt.optimize(x, minf);
CPPUNIT_ASSERT_EQUAL(nlopt::XTOL_REACHED, result);
CPPUNIT_ASSERT_DOUBLES_EQUAL(x_expected[0], x[0], xtol);
CPPUNIT_ASSERT_DOUBLES_EQUAL(x_expected[1], x[1], xtol);
CPPUNIT_ASSERT_DOUBLES_EQUAL(minf_expected, minf, ftol);
}
catch (std::exception &e)
{
std::cout << "nlopt failed: " << e.what() << std::endl;
}
}
void
SimplexTest::testSimplexNLoptRosenbrock2D_NM()
{
Eigen::VectorXd start(2);
start << -1.9, 2.0;
unsigned int ndim = start.size();
Simplex simplex(start);
simplex.vfunc = Rosenbrock2D;
Rosenbrock_par r_par;
r_par.a = 1;
r_par.b = 100;
r_par.count = 0;
double xtol = 1e-8;
double ftol = 1e-4;
simplex.func_par = &r_par;
simplex.setxtol(xtol);
simplex.setftol(ftol);
Eigen::VectorXd expected(2);
expected << 1.0, 1.0;
double minf_expected = 0.0;
try
{
Eigen::VectorXd final = simplex.minimize();
for (unsigned int i = 0; i < ndim; ++i)
{
CPPUNIT_ASSERT_DOUBLES_EQUAL(expected(i), final(i), xtol);
}
CPPUNIT_ASSERT_DOUBLES_EQUAL(minf_expected, simplex.getfmin(), ftol);
// CPPUNIT_ASSERT_EQUAL(nlopt::FTOL_REACHED, simplex.getresult()); //
// doesn't work, seems to always give nlopt::XTOL_REACHED
}
catch (std::exception &e)
{
std::cout << "nlopt failed: " << e.what() << std::endl;
}
}
| 23.309645 | 80 | 0.616071 | [
"vector"
] |
1b852f3b1013bee40e6784834121c6a350033874 | 12,174 | cc | C++ | multidim_image_augmentation/kernels/apply_deformation_ops.cc | alexminnaar/multidim-image-augmentation | 685ea3a5d29745c520b70f69ed66f845c45df4c3 | [
"Apache-2.0"
] | 1 | 2018-12-28T18:07:34.000Z | 2018-12-28T18:07:34.000Z | multidim_image_augmentation/kernels/apply_deformation_ops.cc | alexminnaar/multidim-image-augmentation | 685ea3a5d29745c520b70f69ed66f845c45df4c3 | [
"Apache-2.0"
] | null | null | null | multidim_image_augmentation/kernels/apply_deformation_ops.cc | alexminnaar/multidim-image-augmentation | 685ea3a5d29745c520b70f69ed66f845c45df4c3 | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "multidim_image_augmentation/kernels/apply_deformation.h"
#include <array>
#include <string>
#include "multidim_image_augmentation/ops/apply_deformation_ops.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/lib/core/errors.h"
namespace deepmind {
namespace multidim_image_augmentation {
namespace {
using tensorflow::DEVICE_CPU;
using tensorflow::OpKernel;
using tensorflow::OpKernelConstruction;
using tensorflow::OpKernelContext;
using tensorflow::Status;
using tensorflow::Tensor;
using tensorflow::TensorShape;
using tensorflow::errors::InvalidArgument;
enum SpatialDims {
k2SpatialDims = 2,
k3SpatialDims = 3,
};
//
// Wrappers for ApplyDeformation with a template specialization that allows
// the correct Deform method (2D vs 3D) to be selected based on the
// spatial_dims template parameters, or error if the style is unsupported.
//
template <SpatialDims spatial_dims, InterpolationStyle interpolation_style,
ExtrapolationStyle extrapolation_style,
ConversionStyle conversion_style>
class Applier {};
// 2D Deform.
template <InterpolationStyle interpolation_style,
ExtrapolationStyle extrapolation_style,
ConversionStyle conversion_style>
class Applier<k2SpatialDims, interpolation_style, extrapolation_style,
conversion_style> {
public:
template <typename InTensor, typename DeformTensor, typename OutTensor>
static void Apply(OpKernelContext* context, const InTensor& in,
const DeformTensor& deform, OutTensor* out,
const typename InTensor::Scalar* padding_constant) {
ApplyDeformation<interpolation_style, extrapolation_style,
conversion_style>::Deform2D(in, deform, out,
padding_constant);
}
};
// Error handler for unsupported 2D Deform configurations.
template <ExtrapolationStyle extrapolation_style,
ConversionStyle conversion_style>
class Applier<k2SpatialDims, kMixedNearestLinear, extrapolation_style,
conversion_style> {
public:
template <typename InTensor, typename DeformTensor, typename OutTensor>
static void Apply(OpKernelContext* context, const InTensor& in,
const DeformTensor& deform, OutTensor* out,
const typename InTensor::Scalar* padding_constant) {
context->CtxFailure(
InvalidArgument("Deform 2D does not support `mixed_nearest_linear`."));
}
};
// 3D Deform.
template <InterpolationStyle interpolation_style,
ExtrapolationStyle extrapolation_style,
ConversionStyle conversion_style>
class Applier<k3SpatialDims, interpolation_style, extrapolation_style,
conversion_style> {
public:
template <typename InTensor, typename DeformTensor, typename OutTensor>
static void Apply(OpKernelContext* context, const InTensor& in,
const DeformTensor& deform, OutTensor* out,
const typename InTensor::Scalar* padding_constant) {
ApplyDeformation<interpolation_style, extrapolation_style,
conversion_style>::Deform3D(in, deform, out,
padding_constant);
}
};
//
// ApplyDeformation Op Kernel implementations.
//
template <SpatialDims spatial_dims, typename InType, typename OutType>
class ApplyDeformationOp : public OpKernel {
public:
explicit ApplyDeformationOp(OpKernelConstruction* context)
: OpKernel(context) {
OP_REQUIRES_OK(context, GetAttributes<Status>(context, &attrs_));
OP_REQUIRES(
context,
attrs_.requested_output_spatial_shape.empty() ||
attrs_.requested_output_spatial_shape.size() == spatial_dims,
InvalidArgument(
"If specified, output_spatial_shape must have one element per "
"input dimension"));
}
void Compute(OpKernelContext* context) override {
const Tensor& input = context->input(kInputIndex);
const Tensor& deformation = context->input(kDeformIndex);
const Tensor& padding_constant = context->input(kPaddingConstIndex);
TensorShape output_shape(deformation.shape());
for (int i = 0; i < attrs_.requested_output_spatial_shape.size(); ++i) {
DCHECK(i < spatial_dims);
auto size = attrs_.requested_output_spatial_shape[i];
if (size >= 0) {
OP_REQUIRES(
context, size <= output_shape.dim_size(i),
InvalidArgument(
"output_spatial_shape must not exceed the deformation field "
"size in any dimension"));
output_shape.set_dim(i, size);
}
}
auto num_channels = attrs_.output_num_channels >= 0
? attrs_.output_num_channels
: input.dim_size(spatial_dims);
const InType* eigen_padding_p = nullptr;
if (attrs_.extrapolation_style == "const_padding") {
OP_REQUIRES(
context, padding_constant.NumElements() == num_channels,
InvalidArgument(
"padding constant must be a vector with num_channels elements."));
eigen_padding_p = padding_constant.flat<InType>().data();
}
output_shape.set_dim(spatial_dims, num_channels);
// NOTE: If making any change to the computation of `output_shape` above,
// a corresponding change is also needed in ApplyDeformationShapeFunction.
Tensor* output;
OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
EigenTensorOut eigen_output = output->tensor<OutType, kTensorRank>();
ApplyDeform(context, input.tensor<InType, kTensorRank>(),
deformation.tensor<float, kTensorRank>(), &eigen_output,
eigen_padding_p);
}
private:
// One additional dimension for the channels.
static const int kTensorRank = spatial_dims + 1;
typedef Eigen::Tensor<InType, kTensorRank, Eigen::RowMajor> EigenTensorIn;
typedef Eigen::Tensor<float, kTensorRank, Eigen::RowMajor> EigenTensorDeform;
typedef Eigen::TensorMap<Eigen::Tensor<OutType, kTensorRank, Eigen::RowMajor>,
Eigen::Aligned>
EigenTensorOut;
// Helper method to actually apply the deform on the image provided. This uses
// a chain of internal methods to map out the runtime-provided style
// parameters (in the `attrs_` member) to the appropriate compile-time
// function instances via template parameters.
void ApplyDeform(OpKernelContext* context, const EigenTensorIn& in,
const EigenTensorDeform& deform, EigenTensorOut* out,
const InType* padding_constant) {
ExpandInterpolations(context, in, deform, out, padding_constant);
}
void ExpandInterpolations(OpKernelContext* context, const EigenTensorIn& in,
const EigenTensorDeform& deform,
EigenTensorOut* out,
const InType* padding_constant) {
if (attrs_.interpolation_style == "nearest") {
ExpandExtrapolations<kNearest>(context, in, deform, out,
padding_constant);
} else if (attrs_.interpolation_style == "linear") {
ExpandExtrapolations<kLinear>(context, in, deform, out, padding_constant);
} else if (attrs_.interpolation_style == "mixed_nearest_linear") {
ExpandExtrapolations<kMixedNearestLinear>(context, in, deform, out,
padding_constant);
} else {
LOG(FATAL) << "Bad interpolation style " << attrs_.interpolation_style;
}
}
template <InterpolationStyle interpolation_style>
void ExpandExtrapolations(OpKernelContext* context, const EigenTensorIn& in,
const EigenTensorDeform& deform,
EigenTensorOut* out,
const InType* padding_constant) {
if (attrs_.extrapolation_style == "mirror") {
ExpandConversions<interpolation_style, kMirror>(context, in, deform, out,
padding_constant);
} else if (attrs_.extrapolation_style == "zero_padding") {
ExpandConversions<interpolation_style, kZeroPadding>(
context, in, deform, out, padding_constant);
} else if (attrs_.extrapolation_style == "const_padding") {
ExpandConversions<interpolation_style, kConstPadding>(
context, in, deform, out, padding_constant);
} else {
LOG(FATAL) << "Bad extrapolation style " << attrs_.extrapolation_style;
}
}
template <InterpolationStyle interpolation_style,
ExtrapolationStyle extrapolation_style>
void ExpandConversions(OpKernelContext* context, const EigenTensorIn& in,
const EigenTensorDeform& deform, EigenTensorOut* out,
const InType* padding_constant) {
if (attrs_.conversion_style == "no_conversion") {
Apply<interpolation_style, extrapolation_style, kNoConversion>(
context, in, deform, out, padding_constant);
} else if (attrs_.conversion_style == "indexed_to_one_hot") {
Apply<interpolation_style, extrapolation_style, kIndexedToOneHot>(
context, in, deform, out, padding_constant);
} else {
LOG(FATAL) << "Bad conversion style " << attrs_.conversion_style;
}
}
template <InterpolationStyle interpolation_style,
ExtrapolationStyle extrapolation_style,
ConversionStyle conversion_style>
void Apply(OpKernelContext* context, const EigenTensorIn& in,
const EigenTensorDeform& deform, EigenTensorOut* out,
const InType* padding_constant) {
Applier<spatial_dims, interpolation_style, extrapolation_style,
conversion_style>::Apply(context, in, deform, out,
padding_constant);
}
// Parameters supplied from client.
DeformationAttributes attrs_;
};
#define REGISTER_KERNEL(INTYPE, OUTTYPE) \
REGISTER_KERNEL_BUILDER(Name("ApplyDeformation2D") \
.Device(DEVICE_CPU) \
.TypeConstraint<INTYPE>("input_type") \
.TypeConstraint<OUTTYPE>("output_type"), \
ApplyDeformationOp<k2SpatialDims, INTYPE, OUTTYPE>); \
REGISTER_KERNEL_BUILDER(Name("ApplyDeformation3D") \
.Device(DEVICE_CPU) \
.TypeConstraint<INTYPE>("input_type") \
.TypeConstraint<OUTTYPE>("output_type"), \
ApplyDeformationOp<k3SpatialDims, INTYPE, OUTTYPE>);
// The set of registrations shall satisfy all the {input_type x output_type}
// combinations declared for ApplyDeformation2D and ApplyDeformation3D ops.
// Note that each instantiation of the kernel instantiates 2x the number of
// style combinations (36 at time of writing) of the underlying ApplyDeformation
// template.
REGISTER_KERNEL(float, float)
REGISTER_KERNEL(uint8, float)
REGISTER_KERNEL(int32, float)
REGISTER_KERNEL(float, uint8)
REGISTER_KERNEL(uint8, uint8)
REGISTER_KERNEL(int32, uint8)
REGISTER_KERNEL(float, int32)
REGISTER_KERNEL(uint8, int32)
REGISTER_KERNEL(int32, int32)
#undef REGISTER_KERNEL
} // namespace
} // namespace multidim_image_augmentation
} // namespace deepmind
| 42.270833 | 80 | 0.67217 | [
"shape",
"vector",
"3d"
] |
1b88cb2111bac890d1375842f95c34c35386f1b3 | 5,613 | cpp | C++ | src/ofApp.cpp | xfischer/ofColorBlindCircles | ef473ee7f394db93dcf69519700153f23dfb0bd0 | [
"Apache-2.0"
] | 1 | 2015-06-24T23:27:19.000Z | 2015-06-24T23:27:19.000Z | src/ofApp.cpp | xfischer/ofColorBlindCircles | ef473ee7f394db93dcf69519700153f23dfb0bd0 | [
"Apache-2.0"
] | null | null | null | src/ofApp.cpp | xfischer/ofColorBlindCircles | ef473ee7f394db93dcf69519700153f23dfb0bd0 | [
"Apache-2.0"
] | null | null | null | #include "ofApp.h"
int numCircles= 0;
int maxDiameter = 22;
int minDiameter = 8;
int lastX = -1, lastY = -1;
ofImage motive;
class ofxPoint
{
float x,y;
ofxPoint(float x, float y) {
this->x = x;
this->y = y;
}
};
class Circle
{
float x, y, radius;
vector<int> xs, ys;
ofColor bg, fg;
Circle() {
radius = ofRandom(minDiameter, maxDiameter) / 2.0;
float a = ofRandom(PI*2);
float r = ofRandom(0, ofGetWidth()*.48-radius);
x = lastX < 0 ? ofGetWidth()*.5+cos(a)*r : lastX;
y = lastY < 0 ? ofGetHeight()*.5+ sin(a)*r : lastY;
init();
}
Circle(int x, int y, float rad) {
this->radius = rad;
this->x = x;
this->y = y;
init();
}
void init() {
bg = ofColor(255,255,255);
fg = -1;
int x = int(this->x), y = int(this->y), r = int(radius);
xs.push_back(x);
xs.push_back(x);
xs.push_back(x);
xs.push_back(x-r);
xs.push_back(x+r);
xs.push_back(x-r*.93);
xs.push_back(x-r*.93);
xs.push_back(x+r*.93);
xs.push_back(x+r*.93);
ys.push_back(y);
ys.push_back(y-r);
ys.push_back(y+r);
ys.push_back(y);
ys.push_back(y);
ys.push_back(y+r*.93);
ys.push_back(y-r*.93);
ys.push_back(y+r*.93);
ys.push_back(y-r*.93);
}
bool overlapsMotive() {
for (int i=0;i<xs.size();i++) {
ofColor col = motive.getColor(xs[i],ys[i]);
if (col != bg) {
return true;
}
}
return false;
}
bool overlapsAny() {
for (int i=0;i<xs.size();i++) {
ofColor col = fbo.getTextureReference().texData (xs[i],ys[i]);
if (col != bg) {
return true;
}
}
if (radius > minDiameter) {
radius = minDiameter;
init();
return overlapsAny();
}
return false;
}
bool intersects(Circle c) {
int dx = int(c.x)-int(x), dy = int(c.y) - int(y);
return dx * dx + dy * dy < (c.radius + radius)*(c.radius + radius);
}
bool inside(Circle c) {
int dx = int(c.x)-int(x), dy = int(c.y) - int(y);
return dx * dx + dy * dy < (c.radius - radius)*(c.radius - radius);
}
void draw() {
if (fg < 0) fg = overlapsMotive() ? on[int(ofRandom(0,on.size()))] : off[int(ofRandom(0,off.size()))];
ofSetColor(fg);
ofEllipse(x, y, radius*2, radius*2);
}
};
ofFbo fbo;
vector<Circle> circles;
string motiv = "dog";
int lastAdded = 0;
int lastAddedTimeout = 100;
int lastX = -1, lastY = -1;
ofImage motive;
vector<ofColor> off, on;
//--------------------------------------------------------------
void ofApp::setup(){
fbo.allocate(ofGetWidth(), ofGetHeight());
ofBackground(255);
ofNoFill();
motive.loadImage(motiv+".png");
// style 1
off.push_back(ofColor::fromHex(0x9CA594));
off.push_back(ofColor::fromHex(0xACB4A5));
off.push_back(ofColor::fromHex(0xBBB964));
off.push_back(ofColor::fromHex(0xD7DAAA));
off.push_back(ofColor::fromHex(0xE5D57D));
off.push_back(ofColor::fromHex(0xD1D6AF));
// style 2
/* color(#F49427), color(#C9785D), color(#E88C6A), color(#F1B081),
color(#F49427), color(#C9785D), color(#E88C6A), color(#F1B081),
color(#F49427), color(#C9785D), color(#E88C6A), color(#F1B081), color(#FFCE00)*/
on.push_back(ofColor::fromHex(0xF9BB82));
on.push_back(ofColor::fromHex(0xEBA170));
on.push_back(ofColor::fromHex(0xFCCD84));
/* color(#89B270), color(#7AA45E), color(#B6C674), color(#7AA45E), color(#B6C674),
color(#89B270), color(#7AA45E), color(#B6C674), color(#7AA45E), color(#B6C674),
color(#89B270), color(#7AA45E), color(#B6C674), color(#7AA45E), color(#B6C674), color(#FECB05)*/
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
fbo.begin();
if (numCircles < circles.size()) {
circles[numCircles] = Circle();
if (circles[numCircles].overlapsAny()) {
circles[numCircles] = null;
}
if (circles[numCircles] != null) {
circles[numCircles].draw();
if (numCircles > 1) {
float nearest = 100000;
float current = 0;
int nearestIndex = -1;
for (int i=0; i<numCircles; i++) {
current = ofVec2f(circles[i].x, circles[i].y).distance(circles[numCircles].x, circles[numCircles].y);
if (current < nearest) {
nearest = current;
nearestIndex = i;
}
}
}
numCircles++;
lastAdded = 0;
} else {
if (lastAdded > lastAddedTimeout && maxDiameter > minDiameter) {
maxDiameter--;
// minDiameter--;
lastAdded = 0;
}
lastAdded++;
}
}
lastX = lastY = -1;
fbo.end();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
if (ofVec2f(mouseX, mouseY).distance( ofVec2f(ofGetWidth()*0.5, ofGetHeight()*0.5)) < ofGetWidth() * 0.48) {
lastX = mouseX;
lastY = mouseY;
}
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 21.505747 | 109 | 0.528416 | [
"vector"
] |
b845a1211d4e9d6169ace518af0ad629e69bcf09 | 16,435 | cpp | C++ | dev/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskNode.cpp | brianherrera/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskNode.cpp | ArchitectureStudios/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskNode.cpp | ArchitectureStudios/lumberyard | f85344403c1c2e77ec8c75deb2c116e97b713217 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <AzCore/Serialization/EditContext.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <EMotionFX/Source/Actor.h>
#include <EMotionFX/Source/ActorInstance.h>
#include <EMotionFX/Source/AnimGraph.h>
#include <EMotionFX/Source/AnimGraphAttributeTypes.h>
#include <EMotionFX/Source/AnimGraphInstance.h>
#include <EMotionFX/Source/BlendTreeMaskNode.h>
#include <EMotionFX/Source/EMotionFXManager.h>
namespace EMotionFX
{
AZ_CLASS_ALLOCATOR_IMPL(BlendTreeMaskNode, AnimGraphAllocator, 0)
AZ_CLASS_ALLOCATOR_IMPL(BlendTreeMaskNode::Mask, AnimGraphAllocator, 0)
AZ_CLASS_ALLOCATOR_IMPL(BlendTreeMaskNode::UniqueData, AnimGraphObjectUniqueDataAllocator, 0)
const size_t BlendTreeMaskNode::s_numMasks = 4;
BlendTreeMaskNode::UniqueData::UniqueData(AnimGraphNode* node, AnimGraphInstance* animGraphInstance)
: AnimGraphNodeData(node, animGraphInstance)
{
}
void BlendTreeMaskNode::UniqueData::Update()
{
BlendTreeMaskNode* maskNode = azdynamic_cast<BlendTreeMaskNode*>(mObject);
AZ_Assert(maskNode, "Unique data linked to incorrect node type.");
const Actor* actor = mAnimGraphInstance->GetActorInstance()->GetActor();
const size_t numMaskInstances = maskNode->GetNumUsedMasks();
m_maskInstances.resize(numMaskInstances);
AZ::u32 maskInstanceIndex = 0;
m_motionExtractionInputPortNr.reset();
const AZ::u32 motionExtractionJointIndex = mAnimGraphInstance->GetActorInstance()->GetActor()->GetMotionExtractionNodeIndex();
const AZStd::vector<Mask>& masks = maskNode->GetMasks();
const size_t numMasks = masks.size();
for (size_t i = 0; i < numMasks; ++i)
{
const Mask& mask = masks[i];
if (!mask.m_jointNames.empty())
{
const AZ::u32 inputPortNr = INPUTPORT_START + static_cast<AZ::u32>(i);
// Get the joint indices by joint names and cache them in the unique data
// so that we don't have to look them up at runtime.
UniqueData::MaskInstance& maskInstance = m_maskInstances[maskInstanceIndex];
AnimGraphPropertyUtils::ReinitJointIndices(actor, mask.m_jointNames, maskInstance.m_jointIndices);
maskInstance.m_inputPortNr = inputPortNr;
// Check if the motion extraction node is part of this mask and cache the mask index in that case.
for (AZ::u32 jointIndex : maskInstance.m_jointIndices)
{
if (jointIndex == motionExtractionJointIndex)
{
m_motionExtractionInputPortNr = inputPortNr;
break;
}
}
maskInstanceIndex++;
}
}
}
BlendTreeMaskNode::BlendTreeMaskNode()
: AnimGraphNode()
{
m_masks.resize(s_numMasks);
// Setup the input ports.
InitInputPorts(1 + static_cast<AZ::u32>(s_numMasks)); // Base pose and the input poses for the masks.
SetupInputPort("Base Pose", INPUTPORT_BASEPOSE, AttributePose::TYPE_ID, INPUTPORT_BASEPOSE);
for (size_t i = 0; i < s_numMasks; ++i)
{
const AZ::u32 portNr = static_cast<AZ::u32>(i + INPUTPORT_START);
SetupInputPort(
AZStd::string::format("Pose %zu", i).c_str(),
portNr,
AttributePose::TYPE_ID,
portNr);
}
// Setup the output ports.
InitOutputPorts(1);
SetupOutputPortAsPose("Output Pose", OUTPUTPORT_RESULT, PORTID_OUTPUT_RESULT);
ActorNotificationBus::Handler::BusConnect();
}
BlendTreeMaskNode::~BlendTreeMaskNode()
{
ActorNotificationBus::Handler::BusDisconnect();
}
void BlendTreeMaskNode::Reinit()
{
AZ::u8 maskCounter = 0;
for (Mask& mask : m_masks)
{
mask.m_maskIndex = maskCounter;
mask.m_parent = this;
maskCounter++;
}
AnimGraphNode::Reinit();
}
bool BlendTreeMaskNode::InitAfterLoading(AnimGraph* animGraph)
{
if (!AnimGraphNode::InitAfterLoading(animGraph))
{
return false;
}
InitInternalAttributesForAllInstances();
Reinit();
return true;
}
void BlendTreeMaskNode::OnMotionExtractionNodeChanged(Actor* actor, Node* newMotionExtractionNode)
{
if (!mAnimGraph)
{
return;
}
bool needsReinit = false;
const size_t numAnimGraphInstances = mAnimGraph->GetNumAnimGraphInstances();
for (size_t i = 0; i < numAnimGraphInstances; ++i)
{
AnimGraphInstance* animGraphInstance = mAnimGraph->GetAnimGraphInstance(i);
if (actor == animGraphInstance->GetActorInstance()->GetActor())
{
needsReinit = true;
break;
}
}
if (needsReinit)
{
Reinit();
}
}
void BlendTreeMaskNode::Output(AnimGraphInstance* animGraphInstance)
{
UniqueData* uniqueData = static_cast<UniqueData*>(FindOrCreateUniqueNodeData(animGraphInstance));
RequestPoses(animGraphInstance);
AnimGraphPose* outputAnimGraphPose = GetOutputPose(animGraphInstance, OUTPUTPORT_RESULT)->GetValue();
Pose& outputPose = outputAnimGraphPose->GetPose();
// Use the input base pose as starting pose to apply the masks onto.
AnimGraphNode* basePoseNode = GetInputNode(INPUTPORT_BASEPOSE);
if (basePoseNode)
{
OutputIncomingNode(animGraphInstance, basePoseNode);
*outputAnimGraphPose = *basePoseNode->GetMainOutputPose(animGraphInstance);
}
else
{
// Use bindpose in case no base pose node is connected.
outputAnimGraphPose->InitFromBindPose(animGraphInstance->GetActorInstance());
}
// Iterate over the non-empty masks and copy over its transforms.
for (const UniqueData::MaskInstance& maskInstance : uniqueData->m_maskInstances)
{
const AZ::u32 inputPortNr = maskInstance.m_inputPortNr;
AnimGraphNode* inputNode = GetInputNode(inputPortNr);
if (inputNode)
{
OutputIncomingNode(animGraphInstance, inputNode);
const Pose& inputPose = GetInputPose(animGraphInstance, inputPortNr)->GetValue()->GetPose();
for (AZ::u32 jointIndex : maskInstance.m_jointIndices)
{
outputPose.SetLocalSpaceTransform(jointIndex, inputPose.GetLocalSpaceTransform(jointIndex));
}
}
}
if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance))
{
animGraphInstance->GetActorInstance()->DrawSkeleton(outputAnimGraphPose->GetPose(), mVisualizeColor);
}
}
void BlendTreeMaskNode::Update(AnimGraphInstance* animGraphInstance, float timePassedInSeconds)
{
UniqueData* uniqueData = static_cast<UniqueData*>(FindOrCreateUniqueNodeData(animGraphInstance));
AnimGraphNode* basePoseNode = GetInputNode(INPUTPORT_BASEPOSE);
if (basePoseNode)
{
basePoseNode->PerformUpdate(animGraphInstance, timePassedInSeconds);
uniqueData->Init(animGraphInstance, basePoseNode);
}
else
{
uniqueData->Clear();
}
for (const UniqueData::MaskInstance& maskInstance : uniqueData->m_maskInstances)
{
AnimGraphNode* inputNode = GetInputNode(maskInstance.m_inputPortNr);
if (inputNode)
{
inputNode->PerformUpdate(animGraphInstance, timePassedInSeconds);
}
}
}
void BlendTreeMaskNode::PostUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds)
{
RequestRefDatas(animGraphInstance);
UniqueData* uniqueData = static_cast<UniqueData*>(FindOrCreateUniqueNodeData(animGraphInstance));
AnimGraphRefCountedData* data = uniqueData->GetRefCountedData();
data->ClearEventBuffer();
data->ZeroTrajectoryDelta();
AnimGraphNode* basePoseNode = GetInputNode(INPUTPORT_BASEPOSE);
if (basePoseNode)
{
basePoseNode->PerformPostUpdate(animGraphInstance, timePassedInSeconds);
const AnimGraphNodeData* basePoseNodeUniqueData = basePoseNode->FindOrCreateUniqueNodeData(animGraphInstance);
data->SetEventBuffer(basePoseNodeUniqueData->GetRefCountedData()->GetEventBuffer());
}
const size_t numMaskInstances = uniqueData->m_maskInstances.size();
for (size_t i = 0; i < numMaskInstances; ++i)
{
const UniqueData::MaskInstance& maskInstance = uniqueData->m_maskInstances[i];
const AZ::u32 inputPortNr = maskInstance.m_inputPortNr;
AnimGraphNode* inputNode = GetInputNode(inputPortNr);
if (!inputNode)
{
continue;
}
inputNode->PerformPostUpdate(animGraphInstance, timePassedInSeconds);
// If we want to output events for this input, add the incoming events to the output event buffer.
if (GetOutputEvents(inputPortNr))
{
const AnimGraphEventBuffer& inputEventBuffer = inputNode->FindOrCreateUniqueNodeData(animGraphInstance)->GetRefCountedData()->GetEventBuffer();
AnimGraphEventBuffer& outputEventBuffer = data->GetEventBuffer();
outputEventBuffer.AddAllEventsFrom(inputEventBuffer);
}
}
// Apply motion extraction delta from either the base pose or one of the masks depending on if a mask has the joint set or not.
bool motionExtractionApplied = false;
if (uniqueData->m_motionExtractionInputPortNr.has_value())
{
AnimGraphNode* inputNode = GetInputNode(uniqueData->m_motionExtractionInputPortNr.value());
if (inputNode)
{
AnimGraphRefCountedData* sourceData = inputNode->FindOrCreateUniqueNodeData(animGraphInstance)->GetRefCountedData();
data->SetTrajectoryDelta(sourceData->GetTrajectoryDelta());
data->SetTrajectoryDeltaMirrored(sourceData->GetTrajectoryDeltaMirrored());
motionExtractionApplied = true;
}
}
// In case the motion extraction node is not part of any of the masks while the base pose is connected, use that as a fallback.
if (!motionExtractionApplied && basePoseNode)
{
AnimGraphRefCountedData* sourceData = basePoseNode->FindOrCreateUniqueNodeData(animGraphInstance)->GetRefCountedData();
data->SetTrajectoryDelta(sourceData->GetTrajectoryDelta());
data->SetTrajectoryDeltaMirrored(sourceData->GetTrajectoryDeltaMirrored());
}
}
size_t BlendTreeMaskNode::GetNumUsedMasks() const
{
size_t result = 0;
for (const Mask& mask : m_masks)
{
if (!mask.m_jointNames.empty())
{
result++;
}
}
return result;
}
AZStd::string BlendTreeMaskNode::GetMaskJointName(size_t maskIndex, size_t jointIndex) const
{
return m_masks[maskIndex].m_jointNames[jointIndex];
}
bool BlendTreeMaskNode::GetOutputEvents(size_t inputPortNr) const
{
if (inputPortNr > INPUTPORT_BASEPOSE)
{
return m_masks[inputPortNr - INPUTPORT_START].m_outputEvents;
}
return true;
}
void BlendTreeMaskNode::SetMask(size_t maskIndex, const AZStd::vector<AZStd::string>& jointNames)
{
m_masks[maskIndex].m_jointNames = jointNames;
}
void BlendTreeMaskNode::SetOutputEvents(size_t maskIndex, bool outputEvents)
{
m_masks[maskIndex].m_outputEvents = outputEvents;
}
void BlendTreeMaskNode::Mask::Reinit()
{
if (m_parent)
{
m_parent->Reinit();
}
}
AZStd::string BlendTreeMaskNode::Mask::GetMaskName() const
{
return AZStd::string::format("GetMask %d", m_maskIndex);
}
AZStd::string BlendTreeMaskNode::Mask::GetOutputEventsName() const
{
return AZStd::string::format("Output Events %d", m_maskIndex);
}
void BlendTreeMaskNode::Mask::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<Mask>()
->Version(1)
->Field("jointNames", &BlendTreeMaskNode::Mask::m_jointNames)
->Field("outputEvents", &BlendTreeMaskNode::Mask::m_outputEvents)
;
AZ::EditContext* editContext = serializeContext->GetEditContext();
if (editContext)
{
editContext->Class<Mask>("Pose Mask Node", "Pose mask attributes")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::AutoExpand, "")
->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
->DataElement(AZ_CRC("ActorNodes", 0x70504714), &BlendTreeMaskNode::Mask::m_jointNames, "Mask", "The mask to apply.")
->Attribute(AZ::Edit::Attributes::ContainerCanBeModified, false)
->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::HideChildren)
->Attribute(AZ::Edit::Attributes::NameLabelOverride, &BlendTreeMaskNode::Mask::GetMaskName)
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
->Attribute(AZ::Edit::Attributes::ChangeNotify, &BlendTreeMaskNode::Mask::Reinit)
->DataElement(AZ::Edit::UIHandlers::Default, &BlendTreeMaskNode::Mask::m_outputEvents, "Output Events", "Output events.")
->Attribute(AZ::Edit::Attributes::NameLabelOverride, &BlendTreeMaskNode::Mask::GetOutputEventsName)
;
}
}
}
void BlendTreeMaskNode::Reflect(AZ::ReflectContext* context)
{
BlendTreeMaskNode::Mask::Reflect(context);
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (serializeContext)
{
serializeContext->Class<BlendTreeMaskNode, AnimGraphNode>()
->Version(1)
->Field("masks", &BlendTreeMaskNode::m_masks)
;
AZ::EditContext* editContext = serializeContext->GetEditContext();
if (editContext)
{
editContext->Class<BlendTreeMaskNode>("Pose Mask", "Pose mark attributes")
->ClassElement(AZ::Edit::ClassElements::EditorData, "")
->Attribute(AZ::Edit::Attributes::AutoExpand, "")
->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
->DataElement(AZ::Edit::UIHandlers::Default, &BlendTreeMaskNode::m_masks, "Masks", "The mask to apply on the Pose 1 input port.")
->Attribute(AZ::Edit::Attributes::ChangeNotify, &BlendTreeMaskNode::Reinit)
->Attribute(AZ::Edit::Attributes::ContainerCanBeModified, false)
->Attribute(AZ::Edit::Attributes::AutoExpand, true)
->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
;
}
}
}
} // namespace EMotionFX
| 40.380835 | 159 | 0.63024 | [
"vector"
] |
b8464a766d21e93426eb4a00b8caab2af5470055 | 2,242 | cc | C++ | paddle/fluid/inference/anakin/convert/split.cc | panyx0718/Paddle | 1ebd7434d545f8c439792468298f1108b631668e | [
"Apache-2.0"
] | null | null | null | paddle/fluid/inference/anakin/convert/split.cc | panyx0718/Paddle | 1ebd7434d545f8c439792468298f1108b631668e | [
"Apache-2.0"
] | null | null | null | paddle/fluid/inference/anakin/convert/split.cc | panyx0718/Paddle | 1ebd7434d545f8c439792468298f1108b631668e | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/inference/anakin/convert/split.h"
#include <algorithm>
#include <vector>
using anakin::graph::GraphGlobalMem;
using anakin::AK_FLOAT;
using anakin::Precision;
using anakin::saber::NV;
using anakin::saber::X86;
using anakin::saber::Shape;
using anakin::PBlock;
using anakin::PTuple;
namespace paddle {
namespace inference {
namespace anakin {
void SplitOpConverter::operator()(const framework::proto::OpDesc &op,
const framework::Scope &scope,
bool test_mode) {
framework::OpDesc op_desc(op, nullptr);
auto input_name = op_desc.Input("X").front();
auto y_names = op_desc.Output("Out");
auto op_name = op_desc.Type() + ":" + op_desc.Output("Out").front();
int axis = boost::get<int>(op_desc.GetAttr("axis"));
std::vector<int> output_lengths =
boost::get<std::vector<int>>(op_desc.GetAttr("sections"));
int split_num = output_lengths.size();
PADDLE_ENFORCE(split_num > 1,
"anakin split op converter: the split num should > 1");
int num_sum = 0;
std::vector<int> slice_point;
for (int i = 0; i < split_num - 1; i++) {
num_sum += output_lengths[i];
slice_point.push_back(num_sum);
}
engine_->AddOp(op_name, "Slice", {input_name}, y_names);
engine_->AddOpAttr(op_name, "axis", axis);
engine_->AddOpAttr<PTuple<int>>(op_name, "slice_point", slice_point);
// slice_dim is useless in anakin
engine_->AddOpAttr(op_name, "slice_dim", 4);
}
} // namespace anakin
} // namespace inference
} // namespace paddle
REGISTER_ANAKIN_OP_CONVERTER(split, SplitOpConverter);
| 35.03125 | 75 | 0.694915 | [
"shape",
"vector"
] |
b8486755ba0222c68320742c17da5b0685656f5f | 248 | hpp | C++ | include/exec.hpp | zawwz/lxsh | 2d0041e1ff4d62fdf657ce8ba5c2af6454be6f15 | [
"MIT"
] | 1 | 2021-05-13T15:32:04.000Z | 2021-05-13T15:32:04.000Z | include/exec.hpp | zawwz/lxsh | 2d0041e1ff4d62fdf657ce8ba5c2af6454be6f15 | [
"MIT"
] | null | null | null | include/exec.hpp | zawwz/lxsh | 2d0041e1ff4d62fdf657ce8ba5c2af6454be6f15 | [
"MIT"
] | null | null | null | #ifndef EXEC_HPP
#define EXEC_HPP
#include "options.hpp"
#include "parse.hpp"
void parse_exec(FILE* fd, parse_context ct);
int exec_process(std::string const& runtime, std::vector<std::string> const& args, parse_context ct);
#endif //EXEC_HPP
| 19.076923 | 101 | 0.75 | [
"vector"
] |
b84f44b030e6b7e74dda1bad75e42f15c4df114d | 1,770 | cpp | C++ | Problem Solving with C++/Source Code/Chapter11/11-10.cpp | MorganBergen/Learning-CPP | a8d8ed92a6e4cb6c96d091d6c7e1ef551968932b | [
"Unlicense"
] | null | null | null | Problem Solving with C++/Source Code/Chapter11/11-10.cpp | MorganBergen/Learning-CPP | a8d8ed92a6e4cb6c96d091d6c7e1ef551968932b | [
"Unlicense"
] | null | null | null | Problem Solving with C++/Source Code/Chapter11/11-10.cpp | MorganBergen/Learning-CPP | a8d8ed92a6e4cb6c96d091d6c7e1ef551968932b | [
"Unlicense"
] | null | null | null | //DISPLAY 11.10 Program for a Class with an Array Member
//This is the definition for a class TemperatureList.
//Values of this type are lists of Fahrenheit temperatures.
#include <iostream>
#include <cstdlib>
using namespace std;
const int MAX_LIST_SIZE = 50;
class TemperatureList
{
public:
TemperatureList( );
//Initializes the object to an empty list.
void addTemperature(double temperature);
//Precondition: The list is not full.
//Postcondition: The temperature has been added to the list.
bool full( ) const;
//Returns true if the list is full; false otherwise.
friend ostream& operator <<(ostream& outs,
const TemperatureList& theObject);
//Overloads the << operator so it can be used to output values of
//type TemperatureList. Temperatures are output one per line.
//Precondition: If outs is a file output stream, then outs
//has already been connected to a file.
private:
double list[MAX_LIST_SIZE]; //of temperatures in Fahrenheit
int size; //number of array positions filled
};
//This is the implementation for the class TemperatureList.
TemperatureList::TemperatureList( ) : size(0)
{
//Body intentionally empty.
}
void TemperatureList::addTemperature(double temperature)
{//Uses iostream and cstdlib:
if ( full( ) )
{
cout << "Error: adding to a full list.\n";
exit(1);
}
else
{
list[size] = temperature;
size = size + 1;
}
}
bool TemperatureList::full( ) const
{
return (size == MAX_LIST_SIZE);
}
//Uses iostream:
ostream& operator <<(ostream& outs, const TemperatureList& theObject)
{
for (int i = 0; i < theObject.size; i++)
outs << theObject.list[i] << " F\n";
return outs;
}
| 26.41791 | 70 | 0.670621 | [
"object"
] |
b8562debd461dab9fcda132269df3d11301f2598 | 7,333 | cpp | C++ | tools/CLIOptions/CLIOptions.cpp | m42e/mull | 32c6416d1757ea19c345029ee7a83e5769f231ef | [
"Apache-2.0"
] | null | null | null | tools/CLIOptions/CLIOptions.cpp | m42e/mull | 32c6416d1757ea19c345029ee7a83e5769f231ef | [
"Apache-2.0"
] | null | null | null | tools/CLIOptions/CLIOptions.cpp | m42e/mull | 32c6416d1757ea19c345029ee7a83e5769f231ef | [
"Apache-2.0"
] | null | null | null | #include "CLIOptions.h"
#include <mull/Diagnostics/Diagnostics.h>
#include <mull/Mutators/Mutator.h>
#include <mull/Reporters/IDEReporter.h>
#include <mull/Reporters/MutationTestingElementsReporter.h>
#include <mull/Reporters/SQLiteReporter.h>
#include <mull/Reporters/PatchesReporter.h>
#include <mull/Reporters/GithubAnnotationsReporter.h>
using namespace mull;
using namespace tool;
using namespace llvm::cl;
MutatorsCLIOptions::MutatorsCLIOptions(Diagnostics &diagnostics,
list<MutatorsOptionIndex> ¶meter)
: factory(diagnostics), options(factory.commandLineOptions()), parameter(parameter) {
int index = 0;
for (auto &option : options) {
parameter.getParser().addLiteralOption(option.first.c_str(), index++, option.second.c_str());
}
}
std::vector<std::unique_ptr<Mutator>> MutatorsCLIOptions::mutators() {
std::vector<std::string> selectedGroups;
for (int i = 0; i < parameter.size(); i++) {
auto &name = parameter[i];
selectedGroups.push_back(options[name].first);
}
return factory.mutators(selectedGroups);
}
std::vector<std::pair<std::string, std::string>> &MutatorsCLIOptions::getOptions() {
return options;
}
struct ReporterDefinition {
std::string name;
std::string description;
ReporterKind kind;
};
static std::vector<ReporterDefinition> reporterOptions({
{ "IDE", "Prints compiler-like warnings into stdout", ReporterKind::IDE },
{ "SQLite", "Saves results into an SQLite database", ReporterKind::SQLite },
{ "Elements",
"Generates mutation-testing-elements compatible JSON file",
ReporterKind::Elements },
{ "Patches", "Generates patch file for each mutation", ReporterKind::Patches },
{ "GithubAnnotations", "Print GithubAnnotations for mutants", ReporterKind::GithubAnnotations },
});
ReportersCLIOptions::ReportersCLIOptions(Diagnostics &diagnostics, list<ReporterKind> ¶meter)
: diagnostics(diagnostics), parameter(parameter) {
for (ReporterDefinition &opt : reporterOptions) {
parameter.getParser().addLiteralOption(opt.name.c_str(), opt.kind, opt.description.c_str());
}
}
std::vector<std::unique_ptr<Reporter>> ReportersCLIOptions::reporters(ReporterParameters params) {
std::vector<std::unique_ptr<mull::Reporter>> reporters;
std::string &name = params.reporterName;
std::string &directory = params.reporterDirectory;
// TODO: Move to a better place
for (auto i = 0; i < parameter.getNumOccurrences(); i++) {
switch (parameter[i]) {
case ReporterKind::IDE: {
reporters.emplace_back(new mull::IDEReporter(diagnostics, params.IDEReporterShowKilled));
} break;
case ReporterKind::SQLite: {
reporters.emplace_back(new mull::SQLiteReporter(diagnostics, directory, name, params.mullInformation));
} break;
case ReporterKind::Patches: {
reporters.emplace_back(new mull::PatchesReporter(diagnostics, directory, name, params.patchBasePathDir, params.mullInformation));
} break;
case ReporterKind::GithubAnnotations: {
reporters.emplace_back(new mull::GithubAnnotationsReporter(diagnostics));
} break;
case ReporterKind::Elements: {
if (!params.compilationDatabaseAvailable) {
diagnostics.warning("Mutation Testing Elements Reporter may not work without compilation "
"database. Consider providing -compdb-path or -compilation-flags.");
}
reporters.emplace_back(
new mull::MutationTestingElementsReporter(diagnostics, directory, name, params.mullInformation));
} break;
}
}
if (reporters.empty()) {
reporters.emplace_back(new mull::IDEReporter(diagnostics, params.IDEReporterShowKilled));
}
return reporters;
}
static void sanitizeString(std::string &input, const std::string &replacement) {
std::string escape("\\");
auto pos = input.find(replacement);
if (pos != std::string::npos) {
input.replace(pos, replacement.size(), escape + replacement);
}
}
static std::string sanitizeString(const std::string &input) {
std::string result = input;
sanitizeString(result, "|=");
sanitizeString(result, "*=");
return result;
}
void dumpCLIOption(std::stringstream &stream, llvm::cl::Option *option) {
stream << "--" << option->ArgStr.str();
if (!option->ValueStr.empty()) {
stream << " " << option->ValueStr.str();
}
stream << "\t\t" << option->HelpStr.str();
stream << "\n\n";
}
void dumpCLIReporters(std::stringstream &stream) {
for (ReporterDefinition &opt : reporterOptions) {
stream << " :" << opt.name << ":\t" << opt.description << "\n\n";
}
}
void dumpCLIMutators(std::stringstream &stream, mull::Diagnostics &diagnostics) {
MutatorsFactory factory(diagnostics);
factory.init();
stream << " Groups:\n";
for (const auto &pair : factory.getGroupsMapping()) {
stream << " :" << pair.first << ":\t" << MutatorsFactory::descriptionForGroup(pair.second)
<< "\n\n";
}
stream << " Single mutators:\n";
for (const auto &pair : factory.getMutatorsMapping()) {
stream << " :" << pair.first << ":\t" << sanitizeString(pair.second->getDescription())
<< "\n\n";
}
}
void tool::dumpCLIInterface(mull::Diagnostics &diagnostics,
const std::vector<llvm::cl::Option *> &options,
llvm::cl::Option *reporters, llvm::cl::Option *mutators) {
std::stringstream help;
for (llvm::cl::Option *option : options) {
dumpCLIOption(help, option);
if (option == mutators) {
dumpCLIMutators(help, diagnostics);
}
if (option == reporters) {
dumpCLIReporters(help);
}
}
llvm::outs() << help.str();
}
void tool::dumpMutators(Diagnostics &diagnostics) {
MutatorsFactory factory(diagnostics);
factory.init();
std::vector<Mutator *> availableMutators;
for (const auto &pair : factory.getMutatorsMapping()) {
availableMutators.push_back(pair.second.get());
}
std::sort(availableMutators.begin(), availableMutators.end(), [&](Mutator *lhs, Mutator *rhs) {
return lhs->getUniqueIdentifier() < rhs->getUniqueIdentifier();
});
std::stringstream replacements;
std::stringstream table;
std::string firstHeaderName("Operator Name");
std::string firstHeader(firstHeaderName.size(), '=');
std::string secondHeaderName("Operator Semantics");
std::string secondHeader(secondHeaderName.size(), '=');
table << firstHeader << " " << secondHeader << "\n";
table << firstHeaderName << " " << secondHeaderName << "\n";
table << firstHeader << " " << secondHeader << "\n";
for (size_t i = 0; i < availableMutators.size(); i++) {
Mutator *mutator = availableMutators[i];
std::string n = std::to_string(i);
std::string name("op" + n);
std::string description("desc" + n);
std::string padding(firstHeader.size() - name.size() - 1, ' ');
table << "|" << name << "|" << padding << "|" << description << "|\n";
replacements << ".. |" << name << "| replace:: " << mutator->getUniqueIdentifier() << "\n";
replacements << ".. |" << description
<< "| replace:: " << sanitizeString(mutator->getDescription()) << "\n";
}
replacements << "\n\n";
table << firstHeader << " " << secondHeader << "\n";
llvm::outs() << replacements.str();
llvm::outs() << table.str();
}
| 35.086124 | 135 | 0.666712 | [
"vector"
] |
b85e1a68427b0938b416a7424cee012120fab493 | 5,763 | cxx | C++ | Tracing/trace_srcCUDA/trace_src/SeedContainer3D.cxx | tostathaina/farsight | 7e9d6d15688735f34f7ca272e4e715acd11473ff | [
"Apache-2.0"
] | 8 | 2016-07-22T11:24:19.000Z | 2021-04-10T04:22:31.000Z | Tracing/trace_srcCUDA/trace_src/SeedContainer3D.cxx | YanXuHappygela/Farsight | 1711b2a1458c7e035edd21fe0019a1f7d23fcafa | [
"Apache-2.0"
] | null | null | null | Tracing/trace_srcCUDA/trace_src/SeedContainer3D.cxx | YanXuHappygela/Farsight | 1711b2a1458c7e035edd21fe0019a1f7d23fcafa | [
"Apache-2.0"
] | 7 | 2016-07-21T07:39:17.000Z | 2020-01-29T02:03:27.000Z | //////////////////////////////////////////////////////////////
//Seed points begin as "interest points" consisting of local
//extremum detected on a regular grid. Two options are
//available, full 3-d grid search, or 2-d grid search on
//projection image followed by localization in the z-direction.
#include "SeedContainer3D.h"
#include "itkImageFileWriter.h"
#include <itkImageLinearIteratorWithIndex.h>
#include <itkImageSliceConstIteratorWithIndex.h>
SeedContainer3D::SeedContainer3D() {
}
SeedContainer3D::~SeedContainer3D() {
std::vector<SeedPoint3D *>::iterator it;
for (it = SeedContainer.begin(); it != SeedContainer.end(); ++it)
delete *it;
}
void SeedContainer3D::Configure(TraceConfig::Pointer m_Config) {
this->GridSpacing = m_Config->getGridSpacing();
this->IntensityThreshold = m_Config->getSeedIntensityThreshold();
}
//currently using the project, detect and localize method
void SeedContainer3D::Detect(ImageType3D::Pointer im3D, ImageType2D::Pointer im2D) {
//Obtian the MIP
MIPGenerator(im3D, im2D);
//Detect3Dseeds(im3D);
Detect2Dseeds(im2D);
LocateZPosition(im3D);
}
//search full 3d grid, may require fine grid and has a tendency to
//overgenerate, not the preferred method
void SeedContainer3D::Detect3Dseeds(ImageType3D::Pointer image) {
ImageType3D::IndexType glndx = {{0 , 0 , 0}};
ImageType3D::SizeType sz = image->GetBufferedRegion().GetSize();
for (glndx[2] = 0; glndx[2] < sz[2]-GridSpacing; glndx[2] += GridSpacing) {
for (glndx[1] = 0; glndx[1] < sz[1]-GridSpacing; glndx[1] += GridSpacing) {
for (glndx[0] = 0; glndx[0] < sz[0]-GridSpacing; glndx[0] += GridSpacing) {
ImageType3D::IndexType ndx = glndx;
ImageType3D::IndexType endx;
endx[0] = glndx[0] + GridSpacing; endx[0] = (endx[0]>sz[0]) ? sz[0] : endx[0];
endx[1] = glndx[1] + GridSpacing; endx[1] = (endx[1]>sz[1]) ? sz[1] : endx[1];
endx[2] = glndx[2] + GridSpacing; endx[2] = (endx[2]>sz[2]) ? sz[2] : endx[2];
ImageType3D::PixelType minVal = 255;
ImageType3D::IndexType minNdx;
for ( ndx[2] = glndx[2] ; ndx[2] < endx[2] ; ndx[2]++) {
for ( ndx[1] = glndx[1] ; ndx[1] < endx[1] ; ndx[1]++) {
for ( ndx[0] = glndx[0] ; ndx[0] < endx[0] ; ndx[0]++) {
ImageType3D::PixelType val = image->GetPixel(ndx);
if (val<minVal) {
minVal = val;
minNdx = ndx;
}
}
}
}
//store the index, val, and scale here
AddSeedPoint(minNdx, minVal, GridSpacing);
}
}
}
}
//detect extremum from projection image
void SeedContainer3D::Detect2Dseeds(ImageType2D::Pointer image) {
ImageType2D::RegionType::SizeType size = image->GetRequestedRegion().GetSize();
ImageType2D::RegionType::IndexType p, pmin;
float val, m = 1000.0f;
std::cout << "Detecting Seeds ...";
for ( p[0] = 0; p[0] <size[0] ; p[0]+=GridSpacing) {
for ( p[1] = 0; p[1] <size[1] ; p[1]++) {
val = image->GetPixel(p);
if(val < m) {
m = val;
pmin = p;
}
if(!(p[1]%GridSpacing) && (p[1]>0)) {
AddSeedPoint(pmin, m);
m = 1000.0f;
}
}
}
for ( p[1] = 0; p[1] <size[1] ; p[1]+=GridSpacing) {
for ( p[0] = 0; p[0] <size[0] ; p[0]++) {
val = image->GetPixel(p);
if(val < m) {
m = val;
pmin = p;
}
if(!(p[0]%GridSpacing) && (p[0]>0)) {
AddSeedPoint(pmin, m);
m = 1000.0f;
}
}
}
//std::cout <<SeedContainer.size() <<" seeds found!!"<< std::endl;
}
void SeedContainer3D::AddSeedPoint(ImageType2D::RegionType::IndexType ndx, const float& mn) {
SeedPoint3D *s = new SeedPoint3D();
s->setXYPosition(ndx);
s->setScale(static_cast<float>(GridSpacing)/4);
this->SeedContainer.push_back(s);
//std::cout <<"Seed detected at " << ndx << " Value" << mn <<std::endl;
}
void SeedContainer3D::AddSeedPoint(ImageType3D::IndexType ndx, ImageType3D::PixelType val, long grid) {
SeedPoint3D *s = new SeedPoint3D();
s->setSeed3D(ndx, val, grid);
this->SeedContainer.push_back(s);
}
//generate intensity projection
void SeedContainer3D::MIPGenerator(ImageType3D::Pointer im3D, ImageType2D::Pointer& im2D) {
ImageType3D::SizeType sz3 = im3D->GetRequestedRegion().GetSize();
ImageType2D::SizeType sz2 = {{sz3[0], sz3[1] }};
//im2D = ImageType2D::New(); // new is already done in
im2D->SetRegions(sz2 );
im2D->Allocate();
for (unsigned long x=0; x<sz3[0]; x++) {
for (unsigned long y=0; y<sz3[1]; y++) {
//ImageType3D::PixelType maxVal = 0.0;
ImageType3D::PixelType minVal = 255.0;
for (unsigned long z=0; z<sz3[2]; z++) {
ImageType3D::IndexType nd3 = {{x,y,z}};
ImageType3D::PixelType val = im3D->GetPixel(nd3);
// maxVal = (maxVal > val) ? maxVal : val;
minVal = (minVal < val) ? minVal : val;
}
ImageType2D::IndexType nd2 = {{x, y}};
//im2D->SetPixel(nd2, maxVal);
im2D->SetPixel(nd2, minVal);
}
}
/* itk::ImageFileWriter<ImageType2D>::Pointer wt = itk::ImageFileWriter<ImageType2D>::New();
wt->SetFileName("MIP.mhd");
wt->SetInput(im2D);
wt->Update();
*/
std::cout <<"MIP Generated!!" <<std::endl;
}
//find extrumum in z direction
void SeedContainer3D::LocateZPosition(ImageType3D::Pointer im3D) {
std::vector <SeedPoint3D *>::iterator it;
ImageType3D::RegionType::SizeType sz = im3D->GetRequestedRegion().GetSize();
ImageType3D::RegionType::IndexType ndx;
float currentValue, miniminValue = 255;
unsigned int minimumNdx = 0;
for (it = SeedContainer.begin(); it!= SeedContainer.end(); ++it) {
ndx = (*it)->getIndex();
miniminValue = 255;
for (unsigned int i = 0; i < sz[2]; i++) {
ndx[2] = i;
currentValue = im3D->GetPixel(ndx);
if (currentValue < miniminValue) {
miniminValue = currentValue;
minimumNdx = i;
}
}
(*it)->setZPosition(minimumNdx);
(*it)->setIntensity(miniminValue);
}
}
| 29.106061 | 103 | 0.635259 | [
"vector",
"3d"
] |
b8631a3ec146847360dfa77d58ad418abe0cfe55 | 507 | hpp | C++ | libs/core/render/include/bksge/core/render/fwd/spirv_reflection_fwd.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/core/render/include/bksge/core/render/fwd/spirv_reflection_fwd.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/core/render/include/bksge/core/render/fwd/spirv_reflection_fwd.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file spirv_reflection_fwd.hpp
*
* @brief SpirvReflection の前方宣言
*
* @author myoukaku
*/
#ifndef BKSGE_CORE_RENDER_FWD_SPIRV_REFLECTION_FWD_HPP
#define BKSGE_CORE_RENDER_FWD_SPIRV_REFLECTION_FWD_HPP
namespace bksge
{
namespace render
{
struct SpirvReflectionUniform;
class SpirvReflection;
} // namespace render
using render::SpirvReflectionUniform;
using render::SpirvReflection;
} // namespace bksge
#endif // BKSGE_CORE_RENDER_FWD_SPIRV_REFLECTION_FWD_HPP
| 17.482759 | 57 | 0.761341 | [
"render"
] |
b86358fee7dd44a172c4dad76ea59c1428dbf6f9 | 1,655 | cpp | C++ | PC_Practica_18-nov-21/dungeon_game.cpp | MisaelVM/ProgComp2021B | 6134ae425a4c1a4f087bc1e14615d1f06979beff | [
"BSD-3-Clause"
] | null | null | null | PC_Practica_18-nov-21/dungeon_game.cpp | MisaelVM/ProgComp2021B | 6134ae425a4c1a4f087bc1e14615d1f06979beff | [
"BSD-3-Clause"
] | null | null | null | PC_Practica_18-nov-21/dungeon_game.cpp | MisaelVM/ProgComp2021B | 6134ae425a4c1a4f087bc1e14615d1f06979beff | [
"BSD-3-Clause"
] | null | null | null | #include <bits/stdc++.h>
int calculateMinimumHP_memoized(std::vector<std::vector<int>>& dungeon, int i, int j, int m, int n, std::vector<std::vector<int>>& memo) {
if (memo[i][j] != INT_MIN)
return memo[i][j];
int result;
int health_to_be_lost;
if (i == m - 1 && j == n - 1)
health_to_be_lost = 0;
else if (i == m - 1)
health_to_be_lost = calculateMinimumHP_memoized(dungeon, i, j + 1, m, n, memo);
else if (j == n - 1)
health_to_be_lost = calculateMinimumHP_memoized(dungeon, i + 1, j, m, n, memo);
else {
int tmp1 = calculateMinimumHP_memoized(dungeon, i, j + 1, m, n, memo);
int tmp2 = calculateMinimumHP_memoized(dungeon, i + 1, j, m, n, memo);
health_to_be_lost = std::max(tmp1, tmp2);
}
result = std::min(dungeon[i][j], health_to_be_lost + dungeon[i][j]);
memo[i][j] = result;
return result;
}
int calculateMinimumHP(std::vector<std::vector<int>>& dungeon) {
int m = dungeon.size();
int n = dungeon[0].size();
std::vector<std::vector<int>> memo(m, std::vector<int>(n, INT_MIN));
int health_to_be_lost = calculateMinimumHP_memoized(dungeon, 0, 0, m, n, memo);
return (health_to_be_lost > 0) ? 1 : 1 - health_to_be_lost;
}
int main()
{
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
std::vector<std::vector<int>> dungeon;
// Caso de prueba 1:
// Entrada:
// [[-2,-3,3],[-5,-10,1],[10,30,-5]]
// Salida:
// 7
//
dungeon = {
{ -2, -3, 3 },
{ -5, -10, 1 },
{ 10, 30, -5 }
};
std::cout << calculateMinimumHP(dungeon) << "\n";
// Caso de prueba 2:
// Entrada:
// [[0]]
// Salida:
// 1
//
dungeon = {
{ 0 }
};
std::cout << calculateMinimumHP(dungeon) << "\n";
return 0;
}
| 24.701493 | 138 | 0.616918 | [
"vector"
] |
b86a7e9f28f8caea3cf4c002d47122dd0bd45c19 | 6,406 | cc | C++ | mindspore/lite/src/runtime/kernel/opencl/kernel/activation.cc | fufunoyu/mindspore | 704e367ada35653e8144eb0528c714f4b0231508 | [
"Apache-2.0"
] | 2 | 2021-04-22T07:00:59.000Z | 2021-11-08T02:49:09.000Z | mindspore/lite/src/runtime/kernel/opencl/kernel/activation.cc | fufunoyu/mindspore | 704e367ada35653e8144eb0528c714f4b0231508 | [
"Apache-2.0"
] | 1 | 2020-12-29T06:46:38.000Z | 2020-12-29T06:46:38.000Z | mindspore/lite/src/runtime/kernel/opencl/kernel/activation.cc | kungfu-ml/mindspore | 3fa5dd4495f4071b701e7ff490b7085b8824aaaa | [
"Apache-2.0"
] | 1 | 2021-05-10T03:30:36.000Z | 2021-05-10T03:30:36.000Z | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <vector>
#include <map>
#include <string>
#include <set>
#include "src/runtime/kernel/opencl/kernel/activation.h"
#include "schema/model_generated.h"
#include "src/kernel_registry.h"
#include "src/runtime/runtime_api.h"
#include "include/errorcode.h"
#include "nnacl/fp32/common_func.h"
#include "src/runtime/kernel/opencl/cl/activation.cl.inc"
using mindspore::kernel::KERNEL_ARCH::kGPU;
using mindspore::lite::KernelRegistrar;
using mindspore::lite::RET_ERROR;
using mindspore::lite::RET_OK;
using mindspore::schema::ActivationType_LEAKY_RELU;
using mindspore::schema::ActivationType_RELU;
using mindspore::schema::ActivationType_RELU6;
using mindspore::schema::ActivationType_SIGMOID;
using mindspore::schema::ActivationType_TANH;
using mindspore::schema::PrimitiveType_Activation;
namespace mindspore::kernel {
int ActivationOpenClKernel::Init() {
in_size_ = in_tensors_[0]->shape().size();
out_size_ = out_tensors_[0]->shape().size();
size_t n, h, w, c;
if (in_size_ == 2) {
n = in_tensors_[0]->shape()[0];
c = in_tensors_[0]->shape()[1];
h = w = 1;
} else {
n = in_tensors_[0]->shape()[0];
h = in_tensors_[0]->shape()[1];
w = in_tensors_[0]->shape()[2];
c = in_tensors_[0]->shape()[3];
}
nhwc_shape_ = {n, h, w, c};
enable_fp16_ = ocl_runtime_->GetFp16Enable();
fp_size = enable_fp16_ ? sizeof(uint16_t) : sizeof(float);
if (in_size_ != 2 && in_size_ != 4) {
MS_LOG(ERROR) << "Activate fun only support dim=4 or 2, but your dim=" << in_size_;
return RET_ERROR;
}
std::map<int, std::vector<std::string>> Program_Kernel{
{ActivationType_LEAKY_RELU, std::vector<std::string>{"LEAKY_RELU", "LeakyRelu"}},
{ActivationType_RELU, std::vector<std::string>{"RELU", "Relu"}},
{ActivationType_SIGMOID, std::vector<std::string>{"SIGMOID", "Sigmoid"}},
{ActivationType_RELU6, std::vector<std::string>{"RELU6", "Relu6"}},
{ActivationType_TANH, std::vector<std::string>{"TANH", "Tanh"}}};
if (Program_Kernel.count(type_) == 0) {
MS_LOG(ERROR) << "schema::ActivationType:" << type_ << "not found";
return RET_ERROR;
}
std::string source = activation_source;
std::set<std::string> build_options;
ocl_runtime_->LoadSource(Program_Kernel[type_][0], source);
std::string kernel_name = Program_Kernel[type_][1];
ocl_runtime_->BuildKernel(kernel_, Program_Kernel[type_][0], kernel_name, build_options);
in_ori_format_ = in_tensors_[0]->GetFormat();
out_ori_format_ = out_tensors_[0]->GetFormat();
in_tensors_[0]->SetFormat(op_format_);
out_tensors_[0]->SetFormat(op_format_);
MS_LOG(DEBUG) << op_parameter_->name_ << " init Done!";
return RET_OK;
}
int ActivationOpenClKernel::Run() {
MS_LOG(DEBUG) << op_parameter_->name_ << " begin running!";
cl_int4 img2d_shape = GetImg2dShape();
int arg_idx = 0;
ocl_runtime_->SetKernelArg(kernel_, arg_idx++, in_tensors_[0]->data_c());
ocl_runtime_->SetKernelArg(kernel_, arg_idx++, out_tensors_[0]->data_c());
ocl_runtime_->SetKernelArg(kernel_, arg_idx++, img2d_shape);
if (type_ == ActivationType_LEAKY_RELU) {
ocl_runtime_->SetKernelArg(kernel_, arg_idx++, alpha_);
}
std::vector<size_t> local = {};
std::vector<size_t> global = {static_cast<size_t>(img2d_shape.s[1]), static_cast<size_t>(img2d_shape.s[2])};
auto ret = ocl_runtime_->RunKernel(kernel_, global, local, nullptr);
if (ret != RET_OK) {
MS_LOG(ERROR) << "Run kernel:" << op_parameter_->name_ << " fail.";
return RET_ERROR;
}
return RET_OK;
}
cl_int4 ActivationOpenClKernel::GetImg2dShape() {
cl_int4 img2d_shape = {1, 1, 1, 1};
if (op_format_ == schema::Format_NHWC4) {
img2d_shape.s[1] = nhwc_shape_[1];
img2d_shape.s[2] = nhwc_shape_[2] * UP_DIV(nhwc_shape_[3], C4NUM);
img2d_shape.s[3] = C4NUM;
}
if (op_format_ == schema::Format_NC4HW4) {
img2d_shape.s[1] = UP_DIV(nhwc_shape_[3], C4NUM) * nhwc_shape_[1];
img2d_shape.s[2] = nhwc_shape_[2];
img2d_shape.s[3] = C4NUM;
}
return img2d_shape;
}
int ActivationOpenClKernel::GetImageSize(size_t idx, std::vector<size_t> *img_size) {
cl_int4 img_shape = GetImg2dShape();
size_t img_dtype = CL_FLOAT;
if (enable_fp16_) {
img_dtype = CL_HALF_FLOAT;
}
img_size->clear();
img_size->push_back(img_shape.s[2]);
img_size->push_back(img_shape.s[1]);
img_size->push_back(img_dtype);
return RET_OK;
}
kernel::LiteKernel *OpenClActivationKernelCreator(const std::vector<lite::Tensor *> &inputs,
const std::vector<lite::Tensor *> &outputs, OpParameter *opParameter,
const lite::InnerContext *ctx, const kernel::KernelKey &desc,
const mindspore::lite::PrimitiveC *primitive) {
if (inputs.empty()) {
MS_LOG(ERROR) << "Input data size must be greater than 0, but your size is " << inputs.size();
return nullptr;
}
if (inputs[0]->shape().size() > 2 && inputs[0]->shape()[0] > 1) {
MS_LOG(ERROR) << "Activation kernel:" << opParameter->name_ << " failed: Unsupported multi-batch.";
return nullptr;
}
auto *kernel =
new (std::nothrow) ActivationOpenClKernel(reinterpret_cast<OpParameter *>(opParameter), inputs, outputs);
if (kernel == nullptr) {
MS_LOG(ERROR) << "New kernel:" << opParameter->name_ << "is nullptr.";
return nullptr;
}
auto ret = kernel->Init();
if (ret != RET_OK) {
MS_LOG(ERROR) << "Init activation kernel:" << opParameter->name_ << " failed!";
delete kernel;
return nullptr;
}
return kernel;
}
REG_KERNEL(kGPU, kNumberTypeFloat16, PrimitiveType_Activation, OpenClActivationKernelCreator)
REG_KERNEL(kGPU, kNumberTypeFloat32, PrimitiveType_Activation, OpenClActivationKernelCreator)
} // namespace mindspore::kernel
| 38.824242 | 119 | 0.686388 | [
"shape",
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.