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 109 | 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 48.5k ⌀ | 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e92b3fc986d472e7af5280d52c4343cebbe41635 | 117 | cpp | C++ | 07-File-handling/binaryfile.cpp | increedBull7/C-and-DS-by-Bari | c7cb59673c11c3c65772132dadc3db3634fd7f10 | [
"MIT"
] | null | null | null | 07-File-handling/binaryfile.cpp | increedBull7/C-and-DS-by-Bari | c7cb59673c11c3c65772132dadc3db3634fd7f10 | [
"MIT"
] | null | null | null | 07-File-handling/binaryfile.cpp | increedBull7/C-and-DS-by-Bari | c7cb59673c11c3c65772132dadc3db3634fd7f10 | [
"MIT"
] | 1 | 2021-09-27T12:01:55.000Z | 2021-09-27T12:01:55.000Z | #include <iostream>
using namespace std;
int main(){
cout<<hex<<163;
//cout<<set<<"Hello";
return 0;
} | 11.7 | 25 | 0.581197 | increedBull7 |
e92d566697c739a751f4690038593309ecf36d3b | 8,732 | cpp | C++ | samples/Hello/third-party/fuzzylite/examples/takagi-sugeno/matlab/invkine2.cpp | okocsis/ios-cmake | ca61d83725bc5b1a755928f4592badbd9a8b37f4 | [
"BSD-3-Clause"
] | null | null | null | samples/Hello/third-party/fuzzylite/examples/takagi-sugeno/matlab/invkine2.cpp | okocsis/ios-cmake | ca61d83725bc5b1a755928f4592badbd9a8b37f4 | [
"BSD-3-Clause"
] | null | null | null | samples/Hello/third-party/fuzzylite/examples/takagi-sugeno/matlab/invkine2.cpp | okocsis/ios-cmake | ca61d83725bc5b1a755928f4592badbd9a8b37f4 | [
"BSD-3-Clause"
] | null | null | null | #include <fl/Headers.h>
int main(int argc, char** argv){
//Code automatically generated with fuzzylite 6.0.
using namespace fl;
Engine* engine = new Engine;
engine->setName("invkine2");
engine->setDescription("");
InputVariable* input1 = new InputVariable;
input1->setName("input1");
input1->setDescription("");
input1->setEnabled(true);
input1->setRange(-6.287, 17.000);
input1->setLockValueInRange(false);
input1->addTerm(new Bell("in1mf1", -5.763, 3.015, 1.851));
input1->addTerm(new Bell("in1mf2", -1.624, 3.130, 2.111));
input1->addTerm(new Bell("in1mf3", 3.552, 3.193, 2.104));
input1->addTerm(new Bell("in1mf4", 8.273, 2.907, 1.985));
input1->addTerm(new Bell("in1mf5", 13.232, 2.708, 2.056));
input1->addTerm(new Bell("in1mf6", 17.783, 1.635, 1.897));
engine->addInputVariable(input1);
InputVariable* input2 = new InputVariable;
input2->setName("input2");
input2->setDescription("");
input2->setEnabled(true);
input2->setRange(0.000, 16.972);
input2->setLockValueInRange(false);
input2->addTerm(new Bell("in2mf1", 0.005, 1.877, 1.995));
input2->addTerm(new Bell("in2mf2", 3.312, 2.017, 1.829));
input2->addTerm(new Bell("in2mf3", 6.568, 2.261, 1.793));
input2->addTerm(new Bell("in2mf4", 10.111, 2.741, 1.978));
input2->addTerm(new Bell("in2mf5", 14.952, 2.045, 1.783));
input2->addTerm(new Bell("in2mf6", 17.910, 0.824, 1.734));
engine->addInputVariable(input2);
OutputVariable* output = new OutputVariable;
output->setName("output");
output->setDescription("");
output->setEnabled(true);
output->setRange(0.000, 3.100);
output->setLockValueInRange(false);
output->setAggregation(fl::null);
output->setDefuzzifier(new WeightedAverage("TakagiSugeno"));
output->setDefaultValue(fl::nan);
output->setLockPreviousValue(false);
output->addTerm(Linear::create("out1mf1", engine, -0.048, 1.456, 2.222));
output->addTerm(Linear::create("out1mf2", engine, -0.218, -0.305, 2.042));
output->addTerm(Linear::create("out1mf3", engine, 0.026, -0.141, 3.067));
output->addTerm(Linear::create("out1mf4", engine, 0.052, -0.150, 3.419));
output->addTerm(Linear::create("out1mf5", engine, 0.113, -0.189, 4.339));
output->addTerm(Linear::create("out1mf6", engine, 2.543, 0.361, -2.738));
output->addTerm(Linear::create("out1mf7", engine, 2.517, -6.809, 23.353));
output->addTerm(Linear::create("out1mf8", engine, -0.208, -0.394, 4.472));
output->addTerm(Linear::create("out1mf9", engine, -0.046, -0.300, 4.452));
output->addTerm(Linear::create("out1mf10", engine, -0.006, -0.217, 4.195));
output->addTerm(Linear::create("out1mf11", engine, 0.089, -0.254, 4.992));
output->addTerm(Linear::create("out1mf12", engine, -0.033, 0.103, -2.012));
output->addTerm(Linear::create("out1mf13", engine, 1.355, 1.228, -5.678));
output->addTerm(Linear::create("out1mf14", engine, -0.245, -0.124, 3.753));
output->addTerm(Linear::create("out1mf15", engine, -0.099, -0.111, 3.304));
output->addTerm(Linear::create("out1mf16", engine, -0.052, -0.163, 3.560));
output->addTerm(Linear::create("out1mf17", engine, 0.099, -0.260, 4.662));
output->addTerm(Linear::create("out1mf18", engine, 0.082, -1.849, 31.104));
output->addTerm(Linear::create("out1mf19", engine, 2.180, -2.963, -0.061));
output->addTerm(Linear::create("out1mf20", engine, -0.982, 0.510, 5.657));
output->addTerm(Linear::create("out1mf21", engine, -0.087, -0.179, 3.744));
output->addTerm(Linear::create("out1mf22", engine, -0.124, -0.161, 4.094));
output->addTerm(Linear::create("out1mf23", engine, 0.383, 0.007, -1.559));
output->addTerm(Linear::create("out1mf24", engine, -8.415, 2.083, 5.177));
output->addTerm(Linear::create("out1mf25", engine, 1.721, -15.079, -0.687));
output->addTerm(Linear::create("out1mf26", engine, -1.043, -0.786, 20.510));
output->addTerm(Linear::create("out1mf27", engine, -0.249, -0.396, 6.995));
output->addTerm(Linear::create("out1mf28", engine, -0.076, -0.245, 4.416));
output->addTerm(Linear::create("out1mf29", engine, 0.765, -1.488, 17.384));
output->addTerm(Linear::create("out1mf30", engine, -21.210, -43.022, -2.522));
output->addTerm(Linear::create("out1mf31", engine, -0.661, 3.523, 6.215));
output->addTerm(Linear::create("out1mf32", engine, -1.998, 1.582, 33.256));
output->addTerm(Linear::create("out1mf33", engine, -2.068, 5.673, 6.520));
output->addTerm(Linear::create("out1mf34", engine, -5.044, 7.093, 3.516));
output->addTerm(Linear::create("out1mf35", engine, -46.049, -35.021, -2.926));
output->addTerm(Linear::create("out1mf36", engine, -0.448, -0.770, -0.041));
engine->addOutputVariable(output);
RuleBlock* ruleBlock = new RuleBlock;
ruleBlock->setName("");
ruleBlock->setDescription("");
ruleBlock->setEnabled(true);
ruleBlock->setConjunction(new AlgebraicProduct);
ruleBlock->setDisjunction(fl::null);
ruleBlock->setImplication(fl::null);
ruleBlock->setActivation(new General);
ruleBlock->addRule(Rule::parse("if input1 is in1mf1 and input2 is in2mf1 then output is out1mf1", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf1 and input2 is in2mf2 then output is out1mf2", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf1 and input2 is in2mf3 then output is out1mf3", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf1 and input2 is in2mf4 then output is out1mf4", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf1 and input2 is in2mf5 then output is out1mf5", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf1 and input2 is in2mf6 then output is out1mf6", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf2 and input2 is in2mf1 then output is out1mf7", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf2 and input2 is in2mf2 then output is out1mf8", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf2 and input2 is in2mf3 then output is out1mf9", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf2 and input2 is in2mf4 then output is out1mf10", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf2 and input2 is in2mf5 then output is out1mf11", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf2 and input2 is in2mf6 then output is out1mf12", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf3 and input2 is in2mf1 then output is out1mf13", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf3 and input2 is in2mf2 then output is out1mf14", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf3 and input2 is in2mf3 then output is out1mf15", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf3 and input2 is in2mf4 then output is out1mf16", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf3 and input2 is in2mf5 then output is out1mf17", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf3 and input2 is in2mf6 then output is out1mf18", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf4 and input2 is in2mf1 then output is out1mf19", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf4 and input2 is in2mf2 then output is out1mf20", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf4 and input2 is in2mf3 then output is out1mf21", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf4 and input2 is in2mf4 then output is out1mf22", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf4 and input2 is in2mf5 then output is out1mf23", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf4 and input2 is in2mf6 then output is out1mf24", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf5 and input2 is in2mf1 then output is out1mf25", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf5 and input2 is in2mf2 then output is out1mf26", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf5 and input2 is in2mf3 then output is out1mf27", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf5 and input2 is in2mf4 then output is out1mf28", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf5 and input2 is in2mf5 then output is out1mf29", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf5 and input2 is in2mf6 then output is out1mf30", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf6 and input2 is in2mf1 then output is out1mf31", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf6 and input2 is in2mf2 then output is out1mf32", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf6 and input2 is in2mf3 then output is out1mf33", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf6 and input2 is in2mf4 then output is out1mf34", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf6 and input2 is in2mf5 then output is out1mf35", engine));
ruleBlock->addRule(Rule::parse("if input1 is in1mf6 and input2 is in2mf6 then output is out1mf36", engine));
engine->addRuleBlock(ruleBlock);
}
| 64.205882 | 108 | 0.730875 | okocsis |
e92e0ea2447db7c1581651f5ee244097062f01df | 6,558 | hpp | C++ | QuantExt/qle/termstructures/yoyinflationcurveobservermoving.hpp | nvolfango/Engine | a5ee0fc09d5a50ab36e50d55893b6e484d6e7004 | [
"BSD-3-Clause"
] | 1 | 2021-03-30T17:24:17.000Z | 2021-03-30T17:24:17.000Z | QuantExt/qle/termstructures/yoyinflationcurveobservermoving.hpp | zhangjiayin/Engine | a5ee0fc09d5a50ab36e50d55893b6e484d6e7004 | [
"BSD-3-Clause"
] | null | null | null | QuantExt/qle/termstructures/yoyinflationcurveobservermoving.hpp | zhangjiayin/Engine | a5ee0fc09d5a50ab36e50d55893b6e484d6e7004 | [
"BSD-3-Clause"
] | 1 | 2022-02-07T02:04:10.000Z | 2022-02-07T02:04:10.000Z | /*
Copyright (C) 2016 Quaternion Risk Management Ltd
All rights reserved.
This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org
ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License. You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>
This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file qle/termstructures/yoyinflationcurveobservermoving.hpp
\brief Observable inflation term structure with floating reference date
based on the interpolation of zero rate quotes.
\ingroup termstructures
*/
#ifndef quantext_yoy_inflation_curve_observer_moving_hpp
#define quantext_yoy_inflation_curve_observer_moving_hpp
#include <ql/math/comparison.hpp>
#include <ql/math/interpolations/linearinterpolation.hpp>
#include <ql/patterns/lazyobject.hpp>
#include <ql/termstructures/inflationtermstructure.hpp>
#include <ql/termstructures/interpolatedcurve.hpp>
namespace QuantExt {
using namespace QuantLib;
//! Inflation term structure based on the interpolation of zero rates.
/*! \ingroup inflationtermstructures */
template <class Interpolator>
class YoYInflationCurveObserverMoving : public YoYInflationTermStructure,
protected InterpolatedCurve<Interpolator>,
public LazyObject {
public:
YoYInflationCurveObserverMoving(
Natural settlementDays, const Calendar& calendar, const DayCounter& dayCounter, const Period& lag,
Frequency frequency, bool indexIsInterpolated, const Handle<YieldTermStructure>& yTS,
const std::vector<Time>& times, const std::vector<Handle<Quote> >& rates,
const boost::shared_ptr<Seasonality>& seasonality = boost::shared_ptr<Seasonality>(),
const Interpolator& interpolator = Interpolator());
//! \name InflationTermStructure interface
//@{
Date baseDate() const;
Time maxTime() const;
Date maxDate() const;
//@}
//! \name Inspectors
//@{
const std::vector<Time>& times() const;
const std::vector<Real>& data() const;
const std::vector<Rate>& rates() const;
// std::vector<std::pair<Date, Rate> > nodes() const;
const std::vector<Handle<Quote> >& quotes() const { return quotes_; };
//@}
//! \name Observer interface
//@{
void update();
//@}
private:
//! \name LazyObject interface
//@{
void performCalculations() const;
//@}
protected:
//! \name YoYInflationTermStructure Interface
//@{
Rate yoyRateImpl(Time t) const;
//@}
std::vector<Handle<Quote> > quotes_;
mutable Date baseDate_;
};
// template definitions
template <class Interpolator>
YoYInflationCurveObserverMoving<Interpolator>::YoYInflationCurveObserverMoving(
Natural settlementDays, const Calendar& calendar, const DayCounter& dayCounter, const Period& lag,
Frequency frequency, bool indexIsInterpolated, const Handle<YieldTermStructure>& yTS,
const std::vector<Time>& times, const std::vector<Handle<Quote> >& rates,
const boost::shared_ptr<Seasonality>& seasonality, const Interpolator& interpolator)
: YoYInflationTermStructure(settlementDays, calendar, dayCounter, rates[0]->value(), lag, frequency,
indexIsInterpolated, yTS, seasonality),
InterpolatedCurve<Interpolator>(std::vector<Time>(), std::vector<Real>(), interpolator), quotes_(rates) {
QL_REQUIRE(times.size() > 1, "too few times: " << times.size());
this->times_.resize(times.size());
this->times_[0] = times[0];
for (Size i = 1; i < times.size(); i++) {
QL_REQUIRE(times[i] > times[i - 1], "times not sorted");
this->times_[i] = times[i];
}
QL_REQUIRE(this->quotes_.size() == this->times_.size(),
"quotes/times count mismatch: " << this->quotes_.size() << " vs " << this->times_.size());
// initalise data vector, values are copied from quotes in performCalculations()
this->data_.resize(this->times_.size());
for (Size i = 0; i < this->times_.size(); i++)
this->data_[0] = 0.0;
this->interpolation_ =
this->interpolator_.interpolate(this->times_.begin(), this->times_.end(), this->data_.begin());
this->interpolation_.update();
// register with each of the quotes
for (Size i = 0; i < this->quotes_.size(); i++)
registerWith(this->quotes_[i]);
}
template <class T> Date YoYInflationCurveObserverMoving<T>::baseDate() const {
// if indexIsInterpolated we fixed the dates in the constructor
calculate();
return baseDate_;
}
template <class T> Time YoYInflationCurveObserverMoving<T>::maxTime() const { return this->times_.back(); }
template <class T> Date YoYInflationCurveObserverMoving<T>::maxDate() const { return this->maxDate_; }
template <class T> inline Rate YoYInflationCurveObserverMoving<T>::yoyRateImpl(Time t) const {
calculate();
return this->interpolation_(t, true);
}
template <class T> inline const std::vector<Time>& YoYInflationCurveObserverMoving<T>::times() const {
return this->times_;
}
template <class T> inline const std::vector<Rate>& YoYInflationCurveObserverMoving<T>::rates() const {
calculate();
return this->data_;
}
template <class T> inline const std::vector<Real>& YoYInflationCurveObserverMoving<T>::data() const {
calculate();
return this->data_;
}
template <class T> inline void YoYInflationCurveObserverMoving<T>::update() {
LazyObject::update();
YoYInflationTermStructure::update();
}
template <class T> inline void YoYInflationCurveObserverMoving<T>::performCalculations() const {
Date d = Settings::instance().evaluationDate();
Date d0 = d - this->observationLag();
if (!indexIsInterpolated_) {
baseDate_ = inflationPeriod(d0, this->frequency_).first;
} else {
baseDate_ = d0;
}
for (Size i = 0; i < this->times_.size(); ++i)
this->data_[i] = quotes_[i]->value();
this->interpolation_ =
this->interpolator_.interpolate(this->times_.begin(), this->times_.end(), this->data_.begin());
this->interpolation_.update();
}
} // namespace QuantExt
#endif
| 37.261364 | 111 | 0.695029 | nvolfango |
e92e1b4938c02bd44ffd17b29b06289f768dc1c5 | 1,114 | cpp | C++ | lualibs/bitlib.cpp | canuc/meow-engine | 25f5396136d90691e4a4451f382a45da9fdcebc0 | [
"BSD-3-Clause"
] | 1 | 2020-01-24T01:14:04.000Z | 2020-01-24T01:14:04.000Z | lualibs/bitlib.cpp | canuc/meow-engine | 25f5396136d90691e4a4451f382a45da9fdcebc0 | [
"BSD-3-Clause"
] | null | null | null | lualibs/bitlib.cpp | canuc/meow-engine | 25f5396136d90691e4a4451f382a45da9fdcebc0 | [
"BSD-3-Clause"
] | 1 | 2020-06-05T07:00:16.000Z | 2020-06-05T07:00:16.000Z | #include "lualibs/bitlib.h"
static engine * eventEngine;
static int or_op(lua_State *L) {
int v = 0;
lua_pushnil(L);
while(lua_next(L, -2)) {
v |= ((int)lua_tointeger(L, -1));
lua_pop(L, 1);
}
lua_pushinteger(L,v);
return 1;
}
static int and_op(lua_State *L) {
int v = 0;
lua_pushnil(L);
while(lua_next(L, -2)) {
v &= ((int)lua_tointeger(L, -1));
lua_pop(L, 1);
}
lua_pushinteger(L,v);
return 1;
}
static const luaL_Reg bitlib_functions[] = {
{"or_op",or_op},
{"and_op",and_op},
{NULL,NULL}
};
void load_bit_lib(lua_State * L,struct engine * engine) {
const luaL_Reg *lib;
/* add open functions from 'preloadedlibs' into 'package.preload' table */
eventEngine = engine;
for (lib = bitlib_functions; lib->func; lib++) {
lua_register(L,lib->name, lib->func);
}
// const lua_LConst *constants;
// for (constants = bitlib_functions; constants->name; constants++) {
// lua_pushinteger(L,constants->lua_int);
// lua_setglobal(L,constants->name);
// }
}
| 21.018868 | 78 | 0.584381 | canuc |
e933bc96a3135b31cd39158542f3d9f2c84b8d3f | 557 | cpp | C++ | 450Question(DayWise)/57.cpp | jnvshubham7/CPP_Programming | a17c4a42209556495302ca305b7c3026df064041 | [
"Apache-2.0"
] | 1 | 2021-12-22T12:37:36.000Z | 2021-12-22T12:37:36.000Z | 450Question(DayWise)/57.cpp | jnvshubham7/CPP_Programming | a17c4a42209556495302ca305b7c3026df064041 | [
"Apache-2.0"
] | null | null | null | 450Question(DayWise)/57.cpp | jnvshubham7/CPP_Programming | a17c4a42209556495302ca305b7c3026df064041 | [
"Apache-2.0"
] | null | null | null |
class Solution {
public:
int maximumSwap(int num) {
string n=to_string(num);
//keep in a map the last accurance of each digit
unodered_map<int,int> last;
for(int i=0;i<n.size();i++)
last[n[i]-'0']=i;
for(int i=0;i<n.size();i++)
{
for(int j=9;j>n[i]-'0';j--)
{
if(last[j]>i)
{
swap(n[i],n[last[j]]);
return stoi(n);
}
}
}
return stoi(n);
}
};
| 21.423077 | 56 | 0.37702 | jnvshubham7 |
e93a5606a867254a44102443862a1b3c43fc6b0f | 938 | cpp | C++ | RegexTester/src/main.cpp | GamesTrap/LearnCPP | 710b24876f61e1033aaa0502fc4508250de717c3 | [
"MIT"
] | 7 | 2020-06-14T00:33:29.000Z | 2022-01-08T21:40:06.000Z | RegexTester/src/main.cpp | GamesTrap/LearnCPP | 710b24876f61e1033aaa0502fc4508250de717c3 | [
"MIT"
] | null | null | null | RegexTester/src/main.cpp | GamesTrap/LearnCPP | 710b24876f61e1033aaa0502fc4508250de717c3 | [
"MIT"
] | 1 | 2021-04-04T14:14:15.000Z | 2021-04-04T14:14:15.000Z | #include <iostream>
#include "RegexTester.h"
void TestCases()
{
const std::string testCases[][2] =
{
{"^\\D+([0-9]+) \\1", "Summer 2018 2018"},
{"[a-c]+", "zcbaaxcadey"},
{"\\t", "contains Tab"},
{"[a-c]*", "z"}, //Greedy
{"[^aeiou]+", "hello"},
{"/\\*.*\\*/", "xyz /* hello */ abc */ 123"}, //Greedy
{"/\\*.*?\\*/", "xyz /* hello */ abc */ 123"} //Not greedy
};
for(auto testCase : testCases)
{
RegexTester rt(testCase[0], testCase[1]);
rt.Run();
std::cout << '\n';
}
}
int main(int argc, char* argv[])
{
if(3 != argc)
{
TestCases();
std::cout << R"(Usage: RegexTester.exe "regex" "testString")" << '\n' << "otherwise built-in test cases are output." << '\n';
}
else
{
try
{
RegexTester rt(argv[1], argv[2]);
rt.Run();
} catch(std::regex_error& re)
{
std::cerr << "Error: " << re.what() << '\n';
}
}
std::cout << "Press Enter to continue . . . ";
std::cin.get();
return 0;
} | 19.541667 | 127 | 0.509595 | GamesTrap |
e93c6e1ff9a22a2c0f1e875f3166937c54e79cf6 | 26 | cpp | C++ | ChessGUI/GameSetting.cpp | weininglee/OOP03-Chess | a2cbafe14f04d31012d06d59d23504e7c3382af8 | [
"CC0-1.0"
] | null | null | null | ChessGUI/GameSetting.cpp | weininglee/OOP03-Chess | a2cbafe14f04d31012d06d59d23504e7c3382af8 | [
"CC0-1.0"
] | null | null | null | ChessGUI/GameSetting.cpp | weininglee/OOP03-Chess | a2cbafe14f04d31012d06d59d23504e7c3382af8 | [
"CC0-1.0"
] | null | null | null | #include "GameSetting.h"
| 13 | 25 | 0.730769 | weininglee |
e93e5f0c7c39aafc049959dcd9e346bd43a4bf62 | 2,745 | cpp | C++ | JanuaEngine/tgcviewer-cpp/Examples/ExampleOCEngine1/ExampleCreateRawSceneXML.cpp | gigc/Janua | cbcc8ad0e9501e1faef5b37a964769970aa3d236 | [
"MIT",
"Unlicense"
] | 98 | 2015-01-13T16:23:23.000Z | 2022-02-14T21:51:07.000Z | JanuaEngine/tgcviewer-cpp/Examples/ExampleOCEngine1/ExampleCreateRawSceneXML.cpp | gigc/Janua | cbcc8ad0e9501e1faef5b37a964769970aa3d236 | [
"MIT",
"Unlicense"
] | 1 | 2016-06-30T22:07:54.000Z | 2016-06-30T22:07:54.000Z | JanuaEngine/tgcviewer-cpp/Examples/ExampleOCEngine1/ExampleCreateRawSceneXML.cpp | gigc/Janua | cbcc8ad0e9501e1faef5b37a964769970aa3d236 | [
"MIT",
"Unlicense"
] | 13 | 2015-08-26T11:19:08.000Z | 2021-07-12T03:41:50.000Z | /////////////////////////////////////////////////////////////////////////////////
// TgcViewer-cpp
//
// Author: Matias Leone
//
/////////////////////////////////////////////////////////////////////////////////
#include "Examples/ExampleOCEngine1/ExampleCreateRawSceneXML.h"
using namespace Examples;
string ExampleCreateRawSceneXML::getCategory()
{
return "Occlusion";
}
string ExampleCreateRawSceneXML::getName()
{
return "ExampleCreateRawSceneXML";
}
string ExampleCreateRawSceneXML::getDescription()
{
return "ExampleCreateRawSceneXML";
}
void ExampleCreateRawSceneXML::init()
{
//Load 3D scene data (only parser)
string filePath = GuiController::Instance->examplesMediaPath + "TgcModels\\NormalMapRoom2\\NormalMapRoom2-TgcScene.xml";
string outputPath = GuiController::Instance->examplesMediaPath + "TgcModels\\NormalMapRoom2\\raw-scene.xml";
string mediaPath = filePath.substr(0, filePath.find_last_of('\\') + 1);
TgcSceneParser parser;
TgcSceneData* sceneData = parser.parseSceneFromFile(filePath);
//Create XML file
xml_document doc;
xml_node root = doc.append_child("janua_scene");
xml_node meshesNode = root.append_child("meshes");
meshesNode.append_attribute("count").set_value(sceneData->meshCount);
//Add meshes to XML
for(int i = 0; i < sceneData->meshCount; i++)
{
TgcMeshData* meshData = sceneData->meshesData[i];
int vertexRawDataCount = meshData->coordinatesIndicesCount * 3;
int triCount = meshData->coordinatesIndicesCount / 3;
float* rawVertexData = new float[vertexRawDataCount];
//vertex array
int idx = 0;
for(int j = 0; j < meshData->coordinatesIndicesCount; j++)
{
int vIdx = meshData->coordinatesIndices[j];
rawVertexData[idx++] = meshData->verticesCoordinates[vIdx * 3];
rawVertexData[idx++] = meshData->verticesCoordinates[vIdx * 3 + 1];
rawVertexData[idx++] = meshData->verticesCoordinates[vIdx * 3 + 2];
}
//vertex string array
stringstream vertexStream;
for(int j = 0; j < vertexRawDataCount; j++)
{
vertexStream << rawVertexData[j] << " ";
}
//Mesh node
xml_node meshNode = meshesNode.append_child("m");
meshNode.append_attribute("id").set_value(i);
meshNode.append_attribute("triCount").set_value(triCount);
meshNode.append_child(node_pcdata).set_value(vertexStream.str().c_str());
//Type
if(TgcParserUtils::toUpper(meshData->layerName) == "OCCLUDER")
{
meshNode.append_attribute("type").set_value("OCCLUDER");
}
else
{
meshNode.append_attribute("type").set_value("OCCLUDEE");
}
delete[] rawVertexData;
}
delete sceneData;
//Guardar XML
doc.save_file(outputPath.c_str());
}
void ExampleCreateRawSceneXML::render(float elapsedTime)
{
}
void ExampleCreateRawSceneXML::close()
{
}
| 24.078947 | 121 | 0.686339 | gigc |
e9420b8861db4897af50ff36678bfb5addac951f | 8,860 | cpp | C++ | tests/auto/qamqpexchange/tst_qamqpexchange.cpp | assignonward/aosuite | 243771d237970fe1175aaabc7d8d22f691076b6b | [
"MIT"
] | null | null | null | tests/auto/qamqpexchange/tst_qamqpexchange.cpp | assignonward/aosuite | 243771d237970fe1175aaabc7d8d22f691076b6b | [
"MIT"
] | null | null | null | tests/auto/qamqpexchange/tst_qamqpexchange.cpp | assignonward/aosuite | 243771d237970fe1175aaabc7d8d22f691076b6b | [
"MIT"
] | 1 | 2018-08-11T20:39:07.000Z | 2018-08-11T20:39:07.000Z | #include <QtTest/QtTest>
#include "signalspy.h"
#include "qamqptestcase.h"
#include "qamqpclient.h"
#include "qamqpexchange.h"
#include "qamqpqueue.h"
class tst_QAMQPExchange : public TestCase
{
Q_OBJECT
private Q_SLOTS:
void init();
void cleanup();
void standardTypes_data();
void standardTypes();
void invalidStandardDeclaration_data();
void invalidStandardDeclaration();
void invalidDeclaration();
void invalidRedeclaration();
void removeIfUnused();
void invalidMandatoryRouting();
void invalidImmediateRouting();
void confirmsSupport();
void confirmDontLoseMessages();
void passiveDeclareNotFound();
void cleanupOnDeletion();
void testQueuedPublish();
private:
QScopedPointer<QAmqpClient> client;
};
void tst_QAMQPExchange::init()
{
client.reset(new QAmqpClient);
client->connectToHost();
QVERIFY(waitForSignal(client.data(), SIGNAL(connected())));
}
void tst_QAMQPExchange::cleanup()
{
if (client->isConnected()) {
client->disconnectFromHost();
QVERIFY(waitForSignal(client.data(), SIGNAL(disconnected())));
}
}
void tst_QAMQPExchange::standardTypes_data()
{
QTest::addColumn<QAmqpExchange::ExchangeType>("type");
QTest::addColumn<bool>("delayedDeclaration");
QTest::newRow("direct") << QAmqpExchange::Direct << false;
QTest::newRow("direct-delayed") << QAmqpExchange::Direct << true;
QTest::newRow("fanout") << QAmqpExchange::FanOut << false;
QTest::newRow("fanout-delayed") << QAmqpExchange::FanOut << true;
QTest::newRow("topic") << QAmqpExchange::Topic << false;
QTest::newRow("topic-delayed") << QAmqpExchange::Topic << true;
QTest::newRow("headers") << QAmqpExchange::Headers << false;
QTest::newRow("headers-delayed") << QAmqpExchange::Headers << true;
}
void tst_QAMQPExchange::standardTypes()
{
QFETCH(QAmqpExchange::ExchangeType, type);
QFETCH(bool, delayedDeclaration);
QAmqpExchange *exchange = client->createExchange("test");
if (!delayedDeclaration)
QVERIFY(waitForSignal(exchange, SIGNAL(opened())));
exchange->declare(type);
QVERIFY(waitForSignal(exchange, SIGNAL(declared())));
exchange->remove(QAmqpExchange::roForce);
QVERIFY(waitForSignal(exchange, SIGNAL(removed())));
}
void tst_QAMQPExchange::invalidStandardDeclaration_data()
{
QTest::addColumn<QString>("exchangeName");
QTest::addColumn<QAmqpExchange::ExchangeType>("type");
QTest::addColumn<QAMQP::Error>("error");
QTest::newRow("amq.direct") << "amq.direct" << QAmqpExchange::Direct << QAMQP::PreconditionFailedError;
QTest::newRow("amq.fanout") << "amq.fanout" << QAmqpExchange::FanOut << QAMQP::PreconditionFailedError;
QTest::newRow("amq.headers") << "amq.headers" << QAmqpExchange::Headers << QAMQP::PreconditionFailedError;
QTest::newRow("amq.match") << "amq.match" << QAmqpExchange::Headers << QAMQP::PreconditionFailedError;
QTest::newRow("amq.topic") << "amq.topic" << QAmqpExchange::Topic << QAMQP::PreconditionFailedError;
QTest::newRow("amq.reserved") << "amq.reserved" << QAmqpExchange::Direct << QAMQP::AccessRefusedError;
}
void tst_QAMQPExchange::invalidStandardDeclaration()
{
QFETCH(QString, exchangeName);
QFETCH(QAmqpExchange::ExchangeType, type);
QFETCH(QAMQP::Error, error);
QAmqpExchange *exchange = client->createExchange(exchangeName);
exchange->declare(type);
QVERIFY(waitForSignal(exchange, SIGNAL(error(QAMQP::Error))));
QCOMPARE(exchange->error(), error);
}
void tst_QAMQPExchange::invalidDeclaration()
{
QAmqpExchange *exchange = client->createExchange("test-invalid-declaration");
exchange->declare("invalidExchangeType");
QVERIFY(waitForSignal(client.data(), SIGNAL(error(QAMQP::Error))));
QCOMPARE(client->error(), QAMQP::CommandInvalidError);
}
void tst_QAMQPExchange::invalidRedeclaration()
{
QAmqpExchange *exchange = client->createExchange("test-invalid-redeclaration");
exchange->declare(QAmqpExchange::Direct);
QVERIFY(waitForSignal(exchange, SIGNAL(declared())));
QAmqpExchange *redeclared = client->createExchange("test-invalid-redeclaration");
redeclared->declare(QAmqpExchange::FanOut);
QVERIFY(waitForSignal(redeclared, SIGNAL(error(QAMQP::Error))));
// this is per spec:
// QCOMPARE(redeclared->error(), QAMQP::NotAllowedError);
// this is for rabbitmq:
QCOMPARE(redeclared->error(), QAMQP::PreconditionFailedError);
// Server has probably closed the channel on us, if so, re-open it.
if (!exchange->isOpen()) {
exchange->reopen();
QVERIFY(waitForSignal(exchange, SIGNAL(opened())));
}
// cleanup
exchange->remove();
QVERIFY(waitForSignal(exchange, SIGNAL(removed())));
}
void tst_QAMQPExchange::removeIfUnused()
{
QAmqpExchange *exchange = client->createExchange("test-if-unused-exchange");
exchange->declare(QAmqpExchange::Direct, QAmqpExchange::AutoDelete);
QVERIFY(waitForSignal(exchange, SIGNAL(declared())));
QAmqpQueue *queue = client->createQueue("test-if-unused-queue");
queue->declare();
QVERIFY(waitForSignal(queue, SIGNAL(declared())));
queue->bind("test-if-unused-exchange", "testRoutingKey");
QVERIFY(waitForSignal(queue, SIGNAL(bound())));
exchange->remove(QAmqpExchange::roIfUnused);
QVERIFY(waitForSignal(exchange, SIGNAL(error(QAMQP::Error))));
QCOMPARE(exchange->error(), QAMQP::PreconditionFailedError);
QVERIFY(!exchange->errorString().isEmpty());
// cleanup
queue->remove(QAmqpQueue::roForce);
QVERIFY(waitForSignal(queue, SIGNAL(removed())));
}
void tst_QAMQPExchange::invalidMandatoryRouting()
{
QAmqpExchange *defaultExchange = client->createExchange();
defaultExchange->publish("some message", "unroutable-key", QAmqpMessage::PropertyHash(), QAmqpExchange::poMandatory);
QVERIFY(waitForSignal(defaultExchange, SIGNAL(error(QAMQP::Error))));
QCOMPARE(defaultExchange->error(), QAMQP::NoRouteError);
}
void tst_QAMQPExchange::invalidImmediateRouting()
{
QAmqpExchange *defaultExchange = client->createExchange();
defaultExchange->publish("some message", "unroutable-key", QAmqpMessage::PropertyHash(), QAmqpExchange::poImmediate);
QVERIFY(waitForSignal(client.data(), SIGNAL(error(QAMQP::Error))));
QCOMPARE(client->error(), QAMQP::NotImplementedError);
}
void tst_QAMQPExchange::confirmsSupport()
{
QAmqpExchange *exchange = client->createExchange("confirm-test");
exchange->enableConfirms();
QVERIFY(waitForSignal(exchange, SIGNAL(confirmsEnabled())));
}
void tst_QAMQPExchange::confirmDontLoseMessages()
{
QAmqpExchange *defaultExchange = client->createExchange();
defaultExchange->enableConfirms();
QVERIFY(waitForSignal(defaultExchange, SIGNAL(confirmsEnabled())));
QAmqpMessage::PropertyHash properties;
properties[QAmqpMessage::DeliveryMode] = "2"; // make message persistent
for (int i = 0; i < 10000; ++i)
defaultExchange->publish("noop", "confirms-test", properties);
QVERIFY(defaultExchange->waitForConfirms());
}
void tst_QAMQPExchange::passiveDeclareNotFound()
{
QAmqpExchange *nonExistentExchange = client->createExchange("this-does-not-exist");
nonExistentExchange->declare(QAmqpExchange::Direct, QAmqpExchange::Passive);
QVERIFY(waitForSignal(nonExistentExchange, SIGNAL(error(QAMQP::Error))));
QCOMPARE(nonExistentExchange->error(), QAMQP::NotFoundError);
}
void tst_QAMQPExchange::cleanupOnDeletion()
{
// create, declare, and close the wrong way
QAmqpExchange *exchange = client->createExchange("test-deletion");
exchange->declare();
QVERIFY(waitForSignal(exchange, SIGNAL(declared())));
exchange->close();
exchange->deleteLater();
QVERIFY(waitForSignal(exchange, SIGNAL(destroyed())));
// now create, declare, and close the right way
exchange = client->createExchange("test-deletion");
exchange->declare();
QVERIFY(waitForSignal(exchange, SIGNAL(declared())));
exchange->close();
QVERIFY(waitForSignal(exchange, SIGNAL(closed())));
}
void tst_QAMQPExchange::testQueuedPublish()
{
QAmqpExchange *defaultExchange = client->createExchange();
defaultExchange->enableConfirms();
QVERIFY(waitForSignal(defaultExchange, SIGNAL(confirmsEnabled())));
QAmqpMessage::PropertyHash properties;
properties[QAmqpMessage::DeliveryMode] = "2"; // make message persistent
for (int i = 0; i < 10000; ++i) {
QMetaObject::invokeMethod(defaultExchange, "publish", Qt::QueuedConnection,
Q_ARG(QString, "noop"), Q_ARG(QString, "confirms-test"),
Q_ARG(QAmqpMessage::PropertyHash, properties));
}
QVERIFY(defaultExchange->waitForConfirms());
}
QTEST_MAIN(tst_QAMQPExchange)
#include "tst_qamqpexchange.moc"
| 35.870445 | 121 | 0.711851 | assignonward |
e9422e0a2dfa363966062cba30201dcf76116647 | 519 | cpp | C++ | CODE_S2_Tues_Thurs/CODE_S2_Tues_Thurs/cMeshObject.cpp | Freethetan/INFO3111-S21 | b0526d641c5e744c38e6a48d1b66a47f0d8dd592 | [
"MIT"
] | null | null | null | CODE_S2_Tues_Thurs/CODE_S2_Tues_Thurs/cMeshObject.cpp | Freethetan/INFO3111-S21 | b0526d641c5e744c38e6a48d1b66a47f0d8dd592 | [
"MIT"
] | null | null | null | CODE_S2_Tues_Thurs/CODE_S2_Tues_Thurs/cMeshObject.cpp | Freethetan/INFO3111-S21 | b0526d641c5e744c38e6a48d1b66a47f0d8dd592 | [
"MIT"
] | null | null | null | #include "cMeshObject.h"
cMeshObject::cMeshObject()
{
this->meshName = "";
this->position = glm::vec3(0.0f, 0.0f, 0.0f);
this->wholeObjectColour = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f); // 0,0,0,1 (black)
this->orientation = glm::vec3(0.0f, 0.0f, 0.0f); // Euler angles (x, y, and z)
this->scale = 1.0f; // 1.0f
this->isWireframe = false; // false
this->wholeObjectColour = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f); // bright white
this->bUseVertexColours = true; // If true, then use the file colours
} | 25.95 | 80 | 0.618497 | Freethetan |
e9438b487334094863815802e95838749bf54915 | 2,770 | hpp | C++ | libcaf_core/caf/deduce_mpi.hpp | seewpx/actor-framework | 65ecf35317b81d7a211848d59e734f43483fe410 | [
"BSD-3-Clause"
] | null | null | null | libcaf_core/caf/deduce_mpi.hpp | seewpx/actor-framework | 65ecf35317b81d7a211848d59e734f43483fe410 | [
"BSD-3-Clause"
] | null | null | null | libcaf_core/caf/deduce_mpi.hpp | seewpx/actor-framework | 65ecf35317b81d7a211848d59e734f43483fe410 | [
"BSD-3-Clause"
] | null | null | null | // This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#pragma once
#include <type_traits>
#include "caf/detail/implicit_conversions.hpp"
#include "caf/expected.hpp"
#include "caf/fwd.hpp"
namespace caf::detail {
// dmi = deduce_mpi_implementation
template <class T>
struct dmi;
// case #1: function returning a single value
template <class Out, class... In>
struct dmi<Out(In...)> {
using type = result<implicit_conversions_t<Out>>(std::decay_t<In>...);
};
// case #2: function returning a result<...>
template <class... Out, class... In>
struct dmi<result<Out...>(In...)> {
using type = result<Out...>(std::decay_t<In>...);
};
// case #3: function returning a delegated<...>
template <class... Out, class... In>
struct dmi<delegated<Out...>(In...)> {
using type = result<Out...>(std::decay_t<In>...);
};
// case #4: function returning a typed_response_promise<...>
template <class... Out, class... In>
struct dmi<typed_response_promise<Out...>(In...)> {
using type = result<Out...>(std::decay_t<In>...);
};
// -- dmfou = deduce_mpi_function_object_unboxing
template <class T, bool isClass = std::is_class<T>::value>
struct dmfou;
// case #1a: const member function pointer
template <class C, class Out, class... In>
struct dmfou<Out (C::*)(In...) const, false> : dmi<Out(In...)> {};
// case #1b: const member function pointer with noexcept
template <class C, class Out, class... In>
struct dmfou<Out (C::*)(In...) const noexcept, false> : dmi<Out(In...)> {};
// case #2a: member function pointer
template <class C, class Out, class... In>
struct dmfou<Out (C::*)(In...), false> : dmi<Out(In...)> {};
// case #2b: member function pointer with noexcept
template <class C, class Out, class... In>
struct dmfou<Out (C::*)(In...) noexcept, false> : dmi<Out(In...)> {};
// case #3a: good ol' function
template <class Out, class... In>
struct dmfou<Out(In...), false> : dmi<Out(In...)> {};
// case #3a: good ol' function with noexcept
template <class Out, class... In>
struct dmfou<Out(In...) noexcept, false> : dmi<Out(In...)> {};
template <class T>
struct dmfou<T, true> : dmfou<decltype(&T::operator()), false> {};
// this specialization leaves timeout definitions untouched,
// later stages such as interface_mismatch need to deal with them later
template <class T>
struct dmfou<timeout_definition<T>, true> {
using type = timeout_definition<T>;
};
} // namespace caf::detail
namespace caf {
/// Deduces the message passing interface from a function object.
template <class T>
using deduce_mpi_t = typename detail::dmfou<std::decay_t<T>>::type;
} // namespace caf
| 30.43956 | 77 | 0.678339 | seewpx |
e944e2ddd4607411eee4a7f93da89205cfde2846 | 1,934 | hpp | C++ | include/cpl/search/brent_find_cycle.hpp | dieram3/competitive-programming-library | 29bd0204d00c08e56d1f7fedc5c6c3603c4e5121 | [
"BSL-1.0"
] | 25 | 2016-05-03T02:08:58.000Z | 2022-01-11T03:49:28.000Z | include/cpl/search/brent_find_cycle.hpp | dieram3/competitive-programming-library | 29bd0204d00c08e56d1f7fedc5c6c3603c4e5121 | [
"BSL-1.0"
] | 22 | 2016-04-26T04:46:17.000Z | 2016-12-06T03:53:32.000Z | include/cpl/search/brent_find_cycle.hpp | dieram3/competitive-programming-library | 29bd0204d00c08e56d1f7fedc5c6c3603c4e5121 | [
"BSL-1.0"
] | 5 | 2017-04-04T16:10:42.000Z | 2019-12-05T08:22:30.000Z | // Copyright Diego Ramirez 2015
// 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 CPL_SEARCH_BRENT_FIND_CYCLE_HPP
#define CPL_SEARCH_BRENT_FIND_CYCLE_HPP
#include <cstddef> // size_t
#include <utility> // pair
namespace cpl {
/// \brief Finds a cycle in an iterated function.
///
/// Given the sequence of iterated function values:
/// <blockquote><tt>x<sub>0</sub>, x<sub>1</sub> = f(x<sub>0</sub>), ...,
/// x<sub>i</sub> = f(x<sub>i-1</sub>)</tt></blockquote>
///
/// This function uses the Brent's algorithm to find two values: \p lam and
/// \p mu. The cycle length \p lam is defined as the smallest value that
/// satisfies the loop condition <tt>x<sub>i</sub> == x<sub>i+lam</sub></tt>
/// for all <tt>i >= mu</tt>. The cycle start \p mu is defined as the smallest
/// value needed to comply the above condition, in other words, the number of
/// iterations needed to reach the loop.
///
/// \param f The function to be examined.
/// \param x0 The initial state.
///
/// \pre The function \p f must have a cycle reachable from \p x0.
///
/// \returns A pair containing <tt>(lam, mu)</tt>.
///
/// \par Complexity
/// <tt>O(lam + mu)</tt> applications of \p f.
///
template <typename F, typename T>
std::pair<size_t, size_t> brent_find_cycle(F f, T x0) {
size_t power = 1, lam = 1;
T tortoise = x0;
T hare = f(x0);
while (tortoise != hare) {
if (power == lam) {
tortoise = hare;
power *= 2;
lam = 0;
}
hare = f(hare);
++lam;
}
// At this point, the cycle length 'lam' is known.
size_t mu = 0;
tortoise = hare = x0;
for (size_t rep = 0; rep != lam; ++rep)
hare = f(hare);
while (tortoise != hare) {
tortoise = f(tortoise);
hare = f(hare);
++mu;
}
return {lam, mu};
}
} // end namespace cpl
#endif // Header guard
| 28.865672 | 78 | 0.626163 | dieram3 |
e944f238abd42ba6688d00b48e93cf8801b19112 | 1,814 | cpp | C++ | src/plugins/robots/attabot/simulator/attabot_measures.cpp | DiegoD616/argos3-ATTABOT | e909bf1432dbd6649450dbb95e4e9f68f375eefa | [
"MIT"
] | null | null | null | src/plugins/robots/attabot/simulator/attabot_measures.cpp | DiegoD616/argos3-ATTABOT | e909bf1432dbd6649450dbb95e4e9f68f375eefa | [
"MIT"
] | null | null | null | src/plugins/robots/attabot/simulator/attabot_measures.cpp | DiegoD616/argos3-ATTABOT | e909bf1432dbd6649450dbb95e4e9f68f375eefa | [
"MIT"
] | null | null | null | /**
* @file <argos3/plugins/robots/attabot/simulator/attabot_measures.h>
*
* @author Carlo Pinciroli - <ilpincy@gmail.com>
*/
#include "attabot_measures.h"
/****************************************/
/****************************************/
const Real ATTABOT_BASE_RADIUS = 0.0704;
const Real ATTABOT_BASE_ELEVATION = 0.0047;
const Real ATTABOT_BASE_HEIGHT = 0.053;
const Real ATTABOT_BASE_TOP = ATTABOT_BASE_ELEVATION + ATTABOT_BASE_HEIGHT;
const Real ATTABOT_WHEEL_RADIUS = 0.021;
const Real ATTABOT_WHEEL_DISTANCE = 0.1054;
const Real ATTABOT_HALF_WHEEL_DISTANCE = ATTABOT_WHEEL_DISTANCE * 0.5;
const Real ATTABOT_IR_SENSORS_RING_ELEVATION = 0.0145;
const Real ATTABOT_IR_SENSORS_RING_RADIUS = ATTABOT_BASE_RADIUS;
const Real ATTABOT_IR_SENSORS_RING_RANGE = 0.12;
const Real ATTABOT_ULTRASOUND_SENSORS_RING_ELEVATION = 0.0145;
const Real ATTABOT_ULTRASOUND_SENSORS_RING_RADIUS = ATTABOT_BASE_RADIUS;
const CRange<Real> ATTABOT_ULTRASOUND_SENSORS_RING_RANGE(0.25, 2.0);
const CVector2 ATTABOT_IR_SENSORS_GROUND_OFFSET[4] = {
CVector2(0.06140, 0.01),
CVector2(0.02060, 0.059),
CVector2(0.02060, -0.059),
CVector2(0.06140, -0.01)
};
const CVector3 ATTABOT_LEDS_OFFSET[3] = {
CVector3( 0.04, 0.025, ATTABOT_BASE_TOP),
CVector3(-0.05, 0.000, ATTABOT_BASE_TOP),
CVector3( 0.04, -0.025, ATTABOT_BASE_TOP)
};
const Real ATTABOT_LIDAR_CENTER_ELEVATION = 0.084;
const Real ATTABOT_LIDAR_ELEVATION = ATTABOT_BASE_TOP + ATTABOT_LIDAR_CENTER_ELEVATION;
const Real ATTABOT_LIDAR_SENSORS_FAN_RADIUS = ATTABOT_BASE_RADIUS;
const CRadians ATTABOT_LIDAR_ANGLE_SPAN(ToRadians(CDegrees(210.0)));
const CRange<Real> ATTABOT_LIDAR_SENSORS_RING_RANGE(0.02, 4.0);
/****************************************/
/****************************************/
| 36.28 | 96 | 0.699008 | DiegoD616 |
e9453d612cafe580c706515bbaa88360bb2ded7d | 2,594 | cpp | C++ | HazelGameEngine/src/Hazel/Core/Application.cpp | duo131/Hazel_practice | 04eeec2550b9536e7b8a565d67630c1d2a669991 | [
"Apache-2.0"
] | null | null | null | HazelGameEngine/src/Hazel/Core/Application.cpp | duo131/Hazel_practice | 04eeec2550b9536e7b8a565d67630c1d2a669991 | [
"Apache-2.0"
] | null | null | null | HazelGameEngine/src/Hazel/Core/Application.cpp | duo131/Hazel_practice | 04eeec2550b9536e7b8a565d67630c1d2a669991 | [
"Apache-2.0"
] | null | null | null | #include "hzpch.h"
#include "Application.h"
#include "Hazel/Events/ApplicationEvent.h"
#include "Hazel/Core/Log.h"
#include "Input.h"
#include "Hazel/Renderer/Renderer.h"
#include "glm/glm.hpp"
#include <GLFW/glfw3.h>
namespace Hazel {
#define BIND_EVENT_FN(x) std::bind(&x, this, std::placeholders::_1)
//assign singleton(only one application a time) by this as pointer for other use
Application* Application::s_Instance = nullptr;
Application::Application()
{
HZ_CORE_ASSERT(!s_Instance, "Application already exist!");
s_Instance = this;
m_Window = std::unique_ptr<Window>(Window::Create());
m_Window->SetEventCallback(BIND_EVENT_FN(Application::OnEvent));
//m_Window->SetVSync(false);
//Renderer
Renderer::Init();
m_ImGuiLayer = new ImGuiLayer();
PushOverlay(m_ImGuiLayer);
}
Application::~Application()
{
}
void Application::PushLayer(Layer* layer)
{
m_LayerStack.PushLayer(layer);
layer->OnAttach();
}
void Application::PushOverlay(Layer* overlay)
{
m_LayerStack.PushOverlay(overlay);
overlay->OnAttach();
}
void Application::OnEvent(Event& e)
{
EventDispatcher dispatcher(e);
dispatcher.Dispatch<WindowCloseEvent>(BIND_EVENT_FN(Application::OnWindowClose));
dispatcher.Dispatch<WindowResizeEvent>(BIND_EVENT_FN(Application::OnWindowResize));
//HZ_CORE_TRACE("{0}",e);
//Event layer: from top layer to bottom layer(backward)
for (auto it = m_LayerStack.end(); it != m_LayerStack.begin();)
{
(*--it)->OnEvent(e);
if (e.Handled)
break;
}
}
void Application::Run()
{
while (m_Running)
{
float time = (float)glfwGetTime(); // should be platform getTime
Timestep timestep = time - m_LastFrameTime;
m_LastFrameTime = time;
if (!m_Minimized) // if minimized, no need to update
{
// render layer: from bottom layer to top layer
for (auto layer : m_LayerStack)
{
layer->OnUpdate(timestep);
}
}
// for ImGui Layer
m_ImGuiLayer->Begin();
for (auto layer : m_LayerStack)
{
layer->OnImGuiRender();
}
m_ImGuiLayer->End();
//auto [x, y] = Input::GetMousePostion();
//HZ_CORE_TRACE("{0}, {1}", x, y);
m_Window->OnUpdate();
}
}
bool Application::OnWindowClose(WindowCloseEvent& e)
{
m_Running = false;
return true;
}
bool Application::OnWindowResize(WindowResizeEvent& e)
{
//when windows minimize, the height and width will be 0
if (e.GetWidth() == 0 || e.GetHeight() == 0)
{
m_Minimized = true;
return false;
}
m_Minimized = false;
Renderer::WindowResize(e.GetWidth(), e.GetHeight());
return false;
}
} | 22.17094 | 85 | 0.681958 | duo131 |
e946abe52374922bed3d60418603417c3dedd69d | 372 | cpp | C++ | meta/test/test_complete_type.cpp | theodelrieu/mgs | 965a95e3d539447cc482e915f9c44b3439168a4e | [
"BSL-1.0"
] | 24 | 2020-07-01T13:45:50.000Z | 2021-11-04T19:54:47.000Z | meta/test/test_complete_type.cpp | theodelrieu/mgs | 965a95e3d539447cc482e915f9c44b3439168a4e | [
"BSL-1.0"
] | null | null | null | meta/test/test_complete_type.cpp | theodelrieu/mgs | 965a95e3d539447cc482e915f9c44b3439168a4e | [
"BSL-1.0"
] | null | null | null | #include <catch2/catch.hpp>
#include <mgs/meta/concepts/complete_type.hpp>
using namespace mgs::meta;
TEST_CASE("complete_type")
{
static_assert(is_complete_type<int>::value, "");
static_assert(is_complete_type<struct incomplete*>::value, "");
static_assert(!is_complete_type<struct incomplete>::value, "");
static_assert(!is_complete_type<void>::value, "");
}
| 26.571429 | 65 | 0.744624 | theodelrieu |
e948cd4fea41ac4a023bfc25f292e2da7aaa19c6 | 6,639 | hxx | C++ | nixycore/string/detail/string_ops_define.hxx | yyzybb537/nixy | a77d0eac833a29d29d6717ce722ed75a813a4e1f | [
"MIT"
] | 1 | 2016-09-24T03:49:30.000Z | 2016-09-24T03:49:30.000Z | nixycore/string/detail/string_ops_define.hxx | yyzybb537/nixy | a77d0eac833a29d29d6717ce722ed75a813a4e1f | [
"MIT"
] | null | null | null | nixycore/string/detail/string_ops_define.hxx | yyzybb537/nixy | a77d0eac833a29d29d6717ce722ed75a813a4e1f | [
"MIT"
] | 4 | 2015-10-30T04:01:09.000Z | 2021-01-07T05:11:56.000Z | /*
The Nixy Library
Code covered by the MIT License
Modified from Extended STL string (http://www.gotroot.ca/ext_string)
Modified by : mutouyun (http://darkc.at)
Copyright (c) 2005, Keenan Tims (ktims@gotroot.ca) All rights reserved.
*/
//////////////////////////////////////////////////////////////////////////
/*
split string to a vector
*/
static bool default_check(value_type c)
{
return (c == ' ' || c == '\n' || c == '\t' || c == '\r');
}
static bool split_check(const_iterator i, const_iterator* t) // default check
{
if (t) (*t) = i + 1;
return default_check(*i);
}
static bool split_check(const_iterator i, const_iterator* t, value_type sep) // check with separator
{
if (t) (*t) = i + 1;
return (*i == sep);
}
static bool split_check(const_iterator i, const_iterator* t, const string& sep) // check with string
{
if (t) (*t) = i + sep.length();
return (string(i, i + sep.length()) == sep);
}
nx_rval(vector<string>, true) split(const functor<bool(const_iterator, const_iterator*)>& do_check,
size_type limit = npos) const
{
vector<string> v;
const_iterator i = begin(), last = i;
for (; i != end(); ++i)
{
const_iterator t;
if (!do_check(i, &t)) continue;
if (t != end() && do_check(t, nx::nulptr)) continue;
v.push_back(string(last, i));
last = t;
if (v.size() >= limit - 1)
{
v.push_back(string(last, end()));
return v;
}
}
if (last != i)
v.push_back(string(last, i));
return nx::move(v);
}
nx_rval(vector<string>, true) split(size_type limit = npos) const
{
return split(static_cast<bool(*)(const_iterator, const_iterator*)>(&string::split_check), limit);
}
nx_rval(vector<string>, true) split(value_type sep, size_type limit = npos) const
{
return split(nx::bind(static_cast<bool(*)(const_iterator, const_iterator*, value_type)>(&string::split_check),
nx::_1, nx::_2, nx_pass(sep)),
limit);
}
nx_rval(vector<string>, true) split(const string& sep, size_type limit = npos) const
{
return split(nx::bind(static_cast<bool(*)(const_iterator, const_iterator*, const string&)>(&string::split_check),
nx::_1, nx::_2, nx_pass(sep)),
limit);
}
nx_rval(vector<string>, true) split_to_chunks(size_type chunk_len) const
{
vector<string> v;
v.reserve(size() / chunk_len + 1);
size_type count = 0;
const_iterator i = begin(), last = i;
for (; i != end(); ++i, ++count)
{
if (count == chunk_len)
{
count = 0;
v.push_back(string(last, i));
last = i;
}
}
if (last != i)
v.push_back(string(last, i));
return nx::move(v);
}
/*
replace
*/
string& replace(const string& needle, const string& s)
{
size_type lastpos = 0, thispos;
while ((thispos = find(needle, lastpos)) != npos)
{
base_t::replace(thispos, needle.length(), s);
lastpos = thispos + 1;
}
return (*this);
}
string& replace(value_type needle, value_type c)
{
for (iterator i = begin(); i != end(); ++i)
if (*i == needle) *i = c;
return (*this);
}
/*
string multiplication
*/
nx_rval(string) operator*(size_type n)
{
string ret;
for (size_type i = 0; i < n; ++i)
ret.append(*this);
return nx::move(ret);
}
/*
case conversion
*/
string& to_lower(void)
{
for (iterator i = begin(); i != end(); ++i)
if (*i >= 'A' && *i <= 'Z')
*i += ('a' - 'A');
return (*this);
}
string& to_upper(void)
{
for (iterator i = begin(); i != end(); ++i)
if (*i >= 'a' && *i <= 'z')
*i -= ('a' - 'A');
return (*this);
}
string& swap_case(void)
{
for (iterator i = begin(); i != end(); ++i)
{
if (*i >= 'A' && *i <= 'Z')
*i += ('a' - 'A');
else
if (*i >= 'a' && *i <= 'z')
*i -= ('a' - 'A');
}
return (*this);
}
/*
count the substring from this string
*/
size_type count(const string& sub) const
{
size_type num = 0, last = 0, cur = 0;
while ((cur = find(sub, last + 1)) != npos)
{
num += 1;
last = cur;
}
return num;
}
/*
judgement
*/
bool is_alphabet(void) const
{
if (empty()) return false;
for (const_iterator i = begin(); i != end(); ++i)
if (*i < 'A' || (*i > 'Z' && (*i < 'a' || *i > 'z')))
return false;
return true;
}
bool is_allnumber(void) const
{
if (empty()) return false;
for (const_iterator i = begin(); i != end(); ++i)
if (*i < '0' || *i > '9')
return false;
return true;
}
bool is_integral(void) const
{
if (empty()) return false;
for (const_iterator i = begin(); i != end(); ++i)
{
if (i == begin() && (*i == '-' || *i == '+'))
continue;
if (*i < '0' || *i > '9')
return false;
}
return true;
}
bool is_float(void) const
{
if (empty()) return false;
bool dot = false;
for (const_iterator i = begin(); i != end(); ++i)
{
if (i == begin() && (*i == '-' || *i == '+'))
continue;
if (!dot && *i == '.')
{
dot = true;
continue;
}
if (*i < '0' || *i > '9')
return false;
}
return dot;
}
bool is_numeric(void) const
{
if (empty()) return false;
bool dot = false;
for (const_iterator i = begin(); i != end(); ++i)
{
if (i == begin() && (*i == '-' || *i == '+'))
continue;
if (!dot && *i == '.')
{
dot = true;
continue;
}
if (*i < '0' || *i > '9')
return false;
}
return true;
}
bool is_nonsymbol(void) const
{
if (empty()) return false;
for (const_iterator i = begin(); i != end(); ++i)
{
if (*i < 'A' || *i > 'Z')
if (*i < '0' || *i > '9')
if (*i < 'a' || *i > 'z')
return false;
}
return true;
}
bool is_lower(void) const
{
if (empty()) return false;
for (const_iterator i = begin(); i != end(); ++i)
if (*i < 'a' || *i > 'z')
return false;
return true;
}
bool is_upper(void) const
{
if (empty()) return false;
for (const_iterator i = begin(); i != end(); ++i)
if (*i < 'A' || *i > 'Z')
return false;
return true;
}
//////////////////////////////////////////////////////////////////////////
| 22.972318 | 117 | 0.480795 | yyzybb537 |
e94d9d9c5b2d14bc4c7f52b2f912ae12bd6c393f | 371 | cpp | C++ | gnuplot/gsyscall.cpp | yan9a/plotcpp | 27dc7bcf7b2508de13884bec3b22250db3b8421f | [
"MIT"
] | null | null | null | gnuplot/gsyscall.cpp | yan9a/plotcpp | 27dc7bcf7b2508de13884bec3b22250db3b8421f | [
"MIT"
] | null | null | null | gnuplot/gsyscall.cpp | yan9a/plotcpp | 27dc7bcf7b2508de13884bec3b22250db3b8421f | [
"MIT"
] | null | null | null | // File: gsyscall.cpp
// Description: gnuplot system call
// WebSite: http://cool-emerald.blogspot.com
// MIT License (https://opensource.org/licenses/MIT)
// Copyright (c) 2018 Yan Naing Aye
#include <iostream>
using namespace std;
int main() {
cout<<"Using gnuplot"<<endl;
system("gnuplot -p -e \"set datafile separator ',';plot 'test.csv'\"");
return 0;
} | 28.538462 | 75 | 0.679245 | yan9a |
e950d758ddf11187b791f6b8ea779548ab0ce2e1 | 17,741 | hpp | C++ | modules/core/linalg/include/nt2/linalg/functions/factorizations/symeig.hpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | 34 | 2017-05-19T18:10:17.000Z | 2022-01-04T02:18:13.000Z | modules/core/linalg/include/nt2/linalg/functions/factorizations/symeig.hpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | null | null | null | modules/core/linalg/include/nt2/linalg/functions/factorizations/symeig.hpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | 7 | 2017-12-02T12:59:17.000Z | 2021-07-31T12:46:14.000Z | //==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2013 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_LINALG_FUNCTIONS_FACTORIZATIONS_SYMEIG_HPP_INCLUDED
#define NT2_LINALG_FUNCTIONS_FACTORIZATIONS_SYMEIG_HPP_INCLUDED
#include <nt2/include/functions/symeig.hpp>
#include <boost/dispatch/attributes.hpp>
#include <nt2/include/functions/from_diag.hpp>
#include <nt2/include/functions/height.hpp>
#include <nt2/include/functions/hsev_w.hpp>
#include <nt2/include/functions/hsev_wu.hpp>
#include <nt2/include/functions/of_size.hpp>
#include <nt2/include/functions/real.hpp>
#include <nt2/include/functions/resize.hpp>
#include <nt2/include/functions/tie.hpp>
#include <nt2/sdk/meta/as_real.hpp>
#include <nt2/linalg/options.hpp>
#include <nt2/linalg/details/utility/lapack_verify.hpp>
#include <nt2/core/utility/assign_swap.hpp>
#include <nt2/core/container/dsl/as_terminal.hpp>
#include <nt2/core/container/table/table.hpp>
namespace nt2 { namespace ext
{
//============================================================================
//SYMEIG Scalar
//============================================================================
BOOST_DISPATCH_IMPLEMENT ( symeig_, tag::cpu_
, (A0)
, (scalar_<unspecified_<A0> >)
)
{
typedef typename nt2::meta::as_real<A0>::type result_type;
BOOST_FORCEINLINE result_type operator()(const A0& a0) const
{
return real(a0);
}
};
BOOST_DISPATCH_IMPLEMENT ( symeig_, tag::cpu_
, (A0)(A1)
, (scalar_<unspecified_<A0> >)
(unspecified_<A1>)
)
{
typedef typename nt2::meta::as_real<A0>::type result_type;
BOOST_FORCEINLINE result_type operator()(const A0& a0, const A1&) const
{
return real(a0);
}
};
BOOST_DISPATCH_IMPLEMENT ( symeig_, tag::cpu_
, (A0)(A1)(A2)
, (scalar_<unspecified_<A0> >)
(unspecified_<A1>)
(unspecified_<A2>)
)
{
typedef typename nt2::meta::as_real<A0>::type result_type;
BOOST_FORCEINLINE result_type operator()(const A0& a0, const A1&, const A2&) const
{
return real(a0);
}
};
//============================================================================
//SYMEIG
//============================================================================
BOOST_DISPATCH_IMPLEMENT ( symeig_, tag::cpu_
, (A0)(N0)(A1)(N1)
, ((node_<A0, nt2::tag::symeig_
, N0, nt2::container::domain
>
))
((node_<A1, nt2::tag::tie_
, N1, nt2::container::domain
>
))
)
{
typedef void result_type;
typedef typename boost::proto::result_of::child_c<A0&,0>::value_type child0;
typedef typename child0::value_type type_t;
typedef typename nt2::meta::as_real<type_t>::type rtype_t;
typedef nt2::memory::container<tag::table_, type_t, nt2::_2D> o_semantic;
typedef nt2::memory::container<tag::table_, rtype_t, nt2::_2D> r_semantic;
BOOST_FORCEINLINE result_type operator()( A0& a0, A1& a1 ) const
{
eval(a0, a1, N0(), N1());
}
private:
//==========================================================================
/// INTERNAL ONLY - W = SYMEIG(A)
// returns eigenvalues as a vector
BOOST_FORCEINLINE
void eval ( A0& a0, A1& a1
, boost::mpl::long_<1> const&
, boost::mpl::long_<1> const&
) const
{
eval1_3(a0, a1
, nt2::policy<ext::vector_>()
, nt2::policy<ext::upper_>());
}
//==========================================================================
/// INTERNAL ONLY - W = SYMEIG(A, matrix_/vector_/upper_/lower_/raw_)
// returns eigenvalues as a vector
BOOST_FORCEINLINE
void eval ( A0& a0, A1& a1
, boost::mpl::long_<2> const&
, boost::mpl::long_<1> const&
) const
{
eval1_2(a0, a1
, boost::proto::value(boost::proto::child_c<1>(a0)));
}
BOOST_FORCEINLINE
void eval1_2 ( A0& a0, A1& a1
, nt2::policy<ext::vector_>
) const
{
eval1_3(a0, a1
, nt2::policy<ext::vector_>()
, nt2::policy<ext::upper_>());
}
BOOST_FORCEINLINE
void eval1_2 ( A0& a0, A1& a1
, nt2::policy<ext::raw_>
) const
{
eval1_3(a0, a1
, nt2::policy<ext::vector_>()
, nt2::policy<ext::upper_>());
}
BOOST_FORCEINLINE
void eval1_2 ( A0& a0, A1& a1
, nt2::policy<ext::matrix_>
) const
{
eval1_3(a0, a1
, nt2::policy<ext::matrix_>()
, nt2::policy<ext::upper_>());
}
BOOST_FORCEINLINE
void eval1_2 ( A0& a0, A1& a1
, nt2::policy<ext::upper_>
) const
{
eval1_3(a0, a1
, nt2::policy<ext::vector_>()
, nt2::policy<ext::upper_>());
}
BOOST_FORCEINLINE
void eval1_2 ( A0& a0, A1& a1
, nt2::policy<ext::lower_>
) const
{
eval1_3(a0, a1
, nt2::policy<ext::vector_>()
, nt2::policy<ext::lower_>());
}
//==========================================================================
/// INTERNAL ONLY - W = SYMEIG(A, matrix_/vector_, upper_/lower_)
// returns eigenvalues as a vector
BOOST_FORCEINLINE
void eval ( A0& a0, A1& a1
, boost::mpl::long_<3> const&
, boost::mpl::long_<1> const&
) const
{
eval1_3(a0, a1
, boost::proto::value(boost::proto::child_c<1>(a0))
, boost::proto::value(boost::proto::child_c<2>(a0))
);
}
BOOST_FORCEINLINE
void eval1_3 ( A0& a0, A1& a1
, nt2::policy<ext::vector_> const &
, nt2::policy<ext::lower_> const &
) const
{
nt2::container::table<type_t> work;
NT2_AS_TERMINAL_INOUT(o_semantic, a
, boost::proto::child_c<0>(a0), work);
NT2_AS_TERMINAL_OUT (r_semantic, w
, boost::proto::child_c<0>(a1));
w.resize(nt2::of_size(height(a), 1));
NT2_LAPACK_VERIFY(nt2::hsev_w( boost::proto::value(a)
, boost::proto::value(w)
, 'L'));
assign_swap(boost::proto::child_c<0>(a1), w);
}
BOOST_FORCEINLINE
void eval1_3 ( A0& a0, A1& a1
, nt2::policy<ext::vector_> const &
, nt2::policy<ext::upper_> const &
) const
{
nt2::container::table<type_t> work;
NT2_AS_TERMINAL_INOUT(o_semantic, a
, boost::proto::child_c<0>(a0), work);
NT2_AS_TERMINAL_OUT (r_semantic, w
, boost::proto::child_c<0>(a1));
w.resize(nt2::of_size(height(a), 1));
NT2_LAPACK_VERIFY(nt2::hsev_w( boost::proto::value(a)
, boost::proto::value(w)
, 'U'));
assign_swap(boost::proto::child_c<0>(a1), w);
}
BOOST_FORCEINLINE
void eval1_3 ( A0& a0, A1& a1
, nt2::policy<ext::matrix_> const &
, nt2::policy<ext::lower_> const &
) const
{
nt2::container::table<type_t> work;
NT2_AS_TERMINAL_INOUT(o_semantic, a
, boost::proto::child_c<0>(a0), work);
nt2::container::table<rtype_t> w(of_size(height(a), 1));
NT2_LAPACK_VERIFY(nt2::hsev_w( boost::proto::value(a)
, boost::proto::value(w)
, 'L'));
boost::proto::child_c<0>(a1) = from_diag(w);
}
BOOST_FORCEINLINE
void eval1_3 ( A0& a0, A1& a1
, nt2::policy<ext::matrix_> const &
, nt2::policy<ext::upper_> const &
) const
{
nt2::container::table<type_t> work;
NT2_AS_TERMINAL_INOUT(o_semantic, a
, boost::proto::child_c<0>(a0), work);
nt2::container::table<rtype_t> w(of_size(height(a), 1));
NT2_LAPACK_VERIFY(nt2::hsev_w( boost::proto::value(a)
, boost::proto::value(w)
, 'U'));
boost::proto::child_c<0>(a1) = from_diag(w);
}
BOOST_FORCEINLINE
void eval1_3 ( A0& a0, A1& a1
, nt2::policy<ext::raw_>
, nt2::policy<ext::upper_>
) const
{
eval1_3(a0, a1
, nt2::policy<ext::vector_>(), nt2::policy<ext::upper_>());
}
BOOST_FORCEINLINE
void eval1_3 ( A0& a0, A1& a1
, nt2::policy<ext::raw_>
, nt2::policy<ext::lower_>
) const
{
eval1_3(a0, a1
, nt2::policy<ext::vector_>(), nt2::policy<ext::lower_>());
}
//==========================================================================
/// INTERNAL ONLY - [W, V]= SYMEIG(A, matrix_/vector_/upper_/lower_/raw_)
BOOST_FORCEINLINE
void eval ( A0& a0, A1& a1
, boost::mpl::long_<2> const&
, boost::mpl::long_<2> const&
) const
{
eval2_2(a0, a1
, boost::proto::value(boost::proto::child_c<1>(a0)));
}
//==========================================================================
/// INTERNAL ONLY - [W, U]= SYMEIG(A)
BOOST_FORCEINLINE
void eval ( A0& a0, A1& a1
, boost::mpl::long_<1> const&
, boost::mpl::long_<2> const&
) const
{
eval2_3(a0, a1, nt2::matrix_, nt2::upper_);
}
BOOST_FORCEINLINE
void eval2_2 ( A0& a0, A1& a1
, nt2::policy<ext::matrix_>
) const
{
NT2_AS_TERMINAL_INOUT(o_semantic, u
, boost::proto::child_c<0>(a0)
, boost::proto::child_c<1>(a1));
nt2::container::table<rtype_t> w(of_size(height(u), 1));
NT2_LAPACK_VERIFY(nt2::hsev_wu( boost::proto::value(u)
, boost::proto::value(w)
, 'U'));
boost::proto::child_c<0>(a1) = from_diag(w);
assign_swap(boost::proto::child_c<1>(a1), u);
}
BOOST_FORCEINLINE
void eval2_2 ( A0& a0, A1& a1
, nt2::policy<ext::vector_>
) const
{
NT2_AS_TERMINAL_INOUT(o_semantic, u
, boost::proto::child_c<0>(a0)
, boost::proto::child_c<1>(a1));
NT2_AS_TERMINAL_OUT (r_semantic, w, boost::proto::child_c<0>(a1));
w.resize(nt2::of_size(height(u), 1));
NT2_LAPACK_VERIFY(nt2::hsev_wu( boost::proto::value(u)
, boost::proto::value(w)
, 'U'));
assign_swap(boost::proto::child_c<0>(a1), w);
assign_swap(boost::proto::child_c<1>(a1), u);
}
BOOST_FORCEINLINE
void eval2_2 ( A0& a0, A1& a1
, nt2::policy<ext::raw_>
) const
{
eval2_2(a0, a1, nt2::policy<ext::vector_>());
}
BOOST_FORCEINLINE
void eval2_2 ( A0& a0, A1& a1
, nt2::policy<ext::lower_>
) const
{
eval2_3(a0, a1
, nt2::policy<ext::matrix_>()
, nt2::policy<ext::lower_>());
}
BOOST_FORCEINLINE
void eval2_2 ( A0& a0, A1& a1
, nt2::policy<ext::upper_>
) const
{
eval2_3(a0, a1
, nt2::policy<ext::matrix_>()
, nt2::policy<ext::upper_>());
}
//==========================================================================
/// INTERNAL ONLY - [W, V]= SYMEIG(A, matrix_/vector_, lower_/upper_)
BOOST_FORCEINLINE
void eval ( A0& a0, A1& a1
, boost::mpl::long_<3> const&
, boost::mpl::long_<2> const&
) const
{
eval2_3( a0, a1
, boost::proto::value(boost::proto::child_c<1>(a0))
, boost::proto::value(boost::proto::child_c<2>(a0))
);
}
BOOST_FORCEINLINE
void eval2_3 ( A0& a0, A1& a1
, nt2::policy<ext::matrix_>
, nt2::policy<ext::lower_>
) const
{
NT2_AS_TERMINAL_INOUT(o_semantic, u
, boost::proto::child_c<0>(a0)
, boost::proto::child_c<1>(a1));
nt2::container::table<rtype_t> w(of_size(height(u), 1));
NT2_LAPACK_VERIFY(nt2::hsev_wu( boost::proto::value(u)
, boost::proto::value(w)
, 'L'));
boost::proto::child_c<0>(a1) = from_diag(w);
assign_swap(boost::proto::child_c<1>(a1), u);
}
BOOST_FORCEINLINE
void eval2_3 ( A0& a0, A1& a1
, nt2::policy<ext::matrix_>
, nt2::policy<ext::upper_>
) const
{
NT2_AS_TERMINAL_INOUT(o_semantic, u
, boost::proto::child_c<0>(a0)
, boost::proto::child_c<1>(a1));
nt2::container::table<rtype_t> w(of_size(height(u), 1));
NT2_LAPACK_VERIFY(nt2::hsev_wu( boost::proto::value(u)
, boost::proto::value(w)
, 'U'));
boost::proto::child_c<0>(a1) = from_diag(w);
assign_swap(boost::proto::child_c<1>(a1), u);
}
BOOST_FORCEINLINE
void eval2_3 ( A0& a0, A1& a1
, nt2::policy<ext::vector_>
, nt2::policy<ext::upper_>
) const
{
NT2_AS_TERMINAL_INOUT(o_semantic, u
, boost::proto::child_c<0>(a0)
, boost::proto::child_c<1>(a1));
NT2_AS_TERMINAL_OUT (r_semantic, w
, boost::proto::child_c<0>(a1));
w.resize(of_size(height(u), 1));
NT2_LAPACK_VERIFY(nt2::hsev_wu( boost::proto::value(u)
, boost::proto::value(w)
, 'U'));
assign_swap(boost::proto::child_c<0>(a1), w);
assign_swap(boost::proto::child_c<1>(a1), u);
}
BOOST_FORCEINLINE
void eval2_3 ( A0& a0, A1& a1
, nt2::policy<ext::raw_>
, nt2::policy<ext::upper_>
) const
{
eval2_3(a0, a1
, nt2::policy<ext::vector_>(), nt2::policy<ext::upper_>());
}
BOOST_FORCEINLINE
void eval2_3 ( A0& a0, A1& a1
, nt2::policy<ext::raw_>
, nt2::policy<ext::lower_>
) const
{
eval2_3(a0, a1
, nt2::policy<ext::vector_>(), nt2::policy<ext::lower_>());
}
BOOST_FORCEINLINE
void eval2_3 ( A0& a0, A1& a1
, nt2::policy<ext::vector_>
, nt2::policy<ext::lower_>
) const
{
NT2_AS_TERMINAL_INOUT(o_semantic, u
, boost::proto::child_c<0>(a0)
, boost::proto::child_c<1>(a1));
NT2_AS_TERMINAL_OUT (r_semantic, w
, boost::proto::child_c<0>(a1));
w.resize(of_size(height(u), 1));
NT2_LAPACK_VERIFY(nt2::hsev_wu( boost::proto::value(u)
, boost::proto::value(w)
, 'L'));
assign_swap(boost::proto::child_c<0>(a1), w);
assign_swap(boost::proto::child_c<1>(a1), u);
}
#define MORE_OPTIONS(PARAM, OPT1, OPT2) \
BOOST_FORCEINLINE \
void eval##PARAM( A0& a0, A1& a1 \
, nt2::policy<ext::OPT1> \
, nt2::policy<ext::OPT2> \
) const \
{ \
eval##PARAM(a0, a1 \
, nt2::policy<ext::OPT2>() \
, nt2::policy<ext::OPT1>() \
); \
} \
/**/
MORE_OPTIONS(2_3, lower_, raw_)
MORE_OPTIONS(2_3, upper_, raw_)
MORE_OPTIONS(2_3, lower_, vector_)
MORE_OPTIONS(2_3, upper_, vector_)
MORE_OPTIONS(2_3, lower_, matrix_)
MORE_OPTIONS(2_3, upper_, matrix_)
MORE_OPTIONS(1_3, lower_, vector_)
MORE_OPTIONS(1_3, upper_, vector_)
MORE_OPTIONS(1_3, lower_, raw_)
MORE_OPTIONS(1_3, upper_, raw_)
MORE_OPTIONS(1_3, lower_, matrix_)
MORE_OPTIONS(1_3, upper_, matrix_)
#undef MORE_OPTIONS
};
} }
#endif
| 34.650391 | 86 | 0.457584 | psiha |
e952153a56db7bb8679eeeb5d9da42174f8bc990 | 4,641 | cpp | C++ | Sources/Internal/Render/RenderPass/ForwardRenderPass.cpp | nameless323/KiotoEngine | 3db271540b4cacdfbca697acfa029dd8caf72761 | [
"MIT"
] | 4 | 2019-04-26T15:48:10.000Z | 2020-06-02T02:15:07.000Z | Sources/Internal/Render/RenderPass/ForwardRenderPass.cpp | nameless323/KiotoEngine | 3db271540b4cacdfbca697acfa029dd8caf72761 | [
"MIT"
] | 2 | 2017-08-11T10:49:55.000Z | 2020-04-04T13:20:22.000Z | Sources/Internal/Render/RenderPass/ForwardRenderPass.cpp | nameless323/KiotoEngine | 3db271540b4cacdfbca697acfa029dd8caf72761 | [
"MIT"
] | 1 | 2021-02-07T08:28:04.000Z | 2021-02-07T08:28:04.000Z | #include "stdafx.h"
#include "Render/RenderPass/ForwardRenderPass.h"
#include "Core/KiotoEngine.h"
#include "Render/Camera.h"
#include "Render/Material.h"
#include "Render/Renderer.h"
#include "Render/RenderCommand.h"
#include "Render/RenderObject.h"
#include "Render/RenderPacket.h"
#include "Render/RenderSettings.h"
#include "Render/Shader.h"
#include "Render/RenderGraph/ResourcesBlackboard.h"
#include "Render/RenderGraph/ResourceTable.h"
#include "Render/Shaders/autogen/sInp/Fallback.h"
#include "Render/Shaders/autogen/CommonStructures.h"
#include "Component/LightComponent.h"
namespace Kioto::Renderer
{
ForwardRenderPass::ForwardRenderPass()
: RenderPass("Forward")
{
Renderer::RegisterRenderPass(this);
Renderer::RegisterConstantBuffer(m_lightsBuffer);
SetRenderTargetCount(1);
}
void ForwardRenderPass::BuildRenderPackets(CommandList* commandList, ResourceTable& resources)
{
SetRenderTargets(commandList, resources);
for (uint32 i = 0; i < m_drawData->Lights.size(); ++i)
m_lights.light[i] = std::move(m_drawData->Lights[i]->GetGraphicsLight());
m_lights.shadowTransform = resources.GetPassesSharedData().ShadowTransform;
m_lightsBuffer.Set(m_lights);
Texture* shadowMap = resources.GetResource("ShadowMap");
for (auto ro : m_drawData->RenderObjects)
{
if (!ro->GetIsVisible())
continue;
ro->SetExternalCB(m_passName, Renderer::SInp::Fallback_sinp::cbCameraName, Renderer::GetMainCamera()->GetConstantBuffer().GetHandle());
ro->SetExternalCB(m_passName, Renderer::SInp::Fallback_sinp::cbEngineName, Renderer::EngineBuffers::GetTimeBuffer().GetHandle());
ro->SetExternalCB(m_passName, Renderer::SInp::Fallback_sinp::lightsName, m_lightsBuffer.GetHandle());
ro->SetConstant(m_passName, "LIGHTS_COUNT", static_cast<uint32>(m_drawData->Lights.size()));
Material* mat = ro->GetMaterial();
Mesh* mesh = ro->GetMesh();
mat->BuildMaterialForPass(this);
ro->PrepareConstantBuffers(m_passName);
ro->SetTexture("ShadowTexture", shadowMap, m_passName);
RenderPacket currPacket = {};
currPacket.Material = mat->GetHandle();
currPacket.Shader = mat->GetPipelineState(m_passName).Shader->GetHandle();
currPacket.TextureSet = ro->GetTextureSet(m_passName).GetHandle();
currPacket.Mesh = mesh->GetHandle();
currPacket.Pass = GetHandle();
currPacket.ConstantBufferHandles = std::move(ro->GetCBHandles(m_passName));
currPacket.UniformConstants = std::move(ro->GetConstants(m_passName));
commandList->PushCommand(RenderCommandHelpers::CreateRenderPacketCommand(currPacket, this));
}
commandList->PushCommand(RenderCommandHelpers::CreatePassEndsCommand(this));
}
void ForwardRenderPass::Cleanup()
{
}
void ForwardRenderPass::SetRenderTargets(CommandList* commandList, ResourceTable& resources)
{
SetRenderTargetsCommand cmd;
Texture* rtTex = resources.GetResource("FwdTargetTexture");
cmd.SetRenderTargets(rtTex->GetHandle());
//cmd.SetRenderTargets(Renderer::DefaultBackBufferHandle);
cmd.RenderTargetCount = GetRenderTargetCount();
cmd.DepthStencil = Renderer::DefaultDepthStencilHandle;
cmd.Viewport = { 0, 0, Renderer::GetWidth(), Renderer::GetHeight() };
cmd.Scissor = { 0, 0, Renderer::GetWidth(), Renderer::GetHeight() };
cmd.ClearDepth = true;
cmd.ClearDepthValue = 0.0f;
cmd.ClearColor = true;
cmd.ClearColorValue = Color::DefaultBackgroundColor;
cmd.ClearStencil = true;
cmd.ClearStencilValue = 0;
commandList->PushCommand(RenderCommandHelpers::CreateSetRenderTargetCommand(cmd, this));
}
bool ForwardRenderPass::ConfigureInputsAndOutputs(ResourcesBlackboard& resources)
{
const RenderSettings& settings = KiotoCore::GetRenderSettings();
TextureDescriptor desc;
desc.Dimension = eResourceDim::Texture2D;
desc.Format = eResourceFormat::Format_R8G8B8A8_UNORM;
desc.Flags = eResourceFlags::AllowRenderTarget;
desc.Width = Renderer::GetWidth();
desc.Height = Renderer::GetHeight();
desc.InitialState = eResourceState::Common;
desc.FastClear = true;
desc.FastClearValue = Color::DefaultBackgroundColor;
desc.Name = "FwdTargetTexture";
resources.NewTexture("FwdTargetTexture", std::move(desc));
resources.ScheduleWrite("FwdTargetTexture");
resources.ScheduleRead("ShadowMap");
if (settings.RenderMode == RenderSettings::RenderModeOptions::Final
|| settings.RenderMode == RenderSettings::RenderModeOptions::FinalAndWireframe)
return true;
return false;
}
} | 36.543307 | 143 | 0.730661 | nameless323 |
e9525818407981a21848642878a2d8bdc12dc669 | 6,264 | cpp | C++ | src/Internal/Connection.cpp | MrElectrify/BetteRCon | ecec11174c2aa90a142ef0169b00ad97af9a1068 | [
"MIT"
] | 2 | 2019-12-13T04:10:25.000Z | 2021-10-29T21:26:07.000Z | src/Internal/Connection.cpp | MrElectrify/BetteRCon | ecec11174c2aa90a142ef0169b00ad97af9a1068 | [
"MIT"
] | 2 | 2019-12-26T05:31:46.000Z | 2020-01-18T23:26:46.000Z | src/Internal/Connection.cpp | MrElectrify/BetteRCon | ecec11174c2aa90a142ef0169b00ad97af9a1068 | [
"MIT"
] | null | null | null | #include <BetteRCon/Internal/Connection.h>
using BetteRCon::Internal::Connection;
using BetteRCon::Internal::Packet;
Connection::Connection(Worker_t& worker)
: m_worker(worker), m_connected(false),
m_socket(m_worker), m_timeoutTimer(m_worker) {}
void Connection::AsyncConnect(const Endpoint_t& endpoint, ConnectCallback_t&& connectCallback,
DisconnectCallback_t&& disconnectCallback, RecvCallback_t&& eventCallback) noexcept
{
// make sure we are not already connected
if (m_connected == true)
return connectCallback(asio::error::make_error_code(asio::error::already_connected));
// save the disconnect and event callbacks
m_disconnectCallback = std::move(disconnectCallback);
m_eventCallback = std::move(eventCallback);
// try to connect
ErrorCode_t ec;
m_socket.async_connect(endpoint, [this, connectCallback = std::move(connectCallback)]
(const ErrorCode_t& ec)
{
if (ec)
return connectCallback(ec);
// we are successfully connected.
m_connected = true;
// start the 2-minute connection timeout
m_timeoutTimer.expires_from_now(std::chrono::minutes(2));
m_timeoutTimer.async_wait(std::bind(&Connection::HandleTimeout, this, std::placeholders::_1));
// read the first 8 bytes from the socket, which will include the size of the packet
m_incomingBuf.resize(sizeof(int32_t) * 2);
asio::async_read(m_socket, asio::buffer(m_incomingBuf),
std::bind(&Connection::HandleReadHeader, this,
std::placeholders::_1, std::placeholders::_2));
connectCallback(ec);
});
}
void Connection::Disconnect() noexcept
{
// make sure we are not connected already
if (IsConnected() == false)
return;
// post the functor to allow this operation to be called from any thread
m_worker.post(std::bind(&Connection::CloseConnection, this, ErrorCode_t{}));
}
bool Connection::IsConnected() const noexcept
{
return m_connected == true;
}
void Connection::SendPacket(const Packet& packet, RecvCallback_t&& callback)
{
// make sure we are connected
if (IsConnected() == false)
return callback(asio::error::make_error_code(asio::error::not_connected), std::nullopt);
// serialize the data into our buffer
std::vector<char> sendBuf;
packet.Serialize(sendBuf);
// insert the buffer into the queue
m_sendQueue.push(std::move(sendBuf));
// ours is the only one. otherwise, a callback will handle sending our data
if (m_sendQueue.size() == 1)
SendUnsentBuffers();
// save the callback
m_recvCallbacks.emplace(packet.GetSequence(), std::move(callback));
}
Connection::~Connection()
{
// if it is destructed, it must be from the thread that created it.
if (IsConnected() == true)
CloseConnection(ErrorCode_t{});
}
void Connection::CloseConnection(const ErrorCode_t& ec)
{
ErrorCode_t ignored;
// disconnect the socket and call the handler
m_socket.shutdown(Socket_t::shutdown_both, ignored);
m_socket.close(ignored);
// cancel the timer
m_timeoutTimer.cancel(ignored);
// update connected status
m_connected = false;
// call the disconnect callback
m_disconnectCallback(ec);
}
void Connection::HandleReadHeader(const ErrorCode_t& ec, const size_t bytes_transferred)
{
if (ec)
{
if (ec != asio::error::operation_aborted)
CloseConnection(ec);
return;
}
const auto packetSize = *reinterpret_cast<const int32_t*>(&m_incomingBuf[sizeof(int32_t)]);
// resize the buffer to fit the whole packet
m_incomingBuf.resize(packetSize);
// receive the rest of the packet
asio::async_read(m_socket, asio::buffer(m_incomingBuf.data() + sizeof(int32_t) * 2, packetSize - sizeof(int32_t) * 2),
std::bind(&Connection::HandleReadBody, this,
std::placeholders::_1, std::placeholders::_2));
}
void Connection::HandleReadBody(const ErrorCode_t& ec, const size_t bytes_transferred)
{
if (ec)
{
if (ec != asio::error::operation_aborted)
CloseConnection(ec);
return;
}
// update the 2-minute connection timeout
m_timeoutTimer.expires_from_now(std::chrono::minutes(2));
m_timeoutTimer.async_wait(std::bind(&Connection::HandleTimeout, this, std::placeholders::_1));
// parse the packet
std::optional<Packet> receivedPacket;
try
{
receivedPacket = std::make_optional<Packet>(m_incomingBuf);
}
catch (const Packet::ErrorCode_t& ec)
{
// we got a bad packet. disconnect
return CloseConnection(asio::error::make_error_code(asio::error::invalid_argument));
}
// is this a response or an event?
if (receivedPacket->IsResponse() == true &&
receivedPacket->GetWords().size() > 0)
{
// return the response to the caller
auto callbackFnIt = m_recvCallbacks.find(receivedPacket->GetSequence());
if (callbackFnIt == m_recvCallbacks.end())
{
// this should not happen. abort
return CloseConnection(asio::error::make_error_code(asio::error::invalid_argument));
}
const auto fn = callbackFnIt->second;
// remove the callback
m_recvCallbacks.erase(callbackFnIt);
// call the callback
fn(ErrorCode_t{}, receivedPacket);
}
else
{
// move the event
m_eventCallback(ErrorCode_t{}, receivedPacket);
}
// read the first 8 bytes from the socket, which will include the size of the packet
m_incomingBuf.resize(sizeof(int32_t) * 2);
asio::async_read(m_socket, asio::buffer(m_incomingBuf),
std::bind(&Connection::HandleReadHeader, this,
std::placeholders::_1, std::placeholders::_2));
}
void Connection::HandleTimeout(const ErrorCode_t& ec)
{
// we reset the timer
if (ec == asio::error::operation_aborted)
return;
// 2 minutes have passed since we got a transmission from them. assume they are frozen, shutdown
CloseConnection(asio::error::make_error_code(asio::error::timed_out));
}
void Connection::HandleWrite(const ErrorCode_t& ec, const size_t bytes_transferred)
{
if (ec)
{
if (ec != asio::error::operation_aborted)
CloseConnection(ec);
return;
}
// pop the buffer, we don't need it any more
m_sendQueue.pop();
// send more packets if there are some lined up
if (m_sendQueue.empty() == false)
SendUnsentBuffers();
}
void Connection::SendUnsentBuffers()
{
// get the first buffer
const std::vector<char>& frontBuf = m_sendQueue.front();
// there is no send in progress
asio::async_write(m_socket, asio::buffer(frontBuf),
std::bind(&Connection::HandleWrite, this,
std::placeholders::_1, std::placeholders::_2));
} | 31.796954 | 119 | 0.737388 | MrElectrify |
e953adaa8c90c82e9ac89b889a18c71c6ff7b3ed | 3,119 | cpp | C++ | aws-cpp-sdk-alexaforbusiness/source/model/ConferenceProvider.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | 2 | 2019-03-11T15:50:55.000Z | 2020-02-27T11:40:27.000Z | aws-cpp-sdk-alexaforbusiness/source/model/ConferenceProvider.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-alexaforbusiness/source/model/ConferenceProvider.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | 1 | 2019-01-18T13:03:55.000Z | 2019-01-18T13:03:55.000Z | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/alexaforbusiness/model/ConferenceProvider.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace AlexaForBusiness
{
namespace Model
{
ConferenceProvider::ConferenceProvider() :
m_arnHasBeenSet(false),
m_nameHasBeenSet(false),
m_type(ConferenceProviderType::NOT_SET),
m_typeHasBeenSet(false),
m_iPDialInHasBeenSet(false),
m_pSTNDialInHasBeenSet(false),
m_meetingSettingHasBeenSet(false)
{
}
ConferenceProvider::ConferenceProvider(JsonView jsonValue) :
m_arnHasBeenSet(false),
m_nameHasBeenSet(false),
m_type(ConferenceProviderType::NOT_SET),
m_typeHasBeenSet(false),
m_iPDialInHasBeenSet(false),
m_pSTNDialInHasBeenSet(false),
m_meetingSettingHasBeenSet(false)
{
*this = jsonValue;
}
ConferenceProvider& ConferenceProvider::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Arn"))
{
m_arn = jsonValue.GetString("Arn");
m_arnHasBeenSet = true;
}
if(jsonValue.ValueExists("Name"))
{
m_name = jsonValue.GetString("Name");
m_nameHasBeenSet = true;
}
if(jsonValue.ValueExists("Type"))
{
m_type = ConferenceProviderTypeMapper::GetConferenceProviderTypeForName(jsonValue.GetString("Type"));
m_typeHasBeenSet = true;
}
if(jsonValue.ValueExists("IPDialIn"))
{
m_iPDialIn = jsonValue.GetObject("IPDialIn");
m_iPDialInHasBeenSet = true;
}
if(jsonValue.ValueExists("PSTNDialIn"))
{
m_pSTNDialIn = jsonValue.GetObject("PSTNDialIn");
m_pSTNDialInHasBeenSet = true;
}
if(jsonValue.ValueExists("MeetingSetting"))
{
m_meetingSetting = jsonValue.GetObject("MeetingSetting");
m_meetingSettingHasBeenSet = true;
}
return *this;
}
JsonValue ConferenceProvider::Jsonize() const
{
JsonValue payload;
if(m_arnHasBeenSet)
{
payload.WithString("Arn", m_arn);
}
if(m_nameHasBeenSet)
{
payload.WithString("Name", m_name);
}
if(m_typeHasBeenSet)
{
payload.WithString("Type", ConferenceProviderTypeMapper::GetNameForConferenceProviderType(m_type));
}
if(m_iPDialInHasBeenSet)
{
payload.WithObject("IPDialIn", m_iPDialIn.Jsonize());
}
if(m_pSTNDialInHasBeenSet)
{
payload.WithObject("PSTNDialIn", m_pSTNDialIn.Jsonize());
}
if(m_meetingSettingHasBeenSet)
{
payload.WithObject("MeetingSetting", m_meetingSetting.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace AlexaForBusiness
} // namespace Aws
| 21.363014 | 105 | 0.727797 | curiousjgeorge |
e95a5144c57fb9516db01b2a9baaee4ea76587d5 | 1,559 | hpp | C++ | Source Files/Objects/libstructimpl.hpp | hendry19901990/AlgorithmsUnlocked | e85b6dea4b3aea9b8015db24384b1527d828395d | [
"Xnet",
"X11"
] | 1 | 2022-03-25T10:20:25.000Z | 2022-03-25T10:20:25.000Z | Source Files/Objects/libstructimpl.hpp | hendry19901990/AlgorithmsUnlocked | e85b6dea4b3aea9b8015db24384b1527d828395d | [
"Xnet",
"X11"
] | null | null | null | Source Files/Objects/libstructimpl.hpp | hendry19901990/AlgorithmsUnlocked | e85b6dea4b3aea9b8015db24384b1527d828395d | [
"Xnet",
"X11"
] | null | null | null | #include <iostream>
#include <string>
#include <stdlib.h>
#include <cstdio>
#define MAX_LIMIT_SZ 2048
using namespace std;
typedef struct error{
int *p;
error *dangle = NULL;
}error;
typedef struct node{
int j;
char ch[2];
node *left;
node *right ;
node *dangler ;
node():j(MAX_LIMIT_SZ),left(nullptr),right(nullptr),dangler(nullptr){} // ctor initialization
}name;
void printStruct(node* *t)
{
node **p = t;
printf("%d\t%d\t%d\t%d\t",--((*p)->j),++((*p)->j),++((*p)->j),--((*p)->j));
printf("%d\t%d\t%d\t%d\t",((*p)->j)--,((*p)->j)++,((*p)->j)++,((*p)->j)--);
printf("%d\t%d\t%d\t%d\t",--((*p)->j),++((*p)->j),++((*p)->j),--((*p)->j));
printf("%d\t",(*++p)->j);
printf("%d\t",(*p)++->j);
printf("%d\t",(*++p)->j);
printf("%d\n",(*--p)->j);
}
int runMethodStruct()
{
node start;
node *root = (node*)malloc(sizeof(node));
node **TreeElements = (node**)malloc( MAX_LIMIT_SZ*sizeof(node*));
for(int i = 0; i < MAX_LIMIT_SZ; i++ )
{
TreeElements[i] = (node*)malloc(sizeof(node));
}
TreeElements[0]->j = 90;
TreeElements[0]->ch[0] = 'd';
TreeElements[1]->j = 91;
TreeElements[1]->ch[0] = 'c';
TreeElements[2]->j = 92;
TreeElements[2]->ch[1] = 'j';
printStruct(TreeElements);
int l= 90;
int a[] = {69,57,77,7,6,8,9,10};
error *ptr = (error*)malloc(sizeof(error));
ptr->p = a;
l = (*ptr->p++)++;
int y = ++l;
printf("%d\n",l);
printf("%d\n",y);
printf("%p\n",a);
printf("%d\n",*ptr->p);
return 0;
} | 27.350877 | 97 | 0.508659 | hendry19901990 |
e95cd4976991fbffc0436b5509969ea66722bb23 | 639 | hpp | C++ | src/action_and_component_macros/case_3/actions.hpp | McKillroy/hpx_snippets | 0c87b979cdd3947431be24f88bdb8d16d0c20187 | [
"BSL-1.0"
] | null | null | null | src/action_and_component_macros/case_3/actions.hpp | McKillroy/hpx_snippets | 0c87b979cdd3947431be24f88bdb8d16d0c20187 | [
"BSL-1.0"
] | null | null | null | src/action_and_component_macros/case_3/actions.hpp | McKillroy/hpx_snippets | 0c87b979cdd3947431be24f88bdb8d16d0c20187 | [
"BSL-1.0"
] | null | null | null | #pragma once
#include <hpx/hpx.hpp>
namespace test {
// Free function in namespace
int some_function( );
// Define the action (inside the namespace):
// Parameters: function name, desired action name
HPX_DEFINE_PLAIN_ACTION( some_function, some_function_action );
}; // namespace test
// Declare the Registering of the Action (in global namespace)
// Parameters: Fully qualified action name, desired action name for serialization
// Note: When invoking the action we will still need the fully qualified action name!
HPX_REGISTER_ACTION_DECLARATION( test::some_function_action, some_function_action_serialized );
| 31.95 | 95 | 0.763693 | McKillroy |
e95d67f7401d88fdcb5269fc7a5b94271a778978 | 2,952 | hpp | C++ | hmath/core/units.hpp | oliver-peoples/Hamiltonian-Mathematics | 91075f44829829fb7052b38bcdffd4a58d8c7b6d | [
"Unlicense"
] | null | null | null | hmath/core/units.hpp | oliver-peoples/Hamiltonian-Mathematics | 91075f44829829fb7052b38bcdffd4a58d8c7b6d | [
"Unlicense"
] | null | null | null | hmath/core/units.hpp | oliver-peoples/Hamiltonian-Mathematics | 91075f44829829fb7052b38bcdffd4a58d8c7b6d | [
"Unlicense"
] | null | null | null | #ifndef HMATH_UNITS_HPP
#define HMATH_UNITS_HPP
namespace hmath
{
namespace unit
{
// The base units
const long double second = 1.0;
const long double meter = 1.0;
const long double kilogram = 1.0;
const long double ampere = 1.0;
const long double kelvin = 1.0;
const long double mole = 1.0;
// The defining constants
const long double v_Cs = 9192631770.0;
const long double c = 299792458.0;
const long double h = 6.62607015e-34;
const long double e = 1.602176634e-19;
const long double k = 1.380649e-23;
const long double avocado = 6.02214076e23;
// The scalars
const long double yocto = 10e-24;
const long double zepto = 10e-21;
const long double atto = 10-18;
const long double femto = 10e-15;
const long double pico = 10e-12;
const long double nano = 10e-9;
const long double micro = 10e-6;
const long double milli = 10e-3;
const long double kilo = 10e3;
const long double mega = 10e6;
const long double giga = 10e9;
const long double tera = 10e12;
const long double peta = 10e15;
const long double exa = 10e18;
const long double zetta = 10e21;
const long double yotta = 10e24;
// Common distance scalars
const long double kilometer = 10e3 * meter;
const long double centimeter = 10e-2 * meter;
const long double lightyear = 9460730472580800.0 * meter;
const long double parsec = 96939420213600000.0 * meter;
const long double au = 149597870700.0 * meter;
// Common mass scalars
const long double gram = 1.0e-3 * kilogram;
const long double tonne = 1.00e3 * kilogram;
// Common time scalars
const long double millicsecond = 1.0e-3 * second;
const long double microsecond = 1.00e-6 * second;
const long double nanosecond = 1.0e-9 * second;
const long double hour = 3600.0 * second;
const long double day_ephemerides = 86400.0 * second;
const long double day_sidereal = 86164.0905 * second;
const long double week_ephemerides = 7 * day_ephemerides;
const long double week_sidereal = day_sidereal * 7;
const long double year_sidereal = 365.256363004 * day_ephemerides;
// Derived units
const long double coulomb = ampere * second;
const long double newton = kilogram * (meter / pow(second, 2));
const long double joule = (kilogram * pow(meter, 2)) / pow(second, 2);
const long double volt = joule / coulomb;
// Some very important constants
const long double G = 6.674215e-11 * ((newton * pow(meter, 2)) / pow(kilogram, 2));
const long double vaccuum_permittivity = 8.8541878128e-12 * pow(coulomb, 2) / joule;
const long double g = 9.807;
}
}
#endif | 34.729412 | 93 | 0.615854 | oliver-peoples |
e95dac3823c1707c150ee8017de9f59909f2a2c0 | 24,507 | cpp | C++ | modules/tracktion_engine/model/edit/tracktion_TimecodeDisplayFormat.cpp | jbloit/tracktion_engine | b3fa7d6a3a404f64ae419abdf9c801d672cffb16 | [
"MIT",
"Unlicense"
] | null | null | null | modules/tracktion_engine/model/edit/tracktion_TimecodeDisplayFormat.cpp | jbloit/tracktion_engine | b3fa7d6a3a404f64ae419abdf9c801d672cffb16 | [
"MIT",
"Unlicense"
] | null | null | null | modules/tracktion_engine/model/edit/tracktion_TimecodeDisplayFormat.cpp | jbloit/tracktion_engine | b3fa7d6a3a404f64ae419abdf9c801d672cffb16 | [
"MIT",
"Unlicense"
] | null | null | null | /*
,--. ,--. ,--. ,--.
,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018
'-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software
| | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation
`---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com
Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details.
*/
namespace tracktion_engine
{
TimecodeDuration::TimecodeDuration (std::optional<double> s, std::optional<double> b, int bpb)
: seconds (s), beats (b), beatsPerBar (bpb)
{
}
bool TimecodeDuration::operator== (const TimecodeDuration& o) const
{
if (seconds.has_value() != o.seconds.has_value()) return false;
if (beats.has_value() != o.beats.has_value()) return false;
if (seconds.has_value())
if (*seconds != *o.seconds)
return false;
if (beats.has_value())
if (*beats != *o.beats)
return false;
return true;
}
bool TimecodeDuration::operator!= (const TimecodeDuration& o) const
{
return !(*this == o);
}
TimecodeDuration TimecodeDuration::fromSeconds (Edit& e, double start, double end)
{
return TimecodeDuration (end - start,
e.tempoSequence.timeToBeats (end) - e.tempoSequence.timeToBeats (start),
e.tempoSequence.getTimeSigAt (start).numerator);
}
TimecodeDuration TimecodeDuration::fromSecondsOnly (double duration)
{
return TimecodeDuration (duration, {}, {});
}
TimecodeDuration TimecodeDuration::fromBeatsOnly (double duration, int beatsPerBar)
{
return TimecodeDuration ({}, duration, beatsPerBar);
}
struct TimeAndName
{
double time;
const char* name;
};
static const TimeAndName minSecDivisions[] =
{
{ 0.001, NEEDS_TRANS("1 millisec") },
{ 0.01, NEEDS_TRANS("10 millisecs") },
{ 0.1, NEEDS_TRANS("100 millisecs") },
{ 0.5, NEEDS_TRANS("1/2 second") },
{ 1.0, NEEDS_TRANS("second") },
{ 2.0, NEEDS_TRANS("2 seconds") },
{ 5.0, NEEDS_TRANS("5 seconds") },
{ 10.0, NEEDS_TRANS("10 seconds") },
{ 30.0, NEEDS_TRANS("30 seconds") },
{ 60.0, NEEDS_TRANS("minute") },
{ 5 * 60.0, NEEDS_TRANS("5 minutes") },
{ 15 * 60.0, NEEDS_TRANS("15 minutes") },
{ 30 * 60.0, NEEDS_TRANS("30 minutes") },
{ 60 * 60.0, NEEDS_TRANS("hour") },
{ 5 * 60 * 60.0, NEEDS_TRANS("5 hours") }
};
static const TimeAndName subBeatFractions[] =
{
{ 1.0 / 960, NEEDS_TRANS("1 tick") },
{ 2.0 / 960, NEEDS_TRANS("2 ticks") },
{ 5.0 / 960, NEEDS_TRANS("5 ticks") },
{ 15.0 / 960, NEEDS_TRANS("1/64 beat") },
{ 30.0 / 960, NEEDS_TRANS("1/32 beat") },
{ 60.0 / 960, NEEDS_TRANS("1/16 beat") },
{ 120.0 / 960, NEEDS_TRANS("1/8 beat") },
{ 240.0 / 960, NEEDS_TRANS("1/4 beat") },
{ 480.0 / 960, NEEDS_TRANS("1/2 beat") }
};
static const TimeAndName subBeatFractionsTriplets[] =
{
{ 1.0 / 960, NEEDS_TRANS("1 tick") },
{ 2.0 / 960, NEEDS_TRANS("2 ticks") },
{ 5.0 / 960, NEEDS_TRANS("5 ticks") },
{ 1.0 / 48.0, NEEDS_TRANS("1/48 beat") },
{ 1.0 / 24.0, NEEDS_TRANS("1/24 beat") },
{ 1.0 / 12.0, NEEDS_TRANS("1/12 beat") },
{ 1.0 / 9.0, NEEDS_TRANS("1/9 beat") },
{ 1.0 / 6.0, NEEDS_TRANS("1/6 beat") },
{ 1.0 / 3.0, NEEDS_TRANS("1/3 beat") }
};
static const int subSecDivisionsForType[] = { 1000, Edit::ticksPerQuarterNote, 24, 25, 30 };
static const int barMultiples[] = { 1, 2, 4, 8, 16, 64, 128, 256, 1024, 4096, 16384, 65536 };
// maximum value we can add without shoving a time over into the next 'slot'
static const double nudge = 0.05 / 96000.0;
//==============================================================================
static TimeAndName getMinSecDivisions (int level) noexcept
{
jassert (level >= 0);
return minSecDivisions [std::min (13, level)];
}
juce::String TimecodeSnapType::getDescription (const TempoSetting& tempo, bool isTripletOverride) const
{
if (type == TimecodeType::barsBeats)
{
if (level < 9)
{
bool triplets = isTripletOverride || tempo.getMatchingTimeSig().triplets;
return TRANS (triplets ? subBeatFractionsTriplets[level].name
: subBeatFractions[level].name);
}
if (level == 9) return TRANS("Beat");
if (level == 10) return TRANS("Bar");
return TRANS("33 bars").replace ("33", juce::String (barMultiples[std::min (level, 19) - 10]));
}
if (type == TimecodeType::millisecs)
return TRANS(getMinSecDivisions (level).name);
if (level == 0) return TRANS("1/100 frame");
if (level == 1) return TRANS("Frame");
return TRANS(getMinSecDivisions (level + 2).name);
}
double TimecodeSnapType::getApproxIntervalTime (const TempoSetting& tempo) const
{
return getApproxIntervalTime (tempo, false);
}
double TimecodeSnapType::getApproxIntervalTime (const TempoSetting& tempo, bool isTripletsOverride) const
{
if (type == TimecodeType::barsBeats)
{
const double beatLen = tempo.getApproxBeatLength();
if (level < 9)
{
if (isTripletsOverride || tempo.getMatchingTimeSig().triplets)
return beatLen * subBeatFractionsTriplets [level].time;
return beatLen * subBeatFractions [level].time;
}
if (level == 9)
return beatLen;
auto barLength = tempo.getMatchingTimeSig().numerator * beatLen;
return barLength * barMultiples [level - 10];
}
return getIntervalNonBarsBeats();
}
double TimecodeSnapType::getIntervalNonBarsBeats() const
{
if (type == TimecodeType::millisecs)
return getMinSecDivisions (level).time;
jassert (type != TimecodeType::barsBeats);
auto oneFrame = 1.0 / subSecDivisionsForType[static_cast<int> (type)];
if (level == 0)
return oneFrame * 0.01;
if (level == 1)
return oneFrame;
return getMinSecDivisions (level + 2).time;
}
juce::String TimecodeSnapType::getTimecodeString (double time, const TempoSequence& sequence, bool useStartLabelIfZero) const
{
if (type == TimecodeType::barsBeats)
{
if (time == 0.0 && useStartLabelIfZero)
return TRANS("Bar 1");
auto barsBeats = sequence.timeToBarsBeats (time + nudge);
auto bars = barsBeats.bars + 1;
auto beats = barsBeats.getWholeBeats() + 1;
if (level < 9) return juce::String::formatted ("%d|%d|%03d", bars, beats, (int) (barsBeats.getFractionalBeats() * Edit::ticksPerQuarterNote));
if (level == 9) return juce::String::formatted ("%d|%d", bars, beats);
return TRANS("Bar") + " " + juce::String (bars);
}
if (type == TimecodeType::millisecs)
{
if (time == 0.0 && useStartLabelIfZero)
return "0";
if (level >= 9)
return juce::RelativeTime (time).getDescription();
if (level >= 4)
return TimecodeDisplayFormat::toFullTimecode (time, 0, false);
return TimecodeDisplayFormat::toFullTimecode (time, 1000, false);
}
if (time == 0.0 && useStartLabelIfZero)
return "0";
if (level >= 7)
return juce::RelativeTime (time).getDescription();
if (level >= 2)
return TimecodeDisplayFormat::toFullTimecode (time, 0, false);
return TimecodeDisplayFormat::toFullTimecode (time, subSecDivisionsForType[static_cast<int> (type)], false);
}
int TimecodeSnapType::getOneBarLevel() const noexcept
{
return type == TimecodeType::barsBeats ? 10 : (type == TimecodeType::millisecs ? 4 : 2);
}
double TimecodeSnapType::roundTimeDown (double t, const TempoSequence& sequence) const
{
return roundTime (t, sequence, 0.0);
}
double TimecodeSnapType::roundTimeDown (double t, const TempoSequence& sequence, bool isTripletsOverride) const
{
return roundTime (t, sequence, 0.0, isTripletsOverride);
}
double TimecodeSnapType::roundTimeNearest (double t, const TempoSequence& sequence) const
{
return roundTime (t, sequence, 0.5 - 1.0e-10);
}
double TimecodeSnapType::roundTimeNearest (double t, const TempoSequence& sequence, bool isTripletsOverride) const
{
return roundTime (t, sequence, 0.5 - 1.0e-10, isTripletsOverride);
}
double TimecodeSnapType::roundTimeUp (double t, const TempoSequence& sequence) const
{
return roundTime (t, sequence, 1.0 - 1.0e-10);
}
double TimecodeSnapType::roundTimeUp (double t, const TempoSequence& sequence, bool isTripletsOverride) const
{
return roundTime (t, sequence, 1.0 - 1.0e-10, isTripletsOverride);
}
double TimecodeSnapType::roundTime (double t, const TempoSequence& sequence, double adjustment) const
{
return roundTime (t, sequence, adjustment, sequence.isTripletsAtTime (t));
}
double TimecodeSnapType::roundTime (double t, const TempoSequence& sequence, double adjustment, bool tripletsOverride) const
{
if (type == TimecodeType::barsBeats)
{
auto barsBeats = sequence.timeToBarsBeats (t);
auto& tempo = sequence.getTempoAt (t);
if (level < 9)
{
auto q = tripletsOverride ? subBeatFractionsTriplets[level].time
: subBeatFractions[level].time;
barsBeats.beats = q * std::floor (barsBeats.beats / q + adjustment);
}
else if (level == 9)
{
barsBeats.beats = std::floor (barsBeats.beats + adjustment);
}
else
{
auto barsPlusBeats = barsBeats.bars + barsBeats.beats / tempo.getMatchingTimeSig().numerator;
auto q = barMultiples[level - 10];
barsBeats.bars = q * (int) std::floor (barsPlusBeats / q + adjustment);
barsBeats.beats = 0;
}
return sequence.barsBeatsToTime (barsBeats);
}
auto q = getIntervalNonBarsBeats();
return q * std::floor ((t / q) + adjustment);
}
TimecodeSnapType TimecodeSnapType::getSnapTypeForMaximumSnapLevelOf (double t, const TempoSequence& sequence) const
{
return getSnapTypeForMaximumSnapLevelOf (t, sequence, sequence.isTripletsAtTime (t));
}
TimecodeSnapType TimecodeSnapType::getSnapTypeForMaximumSnapLevelOf (double t, const TempoSequence& sequence, bool isTripletsOverride) const
{
const TimecodeDisplayFormat format (type);
auto numTypes = format.getNumSnapTypes();
int i;
for (i = level; i < numTypes; ++i)
{
TimecodeSnapType snap (type, i);
if (std::abs (t - snap.roundTimeNearest (t, sequence, isTripletsOverride)) > 1.0e-6)
{
--i;
break;
}
}
return format.getSnapType (i);
}
TimecodeSnapType TimecodeSnapType::get1BeatSnapType()
{
return TimecodeSnapType (TimecodeType::barsBeats, 9);
}
//==============================================================================
bool TimecodeDisplayFormat::isBarsBeats() const { return type == TimecodeType::barsBeats; }
bool TimecodeDisplayFormat::isMilliseconds() const { return type == TimecodeType::millisecs; }
bool TimecodeDisplayFormat::isSMPTE() const { return type == TimecodeType::fps24 || type == TimecodeType::fps25 || type == TimecodeType::fps30; }
int TimecodeDisplayFormat::getFPS() const
{
const int defaultFPS = 24;
switch (type)
{
case TimecodeType::millisecs: return defaultFPS;
case TimecodeType::barsBeats: return defaultFPS;
case TimecodeType::fps24: return 24;
case TimecodeType::fps25: return 25;
case TimecodeType::fps30: return 30;
default: jassertfalse; return defaultFPS;
}
}
juce::String TimecodeDisplayFormat::getRoundingDescription() const
{
switch (type)
{
case TimecodeType::millisecs: return TRANS("Snap to nearest round number");
case TimecodeType::barsBeats: return TRANS("Snap to nearest beat or subdivision");
case TimecodeType::fps24:
case TimecodeType::fps25:
case TimecodeType::fps30: return TRANS("Snap to nearest frame");
default: jassertfalse; break;
}
return {};
}
int TimecodeDisplayFormat::getSubSecondDivisions() const
{
return subSecDivisionsForType[static_cast<int> (type)];
}
juce::String TimecodeDisplayFormat::getString (const TempoSequence& tempo, const double time, bool isRelative) const
{
if (type == TimecodeType::barsBeats)
{
TempoSequence::BarsAndBeats barsBeats;
int bars, beats;
double fraction;
if (! isRelative)
{
barsBeats = tempo.timeToBarsBeats (time + nudge);
bars = barsBeats.bars + 1;
beats = barsBeats.getWholeBeats() + 1;
fraction = barsBeats.getFractionalBeats();
}
else if (time < 0)
{
barsBeats = tempo.timeToBarsBeats (time - nudge);
bars = -barsBeats.bars - 1;
beats = (tempo.getTimeSig(0)->numerator - 1) - barsBeats.getWholeBeats();
fraction = 1.0 - barsBeats.getFractionalBeats();
}
else
{
barsBeats = tempo.timeToBarsBeats (time + nudge);
bars = barsBeats.bars + 1;
beats = barsBeats.getWholeBeats() + 1;
fraction = barsBeats.getFractionalBeats();
}
auto s = juce::String::formatted ("%d|%d|%03d", bars, beats, (int) (fraction * Edit::ticksPerQuarterNote));
return time < 0 ? ("-" + s) : s;
}
return TimecodeDisplayFormat::toFullTimecode (time, getSubSecondDivisions());
}
int TimecodeDisplayFormat::getNumParts() const
{
return type == TimecodeType::barsBeats ? 3 : 4;
}
juce::String TimecodeDisplayFormat::getSeparator (int part) const
{
return (type == TimecodeType::barsBeats) ? ","
: ((part == 0 && type == TimecodeType::millisecs) ? "." : ":");
}
int TimecodeDisplayFormat::getMaxCharsInPart (int part, bool canBeNegative) const
{
if (canBeNegative)
{
const char m[5][4] = { { 3, 2, 2, 2 },
{ 3, 2, 4, 4 },
{ 2, 2, 2, 3 },
{ 2, 2, 2, 3 },
{ 2, 2, 2, 3 } };
return m[static_cast<int> (type)][part];
}
const char m[5][4] = { { 3, 2, 2, 2 },
{ 3, 2, 4, 4 },
{ 2, 2, 2, 2 },
{ 2, 2, 2, 2 },
{ 2, 2, 2, 2 } };
return m[static_cast<int> (type)][part];
}
int TimecodeDisplayFormat::getMaxValueOfPart (const TempoSequence& sequence, TimecodeDuration currentTime, int part, bool isRelative) const
{
if (type == TimecodeType::barsBeats && part == 1)
{
if (currentTime.beatsPerBar != 0.0)
return currentTime.beatsPerBar - (isRelative ? 1 : 0);
return sequence.getTimeSigAt (*currentTime.seconds).numerator - (isRelative ? 1 : 0);
}
const short m[5][4] = { { 999, 59, 59, 48 },
{ 959, 99, 999, 9999 },
{ 23, 59, 59, 48 },
{ 24, 59, 59, 48 },
{ 29, 59, 59, 48 } };
return m[static_cast<int> (type)][part];
}
int TimecodeDisplayFormat::getMinValueOfPart (int part, bool isRelative) const
{
return (type == TimecodeType::barsBeats && part > 0 && ! isRelative) ? 1 : 0;
}
static juce::String twoCharString (int n)
{
if (n < 10)
return juce::String::charToString ('0') + (juce::juce_wchar) (n + '0');
return juce::String (n);
}
void TimecodeDisplayFormat::getPartStrings (TimecodeDuration duration,
const TempoSequence& tempo,
bool isRelative,
juce::String results[4]) const
{
if (type == TimecodeType::barsBeats)
{
TempoSequence::BarsAndBeats barsBeats;
if (duration.beats.has_value())
{
auto t = *duration.beats + nudge;
barsBeats.bars = int (t / duration.beatsPerBar);
barsBeats.beats = t - (barsBeats.bars * duration.beatsPerBar);
}
else if (duration.seconds.has_value())
{
auto time = *duration.seconds;
if (time < 0)
{
time = -time;
results[2] = "-";
}
barsBeats = tempo.timeToBarsBeats (time + nudge);
}
{
auto val = (int) (barsBeats.getFractionalBeats() * Edit::ticksPerQuarterNote);
char text[4];
text[0] = (char) ('0' + (val / 100) % 10);
text[1] = (char) ('0' + (val / 10) % 10);
text[2] = (char) ('0' + val % 10);
text[3] = 0;
results[0] = text;
}
for (int part = 1; part < 3; ++part)
{
int val = (part == 1) ? barsBeats.getWholeBeats() : barsBeats.bars;
if (! isRelative)
++val;
results[part] << val;
}
}
else if (duration.seconds.has_value())
{
auto t = std::abs (*duration.seconds) + nudge;
if (type == TimecodeType::millisecs)
{
auto val = ((int) (t * 1000.0)) % 1000;
char text[4];
text[0] = (char) ('0' + (val / 100) % 10);
text[1] = (char) ('0' + (val / 10) % 10);
text[2] = (char) ('0' + val % 10);
text[3] = 0;
results[0] = text;
}
else if (type == TimecodeType::fps24)
{
results[0] = twoCharString (((int) (t * 24)) % 24);
}
else if (type == TimecodeType::fps25)
{
results[0] = twoCharString (((int) (t * 25)) % 25);
}
else
{
jassert (type == TimecodeType::fps30);
results[0] = twoCharString (((int) (t * 30)) % 30);
}
if (*duration.seconds < 0)
results[3] = "-";
auto hours = (int) (t * (1.0 / 3600.0));
results[3] << twoCharString (hours);
auto mins = (((int) t) / 60) % 60;
results[2] = twoCharString (mins);
auto secs = (((int) t) % 60);
results[1] = twoCharString (secs);
}
else
{
jassertfalse;
}
}
TimecodeDuration TimecodeDisplayFormat::getNewTimeWithPartValue (TimecodeDuration time, const TempoSequence& tempo,
int part, int newValue, bool isRelative) const
{
if (type == TimecodeType::barsBeats)
{
if (time.beats.has_value())
{
auto t = *time.beats;
auto bars = int (t / time.beatsPerBar);
auto beats = t - (bars * time.beatsPerBar);
auto ticks = std::fmod (beats, 1.0);
beats = int (beats);
if (part == 2) bars = newValue;
else if (part == 1) beats = newValue;
else if (part == 0) ticks = newValue / double (Edit::ticksPerQuarterNote);
return TimecodeDuration::fromBeatsOnly (bars * time.beatsPerBar + beats + ticks, time.beatsPerBar);
}
else
{
auto t = std::abs (*time.seconds);
TempoSequencePosition pos (tempo);
pos.setTime (t);
auto barsBeats = tempo.timeToBarsBeats (t);
if (part == 0) pos.addBeats ((newValue / (double) Edit::ticksPerQuarterNote) - barsBeats.getFractionalBeats());
else if (part == 1) pos.addBeats ((isRelative ? newValue : (newValue - 1)) - barsBeats.getWholeBeats());
else if (part == 2) pos.addBars ((isRelative ? newValue : (newValue - 1)) - barsBeats.bars);
return TimecodeDuration::fromSecondsOnly (*time.seconds < 0 ? -pos.getTime() : pos.getTime());
}
}
auto t = std::abs (*time.seconds);
auto intT = (int) t;
auto hours = (int) (t / 3600.0);
auto mins = (intT / 60) % 60;
auto secs = (intT % 60);
auto frac = t - intT;
if (part == 0)
{
auto subSecDivs = getSubSecondDivisions();
frac = ((newValue + subSecDivs * 1000) % subSecDivs) / (double) subSecDivs;
}
else if (part == 1)
{
secs = (newValue + 3600) % 60;
}
else if (part == 2)
{
mins = (newValue + 3600) % 60;
}
else if (part == 3)
{
hours = std::max (0, newValue);
}
t = hours * 3600.0 + mins * 60.0 + secs + frac;
return TimecodeDuration::fromSecondsOnly (*time.seconds < 0 ? -t : t);
}
//==============================================================================
juce::String TimecodeDisplayFormat::toFullTimecode (double seconds, int subSecondDivisions, bool showHours)
{
juce::String result = (seconds < 0) ? "-" : "";
auto absSecs = std::abs (seconds);
if (showHours || (absSecs >= 60.0 * 60.0))
result += juce::String::formatted ("%02d:%02d:%02d",
(int) (absSecs / (60.0 * 60.0)),
((int) (absSecs / 60.0)) % 60,
((int) absSecs) % 60);
else
result += juce::String::formatted ("%d:%02d",
((int) (absSecs / 60.0)) % 60,
((int) absSecs) % 60);
if (subSecondDivisions > 0)
result += juce::String::formatted (":%0*d",
juce::String (subSecondDivisions - 1).length(),
juce::roundToInt (absSecs * subSecondDivisions) % subSecondDivisions);
return result;
}
//==============================================================================
TimecodeSnapType TimecodeDisplayFormat::getBestSnapType (const TempoSetting& tempo,
double onScreenTimePerPixel,
bool isTripletOverride) const
{
if (type >= TimecodeType::fps24 && (1.0 / getSubSecondDivisions()) / onScreenTimePerPixel > 2)
return TimecodeSnapType (type, 1);
auto numSnapTypes = getNumSnapTypes();
for (int i = 0; i < numSnapTypes; ++i)
{
TimecodeSnapType snap (type, i);
auto res = snap.getApproxIntervalTime (tempo, isTripletOverride);
auto t = res / onScreenTimePerPixel;
if (t > 12)
return snap;
}
return getSnapType (numSnapTypes);
}
int TimecodeDisplayFormat::getNumSnapTypes() const
{
return type == TimecodeType::millisecs ? 13
: (type == TimecodeType::barsBeats ? 19 : 15);
}
TimecodeSnapType TimecodeDisplayFormat::getSnapType (int index) const
{
return TimecodeSnapType (type, juce::jlimit (0, getNumSnapTypes() - 1, index));
}
//==============================================================================
TimecodeDisplayIterator::TimecodeDisplayIterator (const Edit& edit, double startTime,
TimecodeSnapType minSnapTypeToUse, bool to)
: sequence (edit.tempoSequence),
minSnapType (minSnapTypeToUse),
time (minSnapType.roundTimeDown (startTime, sequence)),
isTripletOverride (to)
{
}
double TimecodeDisplayIterator::next()
{
bool triplets = isTripletOverride || sequence.isTripletsAtTime (time);
auto nextTime = std::max (0.0, minSnapType.roundTimeUp (time + 1.0e-5, sequence, triplets));
if (nextTime <= time)
{
jassertfalse;
nextTime = time + minSnapType.getApproxIntervalTime (*sequence.getTempo (0), triplets);
}
time = nextTime;
currentSnapType = minSnapType.getSnapTypeForMaximumSnapLevelOf (time, sequence, triplets);
return time;
}
juce::String TimecodeDisplayIterator::getTimecodeAsString() const
{
return currentSnapType.getTimecodeString (time, sequence, true);
}
bool TimecodeDisplayIterator::isOneBarOrGreater() const noexcept
{
return currentSnapType.getLevel() >= currentSnapType.getOneBarLevel();
}
}
| 32.895302 | 155 | 0.555474 | jbloit |
e966565428d01c328a1134e44ab0200556f7c84c | 7,080 | cpp | C++ | Sources/Menu.cpp | AnalogMan151/Re-Decode | 7ce4153e00fe234a0347f48c1ebc99c6c7578e02 | [
"Unlicense"
] | 4 | 2021-08-17T18:03:02.000Z | 2021-11-06T21:39:05.000Z | Sources/Menu.cpp | AnalogMan151/Re-Decode | 7ce4153e00fe234a0347f48c1ebc99c6c7578e02 | [
"Unlicense"
] | 1 | 2021-08-11T05:10:38.000Z | 2021-08-11T05:14:43.000Z | Sources/Menu.cpp | AnalogMan151/Re-Decode | 7ce4153e00fe234a0347f48c1ebc99c6c7578e02 | [
"Unlicense"
] | 1 | 2021-08-15T02:56:15.000Z | 2021-08-15T02:56:15.000Z | #include "Menu.hpp"
#include "Cheats.hpp"
#include "Unicode.h"
#include "Helpers/HotkeyHelpers.hpp"
using namespace CTRPluginFramework;
extern std::vector<std::string> approvedCodes;
// Entries with keyboard input made global so keyboard function can enable entry upon input
MenuEntry *g_setMoneyFunc = Entry("Freeze Bits [KB]", setMoneyFunc, setMoneyKBFunc);
MenuEntry *g_setRunSpeedFunc = Entry("Change Run Speed [KB]", setRunSpeedFunc, setRunSpeedKBFunc);
MenuEntry *g_setTrainingMultiFunc = Entry("Set Training Multiplier [KB]", setTrainingMultiFunc, setTrainingMultiKBFunc);
MenuEntry *g_setAnimationSpeedFunc = Entry("Change Game Animation Speed [KB]", "Time passes as normal, only animations are sped up", setAnimationSpeedFunc, setAnimationSpeedKBFunc);
bool IsOnWhiteList(void)
{
FriendKey FKey;
u64 FCode;
if (approvedCodes.size() == 0)
return true;
frdInit();
FRD_GetMyFriendKey(&FKey);
FRD_PrincipalIdToFriendCode(FKey.principalId, &FCode);
std::string FriendCode = std::string(12 - std::to_string(FCode).length(), '0') + std::to_string(FCode);
return !(std::find(approvedCodes.begin(), approvedCodes.end(), FriendCode) == approvedCodes.end());
}
void InitMenu(PluginMenu &Menu)
{
// Check if Friend Code is on whitelist (testing use only) and that game Title ID matches
if (!IsOnWhiteList() || static_cast<u32>(Process::GetTitleID()) != 0x000AFC00)
{
Menu += Entry("Access Denied: Unauthorized User", nullptr);
return;
}
// Quality of life cheats
MenuFolder *QoL = new MenuFolder("Convenience Patches");
*QoL += g_setMoneyFunc;
if (System::IsNew3DS())
{
*QoL += Entry("Map C-Stick to D-Pad", mapDPAD2CStickFunc);
*QoL += Entry("Enable 60 FPS (See Note)", "Unstable, may crash during video scenes. Need to have 3DS clockspeed set to 804MHz & L2 Cache enabled.", enable60FPSFunc);
}
*QoL += Entry("Increase Render Distance x4", enhanceRenderDistance);
*QoL += g_setRunSpeedFunc;
*QoL += g_setTrainingMultiFunc;
*QoL += Entry("Max Card Quantities", "Only changes amount for discovered cards", nullptr, maxKnownCards);
*QoL += Entry("Hack Decode Level", nullptr, setDecodeLVLFunc);
Menu += QoL;
// Battle cheats
MenuFolder *Battle = new MenuFolder("Battle Hacks");
*Battle += Entry("Infinite HP", infHPBattleFunc);
*Battle += Entry("Infinite MP", infMPBattleFunc);
*Battle += Entry("Infinite SP", infSPBattleFunc);
*Battle += EntryWithHotkey("Enemy Instant Death (See Note)", "Okay, what was that??\nDeath.\nWhat kind?\nInstant.\nThere was no sound, he just died!", instantEnemyDeathFunc, { Hotkey(Key::L + Key::R, "Instant Death") });
*Battle += Entry("One-Hit KO", oneHitKOFunc);
*Battle += Entry("Enemy has no MP", enemyNoMPFunc);
Menu += Battle;
// Stat altering cheats
MenuFolder *Stats = new MenuFolder("Stat Adjustments");
*Stats += Entry("Set Max HP", nullptr, setMaxHPFunc);
*Stats += Entry("Set Max MP", nullptr, setMaxMPFunc);
*Stats += Entry("Set ATK", nullptr, setATKFunc);
*Stats += Entry("Set DEF", nullptr, setDEFFunc);
*Stats += Entry("Set SPD", nullptr, setSPDFunc);
*Stats += Entry("Set BRN", nullptr, setBRNFunc);
Menu += Stats;
// Care helping cheats
MenuFolder *Care = new MenuFolder("Care Modifiers");
*Care += Entry("Freeze Digimon Aging", "Also stops digivolution", freezeDigimonFunc);
*Care += Entry("Freeze Sleep", freezeSleepFunc);
*Care += Entry("Freeze Hunger & Fullness", freezeHungerFunc);
*Care += Entry("Freeze Poop", freezePoopFunc);
*Care += Entry("Never Fatigued", neverExhaustedFunc);
*Care += Entry("Never Sick/Injured", neverUnhealthyFunc);
*Care += Entry("Max Lives", maxLivesFunc);
*Care += EntryWithHotkey("Instant Digivolve (See Note)","Won't do anything if no digivolve requirements are met", instantDigivolveFunc, { Hotkey(Key::L + Key::R + Key::A, "Instant Digivolve") });
*Care += Entry("Set Happiness Meter", nullptr, setHappinessMeterFunc);
*Care += Entry("Set Discipline Meter", nullptr, setDisciplineMeterFunc);
*Care += Entry("Set Poop Meter", nullptr, setPoopMeterFunc);
*Care += Entry("Set Weight", nullptr, setWeightFunc);
*Care += Entry("Set Nature", nullptr, setNatureFunc);
*Care += Entry("View/Edit Care Mistakes", nullptr, setCareMistakeFunc);
*Care += Entry("Kill Partner Digimon", nullptr, killDigimonFunc);
Menu += Care;
// Collectable / unlockable things
MenuFolder *Unlock = new MenuFolder("Unlockables");
*Unlock += Entry("Complete Evolution List", nullptr, unlockFieldGuideFunc);
*Unlock += Entry("Unlock All Accessories", nullptr, unlockAccessoriesFunc);
*Unlock += Entry("Learn All Skills", nullptr, unlockSkillsFunc);
*Unlock += Entry("Reveal All Cards", "This only unlocks the card for viewing, doesn't grant any amount of the card", nullptr, unlockAllCardsFunc);
Menu += Unlock;
// Just for fun / may cause instability
MenuFolder *Fun = new MenuFolder("Fun Mods");
if (System::IsNew3DS())
*Fun += EntryWithHotkey("Alter Camera Zoom (See Note)", controlCameraZoom, { Hotkey(Key::ZL, "Zoom In"), Hotkey(Key::ZR, "Zoom Out") });
else
*Fun += EntryWithHotkey("Alter Camera Zoom (See Note)", controlCameraZoom, { Hotkey(Key::L + Key::R + Key::DPadLeft, "Zoom In"), Hotkey(Key::L + Key::R + Key::DPadRight, "Zoom Out") });
*Fun += g_setAnimationSpeedFunc;
*Fun += Entry("Override Player Character", nullptr, choosePlayerFunc);
*Fun += Entry("Change Player Name", nullptr, setPlayerNameKBFunc);
*Fun += Entry("Change Partner Name", nullptr, setDigiNameKBFunc);
*Fun += Entry("Change Partner", nullptr, replacePartnerDigimonFunc);
Menu += Fun;
// Informative, non-interactive entries to explain additional features
Menu += Entry("Terminal (Hold Start or Select)", "Opens a terminal window of info. \n\n"
"Start opens full terminal. May experience lag while open.\n"
"Select opens mini terminal. Mini terminal is lag free.");
Menu += Entry("Additional Info", "Save often. While tested it's better safe than sorry.\n\n"
"Entries with [KB] can be customized with the keyboard icon.\n\n"
"Some cheats require loading a save, read the message boxes to know which ones.\n\n"
"Cheats with hot keys can have the keys changed with the gamepad icon.");
// A blank, non selectable entry to pad out the menu and hide any always on entries
MenuEntry *spacer = Entry("", nullptr);
spacer->CanBeSelected(false);
spacer->Hide();
// Hidden, non-selectable, always on entry
MenuEntry *term = Entry("", toggleOverlayFunc);
term->CanBeSelected(false);
term->Hide();
term->Enable();
// End of menu
Menu += spacer;
Menu += spacer;
Menu += term;
} | 50.212766 | 224 | 0.663983 | AnalogMan151 |
e96727454184931189840b8f94b60cc2edd2be8e | 2,548 | cpp | C++ | example/example06.cpp | zemasoft/wildcards | 5662507f01f5d0a4ec22f45749214276ed366d1b | [
"BSL-1.0"
] | 39 | 2018-04-17T08:25:12.000Z | 2022-03-08T17:15:50.000Z | example/example06.cpp | zemasoft/wildcards | 5662507f01f5d0a4ec22f45749214276ed366d1b | [
"BSL-1.0"
] | 27 | 2018-04-11T19:38:18.000Z | 2020-06-30T05:38:26.000Z | example/example06.cpp | zemasoft/wildcards | 5662507f01f5d0a4ec22f45749214276ed366d1b | [
"BSL-1.0"
] | 4 | 2019-10-29T23:29:39.000Z | 2021-02-06T10:52:13.000Z | // Copyright Tomas Zeman 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <cmath>
#include <cstring>
#include <iostream>
#include <random>
#include <stdexcept>
#include <vector>
#include "cx/string_view.hpp"
#include "wildcards/match.hpp"
#ifndef __DJGPP__
using std::round;
#endif
enum class nucleobase
{
adenine,
cytosine,
guanine,
thymine
};
nucleobase to_base(int n)
{
switch (n)
{
case 0:
return nucleobase::adenine;
case 1:
return nucleobase::cytosine;
case 2:
return nucleobase::guanine;
case 3:
return nucleobase::thymine;
}
throw std::out_of_range("Input out of range");
}
char to_char(nucleobase base)
{
switch (base)
{
case nucleobase::adenine:
return 'A';
case nucleobase::cytosine:
return 'C';
case nucleobase::guanine:
return 'G';
case nucleobase::thymine:
return 'T';
}
throw std::out_of_range("Input out of range");
}
std::ostream& operator<<(std::ostream& o, const std::vector<nucleobase>& sequence)
{
for (auto base : sequence)
{
o << to_char(base);
}
return o;
}
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cout << "usage: " << argv[0] << " pattern" << std::endl;
return EXIT_SUCCESS;
}
if (argc != 2)
{
std::cerr << "invalid arguments" << std::endl;
return EXIT_FAILURE;
}
auto pattern = cx::make_string_view(argv[1], std::strlen(argv[1]));
auto generator = std::default_random_engine{};
auto n_distribution = std::normal_distribution<double>{5.0, 2.0};
auto u_distribution = std::uniform_int_distribution<int>{0, 3};
auto count = 0;
auto found = 0;
do
{
auto length = n_distribution(generator);
if (length < 0.0 || length > 10.0)
{
continue;
}
auto size = static_cast<std::vector<nucleobase>::size_type>(round(length));
auto sequence = std::vector<nucleobase>{};
sequence.reserve(size);
for (decltype(size) n = 0; n < size; ++n)
{
sequence.push_back(to_base(u_distribution(generator)));
}
if (wildcards::match(sequence, pattern,
[](nucleobase base, char c) { return to_char(base) == c; }))
{
std::cout << sequence << std::endl;
++found;
}
++count;
} while (count < 1000000);
std::cout << "Generated : " << count << std::endl;
std::cout << "Found : " << found << std::endl;
return EXIT_SUCCESS;
}
| 20.222222 | 85 | 0.618132 | zemasoft |
e9688de0a9a818f7c86f3863071ca84f111e3e81 | 1,736 | cpp | C++ | Pods/OLMKit/src/utility.cpp | Adore-Infotech/New-IOS2021 | 01efbc0fa61d9af238a00684db1d4455a790ca63 | [
"Apache-2.0"
] | 1 | 2020-08-09T01:02:27.000Z | 2020-08-09T01:02:27.000Z | Pods/OLMKit/src/utility.cpp | Adore-Infotech/New-IOS2021 | 01efbc0fa61d9af238a00684db1d4455a790ca63 | [
"Apache-2.0"
] | null | null | null | Pods/OLMKit/src/utility.cpp | Adore-Infotech/New-IOS2021 | 01efbc0fa61d9af238a00684db1d4455a790ca63 | [
"Apache-2.0"
] | 1 | 2021-12-04T21:07:09.000Z | 2021-12-04T21:07:09.000Z | /* Copyright 2015 OpenMarket 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 "olm/utility.hh"
#include "olm/crypto.h"
olm::Utility::Utility(
) : last_error(OlmErrorCode::OLM_SUCCESS) {
}
size_t olm::Utility::sha256_length() {
return SHA256_OUTPUT_LENGTH;
}
size_t olm::Utility::sha256(
std::uint8_t const * input, std::size_t input_length,
std::uint8_t * output, std::size_t output_length
) {
if (output_length < sha256_length()) {
last_error = OlmErrorCode::OLM_OUTPUT_BUFFER_TOO_SMALL;
return std::size_t(-1);
}
_olm_crypto_sha256(input, input_length, output);
return SHA256_OUTPUT_LENGTH;
}
size_t olm::Utility::ed25519_verify(
_olm_ed25519_public_key const & key,
std::uint8_t const * message, std::size_t message_length,
std::uint8_t const * signature, std::size_t signature_length
) {
if (signature_length < ED25519_SIGNATURE_LENGTH) {
last_error = OlmErrorCode::OLM_BAD_MESSAGE_MAC;
return std::size_t(-1);
}
if (!_olm_crypto_ed25519_verify(&key, message, message_length, signature)) {
last_error = OlmErrorCode::OLM_BAD_MESSAGE_MAC;
return std::size_t(-1);
}
return std::size_t(0);
}
| 29.931034 | 80 | 0.709677 | Adore-Infotech |
e96bc64beb7e9de54607bfe576b324477d1ce187 | 7,442 | cpp | C++ | DlgSplice.cpp | RDamman/SpeakerWorkshop | 87a38d04197a07a9a7878b3f60d5e0706782163c | [
"OML"
] | 12 | 2019-06-07T10:06:41.000Z | 2021-03-22T22:13:59.000Z | DlgSplice.cpp | RDamman/SpeakerWorkshop | 87a38d04197a07a9a7878b3f60d5e0706782163c | [
"OML"
] | 1 | 2019-05-09T07:38:12.000Z | 2019-07-10T04:20:55.000Z | DlgSplice.cpp | RDamman/SpeakerWorkshop | 87a38d04197a07a9a7878b3f60d5e0706782163c | [
"OML"
] | 3 | 2020-09-08T08:27:33.000Z | 2021-05-13T09:25:43.000Z | // DlgSplice.cpp : implementation file
//
#include "stdafx.h"
#include "audtest.h"
#include "Xform.h"
#include "zFormEdt.h"
#include "DlgSplice.h"
#include "DataSet.h"
#include "Folder.h"
#include "Utils.h"
#include "DlgSelec.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
typedef struct tagSPLICEINFO
{
BOOL bUseBHigh;
BOOL bUseBRes;
DWORD dwPicked;
float fStart;
int nStyle;
} SPLICEINFO;
/////////////////////////////////////////////////////////////////////////////
// CDlgXfSplice dialog
CDlgXfSplice::CDlgXfSplice(CWnd* pParent /*=NULL*/)
: CDialog(CDlgXfSplice::IDD, pParent), m_cStart()
{
EnableAutomation();
//{{AFX_DATA_INIT(CDlgXfSplice)
m_bUseBHigh = FALSE;
m_bUseBRes = FALSE;
//}}AFX_DATA_INIT
{
SPLICEINFO fi;
CAudtestApp *capp = (CAudtestApp *)AfxGetApp();
if ( capp->ReadRegistry( IDS_SPLICEINFO, &fi, sizeof(fi))) // success???
{ // failure, we need to set it
fi.bUseBHigh = FALSE;
fi.bUseBRes = FALSE;
fi.dwPicked = 0;
fi.nStyle = 0;
fi.fStart = 500.0f;
}
m_bUseBHigh= fi.bUseBHigh;
m_bUseBRes = fi.bUseBRes;
m_dwPicked = fi.dwPicked;
m_nStyle = fi.nStyle;
m_fStart = fi.fStart;
}
}
void CDlgXfSplice::OnFinalRelease()
{
// When the last reference for an automation object is released
// OnFinalRelease is called. The base class will automatically
// deletes the object. Add additional cleanup required for your
// object before calling the base class.
CDialog::OnFinalRelease();
}
void CDlgXfSplice::DoDataExchange(CDataExchange* pDX)
{
if ( ! pDX->m_bSaveAndValidate)
{
CString cs(cNullString);
CStatic *cctrl;
if ( m_dwPicked)
{
CNamed *cnam = ((CFolder *)m_pRoot)->GetItem( m_dwPicked);
if ( cnam)
cs = cnam->GetFullName();
}
cctrl = (CStatic *)GetDlgItem( IDC_OTHER);
cctrl->SetWindowText( cs);
cs = cNullString; // reset to nothing
if ( m_dwSource)
{
CNamed *cnam = ((CFolder *)m_pRoot)->GetItem( m_dwSource);
if ( cnam)
cs = cnam->GetFullName();
}
cctrl = (CStatic *)GetDlgItem( IDC_TARGET);
cctrl->SetWindowText( cs);
}
m_cStart.DDX_Value( pDX, m_fStart);
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDlgXfSplice)
DDX_Check(pDX, IDC_USEBHIGH, m_bUseBHigh);
DDX_Check(pDX, IDC_USEBRES, m_bUseBRes);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CDlgXfSplice, CDialog)
//{{AFX_MSG_MAP(CDlgXfSplice)
ON_BN_CLICKED(IDC_BROWSE, OnBrowse)
ON_EN_CHANGE(IDC_START, OnChangeStart)
ON_NOTIFY(UDN_DELTAPOS, IDC_SCRL1, OnDeltaposScrl1)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BEGIN_DISPATCH_MAP(CDlgXfSplice, CDialog)
//{{AFX_DISPATCH_MAP(CDlgXfSplice)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_DISPATCH_MAP
END_DISPATCH_MAP()
// Note: we add support for IID_IDlgXfSplice to support typesafe binding
// from VBA. This IID must match the GUID that is attached to the
// dispinterface in the .ODL file.
// {86088380-A862-11CF-AA03-444553540000}
static const IID IID_IDlgXfSplice =
{ 0x86088380, 0xa862, 0x11cf, { 0xaa, 0x3, 0x44, 0x45, 0x53, 0x54, 0x0, 0x0 } };
BEGIN_INTERFACE_MAP(CDlgXfSplice, CDialog)
INTERFACE_PART(CDlgXfSplice, IID_IDlgXfSplice, Dispatch)
END_INTERFACE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDlgXfSplice message handlers
void CDlgXfSplice::OnBrowse()
{
CDlgSelectObject cdlg;
CDataSet *cdsrc = (CDataSet *)m_pRoot->GetItem( m_dwSource);
cdlg.SetParms( m_pRoot, m_dwPicked, ntDataSet, cdsrc->GetUOM());
if ( IDOK == cdlg.DoModal())
{
UpdateData( TRUE); // update the other fields
m_dwPicked = cdlg.m_dwSelected;
UpdateData( FALSE);
}
}
void CDlgXfSplice::OnChangeStart()
{
CheckRadioButton( IDC_USEENTIRE, IDC_USECUSTOM, IDC_USECUSTOM);
}
BOOL CDlgXfSplice::OnInitDialog()
{
m_cStart.Subclass( this, IDC_START, IDC_SCRL1);
CDialog::OnInitDialog();
CStatic *cctrl;
CString cs;
FullFormatValue( cs, m_fStartMarker, 0);
cctrl = (CStatic *)GetDlgItem( IDC_MARKLOW);
cctrl->SetWindowText( cs);
FullFormatValue( cs, m_fEndMarker, 0);
cctrl = (CStatic *)GetDlgItem( IDC_MARKHIGH);
cctrl->SetWindowText( cs);
CheckRadioButton( IDC_USEENTIRE, IDC_USECUSTOM, IDC_USEENTIRE + m_nStyle);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CDlgXfSplice::OnOK()
{
BOOL bok = FALSE;
m_nStyle = GetCheckedRadioButton( IDC_USEENTIRE, IDC_USECUSTOM) - IDC_USEENTIRE;
if ( m_dwPicked)
{
CNamed *cnam = ((CFolder *)m_pRoot)->GetItem( m_dwPicked);
if ( ntDataSet == cnam->GetType())
{
CDataSet *cdr = (CDataSet *)cnam;
if ( uomFreq== cdr->GetUOM())
bok = TRUE;
}
}
if ( ! bok)
{
AfxMessageBox( IDS_ERR_VALIDDATA);
return; // don't do an OK
}
if (! VerboseUpdateData( TRUE))
return;
{
CAudtestApp *capp = (CAudtestApp *)AfxGetApp();
SPLICEINFO fi;
fi.bUseBHigh= m_bUseBHigh;
fi.bUseBRes = m_bUseBRes;
fi.dwPicked = m_dwPicked;
fi.nStyle = m_nStyle;
fi.fStart = m_fStart;
capp->WriteRegistry( IDS_SPLICEINFO, &fi, sizeof(fi) ); // success???
}
CDialog::OnOK();
}
// -------------------------------------
/////////////////////////////////////////////////////////////////////////////
// CXformSplice
// Splice two datasets.....
/////////////////////////////////////////////////////////////////////////////
CXformSplice::CXformSplice( CObject *cTarget, CObject *cOther) : CXtBinary( cTarget, cOther)
{
}
CXformSplice::~CXformSplice()
{
}
int CXformSplice::DoOperation( CNamed *cdDest ) // xeq xform
{
CDataSet *cdSource = (CDataSet *)FindTargetObject();
CDataSet *cother = (CDataSet *)GetOther();
CDataSet *cdnew = (CDataSet *)cdDest;
CDataSet *pref;
float fmin, fmax;
float fdelta;
int ntotal;
float ffreq;
int i;
CDataSet *plow, *phigh;
float fdata, fphase;
{
CString csform, cres;
cres.Format(_T("%f"), m_fFreq);
csform.Format( IDS_SPLICEDESC, (LPCTSTR )cdSource->GetName(), (LPCTSTR )cother->GetName(), (LPCTSTR )cres);
cdnew->SetDescription( csform);
}
if ( m_bUseBHigh)
{
plow = cdSource; // use our source for the low frequency
phigh = cother;
}
else
{
plow = cother; // use the B dataset for the low frequencies
phigh = cdSource;
}
fmin = plow->Minimum( dataFreq);
fmax = phigh->Maximum( dataFreq);
// which one is the frequency reference
if ( m_bUseBRes)
pref = cother;
else
pref = cdSource;
fdelta = pref->GetDelta();
ntotal = (int )((fmax - fmin) / fdelta);
cdnew->SetUOM( uomFreq);
cdnew->SetDOM( uomDbw); // same as source data???
cdnew->SetStart( fmin);
cdnew->SetDelta( fdelta);
cdnew->SetSize( ntotal);
CreateProgressBar( IDS_STATCALC, 100);
for ( i=0; i<ntotal; i++)
{
if ( 0 == ( i % 100))
ShowProgressBar( (100 * i) / ntotal);
ffreq = fdelta * i + fmin;
if ( ffreq > m_fFreq) // copy the high freq guy
{
fdata = phigh->DataValueAt( ffreq, 1);
fphase = phigh->PhaseValueAt( ffreq);
}
else // copy the low freq guy
{
fdata = plow->DataValueAt( ffreq, 1);
fphase = plow->PhaseValueAt( ffreq);
}
cdnew->SetAbsolute(i, fdata, fphase);
}
CloseProgressBar();
return 0;
}
void CDlgXfSplice::OnDeltaposScrl1(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
m_cStart.ProcessDelta( pNMUpDown->iDelta); // that's it....
*pResult = 0;
}
| 22.214925 | 109 | 0.653319 | RDamman |
e96d1b9c06051a494853369fc5ff430b8dd17da4 | 2,516 | cc | C++ | test/cpp/schema_specific/inverse_attr3.cc | tewk/stepcode | 4925b16978c74335b722efd2c35f878a158de57b | [
"BSD-3-Clause"
] | null | null | null | test/cpp/schema_specific/inverse_attr3.cc | tewk/stepcode | 4925b16978c74335b722efd2c35f878a158de57b | [
"BSD-3-Clause"
] | null | null | null | test/cpp/schema_specific/inverse_attr3.cc | tewk/stepcode | 4925b16978c74335b722efd2c35f878a158de57b | [
"BSD-3-Clause"
] | null | null | null | /** \file inverse_attr3.cc
* Oct 2013
* Test inverse attributes; uses a tiny schema similar to a subset of IFC2x3
*
* This test originally used STEPfile, which didn't work. Fixing STEPfile would have been very difficult, it uses lazyInstMgr now.
*/
#include <sc_cf.h>
extern void SchemaInit( class Registry & );
#include <lazyInstMgr.h>
#include <lazyRefs.h>
#include <sdai.h>
#include <STEPattribute.h>
#include <ExpDict.h>
#include <Registry.h>
#include <errordesc.h>
#include <algorithm>
#include <string>
#include <superInvAttrIter.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <sc_getopt.h>
#include "schema.h"
int main( int argc, char * argv[] ) {
int exitStatus = EXIT_SUCCESS;
if( argc != 2 ) {
std::cerr << "Wrong number of args!" << std::endl;
exit( EXIT_FAILURE );
}
lazyInstMgr lim;
lim.initRegistry( SchemaInit );
lim.openFile( argv[1] );
//find attributes
instanceTypes_t::cvector * insts = lim.getInstances( "window" );
if( !insts || insts->empty() ) {
std::cout << "No window instances found!" << std::endl;
exit( EXIT_FAILURE );
}
SdaiWindow * instance = dynamic_cast< SdaiWindow * >( lim.loadInstance( insts->at( 0 ) ) );
if( !instance ) {
std::cout << "Problem loading instance" << std::endl;
exit( EXIT_FAILURE );
}
std::cout << "instance #" << instance->StepFileId() << std::endl;
SDAI_Application_instance::iAMap_t::value_type v = instance->getInvAttr("isdefinedby");
iAstruct attr = v.second; //instance->getInvAttr(ia);
if( attr.a && attr.a->EntryCount() ) {
std::cout << "Map: found " << attr.a->EntryCount() << " inverse references." << std::endl;
} else {
std::cout << "Map: found no inverse references. ias " << (void *) &(v.second) << ", ia " << (void*) v.first << std::endl;
exitStatus = EXIT_FAILURE;
}
EntityAggregate * aggr = instance->isdefinedby_(); //should be filled in when the file is loaded? not sure how to do it using STEPfile...
if( attr.a != aggr ) {
std::cout << "Error! got different EntityAggregate's when using map vs method" << std::endl;
exitStatus = EXIT_FAILURE;
}
if( aggr && aggr->EntryCount() ) {
std::cout << "Found " << aggr->EntryCount() << " inverse references." << std::endl;
} else {
std::cout << "inverse attr is not defined" << std::endl;
exitStatus = EXIT_FAILURE;
}
exit( exitStatus );
}
| 34.465753 | 141 | 0.618045 | tewk |
e96dc274337ac690d36dd61cd328fa6be1a14a0c | 2,192 | cpp | C++ | dijkstra.cpp | qq372505855/shortest_path_algorithms | b32c1c3848d286a5903fed5608b76185c36c5335 | [
"Apache-2.0"
] | 1 | 2019-03-13T15:43:57.000Z | 2019-03-13T15:43:57.000Z | dijkstra.cpp | qq372505855/shortest_path_algorithms | b32c1c3848d286a5903fed5608b76185c36c5335 | [
"Apache-2.0"
] | null | null | null | dijkstra.cpp | qq372505855/shortest_path_algorithms | b32c1c3848d286a5903fed5608b76185c36c5335 | [
"Apache-2.0"
] | null | null | null | /******************************************************************
* FileName : dijkstra.cpp
* Author : Lishuxiang
* E-mail : lishuxiang@cug.edu.cn
* Time : Wed 16 Jan 2019 07:29:14 PM CST
* Function :
******************************************************************/
#include<iostream>
#include<string.h>
#include<stdio.h>
#include<algorithm>
#include<vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::make_heap;
using std::pop_heap;
using std::sort_heap;
#define MAX_ELE 100
#define INFINITE 65535
int main(void)
{
int vertexNum = 0, edgeNum = 0;
cout << "顶点数:";
cin >> vertexNum; // 输入结点数与边数
cout << "边数:";
cin >> edgeNum;
int edgeMatrix[vertexNum][vertexNum];
for (int i = 0; i < vertexNum; i++) { //初始化邻接矩阵
for (int j = 0; j < vertexNum; j++) {
edgeMatrix[i][j] = i == j ? 0 : INFINITE; //对角线权值为0 其余为无穷大
}
}
cout << "边数据(边起点 边终点 权值):" << endl;
for (int i = 0; i < edgeNum; i++) {
int va, vb, value;
cin >> va >> vb >> value; //a点到b点的边的权值为value
edgeMatrix[va][vb] = value;
}
int s = 0;
int e = 0;
int dis[vertexNum]; //起点到各个结点的距离
bool vis[vertexNum]; //访问标志
int pre[vertexNum]; //前驱结点用于倒序输出终点到起点的最短路径
for (int i = 0; i < vertexNum; i++) {
dis[i] = INFINITE;
vis[i] = false;
pre[i] = 0;
}
cout << "起点:";
cin >> s;
cout << "终点:";
cin >> e;
int v = s;
dis[s] = 0;
vis[s] = true;
int min_path = 0;
int min = INFINITE;
do {
for (int i = 0; i < vertexNum; i++) { //松弛相邻结点
if (dis[i] > dis[v] + edgeMatrix[v][i]) {
dis[i] = dis[v] + edgeMatrix[v][i];
pre[i] = v; //记录最终松弛前驱结点
}
}
min = INFINITE;
for (int i = 0; i < vertexNum; i++) { //找最小的没被访问过的结点作为下一结点
if (dis[i] <= min && !vis[i]) {
min_path = i;
min = dis[i];
}
}
vis[v] = true;
v = min_path;
} while (min != INFINITE); //能找到下一结点
cout << "起点到各结点的最短路径长度:"<<endl;
for (int i = 0; i < vertexNum; i++) {
if (dis[i] == INFINITE)
cout << "+∞" << " ";
else
cout << dis[i] << " ";
}
cout << endl;
cout << "起点到终点的最短路径:"<<endl;
for (int i = 0; i < vertexNum; i++) {
cout << pre[i] << " ";
}
cout << endl;
return 0;
}
| 23.319149 | 67 | 0.510036 | qq372505855 |
e97804a7949f241570438c7de01ee78ee1239218 | 6,116 | cc | C++ | tests/test_char_set.cc | phisixersai/ppapi | a4d4a5a249d3f369903be3e1fa1a1dfd16de82e0 | [
"BSD-3-Clause"
] | 2 | 2017-09-02T19:08:28.000Z | 2021-11-15T15:15:14.000Z | tests/test_char_set.cc | rise-worlds/ppapi | a4d4a5a249d3f369903be3e1fa1a1dfd16de82e0 | [
"BSD-3-Clause"
] | null | null | null | tests/test_char_set.cc | rise-worlds/ppapi | a4d4a5a249d3f369903be3e1fa1a1dfd16de82e0 | [
"BSD-3-Clause"
] | 1 | 2020-01-16T01:46:31.000Z | 2020-01-16T01:46:31.000Z | // Copyright (c) 2010 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 "ppapi/tests/test_char_set.h"
#include "ppapi/c/dev/ppb_char_set_dev.h"
#include "ppapi/cpp/module.h"
#include "ppapi/tests/testing_instance.h"
REGISTER_TEST_CASE(CharSet);
TestCharSet::TestCharSet(TestingInstance* instance)
: TestCase(instance),
char_set_interface_(NULL) {
}
bool TestCharSet::Init() {
char_set_interface_ = reinterpret_cast<struct PPB_CharSet_Dev const*>(
pp::Module::Get()->GetBrowserInterface(PPB_CHAR_SET_DEV_INTERFACE));
return !!char_set_interface_;
}
void TestCharSet::RunTest() {
RUN_TEST(UTF16ToCharSet);
RUN_TEST(CharSetToUTF16);
}
std::string TestCharSet::TestUTF16ToCharSet() {
// Empty string.
std::vector<uint16_t> utf16;
utf16.push_back(0);
uint32_t utf8result_len = 0;
char* utf8result = char_set_interface_->UTF16ToCharSet(
&utf16[0], 0, "latin1",
PP_CHARSET_CONVERSIONERROR_SUBSTITUTE, &utf8result_len);
ASSERT_TRUE(utf8result);
ASSERT_TRUE(utf8result[0] == 0);
ASSERT_TRUE(utf8result_len == 0);
pp::Module::Get()->core()->MemFree(utf8result);
// Try round-tripping some English & Chinese from UTF-8 through UTF-16
std::string utf8source("Hello, world. \xe4\xbd\xa0\xe5\xa5\xbd");
utf16 = UTF8ToUTF16(utf8source);
utf8result = char_set_interface_->UTF16ToCharSet(
&utf16[0], static_cast<uint32_t>(utf16.size()), "Utf-8",
PP_CHARSET_CONVERSIONERROR_FAIL, &utf8result_len);
ASSERT_TRUE(utf8source == std::string(utf8result, utf8result_len));
pp::Module::Get()->core()->MemFree(utf8result);
// Test an un-encodable character with various modes.
utf16 = UTF8ToUTF16("h\xe4\xbd\xa0i");
// Fail mode.
utf8result_len = 1234; // Test that this gets 0'ed on failure.
utf8result = char_set_interface_->UTF16ToCharSet(
&utf16[0], static_cast<uint32_t>(utf16.size()), "latin1",
PP_CHARSET_CONVERSIONERROR_FAIL, &utf8result_len);
ASSERT_TRUE(utf8result_len == 0);
ASSERT_TRUE(utf8result == NULL);
// Skip mode.
utf8result = char_set_interface_->UTF16ToCharSet(
&utf16[0], static_cast<uint32_t>(utf16.size()), "latin1",
PP_CHARSET_CONVERSIONERROR_SKIP, &utf8result_len);
ASSERT_TRUE(utf8result_len == 2);
ASSERT_TRUE(utf8result[0] == 'h' && utf8result[1] == 'i' &&
utf8result[2] == 0);
pp::Module::Get()->core()->MemFree(utf8result);
// Substitute mode.
utf8result = char_set_interface_->UTF16ToCharSet(
&utf16[0], static_cast<uint32_t>(utf16.size()), "latin1",
PP_CHARSET_CONVERSIONERROR_SUBSTITUTE, &utf8result_len);
ASSERT_TRUE(utf8result_len == 3);
ASSERT_TRUE(utf8result[0] == 'h' && utf8result[1] == '?' &&
utf8result[2] == 'i' && utf8result[3] == 0);
pp::Module::Get()->core()->MemFree(utf8result);
// Try some invalid input encoding.
utf16.clear();
utf16.push_back(0xD800); // High surrogate.
utf16.push_back('A'); // Not a low surrogate.
utf8result = char_set_interface_->UTF16ToCharSet(
&utf16[0], static_cast<uint32_t>(utf16.size()), "latin1",
PP_CHARSET_CONVERSIONERROR_SUBSTITUTE, &utf8result_len);
ASSERT_TRUE(utf8result_len == 2);
ASSERT_TRUE(utf8result[0] == '?' && utf8result[1] == 'A' &&
utf8result[2] == 0);
pp::Module::Get()->core()->MemFree(utf8result);
// Invalid encoding name.
utf8result = char_set_interface_->UTF16ToCharSet(
&utf16[0], static_cast<uint32_t>(utf16.size()), "poopiepants",
PP_CHARSET_CONVERSIONERROR_SUBSTITUTE, &utf8result_len);
ASSERT_TRUE(!utf8result);
ASSERT_TRUE(utf8result_len == 0);
return std::string();
}
std::string TestCharSet::TestCharSetToUTF16() {
// Empty string.
uint32_t utf16result_len;
uint16_t* utf16result = char_set_interface_->CharSetToUTF16(
"", 0, "latin1", PP_CHARSET_CONVERSIONERROR_FAIL, &utf16result_len);
ASSERT_TRUE(utf16result);
ASSERT_TRUE(utf16result_len == 0);
ASSERT_TRUE(utf16result[0] == 0);
// Basic Latin1.
char latin1[] = "H\xef";
utf16result = char_set_interface_->CharSetToUTF16(
latin1, 2, "latin1", PP_CHARSET_CONVERSIONERROR_FAIL, &utf16result_len);
ASSERT_TRUE(utf16result);
ASSERT_TRUE(utf16result_len == 2);
ASSERT_TRUE(utf16result[0] == 'H' && utf16result[1] == 0xef &&
utf16result[2] == 0);
// Invalid input encoding with FAIL.
char badutf8[] = "A\xe4Z";
utf16result = char_set_interface_->CharSetToUTF16(
badutf8, 3, "utf8", PP_CHARSET_CONVERSIONERROR_FAIL, &utf16result_len);
ASSERT_TRUE(!utf16result);
ASSERT_TRUE(utf16result_len == 0);
// Invalid input with SKIP.
utf16result = char_set_interface_->CharSetToUTF16(
badutf8, 3, "utf8", PP_CHARSET_CONVERSIONERROR_SKIP, &utf16result_len);
ASSERT_TRUE(utf16result);
ASSERT_TRUE(utf16result_len == 2);
ASSERT_TRUE(utf16result[0] == 'A' && utf16result[1] == 'Z' &&
utf16result[2] == 0);
// Invalid input with SUBSTITUTE.
utf16result = char_set_interface_->CharSetToUTF16(
badutf8, 3, "utf8", PP_CHARSET_CONVERSIONERROR_SUBSTITUTE,
&utf16result_len);
ASSERT_TRUE(utf16result);
ASSERT_TRUE(utf16result_len == 3);
ASSERT_TRUE(utf16result[0] == 'A' && utf16result[1] == 0xFFFD &&
utf16result[2] == 'Z' && utf16result[3] == 0);
// Invalid encoding name.
utf16result = char_set_interface_->CharSetToUTF16(
badutf8, 3, "poopiepants",
PP_CHARSET_CONVERSIONERROR_SUBSTITUTE, &utf16result_len);
ASSERT_TRUE(!utf16result);
ASSERT_TRUE(utf16result_len == 0);
return std::string();
}
std::vector<uint16_t> TestCharSet::UTF8ToUTF16(const std::string& utf8) {
uint32_t result_len = 0;
uint16_t* result = char_set_interface_->CharSetToUTF16(
utf8.c_str(), static_cast<uint32_t>(utf8.size()),
"utf-8", PP_CHARSET_CONVERSIONERROR_FAIL, &result_len);
std::vector<uint16_t> result_vector;
if (!result)
return result_vector;
result_vector.assign(result, &result[result_len]);
pp::Module::Get()->core()->MemFree(result);
return result_vector;
}
| 36.404762 | 78 | 0.703564 | phisixersai |
e97b7d37f58d3786c3df1ff0223470105375f156 | 17,155 | cpp | C++ | src/algorithm/cherrypicker.cpp | allison-group/indigox | 22657cb3ceb888049cc231e73d18fb2eac099604 | [
"MIT"
] | 7 | 2019-11-24T15:51:37.000Z | 2021-10-02T05:18:42.000Z | src/algorithm/cherrypicker.cpp | allison-group/indigox | 22657cb3ceb888049cc231e73d18fb2eac099604 | [
"MIT"
] | 2 | 2018-12-17T00:55:32.000Z | 2019-10-11T01:47:04.000Z | src/algorithm/cherrypicker.cpp | allison-group/indigox | 22657cb3ceb888049cc231e73d18fb2eac099604 | [
"MIT"
] | 2 | 2019-10-21T01:26:56.000Z | 2019-12-02T00:00:42.000Z | #include <indigox/algorithm/cherrypicker.hpp>
#include <indigox/algorithm/graph/isomorphism.hpp>
#include <indigox/classes/angle.hpp>
#include <indigox/classes/athenaeum.hpp>
#include <indigox/classes/atom.hpp>
#include <indigox/classes/bond.hpp>
#include <indigox/classes/dihedral.hpp>
#include <indigox/classes/molecule.hpp>
#include <indigox/classes/parameterised.hpp>
#include <indigox/graph/condensed.hpp>
#include <indigox/graph/molecular.hpp>
#include <indigox/utils/combinatronics.hpp>
#include <rilib/RI.h>
#include <boost/dynamic_bitset.hpp>
#include <indigo-bondorder/indigo-bondorder.hpp>
#include <algorithm>
#include <map>
#include <vector>
namespace indigox::algorithm {
using CPSet = CherryPicker::Settings;
CherryPicker::CherryPicker(Forcefield &ff) : _ff(ff), bool_parameters(0) {
DefaultSettings();
}
void CherryPicker::DefaultSettings() {
SetBool(CPSet::VertexElement);
SetBool(CPSet::VertexFormalCharge);
SetBool(CPSet::VertexCondensed);
SetBool(CPSet::VertexDegree);
SetBool(CPSet::EdgeBondOrder);
SetBool(CPSet::EdgeDegree);
SetBool(CPSet::AllowDanglingBonds);
SetBool(CPSet::AllowDanglingAngles);
SetBool(CPSet::AllowDanglingDihedrals);
SetBool(CPSet::UseRISubgraphMatching);
SetInt(CPSet::MinimumFragmentSize, 4);
SetInt(CPSet::MaximumFragmentSize, -1);
SetInt(CPSet::ElectronMethod, 2); // Default to FPT for high accuracy and speed
}
bool CherryPicker::GetBool(CPSet param) {
if (param >= CPSet::BoolCount)
throw std::runtime_error("Not a boolean parameter");
return bool_parameters.test((uint8_t)param);
}
void CherryPicker::SetBool(CPSet param) {
if (param >= CPSet::BoolCount)
throw std::runtime_error("Not a boolean parameter");
bool_parameters.set((uint8_t)param);
}
void CherryPicker::UnsetBool(CPSet param) {
if (param >= CPSet::BoolCount)
throw std::runtime_error("Not a boolean parameter");
bool_parameters.reset((uint8_t)param);
}
int32_t CherryPicker::GetInt(CPSet param) {
uint8_t offset = 1 + (uint8_t)CPSet::BoolCount;
if (param <= CPSet::BoolCount || param >= CPSet::IntCount)
throw std::runtime_error("Not an integer parameter");
return int_parameters[(uint8_t)param - offset];
}
void CherryPicker::SetInt(CPSet param, int32_t value) {
uint8_t offset = 1 + (uint8_t)CPSet::BoolCount;
if (param <= CPSet::BoolCount || param >= CPSet::IntCount)
throw std::runtime_error("Not an integer parameter");
int_parameters[(uint8_t)param - offset] = value;
}
bool CherryPicker::AddAthenaeum(Athenaeum &library) {
std::cout << "Adding new Athenaeum..." << std::endl;
if (library.GetForcefield() != _ff) return false;
_libs.push_back(library);
return true;
}
bool CherryPicker::RemoveAthenaeum(Athenaeum &library) {
std::cout << "Removing Athenaeum..." << std::endl;
auto pos = std::find(_libs.begin(), _libs.end(), library);
if (pos != _libs.end()) _libs.erase(pos);
return pos != _libs.end();
}
using CMGV = graph::CMGVertex;
using CMGE = graph::CMGEdge;
using CMGS = graph::CondensedMolecularGraph;
using U = graph::Undirected;
using GL = graph::GraphLabel;
struct CherryPickerCallback : public CMGCallback {
using GraphType = graph::CondensedMolecularGraph;
using BaseType = CMGCallback;
using CorrespondenceMap = BaseType::CorrespondenceMap;
using VertMasks = eastl::vector_map<CMGV, graph::VertexIsoMask>;
using EdgeMasks = eastl::vector_map<CMGE, graph::EdgeIsoMask>;
CherryPicker &cherrypicker;
GraphType small;
GraphType large;
VertMasks &vmasks_large;
EdgeMasks &emasks_large;
VertMasks vmasks_small;
EdgeMasks emasks_small;
ParamMolecule pmol;
Fragment frag;
bool has_mapping;
CherryPickerCallback(CherryPicker &cp, GraphType &l, VertMasks &vl,
EdgeMasks &el, ParamMolecule &p, Fragment &f,
graph::VertexIsoMask vertmask,
graph::EdgeIsoMask edgemask)
: cherrypicker(cp), small(f.GetGraph()), large(l), vmasks_large(vl),
emasks_large(el), pmol(p), frag(f), has_mapping(false) {
for (CMGV v : small.GetVertices())
vmasks_small.emplace(v, v.GetIsomorphismMask() & vertmask);
for (CMGE e : small.GetEdges())
emasks_small.emplace(e, e.GetIsomorphismMask() & edgemask);
}
bool operator()(const CorrespondenceMap &map) override {
using ConSym = graph::CMGVertex::ContractedSymmetry;
has_mapping = true;
std::vector<graph::MGVertex> frag_v, target_v;
graph::CondensedMolecularGraph G = frag.GetGraph();
graph::MolecularGraph molG = G.GetSuperGraph().GetMolecularGraph();
Molecule fragMol = molG.GetMolecule();
frag_v.reserve(molG.NumVertices());
target_v.reserve(molG.NumVertices());
std::vector<std::pair<size_t, size_t>> regions;
for (auto &frag2target : map) {
frag_v.emplace_back(frag2target.first.GetSource());
target_v.emplace_back(frag2target.second.GetSource());
size_t begin_size = frag_v.size();
ConSym currentSym = ConSym::Hydrogen;
for (auto &cv : frag2target.first.GetCondensedVertices()) {
if (cv.first != currentSym) {
regions.emplace_back(begin_size, frag_v.size());
currentSym = cv.first;
begin_size = frag_v.size();
}
frag_v.emplace_back(cv.second);
}
for (auto &cv : frag2target.second.GetContractedVertices())
target_v.emplace_back(cv);
regions.emplace_back(begin_size, frag_v.size());
}
RegionalPermutation permutation(frag_v.begin(), frag_v.end());
for (std::pair<size_t, size_t> be : regions) {
if (be.second - be.first < 2) continue;
permutation.AddRegion(frag_v.begin() + be.first,
frag_v.begin() + be.second);
}
while (permutation()) {
// Parameterise the atoms
auto patms = frag.GetAtoms();
for (size_t i = 0; i < frag_v.size(); ++i) {
if (std::find(patms.begin(), patms.end(), frag_v[i]) == patms.end())
continue;
ParamAtom patm = pmol.GetAtom(target_v[i].GetAtom());
patm.MappedWith(frag_v[i].GetAtom());
}
// Parameterise the bonds
for (auto bnd : frag.GetBonds()) {
graph::MGVertex v1 = bnd.first, v2 = bnd.second;
if (!cherrypicker.GetBool(CPSet::AllowDanglingBonds) &&
(std::find(patms.begin(), patms.end(), v1) == patms.end() ||
std::find(patms.begin(), patms.end(), v2) == patms.end()))
break;
auto p1 = std::find(frag_v.begin(), frag_v.end(), v1);
auto p2 = std::find(frag_v.begin(), frag_v.end(), v2);
Atom t1 = target_v[std::distance(frag_v.begin(), p1)].GetAtom();
Atom t2 = target_v[std::distance(frag_v.begin(), p2)].GetAtom();
ParamBond pbnd = pmol.GetBond(t1, t2);
pbnd.MappedWith(fragMol.GetBond(v1.GetAtom(), v2.GetAtom()));
}
// Parameterise the angles
for (auto ang : frag.GetAngles()) {
graph::MGVertex v1 = ang.first, v2 = ang.second, v3 = ang.third;
if (!cherrypicker.GetBool(CPSet::AllowDanglingAngles) &&
(std::find(patms.begin(), patms.end(), v1) == patms.end() ||
std::find(patms.begin(), patms.end(), v2) == patms.end() ||
std::find(patms.begin(), patms.end(), v3) == patms.end()))
break;
auto p1 = std::find(frag_v.begin(), frag_v.end(), v1);
auto p2 = std::find(frag_v.begin(), frag_v.end(), v2);
auto p3 = std::find(frag_v.begin(), frag_v.end(), v3);
Atom t1 = target_v[std::distance(frag_v.begin(), p1)].GetAtom();
Atom t2 = target_v[std::distance(frag_v.begin(), p2)].GetAtom();
Atom t3 = target_v[std::distance(frag_v.begin(), p3)].GetAtom();
ParamAngle pang = pmol.GetAngle(t1, t2, t3);
pang.MappedWith(
fragMol.GetAngle(v1.GetAtom(), v2.GetAtom(), v3.GetAtom()));
}
// Parameterise the dihedrals
for (auto dhd : frag.GetDihedrals()) {
graph::MGVertex v1 = dhd.first, v2 = dhd.second, v3 = dhd.third,
v4 = dhd.fourth;
if (!cherrypicker.GetBool(CPSet::AllowDanglingDihedrals) &&
(std::find(patms.begin(), patms.end(), v1) == patms.end() ||
std::find(patms.begin(), patms.end(), v2) == patms.end() ||
std::find(patms.begin(), patms.end(), v3) == patms.end() ||
std::find(patms.begin(), patms.end(), v4) == patms.end()))
break;
auto p1 = std::find(frag_v.begin(), frag_v.end(), v1);
auto p2 = std::find(frag_v.begin(), frag_v.end(), v2);
auto p3 = std::find(frag_v.begin(), frag_v.end(), v3);
auto p4 = std::find(frag_v.begin(), frag_v.end(), v4);
Atom t1 = target_v[std::distance(frag_v.begin(), p1)].GetAtom();
Atom t2 = target_v[std::distance(frag_v.begin(), p2)].GetAtom();
Atom t3 = target_v[std::distance(frag_v.begin(), p3)].GetAtom();
Atom t4 = target_v[std::distance(frag_v.begin(), p4)].GetAtom();
ParamDihedral pdhd = pmol.GetDihedral(t1, t2, t3, t4);
pdhd.MappedWith(fragMol.GetDihedral(v1.GetAtom(), v2.GetAtom(),
v3.GetAtom(), v4.GetAtom()));
}
if (!cherrypicker.GetBool(CPSet::ParameteriseFromAllPermutations))
break;
}
return true;
}
bool operator()(const CMGV &vs, const CMGV &vl) override {
return vmasks_small.at(vs) == vmasks_large.at(vl);
}
bool operator()(const CMGE &es, const CMGE &el) override {
return emasks_small.at(es) == emasks_large.at(el);
}
};
struct RICherryPickerMatcher : rilib::MatchListener {
CherryPickerCallback &cb;
RICherryPickerMatcher(CherryPickerCallback &_cb) : cb(_cb) {}
virtual void match(int n, int *small_ids, int *large_ids) {
CherryPickerCallback::CorrespondenceMap cp_map;
for (int i = 0; i < n; ++i) {
cp_map.emplace(cb.small.GetVertices()[small_ids[i]],
cb.large.GetVertices()[large_ids[i]]);
}
cb(cp_map);
}
};
ParamMolecule CherryPicker::ParameteriseMolecule(Molecule &mol) {
std::cout << "Parameterising molecule " << mol.GetName() << "." << std::endl;
if (_libs.empty())
throw std::runtime_error("No Athenaeums to parameterise from");
graph::MolecularGraph G = mol.GetGraph();
if (!G.IsConnected())
throw std::runtime_error("CherryPicker requires a connected molecule");
mol.PerceiveAngles();
mol.PerceiveDihedrals();
if (GetBool(CPSet::CalculateElectrons)) {
mol.PerceiveElectrons(GetInt(CPSet::ElectronMethod), GetBool(CPSet::NoInput));
}
graph::CondensedMolecularGraph CMG = graph::Condense(G);
ParamMolecule pmol(mol);
// Populate the masks
graph::VertexIsoMask vertmask;
vertmask.reset();
if (GetBool(CPSet::VertexElement)) vertmask |= graph::VertexIsoMask(0x7F);
if (GetBool(CPSet::VertexFormalCharge))
vertmask |= graph::VertexIsoMask(0x780);
if (GetBool(CPSet::VertexCondensed)) {
graph::VertexIsoMask tmp;
tmp.from_uint64(0x1C03FFF800);
vertmask |= tmp;
}
if (GetBool(CPSet::VertexCyclic))
vertmask |= graph::VertexIsoMask(0xC000000);
if (GetBool(CPSet::VertexStereochemistry))
vertmask |= graph::VertexIsoMask(0x30000000);
if (GetBool(CPSet::VertexAromaticity))
vertmask |= graph::VertexIsoMask(0x40000000);
if (GetBool(CPSet::VertexDegree)) {
graph::VertexIsoMask tmp;
tmp.from_uint64(0x380000000);
vertmask |= tmp;
}
graph::EdgeIsoMask edgemask;
edgemask.reset();
if (GetBool(CPSet::EdgeBondOrder)) edgemask |= graph::EdgeIsoMask(7);
if (GetBool(CPSet::EdgeStereochemistry)) edgemask |= graph::EdgeIsoMask(24);
if (GetBool(CPSet::EdgeCyclic)) edgemask |= graph::EdgeIsoMask(96);
// if (GetBool(CPSet::EdgeAromaticity)) edgemask |=
// graph::EdgeIsoMask(128);
if (GetBool(CPSet::EdgeDegree)) edgemask |= graph::EdgeIsoMask(16128);
CherryPickerCallback::VertMasks vmasks;
for (CMGV v : CMG.GetVertices())
vmasks.emplace(v, vertmask & v.GetIsomorphismMask());
CherryPickerCallback::EdgeMasks emasks;
for (CMGE e : CMG.GetEdges())
emasks.emplace(e, edgemask & e.GetIsomorphismMask());
std::unique_ptr<rilib::Graph> CMG_ri;
if (GetBool(CPSet::UseRISubgraphMatching))
CMG_ri = CMGToRIGraph(CMG, edgemask, vertmask);
// Run the matching
if (GetInt(CPSet::ChargeRounding) > 3) {
ParamMolecule::charge_rounding = 1;
for (int32_t i = 0; i < GetInt(CPSet::ChargeRounding); ++i)
ParamMolecule::charge_rounding *= 10;
} else {
ParamMolecule::charge_rounding = 1000;
}
for (Athenaeum &lib : _libs) {
for (auto &g_frag : lib.GetFragments()) {
// Initially all fragments are to be searched
boost::dynamic_bitset<> fragments(g_frag.second.size());
fragments.set();
for (size_t pos = 0; pos < fragments.size();
pos = fragments.find_next(pos)) {
Fragment frag = g_frag.second[pos];
if ((int32_t)frag.Size() < GetInt(CPSet::MinimumFragmentSize))
continue;
if (GetInt(CPSet::MaximumFragmentSize) > 0 &&
(int32_t)frag.Size() > GetInt(CPSet::MaximumFragmentSize))
continue;
if (frag.GetGraph().NumVertices() > CMG.NumVertices()) continue;
CherryPickerCallback callback(*this, CMG, vmasks, emasks, pmol, frag,
vertmask, edgemask);
graph::CondensedMolecularGraph FG = frag.GetGraph();
if (!GetBool(CPSet::UseRISubgraphMatching)) {
SubgraphIsomorphisms(FG, CMG, callback);
} else {
std::unique_ptr<rilib::Graph> FG_ri = CMGToRIGraph(FG, edgemask, vertmask);
std::unique_ptr<rilib::AttributeComparator> vert_compare = std::make_unique<Uint64AttrComparator>();
std::unique_ptr<rilib::AttributeComparator> edge_compare = std::make_unique<Uint32AttrComparator>();
std::unique_ptr<rilib::MatchListener> listener = std::make_unique<RICherryPickerMatcher>(callback);
std::unique_ptr<rilib::MaMaConstrFirst> mama = std::make_unique<rilib::MaMaConstrFirst>(*FG_ri);
mama->build(*FG_ri);
long tmp_1, tmp_2, tmp_3;
// run the matching
rilib::match(*CMG_ri, *FG_ri, *mama, *listener,
rilib::MATCH_TYPE::MT_INDSUB, *vert_compare,
*edge_compare, &tmp_1, &tmp_2, &tmp_3);
}
if (!callback.has_mapping) { fragments -= frag.GetSupersets(); }
}
}
using ATSet = Athenaeum::Settings;
pmol.ApplyParameteristion(lib.GetBool(ATSet::SelfConsistent));
}
// Redistribute any excess charge, but only if all atoms have been mapped
bool redistribute = true;
for (ParamAtom patm : pmol.GetAtoms()) {
if (patm.GetMappedCharges().empty()) {
redistribute = false;
break;
}
}
if (redistribute) {
std::vector<ParamAtom> addable_atoms = pmol.GetChargeAddableAtoms();
std::sort(addable_atoms.begin(), addable_atoms.end(), [](ParamAtom& a, ParamAtom& b) { return a.MeanCharge() < b.MeanCharge(); });
double target_charge = mol.GetMolecularCharge();
double total_charge = 0.;
for (Atom atm : mol.GetAtoms()) total_charge += atm.GetPartialCharge();
double to_add = target_charge - total_charge;
uint64_t count = (uint64_t)abs(round(to_add * ParamMolecule::charge_rounding));
if (count && addable_atoms.empty()) {
std::cout << "WARNING: Total charge does not match target charge but no atoms are available for charge redistribution.\n";
return pmol;
}
if (abs(to_add) > 0.1) std::cout << "WARNING: CherryPicker redistributing a large charge imbalance: " << to_add << "\n";
if (to_add < 0) {
double charge_delta = -1. / ParamMolecule::charge_rounding;
for (int64_t pos = 0; count; count -= 1, pos += 1) {
if (pos == (int64_t)addable_atoms.size()) pos = 0;
addable_atoms[pos].AddRedistributedCharge(charge_delta);
}
} else {
double charge_delta = 1. / ParamMolecule::charge_rounding;
for (int64_t pos = addable_atoms.size() - 1; count; count -= 1, pos -= 1) {
if (!pos) pos = addable_atoms.size() - 1;
addable_atoms[pos].AddRedistributedCharge(charge_delta);
}
}
} else std::cout << "WARNING: Not all atoms mapped so charge cannot be redistributed.\n";
std::cout << "Finished parameterising molecule " << mol.GetName() << ".\n" << std::endl;
return pmol;
}
} // namespace indigox::algorithm
| 41.139089 | 136 | 0.626931 | allison-group |
e97e01a296fe1bd4f1039f9d28e0e604a5fbfef6 | 717 | hpp | C++ | src/model/cell.hpp | TiWinDeTea/NinjaClown | fdd48e62466f11036fa0360fad2bcb182d6d3352 | [
"MIT"
] | 2 | 2020-04-10T14:39:00.000Z | 2021-02-11T15:52:16.000Z | src/model/cell.hpp | TiWinDeTea/NinjaClown | fdd48e62466f11036fa0360fad2bcb182d6d3352 | [
"MIT"
] | 2 | 2019-12-17T08:50:20.000Z | 2020-02-03T09:37:56.000Z | src/model/cell.hpp | TiWinDeTea/NinjaClown | fdd48e62466f11036fa0360fad2bcb182d6d3352 | [
"MIT"
] | 1 | 2020-08-19T03:06:52.000Z | 2020-08-19T03:06:52.000Z | #ifndef NINJACLOWN_CELL_HPP
#define NINJACLOWN_CELL_HPP
#include "model/interaction.hpp"
#include "model/types.hpp"
#include "utils/optional.hpp"
namespace model {
namespace cst {
constexpr float cell_width = 1.0f;
constexpr float cell_height = 1.0f;
} // namespace cst
enum class cell_type {
CHASM = 1,
GROUND = 2,
WALL = 3,
};
struct cell {
cell() noexcept = default;
explicit cell(cell_type type) noexcept
: type{type} { }
cell(cell_type type, handle_t interaction_handle) noexcept
: type{type}
, interaction_handle{interaction_handle} { }
cell_type type{cell_type::CHASM};
utils::optional<handle_t> interaction_handle{};
};
} // namespace model
#endif //NINJACLOWN_CELL_HPP
| 18.868421 | 59 | 0.72106 | TiWinDeTea |
e97eb0b9b87acd5875e06333d265a16c11236bed | 15,402 | hpp | C++ | em_unet/src/PyGreentea/evaluation/src_cython/zi/mesh_tmp/tri_mesh.hpp | VCG/psc | 4826c495b89ff77b68a3c0d5c6e3af805db25386 | [
"MIT"
] | 10 | 2018-09-13T17:37:22.000Z | 2020-05-08T16:20:42.000Z | em_unet/src/PyGreentea/evaluation/src_cython/zi/mesh/tri_mesh.hpp | VCG/psc | 4826c495b89ff77b68a3c0d5c6e3af805db25386 | [
"MIT"
] | 1 | 2018-12-02T14:17:39.000Z | 2018-12-02T20:59:26.000Z | em_unet/src/PyGreentea/evaluation/src_cython/zi/mesh/tri_mesh.hpp | VCG/psc | 4826c495b89ff77b68a3c0d5c6e3af805db25386 | [
"MIT"
] | 2 | 2019-03-03T12:06:10.000Z | 2020-04-12T13:23:02.000Z | //
// Copyright (C) 2010 Aleksandar Zlateski <zlateski@mit.edu>
// ----------------------------------------------------------
//
// 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/>.
//
#ifndef ZI_MESH_TRI_MESH_HPP
#define ZI_MESH_TRI_MESH_HPP 1
#include <zi/bits/cstdint.hpp>
#include <zi/bits/hash.hpp>
#include <zi/utility/assert.hpp>
#include <zi/utility/for_each.hpp>
#include <zi/utility/enable_if.hpp>
#include <zi/utility/detail/dummy.hpp>
#include <zi/utility/exception.hpp>
#include <zi/bits/unordered_map.hpp>
#include <vector>
#include <functional>
#include <stdexcept>
#include <iostream>
#include <zi/mesh/detail/tri_mesh_face.hpp>
#include <zi/mesh/detail/tri_mesh_edge.hpp>
namespace zi {
namespace mesh {
namespace detail {
inline uint64_t make_edge( uint32_t x, uint32_t y )
{
return ( static_cast< uint64_t >( ~x ) << 32 ) | ( ~y );
}
inline uint32_t edge_source( uint64_t e )
{
return ( static_cast< uint32_t >( ~e >> 32 ) );
}
inline uint32_t edge_sink( uint64_t e )
{
return ( static_cast< uint32_t >( ~e & 0x7fffffff ) );
}
inline uint64_t edge_inverse( uint64_t e )
{
return ( e >> 32 ) | ( e << 32 );
}
struct tri_mesh_vertex
{
static const uint32_t valid_edge = 0x80000000;
static const uint32_t invalid_edge = 0x7fffffff;
uint32_t face_;
uint32_t open_;
inline tri_mesh_vertex(): face_( 0 ), open_( 0 )
{
}
inline void reset()
{
face_ = open_ = 0;
}
inline bool valid() const
{
return open_ & valid_edge;
}
inline bool on_border() const
{
return open_ != valid_edge;
}
inline uint32_t face() const
{
return face_;
}
inline void validate()
{
open_ |= valid_edge;
}
inline void unvalidate()
{
open_ &= invalid_edge;
}
inline void face( uint32_t f )
{
face_ = f;
validate();
}
};
} // namespace detail
class tri_mesh //: non_copyable
{
public:
typedef detail::tri_mesh_face_impl face_type ;
typedef detail::tri_mesh_vertex vertex_type ;
typedef detail::tri_mesh_edge_impl edge_type ;
friend struct tri_mesh_vertex;
friend struct tri_mesh_face;
friend struct tri_mesh_edge;
private:
std::size_t size_ ;
std::vector < vertex_type > vertices_;
unordered_map< uint64_t, edge_type > edges_ ;
unordered_map< uint32_t, face_type > faces_ ;
uint32_t max_face_;
public:
detail::tri_mesh_face_container faces;
detail::tri_mesh_edge_container edges;
private:
inline void add_edge( uint32_t x, uint32_t y, uint32_t z, uint32_t f )
{
static_cast< void >( z );
ZI_ASSERT( x != y );
ZI_ASSERT( x != z );
ZI_ASSERT( y != z );
const uint64_t e = detail::make_edge( x, y );
ZI_ASSERT_0( edges_.count( e ) );
if ( edges_.count( detail::edge_inverse( e ) ) )
{
--vertices_[ x ].open_;
--vertices_[ y ].open_;
}
else
{
++vertices_[ x ].open_;
++vertices_[ y ].open_;
}
vertices_[ x ].face( f );
edges_.insert( std::make_pair( e, edge_type( f, z ) ) );
}
inline void remove_edge( uint32_t x, uint32_t y, uint32_t f )
{
const uint64_t e = detail::make_edge( x, y );
ZI_ASSERT( edges_.count( e ) );
if ( edges_.count( detail::edge_inverse( e ) ) )
{
++vertices_[ x ].open_;
++vertices_[ y ].open_;
}
else
{
--vertices_[ x ].open_;
--vertices_[ y ].open_;
}
if ( vertices_[ x ].face_ == f )
{
vertices_[ x ].unvalidate();
}
ZI_VERIFY( edges_.erase( e ) );
}
public:
detail::tri_mesh_face_container& get_faces()
{
return faces;
}
const detail::tri_mesh_face_container& get_faces() const
{
return faces;
}
std::vector< vertex_type >& vertices()
{
return vertices_;
}
const std::vector< vertex_type >& vertices() const
{
return vertices_;
}
detail::tri_mesh_edge_container& get_edges()
{
return edges;
}
const detail::tri_mesh_edge_container& get_edges() const
{
return edges;
}
tri_mesh()
: size_( 0 ),
vertices_( 0 ),
edges_(),
faces_(),
max_face_( 0 ),
faces( faces_ ),
edges( edges_ )
{
}
explicit tri_mesh( std::size_t size )
: size_( size ),
vertices_( size ),
edges_(),
faces_(),
max_face_( 0 ),
faces( faces_ ),
edges( edges_ )
{
}
tri_mesh( const tri_mesh& o )
: size_( o.size_ ),
vertices_( o.vertices_ ),
edges_( o.edges_ ),
faces_( o.faces_ ),
max_face_( o.max_face_ ),
faces( faces_ ),
edges( edges_ )
{
};
inline tri_mesh& operator=( const tri_mesh& o )
{
size_ = o.size_;
vertices_ = o.vertices_;
edges_ = o.edges_;
faces_ = o.faces_;
max_face_ = o.max_face_;
faces = detail::tri_mesh_face_container( faces_ );
edges = detail::tri_mesh_edge_container( edges_ );
return *this;
};
void clear( std::size_t s = 0 )
{
if ( s && ( s != size_ ) )
{
size_ = s;
vertices_.resize( s );
}
vertices_.clear();
edges_.clear();
faces_.clear();
max_face_ = 0;
}
void resize( std::size_t s )
{
size_ = s;
vertices_.resize( s );
clear();
}
uint32_t add_face( const uint32_t x, const uint32_t y, const uint32_t z )
{
ZI_ASSERT( x < size_ && y < size_ && z < size_ );
++max_face_;
while ( faces_.count( max_face_ ) )
{
++max_face_;
}
faces_.insert( std::make_pair( max_face_, face_type( x, y, z ) ) );
add_edge( x, y, z, max_face_ );
add_edge( y, z, x, max_face_ );
add_edge( z, x, y, max_face_ );
return max_face_;
}
void remove_face( const uint32_t id )
{
ZI_ASSERT( faces_.count( id ) );
const face_type& f = faces_[ id ];
remove_edge( f.v0(), f.v1(), id );
remove_edge( f.v1(), f.v2(), id );
remove_edge( f.v2(), f.v0(), id );
faces_.erase( id );
}
void remove_face( const face_type& f )
{
remove_face( f.v0(), f.v1(), f.v2() );
}
void remove_face( const uint32_t x, const uint32_t y, const uint32_t z )
{
static_cast< void >( z );
unordered_map< uint64_t, edge_type >::const_iterator it =
edges_.find( detail::make_edge( x, y ) );
ZI_ASSERT( it != edges_.end() );
ZI_ASSERT( it->second.vertex_ == z );
remove_face( it->second.face_ );
ZI_ASSERT( edges_.count( detail::make_edge( x, y ) ) == 0 );
ZI_ASSERT( edges_.count( detail::make_edge( y, z ) ) == 0 );
ZI_ASSERT( edges_.count( detail::make_edge( z, x ) ) == 0 );
}
inline uint64_t vertex_edge( const uint32_t id ) const
{
if ( vertices_[ id ].on_border() )
{
return 0;
}
unordered_map< uint32_t, face_type >::const_iterator it = faces_.find( vertices_[ id ].face_ );
if ( it == faces_.end() )
{
return 0;
}
return it->second.edge_from( id );
}
inline uint32_t across_edge( const uint64_t eid ) const
{
ZI_ASSERT( edges_.count( eid ) );
return edges_.find( eid )->second.vertex_;
}
inline uint32_t across_edge( const uint32_t v0, const uint32_t v1 ) const
{
ZI_ASSERT( edges_.count( detail::make_edge( v0, v1 ) ) );
return edges_.find( detail::make_edge( v0, v1 ) )->second.vertex_;
}
inline uint64_t next_edge( const uint64_t eid ) const
{
unordered_map< uint64_t, edge_type >::const_iterator it = edges_.find( eid );
if ( it == edges_.end() )
{
return 0;
}
return ( ( eid << 32 ) | ( ~it->second.vertex_ ) );
}
inline uint64_t next_around( const uint64_t eid ) const
{
unordered_map< uint64_t, edge_type >::const_iterator it = edges_.find( eid );
return ( it == edges_.end() ) ? 0 : ( ( eid | 0xffffffffLL ) ^ it->second.vertex_ );
}
inline uint64_t next_around_ccw( const uint64_t eid ) const
{
return next_edge( detail::edge_inverse( eid ) );
}
inline uint64_t next_around_cw( const uint64_t eid ) const
{
unordered_map< uint64_t, edge_type >::const_iterator it = edges_.find( eid );
return ( it == edges_.end() ) ? 0 : ( ( eid | 0xffffffffLL ) ^ it->second.vertex_ );
}
inline bool valid_vertex( const uint32_t id ) const
{
return vertices_[ id ].valid() && !vertices_[ id ].on_border();
}
inline bool valid_edge( const uint64_t eid ) const
{
const uint32_t src = detail::edge_source( eid );
const uint32_t snk = detail::edge_sink( eid );
return
vertices_[ src ].valid() &&
vertices_[ snk ].valid() &&
!vertices_[ src ].on_border() &&
!vertices_[ snk ].on_border();
}
inline bool valid_edge( const uint32_t v1, const uint32_t v2 ) const
{
return valid_edge( detail::make_edge( v1, v2 ) );
}
inline uint64_t edge_pair( const uint64_t eid ) const
{
return detail::edge_inverse( eid );
}
inline uint32_t edge_face( const uint64_t eid ) const
{
unordered_map< uint64_t, edge_type >::const_iterator it = edges_.find( eid );
if ( it == edges_.end() )
{
return 0;
}
return it->second.face_;
}
inline uint32_t collapse_edge( uint64_t eind )
{
uint32_t v1 = detail::edge_source( eind );
uint32_t v2 = detail::edge_sink( eind );
ZI_ASSERT( valid_edge( eind ) );
ZI_ASSERT( vertices_[ v1 ].valid() && vertices_[ v2 ].valid() );
uint64_t einv = detail::edge_inverse( eind );
if ( vertices_[ v1 ].on_border() )
{
ZI_ASSERT_0( vertices_[ v2 ].on_border() );
std::swap( v1, v2 );
std::swap( einv, eind );
}
const edge_type& er = edges_.find( eind )->second;
const edge_type& el = edges_.find( einv )->second;
const uint32_t vr = er.vertex_;
const uint32_t vl = el.vertex_;
ZI_ASSERT( vr != vl );
remove_face( er.face_ );
remove_face( el.face_ );
for ( uint32_t v = vr; v != vl; )
{
const uint64_t e = detail::make_edge( v1, v );
const edge_type& edg = edges_.find( e )->second;
const uint32_t nv = edg.vertex_;
remove_face( edg.face_ );
add_face( v2, v, nv );
v = nv;
}
return v2;
}
inline uint32_t collapse_edge( const uint32_t x, const uint32_t y )
{
return collapse_edge( detail::make_edge( x, y ) );
}
inline std::size_t edge_count() const
{
return edges_.size();
}
inline std::size_t face_count() const
{
return faces_.size();
}
inline std::size_t vertex_count() const
{
return vertices_.size();
}
inline std::size_t size() const
{
return size_;
}
inline bool check_rep() const
{
if ( edges_.size() != faces_.size() * 3 )
{
ZI_THROW( "check_rep: extra edges present" );
}
FOR_EACH( it, faces_ )
{
if ( !( vertices_[ it->second.v0() ].valid() &&
vertices_[ it->second.v1() ].valid() &&
vertices_[ it->second.v2() ].valid() ) )
{
ZI_THROW( "check_rep: invalid vertex found" );
}
if ( ( edges_.find( it->second.e0() )->second ).face() != it->first ||
( edges_.find( it->second.e1() )->second ).face() != it->first ||
( edges_.find( it->second.e2() )->second ).face() != it->first )
{
ZI_THROW( "check_rep: edge doesn't link to the correct face" );
}
if ( !( edges_.count( it->second.e0() ) &&
edges_.count( it->second.e1() ) &&
edges_.count( it->second.e2() ) ) )
{
ZI_THROW( "check_rep: face missing an edge" );
}
}
return true;
}
inline bool is_closed_surface() const
{
if ( edges_.size() != faces_.size() * 3 )
{
return false;
}
//FOR_EACH( it, vertices_ )
//{
//if ( !it->valid() || it->on_border() )
//{
//return false;
//}
//}
FOR_EACH( it, edges_ )
{
if ( !edges_.count( detail::edge_inverse( it->first ) ) )
{
return false;
}
if ( vertices_[ detail::edge_source( it->first ) ].on_border() ||
vertices_[ detail::edge_sink ( it->first ) ].on_border() )
{
return false;
}
if ( !vertices_[ detail::edge_source( it->first ) ].valid() ||
!vertices_[ detail::edge_sink ( it->first ) ].valid() )
{
return false;
}
}
FOR_EACH( it, faces_ )
{
if ( !( vertices_[ it->second.v0() ].valid() &&
vertices_[ it->second.v1() ].valid() &&
vertices_[ it->second.v2() ].valid() ) )
{
return false;
}
if ( !( edges_.count( it->second.e0() ) &&
edges_.count( it->second.e1() ) &&
edges_.count( it->second.e2() ) ) )
{
return false;
}
}
return true;
}
void print_faces() const
{
FOR_EACH( it, faces_ )
{
std::cout << "f: "
<< it->second.v0() << ','
<< it->second.v1() << ','
<< it->second.v2() << '\n';
}
}
bool has_edge( const uint32_t v0, const uint32_t v1 ) const
{
return edges_.count( detail::make_edge( v0, v1 ) );
}
std::size_t stripify() const
{
return 0;
}
};
} // namespace mesh
} // namespace zi
#endif
| 24.564593 | 103 | 0.521491 | VCG |
e9835db2e486b5ce0ec02b1f3a4ede9f0aef7401 | 1,797 | cpp | C++ | c++/16-linked-list-appending.cpp | riskycase/pu2-computer | 31c8f3d54c96fa58b5a9cf07315f284af87cc19b | [
"MIT"
] | null | null | null | c++/16-linked-list-appending.cpp | riskycase/pu2-computer | 31c8f3d54c96fa58b5a9cf07315f284af87cc19b | [
"MIT"
] | null | null | null | c++/16-linked-list-appending.cpp | riskycase/pu2-computer | 31c8f3d54c96fa58b5a9cf07315f284af87cc19b | [
"MIT"
] | null | null | null | /**
* Write a program to create a linked list and append elements to it
*/
#include<iostream>
#define endl "\n"
using namespace std;
class linklist {
private:
struct Node {
int data;
Node* link;
}*START;
public:
linklist();
void print();
void append( int item );
void count();
};
linklist::linklist() {
START = NULL;
}
void linklist::print() {
if ( START == NULL )
cout << "Linked list is empty" << endl;
else {
cout << "Linked list contains ";
Node* pointer = START;
while( pointer != NULL ) {
cout << pointer -> data <<" ";
pointer = pointer -> link;
}
cout << endl;
}
}
void linklist::append(int item) {
Node *newNode;
newNode = new Node;
newNode -> data = item;
newNode -> link = NULL;
if( START == NULL ) {
START = newNode;
cout << item << " is inserted as the first node" << endl;
} else {
Node* pointer = START;
while( pointer -> link != NULL )
pointer = pointer -> link;
pointer -> link = newNode;
cout << item << " is inserted" << endl;
}
}
void linklist::count() {
int count = 0;
for( Node* pointer = START; pointer != NULL; pointer = pointer -> link)
count++;
cout << "Number of nodes in the linked list are " << count << "" << endl;
}
int main() {
linklist* LL = new linklist();
LL->print();
LL->append(100);
LL->print();
LL->count();
LL->append(200);
LL->print();
LL->count();
LL->append(300);
LL->print();
LL->count();
return 0;
}
/**
* Output
*
* Linked list is empty
* 100 is inserted as the first node
* Linked list contains 100
* Number of nodes in the linked list are 1
* 200 is inserted
* Linked list contains 100 200
* Number of nodes in the linked list are 2
* 300 is inserted
* Linked list contains 100 200 300
* Number of nodes in the linked list are 3
*/ | 18.525773 | 74 | 0.608236 | riskycase |
e984b50ccf1ee3dc98211bb1a31fbe3896da7813 | 1,315 | cpp | C++ | stringsorting.cpp | ayaankhan98/C-Progamming_basics | 0aba46dfe91986e30151bed54eaa7f66d0486c5e | [
"MIT"
] | null | null | null | stringsorting.cpp | ayaankhan98/C-Progamming_basics | 0aba46dfe91986e30151bed54eaa7f66d0486c5e | [
"MIT"
] | null | null | null | stringsorting.cpp | ayaankhan98/C-Progamming_basics | 0aba46dfe91986e30151bed54eaa7f66d0486c5e | [
"MIT"
] | null | null | null | #include <iostream>
//#include <string>
using namespace std;
class Person
{
private:
string name;
public:
string getname()
{
return name;
}
void setname()
{
cout<<"Enter Name : ";
cin>>name;
}
void printname()
{
cout<<endl<<name;
}
};
int main()
{
void bsort(Person** , int);
Person* perptr[100];
int n=0;
char choice;
do
{
perptr[n] = new Person;
perptr[n]->setname();
n++;
cout<<"Do you want to enter more (Y/N) : ";
cin>>choice;
}
while(choice == 'y' || choice == 'Y');
cout<<endl<<endl<<"Usorted Names : "<<endl;
for(int i=0;i<n;i++)
perptr[i]->printname();
//cout<<endl;
bsort(perptr , n);
cout<<endl<<endl<<"Sorted Names : "<<endl;
for(int i=0;i<n;i++)
perptr[i]->printname();
cout<<endl;
}
void bsort(Person** ptr, int n)
{
void order(Person** , Person**);
int i,j;
for(i=0 ; i<n-1 ; i++)
for(j=i+1 ; j<n ; j++)
order(ptr+i , ptr+j);
}
void order(Person** ptr1, Person** ptr2)
{
if ( (*ptr1)->getname() > (*ptr2)->getname() )
{
Person* temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}
} | 18.013699 | 51 | 0.455513 | ayaankhan98 |
e986516d067e77784b18df31abf4ca29edb96d47 | 10,025 | cpp | C++ | src/arduino/webusb/Adafruit_USBD_WebUSB.cpp | earlephilhower/Adafruit_TinyUSB_Arduino | 2168ccf7c51cbc99bd90104647d1c12844330023 | [
"MIT"
] | 2 | 2021-07-07T10:13:35.000Z | 2021-10-08T06:40:29.000Z | src/arduino/webusb/Adafruit_USBD_WebUSB.cpp | earlephilhower/Adafruit_TinyUSB_Arduino | 2168ccf7c51cbc99bd90104647d1c12844330023 | [
"MIT"
] | null | null | null | src/arduino/webusb/Adafruit_USBD_WebUSB.cpp | earlephilhower/Adafruit_TinyUSB_Arduino | 2168ccf7c51cbc99bd90104647d1c12844330023 | [
"MIT"
] | null | null | null | /*
* The MIT License (MIT)
*
* Copyright (c) 2019 hathach for Adafruit Industries
*
* 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 "tusb_option.h"
#if TUSB_OPT_DEVICE_ENABLED && CFG_TUD_VENDOR
#include "Adafruit_USBD_WebUSB.h"
#include "Arduino.h"
//--------------------------------------------------------------------+
// MACRO TYPEDEF CONSTANT ENUM DECLARATION
//--------------------------------------------------------------------+
#define EPOUT 0x00
#define EPIN 0x80
#define EPSIZE 64
enum { VENDOR_REQUEST_WEBUSB = 1, VENDOR_REQUEST_MICROSOFT = 2 };
static Adafruit_USBD_WebUSB *_webusb_dev = NULL;
//--------------------------------------------------------------------+
// BOS Descriptor
//--------------------------------------------------------------------+
/* Microsoft OS 2.0 registry property descriptor
Per MS requirements
https://msdn.microsoft.com/en-us/library/windows/hardware/hh450799(v=vs.85).aspx
device should create DeviceInterfaceGUIDs. It can be done by driver and
in case of real PnP solution device should expose MS "Microsoft OS 2.0
registry property descriptor". Such descriptor can insert any record
into Windows registry per device/configuration/interface. In our case it
will insert "DeviceInterfaceGUIDs" multistring property.
GUID is freshly generated and should be OK to use.
https://developers.google.com/web/fundamentals/native-hardware/build-for-webusb/
(Section Microsoft OS compatibility descriptors)
*/
#define BOS_TOTAL_LEN \
(TUD_BOS_DESC_LEN + TUD_BOS_WEBUSB_DESC_LEN + TUD_BOS_MICROSOFT_OS_DESC_LEN)
#define MS_OS_20_DESC_LEN 0xB2
// BOS Descriptor is required for webUSB
uint8_t const desc_bos[] = {
// total length, number of device caps
TUD_BOS_DESCRIPTOR(BOS_TOTAL_LEN, 2),
// Vendor Code, iLandingPage
TUD_BOS_WEBUSB_DESCRIPTOR(VENDOR_REQUEST_WEBUSB, 1),
// Microsoft OS 2.0 descriptor
TUD_BOS_MS_OS_20_DESCRIPTOR(MS_OS_20_DESC_LEN, VENDOR_REQUEST_MICROSOFT)};
uint8_t const *tud_descriptor_bos_cb(void) { return desc_bos; }
uint8_t desc_ms_os_20[] = {
// Set header: length, type, windows version, total length
U16_TO_U8S_LE(0x000A), U16_TO_U8S_LE(MS_OS_20_SET_HEADER_DESCRIPTOR),
U32_TO_U8S_LE(0x06030000), U16_TO_U8S_LE(MS_OS_20_DESC_LEN),
// Configuration subset header: length, type, configuration index, reserved,
// configuration total length
U16_TO_U8S_LE(0x0008), U16_TO_U8S_LE(MS_OS_20_SUBSET_HEADER_CONFIGURATION),
0, 0, U16_TO_U8S_LE(MS_OS_20_DESC_LEN - 0x0A),
// Function Subset header: length, type, first interface, reserved, subset
// length
U16_TO_U8S_LE(0x0008), U16_TO_U8S_LE(MS_OS_20_SUBSET_HEADER_FUNCTION),
0 /*itf num*/, 0, U16_TO_U8S_LE(MS_OS_20_DESC_LEN - 0x0A - 0x08),
// MS OS 2.0 Compatible ID descriptor: length, type, compatible ID, sub
// compatible ID
U16_TO_U8S_LE(0x0014), U16_TO_U8S_LE(MS_OS_20_FEATURE_COMPATBLE_ID), 'W',
'I', 'N', 'U', 'S', 'B', 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, // sub-compatible
// MS OS 2.0 Registry property descriptor: length, type
U16_TO_U8S_LE(MS_OS_20_DESC_LEN - 0x0A - 0x08 - 0x08 - 0x14),
U16_TO_U8S_LE(MS_OS_20_FEATURE_REG_PROPERTY), U16_TO_U8S_LE(0x0007),
U16_TO_U8S_LE(0x002A), // wPropertyDataType, wPropertyNameLength and
// PropertyName "DeviceInterfaceGUIDs\0" in UTF-16
'D', 0x00, 'e', 0x00, 'v', 0x00, 'i', 0x00, 'c', 0x00, 'e', 0x00, 'I', 0x00,
'n', 0x00, 't', 0x00, 'e', 0x00, 'r', 0x00, 'f', 0x00, 'a', 0x00, 'c', 0x00,
'e', 0x00, 'G', 0x00, 'U', 0x00, 'I', 0x00, 'D', 0x00, 's', 0x00, 0x00,
0x00,
U16_TO_U8S_LE(0x0050), // wPropertyDataLength
// bPropertyData: “{975F44D9-0D08-43FD-8B3E-127CA8AFFF9D}”.
'{', 0x00, '9', 0x00, '7', 0x00, '5', 0x00, 'F', 0x00, '4', 0x00, '4', 0x00,
'D', 0x00, '9', 0x00, '-', 0x00, '0', 0x00, 'D', 0x00, '0', 0x00, '8', 0x00,
'-', 0x00, '4', 0x00, '3', 0x00, 'F', 0x00, 'D', 0x00, '-', 0x00, '8', 0x00,
'B', 0x00, '3', 0x00, 'E', 0x00, '-', 0x00, '1', 0x00, '2', 0x00, '7', 0x00,
'C', 0x00, 'A', 0x00, '8', 0x00, 'A', 0x00, 'F', 0x00, 'F', 0x00, 'F', 0x00,
'9', 0x00, 'D', 0x00, '}', 0x00, 0x00, 0x00, 0x00, 0x00};
TU_VERIFY_STATIC(sizeof(desc_ms_os_20) == MS_OS_20_DESC_LEN, "Incorrect size");
//------------- IMPLEMENTATION -------------//
Adafruit_USBD_WebUSB::Adafruit_USBD_WebUSB(void) {
_connected = false;
_url = NULL;
_linestate_cb = NULL;
}
bool Adafruit_USBD_WebUSB::begin(void) {
if (!USBDevice.addInterface(*this))
return false;
// WebUSB requires to change USB version from 2.0 to 2.1
USBDevice.setVersion(0x0210);
_webusb_dev = this;
return true;
}
bool Adafruit_USBD_WebUSB::setLandingPage(const void *url) {
_url = (const uint8_t *)url;
return true;
}
void Adafruit_USBD_WebUSB::setLineStateCallback(linestate_callback_t fp) {
_linestate_cb = fp;
}
uint16_t Adafruit_USBD_WebUSB::getInterfaceDescriptor(uint8_t itfnum, uint8_t *buf,
uint16_t bufsize) {
// usb core will automatically update endpoint number
uint8_t desc[] = {TUD_VENDOR_DESCRIPTOR(itfnum, 0, EPOUT, EPIN, 64)};
uint16_t const len = sizeof(desc);
if (bufsize < len)
return 0;
memcpy(buf, desc, len);
// update the bFirstInterface in MS OS 2.0 descriptor
// that is binded to WinUSB driver
desc_ms_os_20[0x0a + 0x08 + 4] = itfnum;
return len;
}
bool Adafruit_USBD_WebUSB::connected(void) {
return tud_vendor_mounted() && _connected;
}
Adafruit_USBD_WebUSB::operator bool() {
// Add an yield to run usb background in case sketch block wait as follows
// while( !webusb ) {}
if (!connected())
yield();
return connected();
}
int Adafruit_USBD_WebUSB::available(void) {
uint32_t count = tud_vendor_available();
// Add an yield to run usb background in case sketch block wait as follows
// while( !webusb.available() ) {}
if (!count)
yield();
return count;
}
int Adafruit_USBD_WebUSB::read(void) {
uint8_t ch;
return tud_vendor_read(&ch, 1) ? (int)ch : -1;
}
size_t Adafruit_USBD_WebUSB::write(uint8_t b) { return this->write(&b, 1); }
size_t Adafruit_USBD_WebUSB::write(const uint8_t *buffer, size_t size) {
size_t remain = size;
while (remain && _connected) {
size_t wrcount = tud_vendor_write(buffer, remain);
remain -= wrcount;
buffer += wrcount;
// Write FIFO is full, run usb background to flush
if (remain)
yield();
}
return size - remain;
}
int Adafruit_USBD_WebUSB::peek(void) {
uint8_t ch;
return tud_vendor_peek(&ch) ? (int)ch : -1;
}
void Adafruit_USBD_WebUSB::flush(void) {}
extern "C" {
// Invoked when a control transfer occurred on an interface of this class
// Driver response accordingly to the request and the transfer stage (setup/data/ack)
// return false to stall control endpoint (e.g unsupported request)
bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request)
{
if (!_webusb_dev)
return false;
// nothing to with DATA & ACK stage
if (stage != CONTROL_STAGE_SETUP) return true;
switch ( request->bmRequestType_bit.type )
{
case TUSB_REQ_TYPE_VENDOR:
switch ( request->bRequest )
{
case VENDOR_REQUEST_WEBUSB:
// match vendor request in BOS descriptor
// Get landing page url
if ( !_webusb_dev->_url )
return false;
return tud_control_xfer(rhport, request, (void*) _webusb_dev->_url,
_webusb_dev->_url[0]);
case VENDOR_REQUEST_MICROSOFT:
if ( request->wIndex == 7 )
{
// Get Microsoft OS 2.0 compatible descriptor
uint16_t total_len;
memcpy(&total_len, desc_ms_os_20 + 8, 2);
return tud_control_xfer(rhport, request, (void*) desc_ms_os_20,
total_len);
}
else
{
return false;
}
default: break;
}
break;
case TUSB_REQ_TYPE_CLASS:
if (request->bRequest == 0x22)
{
// Webserial simulate the CDC_REQUEST_SET_CONTROL_LINE_STATE (0x22) to
// connect and disconnect.
_webusb_dev->_connected = (request->wValue != 0);
// response with status OK
tud_control_status(rhport, request);
// invoked callback if any (TODO should be done at ACK stage)
if ( _webusb_dev->_linestate_cb )
_webusb_dev->_linestate_cb(_webusb_dev->_connected);
return true;
}
break;
default:
// stall unknown request
return false;
}
return true;
}
// Invoked when DATA Stage of VENDOR's request is complete
bool tud_vendor_control_complete_cb(uint8_t rhport, tusb_control_request_t const *request) {
(void)rhport;
(void)request;
// nothing to do
return true;
}
}
#endif // TUSB_OPT_DEVICE_ENABLED
| 33.305648 | 102 | 0.659052 | earlephilhower |
e9870c315b6c6259000d88f6df1b2655669312e6 | 2,063 | cpp | C++ | software/src/8.0/src/frontend/MStermio.cpp | c-kuhlman/vision | 46b25f7c0da703c059acc8f0a2eac1d5badf9f6d | [
"BSD-3-Clause"
] | 30 | 2016-10-07T15:23:35.000Z | 2020-03-25T20:01:30.000Z | software/src/8.0/src/frontend/MStermio.cpp | VisionAerie/vision | e40c39e3abc49b0e2c9623204c54b900c4333f29 | [
"BSD-3-Clause"
] | 30 | 2016-10-31T19:48:08.000Z | 2021-04-28T01:31:53.000Z | software/src/8.0/src/frontend/MStermio.cpp | c-kuhlman/vision | 46b25f7c0da703c059acc8f0a2eac1d5badf9f6d | [
"BSD-3-Clause"
] | 15 | 2016-10-07T16:44:13.000Z | 2021-06-21T18:47:55.000Z | /***** Machine Specific Terminal IO *****/
#include "Vk.h"
#include "V_VString.h"
#include "stdcurses.h"
#include "SItermio.h"
/*******************************************
***** CURSES compatibility routines *****
*******************************************/
PublicVarDef int STD_hasInsertDeleteLine = FALSE;
PublicVarDef int STD_doNotUseNodelay = FALSE;
PublicVarDef int STD_delwinDoesNotRefresh = TRUE;
#if defined(__hp9000s700)
PublicFnDef int STD_delwin (WINDOW *win)
{
int result;
result = delwin (win);
clearok (curscr, TRUE);
return result;
}
#endif
PublicFnDef void STD_checkTerminalCapabilities() {
static char entry[1024];
static int entryIsntValid = TRUE;
char *areap, area[1024];
if (entryIsntValid)
{
char const *term = getenv ("TERM");
VString iTerm (term ? term : "vt100", false);
entryIsntValid = tgetent (entry, iTerm.storage ()) != 1;
}
char dl[] = "dl"; char DL[] = "DL";
char al[] = "al"; char AL[] = "AL";
areap = area;
if( ((NULL != tgetstr(dl,&areap)) || (NULL != tgetstr(DL,&areap))) &&
((NULL != tgetstr(al,&areap)) || (NULL != tgetstr(AL,&areap))) )
STD_hasInsertDeleteLine = TRUE;
else
STD_hasInsertDeleteLine = FALSE;
}
PublicFnDef void
STD_cleanupTerminal()
{
}
#if 0 // defined(sun)
#include <sgtty.h>
PrivateVarDef struct sgttyb ShellModeTerminalState,
ProgramModeTerminalState;
PublicFnDef int
SUN_def_shell_mode ()
{
gtty (0, &ShellModeTerminalState);
}
PublicFnDef int
SUN_reset_shell_mode ()
{
stty (0, &ShellModeTerminalState);
}
PublicFnDef int
SUN_def_prog_mode ()
{
gtty (0, &ProgramModeTerminalState);
}
PublicFnDef int
SUN_reset_prog_mode ()
{
stty (0, &ProgramModeTerminalState);
}
PublicFnDef int
SUN_initscr ()
{
SUN_def_shell_mode ();
initscr ();
}
#endif
#if defined (sun)
PublicFnDef int STD_checkInputStream()
{
STD_doNotUseNodelay = TRUE;
return(FALSE);
}
#else
PublicFnDef int STD_checkInputStream()
{
return(FALSE);
}
#endif /* sun */
| 18.419643 | 73 | 0.631604 | c-kuhlman |
e988cf61dd86bf57054dfa5c2fcc0fe7c7fb9ef0 | 1,557 | cpp | C++ | tracking_allocatated_memory.cpp | vsoftco/snippets | 467520e285f9c83024416f050a5357bf659f4860 | [
"MIT"
] | 13 | 2015-04-21T09:09:59.000Z | 2021-11-27T11:00:40.000Z | tracking_allocatated_memory.cpp | vsoftco/snippets | 467520e285f9c83024416f050a5357bf659f4860 | [
"MIT"
] | null | null | null | tracking_allocatated_memory.cpp | vsoftco/snippets | 467520e285f9c83024416f050a5357bf659f4860 | [
"MIT"
] | 3 | 2019-08-09T09:29:59.000Z | 2021-01-09T08:52:11.000Z | // Keeping track of memory allocation
// http://stackoverflow.com/q/29820626/3093378 (question)
// http://stackoverflow.com/a/29821408/3093378 (my answer)
#include <iostream>
#include <map>
std::map<void*, std::size_t> memory; // globally allocated memory map
struct tag {}; // tag for placement new's so we don't overload the global ones
void* operator new(std::size_t size, const tag&) {
void* addr = malloc(size);
memory[addr] = size;
return addr;
}
void* operator new[](std::size_t size, const tag&) // for arrays
{
return operator new(size, tag());
}
void operator delete(void* p) noexcept {
memory.erase(p);
free(p);
}
void operator delete[](void* p) noexcept // for arrays
{
operator delete(p);
}
void display_memory() {
std::cout << "Allocated heap memory: " << std::endl;
for (auto&& elem : memory) {
std::cout << "\tADDR: " << elem.first << " "
<< "SIZE: " << elem.second << std::endl;
}
}
bool is_allocated(void* p) { return (memory.find(p) != memory.end()); }
int main() {
int* p = new (tag()) int[10];
char* c = new (tag()) char;
// test if p is allocated
std::cout << std::boolalpha << "Allocated: " << is_allocated(p)
<< std::endl;
// display the allocated memory
display_memory();
// remove p
delete[] p;
// test again if p is allocated
std::cout << std::boolalpha << "Allocated: " << is_allocated(p)
<< std::endl;
display_memory();
// remove c
delete c;
display_memory();
}
| 23.238806 | 78 | 0.595376 | vsoftco |
e9891e5a44a17a1e41c1fb1f5139c466c8db2360 | 989 | cpp | C++ | module/Utils.cpp | eXo-MTA/GPS-Module | 60627b561d42cb17d898387a67665260c78e3fcf | [
"MIT"
] | 15 | 2019-11-14T00:20:17.000Z | 2022-01-13T14:37:51.000Z | module/Utils.cpp | eXo-MTA/GPS-Module | 60627b561d42cb17d898387a67665260c78e3fcf | [
"MIT"
] | 6 | 2017-04-27T19:16:02.000Z | 2017-06-23T01:26:17.000Z | module/Utils.cpp | eXo-MTA/GPS-Module | 60627b561d42cb17d898387a67665260c78e3fcf | [
"MIT"
] | 3 | 2021-02-17T18:17:02.000Z | 2021-11-12T00:29:29.000Z | #include "Utils.h"
void Utils::GetNodeNeighbors(lua_State* luaVM, pathfind::GraphNode* startNode, int depth)
{
std::size_t index = 1;
for (const auto& pair : startNode->edges)
{
pathfind::GraphNode* edgeNode = pair.first;
lua_pushnumber(luaVM, index++);
lua_newtable(luaVM);
lua_pushnumber(luaVM, 1);
lua_pushnumber(luaVM, edgeNode->id);
lua_settable(luaVM, -3);
lua_pushnumber(luaVM, 2);
lua_pushnumber(luaVM, edgeNode->position.GetX());
lua_settable(luaVM, -3);
lua_pushnumber(luaVM, 3);
lua_pushnumber(luaVM, edgeNode->position.GetY());
lua_settable(luaVM, -3);
lua_pushnumber(luaVM, 4);
lua_pushnumber(luaVM, edgeNode->position.GetZ());
lua_settable(luaVM, -3);
lua_pushnumber(luaVM, 5);
if (depth > 0) {
lua_newtable(luaVM);
GetNodeNeighbors(luaVM, edgeNode, depth - 1);
}
else {
lua_pushboolean(luaVM, false);
}
lua_settable(luaVM, -3);
lua_settable(luaVM, -3);
}
} | 24.121951 | 89 | 0.656218 | eXo-MTA |
e989c17db87fc40f1ced81df5952d8874a1add6d | 13,217 | cpp | C++ | RenderOverlays/HighlightEffects.cpp | pocketgems/XLE2 | 82771e9ab1fc3b12927f1687bbe05d4f7dce8765 | [
"MIT"
] | 3 | 2018-05-17T08:39:39.000Z | 2020-12-09T13:20:26.000Z | RenderOverlays/HighlightEffects.cpp | pocketgems/XLE2 | 82771e9ab1fc3b12927f1687bbe05d4f7dce8765 | [
"MIT"
] | null | null | null | RenderOverlays/HighlightEffects.cpp | pocketgems/XLE2 | 82771e9ab1fc3b12927f1687bbe05d4f7dce8765 | [
"MIT"
] | 1 | 2021-11-14T08:50:15.000Z | 2021-11-14T08:50:15.000Z | // Copyright 2015 XLGAMES Inc.
//
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#include "HighlightEffects.h"
#include "../../RenderCore/Metal/DeviceContext.h"
#include "../../RenderCore/Metal/Shader.h"
#include "../../RenderCore/Metal/TextureView.h"
#include "../../RenderCore/Metal/Resource.h"
#include "../../RenderCore/Metal/ObjectFactory.h"
#include "../../RenderCore/Metal/InputLayout.h"
#include "../../RenderCore/Metal/Resource.h"
#include "../../RenderCore/Techniques/CommonResources.h"
#include "../../RenderCore/Techniques/CommonBindings.h"
#include "../../RenderCore/Techniques/RenderPass.h"
#include "../../RenderCore/Techniques/RenderPassUtils.h"
#include "../../RenderCore/Techniques/ParsingContext.h"
#include "../../RenderCore/Format.h"
#include "../../RenderCore/BufferView.h"
#include "../../Assets/Assets.h"
#include "../../ConsoleRig/ResourceBox.h"
#include "../../Utility/StringFormat.h"
#include "../../xleres/FileList.h"
namespace RenderOverlays
{
using namespace RenderCore;
std::shared_ptr<Metal::ShaderProgram> LoadShaderProgram(
StringSection<> vs,
StringSection<> ps,
StringSection<> definesTable = {})
{
auto vsCode = ::Assets::MakeAsset<CompiledShaderByteCode>(vs, definesTable);
auto psCode = ::Assets::MakeAsset<CompiledShaderByteCode>(ps, definesTable);
auto vsActual = vsCode->Actualize();
auto psActual = psCode->Actualize();
return std::make_shared<Metal::ShaderProgram>(Metal::GetObjectFactory(), *vsActual, *psActual);
}
const UInt4 HighlightByStencilSettings::NoHighlight = UInt4(0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff);
HighlightByStencilSettings::HighlightByStencilSettings()
{
_outlineColor = Float3(1.5f, 1.35f, .7f);
_highlightedMarker = NoHighlight;
for (unsigned c=0; c<dimof(_stencilToMarkerMap); ++c)
_stencilToMarkerMap[c] = NoHighlight;
}
static void ExecuteHighlightByStencil(
Metal::DeviceContext& metalContext,
Metal::ShaderResourceView& stencilSrv,
const HighlightByStencilSettings& settings,
bool onlyHighlighted)
{
auto cbData = MakeIteratorRange(&settings, PtrAdd(&settings, sizeof(settings)));
metalContext.GetNumericUniforms(ShaderStage::Pixel).Bind(MakeResourceList(Metal::MakeConstantBuffer(Metal::GetObjectFactory(), cbData)));
metalContext.GetNumericUniforms(ShaderStage::Pixel).Bind(MakeResourceList(stencilSrv));
metalContext.Bind(Techniques::CommonResources()._dssDisable);
metalContext.Bind(Techniques::CommonResources()._blendAlphaPremultiplied);
metalContext.Bind(Topology::TriangleStrip);
metalContext.UnbindInputLayout();
auto desc = stencilSrv.GetResource()->GetDesc();
if (desc._type != ResourceDesc::Type::Texture) return;
auto components = GetComponents(desc._textureDesc._format);
bool stencilInput =
components == FormatComponents::DepthStencil
|| components == FormatComponents::Stencil;
StringMeld<64, ::Assets::ResChar> params;
params << "ONLY_HIGHLIGHTED=" << unsigned(onlyHighlighted);
params << ";INPUT_MODE=" << (stencilInput?0:1);
{
auto shader = LoadShaderProgram(
BASIC2D_VERTEX_HLSL ":fullscreen:vs_*",
HIGHLIGHT_VIS_PIXEL_HLSL ":HighlightByStencil:ps_*",
(const ::Assets::ResChar*)params);
metalContext.Bind(*shader);
metalContext.Draw(4);
}
{
auto shader = LoadShaderProgram(
BASIC2D_VERTEX_HLSL ":fullscreen:vs_*",
HIGHLIGHT_VIS_PIXEL_HLSL ":OutlineByStencil:ps_*",
(const ::Assets::ResChar*)params);
metalContext.Bind(*shader);
metalContext.Draw(4);
}
metalContext.GetNumericUniforms(ShaderStage::Pixel).Reset();
}
void ExecuteHighlightByStencil(
IThreadContext& threadContext,
Techniques::ParsingContext& parsingContext,
const HighlightByStencilSettings& settings,
bool onlyHighlighted)
{
std::vector<FrameBufferDesc::Attachment> attachments {
{ Techniques::AttachmentSemantics::ColorLDR, AsAttachmentDesc(parsingContext.GetNamedResources().GetBoundResource(RenderCore::Techniques::AttachmentSemantics::ColorLDR)->GetDesc()) },
{ Techniques::AttachmentSemantics::MultisampleDepth, Format::D24_UNORM_S8_UINT }
};
SubpassDesc mainPass;
mainPass.SetName("VisualisationOverlay");
mainPass.AppendOutput(0);
mainPass.AppendInput(1);
FrameBufferDesc fbDesc{ std::move(attachments), {mainPass} };
Techniques::RenderPassInstance rpi {
threadContext, fbDesc,
parsingContext.GetFrameBufferPool(),
parsingContext.GetNamedResources() };
auto stencilSrv = rpi.GetInputAttachmentSRV(
0,
TextureViewDesc{
{TextureViewDesc::Aspect::Stencil},
TextureViewDesc::All, TextureViewDesc::All, TextureDesc::Dimensionality::Undefined,
TextureViewDesc::Flags::JustStencil});
if (!stencilSrv->IsGood()) return;
auto& metalContext = *RenderCore::Metal::DeviceContext::Get(threadContext);
ExecuteHighlightByStencil(metalContext, *stencilSrv, settings, onlyHighlighted);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
class HighlightShaders
{
public:
class Desc {};
std::shared_ptr<Metal::ShaderProgram> _drawHighlight;
Metal::BoundUniforms _drawHighlightUniforms;
std::shared_ptr<Metal::ShaderProgram> _drawShadow;
Metal::BoundUniforms _drawShadowUniforms;
const std::shared_ptr<::Assets::DependencyValidation>& GetDependencyValidation() const { return _validationCallback; }
HighlightShaders(const Desc&);
protected:
std::shared_ptr<::Assets::DependencyValidation> _validationCallback;
};
HighlightShaders::HighlightShaders(const Desc&)
{
//// ////
_drawHighlight = LoadShaderProgram(
BASIC2D_VERTEX_HLSL ":fullscreen:vs_*",
OUTLINE_VIS_PIXEL_HLSL ":main:ps_*");
UniformsStreamInterface drawHighlightInterface;
drawHighlightInterface.BindConstantBuffer(0, { Hash64("$Globals") });
_drawHighlightUniforms = Metal::BoundUniforms(*_drawHighlight, {}, {}, drawHighlightInterface);
//// ////
_drawShadow = LoadShaderProgram(
BASIC2D_VERTEX_HLSL ":fullscreen:vs_*",
OUTLINE_VIS_PIXEL_HLSL ":main_shadow:ps_*");
UniformsStreamInterface drawShadowInterface;
drawShadowInterface.BindConstantBuffer(0, { Hash64("ShadowHighlightSettings") });
_drawShadowUniforms = Metal::BoundUniforms(*_drawShadow, {}, {}, drawShadowInterface);
//// ////
_validationCallback = std::make_shared<::Assets::DependencyValidation>();
::Assets::RegisterAssetDependency(_validationCallback, _drawHighlight->GetDependencyValidation());
}
class BinaryHighlight::Pimpl
{
public:
IThreadContext* _threadContext;
Techniques::AttachmentPool* _namedRes;
Techniques::RenderPassInstance _rpi;
FrameBufferDesc _fbDesc;
Pimpl(IThreadContext& threadContext, Techniques::AttachmentPool& namedRes)
: _threadContext(&threadContext), _namedRes(&namedRes) {}
~Pimpl() {}
};
const RenderCore::FrameBufferDesc& BinaryHighlight::GetFrameBufferDesc() const
{
return _pimpl->_fbDesc;
}
BinaryHighlight::BinaryHighlight(
IThreadContext& threadContext,
Techniques::FrameBufferPool& fbPool,
Techniques::AttachmentPool& namedRes)
{
using namespace RenderCore;
_pimpl = std::make_unique<Pimpl>(threadContext, namedRes);
const bool doDepthTest = true;
Techniques::FrameBufferDescFragment fbDescFrag;
auto n_offscreen = fbDescFrag.DefineTemporaryAttachment(
AttachmentDesc {
Format::R8G8B8A8_UNORM, 1.f, 1.f, 0u,
AttachmentDesc::DimensionsMode::OutputRelative,
AttachmentDesc::Flags::RenderTarget | AttachmentDesc::Flags::ShaderResource });
auto n_mainColor = fbDescFrag.DefineAttachment(
RenderCore::Techniques::AttachmentSemantics::ColorLDR,
AsAttachmentDesc(namedRes.GetBoundResource(RenderCore::Techniques::AttachmentSemantics::ColorLDR)->GetDesc()));
AttachmentName n_depth = ~0u;
if (doDepthTest) {
AttachmentDesc depthAttachment;
auto* existingDepthAttachment = namedRes.GetBoundResource(RenderCore::Techniques::AttachmentSemantics::MultisampleDepth).get();
if (existingDepthAttachment) {
depthAttachment = AsAttachmentDesc(existingDepthAttachment->GetDesc());
} else {
depthAttachment._format = Format::D24_UNORM_S8_UINT;
depthAttachment._flags = AttachmentDesc::Flags::DepthStencil | AttachmentDesc::Flags::ShaderResource;
}
n_depth = fbDescFrag.DefineAttachment(RenderCore::Techniques::AttachmentSemantics::MultisampleDepth, depthAttachment);
}
SubpassDesc subpass0;
subpass0.AppendOutput(n_offscreen, LoadStore::Clear, LoadStore::Retain);
subpass0.SetDepthStencil(AttachmentViewDesc { n_depth, LoadStore::Retain, LoadStore::Retain, TextureViewDesc{ TextureViewDesc::Aspect::DepthStencil } });
fbDescFrag.AddSubpass(std::move(subpass0));
SubpassDesc subpass1;
subpass1.AppendOutput(n_mainColor, LoadStore::Retain, LoadStore::Retain);
subpass1.AppendInput(n_offscreen, LoadStore::Retain, LoadStore::DontCare);
fbDescFrag.AddSubpass(std::move(subpass1));
ClearValue clearValues[] = {MakeClearValue(0.f, 0.f, 0.f, 0.f)};
_pimpl->_fbDesc = Techniques::BuildFrameBufferDesc(std::move(fbDescFrag));
_pimpl->_rpi = Techniques::RenderPassInstance(
threadContext, _pimpl->_fbDesc,
fbPool, namedRes,
{MakeIteratorRange(clearValues)});
}
void BinaryHighlight::FinishWithOutlineAndOverlay(RenderCore::IThreadContext& threadContext, Float3 outlineColor, unsigned overlayColor)
{
auto& srv = *_pimpl->_rpi.GetInputAttachmentSRV(0);
assert(srv.IsGood());
_pimpl->_rpi.NextSubpass();
if (srv.IsGood()) {
static Float3 highlightColO(1.5f, 1.35f, .7f);
static unsigned overlayColO = 1;
outlineColor = highlightColO;
overlayColor = overlayColO;
auto& metalContext = *Metal::DeviceContext::Get(threadContext);
HighlightByStencilSettings settings;
settings._outlineColor = outlineColor;
for (unsigned c=1; c<dimof(settings._stencilToMarkerMap); ++c)
settings._stencilToMarkerMap[c] = UInt4(overlayColor, overlayColor, overlayColor, overlayColor);
ExecuteHighlightByStencil(
metalContext, srv,
settings, false);
}
_pimpl->_rpi.End();
}
void BinaryHighlight::FinishWithOutline(RenderCore::IThreadContext& threadContext, Float3 outlineColor)
{
// now we can render these objects over the main image,
// using some filtering
auto& srv = *_pimpl->_rpi.GetInputAttachmentSRV(0);
assert(srv.IsGood());
_pimpl->_rpi.NextSubpass();
if (srv.IsGood()) {
auto& metalContext = *Metal::DeviceContext::Get(threadContext);
metalContext.GetNumericUniforms(ShaderStage::Pixel).Bind(MakeResourceList(srv));
struct Constants { Float3 _color; unsigned _dummy; } constants = { outlineColor, 0 };
ConstantBufferView cbvs[] = { MakeSharedPkt(constants) };
auto& shaders = ConsoleRig::FindCachedBoxDep<HighlightShaders>(HighlightShaders::Desc());
shaders._drawHighlightUniforms.Apply(metalContext, 1, { MakeIteratorRange(cbvs) });
metalContext.Bind(*shaders._drawHighlight);
metalContext.Bind(Techniques::CommonResources()._blendAlphaPremultiplied);
metalContext.Bind(Techniques::CommonResources()._dssDisable);
metalContext.Bind(Topology::TriangleStrip);
metalContext.Draw(4);
}
_pimpl->_rpi.End();
}
void BinaryHighlight::FinishWithShadow(RenderCore::IThreadContext& threadContext, Float4 shadowColor)
{
auto& srv = *_pimpl->_rpi.GetInputAttachmentSRV(0);
assert(srv.IsGood());
_pimpl->_rpi.NextSubpass();
// now we can render these objects over the main image,
// using some filtering
if (srv.IsGood()) {
auto& metalContext = *Metal::DeviceContext::Get(threadContext);
metalContext.GetNumericUniforms(ShaderStage::Pixel).Bind(MakeResourceList(srv));
struct Constants { Float4 _shadowColor; } constants = { shadowColor };
ConstantBufferView cbvs[] = { MakeSharedPkt(constants) };
auto& shaders = ConsoleRig::FindCachedBoxDep<HighlightShaders>(HighlightShaders::Desc());
shaders._drawShadowUniforms.Apply(metalContext, 1, { MakeIteratorRange(cbvs) });
metalContext.Bind(*shaders._drawShadow);
metalContext.Bind(Techniques::CommonResources()._blendStraightAlpha);
metalContext.Bind(Techniques::CommonResources()._dssDisable);
metalContext.Bind(Topology::TriangleStrip);
metalContext.Draw(4);
}
_pimpl->_rpi.End();
}
BinaryHighlight::~BinaryHighlight() {}
}
| 39.571856 | 186 | 0.697813 | pocketgems |
e98f021fc51fd014239c759cce7fbbd9e729508e | 4,081 | cpp | C++ | src/LumberJack.cpp | FRC-3277/2018POWER-UP | 063797b865c3985b77dabe51173595a995d99f0f | [
"MIT"
] | 2 | 2018-01-26T00:54:32.000Z | 2018-03-22T02:24:06.000Z | src/LumberJack.cpp | FRC-3277/2018POWER-UP | 063797b865c3985b77dabe51173595a995d99f0f | [
"MIT"
] | 2 | 2018-02-10T04:04:13.000Z | 2018-02-11T02:24:08.000Z | src/LumberJack.cpp | FRC-3277/2018POWER-UP | 063797b865c3985b77dabe51173595a995d99f0f | [
"MIT"
] | null | null | null | #include <LumberJack.h>
INITIALIZE_EASYLOGGINGPP
LumberJack::LumberJack() {
defaultConf.setToDefault();
defaultLogger = el::Loggers::getLogger("default");
}
LumberJack::~LumberJack() {
}
void LumberJack::SetLoggingLevel(el::Level argSeverityLevel)
{
severityLevelChosen = argSeverityLevel;
}
void LumberJack::SetConfig()
{
// Values are always std::string
defaultConf.set(severityLevelChosen, el::ConfigurationType::Format, "%datetime %level %msg");
// default logger uses default configurations
el::Loggers::reconfigureLogger("default", defaultConf);
}
void LumberJack::iLog(char* msg)
{
LOG_IF(isInfoLoggingEnabled, INFO) << msg;
}
void LumberJack::iLog(char* msg, int loggingFrequency)
{
if(isInfoLoggingEnabled)
{
LOG_EVERY_N(loggingFrequency, INFO) << msg;
}
}
void LumberJack::dLog(char* msg)
{
LOG_IF(isDebugLoggingEnabled, DEBUG) << msg;
}
void LumberJack::dLog(char* msg, int loggingFrequency)
{
if(isDebugLoggingEnabled)
{
LOG_EVERY_N(loggingFrequency, DEBUG) << msg;
}
}
void LumberJack::eLog(char* msg)
{
LOG_IF(isErrorLoggingEnabled, ERROR) << msg;
}
void LumberJack::eLog(char* msg, int loggingFrequency)
{
if(isErrorLoggingEnabled)
{
LOG_EVERY_N(loggingFrequency, ERROR) << msg;
}
}
void LumberJack::wLog(char* msg)
{
LOG_IF(isWarningLoggingEnabled, WARNING) << msg;
}
void LumberJack::wLog(char* msg, int loggingFrequency)
{
if(isWarningLoggingEnabled)
{
LOG_EVERY_N(loggingFrequency, WARNING) << msg;
}
}
void LumberJack::fLog(char* msg)
{
LOG_IF(isFatalLoggingEnabled, FATAL) << msg;
}
void LumberJack::fLog(char* msg, int loggingFrequency)
{
if(isFatalLoggingEnabled)
{
LOG_EVERY_N(loggingFrequency, FATAL) << msg;
}
}
void LumberJack::tLog(char* msg)
{
LOG_IF(isTraceLoggingEnabled, TRACE) << msg;
}
void LumberJack::tLog(char* msg, int loggingFrequency)
{
if(isTraceLoggingEnabled)
{
LOG_EVERY_N(loggingFrequency, TRACE) << msg;
}
}
void LumberJack::iLog(const string& msg)
{
LOG_IF(isInfoLoggingEnabled, INFO) << msg;
}
void LumberJack::iLog(const string& msg, int loggingFrequency)
{
LOG_EVERY_N(loggingFrequency, INFO) << msg;
}
void LumberJack::dLog(const string& msg)
{
LOG_IF(isDebugLoggingEnabled, DEBUG) << msg;
}
void LumberJack::dLog(const string& msg, int loggingFrequency)
{
if(isDebugLoggingEnabled)
{
LOG_EVERY_N(loggingFrequency, DEBUG) << msg;
}
}
void LumberJack::eLog(const string& msg)
{
LOG_IF(isErrorLoggingEnabled, ERROR) << msg;
}
void LumberJack::eLog(const string& msg, int loggingFrequency)
{
if(isErrorLoggingEnabled)
{
LOG_EVERY_N(loggingFrequency, ERROR) << msg;
}
}
void LumberJack::wLog(const string& msg)
{
LOG_IF(isWarningLoggingEnabled, WARNING) << msg;
}
void LumberJack::wLog(const string& msg, int loggingFrequency)
{
if(isWarningLoggingEnabled)
{
LOG_EVERY_N(loggingFrequency, WARNING) << msg;
}
}
void LumberJack::fLog(const string& msg)
{
LOG_IF(isFatalLoggingEnabled, FATAL) << msg;
}
void LumberJack::fLog(const string& msg, int loggingFrequency)
{
if(isFatalLoggingEnabled)
{
LOG_EVERY_N(loggingFrequency, FATAL) << msg;
}
}
void LumberJack::tLog(const string& msg)
{
LOG_IF(isTraceLoggingEnabled, TRACE) << msg;
}
void LumberJack::tLog(const string& msg, int loggingFrequency)
{
if(isTraceLoggingEnabled)
{
LOG_EVERY_N(loggingFrequency, TRACE) << msg;
}
}
/**
* The log method puts "data"... information of interest from the subsystem
* to the SmartDashboard. Useful in dashLog() methods.
*/
void LumberJack::dashLogData(llvm::StringRef key, Sendable* data)
{
SmartDashboard::PutData(key, data);
}
/**
* The log method puts Numerical information of interest from the subsystem
* to the SmartDashboard. Useful in dashLog() methods.
*/
void LumberJack::dashLogNumber(llvm::StringRef key, double value)
{
SmartDashboard::PutNumber(key, value);
}
/**
* The log method puts String information of interest from the subsystem to
* the SmartDashboard. Useful in dashLog() methods.
*/
void LumberJack::dashLogString(llvm::StringRef key, llvm::StringRef message)
{
SmartDashboard::PutString(key, message);
}
| 20.004902 | 94 | 0.737564 | FRC-3277 |
e9942507bfe3217a594bd9a9b56de1cd11ad17aa | 319 | hpp | C++ | include/andromeda/graphics/environment.hpp | NotAPenguin0/Andromeda | 69ac0e448dbc7d5ba8f5915177f333bd8cd1a1b4 | [
"MIT"
] | 7 | 2020-04-28T11:01:55.000Z | 2022-02-22T09:59:33.000Z | include/andromeda/graphics/environment.hpp | NotAPenguin0/Andromeda | 69ac0e448dbc7d5ba8f5915177f333bd8cd1a1b4 | [
"MIT"
] | 2 | 2021-09-03T12:58:06.000Z | 2021-09-20T20:07:33.000Z | include/andromeda/graphics/environment.hpp | NotAPenguin0/Andromeda | 69ac0e448dbc7d5ba8f5915177f333bd8cd1a1b4 | [
"MIT"
] | 1 | 2021-09-03T12:56:25.000Z | 2021-09-03T12:56:25.000Z | #pragma once
#include <phobos/image.hpp>
#include <andromeda/util/handle.hpp>
namespace andromeda::gfx {
struct Environment {
ph::RawImage cubemap;
ph::ImageView cubemap_view;
ph::RawImage irradiance;
ph::ImageView irradiance_view;
ph::RawImage specular;
ph::ImageView specular_view;
};
} | 15.95 | 36 | 0.708464 | NotAPenguin0 |
e9945e5159b3c244910b59fcbf95313f77fd873b | 12,678 | hpp | C++ | 08/vector_tests.hpp | k911mipt/made_2019_cpp | a55a7c867cdc1c076ae86c89a79df6581c80da7b | [
"MIT"
] | null | null | null | 08/vector_tests.hpp | k911mipt/made_2019_cpp | a55a7c867cdc1c076ae86c89a79df6581c80da7b | [
"MIT"
] | null | null | null | 08/vector_tests.hpp | k911mipt/made_2019_cpp | a55a7c867cdc1c076ae86c89a79df6581c80da7b | [
"MIT"
] | null | null | null | #pragma once
#ifndef PRINT_TESTS_H_
#define PRINT_TESTS_H_
#include <algorithm>
#include <functional>
#include "vector.hpp"
#include <deque>
namespace made {
namespace test {
using TestFunc = std::function<bool()>;
using TestGetter = std::function<std::vector<TestFunc>()>;
namespace stl {
using namespace made::stl;
class A {
public:
int x;
A(int _x) :x(_x) {}
};
class B {
public:
inline static int counter_ = 0;
int x;
B() :x(counter_++) {}
B(int _x) :x(_x) {}
};
class BadMove : public std::exception {
public:
BadMove() noexcept : std::exception() {}
const char* what() { return "BadMove"; }
};
class Complex {
public:
Complex() : size_(1), arr_(new int[size_]) {}
Complex(size_t size) : size_(size), arr_(new int[size_]) {
Fill();
}
Complex(const Complex& copied) : size_(copied.size_), arr_(new int[size_]) {
Copy(copied.arr_);
}
Complex(Complex&& moved)
: size_(moved.size_)
{
ThrowIfThresholdReached();
arr_ = moved.arr_;
moved.arr_ = nullptr;
moved.size_ = 0;
}
Complex& operator=(const Complex& copied) {
if (this == &copied)
return *this;
delete[] arr_;
size_ = copied.size_;
arr_ = new int[size_];
Copy(copied.arr_);
return *this;
}
Complex& operator=(Complex&& moved) {
if (this == &moved)
return *this;
ThrowIfThresholdReached();
delete[] arr_;
size_ = moved.size_;
arr_ = moved.arr_;
moved.arr_ = nullptr;
moved.size_ = 0;
return *this;
}
~Complex() {
Fill();
delete[] arr_;
}
void ThrowIfThresholdReached() {
if (move_throw_enabled_ && ++counter_ > throw_threshold_) {
throw BadMove();
}
}
static void EnableMoveThrowCounter(size_t threshold) {
throw_threshold_ = threshold;
move_throw_enabled_ = true;
}
private:
void Fill() {
for (size_t i = 0; i < size_; ++i)
arr_[i] = i;
}
void Copy(int* arr) {
for (size_t i = 0; i < size_; ++i) {
arr_[i] = arr[i];
}
}
static inline size_t counter_ = 0;
static inline size_t throw_threshold_ = 0;
static inline bool move_throw_enabled_ = false;
size_t size_;
int* arr_;
};
#pragma region typed_tests
template <class T>
bool create_vector_without_arguments() {
std::cout << "Creating Vector<" << typeid(T).name() << ">";
Vector<T> v;
return true;
}
template<class T, typename std::enable_if<std::is_default_constructible<T>::value, T>::type * = nullptr>
bool create_vector_with_count() {
std::cout << "Creating Vector<" << typeid(T).name() << ">(int count)";
Vector<T> v(5);
return true;
}
template<class T, typename std::enable_if<!std::is_default_constructible<T>::value, T>::type * = nullptr>
bool create_vector_with_count() {
std::cout << "Creating Vector<" << typeid(T).name() << ">(int count)";
std::cout << ": " << typeid(T).name() << " has no default constructor, skipping";
return true;
}
template<class T, typename std::enable_if<std::is_default_constructible<T>::value, T>::type * = nullptr>
bool create_vector_with_init_value() {
std::cout << "Creating Vector<" << typeid(T).name() << "> with init_value";
Vector<T> v(5, T());
return true;
}
template<class T, typename std::enable_if<!std::is_default_constructible<T>::value, T>::type * = nullptr>
bool create_vector_with_init_value() {
std::cout << "Creating Vector<" << typeid(A).name() << "> with init_value";
Vector<A> v(5, A(4));
return true;
}
template <class T>
bool create_vector_with_init_list() {
std::cout << "Creating Vector<" << typeid(T).name() << "> with initializer list";
Vector<T> v{ 1,2,3 };
return true;
}
template <class T>
std::vector<TestFunc> build_typed_test_functions() {
return {
create_vector_without_arguments<T>,
create_vector_with_count<T>,
create_vector_with_init_value<T>,
create_vector_with_init_list<T>,
};
}
#pragma endregion typed_tests
#pragma region other_tests
bool sort_using_iterators() {
std::cout << "sorting vector<int>{7, 3, 7, 56, 9, 2} using iterators";
Vector<int> v{ 7, 3, 7, 56, 9, 2 };
std::sort(v.begin(), v.end());
for (auto it = v.begin() + 1; it < v.end(); ++it)
if (it < it - 1)
return false;
return true;
}
bool check_push_back() {
std::cout << "testing push_back";
Vector<B> v;
B b;
v.push_back(b);
v.push_back(b);
v.push_back(b);
return b.x == v.back().x;
}
bool check_emplace_back() {
std::cout << "testing emplace_back";
Vector<B> v;
B b;
v.push_back(b);
v.push_back(b);
v.emplace_back();
return b.x == v.back().x - 1;
}
bool check_emplace() {
std::cout << "testing emplace_back";
Vector<A> v{ 1, 3, 4 };
v.emplace(v.begin() + 1, 2);
return v[1].x == 2 && v[3].x == 4;
}
bool check_reserve() {
std::cout << "testing reserve";
Vector<A> v{ 1, 3, 4 };
v.reserve(4);
return v[1].x == 3 && v[2].x == 4 && v.capacity() == 4 && v.size() == 3;
}
bool check_resize() {
std::cout << "testing resize";
Vector<A> v{ 1, 3, 4 };
A a(10);
v.resize(15, a);
return v[1].x == 3 && v[2].x == 4 && v[14].x == 10;
}
bool check_resize_constructing() {
std::cout << "testing resize constructing single time";
B::counter_ = 9;
Vector<B> v{ 1, 3, 4, 2, 0 };
v.resize(15);
return v[1].x == 3 && v[13].x == 9 && v[14].x == 9;
}
bool check_pop_back() {
std::cout << "testing pop_back";
Vector<B> v{ 1, 3, 4, 2, 0 };
v.resize(15);
v.pop_back();
return v.size() == 14;
}
bool check_erase() {
std::cout << "testing erase";
Vector<B> v{ 1, 3, 4, 2, 0 };
v.erase(v.begin() + 1, v.end() - 1);
return v.size() == 2 && v.front().x == 1 && (v.end() - 1)->x == 0;
}
std::vector<TestFunc> get_other_test_functions() {
return {
sort_using_iterators,
check_push_back,
check_emplace_back,
check_emplace,
check_reserve,
check_resize,
check_resize_constructing,
check_pop_back,
check_erase,
};
}
#pragma endregion other_tests
#pragma region uninitialized_move_tests
bool check_complex_emplace() {
std::cout << "testing umove: emplace with realloc";
Vector<Complex> v(1, Complex(5));
v.emplace(v.begin(), Complex(5));
return true;
}
bool check_complex_reserve() {
std::cout << "testing umove: reserve";
Vector<Complex> v(1, Complex(5));
v.reserve(3);
return true;
}
bool check_complex_emplace_at_uninit_space() {
std::cout << "testing umove: emplace at reserved space";
Vector<Complex> v(3, Complex(5));
//std::vector<Complex> v(1, Complex(5));
v.reserve(6);
v.emplace(v.begin(), Complex(2));
return true;
}
bool check_complex_resize_realloc() {
std::cout << "testing umove: resize with reallocating";
Vector<Complex> v(3, Complex(5));
v.resize(6, Complex(1));
return true;
}
bool check_complex_erase_single() {
std::cout << "testing umove: erase single with move";
Vector<Complex> v(3, Complex(5));
v.erase(v.begin());
return true;
}
bool check_complex_erase_range() {
std::cout << "testing umove: erase range with move";
Vector<Complex> v(6, Complex(3));
v.erase(v.begin() + 1, v.end() - 2);
return true;
}
bool check_complex_move_throw() {
std::cout << "testing umove: throw at moving";
Complex::EnableMoveThrowCounter(5);
Vector<Complex> v(6, Complex(3));
try {
v.emplace(v.begin() + 3, Complex(15));
}
catch (BadMove & e) {
return true;
}
return false;
}
std::vector<TestFunc> get_uninitialized_move_test_functions() {
return {
check_complex_emplace,
check_complex_reserve,
check_complex_emplace_at_uninit_space,
check_complex_resize_realloc,
check_complex_erase_single,
check_complex_erase_range,
check_complex_move_throw
};
}
#pragma endregion uninitialized_move_tests
template <typename T>
struct type_wrapper { using type = T; };
template <typename... Ts, typename TF>
void for_types(TF&& f) { (f(type_wrapper<Ts>{}), ...); }
template <typename... Ts>
std::vector<TestFunc> get_type_shared_tests() {
std::vector<TestFunc> result;
for_types<Ts...>([&result](auto t)
{
using T = typename decltype(t)::type;
auto temp = build_typed_test_functions<T>();
result.insert(result.end(), temp.begin(), temp.end());
});
return result;
}
std::vector<TestFunc> GetTests() {
std::vector<TestFunc> result = get_type_shared_tests<int, A, B, Complex>();
std::vector<TestFunc> other = get_other_test_functions();
result.insert(result.end(), other.begin(), other.end());
other = get_uninitialized_move_test_functions();
result.insert(result.end(), other.begin(), other.end());
return result;
}
}
}
}
#endif // !PRINT_TESTS_H_ | 35.61236 | 117 | 0.432324 | k911mipt |
e995169aa51097e69d22d95e7028396678498dc5 | 1,206 | cpp | C++ | InSight/src/Platform/OpenGL/OpenGLContext.cpp | I-Hudson/InSightEngine | a766c87a7be51a19ab796a81888fbbf93a8a43be | [
"Apache-2.0"
] | 3 | 2019-05-26T19:22:27.000Z | 2019-07-09T21:42:18.000Z | InSight/src/Platform/OpenGL/OpenGLContext.cpp | I-Hudson/InSightEngine | a766c87a7be51a19ab796a81888fbbf93a8a43be | [
"Apache-2.0"
] | 15 | 2019-05-26T09:32:22.000Z | 2019-06-11T11:31:03.000Z | InSight/src/Platform/OpenGL/OpenGLContext.cpp | I-Hudson/Insight-Engine | a766c87a7be51a19ab796a81888fbbf93a8a43be | [
"Apache-2.0"
] | null | null | null | #include "Platform/OpenGL/OpenGLContext.h"
#include "InSight/Log.h"
#include <glad/glad.h>
#include <GLFW/glfw3.h>
namespace InSight
{
OpenGLContext::OpenGLContext(GLFWwindow * aWindowHandle)
: mWindowHandle(aWindowHandle)
{
EN_CORE_ASSERT(mWindowHandle, "Window handle is null!");
}
void OpenGLContext::Init()
{
glfwMakeContextCurrent(mWindowHandle);
int gladStatus = gladLoadGL();
EN_CORE_ASSERT(gladStatus, "Failed to initailize GLAD!");
//int major = glfwGetWindowAttrib(static_cast<GLFWwindow*>(mWindow->GetNativeWindow()), GLFW_CONTEXT_VERSION_MAJOR);
//int minor = glfwGetWindowAttrib(static_cast<GLFWwindow*>(mWindow->GetNativeWindow()), GLFW_CONTEXT_VERSION_MINOR);
//int revision = glfwGetWindowAttrib(static_cast<GLFWwindow*>(mWindow->GetNativeWindow()), GLFW_CONTEXT_REVISION);
////log->addLog
//EN_CORE_INFO("OpenGL Version {0}.{1}.{2}", major, minor, revision);
EN_CORE_INFO("OpenGL Info:");
EN_CORE_INFO(" Vendor: {0}", glGetString(GL_VENDOR));
EN_CORE_INFO(" BaseRenderer: {0}", glGetString(GL_BaseRenderer));
EN_CORE_INFO(" Version: {0}", glGetString(GL_VERSION));
}
void OpenGLContext::SwapBuffers()
{
glfwSwapBuffers(mWindowHandle);
}
} | 33.5 | 118 | 0.743781 | I-Hudson |
e996d2245d638ec7ef146c111aa9d1f89b888b1f | 2,806 | cpp | C++ | Topcoder/asia-mut/C.cpp | CodingYue/acm-icpc | 667596efae998f5480819870714c37e9af0740eb | [
"Unlicense"
] | 1 | 2015-11-03T09:31:07.000Z | 2015-11-03T09:31:07.000Z | Topcoder/asia-mut/C.cpp | CodingYue/acm-icpc | 667596efae998f5480819870714c37e9af0740eb | [
"Unlicense"
] | null | null | null | Topcoder/asia-mut/C.cpp | CodingYue/acm-icpc | 667596efae998f5480819870714c37e9af0740eb | [
"Unlicense"
] | null | null | null | // File Name: C.cpp
// Author: YangYue
// Created Time: Mon Jul 28 14:55:52 2014
//headers
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <ctime>
#include <string>
#include <queue>
#include <set>
#include <map>
#include <iostream>
#include <vector>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<double,double> PDD;
typedef pair<LL, LL>PLL;
typedef pair<LL,int>PLI;
const int MaxN = 1200005;
const int MOD = (int) 1e9 + 7;
class Byteland {
public:
LL fac[MaxN], invfac[MaxN];
LL C(LL n, LL k) {
if (n < k || k < 0) return 0;
return fac[n] * invfac[k] % MOD * invfac[n-k] % MOD;
}
LL fpow(LL a, int t, int mod) {
LL res = 1;
for (; t; t >>= 1, a = a * a % mod)
if (t & 1) res = res * a % mod;
return res;
}
int CountDifferentMaps(int n, int k) {
fac[0] = invfac[0] = 1;
for (int i = 1; i <= 1200000; ++i) {
fac[i] = fac[i-1] * i % MOD;
invfac[i] = fpow(fac[i], MOD - 2, MOD);
}
LL ans = n;
ans = ans * C(n-1,k) % MOD;
for (int i = k; i <= n - 2; ++i) ans = ans * i % MOD;
return (int) ans;
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit 2.1.4 (beta) modified by pivanof
bool KawigiEdit_RunTest(int testNum, int p0, int p1, bool hasAnswer, int p2) {
cout << "Test " << testNum << ": [" << p0 << "," << p1;
cout << "]" << endl;
Byteland *obj;
int answer;
obj = new Byteland();
clock_t startTime = clock();
answer = obj->CountDifferentMaps(p0, p1);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << p2 << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << answer << endl;
if (hasAnswer) {
res = answer == p2;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
all_right = true;
int p0;
int p1;
int p2;
{
// ----- test 0 -----
p0 = 5;
p1 = 4;
p2 = 5;
all_right = KawigiEdit_RunTest(0, p0, p1, true, p2) && all_right;
// ------------------
}
{
// ----- test 1 -----
p0 = 6;
p1 = 3;
p2 = 720;
all_right = KawigiEdit_RunTest(1, p0, p1, true, p2) && all_right;
// ------------------
}
if (all_right) {
cout << "You're a stud (at least on the example cases)!" << endl;
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
// hehe ~
| 21.419847 | 88 | 0.571632 | CodingYue |
e999b6a575e299a4d5c495d2c48042494cf02120 | 1,619 | hh | C++ | io/FilteringLineIStream.hh | gvissers/quill2 | 589d7bc3ce20da888547f8f4f6b8da908b3d63a5 | [
"Apache-2.0"
] | null | null | null | io/FilteringLineIStream.hh | gvissers/quill2 | 589d7bc3ce20da888547f8f4f6b8da908b3d63a5 | [
"Apache-2.0"
] | null | null | null | io/FilteringLineIStream.hh | gvissers/quill2 | 589d7bc3ce20da888547f8f4f6b8da908b3d63a5 | [
"Apache-2.0"
] | null | null | null | #ifndef FILTERINGLINEISTREAM_HH
#define FILTERINGLINEISTREAM_HH
/*!
* \file FilteringLineIStream.hh
* \brief Definition of the FilteringLineIStream class
*/
#include "io/LineIStream.hh"
#include "io/FilteringIStream.hh"
/*!
* \brief Class for reading filtered lines
*
* Class FilteringLineIStream is an input stream that provides the ability
* to read filtered input line by line. It provides a line-based stream
* with the possibility of placing lines back on the stream, and can be used
* to e.g. read job files line by line, while filtering out comments.
* \tparam Filter The filter to apply to the input data
*/
template <typename Filter>
struct FilteringLineIStream: public IStreamUser< FilteringIStream<Filter> >,
public LineIStream
{
/*!
* \brief Constructor
*
* Create a new FilteringLineIstream object for reading a job from
* input stream \a is.
* \param is The input stream to read from
*/
explicit FilteringLineIStream(std::istream& is):
IStreamUser< FilteringIStream<Filter> >(is.rdbuf()),
LineIStream(IStreamUser< FilteringIStream<Filter> >::stream())
{}
/*!
* \brief Constructor
*
* Create a new FilteringLineIstream object for reading a job from
* input stream \a is, using \a filter to filter the incoming data.
* \param is The input stream to read from
* \param filter The filter object to apply to the data from \a is.
*/
FilteringLineIStream(std::istream& is, Filter *filter):
IStreamUser< FilteringIStream<Filter> >(is.rdbuf(), filter),
LineIStream(IStreamUser< FilteringIStream<Filter> >::stream())
{}
};
#endif // FILTERINGLINEISTREAM_HH
| 31.745098 | 76 | 0.738728 | gvissers |
e99cb18c33f7bcfd3f2e6c39aa01f214d6123813 | 1,409 | hpp | C++ | editor/src/layers/test_layer.hpp | trbflxr/xe | 13123869a848972e064cb8c6838c4215f034f3d9 | [
"MIT"
] | null | null | null | editor/src/layers/test_layer.hpp | trbflxr/xe | 13123869a848972e064cb8c6838c4215f034f3d9 | [
"MIT"
] | null | null | null | editor/src/layers/test_layer.hpp | trbflxr/xe | 13123869a848972e064cb8c6838c4215f034f3d9 | [
"MIT"
] | null | null | null | //
// Created by FLXR on 9/11/2019.
//
#ifndef XE_TEST_LAYER_HPP
#define XE_TEST_LAYER_HPP
#include <xe/core/engine.hpp>
#include <xe/graphics/camera.hpp>
namespace xe {
class TestLayer : public LayerBase {
public:
explicit TestLayer();
void onStart() override;
void onStop() override;
void onRender() override;
void onUpdate() override;
bool onKeyPressed(Event::Key e) override;
bool onUi() override;
private:
static constexpr int32_t INSTANCES = 50000;
std::unique_ptr<PerspectiveCamera> camera_;
vec3 cameraPos_;
vec2u size_;
struct {
mat4 cubeModel;
mat4 cubeView;
mat4 cubeProj;
} uniforms_;
std::shared_ptr<gpu::Buffer> stateUbo_;
std::shared_ptr<gpu::Framebuffer> fb_;
struct {
vec4 instancePositions[INSTANCES];
std::shared_ptr<gpu::Pipeline> material;
std::shared_ptr<gpu::Buffer> vertexBuff;
std::shared_ptr<gpu::Buffer> indexBuff;
std::shared_ptr<gpu::Buffer> instanceBuffer;
std::shared_ptr<gpu::Texture> texture;
} cube_;
struct {
std::shared_ptr<gpu::Pipeline> material;
std::shared_ptr<gpu::Buffer> vertexBuff;
std::shared_ptr<gpu::Buffer> indexBuff;
Transform transform;
} quad_;
void *texData_ = nullptr;
int32_t instances_ = INSTANCES / 8;
bool quadRotation_ = true;
};
}
#endif //XE_TEST_LAYER_HPP
| 20.720588 | 50 | 0.665011 | trbflxr |
e9a38153790ee71b2ad0af8c1f068a7129b2ce05 | 808 | cc | C++ | pdb/src/computationServer/sources/physicalOptimizer/PDBOptimizerSource.cc | SeraphL/plinycompute | 7788bc2b01d83f4ff579c13441d0ba90734b54a2 | [
"Apache-2.0"
] | 3 | 2019-05-04T05:17:30.000Z | 2020-02-21T05:01:59.000Z | pdb/src/computationServer/sources/physicalOptimizer/PDBOptimizerSource.cc | dcbdan/plinycompute | a6f1c8ac8f75c09615f08752c82179f33cfc6d89 | [
"Apache-2.0"
] | 3 | 2020-02-20T19:50:46.000Z | 2020-06-25T14:31:51.000Z | pdb/src/computationServer/sources/physicalOptimizer/PDBOptimizerSource.cc | dcbdan/plinycompute | a6f1c8ac8f75c09615f08752c82179f33cfc6d89 | [
"Apache-2.0"
] | 5 | 2019-02-19T23:17:24.000Z | 2020-08-03T01:08:04.000Z | #include <PDBOptimizerSource.h>
#include <PDBAbstractPhysicalNode.h>
#include <physicalOptimizer/PDBOptimizerSource.h>
bool pdb::OptimizerSourceComparator::operator()(const pdb::OptimizerSource &lhs, const pdb::OptimizerSource &rhs) {
// first compare them based on the size
if(lhs.first != rhs.first) {
return lhs.first < rhs.first;
}
// if the size is equal compare them on the
return lhs.second->getNodeIdentifier() != rhs.second->getNodeIdentifier();
}
bool pdb::PageSetIdentifierComparator::operator()(const std::pair<size_t, std::string> &lhs, const std::pair<size_t, std::string> &rhs) {
// first compare them based on the size
if(lhs.first != rhs.first) {
return lhs.first < rhs.first;
}
// if the size is equal compare them on the
return lhs.second < rhs.second;
}
| 31.076923 | 137 | 0.717822 | SeraphL |
e9a7600b62d9eb575382b1dfac58d5ec671384ba | 1,184 | cpp | C++ | src/engine/core/texture.cpp | junhaowww/ForkerEngine | a5c71d0de797ab38c77d52d7b5a7f1d2f8005da7 | [
"Apache-2.0"
] | 3 | 2020-12-18T04:31:48.000Z | 2021-10-18T16:55:24.000Z | src/engine/core/texture.cpp | junhaowww/ForkerEngine | a5c71d0de797ab38c77d52d7b5a7f1d2f8005da7 | [
"Apache-2.0"
] | null | null | null | src/engine/core/texture.cpp | junhaowww/ForkerEngine | a5c71d0de797ab38c77d52d7b5a7f1d2f8005da7 | [
"Apache-2.0"
] | null | null | null | //
// Created by JunhaoW on 2020/12/12.
// Modified version from LearnOpenGL by Joey de Vries
//
#include "texture.h"
Texture::Texture()
: Width(0), Height(0), Internal_Format(GL_RGB), Image_Format(GL_RGB),
Wrap_S(GL_REPEAT), Wrap_T(GL_REPEAT), Filter_Min(GL_LINEAR_MIPMAP_LINEAR), Filter_Max(GL_LINEAR)
{
glGenTextures(1, &this->ID);
}
void Texture::Generate(unsigned int width, unsigned int height, const unsigned char* data)
{
this->Width = width;
this->Height = height;
// create texture
glBindTexture(GL_TEXTURE_2D, this->ID);
glTexImage2D(GL_TEXTURE_2D, 0, this->Internal_Format, width, height, 0, this->Image_Format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
// set texture wrap and filter modes
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, this->Wrap_S);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, this->Wrap_T);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, this->Filter_Min);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, this->Filter_Max);
// unbind
glBindTexture(GL_TEXTURE_2D, 0);
}
void Texture::Bind() const
{
glBindTexture(GL_TEXTURE_2D, this->ID);
} | 33.828571 | 120 | 0.735642 | junhaowww |
e9a8428c73a17d9e2d2def3dcc8000f26c3877ed | 887 | hpp | C++ | FactoryPattern/Animals.hpp | jonathan-daniel/ModernDesignPatterns | e9c79ced4261ba98c2c773cc725375903ae4c21c | [
"MIT"
] | 94 | 2018-07-15T19:20:54.000Z | 2021-11-17T15:56:06.000Z | FactoryPattern/Animals.hpp | junyanchang/ModernDesignPatterns | e9c79ced4261ba98c2c773cc725375903ae4c21c | [
"MIT"
] | 2 | 2018-07-15T19:58:31.000Z | 2021-02-22T19:43:15.000Z | FactoryPattern/Animals.hpp | junyanchang/ModernDesignPatterns | e9c79ced4261ba98c2c773cc725375903ae4c21c | [
"MIT"
] | 20 | 2018-07-24T04:47:07.000Z | 2022-03-19T08:52:09.000Z | #pragma once
#include <iostream>
class Animal {
private:
int animalInt;
public:
Animal(int animalInt) : animalInt(animalInt) {}
Animal() : animalInt(12) {}
virtual ~Animal(){} // the base class must have a virtual method.
virtual void doSomething()
{
std::cout << "animal stuff" << std::endl;
}
};
class Dog : public Animal {
private:
int dogInt;
int dogIntExtra = {-1};
public:
Dog() : Animal(10), dogInt(10) {}
Dog(bool extraprint) : Animal(10), dogInt(10), dogIntExtra(999)
{
if(extraprint)
std::cout << "Dog stuff with extra stuff" << std::endl;
}
void doSomething() override
{
std::cout << "dog stuff" << std::endl;
}
int getExtraInt()
{
return dogIntExtra;
}
};
class Duck : public Animal {
private:
int duckInt;
public:
Duck() : Animal(1337), duckInt(1337) {}
void doSomething() override
{
std::cout << "duck stuff" << std::endl;
}
}; | 16.735849 | 66 | 0.642616 | jonathan-daniel |
e9a8f9e7acf00f434b4070c23a305aa5e409a62d | 187 | cpp | C++ | test_main/src/EntryPoint.cpp | jgavert/FazE | 7cf63655869c285a7e5ca8f5a48f296d9548bd6c | [
"MIT"
] | 15 | 2020-01-15T13:04:36.000Z | 2022-02-18T17:08:25.000Z | test_main/src/EntryPoint.cpp | jgavert/FazE | 7cf63655869c285a7e5ca8f5a48f296d9548bd6c | [
"MIT"
] | 3 | 2015-09-09T08:16:30.000Z | 2015-11-24T16:22:48.000Z | test_main/src/EntryPoint.cpp | jgavert/FazE | 7cf63655869c285a7e5ca8f5a48f296d9548bd6c | [
"MIT"
] | 1 | 2021-12-06T07:19:05.000Z | 2021-12-06T07:19:05.000Z | #include <higanbana/core/platform/EntryPoint.hpp>
#include <higanbana/core/ranges/rectangle.hpp>
#include "windowMain.hpp"
int EntryPoint::main() {
mainWindow(m_params);
return 0;
} | 20.777778 | 49 | 0.754011 | jgavert |
e9ade19cc6f3bfc362e36b12d3e2dead26a231b1 | 476 | cpp | C++ | vm/vm.cpp | doublec/factor | 21ef21588252e2b54030ad6fd2fd1075dceb48f0 | [
"BSD-2-Clause"
] | 2 | 2016-05-09T05:56:17.000Z | 2020-12-01T09:27:35.000Z | vm/vm.cpp | doublec/factor | 21ef21588252e2b54030ad6fd2fd1075dceb48f0 | [
"BSD-2-Clause"
] | null | null | null | vm/vm.cpp | doublec/factor | 21ef21588252e2b54030ad6fd2fd1075dceb48f0 | [
"BSD-2-Clause"
] | null | null | null | #include "master.hpp"
namespace factor
{
factor_vm::factor_vm() :
nursery(0,0),
callback_id(0),
c_to_factor_func(NULL),
profiling_p(false),
gc_off(false),
current_gc(NULL),
gc_events(NULL),
fep_disabled(false),
full_output(false),
last_nano_count(0),
signal_callstack_seg(NULL)
{
primitive_reset_dispatch_stats();
}
factor_vm::~factor_vm()
{
delete_contexts();
if(signal_callstack_seg)
{
delete signal_callstack_seg;
signal_callstack_seg = NULL;
}
}
}
| 14.424242 | 34 | 0.739496 | doublec |
e9c4c2b25e8f5e92ed11ca35cf6712136c1c9d49 | 679 | hpp | C++ | XMLSet.hpp | rherardi/xmlset | f9e9071d6745e08cd7d43c34a052a452f29bc40c | [
"Apache-2.0"
] | null | null | null | XMLSet.hpp | rherardi/xmlset | f9e9071d6745e08cd7d43c34a052a452f29bc40c | [
"Apache-2.0"
] | null | null | null | XMLSet.hpp | rherardi/xmlset | f9e9071d6745e08cd7d43c34a052a452f29bc40c | [
"Apache-2.0"
] | null | null | null | // XMLSet.hpp: interface for the CXMLSet class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_XMLSET_HPP__90BFB3A4_5935_48EB_AE2E_014859F49591__INCLUDED_)
#define AFX_XMLSET_HPP__90BFB3A4_5935_48EB_AE2E_014859F49591__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CXMLProc;
class CXMLSet
{
public:
CXMLSet();
virtual ~CXMLSet();
int ProcessCommandLine(int argc, _TCHAR *argv[]);
int MakeConfigChange();
protected:
CXMLProc *m_xmlProc;
bool m_verbose;
void ShowUsage();
};
#endif // !defined(AFX_XMLSET_HPP__90BFB3A4_5935_48EB_AE2E_014859F49591__INCLUDED_)
| 21.21875 | 84 | 0.66863 | rherardi |
e9c8711c0813dbd854f7a55dfb09ddf74d8541dc | 53 | hpp | C++ | src/boost_spirit_include_classic_sequence.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_spirit_include_classic_sequence.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_spirit_include_classic_sequence.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/spirit/include/classic_sequence.hpp>
| 26.5 | 52 | 0.830189 | miathedev |
e9ca0cc95dc0a8608948c8a3d0a40e3fee12d437 | 669 | cpp | C++ | src/sample/test_sample/test_io.cpp | autolaborcenter/PM1SDK | d91731d77c666bb642be5785c1a76d8effe5cf70 | [
"Apache-2.0"
] | 2 | 2019-07-15T12:44:52.000Z | 2021-03-24T04:59:01.000Z | src/sample/test_sample/test_io.cpp | autolaborcenter/PM1SDK | d91731d77c666bb642be5785c1a76d8effe5cf70 | [
"Apache-2.0"
] | null | null | null | src/sample/test_sample/test_io.cpp | autolaborcenter/PM1SDK | d91731d77c666bb642be5785c1a76d8effe5cf70 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <thread>
#include "../../main/internal/serial/serial_port.hh"
int main() {
try {
serial_port port("COM7", 115200);
std::thread([&port] {
uint8_t buffer[128]{};
while (true) {
auto actual = port.read(buffer, sizeof(buffer) - 1);
std::cout << std::string(buffer, buffer + actual) << std::endl;
}
}).detach();
const auto text = "0123456789 0123456789 0123456789";
while (true) port.send((uint8_t *) text, std::strlen(text));
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
}
}
| 29.086957 | 79 | 0.5142 | autolaborcenter |
e9ca91ef6601b832af9bc72e9fd132e92e1b6323 | 1,938 | cpp | C++ | UVA11045.cpp | MaSteve/UVA-problems | 3a240fcca02e24a9c850b7e86062f8581df6f95f | [
"MIT"
] | 17 | 2015-12-08T18:50:03.000Z | 2022-03-16T01:23:20.000Z | UVA11045.cpp | MaSteve/UVA-problems | 3a240fcca02e24a9c850b7e86062f8581df6f95f | [
"MIT"
] | null | null | null | UVA11045.cpp | MaSteve/UVA-problems | 3a240fcca02e24a9c850b7e86062f8581df6f95f | [
"MIT"
] | 6 | 2017-04-04T18:16:23.000Z | 2020-06-28T11:07:22.000Z | #include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
typedef vector<int> vi;
int N, M, mf, f, s, t, INF = 2000000;
int res[40][40];
vi p;
void augment(int v, int minEdge) {
if (v == s) {
f = minEdge;
return;
} else if (p[v] != -1) {
augment(p[v], min(minEdge, res[p[v]][v]));
res[p[v]][v] -= f; res[v][p[v]] += f;
}
}
inline int toi(string s) {
if (s == "XXL") return 1;
if (s == "XL") return 2;
if (s == "L") return 3;
if (s == "M") return 4;
if (s == "S") return 5;
if (s == "XS") return 6;
return -1;
}
int main() {
int T;
cin >> T;
while (T--) {
cin >> N >> M;
s = 0, t = 7 + M;
for (int i = 0; i < 8 + M; i++)
for (int j = 0; j < 8 + M; j++)
res[i][j] = 0;
for (int i = 1; i <= 6; i++) res[0][i] = res[i][0] = N/6;
for (int i = 0; i < M; i++) {
string s1, s2;
int s_1, s_2;
cin >> s1 >> s2;
s_1 = toi(s1), s_2 = toi(s2);
res[s_1][i+7] = res[i+7][s_1] = 1;
res[s_2][i+7] = res[i+7][s_2] = 1;
res[t][i+7] = res[i+7][t] = 1;
}
N = 8 + M;
mf = 0;
while (true) {
f = 0;
vi dist(N, INF); dist[s] = 0;
queue<int> q;
q.push(s);
p.assign(N, -1);
while (!q.empty()) {
int u = q.front(); q.pop();
if (u == t) break;
for (int v = 0; v < N; v++) {
if (res[u][v] > 0 && dist[v] == INF) {
dist[v] = dist[u] + 1, q.push(v), p[v] = u;
}
}
}
augment(t, INF);
if (f == 0) break;
mf += f;
}
if (mf == M) printf("YES\n");
else printf("NO\n");
}
return 0;
}
| 24.846154 | 67 | 0.356553 | MaSteve |
e9cd170ccc371ceb40cda2bb4e40b0797c2113b8 | 701 | cpp | C++ | Nonlinear/code/kaiseki/shin_kaiseki/CountBisection_re.cpp | ShuftBK/kaiseki_report | 84928313a8032727e0dc2f3cc925f536a5619b22 | [
"MIT"
] | null | null | null | Nonlinear/code/kaiseki/shin_kaiseki/CountBisection_re.cpp | ShuftBK/kaiseki_report | 84928313a8032727e0dc2f3cc925f536a5619b22 | [
"MIT"
] | null | null | null | Nonlinear/code/kaiseki/shin_kaiseki/CountBisection_re.cpp | ShuftBK/kaiseki_report | 84928313a8032727e0dc2f3cc925f536a5619b22 | [
"MIT"
] | null | null | null | /*
Bisection Method
*/
#include <stdio.h>
#include <math.h>
const double eps = pow(10.0, -15);
const double delta = pow(10.0, -15);
double count = 0;
double f(double x)
{
return (5 + exp((-6)*x) - 3 * x);
}
int main()
{
double a = -1000000000, b = 1000000000,c, fa, fc, diff, delf, prevc;
int n = 0;
printf("a=%f, b=%f \n", a, b);
do {
c = (a + b) / 2; fc = f(c); fa = f(a);
if (fc*fa < 0) b = c;
else a = c;
prevc = c;
c = (a + b) / 2;
fc = f(c); fa = f(a);
diff = fabs(fc);
delf = fabs(c - prevc);
count++;
} while (diff >= eps || delf >= delta);
c = (a + b) / 2;
printf("a=%f, c=%f, b=%f, diff=%f, delf=%f \n", a, c, b, diff, delf);
printf("Count : %f\n", count);
}
| 18.447368 | 70 | 0.499287 | ShuftBK |
e9cd45d7581b6152d57c1e3671525a52796cc1b3 | 1,467 | hpp | C++ | core/LLVM/composite_decl.hpp | Chengifei/SySSFEs | 9e08715ed137d2405c051d9f74e9ab8bf18d4cbe | [
"Apache-2.0"
] | 1 | 2021-01-02T15:22:05.000Z | 2021-01-02T15:22:05.000Z | core/LLVM/composite_decl.hpp | Chengifei/SySSFEs | 9e08715ed137d2405c051d9f74e9ab8bf18d4cbe | [
"Apache-2.0"
] | null | null | null | core/LLVM/composite_decl.hpp | Chengifei/SySSFEs | 9e08715ed137d2405c051d9f74e9ab8bf18d4cbe | [
"Apache-2.0"
] | null | null | null | /* Copyright 2018 by Yifei Zheng
*
* 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 LLVM_COMPOSITE_DECL_HPP
#define LLVM_COMPOSITE_DECL_HPP
#include <vector>
#include <string>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/DerivedTypes.h>
#include <algorithm>
struct composite_decl_base {
std::vector<std::string> mem_names;
std::vector<support::type> mem_types;
protected:
composite_decl_base() {}
};
class composite_decl : private composite_decl_base {
public:
void add(std::string&& name, support::type tp) {
mem_names.push_back(std::move(name));
mem_types.push_back(tp);
}
std::size_t get_mem_idx(const std::string& str) const {
// FIXME: Handle not found cases, this is unsafe.
return std::find(mem_names.cbegin(), mem_names.cend(), str) - mem_names.cbegin();
}
const composite_decl_base& get() const {
return *this;
}
};
#endif
| 31.212766 | 89 | 0.709611 | Chengifei |
8397be110382af88f4d6763435be437bfe154c36 | 2,561 | cpp | C++ | test/cs/src/server.cpp | netplus/netplus | e3b621e65742f38733d3dcaa1873443da8bbd611 | [
"MIT"
] | 48 | 2021-02-22T03:10:40.000Z | 2022-03-29T03:26:33.000Z | test/cs/src/server.cpp | netplus/netplus | e3b621e65742f38733d3dcaa1873443da8bbd611 | [
"MIT"
] | 7 | 2021-03-20T09:25:11.000Z | 2022-03-07T03:26:56.000Z | test/cs/src/server.cpp | netplus/netplus | e3b621e65742f38733d3dcaa1873443da8bbd611 | [
"MIT"
] | 13 | 2021-02-25T01:49:58.000Z | 2022-03-21T00:30:34.000Z | #include <netp.hpp>
class example_handler :
public netp::channel_handler_abstract
{
public:
example_handler() :
channel_handler_abstract(netp::CH_ACTIVITY|netp::CH_INBOUND_READ|netp::CH_OUTBOUND_WRITE)
{}
void read(NRP<netp::channel_handler_context> const& ctx, NRP<netp::packet> const& income) override
{
NETP_INFO("<<<: %u bytes", income->len() );
ctx->fire_read(income);
}
void write(NRP<netp::promise<int>> const& ch_promise,NRP<netp::channel_handler_context> const& ctx, NRP<netp::packet> const& outlet ) override
{
NETP_INFO(">>>: %u bytes", outlet->len() );
ctx->write(ch_promise,outlet);
}
void connected(NRP<netp::channel_handler_context> const& ctx) override {
NETP_INFO("connected: %d", ctx->ch->ch_id() );
ctx->fire_connected();
}
void closed(NRP<netp::channel_handler_context> const& ctx) override {
NETP_INFO("closed: %d", ctx->ch->ch_id());
ctx->fire_closed();
}
void read_closed(NRP<netp::channel_handler_context> const& ctx) override {
NETP_INFO("read_shutdowned: %d", ctx->ch->ch_id() );
ctx->close_write();
ctx->fire_read_closed();
}
void write_closed(NRP<netp::channel_handler_context> const& ctx) override {
NETP_INFO("write_shutdowned: %d", ctx->ch->ch_id());
ctx->close_read();
ctx->fire_write_closed();
}
};
class my_echo :
public netp::channel_handler_abstract
{
public:
my_echo() :
channel_handler_abstract(netp::CH_ACTIVITY_READ_CLOSED | netp::CH_INBOUND_READ)
{}
~my_echo() {}
void read(NRP<netp::channel_handler_context> const& ctx, NRP<netp::packet> const& income) override {
NRP<netp::promise<int>> ch_promise = ctx->write(income);
ch_promise->if_done([]( int const& wrt) {
NETP_INFO("write rt: %d", wrt);
});
}
void read_closed(NRP<netp::channel_handler_context> const& ctx) override {
ctx->close();
}
};
int main(int argc, char** argv) {
netp::app::instance()->init(argc,argv);
netp::app::instance()->start_loop();
NRP<netp::channel_listen_promise> f_listen = netp::listen_on( "tcp://0.0.0.0:22310", [](NRP<netp::channel> const& ch) {
ch->pipeline()->add_last(netp::make_ref<example_handler>());
ch->pipeline()->add_last(netp::make_ref<my_echo>());
});
int listenrt = std::get<0>(f_listen->get());
if (listenrt != netp::OK) {
return listenrt;
}
NRP<netp::channel> ch = std::get<1>(f_listen->get());
netp::app::instance()->wait();
ch->ch_close();
ch->ch_close_promise()->wait();
NETP_ASSERT(ch->ch_close_promise()->is_done());
NETP_INFO("lsocket closed close: %d", ch->ch_close_promise()->get());
return netp::OK;
} | 28.455556 | 144 | 0.687232 | netplus |
839a991059ce0fc5f1a5cac4daa525f78123413f | 5,835 | hpp | C++ | src/SkinnedMesh.hpp | vadosnaprimer/desktop-m3g | fa04787e8609cd0f4e63defc7f2c669c8cc78d1f | [
"MIT"
] | 2 | 2019-05-14T08:14:15.000Z | 2021-01-19T13:28:38.000Z | src/SkinnedMesh.hpp | vadosnaprimer/desktop-m3g | fa04787e8609cd0f4e63defc7f2c669c8cc78d1f | [
"MIT"
] | null | null | null | src/SkinnedMesh.hpp | vadosnaprimer/desktop-m3g | fa04787e8609cd0f4e63defc7f2c669c8cc78d1f | [
"MIT"
] | null | null | null | #ifndef __M3G_SKINNED_MESH_HPP__
#define __M3G_SKINNED_MESH_HPP__
#include "m3g/Mesh.hpp"
#include "m3g/BoneWeight.hpp"
#include <iosfwd>
#include <vector>
namespace m3g {
class Group;
class VertexBuffer;
class IndexBuffer;
class RayIntersection;
class Vector;
/**
* @~English A scene graph node that represents a skeletally animated polygon mesh.
* @~Japanese スケレタルアニメーションつきのポリゴンメッシュを表すシーングラフノード.
*/
class SkinnedMesh : public Mesh
{
public:
/**
* @~English Constructs a new SkinnedMesh witdh the given vertices, submeshes and skeleton.
* @~Japanese 指定された頂点、サブメッシュ、スケルトンを持つSkinnedMeshを新しく作成する.
* @param[in] vertices 頂点バッファーデータ.
* @param[in] num_submesh 頂点インデックスの配列の個数.
* @param[in] submeshes 頂点インデックスの配列.
* @param[in] num_appearance アピアランスの配列の個数.
* @param[in] appearances アピアランスの配列.
* @param[in] skeleton スケルトン.
*/
SkinnedMesh (VertexBuffer* vertices ,
int num_submesh ,
IndexBuffer** submeshes ,
int num_appearance,
Appearance** apperarances ,
Group* skeleton );
/**
* @~English Constructs a new SkinnedMesh witdh the given vertices, submeshes and skeleton.
* @~Japanese 指定された頂点、サブメッシュ、スケルトンを持つSkinnedMeshを新しく作成する.
* @param[in] vertices 頂点バッファーデータ.
* @param[in] submesh 頂点インデックス.
* @param[in] appearance アピアランス.
* @param[in] skeleton スケルトン.
*/
SkinnedMesh (VertexBuffer* vertices ,
IndexBuffer* submesh ,
Appearance* apperarance ,
Group* skeleton );
/**
* @~English Destructs this object.
* @~Japanese このオブジェクトを削除するデストラクタ.
*/
virtual ~SkinnedMesh ();
/**
* @~English Creates a duplicate of this Object3D.
* @~Japanese このオブジェクトの複製の作成.
* @return 複製されたSkinnedMeshオブジェクト.
*/
SkinnedMesh* duplicate () const;
/**
* @~English Associates a weighted transformation, or "bone", with a range of vertices int this SkinnedMesh.
* @~Japanese このスキンメッシュの持つ頂点配列に対してボーンによる変形を設定する.
* @param[in] bone 変形の元になるボーンノード.
* @param[in] weight ウェイト値.
* @param[in] first_vertex 変形を設定する最初の頂点番号.
* @param[in] num_vertices 変形を設定する頂点の個数.
*/
void addTransform (Node* bone, int weight, int first_vertex, int num_vertices);
/**
* @~English Returns the at-rest tarnsformation (from local coordinate to bone coordinate) for a bone node.
* @~Japanese ボーンノードの基本姿勢の変形(ローカル座標系からボーン座標系への変換行列)を返す.
* @param[in] bone 変形行列を求めたいボーンノード.
* @param[out] tranform 結果を書き込むTransformオブジェクト.
*/
void getBoneTransform (Node* bone, Transform* transform) const;
/**
* @~English Returns the number of vertices influenced by the given bone, filling in the vertices and their weights to given arrays.
* @~Japanese 指定されたボーンに影響を受ける頂点の数を返す。与えられた配列に頂点のインデックスとウェイト値が入る.
* @param[in] bone 変形行列を求めたいボーンノード.
* @param[out] vertex_indices 結果を書き込む頂点インデックス配列.
* @param[out] weights 結果を書き込むウェイト値の配列.
*/
int getBoneVertices (Node* bone, int* vertex_indices, float* weights) const;
/**
* @~English Returns the skeleton Group of this SkinnedMesh.
* @~Japanese このスキンメッシュのスケルトンGroupを返す.
* @return スケルトンとしてセットされたGroupノード.
*/
Group* getSkeleton () const;
/**
* @~English
* @~Japanese
*/
virtual bool intersect (const Vector& org, const Vector& dir, RayIntersection* ri) const;
/**
* @~English Print out information of this class, for debug only.
* @~Japanese このSkinnedMeshクラスの情報を表示する。デバッグ用.
* @param[in] out 表示先のストリーム
*/
virtual std::ostream& print (std::ostream& out) const;
protected:
/**
* @~English
* @~Japanese
*/
virtual int animate_xxx (int world_time);
/**
* @~English
* @~Japanese
*/
virtual SkinnedMesh* duplicate_xxx (Object3D* obj) const;
/**
* @~English
* @~Japanese
*/
virtual int getReferences_xxx (Object3D** references) const;
/**
* @~English
* @~Japanese
*/
virtual void render_xxx (RenderState& state) const;
private:
/**
* @~English Register bone and retriev it's index.
* @~Japanese ボーンの登録とそのインデックスの取得.
*/
int addBoneIndex (Node* bone);
/**
* @~English Retriev bone index.
* @~Japanese ボーンインデックスの取得.
*/
int getBoneIndex (Node* bone) const;
/**
* @~English Update skin vertices.
* @~Japanese スキンの頂点を更新する.
*/
void updateSkinnedVertices ();
private:
/**
* @~English
* @~Japanese 共通初期化処理.
*/
void initialize ();
SkinnedMesh (const SkinnedMesh& mesh);
SkinnedMesh& operator= (const SkinnedMesh& mesh);
private:
Group* skeleton;
VertexBuffer* skinned_vertices;
std::vector<std::vector<BoneWeight> > bone_weights;
std::vector<BindPose> bind_poses;
};
} // namespace m3g {
std::ostream& operator<< (std::ostream& out, const m3g::SkinnedMesh& mesh);
#endif
| 30.07732 | 141 | 0.551671 | vadosnaprimer |
839dedc2311d040510fbab8d9b849e426dd7e4e5 | 1,103 | hpp | C++ | addons/ares_compositions/Ares/Military Structures/Camps/BIS Small Recon Camp.hpp | Braincrushy/TBMod | 785f11cd9cd0defb0d01a6d2861beb6c207eb8a3 | [
"MIT"
] | null | null | null | addons/ares_compositions/Ares/Military Structures/Camps/BIS Small Recon Camp.hpp | Braincrushy/TBMod | 785f11cd9cd0defb0d01a6d2861beb6c207eb8a3 | [
"MIT"
] | 4 | 2018-12-21T06:57:25.000Z | 2020-07-09T09:06:38.000Z | addons/ares_compositions/Ares/Military Structures/Camps/BIS Small Recon Camp.hpp | Braincrushy/TBMod | 785f11cd9cd0defb0d01a6d2861beb6c207eb8a3 | [
"MIT"
] | null | null | null | class Object0 {side=8;rank="";vehicle="Land_TentDome_F";position[]={0,0,0};dir=191.566;};
class Object1 {side=8;rank="";vehicle="Land_WoodenLog_F";position[]={2.67871,2.83691,1.90735e-006};dir=359.888;};
class Object2 {side=8;rank="";vehicle="Land_Canteen_F";position[]={6.58594,0.875977,3.24249e-005};dir=19.5592;};
class Object3 {side=8;rank="";vehicle="Land_Can_Rusty_F";position[]={4.63574,2.49609,5.14984e-005};dir=355.295;};
class Object4 {side=8;rank="";vehicle="Land_BakedBeans_F";position[]={4.35059,2.56055,1.14441e-005};dir=358.572;};
class Object5 {side=8;rank="";vehicle="Land_CerealsBox_F";position[]={4.41797,2.21582,8.58307e-005};dir=22.653;};
class Object6 {side=8;rank="";vehicle="Land_TentDome_F";position[]={5.51172,-0.626953,-0.00367546};dir=46.6942;};
class Object7 {side=8;rank="";vehicle="Land_Canteen_F";position[]={1.65918,1.69727,3.05176e-005};dir=19.4252;};
class Object8 {side=8;rank="";vehicle="Land_SurvivalRadio_F";position[]={1.74512,1.33594,-9.53674e-006};dir=85.6447;};
class Object9 {side=8;rank="";vehicle="Land_TentDome_F";position[]={2.25,6.37793,0};dir=263.207;}; | 110.3 | 118 | 0.723481 | Braincrushy |
83a14fbfd7ba3dad096162365e523b2a4eb676a9 | 24,540 | cpp | C++ | src/plugPikiYamashita/drawCountDown.cpp | doldecomp/pikmin | 8c8c20721ecb2a19af8e50a4bdebdba90c9a27ed | [
"Unlicense"
] | 27 | 2021-09-28T00:33:11.000Z | 2021-11-18T19:38:40.000Z | src/plugPikiYamashita/drawCountDown.cpp | doldecomp/pikmin | 8c8c20721ecb2a19af8e50a4bdebdba90c9a27ed | [
"Unlicense"
] | null | null | null | src/plugPikiYamashita/drawCountDown.cpp | doldecomp/pikmin | 8c8c20721ecb2a19af8e50a4bdebdba90c9a27ed | [
"Unlicense"
] | null | null | null | #include "types.h"
/*
* --INFO--
* Address: ........
* Size: 00009C
*/
void _Error(char*, ...)
{
// UNUSED FUNCTION
}
/*
* --INFO--
* Address: ........
* Size: 0000F4
*/
void _Print(char*, ...)
{
// UNUSED FUNCTION
}
/*
* --INFO--
* Address: 801E7AB0
* Size: 0001F8
*/
zen::DrawCountDown::DrawCountDown()
{
/*
.loc_0x0:
mflr r0
stw r0, 0x4(r1)
stwu r1, -0x70(r1)
stw r31, 0x6C(r1)
stw r30, 0x68(r1)
stw r29, 0x64(r1)
addi r29, r3, 0
li r3, 0x100
bl -0x1A0ACC
addi r30, r3, 0
mr. r3, r30
beq- .loc_0x48
lis r4, 0x802E
addi r4, r4, 0x5A38
li r5, 0
li r6, 0
li r7, 0
bl -0x28580
.loc_0x48:
stw r30, 0x0(r29)
li r31, 0
li r3, 0x2C
stw r31, 0xC(r29)
bl -0x1A0B04
stw r3, 0x8(r29)
li r30, 0
.loc_0x64:
addi r3, r1, 0x54
crclr 6, 0x6
subfic r5, r30, 0xA
addi r4, r13, 0x2680
bl 0x2EA74
lwz r3, 0x0(r29)
li r5, 0x1
lwzu r12, 0x4(r3)
lbz r0, 0x55(r1)
lwz r12, 0x34(r12)
lbz r4, 0x54(r1)
rlwinm r0,r0,16,0,15
lbz r6, 0x56(r1)
mtlr r12
rlwimi r0,r4,24,0,7
lbz r7, 0x57(r1)
rlwimi r0,r6,8,16,23
or r4, r7, r0
blrl
lhz r0, 0x8(r3)
cmplwi r0, 0x12
bne- .loc_0x120
lwz r5, 0x8(r29)
li r4, 0
stwx r3, r5, r31
lwz r3, 0x8(r29)
lwzx r3, r3, r31
stb r4, 0xF0(r3)
lwz r3, 0x8(r29)
lwzx r3, r3, r31
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
lwz r3, 0x8(r29)
lwzx r5, r3, r31
lha r3, 0x18(r5)
lha r0, 0x1C(r5)
lha r4, 0x1A(r5)
sub r0, r0, r3
lha r3, 0x1E(r5)
srawi r0, r0, 0x1
sub r4, r3, r4
extsh r3, r0
srawi r0, r4, 0x1
sth r3, 0xB8(r5)
extsh r0, r0
sth r0, 0xBA(r5)
.loc_0x120:
addi r30, r30, 0x1
cmpwi r30, 0xB
addi r31, r31, 0x4
blt+ .loc_0x64
lwz r5, 0x0(r29)
lis r3, 0x6761
addi r4, r3, 0x7468
lwz r12, 0x4(r5)
addi r3, r5, 0x4
li r5, 0x1
lwz r12, 0x34(r12)
mtlr r12
blrl
lhz r0, 0x8(r3)
cmplwi r0, 0x12
bne- .loc_0x178
stw r3, 0x4(r29)
li r4, 0
lwz r3, 0x4(r29)
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
.loc_0x178:
lfs f0, -0x40A0(r2)
li r0, 0x7F
addi r3, r29, 0
stfs f0, 0x10(r29)
lfs f0, -0x409C(r2)
stfs f0, 0x14(r29)
stb r0, 0x24(r29)
lfs f1, -0x4098(r2)
lfs f2, -0x4094(r2)
lfs f3, -0x4090(r2)
bl .loc_0x1F8
li r5, 0xFF
stb r5, 0x25(r29)
li r0, 0x99
li r4, 0
stb r0, 0x26(r29)
li r0, 0x1
addi r3, r29, 0
stb r4, 0x27(r29)
stb r5, 0x28(r29)
stb r5, 0x29(r29)
stb r5, 0x2A(r29)
stb r5, 0x2B(r29)
stb r5, 0x2C(r29)
stb r0, 0x2D(r29)
lwz r0, 0x74(r1)
lwz r31, 0x6C(r1)
lwz r30, 0x68(r1)
lwz r29, 0x64(r1)
addi r1, r1, 0x70
mtlr r0
blr
.loc_0x1F8:
*/
}
/*
* --INFO--
* Address: 801E7CA8
* Size: 000010
*/
void zen::DrawCountDown::setRate(float, float, float)
{
/*
.loc_0x0:
stfs f1, 0x18(r3)
stfs f2, 0x1C(r3)
stfs f3, 0x20(r3)
blr
*/
}
/*
* --INFO--
* Address: 801E7CB8
* Size: 0001A8
*/
void zen::DrawCountDown::init(float, float, float*)
{
/*
.loc_0x0:
stw r4, 0x30(r3)
li r0, 0
li r6, 0x7F
stfs f1, 0x10(r3)
li r5, 0x1
li r4, 0x8
stfs f2, 0x14(r3)
stw r0, 0xC(r3)
stb r6, 0x24(r3)
lfs f0, -0x4098(r2)
stfs f0, 0x18(r3)
lfs f0, -0x4094(r2)
stfs f0, 0x1C(r3)
lfs f0, -0x4090(r2)
stfs f0, 0x20(r3)
stb r5, 0x2D(r3)
lwz r5, 0x8(r3)
lwz r5, 0x0(r5)
stb r0, 0xF0(r5)
lwz r5, 0x8(r3)
lwz r6, 0x0(r5)
lbz r5, 0xC(r6)
rlwimi r5,r0,7,24,24
stb r5, 0xC(r6)
lwz r5, 0x8(r3)
lwz r5, 0x4(r5)
stb r0, 0xF0(r5)
lwz r5, 0x8(r3)
lwz r6, 0x4(r5)
lbz r5, 0xC(r6)
rlwimi r5,r0,7,24,24
stb r5, 0xC(r6)
lwz r5, 0x8(r3)
lwz r5, 0x8(r5)
stb r0, 0xF0(r5)
lwz r5, 0x8(r3)
lwz r6, 0x8(r5)
lbz r5, 0xC(r6)
rlwimi r5,r0,7,24,24
stb r5, 0xC(r6)
lwz r5, 0x8(r3)
lwz r5, 0xC(r5)
stb r0, 0xF0(r5)
lwz r5, 0x8(r3)
lwz r6, 0xC(r5)
lbz r5, 0xC(r6)
rlwimi r5,r0,7,24,24
stb r5, 0xC(r6)
lwz r5, 0x8(r3)
lwz r5, 0x10(r5)
stb r0, 0xF0(r5)
lwz r5, 0x8(r3)
lwz r6, 0x10(r5)
lbz r5, 0xC(r6)
rlwimi r5,r0,7,24,24
stb r5, 0xC(r6)
lwz r5, 0x8(r3)
lwz r5, 0x14(r5)
stb r0, 0xF0(r5)
lwz r5, 0x8(r3)
lwz r6, 0x14(r5)
lbz r5, 0xC(r6)
rlwimi r5,r0,7,24,24
stb r5, 0xC(r6)
lwz r5, 0x8(r3)
lwz r5, 0x18(r5)
stb r0, 0xF0(r5)
lwz r5, 0x8(r3)
lwz r6, 0x18(r5)
lbz r5, 0xC(r6)
rlwimi r5,r0,7,24,24
stb r5, 0xC(r6)
lwz r5, 0x8(r3)
lwz r5, 0x1C(r5)
stb r0, 0xF0(r5)
lwz r5, 0x8(r3)
lwz r6, 0x1C(r5)
lbz r5, 0xC(r6)
rlwimi r5,r0,7,24,24
stb r5, 0xC(r6)
b .loc_0x19C
.loc_0x144:
subfic r5, r4, 0xB
cmpwi r4, 0xB
mtctr r5
bge- .loc_0x17C
.loc_0x154:
lwz r4, 0x8(r3)
lwzx r4, r4, r6
stb r0, 0xF0(r4)
lwz r4, 0x8(r3)
lwzx r5, r4, r6
addi r6, r6, 0x4
lbz r4, 0xC(r5)
rlwimi r4,r0,7,24,24
stb r4, 0xC(r5)
bdnz+ .loc_0x154
.loc_0x17C:
lwz r5, 0x4(r3)
li r6, 0
li r0, -0x1
lbz r4, 0xC(r5)
rlwimi r4,r6,7,24,24
stb r4, 0xC(r5)
stw r0, 0x34(r3)
blr
.loc_0x19C:
rlwinm r6,r4,2,0,29
b .loc_0x144
blr
*/
}
/*
* --INFO--
* Address: 801E7E60
* Size: 000A70
*/
void zen::DrawCountDown::update()
{
/*
.loc_0x0:
mflr r0
stw r0, 0x4(r1)
stwu r1, -0x160(r1)
stfd f31, 0x158(r1)
stfd f30, 0x150(r1)
stw r31, 0x14C(r1)
stw r30, 0x148(r1)
stw r29, 0x144(r1)
mr r29, r3
lwz r3, 0x30(r3)
cmplwi r3, 0
beq- .loc_0x38
lfs f0, 0x0(r3)
b .loc_0x44
.loc_0x38:
lis r3, 0x803A
subi r3, r3, 0x2848
lfs f0, 0x2F0(r3)
.loc_0x44:
lfs f2, 0x10(r29)
fcmpo cr0, f0, f2
cror 2, 0x1, 0x2
bne- .loc_0x944
lfs f3, 0x14(r29)
fcmpo cr0, f0, f3
bge- .loc_0x944
fsubs f1, f0, f2
lfs f5, -0x408C(r2)
fsubs f0, f3, f2
lis r3, 0x4330
lfd f4, -0x4068(r2)
fdivs f6, f1, f0
lfs f1, -0x4084(r2)
lfs f2, -0x4088(r2)
lwz r0, 0x34(r29)
fdivs f0, f6, f5
fctiwz f0, f0
stfd f0, 0x138(r1)
lwz r30, 0x13C(r1)
xoris r4, r30, 0x8000
stw r4, 0x134(r1)
subfic r31, r30, 0xB
cmpw r31, r0
stw r3, 0x130(r1)
lfd f0, 0x130(r1)
stw r4, 0x12C(r1)
fsubs f0, f0, f4
stw r3, 0x128(r1)
fmuls f3, f5, f0
lfd f0, 0x128(r1)
fsubs f0, f0, f4
fsubs f3, f6, f3
fmuls f0, f1, f0
fdivs f30, f3, f5
fadds f31, f2, f0
beq- .loc_0x104
cmpwi r31, 0x2
bne- .loc_0x104
lis r3, 0x803A
subi r3, r3, 0x2848
lwz r3, 0x1E8(r3)
li r4, 0xF
li r5, 0
lwz r12, 0x0(r3)
lwz r12, 0x8(r12)
mtlr r12
blrl
.loc_0x104:
lis r3, 0x803A
subi r3, r3, 0x2848
lwz r0, 0x2B4(r3)
cmpwi r0, 0
bne- .loc_0x130
lwz r3, 0x4(r29)
li r4, 0x1
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
b .loc_0x144
.loc_0x130:
lwz r3, 0x4(r29)
li r4, 0
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
.loc_0x144:
lwz r4, 0xC(r29)
cmplwi r4, 0
beq- .loc_0x160
lbz r0, 0xC(r4)
li r3, 0
rlwimi r0,r3,7,24,24
stb r0, 0xC(r4)
.loc_0x160:
lwz r3, 0x8(r29)
rlwinm r0,r30,2,0,29
li r4, 0x1
lwzx r0, r3, r0
stw r0, 0xC(r29)
lwz r3, 0xC(r29)
lbz r0, 0xC(r3)
rlwimi r0,r4,7,24,24
stb r0, 0xC(r3)
lfs f1, 0x18(r29)
fcmpo cr0, f30, f1
bge- .loc_0x1D4
lwz r3, 0xC(r29)
li r0, 0
cmpwi r30, 0
stb r0, 0xF0(r3)
ble- .loc_0x1C0
lwz r3, 0x4(r29)
lwz r0, 0x25(r29)
stw r0, 0x108(r3)
lbz r0, 0x24(r29)
lwz r3, 0x4(r29)
stb r0, 0xF0(r3)
b .loc_0x1C8
.loc_0x1C0:
lwz r3, 0x4(r29)
stb r0, 0xF0(r3)
.loc_0x1C8:
li r0, 0x1
stb r0, 0x2D(r29)
b .loc_0x93C
.loc_0x1D4:
lfs f4, 0x1C(r29)
fadds f0, f4, f1
fcmpo cr0, f30, f0
bge- .loc_0x584
fsubs f1, f30, f1
lfs f2, -0x407C(r2)
lfs f3, -0x4080(r2)
lfs f0, -0x4078(r2)
fmuls f1, f2, f1
fdivs f1, f1, f4
fmuls f1, f3, f1
fdivs f1, f1, f0
bl 0x33C84
lbz r3, 0x24(r29)
lis r0, 0x4330
lfs f0, -0x4074(r2)
stw r3, 0x12C(r1)
lfd f4, -0x4060(r2)
fsubs f0, f0, f1
stw r0, 0x128(r1)
lfs f2, -0x4070(r2)
lfd f3, 0x128(r1)
fsubs f3, f3, f4
fmuls f3, f3, f1
fcmpo cr0, f3, f2
cror 2, 0x1, 0x2
bne- .loc_0x24C
lfs f2, -0x406C(r2)
fadds f2, f2, f3
b .loc_0x254
.loc_0x24C:
lfs f2, -0x406C(r2)
fsubs f2, f3, f2
.loc_0x254:
fctiwz f2, f2
lwz r3, 0xC(r29)
fmuls f3, f31, f1
lis r0, 0x4330
stfd f2, 0x128(r1)
lwz r4, 0x12C(r1)
stb r4, 0xF0(r3)
lwz r3, 0xC(r29)
stfs f3, 0xC0(r3)
stfs f3, 0xC4(r3)
lfs f2, -0x4074(r2)
stfs f2, 0xC8(r3)
lbz r3, 0x27(r29)
lbz r4, 0x2B(r29)
stw r3, 0x13C(r1)
lfd f5, -0x4060(r2)
stw r4, 0x134(r1)
lfs f2, -0x4070(r2)
stw r0, 0x130(r1)
stw r0, 0x138(r1)
lfd f4, 0x130(r1)
lfd f3, 0x138(r1)
fsubs f4, f4, f5
fsubs f3, f3, f5
fmuls f4, f4, f1
fmuls f3, f3, f0
fadds f3, f4, f3
fcmpo cr0, f3, f2
cror 2, 0x1, 0x2
bne- .loc_0x304
stw r4, 0x12C(r1)
lfs f4, -0x406C(r2)
stw r3, 0x134(r1)
stw r0, 0x128(r1)
stw r0, 0x130(r1)
lfd f3, 0x128(r1)
lfd f2, 0x130(r1)
fsubs f3, f3, f5
fsubs f2, f2, f5
fmuls f3, f3, f1
fmuls f2, f2, f0
fadds f2, f3, f2
fadds f2, f4, f2
b .loc_0x338
.loc_0x304:
stw r4, 0x12C(r1)
lfs f2, -0x406C(r2)
stw r3, 0x134(r1)
stw r0, 0x128(r1)
stw r0, 0x130(r1)
lfd f4, 0x128(r1)
lfd f3, 0x130(r1)
fsubs f4, f4, f5
fsubs f3, f3, f5
fmuls f4, f4, f1
fmuls f3, f3, f0
fadds f3, f4, f3
fsubs f2, f3, f2
.loc_0x338:
lbz r5, 0x26(r29)
fctiwz f6, f2
lbz r6, 0x2A(r29)
lis r0, 0x4330
stw r5, 0x13C(r1)
lfd f5, -0x4060(r2)
stw r6, 0x134(r1)
lfs f2, -0x4070(r2)
stw r0, 0x130(r1)
stw r0, 0x138(r1)
lfd f4, 0x130(r1)
lfd f3, 0x138(r1)
fsubs f4, f4, f5
stfd f6, 0x128(r1)
fsubs f3, f3, f5
lwz r3, 0x12C(r1)
fmuls f4, f4, f1
fmuls f3, f3, f0
rlwinm r4,r3,0,24,31
fadds f3, f4, f3
fcmpo cr0, f3, f2
cror 2, 0x1, 0x2
bne- .loc_0x3CC
stw r6, 0x12C(r1)
lfs f4, -0x406C(r2)
stw r5, 0x134(r1)
stw r0, 0x128(r1)
stw r0, 0x130(r1)
lfd f3, 0x128(r1)
lfd f2, 0x130(r1)
fsubs f3, f3, f5
fsubs f2, f2, f5
fmuls f3, f3, f1
fmuls f2, f2, f0
fadds f2, f3, f2
fadds f2, f4, f2
b .loc_0x400
.loc_0x3CC:
stw r6, 0x12C(r1)
lfs f2, -0x406C(r2)
stw r5, 0x134(r1)
stw r0, 0x128(r1)
stw r0, 0x130(r1)
lfd f4, 0x128(r1)
lfd f3, 0x130(r1)
fsubs f4, f4, f5
fsubs f3, f3, f5
fmuls f4, f4, f1
fmuls f3, f3, f0
fadds f3, f4, f3
fsubs f2, f3, f2
.loc_0x400:
lbz r6, 0x25(r29)
fctiwz f6, f2
lbz r7, 0x29(r29)
lis r0, 0x4330
stw r6, 0x13C(r1)
lfd f5, -0x4060(r2)
stw r7, 0x134(r1)
lfs f2, -0x4070(r2)
stw r0, 0x130(r1)
stw r0, 0x138(r1)
lfd f4, 0x130(r1)
lfd f3, 0x138(r1)
fsubs f4, f4, f5
stfd f6, 0x128(r1)
fsubs f3, f3, f5
lwz r3, 0x12C(r1)
fmuls f4, f4, f1
fmuls f3, f3, f0
rlwinm r5,r3,0,24,31
fadds f3, f4, f3
fcmpo cr0, f3, f2
cror 2, 0x1, 0x2
bne- .loc_0x494
stw r7, 0x12C(r1)
lfs f4, -0x406C(r2)
stw r6, 0x134(r1)
stw r0, 0x128(r1)
stw r0, 0x130(r1)
lfd f3, 0x128(r1)
lfd f2, 0x130(r1)
fsubs f3, f3, f5
fsubs f2, f2, f5
fmuls f3, f3, f1
fmuls f0, f2, f0
fadds f0, f3, f0
fadds f0, f4, f0
b .loc_0x4C8
.loc_0x494:
stw r7, 0x12C(r1)
lfs f2, -0x406C(r2)
stw r6, 0x134(r1)
stw r0, 0x128(r1)
stw r0, 0x130(r1)
lfd f4, 0x128(r1)
lfd f3, 0x130(r1)
fsubs f4, f4, f5
fsubs f3, f3, f5
fmuls f4, f4, f1
fmuls f0, f3, f0
fadds f0, f4, f0
fsubs f0, f0, f2
.loc_0x4C8:
fctiwz f0, f0
li r0, 0xFF
cmpwi r30, 0
stfd f0, 0x128(r1)
lwz r3, 0x12C(r1)
stb r3, 0x114(r1)
stb r5, 0x115(r1)
stb r4, 0x116(r1)
stb r0, 0x117(r1)
lwz r3, 0x4(r29)
lwz r0, 0x114(r1)
stw r0, 0x108(r3)
ble- .loc_0x50C
lbz r0, 0x24(r29)
lwz r3, 0x4(r29)
stb r0, 0xF0(r3)
b .loc_0x564
.loc_0x50C:
lbz r3, 0x24(r29)
lis r0, 0x4330
lfd f3, -0x4060(r2)
stw r3, 0x12C(r1)
lfs f0, -0x4070(r2)
stw r0, 0x128(r1)
lfd f2, 0x128(r1)
fsubs f2, f2, f3
fmuls f1, f2, f1
fcmpo cr0, f1, f0
cror 2, 0x1, 0x2
bne- .loc_0x548
lfs f0, -0x406C(r2)
fadds f0, f0, f1
b .loc_0x550
.loc_0x548:
lfs f0, -0x406C(r2)
fsubs f0, f1, f0
.loc_0x550:
fctiwz f0, f0
lwz r3, 0x4(r29)
stfd f0, 0x128(r1)
lwz r0, 0x12C(r1)
stb r0, 0xF0(r3)
.loc_0x564:
lbz r0, 0x2D(r29)
cmplwi r0, 0
beq- .loc_0x93C
li r3, 0x115
bl -0x143060
li r0, 0
stb r0, 0x2D(r29)
b .loc_0x93C
.loc_0x584:
lfs f1, -0x4074(r2)
lfs f2, 0x20(r29)
fsubs f0, f1, f2
fcmpo cr0, f30, f0
ble- .loc_0x908
fsubs f0, f30, f0
lbz r3, 0x24(r29)
lis r0, 0x4330
lfd f4, -0x4060(r2)
stw r3, 0x12C(r1)
fdivs f0, f0, f2
stw r0, 0x128(r1)
lfs f2, -0x4070(r2)
lfd f3, 0x128(r1)
fsubs f1, f1, f0
fsubs f3, f3, f4
fmuls f3, f3, f1
fcmpo cr0, f3, f2
cror 2, 0x1, 0x2
bne- .loc_0x5E0
lfs f2, -0x406C(r2)
fadds f2, f2, f3
b .loc_0x5E8
.loc_0x5E0:
lfs f2, -0x406C(r2)
fsubs f2, f3, f2
.loc_0x5E8:
fctiwz f2, f2
lwz r3, 0xC(r29)
lis r0, 0x4330
stfd f2, 0x128(r1)
lwz r4, 0x12C(r1)
stb r4, 0xF0(r3)
lfs f6, -0x406C(r2)
lfs f3, -0x4074(r2)
fmuls f2, f6, f0
lwz r3, 0xC(r29)
fadds f2, f3, f2
fmuls f2, f31, f2
stfs f2, 0xC0(r3)
stfs f2, 0xC4(r3)
stfs f3, 0xC8(r3)
lbz r3, 0x27(r29)
lbz r4, 0x2B(r29)
stw r3, 0x13C(r1)
lfd f5, -0x4060(r2)
stw r4, 0x134(r1)
lfs f2, -0x4070(r2)
stw r0, 0x130(r1)
stw r0, 0x138(r1)
lfd f4, 0x130(r1)
lfd f3, 0x138(r1)
fsubs f4, f4, f5
fsubs f3, f3, f5
fmuls f4, f4, f1
fmuls f3, f3, f0
fadds f3, f4, f3
fcmpo cr0, f3, f2
cror 2, 0x1, 0x2
bne- .loc_0x6A0
stw r4, 0x12C(r1)
stw r3, 0x134(r1)
stw r0, 0x128(r1)
stw r0, 0x130(r1)
lfd f3, 0x128(r1)
lfd f2, 0x130(r1)
fsubs f3, f3, f5
fsubs f2, f2, f5
fmuls f3, f3, f1
fmuls f2, f2, f0
fadds f2, f3, f2
fadds f2, f6, f2
b .loc_0x6D0
.loc_0x6A0:
stw r4, 0x12C(r1)
stw r3, 0x134(r1)
stw r0, 0x128(r1)
stw r0, 0x130(r1)
lfd f3, 0x128(r1)
lfd f2, 0x130(r1)
fsubs f3, f3, f5
fsubs f2, f2, f5
fmuls f3, f3, f1
fmuls f2, f2, f0
fadds f2, f3, f2
fsubs f2, f2, f6
.loc_0x6D0:
lbz r5, 0x26(r29)
fctiwz f6, f2
lbz r6, 0x2A(r29)
lis r0, 0x4330
stw r5, 0x13C(r1)
lfd f5, -0x4060(r2)
stw r6, 0x134(r1)
lfs f2, -0x4070(r2)
stw r0, 0x130(r1)
stw r0, 0x138(r1)
lfd f4, 0x130(r1)
lfd f3, 0x138(r1)
fsubs f4, f4, f5
stfd f6, 0x128(r1)
fsubs f3, f3, f5
lwz r3, 0x12C(r1)
fmuls f4, f4, f1
fmuls f3, f3, f0
rlwinm r4,r3,0,24,31
fadds f3, f4, f3
fcmpo cr0, f3, f2
cror 2, 0x1, 0x2
bne- .loc_0x764
stw r6, 0x12C(r1)
lfs f4, -0x406C(r2)
stw r5, 0x134(r1)
stw r0, 0x128(r1)
stw r0, 0x130(r1)
lfd f3, 0x128(r1)
lfd f2, 0x130(r1)
fsubs f3, f3, f5
fsubs f2, f2, f5
fmuls f3, f3, f1
fmuls f2, f2, f0
fadds f2, f3, f2
fadds f2, f4, f2
b .loc_0x798
.loc_0x764:
stw r6, 0x12C(r1)
lfs f2, -0x406C(r2)
stw r5, 0x134(r1)
stw r0, 0x128(r1)
stw r0, 0x130(r1)
lfd f4, 0x128(r1)
lfd f3, 0x130(r1)
fsubs f4, f4, f5
fsubs f3, f3, f5
fmuls f4, f4, f1
fmuls f3, f3, f0
fadds f3, f4, f3
fsubs f2, f3, f2
.loc_0x798:
lbz r6, 0x25(r29)
fctiwz f6, f2
lbz r7, 0x29(r29)
lis r0, 0x4330
stw r6, 0x13C(r1)
lfd f5, -0x4060(r2)
stw r7, 0x134(r1)
lfs f2, -0x4070(r2)
stw r0, 0x130(r1)
stw r0, 0x138(r1)
lfd f4, 0x130(r1)
lfd f3, 0x138(r1)
fsubs f4, f4, f5
stfd f6, 0x128(r1)
fsubs f3, f3, f5
lwz r3, 0x12C(r1)
fmuls f4, f4, f1
fmuls f3, f3, f0
rlwinm r5,r3,0,24,31
fadds f3, f4, f3
fcmpo cr0, f3, f2
cror 2, 0x1, 0x2
bne- .loc_0x82C
stw r7, 0x12C(r1)
lfs f4, -0x406C(r2)
stw r6, 0x134(r1)
stw r0, 0x128(r1)
stw r0, 0x130(r1)
lfd f3, 0x128(r1)
lfd f2, 0x130(r1)
fsubs f3, f3, f5
fsubs f2, f2, f5
fmuls f3, f3, f1
fmuls f1, f2, f0
fadds f1, f3, f1
fadds f1, f4, f1
b .loc_0x860
.loc_0x82C:
stw r7, 0x12C(r1)
lfs f2, -0x406C(r2)
stw r6, 0x134(r1)
stw r0, 0x128(r1)
stw r0, 0x130(r1)
lfd f4, 0x128(r1)
lfd f3, 0x130(r1)
fsubs f4, f4, f5
fsubs f3, f3, f5
fmuls f4, f4, f1
fmuls f1, f3, f0
fadds f1, f4, f1
fsubs f1, f1, f2
.loc_0x860:
fctiwz f1, f1
li r0, 0xFF
cmpwi r30, 0xA
stfd f1, 0x128(r1)
lwz r3, 0x12C(r1)
stb r3, 0x10C(r1)
stb r5, 0x10D(r1)
stb r4, 0x10E(r1)
stb r0, 0x10F(r1)
lwz r3, 0x4(r29)
lwz r0, 0x10C(r1)
stw r0, 0x108(r3)
bne- .loc_0x8F8
lbz r3, 0x24(r29)
lis r0, 0x4330
lfs f1, -0x4074(r2)
stw r3, 0x12C(r1)
lfd f3, -0x4060(r2)
fsubs f1, f1, f0
stw r0, 0x128(r1)
lfs f0, -0x4070(r2)
lfd f2, 0x128(r1)
fsubs f2, f2, f3
fmuls f1, f2, f1
fcmpo cr0, f1, f0
cror 2, 0x1, 0x2
bne- .loc_0x8D8
lfs f0, -0x406C(r2)
fadds f0, f0, f1
b .loc_0x8E0
.loc_0x8D8:
lfs f0, -0x406C(r2)
fsubs f0, f1, f0
.loc_0x8E0:
fctiwz f0, f0
lwz r3, 0x4(r29)
stfd f0, 0x128(r1)
lwz r0, 0x12C(r1)
stb r0, 0xF0(r3)
b .loc_0x93C
.loc_0x8F8:
lbz r0, 0x24(r29)
lwz r3, 0x4(r29)
stb r0, 0xF0(r3)
b .loc_0x93C
.loc_0x908:
lbz r0, 0x24(r29)
lwz r3, 0xC(r29)
stb r0, 0xF0(r3)
lwz r3, 0xC(r29)
stfs f31, 0xC0(r3)
stfs f31, 0xC4(r3)
stfs f31, 0xC8(r3)
lwz r3, 0x4(r29)
lwz r0, 0x29(r29)
stw r0, 0x108(r3)
lbz r0, 0x24(r29)
lwz r3, 0x4(r29)
stb r0, 0xF0(r3)
.loc_0x93C:
stw r31, 0x34(r29)
b .loc_0xA2C
.loc_0x944:
lwz r5, 0x4(r29)
li r0, 0
li r3, 0x8
lbz r4, 0xC(r5)
rlwimi r4,r0,7,24,24
stb r4, 0xC(r5)
lwz r4, 0x8(r29)
lwz r5, 0x0(r4)
lbz r4, 0xC(r5)
rlwimi r4,r0,7,24,24
stb r4, 0xC(r5)
lwz r4, 0x8(r29)
lwz r5, 0x4(r4)
lbz r4, 0xC(r5)
rlwimi r4,r0,7,24,24
stb r4, 0xC(r5)
lwz r4, 0x8(r29)
lwz r5, 0x8(r4)
lbz r4, 0xC(r5)
rlwimi r4,r0,7,24,24
stb r4, 0xC(r5)
lwz r4, 0x8(r29)
lwz r5, 0xC(r4)
lbz r4, 0xC(r5)
rlwimi r4,r0,7,24,24
stb r4, 0xC(r5)
lwz r4, 0x8(r29)
lwz r5, 0x10(r4)
lbz r4, 0xC(r5)
rlwimi r4,r0,7,24,24
stb r4, 0xC(r5)
lwz r4, 0x8(r29)
lwz r5, 0x14(r4)
lbz r4, 0xC(r5)
rlwimi r4,r0,7,24,24
stb r4, 0xC(r5)
lwz r4, 0x8(r29)
lwz r5, 0x18(r4)
lbz r4, 0xC(r5)
rlwimi r4,r0,7,24,24
stb r4, 0xC(r5)
lwz r4, 0x8(r29)
lwz r5, 0x1C(r4)
lbz r4, 0xC(r5)
rlwimi r4,r0,7,24,24
stb r4, 0xC(r5)
b .loc_0xA44
.loc_0xA00:
subfic r4, r3, 0xB
cmpwi r3, 0xB
mtctr r4
bge- .loc_0xA2C
.loc_0xA10:
lwz r3, 0x8(r29)
lwzx r4, r3, r5
addi r5, r5, 0x4
lbz r3, 0xC(r4)
rlwimi r3,r0,7,24,24
stb r3, 0xC(r4)
bdnz+ .loc_0xA10
.loc_0xA2C:
lwz r3, 0x0(r29)
lwz r12, 0x0(r3)
lwz r12, 0x8(r12)
mtlr r12
blrl
b .loc_0xA4C
.loc_0xA44:
rlwinm r5,r3,2,0,29
b .loc_0xA00
.loc_0xA4C:
lwz r0, 0x164(r1)
lfd f31, 0x158(r1)
lfd f30, 0x150(r1)
lwz r31, 0x14C(r1)
lwz r30, 0x148(r1)
lwz r29, 0x144(r1)
addi r1, r1, 0x160
mtlr r0
blr
*/
}
/*
* --INFO--
* Address: 801E88D0
* Size: 000030
*/
void zen::DrawCountDown::draw(Graphics&)
{
/*
.loc_0x0:
mflr r0
stw r0, 0x4(r1)
stwu r1, -0x8(r1)
lwz r3, 0x0(r3)
lwz r12, 0x0(r3)
lwz r12, 0xC(r12)
mtlr r12
blrl
lwz r0, 0xC(r1)
addi r1, r1, 0x8
mtlr r0
blr
*/
}
| 22.349727 | 53 | 0.454034 | doldecomp |
83a7d2fdcd34d873df9f2e6b02a82be66a1692a9 | 1,936 | cpp | C++ | Lab9/OpenGL_UI_Example/my_gl.cpp | dyaranon/CSE165_UCMerced_OOP | cd6e65e537f6d98244e2bd81f481007629a16852 | [
"Apache-2.0"
] | null | null | null | Lab9/OpenGL_UI_Example/my_gl.cpp | dyaranon/CSE165_UCMerced_OOP | cd6e65e537f6d98244e2bd81f481007629a16852 | [
"Apache-2.0"
] | null | null | null | Lab9/OpenGL_UI_Example/my_gl.cpp | dyaranon/CSE165_UCMerced_OOP | cd6e65e537f6d98244e2bd81f481007629a16852 | [
"Apache-2.0"
] | null | null | null | #include "my_gl.h"
MyGL::MyGL(QWidget *parent) : QOpenGLWidget(parent)
{
xrot = yrot = zrot = 0.0;
}
void MyGL::initializeGL()
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHT0);
}
void MyGL::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0.0, 0.0, -7.0);
glRotatef(xrot, 1.0, 0.0, 0.0);
glRotatef(yrot, 0.0, 1.0, 0.0);
glRotatef(zrot, 0.0, 0.0, 1.0);
glTranslatef(0,0,0);
glBegin(GL_TRIANGLE_STRIP);
glColor3f(1, 0, 0); glVertex3f(0, 1, 0);
glColor3f(1, 0, 1); glVertex3f(-0.5, 0, 0.5);
glColor3f(0, 0, 1); glVertex3f(0.5, 0, 0.5);
glColor3f(0, 1, 0); glVertex3f(0, 0, -0.7);
// with a triangle strip we have to repeat the last two vertices.
glColor3f(1, 0, 1); glVertex3f(0, 1, 0);
glColor3f(1, 1, 1); glVertex3f(-0.5, 0, 0.5);
glEnd();
glFlush();
}
void MyGL::resizeGL(int w, int h)
{
//set viewport
glViewport(0,0,w,h);
//initialize projection matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
/* multiply the current matrix by a perspective matrix
* void glFrustum(GLdouble left, GLdouble right,GLdouble bottom,GLdouble top,GLdouble nearVal,GLdouble farVal);
* left, right: Specify the coordinates for the left and right vertical clipping planes.
* bottom, top: Specify the coordinates for the bottom and top horizontal clipping planes.
* nearVal, farVal: Specify the distances to the near and far depth clipping planes. Both distances must be positive.
*/
glFrustum(-2, +2, -2, +2, 4.0, 10.0);
//initialize modelview matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void MyGL::setRotation(float x, float y, float z)
{
xrot = x;
yrot = y;
zrot = z;
update();
}
| 26.520548 | 122 | 0.607438 | dyaranon |
83a8a10cc914399941b048c65724a3f99e346c1d | 7,328 | cpp | C++ | datastore/importers/nmdb-import-ipconfig/Parser.cpp | mire-all-rashly/netmeld | d3ffd0b3d1332654e9c8df871bc7bf0b8cb46fed | [
"MIT"
] | null | null | null | datastore/importers/nmdb-import-ipconfig/Parser.cpp | mire-all-rashly/netmeld | d3ffd0b3d1332654e9c8df871bc7bf0b8cb46fed | [
"MIT"
] | null | null | null | datastore/importers/nmdb-import-ipconfig/Parser.cpp | mire-all-rashly/netmeld | d3ffd0b3d1332654e9c8df871bc7bf0b8cb46fed | [
"MIT"
] | null | null | null | // =============================================================================
// Copyright 2017 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
//
// 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.
// =============================================================================
// Maintained by Sandia National Laboratories <Netmeld@sandia.gov>
// =============================================================================
#include "Parser.hpp"
// =============================================================================
// Parser logic
// =============================================================================
Parser::Parser() : Parser::base_type(start)
{
start =
// Skip garbage before
*(!qi::lit("Windows IP Configuration") >> -qi::omit[+token] >> qi::eol) >>
(qi::lit("Windows IP Configuration") > +qi::eol >>
(
+adapter |
+(
-compartmentHeader >>
hostData >>
*(adapter)
)
)
) [qi::_val = pnx::bind(&Parser::getData, this)] >>
*(ignoredLine) // Skip garbage after
;
compartmentHeader =
+qi::lit('=') > qi::eol > ignoredLine > +qi::lit('=') > qi::eol
;
hostData =
+( ("Host Name" >> dots > fqdn > qi::eol)
[pnx::bind(&Parser::addDevInfo, this, qi::_1)]
| ("Primary Dns Suffix" >> dots > -fqdn > qi::eol)
| ignoredLine
) >> qi::eol
;
adapter =
ifaceTypeName > +qi::eol >
+( ("Physical Address" >> dots > macAddr > qi::eol)
[(pnx::bind(&Parser::addIfaceMac, this, qi::_1))]
| (ipLine > qi::eol)
[(pnx::bind(&Parser::addIfaceIp, this, qi::_1))]
| ("Media State" >> dots > "Media disconnected" > qi::eol)
[(pnx::bind(&Parser::setIfaceDown, this))]
| ("Connection-specific DNS Suffix" >> dots > -token
[(pnx::bind(&Parser::setIfaceDnsSuffix, this, qi::_1))] > qi::eol)
| ("Default Gateway" >> dots > (+(getIp
[(pnx::bind(&Parser::addRoute, this, qi::_1))] > qi::eol) | qi::eol ))
| servers
| ignoredLine
) >> *qi::eol
;
ifaceTypeName =
(ifaceType >> "adapter" >>
qi::as_string[qi::lexeme[+(qi::char_ - ':')]] > ':')
[(pnx::bind(&Parser::addIface, this, qi::_2, qi::_1))]
;
dots =
*qi::char_(". ") > ':'
;
servers =
( ("DHCP Server" >> dots > getIp > qi::eol)
[(pnx::bind(&Parser::addService, this, "DHCP", qi::_1))]
| ("DNS Servers" >> dots > +(getIp > qi::eol)
[(pnx::bind(&Parser::addService, this, "DNS", qi::_1))])
| (qi::hold[token >> qi::lit("WINS Server")] >> dots > getIp > qi::eol)
[(pnx::bind(&Parser::addService, this, "WINS", qi::_2))]
)
;
ipLine =
("IP" >> -("v" > qi::char_("46"))) >> "Address" >> dots > getIp
[(qi::_val = qi::_1)] >>
-(qi::eol >> "Subnet Mask" >> dots > getIp)
[(pnx::bind(&nmdo::IpAddress::setNetmask, &qi::_val, qi::_1))]
;
getIp =
ipAddr >> -(qi::omit[token])
;
token =
+qi::ascii::graph
;
ifaceType =
+(qi::ascii::print - "adapter")
;
ignoredLine =
+(qi::char_ - qi::eol) > qi::eol
;
BOOST_SPIRIT_DEBUG_NODES(
//(start)
(compartmentHeader)
(hostData)
(adapter)(ifaceTypeName)
(servers)
(ipLine)(getIp)
//(ignoredLine)(dots)
//(token)
);
}
// =============================================================================
// Parser helper methods
// =============================================================================
void
Parser::addDevInfo(const std::string& _hostname)
{
nmdo::DeviceInformation devInfo;
devInfo.setDeviceId(_hostname);
curHostname = devInfo.getDeviceId();
d.devInfos[curHostname] = devInfo;
}
void
Parser::addIface(const std::string& _name, const std::string& _type)
{
nmdo::Interface iface;
std::string whitespace = "\t\n\v\f\r ";
std::string type = _type;
type = type.erase(type.find_last_not_of(whitespace) + 1);
type = type.erase(0, type.find_first_not_of(whitespace));
iface.setName(_name);
iface.setMediaType(type);
iface.setUp();
curIfaceName = iface.getName();
d.ifaces[curIfaceName] = iface;
}
void
Parser::addIfaceMac(nmdo::MacAddress& _macAddr)
{
auto& iface {d.ifaces[curIfaceName]};
iface.setMacAddress(_macAddr);
}
void
Parser::addIfaceIp(nmdo::IpAddress& _ipAddr)
{
auto& iface {d.ifaces[curIfaceName]};
if (dnsSuffix.count(curIfaceName)) {
auto alias {curHostname};
if (!curHostname.empty()) {
alias += '.';
}
alias += dnsSuffix[curIfaceName];
_ipAddr.addAlias(alias, "ipconfig");
}
iface.addIpAddress(_ipAddr);
}
void
Parser::setIfaceDown()
{
auto& iface {d.ifaces[curIfaceName]};
iface.setDown();
}
void
Parser::setIfaceDnsSuffix(const std::string& _suffix)
{
dnsSuffix[curIfaceName] = _suffix;
}
void
Parser::addRoute(const nmdo::IpAddress& _ipAddr)
{
for (auto& ipAddr : d.ifaces[curIfaceName].getIpAddresses()) {
if (ipAddr.isV4() && _ipAddr.isV4()) {
nmdo::Route route;
route.setIfaceName(curIfaceName);
route.setNextHopIpAddr(_ipAddr);
route.setDstIpNet(ipAddr);
d.routes.push_back(route);
}
if (ipAddr.isV6() && _ipAddr.isV6()) {
nmdo::Route route;
route.setIfaceName(curIfaceName);
route.setNextHopIpAddr(_ipAddr);
route.setDstIpNet(ipAddr);
d.routes.push_back(route);
}
}
}
void
Parser::addService(const std::string& _name, const nmdo::IpAddress& _ipAddr)
{
nmdo::Service service;
service.setServiceName(_name);
service.setDstAddress(_ipAddr);
service.setInterfaceName(curIfaceName);
service.setServiceDescription("ipconfig");
if ("DNS" == _name) {
service.addDstPort("53");
} else if ("DHCP" == _name) {
service.addDstPort("67");
} else if ("WINS" == _name) {
service.addDstPort("42");
}
d.services.push_back(service);
}
// Object return
Result
Parser::getData()
{
for (auto& [name, iface] : d.ifaces) {
if (!dnsSuffix.count(name)) { continue; }
for (auto& ipAddr : iface.getIpAddresses()) {
ipAddr.addAlias(dnsSuffix[name], "ipconfig");
}
}
Result r;
r.push_back(d);
return r;
}
| 28.513619 | 80 | 0.574099 | mire-all-rashly |
83bb1a1375152e35b1ca1ae7b907e4e2e0313707 | 1,774 | hpp | C++ | lib/include/CL/Utils/Error.hpp | ProjectPhysX/OpenCL-SDK | f3e8600cfb6c0266c121d7e1f8b2e5dba9c5fab1 | [
"Apache-2.0"
] | null | null | null | lib/include/CL/Utils/Error.hpp | ProjectPhysX/OpenCL-SDK | f3e8600cfb6c0266c121d7e1f8b2e5dba9c5fab1 | [
"Apache-2.0"
] | null | null | null | lib/include/CL/Utils/Error.hpp | ProjectPhysX/OpenCL-SDK | f3e8600cfb6c0266c121d7e1f8b2e5dba9c5fab1 | [
"Apache-2.0"
] | null | null | null | #pragma once
// OpenCL Utils includes
#include "OpenCLUtils_Export.h"
// OpenCL Utils includes
#include <CL/Utils/ErrorCodes.h>
// OpenCL includes
#include <CL/opencl.hpp>
namespace cl {
namespace util {
#if defined(CL_HPP_ENABLE_EXCEPTIONS)
/*! \brief Exception class
*
* This may be thrown by SDK utility functions when
* CL_HPP_ENABLE_EXCEPTIONS is defined.
*/
class Error : public std::exception {
private:
int err_;
const char* errStr_;
public:
/*! \brief Create a new SDK error exception for a given error code
* and corresponding message.
*
* \param err error code value.
*
* \param errStr a descriptive string that must remain in scope until
* handling of the exception has concluded. If set, it
* will be returned by what().
*/
Error(cl_int err, const char* errStr = NULL): err_(err), errStr_(errStr)
{}
~Error() throw() {}
/*! \brief Get error string associated with exception
*
* \return A memory pointer to the error message string.
*/
virtual const char* what() const throw()
{
if (errStr_ == NULL)
{
return "empty";
}
else
{
return errStr_;
}
}
/*! \brief Get error code associated with exception
*
* \return The error code.
*/
cl_int err(void) const { return err_; }
};
#endif
namespace detail {
UTILS_EXPORT cl_int errHandler(cl_int err, cl_int* errPtr,
const char* errStr = nullptr);
}
}
}
| 24.985915 | 80 | 0.536077 | ProjectPhysX |
83bdc42d0ecc0c24d8a7050af0c47290e49b3934 | 10,736 | cpp | C++ | Outputs/file/au.cpp | jgunthorpe/muse | 7701cab4377938a8ce3d8c8d2eb68f5f7a7152bf | [
"MIT"
] | null | null | null | Outputs/file/au.cpp | jgunthorpe/muse | 7701cab4377938a8ce3d8c8d2eb68f5f7a7152bf | [
"MIT"
] | null | null | null | Outputs/file/au.cpp | jgunthorpe/muse | 7701cab4377938a8ce3d8c8d2eb68f5f7a7152bf | [
"MIT"
] | null | null | null | /* ########################################################################
FileAU - Class to allow Muse/2 to output a module to a AU file
Write RAW mix data to a AU file.
########################################################################
*/
#include <muse.h>
#include <au.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <math.h>
museFileAUClass *museFileAU::Meta = new museFileAUClass;
#ifdef __unix__
# define O_BINARY 0
#endif
/* ########################################################################
Class - museFileAU (AU File Interface for the digital mixer)
Member - Constructor (Init the class)
IDL - somDefaultInit
Initilize variables to non play states.
########################################################################
*/
museFileAU::museFileAU()
{
SamplingRate = 0;
Bits = 16;
Stereo = true;
Opened = false;
FileName = 0;
Handle = -1;
BufferSize = 63*1024;
Buffer = new octet[BufferSize];
Play = 0;
Extension = ".AU";
}
museFileAU::~museFileAU()
{
StopPlay();
delete [] Buffer;
}
/* ########################################################################
Class - museFileAU (AU File Interface for the digital mixer)
Member - SetMixParams (Builds the playlist needed for tracking)
Store playback type for initilization.
########################################################################
*/
long museFileAU::SetMixParams(unsigned long SRate, octet Bits, bool Stereo)
{
long Rc = museDACMixer::SetMixParams(SRate,Bits,Stereo);
if (Rc != 0) return Rc;
SamplingRate = SRate;
this->Bits = Bits;
this->Stereo = Stereo;
return 0;
}
/* ########################################################################
Class - museFileAU (AU File Interface for the digital mixer)
Member - InitPlay (Initilize the AU File interface)
Open the file and write the header.
########################################################################
*/
long museFileAU::InitPlay(char **Error)
{
*Error = 0;
if (Opened == true)
StopPlay();
if (SamplingRate == 0)
SetMixParams(8012,16,false);
if (FileName == 0)
{
const char *C = "module.AU";
FileName = new char[strlen(C)+1];
strcpy(FileName,C);
}
Handle = open(FileName,O_WRONLY | O_BINARY | O_CREAT | O_TRUNC,S_IREAD | S_IWRITE);
if (Handle == -1)
{
*Error = "File Open Error";
return 1;
}
TotalSize = 0;
Opened = true;
RealTime = false;
Play = 0;
// Write the header
const char *Comment = "Created by Muse/2";
unsigned long Size = 24 + strlen(Comment) + 1;
write(Handle,".snd",4);
write(Handle,&Size,4);
write(Handle,&Size,4); // Data Size
Size = 1; // ULAW encoding
write(Handle,&Size,4);
Size = 8012; // Smapling Rate
write(Handle,&Size,4);
Size = 1; // Channels
write(Handle,&Size,4);
if (write(Handle,Comment,strlen(Comment) + 1) != (int)(strlen(Comment) + 1))
{
*Error = "Write Error";
close(Handle);
Handle = -1;
Opened = false;
return 1;
}
return 0;
}
/* ########################################################################
Class - museFileAU (AU File Interface for the digital mixer)
Member - TestOutput (Play a sine AUeform)
Fills the buffer with a sine AUe and plays it.
########################################################################
*/
long museFileAU::TestOutput()
{
return 0;
}
/* ########################################################################
Class - museFileAU (AU File Interface for the digital mixer)
Member - StopPlay (Stops the AU playback.)
Closes the file.
########################################################################
*/
static unsigned long Res;
unsigned long *ByteFlip(unsigned long Byte)
{
unsigned char A = Byte & 0x000000FF;
unsigned char B = (Byte & 0x0000FF00) >> 8;
unsigned char C = (Byte & 0x00FF0000) >> 16;
unsigned char D = (Byte & 0xFF000000) >> 24;
Res = (A << 24) + (B << 16) + (C << 8) + D;
return &Res;
}
long museFileAU::StopPlay()
{
if (Opened == false)
return 0;
Opened = false;
Play = 0;
// Re-Write the header
lseek(Handle,0,SEEK_SET);
// Write the header
const char *Comment = "Created by Muse/2";
write(Handle,".snd",4);
write(Handle,ByteFlip(24 + strlen(Comment) + 1),4); // Header Len
write(Handle,ByteFlip(TotalSize),4); // Data Size
write(Handle,ByteFlip(1),4); // ULAW Encode
write(Handle,ByteFlip(8012),4); // Sampling Rate
write(Handle,ByteFlip(1),4); // Channels
close(Handle);
Handle = -1;
return 0;
}
/* ########################################################################
Class - museFileAU (Class to allow Muse/2 to use AU File for output)
Member - StopWhenDone (Fills the buffer with the last byte)
IDL - void StopWhenDone()
Used to allow the buffer to run out so the song can end on a buffer
boundry.
########################################################################
*/
void museFileAU::StopWhenDone()
{
museDACMixer::StopWhenDone();
if (Opened == false)
return;
octet *A;
GetNextBuffer(&A,&A);
StopPlay();
return;
}
/* ########################################################################
Class - museFileAU (AU File Interface for the digital mixer)
Member - PausePlay (Pause the AU playback.)
Pauses writing.
########################################################################
*/
void museFileAU::PausePlay()
{
Play = 2;
}
/* ########################################################################
Class - museFileAU (AU File Interface for the digital mixer)
Member - ResumePlay (Resumes the AU playback.)
Resumes writing.
########################################################################
*/
void museFileAU::ResumePlay()
{
Play = 1;
}
// Taken from libst.c
/*
** This routine converts from linear to ulaw.
**
** Craig Reese: IDA/Supercomputing Research Center
** Joe Campbell: Department of Defense
** 29 September 1989
**
** References:
** 1) CCITT Recommendation G.711 (very difficult to follow)
** 2) "A New Digital Technique for Implementation of Any
** Continuous PCM Companding Law," Villeret, Michel,
** et al. 1973 IEEE Int. Conf. on Communications, Vol 1,
** 1973, pg. 11.12-11.17
** 3) MIL-STD-188-113,"Interoperability and Performance Standards
** for Analog-to_Digital Conversion Techniques,"
** 17 February 1987
**
** Input: Signed 16 bit linear sample
** Output: 8 bit ulaw sample
*/
#define ZEROTRAP /* turn on the trap as per the MIL-STD */
#define BIAS 0x84 /* define the add-in bias for 16 bit samples */
#define CLIP 32635
unsigned char st_linear_to_ulaw(short sample)
{
static short exp_lut[256] = {0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,
4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7};
short sign, exponent, mantissa;
unsigned char ulawbyte;
/* Get the sample into sign-magnitude. */
sign = (sample >> 8) & 0x80; /* set aside the sign */
if ( sign != 0 ) sample = -sample; /* get magnitude */
if ( sample > CLIP ) sample = CLIP; /* clip the magnitude */
/* Convert from 16 bit linear to ulaw. */
sample = sample + BIAS;
exponent = exp_lut[( sample >> 7 ) & 0xFF];
mantissa = ( sample >> ( exponent + 3 ) ) & 0x0F;
ulawbyte = ~ ( sign | ( exponent << 4 ) | mantissa );
#ifdef ZEROTRAP
if ( ulawbyte == 0 ) ulawbyte = 0x02; /* optional CCITT trap */
#endif
return ulawbyte;
}
long museFileAU::GetNextBuffer(unsigned char **Start,unsigned char **Stop)
{
while (Play == 2)
threadSleep(100);
if (Play != 0)
{
octet *S = Buffer;
octet *E = Buffer + BufferSize;
for (octet *C = Buffer; S != E; S += 2,C++)
*C = st_linear_to_ulaw(*((signed short *)S));
if (write(Handle,Buffer,BufferSize/2) != (int)(BufferSize/2))
return 3;
TotalSize += BufferSize/2;
}
Play = 1;
*Start = Buffer;
*Stop = Buffer + BufferSize;
return 0;
}
/* ########################################################################
Class - museFileAUClass (Class of museFileAU)
Member - Constructor (Inits the class)
Simply inits data members.
########################################################################
*/
museFileAUClass::museFileAUClass()
{
Level = 0xFF;
MajorVersion = 1;
MinorVersion = 0;
}
/* ########################################################################
Class - museFileAUClass (Class of museFileAU)
Member - GetTypeName (Returns the name of this class)
IDL - string GetTypeName
Returns a pointer to a string containing 'Scream Tracker 3 Module'.
This string is valid while the object exists.
########################################################################
*/
const char *museFileAUClass::GetTypeName()
{
return ".AU File Ouput";
}
/* ########################################################################
Class - museFileAUClass (Class of museDACMMPM2)
Member - IsSupported (Returns the Support level of this class)
IDL - octet IsSupported()
Checks to see if DART is installed and a Digital AUe device is openable.
########################################################################
*/
octet museFileAUClass::IsSupported()
{
return 0xFF;
}
| 28.178478 | 87 | 0.472802 | jgunthorpe |
83bf4de6115bf3b592627d433296d652d0979f11 | 5,206 | hpp | C++ | src/controller/MessageManager.hpp | JeanMarcZimmer/libDiscordBot | dadd68a15b89f1577fd43a56b6fcf90330f1e1e8 | [
"MIT"
] | 11 | 2020-05-16T08:41:15.000Z | 2022-03-19T23:03:42.000Z | src/controller/MessageManager.hpp | JeanMarcZimmer/libDiscordBot | dadd68a15b89f1577fd43a56b6fcf90330f1e1e8 | [
"MIT"
] | 4 | 2020-05-15T06:59:01.000Z | 2020-10-06T18:13:23.000Z | src/controller/MessageManager.hpp | JeanMarcZimmer/libDiscordBot | dadd68a15b89f1577fd43a56b6fcf90330f1e1e8 | [
"MIT"
] | 5 | 2020-05-16T09:06:39.000Z | 2021-02-23T21:12:46.000Z | /*
* MIT License
*
* Copyright (c) 2020 Christian Tost
*
* 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.
*/
#ifndef MESSAGEMANAGER_HPP
#define MESSAGEMANAGER_HPP
#include <queue>
#include <thread>
#include <mutex>
#include <map>
#include <functional>
#include <atomic>
#include <memory>
#include "../helpers/Helper.hpp"
namespace DiscordBot
{
class IMessageBase
{
public:
IMessageBase() : Event(0), Handled(false) {}
size_t Event; //!< User defined Messagetype.
bool Handled; //!< True if the message doesn't need to propagate.
int Timeout;
int64_t CreateddMs;
virtual ~IMessageBase() {}
};
/**
* @brief Contains a value for the receiver.
*/
template <class T>
class TMessage : public IMessageBase
{
public:
TMessage() : IMessageBase() {}
T Value;
};
using MessageBase = std::shared_ptr<IMessageBase>;
class CMessageManager
{
public:
using OnMessageReceive = std::function<void(const MessageBase Msg)>;
CMessageManager(/* args */) : m_Terminated(false), m_Thread(&CMessageManager::Executor, this) {}
/**
* @brief Subscribes a message type.
*/
void SubscribeMessage(size_t Event, OnMessageReceive callback)
{
std::lock_guard<std::mutex> lock(m_CallbackLock);
m_Callbacks.insert({ Event, callback });
}
template<class T>
void SendMessage(size_t Event, T Value)
{
using Message = std::shared_ptr<TMessage<T>>;
std::lock_guard<std::mutex> lock(m_CallbackLock);
Message Msg = Message(new TMessage<T>());
Msg->Value = Value;
Msg->Event = Event;
SendMessage(Msg);
}
template<class T>
void PostMessage(size_t Event, T Value, int Timeout = 0)
{
using Message = std::shared_ptr<TMessage<T>>;
std::lock_guard<std::mutex> lock(m_QueueLock);
Message Msg = Message(new TMessage<T>());
Msg->Value = Value;
Msg->Event = Event;
Msg->Timeout = Timeout;
Msg->CreateddMs = GetTimeMillis();
m_Queue.push(std::static_pointer_cast<IMessageBase>(Msg));
}
~CMessageManager()
{
m_Terminated = true;
if(m_Thread.joinable())
m_Thread.join();
}
private:
void Executor()
{
while (!m_Terminated)
{
{
std::lock_guard<std::mutex> lock(m_QueueLock);
if(!m_Queue.empty() && m_Queue.size() > 0)
{
MessageBase Data = m_Queue.front();
m_Queue.pop();
if(GetTimeMillis() - Data->CreateddMs > Data->Timeout)
SendMessage(Data);
else
m_Queue.push(Data);
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void SendMessage(MessageBase Msg)
{
auto IT = m_Callbacks.begin();
while (IT != m_Callbacks.end())
{
if((*IT).first == Msg->Event)
(*IT).second(Msg);
if(Msg->Handled)
break;
IT++;
}
}
std::atomic<bool> m_Terminated;
std::queue<MessageBase> m_Queue;
std::mutex m_QueueLock;
std::mutex m_CallbackLock;
std::thread m_Thread;
std::multimap<size_t, OnMessageReceive> m_Callbacks;
};
} // namespace DiscordBot
#endif //MESSAGEMANAGER_HPP | 31.551515 | 108 | 0.531886 | JeanMarcZimmer |
83c03b1592df7c3cfa1e6c69bfd849db928b296d | 343 | cpp | C++ | ksn-2021-karakter/solution-5.cpp | ia-toki/ksn-2021 | e925029fa9ce6198aae489c5f8505c47078da28e | [
"CC-BY-4.0"
] | null | null | null | ksn-2021-karakter/solution-5.cpp | ia-toki/ksn-2021 | e925029fa9ce6198aae489c5f8505c47078da28e | [
"CC-BY-4.0"
] | null | null | null | ksn-2021-karakter/solution-5.cpp | ia-toki/ksn-2021 | e925029fa9ce6198aae489c5f8505c47078da28e | [
"CC-BY-4.0"
] | 1 | 2021-12-05T04:17:41.000Z | 2021-12-05T04:17:41.000Z | #include <bits/stdc++.h>
using namespace std;
int N;
string S;
bool valid() {
for (int i=1;i<N;i++) {
if (S[i-1]==S[i]) {
return 0;
}
}
return 1;
}
int main() {
cin>>N>>S;
sort(S.begin(),S.end());
do {
if (valid()) {
cout<<S<<'\n';
break;
}
}
while (next_permutation(S.begin(),S.end()));
}
| 12.703704 | 46 | 0.472303 | ia-toki |
83c1eb76ac8abc2d16c039c3ce775eefb6d43628 | 1,963 | cpp | C++ | libvast/src/system/spawn_indexer.cpp | knapperzbusch/vast | 9d2af995254519b47febe2062adbc55965055cbe | [
"BSD-3-Clause"
] | null | null | null | libvast/src/system/spawn_indexer.cpp | knapperzbusch/vast | 9d2af995254519b47febe2062adbc55965055cbe | [
"BSD-3-Clause"
] | 1 | 2019-11-29T12:43:41.000Z | 2019-11-29T12:43:41.000Z | libvast/src/system/spawn_indexer.cpp | knapperzbusch/vast | 9d2af995254519b47febe2062adbc55965055cbe | [
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include "vast/system/spawn_indexer.hpp"
#include "vast/filesystem.hpp"
#include "vast/logger.hpp"
#include "vast/system/indexer.hpp"
#include "vast/system/instrumentation.hpp"
#include "vast/type.hpp"
#include <caf/actor.hpp>
#include <caf/local_actor.hpp>
#include <caf/settings.hpp>
namespace vast::system {
caf::actor
spawn_indexer(caf::local_actor* parent, path dir, type column_type,
caf::settings index_opts, size_t column, caf::actor index,
uuid partition_id, atomic_measurement* m) {
VAST_TRACE(VAST_ARG(dir), VAST_ARG(column_type), VAST_ARG(index_opts),
VAST_ARG(column), VAST_ARG(index), VAST_ARG(partition_id),
VAST_ARG(*m));
return parent->spawn<caf::lazy_init>(indexer, std::move(dir),
std::move(column_type),
std::move(index_opts), column,
std::move(index), partition_id, m);
}
} // namespace vast::system
| 46.738095 | 80 | 0.479878 | knapperzbusch |
83c584dce5f9832f335e5c35b4025908d3875230 | 7,400 | hpp | C++ | src/NumericalAlgorithms/DiscontinuousGalerkin/BoundarySchemes/FirstOrder/FirstOrderSchemeLts.hpp | hrueter/spectre | 87825d0ee94378f4e79fbbba252afc5bb4443dcc | [
"MIT"
] | null | null | null | src/NumericalAlgorithms/DiscontinuousGalerkin/BoundarySchemes/FirstOrder/FirstOrderSchemeLts.hpp | hrueter/spectre | 87825d0ee94378f4e79fbbba252afc5bb4443dcc | [
"MIT"
] | null | null | null | src/NumericalAlgorithms/DiscontinuousGalerkin/BoundarySchemes/FirstOrder/FirstOrderSchemeLts.hpp | hrueter/spectre | 87825d0ee94378f4e79fbbba252afc5bb4443dcc | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <cstddef>
#include <utility>
#include "DataStructures/DataBox/DataBoxTag.hpp"
#include "DataStructures/DataBox/Prefixes.hpp"
#include "DataStructures/DataVector.hpp"
#include "DataStructures/Tensor/EagerMath/Magnitude.hpp"
#include "DataStructures/Tensor/Tensor.hpp"
#include "DataStructures/Variables.hpp"
#include "Domain/FaceNormal.hpp"
#include "Domain/Mesh.hpp"
#include "NumericalAlgorithms/DiscontinuousGalerkin/BoundarySchemes/FirstOrder/BoundaryFlux.hpp"
#include "NumericalAlgorithms/DiscontinuousGalerkin/BoundarySchemes/FirstOrder/FirstOrderScheme.hpp"
#include "NumericalAlgorithms/DiscontinuousGalerkin/MortarHelpers.hpp"
#include "NumericalAlgorithms/DiscontinuousGalerkin/Tags.hpp"
#include "Time/Tags.hpp"
#include "Utilities/TMPL.hpp"
namespace dg {
namespace FirstOrderScheme {
namespace detail {
template <size_t Dim, typename VariablesTag, typename NumericalFluxComputerTag,
typename BoundaryData,
typename NumericalFlux = typename NumericalFluxComputerTag::type,
typename ArgsTagsList = typename NumericalFlux::argument_tags>
struct boundary_data_computer_lts_impl;
template <size_t Dim, typename VariablesTag, typename NumericalFluxComputerTag,
typename BoundaryData, typename NumericalFlux, typename... ArgsTags>
struct boundary_data_computer_lts_impl<Dim, VariablesTag,
NumericalFluxComputerTag, BoundaryData,
NumericalFlux, tmpl::list<ArgsTags...>> {
using n_dot_fluxes_tag =
db::add_tag_prefix<::Tags::NormalDotFlux, VariablesTag>;
using magnitude_of_face_normal_tag =
::Tags::Magnitude<domain::Tags::UnnormalizedFaceNormal<Dim>>;
using argument_tags = tmpl::list<NumericalFluxComputerTag, n_dot_fluxes_tag,
magnitude_of_face_normal_tag, ArgsTags...>;
using volume_tags = tmpl::append<tmpl::list<NumericalFluxComputerTag>,
get_volume_tags<NumericalFlux>>;
static auto apply(const NumericalFlux& numerical_flux_computer,
const typename n_dot_fluxes_tag::type& normal_dot_fluxes,
const Scalar<DataVector>& face_normal_magnitude,
const typename ArgsTags::type&... args) noexcept {
BoundaryData boundary_data{normal_dot_fluxes.number_of_grid_points()};
boundary_data.field_data.assign_subset(normal_dot_fluxes);
dg::NumericalFluxes::package_data(make_not_null(&boundary_data),
numerical_flux_computer, args...);
get<magnitude_of_face_normal_tag>(boundary_data.extra_data) =
face_normal_magnitude;
return boundary_data;
}
};
} // namespace detail
/*!
* \ingroup DiscontinuousGalerkinGroup
* \brief Boundary contributions for a first-order DG scheme with local
* time-stepping
*
* This class is the local time-stepping equivalent to the
* `dg::FirstOrderScheme::FirstOrderScheme`. Notable differences are:
*
* - Boundary contributions are added to the `VariablesTag` directly.
* - We use the `Tags::BoundaryHistory` on mortars.
* - We need to store the face-normal magnitude in the boundary history, as
* opposed to the non-LTS case where we can retrieve it when needed.
*/
template <size_t Dim, typename VariablesTag, typename NumericalFluxComputerTag,
typename TemporalIdTag, typename TimeStepperTag>
struct FirstOrderSchemeLts {
private:
using base = FirstOrderScheme<Dim, VariablesTag, NumericalFluxComputerTag,
TemporalIdTag>;
public:
static constexpr size_t volume_dim = Dim;
using variables_tag = VariablesTag;
using numerical_flux_computer_tag = NumericalFluxComputerTag;
using NumericalFlux = typename NumericalFluxComputerTag::type;
using temporal_id_tag = TemporalIdTag;
using receive_temporal_id_tag = ::Tags::Next<temporal_id_tag>;
using time_stepper_tag = TimeStepperTag;
using magnitude_of_face_normal_tag =
::Tags::Magnitude<domain::Tags::UnnormalizedFaceNormal<volume_dim>>;
using BoundaryData = dg::SimpleBoundaryData<
typename base::BoundaryData::field_tags,
tmpl::push_back<typename base::BoundaryData::extra_data_tags,
magnitude_of_face_normal_tag>>;
using boundary_data_computer = detail::boundary_data_computer_lts_impl<
volume_dim, variables_tag, numerical_flux_computer_tag, BoundaryData>;
using mortar_data_tag = Tags::BoundaryHistory<BoundaryData, BoundaryData,
typename variables_tag::type>;
using return_tags =
tmpl::list<variables_tag, ::Tags::Mortars<mortar_data_tag, Dim>>;
using argument_tags =
tmpl::list<domain::Tags::Mesh<Dim>,
::Tags::Mortars<domain::Tags::Mesh<Dim - 1>, Dim>,
::Tags::Mortars<::Tags::MortarSize<Dim - 1>, Dim>,
NumericalFluxComputerTag, time_stepper_tag, ::Tags::TimeStep>;
static void apply(
const gsl::not_null<db::item_type<variables_tag>*> variables,
const gsl::not_null<db::item_type<::Tags::Mortars<mortar_data_tag, Dim>>*>
all_mortar_data,
const Mesh<Dim>& volume_mesh,
const typename ::Tags::Mortars<domain::Tags::Mesh<Dim - 1>, Dim>::type&
mortar_meshes,
const typename ::Tags::Mortars<::Tags::MortarSize<Dim - 1>, Dim>::type&
mortar_sizes,
const NumericalFlux& normal_dot_numerical_flux_computer,
const typename time_stepper_tag::type::element_type& time_stepper,
const TimeDelta& time_step) noexcept {
// Iterate over all mortars
for (auto& mortar_id_and_data : *all_mortar_data) {
// Retrieve mortar data
const auto& mortar_id = mortar_id_and_data.first;
auto& mortar_data = mortar_id_and_data.second;
const auto& direction = mortar_id.first;
const size_t dimension = direction.dimension();
const auto& mortar_mesh = mortar_meshes.at(mortar_id);
const auto& mortar_size = mortar_sizes.at(mortar_id);
const auto face_mesh = volume_mesh.slice_away(dimension);
const size_t extent_perpendicular_to_face =
volume_mesh.extents(dimension);
// This lambda must only capture quantities that are
// independent of the simulation state.
const auto coupling = [&face_mesh, &mortar_mesh, &mortar_size,
&extent_perpendicular_to_face,
&normal_dot_numerical_flux_computer](
const BoundaryData& local_data,
const BoundaryData& remote_data) noexcept {
return boundary_flux(
local_data, remote_data, normal_dot_numerical_flux_computer,
get<magnitude_of_face_normal_tag>(local_data.extra_data),
extent_perpendicular_to_face, face_mesh, mortar_mesh, mortar_size);
};
const auto lifted_data = time_stepper.compute_boundary_delta(
coupling, make_not_null(&mortar_data), time_step);
// Add the flux contribution to the volume data
add_slice_to_data(variables, lifted_data, volume_mesh.extents(),
dimension,
index_to_slice_at(volume_mesh.extents(), direction));
}
}
};
} // namespace FirstOrderScheme
} // namespace dg
| 44.848485 | 100 | 0.705135 | hrueter |
83c63141746ec5457d47f32a9d558dd86145264d | 3,345 | cpp | C++ | examples/3d/example3/example3.cpp | grenkin/joker-fem | b86115f5deebd2f2da1a9417f840da57c2b5c220 | [
"MIT"
] | null | null | null | examples/3d/example3/example3.cpp | grenkin/joker-fem | b86115f5deebd2f2da1a9417f840da57c2b5c220 | [
"MIT"
] | null | null | null | examples/3d/example3/example3.cpp | grenkin/joker-fem | b86115f5deebd2f2da1a9417f840da57c2b5c220 | [
"MIT"
] | null | null | null | /*
-\Delta u + u^2 = -6 + (x^2 + y^2 + z^2)^2
-u_x + u|_{x=-1} = 3 + y^2 + z^2
u_x + u|_{x=1} = 3 + y^2 + z^2
-u_y + u|_{y=-1} = 3 + x^2 + z^2
u_y + u|_{y=1} = 3 + x^2 + z^2
-u_z + u|_{z=-1} = 3 + x^2 + y^2
u_z + u|_{z=1} = 3 + x^2 + y^2
Exact solution: u(x, y, z) = x^2 + y^2 + z^2
*/
#include <joker-fem-3d/bvp3d.h>
#include <iostream>
#include <cmath>
using namespace std;
double gfun(double x, double y, double z)
{
return -6 + pow(x * x + y * y + z * z, 2);
}
double exact(double x, double y, double z)
{
return x * x + y * y + z * z;
}
bool eq (double a, double b)
{
return fabs(a - b) < 1e-5;
}
int main()
{
int tests_num = 3;
int n_values[tests_num] = {10, 20, 40};
string files_names[tests_num] =
{"tr10_cube.mesh", "tr20_cube.mesh", "tr40_cube.mesh"};
int N = 1;
double rms_old;
for (int test = 0; test < tests_num; ++test) {
Mesh mesh(files_names[test]);
ProblemData data(N, mesh);
data.a[0] = 1.0;
for (int i = 0; i < mesh.boundary_triangles_num; ++i)
data.b[0].values[i] = 1.0;
for (int i = 0; i < mesh.boundary_nodes_num; ++i) {
double x = mesh.nodes[mesh.boundary_nodes[i]].x;
double y = mesh.nodes[mesh.boundary_nodes[i]].y;
double z = mesh.nodes[mesh.boundary_nodes[i]].z;
if (eq(x, -1) || eq(x, 1))
data.w[0].values[i] = 3 + y * y + z * z;
else if (eq(y, -1) || eq(y, 1))
data.w[0].values[i] = 3 + x * x + z * z;
else if (eq(z, -1) || eq(z, 1))
data.w[0].values[i] = 3 + x * x + y * y;
else
throw;
}
vector<FunctionP1> sol(N, mesh);
for (int i = 0; i < mesh.nodes_num; ++i)
sol[0].values[i] = 0.0;
// set the initial guess
FunctionP1 sol_old(mesh);
for (int i = 0; i < mesh.nodes_num; ++i)
sol_old.values[i] = 0.0;
int iterations = 0;
while (1) {
cout << ++iterations << " ";
// linearized equation:
// -\Delta u + 2 * u0 * u = -6 + (x^2 + y^2 + z^2)^2 + u0^2
for (int i = 0; i < mesh.nodes_num; ++i) {
data.g[0].values[i] =
gfun(mesh.nodes[i].x, mesh.nodes[i].y, mesh.nodes[i].z)
+ pow(sol_old.values[i], 2);
data.q[0][0].values[i] = 2 * sol_old.values[i];
}
SolveBVP(data, Parameters(), sol);
double max_diff = 0.0;
for (int i = 0; i < mesh.nodes_num; ++i)
max_diff = fmax(max_diff,
fabs(sol[0].values[i] - sol_old.values[i]));
if (max_diff < 1e-5)
break;
for (int i = 0; i < mesh.nodes_num; ++i)
sol_old.values[i] = sol[0].values[i];
}
double rms = 0.0;
for (int i = 0; i < mesh.nodes_num; ++i) {
rms += pow(sol[0].values[i]
- exact(mesh.nodes[i].x, mesh.nodes[i].y, mesh.nodes[i].z), 2);
}
rms = sqrt(rms / mesh.nodes_num);
cout << "n = " << n_values[test] << " rms = " << rms << endl;
if (test > 0)
cout << "rms_old / rms = " << rms_old / rms << endl;
cout << endl;
rms_old = rms;
}
return 0;
}
| 30.688073 | 79 | 0.452915 | grenkin |
83cdf4f3849b3a8893a08cc17bc27db5fbd43552 | 9,649 | cpp | C++ | test/testcpu/testload.cpp | am1ko/nes | 4c1addaa6331733ccde90a3d9a0eed74968e859e | [
"MIT"
] | null | null | null | test/testcpu/testload.cpp | am1ko/nes | 4c1addaa6331733ccde90a3d9a0eed74968e859e | [
"MIT"
] | null | null | null | test/testcpu/testload.cpp | am1ko/nes | 4c1addaa6331733ccde90a3d9a0eed74968e859e | [
"MIT"
] | null | null | null | #include "testload.h"
#include "test_helpers.h"
using ::testing::Return;
using ::testing::Exactly;
using ::testing::_;
// ---------------------------------------------------------------------------------------------- //
LoadTest::LoadTest() : cpu(memory) {
ON_CALL(memory, read(_)).WillByDefault(Return(0U));
}
// ---------------------------------------------------------------------------------------------- //
LoadTest::~LoadTest() {};
// ---------------------------------------------------------------------------------------------- //
void LoadTest::SetUp() {
RESET_CPU(0x8000U);
};
// ---------------------------------------------------------------------------------------------- //
void LoadTest::TearDown() {};
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LDAImmediate) {
EXPECT_MEM_READ_8(REG_PC, 0xA9U);
EXPECT_MEM_READ_8(REG_PC+1, 0x0BU);
unsigned const ret = cpu.tick();
EXPECT_EQ(REG_A, 0x0BU);
EXPECT_EQ(ret, 2U);
EXPECT_EQ(REG_PC, 0x8002U);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LDAZeroPage) {
EXPECT_MEM_READ_8(REG_PC, 0xA5U);
EXPECT_MEM_READ_8(REG_PC+1, 0x0AU);
EXPECT_MEM_READ_8(0x000AU, 0x0BU);
unsigned const ret = cpu.tick();
EXPECT_EQ(REG_A, 0x0BU);
EXPECT_EQ(ret, 3U);
EXPECT_EQ(REG_PC, 0x8002U);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LDAZeroPageX) {
SET_REG_X(5U);
EXPECT_MEM_READ_8(REG_PC, 0xB5U);
EXPECT_MEM_READ_8(REG_PC+1, 0x0AU);
EXPECT_MEM_READ_8(0x000AU + 5U, 0x0BU);
unsigned const ret = cpu.tick();
EXPECT_EQ(REG_A, 0x0BU);
EXPECT_EQ(ret, 4U);
EXPECT_EQ(REG_PC, 0x8002U);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LDAZeroPageXWrap) {
SET_REG_X(5U);
EXPECT_MEM_READ_8(REG_PC, 0xB5U);
EXPECT_MEM_READ_8(REG_PC+1, 0xFFU);
EXPECT_MEM_READ_8(0x0004U, 0x0BU);
unsigned const ret = cpu.tick();
EXPECT_EQ(REG_A, 0x0BU);
EXPECT_EQ(ret, 4U);
EXPECT_EQ(REG_PC, 0x8002U);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LDAAbsolute) {
EXPECT_MEM_READ_8(REG_PC, 0xADU);
EXPECT_MEM_READ_16(REG_PC+1, 0x0A0AU);
EXPECT_MEM_READ_8(0x0A0AU, 0x0BU);
unsigned const ret = cpu.tick();
EXPECT_EQ(REG_A, 0x0BU);
EXPECT_EQ(ret, 4U);
EXPECT_EQ(REG_PC, 0x8003U);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LDAAbsoluteX) {
SET_REG_X(5U);
EXPECT_MEM_READ_8(REG_PC, 0xBDU);
EXPECT_MEM_READ_16(REG_PC+1, 0xA0A0U);
EXPECT_MEM_READ_8(0xA0A5U, 0x0BU);
unsigned const ret = cpu.tick();
EXPECT_EQ(REG_A, 0x0BU);
EXPECT_EQ(ret, 4U);
EXPECT_EQ(REG_PC, 0x8003U);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LDAAbsoluteY) {
SET_REG_Y(5U);
EXPECT_MEM_READ_8(REG_PC, 0xB9U);
EXPECT_MEM_READ_16(REG_PC+1, 0xA0A0U);
EXPECT_MEM_READ_8(0xA0A5U, 0x0BU);
unsigned const ret = cpu.tick();
EXPECT_EQ(REG_A, 0x0BU);
EXPECT_EQ(ret, 4U);
EXPECT_EQ(REG_PC, 0x8003U);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LDAIndirectX) {
SET_REG_X(0x05U); // index
EXPECT_MEM_READ_8(REG_PC, 0xA1U); // instruction
EXPECT_MEM_READ_8(REG_PC+1, 0xA0U); // address of base address
EXPECT_MEM_READ_16(0x00A0U + REG_X, 0x1111U); // parameter address
EXPECT_MEM_READ_8(0x1111U, 0x0BU); // parameter value
unsigned const ret = cpu.tick();
EXPECT_EQ(REG_A, 0x0BU);
EXPECT_EQ(ret, 6U);
EXPECT_EQ(REG_PC, 0x8002U);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LDAIndirectY) {
SET_REG_Y(0x04U); // index
EXPECT_MEM_READ_8(REG_PC, 0xB1U); // instruction
EXPECT_MEM_READ_8(REG_PC+1, 0xF6U); // pointer to pointer to table
EXPECT_MEM_READ_16(0x00F6U, 0x1111U); // table base address
EXPECT_MEM_READ_8(0x1111U + REG_Y, 0x0BU); // index the table using Y
unsigned const ret = cpu.tick();
EXPECT_EQ(REG_A, 0x0BU);
EXPECT_EQ(ret, 5U);
EXPECT_EQ(REG_PC, 0x8002U);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LDANoFlags) {
EXPECT_MEM_READ_8(REG_PC, 0xA9U);
EXPECT_MEM_READ_8(REG_PC+1, 0x0BU);
(void)cpu.tick();
EXPECT_EQ(REG_A, 0x0BU);
EXPECT_EQ(NEGF, false);
EXPECT_EQ(ZEROF, false);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LDAImmediateNegFlag) {
EXPECT_MEM_READ_8(REG_PC, 0xA9U);
EXPECT_MEM_READ_8(REG_PC+1, 0xBBU);
(void)cpu.tick();
EXPECT_EQ(REG_A, 0xBBU);
EXPECT_EQ(NEGF, true);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LDAImmediateZeroFlag) {
EXPECT_MEM_READ_8(REG_PC, 0xA9U);
EXPECT_MEM_READ_8(REG_PC+1, 0x00U);
(void)cpu.tick();
EXPECT_EQ(REG_A, 0x00U);
EXPECT_EQ(ZEROF, true);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LdyImmediate) {
EXPECT_MEM_READ_8(REG_PC, 0xA0U);
EXPECT_MEM_READ_8(REG_PC+1, 0x44U);
unsigned const ret = cpu.tick();
EXPECT_EQ(ret, 2U);
EXPECT_EQ(REG_Y, 0x44U);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LdyImmediateZeroFlagSet) {
EXPECT_MEM_READ_8(REG_PC, 0xA0U);
EXPECT_MEM_READ_8(REG_PC+1, 0x00U);
(void)cpu.tick();
EXPECT_EQ(REG_Y, 0x00U);
EXPECT_EQ(ZEROF, true);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LdyImmediateZeroFlagCleared) {
EXPECT_MEM_READ_8(REG_PC, 0xA0U);
EXPECT_MEM_READ_8(REG_PC+1, 0x01U);
SET_ZEROF(true);
(void)cpu.tick();
EXPECT_EQ(REG_Y, 0x01U);
EXPECT_EQ(ZEROF, false);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LdyImmediateNegativeFlagSet) {
EXPECT_MEM_READ_8(REG_PC, 0xA0U);
EXPECT_MEM_READ_8(REG_PC+1, 0x80U);
(void)cpu.tick();
EXPECT_EQ(REG_Y, 0x80U);
EXPECT_EQ(NEGF, true);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LdyImmediateNegativeFlagCleared) {
EXPECT_MEM_READ_8(REG_PC, 0xA0U);
EXPECT_MEM_READ_8(REG_PC+1, 0x01U);
SET_NEGF(true);
(void)cpu.tick();
EXPECT_EQ(REG_Y, 0x01U);
EXPECT_EQ(NEGF, false);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LdyZeroPage) {
EXPECT_MEM_READ_8(REG_PC, 0xA4U);
EXPECT_MEM_READ_8(REG_PC + 1, 0x0AU);
EXPECT_MEM_READ_8(0x000A, 0x33U);
unsigned const ret = cpu.tick();
EXPECT_EQ(ret, 3U);
EXPECT_EQ(REG_Y, 0x33U);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LdyZeroPageXIndexed) {
SET_REG_X(0x03U);
EXPECT_MEM_READ_8(REG_PC, 0xB4U);
EXPECT_MEM_READ_8(REG_PC + 1, 0x0AU);
EXPECT_MEM_READ_8(0x000A + REG_X, 0x33U);
unsigned const ret = cpu.tick();
EXPECT_EQ(ret, 4U);
EXPECT_EQ(REG_Y, 0x33U);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LdyAbsolute) {
EXPECT_MEM_READ_8(REG_PC, 0xACU);
EXPECT_MEM_READ_16(REG_PC + 1, 0xABBAU);
EXPECT_MEM_READ_8(0xABBAU, 0x11U);
unsigned const ret = cpu.tick();
EXPECT_EQ(ret, 4U);
EXPECT_EQ(REG_Y, 0x11U);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LdyAbsoluteXIndexed) {
SET_REG_X(0x08U);
EXPECT_MEM_READ_8(REG_PC, 0xBCU);
EXPECT_MEM_READ_16(REG_PC + 1, 0xABBAU);
EXPECT_MEM_READ_8(0xABBAU + REG_X, 0x22U);
unsigned const ret = cpu.tick();
EXPECT_EQ(ret, 4U);
EXPECT_EQ(REG_Y, 0x22U);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LdyIndirectPageBoundary) {
SET_REG_Y(0x34U); // index
EXPECT_MEM_READ_8(REG_PC, 0xB1U); // instruction
EXPECT_MEM_READ_8(REG_PC+1, 0x97U); // pointer to pointer to table
EXPECT_MEM_READ_16(0x0097U, 0xFFFFU); // table base address
EXPECT_MEM_READ_8(0x0033U, 0x0BU); // index the table using Y
unsigned const ret = cpu.tick();
EXPECT_EQ(REG_A, 0x0BU);
EXPECT_EQ(ret, 6U);
EXPECT_EQ(REG_PC, 0x8002U);
}
// ---------------------------------------------------------------------------------------------- //
TEST_F(LoadTest, LDAAbsoluteYPageBoundary) {
SET_REG_Y(5U);
EXPECT_MEM_READ_8(REG_PC, 0xB9U);
EXPECT_MEM_READ_16(REG_PC+1, 0xFFFFU);
EXPECT_MEM_READ_8(0x0004U, 0x0BU);
unsigned const ret = cpu.tick();
EXPECT_EQ(REG_A, 0x0BU);
EXPECT_EQ(ret, 5U);
EXPECT_EQ(REG_PC, 0x8003U);
}
| 30.438486 | 100 | 0.480257 | am1ko |
83d159dca4d9552e70fe3f7c382b6dc8bae52cc1 | 550 | hpp | C++ | Loyalty/DataModel/Entities/ClientDesc.hpp | uno-labs-solana-hackathon/core-server | fdbdefd32e12fcaa19227f56154e0163c18a35cb | [
"Apache-2.0"
] | null | null | null | Loyalty/DataModel/Entities/ClientDesc.hpp | uno-labs-solana-hackathon/core-server | fdbdefd32e12fcaa19227f56154e0163c18a35cb | [
"Apache-2.0"
] | 1 | 2021-03-06T11:38:01.000Z | 2021-03-15T21:33:16.000Z | Loyalty/DataModel/Entities/ClientDesc.hpp | uno-labs-solana-hackathon/core-server | fdbdefd32e12fcaa19227f56154e0163c18a35cb | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "BalanceDesc.hpp"
namespace Sol::Loyalty::DataModel {
class SOL_LOYALTY_DATA_MODEL_ENTITIES_API ClientDesc final: public GpTypeStructBase
{
public:
CLASS_DECLARE_DEFAULTS(ClientDesc)
TYPE_STRUCT_DECLARE("6ae53969-df92-47c5-a0b5-9ca4e85e03b3"_sv)
public:
ClientDesc (void) noexcept;
virtual ~ClientDesc (void) noexcept override final;
public:
std::string id;
unix_ts_s_t create_ts;
std::string name;
BalanceDesc balance;
bool is_on_chain = false;
};
}//namespace Sol::Loyalty::DataModel
| 21.153846 | 83 | 0.752727 | uno-labs-solana-hackathon |
83d46e1f24e1b6cc70d8c2cf545c21a70d74581a | 1,200 | cpp | C++ | 5333/src/cpp/Belev.cpp | swan58/2018-PowerUp | 035a4257810ab84de2528048d9afaa635344ae4b | [
"MIT"
] | 1 | 2018-01-26T05:58:48.000Z | 2018-01-26T05:58:48.000Z | 5333/src/cpp/Belev.cpp | swan58/2018-PowerUp | 035a4257810ab84de2528048d9afaa635344ae4b | [
"MIT"
] | null | null | null | 5333/src/cpp/Belev.cpp | swan58/2018-PowerUp | 035a4257810ab84de2528048d9afaa635344ae4b | [
"MIT"
] | null | null | null | #include "Belev.h"
#include "IO.h"
#include <RobotController.h>
void BelevatorControl::tick() {
if (IO::get_instance()->get_belev_limit_min()) IO::get_instance()->belev_motors[0]->SetSelectedSensorPosition(0, 0, 0);
}
void BelevatorControl::lift(double power) {
IO::get_instance()->belev_motors[0]->Set(power);
}
void BelevatorControl::winch_mode(BelevatorControl::Gear mode) {
IO::get_instance()->shifter_solenoid->Set(mode == BelevatorControl::Gear::High ? DoubleSolenoid::Value::kForward : DoubleSolenoid::Value::kReverse);
}
void BelevatorControl::winch_brake(bool enabled) {
IO::get_instance()->brake_solenoid->Set(enabled ? DoubleSolenoid::Value::kForward : DoubleSolenoid::Value::kReverse);
}
void BelevatorControl::claw(bool open) {
for (auto solenoid : IO::get_instance()->intake_solenoids) solenoid->Set(open ? DoubleSolenoid::Value::kForward : DoubleSolenoid::Value::kReverse);
}
void BelevatorControl::intake(double left, double right) {
for (auto motor : IO::get_instance()->intake_motors_left) motor->Set(left);
for (auto motor : IO::get_instance()->intake_motors_right) motor->Set(right);
}
void BelevatorControl::intake(double power) {
intake(power, power);
} | 35.294118 | 150 | 0.744167 | swan58 |
83d4d90c9f1b0943f96015d2572c17668eb69ad5 | 4,508 | cpp | C++ | interval.cpp | phma/mitobrevno | 30526eac54d0d619abd165b803b143347f4ade9d | [
"Apache-2.0"
] | null | null | null | interval.cpp | phma/mitobrevno | 30526eac54d0d619abd165b803b143347f4ade9d | [
"Apache-2.0"
] | null | null | null | interval.cpp | phma/mitobrevno | 30526eac54d0d619abd165b803b143347f4ade9d | [
"Apache-2.0"
] | null | null | null | /******************************************************/
/* */
/* interval.cpp - event intervals */
/* */
/******************************************************/
/* Copyright 2020 Pierre Abbat.
* This file is part of Mitobrevno.
*
* 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 <iostream>
#include <vector>
#include "interval.h"
#include "itree.h"
using namespace std;
using namespace mitobrevno;
/* In addition to the event types listed in mitobrevno.h, this module
* generates events of type 0xfffffnnn, which are errors.
*/
vector<MbEvent> pending;
vector<Interval> intervals;
vector<string> Interval::toStrings()
{
vector<string> ret;
string typeStr;
int i;
ret.push_back(to_string(start));
ret.push_back(to_string(end));
ret.push_back(to_string(end-start));
typeStr=getEventDescription(eventType);
if (typeStr.length())
ret.push_back(typeStr);
else
ret.push_back(to_string(eventType));
ret.push_back(to_string(thread));
for (i=0;i<intParams.size();i++) // TODO floats later
ret.push_back(to_string(intParams[i]));
return ret;
}
void storeInterval(Interval &iv)
{ // stub
intervals.push_back(iv);
}
bool sameButTime(const MbEvent &a,const MbEvent &b)
{
bool ret=eventBase(a.eventType)==eventBase(b.eventType) && a.thread==b.thread;
int i;
for (i=0;ret && i<a.intParams.size();i++)
if (a.intParams[i]!=b.intParams[i])
ret=false;
for (i=0;ret && i<a.floatParams.size();i++)
if (a.floatParams[i]!=b.floatParams[i])
ret=false;
return ret;
}
bool stateChanged(const MbEvent &a,const MbEvent &b)
{
bool ret=a.eventType==b.eventType && a.thread==b.thread && (b.eventType&~0x1000)==0x1000;
return ret;
}
void intervalize(MbEvent &event,uint64_t startTime)
{
int i;
Interval iv;
iv.start=iv.end=event.time-startTime;
iv.thread=event.thread;
iv.eventType=event.eventType;
iv.intParams=event.intParams;
iv.floatParams=event.floatParams;
switch (event.eventType/0x1000)
{
case 0: // unpaired event
storeInterval(iv);
break;
case 1: // state change
for (i=0;i<pending.size();i++)
if (stateChanged(pending[i],event))
break;
if (i==pending.size())
pending.push_back(event);
else
{
iv.start=pending[i].time;
iv.end=event.time-startTime;
pending[i].time=event.time-startTime;
storeInterval(iv);
}
break;
case 2: // lock, or write-lock a RW lock
case 4: // read-lock TODO handle locks, RW locks, and recursive locks differently
case 6: // recursive lock
pending.push_back(event);
break;
case 3: // unlock
case 5: // read-unlock
case 7: // recursive unlock
for (i=0;i<pending.size();i++)
if (sameButTime(pending[i],event))
break;
if (i==pending.size())
{
iv.eventType=(event.eventType&0xfff)-0x2000; // error: end without start
storeInterval(iv);
}
else
{
iv.eventType=pending[i].eventType;
iv.start=pending[i].time-startTime;
storeInterval(iv);
swap(pending[i],pending.back());
pending.resize(pending.size()-1);
}
break;
default: // unknown event type
iv.eventType=(event.eventType&0xfff)-0x1000;
storeInterval(iv);
}
}
void treeize()
{
int64_t earliest=INT64_MAX,latest=0;
int i;
for (i=0;i<intervals.size();i++)
{
if (intervals[i].start<earliest)
earliest=intervals[i].start;
if (intervals[i].end<earliest)
earliest=intervals[i].end;
if (intervals[i].start>latest)
latest=intervals[i].start;
if (intervals[i].end>latest)
latest=intervals[i].end;
}
if (earliest<=latest)
{
intervalTree=IntervalTree(earliest,latest);
for (i=0;i<intervals.size();i++)
if (intervals[i].start<=intervals[i].end)
intervalTree.insert(intervals[i]);
else
cerr<<"Interval is backward\n";
}
else
cerr<<"Interval range is backward\n";
}
| 27.156627 | 91 | 0.636202 | phma |
83d5775eec998ea66bf31b746057587e09af2ee6 | 1,510 | hpp | C++ | include/data_structure.hpp | Algorithms-and-Data-Structures-2021/semester-work-disjoint-set | ea75ee2509422631d35afffd90b368ef783ac4de | [
"MIT"
] | null | null | null | include/data_structure.hpp | Algorithms-and-Data-Structures-2021/semester-work-disjoint-set | ea75ee2509422631d35afffd90b368ef783ac4de | [
"MIT"
] | null | null | null | include/data_structure.hpp | Algorithms-and-Data-Structures-2021/semester-work-disjoint-set | ea75ee2509422631d35afffd90b368ef783ac4de | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <stdexcept>
namespace itis {
/**
* Структура элемента
* Элемент имеет ранг и значение родителя
*/
struct Element {
public:
int rank{0};
int parent{0};
/**
* Конструктор элемента
* @param num - номер(значение) элемента
* Изначально каждый элемент является своим же родителем
*/
Element(int num) : parent{num} {}
};
/**
* Структура СД Disjoint-set
* В данной простой реализации имеет n элементов,
* где элемент имеет значение равное своему порядковому номеру. (Это не бесполезно. Смотрите пример =))
* Элементы хранятся в массиве elements.
* Реализована с использованием сжатия путей и Union-by-rank
*/
struct DisjointSet {
public:
int subset_count{0};
int size{0};
std::vector<Element> elements;
/**
* Конструктор структуры данных
* Он представляет собой make_set, выполненный n раз
* @param n - количество элементов
*/
DisjointSet(int n = 0);
/**
* Отдельный метод для создания подмножества с одним элементом
* и присоединения его к множеству.
*/
void make_set();
/**
* Поиск подмножества, к которому принадлежит элемент
* Реализовано со сжатием путей
* @param node - элемент
* @return - представитель подмножества
*/
int find(int node);
/**
* Объединение подмножеств, к которым принадлежат элементы
* Реализовано с Union-by-rank для оптимизации СД
* @param x - первый элемент
* @param y - второй элемент
*/
void join(int x, int y);
};
} // namespace itis | 22.205882 | 103 | 0.68543 | Algorithms-and-Data-Structures-2021 |
83dc3a950cc94e8a3ea62d07ac2451677637c69e | 593 | cpp | C++ | samples/snippets/cpp/VS_Snippets_Winforms/Classic DataGrid.GetCellBounds1 Example/CPP/source.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 421 | 2018-04-01T01:57:50.000Z | 2022-03-28T15:24:42.000Z | samples/snippets/cpp/VS_Snippets_Winforms/Classic DataGrid.GetCellBounds1 Example/CPP/source.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 5,797 | 2018-04-02T21:12:23.000Z | 2022-03-31T23:54:38.000Z | samples/snippets/cpp/VS_Snippets_Winforms/Classic DataGrid.GetCellBounds1 Example/CPP/source.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 1,482 | 2018-03-31T11:26:20.000Z | 2022-03-30T22:36:45.000Z | #using <System.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>
#using <System.Data.dll>
using namespace System;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::Windows::Forms;
public ref class Form1: public Form
{
protected:
DataGrid^ dataGrid1;
// <Snippet1>
protected:
DataGridCell dgc;
void GetRect()
{
Rectangle rect;
dgc.ColumnNumber = 0;
dgc.RowNumber = 0;
rect = dataGrid1->GetCellBounds( dgc );
Console::WriteLine( rect );
}
// </Snippet1>
};
| 19.766667 | 46 | 0.639123 | hamarb123 |
83e05da69e883e6df46c647aa745e9d6da4707cc | 2,027 | cpp | C++ | buglife.cpp | darksidergod/CompetitiveProgramming | ea0ee53bddd87e41b4586dd30c1d4a6b8ae3a93a | [
"MIT"
] | null | null | null | buglife.cpp | darksidergod/CompetitiveProgramming | ea0ee53bddd87e41b4586dd30c1d4a6b8ae3a93a | [
"MIT"
] | null | null | null | buglife.cpp | darksidergod/CompetitiveProgramming | ea0ee53bddd87e41b4586dd30c1d4a6b8ae3a93a | [
"MIT"
] | 1 | 2020-10-03T19:48:05.000Z | 2020-10-03T19:48:05.000Z | #include <bits/stdc++.h>
using namespace std;
#define mod 1000000007
#define int long long int
#define mk make_pair
#define flp(i, k, n) for(int i=k; i<n; i++)
#define F first
#define pb push_back
#define S second
#define SIZE 1000000
int power(int a, int b) {
int x = 1, y = a;
while(b > 0) {
if(b%2 == 1) {
x=(x*y);
if(x>mod) x%=mod;
}
y = (y*y);
if(y>mod) y%=mod;
b /= 2;
}
return x;
}
int color[SIZE];
vector<int> adj[SIZE];
bool vis[SIZE];
void bfs(int root)
{
queue<int> q;
q.push(root);
vis[root]=true; color[root]=0;
while(!q.empty())
{
int u=q.front();
q.pop();
flp(j, 0, adj[u].size())
{
int v=adj[u][j];
if(!vis[v])
{
q.push(v);
vis[v]=true;
color[v]=(1+color[u])%2;
}
}
}
}
int32_t main(void)
{
int t;
cin>>t;
flp(x, 0, t)
{
memset(color, -1, sizeof(color));
int n, m;
cin>>n>>m;
flp(i, 0, n)
adj[i].clear();
memset(vis, 0, sizeof(vis));
vector<pair<int, int>> edges;
bool flag=true;
flp(i, 0, m)
{
int u, v;
cin>>u>>v;
u--; v--;
adj[u].pb(v);
adj[v].pb(u);
edges.push_back({u, v});
}
flp(i, 0, n)
{
if(!vis[i])
bfs(i);
}
/* flp(i, 0, n)
cout<<color[i]<<" ";
cout<<"\n";*/
for(auto i:edges)
{
if(color[i.F]==color[i.S] && i.F!=i.S)
{
flag=false;
// cout<<i.F<<" "<<i.S<<"\n";
}
}
cout<<"Scenario #"<<x+1<<":\n";
if(flag)
{
cout<<"No suspicious bugs found!"<<"\n";
}
else
{
cout<<"Suspicious bugs found!"<<"\n";
}
}
} | 18.768519 | 52 | 0.371978 | darksidergod |
83e4817f442cc32b9edc2e147ae710ecccfed4ff | 20,113 | hh | C++ | src/solvers/IterativeMethodGMRES.hh | cannsudemir/amanzi | c6cd3287bdc2c6cf26c6f8b79e34799751385f9e | [
"RSA-MD"
] | 1 | 2021-02-23T18:34:47.000Z | 2021-02-23T18:34:47.000Z | src/solvers/IterativeMethodGMRES.hh | cannsudemir/amanzi | c6cd3287bdc2c6cf26c6f8b79e34799751385f9e | [
"RSA-MD"
] | null | null | null | src/solvers/IterativeMethodGMRES.hh | cannsudemir/amanzi | c6cd3287bdc2c6cf26c6f8b79e34799751385f9e | [
"RSA-MD"
] | null | null | null | /*
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Authors: Ethan Coon (ecoon@lanl.gov)
Konstantin Lipnikov (lipnikov@lanl.gov)
*/
//! Generalized minimum residual method for a linear solver.
/*!
Based on the methods of Yu. Kuznetsov, 1968; Y.Saad, 1986. Deflated version of
GMRES is due to R.Morgan, GMRES with deflated restarting, 2002 SISC; S.Rollin,
W.Fichtner, Improving accuracy of GMRES with deflated restarting, 2007 SISC.
.. _iterative-method-gmres-spec:
.. admonition:: iterative-method-gmres-spec
* `"error tolerance`" ``[double]`` **1.e-6** Tolerance on which to declare success.
* `"maximum number of iterations`" ``[int]`` **100** Maximum iterations before declaring failure.
* `"overflow tolerance`" ``[double]`` **3.e50** Error above this value results in failure.
* `"convergence criterial`" ``[Array(string)]`` **{relative rhs}** A list of
criteria, any of which can be applied. Valid include:
- `"relative rhs`" : measure error relative to the norm of the RHS vector
- `"relative residual`" : measure error relative to the norm of the residual
- `"absolute residual`" : measure error directly, norm of error
- `"make one iteration`" : require at least one iteration to be performed before declaring success
* `"size of Krylov space`" ``[int]`` **10** Size of the Krylov space used to span the residual.
* `"controller training start`" ``[int]`` **0** Start iteration for determining
convergence rates. (Add more please!)
* `"controller training end`" ``[int]`` **3** Start iteration for determining
convergence rates. (Add more please!)
* `"preconditioning strategy`" ``[string]`` **left** Valid are "left" and
"right"-type preconditioning (see Saad 1986)
* `"maximum size of deflation space`" ``[int]`` **0** Size of the deflation space, see Rollin et al.
*/
#ifndef AMANZI_GMRES_OPERATOR_HH_
#define AMANZI_GMRES_OPERATOR_HH_
#include <cmath>
#include "Teuchos_RCP.hpp"
#include "errors.hh"
#include "DenseMatrix.hh"
#include "InverseIterativeMethod.hh"
#include "InverseDefs.hh"
namespace Amanzi {
namespace AmanziSolvers {
template<class Matrix,
class Preconditioner=Matrix,
class Vector=typename Matrix::Vector_t,
class VectorSpace=typename Vector::VectorSpace_t>
class IterativeMethodGMRES :
public InverseIterativeMethod<Matrix,Preconditioner,Vector,VectorSpace> {
private:
using InvIt = InverseIterativeMethod<Matrix,Preconditioner,Vector,VectorSpace>;
public:
IterativeMethodGMRES() :
InvIt() {}
virtual void set_inverse_parameters(Teuchos::ParameterList& plist) override final;
virtual int ApplyInverse(const Vector& v, Vector& hv) const override final {
AMANZI_ASSERT(inited_ && h_.get());
returned_code_ = GMRESRestart_(v, hv, this->tol_, this->max_itrs_, this->criteria_);
if (returned_code_ <= 0) return 1;
return 0;
}
protected:
virtual std::string MethodName_() const override { return "GMRES"; }
private:
int GMRESRestart_(const Vector& f, Vector& x, double tol, int max_itrs, int criteria) const;
int GMRES_(const Vector& f, Vector& x, double tol, int max_itrs, int criteria) const;
int GMRES_Deflated_(const Vector& f, Vector& x, double tol, int max_itrs, int criteria) const;
void ComputeSolution_(Vector& x, int k, WhetStone::DenseMatrix& T, double* s,
Vector& p, Vector& r) const;
void ComputeSolution_(Vector& x, double* d, Vector& p, Vector& r) const;
void InitGivensRotation_( double& dx, double& dy, double& cs, double& sn) const;
void ApplyGivensRotation_(double& dx, double& dy, double& cs, double& sn) const;
IterativeMethodGMRES(const IterativeMethodGMRES& other) = delete;
private:
using InvIt::m_;
using InvIt::h_;
using InvIt::vo_;
using InvIt::num_itrs_;
using InvIt::residual_;
using InvIt::returned_code_;
using InvIt::CheckConvergence_;
using InvIt::krylov_dim_;
using InvIt::inited_;
using InvIt::rnorm0_;
mutable std::vector<Teuchos::RCP<Vector> > v_;
mutable WhetStone::DenseMatrix Hu_; // upper Hessenberg matrix
mutable double fnorm_;
mutable int num_itrs_inner_;
int controller_start_, controller_end_;
mutable double controller_[2];
bool left_pc_;
int deflation_;
mutable int num_ritz_;
};
/* ******************************************************************
* GMRES with restart input/output data:
* f [input] the right-hand side
* x [input/output] initial guess / final solution
* tol [input] convergence tolerance
* max_itrs [input] maximum number of iterations
* criteria [input] sum of termination critaria
*
* Return value. If it is positive, it indicates the sucessful
* convergence criterion (criteria in a few exceptional cases) that
* was checked first. If it is negative, it indicates a failure, see
* LinearSolverDefs.hh for the error explanation.
***************************************************************** */
template<class Matrix,class Preconditioner,class Vector,class VectorSpace>
int IterativeMethodGMRES<Matrix,Preconditioner,Vector,VectorSpace>::GMRESRestart_(
const Vector& f, Vector& x, double tol, int max_itrs, int criteria) const
{
// initialize verbose object
Teuchos::OSTab tab = vo_->getOSTab();
// allocate memory for Krylov space
v_.resize(krylov_dim_ + 1, Teuchos::null);
num_itrs_ = 0;
rnorm0_ = -1.0;
int ierr(LIN_SOLVER_MAX_ITERATIONS);
while (ierr == LIN_SOLVER_MAX_ITERATIONS && num_itrs_ < max_itrs) {
int max_itrs_left = max_itrs - num_itrs_;
if (deflation_ == 0) {
ierr = GMRES_(f, x, tol, max_itrs_left, criteria);
} else {
ierr = GMRES_Deflated_(f, x, tol, max_itrs_left, criteria);
}
if (ierr == LIN_SOLVER_RESIDUAL_OVERFLOW) return ierr;
}
if (ierr == LIN_SOLVER_MAX_ITERATIONS) {
if (vo_->os_OK(Teuchos::VERB_MEDIUM))
*vo_->os() << "Not converged (max iterations), ||r||=" << residual_
<< " ||f||=" << fnorm_ << std::endl;
}
return ierr;
}
/* ******************************************************************
* GMRES input/output data:
* f [input] the right-hand side
* x [input/output] initial guess / final solution
* tol [input] convergence tolerance
* max_itrs [input] maximum number of iterations
* criteria [input] sum of termination critaria
*
* Return value. See above.
***************************************************************** */
template<class Matrix,class Preconditioner,class Vector,class VectorSpace>
int IterativeMethodGMRES<Matrix,Preconditioner,Vector,VectorSpace>::GMRES_(
const Vector& f, Vector& x, double tol, int max_itrs, int criteria) const
{
Vector w(f), r(f), p(f); // construct empty vectors
double s[krylov_dim_ + 1], cs[krylov_dim_ + 1], sn[krylov_dim_ + 1];
WhetStone::DenseMatrix T(krylov_dim_ + 1, krylov_dim_);
num_itrs_inner_ = 0;
double fnorm;
// h_->ApplyInverse(f, r);
// r.Dot(fnorm, f); This is the preconditioned norm of the residual.
f.Norm2(&fnorm);
fnorm_ = fnorm;
// initial residual is r = f - M x for the right preconditioner
// and r = H (f - M x) for the left preconditioner
if (left_pc_) {
m_->Apply(x, p);
p.Update(1.0, f, -1.0);
h_->ApplyInverse(p, r);
} else {
m_->Apply(x, r);
r.Update(1.0, f, -1.0);
}
double rnorm0;
r.Norm2(&rnorm0);
residual_ = rnorm0;
if (rnorm0_ < 0.0) rnorm0_ = rnorm0;
if (fnorm == 0.0) {
x.PutScalar(0.0);
if (vo_->os_OK(Teuchos::VERB_MEDIUM))
*vo_->os() << "Converged, itr=" << num_itrs_ << " ||r||=" << rnorm0 << std::endl;
return criteria; // Zero solution satifies all criteria.
}
// Ignore all criteria if one iteration is enforced.
if (! (criteria & LIN_SOLVER_MAKE_ONE_ITERATION)) {
int ierr = CheckConvergence_(rnorm0, fnorm);
if (ierr != 0) return ierr;
}
v_[0] = Teuchos::rcp(new Vector(r));
v_[0]->Update(0.0, r, 1.0 / rnorm0);
s[0] = rnorm0;
for (int i = 0; i < krylov_dim_; i++) {
// calculate H M v_i for the left preconditioner
// and M H v_i for the right preconditioner
if (left_pc_) {
m_->Apply(*(v_[i]), p);
h_->ApplyInverse(p, w);
} else {
h_->ApplyInverse(*(v_[i]), p);
m_->Apply(p, w);
}
double tmp(0.0);
for (int k = 0; k <= i; k++) { // Arnoldi algorithm
w.Dot(*(v_[k]), &tmp);
w.Update(-tmp, *(v_[k]), 1.0);
T(k, i) = tmp;
}
w.Norm2(&tmp);
T(i + 1, i) = tmp;
s[i + 1] = 0.0;
for (int k = 0; k < i; k++) {
ApplyGivensRotation_(T(k, i), T(k + 1, i), cs[k], sn[k]);
}
InitGivensRotation_( T(i, i), T(i + 1, i), cs[i], sn[i]);
ApplyGivensRotation_(T(i, i), T(i + 1, i), cs[i], sn[i]);
ApplyGivensRotation_(s[i], s[i + 1], cs[i], sn[i]);
residual_ = fabs(s[i + 1]);
if (vo_->os_OK(Teuchos::VERB_HIGH)) {
*vo_->os() << num_itrs_ << " ||r||=" << residual_ << std::endl;
}
// Check all criteria one-by-one.
num_itrs_inner_ = i + 1;
num_itrs_++;
int ierr = CheckConvergence_(residual_, fnorm);
if (ierr != 0) {
ComputeSolution_(x, i, T, s, p, r); // vector s is overwritten
return ierr;
}
// optional controller of convergence
if (i == controller_start_) {
controller_[0] = residual_;
} else if (i == controller_end_) {
double len = 0.5 / (controller_end_ - controller_start_);
controller_[0] = std::pow(controller_[0] / residual_, len);
controller_[0] = std::min(controller_[0], 2.0);
controller_[1] = residual_;
} else if (i > controller_end_) {
double reduction = controller_[1] / residual_;
if (reduction < controller_[0]) {
if (vo_->os_OK(Teuchos::VERB_EXTREME))
*vo_->os() << "controller indicates convergence stagnation\n";
ComputeSolution_(x, i, T, s, p, r);
return LIN_SOLVER_MAX_ITERATIONS;
}
controller_[1] = residual_;
}
if (i < krylov_dim_ - 1) {
v_[i + 1] = Teuchos::rcp(new Vector(w));
if (tmp != 0.0) { // zero occurs in exact arithmetic
v_[i + 1]->Update(0.0, r, 1.0 / tmp);
}
}
}
ComputeSolution_(x, krylov_dim_ - 1, T, s, p, r); // vector s is overwritten
return LIN_SOLVER_MAX_ITERATIONS;
}
/* ******************************************************************
* GMRES with deflated start, input/output data: see GMRES_(...)
***************************************************************** */
template<class Matrix,class Preconditioner,class Vector,class VectorSpace>
int IterativeMethodGMRES<Matrix,Preconditioner,Vector,VectorSpace>::GMRES_Deflated_(
const Vector& f, Vector& x, double tol, int max_itrs, int criteria) const
{
Vector p(f), r(f), w(f);
WhetStone::DenseVector d(krylov_dim_ + 1), g(krylov_dim_);
WhetStone::DenseMatrix T(krylov_dim_ + 1, krylov_dim_);
double fnorm;
f.Norm2(&fnorm);
fnorm_ = fnorm;
// initial residual is r = f - M x for the right preconditioner
// and r = H (f - M x) for the left preconditioner
if (left_pc_) {
m_->Apply(x, p);
p.Update(1.0, f, -1.0);
h_->ApplyInverse(p, r);
} else {
m_->Apply(x, r);
r.Update(1.0, f, -1.0);
}
double rnorm0;
r.Norm2(&rnorm0);
residual_ = rnorm0;
if (rnorm0_ < 0.0) rnorm0_ = rnorm0;
if (fnorm == 0.0) {
x.PutScalar(0.0);
if (vo_->os_OK(Teuchos::VERB_MEDIUM))
*vo_->os() << "Converged, itr=" << num_itrs_ << " ||r||=" << rnorm0 << std::endl;
return criteria; // Zero solution satifies all criteria.
}
// Ignore all criteria if one iteration is enforced.
if (! (criteria & LIN_SOLVER_MAKE_ONE_ITERATION)) {
int ierr = CheckConvergence_(rnorm0, fnorm);
if (ierr != 0) return ierr;
}
// calculate the first (num_ritz_ + l) rows of c.
int i0(0);
double tmp;
d.PutScalar(0.0);
if (num_ritz_ == 0) {
v_[0] = Teuchos::rcp(new Vector(r));
v_[0]->Update(0.0, r, 1.0 / rnorm0);
d(0) = rnorm0;
} else {
for (int i = 0 ; i <= num_ritz_; ++i) {
r.Dot(*(v_[i]), &tmp);
d(i) = tmp;
}
i0 = num_ritz_;
}
// set the leading diagonal block of T
T.PutScalar(0.0);
for (int i = 0; i <= num_ritz_; ++i) {
for (int j = 0; j < num_ritz_; ++j) {
T(i, j) = Hu_(i, j);
}
}
// Apply Arnoldi method to extend the Krylov space calculate
// at the end of the previous loop.
double beta;
for (int i = i0; i < krylov_dim_; i++) {
if (left_pc_) {
m_->Apply(*(v_[i]), p);
h_->ApplyInverse(p, w);
} else {
h_->ApplyInverse(*(v_[i]), p);
m_->Apply(p, w);
}
for (int k = 0; k <= i; k++) { // Arnoldi algorithm
w.Dot(*(v_[k]), &tmp);
w.Update(-tmp, *(v_[k]), 1.0);
T(k, i) = tmp;
}
w.Norm2(&beta);
T(i + 1, i) = beta;
if (beta == 0.0) break;
v_[i + 1] = Teuchos::rcp(new Vector(w));
v_[i + 1]->Update(0.0, r, 1.0 / beta);
}
// Solve the least-square problem min_d ||T d - c||.
WhetStone::DenseMatrix Ttmp(T);
int m(krylov_dim_ + 1), n(krylov_dim_), nrhs(1), info;
int lwork(m * n);
WhetStone::DenseVector work(lwork);
WhetStone::DGELS_F77("N", &m, &n, &nrhs, Ttmp.Values(), &m, d.Values(), &m,
work.Values(), &lwork, &info);
residual_ = fabs(d(n));
num_itrs_ += krylov_dim_;
ComputeSolution_(x, d.Values(), p, r);
if (vo_->os_OK(Teuchos::VERB_EXTREME)) {
*vo_->os() << num_itrs_ << " ||r||=" << residual_
<< " ritz vectors=" << num_ritz_ << std::endl;
}
int ierr = CheckConvergence_(residual_, fnorm);
if (ierr != 0) return ierr;
// Compute Schur vectors
// -- allocate memory: Tm, Hm, and Vm
WhetStone::DenseMatrix Tm(T, 0, krylov_dim_, 0, krylov_dim_);
WhetStone::DenseMatrix Sm(Tm);
WhetStone::DenseMatrix Vr(krylov_dim_ + 1, krylov_dim_);
// -- auxiliary vector g = Tm^{-T} e_m
Tm.Inverse();
for (int i = 0; i < krylov_dim_; ++i) g(i) = beta * Tm(krylov_dim_ - 1, i);
// -- solve eigenvector problem
for (int i = 0; i < krylov_dim_; ++i) Sm(i, krylov_dim_ - 1) += beta * g(i);
double Vl[1];
WhetStone::DenseVector wr(krylov_dim_), wi(krylov_dim_);
WhetStone::DGEEV_F77("N", "V", &n, Sm.Values(), &n,
wr.Values(), wi.Values(), Vl, &nrhs, Vr.Values(), &m,
work.Values(), &lwork, &info);
// -- select not more than (deflation_) Schur vectors and
// make them the first columns in Vr
num_ritz_ = deflation_;
for (int i = 0; i < num_ritz_; ++i) {
int imin = i;
double emin = wr(i);
for (int j = i + 1; j < krylov_dim_; ++j) {
if (wr(j) < emin) {
emin = wr(j);
imin = j;
}
}
wr.SwapRows(imin, i);
wi.SwapRows(imin, i);
Vr.SwapColumns(imin, i);
}
if (wi(num_ritz_ - 1) > 0.0) num_ritz_--;
// -- add one vector and orthonormalize all columns.
for (int i = 0; i < krylov_dim_; ++i) {
Vr(krylov_dim_, i) = 0.0;
Vr(i, num_ritz_) = -g(i);
}
Vr(krylov_dim_, num_ritz_) = 1.0;
Vr.OrthonormalizeColumns(0, num_ritz_ + 1);
// Calculate new basis for the next loop.
std::vector<Teuchos::RCP<Vector> > vv(num_ritz_ + 1);
for (int i = 0; i <= num_ritz_; ++i) {
vv[i] = Teuchos::rcp(new Vector(x.Map()));
vv[i]->PutScalar(0.0);
for (int k = 0; k <= krylov_dim_; ++k) {
vv[i]->Update(Vr(k, i), *(v_[k]), 1.0);
}
}
for (int i = 0; i <= num_ritz_; ++i) {
*(v_[i]) = *(vv[i]);
}
// Calculate modified Hessenberg matrix Hu = Vr_{nr+1}^T * T * Vr_nr
WhetStone::DenseMatrix TVr(krylov_dim_ + 1, num_ritz_);
WhetStone::DenseMatrix VTVr(num_ritz_ + 1, num_ritz_);
WhetStone::DenseMatrix Vr1(Vr, 0, krylov_dim_, 0, num_ritz_);
WhetStone::DenseMatrix Vr2(krylov_dim_ + 1, num_ritz_ + 1, Vr.Values(), WhetStone::WHETSTONE_DATA_ACCESS_VIEW);
TVr.Multiply(T, Vr1, false);
VTVr.Multiply(Vr2, TVr, true);
Hu_ = VTVr;
return LIN_SOLVER_MAX_ITERATIONS;
}
/* ******************************************************************
* Initialization from a parameter list. Available parameters:
* "error tolerance" [double] default = 1e-6
* "maximum number of iterations" [int] default = 100
* "convergence criteria" Array(string) default = "{relative rhs}"
****************************************************************** */
template<class Matrix,class Preconditioner,class Vector,class VectorSpace>
void IterativeMethodGMRES<Matrix,Preconditioner,Vector,VectorSpace>::set_inverse_parameters(Teuchos::ParameterList& plist)
{
InvIt::set_inverse_parameters(plist);
controller_start_ = plist.get<int>("controller training start", 0);
controller_end_ = plist.get<int>("controller training end", 3);
controller_end_ = std::max(controller_end_, controller_start_ + 1);
left_pc_ = (plist.get<std::string>("preconditioning strategy", "left") == "left");
deflation_ = plist.get<int>("maximum size of deflation space", 0);
num_ritz_ = 0;
}
/* ******************************************************************
* Givens rotations: initialization
****************************************************************** */
template<class Matrix,class Preconditioner,class Vector,class VectorSpace>
void IterativeMethodGMRES<Matrix,Preconditioner,Vector,VectorSpace>::InitGivensRotation_(
double& dx, double& dy, double& cs, double& sn) const
{
if (dy == 0.0) {
cs = 1.0;
sn = 0.0;
} else if (fabs(dy) > fabs(dx)) {
double tmp = dx / dy;
sn = 1.0 / sqrt(1.0 + tmp * tmp);
cs = tmp * sn;
} else {
double tmp = dy / dx;
cs = 1.0 / sqrt(1.0 + tmp * tmp);
sn = tmp * cs;
}
}
/* ******************************************************************
* Givens rotations: applications
****************************************************************** */
template<class Matrix,class Preconditioner,class Vector,class VectorSpace>
void IterativeMethodGMRES<Matrix,Preconditioner,Vector,VectorSpace>::ApplyGivensRotation_(
double& dx, double& dy, double& cs, double& sn) const
{
double tmp = cs * dx + sn * dy;
dy = -sn * dx + cs * dy;
dx = tmp;
}
/* ******************************************************************
* Computation of the solution destroys vector s.
* Right preconditioner uses two auxiliary vectors p and r.
****************************************************************** */
template<class Matrix,class Preconditioner,class Vector,class VectorSpace>
void IterativeMethodGMRES<Matrix,Preconditioner,Vector,VectorSpace>::ComputeSolution_(
Vector& x, int k, WhetStone::DenseMatrix& T, double* s,
Vector& p, Vector& r) const
{
for (int i = k; i >= 0; i--) {
s[i] /= T(i, i);
for (int j = i - 1; j >= 0; j--) {
s[j] -= T(j, i) * s[i];
}
}
// solution is x = x0 + V s for the left preconditioner
// and x = x0 + H V s for the right preconditioner
if (left_pc_) {
for (int j = 0; j <= k; j++) {
x.Update(s[j], *(v_[j]), 1.0);
}
} else {
p.PutScalar(0.0);
for (int j = 0; j <= k; j++) {
p.Update(s[j], *(v_[j]), 1.0);
}
h_->ApplyInverse(p, r);
x.Update(1.0, r, 1.0);
}
}
/* ******************************************************************
* solution is x = x0 + V s for the left preconditioner
* and x = x0 + H V s for the right preconditioner
****************************************************************** */
template<class Matrix,class Preconditioner,class Vector,class VectorSpace>
void IterativeMethodGMRES<Matrix,Preconditioner,Vector,VectorSpace>::ComputeSolution_(
Vector& x, double* d, Vector& p, Vector& r) const
{
if (left_pc_) {
for (int j = 0; j < krylov_dim_; j++) {
x.Update(d[j], *(v_[j]), 1.0);
}
} else {
p.PutScalar(0.0);
for (int j = 0; j < krylov_dim_; j++) {
p.Update(d[j], *(v_[j]), 1.0);
}
h_->ApplyInverse(p, r);
x.Update(1.0, r, 1.0);
}
}
} // namespace AmanziSolvers
} // namespace Amanzi
#endif
| 32.336013 | 122 | 0.596231 | cannsudemir |
83f1c30c1e8023b63550ae30882cfaacc6c1e6d8 | 763 | cpp | C++ | Binary Search Of Sorted Data.cpp | sayanroy058/C-Programs | 2bb591d5a322d1bf10e8a1627d92db05cb0ece75 | [
"CC0-1.0"
] | 2 | 2019-09-11T16:22:30.000Z | 2019-09-19T18:29:42.000Z | Binary Search Of Sorted Data.cpp | sayanroy058/C-Programs | 2bb591d5a322d1bf10e8a1627d92db05cb0ece75 | [
"CC0-1.0"
] | null | null | null | Binary Search Of Sorted Data.cpp | sayanroy058/C-Programs | 2bb591d5a322d1bf10e8a1627d92db05cb0ece75 | [
"CC0-1.0"
] | null | null | null | #include<stdio.h>
int main()
{
int i,n,a[100],first,last,mid,search;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Enter the numbers:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nEnter the number to find: ");
scanf("%d", &search);
first = 0;
last = n - 1;
mid = (first+last)/2;
while (first <= last)
{
if (a[mid] < search)
{
first = mid + 1;
}
else if (a[mid] == search)
{
printf("%d is present at index %d", search, mid+1);
break;
}
else
{
last = mid - 1;
}
mid = (first + last)/2;
}
if (first > last)
{
printf("%d is not present in the list", search);
}
}
| 19.564103 | 55 | 0.453473 | sayanroy058 |
83f345970389c281998c42889509a5cd765b34fe | 11,180 | cpp | C++ | src/solutions/aoc_day_24.cpp | bcooperstl/advent-of-code-2015 | 0aac084b72aeb45ca01a6ec52e0a71502dfa28e0 | [
"MIT"
] | null | null | null | src/solutions/aoc_day_24.cpp | bcooperstl/advent-of-code-2015 | 0aac084b72aeb45ca01a6ec52e0a71502dfa28e0 | [
"MIT"
] | null | null | null | src/solutions/aoc_day_24.cpp | bcooperstl/advent-of-code-2015 | 0aac084b72aeb45ca01a6ec52e0a71502dfa28e0 | [
"MIT"
] | null | null | null | #include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <climits>
#include <cstring>
#include <algorithm>
#include "aoc_day_24.h"
#include "file_utils.h"
using namespace std;
AocDay24::AocDay24():AocDay(24)
{
}
AocDay24::~AocDay24()
{
}
vector<long> AocDay24::parse_input(string filename)
{
vector<long> values;
FileUtils fileutils;
if (!fileutils.read_as_list_of_longs(filename, values))
{
cerr << "Error reading in the data from " << filename << endl;
return values;
}
sort(values.begin(), values.end(), greater<long>());
return values;
}
long AocDay24::calculate_qr(long * weights, int num_weights)
{
long ret = 1;
for (int i=0; i<num_weights; i++)
{
ret *= weights[i];
}
return ret;
}
bool AocDay24::can_split_remainder_to_equal(long * values, int num_values, long target)
{
/*
going to look for target assuming that the first value is included.
since this is looking to split the values into two groups totalling target, it must be in one of the pairs
*/
// going to use the bits to determine whether in or out of group 1
long max_number = (1 << (num_values - 1)) - 1;
for (int i=0; i<=max_number; i++)
{
long sum = values[0];
/*
lets say we have 7 digits
values[0] is always included
will extract from values[1] to values[6], depending upon the number
shift goes from 0 to 5 in this case
*/
for (int shift = 0; shift < num_values - 1; shift++)
{
if (i & (1 << shift))
{
sum += values[num_values-shift-1]; // need the - 1 because we are zero-indexed
}
}
if (sum == target)
{
return true;
}
}
return false;
}
bool AocDay24::next_position(long * input, int input_size, int output_size, long * values, int * positions, long & current_sum)
{
// sort of doing counting with the position array.
//
for (int i = output_size - 1; i>=0; i--)
{
/*
minimum at position i is i: 0 for the first position, 1 for the second postion ... i-1 for the ith position
maximum at position i is input_size - (output_size - i). so
if 10 input elements and 3 output elmeents
i = 0 can go from 0 to 7
i = 1 can go from 1 to 8
i = 2 can go from 2 to 9
*/
if (positions[i] == (input_size - (output_size - i)))
{
if (i == 0)
{
cout << " Should be done. Trying to carry beyond position 0" << endl;
return false;
}
// need to carry. Set this one back to i--
current_sum -= values[i];
positions[i] = i;
values[i] = input[positions[i]];
current_sum += values[i];
}
else
{
// not carrying here. increment to the next value and stop
current_sum -= values[i];
positions[i]++;
values[i] = input[positions[i]];
current_sum += values[i];
break;
}
}
return true;
}
// input is sorted from largest to smallest
bool AocDay24::find_best_partition_3(long * input, int input_size, int output_size, long target, long * best_values, long & best_qr)
{
cout << "Searching for best partition to make " << target << " out of " << output_size << " weights" << endl;
long values[MAX_VALUES];
int positions[MAX_VALUES];
int num_used = 0;
bool best_found = false;
long shortcut_sum = 0;
for (int i=0; i<output_size; i++)
{
shortcut_sum += input[i];
}
if (shortcut_sum < target)
{
cout << " Cannot make " << target << " out of the largest " << output_size << " weights. Shortcutting and returning false" << endl;
return false;
}
long current_sum = 0;
for (int i=0; i<output_size; i++)
{
values[i] = input[i];
positions[i] = i;
current_sum += input[i];
}
bool valid_position = true;
while (valid_position)
{
//cout << " Checking ";
//for (int i=0; i<output_size; i++)
//{
// cout << " " << values[i];
//}
//cout << endl;
if (current_sum == target)
{
//cout << " Potential match with";
//for (int i=0; i<output_size; i++)
//{
// cout << " " << values[i];
//}
//cout << endl;
long remaining_values[MAX_VALUES];
int remaining_pos = 0;
for (int j=0; j<input_size; j++)
{
bool in_sum = false;
for (int i=0; i<output_size; i++)
{
if (positions[i] == j)
{
in_sum = true;
break;
}
}
if (!in_sum)
{
remaining_values[remaining_pos] = input[j];
remaining_pos++;
}
}
long qr = calculate_qr(values, output_size);
if (qr < best_qr)
{
cout << " Potential best qr of " << qr << endl;
if (can_split_remainder_to_equal(remaining_values, remaining_pos, target))
{
cout << " Remaining values can be split. Good load possibility" << endl;
cout << " NEW BEST QR OF " << qr << " FOUND!" << endl;
best_qr = qr;
best_found = true;
for (int i=0; i<output_size; i++)
{
best_values[i] = values[i];
}
}
else
{
cout << " Cannot split remaining values into two equal part" << endl;
}
}
}
valid_position = next_position(input, input_size, output_size, values, positions, current_sum);
}
return best_found;
}
// input is sorted from largest to smallest
bool AocDay24::find_best_partition_4(long * input, int input_size, int output_size, long target, long * best_values, long & best_qr)
{
cout << "Searching for best partition to make " << target << " out of " << output_size << " weights" << endl;
long values[MAX_VALUES];
int positions[MAX_VALUES];
int num_used = 0;
bool best_found = false;
long shortcut_sum = 0;
for (int i=0; i<output_size; i++)
{
shortcut_sum += input[i];
}
if (shortcut_sum < target)
{
cout << " Cannot make " << target << " out of the largest " << output_size << " weights. Shortcutting and returning false" << endl;
return false;
}
long current_sum = 0;
for (int i=0; i<output_size; i++)
{
values[i] = input[i];
positions[i] = i;
current_sum += input[i];
}
bool valid_position = true;
while (valid_position)
{
//cout << " Checking ";
//for (int i=0; i<output_size; i++)
//{
// cout << " " << values[i];
//}
//cout << endl;
if (current_sum == target)
{
//cout << " Potential match with";
//for (int i=0; i<output_size; i++)
//{
// cout << " " << values[i];
//}
//cout << endl;
long remaining_values[MAX_VALUES];
int remaining_pos = 0;
for (int j=0; j<input_size; j++)
{
bool in_sum = false;
for (int i=0; i<output_size; i++)
{
if (positions[i] == j)
{
in_sum = true;
break;
}
}
if (!in_sum)
{
remaining_values[remaining_pos] = input[j];
remaining_pos++;
}
}
long qr = calculate_qr(values, output_size);
if (qr < best_qr)
{
cout << " Potential 4 best qr of " << qr << endl;
int new_output_size = 1;
bool found = false;
long best_values_3[MAX_VALUES]; // dont care; need it as a placeholder
long best_qr_3 = LONG_MAX; // dont care; need it as a placeholder
while (new_output_size <= remaining_pos / 3)
{
if (find_best_partition_3(remaining_values, remaining_pos, new_output_size, target, best_values_3, best_qr_3))
{
cout << " Remaining values can be split amongst 3 groups. Good load possibility" << endl;
cout << " NEW BEST 4 QR OF " << qr << " FOUND!" << endl;
best_qr = qr;
best_found = true;
for (int i=0; i<output_size; i++)
{
best_values[i] = values[i];
}
break;
found = true;
}
new_output_size++;
}
if (!found)
{
cout << " Cannot split remaining values into three equal parts" << endl;
}
}
}
valid_position = next_position(input, input_size, output_size, values, positions, current_sum);
}
return best_found;
}
string AocDay24::part1(string filename, vector<string> extra_args)
{
long all_values[MAX_VALUES];
long best_values[MAX_VALUES];
long best_qr = LONG_MAX;
long sum = 0;
long target;
vector<long> weights = parse_input(filename);
for (int i=0; i<weights.size(); i++)
{
all_values[i] = weights[i];
sum += all_values[i];
}
target = sum / 3;
int i = 1;
while (!find_best_partition_3(all_values, weights.size(), i, target, best_values, best_qr))
{
i++;
}
ostringstream out;
out << best_qr;
return out.str();
}
string AocDay24::part2(string filename, vector<string> extra_args)
{
long all_values[MAX_VALUES];
long best_values[MAX_VALUES];
long best_qr = LONG_MAX;
long sum = 0;
long target;
vector<long> weights = parse_input(filename);
for (int i=0; i<weights.size(); i++)
{
all_values[i] = weights[i];
sum += all_values[i];
}
target = sum / 4;
int i = 1;
while (!find_best_partition_4(all_values, weights.size(), i, target, best_values, best_qr))
{
i++;
}
ostringstream out;
out << best_qr;
return out.str();
}
| 28.090452 | 139 | 0.482916 | bcooperstl |
83f3b75ec118548069b9602517506e1e5b47b0b7 | 6,422 | hpp | C++ | _engine/code/include/_doxygen/3_code_convention.hpp | Shelim/pixie_engine | bf1d80f3f03bd3d6890f4dfc63440f7dd0ff34a1 | [
"MIT"
] | null | null | null | _engine/code/include/_doxygen/3_code_convention.hpp | Shelim/pixie_engine | bf1d80f3f03bd3d6890f4dfc63440f7dd0ff34a1 | [
"MIT"
] | null | null | null | _engine/code/include/_doxygen/3_code_convention.hpp | Shelim/pixie_engine | bf1d80f3f03bd3d6890f4dfc63440f7dd0ff34a1 | [
"MIT"
] | null | null | null | /**
* \~English @page code_convention Code Convention
* @tableofcontents
* @section code_convention_naming Naming conventions
*
* 1. All names are lowercase with underscores as word separator (ie. `hello_world`)
* 2. Basic name pattern:
* - `object_property` (ie. `game_name`)
* - `action_object_property` (ie. `new_window_handle`)
* - More than one words allowed with underscore as well (ie. `new_game_window_handle`)
* - All types have `_t` suffix, like `game_handle_t`
* - No Hungarian Notation!
* 3. Naming list:
* - `asset` -> Any non-hardcoded piece of data that can be modded. See `content`
* - `build_number` -> Number incremented each time a compilation is run (debug/hybrid/final)
* - `changelog` -> Directory containg all past final builds, for auto-updater
* - `component` -> Single-responsible part of application. All components can be turned off by replacing its functionality with simple dummies
* - `concurrention` -> Multi threaded-aware piece of code
* - `config` -> Runtime user-modificable configuration of application. Usually stored in platform storage
* - `console` -> In-game I/O terminal
* - `container` -> Usually C++'s Standard Template Library container, or custom one
* - `content` -> All `assets`
* - `data` -> Piece of information for engine. Common term for `assets`, `config` files, user profiles, saves, etc.
* - `debug` -> Output configuration intended on running only on developer machine. Also piece of code only to be used in debug. See @ref build_configuration "build specification"
* - `dependency` -> Other party piece of code or application that is used inside Pixie engine
* - `environment` -> Specification of machine running pixie (usually end user machine)
* - `final` -> Output configuration inteded for relese. Beside application it will build auto-updater script and prepare them to push to repository. See @ref build_configuration "build specification"
* - `hybrid` -> Output configuration inteded for testers. It is faster then debug and does not contain debugging symbols. Can be open-tested. See @ref build_configuration "build specification"
* - `logger` -> A way to dump information to a text file for bug checking on end user machines
* - `manifest` -> metadata for given item
* - `module` -> Large logical data-pack of assets. Each running game is composed of one or more modules. Example: large chapters/Total Conversion mods; See: `submodule`
* - `platform` -> Target PC. See `environment` (borader term)
* - `private` -> A thing to be used by developer himself and not included in final build
* - `project` -> Project for given platform (like Visual Studio for Windows, XCode for OS_X, etc.)
* - `provider` -> Simple class giving small pieces of information to other classes (like default path)
* - `release` -> Common name for `hybrid` and `final` output configuration. See @ref build_configuration "build specification"
* - `settings` -> Compile-time engine-wide settings. Needs to be passed to `bootstrapper`
* - `std` -> Macros controlling various engine-wide definitions. Usually used to expand features by client application without need for tampering with engine internals. Have little to no runtime impact. See @ref std
* - `submodule` -> Smaller logical data-pack of assets. Each running game can have zero or more active submodules. Example: DLC or mini-mods; See: `module`
* - `terminal` -> Usually end machine console, unless it does not have one
* - `utility` -> Simple class and functions for rest engine to utilize
*
* @section code_convention_code Code conventions
* @code{.cpp}
*
* // no 'using namespace' ever. Ever.
*
* namespace game
* {
* void foo(int a, int b = 5) { return a + b; } // single line allowed for simple functions
* void bar(int a, int b)
* {
* int ret = 5;
* ret += b;
* return ret;
* }
*
* class baz_t // types always end with _t
* {
*
* public: // separate line, aligned to class
*
* baz_t(std::shared_ptr<logger_t> logger) : logger(logger) // Use dependency injection
* {
*
* }
*
* virtual ~baz_t()
* {
*
* }
*
* int get_foo() const // accessor
* {
* return foo;
* }
* void set_foo(int val) // argument name always 'val'
* {
* foo = val; // no this->
* }
*
* void do_nothing()
* {
* // Do nothing because blah, blah blah <- empty functions require comments!
* }
*
* void long_operation(); // defnition in source
*
* virtual void sample() = 0; // no non-pure virtuals, unless you want some default functionality
*
* void operate()
* {
* set_foo(5);
* operate_local(); // _local for virtual methods of the same name
* }
*
* protected:
*
* std::shared_ptr<logger_t> get_logger()
* {
* return logger;
* }
*
* private:
*
* int foo;
* virtual void operate_local() = 0;
* std::shared_ptr<logger_t> logger;
*
* };
*
* class baz2_t : public baz_t // no final here, it get messed with Depedency Injection... :-(
* {
*
* public:
*
* baz2_t(std::shared_ptr<logger_t> logger) : baz_t(logger)
* {
*
* }
*
*
* void sample() final // no virtual if its final!
* {
* operate(); // call base class. No this!
* }
*
* private:
*
*
* void operate_local()
* {
* get_logger()->log_msg(core, "Simple log message"_u);
* }
*
* }
*
* template<class arg_t> class foo_t // template arguments as `class`. Lowercase.
* {
*
* public:
* int get_a()
* {
* return a; // no static variables!
* }
*
* private:
*
* int a; // no direct expsoure
* }
*
* } // each bracket in own line
*
* @endcode
*/ | 41.432258 | 221 | 0.587045 | Shelim |
83f7845f1c2aa54807b7852bd4abf43ee7add616 | 787 | cpp | C++ | unit_test/hash_map/testhashmap.cpp | filipecalasans/algo-study | dcfc1beebad7a958e7611794f2b88fcd487aaf17 | [
"MIT"
] | 1 | 2021-06-02T13:35:54.000Z | 2021-06-02T13:35:54.000Z | unit_test/hash_map/testhashmap.cpp | filipecalasans/algo-study | dcfc1beebad7a958e7611794f2b88fcd487aaf17 | [
"MIT"
] | null | null | null | unit_test/hash_map/testhashmap.cpp | filipecalasans/algo-study | dcfc1beebad7a958e7611794f2b88fcd487aaf17 | [
"MIT"
] | null | null | null | #include "hash_map/hashmap.h"
#include "gtest/gtest.h"
using namespace Algos;
struct DataTest {
int integer;
bool boolean;
std::string txt;
//DataTest() {}
//DataTest(const DataTest& other) {
// *this = other;
//}
DataTest& operator=(const DataTest& other) {
integer = other.integer;
boolean = other.boolean;
txt = other.txt;
return (*this);
}
bool operator==(const DataTest& other) const {
return (
integer == other.integer &&
boolean == other.boolean &&
txt == other.txt
);
}
};
#define TEST_SIZE 100
void initDataTest(DataTest *t, int n) {
for(int i=0; i<n; i++) {
t[i].integer = i;
t[i].boolean = (i%2 == 0);
t[i].txt = "abc";
}
}
TEST(Hash_table, init)
{
}
| 16.395833 | 49 | 0.557814 | filipecalasans |
83f9eb15dd0684ee475f8113de9ed5a10d9288e0 | 1,163 | cpp | C++ | Week_4/07 Practice Programming Assignment/Example.cpp | Animart/basics-of-c-plus-plus-development-white-belt | 9ad0aec57a54e505955ad4a93a0636903ba92822 | [
"Unlicense"
] | 1 | 2018-11-22T17:33:45.000Z | 2018-11-22T17:33:45.000Z | Week_4/07 Practice Programming Assignment/Example.cpp | Animart/basics-of-c-plus-plus-development-white-belt | 9ad0aec57a54e505955ad4a93a0636903ba92822 | [
"Unlicense"
] | null | null | null | Week_4/07 Practice Programming Assignment/Example.cpp | Animart/basics-of-c-plus-plus-development-white-belt | 9ad0aec57a54e505955ad4a93a0636903ba92822 | [
"Unlicense"
] | 1 | 2021-03-09T05:26:37.000Z | 2021-03-09T05:26:37.000Z | #include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Student
{
Student(string other_firstname, string other_lastname, int other_day, int other_month, int other_year)
{
firstname = other_firstname;
lastname = other_lastname;
day = other_day;
month = other_month;
year = other_year;
}
string firstname = "";
string lastname = "";
int day = 0;
int month = 0;
int year = 0;
};
int main()
{
string firstname, lastname;
int day, month, year;
vector<Student> v;
int n;
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> firstname >> lastname >> day >> month >> year;
Student student{ firstname, lastname, day, month, year };
v.push_back(student);
}
int m;
cin >> m;
for (int j = 0; j < m; ++j)
{
string operation;
int k;
cin >> operation >> k;
if (operation == "name" && k > 0 && k <= v.size())
{
cout << v[k - 1].firstname << " " << v[k - 1].lastname << endl;
}
else
if (operation == "date" && k > 0 && k <= v.size())
{
cout << v[k - 1].day << "." << v[k - 1].month << "." << v[k - 1].year << endl;
}
else
{
cout << "bad request" << endl;
}
}
return 0;
} | 18.171875 | 104 | 0.566638 | Animart |
8601eabd81abaf62c1cfd315585781d8518f0468 | 41,261 | cpp | C++ | src/vulkansubsystem/vulkansubsystem.cpp | kirdaybov/renderingengine | c6979cb1e2f2ca8668e71c46534283d370538cd1 | [
"MIT"
] | 2 | 2021-03-07T16:30:59.000Z | 2022-02-21T15:31:21.000Z | src/vulkansubsystem/vulkansubsystem.cpp | kirdaybov/renderingengine | c6979cb1e2f2ca8668e71c46534283d370538cd1 | [
"MIT"
] | null | null | null | src/vulkansubsystem/vulkansubsystem.cpp | kirdaybov/renderingengine | c6979cb1e2f2ca8668e71c46534283d370538cd1 | [
"MIT"
] | null | null | null | #include "vulkansubsystem.h"
#include "config.h"
#include "logger/logger.h"
#include <vector>
#include <set>
#include <algorithm>
#include <chrono>
#include <array>
#include "assetmanager/assetmanager.h"
#include <GLFW/glfw3.h>
#include <GLFW/glfw3native.h>
#include "app/application.h"
#include "imguirenderable.h"
#include "meshrenderable.h"
#include "screenrenderable.h"
#include <thread>
void Renderer::Init(GLFWwindow* window)
{
CreateInstance();
if (m_EnableValidationLayers)
{
SetupDebugMessenger();
}
CreateSurface(window);
m_Window = window;
PickPhysicalDevice();
CreateLogicalDevice();
CreateSwapChain();
CreateImageViews();
CreateRenderPass();
m_Renderables.push_back(new MeshRenderable());
m_Renderables.push_back(new ScreenRenderable());
m_Renderables.push_back(new ImGuiRenderable());
CreateCommandPool();
CreateDepthResources();
CreateFramebuffers();
CreateSyncObjects();
for (IRenderable* renderable : m_Renderables)
{
renderable->Init();
}
}
void Renderer::Cleanup()
{
for (IRenderable* renderable : m_Renderables)
{
renderable->Cleanup();
delete renderable;
}
CleanupSwapChain();
for (size_t i = 0; i < MaxFramesInFlight; i++)
{
vkDestroySemaphore(m_Device, m_RenderFinishedSemaphores[i], nullptr);
vkDestroySemaphore(m_Device, m_ImageAvailableSemaphores[i], nullptr);
vkDestroyFence(m_Device, m_InFlightFences[i], nullptr);
}
vkDestroyCommandPool(m_Device, m_CommandPool, nullptr);
m_BufferPool.Cleanup();
vkDestroyDevice(m_Device, nullptr);
if (m_EnableValidationLayers)
DestroyDebugUtilsMessengerEXT(m_Instance, m_DebugMessenger, nullptr);
vkDestroySurfaceKHR(m_Instance, m_Surface, nullptr);
vkDestroyInstance(m_Instance, nullptr);
}
#define MEGABYTE (1024*1024)
void Renderer::Update()
{
m_BufferPool.Update();
if (ImGui::Begin("GPU stats"))
{
VkPhysicalDeviceMemoryBudgetPropertiesEXT budgetProperty;
budgetProperty.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT;
budgetProperty.pNext = nullptr;
VkPhysicalDeviceMemoryProperties2 memProperty;
memProperty.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2;
memProperty.pNext = &budgetProperty;
vkGetPhysicalDeviceMemoryProperties2(m_PhysicalDevice, &memProperty);
for (unsigned int i = 0; i < memProperty.memoryProperties.memoryHeapCount; i++)
{
ImGui::Text("Heap %i: %.2f/%.2fMb", i, budgetProperty.heapUsage[i]/float(MEGABYTE), budgetProperty.heapBudget[i] / float(MEGABYTE));
}
ImGui::End();
}
if (ImGui::Begin("Passes"))
{
for (auto& renderable : m_Renderables)
{
ImGui::Checkbox(renderable->GetName(), &renderable->GetShow());
}
ImGui::Checkbox("Lock FPS", &m_IsFPSLocked);
ImGui::DragInt("Lock FPS at", &m_LockedFPS, 1, 30, 144);
ImGui::End();
}
}
void Renderer::CleanupSwapChain()
{
vkDestroyImageView(m_Device, m_DepthImageView, nullptr);
vkDestroyImage(m_Device, m_DepthImage, nullptr);
vkFreeMemory(m_Device, m_DepthImageMemory, nullptr);
for (auto framebuffer : m_SwapChainFramebuffers)
{
vkDestroyFramebuffer(m_Device, framebuffer, nullptr);
}
vkFreeCommandBuffers(m_Device, m_CommandPool, static_cast<uint32_t>(m_CommandBuffers.size()), m_CommandBuffers.data());
vkDestroyRenderPass(m_Device, m_RenderPass, nullptr);
for (auto& imageView : m_SwapChainImageViews)
{
vkDestroyImageView(m_Device, imageView, nullptr);
}
vkDestroySwapchainKHR(m_Device, m_SwapChain, nullptr);
}
void Renderer::RecreateSwapChain()
{
vkDeviceWaitIdle(m_Device);
CleanupSwapChain();
for (IRenderable* renderable : m_Renderables)
{
renderable->OnCleanupSwapChain();
}
CreateSwapChain();
CreateImageViews();
CreateRenderPass();
for (IRenderable* renderable : m_Renderables)
{
renderable->CreateGraphicsPipeline();
}
CreateDepthResources();
CreateFramebuffers();
for (int i = 0; i < m_SwapChainImages.size(); i++)
{
CreateCommandBuffers(i);
}
}
void Renderer::CreateInstance()
{
ListAvailableExtensions();
//ListAvailableValidationLayers();
if (m_EnableValidationLayers && !CheckValidationLayerSupport())
{
DEBUG_BREAK("VK error: validation layers are not supported");
}
VkApplicationInfo applicationInfo = {};
applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
applicationInfo.pApplicationName = Consts::ms_ProjectName;
applicationInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
applicationInfo.pEngineName = Consts::ms_EngineName;
applicationInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
applicationInfo.apiVersion = VK_API_VERSION_1_0;
VkInstanceCreateInfo instanceCreateInfo = {};
instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceCreateInfo.pApplicationInfo = &applicationInfo;
auto extensions = GetRequiredExtensions();
instanceCreateInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
instanceCreateInfo.ppEnabledExtensionNames = extensions.data();
if (m_EnableValidationLayers)
{
instanceCreateInfo.enabledLayerCount = static_cast<uint32_t>(m_ValidationLayers.size());
instanceCreateInfo.ppEnabledLayerNames = m_ValidationLayers.data();
}
else
{
instanceCreateInfo.enabledLayerCount = 0;
}
VK_CHECK(vkCreateInstance(&instanceCreateInfo, nullptr, &m_Instance));
}
void Renderer::ListAvailableExtensions() const
{
uint32_t extensionCount = 0;
vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr);
std::vector<VkExtensionProperties> extensions(extensionCount);
vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, extensions.data());
for (auto& extension : extensions)
LOGF("Extension: %s", extension.extensionName);
}
void Renderer::ListAvailableValidationLayers() const
{
uint32_t validationLayerCount = 0;
vkEnumerateInstanceLayerProperties(&validationLayerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(validationLayerCount);
vkEnumerateInstanceLayerProperties(&validationLayerCount, availableLayers.data());
for (auto& layer : availableLayers)
LOGF("Layer: %s", layer.layerName);
}
bool Renderer::CheckValidationLayerSupport() const
{
uint32_t validationLayerCount = 0;
vkEnumerateInstanceLayerProperties(&validationLayerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(validationLayerCount);
vkEnumerateInstanceLayerProperties(&validationLayerCount, availableLayers.data());
bool supported = true;
for (auto& validationLayer : m_ValidationLayers)
{
bool layerFound = false;
for (auto& availableLayer : availableLayers)
{
if (strcmp(validationLayer, availableLayer.layerName) == 0)
{
layerFound = true;
break;
}
}
if (!layerFound)
{
LOGF("Layer is not supported: %s", validationLayer);
supported = false;
}
}
return supported;
}
std::vector<const char*> Renderer::GetRequiredExtensions() const
{
uint32_t glfwExtensionCount = 0;
const char** glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
std::vector<const char*> extensions(glfwExtensions, glfwExtensions + glfwExtensionCount);
if (m_EnableValidationLayers)
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
extensions.push_back("VK_KHR_surface");
extensions.push_back("VK_KHR_win32_surface");
extensions.push_back("VK_KHR_get_physical_device_properties2");
return extensions;
}
VKAPI_ATTR VkBool32 VKAPI_CALL Renderer::DebugCallback(
VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT* callbackData,
void* userData
)
{
if (messageSeverity & (VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT))
{
DEBUG_BREAK("Validation layer: %s", callbackData->pMessage);
}
else
{
LOGF("Validation layer: %s", callbackData->pMessage);
}
return VK_FALSE;
}
void Renderer::SetupDebugMessenger()
{
VkDebugUtilsMessengerCreateInfoEXT createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
createInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
createInfo.pfnUserCallback = DebugCallback;
createInfo.pUserData = nullptr;
if (CreateDebugUtilsMessengerEXT(m_Instance, &createInfo, nullptr, &m_DebugMessenger) != VK_SUCCESS)
DEBUG_BREAK("Vk error: couldn't create debug messenger");
}
VkResult Renderer::CreateDebugUtilsMessengerEXT(
VkInstance instance,
const VkDebugUtilsMessengerCreateInfoEXT* createInfo,
const VkAllocationCallbacks* allocator,
VkDebugUtilsMessengerEXT* debugMessenger
)
{
auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
if (func != nullptr)
{
return func(instance, createInfo, allocator, debugMessenger);
}
else
{
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
}
void Renderer::DestroyDebugUtilsMessengerEXT(
VkInstance instance,
VkDebugUtilsMessengerEXT debugMessenger,
const VkAllocationCallbacks* allocator
)
{
auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
if (func != nullptr) {
func(instance, debugMessenger, allocator);
}
}
void Renderer::CreateSurface(GLFWwindow* window)
{
VkWin32SurfaceCreateInfoKHR createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
createInfo.hwnd = glfwGetWin32Window(window);
createInfo.hinstance = GetModuleHandle(nullptr);
if (vkCreateWin32SurfaceKHR(m_Instance, &createInfo, nullptr, &m_Surface) != VK_SUCCESS)
DEBUG_BREAK("Vk error: couldn't create surface");
}
void Renderer::PickPhysicalDevice()
{
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(m_Instance, &deviceCount, nullptr);
std::vector<VkPhysicalDevice> devices(deviceCount);
vkEnumeratePhysicalDevices(m_Instance, &deviceCount, devices.data());
for (auto& device : devices)
{
if (IsDeviceSuitable(device))
{
m_PhysicalDevice = device;
break;
}
}
if (m_PhysicalDevice == VK_NULL_HANDLE)
DEBUG_BREAK("Vk error: couldn't find suitable device");
}
bool Renderer::IsDeviceSuitable(VkPhysicalDevice device) const
{
bool extensionsSupported = CheckDeviceExtensionSupport(device);
bool swapChainAdequate = false;
if (extensionsSupported)
{
SwapChainSupportDetails details = QuerySwapChainSupport(device);
swapChainAdequate = !details.formats.empty() && !details.presentModes.empty();
}
VkPhysicalDeviceFeatures supportedFeatures;
vkGetPhysicalDeviceFeatures(device, &supportedFeatures);
return FindQueueFamilies(device).IsComplete() && swapChainAdequate && supportedFeatures.samplerAnisotropy;
}
bool Renderer::CheckDeviceExtensionSupport(VkPhysicalDevice device) const
{
uint32_t extensionCount;
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);
std::vector<VkExtensionProperties> availableExtensions(extensionCount);
vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data());
std::set<std::string> requiredExtensions(m_DeviceExtensions.begin(), m_DeviceExtensions.end());
for (const auto& extension : availableExtensions) {
requiredExtensions.erase(extension.extensionName);
}
return requiredExtensions.empty();
}
QueueFamilyIndices Renderer::FindQueueFamilies(VkPhysicalDevice device) const
{
QueueFamilyIndices indices;
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
int index = 0;
for (auto& queueFamily : queueFamilies)
{
if (queueFamily.queueCount > 0 && queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT)
indices.graphicsFamily = index;
VkBool32 presentSupport = false;
vkGetPhysicalDeviceSurfaceSupportKHR(device, index, m_Surface, &presentSupport);
if (queueFamily.queueCount > 0 && presentSupport)
indices.presentFamily = index;
++index;
}
return indices;
}
void Renderer::CreateLogicalDevice()
{
m_FamilyIndices = FindQueueFamilies(m_PhysicalDevice);
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
std::set<int> uniqueQueueFamilies =
{
m_FamilyIndices.graphicsFamily,
m_FamilyIndices.presentFamily
};
for (int queueFamily : uniqueQueueFamilies)
{
VkDeviceQueueCreateInfo queueCreateInfo = {};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.queueFamilyIndex = queueFamily;
queueCreateInfo.queueCount = 1;
float queuePriority = 1.f;
queueCreateInfo.pQueuePriorities = &queuePriority;
queueCreateInfos.push_back(queueCreateInfo);
}
VkPhysicalDeviceFeatures deviceFeatures = {};
deviceFeatures.samplerAnisotropy = VK_TRUE;
VkDeviceCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
createInfo.pQueueCreateInfos = queueCreateInfos.data();
createInfo.pEnabledFeatures = &deviceFeatures;
createInfo.enabledExtensionCount = static_cast<uint32_t>(m_DeviceExtensions.size());
createInfo.ppEnabledExtensionNames = m_DeviceExtensions.data();
if (m_EnableValidationLayers)
{
createInfo.enabledLayerCount = static_cast<uint32_t>(m_ValidationLayers.size());
createInfo.ppEnabledLayerNames = m_ValidationLayers.data();
}
else
{
createInfo.enabledLayerCount = 0;
}
if (vkCreateDevice(m_PhysicalDevice, &createInfo, nullptr, &m_Device) != VK_SUCCESS)
DEBUG_BREAK("Vk error: couldn't create logical device");
vkGetDeviceQueue(m_Device, m_FamilyIndices.graphicsFamily, 0, &m_GraphicsQueue);
vkGetDeviceQueue(m_Device, m_FamilyIndices.presentFamily, 0, &m_PresentQueue);
}
SwapChainSupportDetails Renderer::QuerySwapChainSupport(VkPhysicalDevice device) const
{
SwapChainSupportDetails details;
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, m_Surface, &details.capabilities);
uint32_t formatCount;
vkGetPhysicalDeviceSurfaceFormatsKHR(device, m_Surface, &formatCount, nullptr);
if (formatCount != 0)
{
details.formats.resize(formatCount);
vkGetPhysicalDeviceSurfaceFormatsKHR(device, m_Surface, &formatCount, details.formats.data());
}
uint32_t presentModeCount;
vkGetPhysicalDeviceSurfacePresentModesKHR(device, m_Surface, &presentModeCount, nullptr);
if (presentModeCount != 0) {
details.presentModes.resize(presentModeCount);
vkGetPhysicalDeviceSurfacePresentModesKHR(device, m_Surface, &presentModeCount, details.presentModes.data());
}
return details;
}
VkSurfaceFormatKHR Renderer::ChooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats)
{
SwapChainSupportDetails details = QuerySwapChainSupport(m_PhysicalDevice);
if (details.formats.size() == 1 && details.formats[0].format == VK_FORMAT_UNDEFINED)
{
return{ VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR };
}
for (const auto& format : details.formats)
{
if (format.format == VK_FORMAT_B8G8R8A8_UNORM && format.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
return format;
}
}
return details.formats[0];
}
VkPresentModeKHR Renderer::ChooseSwapPresentMode(const std::vector<VkPresentModeKHR> availablePresentModes)
{
VkPresentModeKHR bestMode = VK_PRESENT_MODE_FIFO_KHR;
for (const auto& availablePresentMode : availablePresentModes)
{
if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR)
{
return availablePresentMode;
}
else if (availablePresentMode == VK_PRESENT_MODE_IMMEDIATE_KHR)
{
bestMode = availablePresentMode;
}
}
return bestMode;
}
VkExtent2D Renderer::ChooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities)
{
if (capabilities.currentExtent.width != (std::numeric_limits<uint32_t>::max)())
{
return capabilities.currentExtent;
}
else
{
const int width = 1920;
const int height = 1080;
VkExtent2D actualExtent = { width, height };
actualExtent.width = (std::max)(capabilities.minImageExtent.width, (std::min)(capabilities.maxImageExtent.width, actualExtent.width));
actualExtent.height = (std::max)(capabilities.minImageExtent.height, (std::min)(capabilities.maxImageExtent.height, actualExtent.height));
return actualExtent;
}
}
void Renderer::CreateSwapChain()
{
SwapChainSupportDetails swapChainSupport = QuerySwapChainSupport(m_PhysicalDevice);
VkSurfaceFormatKHR surfaceFormat = ChooseSwapSurfaceFormat(swapChainSupport.formats);
VkPresentModeKHR presentMode = ChooseSwapPresentMode(swapChainSupport.presentModes);
VkExtent2D extent = ChooseSwapExtent(swapChainSupport.capabilities);
uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount)
{
imageCount = swapChainSupport.capabilities.maxImageCount;
}
VkSwapchainCreateInfoKHR createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
createInfo.surface = m_Surface;
createInfo.minImageCount = imageCount;
createInfo.imageFormat = surfaceFormat.format;
createInfo.imageColorSpace = surfaceFormat.colorSpace;
createInfo.imageExtent = extent;
createInfo.imageArrayLayers = 1;
createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
QueueFamilyIndices indices = FindQueueFamilies(m_PhysicalDevice);
uint32_t queueFamilyIndices[] = { static_cast<uint32_t>(indices.graphicsFamily), static_cast<uint32_t>(indices.presentFamily) };
if (indices.graphicsFamily != indices.presentFamily)
{
createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
createInfo.queueFamilyIndexCount = 2;
createInfo.pQueueFamilyIndices = queueFamilyIndices;
}
else
{
createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
createInfo.queueFamilyIndexCount = 0; // Optional
createInfo.pQueueFamilyIndices = nullptr; // Optional
}
createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
createInfo.presentMode = presentMode;
createInfo.clipped = VK_TRUE;
createInfo.oldSwapchain = VK_NULL_HANDLE;
if (vkCreateSwapchainKHR(m_Device, &createInfo, nullptr, &m_SwapChain) != VK_SUCCESS)
DEBUG_BREAK("Vk error: couldn't create swap chain");
vkGetSwapchainImagesKHR(m_Device, m_SwapChain, &imageCount, nullptr);
m_SwapChainImages.resize(imageCount);
vkGetSwapchainImagesKHR(m_Device, m_SwapChain, &imageCount, m_SwapChainImages.data());
m_SwapChainImageFormat = surfaceFormat.format;
m_SwapChainExtent = extent;
}
void Renderer::CreateImageViews()
{
m_SwapChainImageViews.resize(m_SwapChainImages.size());
for (int i = 0; i < m_SwapChainImages.size(); i++)
{
m_SwapChainImageViews[i] = CreateImageView(m_SwapChainImages[i], m_SwapChainImageFormat, VK_IMAGE_ASPECT_COLOR_BIT);
}
}
VkShaderModule Renderer::CreateShaderModule(char* code, int size)
{
VkShaderModuleCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
createInfo.codeSize = size;
createInfo.pCode = reinterpret_cast<const uint32_t*>(code);
VkShaderModule shaderModule;
if (vkCreateShaderModule(m_Device, &createInfo, nullptr, &shaderModule) != VK_SUCCESS) {
throw std::runtime_error("failed to create shader module!");
}
return shaderModule;
}
void Renderer::CreateRenderPass()
{
VkAttachmentDescription colorAttachment = {};
colorAttachment.format = m_SwapChainImageFormat;
colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentReference colorAttachmentRef = {};
colorAttachmentRef.attachment = 0;
colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentDescription depthAttachment = {};
depthAttachment.format = FindDepthFormat();
depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkAttachmentReference depthAttachmentRef = {};
depthAttachmentRef.attachment = 1;
depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass = {};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &colorAttachmentRef;
subpass.pDepthStencilAttachment = &depthAttachmentRef;
VkSubpassDependency dependency = {};
dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
dependency.dstSubpass = 0;
dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.srcAccessMask = 0;
dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
std::array<VkAttachmentDescription, 2> attachments = { colorAttachment, depthAttachment };
VkRenderPassCreateInfo renderPassInfo = {};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
renderPassInfo.pAttachments = attachments.data();
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpass;
renderPassInfo.dependencyCount = 1;
renderPassInfo.pDependencies = &dependency;
if (vkCreateRenderPass(m_Device, &renderPassInfo, nullptr, &m_RenderPass) != VK_SUCCESS)
{
throw std::runtime_error("failed to create render pass!");
}
}
void Renderer::CreateFramebuffers()
{
m_SwapChainFramebuffers.resize(m_SwapChainImageViews.size());
for (size_t i = 0; i < m_SwapChainImageViews.size(); i++)
{
std::array<VkImageView, 2> attachments = {
m_SwapChainImageViews[i],
m_DepthImageView
};
VkFramebufferCreateInfo framebufferInfo = {};
framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebufferInfo.renderPass = m_RenderPass;
framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
framebufferInfo.pAttachments = attachments.data();
framebufferInfo.width = m_SwapChainExtent.width;
framebufferInfo.height = m_SwapChainExtent.height;
framebufferInfo.layers = 1;
if (vkCreateFramebuffer(m_Device, &framebufferInfo, nullptr, &m_SwapChainFramebuffers[i]) != VK_SUCCESS)
{
throw std::runtime_error("failed to create framebuffer!");
}
}
}
void Renderer::CreateCommandPool()
{
QueueFamilyIndices queueFamilyIndices = FindQueueFamilies(m_PhysicalDevice);
VkCommandPoolCreateInfo poolInfo = {};
poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily;
poolInfo.flags = 0; // Optional
if (vkCreateCommandPool(m_Device, &poolInfo, nullptr, &m_CommandPool) != VK_SUCCESS) {
throw std::runtime_error("failed to create command pool!");
}
}
void Renderer::FreeCommandBuffers(uint32_t imageIdx)
{
//if (m_CommandBuffers.size() > 0)
//{
// vkFreeCommandBuffers(m_Device, m_CommandPool, static_cast<uint32_t>(m_CommandBuffers.size()), m_CommandBuffers.data());
//}
if (m_CommandBuffers.size() > 0)
{
vkFreeCommandBuffers(m_Device, m_CommandPool, 1, &m_CommandBuffers[imageIdx]);
}
}
void Renderer::CreateCommandBuffers(uint32_t imageIdx)
{
m_CommandBuffers.resize(m_SwapChainFramebuffers.size());
VkCommandBufferAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.commandPool = m_CommandPool;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = (uint32_t)m_CommandBuffers.size();
if (vkAllocateCommandBuffers(m_Device, &allocInfo, m_CommandBuffers.data()) != VK_SUCCESS)
{
throw std::runtime_error("failed to allocate command buffers!");
}
RenderContext ctx = { 0, 0, imageIdx };
for (IRenderable* renderable : m_Renderables)
{
renderable->Update(ctx);
}
for (size_t b = 0; b < m_CommandBuffers.size(); b++)
{
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
beginInfo.pInheritanceInfo = nullptr; // Optional
if (vkBeginCommandBuffer(m_CommandBuffers[b], &beginInfo) != VK_SUCCESS)
{
throw std::runtime_error("failed to begin recording command buffer!");
}
VkRenderPassBeginInfo renderPassInfo = {};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = m_RenderPass;
renderPassInfo.framebuffer = m_SwapChainFramebuffers[b];
renderPassInfo.renderArea.offset = { 0, 0 };
renderPassInfo.renderArea.extent = m_SwapChainExtent;
std::array<VkClearValue, 2> clearValues = {};
clearValues[0].color = { 0.0f, 0.0f, 0.0f, 1.0f };
clearValues[1].depthStencil = { 1.0f, 0 };
renderPassInfo.clearValueCount = static_cast<uint32_t>(clearValues.size());
renderPassInfo.pClearValues = clearValues.data();
vkCmdBeginRenderPass(m_CommandBuffers[b], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
ctx.m_CommandBuffer = m_CommandBuffers[b];
ctx.m_CommandBufferIdx = b;
for (IRenderable* renderable : m_Renderables)
{
if (renderable->GetShow())
{
renderable->Render(ctx);
}
}
vkCmdEndRenderPass(m_CommandBuffers[b]);
if (vkEndCommandBuffer(m_CommandBuffers[b]) != VK_SUCCESS)
{
throw std::runtime_error("failed to record command buffer!");
}
}
}
void Renderer::DrawFrame()
{
vkWaitForFences(m_Device, 1, &m_InFlightFences[m_CurrentFrame], VK_TRUE, (std::numeric_limits<uint64_t>::max)());
vkResetFences(m_Device, 1, &m_InFlightFences[m_CurrentFrame]);
uint32_t imageIndex;
if (vkAcquireNextImageKHR(m_Device, m_SwapChain, (std::numeric_limits<uint64_t>::max)(), m_ImageAvailableSemaphores[m_CurrentFrame], VK_NULL_HANDLE, &imageIndex)
== VK_ERROR_OUT_OF_DATE_KHR)
{
RecreateSwapChain();
return;
};
if (m_ShaderUpdateScheduled)
{
for (IRenderable* renderable : m_Renderables)
{
renderable->OnCleanupSwapChain();
renderable->CreateGraphicsPipeline();
}
m_ShaderUpdateScheduled = false;
}
FreeCommandBuffers(imageIndex);
CreateCommandBuffers(imageIndex);
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkSemaphore waitSemaphores[] = { m_ImageAvailableSemaphores[m_CurrentFrame] };
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = waitSemaphores;
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &m_CommandBuffers[imageIndex];
VkSemaphore signalSemaphores[] = { m_RenderFinishedSemaphores[m_CurrentFrame] };
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = signalSemaphores;
if (vkQueueSubmit(m_GraphicsQueue, 1, &submitInfo, m_InFlightFences[m_CurrentFrame]) != VK_SUCCESS)
{
throw std::runtime_error("failed to submit draw command buffer!");
}
VkPresentInfoKHR presentInfo = {};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = signalSemaphores;
VkSwapchainKHR swapChains[] = { m_SwapChain };
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = swapChains;
presentInfo.pImageIndices = &imageIndex;
presentInfo.pResults = nullptr;
if (m_IsFPSLocked)
{
float waitTime = 1.f / m_LockedFPS - gApp.GetTimer().GetFrameSeconds();
if (waitTime > 0)
{
std::this_thread::sleep_for(std::chrono::milliseconds(static_cast<int>(waitTime*1000)));
}
}
vkQueuePresentKHR(m_PresentQueue, &presentInfo);
m_CurrentFrame = (m_CurrentFrame + 1) % MaxFramesInFlight;
m_TotalFrame++;
}
void Renderer::CreateSyncObjects()
{
m_ImageAvailableSemaphores.resize(MaxFramesInFlight);
m_RenderFinishedSemaphores.resize(MaxFramesInFlight);
m_InFlightFences.resize(MaxFramesInFlight);
VkSemaphoreCreateInfo semaphoreInfo = {};
semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkFenceCreateInfo fenceInfo = {};
fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
for (size_t i = 0; i < MaxFramesInFlight; i++)
{
if (vkCreateSemaphore(m_Device, &semaphoreInfo, nullptr, &m_ImageAvailableSemaphores[i]) != VK_SUCCESS ||
vkCreateSemaphore(m_Device, &semaphoreInfo, nullptr, &m_RenderFinishedSemaphores[i]) != VK_SUCCESS ||
vkCreateFence(m_Device, &fenceInfo, nullptr, &m_InFlightFences[i]))
{
throw std::runtime_error("failed to create semaphores!");
}
}
}
void Renderer::CreateBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, Buffer& buffer)
{
VkBufferCreateInfo bufferInfo = {};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = size;
bufferInfo.usage = usage;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
VK_CHECK(vkCreateBuffer(m_Device, &bufferInfo, nullptr, &buffer.m_Buffer));
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(m_Device, buffer.m_Buffer, &memRequirements);
VkMemoryAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = FindMemoryType(memRequirements.memoryTypeBits, properties);
VK_CHECK(vkAllocateMemory(m_Device, &allocInfo, nullptr, &buffer.m_BufferMemory));
vkBindBufferMemory(m_Device, buffer.m_Buffer, buffer.m_BufferMemory, 0);
}
void Renderer::CreateBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory)
{
VkBufferCreateInfo bufferInfo = {};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = size;
bufferInfo.usage = usage;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateBuffer(m_Device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS)
{
throw std::runtime_error("failed to create vertex buffer!");
}
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(m_Device, buffer, &memRequirements);
VkMemoryAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = FindMemoryType(memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(m_Device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS)
{
throw std::runtime_error("failed to allocate vertex buffer memory!");
}
vkBindBufferMemory(m_Device, buffer, bufferMemory, 0);
}
Buffer* Renderer::CreateBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties)
{
Buffer* buffer = m_BufferPool.GetBuffer();
CreateBuffer(size, usage, properties, *buffer);
return buffer;
}
uint32_t Renderer::FindMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties)
{
VkPhysicalDeviceMemoryProperties memProperties;
vkGetPhysicalDeviceMemoryProperties(m_PhysicalDevice, &memProperties);
for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++)
{
if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties)
{
return i;
}
}
throw std::runtime_error("failed to find suitable memory type!");
}
void Renderer::CopyBuffer(Buffer& srcBuffer, Buffer& dstBuffer, VkDeviceSize size)
{
VkCommandBuffer commandBuffer = BeginSingleTimeCommands();
VkBufferCopy copyRegion = {};
copyRegion.srcOffset = 0; // Optional
copyRegion.dstOffset = 0; // Optional
copyRegion.size = size;
vkCmdCopyBuffer(commandBuffer, srcBuffer.m_Buffer, dstBuffer.m_Buffer, 1, ©Region);
EndSingleTimeCommands(commandBuffer);
}
void Renderer::CreateImage(uint32_t width, uint32_t height, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties, VkImage& image, VkDeviceMemory& imageMemory)
{
VkImageCreateInfo imageInfo = {};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.extent.width = width;
imageInfo.extent.height = height;
imageInfo.extent.depth = 1;
imageInfo.mipLevels = 1;
imageInfo.arrayLayers = 1;
imageInfo.format = format;
imageInfo.tiling = tiling;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.usage = usage;
imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateImage(m_Device, &imageInfo, nullptr, &image) != VK_SUCCESS) {
throw std::runtime_error("failed to create image!");
}
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(m_Device, image, &memRequirements);
VkMemoryAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = FindMemoryType(memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(m_Device, &allocInfo, nullptr, &imageMemory) != VK_SUCCESS)
{
throw std::runtime_error("failed to allocate image memory!");
}
vkBindImageMemory(m_Device, image, imageMemory, 0);
}
VkCommandBuffer Renderer::BeginSingleTimeCommands()
{
VkCommandBufferAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = m_CommandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(m_Device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
return commandBuffer;
}
void Renderer::EndSingleTimeCommands(VkCommandBuffer commandBuffer)
{
vkEndCommandBuffer(commandBuffer);
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(m_GraphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(m_GraphicsQueue);
vkFreeCommandBuffers(m_Device, m_CommandPool, 1, &commandBuffer);
}
void Renderer::TransitionImageLayout(VkImage image, VkFormat format, VkImageLayout oldLayout, VkImageLayout newLayout)
{
VkCommandBuffer commandBuffer = BeginSingleTimeCommands();
VkImageMemoryBarrier barrier = {};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL)
{
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
if (HasStencilComponent(format))
{
barrier.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
}
}
else
{
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
}
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
VkPipelineStageFlags sourceStage;
VkPipelineStageFlags destinationStage;
if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL)
{
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
}
else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)
{
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
}
else if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL) {
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
destinationStage = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
}
else
{
throw std::invalid_argument("unsupported layout transition!");
}
vkCmdPipelineBarrier(
commandBuffer,
sourceStage, destinationStage,
0,
0, nullptr,
0, nullptr,
1, &barrier
);
EndSingleTimeCommands(commandBuffer);
}
void Renderer::CopyBufferToImage(Buffer& buffer, VkImage image, uint32_t width, uint32_t height)
{
VkCommandBuffer commandBuffer = BeginSingleTimeCommands();
VkBufferImageCopy region = {};
region.bufferOffset = 0;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = { 0, 0, 0 };
region.imageExtent = {
width,
height,
1
};
vkCmdCopyBufferToImage(
commandBuffer,
buffer.GetBuffer(),
image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
®ion
);
EndSingleTimeCommands(commandBuffer);
}
VkImageView Renderer::CreateImageView(VkImage image, VkFormat format, VkImageAspectFlags aspectFlags)
{
VkImageViewCreateInfo viewInfo = {};
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.image = image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = format;
viewInfo.subresourceRange.aspectMask = aspectFlags;
viewInfo.subresourceRange.baseMipLevel = 0;
viewInfo.subresourceRange.levelCount = 1;
viewInfo.subresourceRange.baseArrayLayer = 0;
viewInfo.subresourceRange.layerCount = 1;
VkImageView imageView;
if (vkCreateImageView(m_Device, &viewInfo, nullptr, &imageView) != VK_SUCCESS)
{
throw std::runtime_error("failed to create texture image view!");
}
return imageView;
}
void Renderer::CreateDepthResources()
{
VkFormat depthFormat = FindDepthFormat();
CreateImage(m_SwapChainExtent.width, m_SwapChainExtent.height, depthFormat, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, m_DepthImage, m_DepthImageMemory);
m_DepthImageView = CreateImageView(m_DepthImage, depthFormat, VK_IMAGE_ASPECT_DEPTH_BIT);
TransitionImageLayout(m_DepthImage, depthFormat, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
}
VkFormat Renderer::FindSupportedFormat(const std::vector<VkFormat>& candidates, VkImageTiling tiling, VkFormatFeatureFlags features)
{
for (VkFormat format : candidates)
{
VkFormatProperties props;
vkGetPhysicalDeviceFormatProperties(m_PhysicalDevice, format, &props);
if (tiling == VK_IMAGE_TILING_LINEAR && (props.linearTilingFeatures & features) == features)
{
return format;
}
else if (tiling == VK_IMAGE_TILING_OPTIMAL && (props.optimalTilingFeatures & features) == features)
{
return format;
}
}
throw std::runtime_error("failed to find supported format!");
}
VkFormat Renderer::FindDepthFormat()
{
return FindSupportedFormat(
{ VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
VK_IMAGE_TILING_OPTIMAL,
VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
);
}
bool Renderer::HasStencilComponent(VkFormat format)
{
return format == VK_FORMAT_D32_SFLOAT_S8_UINT || format == VK_FORMAT_D24_UNORM_S8_UINT;
}
| 33.792793 | 219 | 0.774606 | kirdaybov |
8603a436782bcd4b9b52197f7b020c52ed8e57a0 | 1,911 | cpp | C++ | qws/src/gui/QPixmapCache.cpp | keera-studios/hsQt | 8aa71a585cbec40005354d0ee43bce9794a55a9a | [
"BSD-2-Clause"
] | 42 | 2015-02-16T19:29:16.000Z | 2021-07-25T11:09:03.000Z | qws/src/gui/QPixmapCache.cpp | keera-studios/hsQt | 8aa71a585cbec40005354d0ee43bce9794a55a9a | [
"BSD-2-Clause"
] | 1 | 2017-11-23T12:49:25.000Z | 2017-11-23T12:49:25.000Z | qws/src/gui/QPixmapCache.cpp | keera-studios/hsQt | 8aa71a585cbec40005354d0ee43bce9794a55a9a | [
"BSD-2-Clause"
] | 5 | 2015-10-15T21:25:30.000Z | 2017-11-22T13:18:24.000Z | /////////////////////////////////////////////////////////////////////////////
//
// File : QPixmapCache.cpp
// Copyright : (c) David Harley 2010
// Project : qtHaskell
// Version : 1.1.4
// Modified : 2010-09-02 17:02:05
//
// Warning : this file is machine generated - do not modify.
//
/////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <wchar.h>
#include <qtc_wrp_core.h>
#include <qtc_wrp_gui.h>
#include <qtc_subclass.h>
#ifndef dhclassheader
#define dhclassheader
#include <qpointer.h>
#include <dynamicqhandler.h>
#include <DhOther_gui.h>
#include <DhAutohead_gui.h>
#endif
extern "C"
{
QTCEXPORT(void*,qtc_QPixmapCache)() {
QPixmapCache*tr = new QPixmapCache();
return (void*) tr;
}
QTCEXPORT(void*,qtc_QPixmapCache1)(void* x1) {
QPixmapCache*tr = new QPixmapCache((const QPixmapCache&)(*(QPixmapCache*)x1));
return (void*) tr;
}
QTCEXPORT(int,qtc_QPixmapCache_cacheLimit)() {
return (int) QPixmapCache::cacheLimit();
}
QTCEXPORT(void,qtc_QPixmapCache_clear)() {
return (void) QPixmapCache::clear();
}
QTCEXPORT(void*,qtc_QPixmapCache_find)(wchar_t* x1) {
return (void*) QPixmapCache::find(from_method(x1));
}
QTCEXPORT(int,qtc_QPixmapCache_insert)(wchar_t* x1, void* x2) {
return (int) QPixmapCache::insert(from_method(x1), (const QPixmap&)(*(QPixmap*)x2));
}
QTCEXPORT(void,qtc_QPixmapCache_remove)(wchar_t* x1) {
return (void) QPixmapCache::remove(from_method(x1));
}
QTCEXPORT(void,qtc_QPixmapCache_setCacheLimit)(int x1) {
return (void) QPixmapCache::setCacheLimit((int)x1);
}
QTCEXPORT(void,qtc_QPixmapCache_finalizer)(void* x0) {
delete ((QPixmapCache*)x0);
}
QTCEXPORT(void*,qtc_QPixmapCache_getFinalizer)() {
return (void*)(&qtc_QPixmapCache_finalizer);
}
QTCEXPORT(void,qtc_QPixmapCache_delete)(void* x0) {
delete((QPixmapCache*)x0);
}
}
| 25.144737 | 86 | 0.645212 | keera-studios |
860590fb58bcb44d94930e8d51a71bfddacaa40f | 9,465 | cpp | C++ | src/core/map/cell_entrance_editor_system.cpp | MrPepperoni/Reaping2-1 | 4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd | [
"MIT"
] | 3 | 2015-02-22T20:34:28.000Z | 2020-03-04T08:55:25.000Z | src/core/map/cell_entrance_editor_system.cpp | MrPepperoni/Reaping2-1 | 4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd | [
"MIT"
] | 22 | 2015-12-13T16:29:40.000Z | 2017-03-04T15:45:44.000Z | src/core/map/cell_entrance_editor_system.cpp | Reaping2/Reaping2 | 0d4c988c99413e50cc474f6206cf64176eeec95d | [
"MIT"
] | 14 | 2015-11-23T21:25:09.000Z | 2020-07-17T17:03:23.000Z | #include "platform/i_platform.h"
#include "cell_entrance_editor_system.h"
#include "ui/ui.h"
#include "editor_grid_system.h"
#include "editor_target_system.h"
#include "editor_brush_system.h"
#include "../../engine/engine.h"
#include "../../input/keyboard.h"
#include "editor_hud_state.h"
#include "input/mouse.h"
#include "group_selected_event.h"
#include "group_map_element.h"
#include "map_system.h"
#include "core/map/level_generator/i_room.h"
#include "level_generator/cell_entrance_property.h"
#include "level_generator/property_factory.h"
#include "room_cell_editor_system.h"
namespace map {
CellEntranceEditorSystem::CellEntranceEditorSystem()
: PropertyEditorBaseSystem( "editor/cell_entrance_hud", "cell_entrance" )
, mScene( Scene::Get() )
, mEditorPropModel( "cell_entrance", &RootModel::Get() )
, mNewPropModel( VoidFunc( this, &CellEntranceEditorSystem::OnNewProp ), "new_prop", &mEditorPropModel )
, mPropNamesModel( (ModelValue::get_string_vec_t) RefTo( mPropNames ), "props", &mEditorPropModel )
, mPropSelectedModel( StringFunc( this, &CellEntranceEditorSystem::OnPropSelected ), "prop_selected", &mEditorPropModel )
, mTargetNameModel( (ModelValue::get_string_t) RefTo( mTargetName ), "target", &mEditorPropModel )
, mChangeTargetModel( VoidFunc( this, &CellEntranceEditorSystem::OnChangeTarget ), "change_target", &mEditorPropModel )
, mBlockedTargetNameModel( (ModelValue::get_string_t) RefTo( mBlockedTargetName ), "blocked_target", &mEditorPropModel )
, mChangeBlockedTargetModel( VoidFunc( this, &CellEntranceEditorSystem::OnChangeBlockedTarget ), "change_blocked_target", &mEditorPropModel )
{
}
void CellEntranceEditorSystem::Init()
{
PropertyEditorBaseSystem::Init();
mOnEditorModeChanged = EventServer<map::EditorModeChangedEvent>::Get().Subscribe( boost::bind( &CellEntranceEditorSystem::OnEditorModeChanged, this, _1 ) );
mOnEditorBack = EventServer<map::EditorBackEvent>::Get().Subscribe( boost::bind( &CellEntranceEditorSystem::OnEditorBack, this, _1 ) );
mOnGroupSelected = EventServer<map::GroupSelectedEvent>::Get().Subscribe( boost::bind( &CellEntranceEditorSystem::OnGroupSelected, this, _1 ) );
mMouseMoveId = EventServer<WorldMouseMoveEvent>::Get().Subscribe( boost::bind( &CellEntranceEditorSystem::OnMouseMoveEvent, this, _1 ) );
}
void CellEntranceEditorSystem::Update(double DeltaTime)
{
if (!mEnabled)
{
return;
}
static Opt<engine::KeyboardSystem> keyboard = ::engine::Engine::Get().GetSystem<engine::KeyboardSystem>();
static Opt<engine::MouseSystem> mouse = ::engine::Engine::Get().GetSystem<MouseSystem>();
if (keyboard->GetKey( GLFW_KEY_SPACE ).State == KeyState::Typed)
{
if (mEditorMode == PropSelect)
{
}
else
{
mEditorMode = PropSelect;
EditorHudState::Get().SetHudShown( false );
Ui::Get().Load( mHUD );
}
}
if (mEditorMode == PropSelect
&& engine::Engine::Get().GetSystem<MouseSystem>()->IsButtonPressed( MouseSystem::Button_Left ))
{
mPropUID = GetPropUIDFromScene( mMousePos );
if (mPropUID == -1)
{
mPropUID = AddNewProperty();
}
LoadProp();
mEditorMode = Edit;
EditorHudState::Get().SetHudShown( true );
Ui::Get().Load( "editor/cell_entrance_edit" );
}
}
int32_t CellEntranceEditorSystem::AddNewProperty()
{
static auto& propertyFactory = PropertyFactory::Get();
static int32_t propertyId = AutoId( "cell_entrance" );
auto prop = propertyFactory( propertyId );
int32_t r = prop->GetUID();
mTargetName.clear();
mBlockedTargetName.clear();
Opt<CellEntranceProperty> cellEntranceProp = static_cast<CellEntranceProperty*>(prop.get());
static auto roomCellEditorSystem = RoomCellEditorSystem::Get();
auto cell = roomCellEditorSystem->GetCellFromScene( mMousePos );
auto entrance = roomCellEditorSystem->GetEntranceType( mMousePos );
cellEntranceProp->SetX( cell->mDescCoord.x );
cellEntranceProp->SetY( cell->mDescCoord.y );
cellEntranceProp->SetEntranceType( entrance );
mRoomDesc->GetRoom()->AddProperty( prop );
return r;
}
int32_t CellEntranceEditorSystem::GetPropUIDFromScene( glm::vec2 mousePos )
{
static auto roomCellEditorSystem = RoomCellEditorSystem::Get();
auto cell = roomCellEditorSystem->GetCellFromScene( mousePos );
auto entrance = roomCellEditorSystem->GetEntranceType( mousePos );
if (cell.IsValid())
{
for (auto&& prop : mRoomDesc->GetRoom()->GetProperties())
{
if (prop.GetType() == CellEntranceProperty::GetType_static())
{
auto& cellEntranceProp = static_cast<CellEntranceProperty&>(prop);
if (cellEntranceProp.GetX() == cell->mDescCoord.x
&&cellEntranceProp.GetY() == cell->mDescCoord.y
&&cellEntranceProp.GetEntranceType() == entrance)
{
return prop.GetUID();
}
}
}
}
return -1;
}
void CellEntranceEditorSystem::OnEditorModeChanged( map::EditorModeChangedEvent const& Evt )
{
if (Evt.mMode == mMode)
{
::engine::Engine::Get().SetEnabled<CellEntranceEditorSystem>( true );
Ui::Get().Load( mHUD );
RoomCellEditorSystem::Get()->AddCells();
EditorHudState::Get().SetHudShown( false );
mEditorMode = PropSelect;
}
else
{
if (Evt.mPrevMode == mMode)
{
if (!RoomCellEditorSystem::Get()->IsCellsVisible())
{
RoomCellEditorSystem::Get()->RemoveCells();
}
}
::engine::Engine::Get().SetEnabled<CellEntranceEditorSystem>( false );
}
}
void CellEntranceEditorSystem::OnEditorBack( map::EditorBackEvent const& Evt )
{
if (mEnabled)
{
EditorSelectSystem::SetActorColors( mGroupPreSelectedActors, nullptr );
mGroupPreSelectedActors.clear();
mGroupPreSelectName.clear();
HandleEditorBack( Evt );
}
}
void CellEntranceEditorSystem::EnableSubsystems( bool enable )
{
}
Opt<CellEntranceEditorSystem> CellEntranceEditorSystem::Get()
{
return engine::Engine::Get().GetSystem<CellEntranceEditorSystem>();
}
void CellEntranceEditorSystem::OnNewProp()
{
}
void CellEntranceEditorSystem::OnPropSelected( std::string groupName )
{
}
void CellEntranceEditorSystem::OnChangeTarget()
{
mEditorMode = EntranceTarget;
Ui::Get().Load( "editor/all_groups" );
}
void CellEntranceEditorSystem::OnChangeBlockedTarget()
{
mEditorMode = BlockedTarget;
Ui::Get().Load( "editor/all_groups" );
}
void CellEntranceEditorSystem::OnGroupSelected( map::GroupSelectedEvent const& Evt )
{
if (!mEnabled)
{
return;
}
if (mGroupPreSelectName == Evt.mGroupName)
{
EditorSelectSystem::SetActorColors( mGroupPreSelectedActors, nullptr );
mGroupPreSelectedActors.clear();
Opt<CellEntranceProperty> prop = mRoomDesc->GetRoom()->GetProperty( mPropUID );
if (prop.IsValid())
{
CellEntranceProperty::Targets_t targets = mEditorMode == EntranceTarget ? prop->GetEntranceTargets() : prop->GetBlockedTargets();;
int32_t groupId = AutoId( Evt.mGroupName );
if (targets.empty())
{
targets.push_back( groupId );
}
else
{
targets.at( 0 ) = groupId;
}
if (mEditorMode == EntranceTarget)
{
prop->SetEntranceTargets( targets );
mTargetName = Evt.mGroupName;
}
else
{
prop->SetBlockedTargets( targets );
mBlockedTargetName = Evt.mGroupName;
}
}
EditorSelectSystem::SetActorColors( mGroupPreSelectedActors, nullptr );
mGroupPreSelectedActors.clear();
mGroupPreSelectName.clear();
mEditorMode = Edit;
Ui::Get().Load( "editor/cell_entrance_edit" );
}
else
{
mGroupPreSelectName = Evt.mGroupName;
EditorSelectSystem::SetActorColors( mGroupPreSelectedActors, nullptr );
mGroupPreSelectedActors.clear();
EditorSelectSystem::FillActorColors( AutoId( Evt.mGroupName ), mGroupPreSelectedActors );
EditorSelectSystem::SetActorColors( mGroupPreSelectedActors, &EditorSelectSystem::PreSelectColor );
}
}
void CellEntranceEditorSystem::OnMouseMoveEvent( const WorldMouseMoveEvent& Event )
{
mMousePos = Event.Pos;
}
void CellEntranceEditorSystem::LoadProp()
{
static auto& idStorage = IdStorage::Get();
Opt<CellEntranceProperty> prop = mRoomDesc->GetRoom()->GetProperty( mPropUID );
if (prop.IsValid())
{
auto const& targets = prop->GetEntranceTargets();
if (!targets.empty()) // TODO: handle more then one target. Just a reminder the editor is a helper to edit json files.
{
idStorage.GetName( *targets.begin(), mTargetName );
}
auto const& blockedTargets = prop->GetBlockedTargets();
if (!blockedTargets.empty()) // TODO: handle more then one target. Just a reminder the editor is a helper to edit json files.
{
idStorage.GetName( *blockedTargets.begin(), mBlockedTargetName );
}
}
}
} // namespace map
| 35.317164 | 160 | 0.660328 | MrPepperoni |
860c6477ba26d7ec28f0cc787718563d9dd48b43 | 2,122 | cpp | C++ | rs/test/append_test.cpp | dymk/rs | b75ab0df5f235ac12ec4da825e6bd6e1fa9e7493 | [
"Apache-2.0"
] | 19 | 2017-05-15T08:20:00.000Z | 2021-12-03T05:58:32.000Z | rs/test/append_test.cpp | dymk/rs | b75ab0df5f235ac12ec4da825e6bd6e1fa9e7493 | [
"Apache-2.0"
] | null | null | null | rs/test/append_test.cpp | dymk/rs | b75ab0df5f235ac12ec4da825e6bd6e1fa9e7493 | [
"Apache-2.0"
] | 3 | 2018-01-16T18:07:30.000Z | 2021-06-30T07:33:44.000Z | // Copyright 2017 Per Grön. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <catch.hpp>
#include <rs/append.h>
#include <rs/empty.h>
#include <rs/just.h>
#include "test_util.h"
namespace shk {
TEST_CASE("Append") {
auto append_nothing = Append();
auto append_one = Append(Just(1));
auto append_two = Append(Just(1), Just(2));
auto append_three = Append(Just(1), Just(2), Just(3));
SECTION("no arguments and no input") {
CHECK(GetAll<int>(append_nothing(Empty())) == std::vector<int>({}));
}
SECTION("no arguments and some input") {
CHECK(
GetAll<int>(append_nothing(Just(1, 2))) ==
std::vector<int>({ 1, 2 }));
}
SECTION("single argument and no input") {
CHECK(GetAll<int>(append_one(Empty())) == std::vector<int>({ 1 }));
}
SECTION("single argument and some input") {
CHECK(
GetAll<int>(append_one(Just(42))) ==
std::vector<int>({ 42, 1 }));
}
SECTION("two arguments and no input") {
CHECK(GetAll<int>(append_two(Empty())) == std::vector<int>({ 1, 2 }));
}
SECTION("two arguments and some input") {
CHECK(
GetAll<int>(append_two(Just(42))) ==
std::vector<int>({ 42, 1, 2 }));
}
SECTION("three arguments and no input") {
CHECK(GetAll<int>(append_three(Empty())) == std::vector<int>({ 1, 2, 3 }));
}
SECTION("three arguments and some input") {
CHECK(
GetAll<int>(append_three(Just(42))) ==
std::vector<int>({ 42, 1, 2, 3 }));
}
SECTION("don't leak the subscriber") {
CheckLeak(append_one(Just(42)));
}
}
} // namespace shk
| 27.558442 | 79 | 0.63525 | dymk |
860c6e0da67893e6547f1d7c259a7a1e6aab884f | 1,457 | cpp | C++ | DemoGame/Game/Source/Player.cpp | Omicrxn/Automated-Builds-CI-CD | 5a3729854dc2716407939e831079737e45f5690a | [
"MIT"
] | null | null | null | DemoGame/Game/Source/Player.cpp | Omicrxn/Automated-Builds-CI-CD | 5a3729854dc2716407939e831079737e45f5690a | [
"MIT"
] | null | null | null | DemoGame/Game/Source/Player.cpp | Omicrxn/Automated-Builds-CI-CD | 5a3729854dc2716407939e831079737e45f5690a | [
"MIT"
] | 1 | 2021-04-18T06:49:36.000Z | 2021-04-18T06:49:36.000Z | #include "Player.h"
Player::Player() : Entity(EntityType::PLAYER)
{
texture = NULL;
position = iPoint(12 * 16, 27 * 16);
jumpSpeed = 200.0f;
width = 16;
height = 32;
// Define Player animations
}
bool Player::Update(Input* input, float dt)
{
#define GRAVITY 400.0f
#define PLAYER_MOVE_SPEED 200.0f
#define PLAYER_JUMP_SPEED 350.0f
//if (input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT) position.y += (PLAYER_MOVE_SPEED * dt);
//if (input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT) position.y -= (PLAYER_MOVE_SPEED * dt);
if (input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT) position.x -= (PLAYER_MOVE_SPEED * dt);
if (input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT) position.x += (PLAYER_MOVE_SPEED * dt);
if (input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT) position.y -= (PLAYER_JUMP_SPEED * dt);
// Calculate gravity acceleration
jumpSpeed += GRAVITY * dt;
position.y += (jumpSpeed * dt);
return true;
}
bool Player::Draw(Render* render)
{
// TODO: Calculate the corresponding rectangle depending on the
// animation state and animation frame
//SDL_Rect rec = { 0 };
//render->DrawTexture(texture, position.x, position.y, rec);
render->DrawRectangle(GetBounds(), { 255, 0, 0, 255 });
return false;
}
void Player::SetTexture(SDL_Texture *tex)
{
texture = tex;
}
SDL_Rect Player::GetBounds()
{
return { position.x, position.y, width, height };
}
| 26.017857 | 97 | 0.663693 | Omicrxn |
860cb25ee368696965c03b5c9240947434af6634 | 5,241 | cc | C++ | engine/dgl/bitmapGif.cc | ClayHanson/B4v21-Public-Repo | c812aa7bf2ecb267e02969c85f0c9c2a29be0d28 | [
"MIT"
] | 1 | 2020-08-18T19:45:34.000Z | 2020-08-18T19:45:34.000Z | engine/dgl/bitmapGif.cc | ClayHanson/B4v21-Launcher-Public-Repo | c812aa7bf2ecb267e02969c85f0c9c2a29be0d28 | [
"MIT"
] | null | null | null | engine/dgl/bitmapGif.cc | ClayHanson/B4v21-Launcher-Public-Repo | c812aa7bf2ecb267e02969c85f0c9c2a29be0d28 | [
"MIT"
] | null | null | null | //-----------------------------------------------------------------------------
// Torque Game Engine
// Copyright (C) GarageGames.com, Inc.
//-----------------------------------------------------------------------------
#include "console/consoleLogger.h"
#include "core/stream.h"
#include "core/fileStream.h"
#include "core/memstream.h"
#include "dgl/gPalette.h"
#include "dgl/gBitmap.h"
#include "gif_lib.h"
//-------------------------------------- Replacement I/O for standard LIBjpeg
// functions. we don't wanna use
// FILE*'s...
static int gifReadDataFn(GifFileType * gifinfo, GifByteType * data, int length)
{
Stream* stream = (Stream*)gifinfo->UserData;
AssertFatal(stream != NULL, "gifReadDataFn::No stream.");
int pos = stream->getPosition();
if (stream->read(length, data))
return length;
if (stream->getStatus() == Stream::EOS)
return (stream->getPosition() - pos);
else
return 0;
}
//--------------------------------------
static int gifWriteDataFn(GifFileType* gifinfo, GifByteType* data, int length)
{
Stream* stream = (Stream*)gifinfo->UserData;
AssertFatal(stream != NULL, "gifWriteDataFn::No stream.");
if (stream->write(length, data))
return length;
else
return 0;
}
//--------------------------------------
bool GBitmap::readGIF(Stream &stream)
{
GifFileType *gifinfo = DGifOpen( (void*)&stream, gifReadDataFn);
if (!gifinfo)
return false;
GifRecordType recordType;
do
{
if (DGifGetRecordType(gifinfo, &recordType) == GIF_ERROR)
break;
if (recordType == IMAGE_DESC_RECORD_TYPE)
{
if (DGifGetImageDesc(gifinfo) == GIF_ERROR)
break;
BitmapFormat format = (gifinfo->SBackGroundColor == 0 ) ? RGB : RGBA;
allocateBitmap(gifinfo->SWidth, gifinfo->SHeight, false, format);
U32 gwidth = gifinfo->Image.Width ? gifinfo->Image.Width : width;
U32 gheight= gifinfo->Image.Height ? gifinfo->Image.Height : height;
U32 gifSize = gwidth * gheight;
U8 *data = new U8[gifSize];
if (DGifGetLine(gifinfo, data, gifSize) != GIF_ERROR)
{
// use the global or local color table ?
GifColorType *color = gifinfo->SColorMap->Colors;
if (gifinfo->Image.ColorMap)
color = gifinfo->Image.ColorMap->Colors;
if (color)
{
U8 *dst = getAddress(gifinfo->Image.Left, gifinfo->Image.Top);
U8 *src = data;
U32 right = gifinfo->Image.Left + gwidth;
U32 bottom = gifinfo->Image.Top + gheight;
U32 next = (width - gwidth) * bytesPerPixel;
if (format == RGBA)
{
for (U32 y=gifinfo->Image.Top; y<bottom; y++)
{
for (U32 x=gifinfo->Image.Left; x<right; x++, src++)
{
if (*src == gifinfo->SBackGroundColor)
{
// this is a transparent pixel
dst[0] = 0; // red
dst[1] = 0; // green
dst[2] = 0; // blue
dst[3] = 0; // alpha
}
else
{
dst[0] = color[*src].Red;
dst[1] = color[*src].Green;
dst[2] = color[*src].Blue;
dst[3] = 0; // alpha
}
dst += bytesPerPixel;
}
dst += next;
}
delete[] data;
DGifCloseFile(gifinfo);
return true;
}
else
{
for (U32 y=gifinfo->Image.Top; y<bottom; y++)
{
for (U32 x=gifinfo->Image.Left; x<right; x++, src++)
{
dst[0] = color[*src].Red;
dst[1] = color[*src].Green;
dst[2] = color[*src].Blue;
dst += bytesPerPixel;
}
dst += next;
}
}
delete [] data;
DGifCloseFile(gifinfo);
return true;
}
}
// failure
delete [] data;
break;
}
else if (recordType == EXTENSION_RECORD_TYPE)
{
GifByteType *extension;
S32 extCode;
// Skip any extension blocks in file
if (DGifGetExtension(gifinfo, &extCode, &extension) != GIF_ERROR)
{
while (extension != NULL)
{
if (DGifGetExtensionNext(gifinfo, &extension) == GIF_ERROR)
return false;
}
}
else
return false;
}
break;
}while (recordType != TERMINATE_RECORD_TYPE);
DGifCloseFile(gifinfo);
return false;
}
//--------------------------------------------------------------------------
bool GBitmap::writeGIF(Stream&) const
{
return false;
}
| 29.948571 | 79 | 0.444572 | ClayHanson |
860df8d3e1cd7b54ff41ffdf4a59967ed41af9e7 | 1,330 | cpp | C++ | main/dx9/TextureCoordsCalc.cpp | dvarubla/directgraph | feb29419eba2fc931a1bdf593545fabdf552ce8a | [
"MIT"
] | null | null | null | main/dx9/TextureCoordsCalc.cpp | dvarubla/directgraph | feb29419eba2fc931a1bdf593545fabdf552ce8a | [
"MIT"
] | null | null | null | main/dx9/TextureCoordsCalc.cpp | dvarubla/directgraph | feb29419eba2fc931a1bdf593545fabdf552ce8a | [
"MIT"
] | null | null | null | #include <main/patterns.h>
#include "TextureCoordsCalc.h"
namespace directgraph{
namespace dx9{
TextureCoords
TextureCoordsCalc::calcLineCoords(float prevEnd, const FCoords &start, const FCoords &end, bool needAddOffset) {
FCoords texStart = {
prevEnd, 0
};
if(needAddOffset){
texStart = addOffset(texStart);
}
FCoords texEnd = {
1.0f * std::abs(end.x - start.x) / LPATTERN_SIZE + texStart.x, 0.0f
};
TextureCoords res = {texStart, texEnd};
return res;
}
TextureCoords TextureCoordsCalc::calcBarCoords(const DCoords &start, const DCoords &end) {
TextureCoords res = {
genFCoords(0, 0), genFCoords(1.0f * (end.x - start.x) / FPATTERN_SIZE, 1.0f * (end.y - start.y) / FPATTERN_SIZE)
};
return res;
}
TextureCoords TextureCoordsCalc::calcLineCoords(const FCoords &start, const FCoords &end, bool needAddOffset) {
return calcLineCoords(0, start, end, needAddOffset);
}
FCoords TextureCoordsCalc::addOffset(const FCoords &coords) {
FCoords res = coords;
res.x += CORR_OFFSET;
return res;
}
}
} | 33.25 | 132 | 0.557143 | dvarubla |
8612820c787dc914aba3094f7eaba14916c9a2ee | 7,189 | cpp | C++ | src/parsegen_xml.cpp | Aiteta/capp | a43c40788e53e28403dd62e576b17e933aac912d | [
"MIT"
] | 3 | 2021-09-01T15:12:23.000Z | 2022-03-28T09:01:05.000Z | src/parsegen_xml.cpp | Aiteta/capp | a43c40788e53e28403dd62e576b17e933aac912d | [
"MIT"
] | null | null | null | src/parsegen_xml.cpp | Aiteta/capp | a43c40788e53e28403dd62e576b17e933aac912d | [
"MIT"
] | null | null | null | #include "parsegen_xml.hpp"
namespace parsegen {
namespace xml {
language build_language() {
language out;
auto& prods = out.productions;
prods.resize(NPRODS);
prods[PROD_DOC] = {"document", {"toplevels"}};
prods[PROD_TOPLEVEL] = {"toplevels", {}};
prods[PROD_TOPLEVELS] = {"toplevels", {"toplevel", "S?", "toplevels"}};
prods[PROD_TOPLEVEL_ELEMENT] = {"toplevel", {"element"}};
prods[PROD_TOPLEVEL_XMLDECL] = {"toplevel", {"XMLDecl"}};
prods[PROD_ELEMENT_EMPTY] = {"element", {"EmptyElemTag"}};
prods[PROD_ELEMENT] = {"element", {"STag", "content"}};
prods[PROD_XMLDECL] = {"XMLDecl", {"<", "?", "Name", "TagFill", "?", ">"}};
prods[PROD_STAG] = {"STag", {"<", "Name", "TagFill", ">"}};
prods[PROD_ETAG] = {"ETag", {"<", "/", "Name", "S?", ">"}};
prods[PROD_EMPTY_TAG] = {"EmptyElemTag", {"<", "Name", "TagFill", "/", ">"}};
prods[PROD_CONTENT] = {"content", {"CharData?", "ContentItem*", "ETag"}};
prods[PROD_NO_CONTENT_ITEMS] = {"ContentItem*", {}};
prods[PROD_CONTENT_ITEMS] = {
"ContentItem*", {"ContentItem*", "ContentItem", "CharData?"}};
prods[PROD_CONTENT_ELEMENT] = {"ContentItem", {"element"}};
prods[PROD_CONTENT_REF] = {"ContentItem", {"Reference"}};
prods[PROD_CONTENT_COMMENT] = {"ContentItem", {"Comment"}};
prods[PROD_NO_CHARDATA] = {"CharData?", {}};
prods[PROD_CHARDATA] = {"CharData?", {"CharData?", "DataChar"}};
prods[PROD_TAGFILL] = {"TagFill", {"Attributes", "S?"}};
prods[PROD_NO_ATTS] = {"Attributes", {}};
prods[PROD_ATTS] = {"Attributes", {"Attributes", "S", "Attribute"}};
prods[PROD_ATT] = {"Attribute", {"Name", "Eq", "AttValue"}};
prods[PROD_EQ] = {"Eq", {"S?", "=", "S?"}};
prods[PROD_ATTVALUE_D] = {"AttValue", {"\"", "DQuoteds", "\""}};
prods[PROD_ATTVALUE_S] = {"AttValue", {"'", "SQuoteds", "'"}};
prods[PROD_NO_DQUOTS] = {"DQuoteds", {}};
prods[PROD_DQUOTS] = {"DQuoteds", {"DQuoteds", "DQuoted"}};
prods[PROD_DQUOT_CHAR] = {"DQuoted", {"DQuotedChar"}};
prods[PROD_DQUOT_REF] = {"DQuoted", {"Reference"}};
prods[PROD_NO_SQUOTS] = {"SQuoteds", {}};
prods[PROD_SQUOTS] = {"SQuoteds", {"SQuoteds", "SQuoted"}};
prods[PROD_SQUOT_CHAR] = {"SQuoted", {"SQuotedChar"}};
prods[PROD_SQUOT_REF] = {"SQuoted", {"Reference"}};
prods[PROD_NAME] = {"Name", {"NameFirstChar", "NameChars"}};
prods[PROD_NAME_FIRST_LETTER] = {"NameFirstChar", {"Letter"}};
prods[PROD_NAME_FIRST_UNDER] = {"NameFirstChar", {"_"}};
prods[PROD_NAME_FIRST_COLON] = {"NameFirstChar", {":"}};
prods[PROD_NO_NAME_CHARS] = {"NameChars", {}};
prods[PROD_NAME_CHARS] = {"NameChars", {"NameChars", "NameChar"}};
prods[PROD_NAME_LETTER] = {"NameChar", {"Letter"}};
prods[PROD_NAME_DIGIT] = {"NameChar", {"Digit"}};
prods[PROD_NAME_DOT] = {"NameChar", {"."}};
prods[PROD_NAME_DASH] = {"NameChar", {"-"}};
prods[PROD_NAME_UNDER] = {"NameChar", {"_"}};
prods[PROD_NAME_COLON] = {"NameChar", {":"}};
prods[PROD_NO_MISCS] = {"Miscs", {}};
prods[PROD_MISCS] = {"Miscs", {"Miscs", "Misc"}};
prods[PROD_MISC_COMMENT] = {"Misc", {"Comment"}};
prods[PROD_MISC_SPACE] = {"Misc", {"S"}};
prods[PROD_COMMENT] = {
"Comment", {"<", "!", "-", "-", "Commenteds", "-", "-", ">"}};
prods[PROD_NO_COMMENTED] = {"Commenteds", {}};
prods[PROD_COMMENTED] = {"Commenteds", {"Commenteds", "Commented"}};
prods[PROD_COMMENT_CHAR] = {"Commented", {"CommentChar"}};
prods[PROD_COMMENT_DASH] = {"Commented", {"-", "CommentChar"}};
prods[PROD_ENT_REF] = {"Reference", {"&", "Name", ";"}};
prods[PROD_CHAR_REF] = {"Reference", {"&", "#", "Digits", ";"}};
prods[PROD_ONE_DIGIT] = {"Digits", {"Digit"}};
prods[PROD_DIGITS] = {"Digits", {"Digits", "Digit"}};
prods[PROD_NO_SPACES] = {"S?", {}};
prods[PROD_YES_SPACES] = {"S?", {"S"}};
prods[PROD_ONE_SPACE] = {"S", {"Space"}};
prods[PROD_SPACES] = {"S", {"S", "Space"}};
prods[PROD_DQUOTED_COMMON] = {"DQuotedChar", {"CommonChar"}};
prods[PROD_DQUOTED_SQUOT] = {"DQuotedChar", {"'"}};
prods[PROD_DQUOTED_RSQUARE] = {"DQuotedChar", {"]"}};
prods[PROD_DQUOTED_DASH] = {"DQuotedChar", {"-"}};
prods[PROD_SQUOTED_CHAR] = {"SQuotedChar", {"CommonChar"}};
prods[PROD_SQUOTED_DQUOT] = {"SQuotedChar", {"\""}};
prods[PROD_SQUOTED_RSQUARE] = {"SQuotedChar", {"]"}};
prods[PROD_SQUOTED_DASH] = {"SQuotedChar", {"-"}};
prods[PROD_DATA_COMMON] = {"DataChar", {"CommonChar"}};
prods[PROD_DATA_SQUOT] = {"DataChar", {"'"}};
prods[PROD_DATA_DQUOT] = {"DataChar", {"\""}};
prods[PROD_DATA_DASH] = {"DataChar", {"-"}};
prods[PROD_COMMENT_COMMON] = {"CommentChar", {"CommonChar"}};
prods[PROD_COMMENT_LANGLE] = {"CommentChar", {"<"}};
prods[PROD_COMMENT_AMP] = {"CommentChar", {"&"}};
prods[PROD_COMMENT_SQUOT] = {"CommentChar", {"'"}};
prods[PROD_COMMENT_DQUOT] = {"CommentChar", {"\""}};
prods[PROD_COMMENT_RSQUARE] = {"CommentChar", {"]"}};
prods[PROD_COMMON_SPACE] = {"CommonChar", {"Space"}};
prods[PROD_COMMON_LETTER] = {"CommonChar", {"Letter"}};
prods[PROD_COMMON_DIGIT] = {"CommonChar", {"Digit"}};
prods[PROD_COMMON_EXCL] = {"CommonChar", {"!"}};
prods[PROD_COMMON_POUND] = {"CommonChar", {"#"}};
prods[PROD_COMMON_DOT] = {"CommonChar", {"."}};
prods[PROD_COMMON_SLASH] = {"CommonChar", {"/"}};
prods[PROD_COMMON_COLON] = {"CommonChar", {":"}};
prods[PROD_COMMON_SEMICOLON] = {"CommonChar", {";"}};
prods[PROD_COMMON_RANGLE] = {"CommonChar", {">"}};
prods[PROD_COMMON_QUESTION] = {"CommonChar", {"?"}};
prods[PROD_COMMON_EQUAL] = {"CommonChar", {"="}};
prods[PROD_COMMON_LSQUARE] = {"CommonChar", {"["}};
prods[PROD_COMMON_UNDER] = {"CommonChar", {"_"}};
prods[PROD_COMMON_OTHER] = {"CommonChar", {"OtherChar"}};
auto& toks = out.tokens;
toks.resize(NTOKS);
toks[TOK_SPACE] = {"Space", "[ \t\r\n]"};
toks[TOK_LETTER] = {"Letter", "[a-zA-Z]"};
toks[TOK_DIGIT] = {"Digit", "[0-9]"};
toks[TOK_EXCL] = {"!", "!"};
toks[TOK_DQUOTE] = {"\"", "\""};
toks[TOK_SQUOTE] = {"'", "'"};
toks[TOK_POUND] = {"#", "#"};
toks[TOK_AMP] = {"&", "&"};
toks[TOK_DASH] = {"-", "\\-"};
toks[TOK_DOT] = {".", "\\."};
toks[TOK_SLASH] = {"/", "/"};
toks[TOK_COLON] = {":", ":"};
toks[TOK_SEMICOLON] = {";", ";"};
toks[TOK_LANGLE] = {"<", "<"};
toks[TOK_RANGLE] = {">", ">"};
toks[TOK_QUESTION] = {"?", "\\?"};
toks[TOK_EQUAL] = {"=", "="};
toks[TOK_LSQUARE] = {"[", "\\["};
toks[TOK_RSQUARE] = {"]", "\\]"};
toks[TOK_UNDER] = {"_", "_"};
toks[TOK_OTHER] = {"OtherChar", "[$%\\(\\)\\*\\+,@\\\\\\^`{}\\|~]"};
return out;
}
language_ptr ask_language() {
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wexit-time-destructors"
#endif
static language_ptr ptr;
#ifdef __clang__
#pragma clang diagnostic pop
#endif
if (ptr.use_count() == 0) {
ptr.reset(new language(build_language()));
}
return ptr;
}
parser_tables_ptr ask_parser_tables() {
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wexit-time-destructors"
#endif
static parser_tables_ptr ptr;
#ifdef __clang__
#pragma clang diagnostic pop
#endif
if (ptr.use_count() == 0) {
auto lang = ask_language();
ptr = build_parser_tables(*lang);
}
return ptr;
}
} // end namespace xml
} // end namespace parsegen
| 43.047904 | 79 | 0.606065 | Aiteta |
8617646bae42b021a02cb1ff0c2d1cd2df1a6c18 | 17,882 | cpp | C++ | src/core/lib/math/bigintfxd/mubintvecfxd.cpp | uishi/Modified_PALISADEv1.9.2 | d8bf4739144e53340481721b1df83dfff2f65cd8 | [
"BSD-2-Clause"
] | 1 | 2021-09-02T07:20:28.000Z | 2021-09-02T07:20:28.000Z | src/core/lib/math/bigintfxd/mubintvecfxd.cpp | uishi/Modified_PALISADEv1.9.2 | d8bf4739144e53340481721b1df83dfff2f65cd8 | [
"BSD-2-Clause"
] | null | null | null | src/core/lib/math/bigintfxd/mubintvecfxd.cpp | uishi/Modified_PALISADEv1.9.2 | d8bf4739144e53340481721b1df83dfff2f65cd8 | [
"BSD-2-Clause"
] | 3 | 2021-09-02T07:21:06.000Z | 2022-01-19T15:24:20.000Z | /*
* @file mubintvecfxd.cpp This file contains the vector manipulation functionality.
* @author TPOC: contact@palisade-crypto.org
*
* @copyright Copyright (c) 2019, New Jersey Institute of Technology (NJIT)
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/*
This code provides basic arithmetic functionality.
*/
#include "math/backend.h"
#include "utils/serializable.h"
#include "math/bigintfxd/mubintvecfxd.h"
#include "math/nbtheory.h"
#include "utils/debug.h"
namespace bigintfxd {
// CONSTRUCTORS
template<class IntegerType>
BigVectorImpl<IntegerType>::BigVectorImpl() {
this->m_length = 0;
this->m_modulus = 0;
m_data = NULL;
}
template<class IntegerType>
BigVectorImpl<IntegerType>::BigVectorImpl(usint length, const IntegerType &modulus) {
this->m_length = length;
this->m_modulus = modulus;
this->m_data = new IntegerType[m_length]();
}
template<class IntegerType>
BigVectorImpl<IntegerType>::BigVectorImpl(const BigVectorImpl &bigVector) {
m_length = bigVector.m_length;
m_modulus = bigVector.m_modulus;
m_data = new IntegerType[m_length];
for (usint i = 0; i < m_length; i++) {
m_data[i] = bigVector.m_data[i];
}
}
template<class IntegerType>
BigVectorImpl<IntegerType>::BigVectorImpl(BigVectorImpl &&bigVector) {
m_data = bigVector.m_data;
m_length = bigVector.m_length;
m_modulus = bigVector.m_modulus;
bigVector.m_data = NULL;
bigVector.m_length = 0;
bigVector.m_modulus = 0;
}
template<class IntegerType>
BigVectorImpl<IntegerType>::BigVectorImpl(usint length, const IntegerType &modulus,
std::initializer_list<std::string> rhs) {
this->m_length = length;
this->m_modulus = modulus;
this->m_data = new IntegerType[m_length]();
usint len = rhs.size();
for (usint i = 0; i < m_length; i++) { // this loops over each entry
if (i < len) {
m_data[i] = IntegerType(*(rhs.begin() + i)) % m_modulus;
} else {
m_data[i] = 0;
}
}
}
template<class IntegerType>
BigVectorImpl<IntegerType>::BigVectorImpl(usint length, const IntegerType &modulus,
std::initializer_list<uint64_t> rhs) {
this->m_length = length;
this->m_modulus = modulus;
this->m_data = new IntegerType[m_length]();
usint len = rhs.size();
for (usint i = 0; i < m_length; i++) { // this loops over each entry
if (i < len) {
m_data[i] = IntegerType(*(rhs.begin() + i)) % m_modulus;
} else {
m_data[i] = 0;
}
}
}
template<class IntegerType>
BigVectorImpl<IntegerType>::~BigVectorImpl() {
delete[] m_data;
}
// ASSIGNMENT OPERATORS
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::operator=(const BigVectorImpl &rhs) {
if (this != &rhs) {
if (this->m_length == rhs.m_length) {
for (size_t i = 0; i < m_length; i++) {
this->m_data[i] = rhs.m_data[i];
}
} else {
delete[] m_data;
m_length = rhs.m_length;
m_modulus = rhs.m_modulus;
m_data = new IntegerType[m_length];
for (size_t i = 0; i < m_length; i++) {
m_data[i] = rhs.m_data[i];
}
}
this->m_modulus = rhs.m_modulus;
}
return *this;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::operator=(BigVectorImpl &&rhs) {
if (this != &rhs) {
delete[] m_data;
m_data = rhs.m_data;
m_length = rhs.m_length;
m_modulus = rhs.m_modulus;
rhs.m_data = NULL;
}
return *this;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::operator=(
std::initializer_list<std::string> rhs) {
size_t len = rhs.size();
for (size_t i = 0; i < m_length; i++) {
if (i < len) {
if (m_modulus != 0) {
m_data[i] = IntegerType(*(rhs.begin() + i)) % m_modulus;
} else {
m_data[i] = IntegerType(*(rhs.begin() + i));
}
} else {
m_data[i] = 0;
}
}
return *this;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::operator=(std::initializer_list<uint64_t> rhs) {
size_t len = rhs.size();
for (size_t i = 0; i < m_length; i++) {
if (i < len) {
if (m_modulus != 0) {
m_data[i] = IntegerType(*(rhs.begin() + i)) % m_modulus;
} else {
m_data[i] = IntegerType(*(rhs.begin() + i));
}
} else {
m_data[i] = 0;
}
}
return *this;
}
// ACCESSORS
template<class IntegerType>
void BigVectorImpl<IntegerType>::SetModulus(const IntegerType &value) {
this->m_modulus = value;
}
/**Switches the integers in the vector to values corresponding to the new modulus
* Algorithm: Integer i, Old Modulus om, New Modulus nm, delta = abs(om-nm):
* Case 1: om < nm
* if i > i > om/2
* i' = i + delta
* Case 2: om > nm
* i > om/2
* i' = i-delta
*/
template<class IntegerType>
void BigVectorImpl<IntegerType>::SwitchModulus(const IntegerType &newModulus) {
IntegerType oldModulus(this->m_modulus);
IntegerType n;
IntegerType oldModulusByTwo(oldModulus >> 1);
IntegerType diff((oldModulus > newModulus) ? (oldModulus - newModulus) : (newModulus - oldModulus));
for (usint i = 0; i < this->m_length; i++) {
n = this->at(i);
if (oldModulus < newModulus) {
if (n > oldModulusByTwo) {
this->at(i) = n.ModAdd(diff, newModulus);
} else {
this->at(i) = n.Mod(newModulus);
}
} else {
if (n > oldModulusByTwo) {
this->at(i) = n.ModSub(diff, newModulus);
} else {
this->at(i) = n.Mod(newModulus);
}
}
}
this->SetModulus(newModulus);
}
// MODULAR ARITHMETIC OPERATIONS
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::Mod(const IntegerType &modulus) const {
BigVectorImpl ans(*this);
ans.ModEq(modulus);
return ans;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::ModEq(const IntegerType &modulus) {
if (modulus == 2) {
return this->ModByTwoEq();
} else {
IntegerType halfQ(this->GetModulus() >> 1);
for (usint i = 0; i < this->GetLength(); i++) {
if (this->m_data[i] > halfQ) {
this->m_data[i].ModSubEq(this->GetModulus(), modulus);
} else {
this->m_data[i].ModEq(modulus);
}
}
return *this;
}
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModAdd(const IntegerType &b) const {
BigVectorImpl ans(*this);
ans.ModAddEq(b);
return ans;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::ModAddEq(const IntegerType &b) {
IntegerType bb = b.Mod(this->m_modulus);
for (usint i = 0; i < this->m_length; i++) {
this->m_data[i].ModAddFastEq(bb, this->m_modulus);
}
return *this;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModAddAtIndex(usint i, const IntegerType &b) const {
BigVectorImpl ans(*this);
ans.ModAddAtIndexEq(i, b);
return ans;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::ModAddAtIndexEq(usint i, const IntegerType &b) {
if (i > this->GetLength() - 1) {
PALISADE_THROW(lbcrypto::math_error,
"mubintvecfxd::ModAddAtIndex. Index is out of range. i = " + std::to_string(i));
}
this->m_data[i].ModAddEq(b, this->m_modulus);
return *this;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModAdd(const BigVectorImpl &b) const {
BigVectorImpl ans(*this);
ans.ModAddEq(b);
return ans;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::ModAddEq(const BigVectorImpl &b) {
if ((this->m_length != b.m_length) || this->m_modulus != b.m_modulus) {
PALISADE_THROW(lbcrypto::math_error, "ModAddEq called on BigVectorImpl's with different parameters.");
}
for (usint i = 0; i < this->m_length; i++) {
this->m_data[i].ModAddFastEq(b.m_data[i], this->m_modulus);
}
return *this;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModSub(const IntegerType &b) const {
BigVectorImpl ans(*this);
ans.ModSubEq(b);
return ans;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::ModSubEq(const IntegerType &b) {
IntegerType bb = b.Mod(this->m_modulus);
for (usint i = 0; i < this->m_length; i++) {
this->m_data[i].ModSubFastEq(bb, this->m_modulus);
}
return *this;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModSub(const BigVectorImpl &b) const {
BigVectorImpl ans(*this);
ans.ModSubEq(b);
return ans;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::ModSubEq(const BigVectorImpl &b) {
if ((this->m_length != b.m_length) || this->m_modulus != b.m_modulus) {
PALISADE_THROW(lbcrypto::math_error, "ModSubEq called on BigVectorImpl's with different parameters.");
}
for (usint i = 0; i < this->m_length; i++) {
this->m_data[i].ModSubFastEq(b.m_data[i], this->m_modulus);
}
return *this;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModMul(const IntegerType &b) const {
BigVectorImpl ans(*this);
ans.ModMulEq(b);
return ans;
}
/*
Source: http://homes.esat.kuleuven.be/~fvercaut/papers/bar_mont.pdf
@article{knezevicspeeding,
title={Speeding Up Barrett and Montgomery Modular Multiplications},
author={Knezevic, Miroslav and Vercauteren, Frederik and Verbauwhede, Ingrid}
}
We use the Generalized Barrett modular reduction algorithm described in Algorithm 2 of the Source. The algorithm was originally
proposed in J.-F. Dhem. Modified version of the Barrett algorithm. Technical report, 1994 and described in more detail
in the PhD thesis of the author published at
http://users.belgacom.net/dhem/these/these_public.pdf (Section 2.2.4).
We take \alpha equal to n + 3. So in our case, \mu = 2^(n + \alpha) = 2^(2*n + 3).
Generally speaking, the value of \alpha should be \ge \gamma + 1, where \gamma + n is the number of digits in the dividend.
We use the upper bound of dividend assuming that none of the dividends will be larger than 2^(2*n + 3).
Potential improvements:
Our implementation makes the modulo operation essentially equivalent to two multiplications. If sparse moduli are selected, it can be replaced
with a single multiplication. The interleaved version of modular multiplication for this case is listed in Algorithm 6 of the source.
This algorithm would most like give the biggest improvement but it sets constraints on moduli.
*/
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::ModMulEq(const IntegerType &b) {
IntegerType bb = b.Mod(this->m_modulus);
IntegerType mu = this->m_modulus.ComputeMu(); //Precompute the Barrett mu parameter
for (usint i = 0; i < this->m_length; i++) {
this->m_data[i].ModMulEq(bb, this->m_modulus, mu);
}
return *this;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModMul(const BigVectorImpl &b) const {
BigVectorImpl ans(*this);
ans.ModMulEq(b);
return ans;
}
/*
Source: http://homes.esat.kuleuven.be/~fvercaut/papers/bar_mont.pdf
@article{knezevicspeeding,
title={Speeding Up Barrett and Montgomery Modular Multiplications},
author={Knezevic, Miroslav and Vercauteren, Frederik and Verbauwhede, Ingrid}
}
We use the Generalized Barrett modular reduction algorithm described in Algorithm 2 of the Source. The algorithm was originally
proposed in J.-F. Dhem. Modified version of the Barrett algorithm. Technical report, 1994 and described in more detail
in the PhD thesis of the author published at
http://users.belgacom.net/dhem/these/these_public.pdf (Section 2.2.4).
We take \alpha equal to n + 3. So in our case, \mu = 2^(n + \alpha) = 2^(2*n + 3).
Generally speaking, the value of \alpha should be \ge \gamma + 1, where \gamma + n is the number of digits in the dividend.
We use the upper bound of dividend assuming that none of the dividends will be larger than 2^(2*n + 3).
Potential improvements:
Our implementation makes the modulo operation essentially equivalent to two multiplications. If sparse moduli are selected, it can be replaced
with a single multiplication. The interleaved version of modular multiplication for this case is listed in Algorithm 6 of the source.
This algorithm would most like give the biggest improvement but it sets constraints on moduli.
*/
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::ModMulEq(const BigVectorImpl &b) {
if ((this->m_length != b.m_length) || this->m_modulus != b.m_modulus) {
PALISADE_THROW(lbcrypto::math_error, "ModMulEq called on BigVectorImpl's with different parameters.");
}
IntegerType mu = this->m_modulus.ComputeMu();; //Precompute the Barrett mu parameter
for (usint i = 0; i < this->m_length; i++) {
this->m_data[i].ModMulEq(b.m_data[i], this->m_modulus, mu);
}
return *this;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModExp(const IntegerType &b) const {
BigVectorImpl ans(*this);
ans.ModExpEq(b);
return ans;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::ModExpEq(const IntegerType &b) {
for (usint i = 0; i < this->m_length; i++) {
this->m_data[i].ModExpEq(b, this->m_modulus);
}
return *this;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModInverse() const {
BigVectorImpl ans(*this);
ans.ModInverseEq();
return ans;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::ModInverseEq() {
for (usint i = 0; i < this->m_length; i++) {
this->m_data[i].ModInverseEq(this->m_modulus);
}
return *this;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::ModByTwo() const {
BigVectorImpl ans(*this);
ans.ModByTwoEq();
return ans;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::ModByTwoEq() {
IntegerType halfQ(this->GetModulus() >> 1);
for (usint i = 0; i < this->GetLength(); i++) {
if (this->m_data[i] > halfQ) {
if (this->m_data[i].Mod(2) == 1) {
this->m_data[i] = IntegerType(0);
} else {
this->m_data[i] = 1;
}
} else {
if (this->m_data[i].Mod(2) == 1) {
this->m_data[i] = 1;
} else {
this->m_data[i] = IntegerType(0);
}
}
}
return *this;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::MultWithOutMod(const BigVectorImpl &b) const {
BigVectorImpl ans(*this);
ans.MultWithOutModEq(b);
return ans;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::MultWithOutModEq(const BigVectorImpl &b) {
if ((this->m_length != b.m_length) || this->m_modulus != b.m_modulus) {
PALISADE_THROW(lbcrypto::type_error,
"MultWithOutMod called on BigVectorImpl's with different parameters.");
}
for (usint i = 0; i < this->m_length; i++) {
this->m_data[i].MulEq(b.m_data[i]);
}
return *this;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::MultiplyAndRound(const IntegerType &p,
const IntegerType &q) const {
BigVectorImpl ans(*this);
ans.MultiplyAndRoundEq(p, q);
return ans;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::MultiplyAndRoundEq(const IntegerType &p,
const IntegerType &q) {
IntegerType halfQ(this->m_modulus >> 1);
IntegerType temp;
for (usint i = 0; i < this->m_length; i++) {
if (this->m_data[i] > halfQ) {
temp = this->m_modulus - this->m_data[i];
this->m_data[i] = this->m_modulus - temp.MultiplyAndRound(p, q);
} else {
this->m_data[i].MultiplyAndRoundEq(p, q);
this->m_data[i].ModEq(this->m_modulus);
}
}
return *this;
}
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::DivideAndRound(const IntegerType &q) const {
BigVectorImpl ans(*this);
ans.DivideAndRoundEq(q);
return ans;
}
template<class IntegerType>
const BigVectorImpl<IntegerType>& BigVectorImpl<IntegerType>::DivideAndRoundEq(const IntegerType &q) {
IntegerType halfQ(this->m_modulus >> 1);
IntegerType temp;
for (usint i = 0; i < this->m_length; i++) {
if (this->m_data[i] > halfQ) {
temp = this->m_modulus - this->m_data[i];
this->m_data[i] = this->m_modulus - temp.DivideAndRound(q);
} else {
this->m_data[i].DivideAndRoundEq(q);
}
}
return *this;
}
// OTHER OPERATIONS
template<class IntegerType>
BigVectorImpl<IntegerType> BigVectorImpl<IntegerType>::GetDigitAtIndexForBase(usint index, usint base) const {
BigVectorImpl ans(*this);
for (usint i = 0; i < this->m_length; i++) {
ans.m_data[i] = IntegerType(ans.m_data[i].GetDigitAtIndexForBase(index, base));
}
return ans;
}
template class BigVectorImpl<BigInteger<integral_dtype, BigIntegerBitLength>> ;
} // namespace lbcrypto ends
| 32.691042 | 143 | 0.72106 | uishi |
861df7df678520582dc80fa869d06e226e61770b | 925 | hpp | C++ | libs/core/include/fcppt/math/vector/length_square.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 13 | 2015-02-21T18:35:14.000Z | 2019-12-29T14:08:29.000Z | libs/core/include/fcppt/math/vector/length_square.hpp | cpreh/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 5 | 2016-08-27T07:35:47.000Z | 2019-04-21T10:55:34.000Z | libs/core/include/fcppt/math/vector/length_square.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 8 | 2015-01-10T09:22:37.000Z | 2019-12-01T08:31:12.000Z | // Copyright Carl Philipp Reh 2009 - 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_MATH_VECTOR_LENGTH_SQUARE_HPP_INCLUDED
#define FCPPT_MATH_VECTOR_LENGTH_SQUARE_HPP_INCLUDED
#include <fcppt/math/size_type.hpp>
#include <fcppt/math/vector/dot.hpp>
#include <fcppt/math/vector/object_impl.hpp>
namespace fcppt::math::vector
{
/**
\brief Calculate the square of the vector's length
\ingroup fcpptmathvector
\param _vector The vector to calculate the length for.
\note
If you just want the length, use fcppt::math::vector::length
\see
fcppt::math::vector::length
*/
template <typename T, fcppt::math::size_type N, typename S>
inline T length_square(fcppt::math::vector::object<T, N, S> const &_vector)
{
return fcppt::math::vector::dot(_vector, _vector);
}
}
#endif
| 25 | 75 | 0.745946 | freundlich |
8622e7357de4b2da523e7b4d44718f4fbc63b133 | 2,318 | cpp | C++ | src/util/sys/fdguard.cpp | rayslava/leechcraft | 4ecc8aa56dc6030d2593922ff41b00ff50902db8 | [
"BSL-1.0"
] | 1 | 2017-01-12T07:05:45.000Z | 2017-01-12T07:05:45.000Z | src/util/sys/fdguard.cpp | ForNeVeR/leechcraft | 384d041d23b1cdb7cc3c758612ac8d68d3d3d88c | [
"BSL-1.0"
] | null | null | null | src/util/sys/fdguard.cpp | ForNeVeR/leechcraft | 384d041d23b1cdb7cc3c758612ac8d68d3d3d88c | [
"BSL-1.0"
] | null | null | null | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
* Copyright (C) 2012 Maxim Ignatenko
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include "fdguard.h"
#include <fcntl.h>
#include <unistd.h>
namespace LeechCraft
{
namespace Util
{
FDGuard::FDGuard (const char *file, int mode)
: FD_ { open (file, mode) }
{
}
FDGuard::FDGuard (FDGuard&& other)
: FD_ { other.FD_ }
{
other.FD_ = -1;
}
FDGuard& FDGuard::operator= (FDGuard&& other)
{
swap (*this, other);
return *this;
}
FDGuard::~FDGuard ()
{
if (FD_ >= 0)
close (FD_);
}
FDGuard::operator bool () const
{
return FD_ >= 0;
}
FDGuard::operator int () const
{
return FD_;
}
void swap (FDGuard& g1, FDGuard& g2)
{
std::swap (g1.FD_, g2.FD_);
}
}
}
| 28.975 | 78 | 0.670837 | rayslava |
8626e61e3bb2a3d6347e661ece41835af910aed5 | 3,386 | cpp | C++ | MachineLearning/NNProject.cpp | bburwood/AIEYear2 | 51c50693c54008f0d199339721024ab6cbaf7456 | [
"MIT"
] | 1 | 2019-08-25T03:04:11.000Z | 2019-08-25T03:04:11.000Z | MachineLearning/NNProject.cpp | bburwood/AIEYear2 | 51c50693c54008f0d199339721024ab6cbaf7456 | [
"MIT"
] | null | null | null | MachineLearning/NNProject.cpp | bburwood/AIEYear2 | 51c50693c54008f0d199339721024ab6cbaf7456 | [
"MIT"
] | null | null | null | #include "NNProject.h"
#include <iostream>
using namespace std;
int gScreenWidth;
int gScreenHeight;
NNProject::NNProject()
{
}
NNProject::~NNProject()
{
}
bool NNProject::onCreate(int argc, char* argv[])
{
// initialise the Gizmos helper class
Gizmos::create(0xffff, 0xffff, 0xffff, 0xffff);
// set the colour the window is cleared to
glClearColor(0.25f, 0.25f, 0.25f, 1);
// enable depth testing
glEnable(GL_DEPTH_TEST);
GLFWMouseButton1Down = false;
glfwGetWindowSize(glfwGetCurrentContext(), &gScreenWidth, &gScreenHeight);
setUpSimulation();
return true;
}
void NNProject::setUpSimulation()
{
setUpAgents();
setUpSimpleLinearZone();
// setUpTurrets();
//setUpFood();
}
void NNProject::onDestroy()
{
Gizmos::destroy();
}
void NNProject::setUpSimpleLinearZone()
{
glm::vec2 centre(600, 400);
float rotation = 1.5;
linearZone = LinearZone(centre, rotation);
}
void NNProject::setUpAgents()
{
srand((unsigned int)time(NULL));
for (int index = 0; index < MAX_AGENTS;index++)
{
glm::vec2 startPos;
startPos.x = (float)(rand() % gScreenWidth);
startPos.y = (float)(rand() %2 * gScreenHeight);
float size = 30;
float facing= 44/7.0f * ((rand()%1000)/1000.0f);
agents[index].setup(startPos, size, glm::vec4(1, 1, 1, 1), facing);
}
}
void NNProject::onUpdate(float deltaTime)
{
// clear all gizmos from last frame
Gizmos::clear();
updateAgents(deltaTime);
linearZone.addGizmo();
addAgentGizmos();
addTurretWidgets();
addFoodWidgets();
}
void NNProject::onDraw()
{
// clear the back-buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// get window dimensions for 2D orthographic projection
int width = 0, height = 0;
glfwGetWindowSize(glfwGetCurrentContext(), &width, &height);
Gizmos::draw2D(glm::ortho<float>(0, (float)width, 0, (float)height, -1.0f, 1.0f));
}
void NNProject::updateAgents(float delta)
{
for (int index = 0; index < MAX_AGENTS; index++)
{
agents[index].update(delta);
checkAgentDamage(&agents[index]);
checkAgentFood(&agents[index]);
}
}
void NNProject::checkAgentDamage(Agent* agent)
{
float damage = 0;
damage += linearZone.checkRange(agent->getPosition());
for (auto turret : turrets)
{
damage += turret.checkRange(agent->getPosition());
}
agent->hurtAgent(damage);
}
void NNProject::checkAgentFood(Agent* agent)
{
float foodFound = 0;
for (auto food : foods)
{
foodFound += food.checkRange(agent->getPosition());
}
agent->feedAgent(foodFound);
}
void NNProject::setUpTurrets()
{
turrets[0] = Turret(glm::vec2(400,300),200);
// turrets[1] = Turret(glm::vec2(1100, 300), 200); //second turret for next experiment
}
void NNProject::setUpFood()
{
foods[0] = Food(glm::vec2(900, 50), 75);
foods[1] = Food(glm::vec2(600,600), 75);
}
float NNProject::simulateTurret(glm::vec2& centre, float range, Agent* agent)
{
glm::vec2 displacment = agent->getPosition() - centre;
float distance = glm::length(displacment);
if (distance<range)
{
return true;
}
return false;
}
void NNProject::drawAgents()
{
for (int index = 0; index < MAX_AGENTS; index++)
{
agents[index].draw();
}
}
void NNProject::addAgentGizmos()
{
for (auto agent : agents)
{
agent.addGizmo();
}
}
void NNProject::addTurretWidgets()
{
for (auto turret :turrets)
{
turret.addGizmo();
}
}
void NNProject::addFoodWidgets()
{
for (auto food : foods)
{
food.addGizmo();
}
} | 18.402174 | 86 | 0.689604 | bburwood |
863143f355084a52204373aa0e4ac765e2cc7387 | 129 | cpp | C++ | boards/px4/fmu-v4/src/timer_config.cpp | Diksha-agg/Firmware_val | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | [
"BSD-3-Clause"
] | null | null | null | boards/px4/fmu-v4/src/timer_config.cpp | Diksha-agg/Firmware_val | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | [
"BSD-3-Clause"
] | null | null | null | boards/px4/fmu-v4/src/timer_config.cpp | Diksha-agg/Firmware_val | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | [
"BSD-3-Clause"
] | null | null | null | version https://git-lfs.github.com/spec/v1
oid sha256:c636ca0a80ea9c8a2340b156473c13cebe20f4257e51982d03e998f5e6290324
size 3114
| 32.25 | 75 | 0.883721 | Diksha-agg |
863241f218a7771773a1fe598b6e46f945173e8d | 1,049 | cpp | C++ | Entregas/ACM_Tarea07/P05/HW07P05.cpp | cesar-magana/Advanced_Programming | 7b5ff09cd2816b67ca9f68d5ede211c73fb73de5 | [
"MIT"
] | null | null | null | Entregas/ACM_Tarea07/P05/HW07P05.cpp | cesar-magana/Advanced_Programming | 7b5ff09cd2816b67ca9f68d5ede211c73fb73de5 | [
"MIT"
] | null | null | null | Entregas/ACM_Tarea07/P05/HW07P05.cpp | cesar-magana/Advanced_Programming | 7b5ff09cd2816b67ca9f68d5ede211c73fb73de5 | [
"MIT"
] | null | null | null | /*------------------------------------------------------------
PROGRAMACIÓN AVANZADA I HW07P05
César Magaña
cesar@cimat.mx
--------------------------------------------------------------*/
#include <ctime>
#include <iostream>
#include <cstdlib>
using namespace std;
float Tab[10] = {3.141592, 2.7178, 1.1, 0.00003, 2.2, 1.1111111, 90.45, 32.32, 1.0, 0.5};
//------------------------------------------------------------
//Función aleatoria.
float& aleatoria(void){
srand(time(0));
int r = (rand() % 10);
return Tab[r];
}
//------------------------------------------------------------
//Función maliciosa.
void maliciosa( const float &val ){
const_cast <float&>(val);
float& val2 = const_cast<float&>(val);
val2 = aleatoria();
}
//------------------------------------------------------------
int main (int argc, char * const argv[]) {
cout << "Entrada original: " << Tab[0] << endl;
maliciosa( Tab[0] );
cout << "Entrada cambiada: " << Tab[0] << endl;
return 0;
}
//------------------------------------------------------------
| 24.97619 | 89 | 0.406101 | cesar-magana |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.