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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
88aa8f8162f404c5188ab4c4539da22493499105
| 2,286
|
cpp
|
C++
|
PropertiesModule/propertypromise.cpp
|
HowCanidothis-zz/DevLib
|
d3d7f4ef7b2b3f1c9559ca6bd56743e5aeff06ee
|
[
"MIT"
] | null | null | null |
PropertiesModule/propertypromise.cpp
|
HowCanidothis-zz/DevLib
|
d3d7f4ef7b2b3f1c9559ca6bd56743e5aeff06ee
|
[
"MIT"
] | null | null | null |
PropertiesModule/propertypromise.cpp
|
HowCanidothis-zz/DevLib
|
d3d7f4ef7b2b3f1c9559ca6bd56743e5aeff06ee
|
[
"MIT"
] | 1
|
2020-07-27T02:23:38.000Z
|
2020-07-27T02:23:38.000Z
|
#include "propertypromise.h"
#include "propertiesscope.h"
PropertyPromiseBase::PropertyPromiseBase()
: m_isValid([]{
return false;
})
{
}
PropertyPromiseBase::PropertyPromiseBase(const Name& name, const Name& scopeName)
{
Assign(name, scopeName);
}
PropertyPromiseBase::PropertyPromiseBase(Property* property)
{
m_getter = [property] { return property; };
m_isValid = [] { return true; };
m_setter = [property](const QVariant& value) {
property->SetValue(value);
};
m_propertyName = property->GetPropertyName();
}
void PropertyPromiseBase::Assign(const Name& name, const PropertiesScopeName& scopeName)
{
m_getter = ([name, scopeName, this]{
const auto& scopeProperties = PropertiesSystem::getOrCreateScope(scopeName)->m_properties;
auto foundIt = scopeProperties.find(name);
Q_ASSERT_X(foundIt != scopeProperties.end(), "PropertiesSystem::getValue", name.AsString().toLatin1().constData());
auto property = foundIt.value();
m_getter = [property]{ return property; };
return property;
});
m_isValid = ([name, scopeName, this]{
const auto& scopeProperties = PropertiesSystem::getOrCreateScope(scopeName)->m_properties;
if(scopeProperties.contains(name)) {
m_isValid = []{ return true; };
} else {
return false;
}
return true;
});
m_setter = ([name, scopeName, this](const QVariant& value){
const auto& scopeProperties = PropertiesSystem::getOrCreateScope(scopeName)->m_properties;
auto foundIt = scopeProperties.find(name);
Q_ASSERT_X(foundIt != scopeProperties.end(), "PropertiesSystem::setValue", name.AsString().toLatin1().constData());
auto property = foundIt.value();
m_setter = [property](const QVariant& value){
property->SetValue(value);
};
property->SetValue(value);
});
m_propertyName = name;
}
void PropertyPromiseBase::Subscribe(const Property::FOnChange& onChange)
{
if(IsValid()) {
GetProperty()->Subscribe(onChange);
} else {
PropertiesSystem::Subscribe(m_propertyName, onChange);
}
}
| 33.617647
| 127
| 0.629921
|
HowCanidothis-zz
|
88ac3d0c985c0048cd501bd6ff89bf72f1f6a6e0
| 2,184
|
cpp
|
C++
|
UNIX/UNIXDllLoader.cpp
|
ddag/mylib
|
f2275a5a32c6255b41b27036dc792192e85e392c
|
[
"MIT"
] | 1
|
2019-03-13T14:28:05.000Z
|
2019-03-13T14:28:05.000Z
|
UNIX/UNIXDllLoader.cpp
|
ddag/mylib
|
f2275a5a32c6255b41b27036dc792192e85e392c
|
[
"MIT"
] | null | null | null |
UNIX/UNIXDllLoader.cpp
|
ddag/mylib
|
f2275a5a32c6255b41b27036dc792192e85e392c
|
[
"MIT"
] | null | null | null |
/**************************************************************************
Copyright (c) 2003 Donald Gobin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**************************************************************************/
#include "UNIXDllLoader.h"
#include "Exception.h"
#include <errno.h>
#include <dlfcn.h>
using namespace MyLib;
UNIXDllLoader::UNIXDllLoader(const string& dll) : dllName(dll)
{
if((dllHandle = dlopen(dllName.c_str(), RTLD_LAZY)) == 0)
throw DllLoaderException(string("Unable to load dll ") + dllName, errno);
}
UNIXDllLoader::~UNIXDllLoader()
{
dlclose(dllHandle);
}
void* UNIXDllLoader::GetAddressOf(const string& name)
{
void* sym = dlsym(dllHandle, name.c_str());
if(sym == 0)
throw DllLoaderException(string("Unable to get address of ") + name + string(" in dll ") + dllName, errno);
return sym;
}
| 42
| 115
| 0.71337
|
ddag
|
88b182521bc717f41872ea155cebb86332895115
| 841
|
hpp
|
C++
|
core/include/bind/emu/edi_yank.hpp
|
pit-ray/win-vind
|
7386f6f7528d015ce7f1a5ae230d6e63f9492df9
|
[
"MIT"
] | 731
|
2020-05-07T06:22:59.000Z
|
2022-03-31T16:36:03.000Z
|
core/include/bind/emu/edi_yank.hpp
|
pit-ray/win-vind
|
7386f6f7528d015ce7f1a5ae230d6e63f9492df9
|
[
"MIT"
] | 67
|
2020-07-20T19:46:42.000Z
|
2022-03-31T15:34:47.000Z
|
core/include/bind/emu/edi_yank.hpp
|
pit-ray/win-vind
|
7386f6f7528d015ce7f1a5ae230d6e63f9492df9
|
[
"MIT"
] | 15
|
2021-01-29T04:49:11.000Z
|
2022-03-04T22:16:31.000Z
|
#ifndef _EDI_YANK_HPP
#define _EDI_YANK_HPP
#include "bind/binded_func_creator.hpp"
namespace vind
{
namespace textanalyze {
struct SelRes ;
}
//Copy
struct YankHighlightText : public BindedFuncCreator<YankHighlightText> {
explicit YankHighlightText() ;
static void sprocess() ;
static void sprocess(NTypeLogger& parent_lgr) ;
static void sprocess(const CharLogger& parent_lgr) ;
} ;
struct YankLine : public BindedFuncCreator<YankLine> {
explicit YankLine() ;
static void sprocess(
unsigned int repeat_num=1,
const textanalyze::SelRes* const exres=nullptr) ;
static void sprocess(NTypeLogger& parent_lgr) ;
static void sprocess(const CharLogger& parent_lgr) ;
} ;
}
#endif
| 27.129032
| 77
| 0.636147
|
pit-ray
|
88b6d5d42d5d976656c5104f16a125c44678b7f3
| 1,171
|
cpp
|
C++
|
src/runtime/PolicyRoundRobin.cpp
|
ixiDev/iris
|
23514bc1b724597afa880c67355d86efd3e37631
|
[
"BSD-3-Clause"
] | 14
|
2020-10-15T16:02:24.000Z
|
2022-02-18T03:50:35.000Z
|
src/runtime/PolicyRoundRobin.cpp
|
ixiDev/iris
|
23514bc1b724597afa880c67355d86efd3e37631
|
[
"BSD-3-Clause"
] | 7
|
2021-11-05T22:31:58.000Z
|
2022-03-25T19:56:53.000Z
|
src/runtime/PolicyRoundRobin.cpp
|
ixiDev/iris
|
23514bc1b724597afa880c67355d86efd3e37631
|
[
"BSD-3-Clause"
] | 5
|
2020-12-13T02:42:22.000Z
|
2022-03-24T17:46:19.000Z
|
#include "PolicyRoundRobin.h"
#include "Debug.h"
#include "Device.h"
#include "Scheduler.h"
#include "Task.h"
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <limits.h>
namespace brisbane {
namespace rt {
PolicyRoundRobin::PolicyRoundRobin(Scheduler* scheduler) {
SetScheduler(scheduler);
index_ = 0;
}
PolicyRoundRobin::~PolicyRoundRobin() {
}
void PolicyRoundRobin::GetDevices(Task* task, Device** devs, int* ndevs) {
int policy = task->brs_policy();
if (policy == brisbane_roundrobin) return GetDevice(task, devs, ndevs);
return GetDeviceType(task, devs, ndevs);
}
void PolicyRoundRobin::GetDevice(Task* task, Device** devs, int* ndevs) {
devs[0] = devs_[index_];
*ndevs = 1;
if (++index_ == ndevs_) index_ = 0;
}
void PolicyRoundRobin::GetDeviceType(Task* task, Device** devs, int* ndevs) {
int policy = task->brs_policy();
for (int i = 0; i < ndevs_; i++) {
if (devs_[index_]->type() & policy) {
devs[0] = devs_[index_];
*ndevs = 1;
if (++index_ == ndevs_) index_ = 0;
return;
}
if (++index_ == ndevs_) index_ = 0;
}
*ndevs = 0;
}
} /* namespace rt */
} /* namespace brisbane */
| 22.960784
| 77
| 0.649872
|
ixiDev
|
88b8dc1f5808560321c54ec6ea95566daafef330
| 9,685
|
cpp
|
C++
|
src/Game.cpp
|
hellopuza/Minecraft-plus-plus
|
a5acf2d43775c1bdbe9bf5123de4cf0a7ca17eb4
|
[
"MIT"
] | 1
|
2021-11-06T17:30:34.000Z
|
2021-11-06T17:30:34.000Z
|
src/Game.cpp
|
hellopuza/Minecraft-plus-plus
|
a5acf2d43775c1bdbe9bf5123de4cf0a7ca17eb4
|
[
"MIT"
] | null | null | null |
src/Game.cpp
|
hellopuza/Minecraft-plus-plus
|
a5acf2d43775c1bdbe9bf5123de4cf0a7ca17eb4
|
[
"MIT"
] | null | null | null |
#include "Game.h"
namespace puza {
Game::Game() :
winsizes_ ({ DEFAULT_WIDTH, DEFAULT_HEIGHT }),
window_ (sf::VideoMode(winsizes_.x, winsizes_.y), TITLE_STRING),
person_ (DEFAULT_CAMERA_FOV, static_cast<float>(winsizes_.x) / static_cast<float>(winsizes_.y),
world_.load(DEFAULT_WORLD_NAME)),
ray_tracer_ (winsizes_, &world_, &person_.camera_, DEFAULT_RAY_DEPTH, DEFAULT_RAY_RANGE),
fps_ (font_, sf::Vector2f(0.0F, 0.0F), 16, sf::Color::White),
mouse_visible_(false),
current_block_(BLOCK_GRASS)
{
window_.setMouseCursorVisible(mouse_visible_);
person_.setPosition(vec3f(person_.getPosition().x, person_.getPosition().y, person_.getPosition().z + 1.0F));
font_.loadFromFile(FONT_DESTINATION);
ray_tracer_.addLight(SUN_POSITION + person_.getPosition(), rgb(1.0F, 1.0F, 1.0F), 1.0F, 1.0F);
ray_tracer_.makeShader();
}
void Game::run()
{
while (window_.isOpen())
{
sf::Event event;
while (window_.pollEvent(event))
{
//Close window
if ((event.type == sf::Event::Closed) ||
((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape) && (mouse_visible_)))
{
window_.close();
break;
}
//Toggle mouse visibility
if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))
{
mouse_visible_ = true;
window_.setMouseCursorVisible(mouse_visible_);
}
else if (sf::Mouse::isButtonPressed(sf::Mouse::Left) && mouse_visible_)
{
mouse_visible_ = false;
window_.setMouseCursorVisible(mouse_visible_);
}
//Toggle fullscreen
else if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::F11))
{
toggleFullScreen();
}
//Resize window
else if (event.type == sf::Event::Resized)
{
sf::FloatRect visible_area(0.0F, 0.0F, static_cast<float>(event.size.width), static_cast<float>(event.size.height));
window_.setView(sf::View(visible_area));
updateWinSizes(vec2u(window_.getSize().x, window_.getSize().y));
}
//Camera rotation
else if ((event.type == sf::Event::MouseMoved) && (not mouse_visible_))
{
static sf::Vector2i last_mouse_pos = sf::Mouse::getPosition();
sf::Vector2i delta_pos = sf::Mouse::getPosition() - last_mouse_pos;
sf::Mouse::setPosition(sf::Vector2i(window_.getSize() / 2U), window_);
last_mouse_pos = sf::Mouse::getPosition();
person_.turnHead(vec2f(static_cast<float>(delta_pos.x) / static_cast<float>(SCREEN_SIZE.x),
static_cast<float>(delta_pos.y) / static_cast<float>(SCREEN_SIZE.y)));
}
else if ((event.type == sf::Event::MouseLeft) && (not mouse_visible_))
{
sf::Mouse::setPosition(sf::Vector2i(window_.getSize() / 2U), window_);
}
//Set block
else if ((event.type == sf::Event::MouseButtonPressed) && (event.mouseButton.button == sf::Mouse::Left))
{
Intersection cam_intersection(Ray(person_.camera_.position_, person_.camera_.getForward()));
if (cam_intersection.intersect(world_, MAX_BLOCK_SET_DISTANCE))
{
vec3f relative_point = cam_intersection.point() - vec3f(cam_intersection.block_pos());
vec3i relative_block_center;
if (isNIL(relative_point.y - 0.0F)) relative_block_center = vec3i( 0, -1, 0);
if (isNIL(relative_point.x - 1.0F)) relative_block_center = vec3i( 1, 0, 0);
if (isNIL(relative_point.y - 1.0F)) relative_block_center = vec3i( 0, 1, 0);
if (isNIL(relative_point.x - 0.0F)) relative_block_center = vec3i(-1, 0, 0);
if (isNIL(relative_point.z - 1.0F)) relative_block_center = vec3i( 0, 0, 1);
if (isNIL(relative_point.z - 0.0F)) relative_block_center = vec3i( 0, 0, -1);
vec3i block_pos = cam_intersection.block_pos() + relative_block_center;
if (block_pos != vec3i(person_.getPosition()) && block_pos != vec3i(person_.camera_.position_))
{
world_.setBlock(cam_intersection.block_pos() + relative_block_center, current_block_);
}
}
}
else if ((event.type == sf::Event::MouseButtonPressed) && (event.mouseButton.button == sf::Mouse::Right))
{
Intersection cam_intersection(Ray(person_.camera_.position_, person_.camera_.getForward()));
if (cam_intersection.intersect(world_, MAX_BLOCK_SET_DISTANCE))
{
world_.setBlock(cam_intersection.block_pos(), BLOCK_AIR);
}
}
//Change block
else if (event.type == sf::Event::MouseWheelMoved)
{
int current_block = event.mouseWheel.delta + current_block_;
while (current_block > static_cast<int>(MATERIALS_NUM) - 1)
current_block -= static_cast<int>(MATERIALS_NUM) - 1;
while (current_block < 1)
current_block += static_cast<int>(MATERIALS_NUM) - 1;
current_block_ = static_cast<block_t>(current_block);
}
else if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::R))
{
person_.setPosition(START_PERSON_POSITION);
}
}
if (not mouse_visible_) person_.move(world_);
world_.update(person_.getPosition());
ray_tracer_.setLightPosition(SUN_POSITION + person_.getPosition(), 0);
ray_tracer_.draw(window_);
fps_.update();
window_.draw(fps_);
drawCross();
window_.display();
}
world_.save();
}
void Game::updateWinSizes(const vec2u& size)
{
winsizes_ = size;
ray_tracer_.updateWinSizes(winsizes_);
person_.camera_.updateAspectRatio(static_cast<float>(winsizes_.x) / static_cast<float>(winsizes_.y));
}
void Game::toggleFullScreen()
{
if ((winsizes_.x == sf::VideoMode::getDesktopMode().width) && (winsizes_.y == sf::VideoMode::getDesktopMode().height))
{
window_.create(sf::VideoMode(DEFAULT_WIDTH, DEFAULT_HEIGHT), TITLE_STRING);
updateWinSizes(vec2u(DEFAULT_WIDTH, DEFAULT_HEIGHT));
}
else
{
window_.create(sf::VideoMode::getDesktopMode(), TITLE_STRING, sf::Style::Fullscreen);
updateWinSizes(vec2u(sf::VideoMode::getDesktopMode().width, sf::VideoMode::getDesktopMode().height));
}
window_.setMouseCursorVisible(mouse_visible_);
}
void Game::savePicture()
{
static int shot_num = 0;
std::string filename = "screenshot(" + std::to_string(shot_num++) + ")" + ".png";
sf::Texture screen;
screen.create(window_.getSize().x, window_.getSize().y);
screen.update(window_);
sf::RectangleShape rectangle;
rectangle.setPosition(0, 0);
rectangle.setSize(sf::Vector2f(window_.getSize()));
if (screen.copyToImage().saveToFile(filename))
rectangle.setFillColor(sf::Color(10, 10, 10, 150)); // grey screen if ok
else
rectangle.setFillColor(sf::Color(255, 10, 10, 200)); // red screen if error
window_.draw(rectangle);
window_.display();
sf::sleep(sf::milliseconds(300));
sf::Sprite screen_sprite(screen);
window_.draw(screen_sprite);
window_.display();
}
void Game::drawCross()
{
const float size = 7.0F;
sf::Vertex line1[] =
{
sf::Vertex(sf::Vector2f(static_cast<float>(winsizes_.x) / 2.0F - size,
static_cast<float>(winsizes_.y) / 2.0F), sf::Color(200, 200, 200)),
sf::Vertex(sf::Vector2f(static_cast<float>(winsizes_.x) / 2.0F + size,
static_cast<float>(winsizes_.y) / 2.0F), sf::Color(200, 200, 200))
};
sf::Vertex line2[] =
{
sf::Vertex(sf::Vector2f(static_cast<float>(winsizes_.x) / 2.0F,
static_cast<float>(winsizes_.y) / 2.0F - size), sf::Color(200, 200, 200)),
sf::Vertex(sf::Vector2f(static_cast<float>(winsizes_.x) / 2.0F,
static_cast<float>(winsizes_.y) / 2.0F + size), sf::Color(200, 200, 200))
};
window_.draw(line1, 2, sf::Lines);
window_.draw(line2, 2, sf::Lines);
sf::Text position;
position.setCharacterSize(16);
position.setStyle(sf::Text::Bold);
position.setFillColor(sf::Color::White);
position.setPosition(sf::Vector2f(100.0F, 0.0F));
position.setFont(font_);
char pos[512] = "";
sprintf(pos, "x: %.2f, y: %.2f, z: %.2f, block: %s\n",
person_.getPosition().x - static_cast<float>(START_CHUNK_POS.x),
person_.getPosition().y - static_cast<float>(START_CHUNK_POS.y), person_.getPosition().z, MATERIALS[current_block_].name);
position.setString(pos);
window_.draw(position);
}
} // namespace puza
| 39.210526
| 133
| 0.567579
|
hellopuza
|
88ba87e332ef0d567bfe63aa8b3f5c174e020607
| 313
|
cpp
|
C++
|
exampleStandalone/src/main.cpp
|
Ant1r/POF
|
b80210527454484f64003b7a09c8e7f9f8a09ac3
|
[
"BSD-2-Clause"
] | 64
|
2015-03-26T00:03:34.000Z
|
2021-12-30T12:27:49.000Z
|
exampleStandalone/src/main.cpp
|
Ant1r/POF
|
b80210527454484f64003b7a09c8e7f9f8a09ac3
|
[
"BSD-2-Clause"
] | 7
|
2015-03-27T09:26:29.000Z
|
2021-05-08T22:59:52.000Z
|
exampleStandalone/src/main.cpp
|
Ant1r/POF
|
b80210527454484f64003b7a09c8e7f9f8a09ac3
|
[
"BSD-2-Clause"
] | 7
|
2015-07-02T11:00:36.000Z
|
2020-04-05T18:48:38.000Z
|
#include "ofMain.h"
#include "testApp.h"
//========================================================================
int main(int argc, char *argv[]){
ofSetupOpenGL(400, 400, OF_WINDOW);
ofSetFrameRate(50);
testApp *app = new testApp();
app->arguments = vector<string>(argv, argv + argc);
ofRunApp(app);
}
| 24.076923
| 74
| 0.517572
|
Ant1r
|
88bdaf18e502f03eb441f27df478c85350580762
| 463
|
hpp
|
C++
|
GD4GameWorld/Include/Book/Node/ShapeNode.hpp
|
Alex-Jay/2d_sfml_game
|
3872c92d1e17b68c2bf2c78f13e32b2bf80a605a
|
[
"MIT"
] | 1
|
2018-12-18T12:00:57.000Z
|
2018-12-18T12:00:57.000Z
|
GD4GameWorld/Include/Book/Node/ShapeNode.hpp
|
Alex-Jay/k-arnage_2d_sfml_game
|
3872c92d1e17b68c2bf2c78f13e32b2bf80a605a
|
[
"MIT"
] | null | null | null |
GD4GameWorld/Include/Book/Node/ShapeNode.hpp
|
Alex-Jay/k-arnage_2d_sfml_game
|
3872c92d1e17b68c2bf2c78f13e32b2bf80a605a
|
[
"MIT"
] | null | null | null |
#pragma once
#include "Structural/ResourceHolder.hpp"
#include "Structural/ResourceIdentifiers.hpp"
#include "Node/SceneNode.hpp"
#include "SFML/Graphics/RectangleShape.hpp"
class ShapeNode : public SceneNode
{
public:
explicit ShapeNode(sf::Color fillColor);
void setFillColor(sf::Color color);
void setSize(int x, int y);
private:
virtual void drawCurrent(sf::RenderTarget& target, sf::RenderStates states) const;
private:
sf::RectangleShape mShape;
};
| 23.15
| 83
| 0.777538
|
Alex-Jay
|
88bfa9e8d2bbcdf1933cdda854f2a40c46256465
| 1,196
|
cpp
|
C++
|
leetcode/648. Replace Words/s1.cpp
|
zhuohuwu0603/leetcode_cpp_lzl124631x
|
6a579328810ef4651de00fde0505934d3028d9c7
|
[
"Fair"
] | 787
|
2017-05-12T05:19:57.000Z
|
2022-03-30T12:19:52.000Z
|
leetcode/648. Replace Words/s1.cpp
|
aerlokesh494/LeetCode
|
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
|
[
"Fair"
] | 8
|
2020-03-16T05:55:38.000Z
|
2022-03-09T17:19:17.000Z
|
leetcode/648. Replace Words/s1.cpp
|
aerlokesh494/LeetCode
|
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
|
[
"Fair"
] | 247
|
2017-04-30T15:07:50.000Z
|
2022-03-30T09:58:57.000Z
|
// OJ: https://leetcode.com/problems/replace-words/
// Author: github.com/lzl124631x
// Time: O(D + S) where D is size of all contents in dictionary, S is size of all contents in sentence
// Space: O(D)
class TrieNode {
public:
TrieNode *next[26] = {};
bool isWord = false;
};
class Trie {
private:
TrieNode root;
public:
void insert(string &s) {
auto node = &root;
for (char c : s) {
if (!node->next[c - 'a']) node->next[c - 'a'] = new TrieNode();
node = node->next[c - 'a'];
}
node->isWord = true;
}
string getWord(string &s) {
auto node = &root;
for (int i = 0; i < s.size(); ++i) {
if (!node->next[s[i] - 'a']) return s;
node = node->next[s[i] - 'a'];
if (node->isWord) return s.substr(0, i + 1);
}
return s;
}
};
class Solution {
public:
string replaceWords(vector<string>& dict, string sentence) {
istringstream ss(sentence);
string word, ans;
Trie trie;
for (auto s : dict) trie.insert(s);
while (ss >> word) ans += trie.getWord(word)+ " ";
ans.pop_back();
return ans;
}
};
| 27.813953
| 102
| 0.522575
|
zhuohuwu0603
|
88bfedee72477d207646b1385250a0285624a13a
| 852
|
cpp
|
C++
|
acm-template/4 Math/Euler.cpp
|
joshua-xia/noip
|
0603a75c7be6e9b21fcabbba4260153cf776c32f
|
[
"Apache-2.0"
] | null | null | null |
acm-template/4 Math/Euler.cpp
|
joshua-xia/noip
|
0603a75c7be6e9b21fcabbba4260153cf776c32f
|
[
"Apache-2.0"
] | null | null | null |
acm-template/4 Math/Euler.cpp
|
joshua-xia/noip
|
0603a75c7be6e9b21fcabbba4260153cf776c32f
|
[
"Apache-2.0"
] | null | null | null |
#### 欧拉函数打表
O(nlog(n))
```
const int maxn = 1e6+100;
int phi[maxn],Prime[maxn];
void init2(int n){
for(int i = 1;i <= n; ++i) phi[i] = i;
for(int i = 2;i <= n; ++i){
if(i == phi[i]){
for(int j = i; j <= n; j += i) phi[j] = phi[j]/i*(i-1);
}
}
}
```
线性筛 O(n)
```
const int maxn = 1e6+100;
bool check[maxn];
int phi[maxn],Prime[maxn];
void init(int MAXN){
int N = maxn-1;
memset(check,false,sizeof(check));
phi[1] = 1;
int tot = 0;
for(int i = 2;i <= N; ++i){
if(!check[i]){
Prime[tot++] = i;
phi[i] = i-1;
}
for(int j = 0;j < tot; ++j){
if(i*Prime[j] > N) break;
check[i*Prime[j]] = true;
if(i%Prime[j] == 0){
phi[i*Prime[j]] = phi[i]*Prime[j];
break;
}
else{
phi[i*Prime[j]] = phi[i]*(Prime[j]-1);
}
}
}
}
```
| 18.12766
| 63
| 0.440141
|
joshua-xia
|
88c5c9e3ec6a081a6a21053bb29d0ba0d7c88526
| 12,274
|
hpp
|
C++
|
H01indexedCSVdatabase/H01indexedCSVdatabaseQuery.hpp
|
baxterai/H01localConnectome
|
52118d10edc4d6d5534ee39c43a4db3b588481de
|
[
"MIT"
] | null | null | null |
H01indexedCSVdatabase/H01indexedCSVdatabaseQuery.hpp
|
baxterai/H01localConnectome
|
52118d10edc4d6d5534ee39c43a4db3b588481de
|
[
"MIT"
] | null | null | null |
H01indexedCSVdatabase/H01indexedCSVdatabaseQuery.hpp
|
baxterai/H01localConnectome
|
52118d10edc4d6d5534ee39c43a4db3b588481de
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
*
* File Name: H01indexedCSVdatabaseQuery.hpp
* Author: Richard Bruce Baxter - Copyright (c) 2021 Baxter AI (baxterai.com)
* License: MIT License
* Project: H01LocalConnectome
* Requirements: requires H01 indexed CSV database to have already been generated (see INDEXED_CSV_DATABASE_CREATE: H01indexedCSVdatabaseCreate.cpp/.hpp)
* Compilation: see H01indexedCSVdatabase.hpp
* Usage: see H01indexedCSVdatabase.hpp
* Description: H01 indexed CSV database query -
* INDEXED_CSV_DATABASE_QUERY_EXTRACT_INCOMING_OUTGOING_CONNECTIONS: mode 1 (lookup indexed CSV database by neuron ID, and find incoming/outgoing target connections, and write them to file)
* INDEXED_CSV_DATABASE_QUERY_PERFORM_INCOMING_AXON_MAPPING: mode 2 (lookup indexed CSV database by neuron ID, find incoming target connections, and generate visualisation)
* INDEXED_CSV_DATABASE_QUERY_GENERATE_LOCAL_CONNECTOME_CONNECTIONS_DATASET: mode 3 (automatically generate localConnectomeConnections-typesFromPresynapticNeurons.csv/localConnectomeConnections-typesFromEMimages.csv from localConnectomeNeurons.csv and indexed CSV database)
* INDEXED_CSV_DATABASE_QUERY_COUNT_CONNECTIONS_PROPORTION_LOCAL_VS_NONLOCAL_CONNECTIONS: mode 4 (lookup indexed CSV database by neuron ID, count/infer proportion of incoming/outgoing excitatory/inhibitory target connections to local vs distal neurons)
* INDEXED_CSV_DATABASE_QUERY_COMPLETE_LOCAL_CONNECTOME_CONNECTIONS_DATASET: mode 5 (lookup indexed CSV database by post/pre synaptic connection neuron ID, and identify connection with pre/post synaptic X/Y coordinates (if pre/post synaptic neuron type=UNKNOWN), add pre/post synaptic neuron ID, Z coordinates, and type coordinates to connection dataset [incomplete: awaiting release of H01 Release C3 neurons dataset; will print UNKNOWN neurons (with x/y coordinates only) along with candidate neuron_ids but not reconcile them])
* INDEXED_CSV_DATABASE_QUERY_CRAWL_CONNECTIONS_COUNT_NUMBER_UNIQUE_AXONS_DENDRITES - mode 6 (crawl indexed CSV database by pre/post synaptic connection neuron ID, and count number of unique axons/dendrites as specified by neuron ID - not explicitly connected to local connectome [incomplete])
* Input:
* INDEXED_CSV_DATABASE_QUERY_OUTPUT_CONNECTIONS: localConnectomeNeurons.csv (or localConnectomeNeuronIDlistDistinct.csv) - id, x, y, z, type, excitation_type (or id)
* INDEXED_CSV_DATABASE_QUERY_PERFORM_INCOMING_AXON_MAPPING: localConnectomeNeurons.csv (or localConnectomeNeuronIDlistDistinct.csv) - id, x, y, z, type, excitation_type (or id)
* INDEXED_CSV_DATABASE_QUERY_GENERATE_LOCAL_CONNECTOME_CONNECTIONS_DATASET: localConnectomeNeurons.csv - id, x, y, z, type, excitation_type
* INDEXED_CSV_DATABASE_QUERY_COUNT_CONNECTIONS_PROPORTION_LOCAL_VS_NONLOCAL_CONNECTIONS: localConnectomeNeurons.csv (or localConnectomeNeuronIDlistDistinct.csv) - id, x, y, z, type, excitation_type (or id)
* INDEXED_CSV_DATABASE_QUERY_COMPLETE_LOCAL_CONNECTOME_CONNECTIONS_DATASET: localConnectomeConnections-typesFromEMimages-useAllValuesAvailableFromInBodyCellConnection.csv - pre_id, pre_x, pre_y, pre_z, pre_type, post_id, post_x, post_y, post_z, post_type, post_class_label, syn_num, excitation_type
* INDEXED_CSV_DATABASE_QUERY_CRAWL_CONNECTIONS_COUNT_NUMBER_UNIQUE_AXONS_DENDRITES: N/A
* Output Format:
* INDEXED_CSV_DATABASE_QUERY_OUTPUT_CONNECTIONS: localConnectomeNeuronIDlistConnectionsPresynaptic.csv/localConnectomeNeuronIDlistConnectionsPostsynaptic.csv - connectionNeuronID1, connectionType1 [, locationObjectContentsXcoordinatesContent1, locationObjectContentsYcoordinatesContent1, locationObjectContentsZcoordinatesContent1], connectionNeuronID2, connectionType2 [, locationObjectContentsXcoordinatesContent2, locationObjectContentsYcoordinatesContent2, locationObjectContentsZcoordinatesContent2], etc
* INDEXED_CSV_DATABASE_QUERY_PERFORM_INCOMING_AXON_MAPPING:
* INDEXED_CSV_DATABASE_QUERY_PERFORM_INCOMING_AXON_MAPPING_3D_LINEAR_REGRESSION:
* INDEXED_CSV_DATABASE_QUERY_OUTPUT_INCOMING_AXON_MAPPING_LDR: localConnectomeIncomingAxonMapping.ldr - LDR_REFERENCE_TYPE_LINE ldrawColor plot3DpointStart.x plot3DpointStart.y plot3DpointStart.z plot3DpointEnd.x plot3DpointEnd.y plot3DpointEnd.z
* INDEXED_CSV_DATABASE_QUERY_OUTPUT_INCOMING_AXON_MAPPING_CSV: localConnectomeIncomingAxonMapping.csv - polyFit.connectionNeuronID, polyFit.estSynapseType, polyFit.origin.x, polyFit.origin.y, polyFit.origin.z, polyFit.axis.x, polyFit.axis.y, polyFit.axis.z
* INDEXED_CSV_DATABASE_QUERY_PERFORM_INCOMING_AXON_MAPPING_2D_POLY_REGRESSION:
* INDEXED_CSV_DATABASE_QUERY_OUTPUT_INCOMING_AXON_MAPPING_CSV: localConnectomeIncomingAxonMapping.csv - polyFit.connectionNeuronID, polyFit.estSynapseType, polyFit.a, polyFit.b, polyFit.c
* INDEXED_CSV_DATABASE_QUERY_GENERATE_LOCAL_CONNECTOME_CONNECTIONS_DATASET: localConnectomeConnections-typesFromPresynapticNeurons.csv/localConnectomeConnections-typesFromEMimages.csv - pre_id, pre_x, pre_y, pre_z, pre_type, post_id, post_x, post_y, post_z, post_type, post_class_label, syn_num, excitation_type
* INDEXED_CSV_DATABASE_QUERY_COUNT_CONNECTIONS_PROPORTION_LOCAL_VS_NONLOCAL_CONNECTIONS: N/A
* INDEXED_CSV_DATABASE_QUERY_COMPLETE_LOCAL_CONNECTOME_CONNECTIONS_DATASET: localConnectomeConnections-typesFromEMimages.csv - pre_id, pre_x, pre_y, pre_z, pre_type, post_id, post_x, post_y, post_z, post_type, post_class_label, syn_num, excitation_type
* INDEXED_CSV_DATABASE_QUERY_CRAWL_CONNECTIONS_COUNT_NUMBER_UNIQUE_AXONS_DENDRITES: N/A
* Comments:
* /
*******************************************************************************/
#ifndef HEADER_H01indexedCSVdatabaseQuery
#define HEADER_H01indexedCSVdatabaseQuery
#include "H01indexedCSVdatabase.hpp"
#ifdef INDEXED_CSV_DATABASE_QUERY_LAYERS
#include "H01indexedCSVdatabaseCalculateNeuronLayer.hpp"
#endif
#include "H01indexedCSVdatabaseOperations.hpp"
#include "SHAREDvars.hpp"
#ifdef INDEXED_CSV_DATABASE_QUERY
typedef struct { int x, y, z; } vecInt;
#ifdef INDEXED_CSV_DATABASE_QUERY_PERFORM_INCOMING_AXON_MAPPING
class H01indexedCSVdatabaseQueryObject
{
public:
H01indexedCSVdatabaseQueryObject(void);
~H01indexedCSVdatabaseQueryObject(void);
long neuronID;
int type;
int locationObjectContentsXcoordinates; //note coordinates are stored as integers in C3 connections database
int locationObjectContentsYcoordinates; //note coordinates are stored as integers in C3 connections database
int locationObjectContentsZcoordinates; //note coordinates are stored as integers in C3 connections database
/*
string neuronIDstring;
string typeString;
string locationObjectContentsXcoordinatesContent;
string locationObjectContentsYcoordinatesContent;
string locationObjectContentsZcoordinatesContent;
*/
};
#endif
class H01indexedCSVdatabaseQueryClass
{
private: SHAREDvarsClass SHAREDvars;
private: H01indexedCSVdatabaseOperationsClass H01indexedCSVdatabaseOperations;
#ifdef INDEXED_CSV_DATABASE_QUERY_LAYERS
private: H01indexedCSVdatabaseCalculateNeuronLayerClass H01indexedCSVdatabaseCalculateNeuronLayer;
#endif
public: bool queryIndexedCSVdatabase(const int queryMode, const string indexed_csv_database_folder, const string local_connectome_folder_base);
private: bool queryIndexedCSVdatabaseByNeuronDatasetOrListFile(const int queryMode, const string indexed_csv_database_folder, const string local_connectome_folder_base, const string neuronDatasetOrListFileName, const bool neuronListIsDataset, const bool queryPresynapticConnectionNeurons, const bool write, const bool appendToFile, const string neuronListConnectionsFileName, const bool connectionTypesDerivedFromPresynapticNeuronsOrEMimages);
private: bool queryIndexedCSVdatabaseByNeuronList(const int queryMode, const string indexed_csv_database_folder, vector<string>* neuronList, map<string, int>* neuronMap, vector<vector<string>>* localConnectomeNeurons, vector<vector<string>>* localConnectomeConnections, map<string, int>* connectionsMap, const bool queryByPresynapticConnectionNeurons, const bool connectionTypesDerivedFromPresynapticNeuronsOrEMimages, ofstream* writeFileObject, string* writeFileString, const bool appendToFile);
#ifdef INDEXED_CSV_DATABASE_QUERY_COUNT_CONNECTIONS
private: void printNumberOfConnections(const bool queryByPresynapticConnectionNeurons, const vector<int>* numberConnectionsLocalConnectomeLayers, const vector<int>* numberConnectionsExternalConnectomeLayers, const vector<int>* numberConnectionsLocalConnectomeExcitatoryLayers, const vector<int>* numberConnectionsExternalConnectomeExcitatoryLayers, const vector<int>* numberConnectionsLocalConnectomeInhibitoryLayers, const vector<int>* numberConnectionsExternalConnectomeInhibitoryLayers, const vector<int>* numberOfLocalConnectomeNeuronsLayers, const vector<int>* numberOfLocalConnectomeNeuronsExcitatoryLayers, const vector<int>* numberOfLocalConnectomeNeuronsInhibitoryLayers, const bool countLocalConnectomeNeurons, const bool countInternalConnectomeConnections, const bool countExternalConnectomeConnections);
private: void printNumberOfConnections(const bool queryByPresynapticConnectionNeurons, const int numberConnectionsLocalConnectome, const int numberConnectionsExternalConnectome, const int numberConnectionsLocalConnectomeExcitatory, const int numberConnectionsExternalConnectomeExcitatory, const int numberConnectionsLocalConnectomeInhibitory, const int numberConnectionsExternalConnectomeInhibitory, const int numberOfLocalConnectomeNeurons, const int numberOfLocalConnectomeNeuronsExcitatory, const int numberOfLocalConnectomeNeuronsInhibitory, const bool countLocalConnectomeNeurons, const bool countInternalConnectomeConnections, const bool countExternalConnectomeConnections);
#ifdef INDEXED_CSV_DATABASE_QUERY_COUNT_CONNECTIONS_LOCAL
private: bool countConnectionsLocal(vector<string>* neuronList, map<string, int>* neuronMap, vector<vector<string>>* localConnectomeNeurons, vector<vector<string>>* localConnectomeConnections, const bool queryByPresynapticConnectionNeurons, const bool connectionTypesDerivedFromPresynapticNeuronsOrEMimages);
#endif
#endif
#ifdef INDEXED_CSV_DATABASE_QUERY_COMPLETE_LOCAL_CONNECTOME_CONNECTIONS_DATASET
private: bool queryIndexedCSVdatabaseByConnectionDatasetFile(const int queryMode, const string indexed_csv_database_folder, const string local_connectome_folder_base, const bool connectionDatasetRead, const string connectionDatasetFileNameRead, vector<vector<string>>* localConnectomeConnections, const bool queryPresynapticConnectionNeurons, const bool connectionDatasetWrite, const bool appendToFile, const string connectionDatasetFileNameWrite, const bool connectionTypesDerivedFromPresynapticNeuronsOrEMimages);
private: bool queryIndexedCSVdatabaseByConnectionNeuronList(const int queryMode, const string indexed_csv_database_folder, vector<string>* neuronList, vector<vector<string>>* localConnectomeConnections, const bool queryByPresynapticConnectionNeurons, const bool connectionTypesDerivedFromPresynapticNeuronsOrEMimages, const bool connectionDatasetWrite, ofstream* writeFileObject, string* writeFileString);
#endif
private: bool queryIndexedCSVdatabaseByNeuronID(const string indexed_csv_database_folder, const string neuronID, const bool queryByPresynapticConnectionNeurons, vector<vector<string>>* neuronConnectionList);
private: bool convertCSVlineToVector(const string* csvLineText, vector<string>* csvLineVector);
#ifdef INDEXED_CSV_DATABASE_QUERY_CRAWL_CONNECTIONS_COUNT_NUMBER_UNIQUE_AXONS_DENDRITES
private: bool crawlIndexedCSVdatabase(const int queryMode, const string indexed_csv_database_folder, const bool queryPresynapticConnectionNeurons);
private: bool crawlIndexedCSVdatabase(const int queryMode, const string indexed_csv_database_folder, const string neuronIDstart, const bool queryByPresynapticConnectionNeurons, map<long,long>* uniqueNeuronIDmap, long* numberConnectionsExcitatory, long* numberConnectionsInhibitory);
#endif
#ifndef INDEXED_CSV_DATABASE_QUERY_READ_WRITE_TO_FILE_OBJECT
private: void appendStringBufferToPreallocatedString(string* s, string stringToAppend);
#endif
};
#endif
#endif
| 105.810345
| 819
| 0.854326
|
baxterai
|
88c78ea7ee36d13932a82afa16117718d0baea1d
| 2,885
|
cpp
|
C++
|
docs/tema4/sesion30.10.20/sable-laser-alumnos.cpp
|
GabJL/FI2020
|
2541622ecc2ce4f4db66ae2006006827dac90217
|
[
"MIT"
] | null | null | null |
docs/tema4/sesion30.10.20/sable-laser-alumnos.cpp
|
GabJL/FI2020
|
2541622ecc2ce4f4db66ae2006006827dac90217
|
[
"MIT"
] | null | null | null |
docs/tema4/sesion30.10.20/sable-laser-alumnos.cpp
|
GabJL/FI2020
|
2541622ecc2ce4f4db66ae2006006827dac90217
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "utils.hpp"
using namespace std;
int main(){
int color, alto, tipo;
limpiarPantalla();
cout << "Crea tu propia sable laser (v1.0)" << endl << endl;
// Lectura de la longitud del sable láser
// Es un valor entre 4-8 o 0 para indicar que está apagada
/// TODO: Usando un do-while repita este código hasta que el valor esté en el rango indicado
cout << "Alto (4-8 o 0 para apagada): ";
cin >> alto;
// Fin de lectura de la longitud
// Lectura del color del sable
// Puede ser un valor entre 1-6
/// TODO: Usando un do-while repita este código hasta que el valor esté en el rango indicado
cout << "1.- Azul" << endl;
cout << "2.- Verde" << endl;
cout << "3.- Cian" << endl;
cout << "4.- Rojo" << endl;
cout << "5.- Morado" << endl;
cout << "6.- Amarillo" << endl;
cout << "Elige el color (1-6): ";
cin >> color;
// Fin de lectura de color
// Lectura del tipo de sable
// Puede ser un valor entre 1-3
/// TODO: Usando un do-while repita este código hasta que el valor esté en el rango indicado
cout << "1.- Clasico" << endl;
cout << "2.- Kylo" << endl;
cout << "3.- Darth Maul" << endl;
cout << "Elige tipo (1-3): ";
cin >> tipo;
// Fin de lectura de tipo de sable
cout << endl;
// Dibujando la hoja luminosa del sable
// Cambiamos el color de lo que escribimos
cambiarColor(color, CLARO, NEGRO, OSCURO);
/// TODO: Repita esta línea tantas veces como dice el alto
cout << " \u2592" << endl;
// Fin de dibujar la hoja
// Volvemos al color normal para dibujar la empuñadura
cambiarColor(BLANCO, CLARO, NEGRO, OSCURO);
/// TODO: Haga un switch dependiendo del tipo de sable para dibujar su empuñadura
// Sable clásico (1)
cout << " \u2588" << endl;
cout << " \u2593" << endl;
cout << " \u2593" << endl;
cout << " \u2580" << endl;
// Sable Kylo (tridente) (r21)
cambiarColor(color, CLARO, NEGRO, OSCURO);
/// TODO: Si está apagada (alto es 0) dibuje 2 espacios sino dibuje "\u25C4\u25AC"
cambiarColor(BLANCO, CLARO, NEGRO, OSCURO);
cout << "\u25AC\u2588\u25AC";
cambiarColor(color, CLARO, NEGRO, OSCURO);
/// TODO: La siguiente sentencia solo debe ejecutarse si no está apagada (alto no es 0)
cout << "\u25AC\u25BA";
cambiarColor(BLANCO, CLARO, NEGRO, OSCURO);
cout << endl;
cout << " \u2593" << endl;
cout << " \u2580" << endl;
// Sable Darth Maul (doble) (3)
cout << " \u2588" << endl;
cout << " \u2593" << endl;
cout << " \u2593" << endl;
cout << " \u2588" << endl;
// Segunda hoja
cambiarColor(color, CLARO, NEGRO, OSCURO);
/// TODO: Repita esta sentencia el número de veces indicada por alto
cout << " \u2592" << endl;
/// TODO: Aquí acaba el switch
// Fin de dibujar todas
restaurarColores();
cout << endl;
return 0;
}
| 33.941176
| 93
| 0.610052
|
GabJL
|
88c86b1fcd02b37f6756015b5e74f22fbdd69f98
| 998
|
cpp
|
C++
|
Kernel/Arch/aarch64/Panic.cpp
|
Anon1428/serenity
|
0daf5cc434e7a998da15330bd8b4d46ae1759485
|
[
"BSD-2-Clause"
] | 2
|
2022-02-16T02:12:38.000Z
|
2022-02-20T18:40:41.000Z
|
Kernel/Arch/aarch64/Panic.cpp
|
Anon1428/serenity
|
0daf5cc434e7a998da15330bd8b4d46ae1759485
|
[
"BSD-2-Clause"
] | null | null | null |
Kernel/Arch/aarch64/Panic.cpp
|
Anon1428/serenity
|
0daf5cc434e7a998da15330bd8b4d46ae1759485
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* Copyright (c) 2022, Timon Kruiper <timonkruiper@gmail.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <Kernel/Arch/Processor.h>
#include <Kernel/KSyms.h>
#include <Kernel/Panic.h>
// FIXME: Merge the code in this file with Kernel/Panic.cpp once the proper abstractions are in place.
// Note: This is required here, since __assertion_failed should be out of the Kernel namespace,
// but the PANIC macro uses functions that require the Kernel namespace.
using namespace Kernel;
[[noreturn]] void __assertion_failed(char const* msg, char const* file, unsigned line, char const* func)
{
critical_dmesgln("ASSERTION FAILED: {}", msg);
critical_dmesgln("{}:{} in {}", file, line, func);
// Used for printing a nice backtrace!
PANIC("Aborted");
}
void Kernel::__panic(char const* file, unsigned int line, char const* function)
{
critical_dmesgln("at {}:{} in {}", file, line, function);
dump_backtrace(PrintToScreen::Yes);
Processor::halt();
}
| 30.242424
| 104
| 0.703407
|
Anon1428
|
88c987fe8b5fd8e7cc66446b29cf9cac356b8f87
| 13,678
|
cpp
|
C++
|
Synergy Editor TGC/Synergy Editor/Utilities.cpp
|
domydev/Dark-Basic-Pro
|
237fd8d859782cb27b9d5994f3c34bc5372b6c04
|
[
"MIT"
] | 231
|
2018-01-28T00:06:56.000Z
|
2022-03-31T21:39:56.000Z
|
Synergy Editor TGC/Synergy Editor/Utilities.cpp
|
domydev/Dark-Basic-Pro
|
237fd8d859782cb27b9d5994f3c34bc5372b6c04
|
[
"MIT"
] | 9
|
2016-02-10T10:46:16.000Z
|
2017-12-06T17:27:51.000Z
|
Synergy Editor TGC/Synergy Editor/Utilities.cpp
|
domydev/Dark-Basic-Pro
|
237fd8d859782cb27b9d5994f3c34bc5372b6c04
|
[
"MIT"
] | 66
|
2018-01-28T21:54:52.000Z
|
2022-02-16T22:50:57.000Z
|
#include "StdAfx.h"
#include "Utilities.h"
#include "Variables.h"
#include "Settings.h"
// For GoToLine
#include "View.h"
#include "Doc.h"
#include "Synergy Editor.h"
WORD Utilities::r;
WORD Utilities::c1;
WORD Utilities::c2;
DWORD Utilities::sum;
// Extracts the filename from the fully qualified path
CString Utilities::ExtractFilename(CString item)
{
UINT stringLength = item.GetLength();
for(UINT i=stringLength; i > 0; i--)
{
if(item.GetAt(i) == '\\')
{
return item.Right(item.GetLength() - (i + 1));
}
}
return item;
}
// Extracts the path from the fully qualified path
CString Utilities::ExtractPath(CString item)
{
UINT stringLength = item.GetLength();
for(UINT i=stringLength; i > 0; i--)
{
if(item.GetAt(i) == '\\')
{
return item.Left(i + 1);
}
}
return item;
}
// Returns the relative path of an item
CString Utilities::GetRelativePath(CString item)
{
if(Utilities::ExtractPath(item) == Variables::m_ProjectPath)
{
return Utilities::ExtractFilename(item);
}
else
{
CString extracted(Utilities::ExtractPath(item));
if(extracted.Mid(0, Variables::m_ProjectPath.GetLength()) == Variables::m_ProjectPath)
{
return item.Mid(Variables::m_ProjectPath.GetLength());
}
else
{
return item;
}
}
}
// Removes the modified flag if it exists from the title
CString Utilities::RemoveModifiedFlag(CString title)
{
if(title.Right(1) == "*")
{
return title.Left(title.GetLength() - 2);
}
else
{
return title;
}
}
// Removes the file extension
CString Utilities::RemoveExtension(CString item)
{
UINT stringLength = item.GetLength();
for(UINT i=stringLength; i > 0; i--)
{
if(item.GetAt(i) == '.')
{
return item.Left(i);
}
}
return item;
}
// Returns whether the path exists
bool Utilities::CheckPathExists(CString szPath)
{
DWORD dwAttrib = GetFileAttributes(szPath);
return (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
// Returns whether the file exists
bool Utilities::CheckFileExists(CString szFile)
{
CFileStatus status;
return (CFile::GetStatus(szFile,status) == TRUE);
}
CTime Utilities::GetFileWriteTime(CString szFile)
{
CFileStatus status;
if(!CFile::GetStatus(szFile, status))
{
return NULL;
}
return status.m_mtime;
}
// Creates a path if it doesn't exist
bool Utilities::EnsurePathExists(CString path)
{
if(Utilities::CheckPathExists(path))
{
return true;
}
if(!CreateDirectory(path, NULL))
{
return false;
}
return true;
}
// Returns whether the string is a number
bool Utilities::isNumber(CString &item)
{
UINT stringLength = item.GetLength();
for(UINT i=0; i<stringLength; i++)
{
if(!isdigit(item.GetAt(i)))
{
return false;
}
}
return true;
}
// Returns the integer as a string
CString Utilities::GetNumber(int num)
{
char pszNum [10] = {0};
_itoa_s(num,pszNum,10, 10);
CString res(pszNum);
return res;
}
CString Utilities::GetSpecialFolderLocation(int nFolder)
{
CString Result;
LPITEMIDLIST pidl;
HRESULT hr = SHGetSpecialFolderLocation(NULL, nFolder, &pidl);
if (SUCCEEDED(hr))
{
// Convert the item ID list's binary
// representation into a file system path
TCHAR szPath[_MAX_PATH];
if (SHGetPathFromIDList(pidl, szPath))
{
Result = szPath;
}
else
{
ASSERT(FALSE);
}
}
else
{
ASSERT(FALSE);
}
return Result;
}
int CALLBACK Utilities::BrowseCallbackProc( HWND hWnd, UINT uMsg, LPARAM lParam, LPARAM lpData )
{
if (uMsg == BFFM_INITIALIZED)
{
SendMessage(hWnd, BFFM_SETSELECTION,TRUE, lpData);
}
return 0;
}
// Shows the browse for folder window
bool Utilities::ShowBrowseWindow(CString &folder, CString text, CString defaultPath)
{
// Create a pointer to a MALLOC (memory allocation object) then get the Shell Malloc.
IMalloc* pMalloc = 0;
if(::SHGetMalloc(&pMalloc) != NOERROR)
return false;
// Now create BROWSEINFO structure, to tell the shell how to display the dialog.
BROWSEINFO bi;
memset(&bi, 0, sizeof(bi));
bi.hwndOwner = NULL;;
bi.lpszTitle = text;
bi.ulFlags = BIF_USENEWUI;
LPITEMIDLIST pidl;
SHGetSpecialFolderLocation(NULL,CSIDL_DRIVES , &pidl);// My Computer
bi.pidlRoot = pidl;
// LPITEMIDLIST pItemIDList = new ITEMIDLIST;
//// the path you want to convert
//LPCWSTR pszName = L"C:\\Windows";
//SHParseDisplayName(pszName, 0, &pItemIDList, 0, 0);
//// then set the pidlroot value of your BROWSEINFO var
//bi.pidlRoot = pItemIDList;
if(defaultPath != L"")
{
TCHAR path[MAX_PATH];
wcscpy_s(path, MAX_PATH, defaultPath);
bi.lParam = (long)(LPCTSTR)path;
bi.lpfn = BrowseCallbackProc;
}
// Now show the dialog and get the itemIDList for the selected folder.
LPITEMIDLIST pIDL = ::SHBrowseForFolder(&bi);
if(pIDL == NULL)
return false;
// Now create a buffer to store the path, thne get it.
TCHAR buffer[_MAX_PATH];
if(::SHGetPathFromIDList(pIDL, buffer) == 0)
return false;
// Finally, set the string to the path, and return true.
folder = CString(buffer);
if(folder.Right(1) != _T("\\"))
{
folder += _T("\\");
}
return true;
}
// Highlights the line in the editor control
void Utilities::GoToLine(CString file)
{
int pos = Variables::IncludeExists(file);
if(pos == -1)
{
return;
}
int line = Variables::m_IncludeFiles.at(pos)->line;
if(line == -1)
{
return;
}
App* pApp = (App*)AfxGetApp();
ASSERT_VALID(pApp);
CDocTemplate* pTemplate = pApp->pDocTemplate;
ASSERT_VALID(pTemplate);
POSITION posDocument = pTemplate->GetFirstDocPosition();
while(posDocument != NULL)
{
CDocument* pDoc = pTemplate->GetNextDoc(posDocument);
ASSERT_VALID(pDoc);
if(pDoc->GetPathName() == file)
{
POSITION posView = pDoc->GetFirstViewPosition ();
View* pView = DYNAMIC_DOWNCAST (View, pDoc->GetNextView (posView));
ASSERT_VALID(pView);
if (pView != NULL)
{
pView->GoToLine(line);
pView->SetSourceFile(Variables::m_IncludeFiles.at(pos));
}
break;
}
}
}
// Returns the location of the db installation from the directory
CString Utilities::GetDBPLocation()
{
// Get DBP location
CString DBPLoc = _T("");
CBCGPRegistry* reg = new CBCGPRegistry(TRUE, KEY_ALL_ACCESS);
reg->Open(_T("SOFTWARE\\Dark Basic\\Dark Basic Pro"));
reg->Read(_T("INSTALL-PATH"), DBPLoc);
reg->Close();
delete reg;
if(DBPLoc != _T(""))
{
DBPLoc = DBPLoc + _T("\\");
}
return DBPLoc;
}
// Returns the processor count
int Utilities::GetProcessorCount()
{
SYSTEM_INFO si;
memset( &si, 0, sizeof(si));
GetSystemInfo( &si);
return si.dwNumberOfProcessors;
}
int Utilities::GetWindowsMajor()
{
OSVERSIONINFO osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
return osvi.dwMajorVersion;
}
// Returns the temporary path
CString Utilities::GetTemporaryPath()
{
if(Settings::TempLocation != L"" && Utilities::CheckAccess(Settings::TempLocation, O_RDWR))
{
return Settings::TempLocation;
}
else
{
TCHAR lpPathBuffer[MAX_PATH];
TCHAR lpLongPathBuffer[MAX_PATH];
GetTempPath(MAX_PATH, lpPathBuffer);
GetLongPathName(lpPathBuffer, lpLongPathBuffer, MAX_PATH);
return CString(lpLongPathBuffer);
}
}
// Returns the application path + name
CString Utilities::GetApplicationPath()
{
// Get the command line.
CString commandLine = GetCommandLine();
if(commandLine.GetLength() == 0)
return CString("");
// The first parameter is the application path. If this begins with quotation marks, then we
// get everything between that and the next set of quotation marks.
if(commandLine[0] == '\"')
{
int nPos = commandLine.Find(_T("\""), 1);
if(nPos != -1)
return commandLine.Mid(1, nPos - 1);
else
return commandLine.Mid(1, commandLine.GetLength()-1);
}
else
{
// The path is not in quotation marks, so it ends with a space.
int nPos = commandLine.Find(_T(" "), 1);
if(nPos != -1)
return commandLine.Mid(0, nPos - 1);
else
return commandLine;
}
}
// Checks to see whether a path has the permission requested
bool Utilities::CheckAccess(CString path, int accessType)
{
bool res = false;
if(Utilities::GetWindowsMajor() > 4)
{
// desired access flags can be set to whatever you define
int flags = accessType;
DWORD sdLen, dwAccessDesired = 0, dwPrivSetSize, dwAccessGranted;
PSECURITY_DESCRIPTOR fileSD;
GENERIC_MAPPING GenericMapping;
PRIVILEGE_SET PrivilegeSet;
BOOL fAccessGranted = FALSE;
HANDLE hToken, hTokenOne;
// Get the users token
if(OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &hTokenOne))
{
DuplicateTokenEx(hTokenOne, TOKEN_IMPERSONATE | TOKEN_READ | TOKEN_DUPLICATE, NULL, SecurityImpersonation, TokenImpersonation, &hToken);
if(ImpersonateLoggedOnUser(hToken))
{
// get file security descriptor - use null value first to get size
if (!GetFileSecurity(path, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, NULL, 0, &sdLen))
{
fileSD = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sdLen);
GetFileSecurity(path, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, fileSD, sdLen, &sdLen);
}
// initialize a GenericMapping structure based on required access
memset(&GenericMapping, 0x00, sizeof(GENERIC_MAPPING));
switch (flags & (O_RDONLY | O_RDWR | O_WRONLY))
{
case O_RDONLY:
dwAccessDesired = FILE_READ_DATA;
GenericMapping.GenericRead = FILE_GENERIC_READ;
break;
case O_RDWR:
dwAccessDesired = FILE_READ_DATA | FILE_WRITE_DATA;
GenericMapping.GenericAll = GENERIC_READ | GENERIC_WRITE;
break;
case O_WRONLY:
dwAccessDesired = FILE_WRITE_DATA;
GenericMapping.GenericWrite = FILE_GENERIC_WRITE;
break;
}
// Create a desired access mask
MapGenericMask(&dwAccessDesired, &GenericMapping);
// check the access
dwPrivSetSize = sizeof(PRIVILEGE_SET);
AccessCheck(fileSD, hToken, dwAccessDesired, &GenericMapping, &PrivilegeSet, &dwPrivSetSize, &dwAccessGranted, &fAccessGranted);
// Free heap
HeapFree(GetProcessHeap(), 0, fileSD);
if (fAccessGranted)
{
res = true;
}
else
{
CString error;
error.Format(L"Access denied, error: %d, requested: %lx\n", GetLastError(), dwAccessDesired);
}
}
else
{
CString error;
error.Format(L"Cannot impersonate, error: %d, requested: %lx\n", GetLastError(), dwAccessDesired);
AfxMessageBox(error);
}
// clean up resources
CloseHandle(hToken);
}
}
else
{
// Windows 95, 98, ME Failover
int test;
if(accessType == O_RDONLY)
{
test = 4;
}
else if(accessType == O_RDWR)
{
test = 6;
}
else
{
test = 2;
}
res = (_waccess_s(path, test) == 0);
}
return res;
}
// Capitalises the first letter of each word
CString Utilities::MixedCase(CString item)
{
CString loweritem = item.MakeLower();
item.MakeUpper();
CString newItem = _T("");
bool nextUpper = true;
for(int i=0; i<item.GetLength(); i++)
{
TCHAR ch = loweritem.GetAt(i);
if(nextUpper == true)
{
newItem += item.GetAt(i);
nextUpper = false;
}
else
{
newItem += ch;
}
if(ch == ' ')
{
nextUpper = true;
}
}
return newItem;
}
// Adds a byte to the checksum
void Utilities::add(BYTE value)
{
BYTE cipher = (value ^ (r >> 8));
r = (cipher + r) * c1 + c2;
sum += cipher;
}
// Adds a string to the checksum
void Utilities::AddToChecksum(const CString & s)
{
for(int i = 0; i < s.GetLength(); i++)
{
add((BYTE)s.GetAt(i));
}
}
// Initialises the checksum
void Utilities::InitChecksum()
{
sum = 0; r = 55665; c1 = 52845; c2 = 22719;
}
// Variables used by methods below
CString returnCode;
// Used by format method below
void AddText(CString line, int tabCount)
{
for(int b = 0; b < tabCount; b++)
{
returnCode += _T("\t");
}
returnCode += line + _T("\n");
}
// Formats the code nicely
CString Utilities::FormatCode(CString file)
{
int tabCount = 0;
bool delayed = false;
bool oneOff = false;
bool inCommentBlock = false;
CString code = _T("");
CStdioFile read;
read.Open(file, CFile::modeRead);
{
CString line;
while(read.ReadString(line))
{
if(delayed)
{
delayed = false;
tabCount++;
}
if(oneOff)
{
oneOff = false;
tabCount++;
}
line = line.Trim();
CString codeUpper = line;
codeUpper.MakeUpper();
if(codeUpper.Left(8) == _T("REMSTART"))
{
AddText(line, tabCount);
inCommentBlock = true;
continue;
}
else if(codeUpper.Left(6) == _T("REMEND"))
{
AddText(line, tabCount);
inCommentBlock = false;
continue;
}
if(inCommentBlock)
{
AddText(line, tabCount);
continue;
}
if(codeUpper.Left(3) == _T("REM"))
{
AddText(line, tabCount);
continue;
}
for(int i = 0; i <line.GetLength(); i++)
{
if(codeUpper.Mid(i, 5) == "ENDIF")
{
tabCount--;
i=i+5;
}
else if(codeUpper.Mid(i, 4) == "ELSE")
{
tabCount--;
oneOff = true;
i=i+4;
}
else if(codeUpper.Mid(i, 4) == "THEN")
{
delayed = false;
i=i+4;
}
else if(codeUpper.Mid(i, 5) == "NEXT ")
{
tabCount--;
i=i+5;
}
else if(codeUpper.Mid(i, 11) == "ENDFUNCTION")
{
tabCount--;
i=i+11;
}
if(codeUpper.Mid(i, 3) == "IF ")
{
i=i+3;
delayed = true;
}
else if(codeUpper.Mid(i, 4) == "FOR ")
{
i=i+4;
delayed = true;
}
else if(codeUpper.Mid(i, 8) == "FUNCTION ")
{
i=i+8;
delayed = true;
}
}
AddText(line, tabCount);
}
}
read.Close();
return returnCode;
}
| 21.075501
| 139
| 0.663036
|
domydev
|
88c99948f613446a465273d51fab13dbcb66ac31
| 3,092
|
hpp
|
C++
|
16th Study/src/expression/SArray.hpp
|
jongchae/CppTemplateStudy
|
976b9b8ef0bc899ccc5b7840d2e2f6bc2a9a3757
|
[
"MIT"
] | 84
|
2017-12-11T04:33:29.000Z
|
2022-03-27T07:27:06.000Z
|
16th Study/src/expression/SArray.hpp
|
jongchae/CppTemplateStudy
|
976b9b8ef0bc899ccc5b7840d2e2f6bc2a9a3757
|
[
"MIT"
] | 2
|
2018-04-05T14:26:56.000Z
|
2018-05-18T13:59:59.000Z
|
16th Study/src/expression/SArray.hpp
|
jongchae/CppTemplateStudy
|
976b9b8ef0bc899ccc5b7840d2e2f6bc2a9a3757
|
[
"MIT"
] | 25
|
2018-01-13T01:50:32.000Z
|
2021-05-01T11:05:13.000Z
|
#pragma once
#include <cassert>
#include <cstddef>
template <typename T>
class SArray
{
private:
T *data_;
size_t size_;
public:
/* ----------------------------------------------------------
CONSTRUCTORS
---------------------------------------------------------- */
// CAPACITY CONSTRUCTOR
explicit SArray(size_t size)
: data_(new T[size]),
size_(size)
{
init();
};
// COPY CONSTRUCTOR
template <typename X>
SArray(const SArray<X> &obj)
: data_(new T[size]),
size_(size)
{
copy(obj);
};
template <typename X>
SArray<T>& operator=(const SArray<X> &obj)
{
copy(obj);
return *this;
};
// DESTRUCTOR
~SArray()
{
delete[] data_;
};
protected:
void init()
{
for (size_t i = 0; i < size(); ++i)
data_[i] = T();
};
template <typename X>
void copy(SArray<X> &obj)
{
assert(size() == obj.size());
for (size_t i = 0; i < size(); ++i)
data_[i] = obj[i];
};
public:
/* ----------------------------------------------------------
ACCESSORS
---------------------------------------------------------- */
size_t size() const
{
return size_;
}
T& operator[](size_t index)
{
return data_[index];
};
const T& operator[](size_t index) const
{
return data_[index];
};
/* ----------------------------------------------------------
SELF OPERATORS
---------------------------------------------------------- */
template <typename X>
SArray<T>& operator+=(const SArray<X> &obj)
{
assert(size() == obj.size());
for (size_t i = 0; i < obj.size(); ++i)
data_[i] += obj[i];
return *this;
};
template <typename X>
SArray<T>& operator*=(const SArray<X> &obj)
{
assert(size() == obj.size());
for (size_t i = 0; i < obj.size(); ++i)
data_[i] *= obj[i];
return *this;
};
template <typename X>
SArray<T>& operator*=(const T &val)
{
for (size_t i = 0; i < a.size(); ++i)
data_[i] *= val;
return *this;
};
};
template <typename X, typename Y, typename Ret = decltype(X() + Y())>
SArray<Ret> operator+(const SArray<X> &x, SArray<Y> &y)
{
assert(x.size() == y.size());
SArray<Ret> ret(x.size());
for (size_t i = 0; i < x.size(); ++i)
ret[i] = x[i] + y[i];
return ret;
}
template <typename X, typename Y, typename Ret = decltype(X() * Y())>
SArray<Ret> operator*(const SArray<X> &x, SArray<Y> &y)
{
assert(x.size() == y.size());
SArray<Ret> ret(x.size());
for (size_t i = 0; i < x.size(); ++i)
ret[i] = x[i] * y[i];
return ret;
}
template <typename X, typename Y, typename Ret = decltype(X() * Y())>
SArray<Ret> operator*(const X &val, SArray<Y> &elems)
{
SArray<Ret> ret(elems.size());
for (size_t i = 0; i < elems.size(); ++i)
ret[i] = val * elems[i];
return ret;
}
| 21.929078
| 69
| 0.435964
|
jongchae
|
88d2473be06db9d59e558dc403d742be6fc61cd6
| 2,938
|
cpp
|
C++
|
tests/opencl/BlackScholes/oclBlackScholes_gold.cpp
|
siliconarts/vortex
|
93232f0e9416779e8a85b08f0a3a8182af30099e
|
[
"BSD-3-Clause"
] | 546
|
2020-08-17T12:01:13.000Z
|
2022-03-31T05:59:05.000Z
|
tests/opencl/BlackScholes/oclBlackScholes_gold.cpp
|
siliconarts/vortex
|
93232f0e9416779e8a85b08f0a3a8182af30099e
|
[
"BSD-3-Clause"
] | 34
|
2020-10-07T15:58:19.000Z
|
2022-03-29T07:40:50.000Z
|
tests/opencl/BlackScholes/oclBlackScholes_gold.cpp
|
siliconarts/vortex
|
93232f0e9416779e8a85b08f0a3a8182af30099e
|
[
"BSD-3-Clause"
] | 90
|
2020-09-30T23:02:21.000Z
|
2022-03-22T09:42:45.000Z
|
/*
* Copyright 1993-2010 NVIDIA Corporation. All rights reserved.
*
* Please refer to the NVIDIA end user license agreement (EULA) associated
* with this source code for terms and conditions that govern your use of
* this software. Any use, reproduction, disclosure, or distribution of
* this software and related documentation outside the terms of the EULA
* is strictly prohibited.
*
*/
#include <math.h>
#include "oclBlackScholes_common.h"
///////////////////////////////////////////////////////////////////////////////
// Rational approximation of cumulative normal distribution function
///////////////////////////////////////////////////////////////////////////////
static double CND(double d){
const double A1 = 0.31938153;
const double A2 = -0.356563782;
const double A3 = 1.781477937;
const double A4 = -1.821255978;
const double A5 = 1.330274429;
const double RSQRT2PI = 0.39894228040143267793994605993438;
double
K = 1.0 / (1.0 + 0.2316419 * fabs(d));
double
cnd = RSQRT2PI * exp(- 0.5 * d * d) *
(K * (A1 + K * (A2 + K * (A3 + K * (A4 + K * A5)))));
if(d > 0)
cnd = 1.0 - cnd;
return cnd;
}
///////////////////////////////////////////////////////////////////////////////
// Black-Scholes formula for both call and put
///////////////////////////////////////////////////////////////////////////////
static void BlackScholesBodyCPU(
float& call, //Call option price
float& put, //Put option price
float Sf, //Current stock price
float Xf, //Option strike price
float Tf, //Option years
float Rf, //Riskless rate of return
float Vf //Stock volatility
){
double S = Sf, X = Xf, T = Tf, R = Rf, V = Vf;
double sqrtT = sqrt(T);
double d1 = (log(S / X) + (R + 0.5 * V * V) * T) / (V * sqrtT);
double d2 = d1 - V * sqrtT;
double CNDD1 = CND(d1);
double CNDD2 = CND(d2);
//Calculate Call and Put simultaneously
double expRT = exp(- R * T);
call = (float)(S * CNDD1 - X * expRT * CNDD2);
put = (float)(X * expRT * (1.0 - CNDD2) - S * (1.0 - CNDD1));
}
////////////////////////////////////////////////////////////////////////////////
// Process an array of optN options
////////////////////////////////////////////////////////////////////////////////
extern "C" void BlackScholesCPU(
float *h_Call, //Call option price
float *h_Put, //Put option price
float *h_S, //Current stock price
float *h_X, //Option strike price
float *h_T, //Option years
float R, //Riskless rate of return
float V, //Stock volatility
unsigned int optionCount
){
for(unsigned int i = 0; i < optionCount; i++)
BlackScholesBodyCPU(
h_Call[i],
h_Put[i],
h_S[i],
h_X[i],
h_T[i],
R,
V
);
}
| 31.591398
| 80
| 0.487406
|
siliconarts
|
88d582ba82ca8fca92ed409d78c66eb510ac2bf7
| 374
|
cpp
|
C++
|
src/compression.cpp
|
BertrandKevin/Save-IMU-s-Data-Reach-RTK
|
5c58081c44e14fb864df39da43879e271baf3a16
|
[
"MIT"
] | null | null | null |
src/compression.cpp
|
BertrandKevin/Save-IMU-s-Data-Reach-RTK
|
5c58081c44e14fb864df39da43879e271baf3a16
|
[
"MIT"
] | null | null | null |
src/compression.cpp
|
BertrandKevin/Save-IMU-s-Data-Reach-RTK
|
5c58081c44e14fb864df39da43879e271baf3a16
|
[
"MIT"
] | 1
|
2019-02-28T02:22:52.000Z
|
2019-02-28T02:22:52.000Z
|
//
// compression.cpp
// Wifi-Client
//
// Created by Kevin Bertrand on 17/07/18.
// Copyright © 2018 KevinBertrand. All rights reserved.
//
#include <stdlib.h>
#include <string.h>
#include "../includes/getData.h"
#include "../includes/MPU9250.h"
using namespace std;
void compression(string path)
{
string action = "gzip " + path;
system(action.c_str());
}
| 17
| 56
| 0.668449
|
BertrandKevin
|
88d878c87839f70b6e026ab2db50355d42362a57
| 16,623
|
hpp
|
C++
|
src/packet_writer.hpp
|
epic-astronomy/bifrost
|
9bc7000ce1b42a55b70dff56a2e03253358ba8eb
|
[
"BSD-3-Clause"
] | 1
|
2021-05-05T16:20:57.000Z
|
2021-05-05T16:20:57.000Z
|
src/packet_writer.hpp
|
epic-astronomy/bifrost
|
9bc7000ce1b42a55b70dff56a2e03253358ba8eb
|
[
"BSD-3-Clause"
] | 6
|
2020-03-18T05:36:54.000Z
|
2021-12-16T17:34:09.000Z
|
src/packet_writer.hpp
|
epic-astronomy/bifrost
|
9bc7000ce1b42a55b70dff56a2e03253358ba8eb
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2019-2020, The Bifrost Authors. 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 Bifrost Authors 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 ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "assert.hpp"
#include <bifrost/io.h>
#include <bifrost/packet_writer.h>
#include "proclog.hpp"
#include "formats/formats.hpp"
#include "utils.hpp"
#include "hw_locality.hpp"
#include <arpa/inet.h> // For ntohs
#include <sys/socket.h> // For recvfrom
#include <queue>
#include <memory>
#include <stdexcept>
#include <cstdlib> // For posix_memalign
#include <cstring> // For memcpy, memset
#include <cstdint>
#include <sys/types.h>
#include <unistd.h>
#include <fstream>
class PacketWriterMethod {
protected:
int _fd;
public:
PacketWriterMethod(int fd)
: _fd(fd) {}
virtual ssize_t send_packets(char* hdrs,
int hdr_size,
char* data,
int data_size,
int npackets,
int flags=0) {
return 0;
}
virtual const char* get_name() { return "generic_writer"; }
};
class DiskPacketWriter : public PacketWriterMethod {
public:
DiskPacketWriter(int fd)
: PacketWriterMethod(fd) {}
ssize_t send_packets(char* hdrs,
int hdr_size,
char* data,
int data_size,
int npackets,
int flags=0) {
ssize_t status, nsent = 0;
for(int i=0; i<npackets; i++) {
status = ::write(_fd, hdrs+hdr_size*i, hdr_size);
if( status != hdr_size ) continue;
status = ::write(_fd, data+data_size*i, data_size);
if( status != data_size) continue;
nsent += 1;
}
return nsent;
}
inline const char* get_name() { return "disk_writer"; }
};
class UDPPacketSender : public PacketWriterMethod {
public:
UDPPacketSender(int fd)
: PacketWriterMethod(fd) {}
ssize_t send_packets(char* hdrs,
int hdr_size,
char* data,
int data_size,
int npackets,
int flags=0) {
struct mmsghdr *mmsg = NULL;
struct iovec *iovs = NULL;
mmsg = (struct mmsghdr *) malloc(sizeof(struct mmsghdr)*npackets);
iovs = (struct iovec *) malloc(sizeof(struct iovec)*2*npackets);
memset(mmsg, 0, sizeof(struct mmsghdr)*npackets);
for(int i=0; i<npackets; i++) {
mmsg[i].msg_hdr.msg_iov = &iovs[2*i];
mmsg[i].msg_hdr.msg_iovlen = 2;
iovs[2*i+0].iov_base = (hdrs + i*hdr_size);
iovs[2*i+0].iov_len = hdr_size;
iovs[2*i+1].iov_base = (data + i*data_size);
iovs[2*i+1].iov_len = data_size;
}
ssize_t nsent = ::sendmmsg(_fd, mmsg, npackets, flags);
/*
if( nsent == -1 ) {
std::cout << "sendmmsg failed: " << std::strerror(errno) << " with " << hdr_size << " and " << data_size << std::endl;
}
*/
free(mmsg);
free(iovs);
return nsent;
}
inline const char* get_name() { return "udp_transmit"; }
};
struct PacketStats {
size_t ninvalid;
size_t ninvalid_bytes;
size_t nlate;
size_t nlate_bytes;
size_t nvalid;
size_t nvalid_bytes;
};
class PacketWriterThread : public BoundThread {
private:
PacketWriterMethod* _method;
PacketStats _stats;
int _core;
public:
PacketWriterThread(PacketWriterMethod* method, int core=0)
: BoundThread(core), _method(method), _core(core) {
this->reset_stats();
}
inline ssize_t send(char* hdrs,
int hdr_size,
char* datas,
int data_size,
int npackets) {
ssize_t nsent = _method->send_packets(hdrs, hdr_size, datas, data_size, npackets);
if( nsent == -1 ) {
_stats.ninvalid += npackets;
_stats.ninvalid_bytes += npackets * (hdr_size + data_size);
} else {
_stats.nvalid += npackets;
_stats.nvalid_bytes += npackets * (hdr_size + data_size);
}
return nsent;
}
inline const char* get_name() { return _method->get_name(); }
inline const int get_core() { return _core; }
inline const PacketStats* get_stats() const { return &_stats; }
inline void reset_stats() {
::memset(&_stats, 0, sizeof(_stats));
}
};
class BFheaderinfo_impl {
PacketDesc _desc;
public:
inline BFheaderinfo_impl() {
::memset(&_desc, 0, sizeof(PacketDesc));
}
inline PacketDesc* get_description() { return &_desc; }
inline void set_nsrc(int nsrc) { _desc.nsrc = nsrc; }
inline void set_nchan(int nchan) { _desc.nchan = nchan; }
inline void set_chan0(int chan0) { _desc.chan0 = chan0; }
inline void set_tuning(int tuning) { _desc.tuning = tuning; }
inline void set_gain(uint16_t gain) { _desc.gain = gain; }
inline void set_decimation(uint16_t decimation) { _desc.decimation = decimation; }
};
class BFpacketwriter_impl {
protected:
std::string _name;
PacketWriterThread* _writer;
PacketHeaderFiller* _filler;
int _nsamples;
BFdtype _dtype;
ProcLog _bind_log;
ProcLog _stat_log;
pid_t _pid;
BFoffset _framecount;
private:
void update_stats_log() {
const PacketStats* stats = _writer->get_stats();
_stat_log.update() << "ngood_bytes : " << stats->nvalid_bytes << "\n"
<< "nmissing_bytes : " << stats->ninvalid_bytes << "\n"
<< "ninvalid : " << stats->ninvalid << "\n"
<< "ninvalid_bytes : " << stats->ninvalid_bytes << "\n"
<< "nlate : " << stats->nlate << "\n"
<< "nlate_bytes : " << stats->nlate_bytes << "\n"
<< "nvalid : " << stats->nvalid << "\n"
<< "nvalid_bytes : " << stats->nvalid_bytes << "\n";
}
public:
inline BFpacketwriter_impl(PacketWriterThread* writer,
PacketHeaderFiller* filler,
int nsamples,
BFdtype dtype)
: _name(writer->get_name()), _writer(writer), _filler(filler),
_nsamples(nsamples), _dtype(dtype),
_bind_log(_name+"/bind"),
_stat_log(_name+"/stats"),
_framecount(0) {
_bind_log.update() << "ncore : " << 1 << "\n"
<< "core0 : " << _writer->get_core() << "\n";
}
virtual ~BFpacketwriter_impl() {}
inline void reset_counter() { _framecount = 0; }
BFstatus send(BFheaderinfo info,
BFoffset seq,
BFoffset seq_increment,
BFoffset src,
BFoffset src_increment,
BFarray const* in);
};
class BFpacketwriter_generic_impl : public BFpacketwriter_impl {
ProcLog _type_log;
public:
inline BFpacketwriter_generic_impl(PacketWriterThread* writer,
int nsamples)
: BFpacketwriter_impl(writer, nullptr, nsamples, BF_DTYPE_U8),
_type_log((std::string(writer->get_name())+"/type").c_str()) {
_filler = new PacketHeaderFiller();
_type_log.update("type : %s\n", "generic");
}
};
class BFpacketwriter_chips_impl : public BFpacketwriter_impl {
ProcLog _type_log;
public:
inline BFpacketwriter_chips_impl(PacketWriterThread* writer,
int nsamples)
: BFpacketwriter_impl(writer, nullptr, nsamples, BF_DTYPE_CI4),
_type_log((std::string(writer->get_name())+"/type").c_str()) {
_filler = new CHIPSHeaderFiller();
_type_log.update("type : %s\n", "chips");
}
};
template<uint8_t B>
class BFpacketwriter_ibeam_impl : public BFpacketwriter_impl {
uint8_t _nbeam = B;
ProcLog _type_log;
public:
inline BFpacketwriter_ibeam_impl(PacketWriterThread* writer,
int nsamples)
: BFpacketwriter_impl(writer, nullptr, nsamples, BF_DTYPE_CF32),
_type_log((std::string(writer->get_name())+"/type").c_str()) {
_filler = new IBeamHeaderFiller<B>();
_type_log.update("type : %s%i\n", "ibeam", _nbeam);
}
};
template<uint8_t B>
class BFpacketwriter_pbeam_impl : public BFpacketwriter_impl {
uint8_t _nbeam = B;
ProcLog _type_log;
public:
inline BFpacketwriter_pbeam_impl(PacketWriterThread* writer,
int nsamples)
: BFpacketwriter_impl(writer, nullptr, nsamples, BF_DTYPE_F32),
_type_log((std::string(writer->get_name())+"/type").c_str()) {
_filler = new PBeamHeaderFiller<B>();
_type_log.update("type : %s%i\n", "pbeam", _nbeam);
}
};
class BFpacketwriter_cor_impl : public BFpacketwriter_impl {
ProcLog _type_log;
public:
inline BFpacketwriter_cor_impl(PacketWriterThread* writer,
int nsamples)
: BFpacketwriter_impl(writer, nullptr, nsamples, BF_DTYPE_CF32),
_type_log((std::string(writer->get_name())+"/type").c_str()) {
_filler = new CORHeaderFiller();
_type_log.update("type : %s\n", "cor");
}
};
class BFpacketwriter_tbn_impl : public BFpacketwriter_impl {
ProcLog _type_log;
public:
inline BFpacketwriter_tbn_impl(PacketWriterThread* writer,
int nsamples)
: BFpacketwriter_impl(writer, nullptr, nsamples, BF_DTYPE_CI8),
_type_log((std::string(writer->get_name())+"/type").c_str()) {
_filler = new TBNHeaderFiller();
_type_log.update("type : %s\n", "tbn");
}
};
class BFpacketwriter_drx_impl : public BFpacketwriter_impl {
ProcLog _type_log;
public:
inline BFpacketwriter_drx_impl(PacketWriterThread* writer,
int nsamples)
: BFpacketwriter_impl(writer, nullptr, nsamples, BF_DTYPE_CI4),
_type_log((std::string(writer->get_name())+"/type").c_str()) {
_filler = new DRXHeaderFiller();
_type_log.update("type : %s\n", "drx");
}
};
class BFpacketwriter_tbf_impl : public BFpacketwriter_impl {
ProcLog _type_log;
public:
inline BFpacketwriter_tbf_impl(PacketWriterThread* writer,
int nsamples)
: BFpacketwriter_impl(writer, nullptr, nsamples, BF_DTYPE_CI4),
_type_log((std::string(writer->get_name())+"/type").c_str()) {
_filler = new TBFHeaderFiller();
_type_log.update("type : %s\n", "tbf");
}
};
BFstatus BFpacketwriter_create(BFpacketwriter* obj,
const char* format,
int fd,
int core,
BFiomethod backend) {
BF_ASSERT(obj, BF_STATUS_INVALID_POINTER);
int nsamples = 0;
if(std::string(format).substr(0, 8) == std::string("generic_") ) {
nsamples = std::atoi((std::string(format).substr(8, std::string(format).length())).c_str());
} else if( std::string(format).substr(0, 6) == std::string("chips_") ) {
int nchan = std::atoi((std::string(format).substr(6, std::string(format).length())).c_str());
nsamples = 32*nchan;
} else if( std::string(format).substr(0, 5) == std::string("ibeam") ) {
int nbeam = std::stoi(std::string(format).substr(5, 1));
int nchan = std::atoi((std::string(format).substr(7, std::string(format).length())).c_str());
nsamples = 2*nbeam*nchan;
} else if( std::string(format).substr(0, 5) == std::string("pbeam") ) {
int nchan = std::atoi((std::string(format).substr(7, std::string(format).length())).c_str());
nsamples = 4*nchan;
} else if(std::string(format).substr(0, 4) == std::string("cor_") ) {
int nchan = std::atoi((std::string(format).substr(4, std::string(format).length())).c_str());
nsamples = 4*nchan;
} else if( format == std::string("tbn") ) {
nsamples = 512;
} else if( format == std::string("drx") ) {
nsamples = 4096;
} else if( format == std::string("tbf") ) {
nsamples = 6144;
}
PacketWriterMethod* method;
if( backend == BF_IO_DISK ) {
method = new DiskPacketWriter(fd);
} else if( backend == BF_IO_UDP ) {
method = new UDPPacketSender(fd);
} else {
return BF_STATUS_UNSUPPORTED;
}
PacketWriterThread* writer = new PacketWriterThread(method, core);
if( std::string(format).substr(0, 8) == std::string("generic_") ) {
BF_TRY_RETURN_ELSE(*obj = new BFpacketwriter_generic_impl(writer, nsamples),
*obj = 0);
} else if( std::string(format).substr(0, 6) == std::string("chips_") ) {
BF_TRY_RETURN_ELSE(*obj = new BFpacketwriter_chips_impl(writer, nsamples),
*obj = 0);
#define MATCH_IBEAM_MODE(NBEAM) \
} else if( std::string(format).substr(0, 7) == std::string("ibeam"#NBEAM"_") ) { \
BF_TRY_RETURN_ELSE(*obj = new BFpacketwriter_ibeam_impl<NBEAM>(writer, nsamples), \
*obj = 0);
MATCH_IBEAM_MODE(2)
MATCH_IBEAM_MODE(3)
MATCH_IBEAM_MODE(4)
#undef MATCH_IBEAM_MODE
#define MATCH_PBEAM_MODE(NBEAM) \
} else if( std::string(format).substr(0, 7) == std::string("pbeam"#NBEAM"_") ) { \
BF_TRY_RETURN_ELSE(*obj = new BFpacketwriter_pbeam_impl<NBEAM>(writer, nsamples), \
*obj = 0);
MATCH_PBEAM_MODE(1)
#undef MATCH_PBEAM_MODE
} else if( std::string(format).substr(0, 4) == std::string("cor_") ) {
BF_TRY_RETURN_ELSE(*obj = new BFpacketwriter_cor_impl(writer, nsamples),
*obj = 0);
} else if( format == std::string("tbn") ) {
BF_TRY_RETURN_ELSE(*obj = new BFpacketwriter_tbn_impl(writer, nsamples),
*obj = 0);
} else if( format == std::string("drx") ) {
BF_TRY_RETURN_ELSE(*obj = new BFpacketwriter_drx_impl(writer, nsamples),
*obj = 0);
} else if( format == std::string("tbf") ) {
BF_TRY_RETURN_ELSE(*obj = new BFpacketwriter_tbf_impl(writer, nsamples),
*obj = 0);
} else {
return BF_STATUS_UNSUPPORTED;
}
}
| 40.152174
| 130
| 0.565843
|
epic-astronomy
|
88dbe01ae5e44619dc66952d334d9b42802521b7
| 10,668
|
cpp
|
C++
|
source/Components/LogicComponent.cpp
|
dom380/IMAT3606-Coursework-2
|
36f50b25823cd3170a403a2e2ef50e3019fcd73b
|
[
"FTL",
"Zlib",
"Apache-2.0",
"MIT"
] | null | null | null |
source/Components/LogicComponent.cpp
|
dom380/IMAT3606-Coursework-2
|
36f50b25823cd3170a403a2e2ef50e3019fcd73b
|
[
"FTL",
"Zlib",
"Apache-2.0",
"MIT"
] | null | null | null |
source/Components/LogicComponent.cpp
|
dom380/IMAT3606-Coursework-2
|
36f50b25823cd3170a403a2e2ef50e3019fcd73b
|
[
"FTL",
"Zlib",
"Apache-2.0",
"MIT"
] | null | null | null |
#include "Components\LogicComponent.h"
#include <Scripting\ScriptEngine.h>
#include <utils/Utilities.h>
LogicComponent::LogicComponent() : Component(ComponentType::LOGIC), updateFunc(luaState), recieveMsgFunc(luaState), params(luaState)
{
}
LogicComponent::LogicComponent(std::weak_ptr<GameObject> owner, std::weak_ptr<GameScreen> screen, const char* scriptFile) : Component(ComponentType::LOGIC), updateFunc(luaState), recieveMsgFunc(luaState), params(luaState)
{
this->owner = owner;
this->screen = screen;
script = scriptFile;
auto splitPath = Utilities::splitFilePath(script);
scriptName = Utilities::removeExtension(splitPath.at(splitPath.size() - 1));
registerLuaBindings();
}
LogicComponent::LogicComponent(std::weak_ptr<GameObject> owner, std::weak_ptr<GameScreen> screen, std::string scriptFile) :
LogicComponent(owner, screen, scriptFile.c_str())
{
//Just a delegation constructor
}
LogicComponent::LogicComponent(std::weak_ptr<GameObject> owner, std::weak_ptr<GameScreen> screen, std::string scriptFile, luabridge::LuaRef params) : Component(ComponentType::LOGIC), updateFunc(luaState), recieveMsgFunc(luaState), params(luaState)
{
this->owner = owner;
this->screen = screen;
this->params = params;
script = scriptFile.c_str();
auto splitPath = Utilities::splitFilePath(script);
scriptName = Utilities::removeExtension(splitPath.at(splitPath.size() - 1));
registerLuaBindings();
}
LogicComponent::LogicComponent(std::weak_ptr<GameObject> owner, std::weak_ptr<GameScreen> screen) : Component(ComponentType::LOGIC), updateFunc(luaState), recieveMsgFunc(luaState), params(luaState)
{
this->owner = owner;
this->screen = screen;
}
LogicComponent::~LogicComponent()
{
}
void LogicComponent::update(double dt)
{
try
{
if (updateFunc.isFunction())
{
updateFunc(this, dt, params);
}
}
catch (luabridge::LuaException e)
{
//Todo - better error handling here
std::cout << e.what() << std::endl;
throw std::runtime_error(e.what());
}
}
void LogicComponent::RecieveMessage(Message * msg)
{
switch (msg->id)
{
case MsgType::LOCATION: //Notified of player location
{
LocationMessage* locationMsg = ((LocationMessage *)msg);
try
{
if (recieveMsgFunc.isFunction())
{
recieveMsgFunc(this, locationMsg, "LOCATION", params); //TODO - Lua doesn't support enums so find better way of translating to scripts
}
}
catch (luabridge::LuaException e)
{
//Todo - better error handling here
std::cout << e.what() << std::endl;
throw std::runtime_error(e.what());
}
}
break;
case MsgType::COLLISION:
{
CollisionMessage* collisionMsg = ((CollisionMessage *)msg);
try
{
if (recieveMsgFunc.isFunction())
{
recieveMsgFunc(this, collisionMsg, "COLLISION", params); //TODO - Lua doesn't support enums so find better way of translating to scripts
}
}
catch (luabridge::LuaException e)
{
//Todo - better error handling here
std::cout << e.what() << std::endl;
throw std::runtime_error(e.what());
}
}
break;
default:
break;
}
}
void LogicComponent::setOwner(std::weak_ptr<GameObject> passedOwner)
{
owner = passedOwner;
}
void LogicComponent::setScreen(std::weak_ptr<GameScreen> passedScreen)
{
screen = passedScreen;
}
luabridge::LuaRef LogicComponent::getParams()
{
return params;
}
string LogicComponent::getScriptName()
{
return scriptName;
}
void LogicComponent::setScriptName(string passedName)
{
scriptName = passedName;
}
void LogicComponent::setScriptFullPath(const char* scriptFullName)
{
script = scriptFullName;
}
void LogicComponent::registerLuaBindings()
{
auto scriptEngine = ScriptEngine::getInstance();
scriptEngine->loadScript(script, scriptName);
updateFunc = scriptEngine->getFunction(scriptName, "update");
recieveMsgFunc = scriptEngine->getFunction(scriptName, "RecieveMessage");
}
void LogicComponent::applyTransform(glm::vec3 position, float scale, glm::quat orientation)
{
std::shared_ptr<GameScreen> sp_Screen = screen.lock(); //Access GameScreen
auto sp_Owner = owner.lock(); //Access GameObject that owns this component
if (sp_Owner != nullptr && sp_Screen != nullptr) //If it still exists
{
Handle comp = sp_Owner->GetComponentHandle (ComponentType::TRANSFORM);
Transform* transformPtr = nullptr;
if (!comp.isNull()) //If the GameObject has a transform component, update it's transform.
{
transformPtr = sp_Screen->getComponentStore()->getComponent<Transform>(comp, ComponentType::TRANSFORM);
transformPtr->position = position;
transformPtr->scale *= scale;
transformPtr->orientation = orientation;
}
comp = sp_Owner->GetComponentHandle(ComponentType::RIGID_BODY);
if (!comp.isNull()) //If the GameObject also has a physics component, update it's transform.
{
auto physicsPtr = sp_Screen->getComponentStore()->getComponent<PhysicsComponent>(comp, ComponentType::RIGID_BODY);
if(transformPtr != nullptr)
physicsPtr->setTransform(transformPtr);
}
comp = sp_Owner->GetComponentHandle(ComponentType::CONTROLLER);
if (!comp.isNull()) //If the GameObject has a controller, update it's transform.
{
auto controllerPtr = sp_Screen->getComponentStore()->getComponent<ControllerComponent>(comp, ComponentType::CONTROLLER);
if (controllerPtr != nullptr)
controllerPtr->setTransform(transformPtr);
}
comp = sp_Owner->GetComponentHandle(ComponentType::TRIGGER);
if (!comp.isNull()) //If the GameObject has a controller, update it's transform.
{
auto triggerPtr = sp_Screen->getComponentStore()->getComponent<CollisionTrigger>(comp, ComponentType::TRIGGER);
if (triggerPtr != nullptr)
triggerPtr->setTransform(*transformPtr);
}
}
}
void LogicComponent::resetTransform()
{
std::shared_ptr<GameScreen> sp_Screen = screen.lock(); //Access GameScreen
auto sp_Owner = owner.lock(); //Access GameObject that owns this component
if (sp_Owner != nullptr && sp_Screen != nullptr) //If it still exists
{
Handle comp = sp_Owner->GetComponentHandle(ComponentType::TRANSFORM);
Transform* transformPtr = nullptr;
if (!comp.isNull()) //If the GameObject has a transform component, update it's transform.
{
transformPtr = sp_Screen->getComponentStore()->getComponent<Transform>(comp, ComponentType::TRANSFORM);
transformPtr->position = transformPtr->getOriginalPos();
transformPtr->orientation = transformPtr->getOrigianlOrient();
}
comp = sp_Owner->GetComponentHandle(ComponentType::RIGID_BODY);
if (!comp.isNull()) //If the GameObject also has a physics component, update it's transform.
{
auto physicsPtr = sp_Screen->getComponentStore()->getComponent<PhysicsComponent>(comp, ComponentType::RIGID_BODY);
if (transformPtr != nullptr)
{
physicsPtr->setTransform(transformPtr);
}
}
comp = sp_Owner->GetComponentHandle(ComponentType::CONTROLLER);
if (!comp.isNull()) //If the GameObject has a controller, update it's transform.
{
auto controllerPtr = sp_Screen->getComponentStore()->getComponent<ControllerComponent>(comp, ComponentType::CONTROLLER);
if (controllerPtr != nullptr)
controllerPtr->setTransform(transformPtr);
}
comp = sp_Owner->GetComponentHandle(ComponentType::TRIGGER);
if (!comp.isNull()) //If the GameObject has a controller, update it's transform.
{
auto triggerPtr = sp_Screen->getComponentStore()->getComponent<CollisionTrigger>(comp, ComponentType::TRIGGER);
if (triggerPtr != nullptr)
triggerPtr->setTransform(*transformPtr);
}
}
}
void LogicComponent::toggleRender()
{
auto sp_Owner = owner.lock();
auto sp_Screen = screen.lock();
if (sp_Owner != nullptr && sp_Screen != nullptr)
{
auto modelComp = sp_Owner->GetComponentHandle(ComponentType::MODEL);
if (!modelComp.isNull())
{
ModelComponent* model = sp_Screen->getComponentStore()->getComponent<ModelComponent>(modelComp, ComponentType::MODEL);
if (model->isDrawing()) //Tell GameObject's model to stop rendering if it exists and hasn't already been collected
{
model->toggleDrawing();
}
}
}
}
void LogicComponent::updateScore(int incValue, string idToUpdate)
{
auto sp_Screen = screen.lock();
if (sp_Screen != nullptr)
{
sp_Screen->updateScore(incValue, idToUpdate);
}
}
int LogicComponent::getUIValueInt(string id)
{
auto sp_Screen = screen.lock();
if (sp_Screen)
return sp_Screen->getTextValueInt(id);
else
return -1;
}
bool LogicComponent::isRendering()
{
auto sp_Owner = owner.lock();
auto sp_Screen = screen.lock();
if (sp_Owner != nullptr && sp_Screen != nullptr)
{
auto modelComp = sp_Owner->GetComponentHandle(ComponentType::MODEL);
if (!modelComp.isNull())
{
ModelComponent* model = sp_Screen->getComponentStore()->getComponent<ModelComponent>(modelComp, ComponentType::MODEL);
return model->isDrawing();
}
return false;
}
else
{
return false;
}
}
glm::vec3 LogicComponent::getPosition()
{
std::shared_ptr<GameScreen> sp_Screen = screen.lock(); //Access GameScreen
auto sp_Owner = owner.lock(); //Access GameObject that owns this component
if (sp_Owner != nullptr && sp_Screen != nullptr) //If it still exists
{
Handle comp = sp_Owner->GetComponentHandle(ComponentType::TRANSFORM);
if (!comp.isNull()) //If the GameObject has a transform component, update it's orientation.
{
auto transform = sp_Screen->getComponentStore()->getComponent<Transform>(comp, ComponentType::TRANSFORM);
return transform->position;
}
return vec3();
}
else
{
return vec3();
}
}
glm::vec3 LogicComponent::vec3Addition(glm::vec3 v1, glm::vec3 v2)
{
return v1 + v2;
}
glm::vec3 LogicComponent::vec3Subtract(glm::vec3 v1, glm::vec3 v2)
{
return v1 - v2;
}
glm::vec3 LogicComponent::vec3Normalise(glm::vec3 v1)
{
return glm::normalize(v1);
}
float LogicComponent::getDistance(glm::vec3 v1, glm::vec3 v2)
{
return glm::distance(v1, v2);
}
glm::quat LogicComponent::angleAxis(float angle, glm::vec3 axis)
{
return glm::angleAxis(glm::radians(angle), axis);
}
glm::quat LogicComponent::getOrientation()
{
std::shared_ptr<GameScreen> sp_Screen = screen.lock(); //Access GameScreen
auto sp_Owner = owner.lock(); //Access GameObject that owns this component
if (sp_Owner != nullptr && sp_Screen != nullptr) //If it still exists
{
Handle comp = sp_Owner->GetComponentHandle(ComponentType::TRANSFORM);
if (!comp.isNull()) //If the GameObject has a transform component, update it's orientation.
{
auto transform = sp_Screen->getComponentStore()->getComponent<Transform>(comp, ComponentType::TRANSFORM);
return transform->orientation;
}
return glm::quat();
}
else
{
return glm::quat();
}
}
glm::quat LogicComponent::quatMultiply(glm::quat q1, glm::quat q2)
{
return q1 * q2;
}
| 30.135593
| 247
| 0.729565
|
dom380
|
88e0d00077ed9bea403773f2105b6424c60ac46f
| 78
|
cxx
|
C++
|
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_matrix_fixed+double.3.6-.cxx
|
rdsouza10/ITK
|
07cb23f9866768b5f4ee48ebec8766b6e19efc69
|
[
"Apache-2.0"
] | 3
|
2019-11-19T09:47:25.000Z
|
2022-02-24T00:32:31.000Z
|
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_matrix_fixed+double.3.6-.cxx
|
rdsouza10/ITK
|
07cb23f9866768b5f4ee48ebec8766b6e19efc69
|
[
"Apache-2.0"
] | 1
|
2019-03-18T14:19:49.000Z
|
2020-01-11T13:54:33.000Z
|
Modules/ThirdParty/VNL/src/vxl/core/vnl/Templates/vnl_matrix_fixed+double.3.6-.cxx
|
rdsouza10/ITK
|
07cb23f9866768b5f4ee48ebec8766b6e19efc69
|
[
"Apache-2.0"
] | 1
|
2022-02-24T00:32:36.000Z
|
2022-02-24T00:32:36.000Z
|
#include <vnl/vnl_matrix_fixed.hxx>
VNL_MATRIX_FIXED_INSTANTIATE(double,3,6);
| 26
| 41
| 0.833333
|
rdsouza10
|
88e5cc61591e7f785b36d6e6adc0f3bf9be2d790
| 1,303
|
cpp
|
C++
|
test/realsense/open_cam.cpp
|
ashikari/MarbleFlow
|
10d054f1b84ba06c373cde2e759cc4917e765f4e
|
[
"Unlicense"
] | null | null | null |
test/realsense/open_cam.cpp
|
ashikari/MarbleFlow
|
10d054f1b84ba06c373cde2e759cc4917e765f4e
|
[
"Unlicense"
] | null | null | null |
test/realsense/open_cam.cpp
|
ashikari/MarbleFlow
|
10d054f1b84ba06c373cde2e759cc4917e765f4e
|
[
"Unlicense"
] | null | null | null |
#include <opencv2/opencv.hpp>
#include <iostream>
#include <librealsense2/rs.hpp>
using namespace cv;
using namespace rs2;
int main()
{
//Contruct a pipeline which abstracts the device
rs2::pipeline pipe;
//Create a configuration for configuring the pipeline with a non default profile
rs2::config cfg;
//Add desired streams to configuration
cfg.enable_stream(RS2_STREAM_COLOR, 640, 480, RS2_FORMAT_BGR8, 30);
//Instruct pipeline to start streaming with the requested configuration
pipe.start(cfg);
// Camera warmup - dropping several first frames to let auto-exposure stabilize
rs2::frameset frames;
for(int i = 0; i < 30; i++)
{
//Wait for all configured streams to produce a frame
frames = pipe.wait_for_frames();
}
namedWindow("Display Image", WINDOW_AUTOSIZE );
while(true){
//Get each frame
frames = pipe.wait_for_frames();
rs2::frame color_frame = frames.get_color_frame();
// Creating OpenCV Matrix from a color image
cv::Mat color(cv::Size(640, 480), CV_8UC3, (void*)color_frame.get_data(), cv::Mat::AUTO_STEP);
// Display in a GUI
imshow("Display Image", color);
if (waitKey(33)>0){
break;
}
}
destroyWindow("Display Image");
return 0;
}
| 23.690909
| 99
| 0.665388
|
ashikari
|
88ef553bea2e7e40094c8b58a1c7078585e51bf2
| 687
|
cpp
|
C++
|
.LHP/.Lop11/.HSG/.T.Hung/Week 1/11136/11136/11136.cpp
|
sxweetlollipop2912/MaCode
|
661d77a2096e4d772fda2b6a7f80c84113b2cde9
|
[
"MIT"
] | null | null | null |
.LHP/.Lop11/.HSG/.T.Hung/Week 1/11136/11136/11136.cpp
|
sxweetlollipop2912/MaCode
|
661d77a2096e4d772fda2b6a7f80c84113b2cde9
|
[
"MIT"
] | null | null | null |
.LHP/.Lop11/.HSG/.T.Hung/Week 1/11136/11136/11136.cpp
|
sxweetlollipop2912/MaCode
|
661d77a2096e4d772fda2b6a7f80c84113b2cde9
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <set>
#define maxN 1000001
typedef long maxn;
typedef long long maxa;
typedef std::multiset <maxa> mset_t;
maxn day;
maxa res;
mset_t set;
void Process() {
res = 0;
set.clear();
while (day--) {
maxn n; std::cin >> n;
maxa a;
while (n--) std::cin >> a, set.insert(a);
mset_t::iterator st = set.begin(), en = set.end(); --en;
res += *en - *st;
set.erase(en); set.erase(st);
}
std::cout << res << '\n';
}
int main() {
//freopen("11136.inp", "r", stdin);
//freopen("11136.out", "w", stdout);
std::ios_base::sync_with_stdio(0);
std::cin.tie(0);
while (std::cin >> day && day)
Process();
}
| 15.976744
| 58
| 0.596798
|
sxweetlollipop2912
|
88ef70f2e6d9697c9556f5025e9ed811d15e281e
| 14,814
|
cpp
|
C++
|
examples/clientserver1/client3WAny.cpp
|
JohanVanslembrouck/corolib
|
0ebbabfe368c29901bf96ae1d3b6e989e3ff82c9
|
[
"MIT"
] | 1
|
2021-08-19T13:49:01.000Z
|
2021-08-19T13:49:01.000Z
|
examples/clientserver1/client3WAny.cpp
|
JohanVanslembrouck/corolib
|
0ebbabfe368c29901bf96ae1d3b6e989e3ff82c9
|
[
"MIT"
] | null | null | null |
examples/clientserver1/client3WAny.cpp
|
JohanVanslembrouck/corolib
|
0ebbabfe368c29901bf96ae1d3b6e989e3ff82c9
|
[
"MIT"
] | null | null | null |
/**
* @file client3WAny.cpp
* @brief
* This example illustrates the use of coroutines
* in combination with Boost ASIO to implement CommClient.
* This example uses 3 CommClient1 objects.
* It also uses a wait_any_awaitable type that allows awaiting the completion of 1 of N asychronous operations.
*
* @author Johan Vanslembrouck (johan.vanslembrouck@altran.com, johan.vanslembrouck@gmail.com)
*/
#include "corolib/print.h"
#include "corolib/async_task.h"
#include "corolib/async_operation.h"
#include "corolib/wait_any_awaitable.h"
#include "corolib/commclient.h"
#include "endpoints.h"
using namespace corolib;
async_task<int> mainflowWA0(CommClient& c1, CommClient& c2, CommClient& c3)
{
print(PRI1, "mainflowWA0: begin\n");
int counter = 0;
for (int i = 0; i < 40; i++)
{
print(PRI1, "mainflowWA0: %d ------------------------------------------------------------------\n", i);
// Connecting
print(PRI1, "mainflowWA0: async_operation<void> sc1 = c1.start_connecting();\n");
async_operation<void> sc1 = c1.start_connecting();
print(PRI1, "mainflowWA0: async_operation<void> sc2 = c2.start_connecting();\n");
async_operation<void> sc2 = c2.start_connecting();
print(PRI1, "mainflowWA0: async_operation<void> sc3 = c3.start_connecting();\n");
async_operation<void> sc3 = c3.start_connecting();
print(PRI1, "mainflowWA0: wait_any_awaitable<async_operation<void>> wac( { &sc1, &sc2, &sc3 } );\n");
wait_any_awaitable<async_operation<void>> wac( { &sc1, &sc2, &sc3 } );
for (int i = 0; i < 3; i++) {
print(PRI1, "mainflowWA0: co_await wac;\n");
co_await wac;
print(PRI1, "mainflowWA0: wac %d completed\n", i);
}
// Writing
std::string str1 = "This is string ";
str1 += std::to_string(counter++);
str1 += " to echo\n";
std::string str2 = "This is string ";
str2 += std::to_string(counter++);
str2 += " to echo\n";
std::string str3 = "This is string ";
str3 += std::to_string(counter++);
str3 += " to echo\n";
print(PRI1, "mainflowWA0: async_operation<void> sw1 = c1.start_writing(...);\n");
async_operation<void> sw1 = c1.start_writing(str1.c_str(), str1.length() + 1);
print(PRI1, "mainflowWA0: async_operation<void> sw2 = c2.start_writing(...);\n");
async_operation<void> sw2 = c2.start_writing(str2.c_str(), str2.length() + 1);
print(PRI1, "mainflowWA0: async_operation<void> sw3 = c3.start_writing(...);\n");
async_operation<void> sw3 = c3.start_writing(str3.c_str(), str3.length() + 1);
print(PRI1, "mainflowWA0: wait_all_awaitable<async_operation<void>> waw( { &sw1, &sw2, &sw3 } );\n");
wait_any_awaitable<async_operation<void>> waw( { &sw1, &sw2, &sw3 } );
for (int i = 0; i < 3; i++) {
print(PRI1, "mainflowWA0: int r = co_await waw;\n");
int r = co_await waw;
print(PRI1, "mainflowWA0: waw %d completed\n", r);
}
// Reading
print(PRI1, "mainflowWA0: async_operation<std::string> sr1 = c1.start_reading();\n");
async_operation<std::string> sr1 = c1.start_reading();
print(PRI1, "mainflowWA0: async_operation<std::string> sr2 = c2.start_reading();\n");
async_operation<std::string> sr2 = c2.start_reading();
print(PRI1, "mainflowWA0: async_operation<std::string> sr3 = c3.start_reading();\n");
async_operation<std::string> sr3 = c3.start_reading();
print(PRI1, "mainflowWA0: wait_any_awaitable<async_operation<std::string>> war( { &sr1, &sr2, &sr3 } ) ;\n");
wait_any_awaitable<async_operation<std::string>> war( { &sr1, &sr2, &sr3 } );
for (int i = 0; i < 3; i++) {
print(PRI1, "mainflowWA0: int r = co_await war;\n");
int r = co_await war;
print(PRI1, "mainflowWA0: war %d completed\n", r);
}
print(PRI1, "sr1.get_result() = %s", sr1.get_result().c_str());
print(PRI1, "sr2.get_result() = %s", sr2.get_result().c_str());
print(PRI1, "sr3.get_result() = %s", sr3.get_result().c_str());
// Closing
print(PRI1, "mainflowWA0: c1.stop();\n");
c1.stop();
print(PRI1, "mainflowWA0: c2.stop();\n");
c2.stop();
print(PRI1, "mainflowWA0: c3.stop();\n");
c3.stop();
print(PRI1, "mainflowWA0: std::this_thread::sleep_for(std::chrono::seconds(1))\n");
std::this_thread::sleep_for(std::chrono::seconds(1));
}
print(PRI1, "mainflowWA0: co_return 0;\n");
co_return 0;
}
async_task<int> mainflowWA1(std::initializer_list<CommClient*> clients)
{
print(PRI1, "mainflowWA1: begin\n");
const int nrClients = 3; //clients.size();
async_operation<void> asyncsc[nrClients];
async_operation<void> asyncsw[nrClients];
async_operation<std::string> asyncsr[nrClients];
std::string results[nrClients];
std::string str[nrClients];
int counter = 0;
for (int i = 0; i < 40; i++)
{
print(PRI1, "mainflowWA1: %d ------------------------------------------------------------------\n", i);
int j;
// Connecting
j = 0;
for (CommClient* cl : clients) {
print(PRI1, "mainflowWA1: asyncsc[%d] = cl->start_connecting();\n", j);
asyncsc[j++] = cl->start_connecting();
}
print(PRI1, "mainflowWA1: wait_any_awaitable<async_operation<void>> wac(asyncsc, nrClients)\n");
wait_any_awaitable<async_operation<void>> wac(asyncsc, nrClients);
for (int i = 0; i < nrClients; i++) {
print(PRI1, "mainflowWA1: int r = co_await wac;\n");
int r = co_await wac;
print(PRI1, "mainflowWA1: wac %d completed\n", r);
}
// Writing
j = 0;
for (CommClient* cl : clients) {
print(PRI1, "mainflowWA1: asyncsw[%d] = cl->start_writing(...);\n", j);
str[j] = "This is string ";
str[j] += std::to_string(counter++);
str[j] += " to echo\n";
asyncsw[j] = cl->start_writing(str[j].c_str(), str[j].length() + 1);
j++;
}
print(PRI1, "mainflowWA1: wait_any_awaitable<async_operation<void>> waw(asyncsw, 3)\n");
wait_any_awaitable<async_operation<void>> waw(asyncsw, 3);
for (int i = 0; i < nrClients; i++) {
print(PRI1, "mainflowWA1: int r = co_await waw;\n");
int r = co_await waw;
print(PRI1, "mainflowWA1: waw %d completed\n", r);
}
// Reading
j = 0;
for (CommClient* cl : clients) {
print(PRI1, "mainflowWA1: asyncsr[%d] = cl->start_reading();\n", j);
asyncsr[j++] = cl->start_reading();
}
print(PRI1, "mainflowWA1: wait_any_awaitable<async_operation<std::string>> war(asyncsr, 3)\n");
wait_any_awaitable<async_operation<std::string>> war(asyncsr, nrClients);
for (int i = 0; i < nrClients; i++) {
print(PRI1, "mainflowWA1: int r = co_await war;\n");
int r = co_await war;
print(PRI1, "mainflowWA1: war %d completed\n", r);
}
for (int i = 0; i < nrClients; i++) {
print(PRI1, "asyncsr[%d].get_result() = %s", i, asyncsr[i].get_result().c_str());
}
// Closing
for (CommClient* cl : clients) {
print(PRI1, "mainflowWA1: cl->stop();\n");
cl->stop();
}
print(PRI1, "mainflowWA1: std::this_thread::sleep_for(std::chrono::seconds(1))\n");
std::this_thread::sleep_for(std::chrono::seconds(1));
}
print(PRI1, "mainflowWA1: co_return 0;\n");
co_return 0;
}
async_task<int> mainflowWA2(std::initializer_list<CommClient*> clients)
{
print(PRI1, "mainflowWA2: begin\n");
const int nrClients = 3; // clients.size();
int counter = 0;
for (int i = 0; i < 40; i++)
{
print(PRI1, "mainflowWA2: %d ------------------------------------------------------------------\n", i);
async_operation<void> asyncsc[nrClients];
async_operation<void> asyncsw[nrClients];
async_operation<std::string> asyncsr[3];
std::string str[nrClients];
std::string results[nrClients];
int j;
// Connecting
j = 0;
for (CommClient* cl : clients) {
print(PRI1, "mainflowWA2: asyncsc[%d] = cl->start_connecting();\n", j);
asyncsc[j++] = cl->start_connecting();
}
print(PRI1, "mainflowWA2: wait_all_awaitable<async_operation<void>> wac(asyncsc, nrClients)\n");
wait_any_awaitable<async_operation<void>> wac(asyncsc, nrClients);
for (int i = 0; i < nrClients; i++) {
print(PRI1, "mainflowWA2: int r = co_await wac;\n");
int r = co_await wac;
print(PRI1, "mainflowWA2: wac %d completed\n", r);
}
// Writing
j = 0;
for (CommClient* cl : clients) {
print(PRI1, "mainflowWA2: asyncsw[%d] = cl->start_writing(...);\n", j);
str[j] = "This is string ";
str[j] += std::to_string(counter++);
str[j] += " to echo\n";
asyncsw[j] = cl->start_writing(str[j].c_str(), str[j].length() + 1);
j++;
}
print(PRI1, "mainflowWA2: wait_any_awaitable<async_operation<void>> waw(asyncsw, 3)\n");
wait_any_awaitable<async_operation<void>> waw(asyncsw, 3);
for (int i = 0; i < 3; i++) {
print(PRI1, "mainflowWA2: int r = co_await waw;\n");
int r = co_await waw;
print(PRI1, "mainflowWA2: waw %d completed\n", r);
}
// Reading
j = 0;
for (CommClient* cl : clients) {
print(PRI1, "mainflowWA2: asyncsr[%d] = cl->start_reading();\n", j);
asyncsr[j++] = cl->start_reading();
}
print(PRI1, "mainflowWA2: wait_any_awaitable<async_operation<std::string>> war(asyncsr, nrClients)\n");
wait_any_awaitable<async_operation<std::string>> war(asyncsr, nrClients);
for (int i = 0; i < nrClients; i++) {
print(PRI1, "mainflowWA2: int r = co_await war;\n");
int r = co_await war;
print(PRI1, "mainflowWA2: war %d completed\n", r);
}
for (int i = 0; i < nrClients; i++) {
print(PRI1, "asyncsr[%d].get_result() = %s", i, asyncsr[i].get_result().c_str());
}
// Closing
for (CommClient* cl : clients) {
print(PRI1, "mainflowWA2: cl->stop();\n");
cl->stop();
}
print(PRI1, "mainflowWA2: std::this_thread::sleep_for(std::chrono::seconds(1))\n");
std::this_thread::sleep_for(std::chrono::seconds(1));
}
print(PRI1, "mainflowWA2: co_return 0;\n");
co_return 0;
}
async_task<int> mainflowOneClient(CommClient& c1, int instance, int counter)
{
print(PRI1, "mainflowOneClient: %d: begin\n", instance);
// Connecting
print(PRI1, "mainflowOneClient: %d: async_operation<void> sc1 = c1.start_connecting();\n", instance);
async_operation<void> sc1 = c1.start_connecting();
print(PRI1, "mainflowOneClient: %d: co_await sc1;\n", instance);
co_await sc1;
// Writing
std::string str = "This is string ";
str += std::to_string(counter);
str += " to echo\n";
print(PRI1, "mainflowOneClient: %d: async_operation<void> sw1 = c1.start_writing(...);\n", instance);
async_operation<void> sw1 = c1.start_writing(str.c_str(), str.length() + 1);
print(PRI1, "mainflowOneClient: %d: co_await sw1;\n", instance);
co_await sw1;
// Reading
print(PRI1, "mainflowOneClient: %d: async_operation<std::string> sr1 = c1.start_reading();\n", instance);
async_operation<std::string> sr1 = c1.start_reading('\n');
print(PRI1, "mainflowOneClient: %d: std::string strout = co_await sr1;\n", instance);
std::string strout = co_await sr1;
print(PRI1, "mainflowOneClient: %d: strout = %s", instance, strout.c_str());
// Closing
print(PRI1, "mainflowOneClient: %d: c1.stop();\n", instance);
c1.stop();
co_return 0;
}
async_task<int> mainflowWA3(CommClient& c1, CommClient& c2, CommClient& c3)
{
print(PRI1, "mainflowWA3: begin\n");
int counter = 0;
for (int i = 0; i < 40; i++)
{
print(PRI1, "mainflowWA3: %d ------------------------------------------------------------------\n", i);
print(PRI1, "mainflowWA3: mainflowOneClient(c1, 0, counter++);\n");
async_task<int> tc1 = mainflowOneClient(c1, 0, counter++);
print(PRI1, "mainflowWA3: mainflowOneClient(c2, 1, counter++);\n");
async_task<int> tc2 = mainflowOneClient(c2, 1, counter++);
print(PRI1, "mainflowWA3: mainflowOneClient(c3, 2, counter++);\n");
async_task<int> tc3 = mainflowOneClient(c3, 2, counter++);
print(PRI1, "mainflowWA3: wait_any_awaitable<async_task<int>> wat({ &tc1, &tc2, &tc3 });\n");
wait_any_awaitable<async_task<int>> wat({ &tc1, &tc2, &tc3 });
for (int i = 0; i < 3; i++) {
print(PRI1, "mainflowWA3: int r = co_await wat;\n");
int r = co_await wat;
print(PRI1, "mainflowWA3: wat %d completed\n", r);
}
print(PRI1, "mainflowWA3: std::this_thread::sleep_for(std::chrono::seconds(1))\n");
std::this_thread::sleep_for(std::chrono::seconds(1));
}
print(PRI1, "mainflowWA3: co_return 0;\n");
co_return 0;
}
void mainflowX(CommClient& c1, CommClient& c2, CommClient& c3, int selected)
{
switch (selected) {
case 0:
{
print(PRI1, "mainflowX: async_task<int> si0 = mainflowWA0(c1, c2, c3);\n");
async_task<int> si0 = mainflowWA0(c1, c2, c3);
}
break;
case 1:
{
print(PRI1, "mainflowX: async_task<int> si1 = mainflowWA1( {&c1, &c2, &c3} )\n");
async_task<int> si1 = mainflowWA1({ &c1, &c2, &c3 });
}
break;
case 2:
{
print(PRI1, "mainflowX: async_task<int> si2 = mainflowWA2( {&c1, &c2, &c3} )\n");
async_task<int> si2 = mainflowWA2({ &c1, &c2, &c3 });
}
break;
case 3:
{
print(PRI1, "mainflowX: async_task<int> si3 = mainflowWA3(c1, c2, c3} )\n");
async_task<int> si3 = mainflowWA3(c1, c2, c3);
}
break;
}
}
async_task<int> mainflowAll(CommClient& c1, CommClient& c2, CommClient& c3)
{
print(PRI1, "mainflowAll: async_task<int> si0 = mainflowWA0(c1, c2, c3);\n");
async_task<int> si0 = mainflowWA0(c1, c2, c3);
print(PRI1, "mainflowAll: co_await si0;\n");
co_await si0;
print(PRI1, "mainflowAll: async_task<int> si1 = mainflowWA1( {&c1, &c2, &c3} )\n");
async_task<int> si1 = mainflowWA1({ &c1, &c2, &c3 });
print(PRI1, "mainflowAll: co_await si1;\n");
co_await si1;
print(PRI1, "mainflowAll: async_task<int> si2 = mainflowWA2( {&c1, &c2, &c3} )\n");
async_task<int> si2 = mainflowWA2({ &c1, &c2, &c3 });
print(PRI1, "mainflowAll: co_await si2;\n");
co_await si2;
print(PRI1, "mainflowAll: async_task<int> si3 = mainflowWA3(c1, c2, c3} )\n");
async_task<int> si3 = mainflowWA3(c1, c2, c3);
print(PRI1, "mainflowAll: co_await si3;\n");
co_await si3;
print(PRI1, "mainflowAll: co_return 0;\n");
co_return 0;
}
int main(int argc, char* argv[])
{
set_priority(0x01);
boost::asio::io_context ioContext;
print(PRI1, "main: CommClient c1(ioContext, ep1);\n");
CommClient c1(ioContext, ep1);
print(PRI1, "main: CommClient c2(ioContext, ep1);\n");
CommClient c2(ioContext, ep1);
print(PRI1, "main: CommClient c3(ioContext, ep1);\n");
CommClient c3(ioContext, ep1);
if (argc == 2)
{
int selected = 0;
selected = atoi(argv[1]);
if (selected < 0 || selected > 3)
{
print(PRI1, "main: selection must be in the range [0..3]\n");
return 0;
}
print(PRI1, "main: mainflowX(c1, c2, c3, selected);\n");
mainflowX(c1, c2, c3, selected);
}
else
{
print(PRI1, "main: async_task<int> si = mainflowAll(c1, c2, c3);\n");
async_task<int> si = mainflowAll(c1, c2, c3);
}
print(PRI1, "main: before ioContext.run();\n");
ioContext.run();
print(PRI1, "main: after ioContext.run();\n");
print(PRI1, "main: std::this_thread::sleep_for(std::chrono::seconds(1))\n");
std::this_thread::sleep_for(std::chrono::seconds(1));
print(PRI1, "main: return 0;\n");
return 0;
}
| 33.591837
| 111
| 0.64331
|
JohanVanslembrouck
|
88f13baa6426fe695708884f021510015e59e2c2
| 1,907
|
hpp
|
C++
|
include/vk/descriptor_set.hpp
|
K1llByte/kazan
|
8023d23b305ee8d3ef47c3bbfa0baae1a2685689
|
[
"Apache-2.0"
] | null | null | null |
include/vk/descriptor_set.hpp
|
K1llByte/kazan
|
8023d23b305ee8d3ef47c3bbfa0baae1a2685689
|
[
"Apache-2.0"
] | 1
|
2021-12-28T23:50:46.000Z
|
2021-12-28T23:50:46.000Z
|
include/vk/descriptor_set.hpp
|
K1llByte/kazan
|
8023d23b305ee8d3ef47c3bbfa0baae1a2685689
|
[
"Apache-2.0"
] | null | null | null |
#ifndef KZN_VK_DESCRIPTOR_SET_HPP
#define KZN_VK_DESCRIPTOR_SET_HPP
#include "vk/device.hpp"
namespace kzn::vk
{
class DescriptorSetLayout
{
friend class DescriptorSetLayoutBuilder;
public:
~DescriptorSetLayout();
VkDescriptorSetLayout vk_descriptor_set_layout() { return vkset_layout; };
private:
DescriptorSetLayout() = default;
private:
Device* device;
VkDescriptorSetLayout vkset_layout;
};
class DescriptorSetLayoutBuilder
{
public:
DescriptorSetLayoutBuilder(Device* _device);
~DescriptorSetLayoutBuilder() = default;
DescriptorSetLayoutBuilder& add_binding(
const uint32_t binding,
const VkDescriptorType desc_type,
const uint32_t count,
const VkShaderStageFlags stages);
DescriptorSetLayout build();
private:
Device* device;
std::vector<VkDescriptorSetLayoutBinding> bindings;
};
class DescriptorSet
{
friend class DescriptorPool;
public:
~DescriptorSet() = default;
VkDescriptorSet vk_descriptor_set() noexcept { return vkdescriptor_set; }
void bind(CommandBuffer& cmd_buffer, VkPipelineLayout vkpipeline_layout);
private:
DescriptorSet() = default;
private:
VkDescriptorSet vkdescriptor_set;
};
class DescriptorPool
{
public:
DescriptorPool(Device* device);
~DescriptorPool();
VkDescriptorPool vk_descriptor_pool() noexcept { return vkdescriptor_pool; }
DescriptorSet allocate(DescriptorSetLayout& descriptor_set_layout);
// TODO: allocate multiple sets at a time
private:
Device* device;
VkDescriptorPool vkdescriptor_pool;
};
} // namespace kzn::vk
#endif // KZN_VK_DESCRIPTOR_SET_HPP
| 25.092105
| 84
| 0.648663
|
K1llByte
|
88f1c26bdf504a987de6f445e4320215d3bd90b4
| 2,190
|
cpp
|
C++
|
sample/HAIROWorld/controller/TiltCameraJoystickController.cpp
|
k38-suzuki/hairo-world-plugin
|
031375812b278d88116f92320d8c5ce74eba7a0a
|
[
"MIT"
] | 5
|
2020-12-16T22:18:46.000Z
|
2022-03-26T08:39:51.000Z
|
sample/HAIROWorld/controller/TiltCameraJoystickController.cpp
|
k38-suzuki/hairo-world-plugin
|
031375812b278d88116f92320d8c5ce74eba7a0a
|
[
"MIT"
] | 2
|
2021-06-29T04:03:15.000Z
|
2021-06-29T05:46:15.000Z
|
sample/HAIROWorld/controller/TiltCameraJoystickController.cpp
|
k38-suzuki/hairo-world-plugin
|
031375812b278d88116f92320d8c5ce74eba7a0a
|
[
"MIT"
] | 2
|
2021-06-19T17:11:12.000Z
|
2021-07-09T06:58:47.000Z
|
/**
TiltCamera Controller
@author Kenta Suzuki
*/
#include <cnoid/Camera>
#include <cnoid/EigenUtil>
#include <cnoid/Joystick>
#include <cnoid/SimpleController>
using namespace cnoid;
class TiltCameraJoystickController : public SimpleController
{
SimpleControllerIO* io;
Link* turret;
double qref;
double qprev;
double dt;
Camera* camera;
Joystick joystick;
public:
virtual bool initialize(SimpleControllerIO* io) override
{
Body* body = io->body();
turret = body->link("TURRET_T");
if(turret) {
turret->setActuationMode(Link::JointEffort);
qref = qprev = turret->q();
io->enableIO(turret);
}
dt = io->timeStep();
camera = body->findDevice<Camera>("Camera");
return true;
}
virtual bool control() override
{
joystick.readCurrentState();
static const double P = 0.01;
static const double D = 0.005;
double pos = -joystick.getPosition(Joystick::DIRECTIONAL_PAD_V_AXIS);
if(fabs(pos) < 0.15) {
pos = 0.0;
}
double q = turret->q();
double dq = (q - qprev) / dt;
double dqref = 0.0;
double deltaq = 0.00025 * pos;
qref += deltaq;
dqref = deltaq / dt;
turret->u() = P * (qref - q) + D * (dqref - dq);
qprev = q;
double p = 0.0;
bool changed = false;
bool pushed = joystick.getButtonState(Joystick::L_BUTTON);
if(!pushed) {
p = joystick.getPosition(Joystick::L_TRIGGER_AXIS);
} else {
p = -1.0;
}
if(fabs(p) < 0.15) {
p = 0.0;
}
if(camera && fabs(p) > 0.0) {
double fov = camera->fieldOfView();
fov += radian(1.0) * p * 0.02;
if((fov > radian(0.0)) && (fov < radian(90.0))) {
camera->setFieldOfView(fov);
changed = true;
}
if(changed) {
camera->notifyStateChange();
}
}
return true;
}
};
CNOID_IMPLEMENT_SIMPLE_CONTROLLER_FACTORY(TiltCameraJoystickController)
| 23.548387
| 78
| 0.528767
|
k38-suzuki
|
88f7cd551b4cdf303bd6566da003e44bdd90a6d9
| 13,004
|
cpp
|
C++
|
core/impl/render/gl/gl_helper.cpp
|
auyunli/enhance
|
ca99530c80b42842e713ed4b62e40d12e56ee24a
|
[
"BSD-2-Clause"
] | null | null | null |
core/impl/render/gl/gl_helper.cpp
|
auyunli/enhance
|
ca99530c80b42842e713ed4b62e40d12e56ee24a
|
[
"BSD-2-Clause"
] | null | null | null |
core/impl/render/gl/gl_helper.cpp
|
auyunli/enhance
|
ca99530c80b42842e713ed4b62e40d12e56ee24a
|
[
"BSD-2-Clause"
] | null | null | null |
#include <cassert>
#include <iostream>
#include <cstdio>
#include "gl_includes.hpp"
#include "gl_helper.hpp"
#include "text_read_write.hpp"
namespace e2 { namespace render { namespace gl {
bool gl_helper::compile_shader_from_string( GLuint * shader, char const * source, GLSLShaderType type ){
bool ret;
if( nullptr == shader ) return false;
if( GLSLShaderType::VERTEX == type ){
*shader = glCreateShader(GL_VERTEX_SHADER);
}else if( GLSLShaderType::FRAGMENT == type ){
*shader = glCreateShader(GL_FRAGMENT_SHADER);
}
else{
return false;
}
if( 0 == *shader ){
assert( false );
return false;
}
char const * sourceTextConst = source;
glShaderSource( *shader, 1, &sourceTextConst, NULL);
check_error();
glCompileShader( *shader );
check_error();
GLint result;
glGetShaderiv( *shader, GL_COMPILE_STATUS, &result );
check_error();
if( GL_FALSE == result ){
std::cerr<< "shader compilation failed!" <<std::endl;
GLint logLen;
glGetShaderiv( *shader, GL_INFO_LOG_LENGTH, &logLen );
if( logLen > 0 ){
char * log = (char *)malloc(logLen);
GLsizei written;
glGetShaderInfoLog( *shader, logLen, &written, log);
std::cerr << "Shader log: \n" << log <<std::endl;
free(log);
}
ret = false;
}else{
ret = true;
}
return ret;
}
bool gl_helper::compile_shader_from_file( GLuint * shader, char const * fileName, GLSLShaderType type ){
bool ret;
std::vector<char> sourceText;
ret = ::e2::file::text_read_write::read( fileName, &sourceText );
if( false == ret ){
assert( false );
return false;
}
char const * sourceTextConst = &sourceText[0];
return compile_shader_from_string( shader, sourceTextConst, type );
}
bool gl_helper::create_program( GLuint * program_handle ){
if( nullptr == program_handle ){
assert( "gl program handle invalid." );
return false;
}
*program_handle = glCreateProgram();
if( 0 == *program_handle ){
assert( "gl program creation failed.");
return false;
}
return true;
}
bool gl_helper::delete_program( GLuint program_handle ){
glDeleteProgram( program_handle );
return check_error();
}
bool gl_helper::link_program( GLuint program_handle ){
glLinkProgram( program_handle );
check_error();
GLint status;
glGetProgramiv( program_handle, GL_LINK_STATUS, &status );
if( GL_FALSE == status ){
GLint logLen;
glGetProgramiv( program_handle, GL_INFO_LOG_LENGTH, &logLen);
if( logLen > 0 ){
char * log = (char *)malloc(logLen);
GLsizei written;
glGetProgramInfoLog( program_handle, logLen, &written, log);
std::cerr<< "Program log: \n" << log <<std::endl;
free(log);
}
assert( false && "gl link program failed." );
return false;
}
return true;
}
bool gl_helper::use_program( GLuint program_handle ){
glUseProgram( program_handle );
return check_error();
}
bool gl_helper::set_program_parameter( GLuint program_handle, GLenum parameter, GLint value ){
glProgramParameteri( program_handle, parameter, value );
return check_error();
}
bool gl_helper::print_info(){
const GLubyte * renderer = glGetString( GL_RENDERER );
const GLubyte * vendor = glGetString( GL_VENDOR );
const GLubyte * version = glGetString( GL_VERSION );
const GLubyte * glslVersion = glGetString( GL_SHADING_LANGUAGE_VERSION );
GLint major, minor;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
printf("GL Vendor: %s\n", vendor);
printf("GL Renderer : %s\n", renderer);
printf("GL Version (string) : %s\n", version);
printf("GL Version (integer) : %d.%d\n", major, minor);
printf("GLSL Version : %s\n", glslVersion);
return check_error();
}
bool gl_helper::bind_attrib_location( GLuint program_handle, GLuint index, GLchar * attrib_name ){
glBindAttribLocation( program_handle, index, attrib_name );
return check_error();
}
bool gl_helper::define_vertex_attrib_data( GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLvoid * pointer ){
glVertexAttribPointer( index, size, type, normalized, stride, pointer );
return check_error();
}
bool gl_helper::bind_frag_data_location( GLuint program_handle, GLuint color_number, char const * name ){
glBindFragDataLocation( program_handle, color_number, name );
return check_error();
}
bool gl_helper::set_uniform_i1( GLuint Program, char const * Name, int * v ){
GLint location = glGetUniformLocation( Program, (GLchar const * ) Name );
if( location >= 0 ){
glUniform1iv( location, 1, v );
return check_error();
}
else{
assert( false );
return false;
}
}
bool gl_helper::set_uniform_i2( GLuint Program, char const * Name, int * v ){
GLint location = glGetUniformLocation( Program, (GLchar const * ) Name );
if( location >= 0 ){
glUniform2iv( location, 1, v );
return check_error();
}
else{
assert( false );
return false;
}
}
bool gl_helper::set_uniform_i3( GLuint Program, char const * Name, int * v ){
GLint location = glGetUniformLocation( Program, (GLchar const * ) Name );
if( location >= 0 ){
glUniform3iv( location, 1, v );
return check_error();
}
else{
assert( false );
return false;
}
}
bool gl_helper::set_uniform_i4( GLuint Program, char const * Name, int * v ){
GLint location = glGetUniformLocation( Program, (GLchar const * ) Name );
if( location >= 0 ){
glUniform4iv( location, 1, v );
return check_error();
}
else{
assert( false );
return false;
}
}
bool gl_helper::set_uniform_f1( GLuint Program, char const * Name, float * v ){
GLint location = glGetUniformLocation( Program, (GLchar const * ) Name );
if( location >= 0 ){
glUniform1fv( location, 1, v );
return check_error();
}
else{
assert( false );
return false;
}
}
bool gl_helper::set_uniform_f2( GLuint Program, char const * Name, float * v ){
GLint location = glGetUniformLocation( Program, (GLchar const * ) Name );
if( location >= 0 ){
glUniform2fv( location, 1, v );
return check_error();
}
else{
assert( false );
return false;
}
}
bool gl_helper::set_uniform_f3( GLuint Program, char const * Name, float * v ){
GLint location = glGetUniformLocation( Program, (GLchar const * ) Name );
if( location >= 0 ){
glUniform3fv( location, 1, v );
return check_error();
}
else{
assert( false );
return false;
}
}
bool gl_helper::set_uniform_f4( GLuint Program, char const * Name, float * v ){
GLint location = glGetUniformLocation( Program, (GLchar const * ) Name );
if( location >= 0 ){
glUniform4fv( location, 1, v );
return check_error();
}
else{
assert( false );
return false;
}
}
bool gl_helper::set_uniform_matf2( GLuint Program, char const * Name, float * m ){
GLint location = glGetUniformLocation( Program, (GLchar const * ) Name );
if( location >= 0 ){
glUniformMatrix2fv( location, 1, GL_FALSE, m );
return check_error();
}
else{
assert( false );
return false;
}
}
bool gl_helper::set_uniform_matf3( GLuint Program, char const * Name, float * m ){
GLint location = glGetUniformLocation( Program, (GLchar const * ) Name );
if( location >= 0 ){
glUniformMatrix3fv( location, 1, GL_FALSE, m );
return check_error();
}
else{
assert( false );
return false;
}
}
bool gl_helper::set_uniform_matf4( GLuint Program, char const * Name, float * m ){
GLint location = glGetUniformLocation( Program, (GLchar const * ) Name );
if( location >= 0 ){
glUniformMatrix4fv( location, 1, GL_FALSE, m );
return true;
}
else{
return false;
}
}
bool gl_helper::print_active_uniforms( GLuint Program )
{
GLint nUniforms, maxLen;
GLenum err = glGetError();
glGetProgramiv( Program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxLen );
err = glGetError();
if( GL_NO_ERROR != err ){
assert( 0 && "GL error" );
}
glGetProgramiv( Program, GL_ACTIVE_UNIFORMS, &nUniforms);
GLchar * name = (GLchar *) malloc( maxLen );
GLint size, location;
GLsizei written;
GLenum type;
std::cout << "Number of uniforms: " << nUniforms << std::endl;
printf(" Location | Name\n");
printf("------------------------------------------------\n");
for( int i = 0; i < nUniforms; ++i ) {
glGetActiveUniform( Program, i, maxLen, &written,
&size, &type, name );
location = glGetUniformLocation( Program, name);
printf(" %-8d | %s\n", location, name);
}
free(name);
return check_error();
}
bool gl_helper::print_active_attribs( GLuint Program )
{
GLint maxLength, nAttribs;
glGetProgramiv(Program, GL_ACTIVE_ATTRIBUTES, &nAttribs);
glGetProgramiv(Program, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &maxLength);
GLchar * name = (GLchar *) malloc( maxLength );
GLint written, size, location;
GLenum type;
printf(" Index | Name\n");
printf("------------------------------------------------\n");
for( int i = 0; i < nAttribs; i++ ) {
glGetActiveAttrib( Program, i, maxLength, &written,
&size, &type, name );
location = glGetAttribLocation(Program, name);
printf(" %-5d | %s\n",location, name);
}
free(name);
return check_error();
}
bool gl_helper::gen_textures( int Size, GLuint * TexNames )
{
if( Size <= 0 ){
return false;
}
else{
glGenTextures( Size, TexNames );
return check_error();
}
}
bool gl_helper::set_texture( int GLTextureUnitOffset, GLuint TexName, unsigned char const * TexData, int Width, int Height )
{
glBindTexture( GL_TEXTURE_2D, TexName );
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, Width,
Height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
TexData );
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR);
return check_error();
}
bool gl_helper::bind_buffer( GLenum buffertype, GLuint bufferhandle ){
glBindBuffer( buffertype, bufferhandle );
return check_error();
}
bool gl_helper::bind_vertex_array( GLuint vbo )
{
glBindVertexArray( vbo );
return check_error();
}
bool gl_helper::unbind_vertex_array()
{
glBindVertexArray( 0 );
return check_error();
}
bool gl_helper::uniform_subroutinesuiv( GLenum ShaderType, GLsizei Count, GLuint const * Indices )
{
glUniformSubroutinesuiv( ShaderType, Count, Indices );
return check_error();
}
bool gl_helper::get_subroutine_uniform_location( GLuint Program, GLenum Shadertype, GLchar const * Name, GLint * ret )
{
*ret = glGetSubroutineUniformLocation( Program, Shadertype, Name );
if( GL_INVALID_ENUM == *ret ||
GL_INVALID_VALUE == *ret ){
assert( false );
return false;
}
return true;
}
bool gl_helper::get_subroutine_index(GLuint program, GLenum shadertype, const GLchar * name, GLuint * ret )
{
*ret = glGetSubroutineIndex( program, shadertype, name );
if( GL_INVALID_ENUM == *ret ||
GL_INVALID_VALUE == *ret ){
assert( false );
return false;
}
return true;
}
bool gl_helper::check_error(){
GLenum ret = glGetError();
if( GL_NO_ERROR != ret ){
assert(false);
return false;
}
return true;
}
bool gl_helper::enable_vertex_attrib_array( GLuint index ){
glEnableVertexAttribArray( index );
return check_error();
}
bool gl_helper::disable_vertex_attrib_array( GLuint index ){
glDisableVertexAttribArray( index );
return check_error();
}
bool gl_helper::generate_vertex_arrays( GLsizei n, GLuint * arrays ){
glGenVertexArrays( n, arrays );
return check_error();
}
bool gl_helper::delete_vertex_arrays( GLsizei n, GLuint * arrays ){
glDeleteVertexArrays( n, arrays );
return check_error();
}
bool gl_helper::store_buffer_data( GLenum target, GLsizeiptr size, GLvoid * data, GLenum usage ){
glBufferData( target, size, data, usage );
return check_error();
}
bool gl_helper::generate_buffers( GLsizei n, GLuint * buffers ){
glGenBuffers( n, buffers );
return check_error();
}
bool gl_helper::delete_buffers( GLsizei n, GLuint * buffers ){
glDeleteBuffers( n, buffers );
return check_error();
}
bool gl_helper::attach_shader( GLuint program_handle, GLuint shader_handle ){
glAttachShader( program_handle, shader_handle );
return check_error();
}
bool gl_helper::detach_shader( GLuint program_handle, GLuint shader_handle ){
glDetachShader( program_handle, shader_handle );
return check_error();
}
} } }
| 29.091723
| 139
| 0.644033
|
auyunli
|
88fb5a2514afb24be9e76bef3cc0141b0c002801
| 3,220
|
cpp
|
C++
|
Blake2/Test/TestUtils.cpp
|
Steppenwolfe65/Blake2
|
9444e194323f98bb797816bc774d202276d17243
|
[
"Intel",
"MIT"
] | 1
|
2016-11-09T05:34:58.000Z
|
2016-11-09T05:34:58.000Z
|
Blake2/Test/TestUtils.cpp
|
Steppenwolfe65/Blake2
|
9444e194323f98bb797816bc774d202276d17243
|
[
"Intel",
"MIT"
] | null | null | null |
Blake2/Test/TestUtils.cpp
|
Steppenwolfe65/Blake2
|
9444e194323f98bb797816bc774d202276d17243
|
[
"Intel",
"MIT"
] | null | null | null |
#include "TestUtils.h"
#include "TestException.h"
#include "../Blake2/CexDomain.h"
#include "../Blake2/CSP.h"
#if defined(_WIN32)
# include <Windows.h>
#else
# include <sys/types.h>
# include <sys/time.h>
#endif
#include <algorithm>
#include <fstream>
#include <iostream>
namespace Test
{
using CEX::Provider::CSP;
void TestUtils::CopyVector(const std::vector<int> &SrcArray, size_t SrcIndex, std::vector<int> &DstArray, size_t DstIndex, size_t Length)
{
memcpy(&DstArray[DstIndex], &SrcArray[SrcIndex], Length * sizeof(SrcArray[SrcIndex]));
}
bool TestUtils::IsEqual(std::vector<byte> &A, std::vector<byte> &B)
{
size_t i = A.size();
if (i != B.size())
return false;
while (i != 0)
{
--i;
if (A[i] != B[i])
return false;
}
return true;
}
uint64_t TestUtils::GetTimeMs64()
{
#if defined(_WIN32)
// Windows
__int64 ctr1 = 0, freq = 0;
if (QueryPerformanceCounter((LARGE_INTEGER *)&ctr1) != 0)
{
QueryPerformanceFrequency((LARGE_INTEGER *)&freq);
// return microseconds to milliseconds
return (uint64_t)(ctr1 * 1000.0 / freq);
}
else
{
FILETIME ft;
LARGE_INTEGER li;
// Get the amount of 100 nano seconds intervals elapsed since January 1, 1601 (UTC) and copy it to a LARGE_INTEGER structure
GetSystemTimeAsFileTime(&ft);
li.LowPart = ft.dwLowDateTime;
li.HighPart = ft.dwHighDateTime;
uint64_t ret = li.QuadPart;
ret -= 116444736000000000LL; // Convert from file time to UNIX epoch time.
ret /= 10000; // From 100 nano seconds (10^-7) to 1 millisecond (10^-3) intervals
return ret;
}
#else
// Linux
struct timeval tv;
gettimeofday(&tv, NULL);
uint64_t ret = tv.tv_usec;
// Convert from micro seconds (10^-6) to milliseconds (10^-3)
ret /= 1000;
// Adds the seconds (10^0) after converting them to milliseconds (10^-3)
ret += (tv.tv_sec * 1000);
return ret;
#endif
}
SymmetricKey TestUtils::GetRandomKey(size_t KeySize, size_t IvSize)
{
CSP rng;
std::vector<byte> key(KeySize, 0);
std::vector<byte> iv(IvSize, 0);
rng.GetBytes(key);
rng.GetBytes(iv);
return SymmetricKey(key, iv);
}
void TestUtils::GetRandom(std::vector<byte> &Data)
{
CSP rng;
rng.GetBytes(Data);
}
bool TestUtils::Read(const std::string &FilePath, std::string &Contents)
{
bool status = false;
std::ifstream ifs(FilePath, std::ios::binary | std::ios::ate);
if (!ifs || !ifs.is_open())
{
throw TestException("Could not open the KAT file!");
}
else
{
ifs.seekg(0, std::ios::end);
const int bufsize = (int)ifs.tellg();
ifs.seekg(0, std::ios::beg);
if (bufsize > 0)
{
status = true;
std::vector<char> bufv(bufsize, 0);
char *buf = &bufv[0];
ifs.read(buf, bufsize);
Contents.assign(buf, bufsize);
}
else
{
throw TestException("The KAT file is empty!");
}
}
return status;
}
std::vector<byte> TestUtils::Reduce(std::vector<byte> Seed)
{
unsigned int len = (unsigned int)(Seed.size() / 2);
std::vector<byte> data(len);
for (unsigned int i = 0; i < len; i++)
data[i] = (byte)(Seed[i] ^ Seed[len + i]);
return data;
}
void TestUtils::Reverse(std::vector<byte> &Data)
{
std::reverse(Data.begin(), Data.end());
}
}
| 21.756757
| 138
| 0.646273
|
Steppenwolfe65
|
88fc192fb39fb2a1b8d8c6bb70ed35df34bdec02
| 177
|
hpp
|
C++
|
NWNXLib/API/Mac/API/CExoArrayListTemplatedchar.hpp
|
acaos/nwnxee-unified
|
0e4c318ede64028c1825319f39c012e168e0482c
|
[
"MIT"
] | 1
|
2019-06-04T04:30:24.000Z
|
2019-06-04T04:30:24.000Z
|
NWNXLib/API/Mac/API/CExoArrayListTemplatedchar.hpp
|
presscad/nwnee
|
0f36b281524e0b7e9796bcf30f924792bf9b8a38
|
[
"MIT"
] | null | null | null |
NWNXLib/API/Mac/API/CExoArrayListTemplatedchar.hpp
|
presscad/nwnee
|
0f36b281524e0b7e9796bcf30f924792bf9b8a38
|
[
"MIT"
] | 1
|
2019-10-20T07:54:45.000Z
|
2019-10-20T07:54:45.000Z
|
#pragma once
#include <cstdint>
namespace NWNXLib {
namespace API {
struct CExoArrayListTemplatedchar
{
char* element;
int32_t num;
int32_t array_size;
};
}
}
| 9.315789
| 33
| 0.689266
|
acaos
|
0000aca1794a79cf75dd578d24948d8694943b37
| 4,340
|
cpp
|
C++
|
3rdParty/Aria/src/ArFileDeviceConnection.cpp
|
bellonemauro/myARIAtestApp
|
8223b5833ccf37cf9f503337858a46544d36a19c
|
[
"Linux-OpenIB"
] | null | null | null |
3rdParty/Aria/src/ArFileDeviceConnection.cpp
|
bellonemauro/myARIAtestApp
|
8223b5833ccf37cf9f503337858a46544d36a19c
|
[
"Linux-OpenIB"
] | null | null | null |
3rdParty/Aria/src/ArFileDeviceConnection.cpp
|
bellonemauro/myARIAtestApp
|
8223b5833ccf37cf9f503337858a46544d36a19c
|
[
"Linux-OpenIB"
] | null | null | null |
/*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2015 Adept Technology, Inc.
Copyright (C) 2016 Omron Adept Technologies, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
robots@mobilerobots.com or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
#include "ArExport.h"
#include "ariaOSDef.h"
#include "ariaTypedefs.h"
#include "ArFileDeviceConnection.h"
#include "ArLog.h"
#include "ariaUtil.h"
#include <stdio.h>
#ifdef WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
AREXPORT ArFileDeviceConnection::ArFileDeviceConnection() :
myInFD(-1), myOutFD(-1), myStatus(STATUS_NEVER_OPENED),
myForceReadBufferSize(0), myReadByteDelay(0.0)
{
}
AREXPORT ArFileDeviceConnection::~ArFileDeviceConnection()
{
close();
}
/**
* @param infilename Input file name, or NULL to use stdin
* @param outfilename Output file name, or NULL to use stdout
* @param outflags Additional flags to pass to system open() function when opening
* the output file in addition to O_WRONLY. For example, pass O_APPEND to append rather than rewrite the
* file.
*/
AREXPORT int ArFileDeviceConnection::open(const char *infilename, const char *outfilename, int outflags)
{
myStatus = STATUS_OPEN_FAILED;
if(infilename)
{
myInFileName = infilename;
myInFD = ArUtil::open(infilename, O_RDONLY);
if(myInFD == -1)
{
ArLog::log(ArLog::Terse, "ArFileDeviceConnection: error opening input file \"%s\": %s", infilename, strerror(errno));
return errno;
}
}
else
{
#ifdef WIN32
myInFD = _fileno(stdin);
#else
myInFD = STDIN_FILENO;
#endif
}
if(outfilename)
{
myOutFileName = outfilename;
myOutFD = ArUtil::open(outfilename, O_WRONLY|outflags);
if(myInFD == -1)
{
ArLog::log(ArLog::Terse, "ArFileDeviceConnection: error opening output file \"%s\": %s", outfilename, strerror(errno));
return errno;
}
}
else
{
#ifdef WIN32
myOutFD = _fileno(stdout);
#else
myOutFD = STDOUT_FILENO;
#endif
}
myStatus = STATUS_OPEN;
return 0;
}
AREXPORT bool ArFileDeviceConnection::close(void)
{
ArUtil::close(myInFD);
ArUtil::close(myOutFD);
myStatus = STATUS_CLOSED_NORMALLY;
return true;
}
AREXPORT int ArFileDeviceConnection::read(const char *data, unsigned int size, unsigned int msWait)
{
unsigned int s = myForceReadBufferSize > 0 ? ArUtil::findMinU(size, myForceReadBufferSize) : size;
#ifdef WIN32
int r = _read(myInFD, (void*)data, s);
#else
int r = ::read(myInFD, (void*)data, s);
#endif
if(myReadByteDelay > 0)
ArUtil::sleep(r * myReadByteDelay);
// TODO add option for intermittent data by returning 0 until a timeout has passed.
// TODO add option to delay full lines (up to \n\r or \n) in above behavior
return r;
}
AREXPORT int ArFileDeviceConnection::write(const char *data, unsigned int size)
{
#ifdef WIN32
return (int) _write(myOutFD, (void*)data, (size_t)size);
#else
return (int) ::write(myOutFD, (void*)data, (size_t)size);
#endif
}
AREXPORT bool ArFileDeviceConnection::isTimeStamping(void)
{
return false;
}
AREXPORT ArTime ArFileDeviceConnection::getTimeRead(int index)
{
ArTime now;
now.setToNow();
return now;
}
AREXPORT const char * ArFileDeviceConnection::getOpenMessage(int err)
{
return strerror(err);
}
| 26.956522
| 125
| 0.721198
|
bellonemauro
|
3231c4dcd936dc29d2cebeafad8f7c3498c80284
| 1,374
|
cpp
|
C++
|
src/common/mesh_utils.cpp
|
jandrej/serac
|
6a19ae5c0cb6ca127d8e897640f7e0c1d5d91ee3
|
[
"BSD-3-Clause"
] | null | null | null |
src/common/mesh_utils.cpp
|
jandrej/serac
|
6a19ae5c0cb6ca127d8e897640f7e0c1d5d91ee3
|
[
"BSD-3-Clause"
] | null | null | null |
src/common/mesh_utils.cpp
|
jandrej/serac
|
6a19ae5c0cb6ca127d8e897640f7e0c1d5d91ee3
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2019-2020, Lawrence Livermore National Security, LLC and
// other Serac Project Developers. See the top-level LICENSE file for
// details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
#include "mesh_utils.hpp"
#include "common/logger.hpp"
#include "fmt/fmt.hpp"
namespace serac {
std::shared_ptr<mfem::ParMesh> buildParallelMesh(const std::string& mesh_file, const int refine_serial,
const int refine_parallel, const MPI_Comm comm)
{
// Get the MPI rank for logging purposes
int rank = 0;
MPI_Comm_rank(comm, &rank);
// Open the mesh
std::string msg = fmt::format("Opening mesh file: {0}", mesh_file);
SLIC_INFO_ROOT(rank, msg);
std::ifstream imesh(mesh_file);
if (!imesh) {
serac::logger::flush();
std::string err_msg = fmt::format("Can not open mesh file: {0}", mesh_file);
SLIC_ERROR_ROOT(rank, err_msg);
serac::exitGracefully();
}
auto mesh = std::make_unique<mfem::Mesh>(imesh, 1, 1, true);
imesh.close();
// mesh refinement if specified in input
for (int lev = 0; lev < refine_serial; lev++) {
mesh->UniformRefinement();
}
// create the parallel mesh
auto pmesh = std::make_shared<mfem::ParMesh>(comm, *mesh);
for (int lev = 0; lev < refine_parallel; lev++) {
pmesh->UniformRefinement();
}
return pmesh;
}
} // namespace serac
| 26.941176
| 103
| 0.658661
|
jandrej
|
323fedbf41575e057b9fb083123e5a62bc031cde
| 23,977
|
cpp
|
C++
|
Tools/RemoteProtocolBridge/Source/ProtocolProcessor/OSCProtocolProcessor/SenderAwareOSCReceiver.cpp
|
dbaudio-soundscape/Support-Generic-OSC-DiGiCo
|
54943f3d797844665644215da70bf7ee3a5bee64
|
[
"Xnet",
"RSA-MD",
"X11"
] | null | null | null |
Tools/RemoteProtocolBridge/Source/ProtocolProcessor/OSCProtocolProcessor/SenderAwareOSCReceiver.cpp
|
dbaudio-soundscape/Support-Generic-OSC-DiGiCo
|
54943f3d797844665644215da70bf7ee3a5bee64
|
[
"Xnet",
"RSA-MD",
"X11"
] | null | null | null |
Tools/RemoteProtocolBridge/Source/ProtocolProcessor/OSCProtocolProcessor/SenderAwareOSCReceiver.cpp
|
dbaudio-soundscape/Support-Generic-OSC-DiGiCo
|
54943f3d797844665644215da70bf7ee3a5bee64
|
[
"Xnet",
"RSA-MD",
"X11"
] | null | null | null |
/*
===============================================================================
Copyright (C) 2019 d&b audiotechnik GmbH & Co. KG. All Rights Reserved.
This file is part of RemoteProtocolBridge.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY d&b audiotechnik GmbH & Co. KG "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
===============================================================================
*/
#include "SenderAwareOSCReceiver.h"
namespace SenderAwareOSC
{
namespace
{
//==============================================================================
/** Allows a block of data to be accessed as a stream of OSC data.
The memory is shared and will be neither copied nor owned by the OSCInputStream.
This class is implementing the Open Sound Control 1.0 Specification for
interpreting the data.
Note: Some older implementations of OSC may omit the OSC Type Tag string
in OSC messages. This class will treat such OSC messages as format errors.
*/
class SenderAwareOSCInputStream
{
public:
/** Creates an SenderAwareOSCInputStream.
@param sourceData the block of data to use as the stream's source
@param sourceDataSize the number of bytes in the source data block
*/
SenderAwareOSCInputStream(const void* sourceData, size_t sourceDataSize)
: input(sourceData, sourceDataSize, false)
{}
//==============================================================================
/** Returns a pointer to the source data block from which this stream is reading. */
const void* getData() const noexcept { return input.getData(); }
/** Returns the number of bytes of source data in the block from which this stream is reading. */
size_t getDataSize() const noexcept { return input.getDataSize(); }
/** Returns the current position of the stream. */
uint64 getPosition() { return (uint64)input.getPosition(); }
/** Attempts to set the current position of the stream. Returns true if this was successful. */
bool setPosition(int64 pos) { return input.setPosition(pos); }
/** Returns the total amount of data in bytes accessible by this stream. */
int64 getTotalLength() { return input.getTotalLength(); }
/** Returns true if the stream has no more data to read. */
bool isExhausted() { return input.isExhausted(); }
//==============================================================================
int32 readInt32()
{
checkBytesAvailable(4, "OSC input stream exhausted while reading int32");
return input.readIntBigEndian();
}
uint64 readUint64()
{
checkBytesAvailable(8, "OSC input stream exhausted while reading uint64");
return (uint64)input.readInt64BigEndian();
}
float readFloat32()
{
checkBytesAvailable(4, "OSC input stream exhausted while reading float");
return input.readFloatBigEndian();
}
String readString()
{
checkBytesAvailable(4, "OSC input stream exhausted while reading string");
auto posBegin = (size_t)getPosition();
auto s = input.readString();
auto posEnd = (size_t)getPosition();
if (static_cast<const char*> (getData())[posEnd - 1] != '\0')
throw OSCFormatError("OSC input stream exhausted before finding null terminator of string");
size_t bytesRead = posEnd - posBegin;
readPaddingZeros(bytesRead);
return s;
}
MemoryBlock readBlob()
{
checkBytesAvailable(4, "OSC input stream exhausted while reading blob");
auto blobDataSize = input.readIntBigEndian();
checkBytesAvailable((blobDataSize + 3) % 4, "OSC input stream exhausted before reaching end of blob");
MemoryBlock blob;
auto bytesRead = input.readIntoMemoryBlock(blob, (ssize_t)blobDataSize);
readPaddingZeros(bytesRead);
return blob;
}
OSCColour readColour()
{
checkBytesAvailable(4, "OSC input stream exhausted while reading colour");
return OSCColour::fromInt32((uint32)input.readIntBigEndian());
}
OSCTimeTag readTimeTag()
{
checkBytesAvailable(8, "OSC input stream exhausted while reading time tag");
return OSCTimeTag(uint64(input.readInt64BigEndian()));
}
OSCAddress readAddress()
{
return OSCAddress(readString());
}
OSCAddressPattern readAddressPattern()
{
return OSCAddressPattern(readString());
}
//==============================================================================
OSCTypeList readTypeTagString()
{
OSCTypeList typeList;
checkBytesAvailable(4, "OSC input stream exhausted while reading type tag string");
if (input.readByte() != ',')
throw OSCFormatError("OSC input stream format error: expected type tag string");
for (;;)
{
if (isExhausted())
throw OSCFormatError("OSC input stream exhausted while reading type tag string");
const OSCType type = input.readByte();
if (type == 0)
break; // encountered null terminator. list is complete.
if (!OSCTypes::isSupportedType(type))
throw OSCFormatError("OSC input stream format error: encountered unsupported type tag");
typeList.add(type);
}
auto bytesRead = (size_t)typeList.size() + 2;
readPaddingZeros(bytesRead);
return typeList;
}
//==============================================================================
OSCArgument readArgument(OSCType type)
{
switch (type)
{
case 'i': return OSCArgument(readInt32());
case 'f': return OSCArgument(readFloat32());
case 's': return OSCArgument(readString());
case 'b': return OSCArgument(readBlob());
case 'r': return OSCArgument(readColour());
default:
// You supplied an invalid OSCType when calling readArgument! This should never happen.
jassertfalse;
throw OSCInternalError("OSC input stream: internal error while reading message argument");
}
}
//==============================================================================
OSCMessage readMessage()
{
auto ap = readAddressPattern();
auto types = readTypeTagString();
OSCMessage msg(ap);
for (auto& type : types)
msg.addArgument(readArgument(type));
return msg;
}
//==============================================================================
OSCBundle readBundle(size_t maxBytesToRead = std::numeric_limits<size_t>::max())
{
// maxBytesToRead is only passed in here in case this bundle is a nested
// bundle, so we know when to consider the next element *not* part of this
// bundle anymore (but part of the outer bundle) and return.
checkBytesAvailable(16, "OSC input stream exhausted while reading bundle");
if (readString() != "#bundle")
throw OSCFormatError("OSC input stream format error: bundle does not start with string '#bundle'");
OSCBundle bundle(readTimeTag());
size_t bytesRead = 16; // already read "#bundle" and timeTag
auto pos = getPosition();
while (!isExhausted() && bytesRead < maxBytesToRead)
{
bundle.addElement(readElement());
auto newPos = getPosition();
bytesRead += (size_t)(newPos - pos);
pos = newPos;
}
return bundle;
}
//==============================================================================
OSCBundle::Element readElement()
{
checkBytesAvailable(4, "OSC input stream exhausted while reading bundle element size");
auto elementSize = (size_t)readInt32();
if (elementSize < 4)
throw OSCFormatError("OSC input stream format error: invalid bundle element size");
return readElementWithKnownSize(elementSize);
}
//==============================================================================
OSCBundle::Element readElementWithKnownSize(size_t elementSize)
{
checkBytesAvailable((int64)elementSize, "OSC input stream exhausted while reading bundle element content");
auto firstContentChar = static_cast<const char*> (getData())[getPosition()];
if (firstContentChar == '/') return OSCBundle::Element(readMessageWithCheckedSize(elementSize));
if (firstContentChar == '#') return OSCBundle::Element(readBundleWithCheckedSize(elementSize));
throw OSCFormatError("OSC input stream: invalid bundle element content");
}
private:
MemoryInputStream input;
//==============================================================================
void readPaddingZeros(size_t bytesRead)
{
size_t numZeros = ~(bytesRead - 1) & 0x03;
while (numZeros > 0)
{
if (isExhausted() || input.readByte() != 0)
throw OSCFormatError("OSC input stream format error: missing padding zeros");
--numZeros;
}
}
OSCBundle readBundleWithCheckedSize(size_t size)
{
auto begin = (size_t)getPosition();
auto maxBytesToRead = size - 4; // we've already read 4 bytes (the bundle size)
OSCBundle bundle(readBundle(maxBytesToRead));
if (getPosition() - begin != size)
throw OSCFormatError("OSC input stream format error: wrong element content size encountered while reading");
return bundle;
}
OSCMessage readMessageWithCheckedSize(size_t size)
{
auto begin = (size_t)getPosition();
auto message = readMessage();
if (getPosition() - begin != size)
throw OSCFormatError("OSC input stream format error: wrong element content size encountered while reading");
return message;
}
void checkBytesAvailable(int64 requiredBytes, const char* message)
{
if (input.getNumBytesRemaining() < requiredBytes)
throw OSCFormatError(message);
}
};
} // namespace
//==============================================================================
/**
* Private implementation of osc receiver. This is an adapted implementation of
* JUCEs' OSCReceiver::pimpl implementation with additional support for sender
* awareness. JUCE OSC implementation cannot differentiate between senders of received
* data - since we need this, we have to provide a modified implementation for this.
*/
struct SenderAwareOSCReceiver::SAOPimpl : private Thread,
private MessageListener
{
SAOPimpl() : Thread("SenderAware OSC server")
{
refCount = 0;
}
~SAOPimpl()
{
disconnect();
}
/**
* Method to connect to a port with given number
*
* @param portNumber The port number to connect to.
* @return True on success, false on failure.
*/
bool connectToPort(int portNumber)
{
if (!disconnect())
return false;
socket.setOwned(new DatagramSocket(false));
if (!socket->bindToPort(portNumber))
return false;
startThread();
return true;
}
/**
* Method to connect to a socket (UDP)
*
* @param newSocket The udp socket object to use to connect.
* @return True on success, false on failure.
*/
bool connectToSocket(DatagramSocket& newSocket)
{
if (!disconnect())
return false;
socket.setNonOwned(&newSocket);
startThread();
return true;
}
/**
* Method to disconnect established connections.
*
* @return True on success, false on failure.
*/
bool disconnect()
{
if (socket != nullptr)
{
signalThreadShouldExit();
if (socket.willDeleteObject())
socket->shutdown();
waitForThreadToExit(10000);
socket.reset();
}
return true;
}
/**
* Method to add a Listener to internal list.
*
* @param listenerToAdd The listener object to add.
*/
void addListener(SenderAwareOSCReceiver::SAOListener<OSCReceiver::MessageLoopCallback>* listenerToAdd)
{
listeners.add(listenerToAdd);
}
/**
* Method to add a Listener to internal list.
*
* @param listenerToAdd The listener object to add.
*/
void addListener(SenderAwareOSCReceiver::SAOListener<OSCReceiver::RealtimeCallback>* listenerToAdd)
{
realtimeListeners.add(listenerToAdd);
}
/**
* Method to remove a Listener from internal list.
*
* @param listenerToRemove The listener object to remove.
*/
void removeListener(SenderAwareOSCReceiver::SAOListener<OSCReceiver::MessageLoopCallback>* listenerToRemove)
{
listeners.remove(listenerToRemove);
}
/**
* Method to remove a Listener from internal list.
*
* @param listenerToRemove The listener object to remove.
*/
void removeListener(SenderAwareOSCReceiver::SAOListener<OSCReceiver::RealtimeCallback>* listenerToRemove)
{
realtimeListeners.remove(listenerToRemove);
}
//==============================================================================
/**
* Implementation of an osc message. This differs from JUCEs' OSCReceiver::pimpl::CallbackMessage
* to enable handling of sender IP and Port of the payload data.
*/
struct CallbackMessage : public Message
{
/**
* Constructor with default initialization of sender ip and port.
*
* @param oscElement The osc element data to use in this message.
*/
CallbackMessage(OSCBundle::Element oscElement) : content(oscElement), senderIPAddress(String()), senderPort(0) {}
/**
* Constructor with default initialization of sender ip and port.
*
* @param oscElement The osc element data to use in this message.
* @param sndIP The sender ip of this message.
* @param sndPort The port this message was received on.
*/
CallbackMessage(OSCBundle::Element oscElement, String sndIP, int sndPort) : content(oscElement), senderIPAddress(sndIP), senderPort(sndPort) {}
OSCBundle::Element content; /**< The payload of the message. Can be either an OSCMessage or an OSCBundle. */
String senderIPAddress; /**< The sender ip address from whom the message was received. */
int senderPort; /**< The sender port from where the message was received. */
};
//==============================================================================
/**
* Method to run to process received data buffer, incl. handling of ip and port the data originates from.
*
* @param data The data buffer to handle.
* @param dataSize The data buffer size.
* @param senderIPAddress The ip the received data originates from.
* @param senderPort The port the data was received on.
*/
void handleBuffer(const char* data, size_t dataSize, String& senderIPAddress, int& senderPort)
{
SenderAwareOSCInputStream inStream(data, dataSize);
try
{
auto content = inStream.readElementWithKnownSize(dataSize);
// realtime listeners should receive the OSC content first - and immediately
// on this thread:
callRealtimeListeners(content, senderIPAddress, senderPort);
// now post the message that will trigger the handleMessage callback
// dealing with the non-realtime listeners.
if (listeners.size() > 0)
postMessage(new CallbackMessage(content, senderIPAddress, senderPort));
}
catch (const OSCFormatError&)
{
if (formatErrorHandler != nullptr)
formatErrorHandler(data, (int)dataSize);
}
}
//==============================================================================
/**
* Method to register a format error handling object.
*
* @param handler The handler object to register.
*/
void registerFormatErrorHandler(OSCReceiver::FormatErrorHandler handler)
{
formatErrorHandler = handler;
}
//==============================================================================
/**
* Getter for an instance corresponding to a given port number of this object (private impl. of sender aware osc, SAOPimpl).
* - If not existing, a new instance is being instanciated and added to internal hash.
* - If existing in hash, internal refcount is increased
*
* @param portNumber The port number to return the corresponding instance of.
* @return The instance of SAOPimpl for the given port number.
*/
static SAOPimpl* getInstance(int portNumber)
{
if (!m_pimples.count(portNumber))
{
m_pimples[portNumber] = std::make_unique<SAOPimpl>();
}
m_pimples[portNumber]->increaseRefCount();
return m_pimples[portNumber].get();
}
/**
* Method to clear instances of SAOPimple for a given port number.
* - If refcount hints at this being the last reference to an instance, the instance is cleared.
* - If refcount hints at this not being the last reference to an instance, refcount is decreased.
*
* @param portNumber The port number the corresponding instance of shall be cleared.
*/
static void cleanInstances(int portNumber)
{
if (m_pimples.count(portNumber) && m_pimples[portNumber])
{
if (m_pimples[portNumber]->isLastRef())
{
m_pimples[portNumber].reset();
m_pimples.erase(portNumber);
}
else
{
m_pimples[portNumber]->decreaseRefCount();
}
}
}
private:
//==============================================================================
void run() override
{
int bufferSize = 65535;
HeapBlock<char> oscBuffer(bufferSize);
String senderIPAddress;
int senderPortNumber;
while (!threadShouldExit())
{
jassert(socket != nullptr);
auto ready = socket->waitUntilReady(true, 100);
if (ready < 0 || threadShouldExit())
return;
if (ready == 0)
continue;
auto bytesRead = (size_t)socket->read(oscBuffer.getData(), bufferSize, false, senderIPAddress, senderPortNumber);
if (bytesRead >= 4)
handleBuffer(oscBuffer.getData(), bytesRead, senderIPAddress, senderPortNumber);
}
}
//==============================================================================
template <typename ListenerType>
void addListenerWithAddress(ListenerType* listenerToAdd,
OSCAddress address,
Array<std::pair<OSCAddress, ListenerType*>>& array)
{
for (auto& i : array)
if (address == i.first && listenerToAdd == i.second)
return;
array.add(std::make_pair(address, listenerToAdd));
}
//==============================================================================
template <typename ListenerType>
void removeListenerWithAddress(ListenerType* listenerToRemove,
Array<std::pair<OSCAddress, ListenerType*>>& array)
{
for (int i = 0; i < array.size(); ++i)
{
if (listenerToRemove == array.getReference(i).second)
{
// aarrgh... can't simply call array.remove (i) because this
// requires a default c'tor to be present for OSCAddress...
// luckily, we don't care about methods preserving element order:
array.swap(i, array.size() - 1);
array.removeLast();
break;
}
}
}
//==============================================================================
void handleMessage(const Message& msg) override
{
if (auto* callbackMessage = dynamic_cast<const CallbackMessage*> (&msg))
{
auto& content = callbackMessage->content;
auto& senderIPAddress = callbackMessage->senderIPAddress;
auto& senderPort = callbackMessage->senderPort;
callListeners(content, senderIPAddress, senderPort);
}
}
//==============================================================================
void callListeners(const OSCBundle::Element& content, const String& senderIPAddress, const int& senderPort)
{
using Listener = SenderAwareOSCReceiver::SAOListener<OSCReceiver::MessageLoopCallback>;
if (content.isMessage())
{
auto&& message = content.getMessage();
listeners.call([&](Listener& l) { l.oscMessageReceived(message, senderIPAddress, senderPort); });
}
else if (content.isBundle())
{
auto&& bundle = content.getBundle();
listeners.call([&](Listener& l) { l.oscBundleReceived(bundle, senderIPAddress, senderPort); });
}
}
void callRealtimeListeners(const OSCBundle::Element& content, const String& senderIPAddress, const int& senderPort)
{
using Listener = SenderAwareOSCReceiver::SAOListener<OSCReceiver::RealtimeCallback>;
if (content.isMessage())
{
auto&& message = content.getMessage();
realtimeListeners.call([&](Listener& l) { l.oscMessageReceived(message, senderIPAddress, senderPort); });
}
else if (content.isBundle())
{
auto&& bundle = content.getBundle();
realtimeListeners.call([&](Listener& l) { l.oscBundleReceived(bundle, senderIPAddress, senderPort); });
}
}
//==============================================================================
bool increaseRefCount()
{
if (refCount < INT_MAX)
refCount++;
else
return false;
return true;
}
bool decreaseRefCount()
{
if (refCount > 0)
refCount--;
else
return false;
return true;
}
bool isLastRef()
{
return refCount == 1;
}
//==============================================================================
ListenerList<SenderAwareOSCReceiver::SAOListener<OSCReceiver::MessageLoopCallback>> listeners;
ListenerList<SenderAwareOSCReceiver::SAOListener<OSCReceiver::RealtimeCallback>> realtimeListeners;
OptionalScopedPointer<DatagramSocket> socket;
OSCReceiver::FormatErrorHandler formatErrorHandler{ nullptr };
friend class SenderAwareOSCReceiver;
friend struct pimples;
int refCount;
static std::map<int, std::unique_ptr<SAOPimpl>> m_pimples;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(SAOPimpl)
};
//==============================================================================
std::map<int, std::unique_ptr<SenderAwareOSCReceiver::SAOPimpl>> SenderAwareOSCReceiver::SAOPimpl::m_pimples;
//==============================================================================
SenderAwareOSCReceiver::SenderAwareOSCReceiver(int portNumber) : m_pimpl(SAOPimpl::getInstance(portNumber))
{
m_portNumber = portNumber;
}
SenderAwareOSCReceiver::~SenderAwareOSCReceiver()
{
SAOPimpl::cleanInstances(m_portNumber);
}
bool SenderAwareOSCReceiver::connect()
{
return m_pimpl->connectToPort(m_portNumber);
}
bool SenderAwareOSCReceiver::connectToSocket(DatagramSocket& socket)
{
return m_pimpl->connectToSocket(socket);
}
bool SenderAwareOSCReceiver::disconnect()
{
return m_pimpl->disconnect();
}
void SenderAwareOSCReceiver::addListener(SAOListener<OSCReceiver::MessageLoopCallback>* listenerToAdd)
{
m_pimpl->addListener(listenerToAdd);
}
void SenderAwareOSCReceiver::addListener(SAOListener<OSCReceiver::RealtimeCallback>* listenerToAdd)
{
m_pimpl->addListener(listenerToAdd);
}
void SenderAwareOSCReceiver::removeListener(SAOListener<OSCReceiver::MessageLoopCallback>* listenerToRemove)
{
m_pimpl->removeListener(listenerToRemove);
}
void SenderAwareOSCReceiver::removeListener(SAOListener<OSCReceiver::RealtimeCallback>* listenerToRemove)
{
m_pimpl->removeListener(listenerToRemove);
}
void SenderAwareOSCReceiver::registerFormatErrorHandler(OSCReceiver::FormatErrorHandler handler)
{
m_pimpl->registerFormatErrorHandler(handler);
}
}
| 31.548684
| 146
| 0.643408
|
dbaudio-soundscape
|
3241a892c48085ce63e9e44d75ef0c0e59863597
| 232
|
cpp
|
C++
|
AtCoder/abc189/a/main.cpp
|
H-Tatsuhiro/Com_Pro-Cpp
|
fd79f7821a76b11f4a6f83bbb26a034db577a877
|
[
"MIT"
] | null | null | null |
AtCoder/abc189/a/main.cpp
|
H-Tatsuhiro/Com_Pro-Cpp
|
fd79f7821a76b11f4a6f83bbb26a034db577a877
|
[
"MIT"
] | 1
|
2021-10-19T08:47:23.000Z
|
2022-03-07T05:23:56.000Z
|
AtCoder/abc189/a/main.cpp
|
H-Tatsuhiro/Com_Pro-Cpp
|
fd79f7821a76b11f4a6f83bbb26a034db577a877
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
char a, b, c; cin >> a >> b >> c;
if (a == b && b == c) cout << "Won" << endl;
else cout << "Lost" << endl;
}
| 21.090909
| 48
| 0.543103
|
H-Tatsuhiro
|
3249e51c1a5b24abe217395fc251242472a546eb
| 1,373
|
cpp
|
C++
|
03/spiralsquare.t.cpp
|
ComicSansMS/AdventOfCode2017
|
238460dd82dae182d78b8460578b7f615cf99fd0
|
[
"Unlicense"
] | null | null | null |
03/spiralsquare.t.cpp
|
ComicSansMS/AdventOfCode2017
|
238460dd82dae182d78b8460578b7f615cf99fd0
|
[
"Unlicense"
] | null | null | null |
03/spiralsquare.t.cpp
|
ComicSansMS/AdventOfCode2017
|
238460dd82dae182d78b8460578b7f615cf99fd0
|
[
"Unlicense"
] | null | null | null |
#include <catch.hpp>
#include <spiralsquare.hpp>
#include <iostream>
TEST_CASE("Spiralsquare")
{
SECTION("Determine Ring")
{
CHECK(getRing(1) == 1);
CHECK(getRing(8) == 3);
CHECK(getRing(11) == 5);
CHECK(getRing(18) == 5);
}
SECTION("Check distance")
{
CHECK(getDistance(1) == 0);
CHECK(getDistance(8) == 1);
CHECK(getDistance(11) == 2);
CHECK(getDistance(18) == 3);
CHECK(getDistance(12) == 3);
CHECK(getDistance(23) == 2);
CHECK(getDistance(1024) == 31);
}
SECTION("Check distance on generated field")
{
Field f(getRing(1024));
f.fillField();
CHECK(f.getDistanceFromCenter(1) == 0);
CHECK(f.getDistanceFromCenter(8) == 1);
CHECK(f.getDistanceFromCenter(11) == 2);
CHECK(f.getDistanceFromCenter(18) == 3);
CHECK(f.getDistanceFromCenter(12) == 3);
CHECK(f.getDistanceFromCenter(23) == 2);
CHECK(f.getDistanceFromCenter(1024) == 31);
}
SECTION("Complicated filling")
{
Field f(5);
int searched = f.fillComplicated(55);
f.printField(std::cout);
CHECK(f.getCell(0, 0) == 1);
CHECK(f.getCell(0, 2) == 806);
CHECK(f.getCell(-2, 2) == 362);
CHECK(f.getCell(0, -2) == 133);
CHECK(searched == 57);
}
}
| 25.425926
| 51
| 0.541151
|
ComicSansMS
|
324beca6e5532de8238fffbeaa9288b7b30c6364
| 1,070
|
cpp
|
C++
|
A2OnlineJudge/Ladder_1400_1499/GargariAndBishops.cpp
|
seeva92/Competitive-Programming
|
69061c5409bb806148616fe7d86543e94bf76edd
|
[
"Apache-2.0"
] | null | null | null |
A2OnlineJudge/Ladder_1400_1499/GargariAndBishops.cpp
|
seeva92/Competitive-Programming
|
69061c5409bb806148616fe7d86543e94bf76edd
|
[
"Apache-2.0"
] | null | null | null |
A2OnlineJudge/Ladder_1400_1499/GargariAndBishops.cpp
|
seeva92/Competitive-Programming
|
69061c5409bb806148616fe7d86543e94bf76edd
|
[
"Apache-2.0"
] | null | null | null |
#include <bits/stdc++.h>
typedef long long ll;
const int mod = 1e9 + 7;
const int MAX = 1e5 + 7;
using namespace std;
typedef vector<int> vi;
ll arr[2007][2007];
ll diag1[2 * 2007], diag2[2 * 2007];
int n;
struct soln {
ll val, i, j;
};
soln sols[2];
int main() {
#ifndef ONLINE_JUDGE
freopen("/Users/seeva92/Workspace/Contests/1.txt", "r", stdin);
freopen("/Users/seeva92/Workspace/Contests/2.txt", "w", stdout);
#endif
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) {
cin >> arr[i][j];
diag1[i + j] += arr[i][j];
diag2[i - j + n] += arr[i][j];
}
sols[0].val = sols[1].val = -1;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) {
if (sols[(i + j) & 1].val < diag1[i + j] + diag2[i - j + n] - arr[i][j]) {
sols[(i + j) & 1].val = diag1[i + j] + diag2[i - j + n] - arr[i][j];
sols[(i + j) & 1].i = i;
sols[(i + j) & 1].j = j;
}
}
cout << sols[0].val + sols[1].val << '\n';
cout << sols[0].i << " " << sols[0].j << " " << sols[1].i << " " << sols[1].j;
}
| 26.75
| 79
| 0.507477
|
seeva92
|
324d9008bf81c4a99c2741b28ac055602ed1d524
| 2,557
|
cpp
|
C++
|
src/frame-counter.cpp
|
longlonghands/fps-challenge
|
020c133a782285364d52b1c98e9661c9aedfd96d
|
[
"MIT"
] | null | null | null |
src/frame-counter.cpp
|
longlonghands/fps-challenge
|
020c133a782285364d52b1c98e9661c9aedfd96d
|
[
"MIT"
] | null | null | null |
src/frame-counter.cpp
|
longlonghands/fps-challenge
|
020c133a782285364d52b1c98e9661c9aedfd96d
|
[
"MIT"
] | null | null | null |
#include "frame-coutner.hpp"
#include "packet-source.hpp"
#include <spdlog/spdlog.h>
namespace challenge { namespace media {
FrameCounter::FrameCounter(int duration)
: PacketSourceSubscriber(50)
, m_durations(15)
, m_targetDuration(duration)
, m_fps(0.0)
, m_frameCounts(-1)
, m_lastFrameTime(0)
, m_currentDuration(0)
, m_isStarted(false) {}
FrameCounter::~FrameCounter() {}
bool FrameCounter::Setup(const AVPacketSource* source) {
auto videoStream = source->VideoStream();
if (videoStream == nullptr) {
return false;
}
m_streamBaseTime = videoStream->time_base;
spdlog::info("setupping frame counter");
return m_decoder.Open([this](int width, int height, FramePtr frame) { this->frameCallback(frame); },
videoStream->codecpar, m_streamBaseTime);
}
void FrameCounter::Start() {
if (m_isStarted) {
return;
}
if (!m_decoder.IsInitiated()) {
spdlog::info("initializing the decoder failed");
return;
}
m_needToStop = false;
m_readThrd.start([&]() { readLoop(); });
}
void FrameCounter::Stop() {
m_needToStop = true;
m_readThrd.join();
m_decoder.Close();
m_isStarted = false;
}
void FrameCounter::readLoop() {
m_isStarted = true;
spdlog::info("fps counter started");
while (!m_needToStop) {
auto pkt = ReadPacket();
if (!pkt) {
common::async::sleep(10);
continue;
}
// spdlog::info("pkt pts is {}", pkt->PTS());
m_decoder.Decode(pkt);
}
m_isStarted = false;
m_needToStop = false;
}
void FrameCounter::frameCallback(FramePtr frame) {
m_frameCounts++;
AVRational perSecond = AVRational{1, 1000};
auto frameTime = av_rescale_q_rnd(frame->PTS(), m_streamBaseTime, perSecond, AV_ROUND_NEAR_INF);
int duration = int(frameTime - m_lastFrameTime);
m_lastFrameTime = frameTime;
m_currentDuration += duration;
// spdlog::info("frame pts is {}", frame->PTS());
// spdlog::info("frame duration is {}", duration);
if (m_currentDuration>m_targetDuration) {
m_fps = m_frameCounts / (m_targetDuration/1000);
spdlog::info("frame-rate is {}", m_fps);
m_currentDuration = 0;
m_frameCounts = 0;
}
// m_durations.push_front(duration);
// m_fps = 1000/(double)m_durations.mean();
}
}} // namespace challenge::media
| 30.440476
| 106
| 0.599922
|
longlonghands
|
3269fd6a68173d2b376df0f394218affa6d0cf4a
| 4,445
|
hpp
|
C++
|
include/expsum/fitting/function_fitter.hpp
|
hide-ikeno/expsum
|
7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda
|
[
"MIT"
] | null | null | null |
include/expsum/fitting/function_fitter.hpp
|
hide-ikeno/expsum
|
7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda
|
[
"MIT"
] | null | null | null |
include/expsum/fitting/function_fitter.hpp
|
hide-ikeno/expsum
|
7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda
|
[
"MIT"
] | null | null | null |
#ifndef EXPSUM_FUNCTION_FITTER_HPP
#define EXPSUM_FUNCTION_FITTER_HPP
#include <type_traits>
#include "expsum/fitting/fast_esprit.hpp"
namespace expsum
{
template <typename T>
class function_fitter
{
public:
using esprit_type = expsum::fast_esprit<T>;
using size_type = typename esprit_type::size_type;
using value_type = typename esprit_type::value_type;
using real_type = typename esprit_type::real_type;
using complex_type = typename esprit_type::complex_type;
using vector_type = typename esprit_type::vector_type;
using real_vector_type = typename esprit_type::real_vector_type;
private:
using is_complex_t =
std::integral_constant<bool, arma::is_complex<T>::value>;
static const real_type default_tolerance;
esprit_type esprit_;
real_type tolerance_;
real_type x0_;
real_type xstep_;
vector_type work_;
bool is_finished_;
public:
function_fitter() = default;
explicit function_fitter(size_type n_samples, size_type max_terms,
real_type tol = default_tolerance)
: esprit_(n_samples, (n_samples + 1) / 2, max_terms),
tolerance_(tol),
x0_(),
xstep_(real_type(1)),
work_(n_samples),
is_finished_(false)
{
}
function_fitter(const function_fitter&) = default;
function_fitter(function_fitter&&) = default;
~function_fitter() = default;
function_fitter& operator=(const function_fitter&) = default;
function_fitter& operator=(function_fitter&&) = default;
void set_size(size_type n_samples, size_type max_terms)
{
esprit_.resize(n_samples, (n_samples + 1) / 2, max_terms);
work_.resize(n_samples);
is_finished_ = false;
}
void set_tolerance(real_type tol)
{
tolerance_ = tol;
}
real_type tolerance() const noexcept
{
return tolerance_;
}
size_type num_samples() const
{
return esprit_.size();
}
size_type max_terms() const
{
return esprit_.ncols();
}
///
/// Fit a funciton by a sum of exponential functions at given inteval
/// [x0,x1].
///
template <typename UnaryFunction>
void run(UnaryFunction fn, real_type x0, real_type x1)
{
assert(num_samples() > 1);
assert(x1 != x0);
is_finished_ = false;
x0_ = x0;
xstep_ = (x1 - x0) / (num_samples() - 1);
// sampling function values
auto xval = x0_;
for (size_type i = 0; i < num_samples(); ++i)
{
work_(i) = fn(xval);
xval += xstep_;
}
// do fit
esprit_.fit(work_, x0_, xstep_, tolerance_);
is_finished_ = true;
}
///
/// @return Vector view to the exponents.
///
auto exponents() const -> decltype(esprit_.exponents())
{
return esprit_.exponents();
}
///
/// @return Vector view to the weights.
///
auto weights() const -> decltype(esprit_.weights())
{
return esprit_.weights();
}
///
/// Calculate errors on sampling points
///
const vector_type& eval_error()
{
assert(is_finished_ && "fitting not yet done");
//
// REMARK: on entry, work_ holds sampled function values
//
auto xval = x0_;
for (size_type i = 0; i < num_samples(); ++i)
{
work_(i) = eval_at(xval, is_complex_t()) - work_(i);
xval += xstep_;
}
}
//
// Get the maximum absolute error of fitting. You must call `run`
// beforehand.
//
real_type max_abs_error() const
{
assert(is_finished_ && "fitting not finished");
return arma::max(arma::abs(work_));
}
real_type max_error(size_type& imax) const
{
return arma::abs(work_).max(imax);
}
private:
value_type eval_at(real_type x, /*is_complex_t*/ std::true_type) const
{
return esprit_.eval_at(x);
}
value_type eval_at(real_type x, /*is_complex_t*/ std::false_type) const
{
return std::real(esprit_.eval_at(x));
}
};
template <typename T>
const typename function_fitter<T>::real_type
function_fitter<T>::default_tolerance =
std::sqrt(std::numeric_limits<real_type>::epsilon());
} // namespace: expsum
#endif /* EXPSUM_FUNCTION_FITTER_HPP */
| 24.832402
| 75
| 0.604499
|
hide-ikeno
|
326f00c546dad683986278036c47676f5a404cf8
| 616
|
cpp
|
C++
|
solutions/316.remove-duplicate-letters.250689698.ac.cpp
|
satu0king/Leetcode-Solutions
|
2edff60d76c2898d912197044f6284efeeb34119
|
[
"MIT"
] | 78
|
2020-10-22T11:31:53.000Z
|
2022-02-22T13:27:49.000Z
|
solutions/316.remove-duplicate-letters.250689698.ac.cpp
|
satu0king/Leetcode-Solutions
|
2edff60d76c2898d912197044f6284efeeb34119
|
[
"MIT"
] | null | null | null |
solutions/316.remove-duplicate-letters.250689698.ac.cpp
|
satu0king/Leetcode-Solutions
|
2edff60d76c2898d912197044f6284efeeb34119
|
[
"MIT"
] | 26
|
2020-10-23T15:10:44.000Z
|
2021-11-07T16:13:50.000Z
|
class Solution {
public:
string removeDuplicateLetters(string s) {
unordered_map<char, int> map;
unordered_set<char> set;
for (char c : s)
map[c]++;
vector<char> stack;
unordered_set<char> done;
for (char c : s) {
while (!done.count(c) && stack.size() && stack.back() >= c &&
map[stack.back()]) {
done.erase(stack.back());
stack.pop_back();
}
if (!done.count(c)) {
stack.push_back(c);
done.insert(c);
}
map[c]--;
}
string ans = "";
for (char c : stack)
ans += c;
return ans;
}
};
| 18.666667
| 67
| 0.501623
|
satu0king
|
326f044c6e5051da1ca410dacdf5f74719f290c4
| 1,976
|
cc
|
C++
|
test/common/network/configurator_test.cc
|
jpsim/envoy-mobile
|
29855f6416b0af1c5b70db2a790212ce6d405946
|
[
"Apache-2.0"
] | 1
|
2022-01-28T06:19:49.000Z
|
2022-01-28T06:19:49.000Z
|
test/common/network/configurator_test.cc
|
jpsim/envoy-mobile
|
29855f6416b0af1c5b70db2a790212ce6d405946
|
[
"Apache-2.0"
] | null | null | null |
test/common/network/configurator_test.cc
|
jpsim/envoy-mobile
|
29855f6416b0af1c5b70db2a790212ce6d405946
|
[
"Apache-2.0"
] | 1
|
2022-02-02T14:38:36.000Z
|
2022-02-02T14:38:36.000Z
|
#include <net/if.h>
#include "test/extensions/common/dynamic_forward_proxy/mocks.h"
#include "gtest/gtest.h"
#include "library/common/network/configurator.h"
using testing::_;
using testing::Return;
namespace Envoy {
namespace Network {
class ConfiguratorTest : public testing::Test {
public:
ConfiguratorTest()
: dns_cache_manager_(
new NiceMock<Extensions::Common::DynamicForwardProxy::MockDnsCacheManager>()),
dns_cache_(dns_cache_manager_->dns_cache_),
configurator_(std::make_shared<Configurator>(dns_cache_manager_)) {
ON_CALL(*dns_cache_manager_, lookUpCacheByName(_)).WillByDefault(Return(dns_cache_));
}
std::shared_ptr<NiceMock<Extensions::Common::DynamicForwardProxy::MockDnsCacheManager>>
dns_cache_manager_;
std::shared_ptr<Extensions::Common::DynamicForwardProxy::MockDnsCache> dns_cache_;
ConfiguratorSharedPtr configurator_;
};
TEST_F(ConfiguratorTest, RefreshDnsForCurrentNetworkTriggersDnsRefresh) {
EXPECT_CALL(*dns_cache_, forceRefreshHosts());
Configurator::setPreferredNetwork(ENVOY_NET_WWAN);
configurator_->refreshDns(ENVOY_NET_WWAN);
}
TEST_F(ConfiguratorTest, RefreshDnsForOtherNetworkDoesntTriggerDnsRefresh) {
EXPECT_CALL(*dns_cache_, forceRefreshHosts()).Times(0);
Configurator::setPreferredNetwork(ENVOY_NET_WLAN);
configurator_->refreshDns(ENVOY_NET_WWAN);
}
TEST_F(ConfiguratorTest, EnumerateInterfacesFiltersByFlags) {
// Select loopback.
auto loopbacks = configurator_->enumerateInterfaces(AF_INET, IFF_LOOPBACK, 0);
EXPECT_EQ(loopbacks[0].rfind("lo", 0), 0);
// Reject loopback.
auto nonloopbacks = configurator_->enumerateInterfaces(AF_INET, 0, IFF_LOOPBACK);
for (const auto& interface : nonloopbacks) {
EXPECT_NE(interface.rfind("lo", 0), 0);
}
// Select AND reject loopback.
auto empty = configurator_->enumerateInterfaces(AF_INET, IFF_LOOPBACK, IFF_LOOPBACK);
EXPECT_EQ(empty.size(), 0);
}
} // namespace Network
} // namespace Envoy
| 32.933333
| 90
| 0.771255
|
jpsim
|
327c45516859cedb1d7e360f7477bd0b6b4e2996
| 164
|
cpp
|
C++
|
codechef_problems/PRESENTS.cpp
|
Ankitahazra-1906/cpp
|
31412ffc844cbafb6dd8a64e031676b48acadfe2
|
[
"MIT"
] | 2
|
2021-11-11T19:18:16.000Z
|
2021-11-13T11:23:03.000Z
|
codechef_problems/PRESENTS.cpp
|
Ankitahazra-1906/cp
|
24ab374184e440c17b467967995b2f6324baa2a6
|
[
"MIT"
] | null | null | null |
codechef_problems/PRESENTS.cpp
|
Ankitahazra-1906/cp
|
24ab374184e440c17b467967995b2f6324baa2a6
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main() {
// your code goes here
int t,n;
cin>>t;
while(t--){
cin>>n;
cout<<n-n/5<<endl;
}
return 0;
}
| 11.714286
| 23
| 0.560976
|
Ankitahazra-1906
|
32821babd81aacd718ff17fa62c07f08858fcc71
| 2,784
|
hpp
|
C++
|
libs/boost_1_72_0/boost/proto/detail/poly_function_traits.hpp
|
henrywarhurst/matrix
|
317a2a7c35c1c7e3730986668ad2270dc19809ef
|
[
"BSD-3-Clause"
] | null | null | null |
libs/boost_1_72_0/boost/proto/detail/poly_function_traits.hpp
|
henrywarhurst/matrix
|
317a2a7c35c1c7e3730986668ad2270dc19809ef
|
[
"BSD-3-Clause"
] | null | null | null |
libs/boost_1_72_0/boost/proto/detail/poly_function_traits.hpp
|
henrywarhurst/matrix
|
317a2a7c35c1c7e3730986668ad2270dc19809ef
|
[
"BSD-3-Clause"
] | null | null | null |
#if !defined(BOOST_PROTO_DONT_USE_PREPROCESSED_FILES)
#include <boost/proto/detail/preprocessed/poly_function_traits.hpp>
#elif !defined(BOOST_PP_IS_ITERATING)
#if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve : 2, line : 0, output \
: "preprocessed/poly_function_traits.hpp")
#endif
///////////////////////////////////////////////////////////////////////////////
// poly_function_traits.hpp
// Contains specializations of poly_function_traits and as_mono_function
//
// Copyright 2008 Eric Niebler. 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)
#if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve : 1)
#endif
#define BOOST_PP_ITERATION_PARAMS_1 \
(3, (1, BOOST_PROTO_MAX_ARITY, \
<boost / proto / detail / poly_function_traits.hpp>))
#include BOOST_PP_ITERATE()
#if defined(__WAVE__) && defined(BOOST_PROTO_CREATE_PREPROCESSED_FILES)
#pragma wave option(output : null)
#endif
#else
#define N BOOST_PP_ITERATION()
////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PolyFun BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)>
struct poly_function_traits<PolyFun, PolyFun(BOOST_PP_ENUM_PARAMS(N, A)),
mpl::size_t<sizeof(poly_function_t)>> {
typedef typename PolyFun::template impl<BOOST_PP_ENUM_PARAMS(N, const A)>
function_type;
typedef typename function_type::result_type result_type;
};
////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PolyFun BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)>
struct as_mono_function_impl<PolyFun(BOOST_PP_ENUM_PARAMS(N, A)), true> {
typedef typename PolyFun::template impl<BOOST_PP_ENUM_PARAMS(N, const A)>
type;
};
////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PolyFun BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)>
struct as_mono_function_impl<PolyFun(BOOST_PP_ENUM_PARAMS(N, A)), false> {
typedef PolyFun type;
};
////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PolyFun BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A)>
struct as_mono_function<PolyFun(BOOST_PP_ENUM_PARAMS(N, A))>
: as_mono_function_impl<PolyFun(BOOST_PP_ENUM_PARAMS(N, A)),
is_poly_function<PolyFun>::value> {};
#undef N
#endif // BOOST_PROTO_DONT_USE_PREPROCESSED_FILES
| 40.941176
| 96
| 0.603807
|
henrywarhurst
|
328a1d2464768465685d9c3436881e9f899cad16
| 573
|
cpp
|
C++
|
Challenge-2020-07/all_paths_from_source_to_target.cpp
|
qiufengyu/LetsCode
|
196fae0bf5c78ee20d05798a9439596e702fdb24
|
[
"MIT"
] | null | null | null |
Challenge-2020-07/all_paths_from_source_to_target.cpp
|
qiufengyu/LetsCode
|
196fae0bf5c78ee20d05798a9439596e702fdb24
|
[
"MIT"
] | null | null | null |
Challenge-2020-07/all_paths_from_source_to_target.cpp
|
qiufengyu/LetsCode
|
196fae0bf5c78ee20d05798a9439596e702fdb24
|
[
"MIT"
] | null | null | null |
#include "../header.h"
class Solution {
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<vector<int>> res;
helper(graph, 0, {}, res);
return res;
}
void helper(vector<vector<int>> &graph, int current, vector<int> path, vector<vector<int>> &res) {
path.push_back(current);
if (current == graph.size() - 1) {
res.push_back(path);
} else {
for (int next: graph[current]) {
helper(graph, next, path, res);
}
}
}
};
| 27.285714
| 102
| 0.530541
|
qiufengyu
|
32917aefba32c304ba8b2b520e7f293542bb3d93
| 731
|
cpp
|
C++
|
solutions/URI_1042 - (2302638) - Accepted.cpp
|
KelwinKomka/URI-Online-Judge-1
|
3d6e37ebe3aa145f47dfcad8b219e53c3cae50f6
|
[
"MIT"
] | null | null | null |
solutions/URI_1042 - (2302638) - Accepted.cpp
|
KelwinKomka/URI-Online-Judge-1
|
3d6e37ebe3aa145f47dfcad8b219e53c3cae50f6
|
[
"MIT"
] | null | null | null |
solutions/URI_1042 - (2302638) - Accepted.cpp
|
KelwinKomka/URI-Online-Judge-1
|
3d6e37ebe3aa145f47dfcad8b219e53c3cae50f6
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cmath>
using namespace std;
int main(int argc, const char * argv[])
{
int x, y, z;
while(cin >> x >> y >> z){
if(x < y)
if(x < z)
if(y < z)
cout << x << endl << y << endl << z << endl;
else
cout << x << endl << z << endl << y << endl;
else
cout << z << endl << x << endl << y << endl;
else
if(y < z)
if(x < z)
cout << y << endl << x << endl << z << endl;
else
cout << y << endl << z << endl << x << endl;
else
cout << z << endl << y << endl << x << endl;
cout << endl << x << endl << y << endl << z << endl;
}
return 0;
}
| 22.151515
| 58
| 0.372093
|
KelwinKomka
|
3292d242f9b1942d38fa8eae8294b8b5c1bbbf5d
| 29,618
|
inl
|
C++
|
src/fonts/stb_font_consolas_26_usascii.inl
|
stetre/moonfonts
|
5c8010c02ea62edcf42902e09478b0cd14af56ea
|
[
"MIT"
] | 3
|
2018-03-13T12:51:57.000Z
|
2021-10-11T11:32:17.000Z
|
src/fonts/stb_font_consolas_26_usascii.inl
|
stetre/moonfonts
|
5c8010c02ea62edcf42902e09478b0cd14af56ea
|
[
"MIT"
] | null | null | null |
src/fonts/stb_font_consolas_26_usascii.inl
|
stetre/moonfonts
|
5c8010c02ea62edcf42902e09478b0cd14af56ea
|
[
"MIT"
] | null | null | null |
// Font generated by stb_font_inl_generator.c (4/1 bpp)
//
// Following instructions show how to use the only included font, whatever it is, in
// a generic way so you can replace it with any other font by changing the include.
// To use multiple fonts, replace STB_SOMEFONT_* below with STB_FONT_consolas_26_usascii_*,
// and separately install each font. Note that the CREATE function call has a
// totally different name; it's just 'stb_font_consolas_26_usascii'.
//
/* // Example usage:
static stb_fontchar fontdata[STB_SOMEFONT_NUM_CHARS];
static void init(void)
{
// optionally replace both STB_SOMEFONT_BITMAP_HEIGHT with STB_SOMEFONT_BITMAP_HEIGHT_POW2
static unsigned char fontpixels[STB_SOMEFONT_BITMAP_HEIGHT][STB_SOMEFONT_BITMAP_WIDTH];
STB_SOMEFONT_CREATE(fontdata, fontpixels, STB_SOMEFONT_BITMAP_HEIGHT);
... create texture ...
// for best results rendering 1:1 pixels texels, use nearest-neighbor sampling
// if allowed to scale up, use bilerp
}
// This function positions characters on integer coordinates, and assumes 1:1 texels to pixels
// Appropriate if nearest-neighbor sampling is used
static void draw_string_integer(int x, int y, char *str) // draw with top-left point x,y
{
... use texture ...
... turn on alpha blending and gamma-correct alpha blending ...
glBegin(GL_QUADS);
while (*str) {
int char_codepoint = *str++;
stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR];
glTexCoord2f(cd->s0, cd->t0); glVertex2i(x + cd->x0, y + cd->y0);
glTexCoord2f(cd->s1, cd->t0); glVertex2i(x + cd->x1, y + cd->y0);
glTexCoord2f(cd->s1, cd->t1); glVertex2i(x + cd->x1, y + cd->y1);
glTexCoord2f(cd->s0, cd->t1); glVertex2i(x + cd->x0, y + cd->y1);
// if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct
x += cd->advance_int;
}
glEnd();
}
// This function positions characters on float coordinates, and doesn't require 1:1 texels to pixels
// Appropriate if bilinear filtering is used
static void draw_string_float(float x, float y, char *str) // draw with top-left point x,y
{
... use texture ...
... turn on alpha blending and gamma-correct alpha blending ...
glBegin(GL_QUADS);
while (*str) {
int char_codepoint = *str++;
stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR];
glTexCoord2f(cd->s0f, cd->t0f); glVertex2f(x + cd->x0f, y + cd->y0f);
glTexCoord2f(cd->s1f, cd->t0f); glVertex2f(x + cd->x1f, y + cd->y0f);
glTexCoord2f(cd->s1f, cd->t1f); glVertex2f(x + cd->x1f, y + cd->y1f);
glTexCoord2f(cd->s0f, cd->t1f); glVertex2f(x + cd->x0f, y + cd->y1f);
// if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct
x += cd->advance;
}
glEnd();
}
*/
#ifndef STB_FONTCHAR__TYPEDEF
#define STB_FONTCHAR__TYPEDEF
typedef struct
{
// coordinates if using integer positioning
float s0,t0,s1,t1;
signed short x0,y0,x1,y1;
int advance_int;
// coordinates if using floating positioning
float s0f,t0f,s1f,t1f;
float x0f,y0f,x1f,y1f;
float advance;
} stb_fontchar;
#endif
#define STB_FONT_consolas_26_usascii_BITMAP_WIDTH 256
#define STB_FONT_consolas_26_usascii_BITMAP_HEIGHT 98
#define STB_FONT_consolas_26_usascii_BITMAP_HEIGHT_POW2 128
#define STB_FONT_consolas_26_usascii_FIRST_CHAR 32
#define STB_FONT_consolas_26_usascii_NUM_CHARS 95
#define STB_FONT_consolas_26_usascii_LINE_SPACING 17
static unsigned int stb__consolas_26_usascii_pixels[]={
0x00cd41db,0x2aa200c8,0x4c402aaa,0x5530000a,0x0c803555,0x7dc00000,
0xcdcb8801,0x87fc0002,0x000002fd,0x3fe7ff30,0x59510001,0x76dc4003,
0x3b61ecce,0x447ba202,0x4db02dee,0x8002dfdb,0xf10fe9ff,0x7dc03dff,
0xffff500e,0x3ff220df,0x1ff4402f,0x09fffff9,0xfb302fe4,0xfc8007bf,
0x7fffd400,0xa8000eff,0x8017ea4f,0xa80dffd8,0x7cbfe25f,0xffb8001f,
0xfa803fff,0x1fffffff,0x6fb81bf2,0x0bbfffe2,0xffffb1ff,0x9ff8007f,
0x3ff6a0fe,0x417fa206,0x06fbaaa8,0x8017bff9,0x37f27ffa,0xff701aaa,
0x2f3bf203,0x5cc00dfe,0xfa80abfe,0xeffb9adf,0x20ff4000,0x9fd000fe,
0x0ff88bfb,0x0ffcbfe2,0x2b3fe600,0x3ea02ffc,0x87fe60bf,0x7fd01ff9,
0x2ffea988,0x644ffbfe,0x3fe000ff,0xff880fe9,0x013fe602,0x3fe21be6,
0x97fe2001,0xff9803fc,0xf70bf903,0x3fffea0b,0x4ff84fff,0x2003ff98,
0x04fb86f9,0x83fa4fa8,0x97fc43fc,0x7e4001ff,0xfd027ec4,0xfd07fe07,
0x801ff309,0x3fff0ffd,0x7c007fd0,0xfb00fe9f,0x01ffb809,0x3fcc37cc,
0x3f214400,0x505fe803,0x207ec0bf,0xbefbeffb,0x7037dc3c,0x17ec00ff,
0x7dc03fc4,0x2fcc7f22,0x1ff97fc4,0x321fec00,0x40ff304f,0x43fdc1ff,
0x7ff005fb,0x2fdc0bfe,0x1fd3ff00,0x36013ee0,0x437cc06f,0x900005fa,
0x0ffb807f,0x7d401fd0,0x7ccbfe23,0x980ffa04,0x7f8801ff,0xf500bf60,
0x0fe87ec7,0x3ff2ff88,0x640b7f6e,0xa81ff44f,0x107fe05f,0x02fe85ff,
0x07fe9fb0,0x6dc437d4,0xfe9ffdee,0x1009f500,0x37cc03ff,0xdd902fd4,
0x647ddddd,0x817fc03f,0x25f804fa,0x80fea7fa,0x17fc01ff,0xf3027dc0,
0xaaef980d,0x7c07f96f,0xffd3ff1f,0xff507fff,0xfb81bf21,0x3607fe05,
0x801fe65f,0x203ff4fd,0x7ffd46fa,0xfe9fffff,0x2009f500,0x1be604fe,
0xffe817ea,0x324fffff,0x03fe603f,0x79b507ec,0x1ffa9ba9,0x3fe205f7,
0x401ff400,0x0ff400ff,0x27bffee0,0x8ffc06f9,0xf913ffff,0xfddfd01f,
0x02fe401d,0x1ff303ff,0x7cc013f2,0x2e03ff2f,0x82ffe65f,0x00fe9ffa,
0x3f200bf5,0x2a1be607,0x4fc8004f,0x6fc80ff2,0xfffd97e0,0x7fc4fb5f,
0xf301fcae,0x04fd801f,0x7d402fd4,0xd0aa9805,0xf1ff803f,0x07fd03ff,
0x7007fff5,0x07fe60bf,0x01ff9ff4,0xf97ffbb6,0x749f901f,0xfd3ff03f,
0x401be201,0xdf300ffa,0x90005f90,0xd01fe49f,0x54fe609f,0x1f69f75f,
0x01fffff3,0xfd003fe6,0x001fd807,0xfb8001ff,0xff1ff804,0xf517ee05,
0x26447fff,0xfd103fe6,0x2bbee03f,0x67ff406f,0x7c40ffc1,0x7c0ff32f,
0x3600fe9f,0x3e201adf,0x26df301f,0x8000efb9,0x80ff24fc,0x25f703ff,
0x365f91fd,0x7ffe440f,0x0ffc40cf,0xf980bfa0,0x00ff2006,0xff006f98,
0x7d407fe3,0x3f2bfe66,0xfd0df51f,0x0ffff4c9,0x03feff88,0x1ff80ff4,
0xbf52fec4,0x07f4ffc0,0x807ffea0,0x2df302ff,0x20003fff,0x40ff24fc,
0x1f901ff8,0xd8fecdf1,0x3fffe207,0x1017fc1f,0x1fe403ff,0x400df100,
0x203531fe,0x203ff0ff,0xe8ffa6fa,0xa85fb8ff,0xf9ffdeff,0x3fff601f,
0xf80ff400,0xeffdceff,0xff817ee0,0x3aa00fe9,0x3fa00cdf,0x372df303,
0xf90004ff,0xf881fe49,0xf31fb00f,0x07d87f4b,0x3ffab7e2,0xfa817fa0,
0x003fe207,0xf7005fb0,0x217fff69,0x203ff0fe,0x41ff15fb,0x04fdeff8,
0x3e3bfff7,0x13fea01f,0x7fc03f60,0xb83effff,0x3a7fe05f,0x003fe00f,
0x6f9817fc,0x4000ff44,0x80ff24fc,0x2afb02ff,0x06e9fe4f,0x1ff44fe6,
0x3fa01ff5,0x0013ee03,0xdf1017ea,0x0ff673ee,0xc80ffc31,0x981ff34f,
0x0401ffff,0xff500ffc,0x7c031001,0x7dc0189f,0xfd3ff307,0x4017e601,
0xdf301ff9,0x90007f70,0xf01fe49f,0x7d5fa09f,0x13e2df14,0x17f62fa8,
0x7ec43dff,0x007fa00f,0xfb00ff40,0x05f99fa3,0x7fc40ffc,0xf703ff11,
0x3fe000df,0x0017fa01,0x9800ffc0,0x7ff440ff,0xbf500fe9,0x981fee00,
0x005fa86f,0x0ff24fc8,0x2fb05fe8,0x2edf95f9,0x447ee01f,0x7ffcc3ff,
0x201fffef,0x2e0005fa,0x7c9f704f,0xff897e27,0xfd883ff2,0xb3077f45,
0xf0003fff,0x1dfb103f,0x205fd100,0x3fa001ff,0x3fffd30d,0x13ea01fd,
0xf302fec0,0x000bf50d,0x01fe49f9,0x43f60ff7,0xfbfdfcff,0x9fc8d546,
0xc980ffda,0x400cffff,0x220002fd,0x07fc40ff,0xb93e61fd,0x9dfff5ff,
0xf981dffb,0xefffeeff,0x7fc000ff,0x3fffb931,0x417fea00,0x3ea001ff,
0xfe9ffeff,0x9f500fe9,0x980bfa00,0x005fa86f,0x0ff24fc8,0xfc81ff88,
0xff37ff70,0xffffc81d,0x801fffff,0x7f8801ff,0x43fc8000,0x5f7dc2fd,
0x4bfe61fe,0x3effffda,0x3bfff620,0x006ff88c,0xfff98ffc,0x3fe2000d,
0x8003ff03,0xfd1dfffa,0x3ea01fd3,0x406fa804,0x05fa86f9,0x3f24fc80,
0x5c2fec03,0xc980402f,0x03defffe,0x90217f60,0xf300007f,0xfc82fd4d,
0x200882ff,0x00008000,0x00660cc0,0x06600880,0x7f400800,0x8809f500,
0x37cc02ff,0x6c002fd4,0x300ff23f,0x05f987ff,0x005f8800,0xd77dff30,
0x0000ff8b,0x08003fd0,0x00000000,0x00000000,0x00000000,0x9fb00fe8,
0x9806fe80,0x00ff986f,0xfc8bfe20,0x41ffc803,0x4c0000fe,0x3ee0004f,
0xd30dffff,0x75400009,0x00000003,0x00000000,0x00000000,0x0fe80000,
0x3202ff88,0x6f9800ff,0x0883ff88,0x3f20ffb8,0xa8dfd003,0x500100ef,
0xa880007f,0x000001bb,0x00000000,0x00000000,0x00000000,0x7f400000,
0x81bffb20,0x99301ff9,0x3ee0dfb9,0x9bf51cff,0xfc85fff9,0xd102cccd,
0xacefc89f,0x00005eba,0x00000000,0x00000000,0x00000000,0x00000000,
0x3a000000,0x19fff10f,0xf5017cc0,0x5c0dffff,0xfff32fff,0xff903dff,
0x7c409fff,0xffffeb83,0x0000002d,0x00000000,0x00000000,0x00000000,
0x00000000,0x83fa0000,0x10020009,0x00133333,0x09998131,0x26666620,
0x26200400,0x00000001,0x00000000,0x00000000,0x00000000,0x00000000,
0x01fd0000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x18800000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0xda800000,0x1eeeeefe,0x7d4007fb,0xff04ffff,0x0ee60003,
0x59b97100,0x33333260,0x95101ccc,0xa980059b,0xdb9302cb,0x3ba20179,
0x3772a202,0xdd97102c,0x6664c39b,0x950ccccc,0x10264c05,0x2159db95,
0x0bceecb8,0xccccccb8,0x2fe884cc,0xfffea800,0x76ffec1e,0xfb1fffff,
0x77754007,0x03ff04ff,0x8013f200,0xeffffffa,0x7ffffdc0,0xff983fff,
0x4404ffff,0x85fffffb,0xfffffffd,0x707ffd82,0x9fffffff,0xffffffc8,
0x3fffee4f,0x9f90ffff,0xfb83fd40,0x75ffffff,0x7fffffff,0xffffffe8,
0x7fdc0fff,0x7ffec006,0x3bee2fee,0xfb0ffe20,0x27e40007,0x90001ff8,
0x3fee009f,0x0effb9ac,0x2aaab7ee,0x67fcc1aa,0x104ffa89,0x35599ffd,
0xa88bffc8,0x7fec0ffe,0x9bdffc87,0x3ff24dba,0x22b999ac,0xfbaaaaa9,
0x5409f90f,0x6fff447f,0x755daa9b,0x3ffb7333,0x67fd5554,0x4ffa82aa,
0x02bfea00,0x6fb82fe8,0x90001fec,0x007fe09f,0xf8027e40,0x23ff984f,
0x3f6004fb,0xe80ff984,0x3ff800df,0x6c41ff98,0x01ffd42e,0x000ffe21,
0x3f21ff10,0xf91fea04,0x2200405f,0x07fe03ff,0xf9000a60,0x503ff00d,
0x003fd8df,0x7fc13f20,0xfddd1001,0x3dddddff,0xdf7037dc,0xf88027dc,
0xa89fb00f,0x07fe006f,0xfd000ffc,0x03fea009,0x21ff1000,0x9fea04fc,
0x80002ff8,0x07fe04fd,0x1ff40000,0x7dc1ff40,0x6c41fec5,0x413f204e,
0xdfec89ff,0x7ffffcc2,0x21ffffff,0x3fe203fe,0x2e009f71,0x8dff505f,
0x3f6002fe,0x2007fa84,0xf3000ffa,0xf880005f,0x5409f90f,0x001bf27f,
0xff00ff40,0xddddd503,0x017f4007,0xff50ffdc,0x7443fd85,0x13f200ef,
0x7fff57fc,0x6cccc2ff,0x419999cf,0x97fc01ff,0x9f9004fb,0xf8ffff90,
0xfa80260f,0x07ff50df,0x20037dc0,0x20002ffe,0x09f90ff8,0x07fb3fd4,
0x80df5000,0xfffa81ff,0x3fa004ff,0xffff9802,0x3fd83fff,0x9003bfa2,
0x3fffe09f,0x640dfb32,0x07fc404f,0x7fdcffa0,0xfd82deff,0x3efffa23,
0x3fafbe67,0xff504fff,0x8005ffdf,0x7cc005fc,0x4000beff,0x09f90ff8,
0x85ff3fd4,0x54099998,0x400dfdba,0x4fc801ff,0x3ffbbb60,0x745eeeee,
0x01cdecaf,0x3bfa27fb,0xf04fc800,0x0ff983ff,0xf9809f90,0xa9fec00f,
0xeffffeee,0x7fd4bfa0,0xf50ff88e,0xffb9bfff,0x3fffea0d,0x27ec000d,
0x7ffe4400,0xff1000cf,0xfa813f21,0xfd83ff17,0x7ff46fff,0x7fc01cff,
0x204fc801,0xffffffff,0x1be27fff,0xfd17fb00,0x827e400b,0x03ff02ff,
0xff3013f2,0x103fe801,0x7ecbff73,0x3e24ffca,0x305ff50f,0xdffa87ff,
0xf981effd,0x0013f62f,0x1ffffb88,0xf90ff880,0xf8bfd409,0x7ee65c1f,
0x7f5d5546,0x007fe02f,0xfe8013f2,0x4e7fcc02,0x33f60199,0x7e4005fe,
0x3e03ff04,0x809f901f,0x7f401ff8,0xb0ffa802,0xf985ffff,0xfc81bea7,
0xf98bfee6,0x3ffe40ff,0x20000bf9,0x4400fffa,0x409f90ff,0x80bfe7fa,
0xffb806fa,0x9003ff00,0x17f4009f,0x7ffffec0,0x6fec3eff,0x7e4003ff,
0x3e03ff04,0x009f901f,0x7fc405ff,0x91ff8801,0xdf501dff,0xff503fcc,
0x7fc417fc,0xb8fffd43,0x2200006f,0x7fc402ff,0x7d409f90,0xfa80ffa6,
0x205ff006,0x4fc801ff,0x200bfa00,0xfeedcefb,0x2aff64ff,0x3f2003ff,
0x3e03ff04,0x009f901f,0x3fd40bfd,0xf70ff880,0xf127e40f,0x4dbea01f,
0x217f607f,0x5ff51ffd,0x27ec0000,0x5fb9fea0,0x7fc97f20,0x7401bea0,
0x003ff02f,0x7f4009f9,0x807fd402,0x5cff67fc,0x9f9002ff,0x7fc07fe0,
0x500df701,0x0ffa01ff,0xff13fdc0,0xe83ff105,0x2a9f903f,0x213f607f,
0x077f47fb,0x02fe8000,0x0ff537e4,0x7ff11ffc,0x2601bea0,0x03ff00ff,
0x74009f90,0x027e402f,0x8ff61ff3,0xfc801ffc,0x3e03ff04,0x05ff501f,
0x6c43dff0,0x5ff7007f,0x3a20efc8,0x41ffb86f,0x9ff11ffa,0xe885ff50,
0x0f7fcc4f,0x91019954,0xf50b21ff,0xb84ff87f,0x6ffdc0ff,0x26037d40,
0x07fe04fe,0xe8013f20,0x07fec02f,0x0ff66fc8,0xfc803ffb,0x3e03ff04,
0x3fffa01f,0x7f4c1fed,0x41effeef,0xfffedeed,0xddffd883,0xffd00eff,
0xb87ffd9b,0xffeddfff,0x41bfb2a4,0xffeffffa,0xdddff94f,0x7ec5fffd,
0xa86fffef,0xffeddfff,0xdffff902,0x3bbadffd,0x745ffeed,0xffffffff,
0x004fc80f,0xff500bfa,0xffd977bd,0x7f41fec3,0x3fbbb20f,0xff2eeeff,
0x8807fe03,0x81fffffc,0x0dffffd8,0xcfffffd8,0x77ffe400,0x7ffe400c,
0xffd501df,0xffe85dff,0x7ff6c403,0xffd71cef,0x9839ffff,0x204efffd,
0x1dffffd9,0x7fffecc0,0xffffd2df,0xfffd03bf,0x91ffffff,0xddfffddd,
0x017f405d,0x7ffffed4,0x41fec0cf,0xffd0efe8,0x5fffffff,0x0ffc07fe,
0x10009880,0x00331001,0x22000220,0x300cc001,0x20060001,0x02600199,
0x20001100,0x13330098,0x7ff40000,0x2fffffff,0x8800bfa0,0x00000999,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x99999300,0x22599999,0x332202cc,0x93007971,
0x9bb75019,0x10059701,0x00f26199,0x4ca80b22,0x22059930,0x40332a3c,
0x3332a3cc,0x2ccccccc,0x1e5c0332,0x99999997,0x32a19999,0x65cf2602,
0x300abccc,0x99999999,0x33333269,0x99954ccc,0x54003579,0xd107260c,
0xffffa85d,0x25ffffff,0xdfb00ffc,0x3a017fd4,0x7ffec45f,0x3fe43fff,
0xbf537dc0,0xd509f500,0x3fee0fff,0x7e4bf306,0x26ff983f,0xfffffffb,
0x07fe5fff,0xffe83fee,0xffffffff,0x5409f91f,0xfffffd6f,0xfff507ff,
0x2effffff,0xffffffff,0xffffff97,0x3f9003df,0x3ff617dc,0x55555447,
0x223ffbaa,0x1ff984ff,0xff5037f4,0x99adfe81,0x3fe61ffd,0xf31ff401,
0x4c9f500d,0x707ffffe,0xbf305fff,0x7e437fe4,0x2aaaa67f,0x24feaaaa,
0x0ffd41ff,0x3feaaaaa,0xf90aaaac,0xfeb7d409,0x2ffecaac,0x55557fd4,
0x55df72aa,0x3f255555,0xfffcaaad,0xf907ec02,0x007ffd83,0x7fd437ec,
0x7cc27f41,0x107fd02f,0xfd13fa07,0x30ffc409,0x27f700df,0x7fbaeff8,
0x30dfdf70,0x0fefecbf,0x400ffbf1,0x87fe1ff8,0xff002ff8,0x5027e403,
0x3a0bfadf,0x4037d46f,0x4fc806fb,0x200ffc88,0x2207ec7e,0x3ea002ed,
0x5cdfb00f,0x0dfb00ef,0xc8001ff7,0x7037e46f,0x807f88df,0xfb8f23fb,
0x5fd9f707,0x2bf65f98,0x1febea4f,0x7fc5fc80,0xf8013fa1,0x813f201f,
0x705fd6fa,0x806fa8ff,0x4fc806fb,0x55513fa0,0x7fd555ff,0x7c400035,
0x2bfe203f,0x3e202ff8,0x0017fc3f,0x3fe637dc,0xf887fb01,0x202fc807,
0x79f707fb,0x3a5f98df,0x75f66f8f,0x1ff8800f,0x05fc8ffc,0xf900ffc0,
0xfeb7d409,0x7d47fa82,0x806fb806,0x1fee04fc,0xfffffffd,0x000bffff,
0x7dc037ec,0xfc805fdf,0x000df70f,0x0ffa17f2,0x1fe03fe2,0x017e41fd,
0x33ee0ff7,0x97e61ff8,0x9f13f97e,0x3ee003fa,0xefb9ff85,0x00ffc000,
0xb7d409f9,0x45fd82fe,0x6fb806fa,0x2604fc80,0x3ea620ff,0x99ef999d,
0x3ff50000,0x03fffa00,0x3e2ffe20,0xff88001f,0xfa86fc81,0x3e21ff06,
0xb807f22f,0x329f707f,0x7e97e65f,0x3a3f79f3,0x0ffc400f,0x007fdffc,
0xf900ffc0,0xb999999d,0x266ffadf,0x7d40ffda,0x0999999f,0x99999ff7,
0x8813f259,0x24f981ff,0x440005f8,0x3ea003ff,0x3fee004f,0xfb0005fc,
0xb03fe60b,0x5c3fa07f,0x807f65ff,0x29f707fb,0x4bf31ff8,0xe9bbfa7f,
0x837dc01f,0x0005ffff,0x7fe403ff,0xffffffff,0xffffffd6,0xffff501b,
0x3ee9ffff,0x5fffffff,0x2ff809f9,0x13e63fa8,0x00dfb000,0x000fffe8,
0x0007fffa,0xfe803ff2,0x7403fe23,0x21fdfb0f,0x1fee00fd,0x2bf927dc,
0xfc9fe5f9,0x8807f63f,0xf7ff02ff,0x3ff0005f,0x55577e40,0xfd6fcaaa,
0x203dfb9b,0xcccccffa,0x555df72c,0x13f23555,0xfb81ff88,0x65c0fea2,
0x007fea00,0x05fdefb8,0x0013fea0,0xf9007ff2,0xfb037d4d,0x27f99f13,
0x1fee00fe,0x1ff327dc,0xf33fcbf3,0x7017ec1f,0x5cffc0df,0x7fc001ff,
0xa813f201,0x7dc5fd6f,0x806fa80f,0x4fc806fb,0x5447fe60,0xfcaacfda,
0x1bff22ad,0x3001ffc4,0x07ff35ff,0x2000ffc0,0xf9801ffc,0x6407fb0f,
0x6f9afaaf,0x07fb80fd,0x9cfd89f7,0x3b8ff15f,0x5ff017ec,0xefd8ffc0,
0x807fe000,0x5bea04fc,0x427ec2fe,0x6fb806fa,0x2a04fc80,0x3fffee7f,
0x7fffffff,0x7ec1fff6,0x92ff4006,0x3fe001ff,0x07ff2001,0xff8bff80,
0x9f6bf200,0x5c07f8fe,0x989f707f,0xdf15faff,0x2e05fb00,0x88ffc06f,
0x3fe005fe,0xa813f201,0xf985fd6f,0x4037d40f,0x4fc806fb,0xaa897fa0,
0xbfeaabfe,0x213fea2a,0x2e001ffa,0x17fa20ff,0xc800ffc0,0x7e4001ff,
0x7dc06fad,0x3efee5fb,0xb83fdc06,0x5fdfe84f,0x7f900df3,0xff00bfe0,
0x801ffcc3,0x13f201ff,0x05fd6fa8,0x06fa89fd,0xfc806fb8,0x203ff904,
0x8807ec7e,0x99cff880,0x22099999,0x2ffa84ff,0xc801ff80,0x99999aff,
0xfbff3009,0x2fefb807,0x701bfbe6,0x213ee0ff,0xdf35fffa,0xf707f900,
0xb83ff00d,0x1ff801ff,0xfa813f20,0xff505fd6,0x5c037d41,0x24fc806f,
0x203ffe98,0x4003f46f,0xfffffffb,0x1bf66fff,0x7c00ffd8,0x7ffc401f,
0x5fffffff,0x003fffe0,0xfe81fff5,0x7fffec5f,0xf74fffff,0x4d7ffa09,
0x83fc806f,0x1ff803ff,0x7c00ffd8,0x813f201f,0x205fd6fa,0x01bea4fe,
0x3fffffee,0xffff97ff,0xf805ffff,0x64003fc6,0xffffffff,0x05ff56ff,
0x3e027fcc,0x7ffc401f,0x5fffffff,0x201bff20,0xffb85ffa,0x7ffffec5,
0x9f74ffff,0x7d57fea0,0x5c4fc806,0x03ff007f,0xff80dfd1,0xa813f201,
0x2e05fd6f,0x00df50ff,0xfffffff7,0x3ffff2ff,0x7c400ade,0x3ea037c5,
0x0000001f,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x6665bff6,0x3001abcc,0x54000799,0xcccc83cc,
0x19900abc,0xcddb9800,0x00000001,0x01eff64c,0x19dffd95,0x6f76e4c0,
0xcdfec983,0x3b600000,0xc983db01,0x320deffe,0xeeeeeeee,0x867dd365,
0x775c0ceb,0x2a1bd700,0x1bdd713e,0x3e3ffee0,0xdfffffff,0x07ffec00,
0x2fffc400,0x7ffffffc,0x00ffc0cf,0xffffff90,0x00009707,0x3ffea16a,
0x7cc1effe,0x1fffffff,0xffffffc8,0x7ffffe47,0x1ff801ff,0x7fc07fe0,
0x3fbffee1,0x3fff61ff,0x3a7fffff,0xfbbfffae,0x2ff444ff,0x9f717fcc,
0x1fffffd3,0x67fdffa0,0x05ffcaaa,0x00bfffe2,0x217fff60,0xfeb99aff,
0x800ffc5f,0xff512efc,0x006ffc45,0x4c5ff900,0x1bf622ff,0x3aa21393,
0x05ffe46f,0x317fdc93,0xff801ffd,0x7c07fe01,0x305ff31f,0x4ccccc41,
0x3ffa3ff9,0x1be7fdf3,0x9fd0ffe6,0x31efefb8,0x5bf609fd,0x0ffa81ff,
0x0bf9bf50,0x5fbefa80,0xffa81ff8,0x26007fe3,0x46fa80ff,0x8000efe8,
0x1fec2ffd,0xf5002ff8,0x2017fccf,0x9fd01ff8,0x3e01ff80,0x2e3ff01f,
0x7ec0005f,0xdfd37f45,0x7fdc07f4,0xff70df90,0x886fb81d,0x103ff2ff,
0x2ff603ff,0xf1000ff9,0xff0bf73f,0xff97fa03,0x205fb801,0x1ffd81ff,
0x81dfd100,0x13f207f8,0xbf91ff80,0x5c0bf700,0x00ffc06f,0x47fe03ff,
0x90001ffa,0x22fe81df,0x403fa1fe,0x80ff9efd,0x7fa80ffb,0xff97ff2a,
0xf107f981,0x400bfe1f,0xf0bf74fc,0xf9bee03f,0x04fd801f,0x7fe40bf6,
0x06ffcc03,0x55557fd4,0x9885fdaa,0xb1ffaaaa,0x09f9007f,0x3fe03fcc,
0x7c07fe01,0x2f7ffa1f,0x03ff5000,0xd07f41fd,0x3ffe201f,0x40bf702f,
0xf0bffe19,0x20bfb03f,0x017f26fa,0x85fb9be6,0x4bf901ff,0x5fc801ff,
0xfa80ff60,0x09ff504f,0x7fffffdc,0x7e45ffff,0x1fffffff,0x7fb005ff,
0xed87fc40,0xeeeffeee,0x203ff0ee,0x3ff221ff,0x3e201dff,0x741fd03f,
0xa803fa0f,0x17ee05ff,0x9ff00980,0x407fd975,0x03fea3fd,0x2fdc3fd0,
0x7f440ffc,0x2a007fe3,0x09f900ff,0x2e0dff98,0x77d402ff,0xaaaaaaaa,
0x266fff21,0x5fd1ff99,0x4c07fb00,0x3ffffe7f,0x1fffffff,0x07fe03ff,
0x0bfff6e2,0x1fd027f4,0x01fd07f4,0xb80ffff4,0xff00005f,0x07ffffff,
0x5ff07fe2,0x3ee27e40,0x2e61ff85,0x00ffc6fe,0xb99aefe8,0x74404ffe,
0x07ff60ef,0x4400ff30,0x23ff02ff,0x4fc804fd,0xff01bea0,0xf80ffc03,
0x3fec401f,0x3fa037e4,0x0fe83fa0,0x1df9df90,0x9800bf70,0x2b3fe2ee,
0xa86ffdba,0x305fd86f,0x85fb81ff,0xffffeeff,0x800ffc0e,0xffffffe9,
0x3fa603fe,0x03ffb80d,0x4c00bfe2,0x23ff307f,0x7d400ffb,0x807fd00f,
0x0ffa01ff,0x26007ff2,0x03fea0ff,0x07f41fd0,0x3ff501fd,0x17ee17fa,
0x7cfffd00,0x43ff981f,0x07fa84fd,0x0bf705fd,0x5bdfffff,0x50007fe0,
0x0bf65797,0x2a027fd4,0x3ff204ff,0x42ff8801,0xff11fffb,0x6ff4501d,
0x2007fe40,0x3bf601ff,0x047fff20,0x7fccff90,0x3a0fe802,0xf303fa0f,
0x21ffcc7f,0x7fc005fb,0x6407fe7f,0x337fe25f,0x42ffcccc,0xcccccffa,
0xff2ccffd,0x00ffc003,0xb81ff800,0xff3003ff,0xdffd101b,0x6c1fdb9b,
0xedffddff,0x3bffea1f,0x3fe67fee,0x02fffddf,0x3e601ff8,0xfdcfedff,
0xfb9bdfb1,0x77ff45ff,0xd1eeeeee,0xfd07f41f,0x5c2ff441,0x017ee2ff,
0x7fc7ff70,0x7d4bf901,0xffffffff,0x7fffdc5f,0xffffffff,0x7c003ff4,
0xfa80001f,0x001ffd85,0xb8077f44,0x45fffffe,0xb3efffd8,0xffec883f,
0x7fec44ff,0xff000dff,0xffffa803,0x3ff23fb3,0x741dffff,0xffffffff,
0x7f41fd2f,0xffd83fa0,0x2e1ffb00,0x4088005f,0x4ff881ff,0x2aaab7f6,
0x5447fcaa,0xfdaaaaaa,0x03ff1aae,0x0000ffc0,0xfe887fe6,0x3f60000e,
0x004cc01f,0x0180004c,0x33000110,0x8800c400,0x00000199,0x00000000,
0x10ffc000,0x7fc1ffb5,0x00bfe201,0x1ff85fb8,0x0007fe00,0x213ff262,
0xc80000dc,0x0000000e,0x00000000,0x00000000,0x00000000,0x40000000,
0xffffffff,0x201fea1f,0x3ee004fd,0x2001ff85,0xffffffff,0x3ffff63f,
0x000002ef,0xfd916d80,0x405db05b,0x07d50ee8,0x1f609d30,0x00019900,
0xdfb3fe40,0x2a21ffcc,0x7f4c002b,0xfffffc85,0x9999996f,0x99999999,
0x7ffffc01,0x04fd83de,0x2e007fb8,0x001ff85f,0x3ffffffe,0x37bf63ff,
0x0000003c,0x3ffa7fe0,0x37e42fff,0x2fd4df70,0x7c827dc0,0x413fee00,
0xfffffff9,0x4ff94fff,0x8ffe66fd,0x40efffe8,0x5fd882eb,0x7fffffe4,
0xfffffff7,0x3fffffff,0x00000000,0x00000000,0x00000000,0x7fffc000,
0xf98dfb32,0x4c7fd00f,0x53fc806f,0x20973649,0x981feef8,0xeeeeeeee,
0x64df93ee,0xc8ffe26f,0x20efebef,0x97ee01fd,0x08888888,0x33333333,
0x00333333,0x00000000,0x00000000,0x00000000,0x4c1fff80,0x41ff40ff,
0x1fe20ff9,0xf92fd897,0xdfb1d73d,0x1be67f20,0x937dc000,0xf17fc4bf,
0x65ffec1f,0x0008807f,0x00000000,0x00000000,0x00000000,0x80000000,
0x83ff02ff,0x85fc86fb,0xe87fe0ff,0x3fbf661f,0x4bf102ef,0xb80003fc,
0xff17ee6f,0x3f61be25,0x00002fff,0x00000000,0x00000000,0x00000000,
0x00000000,0x0ffc07fe,0x5ff07fe2,0x3fea3fb0,0x3ee03fe4,0x107ec05f,
0x666441ff,0x2ccccccc,0x22fdcbf5,0x793001ff,0x00000003,0x00000000,
0x00000000,0x00000000,0xff800000,0xfb03ff01,0xfc837d49,0x3fcfdf92,
0x3fbbbfaa,0xfb84f983,0x3ffffe64,0x004fffff,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0xff80ffc0,0x3f67fa81,0x37e7f703,
0x366f8afc,0xdf96b8df,0x3fd00fe8,0x4ccccccc,0x00000999,0x00000000,
0x00000000,0x00000000,0x00000000,0x40000000,0x03ff01ff,0x03fe2bfe,
0x4d7ce7d4,0x8e64f9df,0x2c98e66c,0x0000f260,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x407fe000,0x7bf901ff,0x66fcc0bf,
0x07f7fd0f,0x000003e4,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0xff000000,0x4407fe03,0x2202feff,0x3bf25fef,0x001b202f,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x3ff01ff8,0x403ffec0,0x3fe62fff,0x0000001f,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x20000000,0x03ff01ff,0x6c027fd4,
0x07ff40ff,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,
};
static signed short stb__consolas_26_usascii_x[95]={ 0,5,3,0,1,0,0,5,3,3,2,1,3,3,
4,1,1,1,1,2,0,2,1,1,1,1,5,3,1,1,2,3,0,0,2,1,1,2,2,0,1,2,2,1,
2,0,1,0,2,0,2,1,1,1,0,0,0,0,1,4,2,3,1,0,0,1,2,2,1,1,0,1,2,2,
1,2,2,1,2,1,2,1,2,2,0,2,0,0,0,0,2,2,6,2,0, };
static signed short stb__consolas_26_usascii_y[95]={ 19,1,1,2,0,0,1,1,0,0,1,5,14,11,
15,1,2,2,2,2,2,2,2,2,2,2,6,6,4,8,4,1,0,2,2,2,2,2,2,2,2,2,2,2,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,1,0,2,22,1,6,1,6,1,6,0,6,1,0,
0,1,1,6,6,6,6,6,6,6,2,6,6,6,6,6,6,0,-2,0,9, };
static unsigned short stb__consolas_26_usascii_w[95]={ 0,4,9,14,12,15,15,4,8,8,11,13,7,8,
6,12,13,12,12,11,14,11,12,12,12,12,5,7,11,12,11,9,15,15,11,12,13,10,10,13,12,11,10,13,
11,14,12,14,11,15,12,12,13,12,15,14,14,15,12,7,11,7,12,15,9,12,11,10,12,12,14,13,11,11,
11,12,11,13,11,13,11,12,12,11,13,11,14,14,14,14,11,10,3,11,14, };
static unsigned short stb__consolas_26_usascii_h[95]={ 0,19,7,17,22,20,19,7,25,25,11,14,10,3,
5,21,18,17,17,18,17,18,18,17,18,17,14,18,16,8,16,19,25,17,17,18,17,17,17,18,17,17,18,17,
17,17,17,18,17,22,17,18,17,18,17,17,17,17,17,25,21,25,9,3,6,14,19,14,19,14,19,19,18,19,
25,18,18,13,13,14,19,19,13,14,18,14,13,13,13,19,13,25,27,25,6, };
static unsigned short stb__consolas_26_usascii_s[95]={ 160,160,185,233,90,144,177,195,65,17,147,
156,248,225,248,119,120,89,45,232,29,108,134,130,147,68,248,160,93,172,81,
221,74,13,1,168,219,208,197,218,171,244,194,143,56,115,102,93,44,103,184,
181,157,205,58,74,14,29,1,57,132,26,159,234,215,118,165,131,243,105,13,
28,67,1,45,42,55,206,105,142,231,193,235,182,79,170,117,132,220,206,194,
34,1,5,200, };
static unsigned short stb__consolas_26_usascii_t[95]={ 21,1,82,49,1,1,1,82,1,1,82,
67,64,82,75,1,29,49,49,29,67,29,29,49,29,67,49,29,67,82,67,
1,1,67,67,29,49,49,49,29,49,29,29,49,67,49,49,29,67,1,49,
29,49,29,49,49,49,49,49,1,1,1,82,82,82,67,1,67,1,67,29,
29,29,29,1,29,29,67,82,67,1,1,67,67,29,67,82,82,67,1,67,
1,1,1,82, };
static unsigned short stb__consolas_26_usascii_a[95]={ 229,229,229,229,229,229,229,229,
229,229,229,229,229,229,229,229,229,229,229,229,229,229,229,229,
229,229,229,229,229,229,229,229,229,229,229,229,229,229,229,229,
229,229,229,229,229,229,229,229,229,229,229,229,229,229,229,229,
229,229,229,229,229,229,229,229,229,229,229,229,229,229,229,229,
229,229,229,229,229,229,229,229,229,229,229,229,229,229,229,229,
229,229,229,229,229,229,229, };
// Call this function with
// font: NULL or array length
// data: NULL or specified size
// height: STB_FONT_consolas_26_usascii_BITMAP_HEIGHT or STB_FONT_consolas_26_usascii_BITMAP_HEIGHT_POW2
// return value: spacing between lines
static void stb_font_consolas_26_usascii(stb_fontchar font[STB_FONT_consolas_26_usascii_NUM_CHARS],
unsigned char data[STB_FONT_consolas_26_usascii_BITMAP_HEIGHT][STB_FONT_consolas_26_usascii_BITMAP_WIDTH],
int height)
{
int i,j;
if (data != 0) {
unsigned int *bits = stb__consolas_26_usascii_pixels;
unsigned int bitpack = *bits++, numbits = 32;
for (i=0; i < STB_FONT_consolas_26_usascii_BITMAP_WIDTH*height; ++i)
data[0][i] = 0; // zero entire bitmap
for (j=1; j < STB_FONT_consolas_26_usascii_BITMAP_HEIGHT-1; ++j) {
for (i=1; i < STB_FONT_consolas_26_usascii_BITMAP_WIDTH-1; ++i) {
unsigned int value;
if (numbits==0) bitpack = *bits++, numbits=32;
value = bitpack & 1;
bitpack >>= 1, --numbits;
if (value) {
if (numbits < 3) bitpack = *bits++, numbits = 32;
data[j][i] = (bitpack & 7) * 0x20 + 0x1f;
bitpack >>= 3, numbits -= 3;
} else {
data[j][i] = 0;
}
}
}
}
// build font description
if (font != 0) {
float recip_width = 1.0f / STB_FONT_consolas_26_usascii_BITMAP_WIDTH;
float recip_height = 1.0f / height;
for (i=0; i < STB_FONT_consolas_26_usascii_NUM_CHARS; ++i) {
// pad characters so they bilerp from empty space around each character
font[i].s0 = (stb__consolas_26_usascii_s[i]) * recip_width;
font[i].t0 = (stb__consolas_26_usascii_t[i]) * recip_height;
font[i].s1 = (stb__consolas_26_usascii_s[i] + stb__consolas_26_usascii_w[i]) * recip_width;
font[i].t1 = (stb__consolas_26_usascii_t[i] + stb__consolas_26_usascii_h[i]) * recip_height;
font[i].x0 = stb__consolas_26_usascii_x[i];
font[i].y0 = stb__consolas_26_usascii_y[i];
font[i].x1 = stb__consolas_26_usascii_x[i] + stb__consolas_26_usascii_w[i];
font[i].y1 = stb__consolas_26_usascii_y[i] + stb__consolas_26_usascii_h[i];
font[i].advance_int = (stb__consolas_26_usascii_a[i]+8)>>4;
font[i].s0f = (stb__consolas_26_usascii_s[i] - 0.5f) * recip_width;
font[i].t0f = (stb__consolas_26_usascii_t[i] - 0.5f) * recip_height;
font[i].s1f = (stb__consolas_26_usascii_s[i] + stb__consolas_26_usascii_w[i] + 0.5f) * recip_width;
font[i].t1f = (stb__consolas_26_usascii_t[i] + stb__consolas_26_usascii_h[i] + 0.5f) * recip_height;
font[i].x0f = stb__consolas_26_usascii_x[i] - 0.5f;
font[i].y0f = stb__consolas_26_usascii_y[i] - 0.5f;
font[i].x1f = stb__consolas_26_usascii_x[i] + stb__consolas_26_usascii_w[i] + 0.5f;
font[i].y1f = stb__consolas_26_usascii_y[i] + stb__consolas_26_usascii_h[i] + 0.5f;
font[i].advance = stb__consolas_26_usascii_a[i]/16.0f;
}
}
}
#ifndef STB_SOMEFONT_CREATE
#define STB_SOMEFONT_CREATE stb_font_consolas_26_usascii
#define STB_SOMEFONT_BITMAP_WIDTH STB_FONT_consolas_26_usascii_BITMAP_WIDTH
#define STB_SOMEFONT_BITMAP_HEIGHT STB_FONT_consolas_26_usascii_BITMAP_HEIGHT
#define STB_SOMEFONT_BITMAP_HEIGHT_POW2 STB_FONT_consolas_26_usascii_BITMAP_HEIGHT_POW2
#define STB_SOMEFONT_FIRST_CHAR STB_FONT_consolas_26_usascii_FIRST_CHAR
#define STB_SOMEFONT_NUM_CHARS STB_FONT_consolas_26_usascii_NUM_CHARS
#define STB_SOMEFONT_LINE_SPACING STB_FONT_consolas_26_usascii_LINE_SPACING
#endif
| 63.151386
| 123
| 0.774597
|
stetre
|
32948c9fb3458d490ccadd7ef77747a6f558d59e
| 23,892
|
hpp
|
C++
|
test/testheader/cmath_test.hpp
|
onihusube/spook
|
a25c49e9fb7320faf1e718a2dc8f35545d3f4a40
|
[
"BSL-1.0"
] | 1
|
2019-09-22T11:27:46.000Z
|
2019-09-22T11:27:46.000Z
|
test/testheader/cmath_test.hpp
|
onihusube/spook
|
a25c49e9fb7320faf1e718a2dc8f35545d3f4a40
|
[
"BSL-1.0"
] | 2
|
2019-08-01T06:05:36.000Z
|
2019-08-01T06:11:20.000Z
|
test/testheader/cmath_test.hpp
|
onihusube/spook
|
a25c49e9fb7320faf1e718a2dc8f35545d3f4a40
|
[
"BSL-1.0"
] | null | null | null |
#include "doctest/doctest.h"
#include <cmath>
#include "spook.hpp"
namespace spook_test::cmath {
TEST_CASE("isinf test")
{
constexpr auto inf = std::numeric_limits<double>::infinity();
CHECK_UNARY(spook::isinf(inf));
CHECK_UNARY(spook::isinf(-inf));
CHECK_UNARY_FALSE(spook::isinf(0.0));
CHECK_UNARY_FALSE(spook::isinf((std::numeric_limits<double>::max)()));
CHECK_UNARY_FALSE(spook::isinf(std::numeric_limits<double>::lowest()));
}
TEST_CASE("isnan test")
{
constexpr auto nan = std::numeric_limits<double>::quiet_NaN();
constexpr auto b = spook::isnan(nan);
static_assert(b == true);
CHECK_UNARY(spook::isnan(nan));
CHECK_UNARY_FALSE(spook::isnan(0.0));
CHECK_UNARY_FALSE(spook::isnan((std::numeric_limits<double>::max)()));
CHECK_UNARY_FALSE(spook::isnan(std::numeric_limits<double>::lowest()));
}
TEST_CASE("isfinite_test")
{
constexpr auto nan = std::numeric_limits<double>::quiet_NaN();
constexpr auto inf = std::numeric_limits<double>::infinity();
constexpr auto b = spook::isfinite(nan);
static_assert(b == false);
CHECK_UNARY_FALSE(spook::isfinite(nan));
CHECK_UNARY_FALSE(spook::isfinite(inf));
CHECK_UNARY_FALSE(spook::isfinite(-inf));
CHECK_UNARY(spook::isfinite(0.0));
CHECK_UNARY(spook::isfinite(-0.0));
CHECK_UNARY(spook::isfinite((std::numeric_limits<double>::max)()));
CHECK_UNARY(spook::isfinite(std::numeric_limits<double>::lowest()));
}
TEST_CASE("isnormal_test")
{
constexpr auto nan = std::numeric_limits<double>::quiet_NaN();
constexpr auto inf = std::numeric_limits<double>::infinity();
constexpr auto denorm = 0x1p-1033;
constexpr bool b = spook::isnormal(denorm);
static_assert(b == false);
CHECK_UNARY_FALSE(spook::isnormal(nan));
CHECK_UNARY_FALSE(spook::isnormal(inf));
CHECK_UNARY_FALSE(spook::isnormal(-inf));
CHECK_UNARY_FALSE(spook::isnormal(0.0));
CHECK_UNARY_FALSE(spook::isnormal(-0.0));
CHECK_UNARY_FALSE(spook::isnormal(denorm));
CHECK_UNARY_FALSE(spook::isnormal(-denorm));
CHECK_UNARY(spook::isnormal(1.0));
CHECK_UNARY(spook::isnormal(-2.0));
CHECK_UNARY(spook::isnormal((std::numeric_limits<double>::max)()));
CHECK_UNARY(spook::isnormal(std::numeric_limits<double>::lowest()));
}
TEST_CASE("fabs_test")
{
constexpr auto p_inf = std::numeric_limits<double>::infinity();
CHECK_UNARY(p_inf == spook::fabs(-std::numeric_limits<double>::infinity()));
CHECK_UNARY(p_inf == spook::fabs(std::numeric_limits<double>::infinity()));
constexpr auto p_zero = +0.0;
CHECK_UNARY(p_zero == spook::fabs(-0.0));
CHECK_UNARY(p_zero == spook::fabs(+0.0));
constexpr auto expect = 3.141;
CHECK_UNARY(expect == spook::fabs(-3.141));
CHECK_UNARY(expect == spook::fabs(+3.141));
}
TEST_CASE("abs_test")
{
constexpr auto ullmax = spook::abs((std::numeric_limits<std::size_t>::max)());
CHECK_UNARY(0 == spook::abs(std::size_t(0)));
CHECK_UNARY(ullmax == spook::abs(ullmax));
CHECK_UNARY(0 == spook::abs(std::int64_t(0)));
constexpr auto sllmin = (std::numeric_limits<std::int64_t>::min)() + 1;
constexpr auto sllmax = (std::numeric_limits<std::int64_t>::max)();
CHECK_UNARY(-sllmin == spook::abs(sllmin));
CHECK_UNARY(sllmax == spook::abs(sllmax));
}
TEST_CASE("signbit_test")
{
CHECK_UNARY(spook::signbit(-1.0));
CHECK_UNARY_FALSE(spook::signbit(1.0));
constexpr auto inf = std::numeric_limits<double>::infinity();
CHECK_UNARY(spook::signbit(-inf));
CHECK_UNARY_FALSE(spook::signbit(inf));
//未対応
//CHECK_UNARY(spook::signbit(-0.0));
//CHECK_UNARY_FALSE(spook::signbit(0.0));
//constexpr auto nan = std::numeric_limits<double>::quiet_NaN();
//CHECK_UNARY(spook::signbit(-nan));
//CHECK_UNARY_FALSE(spook::signbit(nan));
}
TEST_CASE("copysign_test")
{
CHECK_EQ(+2.0, spook::copysign(2.0, +2.0));
CHECK_EQ(-2.0, spook::copysign(2.0, -2.0));
CHECK_EQ(+2.0, spook::copysign(-2.0, +2.0));
CHECK_EQ(-2.0, spook::copysign(-2.0, -2.0));
constexpr auto nan = std::numeric_limits<double>::quiet_NaN();
constexpr auto inf = std::numeric_limits<double>::infinity();
//Assert::IsTrue (spook::signbit(spook::copysign(nan, -2.0)));
//Assert::IsFalse(spook::signbit(spook::copysign(nan, +2.0)));
CHECK_UNARY(std::signbit(spook::copysign(nan, -2.0)));
CHECK_UNARY_FALSE(std::signbit(spook::copysign(nan, +2.0)));
CHECK_EQ(+inf, spook::copysign(inf, +2.0));
CHECK_EQ(-inf, spook::copysign(inf, -2.0));
}
TEST_CASE("ceil_test")
{
CHECK_UNARY(3.0 == spook::ceil(3.0));
CHECK_UNARY(4.0 == spook::ceil(3.1));
CHECK_UNARY(4.0 == spook::ceil(3.5));
CHECK_UNARY(4.0 == spook::ceil(3.9));
CHECK_UNARY(-3.0 == spook::ceil(-3.0));
CHECK_UNARY(-3.0 == spook::ceil(-3.1));
CHECK_UNARY(-3.0 == spook::ceil(-3.5));
CHECK_UNARY(-3.0 == spook::ceil(-3.9));
}
TEST_CASE("floor_test")
{
CHECK_UNARY(3.0 == spook::floor(3.0));
CHECK_UNARY(3.0 == spook::floor(3.1));
CHECK_UNARY(3.0 == spook::floor(3.5));
CHECK_UNARY(3.0 == spook::floor(3.9));
CHECK_UNARY(-3.0 == spook::floor(-3.0));
CHECK_UNARY(-4.0 == spook::floor(-3.1));
CHECK_UNARY(-4.0 == spook::floor(-3.5));
CHECK_UNARY(-4.0 == spook::floor(-3.9));
}
TEST_CASE("trunc_test")
{
CHECK_UNARY(3.0 == spook::trunc(3.0));
CHECK_UNARY(3.0 == spook::trunc(3.1));
CHECK_UNARY(3.0 == spook::trunc(3.5));
CHECK_UNARY(3.0 == spook::trunc(3.9));
CHECK_UNARY(-3.0 == spook::trunc(-3.0));
CHECK_UNARY(-3.0 == spook::trunc(-3.1));
CHECK_UNARY(-3.0 == spook::trunc(-3.5));
CHECK_UNARY(-3.0 == spook::trunc(-3.9));
}
TEST_CASE("roud_to_nearest_test")
{
CHECK_UNARY(3.0 == spook::round_to_nearest(3.0));
CHECK_UNARY(3.0 == spook::round_to_nearest(3.1));
CHECK_UNARY(4.0 == spook::round_to_nearest(3.5));
CHECK_UNARY(4.0 == spook::round_to_nearest(3.9));
CHECK_UNARY(-3.0 == spook::round_to_nearest(-3.0));
CHECK_UNARY(-3.0 == spook::round_to_nearest(-3.1));
CHECK_UNARY(-4.0 == spook::round_to_nearest(-3.5));
CHECK_UNARY(-4.0 == spook::round_to_nearest(-3.9));
}
TEST_CASE("remainder_test")
{
constexpr double eps = 1.0E-15;
{
auto expected = doctest::Approx(std::remainder(3.14, 3.0)).epsilon(eps);
constexpr auto r = spook::remainder(3.14, 3.0);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::remainder(5.0, 2.0)).epsilon(eps);
constexpr auto r = spook::remainder(5.0, 2.0);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::remainder(6.0, 4.0)).epsilon(eps);
constexpr auto r = spook::remainder(6.0, 4.0);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::remainder(6.3, 3.0)).epsilon(eps);
constexpr auto r = spook::remainder(6.3, 3.0);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::remainder(6.3, -3.0)).epsilon(eps);
constexpr auto r = spook::remainder(6.3, -3.0);
CHECK_EQ(expected, r);
}
{
auto expected = std::remainder(-6.3, 3.0);
constexpr auto r = spook::remainder(-6.3, 3.0);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::remainder(6.3, 3.15)).epsilon(eps);
constexpr auto r = spook::remainder(6.3, 3.15);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::remainder(6.0, 2.0)).epsilon(eps);
constexpr auto r = spook::remainder(6.0, 2.0);
CHECK_EQ(expected, r);
}
}
TEST_CASE("fmod_test") {
constexpr double eps = 1.0E-15;
{
auto expected = doctest::Approx(std::fmod(3.14, 3.0)).epsilon(eps);
constexpr auto r = spook::fmod(3.14, 3.0);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::fmod(5.0, 2.0)).epsilon(eps);
constexpr auto r = spook::fmod(5.0, 2.0);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::fmod(6.0, 4.0)).epsilon(eps);
constexpr auto r = spook::fmod(6.0, 4.0);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::fmod(6.3, 3.0)).epsilon(eps);
constexpr auto r = spook::fmod(6.3, 3.0);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::fmod(6.3, -3.0)).epsilon(eps);
constexpr auto r = spook::fmod(6.3, -3.0);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::fmod(-6.3, 3.0)).epsilon(eps);
constexpr auto r = spook::fmod(-6.3, 3.0);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::fmod(6.3, 3.15)).epsilon(eps);
constexpr auto r = spook::fmod(6.3, 3.15);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::fmod(6.0, 2.0)).epsilon(eps);
constexpr auto r = spook::fmod(6.0, 2.0);
CHECK_EQ(expected, r);
}
}
TEST_CASE("sin test") {
using namespace spook::constant;
constexpr double eps = 1.0E-15;
{
constexpr double coeff = 0.0;
auto expected = std::sin(coeff * pi<>);
constexpr auto calc = spook::sin(coeff * pi<>);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
constexpr double coeff = 0.25;
auto expected = std::sin(coeff * pi<>);
constexpr auto calc = spook::sin(coeff * pi<>);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
constexpr double coeff = 0.5;
auto expected = std::sin(coeff * pi<>);
constexpr auto calc = spook::sin(coeff * pi<>);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
constexpr double coeff = 0.75;
auto expected = std::sin(coeff * pi<>);
constexpr auto calc = spook::sin(coeff * pi<>);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
constexpr double coeff = 1.0;
auto expected = std::sin(coeff * pi<>);
constexpr auto calc = spook::sin(coeff * pi<>);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
constexpr double coeff = 1.25;
auto expected = std::sin(coeff * pi<>);
constexpr auto calc = spook::sin(coeff * pi<>);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
constexpr double coeff = 1.5;
auto expected = std::sin(coeff * pi<>);
constexpr auto calc = spook::sin(coeff * pi<>);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
constexpr double coeff = 1.75;
auto expected = std::sin(coeff * pi<>);
constexpr auto calc = spook::sin(coeff * pi<>);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
constexpr double coeff = 2.0;
auto expected = std::sin(coeff * pi<>);
constexpr auto calc = spook::sin(coeff * pi<>);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
}
TEST_CASE("cos test") {
using namespace spook::constant;
constexpr double eps = 1.0E-15;
{
constexpr double coeff = 0.0;
auto expected = std::cos(coeff * pi<>);
constexpr auto calc = spook::cos(coeff * pi<>);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
constexpr double coeff = 0.25;
auto expected = std::cos(coeff * pi<>);
constexpr auto calc = spook::cos(coeff * pi<>);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
constexpr double coeff = 0.5;
auto expected = std::cos(coeff * pi<>);
constexpr auto calc = spook::cos(coeff * pi<>);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
constexpr double coeff = 0.75;
auto expected = std::cos(coeff * pi<>);
constexpr auto calc = spook::cos(coeff * pi<>);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
constexpr double coeff = 1.0;
auto expected = std::cos(coeff * pi<>);
constexpr auto calc = spook::cos(coeff * pi<>);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
constexpr double coeff = 1.25;
auto expected = std::cos(coeff * pi<>);
constexpr auto calc = spook::cos(coeff * pi<>);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
constexpr double coeff = 1.5;
auto expected = std::cos(coeff * pi<>);
constexpr auto calc = spook::cos(coeff * pi<>);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
constexpr double coeff = 1.75;
auto expected = std::cos(coeff * pi<>);
constexpr auto calc = spook::cos(coeff * pi<>);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
constexpr double coeff = 2.0;
auto expected = std::cos(coeff * pi<>);
constexpr auto calc = spook::cos(coeff * pi<>);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
}
TEST_CASE("atan test") {
constexpr double eps = 1.0E-15;
{
auto expected = 4.0 * std::atan(1.0);
constexpr auto pi = 4.0 * spook::atan(1.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), pi);
}
{
auto expected = std::atan(-1.0);
constexpr auto calc = spook::atan(-1.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::atan(-0.75);
constexpr auto calc = spook::atan(-0.75);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::atan(-0.5);
constexpr auto calc = spook::atan(-0.5);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::atan(-0.25);
constexpr auto calc = spook::atan(-0.25);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::atan(0.0);
constexpr auto calc = spook::atan(0.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::atan(0.25);
constexpr auto calc = spook::atan(0.25);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::atan(0.5);
constexpr auto calc = spook::atan(0.5);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::atan(0.75);
constexpr auto calc = spook::atan(0.75);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::atan(1.0);
constexpr auto calc = spook::atan(1.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
}
TEST_CASE("atan2 test") {
constexpr double eps = 1.0E-15;
{
auto expected = std::atan2(0.0, 1.0);
constexpr auto calc = spook::atan2(0.0, 1.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::atan2(1.0, 1.0);
constexpr auto calc = spook::atan2(1.0, 1.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::atan2(1.0, 0.0);
constexpr auto calc = spook::atan2(1.0, 0.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::atan2(1.0, -1.0);
constexpr auto calc = spook::atan2(1.0, -1.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::atan2(0.0, -1.0);
constexpr auto calc = spook::atan2(0.0, -1.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::atan2(-1.0, -1.0);
constexpr auto calc = spook::atan2(-1.0, -1.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::atan2(-1.0, 0.0);
constexpr auto calc = spook::atan2(-1.0, 0.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::atan2(-1.0, 1.0);
constexpr auto calc = spook::atan2(-1.0, 1.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
}
TEST_CASE("float pow test")
{
constexpr double eps = 1.0E-15;
{
auto expected = doctest::Approx(std::pow(2.0, 0.5)).epsilon(eps);
constexpr auto r = spook::pow(2.0, 0.5);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::pow(3.0, 0.5)).epsilon(eps);
constexpr auto r = spook::pow(3.0, 0.5);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::pow(2.0, 2.0)).epsilon(eps);
constexpr auto r = spook::pow(2.0, 2.0);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::pow(2.0, 0.0)).epsilon(eps);
constexpr auto r = spook::pow(2.0, 0.0);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::pow(2.0, -0.5)).epsilon(eps);
constexpr auto r = spook::pow(2.0, -0.5);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::pow(3.0, -0.5)).epsilon(eps);
constexpr auto r = spook::pow(3.0, -0.5);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::pow(2.0, -2.0)).epsilon(eps);
constexpr auto r = spook::pow(2.0, -2.0);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::pow(1000.0, -2.0)).epsilon(eps);
constexpr auto r = spook::pow(1000.0, -2.0);
CHECK_EQ(expected, r);
}
{
auto expected = doctest::Approx(std::pow(1000.0, 2.0)).epsilon(1.0e-6);
constexpr auto r = spook::pow(1000.0, 2.0);
CHECK_EQ(expected, r);
}
}
TEST_CASE("sqrt test") {
constexpr double eps = 1.0E-15;
{
constexpr auto calc = spook::sqrt(-2.0);
CHECK_UNARY(spook::isnan(calc));
}
{
auto expected = std::sqrt(2.0);
constexpr auto calc = spook::sqrt(2.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::sqrt(3.0);
constexpr auto calc = spook::sqrt(3.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::sqrt(4.0);
constexpr auto calc = spook::sqrt(4.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::sqrt(8.0);
constexpr auto calc = spook::sqrt(8.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::sqrt(16.0);
constexpr auto calc = spook::sqrt(16.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::sqrt(32.0);
constexpr auto calc = spook::sqrt(32.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::sqrt(64.0);
constexpr auto calc = spook::sqrt(64.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::sqrt(128.0);
constexpr auto calc = spook::sqrt(128.0);
CHECK_EQ(doctest::Approx(expected).epsilon(1.0E-14), calc);
}
{
auto expected = std::sqrt(256.0);
constexpr auto calc = spook::sqrt(256.0);
CHECK_EQ(doctest::Approx(expected).epsilon(1.0E-14), calc);
}
{
auto expected = std::sqrt(512.0);
constexpr auto calc = spook::sqrt(512.0);
CHECK_EQ(doctest::Approx(expected).epsilon(1.0E-14), calc);
}
{
auto expected = std::sqrt(1024.0);
constexpr auto calc = spook::sqrt(1024.0);
CHECK_EQ(doctest::Approx(expected).epsilon(1.0E-14), calc);
}
}
TEST_CASE("cbrt test") {
constexpr double eps = 1.0E-15;
{
constexpr auto calc = spook::cbrt(-2.0);
CHECK_UNARY(spook::isnan(calc));
}
{
auto expected = std::cbrt(2.0);
constexpr auto calc = spook::cbrt(2.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::cbrt(3.0);
constexpr auto calc = spook::cbrt(3.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::cbrt(4.0);
constexpr auto calc = spook::cbrt(4.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::cbrt(8.0);
constexpr auto calc = spook::cbrt(8.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::cbrt(16.0);
constexpr auto calc = spook::cbrt(16.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::cbrt(32.0);
constexpr auto calc = spook::cbrt(32.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::cbrt(64.0);
constexpr auto calc = spook::cbrt(64.0);
CHECK_EQ(doctest::Approx(expected).epsilon(eps), calc);
}
{
auto expected = std::cbrt(128.0);
constexpr auto calc = spook::cbrt(128.0);
CHECK_EQ(doctest::Approx(expected).epsilon(1.0E-14), calc);
}
{
auto expected = std::cbrt(256.0);
constexpr auto calc = spook::cbrt(256.0);
CHECK_EQ(doctest::Approx(expected).epsilon(1.0E-14), calc);
}
{
auto expected = std::cbrt(512.0);
constexpr auto calc = spook::cbrt(512.0);
CHECK_EQ(doctest::Approx(expected).epsilon(1.0E-14), calc);
}
{
auto expected = std::cbrt(1024.0);
constexpr auto calc = spook::cbrt(1024.0);
CHECK_EQ(doctest::Approx(expected).epsilon(1.0E-14), calc);
}
}
TEST_CASE("lerp test") {
constexpr double start = 0.0;
constexpr double end = 10.0;
constexpr double eps = 1.0E-14;
CHECK_EQ(doctest::Approx(start), spook::lerp(start, end, 0.0));
CHECK_EQ(doctest::Approx(1.0).epsilon(eps), spook::lerp(start, end, 0.1));
CHECK_EQ(doctest::Approx(2.0).epsilon(eps), spook::lerp(start, end, 0.2));
CHECK_EQ(doctest::Approx(3.0).epsilon(eps), spook::lerp(start, end, 0.3));
CHECK_EQ(doctest::Approx(4.0).epsilon(eps), spook::lerp(start, end, 0.4));
CHECK_EQ(doctest::Approx(5.0).epsilon(eps), spook::lerp(start, end, 0.5));
CHECK_EQ(doctest::Approx(6.0).epsilon(eps), spook::lerp(start, end, 0.6));
CHECK_EQ(doctest::Approx(7.0).epsilon(eps), spook::lerp(start, end, 0.7));
CHECK_EQ(doctest::Approx(8.0).epsilon(eps), spook::lerp(start, end, 0.8));
CHECK_EQ(doctest::Approx(9.0).epsilon(eps), spook::lerp(start, end, 0.9));
CHECK_EQ(doctest::Approx(end), spook::lerp(start, end, 1.0));
CHECK_EQ(doctest::Approx(15.0).epsilon(eps), spook::lerp(start, end, 1.5));
CHECK_EQ(doctest::Approx(20.0).epsilon(eps), spook::lerp(start, end, 2.0));
CHECK_EQ(doctest::Approx(end), spook::lerp(end, end, 2.0));
}
}
namespace spook_test::complex {
TEST_CASE("polar test") {
using namespace spook::literals;
constexpr double eps = 1.0E-15;
{
auto expected = std::polar(1.0, 0.0_rad);
constexpr auto calc = spook::polar(1.0, 0.0_rad);
CHECK_EQ(doctest::Approx(expected.real()).epsilon(eps), calc.real());
CHECK_EQ(doctest::Approx(expected.imag()).epsilon(eps), calc.imag());
}
{
auto expected = std::polar(1.0, 45.0_rad);
constexpr auto calc = spook::polar(1.0, 45.0_rad);
CHECK_EQ(doctest::Approx(expected.real()).epsilon(eps), calc.real());
CHECK_EQ(doctest::Approx(expected.imag()).epsilon(eps), calc.imag());
}
{
auto expected = std::polar(1.0, 90.0_rad);
constexpr auto calc = spook::polar(1.0, 90.0_rad);
CHECK_EQ(doctest::Approx(expected.real()).epsilon(eps), calc.real());
CHECK_EQ(doctest::Approx(expected.imag()).epsilon(eps), calc.imag());
}
{
auto expected = std::polar(1.0, 135.0_rad);
constexpr auto calc = spook::polar(1.0, 135.0_rad);
CHECK_EQ(doctest::Approx(expected.real()).epsilon(eps), calc.real());
CHECK_EQ(doctest::Approx(expected.imag()).epsilon(eps), calc.imag());
}
{
auto expected = std::polar(1.0, 180.0_rad);
constexpr auto calc = spook::polar(1.0, 180.0_rad);
CHECK_EQ(doctest::Approx(expected.real()).epsilon(eps), calc.real());
CHECK_EQ(doctest::Approx(expected.imag()).epsilon(eps), calc.imag());
}
{
auto expected = std::polar(1.0, 225.0_rad);
constexpr auto calc = spook::polar(1.0, 225.0_rad);
CHECK_EQ(doctest::Approx(expected.real()).epsilon(eps), calc.real());
CHECK_EQ(doctest::Approx(expected.imag()).epsilon(eps), calc.imag());
}
{
auto expected = std::polar(1.0, 270.0_rad);
constexpr auto calc = spook::polar(1.0, 270.0_rad);
CHECK_EQ(doctest::Approx(expected.real()).epsilon(eps), calc.real());
CHECK_EQ(doctest::Approx(expected.imag()).epsilon(eps), calc.imag());
}
{
auto expected = std::polar(1.0, 315.0_rad);
constexpr auto calc = spook::polar(1.0, 315.0_rad);
CHECK_EQ(doctest::Approx(expected.real()).epsilon(eps), calc.real());
CHECK_EQ(doctest::Approx(expected.imag()).epsilon(eps), calc.imag());
}
{
auto expected = std::polar(1.0, 360.0_rad);
constexpr auto calc = spook::polar(1.0, 360.0_rad);
CHECK_EQ(doctest::Approx(expected.real()).epsilon(eps), calc.real());
CHECK_EQ(doctest::Approx(expected.imag()).epsilon(eps), calc.imag());
}
}
}
| 25.885157
| 80
| 0.639084
|
onihusube
|
32978f2c96f85d14786f950106852d31493ef573
| 12,880
|
cpp
|
C++
|
src/MainWindow.cpp
|
dankrusi/optimal-lunar-landing-analysis
|
ba23b718a4ce6e8277a28ef1da3ae89abd95e399
|
[
"MIT"
] | 5
|
2016-07-18T18:58:51.000Z
|
2021-11-17T11:24:44.000Z
|
src/MainWindow.cpp
|
dankrusi/optimal-lunar-landing-analysis
|
ba23b718a4ce6e8277a28ef1da3ae89abd95e399
|
[
"MIT"
] | null | null | null |
src/MainWindow.cpp
|
dankrusi/optimal-lunar-landing-analysis
|
ba23b718a4ce6e8277a28ef1da3ae89abd95e399
|
[
"MIT"
] | 1
|
2019-05-18T15:30:08.000Z
|
2019-05-18T15:30:08.000Z
|
/*
* Optimal Lunar Landing Analysis
* https://github.com/dankrusi/optimal-lunar-landing-analysis
*
* Contributor(s):
* Dan Krusi <dan.krusi@nerves.ch> (original author)
* Stephan Krusi <stephan.krusi@gmail> (co-author)
*
* 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 "MainWindow.h"
#include "ui_MainWindow.h"
#include <QGLWidget>
#include <QDebug>
#include <QFile>
#include <QByteArray>
#include <QDataStream>
#include <QGraphicsItemGroup>
#include <QGraphicsPixmapItem>
#include <QTimer>
#include <QAction>
#include <QFileDialog>
#include <QInputDialog>
#include <QScrollBar>
#include <QFontDatabase>
#include "SlopeAnalysisMap.h"
#include "ExponentialSlopeAnalysisMap.h"
#include "CombinedAnalysisMap.h"
#include "ElevationAnalysisMap.h"
#include "SpatialAnalysisMap.h"
#include "SlopeAnalysisMapO2.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
// Init
_tilesLoading = 0;
_tilesLoaded = 0;
_settings = new QSettings("OptimalLunarLandingAnalysis.config",QSettings::IniFormat,this);
_settings->setValue("first_run","false");
_settings->sync();
// GUI
ui->setupUi(this);
this->setWindowTitle("Optimal Lunar Landing Analysis");
ui->viewport->setMouseTracking(true);
ui->viewport->setInteractive(true);
ui->viewport->setMouseTracking(true);
ui->viewport->viewport()->setMouseTracking(true);
on_zoomResetButton_clicked(); // reset zoom button
// Status bar
_progressLabel = new QLabel("",this);
ui->statusBar->addPermanentWidget(_progressLabel);
// Actions
// Icons: http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
QMenu *menuFile = new QMenu(tr("&File"), this);
menuBar()->addMenu(menuFile);
registerAction(menuFile,tr("&Load Map..."),QIcon::fromTheme("document-open"),SLOT(openMapFile()));
//registerAction(menuFile,tr("&New Map..."),QIcon::fromTheme("document-new"),SLOT(newMapFile()));
registerAction(menuFile,tr("&Exit"),QIcon::fromTheme("application-exit"),SLOT(close()));
ui->mainToolBar->addSeparator();
QMenu *menuView = new QMenu(tr("&View"), this);
menuBar()->addMenu(menuView);
registerAction(menuView,tr("&Redraw"),QIcon::fromTheme("view-refresh"),SLOT(redrawViewport()));
registerAction(menuView,tr("&Zoom Out"),QIcon::fromTheme("zoom-out"),SLOT(on_zoomOutButton_clicked()));
registerAction(menuView,tr("&Zoom In"),QIcon::fromTheme("zoom-in"),SLOT(on_zoomInButton_clicked()));
registerAction(menuView,tr("&Zoom 1:1"),QIcon::fromTheme("zoom-original"),SLOT(on_zoomResetButton_clicked()));
registerAction(menuView,tr("&Center"),QIcon::fromTheme("go-home"),SLOT(centerViewport()));
// Scene
_scene = new ResponsiveGraphicsScene(this);
connect(_scene,SIGNAL(mouseMoved(int,int)),this,SLOT(viewportCursorMoved(int,int)));
connect(_scene,SIGNAL(mouseReleased()),this,SLOT(redrawViewport()));
// Accelerated graphics
if(_settings->value("use_opengl","false") == "true") ui->viewport->setViewport(new QGLWidget());
// Connections
//connect(ui->zoom,SIGNAL(sliderMoved(int)),this,SLOT(zoomViewport(int)));
// Autostart
QCoreApplication::processEvents();
QTimer::singleShot(100, this, SLOT(autoStart()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::registerDataMap(DataMap *map, bool visible) {
// Connections
connect(map,SIGNAL(tileLoading(MapTile*)),this,SLOT(tileLoading(MapTile*)));
connect(map,SIGNAL(tileLoaded(MapTile*)),this,SLOT(tileLoaded(MapTile*)));
connect(map,SIGNAL(mapLoading(double)),this,SLOT(mapLoading(double)));
// Load the map and register it
map->load();
_dataMaps.append(map);
// Update scene
map->layer()->setVisible(visible);
_scene->addItem(map->layer());
// Register in GUI
DataMapListWidgetItem *item = new DataMapListWidgetItem(map->name(),ui->dataMapsList);
item->setCheckState(visible ? Qt::Checked : Qt::Unchecked);
item->map = map;
}
void MainWindow::registerAnalysisMap(AnalysisMap *map) {
// Connections
connect(map,SIGNAL(tileLoading(MapTile*)),this,SLOT(tileLoading(MapTile*)));
connect(map,SIGNAL(tileLoaded(MapTile*)),this,SLOT(tileLoaded(MapTile*)));
connect(map,SIGNAL(mapLoading(double)),this,SLOT(mapLoading(double)));
// Load the map and register it
map->load();
_analysisMaps.append(map);
// Update scene
map->layer()->setVisible(false);
_scene->addItem(map->layer());
// Register in GUI
DataMapListWidgetItem *item = new DataMapListWidgetItem(map->name(),ui->analysisMapsList);
item->setCheckState(Qt::Unchecked);
item->map = map;
}
void MainWindow::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void MainWindow::registerAction(QMenu *menu, QString title, QIcon icon, const char *member) {
QAction *a;
a = new QAction(title, this);
a->setIcon(icon);
a->setPriority(QAction::LowPriority);
//a->setShortcut(QKeySequence::New);
connect(a, SIGNAL(triggered()), this, member);
ui->mainToolBar->addAction(a);
menu->addAction(a);
}
void MainWindow::autoStart() {
// Load the last opened map file
openMapFile(_settings->value("last_loaded_map","").toString());
}
void MainWindow::redrawViewport() {
ui->viewport->viewport()->update();
}
void MainWindow::showLoadProgress(int percent) {
ui->statusBar->showMessage(QString("Loading %1%").arg(percent));
}
void MainWindow::viewportCursorMoved(int x,int y) {
int elevation = _elevationDataMap->getElevationAtPoint(x,y);
LatLong latlong = _elevationDataMap->getLatLongAtPixel(x,y);
ui->statusBar->showMessage(QString("LatLong: %1,%2 / Pixel: %3,%4 / Elevation: %5m").arg(latlong.latitude).arg(latlong.longitude).arg(x).arg(y).arg(elevation));
}
void MainWindow::centerViewport() {
ui->viewport->horizontalScrollBar()->setValue(ui->viewport->horizontalScrollBar()->maximum()/2);
ui->viewport->verticalScrollBar()->setValue(ui->viewport->verticalScrollBar()->maximum()/2);
}
void MainWindow::updateLoadingStatus() {
int totalTiles = _tilesLoaded+_tilesLoading;
if(totalTiles == _tilesLoaded) {
this->setCursor(Qt::ArrowCursor);
ui->viewport->setCursor(Qt::ArrowCursor);
} else {
this->setCursor(Qt::BusyCursor);
ui->viewport->setCursor(Qt::BusyCursor);
}
_progressLabel->setText(QString("Loading tile %1/%2").arg(_tilesLoaded).arg(totalTiles));
}
void MainWindow::tileLoading(MapTile *tile) {
_tilesLoading++;
}
void MainWindow::tileLoaded(MapTile *tile) {
_tilesLoaded++;
_tilesLoading--;
this->redrawViewport();
updateLoadingStatus();
QCoreApplication::processEvents();
}
void MainWindow::mapLoading(double progress) {
int percent = (int)(progress*100);
_progressLabel->setText(QString("Loading map %1%").arg(percent));
QCoreApplication::processEvents();
}
void MainWindow::newMapFile() {
// Get the type
//TODO
qFatal("unsupported");
// Get image path
QString imagePath = QFileDialog::getOpenFileName(this,tr("Image File"), "", tr("Image Files (*.tif *.tiff *.png *.jpg *.bmp)"));
if(imagePath.isEmpty()) return;
// Get the color table
QString colorTablePath = QFileDialog::getOpenFileName(this,tr("Color Table File"), "", tr("Color Table Files (*.colortable)"));
if(colorTablePath.isEmpty()) return;
// Get tile size
bool ok;
int tileSize = QInputDialog::getInt(this, tr("New Map File"),tr("Tile size:"), 128, 64, 1024, 64, &ok);
if(!ok) return;
// Create new map file
QString mapPath = imagePath + ".map";
qDebug() << "Creating new map " << mapPath;
QFile::remove(mapPath);
QSettings settings(mapPath,QSettings::IniFormat,this);
settings.setValue("map_path",imagePath);
settings.setValue("colortable_path",colorTablePath);
settings.setValue("tile_size",tileSize);
settings.sync();
// Now load it...
openMapFile(mapPath);
}
void MainWindow::openMapFile() {
// Open file
QString filePath = QFileDialog::getOpenFileName(this,tr("Open Map"), "", tr("Map Files (*.map)"));
if(filePath.isEmpty()) return;
// Load it
openMapFile(filePath);
}
void MainWindow::openMapFile(QString filePath) {
// Check if exists
if(!QFile::exists(filePath)) return;
// Register as last used
_settings->setValue("last_loaded_map",filePath);
// Load maps
_colorReliefMap = new ColorReliefDataMap(filePath,_settings,this);
registerDataMap(_colorReliefMap,true);
_elevationDataMap = new ElevationDataMap(filePath,_settings,this);
registerDataMap(_elevationDataMap,false);
ElevationAnalysisMap *elevationAnalysisMap = new ElevationAnalysisMap(_elevationDataMap,_settings,this);
registerAnalysisMap(elevationAnalysisMap);
SlopeAnalysisMap *slopeMap = new SlopeAnalysisMap(_elevationDataMap,_settings,this);
registerAnalysisMap(slopeMap);
SlopeAnalysisMapO2 *slopeMapO2 = new SlopeAnalysisMapO2(_elevationDataMap,_settings,this);
registerAnalysisMap(slopeMapO2);
//ExponentialSlopeAnalysisMap *expSlopeMap = new ExponentialSlopeAnalysisMap(elevationAnalysisMap,_settings,this);
//registerAnalysisMap(expSlopeMap);
SpatialAnalysisMap *spatialAnalysisMap = new SpatialAnalysisMap(_elevationDataMap, _settings,this);
registerAnalysisMap(spatialAnalysisMap);
LargeSpatialAnalysisMap *largeSpatialAnalysisMap = new LargeSpatialAnalysisMap(_elevationDataMap, _settings,this);
registerAnalysisMap(largeSpatialAnalysisMap);
CombinedAnalysisMap *combinedMap = new CombinedAnalysisMap(_elevationDataMap,_settings,this);
//combinedMap->addMap(elevationAnalysisMap);
combinedMap->addMap(slopeMap);
combinedMap->addMap(spatialAnalysisMap);
registerAnalysisMap(combinedMap);
// Set maximum resolution
int maxRes = qLn(_elevationDataMap->tileSize())/qLn(2);
ui->resolutionSlider->setMinimum(0);
ui->resolutionSlider->setMaximum(maxRes);
// Update scene bounds
ui->viewport->setScene(_scene);
centerViewport();
}
void MainWindow::on_zoomSlider_valueChanged(int value) {
double scale = ((double)value / (double)ui->zoomSlider->maximum() + ZOOM_SLIDER_OFFSET);
if(scale > 1.0-ZOOM_SNAP_TOLERANCE && scale < 1.0+ZOOM_SNAP_TOLERANCE) scale = 1.0;
QTransform trans;
trans.scale(scale,scale);
ui->viewport->setTransform(trans,false);
ui->zoomLabel->setText(QString("Zoom: %1").arg(QString::number(scale,'f',1)));
}
void MainWindow::on_resolutionSlider_valueChanged(int value) {
// Init
int resolution = qPow(2,value);
// Show in gui
ui->resolutionLabel->setText(QString("Resolution: 1:%1").arg(resolution));
// Tell the maps
foreach(AnalysisMap *map,_analysisMaps) {
map->setResolution(resolution);
}
// Update
this->redrawViewport();
}
void MainWindow::on_zoomResetButton_clicked() {
int value = (ZOOM_RESET_RATIO - ZOOM_SLIDER_OFFSET) * ui->zoomSlider->maximum();
ui->zoomSlider->setValue(value);
}
void MainWindow::on_zoomInButton_clicked() {
ui->zoomSlider->setValue(ui->zoomSlider->value()+ZOOM_INCREMENT);
}
void MainWindow::on_zoomOutButton_clicked() {
ui->zoomSlider->setValue(ui->zoomSlider->value()-ZOOM_INCREMENT);
}
void MainWindow::on_dataMapsList_itemChanged(QListWidgetItem *item) {
DataMapListWidgetItem *dataMapItem = (DataMapListWidgetItem*)item;
if(dataMapItem->map) {
dataMapItem->map->layer()->setVisible(dataMapItem->checkState() == Qt::Checked);
redrawViewport();
}
}
void MainWindow::on_analysisMapsList_itemChanged(QListWidgetItem *item) {
on_dataMapsList_itemChanged(item);
}
| 33.11054
| 164
| 0.711724
|
dankrusi
|
32a8a84b70f8851bf17b3da0cf3441abda7c7c0a
| 1,345
|
cpp
|
C++
|
Chapter5/Exercise-5-14/main.cpp
|
kozborn/programing-principles-and-practise-using-cpp
|
7fefba8765e26af83f138e660861fe5b90adcda4
|
[
"MIT"
] | null | null | null |
Chapter5/Exercise-5-14/main.cpp
|
kozborn/programing-principles-and-practise-using-cpp
|
7fefba8765e26af83f138e660861fe5b90adcda4
|
[
"MIT"
] | null | null | null |
Chapter5/Exercise-5-14/main.cpp
|
kozborn/programing-principles-and-practise-using-cpp
|
7fefba8765e26af83f138e660861fe5b90adcda4
|
[
"MIT"
] | null | null | null |
#include "../../std_lib_facilities.h"
void print_vector(const vector<int> &vec) {
for (auto const &a : vec) {
cout << a << endl;
}
}
int main() {
cout << "Enter pairs (day temp) " << endl;
string day;
int temp;
vector<int> pon;
vector<int> tue;
vector<int> wed;
vector<int> thu;
vector<int> fri;
vector<int> sat;
vector<int> sun;
while(cin >> day && cin >> temp) {
cout << "Day: " << day << " : " << temp << endl;
transform(day.begin(), day.end(), day.begin(), ::tolower);
if (day.compare("pon") == 0 || day.compare("poniedzialek") == 0) {
pon.push_back(temp);
}
else if (day.compare("wto") == 0 || day.compare("wtorek") == 0)
{
tue.push_back(temp);
}
else if(day.compare("sro") == 0 || day.compare("sroda") == 0)
{
wed.push_back(temp);
}
else if (day.compare("czw") == 0 || day.compare("czwartek") == 0)
{
thu.push_back(temp);
}
else if (day.compare("pia") == 0 || day.compare("piatek") == 0)
{
fri.push_back(temp);
}
else if(day.compare("sob") == 0 || day.compare("sobota") == 0)
{
sat.push_back(temp);
}
else if (day.compare("ndz") == 0 || day.compare("niedziela") == 0)
{
sun.push_back(temp);
}
}
return 0;
}
| 23.189655
| 71
| 0.501115
|
kozborn
|
32aa6db4c59c08b5644f26fc487a56ac5f556f41
| 4,246
|
cpp
|
C++
|
src/widgets/keyboard.cpp
|
Windrill/GuiLite
|
6577199c1c56626ac2436af2392ddf65bb50e761
|
[
"Apache-2.0"
] | 6,304
|
2017-09-23T04:22:51.000Z
|
2022-03-31T05:49:57.000Z
|
src/widgets/keyboard.cpp
|
Windrill/GuiLite
|
6577199c1c56626ac2436af2392ddf65bb50e761
|
[
"Apache-2.0"
] | 41
|
2017-12-01T13:36:21.000Z
|
2022-03-22T08:16:13.000Z
|
src/widgets/keyboard.cpp
|
Windrill/GuiLite
|
6577199c1c56626ac2436af2392ddf65bb50e761
|
[
"Apache-2.0"
] | 764
|
2017-09-26T15:12:11.000Z
|
2022-03-31T08:49:25.000Z
|
#include "../widgets_include/keyboard.h"
#ifdef GUILITE_ON
static c_keyboard_button s_key_0, s_key_1, s_key_2, s_key_3, s_key_4, s_key_5, s_key_6, s_key_7, s_key_8, s_key_9;
static c_keyboard_button s_key_A, s_key_B, s_key_C, s_key_D, s_key_E, s_key_F, s_key_G, s_key_H, s_key_I, s_key_J;
static c_keyboard_button s_key_K, s_key_L, s_key_M, s_key_N, s_key_O, s_key_P, s_key_Q, s_key_R, s_key_S, s_key_T;
static c_keyboard_button s_key_U, s_key_V, s_key_W, s_key_X, s_key_Y, s_key_Z;
static c_keyboard_button s_key_dot, s_key_caps, s_key_space, s_key_enter, s_key_del, s_key_esc, s_key_num_switch;
WND_TREE g_key_board_children[] =
{
//Row 1
{&s_key_Q, 'Q', 0, POS_X(0), POS_Y(0), KEY_WIDTH, KEY_HEIGHT},
{&s_key_W, 'W', 0, POS_X(1), POS_Y(0), KEY_WIDTH, KEY_HEIGHT},
{&s_key_E, 'E', 0, POS_X(2), POS_Y(0), KEY_WIDTH, KEY_HEIGHT},
{&s_key_R, 'R', 0, POS_X(3), POS_Y(0), KEY_WIDTH, KEY_HEIGHT},
{&s_key_T, 'T', 0, POS_X(4), POS_Y(0), KEY_WIDTH, KEY_HEIGHT},
{&s_key_Y, 'Y', 0, POS_X(5), POS_Y(0), KEY_WIDTH, KEY_HEIGHT},
{&s_key_U, 'U', 0, POS_X(6), POS_Y(0), KEY_WIDTH, KEY_HEIGHT},
{&s_key_I, 'I', 0, POS_X(7), POS_Y(0), KEY_WIDTH, KEY_HEIGHT},
{&s_key_O, 'O', 0, POS_X(8), POS_Y(0), KEY_WIDTH, KEY_HEIGHT},
{&s_key_P, 'P', 0, POS_X(9), POS_Y(0), KEY_WIDTH, KEY_HEIGHT},
//Row 2
{&s_key_A, 'A', 0, ((KEY_WIDTH / 2) + POS_X(0)), POS_Y(1), KEY_WIDTH, KEY_HEIGHT},
{&s_key_S, 'S', 0, ((KEY_WIDTH / 2) + POS_X(1)), POS_Y(1), KEY_WIDTH, KEY_HEIGHT},
{&s_key_D, 'D', 0, ((KEY_WIDTH / 2) + POS_X(2)), POS_Y(1), KEY_WIDTH, KEY_HEIGHT},
{&s_key_F, 'F', 0, ((KEY_WIDTH / 2) + POS_X(3)), POS_Y(1), KEY_WIDTH, KEY_HEIGHT},
{&s_key_G, 'G', 0, ((KEY_WIDTH / 2) + POS_X(4)), POS_Y(1), KEY_WIDTH, KEY_HEIGHT},
{&s_key_H, 'H', 0, ((KEY_WIDTH / 2) + POS_X(5)), POS_Y(1), KEY_WIDTH, KEY_HEIGHT},
{&s_key_J, 'J', 0, ((KEY_WIDTH / 2) + POS_X(6)), POS_Y(1), KEY_WIDTH, KEY_HEIGHT},
{&s_key_K, 'K', 0, ((KEY_WIDTH / 2) + POS_X(7)), POS_Y(1), KEY_WIDTH, KEY_HEIGHT},
{&s_key_L, 'L', 0, ((KEY_WIDTH / 2) + POS_X(8)), POS_Y(1), KEY_WIDTH, KEY_HEIGHT},
//Row 3
{&s_key_caps, 0x14, 0, POS_X(0), POS_Y(2), CAPS_WIDTH, KEY_HEIGHT},
{&s_key_Z, 'Z', 0, ((KEY_WIDTH / 2) + POS_X(1)), POS_Y(2), KEY_WIDTH, KEY_HEIGHT},
{&s_key_X, 'X', 0, ((KEY_WIDTH / 2) + POS_X(2)), POS_Y(2), KEY_WIDTH, KEY_HEIGHT},
{&s_key_C, 'C', 0, ((KEY_WIDTH / 2) + POS_X(3)), POS_Y(2), KEY_WIDTH, KEY_HEIGHT},
{&s_key_V, 'V', 0, ((KEY_WIDTH / 2) + POS_X(4)), POS_Y(2), KEY_WIDTH, KEY_HEIGHT},
{&s_key_B, 'B', 0, ((KEY_WIDTH / 2) + POS_X(5)), POS_Y(2), KEY_WIDTH, KEY_HEIGHT},
{&s_key_N, 'N', 0, ((KEY_WIDTH / 2) + POS_X(6)), POS_Y(2), KEY_WIDTH, KEY_HEIGHT},
{&s_key_M, 'M', 0, ((KEY_WIDTH / 2) + POS_X(7)), POS_Y(2), KEY_WIDTH, KEY_HEIGHT},
{&s_key_del, 0x7F, 0, ((KEY_WIDTH / 2) + POS_X(8)), POS_Y(2), DEL_WIDTH, KEY_HEIGHT},
//Row 4
{&s_key_esc, 0x1B, 0, POS_X(0), POS_Y(3), ESC_WIDTH, KEY_HEIGHT},
{&s_key_num_switch, 0x90, 0, POS_X(2), POS_Y(3), SWITCH_WIDTH, KEY_HEIGHT},
{&s_key_space, ' ', 0, ((KEY_WIDTH / 2) + POS_X(3)), POS_Y(3), SPACE_WIDTH, KEY_HEIGHT},
{&s_key_dot, '.', 0, ((KEY_WIDTH / 2) + POS_X(6)), POS_Y(3), DOT_WIDTH, KEY_HEIGHT},
{&s_key_enter, '\n', 0, POS_X(8), POS_Y(3), ENTER_WIDTH, KEY_HEIGHT},
{0,0,0,0,0,0,0}
};
WND_TREE g_number_board_children[] =
{
{&s_key_1, '1', 0, POS_X(0), POS_Y(0), KEY_WIDTH, KEY_HEIGHT},
{&s_key_2, '2', 0, POS_X(1), POS_Y(0), KEY_WIDTH, KEY_HEIGHT},
{&s_key_3, '3', 0, POS_X(2), POS_Y(0), KEY_WIDTH, KEY_HEIGHT},
{&s_key_4, '4', 0, POS_X(0), POS_Y(1), KEY_WIDTH, KEY_HEIGHT},
{&s_key_5, '5', 0, POS_X(1), POS_Y(1), KEY_WIDTH, KEY_HEIGHT},
{&s_key_6, '6', 0, POS_X(2), POS_Y(1), KEY_WIDTH, KEY_HEIGHT},
{&s_key_7, '7', 0, POS_X(0), POS_Y(2), KEY_WIDTH, KEY_HEIGHT},
{&s_key_8, '8', 0, POS_X(1), POS_Y(2), KEY_WIDTH, KEY_HEIGHT},
{&s_key_9, '9', 0, POS_X(2), POS_Y(2), KEY_WIDTH, KEY_HEIGHT},
{&s_key_esc, 0x1B, 0, POS_X(0), POS_Y(3), KEY_WIDTH, KEY_HEIGHT},
{&s_key_0, '0', 0, POS_X(1), POS_Y(3), KEY_WIDTH, KEY_HEIGHT},
{&s_key_dot, '.', 0, POS_X(2), POS_Y(3), KEY_WIDTH, KEY_HEIGHT},
{&s_key_del, 0x7F, 0, POS_X(3), POS_Y(0), KEY_WIDTH, KEY_HEIGHT * 2 + 2},
{&s_key_enter,'\n', 0, POS_X(3), POS_Y(2), KEY_WIDTH, KEY_HEIGHT * 2 + 2},
{0,0,0,0,0,0,0}
};
#endif
| 55.868421
| 114
| 0.639425
|
Windrill
|
32af9a775e68698e366e0b194d7ea26ff17ee7b2
| 402
|
cpp
|
C++
|
374 Big Mod.cpp
|
zihadboss/UVA-Solutions
|
020fdcb09da79dc0a0411b04026ce3617c09cd27
|
[
"Apache-2.0"
] | 86
|
2016-01-20T11:36:50.000Z
|
2022-03-06T19:43:14.000Z
|
374 Big Mod.cpp
|
Mehedishihab/UVA-Solutions
|
474fe3d9d9ba574b97fd40ca5abb22ada95654a1
|
[
"Apache-2.0"
] | null | null | null |
374 Big Mod.cpp
|
Mehedishihab/UVA-Solutions
|
474fe3d9d9ba574b97fd40ca5abb22ada95654a1
|
[
"Apache-2.0"
] | 113
|
2015-12-04T06:40:57.000Z
|
2022-02-11T02:14:28.000Z
|
#include <iostream>
using namespace std;
// Don't need to use long long because the mod^2 is still containable by a signed int
int myPow(int b, int p, int m)
{
b = b % m;
int total = 1;
while (p)
{
if (p & 1)
total = (total * b) % m;
b = (b * b) % m;
p >>= 1;
}
return total;
}
int main()
{
int b, p, m;
while (cin >> b >> p >> m)
{
cout << myPow(b, p, m) << '\n';
}
}
| 12.181818
| 85
| 0.50995
|
zihadboss
|
32b17590918c4e6468ac9424a0b02e24a4cb98db
| 700
|
hpp
|
C++
|
Jimbo/Jimbo/graphics/renderer.hpp
|
BenStorey/Jimbo
|
937ff92a432fea2cb9a8e837d0e6839405f1a6c6
|
[
"MIT"
] | 3
|
2017-05-29T15:44:13.000Z
|
2019-08-24T09:15:09.000Z
|
Jimbo/Jimbo/graphics/renderer.hpp
|
BenStorey/Jimbo
|
937ff92a432fea2cb9a8e837d0e6839405f1a6c6
|
[
"MIT"
] | null | null | null |
Jimbo/Jimbo/graphics/renderer.hpp
|
BenStorey/Jimbo
|
937ff92a432fea2cb9a8e837d0e6839405f1a6c6
|
[
"MIT"
] | null | null | null |
#ifndef JIMBO_GRAPHICS_RENDERER_HPP
#define JIMBO_GRAPHICS_RENDERER_HPP
/////////////////////////////////////////////////////////
// Renderer.h
//
// Ben Storey
//
// More of a placeholder right now. The void* is obviously not ideal, but I don't want to build
// a whole lot of subclasses to implement a Renderer interface just now. We're always a GLFWwindow* so can cast to it
//
/////////////////////////////////////////////////////////
namespace jimbo
{
class Renderer
{
public:
Renderer(void* window) : window_(window) {}
void startRenderFrame();
void endRenderFrame();
private:
void* window_;
};
}
#endif // JIMBO_GRAPHICS_RENDERER_HPP
| 22.580645
| 118
| 0.568571
|
BenStorey
|
32b1a798b47ff61b1923e607f021ec86034d2b65
| 781
|
cpp
|
C++
|
cpp/071-080/Minimum Window Substring.cpp
|
KaiyuWei/leetcode
|
fd61f5df60cfc7086f7e85774704bacacb4aaa5c
|
[
"MIT"
] | 150
|
2015-04-04T06:53:49.000Z
|
2022-03-21T13:32:08.000Z
|
cpp/071-080/Minimum Window Substring.cpp
|
yizhu1012/leetcode
|
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
|
[
"MIT"
] | 1
|
2015-04-13T15:15:40.000Z
|
2015-04-21T20:23:16.000Z
|
cpp/071-080/Minimum Window Substring.cpp
|
yizhu1012/leetcode
|
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
|
[
"MIT"
] | 64
|
2015-06-30T08:00:07.000Z
|
2022-01-01T16:44:14.000Z
|
class Solution {
public:
string minWindow(string s, string t) {
unordered_map<char, int> dict;
int cnt = 0, start = 0, len = INT_MAX, first = 0;
for (char c : t) {
dict[c]++;
}
for (int i = 0; i < s.size(); i++) {
dict[s[i]]--;
if (dict[s[i]] >= 0) {
cnt++;
}
while (cnt == t.size()) {
dict[s[start]]++;
if (dict[s[start]] > 0) {
cnt--;
}
if (i - start + 1 < len) {
len = i - start + 1;
first = start;
}
start++;
}
}
return len == INT_MAX ? "" : s.substr(first, len);
}
};
| 26.931034
| 58
| 0.326504
|
KaiyuWei
|
32c67479a8a81724719a8da3447b38bfd7363513
| 2,166
|
cpp
|
C++
|
day01.cpp
|
Sayansree/gfg30
|
2cd4c1a2a553c045e660ab974b8054d3bce0df2b
|
[
"MIT"
] | 1
|
2021-02-05T13:41:58.000Z
|
2021-02-05T13:41:58.000Z
|
day01.cpp
|
Sayansree/gfg30
|
2cd4c1a2a553c045e660ab974b8054d3bce0df2b
|
[
"MIT"
] | null | null | null |
day01.cpp
|
Sayansree/gfg30
|
2cd4c1a2a553c045e660ab974b8054d3bce0df2b
|
[
"MIT"
] | null | null | null |
/*
/*Geek and his classmates are playing a prank on their Computer Science teacher. They change places every time the teacher turns to look at the blackboard.
Each of the N students in the class can be identified by a unique roll number X and each desk has a number i associated with it. Only one student can sit on one desk.
Each time the teacher turns her back, a student with roll number X sitting on desk number i gets up and takes the place of the student with roll number i.
If the current position of N students in the class is given to you in an array, such that i is the desk number and a[i] is the roll number of the student sitting on the desk, can you modify a[ ] to represent the next position of all the students ?
Example 1:
Input:
N = 6
a[] = {0, 5, 1, 2, 4, 3}
Output: 0 3 5 1 4 2
Explanation: After reshuffling, the modified
position of all the students would be
{0, 3, 5, 1, 4, 2}.
Example 2:
Input:
N = 5
a[] = {4, 3, 2, 1, 0}
Output: 0 1 2 3 4
Explanation: After reshuffling, the modified
position of all the students would be
{0, 1, 2, 3, 4}.
Your Task:
You dont need to read input or print anything. Complete the function prank() which takes the array a[ ] and its size N as input parameters and modifies the array in-place to reflect the new arrangement.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 105
0 ≤ a[i] ≤ N-1
*/
*/
// { Driver Code Starts
//Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution {
public:
void prank(long long a[], int n){
// code here
long long map[n];
for(int i=0;i<n;i++)
map[a[i]]=i;
for(long long i=0;i<n;i++)
a[map[map[i]]]=i;
}
};
// { Driver Code Starts.
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
long long a[n];
for(int i = 0 ;i<n;i++){
cin>>a[i];
}
Solution ob;
ob.prank(a,n);
for(int i = 0;i<n;i++)
cout<<a[i]<<" ";
cout<<"\n";
}
}
// } Driver Code Ends
| 24.337079
| 248
| 0.625115
|
Sayansree
|
32c8a86c58698e9d82358e4bf5fae3444fffe33b
| 1,227
|
cpp
|
C++
|
c++/containers/list_remove.cpp
|
DevNaga/c_cpp_book
|
c08ac6c62a98c701d512ac432df77385b51af97b
|
[
"Apache-2.0"
] | 1
|
2020-11-25T02:06:23.000Z
|
2020-11-25T02:06:23.000Z
|
c++/containers/list_remove.cpp
|
madmax440/c_cpp_book
|
c08ac6c62a98c701d512ac432df77385b51af97b
|
[
"Apache-2.0"
] | null | null | null |
c++/containers/list_remove.cpp
|
madmax440/c_cpp_book
|
c08ac6c62a98c701d512ac432df77385b51af97b
|
[
"Apache-2.0"
] | null | null | null |
/**
* Author Devendra Naga (devendra.aaru@gmail.com)
*
* License apache
*/
#include <list>
#include <string>
#include <iostream>
std::list<std::string>::const_iterator
find_element(std::list<std::string> &s, std::string _s)
{
std::list <std::string> :: const_iterator it;
for (it = s.begin(); it != s.end(); it ++) {
if (*it == _s) {
return it;
}
}
return s.end();
}
int main(int argc, char **argv)
{
std::list <std::string> s;
int i;
for (i = 1; i < argc; i ++) {
std::string t = {argv[i]};
s.push_back(t);
}
std::list <std::string> :: const_iterator it;
std::cout << "print elements " << std::endl;
i = 0;
for (it = s.begin(); it != s.end(); it ++) {
std::cout << "it " << *it << std::endl;
}
std::list <std::string> :: const_iterator it1;
it1 = find_element(s, "hello");
if (it1 != s.end()) {
std::cout << "element found " << *it1 << std::endl;
s.erase(it1);
for (it = s.begin(); it != s.end(); it ++) {
std::cout << "it " << *it << std::endl;
}
} else {
std::cout << "element could not found" << std::endl;
}
return 0;
}
| 18.876923
| 60
| 0.485738
|
DevNaga
|
32c8e0b6add848dc51e92f9445faa589e79c2556
| 3,640
|
cpp
|
C++
|
WRK-V1.2/csharp/shared/positiondata.cpp
|
intj-t/openvmsft
|
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
|
[
"Intel"
] | null | null | null |
WRK-V1.2/csharp/shared/positiondata.cpp
|
intj-t/openvmsft
|
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
|
[
"Intel"
] | null | null | null |
WRK-V1.2/csharp/shared/positiondata.cpp
|
intj-t/openvmsft
|
0d17fbce8607ab2b880be976c2e86d8cfc3e83bb
|
[
"Intel"
] | null | null | null |
// ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
#include "pch.h"
#include "posdata.h"
////////////////////////////////////////////////////////////////////////////////
POSDATA::POSDATA() : iChar(CHARMASK), iUserByte(0xff), iLine(LINEMASK), iUserBits(0xf)
{
}
////////////////////////////////////////////////////////////////////////////////
POSDATA::POSDATA (long i, long c) : iChar(c), iUserByte(0), iLine(i), iUserBits(0)
{
}
////////////////////////////////////////////////////////////////////////////////
bool POSDATA::Adjust (const POSDATA &posOld, const POSDATA &posNew)
{
ASSERT(!(this->IsUninitialized() || posOld.IsUninitialized() || posNew.IsUninitialized()));
// Nothing to adjust if the change is below us, or isn't really a change
if (posOld.iLine > iLine || posOld == posNew)
return false;
if (posOld.iLine == iLine)
{
// The old position is on the same line as us. If the
// char position is before us, update it.
if (posOld.iChar < iChar)
{
iChar += (posNew.iChar - posOld.iChar);
iLine = posNew.iLine;
return true;
}
return false;
}
// The line must be above us, so just update our line
iLine += (posNew.iLine - posOld.iLine);
return (posNew.iLine - posOld.iLine) ? true : false;
}
////////////////////////////////////////////////////////////////////////////////
long POSDATA::Compare (const POSDATA &p) const
{
ASSERT(!(this->IsUninitialized() || p.IsUninitialized()));
if (this->iLine == p.iLine)
return this->iChar - p.iChar;
return this->iLine - p.iLine;
}
////////////////////////////////////////////////////////////////////////////////
bool POSDATA::operator < (const POSDATA &p) const
{
return Compare (p) < 0;
}
////////////////////////////////////////////////////////////////////////////////
bool POSDATA::operator > (const POSDATA &p) const
{
return Compare (p) > 0;
}
////////////////////////////////////////////////////////////////////////////////
bool POSDATA::operator <= (const POSDATA &p) const
{
return Compare (p) <= 0;
}
////////////////////////////////////////////////////////////////////////////////
bool POSDATA::operator >= (const POSDATA &p) const
{
return Compare (p) >= 0;
}
////////////////////////////////////////////////////////////////////////////////
bool POSDATA::operator == (const POSDATA &p) const
{
return this->iLine == p.iLine && this->iChar == p.iChar;
}
////////////////////////////////////////////////////////////////////////////////
bool POSDATA::operator != (const POSDATA &p) const
{
return this->iLine != p.iLine || this->iChar != p.iChar;
}
////////////////////////////////////////////////////////////////////////////////
void POSDATA::SetUninitialized()
{
iChar = CHARMASK; iLine = LINEMASK;
}
////////////////////////////////////////////////////////////////////////////////
bool POSDATA::IsUninitialized () const
{
return ((iChar & CHARMASK) == CHARMASK) && ((iLine & LINEMASK) == LINEMASK);
}
////////////////////////////////////////////////////////////////////////////////
bool POSDATA::IsZero () const
{
return iLine == 0 && iChar == 0;
}
| 26.962963
| 95
| 0.437912
|
intj-t
|
32d3f75905f8f741f8b7216d7922fb313d8e1a88
| 1,023
|
cpp
|
C++
|
shared_model/backend/protobuf/commands/impl/proto_grant_permission.cpp
|
akshatkarani/iroha
|
5acef9dd74720c6185360d951e9b11be4ef73260
|
[
"Apache-2.0"
] | 1,467
|
2016-10-25T12:27:19.000Z
|
2022-03-28T04:32:05.000Z
|
shared_model/backend/protobuf/commands/impl/proto_grant_permission.cpp
|
akshatkarani/iroha
|
5acef9dd74720c6185360d951e9b11be4ef73260
|
[
"Apache-2.0"
] | 2,366
|
2016-10-25T10:07:57.000Z
|
2022-03-31T22:03:24.000Z
|
shared_model/backend/protobuf/commands/impl/proto_grant_permission.cpp
|
akshatkarani/iroha
|
5acef9dd74720c6185360d951e9b11be4ef73260
|
[
"Apache-2.0"
] | 662
|
2016-10-26T04:41:22.000Z
|
2022-03-31T04:15:02.000Z
|
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "backend/protobuf/commands/proto_grant_permission.hpp"
#include "backend/protobuf/permissions.hpp"
namespace shared_model {
namespace proto {
GrantPermission::GrantPermission(iroha::protocol::Command &command)
: grant_permission_{command.grant_permission()} {}
const interface::types::AccountIdType &GrantPermission::accountId() const {
return grant_permission_.account_id();
}
interface::permissions::Grantable GrantPermission::permissionName() const {
return permissions::fromTransport(grant_permission_.permission());
}
std::string GrantPermission::toString() const {
return detail::PrettyStringBuilder()
.init("GrantPermission")
.appendNamed("account_id", accountId())
.appendNamed("permission", permissions::toString(permissionName()))
.finalize();
}
} // namespace proto
} // namespace shared_model
| 30.088235
| 79
| 0.703812
|
akshatkarani
|
32d6c9fe109f8499a3ac3e150d6766a1336f79e6
| 1,256
|
cpp
|
C++
|
NbrhdNash/Scenes/scene_GameOver.cpp
|
OlavJDigranes/groupD
|
1d1fdd4ec0117162d777d0c020cbf4ae1718cf5f
|
[
"MIT"
] | null | null | null |
NbrhdNash/Scenes/scene_GameOver.cpp
|
OlavJDigranes/groupD
|
1d1fdd4ec0117162d777d0c020cbf4ae1718cf5f
|
[
"MIT"
] | null | null | null |
NbrhdNash/Scenes/scene_GameOver.cpp
|
OlavJDigranes/groupD
|
1d1fdd4ec0117162d777d0c020cbf4ae1718cf5f
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <thread>
#include "LevelSystem.h"
#include "scene_GameOver.h"
#include "scene_Level1.h"
#include "../lib_ecm/components/cmp_text.h"
#include "../game.h"
#include "SFML/Window.hpp"
#include "SFML/Window/Joystick.hpp"
using namespace std;
using namespace sf;
void GameOver::Load() {
tag = -3;
L1.cityAtmos.stop();
sf::Joystick::Identification joystickID = sf::Joystick::getIdentification(0);
auto esc = makeEntity();
esc->setPosition(Vector2f(5, 5));
if (Joystick::isConnected(0)) {
auto y = esc->addComponent<ESCTextComponent>("Press Start to exit the game");
}
else {
auto y = esc->addComponent<ESCTextComponent>("Press ESC to exit the game");
}
auto txt = makeEntity();
txt->addTag("GameOverText");
txt->setPosition(Vector2f(Engine::getWindowSize().x * 0.3, Engine::getWindowSize().y * 0.3));
auto y = txt->addComponent<RedTextComponent>("GAME OVER");
//Game over sound
gameOverBuffer.loadFromFile("res/music/GameOver.mp3");
gameOverSound.setBuffer(gameOverBuffer);
gameOverSound.setVolume(80);
gameOverSound.play();
setLoaded(true);
}
void GameOver::UnLoad() {
Scene::UnLoad();
}
void GameOver::Update(const double& dt) {
Scene::Update(dt);
}
void GameOver::Render() {
Scene::Render();
}
| 22.836364
| 94
| 0.710987
|
OlavJDigranes
|
32d9f30702116a90f8debd4ccd6330e2fdf285bc
| 13,540
|
cpp
|
C++
|
src/ncorr/Data2D.cpp
|
relinc/ncorr_cpp
|
1c04e78617d9354fbc9a3c07e28ef2bf98474b6f
|
[
"BSD-3-Clause"
] | null | null | null |
src/ncorr/Data2D.cpp
|
relinc/ncorr_cpp
|
1c04e78617d9354fbc9a3c07e28ef2bf98474b6f
|
[
"BSD-3-Clause"
] | 1
|
2017-11-22T00:08:35.000Z
|
2017-11-22T12:42:17.000Z
|
src/ncorr/Data2D.cpp
|
relinc/ncorr_cpp
|
1c04e78617d9354fbc9a3c07e28ef2bf98474b6f
|
[
"BSD-3-Clause"
] | 2
|
2019-07-17T07:27:48.000Z
|
2020-01-07T06:31:48.000Z
|
/*
* File: Data2D.cpp
* Author: justin
*
* Created on February 28, 2015, 8:57 PM
*/
#include "Data2D.h"
namespace ncorr {
// Additional constructors ---------------------------------------------------//
Data2D::Data2D(Array2D<double> A, const ROI2D &roi, difference_type scalefactor) :
scalefactor(scalefactor), roi(roi), A_ptr(std::make_shared<Array2D<double>>(std::move(A))) {
chk_scalefactor();
chk_data_roi_same_size();
}
Data2D::Data2D(Array2D<double> A, const ROI2D &roi) :
scalefactor(1), roi(roi), A_ptr(std::make_shared<Array2D<double>>(std::move(A))) {
chk_data_roi_same_size();
}
Data2D::Data2D(Array2D<double> A, difference_type scalefactor) :
scalefactor(scalefactor), roi(Array2D<bool>(A.height(), A.width(), true)), A_ptr(std::make_shared<Array2D<double>>(std::move(A))) {
chk_scalefactor();
}
Data2D::Data2D(Array2D<double> A) :
scalefactor(1), roi(Array2D<bool>(A.height(), A.width(), true)), A_ptr(std::make_shared<Array2D<double>>(std::move(A))) { }
// Static factory methods ----------------------------------------------------//
Data2D Data2D::load(std::ifstream &is) {
// Form empty Data2D then fill in values in accordance to how they are saved
Data2D data;
// Load scalefactor
is.read(reinterpret_cast<char*>(&data.scalefactor), std::streamsize(sizeof(difference_type)));
// Load roi
data.roi = ROI2D::load(is);
// Load A
data.A_ptr = std::make_shared<Array2D<double>>(Array2D<double>::load(is));
return data;
}
// Operators interface -------------------------------------------------------//
std::ostream& operator<<(std::ostream &os, const Data2D &data) {
os << "Array: " << '\n' << *data.A_ptr;
os << '\n' << "ROI: " << '\n' << data.roi;
os << '\n' << "scale factor: " << data.scalefactor;
return os;
}
//void imshow(const Data2D &data, Data2D::difference_type delay) {
// // Form buffer; set all values outside of ROI to slightly below minimum
// // value of data, then show it, this guarantees the area outside the ROI is
// // black.
// Array2D<double> A_buf = data.get_array();
// Array2D<double> A_data = A_buf(data.get_roi().get_mask());
// if (!A_data.empty()) {
// double A_min = min(A_data);
// // Subtract small amount so min value doesn't show as black.
// A_buf(~data.get_roi().get_mask()) = std::nextafter(A_min, A_min-1);
// }
// imshow(A_buf,delay);
//}
bool isequal(const Data2D &data1, const Data2D &data2) {
return isequal(data1.get_array(), data2.get_array()) &&
isequal(data1.get_roi(), data2.get_roi()) &&
data1.scalefactor == data2.scalefactor;
}
void save(const Data2D &data, std::ofstream &os) {
typedef Data2D::difference_type difference_type;
// Save scalefactor -> roi -> A
os.write(reinterpret_cast<const char*>(&data.scalefactor), std::streamsize(sizeof(difference_type)));
save(data.roi, os);
save(*data.A_ptr, os);
}
// Interpolator --------------------------------------------------------------//
Data2D::nlinfo_interpolator Data2D::get_nlinfo_interpolator(difference_type region_idx, INTERP interp_type) const {
return details::Data2D_nlinfo_interpolator(*this, region_idx, interp_type);
}
// Utility -------------------------------------------------------------------//
void Data2D::chk_scalefactor() const {
if (scalefactor < 1) {
throw std::invalid_argument("Attempted to form Data2D with scalefactor of: " + std::to_string(scalefactor) +
". scalefactor must be an integer of value 1 or greater.");
}
}
void Data2D::chk_data_roi_same_size() const {
if (A_ptr->height() != roi.height() || A_ptr->width() != roi.width()) {
throw std::invalid_argument("Attempted to form Data2D with Array2D of size: " + A_ptr->size_2D_string() +
" and ROI2D of size: " + roi.size_2D_string() + ". Sizes must be the same.");
}
}
namespace details {
struct sparse_tree_element final {
typedef ROI2D::difference_type difference_type;
// Constructor -------------------------------------------------------//
sparse_tree_element(difference_type p1, difference_type p2, difference_type val) : p1(p1), p2(p2), val(val) { }
// Arithmetic methods ------------------------------------------------//
bool operator<(const sparse_tree_element &b) const {
if (p2 == b.p2) {
return p1 < b.p1; // Sort by p1
}
else {
return p2 < b.p2; // Sort by p2 first
}
};
difference_type p1;
difference_type p2;
mutable difference_type val;
};
void add_to_sparse_tree(std::set<sparse_tree_element> &sparse_tree, const sparse_tree_element &ste) {
auto ste_it = sparse_tree.find(ste);
if (ste_it == sparse_tree.end()) {
// Val isnt in sparse_tree, so just insert it
sparse_tree.insert(ste);
}
else {
// Val is already in sparse_tree, so just modify the value
ste_it->val += ste.val;
}
}
Array2D<double>& inpaint_nlinfo(Array2D<double> &A, const ROI2D::region_nlinfo &nlinfo) {
typedef ROI2D::difference_type difference_type;
if (nlinfo.empty()) {
// No digital inpainting if nlinfo is empty
return A;
}
// Form mask ---------------------------------------------------------//
Array2D<bool> mask_nlinfo(A.height(), A.width());
fill(mask_nlinfo, nlinfo, true);
// Precompute inverse of nlinfo pixels' linear indices ---------------//
Array2D<difference_type> A_inv_loc(A.height(), A.width(), -1); // -1 indicates pixel in nlinfo.
difference_type inv_loc_counter = 0;
for (difference_type p2 = 0; p2 < mask_nlinfo.width(); ++p2) {
for (difference_type p1 = 0; p1 < mask_nlinfo.height(); ++p1) {
if (!mask_nlinfo(p1, p2)) {
A_inv_loc(p1, p2) = inv_loc_counter++;
}
}
}
// Cycle over Array and form constraints -----------------------------//
// Analyze points outside nlinfo AND boundary points
std::set<sparse_tree_element> sparse_tree;
std::vector<double> b;
for (difference_type p2 = 0; p2 < A_inv_loc.width(); ++p2) {
for (difference_type p1 = 0; p1 < A_inv_loc.height(); ++p1) {
// Corners don't have constraints
if ((p1 > 0 && p1 < A_inv_loc.height() - 1) || (p2 > 0 && p2 < A_inv_loc.width() - 1)) {
// Sides have special constraints
if (p1 == 0 || p1 == A_inv_loc.height() - 1) {
// Top or bottom
if (A_inv_loc(p1, p2 - 1) != -1 || A_inv_loc(p1, p2) != -1 || A_inv_loc(p1, p2 + 1) != -1) {
// Point of interest - add a constraint
b.push_back(0);
if (A_inv_loc(p1, p2 - 1) == -1) { b[b.size() - 1] -= A(p1, p2 - 1); }
else { add_to_sparse_tree(sparse_tree, { difference_type(b.size()) - 1, A_inv_loc(p1,p2 - 1), 1 }); }
if (A_inv_loc(p1, p2) == -1) { b[b.size() - 1] += 2 * A(p1, p2); }
else { add_to_sparse_tree(sparse_tree, { difference_type(b.size()) - 1, A_inv_loc(p1,p2), -2 }); }
if (A_inv_loc(p1, p2 + 1) == -1) { b[b.size() - 1] -= A(p1, p2 + 1); }
else { add_to_sparse_tree(sparse_tree, { difference_type(b.size()) - 1, A_inv_loc(p1,p2 + 1), 1 }); }
}
}
else if (p2 == 0 || p2 == A_inv_loc.width() - 1) {
// Left or right
if (A_inv_loc(p1 - 1, p2) != -1 || A_inv_loc(p1, p2) != -1 || A_inv_loc(p1 + 1, p2) != -1) {
// Point of interest - add a constraint
b.push_back(0);
if (A_inv_loc(p1 - 1, p2) == -1) { b[b.size() - 1] -= A(p1 - 1, p2); }
else { add_to_sparse_tree(sparse_tree, { difference_type(b.size()) - 1, A_inv_loc(p1 - 1,p2), 1 }); }
if (A_inv_loc(p1, p2) == -1) { b[b.size() - 1] += 2 * A(p1, p2); }
else { add_to_sparse_tree(sparse_tree, { difference_type(b.size()) - 1, A_inv_loc(p1,p2), -2 }); }
if (A_inv_loc(p1 + 1, p2) == -1) { b[b.size() - 1] -= A(p1 + 1, p2); }
else { add_to_sparse_tree(sparse_tree, { difference_type(b.size()) - 1, A_inv_loc(p1 + 1,p2), 1 }); }
}
}
else {
// Center
if (A_inv_loc(p1 - 1, p2) != -1 || A_inv_loc(p1 + 1, p2) != -1 || A_inv_loc(p1, p2) != -1 || A_inv_loc(p1, p2 - 1) != -1 || A_inv_loc(p1, p2 + 1) != -1) {
// Point of interest - add a constraint
b.push_back(0);
if (A_inv_loc(p1 - 1, p2) == -1) { b[b.size() - 1] -= A(p1 - 1, p2); }
else { add_to_sparse_tree(sparse_tree, { difference_type(b.size()) - 1, A_inv_loc(p1 - 1,p2), 1 }); }
if (A_inv_loc(p1 + 1, p2) == -1) { b[b.size() - 1] -= A(p1 + 1, p2); }
else { add_to_sparse_tree(sparse_tree, { difference_type(b.size()) - 1, A_inv_loc(p1 + 1,p2), 1 }); }
if (A_inv_loc(p1, p2) == -1) { b[b.size() - 1] += 4 * A(p1, p2); }
else { add_to_sparse_tree(sparse_tree, { difference_type(b.size()) - 1, A_inv_loc(p1,p2), -4 }); }
if (A_inv_loc(p1, p2 - 1) == -1) { b[b.size() - 1] -= A(p1, p2 - 1); }
else { add_to_sparse_tree(sparse_tree, { difference_type(b.size()) - 1, A_inv_loc(p1,p2 - 1), 1 }); }
if (A_inv_loc(p1, p2 + 1) == -1) { b[b.size() - 1] -= A(p1, p2 + 1); }
else { add_to_sparse_tree(sparse_tree, { difference_type(b.size()) - 1, A_inv_loc(p1,p2 + 1), 1 }); }
}
}
}
}
}
// Use sparse QR solver ----------------------------------------------//
// Note that later on maybe encapsulate free() into smart pointers. Make
// sure that cholmod_common is finished() last.
// Start CHOLMOD
cholmod_common c;
cholmod_l_start(&c);
// Allocate and fill A
cholmod_sparse *A_sparse = cholmod_l_allocate_sparse(b.size(), // height
inv_loc_counter, // width
sparse_tree.size(), // # of elements
true, // row indices are sorted
true, // it is packed
0, // symmetry (0 = unsymmetric)
CHOLMOD_REAL,
&c);
((SuiteSparse_long*)A_sparse->p)[inv_loc_counter] = sparse_tree.size(); // Set last element before tree gets erased
for (difference_type counter = 0, p2 = 0; p2 < inv_loc_counter; ++p2) {
((SuiteSparse_long*)A_sparse->p)[p2] = counter;
while (!sparse_tree.empty() && p2 == sparse_tree.begin()->p2) {
// Get first element
auto it_ste = sparse_tree.begin();
((SuiteSparse_long*)A_sparse->i)[counter] = it_ste->p1;
((double*)A_sparse->x)[counter] = it_ste->val;
sparse_tree.erase(it_ste); // delete element
++counter;
}
}
// Allocate and fill b
cholmod_dense *b_dense = cholmod_l_allocate_dense(b.size(), // Height
1, // Width
b.size(), // Leading dimension
CHOLMOD_REAL,
&c);
for (difference_type p = 0; p < difference_type(b.size()); ++p) {
((double*)b_dense->x)[p] = b[p];
}
// Solve and then fill results into inverse region of A
// Note that documentation was hard to understand so I've done no error
// checking here (i.e. for out of memory) so maybe fix this later.
cholmod_dense *x_dense = SuiteSparseQR<double>(A_sparse, b_dense, &c);
difference_type counter = 0;
for (difference_type p2 = 0; p2 < mask_nlinfo.width(); ++p2) {
for (difference_type p1 = 0; p1 < mask_nlinfo.height(); ++p1) {
if (!mask_nlinfo(p1, p2)) {
A(p1, p2) = ((double*)x_dense->x)[counter++];
}
}
}
// Free memory
cholmod_l_free_dense(&x_dense, &c);
cholmod_l_free_dense(&b_dense, &c);
cholmod_l_free_sparse(&A_sparse, &c);
// Finish cholmod
cholmod_l_finish(&c);
return A;
}
Data2D_nlinfo_interpolator::Data2D_nlinfo_interpolator(const Data2D &data, difference_type region_idx, INTERP interp_type) :
sub_data_ptr(std::make_shared<Array2D<double>>()),
sub_data_interp(sub_data_ptr->get_interpolator(interp_type)),
first_order_buf(3, 1),
scalefactor(data.get_scalefactor()),
nlinfo_top(),
nlinfo_left() {
// Perform digital inpainting of data contained in nlinfo first - this is
// mainly for biquintic interpolation or any other form that requires an
// image patch for interpolation near edge points.
// Get copy of nlinfo - copy needed because it is shift()'ed which alters it in-place.
auto nlinfo = data.get_roi().get_nlinfo(region_idx);
if (nlinfo.empty()) {
// If this nlinfo is empty, there is nothing to interpolate. Note
// this will still return a functional interpolator that will return
// NaNs.
return;
}
// Store bounds - this allows conversion of interpolation coords
// (p1, p2) to local coordinates
this->nlinfo_top = nlinfo.top;
this->nlinfo_left = nlinfo.left;
// Get sub_data array; use pinpainting so interpolation works nicely for
// boundary points.
sub_data_ptr = std::make_shared<Array2D<double>>(nlinfo.bottom - nlinfo.top + 2 * border + 1,
nlinfo.right - nlinfo.left + 2 * border + 1);
(*sub_data_ptr)({ border, sub_data_ptr->height() - border - 1 }, { border, sub_data_ptr->width() - border - 1 }) = data.get_array()({ nlinfo.top,nlinfo.bottom }, { nlinfo.left,nlinfo.right });
inpaint_nlinfo(*sub_data_ptr, nlinfo.shift(border - nlinfo.top, border - nlinfo.left));
// Get interpolator
sub_data_interp = sub_data_ptr->get_interpolator(interp_type);
}
}
}
| 42.180685
| 196
| 0.579321
|
relinc
|
32dc351944aab16c6866c138c56ef662f56fa005
| 935
|
cpp
|
C++
|
extern/llvm/tools/clang/test/SemaCXX/address-of.cpp
|
chip5441/clReflect
|
d366cced2fff9aefcfc5ec6a0c97ed6c827263eb
|
[
"MIT"
] | null | null | null |
extern/llvm/tools/clang/test/SemaCXX/address-of.cpp
|
chip5441/clReflect
|
d366cced2fff9aefcfc5ec6a0c97ed6c827263eb
|
[
"MIT"
] | 1
|
2020-02-22T09:59:21.000Z
|
2020-02-22T09:59:21.000Z
|
extern/llvm/tools/clang/test/SemaCXX/address-of.cpp
|
chip5441/clReflect
|
d366cced2fff9aefcfc5ec6a0c97ed6c827263eb
|
[
"MIT"
] | null | null | null |
// RUN: %clang_cc1 -fsyntax-only -verify %s
// PR clang/3175
void bar(int*);
class c {
int var;
static int svar;
void foo() {
bar(&var);
bar(&svar);
}
static void wibble() {
bar(&var); // expected-error{{invalid use of member 'var' in static member function}}
bar(&svar);
}
};
enum E {
Enumerator
};
void test() {
(void)&Enumerator; // expected-error{{address expression must be an lvalue or a function designator}}
}
template<int N>
void test2() {
(void)&N; // expected-error{{address expression must be an lvalue or a function designator}}
}
// PR clang/3222
void xpto();
void (*xyz)(void) = &xpto;
struct PR11066 {
static int foo(short);
static int foo(float);
void test();
};
void PR11066::test() {
int (PR11066::*ptr)(int) = & &PR11066::foo; // expected-error{{address expression must be an lvalue or a function designator}}
}
| 19.893617
| 129
| 0.608556
|
chip5441
|
77f900ea0cbd3fa5929d03bbd8b665a4d75c541f
| 5,959
|
cpp
|
C++
|
lib/storage/in_memory_storage.cpp
|
pmqtt/pmq
|
49f4b87c6c6dc5adfe7feab4ef3b2b73e0c435fb
|
[
"Apache-2.0"
] | 2
|
2019-09-08T11:59:05.000Z
|
2019-12-04T09:29:43.000Z
|
lib/storage/in_memory_storage.cpp
|
pmqtt/pmq
|
49f4b87c6c6dc5adfe7feab4ef3b2b73e0c435fb
|
[
"Apache-2.0"
] | 11
|
2019-06-08T20:13:58.000Z
|
2019-12-17T12:03:01.000Z
|
lib/storage/in_memory_storage.cpp
|
pmqtt/pmq
|
49f4b87c6c6dc5adfe7feab4ef3b2b73e0c435fb
|
[
"Apache-2.0"
] | 2
|
2019-12-04T08:06:27.000Z
|
2021-06-03T21:24:40.000Z
|
//
// Created by pmqtt on 2019-06-29.
//
#include <algorithm>
#include <lib/storage/in_memory_storage.hpp>
#include <lib/detail/string.hpp>
#include <lib/mqtt/message.hpp>
#include <random>
namespace {
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> dist(0, 1000);
}
void pmq::in_memory_storage::add_user(const std::string &name, const std::string &pwd) {
std::unique_lock<std::mutex> guard(mutex);
user_password_map[name] = pwd;
}
void pmq::in_memory_storage::add_subscriber(const std::string &client_id, std::string &topic) {
}
void pmq::in_memory_storage::remove_subcriber(const std::string &client_id, std::string &topic) {
}
bool pmq::in_memory_storage::check_user_password(const std::string &name, const std::string &pwd) {
std::unique_lock<std::mutex> guard(mutex);
return user_password_map[name] == pwd;
}
bool pmq::in_memory_storage::exist_user(const std::string &name) {
std::unique_lock<std::mutex> guard(mutex);
return user_password_map.count(name) > 0;
}
void pmq::in_memory_storage::add_client(const std::string & client_id) {
}
void pmq::in_memory_storage::add_client_subscription(const std::string & clientId,
const std::string & topic,
pmq::subscriber & sub){
}
void pmq::in_memory_storage::add_will_message(const std::string & client_id,const pmq::message & message){
}
pmq::message pmq::in_memory_storage::get_will_message(const std::string & client_id) {
std::unique_lock<std::mutex> guard(mutex);
if(this->will_messages.count(client_id) > 0){
return this->will_messages[client_id];
}
return pmq::message(" "," ",QOS_0);
}
void pmq::in_memory_storage::save_qos_two_message_id(const pmq::u_int16 &id, std::shared_ptr<pmq::mqtt_publish> &msg) {
std::unique_lock<std::mutex> guard(mutex);
this->message_storage[id] = msg;
}
std::shared_ptr<pmq::mqtt_publish> pmq::in_memory_storage::restore_qos_two_publish_msg(const pmq::u_int16 &id) {
std::unique_lock<std::mutex> guard(mutex);
if(this->message_storage.count(id) > 0){
auto result = this->message_storage[id];
this->message_storage.erase(id);
return result;
}
throw std::runtime_error("message id doesn't exists");
}
void pmq::in_memory_storage::save_qos_two_message_id(const std::string &id, const std::string &client_id) {
std::unique_lock<std::mutex> guard(mutex);
message_ids[client_id] = id;
}
std::string pmq::in_memory_storage::restore_qos_two_publish_msg(const std::string &client_id) {
std::unique_lock<std::mutex> guard(mutex);
if(this->message_ids.count(client_id) > 0){
auto result = this->message_ids[client_id];
this->message_ids.erase(client_id);
return result;
}
throw std::runtime_error("message id doesn't exists");
}
void pmq::in_memory_storage::add_client(std::shared_ptr<pmq::mqtt_connect> &client_connection) {
std::unique_lock<std::mutex> guard(mutex);
if(client_connection){
std::string client_id = client_connection->get_client_id();
if(client_connection->is_will_flag()){
if(will_messages.count(client_id) < 1){
pmq::QOS qos = pmq::create_qos_from_int(client_connection->get_will_qos());
will_messages[client_id] = pmq::message(client_connection->get_will_topic(),
client_connection->get_will_payload(),qos);
}else{
}
}
if(client_connections.count(client_id) < 1) {
client_connections[client_id] = client_connection;
}
}
}
void pmq::in_memory_storage::add_subscriber(const std::string &topic, const std::shared_ptr<pmq::subscriber> &subscriber) {
std::unique_lock<std::mutex> guard(mutex);
std::vector<std::string> topics = pmq::detail::split_topic(topic);
if(topics.size() > 2){
if(topics[0] == "$share"){
std::string group = topics[1];
std::vector<std::string> sub_topic;
std::string shared_topic;
for(std::size_t i = 2; i < topics.size();++i){
shared_topic += topics[i]+"/";
}
std::cout<<"insert:" <<group <<" ... "<<shared_topic<<std::endl;
this->shared_subscripted_clients[group].insert_subscriber(subscriber,shared_topic);
return;
}
}
this->subscripted_clients.insert_subscriber(subscriber,topic);
}
std::vector<std::shared_ptr<pmq::subscriber>> pmq::in_memory_storage::get_subscriber(const std::string &topic) {
std::unique_lock<std::mutex> guard(mutex);
std::vector<std::shared_ptr<pmq::subscriber>> vec = this->subscripted_clients.get_subscriber(topic);
for(auto x : this->shared_subscripted_clients){
auto tmp = x.second.get_subscriber(topic);
if(!tmp.empty()) {
int pos = static_cast<int>(dist(rng) % tmp.size());
if (pos < tmp.size()) {
vec.push_back(tmp[pos]);
}
}
}
return vec;
}
void pmq::in_memory_storage::add_retained_message(const std::shared_ptr<pmq::message> &msg) {
std::unique_lock<std::mutex> guard(mutex);
auto pred = [&](const std::shared_ptr<pmq::message> & item)->bool{
return item->get_topic() == msg->get_topic();
};
auto it = std::find_if(this->retained_messages.begin(),this->retained_messages.end(),pred);
if(it != this->retained_messages.end()) {
this->retained_messages.erase(it);
}
this->retained_messages.emplace_back(msg);
}
void pmq::in_memory_storage::remove_client(const std::string & client_id){
std::unique_lock<std::mutex> guard(mutex);
if(client_connections.count(client_id) < 1) {
client_connections.erase(client_id);
}
}
void pmq::in_memory_storage::insert_configuration_for_subscribers(const pmq::config_module & config){
cfg = config;
}
| 34.051429
| 123
| 0.662359
|
pmqtt
|
77fbdc4b43634e29fd10db24ec0ecc4ad9f82a1d
| 72
|
cpp
|
C++
|
SCRambl/AutoOperation.cpp
|
Deji69/SCRambl
|
cf6eb64272b4126094c77a720c2402ed47822a50
|
[
"MIT"
] | 5
|
2015-07-10T18:31:14.000Z
|
2021-12-31T18:35:10.000Z
|
SCRambl/AutoOperation.cpp
|
Deji69/SCRambl
|
cf6eb64272b4126094c77a720c2402ed47822a50
|
[
"MIT"
] | null | null | null |
SCRambl/AutoOperation.cpp
|
Deji69/SCRambl
|
cf6eb64272b4126094c77a720c2402ed47822a50
|
[
"MIT"
] | 2
|
2015-03-21T20:03:24.000Z
|
2021-09-18T02:46:26.000Z
|
#include "stdafx.h"
#include "AutoOperation.h"
using namespace SCRambl;
| 18
| 26
| 0.777778
|
Deji69
|
77ffb249731477fc03a1b1070ef129922d35b186
| 13,987
|
cc
|
C++
|
tests/system/src/subsystem_tests.cc
|
xiallc/pixie_sdk
|
a6cf38b0a0d73a55955f4f906f789ee16eb848d4
|
[
"Apache-2.0"
] | 2
|
2021-04-14T13:58:50.000Z
|
2021-08-09T19:42:25.000Z
|
tests/system/src/subsystem_tests.cc
|
xiallc/pixie_sdk
|
a6cf38b0a0d73a55955f4f906f789ee16eb848d4
|
[
"Apache-2.0"
] | 1
|
2021-08-31T10:32:07.000Z
|
2021-09-03T15:03:00.000Z
|
tests/system/src/subsystem_tests.cc
|
xiallc/pixie_sdk
|
a6cf38b0a0d73a55955f4f906f789ee16eb848d4
|
[
"Apache-2.0"
] | 1
|
2022-03-25T12:32:52.000Z
|
2022-03-25T12:32:52.000Z
|
/* SPDX-License-Identifier: Apache-2.0 */
/*
* Copyright 2021 XIA LLC, 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.
*/
/** @file subsystem_tests.cc
* @brief Part of the QA test suite to verify analog front end functionality.
*/
#include "pixie16app_export.h"
#include "pixie16app_globals.h"
#include "pixie16sys_export.h"
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iostream>
#include <signal.h>
#include <sstream>
#include <string>
//#include <unistd.h>
#include <math.h>
#include <windows.h>
using namespace std;
int test_analogfrontend(unsigned short nummodules);
double get_average(unsigned short* data, unsigned long numpnts);
double get_deviation(unsigned short* data, unsigned long numpnts, double avg);
int main(int argc, char* argv[]) {
unsigned short NumModules;
unsigned short* PXISlotMap;
char ComFPGAConfigFile[80];
char SPFPGAConfigFile[80];
char DSPCodeFile[80];
char DSPParFile[80];
char DSPVarFile[80];
char EEPROMFile[80];
char DummyFile[80];
char ErrMSG[256];
const char config[100] = "Configuration/.cfgPixie";
int retval = 0;
ifstream input;
char* temp = new char[80];
input.open(config, ios::in);
if (input.fail()) {
cout << "can't open the config file ! " << config << endl << flush;
return false;
}
input >> NumModules;
cout << "\n\n" << NumModules << " modules, in slots:";
input.getline(temp, 80);
PXISlotMap = new unsigned short[NumModules + 1];
for (int i = 0; i < NumModules; i++) {
input >> PXISlotMap[i];
input.getline(temp, 80);
cout << PXISlotMap[i] << " ";
}
//==== This code is necessary if modules are installed in two crates ====//
//input >> PXISlotMap[NumModules];
//input.getline (temp, 80);
//cout << PXISlotMap[NumModules] << " ";
cout << endl << "Firmware files: \n";
input >> ComFPGAConfigFile;
input.getline(temp, 80);
cout << "ComFPGAConfigFile: " << ComFPGAConfigFile << endl;
input >> SPFPGAConfigFile;
input.getline(temp, 80);
cout << "SPFPGAConfigFile: " << SPFPGAConfigFile << endl;
//input >> TrigFPGAConfigFile;
//input.getline (temp, 80);
//cout << "TrigFPGAConfigFile: " << TrigFPGAConfigFile << endl;
input >> DSPCodeFile;
input.getline(temp, 80);
cout << "DSPCodeFile: " << DSPCodeFile << endl;
input >> DSPParFile;
input.getline(temp, 80);
cout << "DSPParFile: " << DSPParFile << endl;
input >> DummyFile;
input.getline(temp, 80);
cout << "DummyFile: " << DummyFile << endl;
input >> EEPROMFile;
input.getline(temp, 80);
cout << "EEPROMFile: " << EEPROMFile << endl;
input >> DSPVarFile;
input.getline(temp, 80);
cout << "DSPVarFile: " << DSPVarFile << endl;
input.close();
input.clear();
////////////////////////////////////////////////////////////////////
cout << "-----------------------------------------\n";
cout << "Booting....\n";
retval = Pixie16InitSystem(NumModules, PXISlotMap, 0);
if (retval < 0) {
printf("*ERROR* Pixie16InitSystem failed, retval = %d", retval);
sprintf(ErrMSG, "*ERROR* Pixie16InitSystem failed, retval = %d", retval);
Pixie_Print_MSG(ErrMSG);
return (-1);
} else {
cout << "Init OK " << retval << endl;
}
retval = Pixie16BootModule(ComFPGAConfigFile, SPFPGAConfigFile, "", DSPCodeFile, DSPParFile,
DSPVarFile, NumModules, 0x7F);
if (retval < 0) {
printf("*ERROR* Pixie16BootModule failed, retval = %d", retval);
sprintf(ErrMSG, "*ERROR* Pixie16BootModule failed, retval = %d", retval);
Pixie_Print_MSG(ErrMSG);
return (-2);
} else {
cout << "Boot OK " << retval << endl;
}
//Pixie_Init_DSPVarAddress(DSPVarFile, 0);
//==== Test analog front end ====//
cout << "Testing analog front end " << endl;
retval = test_analogfrontend(NumModules);
return (1);
}
int test_analogfrontend(unsigned short nummodules) {
unsigned short m, n, i;
unsigned short ADCTrace[MAX_ADC_TRACE_LEN];
unsigned short ModSerNum[PRESET_MAX_MODULES];
unsigned short SN = 0;
unsigned long k, offsetdac;
double offsetvolts, avg, dev;
FILE* datfil[PRESET_MAX_MODULES];
char IOBytes[PRESET_MAX_MODULES][8192];
char ErrMSG[256], filnam[256];
double fftTrace[MAX_ADC_TRACE_LEN * 2];
double power[MAX_ADC_TRACE_LEN];
int retval;
// Check if nummodules is valid
if (nummodules > PRESET_MAX_MODULES) {
sprintf(
ErrMSG,
"*ERROR* (test_analogfrontend): nummodules %d exceeds maximum allowed number of modules %d",
nummodules, PRESET_MAX_MODULES);
Pixie_Print_MSG(ErrMSG);
return (-1);
}
// Read I2C-EEPROM of each module
for (k = 0; k < nummodules; k++) {
retval = I2CM24C64_Sequential_Read((unsigned short) k, 0, 8192, IOBytes[k]);
if (retval < 0) {
sprintf(
ErrMSG,
"*ERROR* (test_analogfrontend): Could not read I2C-EEPROM in Module=%ld; retval=%d",
k, retval);
Pixie_Print_MSG(ErrMSG);
return (-2);
}
SN = (unsigned short) (unsigned char) IOBytes[k][0] +
256 * (unsigned short) (unsigned char) IOBytes[k][1];
if (IOBytes[k][2] >= 11) {
ModSerNum[k] = SN;
} else {
ModSerNum[k] = (unsigned short) (unsigned char) IOBytes[k][0];
}
printf("Module S/N: %hu\n", ModSerNum[k]);
}
// Make output data files for all modules
for (k = 0; k < nummodules; k++) {
sprintf(filnam, "analogfrontend_test_mod#%hu.dat", ModSerNum[k]);
datfil[k] = fopen(filnam, "w");
if (datfil[k] == NULL) {
sprintf(ErrMSG, "*ERROR* (test_analogfrontend): can't open data file %s", filnam);
Pixie_Print_MSG(ErrMSG);
// Close files that were already opened
for (m = 0; m < k; m++) {
fclose(datfil[m]);
}
return (-3);
}
}
// Write module information to file
for (k = 0; k < nummodules; k++) {
fprintf(datfil[k], "Module serial number: %hu\n\n", ModSerNum[k]);
fprintf(datfil[k], "Module I2C-EEPROM information:\n");
for (m = 0; m < 8192; m++) {
fprintf(datfil[k], "%d\n", (unsigned char) IOBytes[k][m]);
}
}
// Going through each of the 65536 steps of the 16-bit DAC
for (k = 0; k < nummodules; k++) {
fprintf(datfil[k], "\nADC values vs. OffsetDAC steps\n\n");
}
for (k = 0; k < 65535; k++) {
offsetvolts = (double) k / 65536.0 * DAC_VOLTAGE_RANGE - DAC_VOLTAGE_RANGE / 2.0;
for (m = 0; m < nummodules; m++) {
for (n = 0; n < 16; n++) {
retval = Pixie16WriteSglChanPar("VOFFSET", offsetvolts, m, n);
if (retval < 0) {
sprintf(
ErrMSG,
"*ERROR* (test_analogfrontend): Pixie16WriteSglChanPar failed in mod %d, chan %d, retval=%d",
m, n, retval);
Pixie_Print_MSG(ErrMSG);
// Close all data files
for (i = 0; i < nummodules; i++) {
fclose(datfil[i]);
}
return (-4);
}
}
}
// Wait until the DACs are settled down
Sleep(15);
for (m = 0; m < nummodules; m++) {
retval = Pixie16AcquireADCTrace(m);
if (retval < 0) {
sprintf(
ErrMSG,
"*ERROR* (test_analogfrontend): Pixie16AcquireADCTrace failed in mod %d, retval=%d",
m, retval);
Pixie_Print_MSG(ErrMSG);
// Close all data files
for (i = 0; i < nummodules; i++) {
fclose(datfil[i]);
}
return (-5);
}
for (n = 0; n < 16; n++) {
retval = Pixie16ReadSglChanADCTrace(ADCTrace, MAX_ADC_TRACE_LEN, m, n);
if (retval < 0) {
sprintf(
ErrMSG,
"*ERROR* (test_analogfrontend): Pixie16ReadSglChanADCTrace failed in mod %d, chan %d, retval=%d",
m, n, retval);
Pixie_Print_MSG(ErrMSG);
// Close all data files
for (i = 0; i < nummodules; i++) {
fclose(datfil[i]);
}
return (-6);
}
retval = Pixie16IMbufferIO((unsigned int*) &offsetdac, 1,
(unsigned long) (OffsetDAC_Address[m] + n), MOD_READ, m);
if (retval < 0) {
sprintf(
ErrMSG,
"*ERROR* (test_analogfrontend): Pixie16IMbufferIO failed in mod %d, chan %d, retval=%d",
m, n, retval);
Pixie_Print_MSG(ErrMSG);
// Close all data files
for (i = 0; i < nummodules; i++) {
fclose(datfil[i]);
}
return (-7);
}
avg = get_average(ADCTrace, MAX_ADC_TRACE_LEN);
dev = get_deviation(ADCTrace, MAX_ADC_TRACE_LEN, avg);
fprintf(datfil[m], "%d\t%d\t%ld\t%f\t%f\n", m, n, offsetdac, avg, dev);
}
}
if (fmod((double) k, 1000.0) == 0.0) {
printf("DAC Steps %d DONE\n", (int) k);
sprintf(ErrMSG, "DAC Steps %d DONE", (int) k);
Pixie_Print_MSG(ErrMSG);
}
}
// Check FFT of ADC traces
for (k = 0; k < nummodules; k++) {
fprintf(datfil[k], "\nFFT of ADC Traces @ OffsetDAC = 32768\n\n");
}
// First set OffsetDAC to 32768
offsetvolts = 32768.0 / 65536.0 * DAC_VOLTAGE_RANGE - DAC_VOLTAGE_RANGE / 2.0;
for (m = 0; m < nummodules; m++) {
for (n = 0; n < 16; n++) {
retval = Pixie16WriteSglChanPar("VOFFSET", offsetvolts, m, n);
if (retval < 0) {
sprintf(
ErrMSG,
"*ERROR* (test_analogfrontend): Pixie16WriteSglChanPar failed in mod %d, chan %d, retval=%d",
m, n, retval);
Pixie_Print_MSG(ErrMSG);
// Close all data files
for (i = 0; i < nummodules; i++) {
fclose(datfil[i]);
}
return (-8);
}
}
}
// Wait until the DACs are settled down
Sleep(5);
for (m = 0; m < nummodules; m++) {
retval = Pixie16AcquireADCTrace(m);
if (retval < 0) {
sprintf(
ErrMSG,
"*ERROR* (test_analogfrontend): Pixie16AcquireADCTrace failed in mod %d, retval=%d",
m, retval);
Pixie_Print_MSG(ErrMSG);
// Close all data files
for (i = 0; i < nummodules; i++) {
fclose(datfil[i]);
}
return (-9);
}
for (n = 0; n < 16; n++) {
retval = Pixie16ReadSglChanADCTrace(ADCTrace, MAX_ADC_TRACE_LEN, m, n);
if (retval < 0) {
sprintf(
ErrMSG,
"*ERROR* (test_analogfrontend): Pixie16ReadSglChanADCTrace failed in mod %d, chan %d, retval=%d",
m, n, retval);
Pixie_Print_MSG(ErrMSG);
// Close all data files
for (i = 0; i < nummodules; i++) {
fclose(datfil[i]);
}
return (-10);
}
// Compute FFT of the acquired ADC trace
for (i = 0; i < MAX_ADC_TRACE_LEN; i++) {
fftTrace[i * 2] = (double) ADCTrace[i];
fftTrace[i * 2 + 1] = 0.0;
}
// Compute complex FFT
retval = Pixie16complexFFT(fftTrace, MAX_ADC_TRACE_LEN);
// Compute power
for (i = 0; i < MAX_ADC_TRACE_LEN; i++) {
power[i] = sqrt(pow(fftTrace[i * 2], 2.0) + pow(fftTrace[i * 2 + 1], 2.0)) /
(double) MAX_ADC_TRACE_LEN;
}
// clear out the DC offset
power[0] = 0.0;
// Write to the output file
for (i = 0; i < MAX_ADC_TRACE_LEN; i++) {
fprintf(datfil[m], "%d\t%d\t%f\n", m, n, power[i]);
}
}
}
// Close all data files
for (k = 0; k < nummodules; k++) {
fclose(datfil[k]);
}
return (0);
}
double get_average(unsigned short* data, unsigned long numpnts) {
double avg;
unsigned long k;
avg = 0.0;
for (k = 0; k < numpnts; k++) {
avg += data[k];
}
avg /= numpnts;
return avg;
}
double get_deviation(unsigned short* data, unsigned long numpnts, double avg) {
double dev;
unsigned long k;
dev = 0.0;
for (k = 0; k < numpnts; k++) {
dev += ((double) data[k] - avg) * ((double) data[k] - avg);
}
dev /= numpnts;
return dev;
}
| 33.223278
| 121
| 0.514692
|
xiallc
|
ae03c6442bc05122a457ba2559a07dbe6589544b
| 1,603
|
cc
|
C++
|
sejf.cc
|
maaku33/jnp-zadanie3
|
d84c93ed5328f03df1c4a5d9389a701091df9882
|
[
"MIT"
] | null | null | null |
sejf.cc
|
maaku33/jnp-zadanie3
|
d84c93ed5328f03df1c4a5d9389a701091df9882
|
[
"MIT"
] | null | null | null |
sejf.cc
|
maaku33/jnp-zadanie3
|
d84c93ed5328f03df1c4a5d9389a701091df9882
|
[
"MIT"
] | null | null | null |
#include "sejf.h"
#include <iostream>
#include <utility>
Sejf::Sejf (const std::string& napis, unsigned liczba)
: zawartosc(napis)
, dostepy(liczba)
, zmanipulowany(false)
, wlamanie(false)
{}
Sejf::Sejf (std::string&& napis, unsigned liczba)
: zawartosc(std::move(napis))
, dostepy(liczba)
, zmanipulowany(false)
, wlamanie(false)
{}
Sejf::Sejf (Sejf&& s)
: zawartosc(std::move(s.zawartosc))
, dostepy(s.dostepy)
, zmanipulowany(s.zmanipulowany)
, wlamanie(false)
{}
Sejf& Sejf::operator= (Sejf&& s) {
zawartosc = std::move(s.zawartosc);
dostepy = s.dostepy;
zmanipulowany = s.zmanipulowany;
wlamanie = s.wlamanie;
return *this;
}
Sejf& Sejf::operator+= (unsigned ile) {
if (dostepy + ile >= dostepy) {
dostepy += ile;
zmanipulowany = true;
}
return *this;
}
Sejf& Sejf::operator*= (unsigned ile) {
if (dostepy * ile >= dostepy) {
dostepy *= ile;
zmanipulowany = true;
}
return *this;
}
Sejf& Sejf::operator-= (unsigned ile) {
if (dostepy - ile <= dostepy) {
dostepy -= ile;
zmanipulowany = true;
}
return *this;
}
int16_t Sejf::operator[] (size_t indeks) {
if (indeks >= zawartosc.size())
return -1;
if (dostepy == 0) {
wlamanie = true;
return -1;
}
dostepy--;
return (int16_t)(unsigned char) zawartosc[indeks];
}
std::string Sejf::Kontroler::daj_napis() const {
if (sejf.wlamanie)
return WLAMANIE;
if (sejf.zmanipulowany)
return MANIPULACJA;
return OK;
}
| 21.092105
| 54
| 0.588272
|
maaku33
|
ae065777706151d545fb3fe7ad598225be100161
| 4,827
|
hpp
|
C++
|
spline.hpp
|
mdimura/SplineApprox
|
de558dcdf906d0a556e6ec0fa01bc9a039596c89
|
[
"MIT"
] | 1
|
2019-03-27T15:30:07.000Z
|
2019-03-27T15:30:07.000Z
|
spline.hpp
|
mdimura/SplineApprox
|
de558dcdf906d0a556e6ec0fa01bc9a039596c89
|
[
"MIT"
] | null | null | null |
spline.hpp
|
mdimura/SplineApprox
|
de558dcdf906d0a556e6ec0fa01bc9a039596c89
|
[
"MIT"
] | null | null | null |
#ifndef SPLINE_H
#define SPLINE_H
//#pragma GCC optimize("O3")
#include "polynomial.hpp"
#include <Eigen/Dense>
template <unsigned Deg> class Spline
{
private:
using MatrixDXf = Eigen::Matrix<float,Deg+1,Eigen::Dynamic>;
using MatrixXDf = Eigen::Matrix<float,Eigen::Dynamic,Deg+1>;
MatrixDXf c;
float xmin, xmax;
float invdx;
Spline() = default;
void setFromSorted(const Eigen::Matrix2Xf &sortedXY,
const unsigned NPieces);
inline float value(int i, float x) const;
static Eigen::VectorXf values(const Eigen::VectorXf& x, const MatrixXDf& cPerm);
public:
inline float value_unsafe(const float &x) const
{
int i = (x - xmin) * invdx;
assert(i >= 0);
assert(i < c.cols());
return value(i,x);
}
float value_or(const float &x, const float &defaultValue) const
{
if (x < xmin || x > xmax) {
return defaultValue;
}
int i = (x - xmin) * invdx;
return value(i,x);
}
float value_or(const float &x, const float defaultLeft, const float defaultRight) const
{
if (x < xmin) {
return defaultLeft;
}
if (x > xmax) {
return defaultRight;
}
int i = (x - xmin) * invdx;
return value(i,x);
}
Eigen::VectorXf values_unsafe(const Eigen::VectorXf& x) const;
unsigned maxAbsDiffArg(const Eigen::Matrix2Xf &xy) const
{
float max=0.0f;
unsigned arg=0;
for(unsigned i=0; i<xy.cols(); ++i) {
float diff=std::fabs(xy(1,i)-value_unsafe(xy(0,i)));
if(max<diff) {
max=diff;
arg=i;
}
}
return arg;
}
static Spline<Deg> fromSorted(const Eigen::Matrix2Xf &sortedXY,
const unsigned NPieces);
template <unsigned Nd>
friend std::ostream &operator<<(std::ostream &os,
const Spline<Nd> &spline);
};
template <unsigned Deg>
std::ostream &operator<<(std::ostream &os, const Spline<Deg> &spline)
{
for (int i = 0; i < spline.polynomials.size(); ++i) {
float dx = 1.0 / spline.invdx;
float from = spline.xmin + dx * i;
float to = from + dx;
os << '[' << from << ".." << to << "] " << spline.polynomials[i]
<< '\n';
}
return os;
}
template <unsigned int Deg>
Spline<Deg> Spline<Deg>::fromSorted(const Eigen::Matrix2Xf &sortedXY,
const unsigned NPieces)
{
Spline<Deg> sp;
sp.setFromSorted(sortedXY, NPieces);
return sp;
}
template <unsigned int Deg>
void Spline<Deg>::setFromSorted(const Eigen::Matrix2Xf &sortedXY,
const unsigned NPieces)
{
const int nPoints = sortedXY.cols();
assert(nPoints > Deg);
xmin = sortedXY(0, 0);
xmax = sortedXY(0, nPoints - 1);
constexpr float inf = std::numeric_limits<float>::infinity();
const float dx = nextafterf((xmax - xmin) / NPieces, inf);
invdx = 1.0f / dx;
assert((xmax - xmin) * invdx < NPieces);
c.resize(3,NPieces);
int iStart = 0;
for (int piece = 0; piece < NPieces - 1; ++piece) {
float xEnd = dx * (piece + 1) + xmin;
int iEnd = iStart;
while (sortedXY(0, iEnd) < xEnd) {
++iEnd;
}
int len = std::max(iEnd - iStart, int(Deg + 1));
Polynomial<Deg> p(sortedXY.middleCols(iStart, len));
c.col(piece) = p.c;
if (iEnd > iStart + Deg) {
iStart = std::min(int(nPoints - Deg - 1), iEnd);
}
}
Polynomial<Deg> p(sortedXY.middleCols(iStart, nPoints - iStart));
c.col(NPieces - 1) = p.c;
}
template<>
float Spline<0>::value(int i, float ) const
{
return c(0,i);
}
template<>
float Spline<1>::value(int i, float x) const
{
return c(0,i)+c(1,i)*x;
}
template<>
float Spline<2>::value(int i, float x) const
{
return c(0,i)+c(1,i)*x+c(2,i)*x*x;
}
template<unsigned int Deg>
float Spline<Deg>::value(int i, float x) const
{
float val=c(0,i)+c(1,i)*x+c(2,i)*x*x;
for (int e=3; e<=Deg; e++) {
val+=c(e,i)*std::pow(x,e);
}
return val;
}
template<unsigned int Deg>
Eigen::VectorXf Spline<Deg>::values_unsafe(const Eigen::VectorXf& x) const
{
//x<xmin is not verified at runtime!
assert(x.minCoeff()>=xmin);
const int maxCol=c.cols()-1;
const unsigned N=x.size();
Eigen::VectorXi idxs=((x.array()-xmin)*invdx).cast<int>().min(maxCol);
MatrixXDf slc(N,Deg+1);
for(int i=0; i<N; ++i) {
slc.row(i) = c.col(idxs(i));
}
return values(x,slc);
}
template<unsigned int Deg>
Eigen::VectorXf Spline<Deg>::values(const Eigen::VectorXf& x, const Spline::MatrixXDf& cPerm)
{
Eigen::VectorXf res=Spline<2>::values(x,cPerm);
for (int e=3; e<=Deg; ++e) {
res+=cPerm.col(e).cwiseProduct(x.array().pow(e).matrix());
}
return res;
}
template<>
Eigen::VectorXf Spline<2>::values(const Eigen::VectorXf& x, const Spline::MatrixXDf& cPerm)
{
return cPerm.col(0)+cPerm.col(1).cwiseProduct(x)+cPerm.col(2).cwiseProduct(x.cwiseAbs2());
}
template<>
Eigen::VectorXf Spline<1>::values(const Eigen::VectorXf& x, const Spline::MatrixXDf& cPerm)
{
return cPerm.col(0)+cPerm.col(1).cwiseProduct(x);
}
template<>
Eigen::VectorXf Spline<0>::values(const Eigen::VectorXf& x, const Spline::MatrixXDf& cPerm)
{
return cPerm.col(0);
}
#endif // SPLINE_H
| 24.135
| 93
| 0.654029
|
mdimura
|
ae0827467f5f3e39a9af5981761d64270a540ebe
| 4,601
|
cc
|
C++
|
comm/fiu_engine.cc
|
wahidHarb/rdp-1
|
73a0813d9a08f0aad34b56ba678167e6387b5e74
|
[
"Apache-2.0"
] | 112
|
2018-12-05T07:45:42.000Z
|
2022-01-24T11:28:11.000Z
|
comm/fiu_engine.cc
|
wahidHarb/rdp-1
|
73a0813d9a08f0aad34b56ba678167e6387b5e74
|
[
"Apache-2.0"
] | 2
|
2020-02-29T02:34:59.000Z
|
2020-05-12T06:34:29.000Z
|
comm/fiu_engine.cc
|
wahidHarb/rdp-1
|
73a0813d9a08f0aad34b56ba678167e6387b5e74
|
[
"Apache-2.0"
] | 88
|
2018-12-16T07:35:10.000Z
|
2022-03-09T17:41:16.000Z
|
//
//Copyright 2018 vip.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.
//
#include "fiu_engine.h"
namespace fiu {
// Printf debug info to stdout
#define LOG_INFO(x, args...) \
fprintf(stdout, "%s(%s:%d) "#x"\n", __func__, __FILE__, __LINE__, ##args)
#define LOG_FLUSH() fflush(stdout)
// Common request packet
#pragma pack(push)
#pragma pack(1)
struct ReqMsg {
uint32_t type_code_;
uint32_t status_code_;
uint32_t int_parameter_;
char keyword_[129];
char str_parameter_[33];
char reserved_[82];
explicit ReqMsg(void) : type_code_(0), status_code_(0), int_parameter_(0) {
memset(keyword_, 0x0, sizeof(keyword_));
memset(str_parameter_, 0x0, sizeof(str_parameter_));
}
};
#pragma pack(pop)
// Return error message
static std::string GetLastErrorMsg(int err) {
char err_msg[128] = {0x0};
return std::string(strerror_r(err, err_msg, sizeof(err_msg)));
}
enum { kShmSize = (1 << 20) };
// Each ReqMsg is 256 bytes, thus 1M shared memory can held up to
// 4K injection points; For each test case, this should be enough
static const char *g_fiu_shm_name = "/fiu.shm.keyword";
static int g_shm_fd = -1;
static void *g_shm_ptr = NULL;
static bool g_lib_inited = false;
pthread_once_t g_init_once = PTHREAD_ONCE_INIT;
// Open shm once
static void Init(void) {
assert(g_shm_ptr == NULL && g_shm_fd == -1);
// Open 1st
g_shm_fd = shm_open(g_fiu_shm_name, O_RDWR, 0666);
if (-1 == g_shm_fd) {
LOG_INFO("shm_open failed: (%s)", GetLastErrorMsg(errno).c_str());
return;
}
// ftruncate(fd_, kShmSize);
g_shm_ptr = mmap(0, kShmSize, PROT_READ | PROT_WRITE, MAP_SHARED, g_shm_fd, 0);
if (MAP_FAILED == g_shm_ptr) {
LOG_INFO("mmap failed: (%s)", GetLastErrorMsg(errno).c_str());
return;
}
uint32_t idx = *(uint32_t *)g_shm_ptr;
LOG_INFO("(%u) sync points already exist", idx);
// Encountered corrupted share memory
if (sizeof(uint32_t) + idx * sizeof(ReqMsg) > kShmSize) {
LOG_INFO("shm corrupted");
LOG_FLUSH();
assert(0);
}
g_lib_inited = true;
}
// Create shm once
bool Open(void) {
int ret = 0;
ret = pthread_once(&g_init_once, &Init);
if (0 != ret) {
LOG_INFO("pthread_once failed: (%s)", GetLastErrorMsg(ret).c_str());
LOG_FLUSH();
assert(0);
}
return g_lib_inited;
}
// Destroy shm if exist
void Close() {
if (NULL != g_shm_ptr) {
// TODO: Do we need to unmap ?
if (-1 == munmap(g_shm_ptr, kShmSize)) {
LOG_INFO("munmap failed: (%s)", GetLastErrorMsg(errno).c_str());
}
}
}
// Check if a sync point exists
bool IsSyncPointExist(const char *sp) {
assert(sp);
// Check if dbug instance had been initiated
if (NULL == g_shm_ptr || !g_lib_inited) {
// LOG_INFO("dbug instance NOT initiated");
return false;
}
// Encountered corrupted share memory
uint32_t idx = *(uint32_t *)g_shm_ptr;
if (sizeof(uint32_t) + idx * sizeof(ReqMsg) > kShmSize) {
LOG_INFO("shm corrupted");
LOG_FLUSH();
assert(0);
}
// Check if specified key already exist
ReqMsg *p =
(ReqMsg *)((char *)g_shm_ptr + sizeof(uint32_t));
for (uint32_t i = 0; i < idx; i++, p++) {
if (0 == strncasecmp(p->keyword_, sp, 128)) {
if (0 == p->int_parameter_++) {
return true;
} else {
return false;
}
}
}
// LOG_INFO("sync point (%s) NOT found", sp);
return false;
}
bool IsSyncPointSet(const char *sp) {
assert(sp);
// Check if dbug instance had been initiated
if (NULL == g_shm_ptr || !g_lib_inited) {
// LOG_INFO("dbug instance NOT initiated");
return false;
}
// Encountered corrupted share memory
uint32_t idx = *(uint32_t *)g_shm_ptr;
if (sizeof(uint32_t) + idx * sizeof(ReqMsg) > kShmSize) {
LOG_INFO("shm corrupted");
LOG_FLUSH();
assert(0);
}
// Check if specified key already exist
ReqMsg *p =
(ReqMsg *)((char *)g_shm_ptr + sizeof(uint32_t));
for (uint32_t i = 0; i < idx; i++, p++) {
if (0 == strncasecmp(p->keyword_, sp, 128)) {
return true;
}
}
// LOG_INFO("sync point (%s) NOT found", sp);
return false;
}
} // namespace fiu
| 26.595376
| 117
| 0.656162
|
wahidHarb
|
ae0b7717db104999a6dcf04f8819f7f54ba85dc6
| 7,707
|
cpp
|
C++
|
examples/file_server/main.cpp
|
Garcia6l20/g6-web
|
6e9a1f9d85f26a977407d4c895f357e5f045efb9
|
[
"MIT"
] | 3
|
2021-05-16T11:37:59.000Z
|
2022-01-30T13:52:59.000Z
|
examples/file_server/main.cpp
|
Garcia6l20/g6-web
|
6e9a1f9d85f26a977407d4c895f357e5f045efb9
|
[
"MIT"
] | null | null | null |
examples/file_server/main.cpp
|
Garcia6l20/g6-web
|
6e9a1f9d85f26a977407d4c895f357e5f045efb9
|
[
"MIT"
] | 1
|
2021-11-06T12:36:37.000Z
|
2021-11-06T12:36:37.000Z
|
#include <spdlog/spdlog.h>
#include <g6/http/client.hpp>
#include <g6/http/router.hpp>
#include <g6/http/server.hpp>
#include <g6/io/context.hpp>
#include <unifex/scope_guard.hpp>
#include <unifex/sync_wait.hpp>
#include <unifex/task.hpp>
#include <unifex/when_all.hpp>
#include <ranges>
using namespace g6;
namespace fs = std::filesystem;
namespace rng = std::ranges;
static constexpr std::string_view list_dir_template_ = R"(
<!DOCTYPE html>
<html lang="en">
<head lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">
<title>{title}</title>
</head>
<body class="bg-light">
<div class="container">
<div class="py-5 text-center">
<h2>G6 File Server</h2>
<p class="lead">{path}</p>
</div>
<nav aria-label="breadcrumb"><ol class="breadcrumb">{breadcrumb}</ol></nav>
{body}
</div>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script>
</body>
</html>
)";
fmt::memory_buffer make_body(const fs::path &root, std::string_view path) {
auto link_path = fs::relative(path, root).string();
if (link_path.empty()) link_path = ".";
fmt::memory_buffer out;
fmt::format_to(out, R"(<div class="list-group">)");
for (auto &p : fs::directory_iterator(root / path)) {
fmt::format_to(out, R"(<a class="list-group-item-action" href="/{link_path}">{path}</a>)",
fmt::arg("path", fs::relative(p.path(), p.path().parent_path()).c_str()),
fmt::arg("link_path", fs::relative(p.path(), root).c_str()));
}
fmt::format_to(out, "</div>");
return out;
}
fmt::memory_buffer make_breadcrumb(std::string_view path) {
fmt::memory_buffer buff;
constexpr std::string_view init = R"(<li class="breadcrumb-item"><a href="/">Home</a></li>)";
buff.append(std::begin(init), std::end(init));
fs::path p = path;
std::vector<std::string> elems = {
{fmt::format(R"(<li class="breadcrumb-item active" aria-current="page"><a href="/{}">{}</a></li>)", p.string(),
p.filename().c_str())}};
p = p.parent_path();
while (not p.filename().empty()) {
elems.emplace_back(
fmt::format(R"(<li class="breadcrumb-item"><a href="/{}">{}</a></li>)", p.string(), p.filename().c_str()));
p = p.parent_path();
}
for (auto &elem : elems | std::views::reverse) { fmt::format_to(buff, "{}", elem); }
return buff;
}
namespace {
inplace_stop_source g_stop_source{};
}
#include <csignal>
void terminate_handler(int) {
g_stop_source.request_stop();
spdlog::info("stop requested !");
}
int main(int argc, char **argv) {
io::context context{};
std::signal(SIGINT, terminate_handler);
std::signal(SIGTERM, terminate_handler);
std::signal(SIGUSR1, terminate_handler);
auto server = web::make_server(context, web::proto::http, *net::ip_endpoint::from_string("127.0.0.1:0"));
auto server_endpoint = *server.socket.local_endpoint();
fs::path root_path = ".";
spdlog::info("server listening at: http://{}", server_endpoint.to_string());
auto router = router::router{
std::make_tuple(),// global context
http::route::get<R"(/(.*))">(
[&](std::string_view path, router::context<http::server_session<net::async_socket>> session,
router::context<http::server_request<net::async_socket>> request) -> task<void> {
spdlog::info("get: {}", path);
if (fs::is_directory(root_path / path)) {
fmt::memory_buffer body;
try {
body = make_body(root_path, path);
} catch (fs::filesystem_error &error) {
auto err_page = fmt::format(R"(<div><h6>Not found</h6><p>{}</p></div>)", error.what());
co_await net::async_send(*session, http::status::not_found,
as_bytes(span{err_page.data(), err_page.size()}));
}
auto breadcrumb = make_breadcrumb(path);
auto page = fmt::format(
list_dir_template_, fmt::arg("title", path),
fmt::arg("body", std::string_view{body.data(), body.size()}), fmt::arg("path", path),
fmt::arg("breadcrumb", std::string_view{breadcrumb.data(), breadcrumb.size()}));
co_await net::async_send(*session, http::status::ok, as_bytes(span{page.data(), page.size()}));
} else {
try {
auto file = open_file_read_only(context.get_scheduler(), root_path / path);
http::headers headers{{"Transfer-Encoding", "chunked"}};
auto stream = co_await net::async_send(*session, http::status::ok, std::move(headers));
std::array<char, 1024> data{};
size_t offset = 0;
while (size_t bytes =
co_await async_read_some_at(file, offset, as_writable_bytes(span{data}))) {
offset += bytes;
co_await net::async_send(stream, as_bytes(span{data.data(), bytes}));
}
co_await net::async_send(stream);// close stream
} catch (std::system_error &error) {
auto err_page = fmt::format(R"(<div><h6>Not found</h6><p>{}</p></div>)", error.what());
co_await net::async_send(*session, http::status::not_found,
as_bytes(span{err_page.data(), err_page.size()}));
}
}
}),
router::on<R"(.*)">(
[](router::context<http::server_session<net::async_socket>> session,
router::context<http::server_request<net::async_socket>> request) -> task<void> {
spdlog::info("unhandled: {} {}", request->url(), request->method());
std::string_view not_found = R"(<div><h6>Not found</h6><p>{}</p></div>)";
co_await net::async_send(*session, http::status::not_found,
as_bytes(span{not_found.data(), not_found.size()}));
})};
sync_wait(when_all(
[&]() -> task<void> {
co_await web::async_serve(server, g_stop_source, [&]<typename Session>(Session &session) {
return [root_path, &session, &router]<typename Request>(Request request) mutable -> task<void> {
co_await router(request.url(), request.method(), std::ref(request), std::ref(session));
while (net::has_pending_data(request)) {
co_await net::async_recv(request);// flush unused body
}
};
});
spdlog::info("terminated !");
}(),
[&]() -> task<void> {
context.run(g_stop_source.get_token());
co_return;
}()));
}
| 46.709091
| 218
| 0.563124
|
Garcia6l20
|
ae0df01395046443388103c3066066d2a57dd2c5
| 1,981
|
hpp
|
C++
|
3rdparty/libkdtree++_0.7.0/kdtree++/function.hpp
|
rukletsov/bo
|
bfece9e8f910b0c8f522733854405bf0a801b0e8
|
[
"BSD-2-Clause"
] | 3
|
2016-09-14T03:30:30.000Z
|
2021-11-16T10:53:32.000Z
|
3rdparty/libkdtree++_0.7.0/kdtree++/function.hpp
|
rukletsov/bo
|
bfece9e8f910b0c8f522733854405bf0a801b0e8
|
[
"BSD-2-Clause"
] | null | null | null |
3rdparty/libkdtree++_0.7.0/kdtree++/function.hpp
|
rukletsov/bo
|
bfece9e8f910b0c8f522733854405bf0a801b0e8
|
[
"BSD-2-Clause"
] | null | null | null |
/** \file
* Defines the various functors and interfaces used for KDTree.
*
* \author Martin F. Krafft <libkdtree@pobox.madduck.net>
* \author Sylvain Bougerel <sylvain.bougerel.devel@gmail.com>
*/
#ifndef INCLUDE_KDTREE_ACCESSOR_HPP
#define INCLUDE_KDTREE_ACCESSOR_HPP
#include <cstddef>
namespace bo {
template <typename _Val>
struct _Bracket_accessor
{
typedef typename _Val::value_type result_type;
result_type
operator()(_Val const& V, size_t const N) const
{
return V[N];
}
};
template <typename _Tp>
struct always_true
{
bool operator() (const _Tp& ) const { return true; }
};
template <typename _Tp, typename _Dist>
struct squared_difference
{
typedef _Dist distance_type;
distance_type
operator() (const _Tp& __a, const _Tp& __b) const
{
distance_type d=__a - __b;
return d*d;
}
};
template <typename _Tp, typename _Dist>
struct squared_difference_counted
{
typedef _Dist distance_type;
squared_difference_counted()
: _M_count(0)
{ }
void reset ()
{ _M_count = 0; }
long&
count () const
{ return _M_count; }
distance_type
operator() (const _Tp& __a, const _Tp& __b) const
{
distance_type d=__a - __b;
++_M_count;
return d*d;
}
private:
mutable long _M_count;
};
} // namespace bo
#endif // include guard
/* COPYRIGHT --
*
* This file is part of libkdtree++, a C++ template KD-Tree sorting container.
* libkdtree++ is (c) 2004-2007 Martin F. Krafft <libkdtree@pobox.madduck.net>
* and Sylvain Bougerel <sylvain.bougerel.devel@gmail.com> distributed under the
* terms of the Artistic License 2.0. See the ./COPYING file in the source tree
* root for more information.
*
* THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES
* OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
| 22.011111
| 80
| 0.675416
|
rukletsov
|
ae19aa502a598910a401212d8974069928d643ee
| 4,025
|
hpp
|
C++
|
SOLVER/src/preloop/se_model/quad/mapping/MappingSpherical.hpp
|
nicklinyi/AxiSEM-3D
|
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
|
[
"MIT"
] | 8
|
2020-06-05T01:13:20.000Z
|
2022-02-24T05:11:50.000Z
|
SOLVER/src/preloop/se_model/quad/mapping/MappingSpherical.hpp
|
nicklinyi/AxiSEM-3D
|
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
|
[
"MIT"
] | 24
|
2020-10-21T19:03:38.000Z
|
2021-11-17T21:32:02.000Z
|
SOLVER/src/preloop/se_model/quad/mapping/MappingSpherical.hpp
|
nicklinyi/AxiSEM-3D
|
cd11299605cd6b92eb867d4109d2e6a8f15e6b4d
|
[
"MIT"
] | 5
|
2020-06-21T11:54:22.000Z
|
2021-06-23T01:02:39.000Z
|
//
// MappingSpherical.hpp
// AxiSEM3D
//
// Created by Kuangdai Leng on 3/21/20.
// Copyright © 2020 Kuangdai Leng. All rights reserved.
//
// spherical mapping
#ifndef MappingSpherical_hpp
#define MappingSpherical_hpp
#include "Mapping.hpp"
class MappingSpherical: public Mapping {
public:
// constructor
MappingSpherical(const eigen::DMat24 &nodalSZ): Mapping(nodalSZ) {
// find curved outer
const auto &r = nodalSZ.colwise().norm();
double distTol = mMinEdgeLength * 1e-3;
if (std::abs(r(0) - r(1)) < distTol &&
std::abs(r(2) - r(3)) < distTol) {
mCurvedOuter = r(2) > r(0) ? 2 : 0;
} else if (std::abs(r(1) - r(2)) < distTol &&
std::abs(r(3) - r(0)) < distTol) {
mCurvedOuter = r(3) > r(1) ? 3 : 1;
} else {
throw std::runtime_error("MappingSpherical::MappingSpherical || "
"Error identifying curved outer edge.");
}
}
// forward mapping: (ξ,η) -> (s,z)
eigen::DCol2 mapping(const eigen::DCol2 &xieta) const {
// compute coords rotated by Q2
double r0, r2, t0, t1, t2, t3, xi, eta;
computeCoordsQ2(xieta, r0, r2, t0, t1, t2, t3, xi, eta);
// intermediate
double t01 = ((1. - xi) * t0 + (1. + xi) * t1) * .5;
double t32 = ((1. - xi) * t3 + (1. + xi) * t2) * .5;
double r0m = (1. - eta) * r0 * .5;
double r2p = (1. + eta) * r2 * .5;
// compute in new system
eigen::DCol2 sz;
sz(0) = r0m * sin(t01) + r2p * sin(t32);
sz(1) = r0m * cos(t01) + r2p * cos(t32);
// rotate back
return sOrthogQ2[mCurvedOuter].transpose() * sz;
}
// Jacobian: ∂(s,z) / ∂(ξ,η)
eigen::DMat22 jacobian(const eigen::DCol2 &xieta) const {
// compute coords rotated by Q2
double r0, r2, t0, t1, t2, t3, xi, eta;
computeCoordsQ2(xieta, r0, r2, t0, t1, t2, t3, xi, eta);
// intermediate
double t01 = ((1. - xi) * t0 + (1. + xi) * t1) * .5;
double t32 = ((1. - xi) * t3 + (1. + xi) * t2) * .5;
double r0m = (1. - eta) * r0 * .5;
double r2p = (1. + eta) * r2 * .5;
// derivative
double t01_xi = (t1 - t0) * .5;
double t32_xi = (t2 - t3) * .5;
double r0m_eta = -r0 * .5;
double r2p_eta = r2 * .5;
// compute in new system
eigen::DMat22 J;
J(0, 0) = (r0m * cos(t01) * t01_xi + r2p * cos(t32) * t32_xi);
J(1, 0) = (r0m * sin(t01) * t01_xi + r2p * sin(t32) * t32_xi) * (-1.);
J(0, 1) = r0m_eta * sin(t01) + r2p_eta * sin(t32);
J(1, 1) = r0m_eta * cos(t01) + r2p_eta * cos(t32);
// rotate back
const eigen::DMat22 &Q2 = sOrthogQ2[mCurvedOuter];
return Q2.transpose() * J * Q2;
}
private:
// compute coords rotated by Q2
void computeCoordsQ2(const eigen::DCol2 &xieta,
double &r0, double &r2, double &t0, double &t1,
double &t2, double &t3, double &xi, double &eta)
const {
// rotate CS such that mCurvedOuter lies on edge 2
static eigen::DMat24 szQ2, rtQ2;
static eigen::DCol2 xietaQ2;
rotateQ2(xieta, szQ2, rtQ2, xietaQ2);
// the coords are not permutated, so edge 2 should be
// accessed by Mapping::cycle4(mCurvedOuter - 2)
r0 = rtQ2(0, Mapping::cycle4(mCurvedOuter - 2));
r2 = rtQ2(0, Mapping::cycle4(mCurvedOuter + 0));
t0 = rtQ2(1, Mapping::cycle4(mCurvedOuter - 2));
t1 = rtQ2(1, Mapping::cycle4(mCurvedOuter - 1));
t2 = rtQ2(1, Mapping::cycle4(mCurvedOuter + 0));
t3 = rtQ2(1, Mapping::cycle4(mCurvedOuter + 1));
xi = xietaQ2(0);
eta = xietaQ2(1);
// handling angle jumps in atan2
makeAnglesClose(t3, t2);
makeAnglesClose(t0, t1);
}
};
#endif /* MappingSpherical_hpp */
| 35.307018
| 78
| 0.514037
|
nicklinyi
|
ae1ed36c0059f7a8cc530a23594460647283b8a1
| 1,023
|
hpp
|
C++
|
dep/myvk/PipelineLayout.hpp
|
lilesper/SparseVoxelOctree
|
9c4c79ab746758d21070bb733dafe4f78438e4b5
|
[
"MIT"
] | 338
|
2019-08-02T03:57:05.000Z
|
2022-03-29T20:49:21.000Z
|
dep/myvk/PipelineLayout.hpp
|
lilesper/SparseVoxelOctree
|
9c4c79ab746758d21070bb733dafe4f78438e4b5
|
[
"MIT"
] | 12
|
2020-01-10T09:03:22.000Z
|
2022-03-25T02:03:23.000Z
|
dep/myvk/PipelineLayout.hpp
|
lilesper/SparseVoxelOctree
|
9c4c79ab746758d21070bb733dafe4f78438e4b5
|
[
"MIT"
] | 36
|
2019-08-08T11:15:23.000Z
|
2022-02-26T00:31:13.000Z
|
#ifndef MYVK_PIPELINE_LAYOUT_HPP
#define MYVK_PIPELINE_LAYOUT_HPP
#include "DescriptorSetLayout.hpp"
#include "DeviceObjectBase.hpp"
#include <volk.h>
#include <memory>
#include <vector>
namespace myvk {
class PipelineLayout : public DeviceObjectBase {
private:
std::shared_ptr<Device> m_device_ptr;
std::vector<std::shared_ptr<DescriptorSetLayout>> m_descriptor_layout_ptrs;
VkPipelineLayout m_pipeline_layout{VK_NULL_HANDLE};
public:
static std::shared_ptr<PipelineLayout>
Create(const std::shared_ptr<Device> &device,
const std::vector<std::shared_ptr<DescriptorSetLayout>> &descriptor_layouts,
const std::vector<VkPushConstantRange> &push_constant_ranges);
VkPipelineLayout GetHandle() const { return m_pipeline_layout; }
const std::shared_ptr<Device> &GetDevicePtr() const override { return m_device_ptr; }
const std::vector<std::shared_ptr<DescriptorSetLayout>> &GetDescriptorSetPtrs() const {
return m_descriptor_layout_ptrs;
}
~PipelineLayout();
};
} // namespace myvk
#endif
| 26.230769
| 88
| 0.783969
|
lilesper
|
ae20672553d21f207de6a05069c8d47071eb504e
| 2,467
|
cpp
|
C++
|
pixmap_art.cpp
|
gulesh/pixmap-ops
|
573afdd349d7e4913d7dbc60f0b9d3edd33b39ca
|
[
"MIT"
] | null | null | null |
pixmap_art.cpp
|
gulesh/pixmap-ops
|
573afdd349d7e4913d7dbc60f0b9d3edd33b39ca
|
[
"MIT"
] | null | null | null |
pixmap_art.cpp
|
gulesh/pixmap-ops
|
573afdd349d7e4913d7dbc60f0b9d3edd33b39ca
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "ppm_image.h"
#include <string>
#include <fstream>
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace agl;
using namespace std;
int main(int argc, char** argv)
{
ppm_image image;
image.load("../images/imagePart5.ppm");
image.save("imagePart5.ppm"); // should match original
cout << "loaded imagePart5: " << image.width() << " " << image.height() << endl;
//LAYER ONE CHANGES
//1.1.invert Image
ppm_image imageInverted = image.invertColor();
imageInverted.save("imagePart5-inverted-image.ppm");
//1.2.swirl color Image
ppm_image swirlImage = image.swirlColors();
swirlImage.save("imagePart5-swirled-image.ppm");
//1.3.red Extract Image
ppm_image redExtractedImage = image.redExtract();
redExtractedImage.save("imagePart5-redextracted-image.ppm");
//1.4.blue extract Image
ppm_image blueExtractedimage = image.blueExtract();
blueExtractedimage.save("imagePart5-blueextracted-image.ppm");
//1.5.green extract
ppm_image greenExtractedImage = image.greenExtract();
greenExtractedImage.save("imagePart5-greenextracted-image.ppm");
//1.6.Red Only extract
ppm_image redOnlyImage = image.redOnly(imageInverted);
redOnlyImage.save("imagePart5-redOnly-image.ppm");
//1.7.distort Image
ppm_image distortOriginalImage = image.distortImage();
distortOriginalImage.save("imagePart5-distortOriginal-image.ppm");
//1.8.invert Image
ppm_image gammaCorrected = image.gammaCorrect(0.6f);
gammaCorrected.save("imagePart5-gammaCorrected-image.ppm");
//LABEL 2 CHANGES
//2.1 swirl color inverted Image
ppm_image swirlImage2 = imageInverted.swirlColors();
swirlImage2.save("imagePart5-swirled-image2.ppm");
//2.2 difference inverted image
ppm_image differencedImage = image.difference(imageInverted);
differencedImage.save("imagePart5-differenced-image.ppm");
//LABEL 3 CHANGES
//3.1 Rotate differenced image
ppm_image rotatedImaged = differencedImage.rotate90();
rotatedImaged.save("imagePart5-rotated-image.ppm");
//3.2 distort swirled2 image
ppm_image distortedImage = swirlImage2.distortImage();
distortedImage.save("imagePart5-distorted-image.ppm");
//LABEL FOUR CHANGES
//4.1 dirtort rotated image
ppm_image distortedImage2 = rotatedImaged.distortImage();
distortedImage2.save("imagePart5-distorted-image2.ppm");
}
| 32.038961
| 84
| 0.717471
|
gulesh
|
ae2213166f4c876c2494f5dffc276b8deb45929d
| 361
|
hpp
|
C++
|
src/behavior/stochasticgames/madynamicprogramming/SG_backup_operator.hpp
|
MarkieMark/fastrl
|
e4f0b9b60a7ecb6f13bbb79936ea82acb8adae0e
|
[
"Apache-2.0"
] | 4
|
2019-04-19T00:11:36.000Z
|
2020-04-08T09:50:37.000Z
|
src/behavior/stochasticgames/madynamicprogramming/SG_backup_operator.hpp
|
MarkieMark/fastrl
|
e4f0b9b60a7ecb6f13bbb79936ea82acb8adae0e
|
[
"Apache-2.0"
] | null | null | null |
src/behavior/stochasticgames/madynamicprogramming/SG_backup_operator.hpp
|
MarkieMark/fastrl
|
e4f0b9b60a7ecb6f13bbb79936ea82acb8adae0e
|
[
"Apache-2.0"
] | null | null | null |
/*
* Mark Benjamin 6th March 2019
* Copyright (c) 2019 Mark Benjamin
*/
#ifndef FASTRL_BEHAVIOR_STOCHASTICGAMES_MADYNAMICPROGRAMMING_SG_BACKUP_OPERATOR_HPP
#define FASTRL_BEHAVIOR_STOCHASTICGAMES_MADYNAMICPROGRAMMING_SG_BACKUP_OPERATOR_HPP
class SGBackupOperator {
};
#endif //FASTRL_BEHAVIOR_STOCHASTICGAMES_MADYNAMICPROGRAMMING_SG_BACKUP_OPERATOR_HPP
| 24.066667
| 84
| 0.867036
|
MarkieMark
|
ae27dd19824a12b5c45f441b3024c297d3d02262
| 502
|
cpp
|
C++
|
solutions/AtCoder/cpsco2019_s2/B.cpp
|
yumeno-ukihashi/competitive-programming
|
5cc3a7938b62133d8dc71a179cb11dfe985315d3
|
[
"Unlicense"
] | null | null | null |
solutions/AtCoder/cpsco2019_s2/B.cpp
|
yumeno-ukihashi/competitive-programming
|
5cc3a7938b62133d8dc71a179cb11dfe985315d3
|
[
"Unlicense"
] | null | null | null |
solutions/AtCoder/cpsco2019_s2/B.cpp
|
yumeno-ukihashi/competitive-programming
|
5cc3a7938b62133d8dc71a179cb11dfe985315d3
|
[
"Unlicense"
] | null | null | null |
#include<bits/stdc++.h>
#define REP(x,y,z) for(int x=y;x<=z;x++)
#define MSET(x,y) memset(x,y,sizeof(x))
#define M 1005
using namespace std;
int n,in[M];
char c[M];
int main()
{
char buf[3];
while (~scanf("%d",&n)) {
REP(i,1,n) {
scanf("%s %d",buf,&in[i]);
c[i] = buf[0];
}
int ans = 0;
REP(i,1,n) if(c[i]=='+') ans += in[i];
REP(i,1,n) if(c[i]=='*' && in[i]>0) ans *= in[i];
printf("%d\n", ans);
}
return 0;
}
| 19.307692
| 57
| 0.438247
|
yumeno-ukihashi
|
ae2a14e49f45f1fc5456da010e3fa29dab9904a6
| 4,519
|
hh
|
C++
|
src/include/JsonItem.hh
|
websurfer5/json-schema-enforcer
|
99211a602b1c8177d9f9e67cd7773015f74a4080
|
[
"Apache-2.0"
] | null | null | null |
src/include/JsonItem.hh
|
websurfer5/json-schema-enforcer
|
99211a602b1c8177d9f9e67cd7773015f74a4080
|
[
"Apache-2.0"
] | null | null | null |
src/include/JsonItem.hh
|
websurfer5/json-schema-enforcer
|
99211a602b1c8177d9f9e67cd7773015f74a4080
|
[
"Apache-2.0"
] | null | null | null |
// JsonItem.hh
//
// Copyright 2018 Jeffrey Kintscher <websurfer@surf2c.net>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __JSONSCHEMAENFORCER_JSON_ITEM_HH
#define __JSONSCHEMAENFORCER_JSON_ITEM_HH
#include "config.h"
#include <list>
#include <map>
#include <string>
namespace jsonschemaenforcer
{
class JsonItem;
typedef std::list<JsonItem> JsonItemList;
typedef std::map<std::string, JsonItem> JsonItemMap;
class JsonItem
{
public:
typedef enum
{
type_Array = 0,
type_Boolean = 1,
type_Null = 2,
type_Number = 3,
type_Object = 4,
type_String = 5,
type_last_enum = 6
} JsonType;
JsonItem();
JsonItem(const JsonItem& jitem);
JsonItem& operator =(const JsonItem& jitem);
bool operator ==(const JsonItem& jitem) const;
inline bool operator !=(const JsonItem& jitem) const { return !(this->operator ==(jitem)); };
bool operator <(const JsonItem& jitem) const;
bool append_array(const JsonItem& jitem);
void append_array_item(const JsonItem& jitem);
void clear();
void clear_item_values();
void clear_values();
inline const std::string& get_key() const { return key; };
inline const size_t get_array_size() const { return (is_array() ? child_list.size() : 0); };
inline size_t get_properties_count() const { return (is_object() ? child_map.size() : 0); };
inline bool is_array() const { return (type == type_Array); };
inline bool is_boolean() const { return (type == type_Boolean); };
inline bool is_null() const { return (type == type_Null); };
inline bool is_number() const { return (type == type_Number); };
inline bool is_object() const { return (type == type_Object); };
inline bool is_string() const { return (type == type_String); };
inline void set_array(const JsonItemList& jitem_list)
{
set_array("", jitem_list);
}
void set_array(const std::string& _key, const JsonItemList& jitem_list);
inline void set_boolean(bool b)
{
set_boolean("", b);
};
inline void set_boolean(const std::string& _key, bool b)
{
clear_values();
bool_value = b;
type = type_Boolean;
set_key(_key);
};
inline void set_key(const std::string& _key)
{
key = _key;
};
inline void set_null()
{
clear();
}
inline void set_null(const std::string& _key)
{
clear_values();
set_key(_key);
}
inline void set_number(double num)
{
set_number("", num);
}
inline void set_number(const std::string& _key, double num)
{
clear_values();
num_value = num;
type = type_Number;
set_key(_key);
};
inline void set_object(JsonItemMap& jitem_map)
{
set_object("", jitem_map);
}
inline void set_object(const std::string& _key, JsonItemMap& jitem_map)
{
clear_values();
child_map = jitem_map;
type = type_Object;
set_key(_key);
};
inline void set_string(const std::string& str)
{
set_string("", str);
};
inline void set_string(const std::string& _key, const std::string& str)
{
clear_values();
str_value = str;
type = type_String;
set_key(_key);
};
bool bool_value;
double num_value;
JsonItemList child_list;
JsonItemMap child_map;
JsonType type;
std::string key,
str_value;
};
}
#endif // __JSONSCHEMAENFORCER_JSON_ITEM_HH
| 32.278571
| 101
| 0.571808
|
websurfer5
|
ae2fe37caeafd9619d0202873f643d4a2331fcff
| 34,977
|
inl
|
C++
|
nTA/Source/std_Rect.inl
|
loganjones/nTA-Total-Annihilation-Clone
|
d7d0e4d33f1d452d17cf2fed2b2bcb7f6d7d4d14
|
[
"MIT"
] | 2
|
2020-05-09T20:50:12.000Z
|
2021-06-20T08:34:58.000Z
|
nTA/Source/std_Rect.inl
|
loganjones/nTA-Total-Annihilation-Clone
|
d7d0e4d33f1d452d17cf2fed2b2bcb7f6d7d4d14
|
[
"MIT"
] | null | null | null |
nTA/Source/std_Rect.inl
|
loganjones/nTA-Total-Annihilation-Clone
|
d7d0e4d33f1d452d17cf2fed2b2bcb7f6d7d4d14
|
[
"MIT"
] | 2
|
2018-01-08T00:12:04.000Z
|
2020-06-14T10:56:50.000Z
|
// std_Rect.inl // \author Logan Jones
///////////////// \date 10/3/2001
/// \file
/// \brief ...
/////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::std_Rect() // \author Logan Jones
///////////////////////// \date 5/10/2002
//
//====================================================================
//
std_Rect::std_Rect():left(0),top(0),right(0),bottom(0){}
// End std_Rect::std_Rect()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::std_Rect() // \author Logan Jones
//////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const std_Rect& rctCopy -
//
std_Rect::std_Rect( const std_Rect& rctCopy ):
left(rctCopy.left),top(rctCopy.top),right(rctCopy.right),bottom(rctCopy.bottom)
{}
// End std_Rect::std_Rect()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::std_Rect() // \author Logan Jones
//////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const long newLeft -
// const long newTop -
// const long newRight -
// const long newBottom -
//
std_Rect::std_Rect( const long newLeft, const long newTop, const long newRight, const long newBottom ):
left(newLeft),top(newTop),right(newRight),bottom(newBottom)
{}
// End std_Rect::std_Rect()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::std_Rect() // \author Logan Jones
///////////////////////// \date 1/26/2002
//
//====================================================================
// Parameters:
// const std_RectF& rctCopy -
//
std_Rect::std_Rect( const std_RectF& rctCopy ):
left(rctCopy.left),top(rctCopy.top),right(rctCopy.right),bottom(rctCopy.bottom)
{}
// End std_Rect::std_Rect()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::std_Rect() // \author Logan Jones
//////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const RECT& rctCopy -
//
std_Rect::std_Rect( const RECT& rctCopy ):
left(rctCopy.left),top(rctCopy.top),right(rctCopy.right),bottom(rctCopy.bottom)
{}
// End std_Rect::std_Rect()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::std_Rect() // \author Logan Jones
//////////////////////// \date 10/13/2001
//
//====================================================================
// Parameters:
// const long newLeft -
// const long newTop -
// const std_Size& newSize -
//
std_Rect::std_Rect( const long newLeft, const long newTop, const std_Size& newSize ):
left(newLeft),top(newTop),right(left+newSize.width),bottom(top+newSize.height)
{}
// End std_Rect::std_Rect()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::std_Rect() // \author Logan Jones
//////////////////////// \date 10/27/2001
//
//====================================================================
// Parameters:
// const std_Point& newTopLeft -
// const std_Point& newTopLeft -
// const long newWidth -
// const long newHeight -
//
std_Rect::std_Rect( const std_Point& newTopLeft, const long newWidth, const long newHeight ):
left(newTopLeft.x),top(newTopLeft.y),right(left+newWidth),bottom(top+newHeight)
{}
// End std_Rect::std_Rect()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::std_Rect() // \author Logan Jones
//////////////////////// \date 10/13/2001
//
//====================================================================
// Parameters:
// const std_Point& newTopLeft -
// const std_Size& newSize -
//
std_Rect::std_Rect( const std_Point& newTopLeft, const std_Size& newSize ):
left(newTopLeft.x),top(newTopLeft.y),right(left+newSize.width),bottom(top+newSize.height)
{}
// End std_Rect::std_Rect()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::operator RECT() // \author Logan Jones
/////////////////////////////// \date 10/3/2001
//
//====================================================================
//
std_Rect::operator RECT()
{
RECT rect;
SetRect( &rect, left, top, right, bottom );
return rect;
}
// End std_Rect::operator RECT()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::operator+() // \author Logan Jones
/////////////////////////// \date 10/3/2001
//
//====================================================================
// Return: std_Rect -
//
std_Rect std_Rect::operator+() const
{
return (*this);
}
// End std_Rect::operator+()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::operator-() // \author Logan Jones
/////////////////////////// \date 10/3/2001
//
//====================================================================
// Return: std_Rect -
//
std_Rect std_Rect::operator-() const
{
return std_Rect( -left, -top, -right, -bottom );
}
// End std_Rect::operator-()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::operator+() // \author Logan Jones
/////////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const std_Rect& rect -
//
// Return: std_Rect -
//
std_Rect std_Rect::operator+( const std_Rect& rect ) const
{
return std_Rect( left + rect.left, top + rect.top, right + rect.right, bottom + rect.bottom );
}
// End std_Rect::operator+()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::operator-() // \author Logan Jones
/////////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const std_Rect& rect -
//
// Return: std_Rect -
//
std_Rect std_Rect::operator-( const std_Rect& rect ) const
{
return std_Rect( left - rect.left, top - rect.top, right - rect.right, bottom - rect.bottom );
}
// End std_Rect::operator-()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// operator+() // \author Logan Jones
//////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const std_Point& pt -
//
// Return: std_Rect -
//
std_Rect std_Rect::operator+( const std_Point& pt ) const
{
return std_Rect( left + pt.x, top + pt.y, right + pt.x, bottom + pt.y );
}
// End operator+()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// operator-() // \author Logan Jones
//////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const std_Point& pt -
//
// Return: std_Rect -
//
std_Rect std_Rect::operator-( const std_Point& pt ) const
{
return std_Rect( left - pt.x, top - pt.y, right - pt.x, bottom - pt.y );
}
// End operator-()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// operator+() // \author Logan Jones
//////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const std_Size& S -
//
// Return: std_Rect -
//
std_Rect std_Rect::operator+( const std_Size& S ) const
{
return std_Rect( left + S.width, top + S.height, right + S.width, bottom + S.height );
}
// End operator+()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// operator-() // \author Logan Jones
//////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const std_Size& S -
//
// Return: std_Rect -
//
std_Rect std_Rect::operator-( const std_Size& S ) const
{
return std_Rect( left - S.width, top - S.height, right - S.width, bottom - S.height );
}
// End operator-()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// operator<<() // \author Logan Jones
///////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const long s -
//
// Return: std_Rect -
//
std_Rect std_Rect::operator<<( const long s ) const
{
return std_Rect( left - s, top, right - s, bottom );
}
// End operator<<()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// operator>>() // \author Logan Jones
///////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const long s -
//
// Return: std_Rect -
//
std_Rect std_Rect::operator>>( const long s ) const
{
return std_Rect( left + s, top, right + s, bottom );
}
// End operator>>()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect std_Rect::operator *() // \author Logan Jones
////////////////////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const long s -
//
std_Rect std_Rect::operator *( const long s ) const
{
return std_Rect( left * s, top * s, right * s, bottom * s );
}
// End std_Rect std_Rect::operator *()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::operator/() // \author Logan Jones
/////////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const long s -
//
// Return: std_Rect -
//
std_Rect std_Rect::operator/( const long s ) const
{
return std_Rect( left / s, top / s, right / s, bottom / s );
}
// End std_Rect::operator/()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::operator==() // \author Logan Jones
//////////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const std_Rect& rect -
//
// Return: BOOL -
//
BOOL std_Rect::operator==( const std_Rect& rect ) const
{
return ( (left == rect.left) && (top == rect.top) && (right == rect.right) && (bottom == rect.bottom) );
}
// End std_Rect::operator==()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::operator!=() // \author Logan Jones
//////////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const std_Rect& rect -
//
// Return: BOOL -
//
BOOL std_Rect::operator!=( const std_Rect& rect ) const
{
return ( (left != rect.left) || (top != rect.top) || (right != rect.right) || (bottom != rect.bottom) );
}
// End std_Rect::operator!=()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::operator+=() // \author Logan Jones
//////////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const std_Rect& rect -
//
// Return: std_Rect& -
//
std_Rect& std_Rect::operator+=( const std_Rect& rect )
{
left += rect.left;
top += rect.top;
right += rect.right;
bottom += rect.bottom;
return (*this);
}
// End std_Rect::operator+=()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::operator-=() // \author Logan Jones
//////////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const std_Rect& rect -
//
// Return: std_Rect& -
//
std_Rect& std_Rect::operator-=( const std_Rect& rect )
{
left -= rect.left;
top -= rect.top;
right -= rect.right;
bottom -= rect.bottom;
return (*this);
}
// End std_Rect::operator-=()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::operator+=() // \author Logan Jones
//////////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const std_Point& pt -
//
// Return: std_Rect& -
//
std_Rect& std_Rect::operator+=( const std_Point& pt )
{
left += pt.x;
top += pt.y;
right += pt.x;
bottom += pt.y;
return (*this);
}
// End std_Rect::operator+=()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::operator-=() // \author Logan Jones
//////////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const std_Point& pt -
//
// Return: std_Rect& -
//
std_Rect& std_Rect::operator-=( const std_Point& pt )
{
left -= pt.x;
top -= pt.y;
right -= pt.x;
bottom -= pt.y;
return (*this);
}
// End std_Rect::operator-=()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::operator+=() // \author Logan Jones
//////////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const std_Size& S -
//
// Return: std_Rect& -
//
std_Rect& std_Rect::operator+=( const std_Size& S )
{
left += S.width;
top += S.height;
right += S.width;
bottom += S.height;
return (*this);
}
// End std_Rect::operator+=()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::operator-=() // \author Logan Jones
//////////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const std_Size& S -
//
// Return: std_Rect& -
//
std_Rect& std_Rect::operator-=( const std_Size& S )
{
left -= S.width;
top -= S.height;
right -= S.width;
bottom -= S.height;
return (*this);
}
// End std_Rect::operator-=()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::operator*=() // \author Logan Jones
//////////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const long s -
//
// Return: std_Rect& -
//
std_Rect& std_Rect::operator*=( const long s )
{
left *= s;
top *= s;
right *= s;
bottom *= s;
return (*this);
}
// End std_Rect::operator*=()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::operator/=() // \author Logan Jones
//////////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const long s -
//
// Return: std_Rect& -
//
std_Rect& std_Rect::operator/=( const long s )
{
left /= s;
top /= s;
right /= s;
bottom /= s;
return (*this);
}
// End std_Rect::operator/=()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::Set() // \author Logan Jones
///////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const long newLeft -
// const long newTop -
// const long newRight -
// const long newBottom -
//
void std_Rect::Set( const long newLeft, const long newTop, const long newRight, const long newBottom )
{
left = newLeft;
top = newTop;
right = newRight;
bottom = newBottom;
}
// End std_Rect::Set()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::Set() // \author Logan Jones
///////////////////// \date 10/13/2001
//
//====================================================================
// Parameters:
// const long newLeft -
// const long newTop -
// const std_Size& newSize -
//
void std_Rect::Set( const long newLeft, const long newTop, const std_Size& newSize )
{
left = newLeft;
top = newTop;
right = left + newSize.width;
bottom = top + newSize.height;
}
// End std_Rect::Set()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::Set() // \author Logan Jones
///////////////////// \date 10/27/2001
//
//====================================================================
// Parameters:
// const std_Point& newTopLeft -
// const std_Point& newTopLeft -
// const long newWidth -
// const long newHeight -
//
void std_Rect::Set( const std_Point& newTopLeft, const long newWidth, const long newHeight )
{
left = newTopLeft.x;
top = newTopLeft.y;
right = left + newWidth;
bottom = top + newHeight;
}
// End std_Rect::Set()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::Set() // \author Logan Jones
///////////////////// \date 10/13/2001
//
//====================================================================
// Parameters:
// const std_Point& newTopLeft -
// const std_Size& newSize -
//
void std_Rect::Set( const std_Point& newTopLeft, const std_Size& newSize )
{
left = newTopLeft.x;
top = newTopLeft.y;
right = left + newSize.width;
bottom = top + newSize.height;
}
// End std_Rect::Set()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::SetX() // \author Logan Jones
////////////////////// \date 10/13/2001
//
//====================================================================
// Parameters:
// const long newLeft -
// const long newTop -
// const std_Size& newSize -
//
void std_Rect::SetX( const long newLeft, const long newTop, const std_Size& newSize )
{
left = newLeft;
top = newTop;
right = left + newSize.width - 1;
bottom = top + newSize.height - 1;
}
// End std_Rect::SetX()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::SetX() // \author Logan Jones
////////////////////// \date 10/13/2001
//
//====================================================================
// Parameters:
// const std_Point newTopLeft -
// const std_Size& newSize -
//
void std_Rect::SetX( const std_Point& newTopLeft, const std_Size& newSize )
{
left = newTopLeft.x;
top = newTopLeft.y;
right = left + newSize.width - 1;
bottom = top + newSize.height - 1;
}
// End std_Rect::SetX()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::Shift() // \author Logan Jones
/////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const long shiftHorizontal -
// const long shiftVertical -
//
void std_Rect::Shift( const long shiftHorizontal, const long shiftVertical )
{
left += shiftHorizontal;
top += shiftVertical;
right += shiftHorizontal;
bottom += shiftVertical;
}
// End std_Rect::Shift()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::SetPosition() // \author Logan Jones
///////////////////////////// \date 10/27/2001
//
//====================================================================
// Parameters:
// const long newX -
// const long newY -
//
void std_Rect::SetPosition( const long newX, const long newY )
{
const long width = right - left;
const long height= bottom - top;
left = newX;
top = newY;
right = left + width;
bottom = top + height;
}
// End std_Rect::SetPosition()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::SetPosition() // \author Logan Jones
///////////////////////////// \date 10/27/2001
//
//====================================================================
// Parameters:
// const std_Point& newPos -
//
void std_Rect::SetPosition( const std_Point& newPos )
{
const long width = right - left;
const long height= bottom - top;
left = newPos.x;
top = newPos.y;
right = left + width;
bottom = top + height;
}
// End std_Rect::SetPosition()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::SetCenter() // \author Logan Jones
////////////////////////// \date 2/25/2002
//
//====================================================================
// Parameters:
// const long newX -
// const long newY -
//
void std_Rect::SetCenter( const long newX, const long newY )
{
const long width = right - left;
const long height= bottom - top;
left = newX - (width / 2);
top = newY - (height / 2);
right = left + width;
bottom = top + height;
}
// End std_Rect::SetCenter()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::SetCenter() // \author Logan Jones
////////////////////////// \date 2/25/2002
//
//====================================================================
// Parameters:
// const std_Point& newPos -
//
void std_Rect::SetCenter( const std_Point& newPos )
{
const long width = right - left;
const long height= bottom - top;
left = newPos.x - (width / 2);
top = newPos.y - (height / 2);
right = left + width;
bottom = top + height;
}
// End std_Rect::SetCenter()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::SetSize() // \author Logan Jones
///////////////////////// \date 10/27/2001
//
//====================================================================
// Parameters:
// const long newWidth -
// const long newHeight -
//
void std_Rect::SetSize( const long newWidth, const long newHeight )
{
right = left + newWidth;
bottom = top + newHeight;
}
// End std_Rect::SetSize()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::SetSize() // \author Logan Jones
///////////////////////// \date 10/27/2001
//
//====================================================================
// Parameters:
// const std_Size& newSize -
//
void std_Rect::SetSize( const std_Size& newSize )
{
right = left + newSize.width;
bottom = top + newSize.height;
}
// End std_Rect::SetSize()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::Position() // \author Logan Jones
////////////////////////// \date 11/18/2001
//
//====================================================================
// Return: std_Point -
//
std_Point std_Rect::Position() const
{
return std_Point( left, top );
}
// End std_Rect::Position()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::Center() // \author Logan Jones
/////////////////////// \date 2/25/2002
//
//====================================================================
// Return: std_Point -
//
std_Point std_Rect::Center() const
{
return std_Point( left + (Width() / 2), top + (Height() / 2) );
}
// End std_Rect::Center()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::Width() // \author Logan Jones
/////////////////////// \date 10/3/2001
//
//====================================================================
// Return: long -
//
long std_Rect::Width() const
{
return ( right - left );
}
// End std_Rect::Width()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::Height() // \author Logan Jones
//////////////////////// \date 10/3/2001
//
//====================================================================
// Return: long -
//
long std_Rect::Height() const
{
return ( bottom - top );
}
// End std_Rect::Height()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::Size() // \author Logan Jones
////////////////////// \date 10/3/2001
//
//====================================================================
// Return: std_Size -
//
std_Size std_Rect::Size() const
{
return std_Size( right - left ,bottom - top );
}
// End std_Rect::Size()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::WidthX() // \author Logan Jones
//////////////////////// \date 10/3/2001
//
//====================================================================
// Return: long -
//
long std_Rect::WidthX() const
{
return ( right - left + 1 );
}
// End std_Rect::WidthX()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::HeightX() // \author Logan Jones
///////////////////////// \date 10/3/2001
//
//====================================================================
// Return: long -
//
long std_Rect::HeightX() const
{
return ( bottom - top + 1 );
}
// End std_Rect::HeightX()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::SizeX() // \author Logan Jones
/////////////////////// \date 10/3/2001
//
//====================================================================
// Return: std_Size -
//
std_Size std_Rect::SizeX() const
{
return std_Size( right - left + 1 ,bottom - top + 1 );
}
// End std_Rect::SizeX()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::PointInRect() // \author Logan Jones
///////////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const std_Point& pt -
//
// Return: const bool -
//
const bool std_Rect::PointInRect( const std_Point& pt ) const
{
if( (pt.x < left) || (pt.x > right) || (pt.y < top) || (pt.y > bottom) )
return false;
else return true;
}
// End std_Rect::PointInRect()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::RectInRect() // \author Logan Jones
//////////////////////////// \date 10/3/2001
//
//====================================================================
// Parameters:
// const std_Rect& rect -
//
// Return: const bool -
//
const bool std_Rect::RectInRect( const std_Rect& rect ) const
{
if( (rect.right < left) ||
(rect.left > right) ||
(rect.bottom < top) ||
(rect.top > bottom) )
return false;
else return true;
}
// End std_Rect::RectInRect()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// std_Rect::ChangeSpace() // \author Logan Jones
//////////////////////////// \date 5/24/2002
//
//====================================================================
// Parameters:
// const std_Size szFrom -
// const std_Size szTo -
//
void std_Rect::ChangeSpace( const std_Size szFrom, const std_Size szTo )
{
left = (left * szTo.width) / szFrom.width;
right = (right * szTo.width) / szFrom.width;
top = (top * szTo.height)/ szFrom.height;
bottom= (bottom * szTo.height)/ szFrom.height;
}
// End std_Rect::ChangeSpace()
//////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
// End - std_Rect.inl //
///////////////////////
| 34.090643
| 106
| 0.305029
|
loganjones
|
ae34fe188210b8b2951d1aa684b082a4c440e5f0
| 2,533
|
cpp
|
C++
|
src/View.cpp
|
Djamel-Ali/card-games-framework
|
8fc529b3a565dab7da2437e11d82236c0d6ccdc9
|
[
"MIT"
] | null | null | null |
src/View.cpp
|
Djamel-Ali/card-games-framework
|
8fc529b3a565dab7da2437e11d82236c0d6ccdc9
|
[
"MIT"
] | null | null | null |
src/View.cpp
|
Djamel-Ali/card-games-framework
|
8fc529b3a565dab7da2437e11d82236c0d6ccdc9
|
[
"MIT"
] | null | null | null |
#include "View.hpp"
#include <limits>
View::View()
{
}
View::~View() {
delete game;
}
int View::rejouer() {
int choice;
cout << "\n----------------------------------" << endl;
cout << "LA PARTIE EST TERMINÉE" << endl;
cout << "\n----------------------------------\n" << endl;
cout << "1 : REJOUER; 2 : QUITTER" << endl;
cin >> choice;
if (!cin || choice < 1 || choice > 2)
{
cout << "Erreur, merci d'entrer un choix valide " << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
return choice == 2 ? 1 : 0;
}
void View::aurevoir() {
cout << "\n\n AU REVOIR :) \n\n" << endl;
}
int View::printWelcomeInterface() {
cout << "---------------------------------------------------------" << endl;
cout << "Bonjour et bienvenue à notre platforme de jeux ! " << endl;
cout << "---------------------------------------------------------" << endl;
cout << "Liste des jeux : " << endl;
cout << "#1# LA BATAILLE" << endl;
cout << "#2# LE HUIT AMERICAIN" << endl;
cout << "#3# UNO" << endl;
cout << "#4# LA BELOTE" << endl;
cout << "#5# LE TAROT" << endl;
int choix = 0;
cout << "entrez un jeu entre 1 et 5" << endl;
while (true)
{
cin >> choix;
if (!cin || choix < 1 || choix > 5)
{
cout << "Erreur, merci d'entrer un jeu valide " << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
else break;
}
return choix;
}
void View::printPlayer(const Player &player) {
cout << "tour de : " << endl;
cout << player.getName() << endl;
}
void View::printWinner(const Player &player) {
cout << "Bravo, ";
cout << player.getName() << " ";
cout << "a gagné !" << endl;
}
void View::update() {
cout << *(game);
}
int View::play(int max, Player * player) {
printPlayer(*player);
int index = -1;
cout << "entrez une carte entre 0 et "<< max << endl;
while (true)
{
cin >> index;
if (!cin || index < 0 || index > max)
{
cout << "Erreur, merci d'entrer une carte valide " << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
else break;
}
return index;
}
void View::setGame(Game *_game) {
game = _game;
}
| 21.649573
| 81
| 0.439005
|
Djamel-Ali
|
ae3a275095d7783b4c468c2fe502df0af89beba5
| 9,614
|
cxx
|
C++
|
libs/preprocessor/test/array.cxx
|
ballisticwhisper/boost
|
f72119ab640b564c4b983bd457457046b52af9ee
|
[
"BSL-1.0"
] | 2
|
2015-01-02T14:24:56.000Z
|
2015-01-02T14:25:17.000Z
|
libs/preprocessor/test/array.cxx
|
ballisticwhisper/boost
|
f72119ab640b564c4b983bd457457046b52af9ee
|
[
"BSL-1.0"
] | 2
|
2019-01-13T23:45:51.000Z
|
2019-02-03T08:13:26.000Z
|
libs/preprocessor/test/array.cxx
|
ballisticwhisper/boost
|
f72119ab640b564c4b983bd457457046b52af9ee
|
[
"BSL-1.0"
] | 1
|
2016-05-29T13:41:15.000Z
|
2016-05-29T13:41:15.000Z
|
# /* **************************************************************************
# * *
# * (C) Copyright Paul Mensonides 2002.
# * 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)
# * *
# ************************************************************************** */
#
# /* Revised by Edward Diener (2011,2013) */
#
# /* See http://www.boost.org for most recent version. */
#
# include <boost/preprocessor/array.hpp>
# include <libs/preprocessor/test/test.h>
# include <boost/preprocessor/list/at.hpp>
# include <boost/preprocessor/seq/elem.hpp>
# include <boost/preprocessor/tuple/elem.hpp>
# if BOOST_PP_VARIADICS
# include <boost/preprocessor/variadic/size.hpp>
# include <boost/preprocessor/variadic/elem.hpp>
# endif
# define ARRAY (3, (0, 1, 2))
# define ARRAY_LARGE (33, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32))
# define ARRAY_VERY_LARGE (64, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63))
// element access
BEGIN BOOST_PP_ARRAY_ELEM(1, ARRAY) == 1 END
BEGIN BOOST_PP_ARRAY_ELEM(2, (5, (0, 1, 2, 3, 4))) == 2 END
BEGIN BOOST_PP_ARRAY_ELEM(28, ARRAY_LARGE) == 28 END
BEGIN BOOST_PP_ARRAY_ELEM(17, (33, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32))) == 17 END
BEGIN BOOST_PP_ARRAY_ELEM(42, ARRAY_VERY_LARGE) == 42 END
BEGIN BOOST_PP_ARRAY_ELEM(62, (64, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63))) == 62 END
// size
BEGIN BOOST_PP_ARRAY_SIZE(ARRAY) == 3 END
BEGIN BOOST_PP_ARRAY_SIZE((5, (0, 1, 2, 3, 4))) == 5 END
BEGIN BOOST_PP_ARRAY_SIZE(ARRAY_LARGE) == 33 END
BEGIN BOOST_PP_ARRAY_SIZE((33, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32))) == 33 END
BEGIN BOOST_PP_ARRAY_SIZE(ARRAY_VERY_LARGE) == 64 END
BEGIN BOOST_PP_ARRAY_SIZE((64, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63))) == 64 END
// enum
# if BOOST_PP_VARIADICS
BEGIN BOOST_PP_VARIADIC_ELEM(2,BOOST_PP_ARRAY_ENUM(ARRAY)) == 2 END
BEGIN BOOST_PP_VARIADIC_ELEM(3,BOOST_PP_ARRAY_ENUM((5, (0, 1, 2, 3, 4)))) == 3 END
BEGIN BOOST_PP_VARIADIC_ELEM(31,BOOST_PP_ARRAY_ENUM(ARRAY_LARGE)) == 31 END
BEGIN BOOST_PP_VARIADIC_ELEM(13,BOOST_PP_ARRAY_ENUM((33, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32)))) == 13 END
BEGIN BOOST_PP_VARIADIC_ELEM(39,BOOST_PP_ARRAY_ENUM(ARRAY_VERY_LARGE)) == 39 END
BEGIN BOOST_PP_VARIADIC_ELEM(24,BOOST_PP_ARRAY_ENUM((64, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63)))) == 24 END
BEGIN BOOST_PP_VARIADIC_SIZE(BOOST_PP_ARRAY_ENUM((5, (0, 1, 2, 3, 4)))) == 5 END
BEGIN BOOST_PP_VARIADIC_SIZE(BOOST_PP_ARRAY_ENUM(ARRAY_LARGE)) == 33 END
BEGIN BOOST_PP_VARIADIC_SIZE(BOOST_PP_ARRAY_ENUM(ARRAY_VERY_LARGE)) == 64 END
BEGIN BOOST_PP_VARIADIC_SIZE(BOOST_PP_ARRAY_ENUM((64, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63)))) == 64 END
# endif
// to_list
BEGIN BOOST_PP_LIST_AT(BOOST_PP_ARRAY_TO_LIST(ARRAY), 1) == 1 END
BEGIN BOOST_PP_LIST_AT(BOOST_PP_ARRAY_TO_LIST((5, (0, 1, 2, 3, 4))), 4) == 4 END
BEGIN BOOST_PP_LIST_AT(BOOST_PP_ARRAY_TO_LIST((33, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32))), 26) == 26 END
BEGIN BOOST_PP_LIST_AT(BOOST_PP_ARRAY_TO_LIST(ARRAY_VERY_LARGE), 60) == 60 END
// to_seq
BEGIN BOOST_PP_SEQ_ELEM(0, BOOST_PP_ARRAY_TO_SEQ(ARRAY)) == 0 END
BEGIN BOOST_PP_SEQ_ELEM(3, BOOST_PP_ARRAY_TO_SEQ((5, (0, 1, 2, 3, 4)))) == 3 END
BEGIN BOOST_PP_SEQ_ELEM(17, BOOST_PP_ARRAY_TO_SEQ(ARRAY_LARGE)) == 17 END
BEGIN BOOST_PP_SEQ_ELEM(42, BOOST_PP_ARRAY_TO_SEQ((64, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63)))) == 42 END
// to_tuple
# if BOOST_PP_VARIADICS
BEGIN BOOST_PP_TUPLE_ELEM(2, BOOST_PP_ARRAY_TO_TUPLE(ARRAY)) == 2 END
BEGIN BOOST_PP_TUPLE_ELEM(1, BOOST_PP_ARRAY_TO_TUPLE((5, (0, 1, 2, 3, 4)))) == 1 END
BEGIN BOOST_PP_TUPLE_ELEM(26, BOOST_PP_ARRAY_TO_TUPLE(ARRAY_LARGE)) == 26 END
BEGIN BOOST_PP_TUPLE_ELEM(37, BOOST_PP_ARRAY_TO_TUPLE((64, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63)))) == 37 END
# else
BEGIN BOOST_PP_TUPLE_ELEM(3, 2, BOOST_PP_ARRAY_TO_TUPLE(ARRAY)) == 2 END
BEGIN BOOST_PP_TUPLE_ELEM(5, 1, BOOST_PP_ARRAY_TO_TUPLE((5, (0, 1, 2, 3, 4)))) == 1 END
BEGIN BOOST_PP_TUPLE_ELEM(33, 26, BOOST_PP_ARRAY_TO_TUPLE(ARRAY_LARGE)) == 26 END
BEGIN BOOST_PP_TUPLE_ELEM(64, 37, BOOST_PP_ARRAY_TO_TUPLE((64, (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63)))) == 37 END
# endif
// insert
BEGIN BOOST_PP_ARRAY_ELEM(0, BOOST_PP_ARRAY_INSERT(ARRAY,2,40)) == 0 END
BEGIN BOOST_PP_ARRAY_ELEM(1, BOOST_PP_ARRAY_INSERT(ARRAY,1,40)) == 40 END
BEGIN BOOST_PP_ARRAY_ELEM(2, BOOST_PP_ARRAY_INSERT(ARRAY,1,40)) == 1 END
BEGIN BOOST_PP_ARRAY_SIZE(BOOST_PP_ARRAY_INSERT(ARRAY,1,40)) == 4 END
BEGIN BOOST_PP_ARRAY_ELEM(8, BOOST_PP_ARRAY_INSERT(ARRAY_LARGE,22,1000)) == 8 END
BEGIN BOOST_PP_ARRAY_ELEM(22, BOOST_PP_ARRAY_INSERT(ARRAY_LARGE,22,1000)) == 1000 END
BEGIN BOOST_PP_ARRAY_ELEM(26, BOOST_PP_ARRAY_INSERT(ARRAY_LARGE,22,1000)) == 25 END
BEGIN BOOST_PP_ARRAY_SIZE(BOOST_PP_ARRAY_INSERT(ARRAY_LARGE,22,1000)) == 34 END
// pop_back
BEGIN BOOST_PP_ARRAY_SIZE(BOOST_PP_ARRAY_POP_BACK(ARRAY)) == 2 END
BEGIN BOOST_PP_ARRAY_SIZE(BOOST_PP_ARRAY_POP_BACK(ARRAY_LARGE)) == 32 END
BEGIN BOOST_PP_ARRAY_SIZE(BOOST_PP_ARRAY_POP_BACK(ARRAY_VERY_LARGE)) == 63 END
// pop_front
BEGIN BOOST_PP_ARRAY_SIZE(BOOST_PP_ARRAY_POP_FRONT(ARRAY)) == 2 END
BEGIN BOOST_PP_ARRAY_SIZE(BOOST_PP_ARRAY_POP_FRONT(ARRAY_LARGE)) == 32 END
BEGIN BOOST_PP_ARRAY_SIZE(BOOST_PP_ARRAY_POP_FRONT(ARRAY_VERY_LARGE)) == 63 END
BEGIN BOOST_PP_ARRAY_ELEM(1, BOOST_PP_ARRAY_POP_FRONT(ARRAY)) == 2 END
BEGIN BOOST_PP_ARRAY_ELEM(31, BOOST_PP_ARRAY_POP_FRONT(ARRAY_LARGE)) == 32 END
BEGIN BOOST_PP_ARRAY_ELEM(55, BOOST_PP_ARRAY_POP_FRONT(ARRAY_VERY_LARGE)) == 56 END
// push_back
BEGIN BOOST_PP_ARRAY_SIZE(BOOST_PP_ARRAY_PUSH_BACK(ARRAY, 3)) == 4 END
BEGIN BOOST_PP_ARRAY_SIZE(BOOST_PP_ARRAY_PUSH_BACK(ARRAY_LARGE, 33)) == 34 END
BEGIN BOOST_PP_ARRAY_ELEM(0, BOOST_PP_ARRAY_PUSH_BACK(ARRAY, 3)) == 0 END
BEGIN BOOST_PP_ARRAY_ELEM(33, BOOST_PP_ARRAY_PUSH_BACK(ARRAY_LARGE, 33)) == 33 END
// push_front
BEGIN BOOST_PP_ARRAY_SIZE(BOOST_PP_ARRAY_PUSH_FRONT(ARRAY, 555)) == 4 END
BEGIN BOOST_PP_ARRAY_SIZE(BOOST_PP_ARRAY_PUSH_FRONT(ARRAY_LARGE, 666)) == 34 END
BEGIN BOOST_PP_ARRAY_ELEM(0, BOOST_PP_ARRAY_PUSH_FRONT(ARRAY, 555)) == 555 END
BEGIN BOOST_PP_ARRAY_ELEM(33, BOOST_PP_ARRAY_PUSH_FRONT(ARRAY_LARGE, 33)) == 32 END
// remove
BEGIN BOOST_PP_ARRAY_SIZE(BOOST_PP_ARRAY_REMOVE(ARRAY, 1)) == 2 END
BEGIN BOOST_PP_ARRAY_SIZE(BOOST_PP_ARRAY_REMOVE(ARRAY_LARGE, 17)) == 32 END
BEGIN BOOST_PP_ARRAY_SIZE(BOOST_PP_ARRAY_REMOVE(ARRAY_VERY_LARGE, 27)) == 63 END
BEGIN BOOST_PP_ARRAY_ELEM(0, BOOST_PP_ARRAY_REMOVE(ARRAY, 2)) == 0 END
BEGIN BOOST_PP_ARRAY_ELEM(29, BOOST_PP_ARRAY_REMOVE(ARRAY_LARGE, 25)) == 30 END
BEGIN BOOST_PP_ARRAY_ELEM(62, BOOST_PP_ARRAY_REMOVE(ARRAY_VERY_LARGE, 48)) == 63 END
// replace
BEGIN BOOST_PP_ARRAY_SIZE(BOOST_PP_ARRAY_REPLACE(ARRAY_VERY_LARGE, 27, 1000)) == 64 END
BEGIN BOOST_PP_ARRAY_ELEM(0, BOOST_PP_ARRAY_REPLACE(ARRAY, 1, 44)) == 0 END
BEGIN BOOST_PP_ARRAY_ELEM(29, BOOST_PP_ARRAY_REPLACE(ARRAY_LARGE, 29, 999)) == 999 END
BEGIN BOOST_PP_ARRAY_ELEM(38, BOOST_PP_ARRAY_REPLACE(ARRAY_VERY_LARGE, 37, 1)) == 38 END
BEGIN BOOST_PP_ARRAY_ELEM(28, BOOST_PP_ARRAY_REPLACE(ARRAY_VERY_LARGE, 28, 1)) == 1 END
// reverse
BEGIN BOOST_PP_ARRAY_SIZE(BOOST_PP_ARRAY_REVERSE(ARRAY_VERY_LARGE)) == 64 END
BEGIN BOOST_PP_ARRAY_ELEM(0, BOOST_PP_ARRAY_REVERSE(ARRAY)) == 2 END
BEGIN BOOST_PP_ARRAY_ELEM(29, BOOST_PP_ARRAY_REVERSE(ARRAY_LARGE)) == 3 END
BEGIN BOOST_PP_ARRAY_ELEM(38, BOOST_PP_ARRAY_REVERSE(ARRAY_VERY_LARGE)) == 25 END
| 60.0875
| 322
| 0.670481
|
ballisticwhisper
|
ae3c1965221e7fa96d5c6255e0e4e3bfd33ab1fe
| 2,081
|
inl
|
C++
|
include/as/as-mat4.inl
|
pr0g/as
|
5698ded06abca884385b9deebe8a2e702e8a66a8
|
[
"MIT"
] | 6
|
2019-06-16T22:20:55.000Z
|
2021-11-13T17:16:16.000Z
|
include/as/as-mat4.inl
|
pr0g/as
|
5698ded06abca884385b9deebe8a2e702e8a66a8
|
[
"MIT"
] | null | null | null |
include/as/as-mat4.inl
|
pr0g/as
|
5698ded06abca884385b9deebe8a2e702e8a66a8
|
[
"MIT"
] | 1
|
2020-04-11T14:24:13.000Z
|
2020-04-11T14:24:13.000Z
|
namespace as
{
template<typename T>
AS_API constexpr index mat<T, 4>::dim()
{
return 4;
}
template<typename T>
AS_API constexpr index mat<T, 4>::size()
{
return 16;
}
template<typename T>
AS_API constexpr index mat<T, 4>::rows()
{
return mat<T, 4>::dim();
}
template<typename T>
AS_API constexpr index mat<T, 4>::cols()
{
return mat<T, 4>::dim();
}
template<typename T>
AS_API constexpr mat<T, 4> mat<T, 4>::identity()
{
return mat_identity<T, 4>();
}
// clang-format off
template<typename T>
AS_API constexpr mat<T, 4>::mat(
T x0, T y0, T z0, T w0,
T x1, T y1, T z1, T w1,
T x2, T y2, T z2, T w2,
T x3, T y3, T z3, T w3)
: elem_rc{
x0, y0, z0, w0,
x1, y1, z1, w1,
x2, y2, z2, w2,
x3, y3, z3, w3}
{
}
// clang-format on
template<typename T>
#ifdef AS_ROW_MAJOR
AS_API constexpr mat<T, 4>::mat(
const vec<T, 4>& row0, const vec<T, 4>& row1, const vec<T, 4>& row2,
const vec<T, 4>& row3)
: elem_rc{row0.x, row0.y, row0.z, row0.w, row1.x, row1.y, row1.z, row1.w,
row2.x, row2.y, row2.z, row2.w, row3.x, row3.y, row3.z, row3.w}
{
}
#elif defined AS_COL_MAJOR
AS_API constexpr mat<T, 4>::mat(
const vec<T, 4>& col0, const vec<T, 4>& col1, const vec<T, 4>& col2,
const vec<T, 4>& col3)
: elem_rc{col0.x, col0.y, col0.z, col0.w, col1.x, col1.y, col1.z, col1.w,
col2.x, col2.y, col2.z, col2.w, col3.x, col3.y, col3.z, col3.w}
{
}
#endif // AS_ROW_MAJOR ? AS_COL_MAJOR
// clang-format off
template<typename T>
AS_API constexpr mat<T, 4>::mat(
const mat<T, 3>& m, const vec<T, 3>& pos)
: elem_rc{m[0], m[1], m[2], T(0.0),
m[3], m[4], m[5], T(0.0),
m[6], m[7], m[8], T(0.0),
pos.x, pos.y, pos.z, T(1.0)}
{
}
// clang-format on
template<typename T>
AS_API constexpr T& mat<T, 4>::operator[](index i) &
{
return elem_rc[i];
}
template<typename T>
AS_API constexpr const T& mat<T, 4>::operator[](index i) const&
{
return elem_rc[i];
}
template<typename T>
AS_API constexpr const T mat<T, 4>::operator[](index i) &&
{
return elem_rc[i];
}
} // namespace as
| 20.81
| 75
| 0.597309
|
pr0g
|
ae43870a4b7d9e60b7937bebb98b0d4be22ebcd2
| 166
|
cpp
|
C++
|
test/chapter_03_strings_and_regular_expressions/url.cpp
|
rturrado/TheModernCppChallenge
|
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
|
[
"MIT"
] | null | null | null |
test/chapter_03_strings_and_regular_expressions/url.cpp
|
rturrado/TheModernCppChallenge
|
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
|
[
"MIT"
] | null | null | null |
test/chapter_03_strings_and_regular_expressions/url.cpp
|
rturrado/TheModernCppChallenge
|
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
|
[
"MIT"
] | null | null | null |
#include "chapter_03_strings_and_regular_expressions/url.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <sstream> // istringstream, ostringstream
| 18.444444
| 59
| 0.777108
|
rturrado
|
ae44c2e864673aa663e746d75050a8a0a7c7c263
| 2,227
|
cpp
|
C++
|
rev/tools/const_string.cpp
|
Roman-Skabin/REV
|
adfa0a742525784d66f98ff5b0d157343e5f1cf4
|
[
"BSD-4-Clause"
] | 2
|
2020-12-12T20:37:32.000Z
|
2022-01-06T22:20:30.000Z
|
rev/tools/const_string.cpp
|
Roman-Skabin/REV
|
adfa0a742525784d66f98ff5b0d157343e5f1cf4
|
[
"BSD-4-Clause"
] | 2
|
2020-02-22T21:27:59.000Z
|
2020-11-27T23:43:01.000Z
|
engine/tools/const_string.cpp
|
Roman-Skabin/cengine
|
12c99a571246d3a7325d1d6a97e98d3c2c912bcb
|
[
"BSD-4-Clause"
] | null | null | null |
// Copyright (c) 2020-2021, Roman-Skabin
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE.md file in the root directory of this source tree.
#include "core/pch.h"
#include "tools/const_string.h"
#include "tools/string.h"
namespace REV
{
ConstString ConstString::SubString(u64 from) const
{
REV_CHECK_M(from <= m_Length, "Bad arguments: from = %I64u, length = %I64u", from, m_Length);
if (from == 0)
{
return *this;
}
else if (from == m_Length)
{
return ConstString();
}
else
{
return ConstString(m_Data + from, m_Length - from);
}
}
ConstString ConstString::SubString(u64 from, u64 to) const
{
REV_CHECK_M(from <= to && to <= m_Length, "Bad arguments: from = %I64u, to = %I64u, length = %I64u", from, to, m_Length);
if (from == 0 && to == m_Length)
{
return *this;
}
else if (from == to)
{
return ConstString();
}
else
{
return ConstString(m_Data + from, to - from);
}
}
u64 ConstString::Find(char symbol, u64 offset) const
{
REV_CHECK_M(offset < m_Length, "Offset out of bounds.");
char *_end = m_Data + m_Length;
for (char *it = m_Data + offset; it < _end; ++it)
{
if (*it == symbol)
{
return it - m_Data;
}
}
return npos;
}
u64 ConstString::Find(const char *cstring, u64 cstring_length, u64 offset) const
{
REV_CHECK_M(offset < m_Length, "Offset out of bounds.");
const char *_end = m_Data + m_Length;
for (const char *it = m_Data + offset; it < _end; ++it)
{
if (it + cstring_length > _end)
{
return npos;
}
if (CompareStrings(it, cstring_length, cstring, cstring_length) == COMPARE_RESULT_EQ)
{
return it - m_Data;
}
}
return npos;
}
u64 ConstString::RFind(char symbol, u64 offset) const
{
REV_CHECK_M(offset < m_Length, "Offset out of bounds.");
const char *last = pLast();
for (const char *it = last - offset; it >= m_Data; --it)
{
if (*it == symbol)
{
return it - m_Data;
}
}
return npos;
}
}
| 21.209524
| 125
| 0.572968
|
Roman-Skabin
|
ae51cb024404c0b50b45bdb8fe0b32a15be78c02
| 11,783
|
cpp
|
C++
|
sdk/sdk/share/opencv/cxcore/src/cxswitcher.cpp
|
doyaGu/C0501Q_HWJL01
|
07a71328bd9038453cbb1cf9c276a3dd1e416d63
|
[
"MIT"
] | 1
|
2021-10-09T08:05:50.000Z
|
2021-10-09T08:05:50.000Z
|
sdk/sdk/share/opencv/cxcore/src/cxswitcher.cpp
|
doyaGu/C0501Q_HWJL01
|
07a71328bd9038453cbb1cf9c276a3dd1e416d63
|
[
"MIT"
] | null | null | null |
sdk/sdk/share/opencv/cxcore/src/cxswitcher.cpp
|
doyaGu/C0501Q_HWJL01
|
07a71328bd9038453cbb1cf9c276a3dd1e416d63
|
[
"MIT"
] | null | null | null |
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/
/****************************************************************************************/
/* Dynamic detection and loading of IPP modules */
/****************************************************************************************/
#include "_cxcore.h"
#if defined _MSC_VER && _MSC_VER >= 1200
#pragma warning( disable: 4115 ) /* type definition in () */
#endif
#if defined _MSC_VER && defined WIN64 && !defined EM64T
#pragma optimize( "", off )
#endif
#if defined WIN32 || defined WIN64
#include <windows.h>
#else
#include <sys/time.h>
#endif
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#define CV_PROC_GENERIC 0
#define CV_PROC_SHIFT 10
#define CV_PROC_ARCH_MASK ((1 << CV_PROC_SHIFT) - 1)
#define CV_PROC_IA32_GENERIC 1
#define CV_PROC_IA32_WITH_MMX (CV_PROC_IA32_GENERIC|(2 << CV_PROC_SHIFT))
#define CV_PROC_IA32_WITH_SSE (CV_PROC_IA32_GENERIC|(3 << CV_PROC_SHIFT))
#define CV_PROC_IA32_WITH_SSE2 (CV_PROC_IA32_GENERIC|(4 << CV_PROC_SHIFT))
#define CV_PROC_IA64 2
#define CV_PROC_EM64T 3
#define CV_GET_PROC_ARCH(model) ((model) & CV_PROC_ARCH_MASK)
typedef struct CvProcessorInfo
{
int model;
int count;
double frequency; // clocks per microsecond
}
CvProcessorInfo;
#undef MASM_INLINE_ASSEMBLY
#if defined WIN32 && !defined WIN64
#if defined _MSC_VER
#define MASM_INLINE_ASSEMBLY 1
#elif defined __BORLANDC__
#if __BORLANDC__ >= 0x560
#define MASM_INLINE_ASSEMBLY 1
#endif
#endif
#endif
/*
determine processor type
*/
static void
icvInitProcessorInfo( CvProcessorInfo* cpu_info )
{
memset( cpu_info, 0, sizeof(*cpu_info) );
cpu_info->model = CV_PROC_GENERIC;
#if defined WIN32 || defined WIN64
#ifndef PROCESSOR_ARCHITECTURE_AMD64
#define PROCESSOR_ARCHITECTURE_AMD64 9
#endif
#ifndef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64
#define PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 10
#endif
SYSTEM_INFO sys;
LARGE_INTEGER freq;
GetSystemInfo( &sys );
if( sys.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL &&
sys.dwProcessorType == PROCESSOR_INTEL_PENTIUM && sys.wProcessorLevel >= 6 )
{
int version = 0, features = 0, family = 0;
int id = 0;
HKEY key = 0;
cpu_info->count = (int)sys.dwNumberOfProcessors;
unsigned long val = 0, sz = sizeof(val);
if( RegOpenKeyEx( HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\SYSTEM\\CentralProcessor\\0\\",
0, KEY_QUERY_VALUE, &key ) >= 0 )
{
if( RegQueryValueEx( key, "~MHz", 0, 0, (uchar*)&val, &sz ) >= 0 )
cpu_info->frequency = (double)val;
RegCloseKey( key );
}
#ifdef MASM_INLINE_ASSEMBLY
__asm
{
/* use CPUID to determine the features supported */
pushfd
mov eax, 1
push ebx
push esi
push edi
#ifdef __BORLANDC__
db 0fh
db 0a2h
#else
_emit 0x0f
_emit 0xa2
#endif
pop edi
pop esi
pop ebx
mov version, eax
mov features, edx
popfd
}
#elif defined WIN32 && __GNUC__ > 2
asm volatile
(
"movl $1,%%eax\n\t"
".byte 0x0f; .byte 0xa2\n\t"
"movl %%eax, %0\n\t"
"movl %%edx, %1\n\t"
: "=r"(version), "=r" (features)
:
: "%ebx", "%esi", "%edi"
);
#else
{
static const char cpuid_code[] =
"\x53\x56\x57\xb8\x01\x00\x00\x00\x0f\xa2\x5f\x5e\x5b\xc3";
typedef int64 (CV_CDECL * func_ptr)(void);
func_ptr cpuid = (func_ptr)(void*)cpuid_code;
int64 cpuid_val = cpuid();
version = (int)cpuid_val;
features = (int)(cpuid_val >> 32);
}
#endif
#define ICV_CPUID_M6 ((1<<15)|(1<<23)) /* cmov + MMX */
#define ICV_CPUID_A6 ((1<<25)|ICV_CPUID_M6) /* <all above> + SSE */
#define ICV_CPUID_W7 ((1<<26)|ICV_CPUID_A6) /* <all above> + SSE2 */
family = (version >> 8) & 15;
if( family >= 6 && (features & ICV_CPUID_M6) != 0 ) /* Pentium II or higher */
id = features & ICV_CPUID_W7;
cpu_info->model = id == ICV_CPUID_W7 ? CV_PROC_IA32_WITH_SSE2 :
id == ICV_CPUID_A6 ? CV_PROC_IA32_WITH_SSE :
id == ICV_CPUID_M6 ? CV_PROC_IA32_WITH_MMX :
CV_PROC_IA32_GENERIC;
}
else
{
#if defined EM64T
if( sys.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 )
cpu_info->model = CV_PROC_EM64T;
#elif defined WIN64
if( sys.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64 )
cpu_info->model = CV_PROC_IA64;
#endif
if( QueryPerformanceFrequency( &freq ) )
cpu_info->frequency = (double)freq.QuadPart;
}
#else
cpu_info->frequency = 1;
#ifdef __x86_64__
cpu_info->model = CV_PROC_EM64T;
#elif defined __ia64__
cpu_info->model = CV_PROC_IA64;
#elif !defined __i386__
cpu_info->model = CV_PROC_GENERIC;
#else
// reading /proc/cpuinfo file (proc file system must be supported)
FILE *file = fopen( "/proc/cpuinfo", "r" );
if( file )
{
char buffer[1024];
int max_size = sizeof(buffer)-1;
for(;;)
{
const char* ptr = fgets( buffer, max_size, file );
if( !ptr )
break;
if( strncmp( buffer, "flags", 5 ) == 0 )
{
if( strstr( buffer, "mmx" ) && strstr( buffer, "cmov" ))
{
cpu_info->model = CV_PROC_IA32_WITH_MMX;
if( strstr( buffer, "xmm" ) || strstr( buffer, "sse" ))
{
cpu_info->model = CV_PROC_IA32_WITH_SSE;
if( strstr( buffer, "emm" ))
cpu_info->model = CV_PROC_IA32_WITH_SSE2;
}
}
}
else if( strncmp( buffer, "cpu MHz", 7 ) == 0 )
{
char* pos = strchr( buffer, ':' );
if( pos )
cpu_info->frequency = strtod( pos + 1, &pos );
}
}
fclose( file );
if( CV_GET_PROC_ARCH(cpu_info->model) != CV_PROC_IA32_GENERIC )
cpu_info->frequency = 1;
else
assert( cpu_info->frequency > 1 );
}
#endif
#endif
}
CV_INLINE const CvProcessorInfo*
icvGetProcessorInfo()
{
static CvProcessorInfo cpu_info;
static int init_cpu_info = 0;
if( !init_cpu_info )
{
icvInitProcessorInfo( &cpu_info );
init_cpu_info = 1;
}
return &cpu_info;
}
/****************************************************************************************/
/* Make functions descriptions */
/****************************************************************************************/
/*
determine processor type, load appropriate dll and
initialize all function pointers
*/
#if defined WIN32 || defined WIN64
#define DLL_PREFIX ""
#define DLL_SUFFIX ".dll"
#endif
#if 0 /*def _DEBUG*/
#define DLL_DEBUG_FLAG "d"
#else
#define DLL_DEBUG_FLAG ""
#endif
#define VERBOSE_LOADING 0
#if VERBOSE_LOADING
#define ICV_PRINTF(args) printf args; fflush(stdout)
#else
#define ICV_PRINTF(args)
#endif
CV_IMPL int
cvRegisterModule( const CvModuleInfo* module )
{
return -1;
}
CV_IMPL int
cvUseOptimized( int load_flag )
{
return 0;
}
CV_IMPL void
cvGetModuleInfo( const char* name, const char **version, const char **plugin_list )
{
}
typedef int64 (CV_CDECL * rdtsc_func)(void);
/* helper functions for RNG initialization and accurate time measurement */
CV_IMPL int64 cvGetTickCount( void )
{
const CvProcessorInfo* cpu_info = icvGetProcessorInfo();
if( CV_GET_PROC_ARCH(cpu_info->model) == CV_PROC_IA32_GENERIC )
{
#ifdef MASM_INLINE_ASSEMBLY
#ifdef __BORLANDC__
__asm db 0fh
__asm db 31h
#else
__asm _emit 0x0f;
__asm _emit 0x31;
#endif
#elif (defined __GNUC__ || defined CV_ICC) && defined __i386__
int64 t;
asm volatile (".byte 0xf; .byte 0x31" /* "rdtsc" */ : "=A" (t));
return t;
#else
static const char code[] = "\x0f\x31\xc3";
rdtsc_func func = (rdtsc_func)(void*)code;
return func();
#endif
}
else
{
#if defined WIN32 || defined WIN64
LARGE_INTEGER counter;
QueryPerformanceCounter( &counter );
return (int64)counter.QuadPart;
#else
struct timeval tv;
struct timezone tz;
gettimeofday( &tv, &tz );
return (int64)tv.tv_sec*1000000 + tv.tv_usec;
#endif
}
}
CV_IMPL double cvGetTickFrequency()
{
return icvGetProcessorInfo()->frequency;
}
static int icvNumThreads = 0;
static int icvNumProcs = 0;
CV_IMPL int cvGetNumThreads(void)
{
if( !icvNumProcs )
cvSetNumThreads(0);
return icvNumThreads;
}
CV_IMPL void cvSetNumThreads( int threads )
{
if( !icvNumProcs )
{
#ifdef _OPENMP
icvNumProcs = omp_get_num_procs();
icvNumProcs = MIN( icvNumProcs, CV_MAX_THREADS );
#else
icvNumProcs = 1;
#endif
}
if( threads <= 0 )
threads = icvNumProcs;
else
threads = MIN( threads, icvNumProcs );
icvNumThreads = threads;
}
CV_IMPL int cvGetThreadNum(void)
{
#ifdef _OPENMP
return omp_get_thread_num();
#else
return 0;
#endif
}
/* End of file. */
| 28.054762
| 101
| 0.588051
|
doyaGu
|
ae565493c82dcf171038ae864da5221c651b740e
| 18,794
|
cpp
|
C++
|
i8086sim/KExec_Arithm.cpp
|
koutheir/i8086sim
|
c47fe1ad1cfe8121a7cd6c66f673097c283d2af6
|
[
"BSD-3-Clause"
] | 3
|
2018-08-25T00:03:42.000Z
|
2020-01-06T12:37:04.000Z
|
i8086sim/KExec_Arithm.cpp
|
koutheir/i8086sim
|
c47fe1ad1cfe8121a7cd6c66f673097c283d2af6
|
[
"BSD-3-Clause"
] | null | null | null |
i8086sim/KExec_Arithm.cpp
|
koutheir/i8086sim
|
c47fe1ad1cfe8121a7cd6c66f673097c283d2af6
|
[
"BSD-3-Clause"
] | null | null | null |
#include "i8086sim.h"
/*
Bit set: 11 10 9 8 7 6 5 4 3 2 1 0
[OF] [DF] [IF] [TF] [SF] [ZF] [0] [AF] [0] [PF] [1] [CF]
*/
bool K8086VM::Execute_ADD_ADC_INC(K8086VM *VM, KInstructionID &II)
{
char mod, mem_reg_code, reg_code;
byte DispSize=0;
byte *REG, *EA, c;
ushort i8086Flags=VM->GetFlagsIntoBitSet();
switch (II.m_BaseCode[0]) {
case 0x0: //Register/Memory with Register to Either: 000000dw|mod reg r/m
case 0x10: //Add CF to the result
mod = (VM->m_CurCode[1] & 0xC0) >> 6;
mem_reg_code = VM->m_CurCode[1] & 0x7;
reg_code = (VM->m_CurCode[1] & 0x38) >> 3;
c = ((II.m_BaseCode[0] == 0x10) ? VM->CF : 0);
REG = VM->GetRegister(reg_code, (VM->m_CurCode[0] & 0x1) != 0, false);
EA = VM->GetEffectiveAddress(mod, mem_reg_code, VM->m_CurCode+2, DispSize, VM->m_CurCode[0] & 0x1);
//if d=1 then "to" reg; if d=0 then "from" reg
if (VM->m_CurCode[0] & 0x2) {
//REG = REG + REG/MEM
if (VM->m_CurCode[0] & 0x1) {
//*(ushort *)REG += (*(ushort *)EA + (ushort)c);
*(ushort *)REG += (ushort)c;
__asm {
push word ptr [i8086Flags]
popf
mov edx,[EA]
mov dx,[edx]
mov eax,[REG]
add [eax],dx
pushf
pop word ptr [i8086Flags]
}
} else {
//*REG += (*EA + c);
*REG += c;
__asm {
push word ptr [i8086Flags]
popf
mov edx,[EA]
mov dl,[edx]
mov eax,[REG]
add [eax],dl
pushf
pop word ptr [i8086Flags]
}
}
} else {
//REG/MEM = REG + REG/MEM
if (VM->m_CurCode[0] & 0x1) {
//*(ushort *)EA += (*(ushort *)REG + (ushort)c);
*(ushort *)EA += (ushort)c;
__asm {
push word ptr [i8086Flags]
popf
mov edx,[REG]
mov dx,[edx]
mov eax,[EA]
add [eax],dx
pushf
pop word ptr [i8086Flags]
}
} else {
//*EA += (*REG + c);
*EA += c;
__asm {
push word ptr [i8086Flags]
popf
mov edx,[REG]
mov dl,[edx]
mov eax,[EA]
add [eax],dl
pushf
pop word ptr [i8086Flags]
}
}
}
II.m_Size = DispSize+2;
break;
case 0x80: //Immediate to Register/Memory: 100000sw|mod 0 c 0 r/m|data|data if sw=01
//The bit "c" indicates if we should add the CF to the result
c = ((VM->m_CurCode[1] & 0x10) ? VM->CF : 0);
mod = (VM->m_CurCode[1] & 0xC0) >> 6;
mem_reg_code = VM->m_CurCode[1] & 0x7;
EA = VM->GetEffectiveAddress(mod, mem_reg_code, VM->m_CurCode+2, DispSize, VM->m_CurCode[0] & 0x1);
//If sw=01 then 16 bits of immediate data form the operand.
//If sw=11 then an immediate data byte is sign extended to form the 16-bit operand.
if (VM->m_CurCode[0] & 0x1) {
if (VM->m_CurCode[0] & 0x2) { //sw=11
//*(short *)EA += (imm + c);
short imm = (short)(*(char *)(VM->m_CurCode+2+DispSize));
*(short *)EA += (short)c;
__asm {
push word ptr [i8086Flags]
popf
mov dx,[imm]
mov eax,[EA]
add [eax],dx
pushf
pop word ptr [i8086Flags]
}
} else { //sw=01
//*(ushort *)EA += (*(ushort *)(VM->m_CurCode+2+DispSize) + (ushort)c);
ushort imm = *(ushort *)(VM->m_CurCode+2+DispSize);
*(ushort *)EA += (ushort)c;
__asm {
push word ptr [i8086Flags]
popf
mov dx,[imm]
mov eax,[EA]
add [eax],dx
pushf
pop word ptr [i8086Flags]
}
}
} else {
//*EA += (*(VM->m_CurCode+2+DispSize) + c);
byte imm = *(VM->m_CurCode+2+DispSize);
*EA += c;
__asm {
push word ptr [i8086Flags]
popf
mov dl,[imm]
mov eax,[EA]
add [eax],dl
pushf
pop word ptr [i8086Flags]
}
}
II.m_Size = DispSize + 3 + (((VM->m_CurCode[0] & 0x3) == 0x1) ? 1 : 0);
break;
case 0x4: //Immediate to Accumulator: 0000010w|data|data if w=1
case 0x14: //Add CF to the result
c = ((II.m_BaseCode[0] == 0x14) ? VM->CF : 0);
if (VM->m_CurCode[0] & 0x1) {
//VM->A.X += (*(ushort *)(VM->m_CurCode+1) + (ushort)c);
ushort imm = *(ushort *)(VM->m_CurCode+1);
VM->A.X += (ushort)c;
__asm {
push word ptr [i8086Flags]
popf
mov dx,[imm]
mov eax,VM
lea eax,[eax]VM.A.X
add [eax],dx
pushf
pop word ptr [i8086Flags]
}
} else {
//VM->A.R.L += (*(VM->m_CurCode+1) + c);
byte imm = *(VM->m_CurCode+1);
VM->A.R.L += c;
__asm {
push word ptr [i8086Flags]
popf
mov dl,[imm]
mov eax,VM
lea eax,[eax]VM.A.R.L
add [eax],dl
pushf
pop word ptr [i8086Flags]
}
}
II.m_Size = 2 + ((VM->m_CurCode[0] & 0x1) ? 1 : 0);
break;
case 0xFE: //Register/Memory: 1111111w|mod 000 r/m
mod = (VM->m_CurCode[1] & 0xC0) >> 6;
mem_reg_code = VM->m_CurCode[1] & 0x7;
EA = VM->GetEffectiveAddress(mod, mem_reg_code, VM->m_CurCode+2, DispSize, VM->m_CurCode[0] & 0x1);
if (VM->m_CurCode[0] & 0x1) {
//(*(ushort *)EA) ++;
__asm {
push word ptr [i8086Flags]
popf
mov eax,EA
inc word ptr [eax]
pushf
pop word ptr [i8086Flags]
}
} else {
//(*EA) ++;
__asm {
push word ptr [i8086Flags]
popf
mov eax,EA
inc byte ptr [eax]
pushf
pop word ptr [i8086Flags]
}
}
II.m_Size = DispSize + 2;
break;
case 0x40: //Register: 01000reg
reg_code = VM->m_CurCode[0] & 0x7;
VM->GetRegister(reg_code, true, false);
__asm {
push word ptr [i8086Flags]
popf
inc word ptr [eax]
pushf
pop word ptr [i8086Flags]
}
II.m_Size = 1;
break;
}
VM->SetFlagsFromBitSet(i8086Flags);
VM->IP += II.m_Size;
return true;
}
bool K8086VM::Execute_SUB_SSB_DEC(K8086VM *VM, KInstructionID &II)
{
char mod, mem_reg_code, reg_code;
byte DispSize=0;
byte *REG, *EA, c;
ushort i8086Flags=VM->GetFlagsIntoBitSet();
switch (II.m_BaseCode[0]) {
case 0x28: //Register/Memory and Register to Either
case 0x18: //Substract CF from result
c = ((II.m_BaseCode[0] == 0x18) ? VM->CF : 0);
mod = (VM->m_CurCode[1] & 0xC0) >> 6;
mem_reg_code = VM->m_CurCode[1] & 0x7;
reg_code = (VM->m_CurCode[1] & 0x38) >> 3;
REG = VM->GetRegister(reg_code, (VM->m_CurCode[0] & 0x1) != 0, false);
EA = VM->GetEffectiveAddress(mod, mem_reg_code, VM->m_CurCode+2, DispSize, VM->m_CurCode[0] & 0x1);
//if d=1 then "to" reg; if d=0 then "from" reg
if (VM->m_CurCode[0] & 0x2) {
//REG = REG - REG/MEM
if (VM->m_CurCode[0] & 0x1) {
//*(ushort *)REG -= (*(ushort *)EA + (ushort)c);
*(ushort *)REG -= (ushort)c;
__asm {
push word ptr [i8086Flags]
popf
mov edx,[EA]
mov dx,[edx]
mov eax,[REG]
sub [eax],dx
pushf
pop word ptr [i8086Flags]
}
} else {
//*REG -= (*EA + c);
*REG -= c;
__asm {
push word ptr [i8086Flags]
popf
mov edx,[EA]
mov dl,[edx]
mov eax,[REG]
sub [eax],dl
pushf
pop word ptr [i8086Flags]
}
}
} else {
//REG/MEM = REG/MEM - REG
if (VM->m_CurCode[0] & 0x1) {
//*(ushort *)EA -= (*(ushort *)REG + (ushort)c);
*(ushort *)EA -= (ushort)c;
__asm {
push word ptr [i8086Flags]
popf
mov edx,[REG]
mov dx,[edx]
mov eax,[EA]
sub [eax],dx
pushf
pop word ptr [i8086Flags]
}
} else {
//*EA -= (*REG + c);
*EA -= c;
__asm {
push word ptr [i8086Flags]
popf
mov edx,[REG]
mov dl,[edx]
mov eax,[EA]
sub [eax],dl
pushf
pop word ptr [i8086Flags]
}
}
}
II.m_Size = DispSize+2;
break;
case 0x80: //Immediate from Register/Memory: 100000sw|mod 0 c 1 r/m|data|data if sw=01
//The bit "c" indicates if we should substract the CF from the result
c = ((VM->m_CurCode[1] & 0x10) ? VM->CF : 0);
mod = (VM->m_CurCode[1] & 0xC0) >> 6;
mem_reg_code = VM->m_CurCode[1] & 0x7;
EA = VM->GetEffectiveAddress(mod, mem_reg_code, VM->m_CurCode+2, DispSize, VM->m_CurCode[0] & 0x1);
//If sw=01 then 16 bits of immediate data form the operand.
//If sw=11 then an immediate data byte is sign extended to form the 16-bit operand.
if (VM->m_CurCode[0] & 0x1) {
if (VM->m_CurCode[0] & 0x2) { //sw=11
//*(short *)EA -= (imm + c);
short imm = (short)(*(char *)(VM->m_CurCode+2+DispSize));
*(short *)EA -= (short)c;
__asm {
push word ptr [i8086Flags]
popf
mov dx,[imm]
mov eax,[EA]
sub [eax],dx
pushf
pop word ptr [i8086Flags]
}
} else { //sw=01
//*(ushort *)EA -= (*(ushort *)(VM->m_CurCode+2+DispSize) + (ushort)c);
ushort imm = *(ushort *)(VM->m_CurCode+2+DispSize);
*(ushort *)EA -= (ushort)c;
__asm {
push word ptr [i8086Flags]
popf
mov dx,[imm]
mov eax,[EA]
sub [eax],dx
pushf
pop word ptr [i8086Flags]
}
}
} else {
//*EA -= (*(VM->m_CurCode+2+DispSize) + c);
byte imm = *(VM->m_CurCode+2+DispSize);
*EA -= c;
__asm {
push word ptr [i8086Flags]
popf
mov dl,[imm]
mov eax,[EA]
sub [eax],dl
pushf
pop word ptr [i8086Flags]
}
}
II.m_Size = DispSize + 3 + (((VM->m_CurCode[0] & 0x3) == 0x1) ? 1 : 0);
break;
case 0x2C: //Immediate from Accumulator: 0010110w|data|data if w=1
case 0x0E: //Substract CF from result
c = ((II.m_BaseCode[0] == 0x0E) ? VM->CF : 0);
if (VM->m_CurCode[0] & 0x1) {
//VM->A.X -= (*(ushort *)(VM->m_CurCode+1) + (ushort)c);
ushort imm = *(ushort *)(VM->m_CurCode+1);
VM->A.X -= (ushort)c;
__asm {
push word ptr [i8086Flags]
popf
mov dx,[imm]
mov eax,VM
lea eax,[eax]VM.A.X
sub [eax],dx
pushf
pop word ptr [i8086Flags]
}
} else {
//VM->A.R.L -= (*(VM->m_CurCode+1) + c);
byte imm = *(VM->m_CurCode+1);
VM->A.R.L += c;
__asm {
push word ptr [i8086Flags]
popf
mov dl,[imm]
mov eax,VM
lea eax,[eax]VM.A.R.L
sub [eax],dl
pushf
pop word ptr [i8086Flags]
}
}
II.m_Size = 2 + ((VM->m_CurCode[0] & 0x1) ? 1 : 0);
break;
case 0xFE: //Register/Memory: 1111111w|mod 001 r/m
mod = (VM->m_CurCode[1] & 0xC0) >> 6;
mem_reg_code = VM->m_CurCode[1] & 0x7;
EA = VM->GetEffectiveAddress(mod, mem_reg_code, VM->m_CurCode+2, DispSize, VM->m_CurCode[0] & 0x1);
if (VM->m_CurCode[0] & 0x1) {
//(*(ushort *)EA) --;
__asm {
push word ptr [i8086Flags]
popf
mov eax,EA
dec word ptr [eax]
pushf
pop word ptr [i8086Flags]
}
} else {
//(*EA) --;
__asm {
push word ptr [i8086Flags]
popf
mov eax,EA
dec byte ptr [eax]
pushf
pop word ptr [i8086Flags]
}
}
II.m_Size = DispSize + 2;
break;
case 0x48: //Register: 01001reg
reg_code = VM->m_CurCode[0] & 0x7;
VM->GetRegister(reg_code, true, false);
__asm {
push word ptr [i8086Flags]
popf
dec word ptr [eax]
pushf
pop word ptr [i8086Flags]
}
II.m_Size = 1;
break;
}
VM->SetFlagsFromBitSet(i8086Flags);
VM->IP += II.m_Size;
return true;
}
bool K8086VM::Execute_NEG(K8086VM *VM, KInstructionID &II)
{
//1111011w|mod 011 r/m
byte DispSize=0;
ushort i8086Flags=VM->GetFlagsIntoBitSet();
char mod = (VM->m_CurCode[1] & 0xC0) >> 6;
char mem_reg_code = VM->m_CurCode[1] & 0x7;
byte *EA = VM->GetEffectiveAddress(mod, mem_reg_code, VM->m_CurCode+2, DispSize, VM->m_CurCode[0] & 0x1);
if (VM->m_CurCode[0] & 0x1) {
__asm {
push word ptr [i8086Flags]
popf
mov eax,EA
neg word ptr [eax]
pushf
pop word ptr [i8086Flags]
}
} else {
__asm {
push word ptr [i8086Flags]
popf
mov eax,EA
neg byte ptr [eax]
pushf
pop word ptr [i8086Flags]
}
}
VM->SetFlagsFromBitSet(i8086Flags);
II.m_Size = DispSize + 2;
VM->IP += II.m_Size;
return true;
}
bool K8086VM::Execute_CMP(K8086VM *VM, KInstructionID &II)
{
char mod, mem_reg_code, reg_code;
byte DispSize=0;
byte *REG, *EA;
ushort i8086Flags=VM->GetFlagsIntoBitSet();
switch (II.m_BaseCode[0]) {
case 0x38: //Register/Memory and Register: 001110dw|mod reg r/m
mod = (VM->m_CurCode[1] & 0xC0) >> 6;
mem_reg_code = VM->m_CurCode[1] & 0x7;
reg_code = (VM->m_CurCode[1] & 0x38) >> 3;
REG = VM->GetRegister(reg_code, (VM->m_CurCode[0] & 0x1) != 0, false);
EA = VM->GetEffectiveAddress(mod, mem_reg_code, VM->m_CurCode+2, DispSize, VM->m_CurCode[0] & 0x1);
//if d=1 then "to" reg; if d=0 then "from" reg
if (VM->m_CurCode[0] & 0x2) {
//REG = REG - REG/MEM
if (VM->m_CurCode[0] & 0x1) {
__asm {
push word ptr [i8086Flags]
popf
mov edx,[EA]
mov dx,[edx]
mov eax,[REG]
cmp [eax],dx
pushf
pop word ptr [i8086Flags]
}
} else {
__asm {
push word ptr [i8086Flags]
popf
mov edx,[EA]
mov dl,[edx]
mov eax,[REG]
cmp [eax],dl
pushf
pop word ptr [i8086Flags]
}
}
} else {
//REG/MEM = REG/MEM - REG
if (VM->m_CurCode[0] & 0x1) {
__asm {
push word ptr [i8086Flags]
popf
mov edx,[REG]
mov dx,[edx]
mov eax,[EA]
cmp [eax],dx
pushf
pop word ptr [i8086Flags]
}
} else {
__asm {
push word ptr [i8086Flags]
popf
mov edx,[REG]
mov dl,[edx]
mov eax,[EA]
cmp [eax],dl
pushf
pop word ptr [i8086Flags]
}
}
}
II.m_Size = DispSize+2;
break;
case 0x80: //Immediate with Register/Memory: 100000sw|mod 111 r/m|data|data if sw=01
mod = (VM->m_CurCode[1] & 0xC0) >> 6;
mem_reg_code = VM->m_CurCode[1] & 0x7;
EA = VM->GetEffectiveAddress(mod, mem_reg_code, VM->m_CurCode+2, DispSize, VM->m_CurCode[0] & 0x1);
//If sw=01 then 16 bits of immediate data form the operand.
//If sw=11 then an immediate data byte is sign extended to form the 16-bit operand.
if (VM->m_CurCode[0] & 0x1) {
if (VM->m_CurCode[0] & 0x2) { //sw=11
short imm = (short)(*(char *)(VM->m_CurCode+2+DispSize));
__asm {
push word ptr [i8086Flags]
popf
mov dx,[imm]
mov eax,[EA]
cmp [eax],dx
pushf
pop word ptr [i8086Flags]
}
} else { //sw=01
ushort imm = *(ushort *)(VM->m_CurCode+2+DispSize);
__asm {
push word ptr [i8086Flags]
popf
mov dx,[imm]
mov eax,[EA]
cmp [eax],dx
pushf
pop word ptr [i8086Flags]
}
}
} else {
byte imm = *(VM->m_CurCode+2+DispSize);
__asm {
push word ptr [i8086Flags]
popf
mov dl,[imm]
mov eax,[EA]
cmp [eax],dl
pushf
pop word ptr [i8086Flags]
}
}
II.m_Size = DispSize + 3 + (((VM->m_CurCode[0] & 0x3) == 0x1) ? 1 : 0);
break;
case 0x3C: //Immediate with Accumulator: 0011110w|data|data if w=1
if (VM->m_CurCode[0] & 0x1) {
ushort imm = *(ushort *)(VM->m_CurCode+1);
__asm {
push word ptr [i8086Flags]
popf
mov dx,[imm]
mov eax,VM
lea eax,[eax]VM.A.X
cmp [eax],dx
pushf
pop word ptr [i8086Flags]
}
} else {
byte imm = *(VM->m_CurCode+1);
__asm {
push word ptr [i8086Flags]
popf
mov dl,[imm]
mov eax,VM
lea eax,[eax]VM.A.R.L
cmp [eax],dl
pushf
pop word ptr [i8086Flags]
}
}
II.m_Size = 2 + ((VM->m_CurCode[0] & 0x1) ? 1 : 0);
break;
}
VM->SetFlagsFromBitSet(i8086Flags);
VM->IP += II.m_Size;
return true;
}
bool K8086VM::Execute_AAA_DAA_AAS_DAS_AAM_AAD_CBW_CWD(K8086VM *VM, KInstructionID &II)
{
ushort i8086Flags=VM->GetFlagsIntoBitSet();
#define ADJUST_ASM_CODE(adjust_instruction) \
__asm push word ptr [i8086Flags] \
__asm popf \
__asm mov edx,[VM] \
__asm lea edx,[edx]VM.A.X \
__asm mov ax,[edx] \
__asm adjust_instruction \
__asm mov [edx],ax \
__asm pushf \
__asm pop word ptr [i8086Flags]
switch (II.m_BaseCode[0]) {
case 0x37: //ASCII Adjust for Add
ADJUST_ASM_CODE(aaa);
break;
case 0x27: //Decimal Adjust for Add
ADJUST_ASM_CODE(daa);
break;
case 0x3F: //ASCII Adjust for Subtract
ADJUST_ASM_CODE(aas);
break;
case 0x2F: //Decimal Adjust for Subtract
ADJUST_ASM_CODE(das);
break;
case 0xD4: //ASCII Adjust for Multiply
ADJUST_ASM_CODE(aam);
break;
case 0xD5: //ASCII Adjust for Divide
ADJUST_ASM_CODE(aad);
break;
case 0x98: //Convert Byte to Word
ADJUST_ASM_CODE(cbw);
break;
case 0x99: //Convert Word to Double Word
__asm {
push word ptr [i8086Flags]
popf
mov ecx,[VM]
lea ecx,[ecx]VM.A.X
mov ax,[ecx]
cwd
mov [ecx],ax
pushf
pop word ptr [i8086Flags]
mov ecx,[VM]
lea ecx,[ecx]VM.D.X
mov [ecx],dx
}
break;
}
VM->SetFlagsFromBitSet(i8086Flags);
VM->IP += II.m_Size;
return true;
}
bool K8086VM::Execute_MUL_IMUL_DIV_IDIV(K8086VM *VM, KInstructionID &II)
{
//1111011w|mod 100 r/m
byte DispSize=0;
ushort i8086Flags=VM->GetFlagsIntoBitSet();
char mod = (VM->m_CurCode[1] & 0xC0) >> 6;
char mem_reg_code = VM->m_CurCode[1] & 0x7;
byte *EA = VM->GetEffectiveAddress(mod, mem_reg_code, VM->m_CurCode+2, DispSize, VM->m_CurCode[0] & 0x1);
#define MULDIV_ASM_CODE(instruction_mnemonic) \
if (VM->m_CurCode[0] & 0x1) { \
__asm push word ptr [i8086Flags] \
__asm popf \
__asm mov ecx,[VM] \
__asm lea ecx,[ecx]VM.A.X \
__asm mov ax,[ecx] \
__asm mov ecx,[VM] \
__asm lea ecx,[ecx]VM.D.X \
__asm mov dx,[ecx] \
__asm mov ecx,[EA] \
__asm instruction_mnemonic word ptr [ecx] \
__asm mov ecx,[VM] \
__asm lea ecx,[ecx]VM.A.X \
__asm mov [ecx],ax \
__asm mov ecx,[VM] \
__asm lea ecx,[ecx]VM.D.X \
__asm mov [ecx],dx \
__asm pushf \
__asm pop word ptr [i8086Flags] \
} else { \
__asm push word ptr [i8086Flags] \
__asm popf \
__asm mov ecx,[VM] \
__asm lea ecx,[ecx]VM.A.X \
__asm mov ax,[ecx] \
__asm mov ecx,[EA] \
__asm instruction_mnemonic byte ptr [ecx] \
__asm mov ecx,[VM] \
__asm lea ecx,[ecx]VM.A.X \
__asm mov [ecx],ax \
__asm pushf \
__asm pop word ptr [i8086Flags] \
}
if (VM->m_CurCode[1] & 0x10) { //Division
if (VM->m_CurCode[1] & 0x8) { //Signed
MULDIV_ASM_CODE(idiv);
} else { //Unsigned
MULDIV_ASM_CODE(div);
}
} else { //Multiplication
if (VM->m_CurCode[1] & 0x8) { //Signed
MULDIV_ASM_CODE(imul);
} else { //Unsigned
MULDIV_ASM_CODE(mul);
}
}
VM->SetFlagsFromBitSet(i8086Flags);
II.m_Size = DispSize+2;
VM->IP += II.m_Size;
return true;
}
| 24.187902
| 107
| 0.554166
|
koutheir
|
ae5a9c3dd3c3b13e66de9d54513e8a8e506d69d4
| 19,008
|
cpp
|
C++
|
src/mediasystem/util/StateMachine.cpp
|
m1keall1son/ofxMediaSystem
|
c4b1619111b43996aabcb5c123af90824f8eee63
|
[
"MIT"
] | 6
|
2018-06-15T11:50:38.000Z
|
2018-09-13T19:44:12.000Z
|
src/mediasystem/util/StateMachine.cpp
|
m1keall1son/ofxMediaSystem
|
c4b1619111b43996aabcb5c123af90824f8eee63
|
[
"MIT"
] | null | null | null |
src/mediasystem/util/StateMachine.cpp
|
m1keall1son/ofxMediaSystem
|
c4b1619111b43996aabcb5c123af90824f8eee63
|
[
"MIT"
] | 1
|
2018-06-28T16:39:17.000Z
|
2018-06-28T16:39:17.000Z
|
//
// StateMachine.c
// Aerialtronics
//
// Created by Michael Allison on 8/16/18.
//
#include "StateMachine.h"
#include "ofMain.h"
namespace mediasystem {
StateMachine::Transition::Transition(float dur):
duration(dur)
{}
void StateMachine::addState(State&& state)
{
auto name = state.mName;
state.mParent = &mRoot;
state.mDepth = mRoot.mDepth + 1;
mStates.emplace(std::move(name),std::move(state));
}
void StateMachine::addChildState(std::string parent, State&& state)
{
auto found = mStates.find(parent);
if(found != mStates.end()){
auto name = state.mName;
state.mParent = &found->second;
state.mDepth = found->second.mDepth + 1;
mStates.emplace(std::move(name),std::move(state));
}else{
ofLogError("StateMachine") << "cant find parent state: \'" << parent << "\'. adding to root.";
addState(std::move(state));
}
}
void StateMachine::removeState(std::string state)
{
auto found = mStates.find(state);
if(found != mStates.end()){
for(auto & state : mStates){
if(state.second.mParent == &found->second){
state.second.mParent = found->second.mParent;
state.second.mDepth = found->second.mDepth;
}
}
mStates.erase(found);
}else{
ofLogError("StateMachine") << "cant find state: " << state;
}
}
void StateMachine::changeParentTo(std::string state, std::string newParent)
{
auto foundState = mStates.find(state);
if(foundState != mStates.end()){
auto foundParent = mStates.find(newParent);
if(foundParent != mStates.end()){
foundState->second.mParent = &foundParent->second;
foundState->second.mDepth = foundParent->second.mDepth;
}else{
ofLogError("StateMachine") << "cant find new parent: " << newParent;
}
}else{
ofLogError("StateMachine") << "cant find state: " << state;
}
}
void StateMachine::requestState(std::string state, bool force)
{
if(force){
mRequestQueue.clear();
}
Request req;
req.state = std::move(state);
mRequestQueue.emplace_back(std::move(req));
}
void StateMachine::requestState(std::string state, Transition transition, bool force)
{
if(!force){
mRequestQueue.clear();
}
Request req;
req.state = std::move(state);
req.transition = std::move(transition);
mRequestQueue.emplace_back(std::move(req));
}
void StateMachine::update(size_t frame, float elapsedTime, float lastFrameTime)
{
if(mIsTransitioning){
auto percent = (elapsedTime - mTransition.startTime) / mTransition.duration;
switch (mTransition.type) {
case Transition::Type::TRANSITION_IN_ONLY:
{
if(percent >= 1.0f){
for (auto i = mNext.rbegin(); i != mNext.rend(); ++i){
auto state = (*i);
if(state->mTransitionInComplete)
state->mTransitionInComplete();
}
std::swap(mCurrent,mNext);
mNext.clear();
mIsTransitioning = false;
}else{
for(auto state : mNext){
if(state->mTransitionUpdate){
if(mTransition.easing)
state->mTransitionUpdate(TransitionDirection::IN, mTransition.easing(percent));
else
state->mTransitionUpdate(TransitionDirection::IN,percent);
}
}
}
}break;
case Transition::Type::TRANSITION_OUT_ONLY:
{
if(percent >= 1.0f){
for(auto state : mCurrent){
if(state->mTransitionOutComplete)
state->mTransitionOutComplete();
}
for(auto state : mCurrent){
if(state->mExit)
state->mExit();
}
std::swap(mCurrent,mNext);
mNext.clear();
mIsTransitioning = false;
}else{
for(auto state : mCurrent){
if(state->mTransitionUpdate){
if(mTransition.easing)
state->mTransitionUpdate(TransitionDirection::OUT, mTransition.easing(percent));
else
state->mTransitionUpdate(TransitionDirection::OUT,percent);
}
}
}
}break;
case Transition::Type::STAGGERED_TRANSITION:
{
if(percent >= 1.0f){
//done
for (auto i = mNext.rbegin(); i != mNext.rend(); ++i){
auto state = (*i);
if(state->mTransitionInComplete)
state->mTransitionInComplete();
}
std::swap(mCurrent,mNext);
mNext.clear();
mIsTransitioning = false;
}
//do one then the other
if(percent >= 0.5f){
//update the second half
if(!mStaggeredTransitionHalfComplete){
for(auto state : mCurrent){
if(state->mTransitionOutComplete)
state->mTransitionOutComplete();
}
for(auto state : mCurrent){
if(state->mExit)
state->mExit();
}
for (auto i = mNext.rbegin(); i != mNext.rend(); ++i){
auto state = (*i);
if(state->mEnter)
state->mEnter();
}
for (auto i = mNext.rbegin(); i != mNext.rend(); ++i){
auto state = (*i);
if(state->mTransitionIn)
state->mTransitionIn();
}
mStaggeredTransitionHalfComplete = true;
}
for(auto state : mNext){
if(state->mTransitionUpdate){
if(mTransition.easing)
state->mTransitionUpdate(TransitionDirection::IN, mTransition.easing(percent*2.f - 1.f));
else
state->mTransitionUpdate(TransitionDirection::IN,percent*2.f - 1.f);
}
}
}else{
//update the first half
for(auto state : mCurrent){
if(state->mTransitionUpdate){
if(mTransition.easing)
state->mTransitionUpdate(TransitionDirection::OUT, mTransition.easing(percent*2.f));
else
state->mTransitionUpdate(TransitionDirection::OUT,percent*2.f);
}
}
}
}break;
case Transition::Type::SIMULTANEOUS_TRANSITION:
{
if(percent >= 1.0f){
for(auto state : mCurrent){
if(state->mTransitionOutComplete)
state->mTransitionOutComplete();
}
for(auto state : mCurrent){
if(state->mExit)
state->mExit();
}
for (auto i = mNext.rbegin(); i != mNext.rend(); ++i){
auto state = (*i);
if(state->mTransitionInComplete)
state->mTransitionInComplete();
}
std::swap(mCurrent,mNext);
mNext.clear();
mIsTransitioning = false;
}else{
for(auto state : mCurrent){
if(state->mTransitionUpdate){
if(mTransition.easing)
state->mTransitionUpdate(TransitionDirection::OUT, mTransition.easing(percent));
else
state->mTransitionUpdate(TransitionDirection::OUT,percent);
}
}
for(auto state : mNext){
if(state->mTransitionUpdate){
if(mTransition.easing)
state->mTransitionUpdate(TransitionDirection::IN, mTransition.easing(percent));
else
state->mTransitionUpdate(TransitionDirection::IN,percent);
}
}
}
}break;
default: break;
}
if(!mCurrent.empty()){
for(auto state : mCurrent){
if(state->mUpdate)
state->mUpdate(frame, elapsedTime, lastFrameTime);
}
}
if(!mNext.empty()){
for(auto state : mNext){
if(state->mUpdate)
state->mUpdate(frame, elapsedTime, lastFrameTime);
}
}
}else{
bool processRequests = !mRequestQueue.empty();
while(processRequests){
auto req = mRequestQueue.front();
mRequestQueue.pop_front();
auto found = mStates.find(req.state);
if(found != mStates.end()){
mNext.clear();
State* end = &found->second;
State* start = nullptr;
if(!mCurrent.empty()){
start = mCurrent.front();
mCurrent.clear();
}
findCommonParent(&mRoot, start, end, mCurrent, mNext);
switch(req.transition.type){
case Transition::Type::NONE:
{
for(auto state : mCurrent){
if(state->mExit)
state->mExit();
}
for (auto i = mNext.rbegin(); i != mNext.rend(); ++i){
auto state = (*i);
if(state->mEnter)
state->mEnter();
}
std::swap(mCurrent,mNext);
mNext.clear();
}break;
case Transition::Type::TRANSITION_IN_ONLY:{
mTransition = req.transition;
mTransition.startTime = elapsedTime;
for(auto state : mCurrent){
if(state->mExit)
state->mExit();
}
for (auto i = mNext.rbegin(); i != mNext.rend(); ++i){
auto state = (*i);
if(state->mEnter)
state->mEnter();
}
for (auto i = mNext.rbegin(); i != mNext.rend(); ++i){
auto state = (*i);
if(state->mTransitionIn)
state->mTransitionIn();
}
mIsTransitioning = true;
processRequests = false;
}break;
case Transition::Type::TRANSITION_OUT_ONLY:{
mTransition = req.transition;
mTransition.startTime = elapsedTime;
for(auto state : mCurrent){
if(state->mTransitionOut)
state->mTransitionOut();
}
for (auto i = mNext.rbegin(); i != mNext.rend(); ++i){
auto state = (*i);
if(state->mEnter)
state->mEnter();
}
mIsTransitioning = true;
processRequests = false;
}break;
case Transition::Type::STAGGERED_TRANSITION:{
mStaggeredTransitionHalfComplete = false;
mTransition = req.transition;
mTransition.startTime = elapsedTime;
for(auto state : mCurrent){
if(state->mTransitionOut)
state->mTransitionOut();
}
mIsTransitioning = true;
processRequests = false;
}break;
case Transition::Type::SIMULTANEOUS_TRANSITION:
{
mTransition = req.transition;
mTransition.startTime = elapsedTime;
for(auto state : mCurrent){
if(state->mTransitionOut)
state->mTransitionOut();
}
for (auto i = mNext.rbegin(); i != mNext.rend(); ++i){
auto state = (*i);
if(state->mEnter)
state->mEnter();
}
for (auto i = mNext.rbegin(); i != mNext.rend(); ++i){
auto state = (*i);
if(state->mTransitionIn)
state->mTransitionIn();
}
mIsTransitioning = true;
processRequests = false;
}break;
}
}else{
ofLogError("StateMachine") << "No state by name: " << req.state;
}
processRequests = !mRequestQueue.empty();
}
if(!mCurrent.empty()){
for(auto state : mCurrent){
if(state->mUpdate)
state->mUpdate(frame, elapsedTime, lastFrameTime);
}
}
}
}
const std::string& StateMachine::getCurrentState() const { return mCurrent.front()->getName(); }
void StateMachine::findCommonParent( State* root, State* start, State* end, std::list<State*>& curStack, std::list<State*>& nextStack)
{
if(start == end){
//edge case of repeating a state
curStack.push_back(start);
nextStack.push_back(end);
return;
}else if(!start){
//edge case for no state to begin with, just traverse the enter tree
while(end != root){
nextStack.push_back(end);
end = end->mParent;
}
}else{
curStack.clear();
nextStack.clear();
//traverse trees up to root
while(start != nullptr){
curStack.push_back(start);
start = start->mParent;
}
while(end != nullptr){
nextStack.push_back(end);
end = end->mParent;
}
//find the common node
std::list<State*>::iterator exitCommon;
std::list<State*>::iterator enterCommon;
auto curIt = curStack.begin();
auto curEnd = curStack.end();
bool search = true;
while(curIt != curEnd && search){
auto nextIt = nextStack.begin();
auto nextEnd = nextStack.end();
while(nextIt != nextEnd && search){
if(*curIt == *nextIt){
exitCommon = curIt;
enterCommon = nextIt;
search = false;
}
++nextIt;
}
++curIt;
}
//erase from the common node to the root
curStack.erase(exitCommon, curStack.end());
nextStack.erase(enterCommon, nextStack.end());
}
}
}//end namespace media system
| 41.321739
| 138
| 0.373264
|
m1keall1son
|
ae5d5dafb6faf03dbd226a01d524543818e70295
| 1,706
|
cpp
|
C++
|
Leetcode/Dynamic Programming/burst-balloons.cpp
|
susantabiswas/competitive_coding
|
49163ecdc81b68f5c1bd90988cc0dfac34ad5a31
|
[
"MIT"
] | 2
|
2021-04-29T14:44:17.000Z
|
2021-10-01T17:33:22.000Z
|
Leetcode/Dynamic Programming/burst-balloons.cpp
|
adibyte95/competitive_coding
|
a6f084d71644606c21840875bad78d99f678a89d
|
[
"MIT"
] | null | null | null |
Leetcode/Dynamic Programming/burst-balloons.cpp
|
adibyte95/competitive_coding
|
a6f084d71644606c21840875bad78d99f678a89d
|
[
"MIT"
] | 1
|
2021-10-01T17:33:29.000Z
|
2021-10-01T17:33:29.000Z
|
/*
https://leetcode.com/problems/burst-balloons/
*/
class Solution {
public:
// iterative DP bottom up solution
int maxCoinsTabular(vector<int>& nums) {
if(nums.empty())
return 0;
const int N = nums.size();
// since nums[-1] = nums[N] = 1, pad the original nums
nums.insert(nums.begin(), 1), nums.emplace_back(1);
// dp(i, j): max coins when balloons in [i:j] are burst, we also
// add 2 more columns to account for -1 and N boundaries
vector<vector<int> > dp(N + 2, vector<int>(N + 2, 0));
// we approach the balloon bursting from bottom up.
// for a range [i:j], we find the max coins that we can get in that range
// if a balloon 'k' is the last one to be burst, i<=k<=j
// Also since we are thinking in the bottom up way, where the kth balloon is the
// last one to be burst, in the original array, we can still have [ : i-1] and [j+1 : ]
// balloons, so since kth balloon will be the last one in [i:j] range and the corner
// balloons of [ : i-1] and [j+1 : ] will be on its left and right respectively, so
// for bursting it we get nums[i-1] * nums[k] * nums[j+1] + dp[i : k-1] + dp[k+1 : j]
for(int l = 0; l < N; l++) {
for(int i = 1; i <= N - l; i++) {
int j = i + l;
for(int k = i; k <= j; k++) {
dp[i][j] = max(dp[i][j], dp[i][k-1] + nums[i-1] * nums[k] * nums[j+1] + dp[k+1][j]);
}
}
}
return dp[1][N];
}
int maxCoins(vector<int>& nums) {
return maxCoinsTabular(nums);
}
};
| 39.674419
| 104
| 0.512896
|
susantabiswas
|
ae6c22913deb9e610762e0a680a819fe7e878c3c
| 655
|
cpp
|
C++
|
doubling/abc167_d2.cpp
|
Takumi1122/data-structure-algorithm
|
6b9f26e4dbba981f034518a972ecfc698b86d837
|
[
"MIT"
] | null | null | null |
doubling/abc167_d2.cpp
|
Takumi1122/data-structure-algorithm
|
6b9f26e4dbba981f034518a972ecfc698b86d837
|
[
"MIT"
] | null | null | null |
doubling/abc167_d2.cpp
|
Takumi1122/data-structure-algorithm
|
6b9f26e4dbba981f034518a972ecfc698b86d837
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
// ダブリング
/*
参考リンク
ABC 167 D - Teleporter
https://atcoder.jp/contests/abc167/tasks/abc167_d
*/
const int D = 60;
const int MAX_N = 200005;
int to[D][MAX_N];
int main() {
int n;
ll k;
cin >> n >> k;
rep(i, n) {
cin >> to[0][i];
to[0][i]--;
}
rep(i, D - 1) rep(j, n) { to[i + 1][j] = to[i][to[i][j]]; }
int v = 0;
for (int i = D - 1; i >= 0; --i) {
ll l = 1ll << i;
if (l <= k) {
v = to[i][v];
k -= l;
}
}
cout << v + 1 << endl;
return 0;
}
| 15.595238
| 61
| 0.465649
|
Takumi1122
|
ae7c1014fe0d193a48a403d10670665db9cf211e
| 1,023
|
cpp
|
C++
|
Server/Player.cpp
|
jackv24/NetworkingAIE
|
bb8ae376f18e4c2cee9681dbe61e0f67180232cf
|
[
"MIT"
] | null | null | null |
Server/Player.cpp
|
jackv24/NetworkingAIE
|
bb8ae376f18e4c2cee9681dbe61e0f67180232cf
|
[
"MIT"
] | null | null | null |
Server/Player.cpp
|
jackv24/NetworkingAIE
|
bb8ae376f18e4c2cee9681dbe61e0f67180232cf
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <BitStream.h>
#include "GameMessages.h"
#include "GameConstants.h"
#include "Player.h"
Player::Player()
{
}
Player::~Player()
{
}
void Player::Move(float deltaTime)
{
if (moveDir != 0)
{
yPos += PADDLE_SPEED * moveDir * deltaTime;
if (yPos > STAGE_HEIGHT - PADDLE_HEIGHT)
yPos = STAGE_HEIGHT - PADDLE_HEIGHT;
else if (yPos < -STAGE_HEIGHT + PADDLE_HEIGHT)
yPos = -STAGE_HEIGHT + PADDLE_HEIGHT;
}
}
void Player::SendData(int clientID, RakNet::RakPeerInterface* pPeerInterface)
{
//Create new bitstream with client data ID
RakNet::BitStream bs;
bs.Write((RakNet::MessageID)GameMessages::ID_CLIENT_PLAYER_DATA);
m_id = clientID;
//Write client ID and data to stream
bs.Write(clientID);
bs.Write(moveDir);
bs.Write(yPos);
bs.Write(m_isReady);
std::cout << "Sent Player data" << clientID << std::endl;
//Broadcast packet (should be picked up by the server)
pPeerInterface->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, RakNet::UNASSIGNED_SYSTEM_ADDRESS, true);
}
| 21.765957
| 104
| 0.718475
|
jackv24
|
ae7c62774f36043f53012cd72b37ec76c33aa925
| 5,150
|
cpp
|
C++
|
class/app/widget_editor_color.cpp
|
TheMarlboroMan/go-fgj6
|
fa1cdfcd5ecaf4f0ea25b23890310e76fd2504bd
|
[
"Beerware"
] | null | null | null |
class/app/widget_editor_color.cpp
|
TheMarlboroMan/go-fgj6
|
fa1cdfcd5ecaf4f0ea25b23890310e76fd2504bd
|
[
"Beerware"
] | null | null | null |
class/app/widget_editor_color.cpp
|
TheMarlboroMan/go-fgj6
|
fa1cdfcd5ecaf4f0ea25b23890310e76fd2504bd
|
[
"Beerware"
] | null | null | null |
#include "widget_editor_color.h"
#include "framework_impl/input.h"
#include <def_video.h>
#include "definiciones.h"
#ifdef WINCOMPIL
/* Localización del parche mingw32... Esto debería estar en otro lado, supongo. */
#include <templates/parches_compat.h>
#endif
using namespace App;
Widget_editor_color::Widget_editor_color(const DLibV::Fuente_TTF& fuente, tcolor& f, tcolor& l)
:color_fondo(f), color_linea(l), cerrar(false), indice_actual(min_indice), t_pulsado(0.0f)
{
layout.mapear_fuente("akashi", fuente);
layout.parsear(env::data_path+"/data/layout/widget_color.dnot", "layout");
actualizar_layout();
}
void Widget_editor_color::dibujar(DLibV::Pantalla& pantalla)
{
using namespace DLibH;
layout.volcar(pantalla);
}
void Widget_editor_color::input(DFramework::Input& input, float delta)
{
if(input.es_input_down(Input::escape))
{
cerrar=true;
return;
}
if(input.es_input_down(Input::cursor_abajo)) cambiar_seleccion(1);
else if(input.es_input_down(Input::cursor_arriba)) cambiar_seleccion(-1);
else if(input.es_input_pulsado(Input::cursor_izquierda)) cambiar_color(-1, delta);
else if(input.es_input_pulsado(Input::cursor_derecha)) cambiar_color(1, delta);
else t_pulsado=0.0f;
if(input.es_eventos_input_texto ())
{
static_cast<DLibV::Representacion_TTF *>(layout.obtener_por_id("txt_input"))->asignar(input.acc_input_texto());
}
if(input.es_input_down(Input::enter) && input.acc_input_texto().size())
{
int val=0;
try
{
val=stoi(input.acc_input_texto());
}
catch(std::exception& e){}
cambiar_por_indice(indice_actual, val);
input.vaciar_input_texto();
static_cast<DLibV::Representacion_TTF *>(layout.obtener_por_id("txt_input"))->asignar("");
}
}
void Widget_editor_color::cambiar_por_indice(int indice, int val)
{
switch(indice)
{
case 0: cambiar(val, color_fondo.r, "txt_r_frente"); break;
case 1: cambiar(val, color_fondo.g, "txt_g_frente"); break;
case 2: cambiar(val, color_fondo.b, "txt_b_frente"); break;
case 3: cambiar(val, color_fondo.a, "txt_a_frente"); break;
case 4: cambiar(val, color_linea.r, "txt_r_linea"); break;
case 5: cambiar(val, color_linea.g, "txt_g_linea"); break;
case 6: cambiar(val, color_linea.b, "txt_b_linea"); break;
case 7: cambiar(val, color_linea.a, "txt_a_linea"); break;
}
}
int Widget_editor_color::valor_por_indice(int indice) const
{
switch(indice)
{
case 0: return color_fondo.r; break;
case 1: return color_fondo.g; break;
case 2: return color_fondo.b; break;
case 3: return color_fondo.a; break;
case 4: return color_linea.r; break;
case 5: return color_linea.g; break;
case 6: return color_linea.b; break;
case 7: return color_linea.a; break;
}
return 0;
}
bool Widget_editor_color::es_cerrar() const
{
return cerrar;
}
void Widget_editor_color::cambiar_seleccion(int dir)
{
indice_actual+=dir;
if(indice_actual < min_indice) indice_actual=min_indice;
else if(indice_actual > max_indice) indice_actual=max_indice;
int y=layout.const_int("y_selector")+(indice_actual * layout.const_int("salto_selector"));
layout.obtener_por_id("selector")->ir_a(layout.const_int("x_selector"), y);
}
void Widget_editor_color::cambiar_color(int dir, float delta)
{
if(t_pulsado==0.0f)
{
cambiar_por_indice(indice_actual, valor_por_indice(indice_actual)+dir);
t_pulsado+=delta;
}
else
{
if(t_pulsado > 0.6f)
{
cambiar_por_indice(indice_actual, valor_por_indice(indice_actual)+dir);
}
else
{
t_pulsado+=delta;
}
}
}
void Widget_editor_color::cambiar(int val, int& ref, const std::string& id)
{
if(val < 0) val=0;
else if(val > 255) val=255;
ref=val;
#ifdef WINCOMPIL
using namespace compat;
#else
using namespace std;
#endif
std::string cad_final=to_string(val);
static_cast<DLibV::Representacion_TTF *>(layout.obtener_por_id(id))->asignar(cad_final);
actualizar_colores();
}
void Widget_editor_color::actualizar_layout()
{
cambiar(color_fondo.r, color_fondo.r, "txt_r_frente");
cambiar(color_fondo.g, color_fondo.g, "txt_g_frente");
cambiar(color_fondo.b, color_fondo.b, "txt_b_frente");
cambiar(color_fondo.a, color_fondo.a, "txt_a_frente");
cambiar(color_linea.r, color_linea.r, "txt_r_linea");
cambiar(color_linea.g, color_linea.g, "txt_g_linea");
cambiar(color_linea.b, color_linea.b, "txt_b_linea");
cambiar(color_linea.a, color_linea.a, "txt_a_linea");
actualizar_colores();
}
void Widget_editor_color::actualizar_colores()
{
DLibV::Representacion_primitiva_caja * fondo=static_cast<DLibV::Representacion_primitiva_caja *>(layout.obtener_por_id("caja_frente"));
DLibV::Representacion_primitiva_caja * linea=static_cast<DLibV::Representacion_primitiva_caja *>(layout.obtener_por_id("caja_linea"));
auto f=[](DLibV::Representacion_primitiva_caja& rep, tcolor col)
{
rep.mut_rgb(col.r, col.g, col.b);
rep.establecer_alpha(col.a);
};
f(*fondo, color_fondo);
f(*linea, color_linea);
}
void Widget_editor_color::finalizar(DFramework::Input& input)
{
input.vaciar_input_texto();
input.finalizar_input_texto();
color_linea=color_fondo;
}
void Widget_editor_color::inicializar(DFramework::Input& input)
{
input.iniciar_input_texto();
}
| 26.546392
| 136
| 0.747379
|
TheMarlboroMan
|
ae826301e65217141d886d5c9cecc1330e2f9b2f
| 1,265
|
hpp
|
C++
|
src/utils/objectloader.hpp
|
vi3itor/Blunted2
|
318af452e51174a3a4634f3fe19b314385838992
|
[
"Unlicense"
] | 56
|
2020-07-22T22:11:06.000Z
|
2022-03-09T08:11:43.000Z
|
GameplayFootball/src/utils/objectloader.hpp
|
ElsevierSoftwareX/SOFTX-D-20-00016
|
48c28adb72aa167a251636bc92111b3c43c0be67
|
[
"MIT"
] | 9
|
2021-04-22T07:06:25.000Z
|
2022-01-22T12:54:52.000Z
|
GameplayFootball/src/utils/objectloader.hpp
|
ElsevierSoftwareX/SOFTX-D-20-00016
|
48c28adb72aa167a251636bc92111b3c43c0be67
|
[
"MIT"
] | 20
|
2017-11-07T16:52:32.000Z
|
2022-01-25T02:42:48.000Z
|
// written by bastiaan konings schuiling 2008 - 2014
// this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important.
// i do not offer support, so don't ask. to be used for inspiration :)
#ifndef _HPP_UTILS_OBJECTLOADER
#define _HPP_UTILS_OBJECTLOADER
#include "scene/scene3d/scene3d.hpp"
#include "scene/scene3d/node.hpp"
#include "utils/xmlloader.hpp"
namespace blunted {
class ObjectLoader {
public:
ObjectLoader();
~ObjectLoader();
// depricated: LoadObject now recurses, this would take away the need for a level->objects hierarchy
boost::intrusive_ptr<Node> LoadLevel(boost::shared_ptr<Scene3D> scene3D, const std::string &filename) const;
boost::intrusive_ptr<Node> LoadObject(boost::shared_ptr<Scene3D> scene3D, const std::string &filename, const Vector3 &offset = Vector3(0)) const;
protected:
boost::intrusive_ptr<Node> LoadObjectImpl(boost::shared_ptr<Scene3D> scene3D, const std::string &nodename, const XMLTree &objectTree, const Vector3 &offset) const;
void InterpretProperties(const map_XMLTree &tree, Properties &properties) const;
e_LocalMode InterpretLocalMode(const std::string &value) const;
};
}
#endif
| 35.138889
| 169
| 0.745455
|
vi3itor
|
ae84f1baee40d30a7bea10b0f4dcaa5056ed6a55
| 881
|
hpp
|
C++
|
app/app/render/line.hpp
|
muleax/slope
|
254138703163705b57332fc7490dd2eea0082b57
|
[
"MIT"
] | 6
|
2022-02-05T23:28:12.000Z
|
2022-02-24T11:08:04.000Z
|
app/app/render/line.hpp
|
muleax/slope
|
254138703163705b57332fc7490dd2eea0082b57
|
[
"MIT"
] | null | null | null |
app/app/render/line.hpp
|
muleax/slope
|
254138703163705b57332fc7490dd2eea0082b57
|
[
"MIT"
] | null | null | null |
#pragma once
#include "app/render/config.hpp"
#include "app/render/shader.hpp"
namespace slope::app {
struct LinePoint {
vec3 position;
vec3 color;
};
class LineShader : public Shader
{
public:
struct AttributeLayout {
static constexpr uint32_t POSITION = 0;
static constexpr uint32_t COLOR = 1;
};
struct UniformLayout {
static constexpr char VIEW_PROJECTION[] = "view_projection";
};
using Shader::Shader;
void set_view_projection(const mat44& value) const { set(m_view_proj_loc, value); }
private:
void cache_attribute_locations() override;
Location m_view_proj_loc = 0;
};
class LineRenderer {
public:
LineRenderer();
~LineRenderer();
void draw(const LinePoint* data, size_t count) const;
private:
RenderHandle m_line_buffer = 0;
RenderHandle m_line_vao = 0;
};
} // slope::app
| 19.152174
| 87
| 0.681044
|
muleax
|
ae86bf29878b03576c927d65956b6048a6fcb50e
| 360
|
cpp
|
C++
|
openjudge/01/06/09.cpp
|
TheBadZhang/OJ
|
b5407f2483aa630068343b412ecaf3a9e3303f7e
|
[
"Apache-2.0"
] | 1
|
2020-07-22T16:54:07.000Z
|
2020-07-22T16:54:07.000Z
|
openjudge/01/06/09.cpp
|
TheBadZhang/OJ
|
b5407f2483aa630068343b412ecaf3a9e3303f7e
|
[
"Apache-2.0"
] | 1
|
2018-05-12T12:53:06.000Z
|
2018-05-12T12:53:06.000Z
|
openjudge/01/06/09.cpp
|
TheBadZhang/OJ
|
b5407f2483aa630068343b412ecaf3a9e3303f7e
|
[
"Apache-2.0"
] | null | null | null |
#include <cstdio>
int main () {
int n;
scanf ("%d", &n);
int *A = new int [n];
int *B = new int [n];
for (int a = 0; a < n; a += 1) {
scanf ("%d", &A [a]);
}
for (int a = 0; a < n; a += 1) {
scanf ("%d", &B [a]);
}
long long int result = 0;
for (int a = 0; a < n; a += 1) {
result += B [a] * A [a];
}
printf ("%lld", result);
return 0;
}
| 16.363636
| 33
| 0.430556
|
TheBadZhang
|
ae87f8438828385e5a6786957c55a6ecdf0f3cbe
| 704
|
cc
|
C++
|
src/rvg.cc
|
jacquelineCelia/lexicon_discovery
|
1a46f885ad24d2c510ae42f096b054cc6f216fcd
|
[
"MIT"
] | 12
|
2016-01-05T08:34:52.000Z
|
2020-11-23T22:46:39.000Z
|
src/rvg.cc
|
jacquelineCelia/lexicon_discovery
|
1a46f885ad24d2c510ae42f096b054cc6f216fcd
|
[
"MIT"
] | null | null | null |
src/rvg.cc
|
jacquelineCelia/lexicon_discovery
|
1a46f885ad24d2c510ae42f096b054cc6f216fcd
|
[
"MIT"
] | 4
|
2016-08-11T22:16:40.000Z
|
2020-11-23T22:46:49.000Z
|
#include "rvg.h"
using namespace std;
using namespace boost;
using namespace boost::random;
RandomVarGen::RandomVarGen() {
// size_t SEED = time(0);
size_t SEED = 0;
generator.seed(SEED);
}
/*
float RandomVarGen::GetGammaSample(float a, float b) {
gamma_distribution<> dist(a, b);
return dist(generator);
}
*/
float RandomVarGen::GetUniformSample() {
uniform_real<> dist(0, 1);
float sample = dist(generator);
while (sample == 0 || sample == 1) {
sample = dist(generator);
}
return sample;
}
float RandomVarGen::GetNormalSample(float u, float v) {
normal_distribution<> dist(u, v);
return dist(generator);
}
RandomVarGen::~RandomVarGen() {
}
| 19.555556
| 55
| 0.65625
|
jacquelineCelia
|
ae8cd842181a439275b5c6bca94af9b1e5b600fa
| 9,171
|
cpp
|
C++
|
src/modules/ROOTObjectReader/ROOTObjectReaderModule.cpp
|
schmidtseb/allpix-squared
|
f0e47c35a4db405d4d49887e4e8eaffe69176bfa
|
[
"MIT"
] | null | null | null |
src/modules/ROOTObjectReader/ROOTObjectReaderModule.cpp
|
schmidtseb/allpix-squared
|
f0e47c35a4db405d4d49887e4e8eaffe69176bfa
|
[
"MIT"
] | null | null | null |
src/modules/ROOTObjectReader/ROOTObjectReaderModule.cpp
|
schmidtseb/allpix-squared
|
f0e47c35a4db405d4d49887e4e8eaffe69176bfa
|
[
"MIT"
] | null | null | null |
/**
* @file
* @brief Implementation of ROOT data file reader module
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "ROOTObjectReaderModule.hpp"
#include <climits>
#include <string>
#include <utility>
#include <TBranch.h>
#include <TKey.h>
#include <TObjArray.h>
#include <TTree.h>
#include "core/messenger/Messenger.hpp"
#include "core/utils/log.h"
#include "core/utils/type.h"
#include "objects/Object.hpp"
#include "objects/objects.h"
#include "core/utils/type.h"
using namespace allpix;
ROOTObjectReaderModule::ROOTObjectReaderModule(Configuration config, Messenger* messenger, GeometryManager* geo_mgr)
: Module(std::move(config)), messenger_(messenger), geo_mgr_(geo_mgr) {}
/**
* @note Objects cannot be stored in smart pointers due to internal ROOT logic
*/
ROOTObjectReaderModule::~ROOTObjectReaderModule() {
for(auto message_inf : message_info_array_) {
delete message_inf.objects;
}
}
/**
* Adds lambda function map to convert a vector of generic objects to a templated message containing this particular type of
* object from its typeid.
*/
template <typename T> static void add_creator(ROOTObjectReaderModule::MessageCreatorMap& map) {
map[typeid(T)] = [&](std::vector<Object*> objects, std::shared_ptr<Detector> detector = nullptr) {
std::vector<T> data;
for(auto& object : objects) {
data.emplace_back(std::move(*static_cast<T*>(object)));
}
if(detector == nullptr) {
return std::make_shared<Message<T>>(data);
}
return std::make_shared<Message<T>>(data, detector);
};
}
/**
* Uses SFINAE trick to call the add_creator function for all template arguments of a container class. Used to add creators
* for every object in a tuple of objects.
*/
template <template <typename...> class T, typename... Args>
static void gen_creator_map_from_tag(ROOTObjectReaderModule::MessageCreatorMap& map, type_tag<T<Args...>>) {
std::initializer_list<int> value{(add_creator<Args>(map), 0)...};
(void)value;
}
/**
* Wrapper function to make the SFINAE trick in \ref gen_creator_map_from_tag work.
*/
template <typename T> static ROOTObjectReaderModule::MessageCreatorMap gen_creator_map() {
ROOTObjectReaderModule::MessageCreatorMap ret_map;
gen_creator_map_from_tag(ret_map, type_tag<T>());
return ret_map;
}
void ROOTObjectReaderModule::init() {
// Read include and exclude list
if(config_.has("include") && config_.has("exclude")) {
throw InvalidValueError(config_, "exclude", "include and exclude parameter are mutually exclusive");
} else if(config_.has("include")) {
auto inc_arr = config_.getArray<std::string>("include");
include_.insert(inc_arr.begin(), inc_arr.end());
} else if(config_.has("exclude")) {
auto exc_arr = config_.getArray<std::string>("exclude");
exclude_.insert(exc_arr.begin(), exc_arr.end());
}
// Initialize the call map from the tuple of available objects
message_creator_map_ = gen_creator_map<allpix::OBJECTS>();
// Open the file with the objects
input_file_ = std::make_unique<TFile>(config_.getPath("file_name", true).c_str());
// Read all the trees in the file
TList* keys = input_file_->GetListOfKeys();
std::set<std::string> tree_names;
for(auto&& object : *keys) {
auto& key = dynamic_cast<TKey&>(*object);
if(std::string(key.GetClassName()) == "TTree") {
auto tree = static_cast<TTree*>(key.ReadObjectAny(nullptr));
// Check if a version of this tree has already been read
if(tree_names.find(tree->GetName()) != tree_names.end()) {
LOG(TRACE) << "Skipping copy of tree with name " << tree->GetName()
<< " because one with identical name has already been processed";
continue;
}
tree_names.insert(tree->GetName());
// Check if this tree should be used
if((!include_.empty() && include_.find(tree->GetName()) == include_.end()) ||
(!exclude_.empty() && exclude_.find(tree->GetName()) != exclude_.end())) {
LOG(TRACE) << "Ignoring tree with " << tree->GetName()
<< " objects because it has been excluded or not explicitly included";
continue;
}
trees_.push_back(tree);
}
}
if(trees_.empty()) {
LOG(ERROR) << "Provided ROOT file does not contain any trees, module is useless!";
}
// Loop over all found trees
for(auto& tree : trees_) {
// Loop over the list of branches and create the set of receiver objects
TObjArray* branches = tree->GetListOfBranches();
for(int i = 0; i < branches->GetEntries(); i++) {
auto* branch = static_cast<TBranch*>(branches->At(i));
// Add a new vector of objects and bind it to the branch
message_info message_inf;
message_inf.objects = new std::vector<Object*>;
message_info_array_.emplace_back(message_inf);
branch->SetAddress(&(message_info_array_.back().objects));
// Fill the rest of the message information
// FIXME: we want to index this in a different way
std::string branch_name = branch->GetName();
auto split = allpix::split<std::string>(branch_name, "_");
// Fetch information from the tree name
size_t expected_size = 2;
size_t det_idx = 0;
size_t name_idx = 1;
if(branch_name.front() == '_' || branch_name.empty()) {
--expected_size;
det_idx = INT_MAX;
--name_idx;
}
if(branch_name.find('_') == std::string::npos) {
--expected_size;
name_idx = INT_MAX;
}
// Check tree structure and if object type matches name
auto split_type = allpix::split<std::string>(branch->GetClassName(), "<>");
if(expected_size != split.size() || split_type.size() != 2 || split_type[1].size() <= 2) {
throw ModuleError("Tree is malformed and cannot be used for creating messages");
}
std::string class_name = split_type[1].substr(0, split_type[1].size() - 1);
std::string apx_namespace = "allpix::";
size_t ap_idx = class_name.find(apx_namespace);
if(ap_idx != std::string::npos) {
class_name.replace(ap_idx, apx_namespace.size(), "");
}
if(class_name != tree->GetName()) {
throw ModuleError("Tree contains objects of the wrong type");
}
if(name_idx != INT_MAX) {
message_info_array_.back().name = split[name_idx];
}
std::shared_ptr<Detector> detector = nullptr;
if(det_idx != INT_MAX) {
message_info_array_.back().detector = geo_mgr_->getDetector(split[det_idx]);
}
}
}
}
void ROOTObjectReaderModule::run(unsigned int event_num) {
--event_num;
for(auto& tree : trees_) {
if(event_num >= tree->GetEntries()) {
throw EndOfRunException("Requesting end of run because TTree only contains data for " +
std::to_string(event_num) + " events");
}
tree->GetEntry(event_num);
}
LOG(TRACE) << "Building messages from stored objects";
// Loop through all branches
for(auto message_inf : message_info_array_) {
auto objects = message_inf.objects;
// Skip empty objects in current event
if(objects->empty()) {
continue;
}
// Check if a pointer to a dispatcher method exist
auto first_object = (*objects)[0];
auto iter = message_creator_map_.find(typeid(*first_object));
if(iter == message_creator_map_.end()) {
LOG(INFO) << "Cannot dispatch message with object " << allpix::demangle(typeid(*first_object).name())
<< " because it not registered for messaging";
continue;
}
// Update statistics
read_cnt_ += objects->size();
// Create a message
std::shared_ptr<BaseMessage> message = iter->second(*objects, message_inf.detector);
// Dispatch the message
messenger_->dispatchMessage(this, message, message_inf.name);
}
}
void ROOTObjectReaderModule::finalize() {
int branch_count = 0;
for(auto& tree : trees_) {
branch_count += tree->GetListOfBranches()->GetEntries();
}
// Print statistics
LOG(INFO) << "Read " << read_cnt_ << " objects from " << branch_count << " branches";
// Close the file
input_file_->Close();
}
| 37.896694
| 124
| 0.61858
|
schmidtseb
|
ae8f8b92df0a7dec15e55b569a602f4dfcc2235f
| 384
|
cpp
|
C++
|
aashishgahlawat/codeforces/A/560-A/560-A-30841187.cpp
|
aashishgahlawat/CompetetiveProgramming
|
12d6b2682765ae05b622968b9a26b0b519e170aa
|
[
"MIT"
] | null | null | null |
aashishgahlawat/codeforces/A/560-A/560-A-30841187.cpp
|
aashishgahlawat/CompetetiveProgramming
|
12d6b2682765ae05b622968b9a26b0b519e170aa
|
[
"MIT"
] | null | null | null |
aashishgahlawat/codeforces/A/560-A/560-A-30841187.cpp
|
aashishgahlawat/CompetetiveProgramming
|
12d6b2682765ae05b622968b9a26b0b519e170aa
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
// your code goes here
int numberOfNotes;
cin>>numberOfNotes;
int noteValue;
while(numberOfNotes--){
cin>>noteValue;
if(noteValue==1){
cout<<-1;
return 0;
}
}
cout<<1;
return 0;
}
| 18.285714
| 37
| 0.611979
|
aashishgahlawat
|
ae91f1e1dfbd5c1f5278c1b2f99c649786c9a1a7
| 667
|
cpp
|
C++
|
WindowsOpenGLC++/SpaceInvaders/SpaceInvaders.cpp
|
BenjaminNitschke/MobileCourse
|
802ce81f7cd9ee44b35f13e4da302a9fbd29a2b6
|
[
"Apache-2.0"
] | 1
|
2015-06-20T09:09:29.000Z
|
2015-06-20T09:09:29.000Z
|
WindowsOpenGLC++/SpaceInvaders/SpaceInvaders.cpp
|
BenjaminNitschke/MobileCourse
|
802ce81f7cd9ee44b35f13e4da302a9fbd29a2b6
|
[
"Apache-2.0"
] | null | null | null |
WindowsOpenGLC++/SpaceInvaders/SpaceInvaders.cpp
|
BenjaminNitschke/MobileCourse
|
802ce81f7cd9ee44b35f13e4da302a9fbd29a2b6
|
[
"Apache-2.0"
] | null | null | null |
#include "stdafx.h"
#include "SpaceGame.h"
#include "SpaceInvadersVisualTests.h"
using namespace SpaceInvaders;
int _stdcall WinMain(struct HINSTANCE__ *hInstance, struct HINSTANCE__ *hPrevInstance,
char *lpszCmdLine, int nCmdShow)
{
//SpaceInvadersVisualTests().ShowEmptyWindow();
//SpaceInvadersVisualTests().ShowBlueBackground();
//SpaceInvadersVisualTests().DrawColoredTriangle();
//SpaceInvadersVisualTests().DrawTexturedBackground();
//SpaceInvadersVisualTests().DrawShip();
//SpaceInvadersVisualTests().ControlShip();
//SpaceInvadersVisualTests().DrawAllEnemies();
//SpaceInvadersVisualTests().MoveAllEnemies();
SpaceGame().PlayGame();
return 0;
}
| 33.35
| 86
| 0.790105
|
BenjaminNitschke
|
ae97d894cdfbb1543ac236fd19ccf9dc78e8d58c
| 2,136
|
hpp
|
C++
|
include/GamePlay.hpp
|
wooseokyourself/shmup
|
9174208561043210f86f3d4c411589ac5a9aa417
|
[
"MIT"
] | null | null | null |
include/GamePlay.hpp
|
wooseokyourself/shmup
|
9174208561043210f86f3d4c411589ac5a9aa417
|
[
"MIT"
] | 25
|
2021-03-19T11:32:35.000Z
|
2021-06-17T09:06:45.000Z
|
include/GamePlay.hpp
|
wooseokyourself/shmup
|
9174208561043210f86f3d4c411589ac5a9aa417
|
[
"MIT"
] | null | null | null |
#ifndef __GAMEPLAY__
#define __GAMEPLAY__
#include <iostream>
#include <vector>
#include <queue>
#include "core/Object.hpp"
#include "Constants.hpp"
#include "World.hpp"
#include "Aircraft.hpp"
#include "StraightMovingObjectManager.hpp"
#include "Planetary.hpp"
#include "Ai.hpp"
#include "Hud.hpp"
#include "Sun.hpp"
using namespace std;
class GamePlay {
public:
GamePlay();
~GamePlay();
void start();
void renderPerspectiveScene();
void renderOrthoScene();
void update(const bool* asyncKeyBuf, std::queue<unsigned char>& discreteKeyBuf);
private:
void handleAsyncKeyInput(const bool* asyncKeyBuf);
void handleDiscreteKeyInput(std::queue<unsigned char>& discreteKeyBuf);
void setViewTPS();
void setViewFPS();
void setView2D();
void handleHitNormal(StraightMovingObjectManager* attackerBulletManager, Aircraft* target);
void handleHitInstantKill(StraightMovingObjectManager* attackerBulletManager, Aircraft* target);
void handleHitDodge(StraightMovingObjectManager* attackerBulletManager, Aircraft* target);
void handleGotItem(Aircraft* target);
void afterPlayerHit();
void afterEnemyHit();
private:
void win();
void lose();
private: // Camera
glm::vec3 camPos;
glm::vec3 camAt;
glm::vec3 camUp;
private: // Perspective
World* perspectiveSceneRoot;
Sun* sun;
Aircraft* player;
Aircraft* enemy;
StraightMovingObjectManager* playerBulletManager;
StraightMovingObjectManager* enemyBulletManager;
StraightMovingObjectManager* itemManager;
Planetary* planetaryA;
Planetary* planetaryB;
glm::mat4 perspectiveLookAt;
glm::mat4 perspectiveProjection;
private: // Ortho
Hud* hud;
glm::mat4 orthoLookAt;
glm::mat4 orthoProjection;
private: // Lighting utility
int shadingType;
DirectionalLightFactors* dFactorsPtr;
std::vector<PointLightFactors*> pFactorsPtrs;
bool diffuseMapOn;
bool normalMapOn;
int lightingFlag;
private: // Variables for game play
Ai enemyAi;
int stage;
int gameMode;
int viewMode; // 3인칭, 1인칭
bool renderingMode;
};
#endif
| 24.551724
| 100
| 0.725655
|
wooseokyourself
|
ae9f9dbab06028fa0a59e71146ede96412826983
| 404
|
cpp
|
C++
|
cse419/LightOJ/1216/12044153_AC_0ms_1688kB.cpp
|
cosmicray001/academic
|
6aa142baeba4bb1ad73b8669e37305ca0b5102a7
|
[
"MIT"
] | 2
|
2020-09-02T12:07:47.000Z
|
2020-11-17T11:17:16.000Z
|
cse419/LightOJ/1216/12044153_AC_0ms_1688kB.cpp
|
cosmicray001/academic
|
6aa142baeba4bb1ad73b8669e37305ca0b5102a7
|
[
"MIT"
] | null | null | null |
cse419/LightOJ/1216/12044153_AC_0ms_1688kB.cpp
|
cosmicray001/academic
|
6aa142baeba4bb1ad73b8669e37305ca0b5102a7
|
[
"MIT"
] | 4
|
2020-08-11T14:23:34.000Z
|
2020-11-17T10:52:31.000Z
|
#include <bits/stdc++.h>
#define pi acos(-1.0)
using namespace std;
int main()
{
int t, c = 0;
double h, p, r1, r2, r3;
scanf("%d", &t);
while(t--){
scanf("%lf %lf %lf %lf", &r1, &r2, &h, &p);
r3 = r1 - (((r1 - r2) * (h - p)) / h);
double vol = (pi * p * (r2 * r2 + r3 * r3 + r2 * r3)) / 3.0;
printf("Case %d: %.8lf\n", ++c, vol);
}
return 0;
}
| 20.2
| 68
| 0.418317
|
cosmicray001
|
aea084551163eacf3fbed4826d3d54edba61b5c7
| 877
|
cpp
|
C++
|
3 - Branches/3.2 - Relational If-else/print_car_info.cpp
|
aTonyXiao/Zybook
|
36cd05a436c6ca007cdd14638cf5ee2a7724b889
|
[
"MIT"
] | 11
|
2017-11-17T07:31:44.000Z
|
2020-12-05T14:46:56.000Z
|
3 - Branches/3.2 - Relational If-else/print_car_info.cpp
|
aTonyXiao/Zybook
|
36cd05a436c6ca007cdd14638cf5ee2a7724b889
|
[
"MIT"
] | null | null | null |
3 - Branches/3.2 - Relational If-else/print_car_info.cpp
|
aTonyXiao/Zybook
|
36cd05a436c6ca007cdd14638cf5ee2a7724b889
|
[
"MIT"
] | 1
|
2019-10-15T20:58:51.000Z
|
2019-10-15T20:58:51.000Z
|
#include <iostream>
using namespace std;
/*
Write multiple if statements. If carYear is 1969 or earlier, print "Probably has few safety features." If 1970 or higher, print "Probably has seat belts." If 1990 or higher, print "Probably has anti-lock brakes." If 2000 or higher, print "Probably has air bags." End each phrase with period and newline. Ex: carYear = 1995 prints:
Probably has seat belts.
Probably has anti-lock brakes.
*/
int main() {
int carYear = 0;
carYear = 2000;
/* Your solution goes here */
if (carYear <= 1969){
cout << "Probably has few safety features.";
cout << endl;
}
if (carYear >= 1970){
cout << "Probably has seat belts.";
cout << endl;
}
if (carYear >= 1990){
cout << "Probably has anti-lock brakes.";
cout << endl;
}
if (carYear >= 2000){
cout << "Probably has air bags.";
cout << endl;
}
return 0;
}
| 24.361111
| 331
| 0.659065
|
aTonyXiao
|
0004016749c1318eecbc8c43e9b35cbe9facbbae
| 187
|
hpp
|
C++
|
Include/NinjaParty/Vertex.hpp
|
ThirdPartyNinjas/NinjaParty
|
320665104158d7ad0c7b0d3841870e23f37213a7
|
[
"MIT"
] | null | null | null |
Include/NinjaParty/Vertex.hpp
|
ThirdPartyNinjas/NinjaParty
|
320665104158d7ad0c7b0d3841870e23f37213a7
|
[
"MIT"
] | null | null | null |
Include/NinjaParty/Vertex.hpp
|
ThirdPartyNinjas/NinjaParty
|
320665104158d7ad0c7b0d3841870e23f37213a7
|
[
"MIT"
] | 1
|
2018-07-27T15:09:49.000Z
|
2018-07-27T15:09:49.000Z
|
#ifndef NINJAPARTY_VERTEX_HPP
#define NINJAPARTY_VERTEX_HPP
namespace NinjaParty
{
struct Vertex
{
float x, y;
float u, v;
float r, g, b, a;
};
}
#endif//NINJAPARTY_VERTEX_HPP
| 12.466667
| 29
| 0.716578
|
ThirdPartyNinjas
|
00087f5a6e0d31e4d1b28698e0328ec0d08730c2
| 380
|
cc
|
C++
|
racional/src/racional_funk.cc
|
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Shao486
|
35573801b8adc5a419d2787e22227daa3e5ad190
|
[
"MIT"
] | null | null | null |
racional/src/racional_funk.cc
|
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Shao486
|
35573801b8adc5a419d2787e22227daa3e5ad190
|
[
"MIT"
] | null | null | null |
racional/src/racional_funk.cc
|
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Shao486
|
35573801b8adc5a419d2787e22227daa3e5ad190
|
[
"MIT"
] | null | null | null |
/**
* Universidad de La Laguna
* Escuela Superior de Ingeniería y Tecnología
* Grado en Ingeniería Informática
* Informática Básica Grupo 2
* @author Shaowei Weng
* @date 06/01/2021
* @brief
* @see
*/
#include <iostream> //std::cout, std::endl
#include <string> //std::string
#include <cstdlib> //exit
#include "complejo.h"
| 21.111111
| 55
| 0.610526
|
ULL-ESIT-IB-2020-2021
|
001364af0d16817926fd6ebbfab1cfb942a95dc6
| 1,538
|
cpp
|
C++
|
Builder/main.cpp
|
fawcio/design_patters_examples
|
9393b53ca542255970bfdb7ce8e3978e55398cd0
|
[
"MIT"
] | null | null | null |
Builder/main.cpp
|
fawcio/design_patters_examples
|
9393b53ca542255970bfdb7ce8e3978e55398cd0
|
[
"MIT"
] | null | null | null |
Builder/main.cpp
|
fawcio/design_patters_examples
|
9393b53ca542255970bfdb7ce8e3978e55398cd0
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <memory>
#include <sstream>
#include <vector>
#include "XMLBuilder.hpp"
#include "GroovyStyleHTMLBuilder.hpp"
#include "PersonBuilder/PersonAddressBuilder.hpp"
#include "PersonBuilder/PersonBuilder.hpp"
#include "PersonBuilder/PersonJobBuilder.hpp"
// clang-format off
int main()
{
// XML fluent builder test
XMLElement root = XMLBuilder("ul")
.add_child("li", "hello")
.add_child("li", "world")
.add_child("li", "!");
XMLElement nestedList = XMLBuilder("ul")
.add_child("li", "nested")
.add_child("li", "hello")
.add_child("li", "world");
root.add_child(std::move(nestedList));
nestedList.add_child(XMLBuilder("nested_elem").add_child("key", "value"));
std::cout << root << std::endl;
// Grovy style HTML builder test
std::cout <<
P {
Img {"http://pokemon.com/pikachu.png"}
}
<< std::endl;
// Person facade builder
Person p = PersonBuilder()
.lives().at("123 London Road").with_postcode("SW1 1GB").in("London")
.works().at("PragmaSoft").as_a("Consultant").earning(10e6);
// Typical construction
Person p2;
p2.street_address = "Tenisowa 23A/2";
p2.post_code = "71-073";
p2.city = "Szczecin";
p2.company_name = "Mobica Limited";
p2.position = "Senior Software Engineer";
p2.annual_income = 100'000'000;
std::cout << p << std::endl;
std::cout << p2 << std::endl;
}
| 26.517241
| 76
| 0.594928
|
fawcio
|
0016ddeb84202d6249f47a6996d2d59f00300bf8
| 7,064
|
hpp
|
C++
|
src/Process.hpp
|
zlin888/irispl
|
ee2228eb1155c4cffb906a327b7257fb1d360590
|
[
"MIT"
] | 4
|
2020-04-01T05:45:30.000Z
|
2020-05-14T06:38:25.000Z
|
src/Process.hpp
|
zlin888/typed-scheme
|
ee2228eb1155c4cffb906a327b7257fb1d360590
|
[
"MIT"
] | null | null | null |
src/Process.hpp
|
zlin888/typed-scheme
|
ee2228eb1155c4cffb906a327b7257fb1d360590
|
[
"MIT"
] | null | null | null |
#ifndef PROCESS_HPP
#define PROCESS_HPP
#include <string>
#include <utility>
#include <vector>
#include <map>
#include <stdexcept>
#include <memory>
#include "Instruction.hpp"
#include "Utils.hpp"
#include "ModuleLoader.hpp"
#include "IrisObject.hpp"
#include "Heap.hpp"
using namespace std;
typedef int PID;
enum class ProcessState {
READY, RUNNING, SLEEPING, SUSPENDED, STOPPED
};
class StackFrame {
public:
StackFrame(std::shared_ptr<Closure> closure, int returnAddress) : closurePtr(closure),
returnAddress(returnAddress) {}
std::shared_ptr<Closure> closurePtr;
int returnAddress;
};
class Process {
public:
vector<string> opStack;
vector<StackFrame> fStack;
vector<Instruction> instructions;
map<string, int> labelAddressMap;
ProcessState state = ProcessState::READY;
Heap heap;
AST ast;
PID pid = 0;
int PC = 0;
std::shared_ptr<Closure> currentClosurePtr;
Process(PID newPid, const Module &module);
Instruction currentInstruction();
Instruction nextInstruction();
inline void step() { this->PC++; };
string popOperand();
void pushStackFrame(shared_ptr<Closure> closurePtr, int returnAddress);
StackFrame popStackFrame();
void pushOperand(const string &value);
string dereference(const string &variableName);
void pushCurrentClosure(int returnAddress);
Handle newClosure(int instructionAddress);
shared_ptr<struct Closure> getClosurePtr(Handle closureHandle);
void setCurrentClosure(Handle closureHandle);
void gotoAddress(int instructionAddress);
private:
void initLabelLineMap();
};
//=================================================================
// Preprocess
//=================================================================
void Process::initLabelLineMap() {
// Label is normally the indication of beginning of a function (lambda)
// this mapping represents the mapping between the label and the sourceIndex of the corresponding instructionStr
for (int i = 0; i < this->instructions.size(); ++i) {
Instruction instruction = this->instructions[i];
if (instruction.type == InstructionType::LABEL) {
this->labelAddressMap[instruction.instructionStr] = i;
}
}
}
//=================================================================
// PROCESS
//=================================================================
Instruction Process::currentInstruction() {
return this->instructions[PC];
}
Instruction Process::nextInstruction(){
return this->instructions[PC + 1];
}
Process::Process(PID newPid, const Module &module) {
this->pid = newPid;
// from module loader loads instructionStr (string -> instructionStr)
for (auto &i : module.ILCode) {
this->instructions.emplace_back(Instruction(i));
}
// The top closure (not need to worry about this, because this is just a lambda (closure) acted as a beginner
// > at the top of everything
this->currentClosurePtr = std::shared_ptr<Closure>(new Closure(-1, nullptr, TOP_NODE_HANDLE));
this->heap = module.ast.heap;
this->ast = module.ast;
this->heap.set(TOP_NODE_HANDLE, this->currentClosurePtr);
this->initLabelLineMap();
};
void Process::pushOperand(const string &value) {
this->opStack.push_back(value);
}
string Process::popOperand() {
if (this->opStack.empty()) {
throw std::overflow_error("[ERROR] pop from empty opStack : Process::popOperand");
} else {
string popValue = this->opStack.back();
this->opStack.pop_back();
return popValue;
}
}
// Process Closure related
void Process::pushStackFrame(std::shared_ptr<Closure> closurePtr, int returnAddress) {
StackFrame sf(closurePtr, returnAddress);
this->fStack.push_back(sf);
}
StackFrame Process::popStackFrame() {
if (this->fStack.empty()) {
throw std::overflow_error("[ERROR] pop from empty fStack : Process::popStackFrame");
} else {
StackFrame sf = this->fStack.back();
this->fStack.pop_back();
return sf;
}
}
void Process::pushCurrentClosure(int returnAddress) {
StackFrame sf(this->currentClosurePtr, returnAddress);
this->fStack.push_back(sf);
}
string Process::dereference(const string &variableName) {
// if variable is bounded, return it
if (this->currentClosurePtr->hasBoundVariable(variableName)) {
return this->currentClosurePtr->getBoundVariable(variableName);
}
// if variable is free,
if (this->currentClosurePtr->hasFreeVariable(variableName)) {
string freeVariableValue = this->currentClosurePtr->getFreeVariable(variableName);
auto closurePtr = this->currentClosurePtr;
auto topClosurePtr = this->getClosurePtr(TOP_NODE_HANDLE);
while (closurePtr != topClosurePtr) {
if (closurePtr->hasBoundVariable(variableName)) {
string boundVariableValue = closurePtr->getBoundVariable(variableName);
if (freeVariableValue != boundVariableValue) {
if (closurePtr->isDirtyVairable(variableName)) {
// If set! is used in one of the parentHandle closures to change the variable value in the closure
// where the varaible is bounded, the return variable will refer to the set! value
return boundVariableValue;
} else {
// If define is used to change the variable value, the variable value in the children closure
// will be return
return freeVariableValue;
}
} else {
return freeVariableValue;
}
}
closurePtr = closurePtr->parentClosurePtr;
}
}
throw std::runtime_error("'" + variableName + "'" + "is undefined : dereference");
// from current closure backtrack to the top_node_handle
}
Handle Process::newClosure(int instructionAddress) {
Handle newClosureHandle = this->heap.allocateHandle(IrisObjectType::CLOSURE);
this->heap.set(newClosureHandle, std::shared_ptr<Closure>(
new Closure(instructionAddress, this->currentClosurePtr, newClosureHandle)));
return newClosureHandle;
}
shared_ptr<Closure> Process::getClosurePtr(Handle closureHandle) {
auto schemeObjectPtr = this->heap.get(closureHandle);
if (schemeObjectPtr->irisObjectType == IrisObjectType::CLOSURE) {
return static_pointer_cast<Closure>(schemeObjectPtr);
} else {
throw std::invalid_argument("[ERROR] Handle is not a closureHandle : Process::getClosurePtr");
}
}
void Process::setCurrentClosure(Handle closureHandle) {
auto closurePtr = this->getClosurePtr(closureHandle);
this->currentClosurePtr = closurePtr;
}
void Process::gotoAddress(int instructionAddress) {
this->PC = instructionAddress;
}
#endif // !PROCESS_HPP
| 31.535714
| 122
| 0.640997
|
zlin888
|
00178c1eb5e14c62d5fbe1e65d87d819c45e1e7d
| 2,622
|
c++
|
C++
|
fm/fmHand.c++
|
camilleg/vss
|
27f1c8f73f8d7ef2d4e5de077e4b2ed7e4f72803
|
[
"MIT"
] | null | null | null |
fm/fmHand.c++
|
camilleg/vss
|
27f1c8f73f8d7ef2d4e5de077e4b2ed7e4f72803
|
[
"MIT"
] | null | null | null |
fm/fmHand.c++
|
camilleg/vss
|
27f1c8f73f8d7ef2d4e5de077e4b2ed7e4f72803
|
[
"MIT"
] | null | null | null |
#include "fm.h"
fmHand::fmHand(fmAlg* alg): VHandler(alg)
{
setTypeName("fmHand");
}
int fmHand::receiveMessage(const char* Message)
{
CommandFromMessage(Message);
if (CommandIs("SetFreq"))
{
ifFF(z,z2, setCarrierFreq(z, z2) );
ifF(z, setCarrierFreq(z) );
return Uncatch();
}
if (CommandIs("SetCarFreq"))
{
ifFF(z,z2, setCarrierFreq(z, z2) );
ifF(z, setCarrierFreq(z) );
return Uncatch();
}
if (CommandIs("SetModFreq"))
{
ifFF(z,z2, setModulatorFreq(z, z2) );
ifF(z, setModulatorFreq(z) );
return Uncatch();
}
if (CommandIs("SetCMratio"))
{
ifFF(z,z2, setCMratio(z, z2) );
ifF(z, setCMratio(z) );
return Uncatch();
}
if (CommandIs("SetMCratio"))
{
ifFF(z,z2, setMCratio(z, z2) );
ifF(z, setMCratio(z) );
return Uncatch();
}
if (CommandIs("SetModIndex"))
{
ifFF(z,z2, setModIndex(z, z2) );
ifF(z, setModIndex(z) );
return Uncatch();
}
if (CommandIs("SetCarFeedback"))
{
ifFF(z,z2, setCarFeedback(z, z2) );
ifF(z, setCarFeedback(z) );
return Uncatch();
}
if (CommandIs("SetModFeedback"))
{
ifFF(z,z2, setModFeedback(z, z2) );
ifF(z, setModFeedback(z) );
return Uncatch();
}
if (CommandIs("SetRatioMode"))
{
ifF( f, setRatioMode(f) );
ifNil( setRatioMode() );
// return Uncatch();
}
return VHandler::receiveMessage(Message);
}
void fmHand::SetAttribute(IParam iParam, float z)
{
if (iParam.FOnlyI())
{
switch (iParam.i)
{
case isetCarrierFreq:
if (!CheckFreq(z))
printf("fmHandler got bogus carrier freq %f.\n", z);
else
getAlg()->setCarrierFreq(carFreq = z);
break;
case isetModulatorFreq:
if (!CheckFreq(z))
printf("fmHandler got bogus modulator freq %f.\n", z);
else
getAlg()->setModulatorFreq(modFreq = z);
break;
case isetCMratio:
if (!CheckCMratio(z))
printf("fmHandler got bogus cmratio %f.\n", z);
else
getAlg()->setCMratio(cmRatio = z);
break;
case isetModIndex:
if (!CheckIndex(z))
printf("fmHandler got bogus mod index %f.\n", z);
else
getAlg()->setModIndex(modIndex = z);
break;
case isetCarFeedback:
if (!CheckFeedback(z))
printf("fmHandler got bogus car feedback value %f.\n", z);
else
getAlg()->setCarFeedback(carFeedback = z);
break;
case isetModFeedback:
if (!CheckFeedback(z))
printf("fmHandler got bogus mod feedback value %f.\n", z);
else
getAlg()->setModFeedback(modFeedback = z);
break;
default:
printf("vss error: fmHandler got bogus float-index %d.\n", iParam.i);
}
}
else
printf("vss error: fmHandler got bogus element-of-float-array-index %d.\n", iParam.i);
}
| 20.645669
| 88
| 0.636537
|
camilleg
|
0018deb8b7b6b1d0b5e54d218af4939858594eb3
| 576
|
cpp
|
C++
|
engine/kotek.core.containers.unordered_set/src/main_core_containers_unordered_set_dll.cpp
|
wh1t3lord/kotek
|
1e3eb61569974538661ad121ed8eb28c9e608ae6
|
[
"Apache-2.0"
] | null | null | null |
engine/kotek.core.containers.unordered_set/src/main_core_containers_unordered_set_dll.cpp
|
wh1t3lord/kotek
|
1e3eb61569974538661ad121ed8eb28c9e608ae6
|
[
"Apache-2.0"
] | null | null | null |
engine/kotek.core.containers.unordered_set/src/main_core_containers_unordered_set_dll.cpp
|
wh1t3lord/kotek
|
1e3eb61569974538661ad121ed8eb28c9e608ae6
|
[
"Apache-2.0"
] | null | null | null |
#include "../include/kotek_core_containers_unordered_set.h"
namespace Kotek
{
namespace Core
{
bool InitializeModule_Core_Containers_Unordered_Set(
ktkMainManager* p_manager)
{
return true;
}
bool SerializeModule_Core_Containers_Unordered_Set(
ktkMainManager* p_manager)
{
return true;
}
bool DeserializeModule_Core_Containers_Unordered_Set(
ktkMainManager* p_manager)
{
return true;
}
bool ShutdownModule_Core_Containers_Unordered_Set(
ktkMainManager* p_manager)
{
return true;
}
} // namespace Core
} // namespace Kotek
| 18.580645
| 59
| 0.753472
|
wh1t3lord
|
001b21579d46ae51d210924388e89b1fb1f89b2f
| 4,833
|
cpp
|
C++
|
ChipsEninge/02_Script/Deprecated/ColliderComponents/ACollider.cpp
|
jerrypoiu/DX11_ChipsEngine2021
|
a558fb0013259a380d68b66142fc48b575208980
|
[
"MIT"
] | 1
|
2021-01-25T11:38:21.000Z
|
2021-01-25T11:38:21.000Z
|
ChipsEninge/02_Script/Deprecated/ColliderComponents/ACollider.cpp
|
jerrypoiu/ChipsEngine
|
a558fb0013259a380d68b66142fc48b575208980
|
[
"MIT"
] | null | null | null |
ChipsEninge/02_Script/Deprecated/ColliderComponents/ACollider.cpp
|
jerrypoiu/ChipsEngine
|
a558fb0013259a380d68b66142fc48b575208980
|
[
"MIT"
] | null | null | null |
#include "ChipsSystem/Components/ColliderComponents/ACollider.h"
#include "ChipsSystem/Global/Global.h"
#include "ChipsSystem/Camera/Camera.h"
#include "ChipsSystem/Etc/Mathf.h"
#include "ChipsSystem/Etc/Debug.h"
#include "DirectX/Effects/Effects.h"
#include "DirectX/Effects/RenderStates.h"
namespace ChipsEngine
{
ACollider::ACollider(string _componentType) : AComponent(_componentType),
m_collisionShpae(COLLISION_SHAPE::NON), m_collisionLayer(COLLISION_LAYER::NON_FIXED)
{
#ifdef _DEBUG
m_isLoaded = false;
m_indexCount = 0;
m_vertexBuffer = nullptr;
m_indexBuffer = nullptr;
m_material.Ambient = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f);
m_material.Diffuse = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f);
m_material.Specular = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f);
m_material.Reflect = XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f);
#endif
}
VOID ACollider::SetCollisionEvent(COLLISION_STATE _collisionEventType, CollsitionEvent _collsitionEvent)
{
switch (_collisionEventType)
{
case COLLISION_STATE::ENTER:
m_collisionEnter = _collsitionEvent;
break;
case COLLISION_STATE::STAY:
m_collisionStay = _collsitionEvent;
break;
case COLLISION_STATE::EXIT:
m_collisionExit = _collsitionEvent;
break;
default:
break;
}
}
VOID ACollider::CalculateCollisionResult(bool _isCollision, GameObject* _coll)
{
if (m_collisionStates.find(_coll) == m_collisionStates.end())
{
m_collisionStates[_coll] = COLLISION_STATE::ENTER;
}
if (_isCollision)
{
switch (m_collisionStates[_coll])
{
case COLLISION_STATE::ENTER:
m_collisionStates[_coll] = COLLISION_STATE::STAY;
m_collisionEnter(_coll);
break;
case COLLISION_STATE::STAY:
m_collisionStates[_coll] = COLLISION_STATE::STAY;
m_collisionStay(_coll);
break;
}
}
else
{
if (m_collisionStates[_coll] == COLLISION_STATE::STAY)
{
m_collisionStates[_coll] = COLLISION_STATE::ENTER;
m_collisionExit(_coll);
}
}
}
VOID ACollider::Init()
{
#ifdef _DEBUG
InitGemometryBuffer();
//LoadTexture
DirectX::ScratchImage image;
DirectX::LoadFromDDSFile(TEXT("01_Asset/Texture/Collider.dds"), DirectX::DDS_FLAGS_NONE, nullptr, image);
DirectX::CreateShaderResourceView(Global::g_d3dDevice, image.GetImages(), image.GetImageCount(), image.GetMetadata(), &m_diffuseSRV);
#endif
m_collisionEnter = [](GameObject* _marObject) { Debug::Log(_marObject->GetName() + " Enter"); };
m_collisionStay = [](GameObject* _marObject) {};
m_collisionExit = [](GameObject* _marObject) { Debug::Log(_marObject->GetName() + " Exit"); };
m_collisionInfo = make_pair(this, XMFLOAT4());
m_collisionInfo.first = this;
CollisionManager::GetInstance()->AddCollision(&m_collisionInfo);
}
VOID ACollider::Update()
{
}
VOID ACollider::Render()
{
#ifdef _DEBUG
if (m_isLoaded == false)
return;
UINT stride = sizeof(Basic32);
UINT offset = 0;
float blendFactor[] = { 0.0f, 0.0f, 0.0f, 0.0f };
XMMATRIX world = XMMatrixScaling(m_collisionInfo.second.x + 0.01f, m_collisionInfo.second.y + 0.01f, m_collisionInfo.second.z + 0.01f)
* GetGameObject()->GetTransform()->GetWorldRotationMatrix()
* GetGameObject()->GetTransform()->GetWorldTranslationMatrix();
XMMATRIX view = Camera::GetInstance()->View();
XMMATRIX proj = Camera::GetInstance()->Proj();
XMMATRIX worldViewProj = world * view * proj;
XMMATRIX worldInvTranspose = Mathf::InverseTranspose(world);
Global::g_d3dImmediateContext->RSSetState(RenderStates::NoCullRS);
Global::g_d3dImmediateContext->IASetInputLayout(InputLayouts::Basic32);
Global::g_d3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
Global::g_d3dImmediateContext->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset);
Global::g_d3dImmediateContext->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0);
ID3DX11EffectTechnique* activeSkullTech = Effects::BasicFX->Light0TexTech;
D3DX11_TECHNIQUE_DESC techDesc;
activeSkullTech->GetDesc(&techDesc);
Effects::BasicFX->SetEyePosW(Camera::GetInstance()->GetTransform()->GetWorldPosition());
Effects::BasicFX->SetWorld(world);
Effects::BasicFX->SetWorldInvTranspose(worldInvTranspose);
Effects::BasicFX->SetDiffuseMap(m_diffuseSRV);
Effects::BasicFX->SetWorldViewProj(worldViewProj);
Effects::BasicFX->SetMaterial(m_material);
for (UINT p = 0; p < techDesc.Passes; ++p)
{
activeSkullTech->GetPassByIndex(p)->Apply(0, Global::g_d3dImmediateContext);
Global::g_d3dImmediateContext->OMSetBlendState(RenderStates::TransparentBS, blendFactor, 0xffffffff);
Global::g_d3dImmediateContext->DrawIndexed(m_indexCount, 0, 0);
}
#endif
}
VOID ACollider::Release()
{
m_collisionStates.clear();
#ifdef _DEBUG
SAFE_RELEASE(m_vertexBuffer);
SAFE_RELEASE(m_indexBuffer);
SAFE_RELEASE(m_diffuseSRV);
#endif
}
}
| 31.588235
| 136
| 0.740741
|
jerrypoiu
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.