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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
217076e887dfc95d5921ce543b06a3fbb0019445
| 3,811
|
cc
|
C++
|
src/ipfs.cc
|
cloudcosmonaut/Browser
|
4534b66266d73afdd8c80bea437a740b87e8c645
|
[
"MIT"
] | null | null | null |
src/ipfs.cc
|
cloudcosmonaut/Browser
|
4534b66266d73afdd8c80bea437a740b87e8c645
|
[
"MIT"
] | null | null | null |
src/ipfs.cc
|
cloudcosmonaut/Browser
|
4534b66266d73afdd8c80bea437a740b87e8c645
|
[
"MIT"
] | null | null | null |
#include "ipfs.h"
/**
* \brief IPFS Contructor, connect to IPFS
* \param host IPFS host (eg. localhost)
* \param port IPFS port number (5001)
* \param timeout IPFS time-out (which is a string, eg. "6s" for 6 seconds)
*/
IPFS::IPFS(const std::string& host, int port, const std::string& timeout)
: host(host),
port(port),
timeout(timeout),
client(this->host, this->port, this->timeout)
{
}
/**
* \brief Get the number of IPFS peers.
* \return number of peers as size_t
*/
std::size_t IPFS::getNrPeers()
{
ipfs::Json peers;
client.SwarmPeers(&peers);
return peers["Peers"].size();
}
/**
* \brief Retrieve your IPFS client ID.
* \return ID as string
*/
std::string IPFS::getClientID()
{
ipfs::Json id;
client.Id(&id);
return id["ID"];
}
/**
* \brief Retrieve your IPFS Public Key.
* \return Public key string
*/
std::string IPFS::getClientPublicKey()
{
ipfs::Json id;
client.Id(&id);
return id["PublicKey"];
}
/**
* \brief Retrieve the Go IPFS daemon version.
* \return Version string
*/
std::string IPFS::getVersion()
{
ipfs::Json version;
client.Version(&version);
return version["Version"];
}
/**
* \brief Get the number of IPFS peers.
* \return Map with bandwidth information (with keys: 'in' and 'out')
*/
std::map<std::string, float> IPFS::getBandwidthRates()
{
std::map<std::string, float> bandwidthRates;
ipfs::Json bandwidth_info;
client.StatsBw(&bandwidth_info);
float in = bandwidth_info["RateIn"];
float out = bandwidth_info["RateOut"];
bandwidthRates.insert(std::pair<std::string, float>("in", in));
bandwidthRates.insert(std::pair<std::string, float>("out", out));
return bandwidthRates;
}
/**
* \brief Get the stats of the current Repo.
* \return Map with repo stats (with keys: 'repo-size' and 'path')
*/
std::map<std::string, std::variant<int, std::string>> IPFS::getRepoStats()
{
std::map<std::string, std::variant<int, std::string>> repoStats;
ipfs::Json repo_stats;
client.StatsRepo(&repo_stats);
int repoSize = (int)repo_stats["RepoSize"] / 1000000; // Convert from bytes to MB
std::string repoPath = repo_stats["RepoPath"];
repoStats.insert(std::pair<std::string, int>("repo-size", repoSize));
repoStats.insert(std::pair<std::string, std::string>("path", repoPath));
return repoStats;
}
/**
* \brief Fetch file from IFPS network
* \param path File path
* \param contents File contents as iostream
* \throw std::runtime_error when there is a
* connection-time/something goes wrong while trying to get the file
*/
void IPFS::fetch(const std::string& path, std::iostream* contents)
{
client.FilesGet(path, contents);
}
/**
* \brief Add a file to IPFS network
* \param path File path where the file could be stored in IPFS (like putting a file inside a directory within IPFS)
* \param content Content that needs to be written to the IPFS network
* \throw std::runtime_error when there is a connection-time/something goes wrong while adding the file
* \return IPFS content-addressed identifier (CID) hash
*/
std::string IPFS::add(const std::string& path, const std::string& content)
{
ipfs::Json result;
std::string hash;
// Publish a single file
client.FilesAdd({{path, ipfs::http::FileUpload::Type::kFileContents, content}}, &result);
if (result.is_array() && result.size() > 0)
{
for (const auto& files : result.items())
{
hash = files.value()["hash"];
break;
}
}
else
{
throw std::runtime_error("File is not added, result is incorrect.");
}
return hash;
}
/**
* Abort the request abruptly. Used for stopping the thread.
*/
void IPFS::abort()
{
client.Abort();
}
/**
* Reset the state, to allow for new API IPFS requests. Used after the thread.join() and abort() call.
*/
void IPFS::reset()
{
client.Reset();
}
| 25.75
| 116
| 0.674626
|
cloudcosmonaut
|
2172120c9e267a69f2407de2e5284e17f3b1b5b6
| 5,320
|
cpp
|
C++
|
longcat/src/States/GameStateLoadLevel.cpp
|
Dreamer2345/arduboy-longcat
|
576c68fa98574e956ac4f132fb85d0b7fe98d2f5
|
[
"MIT"
] | 2
|
2022-03-05T15:16:14.000Z
|
2022-03-09T03:07:18.000Z
|
longcat/src/States/GameStateLoadLevel.cpp
|
Dreamer2345/arduboy-longcat
|
576c68fa98574e956ac4f132fb85d0b7fe98d2f5
|
[
"MIT"
] | null | null | null |
longcat/src/States/GameStateLoadLevel.cpp
|
Dreamer2345/arduboy-longcat
|
576c68fa98574e956ac4f132fb85d0b7fe98d2f5
|
[
"MIT"
] | 1
|
2022-03-17T23:14:27.000Z
|
2022-03-17T23:14:27.000Z
|
#include "GameStateLoadLevel.h"
#include "../Game.h"
void GameStateLoadLevel::update(Game &game)
{
switch (game.getGameMode())
{
case GameMode::Random:
loadRandomLevel(game);
break;
default:
loadStaticLevel(game);
break;
}
game.setGameState(GameState::GamePlay);
}
void GameStateLoadLevel::render(Game &game)
{
}
void GameStateLoadLevel::loadStaticLevel(Game &game)
{
LevelUtils::initPlayer(game);
LevelUtils::copyStaticLevel(game);
}
bool GameStateLoadLevel::canMoveRandom(int8_t x, int8_t y, Direction currentDirection, uint8_t currentDepth, Game &game)
{
auto &context = game.getGameContext();
int8_t dx = 0;
int8_t dy = 0;
switch (currentDirection)
{
case Direction::Left:
dx = -1;
dy = 0;
break;
case Direction::Right:
dx = 1;
dy = 0;
break;
case Direction::Up:
dx = 0;
dy = -1;
break;
case Direction::Down:
dx = 0;
dy = 1;
break;
}
bool inBounds = context.mapObject.InBounds(x + dx, y + dy);
bool inBoundsNext = context.mapObject.InBounds(x + (dx * 2), y + (dy * 2));
uint16_t currentTilePacked = context.mapObject.getTilePacked(x + dx, y + dy);
uint16_t nextTilePacked = context.mapObject.getTilePacked(x + (dx * 2), y + (dy * 2));
bool isUsed = PackedConverter::usedFromPacked(currentTilePacked);
bool isNextUsed = PackedConverter::usedFromPacked(nextTilePacked);
uint8_t nextDepth = PackedConverter::depthFromPacked(nextTilePacked);
bool canMove = true;
if (inBoundsNext&&isNextUsed&&!(nextDepth < currentDepth))
{
canMove = false;
}
return inBounds && !isUsed && canMove;
}
uint8_t GameStateLoadLevel::getNeighbourUsed(int8_t x, int8_t y, Game &game)
{
auto &context = game.getGameContext();
uint8_t count = 0;
if (!PackedConverter::usedFromPacked(context.mapObject.getTilePacked(x - 1, y)))
++count;
if (!PackedConverter::usedFromPacked(context.mapObject.getTilePacked(x + 1, y)))
++count;
if (!PackedConverter::usedFromPacked(context.mapObject.getTilePacked(x, y - 1)))
++count;
if (!PackedConverter::usedFromPacked(context.mapObject.getTilePacked(x, y + 1)))
++count;
return count;
}
uint8_t GameStateLoadLevel::checkSteps(int8_t x, int8_t y, Direction direction, uint8_t depth, Game &game)
{
uint8_t steps = 0;
int8_t dx = 0;
int8_t dy = 0;
switch (direction)
{
case Direction::Left:
dx = -1;
dy = 0;
break;
case Direction::Right:
dx = 1;
dy = 0;
break;
case Direction::Up:
dx = 0;
dy = -1;
break;
case Direction::Down:
dx = 0;
dy = 1;
break;
}
while (canMoveRandom(x, y, direction, depth + steps, game))
{
x += dx;
y += dy;
steps++;
}
return steps;
}
void GameStateLoadLevel::generateRandomLevel(Game &game)
{
auto &context = game.getGameContext();
randomSeed(context.currentSeed + 1);
randomSeed(context.currentSeed);
context.hero.x = random(8);
context.hero.y = random(8);
context.mapObject.reset(fromTileIndex(PackedConverter::toPackedValue(0, Direction::Center, false)));
uint8_t Depth = 0;
int8_t x = context.hero.x;
int8_t y = context.hero.y;
uint8_t direction = random(4) + 1;
uint8_t previousDirection = direction;
int8_t dx = 0;
int8_t dy = 0;
int8_t pdx = 0;
int8_t pdy = 0;
context.mapObject.setTile(x, y, fromTileIndex(PackedConverter::toPackedValue(Depth, static_cast<Direction>(direction), true)));
while (true)
{
if (getNeighbourUsed(x, y, game) == 0)
{
break;
}
previousDirection = direction;
pdx = dx;
pdy = dy;
do
{
direction = random(4) + 1;
switch (direction)
{
case 1:
dx = -1;
dy = 0;
break;
case 2:
dx = 1;
dy = 0;
break;
case 3:
dx = 0;
dy = -1;
break;
case 4:
dx = 0;
dy = 1;
break;
}
} while (canMoveRandom(x, y, static_cast<Direction>(direction), Depth, game) == false);
int8_t magnitude = random(checkSteps(x, y, static_cast<Direction>(direction), Depth, game)) + 1;
if (direction != previousDirection)
{
if (!PackedConverter::usedFromPacked(context.mapObject.getTilePacked(x + pdx, y + pdy)))
context.mapObject.setTile(x + pdx, y + pdy, fromTileIndex(PackedConverter::toPackedValue(Depth, Direction::Center, true)));
}
for (; magnitude > 0; --magnitude)
{
if (canMoveRandom(x, y, static_cast<Direction>(direction), Depth, game))
{
++Depth;
x += dx;
y += dy;
context.mapObject.setTile(x, y, fromTileIndex(PackedConverter::toPackedValue(Depth, static_cast<Direction>(direction), true)));
}
else
{
break;
}
}
}
for (int j = 0; j < 8; j++)
{
for (int i = 0; i < 8; i++)
{
if (PackedConverter::usedFromPacked(toTileIndex(context.mapObject.getTile(i, j))) && PackedConverter::directionFromPacked(toTileIndex(context.mapObject.getTile(i, j))) != Direction::Center)
{
context.mapObject.setTile(i, j, TileType::Empty);
}
else
{
context.mapObject.setTile(i, j, TileType::Wall);
}
}
}
}
void GameStateLoadLevel::loadRandomLevel(Game &game)
{
LevelUtils::initPlayer(game);
generateRandomLevel(game);
}
| 23.856502
| 195
| 0.628947
|
Dreamer2345
|
2183b1798d89340b6ba3dfcfa7ab80ce4fe2d3b5
| 7,593
|
cpp
|
C++
|
fog/Fog/FogMakerContext.cpp
|
UltimateScript/Forgotten
|
ac59ad21767af9628994c0eecc91e9e0e5680d95
|
[
"BSD-3-Clause"
] | null | null | null |
fog/Fog/FogMakerContext.cpp
|
UltimateScript/Forgotten
|
ac59ad21767af9628994c0eecc91e9e0e5680d95
|
[
"BSD-3-Clause"
] | null | null | null |
fog/Fog/FogMakerContext.cpp
|
UltimateScript/Forgotten
|
ac59ad21767af9628994c0eecc91e9e0e5680d95
|
[
"BSD-3-Clause"
] | null | null | null |
#include <Fog/FogIncludeAll.h>
TYPEINFO_SINGLE(FogMakerContext, Super)
TYPEINFO_SINGLE(FogEntityMakerContext, Super)
TYPEINFO_SINGLE(FogDecoratedMakerContext, Super)
TYPEINFO_SINGLE(FogFunctionMakerContext, Super)
TYPEINFO_SINGLE(FogNestedMakerContext, Super)
TYPEINFO_SINGLE(FogTemplatedMakerContext, Super)
FogEntity *FogMakerContext::find_entity(FindStrategy aStrategy)
{
FogEntityFinding theFinding(aStrategy);
FogEntityFinder theFinder(theFinding, *this);
find_entities(theFinder);
return theFinding.get_unambiguous_finding(short_id(), dynamic_scope());
}
PrimIdHandle FogMakerContext::make_scoped_id(const PrimId& unscopedId) const
{
if (dynamic_scope().is_global_scope() || dynamic_scope().is_null())
return unscopedId;
else
{
PrimOstrstream s;
s << dynamic_scope().global_signature_id() << "::" << unscopedId;
size_t aSize = s.pcount();
return PrimIdHandle(s.str(), aSize);
}
}
PrimIdHandle FogMakerContext::make_templated_id(const PrimId& unscopedId) const
{
const FogTemplateParameterSpecifiers *templateParameterSpecifiers = template_parameters();
if (!templateParameterSpecifiers)
return unscopedId;
else if (!templateParameterSpecifiers->parameters().tally())
return unscopedId;
else
{
PrimOstrstream s;
char tailChar = FogStream::space_and_emit(s, 0, unscopedId);
tailChar = templateParameterSpecifiers->print_suffix(s, tailChar);
size_t aSize = s.pcount();
return PrimIdHandle(s.str(), aSize);
}
}
std::ostream& FogMakerContext::print_this(std::ostream& s) const
{
print_resolution(s);
dynamic_token().print_long_id(s);
s << " <- ";
specifier().print_named(s, 0, 0);
return s;
}
FogScopeContext::Resolution FogMakerContext::resolution() const { return RESOLVE_ATS; }
//
// Resolve the template arguments within primaryEntity and assign to templateArgs, returning false if not possible
// as is the case for resolution of a function name whose templae arguments must be deduced.
//
bool FogMakerContext::resolve_template(FogEntity& primaryEntity, FogTemplateArgsRefToConst& templateArgs)
{
return false;
}
const FogUtility& FogMakerContext::utility() const
{
const FogUtility& superUtility = Super::utility();
const FogUtility& specifierUtility = specifier().utility();
// if (superUtility != specifierUtility)
// ERRMSG("INVESTIGATE -- inconsistent " << superUtility.str() << " and " << specifierUtility.str());
const FogUtility& theUtility = min(specifierUtility, superUtility);
return theUtility;
}
const PrimId& FogDecoratedMakerContext::global_id() const { return maker_context().global_id(); }
PrimIdHandle FogDecoratedMakerContext::global_signature_id() const { return maker_context().global_signature_id(); }
const PrimId& FogDecoratedMakerContext::local_id() const { return maker_context().local_id(); }
PrimIdHandle FogDecoratedMakerContext::local_signature_id() const { return maker_context().local_signature_id(); }
const PrimId& FogDecoratedMakerContext::long_id() const { return maker_context().long_id(); }
FogEntity *FogDecoratedMakerContext::make_entity(FogMakerContext& makerContext, const PrimId& anId)
{ return maker_context().make_entity(makerContext, anId); }
FogScopeContext::Resolution FogDecoratedMakerContext::resolution() const { return maker_context().resolution(); }
const PrimId& FogDecoratedMakerContext::short_id() const { return maker_context().short_id(); }
const FogSpecifier& FogDecoratedMakerContext::specifier() const { return maker_context().specifier(); }
// ---------------------------------------------------------------------------------------------------------------------
FogEntityMakerContext::FogEntityMakerContext(FogMakeEntityContext& makeEntityContext,
const FogSpecifier& aSpecifier, MakerFunction aMaker)
:
Super(makeEntityContext),
_specifier(aSpecifier),
_maker(aMaker)
{}
const PrimId& FogEntityMakerContext::global_id() const { return long_id(); }
PrimIdHandle FogEntityMakerContext::global_signature_id() const { return make_templated_id(global_id()); }
const PrimId& FogEntityMakerContext::local_id() const { return short_id(); }
PrimIdHandle FogEntityMakerContext::local_signature_id() const { return make_templated_id(local_id()); }
const PrimId& FogEntityMakerContext::long_id() const
{
if (!_long_id)
mutate()._long_id = make_scoped_id(short_id());
return *_long_id;
}
FogEntity *FogEntityMakerContext::make_entity(FogMakerContext& makerContext, const PrimId& anId)
{
_short_id = anId;
FogScope& theScope = makerContext.dynamic_scope();
return (theScope.*_maker)(makerContext);
}
const PrimId& FogEntityMakerContext::short_id() const { return *_short_id; }
const FogSpecifier& FogEntityMakerContext::specifier() const { return *_specifier; }
FogFunctionMakerContext::FogFunctionMakerContext(FogMakerContext& makerContext,
const PrimId& localSignatureId, const PrimId& globalSignatureId)
:
Super(makerContext),
_local_signature_id(localSignatureId),
_global_signature_id(globalSignatureId)
{}
PrimIdHandle FogFunctionMakerContext::global_signature_id() const { return *_global_signature_id; }
PrimIdHandle FogFunctionMakerContext::local_signature_id() const { return *_local_signature_id; }
// ---------------------------------------------------------------------------------------------------------------------
FogNestedMakerContext::FogNestedMakerContext(FogMakerContext& makerContext, FogToken& inToken)
:
Super(makerContext),
_dynamic_token(inToken)
{}
FogToken& FogNestedMakerContext::dynamic_token() { return _dynamic_token; }
const FogToken& FogNestedMakerContext::dynamic_token() const { return _dynamic_token; }
bool FogNestedMakerContext::find_formal_slots(FogMetaSlotFinder& theFinder) { return false; }
bool FogNestedMakerContext::find_slots(FogMetaSlotFinder& theFinder) { return _dynamic_token.find_slots(theFinder); }
const PrimId& FogNestedMakerContext::global_id() const
{
if (!_global_id)
mutate()._global_id = make_scoped_id(local_id());
return *_global_id;
}
PrimIdHandle FogNestedMakerContext::global_signature_id() const { return global_id(); }
FogScopeContext::InScope FogNestedMakerContext::in_scope() const { return IN_THIS_SCOPE; }
const PrimId& FogNestedMakerContext::long_id() const
{
if (!_long_id)
mutate()._long_id = make_scoped_id(short_id());
return *_long_id;
}
FogTemplatedMakerContext::FogTemplatedMakerContext(FogMakerContext& makerContext, const FogTemplatedName& templatedName)
:
Super(makerContext),
_templated_name(templatedName)
{}
void FogTemplatedMakerContext::find_entities(FogEntityFinder& theFinder)
{
FogEntityFinding theFinding(theFinder.strategy());
FogEntityFinder nestedFinder(theFinding, theFinder);
Super::find_entities(nestedFinder);
FogEntity *primaryEntity = theFinding.get_unambiguous_finding(dynamic_token(), *this);
if (primaryEntity)
{
FogTemplateArgsRefToConst templateArgs;
if (_templated_name.resolve_template(*primaryEntity, templateArgs, *this))
{
FogMakeTemplateContext makeContext(*this, *primaryEntity, *templateArgs, IS_DEFINITION);
FogEntity *secondaryEntity = primaryEntity->find_template(makeContext);
if (secondaryEntity)
theFinder.add_find(*secondaryEntity);
}
}
}
std::ostream& FogTemplatedMakerContext::print_resolution(std::ostream& s) const
{
Super::print_resolution(s);
s << " < ";
_templated_name.exprs().print_named(s, 0, 0);
s << " >, ";
return s;
}
bool FogTemplatedMakerContext::resolve_template(FogEntity& primaryEntity, FogTemplateArgsRefToConst& templateArgs)
{
return _templated_name.resolve_template(primaryEntity, templateArgs, *this);
}
| 35.985782
| 121
| 0.762018
|
UltimateScript
|
2199a3d86ab5f647ad4d9e32d27f541fd27dfa3f
| 12,290
|
hpp
|
C++
|
include/knn_tester.hpp
|
hfichtenberger/knn_tester
|
a661baf5cf43e57de7ca4e01246c61feca6160f3
|
[
"MIT"
] | 1
|
2018-04-19T16:37:53.000Z
|
2018-04-19T16:37:53.000Z
|
include/knn_tester.hpp
|
hfichtenberger/knn_tester
|
a661baf5cf43e57de7ca4e01246c61feca6160f3
|
[
"MIT"
] | null | null | null |
include/knn_tester.hpp
|
hfichtenberger/knn_tester
|
a661baf5cf43e57de7ca4e01246c61feca6160f3
|
[
"MIT"
] | 1
|
2018-10-16T09:00:36.000Z
|
2018-10-16T09:00:36.000Z
|
/*
Copyright 2018 Dennis Rohde
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.
*/
#pragma once
#include <cmath>
#include <limits>
#include <boost/chrono/include.hpp>
#include "knn_graph.hpp"
#include "random.hpp"
#include "oracle.hpp"
class Tester_Result{
public:
bool decision;
double total_time;
double query_time;
};
template <typename V = double>
class KNN_Tester {
typedef typename KNN_Graph<V>::vertices_type vertices_type;
protected:
bool auto_c1;
public:
/**
*
* tuning parameter c1 for psi
*
*/
double c1 = 1;
/**
*
* tuning parameter c2 for |T|
*
*/
double c2 = 1;
KNN_Tester(const bool auto_c1 = true) : auto_c1{auto_c1} {}
/**
*
* Calculates approximate for c1
* @param Number of dimensions delta
* @return approximate for c1
*
*/
static double c1_approximate(const KNN_Graph<V> &graph) {
auto delta = graph.dimension();
return std::pow(2, 0.401 * delta * (1 + 2.85 * delta / std::pow(delta, 1.4)));
}
/**
*
* Property Testing Algorithm for k-nearest Neighborhood Graphs
* @param KNN_Graph G, average degree of G, epsilon
* @return true or false
*
*/
virtual Tester_Result test(const KNN_Graph<V> &graph, const double d, const double epsilon = 0.001) {
if (auto_c1) this->c1 = c1_approximate(graph);
const auto delta = graph.dimension();
const auto k = graph.get_k();
const auto n = graph.number_vertices();
const auto s = std::ceil(100 * k * sqrt(n) / epsilon * c2);
const auto t = std::ceil(log(10) * c1 * k * sqrt(n));
Uniform_Random_Generator<double> urandom_gen;
const auto S = urandom_gen.get(s);
const auto T = urandom_gen.get(t);
std::cout << "|S| = " << s << std::endl;
std::cout << "|T| = " << t << std::endl;
bool wrongly_connected_found = false;
double distn, distw;
#pragma omp parallel for shared(wrongly_connected_found, distn, distw)
for (unsigned long long i = 0; i < S.size(); ++i) {
if (wrongly_connected_found) continue;
const unsigned long long v = floor(S[i] * n);
const auto v_value = graph.get_vertex(v);
if (graph.number_neighbors(v) > 100 * k * d / epsilon) continue;
const auto &neighbors = graph.get_edges()[v];
V distN = 0;
for (const auto &neighbor: neighbors) {
auto dist = KNN_Graph<V>::euclidean_distance(v_value, graph.get_vertex(neighbor));
if (dist > distN) {
distN = dist;
}
}
for (unsigned long long j = 0; j < T.size(); ++j) {
if (wrongly_connected_found) {
continue;
}
unsigned long long w = floor(T[j] * n);
auto dist = KNN_Graph<V>::euclidean_distance(v_value, graph.get_vertex(w));
if (v != w and distN - dist > std::numeric_limits<V>::epsilon()) {
auto is_neighbor = false;
for (const auto &neighbor: neighbors) {
if (w == neighbor) {
is_neighbor = true;
break;
}
}
if (not is_neighbor) {
#pragma omp critical
{
if (not wrongly_connected_found) {
wrongly_connected_found = true;
distn = distN;
distw = dist;
}
}
}
}
}
}
Tester_Result result;
if (wrongly_connected_found) {
std::cout << "Reject!" << std::endl;
std::cout << distw << " < " << distn << std::endl;
result.decision = false;
} else {
std::cout << "Accept!" << std::endl;
result.decision = true;
}
return result;
}
inline auto get_auto_c1() const {
return auto_c1;
}
inline void set_auto_c1(const bool auto_c1) {
this->auto_c1 = auto_c1;
}
};
template <typename V = double>
class KNN_Tester_Oracle : public KNN_Tester<V> {
Query_Oracle<V> Oracle;
public:
KNN_Tester_Oracle(const Query_Oracle<V> &oracle) : Oracle{std::move(oracle)} {}
/**
*
* Property Testing Algorithm for k-Nearest Neighborhood Graphs - Oracle Version
* @param KNN_Graph G, average degree of G, epsilon
* @return
*
*/
Tester_Result test(const KNN_Graph<V> &graph, const double d, const double epsilon = 0.001) {
auto start = boost::chrono::process_real_cpu_clock::now();
Oracle.reset_timer();
if (this->auto_c1) this->c1 = this->c1_approximate(graph);
const auto delta = graph.dimension();
const auto k = graph.get_k();
const auto n = graph.number_vertices();
const auto s = std::ceil(100 * k * sqrt(n) / epsilon * this->c2);
const auto t = std::ceil(log(10) * this->c1 * k * sqrt(n));
Uniform_Random_Generator<double> urandom_gen;
const auto S = urandom_gen.get(s);
const auto T = urandom_gen.get(t);
std::cout << "|S| = " << s << std::endl;
std::cout << "|T| = " << t << std::endl;
bool wrongly_connected_found = false;
double distn, distw;
#pragma omp parallel for shared(wrongly_connected_found, distn, distw)
for (unsigned long long i = 0; i < S.size(); ++i) {
if (wrongly_connected_found) continue;
const unsigned long long v = floor(S[i] * n);
const auto v_value = graph.get_vertex(v);
Relation<V> neighbors;
#pragma omp critical
{
neighbors = Oracle.query(v);
}
if (neighbors.size() > 100 * k * d / epsilon) continue;
V distN = 0;
for (const auto &neighbor: neighbors) {
auto dist = KNN_Graph<V>::euclidean_distance(v_value, neighbor);
if (dist > distN) {
distN = dist;
}
}
for (unsigned long long j = 0; j < T.size(); ++j) {
if (wrongly_connected_found) {
continue;
}
unsigned long long w = floor(T[j] * n);
auto dist = KNN_Graph<V>::euclidean_distance(v_value, graph.get_vertex(w));
if (v != w and distN - dist > std::numeric_limits<V>::epsilon()) {
auto is_neighbor = false;
for (const auto &neighbor: neighbors) {
if (graph.get_vertex(w) == neighbor) {
is_neighbor = true;
break;
}
}
if (not is_neighbor) {
#pragma omp critical
{
if (not wrongly_connected_found) {
wrongly_connected_found = true;
distn = distN;
distw = dist;
}
}
}
}
}
}
auto stop = boost::chrono::process_real_cpu_clock::now();
auto total_time = (stop-start).count();
auto query_time = Oracle.time();
Tester_Result result;
result.total_time = total_time / 1000000000.0;
result.query_time = query_time / 1000000000.0;
if (wrongly_connected_found) {
std::cout << "Reject!" << std::endl;
std::cout << distw << " < " << distn << std::endl;
result.decision = false;
} else {
std::cout << "Accept!" << std::endl;
result.decision = true;
}
return result;
}
};
template <typename V = double>
class KNN_Improver : public KNN_Tester<V> {
public:
/**
*
* Property Testing Algorithm for k-Nearest Neighborhood Graphs - Graph Restauration
* @param KNN_Graph G, average degree of G, epsilon
* @return
*
*/
auto improve(KNN_Graph<V> &graph, const double d, const double epsilon = 0.001) {
auto result = 0ul;
if (this->auto_c1) this->c1 = this->c1_approximate(graph);
const auto delta = graph.dimension();
const auto k = graph.get_k();
const auto n = graph.number_vertices();
const auto s = ceil(100 * k * sqrt(n) / epsilon * this->c2);
const auto t = ceil(log(10) * this->c1 * k * sqrt(n));
Uniform_Random_Generator<double> urandom_gen;
const auto S = urandom_gen.get(s);
const auto T = urandom_gen.get(t);
std::cout << "|S| = " << s << std::endl;
std::cout << "|T| = " << t << std::endl;
#pragma omp parallel for shared(result)
for (unsigned long long i = 0; i < S.size(); ++i) {
const unsigned long long v = floor(S[i] * n);
const auto v_value = graph.get_vertex(v);
if (graph.number_neighbors(v) > 100 * k * d / epsilon) continue;
auto &neighbors = graph.get_edges()[v];
V distN = 0;
unsigned long long furthest = 0;
for (const auto &neighbor: neighbors) {
auto dist = KNN_Graph<V>::euclidean_distance(v_value, graph.get_vertex(neighbor));
if (dist > distN) {
distN = dist;
furthest = neighbor;
}
}
for (unsigned long long j = 0; j < T.size(); ++j) {
unsigned long long w = floor(T[j] * n);
auto dist = KNN_Graph<V>::euclidean_distance(v_value, graph.get_vertex(w));
if (v != w and distN - dist > std::numeric_limits<V>::epsilon()) {
auto is_neighbor = false;
for (const auto &neighbor: neighbors) {
if (w == neighbor) {
is_neighbor = true;
break;
}
}
if (not is_neighbor) {
#pragma omp critical
{
graph.get_edges()[v][furthest] = w;
++result;
distN = 0;
for (const auto &neighbor: neighbors) {
auto distF = KNN_Graph<V>::euclidean_distance(v_value, graph.get_vertex(neighbor));
if (distF > distN) {
distN = distF;
furthest = neighbor;
}
}
}
}
}
}
}
return result;
}
};
| 37.699387
| 460
| 0.504719
|
hfichtenberger
|
219bc1e121e0a684c067e1bd58f68409328344e7
| 441
|
cpp
|
C++
|
20190727_ABC135/b.cpp
|
miyalab/AtCoder
|
a57c8a6195463a9a8edd1c3ddd36cc56f145c60d
|
[
"MIT"
] | null | null | null |
20190727_ABC135/b.cpp
|
miyalab/AtCoder
|
a57c8a6195463a9a8edd1c3ddd36cc56f145c60d
|
[
"MIT"
] | null | null | null |
20190727_ABC135/b.cpp
|
miyalab/AtCoder
|
a57c8a6195463a9a8edd1c3ddd36cc56f145c60d
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> p(n);
for(int i=0;i<n;i++) cin >> p[i];
vector<int> ps=p;
sort(ps.begin(),ps.end());
int cnt=0;
for(int i=0;i<n;i++){
if(p[i]!=ps[i]){
cnt++;
if(cnt>2){
cout << "NO" << endl;
return 0;
}
}
}
cout << "YES" << endl;
}
| 15.75
| 37
| 0.37415
|
miyalab
|
219bfeb3a6914687f004e95a67fd069c208bff48
| 1,240
|
cpp
|
C++
|
pochi_libs_and_includes/include/fastinterp/fastinterp_tpl_call_expr_enter_cpp_fn.cpp
|
dghosef/taco
|
c5074c359af51242d76724f97bb5fe7d9b638658
|
[
"MIT"
] | null | null | null |
pochi_libs_and_includes/include/fastinterp/fastinterp_tpl_call_expr_enter_cpp_fn.cpp
|
dghosef/taco
|
c5074c359af51242d76724f97bb5fe7d9b638658
|
[
"MIT"
] | null | null | null |
pochi_libs_and_includes/include/fastinterp/fastinterp_tpl_call_expr_enter_cpp_fn.cpp
|
dghosef/taco
|
c5074c359af51242d76724f97bb5fe7d9b638658
|
[
"MIT"
] | null | null | null |
#define POCHIVM_INSIDE_FASTINTERP_TPL_CPP
#define FASTINTERP_TPL_USE_LARGE_MCMODEL
#include "fastinterp_tpl_common.hpp"
#include "fastinterp_function_alignment.h"
#include "fastinterp_tpl_return_type.h"
namespace PochiVM
{
struct FICallExprEnterCppFnImpl
{
template<typename ReturnType,
bool isNoExcept>
static constexpr bool cond()
{
return true;
}
template<typename ReturnType,
bool isNoExcept>
static FIReturnType<ReturnType, isNoExcept> f(uintptr_t stackframe) noexcept
{
using CppFnPrototype = FIReturnType<ReturnType, isNoExcept>(*)(uintptr_t) noexcept;
DEFINE_CPP_FNPTR_PLACEHOLDER_0(CppFnPrototype);
return CPP_FNPTR_PLACEHOLDER_0(stackframe);
}
static auto metavars()
{
return CreateMetaVarList(
CreateTypeMetaVar("returnType"),
CreateBoolMetaVar("isNoExcept")
);
}
};
} // namespace PochiVM
// build_fast_interp_lib.cpp JIT entry point
//
extern "C"
void __pochivm_build_fast_interp_library__()
{
using namespace PochiVM;
RegisterBoilerplate<FICallExprEnterCppFnImpl>(FIAttribute::NoContinuation | FIAttribute::AppendUd2 | FIAttribute::CodeModelLarge);
}
| 25.833333
| 134
| 0.71371
|
dghosef
|
426e282d31852976df92192b2a88a65d5e46ed45
| 6,130
|
cc
|
C++
|
src/base/stream_msg_with_size_reader.cc
|
dspeterson/dory
|
7261fb5481283fdd69b382c3cddbc9b9bd24366d
|
[
"Apache-2.0"
] | 82
|
2016-06-11T23:12:40.000Z
|
2022-02-21T21:01:36.000Z
|
src/base/stream_msg_with_size_reader.cc
|
dspeterson/dory
|
7261fb5481283fdd69b382c3cddbc9b9bd24366d
|
[
"Apache-2.0"
] | 18
|
2016-06-16T22:55:12.000Z
|
2020-07-02T10:32:53.000Z
|
src/base/stream_msg_with_size_reader.cc
|
dspeterson/dory
|
7261fb5481283fdd69b382c3cddbc9b9bd24366d
|
[
"Apache-2.0"
] | 14
|
2016-06-15T18:34:08.000Z
|
2021-09-06T23:16:28.000Z
|
/* <base/stream_msg_with_size_reader.cc>
----------------------------------------------------------------------------
Copyright 2017 Dave Peterson <dave@dspeterson.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
----------------------------------------------------------------------------
Implements <base/stream_msg_with_size_reader.h>.
*/
#include <base/stream_msg_with_size_reader.h>
#include <cassert>
#include <limits>
#include <base/error_util.h>
#include <base/field_access.h>
using namespace Base;
static std::optional<uint64_t> ReadUnsigned8BitSizeField(
const uint8_t *field_loc) noexcept {
return *field_loc;
}
static std::optional<uint64_t> ReadUnsigned16BitSizeField(
const uint8_t *field_loc) noexcept {
return ReadUint16FromHeader(field_loc);
}
static std::optional<uint64_t> ReadUnsigned32BitSizeField(
const uint8_t *field_loc) noexcept {
return ReadUint32FromHeader(field_loc);
}
static std::optional<uint64_t> ReadUnsigned64BitSizeField(
const uint8_t *field_loc) noexcept {
return ReadUint64FromHeader(field_loc);
}
static std::optional<uint64_t> ReadSigned8BitSizeField(
const uint8_t *field_loc) noexcept {
auto size = static_cast<int8_t>(*field_loc);
return (size < 0) ?
std::nullopt : std::optional<uint64_t>(static_cast<uint64_t>(size));
}
static std::optional<uint64_t> ReadSigned16BitSizeField(
const uint8_t *field_loc) noexcept {
int16_t size = ReadInt16FromHeader(field_loc);
return (size < 0) ?
std::nullopt : std::optional<uint64_t>(static_cast<uint64_t>(size));
}
static std::optional<uint64_t> ReadSigned32BitSizeField(
const uint8_t *field_loc) noexcept {
int32_t size = ReadInt32FromHeader(field_loc);
return (size < 0) ?
std::nullopt : std::optional<uint64_t>(static_cast<uint64_t>(size));
}
static std::optional<uint64_t> ReadSigned64BitSizeField(
const uint8_t *field_loc) noexcept {
int64_t size = ReadInt64FromHeader(field_loc);
return (size < 0) ?
std::nullopt : std::optional<uint64_t>(static_cast<uint64_t>(size));
}
TStreamMsgWithSizeReaderBase::TStreamMsgWithSizeReaderBase(
int fd, size_t size_field_size, bool size_field_is_signed,
bool size_includes_size_field, bool include_size_field_in_msg,
size_t max_msg_body_size, size_t preferred_read_size)
: TStreamMsgReader(fd),
SizeFieldSize(size_field_size),
SizeFieldIsSigned(size_field_is_signed),
SizeIncludesSizeField(size_includes_size_field),
IncludeSizeFieldInMsg(include_size_field_in_msg),
SizeFieldReadFn(ChooseSizeFieldReadFn(size_field_size,
size_field_is_signed)),
MaxMsgBodySize(max_msg_body_size),
PreferredReadSize(preferred_read_size) {
assert((std::numeric_limits<size_t>::max() - max_msg_body_size) >=
size_field_size);
assert(max_msg_body_size <=
(static_cast<size_t>(std::numeric_limits<int>::max()) -
size_field_size));
assert(preferred_read_size);
}
size_t TStreamMsgWithSizeReaderBase::GetNextReadSize() noexcept {
return PreferredReadSize;
}
TStreamMsgReader::TGetMsgResult
TStreamMsgWithSizeReaderBase::GetNextMsg() noexcept {
size_t data_size = GetDataSize();
if (data_size < SizeFieldSize) {
assert(!OptMsgBodySize);
return TGetMsgResult::NoMsgReady();
}
if (!OptMsgBodySize) {
auto opt_size = SizeFieldReadFn(GetData());
if (!opt_size) {
/* Signed size field value was found to be negative. */
OptDataInvalidReason = TDataInvalidReason::InvalidSizeField;
return TGetMsgResult::Invalid();
}
uint64_t size = *opt_size;
if (SizeIncludesSizeField && (size < SizeFieldSize)) {
OptDataInvalidReason = TDataInvalidReason::InvalidSizeField;
return TGetMsgResult::Invalid();
}
if ((size > MaxMsgBodySize) &&
(!SizeIncludesSizeField ||
((size - MaxMsgBodySize) > SizeFieldSize))) {
OptDataInvalidReason = TDataInvalidReason::MsgBodyTooLarge;
return TGetMsgResult::Invalid();
}
OptMsgBodySize = static_cast<size_t>(
SizeIncludesSizeField ? (size - SizeFieldSize) : size);
}
size_t body_size = *OptMsgBodySize;
if (data_size < (SizeFieldSize + body_size)) {
return TGetMsgResult::NoMsgReady();
}
size_t reported_size = body_size;
size_t reported_offset = 0;
if (IncludeSizeFieldInMsg) {
reported_size += SizeFieldSize;
} else {
reported_offset += SizeFieldSize;
}
return TGetMsgResult::MsgReady(reported_offset, reported_size, 0);
}
void TStreamMsgWithSizeReaderBase::HandleReset() noexcept {
OptMsgBodySize.reset();
OptDataInvalidReason.reset();
}
void TStreamMsgWithSizeReaderBase::BeforeConsumeReadyMsg() noexcept {
OptMsgBodySize.reset();
}
TStreamMsgWithSizeReaderBase::TSizeFieldReadFn
TStreamMsgWithSizeReaderBase::ChooseSizeFieldReadFn(size_t size_field_size,
bool size_field_is_signed) noexcept {
if ((size_field_size != 1) && (size_field_size != 2) &&
(size_field_size != 4) && (size_field_size != 8)) {
Die("Bad value for size_field_size in TStreamMsgWithSizeReaderBase");
}
switch (size_field_size) {
case 2: {
return size_field_is_signed ?
ReadSigned16BitSizeField : ReadUnsigned16BitSizeField;
}
case 4: {
return size_field_is_signed ?
ReadSigned32BitSizeField : ReadUnsigned32BitSizeField;
}
case 8: {
return size_field_is_signed ?
ReadSigned64BitSizeField : ReadUnsigned64BitSizeField;
}
default: {
break;
}
}
return size_field_is_signed ?
ReadSigned8BitSizeField : ReadUnsigned8BitSizeField;
}
| 31.116751
| 79
| 0.714192
|
dspeterson
|
42826d1483897572808b3dac7e7e2999223f2c88
| 719
|
cpp
|
C++
|
modules/gui/src/MetaObject/params/ui/Wt/bool.cpp
|
dtmoodie/MetaObject
|
8238d143d578ff9c0c6506e7e627eca15e42369e
|
[
"MIT"
] | 2
|
2017-10-26T04:41:49.000Z
|
2018-02-09T05:12:19.000Z
|
modules/gui/src/MetaObject/params/ui/Wt/bool.cpp
|
dtmoodie/MetaObject
|
8238d143d578ff9c0c6506e7e627eca15e42369e
|
[
"MIT"
] | null | null | null |
modules/gui/src/MetaObject/params/ui/Wt/bool.cpp
|
dtmoodie/MetaObject
|
8238d143d578ff9c0c6506e7e627eca15e42369e
|
[
"MIT"
] | 3
|
2017-01-08T21:09:48.000Z
|
2018-02-10T04:27:32.000Z
|
#ifdef HAVE_WT
#include "MetaObject/params/ui/Wt/POD.hpp"
#include <Wt/WCheckBox>
using namespace mo::UI::wt;
TDataProxy<bool, void>::TDataProxy() : _check_box(nullptr)
{
}
void TDataProxy<bool, void>::CreateUi(IParamProxy* proxy, bool& data, bool read_only)
{
_check_box = new Wt::WCheckBox(proxy);
_check_box->changed().connect(proxy, &IParamProxy::onUiUpdate);
_check_box->setReadOnly(read_only);
_check_box->setChecked(data);
}
void TDataProxy<bool, void>::UpdateUi(const bool& data)
{
_check_box->setChecked(data);
}
void TDataProxy<bool, void>::onUiUpdate(bool& data)
{
data = _check_box->isChecked();
}
void TDataProxy<bool, void>::SetTooltip(const std::string& tooltip)
{
}
#endif
| 21.787879
| 85
| 0.717663
|
dtmoodie
|
42858ca9ef79ddb0f71dded492f29825dff1988b
| 1,580
|
cpp
|
C++
|
firmwareupdateprogressdialog.cpp
|
OSVR/OSVR-CPI
|
95abd317d7295a49e0d97f663bce0f25637b63d2
|
[
"Apache-2.0"
] | 7
|
2016-09-15T18:40:12.000Z
|
2021-07-05T16:24:47.000Z
|
firmwareupdateprogressdialog.cpp
|
OSVR/OSVR-CPI
|
95abd317d7295a49e0d97f663bce0f25637b63d2
|
[
"Apache-2.0"
] | 2
|
2016-08-29T17:23:27.000Z
|
2016-10-14T17:01:49.000Z
|
firmwareupdateprogressdialog.cpp
|
OSVR/OSVR-CPI
|
95abd317d7295a49e0d97f663bce0f25637b63d2
|
[
"Apache-2.0"
] | 6
|
2016-08-29T11:10:32.000Z
|
2017-10-04T04:17:49.000Z
|
// Copyright 2016 Razer, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "firmwareupdateprogressdialog.h"
#include "ui_firmwareupdateprogressdialog.h"
FirmwareUpdateProgressDialog::FirmwareUpdateProgressDialog(QWidget *parent)
: QDialog(parent, Qt::WindowStaysOnTopHint | Qt::WindowSystemMenuHint |
Qt::WindowTitleHint),
ui(new Ui::FirmwareUpdateProgressDialog) {
ui->setupUi(this);
ui->firmwareUpdateOKButton->setVisible(false);
}
FirmwareUpdateProgressDialog::~FirmwareUpdateProgressDialog() { delete ui; }
void FirmwareUpdateProgressDialog::setTitle(QString title) {
setWindowTitle(title);
}
void FirmwareUpdateProgressDialog::setText(QString text) {
m_text = text;
ui->label->setText(text);
QApplication::processEvents();
}
QString FirmwareUpdateProgressDialog::getText() { return m_text; }
void FirmwareUpdateProgressDialog::showOK() {
ui->firmwareUpdateOKButton->setVisible(true);
activateWindow();
}
void FirmwareUpdateProgressDialog::on_firmwareUpdateOKButton_clicked() { close(); }
| 33.617021
| 83
| 0.755696
|
OSVR
|
4286c19468d2149e477166a591fe07f81cfb8562
| 374
|
cpp
|
C++
|
c++/boost/Pool/singleton_pool.cpp
|
chenmingqiang/codesnippet
|
6f355113fe4299d5cd0ddce6d8794a2fece0e891
|
[
"MIT"
] | null | null | null |
c++/boost/Pool/singleton_pool.cpp
|
chenmingqiang/codesnippet
|
6f355113fe4299d5cd0ddce6d8794a2fece0e891
|
[
"MIT"
] | null | null | null |
c++/boost/Pool/singleton_pool.cpp
|
chenmingqiang/codesnippet
|
6f355113fe4299d5cd0ddce6d8794a2fece0e891
|
[
"MIT"
] | null | null | null |
#include <boost/pool/singleton_pool.hpp>
#include <iostream>
using namespace std;
struct pool_tag1 { };
struct pool_tag2 { };
typedef boost::singleton_pool<pool_tag1, sizeof(int)> ipl;
typedef boost::singleton_pool<pool_tag2, sizeof(float)> fpl;
int main(int argc, char *argv[])
{
int *p = (int *) ipl::malloc();
float *pf = (float *)fpl::malloc();
return 0;
}
| 19.684211
| 60
| 0.687166
|
chenmingqiang
|
4286cc464dc7d46c94aba09da909309f85855208
| 523
|
hh
|
C++
|
sensactIO_firmware/main/applicationBase.hh
|
klaus-liebler/sensactIO
|
a84f45c06dd47dc635b12472e258afdabe82a158
|
[
"MIT"
] | null | null | null |
sensactIO_firmware/main/applicationBase.hh
|
klaus-liebler/sensactIO
|
a84f45c06dd47dc635b12472e258afdabe82a158
|
[
"MIT"
] | null | null | null |
sensactIO_firmware/main/applicationBase.hh
|
klaus-liebler/sensactIO
|
a84f45c06dd47dc635b12472e258afdabe82a158
|
[
"MIT"
] | null | null | null |
#pragma once
#include <inttypes.h>
#include "common.hh"
using namespace sensact::comm;
class cApplication{
public:
uint32_t const id;
cApplication(const uint32_t id):id(id){}
virtual ErrorCode Setup(SensactContext *ctx) = 0;
virtual ErrorCode Loop(SensactContext *ctx) = 0;
virtual ErrorCode FillStatus(flatbuffers::FlatBufferBuilder *builder, std::vector<flatbuffers::Offset<tStateWrapper>> *status_vector) = 0;
virtual ErrorCode ProcessCommand(const tCommand* cmd) = 0;
};
| 32.6875
| 146
| 0.713193
|
klaus-liebler
|
428e4b24e560522fb0672d766c57799e90e6a69f
| 5,235
|
cpp
|
C++
|
Universe.cpp
|
longmakesstuff/Newtons-Gravitation
|
1d4964dd355cc6acc30b473602f5f29e821c2ac3
|
[
"Apache-2.0"
] | 56
|
2021-01-13T05:22:33.000Z
|
2021-08-20T01:47:05.000Z
|
Universe.cpp
|
longuyen97/newtons-gravitation
|
1d4964dd355cc6acc30b473602f5f29e821c2ac3
|
[
"Apache-2.0"
] | 1
|
2021-01-18T08:51:12.000Z
|
2021-01-19T08:32:21.000Z
|
Universe.cpp
|
longuyen97/newtons-gravitation
|
1d4964dd355cc6acc30b473602f5f29e821c2ac3
|
[
"Apache-2.0"
] | 1
|
2021-05-19T19:59:02.000Z
|
2021-05-19T19:59:02.000Z
|
#include "Universe.hpp"
Universe::Universe(sf::RenderWindow *window, sf::Font *font) : window(window), font(font) {
if (!sunTexture.loadFromFile("sun.png", sf::IntRect(0, 0, 660, 660))) {
LOG_ERROR("Can not load sun.png. Exit now")
std::exit(1);
}
// Load planet images
constexpr int32_t height = 2985;
constexpr int32_t width = 6927;
constexpr int32_t rows = 3;
constexpr int32_t cols = 7;
constexpr int32_t sprite_width = width / cols;
constexpr int32_t sprite_height = height / rows;
sf::Image planet;
if(!planet.loadFromFile("planets.png")) {
LOG_ERROR("Can not load planets.png. Exit now")
std::exit(1);
}
for (int32_t y = 0; y < rows; y++) {
for (int32_t x = 0; x < cols; x++) {
sf::Texture texture;
sf::Image subImage;
subImage.create(sprite_width, sprite_height);
subImage.copy(planet, 0, 0, sf::IntRect{x * sprite_width, y * sprite_height, sprite_width, sprite_height});
texture.loadFromImage(subImage);
planetTextures.push_back(texture);
}
}
// Create the sun
planets.emplace_back(sf::Vector2<fpt>(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2), 2500000000,
sf::Vector2<fpt>(0.f, -0.005),
sf::Color(200, 32, 125, 200), 100, sunTexture);
planets.back().isStar = true;
}
void Universe::simulate() {
std::vector<sf::Vector2<fpt>> deltaVs;
// Simulate one second
for (auto &planet : planets) {
if (!planet.isStar) {
sf::Vector2<fpt> f = planet.gForce(planets);
sf::Vector2<fpt> a = f / planet.m;
sf::Vector2<fpt> deltaV = a * deltaT;
deltaVs.push_back(deltaV);
} else {
deltaVs.emplace_back(0, 0);
}
}
// Update position
for (int i = 0; i < deltaVs.size(); i++) {
if (!planets[i].isStar) {
planets[i].v += deltaVs[i];
sf::Vector2<fpt> deltaS = planets[i].v * deltaT;
planets[i].p += deltaS;
}
}
// Collision detection
for (auto i = planets.begin(); i != planets.end();) {
bool collision = false;
auto j = i + 1;
for (; j != planets.end();) {
if (*i != *j) {
sf::Vector2<fpt> direction = i->p - j->p;
fpt distance = sfAbs(direction);
if (distance < i->r / 2 || distance < j->r / 2) {
collision = true;
break;
} else {
j++;
}
}
}
if (collision) {
if (j->isStar) {
j->m += i->m;
i = planets.erase(i);
} else {
i->m += j->m;
planets.erase(j);
i++;
}
} else {
i++;
}
}
}
void Universe::infoText() {
std::stringstream ss;
ss << "Speed: " << (int) speed;
sf::Text speedText{ss.str(), *font, 10};
speedText.setPosition(10, 10);
speedText.setFillColor(sf::Color::White);
window->draw(speedText);
ss = std::stringstream{};
fps.update();
ss << "FPS: " << fps.getFPS();
sf::Text fpsText{ss.str(), *font, 10};
fpsText.setPosition(10, 25);
fpsText.setFillColor(sf::Color::White);
window->draw(fpsText);
}
void Universe::run() {
while (window->isOpen()) {
while (window->pollEvent(event)) {
if (event.type == sf::Event::EventType::Closed) {
std::exit(0);
}
if (event.type == sf::Event::EventType::MouseButtonPressed) {
fpt x = event.mouseButton.x;
fpt y = event.mouseButton.y;
Planet planet(sf::Vector2<fpt>(x, y), 1000, sf::Vector2<fpt>(0.01f, -0.01),
sf::Color(red_dist(engine),
green_dist(engine),
blue_dist(engine),
alpha_dist(engine)),
50, *select_randomly(planetTextures.begin(), planetTextures.end()));
if (x < WINDOW_WIDTH / 2 && y < WINDOW_HEIGHT / 2) {
planet.v = sf::Vector2<fpt>(0.01f, -0.01);
} else if (x > WINDOW_WIDTH / 2 && y < WINDOW_HEIGHT / 2) {
planet.v = sf::Vector2<fpt>(0.01f, 0.01);
} else if (x < WINDOW_WIDTH / 2 && y > WINDOW_HEIGHT / 2) {
planet.v = sf::Vector2<fpt>(-0.01f, -0.01);
} else {
planet.v = sf::Vector2<fpt>(-0.01f, 0.01);
}
planets.push_back(planet);
}
if (event.type == sf::Event::EventType::MouseWheelMoved) {
fpt scrolled = event.mouseWheel.delta;
speed += scrolled * 100.0f;
}
}
simulate();
window->clear(sf::Color::Black);
for (auto &planet : planets) {
planet.draw(*window);
}
infoText();
window->display();
deltaT = clock.restart().asSeconds() * speed;
}
}
| 32.71875
| 119
| 0.480802
|
longmakesstuff
|
4291b63ed62bb2c6691782cf4b5010f89b0c9a8e
| 1,750
|
cpp
|
C++
|
other/002/code.cpp
|
Shivam010/daily-coding-problem
|
679376a7b0f5f9bccdd261a1a660e951a1142174
|
[
"MIT"
] | 9
|
2020-09-13T12:48:35.000Z
|
2022-03-02T06:25:06.000Z
|
other/002/code.cpp
|
Shivam010/daily-coding-problem
|
679376a7b0f5f9bccdd261a1a660e951a1142174
|
[
"MIT"
] | 9
|
2020-09-11T21:19:27.000Z
|
2020-09-14T20:18:02.000Z
|
other/002/code.cpp
|
Shivam010/daily-coding-problem
|
679376a7b0f5f9bccdd261a1a660e951a1142174
|
[
"MIT"
] | 1
|
2020-09-11T22:03:29.000Z
|
2020-09-11T22:03:29.000Z
|
// Copyright (c) 2020 Shivam Rathore. All rights reserved.
// Use of this source code is governed by MIT License that
// can be found in the LICENSE file.
// This file contains Solution to Challenge Other#002, run using
// g++ other/002/code.cpp -o bin/out
// ./bin/out < other/002/in.txt > other/002/out.txt
#include <bits/stdc++.h>
using namespace std;
#define ll long long
struct Node {
int in, val;
int count[26];
vector<Node *> next;
Node(int v, int x) {
in = x;
val = v;
for (int i = 0; i < 26; i++) {
count[i] = 0;
}
count[v] = 1;
}
};
void iterate(Node *root, vector<int> &answer) {
// null entry
if (root == NULL) return;
int ans = 1, val = root->val;
int n = root->next.size();
for (int i = 0; i < n; i++) {
Node *ne = root->next[i];
iterate(ne, answer);
// count characters
for (int j = 0; j < 26; j++) {
root->count[j] = root->count[j] + ne->count[j];
if (ne->count[j] > 0) ans++;
}
// undo duplicate count
root->count[val] -= ne->count[val];
if (ne->count[val] > 0) ans--;
}
// answer
answer[root->in] = ans;
}
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
char ch;
vector<Node *> tree;
for (int i = 0; i < n; i++) {
cin >> ch;
tree.push_back(new Node(ch - 'a', i));
}
int u, v;
for (int i = 0; i < n - 1; i++) {
cin >> u >> v;
tree[u - 1]->next.push_back(tree[v - 1]);
}
vector<int> answer(n, 0);
iterate(tree[0], answer);
cout << answer[0] << endl;
}
}
| 21.875
| 64
| 0.470286
|
Shivam010
|
42932aa7e75343b486398ced449d88f1af5cad97
| 3,102
|
cpp
|
C++
|
src/rmx_win32/vConfigWnd/ConfigWndTree.cpp
|
darkain/RMX-Automation
|
b98df45a40c6e5ce8a8770579788274924d9e851
|
[
"BSD-3-Clause"
] | 1
|
2020-07-22T20:02:59.000Z
|
2020-07-22T20:02:59.000Z
|
src/rmx_win32/vConfigWnd/ConfigWndTree.cpp
|
darkain/RMX-Automation
|
b98df45a40c6e5ce8a8770579788274924d9e851
|
[
"BSD-3-Clause"
] | null | null | null |
src/rmx_win32/vConfigWnd/ConfigWndTree.cpp
|
darkain/RMX-Automation
|
b98df45a40c6e5ce8a8770579788274924d9e851
|
[
"BSD-3-Clause"
] | null | null | null |
/****************************** RMX SDK ******************************\
* Copyright (c) 2007 Vincent E. Milum Jr., All rights reserved. *
* *
* See license.txt for more information *
* *
* Latest SDK versions can be found at: http://rmx.sourceforge.net *
\***********************************************************************/
#if 0
#include "../../../sdk/rmxBase.h"
#include "ConfigWnd.h"
#include "ConfigWndTree.h"
struct vTreePlugin {
HPLUGIN plugin;
HLIST list;
};
//-----------------------------------------------------------------------------------
vConfigWndTree::vConfigWndTree(wndBase *parent) : wndTree(parent) {
}
wndTreeItem *vConfigWndTree::addItem(const char *name, wndTreeItem *parent, HPLUGIN plugin, HLIST list) {
vTreePlugin data;
data.plugin = plugin;
data.list = list;
return addTreeItem(name, 0, parent, (UINT) &data);
}
wndTreeItem *vConfigWndTree::newTreeItem(const char *name, wndTreeItem *parent, UINT param) {
if (param) {
vTreePlugin *data = (vTreePlugin*)param;
return new vPluginTreeItem(name, parent, data->plugin, (HLIST)data->list);
}
return NULL;
}
//-----------------------------------------------------------------------------------
vPluginTreeItem::vPluginTreeItem(const char *name, wndTreeItem *parent, HPLUGIN cb_plugin, HLIST cb_list)
: wndTreeItem(name, parent), cbCore(cb_plugin, cb_list) {
}
vPluginTreeItem::~vPluginTreeItem() {
}
void vPluginTreeItem::onInit() {
wndTreeItem::onInit();
wndTreeItem::setExpanded( cbCore::isExpanded() ); //todo: find out why this doesnt work
}
//TODO: FIX THIS SHIT!!
void vPluginTreeItem::cb_onNameChange(const char *newname) {
wndTreeItem::setName(newname);
// cbCore::cb_onNameChange(newname);
}
void vPluginTreeItem::onSelected() {
wndTreeItem::onSelected();
vConfigWnd::getConfigWnd()->setActiveItem(this);
}
void vPluginTreeItem::onSetExpanded(BOOL expanded) {
wndTreeItem::onSetExpanded(expanded);
cbCore::setExpanded(expanded);
if (expanded != cbCore::isExpanded()) { //in case of a read-only list
wndTreeItem::setExpanded( cbCore::isExpanded() );
}
}
//TODO: FIX THIS SHIT!!
void vPluginTreeItem::cb_onSetExpanded(BOOL expanded) {
// cbCore::cb_onSetExpanded(expanded);
wndTreeItem::setExpanded(expanded);
}
void vPluginTreeItem::cb_onInsertChild(HLIST child, HLIST insert) {
HPLUGIN plug = getRemotePlugin();
if (plug) {
const char *type = plug->list_getType(child);
const char *name = plug->list_getName(child);
if (type && *type && VSTRCMP(type, "tree") == 0) {
wndTreeItem *item = new vPluginTreeItem(name, this, getRemotePlugin(), child);
getwndBase()->addTreeItem(item);
}
}
}
void vPluginTreeItem::cb_onSetVisible(BOOL isvisible) {
wndTreeItem::setVisible(isvisible);
}
#endif
| 27.945946
| 106
| 0.568021
|
darkain
|
4294c06ac23afda28d822321df25352419712fbe
| 1,649
|
cpp
|
C++
|
source/utils/JdStdStringUtils.cpp
|
soundandform/epigram
|
f4f560b405e529e84ffd4e8a0b1101bf57148b90
|
[
"MIT"
] | 3
|
2018-02-16T04:30:22.000Z
|
2021-03-26T02:06:51.000Z
|
source/utils/JdStdStringUtils.cpp
|
soundandform/epigram
|
f4f560b405e529e84ffd4e8a0b1101bf57148b90
|
[
"MIT"
] | null | null | null |
source/utils/JdStdStringUtils.cpp
|
soundandform/epigram
|
f4f560b405e529e84ffd4e8a0b1101bf57148b90
|
[
"MIT"
] | null | null | null |
//
// JdStdStringUtils.cpp
// Jigidesign
//
// Created by Steven Massey on 6/29/16.
// Copyright © 2016 Jigidesign. All rights reserved.
//
#include "JdStdStringUtils.hpp"
#include <fstream>
using namespace std;
namespace Jd
{
std::string TrimString (std::string i_string)
{
size_t p;
while ((p = i_string.find (' ')) == 0)
{
i_string = i_string.substr (1);
}
while ((p = i_string.rfind (' ')) == (i_string.size() - 1))
{
i_string = i_string.substr (0, p);
}
return i_string;
}
std::vector <std::string> SplitString (std::string i_string, std::string i_delimiter)
{
std::vector <std::string> strings;
std::string subString;
while (true)
{
size_t pos = i_string.find (i_delimiter);
if (pos == std::string::npos) break;
subString = i_string.substr (0, pos);
i_string = i_string.substr (pos + 1);
if (subString.size())
{
strings.push_back (TrimString (subString));
}
}
strings.push_back (TrimString (i_string));
return strings;
}
std::string StripString (const std::string &i_string, cstr_t i_chars)
{
std::string s = i_string;
for (int i = 0; i_chars [i]; ++i)
{
size_t pos;
while ((pos = s.find (i_chars[i])) != std::string::npos)
s.erase (pos, 1);
}
return s;
}
std::string ReadFileContentsToString (stringRef_t i_filename)
{
ifstream ifs (i_filename, ios::binary | ios::ate);
if (ifs.good ())
{
ifstream::pos_type pos = ifs.tellg();
std::string result (pos, 0);
ifs.seekg (0, ios::beg);
ifs.read (& result [0], pos);
return result;
}
else return std::string ();
}
}
| 17.923913
| 86
| 0.607035
|
soundandform
|
429a745a6e4cb7aa617dba0ae1f100d73cc4b4d2
| 19,872
|
cpp
|
C++
|
cpp/fss-client.cpp
|
uishi/libfss
|
7255fd26af146096c5df08f18605251280d2314a
|
[
"MIT"
] | 56
|
2017-03-24T10:06:24.000Z
|
2022-03-24T12:55:32.000Z
|
cpp/fss-client.cpp
|
uishi/libfss
|
7255fd26af146096c5df08f18605251280d2314a
|
[
"MIT"
] | 5
|
2017-04-12T21:49:41.000Z
|
2018-11-15T20:22:29.000Z
|
cpp/fss-client.cpp
|
uishi/libfss
|
7255fd26af146096c5df08f18605251280d2314a
|
[
"MIT"
] | 24
|
2017-01-11T21:52:22.000Z
|
2022-03-25T06:43:52.000Z
|
// This is the client side code that does the key generation
#include "fss-client.h"
void initializeClient(Fss* f, uint32_t numBits, uint32_t numParties) {
#ifndef AESNI
// check if there is aes-ni instruction
uint32_t eax, ebx, ecx, edx;
eax = ebx = ecx = edx = 0;
__get_cpuid(1, &eax, &ebx, &ecx, &edx);
#endif
f->numBits = numBits;
// Initialize keys for Matyas–Meyer–Oseas one-way compression function
f->aes_keys = (AES_KEY*) malloc(sizeof(AES_KEY)*initPRFLen);
for (int i = 0; i < initPRFLen; i++) {
unsigned char rand_bytes[16];
if (!RAND_bytes(rand_bytes, 16)) {
printf("Random bytes failed.\n");
}
#ifndef AESNI
if ((ecx & bit_AES) > 0) {
aesni_set_encrypt_key(rand_bytes, 128, &(f->aes_keys[i]));
} else {
AES_set_encrypt_key(rand_bytes, 128, &(f->aes_keys[i]));
}
#else
aesni_set_encrypt_key(rand_bytes, 128, &(f->aes_keys[i]));
#endif
}
f->numParties = numParties;
// We need prime for the point funciton of FSS, but the new point function FSS does not need this
mpz_class p;
mpz_ui_pow_ui(p.get_mpz_t(), 2, 32);
mpz_nextprime(f->prime.get_mpz_t(), p.get_mpz_t());
f->numKeys = initPRFLen;
}
// Generate keys for 2 party equality FSS
void generateTreeEq(Fss* f, ServerKeyEq* k0, ServerKeyEq* k1, uint64_t a_i, uint64_t b_i){
uint32_t n = f->numBits;
// set bits in keys and allocate memory
k0->cw[0] = (CWEq*) malloc(sizeof(CWEq) * (n-1));
k0->cw[1] = (CWEq*) malloc(sizeof(CWEq) * (n-1));
k1->cw[0] = (CWEq*) malloc(sizeof(CWEq) * (n-1));
k1->cw[1] = (CWEq*) malloc(sizeof(CWEq) * (n-1));
// Figure out first relevant bit
// n represents the number of LSB to compare
int a = getBit(a_i, (64-n+1));
int na = a ^ 1;
// create arrays size (AES_key_size*2 + 2)
unsigned char s0[32];
unsigned char s1[32];
int aStart = 16 * a;
int naStart = 16 *na;
// Set initial seeds for PRF
if(!RAND_bytes((unsigned char*) (s0 + aStart), 16)) {
printf("Random bytes failed\n");
exit(1);
}
if (!RAND_bytes((unsigned char*) (s1 + aStart), 16)) {
printf("Random bytes failed\n");
exit(1);
}
if (!RAND_bytes((unsigned char*) (s0 + naStart), 16)) {
printf("Random bytes failed\n");
exit(1);
}
memcpy((unsigned char*)(s1 + naStart), (unsigned char*)(s0 + naStart), 16);
unsigned char t0[2];
unsigned char t1[2];
unsigned char temp[2];
if (!RAND_bytes((unsigned char*) temp, 2)) {
printf("Random bytes failed\n");
exit(1);
}
// Figure out initial ts
// Make sure t0a and t1a are different
t0[a] = temp[0] % 2;
t1[a] = (t0[a] + 1) % 2;
// Make sure t0na = t1na
t0[na] = temp[1] % 2;
t1[na] = t0[na];
memcpy(k0->s[0], s0, 16);
memcpy(k0->s[1], (unsigned char*)(s0 + 16), 16);
memcpy(k1->s[0], s1, 16);
memcpy(k1->s[1], (unsigned char*) (s1 + 16), 16);
k0->t[0] = t0[0];
k0->t[1] = t0[1];
k1->t[0] = t1[0];
k1->t[1] = t1[1];
// Pick right keys to put into cipher
unsigned char key0[16];
unsigned char key1[16];
memcpy(key0, (unsigned char*) (s0 + aStart), 16);
memcpy(key1, (unsigned char*) (s1 + aStart), 16);
unsigned char tbit0 = t0[a];
unsigned char tbit1 = t1[a];
unsigned char cs0[32];
unsigned char cs1[32];
unsigned char ct0[2];
unsigned char ct1[2];
unsigned char out0[48];
unsigned char out1[48];
for (uint32_t i = 0; i < n; i++) {
f->aes_keys = prf(out0, key0, 48, f->aes_keys, f->numKeys);
f->aes_keys = prf(out1, key1, 48, f->aes_keys, f->numKeys);
memcpy(s0, out0, 32);
memcpy(s1, out1, 32);
t0[0] = out0[32] % 2;
t0[1] = out0[33] % 2;
t1[0] = out1[32] % 2;
t1[1] = out1[33] % 2;
//printf("out0: %d %d\n", out0[32], out0[33]);
// Handle last bit differently, code at the end of the for loop
if (i == n-1) {
break;
}
// Reset a and na bits
a = getBit(a_i, (64-n+i+2));
na = a ^ 1;
// Redefine aStart and naStart based on new a's
aStart = 16 * a;
naStart = 16 * na;
// Create cs and ct for next bit
if (!RAND_bytes((unsigned char*) (cs0 + aStart), 16)) {
printf("Random bytes failed.\n");
exit(1);
}
if (!RAND_bytes((unsigned char*) (cs1 + aStart), 16)) {
printf("Random bytes failed.\n");
exit(1);
}
if (!RAND_bytes((unsigned char*) (cs0 + naStart), 16)) {
printf("Random bytes failed.\n");
exit(1);
}
for (uint32_t j = 0; j < 16; j++) {
cs1[naStart+j] = s0[naStart+j] ^ s1[naStart+j] ^ cs0[naStart+j];
}
if (!RAND_bytes(temp, 2)) {
printf("Random bytes failed.\n");
exit(1);
}
ct0[a] = temp[0] % 2;
ct1[a] = ct0[a] ^ t0[a] ^ t1[a] ^ 1;
ct0[na] = temp[1] % 2;
ct1[na] = ct0[na] ^ t0[na] ^ t1[na];
//printf("ct0: %d %d, ct1: %d %d, t0: %d %d, t1: %d %d\n", ct0[0], ct0[1], ct1[0], ct1[1], t0[0], t0[1], t1[0], t1[1]);
//printf("t0: %d %d, t1: %d %d\n", t0[0], t0[1], t1[0], t1[1]);
// Copy appropriate values into key
memcpy(k0->cw[0][i].cs[0], cs0, 16);
memcpy(k0->cw[0][i].cs[1], (unsigned char*) (cs0 + 16), 16);
k0->cw[0][i].ct[0] = ct0[0];
k0->cw[0][i].ct[1] = ct0[1];
memcpy(k0->cw[1][i].cs[0], cs1, 16);
memcpy(k0->cw[1][i].cs[1], (unsigned char*) (cs1 + 16), 16);
k0->cw[1][i].ct[0] = ct1[0];
k0->cw[1][i].ct[1] = ct1[1];
memcpy(k1->cw[0][i].cs[0], cs0, 16);
memcpy(k1->cw[0][i].cs[1], (unsigned char*) (cs0 + 16), 16);
k1->cw[0][i].ct[0] = ct0[0];
k1->cw[0][i].ct[1] = ct0[1];
memcpy(k1->cw[1][i].cs[0], cs1, 16);
memcpy(k1->cw[1][i].cs[1], (unsigned char*) (cs1 + 16), 16);
k1->cw[1][i].ct[0] = ct1[0];
k1->cw[1][i].ct[1] = ct1[1];
unsigned char* cs;
unsigned char* ct;
if (tbit0 == 1) {
cs = cs1;
ct = ct1;
} else {
cs = cs0;
ct = ct0;
}
for (uint32_t j = 0; j < 16; j++) {
key0[j] = s0[aStart+j] ^ cs[aStart+j];
}
tbit0 = t0[a] ^ ct[a];
if (tbit1 == 1) {
cs = cs1;
ct = ct1;
} else {
cs = cs0;
ct = ct0;
}
for (uint32_t j = 0; j < 16; j++) {
key1[j] = s1[aStart+j] ^ cs[aStart+j];
}
tbit1 = t1[a] ^ ct[a];
}
// Set the w in the keys
unsigned char intArray0[34];
unsigned char intArray1[34];
memcpy(intArray0, s0, 32);
intArray0[32] = t0[0];
intArray0[33] = t0[1];
memcpy(intArray1, s1, 32);
intArray1[32] = t1[0];
intArray1[33] = t1[1];
mpz_class sInt0, sInt1;
mpz_import(sInt0.get_mpz_t(), 34, 1, sizeof(intArray0[0]), 0, 0, intArray0);
mpz_import(sInt1.get_mpz_t(), 34, 1, sizeof(intArray1[0]), 0, 0, intArray1);
if (sInt0 != sInt1) {
mpz_class diff = sInt0 - sInt1;
mpz_invert(diff.get_mpz_t(), diff.get_mpz_t(), f->prime.get_mpz_t());
mpz_class temp_b;
mpz_import(temp_b.get_mpz_t(), 1, -1, sizeof (uint64_t), 0, 0, &b_i);
k0->w = (diff * temp_b) % f->prime;
k1->w = k0->w;
} else {
k0->w = 0;
k1->w = 0;
}
}
// Generate keys for 2 party less than FSS
void generateTreeLt(Fss* f, ServerKeyLt* k0, ServerKeyLt* k1, uint64_t a_i, uint64_t b_i){
uint32_t n = f->numBits;
// Set up num_bits and allocate memory
k0->cw[0] = (CWLt*) malloc(sizeof(CWLt) * (n-1));
k0->cw[1] = (CWLt*) malloc(sizeof(CWLt) * (n-1));
k1->cw[0] = (CWLt*) malloc(sizeof(CWLt) * (n-1));
k1->cw[1] = (CWLt*) malloc(sizeof(CWLt) * (n-1));
// Figure out first relevant bit
// n is the number of least significant bits to compare
int a = getBit(a_i, (64-n+1));
int na = a ^ 1;
// create arrays size (AES_key_size*2 + 2)
unsigned char s0[32];
unsigned char s1[32];
int aStart = 16 * a;
int naStart = 16 *na;
// Set initial seeds for PRF
if(!RAND_bytes((unsigned char*) (s0 + aStart), 16)) {
printf("Random bytes failed\n");
exit(1);
}
if (!RAND_bytes((unsigned char*) (s1 + aStart), 16)) {
printf("Random bytes failed\n");
exit(1);
}
if (!RAND_bytes((unsigned char*) (s0 + naStart), 16)) {
printf("Random bytes failed\n");
exit(1);
}
memcpy((unsigned char*)(s1 + naStart), (unsigned char*)(s0 + naStart), 16);
unsigned char t0[2];
unsigned char t1[2];
unsigned char temp[2];
if (!RAND_bytes((unsigned char*) temp, 2)) {
printf("Random bytes failed\n");
exit(1);
}
// Figure out initial ts
// Make sure t0a and t1a are different
t0[a] = temp[0] % 2;
t1[a] = (t0[a] + 1) % 2;
// Make sure t0na = t1na
t0[na] = temp[1] % 2;
t1[na] = t0[na];
// Set initial v's
unsigned char temp_v[8];
if (!RAND_bytes(temp_v, 8)) {
printf("Random bytes failed.\n");
exit(1);
}
k0->v[a] = byteArr2Int64(temp_v);
k1->v[a] = k0->v[a];
if (!RAND_bytes(temp_v, 8)) {
printf("Random bytes failed.\n");
exit(1);
}
k0->v[na] = byteArr2Int64(temp_v);
k1->v[na] = k0->v[na] - b_i*a;
memcpy(k0->s[0], s0, 16);
memcpy(k0->s[1], (unsigned char*)(s0 + 16), 16);
memcpy(k1->s[0], s1, 16);
memcpy(k1->s[1], (unsigned char*) (s1 + 16), 16);
k0->t[0] = t0[0];
k0->t[1] = t0[1];
k1->t[0] = t1[0];
k1->t[1] = t1[1];
// Pick right keys to put into cipher
unsigned char key0[16];
unsigned char key1[16];
memcpy(key0, (unsigned char*) (s0 + aStart), 16);
memcpy(key1, (unsigned char*) (s1 + aStart), 16);
unsigned char tbit0 = t0[a];
unsigned char tbit1 = t1[a];
unsigned char cs0[32];
unsigned char cs1[32];
unsigned char ct0[2];
unsigned char ct1[2];
unsigned char out0[64];
unsigned char out1[64];
uint64_t v0[2];
uint64_t v1[2];
uint64_t cv[2][2];
uint64_t v;
for (uint32_t i = 0; i < n-1; i++) {
//printf("s: ");
//printByteArray(key0, 16);
f->aes_keys = prf(out0, key0, 64, f->aes_keys, f->numKeys);
f->aes_keys = prf(out1, key1, 64, f->aes_keys, f->numKeys);
memcpy(s0, out0, 32);
memcpy(s1, out1, 32);
t0[0] = out0[32] % 2;
t0[1] = out0[33] % 2;
t1[0] = out1[32] % 2;
t1[1] = out1[33] % 2;
v0[0] = byteArr2Int64((unsigned char*) (out0 + 40));
v0[1] = byteArr2Int64((unsigned char*) (out0 + 48));
v1[0] = byteArr2Int64((unsigned char*) (out1 + 40));
v1[1] = byteArr2Int64((unsigned char*) (out1 + 48));
//printf("out0: %d %d\n", out0[32], out0[33]);
// Reset a and na bits
a = getBit(a_i, (64-n+i+2));
na = a ^ 1;
// Redefine aStart and naStart based on new a's
aStart = 16 * a;
naStart = 16 * na;
// Create cs and ct for next bit
if (!RAND_bytes((unsigned char*) (cs0 + aStart), 16)) {
printf("Random bytes failed.\n");
exit(1);
}
if (!RAND_bytes((unsigned char*) (cs1 + aStart), 16)) {
printf("Random bytes failed.\n");
exit(1);
}
if (!RAND_bytes((unsigned char*) (cs0 + naStart), 16)) {
printf("Random bytes failed.\n");
exit(1);
}
for (uint32_t j = 0; j < 16; j++) {
cs1[naStart+j] = s0[naStart+j] ^ s1[naStart+j] ^ cs0[naStart+j];
}
if (!RAND_bytes(temp, 2)) {
printf("Random bytes failed.\n");
exit(1);
}
ct0[a] = temp[0] % 2;
ct1[a] = ct0[a] ^ t0[a] ^ t1[a] ^ 1;
ct0[na] = temp[1] % 2;
ct1[na] = ct0[na] ^ t0[na] ^ t1[na];
if (!RAND_bytes(temp_v, 8)) {
printf("Random bytes failed.\n");
exit(1);
}
cv[tbit0][a] = byteArr2Int64(temp_v);
v = (cv[tbit0][a] + v0[a]);
v = (v - v1[a]);
cv[tbit1][a] = v;
if (!RAND_bytes(temp_v, 8)) {
printf("Random bytes failed.\n");
exit(1);
}
cv[tbit0][na] = byteArr2Int64(temp_v);
v = (cv[tbit0][na] + v0[na]);
v = (v - v1[na]);
cv[tbit1][na] = (v - b_i*a);
// Copy appropriate values into key
memcpy(k0->cw[0][i].cs[0], cs0, 16);
memcpy(k0->cw[0][i].cs[1], (unsigned char*) (cs0 + 16), 16);
k0->cw[0][i].ct[0] = ct0[0];
k0->cw[0][i].ct[1] = ct0[1];
memcpy(k0->cw[1][i].cs[0], cs1, 16);
memcpy(k0->cw[1][i].cs[1], (unsigned char*) (cs1 + 16), 16);
k0->cw[1][i].ct[0] = ct1[0];
k0->cw[1][i].ct[1] = ct1[1];
k0->cw[0][i].cv[0] = cv[0][0];
k0->cw[0][i].cv[1] = cv[0][1];
k0->cw[1][i].cv[0] = cv[1][0];
k0->cw[1][i].cv[1] = cv[1][1];
memcpy(k1->cw[0][i].cs[0], cs0, 16);
memcpy(k1->cw[0][i].cs[1], (unsigned char*) (cs0 + 16), 16);
k1->cw[0][i].ct[0] = ct0[0];
k1->cw[0][i].ct[1] = ct0[1];
memcpy(k1->cw[1][i].cs[0], cs1, 16);
memcpy(k1->cw[1][i].cs[1], (unsigned char*) (cs1 + 16), 16);
k1->cw[1][i].ct[0] = ct1[0];
k1->cw[1][i].ct[1] = ct1[1];
k1->cw[0][i].cv[0] = cv[0][0];
k1->cw[0][i].cv[1] = cv[0][1];
k1->cw[1][i].cv[0] = cv[1][0];
k1->cw[1][i].cv[1] = cv[1][1];
unsigned char* cs;
unsigned char* ct;
if (tbit0 == 1) {
cs = cs1;
ct = ct1;
} else {
cs = cs0;
ct = ct0;
}
for (uint32_t j = 0; j < 16; j++) {
key0[j] = s0[aStart+j] ^ cs[aStart+j];
}
tbit0 = t0[a] ^ ct[a];
//printf("After XOR: ");
//printByteArray(key0, 16);
if (tbit1 == 1) {
cs = cs1;
ct = ct1;
} else {
cs = cs0;
ct = ct0;
}
for (uint32_t j = 0; j < 16; j++) {
key1[j] = s1[aStart+j] ^ cs[aStart+j];
}
tbit1 = t1[a] ^ ct[a];
}
}
// This function is for multi-party (3 or more parties) FSS
// for equality functions
// The API interface is similar to the 2 party version.
// One main difference is the output of the evaluation function
// is XOR homomorphic, so for additive queries like SUM and COUNT,
// the client has to add it locally.
void generateTreeEqMParty(Fss* f, uint64_t a, uint64_t b, MPKey* keys) {
uint32_t n = f->numBits;
uint32_t p = f->numParties;
uint32_t m = 4; // Assume messages are 4 bytes long
// store 2^p-1
uint32_t p2 = (uint32_t)(pow(2, p-1));
uint64_t mu = (uint64_t)ceil((pow(2, n/2.0) * pow(2,(p-1)/2.0)));
uint64_t v = (uint64_t)ceil((pow(2,n))/mu);
// sigma is last n/2 bits
uint32_t delta = a & ((1 << (n/2)) - 1);
uint32_t gamma = (a & (((1 << (n+1)/2) - 1) << n/2)) >> n/2;
unsigned char*** aArr = (unsigned char***) malloc(sizeof(unsigned char**)*v);
for (int i = 0; i < v; i++) {
aArr[i] = (unsigned char**) malloc(sizeof(unsigned char*)*p);
for (int j = 0; j < p; j++) {
aArr[i][j] = (unsigned char*) malloc(p2);
}
}
for (int i = 0; i < v; i++) {
for (int j = 0; j < p; j++) {
if (j != (p-1)) {
if(!RAND_bytes((unsigned char*) aArr[i][j], p2)) {
printf("Random bytes failed.\n");
exit(1);
}
for (int k = 0; k < p2; k++) {
aArr[i][j][k] = aArr[i][j][k] % 2;
}
} else {
// Set the last row so that the columns have odd or even number
// of bits
for (int k = 0; k < p2; k++) {
uint32_t curr_bits = 0;
for (int l = 0; l < p-1; l++) {
curr_bits += aArr[i][l][k];
}
curr_bits = curr_bits % 2;
// If array index is not gamma, just make sure the p's sum up to even
if (i != gamma) {
if (curr_bits == 0) {
aArr[i][j][k] = 0;
} else {
aArr[i][j][k] = 1;
}
} else {
// Make sure the array at gamma are odd binaries
if (curr_bits == 0) {
aArr[i][j][k] = 1;
} else {
aArr[i][j][k] = 0;
}
}
}
}
}
}
unsigned char *** s = (unsigned char***) malloc(sizeof(unsigned char**)*v);
for (int i = 0; i < v; i++) {
s[i] = (unsigned char**) malloc(sizeof(unsigned char*)*p2);
for (int j = 0; j < p2; j++) {
s[i][j] = (unsigned char*) malloc(16);
if (!RAND_bytes((unsigned char*)s[i][j], 16)) {
printf("Random bytes failed.\n");
exit(1);
}
}
}
uint32_t m_bytes = m*mu;
uint32_t** cw = (uint32_t**) malloc(sizeof(uint32_t*)*p2);
uint32_t* cw_temp = (uint32_t*) malloc(m_bytes);
memset(cw_temp, 0, m_bytes);
// Create cws
for (int i = 0; i < p2; i++) {
unsigned char* temp_out = (unsigned char*) malloc(m_bytes);
f->aes_keys = prf(temp_out, s[gamma][i], m_bytes, f->aes_keys, f->numKeys);
f->numKeys = m_bytes/16;
for (int k = 0; k < mu; k++) {
unsigned char tempIntBytes[4];
memcpy(tempIntBytes, &temp_out[4*k], 4);
cw_temp[k] = cw_temp[k] ^ byteArr2Int32(tempIntBytes);
}
cw[i] = (uint32_t*) malloc(m_bytes);
// The last CW has to fulfill a certain condition
// So we deal with it separately
if (i == (p2-1)) {
break;
}
if (!RAND_bytes((unsigned char*) cw[i], m_bytes)) {
printf("Random bytes failed.\n");
exit(1);
}
for (int j = 0; j < mu; j++) {
cw_temp[j] = cw_temp[j] ^ cw[i][j];
}
free(temp_out);
}
for (int i = 0; i < mu; i++) {
if (i == (delta)) {
cw[p2-1][i] = b ^ cw_temp[i];
} else {
cw[p2-1][i] = cw_temp[i];
}
}
free(cw_temp);
unsigned char *** sigma = (unsigned char***) malloc(sizeof(unsigned char**)* p);
for (int i = 0; i < p; i++) {
sigma[i] = (unsigned char**) malloc(sizeof(unsigned char*)*v);
for (int j = 0; j < v; j++) {
sigma[i][j] = (unsigned char*) malloc(16*p2);
for (int k = 0; k < p2; k++) {
// If the a array has a 0 bit, then set the seed to 0
if (aArr[j][i][k] == 0) {
memset(sigma[i][j] + k*16, 0, 16);
} else {
memcpy(sigma[i][j] + k*16, s[j][k], 16);
}
}
}
}
for (int i = 0; i < p; i++) {
keys[i].sigma = sigma[i];
keys[i].cw = cw;
}
// Clean up unused memory
for (int i = 0; i < v; i++) {
for (int j = 0; j < p; j++) {
free(aArr[i][j]);
}
free(aArr[i]);
}
free(aArr);
for (int i = 0; i < v; i++) {
for (int j = 0; j < p2; j++) {
free(s[i][j]);
}
free(s[i]);
}
free(s);
}
| 30.714065
| 127
| 0.47192
|
uishi
|
42a21e4500f132edf473c7072a27ccbae9030b3c
| 3,318
|
cpp
|
C++
|
Skybox.cpp
|
raulgonzalezupc/FirstAssigment
|
9193de31049922787da966695340253d84439bf3
|
[
"MIT"
] | null | null | null |
Skybox.cpp
|
raulgonzalezupc/FirstAssigment
|
9193de31049922787da966695340253d84439bf3
|
[
"MIT"
] | null | null | null |
Skybox.cpp
|
raulgonzalezupc/FirstAssigment
|
9193de31049922787da966695340253d84439bf3
|
[
"MIT"
] | null | null | null |
#include "Skybox.h"
#include "GL/glew.h"
#include "Application.h"
#include "ModuleTexture.h"
#include "ModuleProgram.h"
#include "ModuleCamera.h"
#include "ModuleRender.h"
#include "Components/Camera.h"
#include "MathGeoLib/include/Math/float4.h"
Skybox::Skybox()
{
directory = "../Textures/Skybox/";
std::vector<std::string> faces
{
"right.jpg",
"left.jpg",
"top.jpg",
"bottom.jpg",
"front.jpg",
"back.jpg"
};
//Load default Skybox
cubemapTexture = LoadCubeMap(faces);
float skyboxVertices[] = {
// positions
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, 1.0f
};
glGenVertexArrays(1, &skyboxVAO);
glGenBuffers(1, &skyboxVBO);
glBindVertexArray(skyboxVAO);
glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), &skyboxVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
}
Skybox::~Skybox()
{
glDeleteVertexArrays(1, &skyboxVAO);
glDeleteBuffers(1, &skyboxVBO);
glDeleteTextures(1, &cubemapTexture);
}
unsigned int Skybox::LoadCubeMap(const std::vector<std::string> &faces)
{
unsigned int textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
for (unsigned int i = 0; i < faces.size(); i++)
{
App->texture->LoadSkybox(faces[i].c_str(), directory, i);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
return textureID;
}
void Skybox::DrawSkybox() const
{
// glDepthFunc(GL_LEQUAL);
// unsigned int skyboxProg = App->program->skyboxProgram;
// glUseProgram(skyboxProg);
//
// // ... set view and projection matrix
// glUniformMatrix4fv(glGetUniformLocation(skyboxProg,
// "projection"), 1, GL_TRUE, &(App->renderer->cam->proj[0][0]));
//
// float4x4 view = App->renderer->cam->view;
// view.SetRow(3, float4::zero);
// view.SetCol(3, float4::zero);
//
// glUniformMatrix4fv(glGetUniformLocation(skyboxProg,
// "view"), 1, GL_TRUE, &view[0][0]);
//
// glBindVertexArray(skyboxVAO);
// glActiveTexture(GL_TEXTURE0);
// glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
// glDrawArrays(GL_TRIANGLES, 0, 36);
// glBindVertexArray(0);
//
// glDepthFunc(GL_LESS);
// glUseProgram(0);
}
| 24.218978
| 88
| 0.645871
|
raulgonzalezupc
|
42a3a8a9ff3ce21aa6af54a36b207008d72efe49
| 1,855
|
cpp
|
C++
|
cgi/vendor/tyco/tycocgi.cpp
|
harryoh/api-gateway
|
9576d499c35fbf8d8304f470e825acaa7d9a4674
|
[
"MIT"
] | null | null | null |
cgi/vendor/tyco/tycocgi.cpp
|
harryoh/api-gateway
|
9576d499c35fbf8d8304f470e825acaa7d9a4674
|
[
"MIT"
] | null | null | null |
cgi/vendor/tyco/tycocgi.cpp
|
harryoh/api-gateway
|
9576d499c35fbf8d8304f470e825acaa7d9a4674
|
[
"MIT"
] | null | null | null |
///////////////////////////////////////////////////////////////////////////////
/// @file tycocgi.cpp
/// @~english
/// @brief Implementation of the TycoCGI class
/// @~
/// @authors Harry Oh (harry.oh@udptechnology.com)
/// @copyright UDP Technology
///////////////////////////////////////////////////////////////////////////////
#include <iostream> // NOLINT(readability/streams)
#include <string>
#include <cassert>
#include "udp/keystone/system/types.h"
#include "tycoerror.hpp"
#include "tycocgi.hpp"
///////////////////////////////////////////////////////////////////////////////
namespace udp {
namespace cgi {
///////////////////////////////////////////////////////////////////////////////
/**
* Private implementation of the TycoCGI API
*/
class TycoCGI::TycoCGIImpl {
public: /* Constructors */
TycoCGIImpl() {}
~TycoCGIImpl() {}
public: /* Public member functions */
/**
* Implemente check querystring is validated.
* @param entrylist parameter entry list
*/
void CheckParameter(const EntryList &entrylist) const {
// Check Common validation.
// throw TycoError(kCodeMissingParameter, "action");
}
};
///////////////////////////////////////////////////////////////////////////////
TycoCGI::TycoCGI() : pimpl_(new TycoCGIImpl()) {}
///////////////////////////////////////////////////////////////////////////////
TycoCGI::~TycoCGI() {}
///////////////////////////////////////////////////////////////////////////////
TycoCGI::TycoCGI(const std::string &querystring)
: CGIBase(querystring), pimpl_(new TycoCGIImpl()) {}
///////////////////////////////////////////////////////////////////////////////
void TycoCGI::CheckParameter() const {
assert(pimpl_.get());
EntryList entrylist = GetValues();
return pimpl_->CheckParameter(entrylist);
}
} // namespace cgi
} // namespace udp
| 29.919355
| 79
| 0.447978
|
harryoh
|
42a4bd0dee99304f63ef921c522d9a81b5b7633f
| 916
|
hpp
|
C++
|
include/lug/System/Logger/Common.hpp
|
Lugdunum3D/Lugdunum3D
|
b6d6907d034fdba1ffc278b96598eba1d860f0d4
|
[
"MIT"
] | 275
|
2016-10-08T15:33:17.000Z
|
2022-03-30T06:11:56.000Z
|
include/lug/System/Logger/Common.hpp
|
Lugdunum3D/Lugdunum3D
|
b6d6907d034fdba1ffc278b96598eba1d860f0d4
|
[
"MIT"
] | 24
|
2016-09-29T20:51:20.000Z
|
2018-05-09T21:41:36.000Z
|
include/lug/System/Logger/Common.hpp
|
Lugdunum3D/Lugdunum3D
|
b6d6907d034fdba1ffc278b96598eba1d860f0d4
|
[
"MIT"
] | 37
|
2017-02-25T05:03:48.000Z
|
2021-05-10T19:06:29.000Z
|
#pragma once
#include <lug/System/Export.hpp>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#define FMT_HEADER_ONLY
#if defined(False)
#undef False
#include <fmt/format.h>
#include <fmt/ostream.h>
#define False 0
#else
#include <fmt/format.h>
#include <fmt/ostream.h>
#endif
#define LUG_LOG_LEVELS(PROCESS) \
PROCESS(Debug) \
PROCESS(Info) \
PROCESS(Warning) \
PROCESS(Error) \
PROCESS(Fatal) \
PROCESS(Assert) \
PROCESS(Off) \
namespace lug {
namespace System {
namespace Logger {
#define LUG_LOG_ENUM(CHANNEL) CHANNEL,
enum class Level : uint8_t {
LUG_LOG_LEVELS(LUG_LOG_ENUM)
};
#undef LUG_LOG_ENUM
LUG_SYSTEM_API std::ostream& operator<<(std::ostream& os, Level level);
} // Logger
} // System
} // lug
| 20.355556
| 71
| 0.593886
|
Lugdunum3D
|
42a5d6917ac74dd6520db6f7e25845c50ed81397
| 3,096
|
cpp
|
C++
|
modules/task_1/ikromov_i_sum_col/main.cpp
|
LioBuitrago/pp_2020_autumn_informatics
|
1ecc1b5dae978295778176ff11ffe42bedbc602e
|
[
"BSD-3-Clause"
] | null | null | null |
modules/task_1/ikromov_i_sum_col/main.cpp
|
LioBuitrago/pp_2020_autumn_informatics
|
1ecc1b5dae978295778176ff11ffe42bedbc602e
|
[
"BSD-3-Clause"
] | 1
|
2021-02-13T03:00:05.000Z
|
2021-02-13T03:00:05.000Z
|
modules/task_1/ikromov_i_sum_col/main.cpp
|
LioBuitrago/pp_2020_autumn_informatics
|
1ecc1b5dae978295778176ff11ffe42bedbc602e
|
[
"BSD-3-Clause"
] | 1
|
2020-10-11T09:11:57.000Z
|
2020-10-11T09:11:57.000Z
|
// Copyright 2020 Ikromov Inom
#include <mpi.h>
#include <gtest-mpi-listener.hpp>
#include <gtest/gtest.h>
#include <vector>
#include "./sum_col.h"
using std::vector;
TEST(Sum_Col_MPI, Square_Matrix) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
vector<vector<int>> global_mat;
const int rows = 5;
const int cols = rows;
if (rank == 0) {
global_mat = getRandomMatrix(rows, cols);
}
vector<int> global_sum = summColumns(global_mat);
if (rank == 0) {
vector<int> reference_sum = summColumnsOneProc(global_mat);
ASSERT_EQ(reference_sum, global_sum);
}
}
TEST(Sum_Col_Multi_Process_MPI, One_Row) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
vector<vector<int>> global_mat;
const int rows = 1, cols = 9;
if (rank == 0) {
global_mat = getRandomMatrix(rows, cols);
}
vector<int> global_sum = summColumns(global_mat);
if (rank == 0) {
vector<int> reference_sum = summColumnsOneProc(global_mat);
ASSERT_EQ(reference_sum, global_sum);
}
}
TEST(Sum_Col_Multi_Process_MPI, One_Column) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
vector<vector<int>> global_mat;
const int rows = 9, cols = 1;
if (rank == 0) {
global_mat = getRandomMatrix(rows, cols);
}
vector<int> global_sum = summColumns(global_mat);
if (rank == 0) {
vector<int> reference_sum = summColumnsOneProc(global_mat);
ASSERT_EQ(reference_sum, global_sum);
}
}
TEST(Sum_Col_Multi_Process_MPI, Rectangle_Matrix) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
vector<vector<int>> global_mat;
const int rows = 9, cols = 5;
if (rank == 0) {
global_mat = getRandomMatrix(rows, cols);
}
vector<int> global_sum = summColumns(global_mat);
if (rank == 0) {
vector<int> reference_sum = summColumnsOneProc(global_mat);
ASSERT_EQ(reference_sum, global_sum);
}
}
TEST(Sum_Col_Multi_Process_MPI, Triangle_Matrix) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
vector<vector<int>> global_mat;
const int rows = 9;
const int cols = rows;
if (rank == 0) {
global_mat = getRandomMatrix(rows, cols);
for (int i = 0; i < rows; ++i) {
for (int j = i + 1; j < cols; ++j) {
global_mat[i][j] = 0;
}
}
}
vector<int> global_sum = summColumns(global_mat);
if (rank == 0) {
vector<int> reference_sum = summColumnsOneProc(global_mat);
ASSERT_EQ(reference_sum, global_sum);
}
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment);
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Release(listeners.default_result_printer());
listeners.Release(listeners.default_xml_generator());
listeners.Append(new GTestMPIListener::MPIMinimalistPrinter);
return RUN_ALL_TESTS();
}
| 28.145455
| 78
| 0.643734
|
LioBuitrago
|
42a73b04f67b3f76d89b3f4d33a19480eb579500
| 2,506
|
cpp
|
C++
|
frameworks/lua/interfaces/dmzLuaModule.cpp
|
tongli/dmz
|
f2242027a17ea804259f9412b07d69f719a527c5
|
[
"MIT"
] | 1
|
2016-05-08T22:02:35.000Z
|
2016-05-08T22:02:35.000Z
|
frameworks/lua/interfaces/dmzLuaModule.cpp
|
tongli/dmz
|
f2242027a17ea804259f9412b07d69f719a527c5
|
[
"MIT"
] | null | null | null |
frameworks/lua/interfaces/dmzLuaModule.cpp
|
tongli/dmz
|
f2242027a17ea804259f9412b07d69f719a527c5
|
[
"MIT"
] | null | null | null |
/*!
\defgroup Lua DMZ Lua Framework
\brief The Lua Framework provides Lua bindings for the DMZ Kernel and various
frameworks. More information about Lua may be found here: http://www.lua.org/ \n\n
\htmlonly
The DMZ Lua binding documentation is available <a href="dmzlua.html">here</a>.
\endhtmlonly
\class dmz::LuaModule
\ingroup Lua
\brief Lua module interface.
\fn dmz::LuaModule *dmz::LuaModule::cast (
const Plugin *PluginPtr,
const String &PluginName)
\brief Casts Plugin pointer to an LuaModule.
\details If the Plugin object implements the LuaModule interface, a pointer to
the LuaModule interface of the Plugin is returned.
\param[in] PluginPtr Pointer to the Plugin to cast.
\param[in] PluginName String containing the name of the desired LuaModule.
\return Returns pointer to the LuaModule. Returns NULL if the PluginPtr does not
implement the LuaModule interface or the \a PluginName is not empty
and not equal to the Plugin's name.
\fn dmz::LuaModule::LuaModule (const PluginInfo &Info)
\brief Constructor.
\fn dmz::LuaModule::~LuaModule ()
\brief Destructor.
\fn void dmz::LuaModule::register_lua_observer (
const UInt32 CallbackMask,
LuaObserver &observer)
\brief Registers a LuaObserver.
\details If the observer has already been registered the \a CallbackMask is OR'd with
the previously stored \a CallbackMask.
\param[in] CallbackMask A bit mask indicating which observer callbacks to activate.
\param[in] observer LuaObserver to register.
\sa dmzLuaObserver.h
\fn void dmz::LuaModule::release_lua_observer (
const UInt32 CallbackMask,
LuaObserver &observer)
\brief Releases a LuaObserver.
\details Only the callbacks specified by \a CallbackMask will be released. To release
all callback use dmz::LuaAllCallbacksMask.
\param[in] CallbackMask A bit mask indicating which observer callbacks to deactivate.
\param[in] observer LuaObserver to release.
\sa dmzLuaObserver.h
\fn dmz::Boolean dmz::LuaModule::reset_lua ()
\brief Resets the Lua runtime.
\return Returns dmz::True if the Lua runtime was successfully restarted.
\note Restarting the Lua runtime will cause all currently loaded Lua scripts to be
released from disk.
\fn void dmz::LuaModule::set_hook_count (const Int32 Count)
\brief Sets the hook count.
\param[in] Count Specifies the number of Lua instructions to process between hook count
callbacks.
\fn dmz::Int32 dmz::LuaModule::get_hook_count ()
\brief Gets the hook count.
\return Returns the number of Lua instructions executed between hook count callbacks.
*/
| 36.318841
| 87
| 0.791301
|
tongli
|
42aa8898cf467083bd4fef7030feac520c5c1450
| 472
|
cpp
|
C++
|
Beginning C++17 From Novice to Professional/Source/04_Making_Decisions/06_Using_the_conditional_operator_to_select_output.cpp
|
devgunho/Cpp_AtoZ
|
4d87f22671a4eab06ca35b32c9b7f8f9abadb2bc
|
[
"MIT"
] | 1
|
2022-03-25T06:11:06.000Z
|
2022-03-25T06:11:06.000Z
|
Beginning C++17 From Novice to Professional/Source/04_Making_Decisions/06_Using_the_conditional_operator_to_select_output.cpp
|
devgunho/Cpp_AtoZ
|
4d87f22671a4eab06ca35b32c9b7f8f9abadb2bc
|
[
"MIT"
] | null | null | null |
Beginning C++17 From Novice to Professional/Source/04_Making_Decisions/06_Using_the_conditional_operator_to_select_output.cpp
|
devgunho/Cpp_AtoZ
|
4d87f22671a4eab06ca35b32c9b7f8f9abadb2bc
|
[
"MIT"
] | null | null | null |
// Using the conditional operator to select output.
#include <iostream>
int main() {
int mice{}; // Count of all mice
int brown{}; // Count of brown mice
int white{}; // Count of white mice
std::cout << "How many brown mice do you have? ";
std::cin >> brown;
std::cout << "How many white mice do you have? ";
std::cin >> white;
mice = brown + white;
std::cout << "You have " << mice
<< (mice == 1 ? " mouse" : " mice")
<< " in total." << std::endl;
}
| 23.6
| 51
| 0.588983
|
devgunho
|
42abb56726c9da5007d92c80dc1b17b987cd95a4
| 944
|
hpp
|
C++
|
traffic/incastGenerator.hpp
|
rajkiranjoshi/syndb-sim
|
4be3e637d94bfd988869757f883cdb16170647df
|
[
"Apache-2.0"
] | 9
|
2021-04-12T17:11:31.000Z
|
2022-03-03T04:05:09.000Z
|
traffic/incastGenerator.hpp
|
ghghliu/syndb-sim
|
4be3e637d94bfd988869757f883cdb16170647df
|
[
"Apache-2.0"
] | 1
|
2021-04-19T07:03:06.000Z
|
2021-04-21T09:52:28.000Z
|
traffic/incastGenerator.hpp
|
ghghliu/syndb-sim
|
4be3e637d94bfd988869757f883cdb16170647df
|
[
"Apache-2.0"
] | 1
|
2021-04-19T06:36:19.000Z
|
2021-04-19T06:36:19.000Z
|
#ifndef INCASTGENERATOR_H
#define INCASTGENERATOR_H
#include <memory>
#include <functional>
#include <list>
#include <set>
#include "utils/types.hpp"
struct incastScheduleInfo{
sim_time_t time;
host_id_t targetHostId;
std::set<host_id_t> sourceHosts;
void printScheduleInfo();
};
typedef std::shared_ptr<incastScheduleInfo> incastScheduleInfo_p;
struct IncastGenerator
{
std::list<incastScheduleInfo_p> incastSchedule;
const sim_time_t initialDelay = 10000; // 10us - for both topologies
sim_time_t totalIncasts;
sim_time_t nextIncastTime;
incastScheduleInfo_p nextIncast;
IncastGenerator();
void generateIncast();
void updateNextIncast();
void printIncastSchedule();
};
struct IncastGeneratorSimpleTopo: IncastGenerator
{
IncastGeneratorSimpleTopo();
};
struct IncastGeneratorFatTreeTopo : IncastGenerator
{
IncastGeneratorFatTreeTopo();
};
#endif
| 17.811321
| 72
| 0.738347
|
rajkiranjoshi
|
42aff4b8a7bf034c952b35fb276cce49756c4196
| 20,741
|
hpp
|
C++
|
visualization/include/pcl/visualization/impl/point_cloud_handlers.hpp
|
zhangxaochen/CuFusion
|
e8bab7a366b1f2c85a80b95093d195d9f0774c11
|
[
"MIT"
] | 52
|
2017-09-05T13:31:44.000Z
|
2022-03-14T08:48:29.000Z
|
visualization/include/pcl/visualization/impl/point_cloud_handlers.hpp
|
GucciPrada/CuFusion
|
522920bcf316d1ddf9732fc71fa457174168d2fb
|
[
"MIT"
] | 4
|
2018-05-17T22:45:35.000Z
|
2020-02-01T21:46:42.000Z
|
visualization/include/pcl/visualization/impl/point_cloud_handlers.hpp
|
GucciPrada/CuFusion
|
522920bcf316d1ddf9732fc71fa457174168d2fb
|
[
"MIT"
] | 21
|
2015-07-27T13:00:36.000Z
|
2022-01-17T08:18:41.000Z
|
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id: point_cloud_handlers.hpp 6731 2012-08-07 06:16:51Z rusu $
*
*/
#include <pcl/console/time.h>
#include <pcl/pcl_macros.h>
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::visualization::PointCloudColorHandlerCustom<PointT>::getColor (vtkSmartPointer<vtkDataArray> &scalars) const
{
if (!capable_)
return;
if (!scalars)
scalars = vtkSmartPointer<vtkUnsignedCharArray>::New ();
scalars->SetNumberOfComponents (3);
vtkIdType nr_points = cloud_->points.size ();
reinterpret_cast<vtkUnsignedCharArray*>(&(*scalars))->SetNumberOfTuples (nr_points);
// Get a random color
unsigned char* colors = new unsigned char[nr_points * 3];
// Color every point
for (vtkIdType cp = 0; cp < nr_points; ++cp)
{
colors[cp * 3 + 0] = static_cast<unsigned char> (r_);
colors[cp * 3 + 1] = static_cast<unsigned char> (g_);
colors[cp * 3 + 2] = static_cast<unsigned char> (b_);
}
reinterpret_cast<vtkUnsignedCharArray*>(&(*scalars))->SetArray (colors, 3 * nr_points, 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::visualization::PointCloudColorHandlerRandom<PointT>::getColor (vtkSmartPointer<vtkDataArray> &scalars) const
{
if (!capable_)
return;
if (!scalars)
scalars = vtkSmartPointer<vtkUnsignedCharArray>::New ();
scalars->SetNumberOfComponents (3);
vtkIdType nr_points = cloud_->points.size ();
reinterpret_cast<vtkUnsignedCharArray*>(&(*scalars))->SetNumberOfTuples (nr_points);
// Get a random color
unsigned char* colors = new unsigned char[nr_points * 3];
double r, g, b;
pcl::visualization::getRandomColors (r, g, b);
int r_ = static_cast<int> (pcl_lrint (r * 255.0)),
g_ = static_cast<int> (pcl_lrint (g * 255.0)),
b_ = static_cast<int> (pcl_lrint (b * 255.0));
// Color every point
for (vtkIdType cp = 0; cp < nr_points; ++cp)
{
colors[cp * 3 + 0] = static_cast<unsigned char> (r_);
colors[cp * 3 + 1] = static_cast<unsigned char> (g_);
colors[cp * 3 + 2] = static_cast<unsigned char> (b_);
}
reinterpret_cast<vtkUnsignedCharArray*>(&(*scalars))->SetArray (colors, 3 * nr_points, 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::visualization::PointCloudColorHandlerRGBField<PointT>::PointCloudColorHandlerRGBField (const PointCloudConstPtr &cloud) :
pcl::visualization::PointCloudColorHandler<PointT>::PointCloudColorHandler (cloud)
{
// Handle the 24-bit packed RGB values
field_idx_ = pcl::getFieldIndex (*cloud, "rgb", fields_);
if (field_idx_ != -1)
{
capable_ = true;
return;
}
else
{
field_idx_ = pcl::getFieldIndex (*cloud, "rgba", fields_);
if (field_idx_ != -1)
capable_ = true;
else
capable_ = false;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::visualization::PointCloudColorHandlerRGBField<PointT>::getColor (vtkSmartPointer<vtkDataArray> &scalars) const
{
if (!capable_)
return;
if (!scalars)
scalars = vtkSmartPointer<vtkUnsignedCharArray>::New ();
scalars->SetNumberOfComponents (3);
vtkIdType nr_points = cloud_->points.size ();
reinterpret_cast<vtkUnsignedCharArray*>(&(*scalars))->SetNumberOfTuples (nr_points);
unsigned char* colors = reinterpret_cast<vtkUnsignedCharArray*>(&(*scalars))->GetPointer (0);
int j = 0;
// If XYZ present, check if the points are invalid
int x_idx = -1;
for (size_t d = 0; d < fields_.size (); ++d)
if (fields_[d].name == "x")
x_idx = static_cast<int> (d);
if (x_idx != -1)
{
// Color every point
for (vtkIdType cp = 0; cp < nr_points; ++cp)
{
// Copy the value at the specified field
if (!pcl_isfinite (cloud_->points[cp].x) ||
!pcl_isfinite (cloud_->points[cp].y) ||
!pcl_isfinite (cloud_->points[cp].z))
continue;
int idx = j * 3;
colors[idx ] = cloud_->points[cp].r;
colors[idx + 1] = cloud_->points[cp].g;
colors[idx + 2] = cloud_->points[cp].b;
j++;
}
}
else
{
// Color every point
for (vtkIdType cp = 0; cp < nr_points; ++cp)
{
int idx = static_cast<int> (cp) * 3;
colors[idx ] = cloud_->points[cp].r;
colors[idx + 1] = cloud_->points[cp].g;
colors[idx + 2] = cloud_->points[cp].b;
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::visualization::PointCloudColorHandlerRGBCloud<PointT>::PointCloudColorHandlerRGBCloud(const PointCloudConstPtr& cloud, const RgbCloudConstPtr& colors) :
PointCloudColorHandler<PointT> (cloud), rgb_ (colors)
{
capable_ = true;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::visualization::PointCloudColorHandlerRGBCloud<PointT>::getColor (vtkSmartPointer<vtkDataArray> &scalars) const
{
if (!capable_)
return;
if (!scalars)
scalars = vtkSmartPointer<vtkUnsignedCharArray>::New ();
scalars->SetNumberOfComponents (3);
vtkIdType nr_points = vtkIdType (cloud_->points.size ());
reinterpret_cast<vtkUnsignedCharArray*>(&(*scalars))->SetNumberOfTuples (nr_points);
unsigned char* colors = reinterpret_cast<vtkUnsignedCharArray*>(&(*scalars))->GetPointer (0);
// Color every point
if (nr_points != int (rgb_->points.size ()))
std::fill (colors, colors + nr_points * 3, static_cast<unsigned char> (0xFF));
else
for (vtkIdType cp = 0; cp < nr_points; ++cp)
{
int idx = cp * 3;
colors[idx + 0] = rgb_->points[cp].r;
colors[idx + 1] = rgb_->points[cp].g;
colors[idx + 2] = rgb_->points[cp].b;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::visualization::PointCloudColorHandlerHSVField<PointT>::PointCloudColorHandlerHSVField (const PointCloudConstPtr &cloud) :
pcl::visualization::PointCloudColorHandler<PointT>::PointCloudColorHandler (cloud)
{
// Check for the presence of the "H" field
field_idx_ = pcl::getFieldIndex (*cloud, "h", fields_);
if (field_idx_ == -1)
{
capable_ = false;
return;
}
// Check for the presence of the "S" field
s_field_idx_ = pcl::getFieldIndex (*cloud, "s", fields_);
if (s_field_idx_ == -1)
{
capable_ = false;
return;
}
// Check for the presence of the "V" field
v_field_idx_ = pcl::getFieldIndex (*cloud, "v", fields_);
if (v_field_idx_ == -1)
{
capable_ = false;
return;
}
capable_ = true;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::visualization::PointCloudColorHandlerHSVField<PointT>::getColor (vtkSmartPointer<vtkDataArray> &scalars) const
{
if (!capable_)
return;
if (!scalars)
scalars = vtkSmartPointer<vtkUnsignedCharArray>::New ();
scalars->SetNumberOfComponents (3);
vtkIdType nr_points = cloud_->points.size ();
reinterpret_cast<vtkUnsignedCharArray*>(&(*scalars))->SetNumberOfTuples (nr_points);
unsigned char* colors = reinterpret_cast<vtkUnsignedCharArray*>(&(*scalars))->GetPointer (0);
int j = 0;
// If XYZ present, check if the points are invalid
int x_idx = -1;
for (size_t d = 0; d < fields_.size (); ++d)
if (fields_[d].name == "x")
x_idx = static_cast<int> (d);
if (x_idx != -1)
{
// Color every point
for (vtkIdType cp = 0; cp < nr_points; ++cp)
{
// Copy the value at the specified field
if (!pcl_isfinite (cloud_->points[cp].x) ||
!pcl_isfinite (cloud_->points[cp].y) ||
!pcl_isfinite (cloud_->points[cp].z))
continue;
int idx = j * 3;
///@todo do this with the point_types_conversion in common, first template it!
// Fill color data with HSV here:
if (cloud_->points[cp].s == 0)
{
colors[idx] = colors[idx+1] = colors[idx+2] = cloud_->points[cp].v;
return;
}
float a = cloud_->points[cp].h / 60;
int i = floor (a);
float f = a - i;
float p = cloud_->points[cp].v * (1 - cloud_->points[cp].s);
float q = cloud_->points[cp].v * (1 - cloud_->points[cp].s * f);
float t = cloud_->points[cp].v * (1 - cloud_->points[cp].s * (1 - f));
switch (i)
{
case 0:
colors[idx] = cloud_->points[cp].v; colors[idx+1] = t; colors[idx+2] = p; break;
case 1:
colors[idx] = q; colors[idx+1] = cloud_->points[cp].v; colors[idx+2] = p; break;
case 2:
colors[idx] = p; colors[idx+1] = cloud_->points[cp].v; colors[idx+2] = t; break;
case 3:
colors[idx] = p; colors[idx+1] = q; colors[idx+2] = cloud_->points[cp].v; break;
case 4:
colors[idx] = t; colors[idx+1] = p; colors[idx+2] = cloud_->points[cp].v; break;
default:
colors[idx] = cloud_->points[cp].v; colors[idx+1] = p; colors[idx+2] = q; break;
}
j++;
}
}
else
{
// Color every point
for (vtkIdType cp = 0; cp < nr_points; ++cp)
{
int idx = cp * 3;
// Fill color data with HSV here:
if (cloud_->points[cp].s == 0)
{
colors[idx] = colors[idx+1] = colors[idx+2] = cloud_->points[cp].v;
return;
}
float a = cloud_->points[cp].h / 60;
int i = floor (a);
float f = a - i;
float p = cloud_->points[cp].v * (1 - cloud_->points[cp].s);
float q = cloud_->points[cp].v * (1 - cloud_->points[cp].s * f);
float t = cloud_->points[cp].v * (1 - cloud_->points[cp].s * (1 - f));
switch (i)
{
case 0:
colors[idx] = cloud_->points[cp].v; colors[idx+1] = t; colors[idx+2] = p; break;
case 1:
colors[idx] = q; colors[idx+1] = cloud_->points[cp].v; colors[idx+2] = p; break;
case 2:
colors[idx] = p; colors[idx+1] = cloud_->points[cp].v; colors[idx+2] = t; break;
case 3:
colors[idx] = p; colors[idx+1] = q; colors[idx+2] = cloud_->points[cp].v; break;
case 4:
colors[idx] = t; colors[idx+1] = p; colors[idx+2] = cloud_->points[cp].v; break;
default:
colors[idx] = cloud_->points[cp].v; colors[idx+1] = p; colors[idx+2] = q; break;
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::visualization::PointCloudColorHandlerGenericField<PointT>::PointCloudColorHandlerGenericField (
const PointCloudConstPtr &cloud, const std::string &field_name) :
pcl::visualization::PointCloudColorHandler<PointT>::PointCloudColorHandler (cloud),
field_name_ (field_name)
{
field_idx_ = pcl::getFieldIndex (*cloud, field_name, fields_);
if (field_idx_ != -1)
capable_ = true;
else
capable_ = false;
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::visualization::PointCloudColorHandlerGenericField<PointT>::getColor (vtkSmartPointer<vtkDataArray> &scalars) const
{
if (!capable_)
return;
if (!scalars)
scalars = vtkSmartPointer<vtkFloatArray>::New ();
scalars->SetNumberOfComponents (1);
vtkIdType nr_points = cloud_->points.size ();
reinterpret_cast<vtkFloatArray*>(&(*scalars))->SetNumberOfTuples (nr_points);
typedef typename pcl::traits::fieldList<PointT>::type FieldList;
float* colors = new float[nr_points];
float field_data;
int j = 0;
// If XYZ present, check if the points are invalid
int x_idx = -1;
for (size_t d = 0; d < fields_.size (); ++d)
if (fields_[d].name == "x")
x_idx = static_cast<int> (d);
if (x_idx != -1)
{
// Color every point
for (vtkIdType cp = 0; cp < nr_points; ++cp)
{
// Copy the value at the specified field
if (!pcl_isfinite (cloud_->points[cp].x) || !pcl_isfinite (cloud_->points[cp].y) || !pcl_isfinite (cloud_->points[cp].z))
continue;
const uint8_t* pt_data = reinterpret_cast<const uint8_t*> (&cloud_->points[cp]);
memcpy (&field_data, pt_data + fields_[field_idx_].offset, pcl::getFieldSize (fields_[field_idx_].datatype));
colors[j] = field_data;
j++;
}
}
else
{
// Color every point
for (vtkIdType cp = 0; cp < nr_points; ++cp)
{
const uint8_t* pt_data = reinterpret_cast<const uint8_t*> (&cloud_->points[cp]);
memcpy (&field_data, pt_data + fields_[field_idx_].offset, pcl::getFieldSize (fields_[field_idx_].datatype));
if (!pcl_isfinite (field_data))
continue;
colors[j] = field_data;
j++;
}
}
reinterpret_cast<vtkFloatArray*>(&(*scalars))->SetArray (colors, j, 0);
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::visualization::PointCloudGeometryHandlerXYZ<PointT>::PointCloudGeometryHandlerXYZ (const PointCloudConstPtr &cloud)
: pcl::visualization::PointCloudGeometryHandler<PointT>::PointCloudGeometryHandler (cloud)
{
field_x_idx_ = pcl::getFieldIndex (*cloud, "x", fields_);
if (field_x_idx_ == -1)
return;
field_y_idx_ = pcl::getFieldIndex (*cloud, "y", fields_);
if (field_y_idx_ == -1)
return;
field_z_idx_ = pcl::getFieldIndex (*cloud, "z", fields_);
if (field_z_idx_ == -1)
return;
capable_ = true;
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::visualization::PointCloudGeometryHandlerXYZ<PointT>::getGeometry (vtkSmartPointer<vtkPoints> &points) const
{
if (!capable_)
return;
if (!points)
points = vtkSmartPointer<vtkPoints>::New ();
points->SetDataTypeToFloat ();
vtkSmartPointer<vtkFloatArray> data = vtkSmartPointer<vtkFloatArray>::New ();
data->SetNumberOfComponents (3);
vtkIdType nr_points = cloud_->points.size ();
// Add all points
vtkIdType j = 0; // true point index
float* pts = static_cast<float*> (malloc (nr_points * 3 * sizeof (float)));
// If the dataset has no invalid values, just copy all of them
if (cloud_->is_dense)
{
for (vtkIdType i = 0; i < nr_points; ++i)
{
pts[i * 3 + 0] = cloud_->points[i].x;
pts[i * 3 + 1] = cloud_->points[i].y;
pts[i * 3 + 2] = cloud_->points[i].z;
}
data->SetArray (&pts[0], nr_points * 3, 0);
points->SetData (data);
}
// Need to check for NaNs, Infs, ec
else
{
for (vtkIdType i = 0; i < nr_points; ++i)
{
// Check if the point is invalid
if (!pcl_isfinite (cloud_->points[i].x) || !pcl_isfinite (cloud_->points[i].y) || !pcl_isfinite (cloud_->points[i].z))
continue;
pts[j * 3 + 0] = cloud_->points[i].x;
pts[j * 3 + 1] = cloud_->points[i].y;
pts[j * 3 + 2] = cloud_->points[i].z;
// Set j and increment
j++;
}
data->SetArray (&pts[0], j * 3, 0);
points->SetData (data);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::visualization::PointCloudGeometryHandlerSurfaceNormal<PointT>::PointCloudGeometryHandlerSurfaceNormal (const PointCloudConstPtr &cloud)
: pcl::visualization::PointCloudGeometryHandler<PointT>::PointCloudGeometryHandler (cloud)
{
field_x_idx_ = pcl::getFieldIndex (*cloud, "normal_x", fields_);
if (field_x_idx_ == -1)
return;
field_y_idx_ = pcl::getFieldIndex (*cloud, "normal_y", fields_);
if (field_y_idx_ == -1)
return;
field_z_idx_ = pcl::getFieldIndex (*cloud, "normal_z", fields_);
if (field_z_idx_ == -1)
return;
capable_ = true;
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::visualization::PointCloudGeometryHandlerSurfaceNormal<PointT>::getGeometry (vtkSmartPointer<vtkPoints> &points) const
{
if (!capable_)
return;
if (!points)
points = vtkSmartPointer<vtkPoints>::New ();
points->SetDataTypeToFloat ();
points->SetNumberOfPoints (cloud_->points.size ());
// Add all points
double p[3];
for (vtkIdType i = 0; i < static_cast<vtkIdType> (cloud_->points.size ()); ++i)
{
p[0] = cloud_->points[i].normal[0];
p[1] = cloud_->points[i].normal[1];
p[2] = cloud_->points[i].normal[2];
points->SetPoint (i, p);
}
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::visualization::PointCloudGeometryHandlerCustom<PointT>::PointCloudGeometryHandlerCustom (const PointCloudConstPtr &cloud,
const std::string &x_field_name, const std::string &y_field_name, const std::string &z_field_name) : pcl::visualization::PointCloudGeometryHandler<PointT>::PointCloudGeometryHandler (cloud)
{
field_x_idx_ = pcl::getFieldIndex (*cloud, x_field_name, fields_);
if (field_x_idx_ == -1)
return;
field_y_idx_ = pcl::getFieldIndex (*cloud, y_field_name, fields_);
if (field_y_idx_ == -1)
return;
field_z_idx_ = pcl::getFieldIndex (*cloud, z_field_name, fields_);
if (field_z_idx_ == -1)
return;
field_name_ = x_field_name + y_field_name + z_field_name;
capable_ = true;
}
////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::visualization::PointCloudGeometryHandlerCustom<PointT>::getGeometry (vtkSmartPointer<vtkPoints> &points) const
{
if (!capable_)
return;
if (!points)
points = vtkSmartPointer<vtkPoints>::New ();
points->SetDataTypeToFloat ();
points->SetNumberOfPoints (cloud_->points.size ());
float data;
// Add all points
double p[3];
for (vtkIdType i = 0; i < static_cast<vtkIdType> (cloud_->points.size ()); ++i)
{
// Copy the value at the specified field
const uint8_t* pt_data = reinterpret_cast<const uint8_t*> (&cloud_->points[i]);
memcpy (&data, pt_data + fields_[field_x_idx_].offset, sizeof (float));
p[0] = data;
memcpy (&data, pt_data + fields_[field_y_idx_].offset, sizeof (float));
p[1] = data;
memcpy (&data, pt_data + fields_[field_z_idx_].offset, sizeof (float));
p[2] = data;
points->SetPoint (i, p);
}
}
| 35.454701
| 194
| 0.585218
|
zhangxaochen
|
42b1bb6a6979135c0a96b957443326031ba2027c
| 2,165
|
cpp
|
C++
|
examples/CBuilder/Simple/ObjectSpace/AssociationClass/MainForm.cpp
|
LenakeTech/BoldForDelphi
|
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
|
[
"MIT"
] | 121
|
2020-09-22T10:46:20.000Z
|
2021-11-17T12:33:35.000Z
|
examples/CBuilder/Simple/ObjectSpace/AssociationClass/MainForm.cpp
|
LenakeTech/BoldForDelphi
|
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
|
[
"MIT"
] | 8
|
2020-09-23T12:32:23.000Z
|
2021-07-28T07:01:26.000Z
|
examples/CBuilder/Simple/ObjectSpace/AssociationClass/MainForm.cpp
|
LenakeTech/BoldForDelphi
|
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
|
[
"MIT"
] | 42
|
2020-09-22T14:37:20.000Z
|
2021-10-04T10:24:12.000Z
|
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "MainForm.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "BoldAbstractListHandle"
#pragma link "BoldCursorHandle"
#pragma link "BoldGrid"
#pragma link "BoldHandles"
#pragma link "BoldListBox"
#pragma link "BoldListHandle"
#pragma link "BoldNavigator"
#pragma link "BoldNavigatorDefs"
#pragma link "BoldRootedHandles"
#pragma link "BoldSubscription"
#pragma link "BoldAbstractModel"
#pragma link "BoldActions"
#pragma link "BoldDBActions"
#pragma link "BoldHandle"
#pragma link "BoldHandleAction"
#pragma link "BoldModel"
#pragma link "BoldPersistenceHandle"
#pragma link "BoldPersistenceHandleDB"
#pragma link "BoldSystemHandle"
#pragma link "BoldUMLModelLink"
#pragma link "BoldAFPDefault"
#pragma link "BoldAFPPluggable"
#pragma link "BoldAbstractDatabaseAdapter"
#pragma link "BoldAbstractPersistenceHandleDB"
#pragma link "BoldDatabaseAdapterIB"
#pragma link "BoldIBDatabaseAction"
#pragma link "BoldUMLRose98Link"
#pragma resource "*.dfm"
TfrmMain *frmMain;
//---------------------------------------------------------------------------
__fastcall TfrmMain::TfrmMain(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::FormCreate(TObject *Sender)
{
Height = 444;
Width = 693;
}
//---------------------------------------------------------------------------
void __fastcall TfrmMain::FormCloseQuery(TObject *Sender, bool &CanClose)
{
CanClose = true;
if (BoldSystemHandle1->Active)
if (BoldSystemHandle1->System->DirtyObjects->Count > 0)
switch (MessageDlg("There are dirty objects. save them before exit?",
mtConfirmation, TMsgDlgButtons() << mbYes << mbNo << mbCancel, 0))
{
case mrYes: BoldSystemHandle1->System->UpdateDatabase(); break;
case mrNo: BoldSystemHandle1->System->Discard(); break;
case mrCancel: CanClose = false;
}
}
//---------------------------------------------------------------------------
| 33.307692
| 77
| 0.591686
|
LenakeTech
|
42b33e4ff5f09003e261c74f8949a3978d932fef
| 359
|
cpp
|
C++
|
unit_tests/core/physics_test_utils.cpp
|
mchurchf/amr-wind
|
4bd712966e830a7c9412b0a4ec4cd8d1e6e0582f
|
[
"BSD-3-Clause"
] | 40
|
2019-11-27T15:38:45.000Z
|
2022-03-07T10:56:35.000Z
|
unit_tests/core/physics_test_utils.cpp
|
mchurchf/amr-wind
|
4bd712966e830a7c9412b0a4ec4cd8d1e6e0582f
|
[
"BSD-3-Clause"
] | 207
|
2019-11-07T22:53:02.000Z
|
2022-03-30T21:41:57.000Z
|
unit_tests/core/physics_test_utils.cpp
|
mchurchf/amr-wind
|
4bd712966e830a7c9412b0a4ec4cd8d1e6e0582f
|
[
"BSD-3-Clause"
] | 55
|
2019-11-08T19:25:08.000Z
|
2022-03-15T20:36:25.000Z
|
#include "physics_test_utils.H"
namespace amr_wind_tests {
PhysicsEx::PhysicsEx(amr_wind::CFDSim&) {}
void PhysicsEx::post_init_actions() {}
void PhysicsEx::post_regrid_actions() {}
void PhysicsEx::initialize_fields(int, const amrex::Geometry&) {}
void PhysicsEx::pre_advance_work() {}
void PhysicsEx::post_advance_work() {}
} // namespace amr_wind_tests
| 25.642857
| 65
| 0.768802
|
mchurchf
|
42b453d12e4af7ad15079083fbbc06cbde92d5a0
| 1,300
|
cpp
|
C++
|
src/simulate.cpp
|
krunal-shah/yinsh
|
4f2bb348e6aa552fa8238420fcad510d70cc102b
|
[
"MIT"
] | null | null | null |
src/simulate.cpp
|
krunal-shah/yinsh
|
4f2bb348e6aa552fa8238420fcad510d70cc102b
|
[
"MIT"
] | null | null | null |
src/simulate.cpp
|
krunal-shah/yinsh
|
4f2bb348e6aa552fa8238420fcad510d70cc102b
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "Solver.h"
#include <stdlib.h>
#include <cstring>
using namespace std;
// Sample C++ Code
int main(int argc, char** argv)
{
// Get input from server about game specifications
// cin >> move;
int seed1 = stoi(argv[1]), seed2 = stoi(argv[2]);
int player_id = 1, board_size = 6, time_limit = 150, consecutive_rings = 5;
int turn = 1;
int moves = 0;
Solver* one = new Solver(player_id, board_size, time_limit, consecutive_rings, seed1);
player_id = 2;
Solver* two = new Solver(player_id, board_size, time_limit, consecutive_rings, seed2);
player_id = 1;
string move = "";
int one_remove = 0, two_remove = 0;
while(true)
{
if(player_id == 1)
{
move = one->move();
move = move.erase(move.length()-1,1);
cout << "1 " << move << endl;
two->make_opp_move(move);
player_id = 2;
for (int i = 0; i < move.length(); ++i)
{
if(move[i] == 'X')
one_remove++;
}
}
else
{
move = two->move();
move = move.erase(move.length()-1,1);
cout << "2 " << move << endl;
one->make_opp_move(move);
player_id = 1;
for (int i = 0; i < move.length(); ++i)
{
if(move[i] == 'X')
two_remove++;
}
}
if(one_remove == 3 || two_remove == 3)
{
cout << "%%**" << endl;
break;
}
}
return 0;
}
| 20.634921
| 87
| 0.58
|
krunal-shah
|
42be6706ac4c63f37bd26818ce2d662adf52c5af
| 13,324
|
cpp
|
C++
|
rpkg_src/load_temp_tblu_hash_depends.cpp
|
hitman-resources/RPKG-Tool
|
8767d3dd85f77df4a6eceaec480b330be34cee57
|
[
"BSD-2-Clause"
] | 9
|
2021-06-01T00:58:46.000Z
|
2022-02-16T12:44:15.000Z
|
rpkg_src/load_temp_tblu_hash_depends.cpp
|
hitman-resources/RPKG-Tool
|
8767d3dd85f77df4a6eceaec480b330be34cee57
|
[
"BSD-2-Clause"
] | 33
|
2021-06-02T17:55:16.000Z
|
2022-02-27T15:03:06.000Z
|
rpkg_src/load_temp_tblu_hash_depends.cpp
|
hitman-resources/RPKG-Tool
|
8767d3dd85f77df4a6eceaec480b330be34cee57
|
[
"BSD-2-Clause"
] | 17
|
2021-06-01T01:05:45.000Z
|
2022-01-30T12:19:53.000Z
|
#include "rpkg_function.h"
#include "file.h"
#include "global.h"
#include "crypto.h"
#include "console.h"
#include "util.h"
#include "generic_function.h"
#include <iostream>
#include <map>
int rpkg_function::load_temp_tblu_hash_depends(uint64_t rpkg_index, uint64_t hash_index)
{
/*hash_depends_variables temporary_temp_hash_depends_data;
temporary_temp_hash_depends_data.rpkg_file_name = rpkgs.at(rpkg_index).rpkg_file_name;
temporary_temp_hash_depends_data.hash_value = rpkgs.at(rpkg_index).hash.at(hash_index).hash_value;
temporary_temp_hash_depends_data.hash_string = rpkgs.at(rpkg_index).hash.at(hash_index).hash_string;
std::string hash_string = temporary_temp_hash_depends_data.hash_string;
uint32_t temp_hash_reference_count = rpkgs.at(rpkg_index).hash.at(hash_index).hash_reference_data.hash_reference_count & 0x3FFFFFFF;
LOG(hash_string + " has " + util::uint32_t_to_string(temp_hash_reference_count) + " dependencies in " + rpkgs.at(rpkg_index).rpkg_file_name);
if (temp_hash_reference_count > 0)
{
for (uint64_t y = 0; y < temp_hash_reference_count; y++)
{
std::vector<std::string> dependency_in_rpkg_file;
bool found = false;
for (uint64_t z = 0; z < rpkgs.size(); z++)
{
std::map<uint64_t, uint64_t>::iterator it3 = rpkgs.at(z).hash_map.find(rpkgs.at(rpkg_index).hash.at(hash_index).hash_reference_data.hash_reference.at(y));
if (it3 != rpkgs.at(z).hash_map.end())
{
LOG(rpkgs.at(z).hash.at(it3->second).hash_resource_type);
if (!found)
{
temporary_temp_hash_depends_data.hash_dependency_file_name.push_back(rpkgs.at(z).hash.at(it3->second).hash_file_name);
}
found = true;
dependency_in_rpkg_file.push_back(rpkgs.at(z).rpkg_file_name);
}
}
if (!found)
{
temporary_temp_hash_depends_data.hash_dependency_file_name.push_back(rpkgs.at(rpkg_index).hash.at(hash_index).hash_reference_data.hash_reference_string.at(y));
}
std::string ioi_string = "";
std::map<uint64_t, uint64_t>::iterator it2 = hash_list_hash_map.find(std::strtoull(temporary_temp_hash_depends_data.hash_dependency_file_name.back().c_str(), nullptr, 16));
if (it2 != hash_list_hash_map.end())
{
temporary_temp_hash_depends_data.hash_dependency_file_name.back() = util::to_upper_case(hash_list_hash_file_names.at(it2->second));
ioi_string = hash_list_hash_strings.at(it2->second);
}
temporary_temp_hash_depends_data.hash_dependency_ioi_string.push_back(ioi_string);
temporary_temp_hash_depends_data.hash_dependency_map[temporary_temp_hash_depends_data.hash_value] = temporary_temp_hash_depends_data.hash_dependency_map.size();
temporary_temp_hash_depends_data.hash_dependency.push_back(util::uint64_t_to_hex_string(temporary_temp_hash_depends_data.hash_value));
temporary_temp_hash_depends_data.hash_dependency_in_rpkg.push_back(dependency_in_rpkg_file);
}
}
temp_hash_depends_data.push_back(temporary_temp_hash_depends_data);
int rpkg_dependency_count = 0;
for (uint64_t x = 0; x < temp_hash_depends_data.size(); x++)
{
if (temp_hash_depends_data.at(x).hash_dependency.size() > 0)
{
rpkg_dependency_count++;
}
}
LOG(hash_string + " has dependencies in " + util::uint32_t_to_string((uint32_t)rpkg_dependency_count) + " RPKG files:");
std::string tblu_file_name = "";
std::string tblu_in_rpkg = "";
bool temp_tblu_depends_found = false;
for (uint64_t x = 0; x < temp_hash_depends_data.size(); x++)
{
if (temp_hash_depends_data.at(x).hash_dependency.size() > 0)
{
LOG(hash_string + " depends on " + util::uint32_t_to_string((uint32_t)temp_hash_depends_data.at(x).hash_dependency_file_name.size()) + " other hash files/resources in RPKG file: " + temp_hash_depends_data.at(x).rpkg_file_name);
if (temp_hash_depends_data.at(x).hash_dependency_file_name.size() > 0)
{
LOG(hash_string + "'s dependencies:");
for (uint64_t y = 0; y < temp_hash_depends_data.at(x).hash_dependency_file_name.size(); y++)
{
LOG("Hash file/resource: " + temp_hash_depends_data.at(x).hash_dependency_file_name.at(y));
LOG(" - IOI String: " + temp_hash_depends_data.at(x).hash_dependency_ioi_string.at(y));
if (temp_hash_depends_data.at(x).hash_dependency_in_rpkg.at(y).size() > 0)
{
int temp_tblu_depends_count = 0;
if (temp_hash_depends_data.at(x).hash_dependency_file_name.at(y).substr((temp_hash_depends_data.at(x).hash_dependency_file_name.at(y).length() - 4), 4) == "TBLU")
{
if (temp_tblu_depends_count == 0)
{
temp_tblu_depends_found = true;
tblu_file_name = temp_hash_depends_data.at(x).hash_dependency_file_name.at(y);
tblu_in_rpkg = temp_hash_depends_data.at(x).hash_dependency_in_rpkg.at(y).at(temp_hash_depends_data.at(x).hash_dependency_in_rpkg.at(y).size() - 1);
temp_tblu_depends_count++;
}
else
{
return TEMP_TBLU_TOO_MANY;
}
}
LOG_NO_ENDL(" - Found in RPKG files: ");
for (uint64_t z = 0; z < temp_hash_depends_data.at(x).hash_dependency_in_rpkg.at(y).size(); z++)
{
LOG_NO_ENDL(temp_hash_depends_data.at(x).hash_dependency_in_rpkg.at(y).at(z));
if (z < temp_hash_depends_data.at(x).hash_dependency_in_rpkg.at(y).size() - 1)
{
LOG_NO_ENDL(", ");
}
}
LOG_NO_ENDL(std::endl);
}
else
{
LOG(" - Found in RPKG files: None");
}
}
}
LOG_NO_ENDL(std::endl);
}
}
if (!temp_tblu_depends_found)
{
return TEMP_TBLU_NOT_FOUND_IN_DEPENDS;
}
bool tblu_found_in_rpkg = false;
uint64_t tblu_hash_value = std::strtoull(tblu_file_name.c_str(), nullptr, 16);
std::map<uint64_t, uint64_t>::iterator it2 = rpkgs.at(rpkg_index).hash_map.find(tblu_hash_value);
if (it2 != rpkgs.at(rpkg_index).hash_map.end())
{
tblu_found_in_rpkg = true;
tblu_rpkg_index_1 = rpkg_index;
tblu_rpkg_index_2 = it2->second;
}
if (!tblu_found_in_rpkg)
{
for (uint64_t x = 0; x < rpkgs.size(); x++)
{
if (!tblu_found_in_rpkg)
{
rpkg_index = (uint64_t)rpkgs.size() - (uint64_t)0x1 - (uint64_t)x;
std::map<uint64_t, uint64_t>::iterator it2 = rpkgs.at(rpkg_index).hash_map.find(tblu_hash_value);
if (it2 != rpkgs.at(rpkg_index).hash_map.end())
{
tblu_found_in_rpkg = true;
hash_index = it2->second;
tblu_rpkg_index_1 = rpkg_index;
tblu_rpkg_index_2 = it2->second;
}
}
}
}
if (!tblu_found_in_rpkg)
{
return TEMP_TBLU_NOT_FOUND_IN_RPKG;
}
tblu_found_in_rpkg = true;
hash_depends_variables temporary_tblu_hash_depends_data;
temporary_tblu_hash_depends_data.rpkg_file_name = rpkgs.at(rpkg_index).rpkg_file_name;
temporary_tblu_hash_depends_data.hash_value = rpkgs.at(rpkg_index).hash.at(hash_index).hash_value;
temporary_tblu_hash_depends_data.hash_string = rpkgs.at(rpkg_index).hash.at(hash_index).hash_string;
temp_hash_reference_count = rpkgs.at(rpkg_index).hash.at(hash_index).hash_reference_data.hash_reference_count & 0x3FFFFFFF;
LOG(hash_string + " has " + util::uint32_t_to_string(temp_hash_reference_count) + " dependencies in " + rpkgs.at(rpkg_index).rpkg_file_name);
if (temp_hash_reference_count > 0)
{
for (uint64_t y = 0; y < temp_hash_reference_count; y++)
{
std::vector<std::string> dependency_in_rpkg_file;
bool found = false;
for (uint64_t z = 0; z < rpkgs.size(); z++)
{
std::map<uint64_t, uint64_t>::iterator it3 = rpkgs.at(z).hash_map.find(rpkgs.at(rpkg_index).hash.at(hash_index).hash_reference_data.hash_reference.at(y));
if (it3 != rpkgs.at(z).hash_map.end())
{
LOG(rpkgs.at(z).hash.at(it3->second).hash_resource_type);
if (!found)// && rpkgs.at(z).hash.at(it3->second).hash_resource_type == "TBLU")
{
temporary_tblu_hash_depends_data.hash_dependency_file_name.push_back(rpkgs.at(z).hash.at(it3->second).hash_file_name);
}
found = true;
dependency_in_rpkg_file.push_back(rpkgs.at(z).rpkg_file_name);
}
}
if (!found)
{
temporary_tblu_hash_depends_data.hash_dependency_file_name.push_back(rpkgs.at(rpkg_index).hash.at(hash_index).hash_reference_data.hash_reference_string.at(y));
}
std::string ioi_string = "";
std::map<uint64_t, uint64_t>::iterator it4 = hash_list_hash_map.find(std::strtoull(temporary_tblu_hash_depends_data.hash_dependency_file_name.back().c_str(), nullptr, 16));
if (it4 != hash_list_hash_map.end())
{
temporary_tblu_hash_depends_data.hash_dependency_file_name.back() = util::to_upper_case(hash_list_hash_file_names.at(it4->second));
ioi_string = hash_list_hash_strings.at(it4->second);
}
temporary_tblu_hash_depends_data.hash_dependency_ioi_string.push_back(ioi_string);
temporary_tblu_hash_depends_data.hash_dependency_map[temporary_tblu_hash_depends_data.hash_value] = temporary_tblu_hash_depends_data.hash_dependency_map.size();
temporary_tblu_hash_depends_data.hash_dependency.push_back(util::uint64_t_to_hex_string(temporary_tblu_hash_depends_data.hash_value));
temporary_tblu_hash_depends_data.hash_dependency_in_rpkg.push_back(dependency_in_rpkg_file);
}
}
tblu_hash_depends_data.push_back(temporary_tblu_hash_depends_data);
rpkg_dependency_count = 0;
for (uint64_t x = 0; x < tblu_hash_depends_data.size(); x++)
{
if (tblu_hash_depends_data.at(x).hash_dependency.size() > 0)
{
rpkg_dependency_count++;
}
}
LOG(tblu_file_name + " has dependencies in " + util::uint32_t_to_string((uint32_t)rpkg_dependency_count) + " RPKG files:");
for (uint64_t x = 0; x < tblu_hash_depends_data.size(); x++)
{
if (tblu_hash_depends_data.at(x).hash_dependency.size() > 0)
{
LOG(tblu_file_name + " depends on " + util::uint32_t_to_string((uint32_t)tblu_hash_depends_data.at(x).hash_dependency_file_name.size()) + " other hash files/resources in RPKG file: " + tblu_hash_depends_data.at(x).rpkg_file_name);
if (tblu_hash_depends_data.at(x).hash_dependency_file_name.size() > 0)
{
LOG(tblu_file_name + "'s dependencies:");
for (uint64_t y = 0; y < tblu_hash_depends_data.at(x).hash_dependency_file_name.size(); y++)
{
LOG("Hash file/resource: " + tblu_hash_depends_data.at(x).hash_dependency_file_name.at(y));
LOG(" - IOI String: " + tblu_hash_depends_data.at(x).hash_dependency_ioi_string.at(y));
if (tblu_hash_depends_data.at(x).hash_dependency_in_rpkg.at(y).size() > 0)
{
LOG_NO_ENDL(" - Found in RPKG files: ");
for (uint64_t z = 0; z < tblu_hash_depends_data.at(x).hash_dependency_in_rpkg.at(y).size(); z++)
{
LOG_NO_ENDL(tblu_hash_depends_data.at(x).hash_dependency_in_rpkg.at(y).at(z));
if (z < tblu_hash_depends_data.at(x).hash_dependency_in_rpkg.at(y).size() - 1)
{
LOG_NO_ENDL(", ");
}
}
LOG_NO_ENDL(std::endl);
}
else
{
LOG(" - Found in RPKG files: None");
}
}
}
LOG_NO_ENDL(std::endl);
}
}
return TEMP_TBLU_FOUND;*/
return 0;
}
| 40.012012
| 242
| 0.594716
|
hitman-resources
|
42bfefce8059538fe81369be2eace83eb8bfb32f
| 1,504
|
hpp
|
C++
|
src/org/apache/poi/util/BitField.hpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
src/org/apache/poi/util/BitField.hpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
src/org/apache/poi/util/BitField.hpp
|
pebble2015/cpoi
|
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
|
[
"Apache-2.0"
] | null | null | null |
// Generated from /POI/java/org/apache/poi/util/BitField.java
#pragma once
#include <fwd-POI.hpp>
#include <org/apache/poi/util/fwd-POI.hpp>
#include <java/lang/Object.hpp>
struct default_init_tag;
class poi::util::BitField
: public virtual ::java::lang::Object
{
public:
typedef ::java::lang::Object super;
private:
int32_t _mask { };
int32_t _shift_count { };
protected:
void ctor(int32_t mask);
public:
virtual int32_t getValue(int32_t holder);
virtual int16_t getShortValue(int16_t holder);
virtual int32_t getRawValue(int32_t holder);
virtual int16_t getShortRawValue(int16_t holder);
virtual bool isSet(int32_t holder);
virtual bool isAllSet(int32_t holder);
virtual int32_t setValue(int32_t holder, int32_t value);
virtual int16_t setShortValue(int16_t holder, int16_t value);
virtual int32_t clear(int32_t holder);
virtual int16_t clearShort(int16_t holder);
virtual int8_t clearByte(int8_t holder);
virtual int32_t set(int32_t holder);
virtual int16_t setShort(int16_t holder);
virtual int8_t setByte(int8_t holder);
virtual int32_t setBoolean(int32_t holder, bool flag);
virtual int16_t setShortBoolean(int16_t holder, bool flag);
virtual int8_t setByteBoolean(int8_t holder, bool flag);
// Generated
BitField(int32_t mask);
protected:
BitField(const ::default_init_tag&);
public:
static ::java::lang::Class *class_();
private:
virtual ::java::lang::Class* getClass0();
};
| 27.345455
| 65
| 0.727394
|
pebble2015
|
42c0105c61902a1f7e7222f2f4bf285e7ca7d9a5
| 2,344
|
hh
|
C++
|
cordic.hh
|
aicodix/dsp
|
c83add357c695482590825ddd2713dc29fd903d2
|
[
"0BSD"
] | 16
|
2019-01-25T02:02:21.000Z
|
2022-02-11T04:05:54.000Z
|
cordic.hh
|
aicodix/dsp
|
c83add357c695482590825ddd2713dc29fd903d2
|
[
"0BSD"
] | 2
|
2020-12-10T05:46:36.000Z
|
2020-12-15T00:16:25.000Z
|
cordic.hh
|
aicodix/dsp
|
c83add357c695482590825ddd2713dc29fd903d2
|
[
"0BSD"
] | 4
|
2019-01-25T02:02:15.000Z
|
2021-10-06T13:50:59.000Z
|
/*
CORDIC atan2 implementation
Copyright 2019 Ahmet Inan <inan@aicodix.de>
*/
#pragma once
/*
for ((i = 0; i < 16; ++i)) ; do
echo -n "int(0.5+FAC*"
echo "scale=100; a((1/2)^$i)/(4*a(1))" | bc -l | head -n1 | sed 's/\\/L),/'
done
*/
namespace DSP {
template <typename TYPE>
class CORDIC
{
static const int BYTES = sizeof(TYPE);
static const int BITS = 8 * BYTES;
static_assert(BITS <= 16, "LUT not big enough");
static const int FAC = BYTES << BITS;
static constexpr int LUT[16] = {
int(0.5+FAC*.2500000000000000000000000000000000000000000000000000000000000000000L),
int(0.5+FAC*.1475836176504332741754010762247405259511345238869178945999223128627L),
int(0.5+FAC*.0779791303773693254605128897731301351165246187810070349907614355625L),
int(0.5+FAC*.0395834241605655420108516713400380263836230512014484657091255843474L),
int(0.5+FAC*.0198685243055408390593598828581045592395809198311117360197658161834L),
int(0.5+FAC*.0099439478235892739286124987559949706675355099351305855673205197301L),
int(0.5+FAC*.0049731872789504128535623156837751800756022858309425918885230220925L),
int(0.5+FAC*.0024867453936697392949686323634656804594951905170750175789691381407L),
int(0.5+FAC*.0012433916687141004173529641246144055092826557912518235730426698546L),
int(0.5+FAC*.0006216982059233715959748655390818054931061630817558971376245115402L),
int(0.5+FAC*.0003108493994100203787468007466901774427133407538770647518959302312L),
int(0.5+FAC*.0001554247367611315255509951068712763232641191255978216125229683284L),
int(0.5+FAC*.0000777123730125834146038201984686638046103667177724187710747868218L),
int(0.5+FAC*.0000388561870852939914306938515989779351910341528053916759630446151L),
int(0.5+FAC*.0000194280936150222836580154085598088977275755448309525831225639103L),
int(0.5+FAC*.0000097140468165580528976715963565423783044063210250363625335628380L),
};
public:
static TYPE atan2(TYPE y, TYPE x)
{
int angle = 0;
int real = x << 1;
int imag = y << 1;
if (x < 0)
real = -real;
for (int i = 0; i < BITS; ++i) {
int re = real;
int im = imag;
if (imag < 0) {
angle -= LUT[i];
re -= imag >> i;
im += real >> i;
} else {
angle += LUT[i];
re += imag >> i;
im -= real >> i;
}
real = re; imag = im;
}
if (x < 0)
angle = FAC - angle;
return angle >> BYTES;
}
};
}
| 32.109589
| 85
| 0.738055
|
aicodix
|
42c39b3a26a14add8177872f728eff47ea8142e7
| 7,193
|
cpp
|
C++
|
tests/src/astro/propagators/unitTestFullPropagationLambertTargeter.cpp
|
kimonito98/tudat
|
c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092
|
[
"BSD-3-Clause"
] | null | null | null |
tests/src/astro/propagators/unitTestFullPropagationLambertTargeter.cpp
|
kimonito98/tudat
|
c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092
|
[
"BSD-3-Clause"
] | null | null | null |
tests/src/astro/propagators/unitTestFullPropagationLambertTargeter.cpp
|
kimonito98/tudat
|
c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092
|
[
"BSD-3-Clause"
] | null | null | null |
/* Copyright (c) 2010-2019, Delft University of Technology
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <tudat/simulation/estimation.h>
#include "tudat/simulation/propagation_setup/propagationLambertTargeterFullProblem.h"
#include <boost/test/tools/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>
#include <Eigen/Core>
#include "tudat/basics/testMacros.h"
#include "tudat/astro/ephemerides/approximatePlanetPositions.h"
#include "tudat/astro/trajectory_design/trajectory.h"
#include "tudat/astro/trajectory_design/exportTrajectory.h"
#include "tudat/astro/trajectory_design/planetTrajectory.h"
using namespace tudat;
using namespace tudat::propagators;
namespace tudat
{
namespace unit_tests
{
//! Function to setup a body map corresponding to the assumptions of the Lambert targeter,
//! using default ephemerides for the central body only, while the positions of departure and arrival bodies are provided as inputs.
/*!
* Function to setup a Lambert targeter map. The body map contains the central, departure and arrival bodies and the body to be propagated.
* The positions of the departure and arrival bodies are defined by the user and provided as inputs.
* \param nameCentralBody Name of the central body.
* \param nameBodyToPropagate Name of the body to be propagated.
* \param departureAndArrivalBodies Vector containing the names of the departure and arrival bodies.
* \param cartesianPositionAtDeparture Vector containing the position coordinates of the departure body [m].
* \param cartesianPositionAtArrival Vector containing the position coordinates of the arrival body [m].
* \return Body map for the Lambert targeter.
*/
simulation_setup::NamedBodyMap setupBodyMapFromUserDefinedStatesForLambertTargeter(
const std::string& nameCentralBody,
const std::string& nameBodyToPropagate,
const std::pair< std::string, std::string >& departureAndArrivalBodies,
const Eigen::Vector3d& cartesianPositionAtDeparture,
const Eigen::Vector3d& cartesianPositionAtArrival )
{
spice_interface::loadStandardSpiceKernels( );
std::string frameOrigin = "SSB";
std::string frameOrientation = "ECLIPJ2000";
// Create ephemeris vector for departure and arrival bodies.
std::vector< ephemerides::EphemerisPointer > ephemerisVectorDepartureAndArrivalBodies(2);
ephemerisVectorDepartureAndArrivalBodies[ 0 ] = std::make_shared< ephemerides::ConstantEphemeris > (
( Eigen::Vector6d( ) << cartesianPositionAtDeparture,
0.0, 0.0, 0.0 ).finished( ), frameOrigin, frameOrientation );
ephemerisVectorDepartureAndArrivalBodies[ 1 ] = std::make_shared< ephemerides::ConstantEphemeris >(
( Eigen::Vector6d( ) << cartesianPositionAtArrival,
0.0, 0.0, 0.0 ).finished( ), frameOrigin, frameOrientation );
// Create body map.
simulation_setup::NamedBodyMap bodyMap =
propagators::setupBodyMapFromUserDefinedEphemeridesForLambertTargeter(
nameCentralBody, nameBodyToPropagate, departureAndArrivalBodies, ephemerisVectorDepartureAndArrivalBodies );
return bodyMap;
}
BOOST_AUTO_TEST_SUITE( testFullPropagationLambertTargeter )
//! Test if the difference between the Lambert targeter solution and the full dynamics problem is computed correctly.
BOOST_AUTO_TEST_CASE( testFullPropagationLambertTargeterBasic )
{
std::cout.precision(20);
double initialTime = 0.0;
Eigen::Vector3d cartesianPositionAtDeparture ( 2.0 * 6.378136e6, 0.0, 0.0 );
Eigen::Vector3d cartesianPositionAtArrival ( 2.0 * 6.378136e6, 2.0 * std::sqrt( 3.0 ) * 6.378136e6, 0.0 );
double timeOfFlight = 806.78 * 5.0;
double fixedStepSize = timeOfFlight / 10000.0;
std::string bodyToPropagate = "spacecraft" ;
std::string centralBody = "Earth";
// Define integrator settings.
std::shared_ptr< numerical_integrators::IntegratorSettings< double > > integratorSettings =
std::make_shared < numerical_integrators::IntegratorSettings < > >
( numerical_integrators::rungeKutta4, initialTime, fixedStepSize);
std::pair< std::string, std::string > departureAndArrivalBodies =
std::make_pair( "departure", "arrival" );
<<<<<<< HEAD
// Define the system of bodies.
simulation_setup::SystemOfBodies bodies = propagators::setupBodyMapFromUserDefinedStatesForLambertTargeter("Earth", "spacecraft", departureAndArrivalBodies,
cartesianPositionAtDeparture, cartesianPositionAtArrival);
basic_astrodynamics::AccelerationMap accelerationModelMap = propagators::setupAccelerationMapLambertTargeter(
"Earth", "spacecraft", bodies);
// Compute the difference in state between the full problem and the Lambert targeter solution at departure and at arrival
std::pair< Eigen::Vector6d, Eigen::Vector6d > differenceState =
propagators::getDifferenceFullPropagationWrtLambertTargeterAtDepartureAndArrival(cartesianPositionAtDeparture,
cartesianPositionAtArrival, timeOfFlight, initialTime, bodies, accelerationModelMap, bodyToPropagate,
centralBody, integratorSettings, departureAndArrivalBodies, false);
=======
// Define the body map.
simulation_setup::NamedBodyMap bodyMap = setupBodyMapFromUserDefinedStatesForLambertTargeter(
"Earth", "spacecraft", departureAndArrivalBodies, cartesianPositionAtDeparture, cartesianPositionAtArrival );
basic_astrodynamics::AccelerationMap accelerationModelMap = propagators::setupAccelerationMapLambertTargeter(
"Earth", "spacecraft", bodyMap );
>>>>>>> dominic-origin/features/mission_segments_refactor
std::map< double, Eigen::Vector6d > lambertTargeterResult;
std::map< double, Eigen::Vector6d > fullProblemResult;
std::map< double, Eigen::VectorXd > dependentVariableResult;
propagateLambertTargeterAndFullProblem(
timeOfFlight, initialTime, bodyMap, accelerationModelMap, bodyToPropagate,
centralBody, departureAndArrivalBodies, integratorSettings, lambertTargeterResult, fullProblemResult,
dependentVariableResult, false );
for( auto stateIterator : lambertTargeterResult )
{
for( int i = 0; i < 3; i++ )
{
BOOST_CHECK_SMALL( std::fabs( lambertTargeterResult.at( stateIterator.first )( i ) -
fullProblemResult.at( stateIterator.first )( i ) ), 1.0E-5 );
BOOST_CHECK_SMALL( std::fabs( lambertTargeterResult.at( stateIterator.first )( i + 3 ) -
fullProblemResult.at( stateIterator.first )( i + 3 ) ), 1.0E-9 );
}
}
}
}
}
| 46.406452
| 160
| 0.72362
|
kimonito98
|
42c510f268f3eda780d60ac4d83c5fc8c5187c83
| 10,716
|
cpp
|
C++
|
src/frontend/logic/main.cpp
|
AquaFlyRat/PotatoAdventure
|
f673d8f520ba88b7ff73888b5871aae99f1ab6b6
|
[
"Zlib"
] | 2
|
2017-06-19T21:08:27.000Z
|
2017-06-20T17:25:58.000Z
|
src/frontend/logic/main.cpp
|
AquaFlyRat/PotatoAdventure
|
f673d8f520ba88b7ff73888b5871aae99f1ab6b6
|
[
"Zlib"
] | 1
|
2017-07-20T11:47:54.000Z
|
2017-07-20T11:48:25.000Z
|
src/frontend/logic/main.cpp
|
AquaFlyRat/PotatoAdventure
|
f673d8f520ba88b7ff73888b5871aae99f1ab6b6
|
[
"Zlib"
] | null | null | null |
#include "../master.h"
#include "gui.h"
#include <deque>
namespace Backend
{
void Start();
void Tick();
}
void Boot();
void Main();
static int window_scale = 2;
static constexpr ivec2 screen_size(480,270);
namespace Cfg
{
static constexpr int log_x = 146, log_width = 334,
log_text_margin_bottom = 34, log_text_margin_left = 8, log_text_margin_right = 8,
log_text_width = log_width - log_text_margin_left - log_text_margin_right,
log_text_height = 270-log_text_margin_bottom,
log_scrollbar_min_height = 16;
static constexpr float log_text_typing_speed = 0.4, log_text_typing_speed_high = 2,
log_text_insertion_offset_pixel_speed = 0.25, log_text_insertion_offset_frac_change_per_frame = 0.025,
log_scroll_speed_drag_factor = 0.05,
log_scroll_pos_reset_pixel_speed = 2, log_scroll_pos_reset_frac_change_per_frame = 0.05;
static constexpr fvec3 color_log_background(0,0,0),
color_log_boundary(0.5,0.5,0.5),
color_log_boundary_dark(0.2,0.2,0.2),
color_log_text(1,1,1);
}
void PreInit()
{
Sys::Config::ApplicationName("Potato Adventure");
Window::Init::Name("Potato Adventure");
Window::Init::Size(screen_size * window_scale);
Window::Init::OpenGL::Vsync(Window::ContextSwapMode::late_swap_tearing);
Sys::SetCurrentFunction(Boot);
glfl::check_errors = 1;
glfl::terminate_on_error = 1;
}
static Utils::TickStabilizer ts(60, 8);
static Graphics::Texture *main_texture;
static Renderer2D *renderer;
static Graphics::Font main_font_obj;
static Graphics::Font mono_font_obj;
static Graphics::FontData main_font;
static Graphics::FontData mono_font;
static Renderer2D::Text::StyleVector main_font_style_vec;
static std::deque<std::string> log_queue;
namespace GUI
{
// Low level
Renderer2D &Renderer() {return *renderer;}
namespace Fonts
{
const Graphics::FontData &Main() {return main_font;}
const Graphics::FontData &Mono() {return mono_font;}
}
namespace FontStyleVectors
{
const Renderer2D::Text::StyleVector &Main() {return main_font_style_vec;}
}
// High level
void WriteLine(std::string_view line) // Line feed is automatically added at the end.
{
std::string str = Renderer2D::Text::InsertLineBreaksToFit(main_font_style_vec, line, Cfg::log_text_width);
char *it = str.data();
const char *word_start = str.c_str();
while (1)
{
bool end = 0;
if (*it == '\n')
*it = '\0';
else if (*it == '\0')
end = 1;
if (*it == '\0')
{
log_queue.emplace_back(word_start);
if (!end)
word_start = it+1;
}
if (end)
return;
it++;
}
}
}
void Resize()
{
renderer->UpdateViewport(window_scale);
}
void Boot()
{
MarkLocation("Boot");
Graphics::Blend::Enable();
auto img = Graphics::ImageData::FromPNG("assets/texture.png");
main_font_obj.Open("assets/Cat12.ttf", 12);
main_font_obj.SetHinting(Graphics::Font::Hinting::light);
main_font_obj.ExportGlyphs(img, main_font, {64,32}, {256,256}, Utils::Encodings::cp1251());
mono_font_obj.Open("assets/CatV_6x12_9.ttf", 12);
mono_font_obj.SetHinting(Graphics::Font::Hinting::light);
mono_font_obj.ExportGlyphs(img, mono_font, {256,32}, {256,256}, Utils::Encodings::cp1251());
main_texture = new Graphics::Texture(img);
main_texture->LinearInterpolation(0);
renderer = new Renderer2D(screen_size);
renderer->SetTexture(*main_texture);
renderer->SetDefaultFont(main_font);
renderer->SetBlendingMode();
renderer->UseMouseMapping(1);
renderer->EnableShader();
main_font_style_vec = renderer->Text()
.color(Cfg::color_log_text)
.shadow({1,1}).shadow_color({0.1f,0.1f,0.1f})
.configure_style(1).bold_aligned(1)
.configure_style(2).italic(0.25)
.configure_style(3).color({0.2f,1,0.2f})
.configure_style(4).color({1,1,0.2f})
.configure_style(5).color({1,0.2f,0.2f})
.export_styles();
Sys::SetCurrentFunction(Main);
}
void Main()
{
Backend::Start();
std::deque<std::string> log_lines;
float log_tmp_offset_y = 0;
float log_queue_current_str_pos = 0;
int log_queue_front_visible_char_count = -1;
float log_position = 0, log_cur_scroll_speed = 0;
int log_text_pixel_height, log_scrollbar_height;
bool log_grabbed = 0;
float log_grab_y;
bool log_mouse_moved_since_grab;
bool log_resetting_pos = 0;
const int text_input_y = screen_size.y - Cfg::log_text_margin_bottom + main_font.LineSkip();
auto Tick = [&]
{
if (log_queue.empty())
Backend::Tick();
// Updating log queue
if (log_queue.size())
{
if (log_queue_front_visible_char_count == -1)
log_queue_front_visible_char_count = Renderer2D::Text::VisibleCharCount(log_queue.front());
if (log_queue_current_str_pos > log_queue_front_visible_char_count)
{
log_lines.emplace_back((std::string &&)log_queue.front());
log_queue.pop_front();
log_queue_current_str_pos = 0;
log_queue_front_visible_char_count = -1;
if (log_position == 0)
log_tmp_offset_y += 1;
else
log_position += main_font.LineSkip();
}
else
log_queue_current_str_pos += (Input::AnyKeyDown() ? Cfg::log_text_typing_speed_high : Cfg::log_text_typing_speed);
}
if (log_tmp_offset_y > 0)
{
log_tmp_offset_y -= log_tmp_offset_y * Cfg::log_text_insertion_offset_frac_change_per_frame + Cfg::log_text_insertion_offset_pixel_speed/main_font.LineSkip();
if (log_tmp_offset_y < 0)
log_tmp_offset_y = 0;
}
log_text_pixel_height = log_lines.size() * main_font.LineSkip();
log_scrollbar_height = clamp(std::lround(screen_size.y * Cfg::log_text_height / float(max(1, log_text_pixel_height))), Cfg::log_scrollbar_min_height, screen_size.y);
if (log_grabbed)
{
if (Input::MouseButtonReleased(1))
{
log_grabbed = 0;
log_cur_scroll_speed = Input::MousePosDelta().y;
if (!log_mouse_moved_since_grab)
log_resetting_pos = 1;
}
else
{
log_position = log_grab_y - (screen_size.y - Input::MousePos().y);
if (Input::MousePosDelta().any())
log_mouse_moved_since_grab = 1;
}
}
else if (Input::MouseButtonPressed(1) && !log_resetting_pos)
{
log_grabbed = 1;
log_grab_y = log_position + screen_size.y - Input::MousePos().y;
log_mouse_moved_since_grab = 0;
}
if (!log_grabbed)
{
log_position += log_cur_scroll_speed;
log_cur_scroll_speed *= 1 - Cfg::log_scroll_speed_drag_factor;
}
if (log_resetting_pos)
{
log_position -= Cfg::log_scroll_pos_reset_pixel_speed + log_position * Cfg::log_scroll_pos_reset_frac_change_per_frame;
if (log_position <= 0)
log_resetting_pos = 0;
}
if (log_position > int(log_lines.size()) * main_font.LineSkip() - Cfg::log_text_height)
log_position = int(log_lines.size()) * main_font.LineSkip() - Cfg::log_text_height;
if (log_position < 0)
log_position = 0;
""; if (Input::KeyPressed(Input::Key_Enter())) GUI::WriteLine("Meow!");
};
auto Render = [&]
{
Graphics::Clear();
// Log background
renderer->Sprite({float(Cfg::log_x), 0}, fvec2(Cfg::log_width, screen_size.y)).color(Cfg::color_log_background);
// Log lines
if (log_lines.size())
{
int max_visible_line = std::min(int(log_lines.size()), int(std::lround(std::ceil((log_position+log_tmp_offset_y) / float(main_font.LineSkip())))) + screen_size.y / main_font.LineSkip() + 2);
int min_visible_line = std::max(0, int(std::lround(log_position / float(main_font.LineSkip())) - 2));
for (int i = min_visible_line; i < max_visible_line; i++)
{
renderer->Text({float(Cfg::log_x + Cfg::log_text_margin_left), std::round(log_position + screen_size.y - Cfg::log_text_margin_bottom - main_font.LineSkip() * (i + 1 - log_tmp_offset_y))}, log_lines[log_lines.size() - 1 - i])
.styles(main_font_style_vec)
.align_h(-1).align_v(-1);
}
}
// Current unfinished line
if (log_queue.size())
{
renderer->Text(fvec2(Cfg::log_x + Cfg::log_text_margin_left, std::round(screen_size.y - Cfg::log_text_margin_bottom + main_font.LineSkip() * log_tmp_offset_y + log_position)), log_queue.front())
.styles(main_font_style_vec)
.align_h(-1).align_v(-1)
.character_count(log_queue_current_str_pos);
}
// Text input background
renderer->Sprite(fvec2(Cfg::log_x, text_input_y), fvec2(Cfg::log_width, screen_size.y - text_input_y)).color(Cfg::color_log_background);
// Line separating log from text input
renderer->Sprite(fvec2(Cfg::log_x, text_input_y), fvec2(Cfg::log_width-2,1)).color(Cfg::color_log_boundary_dark);
// Line separating log from map and stats;
renderer->Sprite({float(Cfg::log_x), 0}, {1,float(screen_size.y)}).color(Cfg::color_log_boundary);
// Line separating log scrollbar
renderer->Sprite({float(Cfg::log_x+Cfg::log_width - 2), 0}, {1,float(screen_size.y)}).color(Cfg::color_log_boundary);
// Scrollbar
renderer->Sprite(fvec2(Cfg::log_x + Cfg::log_width - 1, screen_size.y - log_scrollbar_height - (screen_size.y - log_scrollbar_height) * (log_position / float(log_text_pixel_height - Cfg::log_text_height))),
fvec2(1, log_scrollbar_height))
.color(Cfg::color_log_text);
};
while (1)
{
Sys::BeginFrame();
while (ts.Tick())
{
Sys::Tick();
Tick();
}
Render();
renderer->Flush();
Sys::EndFrame();
}
}
| 33.911392
| 240
| 0.60573
|
AquaFlyRat
|
42c671822fc6edb50c04c797b1226eb317d2faf3
| 1,158
|
cpp
|
C++
|
src/test/test_find_feature_range.cpp
|
JerryLife/FedTree
|
0544e6ac98c05da7e83d0db957fd93bf3bdf6ebf
|
[
"Apache-2.0"
] | 12
|
2021-04-27T11:59:15.000Z
|
2022-03-15T02:55:52.000Z
|
src/test/test_find_feature_range.cpp
|
JerryLife/FedTree
|
0544e6ac98c05da7e83d0db957fd93bf3bdf6ebf
|
[
"Apache-2.0"
] | 1
|
2021-12-20T09:54:01.000Z
|
2021-12-21T04:08:44.000Z
|
src/test/test_find_feature_range.cpp
|
JerryLife/FedTree
|
0544e6ac98c05da7e83d0db957fd93bf3bdf6ebf
|
[
"Apache-2.0"
] | 5
|
2021-04-28T03:27:07.000Z
|
2021-12-18T09:55:58.000Z
|
//
// Created by Kelly Yung on 2021/2/25.
//
#include "FedTree/FL/party.h"
#include "gtest/gtest.h"
#include <vector>
class FeatureRangeTest: public ::testing::Test {
public:
vector<float_type> csc_val = {10, 20, 30, 50, 40, 60, 70, 80};
vector<int> csc_row_idx = {0, 0, 1, 1, 2, 2, 2, 4};
vector<int> csc_col_ptr = {0, 1, 3, 4, 6, 7, 8};
Party p;
protected:
void SetUp() override {
p.dataset.csc_row_idx = csc_row_idx;
p.dataset.csc_col_ptr = csc_col_ptr;
p.dataset.csc_val = csc_val;
}
};
TEST_F(FeatureRangeTest, find_feature_range_by_index_single_value){
vector<float> result = p.get_feature_range_by_feature_index(0);
LOG(INFO) << "Result:" << result;
EXPECT_EQ(result[0], 10);
EXPECT_EQ(result[1], 10);
}
TEST_F(FeatureRangeTest, find_feature_range_by_index_multi_value){
vector<float> result = p.get_feature_range_by_feature_index(1);
EXPECT_EQ(result[0], 20);
EXPECT_EQ(result[1], 30);
}
TEST_F(FeatureRangeTest, find_feature_range_by_last_index){
vector<float> result = p.get_feature_range_by_feature_index(5);
EXPECT_EQ(result[0], 80);
EXPECT_EQ(result[1], 80);
}
| 26.318182
| 67
| 0.686528
|
JerryLife
|
42cb8df109235db8e355bc34384fb65579bb7628
| 6,814
|
hpp
|
C++
|
clients/cpp/pitocin/src/BrokerTcp.hpp
|
javasboy/qmq
|
b39438f07f849e97ab47954e5abb98bee49c7004
|
[
"Apache-2.0"
] | 2,499
|
2018-12-07T06:02:12.000Z
|
2022-03-31T06:46:36.000Z
|
clients/cpp/pitocin/src/BrokerTcp.hpp
|
javasboy/qmq
|
b39438f07f849e97ab47954e5abb98bee49c7004
|
[
"Apache-2.0"
] | 92
|
2018-12-07T06:35:03.000Z
|
2022-03-20T01:54:54.000Z
|
clients/cpp/pitocin/src/BrokerTcp.hpp
|
javasboy/qmq
|
b39438f07f849e97ab47954e5abb98bee49c7004
|
[
"Apache-2.0"
] | 657
|
2018-12-07T06:04:27.000Z
|
2022-03-31T14:27:39.000Z
|
#ifndef PITOCIN_BROKER_TCP_H
#define PITOCIN_BROKER_TCP_H
#include <uv.h>
#include "Conn.hpp"
#include "Protocol.hpp"
#include "StackPool.hpp"
#include "ExiledChecker.hpp"
#include <cstdint>
#include <functional>
#include <string>
#include <unordered_map>
#include <iostream>
using namespace std;
namespace Pitocin
{
class BrokerTcp
{
struct PublishCtx
{
uint32_t id;
function<void(int, Header *, PublishMessageResult *)> callback;
uv_timer_t timeout;
BrokerTcp *broker;
};
uv_loop_t *loop;
Conn conn;
BrokerInfo info;
StackPool<BigendStream> sendStreamPool;
BigendStream recvStream;
uint32_t requestIdAcc = 0;
unordered_map<uint32_t, PublishCtx *> publishMap;
StackPool<PublishCtx> publishPool;
ExiledChecker checker;
public:
static const int CodeSuccess = 0;
static const int CodeTimeout = 999;
static const int CodePaseError = 1;
BrokerTcp() = delete;
BrokerTcp(uv_loop_t *loop)
: loop(loop),
conn(loop),
checker(loop),
recvStream(1024)
{
}
~BrokerTcp()
{
cout << "BrokerTcp_Destruct" << endl;
}
void setInfo(BrokerInfo &brokerInfo)
{
info = brokerInfo;
conn.setAddr(move(info.ip), info.port);
}
BrokerInfo &getInfo()
{
return info;
}
void setConnectCallback(function<void(BrokerTcp *)> callback)
{
conn.setConnectCallback([this, callback]() {
callback(this);
});
}
void setTerminateCallback(function<void(BrokerTcp *, int code)> callback)
{
conn.setTerminateCallback([this, callback](int code) {
callback(this, code);
});
}
void connect()
{
conn.setReadCallback([this](char *base, size_t len) {
this->recvStream.write((uint8_t *)base, len);
size_t suggestBufLen = this->dealReadData();
this->conn.setReadBufSize(suggestBufLen);
});
cout << "conn.connect()" << endl;
conn.connect();
}
void publish(
Header *header,
PublishMessage *msg,
function<void(int, Header *, PublishMessageResult *)> callback)
{
checker.doRequest();
header->code = Header::CodeSendMessage;
header->requestId = ++requestIdAcc;
header->requestCode = header->code;
header->flag = Header::FlagRequest;
if (sendStreamPool.empty())
{
sendStreamPool.emplace();
}
BigendStream *sendStream = sendStreamPool.pop();
sendStream->reset();
*sendStream << (uint32_t)0;
header->encode(*sendStream);
msg->encode(*sendStream);
uint32_t len = sendStream->size - 4;
sendStream->insert(len, 0);
uv_buf_t uvBuf{
.base = (char *)sendStream->buf,
.len = sendStream->size};
conn.write(
uvBuf,
[this, sendStream]() {
this->sendStreamPool.push(sendStream);
});
// 下面的代码是处理超时的
if (publishPool.empty())
{
publishPool.emplace();
}
PublishCtx *pubCtx = publishPool.pop();
pubCtx->id = header->requestId;
pubCtx->callback = callback;
uv_timer_init(loop, &pubCtx->timeout);
pubCtx->timeout.data = pubCtx;
pubCtx->broker = this;
uv_timer_start(
&pubCtx->timeout,
[](uv_timer_t *t) {
PublishCtx *pub = (PublishCtx *)t->data;
if (pub->broker->publishMap.erase(pub->id) > 0)
{
pub->callback(CodeTimeout, nullptr, nullptr);
pub->broker->publishPool.push(pub);
}
},
10000, 0);
publishMap.emplace(header->requestId, pubCtx);
}
void heartbeat()
{
checker.doRequest();
Header header;
header.code = Header::CodeHeartbeat;
header.requestId = ++requestIdAcc;
header.requestCode = header.code;
if (sendStreamPool.empty())
{
sendStreamPool.emplace();
}
BigendStream *sendStream = sendStreamPool.pop();
sendStream->reset();
*sendStream << (uint32_t)0;
header.encode(*sendStream);
uint32_t len = sendStream->size - 4;
sendStream->insert(len, 0);
uv_buf_t uvBuf{
.base = (char *)sendStream->buf,
.len = sendStream->size};
conn.write(
uvBuf,
[this, sendStream]() {
this->sendStreamPool.push(sendStream);
});
cout << "broker-heartbeat" << endl;
}
void setExile(uint64_t timeout)
{
checker.setInterval(timeout);
checker.setCallback([this](uint64_t timestamp) {
this->conn.close();
});
checker.start();
}
private:
size_t dealReadData()
{
// cout << recvStream.toString() << endl;
size_t positMark = recvStream.posit;
uint32_t binLen = 0;
recvStream.readError = false;
while (true)
{
recvStream >> binLen;
BigendReader content = recvStream.slice(binLen);
if (recvStream.readError)
{
break;
}
positMark = recvStream.posit;
Header header;
if (!header.decode(content))
{
break;
}
// heartbeat 100
if (header.code == Header::CodeHeartbeat)
{
cout << "RecvHeartbeat" << endl
<< header.toString() << endl;
continue;
}
// publish
if (header.requestCode == Header::CodeSendMessage)
{
auto got = publishMap.find(header.requestId);
if (got == publishMap.end())
{
continue;
}
PublishCtx *pubCtx = got->second;
publishMap.erase(got);
uv_timer_stop(&pubCtx->timeout);
PublishMessageResult resp;
if (resp.decode(content))
{
pubCtx->callback(CodeSuccess, &header, &resp);
}
else
{
pubCtx->callback(CodePaseError, &header, nullptr);
}
pubCtx->broker->publishPool.push(pubCtx);
continue;
}
}
recvStream.posit = positMark;
if (recvStream.posit > 0)
{
recvStream.compact();
}
return recvStream.posit + 4 + binLen;
}
};
} // namespace Pitocin
#endif //PITOCIN_BROKER_TCP_H
| 27.475806
| 77
| 0.526856
|
javasboy
|
42cc5e6fb3e04419397b2613ceef3d0b5defc1a6
| 8,437
|
cc
|
C++
|
algorithms/map-sparsification/test/test_heuristic_landmark_sparsification.cc
|
AdronTech/maplab
|
1340e01466fc1c02994860723b8117daf9ad226d
|
[
"Apache-2.0"
] | 1,936
|
2017-11-27T23:11:37.000Z
|
2022-03-30T14:24:14.000Z
|
algorithms/map-sparsification/test/test_heuristic_landmark_sparsification.cc
|
AdronTech/maplab
|
1340e01466fc1c02994860723b8117daf9ad226d
|
[
"Apache-2.0"
] | 353
|
2017-11-29T18:40:39.000Z
|
2022-03-30T15:53:46.000Z
|
algorithms/map-sparsification/test/test_heuristic_landmark_sparsification.cc
|
AdronTech/maplab
|
1340e01466fc1c02994860723b8117daf9ad226d
|
[
"Apache-2.0"
] | 661
|
2017-11-28T07:20:08.000Z
|
2022-03-28T08:06:29.000Z
|
#include <memory>
#include <Eigen/Core>
#include <map-sparsification/heuristic/cost-functions/min-keypoints-per-keyframe-cost.h>
#include <map-sparsification/heuristic/heuristic-sampling.h>
#include <map-sparsification/heuristic/scoring/descriptor-variance-scoring.h>
#include <map-sparsification/heuristic/scoring/observation-count-scoring.h>
#include <maplab-common/test/testing-entrypoint.h>
#include <maplab-common/test/testing-predicates.h>
#include <vi-map/pose-graph.h>
#include <vi-map/test/vi-map-generator.h>
#include <vi-map/vi-map.h>
class MapSparsification : public testing::Test {
protected:
typedef map_sparsification::sampling::LandmarkSamplingWithCostFunctions
Sampler;
virtual void SetUp() {
generator_map_.reset(new vi_map::VIMap);
constexpr int kSeed = 42;
generator_.reset(new vi_map::VIMapGenerator(*generator_map_, kSeed));
is_map_data_initialized_ = false;
initializeMapData();
addMissionAndVertices();
buildMapSummarizer();
}
const vi_map::LandmarkId& generateMapToTestObservationCount();
const vi_map::LandmarkId& generateMapToTestKeyframeConstraints();
void sample(vi_map::LandmarkIdSet* summary_store_landmark_ids);
void expectRemovedLandmark(
const vi_map::LandmarkIdSet& summary_store_landmark_ids,
const vi_map::LandmarkId& deleted_landmark) const;
void expectPreservedLandmark(
const vi_map::LandmarkIdSet& summary_store_landmark_ids,
const vi_map::LandmarkId& preserved_landmark) const;
inline int getNumDesiredLandmarks() const {
return kNumDesiredNumLandmarks;
}
private:
void initializeMapData();
void addMissionAndVertices();
void buildMapSummarizer();
std::unique_ptr<vi_map::VIMap> generator_map_;
std::unique_ptr<vi_map::VIMapGenerator> generator_;
Sampler sampler_;
static constexpr int kNumVertices = 5;
static constexpr int kNumLandmarks = 5;
static constexpr int kNumMissions = 1;
static constexpr int kNumDesiredNumLandmarks = 4;
vi_map::MissionId mission_id_;
pose_graph::VertexId vertex_ids_[kNumVertices];
vi_map::LandmarkId landmark_ids_[kNumLandmarks];
pose::Transformation T_G_M_;
pose::Transformation T_G_I_[kNumVertices];
Eigen::Vector3d p_G_fi_[kNumLandmarks];
bool is_map_data_initialized_;
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
void MapSparsification::initializeMapData() {
ASSERT_FALSE(is_map_data_initialized_);
T_G_M_.setIdentity();
for (unsigned int i = 0; i < kNumVertices; ++i) {
T_G_I_[i].setIdentity();
}
for (unsigned int i = 0; i < kNumLandmarks; ++i) {
p_G_fi_[i] = Eigen::Vector3d(1, 1, 1);
}
is_map_data_initialized_ = true;
}
void MapSparsification::addMissionAndVertices() {
ASSERT_TRUE(is_map_data_initialized_);
mission_id_ = generator_->createMission(T_G_M_);
for (unsigned int i = 0; i < kNumVertices; ++i) {
vertex_ids_[i] = generator_->createVertex(mission_id_, T_G_I_[i]);
}
}
// This method generates a map where one of the landmarks has fewer
// observations than all the others. ID of this landmark is returned.
const vi_map::LandmarkId&
MapSparsification::generateMapToTestObservationCount() {
pose_graph::VertexIdList all_vertices;
all_vertices.assign(vertex_ids_ + 1, vertex_ids_ + kNumVertices);
for (unsigned int i = 1; i < kNumLandmarks; ++i) {
landmark_ids_[i] =
generator_->createLandmark(p_G_fi_[i], vertex_ids_[0], all_vertices);
}
pose_graph::VertexIdList empty_vertex_list;
landmark_ids_[0] =
generator_->createLandmark(p_G_fi_[0], vertex_ids_[0], empty_vertex_list);
generator_->generateMap();
return landmark_ids_[0];
}
// This method generates a map where one of the keyframes is observed by
// smaller number of landmarks than the rest. The observation count of all
// landmarks is identical. The method returns the landmark ID that should
// be preserved because of keypoint per keyframe threshold violation.
const vi_map::LandmarkId&
MapSparsification::generateMapToTestKeyframeConstraints() {
const pose_graph::VertexId additional_vertex =
generator_->createVertex(mission_id_, T_G_I_[0]);
pose_graph::VertexIdList vertices_minus_first_and_last;
vertices_minus_first_and_last.assign(
vertex_ids_ + 1, vertex_ids_ + kNumVertices - 1);
for (unsigned int i = 1; i < kNumLandmarks; ++i) {
landmark_ids_[i] = generator_->createLandmark(
p_G_fi_[i], vertex_ids_[0], vertices_minus_first_and_last);
}
pose_graph::VertexIdList vertices_minus_first_plus_additional;
vertices_minus_first_plus_additional.assign(
vertex_ids_ + 1, vertex_ids_ + kNumVertices);
vertices_minus_first_plus_additional.push_back(additional_vertex);
// Additional link s.t. all landmarks have idential number of observers.
landmark_ids_[0] = generator_->createLandmark(
p_G_fi_[0], vertex_ids_[0], vertices_minus_first_plus_additional);
generator_->generateMap();
return landmark_ids_[0];
}
void MapSparsification::buildMapSummarizer() {
using map_sparsification::cost_functions::IsRequiredToConstrainKeyframesCost;
using map_sparsification::scoring::ObservationCountScoringFunction;
using map_sparsification::scoring::DescriptorVarianceScoring;
const double kDescriptorDevThreshold = 30.0;
const int kMinKeyframesPerKeypoint = 5;
DescriptorVarianceScoring::Ptr descriptor_dev_score(
new DescriptorVarianceScoring(kDescriptorDevThreshold));
IsRequiredToConstrainKeyframesCost::Ptr keyframe_keypoint_cost(
new IsRequiredToConstrainKeyframesCost(kMinKeyframesPerKeypoint));
ObservationCountScoringFunction::Ptr obs_count_score(
new ObservationCountScoringFunction);
const double kDescriptorVarianceWeight = 0.2;
const double kObsCountWeight = 1.0;
const double kKeyframeConstraintWeight = 1.0;
descriptor_dev_score->setWeight(kDescriptorVarianceWeight);
obs_count_score->setWeight(kObsCountWeight);
keyframe_keypoint_cost->setWeight(kKeyframeConstraintWeight);
// Squared loss.
std::function<double(double)> keyframe_constraint_loss = // NOLINT
[](double x) {
const double kLinearFactor = 5.0;
return kLinearFactor * x * x;
}; // NOLINT
keyframe_keypoint_cost->setLossFunction(keyframe_constraint_loss);
sampler_.registerScoringFunction(obs_count_score);
sampler_.registerScoringFunction(descriptor_dev_score);
sampler_.registerCostFunction(keyframe_keypoint_cost);
}
void MapSparsification::sample(
vi_map::LandmarkIdSet* summary_store_landmark_ids) {
CHECK_NOTNULL(summary_store_landmark_ids);
sampler_.sample(
*generator_map_, kNumDesiredNumLandmarks, summary_store_landmark_ids);
}
void MapSparsification::expectRemovedLandmark(
const vi_map::LandmarkIdSet& summary_landmark_ids,
const vi_map::LandmarkId& deleted_landmark) const {
EXPECT_EQ(0u, summary_landmark_ids.count(deleted_landmark));
for (unsigned int i = 0; i < kNumLandmarks; ++i) {
if (landmark_ids_[i] != deleted_landmark) {
EXPECT_EQ(1u, summary_landmark_ids.count(landmark_ids_[i]));
}
}
}
void MapSparsification::expectPreservedLandmark(
const vi_map::LandmarkIdSet& summary_landmark_ids,
const vi_map::LandmarkId& preserved_landmark) const {
// Expect that preserved_landmark is indeed preserved.
EXPECT_EQ(1u, summary_landmark_ids.count(preserved_landmark));
int num_preserved_landmarks = 0;
for (unsigned int i = 0; i < kNumLandmarks; ++i) {
if (summary_landmark_ids.count(landmark_ids_[i]) > 0u) {
++num_preserved_landmarks;
}
}
// Other landmarks could be deleted, but the total number has to match
// the desired number.
EXPECT_EQ(getNumDesiredLandmarks(), num_preserved_landmarks);
}
TEST_F(MapSparsification, ObservationCountSparsificationTest) {
const vi_map::LandmarkId& landmark_to_be_deleted =
generateMapToTestObservationCount();
vi_map::LandmarkIdSet summary_landmark_list;
sample(&summary_landmark_list);
expectRemovedLandmark(summary_landmark_list, landmark_to_be_deleted);
EXPECT_EQ(getNumDesiredLandmarks(), summary_landmark_list.size());
}
TEST_F(MapSparsification, KeyframeKeypointConstraintSparsificationTest) {
const vi_map::LandmarkId& landmark_to_be_preserved =
generateMapToTestKeyframeConstraints();
vi_map::LandmarkIdSet summary_landmark_list;
sample(&summary_landmark_list);
expectPreservedLandmark(summary_landmark_list, landmark_to_be_preserved);
}
MAPLAB_UNITTEST_ENTRYPOINT
| 35.301255
| 88
| 0.775276
|
AdronTech
|
42ce01cbee2b709316f050822d10df725830726d
| 6,865
|
cpp
|
C++
|
eb/src/v20210416/model/EventBus.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | 1
|
2022-01-27T09:27:34.000Z
|
2022-01-27T09:27:34.000Z
|
eb/src/v20210416/model/EventBus.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | null | null | null |
eb/src/v20210416/model/EventBus.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/eb/v20210416/model/EventBus.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Eb::V20210416::Model;
using namespace std;
EventBus::EventBus() :
m_modTimeHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_addTimeHasBeenSet(false),
m_eventBusNameHasBeenSet(false),
m_eventBusIdHasBeenSet(false),
m_typeHasBeenSet(false)
{
}
CoreInternalOutcome EventBus::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("ModTime") && !value["ModTime"].IsNull())
{
if (!value["ModTime"].IsString())
{
return CoreInternalOutcome(Core::Error("response `EventBus.ModTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_modTime = string(value["ModTime"].GetString());
m_modTimeHasBeenSet = true;
}
if (value.HasMember("Description") && !value["Description"].IsNull())
{
if (!value["Description"].IsString())
{
return CoreInternalOutcome(Core::Error("response `EventBus.Description` IsString=false incorrectly").SetRequestId(requestId));
}
m_description = string(value["Description"].GetString());
m_descriptionHasBeenSet = true;
}
if (value.HasMember("AddTime") && !value["AddTime"].IsNull())
{
if (!value["AddTime"].IsString())
{
return CoreInternalOutcome(Core::Error("response `EventBus.AddTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_addTime = string(value["AddTime"].GetString());
m_addTimeHasBeenSet = true;
}
if (value.HasMember("EventBusName") && !value["EventBusName"].IsNull())
{
if (!value["EventBusName"].IsString())
{
return CoreInternalOutcome(Core::Error("response `EventBus.EventBusName` IsString=false incorrectly").SetRequestId(requestId));
}
m_eventBusName = string(value["EventBusName"].GetString());
m_eventBusNameHasBeenSet = true;
}
if (value.HasMember("EventBusId") && !value["EventBusId"].IsNull())
{
if (!value["EventBusId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `EventBus.EventBusId` IsString=false incorrectly").SetRequestId(requestId));
}
m_eventBusId = string(value["EventBusId"].GetString());
m_eventBusIdHasBeenSet = true;
}
if (value.HasMember("Type") && !value["Type"].IsNull())
{
if (!value["Type"].IsString())
{
return CoreInternalOutcome(Core::Error("response `EventBus.Type` IsString=false incorrectly").SetRequestId(requestId));
}
m_type = string(value["Type"].GetString());
m_typeHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void EventBus::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_modTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ModTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_modTime.c_str(), allocator).Move(), allocator);
}
if (m_descriptionHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Description";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_description.c_str(), allocator).Move(), allocator);
}
if (m_addTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "AddTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_addTime.c_str(), allocator).Move(), allocator);
}
if (m_eventBusNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "EventBusName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_eventBusName.c_str(), allocator).Move(), allocator);
}
if (m_eventBusIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "EventBusId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_eventBusId.c_str(), allocator).Move(), allocator);
}
if (m_typeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Type";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_type.c_str(), allocator).Move(), allocator);
}
}
string EventBus::GetModTime() const
{
return m_modTime;
}
void EventBus::SetModTime(const string& _modTime)
{
m_modTime = _modTime;
m_modTimeHasBeenSet = true;
}
bool EventBus::ModTimeHasBeenSet() const
{
return m_modTimeHasBeenSet;
}
string EventBus::GetDescription() const
{
return m_description;
}
void EventBus::SetDescription(const string& _description)
{
m_description = _description;
m_descriptionHasBeenSet = true;
}
bool EventBus::DescriptionHasBeenSet() const
{
return m_descriptionHasBeenSet;
}
string EventBus::GetAddTime() const
{
return m_addTime;
}
void EventBus::SetAddTime(const string& _addTime)
{
m_addTime = _addTime;
m_addTimeHasBeenSet = true;
}
bool EventBus::AddTimeHasBeenSet() const
{
return m_addTimeHasBeenSet;
}
string EventBus::GetEventBusName() const
{
return m_eventBusName;
}
void EventBus::SetEventBusName(const string& _eventBusName)
{
m_eventBusName = _eventBusName;
m_eventBusNameHasBeenSet = true;
}
bool EventBus::EventBusNameHasBeenSet() const
{
return m_eventBusNameHasBeenSet;
}
string EventBus::GetEventBusId() const
{
return m_eventBusId;
}
void EventBus::SetEventBusId(const string& _eventBusId)
{
m_eventBusId = _eventBusId;
m_eventBusIdHasBeenSet = true;
}
bool EventBus::EventBusIdHasBeenSet() const
{
return m_eventBusIdHasBeenSet;
}
string EventBus::GetType() const
{
return m_type;
}
void EventBus::SetType(const string& _type)
{
m_type = _type;
m_typeHasBeenSet = true;
}
bool EventBus::TypeHasBeenSet() const
{
return m_typeHasBeenSet;
}
| 27.242063
| 139
| 0.675455
|
suluner
|
42cf83246cfd5df550b96a6efeb7aec0a7007eb6
| 2,965
|
cpp
|
C++
|
src/core/SettingsManager.cpp
|
tinfah/nvidia-system-monitor-qt
|
805b7ba49c879c6d6d0af576292274e60148353f
|
[
"MIT"
] | null | null | null |
src/core/SettingsManager.cpp
|
tinfah/nvidia-system-monitor-qt
|
805b7ba49c879c6d6d0af576292274e60148353f
|
[
"MIT"
] | null | null | null |
src/core/SettingsManager.cpp
|
tinfah/nvidia-system-monitor-qt
|
805b7ba49c879c6d6d0af576292274e60148353f
|
[
"MIT"
] | null | null | null |
#include "SettingsManager.h"
#include "NVSMIParser.h"
#include <QJsonArray>
#define constant(name) constexpr char name[] = "Graph/" #name
namespace Constants {
constant(gpuColors);
constant(updateDelay);
constant(length);
}
QVarLengthArray<QString> SettingsManager::m_gpuNames;
QVarLengthArray<QColor> SettingsManager::m_gpuColors;
uint SettingsManager::m_updateDelay;
uint SettingsManager::m_graphLength;
uint SettingsManager::m_gpuCount;
void SettingsManager::init() {
NVSMIParser::init();
m_gpuCount = NVSMIParser::getGPUCount();
m_gpuNames = NVSMIParser::getGPUNames();
}
void SettingsManager::load() {
using namespace Constants;
QSettings settings(NVSM_SETTINGS);
m_updateDelay = settings.value(updateDelay, 2000).toUInt();
m_graphLength = settings.value(length, 60000).toUInt();
// load gpu colors
{
auto array = settings.value(gpuColors).toJsonArray();
m_gpuColors.resize(array.size());
for (uint i = 0; i < array.size(); i++) {
m_gpuColors[i] = QColor(array[i].toInt());
}
}
if (m_gpuColors.size() < m_gpuCount) {
auto gpuColorsSize = m_gpuColors.size();
m_gpuColors.resize(m_gpuCount);
QColor defaultGPUColors[8] = {
{0, 255, 0},
{0, 0, 255},
{255, 0, 0},
{255, 255, 0},
{255, 0, 255},
{0, 255, 255},
{255, 255, 255},
{32, 32, 32}
};
for (uint i = gpuColorsSize; i < m_gpuCount; i++) {
m_gpuColors[i] = defaultGPUColors[i % 8];
}
}
}
void SettingsManager::save() {
using namespace Constants;
QSettings settings(NVSM_SETTINGS);
settings.setValue(updateDelay, m_updateDelay);
settings.setValue(length, m_graphLength);
settings.setValue(gpuColors, [&]() {
QJsonArray array;
for (const auto &color : m_gpuColors)
array.append(color.value());
return array;
}());
}
void SettingsManager::setGPUColors(const QVarLengthArray<QColor> &gpuColors) {
m_gpuColors = gpuColors;
}
void SettingsManager::setUpdateDelay(uint updateDelay) {
m_updateDelay = updateDelay;
}
void SettingsManager::setGraphLength(uint graphLength) {
m_graphLength = graphLength;
}
void SettingsManager::setGPUColor(uint index, const QColor &color) {
m_gpuColors[index] = color;
}
const QVarLengthArray<QString>& SettingsManager::getGPUNames() {
return m_gpuNames;
}
const QVarLengthArray<QColor>& SettingsManager::getGPUColors() {
return m_gpuColors;
}
const QString& SettingsManager::getGPUName(uint index) {
return m_gpuNames[index];
}
const QColor& SettingsManager::getGPUColor(uint index) {
return m_gpuColors[index];
}
uint SettingsManager::getUpdateDelay() {
return m_updateDelay;
}
uint SettingsManager::getGraphLength() {
return m_graphLength;
}
uint SettingsManager::getGPUCount() {
return m_gpuCount;
}
| 23.531746
| 78
| 0.661046
|
tinfah
|
42d3f4d158020b542d3c89f337537ba5017fb838
| 17,542
|
cc
|
C++
|
meter_multical21.cc
|
IBUSOL/wmbusmeters
|
6786caaec646db23a1ad057692609e22cecfa029
|
[
"MIT"
] | null | null | null |
meter_multical21.cc
|
IBUSOL/wmbusmeters
|
6786caaec646db23a1ad057692609e22cecfa029
|
[
"MIT"
] | null | null | null |
meter_multical21.cc
|
IBUSOL/wmbusmeters
|
6786caaec646db23a1ad057692609e22cecfa029
|
[
"MIT"
] | 1
|
2019-12-01T08:19:51.000Z
|
2019-12-01T08:19:51.000Z
|
// Copyright (c) 2017 Fredrik Öhrström
//
// 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"aes.h"
#include"meters.h"
#include"wmbus.h"
#include"util.h"
#include<memory.h>
#include<stdio.h>
#include<string>
#include<time.h>
#include<vector>
using namespace std;
#define INFO_CODE_DRY 0x01
#define INFO_CODE_DRY_SHIFT (4+0)
#define INFO_CODE_REVERSE 0x02
#define INFO_CODE_REVERSE_SHIFT (4+3)
#define INFO_CODE_LEAK 0x04
#define INFO_CODE_LEAK_SHIFT (4+6)
#define INFO_CODE_BURST 0x08
#define INFO_CODE_BURST_SHIFT (4+9)
struct MeterMultical21 : public Meter {
MeterMultical21(WMBus *bus, const char *name, const char *id, const char *key);
string id();
string name();
// Total water counted through the meter
float totalWaterConsumption();
bool hasTotalWaterConsumption();
// Meter sends target water consumption or max flow, depending on meter configuration
// We can see which was sent inside the wmbus message!
// Target water consumption: The total consumption at the start of the previous 30 day period.
float targetWaterConsumption();
bool hasTargetWaterConsumption();
// Max flow during last month or last 24 hours depending on meter configuration.
float maxFlow();
bool hasMaxFlow();
// statusHumanReadable: DRY,REVERSED,LEAK,BURST if that status is detected right now, followed by
// (dry 15-21 days) which means that, even it DRY is not active right now,
// DRY has been active for 15-21 days during the last 30 days.
string statusHumanReadable();
string status();
string timeDry();
string timeReversed();
string timeLeaking();
string timeBursting();
string datetimeOfUpdateHumanReadable();
string datetimeOfUpdateRobot();
void onUpdate(function<void(Meter*)> cb);
int numUpdates();
private:
void handleTelegram(Telegram*t);
void processContent(vector<uchar> &d);
string decodeTime(int time);
int info_codes_;
float total_water_consumption_;
bool has_total_water_consumption_;
float target_volume_;
bool has_target_volume_;
float max_flow_;
bool has_max_flow_;
time_t datetime_of_update_;
string name_;
vector<uchar> id_;
vector<uchar> key_;
WMBus *bus_;
vector<function<void(Meter*)>> on_update_;
int num_updates_;
bool matches_any_id_;
bool use_aes_;
};
MeterMultical21::MeterMultical21(WMBus *bus, const char *name, const char *id, const char *key) :
info_codes_(0), total_water_consumption_(0), has_total_water_consumption_(false),
target_volume_(0), has_target_volume_(false),
max_flow_(0), has_max_flow_(false), name_(name), bus_(bus), num_updates_(0),
matches_any_id_(false), use_aes_(true)
{
if (strlen(id) == 0) {
matches_any_id_ = true;
} else {
hex2bin(id, &id_);
}
if (strlen(key) == 0) {
use_aes_ = false;
} else {
hex2bin(key, &key_);
}
bus_->onTelegram(calll(this,handleTelegram,Telegram*));
}
string MeterMultical21::id()
{
return bin2hex(id_);
}
string MeterMultical21::name()
{
return name_;
}
void MeterMultical21::onUpdate(function<void(Meter*)> cb)
{
on_update_.push_back(cb);
}
int MeterMultical21::numUpdates()
{
return num_updates_;
}
float MeterMultical21::totalWaterConsumption()
{
return total_water_consumption_;
}
bool MeterMultical21::hasTotalWaterConsumption()
{
return has_total_water_consumption_;
}
float MeterMultical21::targetWaterConsumption()
{
return target_volume_;
}
bool MeterMultical21::hasTargetWaterConsumption()
{
return has_target_volume_;
}
float MeterMultical21::maxFlow()
{
return max_flow_;
}
bool MeterMultical21::hasMaxFlow()
{
return has_max_flow_;
}
string MeterMultical21::datetimeOfUpdateHumanReadable()
{
char datetime[40];
memset(datetime, 0, sizeof(datetime));
strftime(datetime, 20, "%Y-%m-%d %H:%M.%S", localtime(&datetime_of_update_));
return string(datetime);
}
string MeterMultical21::datetimeOfUpdateRobot()
{
char datetime[40];
memset(datetime, 0, sizeof(datetime));
// This is the date time in the Greenwich timezone, dont get surprised!
strftime(datetime, sizeof(datetime), "%FT%TZ", gmtime(&datetime_of_update_));
return string(datetime);
}
Meter *createMultical21(WMBus *bus, const char *name, const char *id, const char *key) {
return new MeterMultical21(bus,name,id,key);
}
void MeterMultical21::handleTelegram(Telegram *t) {
if (matches_any_id_ || (
t->m_field == MANUFACTURER_KAM &&
t->a_field_address[3] == id_[3] &&
t->a_field_address[2] == id_[2] &&
t->a_field_address[1] == id_[1] &&
t->a_field_address[0] == id_[0])) {
verbose("Meter %s receives update with id %02x%02x%02x%02x!\n",
name_.c_str(),
t->a_field_address[0], t->a_field_address[1], t->a_field_address[2],
t->a_field_address[3]);
} else {
verbose("Meter %s ignores message with id %02x%02x%02x%02x \n",
name_.c_str(),
t->a_field_address[0], t->a_field_address[1], t->a_field_address[2],
t->a_field_address[3]);
return;
}
// This is part of the wmbus protocol, should be moved to wmbus source files!
int cc_field = t->payload[0];
verbose("CC field=%02x ( ", cc_field);
if (cc_field & CC_B_BIDIRECTIONAL_BIT) verbose("bidir ");
if (cc_field & CC_RD_RESPONSE_DELAY_BIT) verbose("fast_res ");
else verbose("slow_res ");
if (cc_field & CC_S_SYNCH_FRAME_BIT) verbose("synch ");
if (cc_field & CC_R_RELAYED_BIT) verbose("relayed "); // Relayed by a repeater
if (cc_field & CC_P_HIGH_PRIO_BIT) verbose("prio ");
verbose(")\n");
int acc = t->payload[1];
verbose("ACC field=%02x\n", acc);
uchar sn[4];
sn[0] = t->payload[2];
sn[1] = t->payload[3];
sn[2] = t->payload[4];
sn[3] = t->payload[5];
verbose("SN=%02x%02x%02x%02x encrypted=", sn[3], sn[2], sn[1], sn[0]);
if ((sn[3] & SN_ENC_BITS) == 0) verbose("no\n");
else if ((sn[3] & SN_ENC_BITS) == 0x40) verbose("yes\n");
else verbose("? %d\n", sn[3] & SN_ENC_BITS);
// The content begins with the Payload CRC at offset 6.
vector<uchar> content;
content.insert(content.end(), t->payload.begin()+6, t->payload.end());
size_t remaining = content.size();
if (remaining > 16) remaining = 16;
uchar iv[16];
int i=0;
// M-field
iv[i++] = t->m_field&255; iv[i++] = t->m_field>>8;
// A-field
for (int j=0; j<6; ++j) { iv[i++] = t->a_field[j]; }
// CC-field
iv[i++] = cc_field;
// SN-field
for (int j=0; j<4; ++j) { iv[i++] = sn[j]; }
// FN
iv[i++] = 0; iv[i++] = 0;
// BC
iv[i++] = 0;
if (use_aes_) {
vector<uchar> ivv(iv, iv+16);
verbose("Decrypting\n");
string s = bin2hex(ivv);
verbose("IV %s\n", s.c_str());
uchar xordata[16];
AES_ECB_encrypt(iv, &key_[0], xordata, 16);
uchar decrypt[16];
xorit(xordata, &content[0], decrypt, remaining);
vector<uchar> dec(decrypt, decrypt+remaining);
string answer = bin2hex(dec);
verbose("Decrypted >%s<\n", answer.c_str());
if (content.size() > 22) {
fprintf(stderr, "Received too many bytes of content from a Multical21 meter!\n"
"Got %zu bytes, expected at most 22.\n", content.size());
}
if (content.size() > 16) {
// Yay! Lets decrypt a second block. Full frame content is 22 bytes.
// So a second block should enough for everyone!
remaining = content.size()-16;
if (remaining > 16) remaining = 16; // Should not happen.
incrementIV(iv, sizeof(iv));
vector<uchar> ivv2(iv, iv+16);
string s2 = bin2hex(ivv2);
verbose("IV+1 %s\n", s2.c_str());
AES_ECB_encrypt(iv, &key_[0], xordata, 16);
xorit(xordata, &content[16], decrypt, remaining);
vector<uchar> dec2(decrypt, decrypt+remaining);
string answer2 = bin2hex(dec2);
verbose("Decrypted second block >%s<\n", answer2.c_str());
// Append the second decrypted block to the first.
dec.insert(dec.end(), dec2.begin(), dec2.end());
}
content.clear();
content.insert(content.end(), dec.begin(), dec.end());
}
processContent(content);
datetime_of_update_ = time(NULL);
num_updates_++;
for (auto &cb : on_update_) if (cb) cb(this);
}
float getScaleFactor(int vif) {
switch (vif) {
case 0x13: return 1000.0;
case 0x14: return 100.0;
case 0x15: return 10.0;
case 0x16: return 10.0;
}
fprintf(stderr, "Warning! Unknown vif code %d for scale factor.\n", vif);
return 1000.0;
}
void MeterMultical21::processContent(vector<uchar> &c) {
int crc0 = c[0];
int crc1 = c[1];
int frame_type = c[2];
verbose("CRC16: %02x%02x\n", crc1, crc0);
/*
uint16_t crc = crc16(&(c[2]), c.size()-2);
verbose("CRC16 calc: %04x\n", crc);
*/
if (frame_type == 0x79) {
verbose("Short frame %d bytes\n", c.size());
if (c.size() != 15) {
fprintf(stderr, "Warning! Unexpected length of frame %zu. Expected 15 bytes!\n", c.size());
}
/*int ecrc0 = c[3];
int ecrc1 = c[4];
int ecrc2 = c[5];
int ecrc3 = c[6];*/
int rec1val0 = c[7];
int rec1val1 = c[8];
int rec2val0 = c[9];
int rec2val1 = c[10];
int rec2val2 = c[11];
int rec2val3 = c[12];
int rec3val0 = c[13];
int rec3val1 = c[14];
info_codes_ = rec1val1*256+rec1val0;
verbose("short rec1 %02x %02x info codes\n", rec1val1, rec1val0);
int consumption_raw = rec2val3*256*256*256 + rec2val2*256*256 + rec2val1*256 + rec2val0;
verbose("short rec2 %02x %02x %02x %02x = %d total consumption\n", rec2val3, rec2val2, rec2val1, rec2val0, consumption_raw);
// The dif=0x04 vif=0x13 means current volume with scale factor .001
total_water_consumption_ = ((float)consumption_raw) / ((float)1000);
has_total_water_consumption_ = true;
// The short frame target volume supplies two low bytes,
// the remaining two hi bytes are >>probably<< picked from rec2!
int target_volume_raw = rec2val3*256*256*256 + rec2val2*256*256 + rec3val1*256 + rec3val0;
verbose("short rec3 (%02x %02x) %02x %02x = %d target volume\n", rec2val3, rec2val2, rec3val1, rec3val0, target_volume_raw);
target_volume_ = ((float)target_volume_raw) / ((float)1000);
has_target_volume_ = true;
} else
if (frame_type == 0x78) {
verbose("Full frame %d bytes\n", c.size());
if (c.size() != 22) {
fprintf(stderr, "Warning! Unexpected length of frame %zu. Expected 22 bytes!\n", c.size());
}
int rec1dif = c[3];
int rec1vif = c[4];
int rec1vife = c[5];
int rec1val0 = c[6];
int rec1val1 = c[7];
int rec2dif = c[8];
int rec2vif = c[9];
int rec2val0 = c[10];
int rec2val1 = c[11];
int rec2val2 = c[12];
int rec2val3 = c[13];
int rec3dif = c[14];
int rec3vif = c[15];
int rec3val0 = c[16];
int rec3val1 = c[17];
int rec3val2 = c[18];
int rec3val3 = c[19];
// There are two more bytes in the data. Unknown purpose.
int rec4val0 = c[20];
int rec4val1 = c[21];
if (rec1dif != 0x02 || rec1vif != 0xff || rec1vife != 0x20 ) {
fprintf(stderr, "Warning unexpected field! Expected info codes\n"
"with dif=0x02 vif=0xff vife=0x20 but got dif=%02x vif=%02x vife=%02x\n", rec1dif, rec1vif, rec1vife);
}
info_codes_ = rec1val1*256+rec1val0;
verbose("full rec1 dif=%02x vif=%02x vife=%02x\n", rec1dif, rec1vif, rec1vife);
verbose("full rec1 %02x %02x info codes\n", rec1val1, rec1val0);
if (rec2dif != 0x04 || rec2vif != 0x13) {
fprintf(stderr, "Warning unexpected field! Expected current volume\n"
"with dif=0x04 vif=0x13 but got dif=%02x vif=%02x\n", rec2dif, rec2vif);
}
int consumption_raw = rec2val3*256*256*256 + rec2val2*256*256 + rec2val1*256 + rec2val0;
verbose("full rec2 dif=%02x vif=%02x\n", rec2dif, rec2vif);
verbose("full rec2 %02x %02x %02x %02x = %d total consumption\n", rec2val3, rec2val2, rec2val1, rec2val0, consumption_raw);
// The dif=0x04 vif=0x13 means current volume with scale factor .001
total_water_consumption_ = ((float)consumption_raw) / ((float)1000);
has_total_water_consumption_ = true;
if (rec3dif != 0x44 || rec3vif != 0x13) {
fprintf(stderr, "Warning unexpecte field! Expected target volume (ie volume recorded on first day of month)\n"
"with dif=0x44 vif=0x13 but got dif=%02x vif=%02x\n", rec3dif, rec3vif);
}
int target_volume_raw = rec3val3*256*256*256 + rec3val2*256*256 + rec3val1*256 + rec3val0;
verbose("full rec3 dif=%02x vif=%02x\n", rec3dif, rec3vif);
verbose("full rec3 %02x %02x %02x %02x = %d target volume\n", rec3val3, rec3val2, rec3val1, rec3val0, target_volume_raw);
target_volume_ = ((float)target_volume_raw) / ((float)1000);
has_target_volume_ = true;
// To unknown bytes, seems to be very constant.
verbose("full rec4 %02x %02x = unknown\n", rec4val1, rec4val0);
} else {
fprintf(stderr, "Unknown frame %02x\n", frame_type);
}
}
string MeterMultical21::status() {
string s;
if (info_codes_ & INFO_CODE_DRY) s.append("DRY ");
if (info_codes_ & INFO_CODE_REVERSE) s.append("REVERSED ");
if (info_codes_ & INFO_CODE_LEAK) s.append("LEAK ");
if (info_codes_ & INFO_CODE_BURST) s.append("BURST ");
if (s.length() > 0) {
s.pop_back(); // Remove final space
return s;
}
return s;
}
string MeterMultical21::timeDry() {
int time_dry = (info_codes_ >> INFO_CODE_DRY_SHIFT) & 7;
if (time_dry) {
return decodeTime(time_dry);
}
return "";
}
string MeterMultical21::timeReversed() {
int time_reversed = (info_codes_ >> INFO_CODE_REVERSE_SHIFT) & 7;
if (time_reversed) {
return decodeTime(time_reversed);
}
return "";
}
string MeterMultical21::timeLeaking() {
int time_leaking = (info_codes_ >> INFO_CODE_LEAK_SHIFT) & 7;
if (time_leaking) {
return decodeTime(time_leaking);
}
return "";
}
string MeterMultical21::timeBursting() {
int time_bursting = (info_codes_ >> INFO_CODE_BURST_SHIFT) & 7;
if (time_bursting) {
return decodeTime(time_bursting);
}
return "";
}
string MeterMultical21::statusHumanReadable() {
string s;
bool dry = info_codes_ & INFO_CODE_DRY;
int time_dry = (info_codes_ >> INFO_CODE_DRY_SHIFT) & 7;
if (dry || time_dry) {
if (dry) s.append("DRY");
s.append("(dry ");
s.append(decodeTime(time_dry));
s.append(") ");
}
bool reversed = info_codes_ & INFO_CODE_REVERSE;
int time_reversed = (info_codes_ >> INFO_CODE_REVERSE_SHIFT) & 7;
if (reversed || time_reversed) {
if (dry) s.append("REVERSED");
s.append("(rev ");
s.append(decodeTime(time_reversed));
s.append(") ");
}
bool leak = info_codes_ & INFO_CODE_LEAK;
int time_leak = (info_codes_ >> INFO_CODE_LEAK_SHIFT) & 7;
if (leak || time_leak) {
if (dry) s.append("LEAK");
s.append("(leak ");
s.append(decodeTime(time_leak));
s.append(") ");
}
bool burst = info_codes_ & INFO_CODE_BURST;
int time_burst = (info_codes_ >> INFO_CODE_BURST_SHIFT) & 7;
if (burst || time_burst) {
if (dry) s.append("BURST");
s.append("(burst ");
s.append(decodeTime(time_burst));
s.append(") ");
}
if (s.length() > 0) {
s.pop_back();
return s;
}
return "OK";
}
string MeterMultical21::decodeTime(int time) {
if (time>7) {
fprintf(stderr, "Error when decoding time %d\n", time);
}
switch (time) {
case 0:
return "0 hours";
case 1:
return "1-8 hours";
case 2:
return "9-24 hours";
case 3:
return "2-3 days";
case 4:
return "4-7 days";
case 5:
return "8-14 days";
case 6:
return "15-21 days";
case 7:
return "22-31 days";
default:
return "?";
}
}
| 31.66426
| 133
| 0.627009
|
IBUSOL
|
42d50924ec6b5490b3c68609206c657cf4829a4e
| 1,068
|
cpp
|
C++
|
scene.cpp
|
malinowskikam/OpenGLEngine
|
146119967382283db8dc458cfa07b740c7accfc1
|
[
"MIT"
] | null | null | null |
scene.cpp
|
malinowskikam/OpenGLEngine
|
146119967382283db8dc458cfa07b740c7accfc1
|
[
"MIT"
] | null | null | null |
scene.cpp
|
malinowskikam/OpenGLEngine
|
146119967382283db8dc458cfa07b740c7accfc1
|
[
"MIT"
] | null | null | null |
#include "include.hpp"
extern Global *global;
Scene::Scene()
{
this->cameraRotation = glm::vec3(0.0f,-(M_PI/2.0),0.0f);//pitch, yaw, roll
this->cameraPosition = glm::vec3(0.0f,0.0f,0.0f);
this->cameraUp = glm::vec3(0.0,1.0,0.0);
}
void Scene::updateLookingAngle()
{
glm::vec3 direction;
direction.x = cos(cameraRotation[1]) * cos(cameraRotation[0]);
direction.y = sin(cameraRotation[0]);
direction.z = sin(cameraRotation[1]) * cos(cameraRotation[0]);
this->cameraFront = glm::normalize(direction);
this->cameraFrontXZ = glm::normalize(glm::vec3(cameraFront.x,0.0,cameraFront.z));
this->cameraLocalX = glm::normalize(glm::cross(cameraFront,this->cameraUp));
this->projectionMatrix = glm::perspective(glm::radians(global->cameraFov), global->windowWidth/(float)(global->windowHeight), global->drawStart, global->drawEnd);
this->viewMatrix = glm::lookAt(cameraPosition,cameraPosition+cameraFront,cameraUp);
this->projViewMatrix = this->projectionMatrix * this->viewMatrix;
}
void updateCameraPosition()
{
}
| 33.375
| 166
| 0.698502
|
malinowskikam
|
42d910b6ddbd2e5c0372fbc68b84ae05b5cea2b9
| 1,491
|
hpp
|
C++
|
utility.hpp
|
YuexuanX/WSDAD-MODEL
|
e24a566f6a4f54b7ab780a7a852b4801a411eede
|
[
"BSD-2-Clause"
] | 29
|
2018-08-01T00:27:16.000Z
|
2021-12-16T06:20:46.000Z
|
utility.hpp
|
YuexuanX/WSDAD-MODEL
|
e24a566f6a4f54b7ab780a7a852b4801a411eede
|
[
"BSD-2-Clause"
] | 2
|
2018-09-05T07:07:17.000Z
|
2019-05-20T23:26:12.000Z
|
utility.hpp
|
YuexuanX/WSDAD-MODEL
|
e24a566f6a4f54b7ab780a7a852b4801a411eede
|
[
"BSD-2-Clause"
] | 8
|
2018-08-29T02:53:31.000Z
|
2021-06-15T06:11:55.000Z
|
/*
* utitlity.h
*
* Created on: Mar 27, 2015
* Author: Tadeze
*/
#ifndef UTILITY_HPP_
#define UTILITY_HPP_
#include<iostream>
#include<fstream>
#include<sstream>
#include <cmath>
#include <cstdlib>
#include<ctime>
#include<algorithm>
#include<queue>
#include<string>
#include<iterator>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<random>
#include<utility>
#include "cincl.hpp"
/*
struct Data
{
int ncol;
int nrow;
std::vector<std::vector<double> > data;
};
*/
//default_random_engine gen(time(NULL));
int randomI(int min, int max);
int randomEx(int min, int max, std::set<int>& exlude);
void sampleI(int min, int max, int nsample, std::vector<int> &sampleIndx);
double avgPL(int n);
double randomD(double min, double max);
template<typename T>
T randomT(T min, T max);
void swapInt(int a, int b, int* x);
//template<typename T>
double mean(std::vector<double> points);
std::vector<std::vector<double> > readcsv(const char* filename, char delim,
bool header);
//extern std::ofstream ffile; //("log.txt");
std::map<double, double> ecdf(std::vector<double> points);
std::vector<double> ADdistance(const std::vector<std::vector<double> > &depths,
bool weightToTail);
//extern doubleframe* dt;
//log file
extern std::ofstream logfile;
extern std::string tmpVar;
double score(double depth, int n);
int dblcmp(double *a, double *b);
//extern Data *dt;
#endif
/* UTITLITY_H_ */
| 22.253731
| 80
| 0.68008
|
YuexuanX
|
42d96c18584be698a4fbb430af9f9bc341a2d455
| 368
|
cpp
|
C++
|
Codeforces/268A.cpp
|
DT3264/ProgrammingContestsSolutions
|
a297f2da654c2ca2815b9aa375c2b4ca0052269d
|
[
"MIT"
] | null | null | null |
Codeforces/268A.cpp
|
DT3264/ProgrammingContestsSolutions
|
a297f2da654c2ca2815b9aa375c2b4ca0052269d
|
[
"MIT"
] | null | null | null |
Codeforces/268A.cpp
|
DT3264/ProgrammingContestsSolutions
|
a297f2da654c2ca2815b9aa375c2b4ca0052269d
|
[
"MIT"
] | null | null | null |
#include<stdio.h>
int hosts[100];
int guests[100];
int main(){
int n, i, j, cont=0;
scanf("%d", &n);
for(i=0; i<n; i++){
scanf("%d%d", &hosts[i], &guests[i]);
}
for(i=0; i<n; i++){
for(j=0; j<n; j++){
if(hosts[i]==guests[j]){
cont++;
}
}
}
printf("%d", cont);
return 0;
}
| 18.4
| 45
| 0.38587
|
DT3264
|
42e11bfe05e3e9861fa72326adb324ff1ea96969
| 2,325
|
cpp
|
C++
|
Ouroboros/Source/oGfx/surface_view.cpp
|
jiangzhu1212/oooii
|
fc00ff81e74adaafd9c98ba7c055f55d95a36e3b
|
[
"MIT"
] | null | null | null |
Ouroboros/Source/oGfx/surface_view.cpp
|
jiangzhu1212/oooii
|
fc00ff81e74adaafd9c98ba7c055f55d95a36e3b
|
[
"MIT"
] | null | null | null |
Ouroboros/Source/oGfx/surface_view.cpp
|
jiangzhu1212/oooii
|
fc00ff81e74adaafd9c98ba7c055f55d95a36e3b
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2014 Antony Arciuolo. See License.txt regarding use.
#include <oGfx/surface_view.h>
#include <oGPU/vertex_buffer.h>
namespace ouro { namespace gfx {
void surface_view::initialize(gfx::core& _core)
{
core = &_core;
active = nullptr;
vs.initialize("fullscreen_tri", core->device, gpu::intrinsic::byte_code(gpu::intrinsic::vertex_shader::fullscreen_tri));
ps.initialize("texture", core->device, gpu::intrinsic::byte_code(gpu::intrinsic::pixel_shader::texture2d));
}
void surface_view::deinitialize()
{
t1d.deinitialize();
t2d.deinitialize();
t3d.deinitialize();
tcube.deinitialize();
ps.deinitialize();
vs.deinitialize();
active = nullptr;
core = nullptr;
}
void surface_view::set_texels(const char* name, const surface::image& img)
{
t1d.deinitialize();
t2d.deinitialize();
t3d.deinitialize();
tcube.deinitialize();
inf = img.get_info();
if (inf.is_1d())
{
t1d.initialize(name, core->device, img, inf.mips());
active = &t1d;
oTHROW(operation_not_supported, "1d viewing not yet enabled");
}
else if (inf.is_2d())
{
t2d.initialize(name, core->device, img, inf.mips());
active = &t2d;
}
else if (inf.is_3d())
{
t3d.initialize(name, core->device, img, inf.mips());
active = &t3d;
oTHROW(operation_not_supported, "3d slice viewing not yet enabled");
}
else if (inf.is_cube())
{
tcube.initialize(name, core->device, img, inf.mips());
active = &tcube;
oTHROW(operation_not_supported, "cube slice viewing not yet enabled");
}
needs_update = 2;
}
void surface_view::render()
{
if (!ctarget || !*ctarget || !needs_update)
return;
auto& c = *core;
auto& ct = *ctarget;
auto& cl = c.device.immediate();
ct.clear(cl, black);
ct.set_draw_target(cl);
if (active)
{
c.bs.set(cl, gpu::blend_state::opaque);
c.dss.set(cl, gpu::depth_stencil_state::none);
c.rs.set(cl, gpu::rasterizer_state::front_face);
c.ss.set(cl, gpu::sampler_state::linear_wrap, gpu::sampler_state::linear_wrap);
c.ls.set(cl, gpu::intrinsic::vertex_layout::none, mesh::primitive_type::triangles);
vs.set(cl);
ps.set(cl);
active->set(cl, 0);
gpu::vertex_buffer::draw_unindexed(cl, 3);
}
if (present)
((gpu::primary_target&)ct).present();
needs_update--;
}
}}
| 23.72449
| 122
| 0.660645
|
jiangzhu1212
|
42e1f1a29fd3b5f53791ce5cb15d46938da0f5cf
| 1,294
|
cpp
|
C++
|
android-31/android/provider/Contacts_Organizations.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-31/android/provider/Contacts_Organizations.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-29/android/provider/Contacts_Organizations.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#include "../content/Context.hpp"
#include "../net/Uri.hpp"
#include "../../JString.hpp"
#include "../../JString.hpp"
#include "./Contacts_Organizations.hpp"
namespace android::provider
{
// Fields
JString Contacts_Organizations::CONTENT_DIRECTORY()
{
return getStaticObjectField(
"android.provider.Contacts$Organizations",
"CONTENT_DIRECTORY",
"Ljava/lang/String;"
);
}
android::net::Uri Contacts_Organizations::CONTENT_URI()
{
return getStaticObjectField(
"android.provider.Contacts$Organizations",
"CONTENT_URI",
"Landroid/net/Uri;"
);
}
JString Contacts_Organizations::DEFAULT_SORT_ORDER()
{
return getStaticObjectField(
"android.provider.Contacts$Organizations",
"DEFAULT_SORT_ORDER",
"Ljava/lang/String;"
);
}
// QJniObject forward
Contacts_Organizations::Contacts_Organizations(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
JString Contacts_Organizations::getDisplayLabel(android::content::Context arg0, jint arg1, JString arg2)
{
return callStaticObjectMethod(
"android.provider.Contacts$Organizations",
"getDisplayLabel",
"(Landroid/content/Context;ILjava/lang/CharSequence;)Ljava/lang/CharSequence;",
arg0.object(),
arg1,
arg2.object<jstring>()
);
}
} // namespace android::provider
| 23.962963
| 105
| 0.727202
|
YJBeetle
|
42e3d619d693b69d27ffe109fc599f1213f3b067
| 9,214
|
cpp
|
C++
|
main/main.cpp
|
tamim-asif/lgraph-private
|
733bbcd9e14a9850580b51c011e33785ab758b9d
|
[
"BSD-3-Clause"
] | null | null | null |
main/main.cpp
|
tamim-asif/lgraph-private
|
733bbcd9e14a9850580b51c011e33785ab758b9d
|
[
"BSD-3-Clause"
] | null | null | null |
main/main.cpp
|
tamim-asif/lgraph-private
|
733bbcd9e14a9850580b51c011e33785ab758b9d
|
[
"BSD-3-Clause"
] | null | null | null |
// This file is distributed under the BSD 3-Clause License. See LICENSE for details.
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <regex>
#include <string>
#include <vector>
#include <cctype>
#include <utility>
#include <iomanip>
#include <iostream>
#include "lgraph.hpp"
#include "eprp.hpp"
#include "replxx.hxx"
using Replxx = replxx::Replxx;
#include "main_api.hpp"
void help(const std::string &cmd, const std::string &txt) {
fmt::print("{:20s} {}\n",cmd,txt);
}
void help_labels(const std::string &cmd, const std::string &txt, bool required) {
if (required)
fmt::print(" {:20s} {} (required)\n",cmd,txt);
else
fmt::print(" {:20s} {} (optional)\n",cmd,txt);
}
// prototypes
Replxx::completions_t hook_completion(std::string const& context, int index, void* user_data);
Replxx::hints_t hook_hint(std::string const& context, int index, Replxx::Color& color, void* user_data);
void hook_color(std::string const& str, Replxx::colors_t& colors, void* user_data);
Replxx::completions_t hook_completion(std::string const& context, int index, void* user_data) {
auto* examples = static_cast<std::vector<std::string>*>(user_data);
Replxx::completions_t completions;
int last_cmd_start = context.size();
int last_cmd_end = context.size();
bool skipping_word = true;
for(int i=context.size();i>=0;i--) {
if (context[i] == ' ') {
skipping_word = false;
continue;
}
if (context[i] == '>')
break;
if (context[i] == ':') {
last_cmd_start = i;
last_cmd_end = i;
skipping_word = true;
}
if (!skipping_word) {
last_cmd_start = i;
}
}
std::vector<std::string> fields;
if (last_cmd_start< last_cmd_end) {
std::string cmd = context.substr(last_cmd_start,last_cmd_end);
auto pos = cmd.find(" ");
if (pos != std::string::npos) {
cmd = cmd.substr(0,pos);
}
//fmt::print("cmd[{}]\n", cmd);
Main_api::get_labels(cmd, [&fields](const std::string &label, const std::string txt, bool required) {
fields.push_back(label + ":");
});
if (!fields.empty())
examples = &fields;
}
std::string prefix {context.substr(index)};
for (auto const& e : *examples) {
if (e.compare(0, prefix.size(), prefix) == 0) {
completions.emplace_back(e.c_str());
}
}
return completions;
}
Replxx::hints_t hook_hint(std::string const& context, int index, Replxx::Color& color, void* user_data) {
auto* examples = static_cast<std::vector<std::string>*>(user_data);
Replxx::hints_t hints;
// only show hint if prefix is at least 'n' chars long
// or if prefix begins with a specific character
std::string prefix {context.substr(index)};
if (prefix.size() >= 2 || (! prefix.empty() && prefix.at(0) == '.')) {
for (auto const& e : *examples) {
if (e.compare(0, prefix.size(), prefix) == 0) {
hints.emplace_back(e.substr(prefix.size()).c_str());
}
}
}
// set hint color to green if single match found
if (hints.size() == 1) {
color = Replxx::Color::GREEN;
}
return hints;
}
int real_len( std::string const& s ) {
int len( 0 );
char m4( 128 + 64 + 32 + 16 );
char m3( 128 + 64 + 32 );
char m2( 128 + 64 );
for ( int i( 0 ); i < static_cast<int>( s.length() ); ++ i, ++ len ) {
char c( s[i] );
if ( ( c & m4 ) == m4 ) {
i += 3;
} else if ( ( c & m3 ) == m3 ) {
i += 2;
} else if ( ( c & m2 ) == m2 ) {
i += 1;
}
}
return ( len );
}
void hook_color(std::string const& context, Replxx::colors_t& colors, void* user_data) {
auto* regex_color = static_cast<std::vector<std::pair<std::string, Replxx::Color>>*>(user_data);
// highlight matching regex sequences
for (auto const& e : *regex_color) {
size_t pos {0};
std::string str = context;
std::smatch match;
while(std::regex_search(str, match, std::regex(e.first))) {
std::string c {match[0]};
pos += real_len( match.prefix() );
int len( real_len( c ) );
for (int i = 0; i < len; ++i) {
colors.at(pos + i) = e.second;
}
pos += len;
str = match.suffix();
}
}
}
int main() {
using cl = Replxx::Color;
std::vector<std::pair<std::string, cl>> regex_color {
// pipe operator
{"\\|\\>", cl::BRIGHTCYAN},
// method keywords
{"color_blue", cl::CYAN},
// commands
{"help", cl::BRIGHTMAGENTA},
{"history", cl::BRIGHTMAGENTA},
{"quit", cl::BRIGHTMAGENTA},
{"exit", cl::BRIGHTMAGENTA},
{"clear", cl::BRIGHTMAGENTA},
{"prompt", cl::BRIGHTMAGENTA},
// numbers
{"[\\-|+]{0,1}[0-9]+", cl::CYAN}, // integers
{"[\\-|+]{0,1}[0-9]*\\.[0-9]+", cl::CYAN}, // decimals
{"[\\-|+]{0,1}[0-9]+e[\\-|+]{0,1}[0-9]+", cl::CYAN}, // scientific notation
// registers
{"\\@\\w+", cl::MAGENTA},
// labels
{"\\w+\\:", cl::YELLOW},
};
// init the repl
Replxx rx;
rx.install_window_change_handler();
// words to be completed
std::vector<std::string> examples {
"help", "history", "quit", "exit", "clear", "prompt ",
};
// init all the lgraph libraries used
Main_api::init();
Main_api::get_commands([&examples](const std::string &cmd, const std::string &help_msg) {
examples.push_back(cmd);
});
const char *env_home = std::getenv("HOME");
if(env_home==0) {
std::cerr << "error: unset HOME directory??\n";
exit(-3);
}
// the path to the history file
std::string history_file(env_home);
history_file.append("/.config/lgraph/history.txt");
if ( access( history_file.c_str(), F_OK ) == -1 ) {
std::cout << "Setting history file to $HOME/.config/lgraph/history.txt\n";
std::string lgraph_path(env_home);
lgraph_path.append("/.config");
if ( access( lgraph_path.c_str(), F_OK ) == -1 ) {
int ok = mkdir(lgraph_path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if (ok<0) {
std::cerr << "error: could not create " << lgraph_path << " directory for history.txt\n";
exit(-3);
}
}
lgraph_path.append("/lgraph");
if ( access( lgraph_path.c_str(), F_OK ) == -1 ) {
int ok = mkdir(lgraph_path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if (ok<0) {
std::cerr << "error: could not create " << lgraph_path << " directory for history.txt\n";
exit(-3);
}
}
int ok = creat(history_file.c_str(), S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (ok<0) {
std::cerr << "error: could not create " << history_file << "\n";
exit(-3);
}
}
rx.history_load(history_file);
rx.set_max_history_size(8192);
rx.set_max_line_size(128);
rx.set_max_hint_rows(16);
rx.set_highlighter_callback(hook_color, static_cast<void*>(®ex_color));
rx.set_completion_callback(hook_completion, static_cast<void*>(&examples));
rx.set_hint_callback(hook_hint, static_cast<void*>(&examples));
std::cout
<< "Welcome to lgraph\n"
//<< "Press 'tab' to view autocompletions\n"
<< "Type '.help' for help\n"
<< "Type '.quit' or '.exit' to exit\n\n";
// set the repl prompt
std::string prompt {"\x1b[1;32mlgraph\x1b[0m> "};
// main repl loop
for (;;) {
// display the prompt and retrieve input from the user
char const *cinput{ nullptr };
do {
cinput = rx.input(prompt);
} while ( ( cinput == nullptr ) && ( errno == EAGAIN ) );
if (cinput == nullptr) {
break;
}
if (cinput[0]==0) {
continue; // Empty line
}
std::string input {cinput};
if (input.compare(0, 4, "quit") == 0 || input.compare(0, 4, "exit") == 0) {
rx.history_add(input);
break;
}else if (input.compare(0, 4, "help") == 0) {
auto pos = input.find(" ");
while(input[pos+1] == ' ')
pos++;
if (pos == std::string::npos) {
help("help [str]","this output, or for a specific command");
help("quit","exit lgraph");
help("exit","exit lgraph");
help("clear","clear the screen");
help("history","display the current history");
help("prompt <str>","change the current prompt");
Main_api::get_commands(help);
} else {
std::string cmd = input.substr(pos + 1);
auto pos2 = cmd.find(" ");
if (pos2 != std::string::npos)
cmd = cmd.substr(0,pos2);
help(cmd,Main_api::get_command_help(cmd));
Main_api::get_labels(cmd, help_labels);
}
rx.history_add(input);
continue;
}else if (input.compare(0, 6, "prompt") == 0) {
// set the repl prompt text
auto pos = input.find(" ");
if (pos == std::string::npos) {
std::cout << "Error: 'prompt' missing argument\n";
} else {
prompt = input.substr(pos + 1) + " ";
}
rx.history_add(input);
continue;
}else if (input.compare(0, 7, "history") == 0) {
// display the current history
for (size_t i = 0, sz = rx.history_size(); i < sz; ++i) {
std::cout << std::setw(4) << i << ": " << rx.history_line(i) << "\n";
}
rx.history_add(input);
continue;
}else if (input.compare(0, 5, "clear") == 0) {
// clear the screen
rx.clear_screen();
rx.history_add(input);
continue;
}else{
// default action
std::cout << input << "\n";
Main_api::parse(input);
rx.history_add(input);
continue;
}
}
std::cerr << "See you soon\n";
rx.history_save(history_file);
return 0;
}
| 26.176136
| 105
| 0.597026
|
tamim-asif
|
42e4d4601c5e15f07f865c9a1ced0112b8c22a99
| 1,624
|
cpp
|
C++
|
Stack/NextGreater/NextGreater.cpp
|
PrachieNaik/DSA
|
083522bb3c8a0694adec1f2856d4d4cd0fb51722
|
[
"MIT"
] | null | null | null |
Stack/NextGreater/NextGreater.cpp
|
PrachieNaik/DSA
|
083522bb3c8a0694adec1f2856d4d4cd0fb51722
|
[
"MIT"
] | null | null | null |
Stack/NextGreater/NextGreater.cpp
|
PrachieNaik/DSA
|
083522bb3c8a0694adec1f2856d4d4cd0fb51722
|
[
"MIT"
] | null | null | null |
/*
Problem statement: Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element x is the first greater element
on the right side of x in the array. Elements for which no greater element exist, consider next greater element as -1.
Approaches:
Method 1: Use two loops: The outer loop picks all the elements one by one. The inner loop looks for the first greater element for the element picked by the outer
loop. If a greater element is found then that element is printed as next, otherwise -1 is printed.
Complexity Analysis:
Time Complexity: O(n^2).
Space Complexity: O(1).
Method 2: Traverse the array in reverse order, while current element is greater then top element on auxillary stack, keep removing the elements from stack.
If stack is empty, there is no greater element, if not, top element is greater. At last, push current element to stack.
Complexity Analysis:
Space Complexity: O(N)
Time Complexity: O(N).
*/
vector<long long> nextLargerElement(vector<long long> arr, int n){
stack<long long> st;
vector<long long> ans;
for(int i=n-1;i>=0;i--) {
if(st.empty()) {
ans.push_back(-1);
st.push(arr[i]);
} else {
while(!st.empty() && st.top()<arr[i]) {
st.pop();
}
if(st.empty()) {
ans.push_back(-1);
} else {
ans.push_back(st.top());
}
st.push(arr[i]);
}
}
reverse(ans.begin(),ans.end());
return ans;
}
| 33.142857
| 162
| 0.616379
|
PrachieNaik
|
42e5f53a584b97bb6ecf49879cb5daa3cf5fac19
| 4,146
|
cpp
|
C++
|
Libraries/SdFs-master/src/SpiDriver/SdSpiSTM32F1.cpp
|
surgtechlab/MagLib
|
491937caec71c44ec58feec587109f27b50dfece
|
[
"MIT"
] | 45
|
2017-08-15T00:29:38.000Z
|
2022-02-20T14:05:29.000Z
|
src/SpiDriver/SdSpiSTM32F1.cpp
|
digitalpbk/SdFs
|
190a2677d4cbc87e6062137dfb5da6b2fed2b435
|
[
"MIT"
] | 8
|
2017-12-14T12:07:43.000Z
|
2021-01-12T16:23:14.000Z
|
src/SpiDriver/SdSpiSTM32F1.cpp
|
digitalpbk/SdFs
|
190a2677d4cbc87e6062137dfb5da6b2fed2b435
|
[
"MIT"
] | 17
|
2017-09-09T08:36:18.000Z
|
2021-11-27T07:41:12.000Z
|
/**
* Copyright (c) 20011-2017 Bill Greiman
* This file is part of the SdFs library for SD memory cards.
*
* MIT License
*
* 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.
*/
#if defined(__STM32F1__)
#include "SdSpiDriver.h"
#define USE_STM32F1_DMAC 1
//------------------------------------------------------------------------------
#if BOARD_NR_SPI > 1
static SPIClass m_SPI2(2);
#endif // BOARD_NR_SPI > 1
#if BOARD_NR_SPI > 2
static SPIClass m_SPI3(3);
#endif // BOARD_NR_SPI > 2
//
static SPIClass* pSpi[] =
#if BOARD_NR_SPI == 1
{&SPI};
#elif BOARD_NR_SPI == 2
{&SPI, &m_SPI2};
#elif BOARD_NR_SPI == 3
{&SPI, &m_SPI2, &m_SPI3};
#else // BOARD_NR_SPI
#error "BOARD_NR_SPI too large"
#endif // BOARD_NR_SPI
//------------------------------------------------------------------------------
/** Set SPI options for access to SD/SDHC cards.
*
* \param[in] divisor SCK clock divider relative to the APB1 or APB2 clock.
*/
void SdSpiAltDriver::activate() {
m_spi->beginTransaction(m_spiSettings);
}
//------------------------------------------------------------------------------
/** Initialize the SPI bus.
*
* \param[in] chipSelectPin SD card chip select pin.
*/
void SdSpiAltDriver::begin(SdSpiConfig spiConfig) {
if (spiConfig.spiPort > 0 && spiConfig.spiPort <= BOARD_NR_SPI) {
m_spi = pSpi[spiConfig.spiPort - 1];
} else {
m_spi = pSpi[0];
}
m_csPin = spiConfig.csPin;
pinMode(m_csPin, OUTPUT);
digitalWrite(m_csPin, HIGH);
m_spi->begin();
}
//------------------------------------------------------------------------------
/**
* End SPI transaction.
*/
void SdSpiAltDriver::deactivate() {
m_spi->endTransaction();
}
//------------------------------------------------------------------------------
/** Receive a byte.
*
* \return The byte.
*/
uint8_t SdSpiAltDriver::receive() {
return m_spi->transfer(0XFF);
}
//------------------------------------------------------------------------------
/** Receive multiple bytes.
*
* \param[out] buf Buffer to receive the data.
* \param[in] n Number of bytes to receive.
*
* \return Zero for no error or nonzero error code.
*/
uint8_t SdSpiAltDriver::receive(uint8_t* buf, size_t n) {
int rtn = 0;
#if USE_STM32F1_DMAC
rtn = m_spi->dmaTransfer(0, const_cast<uint8*>(buf), n);
#else // USE_STM32F1_DMAC
// m_spi->read(buf, n); fails ?? use byte transfer
for (size_t i = 0; i < n; i++) {
buf[i] = m_spi->transfer(0XFF);
}
#endif // USE_STM32F1_DMAC
return rtn;
}
//------------------------------------------------------------------------------
/** Send a byte.
*
* \param[in] b Byte to send
*/
void SdSpiAltDriver::send(uint8_t b) {
m_spi->transfer(b);
}
//------------------------------------------------------------------------------
/** Send multiple bytes.
*
* \param[in] buf Buffer for data to be sent.
* \param[in] n Number of bytes to send.
*/
void SdSpiAltDriver::send(const uint8_t* buf , size_t n) {
#if USE_STM32F1_DMAC
m_spi->dmaSend(const_cast<uint8*>(buf), n);
#else // #if USE_STM32F1_DMAC
m_spi->write(buf, n);
#endif // USE_STM32F1_DMAC
}
#endif // defined(__STM32F1__)
| 32.645669
| 80
| 0.592137
|
surgtechlab
|
42e6351fb2e0e41becc6572f3364c23aa4b0ec52
| 323
|
cpp
|
C++
|
solutions/781.rabbits-in-forest.379275117.ac.cpp
|
satu0king/Leetcode-Solutions
|
2edff60d76c2898d912197044f6284efeeb34119
|
[
"MIT"
] | 78
|
2020-10-22T11:31:53.000Z
|
2022-02-22T13:27:49.000Z
|
solutions/781.rabbits-in-forest.379275117.ac.cpp
|
satu0king/Leetcode-Solutions
|
2edff60d76c2898d912197044f6284efeeb34119
|
[
"MIT"
] | null | null | null |
solutions/781.rabbits-in-forest.379275117.ac.cpp
|
satu0king/Leetcode-Solutions
|
2edff60d76c2898d912197044f6284efeeb34119
|
[
"MIT"
] | 26
|
2020-10-23T15:10:44.000Z
|
2021-11-07T16:13:50.000Z
|
class Solution {
public:
int numRabbits(vector<int> &answers) {
unordered_map<int, int> count;
for (int a : answers)
count[a]++;
int ans = 0;
for (auto &p : count) {
while (p.second > 0) {
ans += (p.first + 1);
p.second -= (p.first + 1);
}
}
return ans;
}
};
| 17
| 40
| 0.489164
|
satu0king
|
42e67df334542b7ec490b2cbf614887fbc338747
| 2,297
|
hpp
|
C++
|
src/util/vector.hpp
|
rxnew/qc
|
dcb9c0d9b4347d3cc9311fee16c88a0c2dca1dce
|
[
"MIT"
] | null | null | null |
src/util/vector.hpp
|
rxnew/qc
|
dcb9c0d9b4347d3cc9311fee16c88a0c2dca1dce
|
[
"MIT"
] | null | null | null |
src/util/vector.hpp
|
rxnew/qc
|
dcb9c0d9b4347d3cc9311fee16c88a0c2dca1dce
|
[
"MIT"
] | null | null | null |
#pragma once
#include <array>
#include <sstream>
namespace qc {
namespace util {
namespace vector {
template <int dim, class Real = float>
class Vector {
public:
Vector() = default;
template <class T, class... Args,
class = std::enable_if_t<!std::is_convertible<T, Vector>::value>>
Vector(T&& t, Args&&... args);
Vector(Vector const&) = default;
Vector(Vector&&) noexcept = default;
~Vector() = default;
auto operator=(Vector const&) -> Vector& = default;
auto operator=(Vector&&) -> Vector& = default;
auto operator==(Vector const& other) const -> bool;
auto operator!=(Vector const& other) const -> bool;
auto operator<(Vector const& other) const -> bool;
auto operator>(Vector const& other) const -> bool;
auto operator+(Vector const& other) const -> Vector;
auto operator-(Vector const& other) const -> Vector;
auto operator[](size_t n) -> Real&;
auto operator[](size_t n) const -> Real const&;
auto dimension() const -> int;
template <class = std::enable_if_t<std::is_floating_point<Real>::value>>
auto norm(int n = 2) const -> Real;
template <class = std::enable_if_t<!std::is_floating_point<Real>::value>>
auto norm(int n = 2) const -> long double;
private:
Vector(std::array<Real, dim> const& p);
Vector(std::array<Real, dim>&& p);
std::array<Real, dim> p_;
};
using Vector1d = Vector<1>;
using Vector2d = Vector<2>;
template <int dim, class Real>
auto operator<<(std::ostream& os, Vector<dim, Real> const& vector)
-> std::ostream&;
template <int dim, class Real>
auto dot(Vector<dim, Real> const& a, Vector<dim, Real> const& b) -> Real;
template <class Real>
auto cross(Vector<2, Real> const& a, Vector<2, Real> const& b) -> Real;
template <class Real>
auto cross(Vector<3, Real> const& a, Vector<3, Real> const& b)
-> Vector<3, Real>;
template <class Real>
auto is_intersected(Vector<1, Real> const& a1,
Vector<1, Real> const& a2,
Vector<1, Real> const& b1,
Vector<1, Real> const& b2) -> bool;
template <class Real>
auto is_intersected(Vector<2, Real> const& a1,
Vector<2, Real> const& a2,
Vector<2, Real> const& b1,
Vector<2, Real> const& b2) -> bool;
}
}
}
#include "vector/vector_impl.hpp"
| 31.902778
| 77
| 0.638224
|
rxnew
|
42e92981aa07dbeb3bbe3d3b8678b99df6f35373
| 1,762
|
cpp
|
C++
|
Practice/2018/2018.2.20/BZOJ1064.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | 4
|
2017-10-31T14:25:18.000Z
|
2018-06-10T16:10:17.000Z
|
Practice/2018/2018.2.20/BZOJ1064.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | null | null | null |
Practice/2018/2018.2.20/BZOJ1064.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
const int maxN=100100;
const int maxM=1001000*2;
const int inf=2147483647;
int n,m;
int edgecnt=0,Head[maxN],Next[maxM],V[maxM],W[maxM];
bool vis[maxN];
int Depth[maxN],Queue[maxN],Fa[maxN];
void Add_Edge(int u,int v,int w);
int gcd(int a,int b);
int main()
{
mem(Head,-1);
scanf("%d%d",&n,&m);
for (int i=1;i<=m;i++)
{
int a,b;scanf("%d%d",&a,&b);
Add_Edge(a,b,1);Add_Edge(b,a,-1);
}
int length=0,chain=0;
for (int i=1;i<=n;i++)
if (vis[i]==0)
{
Depth[i]=0;
int h=1,t=0;Queue[1]=i;vis[i]=1;
int mx=-inf,mn=inf;
do
{
int u=Queue[++t];mx=max(mx,Depth[u]),mn=min(mn,Depth[u]);
for (int i=Head[u];i!=-1;i=Next[i])
{
if (V[i]==Fa[u]) continue;
if (vis[V[i]]==0) vis[Queue[++h]=V[i]]=1,Depth[V[i]]=Depth[u]+W[i],Fa[V[i]]=u;
else
{
//cout<<u<<" "<<V[i]<<" "<<abs(Depth[u]-Depth[V[i]])+1<<endl;
if (length==0) length=abs(Depth[u]-Depth[V[i]]+W[i]);
else length=gcd(length,abs(Depth[u]-Depth[V[i]]+W[i]));
}
}
}
while (h!=t);
chain=chain+mx-mn+1;
}
//for (int i=1;i<=n;i++) cout<<Depth[i]<<" ";cout<<endl;
if (length==0)
{
if (chain<3) printf("-1 -1\n");
else printf("%d 3\n",chain);
}
else
{
if (length<3) printf("-1 -1\n");
else
{
printf("%d ",length);
for (int i=3;i<=length;i++) if (length%i==0) {length=i;break;}
printf("%d\n",length);
}
}
return 0;
}
void Add_Edge(int u,int v,int w)
{
edgecnt++;Next[edgecnt]=Head[u];Head[u]=edgecnt;V[edgecnt]=v;W[edgecnt]=w;
return;
}
int gcd(int a,int b)
{
int tmp;
while (b) tmp=b,b=a%b,a=tmp;
return a;
}
| 20.022727
| 83
| 0.563564
|
SYCstudio
|
42edf91c0e136c5ecca5b2d1b0aaa074e6bc097e
| 7,721
|
cpp
|
C++
|
3DEngine/Source/ModuleCamera3D.cpp
|
PatatesIDracs/3DGameEngine
|
9bf1fbbea6c9d6f02174657ae41e01ea3a984858
|
[
"MIT"
] | 4
|
2017-10-23T18:05:48.000Z
|
2017-11-29T06:57:26.000Z
|
3DEngine/Source/ModuleCamera3D.cpp
|
PatatesIDracs/3DGameEngine
|
9bf1fbbea6c9d6f02174657ae41e01ea3a984858
|
[
"MIT"
] | null | null | null |
3DEngine/Source/ModuleCamera3D.cpp
|
PatatesIDracs/3DGameEngine
|
9bf1fbbea6c9d6f02174657ae41e01ea3a984858
|
[
"MIT"
] | null | null | null |
#include "Application.h"
#include "ModuleCamera3D.h"
#include "ModuleSceneIntro.h"
#include "ConfigJSON.h"
#include "Imgui\imgui.h"
#include "Imgui\ImGuizmo.h"
#include "Glew\include\glew.h"
ModuleCamera3D::ModuleCamera3D(Application* app, bool start_enabled) : Module(app, "Camera", start_enabled)
{
Position = vec(1.0f, 1.0f, 1.0f);
Reference = vec(0.0f, 0.0f, 0.0f);
LookAt(float3(0, 0, 0));
}
ModuleCamera3D::~ModuleCamera3D()
{
if(camera_editor != nullptr) delete camera_editor;
}
// -----------------------------------------------------------------
bool ModuleCamera3D::CleanUp()
{
LOGC("Cleaning camera");
return true;
}
void ModuleCamera3D::SetCameraEditor()
{
camera_editor = new Camera(nullptr, true);
camera_editor->SetFrustumPlanes(0.5, 512);
camera_editor->SetFrustumViewAngle();
camera_editor->SetNewFrame(Position, -Z, Y);
}
void ModuleCamera3D::SetMainCamera(Camera* comp_camera, bool active)
{
if (active) {
if (main_camera != nullptr && main_camera != comp_camera) main_camera->Disable();
main_camera = comp_camera;
main_camera->SetFOVRatio(App->window->width, App->window->height);
}
else if (main_camera == comp_camera) main_camera = nullptr;
}
void ModuleCamera3D::ChangeCamera(bool mode_editor)
{
this->mode_editor = mode_editor;
if (mode_editor) {
camera_editor->GetCameraVectors(Position, Z, Y);
}
else {
GetMainCamera()->GetCameraVectors(Position, Z, Y);
}
Reference = Position;
X = Y.Cross(Z);
update_camera = true;
}
void ModuleCamera3D::UpdateFov(int width, int height)
{
if (main_camera != nullptr)
main_camera->SetFOVRatio(width, height);
if (camera_editor != nullptr)
camera_editor->SetFOVRatio(width, height);
}
Camera * ModuleCamera3D::GetMainCamera() const
{
if (main_camera != nullptr) return main_camera;
else return camera_editor;
}
bool ModuleCamera3D::Start()
{
SetCameraEditor();
return true;
}
// -----------------------------------------------------------------
update_status ModuleCamera3D::Update(float dt)
{
//If ImGui is using inputs don't use the camera
if (App->input->IsImGuiUsingInput() || (ImGui::GetIO().WantCaptureMouse && ImGuizmo::IsOver())) return UPDATE_CONTINUE;
last_dt = App->clock.real_delta_time;
if (App->input->GetKey(SDL_SCANCODE_F) == KEY_DOWN)
{
App->scene_intro->LookAtScene();
}
// Mouse motion ----------------
if (App->input->GetKey(SDL_SCANCODE_LALT) == KEY_REPEAT && App->input->GetMouseButton(SDL_BUTTON_LEFT) == KEY_REPEAT)
{
RotateCamera();
}
// Right Click + WASD to Move like FPS
if (App->input->GetMouseButton(SDL_BUTTON_RIGHT) == KEY_REPEAT)
{
RotateCamera(false);
MoveCamera();
}
// Zoom in and out
int wheelmotion = App->input->GetMouseZ();
if (wheelmotion != 0)
{
Position -= Z*(float)wheelmotion;
Reference -= Z*(float)(wheelmotion);
update_camera = true;
}
if (!update_camera && App->input->GetMouseButton(SDL_BUTTON_LEFT) == KEY_REPEAT && App->clock.state != APPSTATE::APP_PLAY)
{
CameraRayCast();
}
return UPDATE_CONTINUE;
}
update_status ModuleCamera3D::PostUpdate(float dt)
{
// Recalculate matrix -------------
if (update_camera) {
if (mode_editor) {
camera_editor->SetNewFrame(Position, -Z, Y);
}
else GetMainCamera()->SetNewFrame(Position, -Z, Y);
if (App->clock.state != APP_PLAY)
App->physics->SetDebugCullingLimits(GetMainCamera()->GetFrustum().MinimalEnclosingAABB());
update_camera = false;
}
return UPDATE_CONTINUE;
}
// -----------------------------------------------------------------
void ModuleCamera3D::Look(const vec &Position, const vec &Reference, bool RotateAroundReference)
{
this->Position = Position;
this->Reference = Reference;
Z = (Position - Reference).Normalized();
X = vec(0.0f, 1.0f, 0.0f).Cross(Z).Normalized();
Y = Z.Cross(X);
if (!RotateAroundReference)
{
this->Reference = this->Position;
this->Position += Z * 0.05f;
}
update_camera = true;
}
// -----------------------------------------------------------------
void ModuleCamera3D::LookAt(const vec &Spot)
{
Reference = Spot;
Z = (Position - Reference).Normalized();
X = vec(0.0f,1.0f,0.0f).Cross(Z).Normalized();
Y = Z.Cross(X);
update_camera = true;
}
// -----------------------------------------------------------------
void ModuleCamera3D::Move(const vec &Movement)
{
Position += Movement;
Reference += Movement;
update_camera = true;
}
void ModuleCamera3D::MoveTo(const vec &Movement, float distance)
{
Position -= Reference;
Reference = Movement;
this->distance = (float)1.2*distance;
Position = Reference + Z*distance * 2;
update_camera = true;
}
void ModuleCamera3D::RotateCamera(bool RotateAroundReference)
{
int dx = -App->input->GetMouseXMotion();
int dy = -App->input->GetMouseYMotion();
float Sensitivity = 0.25f;
if (RotateAroundReference)
Position = (Position - Reference);
if (dx != 0)
{
float DeltaX = (float)dx * Sensitivity*DEGTORAD;
float3x3 rotate = float3x3::RotateAxisAngle(vec(0.0f, 1.0f, 0.0f), DeltaX);
X = rotate * X;
Y = rotate * Y;
Z = rotate * Z;
}
if (dy != 0)
{
float DeltaY = (float)dy * Sensitivity*DEGTORAD;
float3x3 rotate = float3x3::RotateAxisAngle(X, DeltaY);
Y = rotate * Y;
Z = rotate * Z;
if (Y.y < 0.0f)
{
Z = vec(0.0f, Z.y > 0.0f ? 1.0f : -1.0f, 0.0f);
Y = Z.Cross(X);
}
}
if (RotateAroundReference) Position = Reference + Z *Position.Length();
else Reference = Position - Z*(Position - Reference).Length();
update_camera = true;
}
void ModuleCamera3D::MoveCamera()
{
float dx = 0;
float dy = 0;
if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) dx = -speed;
if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) dx = speed;
if (App->input->GetKey(SDL_SCANCODE_W) == KEY_REPEAT) dy = -speed;
if (App->input->GetKey(SDL_SCANCODE_S) == KEY_REPEAT) dy = speed;
if (dx != 0)
{
Position += X*dx*last_dt;
Reference += X*dx*last_dt;
}
if (dy != 0)
{
Position += Z*dy*last_dt;
Reference += Z*dy*last_dt;
}
update_camera = true;
}
float4x4 ModuleCamera3D::GetProjMatrix() const
{
if (mode_editor) return camera_editor->GetProjMatrix();
else return GetMainCamera()->GetProjMatrix();
}
float4x4 ModuleCamera3D::GetViewMatrix4x4() const
{
return camera_editor->GetViewMatrix4x4();
}
// -----------------------------------------------------------------
float* ModuleCamera3D::GetViewMatrix() const
{
if (mode_editor) return camera_editor->GetViewMatrix();
else return GetMainCamera()->GetViewMatrix();
}
void ModuleCamera3D::CameraRayCast()
{
float y = (float)(-App->input->GetMouseY() + App->window->height*0.5f) / (App->window->height*0.5f);
float x = (float)(App->input->GetMouseX() - App->window->width*0.5f) / (App->window->width*0.5f);
// Camera Ray Cast
App->scene_intro->CheckRayCastCollision(camera_editor->GetFrustum().UnProjectLineSegment(x, y));
}
float3 ModuleCamera3D::CameraShotBall()
{
float y = (float)(-App->input->GetMouseY() + App->window->height*0.5f) / (App->window->height*0.5f);
float x = (float)(App->input->GetMouseX() - App->window->width*0.5f) / (App->window->width*0.5f);
// Camera Ray Cast
LineSegment dir = GetMainCamera()->GetFrustum().UnProjectLineSegment(x, y);
if(dir.IsFinite())
return dir.Dir();
else return float3(0.f, 0.f, 1.f);
}
// ----------------------------------------------
void ModuleCamera3D::LoadModuleConfig(Config_Json & config)
{
speed = config.GetFloat("Speed", 10.0f);
}
void ModuleCamera3D::SaveModuleConfig(Config_Json & config)
{
Config_Json camera_config = config.AddJsonObject(this->GetName());
camera_config.SetBool("Is Active", true);
camera_config.SetInt("Speed", (int)speed);
}
void ModuleCamera3D::DrawConfig()
{
ImGui::SliderFloat("Speed", &speed, 8.0f, 30.0f);
}
| 24.279874
| 123
| 0.652636
|
PatatesIDracs
|
0cd3ab4502636bbcb208be68e57b69ba78456ec5
| 606
|
cc
|
C++
|
test/client_test.cc
|
Tibonium/genecis
|
4de1d987f5a7928b1fc3e31d2820f5d2452eb5fc
|
[
"BSD-2-Clause"
] | null | null | null |
test/client_test.cc
|
Tibonium/genecis
|
4de1d987f5a7928b1fc3e31d2820f5d2452eb5fc
|
[
"BSD-2-Clause"
] | null | null | null |
test/client_test.cc
|
Tibonium/genecis
|
4de1d987f5a7928b1fc3e31d2820f5d2452eb5fc
|
[
"BSD-2-Clause"
] | null | null | null |
#include <iostream>
#include <sstream>
#include <genecis/net/genecis_server.h>
using namespace std ;
using namespace genecis::net ;
int main() {
string host = "localhost" ;
int port = 45000 ;
cout << "Creating client server..." << endl ;
genecis_server client( host, port ) ;
cout << "Connecting..." << endl ;
client << "ready" ;
while( true ) {
cout << "msg: " ;
string msg ;
getline(cin, msg) ;
client << msg ;
if( strcmp(msg.c_str(),"break") == 0 ) break ;
string s ;
client >> s ;
if( strcmp(s.c_str(),"break") == 0 ) break ;
cout << "server: " << s.c_str() << endl ;
}
}
| 20.896552
| 48
| 0.590759
|
Tibonium
|
0cd5682ae738de1b87ea1b6937053ce8f94340df
| 1,421
|
cpp
|
C++
|
Other/CampusChapter1/WASHHAND.cpp
|
vinaysomawat/CodeChef-Solutions
|
9a0666a4f1badd593cd075f3beb05377e3c6657a
|
[
"MIT"
] | 1
|
2020-04-12T01:39:10.000Z
|
2020-04-12T01:39:10.000Z
|
Other/CampusChapter1/WASHHAND.cpp
|
vinaysomawat/CodeChef-Solutions
|
9a0666a4f1badd593cd075f3beb05377e3c6657a
|
[
"MIT"
] | null | null | null |
Other/CampusChapter1/WASHHAND.cpp
|
vinaysomawat/CodeChef-Solutions
|
9a0666a4f1badd593cd075f3beb05377e3c6657a
|
[
"MIT"
] | null | null | null |
/*
Contest: CodeChef March 2020 Cook-Off challange
Problem link:https://www.codechef.com/CHPTRS01/problems/WASHHAND
GitHub Solution Repository: https://github.com/vinaysomawat/CodeChef-Solutions
Author: Vinay Somawat
Author's Webpage: http://vinaysomawat.github.io/
Author's mail: vinaysomawat@hotmail.com
*/
#include<bits/stdc++.h>
#define ll long long int
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
void solve()
{
int n,k;
cin>>n;
int cnt=0;
int infarr[n+1];
bool Arr[n+1];
fill(Arr, Arr+n+1, false);
stack<int> stk;
string str;
cin>>str;
for(int i=1; i<=n; i++)
{
infarr[i] = str[i-1]-'0';
if(infarr[i]==1) {
stk.push(i);
cnt++;
}
}
cin>>k;
int isolatedarr[k+1];
for(int i =1; i<=k; i++)
cin>>isolatedarr[i];
for(int day=1; day<= k; day++)
{
Arr[ isolatedarr[day]] = true;
stack<int> stknew;
int index;
while(!stk.empty())
{
index = stk.top();
stk.pop();
if(index-1>0 && !Arr[index] && infarr[index-1]==0){
cnt++;
infarr[index-1] = 1;
stknew.push(index-1);
}
if(index+1 <= n && !Arr[index+1] && infarr[index+1]== 0){
cnt++;
infarr[index+1] = 1;
stknew.push(index+1);
}
}
stk = stknew;
}
cout<<cnt<<"\n";
}
int main()
{
IOS
int t;
cin>>t;
while(t--)
{
solve();
}
return 0;
}
| 16.147727
| 82
| 0.557354
|
vinaysomawat
|
0cd6ebc232993072993631da2b910f095b433944
| 3,070
|
hpp
|
C++
|
include/view.hpp
|
procedural/d3d11_on_12
|
ffede331ce53247fc66ffdfcff625c632c1dd23b
|
[
"MIT"
] | 157
|
2020-01-15T20:24:54.000Z
|
2022-03-17T01:50:45.000Z
|
include/view.hpp
|
TheozZ79/D3D11On12
|
37048dfc43665bad3dc6642f3c3991ed0edc982b
|
[
"MIT"
] | 11
|
2020-03-07T08:29:05.000Z
|
2022-02-01T01:25:22.000Z
|
include/view.hpp
|
TheozZ79/D3D11On12
|
37048dfc43665bad3dc6642f3c3991ed0edc982b
|
[
"MIT"
] | 24
|
2020-01-17T03:46:09.000Z
|
2022-03-17T13:28:32.000Z
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
namespace D3D11On12
{
template< class TIface >
struct ViewTraits;
#define DECLARE_VIEW_TRAITS(View, AbbreviatedView, DDIDescType, HandleType) \
template<> struct ViewTraits<ID3D11##View> \
{ \
typedef D3D12TranslationLayer::##AbbreviatedView TranslationLayerView; \
typedef HandleType ViewHandle; \
typedef DDIDescType DDIDesc; \
}
DECLARE_VIEW_TRAITS(ShaderResourceView, SRV, D3DWDDM2_0DDIARG_CREATESHADERRESOURCEVIEW, D3D10DDI_HSHADERRESOURCEVIEW);
DECLARE_VIEW_TRAITS(RenderTargetView, RTV, D3DWDDM2_0DDIARG_CREATERENDERTARGETVIEW, D3D10DDI_HRENDERTARGETVIEW);
DECLARE_VIEW_TRAITS(DepthStencilView, DSV, D3D11DDIARG_CREATEDEPTHSTENCILVIEW, D3D10DDI_HDEPTHSTENCILVIEW);
DECLARE_VIEW_TRAITS(UnorderedAccessView, UAV, D3DWDDM2_0DDIARG_CREATEUNORDEREDACCESSVIEW, D3D11DDI_HUNORDEREDACCESSVIEW);
DECLARE_VIEW_TRAITS(VideoDecoderOutputView, VDOV, D3D11_1DDIARG_CREATEVIDEODECODEROUTPUTVIEW, D3D11_1DDI_HVIDEODECODEROUTPUTVIEW);
DECLARE_VIEW_TRAITS(VideoProcessorInputView, VPIV, D3D11_1DDIARG_CREATEVIDEOPROCESSORINPUTVIEW, D3D11_1DDI_HVIDEOPROCESSORINPUTVIEW);
DECLARE_VIEW_TRAITS(VideoProcessorOutputView, VPOV, D3D11_1DDIARG_CREATEVIDEOPROCESSOROUTPUTVIEW, D3D11_1DDI_HVIDEOPROCESSOROUTPUTVIEW);
template<typename Traits>
class View : public DeviceChild
{
public:
View(Device &device, D3D12TranslationLayer::Resource &resource, typename Traits::DDIDesc const* pDesc);
typename Traits::TranslationLayerView *GetTranslationLayerView() { return m_spView.get(); }
static View *CastFrom(typename Traits::ViewHandle hView) { return static_cast< View* >(hView.pDrvPrivate); }
static typename Traits::TranslationLayerView *CastToTranslationView(typename Traits::ViewHandle hView) {
View *pView = CastFrom(hView);
return (pView) ? pView->GetTranslationLayerView() : nullptr;
}
static void GatherViewsFromHandles(typename const Traits::ViewHandle* pHViews, typename Traits::TranslationLayerView ** pUnderlying, UINT count)
{
for (size_t i = 0; i < count; i++)
{
pUnderlying[i] = CastToTranslationView(pHViews[i]);
}
}
private:
D3D12TranslationLayer::unique_batched_ptr<typename Traits::TranslationLayerView> m_spView;
};
typedef View <ViewTraits <ID3D11RenderTargetView> > RenderTargetView;
typedef View <ViewTraits <ID3D11DepthStencilView> > DepthStencilView;
typedef View <ViewTraits <ID3D11UnorderedAccessView> > UnorderedAccessView;
typedef View <ViewTraits <ID3D11ShaderResourceView> > ShaderResourceView;
typedef View <ViewTraits <ID3D11VideoDecoderOutputView> > VideoDecoderOutputView;
typedef View <ViewTraits <ID3D11VideoProcessorInputView> > VideoProcessorInputView;
typedef View <ViewTraits <ID3D11VideoProcessorOutputView> > VideoProcessorOutputView;
};
| 52.033898
| 153
| 0.754072
|
procedural
|
0cdb99eedb08cdd734bf5ea831e1c149cbd336a3
| 233
|
cpp
|
C++
|
Game/Client/WXClient/Network/PacketHandler/CGModifySettingHandler.cpp
|
hackerlank/SourceCode
|
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
|
[
"MIT"
] | 4
|
2021-07-31T13:56:01.000Z
|
2021-11-13T02:55:10.000Z
|
Game/Client/WXClient/Network/PacketHandler/CGModifySettingHandler.cpp
|
shacojx/SourceCodeGameTLBB
|
e3cea615b06761c2098a05427a5f41c236b71bf7
|
[
"MIT"
] | null | null | null |
Game/Client/WXClient/Network/PacketHandler/CGModifySettingHandler.cpp
|
shacojx/SourceCodeGameTLBB
|
e3cea615b06761c2098a05427a5f41c236b71bf7
|
[
"MIT"
] | 7
|
2021-08-31T14:34:23.000Z
|
2022-01-19T08:25:58.000Z
|
#include "StdAfx.h"
#include "CGModifySetting.h"
uint CGModifySettingHandler::Execute( CGModifySetting* pPacket, Player* pPlayer )
{
__ENTER_FUNCTION
return PACKET_EXE_CONTINUE ;
__LEAVE_FUNCTION
return PACKET_EXE_ERROR ;
}
| 13.705882
| 81
| 0.7897
|
hackerlank
|
0ce14b60b5960049e45c0996398a64d404c427cd
| 11,343
|
cpp
|
C++
|
library/src/conversion/rocsparse_dense2coo.cpp
|
scchan/rocSPARSE
|
6efc875765236a91d6b07ef42446b1b46de661e0
|
[
"MIT"
] | null | null | null |
library/src/conversion/rocsparse_dense2coo.cpp
|
scchan/rocSPARSE
|
6efc875765236a91d6b07ef42446b1b46de661e0
|
[
"MIT"
] | null | null | null |
library/src/conversion/rocsparse_dense2coo.cpp
|
scchan/rocSPARSE
|
6efc875765236a91d6b07ef42446b1b46de661e0
|
[
"MIT"
] | 1
|
2019-09-26T21:19:46.000Z
|
2019-09-26T21:19:46.000Z
|
/*! \file */
/* ************************************************************************
* Copyright (c) 2020-2021 Advanced Micro Devices, Inc.
*
* 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 "definitions.h"
#include "utility.h"
#include "rocsparse_csr2coo.hpp"
#include "rocsparse_dense2coo.hpp"
#include "rocsparse_dense2csx_impl.hpp"
#include <rocprim/rocprim.hpp>
template <typename I, typename T>
rocsparse_status rocsparse_dense2coo_template(rocsparse_handle handle,
rocsparse_order order,
I m,
I n,
const rocsparse_mat_descr descr,
const T* A,
I ld,
const I* nnz_per_rows,
T* coo_val,
I* coo_row_ind,
I* coo_col_ind)
{
// Check for valid handle and matrix descriptor
if(handle == nullptr)
{
return rocsparse_status_invalid_handle;
}
// Logging
log_trace(handle,
replaceX<T>("rocsparse_Xdense2coo"),
order,
m,
n,
descr,
(const void*&)A,
ld,
(const void*&)nnz_per_rows,
(const void*&)coo_val,
(const void*&)coo_row_ind,
(const void*&)coo_col_ind);
log_bench(handle, "./rocsparse-bench -f dense2coo -r", replaceX<T>("X"), "--mtx <matrix.mtx>");
// Check matrix descriptor
if(descr == nullptr)
{
return rocsparse_status_invalid_pointer;
}
// Check sizes
if(m < 0 || n < 0 || ld < (order == rocsparse_order_column ? m : n))
{
return rocsparse_status_invalid_size;
}
// Quick return if possible
if(m == 0 || n == 0)
{
return rocsparse_status_success;
}
// Check pointer arguments
if(A == nullptr || nnz_per_rows == nullptr || coo_val == nullptr || coo_row_ind == nullptr
|| coo_col_ind == nullptr)
{
return rocsparse_status_invalid_pointer;
}
I* row_ptr;
RETURN_IF_HIP_ERROR(hipMalloc(&row_ptr, (m + 1) * sizeof(I)));
RETURN_IF_ROCSPARSE_ERROR(rocsparse_dense2csx_impl<rocsparse_direction_row>(
handle, order, m, n, descr, A, ld, nnz_per_rows, coo_val, row_ptr, coo_col_ind));
I start;
I end;
RETURN_IF_HIP_ERROR(hipMemcpy(&start, &row_ptr[0], sizeof(I), hipMemcpyDeviceToHost));
RETURN_IF_HIP_ERROR(hipMemcpy(&end, &row_ptr[m], sizeof(I), hipMemcpyDeviceToHost));
I nnz = end - start;
RETURN_IF_ROCSPARSE_ERROR(
rocsparse_csr2coo_template(handle, row_ptr, nnz, m, coo_row_ind, descr->base));
RETURN_IF_HIP_ERROR(hipFree(row_ptr));
return rocsparse_status_success;
}
#define INSTANTIATE(ITYPE, TTYPE) \
template rocsparse_status rocsparse_dense2coo_template<ITYPE, TTYPE>( \
rocsparse_handle handle, \
rocsparse_order order, \
ITYPE m, \
ITYPE n, \
const rocsparse_mat_descr descr, \
const TTYPE* A, \
ITYPE ld, \
const ITYPE* nnz_per_rows, \
TTYPE* coo_val, \
ITYPE* coo_row_ind, \
ITYPE* coo_col_ind);
INSTANTIATE(int32_t, float);
INSTANTIATE(int32_t, double);
INSTANTIATE(int32_t, rocsparse_float_complex);
INSTANTIATE(int32_t, rocsparse_double_complex);
INSTANTIATE(int64_t, float);
INSTANTIATE(int64_t, double);
INSTANTIATE(int64_t, rocsparse_float_complex);
INSTANTIATE(int64_t, rocsparse_double_complex);
/*
* ===========================================================================
* C wrapper
* ===========================================================================
*/
extern "C" rocsparse_status rocsparse_sdense2coo(rocsparse_handle handle,
rocsparse_int m,
rocsparse_int n,
const rocsparse_mat_descr descr,
const float* A,
rocsparse_int ld,
const rocsparse_int* nnz_per_rows,
float* coo_val,
rocsparse_int* coo_row_ind,
rocsparse_int* coo_col_ind)
{
return rocsparse_dense2coo_template(handle,
rocsparse_order_column,
m,
n,
descr,
A,
ld,
nnz_per_rows,
coo_val,
coo_row_ind,
coo_col_ind);
}
extern "C" rocsparse_status rocsparse_ddense2coo(rocsparse_handle handle,
rocsparse_int m,
rocsparse_int n,
const rocsparse_mat_descr descr,
const double* A,
rocsparse_int ld,
const rocsparse_int* nnz_per_rows,
double* coo_val,
rocsparse_int* coo_row_ind,
rocsparse_int* coo_col_ind)
{
return rocsparse_dense2coo_template(handle,
rocsparse_order_column,
m,
n,
descr,
A,
ld,
nnz_per_rows,
coo_val,
coo_row_ind,
coo_col_ind);
}
extern "C" rocsparse_status rocsparse_cdense2coo(rocsparse_handle handle,
rocsparse_int m,
rocsparse_int n,
const rocsparse_mat_descr descr,
const rocsparse_float_complex* A,
rocsparse_int ld,
const rocsparse_int* nnz_per_rows,
rocsparse_float_complex* coo_val,
rocsparse_int* coo_row_ind,
rocsparse_int* coo_col_ind)
{
return rocsparse_dense2coo_template(handle,
rocsparse_order_column,
m,
n,
descr,
A,
ld,
nnz_per_rows,
coo_val,
coo_row_ind,
coo_col_ind);
}
extern "C" rocsparse_status rocsparse_zdense2coo(rocsparse_handle handle,
rocsparse_int m,
rocsparse_int n,
const rocsparse_mat_descr descr,
const rocsparse_double_complex* A,
rocsparse_int ld,
const rocsparse_int* nnz_per_rows,
rocsparse_double_complex* coo_val,
rocsparse_int* coo_row_ind,
rocsparse_int* coo_col_ind)
{
return rocsparse_dense2coo_template(handle,
rocsparse_order_column,
m,
n,
descr,
A,
ld,
nnz_per_rows,
coo_val,
coo_row_ind,
coo_col_ind);
}
| 47.659664
| 99
| 0.385524
|
scchan
|
0ce8e8842221bd3d28aa1aac28d7c5e37f8d58a9
| 1,830
|
hpp
|
C++
|
bulletgba/generator/data/code/otakutwo/self-0063.hpp
|
pqrs-org/BulletGBA
|
a294007902970242b496f2528b4762cfef22bc86
|
[
"Unlicense"
] | 5
|
2020-03-24T07:44:49.000Z
|
2021-08-30T14:43:31.000Z
|
bulletgba/generator/data/code/otakutwo/self-0063.hpp
|
pqrs-org/BulletGBA
|
a294007902970242b496f2528b4762cfef22bc86
|
[
"Unlicense"
] | null | null | null |
bulletgba/generator/data/code/otakutwo/self-0063.hpp
|
pqrs-org/BulletGBA
|
a294007902970242b496f2528b4762cfef22bc86
|
[
"Unlicense"
] | null | null | null |
#ifndef GENERATED_a72e55c1eeb625dca9fc19a505808a41_HPP
#define GENERATED_a72e55c1eeb625dca9fc19a505808a41_HPP
#include "bullet.hpp"
void stepfunc_c22bc11f82cdfa20eb78a2374f78cb49_bc2040b4edc291f3d17b547048b6ef88(BulletInfo *p);
void stepfunc_7b7f365efd1478dca120d8a43d514890_bc2040b4edc291f3d17b547048b6ef88(BulletInfo *p);
void stepfunc_ac5966651c761944fa5869edfc9fce6c_bc2040b4edc291f3d17b547048b6ef88(BulletInfo *p);
void stepfunc_d8579b10d770cecce15810efe8808540_bc2040b4edc291f3d17b547048b6ef88(BulletInfo *p);
void stepfunc_142b983889f08346cc7f29996da6f2b3_bc2040b4edc291f3d17b547048b6ef88(BulletInfo *p);
void stepfunc_316d24835af81d85907123e6aa79b859_bc2040b4edc291f3d17b547048b6ef88(BulletInfo *p);
void stepfunc_6a44bb20f393a4c1d9283abe159a2ec3_bc2040b4edc291f3d17b547048b6ef88(BulletInfo *p);
void stepfunc_628ca3fcbd29454265993f05a870e75e_bc2040b4edc291f3d17b547048b6ef88(BulletInfo *p);
void stepfunc_63ef13a516c6d2d2debf73aa9375157d_bc2040b4edc291f3d17b547048b6ef88(BulletInfo *p);
void stepfunc_81ca9369c3add03857671d66e3835cb7_bc2040b4edc291f3d17b547048b6ef88(BulletInfo *p);
void stepfunc_b29cebfac2f19abeac4b7b53f6b48124_bc2040b4edc291f3d17b547048b6ef88(BulletInfo *p);
void stepfunc_2fe80bcd1a1247ae0b9f61b7d2d26a76_bc2040b4edc291f3d17b547048b6ef88(BulletInfo *p);
void stepfunc_9a262eab9bee9a27b0f4b6d72eb6d017_bc2040b4edc291f3d17b547048b6ef88(BulletInfo *p);
extern const BulletStepFunc bullet_94cf1becef12703febe1a112c445c9b1_bc2040b4edc291f3d17b547048b6ef88[];
const unsigned int bullet_94cf1becef12703febe1a112c445c9b1_bc2040b4edc291f3d17b547048b6ef88_size = 3;
extern const BulletStepFunc bullet_f5d0652614ce038eade5dec691b88564_bc2040b4edc291f3d17b547048b6ef88[];
const unsigned int bullet_f5d0652614ce038eade5dec691b88564_bc2040b4edc291f3d17b547048b6ef88_size = 2128;
#endif
| 63.103448
| 105
| 0.910929
|
pqrs-org
|
0cec24619955ad46b053f84130f41a15f5b010fe
| 15,081
|
cpp
|
C++
|
plugins/csp-measurement-tools/src/PathTool.cpp
|
FellegaraR/cosmoscout-vr
|
e04e1ac9c531106693a965bb03d3064f3a6179c6
|
[
"BSL-1.0",
"Apache-2.0",
"MIT"
] | 302
|
2019-03-05T08:05:03.000Z
|
2022-03-16T22:35:21.000Z
|
plugins/csp-measurement-tools/src/PathTool.cpp
|
FellegaraR/cosmoscout-vr
|
e04e1ac9c531106693a965bb03d3064f3a6179c6
|
[
"BSL-1.0",
"Apache-2.0",
"MIT"
] | 230
|
2019-07-30T13:26:09.000Z
|
2022-03-11T11:21:06.000Z
|
plugins/csp-measurement-tools/src/PathTool.cpp
|
FellegaraR/cosmoscout-vr
|
e04e1ac9c531106693a965bb03d3064f3a6179c6
|
[
"BSL-1.0",
"Apache-2.0",
"MIT"
] | 24
|
2019-07-22T08:00:49.000Z
|
2022-01-25T10:55:17.000Z
|
////////////////////////////////////////////////////////////////////////////////////////////////////
// This file is part of CosmoScout VR //
// and may be used under the terms of the MIT license. See the LICENSE file for details. //
// Copyright: (c) 2019 German Aerospace Center (DLR) //
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "PathTool.hpp"
#include "logger.hpp"
#include "../../../src/cs-core/GuiManager.hpp"
#include "../../../src/cs-core/InputManager.hpp"
#include "../../../src/cs-core/Settings.hpp"
#include "../../../src/cs-core/SolarSystem.hpp"
#include "../../../src/cs-core/TimeControl.hpp"
#include "../../../src/cs-core/tools/DeletableMark.hpp"
#include "../../../src/cs-scene/CelestialAnchorNode.hpp"
#include "../../../src/cs-utils/convert.hpp"
#include "../../../src/cs-utils/utils.hpp"
#include <VistaKernel/GraphicsManager/VistaOpenGLNode.h>
#include <VistaKernel/GraphicsManager/VistaSceneGraph.h>
#include <VistaKernel/VistaSystem.h>
#include <VistaKernelOpenSGExt/VistaOpenSGMaterialTools.h>
namespace csp::measurementtools {
////////////////////////////////////////////////////////////////////////////////////////////////////
const char* PathTool::SHADER_VERT = R"(
#version 330
layout(location=0) in vec3 iPosition;
out vec4 vPosition;
uniform mat4 uMatModelView;
uniform mat4 uMatProjection;
void main()
{
vPosition = uMatModelView * vec4(iPosition, 1.0);
gl_Position = uMatProjection * vPosition;
}
)";
////////////////////////////////////////////////////////////////////////////////////////////////////
const char* PathTool::SHADER_FRAG = R"(
#version 330
in vec4 vPosition;
uniform vec3 uColor;
uniform float uFarClip;
layout(location = 0) out vec4 oColor;
void main()
{
oColor = vec4(uColor, 1.0);
gl_FragDepth = length(vPosition.xyz) / uFarClip;
}
)";
////////////////////////////////////////////////////////////////////////////////////////////////////
PathTool::PathTool(std::shared_ptr<cs::core::InputManager> const& pInputManager,
std::shared_ptr<cs::core::SolarSystem> const& pSolarSystem,
std::shared_ptr<cs::core::Settings> const& settings,
std::shared_ptr<cs::core::TimeControl> const& pTimeControl, std::string const& sCenter,
std::string const& sFrame)
: MultiPointTool(pInputManager, pSolarSystem, settings, pTimeControl, sCenter, sFrame)
, mGuiArea(std::make_unique<cs::gui::WorldSpaceGuiArea>(800, 475))
, mGuiItem(
std::make_unique<cs::gui::GuiItem>("file://{toolZoom}../share/resources/gui/path.html")) {
// create the shader
mShader.InitVertexShaderFromString(SHADER_VERT);
mShader.InitFragmentShaderFromString(SHADER_FRAG);
mShader.Link();
mUniforms.modelViewMatrix = mShader.GetUniformLocation("uMatModelView");
mUniforms.projectionMatrix = mShader.GetUniformLocation("uMatProjection");
mUniforms.color = mShader.GetUniformLocation("uColor");
mUniforms.farClip = mShader.GetUniformLocation("uFarClip");
// attach this as OpenGLNode to scenegraph's root (all line vertices
// will be draw relative to the observer, therfore we do not want
// any transformation)
auto* pSG = GetVistaSystem()->GetGraphicsManager()->GetSceneGraph();
mPathOpenGLNode.reset(pSG->NewOpenGLNode(pSG->GetRoot(), this));
VistaOpenSGMaterialTools::SetSortKeyOnSubtree(
mPathOpenGLNode.get(), static_cast<int>(cs::utils::DrawOrder::eOpaqueNonHDR));
// create a a CelestialAnchorNode for the user interface
// it will be moved to the center of all points when a point is moved
// and rotated in such a way, that it always faces the observer
mGuiAnchor = std::make_shared<cs::scene::CelestialAnchorNode>(
pSG->GetRoot(), pSG->GetNodeBridge(), "", sCenter, sFrame);
mGuiAnchor->setAnchorScale(mSolarSystem->getObserver().getAnchorScale());
mSolarSystem->registerAnchor(mGuiAnchor);
// create the user interface
mGuiTransform.reset(pSG->NewTransformNode(mGuiAnchor.get()));
mGuiTransform->Translate(0.F, 0.9F, 0.F);
mGuiTransform->Scale(0.0005F * static_cast<float>(mGuiArea->getWidth()),
0.0005F * static_cast<float>(mGuiArea->getHeight()), 1.F);
mGuiTransform->Rotate(VistaAxisAndAngle(VistaVector3D(0.0, 1.0, 0.0), -glm::pi<float>() / 2.F));
mGuiArea->addItem(mGuiItem.get());
mGuiArea->setUseLinearDepthBuffer(true);
mGuiOpenGLNode.reset(pSG->NewOpenGLNode(mGuiTransform.get(), mGuiArea.get()));
mInputManager->registerSelectable(mGuiOpenGLNode.get());
mGuiItem->setCanScroll(false);
mGuiItem->waitForFinishedLoading();
// We use a zoom factor of 2.0 in order to increae the DPI of our world space UIs.
mGuiItem->setZoomFactor(2.0);
mGuiItem->registerCallback("deleteMe", "Call this to delete the tool.",
std::function([this]() { pShouldDelete = true; }));
mGuiItem->registerCallback("setAddPointMode", "Call this to enable creation of new points.",
std::function([this](bool enable) {
addPoint();
pAddPointMode = enable;
}));
mGuiItem->setCursorChangeCallback([](cs::gui::Cursor c) { cs::core::GuiManager::setCursor(c); });
VistaOpenSGMaterialTools::SetSortKeyOnSubtree(
mGuiAnchor.get(), static_cast<int>(cs::utils::DrawOrder::eTransparentItems));
// whenever the height scale changes our vertex positions need to be updated
mScaleConnection = mSettings->mGraphics.pHeightScale.connectAndTouch(
[this](float /*h*/) { mVerticesDirty = true; });
// Update text.
mTextConnection = pText.connectAndTouch(
[this](std::string const& value) { mGuiItem->callJavascript("setText", value); });
mGuiItem->registerCallback("onSetText",
"This is called whenever the text input of the tool's name changes.",
std::function(
[this](std::string&& value) { pText.setWithEmitForAllButOne(value, mTextConnection); }));
}
////////////////////////////////////////////////////////////////////////////////////////////////////
PathTool::~PathTool() {
mSettings->mGraphics.pHeightScale.disconnect(mScaleConnection);
mGuiItem->unregisterCallback("deleteMe");
mGuiItem->unregisterCallback("setAddPointMode");
mGuiItem->unregisterCallback("onSetText");
mInputManager->unregisterSelectable(mGuiOpenGLNode.get());
mSolarSystem->unregisterAnchor(mGuiAnchor);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void PathTool::setCenterName(std::string const& name) {
cs::core::tools::MultiPointTool::setCenterName(name);
mGuiAnchor->setCenterName(name);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void PathTool::setFrameName(std::string const& name) {
cs::core::tools::MultiPointTool::setFrameName(name);
mGuiAnchor->setFrameName(name);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void PathTool::setNumSamples(int const& numSamples) {
if (mNumSamples != numSamples) {
mNumSamples = numSamples;
mVerticesDirty = true;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
glm::dvec4 PathTool::getInterpolatedPosBetweenTwoMarks(cs::core::tools::DeletableMark const& l0,
cs::core::tools::DeletableMark const& l1, double value, double const& scale) {
auto body = mSolarSystem->getBody(getCenterName());
if (!body) {
return glm::dvec4(0.0);
}
glm::dvec3 radii = body->getRadii();
// Calculate the position for the new segment anchor
double h0 = body->getHeight(l0.pLngLat.get()) * scale;
double h1 = body->getHeight(l1.pLngLat.get()) * scale;
// Get cartesian coordinates for interpolation
glm::dvec3 p0 = cs::utils::convert::toCartesian(l0.pLngLat.get(), radii, h0);
glm::dvec3 p1 = cs::utils::convert::toCartesian(l1.pLngLat.get(), radii, h1);
glm::dvec3 interpolatedPos = p0 + (value * (p1 - p0));
// Calc final position
glm::dvec2 ll = cs::utils::convert::cartesianToLngLat(interpolatedPos, radii);
double height = body->getHeight(ll) * scale;
glm::dvec3 pos = cs::utils::convert::toCartesian(ll, radii, height);
return glm::dvec4(pos, height);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void PathTool::onPointMoved() {
mVerticesDirty = true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void PathTool::onPointAdded() {
mVerticesDirty = true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void PathTool::onPointRemoved(int /*index*/) {
mVerticesDirty = true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void PathTool::updateLineVertices() {
if (mPoints.empty()) {
return;
}
// Fill the vertex buffer with sampled data
mSampledPositions.clear();
auto body = mSolarSystem->getBody(getCenterName());
glm::dvec3 averagePosition(0.0);
for (auto const& mark : mPoints) {
averagePosition += mark->getAnchor()->getAnchorPosition() / static_cast<double>(mPoints.size());
}
double h_scale = mSettings->mGraphics.pHeightScale.get();
auto radii = body->getRadii();
auto lngLat = cs::utils::convert::cartesianToLngLat(averagePosition, radii);
double height = body ? body->getHeight(lngLat) * h_scale : 0.0;
auto center = cs::utils::convert::toCartesian(lngLat, radii, height);
mGuiAnchor->setAnchorPosition(center);
// This seems to be the first time the tool is moved, so we have to store the distance to the
// observer so that we can scale the tool later based on the observer's position.
if (pScaleDistance.get() < 0) {
try {
pScaleDistance = mSolarSystem->getObserver().getAnchorScale() *
glm::length(mSolarSystem->getObserver().getRelativePosition(
mTimeControl->pSimulationTime.get(), *mGuiAnchor));
} catch (std::exception const& e) {
// Getting the relative transformation may fail due to insufficient SPICE data.
logger().warn("Failed to calculate scale distance of Path Tool: {}", e.what());
}
}
auto lastMark = mPoints.begin();
auto currMark = ++mPoints.begin();
std::stringstream json;
std::string jsonSeperator;
double distance = -1;
glm::dvec3 lastPos(0.0);
while (currMark != mPoints.end()) {
// generate X points for each line segment
for (int vertex_id = 0; vertex_id < mNumSamples; vertex_id++) {
glm::dvec4 pos = getInterpolatedPosBetweenTwoMarks(
**lastMark, **currMark, (vertex_id / static_cast<double>(mNumSamples)), h_scale);
mSampledPositions.push_back(pos.xyz());
// coordinate normalized by height scale; to count distance correctly
glm::dvec4 posNorm = pos;
if (h_scale != 1) {
posNorm = getInterpolatedPosBetweenTwoMarks(
**lastMark, **currMark, (vertex_id / static_cast<double>(mNumSamples)), 1);
}
if (distance < 0) {
distance = 0;
} else {
distance += glm::length(posNorm.xyz() - lastPos);
}
json << jsonSeperator << "[" << distance << "," << pos.w / h_scale << "]";
jsonSeperator = ",";
lastPos = posNorm.xyz();
}
lastMark = currMark;
++currMark;
}
mGuiItem->callJavascript("setData", "[" + json.str() + "]");
mIndexCount = mSampledPositions.size();
// Upload new data
mVBO.Bind(GL_ARRAY_BUFFER);
mVBO.BufferData(mSampledPositions.size() * sizeof(glm::vec3), nullptr, GL_DYNAMIC_DRAW);
mVBO.Release();
mVAO.EnableAttributeArray(0);
mVAO.SpecifyAttributeArrayFloat(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), 0, &mVBO);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void PathTool::update() {
MultiPointTool::update();
if (mVerticesDirty) {
updateLineVertices();
mVerticesDirty = false;
}
double simulationTime(mTimeControl->pSimulationTime.get());
cs::core::SolarSystem::scaleRelativeToObserver(*mGuiAnchor, mSolarSystem->getObserver(),
simulationTime, pScaleDistance.get(), mSettings->mGraphics.pWorldUIScale.get());
cs::core::SolarSystem::turnToObserver(
*mGuiAnchor, mSolarSystem->getObserver(), simulationTime, false);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool PathTool::Do() {
// transform all high precision sample points to observer centric
// low precision coordinates
std::vector<glm::vec3> vRelativePositions(mIndexCount);
auto time = mTimeControl->pSimulationTime.get();
auto const& observer = mSolarSystem->getObserver();
try {
cs::scene::CelestialAnchor centerAnchor(getCenterName(), getFrameName());
auto mat = observer.getRelativeTransform(time, centerAnchor);
for (size_t i(0); i < mIndexCount; ++i) {
vRelativePositions[i] = (mat * glm::dvec4(mSampledPositions[i], 1.0)).xyz();
}
// upload the new points to the GPU
mVBO.Bind(GL_ARRAY_BUFFER);
mVBO.BufferSubData(0, vRelativePositions.size() * sizeof(glm::vec3), vRelativePositions.data());
mVBO.Release();
glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_LINE_BIT);
// enable alpha blending for smooth line
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// enable and configure line rendering
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glLineWidth(5);
std::array<GLfloat, 16> glMatMV{};
std::array<GLfloat, 16> glMatP{};
glGetFloatv(GL_MODELVIEW_MATRIX, glMatMV.data());
glGetFloatv(GL_PROJECTION_MATRIX, glMatP.data());
mShader.Bind();
mVAO.Bind();
glUniformMatrix4fv(mUniforms.modelViewMatrix, 1, GL_FALSE, glMatMV.data());
glUniformMatrix4fv(mUniforms.projectionMatrix, 1, GL_FALSE, glMatP.data());
mShader.SetUniform(mUniforms.color, pColor.get().r, pColor.get().g, pColor.get().b);
mShader.SetUniform(mUniforms.farClip, cs::utils::getCurrentFarClipDistance());
// draw the linestrip
glDrawArrays(GL_LINE_STRIP, 0, static_cast<GLsizei>(mIndexCount));
mVAO.Release();
mShader.Release();
glPopAttrib();
} catch (std::exception const& e) { logger().warn("PathTool::Do failed: {}", e.what()); }
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
bool PathTool::GetBoundingBox(VistaBoundingBox& bb) {
std::array fMin{-0.1F, -0.1F, -0.1F};
std::array fMax{0.1F, 0.1F, 0.1F};
bb.SetBounds(fMin.data(), fMax.data());
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace csp::measurementtools
| 36.515738
| 100
| 0.602148
|
FellegaraR
|
0ced9f39706658dbfb6f60608eb52a71d9d40693
| 2,068
|
cpp
|
C++
|
library/src/Wav.cpp
|
StratifyLabs/AudioAPI
|
1c85a8ae188bc03d3699dec448bc9d6f3439e3d7
|
[
"MIT"
] | null | null | null |
library/src/Wav.cpp
|
StratifyLabs/AudioAPI
|
1c85a8ae188bc03d3699dec448bc9d6f3439e3d7
|
[
"MIT"
] | null | null | null |
library/src/Wav.cpp
|
StratifyLabs/AudioAPI
|
1c85a8ae188bc03d3699dec448bc9d6f3439e3d7
|
[
"MIT"
] | null | null | null |
// Copyright 2011-2021 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md for rights.
#include "audio/Wav.hpp"
using namespace audio;
using namespace fs;
Wav::Wav() : m_header({0}){}
Wav::Wav(const var::StringView path) : File(path) {
read(var::View(m_header));
}
Wav::Wav(IsOverwrite is_overwrite, const var::StringView path) : File(is_overwrite, path), m_header({0}) {}
Wav &Wav::copy_header(const Wav &reference) {
return set_header(SetHeader()
.set_channel_count(reference.channel_count())
.set_sample_rate(reference.sample_rate())
.set_bits_per_sample(reference.bits_per_sample())
.set_sample_count(reference.sample_count()));
}
Wav &Wav::set_header(const SetHeader &options) {
m_header.riff[0] = 'R';
m_header.riff[1] = 'I';
m_header.riff[2] = 'F';
m_header.riff[3] = 'F';
m_header.size = 0; // need to calculate later
m_header.wave[0] = 'W';
m_header.wave[1] = 'A';
m_header.wave[2] = 'V';
m_header.wave[3] = 'E';
m_header.format_description[0] = 'f';
m_header.format_description[1] = 'm';
m_header.format_description[2] = 't';
m_header.format_description[3] = ' ';
m_header.format_size = 16;
m_header.wav_format = 1; // 1 means PCM other value indicate compression
m_header.channels = options.channel_count();
m_header.sample_rate = options.sample_rate();
m_header.bytes_per_second = options.sample_rate() *
options.channel_count() *
options.bits_per_sample() / 8;
m_header.block_alignment =
options.channel_count() * options.bits_per_sample() / 8;
m_header.bits_per_sample = options.bits_per_sample();
m_header.data_description[0] = 'd';
m_header.data_description[1] = 'a';
m_header.data_description[2] = 't';
m_header.data_description[3] = 'a';
m_header.data_size = options.sample_count() * options.channel_count() *
options.bits_per_sample() / 8;
m_header.size = 36 + m_header.data_size;
return *this;
}
| 35.655172
| 107
| 0.651838
|
StratifyLabs
|
0ceeb3f3ad0db4a1d0dfb3c1253cd707a66031c3
| 683
|
hpp
|
C++
|
MPAGScipher/processCommandline.hpp
|
bear-cpp-course/day-1-zoulzubazz
|
fe88e9a38e7baf223a26d05e55ac3ac221df61a0
|
[
"MIT"
] | null | null | null |
MPAGScipher/processCommandline.hpp
|
bear-cpp-course/day-1-zoulzubazz
|
fe88e9a38e7baf223a26d05e55ac3ac221df61a0
|
[
"MIT"
] | null | null | null |
MPAGScipher/processCommandline.hpp
|
bear-cpp-course/day-1-zoulzubazz
|
fe88e9a38e7baf223a26d05e55ac3ac221df61a0
|
[
"MIT"
] | null | null | null |
#ifndef MPAGSCIPHER_PROCESSCOMMANDLINE_HPP
#define MPAGSCIPHER_PROCESSCOMMANDLINE_HPP
#include <string>
#include <cctype>
#include <vector>
#include <iostream>
#include "CipherMode.hpp"
/** Processes command line arguments input to the Ceaser cipher */
class ProcessCmdArgs{
public:
struct programSettings {
bool helpRequested = false;
bool versionRequested = false;
bool inputError = false;
int key = 0;
std::string inputFileName = "";
std::string outputFileName = "";
CipherMode cMode {CipherMode::encrypt};
};
/*struct ProcessCmdArgs:: */
programSettings processCommandLine(const std::vector<std::string>& args);
};
#endif
| 25.296296
| 73
| 0.711567
|
bear-cpp-course
|
0cf050c2cabebee94460a3e8fcb72dfd1ded2988
| 780
|
cpp
|
C++
|
test/test_homo_matrix.cpp
|
UnknownBugs/TMATH
|
043f320a6ed05459cc6de3144be8a15fcfbd0f53
|
[
"MIT"
] | null | null | null |
test/test_homo_matrix.cpp
|
UnknownBugs/TMATH
|
043f320a6ed05459cc6de3144be8a15fcfbd0f53
|
[
"MIT"
] | null | null | null |
test/test_homo_matrix.cpp
|
UnknownBugs/TMATH
|
043f320a6ed05459cc6de3144be8a15fcfbd0f53
|
[
"MIT"
] | null | null | null |
#include <iostream>
#define __INITIALIZER_LIST_HPP__
#include <matrix.hpp>
#include <homocoordinates.hpp>
#include <initializer_list>
template<typename T>
void printV(const T &v) {
for (int i = 0; i < v.size(); i++) {
std::cout << v[i] << "\t";
}
std::cout << std::endl;
}
template<typename T>
void printM(const T &m) {
for (int i = 0; i < m.getRow(); i++) {
for (int j = 0; j < m.getCol(); j++) {
std::cout << m[i][j] << "\t";
}
std::cout << std::endl;
}
}
int main() {
TMATH::HomoCoordinates<3> rectPointer { 100, 100, 1};
TMATH::Matrix<double, 3, 3> scale {
{2, 0, 0},
{0, 3, 0},
{0, 0, 1}
};
auto ans = scale * rectPointer;
printV(ans);
return 0;
}
| 17.727273
| 57
| 0.503846
|
UnknownBugs
|
0cf0ff109567188005ff55bd42571bd60a74e684
| 5,285
|
hpp
|
C++
|
src/main/include/cyng/core/wrapper.hpp
|
solosTec/cyng
|
3862a6b7a2b536d1f00fef20700e64170772dcff
|
[
"MIT"
] | null | null | null |
src/main/include/cyng/core/wrapper.hpp
|
solosTec/cyng
|
3862a6b7a2b536d1f00fef20700e64170772dcff
|
[
"MIT"
] | null | null | null |
src/main/include/cyng/core/wrapper.hpp
|
solosTec/cyng
|
3862a6b7a2b536d1f00fef20700e64170772dcff
|
[
"MIT"
] | null | null | null |
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 Sylko Olzscher
*
*/
#ifndef CYNG_CORE_WRAPPER_HPP
#define CYNG_CORE_WRAPPER_HPP
#include <CYNG_project_info.h>
#include <cyng/compatibility/legacy_mode.hpp>
#include <cyng/core/object_interface.h>
#include <cyng/object.h>
#include <cyng/core/class_impl.hpp>
#include <cyng/core/object_cast_fwd.h>
#include <cyng/core/value_cast_fwd.h>
#include <cyng/intrinsics/policy/hash.h>
#include <iostream>
#include <utility>
#include <functional>
namespace cyng
{
namespace core
{
/**
* @tparam T hidden data type
*/
template <typename T>
class wrapper
: public object_interface
, public std::enable_shared_from_this< wrapper< T > >
{
template < typename U >
friend const U* cyng::object_cast(object const&) noexcept;
template < typename U >
friend U cyng::value_cast(object const&, U const&) noexcept;
// friend const U& cyng::value_cast(object const&, U const&) noexcept;
using class_t = class_impl< T >;
using this_type = wrapper< T >;
public:
template < typename... Args >
wrapper(Args&&... args)
: held_(std::forward<Args>(args)...)
{}
wrapper(wrapper const&) = delete;
wrapper& operator=(wrapper const&) = delete;
virtual ~wrapper()
{}
/**
* Offers a route for safe copying. Requires that T
* can be copied.
*
* @return a copy of the value as shared pointer
*/
virtual shared_object clone() const override
{
return shared_object();
//return std::make_shared< wrapper< T > >(held_);
}
virtual class_interface const& get_class() const noexcept override
{
return static_cast<class_interface const&>(class_);
}
virtual std::size_t hash() const override
{
return std::hash<T>()(held_);
}
/**
* Reiteration of std::equal_to
*/
virtual bool equal_to(object const& obj) const noexcept override
{
if (typeid(T) == obj.get_class().type())
{
auto wp = std::dynamic_pointer_cast< this_type >(obj.value_);
if (wp)
{
return std::equal_to<T>()(this->held_, wp->held_);
}
return true;
}
return false;
}
/**
* Reiteration of std::less
*/
virtual bool less(object const& obj) const noexcept override
{
if (typeid(T) == obj.get_class().type())
{
auto wp = std::dynamic_pointer_cast< this_type >(obj.value_);
if (wp)
{
return std::less<T>()(this->held_, wp->held_);
}
return true;
}
return false;
}
private:
/**
* The hidden value
*/
T held_;
/*
* Class info is static. Therefore all pointers to the same
* class info are equal.
*/
static const class_t class_;
};
/**
* Initialize static data member class_
*/
template <typename T>
typename wrapper<T>::class_t const wrapper<T>::class_;
/**
* Specialized for arrays
*
* @tparam T hidden data type
* @tparam N array size
*/
template <typename T, std::size_t N>
class wrapper<T[N]>
: public object_interface
, public std::enable_shared_from_this< wrapper< T[N] > >
{
template < typename U >
friend const U* cyng::object_cast(object const&) noexcept;
template < typename U >
// friend const U& cyng::value_cast(object const&, U const&) noexcept;
friend U cyng::value_cast(object const&, U const&) noexcept;
using class_t = class_impl< T[N] >;
#if defined(CYNG_LEGACY_MODE_ON)
// using indices = typename generate_sequence<N>::type;
using indices = meta::make_index_sequence<N>;
#else
using indices = typename std::make_index_sequence<N>;
#endif
public:
wrapper()
: held_{0}
{}
/**
* Delegate constructor
*/
wrapper(T const(&v)[N])
: wrapper(v, indices{})
{}
#if defined(CYNG_LEGACY_MODE_ON)
template<std::size_t... I>
wrapper(T const(&v)[N], typename meta::generate_index_sequence<N>::type)
: held_{ v[I]... }
{}
#else
template<std::size_t... I>
wrapper(T const(&v)[N], std::index_sequence<I...>)
: held_{ v[I]... }
{}
#endif
virtual ~wrapper()
{}
virtual shared_object clone() const override
{
return std::make_shared< wrapper< T[N] > >(held_);
}
virtual class_interface const& get_class() const noexcept override
{
return static_cast<class_interface const&>(class_);
}
virtual std::size_t hash() const override
{
// ToDo: implement for arrays
return 0;
}
virtual bool equal_to(object const& obj) const noexcept override
{
// ToDo: implement for arrays
if (obj.get_class().is_array()) {
}
return false;
}
virtual bool less(object const& obj) const noexcept override
{
// ToDo: implement for arrays
if (obj.get_class().is_array()) {
}
return false;
}
private:
/**
* The hidden array
*/
T held_[N];
/*
* Class info is static. Therefore all pointers to the same
* class info are equal.
*/
static const class_t class_;
};
/**
* Initialize static data member class_
*/
template <typename T, std::size_t N>
typename wrapper<T[N]>::class_t const wrapper<T[N]>::class_;
}
}
#endif // CYNG_CORE_WRAPPER_HPP
| 21.396761
| 75
| 0.620814
|
solosTec
|
0cfa9fedbc74b618962d5a977d4370697bb70564
| 780
|
hpp
|
C++
|
libraries/chain/include/scorum/chain/operation_notification.hpp
|
scorum/scorum
|
1da00651f2fa14bcf8292da34e1cbee06250ae78
|
[
"MIT"
] | 53
|
2017-10-28T22:10:35.000Z
|
2022-02-18T02:20:48.000Z
|
libraries/chain/include/scorum/chain/operation_notification.hpp
|
Scorum/Scorum
|
fb4aa0b0960119b97828865d7a5b4d0409af7876
|
[
"MIT"
] | 38
|
2017-11-25T09:06:51.000Z
|
2018-10-31T09:17:22.000Z
|
libraries/chain/include/scorum/chain/operation_notification.hpp
|
Scorum/Scorum
|
fb4aa0b0960119b97828865d7a5b4d0409af7876
|
[
"MIT"
] | 27
|
2018-01-08T19:43:35.000Z
|
2022-01-14T10:50:42.000Z
|
#pragma once
#include <scorum/chain/schema/scorum_object_types.hpp>
#include <scorum/protocol/operations.hpp>
namespace scorum {
namespace chain {
struct operation_notification
{
operation_notification(protocol::transaction_id_type trx_id,
uint32_t block,
uint32_t trx_in_block,
uint16_t op_in_trx,
const protocol::operation& o)
: trx_id(trx_id)
, block(block)
, trx_in_block(trx_in_block)
, op_in_trx(op_in_trx)
, op(o)
{
}
const protocol::transaction_id_type trx_id;
const uint32_t block = 0;
const uint32_t trx_in_block = 0;
const uint16_t op_in_trx = 0;
const protocol::operation& op;
};
}
}
| 24.375
| 64
| 0.605128
|
scorum
|
0cfd9925e02970866f1d616127bc3a8588a2b411
| 5,230
|
cc
|
C++
|
src/api/auto_updater/api_auto_updater.cc
|
jtg-gg/node-webkit
|
bf309df6ccb7743f6211e5bcb109bb0fdf0ac294
|
[
"MIT"
] | 27
|
2015-03-11T10:04:08.000Z
|
2017-12-09T18:34:11.000Z
|
src/api/auto_updater/api_auto_updater.cc
|
jtg-gg/node-webkit
|
bf309df6ccb7743f6211e5bcb109bb0fdf0ac294
|
[
"MIT"
] | null | null | null |
src/api/auto_updater/api_auto_updater.cc
|
jtg-gg/node-webkit
|
bf309df6ccb7743f6211e5bcb109bb0fdf0ac294
|
[
"MIT"
] | 7
|
2015-08-12T05:15:39.000Z
|
2016-12-15T04:11:03.000Z
|
// Copyright (c) 2014 Jefry Tedjokusumo <jtg_gg@yahoo.com.sg>
//
// 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 co
// pies 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 al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER 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 "base/values.h"
#include "content/nw/src/api/auto_updater/api_auto_updater.h"
#include "content/nw/src/api/nw_auto_updater.h"
#include "content/nw/src/browser/auto_updater.h"
#include "extensions/browser/extensions_browser_client.h"
using namespace extensions::nwapi::nw__auto_updater;
using namespace content;
namespace extensions {
static void DispatchEvent(events::HistogramValue histogram_value,
const std::string& event_name,
scoped_ptr<base::ListValue> args) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
ExtensionsBrowserClient::Get()->BroadcastEventToRenderers(
histogram_value, event_name, std::move(args));
}
class AutoUpdaterObserver : public auto_updater::Delegate {
// An error happened.
void OnError(const std::string& error) override {
scoped_ptr<base::ListValue> arguments (new base::ListValue());
arguments->AppendString(error);
DispatchEvent(events::HistogramValue::UNKNOWN,
nwapi::nw__auto_updater::OnError::kEventName,
std::move(arguments));
}
// Checking to see if there is an update
void OnCheckingForUpdate() override {
scoped_ptr<base::ListValue> arguments (new base::ListValue());
DispatchEvent(events::HistogramValue::UNKNOWN,
nwapi::nw__auto_updater::OnCheckingForUpdate::kEventName,
std::move(arguments));
}
// There is an update available and it is being downloaded
void OnUpdateAvailable() override {
scoped_ptr<base::ListValue> arguments (new base::ListValue());
DispatchEvent(events::HistogramValue::UNKNOWN,
nwapi::nw__auto_updater::OnUpdateAvailable::kEventName,
std::move(arguments));
}
// There is no available update.
void OnUpdateNotAvailable() override {
scoped_ptr<base::ListValue> arguments (new base::ListValue());
DispatchEvent(events::HistogramValue::UNKNOWN,
nwapi::nw__auto_updater::OnUpdateNotAvailable::kEventName,
std::move(arguments));
}
// There is a new update which has been downloaded.
void OnUpdateDownloaded(const std::string& release_notes,
const std::string& release_name,
const base::Time& release_date,
const std::string& update_url) override {
scoped_ptr<base::ListValue> arguments (new base::ListValue());
arguments->AppendString(release_notes);
arguments->AppendString(release_name);
arguments->AppendDouble(release_date.ToJsTime());
arguments->AppendString(update_url);
DispatchEvent(events::HistogramValue::UNKNOWN,
nwapi::nw__auto_updater::OnUpdateDownloaded::kEventName,
std::move(arguments));
}
public:
AutoUpdaterObserver() {
}
~AutoUpdaterObserver() override {
}
};
AutoUpdaterObserver gAutoUpdateObserver;
NwAutoUpdaterNativeCallSyncFunction::NwAutoUpdaterNativeCallSyncFunction() {}
bool NwAutoUpdaterNativeCallSyncFunction::RunNWSync(base::ListValue* response, std::string* error) {
if (!auto_updater::AutoUpdater::GetDelegate()) {
auto_updater::AutoUpdater::SetDelegate(&gAutoUpdateObserver);
}
std::string method;
EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &method));
if (method == "SetFeedURL") {
auto_updater::AutoUpdater::HeaderMap headers;
std::string url;
EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &url));
auto_updater::AutoUpdater::SetFeedURL(url, headers);
} else if (method == "GetFeedURL") {
std::string url = auto_updater::AutoUpdater::GetFeedURL();
response->AppendString(url);
} else if (method == "QuitAndInstall") {
auto_updater::AutoUpdater::QuitAndInstall();
} else if (method == "CheckForUpdates") {
auto_updater::AutoUpdater::CheckForUpdates();
}
return true;
}
} // namespace extension
| 40.859375
| 102
| 0.682218
|
jtg-gg
|
4906612fb7ee9dda4e91807a359f35958641ea5a
| 4,618
|
cxx
|
C++
|
plugins/data/modules/rectilinear_grid_to_image/rectilinear_grid_to_image.cxx
|
moritz-h/ParaView-Plugins
|
b32e5dc4e710b25dc3f00b87a616e954d8549002
|
[
"MIT"
] | null | null | null |
plugins/data/modules/rectilinear_grid_to_image/rectilinear_grid_to_image.cxx
|
moritz-h/ParaView-Plugins
|
b32e5dc4e710b25dc3f00b87a616e954d8549002
|
[
"MIT"
] | null | null | null |
plugins/data/modules/rectilinear_grid_to_image/rectilinear_grid_to_image.cxx
|
moritz-h/ParaView-Plugins
|
b32e5dc4e710b25dc3f00b87a616e954d8549002
|
[
"MIT"
] | 1
|
2021-02-22T16:27:28.000Z
|
2021-02-22T16:27:28.000Z
|
#include "rectilinear_grid_to_image.h"
#include "common/checks.h"
#include "vtkCellData.h"
#include "vtkDataArray.h"
#include "vtkFieldData.h"
#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkRectilinearGrid.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include <array>
#include <cmath>
#include <iostream>
vtkStandardNewMacro(rectilinear_grid_to_image);
rectilinear_grid_to_image::rectilinear_grid_to_image()
{
this->SetNumberOfInputPorts(1);
this->SetNumberOfOutputPorts(1);
}
rectilinear_grid_to_image::~rectilinear_grid_to_image() {}
int rectilinear_grid_to_image::FillInputPortInformation(int port, vtkInformation* info)
{
if (!this->Superclass::FillInputPortInformation(port, info))
{
return 0;
}
if (port == 0)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkRectilinearGrid");
return 1;
}
return 0;
}
int rectilinear_grid_to_image::RequestUpdateExtent(vtkInformation* vtkNotUsed(request), vtkInformationVector** input_vector, vtkInformationVector* output_vector)
{
return 1;
}
int rectilinear_grid_to_image::RequestData(vtkInformation* vtkNotUsed(request), vtkInformationVector** input_vector, vtkInformationVector* output_vector)
{
// Get access to information and data
auto in_info = input_vector[0]->GetInformationObject(0);
auto input = vtkRectilinearGrid::SafeDownCast(in_info->Get(vtkDataObject::DATA_OBJECT()));
__check_not_null_ret(input, "Input is not a rectilinear grid.");
// Get output
auto out_info = output_vector->GetInformationObject(0);
auto output = vtkImageData::SafeDownCast(out_info->Get(vtkDataObject::DATA_OBJECT()));
__check_not_null_ret(output, "Output is not an image.");
// Create image from rectilinear grid
std::array<int, 6> extent{};
input->GetExtent(extent.data());
auto coordinates_x = input->GetXCoordinates();
auto coordinates_y = input->GetYCoordinates();
auto coordinates_z = input->GetZCoordinates();
const std::array<double, 3> origin{
coordinates_x->GetComponent(0, 0),
coordinates_y->GetComponent(0, 0),
coordinates_z->GetComponent(0, 0)
};
const std::array<double, 3> spacing{
(coordinates_x->GetNumberOfTuples() > 1) ? (coordinates_x->GetComponent(1, 0) - coordinates_x->GetComponent(0, 0)) : 0.0,
(coordinates_y->GetNumberOfTuples() > 1) ? (coordinates_y->GetComponent(1, 0) - coordinates_y->GetComponent(0, 0)) : 0.0,
(coordinates_z->GetNumberOfTuples() > 1) ? (coordinates_z->GetComponent(1, 0) - coordinates_z->GetComponent(0, 0)) : 0.0
};
output->SetExtent(extent.data());
output->SetOrigin(origin.data());
output->SetSpacing(spacing.data());
// Check if input is an image
double previous = coordinates_x->GetComponent(0, 0);
for (vtkIdType i = 1; i < coordinates_x->GetNumberOfTuples(); ++i)
{
const auto current = coordinates_x->GetComponent(i, 0);
const auto difference = std::abs(current - previous);
if (std::abs(spacing[0] - difference) > 1.0e-6)
{
std::cerr << "Input cannot be converted to image: X coordinates are not equally spaced." << std::endl;
return 0;
}
previous = current;
}
previous = coordinates_y->GetComponent(0, 0);
for (vtkIdType i = 1; i < coordinates_y->GetNumberOfTuples(); ++i)
{
const auto current = coordinates_y->GetComponent(i, 0);
const auto difference = std::abs(current - previous);
if (std::abs(spacing[0] - difference) > 1.0e-6)
{
std::cerr << "Input cannot be converted to image: Y coordinates are not equally spaced." << std::endl;
return 0;
}
previous = current;
}
previous = coordinates_z->GetComponent(0, 0);
for (vtkIdType i = 1; i < coordinates_z->GetNumberOfTuples(); ++i)
{
const auto current = coordinates_z->GetComponent(i, 0);
const auto difference = std::abs(current - previous);
if (std::abs(spacing[0] - difference) > 1.0e-6)
{
std::cerr << "Input cannot be converted to image: Z coordinates are not equally spaced." << std::endl;
return 0;
}
previous = current;
}
// Copy data
output->GetPointData()->ShallowCopy(input->GetPointData());
output->GetCellData()->ShallowCopy(input->GetCellData());
output->GetFieldData()->ShallowCopy(input->GetFieldData());
return 1;
}
| 30.993289
| 161
| 0.67042
|
moritz-h
|
490ac8955842cc316bdd2c92b6e90afcec944db5
| 892
|
cpp
|
C++
|
test/either/object.cpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
test/either/object.cpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
test/either/object.cpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Carl Philipp Reh 2009 - 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 <fcppt/either/object.hpp>
#include <fcppt/config/external_begin.hpp>
#include <catch2/catch.hpp>
#include <string>
#include <fcppt/config/external_end.hpp>
TEST_CASE(
"either::object",
"[either]"
)
{
typedef
fcppt::either::object<
std::string,
int
>
either;
SECTION(
"test failure"
)
{
either const test1(
std::string(
"failure"
)
);
REQUIRE(
test1.has_failure()
);
CHECK(
test1.get_failure_unsafe()
==
std::string(
"failure"
)
);
}
SECTION(
"test success"
)
{
either const test2( 42
);
REQUIRE(
test2.has_success()
);
CHECK(
test2.get_success_unsafe()
==
42
);
}
}
| 13.313433
| 61
| 0.619955
|
pmiddend
|
490b610e09bac10f7383756124e594ca378c1537
| 3,721
|
cpp
|
C++
|
src/transport/websocket/WsFrame.cpp
|
xDimon/primitive
|
092e9158444710cdde45c57c4115efa06c85e161
|
[
"Apache-2.0"
] | 12
|
2017-09-12T20:47:16.000Z
|
2019-04-05T11:39:40.000Z
|
src/transport/websocket/WsFrame.cpp
|
xDimon/primitive
|
092e9158444710cdde45c57c4115efa06c85e161
|
[
"Apache-2.0"
] | null | null | null |
src/transport/websocket/WsFrame.cpp
|
xDimon/primitive
|
092e9158444710cdde45c57c4115efa06c85e161
|
[
"Apache-2.0"
] | 1
|
2018-11-23T16:51:55.000Z
|
2018-11-23T16:51:55.000Z
|
// Copyright © 2017-2019 Dmitriy Khaustov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Dmitriy Khaustov aka xDimon
// Contacts: khaustov.dm@gmail.com
// File created on: 2017.03.31
// WsFrame.cpp
#include <cstring>
#include "WsFrame.hpp"
size_t WsFrame::calcHeaderSize(const char data[2])
{
uint8_t prelen = (static_cast<uint8_t>(data[1]) >> 0) & static_cast<uint8_t>(0x7F);
uint8_t masked = (static_cast<uint8_t>(data[1]) >> 7) & static_cast<uint8_t>(0x01);
return 2 // Стартовые байты
+ ((prelen <= 125) ? 0 : (prelen == 126) ? 2 : 8) // Байты расширенной длины
+ ((masked == 0) ? 0 : 4); // Байты маски
}
WsFrame::WsFrame(const char *begin, const char *end)
{
auto s = begin;
_finaly = static_cast<bool>((s[0] >> 7) & 0x01);
_opcode = static_cast<Opcode>((s[0] >> 0) & 0x0F);
_masked = static_cast<bool>((s[1] >> 7) & 0x01);
uint8_t prelen = (static_cast<uint8_t>(s[1]) >> 0) & static_cast<uint8_t>(0x7F);
if ((s + 2) > end)
{
throw std::runtime_error("Not anough data");
}
s += 2;
if (prelen < 126)
{
_length = prelen;
}
else if (prelen == 126)
{
if ((s + 2) > end)
{
throw std::runtime_error("Not anough data");
}
uint16_t length;
memcpy(&length, s, sizeof(length));
s += sizeof(length);
_length = be16toh(length);
}
else if (prelen == 127)
{
if ((s + 8) > end)
{
throw std::runtime_error("Not anough data");
}
uint64_t length;
memcpy(&length, s, sizeof(length));
s += sizeof(length);
_length = be64toh(length);
}
if (_masked)
{
if ((s + 4) > end)
{
throw std::runtime_error("Not anough data");
}
_mask[0] = static_cast<uint8_t>(*s++);
_mask[1] = static_cast<uint8_t>(*s++);
_mask[2] = static_cast<uint8_t>(*s++);
_mask[3] = static_cast<uint8_t>(*s);
}
else
{
_mask[0] =
_mask[1] =
_mask[2] =
_mask[3] = 0;
}
}
void WsFrame::applyMask()
{
if (!_masked)
{
return;
}
int i = 0;
size_t remain = dataLen();
for (auto &b : _data)
{
b ^= _mask[i++];
if (--remain == 0)
{
break;
}
if (i == 4)
{
i = 0;
}
}
}
void WsFrame::send(const std::shared_ptr<Writer>& writer, Opcode code, const char* data, size_t size)
{
// bool masked = false;
uint8_t byte;
byte = (static_cast<uint8_t>(1) << 7) | static_cast<uint8_t>(code);
writer->write(&byte, sizeof(byte));
byte = static_cast<uint8_t>((size > 65535) ? 127 : (size > 125) ? 126 : size);
// if (masked)
// {
// byte |= (1_u8 << 7);
// }
writer->write(&byte, sizeof(byte));
if (size > 65535)
{
uint64_t size64 = htobe64(static_cast<uint64_t>(size));
writer->write(&size64, sizeof(size64));
}
else if (size > 125)
{
uint16_t size16 = htobe16(static_cast<uint16_t>(size));
writer->write(&size16, sizeof(size16));
}
// if (!masked)
// {
writer->write(data, size);
// return;
// }
//
// union {
// uint32_t i;
// uint8_t b[4];
// } mask;
//
// mask.i = static_cast<uint32_t>(std::rand());
//
// for (size_t i = 0; i < sizeof(mask.b); i++)
// {
// writer->write(&mask.b[i], 1);
// }
//
// int i = 0;
// while (size--)
// {
// byte = static_cast<uint8_t>(*data++) ^ mask.b[i++];
//
// writer->write(&byte, sizeof(byte));
//
// if (i == 4)
// {
// i = 0;
// }
// }
}
| 21.022599
| 101
| 0.604139
|
xDimon
|
490b69a7d63573e84afe1e53cba007ee4d383ff5
| 523
|
hpp
|
C++
|
src/headers/universal_ref.hpp
|
HrvojeFER/cpp_bench
|
f3657e58255b14ff256a4a892c790bd813fab850
|
[
"MIT"
] | null | null | null |
src/headers/universal_ref.hpp
|
HrvojeFER/cpp_bench
|
f3657e58255b14ff256a4a892c790bd813fab850
|
[
"MIT"
] | null | null | null |
src/headers/universal_ref.hpp
|
HrvojeFER/cpp_bench
|
f3657e58255b14ff256a4a892c790bd813fab850
|
[
"MIT"
] | null | null | null |
enum class ref_type_t
{
lvalue,
rvalue,
value
};
template <typename T>
constexpr inline ref_type_t get_ref_type(T &&of) noexcept
{
if constexpr (std::is_rvalue_reference_v<T>)
return ref_type_t::rvalue;
else if constexpr (std::is_lvalue_reference_v<T>)
return ref_type_t::lvalue;
else
return ref_type_t::value;
}
TEST_CASE("universal_ref")
{
int lvalue{1};
REQUIRE_EQ(get_ref_type(1), ref_type_t::value);
REQUIRE_EQ(get_ref_type(lvalue), ref_type_t::lvalue);
}
| 20.92
| 57
| 0.688337
|
HrvojeFER
|
49154c2311e38eb121bc44a1aec5ebfef7431758
| 2,270
|
cpp
|
C++
|
test/peer/test_peer_manager.cpp
|
EPI-ONE/epic
|
c314cab526641c00d49e51e08ec0793f1a6c171b
|
[
"MIT"
] | 24
|
2019-10-14T14:35:32.000Z
|
2021-11-28T02:06:26.000Z
|
test/peer/test_peer_manager.cpp
|
EPI-ONE/epic
|
c314cab526641c00d49e51e08ec0793f1a6c171b
|
[
"MIT"
] | 3
|
2019-10-14T14:29:07.000Z
|
2020-01-21T14:48:49.000Z
|
test/peer/test_peer_manager.cpp
|
EPI-ONE/epic
|
c314cab526641c00d49e51e08ec0793f1a6c171b
|
[
"MIT"
] | 4
|
2020-04-09T09:12:50.000Z
|
2021-06-15T13:41:42.000Z
|
// Copyright (c) 2019 EPI-ONE Core Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <gtest/gtest.h>
#include "peer_manager.h"
#include "test_env.h"
class TestPeerManager : public testing::Test {
public:
PeerManager server;
PeerManager client;
static void SetUpTestCase() {
CONFIG = std::make_unique<Config>();
EpicTestEnvironment::SetUpDAG("test_peer_manager/");
}
static void TearDownTestCase() {
CONFIG.reset();
EpicTestEnvironment::TearDownDAG("test_peer_manager/");
}
void SetUp() {
CONFIG->SetAmISeed(true);
server.Start();
client.Start();
}
void TearDown() {
CONFIG->SetAmISeed(false);
server.Stop();
client.Stop();
}
};
TEST_F(TestPeerManager, CallBack) {
ASSERT_TRUE(server.Bind("127.0.0.1"));
ASSERT_TRUE(server.Listen(43250));
ASSERT_TRUE(client.ConnectTo("127.0.0.1:43250"));
usleep(50000);
EXPECT_EQ(server.GetFullyConnectedPeerSize(), 1);
EXPECT_EQ(client.GetFullyConnectedPeerSize(), 1);
}
TEST_F(TestPeerManager, CheckHaveConnectedSameIP) {
ASSERT_TRUE(server.Bind("127.0.0.1"));
ASSERT_TRUE(server.Listen(43260));
ASSERT_TRUE(client.ConnectTo("127.0.0.1:43260"));
usleep(50000);
PeerManager same_ip_client;
same_ip_client.Start();
same_ip_client.ConnectTo("127.0.0.1:43260");
usleep(50000);
EXPECT_EQ(server.GetFullyConnectedPeerSize(), 2);
EXPECT_EQ(same_ip_client.GetConnectedPeerSize(), 1);
ASSERT_EQ(server.RandomlySelect(2).size(), 2);
same_ip_client.Stop();
}
TEST_F(TestPeerManager, RelayProtocol) {
ASSERT_TRUE(server.Bind("127.0.0.1"));
ASSERT_TRUE(server.Listen(43280));
usleep(50000);
TestFactory fac = EpicTestEnvironment::GetFactory();
auto block = fac.CreateBlockPtr();
block->SetCount(1);
server.RelayBlock(block, nullptr);
ASSERT_EQ(block->GetCount(), 1);
ASSERT_TRUE(client.ConnectTo("127.0.0.1:43280"));
usleep(50000);
server.RelayBlock(block, nullptr);
ASSERT_EQ(block->GetCount(), 0);
server.RelayBlock(block, nullptr);
ASSERT_EQ(block->GetCount(), 0);
}
| 27.02381
| 70
| 0.673128
|
EPI-ONE
|
491598848f75b9bb37ca887549d71920846aebbc
| 240
|
cpp
|
C++
|
[Lib]__RanClientUI/Sources/InnerUI/PrivateMarketShow.cpp
|
yexiuph/RanOnline
|
7f7be07ef740c8e4cc9c7bef1790b8d099034114
|
[
"Apache-2.0"
] | null | null | null |
[Lib]__RanClientUI/Sources/InnerUI/PrivateMarketShow.cpp
|
yexiuph/RanOnline
|
7f7be07ef740c8e4cc9c7bef1790b8d099034114
|
[
"Apache-2.0"
] | null | null | null |
[Lib]__RanClientUI/Sources/InnerUI/PrivateMarketShow.cpp
|
yexiuph/RanOnline
|
7f7be07ef740c8e4cc9c7bef1790b8d099034114
|
[
"Apache-2.0"
] | null | null | null |
#include "pch.h"
#include "PrivateMarketShow.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
CPrivateMarketShow::CPrivateMarketShow ()
: m_dwGaeaID ( UINT_MAX )
, m_bUsedMemPool( false )
{
}
CPrivateMarketShow::~CPrivateMarketShow ()
{
}
| 15
| 42
| 0.745833
|
yexiuph
|
491bcc4eb54adf38abd2bdd60824f3e756aa77ab
| 524
|
cpp
|
C++
|
Source/VSDKInputPlugin/Interactions/InteractableComponent.cpp
|
charles-river-analytics/VSDK-Unreal
|
0f99ec140f6d6660a09148163bdd006c5ecc67d5
|
[
"MIT"
] | 3
|
2021-05-26T14:12:01.000Z
|
2022-01-09T01:15:12.000Z
|
Source/VSDKInputPlugin/Interactions/InteractableComponent.cpp
|
charles-river-analytics/VSDK-Unreal
|
0f99ec140f6d6660a09148163bdd006c5ecc67d5
|
[
"MIT"
] | null | null | null |
Source/VSDKInputPlugin/Interactions/InteractableComponent.cpp
|
charles-river-analytics/VSDK-Unreal
|
0f99ec140f6d6660a09148163bdd006c5ecc67d5
|
[
"MIT"
] | null | null | null |
// Copyright 2020 Charles River Analytics, Inc. All Rights Reserved.
#include "InteractableComponent.h"
UInteractableComponent::UInteractableComponent()
{
bIsComponentActive = false;
InteractableObject = Cast<AInteractableObject>(GetOwner());
}
void UInteractableComponent::BeginPlay()
{
Super::BeginPlay();
}
FName UInteractableComponent::GetComponentName()
{
return ComponentName;
}
// Default interactable component is not actionable
bool UInteractableComponent::IsActionable_Implementation()
{
return false;
}
| 20.153846
| 68
| 0.795802
|
charles-river-analytics
|
491efd93876ce5b551222828e827983764b44f44
| 3,797
|
cpp
|
C++
|
main.cpp
|
TheQuantumPhysicist/HttpRpcRelay
|
810d9ed8907b4c769faa432ba7f829445b8d6f9f
|
[
"MIT"
] | null | null | null |
main.cpp
|
TheQuantumPhysicist/HttpRpcRelay
|
810d9ed8907b4c769faa432ba7f829445b8d6f9f
|
[
"MIT"
] | null | null | null |
main.cpp
|
TheQuantumPhysicist/HttpRpcRelay
|
810d9ed8907b4c769faa432ba7f829445b8d6f9f
|
[
"MIT"
] | null | null | null |
#include "Logging/DefaultLogger.h"
#include "Relay/JsonRpcRelay.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include <atomic>
#include <boost/program_options.hpp>
#include <cstdlib>
#include <thread>
#include <vector>
std::atomic<bool> g_ShutdownProgram{false};
void interrupt_handler(int)
{
if (!g_ShutdownProgram) {
LogWrite("Signal sent to stop application. Setting stop flag.", b_sev::info);
g_ShutdownProgram.store(true);
}
}
int main(int argc, char* argv[])
{
g_ShutdownProgram.store(false);
signal(SIGINT, interrupt_handler);
namespace params = boost::program_options;
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
LoggerSingleton::get().add_stream(console_sink, b_sev::info);
params::options_description desc("Program options");
// clang-format off
desc.add_options()("help", "produce help message")
("bind_address", params::value<std::string>(), "Server bind address (e.g., 127.0.0.1 or 0.0.0.0)")
("bind_port", params::value<uint16_t>(),"Server bind port")
("target_address", params::value<std::string>(),"Target address to send requests to that pass")
("target_port", params::value<uint16_t>(),"Target port to send requests that pass")
("filter_kind", params::value<std::string>(),"Filter kind to be used; default is jsonrpc filter")
("filter_options", params::value<std::string>(),"Filter definitions based on the filter you choose (for jsonrpc, it's a comma separated list of allowed methods)")
("threads", params::value<uint32_t>(),"Number of threads to use in the application");
// clang-format on
params::variables_map vm;
params::store(params::parse_command_line(argc, argv, desc), vm);
params::notify(vm);
if (vm.count("help")) {
std::cout << "Basic Command Line Parameter App" << std::endl << desc << std::endl;
return EXIT_SUCCESS;
}
std::string server_bind_address;
uint16_t server_bind_port;
std::string target_bind_address;
uint16_t target_bind_port;
uint32_t thread_count;
std::string filter_options;
try {
server_bind_address = vm["bind_address"].as<std::string>();
server_bind_port = vm["bind_port"].as<uint16_t>();
target_bind_address = vm["target_address"].as<std::string>();
target_bind_port = vm["target_port"].as<uint16_t>();
thread_count = std::thread::hardware_concurrency();
if (vm.find("threads") != vm.cend()) {
thread_count = vm["threads"].as<uint32_t>();
}
if (vm.find("filter_kind") != vm.cend()) {
// currently there's only jsonrpc filter, so this is no-op
}
if (vm.find("filter_options") == vm.cend()) {
throw std::runtime_error("The argument filter_options should be specified");
}
filter_options = vm["filter_options"].as<std::string>();
} catch (std::bad_cast& ex) {
std::cerr << std::endl
<< "Please include all required options. Use the command line `--help` to see them. "
<< std::endl
<< std::endl;
return EXIT_FAILURE;
}
/////////// start the server
JsonRPCFilter filter;
filter.applyOptions(filter_options);
JsonRpcRelay relay(std::move(filter),
server_bind_address,
server_bind_port,
target_bind_address,
target_bind_port,
thread_count);
while (!g_ShutdownProgram.load(std::memory_order_relaxed)) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
relay.stop();
return EXIT_SUCCESS;
}
| 36.864078
| 174
| 0.622597
|
TheQuantumPhysicist
|
492089b402c774f2fd897795f4a392beefdd1350
| 2,476
|
cpp
|
C++
|
libmoon/deps/MoonState/deps/AstraeusVPN/src/dtlsClientSpam.cpp
|
anonReview/Implementation
|
b86e0c48a1a9183a143687a2875b160504bcb202
|
[
"MIT"
] | null | null | null |
libmoon/deps/MoonState/deps/AstraeusVPN/src/dtlsClientSpam.cpp
|
anonReview/Implementation
|
b86e0c48a1a9183a143687a2875b160504bcb202
|
[
"MIT"
] | null | null | null |
libmoon/deps/MoonState/deps/AstraeusVPN/src/dtlsClientSpam.cpp
|
anonReview/Implementation
|
b86e0c48a1a9183a143687a2875b160504bcb202
|
[
"MIT"
] | 1
|
2020-08-14T02:53:20.000Z
|
2020-08-14T02:53:20.000Z
|
#include <array>
#include <cerrno>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <arpa/inet.h>
#include <cstring>
#include <signal.h>
#include <sys/select.h>
#include <unistd.h>
#include "common.hpp"
#include "dtls.hpp"
#include "tap.hpp"
using namespace std;
// Taken from:
// https://stackoverflow.com/a/20602159
struct pairhash {
public:
template <typename T, typename U> std::size_t operator()(const std::pair<T, U> &x) const {
return std::hash<T>()(x.first) ^ std::hash<U>()(x.second);
}
};
static int stopFlag = 0;
void sigHandler(int sig) {
(void)sig;
stopFlag = 1;
}
int runConnect(int fd, char *buf, int bufLen, SSL_CTX *ctx, struct sockaddr_in *dst_addr) {
DEBUG_ENABLED(std::cout << "run handlePacket" << std::endl;)
DTLS::Connection conn = DTLS::createClientConn(ctx);
// Start the handshake
SSL_connect(conn.ssl);
// Write out all data
int readCount;
while ((readCount = BIO_read(conn.wbio, buf, bufLen)) > 0) {
int sendBytes = sendto(
fd, buf, readCount, 0, (struct sockaddr *)dst_addr, sizeof(struct sockaddr_in));
if (sendBytes != readCount) {
throw new std::system_error(std::error_code(errno, std::generic_category()),
std::string("runConnect() sendto() failed"));
} else {
DEBUG_ENABLED(std::cout << "runConnect() Send packet to peer" << std::endl;)
}
}
return 0;
};
void usage(string name) {
cout << "Usage: " << name << " <server IP> <server port>" << endl;
exit(0);
}
int main(int argc, char **argv) {
try {
if (argc < 3) {
usage(string(argv[0]));
}
// Prepare server address
struct sockaddr_in server;
if (inet_aton(argv[1], &server.sin_addr) != 1) {
cout << "inet_aton() failed" << endl;
exit(EXIT_FAILURE);
}
server.sin_port = htons(atoi(argv[2]));
server.sin_family = AF_INET;
signal(SIGINT, sigHandler);
SSL_CTX *ctx = DTLS::createClientCTX();
// Create the server UDP listener socket
int fd = DTLS::createSocket();
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv, sizeof(struct timeval));
std::cout << "socket created" << std::endl;
char buf[2048];
while (stopFlag == 0) {
runConnect(fd, buf, 2048, ctx, &server);
}
close(fd);
std::cout << "Client shutting down..." << std::endl;
} catch (std::exception *e) {
std::cout << "Caught exception:" << std::endl;
std::cout << e->what() << std::endl;
}
}
| 22.715596
| 91
| 0.651454
|
anonReview
|
4924694af36a1abdb478c850a1ac12136321b7ba
| 2,716
|
cpp
|
C++
|
WinGUI/add35mmFocalLengthGUI.cpp
|
devil-tamachan/add35mmFocalLength
|
01b084c2421fb75483350a17ed2b7fb1d45bbdf4
|
[
"BSD-3-Clause"
] | 2
|
2018-06-13T18:17:26.000Z
|
2019-01-06T16:30:19.000Z
|
WinGUI/add35mmFocalLengthGUI.cpp
|
devil-tamachan/add35mmFocalLength
|
01b084c2421fb75483350a17ed2b7fb1d45bbdf4
|
[
"BSD-3-Clause"
] | null | null | null |
WinGUI/add35mmFocalLengthGUI.cpp
|
devil-tamachan/add35mmFocalLength
|
01b084c2421fb75483350a17ed2b7fb1d45bbdf4
|
[
"BSD-3-Clause"
] | null | null | null |
/*
licenced by New BSD License
Copyright (c) 2014, devil.tamachan@gmail.com
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "stdafx.h"
#include <atlframe.h>
#include <atlctrls.h>
#include <atldlgs.h>
#include "resource.h"
#include "MainDlg.h"
CAppModule _Module;
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR /*lpstrCmdLine*/, int nCmdShow)
{
HRESULT hRes = ::CoInitialize(NULL);
// If you are running on NT 4.0 or higher you can use the following call instead to
// make the EXE free threaded. This means that calls come in on a random RPC thread.
// HRESULT hRes = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
ATLASSERT(SUCCEEDED(hRes));
// this resolves ATL window thunking problem when Microsoft Layer for Unicode (MSLU) is used
::DefWindowProc(NULL, 0, 0, 0L);
AtlInitCommonControls(ICC_BAR_CLASSES); // add flags to support other controls
hRes = _Module.Init(NULL, hInstance);
ATLASSERT(SUCCEEDED(hRes));
CMessageLoop theLoop;
_Module.AddMessageLoop(&theLoop);
int nRet = 0;
// BLOCK: Run application
CMainDlg dlgMain;
//nRet = dlgMain.DoModal();
dlgMain.Create(NULL);
dlgMain.ShowWindow(nCmdShow);
nRet = theLoop.Run();
_Module.RemoveMessageLoop();
_Module.Term();
::CoUninitialize();
return nRet;
}
| 34.820513
| 109
| 0.764359
|
devil-tamachan
|
492fc81cc8c20851bfaeb5d2c5161934aa6789cd
| 533
|
cpp
|
C++
|
src/debug_gui/column.cpp
|
degarashi/revenant
|
9e671320a5c8790f6bdd1b14934f81c37819f7b3
|
[
"MIT"
] | null | null | null |
src/debug_gui/column.cpp
|
degarashi/revenant
|
9e671320a5c8790f6bdd1b14934f81c37819f7b3
|
[
"MIT"
] | null | null | null |
src/debug_gui/column.cpp
|
degarashi/revenant
|
9e671320a5c8790f6bdd1b14934f81c37819f7b3
|
[
"MIT"
] | null | null | null |
#include "column.hpp"
#include "../imgui/imgui.h"
#include "lubee/src/error.hpp"
namespace rev {
namespace debug {
ColumnPush::ColumnPush(const int n, const bool border):
_prev(ImGui::GetColumnsCount()),
_n(n)
{
if(_prev > 1)
ImGui::Columns(1);
if(n > 1)
ImGui::Columns(n, nullptr, border);
}
ColumnPush::ColumnPush(ColumnPush&& c):
_prev(c._prev),
_n(c._n)
{
c._prev = -1;
}
ColumnPush::~ColumnPush() {
if(_prev >= 1) {
ImGui::Columns(1);
ImGui::Columns(_prev);
}
}
}
}
| 17.766667
| 57
| 0.596623
|
degarashi
|
493756ad5a8ab388429b34ed5c3a39ec5f7d9d04
| 7,406
|
cpp
|
C++
|
src/runtime/type/ucase.cpp
|
sparkoss/ccm
|
9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d
|
[
"Apache-2.0"
] | 6
|
2018-05-08T10:08:21.000Z
|
2021-11-13T13:22:58.000Z
|
src/runtime/type/ucase.cpp
|
sparkoss/ccm
|
9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d
|
[
"Apache-2.0"
] | 1
|
2018-05-08T10:20:17.000Z
|
2018-07-23T05:19:19.000Z
|
src/runtime/type/ucase.cpp
|
sparkoss/ccm
|
9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d
|
[
"Apache-2.0"
] | 4
|
2018-03-13T06:21:11.000Z
|
2021-06-19T02:48:07.000Z
|
//=========================================================================
// Copyright (C) 2018 The C++ Component Model(CCM) Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
// Copyright (C) 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
*
* Copyright (C) 2004-2014, International Business Machines
* Corporation and others. All Rights Reserved.
*
*******************************************************************************
* file name: ucase.cpp
* encoding: US-ASCII
* tab size: 8 (not used)
* indentation:4
*
* created on: 2004aug30
* created by: Markus W. Scherer
*
* Low-level Unicode character/string case mapping code.
* Much code moved here (and modified) from uchar.c.
*/
#include "ucase.h"
#include "utrie2.h"
/** An ICU version consists of up to 4 numbers from 0..255.
* @stable ICU 2.4
*/
#define U_MAX_VERSION_LENGTH 4
/** The binary form of a version on ICU APIs is an array of 4 uint8_t.
* To compare two versions, use memcmp(v1,v2,sizeof(UVersionInfo)).
* @stable ICU 2.4
*/
typedef uint8_t UVersionInfo[U_MAX_VERSION_LENGTH];
/* indexes into indexes[] */
enum {
UCASE_IX_INDEX_TOP,
UCASE_IX_LENGTH,
UCASE_IX_TRIE_SIZE,
UCASE_IX_EXC_LENGTH,
UCASE_IX_UNFOLD_LENGTH,
UCASE_IX_MAX_FULL_LENGTH=15,
UCASE_IX_TOP=16
};
/* 2-bit constants for types of cased characters */
#define UCASE_TYPE_MASK 3
enum {
UCASE_NONE,
UCASE_LOWER,
UCASE_UPPER,
UCASE_TITLE
};
#define UCASE_GET_TYPE(props) ((props)&UCASE_TYPE_MASK)
#define UCASE_EXCEPTION 0x10
/* no exception: bits 15..7 are a 9-bit signed case mapping delta */
#define UCASE_DELTA_SHIFT 7
#define UCASE_GET_DELTA(props) ((int16_t)(props)>>UCASE_DELTA_SHIFT)
/* exception: bits 15..5 are an unsigned 11-bit index into the exceptions array */
#define UCASE_EXC_SHIFT 5
/* definitions for 16-bit main exceptions word ------------------------------ */
/* first 8 bits indicate values in optional slots */
enum {
UCASE_EXC_LOWER,
UCASE_EXC_FOLD,
UCASE_EXC_UPPER,
UCASE_EXC_TITLE,
UCASE_EXC_4, /* reserved */
UCASE_EXC_5, /* reserved */
UCASE_EXC_CLOSURE,
UCASE_EXC_FULL_MAPPINGS,
UCASE_EXC_ALL_SLOTS /* one past the last slot */
};
/* each slot is 2 uint16_t instead of 1 */
#define UCASE_EXC_DOUBLE_SLOTS 0x100
struct UCaseProps {
void *mem;
const int32_t *indexes;
const uint16_t *exceptions;
const uint16_t *unfold;
UTrie2 trie;
uint8_t formatVersion[4];
};
/* ucase_props_data.h is machine-generated by gencase --csource */
#define INCLUDED_FROM_UCASE_CPP
#include "ucase_props_data.h"
/* data access primitives --------------------------------------------------- */
#define GET_EXCEPTIONS(csp, props) ((csp)->exceptions+((props)>>UCASE_EXC_SHIFT))
#define PROPS_HAS_EXCEPTION(props) ((props)&UCASE_EXCEPTION)
/* number of bits in an 8-bit integer value */
static const uint8_t flagsOffset[256]={
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
};
#define HAS_SLOT(flags, idx) ((flags)&(1<<(idx)))
#define SLOT_OFFSET(flags, idx) flagsOffset[(flags)&((1<<(idx))-1)]
/*
* Get the value of an optional-value slot where HAS_SLOT(excWord, idx).
*
* @param excWord (in) initial exceptions word
* @param idx (in) desired slot index
* @param pExc16 (in/out) const uint16_t * after excWord=*pExc16++;
* moved to the last uint16_t of the value, use +1 for beginning of next slot
* @param value (out) int32_t or uint32_t output if hasSlot, otherwise not modified
*/
#define GET_SLOT_VALUE(excWord, idx, pExc16, value) \
if(((excWord)&UCASE_EXC_DOUBLE_SLOTS)==0) { \
(pExc16)+=SLOT_OFFSET(excWord, idx); \
(value)=*pExc16; \
} else { \
(pExc16)+=2*SLOT_OFFSET(excWord, idx); \
(value)=*pExc16++; \
(value)=((value)<<16)|*pExc16; \
}
UChar32 ucase_tolower(const UCaseProps *csp, UChar32 c)
{
uint16_t props=UTRIE2_GET16(&csp->trie, c);
if(!PROPS_HAS_EXCEPTION(props)) {
if(UCASE_GET_TYPE(props)>=UCASE_UPPER) {
c+=UCASE_GET_DELTA(props);
}
} else {
const uint16_t *pe=GET_EXCEPTIONS(csp, props);
uint16_t excWord=*pe++;
if(HAS_SLOT(excWord, UCASE_EXC_LOWER)) {
GET_SLOT_VALUE(excWord, UCASE_EXC_LOWER, pe, c);
}
}
return c;
}
UChar32 ucase_toupper(const UCaseProps *csp, UChar32 c)
{
uint16_t props=UTRIE2_GET16(&csp->trie, c);
if(!PROPS_HAS_EXCEPTION(props)) {
if(UCASE_GET_TYPE(props)==UCASE_LOWER) {
c+=UCASE_GET_DELTA(props);
}
} else {
const uint16_t *pe=GET_EXCEPTIONS(csp, props);
uint16_t excWord=*pe++;
if(HAS_SLOT(excWord, UCASE_EXC_UPPER)) {
GET_SLOT_VALUE(excWord, UCASE_EXC_UPPER, pe, c);
}
}
return c;
}
UChar32 ucase_totitle(const UCaseProps *csp, UChar32 c)
{
uint16_t props=UTRIE2_GET16(&csp->trie, c);
if(!PROPS_HAS_EXCEPTION(props)) {
if(UCASE_GET_TYPE(props)==UCASE_LOWER) {
c+=UCASE_GET_DELTA(props);
}
} else {
const uint16_t *pe=GET_EXCEPTIONS(csp, props);
uint16_t excWord=*pe++;
int32_t idx;
if(HAS_SLOT(excWord, UCASE_EXC_TITLE)) {
idx=UCASE_EXC_TITLE;
} else if(HAS_SLOT(excWord, UCASE_EXC_UPPER)) {
idx=UCASE_EXC_UPPER;
} else {
return c;
}
GET_SLOT_VALUE(excWord, idx, pe, c);
}
return c;
}
ccm::Char u_tolower(
/* [in] */ ccm::Char c)
{
return (ccm::Char)ucase_tolower(&ucase_props_singleton, (UChar32)c);
}
ccm::Char u_toupper(
/* [in] */ ccm::Char c)
{
return (ccm::Char)ucase_toupper(&ucase_props_singleton, (UChar32)c);
}
ccm::Char u_totitle(
/* [in] */ ccm::Char c)
{
return (ccm::Char)ucase_totitle(&ucase_props_singleton, (UChar32)c);
}
| 30.858333
| 91
| 0.588172
|
sparkoss
|
4944dbf6a3aeeb2653e538c5147f76c291046b35
| 3,063
|
cpp
|
C++
|
Terrain/worldMap.cpp
|
marcgpuig/FrozenEngine
|
0abb8a15bc68efff8865f06523bc1d7b6f255175
|
[
"MIT"
] | 2
|
2021-02-05T17:26:26.000Z
|
2022-02-16T06:18:04.000Z
|
Terrain/worldMap.cpp
|
marcgpuig/FrozenEngine
|
0abb8a15bc68efff8865f06523bc1d7b6f255175
|
[
"MIT"
] | null | null | null |
Terrain/worldMap.cpp
|
marcgpuig/FrozenEngine
|
0abb8a15bc68efff8865f06523bc1d7b6f255175
|
[
"MIT"
] | null | null | null |
#include "worldMap.h"
#include "chunk.h"
//imgui
#include "ImGui/imgui.h"
#include "ImGui/examples/opengl3_example/imgui_impl_glfw_gl3.h"
static terraGen terrainGenerator;
worldMap::worldMap(uint8_t _width = 1, uint8_t _height = 1) : width(_width), height(_height)
{
for (int i = 0; i < width; ++i)
{
for (int j = 0; j < height; ++j)
{
map[i][j] = chunk(i, j, this);
}
}
generateHeightMapImage();
}
worldMap::~worldMap()
{
// TODO //////////////////////
}
void worldMap::render()
{
for (int i = 0; i < width; ++i)
{
for (int j = 0; j < height; ++j)
{
//map[i][j].render_sprites();
map[i][j].render();
}
}
}
void worldMap::generateHeightMapImage()
{
long long int image_size = width * height * CHUNK_RESOLUTION * CHUNK_RESOLUTION * 3;
GLubyte *data = new GLubyte[image_size];
for (int ii = 0; ii < height; ii++)
{
for (int jj = 0; jj < width; jj++)
{
for (int i = 0; i < CHUNK_RESOLUTION; ++i)
{
for (int j = 0; j < CHUNK_RESOLUTION; j++)
{
GLfloat pixelHeight = map[jj][ii].getVertexHeight(j, i) + abs(terrainGenerator.loBound);
int index = ii*(width*CHUNK_RESOLUTION*CHUNK_RESOLUTION*3) + jj*(CHUNK_RESOLUTION*3) + i*(width*CHUNK_RESOLUTION*3) + j*3;
data[index] = GLubyte(pixelHeight * 255);
data[index + 1] = GLubyte(pixelHeight * 255);
data[index + 2] = GLubyte(pixelHeight * 255);
//camera.Position;
}
}
}
}
ResourceManager::LoadTexture(data, CHUNK_RESOLUTION*width, CHUNK_RESOLUTION*height, false, "height");
delete[] data;
}
void worldMap::renderInterface()
{
ImGui::SetNextWindowSize(ImVec2(200, 100), ImGuiSetCond_FirstUseEver);
ImGui::Begin("Terrain info");
ImGui::Text("Size: %d x %d", this->width, this->height);
ImGui::Separator();
ImGui::Text("Height Map");
ImVec2 canvas_size = ImGui::GetContentRegionAvail(); // Resize canvas to what's available
//int imageSize = (canvas_size.x<canvas_size.y) ? canvas_size.x : canvas_size.y;
ImVec2 imageSize;
imageSize = ImVec2(canvas_size.x, ResourceManager::GetTexture("height").Height / (ResourceManager::GetTexture("height").Width / canvas_size.x));
ImGui::Image((void*)ResourceManager::GetTexture("height").ID,
imageSize,
ImVec2(0, 0), ImVec2(1, 1), ImColor(255, 255, 255, 255), ImColor(255, 255, 255, 0));
ImGui::Separator();
ImGui::Text("Preview:");
const int noisePlotSubd = 400;
static float arr[noisePlotSubd];
for (int i = 0; i < noisePlotSubd; ++i)
{
arr[i] = terrainGenerator.heightInPoint(50, float(i + 50));
}
canvas_size = ImGui::GetContentRegionAvail();
ImGui::PlotLines("", arr, IM_ARRAYSIZE(arr), noisePlotSubd, "", terrainGenerator.loBound, terrainGenerator.hiBound, ImVec2(canvas_size.x, 50));
ImGui::Text("Parameters:");
ImGui::SliderInt("Octaves", (int*)&terrainGenerator.octaves, 1, 10);
ImGui::SliderFloat("Persistence", (float*)&terrainGenerator.persistence, 0.0, 1.0);
ImGui::SliderFloat("Scale", (float*)&terrainGenerator.scale, 0.0, 0.1);
ImGui::Button("Generate", ImVec2(canvas_size.x, 25));
ImGui::End();
}
| 28.626168
| 146
| 0.658831
|
marcgpuig
|
494570ced3afddbcc579870806960c74d093f9da
| 1,896
|
hpp
|
C++
|
include/utils/Tracer.hpp
|
alexbatashev/pi_reproduce
|
7129111ff80b9d76e4dfad26f1f2b67ef3826e52
|
[
"Apache-2.0"
] | null | null | null |
include/utils/Tracer.hpp
|
alexbatashev/pi_reproduce
|
7129111ff80b9d76e4dfad26f1f2b67ef3826e52
|
[
"Apache-2.0"
] | 4
|
2021-07-05T12:14:37.000Z
|
2021-07-29T18:39:42.000Z
|
include/utils/Tracer.hpp
|
alexbatashev/pi_reproduce
|
7129111ff80b9d76e4dfad26f1f2b67ef3826e52
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "utils/RTTI.hpp"
#include <functional>
#include <memory>
#include <span>
#include <string_view>
namespace dpcpp_trace {
namespace detail {
class NativeTracerImpl;
}
class OpenHandler {
public:
virtual void replaceFilename(std::string_view newFile) const = 0;
virtual ~OpenHandler() = default;
};
class StatHandler {
public:
virtual void replaceFilename(std::string_view newFile) const = 0;
virtual ~StatHandler() = default;
};
class Tracer : public RTTIRoot, public RTTIChild<Tracer> {
public:
constexpr static char ID = static_cast<size_t>(RTTIHierarchy::Tracer);
using onFileOpenHandler =
std::function<void(std::string_view, const OpenHandler &)>;
using onStatHandler =
std::function<void(std::string_view, const StatHandler &)>;
virtual void launch(std::string_view executable, std::span<std::string> args,
std::span<std::string> env) = 0;
virtual void onFileOpen(onFileOpenHandler) = 0;
virtual void onStat(onStatHandler) = 0;
virtual ~Tracer() = default;
virtual void start() = 0;
virtual int wait() = 0;
virtual void kill() = 0;
virtual void interrupt() = 0;
void *cast(std::size_t type) override {
if (type == RTTIChild<Tracer>::getID()) {
return this;
}
return nullptr;
}
};
class NativeTracer : public Tracer {
public:
using onFileOpenHandler = Tracer::onFileOpenHandler;
using onStatHandler = Tracer::onStatHandler;
NativeTracer();
void launch(std::string_view executable, std::span<std::string> args,
std::span<std::string> env) final;
void fork(std::function<void()> child);
void onFileOpen(onFileOpenHandler) final;
void onStat(onStatHandler) final;
void start() final;
int wait() final;
void kill() final;
void interrupt() final;
private:
std::shared_ptr<detail::NativeTracerImpl> mImpl;
};
} // namespace dpcpp_trace
| 24
| 79
| 0.698312
|
alexbatashev
|
49486d9cbcada57137cc827b5757b6a799b1d357
| 1,557
|
cc
|
C++
|
elements/local.bak/forceip.cc
|
MacWR/Click-changed-for-ParaGraph
|
18285e5da578fbb7285d10380836146e738dee6e
|
[
"Apache-2.0"
] | 129
|
2015-10-08T14:38:35.000Z
|
2022-03-06T14:54:44.000Z
|
elements/local.bak/forceip.cc
|
MacWR/Click-changed-for-ParaGraph
|
18285e5da578fbb7285d10380836146e738dee6e
|
[
"Apache-2.0"
] | 241
|
2016-02-17T16:17:58.000Z
|
2022-03-15T09:08:33.000Z
|
elements/local.bak/forceip.cc
|
MacWR/Click-changed-for-ParaGraph
|
18285e5da578fbb7285d10380836146e738dee6e
|
[
"Apache-2.0"
] | 61
|
2015-12-17T01:46:58.000Z
|
2022-02-07T22:25:19.000Z
|
/*
* ForceIP.{cc,hh} -- element encapsulates packet in IP header
* Robert Morris
*
* Copyright (c) 1999-2000 Massachusetts Institute of Technology
*
* 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, subject to the conditions
* listed in the Click LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Click LICENSE file; the license in that file is
* legally binding.
*/
#include <click/config.h>
#include "forceip.hh"
#include <click/error.hh>
#include <click/glue.hh>
#include <click/standard/alignmentinfo.hh>
CLICK_DECLS
ForceIP::ForceIP()
{
_count = 0;
}
ForceIP::~ForceIP()
{
}
Packet *
ForceIP::simple_action(Packet *p_in)
{
WritablePacket *p = p_in->uniqueify();
click_ip *ip = reinterpret_cast<click_ip *>(p->data());
unsigned plen = p->length();
ip->ip_v = 4;
ip->ip_len = htons(plen);
if((_count++ & 7) != 1){
ip->ip_off = 0;
}
unsigned hlen = ip->ip_hl << 2;
if(hlen < sizeof(click_ip) || hlen > plen){
ip->ip_hl = plen >> 2;
}
ip->ip_sum = 0;
ip->ip_sum = click_in_cksum((unsigned char *)ip, ip->ip_hl << 2);
p->set_ip_header(ip, hlen);
return p;
}
CLICK_ENDDECLS
EXPORT_ELEMENT(ForceIP)
| 24.714286
| 77
| 0.69878
|
MacWR
|
494d3e3960cf5a8bf95286c814c6915abf683974
| 9,718
|
cpp
|
C++
|
NWNXLib/API/Mac/API/CExoFileInternal.cpp
|
Qowyn/unified
|
149d0b7670a9d156e64555fe0bd7715423db4c2a
|
[
"MIT"
] | null | null | null |
NWNXLib/API/Mac/API/CExoFileInternal.cpp
|
Qowyn/unified
|
149d0b7670a9d156e64555fe0bd7715423db4c2a
|
[
"MIT"
] | null | null | null |
NWNXLib/API/Mac/API/CExoFileInternal.cpp
|
Qowyn/unified
|
149d0b7670a9d156e64555fe0bd7715423db4c2a
|
[
"MIT"
] | null | null | null |
#include "CExoFileInternal.hpp"
#include "API/Functions.hpp"
#include "Platform/ASLR.hpp"
namespace NWNXLib {
namespace API {
CExoFileInternal::CExoFileInternal(const CExoString& a0, const CExoString& a1)
{
CExoFileInternal__CExoFileInternalCtor__0(this, a0, a1);
}
CExoFileInternal::CExoFileInternal(const void* a0, int32_t a1)
{
CExoFileInternal__CExoFileInternalCtor__2(this, a0, a1);
}
CExoFileInternal::CExoFileInternal(const CExoString& a0, uint16_t a1, const CExoString& a2)
{
CExoFileInternal__CExoFileInternalCtor__4(this, a0, a1, a2);
}
CExoFileInternal::~CExoFileInternal()
{
CExoFileInternal__CExoFileInternalDtor__0(this);
}
int32_t CExoFileInternal::Eof()
{
return CExoFileInternal__Eof(this);
}
int32_t CExoFileInternal::FileOpened()
{
return CExoFileInternal__FileOpened(this);
}
int32_t CExoFileInternal::Flush()
{
return CExoFileInternal__Flush(this);
}
uint32_t CExoFileInternal::GetOffset()
{
return CExoFileInternal__GetOffset(this);
}
int32_t CExoFileInternal::GetSize()
{
return CExoFileInternal__GetSize(this);
}
int32_t CExoFileInternal::IsMemoryBacked()
{
return CExoFileInternal__IsMemoryBacked(this);
}
uint32_t CExoFileInternal::Read(CExoString* a0, uint32_t a1)
{
return CExoFileInternal__Read__0(this, a0, a1);
}
uint32_t CExoFileInternal::Read(void* a0, uint32_t a1, uint32_t a2)
{
return CExoFileInternal__Read__1(this, a0, a1, a2);
}
void CExoFileInternal::ReadAsync(void* a0, uint32_t a1, uint32_t a2)
{
return CExoFileInternal__ReadAsync(this, a0, a1, a2);
}
uint32_t CExoFileInternal::ReadAsyncBytesRead()
{
return CExoFileInternal__ReadAsyncBytesRead(this);
}
int32_t CExoFileInternal::ReadAsyncComplete()
{
return CExoFileInternal__ReadAsyncComplete(this);
}
int32_t CExoFileInternal::Seek(int32_t a0, int32_t a1)
{
return CExoFileInternal__Seek(this, a0, a1);
}
int32_t CExoFileInternal::SeekBeginning()
{
return CExoFileInternal__SeekBeginning(this);
}
int32_t CExoFileInternal::SeekEnd()
{
return CExoFileInternal__SeekEnd(this);
}
void CExoFileInternal::SetMemoryBuffer(const void* a0, int32_t a1)
{
return CExoFileInternal__SetMemoryBuffer(this, a0, a1);
}
uint32_t CExoFileInternal::Write(const char* a0)
{
return CExoFileInternal__Write(this, a0);
}
void CExoFileInternal__CExoFileInternalCtor__0(CExoFileInternal* thisPtr, const CExoString& a0, const CExoString& a1)
{
using FuncPtrType = void(__attribute__((cdecl)) *)(CExoFileInternal*, const CExoString&, const CExoString&);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__CExoFileInternalCtor__0);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
func(thisPtr, a0, a1);
}
void CExoFileInternal__CExoFileInternalCtor__2(CExoFileInternal* thisPtr, const void* a0, int32_t a1)
{
using FuncPtrType = void(__attribute__((cdecl)) *)(CExoFileInternal*, const void*, int32_t);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__CExoFileInternalCtor__2);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
func(thisPtr, a0, a1);
}
void CExoFileInternal__CExoFileInternalCtor__4(CExoFileInternal* thisPtr, const CExoString& a0, uint16_t a1, const CExoString& a2)
{
using FuncPtrType = void(__attribute__((cdecl)) *)(CExoFileInternal*, const CExoString&, uint16_t, const CExoString&);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__CExoFileInternalCtor__4);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
func(thisPtr, a0, a1, a2);
}
void CExoFileInternal__CExoFileInternalDtor__0(CExoFileInternal* thisPtr)
{
using FuncPtrType = void(__attribute__((cdecl)) *)(CExoFileInternal*, int);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__CExoFileInternalDtor__0);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
func(thisPtr, 2);
}
int32_t CExoFileInternal__Eof(CExoFileInternal* thisPtr)
{
using FuncPtrType = int32_t(__attribute__((cdecl)) *)(CExoFileInternal*);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__Eof);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
return func(thisPtr);
}
int32_t CExoFileInternal__FileOpened(CExoFileInternal* thisPtr)
{
using FuncPtrType = int32_t(__attribute__((cdecl)) *)(CExoFileInternal*);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__FileOpened);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
return func(thisPtr);
}
int32_t CExoFileInternal__Flush(CExoFileInternal* thisPtr)
{
using FuncPtrType = int32_t(__attribute__((cdecl)) *)(CExoFileInternal*);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__Flush);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
return func(thisPtr);
}
uint32_t CExoFileInternal__GetOffset(CExoFileInternal* thisPtr)
{
using FuncPtrType = uint32_t(__attribute__((cdecl)) *)(CExoFileInternal*);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__GetOffset);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
return func(thisPtr);
}
int32_t CExoFileInternal__GetSize(CExoFileInternal* thisPtr)
{
using FuncPtrType = int32_t(__attribute__((cdecl)) *)(CExoFileInternal*);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__GetSize);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
return func(thisPtr);
}
int32_t CExoFileInternal__IsMemoryBacked(CExoFileInternal* thisPtr)
{
using FuncPtrType = int32_t(__attribute__((cdecl)) *)(CExoFileInternal*);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__IsMemoryBacked);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
return func(thisPtr);
}
uint32_t CExoFileInternal__Read__0(CExoFileInternal* thisPtr, CExoString* a0, uint32_t a1)
{
using FuncPtrType = uint32_t(__attribute__((cdecl)) *)(CExoFileInternal*, CExoString*, uint32_t);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__Read__0);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
return func(thisPtr, a0, a1);
}
uint32_t CExoFileInternal__Read__1(CExoFileInternal* thisPtr, void* a0, uint32_t a1, uint32_t a2)
{
using FuncPtrType = uint32_t(__attribute__((cdecl)) *)(CExoFileInternal*, void*, uint32_t, uint32_t);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__Read__1);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
return func(thisPtr, a0, a1, a2);
}
void CExoFileInternal__ReadAsync(CExoFileInternal* thisPtr, void* a0, uint32_t a1, uint32_t a2)
{
using FuncPtrType = void(__attribute__((cdecl)) *)(CExoFileInternal*, void*, uint32_t, uint32_t);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__ReadAsync);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
return func(thisPtr, a0, a1, a2);
}
uint32_t CExoFileInternal__ReadAsyncBytesRead(CExoFileInternal* thisPtr)
{
using FuncPtrType = uint32_t(__attribute__((cdecl)) *)(CExoFileInternal*);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__ReadAsyncBytesRead);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
return func(thisPtr);
}
int32_t CExoFileInternal__ReadAsyncComplete(CExoFileInternal* thisPtr)
{
using FuncPtrType = int32_t(__attribute__((cdecl)) *)(CExoFileInternal*);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__ReadAsyncComplete);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
return func(thisPtr);
}
int32_t CExoFileInternal__Seek(CExoFileInternal* thisPtr, int32_t a0, int32_t a1)
{
using FuncPtrType = int32_t(__attribute__((cdecl)) *)(CExoFileInternal*, int32_t, int32_t);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__Seek);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
return func(thisPtr, a0, a1);
}
int32_t CExoFileInternal__SeekBeginning(CExoFileInternal* thisPtr)
{
using FuncPtrType = int32_t(__attribute__((cdecl)) *)(CExoFileInternal*);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__SeekBeginning);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
return func(thisPtr);
}
int32_t CExoFileInternal__SeekEnd(CExoFileInternal* thisPtr)
{
using FuncPtrType = int32_t(__attribute__((cdecl)) *)(CExoFileInternal*);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__SeekEnd);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
return func(thisPtr);
}
void CExoFileInternal__SetMemoryBuffer(CExoFileInternal* thisPtr, const void* a0, int32_t a1)
{
using FuncPtrType = void(__attribute__((cdecl)) *)(CExoFileInternal*, const void*, int32_t);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__SetMemoryBuffer);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
return func(thisPtr, a0, a1);
}
uint32_t CExoFileInternal__Write(CExoFileInternal* thisPtr, const char* a0)
{
using FuncPtrType = uint32_t(__attribute__((cdecl)) *)(CExoFileInternal*, const char*);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CExoFileInternal__Write);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
return func(thisPtr, a0);
}
}
}
| 35.727941
| 130
| 0.777526
|
Qowyn
|
49510d17a15d28945d0ca01c4866cd1238212a12
| 534
|
cpp
|
C++
|
Code/1005.cpp
|
sunruisjtu2020/POJ_Submits
|
786161a5bc297ef7a2457951341e45ea31b6a481
|
[
"MIT"
] | 1
|
2022-03-29T11:38:18.000Z
|
2022-03-29T11:38:18.000Z
|
Code/1005.cpp
|
sunruisjtu2020/POJ_Submits
|
786161a5bc297ef7a2457951341e45ea31b6a481
|
[
"MIT"
] | null | null | null |
Code/1005.cpp
|
sunruisjtu2020/POJ_Submits
|
786161a5bc297ef7a2457951341e45ea31b6a481
|
[
"MIT"
] | null | null | null |
/*
* Problem 1005 - I Think I Need a Houseboat
* http://poj.org/problem?id=1005
* Date 3/30/2022
* Accepted
* MATH - Floating Numbers
*/
#include <cstdio>
#include <cmath>
const double pi = 3.14159265358979;
int n;
double x, y;
int main() {
scanf("%d", &n);
for(int i = 1; i <= n; ++i) {
scanf("%lf%lf", &x, &y);
double r2 = x * x + y * y;
double area = pi * r2 / 2;
int ans = ceil(area / 50);
printf("Property %d: This property will begin eroding in year %d.\n", i, ans);
}
printf("END OF OUTPUT.\n");
return 0;
}
| 18.413793
| 80
| 0.593633
|
sunruisjtu2020
|
49513be5f83ef9f2046f88279209ca47c4a095b9
| 8,006
|
cc
|
C++
|
cpp/src/external/xpdf/xpdf/xpdf/pdftotext.cc
|
Mosaic-DigammaDB/HandbookPragmatics
|
55399bb16362f90e26626704f8563fd6d7c0a1f9
|
[
"BSL-1.0"
] | 1
|
2019-04-15T08:44:13.000Z
|
2019-04-15T08:44:13.000Z
|
cpp/src/external/xpdf/xpdf/xpdf/pdftotext.cc
|
Mosaic-DigammaDB/HandbookPragmatics
|
55399bb16362f90e26626704f8563fd6d7c0a1f9
|
[
"BSL-1.0"
] | 1
|
2018-11-13T17:41:46.000Z
|
2018-11-13T20:54:38.000Z
|
cpp/src/external/xpdf/xpdf/xpdf/pdftotext.cc
|
Mosaic-DigammaDB/HandbookPragmatics
|
55399bb16362f90e26626704f8563fd6d7c0a1f9
|
[
"BSL-1.0"
] | 1
|
2018-11-13T16:43:10.000Z
|
2018-11-13T16:43:10.000Z
|
//========================================================================
//
// pdftotext.cc
//
// Copyright 1997-2013 Glyph & Cog, LLC
//
//========================================================================
#include <aconf.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#ifdef DEBUG_FP_LINUX
# include <fenv.h>
# include <fpu_control.h>
#endif
#include "gmem.h"
#include "gmempp.h"
#include "parseargs.h"
#include "GString.h"
#include "GlobalParams.h"
#include "Object.h"
#include "Stream.h"
#include "Array.h"
#include "Dict.h"
#include "XRef.h"
#include "Catalog.h"
#include "Page.h"
#include "PDFDoc.h"
#include "TextOutputDev.h"
#include "CharTypes.h"
#include "UnicodeMap.h"
#include "TextString.h"
#include "Error.h"
#include "config.h"
static int firstPage = 1;
static int lastPage = 0;
static GBool physLayout = gFalse;
static GBool simpleLayout = gFalse;
static GBool tableLayout = gFalse;
static GBool linePrinter = gFalse;
static GBool rawOrder = gFalse;
static double fixedPitch = 0;
static double fixedLineSpacing = 0;
static GBool clipText = gFalse;
static GBool discardDiag = gFalse;
static char textEncName[128] = "";
static char textEOL[16] = "";
static GBool noPageBreaks = gFalse;
static GBool insertBOM = gFalse;
static char ownerPassword[33] = "\001";
static char userPassword[33] = "\001";
static GBool quiet = gFalse;
static char cfgFileName[256] = "";
static GBool printVersion = gFalse;
static GBool printHelp = gFalse;
static ArgDesc argDesc[] = {
{"-f", argInt, &firstPage, 0,
"first page to convert"},
{"-l", argInt, &lastPage, 0,
"last page to convert"},
{"-layout", argFlag, &physLayout, 0,
"maintain original physical layout"},
{"-simple", argFlag, &simpleLayout, 0,
"simple one-column page layout"},
{"-table", argFlag, &tableLayout, 0,
"similar to -layout, but optimized for tables"},
{"-lineprinter", argFlag, &linePrinter, 0,
"use strict fixed-pitch/height layout"},
{"-raw", argFlag, &rawOrder, 0,
"keep strings in content stream order"},
{"-fixed", argFP, &fixedPitch, 0,
"assume fixed-pitch (or tabular) text"},
{"-linespacing", argFP, &fixedLineSpacing, 0,
"fixed line spacing for LinePrinter mode"},
{"-clip", argFlag, &clipText, 0,
"separate clipped text"},
{"-nodiag", argFlag, &discardDiag, 0,
"discard diagonal text"},
{"-enc", argString, textEncName, sizeof(textEncName),
"output text encoding name"},
{"-eol", argString, textEOL, sizeof(textEOL),
"output end-of-line convention (unix, dos, or mac)"},
{"-nopgbrk", argFlag, &noPageBreaks, 0,
"don't insert page breaks between pages"},
{"-bom", argFlag, &insertBOM, 0,
"insert a Unicode BOM at the start of the text file"},
{"-opw", argString, ownerPassword, sizeof(ownerPassword),
"owner password (for encrypted files)"},
{"-upw", argString, userPassword, sizeof(userPassword),
"user password (for encrypted files)"},
{"-q", argFlag, &quiet, 0,
"don't print any messages or errors"},
{"-cfg", argString, cfgFileName, sizeof(cfgFileName),
"configuration file to use in place of .xpdfrc"},
{"-v", argFlag, &printVersion, 0,
"print copyright and version info"},
{"-h", argFlag, &printHelp, 0,
"print usage information"},
{"-help", argFlag, &printHelp, 0,
"print usage information"},
{"--help", argFlag, &printHelp, 0,
"print usage information"},
{"-?", argFlag, &printHelp, 0,
"print usage information"},
{NULL}
};
int main(int argc, char *argv[]) {
PDFDoc *doc;
GString *fileName;
GString *textFileName;
GString *ownerPW, *userPW;
TextOutputControl textOutControl;
TextOutputDev *textOut;
UnicodeMap *uMap;
Object info;
GBool ok;
char *p;
int exitCode;
#ifdef DEBUG_FP_LINUX
// enable exceptions on floating point div-by-zero
feenableexcept(FE_DIVBYZERO);
// force 64-bit rounding: this avoids changes in output when minor
// code changes result in spills of x87 registers; it also avoids
// differences in output with valgrind's 64-bit floating point
// emulation (yes, this is a kludge; but it's pretty much
// unavoidable given the x87 instruction set; see gcc bug 323 for
// more info)
fpu_control_t cw;
_FPU_GETCW(cw);
cw = (cw & ~_FPU_EXTENDED) | _FPU_DOUBLE;
_FPU_SETCW(cw);
#endif
exitCode = 99;
// parse args
ok = parseArgs(argDesc, &argc, argv);
if (!ok || argc < 2 || argc > 3 || printVersion || printHelp) {
fprintf(stderr, "pdftotext version %s\n", xpdfVersion);
fprintf(stderr, "%s\n", xpdfCopyright);
if (!printVersion) {
printUsage("pdftotext", "<PDF-file> [<text-file>]", argDesc);
}
goto err0;
}
fileName = new GString(argv[1]);
// read config file
globalParams = new GlobalParams(cfgFileName);
if (textEncName[0]) {
globalParams->setTextEncoding(textEncName);
}
if (textEOL[0]) {
if (!globalParams->setTextEOL(textEOL)) {
fprintf(stderr, "Bad '-eol' value on command line\n");
}
}
if (noPageBreaks) {
globalParams->setTextPageBreaks(gFalse);
}
if (quiet) {
globalParams->setErrQuiet(quiet);
}
// get mapping to output encoding
if (!(uMap = globalParams->getTextEncoding())) {
error(errConfig, -1, "Couldn't get text encoding");
delete fileName;
goto err1;
}
// open PDF file
if (ownerPassword[0] != '\001') {
ownerPW = new GString(ownerPassword);
} else {
ownerPW = NULL;
}
if (userPassword[0] != '\001') {
userPW = new GString(userPassword);
} else {
userPW = NULL;
}
doc = new PDFDoc(fileName, ownerPW, userPW);
if (userPW) {
delete userPW;
}
if (ownerPW) {
delete ownerPW;
}
if (!doc->isOk()) {
exitCode = 1;
goto err2;
}
// check for copy permission
if (!doc->okToCopy()) {
error(errNotAllowed, -1,
"Copying of text from this document is not allowed.");
exitCode = 3;
goto err2;
}
// construct text file name
if (argc == 3) {
textFileName = new GString(argv[2]);
} else {
p = fileName->getCString() + fileName->getLength() - 4;
if (!strcmp(p, ".pdf") || !strcmp(p, ".PDF")) {
textFileName = new GString(fileName->getCString(),
fileName->getLength() - 4);
} else {
textFileName = fileName->copy();
}
textFileName->append(".txt");
}
// get page range
if (firstPage < 1) {
firstPage = 1;
}
if (lastPage < 1 || lastPage > doc->getNumPages()) {
lastPage = doc->getNumPages();
}
// write text file
if (tableLayout) {
textOutControl.mode = textOutTableLayout;
textOutControl.fixedPitch = fixedPitch;
} else if (physLayout) {
textOutControl.mode = textOutPhysLayout;
textOutControl.fixedPitch = fixedPitch;
} else if (simpleLayout) {
textOutControl.mode = textOutSimpleLayout;
} else if (linePrinter) {
textOutControl.mode = textOutLinePrinter;
textOutControl.fixedPitch = fixedPitch;
textOutControl.fixedLineSpacing = fixedLineSpacing;
} else if (rawOrder) {
textOutControl.mode = textOutRawOrder;
} else {
textOutControl.mode = textOutReadingOrder;
}
textOutControl.clipText = clipText;
textOutControl.discardDiagonalText = discardDiag;
textOutControl.insertBOM = insertBOM;
textOut = new TextOutputDev(textFileName->getCString(), &textOutControl,
gFalse);
if (textOut->isOk()) {
doc->displayPages(textOut, firstPage, lastPage, 72, 72, 0,
gFalse, gTrue, gFalse);
} else {
delete textOut;
exitCode = 2;
goto err3;
}
delete textOut;
exitCode = 0;
// clean up
err3:
delete textFileName;
err2:
delete doc;
uMap->decRefCnt();
err1:
delete globalParams;
err0:
// check for memory leaks
Object::memCheck(stderr);
gMemReport(stderr);
return exitCode;
}
| 28.390071
| 74
| 0.631526
|
Mosaic-DigammaDB
|
49514d067e943b8241e816096871f932e7508b31
| 12,102
|
cpp
|
C++
|
src/ui-win/manip/ManipAttrDragXy.cpp
|
steptosky/3DsMax-X-Obj-Exporter
|
c70f5a60056ee71aba1569f1189c38b9e01d2f0e
|
[
"BSD-3-Clause"
] | 20
|
2017-07-07T06:07:30.000Z
|
2022-03-09T12:00:57.000Z
|
src/ui-win/manip/ManipAttrDragXy.cpp
|
steptosky/3DsMax-X-Obj-Exporter
|
c70f5a60056ee71aba1569f1189c38b9e01d2f0e
|
[
"BSD-3-Clause"
] | 28
|
2017-07-07T06:08:27.000Z
|
2022-03-09T12:09:23.000Z
|
src/ui-win/manip/ManipAttrDragXy.cpp
|
steptosky/3DsMax-X-Obj-Exporter
|
c70f5a60056ee71aba1569f1189c38b9e01d2f0e
|
[
"BSD-3-Clause"
] | 7
|
2018-01-24T19:43:22.000Z
|
2020-01-06T00:05:40.000Z
|
/*
** Copyright(C) 2017, StepToSky
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
**
** 1.Redistributions of source code must retain the above copyright notice, this
** list of conditions and the following disclaimer.
** 2.Redistributions in binary form must reproduce the above copyright notice,
** this list of conditions and the following disclaimer in the documentation
** and / or other materials provided with the distribution.
** 3.Neither the name of StepToSky nor the names of its contributors
** may be used to endorse or promote products derived from this software
** without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
** Contacts: www.steptosky.com
*/
#include "ManipAttrDragXy.h"
#pragma warning(push, 0)
#include <3dsmaxport.h>
#pragma warning(pop)
#include <xpln/enums/ECursor.h>
#include "ui-win/Utils.h"
#include "resource/resource.h"
#include "common/Logger.h"
#include "resource/ResHelper.h"
#include "presenters/Datarefs.h"
namespace ui {
namespace win {
/**************************************************************************************************/
//////////////////////////////////////////* Static area *///////////////////////////////////////////
/**************************************************************************************************/
INT_PTR CALLBACK ManipAttrDragXy::panelProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
ManipAttrDragXy * theDlg;
if (msg == WM_INITDIALOG) {
theDlg = reinterpret_cast<ManipAttrDragXy*>(lParam);
DLSetWindowLongPtr(hWnd, lParam);
theDlg->initWindow(hWnd);
}
else if (msg == WM_DESTROY) {
theDlg = DLGetWindowLongPtr<ManipAttrDragXy*>(hWnd);
theDlg->destroyWindow(hWnd);
}
else {
theDlg = DLGetWindowLongPtr<ManipAttrDragXy *>(hWnd);
if (!theDlg) {
return FALSE;
}
}
//--------------------------------------
switch (msg) {
case WM_COMMAND: {
switch (LOWORD(wParam)) {
case BTN_X_DATAREF: {
MSTR str;
Utils::getText(theDlg->cEdtXDataRef, str);
str = presenters::Datarefs::selectData(str);
theDlg->cEdtXDataRef->SetText(str);
theDlg->mData.setXDataref(xobj::fromMStr(str));
theDlg->save();
break;
}
case BTN_Y_DATAREF: {
MSTR str;
Utils::getText(theDlg->cEdtYDataRef, str);
str = presenters::Datarefs::selectData(str);
theDlg->cEdtYDataRef->SetText(str);
theDlg->mData.setYDataref(xobj::fromMStr(str));
theDlg->save();
break;
}
case CMB_CURSOR: {
if (HIWORD(wParam) == CBN_SELCHANGE) {
theDlg->mData.setCursor(xobj::ECursor::fromUiString(sts::toMbString(theDlg->cCmbCursor.currSelectedText()).c_str()));
theDlg->save();
}
break;
}
default: break;
}
break;
}
case WM_CUSTEDIT_ENTER: {
switch (LOWORD(wParam)) {
case EDIT_X_DATAREF: {
theDlg->mData.setXDataref(sts::toMbString(Utils::getText(theDlg->cEdtXDataRef)));
theDlg->save();
break;
}
case EDIT_Y_DATAREF: {
theDlg->mData.setYDataref(sts::toMbString(Utils::getText(theDlg->cEdtYDataRef)));
theDlg->save();
break;
}
case EDIT_TOOLTIP: {
theDlg->mData.setToolTip(sts::toMbString(Utils::getText(theDlg->cEdtToolType)));
theDlg->save();
break;
}
default: break;
}
break;
}
case CC_SPINNER_CHANGE: {
switch (LOWORD(wParam)) {
case SPN_X: {
theDlg->mData.setX(theDlg->mSpnX->GetFVal());
theDlg->save();
break;
}
case SPN_MIN: {
theDlg->mData.setXMin(theDlg->mSpnXMin->GetFVal());
theDlg->save();
break;
}
case SPN_MAX: {
theDlg->mData.setXMax(theDlg->mSpnXMax->GetFVal());
theDlg->save();
break;
}
case SPN_Y: {
theDlg->mData.setY(theDlg->mSpnY->GetFVal());
theDlg->save();
break;
}
case SPN_MIN2: {
theDlg->mData.setYMin(theDlg->mSpnYMin->GetFVal());
theDlg->save();
break;
}
case SPN_MAX2: {
theDlg->mData.setYMax(theDlg->mSpnYMax->GetFVal());
theDlg->save();
break;
}
default: break;
}
break;
}
default: break;
}
return 0;
}
/**************************************************************************************************/
////////////////////////////////////* Constructors/Destructor */////////////////////////////////////
/**************************************************************************************************/
ManipAttrDragXy::ManipAttrDragXy(MdManip * modelData)
: mModelData(modelData) {
assert(mModelData);
}
ManipAttrDragXy::~ManipAttrDragXy() {
ManipAttrDragXy::destroy();
}
/**************************************************************************************************/
///////////////////////////////////////////* Functions *////////////////////////////////////////////
/**************************************************************************************************/
void ManipAttrDragXy::create(HWND inParent) {
assert(inParent);
mHwnd.setup(CreateDialogParam(ResHelper::hInstance,
MAKEINTRESOURCE(ROLL_MANIP_DRAGXY),
inParent, panelProc,
reinterpret_cast<LPARAM>(this)));
assert(mHwnd);
if (mHwnd) {
toWindow();
mHwnd.show(true);
}
else {
LError << WinCode(GetLastError());
}
}
void ManipAttrDragXy::destroy() {
if (mHwnd) {
BOOL res = DestroyWindow(mHwnd.hwnd());
if (!res) {
LError << WinCode(GetLastError());
}
mHwnd.release();
}
}
RECT ManipAttrDragXy::rect() const {
RECT r{0, 0, 0, 0};
if (mHwnd) {
r = mHwnd.rect();
}
return r;
}
void ManipAttrDragXy::move(const POINT & point) {
if (mHwnd) {
mHwnd.move(point);
}
}
/**************************************************************************************************/
//////////////////////////////////////////* Functions */////////////////////////////////////////////
/**************************************************************************************************/
void ManipAttrDragXy::setManip(const xobj::AttrManipBase & manip) {
if (manip.type() != mData.type()) {
LError << "Incorrect manipulator: " << manip.type().toString();
return;
}
mData = static_cast<const xobj::AttrManipDragXy &>(manip);
}
/**************************************************************************************************/
///////////////////////////////////////////* Functions *////////////////////////////////////////////
/**************************************************************************************************/
void ManipAttrDragXy::initWindow(HWND hWnd) {
mSpnX = SetupFloatSpinner(hWnd, SPN_X, SPN_X_EDIT, -10000.0f, 10000.0f, 0.0f, 0.1f);
mSpnXMin = SetupFloatSpinner(hWnd, SPN_MIN, SPN_MIN_EDIT, -10000.0f, 10000.0f, 0.0f, 0.1f);
mSpnXMax = SetupFloatSpinner(hWnd, SPN_MAX, SPN_MAX_EDIT, -10000.0f, 10000.0f, 0.0f, 0.1f);
cBtnXDataRef.setup(hWnd, BTN_X_DATAREF);
cEdtXDataRef = GetICustEdit(GetDlgItem(hWnd, EDIT_X_DATAREF));
mSpnY = SetupFloatSpinner(hWnd, SPN_Y, SPN_Y_EDIT, -10000.0f, 10000.0f, 0.0f, 0.1f);
mSpnYMin = SetupFloatSpinner(hWnd, SPN_MIN2, SPN_MIN_EDIT2, -10000.0f, 10000.0f, 0.0f, 0.1f);
mSpnYMax = SetupFloatSpinner(hWnd, SPN_MAX2, SPN_MAX_EDIT2, -10000.0f, 10000.0f, 0.0f, 0.1f);
cBtnYDataRef.setup(hWnd, BTN_Y_DATAREF);
cEdtYDataRef = GetICustEdit(GetDlgItem(hWnd, EDIT_Y_DATAREF));
cEdtToolType = GetICustEdit(GetDlgItem(hWnd, EDIT_TOOLTIP));
cCmbCursor.setup(hWnd, CMB_CURSOR);
for (auto & curr : xobj::ECursor::list()) {
cCmbCursor.addItem(sts::toString(curr.toUiString()));
}
cCmbCursor.setCurrSelected(0);
}
void ManipAttrDragXy::destroyWindow(HWND /*hWnd*/) {
ReleaseISpinner(mSpnX);
ReleaseISpinner(mSpnXMin);
ReleaseISpinner(mSpnXMax);
cBtnXDataRef.release();
ReleaseICustEdit(cEdtXDataRef);
ReleaseISpinner(mSpnY);
ReleaseISpinner(mSpnYMin);
ReleaseISpinner(mSpnYMax);
cBtnYDataRef.release();
ReleaseICustEdit(cEdtYDataRef);
ReleaseICustEdit(cEdtToolType);
cCmbCursor.release();
}
void ManipAttrDragXy::toWindow() {
mSpnX->SetValue(mData.x(), FALSE);
mSpnXMin->SetValue(mData.xMin(), FALSE);
mSpnXMax->SetValue(mData.xMax(), FALSE);
cEdtXDataRef->SetText(xobj::toMStr(mData.xDataref()));
mSpnY->SetValue(mData.y(), FALSE);
mSpnYMin->SetValue(mData.yMin(), FALSE);
mSpnYMax->SetValue(mData.yMax(), FALSE);
cEdtYDataRef->SetText(xobj::toMStr(mData.yDataref()));
cEdtToolType->SetText(xobj::toMStr(mData.toolTip()));
cCmbCursor.setCurrSelected(sts::toString(mData.cursor().toUiString()));
}
/********************************************************************************************************/
//////////////////////////////////////////////////////////////////////////////////////////////////////////
/********************************************************************************************************/
}
}
| 40.885135
| 145
| 0.44943
|
steptosky
|
49517757fa5cd6fe1f5f7099a366950e29099e73
| 28
|
cpp
|
C++
|
ReferenceDesign/SampleQTHMI/HMIFrameWork/log_interface.cpp
|
zenghuan1/HMI_SDK_LIB
|
d0d03af04abe07f5ca087cabcbb1e4f4858f266a
|
[
"BSD-3-Clause"
] | 8
|
2019-01-04T10:08:39.000Z
|
2021-12-13T16:34:08.000Z
|
ReferenceDesign/SampleQTHMI/HMIFrameWork/log_interface.cpp
|
zenghuan1/HMI_SDK_LIB
|
d0d03af04abe07f5ca087cabcbb1e4f4858f266a
|
[
"BSD-3-Clause"
] | 33
|
2017-07-27T09:51:59.000Z
|
2018-07-13T09:45:52.000Z
|
ReferenceDesign/SampleQTHMI/HMIFrameWork/log_interface.cpp
|
JH-G/HMI_SDK_LIB
|
caa4eac66d1f3b76349ef5d6ca5cf7dd69fcd760
|
[
"BSD-3-Clause"
] | 12
|
2017-07-28T02:54:53.000Z
|
2022-02-20T15:48:24.000Z
|
#include "log_interface.h"
| 9.333333
| 26
| 0.75
|
zenghuan1
|
49557dd655167dfb1ab6cdeac085aba0a8e3e5fd
| 992
|
cpp
|
C++
|
src/CaptureScreen/captureScreen.cpp
|
HalZhan/imager
|
90bd14604c87a980a1a7734f3df180571847b57e
|
[
"MIT"
] | null | null | null |
src/CaptureScreen/captureScreen.cpp
|
HalZhan/imager
|
90bd14604c87a980a1a7734f3df180571847b57e
|
[
"MIT"
] | null | null | null |
src/CaptureScreen/captureScreen.cpp
|
HalZhan/imager
|
90bd14604c87a980a1a7734f3df180571847b57e
|
[
"MIT"
] | null | null | null |
#include <node.h>
#include <iostream>
#include "CaptureScreen.h"
namespace imager {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
// string to char *
char *To_CharP(Local<Value> val) {
String::Utf8Value utf8_value(val->ToString());
std::string str = *utf8_value;
char *ch = new char[str.length() + 1];
std::strcpy(ch, str.c_str());
return ch;
}
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
char *savePath;
char defaultSavePath[] = "_capture_screen.bmp";
if (args.Length() < 1 || !args[0]->ToString()->Length()) {
// no read-path
savePath = defaultSavePath;
}
else {
savePath = To_CharP(args[0]);
}
CaptureScreen(savePath);
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "OK"));
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "captureScreen", Method);
}
NODE_MODULE(captureScreen, init)
}
| 23.619048
| 64
| 0.678427
|
HalZhan
|
4955c039b3bb3dc50f754754f259b52701fb26c7
| 3,520
|
hxx
|
C++
|
src/helperFunctions.hxx
|
mkuczyns/VTK_visualization
|
68e2fca878bfa233e2c0e69c8f82c39c9da4f046
|
[
"MIT"
] | null | null | null |
src/helperFunctions.hxx
|
mkuczyns/VTK_visualization
|
68e2fca878bfa233e2c0e69c8f82c39c9da4f046
|
[
"MIT"
] | null | null | null |
src/helperFunctions.hxx
|
mkuczyns/VTK_visualization
|
68e2fca878bfa233e2c0e69c8f82c39c9da4f046
|
[
"MIT"
] | null | null | null |
/****************************************************************************
* helperFunctions.hxx
*
* Created by: Michael Kuczynski
* Created on: 19/01/2019
* Description: Definition of additional classes and functions
* used by the main program.
****************************************************************************/
#ifndef HELPERFUNCTIONS_H
#define HELPERFUNCTIONS_H
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <vector>
#include <chrono>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkInteractorStyleImage.h>
#include <vtkRenderer.h>
#include <vtkActor.h>
#include <vtkActor2D.h>
#include <vtkImageMapper.h>
#include <vtkImageViewer2.h>
#include <vtkImageData.h>
#include <vtkImageActor.h>
#include <vtkDICOMImageReader.h>
#include <vtkNIFTIImageReader.h>
#include <vtkInteractorStyleImage.h>
#include <vtkTextProperty.h>
#include <vtkTextMapper.h>
#include <vtkImageMapper3D.h>
#include <vtkImageMapToWindowLevelColors.h>
#include <vtkLookupTable.h>
#include <vtkImageMapToColors.h>
#include <vtkSmartPointer.h>
#include <vtkObjectFactory.h>
#include <vtkImageAlgorithm.h>
#include <vtkImageGaussianSmooth.h>
#include <vtkMarchingCubes.h>
#include <vtkPolyDataMapper.h>
#include <vtkImageThreshold.h>
#include <vtkVolume.h>
#include <vtkFixedPointVolumeRayCastMapper.h>
#include <vtkVolumeProperty.h>
#include <vtkColorTransferFunction.h>
#include <vtkPiecewiseFunction.h>
#include <vtkMetaImageReader.h>
/*
* A helper class to display messages with information about current slice
* number and current window level in the rendered window.
*/
class ImageMessage
{
public:
/*
* Create a message that shows the current slice number.
*
* @param minSlice The minimum slice number
* @param maxSlice The maximum slice number
*
* @returns A string steam with the slice message
*/
static std::string sliceNumberFormat( int minSlice, int maxSlice );
/*
* Create a message that shows the current window level.
*
* @param windowLevel The current window level
*
* @returns A string steam with the window level message
*/
static std::string windowLevelFormat( int windowLevel );
/*
* Create a message that shows the current window.
*
* @param window The current window
*
* @returns A string steam with the window message
*/
static std::string windowFormat( int window );
};
/************************* Other helper functions **************************/
/*
* Global threshold variables. Values will change depending on
* the specified input tissue type to segment.
*/
extern int upperThreshold, lowerThreshold;
int clamp( int value );
struct fileType_t
{
int type;
fileType_t( int _type ) : type{ clamp( _type ) } {}
fileType_t() : type{ -1 } {}
};
/*
* Check the input arguements provided in the commandline when running the program.
*
* @param inputArguement Input arguement from commandline
*
* @returns the integer corresponding to the input type
* -1 for invalid arguement
* 0 for a DICOM directory
* 1 for a NIfTI file
*/
fileType_t checkInputs( std::string inputFile );
/***************************************************************************/
#endif // HELPERFUNCTIONS_H
| 27.936508
| 84
| 0.63125
|
mkuczyns
|
49585c3d858c9f406bbe22ce62befac55dfbb2f7
| 10,238
|
cpp
|
C++
|
src/Graph.cpp
|
RobertStivanson/CPP-Graph
|
07a0d8cb3860986c3257285ee02e184352ca5bfe
|
[
"MIT"
] | null | null | null |
src/Graph.cpp
|
RobertStivanson/CPP-Graph
|
07a0d8cb3860986c3257285ee02e184352ca5bfe
|
[
"MIT"
] | null | null | null |
src/Graph.cpp
|
RobertStivanson/CPP-Graph
|
07a0d8cb3860986c3257285ee02e184352ca5bfe
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cmath>
#include "UnionFind.h"
#include "Heap.h"
#include "Graph.h"
//Default constructor
Graph::Graph() {
Clear();
return;
}
// GetNumVertices
// Returns the number of vertices in the graph
int Graph::GetNumVertices() const {
return vertices;
}
// GetNumEdges
// Returns the number of edges in the graph
int Graph::GetNumEdges() const {
return edges;
}
// AddNode
// Add the node to the adjacency list, returns the new nodes ID
int Graph::AddNode() {
// Add the entry to the adjacency list
// and increment the number of vertices
adjList.push_back(Node(vertices++));
return (vertices - 1);
}
/*// RemoveNode
// params:
// node: This is the node we wish to remove from the graph
// Removes the node from the adjancy list, if it exists
bool Graph::RemoveNode(NodeID node) {
bool removed = false;
// If the graph contains the node
if (Contains(node)) {
// Erase this node from the adjacency list
adjList.erase(adjList.begin() + GetIndex(node));
// For every node in our adjacency list
for (int i = 0; i < adjList.size(); i++) {
// Remove any edge to the node we are removing
adjList[i].RemoveEdge(node);
}
// Decrement the number of vertices
vertices--;
// We removed the node
removed = true;
}
return removed;
}*/
// AddEdge
// params:
// startID: This is the node id of the starting node
// endID: This is the node id of the ending node
// weight: This is the weight associated with this link
// directed: This is a flag if the link is bidirectional or not
// Adds the edge between the start and end node, if directional is false
// then an edge will be added between end and start as well.
bool Graph::AddEdge(NodeID startID, NodeID endID, float weight, bool directed) {
bool added = false;
// If the graph contains the starting and ending node
if (ContainsPair(startID, endID)) {
// Add the edge from the starting node to the ending node
adjList[GetIndex(startID)].AddEdge(endID, weight);
// Increment the number of edges
edges++;
// If this link is not directed
if (!directed) {
// Add the edge from the ending node to the starting node
adjList[GetIndex(endID)].AddEdge(startID, weight);
// Increment the number of edges
edges++;
}
// We added the edge
added = true;
}
return added;
}
// RemoveEdge
// params:
// startID: This is the node id of the starting node
// endID: This is the node id of the ending node
// This removes all edges between these two node, the removal is
// not directional
bool Graph::RemoveEdge(NodeID startID, NodeID endID) {
bool removed = false;
// If the graph contains both the starting and ending node
if (ContainsPair(startID, endID)) {
// Remove the edge between the starting and ending node
if (adjList[GetIndex(startID)].RemoveEdge(endID))
// Decrement the number of edges
edges--;
// Remove the edge between the ending and starting node
if (adjList[GetIndex(endID)].RemoveEdge(startID))
// Decrement the number of edges
edges--;
// We removed the edges
removed = true;
}
return removed;
}
// GetEdges
// params:
// node: This is the node for whose neighbors we want
// Returns an EdgeList with all neighbors for that node
EdgeList Graph::GetNodeEdges(NodeID node) const {
if (node >= 0 && node < adjList.size())
return adjList[node].GetEdges();
return EdgeList();
}
// Contains
// params:
// node: This is the node we are looking for
// Returns true if the graph contains the node, false otherwise
bool Graph::Contains(NodeID node) const {
return (GetIndex(node) != -1);
}
// ContainsPair
// params:
// nodeOne: This is the first node we are looking for
// nodeTwo: This is the second node we are looking for
// Returns true if the graph contains both nodes, false otherwise
bool Graph::ContainsPair(NodeID nodeOne, NodeID nodeTwo) const {
bool containsFirst = false, containsSecond = false;
// For every node while we haven't found both nodes
for (int i = 0; (i < adjList.size()) && (!containsFirst || !containsSecond); i++) {
// If this is a node we are looking for
if (adjList[i].GetID() == nodeOne) {
containsFirst = true;
}
// If this is a node we are looking for
if (adjList[i].GetID() == nodeTwo) {
containsSecond = true;
}
}
return (containsFirst && containsSecond);
}
// GetIndex
// params:
// node: This is the node we wish to find
// Finds the given node and returns its index
int Graph::GetIndex(NodeID node) const {
int index = -1;
// For every node while we haven't found the node
for (int i = 0; (i < adjList.size()) && (index == -1); i++) {
// If this is the node we are looking for
if (adjList[i].GetID() == node) {
// Get its index
index = i;
}
}
return index;
}
// Quicksort
// params:
// edges: This is the list of edges to sort
// size: This is the size of the array in which is being sorted
// Performs the Quicksort algorithm on the list of edges
void Graph::QuickSort(EdgeList & edges, const int & low, const int & high) const {
// If the gap is greater than one
if (low < high) {
// Create a partition point
int partition = Partition(edges, low, high);
// Sort the sub arrays
QuickSort(edges, low, (partition - 1));
QuickSort(edges, (partition + 1), high);
}
return;
}
// Clear
// Resets all values used to by the graph to a default value
void Graph::Clear() {
adjList.clear();
vertices = 0;
edges = 0;
return;
}
// Partition
// params:
// edges: This is the list of edges to sort
// low: This is the lower bound index in the array to partition
// high: This is the higher bound index in the array to partition
// Takes the edges and returns a partition point used in the Quick sort algorithm
int Graph::Partition(EdgeList & edges, const int & low, const int & high) const {
Edge temp(0, 0), pivot(edges[high]);
int i = low;
// For every element in the sub array
for (int j = low; j < high; ++j) {
// If this element is less than our pivot
if (edges[j] < pivot) {
// Swap the elements
temp = edges[i];
edges[i] = edges[j];
edges[j] = temp;
++i;
}
}
// Swap the lowest elements and the last element
temp = edges[i];
edges[i] = edges[high];
edges[high] = temp;
return i;
}
// GetSortedEdges
// Gathers and sorts a list of all edges
EdgeList Graph::GetSortedEdges() const {
EdgeList e;
// For every node in the adjacency list
for (int i = 0; i < adjList.size(); i++) {
// Get the nodes edges
EdgeList tmp = adjList[i].GetEdges();
// Compile them with the other edges
e.insert(e.begin(), tmp.begin(), tmp.end());
}
// Sort the edges
QuickSort(e, 0, e.size() - 1);
return e;
}
// PrimsAlgorithm
// params:
// start: This is the starting node for the produced MSF
// Runs Prim's Algorithm on the graph and returns the produced MSF
AdjList Graph::PrimsAlgorithm(NodeID start) const {
AdjList mst;
EdgeList n;
Heap <PrimsNode> nodes;
PrimsNode temp, min, updated;
float costs[adjList.size()];
bool visited[adjList.size()];
int edgeCounter = 0;
// Clamp start inside the bounds of the graphs
if (start < 0 || start >= adjList.size())
start = 0;
// For every vertice
for (int i = 0; i < adjList.size(); i++) {
// Push back every node
mst.push_back(Node(i));
// Prepare them for prims algorithm
temp.node = adjList[i].GetID();
// If this is the starting node
if (i == start) {
// Set this node to root values
temp.cost = 0;
costs[i] = 0;
} else {
// Set the costs to infinity
temp.cost = INFINITY;
costs[i] = INFINITY;
}
// Set the nodes to not being visited
visited[i] = false;
// And the parents to themselves
temp.parent = i;
nodes.Push(temp);
}
// While we don't have V-1 edges in our MST
while (edgeCounter < adjList.size() - 1) {
// Get the node with the minimum cost and its neighbors
min = nodes.Pop();
n = adjList[min.node].GetEdges();
// If this node has not already been visited
if (!visited[min.node]) {
visited[min.node] = true;
// If this node is not the root node
if (min.node != start) {
// Add a bidirectional connection between the two points
mst[min.parent].AddEdge(min.node, min.cost);
mst[min.node].AddEdge(min.parent, min.cost);
// Increment the edge counter
edgeCounter++;
}
// For every neighbor to this node
for (int i = 0; i < n.size(); i++) {
// If this node has not been visited already and if
// the cost of the current weight plus the edge is better
if (!visited[n[i].GetID()] && (min.cost + n[i].GetWeight()) < costs[n[i].GetID()]) {
// Create a new node with the updated values
updated.node = n[i].GetID();
updated.parent = min.node;
updated.cost = min.cost + n[i].GetWeight();
// Update the cost values
costs[n[i].GetID()] = min.cost + n[i].GetWeight();
// Push the new node to the heap
nodes.Push(updated);
}
}
}
}
return mst;
}
// KruskalsAlgorithm
// Performs Kruskals Algorithm on the current state of the
// graph and returns an EdgeList that makes a MSF
AdjList Graph::KruskalsAlgorithm() const {
AdjList mst;
EdgeList e = GetSortedEdges();
// Initialize an adjancy list for the MST
for (int i = 0; i < adjList.size(); i++) {
// Push back every node
mst.push_back(Node(i));
}
// Create a UnionFind DS with the size of the amount of nodes
UnionFind ufn(adjList.size());
// For every edge in the sorted edges list
for (int i = 0; i < e.size(); i++) {
// Find the set that each point belongs to
NodeID x = ufn.Find(e[i].GetStartID()),
y = ufn.Find(e[i].GetID());
// If the points are not in the same set
if (x != y) {
// Merge the sets
ufn.Union(x, y);
// Add a bidirectional connection between the two points
mst[e[i].GetStartID()].AddEdge(e[i].GetID(), e[i].GetWeight());
mst[e[i].GetID()].AddEdge(e[i].GetStartID(), e[i].GetWeight());
}
}
return mst;
}
// Print
// Prints the adjacency list of this graph
void Graph::Print() const {
// For every node in the adjacency list
for (int i = 0; i < adjList.size(); i++) {
// Print the node
adjList[i].Print();
// Move to the next line
std::cout << std::endl;
}
return;
}
| 25.341584
| 88
| 0.659113
|
RobertStivanson
|
495a23c8602085bc502de9aeef2d96c9e6ddfc65
| 369
|
cxx
|
C++
|
@test/remove_cv_t.cxx
|
mojo-runtime/lib-std
|
35178964db5b51184f35447f33c379de9768b534
|
[
"MIT"
] | null | null | null |
@test/remove_cv_t.cxx
|
mojo-runtime/lib-std
|
35178964db5b51184f35447f33c379de9768b534
|
[
"MIT"
] | null | null | null |
@test/remove_cv_t.cxx
|
mojo-runtime/lib-std
|
35178964db5b51184f35447f33c379de9768b534
|
[
"MIT"
] | null | null | null |
#include "../is_same.hxx"
#include "../remove_cv_t.hxx"
static_assert(std::is_same<std::remove_cv_t< int>, int>(), "");
static_assert(std::is_same<std::remove_cv_t<const int>, int>(), "");
static_assert(std::is_same<std::remove_cv_t< volatile int>, int>(), "");
static_assert(std::is_same<std::remove_cv_t<const volatile int>, int>(), "");
| 46.125
| 77
| 0.639566
|
mojo-runtime
|
495ffde72df16e3872d0e947c9180005b17bdaf6
| 2,163
|
hpp
|
C++
|
TemporaryNameRenderer/camera.hpp
|
Cake42/RTN-Renderer
|
57fe8353550fd8019a92caa0b7485faea26e03f0
|
[
"MIT"
] | 1
|
2019-11-19T22:19:15.000Z
|
2019-11-19T22:19:15.000Z
|
TemporaryNameRenderer/camera.hpp
|
Cake42/RTN-Renderer
|
57fe8353550fd8019a92caa0b7485faea26e03f0
|
[
"MIT"
] | null | null | null |
TemporaryNameRenderer/camera.hpp
|
Cake42/RTN-Renderer
|
57fe8353550fd8019a92caa0b7485faea26e03f0
|
[
"MIT"
] | null | null | null |
#pragma once
#ifndef CAMERA_HPP
#define CAMERA_HPP
#include <crt/host_defines.h>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/vec3.hpp>
#include "let.hpp"
#include "ray.hpp"
#include "utility.hpp"
namespace rtn
{
struct camera
{
float const fov;
float const width;
float const height;
union
{
glm::mat4 const world_matrix;
struct
{
glm::vec4 const i;
glm::vec4 const j;
glm::vec4 const k;
glm::vec4 const p;
};
};
float const focal_length;
float const f_number;
__device__ __host__
camera(
float const fov_rad,
float const width,
float const height,
glm::mat4 const& world_matrix,
float const focal_length = 1.0f,
float const f_number = 2.0f)
: fov(fov_rad)
, width(width)
, height(height)
, world_matrix(world_matrix)
, focal_length(focal_length)
, f_number(f_number)
{
}
};
__device__ __host__
camera look_at(
camera const& c,
glm::vec3 const& position,
glm::vec3 const& target,
glm::vec3 const& up)
{
let look = glm::lookAt(position, target, up);
return
{
c.fov,
c.width,
c.height,
std::move(look),
c.focal_length,
c.f_number,
};
}
__device__ __host__
ray generate_ray(
camera const& c,
float const x,
float const y,
glm::vec2 const& sample,
glm::vec2 const& sample_dof)
{
let x_ndc = ((x + sample.x) / c.width * 2.0f - 1.0f);
let y_ndc = -((y + sample.y) / c.height * 2.0f - 1.0f);
let d = c.focal_length * glm::tan(c.fov / 2.0f);
let a = c.width / c.height;
let xc = d * x_ndc * a;
let yc = d * y_ndc;
let zc = -c.focal_length;
glm::vec4 const pc(xc, yc, zc, 1.0f);
let p_ = c.world_matrix * pc;
let r = c.focal_length / (2.0f * c.f_number);
let circle_sample = glm::vec4(
r * concentric_sample_disk(sample_dof),
0.0f,
1.0f);
let cp = c.world_matrix * circle_sample;
let d_ = glm::normalize(p_ - cp);
return { cp, d_ };
}
}
#endif
| 20.6
| 59
| 0.566805
|
Cake42
|
49669e0543f6247c09e613667acf65707876ebf1
| 997
|
cpp
|
C++
|
src/arken/digest/md5/qt.cpp
|
charonplatform/charonplatform
|
ba5f711b2f8a8da760ccb71925d21a53f3255817
|
[
"BSD-3-Clause"
] | 1
|
2018-01-26T14:54:27.000Z
|
2018-01-26T14:54:27.000Z
|
src/arken/digest/md5/qt.cpp
|
arken-dev/arken
|
ba5f711b2f8a8da760ccb71925d21a53f3255817
|
[
"BSD-3-Clause"
] | null | null | null |
src/arken/digest/md5/qt.cpp
|
arken-dev/arken
|
ba5f711b2f8a8da760ccb71925d21a53f3255817
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2016 The Arken Platform 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 <cstring>
#include <arken/base>
#include <QCryptographicHash>
using namespace arken::digest;
char * md5::hash(const char * hash)
{
return md5::hash(hash, strlen(hash));
}
char * md5::hash(const char * hash, int length)
{
QByteArray hex = QCryptographicHash::hash(QByteArray(hash, length), QCryptographicHash::Md5).toHex();
const char * data = hex.data();
char * result = new char[33];
strcpy(result, data);
result[32] = '\0';
return result;
}
char * md5::file(const char * path)
{
char * buffer;
std::ifstream file;
int length;
file.open(path);
file.seekg(0, std::ios::end);
length = file.tellg();
file.seekg(0, std::ios::beg);
buffer = new char[length];
file.read(buffer, length);
file.close();
char * result = hash(buffer, length);
delete[] buffer;
return result;
}
| 22.659091
| 103
| 0.674022
|
charonplatform
|
4969dcb431befa1db3e933750f5a1332cc803126
| 24,584
|
cp
|
C++
|
Win32/Sources/Formatting/CDisplayFormatter.cp
|
mulberry-mail/mulberry4-client
|
cdaae15c51dd759110b4fbdb2063d0e3d5202103
|
[
"ECL-2.0",
"Apache-2.0"
] | 12
|
2015-04-21T16:10:43.000Z
|
2021-11-05T13:41:46.000Z
|
Win32/Sources/Formatting/CDisplayFormatter.cp
|
mulberry-mail/mulberry4-client
|
cdaae15c51dd759110b4fbdb2063d0e3d5202103
|
[
"ECL-2.0",
"Apache-2.0"
] | 2
|
2015-11-02T13:32:11.000Z
|
2019-07-10T21:11:21.000Z
|
Win32/Sources/Formatting/CDisplayFormatter.cp
|
mulberry-mail/mulberry4-client
|
cdaae15c51dd759110b4fbdb2063d0e3d5202103
|
[
"ECL-2.0",
"Apache-2.0"
] | 6
|
2015-01-12T08:49:12.000Z
|
2021-03-27T09:11:10.000Z
|
/*
Copyright (c) 2007-2009 Cyrus Daboo. 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.
*/
// CDisplayFormatter.cp : implementation file
//
#include "CDisplayFormatter.h"
#include "CClickList.h"
#include "CFormatList.h"
#include "CFormattedTextDisplay.h"
#include "CLetterTextEditView.h"
#include "CLetterWindow.h"
#include "CParserPlain.h"
#include "CParserEnriched.h"
#include "CParserHTML.h"
#include "CPreferences.h"
#include "CStringUtils.h"
/////////////////////////////////////////////////////////////////////////////
// CDisplayFormatter
CDisplayFormatter::CDisplayFormatter(CFormattedTextDisplay* disp)
{
mList = NULL;
mOverrideList = NULL;
mClickList = NULL;
mAnchorMap = NULL;
mMessageText = disp;
mLetterText = NULL;
mView = eViewFormatted;
mFontScale = 0;
ResetColors();
}
CDisplayFormatter::CDisplayFormatter(CLetterTextEditView* disp)
{
mList = NULL;
mOverrideList = NULL;
mClickList = NULL;
mAnchorMap = NULL;
mLetterText = disp;
mMessageText = NULL;
mView = eViewFormatted;
mFontScale = 0;
ResetColors();
}
CDisplayFormatter::~CDisplayFormatter()
{
delete mList;
mList = NULL;
delete mClickList;
mClickList = NULL;
delete mAnchorMap;
mAnchorMap = NULL;
delete mOverrideList;
mOverrideList = NULL;
}
void CDisplayFormatter::Reset(bool click, long scale)
{
mText.clear();
delete mList;
mList = NULL;
if (click)
{
delete mClickList;
mClickList = NULL;
delete mAnchorMap;
mAnchorMap = NULL;
}
delete mOverrideList;
mOverrideList = NULL;
mFontScale = scale;
ResetColors();
}
void CDisplayFormatter::ResetColors()
{
// Set default colors
mBackground = ::GetSysColor(COLOR_WINDOW);
mTextColor = ::GetSysColor(COLOR_WINDOWTEXT);
}
void CDisplayFormatter::DrawHeader(SInt32 start, SInt32 stop)
{
mList->addElement(new CColorFormatElement(start, stop, CPreferences::sPrefs->mHeaderStyle.GetValue().color));
if (CPreferences::sPrefs->mHeaderStyle.GetValue().style & bold)
mList->addElement(new CFaceFormatElement(start, stop, E_BOLD));
if (CPreferences::sPrefs->mHeaderStyle.GetValue().style & underline)
mList->addElement(new CFaceFormatElement(start, stop, E_UNDERLINE));
if (CPreferences::sPrefs->mHeaderStyle.GetValue().style & italic)
mList->addElement(new CFaceFormatElement(start, stop, E_ITALIC));
}
void CDisplayFormatter::DrawHeaderDirect(SInt32 start, SInt32 stop)
{
// Formatting changes selection
CCmdEditView::StPreserveSelection _preserve(&GetTextDisplay());
ColorFormat(CPreferences::sPrefs->mHeaderStyle.GetValue().color, start, stop);
if (CPreferences::sPrefs->mHeaderStyle.GetValue().style & bold)
FaceFormat(E_BOLD, start, stop);
if (CPreferences::sPrefs->mHeaderStyle.GetValue().style & underline)
FaceFormat(E_UNDERLINE, start, stop);
if (CPreferences::sPrefs->mHeaderStyle.GetValue().style & italic)
FaceFormat(E_ITALIC, start, stop);
}
// UTF8 in
void CDisplayFormatter::ParseHeader(const char* header, EView parsing)
{
int start=0, stop=0;
if (mList == NULL)
mList = new CFormatList;
if (mClickList == NULL)
mClickList = new CClickList;
if (mAnchorMap == NULL)
mAnchorMap = new CAnchorElementMap;
// Only if header exists
if (header != NULL)
{
// Convert to UTF16 for insertion into text widget
cdustring uheader(header);
::FilterOutLFs(uheader.c_str_mod());
const unichar_t* p = uheader;
int char_offset = 0;
int start = 0;
int stop = 0;
for(; *p; p++, char_offset++)
{
switch(*p)
{
case '\r':
start = char_offset;
break;
case '\n':
// Ignore LFs with RichEdit2.0
char_offset--;
break;
case ':':
if (*(p+1) == ' ')
stop = char_offset;
else
{
start = -1;
stop = -1;
}
break;
case ' ':
case '\t':
start = -1;
stop = -1;
break;
}
if ((stop > 0) && (start >= 0))
{
stop++;
DrawHeader(start, stop);
stop = 0;
start = -1;
}
}
// Do URLs
{
std::auto_ptr<CParserPlain> PParser(new CParserPlain(uheader, mList, mClickList));
for(int j = 0; j < CPreferences::sPrefs->mRecognizeURLs.GetValue().size(); j++)
PParser->AddURL(CPreferences::sPrefs->mRecognizeURLs.GetValue()[j].c_str());
PParser->LookForURLs(mText.length());
}
// Do font
LOGFONT fontInfo = CPreferences::sPrefs->mDisplayTextFontInfo.GetValue().logfont;
cdstring fontName = fontInfo.lfFaceName;
mList->addElement(new CFontFormatElement(0, char_offset, fontName));
HDC hDC = ::GetDC(NULL);
int logpix = ::GetDeviceCaps(hDC, LOGPIXELSY);
if (logpix == 0)
logpix = 1;
::ReleaseDC(NULL, hDC);
int ht = fontInfo.lfHeight;
int pt_size = ((2*-72*ht/logpix) + 1)/2; // Round up to nearest int
mList->addElement(new CFontSizeFormatElement(0, char_offset, pt_size, false, true));
mText += uheader;
}
}
// UTF8 in
void CDisplayFormatter::InsertFormattedHeader(const char* header)
{
if ((header == NULL) || !*header)
return;
// Start at the top
GetTextDisplay().SetSelectionRange(0, 0);
// Convert to UTF16 for insertion into text widget
cdustring uheader(header);
// Format header text at the start of the message
const unichar_t* p = uheader;
while(*p)
{
bool do_format = false;
long format_start = 0;
long format_end = 0;
// Look for start of unfolded line
if (!isuspace(*p))
{
// Get header text to format
const unichar_t* field_start = p;
while(*p && (*p != ':'))
p++;
if (*p)
p++;
// Get current insert position
long dummy;
GetTextDisplay().GetSelectionRange(format_start, dummy);
// Insert the header field text
GetTextDisplay().InsertText(field_start, p - field_start);
do_format = true;
format_end = format_start + p - field_start;
}
// Insert entire line unformatted
const unichar_t* line_start = p;
while(*p && (*p != lendl1))
p++;
if (*p)
p++;
GetTextDisplay().InsertText(line_start, p - line_start);
// Format it (do this after inserting the other text to prevent the other text
// picking up the formatting style of the header)
if (do_format)
DrawHeaderDirect(format_start, format_end);
}
}
const unichar_t* CDisplayFormatter::ParseBody(const unichar_t* body, EContentSubType Etype, EView parsing, long quote, bool use_styles)
{
// Reset background/text colors
ResetColors();
if (mList == NULL)
mList = new CFormatList;
if (mClickList == NULL)
mClickList = new CClickList;
if (mAnchorMap == NULL)
mAnchorMap = new CAnchorElementMap;
if (mOverrideList == NULL)
mOverrideList = new CFormatList;
if (body)
{
switch(Etype)
{
case eContentSubHTML:
{
if (parsing != eViewRaw)
{
std::auto_ptr<CParserHTML> HParser(new CParserHTML(body, mList,
(mMessageText && (parsing == eViewFormatted)) ? mClickList : NULL,
(mMessageText && (parsing == eViewFormatted)) ? mAnchorMap : NULL, use_styles));
HParser->SetFontScale(mFontScale);
std::auto_ptr<const unichar_t> data(HParser->Parse(mText.length(), true));
if (parsing == eViewFormatted)
{
mBackground = HParser->GetBackgroundColor();
mTextColor = HParser->GetTextColor();
}
mText += data.get();
}
else
{
std::auto_ptr<CParserHTML> HParser(new CParserHTML(body, mList, mClickList, mAnchorMap));
HParser->SetFontScale(mFontScale);
HParser->RawParse(mText.length());
mText += body;
}
}
break;
case eContentSubEnriched:
{
if (parsing != eViewRaw)
{
std::auto_ptr<CParserEnriched> EParser(new CParserEnriched(body, mList, use_styles));
EParser->SetFontScale(mFontScale);
std::auto_ptr<const unichar_t> data(EParser->Parse(mText.length(), true));
EParser.reset();
if (mMessageText)
{
// URLs only if formatted display
if (parsing == eViewFormatted)
{
std::auto_ptr<CParserPlain> PParser(new CParserPlain(data.get(), mOverrideList, mClickList));
for(int j = 0; j < CPreferences::sPrefs->mRecognizeURLs.GetValue().size(); j++)
PParser->AddURL(CPreferences::sPrefs->mRecognizeURLs.GetValue()[j].c_str());
PParser->LookForURLs(mText.length());
}
}
mText += data.get();
}
else
{
std::auto_ptr<CParserEnriched> EParser(new CParserEnriched(body, mList));
EParser->SetFontScale(mFontScale);
EParser->RawParse(mText.length());
mText += body;
}
}
break;
case eContentSubPlain:
default:
if (mMessageText)
{
std::auto_ptr<CParserPlain> PParser(new CParserPlain(body, NULL, NULL));
if (parsing == eViewFormatted)
PParser->SetQuoteDepth(quote);
std::auto_ptr<const unichar_t> data(PParser->Parse(mText.length()));
PParser.reset();
// URLs only if formatted display
if (parsing == eViewFormatted)
{
PParser.reset(new CParserPlain(data.get(), mOverrideList, mClickList));
for(int j = 0; j < CPreferences::sPrefs->mRecognizeURLs.GetValue().size(); j++)
PParser->AddURL(CPreferences::sPrefs->mRecognizeURLs.GetValue()[j].c_str());
PParser->LookForURLs(mText.length());
}
mText += data.get();
}
else
mText += body;
break;
}
}
else
{
mText += body;
}
return mText.c_str();
}
void CDisplayFormatter::InsertFormatted(EView parse)
{
mView = parse;
{
// Prvent drawing while this is added
StStopRedraw redraw(mMessageText ? (CCmdEditView*) mMessageText : (CCmdEditView*) mLetterText);
// Always set background color
GetRichEditCtrl().SetBackgroundColor(FALSE, mBackground);
GetTextDisplay().SetSelectionRange(0, -1);
GetTextDisplay().InsertText(mText);
if (mView == eViewFormatted)
{
// Change default text color if not default
if (mTextColor != ::GetSysColor(COLOR_WINDOWTEXT))
ColorFormat(mTextColor);
if (mList)
mList->draw(this);
// Only quote in incoming messages
if (mMessageText && !mText.empty())
DoQuotation();
// Do override list (URLs) after everything else
if (mOverrideList)
mOverrideList->draw(this);
}
else if (mView == eViewRaw)
{
if (mList)
mList->draw(this);
}
Reset(false);
}
GetRichEditCtrl().Invalidate();
}
void CDisplayFormatter::InsertFormattedText(const unichar_t* body, EContentSubType subtype, bool quote, bool forward)
{
{
// Prvent drawing while this is added
StStopRedraw redraw(mMessageText ? (CCmdEditView*) mMessageText : (CCmdEditView*) mLetterText);
// This is always quoted text - we do not spell check it
CTextDisplay::StPauseSpelling _spelling(&GetTextDisplay());
if (subtype == eContentSubPlain)
{
// Just insert text as-is
GetTextDisplay().InsertText(body);
}
else
{
// Create styler list
std::auto_ptr<CFormatList> flist(new CFormatList);
std::auto_ptr<const unichar_t> data;
// Get pos of insert cursor
long selStart;
long selEnd;
GetTextDisplay().GetSelectionRange(selStart, selEnd);
// Parse the text to get raw text and styles
if (subtype == eContentSubHTML)
{
std::auto_ptr<CParserHTML> HParser(new CParserHTML(body, flist.get(), NULL, NULL, true));
data.reset(HParser->Parse(selStart, true, quote, forward));
}
else if (subtype == eContentSubEnriched)
{
std::auto_ptr<CParserEnriched> EParser(new CParserEnriched(body, flist.get(), true));
data.reset(EParser->Parse(selStart, true, quote, forward));
}
// Now insert the text
GetTextDisplay().InsertText(data.get());
// Draw the styles
{
CTextDisplay::StPreserveSelection _preserve(&GetTextDisplay());
flist->draw(this);
}
}
}
GetRichEditCtrl().Invalidate();
}
CTextDisplay& CDisplayFormatter::GetTextDisplay()
{
return (mMessageText ? *static_cast<CTextDisplay*>(mMessageText) : *static_cast<CTextDisplay*>(mLetterText));
}
CRichEditCtrl& CDisplayFormatter::GetRichEditCtrl()
{
if (mMessageText)
return mMessageText->GetRichEditCtrl();
else
return mLetterText->GetRichEditCtrl();
}
void CDisplayFormatter::FaceFormat(ETag tagid)
{
long start, stop;
GetTextDisplay().GetSelectionRange(start, stop);
FaceFormat(tagid, start, stop);
}
void CDisplayFormatter::FaceFormat(ETag tagid, SInt32 start, SInt32 stop)
{
GetTextDisplay().SetSelectionRange(start, stop);
CHARFORMAT2 format;
switch(tagid)
{
case E_BOLD:
format.dwMask = CFM_BOLD;
format.dwEffects = CFE_BOLD;
break;
case E_UNBOLD:
format.dwMask = CFM_BOLD;
format.dwEffects = 0;
break;
case E_UNDERLINE:
format.dwMask = CFM_UNDERLINETYPE;
format.bUnderlineType = CFU_UNDERLINE;
break;
case E_UNUNDERLINE:
format.dwMask = CFM_UNDERLINETYPE;
format.bUnderlineType = CFU_UNDERLINENONE;
break;
case E_ITALIC:
format.dwMask = CFM_ITALIC;
format.dwEffects = CFE_ITALIC;
break;
case E_UNITALIC:
format.dwMask = CFM_ITALIC;
format.dwEffects = 0;
break;
case E_PLAIN:
format.dwMask = CFM_BOLD | CFM_UNDERLINE | CFM_UNDERLINETYPE | CFM_ITALIC;
format.dwEffects = 0;
format.bUnderlineType = CFU_UNDERLINENONE;
break;
}
GetRichEditCtrl().SetSelectionCharFormat(format);
}
void CDisplayFormatter::FontFormat(const char* font)
{
long start, stop;
GetTextDisplay().GetSelectionRange(start,stop);
FontFormat(font, start, stop);
}
void CDisplayFormatter::FontFormat(const char* font, SInt32 start, SInt32 stop)
{
GetTextDisplay().SetSelectionRange(start, stop);
CHARFORMAT format;
format.dwMask = CFM_FACE | CFM_CHARSET;
format.dwEffects = 0;
format.yHeight = 0;
format.yOffset = 0;
if (CFontPopup::GetInfo(font, &(format.bCharSet), &(format.bPitchAndFamily)))
{
}
else
{
for(int i=0; i < strlen(font); i++)
{
if (font[i] == '_')
((char*) font)[i] = ' ';
}
CFontPopup::GetInfo(font, &(format.bCharSet), &(format.bPitchAndFamily));
}
::lstrcpyn(format.szFaceName, cdstring(font).win_str(), LF_FACESIZE);
format.szFaceName[LF_FACESIZE - 1] = 0;
GetRichEditCtrl().SetSelectionCharFormat(format);
}
void CDisplayFormatter::ColorFormat(RGBColor color)
{
long start, stop;
GetTextDisplay().GetSelectionRange(start,stop);
ColorFormat(color, start, stop);
}
void CDisplayFormatter::ColorFormat(RGBColor color, SInt32 start, SInt32 stop)
{
GetTextDisplay().SetSelectionRange(start, stop);
CHARFORMAT format;
format.dwEffects = 0;
format.dwMask = CFM_COLOR;
format.crTextColor = color;
GetRichEditCtrl().SetSelectionCharFormat(format);
}
void CDisplayFormatter::FontSizeFormat(short size, bool adding, bool overrideprefs)
{
long start, stop;
GetTextDisplay().GetSelectionRange(start, stop);
FontSizeFormat(size, adding, start, stop, overrideprefs);
}
void CDisplayFormatter::FontSizeFormat(short size, bool adding, SInt32 start, SInt32 stop, bool overrideprefs)
{
CHARFORMAT format;
format.dwMask = CFM_SIZE;
int ht;
int pt_size;
if (adding)
{
CHARFORMAT currentFormat;
currentFormat.dwMask = CFM_SIZE;
bool accumulate = false;
int acc_start = start;
int last_ht = 0;
for(int i = start; i < stop; i++)
{
GetTextDisplay().SetSelectionRange(i, i + 1);
GetRichEditCtrl().GetSelectionCharFormat(currentFormat);
ht = currentFormat.yHeight;
if (ht == last_ht)
accumulate = true;
else if (accumulate)
{
// Do format for previous run
GetTextDisplay().SetSelectionRange(acc_start, i);
format.yHeight = last_ht + size * 20;
GetRichEditCtrl().SetSelectionCharFormat(format);
accumulate = false;
acc_start = i;
}
last_ht = ht;
}
// Do remaining
if (accumulate)
{
// Do format for previous run
GetTextDisplay().SetSelectionRange(acc_start, stop);
format.yHeight = ht + size * 20;
GetRichEditCtrl().SetSelectionCharFormat(format);
}
}
else
{
pt_size = size;
// Limit size to preference minimum
if (!overrideprefs && (pt_size < CPreferences::sPrefs->mMinimumFont.GetValue()))
pt_size = CPreferences::sPrefs->mMinimumFont.GetValue();
format.yHeight = pt_size * 20;
GetTextDisplay().SetSelectionRange(start, stop);
GetRichEditCtrl().SetSelectionCharFormat(format);
}
}
void CDisplayFormatter::AlignmentFormat(ETag tagid)
{
long start, stop;
GetTextDisplay().GetSelectionRange(start, stop);
AlignmentFormat(tagid, start, stop);
}
void CDisplayFormatter::AlignmentFormat(ETag tagid, SInt32 start, SInt32 stop)
{
GetTextDisplay().SetSelectionRange(start, stop);
PARAFORMAT format;
format.dwMask = PFM_ALIGNMENT;
switch(tagid)
{
case E_CENTER:
format.wAlignment = PFA_CENTER;
break;
case E_FLEFT:
format.wAlignment = PFA_LEFT;
break;
case E_FRIGHT:
format.wAlignment = PFA_RIGHT;
break;
case E_FBOTH:
format.wAlignment = PFA_LEFT;
break;
}
GetRichEditCtrl().SetParaFormat(format);
}
void CDisplayFormatter::ExcerptFormat(char Excerpt, SInt32 start, SInt32 stop)
{
// Just apply quotation style from prefs
ColorFormat(CPreferences::sPrefs->mQuotationStyle.GetValue().color, start, stop);
if (CPreferences::sPrefs->mQuotationStyle.GetValue().style & bold)
FaceFormat(E_BOLD, start, stop);
if (CPreferences::sPrefs->mQuotationStyle.GetValue().style & underline)
FaceFormat(E_UNDERLINE, start, stop);
if (CPreferences::sPrefs->mQuotationStyle.GetValue().style & italic)
FaceFormat(E_ITALIC, start, stop);
}
bool CDisplayFormatter::GetLineRange(SInt32 &first, SInt32 &last, SInt32 start, SInt32 stop)
{
/*int line;
long lineStart, lineEnd;
first = last = -1;
int i = start;
while(i < stop){
line = WEOffsetToLine(i, mWEReference);
if (first < 0)
first = line;
last = line;
WEGetLineRange(line, &lineStart, &lineEnd);
i = lineEnd + 1;
}
if (first >= 0 && last >= 0){
return true;
}
else
return false;*/
return false;
}
DWORD CDisplayFormatter::GetContinuousCharSelection(CHARFORMAT ¤tFormat)
{
return GetRichEditCtrl().GetSelectionCharFormat(currentFormat);
}
DWORD CDisplayFormatter::GetContinuousParaSelection(PARAFORMAT ¤tFormat)
{
return GetRichEditCtrl().GetParaFormat(currentFormat);
}
CClickElement* CDisplayFormatter::FindCursor(int po)
{
return (mClickList ? mClickList->findCursor(po) : false);
}
bool CDisplayFormatter::LaunchURL(const cdstring& url)
{
TCHAR dir[MAX_PATH];
if (::GetCurrentDirectory(MAX_PATH, dir))
{
HINSTANCE hinst = ::ShellExecute(*::AfxGetMainWnd(), _T("open"), url.win_str(), NULL, dir, SW_SHOWNORMAL);
return (((int) hinst) > 32);
}
else
return false;
}
bool CDisplayFormatter::DoAnchor(const CClickElement* anchor)
{
// Only f anchors exist
if (mAnchorMap == NULL)
return false;
// See if matching anchor exists
CAnchorElementMap::const_iterator found = mAnchorMap->find(anchor->GetDescriptor());
if (found != mAnchorMap->end())
{
// Get target element
const CAnchorClickElement* target = &(*found).second;
// Scroll target element text position to top of screen
GetRichEditCtrl().LineScroll(GetRichEditCtrl().LineFromChar(target->getStart()) - GetRichEditCtrl().GetFirstVisibleLine(), 0);
return true;
}
return false;
}
int CDisplayFormatter::CharFromPos(CPoint pt) const
{
HWND m_hWnd;
if (mLetterText)
m_hWnd = mLetterText->m_hWnd;
else if (mMessageText)
m_hWnd = mMessageText->m_hWnd;
ASSERT(::IsWindow(m_hWnd));
int me = ::SendMessage(m_hWnd, EM_CHARFROMPOS, (WPARAM)&me, (LPARAM)&pt);
return me;
}
void CDisplayFormatter::DrawQuotation(long start, long stop, long depth)
{
FaceFormat(E_PLAIN, start, stop);
if (depth == 1)
ColorFormat(CPreferences::sPrefs->mQuotationStyle.GetValue().color, start, stop);
else
{
// Decrement to bump down index
depth--;
// Click to max size
unsigned long max_size = CPreferences::sPrefs->mQuoteColours.GetValue().size();
if (depth > max_size)
depth = max_size;
if (depth)
ColorFormat(CPreferences::sPrefs->mQuoteColours.GetValue().at(depth - 1), start, stop);
}
if (CPreferences::sPrefs->mQuotationStyle.GetValue().style & bold)
FaceFormat(E_BOLD, start, stop);
if (CPreferences::sPrefs->mQuotationStyle.GetValue().style & underline)
FaceFormat(E_UNDERLINE, start, stop);
if (CPreferences::sPrefs->mQuotationStyle.GetValue().style & italic)
FaceFormat(E_ITALIC, start, stop);
}
void CDisplayFormatter::DoQuotation()
{
// Don't bother if no quotes to recognize
if (!CPreferences::sPrefs->mRecognizeQuotes.GetValue().size())
return;
// Get number of lines and create line info array
int lines = GetRichEditCtrl().GetLineCount();
std::auto_ptr<SLineInfo> info(new SLineInfo[lines]);
// Get quotes and pre-calculate their sizes
const cdstrvect& quotes = CPreferences::sPrefs->mRecognizeQuotes.GetValue();
cdustrvect uquotes;
ulvector sizes;
for(cdstrvect::const_iterator iter = quotes.begin(); iter != quotes.end(); iter++)
{
uquotes.push_back(cdustring(*iter));
sizes.push_back(uquotes.back().length());
}
// Determine quote depth of each line
long current_depth = 0;
for(int i = 0; i < lines; i++)
{
int astart, astop;
astart = GetRichEditCtrl().LineIndex(i);
astop = GetRichEditCtrl().LineIndex(i + 1);
const unichar_t* c = &mText.c_str()[astart];
// Check whether line is 'real' ie previous line ended with CR
bool real_line = (astart && (mText.c_str()[astart - 1] == '\r')) || (!astart);
info.get()[i].start = astart;
info.get()[i].stop = astop;
// Look for quotation only if 'real' line
if (real_line)
current_depth = GetQuoteDepth(c, uquotes, sizes);
info.get()[i].depth = current_depth;
}
long start = info.get()[0].start;
long stop = info.get()[0].stop;
current_depth = 0;
for(int i = 0; i < lines; i++)
{
// Check if same depth
if ((current_depth == info.get()[i].depth) ||
// Check for orphaned lines
(!info.get()[i].depth &&
(info.get()[i+1].depth == current_depth)))
// Accumulate same depth quotation
stop = info.get()[i].stop;
else
{
// Draw current quotation
if (current_depth)
DrawQuotation(start, stop, current_depth);
// Reset to new accumulation
start = info.get()[i].start;
stop = info.get()[i].stop;
current_depth = info.get()[i].depth;
}
}
// Draw last quotation
if (current_depth)
DrawQuotation(start, stop, current_depth);
}
long CDisplayFormatter::GetQuoteDepth(const unichar_t* line, const cdustrvect& quotes, const ulvector& sizes)
{
long depth = 0;
const unichar_t* p = line;
while((*p == ' ') || (*p == '\t')) p++;
while(*p)
{
// Compare beginning of line with each quote
cdustrvect::const_iterator iter1 = quotes.begin();
ulvector::const_iterator iter2 = sizes.begin();
bool found = false;
for(; iter1 != quotes.end(); iter1++, iter2++)
{
// Must check that size is non-zero otherwise infinite loop occurs
if (*iter2 && (::unistrncmp(*iter1, p, *iter2) == 0))
{
p += *iter2;
found = true;
break;
}
}
// Done with tests if not found
if (!found)
break;
// Bump up quote depth
depth++;
// Always exit after first quote if multiples not being used
if ((depth == 1) && !CPreferences::sPrefs->mUseMultipleQuotes.GetValue())
break;
while((*p == ' ') || (*p == '\t')) p++;
}
return depth;
}
| 25.555094
| 136
| 0.659819
|
mulberry-mail
|
496f5b667b8af29e8cdd4f55bd1d616ec3a27afb
| 676
|
hpp
|
C++
|
fmo-cpp/android/env.hpp
|
sverbach/fmo-android
|
b4957ea51a4e0df6dc5315eaaf16b73c954d16a4
|
[
"MIT"
] | 37
|
2019-03-11T09:08:20.000Z
|
2022-02-26T19:01:51.000Z
|
fmo-cpp/android/env.hpp
|
sverbach/fmo-android
|
b4957ea51a4e0df6dc5315eaaf16b73c954d16a4
|
[
"MIT"
] | 83
|
2020-09-22T09:04:38.000Z
|
2021-06-10T16:15:17.000Z
|
fmo-cpp/android/env.hpp
|
sverbach/fmo-android
|
b4957ea51a4e0df6dc5315eaaf16b73c954d16a4
|
[
"MIT"
] | 10
|
2020-06-29T03:22:28.000Z
|
2021-10-01T15:28:25.000Z
|
#ifndef FMO_ANDROID_ENV_HPP
#define FMO_ANDROID_ENV_HPP
#include "java_interface.hpp"
#include <fmo/assert.hpp>
struct Env {
Env(const Env&) = delete;
Env& operator=(const Env&) = delete;
Env(JavaVM* vm, const char* threadName) : mVM(vm) {
JavaVMAttachArgs args = {JNI_VERSION_1_6, threadName, nullptr};
jint result = mVM->AttachCurrentThread(&mPtr, &args);
FMO_ASSERT(result == JNI_OK, "AttachCurrentThread failed");
}
~Env() { mVM->DetachCurrentThread(); }
JNIEnv* get() { return mPtr; }
JNIEnv& operator->() { return *mPtr; }
private:
JavaVM* mVM;
JNIEnv* mPtr = nullptr;
};
#endif //FMO_ANDROID_ENV_HPP
| 22.533333
| 71
| 0.655325
|
sverbach
|
497560e68d677ab7f2476dfe7844d75de90e23f5
| 560
|
cpp
|
C++
|
dp/linear_dp/demo/acwing896.cpp
|
Fanjunmin/algorithm-template
|
db0d37a7c9c37ee9a167918fb74b03d1d09b6fad
|
[
"MIT"
] | 1
|
2021-04-26T11:03:04.000Z
|
2021-04-26T11:03:04.000Z
|
dp/linear_dp/demo/acwing896.cpp
|
Fanjunmin/algrithm-template
|
db0d37a7c9c37ee9a167918fb74b03d1d09b6fad
|
[
"MIT"
] | null | null | null |
dp/linear_dp/demo/acwing896.cpp
|
Fanjunmin/algrithm-template
|
db0d37a7c9c37ee9a167918fb74b03d1d09b6fad
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
int a[N];
int q[N]; //q[k]表示长度为k的上升子序列中的最小的末尾元素的值
int n;
int main()
{
cin >> n;
for (int i = 0; i < n; ++i) cin >> a[i];
int k = 0;
for (int i = 0; i < n; ++i) {
int l = 0, r = k;
while (l < r) {
// 二分查找q[N]中的第一个小于a[i]的元素
int mid = l + r + 1 >> 1;
if (q[mid] < a[i]) l = mid;
else r = mid - 1;
}
q[r + 1] = a[i]; //将a[i]更新到q[r+1]
k = max(k, r + 1);
}
cout << k;
return 0;
}
| 21.538462
| 44
| 0.4
|
Fanjunmin
|
4977c74cc7e38ed67d7ef872e19d00330d07fe1a
| 3,491
|
cpp
|
C++
|
src/main/laserAblationTest.cpp
|
fpancald/EpiScale_CrossSection
|
d7d941a18edf5d9cd6419bc772e72645f30e8eef
|
[
"MIT"
] | null | null | null |
src/main/laserAblationTest.cpp
|
fpancald/EpiScale_CrossSection
|
d7d941a18edf5d9cd6419bc772e72645f30e8eef
|
[
"MIT"
] | 5
|
2018-10-11T23:43:01.000Z
|
2020-05-08T13:37:07.000Z
|
src/main/laserAblationTest.cpp
|
arame002/EpiScale_Signal
|
5215fd35ae60ad47b23fd36d94e68b4cf463f8f4
|
[
"MIT"
] | 7
|
2018-06-14T23:42:28.000Z
|
2019-12-13T22:04:07.000Z
|
//============================================================================
// Name : MeshGen.cpp
// Author : Wenzhao Sun
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include "MeshGen.h"
#include "commonData.h"
#include "CellInitHelper.h"
#include <vector>
#include "SimulationDomainGPU.h"
using namespace std;
GlobalConfigVars globalConfigVars;
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort =
true) {
if (code != cudaSuccess) {
fprintf(stderr, "GPUassert: %s %s %d\n", cudaGetErrorString(code), file,
line);
if (abort)
exit(code);
}
}
void initializeLaserTestConfig(AblationEvent &ablaEvent) {
// read configuration.
ConfigParser parser;
std::string configFileNameDefault = "./resources/disc_master.cfg";
globalConfigVars = parser.parseConfigFile(configFileNameDefault);
std::string configFileNameOverride = "./resources/laserTestOverride.cfg";
parser.updateConfigFile(globalConfigVars, configFileNameOverride);
// no input argument. Take default.
// set GPU device.
int myDeviceID = globalConfigVars.getConfigValue("GPUDeviceNumber").toInt();
gpuErrchk(cudaSetDevice(myDeviceID));
std::string ablationInputName = "./resources/laserTest_input.txt";
ablaEvent = readAblationEvent(ablationInputName);
}
int main(int argc, char* argv[]) {
/*
// initialize random seed.
srand(time(NULL));
AblationEvent ablEvent;
initializeLaserTestConfig(ablEvent);
// initialize simulation control related parameters from config file.
SimulationGlobalParameter mainPara;
mainPara.initFromConfig();
// initialize post-processing related parameters from config file.
PixelizePara pixelPara;
pixelPara.initFromConfigFile();
// initialize simulation initialization helper.
CellInitHelper initHelper;
// initialize simulation domain.
SimulationDomainGPU simuDomain;
// initialize stabilization inputs.
SimulationInitData_V2 initData = initHelper.initStabInput();
// Stabilize the initial inputs and output stablized inputs.
std::vector<CVector> stabilizedCenters = simuDomain.stablizeCellCenters(
initData);
// Generate initial inputs for simulation domain.
SimulationInitData_V2 simuData2 = initHelper.initSimuInput(
stabilizedCenters);
// initialize domain based on initial inputs.
simuDomain.initialize_v2(simuData2);
// delete old data file.
std::remove(mainPara.dataOutput.c_str());
// preparation.
uint aniFrame = 0;
// main simulation steps.
for (uint i = 0; i <= (uint) mainPara.totalTimeSteps; i++) {
cout << "step number = " << i << endl;
if (i % mainPara.aniAuxVar == 0) {
simuDomain.outputVtkFilesWithCri(mainPara.animationNameBase,
aniFrame, mainPara.aniCri);
cout << "finished output Animation" << endl;
vector<vector<int> > labelMatrix = simuDomain.outputLabelMatrix(
mainPara.dataName, aniFrame, pixelPara);
cout << "finished writing label matrix" << endl;
simuDomain.analyzeLabelMatrix(labelMatrix, aniFrame,
mainPara.imgOutput, mainPara.dataOutput);
cout << "finished output matrix analysis" << endl;
aniFrame++;
}
if (i == ablEvent.timeStep) {
simuDomain.performAblation(ablEvent);
}
// for each step, run all logics of the domain.
simuDomain.runAllLogic(mainPara.dt);
}
*/
return 0;
}
| 30.893805
| 80
| 0.708679
|
fpancald
|
4978a37fbb3d51d260094d41d175bdf941c08a8c
| 1,133
|
cpp
|
C++
|
src/exceptions.cpp
|
olivia76/cpp-sas7bdat
|
1cd22561a13ee3df6bcec0b057f928de2014b81f
|
[
"Apache-2.0"
] | 4
|
2021-12-23T13:24:03.000Z
|
2022-02-24T10:20:12.000Z
|
src/exceptions.cpp
|
olivia76/cpp-sas7bdat
|
1cd22561a13ee3df6bcec0b057f928de2014b81f
|
[
"Apache-2.0"
] | 6
|
2022-02-23T14:05:53.000Z
|
2022-03-17T13:47:46.000Z
|
src/exceptions.cpp
|
olivia76/cpp-sas7bdat
|
1cd22561a13ee3df6bcec0b057f928de2014b81f
|
[
"Apache-2.0"
] | null | null | null |
/**
* \file src/exceptions.cpp
*
* \brief Exceptions
*
* \author Olivia Quinet
*/
#include "exceptions.hpp"
#include <fmt/core.h>
#include <spdlog/spdlog.h>
#include <stdexcept>
namespace cppsas7bdat {
void raise_exception(const std::string &_msg) {
spdlog::critical(_msg);
throw std::runtime_error(_msg);
}
void EXCEPTION::cannot_allocate_memory() {
raise_exception("cannot_allocate_memory");
}
void EXCEPTION::not_a_valid_file(const char *_pcszFileName) {
raise_exception(fmt::format("not_a_valid_file: [{}]", _pcszFileName));
}
void EXCEPTION::header_too_short() { raise_exception("header_too_short"); }
void EXCEPTION::invalid_magic_number() {
raise_exception("invalid_magic_number");
}
void EXCEPTION::cannot_read_page() { raise_exception("cannot_read_page"); }
void EXCEPTION::cannot_decompress() { raise_exception("cannot_decompress"); }
void EXCEPTION::invalid_buffer_access(const size_t _offset, const size_t _n,
const size_t _size) {
raise_exception(
fmt::format("invalid_buffer_access: {}+{}>{}", _offset, _n, _size));
}
} // namespace cppsas7bdat
| 25.75
| 77
| 0.714916
|
olivia76
|
497c3ac096c6c7ca6d30406201a74908ad0d485f
| 32,980
|
hpp
|
C++
|
contrib/autoboost/autoboost/concept_check.hpp
|
CaseyCarter/autowiring
|
48e95a71308318c8ffb7ed1348e034fd9110f70c
|
[
"Apache-2.0"
] | 87
|
2015-01-18T00:43:06.000Z
|
2022-02-11T17:40:50.000Z
|
contrib/autoboost/autoboost/concept_check.hpp
|
CaseyCarter/autowiring
|
48e95a71308318c8ffb7ed1348e034fd9110f70c
|
[
"Apache-2.0"
] | 274
|
2015-01-03T04:50:49.000Z
|
2021-03-08T09:01:09.000Z
|
contrib/autoboost/autoboost/concept_check.hpp
|
CaseyCarter/autowiring
|
48e95a71308318c8ffb7ed1348e034fd9110f70c
|
[
"Apache-2.0"
] | 15
|
2015-09-30T20:58:43.000Z
|
2020-12-19T21:24:56.000Z
|
//
// (C) Copyright Jeremy Siek 2000.
// Copyright 2002 The Trustees of Indiana University.
//
// 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)
//
// Revision History:
// 05 May 2001: Workarounds for HP aCC from Thomas Matelich. (Jeremy Siek)
// 02 April 2001: Removed limits header altogether. (Jeremy Siek)
// 01 April 2001: Modified to use new <autoboost/limits.hpp> header. (JMaddock)
//
// See http://www.boost.org/libs/concept_check for documentation.
#ifndef AUTOBOOST_CONCEPT_CHECKS_HPP
# define AUTOBOOST_CONCEPT_CHECKS_HPP
# include <autoboost/concept/assert.hpp>
# include <autoboost/iterator.hpp>
# include <autoboost/type_traits/conversion_traits.hpp>
# include <utility>
# include <autoboost/type_traits/is_same.hpp>
# include <autoboost/type_traits/is_void.hpp>
# include <autoboost/mpl/assert.hpp>
# include <autoboost/mpl/bool.hpp>
# include <autoboost/detail/workaround.hpp>
# include <autoboost/detail/iterator.hpp>
# include <autoboost/concept/usage.hpp>
# include <autoboost/concept/detail/concept_def.hpp>
#if (defined _MSC_VER)
# pragma warning( push )
# pragma warning( disable : 4510 ) // default constructor could not be generated
# pragma warning( disable : 4610 ) // object 'class' can never be instantiated - user-defined constructor required
#endif
namespace autoboost
{
//
// Backward compatibility
//
template <class Model>
inline void function_requires(Model* = 0)
{
AUTOBOOST_CONCEPT_ASSERT((Model));
}
template <class T> inline void ignore_unused_variable_warning(T const&) {}
# define AUTOBOOST_CLASS_REQUIRE(type_var, ns, concept) \
AUTOBOOST_CONCEPT_ASSERT((ns::concept<type_var>))
# define AUTOBOOST_CLASS_REQUIRE2(type_var1, type_var2, ns, concept) \
AUTOBOOST_CONCEPT_ASSERT((ns::concept<type_var1,type_var2>))
# define AUTOBOOST_CLASS_REQUIRE3(tv1, tv2, tv3, ns, concept) \
AUTOBOOST_CONCEPT_ASSERT((ns::concept<tv1,tv2,tv3>))
# define AUTOBOOST_CLASS_REQUIRE4(tv1, tv2, tv3, tv4, ns, concept) \
AUTOBOOST_CONCEPT_ASSERT((ns::concept<tv1,tv2,tv3,tv4>))
//
// Begin concept definitions
//
AUTOBOOST_concept(Integer, (T))
{
AUTOBOOST_CONCEPT_USAGE(Integer)
{
x.error_type_must_be_an_integer_type();
}
private:
T x;
};
template <> struct Integer<char> {};
template <> struct Integer<signed char> {};
template <> struct Integer<unsigned char> {};
template <> struct Integer<short> {};
template <> struct Integer<unsigned short> {};
template <> struct Integer<int> {};
template <> struct Integer<unsigned int> {};
template <> struct Integer<long> {};
template <> struct Integer<unsigned long> {};
# if defined(AUTOBOOST_HAS_LONG_LONG)
template <> struct Integer< ::autoboost::long_long_type> {};
template <> struct Integer< ::autoboost::ulong_long_type> {};
# elif defined(AUTOBOOST_HAS_MS_INT64)
template <> struct Integer<__int64> {};
template <> struct Integer<unsigned __int64> {};
# endif
AUTOBOOST_concept(SignedInteger,(T)) {
AUTOBOOST_CONCEPT_USAGE(SignedInteger) {
x.error_type_must_be_a_signed_integer_type();
}
private:
T x;
};
template <> struct SignedInteger<signed char> { };
template <> struct SignedInteger<short> {};
template <> struct SignedInteger<int> {};
template <> struct SignedInteger<long> {};
# if defined(AUTOBOOST_HAS_LONG_LONG)
template <> struct SignedInteger< ::autoboost::long_long_type> {};
# elif defined(AUTOBOOST_HAS_MS_INT64)
template <> struct SignedInteger<__int64> {};
# endif
AUTOBOOST_concept(UnsignedInteger,(T)) {
AUTOBOOST_CONCEPT_USAGE(UnsignedInteger) {
x.error_type_must_be_an_unsigned_integer_type();
}
private:
T x;
};
template <> struct UnsignedInteger<unsigned char> {};
template <> struct UnsignedInteger<unsigned short> {};
template <> struct UnsignedInteger<unsigned int> {};
template <> struct UnsignedInteger<unsigned long> {};
# if defined(AUTOBOOST_HAS_LONG_LONG)
template <> struct UnsignedInteger< ::autoboost::ulong_long_type> {};
# elif defined(AUTOBOOST_HAS_MS_INT64)
template <> struct UnsignedInteger<unsigned __int64> {};
# endif
//===========================================================================
// Basic Concepts
AUTOBOOST_concept(DefaultConstructible,(TT))
{
AUTOBOOST_CONCEPT_USAGE(DefaultConstructible) {
TT a; // require default constructor
ignore_unused_variable_warning(a);
}
};
AUTOBOOST_concept(Assignable,(TT))
{
AUTOBOOST_CONCEPT_USAGE(Assignable) {
#if !defined(_ITERATOR_) // back_insert_iterator broken for VC++ STL
a = b; // require assignment operator
#endif
const_constraints(b);
}
private:
void const_constraints(const TT& x) {
#if !defined(_ITERATOR_) // back_insert_iterator broken for VC++ STL
a = x; // const required for argument to assignment
#else
ignore_unused_variable_warning(x);
#endif
}
private:
TT a;
TT b;
};
AUTOBOOST_concept(CopyConstructible,(TT))
{
AUTOBOOST_CONCEPT_USAGE(CopyConstructible) {
TT a(b); // require copy constructor
TT* ptr = &a; // require address of operator
const_constraints(a);
ignore_unused_variable_warning(ptr);
}
private:
void const_constraints(const TT& a) {
TT c(a); // require const copy constructor
const TT* ptr = &a; // require const address of operator
ignore_unused_variable_warning(c);
ignore_unused_variable_warning(ptr);
}
TT b;
};
// The SGI STL version of Assignable requires copy constructor and operator=
AUTOBOOST_concept(SGIAssignable,(TT))
{
AUTOBOOST_CONCEPT_USAGE(SGIAssignable) {
TT c(a);
#if !defined(_ITERATOR_) // back_insert_iterator broken for VC++ STL
a = b; // require assignment operator
#endif
const_constraints(b);
ignore_unused_variable_warning(c);
}
private:
void const_constraints(const TT& x) {
TT c(x);
#if !defined(_ITERATOR_) // back_insert_iterator broken for VC++ STL
a = x; // const required for argument to assignment
#endif
ignore_unused_variable_warning(c);
}
TT a;
TT b;
};
AUTOBOOST_concept(Convertible,(X)(Y))
{
AUTOBOOST_CONCEPT_USAGE(Convertible) {
Y y = x;
ignore_unused_variable_warning(y);
}
private:
X x;
};
// The C++ standard requirements for many concepts talk about return
// types that must be "convertible to bool". The problem with this
// requirement is that it leaves the door open for evil proxies that
// define things like operator|| with strange return types. Two
// possible solutions are:
// 1) require the return type to be exactly bool
// 2) stay with convertible to bool, and also
// specify stuff about all the logical operators.
// For now we just test for convertible to bool.
template <class TT>
void require_boolean_expr(const TT& t) {
bool x = t;
ignore_unused_variable_warning(x);
}
AUTOBOOST_concept(EqualityComparable,(TT))
{
AUTOBOOST_CONCEPT_USAGE(EqualityComparable) {
require_boolean_expr(a == b);
require_boolean_expr(a != b);
}
private:
TT a, b;
};
AUTOBOOST_concept(LessThanComparable,(TT))
{
AUTOBOOST_CONCEPT_USAGE(LessThanComparable) {
require_boolean_expr(a < b);
}
private:
TT a, b;
};
// This is equivalent to SGI STL's LessThanComparable.
AUTOBOOST_concept(Comparable,(TT))
{
AUTOBOOST_CONCEPT_USAGE(Comparable) {
require_boolean_expr(a < b);
require_boolean_expr(a > b);
require_boolean_expr(a <= b);
require_boolean_expr(a >= b);
}
private:
TT a, b;
};
#define AUTOBOOST_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(OP,NAME) \
AUTOBOOST_concept(NAME, (First)(Second)) \
{ \
AUTOBOOST_CONCEPT_USAGE(NAME) { (void)constraints_(); } \
private: \
bool constraints_() { return a OP b; } \
First a; \
Second b; \
}
#define AUTOBOOST_DEFINE_BINARY_OPERATOR_CONSTRAINT(OP,NAME) \
AUTOBOOST_concept(NAME, (Ret)(First)(Second)) \
{ \
AUTOBOOST_CONCEPT_USAGE(NAME) { (void)constraints_(); } \
private: \
Ret constraints_() { return a OP b; } \
First a; \
Second b; \
}
AUTOBOOST_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(==, EqualOp);
AUTOBOOST_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(!=, NotEqualOp);
AUTOBOOST_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(<, LessThanOp);
AUTOBOOST_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(<=, LessEqualOp);
AUTOBOOST_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(>, GreaterThanOp);
AUTOBOOST_DEFINE_BINARY_PREDICATE_OP_CONSTRAINT(>=, GreaterEqualOp);
AUTOBOOST_DEFINE_BINARY_OPERATOR_CONSTRAINT(+, PlusOp);
AUTOBOOST_DEFINE_BINARY_OPERATOR_CONSTRAINT(*, TimesOp);
AUTOBOOST_DEFINE_BINARY_OPERATOR_CONSTRAINT(/, DivideOp);
AUTOBOOST_DEFINE_BINARY_OPERATOR_CONSTRAINT(-, SubtractOp);
AUTOBOOST_DEFINE_BINARY_OPERATOR_CONSTRAINT(%, ModOp);
//===========================================================================
// Function Object Concepts
AUTOBOOST_concept(Generator,(Func)(Return))
{
AUTOBOOST_CONCEPT_USAGE(Generator) { test(is_void<Return>()); }
private:
void test(autoboost::mpl::false_)
{
// Do we really want a reference here?
const Return& r = f();
ignore_unused_variable_warning(r);
}
void test(autoboost::mpl::true_)
{
f();
}
Func f;
};
AUTOBOOST_concept(UnaryFunction,(Func)(Return)(Arg))
{
AUTOBOOST_CONCEPT_USAGE(UnaryFunction) { test(is_void<Return>()); }
private:
void test(autoboost::mpl::false_)
{
f(arg); // "priming the pump" this way keeps msvc6 happy (ICE)
Return r = f(arg);
ignore_unused_variable_warning(r);
}
void test(autoboost::mpl::true_)
{
f(arg);
}
#if (AUTOBOOST_WORKAROUND(__GNUC__, AUTOBOOST_TESTED_AT(4) \
&& AUTOBOOST_WORKAROUND(__GNUC__, > 3)))
// Declare a dummy construktor to make gcc happy.
// It seems the compiler can not generate a sensible constructor when this is instantiated with a refence type.
// (warning: non-static reference "const double& autoboost::UnaryFunction<YourClassHere>::arg"
// in class without a constructor [-Wuninitialized])
UnaryFunction();
#endif
Func f;
Arg arg;
};
AUTOBOOST_concept(BinaryFunction,(Func)(Return)(First)(Second))
{
AUTOBOOST_CONCEPT_USAGE(BinaryFunction) { test(is_void<Return>()); }
private:
void test(autoboost::mpl::false_)
{
f(first,second);
Return r = f(first, second); // require operator()
(void)r;
}
void test(autoboost::mpl::true_)
{
f(first,second);
}
#if (AUTOBOOST_WORKAROUND(__GNUC__, AUTOBOOST_TESTED_AT(4) \
&& AUTOBOOST_WORKAROUND(__GNUC__, > 3)))
// Declare a dummy constructor to make gcc happy.
// It seems the compiler can not generate a sensible constructor when this is instantiated with a refence type.
// (warning: non-static reference "const double& autoboost::BinaryFunction<YourClassHere>::arg"
// in class without a constructor [-Wuninitialized])
BinaryFunction();
#endif
Func f;
First first;
Second second;
};
AUTOBOOST_concept(UnaryPredicate,(Func)(Arg))
{
AUTOBOOST_CONCEPT_USAGE(UnaryPredicate) {
require_boolean_expr(f(arg)); // require operator() returning bool
}
private:
#if (AUTOBOOST_WORKAROUND(__GNUC__, AUTOBOOST_TESTED_AT(4) \
&& AUTOBOOST_WORKAROUND(__GNUC__, > 3)))
// Declare a dummy constructor to make gcc happy.
// It seems the compiler can not generate a sensible constructor when this is instantiated with a refence type.
// (warning: non-static reference "const double& autoboost::UnaryPredicate<YourClassHere>::arg"
// in class without a constructor [-Wuninitialized])
UnaryPredicate();
#endif
Func f;
Arg arg;
};
AUTOBOOST_concept(BinaryPredicate,(Func)(First)(Second))
{
AUTOBOOST_CONCEPT_USAGE(BinaryPredicate) {
require_boolean_expr(f(a, b)); // require operator() returning bool
}
private:
#if (AUTOBOOST_WORKAROUND(__GNUC__, AUTOBOOST_TESTED_AT(4) \
&& AUTOBOOST_WORKAROUND(__GNUC__, > 3)))
// Declare a dummy constructor to make gcc happy.
// It seems the compiler can not generate a sensible constructor when this is instantiated with a refence type.
// (warning: non-static reference "const double& autoboost::BinaryPredicate<YourClassHere>::arg"
// in class without a constructor [-Wuninitialized])
BinaryPredicate();
#endif
Func f;
First a;
Second b;
};
// use this when functor is used inside a container class like std::set
AUTOBOOST_concept(Const_BinaryPredicate,(Func)(First)(Second))
: BinaryPredicate<Func, First, Second>
{
AUTOBOOST_CONCEPT_USAGE(Const_BinaryPredicate) {
const_constraints(f);
}
private:
void const_constraints(const Func& fun) {
// operator() must be a const member function
require_boolean_expr(fun(a, b));
}
#if (AUTOBOOST_WORKAROUND(__GNUC__, AUTOBOOST_TESTED_AT(4) \
&& AUTOBOOST_WORKAROUND(__GNUC__, > 3)))
// Declare a dummy constructor to make gcc happy.
// It seems the compiler can not generate a sensible constructor when this is instantiated with a refence type.
// (warning: non-static reference "const double& autoboost::Const_BinaryPredicate<YourClassHere>::arg"
// in class without a constructor [-Wuninitialized])
Const_BinaryPredicate();
#endif
Func f;
First a;
Second b;
};
AUTOBOOST_concept(AdaptableGenerator,(Func)(Return))
: Generator<Func, typename Func::result_type>
{
typedef typename Func::result_type result_type;
AUTOBOOST_CONCEPT_USAGE(AdaptableGenerator)
{
AUTOBOOST_CONCEPT_ASSERT((Convertible<result_type, Return>));
}
};
AUTOBOOST_concept(AdaptableUnaryFunction,(Func)(Return)(Arg))
: UnaryFunction<Func, typename Func::result_type, typename Func::argument_type>
{
typedef typename Func::argument_type argument_type;
typedef typename Func::result_type result_type;
~AdaptableUnaryFunction()
{
AUTOBOOST_CONCEPT_ASSERT((Convertible<result_type, Return>));
AUTOBOOST_CONCEPT_ASSERT((Convertible<Arg, argument_type>));
}
};
AUTOBOOST_concept(AdaptableBinaryFunction,(Func)(Return)(First)(Second))
: BinaryFunction<
Func
, typename Func::result_type
, typename Func::first_argument_type
, typename Func::second_argument_type
>
{
typedef typename Func::first_argument_type first_argument_type;
typedef typename Func::second_argument_type second_argument_type;
typedef typename Func::result_type result_type;
~AdaptableBinaryFunction()
{
AUTOBOOST_CONCEPT_ASSERT((Convertible<result_type, Return>));
AUTOBOOST_CONCEPT_ASSERT((Convertible<First, first_argument_type>));
AUTOBOOST_CONCEPT_ASSERT((Convertible<Second, second_argument_type>));
}
};
AUTOBOOST_concept(AdaptablePredicate,(Func)(Arg))
: UnaryPredicate<Func, Arg>
, AdaptableUnaryFunction<Func, bool, Arg>
{
};
AUTOBOOST_concept(AdaptableBinaryPredicate,(Func)(First)(Second))
: BinaryPredicate<Func, First, Second>
, AdaptableBinaryFunction<Func, bool, First, Second>
{
};
//===========================================================================
// Iterator Concepts
AUTOBOOST_concept(InputIterator,(TT))
: Assignable<TT>
, EqualityComparable<TT>
{
typedef typename autoboost::detail::iterator_traits<TT>::value_type value_type;
typedef typename autoboost::detail::iterator_traits<TT>::difference_type difference_type;
typedef typename autoboost::detail::iterator_traits<TT>::reference reference;
typedef typename autoboost::detail::iterator_traits<TT>::pointer pointer;
typedef typename autoboost::detail::iterator_traits<TT>::iterator_category iterator_category;
AUTOBOOST_CONCEPT_USAGE(InputIterator)
{
AUTOBOOST_CONCEPT_ASSERT((SignedInteger<difference_type>));
AUTOBOOST_CONCEPT_ASSERT((Convertible<iterator_category, std::input_iterator_tag>));
TT j(i);
(void)*i; // require dereference operator
++j; // require preincrement operator
i++; // require postincrement operator
}
private:
TT i;
};
AUTOBOOST_concept(OutputIterator,(TT)(ValueT))
: Assignable<TT>
{
AUTOBOOST_CONCEPT_USAGE(OutputIterator) {
++i; // require preincrement operator
i++; // require postincrement operator
*i++ = t; // require postincrement and assignment
}
private:
TT i, j;
ValueT t;
};
AUTOBOOST_concept(ForwardIterator,(TT))
: InputIterator<TT>
{
AUTOBOOST_CONCEPT_USAGE(ForwardIterator)
{
AUTOBOOST_CONCEPT_ASSERT((Convertible<
AUTOBOOST_DEDUCED_TYPENAME ForwardIterator::iterator_category
, std::forward_iterator_tag
>));
typename InputIterator<TT>::reference r = *i;
ignore_unused_variable_warning(r);
}
private:
TT i;
};
AUTOBOOST_concept(Mutable_ForwardIterator,(TT))
: ForwardIterator<TT>
{
AUTOBOOST_CONCEPT_USAGE(Mutable_ForwardIterator) {
*i++ = *j; // require postincrement and assignment
}
private:
TT i, j;
};
AUTOBOOST_concept(BidirectionalIterator,(TT))
: ForwardIterator<TT>
{
AUTOBOOST_CONCEPT_USAGE(BidirectionalIterator)
{
AUTOBOOST_CONCEPT_ASSERT((Convertible<
AUTOBOOST_DEDUCED_TYPENAME BidirectionalIterator::iterator_category
, std::bidirectional_iterator_tag
>));
--i; // require predecrement operator
i--; // require postdecrement operator
}
private:
TT i;
};
AUTOBOOST_concept(Mutable_BidirectionalIterator,(TT))
: BidirectionalIterator<TT>
, Mutable_ForwardIterator<TT>
{
AUTOBOOST_CONCEPT_USAGE(Mutable_BidirectionalIterator)
{
*i-- = *j; // require postdecrement and assignment
}
private:
TT i, j;
};
AUTOBOOST_concept(RandomAccessIterator,(TT))
: BidirectionalIterator<TT>
, Comparable<TT>
{
AUTOBOOST_CONCEPT_USAGE(RandomAccessIterator)
{
AUTOBOOST_CONCEPT_ASSERT((Convertible<
AUTOBOOST_DEDUCED_TYPENAME BidirectionalIterator<TT>::iterator_category
, std::random_access_iterator_tag
>));
i += n; // require assignment addition operator
i = i + n; i = n + i; // require addition with difference type
i -= n; // require assignment subtraction operator
i = i - n; // require subtraction with difference type
n = i - j; // require difference operator
(void)i[n]; // require element access operator
}
private:
TT a, b;
TT i, j;
typename autoboost::detail::iterator_traits<TT>::difference_type n;
};
AUTOBOOST_concept(Mutable_RandomAccessIterator,(TT))
: RandomAccessIterator<TT>
, Mutable_BidirectionalIterator<TT>
{
AUTOBOOST_CONCEPT_USAGE(Mutable_RandomAccessIterator)
{
i[n] = *i; // require element access and assignment
}
private:
TT i;
typename autoboost::detail::iterator_traits<TT>::difference_type n;
};
//===========================================================================
// Container s
AUTOBOOST_concept(Container,(C))
: Assignable<C>
{
typedef typename C::value_type value_type;
typedef typename C::difference_type difference_type;
typedef typename C::size_type size_type;
typedef typename C::const_reference const_reference;
typedef typename C::const_pointer const_pointer;
typedef typename C::const_iterator const_iterator;
AUTOBOOST_CONCEPT_USAGE(Container)
{
AUTOBOOST_CONCEPT_ASSERT((InputIterator<const_iterator>));
const_constraints(c);
}
private:
void const_constraints(const C& cc) {
i = cc.begin();
i = cc.end();
n = cc.size();
n = cc.max_size();
b = cc.empty();
}
C c;
bool b;
const_iterator i;
size_type n;
};
AUTOBOOST_concept(Mutable_Container,(C))
: Container<C>
{
typedef typename C::reference reference;
typedef typename C::iterator iterator;
typedef typename C::pointer pointer;
AUTOBOOST_CONCEPT_USAGE(Mutable_Container)
{
AUTOBOOST_CONCEPT_ASSERT((
Assignable<typename Mutable_Container::value_type>));
AUTOBOOST_CONCEPT_ASSERT((InputIterator<iterator>));
i = c.begin();
i = c.end();
c.swap(c2);
}
private:
iterator i;
C c, c2;
};
AUTOBOOST_concept(ForwardContainer,(C))
: Container<C>
{
AUTOBOOST_CONCEPT_USAGE(ForwardContainer)
{
AUTOBOOST_CONCEPT_ASSERT((
ForwardIterator<
typename ForwardContainer::const_iterator
>));
}
};
AUTOBOOST_concept(Mutable_ForwardContainer,(C))
: ForwardContainer<C>
, Mutable_Container<C>
{
AUTOBOOST_CONCEPT_USAGE(Mutable_ForwardContainer)
{
AUTOBOOST_CONCEPT_ASSERT((
Mutable_ForwardIterator<
typename Mutable_ForwardContainer::iterator
>));
}
};
AUTOBOOST_concept(ReversibleContainer,(C))
: ForwardContainer<C>
{
typedef typename
C::const_reverse_iterator
const_reverse_iterator;
AUTOBOOST_CONCEPT_USAGE(ReversibleContainer)
{
AUTOBOOST_CONCEPT_ASSERT((
BidirectionalIterator<
typename ReversibleContainer::const_iterator>));
AUTOBOOST_CONCEPT_ASSERT((BidirectionalIterator<const_reverse_iterator>));
const_constraints(c);
}
private:
void const_constraints(const C& cc)
{
const_reverse_iterator i = cc.rbegin();
i = cc.rend();
}
C c;
};
AUTOBOOST_concept(Mutable_ReversibleContainer,(C))
: Mutable_ForwardContainer<C>
, ReversibleContainer<C>
{
typedef typename C::reverse_iterator reverse_iterator;
AUTOBOOST_CONCEPT_USAGE(Mutable_ReversibleContainer)
{
typedef typename Mutable_ForwardContainer<C>::iterator iterator;
AUTOBOOST_CONCEPT_ASSERT((Mutable_BidirectionalIterator<iterator>));
AUTOBOOST_CONCEPT_ASSERT((Mutable_BidirectionalIterator<reverse_iterator>));
reverse_iterator i = c.rbegin();
i = c.rend();
}
private:
C c;
};
AUTOBOOST_concept(RandomAccessContainer,(C))
: ReversibleContainer<C>
{
typedef typename C::size_type size_type;
typedef typename C::const_reference const_reference;
AUTOBOOST_CONCEPT_USAGE(RandomAccessContainer)
{
AUTOBOOST_CONCEPT_ASSERT((
RandomAccessIterator<
typename RandomAccessContainer::const_iterator
>));
const_constraints(c);
}
private:
void const_constraints(const C& cc)
{
const_reference r = cc[n];
ignore_unused_variable_warning(r);
}
C c;
size_type n;
};
AUTOBOOST_concept(Mutable_RandomAccessContainer,(C))
: Mutable_ReversibleContainer<C>
, RandomAccessContainer<C>
{
private:
typedef Mutable_RandomAccessContainer self;
public:
AUTOBOOST_CONCEPT_USAGE(Mutable_RandomAccessContainer)
{
AUTOBOOST_CONCEPT_ASSERT((Mutable_RandomAccessIterator<typename self::iterator>));
AUTOBOOST_CONCEPT_ASSERT((Mutable_RandomAccessIterator<typename self::reverse_iterator>));
typename self::reference r = c[i];
ignore_unused_variable_warning(r);
}
private:
typename Mutable_ReversibleContainer<C>::size_type i;
C c;
};
// A Sequence is inherently mutable
AUTOBOOST_concept(Sequence,(S))
: Mutable_ForwardContainer<S>
// Matt Austern's book puts DefaultConstructible here, the C++
// standard places it in Container --JGS
// ... so why aren't we following the standard? --DWA
, DefaultConstructible<S>
{
AUTOBOOST_CONCEPT_USAGE(Sequence)
{
S
c(n),
c2(n, t),
c3(first, last);
c.insert(p, t);
c.insert(p, n, t);
c.insert(p, first, last);
c.erase(p);
c.erase(p, q);
typename Sequence::reference r = c.front();
ignore_unused_variable_warning(c);
ignore_unused_variable_warning(c2);
ignore_unused_variable_warning(c3);
ignore_unused_variable_warning(r);
const_constraints(c);
}
private:
void const_constraints(const S& c) {
typename Sequence::const_reference r = c.front();
ignore_unused_variable_warning(r);
}
typename S::value_type t;
typename S::size_type n;
typename S::value_type* first, *last;
typename S::iterator p, q;
};
AUTOBOOST_concept(FrontInsertionSequence,(S))
: Sequence<S>
{
AUTOBOOST_CONCEPT_USAGE(FrontInsertionSequence)
{
c.push_front(t);
c.pop_front();
}
private:
S c;
typename S::value_type t;
};
AUTOBOOST_concept(BackInsertionSequence,(S))
: Sequence<S>
{
AUTOBOOST_CONCEPT_USAGE(BackInsertionSequence)
{
c.push_back(t);
c.pop_back();
typename BackInsertionSequence::reference r = c.back();
ignore_unused_variable_warning(r);
const_constraints(c);
}
private:
void const_constraints(const S& cc) {
typename BackInsertionSequence::const_reference
r = cc.back();
ignore_unused_variable_warning(r);
}
S c;
typename S::value_type t;
};
AUTOBOOST_concept(AssociativeContainer,(C))
: ForwardContainer<C>
, DefaultConstructible<C>
{
typedef typename C::key_type key_type;
typedef typename C::key_compare key_compare;
typedef typename C::value_compare value_compare;
typedef typename C::iterator iterator;
AUTOBOOST_CONCEPT_USAGE(AssociativeContainer)
{
i = c.find(k);
r = c.equal_range(k);
c.erase(k);
c.erase(i);
c.erase(r.first, r.second);
const_constraints(c);
AUTOBOOST_CONCEPT_ASSERT((BinaryPredicate<key_compare,key_type,key_type>));
typedef typename AssociativeContainer::value_type value_type_;
AUTOBOOST_CONCEPT_ASSERT((BinaryPredicate<value_compare,value_type_,value_type_>));
}
// Redundant with the base concept, but it helps below.
typedef typename C::const_iterator const_iterator;
private:
void const_constraints(const C& cc)
{
ci = cc.find(k);
n = cc.count(k);
cr = cc.equal_range(k);
}
C c;
iterator i;
std::pair<iterator,iterator> r;
const_iterator ci;
std::pair<const_iterator,const_iterator> cr;
typename C::key_type k;
typename C::size_type n;
};
AUTOBOOST_concept(UniqueAssociativeContainer,(C))
: AssociativeContainer<C>
{
AUTOBOOST_CONCEPT_USAGE(UniqueAssociativeContainer)
{
C c(first, last);
pos_flag = c.insert(t);
c.insert(first, last);
ignore_unused_variable_warning(c);
}
private:
std::pair<typename C::iterator, bool> pos_flag;
typename C::value_type t;
typename C::value_type* first, *last;
};
AUTOBOOST_concept(MultipleAssociativeContainer,(C))
: AssociativeContainer<C>
{
AUTOBOOST_CONCEPT_USAGE(MultipleAssociativeContainer)
{
C c(first, last);
pos = c.insert(t);
c.insert(first, last);
ignore_unused_variable_warning(c);
ignore_unused_variable_warning(pos);
}
private:
typename C::iterator pos;
typename C::value_type t;
typename C::value_type* first, *last;
};
AUTOBOOST_concept(SimpleAssociativeContainer,(C))
: AssociativeContainer<C>
{
AUTOBOOST_CONCEPT_USAGE(SimpleAssociativeContainer)
{
typedef typename C::key_type key_type;
typedef typename C::value_type value_type;
AUTOBOOST_MPL_ASSERT((autoboost::is_same<key_type,value_type>));
}
};
AUTOBOOST_concept(PairAssociativeContainer,(C))
: AssociativeContainer<C>
{
AUTOBOOST_CONCEPT_USAGE(PairAssociativeContainer)
{
typedef typename C::key_type key_type;
typedef typename C::value_type value_type;
typedef typename C::mapped_type mapped_type;
typedef std::pair<const key_type, mapped_type> required_value_type;
AUTOBOOST_MPL_ASSERT((autoboost::is_same<value_type,required_value_type>));
}
};
AUTOBOOST_concept(SortedAssociativeContainer,(C))
: AssociativeContainer<C>
, ReversibleContainer<C>
{
AUTOBOOST_CONCEPT_USAGE(SortedAssociativeContainer)
{
C
c(kc),
c2(first, last),
c3(first, last, kc);
p = c.upper_bound(k);
p = c.lower_bound(k);
r = c.equal_range(k);
c.insert(p, t);
ignore_unused_variable_warning(c);
ignore_unused_variable_warning(c2);
ignore_unused_variable_warning(c3);
const_constraints(c);
}
void const_constraints(const C& c)
{
kc = c.key_comp();
vc = c.value_comp();
cp = c.upper_bound(k);
cp = c.lower_bound(k);
cr = c.equal_range(k);
}
private:
typename C::key_compare kc;
typename C::value_compare vc;
typename C::value_type t;
typename C::key_type k;
typedef typename C::iterator iterator;
typedef typename C::const_iterator const_iterator;
typedef SortedAssociativeContainer self;
iterator p;
const_iterator cp;
std::pair<typename self::iterator,typename self::iterator> r;
std::pair<typename self::const_iterator,typename self::const_iterator> cr;
typename C::value_type* first, *last;
};
// HashedAssociativeContainer
AUTOBOOST_concept(Collection,(C))
{
AUTOBOOST_CONCEPT_USAGE(Collection)
{
autoboost::function_requires<autoboost::InputIteratorConcept<iterator> >();
autoboost::function_requires<autoboost::InputIteratorConcept<const_iterator> >();
autoboost::function_requires<autoboost::CopyConstructibleConcept<value_type> >();
const_constraints(c);
i = c.begin();
i = c.end();
c.swap(c);
}
void const_constraints(const C& cc) {
ci = cc.begin();
ci = cc.end();
n = cc.size();
b = cc.empty();
}
private:
typedef typename C::value_type value_type;
typedef typename C::iterator iterator;
typedef typename C::const_iterator const_iterator;
typedef typename C::reference reference;
typedef typename C::const_reference const_reference;
// typedef typename C::pointer pointer;
typedef typename C::difference_type difference_type;
typedef typename C::size_type size_type;
C c;
bool b;
iterator i;
const_iterator ci;
size_type n;
};
} // namespace autoboost
#if (defined _MSC_VER)
# pragma warning( pop )
#endif
# include <autoboost/concept/detail/concept_undef.hpp>
#endif // AUTOBOOST_CONCEPT_CHECKS_HPP
| 30.368324
| 117
| 0.636234
|
CaseyCarter
|
21aa5f2c627281b7fa8f2ba357f2b17908670492
| 800
|
cpp
|
C++
|
src/Texture.cpp
|
TaniyaPeters/BorealEngine
|
57937d0ec5476de0383f4cd1336b307a8a1f5434
|
[
"Apache-2.0"
] | 1
|
2021-05-25T23:59:41.000Z
|
2021-05-25T23:59:41.000Z
|
src/Texture.cpp
|
TaniyaPeters/BorealEngine
|
57937d0ec5476de0383f4cd1336b307a8a1f5434
|
[
"Apache-2.0"
] | null | null | null |
src/Texture.cpp
|
TaniyaPeters/BorealEngine
|
57937d0ec5476de0383f4cd1336b307a8a1f5434
|
[
"Apache-2.0"
] | null | null | null |
#include "Texture.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include "glad/glad.h"
namespace Boreal {
Texture::Texture(const char* texturePath) {
unsigned char* data = stbi_load(texturePath, &m_Width, &m_Height, &m_Channels, 0);
glGenTextures(1, &m_Texture);
Bind();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_Width, m_Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
UnBind();
stbi_image_free(data);
}
Texture::~Texture() {
glDeleteTextures(1, &m_Texture);
}
void Texture::Bind() {
glBindTexture(GL_TEXTURE_2D, m_Texture);
}
void Texture::UnBind() {
glBindTexture(GL_TEXTURE_2D, 0);
}
}
| 26.666667
| 97
| 0.745
|
TaniyaPeters
|
21b1a792729f667935a9f3968b1e4555bc2ccc6c
| 5,449
|
cpp
|
C++
|
src/sound/iremga20.cpp
|
gameblabla/mame_nspire
|
83dfe1606aba906bd28608f2cb8f0754492ac3da
|
[
"Unlicense"
] | 8
|
2020-05-01T15:15:16.000Z
|
2021-05-30T18:49:15.000Z
|
src/sound/iremga20.cpp
|
gameblabla/mame_nspire
|
83dfe1606aba906bd28608f2cb8f0754492ac3da
|
[
"Unlicense"
] | null | null | null |
src/sound/iremga20.cpp
|
gameblabla/mame_nspire
|
83dfe1606aba906bd28608f2cb8f0754492ac3da
|
[
"Unlicense"
] | 5
|
2020-05-07T18:38:11.000Z
|
2021-08-03T12:57:41.000Z
|
/*********************************************************
Irem GA20 PCM Sound Chip
It's not currently known whether this chip is stereo.
Revisions:
04-15-2002 Acho A. Tang
- rewrote channel mixing
- added prelimenary volume and sample rate emulation
05-30-2002 Acho A. Tang
- applied hyperbolic gain control to volume and used
a musical-note style progression in sample rate
calculation(still very inaccurate)
02-18-2004 R. Belmont
- sample rate calculation reverse-engineered.
Thanks to Fujix, Yasuhiro Ogawa, the Guru, and Tormod
for real PCB samples that made this possible.
*********************************************************/
#include <math.h>
#include "driver.h"
#include "iremga20.h"
//AT
#define MAX_VOL 256
#define MIX_CH(CH) \
if (play[CH]) \
{ \
eax = pos[CH]; \
ebx = eax; \
eax >>= 8; \
eax = *(char *)(esi + eax); \
eax *= vol[CH]; \
ebx += rate[CH]; \
pos[CH] = ebx; \
ebx = (ebx < end[CH]); \
play[CH] = ebx; \
edx += eax; \
}
//ZT
static struct IremGA20_chip_def
{
const struct IremGA20_interface *intf;
unsigned char *rom;
int rom_size;
int channel;
int mode;
int regs[0x40];
} IremGA20_chip;
static struct IremGA20_channel_def
{
unsigned long rate;
unsigned long size;
unsigned long start;
unsigned long pos;
unsigned long end;
unsigned long volume;
unsigned long pan;
unsigned long effect;
unsigned long play;
} IremGA20_channel[4];
static int sr_table[256];
void IremGA20_update( int param, INT16 **buffer, int length )
{
unsigned long rate[4], pos[4], end[4], vol[4], play[4];
int edi, ebp, esi, eax, ebx, ecx, edx;
if (!Machine->sample_rate) return;
/* precache some values */
for (ecx=0; ecx<4; ecx++)
{
rate[ecx] = IremGA20_channel[ecx].rate;
pos[ecx] = IremGA20_channel[ecx].pos;
end[ecx] = (IremGA20_channel[ecx].end - 0x20) << 8;
vol[ecx] = IremGA20_channel[ecx].volume;
play[ecx] = IremGA20_channel[ecx].play;
}
ecx = length << 1;
esi = (int)IremGA20_chip.rom;
edi = (int)buffer[0];
ebp = (int)buffer[1];
edi += ecx;
ebp += ecx;
ecx = -ecx;
for (; ecx; ecx+=2)
{
edx = 0;
MIX_CH(0);
MIX_CH(1);
MIX_CH(2);
MIX_CH(3);
edx >>= 2;
*(short *)(edi + ecx) = (short)edx;
*(short *)(ebp + ecx) = (short)edx;
}
/* update the regs now */
for (ecx=0; ecx< 4; ecx++)
{
IremGA20_channel[ecx].pos = pos[ecx];
IremGA20_channel[ecx].play = play[ecx];
}
}
//ZT
WRITE_HANDLER( IremGA20_w )
{
int channel;
//logerror("GA20: Offset %02x, data %04x\n",offset,data);
if (!Machine->sample_rate)
return;
stream_update(IremGA20_chip.channel, 0);
channel = offset >> 4;
IremGA20_chip.regs[offset] = data;
switch (offset & 0xf)
{
case 0: /* start address low */
IremGA20_channel[channel].start = ((IremGA20_channel[channel].start)&0xff000) | (data<<4);
break;
case 2: /* start address high */
IremGA20_channel[channel].start = ((IremGA20_channel[channel].start)&0x00ff0) | (data<<12);
break;
case 4: /* end address low */
IremGA20_channel[channel].end = ((IremGA20_channel[channel].end)&0xff000) | (data<<4);
break;
case 6: /* end address high */
IremGA20_channel[channel].end = ((IremGA20_channel[channel].end)&0x00ff0) | (data<<12);
break;
case 8:
IremGA20_channel[channel].rate = (sr_table[data]<<8) / Machine->sample_rate;
break;
case 0xa: //AT: gain control
IremGA20_channel[channel].volume = (data * MAX_VOL) / (data + 10);
break;
case 0xc: //AT: this is always written 2(enabling both channels?)
IremGA20_channel[channel].play = data;
IremGA20_channel[channel].pos = IremGA20_channel[channel].start << 8;
break;
}
}
READ_HANDLER( IremGA20_r )
{
int channel;
if (!Machine->sample_rate)
return 0;
stream_update(IremGA20_chip.channel, 0);
channel = offset >> 4;
switch (offset & 0xf)
{
case 0xe: // voice status. bit 0 is 1 if active. (routine around 0xccc in rtypeleo)
return IremGA20_channel[channel].play ? 1 : 0;
break;
default:
logerror("GA20: read unk. register %d, channel %d\n", offset & 0xf, channel);
break;
}
return 0;
}
static void IremGA20_reset( void )
{
int i;
for( i = 0; i < 4; i++ ) {
IremGA20_channel[i].rate = 0;
IremGA20_channel[i].size = 0;
IremGA20_channel[i].start = 0;
IremGA20_channel[i].pos = 0;
IremGA20_channel[i].end = 0;
IremGA20_channel[i].volume = 0;
IremGA20_channel[i].pan = 0;
IremGA20_channel[i].effect = 0;
IremGA20_channel[i].play = 0;
}
}
int IremGA20_sh_start(const struct MachineSound *msound)
{
const char *names[2];
char ch_names[2][40];
int i;
if (!Machine->sample_rate) return 0;
/* Initialize our chip structure */
IremGA20_chip.intf = msound->sound_interface;
IremGA20_chip.mode = 0;
IremGA20_chip.rom = memory_region(IremGA20_chip.intf->region);
IremGA20_chip.rom_size = memory_region_length(IremGA20_chip.intf->region);
/* Initialize our pitch table */
for (i = 0; i < 255; i++)
{
sr_table[i] = (IremGA20_chip.intf->clock / (256-i) / 4);
}
/* change signedness of PCM samples in advance */
for (i=0; i<IremGA20_chip.rom_size; i++)
IremGA20_chip.rom[i] -= 0x80;
IremGA20_reset();
for ( i = 0; i < 0x40; i++ )
IremGA20_chip.regs[i] = 0;
for ( i = 0; i < 2; i++ ) {
names[i] = ch_names[i];
sprintf(ch_names[i],"%s Ch %d",sound_name(msound),i);
}
IremGA20_chip.channel = stream_init_multi( 2, names,
IremGA20_chip.intf->mixing_level, Machine->sample_rate,
0, IremGA20_update );
return 0;
}
void IremGA20_sh_stop( void )
{
}
| 21.285156
| 93
| 0.653514
|
gameblabla
|
21b893a2df1e2252ee19db53c52c3fc8d8f72774
| 404
|
cpp
|
C++
|
src/archt/processor_status.cpp
|
omecamtiv/mos6502emu
|
ff4a77638c41dcc3726f8f7e78637639a66f9c6c
|
[
"MIT"
] | null | null | null |
src/archt/processor_status.cpp
|
omecamtiv/mos6502emu
|
ff4a77638c41dcc3726f8f7e78637639a66f9c6c
|
[
"MIT"
] | null | null | null |
src/archt/processor_status.cpp
|
omecamtiv/mos6502emu
|
ff4a77638c41dcc3726f8f7e78637639a66f9c6c
|
[
"MIT"
] | null | null | null |
#include "processor_status.hpp"
#include "bit_width.hpp"
ProcessorStatus::ProcessorStatus() {
StatusFlag.C = 0;
StatusFlag.Z = 0;
StatusFlag.I = 0;
StatusFlag.D = 0;
StatusFlag.B = 0;
StatusFlag.U = 0;
StatusFlag.V = 0;
StatusFlag.N = 0;
}
void ProcessorStatus::setPS(sByte byte) {
Status = (uByte)byte;
StatusFlag.U = 0;
return;
}
sByte ProcessorStatus::getPS() { return (sByte)Status; }
| 17.565217
| 56
| 0.690594
|
omecamtiv
|
21c0d2811891ad5f539f3aa6e2ace59d492239e0
| 2,355
|
cpp
|
C++
|
mel/source/parallelism/ThreadPool.cpp
|
dani-barrientos/dabal
|
72f18260e20ce0c413d7c80b43e0b6a3bfb00e5e
|
[
"MIT"
] | null | null | null |
mel/source/parallelism/ThreadPool.cpp
|
dani-barrientos/dabal
|
72f18260e20ce0c413d7c80b43e0b6a3bfb00e5e
|
[
"MIT"
] | null | null | null |
mel/source/parallelism/ThreadPool.cpp
|
dani-barrientos/dabal
|
72f18260e20ce0c413d7c80b43e0b6a3bfb00e5e
|
[
"MIT"
] | null | null | null |
#include <parallelism/ThreadPool.h>
using mel::parallelism::ThreadPool;
ThreadPool::ThreadPool( const ThreadPoolOpts& opts ):
mLastIndex(-1),
mPool(nullptr),
mOpts(opts)
{
if (opts.nThreads == THREADS_USE_ALL_CORES)
{
mNThreads = ::mel::core::getNumProcessors();
}
else if (opts.nThreads < 0)
{
int n = (int)mel::core::getNumProcessors() + opts.nThreads;
if (n < 0)
n = 0;
mNThreads = (unsigned int)n;
}else // > 0
mNThreads = (unsigned int)opts.nThreads;
if (mNThreads > 0)
{
bool applyAffinity = (opts.affinity != THREAD_AFFINITY_ALL || opts.forceAffinitty);
uint64_t pAff = applyAffinity?core::getProcessAffinity():0;
const uint64_t lastProc = 0x8000000000000000;
uint64_t coreSelector = lastProc;
mPool = new std::shared_ptr<ThreadRunnable>[mNThreads];
for (unsigned int i = 0; i < mNThreads; ++i)
{
auto th = ThreadRunnable::create(false,opts.threadOpts);
mPool[i] = th;
if (pAff != 0 && applyAffinity)
{
if (!opts.forceAffinitty)
th->setAffinity(opts.affinity);
else
{
do
{
//circular shift
if (coreSelector & 0x8000000000000000)
coreSelector = 1;
else
coreSelector = coreSelector << 1;
} while (((coreSelector&opts.affinity) == 0) || ((coreSelector&pAff) == 0));
//if (!th->setAffinity(coreSelector))
// spdlog::error("Error setting thread affinity");
}
}
th->resume(); //need to start after setting affinity
}
}
}
ThreadPool::~ThreadPool()
{
unsigned int i;
for ( i = 0; i < mNThreads; ++i )
mPool[i]->terminate();
for ( i = 0; i < mNThreads; ++i )
{
mPool[i]->join();
}
delete[]mPool;
}
std::shared_ptr<ThreadRunnable> ThreadPool::selectThread(const ExecutionOpts& opts)
{
mLastIndex = _chooseIndex(opts);
return mPool[mLastIndex];
}
size_t ThreadPool::_chooseIndex(const ExecutionOpts& opts) {
size_t result;
switch (opts.schedPolicy)
{
case SchedulingPolicy::SP_ROUNDROBIN:
result = (int)((mLastIndex + 1) % mNThreads);
break;
case SchedulingPolicy::SP_BESTFIT:
//@todo choose least busy thread
result = (int)((mLastIndex + 1) % mNThreads);
break;
case SchedulingPolicy::SP_EXPLICIT:
//assert(opts.threadIndex < (size_t)mNThreads);
result = opts.threadIndex;
break;
default:
result = (int)((mLastIndex + 1) % mNThreads);
}
return result;
}
| 25.322581
| 85
| 0.657325
|
dani-barrientos
|
21c7ded0a0683deb5420e27946d095a98ee196fa
| 867
|
cpp
|
C++
|
src/botchi_c_3002/botchi_c_3002.cpp
|
dnasdw/paiza_botchi
|
8f5c1a72492903fd3a69c13dfe5b840eab89464c
|
[
"MIT"
] | null | null | null |
src/botchi_c_3002/botchi_c_3002.cpp
|
dnasdw/paiza_botchi
|
8f5c1a72492903fd3a69c13dfe5b840eab89464c
|
[
"MIT"
] | null | null | null |
src/botchi_c_3002/botchi_c_3002.cpp
|
dnasdw/paiza_botchi
|
8f5c1a72492903fd3a69c13dfe5b840eab89464c
|
[
"MIT"
] | 1
|
2019-01-27T13:03:11.000Z
|
2019-01-27T13:03:11.000Z
|
#include <iostream>
#ifndef USE_LIBSUNDAOWEN
#define USE_LIBSUNDAOWEN 0
#endif
#if USE_LIBSUNDAOWEN != 0
#include <sdw.h>
#else
#include <string>
using namespace std;
#endif
int main(int argc, char* argv[])
{
string sLine;
getline(cin, sLine);
bool bValid = true;
do
{
int nSize = static_cast<int>(sLine.size());
if (nSize < 6)
{
bValid = false;
break;
}
if (sLine.find_first_of("0123456789") == string::npos)
{
bValid = false;
break;
}
if (sLine.find_first_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") == string::npos)
{
bValid = false;
break;
}
for (int i = 0; i < nSize - 2; i++)
{
if (sLine[i + 1] == sLine[i] && sLine[i + 2] == sLine[i])
{
bValid = false;
break;
}
}
if (!bValid)
{
break;
}
} while (false);
printf("%s\n", bValid ? "Valid" : "Invalid");
return 0;
}
| 16.055556
| 98
| 0.60323
|
dnasdw
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.