hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
79cc8462db5e2701abb1256d516c7d0ccc627ab3 | 1,330 | cpp | C++ | code/components/net/src/NetBuffer.cpp | antonand03/hello-my-friend | fb4e225a75aea3007a391ccc4dcda3eda65c2142 | [
"MIT"
] | 6 | 2019-01-30T14:33:30.000Z | 2021-07-21T18:06:52.000Z | code/components/net/src/NetBuffer.cpp | antonand03/hello-my-friend | fb4e225a75aea3007a391ccc4dcda3eda65c2142 | [
"MIT"
] | 6 | 2021-05-11T09:09:11.000Z | 2022-03-23T18:34:23.000Z | code/components/net/src/NetBuffer.cpp | antonand03/hello-my-friend | fb4e225a75aea3007a391ccc4dcda3eda65c2142 | [
"MIT"
] | 22 | 2018-11-17T17:19:01.000Z | 2021-05-22T09:51:07.000Z | /*
* This file is part of the CitizenFX project - http://citizen.re/
*
* See LICENSE and MENTIONS in the root of the source tree for information
* regarding licensing.
*/
#include "StdInc.h"
#include "NetBuffer.h"
NetBuffer::NetBuffer(const char* bytes, size_t length)
: m_bytesManaged(false), m_bytes(const_cast<char*>(bytes)), m_curOff(0), m_length(length), m_end(false)
{
}
NetBuffer::NetBuffer(size_t length)
: m_length(length), m_curOff(0), m_bytesManaged(true), m_end(false)
{
m_bytes = new char[length];
}
NetBuffer::~NetBuffer()
{
if (m_bytesManaged)
{
delete[] m_bytes;
}
}
bool NetBuffer::Read(void* buffer, size_t length)
{
if ((m_curOff + length) >= m_length)
{
m_end = true;
// and if it really doesn't fit out of our buffer
if ((m_curOff + length) > m_length)
{
memset(buffer, 0xCE, length);
return false;
}
}
memcpy(buffer, &m_bytes[m_curOff], length);
m_curOff += length;
return true;
}
void NetBuffer::Write(const void* buffer, size_t length)
{
if ((m_curOff + length) >= m_length)
{
m_end = true;
if ((m_curOff + length) > m_length)
{
return;
}
}
memcpy(&m_bytes[m_curOff], buffer, length);
m_curOff += length;
}
bool NetBuffer::End()
{
return (m_end || m_curOff == m_length);
} | 19 | 105 | 0.63609 | antonand03 |
79d1c8415db18d3ebd6a31d0a5ce7a137239aea9 | 4,946 | cc | C++ | Geometry/CommonTopologies/src/TrapezoidalStripTopology.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | Geometry/CommonTopologies/src/TrapezoidalStripTopology.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | Geometry/CommonTopologies/src/TrapezoidalStripTopology.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #include "Geometry/CommonTopologies/interface/TrapezoidalStripTopology.h"
#include <iostream>
#include <cmath>
#include <algorithm>
TrapezoidalStripTopology::TrapezoidalStripTopology(int ns, float p,
float l,
float r0) :
theNumberOfStrips(ns), thePitch(p),
theDistToBeam(r0), theDetHeight(l) {
theOffset = -theNumberOfStrips/2. * thePitch;
theYAxOr = 1;
#ifdef VERBOSE
cout<<"Constructing TrapezoidalStripTopology with"
<<" nstrips = "<<ns
<<" pitch = "<<p
<<" length = "<<l
<<" r0 ="<<r0
<<endl;
#endif
}
TrapezoidalStripTopology::TrapezoidalStripTopology(int ns, float p,
float l,
float r0, int yAx) :
theNumberOfStrips(ns), thePitch(p),
theDistToBeam(r0), theDetHeight(l), theYAxOr(yAx){
theOffset = -theNumberOfStrips/2. * thePitch;
#ifdef VERBOSE
cout<<"Constructing TrapezoidalStripTopology with"
<<" nstrips = "<<ns
<<" pitch = "<<p
<<" length = "<<l
<<" r0 ="<<r0
<<" yAxOrientation ="<<yAx
<<endl;
#endif
}
LocalPoint
TrapezoidalStripTopology::localPosition(float strip) const {
return LocalPoint( strip*thePitch + theOffset, 0.0);
}
LocalPoint
TrapezoidalStripTopology::localPosition(const MeasurementPoint& mp) const {
float y = mp.y()*theDetHeight;
float x = (mp.x()*thePitch +
theOffset)*(theYAxOr*y+theDistToBeam)/theDistToBeam;
return LocalPoint(x,y);
}
LocalError
TrapezoidalStripTopology::localError(float strip, float stripErr2) const {
float lt,lc2,ls2,lslc;
float localL2,localP2;
float sl2,sp2;
// angle from strip to local frame (see CMS TN / 95-170)
lt = -(strip*thePitch + theOffset)*theYAxOr/theDistToBeam;
lc2 = 1.f/(1.+lt*lt);
lslc = lt*lc2;
ls2 = 1.f-lc2;
localL2 = theDetHeight*theDetHeight / lc2;
localP2 = thePitch*thePitch*lc2;
sl2 = localL2/12.;
sp2 = stripErr2*localP2;
return LocalError(lc2*sp2+ls2*sl2,
lslc*(sp2-sl2),
ls2*sp2+lc2*sl2);
}
LocalError
TrapezoidalStripTopology::localError(const MeasurementPoint& mp,
const MeasurementError& merr) const {
float lt,lc2,ls2,lslc;
float localL,localP;
float sl2,sp2,spl;
// angle from strip to local frame (see CMS TN / 95-170)
lt = -(mp.x()*thePitch + theOffset)*theYAxOr/theDistToBeam;
lc2 = 1./(1.+lt*lt);
lslc = lt*lc2;
ls2 = 1.f-lc2;
localL = theDetHeight / std::sqrt(lc2);
localP = localPitch(localPosition(mp));
sp2 = merr.uu() * localP*localP;
sl2 = merr.vv() * localL*localL;
spl = merr.uv() * localP*localL;
return LocalError(lc2*sp2+ls2*sl2-2*lslc*spl,
lslc*(sp2-sl2)+(lc2-ls2)*spl,
ls2*sp2+lc2*sl2+2*lslc*spl);
}
float
TrapezoidalStripTopology::strip(const LocalPoint& lp) const {
float aStrip =
((lp.x()*theDistToBeam/(theYAxOr*lp.y()+theDistToBeam))-theOffset)/thePitch;
if (aStrip < 0 ) aStrip = 0;
else if (aStrip > theNumberOfStrips) aStrip = theNumberOfStrips;
return aStrip;
}
MeasurementPoint
TrapezoidalStripTopology::measurementPosition(const LocalPoint& lp) const {
return
MeasurementPoint(((lp.x()*theDistToBeam/(theYAxOr*lp.y()+theDistToBeam))-theOffset)/thePitch,
lp.y()/theDetHeight);
}
MeasurementError
TrapezoidalStripTopology::measurementError(const LocalPoint& lp,
const LocalError& lerr) const {
float lt,lc2,ls2,lslc;
float localL,localP;
float sl2,sp2,spl;
lt = -lp.x()/(theYAxOr*lp.y()+theDistToBeam)*theYAxOr;
lc2 = 1./(1.+lt*lt);
lslc = lt*lc2;
ls2 = 1.-lc2;
localL = theDetHeight / std::sqrt(lc2);
localP = localPitch(lp);
sp2 = lc2*lerr.xx()+ls2*lerr.yy()+2*lslc*lerr.xy();
sl2 = ls2*lerr.xx()+lc2*lerr.yy()-2*lslc*lerr.xy();
spl = lslc*(lerr.yy()-lerr.xx())+(lc2-ls2)*lerr.xy();
return MeasurementError(sp2/(localP*localP),
spl/(localP*localL),
sl2/(localL*localL));
}
int
TrapezoidalStripTopology::channel(const LocalPoint& lp) const {
return std::min(int(strip(lp)),theNumberOfStrips-1);
}
float
TrapezoidalStripTopology::pitch() const {
return thePitch;
}
float
TrapezoidalStripTopology::localPitch(const LocalPoint& lp) const {
float x=lp.x();
float y=theYAxOr*lp.y()+theDistToBeam;
return thePitch*y/(theDistToBeam*std::sqrt(1.f+x*x/(y*y)));
}
float
TrapezoidalStripTopology::stripAngle(float strip) const {
return std::atan( -(strip*thePitch + theOffset)*theYAxOr/theDistToBeam );
}
int
TrapezoidalStripTopology::nstrips() const {
return theNumberOfStrips;
}
float TrapezoidalStripTopology::shiftOffset( float pitch_fraction) {
theOffset += thePitch * pitch_fraction;
return theOffset;
}
float TrapezoidalStripTopology::localStripLength(const LocalPoint& lp)
const {
float ltan = -lp.x()/(theYAxOr*lp.y()+theDistToBeam)*theYAxOr;
float localL = theDetHeight * std::sqrt(1.f+ltan*ltan);
// float lcos2 = 1.f/(1.f+ltan*ltan);
// float localL = theDetHeight / std::sqrt(lcos2);
return localL;
}
| 28.589595 | 97 | 0.675091 | nistefan |
79d68d05282cb4ad32b0827ca13108ef551b0748 | 1,358 | cc | C++ | sources/utility/misc.cc | jujudusud/gmajctl | b15466168b94ee6bc4731fc77d2b2dd0e36dc995 | [
"BSL-1.0"
] | 4 | 2018-11-01T23:38:33.000Z | 2021-04-22T11:29:07.000Z | sources/utility/misc.cc | jujudusud/gmajctl | b15466168b94ee6bc4731fc77d2b2dd0e36dc995 | [
"BSL-1.0"
] | 10 | 2018-10-17T21:16:01.000Z | 2019-09-29T21:51:58.000Z | sources/utility/misc.cc | linuxmao-org/FreeMajor | 41bca20fce919e63a918aa472411652031e19ec5 | [
"BSL-1.0"
] | 1 | 2018-10-03T22:31:34.000Z | 2018-10-03T22:31:34.000Z | // Copyright Jean Pierre Cimalando 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)
#include "misc.h"
bool starts_with(const char *x, const char *s)
{
size_t nx = strlen(x), ns = strlen(s);
return nx >= ns && !memcmp(s, x, ns);
}
bool ends_with(const char *x, const char *s)
{
size_t nx = strlen(x), ns = strlen(s);
return nx >= ns && !memcmp(s, x + nx - ns, ns);
}
bool read_entire_file(FILE *fh, size_t max_size, std::vector<uint8_t> &data)
{
struct stat st;
if (fstat(fileno(fh), &st) != 0)
return false;
size_t size = st.st_size;
if (size > max_size)
return false;
data.resize(size);
rewind(fh);
return fread(data.data(), 1, size, fh) == size;
}
std::string file_name_extension(const std::string &fn)
{
size_t n = fn.size();
for (size_t i = n; i-- > 0;) {
char c = fn[i];
if (c == '.')
return fn.substr(i);
else if (c == '/')
break;
#if defined(_WIN32)
else if (c == '\\')
break;
#endif
}
return std::string();
}
std::string file_name_without_extension(const std::string &fn)
{
std::string ext = file_name_extension(fn);
return fn.substr(0, fn.size() - ext.size());
}
| 23.824561 | 76 | 0.574374 | jujudusud |
79d6c4ed083b737e8231c8bc457bdee982554ed1 | 391 | hpp | C++ | lib/rendering/ray.hpp | julienlopez/Raytracer | 35fa5a00e190592a8780971fcbd2936a54e06d3a | [
"MIT"
] | null | null | null | lib/rendering/ray.hpp | julienlopez/Raytracer | 35fa5a00e190592a8780971fcbd2936a54e06d3a | [
"MIT"
] | 2 | 2017-06-01T16:43:37.000Z | 2017-06-07T16:17:51.000Z | lib/rendering/ray.hpp | julienlopez/Raytracer | 35fa5a00e190592a8780971fcbd2936a54e06d3a | [
"MIT"
] | null | null | null | #pragma once
#include "math/types.hpp"
namespace Rendering
{
class Ray
{
public:
Ray(const Math::Point3d& origin_, const Math::Vector3d& direction_);
~Ray() = default;
const Math::Point3d& origin() const;
const Math::Vector3d& direction() const;
Math::Vector3d& direction();
private:
Math::Point3d m_origin;
Math::Vector3d m_direction;
};
} // Rendering
| 14.481481 | 72 | 0.667519 | julienlopez |
79df904e6678cf595472d70326b9395ee90aa4ed | 937 | cpp | C++ | Factorio-Imitation/DeactiveButtonUI.cpp | JiokKae/Factorio-Imitation | 06b6328a48926e64b376ff8e985eedef22f06c14 | [
"MIT"
] | 2 | 2020-12-24T10:38:46.000Z | 2021-04-23T11:44:48.000Z | Factorio-Imitation/DeactiveButtonUI.cpp | JiokKae/Factorio-Imitation | 06b6328a48926e64b376ff8e985eedef22f06c14 | [
"MIT"
] | null | null | null | Factorio-Imitation/DeactiveButtonUI.cpp | JiokKae/Factorio-Imitation | 06b6328a48926e64b376ff8e985eedef22f06c14 | [
"MIT"
] | null | null | null | #include "DeactiveButtonUI.h"
#include "GLImage.h"
HRESULT DeactiveButtonUI::Init()
{
image = new GLImage();
image->Init("UI/DeactiveButtonUI", 3, 1);
onMouse = false;
return S_OK;
}
void DeactiveButtonUI::Release()
{
}
void DeactiveButtonUI::Update()
{
if (active)
{
if (PtInFRect(GetFrect(), { g_ptMouse.x, g_ptMouse.y }))
{
onMouse = true;
if (isMouseDown)
{
if (KeyManager::GetSingleton()->IsOnceKeyUp(VK_LBUTTON))
{
SoundManager::GetSingleton()->Play("GUI-ToolButton", 0.6f);
UIManager::GetSingleton()->DeactiveUI();
}
}
if (KeyManager::GetSingleton()->IsStayKeyDown(VK_LBUTTON))
{
isMouseDown = true;
}
else
isMouseDown = false;
}
else
{
onMouse = false;
isMouseDown = false;
}
}
}
void DeactiveButtonUI::Render(Shader* lpShader)
{
if (active)
{
image->Render(lpShader, GetPosition().x, GetPosition().y, onMouse + isMouseDown, 0);
}
}
| 16.155172 | 86 | 0.640342 | JiokKae |
0763c29128af9170301bb0fc5996c9ce36f327b0 | 5,936 | hpp | C++ | testing_utilities/discrete_trajectory_factories_body.hpp | net-lisias-ksp/Principia | 9292ea1fc2e4b4f0ce7a717e2f507168519f5f8a | [
"MIT"
] | null | null | null | testing_utilities/discrete_trajectory_factories_body.hpp | net-lisias-ksp/Principia | 9292ea1fc2e4b4f0ce7a717e2f507168519f5f8a | [
"MIT"
] | null | null | null | testing_utilities/discrete_trajectory_factories_body.hpp | net-lisias-ksp/Principia | 9292ea1fc2e4b4f0ce7a717e2f507168519f5f8a | [
"MIT"
] | null | null | null | #pragma once
#include "testing_utilities/discrete_trajectory_factories.hpp"
#include "base/status_utilities.hpp"
#include "physics/degrees_of_freedom.hpp"
#include "physics/discrete_trajectory_segment.hpp"
#include "physics/discrete_trajectory_segment_iterator.hpp"
#include "quantities/elementary_functions.hpp"
#include "quantities/si.hpp"
namespace principia {
namespace testing_utilities {
namespace internal_discrete_trajectory_factories {
using base::check_not_null;
using base::make_not_null_unique;
using geometry::Displacement;
using geometry::Velocity;
using physics::DegreesOfFreedom;
using physics::DiscreteTrajectorySegment;
using physics::DiscreteTrajectorySegmentIterator;
using quantities::Cos;
using quantities::Pow;
using quantities::Sin;
using quantities::Speed;
using quantities::si::Radian;
template<typename Frame>
absl::Status DiscreteTrajectoryFactoriesFriend<Frame>::Append(
Instant const& t,
DegreesOfFreedom<Frame> const& degrees_of_freedom,
DiscreteTrajectorySegment<Frame>& segment) {
return segment.Append(t, degrees_of_freedom);
}
template<typename Frame>
Timeline<Frame> NewMotionlessTrajectoryTimeline(Position<Frame> const& position,
Time const& Δt,
Instant const& t1,
Instant const& t2) {
return NewLinearTrajectoryTimeline(
DegreesOfFreedom<Frame>(position, Velocity<Frame>()), Δt, t1, t2);
}
template<typename Frame>
Timeline<Frame>
NewLinearTrajectoryTimeline(DegreesOfFreedom<Frame> const& degrees_of_freedom,
Time const& Δt,
Instant const& t0,
Instant const& t1,
Instant const& t2) {
Timeline<Frame> timeline;
for (auto t = t1; t < t2; t += Δt) {
auto const velocity = degrees_of_freedom.velocity();
auto const position = degrees_of_freedom.position() + velocity * (t - t0);
timeline.emplace(t, DegreesOfFreedom<Frame>(position, velocity));
}
return timeline;
}
template<typename Frame>
Timeline<Frame>
NewLinearTrajectoryTimeline(DegreesOfFreedom<Frame> const& degrees_of_freedom,
Time const& Δt,
Instant const& t1,
Instant const& t2) {
return NewLinearTrajectoryTimeline(degrees_of_freedom, Δt, /*t0=*/t1, t1, t2);
}
template<typename Frame>
Timeline<Frame>
NewLinearTrajectoryTimeline(Velocity<Frame> const& v,
Time const& Δt,
Instant const& t1,
Instant const& t2) {
return NewLinearTrajectoryTimeline(
DegreesOfFreedom<Frame>(Frame::origin, v), Δt, /*t0=*/t1, t1, t2);
}
template<typename Frame>
Timeline<Frame> NewAcceleratedTrajectoryTimeline(
DegreesOfFreedom<Frame> const& degrees_of_freedom,
Vector<Acceleration, Frame> const& acceleration,
Time const& Δt,
Instant const& t1,
Instant const& t2) {
static Instant const t0;
Timeline<Frame> timeline;
for (auto t = t1; t < t2; t += Δt) {
auto const velocity =
degrees_of_freedom.velocity() + acceleration * (t - t0);
auto const position = degrees_of_freedom.position() +
degrees_of_freedom.velocity() * (t - t0) +
acceleration * Pow<2>(t - t0) * 0.5;
timeline.emplace(t, DegreesOfFreedom<Frame>(position, velocity));
}
return timeline;
}
template<typename Frame>
Timeline<Frame>
NewCircularTrajectoryTimeline(AngularFrequency const& ω,
Length const& r,
Time const& Δt,
Instant const& t1,
Instant const& t2) {
static Instant const t0;
Timeline<Frame> timeline;
Speed const v = ω * r / Radian;
for (auto t = t1; t < t2; t += Δt) {
DegreesOfFreedom<Frame> const dof = {
Frame::origin + Displacement<Frame>{{r * Cos(ω * (t - t0)),
r * Sin(ω * (t - t0)),
Length{}}},
Velocity<Frame>{{-v * Sin(ω * (t - t0)),
v * Cos(ω * (t - t0)),
Speed{}}}};
timeline.emplace(t, dof);
}
return timeline;
}
template<typename Frame>
Timeline<Frame>
NewCircularTrajectoryTimeline(Time const& period,
Length const& r,
Time const& Δt,
Instant const& t1,
Instant const& t2) {
return NewCircularTrajectoryTimeline<Frame>(/*ω=*/2 * π * Radian / period,
r,
Δt,
t1,
t2);
}
template<typename Frame>
void AppendTrajectoryTimeline(Timeline<Frame> const& from,
DiscreteTrajectorySegment<Frame>& to) {
for (auto const& [t, degrees_of_freedom] : from) {
CHECK_OK(DiscreteTrajectoryFactoriesFriend<Frame>::Append(
t, degrees_of_freedom, to));
}
}
template<typename Frame>
void AppendTrajectoryTimeline(Timeline<Frame> const& from,
DiscreteTrajectory<Frame>& to) {
for (auto const& [t, degrees_of_freedom] : from) {
CHECK_OK(to.Append(t, degrees_of_freedom));
}
}
template<typename Frame>
void AppendTrajectoryTimeline(
Timeline<Frame> const& from,
std::function<void(
Instant const& time,
DegreesOfFreedom<Frame> const& degrees_of_freedom)> const& append_to) {
for (auto const& [t, degrees_of_freedom] : from) {
append_to(t, degrees_of_freedom);
}
}
} // namespace internal_discrete_trajectory_factories
} // namespace testing_utilities
} // namespace principia
| 35.12426 | 80 | 0.60091 | net-lisias-ksp |
076468edc1cac5aa3638c664fa752676e4485084 | 4,412 | cc | C++ | third_party/blink/common/privacy_budget/identifiable_surface_unittest.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 | third_party/blink/common/privacy_budget/identifiable_surface_unittest.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 | third_party/blink/common/privacy_budget/identifiable_surface_unittest.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 2020 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 "third_party/blink/public/common/privacy_budget/identifiable_surface.h"
#include <functional>
#include <unordered_set>
#include "services/metrics/public/cpp/ukm_builders.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace blink {
// These metric names were chosen so that they result in a surface type of
// kReservedInternal. These are static_asserts because these expressions should
// resolve at compile-time.
static_assert(IdentifiableSurface::FromMetricHash(
ukm::builders::Identifiability::kStudyGeneration_626NameHash)
.GetType() ==
IdentifiableSurface::Type::kReservedInternal,
"");
static_assert(IdentifiableSurface::FromMetricHash(
ukm::builders::Identifiability::kGeneratorVersion_926NameHash)
.GetType() ==
IdentifiableSurface::Type::kReservedInternal,
"");
TEST(IdentifiableSurfaceTest, FromTypeAndTokenIsConstexpr) {
constexpr uint64_t kTestInputHash = 5u;
constexpr auto kSurface = IdentifiableSurface::FromTypeAndToken(
IdentifiableSurface::Type::kWebFeature, kTestInputHash);
static_assert(
(kTestInputHash << 8) +
static_cast<uint64_t>(IdentifiableSurface::Type::kWebFeature) ==
kSurface.ToUkmMetricHash(),
"");
static_assert(IdentifiableSurface::Type::kWebFeature == kSurface.GetType(),
"");
static_assert(kTestInputHash == kSurface.GetInputHash(), "");
}
TEST(IdentifiableSurfaceTest, FromKeyIsConstexpr) {
constexpr uint64_t kTestInputHash = 5u;
constexpr uint64_t kTestMetricHash =
((kTestInputHash << 8) |
static_cast<uint64_t>(IdentifiableSurface::Type::kWebFeature));
constexpr auto kSurface =
IdentifiableSurface::FromMetricHash(kTestMetricHash);
static_assert(kTestMetricHash == kSurface.ToUkmMetricHash(), "");
static_assert(IdentifiableSurface::Type::kWebFeature == kSurface.GetType(),
"");
}
TEST(IdentifiableSurfaceTest, AllowsMaxTypeValue) {
constexpr uint64_t kInputHash = UINT64_C(0x1123456789abcdef);
constexpr auto kSurface = IdentifiableSurface::FromTypeAndToken(
IdentifiableSurface::Type::kMax, kInputHash);
EXPECT_EQ(UINT64_C(0x23456789abcdefff), kSurface.ToUkmMetricHash());
EXPECT_EQ(IdentifiableSurface::Type::kMax, kSurface.GetType());
// The lower 56 bits of kInputHash should match GetInputHash().
EXPECT_EQ(kInputHash << 8, kSurface.GetInputHash() << 8);
EXPECT_NE(kInputHash, kSurface.GetInputHash());
}
TEST(IdentifiableSurfaceTest, IdentifiableSurfaceHash) {
constexpr uint64_t kTestInputHashA = 1;
constexpr uint64_t kTestInputHashB = 3;
// surface2 == surface3 != surface1
auto surface1 = IdentifiableSurface::FromTypeAndToken(
IdentifiableSurface::Type::kWebFeature, kTestInputHashA);
auto surface2 = IdentifiableSurface::FromTypeAndToken(
IdentifiableSurface::Type::kWebFeature, kTestInputHashB);
auto surface3 = IdentifiableSurface::FromTypeAndToken(
IdentifiableSurface::Type::kWebFeature, kTestInputHashB);
IdentifiableSurfaceHash hash_object;
size_t hash1 = hash_object(surface1);
size_t hash2 = hash_object(surface2);
size_t hash3 = hash_object(surface3);
EXPECT_NE(hash1, hash2);
EXPECT_EQ(hash3, hash2);
std::unordered_set<IdentifiableSurface, IdentifiableSurfaceHash> surface_set;
surface_set.insert(surface1);
surface_set.insert(surface2);
surface_set.insert(surface3);
EXPECT_EQ(surface_set.size(), 2u);
EXPECT_EQ(surface_set.count(surface1), 1u);
}
TEST(IdentifiableSurfaceTest, Comparison) {
constexpr uint64_t kTestInputHashA = 1;
constexpr uint64_t kTestInputHashB = 3;
// surface2 == surface3 != surface1
auto surface1 = IdentifiableSurface::FromTypeAndToken(
IdentifiableSurface::Type::kWebFeature, kTestInputHashA);
auto surface2 = IdentifiableSurface::FromTypeAndToken(
IdentifiableSurface::Type::kWebFeature, kTestInputHashB);
auto surface3 = IdentifiableSurface::FromTypeAndToken(
IdentifiableSurface::Type::kWebFeature, kTestInputHashB);
EXPECT_TRUE(surface2 == surface3);
EXPECT_TRUE(surface1 != surface3);
EXPECT_TRUE(surface1 < surface2);
}
} // namespace blink
| 37.709402 | 80 | 0.740254 | zealoussnow |
076581d0398811b88e5e93ac46448596bd777e94 | 15,188 | cpp | C++ | src/test-rhi.cpp | sgorsten/workbench | 5209bb405e0e0f4696b36684bbd1d7ecff7daa2f | [
"Unlicense"
] | 16 | 2015-12-15T17:17:37.000Z | 2021-12-07T20:19:38.000Z | src/test-rhi.cpp | sgorsten/workbench | 5209bb405e0e0f4696b36684bbd1d7ecff7daa2f | [
"Unlicense"
] | null | null | null | src/test-rhi.cpp | sgorsten/workbench | 5209bb405e0e0f4696b36684bbd1d7ecff7daa2f | [
"Unlicense"
] | 1 | 2016-03-25T08:04:58.000Z | 2016-03-25T08:04:58.000Z | #include "engine/pbr.h"
#include "engine/mesh.h"
#include "engine/sprite.h"
#include "engine/camera.h"
#include <chrono>
#include <iostream>
struct common_assets
{
coord_system game_coords;
shader_compiler compiler;
pbr::shaders standard;
rhi::shader_desc vs, lit_fs, unlit_fs, skybox_vs, skybox_fs;
image env_spheremap;
mesh ground_mesh, box_mesh, sphere_mesh;
sprite_sheet sheet;
canvas_sprites sprites;
font_face face;
common_assets(loader & loader) : game_coords {coord_axis::right, coord_axis::forward, coord_axis::up},
compiler{loader}, standard{pbr::shaders::compile(compiler)},
sprites{sheet}, face{sheet, loader.load_ttf_font("arial.ttf", 20, 0x20, 0x7E)}
{
vs = compiler.compile_file(rhi::shader_stage::vertex, "static-mesh.vert");
lit_fs = compiler.compile_file(rhi::shader_stage::fragment, "textured-pbr.frag");
unlit_fs = compiler.compile_file(rhi::shader_stage::fragment, "colored-unlit.frag");
skybox_vs = compiler.compile_file(rhi::shader_stage::vertex, "skybox.vert");
skybox_fs = compiler.compile_file(rhi::shader_stage::fragment, "skybox.frag");
env_spheremap = loader.load_image("monument-valley.hdr", true);
ground_mesh = make_quad_mesh(game_coords(coord_axis::right)*8.0f, game_coords(coord_axis::forward)*8.0f);
box_mesh = make_box_mesh({-0.3f,-0.3f,-0.3f}, {0.3f,0.3f,0.3f});
sphere_mesh = make_sphere_mesh(32, 32, 0.5f);
sheet.prepare_sheet();
}
};
class device_session
{
const common_assets & assets;
rhi::ptr<rhi::device> dev;
pbr::device_objects standard;
canvas_device_objects canvas_objects;
rhi::device_info info;
gfx::transient_resource_pool pools[3];
int pool_index=0;
gfx::simple_mesh ground, box, sphere;
rhi::ptr<rhi::image> font_image;
rhi::ptr<rhi::image> checkerboard;
pbr::environment_map env;
rhi::ptr<rhi::sampler> nearest;
rhi::ptr<rhi::descriptor_set_layout> per_scene_layout, per_view_layout, skybox_material_layout, pbr_material_layout, static_object_layout;
rhi::ptr<rhi::pipeline_layout> common_layout, object_layout, skybox_layout;
rhi::ptr<rhi::pipeline> light_pipe, solid_pipe, skybox_pipe;
std::unique_ptr<gfx::window> gwindow;
double2 last_cursor;
public:
device_session(common_assets & assets, const std::string & name, rhi::ptr<rhi::device> dev, const int2 & window_pos) :
assets{assets}, dev{dev}, standard{dev, assets.standard}, canvas_objects{*dev, assets.compiler, assets.sheet}, info{dev->get_info()}, pools{*dev, *dev, *dev}
{
// Buffers
ground = {*dev, assets.ground_mesh.vertices, assets.ground_mesh.triangles};
box = {*dev, assets.box_mesh.vertices, assets.box_mesh.triangles};
sphere = {*dev, assets.sphere_mesh.vertices, assets.sphere_mesh.triangles};
// Samplers
nearest = dev->create_sampler({rhi::filter::nearest, rhi::filter::nearest, std::nullopt, rhi::address_mode::clamp_to_edge, rhi::address_mode::repeat});
// Images
const byte4 w{255,255,255,255}, g{128,128,128,255}, grid[]{w,g,w,g,g,w,g,w,w,g,w,g,g,w,g,w};
checkerboard = dev->create_image({rhi::image_shape::_2d, {4,4,1}, 1, rhi::image_format::rgba_unorm8, rhi::sampled_image_bit}, {grid});
font_image = dev->create_image({rhi::image_shape::_2d, {assets.sheet.sheet_image.dims(),1}, 1, rhi::image_format::r_unorm8, rhi::sampled_image_bit}, {assets.sheet.sheet_image.data()});
auto env_spheremap = dev->create_image({rhi::image_shape::_2d, {assets.env_spheremap.dimensions,1}, 1, assets.env_spheremap.format, rhi::sampled_image_bit}, {assets.env_spheremap.get_pixels()});
// Descriptor set layouts
per_scene_layout = dev->create_descriptor_set_layout({
{0, rhi::descriptor_type::uniform_buffer, 1},
{1, rhi::descriptor_type::combined_image_sampler, 1},
{2, rhi::descriptor_type::combined_image_sampler, 1},
{3, rhi::descriptor_type::combined_image_sampler, 1}
});
per_view_layout = dev->create_descriptor_set_layout({
{0, rhi::descriptor_type::uniform_buffer, 1}
});
skybox_material_layout = dev->create_descriptor_set_layout({
{0, rhi::descriptor_type::combined_image_sampler, 1}
});
pbr_material_layout = dev->create_descriptor_set_layout({
{0, rhi::descriptor_type::uniform_buffer, 1},
{1, rhi::descriptor_type::combined_image_sampler, 1}
});
static_object_layout = dev->create_descriptor_set_layout({
{0, rhi::descriptor_type::uniform_buffer, 1},
});
// Pipeline layouts
common_layout = dev->create_pipeline_layout({per_scene_layout, per_view_layout});
skybox_layout = dev->create_pipeline_layout({per_scene_layout, per_view_layout, skybox_material_layout});
object_layout = dev->create_pipeline_layout({per_scene_layout, per_view_layout, pbr_material_layout, static_object_layout});
const auto mesh_vertex_binding = gfx::vertex_binder<mesh_vertex>(0)
.attribute(0, &mesh_vertex::position)
.attribute(1, &mesh_vertex::normal)
.attribute(2, &mesh_vertex::texcoord)
.attribute(3, &mesh_vertex::tangent)
.attribute(4, &mesh_vertex::bitangent);
const auto ui_vertex_binding = gfx::vertex_binder<ui_vertex>(0)
.attribute(0, &ui_vertex::position)
.attribute(1, &ui_vertex::texcoord)
.attribute(2, &ui_vertex::color);
// Shaders
auto vs = dev->create_shader(assets.vs), lit_fs = dev->create_shader(assets.lit_fs), unlit_fs = dev->create_shader(assets.unlit_fs);
auto skybox_vs = dev->create_shader(assets.skybox_vs), skybox_fs = dev->create_shader(assets.skybox_fs);
// Blend states
const rhi::blend_state opaque {true, false};
const rhi::blend_state translucent {true, true, {rhi::blend_factor::source_alpha, rhi::blend_op::add, rhi::blend_factor::one_minus_source_alpha}, {rhi::blend_factor::source_alpha, rhi::blend_op::add, rhi::blend_factor::one_minus_source_alpha}};
// Pipelines
light_pipe = dev->create_pipeline({object_layout, {mesh_vertex_binding}, {vs,unlit_fs}, rhi::primitive_topology::triangles, rhi::front_face::counter_clockwise, rhi::cull_mode::back, rhi::depth_state{rhi::compare_op::less, true}, std::nullopt, {opaque}});
solid_pipe = dev->create_pipeline({object_layout, {mesh_vertex_binding}, {vs,lit_fs}, rhi::primitive_topology::triangles, rhi::front_face::counter_clockwise, rhi::cull_mode::back, rhi::depth_state{rhi::compare_op::less, true}, std::nullopt, {opaque}});
skybox_pipe = dev->create_pipeline({skybox_layout, {mesh_vertex_binding}, {skybox_vs,skybox_fs}, rhi::primitive_topology::triangles, rhi::front_face::clockwise, rhi::cull_mode::back, rhi::depth_state{rhi::compare_op::always, false}, std::nullopt, {opaque}});
// Do some initial work
pools[pool_index].begin_frame(*dev);
env = standard.create_environment_map_from_spheremap(pools[pool_index], *env_spheremap, 512, assets.game_coords);
pools[pool_index].end_frame(*dev);
// Window
gwindow = std::make_unique<gfx::window>(*dev, int2{512,512}, to_string("Workbench 2018 Render Test (", name, ")"));
gwindow->set_pos(window_pos);
}
bool update(camera & cam, float timestep)
{
const double2 cursor = gwindow->get_cursor_pos();
if(gwindow->get_mouse_button(GLFW_MOUSE_BUTTON_LEFT))
{
cam.yaw += static_cast<float>(cursor.x - last_cursor.x) * 0.01f;
cam.pitch = std::min(std::max(cam.pitch + static_cast<float>(cursor.y - last_cursor.y) * 0.01f, -1.5f), +1.5f);
}
last_cursor = cursor;
const float cam_speed = timestep * 10;
if(gwindow->get_key(GLFW_KEY_W)) cam.move(coord_axis::forward, cam_speed);
if(gwindow->get_key(GLFW_KEY_A)) cam.move(coord_axis::left, cam_speed);
if(gwindow->get_key(GLFW_KEY_S)) cam.move(coord_axis::back, cam_speed);
if(gwindow->get_key(GLFW_KEY_D)) cam.move(coord_axis::right, cam_speed);
return !gwindow->should_close();
}
void render_frame(const camera & cam)
{
// Reset resources
pool_index = (pool_index+1)%3;
auto & pool = pools[pool_index];
pool.begin_frame(*dev);
// Set up per scene uniforms
pbr::scene_uniforms per_scene_uniforms {};
per_scene_uniforms.point_lights[0] = {{-3, -3, 8}, {23.47f, 21.31f, 20.79f}};
per_scene_uniforms.point_lights[1] = {{ 3, -3, 8}, {23.47f, 21.31f, 20.79f}};
per_scene_uniforms.point_lights[2] = {{ 3, 3, 8}, {23.47f, 21.31f, 20.79f}};
per_scene_uniforms.point_lights[3] = {{-3, 3, 8}, {23.47f, 21.31f, 20.79f}};
auto per_scene_set = pool.alloc_descriptor_set(*common_layout, pbr::scene_set_index);
per_scene_set.write(0, per_scene_uniforms);
per_scene_set.write(1, standard.get_image_sampler(), standard.get_brdf_integral_image());
per_scene_set.write(2, standard.get_cubemap_sampler(), *env.irradiance_cubemap);
per_scene_set.write(3, standard.get_cubemap_sampler(), *env.reflectance_cubemap);
auto cmd = dev->create_command_buffer();
// Set up per-view uniforms for a specific framebuffer
auto & fb = gwindow->get_rhi_window().get_swapchain_framebuffer();
auto per_view_set = pool.alloc_descriptor_set(*common_layout, pbr::view_set_index);
per_view_set.write(0, pbr::view_uniforms{cam, gwindow->get_aspect(), fb.get_ndc_coords(), info.z_range});
// Draw objects to our primary framebuffer
rhi::render_pass_desc pass;
pass.color_attachments = {{rhi::dont_care{}, rhi::store{rhi::layout::present_source}}};
pass.depth_attachment = {rhi::clear_depth{1.0f,0}, rhi::dont_care{}};
cmd->begin_render_pass(pass, fb);
// Bind common descriptors
per_scene_set.bind(*cmd);
per_view_set.bind(*cmd);
// Draw skybox
cmd->bind_pipeline(*skybox_pipe);
auto skybox_set = pool.descriptors->alloc(*skybox_material_layout);
skybox_set->write(0, standard.get_cubemap_sampler(), *env.environment_cubemap);
cmd->bind_descriptor_set(*skybox_layout, pbr::material_set_index, *skybox_set);
box.draw(*cmd);
// Draw lights
cmd->bind_pipeline(*light_pipe);
auto material_set = pool.descriptors->alloc(*pbr_material_layout);
material_set->write(0, pool.uniforms.upload(pbr::material_uniforms{{0.5f,0.5f,0.5f},0.5f,0}));
material_set->write(1, *nearest, *checkerboard);
cmd->bind_descriptor_set(*object_layout, pbr::material_set_index, *material_set);
for(auto & p : per_scene_uniforms.point_lights)
{
auto object_set = pool.descriptors->alloc(*static_object_layout);
object_set->write(0, pool.uniforms.upload(pbr::object_uniforms{mul(translation_matrix(p.position), scaling_matrix(float3{0.5f}))}));
cmd->bind_descriptor_set(*object_layout, pbr::object_set_index, *object_set);
sphere.draw(*cmd);
}
// Draw the ground
cmd->bind_pipeline(*solid_pipe);
auto object_set = pool.descriptors->alloc(*static_object_layout);
object_set->write(0, pool.uniforms.upload(pbr::object_uniforms{translation_matrix(cam.coords(coord_axis::down)*0.5f)}));
cmd->bind_descriptor_set(*object_layout, pbr::object_set_index, *object_set);
ground.draw(*cmd);
// Draw a bunch of spheres
for(int i=0; i<6; ++i)
{
for(int j=0; j<6; ++j)
{
material_set = pool.descriptors->alloc(*pbr_material_layout);
material_set->write(0, pool.uniforms.upload(pbr::material_uniforms{{1,1,1},(j+0.5f)/6,(i+0.5f)/6}));
material_set->write(1, *nearest, *checkerboard);
cmd->bind_descriptor_set(*object_layout, pbr::material_set_index, *material_set);
object_set = pool.descriptors->alloc(*static_object_layout);
object_set->write(0, pool.uniforms.upload(pbr::object_uniforms{translation_matrix(cam.coords(coord_axis::right)*(i*2-5.f) + cam.coords(coord_axis::forward)*(j*2-5.f))}));
cmd->bind_descriptor_set(*object_layout, pbr::object_set_index, *object_set);
sphere.draw(*cmd);
}
}
// Draw the UI
canvas canvas {assets.sprites, canvas_objects, pool};
canvas.set_target(0, {{0,0},gwindow->get_window_size()}, nullptr);
canvas.draw_rounded_rect({10,10,140,30+assets.face.line_height}, 6, {0,0,0,0.8f});
canvas.draw_shadowed_text({20,20}, {1,1,1,1}, assets.face, "This is a test");
canvas.encode_commands(*cmd, *gwindow);
cmd->end_render_pass();
dev->acquire_and_submit_and_present(*cmd, gwindow->get_rhi_window());
pool.end_frame(*dev);
}
};
int main(int argc, const char * argv[]) try
{
// Run tests, if requested
if(argc > 1 && strcmp("--test", argv[1]) == 0)
{
doctest::Context dt_context;
dt_context.applyCommandLine(argc-1, argv+1);
const int dt_return = dt_context.run();
if(dt_context.shouldExit()) return dt_return;
}
// Register asset paths
std::cout << "Running from " << get_program_binary_path() << std::endl;
loader loader;
loader.register_root(get_program_binary_path() + "../../assets");
loader.register_root("C:/windows/fonts");
// Loader assets and initialize state
common_assets assets{loader};
camera cam {assets.game_coords};
cam.pitch += 0.8f;
cam.move(coord_axis::back, 10.0f);
// Create a session for each device
gfx::context context;
auto debug = [](const char * message) { std::cerr << message << std::endl; };
int2 pos{100,100};
std::vector<std::unique_ptr<device_session>> sessions;
for(auto & backend : context.get_clients())
{
std::cout << "Initializing " << backend.name << " backend:\n";
sessions.push_back(std::make_unique<device_session>(assets, backend.name, backend.create_device(debug), pos));
std::cout << backend.name << " has been initialized." << std::endl;
pos.x += 600;
}
// Main loop
auto t0 = std::chrono::high_resolution_clock::now();
bool running = true;
while(running)
{
// Render frame
for(auto & s : sessions) s->render_frame(cam);
// Poll events
context.poll_events();
// Compute timestep
const auto t1 = std::chrono::high_resolution_clock::now();
const auto timestep = std::chrono::duration<float>(t1-t0).count();
t0 = t1;
// Handle input
for(auto & s : sessions) if(!s->update(cam, timestep)) running = false;
}
return EXIT_SUCCESS;
}
catch(const std::exception & e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
| 47.021672 | 269 | 0.659139 | sgorsten |
0765c49926bec7a3eac614ee1d8f6d68ba8604a9 | 3,362 | cpp | C++ | src/albert/cui/cui.cpp | a1exwang/dht | 1ff57a3bd1ea0adb2e98e8eac5041b786092e5a2 | [
"MIT"
] | 1 | 2020-02-23T13:25:58.000Z | 2020-02-23T13:25:58.000Z | src/albert/cui/cui.cpp | a1exwang/dht | 1ff57a3bd1ea0adb2e98e8eac5041b786092e5a2 | [
"MIT"
] | null | null | null | src/albert/cui/cui.cpp | a1exwang/dht | 1ff57a3bd1ea0adb2e98e8eac5041b786092e5a2 | [
"MIT"
] | null | null | null | #include <albert/cui/cui.hpp>
#include <cstddef>
#include <cstdint>
#include <vector>
#include <string>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/asio/read_until.hpp>
#include <boost/bind/bind.hpp>
#include <boost/system/error_code.hpp>
#include <albert/bt/torrent_resolver.hpp>
#include <albert/bt/peer_connection.hpp>
#include <albert/dht/dht.hpp>
#include <albert/krpc/krpc.hpp>
#include <albert/log/log.hpp>
#include <albert/u160/u160.hpp>
namespace albert::cui {
void CommandLineUI::handle_read_input(
const boost::system::error_code &error,
std::size_t bytes_transferred) {
if (!error) {
if (is_searching_) {
input_buffer_.consume(input_buffer_.size());
LOG(error) << "Already in search, ignored";
} else {
std::vector<char> data(input_buffer_.size());
input_buffer_.sgetn(data.data(), data.size());
input_buffer_.consume(input_buffer_.size());
std::string command_line(data.data(), data.size());
std::vector<std::string> cmd;
boost::split(cmd, command_line, boost::is_any_of("\t "));
if (cmd.size() == 2) {
auto function_name = cmd[0];
if (function_name == "ih") {
target_info_hash_ = cmd[1];
} else {
if (target_info_hash_.empty()) {
LOG(error) << "Unknown function name " << function_name;
}
}
} else {
if (target_info_hash_.empty()) {
LOG(error) << "Invalid command size " << cmd.size();
}
}
if (!target_info_hash_.empty()) {
start_search();
}
}
} else {
input_buffer_.consume(input_buffer_.size());
LOG(error) << "Failed to read from stdin " << error.message();
}
boost::asio::async_read_until(
input_,
input_buffer_,
'\n',
boost::bind(
&CommandLineUI::handle_read_input,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)
);
}
CommandLineUI::CommandLineUI(std::string info_hash, boost::asio::io_service &io, dht::DHTInterface &dht, bt::BT &bt)
:io_(io), dht_(dht), bt_(bt), input_(io, ::dup(STDIN_FILENO)), target_info_hash_(info_hash) {
}
void CommandLineUI::start() {
// set stdin read handler
boost::asio::async_read_until(
input_,
input_buffer_,
'\n',
boost::bind(
&CommandLineUI::handle_read_input,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)
);
}
void CommandLineUI::start_search() {
this->is_searching_ = true;
auto ih = u160::U160::from_hex(target_info_hash_);
auto resolver = bt_.resolve_torrent(ih, [this, ih](const bencoding::DictNode &torrent) {
is_searching_ = false;
auto file_name = ih.to_string() + ".torrent";
std::ofstream f(file_name, std::ios::binary);
torrent.encode(f, bencoding::EncodeMode::Bencoding);
LOG(info) << "torrent saved as '" << file_name;
});
dht_.get_peers(ih, [resolver](uint32_t ip, uint16_t port) {
if (resolver.expired()) {
LOG(error) << "TorrentResolver gone before a get_peer request received";
} else {
resolver.lock()->add_peer(ip, port);
}
});
}
}
| 28.735043 | 116 | 0.635634 | a1exwang |
07674e39420d832e82b3eaa032f85a1268b4f0b6 | 12,085 | cpp | C++ | Libraries/Audio/input_adcs.cpp | InspiredChaos/New_Visualizer_Skeleton | 97967caa3cd74a3ea7a2727f9e886cadc44e8451 | [
"MIT"
] | 18 | 2020-04-15T11:58:46.000Z | 2022-02-06T19:09:51.000Z | src/lib/Audio/input_adcs.cpp | ARSFI/HFSimulator | b6a5b32ea7bf45bc37c6ec74c55167bb2479d5ac | [
"MIT"
] | 1 | 2018-12-07T01:38:43.000Z | 2018-12-07T01:38:43.000Z | src/lib/Audio/input_adcs.cpp | ARSFI/HFSimulator | b6a5b32ea7bf45bc37c6ec74c55167bb2479d5ac | [
"MIT"
] | 7 | 2020-05-09T19:53:34.000Z | 2021-09-04T21:39:28.000Z | /* Audio Library for Teensy 3.X
* Copyright (c) 2014, Paul Stoffregen, paul@pjrc.com
*
* Development of this audio library was funded by PJRC.COM, LLC by sales of
* Teensy and Audio Adaptor boards. Please support PJRC's efforts to develop
* open source software by purchasing Teensy or other PJRC products.
*
* 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, development funding 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 <Arduino.h>
#include "input_adcs.h"
#include "utility/pdb.h"
#include "utility/dspinst.h"
#if defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__)
#define COEF_HPF_DCBLOCK (1048300<<10) // DC Removal filter coefficient in S1.30
DMAMEM static uint16_t left_buffer[AUDIO_BLOCK_SAMPLES];
DMAMEM static uint16_t right_buffer[AUDIO_BLOCK_SAMPLES];
audio_block_t * AudioInputAnalogStereo::block_left = NULL;
audio_block_t * AudioInputAnalogStereo::block_right = NULL;
uint16_t AudioInputAnalogStereo::offset_left = 0;
uint16_t AudioInputAnalogStereo::offset_right = 0;
int32_t AudioInputAnalogStereo::hpf_y1[2] = { 0, 0 };
int32_t AudioInputAnalogStereo::hpf_x1[2] = { 0, 0 };
bool AudioInputAnalogStereo::update_responsibility = false;
DMAChannel AudioInputAnalogStereo::dma0(false);
DMAChannel AudioInputAnalogStereo::dma1(false);
static int analogReadADC1(uint8_t pin);
void AudioInputAnalogStereo::init(uint8_t pin0, uint8_t pin1)
{
uint32_t tmp;
//pinMode(32, OUTPUT);
//pinMode(33, OUTPUT);
// Configure the ADC and run at least one software-triggered
// conversion. This completes the self calibration stuff and
// leaves the ADC in a state that's mostly ready to use
analogReadRes(16);
analogReference(INTERNAL); // range 0 to 1.2 volts
#if F_BUS == 96000000 || F_BUS == 48000000 || F_BUS == 24000000
analogReadAveraging(8);
ADC1_SC3 = ADC_SC3_AVGE + ADC_SC3_AVGS(1);
#else
analogReadAveraging(4);
ADC1_SC3 = ADC_SC3_AVGE + ADC_SC3_AVGS(0);
#endif
// Note for review:
// Probably not useful to spin cycles here stabilizing
// since DC blocking is similar to te external analog filters
tmp = (uint16_t) analogRead(pin0);
tmp = ( ((int32_t) tmp) << 14);
hpf_x1[0] = tmp; // With constant DC level x1 would be x0
hpf_y1[0] = 0; // Output will settle here when stable
tmp = (uint16_t) analogReadADC1(pin1);
tmp = ( ((int32_t) tmp) << 14);
hpf_x1[1] = tmp; // With constant DC level x1 would be x0
hpf_y1[1] = 0; // Output will settle here when stable
// set the programmable delay block to trigger the ADC at 44.1 kHz
//if (!(SIM_SCGC6 & SIM_SCGC6_PDB)
//|| (PDB0_SC & PDB_CONFIG) != PDB_CONFIG
//|| PDB0_MOD != PDB_PERIOD
//|| PDB0_IDLY != 1
//|| PDB0_CH0C1 != 0x0101) {
SIM_SCGC6 |= SIM_SCGC6_PDB;
PDB0_IDLY = 1;
PDB0_MOD = PDB_PERIOD;
PDB0_SC = PDB_CONFIG | PDB_SC_LDOK;
PDB0_SC = PDB_CONFIG | PDB_SC_SWTRIG;
PDB0_CH0C1 = 0x0101;
PDB0_CH1C1 = 0x0101;
//}
// enable the ADC for hardware trigger and DMA
ADC0_SC2 |= ADC_SC2_ADTRG | ADC_SC2_DMAEN;
ADC1_SC2 |= ADC_SC2_ADTRG | ADC_SC2_DMAEN;
// set up a DMA channel to store the ADC data
dma0.begin(true);
dma1.begin(true);
// ADC0_RA = 0x4003B010
// ADC1_RA = 0x400BB010
dma0.TCD->SADDR = &ADC0_RA;
dma0.TCD->SOFF = 0;
dma0.TCD->ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1);
dma0.TCD->NBYTES_MLNO = 2;
dma0.TCD->SLAST = 0;
dma0.TCD->DADDR = left_buffer;
dma0.TCD->DOFF = 2;
dma0.TCD->CITER_ELINKNO = sizeof(left_buffer) / 2;
dma0.TCD->DLASTSGA = -sizeof(left_buffer);
dma0.TCD->BITER_ELINKNO = sizeof(left_buffer) / 2;
dma0.TCD->CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
dma1.TCD->SADDR = &ADC1_RA;
dma1.TCD->SOFF = 0;
dma1.TCD->ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1);
dma1.TCD->NBYTES_MLNO = 2;
dma1.TCD->SLAST = 0;
dma1.TCD->DADDR = right_buffer;
dma1.TCD->DOFF = 2;
dma1.TCD->CITER_ELINKNO = sizeof(right_buffer) / 2;
dma1.TCD->DLASTSGA = -sizeof(right_buffer);
dma1.TCD->BITER_ELINKNO = sizeof(right_buffer) / 2;
dma1.TCD->CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
dma0.triggerAtHardwareEvent(DMAMUX_SOURCE_ADC0);
//dma1.triggerAtHardwareEvent(DMAMUX_SOURCE_ADC1);
dma1.triggerAtTransfersOf(dma0);
dma1.triggerAtCompletionOf(dma0);
update_responsibility = update_setup();
dma0.enable();
dma1.enable();
dma0.attachInterrupt(isr0);
dma1.attachInterrupt(isr1);
}
void AudioInputAnalogStereo::isr0(void)
{
uint32_t daddr, offset;
const uint16_t *src, *end;
uint16_t *dest;
daddr = (uint32_t)(dma0.TCD->DADDR);
dma0.clearInterrupt();
//digitalWriteFast(32, HIGH);
if (daddr < (uint32_t)left_buffer + sizeof(left_buffer) / 2) {
// DMA is receiving to the first half of the buffer
// need to remove data from the second half
src = (uint16_t *)&left_buffer[AUDIO_BLOCK_SAMPLES/2];
end = (uint16_t *)&left_buffer[AUDIO_BLOCK_SAMPLES];
} else {
// DMA is receiving to the second half of the buffer
// need to remove data from the first half
src = (uint16_t *)&left_buffer[0];
end = (uint16_t *)&left_buffer[AUDIO_BLOCK_SAMPLES/2];
//if (update_responsibility) AudioStream::update_all();
}
if (block_left != NULL) {
offset = offset_left;
if (offset > AUDIO_BLOCK_SAMPLES/2) offset = AUDIO_BLOCK_SAMPLES/2;
offset_left = offset + AUDIO_BLOCK_SAMPLES/2;
dest = (uint16_t *)&(block_left->data[offset]);
do {
*dest++ = *src++;
} while (src < end);
}
//digitalWriteFast(32, LOW);
}
void AudioInputAnalogStereo::isr1(void)
{
uint32_t daddr, offset;
const uint16_t *src, *end;
uint16_t *dest;
daddr = (uint32_t)(dma1.TCD->DADDR);
dma1.clearInterrupt();
//digitalWriteFast(33, HIGH);
if (daddr < (uint32_t)right_buffer + sizeof(right_buffer) / 2) {
// DMA is receiving to the first half of the buffer
// need to remove data from the second half
src = (uint16_t *)&right_buffer[AUDIO_BLOCK_SAMPLES/2];
end = (uint16_t *)&right_buffer[AUDIO_BLOCK_SAMPLES];
if (update_responsibility) AudioStream::update_all();
} else {
// DMA is receiving to the second half of the buffer
// need to remove data from the first half
src = (uint16_t *)&right_buffer[0];
end = (uint16_t *)&right_buffer[AUDIO_BLOCK_SAMPLES/2];
}
if (block_right != NULL) {
offset = offset_right;
if (offset > AUDIO_BLOCK_SAMPLES/2) offset = AUDIO_BLOCK_SAMPLES/2;
offset_right = offset + AUDIO_BLOCK_SAMPLES/2;
dest = (uint16_t *)&(block_right->data[offset]);
do {
*dest++ = *src++;
} while (src < end);
}
//digitalWriteFast(33, LOW);
}
void AudioInputAnalogStereo::update(void)
{
audio_block_t *new_left=NULL, *out_left=NULL;
audio_block_t *new_right=NULL, *out_right=NULL;
int32_t tmp;
int16_t s, *p, *end;
//Serial.println("update");
// allocate new block (ok if both NULL)
new_left = allocate();
if (new_left == NULL) {
new_right = NULL;
} else {
new_right = allocate();
if (new_right == NULL) {
release(new_left);
new_left = NULL;
}
}
__disable_irq();
if (offset_left < AUDIO_BLOCK_SAMPLES || offset_right < AUDIO_BLOCK_SAMPLES) {
// the DMA hasn't filled up both blocks
if (block_left == NULL) {
block_left = new_left;
offset_left = 0;
new_left = NULL;
}
if (block_right == NULL) {
block_right = new_right;
offset_right = 0;
new_right = NULL;
}
__enable_irq();
if (new_left) release(new_left);
if (new_right) release(new_right);
return;
}
// the DMA filled blocks, so grab them and get the
// new blocks to the DMA, as quickly as possible
out_left = block_left;
out_right = block_right;
block_left = new_left;
block_right = new_right;
offset_left = 0;
offset_right = 0;
__enable_irq();
//
// DC Offset Removal Filter
// 1-pole digital high-pass filter implementation
// y = a*(x[n] - x[n-1] + y[n-1])
// The coefficient "a" is as follows:
// a = UNITY*e^(-2*pi*fc/fs)
// fc = 2 @ fs = 44100
//
// DC removal, LEFT
p = out_left->data;
end = p + AUDIO_BLOCK_SAMPLES;
do {
tmp = (uint16_t)(*p);
tmp = ( ((int32_t) tmp) << 14);
int32_t acc = hpf_y1[0] - hpf_x1[0];
acc += tmp;
hpf_y1[0] = FRACMUL_SHL(acc, COEF_HPF_DCBLOCK, 1);
hpf_x1[0] = tmp;
s = signed_saturate_rshift(hpf_y1[0], 16, 14);
*p++ = s;
} while (p < end);
// DC removal, RIGHT
p = out_right->data;
end = p + AUDIO_BLOCK_SAMPLES;
do {
tmp = (uint16_t)(*p);
tmp = ( ((int32_t) tmp) << 14);
int32_t acc = hpf_y1[1] - hpf_x1[1];
acc += tmp;
hpf_y1[1]= FRACMUL_SHL(acc, COEF_HPF_DCBLOCK, 1);
hpf_x1[1] = tmp;
s = signed_saturate_rshift(hpf_y1[1], 16, 14);
*p++ = s;
} while (p < end);
// then transmit the AC data
transmit(out_left, 0);
release(out_left);
transmit(out_right, 1);
release(out_right);
}
#if defined(__MK20DX256__)
static const uint8_t pin2sc1a[] = {
5, 14, 8+128, 9+128, 13, 12, 6, 7, 15, 4, 0, 19, 3, 19+128, // 0-13 -> A0-A13
5, 14, 8+128, 9+128, 13, 12, 6, 7, 15, 4, // 14-23 are A0-A9
255, 255, // 24-25 are digital only
5+192, 5+128, 4+128, 6+128, 7+128, 4+192, // 26-31 are A15-A20
255, 255, // 32-33 are digital only
0, 19, 3, 19+128, // 34-37 are A10-A13
26, // 38 is temp sensor,
18+128, // 39 is vref
23 // 40 is A14
};
#elif defined(__MK64FX512__) || defined(__MK66FX1M0__)
static const uint8_t pin2sc1a[] = {
5, 14, 8+128, 9+128, 13, 12, 6, 7, 15, 4, 3, 19+128, 14+128, 15+128, // 0-13 -> A0-A13
5, 14, 8+128, 9+128, 13, 12, 6, 7, 15, 4, // 14-23 are A0-A9
255, 255, 255, 255, 255, 255, 255, // 24-30 are digital only
14+128, 15+128, 17, 18, 4+128, 5+128, 6+128, 7+128, 17+128, // 31-39 are A12-A20
255, 255, 255, 255, 255, 255, 255, 255, 255, // 40-48 are digital only
10+128, 11+128, // 49-50 are A23-A24
255, 255, 255, 255, 255, 255, 255, // 51-57 are digital only
255, 255, 255, 255, 255, 255, // 58-63 (sd card pins) are digital only
3, 19+128, // 64-65 are A10-A11
23, 23+128,// 66-67 are A21-A22 (DAC pins)
1, 1+128, // 68-69 are A25-A26 (unused USB host port on Teensy 3.5)
26, // 70 is Temperature Sensor
18+128 // 71 is Vref
};
#endif
static int analogReadADC1(uint8_t pin)
{
ADC1_SC1A = 9;
while (1) {
if ((ADC1_SC1A & ADC_SC1_COCO)) {
return ADC1_RA;
}
}
if (pin >= sizeof(pin2sc1a)) return 0;
uint8_t channel = pin2sc1a[pin];
if ((channel & 0x80) == 0) return 0;
if (channel == 255) return 0;
if (channel & 0x40) {
ADC1_CFG2 &= ~ADC_CFG2_MUXSEL;
} else {
ADC1_CFG2 |= ADC_CFG2_MUXSEL;
}
ADC1_SC1A = channel & 0x3F;
while (1) {
if ((ADC1_SC1A & ADC_SC1_COCO)) {
return ADC1_RA;
}
}
}
#else
void AudioInputAnalogStereo::init(uint8_t pin0, uint8_t pin1)
{
}
void AudioInputAnalogStereo::update(void)
{
}
#endif
| 32.226667 | 94 | 0.659247 | InspiredChaos |
0767d5a2a29a50e096bbb849b5c876dab5329a7f | 30,872 | cpp | C++ | dlls/Game/scene/MainMenu.cpp | Mynsu/sirtet_SFML | ad1b64597868959d96d27fcb73fd272f41b21e16 | [
"MIT"
] | null | null | null | dlls/Game/scene/MainMenu.cpp | Mynsu/sirtet_SFML | ad1b64597868959d96d27fcb73fd272f41b21e16 | [
"MIT"
] | null | null | null | dlls/Game/scene/MainMenu.cpp | Mynsu/sirtet_SFML | ad1b64597868959d96d27fcb73fd272f41b21e16 | [
"MIT"
] | null | null | null | #include "../pch.h"
#include "MainMenu.h"
#include "../ServiceLocatorMirror.h"
bool ::scene::MainMenu::IsInstantiated = false;
::scene::MainMenu::MainMenu( const sf::RenderWindow& window )
: mIsCursorOnButton( false ),
mNextSceneID( ::scene::ID::AS_IS )
{
ASSERT_TRUE( false == IsInstantiated );
loadResources( window );
IsInstantiated = true;
}
::scene::MainMenu::~MainMenu( )
{
IsInstantiated = false;
}
void scene::MainMenu::loadResources( const sf::RenderWindow& )
{
std::string spritePath( "Images/MainMenu.png" );
mSoundPaths[(int)SoundIndex::BGM] = "Sounds/korobeiniki.mp3";
mSoundPaths[(int)SoundIndex::SELECTION] = "Sounds/selection.wav";
mDrawingInfo.logoSourcePosition.x = 0;
mDrawingInfo.logoSourcePosition.y = 0;
mDrawingInfo.logoClipSize.x = 256;
mDrawingInfo.logoClipSize.y = 256;
mDrawingInfo.logoDestinationPosition.x = 474.f;
mDrawingInfo.logoDestinationPosition.y = 302.f;
mDrawingInfo.buttonSingleSourcePosition.x = 0;
mDrawingInfo.buttonSingleSourcePosition.y = 256;
mDrawingInfo.buttonSingleClipSize.x = 256;
mDrawingInfo.buttonSingleClipSize.y = 128;
mDrawingInfo.buttonSinglePosition.x = 150.f;
mDrawingInfo.buttonSinglePosition.y = 150.f;
mDrawingInfo.buttonOnlineSourcePosition.x = 0;
mDrawingInfo.buttonOnlineSourcePosition.y = 256+128;
mDrawingInfo.buttonOnlineClipSize.x = 256;
mDrawingInfo.buttonOnlineClipSize.y = 128;
mDrawingInfo.buttonOnlinePosition.x = 150.f;
mDrawingInfo.buttonOnlinePosition.y = 300.f;
std::string fontPath( "Fonts/AGENCYB.ttf" );
uint16_t fontSize = 30;
sf::Vector2f copyrightPosition( 150.f, 150.f );
std::string copyright;
lua_State* lua = luaL_newstate();
const std::string scriptPath( "Scripts/MainMenu.lua" );
if ( true == luaL_dofile(lua, scriptPath.data()) )
{
gService()->console().printFailure( FailureLevel::FATAL,
"File Not Found: "+scriptPath );
}
else
{
luaL_openlibs( lua );
const int TOP_IDX = -1;
std::string tableName( "Sprite" );
lua_getglobal( lua, tableName.data() );
if ( false == lua_istable(lua, TOP_IDX) )
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName, scriptPath );
}
else
{
std::string field( "path" );
lua_pushstring( lua, field.data() );
lua_gettable( lua, 1 );
int type = lua_type(lua, TOP_IDX);
if ( LUA_TSTRING == type )
{
spritePath = lua_tostring(lua, TOP_IDX);
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
std::string innerTableName( "logo" );
lua_pushstring( lua, innerTableName.data() );
lua_gettable( lua, 1 );
if ( false == lua_istable(lua, TOP_IDX) )
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName, scriptPath );
}
else
{
field = "sourceX";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
mDrawingInfo.logoSourcePosition.x = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+innerTableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "sourceY";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
mDrawingInfo.logoSourcePosition.y = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+innerTableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "clipWidth";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
mDrawingInfo.logoClipSize.x = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+innerTableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "clipHeight";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
mDrawingInfo.logoClipSize.y = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+innerTableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "destinationX";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const float temp = (float)lua_tonumber(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
mDrawingInfo.logoDestinationPosition.x = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+innerTableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "destinationY";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const float temp = (float)lua_tonumber(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
mDrawingInfo.logoDestinationPosition.y = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+innerTableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
}
lua_pop( lua, 1 );
innerTableName = "buttonSingle";
lua_pushstring( lua, innerTableName.data() );
lua_gettable( lua, 1 );
if ( false == lua_istable(lua, TOP_IDX) )
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName, scriptPath );
}
else
{
field = "sourceX";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
mDrawingInfo.buttonSingleSourcePosition.x = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+innerTableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "sourceY";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
mDrawingInfo.buttonSingleSourcePosition.y = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+innerTableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "clipWidth";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
mDrawingInfo.buttonSingleClipSize.x = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+innerTableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "clipHeight";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
mDrawingInfo.buttonSingleClipSize.y = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+innerTableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "destinationX";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const float temp = (float)lua_tonumber(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
mDrawingInfo.buttonSinglePosition.x = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+innerTableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "destinationY";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const float temp = (float)lua_tonumber(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
mDrawingInfo.buttonSinglePosition.y = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+innerTableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
}
lua_pop( lua, 1 );
innerTableName = "buttonOnline";
lua_pushstring( lua, innerTableName.data() );
lua_gettable( lua, 1 );
if ( false == lua_istable(lua, TOP_IDX) )
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName, scriptPath );
}
else
{
field = "sourceX";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
mDrawingInfo.buttonOnlineSourcePosition.x = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+innerTableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "sourceY";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
mDrawingInfo.buttonOnlineSourcePosition.y = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+innerTableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "clipWidth";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
mDrawingInfo.buttonOnlineClipSize.x = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+innerTableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "clipHeight";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const int32_t temp = (int32_t)lua_tointeger(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
mDrawingInfo.buttonOnlineClipSize.y = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+innerTableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "destinationX";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const float temp = (float)lua_tonumber(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
mDrawingInfo.buttonOnlinePosition.x = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+innerTableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "destinationY";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const float temp = (float)lua_tonumber(lua, TOP_IDX);
if ( 0 > temp )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
mDrawingInfo.buttonOnlinePosition.y = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+innerTableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
}
lua_pop( lua, 1 );
}
lua_pop( lua, 1 );
tableName = "Copyright";
lua_getglobal( lua, tableName.data() );
if ( false == lua_istable(lua, TOP_IDX) )
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName, scriptPath );
}
else
{
std::string field( "font" );
lua_pushstring( lua, field.data() );
lua_gettable( lua, 1 );
int type = lua_type(lua, TOP_IDX);
if ( LUA_TSTRING == type )
{
fontPath = lua_tostring(lua, TOP_IDX);
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "fontSize";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 1 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const uint16_t temp = (uint16_t)lua_tointeger(lua, TOP_IDX);
if ( temp < 0 )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
fontSize = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "positionX";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 1 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const float temp = (float)lua_tonumber(lua, TOP_IDX);
if ( temp < 0 )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
copyrightPosition.x = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "positionY";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 1 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TNUMBER == type )
{
const float temp = (float)lua_tonumber(lua, TOP_IDX);
if ( temp < 0 )
{
gService()->console().printScriptError( ExceptionType::RANGE_CHECK,
tableName+':'+field, scriptPath );
}
else
{
copyrightPosition.y = temp;
}
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
field = "text";
lua_pushstring( lua, field.data() );
lua_gettable( lua, 1 );
type = lua_type(lua, TOP_IDX);
if ( LUA_TSTRING == type )
{
copyright = lua_tostring(lua, TOP_IDX);
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
}
lua_pop( lua, 1 );
tableName = "Sound";
lua_getglobal( lua, tableName.data() );
if ( false == lua_istable(lua, TOP_IDX) )
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK, tableName, scriptPath );
}
else
{
std::string innerTableName( "BGM" );
lua_pushstring( lua, innerTableName.data() );
lua_gettable( lua, 1 );
if ( false == lua_istable(lua, TOP_IDX) )
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName, scriptPath );
}
else
{
std::string field( "path" );
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
int type = lua_type(lua, TOP_IDX);
if ( LUA_TSTRING == type )
{
mSoundPaths[(int)SoundIndex::BGM] = lua_tostring(lua, TOP_IDX);
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
}
lua_pop( lua, 1 );
innerTableName = "onSelection";
lua_pushstring( lua, innerTableName.data() );
lua_gettable( lua, 1 );
if ( false == lua_istable(lua, TOP_IDX) )
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+innerTableName, scriptPath );
}
else
{
std::string field( "path" );
lua_pushstring( lua, field.data() );
lua_gettable( lua, 2 );
int type = lua_type(lua, TOP_IDX);
if ( LUA_TSTRING == type )
{
mSoundPaths[(int)SoundIndex::SELECTION] = lua_tostring(lua, TOP_IDX);
}
else if ( LUA_TNIL == type )
{
gService()->console().printScriptError( ExceptionType::VARIABLE_NOT_FOUND,
tableName+':'+field, scriptPath );
}
else
{
gService()->console().printScriptError( ExceptionType::TYPE_CHECK,
tableName+':'+field, scriptPath );
}
lua_pop( lua, 1 );
}
lua_pop( lua, 1 );
}
lua_pop( lua, 1 );
}
lua_close( lua );
if ( false == mTexture.loadFromFile(spritePath) )
{
gService()->console().printFailure( FailureLevel::WARNING,
"File Not Found: "+spritePath );
}
mSprite.setTexture( mTexture );
if ( false == mFont.loadFromFile(fontPath) )
{
gService()->console().printFailure( FailureLevel::WARNING,
"File Not Found: "+fontPath );
}
mTextLabelForCopyrightNotice.setCharacterSize( fontSize );
mTextLabelForCopyrightNotice.setFont( mFont );
mTextLabelForCopyrightNotice.setPosition( copyrightPosition );
mTextLabelForCopyrightNotice.setString( copyright );
if ( false == gService()->sound().playBGM(mSoundPaths[(int)SoundIndex::BGM], true) )
{
gService()->console().printFailure(FailureLevel::WARNING,
"File Not Found: "+mSoundPaths[(int)SoundIndex::BGM] );
}
}
::scene::ID scene::MainMenu::update( std::vector<sf::Event>& eventQueue,
const sf::RenderWindow& )
{
for ( const sf::Event& it : eventQueue )
{
if ( sf::Event::KeyPressed == it.type &&
sf::Keyboard::Escape == it.key.code )
{
auto& vault = gService()->vault();
const auto it = vault.find(HK_IS_RUNNING);
ASSERT_TRUE( vault.end() != it );
it->second = 0;
}
}
return mNextSceneID;
}
void ::scene::MainMenu::draw( sf::RenderWindow& window )
{
bool hasGainedFocus = false;
auto& vault = gService()->vault();
{
const auto it = vault.find(HK_HAS_GAINED_FOCUS);
ASSERT_TRUE( vault.end() != it );
hasGainedFocus = (bool)it->second;
}
if ( true == hasGainedFocus && false == gService()->console().isVisible() )
{
const sf::Vector2f mousePos( sf::Mouse::getPosition()-window.getPosition() );
const sf::FloatRect boundLogo( mDrawingInfo.logoDestinationPosition,
sf::Vector2f(mDrawingInfo.logoClipSize) );
if ( true == boundLogo.contains(mousePos) )
{
// Logo
const sf::Vector2i sourcePos( mDrawingInfo.logoSourcePosition.x + mDrawingInfo.logoClipSize.x,
mDrawingInfo.logoSourcePosition.y );
mSprite.setTextureRect( sf::IntRect(sourcePos, mDrawingInfo.logoClipSize) );
mSprite.setPosition( mDrawingInfo.logoDestinationPosition );
window.draw( mSprite );
// Copyright
window.draw( mTextLabelForCopyrightNotice );
}
else if ( const sf::FloatRect boundButtonSingle(mDrawingInfo.buttonSinglePosition,
sf::Vector2f(mDrawingInfo.buttonSingleClipSize));
true == boundButtonSingle.contains(mousePos) )
{
// Logo
mSprite.setTextureRect( sf::IntRect(mDrawingInfo.logoSourcePosition,
mDrawingInfo.logoClipSize) );
mSprite.setPosition( mDrawingInfo.logoDestinationPosition );
window.draw( mSprite );
if ( true == sf::Mouse::isButtonPressed(sf::Mouse::Left) )
{
mNextSceneID = ::scene::ID::SINGLE_PLAY;
}
// Buttons
const sf::Vector2i sourcePos( mDrawingInfo.buttonSingleSourcePosition.x + mDrawingInfo.buttonSingleClipSize.x,
mDrawingInfo.buttonSingleSourcePosition.y );
mSprite.setTextureRect( sf::IntRect(sourcePos, mDrawingInfo.buttonSingleClipSize) );
mSprite.setPosition( mDrawingInfo.buttonSinglePosition );
window.draw( mSprite );
mSprite.setTextureRect( sf::IntRect(mDrawingInfo.buttonOnlineSourcePosition,
mDrawingInfo.buttonOnlineClipSize) );
mSprite.setPosition( mDrawingInfo.buttonOnlinePosition );
window.draw( mSprite );
if ( false == mIsCursorOnButton )
{
mIsCursorOnButton = true;
if ( false == gService()->sound().playSFX(mSoundPaths[(int)SoundIndex::SELECTION]) )
{
gService()->console().printFailure(FailureLevel::WARNING,
"File Not Found: "+mSoundPaths[(int)SoundIndex::SELECTION] );
}
}
}
else if ( const sf::FloatRect boundButtonOnline(mDrawingInfo.buttonOnlinePosition,
sf::Vector2f(mDrawingInfo.buttonOnlineClipSize));
true == boundButtonOnline.contains(mousePos) )
{
// Logo
mSprite.setTextureRect( sf::IntRect(mDrawingInfo.logoSourcePosition,
mDrawingInfo.logoClipSize) );
mSprite.setPosition( mDrawingInfo.logoDestinationPosition );
window.draw( mSprite );
if ( true == sf::Mouse::isButtonPressed(sf::Mouse::Left) )
{
mNextSceneID = ::scene::ID::ONLINE_BATTLE;
}
// Buttons
mSprite.setTextureRect( sf::IntRect(mDrawingInfo.buttonSingleSourcePosition,
mDrawingInfo.buttonSingleClipSize) );
mSprite.setPosition( mDrawingInfo.buttonSinglePosition );
window.draw( mSprite );
const sf::Vector2i sourcePos( mDrawingInfo.buttonOnlineSourcePosition.x + mDrawingInfo.buttonOnlineClipSize.x,
mDrawingInfo.buttonOnlineSourcePosition.y );
mSprite.setTextureRect( sf::IntRect(sourcePos, mDrawingInfo.buttonOnlineClipSize) );
mSprite.setPosition( mDrawingInfo.buttonOnlinePosition );
window.draw( mSprite );
if ( false == mIsCursorOnButton )
{
mIsCursorOnButton = true;
if ( false == gService()->sound().playSFX(mSoundPaths[(int)SoundIndex::SELECTION]) )
{
gService()->console().printFailure(FailureLevel::WARNING,
"File Not Found: "+mSoundPaths[(int)SoundIndex::SELECTION] );
}
}
}
else
{
goto defaultLabel;
}
}
else
{
defaultLabel:
mSprite.setTextureRect( sf::IntRect(mDrawingInfo.logoSourcePosition,
mDrawingInfo.logoClipSize) );
mSprite.setPosition( mDrawingInfo.logoDestinationPosition );
window.draw( mSprite );
mNextSceneID = ::scene::ID::AS_IS;
mSprite.setPosition( mDrawingInfo.buttonSinglePosition );
mSprite.setTextureRect( sf::IntRect(mDrawingInfo.buttonSingleSourcePosition,
mDrawingInfo.buttonSingleClipSize) );
window.draw( mSprite );
mSprite.setPosition( mDrawingInfo.buttonOnlinePosition );
mSprite.setTextureRect( sf::IntRect(mDrawingInfo.buttonOnlineSourcePosition,
mDrawingInfo.buttonOnlineClipSize) );
window.draw( mSprite );
mIsCursorOnButton = false;
}
}
::scene::ID scene::MainMenu::currentScene( ) const
{
return ::scene::ID::MAIN_MENU;
}
| 30.089669 | 113 | 0.616611 | Mynsu |
07692fe54f3ed175bee0929e758ecff96029093e | 4,724 | cpp | C++ | addons/a3/language_f_tank/config.cpp | GoldJohnKing/Arma-III-Chinese-Localization-Enhanced | 6ce8a75d1176adc2f1d5f4e9abd5dd2a1c581222 | [
"MIT"
] | 23 | 2017-07-13T16:15:55.000Z | 2022-01-06T04:56:34.000Z | addons/a3/language_f_tank/config.cpp | GoldJohnKing/Arma-III-Chinese-Localization-Enhanced | 6ce8a75d1176adc2f1d5f4e9abd5dd2a1c581222 | [
"MIT"
] | 3 | 2017-07-14T10:34:25.000Z | 2021-02-28T18:42:43.000Z | addons/a3/language_f_tank/config.cpp | GoldJohnKing/Arma-III-Chinese-Localization-Enhanced | 6ce8a75d1176adc2f1d5f4e9abd5dd2a1c581222 | [
"MIT"
] | 13 | 2017-07-14T04:13:43.000Z | 2021-11-27T04:45:29.000Z | ////////////////////////////////////////////////////////////////////
//DeRap: 新增資料夾\language_f_tank\config.bin
//Produced from mikero's Dos Tools Dll version 6.80
//'now' is Sun Mar 31 23:01:41 2019 : 'file' last modified on Tue Jan 29 22:16:12 2019
//http://dev-heaven.net/projects/list_files/mikero-pbodll
////////////////////////////////////////////////////////////////////
#define _ARMA_
//(13 Enums)
enum {
destructengine = 2,
destructdefault = 6,
destructwreck = 7,
destructtree = 3,
destructtent = 4,
stabilizedinaxisx = 1,
stabilizedinaxesxyz = 4,
stabilizedinaxisy = 2,
stabilizedinaxesboth = 3,
destructno = 0,
stabilizedinaxesnone = 0,
destructman = 5,
destructbuilding = 1
};
class CfgPatches
{
class A3_Language_F_Tank
{
author = "$STR_A3_Bohemia_Interactive";
name = "Arma 3 Tank - Texts and Translations";
url = "https://www.arma3.com";
requiredAddons[] = {"A3_Data_F_Tank"};
requiredVersion = 0.1;
units[] = {};
weapons[] = {};
};
};
class CfgHints
{
class PremiumContent
{
class PremiumTank
{
displayName = "$STR_A3_Tank_CfgMods_nameDLC";
description = "$STR_A3_CfgHints_PremiumContent_PremiumTank0";
tip = "$STR_A3_CfgHints_PremiumContent_PremiumKarts2";
arguments[] = {{"$STR_A3_cfgmods_tank_overview0"},"""<img size='9' shadow='0' image='A3\Data_F_tank\Images\tank_fm_overview_co' />""","""http://steamcommunity.com/stats/107410/achievements"""};
image = "\a3\data_f_tank\logos\arma3_tank_icon_hint_ca.paa";
logicalOrder = 7;
class Hint
{
displayName = "$STR_A3_Tank_CfgMods_nameDLC";
description = "%11%1%12";
tip = "$STR_A3_CfgHints_PremiumContent_PremiumKarts2";
arguments[] = {{"$STR_A3_cfgmods_tank_overview0"},"""<img size='7' shadow='0' image='A3\Data_F_tank\Images\tank_fm_overview_co' />"""};
image = "\a3\data_f_tank\logos\arma3_tank_icon_hint_ca.paa";
};
};
};
class DlcMessage
{
class Dlc571710;
class Dlc798390: Dlc571710
{
displayName = "$STR_A3_cfgmods_tank_name0";
image = "\a3\Data_F_tank\logos\arma3_tank_logo_hint_ca.paa";
};
class Dlc798390FM: Dlc798390{};
};
class Weapons
{
class MissileFlightModes
{
displayName = "$STR_A3_MissileFlightModes1";
description = "$STR_A3_MissileFlightModes2";
tip = "$STR_A3_MissileFlightModes3";
arguments[] = {};
image = "\a3\ui_f\data\gui\cfg\hints\Missile_Modes_ca.paa";
logicalOrder = 25;
};
class WarheadTypes
{
displayName = "$STR_A3_WarheadTypes1";
description = "$STR_A3_WarheadTypes2";
tip = "";
arguments[] = {};
image = "\a3\ui_f\data\gui\cfg\hints\Warhead_Types_ca.paa";
logicalOrder = 26;
};
class ReactiveArmor
{
displayName = "$STR_A3_ReactiveArmor1";
description = "$STR_A3_ReactiveArmor2";
tip = "$STR_A3_ReactiveArmor3";
arguments[] = {};
image = "\a3\ui_f\data\gui\cfg\hints\Armor_ERA_ca.paa";
logicalOrder = 28;
};
class SlatArmor
{
displayName = "$STR_A3_SlatArmor1";
description = "$STR_A3_SlatArmor2";
tip = "$STR_A3_SlatArmor3";
arguments[] = {};
image = "\a3\ui_f\data\gui\cfg\hints\Armor_SLAT_ca.paa";
logicalOrder = 29;
};
class LOAL
{
displayName = "$STR_A3_LOAL1";
description = "$STR_A3_LOAL2";
tip = "$STR_A3_LOAL3";
arguments[] = {{{"VehLockTargets"}},{{"NextWeapon"}}};
image = "\a3\ui_f\data\gui\cfg\hints\Missile_Seeking_ca.paa";
logicalOrder = 30;
};
};
class VehicleList
{
class Angara
{
displayName = "$STR_A3_Angara_library0";
description = "$STR_A3_Angara_library1";
tip = "";
arguments[] = {};
image = "\a3\ui_f\data\gui\cfg\hints\Miss_icon_ca.paa";
dlc = 798390;
vehicle = "O_MBT_04_cannon_F";
};
class Rhino
{
displayName = "$STR_A3_Rhino_library0";
description = "$STR_A3_Rhino_library1";
tip = "";
arguments[] = {};
image = "\a3\ui_f\data\gui\cfg\hints\Miss_icon_ca.paa";
dlc = 798390;
vehicle = "B_AFV_Wheeled_01_cannon_F";
};
class Nyx
{
displayName = "$STR_A3_Nyx_library0";
description = "$STR_A3_Nyx_library1";
tip = "";
arguments[] = {};
image = "\a3\ui_f\data\gui\cfg\hints\Miss_icon_ca.paa";
dlc = 798390;
vehicle = "I_LT_01_AT_F";
};
};
class WeaponList
{
class Vorona
{
displayName = "$STR_A3_Vorona_library0";
description = "$STR_A3_Vorona_library1";
tip = "";
arguments[] = {};
image = "\a3\ui_f\data\gui\cfg\hints\Miss_icon_ca.paa";
dlc = 798390;
weapon = "launch_O_Vorona_brown_F";
};
class MAAWS
{
displayName = "$STR_A3_MAAWS_library0";
description = "$STR_A3_MAAWS_library1";
tip = "";
arguments[] = {};
image = "\a3\ui_f\data\gui\cfg\hints\Miss_icon_ca.paa";
dlc = 798390;
weapon = "launch_MRAWS_green_F";
};
};
};
| 26.689266 | 196 | 0.652413 | GoldJohnKing |
0769876a45ca80bd2103ecc61d3775b7d9233c98 | 5,013 | cpp | C++ | zc702/GEMM_Hardware_NoInterrupt/matrix_mult_accel.cpp | kranik/ENEAC | 8faceedf89f598f7fab728ee94341a47c8976830 | [
"BSD-3-Clause"
] | null | null | null | zc702/GEMM_Hardware_NoInterrupt/matrix_mult_accel.cpp | kranik/ENEAC | 8faceedf89f598f7fab728ee94341a47c8976830 | [
"BSD-3-Clause"
] | null | null | null | zc702/GEMM_Hardware_NoInterrupt/matrix_mult_accel.cpp | kranik/ENEAC | 8faceedf89f598f7fab728ee94341a47c8976830 | [
"BSD-3-Clause"
] | null | null | null | /* File: matrix_mult_accel.cpp
*
Copyright (c) [2016] [Mohammad Hosseinabady (mohammad@hosseinabady.com)]
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 has been written at University of Bristol
* for the ENPOWER project funded by EPSRC
*
* File name : matrix_mult_accel.cpp
* author : Mohammad hosseinabady mohammad@hosseinabady.com
* date : 1 October 2016
* blog: https://highlevel-synthesis.com/
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "matrix_mult.h"
inline void mxv(float* a, float* c, float b[B_HEIGHT][B_WIDTH_BLOCK]);
typedef unsigned long u32;
// note that BLOCK shoudl be less than B_WIDTH_BLOCK
const int BLOCK=B_WIDTH_BLOCK; //BLOCK should be less than B_WIDTH_BLOCK
const int STEP=1;
/*
The amount of data saved in the FPGA is B_HEIGHT*B_WIDTH_BLOCK+A_WIDTH+B_WIDTH_BLOCK which should be less than FPGA BRAM size
*/
#pragma SDS data sys_port(A:ACP,B:ACP,C:ACP)
////#pragma SDS data zero_copy(A[0:line_count*A_WIDTH],B[0:B_HEIGHT*B_WIDTH], C[0:line_count*B_WIDTH],status[0:1])
#pragma SDS data zero_copy(A[0:line_count*A_WIDTH],B[0:B_HEIGHT*B_WIDTH], C[0:line_count*B_WIDTH])
//#pragma SDS data data_mover(status:AXIDMA_SG)
//#pragma SDS data copy(status[0:2])
//#pragma SDS data access_pattern(status:SEQUENTIAL)
//#pragma SDS data mem_attribute(interrupt:NON_CACHEABLE)
////void mmult_top(float* A, float* B, float* C,int line_count, int *interrupt,int *status)
void mmult_top(float* A, float* B, float* C,int line_count, int &dummy)
{
float A_accel[A_WIDTH], B_accel[B_HEIGHT][B_WIDTH_BLOCK], C_accel[B_WIDTH_BLOCK];
#pragma HLS array_partition variable=A_accel block factor=16 dim=1
#pragma HLS array_partition variable=B_accel block factor=16 dim=2
#pragma HLS array_partition variable=C_accel complete
//int *local = (int *)(0x41200000);
//*interrupt = 255;
for (int B_index = 0; B_index < B_WIDTH/B_WIDTH_BLOCK; B_index++) {
for (int i = 0; i < B_HEIGHT; i++) {
for (int j = 0; j < B_WIDTH_BLOCK; j++) {
B_accel[i][j] = B[i*B_WIDTH+j+B_index*B_WIDTH_BLOCK];
}
}
for (int A_index = 0; A_index < line_count; A_index++) {
for (int j = 0; j < A_WIDTH; j++) {
A_accel[j] = A[A_index*A_WIDTH+j];
}
mmult_accel(A_accel, B_accel, C_accel);
for (int i = 0; i < C_HEIGHT_BLOCK; i++) {
for (int j = 0; j < C_WIDTH_BLOCK; j++) {
C[(i+A_index*A_HEIGHT_BLOCK)*C_WIDTH+j+B_index*B_WIDTH_BLOCK] = C_accel[i*C_WIDTH_BLOCK+j];
}
}
}
}
//*debug = (int)(size_t)interrupt;
//// *interrupt = 255; //switch on leds
//status[0] = 255;
//status[1] = 255;
//// *status = 255; //trigger interrupt by writting to gpio
dummy = 1;
}
int mmult_accel( float A[A_HEIGHT_BLOCK*A_WIDTH], float B[B_HEIGHT][B_WIDTH_BLOCK], float C[C_HEIGHT_BLOCK*C_WIDTH_BLOCK])
{
//float b[B_HEIGHT][B_WIDTH_BLOCK];
//#pragma HLS ARRAY_PARTITION variable=b complete dim=2
/*
for (int i = 0; i < B_HEIGHT; i++) {
for (int j = 0; j < B_WIDTH_BLOCK; j++) {
#pragma HLS PIPELINE
b[i][j] = *(B+i*B_WIDTH_BLOCK+j);
}
}*/
for (int p = 0; p < A_HEIGHT_BLOCK; p+=STEP) {
mxv(A+p*A_WIDTH, C+p*C_WIDTH_BLOCK, B);
}
return 0;
}
inline void mxv(float *A, float* C, float b[B_HEIGHT][B_WIDTH_BLOCK]) {
//float a[A_WIDTH];
//float c[B_WIDTH_BLOCK];
//#pragma HLS ARRAY_PARTITION variable=c complete dim=1
//#pragma HLS array_partition variable=a block factor=16
//memcpy(a,(float *)(A),A_WIDTH*sizeof(float));
//for (int i = 0; i < A_WIDTH; i++) {
// a[i] = A[i];
//}
for (int j = 0; j < C_WIDTH_BLOCK; j++) {
#pragma HLS UNROLL
C[j] = 0;
}
for(int k = 0; k < B_HEIGHT; k+=1) {
for (int j = 0; j < B_WIDTH_BLOCK; j++) {
#pragma HLS PIPELINE
#pragma HLS UNROLL factor=BLOCK
C[j] += A[k]*b[k][j];
}
}
//
// for (int i = 0; i < B_WIDTH_BLOCK; i++) {
// C[i] = c[i];
// }
//memcpy((float *)(C), c, C_WIDTH_BLOCK*sizeof(float));
return;
}
| 30.944444 | 126 | 0.678436 | kranik |
0769fb57bf876765b4b7cbb2c04f823571eb9dbf | 705 | cpp | C++ | Vijos/1164.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | 18 | 2019-01-01T13:16:59.000Z | 2022-02-28T04:51:50.000Z | Vijos/1164.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | null | null | null | Vijos/1164.cpp | HeRaNO/OI-ICPC-Codes | 4a4639cd3e347b472520065ca6ab8caadde6906d | [
"MIT"
] | 5 | 2019-09-13T08:48:17.000Z | 2022-02-19T06:59:03.000Z | #include <cstdio>
#define MAXN 11
using namespace std;
long long a[MAXN], m[MAXN];
long long n;
void ex_gcd(long long a, long long b, long long &x, long long &y)
{
if (!b)
{
x = 1;
y = 0;
return ;
}
else
{
ex_gcd(b, a % b, x, y);
long long tmp = x;
x = y;
y = tmp - (a / b) * y;
}
}
long long crt(long long n)
{
long long M = 1, ans = 0;
for (int i = 1; i <= n; i++) M *= m[i];
for (int i = 1; i <= n; i++)
{
long long w = M / m[i];
long long x, y;
ex_gcd(w, m[i], x, y);
ans = (ans + x * w * a[i]) % M;
}
return (ans + M) % M;
}
int main()
{
scanf("%lld", &n);
for (int i = 1; i <= n; i++)
scanf("%lld %lld", &m[i], &a[i]);
printf("%lld", crt(n));
return 0;
}
| 15 | 65 | 0.48227 | HeRaNO |
076b03748bc3d9cc6143c38672765a2dd2224054 | 5,069 | cpp | C++ | Code/Tools/FBuild/FBuildTest/Data/TestFastCancel/Cancel/main.cpp | qq573011406/FASTBuild_UnrealEngine | 29c49672f82173a903cb32f0e4656e2fd07ebef2 | [
"MIT"
] | 30 | 2020-07-15T06:16:55.000Z | 2022-02-10T21:37:52.000Z | Code/Tools/FBuild/FBuildTest/Data/TestFastCancel/Cancel/main.cpp | qq573011406/FASTBuild_UnrealEngine | 29c49672f82173a903cb32f0e4656e2fd07ebef2 | [
"MIT"
] | 1 | 2020-11-23T13:35:00.000Z | 2020-11-23T13:35:00.000Z | Code/Tools/FBuild/FBuildTest/Data/TestFastCancel/Cancel/main.cpp | qq573011406/FASTBuild_UnrealEngine | 29c49672f82173a903cb32f0e4656e2fd07ebef2 | [
"MIT"
] | 12 | 2020-09-16T17:39:34.000Z | 2021-08-17T11:32:37.000Z | // main.cpp
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
// system
#if defined( __WINDOWS__ )
#include <Windows.h>
#endif
#if defined( __LINUX__ ) || defined( __APPLE__ )
#include <errno.h>
#include <sys/file.h>
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
// LockSystemMutex
//------------------------------------------------------------------------------
bool LockSystemMutex( const char * name )
{
// NOTE: This function doesn't cleanup failures to simplify the test
// (the process will be terminated anyway)
// Acquire system mutex which should be uncontested
#if defined( __WINDOWS__ )
CreateMutex( nullptr, TRUE, name );
if ( GetLastError() == ERROR_ALREADY_EXISTS )
{
return false; // Test fails
}
return true;
#elif defined( __LINUX__ ) || defined( __APPLE__ )
char tempFileName[256];
sprintf( tempFileName, "/tmp/%s.lock", name );
int handle = open( tempFileName, O_CREAT | O_RDWR, 0666 );
if ( handle < 0 )
{
return false; // Test fails
}
int rc = flock( handle, LOCK_EX | LOCK_NB );
if ( rc )
{
return false; // Test fails
}
return true;
#else
#error Unknown platform
#endif
}
// Spawn
//------------------------------------------------------------------------------
bool Spawn( const char * mutexId )
{
// NOTE: This function doesn't cleanup failures to simplify the test
// (the process will be terminated anyway)
#if defined( __WINDOWS__ )
// Set up the start up info struct.
STARTUPINFO si;
ZeroMemory( &si, sizeof(STARTUPINFO) );
si.cb = sizeof( STARTUPINFO );
si.dwFlags |= STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
// Prepare args
char fullArgs[256];
sprintf_s( fullArgs, "\"FBuildTestCancel.exe\" %s", mutexId );
// create the child
LPPROCESS_INFORMATION processInfo;
if ( !CreateProcess( nullptr,
fullArgs,
nullptr,
nullptr,
false, // inherit handles
0,
nullptr,
nullptr,
&si,
(LPPROCESS_INFORMATION)&processInfo ) )
{
return false;
}
return true;
#else
// prepare args
const char * args[ 3 ] = { "FBuildTestCancel.exe", mutexId, nullptr };
// fork the process
const pid_t childProcessPid = fork();
if ( childProcessPid == -1 )
{
return false;
}
const bool isChild = ( childProcessPid == 0 );
if ( isChild )
{
// transfer execution to new executable
execv( executable, argV );
exit( -1 ); // only get here if execv fails
}
else
{
return true;
}
#endif
}
// Main
//------------------------------------------------------------------------------
int main( int argc, char ** argv )
{
// Check args
if ( argc < 2 )
{
printf( "Bad args (1)\n" );
return 1;
}
// Get the mutex id passed on the command line
const int mutexId = atoi( argv[ 1 ] );
if ( ( mutexId < 1 ) || ( mutexId > 4 ) )
{
printf( "Bad args (2)\n" );
return 2;
}
// Spawn child if we're not the last one
if ( mutexId < 4 )
{
char mutexIdString[2] = { ' ', 0 };
mutexIdString[ 0 ] = (char)( '0' + mutexId + 1 );
if ( !Spawn( mutexIdString ) )
{
printf( "Failed to spawn child '%s'\n", mutexIdString );
return 3;
}
}
// Aqcuire SystemMutex which test uses to check our lifetimes
const char * mutexNames[4] =
{
"FASTBuildFastCancelTest1",
"FASTBuildFastCancelTest2",
"FASTBuildFastCancelTest3",
"FASTBuildFastCancelTest4"
};
const char * mutexName = mutexNames[ mutexId - 1 ];
if ( LockSystemMutex( mutexName ) == false )
{
printf( "Failed to acquire: %s\n", mutexName );
return 4;
}
// Spin forever - test will terminate
int count = 0;
for (;;)
{
#if defined( __WINDOWS__ )
::Sleep( 1000 );
#else
usleep(ms * 1000);
#endif
// If we haven't been terminated in a sensible time frame
// quit to avoid zombie processes. Useful when debugging
// the test also
if ( count > 10 )
{
printf( "Alive for too long: %s\n", mutexName );
return 5;
}
++count;
}
}
//------------------------------------------------------------------------------
| 28.005525 | 80 | 0.459262 | qq573011406 |
076e1fbc108660e2f4ac9955f342916a7cd269de | 222 | hpp | C++ | C++ Programming/CPTS 122/Labs/Inheritance in C++/TestPerson.hpp | subhamb123/WSU-Coding-Projects | bb2910d76ac446f190ce641b869e68ae86d9b760 | [
"MIT"
] | 1 | 2020-09-03T07:09:05.000Z | 2020-09-03T07:09:05.000Z | C++ Programming/CPTS 122/Labs/Inheritance in C++/TestPerson.hpp | subhamb123/WSU-Coding-Projects | bb2910d76ac446f190ce641b869e68ae86d9b760 | [
"MIT"
] | null | null | null | C++ Programming/CPTS 122/Labs/Inheritance in C++/TestPerson.hpp | subhamb123/WSU-Coding-Projects | bb2910d76ac446f190ce641b869e68ae86d9b760 | [
"MIT"
] | null | null | null | #pragma once
#include "Person.hpp";
class TestPerson : public Person {
public:
void testPerson();
void testCopyPerson();
void testEquals();
void testExtraction();
void testInsertion();
void copyHelper(Person p);
}; | 17.076923 | 34 | 0.725225 | subhamb123 |
076e92c8b7854650814222dd5b7dc9efebcc42eb | 21,717 | cpp | C++ | src/marchingcubes.cpp | menonon/SimpleGLWrapper | a99af4ee9b0e9fef8ac1ffe3b01aef32157929bb | [
"MIT"
] | null | null | null | src/marchingcubes.cpp | menonon/SimpleGLWrapper | a99af4ee9b0e9fef8ac1ffe3b01aef32157929bb | [
"MIT"
] | null | null | null | src/marchingcubes.cpp | menonon/SimpleGLWrapper | a99af4ee9b0e9fef8ac1ffe3b01aef32157929bb | [
"MIT"
] | null | null | null | /*
The MIT License (MIT)
Copyright (c) 2013-2018 menonon
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 "marchingcubes.hpp"
#include "error.hpp"
Shader* MarchingCubes::mMCShader = NULL;
bool MarchingCubes::isInitialized = false;
GLint* MarchingCubes::mEdgeConnection = NULL;
GLint* MarchingCubes::mEdgeFlags = NULL;
Texture<GLint>* MarchingCubes::mTexEdgeConnection = NULL;
MarchingCubes::~MarchingCubes() {
}
MarchingCubes::MarchingCubes() {
mModel = glm::mat4(1.0);
staticInit();
}
void MarchingCubes::staticInit() {
if (isInitialized) {
// do nothing
}
else {
isInitialized = true;
initTables();
initBuffers();
initShader();
}
}
void MarchingCubes::setData(Texture<GLfloat>* aData) {
mData = aData;
mData->createSampler(GL_NEAREST, GL_NEAREST, GL_CLAMP_TO_EDGE);
mData->setTextureUnit(0);
}
void MarchingCubes::setThreshold(GLfloat aPercentage) {
GLfloat min = mData->getDataRange().x;
GLfloat max = mData->getDataRange().y;
GLfloat base = max - min;
mThreshold = (aPercentage * 0.01 * base) + min;
//std::cout << "min,value,per,max: " << min << "," << mThreshold << "," << aPercentage << "," << max << std::endl;
}
void MarchingCubes::bind(int i) {
mTexEdgeConnection->bind();
mData->bind();
mCells[i]->bind();
}
void MarchingCubes::unbind(int i) {
mTexEdgeConnection->unbind();
mData->unbind();
mCells[i]->unbind();
}
void MarchingCubes::render(glm::mat4 aProjection, glm::mat4 aView) {
mMCShader->use();
//uniforms update
mMCShader->setUniform("uProjection", aProjection);
mMCShader->setUniform("uModelView", aView * mModel);
mMCShader->setUniform("uSlice", mSlices);
mMCShader->setUniform("uThreshold", mThreshold);
mMCShader->setUniform("uData", mData->getTextureUnit());
mMCShader->setUniform("uEdgeConnection", mTexEdgeConnection->getTextureUnit());
for (int i = 0; i < 1; i++) {
bind(i);
mCells[i]->draw();
unbind(i);
glFlush();
}
mMCShader->unuse();
}
void MarchingCubes::generateGeometry() {
mSlices = mData->getSize();
std::vector<glm::vec3> points[100];
for (int i = 0; i < d; i++) {
mCells[i] = new Geometry(Geometry::POINTS);
points[i].reserve((mSlices.x - 1) * (mSlices.y - 1) * (mSlices.z - 1));
}
for (float i = 0.5; i < mSlices.x - 1; i += 1.0) {
for (float j = 0.5; j < mSlices.y - 1; j += 1.0) {
for (float k = 0.5; k < mSlices.z - 1; k += 1.0) {
int m = static_cast<int>(i) % d;
points[m].push_back(glm::vec3(i, j, k));
}
}
}
for (int i = 0; i < d; i++) {
mCells[i]->setVertices(&(points[i]));
}
// scale model matrix
glm::vec3 scaleVect = glm::vec3(2.0 / static_cast<GLfloat>(mSlices.x - 1), 2.0 / static_cast<GLfloat>(mSlices.y - 1), 2.0 / static_cast<GLfloat>(mSlices.z - 1));
glm::mat4 tra = glm::translate(glm::mat4(1.0), glm::vec3(-1.0, -1.0, -1.0));
glm::mat4 sca = glm::scale(tra, scaleVect);
mModel = sca;
}
void MarchingCubes::initShader() {
mMCShader = new Shader();
mMCShader->compileShader(GL_VERTEX_SHADER, "../../shader/simple.vert");
mMCShader->compileShader(GL_GEOMETRY_SHADER, "../../shader/marchingcubes.geom");
mMCShader->compileShader(GL_FRAGMENT_SHADER, "../../shader/phong.frag");
mMCShader->linkProgram();
}
void MarchingCubes::initBuffers() {
mTexEdgeConnection = new Texture<GLint>(Texture<GLint>::T_BUFF, GL_R32I);
mTexEdgeConnection->setTextureUnit(1);
mTexEdgeConnection->setImageData(mEdgeConnection, 256, 16, 1, GL_R32I);
}
void MarchingCubes::initTables() {
mEdgeConnection = new GLint[256 * 16]
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1 ,
3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1 ,
3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1 ,
3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1 ,
9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1 ,
1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1 ,
9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1 ,
2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1 ,
8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1 ,
9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1 ,
4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1 ,
3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1 ,
1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1 ,
4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1 ,
4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1 ,
9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1 ,
1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1 ,
5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1 ,
2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1 ,
9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1 ,
0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1 ,
2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1 ,
10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1 ,
4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1 ,
5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1 ,
5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1 ,
9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1 ,
0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1 ,
1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1 ,
10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1 ,
8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1 ,
2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1 ,
7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1 ,
9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1 ,
2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1 ,
11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1 ,
9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1 ,
5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1 ,
11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1 ,
11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1 ,
1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1 ,
9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1 ,
5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1 ,
2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1 ,
0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1 ,
5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1 ,
6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1 ,
0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1 ,
3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1 ,
6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1 ,
5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1 ,
1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1 ,
10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1 ,
6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1 ,
1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1 ,
8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1 ,
7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1 ,
3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1 ,
5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1 ,
0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1 ,
9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1 ,
8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1 ,
5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1 ,
0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1 ,
6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1 ,
10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1 ,
10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1 ,
8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1 ,
1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1 ,
3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1 ,
0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1 ,
10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1 ,
0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1 ,
3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1 ,
6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1 ,
9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1 ,
8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1 ,
3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1 ,
6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1 ,
0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1 ,
10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1 ,
10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1 ,
1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1 ,
2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1 ,
7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1 ,
7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1 ,
2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1 ,
1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1 ,
11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1 ,
8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1 ,
0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1 ,
7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1 ,
10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1 ,
2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1 ,
6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1 ,
7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1 ,
2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1 ,
1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1 ,
10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1 ,
10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1 ,
0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1 ,
7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1 ,
6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1 ,
8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1 ,
9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1 ,
6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1 ,
1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1 ,
4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1 ,
10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1 ,
8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1 ,
0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1 ,
1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1 ,
8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1 ,
10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1 ,
4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1 ,
10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1 ,
5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1 ,
11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1 ,
9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1 ,
6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1 ,
7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1 ,
3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1 ,
7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1 ,
9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1 ,
3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1 ,
6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1 ,
9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1 ,
1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1 ,
4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1 ,
7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1 ,
6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1 ,
3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1 ,
0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1 ,
6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1 ,
1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1 ,
0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1 ,
11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1 ,
6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1 ,
5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1 ,
9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1 ,
1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1 ,
1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1 ,
10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1 ,
0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1 ,
5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1 ,
10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1 ,
11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1 ,
0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1 ,
9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1 ,
7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1 ,
2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1 ,
8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1 ,
9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1 ,
9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1 ,
1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1 ,
9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1 ,
9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1 ,
5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1 ,
0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1 ,
10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1 ,
2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1 ,
0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1 ,
0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1 ,
9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1 ,
5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1 ,
3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1 ,
5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1 ,
8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1 ,
0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1 ,
9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1 ,
0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1 ,
1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1 ,
3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1 ,
4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1 ,
9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1 ,
11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1 ,
11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1 ,
2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1 ,
9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1 ,
3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1 ,
1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1 ,
4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1 ,
4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1 ,
0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1 ,
3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1 ,
3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1 ,
0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1 ,
9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1 ,
1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
mEdgeFlags = new GLint[256]
{
0x000, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00,
0x190, 0x099, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90,
0x230, 0x339, 0x033, 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30,
0x3a0, 0x2a9, 0x1a3, 0x0aa, 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0,
0x460, 0x569, 0x663, 0x76a, 0x066, 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60,
0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0x0ff, 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0,
0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x055, 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950,
0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0x0cc, 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0,
0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0x0cc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0,
0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x055, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650,
0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0x0ff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0,
0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x066, 0x76a, 0x663, 0x569, 0x460,
0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0x0aa, 0x1a3, 0x2a9, 0x3a0,
0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x033, 0x339, 0x230,
0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x099, 0x190,
0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x000
};
}
| 47.940397 | 162 | 0.411014 | menonon |
076ed479fa395053a6a704771c210791dc27431c | 1,316 | cpp | C++ | STL/lambda/lambda_2.cpp | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | 5 | 2019-09-17T09:12:15.000Z | 2021-05-29T10:54:39.000Z | STL/lambda/lambda_2.cpp | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | null | null | null | STL/lambda/lambda_2.cpp | liangjisheng/C-Cpp | 8b33ba1f43580a7bdded8bb4ce3d92983ccedb81 | [
"MIT"
] | 2 | 2021-07-26T06:36:12.000Z | 2022-01-23T15:20:30.000Z | #include <iostream>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;
class SumAndProd
{
public:
SumAndProd() : mSum(0), mProd(1) {}
void operator()(int elem);
int getSum() const { return mSum; }
int getProduct() const { return mProd; }
private:
int mSum;
int mProd;
};
void SumAndProd::operator()(int elem)
{
mSum += elem;
mProd *= elem;
}
int main()
{
map<int, int> myMap = { {4,40}, {5,50}, {6,60} };
for_each(myMap.cbegin(), myMap.cend(),
[](const pair<int, int>& p) { cout << p.first << "->" << p.second << endl;});
vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
int sum = 0;
int prod = 1;
for_each(vec.cbegin(), vec.cend(),
[&sum, &prod](int i){
sum += i;
prod *= i;
});
cout << "The sum is :" << sum << endl;
cout << "The product is :" << prod << endl;
// 求连乘与求和除了可以用lambda表达式,也可以用仿函数
SumAndProd func;
// 仿函数移入for_each(),最终会移出for_each(),
// 为了获得正确的行为,必须捕捉返回值
func = for_each(vec.cbegin(), vec.cend(), func);
cout << "The sum is :" << func.getSum() << endl;
cout << "The product is :" << func.getProduct() << endl;
return 0;
}
| 21.225806 | 90 | 0.538754 | liangjisheng |
07715ce23d6844d2351a29ecad1fa9a664ef5748 | 162 | cpp | C++ | CH1/Bookexamples/1.5.2.cpp | Alfredo-Palace/C | cb1ef3386e9d7ab817ee4906d9db05ea1afd551f | [
"Apache-2.0"
] | null | null | null | CH1/Bookexamples/1.5.2.cpp | Alfredo-Palace/C | cb1ef3386e9d7ab817ee4906d9db05ea1afd551f | [
"Apache-2.0"
] | null | null | null | CH1/Bookexamples/1.5.2.cpp | Alfredo-Palace/C | cb1ef3386e9d7ab817ee4906d9db05ea1afd551f | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
int main() {
long nc = 0;
while (getchar() != EOF) {
++nc;
}
printf("A total of %ld characters.\n", nc);
return 1;
}
| 14.727273 | 47 | 0.493827 | Alfredo-Palace |
0771e586625388f91caada87d1a7724679edc209 | 777 | cpp | C++ | source/src/python/python.cpp | danstowell/signalflow | 66cbe1d7b573312dc3a7435a154fbb10e47a24c5 | [
"MIT"
] | 61 | 2020-10-12T11:46:09.000Z | 2022-02-07T04:26:05.000Z | source/src/python/python.cpp | danstowell/signalflow | 66cbe1d7b573312dc3a7435a154fbb10e47a24c5 | [
"MIT"
] | 26 | 2020-10-07T20:25:26.000Z | 2022-03-25T11:40:57.000Z | source/src/python/python.cpp | danstowell/signalflow | 66cbe1d7b573312dc3a7435a154fbb10e47a24c5 | [
"MIT"
] | 6 | 2021-02-27T19:50:25.000Z | 2021-11-09T11:02:20.000Z | #include "signalflow/python/python.h"
void init_python_constants(py::module &m);
void init_python_node(py::module &m);
void init_python_nodes(py::module &m);
void init_python_buffer(py::module &m);
void init_python_config(py::module &m);
void init_python_graph(py::module &m);
void init_python_patch(py::module &m);
void init_python_exceptions(py::module &m);
void init_python_util(py::module &m);
PYBIND11_MODULE(signalflow, m)
{
m.doc() = R"pbdoc(
SignalFlow
----------
A framework for audio DSP.
)pbdoc";
init_python_constants(m);
init_python_node(m);
init_python_nodes(m);
init_python_config(m);
init_python_graph(m);
init_python_buffer(m);
init_python_patch(m);
init_python_exceptions(m);
init_python_util(m);
}
| 24.28125 | 43 | 0.710425 | danstowell |
0773f46d11490956c1372859aead18e87ec8637a | 361 | cpp | C++ | SimpleInterest/Main.cpp | sounishnath003/CPP-for-beginner | d4755ab4ae098d63c9a0666d8eb4d152106d4a20 | [
"MIT"
] | 4 | 2020-05-14T04:41:04.000Z | 2021-06-13T06:42:03.000Z | SimpleInterest/Main.cpp | sounishnath003/CPP-for-beginner | d4755ab4ae098d63c9a0666d8eb4d152106d4a20 | [
"MIT"
] | null | null | null | SimpleInterest/Main.cpp | sounishnath003/CPP-for-beginner | d4755ab4ae098d63c9a0666d8eb4d152106d4a20 | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std ;
class Main
{
private:
int rate = 8.9 ;
public:
int interest(int ammount, double time) {
return (ammount * rate * time)/100 ;
}
};
int main(int argc, char const *argv[])
{
Main obj ;
int r = obj.interest(20000, 2) ;
cout << r << endl ;
return 0;
}
| 15.695652 | 45 | 0.523546 | sounishnath003 |
0773fbe6a06ce6f1ce2d6d823b649f2f1f9f3972 | 1,932 | cc | C++ | src/base/flat_set_benchmark.cc | nicomazz/perfetto | fb875c61cf00ded88a3f46cb562ab943129cb7af | [
"Apache-2.0"
] | 2 | 2020-03-09T04:39:32.000Z | 2020-03-09T09:12:02.000Z | src/base/flat_set_benchmark.cc | nicomazz/perfetto | fb875c61cf00ded88a3f46cb562ab943129cb7af | [
"Apache-2.0"
] | 6 | 2021-03-01T21:03:47.000Z | 2022-02-26T01:51:15.000Z | src/base/flat_set_benchmark.cc | nicomazz/perfetto | fb875c61cf00ded88a3f46cb562ab943129cb7af | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2019 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <random>
#include <set>
#include <unordered_set>
#include <benchmark/benchmark.h>
#include "perfetto/base/flat_set.h"
namespace {
std::vector<int> GetRandData(int num_pids) {
std::vector<int> rnd_data;
std::minstd_rand0 rng(0);
static constexpr int kDistinctValues = 100;
for (int i = 0; i < num_pids; i++)
rnd_data.push_back(static_cast<int>(rng()) % kDistinctValues);
return rnd_data;
}
bool IsBenchmarkFunctionalOnly() {
return getenv("BENCHMARK_FUNCTIONAL_TEST_ONLY") != nullptr;
}
void BenchmarkArgs(benchmark::internal::Benchmark* b) {
if (IsBenchmarkFunctionalOnly()) {
b->Arg(64);
} else {
b->RangeMultiplier(2)->Range(64, 4096);
}
}
} // namespace
template <typename SetType>
static void BM_SetInsert(benchmark::State& state) {
std::vector<int> rnd_data = GetRandData(state.range(0));
for (auto _ : state) {
SetType iset;
for (const int val : rnd_data)
iset.insert(val);
benchmark::DoNotOptimize(iset);
benchmark::DoNotOptimize(iset.begin());
benchmark::ClobberMemory();
}
}
using perfetto::base::FlatSet;
BENCHMARK_TEMPLATE(BM_SetInsert, FlatSet<int>)->Apply(BenchmarkArgs);
BENCHMARK_TEMPLATE(BM_SetInsert, std::set<int>)->Apply(BenchmarkArgs);
BENCHMARK_TEMPLATE(BM_SetInsert, std::unordered_set<int>)->Apply(BenchmarkArgs);
| 29.723077 | 80 | 0.72412 | nicomazz |
07752c7ae25b64365e655df3ca9d4493556e85ad | 1,540 | cpp | C++ | Practice/2018/2018.12.16/UOJ188.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | 4 | 2017-10-31T14:25:18.000Z | 2018-06-10T16:10:17.000Z | Practice/2018/2018.12.16/UOJ188.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | Practice/2018/2018.12.16/UOJ188.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
const int maxN=705000;
const int inf=2147483647;
ll n,srt;
bool notprime[maxN];
int pcnt,P[maxN];
ll num,Num[maxN+maxN],Id[maxN+maxN];
ll G[maxN+maxN];
void Init();
ll Calc(ll x);
int GetId(ll x);
pair<ll,ll> S(ll x,int p);
int main(){
Init();ll L,R;scanf("%lld%lld",&L,&R);
printf("%lld\n",Calc(R)-Calc(L-1));
return 0;
}
void Init(){
notprime[1]=1;
for (int i=2;i<maxN;i++){
if (notprime[i]==0) P[++pcnt]=i;
for (int j=1;(j<=pcnt)&&(1ll*i*P[j]<maxN);j++){
notprime[i*P[j]]=1;if (i%P[j]==0) break;
}
}
return;
}
ll Calc(ll x){
num=0;n=x;srt=sqrt(x);
for (ll i=1,j;i<=n;i=j+1){
j=x/i;Num[++num]=j;G[num]=j-1;
if (j<=srt) Id[j]=num;
else Id[i+maxN]=num;j=n/j;
}
for (int j=1;j<=pcnt;j++)
for (int i=1;(i<=num)&&(1ll*P[j]*P[j]<=Num[i]);i++)
G[i]=G[i]-G[GetId(Num[i]/P[j])]+j-1;
//for (int i=1;i<=num;i++) cout<<Num[i]<<" ";cout<<endl;
//for (int i=1;i<=num;i++) cout<<G[i]<<" ";cout<<endl;
return S(x,1).second;
}
int GetId(ll x){
if (x<=srt) return Id[x];
return Id[n/x+maxN];
}
pair<ll,ll> S(ll x,int p){
if ((x<=1)||(x<P[p])) return make_pair(0,0);
ll r1=G[GetId(x)]-(p-1),r2=0;
for (int i=p;(i<=pcnt)&&(1ll*P[i]*P[i]<=x);i++){
ll mul=P[i];
for (int j=1;1ll*mul*P[i]<=x;j++,mul=mul*P[i]){
pair<ll,ll> R=S(x/mul,i+1);
r2=r2+R.first*P[i]+R.second+P[i];
}
}
return make_pair(r1,r2);
}
| 20.533333 | 57 | 0.569481 | SYCstudio |
077874189b8e5a531724039adce131445eb3ca81 | 840 | cpp | C++ | Chapter08/tinylang2/lib/Basic/TokenKinds.cpp | PacktPublishing/Learn-LLVM-12 | e53e4ce5ecabeecc42a61acad9b707e3424dc472 | [
"MIT"
] | 149 | 2021-04-24T05:39:42.000Z | 2022-03-31T02:02:39.000Z | Chapter08/tinylang2/lib/Basic/TokenKinds.cpp | PacktPublishing/Learn-LLVM-12 | e53e4ce5ecabeecc42a61acad9b707e3424dc472 | [
"MIT"
] | 7 | 2021-06-03T00:44:13.000Z | 2022-01-06T23:05:50.000Z | Chapter08/tinylang2/lib/Basic/TokenKinds.cpp | PacktPublishing/Learn-LLVM-9 | e53e4ce5ecabeecc42a61acad9b707e3424dc472 | [
"MIT"
] | 42 | 2021-05-18T11:41:05.000Z | 2022-03-29T02:11:53.000Z | #include "tinylang/Basic/TokenKinds.h"
#include "llvm/Support/ErrorHandling.h"
using namespace tinylang;
static const char * const TokNames[] = {
#define TOK(ID) #ID,
#define KEYWORD(ID, FLAG) #ID,
#include "tinylang/Basic/TokenKinds.def"
nullptr
};
const char *tok::getTokenName(TokenKind Kind) {
if (Kind < tok::NUM_TOKENS)
return TokNames[Kind];
llvm_unreachable("unknown TokenKind");
return nullptr;
}
const char *tok::getPunctuatorSpelling(TokenKind Kind) {
switch (Kind) {
#define PUNCTUATOR(ID, SP) case ID: return SP;
#include "tinylang/Basic/TokenKinds.def"
default: break;
}
return nullptr;
}
const char *tok::getKeywordSpelling(TokenKind Kind) {
switch (Kind) {
#define KEYWORD(ID, FLAG) case kw_ ## ID: return #ID;
#include "tinylang/Basic/TokenKinds.def"
default: break;
}
return nullptr;
} | 23.333333 | 56 | 0.715476 | PacktPublishing |
077cb609be464433ca006bf73693954ad7ccfe71 | 8,746 | cpp | C++ | testeSHP/GIS.Map.cpp | darioajr/shapeview | 00f46e4ac8a53dd4b3d58b57487b8469427b97cb | [
"MIT"
] | 2 | 2020-05-05T15:12:48.000Z | 2021-05-13T05:00:44.000Z | testeSHP/GIS.Map.cpp | darioajr/shapeview | 00f46e4ac8a53dd4b3d58b57487b8469427b97cb | [
"MIT"
] | null | null | null | testeSHP/GIS.Map.cpp | darioajr/shapeview | 00f46e4ac8a53dd4b3d58b57487b8469427b97cb | [
"MIT"
] | 1 | 2017-09-21T05:07:10.000Z | 2017-09-21T05:07:10.000Z | #include "stdafx.h"
#include "GIS.Map.h"
#include "GIS.IMapLayer.h"
using MapGIS::IMapLayer;
using MapGIS::Map;
//Geo
#include "GIS.MapMetrics.h"
using MapGIS::MapMetrics;
//DataSources
#include "GIS.SHPReader.h"
#include "GIS.DXFReader.h"
using MapGIS::SHPReader;
using MapGIS::DXFReader;
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#define FILETYPE_SHP _T(".SHP")
#define FILETYPE_DXF _T(".DXF")
Map::Map() : _mapMetrics(NULL)
{
_mapMetrics = new MapMetrics();
m_bModified = FALSE;
m_dwBrushColor = RGB(128,128,128);
m_iPenWidth = 1;
m_phBrush = new CBrush(m_dwBrushColor);
m_phBrushActive = new CBrush(RGB(255,128,64));
m_phPen = new CPen(PS_SOLID,m_iPenWidth,RGB(0,0,0));
m_phPenSelected = new CPen(PS_SOLID,m_iPenWidth*2,RGB(255,0,0));
m_phColorsACI = NULL;
m_phColorsACI = ::new CPen[256];
for (int i=0;i<256;i++)
m_phColorsACI[i].CreatePen(PS_SOLID,m_iPenWidth,ACI[i]);
m_iZoomObjectScale = 200;
}
Map::~Map()
{
while(List.GetCount() > 0)
delete List.RemoveTail();
for (int i=0;i<256;i++)
::DeleteObject(m_phColorsACI[i]);
::delete[] m_phColorsACI;
delete _mapMetrics;
delete m_phBrush;
delete m_phBrushActive;
delete m_phPen;
delete m_phPenSelected;
}
int Map::Add( CString filename,CRect rect )
{
filename.MakeUpper();
filename.TrimRight();
_mapMetrics->_canvas = rect;
if(filename.Find(FILETYPE_SHP) != -1)
{
IMapLayer *ml = NULL;
ml = new SHPReader( filename, _mapMetrics, m_phBrush, m_phBrushActive, m_phPen, m_phPenSelected);
ml->m_LayerType = Vector;
ml->m_LayerSubType = Shapefile;
List.AddTail(ml);
}
else if(filename.Find(FILETYPE_DXF) != -1)
{
IMapLayer *ml = NULL;
ml = new DXFReader( filename, _mapMetrics, m_phColorsACI);
ml->m_LayerType = Vector;
ml->m_LayerSubType = Shapefile;
List.AddTail(ml);
}
else
{
AfxMessageBox(_T("Arquivo nao suportado!"));
return 0;
}
CalculateExtents();
SetModifiedFlag();
return 0;
}
void Map::Insert(int index, IMapLayer *ml )
{
POSITION POS = List.FindIndex(index);
if(POS)
{
List.InsertAfter(POS, ml);
CalculateExtents();
}
}
int Map::GetCount()
{
return List.GetCount();
}
IMapLayer* Map::GetLayer(int index)
{
POSITION POS = List.FindIndex(index);
if(POS)
return List.GetAt(POS);
else
return NULL;
}
void Map::Remove( int index )
{
POSITION POS = List.FindIndex(index);
if(POS)
{
IMapLayer *ml;
ml = List.GetAt(POS);
List.RemoveAt(POS);
delete ml;
CalculateExtents();
}
}
void Map::SetLayerActive(DWORD index)
{
POSITION POS = List.GetHeadPosition();
while (POS)
{
IMapLayer *layer = List.GetNext(POS);
layer->m_bActive = FALSE;
}
IMapLayer *layer = GetLayer(index);
if(layer)
layer->m_bActive = TRUE;
}
void Map::CalculateExtents()
{
if ( List.GetCount() == 0 )
{
_mapMetrics->Reset();
_mapMetrics->UpdateMetrics();
}
else
{
_mapMetrics->_extents.setXmin(MAXDOUBLE);
_mapMetrics->_extents.setYmin(MAXDOUBLE);
_mapMetrics->_extents.setXmax(MINDOUBLE);
_mapMetrics->_extents.setYmax(MINDOUBLE);
POSITION POS = List.GetHeadPosition();
while (POS)
{
IMapLayer *layer = List.GetNext(POS);
if ( layer->_extents->Xmin() < _mapMetrics->_extents.Xmin() )
_mapMetrics->_extents.setXmin(layer->_extents->Xmin());
if ( layer->_extents->Ymin() < _mapMetrics->_extents.Ymin() )
_mapMetrics->_extents.setYmin(layer->_extents->Ymin());
if ( layer->_extents->Xmax() > _mapMetrics->_extents.Xmax() )
_mapMetrics->_extents.setXmax(layer->_extents->Xmax());
if ( layer->_extents->Ymax() > _mapMetrics->_extents.Ymax() )
_mapMetrics->_extents.setYmax(layer->_extents->Ymax());
}
}
if ( _mapMetrics->_viewport.DeltaX() == 0 &&
_mapMetrics->_viewport.DeltaY() == 0 )
{
_mapMetrics->_extents.FixGeoAspect();
_mapMetrics->_viewport.setXmin(_mapMetrics->_extents.Xmin());
_mapMetrics->_viewport.setYmin(_mapMetrics->_extents.Ymin());
_mapMetrics->_viewport.setXmax(_mapMetrics->_extents.Xmax());
_mapMetrics->_viewport.setYmax(_mapMetrics->_extents.Ymax());
}
_mapMetrics->_extents.FixGeoAspect();
}
void Map::Center( int x, int y )
{
double dx = (double) x;
double dy = (double) y;
_mapMetrics->Pixel2World( dx, dy );
Center( dx, dy );
SetModifiedFlag();
}
void Map::Center( double x, double y )
{
double halfdeltax;
double halfdeltay;
halfdeltax = _mapMetrics->_viewport.DeltaX() / 2;
halfdeltay = _mapMetrics->_viewport.DeltaY() / 2;
_mapMetrics->_viewport.setXmin(x - halfdeltax);
_mapMetrics->_viewport.setXmax(x + halfdeltax);
_mapMetrics->_viewport.setYmin(y - halfdeltay);
_mapMetrics->_viewport.setYmax(y + halfdeltay);
SetModifiedFlag();
}
void Map::SetModifiedFlag( BOOL bModified )
{
m_bModified = bModified;
}
BOOL Map::IsModified( )
{
return m_bModified;
}
void Map::Draw(CWnd *pWnd, CDC *pDC)
{
ASSERT(pDC);
_mapMetrics->UpdateMetrics();
POSITION POS = List.GetHeadPosition();
while(POS)
{
IMapLayer *layer = List.GetAt(POS);
switch(layer->m_LayerType)
{
case Vector:
{
//uso futuro
switch(layer->m_LayerSubType)
{
case Shapefile:
layer->Draw(pWnd, pDC);
break;
case DXF:
layer->Draw(pWnd, pDC);
break;
default:
break;
}
}
break;
case Raster:
//uso futuro
break;
default:
break;
}
List.GetNext(POS);
}
}
RectangleD* Map::getExtents()
{
return &_mapMetrics->_extents;
}
void Map::ZoomArea( int sx, int sy, int ex, int ey )
{
double dsx = (double) sx;
double dsy = (double) sy;
double dex = (double) ex;
double dey = (double) ey;
if ( sx != ex || sy != ey )
{
_mapMetrics->Pixel2World( dsx, dsy );
_mapMetrics->Pixel2World( dex, dey );
_mapMetrics->_viewport.setXmin(dsx);
_mapMetrics->_viewport.setXmax(dex);
_mapMetrics->_viewport.setYmin(dey);
_mapMetrics->_viewport.setYmax(dsy);
_mapMetrics->_viewport.FixGeoAspect();
}
}
void Map::ZoomArea( RectangleD &rect )
{
_mapMetrics->_viewport = rect;
}
void Map::ZoomExtents()
{
_mapMetrics->_viewport.setXmin(_mapMetrics->_extents.Xmin());
_mapMetrics->_viewport.setYmin(_mapMetrics->_extents.Ymin());
_mapMetrics->_viewport.setXmax(_mapMetrics->_extents.Xmax());
_mapMetrics->_viewport.setYmax(_mapMetrics->_extents.Ymax());
}
void Map::ZoomIn()
{
double quarterdeltax;
double quarterdeltay;
quarterdeltax = _mapMetrics->_viewport.DeltaX() / 4;
quarterdeltay = _mapMetrics->_viewport.DeltaY() / 4;
_mapMetrics->_viewport.setXmin(_mapMetrics->_viewport.Xmin() + quarterdeltax);
_mapMetrics->_viewport.setXmax(_mapMetrics->_viewport.Xmax() - quarterdeltax);
_mapMetrics->_viewport.setYmin(_mapMetrics->_viewport.Ymin() + quarterdeltay);
_mapMetrics->_viewport.setYmax(_mapMetrics->_viewport.Ymax() - quarterdeltay);
}
void Map::ZoomIn( int x, int y )
{
Center( x, y );
ZoomIn();
}
void Map::ZoomIn( double x, double y )
{
Center( x, y );
ZoomIn();
}
void Map::ZoomOut()
{
double thirddeltax;
double thirddeltay;
thirddeltax = _mapMetrics->_viewport.DeltaX() / 3;
thirddeltay = _mapMetrics->_viewport.DeltaY() / 3;
_mapMetrics->_viewport.setXmin(_mapMetrics->_viewport.Xmin() - thirddeltax);
_mapMetrics->_viewport.setXmax(_mapMetrics->_viewport.Xmax() + thirddeltax);
_mapMetrics->_viewport.setYmin(_mapMetrics->_viewport.Ymin() - thirddeltay);
_mapMetrics->_viewport.setYmax(_mapMetrics->_viewport.Ymax() + thirddeltay);
}
void Map::ZoomOut( int x, int y )
{
Center( x, y );
ZoomOut();
}
void Map::ZoomOut( double x, double y )
{
Center( x, y );
ZoomOut();
}
CString Map::GetLayerNames()
{
CString sNames;
POSITION POS = List.GetHeadPosition();
while(POS)
{
IMapLayer *layer = List.GetNext(POS);
sNames += layer->LayerName();
sNames += _T("|");
}
return sNames;
}
MapMetrics* Map::getMetrics()
{
return _mapMetrics;
}
void Map::setMetrics(MapMetrics *value)
{
_mapMetrics = value;
}
void Map::ZoomObject(DWORD Handle)
{
POSITION POS = List.GetHeadPosition();
while(POS)
{
RectangleD rc;
IMapLayer *layer = List.GetNext(POS);
layer->SelectObject(Handle);
if(layer->GetRectObject(Handle,&rc))
{
rc.setXmin(rc.Xmin()-m_iZoomObjectScale);
rc.setXmax(rc.Xmax()+m_iZoomObjectScale);
rc.setYmin(rc.Ymin()-m_iZoomObjectScale);
rc.setYmax(rc.Ymax()+m_iZoomObjectScale);
ZoomArea(rc);
}
}
}
void Map::SelectObject(DWORD Handle)
{
POSITION POS = List.GetHeadPosition();
while(POS)
{
IMapLayer *layer = List.GetNext(POS);
layer->SelectObject(Handle);
}
}
void Map::ClearSelected()
{
POSITION POS = List.GetHeadPosition();
while(POS)
{
IMapLayer *layer = List.GetNext(POS);
layer->ClearSelected();
}
}
void Map::SetZoomObjectScale(UINT Scale)
{
m_iZoomObjectScale = Scale;
} | 19.698198 | 99 | 0.69003 | darioajr |
077da983004cfbcd76a472034d20cbef096cac5f | 1,915 | cpp | C++ | src/cpp/lib/QtGui/QCursor/qcursor_wrap.cpp | TheRakeshPurohit/nodegui | 9fcc5e99d30ff0dc208f045abeeab50e59a73f22 | [
"MIT"
] | 7,857 | 2019-08-12T17:06:12.000Z | 2022-03-31T09:40:05.000Z | src/cpp/lib/QtGui/QCursor/qcursor_wrap.cpp | TheRakeshPurohit/nodegui | 9fcc5e99d30ff0dc208f045abeeab50e59a73f22 | [
"MIT"
] | 584 | 2019-08-11T21:39:18.000Z | 2022-03-25T23:37:10.000Z | src/cpp/lib/QtGui/QCursor/qcursor_wrap.cpp | master-atul/nodegui | 123524d1265ec9c9737596cfb475308c56a06750 | [
"MIT"
] | 310 | 2019-08-16T01:40:14.000Z | 2022-03-29T09:45:31.000Z | #include "QtGui/QCursor/qcursor_wrap.h"
#include "Extras/Utils/nutils.h"
#include "QtGui/QPixmap/qpixmap_wrap.h"
Napi::FunctionReference QCursorWrap::constructor;
Napi::Object QCursorWrap::init(Napi::Env env, Napi::Object exports) {
Napi::HandleScope scope(env);
char CLASSNAME[] = "QCursor";
Napi::Function func =
DefineClass(env, CLASSNAME,
{InstanceMethod("pos", &QCursorWrap::pos),
InstanceMethod("setPos", &QCursorWrap::setPos),
COMPONENT_WRAPPED_METHODS_EXPORT_DEFINE(QCursorWrap)});
constructor = Napi::Persistent(func);
exports.Set(CLASSNAME, func);
return exports;
}
QCursorWrap::QCursorWrap(const Napi::CallbackInfo& info)
: Napi::ObjectWrap<QCursorWrap>(info) {
Napi::Env env = info.Env();
if (info.Length() == 1) {
Napi::Number cursor = info[0].As<Napi::Number>();
this->instance = std::make_unique<QCursor>(
static_cast<Qt::CursorShape>(cursor.Int32Value()));
} else if (info.Length() == 0) {
this->instance = std::make_unique<QCursor>();
} else {
Napi::TypeError::New(env, "Wrong number of arguments")
.ThrowAsJavaScriptException();
}
this->rawData = extrautils::configureComponent(this->getInternalInstance());
}
QCursorWrap::~QCursorWrap() { this->instance.reset(); }
QCursor* QCursorWrap::getInternalInstance() { return this->instance.get(); }
Napi::Value QCursorWrap::pos(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
QPoint pos = this->instance->pos();
Napi::Object posObj = Napi::Object::New(env);
posObj.Set("x", pos.x());
posObj.Set("y", pos.y());
return posObj;
}
Napi::Value QCursorWrap::setPos(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::Number x = info[0].As<Napi::Number>();
Napi::Number y = info[1].As<Napi::Number>();
this->instance->setPos(x.Int32Value(), y.Int32Value());
return env.Null();
} | 34.196429 | 78 | 0.667885 | TheRakeshPurohit |
077ed1102aba2c6e416f4a57e7acfdba0bdaa693 | 32,013 | cc | C++ | ge/graph/optimize/mem_rw_conflict_optimize.cc | Ascend/graphengine | 45d6a09b12a07eb3c854452f83dab993eba79716 | [
"Apache-2.0"
] | null | null | null | ge/graph/optimize/mem_rw_conflict_optimize.cc | Ascend/graphengine | 45d6a09b12a07eb3c854452f83dab993eba79716 | [
"Apache-2.0"
] | null | null | null | ge/graph/optimize/mem_rw_conflict_optimize.cc | Ascend/graphengine | 45d6a09b12a07eb3c854452f83dab993eba79716 | [
"Apache-2.0"
] | null | null | null | /**
* 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 <string>
#include <vector>
#include "common/ge/ge_util.h"
#include "graph/common/omg_util.h"
#include "graph/debug/ge_attr_define.h"
#include "graph/optimize/graph_optimize.h"
#include "graph/utils/graph_utils.h"
#include "graph/utils/node_utils.h"
namespace {
using namespace ge;
const int kIdentityAnchorIndex = 0;
const size_t kSerialStringVecSize = 4;
const int kCaseReadOnly = 0;
const int kCaseScopeWriteable = 2;
const int kCaseWriteable = 3;
const int kCaseInvalidRWType = 5;
// rw type of input.
enum class InputRWType {
kReadOnly, // Normal op input only read
kWriteable, // Op like Assign/ApplyMomentum
kScopeWriteable, // Op like hcom_allreduce, it will modify input ,but not expect take effect on pre ouput
kInvalidRWType
};
// rw type of output
enum class OutputRWType {
kReadOnly, // 1.const output 2.not ref output but has several peer output
kSoftRead, // not ref output but only has one output node
kWriteable, // ref output. Like Assign/ApplyMomentum
kInvalidRWType
};
// input and output rw_type of one node. key is anchor_idx, value is rw_type
struct NodeInputOutputRWType {
map<uint32_t, InputRWType> input_rw_type_map;
map<uint32_t, OutputRWType> output_rw_type_map;
};
// input and output rw_type of node in current graph
thread_local map<string, NodeInputOutputRWType> node_rwtype_map_;
///
/// @brief Convert input rw_type enum to string. For log print.
/// @param rw_type
/// @return rw_type_name
///
static std::string InputRWTypeToSerialString(InputRWType rw_type) {
const static char *names[kSerialStringVecSize] = {"ReadOnly", "Writeable", "ScopeWriteable", "InvalidRWType"};
return names[static_cast<int>(rw_type)];
}
///
/// @brief Convert output rw_type enum to string. For log print.
/// @param rw_type
/// @return rw_type_name
///
static std::string OutputRWTypeToSerialString(OutputRWType rw_type) {
const static char *names[kSerialStringVecSize] = {"ReadOnly", "SoftRead", "Writeable", "InvalidRWType"};
return names[static_cast<int>(rw_type)];
}
OutputRWType GetSingleNodeOutputRWTypeByIndex(const Node &node, uint32_t index) {
auto op_desc = node.GetOpDesc();
if (op_desc == nullptr) {
return OutputRWType::kInvalidRWType;
}
if (op_desc->GetType() == VARIABLE) {
return OutputRWType::kWriteable;
}
// check if it is ref output
auto input_names = op_desc->GetAllInputName();
for (auto &input_name_2_idx : input_names) {
if (op_desc->GetOutputNameByIndex(index) == input_name_2_idx.first) {
return OutputRWType::kWriteable;
}
}
// check if it is ref switch
std::string type;
if ((node.GetType() == FRAMEWORK_OP_TYPE) && AttrUtils::GetStr(op_desc, ATTR_NAME_FRAMEWORK_ORIGINAL_TYPE, type)
&& (type == REFSWITCH)) {
return OutputRWType::kWriteable;
}
if (op_desc->GetType() == CONSTANT || op_desc->GetType() == CONSTANTOP) {
return OutputRWType::kReadOnly;
}
auto out_data_anchor = node.GetOutDataAnchor(index);
if (out_data_anchor == nullptr) {
return OutputRWType::kInvalidRWType;
}
if (out_data_anchor->GetPeerInDataNodesSize() > 1) {
return OutputRWType::kReadOnly;
} else {
return OutputRWType::kSoftRead;
}
}
///
/// @brief Get input rw_type of one node with sub graph. It will return rw_type after solve conflict scene.
/// @param rw_type_set
/// @return
///
InputRWType GetInputRwTypeInConflict(const std::set<int> &rw_type_set) {
// for input rw type calc
int total_rw_type = 0;
for (const auto rw : rw_type_set) {
total_rw_type += rw;
}
switch (total_rw_type) {
case kCaseReadOnly:
return InputRWType::kReadOnly; // all input rw type is readonly
case kCaseScopeWriteable:
return InputRWType::kScopeWriteable; // readonly 2 scope_writeable
case kCaseWriteable:
return InputRWType::kWriteable; // all input rw type is writeable or readonly 2 writeable
case kCaseInvalidRWType:
return InputRWType::kInvalidRWType; // writeable 2 scope_writeable
default:
return InputRWType::kInvalidRWType;
}
}
bool IsSubgraphInputNode(const NodePtr &node) {
if ((node == nullptr) || (node->GetOpDesc() == nullptr) || (node->GetType() != DATA) ||
(node->GetOwnerComputeGraph()->GetParentNode() == nullptr)) {
return false;
}
return true;
}
bool IsSubgraphOutputNode(const NodePtr &node) {
if ((node == nullptr) || (node->GetOpDesc() == nullptr) || (node->GetType() != NETOUTPUT) ||
(node->GetOwnerComputeGraph()->GetParentNode() == nullptr)) {
return false;
}
return true;
}
NodePtr CreateIdentityAfterSrcNode(const Node &src_node, int out_anchor_idx) {
if (src_node.GetOpDesc() == nullptr) {
return nullptr;
}
static std::atomic_long identity_num(0);
auto next_num = identity_num.fetch_add(1);
// 1. create new identity op desc
string identity_name = src_node.GetName() + "_" + IDENTITY + std::to_string(next_num);
auto identity_opdesc = MakeShared<OpDesc>(identity_name, IDENTITY);
if (identity_opdesc == nullptr) {
GELOGE(OUT_OF_MEMORY, "Failed to insert identity node, name %s", identity_name.c_str());
return nullptr;
}
auto data_desc = src_node.GetOpDesc()->GetOutputDesc(out_anchor_idx);
// 2. add input_desc & output_desc for new identity
Status ret = identity_opdesc->AddInputDesc("x", data_desc);
if (ret != SUCCESS) {
GELOGE(ret, "Add Input desc failed for new identity %s.", identity_name.c_str());
return nullptr;
}
ret = identity_opdesc->AddOutputDesc("y", data_desc);
if (ret != SUCCESS) {
GELOGE(ret, "Add Output desc failed for new Identity %s.", identity_name.c_str());
return nullptr;
}
GELOGI("Insert new Identity node %s.", identity_name.c_str());
auto graph = src_node.GetOwnerComputeGraph();
if (graph == nullptr) {
GELOGE(GRAPH_PARAM_INVALID, "Node %s owner compute graph is null.", src_node.GetName().c_str());
return nullptr;
}
return graph->AddNode(identity_opdesc);
}
OutputRWType GetOutputRWTypeByIndex(const Node &node, uint32_t index) {
auto op_desc = node.GetOpDesc();
if (op_desc == nullptr) {
return OutputRWType::kInvalidRWType;
}
if (op_desc->GetType() == WHILE) {
return OutputRWType::kSoftRead;
}
vector<string> subgraph_names = op_desc->GetSubgraphInstanceNames();
if (subgraph_names.empty()) {
// single node without sub graph
return GetSingleNodeOutputRWTypeByIndex(node, index);
} else {
// node with sub graph
auto output_node_vec = NodeUtils::GetSubgraphOutputNodes(node);
auto output_rw_type = OutputRWType::kInvalidRWType;
if (output_node_vec.size() == 1) {
// find rw type from map.
auto iter = node_rwtype_map_.find(output_node_vec.at(0)->GetName());
if (iter == node_rwtype_map_.end()) {
GELOGW("Can not find rw type of node %s from map.It could take some effect on following preprocess.",
output_node_vec.at(0)->GetName().c_str());
return OutputRWType::kInvalidRWType;
}
auto index_2_output_rw_type = iter->second.output_rw_type_map.find(index);
if (index_2_output_rw_type == iter->second.output_rw_type_map.end()) {
GELOGW("Can not find rw type of node %s from map.It could take some effect on following preprocess.",
output_node_vec.at(0)->GetName().c_str());
return OutputRWType::kInvalidRWType;
}
output_rw_type = index_2_output_rw_type->second;
} else {
output_rw_type = OutputRWType::kSoftRead;
}
// check peer input
auto out_data_anchor = node.GetOutDataAnchor(index);
if (out_data_anchor == nullptr) {
return OutputRWType::kInvalidRWType;
}
if (out_data_anchor->GetPeerInDataNodesSize() > 1) {
return OutputRWType::kReadOnly;
} else {
return output_rw_type;
}
}
}
InputRWType GetSingleNodeInputRWTypeByIndex(const Node &node, uint32_t index) {
auto op_desc = node.GetOpDesc();
if (op_desc == nullptr) {
return InputRWType::kInvalidRWType;
}
if (op_desc->GetType() == HCOMALLREDUCE || op_desc->GetType() == HCOMALLGATHER
|| op_desc->GetType() == HCOMREDUCESCATTER || op_desc->GetType() == HCOMREDUCE) {
return InputRWType::kScopeWriteable;
}
// check if it is ref input
auto output_names = op_desc->GetAllOutputName();
for (auto &output_name_2_idx : output_names) {
if (op_desc->GetInputNameByIndex(index) == output_name_2_idx.first) {
return InputRWType::kWriteable;
}
}
// check if it is ref switch
std::string type;
if ((node.GetType() == FRAMEWORK_OP_TYPE) && (AttrUtils::GetStr(op_desc, ATTR_NAME_FRAMEWORK_ORIGINAL_TYPE, type))
&& (type == REFSWITCH) && (index == 0)) {
return InputRWType::kWriteable;
}
return InputRWType::kReadOnly;
}
InputRWType GetInputRWTypeByIndex(const Node &node, uint32_t index) {
auto op_desc = node.GetOpDesc();
if (op_desc == nullptr) {
return InputRWType::kInvalidRWType;
}
if (op_desc->GetType() == WHILE) {
return InputRWType::kScopeWriteable;
}
vector<string> subgraph_names = op_desc->GetSubgraphInstanceNames();
if (subgraph_names.empty()) {
// single node without sub graph
return GetSingleNodeInputRWTypeByIndex(node, index);
} else {
// node with sub graph
std::set<int> node_rw_type_set;
auto data_node_vec = NodeUtils::GetSubgraphDataNodesByIndex(node, index);
// get all input data node in subgraph
std::set<int> anchor_rw_type_set;
for (const auto &data_node : data_node_vec) {
// Data only has 1 out data anchor. Here just take first out data anchor. And index 0 is valid.
auto out_data_anchor = data_node->GetOutDataAnchor(0);
if (out_data_anchor == nullptr) {
continue;
}
auto data_op_desc = data_node->GetOpDesc();
if (data_op_desc == nullptr) {
continue;
}
// find rw type from map.
auto iter = node_rwtype_map_.find(data_op_desc->GetName());
if (iter == node_rwtype_map_.end()) {
GELOGW("Can not find rw type of node %s from map.It could take some effect on following preprocess.",
data_op_desc->GetName().c_str());
return InputRWType::kInvalidRWType;
}
auto input_rw_type = iter->second.input_rw_type_map.find(out_data_anchor->GetIdx());
if (input_rw_type == iter->second.input_rw_type_map.end()) {
GELOGW("Can not find rw type of node %s from map.It could take some effect on following preprocess.",
data_op_desc->GetName().c_str());
return InputRWType::kInvalidRWType;
}
anchor_rw_type_set.emplace(static_cast<int>(input_rw_type->second));
}
return GetInputRwTypeInConflict(anchor_rw_type_set);
}
}
Status MarkRWTypeForSubgraph(const ComputeGraphPtr &sub_graph) {
for (const auto &node : sub_graph->GetDirectNode()) {
GE_CHECK_NOTNULL(node);
GE_CHECK_NOTNULL(node->GetOpDesc());
std::set<int> anchor_rw_type_set;
if (node->GetType() == DATA) {
// calc all input_rw_type of peer output , as input_rw_type of DATA. Index 0 is valid.
auto anchor_2_node_vec = NodeUtils::GetOutDataNodesWithAnchorByIndex(*node, 0);
for (const auto anchor_2_node_pair : anchor_2_node_vec) {
auto input_rw_type = GetInputRWTypeByIndex(*anchor_2_node_pair.second, anchor_2_node_pair.first->GetIdx());
GELOGD("Input rw type of Node %s %dth input anchor is %s", anchor_2_node_pair.second->GetName().c_str(),
anchor_2_node_pair.first->GetIdx(), InputRWTypeToSerialString(input_rw_type).c_str());
anchor_rw_type_set.emplace(static_cast<int>(input_rw_type));
}
auto anchor_rw_type = GetInputRwTypeInConflict(anchor_rw_type_set);
GELOGD("Input rw type of Node %s is %s", node->GetName().c_str(),
InputRWTypeToSerialString(anchor_rw_type).c_str());
map<uint32_t, InputRWType> input_rw_type_map{std::make_pair(0, anchor_rw_type)};
NodeInputOutputRWType data_rw_type{input_rw_type_map};
node_rwtype_map_.emplace(std::make_pair(node->GetName(), data_rw_type));
}
if (node->GetType() == NETOUTPUT) {
// calc all output_rw_type of peer input , as output_rw_type of DATA
map<uint32_t, OutputRWType> output_rw_type_map;
for (const auto &in_data_anchor : node->GetAllInDataAnchors()) {
GE_CHECK_NOTNULL(in_data_anchor);
auto pre_out_anchor = in_data_anchor->GetPeerOutAnchor();
GE_CHECK_NOTNULL(pre_out_anchor);
auto pre_node = pre_out_anchor->GetOwnerNode();
GE_CHECK_NOTNULL(pre_node);
auto pre_output_rw_type = GetOutputRWTypeByIndex(*pre_node, pre_out_anchor->GetIdx());
GELOGD("Output rw type of Node %s %dth output anchor is %s", pre_node->GetName().c_str(),
pre_out_anchor->GetIdx(), OutputRWTypeToSerialString(pre_output_rw_type).c_str());
auto parent_node = sub_graph->GetParentNode();
if (pre_output_rw_type == OutputRWType::kWriteable && parent_node->GetType() != PARTITIONEDCALL) {
// insert identity
auto identity_node = CreateIdentityAfterSrcNode(*pre_node, pre_out_anchor->GetIdx());
GE_CHECK_NOTNULL(identity_node);
auto ret = GraphUtils::InsertNodeBetweenDataAnchors(pre_out_anchor, in_data_anchor, identity_node);
if (ret != SUCCESS) {
GELOGE(ret, "Fail to insert identity");
return ret;
}
GELOGI("InsertNode %s between %s and %s successfully.", identity_node->GetName().c_str(),
pre_node->GetName().c_str(), node->GetName().c_str());
pre_output_rw_type = OutputRWType::kSoftRead;
}
output_rw_type_map.emplace(std::make_pair(in_data_anchor->GetIdx(), pre_output_rw_type));
}
NodeInputOutputRWType output_rw_type{{}, output_rw_type_map};
node_rwtype_map_.emplace(std::make_pair(node->GetName(), output_rw_type));
}
}
return SUCCESS;
}
///
/// @brief Reverse traversal all subgraph and mark rw_type for Data/Netoutput.
/// @param sub_graph_vecgs
///
Status MarkRWTypeForAllSubgraph(const vector<ComputeGraphPtr> &sub_graph_vec) {
for (auto iter = sub_graph_vec.rbegin(); iter != sub_graph_vec.rend(); ++iter) {
auto parent_node = (*iter)->GetParentNode();
if (parent_node == nullptr) {
GELOGD("Current sub graph has no parent node. Ignore it.");
continue;
}
if (parent_node->GetType() == WHILE) {
continue;
}
auto ret = MarkRWTypeForSubgraph(*iter);
if (ret != SUCCESS) {
return ret;
}
}
return SUCCESS;
}
///
/// @brief Check identity is near subgraph.
/// Eg. As output of Data node in subgraph
/// or as input of Netoutput of subgraph
/// or as input of one node with subgraph
/// or as output of one node with subgraph
/// @param node
/// @return is_near_subgraph
///
bool CheckIdentityIsNearSubgraph(const Node &node) {
for (const auto &in_node : node.GetInDataNodes()) {
auto in_node_opdesc = in_node->GetOpDesc();
if (in_node_opdesc == nullptr) {
continue;
}
// near entrance of subgraph
if (IsSubgraphInputNode(in_node)) {
return true;
}
// near subgraph
if (!in_node_opdesc->GetSubgraphInstanceNames().empty()) {
return true;
}
}
for (const auto &out_node : node.GetOutDataNodes()) {
auto out_node_opdesc = out_node->GetOpDesc();
if (out_node_opdesc == nullptr) {
continue;
}
// near output of subgraph
if (IsSubgraphOutputNode(out_node)) {
return true;
}
// near subgraph
if (!out_node_opdesc->GetSubgraphInstanceNames().empty()) {
return true;
}
}
return false;
}
enum ConflictResult { DO_NOTHING, WRONG_GRAPH, INSERT_IDENTITY };
vector<vector<ConflictResult>> output_2_input_rwtype = {{DO_NOTHING, WRONG_GRAPH, INSERT_IDENTITY},
{DO_NOTHING, WRONG_GRAPH, DO_NOTHING},
{DO_NOTHING, DO_NOTHING, INSERT_IDENTITY}};
ConflictResult GetConflictResultBetweenNode(const OutputRWType output_rw_type, const InputRWType input_rw_type) {
if (output_rw_type == OutputRWType::kInvalidRWType || input_rw_type == InputRWType::kInvalidRWType) {
return WRONG_GRAPH;
}
auto n = static_cast<int>(output_rw_type);
auto m = static_cast<int>(input_rw_type);
// no need to check index or container, because container and index is all defined.
return output_2_input_rwtype[n][m];
}
///
/// @brief Keep identity_node which near subgraph or has multi output
/// @param node
/// @return
///
Status RemoveNoUseIdentity(const NodePtr &node) {
if (node->GetInDataNodes().empty() || node->GetOutDataNodesSize() > 1) {
return SUCCESS;
}
if (node->GetOutDataNodesSize() == 1 && node->GetOutDataNodes().at(0)->GetType() == STREAMMERGE) {
return SUCCESS;
}
if (CheckIdentityIsNearSubgraph(*node)) {
return SUCCESS;
}
GE_CHECK_NOTNULL(node->GetInDataAnchor(kIdentityAnchorIndex));
auto pre_out_anchor = node->GetInDataAnchor(kIdentityAnchorIndex)->GetPeerOutAnchor();
GE_CHECK_NOTNULL(pre_out_anchor);
auto pre_node = pre_out_anchor->GetOwnerNode();
auto pre_output_rw_type = GetOutputRWTypeByIndex(*pre_node, pre_out_anchor->GetIdx());
auto anchor_2_outnode_vec = NodeUtils::GetOutDataNodesWithAnchorByIndex(*node, kIdentityAnchorIndex);
ConflictResult conflict_result = WRONG_GRAPH;
if (!anchor_2_outnode_vec.empty()) {
auto anchor_2_outnode = anchor_2_outnode_vec.at(0);
auto peer_input_rw_type = GetInputRWTypeByIndex(*anchor_2_outnode.second, anchor_2_outnode.first->GetIdx());
GELOGD("Pre Node %s %dth output rw type is %s, peer node %s %dth input rw type is %s.", pre_node->GetName().c_str(),
pre_out_anchor->GetIdx(), OutputRWTypeToSerialString(pre_output_rw_type).c_str(),
anchor_2_outnode.second->GetName().c_str(), anchor_2_outnode.first->GetIdx(),
InputRWTypeToSerialString(peer_input_rw_type).c_str());
conflict_result = GetConflictResultBetweenNode(pre_output_rw_type, peer_input_rw_type);
} else {
// identity node has no out data node, it can be removed
conflict_result = DO_NOTHING;
}
if (conflict_result != DO_NOTHING) {
return SUCCESS;
}
GELOGI("No need insert Identity. Node %s need to remove.", node->GetName().c_str());
auto ret = GraphUtils::IsolateNode(node, {0});
if (ret != SUCCESS) {
GELOGE(ret, "Fail to isolate node %s.", node->GetName().c_str());
return ret;
}
ret = GraphUtils::RemoveNodeWithoutRelink(node->GetOwnerComputeGraph(), node);
if (ret != SUCCESS) {
GELOGE(ret, "Fail to isolate node %s.", node->GetName().c_str());
return ret;
}
GELOGI("Pre node is %s and %dth output rw type is %s. Isolate and remove Identity node %s.",
pre_node->GetName().c_str(), pre_out_anchor->GetIdx(), OutputRWTypeToSerialString(pre_output_rw_type).c_str(),
node->GetName().c_str());
return SUCCESS;
}
Status SplitIdentityAlongAnchor(const OutDataAnchorPtr &out_data_anchor, const InDataAnchorPtr &peer_in_data_anchor,
const OutDataAnchorPtr &pre_out_data_anchor, NodePtr &pre_node) {
// 1.check peer in node RW type.
GE_CHECK_NOTNULL(peer_in_data_anchor);
auto peer_in_data_node = peer_in_data_anchor->GetOwnerNode();
GE_CHECK_NOTNULL(peer_in_data_node);
auto input_rw_type = GetInputRWTypeByIndex(*peer_in_data_node, peer_in_data_anchor->GetIdx());
auto ret = out_data_anchor->Unlink(peer_in_data_anchor);
auto old_identity = out_data_anchor->GetOwnerNode();
if (ret != SUCCESS) {
GELOGE(ret, "Failed to unlink from %s %dth out to %s.", old_identity->GetName().c_str(), out_data_anchor->GetIdx(),
peer_in_data_anchor->GetOwnerNode()->GetName().c_str());
return ret;
}
if (input_rw_type == InputRWType::kScopeWriteable || input_rw_type == InputRWType::kWriteable) {
auto new_identity = CreateIdentityAfterSrcNode(*pre_node, pre_out_data_anchor->GetIdx());
GE_CHECK_NOTNULL(new_identity);
if (GraphUtils::AddEdge(pre_out_data_anchor, new_identity->GetInDataAnchor(kIdentityAnchorIndex)) != SUCCESS
|| GraphUtils::AddEdge(new_identity->GetOutDataAnchor(kIdentityAnchorIndex), peer_in_data_anchor) != SUCCESS) {
GELOGE(INTERNAL_ERROR, "Failed to insert Identity between node %s and %s",
pre_out_data_anchor->GetOwnerNode()->GetName().c_str(),
peer_in_data_anchor->GetOwnerNode()->GetName().c_str());
return INTERNAL_ERROR;
}
// 2. copy in-control-edge from dst to Identity
if (GraphUtils::CopyInCtrlEdges(peer_in_data_node, new_identity) != SUCCESS) {
GELOGE(INTERNAL_ERROR, "Failed to copy in_control edges from node %s to %s", peer_in_data_node->GetName().c_str(),
new_identity->GetName().c_str());
return INTERNAL_ERROR;
}
GELOGI("Node %s intput rw type is %s. Insert Identity between %s and %s.", peer_in_data_node->GetName().c_str(),
InputRWTypeToSerialString(input_rw_type).c_str(), pre_out_data_anchor->GetOwnerNode()->GetName().c_str(),
peer_in_data_anchor->GetOwnerNode()->GetName().c_str());
} else {
// copy control edge to pre and peer node
if (GraphUtils::CopyInCtrlEdges(old_identity, peer_in_data_node) != SUCCESS
|| GraphUtils::CopyOutCtrlEdges(old_identity, pre_node) != SUCCESS) {
GELOGW("Fail to copy control edge from node %s.", old_identity->GetName().c_str());
return FAILED;
}
// link identity pre node to next node directly
if (GraphUtils::AddEdge(pre_out_data_anchor, peer_in_data_anchor) != SUCCESS) {
GELOGW("Fail to link data edge from node %s to %s.", pre_out_data_anchor->GetOwnerNode()->GetName().c_str(),
peer_in_data_anchor->GetOwnerNode()->GetName().c_str());
return FAILED;
}
GELOGI("Node %s input rw type is %s, link data edge from Identity input node %s to out node %s directly.",
peer_in_data_node->GetName().c_str(), InputRWTypeToSerialString(input_rw_type).c_str(),
pre_node->GetName().c_str(), peer_in_data_node->GetName().c_str());
}
return SUCCESS;
}
Status SplitIdentity(const NodePtr &node) {
GE_CHECK_NOTNULL(node);
auto out_data_anchor = node->GetOutDataAnchor(kIdentityAnchorIndex);
GE_CHECK_NOTNULL(out_data_anchor);
if (out_data_anchor->GetPeerInDataNodesSize() <= 1) {
return SUCCESS;
}
// get pre node and next node of identity
GE_CHECK_NOTNULL(node->GetInDataAnchor(kIdentityAnchorIndex));
auto pre_out_data_anchor = node->GetInDataAnchor(kIdentityAnchorIndex)->GetPeerOutAnchor();
GE_CHECK_NOTNULL(pre_out_data_anchor);
auto pre_node = pre_out_data_anchor->GetOwnerNode();
GE_CHECK_NOTNULL(pre_node);
for (const auto &peer_in_data_anchor : out_data_anchor->GetPeerInDataAnchors()) {
Status ret = SplitIdentityAlongAnchor(out_data_anchor, peer_in_data_anchor, pre_out_data_anchor, pre_node);
if (ret != SUCCESS) {
GELOGE(ret, "Split identity node along anchor failed.");
return ret;
}
}
// 2.isolate Identity node with no data output
if (node->GetOutDataNodesSize() == 0) {
Status ret = GraphUtils::IsolateNode(node, {});
if (ret != SUCCESS) {
GELOGE(FAILED, "IsolateAndDelete identity node %s.", node->GetName().c_str());
return FAILED;
}
ret = GraphUtils::RemoveNodeWithoutRelink(node->GetOwnerComputeGraph(), node);
if (ret != SUCCESS) {
GELOGE(FAILED, "IsolateAndDelete identity node %s.", node->GetName().c_str());
return FAILED;
}
GELOGI("IsolateAndDelete identity node %s.", node->GetName().c_str());
}
return SUCCESS;
}
Status InsertIdentityAsNeeded(const NodePtr &node) {
auto op_desc = node->GetOpDesc();
GE_CHECK_NOTNULL(op_desc);
if (node->GetOutDataNodesSize() == 0) {
return SUCCESS;
}
for (const auto &out_data_anchor : node->GetAllOutDataAnchors()) {
GE_CHECK_NOTNULL(out_data_anchor);
auto output_rw_type = GetOutputRWTypeByIndex(*node, out_data_anchor->GetIdx());
for (const auto &peer_in_data_anchor : out_data_anchor->GetPeerInDataAnchors()) {
GE_CHECK_NOTNULL(peer_in_data_anchor);
auto peer_in_node = peer_in_data_anchor->GetOwnerNode();
GE_CHECK_NOTNULL(peer_in_node);
auto input_rw_type = GetInputRWTypeByIndex(*peer_in_node, peer_in_data_anchor->GetIdx());
GELOGD("Node %s output rw type is %s, Node %s input rw type is %s", node->GetName().c_str(),
OutputRWTypeToSerialString(output_rw_type).c_str(), peer_in_node->GetName().c_str(),
InputRWTypeToSerialString(input_rw_type).c_str());
auto conflict_result = GetConflictResultBetweenNode(output_rw_type, input_rw_type);
switch (conflict_result) {
case DO_NOTHING:
case WRONG_GRAPH:
GELOGD("No need insert Identity.");
continue;
case INSERT_IDENTITY:
auto identity_node = CreateIdentityAfterSrcNode(*node, out_data_anchor->GetIdx());
if (identity_node == nullptr) {
GELOGE(FAILED, "Create identity node failed.");
return FAILED;
}
auto ret = GraphUtils::InsertNodeBetweenDataAnchors(out_data_anchor, peer_in_data_anchor, identity_node);
if (ret != GRAPH_SUCCESS) {
GELOGE(INTERNAL_ERROR, "Failed to insert reshape between node %s and %s", node->GetName().c_str(),
peer_in_node->GetName().c_str());
return INTERNAL_ERROR;
}
GELOGI("Insert Identity between %s and %s to handle memory conflict.", node->GetName().c_str(),
peer_in_node->GetName().c_str());
continue;
}
}
}
return SUCCESS;
}
Status HandleAllreduceDuplicateInput(ComputeGraphPtr &compute_graph) {
for (const auto &node : compute_graph->GetDirectNode()) {
if (node->GetType() == HCOMALLREDUCE) {
std::set<OutDataAnchorPtr> pre_out_anchor_set;
for (const auto &in_data_anchor : node->GetAllInDataAnchors()) {
auto pre_out_anchor = in_data_anchor->GetPeerOutAnchor();
GE_CHECK_NOTNULL(pre_out_anchor);
if (pre_out_anchor_set.find(pre_out_anchor) == pre_out_anchor_set.end()) {
pre_out_anchor_set.emplace(pre_out_anchor);
continue;
}
// need insert identity
auto pre_node = pre_out_anchor->GetOwnerNode();
auto identity_node = CreateIdentityAfterSrcNode(*pre_node, pre_out_anchor->GetIdx());
GE_CHECK_NOTNULL(identity_node);
auto ret = GraphUtils::InsertNodeBetweenDataAnchors(pre_out_anchor, in_data_anchor, identity_node);
GE_CHK_STATUS_RET(ret, "Fail to insert identity.");
GELOGI("InsertNode %s between %s and %s successfully.", identity_node->GetName().c_str(),
pre_node->GetName().c_str(), node->GetName().c_str());
}
}
}
return SUCCESS;
}
} // namespace
namespace ge {
Status GraphOptimize::CheckRWConflict(ComputeGraphPtr &compute_graph, bool &has_conflict) {
node_rwtype_map_.clear();
auto sub_graph_vec = compute_graph->GetAllSubgraphs();
if (sub_graph_vec.empty()) {
GELOGD("No sub graph here. Ignore memory conflict handle.");
return SUCCESS;
}
// 1.loop all subgraph, mark rw type from inside to outside
Status ret = MarkRWTypeForAllSubgraph(sub_graph_vec);
if (ret != SUCCESS) {
GELOGE(ret, "Fail to mark rw type for subgraph.");
return ret;
}
has_conflict = false;
for (const auto &node : compute_graph->GetAllNodes()) {
auto op_desc = node->GetOpDesc();
GE_CHECK_NOTNULL(op_desc);
if (node->GetOutDataNodesSize() == 0) {
return SUCCESS;
}
if (node->GetType() == WHILE) {
return SUCCESS;
}
for (const auto &out_data_anchor : node->GetAllOutDataAnchors()) {
GE_CHECK_NOTNULL(out_data_anchor);
auto output_rw_type = GetOutputRWTypeByIndex(*node, out_data_anchor->GetIdx());
for (const auto &peer_in_data_anchor : out_data_anchor->GetPeerInDataAnchors()) {
GE_CHECK_NOTNULL(peer_in_data_anchor);
auto peer_in_node = peer_in_data_anchor->GetOwnerNode();
GE_CHECK_NOTNULL(peer_in_node);
if (peer_in_node->GetType() == WHILE) {
return SUCCESS;
}
auto input_rw_type = GetInputRWTypeByIndex(*peer_in_node, peer_in_data_anchor->GetIdx());
auto conflict_result = GetConflictResultBetweenNode(output_rw_type, input_rw_type);
switch (conflict_result) {
case DO_NOTHING:
GELOGD("No rw conflict.");
continue;
case WRONG_GRAPH:
has_conflict = true;
GELOGI("Node %s output rw type is %s, next node %s input_rw_type is %s.It is wrong graph.",
node->GetName().c_str(), OutputRWTypeToSerialString(output_rw_type).c_str(),
peer_in_node->GetName().c_str(), InputRWTypeToSerialString(input_rw_type).c_str());
return SUCCESS;
case INSERT_IDENTITY:
GELOGD("There is rw conflict. It will handle later.");
continue;
}
}
}
}
return SUCCESS;
}
Status GraphOptimize::HandleMemoryRWConflict(ComputeGraphPtr &compute_graph) {
GE_DUMP(compute_graph, "BeforeHandleMemConflict");
node_rwtype_map_.clear();
auto sub_graph_vec = compute_graph->GetAllSubgraphs();
if (sub_graph_vec.empty()) {
// only root graph, to handle allreduce servral input from one output anchor
return HandleAllreduceDuplicateInput(compute_graph);
}
// 1.loop all subgraph, mark rw type from inside to outside
Status ret = MarkRWTypeForAllSubgraph(sub_graph_vec);
if (ret != SUCCESS) {
GELOGE(ret, "Fail to mark rw type for subgraph.");
return ret;
}
// 2.loop all node, including node in subgraph and handle memory rw conflict
for (auto &node : compute_graph->GetAllNodes()) {
// ignore while subgraph node
const auto parent_node = node->GetOwnerComputeGraph()->GetParentNode();
if ((parent_node != nullptr) && (kWhileOpTypes.count(parent_node->GetType()) > 0)) {
continue;
}
// ignore data / netoutput of subgraph
if (node->GetType() == DATA && AttrUtils::HasAttr(node->GetOpDesc(), ATTR_NAME_PARENT_NODE_INDEX)) {
continue;
}
if (node->GetType() == NETOUTPUT && AttrUtils::HasAttr(node->GetOpDesc(), ATTR_NAME_PARENT_NODE_INDEX)) {
continue;
}
bool identity_reserved = false;
AttrUtils::GetBool(node->GetOpDesc(), ATTR_NAME_CANNOT_BE_DELETED, identity_reserved);
if (identity_reserved) {
GELOGD("Identity [%s] need to be reserved", node->GetName().c_str());
continue;
}
if (node->GetType() == IDENTITY || node->GetType() == READVARIABLEOP) {
// split identity
ret = SplitIdentity(node);
if (ret != SUCCESS) {
GELOGE(ret, "Fail to split identity node %s.", node->GetName().c_str());
return ret;
}
// remove no use identity
ret = RemoveNoUseIdentity(node);
if (ret != SUCCESS) {
GELOGE(ret, "Fail to remove useless identity node %s.", node->GetName().c_str());
return ret;
}
}
// insert Identity
ret = InsertIdentityAsNeeded(node);
if (ret != SUCCESS) {
GELOGE(ret, "Fail to insert Identity node.");
return ret;
}
}
GE_DUMP(compute_graph, "AfterHandleMemConflict");
return SUCCESS;
}
} // namespace ge
| 41.253866 | 120 | 0.688064 | Ascend |
07801b4f11a045b8238458093cf635e90d02a917 | 483 | cpp | C++ | test/test_common.cpp | jhigginbotham64/Telescope | ef82f388934549e33d5fb21838d408c373b066e5 | [
"MIT"
] | null | null | null | test/test_common.cpp | jhigginbotham64/Telescope | ef82f388934549e33d5fb21838d408c373b066e5 | [
"MIT"
] | null | null | null | test/test_common.cpp | jhigginbotham64/Telescope | ef82f388934549e33d5fb21838d408c373b066e5 | [
"MIT"
] | null | null | null | //
// Copyright (c) Joshua Higginbotham, 2022
//
#include <test/test.hpp>
#include <telescope.hpp>
int main()
{
Test::initialize();
Test::testset("CLAMP", [](){
});
Test::testset("TS_NDCX", [](){
});
Test::testset("TS_NDCY", [](){
});
Test::testset("TS_NDCRect", [](){
});
Test::testset("TS_NTCU", [](){
});
Test::testset("TS_NTCV", [](){
});
Test::testset("TS_NTCRect", [](){
});
return Test::conclude();
}
| 13.416667 | 42 | 0.492754 | jhigginbotham64 |
078828ce4470d172569c812f55a8753fcc5f28fd | 1,573 | hpp | C++ | include/amtrs/.inc/net-types.hpp | isaponsoft/libamtrs | 5adf821ee15592fc3280985658ca8a4b175ffcaa | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2019-12-10T02:12:49.000Z | 2019-12-10T02:12:49.000Z | include/amtrs/.inc/net-types.hpp | isaponsoft/libamtrs | 5adf821ee15592fc3280985658ca8a4b175ffcaa | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | include/amtrs/.inc/net-types.hpp | isaponsoft/libamtrs | 5adf821ee15592fc3280985658ca8a4b175ffcaa | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | /* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. *
* Use of this source code is governed by a BSD-style license that *
* can be found in the LICENSE file. */
#ifndef __libamtrs__net__types__hpp
#define __libamtrs__net__types__hpp
AMTRS_NET_NAMESPACE_BEGIN
enum class protocol
{
http,
https,
};
enum class http_method
{
GET,
POST,
PUT,
DEL,
HEAD,
OPTIONS,
TRACE,
CONNECT,
};
enum class url_encode_type
{
// RFC2396 = 1,
RFC3986 = 2,
};
enum class http_statuscode
{
// 1xx
Continue = 100,
SwitchingProtocols = 101,
// 2xx
OK = 200,
Created = 201,
Accepted = 202,
NonAuthoritativeInformation = 203,
NoContent = 204,
ResetContent = 205,
PartialContent = 206,
// 3xx
MultipleChoices = 300,
MovedPermanently = 301,
MovedTemporarily = 302,
SeeOther = 303,
NotModified = 304,
UseProxy = 305,
// 4xx
BadRequest = 400,
Unauthorized = 401,
PaymentRequired = 402,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
NotAcceptable = 406,
ProxyAuthenticationRequired = 407,
RequestTimeOut = 408,
Conflict = 409,
Gone = 410,
LengthRequired = 411,
PreconditionFailed = 412,
RequestEntityTooLarge = 413,
RequestURITooLarge = 414,
UnsupportedMediaType = 415,
// 5xx
InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
SeviceUnavailable = 503,
GatewayTimeOut = 504,
HTTPVersionnotsupported = 505,
};
AMTRS_NET_NAMESPACE_END
#endif
| 18.290698 | 72 | 0.65035 | isaponsoft |
078da27b7e117a9fc7104873e11e7428a27cdc92 | 644 | cc | C++ | source/pkgsrc/chat/centerim/patches/patch-src_hooks_msnhook.cc | Scottx86-64/dotfiles-1 | 51004b1e2b032664cce6b553d2052757c286087d | [
"Unlicense"
] | 1 | 2021-11-20T22:46:39.000Z | 2021-11-20T22:46:39.000Z | source/pkgsrc/chat/centerim/patches/patch-src_hooks_msnhook.cc | Scottx86-64/dotfiles-1 | 51004b1e2b032664cce6b553d2052757c286087d | [
"Unlicense"
] | null | null | null | source/pkgsrc/chat/centerim/patches/patch-src_hooks_msnhook.cc | Scottx86-64/dotfiles-1 | 51004b1e2b032664cce6b553d2052757c286087d | [
"Unlicense"
] | null | null | null | $NetBSD: patch-src_hooks_msnhook.cc,v 1.1 2013/03/02 18:20:19 joerg Exp $
--- src/hooks/msnhook.cc.orig 2013-03-01 12:43:38.000000000 +0000
+++ src/hooks/msnhook.cc
@@ -684,7 +684,7 @@ void msncallbacks::gotBuddyListInfo(MSN:
mhook.setautostatus(mhook.manualstatus);
mhook.timer_ping = timer_current;
- mhook.log(abstracthook::logLogged);
+ mhook.log(msnhook::logLogged);
face.update();
}
@@ -883,7 +883,7 @@ void msncallbacks::closingConnection(MSN
clist.setoffline(msn);
mhook.fonline = false;
- mhook.log(abstracthook::logDisconnected);
+ mhook.log(msnhook::logDisconnected);
face.update();
}
| 28 | 73 | 0.687888 | Scottx86-64 |
078db69c7a027642e84fa4603a204afca6927b36 | 4,087 | cpp | C++ | test/PointFinder.cpp | dannosliwcd/PointQuery | 106eeef2838525909402d0316b827dfbf1a0ecd0 | [
"MIT"
] | null | null | null | test/PointFinder.cpp | dannosliwcd/PointQuery | 106eeef2838525909402d0316b827dfbf1a0ecd0 | [
"MIT"
] | null | null | null | test/PointFinder.cpp | dannosliwcd/PointQuery | 106eeef2838525909402d0316b827dfbf1a0ecd0 | [
"MIT"
] | 1 | 2018-12-04T20:37:27.000Z | 2018-12-04T20:37:27.000Z | #include <PointFinder.h>
#include <CountyRecord.h>
#include <catch.hpp>
#include <string>
TEST_CASE("search in empty finder")
{
std::vector<CountyRecord> records;
auto finder = PointFinder::Make(PointFinder::Method::KDTree, records);
REQUIRE(finder->FindNearest(0, 0, 1).empty());
finder = PointFinder::Make(PointFinder::Method::Heap, records);
REQUIRE(finder->FindNearest(0, 0, 1).empty());
}
TEST_CASE("search for exact points")
{
auto test = [](PointFinder::Method method)
{
std::vector<CountyRecord> records {
{"S1", "C1", 100, 200},
{"S1", "C2", 100, 210},
{"S1", "C3", 100, 220},
};
auto finder = PointFinder::Make(method, records);
for (const auto& record : records)
{
auto nearest = finder->FindNearest(record.m_latitude, record.m_longitude, 1);
REQUIRE(nearest.size() == 1);
REQUIRE(record == nearest.front().second);
}
};
SECTION("KD Tree")
{
test(PointFinder::Method::KDTree);
}
SECTION("Heap")
{
test(PointFinder::Method::Heap);
}
}
TEST_CASE("Search for a trivially close point")
{
auto test = [](PointFinder::Method method)
{
std::vector<CountyRecord> records {
{"S1", "C1", 100, 200},
{"S1", "C2", 100, 210},
{"S1", "C3", 100, 220},
};
auto finder = PointFinder::Make(PointFinder::Method::KDTree, records);
auto nearest = finder->FindNearest(101, 201, 1);
REQUIRE(nearest.size() == 1);
REQUIRE(records[0] == nearest.front().second);
};
SECTION("KD Tree")
{
test(PointFinder::Method::KDTree);
}
SECTION("Heap")
{
test(PointFinder::Method::Heap);
}
}
TEST_CASE("bottom of valley")
{
auto test = [](PointFinder::Method method)
{
std::vector<CountyRecord> records {
{"S1", "C1", 4, 1},
{"S1", "C2", 3, 1},
{"S1", "C3", 2, -1},
{"S1", "C4", 1, -1},
{"S1", "C5", 0, 0},
{"S1", "C6", 1, 1},
{"S1", "C7", 2, 1},
{"S1", "C8", 3, -1},
{"S1", "C9", 4, -1},
};
// KD Tree should split in to left and right halves on the root
auto finder = PointFinder::Make(PointFinder::Method::KDTree, records);
auto nearest = finder->FindNearest(0, 0, 1);
REQUIRE(nearest.size() == 1);
REQUIRE(records[4] == nearest.front().second);
};
SECTION("KD Tree")
{
test(PointFinder::Method::KDTree);
}
SECTION("Heap")
{
test(PointFinder::Method::Heap);
}
}
TEST_CASE("surrounding a central point")
{
auto test = [](PointFinder::Method method)
{
// Due to the lat/long projection, this is more of an octagon than a square, but
// that's not a problem for this test case.
std::vector<CountyRecord> records {
// corners counter clockwise from quadrant I
{"Corner", "C1", 9, 9},
{"Corner", "C2", -9, 9},
{"Corner", "C3", -9, -9},
{"Corner", "C4", 9, -9},
// midpoints counter clockwise from top
{"Midpoint", "MT", 0, 9},
{"Midpoint", "ML", -9, 0},
{"Midpoint", "MB", 0, -9},
{"Midpoint", "MR", 9, 0},
// center
{"Center", "O", 0, 0},
};
// KD Tree should split in to left and right halves on the root
auto finder = PointFinder::Make(PointFinder::Method::KDTree, records);
SECTION("exact points")
{
for (const auto& record : records)
{
auto nearest = finder->FindNearest(record.m_latitude, record.m_longitude, 1);
REQUIRE(nearest.size() == 1);
REQUIRE(record == nearest.front().second);
}
}
SECTION("in between")
{
auto nearest = finder->FindNearest(1, 1, 1);
REQUIRE(nearest.size() == 1);
REQUIRE(records[8] == nearest.front().second);
nearest = finder->FindNearest(8, 8, 1);
REQUIRE(nearest.size() == 1);
REQUIRE(records[0] == nearest.front().second);
}
SECTION("2 nearest")
{
auto nearest = finder->FindNearest(7, 9, 2);
REQUIRE(nearest.size() == 2);
CHECK(records[4] == nearest[0].second);
REQUIRE(records[0] == nearest[1].second);
}
};
SECTION("KD Tree")
{
test(PointFinder::Method::KDTree);
}
SECTION("Heap")
{
test(PointFinder::Method::Heap);
}
}
| 24.041176 | 83 | 0.584781 | dannosliwcd |
078ece8917fdd195baf28dd28d9ee2f1b32fa277 | 2,082 | hpp | C++ | shared/storage/option.hpp | jrnh/herby | bf0e90b850e2f81713e4dbc21c8d8b9af78ad203 | [
"MIT"
] | null | null | null | shared/storage/option.hpp | jrnh/herby | bf0e90b850e2f81713e4dbc21c8d8b9af78ad203 | [
"MIT"
] | null | null | null | shared/storage/option.hpp | jrnh/herby | bf0e90b850e2f81713e4dbc21c8d8b9af78ad203 | [
"MIT"
] | null | null | null | #pragma once
#include <windows.h>
#include <string>
#include <vector>
#include "shared/imgui/imgui.hpp"
#include "shared/memory/procedure.hpp"
namespace shared::option
{
struct VisualData
{
// core
int m_box = 0; // 0 - 3 | off, normal, corners, 3d
bool m_drop = false; //
bool m_drop_weapons = false; //
bool m_drop_cases = false; //
bool m_drop_medkit = false; //
bool m_drop_armor = false; //
bool m_drop_bags = false; //
bool m_drop_ammo = false; //
bool m_outlined = false; //
bool m_colored = false; //
bool m_spot = false; //
bool m_backtrack = false; //
bool m_fov = false; //
// target
bool m_friendly = false; //
bool m_visible_check = false; //
bool m_smoke_check = false; //
bool m_bomb = false; //
bool m_bomb_timer = false; //
// information
bool m_name = false; //
bool m_weapon = false; //
bool m_skeleton = false; //
bool m_defusing = false; //
int m_health = 0; // 0 - 2 | off, text, bar
int m_armor = 0; // 0 - 2 | off, text, bar
static std::vector< std::string > m_box_mode_array;
static std::vector< std::string > m_style_array;
void Clamp()
{
memory::Clamp(&m_box, 0, 3);
memory::Clamp(&m_health, 0, 2);
memory::Clamp(&m_armor, 0, 2);
}
};
struct ColorData
{
// main
ImColor color_esp_ct_normal = { 0.f, 0.5f, 1.f, 1.f };
ImColor color_esp_t_normal = { 1.f, 0.f, 0.f, 1.f };
ImColor color_esp_ct_colored = { 0, 237, 180, 255 };
ImColor color_esp_t_colored = { 237, 200, 0, 255 };
// reset
ImColor color_esp_ct_normal_r = { 0.f, 0.5f, 1.f, 1.f };
ImColor color_esp_t_normal_r = { 1.f, 0.f, 0.f, 1.f };
ImColor color_esp_ct_colored_r = { 0, 237, 180, 255 };
ImColor color_esp_t_colored_r = { 237, 200, 0, 255 };
};
extern VisualData m_visual;
extern ColorData m_colors;
bool Create();
void Destroy();
void Load(const std::string& name);
void Save(const std::string& name);
void Delete(const std::string& name);
} | 24.785714 | 59 | 0.599424 | jrnh |
0791bfdcf36a4fbb31345108c4cf6c86ab27bd51 | 9,351 | cpp | C++ | libraries/zmusic/midisources/midisource_mus.cpp | 351ELEC/lzdoom | 2ee3ea91bc9c052b3143f44c96d85df22851426f | [
"RSA-MD"
] | 2 | 2020-04-19T13:37:34.000Z | 2021-06-09T04:26:25.000Z | libraries/zmusic/midisources/midisource_mus.cpp | 351ELEC/lzdoom | 2ee3ea91bc9c052b3143f44c96d85df22851426f | [
"RSA-MD"
] | 4 | 2021-09-02T00:05:17.000Z | 2021-09-07T14:56:12.000Z | libraries/zmusic/midisources/midisource_mus.cpp | 351ELEC/lzdoom | 2ee3ea91bc9c052b3143f44c96d85df22851426f | [
"RSA-MD"
] | 1 | 2021-09-28T19:03:39.000Z | 2021-09-28T19:03:39.000Z | /*
** music_mus_midiout.cpp
** Code to let ZDoom play MUS music through the MIDI streaming API.
**
**---------------------------------------------------------------------------
** Copyright 1998-2008 Randy Heit
** 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. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**---------------------------------------------------------------------------
*/
// HEADER FILES ------------------------------------------------------------
#include <algorithm>
#include "midisource.h"
#include "zmusic/m_swap.h"
// MACROS ------------------------------------------------------------------
// TYPES -------------------------------------------------------------------
// EXTERNAL FUNCTION PROTOTYPES --------------------------------------------
// PUBLIC FUNCTION PROTOTYPES ----------------------------------------------
int MUSHeaderSearch(const uint8_t *head, int len);
// PRIVATE FUNCTION PROTOTYPES ---------------------------------------------
// EXTERNAL DATA DECLARATIONS ----------------------------------------------
// PRIVATE DATA DEFINITIONS ------------------------------------------------
static const uint8_t CtrlTranslate[15] =
{
0, // program change
0, // bank select
1, // modulation pot
7, // volume
10, // pan pot
11, // expression pot
91, // reverb depth
93, // chorus depth
64, // sustain pedal
67, // soft pedal
120, // all sounds off
123, // all notes off
126, // mono
127, // poly
121, // reset all controllers
};
// PUBLIC DATA DEFINITIONS -------------------------------------------------
// CODE --------------------------------------------------------------------
//==========================================================================
//
// MUSSong2 Constructor
//
// Performs some validity checks on the MUS file, buffers it, and creates
// the playback thread control events.
//
//==========================================================================
MUSSong2::MUSSong2 (const uint8_t *data, size_t len)
{
int start;
// To tolerate sloppy wads (diescum.wad, I'm looking at you), we search
// the first 32 bytes of the file for a signature. My guess is that DMX
// does no validation whatsoever and just assumes it was passed a valid
// MUS file, since where the header is offset affects how it plays.
start = MUSHeaderSearch(data, 32);
if (start < 0)
{
return;
}
data += start;
len -= start;
// Read the remainder of the song.
if (len < sizeof(MUSHeader))
{ // It's too short.
return;
}
MusData.resize(len);
memcpy(MusData.data(), data, len);
auto MusHeader = (MUSHeader*)MusData.data();
// Do some validation of the MUS file.
if (LittleShort(MusHeader->NumChans) > 15)
{
return;
}
MusBuffer = MusData.data() + LittleShort(MusHeader->SongStart);
MaxMusP = std::min<int>(LittleShort(MusHeader->SongLen), int(len) - LittleShort(MusHeader->SongStart));
Division = 140;
Tempo = InitialTempo = 1000000;
}
//==========================================================================
//
// MUSSong2 :: DoInitialSetup
//
// Sets up initial velocities and channel volumes.
//
//==========================================================================
void MUSSong2::DoInitialSetup()
{
for (int i = 0; i < 16; ++i)
{
LastVelocity[i] = 100;
ChannelVolumes[i] = 127;
}
}
//==========================================================================
//
// MUSSong2 :: DoRestart
//
// Rewinds the song.
//
//==========================================================================
void MUSSong2::DoRestart()
{
MusP = 0;
}
//==========================================================================
//
// MUSSong2 :: CheckDone
//
//==========================================================================
bool MUSSong2::CheckDone()
{
return MusP >= MaxMusP;
}
//==========================================================================
//
// MUSSong2 :: Precache
//
// MUS songs contain information in their header for exactly this purpose.
//
//==========================================================================
std::vector<uint16_t> MUSSong2::PrecacheData()
{
auto MusHeader = (MUSHeader*)MusData.data();
std::vector<uint16_t> work;
const uint8_t *used = MusData.data() + sizeof(MUSHeader) / sizeof(uint8_t);
int i, k;
int numinstr = LittleShort(MusHeader->NumInstruments);
work.reserve(LittleShort(MusHeader->NumInstruments));
for (i = k = 0; i < numinstr; ++i)
{
uint8_t instr = used[k++];
uint16_t val;
if (instr < 128)
{
val = instr;
}
else if (instr >= 135 && instr <= 188)
{ // Percussions are 100-based, not 128-based, eh?
val = instr - 100 + (1 << 14);
}
else
{
// skip it.
val = used[k++];
k += val;
continue;
}
int numbanks = used[k++];
if (numbanks > 0)
{
for (int b = 0; b < numbanks; b++)
{
work.push_back(val | (used[k++] << 7));
}
}
else
{
work.push_back(val);
}
}
return work;
}
//==========================================================================
//
// MUSSong2 :: MakeEvents
//
// Translates MUS events into MIDI events and puts them into a MIDI stream
// buffer. Returns the new position in the buffer.
//
//==========================================================================
uint32_t *MUSSong2::MakeEvents(uint32_t *events, uint32_t *max_event_p, uint32_t max_time)
{
uint32_t tot_time = 0;
uint32_t time = 0;
auto MusHeader = (MUSHeader*)MusData.data();
max_time = max_time * Division / Tempo;
while (events < max_event_p && tot_time <= max_time)
{
uint8_t mid1, mid2;
uint8_t channel;
uint8_t t = 0, status;
uint8_t event = MusBuffer[MusP++];
if ((event & 0x70) != MUS_SCOREEND)
{
t = MusBuffer[MusP++];
}
channel = event & 15;
// Map MUS channels to MIDI channels
if (channel == 15)
{
channel = 9;
}
else if (channel >= 9)
{
channel = channel + 1;
}
status = channel;
switch (event & 0x70)
{
case MUS_NOTEOFF:
status |= MIDI_NOTEON;
mid1 = t;
mid2 = 0;
break;
case MUS_NOTEON:
status |= MIDI_NOTEON;
mid1 = t & 127;
if (t & 128)
{
LastVelocity[channel] = MusBuffer[MusP++];
}
mid2 = LastVelocity[channel];
break;
case MUS_PITCHBEND:
status |= MIDI_PITCHBEND;
mid1 = (t & 1) << 6;
mid2 = (t >> 1) & 127;
break;
case MUS_SYSEVENT:
status |= MIDI_CTRLCHANGE;
mid1 = CtrlTranslate[t];
mid2 = t == 12 ? LittleShort(MusHeader->NumChans) : 0;
break;
case MUS_CTRLCHANGE:
if (t == 0)
{ // program change
status |= MIDI_PRGMCHANGE;
mid1 = MusBuffer[MusP++];
mid2 = 0;
}
else
{
status |= MIDI_CTRLCHANGE;
mid1 = CtrlTranslate[t];
mid2 = MusBuffer[MusP++];
if (mid1 == 7)
{ // Clamp volume to 127, since DMX apparently allows 8-bit volumes.
// Fix courtesy of Gez, courtesy of Ben Ryves.
mid2 = VolumeControllerChange(channel, std::min<int>(mid2, 0x7F));
}
}
break;
case MUS_SCOREEND:
default:
MusP = MaxMusP;
goto end;
}
events[0] = time; // dwDeltaTime
events[1] = 0; // dwStreamID
events[2] = status | (mid1 << 8) | (mid2 << 16);
events += 3;
time = 0;
if (event & 128)
{
do
{
t = MusBuffer[MusP++];
time = (time << 7) | (t & 127);
}
while (t & 128);
}
tot_time += time;
}
end:
if (time != 0)
{
events[0] = time; // dwDeltaTime
events[1] = 0; // dwStreamID
events[2] = MEVENT_NOP << 24; // dwEvent
events += 3;
}
return events;
}
//==========================================================================
//
// MUSHeaderSearch
//
// Searches for the MUS header within the given memory block, returning
// the offset it was found at, or -1 if not present.
//
//==========================================================================
int MUSHeaderSearch(const uint8_t *head, int len)
{
len -= 4;
for (int i = 0; i <= len; ++i)
{
if (head[i+0] == 'M' && head[i+1] == 'U' && head[i+2] == 'S' && head[i+3] == 0x1A)
{
return i;
}
}
return -1;
}
| 25.54918 | 104 | 0.52465 | 351ELEC |
0793dfa5e53053633acc28922aea43c1bb12d941 | 753 | hpp | C++ | src/optimizer/path_generator.hpp | dzitkowskik/GpuTimeSeriesCompressionOptimizer | d8c68c14b869ab4b3b9e248f41bc5593a4fddfe8 | [
"MIT",
"Unlicense"
] | 2 | 2019-06-20T19:49:13.000Z | 2020-08-11T09:22:33.000Z | src/optimizer/path_generator.hpp | dzitkowskik/GpuTimeSeriesCompressionOptimizer | d8c68c14b869ab4b3b9e248f41bc5593a4fddfe8 | [
"MIT",
"Unlicense"
] | null | null | null | src/optimizer/path_generator.hpp | dzitkowskik/GpuTimeSeriesCompressionOptimizer | d8c68c14b869ab4b3b9e248f41bc5593a4fddfe8 | [
"MIT",
"Unlicense"
] | 2 | 2021-03-11T01:08:00.000Z | 2022-03-02T13:53:29.000Z | /*
* path_generator.hpp
*
* Created on: 12/11/2015
* Author: Karol Dzitkowski
*/
#ifndef PATH_GENERATOR_HPP_
#define PATH_GENERATOR_HPP_
#include "compression/encoding_type.hpp"
#include "data_type.hpp"
#include "tree/compression_tree.hpp"
#include "util/statistics/cuda_array_statistics.hpp"
#include <vector>
#include <list>
namespace ddj
{
using Path = std::vector<EncodingType>;
using PathList = std::list<Path>;
using PossibleTree = std::pair<CompressionTree, size_t>;
class PathGenerator
{
public:
PathList GeneratePaths();
CompressionTree GenerateTree(Path path, DataType type);
Path GetContinuations(EncodingType et, DataType dt, DataStatistics stats, int level);
};
} /* namespace ddj */
#endif /* PATH_GENERATOR_HPP_ */
| 20.351351 | 86 | 0.752988 | dzitkowskik |
07960f8068d9496d940b689a9d3458617fa16024 | 3,071 | cpp | C++ | src/gui/GuiText.cpp | Eyadplayz/Project-Architesis | 89c44d3e35604c1fb9a3f0b3635620e3e6241025 | [
"MIT"
] | null | null | null | src/gui/GuiText.cpp | Eyadplayz/Project-Architesis | 89c44d3e35604c1fb9a3f0b3635620e3e6241025 | [
"MIT"
] | null | null | null | src/gui/GuiText.cpp | Eyadplayz/Project-Architesis | 89c44d3e35604c1fb9a3f0b3635620e3e6241025 | [
"MIT"
] | 2 | 2021-11-20T01:39:37.000Z | 2021-11-28T00:06:19.000Z | /****************************************************************************
* Copyright (C) 2015 Dimok
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
****************************************************************************/
#include <cstdarg>
#include <SDL2/SDL_surface.h>
#include "GuiText.h"
/**
* Constructor for the GuiText class.
*/
GuiText::GuiText(const std::string& text, SDL_Color c, FC_Font* gFont) {
this->text = text;
this->color = c;
this->fc_font = gFont;
this->doUpdateTexture = true;
this->texture.setParent(this);
}
GuiText::~GuiText() {
delete textureData;
}
void GuiText::draw(Renderer *renderer) {
if (!this->isVisible()) {
return;
}
updateTexture(renderer);
texture.draw(renderer);
}
void GuiText::process() {
GuiElement::process();
}
void GuiText::setMaxWidth(float width) {
this->maxWidth = width;
// Rebuild the texture cache on next draw
doUpdateTexture = true;
}
void GuiText::updateSize() {
auto height = FC_GetColumnHeight(fc_font, maxWidth, text.c_str());
auto width = FC_GetWidth(fc_font, text.c_str());
width = width > maxWidth ? maxWidth : width;
this->setSize(width, height);
}
void GuiText::updateTexture(Renderer *renderer) {
if(doUpdateTexture) {
updateSize();
int tex_width = tex_width = width == 0 ? 1 : (int) width;
int tex_height = tex_height = height == 0 ? 1 : (int)height;
SDL_Texture *temp = SDL_CreateTexture(renderer->getRenderer(), renderer->getPixelFormat(), SDL_TEXTUREACCESS_TARGET, tex_width, tex_height);
if (temp) {
texture.setTexture(nullptr);
delete textureData;
textureData = new GuiTextureData(temp);
textureData->setBlendMode(SDL_BLENDMODE_BLEND);
texture.setTexture(textureData);
// Set render target to texture
SDL_SetRenderTarget(renderer->getRenderer(), temp);
// Clear texture.
SDL_SetRenderDrawColor(renderer->getRenderer(), 0, 0, 0, 0);
SDL_RenderClear(renderer->getRenderer());
// Draw text to texture
FC_DrawColumn(fc_font, renderer->getRenderer(), 0, 0, maxWidth, text.c_str());
// Restore render target
SDL_SetRenderTarget(renderer->getRenderer(), nullptr);
} else {
DEBUG_FUNCTION_LINE("Failed to create texture");
}
doUpdateTexture = false;
}
}
| 31.659794 | 148 | 0.622924 | Eyadplayz |
0796e351bc1d6a4c6b27bb20ea45638c6839f61b | 2,537 | cpp | C++ | GoogleServiceServer/recommit.cpp | satadriver/GoogleServiceServer | 7d6e55d2f9a189301dd68821c920d0a0e300322a | [
"Apache-2.0"
] | null | null | null | GoogleServiceServer/recommit.cpp | satadriver/GoogleServiceServer | 7d6e55d2f9a189301dd68821c920d0a0e300322a | [
"Apache-2.0"
] | null | null | null | GoogleServiceServer/recommit.cpp | satadriver/GoogleServiceServer | 7d6e55d2f9a189301dd68821c920d0a0e300322a | [
"Apache-2.0"
] | null | null | null |
#include "recommit.h"
#include "FileOperator.h"
#include "FileWriter.h"
#include <iostream>
#include "DataProcess.h"
#include "PublicFunction.h"
#include <string>
using namespace std;
#define BUF_SIZE 4096
#define ENTERLN "\r\n"
int commit(string path) {
WIN32_FIND_DATAA fd = { 0 };
string fn = path + "*.*";
HANDLE hf = FindFirstFileA(fn.c_str(), &fd);
if (hf == INVALID_HANDLE_VALUE)
{
return -1;
}
while(1)
{
int ret = 0;
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if (strcmp(fd.cFileName, "..") == 0 || strcmp(fd.cFileName, ".") == 0)
{
}
else {
string next = path + fd.cFileName + "\\";
if (lstrcmpiA(fd.cFileName, "WeiXinVideo") == 0 ||
lstrcmpiA(fd.cFileName, "WeiXinAudio") == 0 || lstrcmpiA(fd.cFileName, "WeiXinPhoto") == 0 ||
lstrcmpiA(fd.cFileName, "DCIM") == 0)
{
ret = commit(next);
// string nextpath = path + fd.cFileName ;
// string cmd = "cmd /c rmdir /s/q " + nextpath; //rmdir == rd ?
// ret = WinExec(cmd.c_str(),SW_HIDE);
// WriteLogFile((char*)(cmd + "\r\n").c_str());
}
else {
ret = commit(next);
}
}
}
else if (fd.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) {
if (strstr(fd.cFileName, ".json") /*|| strstr(fd.cFileName, ".jpg")*/) {
string tag = "notify:" + path + fd.cFileName + "\r\n";
WriteLogFile((char*)tag.c_str());
//int res = DataProcess::DataNotify(path + fd.cFileName);
Sleep(1000);
}
}
ret = FindNextFileA(hf, &fd);
if (ret <= 0)
{
break;
}
}
FindClose(hf);
return 0;
}
int __stdcall Recommit::recommit() {
while (1)
{
char szpath[MAX_PATH] = { 0 };
int ret = GetCurrentDirectoryA(MAX_PATH, szpath);
string fn = string(szpath) + "\\recommit.config";
DWORD filesize = 0;
char * lpdata = new char[BUF_SIZE];
filesize = FileOperator::fileReader(fn.c_str(), lpdata, BUF_SIZE);
if (filesize > 0) {
string path = lpdata;
string sub = "";
while (1)
{
int pos = path.find(ENTERLN);
if (pos >= 0)
{
sub = path.substr(0, pos);
path = path.substr(pos + strlen(ENTERLN));
if (sub.back() != '\\')
{
sub.append("\\");
}
}
else if (path.length() > 0)
{
sub = path;
if (sub.back() != '\\')
{
sub.append("\\");
}
path = "";
//path = path.substr(path.length());
}
else {
break;
}
ret = commit(string(szpath) + "\\"+ sub);
if (ret < 0)
{
}
}
}
delete[] lpdata;
Sleep(3000);
}
} | 18.932836 | 98 | 0.553015 | satadriver |
0798aa108bfb952eb527c60bb0a61482f2a7ba6f | 2,128 | cpp | C++ | project-2/CS248/examples/event.cpp | JRBarreraM/CI4321_COMPUTACION_GRAFICA_I | 8d5aaa536fdfe0e2e678bc9b7abb613e33057b07 | [
"MIT"
] | 1 | 2022-02-08T10:39:40.000Z | 2022-02-08T10:39:40.000Z | project-2/CS248/examples/event.cpp | JRBarreraM/CI4321_COMPUTACION_GRAFICA_I | 8d5aaa536fdfe0e2e678bc9b7abb613e33057b07 | [
"MIT"
] | null | null | null | project-2/CS248/examples/event.cpp | JRBarreraM/CI4321_COMPUTACION_GRAFICA_I | 8d5aaa536fdfe0e2e678bc9b7abb613e33057b07 | [
"MIT"
] | null | null | null | #include <string>
#include <iostream>
#include "CS248/viewer.h"
#include "CS248/renderer.h"
using namespace std;
using namespace CS248;
class EventDisply : public Renderer {
public:
~EventDisply() { }
string name() {
return "Event handling example";
}
string info() {
return "Event handling example";
}
void init() {
text_mgr.init(use_hdpi);
size = 16;
line0 = text_mgr.add_line(0.0, 0.0, "Hi there!", size, Color::White);
return;
}
void render() {
text_mgr.render();
}
void resize(size_t w, size_t h) {
this->w = w;
this->h = h;
text_mgr.resize(w,h);
return;
}
void cursor_event(float x, float y) {
if (left_down) {
text_mgr.set_anchor(line0, 2 * (x - .5 * w) / w, 2 * (.5 * h - y) / h);
}
}
void scroll_event(float offset_x, float offset_y) {
size += int(offset_y + offset_x);
text_mgr.set_size(line0, size);
}
void mouse_event(int key, int event, unsigned char mods) {
if (key == MOUSE_LEFT) {
if (event == EVENT_PRESS) left_down = true;
if (event == EVENT_RELEASE) left_down = false;
}
}
void keyboard_event(int key, int event, unsigned char mods) {
string s;
switch (event) {
case EVENT_PRESS:
s = "You just pressed: ";
break;
case EVENT_RELEASE:
s = "You just released: ";
break;
case EVENT_REPEAT:
s = "You are holding: ";
break;
}
if (key == KEYBOARD_ENTER) {
s += "Enter";
} else {
char c = key;
s += c;
}
text_mgr.set_text(line0, s);
}
private:
// OSD text manager
OSDText text_mgr;
// my line id's
int line0;
// my line's font size
size_t size;
// frame buffer size
size_t w, h;
// key states
bool left_down;
};
int main( int argc, char** argv ) {
// create viewer
Viewer viewer = Viewer();
// defined a user space renderer
Renderer* renderer = new EventDisply();
// set user space renderer
viewer.set_renderer(renderer);
// start the viewer
viewer.init();
viewer.start();
return 0;
}
| 16.496124 | 83 | 0.578477 | JRBarreraM |
079af748c512aa6b318e54268f5cdba8e013efdb | 102 | hpp | C++ | addons/heavylifter/XEH_PREP.hpp | Task-Force-Dagger/Dagger | 56b9ffe3387f74830419a987eed5a0f386674331 | [
"MIT"
] | null | null | null | addons/heavylifter/XEH_PREP.hpp | Task-Force-Dagger/Dagger | 56b9ffe3387f74830419a987eed5a0f386674331 | [
"MIT"
] | 7 | 2021-11-22T04:36:52.000Z | 2021-12-13T18:55:24.000Z | addons/heavylifter/XEH_PREP.hpp | Task-Force-Dagger/Dagger | 56b9ffe3387f74830419a987eed5a0f386674331 | [
"MIT"
] | null | null | null | PREP(canAttach);
PREP(canDetach);
PREP(exportConfig);
PREP(prepare);
PREP(progress);
PREP(unprepare);
| 14.571429 | 19 | 0.764706 | Task-Force-Dagger |
079c1060a8c9edb1b2ba14700cf3e23a2922ffda | 2,138 | cpp | C++ | Native/Live2DCubismFrameworkJNI/extend_cpp/JavaPal.cpp | leekcake/Live2D-for-JVM | 686931131b43a1a1c0a6ca6cf01839b28876af2f | [
"MIT"
] | 10 | 2018-03-01T14:57:19.000Z | 2021-11-28T06:30:44.000Z | Native/Live2DCubismFrameworkJNI/extend_cpp/JavaPal.cpp | leekcake/Live2D-for-JVM | 686931131b43a1a1c0a6ca6cf01839b28876af2f | [
"MIT"
] | 2 | 2018-10-26T15:15:29.000Z | 2018-11-04T09:58:34.000Z | Native/Live2DCubismFrameworkJNI/extend_cpp/JavaPal.cpp | leekcake/Live2D-for-JVM | 686931131b43a1a1c0a6ca6cf01839b28876af2f | [
"MIT"
] | null | null | null | /*
* Copyright(c) Live2D Inc. All rights reserved.
*
* Use of this source code is governed by the Live2D Open Software license
* that can be found at http://live2d.com/eula/live2d-open-software-license-agreement_en.html.
*/
#include "JavaPal.hpp"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/stat.h>
#include <iostream>
#include <fstream>
#include <Model/CubismMoc.hpp>
#include "JavaDefine.hpp"
#include <Live2DCubismCore.hpp>
using std::endl;
using namespace Csm;
using namespace std;
using namespace JavaDefine;
double JavaPal::s_currentFrame = 0.0;
double JavaPal::s_lastFrame = 0.0;
double JavaPal::s_deltaTime = 0.0;
JavaPALTimeFunction JavaPal::s_timeFunction = NULL;
JavaPALTextureFunction JavaPal::s_textureFunction = NULL;
JavaPALDataFunction JavaPal::s_dataFunction = NULL;
csmByte* JavaPal::LoadFileAsBytes(const string filePath, csmSizeInt* outSize)
{
if (s_dataFunction == NULL) {
return NULL;
}
return s_dataFunction(filePath, outSize);
}
void JavaPal::ReleaseBytes(csmByte* byteData)
{
delete[] byteData;
}
csmFloat32 JavaPal::GetDeltaTime()
{
return static_cast<csmFloat32>(s_deltaTime);
}
void JavaPal::UpdateTime()
{
if (s_timeFunction == NULL) {
return;
}
s_currentFrame = s_timeFunction();
s_deltaTime = s_currentFrame - s_lastFrame;
s_lastFrame = s_currentFrame;
}
void JavaPal::PrintLog(const csmChar* format, ...)
{
va_list args;
csmChar buf[256];
va_start(args, format);
vsnprintf(buf, sizeof(buf), format, args); // 標準出力でレンダリング
Live2D::Cubism::Core::csmGetLogFunction()(buf);
va_end(args);
}
void JavaPal::PrintMessage(const csmChar* message)
{
PrintLog("%s", message);
}
int JavaPal::GetTexture(const char * filePath)
{
if (s_textureFunction == NULL) {
return -1;
}
return s_textureFunction(filePath);
}
void JavaPal::SetJavaPALTimeFunction(JavaPALTimeFunction function)
{
s_timeFunction = function;
}
void JavaPal::SetJavaPALTextureFunction(JavaPALTextureFunction function)
{
s_textureFunction = function;
}
void JavaPal::SetJavaPALDataFunction(JavaPALDataFunction function)
{
s_dataFunction = function;
}
| 22.270833 | 93 | 0.745089 | leekcake |
07a1f9580011afe3cacfe8ce786c2710771af852 | 569 | cpp | C++ | Volume126/12673 - Football/12673.cpp | rstancioiu/uva-online-judge | 31c536d764462d389b48b4299b9731534824c9f5 | [
"MIT"
] | 1 | 2017-01-25T18:07:49.000Z | 2017-01-25T18:07:49.000Z | Volume126/12673 - Football/12673.cpp | rstancioiu/uva-online-judge | 31c536d764462d389b48b4299b9731534824c9f5 | [
"MIT"
] | null | null | null | Volume126/12673 - Football/12673.cpp | rstancioiu/uva-online-judge | 31c536d764462d389b48b4299b9731534824c9f5 | [
"MIT"
] | null | null | null | // Author: Stancioiu Nicu Razvan
// Problem: http://uva.onlinejudge.org/external/126/12673.html
#include <bits/stdc++.h>
#define N 100010
using namespace std;
int n,g,s,r;
int dif[N];
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
while(cin>>n>>g)
{
for(int i=0;i<n;++i)
{
cin>>s>>r;
dif[i]=s-r;
}
sort(dif,dif+n);
int cnt=0;
for(int i=n-1;i>=0;--i)
{
if(dif[i]>0)
cnt+=3;
else if(dif[i]+g>0)
{
g-=1-dif[i];
cnt+=3;
}
else if(dif[i]+g==0)
{
g=0;
cnt++;
}
}
cout<<cnt<<endl;
}
return 0;
} | 13.547619 | 62 | 0.528998 | rstancioiu |
07a400ed2d86ebf50b74d52f1df9936fdaa6f027 | 7,809 | cc | C++ | rl_agent/src/Agent/Sarsa.cc | utexas-rl-texplore/rl_suite | 73b5c3cdeaa2397cef6758dad8275193e7b0019a | [
"BSD-3-Clause"
] | 1 | 2015-07-23T21:14:56.000Z | 2015-07-23T21:14:56.000Z | rl_agent/src/Agent/Sarsa.cc | utexas-rl-texplore/rl_suite | 73b5c3cdeaa2397cef6758dad8275193e7b0019a | [
"BSD-3-Clause"
] | null | null | null | rl_agent/src/Agent/Sarsa.cc | utexas-rl-texplore/rl_suite | 73b5c3cdeaa2397cef6758dad8275193e7b0019a | [
"BSD-3-Clause"
] | 1 | 2018-03-01T05:54:44.000Z | 2018-03-01T05:54:44.000Z | #include <rl_agent/Sarsa.hh>
#include <algorithm>
Sarsa::Sarsa(int numactions, float gamma,
float initialvalue, float alpha, float ep, float lambda,
Random rng):
numactions(numactions), gamma(gamma),
initialvalue(initialvalue), alpha(alpha),
epsilon(ep), lambda(lambda),
rng(rng)
{
currentq = NULL;
ACTDEBUG = false; //true; //false;
ELIGDEBUG = false;
}
Sarsa::~Sarsa() {}
int Sarsa::first_action(const std::vector<float> &s) {
if (ACTDEBUG){
cout << "First - in state: ";
printState(s);
cout << endl;
}
// clear all eligibility traces
for (std::map<state_t, std::vector<float> >::iterator i = eligibility.begin();
i != eligibility.end(); i++){
std::vector<float> & elig_s = (*i).second;
for (int j = 0; j < numactions; j++){
elig_s[j] = 0.0;
}
}
// Get action values
state_t si = canonicalize(s);
std::vector<float> &Q_s = Q[si];
// Choose an action
const std::vector<float>::iterator a =
rng.uniform() < epsilon
? Q_s.begin() + rng.uniformDiscrete(0, numactions - 1) // Choose randomly
: random_max_element(Q_s.begin(), Q_s.end()); // Choose maximum
// set eligiblity to 1
std::vector<float> &elig_s = eligibility[si];
elig_s[a-Q_s.begin()] = 1.0;
if (ACTDEBUG){
cout << " act: " << (a-Q_s.begin()) << " val: " << *a << endl;
for (int iAct = 0; iAct < numactions; iAct++){
cout << " Action: " << iAct
<< " val: " << Q_s[iAct] << endl;
}
cout << "Took action " << (a-Q_s.begin()) << " from state ";
printState(s);
cout << endl;
}
return a - Q_s.begin();
}
int Sarsa::next_action(float r, const std::vector<float> &s) {
if (ACTDEBUG){
cout << "Next: got reward " << r << " in state: ";
printState(s);
cout << endl;
}
// Get action values
state_t st = canonicalize(s);
std::vector<float> &Q_s = Q[st];
const std::vector<float>::iterator max =
random_max_element(Q_s.begin(), Q_s.end());
// Choose an action
const std::vector<float>::iterator a =
rng.uniform() < epsilon
? Q_s.begin() + rng.uniformDiscrete(0, numactions - 1)
: max;
// Update value for all with positive eligibility
for (std::map<state_t, std::vector<float> >::iterator i = eligibility.begin();
i != eligibility.end(); i++){
state_t si = (*i).first;
std::vector<float> & elig_s = (*i).second;
for (int j = 0; j < numactions; j++){
if (elig_s[j] > 0.0){
if (ELIGDEBUG) {
cout << "updating state " << (*((*i).first))[0] << ", " << (*((*i).first))[1] << " act: " << j << " with elig: " << elig_s[j] << endl;
}
// update
Q[si][j] += alpha * elig_s[j] * (r + gamma * (*a) - Q[si][j]);
elig_s[j] *= lambda;
}
}
}
// Set elig to 1
eligibility[st][a-Q_s.begin()] = 1.0;
if (ACTDEBUG){
cout << " act: " << (a-Q_s.begin()) << " val: " << *a << endl;
for (int iAct = 0; iAct < numactions; iAct++){
cout << " Action: " << iAct
<< " val: " << Q_s[iAct] << endl;
}
cout << "Took action " << (a-Q_s.begin()) << " from state ";
printState(s);
cout << endl;
}
return a - Q_s.begin();
}
void Sarsa::last_action(float r) {
if (ACTDEBUG){
cout << "Last: got reward " << r << endl;
}
// Update value for all with positive eligibility
for (std::map<state_t, std::vector<float> >::iterator i = eligibility.begin();
i != eligibility.end(); i++){
state_t si = (*i).first;
std::vector<float> & elig_s = (*i).second;
for (int j = 0; j < numactions; j++){
if (elig_s[j] > 0.0){
if (ELIGDEBUG){
cout << "updating state " << (*((*i).first))[0] << ", " << (*((*i).first))[1] << " act: " << j << " with elig: " << elig_s[j] << endl;
}
// update
Q[si][j] += alpha * elig_s[j] * (r - Q[si][j]);
elig_s[j] = 0.0;
}
}
}
}
Sarsa::state_t Sarsa::canonicalize(const std::vector<float> &s) {
const std::pair<std::set<std::vector<float> >::iterator, bool> result =
statespace.insert(s);
state_t retval = &*result.first; // Dereference iterator then get pointer
if (result.second) { // s is new, so initialize Q(s,a) for all a
std::vector<float> &Q_s = Q[retval];
Q_s.resize(numactions,initialvalue);
std::vector<float> &elig = eligibility[retval];
elig.resize(numactions,0);
}
return retval;
}
std::vector<float>::iterator
Sarsa::random_max_element(
std::vector<float>::iterator start,
std::vector<float>::iterator end) {
std::vector<float>::iterator max =
std::max_element(start, end);
int n = std::count(max, end, *max);
if (n > 1) {
n = rng.uniformDiscrete(1, n);
while (n > 1) {
max = std::find(max + 1, end, *max);
--n;
}
}
return max;
}
void Sarsa::setDebug(bool d){
ACTDEBUG = d;
}
void Sarsa::printState(const std::vector<float> &s){
for (unsigned j = 0; j < s.size(); j++){
cout << s[j] << ", ";
}
}
void Sarsa::seedExp(std::vector<experience> seeds){
// for each seeding experience, update our model
for (unsigned i = 0; i < seeds.size(); i++){
experience e = seeds[i];
std::vector<float> &Q_s = Q[canonicalize(e.s)];
// Get q value for action taken
const std::vector<float>::iterator a = Q_s.begin() + e.act;
// Update value of action just executed
Q_s[e.act] += alpha * (e.reward + gamma * (*a) - Q_s[e.act]);
/*
cout << "Seeding with experience " << i << endl;
cout << "last: " << (e.s)[0] << ", " << (e.s)[1] << ", "
<< (e.s)[2] << endl;
cout << "act: " << e.act << " r: " << e.reward << endl;
cout << "next: " << (e.next)[0] << ", " << (e.next)[1] << ", "
<< (e.next)[2] << ", " << e.terminal << endl;
cout << "Q: " << *currentq << " max: " << *max << endl;
*/
}
}
void Sarsa::logValues(ofstream *of, int xmin, int xmax, int ymin, int ymax){
std::vector<float> s;
s.resize(2, 0.0);
for (int i = xmin ; i < xmax; i++){
for (int j = ymin; j < ymax; j++){
s[0] = j;
s[1] = i;
std::vector<float> &Q_s = Q[canonicalize(s)];
const std::vector<float>::iterator max =
random_max_element(Q_s.begin(), Q_s.end());
*of << (*max) << ",";
}
}
}
float Sarsa::getValue(std::vector<float> state){
state_t s = canonicalize(state);
// Get Q values
std::vector<float> &Q_s = Q[s];
// Choose an action
const std::vector<float>::iterator a =
random_max_element(Q_s.begin(), Q_s.end()); // Choose maximum
// Get avg value
float valSum = 0.0;
float cnt = 0;
for (std::set<std::vector<float> >::iterator i = statespace.begin();
i != statespace.end(); i++){
state_t s = canonicalize(*i);
// get state's info
std::vector<float> &Q_s = Q[s];
for (int j = 0; j < numactions; j++){
valSum += Q_s[j];
cnt++;
}
}
cout << "Avg Value: " << (valSum / cnt) << endl;
return *a;
}
void Sarsa::savePolicy(const char* filename){
ofstream policyFile(filename, ios::out | ios::binary | ios::trunc);
// first part, save the vector size
std::set< std::vector<float> >::iterator i = statespace.begin();
int fsize = (*i).size();
policyFile.write((char*)&fsize, sizeof(int));
// save numactions
policyFile.write((char*)&numactions, sizeof(int));
// go through all states, and save Q values
for (std::set< std::vector<float> >::iterator i = statespace.begin();
i != statespace.end(); i++){
state_t s = canonicalize(*i);
std::vector<float> *Q_s = &(Q[s]);
// save state
policyFile.write((char*)&((*i)[0]), sizeof(float)*fsize);
// save q-values
policyFile.write((char*)&((*Q_s)[0]), sizeof(float)*numactions);
}
policyFile.close();
}
| 25.271845 | 144 | 0.548214 | utexas-rl-texplore |
07a67fd2461a8d8e01d2b350f64f3c0edfe0e718 | 8,240 | cpp | C++ | WGLTest/main.cpp | yorung/WGLGrabber | 8887cfc95d2f2040205a084473b96f53f46cf591 | [
"MIT"
] | null | null | null | WGLTest/main.cpp | yorung/WGLGrabber | 8887cfc95d2f2040205a084473b96f53f46cf591 | [
"MIT"
] | null | null | null | WGLTest/main.cpp | yorung/WGLGrabber | 8887cfc95d2f2040205a084473b96f53f46cf591 | [
"MIT"
] | null | null | null | // WGLTest.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "resource.h"
#pragma comment(lib, "opengl32.lib")
HGLRC hglrc;
static void err(char *msg)
{
puts(msg);
}
#ifdef _DEBUG
static void DumpInfo()
{
puts((char*)glGetString(GL_VERSION));
puts((char*)glGetString(GL_RENDERER));
puts((char*)glGetString(GL_VENDOR));
puts((char*)glGetString(GL_SHADING_LANGUAGE_VERSION));
GLint num;
glGetIntegerv(GL_NUM_EXTENSIONS, &num);
for (int i = 0; i < num; i++) {
const GLubyte* ext = glGetStringi(GL_EXTENSIONS, i);
printf("%s\n", ext);
}
}
static void APIENTRY debugMessageHandler(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam)
{
puts(message);
}
#endif
void CreateWGL(HWND hWnd)
{
HDC hdc = GetDC(hWnd);
PIXELFORMATDESCRIPTOR pfd;
memset(&pfd, 0, sizeof(pfd));
pfd.nSize = sizeof(pfd);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
int pixelFormat;
if (!(pixelFormat = ChoosePixelFormat(hdc, &pfd))){
err("ChoosePixelFormat failed.");
goto END;
}
if (!SetPixelFormat(hdc, pixelFormat, &pfd)){
err("SetPixelFormat failed.");
goto END;
}
if (!(hglrc = wglCreateContext(hdc))){
err("wglCreateContext failed.");
goto END;
}
if (!wglMakeCurrent(hdc, hglrc)){
err("wglMakeCurrent failed.");
goto END;
}
#if 0 // for test
void* glpu = wglGetProcAddress("glProgramUniform1f");
void* gldei = wglGetProcAddress("glDrawElementsIndirect");
void* glen1 = glEnable;
void* glen2 = wglGetProcAddress("glEnable");
GLuint(APIENTRY*glCreateProgram)(void);
glCreateProgram = (GLuint(APIENTRY*)(void))wglGetProcAddress("glCreateProgram");
GLuint(APIENTRY*glCreateShader)(GLenum type);
glCreateShader = (GLuint(APIENTRY*)(GLenum type))wglGetProcAddress("glCreateShader");
GLuint test = glCreateShader(GL_VERTEX_SHADER);
void(APIENTRY*glDeleteShader)(GLuint name);
glDeleteShader = (void(APIENTRY*)(GLuint name))wglGetProcAddress("glDeleteShader");
glDeleteShader(test);
#endif
WGLGrabberInit();
int flags = 0;
#ifdef _DEBUG
flags |= WGL_CONTEXT_DEBUG_BIT_ARB;
#endif
static const int attribList[] = {
WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
WGL_CONTEXT_MINOR_VERSION_ARB, 3,
WGL_CONTEXT_FLAGS_ARB, flags,
// WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_ES2_PROFILE_BIT_EXT,
0,
};
HGLRC hglrcNew = wglCreateContextAttribsARB(hdc, 0, attribList);
wglMakeCurrent(nullptr, nullptr);
if (hglrcNew) {
wglDeleteContext(hglrc);
hglrc = hglrcNew;
}
if (!wglMakeCurrent(hdc, hglrc)){
err("wglMakeCurrent failed.");
goto END;
}
#ifdef _DEBUG
DumpInfo();
glDebugMessageCallbackARB(debugMessageHandler, nullptr);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
#endif
END:
// ReleaseDC(hWnd, hdc); // do not release dc; WGL using it
return; // do nothing
}
void DestroyWGL(HWND hWnd)
{
HDC hdc = wglGetCurrentDC();
if (hdc) {
ReleaseDC(hWnd, hdc);
}
wglMakeCurrent(nullptr, nullptr);
if (hglrc) {
wglDeleteContext(hglrc);
hglrc = nullptr;
}
}
#define MAX_LOADSTRING 100
// Global Variables:
HWND hWnd;
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
// WindowMessage
static BOOL ProcessWindowMessage(){
MSG msg;
for (;;){
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
if (msg.message == WM_QUIT){
return FALSE;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
BOOL active = !IsIconic(hWnd) && GetForegroundWindow() == hWnd;
if (!active){
WaitMessage();
continue;
}
return TRUE;
}
}
static void Input()
{
static bool last;
bool current = !!(GetKeyState(VK_LBUTTON) & 0x80);
bool edge = current && !last;
last = current;
if (edge) {
POINT pt;
GetCursorPos(&pt);
ScreenToClient(GetForegroundWindow(), &pt);
RECT rc;
GetClientRect(hWnd, &rc);
int w = rc.right - rc.left;
int h = rc.bottom - rc.top;
app.CreateRipple((float)pt.x / w * 2 - 1, (float)pt.y / h * -2 + 1);
}
}
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
#ifdef _DEBUG
int main(int, char**)
#else
int APIENTRY _tWinMain(_In_ HINSTANCE,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int)
#endif
{
HINSTANCE hInstance = GetModuleHandle(nullptr);
// TODO: Place code here.
HACCEL hAccelTable;
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_WGLTEST, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WGLTEST));
GoMyDir();
SetCurrentDirectoryA("assets");
CreateWGL(hWnd);
app.Create();
// Main message loop:
for (;;) {
if (!ProcessWindowMessage()) {
break;
}
Input();
RECT rc;
GetClientRect(hWnd, &rc);
int w = rc.right - rc.left;
int h = rc.bottom - rc.top;
app.Update(w, h, 0);
app.Draw();
Sleep(1);
}
return 0;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_WGLTEST));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_WGLTEST);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance)
{
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, SW_SHOWNORMAL);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
SendMessage(hWnd, WM_CLOSE, 0, 0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code here...
EndPaint(hWnd, &ps);
break;
case WM_CLOSE:
app.Destroy();
DestroyWGL(hWnd);
DestroyWindow(hWnd);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
| 22.391304 | 158 | 0.706917 | yorung |
07a8b224b892810672128d8e7fba9fe9c84613f7 | 3,661 | cpp | C++ | searchcore/src/vespa/searchcore/proton/matching/match_loop_communicator.cpp | amahussein/vespa | 29d266ae1e5c95e25002b97822953fdd02b1451e | [
"Apache-2.0"
] | 1 | 2018-12-30T05:42:18.000Z | 2018-12-30T05:42:18.000Z | searchcore/src/vespa/searchcore/proton/matching/match_loop_communicator.cpp | amahussein/vespa | 29d266ae1e5c95e25002b97822953fdd02b1451e | [
"Apache-2.0"
] | 1 | 2021-03-31T22:24:20.000Z | 2021-03-31T22:24:20.000Z | searchcore/src/vespa/searchcore/proton/matching/match_loop_communicator.cpp | amahussein/vespa | 29d266ae1e5c95e25002b97822953fdd02b1451e | [
"Apache-2.0"
] | 1 | 2020-02-01T07:21:28.000Z | 2020-02-01T07:21:28.000Z | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "match_loop_communicator.h"
#include <vespa/vespalib/util/priority_queue.h>
namespace proton:: matching {
MatchLoopCommunicator::MatchLoopCommunicator(size_t threads, size_t topN)
: MatchLoopCommunicator(threads, topN, std::unique_ptr<IDiversifier>())
{}
MatchLoopCommunicator::MatchLoopCommunicator(size_t threads, size_t topN, std::unique_ptr<IDiversifier> diversifier)
: _best_dropped(),
_estimate_match_frequency(threads),
_selectBest(threads, topN, _best_dropped, std::move(diversifier)),
_rangeCover(threads, _best_dropped)
{}
MatchLoopCommunicator::~MatchLoopCommunicator() = default;
void
MatchLoopCommunicator::EstimateMatchFrequency::mingle()
{
double freqSum = 0.0;
for (size_t i = 0; i < size(); ++i) {
if (in(i).docs > 0) {
double h = in(i).hits;
double d = in(i).docs;
freqSum += h/d;
}
}
double freq = freqSum / size();
for (size_t i = 0; i < size(); ++i) {
out(i) = freq;
}
}
MatchLoopCommunicator::SelectBest::SelectBest(size_t n, size_t topN_in, BestDropped &best_dropped_in, std::unique_ptr<IDiversifier> diversifier)
: vespalib::Rendezvous<SortedHitSequence, Hits>(n),
topN(topN_in),
best_dropped(best_dropped_in),
_diversifier(std::move(diversifier))
{}
MatchLoopCommunicator::SelectBest::~SelectBest() = default;
template<typename Q, typename F>
void
MatchLoopCommunicator::SelectBest::mingle(Q &queue, F &&accept)
{
best_dropped.valid = false;
for (size_t picked = 0; picked < topN && !queue.empty(); ) {
uint32_t i = queue.front();
const Hit & hit = in(i).get();
if (accept(hit.first)) {
out(i).push_back(hit);
++picked;
} else if (!best_dropped.valid) {
best_dropped.valid = true;
best_dropped.score = hit.second;
}
in(i).next();
if (in(i).valid()) {
queue.adjust();
} else {
queue.pop_front();
}
}
}
void
MatchLoopCommunicator::SelectBest::mingle()
{
size_t est_out = (topN / size()) + 16;
vespalib::PriorityQueue<uint32_t, SelectCmp> queue(SelectCmp(*this));
for (size_t i = 0; i < size(); ++i) {
if (in(i).valid()) {
out(i).reserve(est_out);
queue.push(i);
}
}
if (_diversifier) {
mingle(queue, [diversifier=_diversifier.get()](uint32_t docId) { return diversifier->accepted(docId);});
} else {
mingle(queue, [](uint32_t) { return true;});
}
}
void
MatchLoopCommunicator::RangeCover::mingle()
{
size_t i = 0;
while (i < size() && (!in(i).first.isValid() || !in(i).second.isValid())) {
++i;
}
if (i < size()) {
RangePair result = in(i++);
for (; i < size(); ++i) {
if (in(i).first.isValid() && in(i).second.isValid()) {
result.first.low = std::min(result.first.low, in(i).first.low);
result.first.high = std::max(result.first.high, in(i).first.high);
result.second.low = std::min(result.second.low, in(i).second.low);
result.second.high = std::max(result.second.high, in(i).second.high);
}
}
if (best_dropped.valid) {
result.first.low = std::max(result.first.low, best_dropped.score);
result.first.high = std::max(result.first.low, result.first.high);
}
for (size_t j = 0; j < size(); ++j) {
out(j) = result;
}
}
}
}
| 32.114035 | 144 | 0.593007 | amahussein |
07ac87d095f48234a6849915afbc8c7e4e8c70db | 1,836 | cpp | C++ | alignment/algorithms/alignment/ExtendAlign.cpp | ggraham/blasr_libcpp | 4abef36585bbb677ebc4acb9d4e44e82331d59f7 | [
"RSA-MD"
] | 4 | 2015-07-03T11:59:54.000Z | 2018-05-17T00:03:22.000Z | alignment/algorithms/alignment/ExtendAlign.cpp | ggraham/blasr_libcpp | 4abef36585bbb677ebc4acb9d4e44e82331d59f7 | [
"RSA-MD"
] | 79 | 2015-06-29T18:07:21.000Z | 2018-09-19T13:38:39.000Z | alignment/algorithms/alignment/ExtendAlign.cpp | ggraham/blasr_libcpp | 4abef36585bbb677ebc4acb9d4e44e82331d59f7 | [
"RSA-MD"
] | 19 | 2015-06-23T08:43:29.000Z | 2021-04-28T18:37:47.000Z | #include <alignment/algorithms/alignment/ExtendAlign.hpp>
RCToIndex::RCToIndex()
{
qStart = 0;
tStart = 0;
band = middleCol = nCols = 0;
}
int RCToIndex::operator()(int r, int c, int &index)
{
//
// First do some error checking on the row and column to see if it
// is within the band.
//
if (r < qStart) {
return 0;
}
if (c < tStart) {
return 0;
}
r -= qStart;
c -= tStart;
if (std::abs(r - c) > band) {
return 0;
} // outside band range.
if (c < 0) {
return 0;
}
if (middleCol - (r - c) >= nCols) {
return 0;
}
index = (r * nCols) + (middleCol - (r - c));
return 1;
}
int BaseIndex::QNotAtSeqBoundary(int q) { return q != queryAlignLength; }
int BaseIndex::TNotAtSeqBoundary(int t) { return t != refAlignLength; }
int BaseIndex::QAlignLength() { return queryAlignLength; }
int BaseIndex::TAlignLength() { return refAlignLength; }
int ForwardIndex::QuerySeqPos(int q) { return queryPos + q; }
int ForwardIndex::RefSeqPos(int t) { return refPos + t; }
int ForwardIndex::GetQueryStartPos(int startQ, int endQ)
{
(void)(endQ);
return queryPos + startQ + 1;
}
int ForwardIndex::GetRefStartPos(int startT, int endT)
{
(void)(endT);
return refPos + startT + 1;
}
void ForwardIndex::OrderArrowVector(std::vector<Arrow> &mat) { reverse(mat.begin(), mat.end()); }
int ReverseIndex::QuerySeqPos(int q) { return queryPos - q; }
int ReverseIndex::RefSeqPos(int t) { return refPos - t; }
int ReverseIndex::GetQueryStartPos(int startQ, int endQ)
{
(void)(startQ);
return queryPos - (endQ - 1);
}
int ReverseIndex::GetRefStartPos(int startT, int endT)
{
(void)(startT);
return refPos - (endT - 1);
}
void ReverseIndex::OrderArrowVector(std::vector<Arrow> &mat) { (void)(mat); }
| 23.240506 | 97 | 0.622549 | ggraham |
07adb5ba8538638fde63be64640602a8c94246bc | 685 | cpp | C++ | Codes/CodeForces/A/938A.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | 3 | 2019-07-20T07:26:31.000Z | 2020-08-06T09:31:09.000Z | Codes/CodeForces/A/938A.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | null | null | null | Codes/CodeForces/A/938A.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | 4 | 2019-06-20T18:43:32.000Z | 2020-10-07T16:45:23.000Z | #include <bits/stdc++.h>
using namespace std;
class A938{
private:
int n;
int pos;
string s;
public:
bool isVowel(char c){
return (c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || c=='y');
}
void escape(){
int j=pos+1;
while(isVowel(s[j])){
j++;
}
pos = j;
}
A938(){
scanf("%d",&n);
cin>>s;
pos = 0;
while(pos<n){
printf("%c",s[pos]);
if(!isVowel(s[pos])){
pos++;
}else{
escape();
}
}
printf("\n");
}
~A938(){}
};
int main()
{
A938 a938;
return 0;
}
| 14.891304 | 74 | 0.351825 | fahimfarhan |
07b0343ec381a5f865f7373ac985c3dd1909dbbe | 1,258 | hpp | C++ | contrib/autoboost/autoboost/asio/detail/cstdint.hpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 87 | 2015-01-18T00:43:06.000Z | 2022-02-11T17:40:50.000Z | contrib/autoboost/autoboost/asio/detail/cstdint.hpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 274 | 2015-01-03T04:50:49.000Z | 2021-03-08T09:01:09.000Z | contrib/autoboost/autoboost/asio/detail/cstdint.hpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 15 | 2015-09-30T20:58:43.000Z | 2020-12-19T21:24:56.000Z | //
// detail/cstdint.hpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef AUTOBOOST_ASIO_DETAIL_CSTDINT_HPP
#define AUTOBOOST_ASIO_DETAIL_CSTDINT_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <autoboost/asio/detail/config.hpp>
#if defined(AUTOBOOST_ASIO_HAS_CSTDINT)
# include <cstdint>
#else // defined(AUTOBOOST_ASIO_HAS_CSTDINT)
# include <autoboost/cstdint.hpp>
#endif // defined(AUTOBOOST_ASIO_HAS_CSTDINT)
namespace autoboost {
namespace asio {
#if defined(AUTOBOOST_ASIO_HAS_CSTDINT)
using std::int16_t;
using std::uint16_t;
using std::int32_t;
using std::uint32_t;
using std::int64_t;
using std::uint64_t;
#else // defined(AUTOBOOST_ASIO_HAS_CSTDINT)
using autoboost::int16_t;
using autoboost::uint16_t;
using autoboost::int32_t;
using autoboost::uint32_t;
using autoboost::int64_t;
using autoboost::uint64_t;
#endif // defined(AUTOBOOST_ASIO_HAS_CSTDINT)
} // namespace asio
} // namespace autoboost
#endif // AUTOBOOST_ASIO_DETAIL_CSTDINT_HPP
| 25.673469 | 79 | 0.762321 | CaseyCarter |
07b0d35926409ab1270cf5db627937bb6d690ab4 | 2,991 | cpp | C++ | src/pd/fireball.cpp | mtribiere/Pixel-dungeon-CPP | ed930aaeefd1f08eed73ced928acae6e1fe34fa4 | [
"MIT"
] | null | null | null | src/pd/fireball.cpp | mtribiere/Pixel-dungeon-CPP | ed930aaeefd1f08eed73ced928acae6e1fe34fa4 | [
"MIT"
] | null | null | null | src/pd/fireball.cpp | mtribiere/Pixel-dungeon-CPP | ed930aaeefd1f08eed73ced928acae6e1fe34fa4 | [
"MIT"
] | null | null | null | #include "../engine/stdafx.h"
#include "fireball.h"
#include "../pd/define.h"
#include "../engine/util.h"
#include "../engine/game.h"
#include "../engine/pixelparticle.h"
float Flame::LIFESPAN = 1.0f;
float Flame::SPEED = -40.0f;
float Flame::ACC = -20.0f;
Flame::Flame()
{
init();
tag = "Flame";
}
void Flame::init()
{
texture(Assets::FIREBALL);
frame(Random::Int(0, 2) == 0 ? Fireball_FLAME1 : Fireball_FLAME2);
GameMath::PointFSet(&origin, width / 2, height / 2);
//origin.set(width / 2, height / 2);
GameMath::PointFSet(&acc, 0, ACC);
//acc.set(0, ACC);
}
void Flame::reset()
{
revive();
timeLeft = LIFESPAN;
GameMath::PointFSet(&speed, 0, SPEED);
//speed.set(0, SPEED);
}
void Flame::update()
{
Image::update();
if ((timeLeft -= Game::elapsed) <= 0)
{
kill();
}
else
{
float p = timeLeft / LIFESPAN;
GameMath::PointFSet(&scale, p);
//scale.set(p);
alpha(p > 0.8f ? (1 - p) * 5.0f : p * 1.25f);
}
}
void EmitterFactory1::emit(Emitter* emitter, int index, float x, float y)
{
Flame* p = (Flame*)emitter->recycle("Flame");
if (p == NULL)
{
p = (Flame*)emitter->add(new Flame());
}
p->reset();
p->x = x - p->width / 2;
p->y = y - p->height / 2;
}
Fireball::Fireball()
{
init();
}
void Fireball::createChildren()
{
_sparks = new Group();
add(_sparks);
_bLight = new Image(Assets::FIREBALL);
_bLight->frame(Fireball_BLIGHT);
GameMath::PointFSet(&_bLight->origin, _bLight->width / 2);
//bLight.origin.set( bLight.width / 2 );
_bLight->angularSpeed = -90;
add(_bLight);
_emitter = new Emitter();
_emitter->pour(new EmitterFactory1(), 0.1f);
add(_emitter);
_fLight = new Image(Assets::FIREBALL);
_fLight->frame(Fireball_FLIGHT);
GameMath::PointFSet(&_fLight->origin, _fLight->width / 2);
//_fLight->origin.set(_fLight.width / 2);
_fLight->angularSpeed = 360;
add(_fLight);
//
_bLight->tex->filter(Texture::LINEAR, Texture::LINEAR);
}
void Fireball::layout()
{
_bLight->x = _x - _bLight->width / 2;
_bLight->y = _y - _bLight->height / 2;
_emitter->pos(
_x - _bLight->width / 4,
_y - _bLight->height / 4,
_bLight->width / 2,
_bLight->height / 2);
_fLight->x = _x - _fLight->width / 2;
_fLight->y = _y - _fLight->height / 2;
}
void Fireball::update()
{
Component::update();
if (Random::Float(0, 1) < Game::elapsed)
{
PixelParticle* spark = (PixelParticle*)_sparks->recycle("Shrinking");
if (spark == NULL)
{
//spark = (PixelParticle*)_sparks->add(new Shrinking());
spark = new Shrinking();
}
spark->reset(_x, _y, ColorMath::random(COLOR, 0x66FF66), 2, Random::Float(0.5f, 1.0f));
GameMath::PointFSet(&spark->speed, Random::Float(-40, +40), Random::Float(-60, +20));
//spark->speed.set(
// Random::Float(-40, +40),
// Random::Float(-60, +20));
GameMath::PointFSet(&spark->acc, 0, 80);
//spark->acc.set(0, +80);
_sparks->add(spark);
}
} | 22.488722 | 90 | 0.598462 | mtribiere |
07b1511a2e57346c6ea7ccea6c9cefb6cda5eb0b | 2,880 | hpp | C++ | include/dtc/utility/lexical_cast.hpp | tsung-wei-huang/DtCraft | 80cc9e1195adc0026107814243401a1fc47b5be2 | [
"MIT"
] | 69 | 2019-03-16T20:13:26.000Z | 2022-03-24T14:12:19.000Z | include/dtc/utility/lexical_cast.hpp | Tsung-Wei/DtCraft | 80cc9e1195adc0026107814243401a1fc47b5be2 | [
"MIT"
] | 12 | 2017-12-02T05:38:30.000Z | 2019-02-08T11:16:12.000Z | include/dtc/utility/lexical_cast.hpp | Tsung-Wei/DtCraft | 80cc9e1195adc0026107814243401a1fc47b5be2 | [
"MIT"
] | 12 | 2019-04-13T16:27:29.000Z | 2022-01-07T14:42:46.000Z | /******************************************************************************
* *
* Copyright (c) 2018, Tsung-Wei Huang and Martin D. F. Wong, *
* University of Illinois at Urbana-Champaign (UIUC), IL, USA. *
* *
* All Rights Reserved. *
* *
* This program is free software. You can redistribute and/or modify *
* it in accordance with the terms of the accompanying license agreement. *
* See LICENSE in the top-level directory for details. *
* *
******************************************************************************/
#ifndef DTC_UTILITY_LEXICAL_CAST_HPP_
#define DTC_UTILITY_LEXICAL_CAST_HPP_
namespace dtc::lexical_cast_impl {
template <typename T>
struct Converter;
// Numeric to string
template <>
struct Converter<std::string> {
static auto convert(auto&& from) {
return std::to_string(from);
}
};
template <>
struct Converter<int> {
static auto convert(std::string_view from) {
return std::atoi(from.data());
}
};
template <>
struct Converter<long> {
static auto convert(std::string_view from) {
return std::atol(from.data());
}
};
template <>
struct Converter<long long> {
static auto convert(std::string_view from) {
return std::atoll(from.data());
}
};
template <>
struct Converter<unsigned long> {
static auto convert(std::string_view from) {
return std::strtoul(from.data(), nullptr, 10);
}
};
template <>
struct Converter<unsigned long long> {
static auto convert(std::string_view from) {
return std::strtoull(from.data(), nullptr, 10);
}
};
template <>
struct Converter<float> {
static auto convert(std::string_view from) {
return std::strtof(from.data(), nullptr);
}
};
template <>
struct Converter<double> {
static auto convert(std::string_view from) {
return std::strtod(from.data(), nullptr);
}
};
template <>
struct Converter<long double> {
static auto convert(std::string_view from) {
return std::strtold(from.data(), nullptr);
}
};
}; // end of namespace dtc::lexical_cast_details. ------------------------------------------------
namespace dtc {
template <typename To, typename From>
auto lexical_cast(From&& from) {
using T = std::decay_t<To>;
using F = std::decay_t<From>;
if constexpr (std::is_same_v<T, F>) {
return from;
}
else {
return lexical_cast_impl::Converter<T>::convert(from);
}
}
}; // End of namespace dtc. ---------------------------------------------------------------------
#endif
| 26.666667 | 99 | 0.514236 | tsung-wei-huang |
07b1accc2b5f84a11e6493c4eb3ba02e445b28f1 | 379 | cpp | C++ | problem solving/electronics-shop.cpp | blog-a1/hackeRRank | 72923ee08c8759bd5a10ba6c390b6755fe2bd2e2 | [
"MIT"
] | 1 | 2021-01-13T11:52:27.000Z | 2021-01-13T11:52:27.000Z | problem solving/electronics-shop.cpp | blog-a1/hackeRRank | 72923ee08c8759bd5a10ba6c390b6755fe2bd2e2 | [
"MIT"
] | null | null | null | problem solving/electronics-shop.cpp | blog-a1/hackeRRank | 72923ee08c8759bd5a10ba6c390b6755fe2bd2e2 | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
int main()
{
int b,n,m,c=-1;cin>>b>>n>>m;int a[n],d[m];
for(int i=0;i<n;i++) cin>>a[i];
for(int i=0;i<m;i++) cin>>d[i];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if((a[i]+d[j])<=b&&(a[i]+d[j])>c)
c=a[i]+d[j];
cout<<c<<endl;
return 0;
} | 27.071429 | 47 | 0.387863 | blog-a1 |
07bb133c50e133d17bddf58d15a7b25f9eb6fb7a | 6,886 | hpp | C++ | library/include/slonczewski2.hpp | xfong/sycl | 405397e7bd030d104c5c88f403a617b6e8c3429a | [
"MIT"
] | 1 | 2021-06-15T02:42:29.000Z | 2021-06-15T02:42:29.000Z | library/include/slonczewski2.hpp | xfong/sycl | 405397e7bd030d104c5c88f403a617b6e8c3429a | [
"MIT"
] | null | null | null | library/include/slonczewski2.hpp | xfong/sycl | 405397e7bd030d104c5c88f403a617b6e8c3429a | [
"MIT"
] | null | null | null | #ifndef RUNTIME_INCLUDE_SYCL_SYCL_HPP_
#define RUNTIME_INCLUDE_SYCL_SYCL_HPP_
#include <CL/sycl.hpp>
namespace sycl = cl::sycl;
#endif // RUNTIME_INCLUDE_SYCL_SYCL_HPP_
#include "amul.hpp"
#include "constants.hpp"
// Original implementation by Mykola Dvornik for mumax2
// Modified for mumax3 by Arne Vansteenkiste, 2013, 2016
template <typename dataT>
class addslonczewskitorque2_kernel {
public:
using read_accessor =
sycl::accessor<dataT, 1, sycl::access::mode::read, sycl::access::target::global_buffer>;
using write_accessor =
sycl::accessor<dataT, 1, sycl::access::mode::read_write, sycl::access::target::global_buffer>;
addslonczewskitorque2_kernel(write_accessor tXPtr, write_accessor tYPtr, write_accessor tZPtr,
read_accessor mxPtr, read_accessor myPtr, read_accessor mzPtr,
read_accessor MsPtr, dataT Ms_mul,
read_accessor jzPtr, dataT jz_mul,
read_accessor pxPtr, dataT px_mul,
read_accessor pyPtr, dataT py_mul,
read_accessor pzPtr, dataT pz_mul,
read_accessor alphaPtr, dataT alpha_mul,
read_accessor polPtr, dataT pol_mul,
read_accessor lambdaPtr, dataT lambda_mul,
read_accessor epsPrimePtr, dataT epsPrime_mul,
read_accessor fltPtr, dataT flt_mul,
size_t N)
: tx(tXPtr),
ty(tYPtr),
tz(tZPtr),
mx_(mxPtr),
my_(myPtr),
mz_(mzPtr),
Ms_(MsPtr),
Ms_mul(Ms_mul),
jz_(jzPtr),
jz_mul(jz_mul),
px_(pxPtr),
px_mul(px_mul),
py_(pyPtr),
py_mul(py_mul),
pz_(pzPtr),
pz_mul(pz_mul),
alpha_(alphaPtr),
alpha_mul(alpha_mul),
pol_(polPtr),
pol_mul(pol_mul),
lambda_(lambdaPtr),
lambda_mul(lambda_mul),
epsPrime_(epsPrimePtr),
epsPrime_mul(epsPrime_mul),
flt_(fltPtr),
flt_mul(flt_mul),
N(N) {}
void operator()(sycl::nd_item<1> item) {
size_t stride = item.get_global_range(0);
for (size_t gid = item.get_global_linear_id(); gid < N; gid += stride) {
dataT J = amul(jz_, jz_mul, gid);
dataT Ms = amul(Ms_, Ms_mul, gid);
if (J == (dataT)(0.0) || Ms == (dataT)(0.0)) {
return;
}
sycl::vec<dataT, 3> m = make_vec3(mx_[gid], my_[gid], mz_[gid]);
sycl::vec<dataT, 3> p = normalized(vmul(px_, py_, pz_, px_mul, py_mul, pz_mul, gid));
dataT alpha = amul(alpha_, alpha_mul, gid);
dataT flt = amul(flt_, flt_mul, gid);
dataT pol = amul(pol_, pol_mul, gid);
dataT lambda = amul(lambda_, lambda_mul, gid);
dataT epsilonPrime = amul(epsPrime_, epsPrime_mul, gid);
dataT beta = (HBAR / QE) * (J / (flt*Ms) );
dataT lambda2 = lambda * lambda;
dataT epsilon = pol * lambda2 / ((lambda2 + (dataT)(1.0)) + (lambda2 - (dataT)(1.0)) * sycl::dot(p, m));
dataT A = beta * epsilon;
dataT B = beta * epsilonPrime;
dataT gilb = (dataT)(1.0) / ((dataT)(1.0) + alpha * alpha);
dataT mxpxmFac = gilb * (A + alpha * B);
dataT pxmFac = gilb * (B - alpha * A);
sycl::vec<dataT, 3> pxm = sycl::cross(p, m);
sycl::vec<dataT, 3> mxpxm = sycl::cross(m, pxm);
tx[gid] += mxpxmFac * mxpxm.x() + pxmFac * pxm.x();
ty[gid] += mxpxmFac * mxpxm.y() + pxmFac * pxm.y();
tz[gid] += mxpxmFac * mxpxm.z() + pxmFac * pxm.z();
}
}
private:
write_accessor tx;
write_accessor ty;
write_accessor tz;
read_accessor mx_;
read_accessor my_;
read_accessor mz_;
read_accessor jz_;
dataT jz_mul;
read_accessor px_;
dataT px_mul;
read_accessor py_;
dataT py_mul;
read_accessor pz_;
dataT jz_mul;
read_accessor alpha_;
dataT alpha_mul;
read_accessor pol_;
dataT pol_mul;
read_accessor lambda_;
dataT lambda_mul;
read_accessor epsPrime_;
dataT epsPrime_mul;
read_accessor flt_;
dataT flt_mul;
size_t N;
};
template <typename dataT>
void addslonczewskitorque2_async(sycl::queue funcQueue,
sycl::buffer<dataT, 1> *tx, sycl::buffer<dataT, 1> *ty, sycl::buffer<dataT, 1> *tz,
sycl::buffer<dataT, 1> *mx, sycl::buffer<dataT, 1> *my, sycl::buffer<dataT, 1> *mz,
sycl::buffer<dataT, 1> *Ms, dataT Ms_mul,
sycl::buffer<dataT, 1> *jz, dataT jz_mul,
sycl::buffer<dataT, 1> *px, dataT px_mul,
sycl::buffer<dataT, 1> *py, dataT py_mul,
sycl::buffer<dataT, 1> *pz, dataT pz_mul,
sycl::buffer<dataT, 1> *alpha, dataT alpha_mul,
sycl::buffer<dataT, 1> *pol, dataT pol_mul,
sycl::buffer<dataT, 1> *lambda, dataT lambda_mul,
sycl::buffer<dataT, 1> *epsPrime, dataT epsPrime_mul,
sycl::buffer<dataT, 1> *flt, dataT flt_mul,
size_t N,
size_t gsize,
size_t lsize) {
funcQueue.submit([&] (sycl::handler& cgh) {
auto tx_acc = tx->template get_access<sycl::access::mode::read_write>(cgh);
auto ty_acc = ty->template get_access<sycl::access::mode::read_write>(cgh);
auto tz_acc = tz->template get_access<sycl::access::mode::read_write>(cgh);
auto mx_acc = mx->template get_access<sycl::access::mode::read>(cgh);
auto my_acc = my->template get_access<sycl::access::mode::read>(cgh);
auto mz_acc = mz->template get_access<sycl::access::mode::read>(cgh);
auto Ms_acc = Ms->template get_access<sycl::access::mode::read>(cgh);
auto jz_acc = jz->template get_access<sycl::access::mode::read>(cgh);
auto px_acc = px->template get_access<sycl::access::mode::read>(cgh);
auto py_acc = py->template get_access<sycl::access::mode::read>(cgh);
auto pz_acc = pz->template get_access<sycl::access::mode::read>(cgh);
auto alpha_acc = alpha_->template get_access<sycl::access::mode::read>(cgh);
auto pol_acc = pol->template get_access<sycl::access::mode::read>(cgh);
auto lambda_acc = lambda->template get_access<sycl::access::mode::read>(cgh);
auto epsPrime_acc = epsPrime->template get_access<sycl::access::mode::read>(cgh);
auto flt_acc = flt->template get_access<sycl::access::mode::read>(cgh);
cgh.parallel_for(sycl::nd_range<1>(sycl::range<1>(gsize),
sycl::range<1>(lsize)),
addslonczewskitorque2_kernel<dataT>(tx_acc, ty_acc, tz_acc,
mx_acc, my_acc, mz_acc,
Ms_acc, Ms_mul,
jz_acc, jz_mul,
px_acc, px_mul,
py_acc, py_mul,
pz_acc, pz_mul,
alpha_acc, alpha_mul,
pol_acc, pol_mul,
lambda_acc, lambda_mul,
epsPrime_acc, epsPrime_mul,
flt_acc, flt_mul,
N));
});
}
| 38.685393 | 108 | 0.60456 | xfong |
07bbf1c6d87564eb8960c83dc03bb998058464cb | 5,305 | hpp | C++ | src/planning/recordreplay_planner_node/include/recordreplay_planner_node/recordreplay_planner_node.hpp | jiangtaojiang/AutowareAuto | 579bd5cec65859779d215c28c468b06de809749b | [
"Apache-2.0"
] | 4 | 2020-12-04T00:38:42.000Z | 2022-02-24T05:48:58.000Z | src/planning/recordreplay_planner_node/include/recordreplay_planner_node/recordreplay_planner_node.hpp | jiangtaojiang/AutowareAuto | 579bd5cec65859779d215c28c468b06de809749b | [
"Apache-2.0"
] | null | null | null | src/planning/recordreplay_planner_node/include/recordreplay_planner_node/recordreplay_planner_node.hpp | jiangtaojiang/AutowareAuto | 579bd5cec65859779d215c28c468b06de809749b | [
"Apache-2.0"
] | 1 | 2020-12-04T00:38:56.000Z | 2020-12-04T00:38:56.000Z | // Copyright 2020 Embotech AG, Zurich, Switzerland, inspired by Christopher Ho's mpc code
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RECORDREPLAY_PLANNER_NODE__RECORDREPLAY_PLANNER_NODE_HPP_
#define RECORDREPLAY_PLANNER_NODE__RECORDREPLAY_PLANNER_NODE_HPP_
#include <tf2_ros/transform_listener.h>
#include <tf2_ros/buffer.h>
#include <recordreplay_planner_node/visibility_control.hpp>
#include <recordreplay_planner/recordreplay_planner.hpp>
#include <recordreplay_planner_actions/action/record_trajectory.hpp>
#include <recordreplay_planner_actions/action/replay_trajectory.hpp>
#include <autoware_auto_msgs/msg/bounding_box_array.hpp>
#include <autoware_auto_msgs/msg/trajectory.hpp>
#include <autoware_auto_msgs/msg/vehicle_kinematic_state.hpp>
#include <geometry_msgs/msg/transform_stamped.hpp>
#include <motion_common/motion_common.hpp>
#include <motion_common/config.hpp>
#include <common/types.hpp>
#include <rclcpp_action/rclcpp_action.hpp>
#include <rclcpp/rclcpp.hpp>
#include <string>
#include <memory>
using autoware::common::types::float64_t;
namespace motion
{
namespace planning
{
namespace recordreplay_planner_node
{
using PlannerPtr = std::unique_ptr<motion::planning::recordreplay_planner::RecordReplayPlanner>;
using autoware_auto_msgs::msg::BoundingBoxArray;
using autoware_auto_msgs::msg::Trajectory;
using recordreplay_planner_actions::action::RecordTrajectory;
using recordreplay_planner_actions::action::ReplayTrajectory;
using State = autoware_auto_msgs::msg::VehicleKinematicState;
using Transform = geometry_msgs::msg::TransformStamped;
using motion::motion_common::VehicleConfig;
using motion::motion_common::Real;
class RECORDREPLAY_PLANNER_NODE_PUBLIC RecordReplayPlannerNode : public rclcpp::Node
{
public:
using GoalHandleRecordTrajectory = rclcpp_action::ServerGoalHandle<RecordTrajectory>;
using GoalHandleReplayTrajectory = rclcpp_action::ServerGoalHandle<ReplayTrajectory>;
/// Parameter file constructor
explicit RecordReplayPlannerNode(const rclcpp::NodeOptions & node_options);
protected:
rclcpp_action::Server<RecordTrajectory>::SharedPtr m_recordserver;
rclcpp_action::Server<ReplayTrajectory>::SharedPtr m_replayserver;
std::shared_ptr<GoalHandleRecordTrajectory> m_recordgoalhandle{nullptr};
std::shared_ptr<GoalHandleReplayTrajectory> m_replaygoalhandle{nullptr};
rclcpp::Subscription<State>::SharedPtr m_ego_sub{};
rclcpp::Subscription<BoundingBoxArray>::SharedPtr m_boundingbox_sub{};
rclcpp::Publisher<Trajectory>::SharedPtr m_trajectory_pub{};
rclcpp::Publisher<BoundingBoxArray>::SharedPtr m_trajectory_boundingbox_pub{};
rclcpp::Publisher<BoundingBoxArray>::SharedPtr m_collison_boundingbox_pub{};
rclcpp::Publisher<BoundingBoxArray>::SharedPtr m_transformed_boundingbox_pub{};
PlannerPtr m_planner{nullptr};
private:
RECORDREPLAY_PLANNER_NODE_LOCAL void init(
const std::string & ego_topic,
const std::string & trajectory_topic,
const std::string & bounding_boxes_topic,
const VehicleConfig & vehicle_param,
const float64_t heading_weight,
const float64_t min_record_distance);
RECORDREPLAY_PLANNER_NODE_LOCAL void on_ego(const State::SharedPtr & msg);
RECORDREPLAY_PLANNER_NODE_LOCAL void on_bounding_box(const BoundingBoxArray::SharedPtr & msg);
// TODO(s.me) there does not seem to be a RecordTrajectory::SharedPtr? Also
// the return types need to be changed to the rclcpp_action types once the package
// is available.
RECORDREPLAY_PLANNER_NODE_LOCAL rclcpp_action::GoalResponse record_handle_goal(
const rclcpp_action::GoalUUID & uuid,
const std::shared_ptr<const RecordTrajectory::Goal> goal);
RECORDREPLAY_PLANNER_NODE_LOCAL rclcpp_action::CancelResponse record_handle_cancel(
const std::shared_ptr<GoalHandleRecordTrajectory> goal_handle);
RECORDREPLAY_PLANNER_NODE_LOCAL void record_handle_accepted(
const std::shared_ptr<GoalHandleRecordTrajectory> goal_handle);
RECORDREPLAY_PLANNER_NODE_LOCAL rclcpp_action::GoalResponse replay_handle_goal(
const rclcpp_action::GoalUUID & uuid,
const std::shared_ptr<const ReplayTrajectory::Goal> goal);
RECORDREPLAY_PLANNER_NODE_LOCAL rclcpp_action::CancelResponse replay_handle_cancel(
const std::shared_ptr<GoalHandleReplayTrajectory> goal_handle);
RECORDREPLAY_PLANNER_NODE_LOCAL void replay_handle_accepted(
const std::shared_ptr<GoalHandleReplayTrajectory> goal_handle);
std::string m_odom_frame_id{};
std::shared_ptr<tf2_ros::Buffer> tf_buffer_;
std::shared_ptr<tf2_ros::TransformListener> tf_listener_;
bool m_enable_obstacle_detection{true};
}; // class RecordReplayPlannerNode
} // namespace recordreplay_planner_node
} // namespace planning
} // namespace motion
#endif // RECORDREPLAY_PLANNER_NODE__RECORDREPLAY_PLANNER_NODE_HPP_
| 43.483607 | 96 | 0.816777 | jiangtaojiang |
07be85a0d07b42bcce7185e3727e05f66421b709 | 5,501 | cpp | C++ | test/json_parser_tests.cpp | Malibushko/yatgbotlib | a5109c36c9387aef0e6d15e303d2f3753eef9aac | [
"MIT"
] | 3 | 2020-04-05T23:51:09.000Z | 2020-08-14T07:24:45.000Z | test/json_parser_tests.cpp | Malibushko/yatgbotlib | a5109c36c9387aef0e6d15e303d2f3753eef9aac | [
"MIT"
] | 1 | 2020-07-24T19:46:28.000Z | 2020-07-31T14:49:28.000Z | test/json_parser_tests.cpp | Malibushko/yatgbotlib | a5109c36c9387aef0e6d15e303d2f3753eef9aac | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <memory>
#include "telegram_bot.h"
using namespace telegram;
struct Small {
declare_struct
declare_field(bool,test);
};
TEST(JsonParser,to_json_small_structure) {
std::string json = JsonParser::i().toJson(Small{false});
std::string expected_json = "{\"test\":false}";
EXPECT_EQ(expected_json,json);
}
struct Large {
declare_struct
declare_field(bool,b1);
declare_field(bool,b2);
declare_field(bool,b3);
declare_field(bool,b4);
declare_field(bool,b5);
declare_field(bool,b6);
declare_field(bool,b7);
declare_field(bool,b8);
declare_field(bool,b9);
declare_field(bool,b10);
declare_field(bool,b11);
declare_field(bool,b12);
declare_field(bool,b13);
declare_field(bool,b14);
declare_field(bool,b15);
declare_field(bool,b16);
declare_field(bool,b17);
declare_field(bool,b18);
declare_field(bool,b19);
declare_field(bool,b20);
declare_field(bool,b21);
declare_field(bool,b22);
declare_field(bool,b23);
declare_field(bool,b24);
declare_field(bool,b25);
Large() = default;
};
TEST(JsonParser,to_json_large_structure) {
std::string json = JsonParser::i().toJson(Large{});
std::string expected_json = "{"
"\"b1\":false,"
"\"b2\":false,"
"\"b3\":false,"
"\"b4\":false,"
"\"b5\":false,"
"\"b6\":false,"
"\"b7\":false,"
"\"b8\":false,"
"\"b9\":false,"
"\"b10\":false,"
"\"b11\":false,"
"\"b12\":false,"
"\"b13\":false,"
"\"b14\":false,"
"\"b15\":false,"
"\"b16\":false,"
"\"b17\":false,"
"\"b18\":false,"
"\"b19\":false,"
"\"b20\":false,"
"\"b21\":false,"
"\"b22\":false,"
"\"b23\":false,"
"\"b24\":false,"
"\"b25\":false"
"}";
EXPECT_EQ(expected_json,json);
}
struct Array {
declare_struct
declare_field(std::vector<int>,data);
};
TEST(JsonParser,to_json_array_type) {
Array arr;
arr.data = {1,2,3,4,5};
std::string json = JsonParser::i().toJson(arr);
std::string expected_json = "{\"data\":[1,2,3,4,5]}";
EXPECT_EQ(expected_json,json);
}
struct ComplexArray {
declare_struct
declare_field(std::vector<Small>,data);
};
TEST(JsonParser,to_json_complex_array_type) {
ComplexArray arr;
arr.data = {{false},{true},{false}};
std::string json = JsonParser::i().toJson(arr);
std::string expected_json = "{\"data\":[{\"test\":false},{\"test\":true},{\"test\":false}]}";
EXPECT_EQ(expected_json,json);
}
struct SharedPtr {
declare_struct
declare_field(std::unique_ptr<int>,data);
};
TEST(JsonParse,to_json_unique_ptr) {
SharedPtr ptr;
ptr.data = std::make_unique<int>(5);
std::string json = JsonParser::i().toJson(ptr);
std::string expected_json = "{\"data\":5}";
EXPECT_EQ(expected_json,json);
}
struct Variant {
using variant_type = std::variant<std::string,int>;
declare_struct
declare_field(variant_type,data);
};
TEST(JsonParser,to_json_variant) {
Variant test1;
Variant test2;
test1.data = 5;
test2.data = "Test";
std::string json_1 = JsonParser::i().toJson(test1);
std::string expected_json_1 = "{\"data\":5}";
std::string json_2 = JsonParser::i().toJson(test2);
std::string expected_json_2 = "{\"data\":\"Test\"}";
EXPECT_EQ(expected_json_1,json_1);
EXPECT_EQ(expected_json_2,json_2);
}
struct Matrix {
declare_struct
declare_field(std::vector<std::vector<int>>,data);
};
TEST(JsonParser,to_json_2darray) {
Matrix m{
{{1,2,3},
{4,5,6},
{7,8,9}}
};
std::string json = JsonParser::i().toJson(m);
std::string expected_json = "{\"data\":[[1,2,3],[4,5,6],[7,8,9]]}";
EXPECT_EQ(expected_json,json);
}
TEST(JsonParser,forward_reverse_parse) {
Small m{true};
std::string json = JsonParser::i().toJson(m);
Small after = JsonParser::i().fromJson<Small>(json);
EXPECT_EQ(m.test,after.test);
}
TEST(JsonParser,parse_array) {
ComplexArray arr = JsonParser::i().fromJson<ComplexArray>({"{\"data\":[{\"test\":false},{\"test\":true},{\"test\":false}]}"});
auto expected = std::vector<Small>{{false},{true},{false}};
if (arr.data.size() != expected.size()) {
ASSERT_TRUE(false);
}
for (size_t i = 0; i < arr.data.size();++i)
if (arr.data[i].test != expected[i].test) {
ASSERT_TRUE(false);
break;
}
ASSERT_TRUE(true);
}
TEST(JsonParse,parse_unique_ptr) {
SharedPtr ptr = JsonParser::i().fromJson<SharedPtr>({"{\"data\":5}"});
if (!ptr.data) {
ASSERT_TRUE(false);
}
EXPECT_EQ((*ptr.data),5);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 30.561111 | 130 | 0.52954 | Malibushko |
07bf4da729fee2acecdbde117105c397b5a6f1e3 | 108 | cc | C++ | 15/17/17.cc | williamgherman/cpp-solutions | cf947b3b8f49fa3071fbee96f522a4228e4207b8 | [
"BSD-Source-Code"
] | 5 | 2019-08-01T07:52:27.000Z | 2022-03-27T08:09:35.000Z | 15/17/17.cc | williamgherman/cpp-solutions | cf947b3b8f49fa3071fbee96f522a4228e4207b8 | [
"BSD-Source-Code"
] | 1 | 2020-10-03T17:29:59.000Z | 2020-11-17T10:03:10.000Z | 15/17/17.cc | williamgherman/cpp-solutions | cf947b3b8f49fa3071fbee96f522a4228e4207b8 | [
"BSD-Source-Code"
] | 6 | 2019-08-24T08:55:56.000Z | 2022-02-09T08:41:44.000Z | #include <iostream>
#include "quote.h"
int main()
{
Disc_quote *dq = new Disc_quote();
return 0;
}
| 12 | 38 | 0.62037 | williamgherman |
07bfa487955b94af69270d30843ef63cdab3b98c | 565 | hpp | C++ | include/render_objects/materials.hpp | Adanos020/ErupTrace | 2d359c4d53e758299e8b2d476d945fe2dd2f1c2d | [
"MIT"
] | null | null | null | include/render_objects/materials.hpp | Adanos020/ErupTrace | 2d359c4d53e758299e8b2d476d945fe2dd2f1c2d | [
"MIT"
] | null | null | null | include/render_objects/materials.hpp | Adanos020/ErupTrace | 2d359c4d53e758299e8b2d476d945fe2dd2f1c2d | [
"MIT"
] | null | null | null | #pragma once
#include <render_objects/textures.hpp>
#include <util/numeric.hpp>
enum class material_type
{
none,
dielectric,
diffuse,
emit_light,
reflect,
};
struct material
{
material_type type;
array_index index;
invalidable_array_index normals_index = -1;
};
struct dielectric_material
{
float refractive_index;
texture albedo;
};
struct diffuse_material
{
texture albedo;
};
struct emit_light_material
{
texture emit;
float intensity;
};
struct reflect_material
{
float fuzz;
texture albedo;
}; | 13.139535 | 47 | 0.699115 | Adanos020 |
07bfa6f58fb68fda020022bc25a05be5ec795fdd | 3,232 | cpp | C++ | src/plugins/snails/certificateverifier.cpp | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 120 | 2015-01-22T14:10:39.000Z | 2021-11-25T12:57:16.000Z | src/plugins/snails/certificateverifier.cpp | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 8 | 2015-02-07T19:38:19.000Z | 2017-11-30T20:18:28.000Z | src/plugins/snails/certificateverifier.cpp | Maledictus/leechcraft | 79ec64824de11780b8e8bdfd5d8a2f3514158b12 | [
"BSL-1.0"
] | 33 | 2015-02-07T16:59:55.000Z | 2021-10-12T00:36:40.000Z | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
**********************************************************************/
#include "certificateverifier.h"
#include <QSslCertificate>
#include <QSslError>
#include <QtDebug>
#include <vmime/security/cert/certificateExpiredException.hpp>
#include <vmime/security/cert/certificateNotYetValidException.hpp>
#include <vmime/security/cert/serverIdentityException.hpp>
#include "vmimeconversions.h"
namespace LC
{
namespace Snails
{
void CertificateVerifier::verify (const vmime::shared_ptr<vmime::security::cert::certificateChain>& chain,
const vmime::string& host)
{
namespace vsc = vmime::security::cert;
QList<QSslCertificate> qtChain;
for (size_t i = 0; i < chain->getCount (); ++i)
{
const auto& item = chain->getAt (i);
const auto& subcerts = ToSslCerts (item);
if (subcerts.size () != 1)
{
qWarning () << Q_FUNC_INFO
<< "unexpected certificates count for certificate type"
<< item->getType ().c_str ()
<< ", got"
<< subcerts.size ()
<< "certificates";
throw vsc::unsupportedCertificateTypeException { "unexpected certificates counts" };
}
qtChain << subcerts.at (0);
}
const auto& errs = QSslCertificate::verify (qtChain, QString::fromStdString (host));
if (errs.isEmpty ())
return;
qWarning () << Q_FUNC_INFO
<< errs;
for (const auto& error : errs)
switch (error.error ())
{
case QSslError::CertificateExpired:
throw vsc::certificateExpiredException {};
case QSslError::CertificateNotYetValid:
throw vsc::certificateNotYetValidException {};
case QSslError::HostNameMismatch:
throw vsc::serverIdentityException {};
case QSslError::UnableToDecryptCertificateSignature:
case QSslError::InvalidNotAfterField:
case QSslError::InvalidNotBeforeField:
case QSslError::CertificateSignatureFailed:
case QSslError::PathLengthExceeded:
case QSslError::UnspecifiedError:
throw vsc::unsupportedCertificateTypeException { "incorrect format" };
case QSslError::UnableToGetIssuerCertificate:
case QSslError::UnableToGetLocalIssuerCertificate:
case QSslError::UnableToDecodeIssuerPublicKey:
case QSslError::UnableToVerifyFirstCertificate:
case QSslError::SubjectIssuerMismatch:
case QSslError::AuthorityIssuerSerialNumberMismatch:
throw vsc::certificateIssuerVerificationException {};
case QSslError::SelfSignedCertificate:
case QSslError::SelfSignedCertificateInChain:
case QSslError::CertificateRevoked:
case QSslError::InvalidCaCertificate:
case QSslError::InvalidPurpose:
case QSslError::CertificateUntrusted:
case QSslError::CertificateRejected:
case QSslError::NoPeerCertificate:
case QSslError::CertificateBlacklisted:
throw vsc::certificateNotTrustedException {};
case QSslError::NoError:
case QSslError::NoSslSupport:
break;
}
throw vsc::certificateException { "other certificate error" };
}
}
}
| 33.666667 | 107 | 0.70854 | Maledictus |
07c26fcc5a14e25d18906596c898060bb1409009 | 171 | cpp | C++ | UVa 12502 three families/sample/12502 - Three Families.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2020-11-24T03:17:21.000Z | 2020-11-24T03:17:21.000Z | UVa 12502 three families/sample/12502 - Three Families.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | null | null | null | UVa 12502 three families/sample/12502 - Three Families.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2021-04-11T16:22:31.000Z | 2021-04-11T16:22:31.000Z | #include <stdio.h>
int main() {
int x, y, z;
scanf("%*d");
while(scanf("%d %d %d", &x ,&y, &z) == 3)
printf("%d\n", z*(2*x-y)/(x+y));
return 0;
}
| 17.1 | 45 | 0.409357 | tadvi |
07c332a9ae226d86b1e4bd084ebfb7c05934abd2 | 3,769 | hpp | C++ | core/unit_test/TestCompilerMacros.hpp | Char-Aznable/kokkos | 2983b80d9aeafabb81f2c8c1c5a49b40cc0856cb | [
"BSD-3-Clause"
] | 2 | 2019-12-18T20:37:06.000Z | 2020-04-07T00:44:39.000Z | core/unit_test/TestCompilerMacros.hpp | Char-Aznable/kokkos | 2983b80d9aeafabb81f2c8c1c5a49b40cc0856cb | [
"BSD-3-Clause"
] | 1 | 2019-09-25T15:41:23.000Z | 2019-09-25T15:41:23.000Z | core/unit_test/TestCompilerMacros.hpp | Char-Aznable/kokkos | 2983b80d9aeafabb81f2c8c1c5a49b40cc0856cb | [
"BSD-3-Clause"
] | 2 | 2020-04-01T19:16:16.000Z | 2022-02-09T21:45:19.000Z | /*
//@HEADER
// ************************************************************************
//
// Kokkos v. 2.0
// Copyright (2014) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// 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 Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#include <Kokkos_Core.hpp>
#if defined(KOKKOS_ENABLE_CUDA) && \
( !defined(KOKKOS_ENABLE_CUDA_LAMBDA) || \
( ( defined(KOKKOS_ENABLE_SERIAL) || defined(KOKKOS_ENABLE_OPENMP) ) && \
( (CUDA_VERSION < 8000) && defined( __NVCC__ ))))
#if defined(KOKKOS_ENABLE_CXX11_DISPATCH_LAMBDA)
#error "Macro bug: KOKKOS_ENABLE_CXX11_DISPATCH_LAMBDA shouldn't be defined"
#endif
#else
#if !defined(KOKKOS_ENABLE_CXX11_DISPATCH_LAMBDA)
#error "Macro bug: KOKKOS_ENABLE_CXX11_DISPATCH_LAMBDA should be defined"
#endif
#endif
#define KOKKOS_PRAGMA_UNROLL(a)
namespace TestCompilerMacros {
template< class DEVICE_TYPE >
struct AddFunctor {
typedef DEVICE_TYPE execution_space;
typedef typename Kokkos::View< int**, execution_space > type;
type a, b;
int length;
AddFunctor( type a_, type b_ ) : a( a_ ), b( b_ ), length( a.extent(1) ) {}
KOKKOS_INLINE_FUNCTION
void operator()( int i ) const {
#ifdef KOKKOS_ENABLE_PRAGMA_UNROLL
#pragma unroll
#endif
#ifdef KOKKOS_ENABLE_PRAGMA_IVDEP
#pragma ivdep
#endif
#ifdef KOKKOS_ENABLE_PRAGMA_VECTOR
#pragma vector always
#endif
#ifdef KOKKOS_ENABLE_PRAGMA_LOOPCOUNT
#pragma loop count(128)
#endif
#ifndef KOKKOS_DEBUG
#ifdef KOKKOS_ENABLE_PRAGMA_SIMD
#pragma simd
#endif
#endif
for ( int j = 0; j < length; j++ ) {
a( i, j ) += b( i, j );
}
}
};
template< class DeviceType >
bool Test() {
typedef typename Kokkos::View< int**, DeviceType > type;
type a( "A", 1024, 128 );
type b( "B", 1024, 128 );
AddFunctor< DeviceType > f( a, b );
Kokkos::parallel_for( 1024, f );
DeviceType().fence();
return true;
}
} // namespace TestCompilerMacros
namespace Test {
TEST_F( TEST_CATEGORY, compiler_macros )
{
ASSERT_TRUE( ( TestCompilerMacros::Test< TEST_EXECSPACE >() ) );
}
}
| 31.940678 | 80 | 0.69541 | Char-Aznable |
07c5e6f0c6141c6e72a76afe7a9dfdac39b9ca46 | 545 | cpp | C++ | PrimerTest/PrimerTest/ch10/ex10_17.cpp | silence0201/C-Plus-Study | ad013f093f275620dee892033e5152083b10f2fc | [
"MIT"
] | 3,366 | 2015-03-27T10:10:24.000Z | 2022-03-31T15:46:34.000Z | PrimerTest/PrimerTest/ch10/ex10_17.cpp | silence0201/C-Plus-Study | ad013f093f275620dee892033e5152083b10f2fc | [
"MIT"
] | 129 | 2015-03-26T15:12:27.000Z | 2021-12-07T10:11:13.000Z | PrimerTest/PrimerTest/ch10/ex10_17.cpp | silence0201/C-Plus-Study | ad013f093f275620dee892033e5152083b10f2fc | [
"MIT"
] | 1,809 | 2015-03-26T08:36:59.000Z | 2022-03-30T02:17:28.000Z | #include <algorithm>
#include <vector>
#include "../ch07/ex7_26_sales_data.h" // Sales_data class.
int main()
{
Sales_data d1("CppPrimer"), d2("JavaCore"), d3("PythonCookBook"),
d4("CppCore"), d5("AwesomeCPP");
std::vector<Sales_data> v{d1, d2, d3, d4, d5};
std::sort(v.begin(), v.end(),
[](const Sales_data& sd1, const Sales_data& sd2) {
return sd1.isbn() < sd2.isbn();
});
for (const auto& element : v) std::cout << element.isbn() << " ";
std::cout << std::endl;
}
| 27.25 | 69 | 0.555963 | silence0201 |
07c6a96e130b4171ef33a8255e3f88f896ff44d7 | 5,334 | cpp | C++ | libi2pd/Gzip.cpp | ChristopherBilg/i2pd | b7e20b9b86165a0eb2ba5bcf9a580f3824a38462 | [
"BSD-3-Clause"
] | 2,019 | 2015-01-24T03:24:58.000Z | 2022-03-31T03:38:00.000Z | libi2pd/Gzip.cpp | ChristopherBilg/i2pd | b7e20b9b86165a0eb2ba5bcf9a580f3824a38462 | [
"BSD-3-Clause"
] | 1,093 | 2015-01-30T10:43:04.000Z | 2022-03-31T15:51:40.000Z | libi2pd/Gzip.cpp | ChristopherBilg/i2pd | b7e20b9b86165a0eb2ba5bcf9a580f3824a38462 | [
"BSD-3-Clause"
] | 457 | 2015-02-02T05:20:25.000Z | 2022-03-27T09:41:08.000Z | /*
* Copyright (c) 2013-2020, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#include <inttypes.h>
#include <string.h> /* memset */
#include <iostream>
#include "Log.h"
#include "I2PEndian.h"
#include "Gzip.h"
namespace i2p
{
namespace data
{
const size_t GZIP_CHUNK_SIZE = 16384;
GzipInflator::GzipInflator (): m_IsDirty (false)
{
memset (&m_Inflator, 0, sizeof (m_Inflator));
inflateInit2 (&m_Inflator, MAX_WBITS + 16); // gzip
}
GzipInflator::~GzipInflator ()
{
inflateEnd (&m_Inflator);
}
size_t GzipInflator::Inflate (const uint8_t * in, size_t inLen, uint8_t * out, size_t outLen)
{
if (inLen < 23) return 0;
if (in[10] == 0x01) // non compressed
{
size_t len = bufle16toh (in + 11);
if (len + 23 < inLen)
{
LogPrint (eLogError, "Gzip: Incorrect length");
return 0;
}
if (len > outLen) len = outLen;
memcpy (out, in + 15, len);
return len;
}
else
{
if (m_IsDirty) inflateReset (&m_Inflator);
m_IsDirty = true;
m_Inflator.next_in = const_cast<uint8_t *>(in);
m_Inflator.avail_in = inLen;
m_Inflator.next_out = out;
m_Inflator.avail_out = outLen;
int err;
if ((err = inflate (&m_Inflator, Z_NO_FLUSH)) == Z_STREAM_END)
return outLen - m_Inflator.avail_out;
// else
LogPrint (eLogError, "Gzip: Inflate error ", err);
return 0;
}
}
void GzipInflator::Inflate (const uint8_t * in, size_t inLen, std::ostream& os)
{
m_IsDirty = true;
uint8_t * out = new uint8_t[GZIP_CHUNK_SIZE];
m_Inflator.next_in = const_cast<uint8_t *>(in);
m_Inflator.avail_in = inLen;
int ret;
do
{
m_Inflator.next_out = out;
m_Inflator.avail_out = GZIP_CHUNK_SIZE;
ret = inflate (&m_Inflator, Z_NO_FLUSH);
if (ret < 0)
{
inflateEnd (&m_Inflator);
os.setstate(std::ios_base::failbit);
break;
}
os.write ((char *)out, GZIP_CHUNK_SIZE - m_Inflator.avail_out);
}
while (!m_Inflator.avail_out); // more data to read
delete[] out;
}
void GzipInflator::Inflate (std::istream& in, std::ostream& out)
{
uint8_t * buf = new uint8_t[GZIP_CHUNK_SIZE];
while (!in.eof ())
{
in.read ((char *) buf, GZIP_CHUNK_SIZE);
Inflate (buf, in.gcount (), out);
}
delete[] buf;
}
GzipDeflator::GzipDeflator (): m_IsDirty (false)
{
memset (&m_Deflator, 0, sizeof (m_Deflator));
deflateInit2 (&m_Deflator, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY); // 15 + 16 sets gzip
}
GzipDeflator::~GzipDeflator ()
{
deflateEnd (&m_Deflator);
}
void GzipDeflator::SetCompressionLevel (int level)
{
deflateParams (&m_Deflator, level, Z_DEFAULT_STRATEGY);
}
size_t GzipDeflator::Deflate (const uint8_t * in, size_t inLen, uint8_t * out, size_t outLen)
{
if (m_IsDirty) deflateReset (&m_Deflator);
m_IsDirty = true;
m_Deflator.next_in = const_cast<uint8_t *>(in);
m_Deflator.avail_in = inLen;
m_Deflator.next_out = out;
m_Deflator.avail_out = outLen;
int err;
if ((err = deflate (&m_Deflator, Z_FINISH)) == Z_STREAM_END)
{
out[9] = 0xff; // OS is always unknown
return outLen - m_Deflator.avail_out;
}
// else
LogPrint (eLogError, "Gzip: Deflate error ", err);
return 0;
}
size_t GzipDeflator::Deflate (const std::vector<std::pair<const uint8_t *, size_t> >& bufs, uint8_t * out, size_t outLen)
{
if (m_IsDirty) deflateReset (&m_Deflator);
m_IsDirty = true;
size_t offset = 0;
int err;
for (const auto& it: bufs)
{
m_Deflator.next_in = const_cast<uint8_t *>(it.first);
m_Deflator.avail_in = it.second;
m_Deflator.next_out = out + offset;
m_Deflator.avail_out = outLen - offset;
auto flush = (it == bufs.back ()) ? Z_FINISH : Z_NO_FLUSH;
err = deflate (&m_Deflator, flush);
if (err)
{
if (flush && err == Z_STREAM_END)
{
out[9] = 0xff; // OS is always unknown
return outLen - m_Deflator.avail_out;
}
break;
}
offset = outLen - m_Deflator.avail_out;
}
// else
LogPrint (eLogError, "Gzip: Deflate error ", err);
return 0;
}
size_t GzipNoCompression (const uint8_t * in, uint16_t inLen, uint8_t * out, size_t outLen)
{
static const uint8_t gzipHeader[11] = { 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x01 };
if (outLen < (size_t)inLen + 23) return 0;
memcpy (out, gzipHeader, 11);
htole16buf (out + 11, inLen);
htole16buf (out + 13, 0xffff - inLen);
memcpy (out + 15, in, inLen);
htole32buf (out + inLen + 15, crc32 (0, in, inLen));
htole32buf (out + inLen + 19, inLen);
return inLen + 23;
}
size_t GzipNoCompression (const std::vector<std::pair<const uint8_t *, size_t> >& bufs, uint8_t * out, size_t outLen)
{
static const uint8_t gzipHeader[11] = { 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x01 };
memcpy (out, gzipHeader, 11);
uint32_t crc = 0;
size_t len = 0, len1;
for (const auto& it: bufs)
{
len1 = len;
len += it.second;
if (outLen < len + 23) return 0;
memcpy (out + 15 + len1, it.first, it.second);
crc = crc32 (crc, it.first, it.second);
}
if (len > 0xffff) return 0;
htole32buf (out + len + 15, crc);
htole32buf (out + len + 19, len);
htole16buf (out + 11, len);
htole16buf (out + 13, 0xffff - len);
return len + 23;
}
} // data
} // i2p
| 26.405941 | 122 | 0.652981 | ChristopherBilg |
07c6da4c0d86010f51fdce92114fe99aaffbe8c5 | 7,727 | cpp | C++ | rfm69.cpp | wintersteiger/wlmcd | 7bdc184b875a0be652a0dd346fd9a598c14181d8 | [
"MIT"
] | 4 | 2021-01-11T13:50:25.000Z | 2021-01-24T19:34:47.000Z | rfm69.cpp | wintersteiger/wlmcd | 7bdc184b875a0be652a0dd346fd9a598c14181d8 | [
"MIT"
] | 1 | 2021-02-12T15:49:18.000Z | 2021-02-12T16:50:55.000Z | rfm69.cpp | wintersteiger/wlmcd | 7bdc184b875a0be652a0dd346fd9a598c14181d8 | [
"MIT"
] | 2 | 2021-01-11T13:53:18.000Z | 2021-03-01T10:22:46.000Z | // Copyright (c) Christoph M. Wintersteiger
// Licensed under the MIT License.
#include <cstring>
#include <cmath>
#include <unistd.h>
#include <vector>
#include <fstream>
#include <iomanip>
#include <gpiod.h>
#include "json.hpp"
#include "sleep.h"
#include "rfm69.h"
#include "rfm69_rt.h"
using json = nlohmann::json;
RFM69::RFM69(
unsigned spi_bus, unsigned spi_channel,
const std::string &config_file,
double f_xosc) :
Device(),
SPIDev(spi_bus, spi_channel, 10000000),
RT(new RegisterTable(*this)),
spi_channel(spi_channel),
f_xosc(f_xosc),
f_step(f_xosc / pow(2, 19))
// ,
// recv_buf(new uint8_t[1024]),
// recv_buf_sz(1024), recv_buf_begin(0), recv_buf_pos(0)
{
Reset();
SetMode(Mode::STDBY);
if (!config_file.empty()) {
auto is = std::ifstream(config_file);
Read(is);
}
SetMode(Mode::RX);
RT->Refresh(false);
}
RFM69::~RFM69() {
Reset();
SetMode(Mode::SLEEP);
// delete[](recv_buf);
delete(RT);
}
void RFM69::Reset()
{
ClearFlags();
SetMode(Mode::STDBY);
}
uint8_t RFM69::Read(const uint8_t &addr)
{
mtx.lock();
std::vector<uint8_t> res(2);
res[0] = addr & 0x7F;
SPIDev::Transfer(res);
mtx.unlock();
return res[1];
}
std::vector<uint8_t> RFM69::Read(const uint8_t &addr, size_t length)
{
mtx.lock();
std::vector<uint8_t> res(length + 1);
res[0] = addr & 0x7F;
SPIDev::Transfer(res);
res.erase(res.begin());
mtx.unlock();
return res;
}
void RFM69::Write(const uint8_t &addr, const uint8_t &value)
{
mtx.lock();
std::vector<uint8_t> buf(2);
buf[0] = 0x80 | (addr & 0x7F);
buf[1] = value;
SPIDev::Transfer(buf);
mtx.unlock();
}
void RFM69::Write(const uint8_t &addr, const std::vector<uint8_t> &values)
{
mtx.lock();
size_t n = values.size();
std::vector<uint8_t> buf(n+1);
buf[0] = 0x80 | (addr & 0x7F);;
memcpy(&buf[1], values.data(), n);
SPIDev::Transfer(buf);
mtx.unlock();
}
RFM69::Mode RFM69::GetMode()
{
return (Mode)RT->_vMode(Read(RT->_rOpMode));
}
void RFM69::SetMode(Mode m)
{
uint8_t nv = RT->_vMode.Set(Read(RT->_rOpMode), m);
Write(RT->_rOpMode, nv);
size_t limit = 50;
do {
if (GetMode() == m)
return;
sleep_us(10);
} while(--limit);
// Device did not react after `limit` tries.
responsive = false;
}
void RFM69::UpdateFrequent()
{
RT->Refresh(true);
}
void RFM69::UpdateInfrequent()
{
RT->Refresh(false);
}
void RFM69::Write(std::ostream &os)
{
RT->Write(os);
}
void RFM69::Read(std::istream &is)
{
RT->Read(is);
}
void RFM69::ClearFlags()
{
uint8_t irq1 = Read(RT->_rIrqFlags1);
uint8_t irq2 = Read(RT->_rIrqFlags2);
Write(RT->_rIrqFlags1, irq1 | 0x09); // RSSI, SyncAddressMatch
Write(RT->_rIrqFlags2, irq2 | 0x10); // FifoOverrun
}
void RFM69::Receive(std::vector<uint8_t> &packet)
{
const uint8_t format = RT->_vPacketFormat(Read(RT->_rPacketConfig1));
const uint8_t length = Read(RT->_rPayloadLength);
const uint8_t threshold = RT->_vFifoThreshold(Read(RT->_rFifoThresh));
size_t max_wait = 5;
packet.resize(0);
if (format == 0 && length == 0)
throw std::runtime_error("unlimited packet length not implemented yet");
else {
packet.reserve(length);
while (packet.size() < length && max_wait > 0) {
uint8_t irqflags2 = Read(RT->_rIrqFlags2);
if (RT->_vFifoNotEmpty(irqflags2)) {
if (RT->_vFifoLevel(irqflags2)) {
// auto p = Read(RT->_rFifo.Address(), threshold);
// packet.insert(packet.end(), p.begin(), p.end());
for (size_t i = 0; i < threshold; i++)
packet.push_back(Read(RT->_rFifo));
}
else
packet.push_back(Read(RT->_rFifo));
}
else {
sleep_us(8 * (1e6 / rBitrate()));
max_wait--;
}
}
}
// uint8_t crc;
// size_t rxbytes_last = 0, rxbytes = 1;
// while (true)
// {
// do {
// rxbytes_last = rxbytes;
// rxbytes = 128; // number of bytes in fifo not available?
// } while (rxbytes != rxbytes_last);
// bool overflow = (rxbytes & 0x80) != 0;
// size_t n = rxbytes & 0x7F;
// size_t m = n <= 1 ? n : n-1;
// if (n == 0)
// break;
// else if (overflow) {
// break;
// }
// else
// {
// std::vector<uint8_t> buf = Read(RT->_rFifo.Address(), m);
// for (uint8_t &bi : buf) {
// recv_buf[recv_buf_pos++] = bi;
// recv_buf_pos %= recv_buf_sz;
// }
// }
// sleep_us(1000); // give the FIFO a chance to catch up
// }
// size_t pkt_sz = recv_buf_held(), i=0;
// packet.resize(pkt_sz);
// while (recv_buf_begin != recv_buf_pos) {
// packet[i++] = recv_buf[recv_buf_begin++];
// recv_buf_begin %= recv_buf_sz;
// }
// recv_buf_begin = recv_buf_pos;
}
void RFM69::Transmit(const std::vector<uint8_t> &pkt)
{
}
void RFM69::Test(const std::vector<uint8_t> &data)
{
Transmit(data);
}
double RFM69::rRSSI() const {
return - (RT->RssiValue() / 2.0);
}
uint64_t RFM69::rSyncWord() const {
uint64_t r = 0;
r = (r << 8) | RT->SyncValue1();
r = (r << 8) | RT->SyncValue2();
r = (r << 8) | RT->SyncValue3();
r = (r << 8) | RT->SyncValue4();
r = (r << 8) | RT->SyncValue5();
r = (r << 8) | RT->SyncValue6();
r = (r << 8) | RT->SyncValue7();
r = (r << 8) | RT->SyncValue8();
return r;
}
double RFM69::rBitrate() const {
uint64_t br = (RT->BitrateMsb() << 8) | RT->BitrateLsb();
return F_XOSC() / (double)br / 1e3;
}
void RFM69::RegisterTable::Refresh(bool frequent)
{
RegisterTable &rt = *device.RT;
uint8_t om = device.Read(rt._rOpMode);
uint8_t irq1 = device.Read(rt._rIrqFlags1);
uint8_t irq2 = device.Read(rt._rIrqFlags2);
uint8_t rssi = device.Read(rt._rRssiValue);
uint8_t feim = device.Read(rt._rFeiMsb);
uint8_t feil = device.Read(rt._rFeiLsb);
device.mtx.lock();
if (buffer.size() != 0x72)
buffer.resize(0x72, 0);
buffer[rt._rOpMode.Address()] = om;
buffer[rt._rIrqFlags1.Address()] = irq1;
buffer[rt._rIrqFlags2.Address()] = irq2;
buffer[rt._rRssiValue.Address()] = rssi;
buffer[rt._rFeiMsb.Address()] = feim;
buffer[rt._rFeiLsb.Address()] = feil;
device.mtx.unlock();
if (!frequent)
for (size_t i=0x01; i < 0x71; i++)
buffer[i] = device.Read(i);
}
void RFM69::RegisterTable::Write(std::ostream &os)
{
json j, dev, regs;
dev["name"] = device.Name();
j["device"] = dev;
for (const auto reg : registers)
if (reg->Address() != 0x00) {
char tmp[3];
snprintf(tmp, 3, "%02x", (*this)(*reg));
regs[reg->Name()] = tmp;
}
j["registers"] = regs;
os << std::setw(2) << j << std::endl;
}
void RFM69::RegisterTable::Set(const std::string &key, const std::string &value)
{
if (value.size() != 2)
throw std::runtime_error(std::string("invalid value length for '" + key + "'"));
bool found = false;
for (const auto &r : registers)
if (r->Name() == key && r->Address() != 0) {
uint8_t val;
sscanf(value.c_str(), "%02hhx", &val);
device.Write(*r, val);
found = true;
break;
}
if (!found)
throw std::runtime_error(std::string("invalid register '") + key + "'");
}
void RFM69::RegisterTable::Read(std::istream &is)
{
device.SetMode(Mode::STDBY);
device.ClearFlags();
json j = json::parse(is);
if (j["device"]["name"] != device.Name())
throw std::runtime_error("device mismatch");
for (const auto &e : j["registers"].items()) {
const std::string &name = e.key();
if (name == "OpMode")
continue;
if (!e.value().is_string())
throw std::runtime_error(std::string("invalid value for '" + e.key() + "'"));
Set(name, e.value().get<std::string>());
}
if (j["registers"].contains("OpMode"))
Set("OpMode", j["registers"]["OpMode"]);
}
| 23.134731 | 84 | 0.599974 | wintersteiger |
07c6df38e78c2ba8e1c5f41cee29d99d1074be13 | 668 | cpp | C++ | tests/game_of_life.cpp | omrisim210/cellular- | e2e02a6577c6ffa015a2873817c5761e5e6835a5 | [
"MIT"
] | 1 | 2020-06-29T19:04:06.000Z | 2020-06-29T19:04:06.000Z | tests/game_of_life.cpp | omrisim210/cellularpp | e2e02a6577c6ffa015a2873817c5761e5e6835a5 | [
"MIT"
] | null | null | null | tests/game_of_life.cpp | omrisim210/cellularpp | e2e02a6577c6ffa015a2873817c5761e5e6835a5 | [
"MIT"
] | null | null | null | #include "game_of_life.hpp"
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <iostream>
#include "doctest.h"
using namespace gol;
GameOfLife automaton("./spinner.txt");
TEST_CASE("generation 0") {
// for (auto i = 0; i < automaton.width(); ++i) {
// for (auto j = 0; j < automaton.height(); ++j) {
// INFO(automaton.state_to_char(automaton(i, j)));
// }
// INFO('\n');
// }
CHECK(automaton(0, 0) == State::Dead);
// CHECK(automaton(2, 1) == State::Alive);
}
// TEST_CASE("generation 1") {
// automaton.step();
// CHECK(automaton(0, 0) == State::Dead);
// CHECK(automaton(2, 1) == State::Dead);
// CHECK(automaton(1, 2) == State::Alive);
// }
| 23.034483 | 53 | 0.615269 | omrisim210 |
07c7f5d56e10be6c309887917a06cc6db95c4ab0 | 907 | cpp | C++ | code/quick sort/quick-sort.cpp | logancrocker/interview-toolkit | e33e4ba0c76f0bcbd831d2955095ad3325569388 | [
"MIT"
] | null | null | null | code/quick sort/quick-sort.cpp | logancrocker/interview-toolkit | e33e4ba0c76f0bcbd831d2955095ad3325569388 | [
"MIT"
] | null | null | null | code/quick sort/quick-sort.cpp | logancrocker/interview-toolkit | e33e4ba0c76f0bcbd831d2955095ad3325569388 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
int partition(int arr[], int left, int right) {
int pivot = arr[right];
int i = left - 1;
for (int j = left; j <= right - 1; ++j) {
if (arr[j] <= pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[right]);
return (i + 1);
}
void quickSort(int arr[], int left, int right) {
if (left < right) {
int partitionIndex = partition(arr, left, right);
quickSort(arr, left, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, right);
}
}
int main() {
int arr[10] = { 3, 8, 4, 1, 9, 10, 5, 2, 7, 6 };
const int size = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, size - 1);
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
} | 19.297872 | 54 | 0.486218 | logancrocker |
07c99a785148601546e0293a660ecc7c2ad4b8e5 | 4,419 | cpp | C++ | OpenMeshCmd/src/OpenMeshCmd.cpp | tody411/MayaPluginSamples | 785f1b1425e202f42d77622290c3faf80d7bd06f | [
"MIT"
] | 2 | 2016-06-16T14:48:42.000Z | 2018-06-28T20:12:09.000Z | OpenMeshCmd/src/OpenMeshCmd.cpp | tody411/MayaPluginSamples | 785f1b1425e202f42d77622290c3faf80d7bd06f | [
"MIT"
] | null | null | null | OpenMeshCmd/src/OpenMeshCmd.cpp | tody411/MayaPluginSamples | 785f1b1425e202f42d77622290c3faf80d7bd06f | [
"MIT"
] | null | null | null | //! Simple OpenMesh command plug-in.
/*!
\file OpenMeshCmd.cpp
\author Tody
\date 2015/08/05
Usage:
MEL: OpenMeshCmd ;
Python: cmds.OpenMeshCmd();
*/
#define _USE_MATH_DEFINES
#include <OpenMesh/Core/Mesh/PolyMesh_ArrayKernelT.hh>
typedef OpenMesh::PolyMesh_ArrayKernelT<> MeshType;
#include <maya/MIOStream.h>
#include <maya/MSimple.h>
#include <maya/MGlobal.h>
#include <maya/MString.h>
#include <maya/MDagPath.h>
#include <maya/MDagPathArray.h>
#include <maya/MFnDagNode.h>
#include <maya/MFnMesh.h>
#include <maya/MPointArray.h>
#include <maya/MSelectionList.h>
#include <maya/MItSelectionList.h>
#include <maya/MItMeshVertex.h>
#include <maya/MItMeshPolygon.h>
#include <random>
//! This function will automatically create NoiseCmd class and register the plugin.
DeclareSimpleCommand ( OpenMeshCmd, "SimplePlugin", "1.0" );
//! Get selected dag list.
/*!
\param dagList selected dag list.
\param filter target API types. kMesh | kLight | ...
*/
MStatus getSelectedDagList ( MDagPathArray& dagList, MFn::Type filter = MFn::kInvalid )
{
MDagPath node;
MObject component;
MSelectionList list;
MFnDagNode nodeFn;
MGlobal::getActiveSelectionList ( list );
for ( MItSelectionList listIter ( list, filter ); !listIter.isDone(); listIter.next() )
{
listIter.getDagPath ( node, component );
nodeFn.setObject ( node );
dagList.append ( node );
cout << nodeFn.name().asChar() << " is selected" << endl;
}
return MStatus::kSuccess;
}
//! Get seleted mesh list.
/*!
\param meshList selected mesh list.
*/
MStatus getSelectedMeshList ( MDagPathArray& meshList )
{
return getSelectedDagList ( meshList, MFn::kMesh );
}
//! Compute noise for target mesh with parameter sigma.
/*!
\param mesh target mesh.
\param sigma noise parameter.
\param space target space. kObject | kWorld | kTransform | ...
Random position will be compute with std::uniform_real_distribution method.
*/
MStatus openMeshInfo ( const MDagPath& mesh, MSpace::Space space = MSpace::kObject )
{
MFnMesh meshFn ( mesh );
cout << "=============================" << endl;
cout << "MayaMesh data" << endl;
cout << "=============================" << endl;
cout << "numVertices: " << meshFn.numVertices() << endl;
cout << "numEdges: " << meshFn.numEdges() << endl;
cout << "numFaces: " << meshFn.numPolygons() << endl;
cout << endl;
int numVertices = meshFn.numVertices();
// create vertex data.
MeshType openMesh;
std::vector<MeshType::VertexHandle> vHandles ( numVertices );
MPointArray points;
meshFn.getPoints ( points, space );
for ( int vi = 0; vi < numVertices; vi++ )
{
MPoint p = points[vi];
vHandles[vi] = openMesh.add_vertex ( MeshType::Point ( p.x, p.y, p.z ) );
}
// create face data.
MIntArray triangleCounts;
MIntArray triangleVertices;
meshFn.getTriangles ( triangleCounts, triangleVertices );
int numTriangles = triangleVertices.length() / 3;
for ( int fi = 0; fi < numTriangles; fi++ )
{
std::vector<MeshType::VertexHandle> face_vhandles;
for ( int fvi = 0; fvi < 3; fvi++ )
{
face_vhandles.push_back ( vHandles[triangleVertices[3 * fi + fvi]] );
}
openMesh.add_face ( face_vhandles );
}
// compute vertex normals.
openMesh.request_vertex_normals();
openMesh.update_normals();
cout << "=============================" << endl;
cout << "OpenMesh data" << endl;
cout << "=============================" << endl;
cout << "numVertices: " << openMesh.n_vertices() << endl;
cout << "numEdges: " << openMesh.n_edges() << endl;
cout << "numFaces: " << openMesh.n_faces() << endl;
cout << "numHalfEdges: " << openMesh.n_halfedges() << endl;
cout << "hasVertexNormals: " << openMesh.has_vertex_normals() << endl;
cout << "hasFaceNormals: " << openMesh.has_face_normals() << endl;
return MStatus::kSuccess;
}
//! Simple command to get noisy mesh.
MStatus OpenMeshCmd::doIt ( const MArgList& args )
{
cout << "OpenMeshCmd " << endl;
MDagPathArray meshList;
getSelectedMeshList ( meshList );
for ( int i = 0; i < meshList.length(); i++ )
{
MDagPath mesh ( meshList[i] );
openMeshInfo ( mesh );
}
return MS::kSuccess;
}
| 28.509677 | 91 | 0.62186 | tody411 |
07caf422ce8171d0f42f20409396239b0dd3e0a1 | 353 | cpp | C++ | src/sprite/SpriteBatch.cpp | deianvn/kit2d | a8fd6d75cf1f8d14baabaa04903ab3fdee3b4ef5 | [
"Apache-2.0"
] | null | null | null | src/sprite/SpriteBatch.cpp | deianvn/kit2d | a8fd6d75cf1f8d14baabaa04903ab3fdee3b4ef5 | [
"Apache-2.0"
] | null | null | null | src/sprite/SpriteBatch.cpp | deianvn/kit2d | a8fd6d75cf1f8d14baabaa04903ab3fdee3b4ef5 | [
"Apache-2.0"
] | null | null | null | #include "../../include/kit2d/sprite/SpriteBatch.hpp"
#include "../../include/kit2d/core/Renderer.hpp"
namespace kit2d {
void SpriteBatch::add(Sprite& sprite) {
sprites.push_back(&sprite);
}
void SpriteBatch::process(Renderer& renderer) {
for (auto sprite : sprites) {
sprite->draw(renderer);
}
renderer.present();
}
}
| 19.611111 | 53 | 0.651558 | deianvn |
07ceced65e6b956fe2e59db1d341d5f56ffaf56c | 88,134 | cpp | C++ | floatnuc.cpp | rainoverme002/FloatNuc | ee0206f3f54cbc2a93ac88fc27116a10375db701 | [
"MIT"
] | 1 | 2021-03-29T03:59:18.000Z | 2021-03-29T03:59:18.000Z | floatnuc.cpp | rainoverme002/FloatNuc | ee0206f3f54cbc2a93ac88fc27116a10375db701 | [
"MIT"
] | null | null | null | floatnuc.cpp | rainoverme002/FloatNuc | ee0206f3f54cbc2a93ac88fc27116a10375db701 | [
"MIT"
] | null | null | null | #include "floatnuc.h"
#include "ui_floatnuc.h"
#include "fixeditem.h"
#include "movingitem.h"
#include "corebackground.h"
#include "qcustomplot.h"
#include "videoplayer.h"
#include <QApplication>
#include <QTimer>
#include <QtCore>
#include <QtGui>
#include <valarray>
#include <chrono>
#include <thread>
#include <cmath>
#include <fstream>
using namespace std;
//Variabel for the Chart
QVector<double> qv_x(10), qv_y0(10), qv_y1(10), qv_y2(10), qv_y3(10), qv_y4(10),
qv_y5(10), qv_y6(10), qv_y7(10), qv_y8(10), qv_y9(10), qv_y10(10), qv_y11(10),
qv_y12(10), qv_y13(10), qv_y14(10), qv_y15(10), qv_y16(10), qv_y17(10), qv_y18(10);
//Variabel for the SeaStatecondition
int SeaState = 0, ShipMovement = 0;
//Variabel for the condition Simulation
int condition_choose = 0;
//Variabel for Plot Choose
int plot_1_choose = 0, plot_2_choose = 0, plot_3_choose = 0, plot_4_choose = 0;
// Set number of Array in Valarray
int const ndep = 33;
valarray<double> Y(ndep);
//=============================Constant Variable=======================
//Timestep
// Set step size (fixed for the real time simulation) -increase it will increase exe time
double const dx = 0.0001;
//Please change this if you want change the simulation interval
double const intervalwaktu (100);//milisecond
//The time on the function step
double xo = 0;//second
double xn = intervalwaktu/1000; //second
//Nilai Reaktivitas Tambahan
double const reaktivitasundak = 0.0004;//k
double const reaktivitasramp = 0.0001;//k
double reaktivitastambahan = 0;
//Untuk Parameter Kinetik Teras
double const prompt (1.E-4);
double const neutronlifetime (1E-4);
double const beta (0.0065);
double const betagrup1 (0.000215);
double const betagrup2 (0.001424);
double const betagrup3 (0.001274);
double const betagrup4 (0.002568);
double const betagrup5 (0.000748);
double const betagrup6 (0.000273);
double const lamdagrup1 (0.0124) ;
double const lamdagrup2 (0.0305) ;
double const lamdagrup3 (0.111) ;
double const lamdagrup4 (0.301) ;
double const lamdagrup5 (1.14) ;
double const lamdagrup6 (3.01) ;
//Untuk Perhitungan Daya
double const convertpowertofluks (0.95 * 190E6 * 1.6E-19);
double const reactorvol (1.257);//m^3
double const fissioncrosssection (0.337);//cm^-1 for U-235
double const fullpower(150);//Mwth
//Untuk Reaktivitas Void
double const koefreaktivitasvoid(-0.0015);//k/K
//Untuk Reaktivitas Moderator
double const koefsuhumod (-0.0002);//k/K
double const Suhuawalmod (300);//K
//Untuk Reaktivitas Fuel
double const koefsuhufuel (-0.0000178);//k/K
double const suhuawalfuel (300);//K
//Untuk Reaktivitas Daya
double const koefdaya (-0.00004);// k/persen daya
//Untuk Reaktivitas Batang Kendali
double const controlrodspeed (0.2);//cm/s
double const scramrodspeed (13);//cm/s
//Untuk Perhitungan Racun Neutron
double const yieldiodine (6.386);//Yield for U-235
double const yieldxenon (0.228);//Yield for U-235
double const yieldpromethium (0.66);//Yield for U-235
double const lamdaiodine (0.1035/3600);//Decay Constant Iodine in s^-1
double const lamdaxenon (0.0753/3600);//Decay Constant Xenon in s^-1
double const lamdapromethium (0.0128/3600);//Decay Constant Promethium in s^-1
double const sigmaabsorptionxenon(3*1E5*1E-24);//Sigma Absortion for Xenon in cm^2
double const sigmaabsorptionsamarium(5.8*1E4*1E-24);//Sigma Absorption for Samarium in cm^2
//Untuk Transfer Kalor dari Daya ke Bahan Bakar
double const h (35000);//W/m^2 K
double const a (4.21405381);//m^2
double const mfuel (2920);//Kg
double const cpfuel (239.258);//J/kgK Uranium
//Untuk Transfer Kalor dari Bahan Bakar ke Moderator/Pendingin
double const lajumassa (734);//Kg/s
double const Tin (553);//K
double const vpendingin (1.4457385);//m^3
double const Tsaturated (602.19);//K
double const coreheight (1.67);//m
double const Acoolant (4.201622E-3);//m2
floatnuc::floatnuc(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::floatnuc)
{
ui->setupUi(this);
//Plotting Initialization
ui->Plot_1->addGraph();
ui->Plot_1->graph(0)->setScatterStyle(QCPScatterStyle::ssCircle);
ui->Plot_1->setInteraction(QCP::iRangeZoom);//Can be Zoom
ui->Plot_1->setInteraction(QCP::iRangeDrag);//Can be Drag
//Plotting Initialization
ui->Plot_2->addGraph();
ui->Plot_2->graph(0)->setScatterStyle(QCPScatterStyle::ssCircle);
ui->Plot_2->setInteraction(QCP::iRangeZoom);//Can be Zoom
ui->Plot_2->setInteraction(QCP::iRangeDrag);//Can be Drag
//Plotting Initialization
ui->Plot_3->addGraph();
ui->Plot_3->graph(0)->setScatterStyle(QCPScatterStyle::ssCircle);
ui->Plot_3->setInteraction(QCP::iRangeZoom);//Can be Zoom
ui->Plot_3->setInteraction(QCP::iRangeDrag);//Can be Drag
//Plotting Initialization
ui->Plot_4->addGraph();
ui->Plot_4->graph(0)->setScatterStyle(QCPScatterStyle::ssCircle);
ui->Plot_4->setInteraction(QCP::iRangeZoom);//Can be Zoom
ui->Plot_4->setInteraction(QCP::iRangeDrag);//Can be Drag
//Timer Initialization
timer = new QTimer (this);
connect(timer,SIGNAL(timeout()),this,SLOT(engine()));
//Video Initialization
//Video Platlist Definition
playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Kondisi Diam.mp4"));
playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Pitching - Heaving - Sea State 2.mp4"));
playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Pitching - Heaving - Sea State 3.mp4"));
playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Pitching - Heaving - Sea State 4.mp4"));
playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Pitching - Heaving - Sea State 5.mp4"));
playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Pitching - Heaving - Sea State 6.mp4"));
playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Pitching - Heaving - Sea State 7.mp4"));
playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Pitching - Heaving - Sea State 8.mp4"));
playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Pitching - Heaving - Sea State 9.mp4"));
playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Rolling - Heaving - Sea State 2.mp4"));
playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Rolling - Heaving - Sea State 3.mp4"));
playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Rolling - Heaving - Sea State 4.mp4"));
playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Rolling - Heaving - Sea State 5.mp4"));
playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Rolling - Heaving - Sea State 6.mp4"));
playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Rolling - Heaving - Sea State 7.mp4"));
playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Rolling - Heaving - Sea State 8.mp4"));
playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/Rolling - Heaving - Sea State 9.mp4"));
playlist->addMedia(QUrl::fromLocalFile("G:/Data/Thesis/QT/FloatNuc/videos/World’s only floating nuclear power plant to be loaded with fuel in Russia.mp4"));
playlist->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
ui->Video_Widget->m_mediaPlayer->setPlaylist(playlist);
//Animation Initialization
scene = new QGraphicsScene(this);
ui->Animation_View->setScene(scene);
ui->Animation_View->setRenderHint(QPainter::Antialiasing);
//Animation Position
int const x = 1150;
int const y = 0;
scene->setSceneRect(x,y,500,400);
CR_Animation();
}
floatnuc::~floatnuc()
{
delete ui;
}
void floatnuc::CR_Animation()
{
//Animation Position
int const x = 1200;
int const y = 0;
background = new corebackground(x-50,y);
scene->addItem(background);
int XAxis = x;
int YAxis = y+20;
for (int i =0; i<6; i++){
core = new fixeditem(XAxis,YAxis);
scene->addItem(core);
XAxis+=80;
}
//Group Dalam Position Initialization
DalamCR = new movingitem(x+200, YAxis);
scene->addItem(DalamCR);
//Group Antara Position Initialization
AntaraCR1 = new movingitem(x+120, YAxis);
scene->addItem(AntaraCR1);
AntaraCR2 = new movingitem(x+280, YAxis);
scene->addItem(AntaraCR2);
//Group Terluar Position Initialization
TerluarCR1 = new movingitem(x+40, YAxis);
scene->addItem(TerluarCR1);
TerluarCR2 = new movingitem(x+360, YAxis);
scene->addItem(TerluarCR2);
}
void floatnuc::videocalling(int SeaState, int ShipMovement){
switch (ShipMovement)
{
case 0:
switch (SeaState)
{
case 0:
playlist->setCurrentIndex(0);
ui->Video_Widget->m_mediaPlayer->play();
break;
case 1:
playlist->setCurrentIndex(1);
ui->Video_Widget->m_mediaPlayer->play();
break;
case 2:
playlist->setCurrentIndex(2);
ui->Video_Widget->m_mediaPlayer->play();
break;
case 3:
playlist->setCurrentIndex(3);
ui->Video_Widget->m_mediaPlayer->play();
break;
case 4:
playlist->setCurrentIndex(4);
ui->Video_Widget->m_mediaPlayer->play();
break;
case 5:
playlist->setCurrentIndex(5);
ui->Video_Widget->m_mediaPlayer->play();
break;
case 6:
playlist->setCurrentIndex(6);
ui->Video_Widget->m_mediaPlayer->play();
break;
case 7:
playlist->setCurrentIndex(7);
ui->Video_Widget->m_mediaPlayer->play();
break;
case 8:
playlist->setCurrentIndex(8);
ui->Video_Widget->m_mediaPlayer->play();
break;
}
break;
case 1:
switch (SeaState)
{
case 0:
playlist->setCurrentIndex(0);
ui->Video_Widget->m_mediaPlayer->play();
break;
case 1:
//Looping
playlist->setCurrentIndex(9);
ui->Video_Widget->m_mediaPlayer->play();
break;
case 2:
playlist->setCurrentIndex(10);
ui->Video_Widget->m_mediaPlayer->play();
break;
case 3:
playlist->setCurrentIndex(11);
ui->Video_Widget->m_mediaPlayer->play();
break;
case 4:
playlist->setCurrentIndex(12);
ui->Video_Widget->m_mediaPlayer->play();
break;
case 5:
playlist->setCurrentIndex(13);
ui->Video_Widget->m_mediaPlayer->play();
break;
case 6:
playlist->setCurrentIndex(14);
ui->Video_Widget->m_mediaPlayer->play();
break;
case 7:
playlist->setCurrentIndex(15);
ui->Video_Widget->m_mediaPlayer->play();
break;
case 8:
playlist->setCurrentIndex(16);
ui->Video_Widget->m_mediaPlayer->play();
break;
}
break;
}
}
void floatnuc::plotting_1(){
switch (plot_1_choose)
{
case 0:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y0);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
case 1:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y1);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
case 2:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y2);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
case 3:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y3);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
case 4:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y4);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
case 5:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y5);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
case 6:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y6);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
case 7:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y7);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
case 8:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y8);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
case 9:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y9);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
case 10:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y10);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
case 11:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y11);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
case 12:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y12);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
case 13:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y13);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
case 14:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y14);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
case 15:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y15);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
case 16:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y16);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
case 17:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y17);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
case 18:
ui->Plot_1->graph(0)->data().clear();
ui->Plot_1->graph(0)->setData(qv_x, qv_y18);
ui->Plot_1->graph(0)->rescaleValueAxis(false);
ui->Plot_1->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_1->xAxis->setLabel("Time(s)");
ui->Plot_1->yAxis->setLabel(ui->Plot_1_Combobox->currentText());
ui->Plot_1->replot();
break;
}
}
void floatnuc::plotting_2(){
switch (plot_2_choose)
{
case 0:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y0);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
case 1:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y1);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
case 2:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y2);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
case 3:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y3);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
case 4:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y4);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
case 5:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y5);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
case 6:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y6);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
case 7:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y7);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
case 8:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y8);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
case 9:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y9);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
case 10:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y10);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
case 11:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y11);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
case 12:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y12);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
case 13:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y13);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
case 14:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y14);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
case 15:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y15);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
case 16:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y16);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
case 17:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y17);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
case 18:
ui->Plot_2->graph(0)->data().clear();
ui->Plot_2->graph(0)->setData(qv_x, qv_y18);
ui->Plot_2->graph(0)->rescaleValueAxis(false);
ui->Plot_2->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_2->xAxis->setLabel("Time(s)");
ui->Plot_2->yAxis->setLabel(ui->Plot_2_Combobox->currentText());
ui->Plot_2->replot();
break;
}
}
void floatnuc::plotting_3(){
switch (plot_3_choose)
{
case 0:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y0);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
case 1:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y1);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
case 2:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y2);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
case 3:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y3);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
case 4:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y4);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
case 5:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y5);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
case 6:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y6);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
case 7:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y7);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
case 8:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y8);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
case 9:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y9);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
case 10:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y10);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
case 11:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y11);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
case 12:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y12);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
case 13:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y13);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
case 14:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y14);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
case 15:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y15);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
case 16:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y16);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
case 17:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y17);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
case 18:
ui->Plot_3->graph(0)->data().clear();
ui->Plot_3->graph(0)->setData(qv_x, qv_y18);
ui->Plot_3->graph(0)->rescaleValueAxis(false);
ui->Plot_3->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_3->xAxis->setLabel("Time(s)");
ui->Plot_3->yAxis->setLabel(ui->Plot_3_Combobox->currentText());
ui->Plot_3->replot();
break;
}
}
void floatnuc::plotting_4(){
switch (plot_4_choose)
{
case 0:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y0);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
case 1:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y1);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
case 2:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y2);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
case 3:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y3);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
case 4:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y4);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
case 5:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y5);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
case 6:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y6);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
case 7:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y7);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
case 8:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y8);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
case 9:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y9);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
case 10:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y10);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
case 11:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y11);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
case 12:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y12);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
case 13:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y13);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
case 14:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y14);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
case 15:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y15);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
case 16:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y16);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
case 17:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y17);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
case 18:
ui->Plot_4->graph(0)->data().clear();
ui->Plot_4->graph(0)->setData(qv_x, qv_y18);
ui->Plot_4->graph(0)->rescaleValueAxis(false);
ui->Plot_4->xAxis->setRange(xo + 10, 20, Qt::AlignRight);
ui->Plot_4->xAxis->setLabel("Time(s)");
ui->Plot_4->yAxis->setLabel(ui->Plot_4_Combobox->currentText());
ui->Plot_4->replot();
break;
}
}
void floatnuc::tampilhasil(double x, valarray<double> &Y)
{
//See The ComboBox Index
SeaState = ui->SeaState_Combobox->currentIndex();
ShipMovement = ui->ShipMove_Combobox->currentIndex();
condition_choose = ui->Kecelakaan_Combobox->currentIndex();
plot_1_choose = ui->Plot_1_Combobox->currentIndex();
plot_2_choose = ui->Plot_2_Combobox->currentIndex();
plot_3_choose = ui->Plot_3_Combobox->currentIndex();
plot_4_choose = ui->Plot_4_Combobox->currentIndex();
//Output The Value to Line Edit
QString Time = QString::number(xo);
QString Power = QString::number(Y[0]);
QString Fluks = QString::number(Y[2]);
QString Precursor = QString::number(Y[20]);
QString TFuel = QString::number(Y[8]);
QString TMod = QString::number(Y[9]);
QString React = QString::number(Y[3]);
QString Xenon = QString::number(Y[11]);
QString Samarium = QString::number(Y[12]);
QString ReactorPeriod = QString::number(Y[15]);
QString PowerPercent = QString::number(Y[1]);
QString PosisiGroupDalam = QString::number(Y[16]);
QString PosisiGroupAntara = QString::number(Y[17]);
QString PosisiGroupTerluar = QString::number(Y[18]);
QString MassFlow = QString::number(Y[27]);
ui->Time_Line->setText(Time);
ui->Daya_Line->setText(Power);
ui->Fluks_Line->setText(Fluks);
ui->Prekursor_Line->setText(Precursor);
ui->TFuel_Line->setText(TFuel);
ui->TModerator_Line->setText(TMod);
ui->Reaktivitas_Line->setText(React);
ui->Xenon_Line->setText(Xenon);
ui->Samarium_Line->setText(Samarium);
ui->Period_Line->setText(ReactorPeriod);
ui->PersenDaya_Line->setText(PowerPercent);
ui->GroupDalam_Line->setText(PosisiGroupDalam);
ui->GroupAntara_Line->setText(PosisiGroupAntara);
ui->GroupTerluar_Line->setText(PosisiGroupTerluar);
ui->MassFlow_Line->setText(MassFlow);
//Data Fetching
qv_x.append(x);
qv_y0.append(Y[0]);
qv_y1.append(Y[1]);
qv_y2.append(Y[2]);
qv_y3.append(Y[3]);
qv_y4.append(Y[4]);
qv_y5.append(Y[5]);
qv_y6.append(Y[6]);
qv_y7.append(Y[7]);
qv_y8.append(Y[8]);
qv_y9.append(Y[9]);
qv_y10.append(Y[10]);
qv_y11.append(Y[11]);
qv_y12.append(Y[12]);
qv_y13.append(Y[15]);
qv_y14.append(Y[27]);
qv_y15.append(Y[28]);
qv_y16.append(Y[29]);
qv_y17.append(Y[30]);
qv_y18.append(Y[31]);
//Data Plotting
plotting_1();
plotting_2();
plotting_3();
plotting_4();
//CR Position in Animation
DalamCR->setY(-3*Y[16]);
DalamCR->update();
AntaraCR1->setY(-3*Y[17]);
AntaraCR1->update();
AntaraCR2->setY(-3*Y[17]);
AntaraCR2->update();
TerluarCR1->setY(-3*Y[18]);
TerluarCR1->update();
TerluarCR2->setY(-3*Y[18]);
TerluarCR2->update();
}
void floatnuc::simpanhasil(double x, valarray<double> &Y){
if (x == 0.0){
ofstream datakeluar;
QString namefile = ui->SaveFile_Line->text();
std::string namefiletxt = namefile.toUtf8().constData();
datakeluar.open(namefiletxt, std::ios_base::app);
datakeluar << "Waktu (s)" << ","<< "Daya (MWth)" << "," << "Daya (%)" << "," << "Fluks Neutron (CPS)"
<< "," << "Total Reaktivitas (dk/k)" << "," << "Reaktivitas Batang Kendali (dk/k)" << ","
<< "Reaktivitas Xenon (dk/k)" << "," << "Reaktivitas Samarium (dk/k)" << ","
<< "Reaktivitas Void (dk/k)" << "," << "Fuel Temperature (K)" << "," << "Moderator Temperature (K)" << ","
<< "Void Fraction (%)" << "," << "Xenon (CPS)" << "," << "Samarium (CPS)" << "," << "Reactor Period (s)"
<< "," << "Mass Flow (Kg/s)" << "," << "Coolant Output Temperature (K)" << ","
<< "Prandtl Number" << "," << "Nusselt Number" << "," << "Reynold Number" << ","
<< "SeaState" << "," << "ShipMovement" <<endl;
datakeluar.close();
}else{
ofstream datakeluar;
QString namefile = ui->SaveFile_Line->text();
std::string namefiletxt = namefile.toUtf8().constData();
datakeluar.open(namefiletxt, std::ios_base::app);
datakeluar << x << ","<< Y[0] << "," << Y[1] << "," << Y[2] << "," << Y[3] << "," << Y[4] << ","
<< Y[5] << "," << Y[6] << "," << Y[7] << "," << Y[8] << "," << Y[9] << ","
<< Y[10] << "," << Y[11] << "," << Y[12] << "," << Y[15] << ","
<< Y[27] << "," << Y[28] << "," << Y[29] << "," << Y[30] << "," << Y[31] << ","
<< SeaState << "," << ShipMovement <<endl;
datakeluar.close();
}
}
//===================================================================================================================================================================//
//========Convection heat transfer Function========//
double floatnuc::prandtl(valarray<double> &Y){
double viscocity;
double coolantconductivity;
double cpcoolant = heatcapacitymoderator(Y);
viscocity = 4E-08*Y[9] - 4E-06;
if (Y[9]> Tsaturated){
coolantconductivity = 4E-07*pow(Y[9],2) - 0.0006*Y[9] + 0.2876;
}else{
coolantconductivity = -0.0021*Y[9] + 1.7319;
}
return (viscocity*cpcoolant)/coolantconductivity;
}
double floatnuc::nusselt(valarray<double> &Y){
double reynoldnumber = reynold(Y);
double prandtlnumber = prandtl(Y);
return 0.023*pow(reynoldnumber,0.8)*pow(prandtlnumber,0.4);
}
double floatnuc::reynold(valarray<double> &Y){
double viscocity;
if (Y[9]> Tsaturated){
viscocity = 4E-08*Y[9] - 4E-06;
}else{
viscocity = -4E-07*Y[9] + 0.0003;
}
viscocity = 4E-08*Y[9] - 4E-06;
double rho = massmoderator(Y)/(vpendingin);
double Dh = pow(Acoolant/3.145511,0.5)*2;
return (rho*vpendingin*Dh/viscocity);
}
double floatnuc::convectionheattransfercoefficient(valarray<double> &Y){
double nusseltnumber = nusselt(Y);
double coolantconductivity;
if (Y[9]> Tsaturated){
coolantconductivity = 4E-07*pow(Y[9],2) - 0.0006*Y[9] + 0.2876;
}else{
coolantconductivity = -0.0021*Y[9] + 1.7319;
}
double Dh = pow(Acoolant/3.145511,0.5)*2;
return (nusseltnumber*coolantconductivity/Dh);
}
//===================================================================================================================================================================//
//========Mass Moderator Function========//
double floatnuc::massmoderator(valarray<double> &Y){
double massmoderator, densitymoderator;
if (Y[9]> Tsaturated){
densitymoderator = -1E-09*pow(Y[9],3) + 4E-06*pow(Y[9],2) - 0.0034*Y[9] + 1.0474;
massmoderator = densitymoderator * 1000 * vpendingin;
return massmoderator;
} else {
densitymoderator = -0.0024*Y[9] + 2.0691;
massmoderator = densitymoderator * 1000 * vpendingin;
return massmoderator;
}
}
//===================================================================================================================================================================//
//========Heat Capacity Function========//
double floatnuc::heatcapacitymoderator(valarray<double> &Y){
double heatcapacity;
if (Y[9] > Tsaturated){
heatcapacity = -0.0004*pow(Y[9],3) + 1.1182*pow(Y[9],2)- 946.14*Y[9] + 267795;
return heatcapacity;
} else {
heatcapacity = 0.7165*pow(Y[9],2) - 789.09*Y[9] + 222431;
return heatcapacity;
}
}
//===================================================================================================================================================================//
//========Reactor Period========//
void floatnuc::reactorperiod(double x, valarray<double> &Y){
if (Y[3]>beta) {
Y[15] = neutronlifetime/Y[3];
}
else {
Y[15] = (beta-Y[3])*(0.0848/beta)/Y[3];
}
}
//===================================================================================================================================================================//
//========Reactor Condition Simulation========//
void floatnuc::condition(double x, valarray<double> &Y){
//The condition Choose
switch (condition_choose) {
case 0:
Y[27] = fungsimassflow (Y[1], x);
reaktivitastambahan = 0;
break;
case 1:
Y[27] = 5;
reaktivitastambahan = 0;
break;
case 2:
Y[27] = fungsimassflow (Y[1], x);
reaktivitastambahan = reaktivitasundak;//k
break;
case 3:
Y[27] = fungsimassflow (Y[1], x);
reaktivitastambahan = -reaktivitasundak;//k
break;
case 4:
Y[27] = fungsimassflow (Y[1], x);
reaktivitastambahan = 0.5*beta;//k
break;
case 5:
Y[27] = fungsimassflow (Y[1], x);
reaktivitastambahan = -0.5*beta;//k
break;
case 6:
Y[27] = fungsimassflow (Y[1], x);
if (reaktivitastambahan < 0.0004){
reaktivitastambahan += reaktivitasramp*dx;
}else{
reaktivitastambahan = reaktivitastambahan;
}
break;
case 7:
Y[27] = fungsimassflow (Y[1], x);
if (reaktivitastambahan > -0.0004){
reaktivitastambahan += -reaktivitasramp*dx;
}else{
reaktivitastambahan = reaktivitastambahan;
}
break;
case 8:
Y[27] = fungsimassflow (Y[1], x);
ui->GroupDalam_Slider->setValue(0);
ui->GroupAntara_Slider->setValue(0);
ui->GroupTerluar_Slider->setValue(0);
break;
}
}
//===================================================================================================================================================================//
//========Void Reactivity Function========//
double floatnuc::pitchheavemassflow(double Percentdaya, double x)
{
double nilaimassflow, yo, amplitudo, perioda;
double Pdaya = Percentdaya/100;
switch(SeaState)
{
case 0:
return lajumassa;
case 1:
if (Percentdaya > 90)
{
yo = -123.6*pow(Pdaya,3) + 404.86*pow(Pdaya,2) - 433.41*Pdaya + 886.06;
amplitudo = 51.667*pow(Pdaya,3) - 148.79*pow(Pdaya,2) + 142.66*Pdaya - 44.957;
perioda = -4.9333*pow(Pdaya,3) + 14.694*pow(Pdaya,2) - 14.539*Pdaya + 5.9796;
nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow;
}else{
return lajumassa;
}
case 2:
if (Percentdaya > 90)
{
yo = 72.48*pow(Pdaya,2) - 135.81*Pdaya + 804.84;
amplitudo = 154.97*pow(Pdaya,2) - 297.93*Pdaya + 163.86;
perioda = 200.33*pow(Pdaya,3) - 618.07*pow(Pdaya,2) + 634.64*Pdaya - 216.58;
nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow;
}else{
return lajumassa;
}
case 3:
if (Percentdaya > 90)
{
yo = -1.7543*pow(Pdaya,2) + 9.313*Pdaya + 726.55;
amplitudo = -2148*pow(Pdaya,4) + 8496.9*pow(Pdaya,3) - 12582*pow(Pdaya,2) + 8266.1*Pdaya - 2033;
perioda = -36461*pow(Pdaya,4)+ 149790*pow(Pdaya,3) - 230550*pow(Pdaya,2) + 157564*Pdaya - 40337;
nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow;
}else{
return lajumassa;
}
case 4:
if (Percentdaya > 90)
{
yo = 11.534*pow(Pdaya,2) - 14.94*Pdaya + 737.65;
amplitudo = -9.0514*pow(Pdaya,2) + 21.92*Pdaya - 10.695;
perioda = 1.0257*pow(Pdaya,2) - 1.9784*Pdaya + 6.9588;
nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow;
}else{
return lajumassa;
}
break;
case 5:
if (Percentdaya > 90)
{
yo = 13.051*pow(Pdaya,2) - 18.774*Pdaya + 739.93;
amplitudo = 7.6686*pow(Pdaya,2) - 9.5155*Pdaya + 5.6885;
perioda = -0.0086*pow(Pdaya,2) + 0.0161*Pdaya + 6.0109;
nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow;
}else{
return lajumassa;
}
case 6:
if (Percentdaya > 90)
{
yo = 23.376*pow(Pdaya,2) - 37.644*Pdaya + 748.63;
amplitudo = 22.397*pow(Pdaya,2) - 36.617*Pdaya + 19.007;
perioda = -2.1061*pow(Pdaya,2) + 4.0631*Pdaya + 4.0645;
nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow;
}else{
return lajumassa;
}
case 7:
if (Percentdaya > 90)
{
yo = 26.031*pow(Pdaya,2) - 39.495*Pdaya + 748.17;
amplitudo = 25.877*pow(Pdaya,2) - 36.974*Pdaya + 17.626;
perioda = -542.67*pow(Pdaya,4)+ 2226.9*pow(Pdaya,3) - 3415*pow(Pdaya,2) + 2319.3*Pdaya - 582.62;
nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow;
}else{
return lajumassa;
}
case 8:
if (Percentdaya > 70)
{
yo = 372.75*pow(Pdaya,3) - 924*pow(Pdaya,2) + 768.31*Pdaya + 519.62;
amplitudo = 763.49*pow(Pdaya,3) - 1912*pow(Pdaya,2) + 1599.4*Pdaya - 438.36;
perioda = 1.9846*pow(Pdaya,3) - 4.9791*pow(Pdaya,2) + 4.1275*Pdaya + 4.8585;
nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow;
}else{
return lajumassa;
}
}
}
double floatnuc::rollheavemassflow (double Percentdaya, double x)
{
double nilaimassflow, yo, amplitudo, perioda;
double Pdaya = Percentdaya/100;
switch(SeaState)
{
case 0:
return lajumassa;
case 1:
if (Percentdaya > 90)
{
yo = 0.42*pow(Pdaya,2)+ 4.8422*Pdaya + 728.83;
amplitudo = 0.06*pow(Pdaya,2) - 0.0038*Pdaya + 0.0353;
perioda = 217.87*pow(Pdaya,3) - 673.16*pow(Pdaya,2)+ 692.5*Pdaya - 229.17;
nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow;
}else{
return lajumassa;
}
case 2:
if (Percentdaya > 90)
{
yo = 0.41*pow(Pdaya,2) + 4.8645*Pdaya + 728.81;
amplitudo =0.04*pow(Pdaya,2) + 0.058*Pdaya + 0.0077;
perioda = 3E-08*pow(Pdaya,3) + 9E-08*pow(Pdaya,2) - 1E-07*Pdaya + 8.91;
nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow;
}else{
return lajumassa;
}
case 3:
if (Percentdaya > 90)
{
yo = 0.38*pow(Pdaya,2) + 4.9054*Pdaya + 728.79;
amplitudo = 0.27*pow(Pdaya,2) - 0.0577*Pdaya + 0.1707;
perioda = 4.48*pow(Pdaya,2) - 9.4528*Pdaya + 14.36;
nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow;
}else{
return lajumassa;
}
case 4:
if (Percentdaya > 90)
{
yo = 0.35*pow(Pdaya,2) + 4.9519*Pdaya + 728.75;
amplitudo = 0.61*pow(Pdaya,2) - 0.1643*Pdaya + 0.395;
perioda = -6E-11*pow(Pdaya,2) + 1E-10*Pdaya + 10.376;
nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow;
}else{
return lajumassa;
}
case 5:
if (Percentdaya > 90)
{
yo = 2.72*pow(Pdaya,2) - 0.186*Pdaya + 731.33;
amplitudo = 0.94*pow(Pdaya,2) - 0.1198*Pdaya + 0.5445;
perioda = -930.13*pow(Pdaya,3) + 2898*pow(Pdaya,2) - 3005.5*Pdaya + 1048.6;
nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow;
}else{
return lajumassa;
}
case 6:
if (Percentdaya > 90)
{
yo = 0.8*pow(Pdaya,2) + 3.9372*Pdaya + 729.25;
amplitudo = 0.92*pow(Pdaya,2) - 0.014*Pdaya + 0.5448;
perioda = 315.2*pow(Pdaya,3) - 961.36*pow(Pdaya,2) + 975.54*Pdaya - 318.02;
nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow;
}else{
return lajumassa;
}
case 7:
if (Percentdaya > 90)
{
yo = -82.4*pow(Pdaya,3) + 250.16*pow(Pdaya,2) - 247.01*Pdaya + 813.28;
amplitudo = -793.2*pow(Pdaya,3) + 2460.7*pow(Pdaya,2) - 2537.5*Pdaya + 871.65;
perioda = -5059.6*pow(Pdaya,2) + 10625*Pdaya - 5565.6;
nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow;
}else{
return lajumassa;
}
case 8:
if (Percentdaya > 90)
{
yo = -29.83*pow(Pdaya,2) + 67.364*Pdaya + 696.71;
amplitudo = 14.667*pow(Pdaya,3) + 5.5*pow(Pdaya,2) - 53.904*Pdaya + 36.55;
perioda = -989.02*pow(Pdaya,2) + 2092.3*Pdaya - 1094.5;
nilaimassflow = yo + (amplitudo*sin(2*3.143684*x/perioda));return nilaimassflow;
}else{
return lajumassa;
}
}
}
double floatnuc::fungsimassflow(double Percentdaya, double x)
{
double massflow;
switch (ShipMovement)
{
case 0:
massflow = pitchheavemassflow(Percentdaya, x);
return massflow;
case 1:
massflow = rollheavemassflow(Percentdaya, x);
return massflow;
}
}
double floatnuc::pitchheavereaktivitas (double Percentdaya, double x)
{
double reaktivitasvoid;
double nilaivoid, yo, amplitudo, perioda;
double Pdaya = Percentdaya/100;
switch(SeaState)
{
case 0:
reaktivitasvoid = 0;
Y[10] = 0;
return reaktivitasvoid;
case 1:
if (Percentdaya > 90)
{
yo = 2.0486*pow(Pdaya,4) - 7.9587*pow(Pdaya,3) + 11.584*pow(Pdaya,2) - 7.4865*Pdaya + 1.8127;
amplitudo = 0.0329*pow(Pdaya,3) - 0.0958*pow(Pdaya,2) + 0.0928*Pdaya - 0.0299;
perioda = -24000*pow(Pdaya,4) + 95200*pow(Pdaya,3) - 141300*pow(Pdaya,2) + 93014*Pdaya - 22914;
nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda));
if (nilaivoid < 0){
Y[10] = 0;
return reaktivitasvoid = 0;
} else if (nilaivoid > 0){
Y[10] = nilaivoid*100;
//Koefisien dalam (dk/k)/persen
reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;}
} else {return reaktivitasvoid = 0;}
break;
case 2:
if (Percentdaya > 90)
{
yo = 0.1771*pow(Pdaya,2) - 0.3079*Pdaya + 0.1337;
amplitudo = -4*pow(Pdaya,4) + 15.867*pow(Pdaya,3) - 23.49*pow(Pdaya,2) + 15.403*Pdaya - 3.7784;
perioda = -7E-15*Pdaya + 0.2995;
nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda));
if (nilaivoid < 0){
Y[10] = 0;
return reaktivitasvoid = 0;
} else if (nilaivoid > 0){
Y[10] = nilaivoid*100;
//Koefisien dalam (dk/k)/persen
reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;}
} else {return reaktivitasvoid = 0;}
break;
case 3:
if (Percentdaya > 90)
{
yo = 4.8314*pow(Pdaya,4) - 18.831*pow(Pdaya,3) + 27.494*pow(Pdaya,2) - 17.823*Pdaya + 4.3282;
amplitudo = 3.2921*pow(Pdaya,4) - 12.846*pow(Pdaya,3) + 18.778*pow(Pdaya,2) - 12.186*Pdaya + 2.9623;
perioda = 59839*pow(Pdaya,4) - 241351*pow(Pdaya,3) + 364270*pow(Pdaya,2) - 243809*Pdaya + 61053;
nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda));
if (nilaivoid < 0){
Y[10] = 0;
return reaktivitasvoid = 0;
} else if (nilaivoid > 0){
Y[10] = nilaivoid*100;
//Koefisien dalam (dk/k)/persen
reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;}
} else {return reaktivitasvoid = 0;}
break;
case 4:
if (Percentdaya > 90)
{
yo = 2.0503*pow(Pdaya,4) - 8.1396*pow(Pdaya,3) + 12.252*pow(Pdaya,2) - 8.2593*Pdaya + 2.0979;
amplitudo = -1.2469*pow(Pdaya,4) + 4.5788*pow(Pdaya,3) - 6.0721*pow(Pdaya,2) + 3.4353*Pdaya - 0.6932;
perioda = -1.1333*pow(Pdaya,3) + 3.4914*pow(Pdaya,2) - 3.56*Pdaya + 4.1942;
nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda));
if (nilaivoid < 0){
Y[10] = 0;
return reaktivitasvoid = 0;
} else if (nilaivoid > 0){
Y[10] = nilaivoid*100;
//Koefisien dalam (dk/k)/persen
reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;}
} else {return reaktivitasvoid = 0;}
break;
case 5:
if (Percentdaya > 90)
{
yo = -3.1926*pow(Pdaya,4) + 12.93*pow(Pdaya,3) - 19.442*pow(Pdaya,2) + 12.886*Pdaya - 3.1801;
amplitudo = -0.2905*pow(Pdaya,3) + 1.0507*pow(Pdaya,2) - 1.1984*Pdaya + 0.4393;
perioda = 0.09*pow(Pdaya,2) - 0.1707*Pdaya + 3.0723;
nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda));
if (nilaivoid < 0){
Y[10] = 0;
return reaktivitasvoid = 0;
} else if (nilaivoid > 0){
Y[10] = nilaivoid*100;
//Koefisien dalam (dk/k)/persen
reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;}
} else {return reaktivitasvoid = 0;}
break;
case 6:
if (Percentdaya > 90)
{
yo = 0.1474*pow(Pdaya,2) - 0.2587*Pdaya + 0.1135;
amplitudo = -5.3333*pow(Pdaya,4) + 20.667*pow(Pdaya,3) - 29.807*pow(Pdaya,2) + 19.001*Pdaya - 4.5245;
perioda = 2.6667*pow(Pdaya,4) - 10.667*pow(Pdaya,3) + 15.973*pow(Pdaya,2) - 10.6*Pdaya + 5.6194;
nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda));
if (nilaivoid < 0){
Y[10] = 0;
return reaktivitasvoid = 0;
} else if (nilaivoid > 0){
Y[10] = nilaivoid*100;
//Koefisien dalam (dk/k)/persen
reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;}
} else {return reaktivitasvoid = 0;}
break;
case 7:
if (Percentdaya > 90)
{
yo = 0.1371*pow(Pdaya,2) - 0.2267*Pdaya + 0.0937;
amplitudo = 0.1*pow(Pdaya,2) - 0.1358*Pdaya + 0.0425;
perioda = -0.0057*pow(Pdaya,2) + 0.0206*Pdaya + 2.9778;
nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda));
if (nilaivoid < 0){
Y[10] = 0;
return reaktivitasvoid = 0;
} else if (nilaivoid > 0){
Y[10] = nilaivoid*100;
//Koefisien dalam (dk/k)/persen
reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;}
} else {return reaktivitasvoid = 0;}
break;
case 8:
if (Percentdaya > 70)
{
yo = -0.1246*pow(Pdaya,3) + 0.4406*pow(Pdaya,2) - 0.4364*Pdaya + 0.1324;
amplitudo = -0.3392*pow(Pdaya,3) + 1.0276*pow(Pdaya,2) - 0.9425*Pdaya + 0.27265;
perioda = -0.0059*pow(Pdaya,2) + 0.0144*Pdaya + 2.9843;
nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda));
if (nilaivoid < 0){
Y[10] = 0;
return reaktivitasvoid = 0;
} else if (nilaivoid > 0){
Y[10] = nilaivoid*100;
//Koefisien dalam (dk/k)/persen
reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;}
} else {return reaktivitasvoid = 0;}
break;
}
}
double floatnuc::rollheavereaktivitas (double Percentdaya, double x)
{
double reaktivitasvoid;
double nilaivoid, yo, amplitudo, perioda;
double Pdaya = Percentdaya/100;
switch(SeaState)
{
case 0:
reaktivitasvoid = 0;
Y[10] = 0;
return reaktivitasvoid;
case 1:
if (Percentdaya > 95)
{
yo = 0.4529*pow(Pdaya,3) - 1.3552*pow(Pdaya,2) + 1.3509*Pdaya - 0.4486;
amplitudo = 0.0124*pow(Pdaya,3) - 0.0372*pow(Pdaya,2) + 0.0372*Pdaya - 0.0124;
perioda = 10674*pow(Pdaya,3) - 33622*pow(Pdaya,2) + 35275*Pdaya - 12319;
nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda));
if (nilaivoid < 0){
Y[10] = 0;
return reaktivitasvoid = 0;
} else if (nilaivoid > 0){
Y[10] = nilaivoid*100;
//Koefisien dalam (dk/k)/persen
reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;}
} else {return reaktivitasvoid = 0;}
break;
case 2:
if (Percentdaya > 95)
{
yo = 0.4529*pow(Pdaya,3) - 1.3552*pow(Pdaya,2) + 1.3509*Pdaya - 0.4486;
amplitudo = 0.0155*pow(Pdaya,3) - 0.0465*pow(Pdaya,2) + 0.0464*Pdaya - 0.0155;
perioda = 11992*pow(Pdaya,3) - 37758*pow(Pdaya,2) + 39600*Pdaya - 13825;
nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda));
if (nilaivoid < 0){
Y[10] = 0;
return reaktivitasvoid = 0;
} else if (nilaivoid > 0){
Y[10] = nilaivoid*100;
//Koefisien dalam (dk/k)/persen
reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;}
} else {return reaktivitasvoid = 0;}
break;
case 3:
if (Percentdaya > 95)
{
yo = 0.4528*pow(Pdaya,3) - 1.355*pow(Pdaya,2) + 1.3507*Pdaya - 0.4485;
amplitudo = 0.0533*pow(Pdaya,3) - 0.1599*pow(Pdaya,2) + 0.1598*Pdaya - 0.0532;
perioda = 12557*pow(Pdaya,3) - 39554*pow(Pdaya,2) + 41501*Pdaya - 14494;
nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda));
if (nilaivoid < 0){
Y[10] = 0;
return reaktivitasvoid = 0;
} else if (nilaivoid > 0){
Y[10] = nilaivoid*100;
//Koefisien dalam (dk/k)/persen
reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;}
} else {return reaktivitasvoid = 0;}
break;
case 4:
if (Percentdaya > 95)
{
yo = 0.4526*pow(Pdaya,3) - 1.3545*pow(Pdaya,2) + 1.3502*Pdaya - 0.4483;
amplitudo = 0.1184*pow(Pdaya,3) - 0.3553*pow(Pdaya,2) + 0.3551*Pdaya - 0.1182;
perioda = 13907*pow(Pdaya,3) - 43805*pow(Pdaya,2) + 45960*Pdaya - 16051;
nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda));
if (nilaivoid < 0){
Y[10] = 0;
return reaktivitasvoid = 0;
} else if (nilaivoid > 0){
Y[10] = nilaivoid*100;
//Koefisien dalam (dk/k)/persen
reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;}
} else {return reaktivitasvoid = 0;}
break;
case 5:
if (Percentdaya > 95)
{
yo = 0.5849*pow(Pdaya,3) - 1.7513*pow(Pdaya,2) + 1.7467*Pdaya - 0.5803;
amplitudo = 0.2596*pow(Pdaya,3) - 0.7788*pow(Pdaya,2) + 0.7782*Pdaya - 0.259;
perioda = 14849*pow(Pdaya,3) - 46775*pow(Pdaya,2) + 49075*Pdaya - 17139;
nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda));
if (nilaivoid < 0){
Y[10] = 0;
return reaktivitasvoid = 0;
} else if (nilaivoid > 0){
Y[10] = nilaivoid*100;
//Koefisien dalam (dk/k)/persen
reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;}
} else {return reaktivitasvoid = 0;}
break;
case 6:
if (Percentdaya > 95)
{
yo = 0.2593*pow(Pdaya,3) - 0.7781*pow(Pdaya,2) + 0.7775*Pdaya - 0.2588;
amplitudo = 0.2593*pow(Pdaya,3) - 0.7781*pow(Pdaya,2)+ 0.7775*Pdaya - 0.2588;
perioda = 15059*pow(Pdaya,3) - 47435*pow(Pdaya,2) + 49769*Pdaya - 17382;
nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda));
if (nilaivoid < 0){
Y[10] = 0;
return reaktivitasvoid = 0;
} else if (nilaivoid > 0){
Y[10] = nilaivoid*100;
//Koefisien dalam (dk/k)/persen
reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;}
} else {return reaktivitasvoid = 0;}
break;
case 7:
if (Percentdaya > 95)
{
yo = 0.4523*pow(Pdaya,3) - 1.3534*pow(Pdaya,2) + 1.3491*Pdaya - 0.4479;
amplitudo = 0.4523*pow(Pdaya,3) - 1.3534*pow(Pdaya,2)+ 1.3491*Pdaya - 0.4479;
perioda = 18223*pow(Pdaya,3) - 57337*pow(Pdaya,2) + 60077*Pdaya - 20951;
nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda));
if (nilaivoid < 0){
Y[10] = 0;
return reaktivitasvoid = 0;
} else if (nilaivoid > 0){
Y[10] = nilaivoid*100;
//Koefisien dalam (dk/k)/persen
reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;}
} else {return reaktivitasvoid = 0;}
break;
case 8:
if (Percentdaya > 95)
{
yo = 0.029*pow(Pdaya,2) - 0.0576*Pdaya + 0.0286;
amplitudo = 0.3809*pow(Pdaya,3) - 1.1423*pow(Pdaya,2) + 1.141*Pdaya - 0.3796;
perioda = 5729.7*pow(Pdaya,3) - 18636*pow(Pdaya,2) + 20187*Pdaya - 7270.7;
nilaivoid = yo + (amplitudo*sin(2*3.143684*x/perioda));
if (nilaivoid < 0){
Y[10] = 0;
return reaktivitasvoid = 0;
} else if (nilaivoid > 0){
Y[10] = nilaivoid*100;
//Koefisien dalam (dk/k)/persen
reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100; return reaktivitasvoid;}
} else {return reaktivitasvoid = 0;}
break;
}
}
double floatnuc::fungsireaktivitasvoid(valarray<double> &Y, double x)
{
double reaktivitasvoid;
if(Y[9] > Tsaturated){
double nilaivoid = 1;
Y[10] = nilaivoid*100;
double reaktivitasvoid = koefreaktivitasvoid * nilaivoid*100;
return reaktivitasvoid;
} else{
switch (ShipMovement)
{
case 0:
reaktivitasvoid = pitchheavereaktivitas(Y[1], x);
return reaktivitasvoid;
case 1:
reaktivitasvoid = rollheavereaktivitas(Y[1], x);
return reaktivitasvoid;
}
}
}
//===================================================================================================================================================================//
//========Moderator Temperature Reactivity Function========//
double floatnuc::fungsireaktivitassuhumoderator(double ysuhu)
{
//Perhitungan Nilai Reaktivitas Suhu Moderator
double reaktivitassuhumoderator = koefsuhumod*(ysuhu-Suhuawalmod );
return reaktivitassuhumoderator;
}
//===================================================================================================================================================================//
//========Fuel Temperature Reactivity Function========//
double floatnuc::fungsireaktivitassuhufuel(double ysuhu)
{
//Perhitungan Nilai Reaktivitas Suhu BB
double reaktivitassuhufuel = koefsuhufuel*(ysuhu-suhuawalfuel);
return reaktivitassuhufuel;
}
//===================================================================================================================================================================//
//========Power Reactivity Function========//
double floatnuc::fungsireaktivitasdaya(double Percentdaya)
{
//Perhitungan Nilai Reaktivitas Daya
double reaktivitasdaya = koefdaya*Percentdaya;
return reaktivitasdaya;
}
//===================================================================================================================================================================//
//========Control Rod Reactivity Function========//
double floatnuc::fungsireaktivitasbatang (double x, valarray<double> Y)
{
//Nilai reaktivitas grup dalam
double reaktivitasgroupdalam = 0.0002*pow(Y[16],4) - 0.0533*pow(Y[16],3) + 4.331*pow(Y[16],2) - 39.798*Y[16];
//Nilai reaktivitas grup antara
double reaktivitasgroupantara = 1E-06*pow(Y[17],5) - 0.0003*pow(Y[17],4) + 0.02*pow(Y[17],3) - 0.1167*pow(Y[17],2) - 0.4026*Y[17];
//Nilai reaktivitas grup Terluar
double reaktivitasgroupterluar1 = -2E-05*pow(Y[18],4) + 0.0032*pow(Y[18],3) - 0.0517*pow(Y[18],2) + 2.7248*Y[18];
double reaktivitasgroupterluar2 = -3E-05*pow(Y[18],4) + 0.0033*pow(Y[18],3) - 0.0367*pow(Y[18],2) + 1.9241*Y[18];
double reaktivitasbatang = reaktivitasgroupantara + 3*reaktivitasgroupdalam + 2*reaktivitasgroupterluar1 + 2*reaktivitasgroupterluar2;
return reaktivitasbatang*1E-5;//convert to dk/k from pcm
}
double floatnuc::PosisiBatangKendali (int pilihan, double yposisi)
{
double ctrlrodspeed;
if(condition_choose == 6){
ctrlrodspeed = scramrodspeed;
}else{
ctrlrodspeed = controlrodspeed;
}
switch (pilihan)
{
case 0:
if(ui->GroupDalam_Slider->value()*1.005 > yposisi && ui->GroupDalam_Slider->value()*0.995 < yposisi)
{
return 0;
} else if (ui->GroupDalam_Slider->value()*1.02 < yposisi){
return -ctrlrodspeed/120*100;//%
} else if (ui->GroupDalam_Slider->value()*0.995 > yposisi){
return ctrlrodspeed/120*100;//%
}break;
case 1:
if(ui->GroupAntara_Slider->value()*1.005 > yposisi && ui->GroupAntara_Slider->value()*0.995 < yposisi)
{
return 0;
} else if (ui->GroupAntara_Slider->value()*1.02 < yposisi){
return -ctrlrodspeed/120*100;//%
} else if (ui->GroupAntara_Slider->value()*0.995 > yposisi){
return ctrlrodspeed/120*100;//%
}break;
case 2:
if(ui->GroupTerluar_Slider->value()*1.005 > yposisi && ui->GroupTerluar_Slider->value()*0.995 < yposisi)
{
return 0;
} else if (ui->GroupTerluar_Slider->value()*1.02 < yposisi){
return -ctrlrodspeed/120*100;//%
} else if (ui->GroupTerluar_Slider->value()*0.995 > yposisi){
return ctrlrodspeed/120*100;//%
}break;
}
}
//===================================================================================================================================================================//
//========Xenon Reactivity Function========//
double floatnuc::fungsireaktivitasxenon (double yxenon)
{
//Nilai Koefisien xenon
double koefxenon = -1E-3;//= 1 mk
double yxenonawal = 0;//atom/cm3
//Perhitungan Nilai Reaktivitas Xenon
double reaktivitasxenon = koefxenon*(yxenon-yxenonawal)*6E-16;//6x10^16 atom = 1 mk
return reaktivitasxenon;
}
//===================================================================================================================================================================//
//========Samarium Reactivity Function========//
double floatnuc::fungsireaktivitassamarium (double ysamarium)
{
//Nilai Koefisien samarium
double koefsamarium = -1E-3*0.1825;// = 0.1825* 1 mk
double ysamariumawal = 0;//atom/cm3
//Perhitungan Nilai Reaktivitas Samarium
double reaktivitassamarium = koefsamarium*(ysamarium-ysamariumawal)*6E-16; //6x10^16 atom = 1 mk
return reaktivitassamarium;
}
//===================================================================================================================================================================//
//========Total Reactivity Function========//
double floatnuc::fungsireaktivitastotal (valarray<double> &Y, double x)
{
//Memanggil Subprogram Reaktivitas Batang
double reaktivitasbatang = fungsireaktivitasbatang(x,Y);
Y[4] = reaktivitasbatang;
//Memanggil Subprogram Reaktivitas Akibat Daya
double reaktivitasdaya = fungsireaktivitasdaya(Y[1]);
//Memanggil Subprogram Reaktivitas Akibat Suhu Reaktor
double reaktivitassuhufuel = fungsireaktivitassuhufuel(Y[8]);
//Memanggil Subprogram Reaktivitas Akibat Suhu Reaktor
double reaktivitassuhumoderator = fungsireaktivitassuhumoderator(Y[9]);
//Memanggil Subprogram Reaktivitas Akibat Xenon
double reaktivitasxenon = fungsireaktivitasxenon(Y[11]);
Y[5] = reaktivitasxenon;
//Memanggil Subprogram Reaktivitas Akibat Samarium
double reaktivitassamarium = fungsireaktivitassamarium(Y[12]);
Y[6] = reaktivitassamarium;
//Memanggil Subprogram Reaktivitas Akibat Adanya Void
double reaktivitasvoid = fungsireaktivitasvoid(Y,x);
Y[7] = reaktivitasvoid;
//Menghitung Nilai Reaktivitas total
double reaktivitastotal = reaktivitasvoid + reaktivitasdaya + reaktivitasbatang
+ reaktivitassuhufuel + reaktivitassuhumoderator + reaktivitassamarium + reaktivitasxenon + reaktivitastambahan; //in %
return reaktivitastotal;
}
valarray<double> floatnuc::F( double x, valarray<double> y )
{
valarray<double> f( y.size() ); // Array for differential equation depends on the size of the data
//Power Equation
f[0] = ((y[3] - beta)/prompt*y[0]) + ((lamdagrup1)*y[21] + (lamdagrup2)*y[22] + (lamdagrup3)*y[23]
+ (lamdagrup4)*y[24] + (lamdagrup5)*y[25] + (lamdagrup6)*y[26]);
//Power Percent Equation
//f[1] = 0;
//Fluks Equation
//f[2] = 0;
//Total Reactivity Equation
//f[3] = 0;
//Control Rod Reactivity Equation
//f[4] = 0;
//Xenon Reactivity Equation
//f[5] = 0;
//Samarium Reactivity Equation
//f[6] = 0;
//Void Reactivity Equation
//f[7] = 0;
//Fuel Equation
f[8] = (y[0]*1E6 - h*a*(y[8]-y[9]))/(mfuel*cpfuel);
//Persamaan Suhu Pendingin
double cpmoderator = heatcapacitymoderator(y);
double mpendingin = massmoderator(y);
double hpendingin = convectionheattransfercoefficient(y);
f[9] = (hpendingin*a*(y[8]-y[9])
- (y[27]*cpmoderator*(Y[28] - Tin)))/(mpendingin*cpmoderator);
//Void Fraction
//f[10] = 0;
//iodine equation
f[13] = (yieldiodine*fissioncrosssection*y[2]) - lamdaiodine*y[13];
//xenon equation
f[11] = (yieldxenon*fissioncrosssection*y[2]) + (lamdaiodine*y[13])
- (lamdaxenon*y[11] + sigmaabsorptionxenon * y[11] * y[2]);
//promethium Equation
f[14] = (yieldpromethium*fissioncrosssection*y[2]) - (lamdapromethium * y[14]);
//samarium Equation
f[12] = (lamdapromethium*y[14]) - (sigmaabsorptionsamarium*y[2]*y[12]);
//Reactor Period
//f[15] = 0;
//Control Rod Positions Equation
f[16] = PosisiBatangKendali(0,Y[16]);
f[17] = PosisiBatangKendali(1,Y[17]);
f[18] = PosisiBatangKendali(2,Y[18]);
//Total Precursor
//f[20] = 0;
//Precursor Equation
//Grup 1
f[21] = (betagrup1/prompt*y[0])-(lamdagrup1*y[21]);
//Grup 2
f[22] = (betagrup2/prompt*y[0])-(lamdagrup2*y[22]);
//Grup 3
f[23] = (betagrup3/prompt*y[0])-(lamdagrup3*y[23]);
//Grup 4
f[24] = (betagrup4/prompt*y[0])-(lamdagrup4*y[24]);
//Grup 5
f[25] = (betagrup5/prompt*y[0])-(lamdagrup5*y[25]);
//Grup 6
f[26] = (betagrup6/prompt*y[0])-(lamdagrup6*y[26]);
//Mass Flow
//f[27] = 0;//Kg/s
// ****************************************
return f;
}
void floatnuc::step( double dx, double &x, valarray<double> &Y )
{
qApp->processEvents();
valarray<double> dY1(ndep), dY2(ndep), dY3(ndep), dY4(ndep);
dY1 = F( x , Y ) * dx;
dY2 = F( x + 0.5 * dx, Y + 0.5 * dY1 ) * dx;
dY3 = F( x + 0.5 * dx, Y + 0.5 * dY2 ) * dx;
dY4 = F( x + dx, Y + dY3 ) * dx;
Y += ( dY1 + 2.0 * dY2 + 2.0 * dY3 + dY4 ) / 6.0;
x += dx;
}
void floatnuc::initialcondition(valarray<double> &Y)
{
//Initial Condition
Y[0] = 50; //Daya in MWth
Y[1] = Y[0]/fullpower*100;//PowerPercent
Y[2] = Y[0]/(convertpowertofluks*reactorvol*fissioncrosssection); //Fluks in n/cm2*s
Y[20] = beta*Y[0]/(lamdagrup4*prompt); //Prekursor
Y[8] = 839; //Suhu Fuel in K
Y[9] = 553; //Suhu Moderator in K
Y[3] = 0; //Reaktivitas
Y[13] = 0; //Iodine in atom/cm3
Y[11] = 0; //Xenon in atom/cm3
Y[14] = 0; //Promethium atom/cm3
Y[12] = 0; //Samarium atom/cm3
Y[15] = neutronlifetime/Y[3];//Reactor period
Y[16] = 35; //ControlRodPositionDalam %
Y[17] = 35; //ControlRodPositionAntara %
Y[18] = 35; //ControlRodPositionLuar %
Y[27] = lajumassa;//Kg/s
Y[28] = 553; //Suhu Keluaran Moderator in K
ui->GroupDalam_Slider->setValue(Y[16]);
ui->GroupAntara_Slider->setValue(Y[17]);
ui->GroupTerluar_Slider->setValue(Y[18]);
}
void floatnuc::engine()
{
// Set initial values
double x = xo;
//This is the step number
double nstep = (xn - xo) / dx;
if (x == 0.0){
initialcondition(Y);
}else{
tampilhasil(x, Y);
}
simpanhasil(x, Y);
// Solve the differential equation using nstep intervals
for ( int n = 0; n < nstep; n++ )
{
//The Reactivity and fluxdont need the RK Method
Y[3] = fungsireaktivitastotal( Y, x);
Y[2] = Y[0]/(convertpowertofluks*reactorvol*fissioncrosssection); //Fluks in n/cm2*s
//The Total Prekursor also dont need RK Method
Y[20] = Y[21]+Y[22]+Y[23]+Y[24]+Y[25]+Y[26];
//The Reactor Power Percent also dont need RK Method
Y[1] = Y[0]/fullpower*100;//PowerPercent
reactorperiod(x,Y);
//Moderator average temperature Equation
Y[28] = 2 * Y[9] - Tin;
//Dimensionless number
Y[29] = prandtl(Y);
Y[30] = nusselt(Y);
Y[31] = reynold(Y);
condition(x, Y);
// The Main Runge-Kutta step
step( dx, x, Y );
}
//Counting the initial and end condition from engine time
xo+= intervalwaktu/1000;
xn+= intervalwaktu/1000;
}
//Simulation Control
void floatnuc::on_Start_PushButton_clicked()
{
timer->start(100);
ui->Video_Widget->m_mediaPlayer->play();
}
void floatnuc::on_Stop_PushButton_clicked()
{
timer->stop();
ui->Video_Widget->m_mediaPlayer->pause();
}
void floatnuc::on_Update_PushButton_clicked()
{
tampilhasil(xo, Y);
}
//Stacked Widget Control
void floatnuc::on_Start_Button_clicked()
{
ui->stackedWidget->setCurrentIndex(0);
}
void floatnuc::on_Intro_Button_clicked()
{
ui->stackedWidget->setCurrentIndex(1);
}
void floatnuc::on_Save_Button_clicked()
{
ui->stackedWidget->setCurrentIndex(2);
}
void floatnuc::on_Simulation_Button_clicked()
{
ui->stackedWidget->setCurrentIndex(3);
//Set Current Index of Video
//playlist->setCurrentIndex(17);
//ui->Video_Widget->m_mediaPlayer->play();
}
void floatnuc::on_Graph_Button_clicked()
{
ui->stackedWidget->setCurrentIndex(4);
}
void floatnuc::on_Spec_Button_clicked()
{
ui->stackedWidget->setCurrentIndex(5);
}
void floatnuc::on_AboutUs_Button_clicked()
{
ui->stackedWidget->setCurrentIndex(6);
}
void floatnuc::on_Exit_Button_clicked()
{
this->close();
}
void floatnuc::on_ShipMove_Combobox_currentIndexChanged(int index)
{
videocalling(SeaState,index);
}
void floatnuc::on_SeaState_Combobox_currentIndexChanged(int index)
{
videocalling(index, ShipMovement);
}
| 37.841992 | 167 | 0.549833 | rainoverme002 |
07d4775dcd775f15558c912809dde9cfa138fac7 | 6,791 | cpp | C++ | source/solution_zoo/common/xproto_plugins/iotvioplugin/src/iotviomanager/camera/camera_ov10635.cpp | HorizonRobotics-Platform/AI-EXPRESS | 413206d88dae1fbd465ced4d60b2a1769d15c171 | [
"BSD-2-Clause"
] | 98 | 2020-09-11T13:52:44.000Z | 2022-03-23T11:52:02.000Z | source/solution_zoo/common/xproto_plugins/iotvioplugin/src/iotviomanager/camera/camera_ov10635.cpp | HorizonRobotics-Platform/ai-express | 413206d88dae1fbd465ced4d60b2a1769d15c171 | [
"BSD-2-Clause"
] | 8 | 2020-10-19T14:23:30.000Z | 2022-03-16T01:00:07.000Z | source/solution_zoo/common/xproto_plugins/iotvioplugin/src/iotviomanager/camera/camera_ov10635.cpp | HorizonRobotics-Platform/AI-EXPRESS | 413206d88dae1fbd465ced4d60b2a1769d15c171 | [
"BSD-2-Clause"
] | 28 | 2020-09-17T14:20:35.000Z | 2022-01-10T16:26:00.000Z | /***************************************************************************
* COPYRIGHT NOTICE
* Copyright 2020 Horizon Robotics, Inc.
* All rights reserved.
***************************************************************************/
#include "iotviomanager/vinparams.h"
namespace horizon {
namespace vision {
namespace xproto {
namespace vioplugin {
MIPI_SENSOR_INFO_S SENSOR_2LANE_OV10635_30FPS_YUV_720P_954_INFO = {
.deseEnable = 1,
.inputMode = INPUT_MODE_MIPI,
.deserialInfo = {
.bus_type = 0,
.bus_num = 4,
.deserial_addr = 0x3d,
.deserial_name = const_cast<char*>("s954")
},
.sensorInfo = {
.port = 0,
.dev_port = 0,
.bus_type = 0,
.bus_num = 4,
.fps = 30,
.resolution = 720,
.sensor_addr = 0x40,
.serial_addr = 0x1c,
.entry_index = 1,
.sensor_mode = {},
.reg_width = 16,
.sensor_name = const_cast<char*>("ov10635"),
.extra_mode = 0,
.deserial_index = 0,
.deserial_port = 0
}
};
MIPI_SENSOR_INFO_S SENSOR_2LANE_OV10635_30FPS_YUV_720P_960_INFO = {
.deseEnable = 1,
.inputMode = INPUT_MODE_MIPI,
.deserialInfo = {
.bus_type = 0,
.bus_num = 1,
.deserial_addr = 0x30,
.deserial_name = const_cast<char*>("s960")
},
.sensorInfo = {
.port = 0,
.dev_port = 0,
.bus_type = 0,
.bus_num = 4,
.fps = 30,
.resolution = 720,
.sensor_addr = 0x40,
.serial_addr = 0x1c,
.entry_index = 0,
.sensor_mode = {},
.reg_width = 16,
.sensor_name = const_cast<char*>("ov10635"),
.extra_mode = 0,
.deserial_index = 0,
.deserial_port = 0
}
};
MIPI_ATTR_S MIPI_2LANE_OV10635_30FPS_YUV_720P_954_ATTR = {
.mipi_host_cfg = {
2, /* lane */
0x1e, /* datatype */
24, /* mclk */
1600, /* mipiclk */
30, /* fps */
1280, /* width */
720, /*height */
3207, /* linlength */
748, /* framelength */
30, /* settle */
4,
{0, 1, 2, 3}
},
.dev_enable = 0 /* mipi dev enable */
};
MIPI_ATTR_S MIPI_2LANE_OV10635_30FPS_YUV_720P_960_ATTR = {
.mipi_host_cfg = {
2, /* lane */
0x1e, /* datatype */
24, /* mclk */
3200, /* mipiclk */
30, /* fps */
1280, /* width */
720, /*height */
3207, /* linlength */
748, /* framelength */
30, /* settle */
4,
{0, 1, 2, 3}
},
.dev_enable = 0 /* mipi dev enable */
};
MIPI_ATTR_S MIPI_2LANE_OV10635_30FPS_YUV_LINE_CONCATE_720P_960_ATTR = {
.mipi_host_cfg = {
2, /* lane */
0x1e, /* datatype */
24, /* mclk */
3200, /* mipiclk */
30, /* fps */
1280, /* width */
720, /* height */
3207, /* linlength */
748, /* framelength */
30, /* settle */
2,
{0, 1}
},
.dev_enable = 0 /* mipi dev enable */
};
VIN_DEV_ATTR_S DEV_ATTR_OV10635_YUV_BASE = {
.stSize = {
8, /*format*/
1280, /*width*/
720, /*height*/
0 /*pix_length*/
},
{
.mipiAttr = {
.enable = 1,
.ipi_channels = 1,
.ipi_mode = 0,
.enable_mux_out = 1,
.enable_frame_id = 1,
.enable_bypass = 0,
.enable_line_shift = 0,
.enable_id_decoder = 0,
.set_init_frame_id = 1,
.set_line_shift_count = 0,
.set_bypass_channels = 1,
},
},
.DdrIspAttr = {
.stride = 0,
.buf_num = 4,
.raw_feedback_en = 0,
.data = {
.format = 8,
.width = 1280,
.height = 720,
.pix_length = 0,
}
},
.outDdrAttr = {
.stride = 1280,
.buffer_num = 8,
},
.outIspAttr = {
.dol_exp_num = 1,
.enable_dgain = 0,
.set_dgain_short = 0,
.set_dgain_medium = 0,
.set_dgain_long = 0,
}
};
VIN_DEV_ATTR_S DEV_ATTR_OV10635_YUV_LINE_CONCATE_BASE = {
.stSize = {
8, /* format */
2560, /* width */
720, /* height */
0 /* pix_length */
},
{
.mipiAttr = {
.enable = 1,
.ipi_channels = 1,
.ipi_mode = 0,
.enable_mux_out = 1,
.enable_frame_id = 1,
.enable_bypass = 0,
.enable_line_shift = 0,
.enable_id_decoder = 0,
.set_init_frame_id = 1,
.set_line_shift_count = 0,
.set_bypass_channels = 1,
},
},
.DdrIspAttr = {
.stride = 0,
.buf_num = 4,
.raw_feedback_en = 0,
.data = {
.format = 8,
.width = 2560,
.height = 720,
.pix_length = 0,
}
},
.outDdrAttr = {
.stride = 2560,
.buffer_num = 8,
},
.outIspAttr = {
.dol_exp_num = 1,
.enable_dgain = 0,
.set_dgain_short = 0,
.set_dgain_medium = 0,
.set_dgain_long = 0,
}
};
VIN_DEV_ATTR_EX_S DEV_ATTR_OV10635_MD_BASE = {
.path_sel = 1,
.roi_top = 0,
.roi_left = 0,
.roi_width = 1280,
.roi_height = 640,
.grid_step = 128,
.grid_tolerance = 10,
.threshold = 10,
.weight_decay = 128,
.precision = 0
};
VIN_PIPE_ATTR_S PIPE_ATTR_OV10635_YUV_BASE = {
.ddrOutBufNum = 8,
.frameDepth = 0,
.snsMode = SENSOR_NORMAL_MODE,
.stSize = {
.format = 0,
.width = 1280,
.height = 720,
},
.cfaPattern = PIPE_BAYER_RGGB,
.temperMode = 0,
.ispBypassEn = 1,
.ispAlgoState = 0,
.bitwidth = 12,
.startX = 0,
.startY = 0,
.calib = {
.mode = 0,
.lname = NULL,
}
};
VIN_PIPE_ATTR_S VIN_ATTR_OV10635_YUV_LINE_CONCATE_BASE = {
.ddrOutBufNum = 8,
.frameDepth = 0,
.snsMode = SENSOR_NORMAL_MODE,
.stSize = {
.format = 0,
.width = 2560,
.height = 720,
},
.cfaPattern = PIPE_BAYER_RGGB,
.temperMode = 0,
.ispBypassEn = 1,
.ispAlgoState = 0,
.bitwidth = 12,
.startX = 0,
.startY = 0,
.calib = {
.mode = 0,
.lname = NULL,
}
};
VIN_DIS_ATTR_S DIS_ATTR_OV10635_BASE = {
.picSize = {
.pic_w = 1279,
.pic_h = 719,
},
.disPath = {
.rg_dis_enable = 0,
.rg_dis_path_sel = 1,
},
.disHratio = 65536,
.disVratio = 65536,
.xCrop = {
.rg_dis_start = 0,
.rg_dis_end = 1279,
},
.yCrop = {
.rg_dis_start = 0,
.rg_dis_end = 719,
}
};
VIN_LDC_ATTR_S LDC_ATTR_OV10635_BASE = {
.ldcEnable = 0,
.ldcPath = {
.rg_y_only = 0,
.rg_uv_mode = 0,
.rg_uv_interpo = 0,
.reserved1 = 0,
.rg_h_blank_cyc = 32,
.reserved0 = 0
},
.yStartAddr = 524288,
.cStartAddr = 786432,
.picSize = {
.pic_w = 1279,
.pic_h = 719,
},
.lineBuf = 99,
.xParam = {
.rg_algo_param_b = 1,
.rg_algo_param_a = 1,
},
.yParam = {
.rg_algo_param_b = 1,
.rg_algo_param_a = 1,
},
.offShift = {
.rg_center_xoff = 0,
.rg_center_yoff = 0,
},
.xWoi = {
.rg_start = 0,
.reserved1 = 0,
.rg_length = 1279,
.reserved0 = 0
},
.yWoi = {
.rg_start = 0,
.reserved1 = 0,
.rg_length = 719,
.reserved0 = 0
}
};
} // namespace vioplugin
} // namespace xproto
} // namespace vision
} // namespace horizon
| 19.973529 | 77 | 0.537329 | HorizonRobotics-Platform |
07d64c4840b6f9c8bcb8847a08cea837bb9460a7 | 1,420 | cpp | C++ | cpp/multiply_string.cpp | caleberi/LeetCode | fa170244648f73e76d316a6d7fc0e813adccaa82 | [
"MIT"
] | 1 | 2021-08-10T20:00:24.000Z | 2021-08-10T20:00:24.000Z | cpp/multiply_string.cpp | caleberi/LeetCode | fa170244648f73e76d316a6d7fc0e813adccaa82 | [
"MIT"
] | null | null | null | cpp/multiply_string.cpp | caleberi/LeetCode | fa170244648f73e76d316a6d7fc0e813adccaa82 | [
"MIT"
] | 3 | 2021-06-11T11:56:39.000Z | 2021-08-10T08:50:49.000Z | #include <string>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
/**
* @brief function to mutliply two numbers.
* this is not an optimal solution as it can't be stored due to
* memory size
* @param num1 string to be multiplied
* @param num2 string to multipy with
* @return string
*/
string multiply(string num1, string num2) {
long long n1 = 0;
long long p = 1;
for(int i=num1.size()-1;i>=0;i--){
n1+= (num1[i]-48)*p;
p*=10;
}
long long n2=0;
p = 1;
for(int i=num2.size()-1;i>=0;i--){
n2+= (num2[i]-48)*p;
p*=10;
}
long long int n = n2 * n1;
return to_string(n);
}
string multiply_v2(string num1,string num2){
if (num1.size()==0 || num2.size()==0){
return "";
}
vector<int> res(num1.size()+num2.size(),0);
for (int i=num1.size()-1; i>=0;i--){
for (int j=num2.size()-1;j>=0;j--){
res[i+j+1] += (num2[i]-48) * (num1[i]-48);
res[i+j] += res[i+j+1]/10;
res[i+j+1] %= 10;
}
}
int i=0;
string ans="";
while (res[i] == 0) i++;
while (i < res.size()) ans+=to_string(res[i++]);
return ans;
}
}; | 25.357143 | 68 | 0.457746 | caleberi |
07d6a85081e2f35a2f51806f61a606750c1a47a3 | 5,906 | cc | C++ | apps/grid.cc | CS126SP20/Game-of-Life | a626f94ccd5ab1f93cefa2c37fc4868fbc0ba6bd | [
"MIT"
] | null | null | null | apps/grid.cc | CS126SP20/Game-of-Life | a626f94ccd5ab1f93cefa2c37fc4868fbc0ba6bd | [
"MIT"
] | null | null | null | apps/grid.cc | CS126SP20/Game-of-Life | a626f94ccd5ab1f93cefa2c37fc4868fbc0ba6bd | [
"MIT"
] | null | null | null | // Copyright (c) 2020 [Swathi Ram]. All rights reserved.
#include "../include/mylibrary/grid.h"
namespace mylibrary {
/*
* Overridden function that does not take in a parameter if the grid has
* stabilized. Used if the user has chosen to pause the automaton or if it
* is the first call to the calculation of the configuration.
*/
std::vector<std::vector<int>>& Grid::GetCurrentGrid() {
return grids_[gen_id_ % 2];
}
/*
* Helper method to check which grid to use as the current vs. the next
* generation. This method facilitates the ping pong effect between the two
* grids. If the next generation should be calculated, an even id prompts the
* calculated using the first grid as the current and the second as the next
* generation to be added to. An odd id uses the next generation that was
* previously calculated as the current and fills out the other grid with the
* next generation of that grid.
* @param calculate_next_gen: boolean to check whether next generation should
* be calculated
* @return: returns the grid containing the current cell configuration
*/
std::vector<std::vector<int>>& Grid::GetCurrentGrid(bool& did_gen_change_) {
if (gen_id_ % 2 == 0) {
CalculateNextGeneration(grids_[0], grids_[1]);
} else {
CalculateNextGeneration(grids_[1], grids_[0]);
}
did_gen_change_ = DidGridChange();
return grids_[gen_id_ % 2];
}
/*
* Helper method to resize the 3D vector of grids and fill in the grid's cell
* configuration based on the coordinates from the json file read into seed
* from cell_automaton.cc. The dimension of the 3D vector dealing with the
* grids is resized to 2 to account for the current and next generation of
* cells. The next two dimensions are resized to the passed in dimensions. The
* cell configuration is set to 1 if a cell exists at the coordinate and is kept
* as 0 if not.
* @param dimension: passed in size of the grid
* @param seed: vector containing coordinates of cells from json file
*/
void Grid::SetDimensionAndFillSeeds(int dimension,
std::vector<std::vector<int>> seed) {
grid_dimension_ = dimension;
// first level
grids_.resize(2);
// second level
grids_[0].resize(dimension);
grids_[1].resize(dimension);
// third level
for (int i = 0; i < 2; i++) {
for (int j = 0; j < dimension; j++) {
grids_[i][j].resize(dimension);
}
}
for (int i = 0; i < seed.size(); i++) {
assert((seed[i][0]) < grid_dimension_);
assert((seed[i][1]) < grid_dimension_);
grids_[0][seed[i][0]][seed[i][1]] = 1;
}
}
/*
* Helper method to compare two grids for equality. Used to check when the
* cell configuration has stabilized as the grids will be equal when no more
* generations can be calculated.
* @return: Boolean for if the grids are the same in each position
*/
bool Grid::DidGridChange() {
for (int i = 0; i < grid_dimension_; i++) {
for (int j = 0; j < grid_dimension_; j++) {
if (grids_[0][i][j] != grids_[1][i][j]) {
return true;
}
}
}
return false;
}
/*
* Helper method dealing with the main logic of calculating the next generation
* of cells. Method is passed in two grids- the current generation of cells to
* use for cell information and the next generation to be calculated and filled
* in with the cells at their calculated position. The calculations follow the
* fundamental rules of the Game of life:
* 1. Any live cell with fewer than two live neighbours dies.
* 2. Any live cell with two or three live neighbours lives.
* 3. Any live cell with more than three live neighbours dies.
* 4. Any dead cell with exactly three live neighbours becomes a live cell.
* At the end of the method, the gen_id_ is incremented to
* allow the switch between grids by the next call.
* @param curr_gen_: current generation of cell configurations
* @param next_gen_: next generation of cell configurations
*/
void Grid::CalculateNextGeneration(std::vector<std::vector<int>>& curr_gen_,
std::vector<std::vector<int>>& next_gen_) {
for (int i = 0; i < curr_gen_.size(); i++) {
for (int j = 0; j < curr_gen_.size(); j++) {
int state = curr_gen_[i][j];
// account for edge cells
if (i == 0 || i == curr_gen_.size() - 1 || j == 0 ||
j == curr_gen_.size() - 1) {
next_gen_[i][j] = state;
} else {
size_t num_neighbors = CountNeighbors(curr_gen_, i, j);
if (state == 1 && num_neighbors < 2) {
next_gen_[i][j] = 0;
} else if (state == 1 && num_neighbors > 3) {
next_gen_[i][j] = 0;
} else if (state == 0 && (num_neighbors == 3)) {
next_gen_[i][j] = 1;
} else {
next_gen_[i][j] = state;
}
}
}
}
gen_id_++;
}
/*
* Helper method to count the number of surrounding cells around a particular
* cell at the passed in location on the grid. Calculates neighbors by adding
* the label of the cell (1 or 0).
* @param grid: cell grid containing the cell configuration information
* @param x: x coordinate of the cell
* @param y: y coordinate of the cell
* @return: method returns the numbers of neighbors of a particular cell
*/
size_t Grid::CountNeighbors(std::vector<std::vector<int>>& grid, int x, int y) {
size_t num_neighbors = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
num_neighbors += grid[x + i][y + j]; // 0's and 1's so add for sum
}
}
num_neighbors -= grid[x][y];
return num_neighbors;
}
/*
* Helper method to support restarting the automaton when the user chooses.
* Clears the grids, setting all positions to 0.
*/
void Grid::ResetGrid() {
for (int i = 0; i < grid_dimension_; i++) {
for (int j = 0; j < grid_dimension_; j++) {
grids_[0][i][j] = 0;
grids_[1][i][j] = 0;
}
}
gen_id_ = 0;
}
} // namespace mylibrary
| 35.365269 | 80 | 0.655943 | CS126SP20 |
07d784af7e9a54228587adeedc00ebc09ff5c2f6 | 13,206 | cpp | C++ | transport/RecordingTransport.cpp | marcusspangenberg/SymphonyMediaBridge | b46eb38ec5585e1280720a20170ef505fdd2a4c9 | [
"Apache-2.0"
] | 13 | 2021-11-24T09:55:32.000Z | 2022-03-25T12:29:50.000Z | transport/RecordingTransport.cpp | marcusspangenberg/SymphonyMediaBridge | b46eb38ec5585e1280720a20170ef505fdd2a4c9 | [
"Apache-2.0"
] | 10 | 2021-11-23T15:21:41.000Z | 2022-03-28T08:37:59.000Z | transport/RecordingTransport.cpp | marcusspangenberg/SymphonyMediaBridge | b46eb38ec5585e1280720a20170ef505fdd2a4c9 | [
"Apache-2.0"
] | 4 | 2021-11-23T14:58:44.000Z | 2022-03-13T12:11:00.000Z | #include "transport/RecordingTransport.h"
#include "codec/Opus.h"
#include "codec/Vp8.h"
#include "config/Config.h"
#include "rtp/RtcpHeader.h"
#include "rtp/RtpHeader.h"
#include "transport/DataReceiver.h"
#include "transport/RtpSenderState.h"
#include "transport/recp/RecControlHeader.h"
#include "transport/recp/RecStreamAddedEvent.h"
#include "transport/recp/RecStreamRemovedEvent.h"
namespace transport
{
// Placed last in queue during shutdown to reduce ref count when all jobs are complete.
// This means other jobs in the transport job queue do not have to have counters
class ShutdownJob : public jobmanager::CountedJob
{
public:
explicit ShutdownJob(std::atomic_uint32_t& ownerCount) : CountedJob(ownerCount) {}
void run() override {}
};
std::unique_ptr<RecordingTransport> createRecordingTransport(jobmanager::JobManager& jobManager,
const config::Config& config,
RecordingEndpoint* recordingEndpoint,
const size_t endpointIdHash,
const size_t streamIdHash,
const SocketAddress& peer,
const uint8_t aesKey[32],
const uint8_t salt[12],
memory::PacketPoolAllocator& allocator)
{
return std::make_unique<RecordingTransport>(jobManager,
config,
recordingEndpoint,
endpointIdHash,
streamIdHash,
peer,
aesKey,
salt,
allocator);
}
RecordingTransport::RecordingTransport(jobmanager::JobManager& jobManager,
const config::Config& config,
RecordingEndpoint* recordingEndpoint,
const size_t endpointIdHash,
const size_t streamIdHash,
const SocketAddress& remotePeer,
const uint8_t aesKey[32],
const uint8_t salt[12],
memory::PacketPoolAllocator& allocator)
: _isInitialized(false),
_loggableId("RecordingTransport"),
_config(config),
_endpointIdHash(endpointIdHash),
_streamIdHash(streamIdHash),
_isRunning(true),
_recordingEndpoint(recordingEndpoint),
_peerPort(remotePeer),
_jobCounter(0),
_jobQueue(jobManager),
_aes(nullptr),
_ivGenerator(nullptr),
_previousSequenceNumber(256), // TODO what is a reasonable number?
_rolloverCounter(256), // TODO what is a reasonable number?
_outboundSsrcCounters(256),
_rtcp(config.recordingRtcp.reportInterval),
_allocator(allocator)
{
logger::info("Recording client: %s", _loggableId.c_str(), _peerPort.toString().c_str());
assert(_recordingEndpoint->isGood());
assert(recordingEndpoint->getLocalPort().getFamily() == remotePeer.getFamily());
_recordingEndpoint->registerRecordingListener(_peerPort, this);
++_jobCounter;
_aes = std::make_unique<crypto::AES>(aesKey, 32);
_ivGenerator = std::make_unique<crypto::AesGcmIvGenerator>(salt, 12);
_isInitialized = true;
if (recordingEndpoint->getLocalPort().getFamily() != remotePeer.getFamily())
{
logger::error("ip family mismatch. local ip family: %d, remote ip family: %d",
_loggableId.c_str(),
recordingEndpoint->getLocalPort().getFamily(),
remotePeer.getFamily());
}
}
bool RecordingTransport::start()
{
return _isInitialized && _recordingEndpoint->isGood();
}
void RecordingTransport::stop()
{
logger::debug("stopping jobcount %u, running %u", _loggableId.c_str(), _jobCounter.load(), _isRunning.load());
if (!_isRunning)
{
return;
}
_recordingEndpoint->unregisterRecordingListener(this);
_jobQueue.getJobManager().abortTimedJobs(getId());
_isRunning = false;
}
void RecordingTransport::protectAndSend(memory::UniquePacket packet)
{
if (!isConnected())
{
// Recording events are very important to convertor and must not be lost!
if (recp::isRecPacket(*packet))
{
logger::error("A recording event was not sent because transport is not connected", _loggableId.c_str());
}
return;
}
protectAndSend(std::move(packet), _peerPort, _recordingEndpoint);
}
void RecordingTransport::protectAndSend(memory::UniquePacket packet, const SocketAddress& target, Endpoint* endpoint)
{
assert(packet->getLength() + 24 <= _config.mtu);
if (rtp::isRtpPacket(*packet))
{
auto* rtpHeader = rtp::RtpHeader::fromPacket(*packet);
auto roc = getRolloverCounter(rtpHeader->ssrc, rtpHeader->sequenceNumber);
uint8_t iv[crypto::DEFAULT_AES_IV_SIZE];
_ivGenerator->generateForRtp(rtpHeader->ssrc, roc, rtpHeader->sequenceNumber, iv, crypto::DEFAULT_AES_IV_SIZE);
auto payload = rtpHeader->getPayload();
auto headerLength = rtpHeader->headerLength();
auto payloadLength = packet->getLength() - headerLength;
uint16_t encryptedLength = _config.mtu - headerLength;
_aes->gcmEncrypt(payload,
payloadLength,
reinterpret_cast<unsigned char*>(payload),
encryptedLength,
iv,
crypto::DEFAULT_AES_IV_SIZE,
reinterpret_cast<unsigned char*>(rtpHeader),
headerLength);
packet->setLength(headerLength + encryptedLength);
const auto timestamp = utils::Time::getAbsoluteTime();
auto* senderState = getOutboundSsrc(rtpHeader->ssrc);
// Sometimes we can have a race and end up with a RTP packet before the add stream event or
// we can receive a packet for a stream that was removed already.
// Neither cases cause problems, we just need to force to send a RTCP in the first packet after the
// stream has been registered (as we depend on it to calculate the mute time in beginning)
// and be aware that senderState can be a nullptr
const bool isFirstPacket = senderState && senderState->getLastSendTime() == 0;
if (senderState)
{
senderState->onRtpSent(timestamp, *packet);
}
endpoint->sendTo(target, std::move(packet));
if (isFirstPacket || _rtcp.lastSendTime == 0 ||
utils::Time::diffGT(_rtcp.lastSendTime, timestamp, _rtcp.reportInterval))
{
sendRtcpSenderReport(_allocator, timestamp);
}
}
else if (recp::isRecPacket(*packet))
{
auto recHeader = recp::RecHeader::fromPacket(*packet);
auto payload = recHeader->getPayload();
if (recHeader->event == recp::RecEventType::StreamAdded)
{
onSendingStreamAddedEvent(*packet);
}
else if (recHeader->event == recp::RecEventType::StreamRemoved)
{
onSendingStreamRemovedEvent(*packet);
}
uint8_t iv[crypto::DEFAULT_AES_IV_SIZE];
_ivGenerator->generateForRec(static_cast<uint8_t>(recHeader->event),
recHeader->sequenceNumber,
recHeader->timestamp,
iv,
crypto::DEFAULT_AES_IV_SIZE);
auto payloadLength = packet->getLength() - recp::REC_HEADER_SIZE;
uint16_t encryptedLength = _config.mtu - recp::REC_HEADER_SIZE;
_aes->gcmEncrypt(payload,
payloadLength,
reinterpret_cast<unsigned char*>(payload),
encryptedLength,
iv,
crypto::DEFAULT_AES_IV_SIZE,
reinterpret_cast<unsigned char*>(recHeader),
recp::REC_HEADER_SIZE);
packet->setLength(recp::REC_HEADER_SIZE + encryptedLength);
endpoint->sendTo(target, std::move(packet));
}
else if (rtp::isRtcpPacket(*packet))
{
endpoint->sendTo(target, std::move(packet));
}
else
{
logger::debug("DIDN'T send packet to %s", getLoggableId().c_str(), target.toString().c_str());
}
}
bool RecordingTransport::unprotect(memory::Packet& packet)
{
// TODO implement payload decryption
return false;
}
bool RecordingTransport::isConnected()
{
return _isRunning && _recordingEndpoint->isGood();
}
void RecordingTransport::setDataReceiver(DataReceiver* dataReceiver)
{
_dataReceiver.store(dataReceiver);
}
uint32_t RecordingTransport::getRolloverCounter(uint32_t ssrc, uint16_t sequenceNumber)
{
auto previousSequenceNumber = _previousSequenceNumber.find(ssrc);
if (previousSequenceNumber != _previousSequenceNumber.cend())
{
auto roc = _rolloverCounter.find(ssrc);
assert(roc != _rolloverCounter.cend());
int32_t diff = previousSequenceNumber->second - sequenceNumber;
auto quarter = 1 << 14;
// if sequence number is more than a quarter-turn away it's a rollover
if (diff > quarter)
{
previousSequenceNumber->second = sequenceNumber;
return ++roc->second;
}
// if sequence number is less than a quarter-turn away negatively it's a reordering
else if (diff < -quarter)
{
return roc->second - 1;
}
else if (sequenceNumber > previousSequenceNumber->second)
{
previousSequenceNumber->second = sequenceNumber;
return roc->second;
}
else
{
return roc->second;
}
}
else
{
_previousSequenceNumber.emplace(ssrc, sequenceNumber);
_rolloverCounter.emplace(ssrc, 0);
return 0;
}
}
void RecordingTransport::sendRtcpSenderReport(memory::PacketPoolAllocator& sendAllocator, uint64_t timestamp)
{
auto rtcpPacket = memory::makeUniquePacket(sendAllocator);
if (!rtcpPacket)
{
logger::warn("Not enough memory to send SR RTCP", _loggableId.c_str());
return;
}
constexpr int MINIMUM_SR = 7 * sizeof(uint32_t);
const auto wallClock = std::chrono::system_clock::now();
for (auto& it : _outboundSsrcCounters)
{
const size_t remaining = _config.recordingRtcp.mtu - rtcpPacket->getLength();
if (remaining < MINIMUM_SR + sizeof(rtp::ReportBlock))
{
protectAndSend(std::move(rtcpPacket));
_rtcp.lastSendTime = timestamp;
rtcpPacket = memory::makeUniquePacket(sendAllocator);
if (!rtcpPacket)
{
logger::warn("Not enough memory to send SR RTCP", _loggableId.c_str());
return;
}
}
auto* senderReport = rtp::RtcpSenderReport::create(rtcpPacket->get() + rtcpPacket->getLength());
senderReport->ssrc = it.first;
it.second.fillInReport(*senderReport, timestamp, utils::Time::toNtp(wallClock));
rtcpPacket->setLength(senderReport->header.size() + rtcpPacket->getLength());
assert(!memory::PacketPoolAllocator::isCorrupt(rtcpPacket.get()));
}
if (!rtcpPacket)
{
return;
}
if (rtcpPacket->getLength() > 0)
{
protectAndSend(std::move(rtcpPacket));
_rtcp.lastSendTime = timestamp;
}
}
void RecordingTransport::onSendingStreamAddedEvent(const memory::Packet& packet)
{
const auto* recordingEvent = recp::RecStreamAddedEvent::fromPacket(packet);
assert(packet.getLength() >= recp::RecStreamAddedEvent::MIN_SIZE);
assert(recordingEvent->header.event == recp::RecEventType::StreamAdded);
uint32_t frequency = 0;
switch (recordingEvent->rtpPayload)
{
case codec::Opus::payloadType:
frequency = codec::Opus::sampleRate;
break;
case codec::Vp8::payloadType:
frequency = codec::Vp8::sampleRate;
break;
default:
logger::error("Payload type %d not recognized", _loggableId.c_str(), recordingEvent->rtpPayload);
break;
}
if (frequency != 0)
{
_outboundSsrcCounters.emplace(recordingEvent->ssrc, frequency, _config);
}
}
void RecordingTransport::onSendingStreamRemovedEvent(const memory::Packet& packet)
{
const auto* recordingEvent = recp::RecStreamRemovedEvent::fromPacket(packet);
assert(packet.getLength() >= recp::RecStreamRemovedEvent::MIN_SIZE);
assert(recordingEvent->header.event == recp::RecEventType::StreamRemoved);
_outboundSsrcCounters.erase(recordingEvent->ssrc);
}
RtpSenderState* RecordingTransport::getOutboundSsrc(const uint32_t ssrc)
{
auto ssrcIt = _outboundSsrcCounters.find(ssrc);
if (ssrcIt != _outboundSsrcCounters.cend())
{
return &ssrcIt->second;
}
return nullptr;
}
void RecordingTransport::onUnregistered(RecordingEndpoint& endpoint)
{
logger::debug("Unregistered %s, %p", _loggableId.c_str(), endpoint.getName(), this);
logger::debug("Recording transport events stopped jobcount %u", _loggableId.c_str(), _jobCounter.load() - 1);
_jobQueue.addJob<ShutdownJob>(_jobCounter);
_jobQueue.getJobManager().abortTimedJobs(getId());
_isInitialized = false;
--_jobCounter;
}
void RecordingTransport::onRecControlReceived(RecordingEndpoint& endpoint,
const SocketAddress& source,
const SocketAddress& target,
memory::UniquePacket packet)
{
DataReceiver* const dataReceiver = _dataReceiver.load();
if (!dataReceiver)
{
return;
}
if (!recp::isRecControlPacket(packet->get(), packet->getLength()))
{
return;
}
const auto receiveTime = utils::Time::getAbsoluteTime();
dataReceiver->onRecControlReceived(this, std::move(packet), receiveTime);
}
} // namespace transport
| 32.367647 | 119 | 0.666061 | marcusspangenberg |
07d9bcaf73944e3fb39ad3e8ff64dbd5a386d785 | 258 | cpp | C++ | Core/Event/Event.cpp | digital7-code/gaps_engine | 43e2ed7c8cc43800c8815d68ab22963a773f0c5f | [
"Apache-2.0"
] | null | null | null | Core/Event/Event.cpp | digital7-code/gaps_engine | 43e2ed7c8cc43800c8815d68ab22963a773f0c5f | [
"Apache-2.0"
] | null | null | null | Core/Event/Event.cpp | digital7-code/gaps_engine | 43e2ed7c8cc43800c8815d68ab22963a773f0c5f | [
"Apache-2.0"
] | 1 | 2021-10-16T14:11:00.000Z | 2021-10-16T14:11:00.000Z | #include <gapspch.hpp>
#include <Core/Event/Event.hpp>
namespace gaps
{
EventId Event::GetId() const noexcept
{
return id;
}
Event::Event(const EventId id) noexcept
:
id{ id }
{
}
void Event::OnCreate()
{
}
void Event::OnRelease()
{
}
} | 10.75 | 40 | 0.631783 | digital7-code |
07da80fff5916e196089971a4998c90c9cc20b37 | 532 | cpp | C++ | src/systems/sources/type.cpp | hexoctal/zenith | eeef065ed62f35723da87c8e73a6716e50d34060 | [
"MIT"
] | 2 | 2021-03-18T16:25:04.000Z | 2021-11-13T00:29:27.000Z | src/systems/sources/type.cpp | hexoctal/zenith | eeef065ed62f35723da87c8e73a6716e50d34060 | [
"MIT"
] | null | null | null | src/systems/sources/type.cpp | hexoctal/zenith | eeef065ed62f35723da87c8e73a6716e50d34060 | [
"MIT"
] | 1 | 2021-11-13T00:29:30.000Z | 2021-11-13T00:29:30.000Z | /**
* @file
* @author __AUTHOR_NAME__ <mail@host.com>
* @copyright 2021 __COMPANY_LTD__
* @license <a href="https://opensource.org/licenses/MIT">MIT License</a>
*/
#include "../type.hpp"
#include "../../components/type.hpp"
#include "../../utils/assert.hpp"
namespace Zen {
extern entt::registry g_registry;
std::string GetType (Entity entity)
{
auto blendMode = g_registry.try_get<Components::Type>(entity);
ZEN_ASSERT(blendMode, "The entity has no 'Type' component.");
return blendMode->type;
}
} // namespace Zen
| 21.28 | 74 | 0.695489 | hexoctal |
07dd5260fe7a319e58385b38ffc31bad2d689dbb | 29,107 | hpp | C++ | System.Core/include/Switch/System/Threading/Monitor.hpp | kkptm/CppLikeCSharp | b2d8d9da9973c733205aa945c9ba734de0c734bc | [
"MIT"
] | 4 | 2021-10-14T01:43:00.000Z | 2022-03-13T02:16:08.000Z | System.Core/include/Switch/System/Threading/Monitor.hpp | kkptm/CppLikeCSharp | b2d8d9da9973c733205aa945c9ba734de0c734bc | [
"MIT"
] | null | null | null | System.Core/include/Switch/System/Threading/Monitor.hpp | kkptm/CppLikeCSharp | b2d8d9da9973c733205aa945c9ba734de0c734bc | [
"MIT"
] | 2 | 2022-03-13T02:16:06.000Z | 2022-03-14T14:32:57.000Z | /// @file
/// @brief Contains Switch::System::Threading::Monitor class.
#pragma once
#include <map>
#include "../../RefPtr.hpp"
#include "../../Static.hpp"
#include "../IntPtr.hpp"
#include "../Object.hpp"
#include "../Nullable.hpp"
#include "../TimeSpan.hpp"
#include "AutoResetEvent.hpp"
#include "Mutex.hpp"
#include "Timeout.hpp"
#include "../SystemException.hpp"
#include "../Collections/Generic/Dictionary.hpp"
/// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more.
namespace Switch {
/// @brief The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.
namespace System {
/// @brief The System::Threading namespace provides classes and interfaces that enable multithreaded programming.
/// In addition to classes for synchronizing thread activities and access to data ( Mutex, Monitor, Interlocked, AutoResetEvent, and so on), this namespace includes a ThreadPool class that allows you to use a pool of system-supplied threads, and a Timer class that executes callback methods on thread pool threads.
namespace Threading {
/// @brief Provides a mechanism that synchronizes access to objects.
class core_export_ Monitor static_ {
public:
/// @brief Acquires an exclusive lock on the specified obj.
/// @param obj The object on which to acquire the monitor lock.
/// @exception ArgumentNullException The obj parameter is null.
/// @remarks Use Enter to acquire the Monitor on the object passed as the parameter. If another thread has executed an Enter on the object, but has not yet executed the corresponding Exit, the current thread will block until the other thread releases the object. It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock.
/// @remarks Usex Monitor to lock objects (that is, reference types), not value types. When you pass a value type variable to Enter, it is boxed as an object. If you pass the same variable to Enter again, the thread is block. The code that Monitor is supposedly protecting is not protected. Furthermore, when you pass the variable to Exit, still another separate object is created. Because the object passed to Exit is different from the object passed to Enter, Monitor throws SynchronizationLockException. For details, see the conceptual topic Monitors.
static void Enter(const object& obj) {
bool lockTaken = false;
Enter(obj, lockTaken);
}
/// @brief Acquires an exclusive lock on the specified obj.
/// @param obj The object on which to acquire the monitor lock.
/// @param lockTaken The result of the attempt to acquire the lock, passed by reference. The input must be false. The output is true if the lock is acquired; otherwise, the output is false. The output is set even if an exception occurs during the attempt to acquire the lock.
/// @note If no exception occurs, the output of this method is always true.
/// @exception ArgumentNullException The obj parameter is null.
/// @remarks Use Enter to acquire the Monitor on the object passed as the parameter. If another thread has executed an Enter on the object, but has not yet executed the corresponding Exit, the current thread will block until the other thread releases the object. It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock.
/// @remarks Use Monitor to lock objects (that is, reference types), not value types. When you pass a value type variable to Enter, it is boxed as an object. If you pass the same variable to Enter again, the thread is block. The code that Monitor is supposedly protecting is not protected. Furthermore, when you pass the variable to Exit, still another separate object is created. Because the object passed to Exit is different from the object passed to Enter, Monitor throws SynchronizationLockException. For details, see the conceptual topic Monitors.
static void Enter(const object& obj, bool& lockTaken) {
if (TryEnter(obj, lockTaken) == false)
throw InvalidOperationException(caller_);
}
/// @brief Acquires an exclusive lock on the specified obj.
/// @param obj The object on which to acquire the monitor lock.
/// @exception ArgumentNullException The obj parameter is null.
/// @remarks Use Enter to acquire the Monitor on the object passed as the parameter. If another thread has executed an Enter on the object, but has not yet executed the corresponding Exit, the current thread will block until the other thread releases the object. It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock.
/// @remarks Usex Monitor to lock objects (that is, reference types), not value types. When you pass a value type variable to Enter, it is boxed as an object. If you pass the same variable to Enter again, the thread is block. The code that Monitor is supposedly protecting is not protected. Furthermore, when you pass the variable to Exit, still another separate object is created. Because the object passed to Exit is different from the object passed to Enter, Monitor throws SynchronizationLockException. For details, see the conceptual topic Monitors.
static bool IsEntered(const object& obj) {
return MonitorItems().ContainsKey(ToKey(obj));
}
/// @brief Notifies a thread in the waiting queue of a change in the locked object's state.
/// @param obj The object a thread is waiting for.
/// @exception ArgumentNullException The obj parameter is null.
/// Only the current owner of the lock can signal a waiting object using Pulse.
/// The thread that currently owns the lock on the specified object invokes this method to signal the next thread in line for the lock. Upon receiving the pulse, the waiting thread is moved to the ready queue. When the thread that invoked Pulse releases the lock, the next thread in the ready queue (which is not necessarily the thread that was pulsed) acquires the lock.
static void Pulse(const object& obj);
/// @brief Notifies all waiting threads of a change in the object's state.
/// @param obj The object a thread is waiting for.
/// @exception ArgumentNullException The obj parameter is null.
/// @remarks The thread that currently owns the lock on the specified object invokes this method to signal all threads waiting to acquire the lock on the object. After the signal is sent, the waiting threads are moved to the ready queue. When the thread that invoked PulseAll releases the lock, the next thread in the ready queue acquires the lock.
/// @remarks Note that a synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state.
/// @remarks The Pulse, PulseAll, and Wait methods must be invoked from within a synchronized block of code.
/// @remarks The remarks for the Pulse method explain what happens if Pulse is called when no threads are waiting.
/// @remarks To signal a single thread, use the Pulse method.
static void PulseAll(const object& obj);
/// @brief Releases an exclusive lock on the specified obj.
/// @param obj The object on which to release the lock.
/// @exception ArgumentNullException The obj parameter is null.
/// @remarks The calling thread must own the lock on the obj parameter. If the calling thread owns the lock on the specified object, and has made an equal number of Exit and Enter calls for the object, then the lock is released. If the calling thread has not invoked Exit as many times as Enter, the lock is not released.
/// @remarks If the lock is released and other threads are in the ready queue for the object, one of the threads acquires the lock. If other threads are in the waiting queue waiting to acquire the lock, they are not automatically moved to the ready queue when the owner of the lock calls Exit. To move one or more waiting threads into the ready queue, call Pulse or PulseAll before invoking Exit.
static void Exit(const object& obj) {Remove(obj);}
/// @brief Attempts to acquire an exclusive lock on the specified object.
/// @param obj The object on which to acquire the lock.
/// @return bool true if the current thread acquires the lock; otherwise, false
/// @exception ArgumentNullException The obj parameter is null.
/// @remarks If successful, this method acquires an exclusive lock on the obj parameter. This method returns immediately, whether or not the lock is available.
/// @remarks This method is similar to Enter, but it will never block. If the thread cannot enter without blocking, the method returns false, and the thread does not enter the critical section.
static bool TryEnter(const object& obj) {return TryEnter(obj, Timeout::Infinite);}
/// @brief Attempts to acquire an exclusive lock on the specified object.
/// @param obj The object on which to acquire the lock.
/// @param lockTaken The result of the attempt to acquire the lock, passed by reference. The input must be false. The output is true if the lock is acquired; otherwise, the output is false. The output is set even if an exception occurs during the attempt to acquire the lock.
/// @note If no exception occurs, the output of this method is always true.
/// @return bool true if the current thread acquires the lock; otherwise, false
/// @exception ArgumentNullException The obj parameter is null.
/// @remarks If successful, this method acquires an exclusive lock on the obj parameter. This method returns immediately, whether or not the lock is available.
/// @remarks This method is similar to Enter, but it will never block. If the thread cannot enter without blocking, the method returns false, and the thread does not enter the critical section.
static bool TryEnter(const object& obj, bool& lockTaken) {return TryEnter(obj, Timeout::Infinite, lockTaken);}
/// @brief Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object.
/// @param obj The object on which to acquire the lock.
/// @param millisecondsTimeout The number of milliseconds to wait for the lock.
/// @return bool true if the current thread acquires the lock; otherwise, false
/// @exception ArgumentNullException The obj parameter is null.
/// @remarks If the millisecondsTimeout parameter equals Timeout::Infinite, this method is equivalent to Enter. If millisecondsTimeout equals 0, this method is equivalent to TryEnter.
static bool TryEnter(const object& obj, int32 millisecondsTimeout) {
bool lockTacken = false;
return TryEnter(obj, millisecondsTimeout, lockTacken);
}
/// @brief Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object.
/// @param obj The object on which to acquire the lock.
/// @param millisecondsTimeout The number of milliseconds to wait for the lock.
/// @param lockTaken The result of the attempt to acquire the lock, passed by reference. The input must be false. The output is true if the lock is acquired; otherwise, the output is false. The output is set even if an exception occurs during the attempt to acquire the lock.
/// @note If no exception occurs, the output of this method is always true.
/// @return bool true if the current thread acquires the lock; otherwise, false
/// @exception ArgumentNullException The obj parameter is null.
/// @remarks If the millisecondsTimeout parameter equals Timeout::Infinite, this method is equivalent to Enter. If millisecondsTimeout equals 0, this method is equivalent to TryEnter.
static bool TryEnter(const object& obj, int32 millisecondsTimeout, bool& lockTaken) {
if (millisecondsTimeout < -1)
return false;
lockTaken = Add(obj, millisecondsTimeout);
return true;
}
/// @brief Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object.
/// @param obj The object on which to acquire the lock.
/// @param millisecondsTimeout The number of milliseconds to wait for the lock.
/// @return bool true if the current thread acquires the lock; otherwise, false
/// @exception ArgumentNullException The obj parameter is null.
/// @remarks If the millisecondsTimeout parameter equals Timeout::Infinite, this method is equivalent to Enter. If millisecondsTimeout equals 0, this method is equivalent to TryEnter.
static bool TryEnter(const object& obj, int64 millisecondsTimeout) {
bool lockTacken = false;
return TryEnter(obj, millisecondsTimeout, lockTacken);
}
/// @brief Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object.
/// @param obj The object on which to acquire the lock.
/// @param millisecondsTimeout The number of milliseconds to wait for the lock.
/// @param lockTaken The result of the attempt to acquire the lock, passed by reference. The input must be false. The output is true if the lock is acquired; otherwise, the output is false. The output is set even if an exception occurs during the attempt to acquire the lock.
/// @note If no exception occurs, the output of this method is always true.
/// @return bool true if the current thread acquires the lock; otherwise, false
/// @exception ArgumentNullException The obj parameter is null.
/// @remarks If the millisecondsTimeout parameter equals Timeout::Infinite, this method is equivalent to Enter. If millisecondsTimeout equals 0, this method is equivalent to TryEnter.
static bool TryEnter(const object& obj, int64 millisecondsTimeout, bool& lockTaken) {
if (millisecondsTimeout < -1)
return false;
lockTaken = Add(obj, (int32)millisecondsTimeout);
return true;
}
/// @brief Attempts, for the specified amount of time, to acquire an exclusive lock on the specified object.
/// @param obj The object on which to acquire the lock.
/// @param timeout A TimeSpan representing the amount of time to wait for the lock. A value of -1 millisecond specifies an infinite wait.
/// @return bool true if the current thread acquires the lock; otherwise, false
/// @exception ArgumentNullException The obj timeout or parameter is null.
/// @remarks If the value of the timeout parameter converted to milliseconds equals -1, this method is equivalent to Enter. If the value of timeout equals 0, this method is equivalent to TryEnter.
static bool TryEnter(const object& obj, const TimeSpan& timeout) {
bool lockTaken = false;
return TryEnter(obj, as<int32>(timeout.TotalMilliseconds()), lockTaken);
}
/// @brief Attempts, for the specified amount of time, to acquire an exclusive lock on the specified object.
/// @param obj The object on which to acquire the lock.
/// @param timeout A TimeSpan representing the amount of time to wait for the lock. A value of -1 millisecond specifies an infinite wait.
/// @param lockTaken The result of the attempt to acquire the lock, passed by reference. The input must be false. The output is true if the lock is acquired; otherwise, the output is false. The output is set even if an exception occurs during the attempt to acquire the lock.
/// @note If no exception occurs, the output of this method is always true.
/// @return bool true if the current thread acquires the lock; otherwise, false
/// @exception ArgumentNullException The obj timeout or parameter is null.
/// @remarks If the value of the timeout parameter converted to milliseconds equals -1, this method is equivalent to Enter. If the value of timeout equals 0, this method is equivalent to TryEnter.
static bool TryEnter(const object& obj, const TimeSpan& timeout, bool& lockTaken) {return TryEnter(obj, as<int32>(timeout.TotalMilliseconds()), lockTaken);}
/// @brief Releases the lock on an object and blocks the current thread until it reacquires the lock.
/// @param obj The object on which to wait.
/// @return Boolean true if the call returned because the caller reacquired the lock for the specified object. This method does not return if the lock is not reacquired.
/// @exception ArgumentNullException The obj parameter is null.
/// The thread that currently owns the lock on the specified object invokes this method in order to release the object so that another thread can access it. The caller is blocked while waiting to reacquire the lock. This method is called when the caller needs to wait for a state change that will occur as a result of another thread's operations.
/// When a thread calls Wait, it releases the lock on the object and enters the object's waiting queue. The next thread in the object's ready queue (if there is one) acquires the lock and has exclusive use of the object. All threads that call Wait remain in the waiting queue until they receive a signal from Pulse or PulseAll, sent by the owner of the lock. If Pulse is sent, only the thread at the head of the waiting queue is affected. If PulseAll is sent, all threads that are waiting for the object are affected. When the signal is received, one or more threads leave the waiting queue and enter the ready queue. A thread in the ready queue is permitted to reacquire the lock.
/// This method returns when the calling thread reacquires the lock on the object. Note that this method blocks indefinitely if the holder of the lock does not call Pulse or PulseAll.
/// The caller executes Wait once, regardless of the number of times Enter has been invoked for the specified object. Conceptually, the Wait method stores the number of times the caller invoked Enter on the object and invokes Exit as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls Enter as many times as necessary to restore the saved Enter count for the caller. Calling Wait releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released.
/// Note that a synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state.
/// The Pulse, PulseAll, and Wait methods must be invoked from within a synchronized block of code.
/// The remarks for the Pulse method explain what happens if Pulse is called when no threads are waiting.
static bool Wait(const object& obj) {return Wait(obj, Timeout::Infinite);}
/// @brief Releases the lock on an object and blocks the current thread until it reacquires the lock.
/// @param obj The object on which to wait.
/// @param millisecondsTimeout The number of milliseconds to wait before the thread enters the ready queue.
/// @return bool true if the lock was reacquired before the specified time elapsed; false if the lock was reacquired after the specified time elapsed. The method does not return until the lock is reacquired.
/// @exception ArgumentNullException The obj parameter is null.
/// This method does not return until it reacquires an exclusive lock on the obj parameter.
/// The thread that currently owns the lock on the specified object invokes this method in order to release the object so that another thread can access it. The caller is blocked while waiting to reacquire the lock. This method is called when the caller needs to wait for a state change that will occur as a result of another thread's operations.
/// The time-out ensures that the current thread does not block indefinitely if another thread releases the lock without first calling the Pulse or PulseAll method. It also moves the thread to the ready queue, bypassing other threads ahead of it in the wait queue, so that it can reacquire the lock sooner. The thread can test the return value of the Wait method to determine whether it reacquired the lock prior to the time-out. The thread can evaluate the conditions that caused it to enter the wait, and if necessary call the Wait method again.
/// When a thread calls Wait, it releases the lock on the object and enters the object's waiting queue. The next thread in the object's ready queue (if there is one) acquires the lock and has exclusive use of the object. The thread that invoked Wait remains in the waiting queue until either a thread that holds the lock invokes PulseAll, or it is the next in the queue and a thread that holds the lock invokes Pulse. However, if millisecondsTimeout elapses before another thread invokes this object's Pulse or PulseAll method, the original thread is moved to the ready queue in order to regain the lock.
/// If Timeout::Infinite is specified for the millisecondsTimeout parameter, this method blocks indefinitely unless the holder of the lock calls Pulse or PulseAll. If millisecondsTimeout equals 0, the thread that calls Wait releases the lock and then immediately enters the ready queue in order to regain the lock.
/// The caller executes Wait once, regardless of the number of times Enter has been invoked for the specified object. Conceptually, the Wait method stores the number of times the caller invoked Enter on the object and invokes Exit as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls Enter as many times as necessary to restore the saved Enter count for the caller. Calling Wait releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released.
/// A synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state.
/// The Pulse, PulseAll, and Wait methods must be invoked from within a synchronized block of code.
/// The remarks for the Pulse method explain what happens if Pulse is called when no threads are waiting.
static bool Wait(const object& obj, int32 millisecondsTimeout);
/// @brief Releases the lock on an object and blocks the current thread until it reacquires the lock. If the specified time-out interval elapses, the thread enters the ready queue.
/// @param obj The object on which to wait.
/// @param timeout A TimeSpan representing the amount of time to wait before the thread enters the ready queue.
/// @return bool true if the lock was reacquired before the specified time elapsed; false if the lock was reacquired after the specified time elapsed. The method does not return until the lock is reacquired.
/// @exception ArgumentNullException The obj parameter is null.
/// This method does not return until it reacquires an exclusive lock on the obj parameter.
/// The thread that currently owns the lock on the specified object invokes this method in order to release the object so that another thread can access it. The caller is blocked while waiting to reacquire the lock. This method is called when the caller needs to wait for a state change that will occur as a result of another thread's operations.
/// The time-out ensures that the current thread does not block indefinitely if another thread releases the lock without first calling the Pulse or PulseAll method. It also moves the thread to the ready queue, bypassing other threads ahead of it in the wait queue, so that it can reacquire the lock sooner. The thread can test the return value of the Wait method to determine whether it reacquired the lock prior to the time-out. The thread can evaluate the conditions that caused it to enter the wait, and if necessary call the Wait method again.
/// When a thread calls Wait, it releases the lock on the object and enters the object's waiting queue. The next thread in the object's ready queue (if there is one) acquires the lock and has exclusive use of the object. The thread that invoked Wait remains in the waiting queue until either a thread that holds the lock invokes PulseAll, or it is the next in the queue and a thread that holds the lock invokes Pulse. However, if timeout elapses before another thread invokes this object's Pulse or PulseAll method, the original thread is moved to the ready queue in order to regain the lock.
/// If a TimeSpan representing -1 millisecond is specified for the timeout parameter, this method blocks indefinitely unless the holder of the lock calls Pulse or PulseAll. If timeout is 0 milliseconds, the thread that calls Wait releases the lock and then immediately enters the ready queue in order to regain the lock.
/// The caller executes Wait once, regardless of the number of times Enter has been invoked for the specified object. Conceptually, the Wait method stores the number of times the caller invoked Enter on the object and invokes Exit as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls Enter as many times as necessary to restore the saved Enter count for the caller. Calling Wait releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released.
/// A synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state.
/// The Pulse, PulseAll, and Wait methods must be invoked from within a synchronized block of code.
///The remarks for the Pulse method explain what happens if Pulse is called when no threads are waiting.
static bool Wait(const object& obj, const TimeSpan& timeout) {return Wait(obj, as<int32>(timeout.TotalMilliseconds()));}
private:
struct MonitorItem {
MonitorItem() {}
MonitorItem(const string& name) : name(name) {}
bool operator==(const MonitorItem& monitorItem) const {return this->event == monitorItem.event && this->usedCounter == monitorItem.usedCounter;}
bool operator!=(const MonitorItem& monitorItem) const {return !this->operator==(monitorItem);}
Mutex event {false};
int32 usedCounter {0};
Nullable<string> name;
};
static const object* ToKey(const object& obj) {
if (is<string>(obj)) {
for (const auto& item : MonitorItems())
if (item.Value().name.HasValue && item.Value().name.Value().Equals((const string&)obj))
return item.Key;
}
return &obj;
}
static System::Collections::Generic::Dictionary<const object*, MonitorItem>& MonitorItems() {
static System::Collections::Generic::Dictionary<const object*, MonitorItem> monitorItems;
return monitorItems;
}
static bool Add(const object& obj, int32 millisecondsTimeout);
static void Remove(const object& obj);
};
}
}
}
using namespace Switch;
| 113.699219 | 689 | 0.738448 | kkptm |
07e0461230af130de0991a11a9d7b7376ea6827b | 9,993 | cpp | C++ | IETutorials/hydra/instancing/SceneDelegate.cpp | ousttrue/usd_cpp_samples | b35af2d26c0708d8977ce1ba2bb85a1a90bf7dcb | [
"MIT"
] | 5 | 2020-10-06T05:18:53.000Z | 2022-03-15T02:18:02.000Z | IETutorials/hydra/instancing/SceneDelegate.cpp | ousttrue/usd_cpp_samples | b35af2d26c0708d8977ce1ba2bb85a1a90bf7dcb | [
"MIT"
] | null | null | null | IETutorials/hydra/instancing/SceneDelegate.cpp | ousttrue/usd_cpp_samples | b35af2d26c0708d8977ce1ba2bb85a1a90bf7dcb | [
"MIT"
] | null | null | null | #include "SceneDelegate.h"
#include "pxr/imaging/hd/camera.h"
#include "pxr/imaging/cameraUtil/conformWindow.h"
#include "pxr/imaging/pxOsd/tokens.h"
#include "pxr/imaging/hdx/renderTask.h"
#include "pxr/base/gf/range3f.h"
#include "pxr/base/gf/frustum.h"
#include "pxr/base/vt/array.h"
SceneDelegate::SceneDelegate(pxr::HdRenderIndex *parentIndex, pxr::SdfPath const &delegateID)
: pxr::HdSceneDelegate(parentIndex, delegateID),
rotation(45.0f)
{
cameraPath = pxr::SdfPath("/camera");
GetRenderIndex().InsertSprim(pxr::HdPrimTypeTokens->camera, this, cameraPath);
pxr::GfFrustum frustum;
frustum.SetPosition(pxr::GfVec3d(0, 0, 10));
frustum.SetNearFar(pxr::GfRange1d(0.01, 100.0));
SetCamera(frustum.ComputeViewMatrix(), frustum.ComputeProjectionMatrix());
pxr::SdfPath instancerPath("/instances");
GetRenderIndex().InsertRprim(pxr::HdPrimTypeTokens->mesh, this, pxr::SdfPath("/cube"), instancerPath); //,
GetRenderIndex().InsertInstancer(this, instancerPath);
}
void
SceneDelegate::AddRenderTask(pxr::SdfPath const &id)
{
GetRenderIndex().InsertTask<pxr::HdxRenderTask>(this, id);
_ValueCache &cache = _valueCacheMap[id];
cache[pxr::HdTokens->children] = pxr::VtValue(pxr::SdfPathVector());
cache[pxr::HdTokens->collection]
= pxr::HdRprimCollection(pxr::HdTokens->geometry, pxr::HdTokens->smoothHull);
}
void
SceneDelegate::AddRenderSetupTask(pxr::SdfPath const &id)
{
GetRenderIndex().InsertTask<pxr::HdxRenderSetupTask>(this, id);
_ValueCache &cache = _valueCacheMap[id];
pxr::HdxRenderTaskParams params;
params.camera = cameraPath;
params.enableLighting = true;
params.enableHardwareShading = true;
params.viewport = pxr::GfVec4f(0, 0, 512, 512);
cache[pxr::HdTokens->children] = pxr::VtValue(pxr::SdfPathVector());
cache[pxr::HdTokens->params] = pxr::VtValue(params);
}
void SceneDelegate::SetCamera(pxr::GfMatrix4d const &viewMatrix, pxr::GfMatrix4d const &projMatrix)
{
SetCamera(cameraPath, viewMatrix, projMatrix);
}
void SceneDelegate::SetCamera(pxr::SdfPath const &cameraId, pxr::GfMatrix4d const &viewMatrix, pxr::GfMatrix4d const &projMatrix)
{
_ValueCache &cache = _valueCacheMap[cameraId];
cache[pxr::HdCameraTokens->windowPolicy] = pxr::VtValue(pxr::CameraUtilFit);
cache[pxr::HdCameraTokens->worldToViewMatrix] = pxr::VtValue(viewMatrix);
cache[pxr::HdCameraTokens->projectionMatrix] = pxr::VtValue(projMatrix);
GetRenderIndex().GetChangeTracker().MarkSprimDirty(cameraId, pxr::HdCamera::AllDirty);
}
pxr::VtValue SceneDelegate::Get(pxr::SdfPath const &id, const pxr::TfToken &key)
{
std::cout << "[" << id.GetString() <<"][Get][" << key << "]" << std::endl;
_ValueCache *vcache = pxr::TfMapLookupPtr(_valueCacheMap, id);
pxr::VtValue ret;
if (vcache && pxr::TfMapLookup(*vcache, key, &ret)) {
return ret;
}
if (key == pxr::HdShaderTokens->material)
{
return pxr::VtValue();
}
if (id == pxr::SdfPath("/cube"))
{
if (key == pxr::HdTokens->color)
{
return pxr::VtValue(pxr::GfVec4f(0.3, 0.2, 0.2, 1.0));
}
else if (key == pxr::HdTokens->points)
{
pxr::VtVec3fArray points;
points.push_back(pxr::GfVec3f(0,0,0));
points.push_back(pxr::GfVec3f(1,0,0));
points.push_back(pxr::GfVec3f(1,1,0));
points.push_back(pxr::GfVec3f(0,1,0));
points.push_back(pxr::GfVec3f(0,0,1));
points.push_back(pxr::GfVec3f(1,0,1));
points.push_back(pxr::GfVec3f(1,1,1));
points.push_back(pxr::GfVec3f(0,1,1));
for (size_t i = 0; i < points.size(); ++i)
{
points[i] -= pxr::GfVec3f(0.5f, 0.5f, 0.5f);
}
return pxr::VtValue(points);
}
else if (key == pxr::HdTokens->normals)
{
pxr::VtVec3fArray normals;
normals.push_back(pxr::GfVec3f(0,0,-1));
normals.push_back(pxr::GfVec3f(0,0,-1));
normals.push_back(pxr::GfVec3f(0,0,-1));
normals.push_back(pxr::GfVec3f(0,0,-1));
normals.push_back(pxr::GfVec3f(0,0,1));
normals.push_back(pxr::GfVec3f(0,0,1));
normals.push_back(pxr::GfVec3f(0,0,1));
normals.push_back(pxr::GfVec3f(0,0,1));
normals.push_back(pxr::GfVec3f(1,0,0));
normals.push_back(pxr::GfVec3f(1,0,0));
normals.push_back(pxr::GfVec3f(1,0,0));
normals.push_back(pxr::GfVec3f(1,0,0));
normals.push_back(pxr::GfVec3f(0,1,0));
normals.push_back(pxr::GfVec3f(0,1,0));
normals.push_back(pxr::GfVec3f(0,1,0));
normals.push_back(pxr::GfVec3f(0,1,0));
normals.push_back(pxr::GfVec3f(-1,0,0));
normals.push_back(pxr::GfVec3f(-1,0,0));
normals.push_back(pxr::GfVec3f(-1,0,0));
normals.push_back(pxr::GfVec3f(-1,0,0));
normals.push_back(pxr::GfVec3f(0,-1,0));
normals.push_back(pxr::GfVec3f(0,-1,0));
normals.push_back(pxr::GfVec3f(0,-1,0));
normals.push_back(pxr::GfVec3f(0,-1,0));
return pxr::VtValue(normals);
}
}
else if (id == pxr::SdfPath("/instances"))
{
if (key == pxr::HdTokens->instanceIndices)
{
pxr::VtIntArray indices;
int index = 0;
for (int i = 0; i < 10; ++i)
{
for (int j = 0; j < 10; ++j)
{
indices.push_back(index++);
}
}
return pxr::VtValue(indices);
}
else if (key == pxr::HdTokens->instanceTransform )
{
pxr::VtMatrix4dArray transforms;
for (int i = 0; i < 10; ++i)
{
for (int j = 0; j < 10; ++j)
{
transforms.push_back(
pxr::GfMatrix4d(pxr::GfRotation(pxr::GfVec3d(1, 0, 0), 0.0), pxr::GfVec3d(16.0 * (i / 10.0 - 0.5), 16.0 * (j / 10.0 - 0.5), 0)));
}
}
return pxr::VtValue(transforms);
}
}
return pxr::VtValue();
}
bool SceneDelegate::GetVisible(pxr::SdfPath const &id)
{
std::cout << "[" << id.GetString() <<"][Visible]" << std::endl;
return true;
}
pxr::GfRange3d SceneDelegate::GetExtent(pxr::SdfPath const &id)
{
std::cout << "[" << id.GetString() <<"][Extent]" << std::endl;
return pxr::GfRange3d(pxr::GfVec3d(-1,-1,-1), pxr::GfVec3d(1,1,1));
}
pxr::GfMatrix4d SceneDelegate::GetTransform(pxr::SdfPath const &id)
{
std::cout << "[" << id.GetString() <<"][Transform]" << std::endl;
if (id == pxr::SdfPath("/cube") )
{
pxr::GfMatrix4d m ;
m.SetTransform(pxr::GfRotation(pxr::GfVec3d(0,1,0), rotation) * pxr::GfRotation(pxr::GfVec3d(1,0,0), rotation) , pxr::GfVec3d(0,0,0));
return m;
}
pxr::GfMatrix4d();
}
pxr::HdPrimvarDescriptorVector SceneDelegate::GetPrimvarDescriptors(pxr::SdfPath const& id, pxr::HdInterpolation interpolation)
{
std::cout << "[" << id.GetString() <<"][GetPrimvarDescriptors]" << std::endl;
pxr::HdPrimvarDescriptorVector primvarDescriptors;
if (id == pxr::SdfPath("/cube"))
{
if (interpolation == pxr::HdInterpolation::HdInterpolationVertex)
{
primvarDescriptors.push_back(pxr::HdPrimvarDescriptor(pxr::HdTokens->points, interpolation));
}
else if (interpolation == pxr::HdInterpolationFaceVarying)
{
primvarDescriptors.push_back(pxr::HdPrimvarDescriptor(pxr::HdTokens->normals, interpolation));
}
else if (interpolation == pxr::HdInterpolationConstant)
{
primvarDescriptors.push_back(pxr::HdPrimvarDescriptor(pxr::HdTokens->color, interpolation));
}
// else if (interpolation == pxr::HdInterpolationInstance)
// {
// primvarDescriptors.push_back(pxr::HdPrimvarDescriptor(pxr::HdTokens->instanceIndices, interpolation));
// primvarDescriptors.push_back(pxr::HdPrimvarDescriptor(pxr::HdTokens->instanceTransform, interpolation));
// }
}
return primvarDescriptors;
}
//
//pxr::TfTokenVector SceneDelegate::GetPrimVarInstanceNames(pxr::SdfPath const &id)
//{
// std::cout << "[" << id.GetString() <<"][GetPrimVarInstanceNames]" << std::endl;
//
// pxr::TfTokenVector names;
// names.push_back(pxr::HdTokens->instanceIndices);
// names.push_back(pxr::HdTokens->instanceTransform);
// return names;
//}
void SceneDelegate::UpdateTransform()
{
rotation += 1.0f;
}
pxr::VtIntArray SceneDelegate::GetInstanceIndices(pxr::SdfPath const &instancerId, pxr::SdfPath const &prototypeId)
{
std::cout << "[" << instancerId.GetString() <<"][GetInstanceIndices]:" << prototypeId << std::endl;
pxr::VtIntArray indices;
int index = 0;
for (int i = 0; i < 10; ++i)
{
for (int j = 0; j < 10; ++j)
{
indices.push_back(index++);
}
}
return indices;
}
pxr::GfMatrix4d SceneDelegate::GetInstancerTransform(pxr::SdfPath const &instancerId, pxr::SdfPath const &prototypeId)
{
std::cout << "[" << instancerId.GetString() <<"][GetInstancerTransform]:" << prototypeId << std::endl;
return pxr::GfMatrix4d(1.0);
}
pxr::SdfPath SceneDelegate::GetPathForInstanceIndex(const pxr::SdfPath &protoPrimPath, int instanceIndex, int *absoluteInstanceIndex,
pxr::SdfPath *rprimPath,
pxr::SdfPathVector *instanceContext)
{
std::cout << "[" << protoPrimPath.GetString() <<"][GetPathForInstanceIndex]:" << instanceIndex << std::endl;
pxr::VtIntArray tmp;//
int index = 0;
for (int i = 0; i < 10; ++i)
{
for (int j = 0; j < 10; ++j)
{
absoluteInstanceIndex[index] = index;
index++;
}
}
return pxr::SdfPath();
}
pxr::HdMeshTopology SceneDelegate::GetMeshTopology(pxr::SdfPath const &id)
{
std::cout << "[" << id.GetString() <<"][Topology]" << std::endl;
if ( id == pxr::SdfPath("/cube") )
{
pxr::VtArray<int> vertCountsPerFace;
pxr::VtArray<int> verts;
vertCountsPerFace.push_back(4);
vertCountsPerFace.push_back(4);
vertCountsPerFace.push_back(4);
vertCountsPerFace.push_back(4);
vertCountsPerFace.push_back(4);
vertCountsPerFace.push_back(4);
verts.push_back(0);
verts.push_back(3);
verts.push_back(2);
verts.push_back(1);
verts.push_back(4);
verts.push_back(5);
verts.push_back(6);
verts.push_back(7);
verts.push_back(1);
verts.push_back(2);
verts.push_back(6);
verts.push_back(5);
verts.push_back(2);
verts.push_back(3);
verts.push_back(7);
verts.push_back(6);
verts.push_back(3);
verts.push_back(0);
verts.push_back(4);
verts.push_back(7);
verts.push_back(0);
verts.push_back(1);
verts.push_back(5);
verts.push_back(4);
pxr::HdMeshTopology topology(pxr::PxOsdOpenSubdivTokens->none, pxr::HdTokens->rightHanded,
vertCountsPerFace, verts);
return topology;
}
}
| 28.551429 | 138 | 0.681877 | ousttrue |
07e112450ef89a85c834cdb9210a05ec27e0aa8d | 1,727 | cpp | C++ | src/CSVGFeLighting.cpp | colinw7/CSVG | 049419b4114fc6ff7f5b25163398f02c21a64bf6 | [
"MIT"
] | 5 | 2015-04-11T14:56:03.000Z | 2021-12-14T10:12:36.000Z | src/CSVGFeLighting.cpp | colinw7/CSVG | 049419b4114fc6ff7f5b25163398f02c21a64bf6 | [
"MIT"
] | 3 | 2015-04-20T19:23:15.000Z | 2021-09-03T20:03:30.000Z | src/CSVGFeLighting.cpp | colinw7/CSVG | 049419b4114fc6ff7f5b25163398f02c21a64bf6 | [
"MIT"
] | 3 | 2015-05-21T08:33:12.000Z | 2020-05-13T15:45:11.000Z | #include <CSVGFeLighting.h>
#include <CSVGFeDistantLight.h>
#include <CSVGFePointLight.h>
#include <CSVGFeSpotLight.h>
#include <CSVGBuffer.h>
#include <CSVGFilter.h>
#include <CSVG.h>
CSVGFeLighting::
CSVGFeLighting(CSVG &svg) :
CSVGFilterBase(svg)
{
}
CSVGFeLighting::
CSVGFeLighting(const CSVGFeLighting &fe) :
CSVGFilterBase (fe),
filterIn_ (fe.filterIn_),
filterOut_ (fe.filterOut_),
lightingColor_ (fe.lightingColor_),
diffuseConstant_ (fe.diffuseConstant_),
specularConstant_(fe.specularConstant_),
specularExponent_(fe.specularExponent_),
surfaceScale_ (fe.surfaceScale_)
{
}
std::string
CSVGFeLighting::
getFilterIn() const
{
return calcFilterIn(filterIn_);
}
std::string
CSVGFeLighting::
getFilterOut() const
{
return calcFilterOut(filterOut_);
}
void
CSVGFeLighting::
filterImage(CSVGBuffer *inBuffer, const CBBox2D &bbox, CSVGBuffer *outBuffer)
{
std::vector<CSVGFilterBase *> lights;
for (const auto &c : children()) {
auto *dl = dynamic_cast<CSVGFeDistantLight *>(c);
auto *pl = dynamic_cast<CSVGFePointLight *>(c);
auto *sl = dynamic_cast<CSVGFeSpotLight *>(c);
if (dl) lights.push_back(dl);
else if (pl) lights.push_back(pl);
else if (sl) lights.push_back(sl);
}
CSVGLightData lightData;
lightData.lcolor = svg_.colorToRGBA(getLightingColor());
lightData.surfaceScale = getSurfaceScale();
lightData.isDiffuse = isDiffuse();
lightData.diffuseConstant = getDiffuseConstant();
lightData.isSpecular = isSpecular();
lightData.specConstant = getSpecularConstant();
lightData.specExponent = getSpecularExponent();
CSVGBuffer::lightBuffers(inBuffer, bbox, lights, lightData, outBuffer);
}
| 24.671429 | 77 | 0.723798 | colinw7 |
07e204bb40e36c20f9a8052d0c265e6bee08baf0 | 719 | cc | C++ | cartographer/cloud/map_builder_server_interface.cc | laotie/cartographer | b8228ee6564f5a7ad0d6d0b9a30516521cff2ee9 | [
"Apache-2.0"
] | 5,196 | 2016-08-04T14:52:31.000Z | 2020-04-02T18:30:00.000Z | cartographer/cloud/map_builder_server_interface.cc | laotie/cartographer | b8228ee6564f5a7ad0d6d0b9a30516521cff2ee9 | [
"Apache-2.0"
] | 1,206 | 2016-08-03T14:27:00.000Z | 2020-03-31T21:14:18.000Z | cartographer/cloud/map_builder_server_interface.cc | laotie/cartographer | b8228ee6564f5a7ad0d6d0b9a30516521cff2ee9 | [
"Apache-2.0"
] | 1,810 | 2016-08-03T05:45:02.000Z | 2020-04-02T03:44:18.000Z | #include "cartographer/cloud/map_builder_server_interface.h"
#include "absl/memory/memory.h"
#include "cartographer/cloud/internal/map_builder_server.h"
namespace cartographer {
namespace cloud {
void RegisterMapBuilderServerMetrics(metrics::FamilyFactory* factory) {
MapBuilderServer::RegisterMetrics(factory);
}
std::unique_ptr<MapBuilderServerInterface> CreateMapBuilderServer(
const proto::MapBuilderServerOptions& map_builder_server_options,
std::unique_ptr<mapping::MapBuilderInterface> map_builder) {
return absl::make_unique<MapBuilderServer>(map_builder_server_options,
std::move(map_builder));
}
} // namespace cloud
} // namespace cartographer
| 32.681818 | 72 | 0.76217 | laotie |
07e298c33ca879800b5608f5928da1363551daeb | 11,964 | cxx | C++ | Packages/java/io/PrintStream.cxx | Brandon-T/Aries | 4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca | [
"MIT"
] | null | null | null | Packages/java/io/PrintStream.cxx | Brandon-T/Aries | 4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca | [
"MIT"
] | null | null | null | Packages/java/io/PrintStream.cxx | Brandon-T/Aries | 4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca | [
"MIT"
] | null | null | null | //
// PrintStream.cxx
// Aries
//
// Created by Brandon on 2017-08-26.
// Copyright © 2017 Brandon. All rights reserved.
//
#include "PrintStream.hxx"
#include "FilterOutputStream.hxx"
#include "File.hxx"
#include "OutputStream.hxx"
#include "CharSequence.hxx"
#include "Object.hxx"
#include "String.hxx"
#include "Locale.hxx"
using java::io::PrintStream;
using java::io::File;
using java::io::FilterOutputStream;
using java::io::OutputStream;
using java::lang::CharSequence;
using java::lang::Object;
using java::lang::String;
using java::util::Locale;
PrintStream::PrintStream(JVM* vm, jobject instance) : FilterOutputStream()
{
if (vm && instance)
{
this->vm = vm;
this->cls = JVMRef<jclass>(this->vm, this->vm->FindClass("Ljava/io/PrintStream;"));
this->inst = JVMRef<jobject>(this->vm, instance);
}
}
PrintStream::PrintStream(JVM* vm, OutputStream out) : FilterOutputStream()
{
if (vm)
{
this->vm = vm;
this->cls = JVMRef<jclass>(this->vm, this->vm->FindClass("Ljava/io/PrintStream;"));
jmethodID constructor = this->vm->GetMethodID(this->cls.get(), "<init>", "(Ljava/io/OutputStream;)V");
this->inst = JVMRef<jobject>(this->vm, this->vm->NewObject(this->cls.get(), constructor, out.ref().get()));
}
}
PrintStream::PrintStream(JVM* vm, OutputStream out, bool autoFlush) : FilterOutputStream()
{
if (vm)
{
this->vm = vm;
this->cls = JVMRef<jclass>(this->vm, this->vm->FindClass("Ljava/io/PrintStream;"));
jmethodID constructor = this->vm->GetMethodID(this->cls.get(), "<init>", "(Ljava/io/OutputStream;Z)V");
this->inst = JVMRef<jobject>(this->vm, this->vm->NewObject(this->cls.get(), constructor, out.ref().get(), autoFlush));
}
}
PrintStream::PrintStream(JVM* vm, OutputStream out, bool autoFlush, String encoding) : FilterOutputStream()
{
if (vm)
{
this->vm = vm;
this->cls = JVMRef<jclass>(this->vm, this->vm->FindClass("Ljava/io/PrintStream;"));
jmethodID constructor = this->vm->GetMethodID(this->cls.get(), "<init>", "(Ljava/io/OutputStream;ZLjava/lang/String;)V");
this->inst = JVMRef<jobject>(this->vm, this->vm->NewObject(this->cls.get(), constructor, out.ref().get(), autoFlush, encoding.ref().get()));
}
}
PrintStream::PrintStream(JVM* vm, String fileName) : FilterOutputStream()
{
if (vm)
{
this->vm = vm;
this->cls = JVMRef<jclass>(this->vm, this->vm->FindClass("Ljava/io/PrintStream;"));
jmethodID constructor = this->vm->GetMethodID(this->cls.get(), "<init>", "(Ljava/lang/String;)V");
this->inst = JVMRef<jobject>(this->vm, this->vm->NewObject(this->cls.get(), constructor, fileName.ref().get()));
}
}
PrintStream::PrintStream(JVM* vm, String fileName, String csn) : FilterOutputStream()
{
if (vm)
{
this->vm = vm;
this->cls = JVMRef<jclass>(this->vm, this->vm->FindClass("Ljava/io/PrintStream;"));
jmethodID constructor = this->vm->GetMethodID(this->cls.get(), "<init>", "(Ljava/lang/String;Ljava/lang/String;)V");
this->inst = JVMRef<jobject>(this->vm, this->vm->NewObject(this->cls.get(), constructor, fileName.ref().get(), csn.ref().get()));
}
}
PrintStream::PrintStream(JVM* vm, File file) : FilterOutputStream()
{
if (vm)
{
this->vm = vm;
this->cls = JVMRef<jclass>(this->vm, this->vm->FindClass("Ljava/io/PrintStream;"));
jmethodID constructor = this->vm->GetMethodID(this->cls.get(), "<init>", "(Ljava/io/File;)V");
this->inst = JVMRef<jobject>(this->vm, this->vm->NewObject(this->cls.get(), constructor, file.ref().get()));
}
}
PrintStream::PrintStream(JVM* vm, File file, String csn) : FilterOutputStream()
{
if (vm)
{
this->vm = vm;
this->cls = JVMRef<jclass>(this->vm, this->vm->FindClass("Ljava/io/PrintStream;"));
jmethodID constructor = this->vm->GetMethodID(this->cls.get(), "<init>", "(Ljava/io/File;Ljava/lang/String;)V");
this->inst = JVMRef<jobject>(this->vm, this->vm->NewObject(this->cls.get(), constructor, file.ref().get(), csn.ref().get()));
}
}
PrintStream PrintStream::append(CharSequence csq)
{
static jmethodID appendMethod = this->vm->GetMethodID(this->cls.get(), "append", "(Ljava/lang/CharSequence;)Ljava/io/PrintStream;");
return PrintStream(this->vm, this->vm->CallObjectMethod(this->inst.get(), appendMethod, csq.ref().get()));
}
PrintStream PrintStream::append(CharSequence csq, std::int32_t start, std::int32_t end)
{
static jmethodID appendMethod = this->vm->GetMethodID(this->cls.get(), "append", "(Ljava/lang/CharSequence;II)Ljava/io/PrintStream;");
return PrintStream(this->vm, this->vm->CallObjectMethod(this->inst.get(), appendMethod, csq.ref().get(), start, end));
}
PrintStream PrintStream::append(char c)
{
static jmethodID appendMethod = this->vm->GetMethodID(this->cls.get(), "append", "(C)Ljava/io/PrintStream;");
return PrintStream(this->vm, this->vm->CallObjectMethod(this->inst.get(), appendMethod, c));
}
bool PrintStream::checkError()
{
static jmethodID checkErrorMethod = this->vm->GetMethodID(this->cls.get(), "checkError", "()Z");
return this->vm->CallBooleanMethod(this->inst.get(), checkErrorMethod);
}
void PrintStream::close()
{
static jmethodID closeMethod = this->vm->GetMethodID(this->cls.get(), "close", "()V");
this->vm->CallVoidMethod(this->inst.get(), closeMethod);
}
void PrintStream::flush()
{
static jmethodID flushMethod = this->vm->GetMethodID(this->cls.get(), "flush", "()V");
this->vm->CallVoidMethod(this->inst.get(), flushMethod);
}
PrintStream PrintStream::format(String arg0, Array<Object>& arg1)
{
static jmethodID formatMethod = this->vm->GetMethodID(this->cls.get(), "format", "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/PrintStream;");
return PrintStream(this->vm, this->vm->CallObjectMethod(this->inst.get(), formatMethod, arg0.ref().get(), arg1.ref().get()));
}
PrintStream PrintStream::format(Locale arg0, String arg1, Array<Object>& arg2)
{
static jmethodID formatMethod = this->vm->GetMethodID(this->cls.get(), "format", "(Ljava/util/Locale;Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/PrintStream;");
return PrintStream(this->vm, this->vm->CallObjectMethod(this->inst.get(), formatMethod, arg0.ref().get(), arg1.ref().get(), arg2.ref().get()));
}
void PrintStream::print(bool b)
{
static jmethodID printMethod = this->vm->GetMethodID(this->cls.get(), "print", "(Z)V");
this->vm->CallVoidMethod(this->inst.get(), printMethod, b);
}
void PrintStream::print(char c)
{
static jmethodID printMethod = this->vm->GetMethodID(this->cls.get(), "print", "(C)V");
this->vm->CallVoidMethod(this->inst.get(), printMethod, c);
}
void PrintStream::print(std::int32_t i)
{
static jmethodID printMethod = this->vm->GetMethodID(this->cls.get(), "print", "(I)V");
this->vm->CallVoidMethod(this->inst.get(), printMethod, i);
}
void PrintStream::print(std::int64_t l)
{
static jmethodID printMethod = this->vm->GetMethodID(this->cls.get(), "print", "(J)V");
this->vm->CallVoidMethod(this->inst.get(), printMethod, l);
}
void PrintStream::print(float f)
{
static jmethodID printMethod = this->vm->GetMethodID(this->cls.get(), "print", "(F)V");
this->vm->CallVoidMethod(this->inst.get(), printMethod, f);
}
void PrintStream::print(double d)
{
static jmethodID printMethod = this->vm->GetMethodID(this->cls.get(), "print", "(D)V");
this->vm->CallVoidMethod(this->inst.get(), printMethod, d);
}
void PrintStream::print(Array<char>& s)
{
static jmethodID printMethod = this->vm->GetMethodID(this->cls.get(), "print", "([C)V");
this->vm->CallVoidMethod(this->inst.get(), printMethod, s.ref().get());
}
void PrintStream::print(String s)
{
static jmethodID printMethod = this->vm->GetMethodID(this->cls.get(), "print", "(Ljava/lang/String;)V");
this->vm->CallVoidMethod(this->inst.get(), printMethod, s.ref().get());
}
void PrintStream::print(Object obj)
{
static jmethodID printMethod = this->vm->GetMethodID(this->cls.get(), "print", "(Ljava/lang/Object;)V");
this->vm->CallVoidMethod(this->inst.get(), printMethod, obj.ref().get());
}
PrintStream PrintStream::printf(String arg0, Array<Object>& arg1)
{
static jmethodID printfMethod = this->vm->GetMethodID(this->cls.get(), "printf", "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/PrintStream;");
return PrintStream(this->vm, this->vm->CallObjectMethod(this->inst.get(), printfMethod, arg0.ref().get(), arg1.ref().get()));
}
PrintStream PrintStream::printf(Locale arg0, String arg1, Array<Object>& arg2)
{
static jmethodID printfMethod = this->vm->GetMethodID(this->cls.get(), "printf", "(Ljava/util/Locale;Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/PrintStream;");
return PrintStream(this->vm, this->vm->CallObjectMethod(this->inst.get(), printfMethod, arg0.ref().get(), arg1.ref().get(), arg2.ref().get()));
}
void PrintStream::println()
{
static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "()V");
this->vm->CallVoidMethod(this->inst.get(), printlnMethod);
}
void PrintStream::println(bool x)
{
static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "(Z)V");
this->vm->CallVoidMethod(this->inst.get(), printlnMethod, x);
}
void PrintStream::println(char x)
{
static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "(C)V");
this->vm->CallVoidMethod(this->inst.get(), printlnMethod, x);
}
void PrintStream::println(std::int32_t x)
{
static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "(I)V");
this->vm->CallVoidMethod(this->inst.get(), printlnMethod, x);
}
void PrintStream::println(std::int64_t x)
{
static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "(J)V");
this->vm->CallVoidMethod(this->inst.get(), printlnMethod, x);
}
void PrintStream::println(float x)
{
static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "(F)V");
this->vm->CallVoidMethod(this->inst.get(), printlnMethod, x);
}
void PrintStream::println(double x)
{
static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "(D)V");
this->vm->CallVoidMethod(this->inst.get(), printlnMethod, x);
}
void PrintStream::println(Array<char>& x)
{
static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "([C)V");
this->vm->CallVoidMethod(this->inst.get(), printlnMethod, x.ref().get());
}
void PrintStream::println(String x)
{
static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "(Ljava/lang/String;)V");
this->vm->CallVoidMethod(this->inst.get(), printlnMethod, x.ref().get());
}
void PrintStream::println(Object x)
{
static jmethodID printlnMethod = this->vm->GetMethodID(this->cls.get(), "println", "(Ljava/lang/Object;)V");
this->vm->CallVoidMethod(this->inst.get(), printlnMethod, x.ref().get());
}
void PrintStream::write(std::int32_t b)
{
static jmethodID writeMethod = this->vm->GetMethodID(this->cls.get(), "write", "(I)V");
this->vm->CallVoidMethod(this->inst.get(), writeMethod, b);
}
void PrintStream::write(Array<std::uint8_t>& buf, std::int32_t off, std::int32_t len)
{
static jmethodID writeMethod = this->vm->GetMethodID(this->cls.get(), "write", "([BII)V");
this->vm->CallVoidMethod(this->inst.get(), writeMethod, buf.ref().get(), off, len);
}
void PrintStream::clearError()
{
static jmethodID clearErrorMethod = this->vm->GetMethodID(this->cls.get(), "clearError", "()V");
this->vm->CallVoidMethod(this->inst.get(), clearErrorMethod);
}
void PrintStream::setError()
{
static jmethodID setErrorMethod = this->vm->GetMethodID(this->cls.get(), "setError", "()V");
this->vm->CallVoidMethod(this->inst.get(), setErrorMethod);
}
| 38.346154 | 167 | 0.666499 | Brandon-T |
07e3a9a55b3f4af4ca2d096594e4c06beca81467 | 6,729 | cpp | C++ | HelperFunctions/getVkPhysicalDeviceLineRasterizationFeaturesEXT.cpp | dkaip/jvulkan-natives-Linux-x86_64 | ea7932f74e828953c712feea11e0b01751f9dc9b | [
"Apache-2.0"
] | null | null | null | HelperFunctions/getVkPhysicalDeviceLineRasterizationFeaturesEXT.cpp | dkaip/jvulkan-natives-Linux-x86_64 | ea7932f74e828953c712feea11e0b01751f9dc9b | [
"Apache-2.0"
] | null | null | null | HelperFunctions/getVkPhysicalDeviceLineRasterizationFeaturesEXT.cpp | dkaip/jvulkan-natives-Linux-x86_64 | ea7932f74e828953c712feea11e0b01751f9dc9b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020 Douglas Kaip
*
* 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.
*/
/*
* getVkPhysicalDeviceLineRasterizationFeaturesEXT.cpp
*
* Created on: Sep 9, 2020
* Author: Douglas Kaip
*/
#include "JVulkanHelperFunctions.hh"
#include "slf4j.hh"
namespace jvulkan
{
void getVkPhysicalDeviceLineRasterizationFeaturesEXT(
JNIEnv *env,
jobject jVkPhysicalDeviceLineRasterizationFeaturesEXTObject,
VkPhysicalDeviceLineRasterizationFeaturesEXT *vkPhysicalDeviceLineRasterizationFeaturesEXT,
std::vector<void *> *memoryToFree)
{
jclass theClass = env->GetObjectClass(jVkPhysicalDeviceLineRasterizationFeaturesEXTObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not get class for jVkPhysicalDeviceLineRasterizationFeaturesEXTObject");
return;
}
////////////////////////////////////////////////////////////////////////
VkStructureType sTypeValue = getSType(env, jVkPhysicalDeviceLineRasterizationFeaturesEXTObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Call to getSType failed.");
return;
}
////////////////////////////////////////////////////////////////////////
jobject jpNextObject = getpNextObject(env, jVkPhysicalDeviceLineRasterizationFeaturesEXTObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Call to getpNext failed.");
return;
}
void *pNext = nullptr;
if (jpNextObject != nullptr)
{
getpNextChain(
env,
jpNextObject,
&pNext,
memoryToFree);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Call to getpNextChain failed.");
return;
}
}
////////////////////////////////////////////////////////////////////////
jmethodID methodId = env->GetMethodID(theClass, "isRectangularLines", "()Z");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not find method id for isRectangularLines.");
return;
}
VkBool32 rectangularLines = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceLineRasterizationFeaturesEXTObject, methodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallBooleanMethod.");
return;
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(theClass, "isBresenhamLines", "()Z");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not find method id for isBresenhamLines.");
return;
}
VkBool32 bresenhamLines = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceLineRasterizationFeaturesEXTObject, methodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallBooleanMethod.");
return;
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(theClass, "isSmoothLines", "()Z");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not find method id for isSmoothLines.");
return;
}
VkBool32 smoothLines = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceLineRasterizationFeaturesEXTObject, methodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallBooleanMethod.");
return;
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(theClass, "isStippledRectangularLines", "()Z");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not find method id for isStippledRectangularLines.");
return;
}
VkBool32 stippledRectangularLines = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceLineRasterizationFeaturesEXTObject, methodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallBooleanMethod.");
return;
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(theClass, "isStippledBresenhamLines", "()Z");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not find method id for isStippledBresenhamLines.");
return;
}
VkBool32 stippledBresenhamLines = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceLineRasterizationFeaturesEXTObject, methodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallBooleanMethod.");
return;
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(theClass, "isStippledSmoothLines", "()Z");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not find method id for isStippledSmoothLines.");
return;
}
VkBool32 stippledSmoothLines = (VkBool32)env->CallBooleanMethod(jVkPhysicalDeviceLineRasterizationFeaturesEXTObject, methodId);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallBooleanMethod.");
return;
}
vkPhysicalDeviceLineRasterizationFeaturesEXT->sType = sTypeValue;
vkPhysicalDeviceLineRasterizationFeaturesEXT->pNext = (void *)pNext;
vkPhysicalDeviceLineRasterizationFeaturesEXT->rectangularLines = rectangularLines;
vkPhysicalDeviceLineRasterizationFeaturesEXT->bresenhamLines = bresenhamLines;
vkPhysicalDeviceLineRasterizationFeaturesEXT->smoothLines = smoothLines;
vkPhysicalDeviceLineRasterizationFeaturesEXT->stippledRectangularLines = stippledRectangularLines;
vkPhysicalDeviceLineRasterizationFeaturesEXT->stippledBresenhamLines = stippledBresenhamLines;
vkPhysicalDeviceLineRasterizationFeaturesEXT->stippledSmoothLines = stippledSmoothLines;
}
}
| 38.895954 | 140 | 0.585674 | dkaip |
07e3b5d7056376be055dad6e9850772b35e89d49 | 2,468 | cpp | C++ | Source/Runtime/Foundation/Filesystem/FileSystem.cpp | simeks/Sandbox | 394b7ab774b172b6e8bc560eb2740620a8dee399 | [
"MIT"
] | null | null | null | Source/Runtime/Foundation/Filesystem/FileSystem.cpp | simeks/Sandbox | 394b7ab774b172b6e8bc560eb2740620a8dee399 | [
"MIT"
] | null | null | null | Source/Runtime/Foundation/Filesystem/FileSystem.cpp | simeks/Sandbox | 394b7ab774b172b6e8bc560eb2740620a8dee399 | [
"MIT"
] | null | null | null | // Copyright 2008-2014 Simon Ekström
#include "Common.h"
#include "FileSystem.h"
#include "FileSource.h"
#include "File.h"
#include "FileUtil.h"
namespace sb
{
//-------------------------------------------------------------------------------
FileSystem::FileSystem(const char* base_path)
{
_base_path = base_path;
}
FileSystem::~FileSystem()
{
// Clear any file sources that are left
for (auto& source : _file_sources)
{
delete source;
}
_file_sources.clear();
}
FileStreamPtr FileSystem::OpenFile(const char* file_path, const File::FileMode mode)
{
Assert(!_file_sources.empty());
FileStreamPtr file;
for (auto& source : _file_sources)
{
file = source->OpenFile(file_path, mode);
if (file.Get())
{
return file;
}
}
logging::Warning("FileSystem: File '%s' not found", file_path);
return FileStreamPtr();
}
FileSource* FileSystem::OpenFileSource(const char* path, const PathAddFlags flags)
{
FileSource* source = 0;
// First check if the path already exists in the system
for (auto& source : _file_sources)
{
if (source->GetPath() == path)
{
return source;
}
}
source = new FileSource(this, path);
if (flags == ADD_TO_TAIL)
{
_file_sources.push_back(source);
}
else
{
_file_sources.push_front(source);
}
return source;
}
void FileSystem::CloseFileSource(FileSource* source)
{
deque<FileSource*>::iterator it = std::find(_file_sources.begin(), _file_sources.end(), source);
if (it != _file_sources.end())
{
delete source;
_file_sources.erase(it);
return;
}
}
void FileSystem::CloseFileSource(const char* path)
{
for (deque<FileSource*>::iterator it = _file_sources.begin(); it != _file_sources.end(); ++it)
{
if ((*it)->GetPath() == path)
{
delete (*it);
_file_sources.erase(it);
return;
}
}
}
void FileSystem::MakeDirectory(const char* path)
{
string dir_path(path);
string full_path;
// Is the sources file path absolute?
if (dir_path.find(':') != string::npos)
{
full_path = dir_path;
}
else
{
file_util::BuildOSPath(full_path, _base_path, dir_path);
}
#ifdef SANDBOX_PLATFORM_WIN
CreateDirectory(full_path.c_str(), NULL);
#elif SANDBOX_PLATFORM_MACOSX
mkdir(full_path.Ptr(), S_IRWXU);
#endif
}
const string& FileSystem::GetBasePath() const
{
return _base_path;
}
//-------------------------------------------------------------------------------
} // namespace sb
| 20.566667 | 98 | 0.623987 | simeks |
2e38e61fc47051fc67aa6e8ef6969c2539e90b68 | 952 | cpp | C++ | D3D12Backend/APIWrappers/CommandQueue/GraphicQueue.cpp | bestdark/BoolkaEngine | 35ae68dedb42baacb19908c0aaa047fe7f71f6b2 | [
"MIT"
] | 27 | 2021-02-12T10:13:55.000Z | 2022-03-24T14:44:06.000Z | D3D12Backend/APIWrappers/CommandQueue/GraphicQueue.cpp | bestdark/BoolkaEngine | 35ae68dedb42baacb19908c0aaa047fe7f71f6b2 | [
"MIT"
] | null | null | null | D3D12Backend/APIWrappers/CommandQueue/GraphicQueue.cpp | bestdark/BoolkaEngine | 35ae68dedb42baacb19908c0aaa047fe7f71f6b2 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "GraphicQueue.h"
#include "APIWrappers/CommandList/GraphicCommandListImpl.h"
#include "APIWrappers/Device.h"
namespace Boolka
{
bool GraphicQueue::Initialize(Device& device)
{
ID3D12CommandQueue* commandQueue = nullptr;
D3D12_COMMAND_QUEUE_DESC desc = {};
desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
desc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
desc.NodeMask = 0;
HRESULT hr = device->CreateCommandQueue(&desc, IID_PPV_ARGS(&commandQueue));
if (FAILED(hr))
return false;
return CommandQueue::Initialize(device, commandQueue);
}
void GraphicQueue::ExecuteCommandList(GraphicCommandListImpl& commandList)
{
ID3D12CommandList* nativeCommandList = commandList.Get();
m_Queue->ExecuteCommandLists(1, &nativeCommandList);
}
} // namespace Boolka
| 28.848485 | 84 | 0.70063 | bestdark |
2e3a0e6af8dd2f1a0d28a23c16e871958be75598 | 4,389 | cc | C++ | tensorflow/libs/octree_set_property_op.cc | pauldinh/O-CNN | fecefd92b559bdfe94a3983b2b010645167c41a1 | [
"MIT"
] | 299 | 2019-05-27T02:18:56.000Z | 2022-03-31T15:29:20.000Z | tensorflow/libs/octree_set_property_op.cc | pauldinh/O-CNN | fecefd92b559bdfe94a3983b2b010645167c41a1 | [
"MIT"
] | 100 | 2019-05-07T03:17:01.000Z | 2022-03-30T09:02:04.000Z | tensorflow/libs/octree_set_property_op.cc | pauldinh/O-CNN | fecefd92b559bdfe94a3983b2b010645167c41a1 | [
"MIT"
] | 84 | 2019-05-17T17:44:06.000Z | 2022-02-14T04:32:02.000Z | #include <cuda_runtime.h>
#include <tensorflow/core/framework/op.h>
#include <tensorflow/core/framework/op_kernel.h>
#include <tensorflow/core/framework/shape_inference.h>
#include "octree_info.h"
#include "octree_parser.h"
namespace tensorflow {
REGISTER_OP("OctreeSetProperty")
.Input("octree_in: int8")
.Input("property_in: dtype")
.Attr("property_name: string")
.Attr("depth: int")
.Attr("dtype: {int32,float32,uint32,uint64}")
.Output("octree_out: int8")
.SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {
c->set_output(0, c->input(0));
return Status::OK();
})
.Doc(R"doc(Octree set property operator.)doc");
class OctreeSetPropertyOp : public OpKernel {
public:
explicit OctreeSetPropertyOp(OpKernelConstruction* context)
: OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("property_name", &property_name_));
OP_REQUIRES_OK(context, context->GetAttr("depth", &depth_));
OP_REQUIRES_OK(context, context->GetAttr("dtype", &dtype_));
}
void Compute(OpKernelContext* context) override {
const Tensor& octree_in = context->input(0);
const Tensor& property_in = context->input(1);
auto ptr_in = octree_in.flat<int8>().data();
Tensor* octree_out;
OP_REQUIRES_OK(context, context->allocate_output(0, octree_in.shape(), &octree_out));
auto ptr_out = octree_out->flat<int8>().data();
cudaMemcpy(ptr_out, ptr_in, octree_in.NumElements(), cudaMemcpyDeviceToDevice);
OctreeParser oct_parser;
oct_parser.set_gpu(ptr_out);
void* property_ptr = nullptr;
int length = oct_parser.info().node_num(depth_);
if (property_name_ == "key") {
bool key32 = std::is_same<uintk, uint32>::value;
DataType key_dtype = key32 ? DataType::DT_UINT32 : DataType::DT_UINT64;
property_ptr = oct_parser.mutable_key_gpu(depth_);
length *= oct_parser.info().channel(OctreeInfo::kKey);
CHECK_EQ(dtype_, key_dtype);
} else if (property_name_ == "child") {
property_ptr = oct_parser.mutable_children_gpu(depth_);
length *= oct_parser.info().channel(OctreeInfo::kChild);
CHECK_EQ(dtype_, DataType::DT_INT32);
} else if (property_name_ == "neigh") {
property_ptr = oct_parser.mutable_neighbor_gpu(depth_);
length *= oct_parser.info().channel(OctreeInfo::kNeigh);
CHECK_EQ(dtype_, DataType::DT_INT32);
} else if (property_name_ == "feature") {
property_ptr = oct_parser.mutable_feature_gpu(depth_);
length *= oct_parser.info().channel(OctreeInfo::kFeature);
CHECK_EQ(dtype_, DataType::DT_FLOAT);
} else if (property_name_ == "label") {
property_ptr = oct_parser.mutable_label_gpu(depth_);
length *= oct_parser.info().channel(OctreeInfo::kLabel);
CHECK_EQ(dtype_, DataType::DT_FLOAT);
} else if (property_name_ == "split") {
property_ptr = oct_parser.mutable_split_gpu(depth_);
length *= oct_parser.info().channel(OctreeInfo::kSplit);
CHECK_EQ(dtype_, DataType::DT_FLOAT);
} else {
LOG(FATAL) << "Unsupported Octree Property";
}
CHECK_EQ(length, property_in.NumElements()) << "Wrong Property Size";
switch (dtype_) {
case DataType::DT_UINT32: {
auto property_in_ptr = property_in.flat<uint32>().data();
cudaMemcpy(property_ptr, property_in_ptr, sizeof(uint32) * length,
cudaMemcpyDeviceToDevice);
} break;
case DataType::DT_UINT64: {
auto property_in_ptr = property_in.flat<uint64>().data();
cudaMemcpy(property_ptr, property_in_ptr, sizeof(uint64) * length,
cudaMemcpyDeviceToDevice);
} break;
case DataType::DT_INT32: {
auto property_in_ptr = property_in.flat<int>().data();
cudaMemcpy(property_ptr, property_in_ptr, sizeof(int) * length,
cudaMemcpyDeviceToDevice);
} break;
case DataType::DT_FLOAT: {
auto property_in_ptr = property_in.flat<float>().data();
cudaMemcpy(property_ptr, property_in_ptr, sizeof(float) * length,
cudaMemcpyDeviceToDevice);
} break;
default:
LOG(FATAL) << "Wrong DataType";
}
}
private:
string property_name_;
DataType dtype_;
int depth_;
};
REGISTER_KERNEL_BUILDER(Name("OctreeSetProperty").Device(DEVICE_GPU), OctreeSetPropertyOp);
} // namespace tensorflow
| 38.840708 | 91 | 0.678514 | pauldinh |
2e3a71e3282033c5a3b41c23659a1f6082156d82 | 1,135 | cc | C++ | 2020/PTA/Contest/1.cc | slowbear/TrainingCode | 688872b9dab784a410069b787457f8c0871648aa | [
"CC0-1.0"
] | null | null | null | 2020/PTA/Contest/1.cc | slowbear/TrainingCode | 688872b9dab784a410069b787457f8c0871648aa | [
"CC0-1.0"
] | null | null | null | 2020/PTA/Contest/1.cc | slowbear/TrainingCode | 688872b9dab784a410069b787457f8c0871648aa | [
"CC0-1.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using LL = long long;
using Pii = pair<int, int>;
using Pll = pair<LL, LL>;
using VI = vector<int>;
using VP = vector<pair<int, int>>;
#define rep(i, a, b) for (auto i = (a); i < (b); ++i)
#define rev(i, a, b) for (auto i = (b - 1); i >= (a); --i)
#define grep(i, u) for (auto i = gh[u]; i != -1; i = gn[i])
#define mem(x, v) memset(x, v, sizeof(x))
#define cpy(x, y) memcpy(x, y, sizeof(x))
#define SZ(V) static_cast<int>(V.size())
#define pb push_back
#define mp make_pair
struct factor {
LL x, y;
};
factor operator+(const factor &a, const factor &b) {
LL new_y = a.y * b.y;
LL new_x = a.x * b.y + b.x * a.y;
LL d = __gcd(abs(new_x), abs(new_y));
return factor{new_x / d, new_y / d};
}
int main() {
int n;
scanf("%d", &n);
factor sum{0, 1};
rep(i, 0, n) {
LL x, y;
scanf("%lld/%lld", &x, &y);
sum = sum + factor{x, y};
}
if (!sum.x) {
printf("0\n");
return 0;
}
LL z = sum.x / sum.y;
sum.x = sum.x % sum.y;
if (z) printf("%lld", z);
if (sum.x) {
if (z) printf(" ");
printf("%lld/%lld", sum.x, sum.y);
}
printf("\n");
}
| 22.7 | 59 | 0.533921 | slowbear |
2e3ad3fba23db62f62ab996454a2842427a202fe | 5,914 | cc | C++ | RecoJets/JetAnalyzers/src/CMSDAS11DijetTestAnalyzer.cc | PKUfudawei/cmssw | 8fbb5ce74398269c8a32956d7c7943766770c093 | [
"Apache-2.0"
] | 1 | 2018-08-28T16:51:36.000Z | 2018-08-28T16:51:36.000Z | RecoJets/JetAnalyzers/src/CMSDAS11DijetTestAnalyzer.cc | PKUfudawei/cmssw | 8fbb5ce74398269c8a32956d7c7943766770c093 | [
"Apache-2.0"
] | 25 | 2016-06-24T20:55:32.000Z | 2022-02-01T19:24:45.000Z | RecoJets/JetAnalyzers/src/CMSDAS11DijetTestAnalyzer.cc | PKUfudawei/cmssw | 8fbb5ce74398269c8a32956d7c7943766770c093 | [
"Apache-2.0"
] | 8 | 2016-03-25T07:17:43.000Z | 2021-07-08T17:11:21.000Z | // CMSDAS11DijetTestAnalyzer.cc
// Description: A basic dijet analyzer for the CMSDAS 2011
// Author: John Paul Chou
// Date: January 12, 2011
#include "RecoJets/JetAnalyzers/interface/CMSDAS11DijetTestAnalyzer.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "CommonTools/UtilAlgos/interface/TFileService.h"
#include "DataFormats/VertexReco/interface/Vertex.h"
#include "JetMETCorrections/Objects/interface/JetCorrector.h"
#include "SimDataFormats/GeneratorProducts/interface/GenEventInfoProduct.h"
#include "SimDataFormats/GeneratorProducts/interface/GenRunInfoProduct.h"
#include <TH1D.h>
#include <TH2D.h>
CMSDAS11DijetTestAnalyzer::CMSDAS11DijetTestAnalyzer(edm::ParameterSet const& params)
: jetSrc(params.getParameter<edm::InputTag>("jetSrc")),
vertexSrc(params.getParameter<edm::InputTag>("vertexSrc")),
jetCorrections(params.getParameter<std::string>("jetCorrections")),
innerDeltaEta(params.getParameter<double>("innerDeltaEta")),
outerDeltaEta(params.getParameter<double>("outerDeltaEta")),
JESbias(params.getParameter<double>("JESbias")) {
// setup file service
usesResource(TFileService::kSharedResource);
edm::Service<TFileService> fs;
const int NBINS = 36;
Double_t BOUNDARIES[NBINS] = {220, 244, 270, 296, 325, 354, 386, 419, 453, 489, 526, 565,
606, 649, 693, 740, 788, 838, 890, 944, 1000, 1058, 1118, 1181,
1246, 1313, 1383, 1455, 1530, 1607, 1687, 1770, 1856, 1945, 2037, 2132};
// setup histograms
hVertexZ = fs->make<TH1D>("hVertexZ", "Z position of the Vertex", 50, -20, 20);
hJetRawPt = fs->make<TH1D>("hJetRawPt", "Raw Jet Pt", 50, 0, 1000);
hJetCorrPt = fs->make<TH1D>("hJetCorrPt", "Corrected Jet Pt", 50, 0, 1000);
hJet1Pt = fs->make<TH1D>("hJet1Pt", "Corrected Jet1 Pt", 50, 0, 1000);
hJet2Pt = fs->make<TH1D>("hJet2Pt", "Corrected Jet2 Pt", 50, 0, 1000);
hJetEta = fs->make<TH1D>("hJetEta", "Corrected Jet Eta", 50, -5, 5);
hJet1Eta = fs->make<TH1D>("hJet1Eta", "Corrected Jet1 Eta", 50, -5, 5);
hJet2Eta = fs->make<TH1D>("hJet2Eta", "Corrected Jet2 Eta", 50, -5, 5);
hJetPhi = fs->make<TH1D>("hJetPhi", "Corrected Jet Phi", 50, -3.1415, 3.1415);
hJet1Phi = fs->make<TH1D>("hJet1Phi", "Corrected Jet1 Phi", 50, -3.1415, 3.1415);
hJet2Phi = fs->make<TH1D>("hJet2Phi", "Corrected Jet2 Phi", 50, -3.1415, 3.1415);
hJetEMF = fs->make<TH1D>("hJetEMF", "EM Fraction of Jets", 50, 0, 1);
hJet1EMF = fs->make<TH1D>("hJet1EMF", "EM Fraction of Jet1", 50, 0, 1);
hJet2EMF = fs->make<TH1D>("hJet2EMF", "EM Fraction of Jet2", 50, 0, 1);
hCorDijetMass = fs->make<TH1D>("hCorDijetMass", "Corrected Dijet Mass", NBINS - 1, BOUNDARIES);
hDijetDeltaPhi = fs->make<TH1D>("hDijetDeltaPhi", "Dijet |#Delta #phi|", 50, 0, 3.1415);
hDijetDeltaEta = fs->make<TH1D>("hDijetDeltaEta", "Dijet |#Delta #eta|", 50, 0, 1.3);
hDijetDeltaPhiNJets =
fs->make<TH2D>("hDijetDeltaPhiNJets", "Dijet |#Delta #phi| v. the number of jets", 50, 0, 3.1415, 7, 0.5, 7.5);
hDijetEta1Eta2 = fs->make<TH2D>("hDijetEta1Eta2", "Eta 1 versus Eta 2 of dijet events", 50, -5, 5, 50, -5, 5);
hInnerDijetMass = fs->make<TH1D>("hInnerDijetMass", "Corrected Inner Dijet Mass", NBINS - 1, BOUNDARIES);
hOuterDijetMass = fs->make<TH1D>("hOuterDijetMass", "Corrected Outer Dijet Mass", NBINS - 1, BOUNDARIES);
}
void CMSDAS11DijetTestAnalyzer::endJob(void) {}
void CMSDAS11DijetTestAnalyzer::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) {
////////Get Weight, if this is MC//////////////
double mWeight;
edm::Handle<GenEventInfoProduct> hEventInfo;
iEvent.getByLabel("generator", hEventInfo);
if (hEventInfo.isValid()) {
mWeight = hEventInfo->weight();
} else
mWeight = 1.;
////////////////////////////////////////////
// Get event ID information
////////////////////////////////////////////
//int nrun=iEvent.id().run();
//int nlumi=iEvent.luminosityBlock();
//int nevent=iEvent.id().event();
////////////////////////////////////////////
// Get Primary Vertex Information
////////////////////////////////////////////
// magic to get the vertices from EDM
edm::Handle<std::vector<reco::Vertex> > vertices_h;
iEvent.getByLabel(vertexSrc, vertices_h);
if (!vertices_h.isValid()) {
std::cout << "Didja hear the one about the empty vertex collection?\n";
return;
}
// require in the event that there is at least one reconstructed vertex
if (vertices_h->empty())
return;
// pick the first (i.e. highest sum pt) verte
const reco::Vertex* theVertex = &(vertices_h->front());
// require that the vertex meets certain criteria
if (theVertex->ndof() < 5)
return;
if (fabs(theVertex->z()) > 24.0)
return;
if (fabs(theVertex->position().rho()) > 2.0)
return;
////////////////////////////////////////////
// Get Jet Information
////////////////////////////////////////////
// magic to get the jets from EDM
edm::Handle<reco::CaloJetCollection> jets_h;
iEvent.getByLabel(jetSrc, jets_h);
if (!jets_h.isValid()) {
std::cout << "Didja hear the one about the empty jet collection?\n";
return;
}
// magic to get the jet energy corrections
const JetCorrector* corrector = JetCorrector::getJetCorrector(jetCorrections, iSetup);
corrector->vectorialCorrection();
// collection of selected jets
std::vector<reco::CaloJet> selectedJets;
// loop over the jet collection
for (reco::CaloJetCollection::const_iterator j_it = jets_h->begin(); j_it != jets_h->end(); j_it++) {
reco::CaloJet jet = *j_it;
// put the selected jets into a collection
selectedJets.push_back(jet);
}
hVertexZ->Fill(theVertex->z(), mWeight);
return;
}
DEFINE_FWK_MODULE(CMSDAS11DijetTestAnalyzer);
| 40.786207 | 117 | 0.650998 | PKUfudawei |
2e3dd45c74178ada77a28f0951aee800499e7b43 | 1,930 | cpp | C++ | engine/plugins/files/file_reader_class.cpp | dmpas/e8engine | 27390fa096fa721be5f8a868a844fbb20f6ebc9c | [
"MIT"
] | 1 | 2017-11-17T07:28:02.000Z | 2017-11-17T07:28:02.000Z | engine/plugins/files/file_reader_class.cpp | dmpas/e8engine | 27390fa096fa721be5f8a868a844fbb20f6ebc9c | [
"MIT"
] | null | null | null | engine/plugins/files/file_reader_class.cpp | dmpas/e8engine | 27390fa096fa721be5f8a868a844fbb20f6ebc9c | [
"MIT"
] | null | null | null | #include "file_reader_class.hpp"
#include <boost/filesystem.hpp>
#include "e8core/env/_array.h"
#include <sys/types.h>
#include <sys/stat.h>
namespace fs = boost::filesystem;
using namespace std;
void FileReaderClass::Close()
{
stream.close();
}
void FileReaderClass::Open(E8_IN FileName, E8_IN Exclusive)
{
if (IsOpen())
Close();
wstring ws = FileName.to_string().to_wstring();
fs::path m_path(ws);
stream.open(m_path, std::ios_base::binary);
stream.seekg(0, stream.end);
m_full_size = stream.tellg();
stream.seekg(0, stream.beg);
m_tail_size = m_full_size;
}
/* .Прочитать([Размер]) -> ФиксированныйМассив */
E8::Variant FileReaderClass::Read(E8_IN Size)
{
if (!IsOpen()) {
throw E8::EnvironmentException();
//E8_THROW_DETAIL(E8_RT_EXCEPTION_RAISED, "File not opened!");
}
//std::cout << "inSize: " << Size << std::endl << std::flush;
size_t size = 0;
if (Size != E8::Variant::Undefined()) {
size = Size.to_long();
}
if (size == 0 || size > m_tail_size)
size = m_tail_size;
char *buf = new char[size];
int read = stream.readsome(buf, size);
m_tail_size -= read;
if (m_tail_size < 0)
m_tail_size = 0;
E8::Variant A = E8::NewObject("Array", size);
int i = 0;
for (i = 0; i < read; ++i) {
long l_value = (unsigned char)buf[i];
E8::Variant V(l_value);
A.__Call("Set", i, V);
}
delete buf;
A = E8::NewObject("FixedArray", A);
return A;
}
FileReaderClass *FileReaderClass::Constructor(E8_IN FileName, E8_IN Exclusive)
{
FileReaderClass *R = new FileReaderClass();
if (FileName != E8::Variant::Undefined())
R->Open(FileName, Exclusive);
return R;
}
bool FileReaderClass::IsOpen() const
{
return stream.is_open();
}
FileReaderClass::FileReaderClass()
{
}
FileReaderClass::~FileReaderClass()
{
}
| 20.104167 | 79 | 0.615026 | dmpas |
2e3f939a80e1f08d1776dc3983d5168532a9a878 | 228 | cpp | C++ | LibC/poll.cpp | mmatoscom/serenity | b7e1fbc1d1b820ba3e5dd55a00c80e7e6822dab8 | [
"BSD-2-Clause"
] | 1 | 2019-06-06T21:41:44.000Z | 2019-06-06T21:41:44.000Z | LibC/poll.cpp | mmatoscom/serenity | b7e1fbc1d1b820ba3e5dd55a00c80e7e6822dab8 | [
"BSD-2-Clause"
] | null | null | null | LibC/poll.cpp | mmatoscom/serenity | b7e1fbc1d1b820ba3e5dd55a00c80e7e6822dab8 | [
"BSD-2-Clause"
] | null | null | null | #include <poll.h>
#include <Kernel/Syscall.h>
#include <errno.h>
extern "C" {
int poll(struct pollfd* fds, int nfds, int timeout)
{
int rc = syscall(SC_poll, fds, nfds, timeout);
__RETURN_WITH_ERRNO(rc, rc, -1);
}
}
| 15.2 | 51 | 0.653509 | mmatoscom |
2e41354ef0b892b7060c8aa8342a25d837b4f2fb | 130 | hpp | C++ | cinemagraph_editor/opencv2.framework/Versions/A/Headers/core/base.hpp | GeonHyeongKim/cinemagraph_editor | 20639c63a5a3cf55267fb5f68f56a74da5820652 | [
"MIT"
] | null | null | null | cinemagraph_editor/opencv2.framework/Versions/A/Headers/core/base.hpp | GeonHyeongKim/cinemagraph_editor | 20639c63a5a3cf55267fb5f68f56a74da5820652 | [
"MIT"
] | null | null | null | cinemagraph_editor/opencv2.framework/Versions/A/Headers/core/base.hpp | GeonHyeongKim/cinemagraph_editor | 20639c63a5a3cf55267fb5f68f56a74da5820652 | [
"MIT"
] | null | null | null | version https://git-lfs.github.com/spec/v1
oid sha256:bb04bec725a144a389cb9e9109385e3d4e78b260c95a9d3196603a4ce28457ab
size 26499
| 32.5 | 75 | 0.884615 | GeonHyeongKim |
2e4495c3d5f45265896d9764baa5098f8a4f78b5 | 6,921 | cpp | C++ | src/mongo/db/pipeline/tee_buffer_test.cpp | mwhudson/mongo | 914bbbd26a686e032fdddec964b109ea78c6e6f6 | [
"Apache-2.0"
] | 1 | 2019-05-15T03:41:50.000Z | 2019-05-15T03:41:50.000Z | src/mongo/db/pipeline/tee_buffer_test.cpp | mwhudson/mongo | 914bbbd26a686e032fdddec964b109ea78c6e6f6 | [
"Apache-2.0"
] | 2 | 2021-03-26T00:01:11.000Z | 2021-03-26T00:02:19.000Z | src/mongo/db/pipeline/tee_buffer_test.cpp | mwhudson/mongo | 914bbbd26a686e032fdddec964b109ea78c6e6f6 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2016 MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/pipeline/tee_buffer.h"
#include "mongo/db/pipeline/document.h"
#include "mongo/db/pipeline/document_source_mock.h"
#include "mongo/db/pipeline/document_value_test_util.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/assert_util.h"
namespace mongo {
namespace {
TEST(TeeBufferTest, ShouldRequireAtLeastOneConsumer) {
ASSERT_THROWS_CODE(TeeBuffer::create(0), UserException, 40309);
}
TEST(TeeBufferTest, ShouldRequirePositiveBatchSize) {
ASSERT_THROWS_CODE(TeeBuffer::create(1, 0), UserException, 40310);
ASSERT_THROWS_CODE(TeeBuffer::create(1, -2), UserException, 40310);
}
TEST(TeeBufferTest, ShouldBeExhaustedIfInputIsExhausted) {
auto mock = DocumentSourceMock::create();
auto teeBuffer = TeeBuffer::create(1);
teeBuffer->setSource(mock.get());
ASSERT(teeBuffer->getNext(0).isEOF());
ASSERT(teeBuffer->getNext(0).isEOF());
ASSERT(teeBuffer->getNext(0).isEOF());
}
TEST(TeeBufferTest, ShouldProvideAllResultsWithoutPauseIfTheyFitInOneBatch) {
std::deque<DocumentSource::GetNextResult> inputs{Document{{"a", 1}}, Document{{"a", 2}}};
auto mock = DocumentSourceMock::create(inputs);
auto teeBuffer = TeeBuffer::create(1);
teeBuffer->setSource(mock.get());
auto next = teeBuffer->getNext(0);
ASSERT_TRUE(next.isAdvanced());
ASSERT_DOCUMENT_EQ(next.getDocument(), inputs.front().getDocument());
next = teeBuffer->getNext(0);
ASSERT_TRUE(next.isAdvanced());
ASSERT_DOCUMENT_EQ(next.getDocument(), inputs.back().getDocument());
ASSERT_TRUE(teeBuffer->getNext(0).isEOF());
ASSERT_TRUE(teeBuffer->getNext(0).isEOF());
}
TEST(TeeBufferTest, ShouldProvideAllResultsWithoutPauseIfOnlyOneConsumer) {
std::deque<DocumentSource::GetNextResult> inputs{Document{{"a", 1}}, Document{{"a", 2}}};
auto mock = DocumentSourceMock::create(inputs);
const size_t bufferBytes = 1; // Both docs won't fit in a single batch.
auto teeBuffer = TeeBuffer::create(1, bufferBytes);
teeBuffer->setSource(mock.get());
auto next = teeBuffer->getNext(0);
ASSERT_TRUE(next.isAdvanced());
ASSERT_DOCUMENT_EQ(next.getDocument(), inputs.front().getDocument());
next = teeBuffer->getNext(0);
ASSERT_TRUE(next.isAdvanced());
ASSERT_DOCUMENT_EQ(next.getDocument(), inputs.back().getDocument());
ASSERT_TRUE(teeBuffer->getNext(0).isEOF());
ASSERT_TRUE(teeBuffer->getNext(0).isEOF());
}
TEST(TeeBufferTest, ShouldTellConsumerToPauseIfItFinishesBatchBeforeOtherConsumers) {
std::deque<DocumentSource::GetNextResult> inputs{Document{{"a", 1}}, Document{{"a", 2}}};
auto mock = DocumentSourceMock::create(inputs);
const size_t nConsumers = 2;
const size_t bufferBytes = 1; // Both docs won't fit in a single batch.
auto teeBuffer = TeeBuffer::create(nConsumers, bufferBytes);
teeBuffer->setSource(mock.get());
auto next0 = teeBuffer->getNext(0);
ASSERT_TRUE(next0.isAdvanced());
ASSERT_DOCUMENT_EQ(next0.getDocument(), inputs.front().getDocument());
ASSERT_TRUE(teeBuffer->getNext(0).isPaused()); // Consumer #1 hasn't seen the first doc yet.
ASSERT_TRUE(teeBuffer->getNext(0).isPaused());
auto next1 = teeBuffer->getNext(1);
ASSERT_TRUE(next1.isAdvanced());
ASSERT_DOCUMENT_EQ(next1.getDocument(), inputs.front().getDocument());
// Both consumers should be able to advance now. We'll advance consumer #1.
next1 = teeBuffer->getNext(1);
ASSERT_TRUE(next1.isAdvanced());
ASSERT_DOCUMENT_EQ(next1.getDocument(), inputs.back().getDocument());
// Consumer #1 should be blocked now. The next input is EOF, but the TeeBuffer didn't get that
// far, since the first doc filled up the buffer.
ASSERT_TRUE(teeBuffer->getNext(1).isPaused());
ASSERT_TRUE(teeBuffer->getNext(1).isPaused());
// Now exhaust consumer #0.
next0 = teeBuffer->getNext(0);
ASSERT_TRUE(next0.isAdvanced());
ASSERT_DOCUMENT_EQ(next0.getDocument(), inputs.back().getDocument());
ASSERT_TRUE(teeBuffer->getNext(0).isEOF());
ASSERT_TRUE(teeBuffer->getNext(0).isEOF());
// Consumer #1 will now realize it's exhausted.
ASSERT_TRUE(teeBuffer->getNext(1).isEOF());
ASSERT_TRUE(teeBuffer->getNext(1).isEOF());
}
TEST(TeeBufferTest, ShouldAllowOtherConsumersToAdvanceOnceTrailingConsumerIsDisposed) {
std::deque<DocumentSource::GetNextResult> inputs{Document{{"a", 1}}, Document{{"a", 2}}};
auto mock = DocumentSourceMock::create(inputs);
const size_t nConsumers = 2;
const size_t bufferBytes = 1; // Both docs won't fit in a single batch.
auto teeBuffer = TeeBuffer::create(nConsumers, bufferBytes);
teeBuffer->setSource(mock.get());
auto next0 = teeBuffer->getNext(0);
ASSERT_TRUE(next0.isAdvanced());
ASSERT_DOCUMENT_EQ(next0.getDocument(), inputs.front().getDocument());
ASSERT_TRUE(teeBuffer->getNext(0).isPaused()); // Consumer #1 hasn't seen the first doc yet.
ASSERT_TRUE(teeBuffer->getNext(0).isPaused());
// Kill consumer #1.
teeBuffer->dispose(1);
// Consumer #0 should be able to advance now.
next0 = teeBuffer->getNext(0);
ASSERT_TRUE(next0.isAdvanced());
ASSERT_DOCUMENT_EQ(next0.getDocument(), inputs.back().getDocument());
ASSERT_TRUE(teeBuffer->getNext(0).isEOF());
ASSERT_TRUE(teeBuffer->getNext(0).isEOF());
}
} // namespace
} // namespace mongo
| 40.473684 | 98 | 0.714926 | mwhudson |
2e460c2d26df8d1ac75ed080ce61f8e785439afd | 219 | cpp | C++ | IMU/VTK-6.2.0/ThirdParty/ftgl/src/FTPixmapGlyphRenderMesa.cpp | timkrentz/SunTracker | 9a189cc38f45e5fbc4e4c700d7295a871d022795 | [
"MIT"
] | null | null | null | IMU/VTK-6.2.0/ThirdParty/ftgl/src/FTPixmapGlyphRenderMesa.cpp | timkrentz/SunTracker | 9a189cc38f45e5fbc4e4c700d7295a871d022795 | [
"MIT"
] | null | null | null | IMU/VTK-6.2.0/ThirdParty/ftgl/src/FTPixmapGlyphRenderMesa.cpp | timkrentz/SunTracker | 9a189cc38f45e5fbc4e4c700d7295a871d022795 | [
"MIT"
] | null | null | null | #include "MangleMesaInclude/gl_mangle.h"
#include "MangleMesaInclude/gl.h"
#define RenderFunctionName RenderMesa
#define GetCurrentColorFunctionName GetCurrentColorMesa
#include "FTPixmapGlyphRenderOpenGL.cpp"
| 27.375 | 56 | 0.83105 | timkrentz |
2e48e9bbb8a00ab2769fdb376785d8e647aa0fc4 | 496 | cpp | C++ | code/engine/input.cpp | ugozapad/g-ray-engine | 6a28c26541a6f4d50b0ca666375ab45f815c9299 | [
"BSD-2-Clause"
] | 1 | 2021-11-18T15:13:30.000Z | 2021-11-18T15:13:30.000Z | code/engine/input.cpp | ugozapad/g-ray-engine | 6a28c26541a6f4d50b0ca666375ab45f815c9299 | [
"BSD-2-Clause"
] | null | null | null | code/engine/input.cpp | ugozapad/g-ray-engine | 6a28c26541a6f4d50b0ca666375ab45f815c9299 | [
"BSD-2-Clause"
] | null | null | null | #include "stdafx.h"
#include "input.h"
Input Input::ms_Singleton;
Input* Input::Instance()
{
return &ms_Singleton;
}
void Input::KeyAction(uint32_t keyid, bool state)
{
if (keyid >= m_kMaxmimumKeys) return;
m_Keys[keyid] = state;
}
void Input::MousePosAction(float x, float y)
{
m_MousePos.x = x;
m_MousePos.y = y;
}
bool Input::GetKey(uint32_t keyid)
{
if (keyid >= m_kMaxmimumKeys) return false;
return m_Keys[keyid];
}
void Input::LockMouse()
{
}
void Input::UnlockMouse()
{
}
| 13.052632 | 49 | 0.693548 | ugozapad |
2e491c2d707e27e7a1f347b14cbea8e2f59cb88c | 3,342 | cpp | C++ | backends/dpdk/printUtils.cpp | st22nestrel/p4c | 5285887bd4f6fcf6fd40b27e58291f647583f3b1 | [
"Apache-2.0"
] | null | null | null | backends/dpdk/printUtils.cpp | st22nestrel/p4c | 5285887bd4f6fcf6fd40b27e58291f647583f3b1 | [
"Apache-2.0"
] | 5 | 2022-02-11T09:23:13.000Z | 2022-03-29T12:03:35.000Z | backends/dpdk/printUtils.cpp | st22nestrel/p4c | 5285887bd4f6fcf6fd40b27e58291f647583f3b1 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2021 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "printUtils.h"
namespace DPDK {
bool ConvertToString::preorder(const IR::Expression *e) {
BUG("%1% not implemented", e);
return false;
}
bool ConvertToString::preorder(const IR::Type *t) {
BUG("Not implemented type %1%", t->node_type_name());
return false;
}
bool ConvertToString::preorder(const IR::PropertyValue *p) {
BUG("Not implemented property value %1%", p->node_type_name());
return false;
}
bool ConvertToString::preorder(const IR::Constant *e) {
out << "0x" << std::hex << e->value;
return false;
}
bool ConvertToString::preorder(const IR::BoolLiteral *e) {
out << e->value;
return false;
}
bool ConvertToString::preorder(const IR::Member *e){
out << toStr(e->expr) << "." << e->member.toString();
return false;
}
bool ConvertToString::preorder(const IR::PathExpression *e) {
out << e->path->name;
return false;
}
bool ConvertToString::preorder(const IR::TypeNameExpression *e) {
if (auto tn = e->typeName->to<IR::Type_Name>()) {
out << tn->path->name;
} else {
BUG("%1%: unexpected typeNameExpression", e);
}
return false;
}
bool ConvertToString::preorder(const IR::MethodCallExpression *e) {
out << "";
if (auto path = e->method->to<IR::PathExpression>()) {
out << path->path->name.name;
} else {
::error(ErrorType::ERR_INVALID,
"%1% is not a PathExpression", e->toString());
}
return false;
}
bool ConvertToString::preorder(const IR::Cast *e) {
out << toStr(e->expr);
return false;
}
bool ConvertToString::preorder(const IR::ArrayIndex *e) {
if (auto cst = e->right->to<IR::Constant>()) {
out << toStr(e->left) << "_" << cst->value;
} else {
::error(ErrorType::ERR_INVALID, "%1% is not a constant", e->right);
}
return false;
}
bool ConvertToString::preorder(const IR::Type_Boolean * /*type*/) {
out << "bool";
return false;
}
bool ConvertToString::preorder(const IR::Type_Bits *type) {
out << "bit_" << type->width_bits();
return false;
}
bool ConvertToString::preorder(const IR::Type_Name *type) {
out << type->path->name;
return false;
}
bool ConvertToString::preorder(const IR::Type_Specialized *type) {
out << type->baseType->path->name.name;
return false;
}
bool ConvertToString::preorder(const IR::ExpressionValue *property) {
out << toStr(property->expression);
return false;
}
cstring toStr(const IR::Node *const n) {
auto nodeToString = new ConvertToString;
n->apply(*nodeToString);
if (nodeToString->out.str() != "") {
return nodeToString->out.str();
} else {
std::cerr << n->node_type_name() << std::endl;
BUG("not implemented type");
}
}
} // namespace DPDK
| 26.736 | 75 | 0.650509 | st22nestrel |
2e4a2b9f781e62b5ea931bc46f0f26c60195585e | 7,956 | cpp | C++ | RenderSystems/GLES2/src/OgreGLES2Support.cpp | MrTypename/ogre-code | b755e3884aa3b3a5fb37b2b2a75a8e44e70bcd56 | [
"MIT"
] | null | null | null | RenderSystems/GLES2/src/OgreGLES2Support.cpp | MrTypename/ogre-code | b755e3884aa3b3a5fb37b2b2a75a8e44e70bcd56 | [
"MIT"
] | null | null | null | RenderSystems/GLES2/src/OgreGLES2Support.cpp | MrTypename/ogre-code | b755e3884aa3b3a5fb37b2b2a75a8e44e70bcd56 | [
"MIT"
] | null | null | null | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
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 "OgreGLES2Support.h"
#include "OgreLogManager.h"
namespace Ogre {
void GLES2Support::setConfigOption(const String &name, const String &value)
{
ConfigOptionMap::iterator it = mOptions.find(name);
if (it == mOptions.end())
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Option named " + name + " does not exist.",
"GLESSupport::setConfigOption");
}
else
{
it->second.currentValue = value;
}
}
ConfigOptionMap& GLES2Support::getConfigOptions(void)
{
return mOptions;
}
void GLES2Support::initialiseExtensions(void)
{
// Set version string
const GLubyte* pcVer = glGetString(GL_VERSION);
assert(pcVer && "Problems getting GL version string using glGetString");
String tmpStr = (const char*)pcVer;
LogManager::getSingleton().logMessage("GL_VERSION = " + tmpStr);
mVersion = tmpStr.substr(0, tmpStr.find(" "));
// Get vendor
const GLubyte* pcVendor = glGetString(GL_VENDOR);
tmpStr = (const char*)pcVendor;
LogManager::getSingleton().logMessage("GL_VENDOR = " + tmpStr);
mVendor = tmpStr.substr(0, tmpStr.find(" "));
// Get renderer
const GLubyte* pcRenderer = glGetString(GL_RENDERER);
tmpStr = (const char*)pcRenderer;
LogManager::getSingleton().logMessage("GL_RENDERER = " + tmpStr);
// Set extension list
std::stringstream ext;
String str;
const GLubyte* pcExt = glGetString(GL_EXTENSIONS);
LogManager::getSingleton().logMessage("GL_EXTENSIONS = " + String((const char*)pcExt));
assert(pcExt && "Problems getting GL extension string using glGetString");
ext << pcExt;
while (ext >> str)
{
LogManager::getSingleton().logMessage("EXT:" + str);
extensionList.insert(str);
}
// Get function pointers on platforms that doesn't have prototypes
#ifndef GL_GLEXT_PROTOTYPES
// define the GL types if they are not defined
# ifndef PFNGLISRENDERBUFFEROES
// GL_OES_Framebuffer_object
typedef GLboolean (GL_APIENTRY *PFNGLISRENDERBUFFEROES)(GLuint renderbuffer);
typedef void (GL_APIENTRY *PFNGLBINDRENDERBUFFEROES)(GLenum target, GLuint renderbuffer);
typedef void (GL_APIENTRY *PFNGLDELETERENDERBUFFERSOES)(GLsizei n, const GLuint *renderbuffers);
typedef void (GL_APIENTRY *PFNGLGENRENDERBUFFERSOES)(GLsizei n, GLuint *renderbuffers);
typedef void (GL_APIENTRY *PFNGLRENDERBUFFERSTORAGEOES)(GLenum target, GLenum internalformat,GLsizei width, GLsizei height);
typedef void (GL_APIENTRY *PFNGLGETRENDERBUFFERPARAMETERIVOES)(GLenum target, GLenum pname, GLint* params);
typedef GLboolean (GL_APIENTRY *PFNGLISFRAMEBUFFEROES)(GLuint framebuffer);
typedef void (GL_APIENTRY *PFNGLBINDFRAMEBUFFEROES)(GLenum target, GLuint framebuffer);
typedef void (GL_APIENTRY *PFNGLDELETEFRAMEBUFFERSOES)(GLsizei n, const GLuint *framebuffers);
typedef void (GL_APIENTRY *PFNGLGENFRAMEBUFFERSOES)(GLsizei n, GLuint *framebuffers);
typedef GLenum (GL_APIENTRY *PFNGLCHECKFRAMEBUFFERSTATUSOES)(GLenum target);
typedef void (GL_APIENTRY *PFNGLFRAMEBUFFERTEXTURE2DOES)(GLenum target, GLenum attachment,GLenum textarget, GLuint texture,GLint level);
typedef void (GL_APIENTRY *PFNGLFRAMEBUFFERRENDERBUFFEROES)(GLenum target, GLenum attachment,GLenum renderbuffertarget, GLuint renderbuffer);
typedef void (GL_APIENTRY *PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVOES)(GLenum target, GLenum attachment,GLenum pname, GLint *params);
typedef void (GL_APIENTRY *PFNGLGENERATEMIPMAPOES)(GLenum target);
typedef void (GL_APIENTRY *PFNGLBLENDEQUATIONOES)(GLenum mode);
typedef void (GL_APIENTRY *PFNGLBLENDFUNCSEPARATEOES)(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha);
typedef void (GL_APIENTRY *PFNGLBLENDEQUATIONSEPARATEOES)(GLenum modeRGB, GLenum modeAlpha);
typedef void* (GL_APIENTRY *PFNGLMAPBUFFEROES)(GLenum target, GLenum access);
typedef GLboolean (GL_APIENTRY *PFNGLUNMAPBUFFEROES)(GLenum target);
// GL_OES_point_size_array
typedef void (GL_APIENTRY *PFNGLPOINTSIZEPOINTEROES)(GLenum type, GLsizei stride, const void *ptr );
# endif
glIsRenderbufferOES = (PFNGLISRENDERBUFFEROES)getProcAddress("glIsRenderbufferOES");
glBindRenderbufferOES = (PFNGLBINDRENDERBUFFEROES)getProcAddress("glBindRenderbufferOES");
glDeleteRenderbuffersOES = (PFNGLDELETERENDERBUFFERSOES)getProcAddress("glDeleteRenderbuffersOES");
glGenRenderbuffersOES = (PFNGLGENRENDERBUFFERSOES)getProcAddress("glGenRenderbuffersOES");
glRenderbufferStorageOES = (PFNGLRENDERBUFFERSTORAGEOES)getProcAddress("glRenderbufferStorageOES");
glGetRenderbufferParameterivOES = (PFNGLGETRENDERBUFFERPARAMETERIVOES)getProcAddress("glGetRenderbufferParameterivOES");
glIsFramebufferOES = (PFNGLISFRAMEBUFFEROES)getProcAddress("glIsFramebufferOES");
glBindFramebufferOES = (PFNGLBINDFRAMEBUFFEROES)getProcAddress("glBindFramebufferOES");
glDeleteFramebuffersOES = (PFNGLDELETEFRAMEBUFFERSOES)getProcAddress("glDeleteFramebuffersOES");
glGenFramebuffersOES = (PFNGLGENFRAMEBUFFERSOES)getProcAddress("glGenFramebuffersOES");
glCheckFramebufferStatusOES = (PFNGLCHECKFRAMEBUFFERSTATUSOES)getProcAddress("glCheckFramebufferStatusOES");
glFramebufferRenderbufferOES = (PFNGLFRAMEBUFFERRENDERBUFFEROES)getProcAddress("glFramebufferRenderbufferOES");
glFramebufferTexture2DOES = (PFNGLFRAMEBUFFERTEXTURE2DOES)getProcAddress("glFramebufferTexture2DOES");
glGetFramebufferAttachmentParameterivOES = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVOES)getProcAddress("glGetFramebufferAttachmentParameterivOES");
glGenerateMipmapOES = (PFNGLGENERATEMIPMAPOES)getProcAddress("glGenerateMipmapOES");
glBlendEquationOES = (PFNGLBLENDEQUATIONOES)getProcAddress("glBlendEquationOES");
glBlendFuncSeparateOES = (PFNGLBLENDFUNCSEPARATEOES)getProcAddress("glBlendFuncSeparateOES");
glBlendEquationSeparateOES = (PFNGLBLENDEQUATIONSEPARATEOES)getProcAddress("glBlendEquationSeparateOES");
glMapBufferOES = (PFNGLMAPBUFFEROES)getProcAddress("glMapBufferOES");
glUnmapBufferOES = (PFNGLUNMAPBUFFEROES)getProcAddress("glUnmapBufferOES");
#endif
}
bool GLES2Support::checkExtension(const String& ext) const
{
if(extensionList.find(ext) == extensionList.end())
return false;
return true;
}
}
| 49.111111 | 155 | 0.734917 | MrTypename |
2e4d2e09f38fe2cc1d1902a1c02eb7b9f4ce4204 | 1,534 | hpp | C++ | assembler/inc/symtable.hpp | miledevv/GNU-assembler-linker | 98b3df7f0b920e86ff8ad76981ed45a1f4639f27 | [
"MIT"
] | null | null | null | assembler/inc/symtable.hpp | miledevv/GNU-assembler-linker | 98b3df7f0b920e86ff8ad76981ed45a1f4639f27 | [
"MIT"
] | null | null | null | assembler/inc/symtable.hpp | miledevv/GNU-assembler-linker | 98b3df7f0b920e86ff8ad76981ed45a1f4639f27 | [
"MIT"
] | null | null | null | #ifndef _SYMTABLE_H
#define _SYMTABLE_H
#include <iostream>
#include <string>
#include <sstream>
#include <list>
using namespace std;
#define UND -2
#define LOCAL 0
#define GLOBAL 1
#define IS_EQU 1
#define R_VN_PC16 0
#define R_VN_16 1
typedef struct {
int id;
string name;
int value;
short bind; // 0 - local , global - 1
int mysec;
int size;
bool is_section;
bool is_equ;
} symdata;
typedef struct {
int offset;
string type;
string value;
} reldata;
class SymbolTable
{
public:
SymbolTable();
void add(string name, int value, short bind, int ndx, bool is_equ);
static int get_id();
void st_print(stringstream &stream);
string print_mysection(symdata& el);
bool is_global(string name);
bool is_equ(string name);
int get_symValue(string symbol_name);
int get_symId(string symbol_name);
int get_sectionId(string symbol_name); //Vraca mysec - tj sekciju u kojoj je simbol definisan.
string get_symName(int id);
void set_size(string name, int size);
bool symbol_exists(string name);
void set_global(string name);
private:
static int st_ID;
list<symdata> symt_entry;
};
// ----------------------------- REL TABLE -----------------------------
class RelTable {
public:
RelTable(string name);
void push_entry(int offset, string type, string value);
void print_reltable(stringstream &stream);
string get_name();
private:
list<reldata> relt_entry;
string name;
};
#endif | 19.417722 | 106 | 0.651239 | miledevv |
2e4e07adf7de00411219cc4f0eec23ac345206e1 | 18,061 | hpp | C++ | src/Color.hpp | sweetkristas/svg_parser | 6d591823eba6ba2423e898fe323f1cdbe08d7947 | [
"Zlib"
] | null | null | null | src/Color.hpp | sweetkristas/svg_parser | 6d591823eba6ba2423e898fe323f1cdbe08d7947 | [
"Zlib"
] | null | null | null | src/Color.hpp | sweetkristas/svg_parser | 6d591823eba6ba2423e898fe323f1cdbe08d7947 | [
"Zlib"
] | null | null | null | /*
Copyright (C) 2013-2014 by Kristina Simpson <sweet.kristas@gmail.com>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgement in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#pragma once
#include <iostream>
#include <memory>
#include <string>
#include <glm/gtc/type_precision.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "variant.hpp"
namespace KRE
{
class Color;
typedef std::shared_ptr<Color> ColorPtr;
enum class ColorByteOrder
{
RGBA,
ARGB,
BGRA,
ABGR,
};
class Color
{
public:
Color();
~Color();
explicit Color(const float r, const float g, const float b, const float a=1.0f);
explicit Color(const int r, const int g, const int b, const int a=255);
explicit Color(const std::string& s);
explicit Color(const variant& node);
explicit Color(const glm::vec4& value);
explicit Color(const glm::u8vec4& value);
explicit Color(unsigned long n, ColorByteOrder order=ColorByteOrder::RGBA);
float r() const { return color_[0]; }
float g() const { return color_[1]; }
float b() const { return color_[2]; }
float a() const { return color_[3]; }
float red() const { return color_[0]; }
float green() const { return color_[1]; }
float blue() const { return color_[2]; }
float alpha() const { return color_[3]; }
int ri() const { return icolor_.r; }
int gi() const { return icolor_.g; }
int bi() const { return icolor_.b; }
int ai() const { return icolor_.a; }
int r_int() const { return icolor_.r; }
int g_int() const { return icolor_.g; }
int b_int() const { return icolor_.b; }
int a_int() const { return icolor_.a; }
void setRed(int a);
void setRed(float a);
void setGreen(int a);
void setGreen(float a);
void setBlue(int a);
void setBlue(float a);
void setAlpha(int a);
void setAlpha(float a);
uint32_t asARGB() const {
return (static_cast<uint32_t>(icolor_.a) << 24)
| (static_cast<uint32_t>(icolor_.r) << 16)
| (static_cast<uint32_t>(icolor_.g) << 8)
| (static_cast<uint32_t>(icolor_.b));
}
uint32_t asRGBA() const {
return (static_cast<uint32_t>(icolor_.r) << 24)
| (static_cast<uint32_t>(icolor_.g) << 16)
| (static_cast<uint32_t>(icolor_.b) << 8)
| (static_cast<uint32_t>(icolor_.a));
}
bool operator==(const Color& rhs) const {
return asRGBA() == rhs.asRGBA();
}
std::size_t operator()(const Color& color) const {
return asRGBA();
}
glm::u8vec4 as_u8vec4(ColorByteOrder order=ColorByteOrder::RGBA) const {
switch(order) {
case ColorByteOrder::BGRA: return glm::u8vec4(b_int(), g_int(), r_int(), a_int());
case ColorByteOrder::ARGB: return glm::u8vec4(a_int(), r_int(), g_int(), b_int());
case ColorByteOrder::ABGR: return glm::u8vec4(a_int(), b_int(), g_int(), r_int());
default: break;
}
return icolor_;
}
const float* asFloatVector(ColorByteOrder order=ColorByteOrder::RGBA) const {
switch(order) {
case ColorByteOrder::BGRA: return glm::value_ptr(glm::vec4(color_[2], color_[1], color_[0], color_[3]));
case ColorByteOrder::ARGB: return glm::value_ptr(glm::vec4(color_[3], color_[0], color_[1], color_[2]));
case ColorByteOrder::ABGR: return glm::value_ptr(glm::vec4(color_[3], color_[2], color_[1], color_[0]));
default: break;
}
return glm::value_ptr(color_);
}
glm::u8vec4 to_hsv() const;
glm::vec4 to_hsv_vec4() const;
static Color from_hsv(int h, int s, int v, int a=255);
static Color from_hsv(float h, float s, float v, float a=1.0f);
variant write() const;
void preMultiply();
void preMultiply(int alpha);
void preMultiply(float alpha);
static ColorPtr factory(const std::string& name);
static const Color& colorAliceblue() { static Color res(240, 248, 255); return res; }
static const Color& colorAntiquewhite() { static Color res(250, 235, 215); return res; }
static const Color& colorAqua() { static Color res(0, 255, 255); return res; }
static const Color& colorAquamarine() { static Color res(127, 255, 212); return res; }
static const Color& colorAzure() { static Color res(240, 255, 255); return res; }
static const Color& colorBeige() { static Color res(245, 245, 220); return res; }
static const Color& colorBisque() { static Color res(255, 228, 196); return res; }
static const Color& colorBlack() { static Color res(0, 0, 0); return res; }
static const Color& colorBlanchedalmond() { static Color res(255, 235, 205); return res; }
static const Color& colorBlue() { static Color res(0, 0, 255); return res; }
static const Color& colorBlueviolet() { static Color res(138, 43, 226); return res; }
static const Color& colorBrown() { static Color res(165, 42, 42); return res; }
static const Color& colorBurlywood() { static Color res(222, 184, 135); return res; }
static const Color& colorCadetblue() { static Color res(95, 158, 160); return res; }
static const Color& colorChartreuse() { static Color res(127, 255, 0); return res; }
static const Color& colorChocolate() { static Color res(210, 105, 30); return res; }
static const Color& colorCoral() { static Color res(255, 127, 80); return res; }
static const Color& colorCornflowerblue() { static Color res(100, 149, 237); return res; }
static const Color& colorCornsilk() { static Color res(255, 248, 220); return res; }
static const Color& colorCrimson() { static Color res(220, 20, 60); return res; }
static const Color& colorCyan() { static Color res(0, 255, 255); return res; }
static const Color& colorDarkblue() { static Color res(0, 0, 139); return res; }
static const Color& colorDarkcyan() { static Color res(0, 139, 139); return res; }
static const Color& colorDarkgoldenrod() { static Color res(184, 134, 11); return res; }
static const Color& colorDarkgray() { static Color res(169, 169, 169); return res; }
static const Color& colorDarkgreen() { static Color res(0, 100, 0); return res; }
static const Color& colorDarkgrey() { static Color res(169, 169, 169); return res; }
static const Color& colorDarkkhaki() { static Color res(189, 183, 107); return res; }
static const Color& colorDarkmagenta() { static Color res(139, 0, 139); return res; }
static const Color& colorDarkolivegreen() { static Color res(85, 107, 47); return res; }
static const Color& colorDarkorange() { static Color res(255, 140, 0); return res; }
static const Color& colorDarkorchid() { static Color res(153, 50, 204); return res; }
static const Color& colorDarkred() { static Color res(139, 0, 0); return res; }
static const Color& colorDarksalmon() { static Color res(233, 150, 122); return res; }
static const Color& colorDarkseagreen() { static Color res(143, 188, 143); return res; }
static const Color& colorDarkslateblue() { static Color res(72, 61, 139); return res; }
static const Color& colorDarkslategray() { static Color res(47, 79, 79); return res; }
static const Color& colorDarkslategrey() { static Color res(47, 79, 79); return res; }
static const Color& colorDarkturquoise() { static Color res(0, 206, 209); return res; }
static const Color& colorDarkviolet() { static Color res(148, 0, 211); return res; }
static const Color& colorDeeppink() { static Color res(255, 20, 147); return res; }
static const Color& colorDeepskyblue() { static Color res(0, 191, 255); return res; }
static const Color& colorDimgray() { static Color res(105, 105, 105); return res; }
static const Color& colorDimgrey() { static Color res(105, 105, 105); return res; }
static const Color& colorDodgerblue() { static Color res(30, 144, 255); return res; }
static const Color& colorFirebrick() { static Color res(178, 34, 34); return res; }
static const Color& colorFloralwhite() { static Color res(255, 250, 240); return res; }
static const Color& colorForestgreen() { static Color res(34, 139, 34); return res; }
static const Color& colorFuchsia() { static Color res(255, 0, 255); return res; }
static const Color& colorGainsboro() { static Color res(220, 220, 220); return res; }
static const Color& colorGhostwhite() { static Color res(248, 248, 255); return res; }
static const Color& colorGold() { static Color res(255, 215, 0); return res; }
static const Color& colorGoldenrod() { static Color res(218, 165, 32); return res; }
static const Color& colorGray() { static Color res(128, 128, 128); return res; }
static const Color& colorGrey() { static Color res(128, 128, 128); return res; }
static const Color& colorGreen() { static Color res(0, 128, 0); return res; }
static const Color& colorGreenyellow() { static Color res(173, 255, 47); return res; }
static const Color& colorHoneydew() { static Color res(240, 255, 240); return res; }
static const Color& colorHotpink() { static Color res(255, 105, 180); return res; }
static const Color& colorIndianred() { static Color res(205, 92, 92); return res; }
static const Color& colorIndigo() { static Color res(75, 0, 130); return res; }
static const Color& colorIvory() { static Color res(255, 255, 240); return res; }
static const Color& colorKhaki() { static Color res(240, 230, 140); return res; }
static const Color& colorLavender() { static Color res(230, 230, 250); return res; }
static const Color& colorLavenderblush() { static Color res(255, 240, 245); return res; }
static const Color& colorLawngreen() { static Color res(124, 252, 0); return res; }
static const Color& colorLemonchiffon() { static Color res(255, 250, 205); return res; }
static const Color& colorLightblue() { static Color res(173, 216, 230); return res; }
static const Color& colorLightcoral() { static Color res(240, 128, 128); return res; }
static const Color& colorLightcyan() { static Color res(224, 255, 255); return res; }
static const Color& colorLightgoldenrodyellow() { static Color res(250, 250, 210); return res; }
static const Color& colorLightgray() { static Color res(211, 211, 211); return res; }
static const Color& colorLightgreen() { static Color res(144, 238, 144); return res; }
static const Color& colorLightgrey() { static Color res(211, 211, 211); return res; }
static const Color& colorLightpink() { static Color res(255, 182, 193); return res; }
static const Color& colorLightsalmon() { static Color res(255, 160, 122); return res; }
static const Color& colorLightseagreen() { static Color res(32, 178, 170); return res; }
static const Color& colorLightskyblue() { static Color res(135, 206, 250); return res; }
static const Color& colorLightslategray() { static Color res(119, 136, 153); return res; }
static const Color& colorLightslategrey() { static Color res(119, 136, 153); return res; }
static const Color& colorLightsteelblue() { static Color res(176, 196, 222); return res; }
static const Color& colorLightyellow() { static Color res(255, 255, 224); return res; }
static const Color& colorLime() { static Color res(0, 255, 0); return res; }
static const Color& colorLimegreen() { static Color res(50, 205, 50); return res; }
static const Color& colorLinen() { static Color res(250, 240, 230); return res; }
static const Color& colorMagenta() { static Color res(255, 0, 255); return res; }
static const Color& colorMaroon() { static Color res(128, 0, 0); return res; }
static const Color& colorMediumaquamarine() { static Color res(102, 205, 170); return res; }
static const Color& colorMediumblue() { static Color res(0, 0, 205); return res; }
static const Color& colorMediumorchid() { static Color res(186, 85, 211); return res; }
static const Color& colorMediumpurple() { static Color res(147, 112, 219); return res; }
static const Color& colorMediumseagreen() { static Color res(60, 179, 113); return res; }
static const Color& colorMediumslateblue() { static Color res(123, 104, 238); return res; }
static const Color& colorMediumspringgreen() { static Color res(0, 250, 154); return res; }
static const Color& colorMediumturquoise() { static Color res(72, 209, 204); return res; }
static const Color& colorMediumvioletred() { static Color res(199, 21, 133); return res; }
static const Color& colorMidnightblue() { static Color res(25, 25, 112); return res; }
static const Color& colorMintcream() { static Color res(245, 255, 250); return res; }
static const Color& colorMistyrose() { static Color res(255, 228, 225); return res; }
static const Color& colorMoccasin() { static Color res(255, 228, 181); return res; }
static const Color& colorNavajowhite() { static Color res(255, 222, 173); return res; }
static const Color& colorNavy() { static Color res(0, 0, 128); return res; }
static const Color& colorOldlace() { static Color res(253, 245, 230); return res; }
static const Color& colorOlive() { static Color res(128, 128, 0); return res; }
static const Color& colorOlivedrab() { static Color res(107, 142, 35); return res; }
static const Color& colorOrange() { static Color res(255, 165, 0); return res; }
static const Color& colorOrangered() { static Color res(255, 69, 0); return res; }
static const Color& colorOrchid() { static Color res(218, 112, 214); return res; }
static const Color& colorPalegoldenrod() { static Color res(238, 232, 170); return res; }
static const Color& colorPalegreen() { static Color res(152, 251, 152); return res; }
static const Color& colorPaleturquoise() { static Color res(175, 238, 238); return res; }
static const Color& colorPalevioletred() { static Color res(219, 112, 147); return res; }
static const Color& colorPapayawhip() { static Color res(255, 239, 213); return res; }
static const Color& colorPeachpuff() { static Color res(255, 218, 185); return res; }
static const Color& colorPeru() { static Color res(205, 133, 63); return res; }
static const Color& colorPink() { static Color res(255, 192, 203); return res; }
static const Color& colorPlum() { static Color res(221, 160, 221); return res; }
static const Color& colorPowderblue() { static Color res(176, 224, 230); return res; }
static const Color& colorPurple() { static Color res(128, 0, 128); return res; }
static const Color& colorRed() { static Color res(255, 0, 0); return res; }
static const Color& colorRosybrown() { static Color res(188, 143, 143); return res; }
static const Color& colorRoyalblue() { static Color res(65, 105, 225); return res; }
static const Color& colorSaddlebrown() { static Color res(139, 69, 19); return res; }
static const Color& colorSalmon() { static Color res(250, 128, 114); return res; }
static const Color& colorSandybrown() { static Color res(244, 164, 96); return res; }
static const Color& colorSeagreen() { static Color res(46, 139, 87); return res; }
static const Color& colorSeashell() { static Color res(255, 245, 238); return res; }
static const Color& colorSienna() { static Color res(160, 82, 45); return res; }
static const Color& colorSilver() { static Color res(192, 192, 192); return res; }
static const Color& colorSkyblue() { static Color res(135, 206, 235); return res; }
static const Color& colorSlateblue() { static Color res(106, 90, 205); return res; }
static const Color& colorSlategray() { static Color res(112, 128, 144); return res; }
static const Color& colorSlategrey() { static Color res(112, 128, 144); return res; }
static const Color& colorSnow() { static Color res(255, 250, 250); return res; }
static const Color& colorSpringgreen() { static Color res(0, 255, 127); return res; }
static const Color& colorSteelblue() { static Color res(70, 130, 180); return res; }
static const Color& colorTan() { static Color res(210, 180, 140); return res; }
static const Color& colorTeal() { static Color res(0, 128, 128); return res; }
static const Color& colorThistle() { static Color res(216, 191, 216); return res; }
static const Color& colorTomato() { static Color res(255, 99, 71); return res; }
static const Color& colorTurquoise() { static Color res(64, 224, 208); return res; }
static const Color& colorViolet() { static Color res(238, 130, 238); return res; }
static const Color& colorWheat() { static Color res(245, 222, 179); return res; }
static const Color& colorWhite() { static Color res(255, 255, 255); return res; }
static const Color& colorWhitesmoke() { static Color res(245, 245, 245); return res; }
static const Color& colorYellow() { static Color res(255, 255, 0); return res; }
static const Color& colorYellowgreen() { static Color res(154, 205, 50); return res; }
// XXX We should have a ColorCallable, in a seperate file, then move these two into the ColorCallable.
static std::string getSetFieldType() { return "string"
"|[int,int,int,int]"
"|[int,int,int]"
"|{red:int|decimal,green:int|decimal,blue:int|decimal,alpha:int|decimal|null}"
"|{r:int|decimal,g:int|decimal,b:int|decimal,a:int|decimal|null}"; }
static std::string getDefineFieldType() { return "[int,int,int,int]"; }
private:
void convert_to_icolor();
void convert_to_color();
glm::u8vec4 icolor_;
glm::vec4 color_;
};
std::ostream& operator<<(std::ostream& os, const Color& c);
inline bool operator<(const Color& lhs, const Color& rhs)
{
return lhs.asARGB() < rhs.asARGB();
}
inline bool operator!=(const Color& lhs, const Color& rhs)
{
return !(lhs == rhs);
}
Color operator*(const Color& lhs, const Color& rhs);
typedef std::shared_ptr<Color> ColorPtr;
}
| 55.572308 | 107 | 0.696473 | sweetkristas |
2e50a0649921d3dbd239de28ffcf938e55d0c04a | 5,303 | cc | C++ | third_party/blink/renderer/platform/heap/heap_traits_test.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/platform/heap/heap_traits_test.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/platform/heap/heap_traits_test.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 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 <type_traits>
#include <utility>
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/heap/heap_traits.h"
#include "third_party/blink/renderer/platform/heap/member.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
// No gtest tests; only static_assert checks.
namespace blink {
class Visitor;
namespace {
struct Empty {};
// Similar to an IDL union or dictionary, which have Trace() methods but are
// not garbage-collected types themselves.
struct StructWithTraceMethod {
void Trace(Visitor*) {}
};
struct GarbageCollectedStruct
: public GarbageCollected<GarbageCollectedStruct> {
void Trace(Visitor*) {}
};
// AddMemberIfNeeded<T>
static_assert(std::is_same<AddMemberIfNeeded<double>, double>::value,
"AddMemberIfNeeded<double> must not add a Member wrapper");
static_assert(std::is_same<AddMemberIfNeeded<double*>, double*>::value,
"AddMemberIfNeeded<double*> must not add a Member wrapper");
static_assert(std::is_same<AddMemberIfNeeded<Empty>, Empty>::value,
"AddMemberIfNeeded<Empty> must not add a Member wrapper");
static_assert(
std::is_same<AddMemberIfNeeded<StructWithTraceMethod>,
StructWithTraceMethod>::value,
"AddMemberIfNeeded<StructWithTraceMethod> must not add a Member wrapper");
static_assert(
std::is_same<AddMemberIfNeeded<GarbageCollectedStruct>,
Member<GarbageCollectedStruct>>::value,
"AddMemberIfNeeded<GarbageCollectedStruct> must not add a Member wrapper");
static_assert(
std::is_same<AddMemberIfNeeded<HeapVector<Member<GarbageCollectedStruct>>>,
Member<HeapVector<Member<GarbageCollectedStruct>>>>::value,
"AddMemberIfNeeded on a HeapVector<Member<T>> must wrap it in a Member<>");
// VectorOf<T>
static_assert(std::is_same<VectorOf<double>, Vector<double>>::value,
"VectorOf<double> should use a Vector");
static_assert(std::is_same<VectorOf<double*>, Vector<double*>>::value,
"VectorOf<double*> should use a Vector");
static_assert(std::is_same<VectorOf<Empty>, Vector<Empty>>::value,
"VectorOf<Empty> should use a Vector");
static_assert(
std::is_same<VectorOf<StructWithTraceMethod>,
HeapVector<StructWithTraceMethod>>::value,
"VectorOf<StructWithTraceMethod> must not add a Member<> wrapper");
static_assert(std::is_same<VectorOf<GarbageCollectedStruct>,
HeapVector<Member<GarbageCollectedStruct>>>::value,
"VectorOf<GarbageCollectedStruct> must add a Member<> wrapper");
static_assert(
std::is_same<VectorOf<Vector<double>>, Vector<Vector<double>>>::value,
"Nested Vectors must not add HeapVectors");
static_assert(
std::is_same<VectorOf<HeapVector<StructWithTraceMethod>>,
HeapVector<Member<HeapVector<StructWithTraceMethod>>>>::value,
"Nested HeapVector<StructWithTraceMethod> must add a HeapVector");
static_assert(
std::is_same<
VectorOf<HeapVector<Member<GarbageCollectedStruct>>>,
HeapVector<Member<HeapVector<Member<GarbageCollectedStruct>>>>>::value,
"Nested HeapVectors must not add Vectors");
// VectorOfPairs<T, U>
static_assert(std::is_same<VectorOfPairs<int, double>,
Vector<std::pair<int, double>>>::value,
"POD types must use a regular Vector");
static_assert(std::is_same<VectorOfPairs<Empty, double>,
Vector<std::pair<Empty, double>>>::value,
"POD types must use a regular Vector");
static_assert(
std::is_same<VectorOfPairs<StructWithTraceMethod, float>,
HeapVector<std::pair<StructWithTraceMethod, float>>>::value,
"StructWithTraceMethod causes a HeapVector to be used");
static_assert(
std::is_same<VectorOfPairs<float, StructWithTraceMethod>,
HeapVector<std::pair<float, StructWithTraceMethod>>>::value,
"StructWithTraceMethod causes a HeapVector to be used");
static_assert(
std::is_same<VectorOfPairs<StructWithTraceMethod, StructWithTraceMethod>,
HeapVector<std::pair<StructWithTraceMethod,
StructWithTraceMethod>>>::value,
"StructWithTraceMethod causes a HeapVector to be used");
static_assert(
std::is_same<
VectorOfPairs<GarbageCollectedStruct, float>,
HeapVector<std::pair<Member<GarbageCollectedStruct>, float>>>::value,
"GarbageCollectedStruct causes a HeapVector to be used");
static_assert(
std::is_same<
VectorOfPairs<float, GarbageCollectedStruct>,
HeapVector<std::pair<float, Member<GarbageCollectedStruct>>>>::value,
"GarbageCollectedStruct causes a HeapVector to be used");
static_assert(
std::is_same<VectorOfPairs<GarbageCollectedStruct, GarbageCollectedStruct>,
HeapVector<std::pair<Member<GarbageCollectedStruct>,
Member<GarbageCollectedStruct>>>>::value,
"GarbageCollectedStruct causes a HeapVector to be used");
} // namespace
} // namespace blink
| 41.755906 | 79 | 0.707147 | sarang-apps |
2e519b4b635eae79996faec251229134c54cba03 | 18,250 | hpp | C++ | machine_learning/vector_ops.hpp | icbdubey/C-Plus-Plus | d51947a9d5a96695ea52db4394db6518d777bddf | [
"MIT"
] | 20,295 | 2016-07-17T06:29:04.000Z | 2022-03-31T23:32:16.000Z | machine_learning/vector_ops.hpp | icbdubey/C-Plus-Plus | d51947a9d5a96695ea52db4394db6518d777bddf | [
"MIT"
] | 1,399 | 2017-06-02T05:59:45.000Z | 2022-03-31T00:55:00.000Z | machine_learning/vector_ops.hpp | icbdubey/C-Plus-Plus | d51947a9d5a96695ea52db4394db6518d777bddf | [
"MIT"
] | 5,775 | 2016-10-14T08:10:18.000Z | 2022-03-31T18:26:39.000Z | /**
* @file vector_ops.hpp
* @author [Deep Raval](https://github.com/imdeep2905)
*
* @brief Various functions for vectors associated with [NeuralNetwork (aka
* Multilayer Perceptron)]
* (https://en.wikipedia.org/wiki/Multilayer_perceptron).
*
*/
#ifndef VECTOR_OPS_FOR_NN
#define VECTOR_OPS_FOR_NN
#include <algorithm>
#include <chrono>
#include <iostream>
#include <random>
#include <valarray>
#include <vector>
/**
* @namespace machine_learning
* @brief Machine Learning algorithms
*/
namespace machine_learning {
/**
* Overloaded operator "<<" to print 2D vector
* @tparam T typename of the vector
* @param out std::ostream to output
* @param A 2D vector to be printed
*/
template <typename T>
std::ostream &operator<<(std::ostream &out,
std::vector<std::valarray<T>> const &A) {
// Setting output precision to 4 in case of floating point numbers
out.precision(4);
for (const auto &a : A) { // For each row in A
for (const auto &x : a) { // For each element in row
std::cout << x << ' '; // print element
}
std::cout << std::endl;
}
return out;
}
/**
* Overloaded operator "<<" to print a pair
* @tparam T typename of the pair
* @param out std::ostream to output
* @param A Pair to be printed
*/
template <typename T>
std::ostream &operator<<(std::ostream &out, const std::pair<T, T> &A) {
// Setting output precision to 4 in case of floating point numbers
out.precision(4);
// printing pair in the form (p, q)
std::cout << "(" << A.first << ", " << A.second << ")";
return out;
}
/**
* Overloaded operator "<<" to print a 1D vector
* @tparam T typename of the vector
* @param out std::ostream to output
* @param A 1D vector to be printed
*/
template <typename T>
std::ostream &operator<<(std::ostream &out, const std::valarray<T> &A) {
// Setting output precision to 4 in case of floating point numbers
out.precision(4);
for (const auto &a : A) { // For every element in the vector.
std::cout << a << ' '; // Print element
}
std::cout << std::endl;
return out;
}
/**
* Function to insert element into 1D vector
* @tparam T typename of the 1D vector and the element
* @param A 1D vector in which element will to be inserted
* @param ele element to be inserted
* @return new resultant vector
*/
template <typename T>
std::valarray<T> insert_element(const std::valarray<T> &A, const T &ele) {
std::valarray<T> B; // New 1D vector to store resultant vector
B.resize(A.size() + 1); // Resizing it accordingly
for (size_t i = 0; i < A.size(); i++) { // For every element in A
B[i] = A[i]; // Copy element in B
}
B[B.size() - 1] = ele; // Inserting new element in last position
return B; // Return resultant vector
}
/**
* Function to remove first element from 1D vector
* @tparam T typename of the vector
* @param A 1D vector from which first element will be removed
* @return new resultant vector
*/
template <typename T>
std::valarray<T> pop_front(const std::valarray<T> &A) {
std::valarray<T> B; // New 1D vector to store resultant vector
B.resize(A.size() - 1); // Resizing it accordingly
for (size_t i = 1; i < A.size();
i++) { // // For every (except first) element in A
B[i - 1] = A[i]; // Copy element in B with left shifted position
}
return B; // Return resultant vector
}
/**
* Function to remove last element from 1D vector
* @tparam T typename of the vector
* @param A 1D vector from which last element will be removed
* @return new resultant vector
*/
template <typename T>
std::valarray<T> pop_back(const std::valarray<T> &A) {
std::valarray<T> B; // New 1D vector to store resultant vector
B.resize(A.size() - 1); // Resizing it accordingly
for (size_t i = 0; i < A.size() - 1;
i++) { // For every (except last) element in A
B[i] = A[i]; // Copy element in B
}
return B; // Return resultant vector
}
/**
* Function to equally shuffle two 3D vectors (used for shuffling training data)
* @tparam T typename of the vector
* @param A First 3D vector
* @param B Second 3D vector
*/
template <typename T>
void equal_shuffle(std::vector<std::vector<std::valarray<T>>> &A,
std::vector<std::vector<std::valarray<T>>> &B) {
// If two vectors have different sizes
if (A.size() != B.size()) {
std::cerr << "ERROR (" << __func__ << ") : ";
std::cerr
<< "Can not equally shuffle two vectors with different sizes: ";
std::cerr << A.size() << " and " << B.size() << std::endl;
std::exit(EXIT_FAILURE);
}
for (size_t i = 0; i < A.size(); i++) { // For every element in A and B
// Genrating random index < size of A and B
std::srand(std::chrono::system_clock::now().time_since_epoch().count());
size_t random_index = std::rand() % A.size();
// Swap elements in both A and B with same random index
std::swap(A[i], A[random_index]);
std::swap(B[i], B[random_index]);
}
return;
}
/**
* Function to initialize given 2D vector using uniform random initialization
* @tparam T typename of the vector
* @param A 2D vector to be initialized
* @param shape required shape
* @param low lower limit on value
* @param high upper limit on value
*/
template <typename T>
void uniform_random_initialization(std::vector<std::valarray<T>> &A,
const std::pair<size_t, size_t> &shape,
const T &low, const T &high) {
A.clear(); // Making A empty
// Uniform distribution in range [low, high]
std::default_random_engine generator(
std::chrono::system_clock::now().time_since_epoch().count());
std::uniform_real_distribution<T> distribution(low, high);
for (size_t i = 0; i < shape.first; i++) { // For every row
std::valarray<T>
row; // Making empty row which will be inserted in vector
row.resize(shape.second);
for (auto &r : row) { // For every element in row
r = distribution(generator); // copy random number
}
A.push_back(row); // Insert new row in vector
}
return;
}
/**
* Function to Intialize 2D vector as unit matrix
* @tparam T typename of the vector
* @param A 2D vector to be initialized
* @param shape required shape
*/
template <typename T>
void unit_matrix_initialization(std::vector<std::valarray<T>> &A,
const std::pair<size_t, size_t> &shape) {
A.clear(); // Making A empty
for (size_t i = 0; i < shape.first; i++) {
std::valarray<T>
row; // Making empty row which will be inserted in vector
row.resize(shape.second);
row[i] = T(1); // Insert 1 at ith position
A.push_back(row); // Insert new row in vector
}
return;
}
/**
* Function to Intialize 2D vector as zeroes
* @tparam T typename of the vector
* @param A 2D vector to be initialized
* @param shape required shape
*/
template <typename T>
void zeroes_initialization(std::vector<std::valarray<T>> &A,
const std::pair<size_t, size_t> &shape) {
A.clear(); // Making A empty
for (size_t i = 0; i < shape.first; i++) {
std::valarray<T>
row; // Making empty row which will be inserted in vector
row.resize(shape.second); // By default all elements are zero
A.push_back(row); // Insert new row in vector
}
return;
}
/**
* Function to get sum of all elements in 2D vector
* @tparam T typename of the vector
* @param A 2D vector for which sum is required
* @return returns sum of all elements of 2D vector
*/
template <typename T>
T sum(const std::vector<std::valarray<T>> &A) {
T cur_sum = 0; // Initially sum is zero
for (const auto &a : A) { // For every row in A
cur_sum += a.sum(); // Add sum of that row to current sum
}
return cur_sum; // Return sum
}
/**
* Function to get shape of given 2D vector
* @tparam T typename of the vector
* @param A 2D vector for which shape is required
* @return shape as pair
*/
template <typename T>
std::pair<size_t, size_t> get_shape(const std::vector<std::valarray<T>> &A) {
const size_t sub_size = (*A.begin()).size();
for (const auto &a : A) {
// If supplied vector don't have same shape in all rows
if (a.size() != sub_size) {
std::cerr << "ERROR (" << __func__ << ") : ";
std::cerr << "Supplied vector is not 2D Matrix" << std::endl;
std::exit(EXIT_FAILURE);
}
}
return std::make_pair(A.size(), sub_size); // Return shape as pair
}
/**
* Function to scale given 3D vector using min-max scaler
* @tparam T typename of the vector
* @param A 3D vector which will be scaled
* @param low new minimum value
* @param high new maximum value
* @return new scaled 3D vector
*/
template <typename T>
std::vector<std::vector<std::valarray<T>>> minmax_scaler(
const std::vector<std::vector<std::valarray<T>>> &A, const T &low,
const T &high) {
std::vector<std::vector<std::valarray<T>>> B =
A; // Copying into new vector B
const auto shape = get_shape(B[0]); // Storing shape of B's every element
// As this function is used for scaling training data vector should be of
// shape (1, X)
if (shape.first != 1) {
std::cerr << "ERROR (" << __func__ << ") : ";
std::cerr
<< "Supplied vector is not supported for minmax scaling, shape: ";
std::cerr << shape << std::endl;
std::exit(EXIT_FAILURE);
}
for (size_t i = 0; i < shape.second; i++) {
T min = B[0][0][i], max = B[0][0][i];
for (size_t j = 0; j < B.size(); j++) {
// Updating minimum and maximum values
min = std::min(min, B[j][0][i]);
max = std::max(max, B[j][0][i]);
}
for (size_t j = 0; j < B.size(); j++) {
// Applying min-max scaler formula
B[j][0][i] =
((B[j][0][i] - min) / (max - min)) * (high - low) + low;
}
}
return B; // Return new resultant 3D vector
}
/**
* Function to get index of maximum element in 2D vector
* @tparam T typename of the vector
* @param A 2D vector for which maximum index is required
* @return index of maximum element
*/
template <typename T>
size_t argmax(const std::vector<std::valarray<T>> &A) {
const auto shape = get_shape(A);
// As this function is used on predicted (or target) vector, shape should be
// (1, X)
if (shape.first != 1) {
std::cerr << "ERROR (" << __func__ << ") : ";
std::cerr << "Supplied vector is ineligible for argmax" << std::endl;
std::exit(EXIT_FAILURE);
}
// Return distance of max element from first element (i.e. index)
return std::distance(std::begin(A[0]),
std::max_element(std::begin(A[0]), std::end(A[0])));
}
/**
* Function which applys supplied function to every element of 2D vector
* @tparam T typename of the vector
* @param A 2D vector on which function will be applied
* @param func Function to be applied
* @return new resultant vector
*/
template <typename T>
std::vector<std::valarray<T>> apply_function(
const std::vector<std::valarray<T>> &A, T (*func)(const T &)) {
std::vector<std::valarray<double>> B =
A; // New vector to store resultant vector
for (auto &b : B) { // For every row in vector
b = b.apply(func); // Apply function to that row
}
return B; // Return new resultant 2D vector
}
/**
* Overloaded operator "*" to multiply given 2D vector with scaler
* @tparam T typename of both vector and the scaler
* @param A 2D vector to which scaler will be multiplied
* @param val Scaler value which will be multiplied
* @return new resultant vector
*/
template <typename T>
std::vector<std::valarray<T>> operator*(const std::vector<std::valarray<T>> &A,
const T &val) {
std::vector<std::valarray<double>> B =
A; // New vector to store resultant vector
for (auto &b : B) { // For every row in vector
b = b * val; // Multiply row with scaler
}
return B; // Return new resultant 2D vector
}
/**
* Overloaded operator "/" to divide given 2D vector with scaler
* @tparam T typename of the vector and the scaler
* @param A 2D vector to which scaler will be divided
* @param val Scaler value which will be divided
* @return new resultant vector
*/
template <typename T>
std::vector<std::valarray<T>> operator/(const std::vector<std::valarray<T>> &A,
const T &val) {
std::vector<std::valarray<double>> B =
A; // New vector to store resultant vector
for (auto &b : B) { // For every row in vector
b = b / val; // Divide row with scaler
}
return B; // Return new resultant 2D vector
}
/**
* Function to get transpose of 2D vector
* @tparam T typename of the vector
* @param A 2D vector which will be transposed
* @return new resultant vector
*/
template <typename T>
std::vector<std::valarray<T>> transpose(
const std::vector<std::valarray<T>> &A) {
const auto shape = get_shape(A); // Current shape of vector
std::vector<std::valarray<T>> B; // New vector to store result
// Storing transpose values of A in B
for (size_t j = 0; j < shape.second; j++) {
std::valarray<T> row;
row.resize(shape.first);
for (size_t i = 0; i < shape.first; i++) {
row[i] = A[i][j];
}
B.push_back(row);
}
return B; // Return new resultant 2D vector
}
/**
* Overloaded operator "+" to add two 2D vectors
* @tparam T typename of the vector
* @param A First 2D vector
* @param B Second 2D vector
* @return new resultant vector
*/
template <typename T>
std::vector<std::valarray<T>> operator+(
const std::vector<std::valarray<T>> &A,
const std::vector<std::valarray<T>> &B) {
const auto shape_a = get_shape(A);
const auto shape_b = get_shape(B);
// If vectors don't have equal shape
if (shape_a.first != shape_b.first || shape_a.second != shape_b.second) {
std::cerr << "ERROR (" << __func__ << ") : ";
std::cerr << "Supplied vectors have different shapes ";
std::cerr << shape_a << " and " << shape_b << std::endl;
std::exit(EXIT_FAILURE);
}
std::vector<std::valarray<T>> C;
for (size_t i = 0; i < A.size(); i++) { // For every row
C.push_back(A[i] + B[i]); // Elementwise addition
}
return C; // Return new resultant 2D vector
}
/**
* Overloaded operator "-" to add subtract 2D vectors
* @tparam T typename of the vector
* @param A First 2D vector
* @param B Second 2D vector
* @return new resultant vector
*/
template <typename T>
std::vector<std::valarray<T>> operator-(
const std::vector<std::valarray<T>> &A,
const std::vector<std::valarray<T>> &B) {
const auto shape_a = get_shape(A);
const auto shape_b = get_shape(B);
// If vectors don't have equal shape
if (shape_a.first != shape_b.first || shape_a.second != shape_b.second) {
std::cerr << "ERROR (" << __func__ << ") : ";
std::cerr << "Supplied vectors have different shapes ";
std::cerr << shape_a << " and " << shape_b << std::endl;
std::exit(EXIT_FAILURE);
}
std::vector<std::valarray<T>> C; // Vector to store result
for (size_t i = 0; i < A.size(); i++) { // For every row
C.push_back(A[i] - B[i]); // Elementwise substraction
}
return C; // Return new resultant 2D vector
}
/**
* Function to multiply two 2D vectors
* @tparam T typename of the vector
* @param A First 2D vector
* @param B Second 2D vector
* @return new resultant vector
*/
template <typename T>
std::vector<std::valarray<T>> multiply(const std::vector<std::valarray<T>> &A,
const std::vector<std::valarray<T>> &B) {
const auto shape_a = get_shape(A);
const auto shape_b = get_shape(B);
// If vectors are not eligible for multiplication
if (shape_a.second != shape_b.first) {
std::cerr << "ERROR (" << __func__ << ") : ";
std::cerr << "Vectors are not eligible for multiplication ";
std::cerr << shape_a << " and " << shape_b << std::endl;
std::exit(EXIT_FAILURE);
}
std::vector<std::valarray<T>> C; // Vector to store result
// Normal matrix multiplication
for (size_t i = 0; i < shape_a.first; i++) {
std::valarray<T> row;
row.resize(shape_b.second);
for (size_t j = 0; j < shape_b.second; j++) {
for (size_t k = 0; k < shape_a.second; k++) {
row[j] += A[i][k] * B[k][j];
}
}
C.push_back(row);
}
return C; // Return new resultant 2D vector
}
/**
* Function to get hadamard product of two 2D vectors
* @tparam T typename of the vector
* @param A First 2D vector
* @param B Second 2D vector
* @return new resultant vector
*/
template <typename T>
std::vector<std::valarray<T>> hadamard_product(
const std::vector<std::valarray<T>> &A,
const std::vector<std::valarray<T>> &B) {
const auto shape_a = get_shape(A);
const auto shape_b = get_shape(B);
// If vectors are not eligible for hadamard product
if (shape_a.first != shape_b.first || shape_a.second != shape_b.second) {
std::cerr << "ERROR (" << __func__ << ") : ";
std::cerr << "Vectors have different shapes ";
std::cerr << shape_a << " and " << shape_b << std::endl;
std::exit(EXIT_FAILURE);
}
std::vector<std::valarray<T>> C; // Vector to store result
for (size_t i = 0; i < A.size(); i++) {
C.push_back(A[i] * B[i]); // Elementwise multiplication
}
return C; // Return new resultant 2D vector
}
} // namespace machine_learning
#endif
| 35.436893 | 80 | 0.599068 | icbdubey |
2e53cd9bd2912edeef2e6004c6ca412f668f0489 | 2,705 | cpp | C++ | src/twitter/twitterconversationfilterinterface.cpp | sailfishos/nemo-qml-plugin-social | da64c1f5665e6c3b4d4f3f244afcf90308ecfd30 | [
"BSD-3-Clause"
] | null | null | null | src/twitter/twitterconversationfilterinterface.cpp | sailfishos/nemo-qml-plugin-social | da64c1f5665e6c3b4d4f3f244afcf90308ecfd30 | [
"BSD-3-Clause"
] | null | null | null | src/twitter/twitterconversationfilterinterface.cpp | sailfishos/nemo-qml-plugin-social | da64c1f5665e6c3b4d4f3f244afcf90308ecfd30 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2013 Jolla Ltd. <chris.adams@jollamobile.com>
*
* You may use this file under the terms of the BSD license as follows:
*
* "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 Nemo Mobile 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."
*/
#include "twitterconversationfilterinterface.h"
class TwitterConversationFilterInterfacePrivate
{
public:
TwitterConversationFilterInterfacePrivate();
TwitterConversationFilterInterface::Stream stream;
};
TwitterConversationFilterInterfacePrivate::TwitterConversationFilterInterfacePrivate():
stream(TwitterConversationFilterInterface::Downstream)
{
}
// ------------------------------
TwitterConversationFilterInterface::TwitterConversationFilterInterface(QObject *parent)
: FilterInterface(parent), d_ptr(new TwitterConversationFilterInterfacePrivate)
{
}
TwitterConversationFilterInterface::~TwitterConversationFilterInterface()
{
}
TwitterConversationFilterInterface::Stream TwitterConversationFilterInterface::stream() const
{
Q_D(const TwitterConversationFilterInterface);
return d->stream;
}
void TwitterConversationFilterInterface::setStream(Stream stream)
{
Q_D(TwitterConversationFilterInterface);
if (d->stream != stream) {
d->stream = stream;
emit streamChanged();
}
}
| 37.569444 | 93 | 0.765619 | sailfishos |
2e54bdaebcea8214fdac807bd1f2f72d9d4c377a | 5,705 | cpp | C++ | tests/cthread/test_cthread_sel_bit.cpp | rseac/systemc-compiler | ad1c68054467ed8db1c4e9b8f63eda092945d56d | [
"Apache-2.0"
] | null | null | null | tests/cthread/test_cthread_sel_bit.cpp | rseac/systemc-compiler | ad1c68054467ed8db1c4e9b8f63eda092945d56d | [
"Apache-2.0"
] | null | null | null | tests/cthread/test_cthread_sel_bit.cpp | rseac/systemc-compiler | ad1c68054467ed8db1c4e9b8f63eda092945d56d | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* Copyright (c) 2020, Intel Corporation. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception.
*
*****************************************************************************/
#include "sct_assert.h"
#include <systemc.h>
// Bit access of SC type in LHS and RHS
class top : sc_module
{
public:
sc_in_clk clk;
sc_signal<bool> arstn{"arstn", 1};
sc_signal<int> in{"in"};
sc_signal<bool> in2{"in2"};
sc_signal<int> out{"out"};
sc_uint<3> a;
sc_uint<4> b;
sc_uint<5> c;
sc_uint<6> d;
sc_uint<7> e;
sc_signal<sc_uint<4>> s;
sc_signal<bool> sb;
SC_HAS_PROCESS(top);
top(sc_module_name)
{
SC_CTHREAD(bit_select_use_def, clk.pos());
async_reset_signal_is(arstn, false);
SC_CTHREAD(bit_select_use_def, clk.pos());
async_reset_signal_is(arstn, false);
SC_CTHREAD(bit_select_lhs1, clk.pos());
async_reset_signal_is(arstn, false);
SC_CTHREAD(bit_select_lhs1a, clk.pos());
async_reset_signal_is(arstn, false);
SC_CTHREAD(bit_select_lhs2, clk.pos());
async_reset_signal_is(arstn, false);
SC_CTHREAD(bit_select_lhs3, clk.pos());
async_reset_signal_is(arstn, false);
SC_CTHREAD(bit_select_lhs4, clk.pos());
async_reset_signal_is(arstn, false);
SC_CTHREAD(bit_select_lhs4a, clk.pos());
async_reset_signal_is(arstn, false);
SC_CTHREAD(bit_select_logic, clk.pos());
async_reset_signal_is(arstn, false);
SC_CTHREAD(bit_select_comp_logic, clk.pos());
async_reset_signal_is(arstn, false);
SC_CTHREAD(bit_select_lhs_misc, clk.pos());
async_reset_signal_is(arstn, false);
}
// Write some bits does not lead to defined, values is unknown
void bit_select_use_def()
{
sc_uint<5> z;
wait();
while (true) {
z[1] = 1;
sct_assert_defined(z, false);
sct_assert_unknown(z);
wait();
}
}
// @bit() in LHS with other read/write
void bit_select_lhs1()
{
out = 0;
sc_uint<3> x = 0;
a = 3;
wait();
while (true) {
x.bit(1) = 1; // Extra register for @x
a[2] = x[1];
out.write(x[1] + a);
wait();
}
}
// @bit() in LHS with other read/write
void bit_select_lhs1a()
{
out = 0;
sc_uint<3> x;
wait();
while (true) {
x[0] = 1; x[1] = 0;
x[2] = x[1] != in2;
out = (x[2] == in2) ? x.bit(1) + 1 : x[0]*2;
wait();
}
}
// No write to @b except via @bit()
void bit_select_lhs2()
{
out = 0;
wait();
while (true) {
b.bit(2) = 1;
out = b;
wait();
}
}
// No read from @c except via @bit()
void bit_select_lhs3()
{
c = 0;
wait();
while (true) {
c = 3;
c.bit(2) = 1;
wait();
}
}
// No read/write to @d except via @bit()
void bit_select_lhs4()
{
wait();
while (true) {
d.bit(0) = 1;
wait();
}
}
// No read/write to @d except via @bit()
void bit_select_lhs4a()
{
out = 1;
wait();
while (true) {
out = e.bit(2);
wait();
}
}
// @bit() used in logic expression
void bit_select_logic()
{
int j = s.read();
sc_uint<7> x = 0;
wait();
while (true) {
int k = 0;
x.bit(j) = 1;
if (x[j]) k = 1;
if (x.bit(j+1)) k = 2;
if (x[1] || j == 1) {
if (x[j] && j == 2) {
k = 3;
}
k = 4;
}
bool b = x[1] || x[2] && x[3] || !x[4];
b = x[1] || true && b && !(false || x[5] || x[6]);
wait();
}
}
// @bit() used in complex logic expression with &&/||
void bit_select_comp_logic()
{
int j = s.read();
sc_uint<3> x = 0;
x[1] = sb.read();
wait();
while (true) {
int k = 0;
if (true && x[1]) k = 1;
if (true || x[2]) k = 2;
if (false && x[3]) k = 3;
if (false || x[4]) k = 4;
if (false || true && x[5] || false) k = 5;
if (false || true && x[6] || true) k = 6;
bool b = true && x[1];
b = true || x[2];
b = false && x[3];
b = false || x[4];
b = true && false || x[5];
wait();
}
}
// Various usages of bit()
void bit_select_lhs_misc()
{
sc_uint<3> x = 0;
wait();
while (true) {
x = in.read();
if (x.bit(1)) {
x.bit(2) = x.bit(0);
}
for (int i = 0; i < 3; i++) {
x.bit(i) = i % 2;
}
wait();
}
}
};
int sc_main(int argc, char *argv[])
{
sc_clock clk{"clk", 10, SC_NS};
top top_inst{"top_inst"};
top_inst.clk(clk);
sc_start(100, SC_NS);
return 0;
}
| 23.004032 | 79 | 0.408063 | rseac |
2e5515112fa86ff46a1d3b8a190d567f110fbc29 | 3,415 | cpp | C++ | image/shifted_interp2_mex.cpp | ojwoodford/ojwul | fe8b45ee0c74ecdff2b6f832cde1b9c31f30e022 | [
"BSD-2-Clause"
] | 8 | 2017-03-13T01:20:50.000Z | 2020-09-08T12:34:28.000Z | image/shifted_interp2_mex.cpp | ojwoodford/ojwul | fe8b45ee0c74ecdff2b6f832cde1b9c31f30e022 | [
"BSD-2-Clause"
] | null | null | null | image/shifted_interp2_mex.cpp | ojwoodford/ojwul | fe8b45ee0c74ecdff2b6f832cde1b9c31f30e022 | [
"BSD-2-Clause"
] | 1 | 2017-03-13T01:20:51.000Z | 2017-03-13T01:20:51.000Z | #include <mex.h>
#include <math.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include <stdint.h>
#include "interp2_methods.hpp"
#include "../utils/private/class_handle.hpp"
typedef IM_SHIFT<uint8_t, double, double> shiftIm_t;
#if _MATLAB_ < 805 // R2015a
extern "C" mxArray *mxCreateUninitNumericArray(mwSize ndim, const size_t *dims, mxClassID classid, mxComplexity ComplexFlag);
#endif
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// Check number of arguments
if (nrhs < 1 || nrhs > 4)
mexErrMsgTxt("Unexpected number of input arguments.");
// Destructor
if (nrhs == 1) {
// Destroy the C++ object
destroyObject<shiftIm_t>(prhs[0]);
if (nlhs != 0)
mexWarnMsgTxt("Unexpected number of output arguments.");
return;
}
if (nlhs != 1)
mexErrMsgTxt("Unexpected number of output arguments.");
// Constructor
if (nrhs == 2) {
// Get the image matrix
if (mxGetClassID(prhs[0]) != mxUINT8_CLASS)
mexErrMsgTxt("im must be a uint8 array.");
const uint8_t *im = (const uint8_t *)mxGetData(prhs[0]);
// Get the number of channels
int ndims = mxGetNumberOfDimensions(prhs[0]);
const mwSize* dims = mxGetDimensions(prhs[0]);
int nchannels = 1;
for (int i = 2; i < ndims; ++i)
nchannels *= dims[i];
// Get the value for oobv
if (mxGetNumberOfElements(prhs[1]) != 1 || !mxIsDouble(prhs[1]))
mexErrMsgTxt("oobv must be a scalar double.");
double oobv = mxGetScalar(prhs[1]);
// Create a new instance of the interpolator
shiftIm_t *instance = new shiftIm_t(im, oobv, dims[0], dims[1], nchannels);
// Return a handle to the class
plhs[0] = convertPtr2Mat<shiftIm_t>(instance);
return;
}
// Get the class instance pointer from the first input
shiftIm_t *instance = convertMat2Ptr<shiftIm_t>(prhs[0]);
// Check argument types are valid
int num_points = mxGetNumberOfElements(prhs[1]);
if (!mxIsDouble(prhs[1]) || !mxIsDouble(prhs[2]) || num_points != mxGetNumberOfElements(prhs[2]) || mxIsComplex(prhs[1]) || mxIsComplex(prhs[2]))
mexErrMsgTxt("X and Y must be real double arrays of the same size");
// Get the value for oobv
if (nrhs > 3) {
if (mxGetNumberOfElements(prhs[3]) != 1 || !mxIsDouble(prhs[3]))
mexErrMsgTxt("oobv must be a scalar double.");
instance->SetOOBV(mxGetScalar(prhs[3]));
}
// Get pointers to the coordinate arrays
const double *X = (const double *)mxGetData(prhs[1]);
const double *Y = (const double *)mxGetData(prhs[2]);
// Get output dimensions
size_t out_dims[3];
out_dims[0] = mxGetM(prhs[1]);
out_dims[1] = mxGetN(prhs[1]);
out_dims[2] = instance->Channels();
// Create the output array
plhs[0] = mxCreateUninitNumericArray(3, out_dims, mxDOUBLE_CLASS, mxREAL);
double *out = (double *)mxGetData(plhs[0]);
// For each of the interpolation points
int i;
#pragma omp parallel for if (num_points > 1000) num_threads(2) default(shared) private(i)
for (i = 0; i < num_points; ++i)
instance->lookup(&out[i], Y[i]-1.0, X[i]-1.0, num_points); // Do the interpolation
return;
} | 35.947368 | 147 | 0.610835 | ojwoodford |
2e64db339c81803ee0fa08e3ac751b3266b9fe97 | 8,945 | cpp | C++ | OpenGLTraining/src/1.Start/CoordinateSystemDepth.cpp | NewBediver/OpenGLTraining | caf38b9601544e3145b9d2995d9bd28558bf3d11 | [
"Apache-2.0"
] | null | null | null | OpenGLTraining/src/1.Start/CoordinateSystemDepth.cpp | NewBediver/OpenGLTraining | caf38b9601544e3145b9d2995d9bd28558bf3d11 | [
"Apache-2.0"
] | null | null | null | OpenGLTraining/src/1.Start/CoordinateSystemDepth.cpp | NewBediver/OpenGLTraining | caf38b9601544e3145b9d2995d9bd28558bf3d11 | [
"Apache-2.0"
] | null | null | null | #include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <stb/stb_image.h>
#include "Shader/Shader.h"
#include <iostream>
// Callback for resizing
void framebufferSizeCallback(GLFWwindow* window, int width, int height);
// Input processing
void processInput(GLFWwindow* window);
int main()
{
// Initialize OpenGL and configure it
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Create GLFWwindow and configure context
GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create OpenGL window!" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// Initialize GLAD
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD!" << std::endl;
return -1;
}
// Get the maximum number of 4 component vertex attributes
int nrAttributes;
glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &nrAttributes);
std::cout << "Maximum nr of vertex attributes supported: " << nrAttributes << std::endl;
// Configure viewport
glViewport(0, 0, 800, 600);
// Setup resize callback for window
glfwSetFramebufferSizeCallback(window, framebufferSizeCallback);
//======================================
float vertices[] = {
// Position // Texture coords
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f
};
// Create shader
Shader ourShader("Shaders/6.1.CoordinateSystem.vs", "Shaders/6.1.CoordinateSystem.fs");
unsigned int VAO, VBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// Set positions
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(0));
glEnableVertexAttribArray(0);
// Set texture coords
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), reinterpret_cast<void*>(3 * sizeof(float)));
glEnableVertexAttribArray(1);
// Generate texture object
unsigned int texture1;
glGenTextures(1, &texture1);
// Bind texture
glBindTexture(GL_TEXTURE_2D, texture1);
// set the texture wrapping/filtering options (on currently bound texture)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Say stb to flip texture vertically
stbi_set_flip_vertically_on_load(true);
// Get texture image data
int width, height, nrChannels;
unsigned char* data = stbi_load("Textures/container.jpg", &width, &height, &nrChannels, 0);
if (data)
{
// Generate texture and create it's bitmap
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
std::cout << "Failed to load texture1" << std::endl;
}
// Generate texture object
unsigned int texture2;
glGenTextures(1, &texture2);
// Bind texture
glBindTexture(GL_TEXTURE_2D, texture2);
// set the texture wrapping/filtering options (on currently bound texture)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// Get texture image data
data = stbi_load("Textures/awesomeface.png", &width, &height, &nrChannels, 0);
if (data)
{
// Generate texture and create it's bitmap
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
std::cout << "Failed to load texture2" << std::endl;
}
// Free image data because we have already set it to our texture
stbi_image_free(data);
// Set texture units to its uniforms
ourShader.Use();
ourShader.SetInt("texture1", 0);
ourShader.SetInt("texture2", 1);
// Transformation matrices ----------------------------------------------------------------
// (Model matrix) Rotate model to -55 degrees by X axis
/*glm::mat4 model = glm::rotate(glm::mat4(1.0f), glm::radians(-55.0f), glm::vec3(1.0f, 0.0f, 0.0f));
// (View matrix) Move the scene in depth of the screen
glm::mat4 view = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -3.0f));
// (Projection matrix) Define perspective projection matrix
glm::mat4 projection = glm::perspective(glm::radians(45.0f), 800.0f / 600.0f, 0.1f, 100.0f);*/
// ----------------------------------------------------------------------------------------
glm::vec3 cubePositions[] = {
glm::vec3( 0.0f, 0.0f, 0.0f),
glm::vec3( 2.0f, 5.0f, -15.0f),
glm::vec3(-1.5f, -2.2f, -2.5f),
glm::vec3(-3.8f, -2.0f, -12.3f),
glm::vec3( 2.4f, -0.4f, -3.5f),
glm::vec3(-1.7f, 3.0f, -7.5f),
glm::vec3( 1.3f, -2.0f, -2.5f),
glm::vec3( 1.5f, 2.0f, -2.5f),
glm::vec3( 1.5f, 0.2f, -1.5f),
glm::vec3(-1.3f, 1.0f, -1.5f)
};
//======================================
glEnable(GL_DEPTH_TEST);
// Render loop
while (!glfwWindowShouldClose(window))
{
// Check input
processInput(window);
// State-setting function setup color
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
// State-using function uses current state to retrieve the color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//========================================
// Bind textures on corresponding texture units
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2);
// create transformations
glm::mat4 view = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -5.0f));
glm::mat4 projection = glm::mat4(1.0f);
projection = glm::perspective(glm::radians(45.0f), 800.0f / 600.0f, 0.1f, 100.0f);
// Set the matrices to transform objects
glUniformMatrix4fv(glGetUniformLocation(ourShader.GetID(), "view"), 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(glGetUniformLocation(ourShader.GetID(), "projection"), 1, GL_FALSE, glm::value_ptr(projection));
// render containers
glBindVertexArray(VAO);
for (int i = 0; i < 10; ++i)
{
glm::mat4 model = glm::translate(glm::mat4(1.0f), cubePositions[i]);
float angle = 20.0f * (i + 1);
model = glm::rotate(model, (i % 2 == 0 ? static_cast<float>(glfwGetTime()) : 1.0f) * glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f));
ourShader.SetMat4("model", model);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
ourShader.Use();
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
//=========================================
// Swap buffers
glfwSwapBuffers(window);
// Check and call events
glfwPollEvents();
}
// optional: de-allocate all resources once they've outlived their purpose:
// ------------------------------------------------------------------------
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
// Properly cleaning / deleting all the GLFW resources
glfwTerminate();
return 0;
}
void framebufferSizeCallback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
void processInput(GLFWwindow* window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, true);
}
} | 30.738832 | 138 | 0.633091 | NewBediver |
2e6587cf40f125e04aaa1173f0df233ea7d2627c | 370 | cpp | C++ | Competitive Programming/RotaUFMG/Roteiro 2 (STL)/EleEstaImpedido.cpp | NelsonGomesNeto/ProgramC | e743b1b869f58f7f3022d18bac00c5e0b078562e | [
"MIT"
] | 3 | 2018-12-18T13:39:42.000Z | 2021-06-23T18:05:18.000Z | Competitive Programming/RotaUFMG/Roteiro 2 (STL)/EleEstaImpedido.cpp | NelsonGomesNeto/ProgramC | e743b1b869f58f7f3022d18bac00c5e0b078562e | [
"MIT"
] | 1 | 2018-11-02T21:32:40.000Z | 2018-11-02T22:47:12.000Z | Competitive Programming/RotaUFMG/Roteiro 2 (STL)/EleEstaImpedido.cpp | NelsonGomesNeto/ProgramC | e743b1b869f58f7f3022d18bac00c5e0b078562e | [
"MIT"
] | 6 | 2018-10-27T14:07:52.000Z | 2019-11-14T13:49:29.000Z | #include <bits/stdc++.h>
using namespace std;
int main()
{
int a, d;
while (scanf("%d %d", &a, &d) && !(!a && !d))
{
int aa[a], dd[d];
for (int i = 0; i < a; i ++) scanf("%d", &aa[i]);
for (int i = 0; i < d; i ++) scanf("%d", &dd[i]);
sort(aa, aa+a); sort(dd, dd+d);
if (aa[0] < dd[1])
printf("Y\n");
else
printf("N\n");
}
} | 19.473684 | 53 | 0.421622 | NelsonGomesNeto |
2e66057a57e98c17598d363186ff6c09c768c0b3 | 3,326 | cpp | C++ | src/types/Categories.cpp | Mostah/parallel-pymcda | d5f5bb0de95dec90b88be9d00a3860e52eed4003 | [
"MIT"
] | 2 | 2020-12-12T22:48:57.000Z | 2021-02-24T09:37:40.000Z | src/types/Categories.cpp | Mostah/parallel-pymcda | d5f5bb0de95dec90b88be9d00a3860e52eed4003 | [
"MIT"
] | 5 | 2021-01-07T19:34:24.000Z | 2021-03-17T13:52:22.000Z | src/types/Categories.cpp | Mostah/parallel-pymcda | d5f5bb0de95dec90b88be9d00a3860e52eed4003 | [
"MIT"
] | 3 | 2020-12-12T22:49:56.000Z | 2021-09-08T05:26:38.000Z | #include "../../include/types/Categories.h"
#include "../../include/utils.h"
#include <iostream>
#include <ostream>
#include <string.h>
#include <vector>
Categories::Categories(int number_of_categories, std::string prefix) {
for (int i = 0; i < number_of_categories; i++) {
std::string id = prefix + std::to_string(i);
Category tmp_cat = Category(id, i);
categories_vector_.push_back(tmp_cat);
}
}
Categories::Categories(std::vector<std::string> vect_category_ids) {
for (int i = 0; i < vect_category_ids.size(); i++) {
Category tmp_cat = Category(vect_category_ids[i], i);
categories_vector_.push_back(tmp_cat);
}
}
Categories::Categories(const Categories &categories) {
for (int i = 0; i < categories.categories_vector_.size(); i++) {
Category tmp_cat = categories.categories_vector_[i];
categories_vector_.push_back(tmp_cat);
}
}
Category Categories::operator[](int index) { return categories_vector_[index]; }
Category Categories::operator[](int index) const {
return categories_vector_[index];
}
int Categories::getNumberCategories() { return categories_vector_.size(); }
Categories::~Categories() {
// https://stackoverflow.com/questions/993590/should-i-delete-vectorstring
std::vector<Category>().swap(categories_vector_);
}
std::vector<int> Categories::getRankCategories() {
std::vector<int> rank_categories;
for (int i = 0; i < categories_vector_.size(); i++) {
rank_categories.push_back(categories_vector_[i].rank_);
}
return rank_categories;
}
void Categories::setRankCategories(std::vector<int> &set_ranks) {
if (set_ranks.size() != set_ranks.size()) {
throw std::invalid_argument(
"RankCategories setter object is not the same size as Categories.");
}
for (int i = 0; i < set_ranks.size(); i++) {
categories_vector_[i].rank_ = set_ranks[i];
}
}
void Categories::setRankCategories() {
for (int i = 0; i < categories_vector_.size(); i++) {
categories_vector_[i].rank_ = i;
}
}
std::vector<std::string> Categories::getIdCategories() {
std::vector<std::string> categories_ids;
for (int i = 0; i < categories_vector_.size(); i++) {
categories_ids.push_back(categories_vector_[i].category_id_);
}
return categories_ids;
}
void Categories::setIdCategories(std::string prefix) {
for (int i = 0; i < categories_vector_.size(); i++) {
categories_vector_[i].category_id_ = prefix + std::to_string(i);
}
}
void Categories::setIdCategories(std::vector<std::string> &set_category_ids) {
if (set_category_ids.size() != categories_vector_.size()) {
throw std::invalid_argument(
"IdCategories setter object is not the same size as Categories.");
}
for (int i = 0; i < set_category_ids.size(); i++) {
categories_vector_[i].category_id_ = set_category_ids[i];
}
}
Category Categories::getCategoryOfRank(int rank) {
for (Category cat : categories_vector_) {
if (cat.rank_ == rank) {
return cat;
}
}
throw std::invalid_argument("Category not found.");
}
std::ostream &operator<<(std::ostream &out, const Categories &cats) {
out << "Categories(";
for (int i = 0; i < cats.categories_vector_.size(); i++) {
if (i == cats.categories_vector_.size() - 1) {
out << cats[i];
} else {
out << cats[i] << ", ";
}
}
out << ")";
return out;
}
| 29.696429 | 80 | 0.678894 | Mostah |