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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5015a1e38b9238f7e1ed4d2facfb5c2797d1223f
| 102 |
cpp
|
C++
|
samples/win/stdafx.cpp
|
keima97/ouzel
|
e6673e678b4739235371a15ae3863942b692c5fb
|
[
"BSD-2-Clause"
] | null | null | null |
samples/win/stdafx.cpp
|
keima97/ouzel
|
e6673e678b4739235371a15ae3863942b692c5fb
|
[
"BSD-2-Clause"
] | null | null | null |
samples/win/stdafx.cpp
|
keima97/ouzel
|
e6673e678b4739235371a15ae3863942b692c5fb
|
[
"BSD-2-Clause"
] | null | null | null |
// Copyright (C) 2015 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "stdafx.h"
| 20.4 | 41 | 0.715686 |
keima97
|
5018af41fe7b65f08e4d739b40101ed699558645
| 17,945 |
cpp
|
C++
|
handlers/FilmHandlers.cpp
|
jedimahdi/movie-network
|
8b11febb3121ea31f94713528d270618b56bd327
|
[
"MIT"
] | 1 |
2020-09-03T14:53:11.000Z
|
2020-09-03T14:53:11.000Z
|
handlers/FilmHandlers.cpp
|
jedimahdi/movie-network
|
8b11febb3121ea31f94713528d270618b56bd327
|
[
"MIT"
] | null | null | null |
handlers/FilmHandlers.cpp
|
jedimahdi/movie-network
|
8b11febb3121ea31f94713528d270618b56bd327
|
[
"MIT"
] | null | null | null |
#include "FilmHandlers.h"
#include "../exceptions/BadRequest.h"
#include "../exceptions/PermissionDenied.h"
#include "../models/Comment.h"
#include "../models/Film.h"
#include <sstream>
#include <vector>
using namespace std;
map<string, string> ShowCreateFilm::handle(Request *req) {
map<string, string> context;
if (req->getSessionId() == "") {
throw Server::Exception("Permission Denied!");
} else {
User *user = user_controller->get_user(stoi(req->getSessionId()));
if (user->is_publisher()) {
context["is_publisher"] = "1";
} else {
context["is_publisher"] = "0";
}
context["logged_user_name"] = user->get_username();
}
return context;
}
CreateFilmHandler::CreateFilmHandler(FilmController *fc, UserController *uc, Recommendation *rc)
: film_controller(fc), user_controller(uc), recommendation(rc) {}
Response *CreateFilmHandler::callback(Request *req) {
if (req->getSessionId() == "")
return Response::redirect("/login");
int logged_user_id = stoi(req->getSessionId());
User *user = user_controller->get_user(logged_user_id);
if (!user->is_publisher()) {
Response *res = Response::redirect("/");
res->setStatus(403);
return res;
}
film_controller->create_film(
logged_user_id, req->getBodyParam("name"),
stoi(req->getBodyParam("year")), stoi(req->getBodyParam("length")),
stoi(req->getBodyParam("price")), req->getBodyParam("summary"),
req->getBodyParam("director"));
recommendation->on_add_film();
ostringstream message;
message << "Publisher " << user->get_username() << " with id " << user->get_id() << "register new film." << endl;
vector<User *> followers = user->get_followers();
for (size_t i = 0; i < followers.size(); i++) {
followers[i]->notify(message.str());
}
return Response::redirect("/films/add");
}
Response *ShowFilms::callback(Request *req) {
Response *res = new Response();
res->setHeader("Content-Type", "text/html");
ostringstream body;
if (req->getSessionId() == "")
return Response::redirect("/login");
User *user = user_controller->get_user(stoi(req->getSessionId()));
vector<Film *> films;
if (user->is_publisher()) {
films = film_controller->get_user_films(user->get_id(), req->getQueryParam("name"), req->getQueryParam("rate"),
req->getQueryParam("min_year"), req->getQueryParam("price"),
req->getQueryParam("max_year"), req->getQueryParam("director"));
} else {
films = film_controller->get_all_films(req->getQueryParam("name"), req->getQueryParam("rate"),
req->getQueryParam("min_year"), req->getQueryParam("price"),
req->getQueryParam("max_year"), req->getQueryParam("director"));
}
body << "<!DOCTYPE html>" << endl;
body << "<html lang='en'>" << endl;
body << "<head>" << endl;
body << " <meta charset='UTF-8'>" << endl;
body << " <meta name='viewport' content='width=device-width, initial-scale=1.0'>" << endl;
body << " <meta http-equiv='X-UA-Compatible' content='ie=edge'>" << endl;
body << " <link rel='stylesheet' href='bootstrap.css'>" << endl;
body << " <title>Home | Movie Network</title>" << endl;
body << "</head>" << endl;
body << "<body>" << endl;
body << " <div style='margin-bottom: 0 !important;' class='d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom shadow-sm'>" << endl;
body << " <h5 class='my-0 mr-md-auto font-weight-normal'>Movie Network</h5>" << endl;
body << " <nav class='my-2 my-md-0 mr-md-3'>" << endl;
body << " <a class='p-2 text-dark' href='/'>Home</a>" << endl;
if (user->is_publisher()) {
body << " <a class='p-2 text-dark' href='/films/add'>Add Film</a>" << endl;
}
body << " <a class='p-2 text-dark' href='/profile'>Profile</a>" << endl;
body << " </nav>" << endl;
body << " <a class='btn btn-outline-primary' href='/logout'>Logout</a>" << endl;
body << " </div>" << endl;
body << " <div class='album py-5 bg-light'>" << endl;
body << " <div class='container'>" << endl;
body << "<form method='GET' action='/'>" << endl;
body << " <div class='row'>" << endl;
body << "<div class='col-md-10 mb-4'><input name='director' type='text' class='form-control' placeholder='Search by director name'> </div>" << endl;
body << "<div class='col-md-2 mb-4'><button class='btn btn-secondary' type='submit'>Search</button> </div>" << endl;
body << "</div>" << endl;
body << "</form>" << endl;
body << " <div class='row'>" << endl;
for (size_t i = 0; i < films.size(); i++) {
body << "<div class='col-md-4'>" << endl;
body << "<div class='card mb-4 shadow-sm'>" << endl;
body << "<div class='card-body'>" << endl;
body << "<h5 class='card-title'>" << films[i]->get_name() << "</h5>" << endl;
body << "<p class='card-text'>"
<< "Director : " << films[i]->get_director() << "<br />"
<< "Price : " << films[i]->get_price() << "<br />"
<< "Rate : " << films[i]->get_rate() << "<br />"
<< "Year : " << films[i]->get_year() << "<br />"
<< "</p>" << endl;
body << "<div class='d-flex justify-content-between align-items-center'>" << endl;
body << "<div class='btn-group'>" << endl;
body << "<a href='/film?id=" << films[i]->get_id() << "' class='btn btn-sm btn-outline-secondary'>View</a>" << endl;
if (user->is_publisher()) {
body << "<a href='/delete_film?id=" << films[i]->get_id() << "' class='btn btn-sm btn-outline-secondary'>Delete</a>" << endl;
}
body << "</div>" << endl;
body << "<small class='text-muted'>" << films[i]->get_length() << " mins</small>" << endl;
body << "</div>" << endl;
body << "</div>" << endl;
body << "</div>" << endl;
body << "</div>" << endl;
}
body << " </div>" << endl;
body << " </div>" << endl;
body << " </div>" << endl;
body << "</body>" << endl;
body << "</html>" << endl;
res->setBody(body.str());
return res;
}
Response *ShowFilmDetails::callback(Request *req) {
if (req->getSessionId() == "")
return Response::redirect("/login");
Response *res = new Response();
res->setHeader("Content-Type", "text/html");
ostringstream body;
Film *film = film_controller->get_film(stoi(req->getQueryParam("id")));
User *user = user_controller->get_user(stoi(req->getSessionId()));
vector<int> film_ids = recommendation->get_films(film->get_id());
body << "<!DOCTYPE html>" << endl;
body << "<html lang='en'>" << endl;
body << "<head>" << endl;
body << " <meta charset='UTF-8'>" << endl;
body << " <meta name='viewport' content='width=device-width, initial-scale=1.0'>" << endl;
body << " <meta http-equiv='X-UA-Compatible' content='ie=edge'>" << endl;
body << " <link rel='stylesheet' href='bootstrap.css'>" << endl;
body << " <title>Home | Movie Network</title>" << endl;
body << "</head>" << endl;
body << "<body class='bg-light'>" << endl;
body << " <div style='margin-bottom: 0 !important;' class='d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 border-bottom shadow-sm'>" << endl;
body << " <h5 class='my-0 mr-md-auto font-weight-normal'>Movie Network</h5>" << endl;
body << " <nav class='my-2 my-md-0 mr-md-3'>" << endl;
body << " <a class='p-2 text-dark' href='/'>Home</a>" << endl;
if (user->is_publisher()) {
body << " <a class='p-2 text-dark' href='/films/add'>Add Film</a>" << endl;
}
body << " <a class='p-2 text-dark' href='/profile'>Profile</a>" << endl;
body << " </nav>" << endl;
body << " <a class='btn btn-outline-primary' href='/logout'>Logout</a>" << endl;
body << " </div>" << endl;
body << " <div class='container'>" << endl;
body << "<div class='d-flex align-items-center p-3 my-3 rounded shadow-sm bg-white'>" << endl;
body << "<div class='lh-100'>" << endl;
body << "<h2 class='lh-100'>" << film->get_name() << "</h2>" << endl;
body << "<p>Production Year: " << film->get_year() << "</p>" << endl;
body << "<p>Director: " << film->get_director() << "</p>" << endl;
body << "<p>Rate: " << film->get_rate() << "</p>" << endl;
body << "<p>Length: " << film->get_length() << " min</p>" << endl;
body << "<p>Price: " << film->get_price() << "</p>" << endl;
body << "<p>Summary: " << film->get_summary() << "</p>" << endl;
if (!film->is_member_of(user->get_purchased_films())) {
body << "<form method='POST' action='/buy'>" << endl;
body << "<input type='hidden' name='film_id' value='" << film->get_id() << "'>" << endl;
body << "<button type='submit' class='btn btn-primary'>Buy</button>" << endl;
body << "</form>" << endl;
} else {
body << "<form method='POST' action='/rate'>" << endl;
body << "<input type='hidden' name='film_id' value='" << film->get_id() << "'>" << endl;
body << "<input type='text' name='score' class='form-control' placeholder='Score'>" << endl;
body << "<button type='submit' class='btn btn-block btn-primary'>Rate</button>" << endl;
body << "</form>" << endl;
}
body << "</div>" << endl;
body << "</div>" << endl;
body << "<div class='my-3 p-3 bg-white rounded shadow-sm'>" << endl;
body << "<h6 class='border-bottom border-gray pb-2 mb-0'>Suggestions</h6>" << endl;
Film *f;
for (size_t i = 0; i < film_ids.size(); i++) {
f = film_controller->get_film(film_ids[i]);
body << "<div class='media text-muted pt-3'>" << endl;
body << "<div class='media-body pb-3 mb-0 small lh-125 border-bottom border-gray'>" << endl;
body << "<div class='d-flex justify-content-between align-items-center w-100'>" << endl;
body << "<strong class='text-gray-dark'>" << f->get_name() << " (" << f->get_director() << ")</strong>" << endl;
body << "<a href='/film?id=" << f->get_id() << "'>View</a>" << endl;
body << "</div>" << endl;
body << "<span class='d-block'>" << f->get_length() << " mins</span>" << endl;
body << "</div>" << endl;
body << "</div>" << endl;
}
body << "</div>" << endl;
body << " </div>" << endl;
body << "</body>" << endl;
body << "</html>" << endl;
res->setBody(body.str());
return res;
}
Response *DeleteFilmHandler::callback(Request *req) {
if (req->getSessionId() == "")
return Response::redirect("/login");
int logged_user_id = stoi(req->getSessionId());
User *user = user_controller->get_user(logged_user_id);
if (!user->is_publisher()) {
Response *res = Response::redirect("/");
res->setStatus(403);
return res;
}
int film_id = stoi(req->getQueryParam("id"));
film_controller->delete_film(film_id, logged_user_id);
recommendation->on_delete_film(film_id);
return Response::redirect("/");
}
Response *ShowPurchasedFilms::callback(Request *req) {
Response *res = new Response();
res->setHeader("Content-Type", "text/html");
ostringstream body;
if (req->getSessionId() == "")
return Response::redirect("/login");
User *user = user_controller->get_user(stoi(req->getSessionId()));
vector<Film *> films = user->get_purchased_films();
body << "<!DOCTYPE html>" << endl;
body << "<html lang='en'>" << endl;
body << "<head>" << endl;
body << " <meta charset='UTF-8'>" << endl;
body << " <meta name='viewport' content='width=device-width, initial-scale=1.0'>" << endl;
body << " <meta http-equiv='X-UA-Compatible' content='ie=edge'>" << endl;
body << " <link rel='stylesheet' href='bootstrap.css'>" << endl;
body << " <title>Home | Movie Network</title>" << endl;
body << "</head>" << endl;
body << "<body>" << endl;
body << " <div style='margin-bottom: 0 !important;' class='d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom shadow-sm'>" << endl;
body << " <h5 class='my-0 mr-md-auto font-weight-normal'>Movie Network</h5>" << endl;
body << " <nav class='my-2 my-md-0 mr-md-3'>" << endl;
body << " <a class='p-2 text-dark' href='/'>Home</a>" << endl;
if (user->is_publisher()) {
body << " <a class='p-2 text-dark' href='/films/add'>Add Film</a>" << endl;
}
body << " <a class='p-2 text-dark' href='/profile'>Profile</a>" << endl;
body << " </nav>" << endl;
body << " <a class='btn btn-outline-primary' href='/logout'>Logout</a>" << endl;
body << " </div>" << endl;
body << " <div class='album py-5 bg-light'>" << endl;
body << " <div class='container'>" << endl;
body << " <form method='POST' action='/money'>" << endl;
body << " <div class='row'>" << endl;
body << " <div class='col-md-6 mb-4'>" << endl;
body << " <h4>Add Money : </h4>" << endl;
body << " <div class='row'><div class='col-md-8'>" << endl;
body << " <input class='form-control' type='text' name='amount' placeholder='Amount'>" << endl;
body << " </div><div class='col-md-4'>" << endl;
body << " <button type='submit' class='btn btn-dark'>Add</button>" << endl;
body << " </div>" << endl;
body << " </div>" << endl;
body << " </div>" << endl;
body << " <div class='col-md-6 mb-4'>" << endl;
body << " <h4>Your Money : </h4>" << user->get_money() << endl;
body << " </div>" << endl;
body << " </div>" << endl;
body << " </form>" << endl;
body << " <hr />" << endl;
body << " <div class='row'>" << endl;
for (size_t i = 0; i < films.size(); i++) {
body << "<div class='col-md-4'>" << endl;
body << "<div class='card mb-4 shadow-sm'>" << endl;
body << "<div class='card-body'>" << endl;
body << "<h5 class='card-title'>" << films[i]->get_name() << "</h5>" << endl;
body << "<p class='card-text'>"
<< "Director : " << films[i]->get_director() << "<br />"
<< "Price : " << films[i]->get_price() << "<br />"
<< "Rate : " << films[i]->get_rate() << "<br />"
<< "Year : " << films[i]->get_year() << "<br />"
<< "</p>" << endl;
body << "<div class='d-flex justify-content-between align-items-center'>" << endl;
body << "<div class='btn-group'>" << endl;
body << "<a href='/film?id=" << films[i]->get_id() << "' class='btn btn-sm btn-outline-secondary'>View</a>" << endl;
body << "</div>" << endl;
body << "<small class='text-muted'>" << films[i]->get_length() << " mins</small>" << endl;
body << "</div>" << endl;
body << "</div>" << endl;
body << "</div>" << endl;
body << "</div>" << endl;
}
body << " </div>" << endl;
body << " </div>" << endl;
body << " </div>" << endl;
body << "</body>" << endl;
body << "</html>" << endl;
res->setBody(body.str());
return res;
}
Response *BuyFilmHandler::callback(Request *req) {
if (req->getSessionId() == "")
return Response::redirect("/login");
User *user = user_controller->get_user(stoi(req->getSessionId()));
Film *film = film_controller->get_film(stoi(req->getBodyParam("film_id")));
if (user->get_money() < film->get_price()) {
throw Server::Exception("You don't have enough money to buy this film!");
}
user->add_money(-film->get_price());
user->add_purchased_film(film);
film->sell();
recommendation->on_buy_film(film->get_id());
ostringstream message;
message << "User " << user->get_username() << " with id " << user->get_id() << " buy your film "
<< film->get_name() << " with id " << film->get_id() << "." << endl;
user_controller->get_user(film->get_user_id())->notify(message.str());
return Response::redirect("/film?id=" + req->getBodyParam("film_id"));
}
Response *RateFilmHandler::callback(Request *req) {
if (req->getSessionId() == "")
return Response::redirect("/login");
User *user = user_controller->get_user(stoi(req->getSessionId()));
Film *film = film_controller->get_film(stoi(req->getBodyParam("film_id")));
if (film->is_member_of(user->get_purchased_films())) {
film->rate_film(stoi(req->getBodyParam("score")));
ostringstream message;
message << "User " << user->get_username() << " with id " << user->get_id() << " rate your film "
<< film->get_name() << " with id " << film->get_id() << "." << endl;
user_controller->get_user(film->get_user_id())->notify(message.str());
} else {
throw Server::Exception("You must first buy this film to rate.");
}
return Response::redirect("/film?id=" + req->getBodyParam("film_id"));
}
Response *MoneyHandler::callback(Request *req) {
if (req->getSessionId() == "")
return Response::redirect("/login");
User *user = user_controller->get_user(stoi(req->getSessionId()));
user->add_money(stoi(req->getBodyParam("amount")));
return Response::redirect("/profile");
}
| 46.25 | 176 | 0.531011 |
jedimahdi
|
5018b141a2500b20faf3d680e229dcada4d1713c
| 770 |
cpp
|
C++
|
2020/03/pcapng-parse/main.cpp
|
NanXiao/code-for-my-blog
|
c2c4f59e438241696d938354bb14396f36f97748
|
[
"BSD-3-Clause"
] | 5 |
2020-03-03T21:00:05.000Z
|
2021-12-17T07:04:14.000Z
|
2020/03/pcapng-parse/main.cpp
|
NanXiao/code-for-my-blog
|
c2c4f59e438241696d938354bb14396f36f97748
|
[
"BSD-3-Clause"
] | null | null | null |
2020/03/pcapng-parse/main.cpp
|
NanXiao/code-for-my-blog
|
c2c4f59e438241696d938354bb14396f36f97748
|
[
"BSD-3-Clause"
] | 2 |
2020-05-10T18:12:21.000Z
|
2021-12-17T02:40:42.000Z
|
#include <iostream>
#include <PcapFileDevice.h>
int
main()
{
std::cout << pcap_lib_version() << '\n';
pcpp::PcapNgFileReaderDevice input_file("/Users/nanxiao/Downloads/capture.pcapng");
if (input_file.open()) {
std::cout << "Open successfully\n";
} else {
std::cerr << "Open failed\n";
return 1;
}
std::cout << input_file.getOS() << '\n';
std::cout << input_file.getHardware() << '\n';
std::cout << input_file.getCaptureApplication() << '\n';
std::cout << input_file.getCaptureFileComment() << '\n';
pcpp::RawPacket packet;
std::string comment;
for (size_t i = 1; i < 10; i++)
{
if (input_file.getNextPacket(packet, comment)) {
std::cout << i << ":" << comment << '\n';
} else {
std::cerr << "Get packet failed\n";
return 1;
}
}
}
| 22.647059 | 84 | 0.616883 |
NanXiao
|
501b2482b4a90a3a55d5d08380c319c154a03a9a
| 203 |
cpp
|
C++
|
src/FBStateNormal.cpp
|
LesmesWasNotHere/Footsketball
|
d8072eda69a3cab570c5a9094eeef0228582cac1
|
[
"MIT"
] | null | null | null |
src/FBStateNormal.cpp
|
LesmesWasNotHere/Footsketball
|
d8072eda69a3cab570c5a9094eeef0228582cac1
|
[
"MIT"
] | null | null | null |
src/FBStateNormal.cpp
|
LesmesWasNotHere/Footsketball
|
d8072eda69a3cab570c5a9094eeef0228582cac1
|
[
"MIT"
] | null | null | null |
#include "FBStateNormal.h"
#define OWN_DISTANCE = 13
FBStateNormal::FBStateNormal(FootsketBall& gameObject):_GameObject(gameObject)
{
}
bool FBStateNormal::Update(unsigned milis)
{
return true;
}
| 15.615385 | 78 | 0.768473 |
LesmesWasNotHere
|
501ba224ebc3cce46a06507b53164c6bd0ab0099
| 1,178 |
hpp
|
C++
|
include/P12218319/cio/benchmarks/Problem.hpp
|
p12218319/CIO
|
b302fec4d1b3e0f6f18bf8b83a4229fadd5091c0
|
[
"Apache-2.0"
] | null | null | null |
include/P12218319/cio/benchmarks/Problem.hpp
|
p12218319/CIO
|
b302fec4d1b3e0f6f18bf8b83a4229fadd5091c0
|
[
"Apache-2.0"
] | null | null | null |
include/P12218319/cio/benchmarks/Problem.hpp
|
p12218319/CIO
|
b302fec4d1b3e0f6f18bf8b83a4229fadd5091c0
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2016 Adam Smith & Fabio Caraffini (Original Java version)
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.
email : [email protected]
*/
#ifndef P12218319_CIO_PROBLEM_HPP
#define P12218319_CIO_PROBLEM_HPP
#include <cmath>
#include "P12218319\core\core.hpp"
namespace P12218319 { namespace cio {
template<const uint32_t DIMENTIONS>
class P12218319_EXPORT_API Problem {
public:
typedef double InputArray[DIMENTIONS];
typedef double BoundArray[DIMENTIONS][2];
private:
BoundArray mBounds;
public:
virtual P12218319_CALL ~Problem(){}
virtual double P12218319_CALL operator()(InputArray& x) const override throw() = 0;
};
}}
#endif
| 31 | 85 | 0.758913 |
p12218319
|
502adbbb70f2ae9c1a7186c42445eac4836a4a00
| 4,895 |
cpp
|
C++
|
src/confseq/boundaries.cpp
|
gostevehoward/confseq
|
a4d85ba77ccbde4b10ec4f73530122dc32b45178
|
[
"MIT"
] | 28 |
2019-09-23T19:19:11.000Z
|
2022-01-25T18:40:28.000Z
|
src/confseq/boundaries.cpp
|
WannabeSmith/confseq
|
8c847f8915e553c9fd1a7f3f0fec8f36e2074d42
|
[
"MIT"
] | 10 |
2019-09-23T02:41:12.000Z
|
2022-01-12T02:14:07.000Z
|
src/confseq/boundaries.cpp
|
WannabeSmith/confseq
|
8c847f8915e553c9fd1a7f3f0fec8f36e2074d42
|
[
"MIT"
] | 4 |
2019-09-23T01:36:30.000Z
|
2021-06-24T19:51:03.000Z
|
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include "uniform_boundaries.h"
using namespace pybind11::literals;
PYBIND11_MODULE(boundaries, m) {
m.doc() = R"pbdoc(
Uniform boundaries and mixture supermartingales. See package documentation
at https://github.com/gostevehoward/confseq.
All `*_bound()` functions implement uniform boundaries, and accept intrinsic
time `v` at which to evaluate the bound and crossing probability `alpha`.
All `*_log_mixture()` functions evaluate the logarithm of the mixture
supermartingale, and accept `s`, the value of the underlying martingale, and
`v`, the intrinsic time value.
All mixture functions accept `v_opt` and optionally `alpha_opt`. The
mixtures are then tuned to optimize the uniform boundary with crossing
probability `alpha_opt` at intrinsic time `v_opt`.
)pbdoc";
m.def("normal_log_mixture",
pybind11::vectorize(confseq::normal_log_mixture),
R"pbdoc(
Logarithm of mixture supermartingale for the one- or two-sided normal
mixture.
)pbdoc",
"s"_a, "v"_a, "v_opt"_a, "alpha_opt"_a=0.05, "is_one_sided"_a=true);
m.def("normal_mixture_bound",
pybind11::vectorize(confseq::normal_mixture_bound),
R"pbdoc(
One- or two-sided normal mixture uniform boundary.
)pbdoc",
"v"_a, "alpha"_a, "v_opt"_a, "alpha_opt"_a=0.05,
"is_one_sided"_a=true);
m.def("gamma_exponential_log_mixture",
pybind11::vectorize(confseq::gamma_exponential_log_mixture),
R"pbdoc(
Logarithm of mixture supermartingale for the gamma-exponential
mixture.
`c` is the sub-exponential scale parameter.
)pbdoc",
"s"_a, "v"_a, "v_opt"_a, "c"_a, "alpha_opt"_a=0.05);
m.def("gamma_exponential_mixture_bound",
pybind11::vectorize(confseq::gamma_exponential_mixture_bound),
R"pbdoc(
Gamma-exponential mixture uniform boundary.
`c` is the sub-exponential scale parameter.
)pbdoc",
"v"_a, "alpha"_a, "v_opt"_a, "c"_a, "alpha_opt"_a=0.05);
m.def("gamma_poisson_log_mixture",
pybind11::vectorize(confseq::gamma_poisson_log_mixture),
R"pbdoc(
Logarithm of mixture supermartingale for the gamma-Poisson mixture.
`c` is the sub-Poisson scale parameter.
)pbdoc",
"s"_a, "v"_a, "v_opt"_a, "c"_a, "alpha_opt"_a=0.05);
m.def("gamma_poisson_mixture_bound",
pybind11::vectorize(confseq::gamma_poisson_mixture_bound),
R"pbdoc(
Gamma-Poisson mixture uniform boundary.
`c` is the sub-Poisson scale parameter.
)pbdoc",
"v"_a, "alpha"_a, "v_opt"_a, "c"_a, "alpha_opt"_a=0.05);
m.def("beta_binomial_log_mixture",
pybind11::vectorize(confseq::beta_binomial_log_mixture),
R"pbdoc(
Logarithm of mixture supermartingale for the one- or two-sided
beta-binomial mixture.
`g` and `h` are the sub-Bernoulli range parameter.
)pbdoc",
"s"_a, "v"_a, "v_opt"_a, "g"_a, "h"_a, "alpha_opt"_a=0.05,
"is_one_sided"_a=true);
m.def("beta_binomial_mixture_bound",
pybind11::vectorize(confseq::beta_binomial_mixture_bound),
R"pbdoc(
One- or two-sided beta-binomial mixture uniform boundary.
`g` and `h` are the sub-Bernoulli range parameter.
)pbdoc",
"v"_a, "alpha"_a, "v_opt"_a, "g"_a, "h"_a, "alpha_opt"_a=0.05,
"is_one_sided"_a=true);
m.def("poly_stitching_bound",
pybind11::vectorize(confseq::poly_stitching_bound),
R"pbdoc(
Polynomial stitched uniform boundary.
* `v_min`: optimized-for intrinsic time
* `c`: sub-gamma scale parameter
* `s`: controls how crossing probability is distribted over epochs
* `eta`: controls the spacing of epochs
)pbdoc",
"v"_a, "alpha"_a, "v_min"_a, "c"_a=0, "s"_a=1.4, "eta"_a=2);
m.def("bernoulli_confidence_interval",
&confseq::bernoulli_confidence_interval,
R"pbdoc(
Confidence sequence for [0, 1]-bounded distributions.
This function returns confidence bounds for the mean of a Bernoulli
distribution, or more generally, any distribution with support in the
unit interval [0, 1]. (This applies to any bounded distribution after
rescaling.) The confidence bounds form a confidence sequence, so are
guaranteed to cover the true mean uniformly over time with probability 1
- `alpha`.
* `num_successes`: number of "successful" Bernoulli trials seen so far,
or more generally, sum of observed outcomes.
* `num_trials`: total number of observations seen so far.
)pbdoc",
"num_successes"_a, "num_trials"_a, "alpha"_a, "t_opt"_a,
"alpha_opt"_a=0.05);
}
| 40.454545 | 80 | 0.654137 |
gostevehoward
|
df25ca3b040496c41625f5e1557b0e1f788b29f4
| 654 |
cpp
|
C++
|
Algorithms/Strings/two-strings.cpp
|
CodeLogist/hackerrank-solutions
|
faecc4c9563a017eb61e83f0025aa9eb78fd33a1
|
[
"MIT"
] | 73 |
2016-09-14T18:20:41.000Z
|
2022-02-05T14:58:04.000Z
|
Algorithms/Strings/two-strings.cpp
|
A-STAR0/hackerrank-solutions-1
|
518cdd9049477d70c499ba4f51f06ac99178f0ab
|
[
"MIT"
] | 3 |
2017-03-03T01:12:31.000Z
|
2020-04-18T16:51:59.000Z
|
Algorithms/Strings/two-strings.cpp
|
A-STAR0/hackerrank-solutions-1
|
518cdd9049477d70c499ba4f51f06ac99178f0ab
|
[
"MIT"
] | 69 |
2017-03-02T19:03:54.000Z
|
2022-03-29T12:35:38.000Z
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
bool check(const string& _a, const string& _b) {
// O(n*m) lol no thanks
// more like O(n+m+52)
bool arr[52] = {false};
for(auto& a : _a)
arr[a - 'a'] = true;
for(auto& b : _b)
arr[b - 'a' + 26] = true;
for(int i = 0; i < 26; i++)
if (arr[i] && arr[i+26])
return true;
return false;
}
int main() {
int t; cin >> t;
string a, b;
while (t-- > 0) {
cin >> a >> b;
cout << (check(a,b) ? "YES" : "NO") << endl;
}
return 0;
}
| 19.235294 | 52 | 0.472477 |
CodeLogist
|
df276a14ee404b07e07c2344fdf9670154d65cc7
| 13,301 |
cpp
|
C++
|
cisstICP/cisstICP/DirPDTreeNode.cpp
|
sbillin/IMLP
|
38cbf6f528747ab5421f02f50b9bc3cd416cff8c
|
[
"BSD-3-Clause"
] | 14 |
2015-05-15T08:54:19.000Z
|
2021-12-14T06:16:37.000Z
|
cisstICP/DirPDTreeNode.cpp
|
Xingorno/cisstICP
|
dfa00db642a25500946a0c70a900fbc68e5af248
|
[
"BSD-3-Clause"
] | 3 |
2017-01-11T15:10:31.000Z
|
2020-12-28T16:16:32.000Z
|
cisstICP/DirPDTreeNode.cpp
|
Xingorno/cisstICP
|
dfa00db642a25500946a0c70a900fbc68e5af248
|
[
"BSD-3-Clause"
] | 8 |
2015-01-07T20:28:12.000Z
|
2018-07-13T15:40:39.000Z
|
// ****************************************************************************
//
// Copyright (c) 2014, Seth Billings, Russell Taylor, Johns Hopkins University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ****************************************************************************
#include <stdio.h>
#include <iostream>
#include <cisstVector.h>
#include <cisstCommon.h>
#include <cisstNumerical.h>
#include "DirPDTreeNode.h"
#include "DirPDTreeBase.h"
#include "utilities.h"
DirPDTreeNode::DirPDTreeNode(
int* pDataIndexArray,
int numIndexes,
DirPDTreeBase* pTree,
DirPDTreeNode* pParent) :
Bounds(),
pDataIndices(pDataIndexArray),
NData(numIndexes),
pLEq(NULL),
pMore(NULL),
pMyTree(pTree),
pParent(pParent)
{
// Compute local coordinate frame for this node
// computes local -> global
// take inverse to get global -> local
F = ComputeCovFrame(0, NData).Inverse();
for (int i = 0; i < NData; i++)
{
// since we don't know what type of datum we're dealing with
// (and since we want the bounds to completely hold all of this datum)
// we must place the enlarge bounds function at the tree level where
// the datum type is known.
pMyTree->EnlargeBounds(F, Datum(i), Bounds);
}
//std::stringstream ss;
//ss << F.Rotation().Row(0) << " " << F.Rotation().Row(1) << " "
// << " " << F.Rotation().Row(2) << " " << F.Translation() << std::endl;
////ss << "F:" << F << std::endl;
//fprintf(pMyTree->debugFile, "%s", ss.str().c_str());
}
DirPDTreeNode::~DirPDTreeNode()
{
if (pLEq != NULL) delete pLEq;
if (pMore != NULL) delete pMore;
}
// computes a local reference frame for this node based on the
// covariances of the datum sort positions; returns a frame
// transformation that converts points from local -> global coordinates
vctFrm3 DirPDTreeNode::ComputeCovFrame(int i0, int i1)
{ // returns a frame whose origin is at centroid and whose x-axis
// points in the direction of largest point spread
vct3 p(0, 0, 0);
vctRot3 R;
vctDouble3x3 C(0.0); // covariances
vctDouble3x3 Q; // Eigen vectors
vct3 e; // Eigen values
int i;
if (i1 <= i0) return vctFrm3();
int N = i1 - i0;
if (N < 5)
return (pParent != NULL) ? pParent->F : vctFrm3();
for (i = i0; i < i1; i++)
AccumulateCentroid(Datum(i), p);
p *= (1.0 / (i1 - i0));
for (i = i0; i < i1; i++)
{
AccumulateVariances(Datum(i), p, C);
}
// compute eigen decomposition of covariance matrix
ComputeCovEigenDecomposition_NonIter(C, e, Q);
int j = 0;
for (i = 1; i < 3; i++)
{
if (fabs(e(i)) > fabs(e(j))) j = i;
};
switch (j)
{
case 0: // E[0] is biggest eigen value
R = Q;
break;
case 1: // E[1] is biggest eigen value
// by right hand rule, map x->y, y->-x, z->z
// (assuming Q is a valid rotation matrix)
R.Column(0) = Q.Column(1);
R.Column(1) = -Q.Column(0);
R.Column(2) = Q.Column(2);
break;
case 2: // E[2] is biggest eigen value
// by right hand rule: x->z, y->y, z->-x
R.Column(0) = Q.Column(2);
R.Column(1) = Q.Column(1);
R.Column(2) = -Q.Column(0);
}
// SDB: should this be: [R',-R'*p]?
// no, because the function that calls this takes the inverse
return vctFrm3(R, p);
}
void DirPDTreeNode::AccumulateCentroid(int datum, vct3 &sum) const
{
sum += pMyTree->DatumSortPoint(datum);
}
// NOTE: providing the M argument is not important for the calling function,
// it merely helps with speed-up, as memory for the matrix doesn't
// have to be re-allocated N times
void DirPDTreeNode::AccumulateVariances(int datum, const vct3 &mean, vctDouble3x3 &C) const
{
static vctDouble3x3 M;
vct3 d = pMyTree->DatumSortPoint(datum) - mean;
M.OuterProductOf(d, d);
C += M;
}
// returns a value "top", for which datums should be on the pMore side if t>=top
int DirPDTreeNode::SortNodeForSplit()
{
int top = NData;
static int callNumber = 0;
callNumber++;
vct3 Ck; vct3 Ct;
vct3 r = F.Rotation().Row(0);
double px = F.Translation()[0];
for (int k = 0; k < top; k++) {
Ck = pMyTree->DatumSortPoint(Datum(k)); // 3D coordinate of datum in global coord system
double kx = r*Ck + px; // compute the x coordinate in local coord system
if (kx > 0) { // this one needs to go to the end of the line
while ((--top) > k) {
Ct = pMyTree->DatumSortPoint(Datum(top));
double tx = r*Ct + px;
if (tx <= 0) {
int Temp = Datum(k);
Datum(k) = Datum(top);
Datum(top) = Temp;
break; // from the "top" loop
};
}; // end of the "t" loop
}; // end of the kx>0 case; at this point F*datum.x-coord <= 0 for i=0,...,k
}; // end of k loop
return top;
}
DirPDTreeNode* DirPDTreeNode::GetChildSplitNode(const vct3 &datumPos)
{
// node split occurs along the local x-axis
double x_node = F.Rotation().Row(0)*datumPos + F.Translation()[0];
if (x_node > 0)
return pMore;
else
return pLEq;
}
// computes average orientation and max deviation for this node
// returns the running sum of vector orientations
vct3 DirPDTreeNode::ComputeOrientationParams()
{
// avg orientation
vct3 Nsum(0.0);
for (int i = 0; i < NumData(); i++)
{
Nsum += pMyTree->DatumNorm(Datum(i));
}
if (Nsum.Norm() < 1e-10)
{ // prevent division by zero
Navg.Assign(0.0, 0.0, 1.0);
}
else
{
Navg = Nsum.Normalized();
}
// max deviation from the avg orientation
// cos(theta) = n'*Navg (note n & Navg are unit vectors)
dThetaMax = 0.0;
vct3 n;
double Theta;
for (int i = 0; i < NumData(); i++)
{
n = pMyTree->DatumNorm(Datum(i));
Theta = acos(n.DotProduct(Navg));
if (Theta > dThetaMax) { dThetaMax = Theta; }
}
#ifdef DebugDirPDTree
fprintf(pMyTree->debugFile, " dThetaMax = %f\n", dThetaMax);
#endif
return Nsum;
}
// returns tree depth
int DirPDTreeNode::ConstructSubtree(int CountThresh, double DiagThresh) {
if (NumData() < CountThresh || Bounds.DiagonalLength() < DiagThresh)
{ // leaf node
#ifdef DebugDirPDTree
fprintf(pMyTree->debugFile, "Leaf Node: Ndata=%d\tDiagLen=%f\n", NumData(), Bounds.DiagonalLength());
#endif
ComputeOrientationParams();
myDepth = 0;
return myDepth;
}
int topLEq = SortNodeForSplit();
if (topLEq == NumData() || topLEq == 0)
{ // need this in case count threshold = 1
// TODO: avoid this case by NumData()<=CountThresh above
#ifdef DebugDirPDTree
fprintf(pMyTree->debugFile, "ERROR! all data splits to one node; topLEq=%d\tNdata=%d\tDiagLen=%f\n",
topLEq, NumData(), Bounds.DiagonalLength());
#endif
ComputeOrientationParams();
myDepth = 0; // stop here and do not split any further
return 0;
}
#ifdef DebugDirPDTree
fprintf(pMyTree->debugFile2, "NNodeL=%d\tNNodeR=%d\n", topLEq, NumData() - topLEq);
#endif
assert (topLEq>0&&topLEq<NumData());
int depthL, depthR;
pLEq = new DirPDTreeNode(pDataIndices, topLEq, pMyTree, this);
pMyTree->NNodes++;
depthL = pLEq->ConstructSubtree(CountThresh, DiagThresh);
pMore = new DirPDTreeNode(&pDataIndices[topLEq], NumData() - topLEq, pMyTree, this);
pMyTree->NNodes++;
depthR = pMore->ConstructSubtree(CountThresh, DiagThresh);
myDepth = (depthL > depthR ? depthL : depthR) + 1;
ComputeOrientationParams(); // TODO: speed up this one by using NSum from children
return myDepth;
}
// Check if a datum in this node has a lower match error than the error bound
// If a lower match error is found, set the new closest point, update error
// bound, and return the global datum index of the closest datum.
// Otherwise, return -1.
int DirPDTreeNode::FindClosestDatum(
const vct3 &v, const vct3 &n,
vct3 &closestPoint, vct3 &closestPointNorm,
double &ErrorBound,
unsigned int &numNodesVisited,
unsigned int &numNodesSearched)
{
numNodesVisited++;
// fast check if this node may contain a datum with better match error
if (pMyTree->pAlgorithm->NodeMightBeCloser(v, n, this, ErrorBound) == 0)
{
return -1;
}
// Search points w/in this node
int ClosestDatum = -1;
numNodesSearched++;
if (IsTerminalNode())
{ // a leaf node => look at each datum in the node
for (int i = 0; i < NData; i++)
{
int datum = Datum(i);
// fast check if this datum might have a lower match error than error bound
if (pMyTree->pAlgorithm->DatumMightBeCloser(v, n, datum, ErrorBound))
{ // a candidate
vct3 candidate;
vct3 candidateNorm;
// close check if this datum has a lower match error than error bound
double err = pMyTree->pAlgorithm->FindClosestPointOnDatum(v, n, candidate, candidateNorm, datum);
if (err < ErrorBound)
{
closestPoint = candidate;
closestPointNorm = candidateNorm;
ErrorBound = err;
ClosestDatum = datum;
}
}
}
return ClosestDatum;
}
// here if not a terminal node =>
// extend search to both child nodes
int ClosestLEq = -1;
int ClosestMore = -1;
// 1st call to pLEq updates both distance bound and closest point
// before 2nd call to pMore. If pMore returns (-1), then pMore had
// nothing better than pLEq and the resulting datum should be
// the return value of pLEq (whether that is -1 or a closer datum index)
ClosestLEq = pLEq->FindClosestDatum(v, n, closestPoint, closestPointNorm, ErrorBound, numNodesVisited, numNodesSearched);
ClosestMore = pMore->FindClosestDatum(v, n, closestPoint, closestPointNorm, ErrorBound, numNodesVisited, numNodesSearched);
ClosestDatum = (ClosestMore < 0) ? ClosestLEq : ClosestMore;
return ClosestDatum;
}
// find terminal node holding the specified datum
int DirPDTreeNode::FindTerminalNode(int datum, DirPDTreeNode **termNode)
{
if (!IsTerminalNode())
{
if (pLEq->FindTerminalNode(datum, termNode)) return 1;
if (pMore->FindTerminalNode(datum, termNode)) return 1;
return 0;
}
for (int i = 0; i < NData; i++)
{
if (Datum(i) == datum)
{
*termNode = this;
return 1;
}
}
return 0;
}
void DirPDTreeNode::PrintTerminalNodes(std::ofstream &fs)
{
if (IsTerminalNode())
{
fs << "Terminal Node:" << std::endl
<< " NData = " << NData << std::endl
<< F << std::endl
<< " Bounds Min: " << Bounds.MinCorner << std::endl
<< " Bounds Max: " << Bounds.MaxCorner << std::endl
<< " Datum Indices: " << std::endl;
for (int i = 0; i < NData; i++)
{
fs << " " << Datum(i) << std::endl;
}
}
else
{
pLEq->PrintTerminalNodes(fs);
pMore->PrintTerminalNodes(fs);
}
}
//void DirPDTreeNode::Print(FILE* chan, int indent)
//{
// fprintfBlanks(chan, indent);
// fprintf(chan, "NData = %d Bounds = [", NData); fprintfVct3(chan, Bounds.MinCorner);
// fprintf(chan, "] ["); fprintfVct3(chan, Bounds.MaxCorner);
// fprintf(chan, "]\n");
// fprintfBlanks(chan, indent);
// fprintfRodFrame(chan, "F =", F); fprintf(chan, "\n");
// if (IsTerminalNode())
// {
// for (int k = 0; k < NData; k++)
// {
// pMyTree->PrintDatum(chan, indent + 2, Datum(k));
// };
// fprintf(chan, "\n");
// }
// else
// {
// pLEq->Print(chan, indent + 2);
// pMore->Print(chan, indent + 2);
// };
//}
//void DirPDTreeNode::Print(int indent)
//{
// printf("NData = %d Bounds = [", NData); fprintfVct3(chan,Bounds.MinCorner);
// printf("] ["); fprintfVct3(chan, Bounds.MaxCorner);
// printf("]\n");
// std::cout << "F:" << std::endl << F << std::endl;
// if (IsTerminalNode())
// { for (int k=0;k<NData;k++)
// { pMyTree->PrintDatum(chan,indent+2,Datum(k));
// };
// }
// else
// { pLEq->Print(chan,indent+2);
// pMore->Print(chan,indent+2);
// };
//}
| 31.370283 | 125 | 0.636493 |
sbillin
|
df28ecaeef52f8de3864c5efcfd6a03cb13d7c34
| 615 |
cpp
|
C++
|
Engine/Code/Engine/Physics/GravityForceGenerator.cpp
|
cugone/Abrams2022
|
54efe5fdd7d2d9697f005ee45a171ecea68d0df8
|
[
"MIT"
] | null | null | null |
Engine/Code/Engine/Physics/GravityForceGenerator.cpp
|
cugone/Abrams2022
|
54efe5fdd7d2d9697f005ee45a171ecea68d0df8
|
[
"MIT"
] | 20 |
2021-11-29T14:09:33.000Z
|
2022-03-26T20:12:44.000Z
|
Engine/Code/Engine/Physics/GravityForceGenerator.cpp
|
cugone/Abrams2022
|
54efe5fdd7d2d9697f005ee45a171ecea68d0df8
|
[
"MIT"
] | null | null | null |
#include "Engine/Physics/GravityForceGenerator.hpp"
#include "Engine/Math/Vector2.hpp"
#include "Engine/Physics/RigidBody.hpp"
GravityForceGenerator::GravityForceGenerator(const Vector2& gravity) noexcept
: ForceGenerator()
, m_g(gravity) {
/* DO NOTHING */
}
void GravityForceGenerator::notify([[maybe_unused]] TimeUtils::FPSeconds deltaSeconds) const noexcept {
if(m_g == Vector2::Zero) {
return;
}
for(auto* body : m_observers) {
body->ApplyForce(m_g, deltaSeconds);
}
}
void GravityForceGenerator::SetGravity(const Vector2& newGravity) noexcept {
m_g = newGravity;
}
| 25.625 | 103 | 0.718699 |
cugone
|
df2a6844ceb58154b763d1760fd43b7d80a2f324
| 16,140 |
hpp
|
C++
|
kvm_core/include/kvm_serializer.hpp
|
pspglb/kvm
|
2dc3c4cc331dedaf5245e5c8a24bcba02b6ded32
|
[
"BSD-3-Clause"
] | 26 |
2020-12-03T11:13:42.000Z
|
2022-03-25T05:36:33.000Z
|
kvm_core/include/kvm_serializer.hpp
|
mtlynch/kvm
|
f0128edd493a758197a683cbb40dd409d16235e5
|
[
"BSD-3-Clause"
] | 4 |
2021-01-28T19:32:17.000Z
|
2021-06-01T15:01:42.000Z
|
kvm_core/include/kvm_serializer.hpp
|
mtlynch/kvm
|
f0128edd493a758197a683cbb40dd409d16235e5
|
[
"BSD-3-Clause"
] | 8 |
2020-12-04T01:30:21.000Z
|
2021-12-01T11:19:11.000Z
|
// Copyright 2020 Christopher A. Taylor
/*
Binary serialization tools
*/
#pragma once
#include "kvm_core.hpp"
#include <string.h>
namespace kvm {
//------------------------------------------------------------------------------
// Byte Order
// Swaps byte order in a 16-bit word
CORE_INLINE uint16_t ByteSwap16(uint16_t word)
{
return (word >> 8) | (word << 8);
}
// Swaps byte order in a 32-bit word
CORE_INLINE uint32_t ByteSwap32(uint32_t word)
{
const uint16_t swapped_old_hi = ByteSwap16(static_cast<uint16_t>(word >> 16));
const uint16_t swapped_old_lo = ByteSwap16(static_cast<uint16_t>(word));
return (static_cast<uint32_t>(swapped_old_lo) << 16) | swapped_old_hi;
}
// Swaps byte order in a 64-bit word
CORE_INLINE uint64_t ByteSwap64(uint64_t word)
{
const uint32_t swapped_old_hi = ByteSwap32(static_cast<uint32_t>(word >> 32));
const uint32_t swapped_old_lo = ByteSwap32(static_cast<uint32_t>(word));
return (static_cast<uint64_t>(swapped_old_lo) << 32) | swapped_old_hi;
}
//------------------------------------------------------------------------------
// POD Serialization
/**
* array[2] = { 0, 1 }
*
* Little Endian: word = 0x0100 <- first byte is least-significant
* Big Endian: word = 0x0001 <- first byte is most-significant
**/
/**
* word = 0x0102
*
* Little Endian: array[2] = { 0x02, 0x01 }
* Big Endian: array[2] = { 0x01, 0x02 }
**/
// Little-endian 16-bit read
CORE_INLINE uint16_t ReadU16_LE(const void* data)
{
#ifdef CORE_ALIGNED_ACCESSES
const uint8_t* u8p = reinterpret_cast<const uint8_t*>(data);
return ((uint16_t)u8p[1] << 8) | u8p[0];
#else
const uint16_t* word_ptr = reinterpret_cast<const uint16_t*>(data);
return *word_ptr;
#endif
}
// Big-endian 16-bit read
CORE_INLINE uint16_t ReadU16_BE(const void* data)
{
return ByteSwap16(ReadU16_LE(data));
}
// Little-endian 24-bit read
CORE_INLINE uint32_t ReadU24_LE(const void* data)
{
const uint8_t* u8p = reinterpret_cast<const uint8_t*>(data);
return ((uint32_t)u8p[2] << 16) | ((uint32_t)u8p[1] << 8) | u8p[0];
}
// Big-endian 24-bit read
CORE_INLINE uint32_t ReadU24_BE(const void* data)
{
const uint8_t* u8p = reinterpret_cast<const uint8_t*>(data);
return ((uint32_t)u8p[0] << 16) | ((uint32_t)u8p[1] << 8) | u8p[2];
}
// Little-endian 32-bit read
CORE_INLINE uint32_t ReadU32_LE(const void* data)
{
#ifdef CORE_ALIGNED_ACCESSES
const uint8_t* u8p = reinterpret_cast<const uint8_t*>(data);
return ((uint32_t)u8p[3] << 24) | ((uint32_t)u8p[2] << 16) | ((uint32_t)u8p[1] << 8) | u8p[0];
#else
const uint32_t* u32p = reinterpret_cast<const uint32_t*>(data);
return *u32p;
#endif
}
// Big-endian 32-bit read
CORE_INLINE uint32_t ReadU32_BE(const void* data)
{
#ifdef CORE_ALIGNED_ACCESSES
const uint8_t* u8p = reinterpret_cast<const uint8_t*>(data);
return ((uint32_t)u8p[0] << 24) | ((uint32_t)u8p[1] << 16) | ((uint32_t)u8p[2] << 8) | u8p[3];
#else
return ByteSwap32(ReadU32_LE(data));
#endif
}
// Little-endian 64-bit read
CORE_INLINE uint64_t ReadU64_LE(const void* data)
{
#ifdef CORE_ALIGNED_ACCESSES
const uint8_t* u8p = reinterpret_cast<const uint8_t*>(data);
return ((uint64_t)u8p[7] << 56) | ((uint64_t)u8p[6] << 48) | ((uint64_t)u8p[5] << 40) |
((uint64_t)u8p[4] << 32) | ((uint64_t)u8p[3] << 24) | ((uint64_t)u8p[2] << 16) |
((uint64_t)u8p[1] << 8) | u8p[0];
#else
const uint64_t* word_ptr = reinterpret_cast<const uint64_t*>(data);
return *word_ptr;
#endif
}
// Big-endian 64-bit read
CORE_INLINE uint64_t ReadU64_BE(const void* data)
{
#ifdef CORE_ALIGNED_ACCESSES
const uint8_t* u8p = reinterpret_cast<const uint8_t*>(data);
return ((uint64_t)u8p[0] << 56) | ((uint64_t)u8p[1] << 48) | ((uint64_t)u8p[2] << 40) |
((uint64_t)u8p[3] << 32) | ((uint64_t)u8p[4] << 24) | ((uint64_t)u8p[5] << 16) |
((uint64_t)u8p[6] << 8) | u8p[7];
#else
return ByteSwap64(ReadU64_LE(data));
#endif
}
// Little-endian 16-bit write
CORE_INLINE void WriteU16_LE(void* data, uint16_t value)
{
#ifdef CORE_ALIGNED_ACCESSES
uint8_t* u8p = reinterpret_cast<uint8_t*>(data);
u8p[1] = static_cast<uint8_t>(value >> 8);
u8p[0] = static_cast<uint8_t>(value);
#else
uint16_t* word_ptr = reinterpret_cast<uint16_t*>(data);
*word_ptr = value;
#endif
}
// Big-endian 16-bit write
CORE_INLINE void WriteU16_BE(void* data, uint16_t value)
{
#ifdef CORE_ALIGNED_ACCESSES
uint8_t* u8p = reinterpret_cast<uint8_t*>(data);
u8p[0] = static_cast<uint8_t>(value >> 8);
u8p[1] = static_cast<uint8_t>(value);
#else
uint16_t* word_ptr = reinterpret_cast<uint16_t*>(data);
*word_ptr = ByteSwap16(value);
#endif
}
// Little-endian 24-bit write
CORE_INLINE void WriteU24_LE(void* data, uint32_t value)
{
uint8_t* u8p = reinterpret_cast<uint8_t*>(data);
u8p[2] = static_cast<uint8_t>(value >> 16);
WriteU16_LE(u8p, static_cast<uint16_t>(value));
}
// Big-endian 24-bit write
CORE_INLINE void WriteU24_BE(void* data, uint32_t value)
{
uint8_t* u8p = reinterpret_cast<uint8_t*>(data);
u8p[0] = static_cast<uint8_t>(value >> 16);
WriteU16_BE(u8p + 1, static_cast<uint16_t>(value));
}
// Little-endian 32-bit write
CORE_INLINE void WriteU32_LE(void* data, uint32_t value)
{
#ifdef CORE_ALIGNED_ACCESSES
uint8_t* u8p = reinterpret_cast<uint8_t*>(data);
u8p[3] = (uint8_t)(value >> 24);
u8p[2] = static_cast<uint8_t>(value >> 16);
u8p[1] = static_cast<uint8_t>(value >> 8);
u8p[0] = static_cast<uint8_t>(value);
#else
uint32_t* word_ptr = reinterpret_cast<uint32_t*>(data);
*word_ptr = value;
#endif
}
// Big-endian 32-bit write
CORE_INLINE void WriteU32_BE(void* data, uint32_t value)
{
#ifdef CORE_ALIGNED_ACCESSES
uint8_t* u8p = reinterpret_cast<uint8_t*>(data);
u8p[0] = (uint8_t)(value >> 24);
u8p[1] = static_cast<uint8_t>(value >> 16);
u8p[2] = static_cast<uint8_t>(value >> 8);
u8p[3] = static_cast<uint8_t>(value);
#else
uint32_t* word_ptr = reinterpret_cast<uint32_t*>(data);
*word_ptr = ByteSwap32(value);
#endif
}
// Little-endian 64-bit write
CORE_INLINE void WriteU64_LE(void* data, uint64_t value)
{
#ifdef CORE_ALIGNED_ACCESSES
uint8_t* u8p = reinterpret_cast<uint8_t*>(data);
u8p[7] = static_cast<uint8_t>(value >> 56);
u8p[6] = static_cast<uint8_t>(value >> 48);
u8p[5] = static_cast<uint8_t>(value >> 40);
u8p[4] = static_cast<uint8_t>(value >> 32);
u8p[3] = static_cast<uint8_t>(value >> 24);
u8p[2] = static_cast<uint8_t>(value >> 16);
u8p[1] = static_cast<uint8_t>(value >> 8);
u8p[0] = static_cast<uint8_t>(value);
#else
uint64_t* word_ptr = reinterpret_cast<uint64_t*>(data);
*word_ptr = value;
#endif
}
// Big-endian 64-bit write
CORE_INLINE void WriteU64_BE(void* data, uint64_t value)
{
#ifdef CORE_ALIGNED_ACCESSES
uint8_t* u8p = reinterpret_cast<uint8_t*>(data);
u8p[0] = static_cast<uint8_t>(value >> 56);
u8p[1] = static_cast<uint8_t>(value >> 48);
u8p[2] = static_cast<uint8_t>(value >> 40);
u8p[3] = static_cast<uint8_t>(value >> 32);
u8p[4] = static_cast<uint8_t>(value >> 24);
u8p[5] = static_cast<uint8_t>(value >> 16);
u8p[6] = static_cast<uint8_t>(value >> 8);
u8p[7] = static_cast<uint8_t>(value);
#else
uint64_t* word_ptr = reinterpret_cast<uint64_t*>(data);
*word_ptr = ByteSwap64(value);
#endif
}
/**
* ReadBytes64_LE()
*
* Little-endian variable-bit read up to 8 bytes into a 64-bit unsigned integer.
*
* If bytes > 8, the left-most bytes are taken (truncating the MSBs).
*
* Returns the value, truncated to 64 bits.
*/
uint64_t ReadBytes64_LE(const void* data, int bytes);
/**
* WriteBytes64_BE()
*
* Little-endian variable-bit write up to 8 bytes from a 64-bit unsigned integer.
*
* WARNING: Does not support more than eight bytes.
*
* Precondition: 0 <= bytes <= 8
* If 0 bytes is specified, no writes are performed.
*/
void WriteBytes64_LE(void* data, int bytes, uint64_t value);
/**
* ReadBytes64_BE()
*
* Big-endian variable-bit read up to 8 bytes into a 64-bit unsigned integer.
*
* If bytes > 8, the right-most bytes are taken (truncating the MSBs).
*
* Returns the value, truncated to 64 bits.
*/
uint64_t ReadBytes64_BE(const void* data, int bytes);
/**
* WriteBytes64_BE()
*
* Big-endian variable-bit write up to 8 bytes from a 64-bit unsigned integer.
*
* WARNING: Does not support more than eight bytes.
*
* Precondition: 0 <= bytes <= 8
* If 0 bytes is specified, no writes are performed.
*/
void WriteBytes64_BE(void* data, int bytes, uint64_t value);
//------------------------------------------------------------------------------
// WriteByteStream
/// Helper class to serialize POD types to a byte buffer
struct WriteByteStream
{
/// Wrapped data pointer
uint8_t* Data = nullptr;
/// Number of wrapped buffer bytes
int BufferBytes = 0;
/// Number of bytes written so far by Write*() functions
int WrittenBytes = 0;
CORE_INLINE WriteByteStream()
{
}
CORE_INLINE WriteByteStream(const WriteByteStream& other)
: Data(other.Data)
, BufferBytes(other.BufferBytes)
, WrittenBytes(other.WrittenBytes)
{
}
CORE_INLINE WriteByteStream(void* data, int bytes)
: Data(reinterpret_cast<uint8_t*>(data))
, BufferBytes(bytes)
{
CORE_DEBUG_ASSERT(data != nullptr && bytes > 0);
}
CORE_INLINE uint8_t* Peek()
{
CORE_DEBUG_ASSERT(WrittenBytes <= BufferBytes);
return Data + WrittenBytes;
}
CORE_INLINE int Remaining()
{
CORE_DEBUG_ASSERT(WrittenBytes <= BufferBytes);
return BufferBytes - WrittenBytes;
}
CORE_INLINE WriteByteStream& Write8(uint8_t value)
{
CORE_DEBUG_ASSERT(WrittenBytes + 1 <= BufferBytes);
Data[WrittenBytes] = value;
WrittenBytes++;
return *this;
}
CORE_INLINE WriteByteStream& Write16_LE(uint16_t value)
{
CORE_DEBUG_ASSERT(WrittenBytes + 2 <= BufferBytes);
WriteU16_LE(Data + WrittenBytes, value);
WrittenBytes += 2;
return *this;
}
CORE_INLINE WriteByteStream& Write16_BE(uint16_t value)
{
CORE_DEBUG_ASSERT(WrittenBytes + 2 <= BufferBytes);
WriteU16_BE(Data + WrittenBytes, value);
WrittenBytes += 2;
return *this;
}
CORE_INLINE WriteByteStream& Write24_LE(uint32_t value)
{
CORE_DEBUG_ASSERT(WrittenBytes + 3 <= BufferBytes);
WriteU24_LE(Data + WrittenBytes, value);
WrittenBytes += 3;
return *this;
}
CORE_INLINE WriteByteStream& Write24_BE(uint32_t value)
{
CORE_DEBUG_ASSERT(WrittenBytes + 3 <= BufferBytes);
WriteU24_BE(Data + WrittenBytes, value);
WrittenBytes += 3;
return *this;
}
CORE_INLINE WriteByteStream& Write32_LE(uint32_t value)
{
CORE_DEBUG_ASSERT(WrittenBytes + 4 <= BufferBytes);
WriteU32_LE(Data + WrittenBytes, value);
WrittenBytes += 4;
return *this;
}
CORE_INLINE WriteByteStream& Write32_BE(uint32_t value)
{
CORE_DEBUG_ASSERT(WrittenBytes + 4 <= BufferBytes);
WriteU32_BE(Data + WrittenBytes, value);
WrittenBytes += 4;
return *this;
}
CORE_INLINE WriteByteStream& Write64_LE(uint64_t value)
{
CORE_DEBUG_ASSERT(WrittenBytes + 8 <= BufferBytes);
WriteU64_LE(Data + WrittenBytes, value);
WrittenBytes += 8;
return *this;
}
CORE_INLINE WriteByteStream& Write64_BE(uint64_t value)
{
CORE_DEBUG_ASSERT(WrittenBytes + 8 <= BufferBytes);
WriteU64_BE(Data + WrittenBytes, value);
WrittenBytes += 8;
return *this;
}
CORE_INLINE WriteByteStream& WriteBuffer(const void* source, int bytes)
{
CORE_DEBUG_ASSERT(source != nullptr || bytes == 0);
CORE_DEBUG_ASSERT(WrittenBytes + bytes <= BufferBytes);
memcpy(Data + WrittenBytes, source, bytes);
WrittenBytes += bytes;
return *this;
}
};
//------------------------------------------------------------------------------
// ReadByteStream
/// Helper class to deserialize POD types from a byte buffer
struct ReadByteStream
{
/// Wrapped data pointer
const uint8_t* const Data;
/// Number of wrapped buffer bytes
const int BufferBytes;
/// Number of bytes read so far by Read*() functions
int BytesRead = 0;
ReadByteStream(const void* data, int bytes)
: Data(reinterpret_cast<const uint8_t*>(data))
, BufferBytes(bytes)
{
CORE_DEBUG_ASSERT(data != nullptr);
}
CORE_INLINE const uint8_t* Peek()
{
CORE_DEBUG_ASSERT(BytesRead <= BufferBytes);
return Data + BytesRead;
}
CORE_INLINE int Remaining()
{
CORE_DEBUG_ASSERT(BytesRead <= BufferBytes);
return BufferBytes - BytesRead;
}
CORE_INLINE void Skip(int bytes)
{
CORE_DEBUG_ASSERT(BytesRead + bytes <= BufferBytes);
BytesRead += bytes;
}
CORE_INLINE const uint8_t* Read(int bytes)
{
const uint8_t* data = Peek();
Skip(bytes);
return data;
}
CORE_INLINE uint8_t Read8()
{
CORE_DEBUG_ASSERT(BytesRead + 1 <= BufferBytes);
uint8_t value = *Peek();
BytesRead++;
return value;
}
CORE_INLINE uint16_t Read16_LE()
{
CORE_DEBUG_ASSERT(BytesRead + 2 <= BufferBytes);
uint16_t value = ReadU16_LE(Peek());
BytesRead += 2;
return value;
}
CORE_INLINE uint16_t Read16_BE()
{
CORE_DEBUG_ASSERT(BytesRead + 2 <= BufferBytes);
uint16_t value = ReadU16_BE(Peek());
BytesRead += 2;
return value;
}
CORE_INLINE uint32_t Read24_LE()
{
CORE_DEBUG_ASSERT(BytesRead + 3 <= BufferBytes);
uint32_t value = ReadU24_LE(Peek());
BytesRead += 3;
return value;
}
CORE_INLINE uint32_t Read24_BE()
{
CORE_DEBUG_ASSERT(BytesRead + 3 <= BufferBytes);
uint32_t value = ReadU24_BE(Peek());
BytesRead += 3;
return value;
}
CORE_INLINE uint32_t Read32_LE()
{
CORE_DEBUG_ASSERT(BytesRead + 4 <= BufferBytes);
uint32_t value = ReadU32_LE(Peek());
BytesRead += 4;
return value;
}
CORE_INLINE uint32_t Read32_BE()
{
CORE_DEBUG_ASSERT(BytesRead + 4 <= BufferBytes);
uint32_t value = ReadU32_BE(Peek());
BytesRead += 4;
return value;
}
CORE_INLINE uint64_t Read64_LE()
{
CORE_DEBUG_ASSERT(BytesRead + 8 <= BufferBytes);
uint64_t value = ReadU64_LE(Peek());
BytesRead += 8;
return value;
}
CORE_INLINE uint64_t Read64_BE()
{
CORE_DEBUG_ASSERT(BytesRead + 8 <= BufferBytes);
uint64_t value = ReadU64_BE(Peek());
BytesRead += 8;
return value;
}
};
//------------------------------------------------------------------------------
// ReadBitStream
/// Helper class to deserialize POD types from a bit buffer
struct ReadBitStream
{
/// Based on ReadByteStream
ReadByteStream Reader;
/// Current workspace for reading
uint64_t Workspace = 0;
/// Number of unread bits in the workspace
int WorkspaceRemaining = 0;
ReadBitStream(const void* data, int bytes)
: Reader(data, bytes)
{
}
/// Read up to 32 bits.
/// Precondition: bits > 0, bits <= 32
uint32_t Read(int bits);
};
} // namespace kvm
| 29.23913 | 99 | 0.61171 |
pspglb
|
df2aebd6aed1ff09fb6b72d2224ee1957bb37474
| 757 |
cpp
|
C++
|
Code_Jam/codejam1.cpp
|
Jonsy13/Competitive-Programming
|
67e1918488c82b7ab8272b57dd4ffcff9dd4b1ac
|
[
"MIT"
] | null | null | null |
Code_Jam/codejam1.cpp
|
Jonsy13/Competitive-Programming
|
67e1918488c82b7ab8272b57dd4ffcff9dd4b1ac
|
[
"MIT"
] | null | null | null |
Code_Jam/codejam1.cpp
|
Jonsy13/Competitive-Programming
|
67e1918488c82b7ab8272b57dd4ffcff9dd4b1ac
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
int main(){
int T;
cin>>T;
while(T>0){
int N,ele;
cin>>N;
vector<vector<int>>vec;
for(int i=0;i<N;i++){
vector<int>vec2;
for(int j=0;j<N;j++){
cin>>ele;
vec2.push_back(ele);
}
vec.push_back(vec2);
}
int sum = 0;
for(int i=0;i<N;i++){
sum +=vec.at(i).at(i);
}
int flag = 0;
for(int i=0;i<N;i++){
auto it = std::unique(vec.at(i).begin(), vec.at(i).end());
flag = ((it == vec.at(i).end()) ? 0 : ++flag);
}
cout<<"No. of rows having duplicates : "<<flag<<endl;
T--;
};
}
| 22.264706 | 70 | 0.393659 |
Jonsy13
|
df2d731e6db854943d4b41656ef612c5ec01b381
| 1,357 |
hpp
|
C++
|
mogl/object/shader/shader.hpp
|
ninnghazad/moGL
|
041c5a891469eecfce904e170c62c016d0864cb6
|
[
"MIT"
] | 27 |
2015-02-26T12:27:19.000Z
|
2022-03-09T22:24:01.000Z
|
mogl/object/shader/shader.hpp
|
ninnghazad/moGL
|
041c5a891469eecfce904e170c62c016d0864cb6
|
[
"MIT"
] | 21 |
2015-01-07T15:30:55.000Z
|
2022-03-22T09:58:35.000Z
|
mogl/object/shader/shader.hpp
|
ninnghazad/moGL
|
041c5a891469eecfce904e170c62c016d0864cb6
|
[
"MIT"
] | 6 |
2015-02-25T13:02:30.000Z
|
2019-11-29T08:01:15.000Z
|
////////////////////////////////////////////////////////////////////////////////
/// Modern OpenGL Wrapper
///
/// Copyright (c) 2015 Thibault Schueller
/// This file is distributed under the MIT License
///
/// @file shader.hpp
/// @author Thibault Schueller <[email protected]>
////////////////////////////////////////////////////////////////////////////////
#ifndef MOGL_SHADER_INCLUDED
#define MOGL_SHADER_INCLUDED
#include <string>
#include <mogl/object/handle.hpp>
namespace mogl
{
class Shader : public Handle<GLuint>
{
public:
Shader(GLenum type);
~Shader();
Shader(const Shader& other) = delete;
Shader& operator=(const Shader& other) = delete;
public:
bool compile(const std::string& source);
bool compile(std::istream& sourceFile);
const std::string getSource() const;
GLenum getType() const;
const std::string getLog() const;
void get(GLenum property, GLint* value) const; // Direct call to glGetShaderiv()
GLint get(GLenum property) const;
bool isCompiled() const;
bool isValid() const override final;
private:
const GLenum _type;
};
}
#include "shader.inl"
#endif // MOGL_SHADER_INCLUDED
| 28.270833 | 103 | 0.518791 |
ninnghazad
|
df2f7804800329b095763f3c1918977db8572e44
| 1,683 |
hpp
|
C++
|
xyginext/src/network/NetConf.hpp
|
fallahn/xygine
|
c17e7d29bb57a5425a58abd3a05a843d6bac48e3
|
[
"Unlicense"
] | 220 |
2015-10-22T16:12:13.000Z
|
2022-03-16T18:51:11.000Z
|
xyginext/src/network/NetConf.hpp
|
fallahn/xygine
|
c17e7d29bb57a5425a58abd3a05a843d6bac48e3
|
[
"Unlicense"
] | 64 |
2016-05-05T19:17:13.000Z
|
2021-02-11T19:24:37.000Z
|
xyginext/src/network/NetConf.hpp
|
fallahn/xygine
|
c17e7d29bb57a5425a58abd3a05a843d6bac48e3
|
[
"Unlicense"
] | 33 |
2016-01-13T16:44:26.000Z
|
2021-11-05T21:57:24.000Z
|
/*********************************************************************
(c) Matt Marchant 2017 - 2021
http://trederia.blogspot.com
xygineXT - Zlib license.
This software is provided 'as-is', without any express or
implied warranty. In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
*********************************************************************/
#ifndef XY_NETCONF_HPP_
#define XY_NETCONF_HPP_
#include <memory>
namespace xy
{
/*!
\brief Used to ensure proper startup and shutdown
of Enet networking libraries
*/
class NetConf final
{
public:
NetConf();
~NetConf();
NetConf(const NetConf&) = delete;
NetConf(NetConf&&) = delete;
NetConf& operator = (const NetConf&) = delete;
NetConf& operator = (NetConf&&) = delete;
private:
friend class EnetClientImpl;
friend class EnetHostImpl;
static std::unique_ptr<NetConf> instance;
bool m_initOK;
};
}
#endif //XY_NETCONF_HPP_
| 28.05 | 70 | 0.660131 |
fallahn
|
df318fdd648d2c6c3ba1c3ed2e8f9c3443146cf2
| 2,378 |
inl
|
C++
|
include/memorypool/bufferpool.inl
|
yesheng86/cpp-utils
|
36cbf303b820a5c73b34922564be12419bec1e7d
|
[
"MIT"
] | null | null | null |
include/memorypool/bufferpool.inl
|
yesheng86/cpp-utils
|
36cbf303b820a5c73b34922564be12419bec1e7d
|
[
"MIT"
] | null | null | null |
include/memorypool/bufferpool.inl
|
yesheng86/cpp-utils
|
36cbf303b820a5c73b34922564be12419bec1e7d
|
[
"MIT"
] | null | null | null |
#pragma once
#include <functional>
#include <map>
#include "waitqueue/waitqueue.hpp"
#include "log/log.hpp"
using namespace util::memorypool;
using namespace util::buffer;
using namespace util::mt;
class BufferPool::Impl {
using BufferDescriptorQueue = WaitQueue<BufferDescriptor*>;
public:
Impl() = default;
~Impl() {
for (auto& pair: m_buf_desc_queue_map) {
BufferDescriptorQueue& queue = pair.second;
queue.stop_queue();
BufferDescriptor* p_desc = NULL;
while (queue.try_pop(p_desc)) {
if (p_desc->raw_ptr()) {
free(p_desc->raw_ptr());
}
if (p_desc) {
delete(p_desc);
}
}
}
THREAD_SAFE_PRINT("BufferPool::~Impl");
}
BufferDescriptorPtr alloc(uint32_t size) {
return alloc(0, size);
}
BufferDescriptorPtr alloc(uint32_t alignment, uint32_t size) {
BufferDescriptor* p_buf_desc = NULL;
uint64_t key = get_map_key(alignment, size);
if (!m_buf_desc_queue_map[key].try_pop(p_buf_desc)) {
void* buf_ptr = NULL;
if (alignment == 0) {
buf_ptr = std::malloc(size);
} else {
buf_ptr = std::aligned_alloc(alignment, size);
}
if (!buf_ptr) {
return nullptr;
}
p_buf_desc = new BufferDescriptor(buf_ptr, alignment, size);
if (!p_buf_desc) {
free(buf_ptr);
return nullptr;
}
}
return std::shared_ptr<BufferDescriptor>(p_buf_desc, std::bind(&BufferPool::Impl::deleter, this, std::placeholders::_1));
}
private:
void deleter(BufferDescriptor* p_buf_desc) {
if (p_buf_desc == NULL) {
return;
}
uint64_t key = get_map_key(p_buf_desc->alignment(), p_buf_desc->size());
m_buf_desc_queue_map[key].push(p_buf_desc);
}
inline uint64_t get_map_key(uint32_t alignment, uint32_t size) {
uint64_t key = (uint64_t)alignment;
key = (key << 32) | (uint64_t)size;
return key;
}
std::map<uint64_t, BufferDescriptorQueue> m_buf_desc_queue_map;
};
inline BufferPool::BufferPool()
: util::base::MoveOnly(), m_p_impl{ std::make_unique<Impl>() } {}
inline BufferPool::~BufferPool() = default;
inline BufferDescriptorPtr BufferPool::alloc(uint32_t size) {
return m_p_impl->alloc(size);
}
inline BufferDescriptorPtr BufferPool::alloc(uint32_t alignment, uint32_t size) {
return m_p_impl->alloc(alignment, size);
}
| 26.719101 | 125 | 0.655593 |
yesheng86
|
df3d2abefbbefd312b52d50c70c640db674197d6
| 1,183 |
cpp
|
C++
|
UVA Online Judge/10189 - Minesweeper.cpp
|
amiraslanaslani/UVA-Solved-Problems
|
1becb706702789a5f5e0ee86297561fc5b6e5ffc
|
[
"Unlicense"
] | null | null | null |
UVA Online Judge/10189 - Minesweeper.cpp
|
amiraslanaslani/UVA-Solved-Problems
|
1becb706702789a5f5e0ee86297561fc5b6e5ffc
|
[
"Unlicense"
] | null | null | null |
UVA Online Judge/10189 - Minesweeper.cpp
|
amiraslanaslani/UVA-Solved-Problems
|
1becb706702789a5f5e0ee86297561fc5b6e5ffc
|
[
"Unlicense"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
int t = 1;
while(true){
int io,jo;
cin >> io >> jo;
if( io == 0 && jo == 0)
return 0;
if(t != 1)
cout << endl;
cout << "Field #" << t << ":" << endl;
t ++;
char m[io][jo];
for(int i = 0;i < io;i ++)
for(int j = 0;j < jo;j ++)
cin >> m[i][j];
for(int i = 0;i < io;i ++)
for(int j = 0;j < jo;j ++){
if(m[i][j] == '*')
continue;
int c = 0;
for(int pi = -1;pi <= 1;pi ++)
for(int pj = -1;pj <= 1;pj ++)
if(i + pi >= 0 &&
i + pi < io &&
j + pj >= 0 &&
j + pj < jo &&
m[i + pi][j + pj] == '*')
c ++;
m[i][j] = c + '0';
}
for(int i = 0;i < io;i ++){
for(int j = 0;j < jo;j ++)
cout << m[i][j];
cout << '\n';
}
//cout << '\n';
}
return 0;
}
| 25.170213 | 52 | 0.252747 |
amiraslanaslani
|
df410b003d3a641134686f2e8a87f5cf1df3b292
| 16,150 |
cpp
|
C++
|
src/utils/regexwrappers.cpp
|
compiler-explorer/asm-parser
|
bc69e6bfd3b8b080a6781cc85dc89d127dd15a40
|
[
"BSD-2-Clause"
] | 12 |
2021-03-23T16:09:11.000Z
|
2022-02-06T09:04:58.000Z
|
src/utils/regexwrappers.cpp
|
compiler-explorer/asm-parser
|
bc69e6bfd3b8b080a6781cc85dc89d127dd15a40
|
[
"BSD-2-Clause"
] | 15 |
2020-10-04T16:47:19.000Z
|
2022-02-05T18:29:39.000Z
|
src/utils/regexwrappers.cpp
|
compiler-explorer/asm-parser
|
bc69e6bfd3b8b080a6781cc85dc89d127dd15a40
|
[
"BSD-2-Clause"
] | 1 |
2021-01-14T03:33:04.000Z
|
2021-01-14T03:33:04.000Z
|
#include "regexwrappers.hpp"
#include "regexes.hpp"
#include "utils.hpp"
#include <fmt/core.h>
inline int svtoi(const std::string_view sv)
{
return std::atoi(sv.data());
}
std::pair<int, int> AsmParser::AssemblyTextParserUtils::getSourceRef(const std::string_view line)
{
const auto match = AsmParser::Regexes::sourceTag(line);
if (match)
{
const auto file_index = svtoi(match.get<1>().to_view());
const auto line_index = svtoi(match.get<2>().to_view());
return { file_index, line_index };
}
else
{
return { 0, 0 };
}
}
std::optional<AsmParser::asm_file_def> AsmParser::AssemblyTextParserUtils::getFileDef(const std::string_view line)
{
const auto match = Regexes::fileFind(line);
if (match)
{
const auto file_index = svtoi(match.get<1>().to_view());
const auto file_name = match.get<2>().to_view();
const auto file_name_rest = match.get<4>().to_view();
if (!file_name_rest.empty())
{
return asm_file_def{ file_index, fmt::format("{}/{}", file_name, file_name_rest) };
}
else
{
return asm_file_def{ file_index, std::string(file_name) };
}
}
return std::nullopt;
}
std::string AsmParser::AssemblyTextParserUtils::expandTabs(const std::string_view line)
{
std::string expandedLine;
const std::string spaces = " ";
expandedLine.reserve(line.length());
auto extraChars = 0;
for (auto c : line)
{
if (c == '\t')
{
const auto total = expandedLine.length() + extraChars;
const auto spacesNeeded = (total + 8) & 7;
extraChars += spacesNeeded;
expandedLine += spaces.substr(spacesNeeded);
}
else
{
expandedLine += c;
}
}
return expandedLine;
}
static inline void rtrim(std::string &s)
{
s.erase(std::find_if(s.rbegin(), s.rend(),
[](unsigned char ch) {
return !std::isspace(ch);
})
.base(),
s.end());
}
static inline void ltrim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {
return !std::isspace(ch);
}));
}
std::string_view AsmParser::AssemblyTextParserUtils::getLineWithoutComment(const std::string_view line)
{
bool spacing = false;
bool stillStarting = true;
auto lastit = line.end();
for (auto it = line.begin(); it != line.end(); it++)
{
auto c = *it;
if (c == ';' || c == '#')
{
if (!spacing)
lastit = it;
break;
}
else if (spacing)
{
if (!is_whitespace(c))
{
spacing = false;
}
}
else if (is_whitespace(c))
{
if (!stillStarting)
{
spacing = true;
lastit = it;
}
}
else
{
stillStarting = false;
}
}
return std::string_view{ line.begin(), lastit };
}
std::string_view AsmParser::AssemblyTextParserUtils::getLineWithoutCommentAndStripFirstWord(const std::string_view line)
{
bool wordstarted = false;
bool wordended = false;
bool spacing = false;
auto lastit = line.end();
auto afterfirstword = line.begin();
for (auto it = line.begin(); it != line.end(); it++)
{
auto c = *it;
if (c == ';' || c == '#')
{
auto nextit = it + 1;
if (nextit != line.end())
{
auto nextchar = *nextit;
// it's only a comment if the ; or # is followed by a whitespace
if (nextchar != ' ' && nextchar != '\t')
{
continue;
}
}
if (!spacing)
lastit = it;
break;
}
else if (!wordstarted && ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')))
{
wordstarted = true;
}
else if (wordstarted && !wordended && is_whitespace(c))
{
wordended = true;
afterfirstword = it;
}
else if (wordended)
{
if (spacing)
{
if (!is_whitespace(c))
{
lastit = line.end();
spacing = false;
}
}
else if (is_whitespace(c))
{
spacing = true;
lastit = it;
}
}
}
return std::string_view{ afterfirstword, lastit };
}
bool AsmParser::AssemblyTextParserUtils::is_probably_label(const std::string_view line)
{
const auto filtered = getLineWithoutComment(line);
return (filtered.ends_with(":"));
}
std::string AsmParser::AssemblyTextParserUtils::fixLabelIndentation(const std::string_view line)
{
std::string filtered{ line };
if (is_probably_label(line))
ltrim(filtered);
return filtered;
}
std::vector<AsmParser::asm_label> AsmParser::AssemblyTextParserUtils::getUsedLabelsInLine(const std::string_view line)
{
std::vector<AsmParser::asm_label> labelsInLine;
const auto filteredLine = AssemblyTextParserUtils::getLineWithoutCommentAndStripFirstWord(line);
if (filteredLine.find('\"') != std::string_view::npos)
{
return labelsInLine;
}
int diffLen = line.length() - filteredLine.length() + 1;
int startidx = 0;
for (auto match : ctre::range<R"re(([$%]?)([.@A-Z_a-z][.\dA-Z_a-z]*))re">(filteredLine))
{
AsmParser::asm_label label{};
label.name = std::string(match.get<2>().to_view());
const auto len = label.name.length();
const auto loc = filteredLine.find(label.name, startidx);
startidx += (loc - startidx) + len;
label.range.start_col = loc + diffLen;
label.range.end_col = loc + diffLen + ustrlen(label.name);
labelsInLine.push_back(label);
auto prefix = match.get<1>().to_view();
if (!prefix.empty())
{
AsmParser::asm_label labelWithPrefix = label;
labelWithPrefix.name = prefix;
labelWithPrefix.name += label.name;
labelWithPrefix.range.start_col--;
labelsInLine.push_back(labelWithPrefix);
}
}
return labelsInLine;
}
bool AsmParser::AssemblyTextParserUtils::hasOpcode(const std::string_view line, bool inNvccCode)
{
// Remove any leading label definition...
const auto match = Regexes::labelDef(line);
if (match)
{
// todo
// line = line.substr(match[0].length);
}
// Strip any comments
const auto lineWithoutComment = getLineWithoutComment(line);
// .inst generates an opcode, so also counts
if (Regexes::instOpcodeRe(lineWithoutComment))
return true;
// Detect assignment, that's not an opcode...
if (Regexes::assignmentDef(lineWithoutComment))
return false;
if (inNvccCode)
return !!Regexes::hasNvccOpcodeRe(lineWithoutComment);
return !!Regexes::hasOpcodeRe(lineWithoutComment);
}
bool AsmParser::AssemblyTextParserUtils::isExampleOrStdin(const std::string_view filename)
{
if (Regexes::stdInLooking(filename))
return true;
return false;
}
std::optional<AsmParser::asm_stabn> AsmParser::AssemblyTextParserUtils::getSourceInfoFromStabs(const std::string_view line)
{
const auto match = Regexes::sourceStab(line);
if (!match)
return std::nullopt;
const auto type = svtoi(match.get<1>().to_view());
if (type == 68)
{
const auto line = svtoi(match.get<2>().to_view());
return asm_stabn{ type, line };
}
else
{
return asm_stabn{ type, 0 };
}
}
std::optional<AsmParser::asm_source_v> AsmParser::AssemblyTextParserUtils::get6502DbgInfo(const std::string_view line)
{
const auto match = Regexes::source6502Dbg(line);
if (match)
{
const auto file = match.get<1>().to_view();
const auto line = svtoi(match.get<2>().to_view());
// todo check if stdin?
return asm_source_v{ .file = file, .line = line, .is_end = false };
}
else
{
const auto matchend = Regexes::source6502DbgEnd(line);
if (matchend)
{
return asm_source_v{ .file = "", .line = 0, .is_end = true };
}
}
return std::nullopt;
}
std::optional<AsmParser::asm_source_l> AsmParser::AssemblyTextParserUtils::getD2LineInfo(const std::string_view line)
{
const auto match = Regexes::sourceD2Tag(line);
if (match)
{
const auto line = svtoi(match.get<1>().to_view());
return asm_source_l{ .line = line };
}
return std::nullopt;
}
std::optional<AsmParser::asm_source_f> AsmParser::AssemblyTextParserUtils::getD2FileInfo(const std::string_view line)
{
const auto match = Regexes::sourceD2File(line);
if (match)
{
const auto file = match.get<1>().to_view();
return asm_source_f{ .file = file };
}
return std::nullopt;
}
bool AsmParser::AssemblyTextParserUtils::startCommentBlock(const std::string_view line)
{
if (Regexes::blockCommentStart(line))
return true;
return false;
}
bool AsmParser::AssemblyTextParserUtils::endCommentBlock(const std::string_view line)
{
if (Regexes::blockCommentStop(line))
return true;
return false;
}
bool AsmParser::AssemblyTextParserUtils::startAppBlock(const std::string_view line)
{
if (Regexes::startAppBlock(line))
return true;
return false;
}
bool AsmParser::AssemblyTextParserUtils::endAppBlock(const std::string_view line)
{
if (Regexes::endAppBlock(line))
return true;
return false;
}
bool AsmParser::AssemblyTextParserUtils::startAsmNesting(const std::string_view line)
{
if (Regexes::startAsmNesting(line))
return true;
return false;
}
bool AsmParser::AssemblyTextParserUtils::endAsmNesting(const std::string_view line)
{
if (Regexes::endAsmNesting(line))
return true;
return false;
}
bool AsmParser::AssemblyTextParserUtils::startBlock(const std::string_view line)
{
if (Regexes::startBlock(line))
return true;
return false;
}
bool AsmParser::AssemblyTextParserUtils::endBlock(const std::string_view line)
{
if (Regexes::endBlock(line))
return true;
return false;
}
std::optional<std::string_view> AsmParser::AssemblyTextParserUtils::getLabel(const std::string_view line)
{
auto match = Regexes::labelDef(line);
if (match)
{
return match.get<1>().to_view();
}
return std::nullopt;
}
std::optional<std::string_view> AsmParser::AssemblyTextParserUtils::getLabelAssignment(const std::string_view line)
{
auto matchAssign = Regexes::labelAssignmentDef(line);
if (matchAssign)
{
return matchAssign.get<1>().to_view();
}
return std::nullopt;
}
std::optional<std::string_view> AsmParser::AssemblyTextParserUtils::getAssignmentDef(const std::string_view line)
{
auto match = Regexes::assignmentDef(line);
if (match)
return match.get<1>().to_view();
return std::nullopt;
}
std::optional<std::string_view> AsmParser::AssemblyTextParserUtils::getCudaLabel(const std::string_view line)
{
auto match = Regexes::cudaBeginDef(line);
if (match)
return match.get<1>().to_view();
return std::nullopt;
}
std::optional<std::string_view> AsmParser::AssemblyTextParserUtils::getFunctionTypeDefinedLabel(const std::string_view line)
{
auto match = Regexes::definesFunctionOrObject(line);
if (match)
return match.get<1>().to_view();
return std::nullopt;
}
std::optional<std::string_view> AsmParser::AssemblyTextParserUtils::getWeakDefinedLabel(const std::string_view line)
{
auto match = Regexes::definesWeak(line);
if (match)
return match.get<1>().to_view();
return std::nullopt;
}
std::optional<std::string_view> AsmParser::AssemblyTextParserUtils::getGlobalDefinedLabel(const std::string_view line)
{
auto match = Regexes::definesGlobal(line);
if (match)
return match.get<1>().to_view();
return std::nullopt;
}
std::optional<std::string_view> AsmParser::AssemblyTextParserUtils::getSectionNameDef(const std::string_view line)
{
auto match = Regexes::sectionDef(line);
if (match)
{
if (match.get<1>().to_view() == "section")
{
return match.get<2>().to_view();
}
else
{
return match.get<1>().to_view();
}
}
return std::nullopt;
}
bool AsmParser::AssemblyTextParserUtils::isJustComments(const std::string_view line)
{
if (Regexes::commentOnly(line))
return true;
return false;
}
bool AsmParser::AssemblyTextParserUtils::isJustNvccComments(const std::string_view line)
{
if (Regexes::commentOnlyNvcc(line))
return true;
return false;
}
bool AsmParser::AssemblyTextParserUtils::isCudaEndDef(const std::string_view line)
{
if (Regexes::cudaEndDef(line))
return true;
return false;
}
bool AsmParser::AssemblyTextParserUtils::isDataDefn(const std::string_view line)
{
if (Regexes::dataDefn(line))
return true;
return false;
}
bool AsmParser::AssemblyTextParserUtils::isDirective(const std::string_view line)
{
if (Regexes::directive(line))
return true;
return false;
}
bool AsmParser::AssemblyTextParserUtils::isInstOpcode(const std::string_view line)
{
if (Regexes::instOpcodeRe(line))
return true;
return false;
}
std::string AsmParser::AssemblyTextParserUtils::squashHorizontalWhitespace(const std::string_view line, bool atStart)
{
std::string squashed;
squashed.reserve(line.length());
enum class HorSpaceState
{
Start,
Second,
Stop,
JustOne
} state;
if (atStart)
{
state = HorSpaceState::Start;
}
else
{
state = HorSpaceState::JustOne;
}
bool justspaces = true;
for (auto c : line)
{
if (state == HorSpaceState::Stop)
{
if (is_whitespace(c))
{
// ignore
}
else
{
state = HorSpaceState::JustOne;
squashed += c;
justspaces = false;
}
}
else if (state == HorSpaceState::JustOne)
{
if (is_whitespace(c))
{
state = HorSpaceState::Stop;
squashed += ' ';
}
else
{
squashed += c;
justspaces = false;
}
}
else if (state == HorSpaceState::Start)
{
if (is_whitespace(c))
{
state = HorSpaceState::Second;
squashed += ' ';
}
else
{
state = HorSpaceState::Stop;
squashed += c;
justspaces = false;
}
}
else if (state == HorSpaceState::Second)
{
if (is_whitespace(c))
{
squashed += ' ';
}
else
{
squashed += c;
justspaces = false;
}
state = HorSpaceState::Stop;
}
}
if (atStart && justspaces)
{
squashed.clear();
}
return squashed;
}
std::string AsmParser::AssemblyTextParserUtils::squashHorizontalWhitespaceWithQuotes(const std::string_view line, bool atStart)
{
const auto quotes = Regexes::findQuotes(line);
if (quotes)
{
return fmt::format("{}{}{}", squashHorizontalWhitespaceWithQuotes(quotes.get<1>().to_view(), atStart),
quotes.get<2>().to_view(), squashHorizontalWhitespaceWithQuotes(quotes.get<3>().to_view(), false));
}
return squashHorizontalWhitespace(line);
}
| 24.732006 | 127 | 0.582663 |
compiler-explorer
|
df4cb0ca67799da84ae3cd56b87cccfd8f6f8d64
| 8,837 |
hpp
|
C++
|
include/murk/crypto/aes.hpp
|
Cyclic3/murk
|
fd2f71a4b258be71ef828f1223ddb76cc4ec8254
|
[
"MIT"
] | 2 |
2019-08-06T21:02:12.000Z
|
2021-12-22T16:12:38.000Z
|
include/murk/crypto/aes.hpp
|
Cyclic3/murk
|
fd2f71a4b258be71ef828f1223ddb76cc4ec8254
|
[
"MIT"
] | null | null | null |
include/murk/crypto/aes.hpp
|
Cyclic3/murk
|
fd2f71a4b258be71ef828f1223ddb76cc4ec8254
|
[
"MIT"
] | null | null | null |
#pragma once
#include "murk/data.hpp"
#include "murk/flows/bytes.hpp"
namespace murk::crypto::aes {
constexpr uint8_t sbox[256] = {0x63 ,0x7c ,0x77 ,0x7b ,0xf2 ,0x6b ,0x6f ,0xc5 ,0x30 ,0x01 ,0x67 ,0x2b ,0xfe ,0xd7 ,0xab ,0x76
,0xca ,0x82 ,0xc9 ,0x7d ,0xfa ,0x59 ,0x47 ,0xf0 ,0xad ,0xd4 ,0xa2 ,0xaf ,0x9c ,0xa4 ,0x72 ,0xc0
,0xb7 ,0xfd ,0x93 ,0x26 ,0x36 ,0x3f ,0xf7 ,0xcc ,0x34 ,0xa5 ,0xe5 ,0xf1 ,0x71 ,0xd8 ,0x31 ,0x15
,0x04 ,0xc7 ,0x23 ,0xc3 ,0x18 ,0x96 ,0x05 ,0x9a ,0x07 ,0x12 ,0x80 ,0xe2 ,0xeb ,0x27 ,0xb2 ,0x75
,0x09 ,0x83 ,0x2c ,0x1a ,0x1b ,0x6e ,0x5a ,0xa0 ,0x52 ,0x3b ,0xd6 ,0xb3 ,0x29 ,0xe3 ,0x2f ,0x84
,0x53 ,0xd1 ,0x00 ,0xed ,0x20 ,0xfc ,0xb1 ,0x5b ,0x6a ,0xcb ,0xbe ,0x39 ,0x4a ,0x4c ,0x58 ,0xcf
,0xd0 ,0xef ,0xaa ,0xfb ,0x43 ,0x4d ,0x33 ,0x85 ,0x45 ,0xf9 ,0x02 ,0x7f ,0x50 ,0x3c ,0x9f ,0xa8
,0x51 ,0xa3 ,0x40 ,0x8f ,0x92 ,0x9d ,0x38 ,0xf5 ,0xbc ,0xb6 ,0xda ,0x21 ,0x10 ,0xff ,0xf3 ,0xd2
,0xcd ,0x0c ,0x13 ,0xec ,0x5f ,0x97 ,0x44 ,0x17 ,0xc4 ,0xa7 ,0x7e ,0x3d ,0x64 ,0x5d ,0x19 ,0x73
,0x60 ,0x81 ,0x4f ,0xdc ,0x22 ,0x2a ,0x90 ,0x88 ,0x46 ,0xee ,0xb8 ,0x14 ,0xde ,0x5e ,0x0b ,0xdb
,0xe0 ,0x32 ,0x3a ,0x0a ,0x49 ,0x06 ,0x24 ,0x5c ,0xc2 ,0xd3 ,0xac ,0x62 ,0x91 ,0x95 ,0xe4 ,0x79
,0xe7 ,0xc8 ,0x37 ,0x6d ,0x8d ,0xd5 ,0x4e ,0xa9 ,0x6c ,0x56 ,0xf4 ,0xea ,0x65 ,0x7a ,0xae ,0x08
,0xba ,0x78 ,0x25 ,0x2e ,0x1c ,0xa6 ,0xb4 ,0xc6 ,0xe8 ,0xdd ,0x74 ,0x1f ,0x4b ,0xbd ,0x8b ,0x8a
,0x70 ,0x3e ,0xb5 ,0x66 ,0x48 ,0x03 ,0xf6 ,0x0e ,0x61 ,0x35 ,0x57 ,0xb9 ,0x86 ,0xc1 ,0x1d ,0x9e
,0xe1 ,0xf8 ,0x98 ,0x11 ,0x69 ,0xd9 ,0x8e ,0x94 ,0x9b ,0x1e ,0x87 ,0xe9 ,0xce ,0x55 ,0x28 ,0xdf
,0x8c ,0xa1 ,0x89 ,0x0d ,0xbf ,0xe6 ,0x42 ,0x68 ,0x41 ,0x99 ,0x2d ,0x0f ,0xb0 ,0x54 ,0xbb ,0x16};
constexpr uint8_t inv_sbox[256] = {0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d};
constexpr size_t state_size = 16;
using table_t = std::array<uint8_t, state_size>;
using table_ref_t = nonstd::span<uint8_t, state_size>;
using round_constant_t = std::array<uint8_t, 4>;
inline void sub_bytes(table_ref_t tab) {
for (auto& i : tab)
i = sbox[i];
}
inline void unsub_bytes(table_ref_t tab) {
for (auto& i : tab)
i = inv_sbox[i];
}
inline void shift_rows(table_ref_t tab) {
table_t ref;
std::copy(tab.begin(), tab.end(), ref.begin());
tab[ 1] = ref[ 5]; tab[ 5] = ref[ 9]; tab[ 9] = ref[13]; tab[13] = ref[ 1];
tab[ 2] = ref[10]; tab[ 6] = ref[14]; tab[10] = ref[ 2]; tab[14] = ref[ 6];
tab[ 3] = ref[15]; tab[ 7] = ref[ 3]; tab[11] = ref[ 7]; tab[15] = ref[11];
}
inline void unshift_rows(table_ref_t tab) {
table_t ref;
std::copy(tab.begin(), tab.end(), ref.begin());
tab[ 5] = ref[ 1]; tab[ 9] = ref[ 5]; tab[13] = ref[ 9]; tab[ 1] = ref[13];
tab[10] = ref[ 2]; tab[14] = ref[ 6]; tab[ 2] = ref[10]; tab[ 6] = ref[14];
tab[15] = ref[ 3]; tab[ 3] = ref[ 7]; tab[ 7] = ref[11]; tab[11] = ref[15];
}
inline void mix_columns(table_ref_t tab) {
// Thx wikipedia
auto* r = tab.data();
unsigned char a[4];
unsigned char b[4];
unsigned char c;
unsigned char h;
/* The array 'a' is simply a copy of the input array 'r'
* The array 'b' is each element of the array 'a' multiplied by 2
* in Rijndael's Galois field
* a[n] ^ b[n] is element n multiplied by 3 in Rijndael's Galois field */
for (c = 0; c < 4; c++) {
a[c] = r[c];
/* h is 0xff if the high bit of r[c] is set, 0 otherwise */
h = (unsigned char)((signed char)r[c] >> 7); /* arithmetic right shift, thus shifting in either zeros or ones */
b[c] = r[c] << 1; /* implicitly removes high bit because b[c] is an 8-bit char, so we xor by 0x1b and not 0x11b in the next line */
b[c] ^= 0x1B & h; /* Rijndael's Galois field */
}
r[0] = b[0] ^ a[3] ^ a[2] ^ b[1] ^ a[1]; /* 2 * a0 + a3 + a2 + 3 * a1 */
r[1] = b[1] ^ a[0] ^ a[3] ^ b[2] ^ a[2]; /* 2 * a1 + a0 + a3 + 3 * a2 */
r[2] = b[2] ^ a[1] ^ a[0] ^ b[3] ^ a[3]; /* 2 * a2 + a1 + a0 + 3 * a3 */
r[3] = b[3] ^ a[2] ^ a[1] ^ b[0] ^ a[0]; /* 2 * a3 + a2 + a1 + 3 * a0 */
}
inline void add_round_key(table_ref_t tab, table_ref_t key) {
murk::xor_bytes_inplace(tab, key);
}
/// If you end up using this namespace, something has gone _very_ wrong
namespace rcon_detail {
/// @param i the 0-indexed round number, but NOT 0!!!
constexpr inline void update_round_constant(round_constant_t& prev, uint8_t i) {
[[unlikely]]
if (i == 1)
prev = {1, 0, 0, 0};
else {
uint16_t f = prev.front();
f = (f << 1) ^ (0x11b & -(f >> 7));
prev[0] = f;
}
}
constexpr round_constant_t round_constants[11] = {
{0x01, 0x00, 0x00, 0x00},
{0x02, 0x00, 0x00, 0x00},
{0x04, 0x00, 0x00, 0x00},
{0x08, 0x00, 0x00, 0x00},
{0x10, 0x00, 0x00, 0x00},
{0x20, 0x00, 0x00, 0x00},
{0x40, 0x00, 0x00, 0x00},
{0x80, 0x00, 0x00, 0x00},
{0x1B, 0x00, 0x00, 0x00},
{0x36, 0x00, 0x00, 0x00}
};
inline void rot_word(round_constant_t& rcon) {
uint8_t b;
b = rcon[0];
rcon[0] = rcon[1];
rcon[1] = rcon[2];
rcon[2] = rcon[3];
rcon[3] = b;
}
inline void sub_word(round_constant_t& rcon) {
rcon[0] = sbox[rcon[0]];
rcon[1] = sbox[rcon[1]];
rcon[2] = sbox[rcon[2]];
rcon[3] = sbox[rcon[3]];
}
inline void schedule_core(round_constant_t& rcon, uint8_t i) {
rot_word(rcon);
sub_word(rcon);
rcon[0] ^= round_constants[i - 1][0];
}
}
template<int KeyBits>
constexpr int get_round_count();
template<>
constexpr int get_round_count<128>() { return 11; }
template<>
constexpr int get_round_count<176>() { return 13; }
template<>
constexpr int get_round_count<256>() { return 15; }
template<int KeyBits>
using round_keys_t = std::array<table_t, get_round_count<KeyBits>()>;
template<int KeyBits>
inline void expand_key(round_keys_t<KeyBits>& out, nonstd::span<const uint8_t, KeyBits / 8> key);
template<>
inline void expand_key<128>(round_keys_t<128>& out, nonstd::span<const uint8_t, 128 / 8> key) {
std::copy(key.begin(), key.end(), out.front().begin());
round_constant_t t;
for (size_t round = 1; round < get_round_count<128>(); ++round) {
auto& out_round = out[round];
for (size_t word_start = 0; word_start < 16;) {
if (word_start == 0) {
auto& target = out[round - 1];
std::copy(target.begin() + 12, target.end(), t.begin());
rcon_detail::schedule_core(t, round);
}
else {
std::copy(out_round.begin() + word_start - 4, out_round.begin() + word_start, t.begin());
}
auto in_round = out[round - 1];
for (size_t a = 0; a < 4; ++a) {
out_round[word_start] = in_round[word_start] ^ t[a];
++word_start;
}
}
}
}
}
| 49.094444 | 1,573 | 0.565237 |
Cyclic3
|
df54fe9ea960519cc358e317ea5ebfc56d595593
| 28 |
cpp
|
C++
|
src/StoneCold.3D.Game/InputManager.cpp
|
krck/StoneCold_3D
|
5661a96e5167922b0ba555714a6d337acdea48c5
|
[
"BSD-3-Clause"
] | null | null | null |
src/StoneCold.3D.Game/InputManager.cpp
|
krck/StoneCold_3D
|
5661a96e5167922b0ba555714a6d337acdea48c5
|
[
"BSD-3-Clause"
] | null | null | null |
src/StoneCold.3D.Game/InputManager.cpp
|
krck/StoneCold_3D
|
5661a96e5167922b0ba555714a6d337acdea48c5
|
[
"BSD-3-Clause"
] | null | null | null |
#include "InputManager.hpp"
| 14 | 27 | 0.785714 |
krck
|
df5b035b3addb1a074dad1985cb5fb0be699c696
| 331 |
cpp
|
C++
|
sandbox/sandbox_shared_lib/derived.cpp
|
VaderY/cereal
|
b03f237713a7e4aab18c7d9150fb3c9a5e92ea3a
|
[
"BSD-3-Clause"
] | null | null | null |
sandbox/sandbox_shared_lib/derived.cpp
|
VaderY/cereal
|
b03f237713a7e4aab18c7d9150fb3c9a5e92ea3a
|
[
"BSD-3-Clause"
] | null | null | null |
sandbox/sandbox_shared_lib/derived.cpp
|
VaderY/cereal
|
b03f237713a7e4aab18c7d9150fb3c9a5e92ea3a
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef CEREAL_DLL_USE
#define CEREAL_DLL_MAKE
#endif
#include "derived.hpp"
template void Derived::serialize<cereal::XMLOutputArchive>
( cereal::XMLOutputArchive & ar, const std::uint32_t version );
template void Derived::serialize<cereal::XMLInputArchive>
( cereal::XMLInputArchive & ar, const std::uint32_t version );
| 30.090909 | 67 | 0.770393 |
VaderY
|
df5ecbcc497ea0260cb3437fb2d483967e14974f
| 329 |
cpp
|
C++
|
Arcanist/src/ArcanistApp.cpp
|
zaub3rfuchs/Arc
|
19b159bb6ea014b615e16ff13c946b6f93c0f281
|
[
"Apache-2.0"
] | null | null | null |
Arcanist/src/ArcanistApp.cpp
|
zaub3rfuchs/Arc
|
19b159bb6ea014b615e16ff13c946b6f93c0f281
|
[
"Apache-2.0"
] | null | null | null |
Arcanist/src/ArcanistApp.cpp
|
zaub3rfuchs/Arc
|
19b159bb6ea014b615e16ff13c946b6f93c0f281
|
[
"Apache-2.0"
] | null | null | null |
#include <Arc.h>
#include <Arc/Core/EntryPoint.h>
#include "EditorLayer.h"
namespace ArcEngine {
class Arcanist : public Application
{
public:
Arcanist()
: Application("Arcanist")
{
PushLayer(new EditorLayer());
}
~Arcanist()
{
}
};
Application* CreateApplication()
{
return new Arcanist();
}
}
| 11.344828 | 36 | 0.644377 |
zaub3rfuchs
|
df62d5005e157b28b4e891feda043cb83077a258
| 8,473 |
cc
|
C++
|
lang/cimport/packing.cc
|
meyerj/typelib
|
e2a8d67d35732ffdd1d586aa8370576033ecc5a6
|
[
"CECILL-B"
] | null | null | null |
lang/cimport/packing.cc
|
meyerj/typelib
|
e2a8d67d35732ffdd1d586aa8370576033ecc5a6
|
[
"CECILL-B"
] | null | null | null |
lang/cimport/packing.cc
|
meyerj/typelib
|
e2a8d67d35732ffdd1d586aa8370576033ecc5a6
|
[
"CECILL-B"
] | null | null | null |
#include "packing.hh"
#include <typelib/typemodel.hh>
#include <typelib/typevisitor.hh>
#include <boost/lexical_cast.hpp>
#include <typelib/typedisplay.hh>
////////////////////////////////////////////////////////////////////////////////
//
// Check some assumptions we make in the packing code
//
#include <boost/mpl/size.hpp>
#include "packing/tools.tcc"
#include "packing/check_arrays.tcc"
#include "packing/check_struct_in_struct.tcc"
#include "packing/check_size_criteria.tcc"
#include <vector>
#include <set>
#include <map>
namespace
{
struct PackingInfo
{
size_t size;
size_t packing;
PackingInfo()
: size(0), packing(0) {}
};
int const packing_info_size = ::boost::mpl::size<podlist>::type::value;
PackingInfo packing_info[packing_info_size];
template<typename T>
struct DiscoverCollectionPacking
{
int8_t v;
T collection;
static size_t get() {
DiscoverCollectionPacking<T> obj;
return reinterpret_cast<uint8_t*>(&obj.collection) - reinterpret_cast<uint8_t*>(&obj);
}
};
struct CollectionPackingInfo
{
char const* name;
size_t packing;
};
/** It seems that the following rule apply with struct size rounding: the
* size is rounded so that the biggest element in the structure is properly
* aligned.
*/
// To get the size of an empty struct
struct EmptyStruct { };
// Rounded size is 24
struct StructSizeDiscovery1 { int64_t a; int64_t z; int8_t end; };
struct StructSizeDiscovery2 { int32_t a; int32_t b; int64_t z; int8_t end; };
// Rounded size is 20
struct StructSizeDiscovery3 { int32_t a; int32_t b; int32_t c; int32_t d; int8_t end; };
struct StructSizeDiscovery4 { int32_t a[4]; int8_t end; };
struct StructSizeDiscovery5 { int16_t a[2]; int32_t b[3]; int8_t end; };
// Rounded size is 18
struct StructSizeDiscovery6 { int16_t a[2]; int16_t b[6]; int8_t end; };
struct StructSizeDiscovery7 { int8_t a[4]; int16_t b[6]; int8_t end; };
// Rounded size is 17
struct StructSizeDiscovery8 { int8_t a[4]; int8_t b[12]; int8_t end; };
BOOST_STATIC_ASSERT(
(sizeof(long) == 8 && sizeof(StructSizeDiscovery1) == 24) ||
(sizeof(long) == 4 && sizeof(StructSizeDiscovery1) == 20));
BOOST_STATIC_ASSERT(
(sizeof(long) == 8 && sizeof(StructSizeDiscovery2) == 24) ||
(sizeof(long) == 4 && sizeof(StructSizeDiscovery2) == 20));
BOOST_STATIC_ASSERT(sizeof(StructSizeDiscovery3) == 20);
BOOST_STATIC_ASSERT(sizeof(StructSizeDiscovery4) == 20);
BOOST_STATIC_ASSERT(sizeof(StructSizeDiscovery5) == 20);
BOOST_STATIC_ASSERT(sizeof(StructSizeDiscovery6) == 18);
BOOST_STATIC_ASSERT(sizeof(StructSizeDiscovery7) == 18);
BOOST_STATIC_ASSERT(sizeof(StructSizeDiscovery8) == 17);
}
#include "packing/build_packing_info.tcc"
// build_packing_info builds a
// PackingInfo[] packing_info
//
// where the first element is the size to
// consider and the second its packing
namespace {
//////////////////////////////////////////////////////////////////////////
//
// Helpers for client code
//
using namespace Typelib;
struct GetPackingSize : public TypeVisitor
{
int size;
GetPackingSize(Type const& base_type)
: size(-1)
{ apply(base_type); }
bool visit_(Numeric const& value)
{ size = value.getSize();
return false; }
bool visit_(Enum const& value)
{ size = value.getSize();
return false; }
bool visit_(Pointer const& value)
{ size = value.getSize();
return false; }
bool visit_(Compound const& value)
{
typedef Compound::FieldList Fields;
Fields const& fields(value.getFields());
if (fields.empty())
throw Packing::FoundNullStructure();
// TODO: add a static check for this
// we assume that unions are packed as their biggest field
int max_size = 0;
for (Fields::const_iterator it = fields.begin(); it != fields.end(); ++it)
{
GetPackingSize recursive(it->getType());
if (recursive.size == -1)
throw std::runtime_error("cannot compute the packing size for " + value.getName());
max_size = std::max(max_size, recursive.size);
}
size = max_size;
return true;
}
bool visit_(Container const& value)
{
CollectionPackingInfo collection_packing_info[] = {
{ "/std/vector", DiscoverCollectionPacking< std::vector<uint16_t> >::get() },
{ "/std/set", DiscoverCollectionPacking< std::set<uint8_t> >::get() },
{ "/std/map", DiscoverCollectionPacking< std::map<uint8_t, uint8_t> >::get() },
{ "/std/string", DiscoverCollectionPacking< std::string >::get() },
{ 0, 0 }
};
for (CollectionPackingInfo* info = collection_packing_info; info->name; ++info)
{
if (info->name == std::string(value.getName(), 0, std::string(info->name).size()))
{
size = info->packing;
return true;
}
}
throw Packing::PackingUnknown("cannot compute the packing of " + boost::lexical_cast<std::string>(value.getName()));
}
};
};
#include <iostream>
using std::cout;
using std::endl;
int Typelib::Packing::getOffsetOf(const Field& last_field, const Type& append_field, size_t packing)
{
if (packing == 0)
return 0;
int base_offset = last_field.getOffset() + last_field.getType().getSize();
return (base_offset + (packing - 1)) / packing * packing;
}
int Typelib::Packing::getOffsetOf(Compound const& compound, const Type& append_field, size_t packing)
{
Compound::FieldList const& fields(compound.getFields());
if (fields.empty())
return 0;
return getOffsetOf(fields.back(), append_field, packing);
}
int Typelib::Packing::getOffsetOf(const Field& last_field, const Type& append_field)
{
GetPackingSize visitor(append_field);
if (visitor.size == -1)
throw PackingUnknown("cannot compute the packing of " + boost::lexical_cast<std::string>(append_field.getName()));
size_t const size(visitor.size);
for (int i = 0; i < packing_info_size; ++i)
{
if (packing_info[i].size == size)
return getOffsetOf(last_field, append_field, packing_info[i].packing);
}
throw PackingUnknown("cannot compute the packing of " + boost::lexical_cast<std::string>(append_field.getName()));
}
int Typelib::Packing::getOffsetOf(const Compound& current, const Type& append_field)
{
Compound::FieldList const& fields(current.getFields());
if (fields.empty())
return 0;
return getOffsetOf(fields.back(), append_field);
}
struct AlignmentBaseTypeVisitor : public TypeVisitor
{
Type const* result;
bool handleType(Type const& type)
{
if (!result || result->getSize() < type.getSize())
result = &type;
return true;
}
virtual bool visit_ (NullType const& type) { throw UnsupportedType(type, "cannot represent alignment of null types"); }
virtual bool visit_ (OpaqueType const& type) { throw UnsupportedType(type, "cannot represent alignment of opaque types"); };
virtual bool visit_ (Numeric const& type) { return handleType(type); }
virtual bool visit_ (Enum const& type) { return handleType(type); }
virtual bool visit_ (Pointer const& type) { return handleType(type); }
virtual bool visit_ (Container const& type) { return handleType(type); }
// arrays and compound are handled recursively
static Type const* find(Type const& type)
{
AlignmentBaseTypeVisitor visitor;
visitor.result = NULL;
visitor.apply(type);
return visitor.result;
}
};
int Typelib::Packing::getSizeOfCompound(Compound const& compound)
{
// Find the biggest type in the compound
Compound::FieldList const& fields(compound.getFields());
if (fields.empty())
return sizeof(EmptyStruct);
Type const* biggest_type = AlignmentBaseTypeVisitor::find(compound);
return getOffsetOf(compound, *biggest_type);
}
| 32.968872 | 128 | 0.619497 |
meyerj
|
df647043b80cd16f957121b27129855a843460bf
| 927 |
cpp
|
C++
|
LeviathanTest/TestFiles/GuiTests.cpp
|
Higami69/Leviathan
|
90f68f9f6e5506d6133bcefcf35c8e84f158483b
|
[
"BSL-1.0"
] | null | null | null |
LeviathanTest/TestFiles/GuiTests.cpp
|
Higami69/Leviathan
|
90f68f9f6e5506d6133bcefcf35c8e84f158483b
|
[
"BSL-1.0"
] | null | null | null |
LeviathanTest/TestFiles/GuiTests.cpp
|
Higami69/Leviathan
|
90f68f9f6e5506d6133bcefcf35c8e84f158483b
|
[
"BSL-1.0"
] | null | null | null |
//! \file Tests for various supporting GUI methods. Doesn't actually
//! try any rendering or anything like that
#include "GUI/VideoPlayer.h"
#include "../PartialEngine.h"
#include "catch.hpp"
using namespace Leviathan;
using namespace Leviathan::Test;
using namespace Leviathan::GUI;
TEST_CASE("Leviathan VideoPlayer loads correctly", "[gui][video][xrequired]"){
// TODO: add leviathan intro video that can be attempted to be opened
// Requires audio
SoundDevice sound;
PartialEngineWithOgre engine(nullptr, &sound);
engine.Log.IgnoreWarnings = true;
REQUIRE(sound.Init(false, true));
VideoPlayer player;
REQUIRE(player.Play("Data/Videos/SampleVideo.mkv"));
CHECK(player.GetDuration() == 10.336f);
CHECK(player.GetVideoWidth() == 1920);
CHECK(player.GetVideoHeight() == 1080);
CHECK(player.IsStreamValid());
player.Stop();
sound.Release();
}
| 22.609756 | 78 | 0.693635 |
Higami69
|
df659582d24a157fdf0a3351a454f1291e7053cf
| 8,833 |
cpp
|
C++
|
src/vm/readytoruninfo.cpp
|
CyberSys/coreclr-mono
|
83b2cb83b32faa45b4f790237b5c5e259692294a
|
[
"MIT"
] | 10 |
2015-11-03T16:35:25.000Z
|
2021-07-31T16:36:29.000Z
|
src/vm/readytoruninfo.cpp
|
CyberSys/coreclr-mono
|
83b2cb83b32faa45b4f790237b5c5e259692294a
|
[
"MIT"
] | 1 |
2019-03-05T18:50:09.000Z
|
2019-03-05T18:50:09.000Z
|
src/vm/readytoruninfo.cpp
|
CyberSys/coreclr-mono
|
83b2cb83b32faa45b4f790237b5c5e259692294a
|
[
"MIT"
] | 4 |
2015-10-28T12:26:26.000Z
|
2021-09-04T11:36:04.000Z
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
// ===========================================================================
// File: ReadyToRunInfo.cpp
//
//
// Runtime support for Ready to Run
// ===========================================================================
#include "common.h"
#include "dbginterface.h"
#include "compile.h"
using namespace NativeFormat;
IMAGE_DATA_DIRECTORY * ReadyToRunInfo::FindSection(DWORD type)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
SO_TOLERANT;
SUPPORTS_DAC;
}
CONTRACTL_END;
PTR_READYTORUN_SECTION pSections = dac_cast<PTR_READYTORUN_SECTION>(dac_cast<TADDR>(m_pHeader) + sizeof(READYTORUN_HEADER));
for (DWORD i = 0; i < m_pHeader->NumberOfSections; i++)
{
// Verify that section types are sorted
_ASSERTE(i == 0 || (pSections[i-1].Type < pSections[i].Type));
READYTORUN_SECTION * pSection = pSections + i;
if (pSection->Type == type)
return &pSection->Section;
}
return NULL;
}
MethodDesc * ReadyToRunInfo::GetMethodDescForEntryPoint(PCODE entryPoint)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
SO_TOLERANT;
SUPPORTS_DAC;
}
CONTRACTL_END;
#ifdef _TARGET_AMD64_
// A normal method entry point is always 8 byte aligned, but a funclet can start at an odd address.
// Since PtrHashMap can't handle odd pointers, check for this case and return NULL.
if ((entryPoint & 0x1) != 0)
return NULL;
#endif
TADDR val = (TADDR)m_entryPointToMethodDescMap.LookupValue(PCODEToPINSTR(entryPoint), (LPVOID)PCODEToPINSTR(entryPoint));
if (val == (TADDR)INVALIDENTRY)
return NULL;
return dac_cast<PTR_MethodDesc>(val);
}
PTR_BYTE ReadyToRunInfo::GetDebugInfo(PTR_RUNTIME_FUNCTION pRuntimeFunction)
{
CONTRACTL
{
GC_NOTRIGGER;
THROWS;
MODE_ANY;
SUPPORTS_DAC;
}
CONTRACTL_END;
IMAGE_DATA_DIRECTORY * pDebugInfoDir = FindSection(READYTORUN_SECTION_DEBUG_INFO);
if (pDebugInfoDir == NULL)
return NULL;
SIZE_T methodIndex = pRuntimeFunction - m_pRuntimeFunctions;
_ASSERTE(methodIndex < m_nRuntimeFunctions);
NativeArray debugInfoIndex(&m_nativeReader, pDebugInfoDir->VirtualAddress);
uint offset;
if (!debugInfoIndex.TryGetAt((DWORD)methodIndex, &offset))
return NULL;
uint lookBack;
uint debugInfoOffset = m_nativeReader.DecodeUnsigned(offset, &lookBack);
if (lookBack != 0)
debugInfoOffset = offset - lookBack;
return dac_cast<PTR_BYTE>(m_pLayout->GetBase()) + debugInfoOffset;
}
#ifndef DACCESS_COMPILE
BOOL ReadyToRunInfo::IsReadyToRunEnabled()
{
STANDARD_VM_CONTRACT;
static ConfigDWORD configReadyToRun;
return configReadyToRun.val(CLRConfig::EXTERNAL_ReadyToRun);
}
PTR_ReadyToRunInfo ReadyToRunInfo::Initialize(Module * pModule, AllocMemTracker *pamTracker)
{
STANDARD_VM_CONTRACT;
PEFile * pFile = pModule->GetFile();
// Ignore ReadyToRun for introspection-only loads
if (pFile->IsIntrospectionOnly())
return NULL;
if (!pFile->HasLoadedIL())
return NULL;
PEImageLayout * pLayout = pFile->GetLoadedIL();
if (!pLayout->HasReadyToRunHeader())
return NULL;
if (!IsReadyToRunEnabled())
return NULL;
if (!pLayout->IsNativeMachineFormat())
{
#ifdef FEATURE_CORECLR
// For CoreCLR, be strict about disallowing machine mismatches.
COMPlusThrowHR(COR_E_BADIMAGEFORMAT);
#else
return NULL;
#endif
}
#ifdef FEATURE_NATIVE_IMAGE_GENERATION
// Ignore ReadyToRun during NGen
if (IsCompilationProcess() && !IsNgenPDBCompilationProcess())
return NULL;
#endif
#ifndef CROSSGEN_COMPILE
// The file must have been loaded using LoadLibrary
if (!pLayout->IsRelocated())
return NULL;
#endif
READYTORUN_HEADER * pHeader = pLayout->GetReadyToRunHeader();
// Ignore the content if the image major version is higher than the major version currently supported by the runtime
if (pHeader->MajorVersion > READYTORUN_MAJOR_VERSION)
return NULL;
LoaderHeap *pHeap = pModule->GetLoaderAllocator()->GetHighFrequencyHeap();
void * pMemory = pamTracker->Track(pHeap->AllocMem((S_SIZE_T)sizeof(ReadyToRunInfo)));
return new (pMemory) ReadyToRunInfo(pModule, pLayout, pHeader);
}
ReadyToRunInfo::ReadyToRunInfo(Module * pModule, PEImageLayout * pLayout, READYTORUN_HEADER * pHeader)
: m_pModule(pModule), m_pLayout(pLayout), m_pHeader(pHeader), m_Crst(CrstLeafLock)
{
STANDARD_VM_CONTRACT;
IMAGE_DATA_DIRECTORY * pRuntimeFunctionsDir = FindSection(READYTORUN_SECTION_RUNTIME_FUNCTIONS);
if (pRuntimeFunctionsDir != NULL)
{
m_pRuntimeFunctions = (RUNTIME_FUNCTION *)pLayout->GetDirectoryData(pRuntimeFunctionsDir);
m_nRuntimeFunctions = pRuntimeFunctionsDir->Size / sizeof(RUNTIME_FUNCTION);
}
else
{
m_nRuntimeFunctions = 0;
}
IMAGE_DATA_DIRECTORY * pImportSectionsDir = FindSection(READYTORUN_SECTION_IMPORT_SECTIONS);
if (pImportSectionsDir != NULL)
{
m_pImportSections = (CORCOMPILE_IMPORT_SECTION*)pLayout->GetDirectoryData(pImportSectionsDir);
m_nImportSections = pImportSectionsDir->Size / sizeof(CORCOMPILE_IMPORT_SECTION);
}
else
{
m_nImportSections = 0;
}
m_nativeReader = NativeReader((byte *)pLayout->GetBase(), pLayout->GetVirtualSize());
IMAGE_DATA_DIRECTORY * pEntryPointsDir = FindSection(READYTORUN_SECTION_METHODDEF_ENTRYPOINTS);
if (pEntryPointsDir != NULL)
{
m_methodDefEntryPoints = NativeArray(&m_nativeReader, pEntryPointsDir->VirtualAddress);
}
{
LockOwner lock = {&m_Crst, IsOwnerOfCrst};
m_entryPointToMethodDescMap.Init(TRUE, &lock);
}
}
PCODE ReadyToRunInfo::GetEntryPoint(MethodDesc * pMD, BOOL fFixups /*=TRUE*/)
{
STANDARD_VM_CONTRACT;
// READYTORUN: FUTURE: Support for generics
if (pMD->HasClassOrMethodInstantiation())
return NULL;
mdToken token = pMD->GetMemberDef();
int rid = RidFromToken(token);
if (rid == 0)
return NULL;
uint offset;
if (!m_methodDefEntryPoints.TryGetAt(rid - 1, &offset))
return NULL;
uint id;
offset = m_nativeReader.DecodeUnsigned(offset, &id);
if (id & 1)
{
if (id & 2)
{
uint val;
m_nativeReader.DecodeUnsigned(offset, &val);
offset -= val;
}
if (fFixups)
{
if (!m_pModule->FixupDelayList(dac_cast<TADDR>(m_pLayout->GetBase()) + offset))
return NULL;
}
id >>= 2;
}
else
{
id >>= 1;
}
_ASSERTE(id < m_nRuntimeFunctions);
PCODE pEntryPoint = dac_cast<TADDR>(m_pLayout->GetBase()) + m_pRuntimeFunctions[id].BeginAddress;
{
CrstHolder ch(&m_Crst);
if (m_entryPointToMethodDescMap.LookupValue(PCODEToPINSTR(pEntryPoint), (LPVOID)PCODEToPINSTR(pEntryPoint)) == (LPVOID)INVALIDENTRY)
m_entryPointToMethodDescMap.InsertValue(PCODEToPINSTR(pEntryPoint), pMD);
}
if (g_pDebugInterface != NULL)
{
g_pDebugInterface->JITComplete(pMD, pEntryPoint);
}
return pEntryPoint;
}
BOOL ReadyToRunInfo::MethodIterator::Next()
{
STANDARD_VM_CONTRACT;
while (++m_methodDefIndex < (int)m_pInfo->m_methodDefEntryPoints.GetCount())
{
uint offset;
if (m_pInfo->m_methodDefEntryPoints.TryGetAt(m_methodDefIndex, &offset))
return TRUE;
}
return FALSE;
}
MethodDesc * ReadyToRunInfo::MethodIterator::GetMethodDesc()
{
STANDARD_VM_CONTRACT;
return MemberLoader::GetMethodDescFromMethodDef(m_pInfo->m_pModule, mdtMethodDef | (m_methodDefIndex + 1), FALSE);
}
PCODE ReadyToRunInfo::MethodIterator::GetMethodStartAddress()
{
STANDARD_VM_CONTRACT;
PCODE ret = m_pInfo->GetEntryPoint(GetMethodDesc(), FALSE);
_ASSERTE(ret != NULL);
return ret;
}
DWORD ReadyToRunInfo::GetFieldBaseOffset(MethodTable * pMT)
{
STANDARD_VM_CONTRACT;
DWORD dwAlignment = DATA_ALIGNMENT;
DWORD dwOffsetBias = 0;
#ifdef FEATURE_64BIT_ALIGNMENT
dwOffsetBias = 4;
if (pMT->RequiresAlign8())
dwAlignment = 8;
#endif
MethodTable * pParentMT = pMT->GetParentMethodTable();
DWORD dwCumulativeInstanceFieldPos = (pParentMT != NULL) ? pParentMT->GetNumInstanceFieldBytes() : 0;
dwCumulativeInstanceFieldPos += dwOffsetBias;
dwCumulativeInstanceFieldPos = (DWORD)ALIGN_UP(dwCumulativeInstanceFieldPos, dwAlignment);
return (DWORD)sizeof(Object) + dwCumulativeInstanceFieldPos - dwOffsetBias;
}
#endif // DACCESS_COMPILE
| 27.77673 | 140 | 0.676893 |
CyberSys
|
df67439f69e0ad36bce2d6fcd74b8dc868f80f71
| 304 |
cpp
|
C++
|
src/debug20/backtrace.cpp
|
Tomcus/debug20
|
4124f83359b49c8b340f957bce1e0b83bffd443e
|
[
"MIT"
] | null | null | null |
src/debug20/backtrace.cpp
|
Tomcus/debug20
|
4124f83359b49c8b340f957bce1e0b83bffd443e
|
[
"MIT"
] | null | null | null |
src/debug20/backtrace.cpp
|
Tomcus/debug20
|
4124f83359b49c8b340f957bce1e0b83bffd443e
|
[
"MIT"
] | null | null | null |
#include "backtrace.hpp"
#include <fmt/os.h>
void d20::print_backtrace() noexcept {
backtrace_data data;
try {
data = get_backtrace();
for (auto trace:data) {
fmt::print("{}\n", trace);
}
} catch (const exception& e) {
puts(e.what());
}
}
| 20.266667 | 38 | 0.523026 |
Tomcus
|
df6f519bdaae3b19dd7843d83822c94c2e3394d9
| 3,872 |
cpp
|
C++
|
Munch/assem.cpp
|
Compiladori/Tiger-Compiler
|
d52f92459dac0fa00534162a808376875883446d
|
[
"MIT"
] | 1 |
2020-12-31T16:05:42.000Z
|
2020-12-31T16:05:42.000Z
|
Munch/assem.cpp
|
Compiladori/Tiger-Compiler
|
d52f92459dac0fa00534162a808376875883446d
|
[
"MIT"
] | 1 |
2021-01-27T15:41:18.000Z
|
2021-05-31T21:47:02.000Z
|
Munch/assem.cpp
|
Compiladori/Tiger-Compiler
|
d52f92459dac0fa00534162a808376875883446d
|
[
"MIT"
] | null | null | null |
#include "assem.h"
using namespace assem;
/**
* Instructions
* **/
void Oper::output(std::ostream& os, temp::TempMap temp_map) const {
std::string result;
for ( auto it = assm.cbegin(); it != assm.cend(); ++it ) {
if ( *it == '\'' ) {
switch ( *(++it) ) {
case 's': {
int n = std::atoi(&*(++it));
if ( n >= src.size() ) {
std::cout << "ERROR : tried to access element " << n << " of " << src.size() << "-sized src vector. Instruction = ";
this->print();
std::cout << std::endl;
} else if ( not temp_map.count(src[n]) ) {
std::cout << "ERROR : temp_map has no element src[n] = src[" << n << "] = " << src[n].num << std::endl;
}
std::string s = temp_map.at(src[n]).name;
result.append(s);
} break;
case 'd': {
int n = std::atoi(&*(++it));
if ( n >= dst.size() ) {
std::cout << "ERROR : tried to access element " << n << " of " << dst.size() << "-sized dst vector. Instruction = ";
this->print();
std::cout << std::endl;
} else if ( not temp_map.count(dst[n]) ) {
std::cout << "ERROR : temp_map has no element dst[n] = dst[" << n << "] = " << dst[n].num << std::endl;
}
std::string s = temp_map.at(dst[n]).name;
result.append(s);
} break;
case 'j': {
int n = std::atoi(&*(++it));
if ( n >= jumps.size() ) {
std::cout << "ERROR : tried to access element " << n << " of " << jumps.size() << "-sized jumps vector. Instruction = ";
this->print();
std::cout << std::endl;
}
std::string s = jumps[n].name;
result.append(s);
} break;
case '\'': {
result.append(1, *it);
} break;
}
} else {
result.append(1, *it);
}
}
os << " " << result << "\n";
}
void Label::output(std::ostream& os, temp::TempMap temp_map) const {
os << assm << "\n";
}
void Move::output(std::ostream& os, temp::TempMap temp_map) const {
std::string result;
if ( temp_map.at(src[0]).name == temp_map.at(dst[0]).name ) {
return;
}
for ( auto it = assm.cbegin(); it != assm.cend(); ++it ) {
if ( *it == '\'' ) {
switch ( *(++it) ) {
case 's': {
int n = std::atoi(&*(++it));
std::string s = temp_map.at(src[n]).name;
result.append(s);
} break;
case 'd': {
int n = std::atoi(&*(++it));
std::string s = temp_map.at(dst[n]).name;
result.append(s);
} break;
case '\'': {
result.append(1, *it);
} break;
}
} else {
result.append(1, *it);
}
}
os << " " << result << "\n";
}
void Oper::print() const {
std::cout << "Oper( " + assm + " ) ( ";
temp::print_templist(src);
std::cout << " ) ( ";
temp::print_templist(dst);
std::cout << " ) ( ";
temp::print_labellist(jumps);
std::cout << " )";
}
void Label::print() const { std::cout << "Label( " + label.name + " )"; }
void Move::print() const {
std::cout << "Move( " + assm + " ) ( ";
temp::print_templist(src);
temp::print_templist(dst);
std::cout << " )";
}
| 36.528302 | 144 | 0.383781 |
Compiladori
|
df73c1eebe1b09c510eb28608abf20db66330d4c
| 8,710 |
cpp
|
C++
|
Source/Engine/World/Private/Components/Drawable.cpp
|
CodeLikeCXK/AngieEngine
|
26f3cfdb1fdef6378ee75b000b8fe966bebb3a6e
|
[
"MIT"
] | 24 |
2019-07-15T22:48:44.000Z
|
2021-11-02T04:42:48.000Z
|
Source/Engine/World/Private/Components/Drawable.cpp
|
CodeLikeCXK/AngieEngine
|
26f3cfdb1fdef6378ee75b000b8fe966bebb3a6e
|
[
"MIT"
] | 1 |
2021-11-02T09:41:31.000Z
|
2021-11-05T18:35:14.000Z
|
Source/Engine/World/Private/Components/Drawable.cpp
|
CodeLikeCXK/AngieEngine
|
26f3cfdb1fdef6378ee75b000b8fe966bebb3a6e
|
[
"MIT"
] | 3 |
2020-02-03T08:34:50.000Z
|
2021-07-28T05:19:22.000Z
|
/*
Angie Engine Source Code
MIT License
Copyright (C) 2017-2021 Alexander Samusev.
This file is part of the Angie Engine Source Code.
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 <World/Public/Components/Drawable.h>
#include <World/Public/World.h>
#include <Core/Public/IntrusiveLinkedListMacro.h>
AN_CLASS_META( ADrawable )
static void EvaluateRaycastResult( SPrimitiveDef * Self,
ALevel const * LightingLevel,
SMeshVertex const * pVertices,
SMeshVertexUV const * pLightmapVerts,
int LightmapBlock,
unsigned int const * pIndices,
Float3 const & HitLocation,
Float2 const & HitUV,
Float3 * Vertices,
Float2 & TexCoord,
Float3 & LightmapSample )
{
ASceneComponent * primitiveOwner = Self->Owner;
Float3x4 const & transform = primitiveOwner->GetWorldTransformMatrix();
Float3 const & v0 = pVertices[pIndices[0]].Position;
Float3 const & v1 = pVertices[pIndices[1]].Position;
Float3 const & v2 = pVertices[pIndices[2]].Position;
// transform triangle vertices to worldspace
Vertices[0] = transform * v0;
Vertices[1] = transform * v1;
Vertices[2] = transform * v2;
const float hitW = 1.0f - HitUV[0] - HitUV[1];
Float2 uv0 = pVertices[pIndices[0]].GetTexCoord();
Float2 uv1 = pVertices[pIndices[1]].GetTexCoord();
Float2 uv2 = pVertices[pIndices[2]].GetTexCoord();
TexCoord = uv0 * hitW + uv1 * HitUV[0] + uv2 * HitUV[1];
if ( pLightmapVerts && LightingLevel && LightmapBlock >= 0 ) {
Float2 const & lm0 = pLightmapVerts[pIndices[0]].TexCoord;
Float2 const & lm1 = pLightmapVerts[pIndices[1]].TexCoord;
Float2 const & lm2 = pLightmapVerts[pIndices[2]].TexCoord;
Float2 lighmapTexcoord = lm0 * hitW + lm1 * HitUV[0] + lm2 * HitUV[1];
LightmapSample = LightingLevel->SampleLight( LightmapBlock, lighmapTexcoord );
}
else {
LightmapSample = Float3(0.0f);
}
}
ADrawable::ADrawable() {
Bounds.Clear();
WorldBounds.Clear();
OverrideBoundingBox.Clear();
Core::ZeroMem( &Primitive, sizeof( Primitive ) );
Primitive.Owner = this;
Primitive.Type = VSD_PRIMITIVE_BOX;
Primitive.VisGroup = VISIBILITY_GROUP_DEFAULT;
Primitive.QueryGroup = VSD_QUERY_MASK_VISIBLE | VSD_QUERY_MASK_VISIBLE_IN_LIGHT_PASS | VSD_QUERY_MASK_SHADOW_CAST;
Primitive.EvaluateRaycastResult = EvaluateRaycastResult;
bOverrideBounds = false;
bSkinnedMesh = false;
bCastShadow = true;
bAllowRaycast = false;
}
void ADrawable::SetVisibilityGroup( int InVisibilityGroup ) {
Primitive.VisGroup = InVisibilityGroup;
}
int ADrawable::GetVisibilityGroup() const {
return Primitive.VisGroup;
}
void ADrawable::SetVisible( bool _Visible ) {
if ( _Visible ) {
Primitive.QueryGroup |= VSD_QUERY_MASK_VISIBLE;
Primitive.QueryGroup &= ~VSD_QUERY_MASK_INVISIBLE;
} else {
Primitive.QueryGroup &= ~VSD_QUERY_MASK_VISIBLE;
Primitive.QueryGroup |= VSD_QUERY_MASK_INVISIBLE;
}
}
bool ADrawable::IsVisible() const {
return !!( Primitive.QueryGroup & VSD_QUERY_MASK_VISIBLE );
}
void ADrawable::SetHiddenInLightPass( bool _HiddenInLightPass ) {
if ( _HiddenInLightPass ) {
Primitive.QueryGroup &= ~VSD_QUERY_MASK_VISIBLE_IN_LIGHT_PASS;
Primitive.QueryGroup |= VSD_QUERY_MASK_INVISIBLE_IN_LIGHT_PASS;
} else {
Primitive.QueryGroup |= VSD_QUERY_MASK_VISIBLE_IN_LIGHT_PASS;
Primitive.QueryGroup &= ~VSD_QUERY_MASK_INVISIBLE_IN_LIGHT_PASS;
}
}
bool ADrawable::IsHiddenInLightPass() const {
return !(Primitive.QueryGroup & VSD_QUERY_MASK_VISIBLE_IN_LIGHT_PASS);
}
void ADrawable::SetQueryGroup( int _UserQueryGroup ) {
Primitive.QueryGroup |= _UserQueryGroup & 0xffff0000;
}
void ADrawable::SetSurfaceFlags( uint8_t Flags ) {
Primitive.Flags = Flags;
}
uint8_t ADrawable::GetSurfaceFlags() const {
return Primitive.Flags;
}
void ADrawable::SetFacePlane( PlaneF const & _Plane ) {
Primitive.Face = _Plane;
}
PlaneF const & ADrawable::GetFacePlane() const {
return Primitive.Face;
}
void ADrawable::ForceOverrideBounds( bool _OverrideBounds ) {
if ( bOverrideBounds == _OverrideBounds ) {
return;
}
bOverrideBounds = _OverrideBounds;
UpdateWorldBounds();
}
void ADrawable::SetBoundsOverride( BvAxisAlignedBox const & _Bounds ) {
OverrideBoundingBox = _Bounds;
if ( bOverrideBounds ) {
UpdateWorldBounds();
}
}
BvAxisAlignedBox const & ADrawable::GetBounds() const {
return bOverrideBounds ? OverrideBoundingBox : Bounds;
}
BvAxisAlignedBox const & ADrawable::GetWorldBounds() const {
return WorldBounds;
}
void ADrawable::OnTransformDirty() {
Super::OnTransformDirty();
UpdateWorldBounds();
}
void ADrawable::InitializeComponent() {
Super::InitializeComponent();
GetLevel()->AddPrimitive( &Primitive );
UpdateWorldBounds();
if ( bCastShadow )
{
GetWorld()->GetRender().AddShadowCaster( this );
}
}
void ADrawable::DeinitializeComponent() {
Super::DeinitializeComponent();
GetLevel()->RemovePrimitive( &Primitive );
if ( bCastShadow )
{
GetWorld()->GetRender().RemoveShadowCaster( this );
}
}
void ADrawable::SetCastShadow( bool _CastShadow ) {
if ( bCastShadow == _CastShadow )
{
return;
}
bCastShadow = _CastShadow;
if ( bCastShadow )
{
Primitive.QueryGroup |= VSD_QUERY_MASK_SHADOW_CAST;
Primitive.QueryGroup &= ~VSD_QUERY_MASK_NO_SHADOW_CAST;
}
else
{
Primitive.QueryGroup &= ~VSD_QUERY_MASK_SHADOW_CAST;
Primitive.QueryGroup |= VSD_QUERY_MASK_NO_SHADOW_CAST;
}
if ( IsInitialized() )
{
ARenderWorld & RenderWorld = GetWorld()->GetRender();
if ( bCastShadow )
{
RenderWorld.AddShadowCaster( this );
} else
{
RenderWorld.RemoveShadowCaster( this );
}
}
}
void ADrawable::UpdateWorldBounds() {
BvAxisAlignedBox const & boundingBox = GetBounds();
WorldBounds = boundingBox.Transform( GetWorldTransformMatrix() );
Primitive.Box = WorldBounds;
if ( IsInitialized() )
{
GetLevel()->MarkPrimitive( &Primitive );
}
}
void ADrawable::ForceOutdoor( bool _OutdoorSurface ) {
if ( Primitive.bIsOutdoor == _OutdoorSurface ) {
return;
}
Primitive.bIsOutdoor = _OutdoorSurface;
if ( IsInitialized() )
{
GetLevel()->MarkPrimitive( &Primitive );
}
}
bool ADrawable::IsOutdoor() const {
return Primitive.bIsOutdoor;
}
void ADrawable::PreRenderUpdate( SRenderFrontendDef const * _Def ) {
if ( VisFrame != _Def->FrameNumber ) {
VisFrame = _Def->FrameNumber;
OnPreRenderUpdate( _Def );
}
}
bool ADrawable::Raycast( Float3 const & InRayStart, Float3 const & InRayEnd, TPodVector< STriangleHitResult > & Hits ) const {
if ( !Primitive.RaycastCallback ) {
return false;
}
Hits.Clear();
return Primitive.RaycastCallback( &Primitive, InRayStart, InRayEnd, Hits );
}
bool ADrawable::RaycastClosest( Float3 const & InRayStart, Float3 const & InRayEnd, STriangleHitResult & Hit ) const {
if ( !Primitive.RaycastClosestCallback ) {
return false;
}
SMeshVertex const * pVertices;
return Primitive.RaycastClosestCallback( &Primitive, InRayStart, InRayEnd, Hit, &pVertices );
}
| 28.936877 | 126 | 0.673479 |
CodeLikeCXK
|
df76745843887c5fce7997ba21567a428c020ec3
| 164 |
cpp
|
C++
|
ext/n7zip/guid.cpp
|
yagisumi/node-n7zip_native
|
7e9b5e1ca1e2e0889fee637908f4c70238584bac
|
[
"MIT"
] | null | null | null |
ext/n7zip/guid.cpp
|
yagisumi/node-n7zip_native
|
7e9b5e1ca1e2e0889fee637908f4c70238584bac
|
[
"MIT"
] | 1 |
2020-10-16T17:26:54.000Z
|
2020-10-16T17:26:54.000Z
|
ext/n7zip/guid.cpp
|
yagisumi/node-n7zip_native
|
7e9b5e1ca1e2e0889fee637908f4c70238584bac
|
[
"MIT"
] | null | null | null |
// #include <Common/MyInitGuid.h>
#define INITGUID
// #include <7zip/Archive/IArchive.h>
// #include <7zip/IStream.h>
// #include <7zip/ICoder.h>
#include "guid.h"
| 23.428571 | 37 | 0.695122 |
yagisumi
|
df7ad6c85627a82ea0a3eaa9fc6138adc3df9da1
| 7,506 |
cpp
|
C++
|
Source/Game/Collision/CollisionSystem.cpp
|
gunstarpl/Game-Engine-12-2013
|
bfc53f5c998311c17e97c1b4d65792d615c51d36
|
[
"MIT",
"Unlicense"
] | 6 |
2017-12-31T17:28:40.000Z
|
2021-12-04T06:11:34.000Z
|
Source/Game/Collision/CollisionSystem.cpp
|
gunstarpl/Game-Engine-12-2013
|
bfc53f5c998311c17e97c1b4d65792d615c51d36
|
[
"MIT",
"Unlicense"
] | null | null | null |
Source/Game/Collision/CollisionSystem.cpp
|
gunstarpl/Game-Engine-12-2013
|
bfc53f5c998311c17e97c1b4d65792d615c51d36
|
[
"MIT",
"Unlicense"
] | null | null | null |
#include "Precompiled.hpp"
#include "CollisionSystem.hpp"
#include "CollisionComponent.hpp"
#include "Common/Services.hpp"
#include "Game/Event/EventDefinitions.hpp"
#include "Game/Event/EventSystem.hpp"
#include "Game/Entity/EntitySystem.hpp"
#include "Game/Component/ComponentSystem.hpp"
#include "Game/Transform/TransformComponent.hpp"
namespace
{
void TransformBoundingBox(glm::vec4* boundingBox, const TransformComponent* transform)
{
assert(boundingBox != nullptr);
// Translate by position.
boundingBox->x += transform->GetPosition().x;
boundingBox->y += transform->GetPosition().y;
boundingBox->z += transform->GetPosition().x;
boundingBox->w += transform->GetPosition().y;
// Todo: Handle rotation and scale.
}
bool IntersectBoundingBox(const glm::vec4& a, const glm::vec4& b)
{
// Check if bounding boxes collide.
return !(a.x > b.z || a.z < b.x || a.y > b.w || a.w < b.y);
}
}
const float CollisionSystem::Permanent = -1.0f;
CollisionSystem::CollisionSystem() :
m_initialized(false),
m_eventSystem(nullptr),
m_entitySystem(nullptr),
m_componentSystem(nullptr)
{
}
CollisionSystem::~CollisionSystem()
{
Cleanup();
}
void CollisionSystem::Cleanup()
{
m_initialized = false;
m_eventSystem = nullptr;
m_entitySystem = nullptr;
m_componentSystem = nullptr;
ClearContainer(m_objects);
ClearContainer(m_disabled);
}
bool CollisionSystem::Initialize(const Services& services)
{
Cleanup();
// Setup scope guard.
SCOPE_GUARD_IF(!m_initialized, Cleanup());
// Get required services.
m_eventSystem = services.Get<EventSystem>();
if(m_eventSystem == nullptr) return false;
m_entitySystem = services.Get<EntitySystem>();
if(m_entitySystem == nullptr) return false;
m_componentSystem = services.Get<ComponentSystem>();
if(m_componentSystem == nullptr) return false;
// Declare required components.
m_componentSystem->Declare<TransformComponent>();
m_componentSystem->Declare<CollisionComponent>();
// Success!
return m_initialized = true;
}
void CollisionSystem::Update(float timeDelta)
{
assert(m_initialized);
// Update timers of disabled collision response pairs.
for(auto it = m_disabled.begin(); it != m_disabled.end();)
{
const EntityHandle& sourceEntity = it->first.first;
const EntityHandle& targetEntity = it->first.second;
float& time = it->second;
// Check if entities are still valid.
bool sourceEntityValid = m_entitySystem->IsHandleValid(sourceEntity);
bool targetEntityValid = m_entitySystem->IsHandleValid(targetEntity);
if(!sourceEntityValid || !targetEntityValid)
{
m_disabled.erase(it++);
continue;
}
// Skip if it has been disabled permanently.
if(time < 0.0f)
continue;
// Update the timer.
time = std::max(0.0f, time - timeDelta);
// Erase the element if outdated.
if(time == 0.0f)
{
m_disabled.erase(it++);
continue;
}
// Iterate normally if current element hasn't been removed.
++it;
}
// Create a list of collision objects.
auto componentsBegin = m_componentSystem->Begin<CollisionComponent>();
auto componentsEnd = m_componentSystem->End<CollisionComponent>();
for(auto it = componentsBegin; it != componentsEnd; ++it)
{
// Check if entity is active.
if(!m_entitySystem->IsHandleValid(it->first))
continue;
// Get the collision component.
CollisionComponent* collision = &it->second;
if(!collision->IsEnabled())
continue;
// Get the transform component.
TransformComponent* transform = m_componentSystem->Lookup<TransformComponent>(it->first);
if(transform == nullptr)
continue;
// Transform the bounding box to world space.
glm::vec4 boundingBox = collision->GetBoundingBox();
TransformBoundingBox(&boundingBox, transform);
// Add a collision object.
CollisionObject object;
object.entity = it->first;
object.transform = transform;
object.collision = collision;
object.worldAABB = boundingBox;
object.enabled = true;
m_objects.push_back(object);
}
// Process collision objects.
for(auto it = m_objects.begin(); it != m_objects.end(); ++it)
{
// Check if collision object is still enabled.
if(!it->enabled)
continue;
// Check if it collides with other objects.
for(auto other = m_objects.begin(); other != m_objects.end(); ++other)
{
// Don't check against itself.
if(other == it)
continue;
// Check if collision response with other entity has been disabled.
// This shouldn't be here before actuall collision calculation, but
// we only do a collision response (no physical interaction) so it's
// totally fine for now (we skip the expensive calculation).
EntityPair pair = { it->entity, other->entity };
if(m_disabled.count(pair) == 1)
continue;
// Check if collision object is still enabled.
if(!other->enabled)
continue;
// Check if an object can collide with it.
if(it->collision->GetMask() & other->collision->GetType())
{
// Check if objects physically and logically collide.
bool intersects = IntersectBoundingBox(it->worldAABB, other->worldAABB);
bool reversed = (it->collision->GetFlags() & CollisionFlags::Reversed) != 0;
if(intersects != reversed)
{
// Dispatch an entity collision event.
{
GameEvent::EntityCollision event(*it, *other);
m_eventSystem->Dispatch(event);
}
// Check if other collision object is still valid.
if(!m_entitySystem->IsHandleValid(other->entity) || !other->collision->IsEnabled())
{
other->enabled = false;
}
// Check if this collision object is still valid.
if(!m_entitySystem->IsHandleValid(it->entity) || !it->collision->IsEnabled())
{
it->enabled = false;
// No point in checking further collisions against this objects.
break;
}
}
}
}
}
// Clear intermediate collision object list.
m_objects.clear();
}
void CollisionSystem::DisableCollisionResponse(EntityHandle sourceEntity, EntityHandle targetEntity, float duration)
{
assert(m_initialized);
// Check if this pair is already disabled.
EntityPair pair = { sourceEntity, targetEntity };
auto it = m_disabled.find(pair);
if(it != m_disabled.end())
{
// Update the duration.
float& time = it->second;
if(time < duration)
{
time = duration;
}
}
else
{
// Insert a new pair.
m_disabled.emplace(std::make_pair(pair, duration));
}
}
| 29.785714 | 116 | 0.59619 |
gunstarpl
|
df7bc70853f767f049300ed1050261a60ee47670
| 2,111 |
cxx
|
C++
|
Libraries/VtkVgQtUtil/vtkVgQtUtil.cxx
|
judajake/vivia
|
ac0bad0dc200b5af25911513edb0ca6fd6e9f622
|
[
"BSD-3-Clause"
] | 1 |
2017-07-31T07:08:05.000Z
|
2017-07-31T07:08:05.000Z
|
Libraries/VtkVgQtUtil/vtkVgQtUtil.cxx
|
judajake/vivia
|
ac0bad0dc200b5af25911513edb0ca6fd6e9f622
|
[
"BSD-3-Clause"
] | null | null | null |
Libraries/VtkVgQtUtil/vtkVgQtUtil.cxx
|
judajake/vivia
|
ac0bad0dc200b5af25911513edb0ca6fd6e9f622
|
[
"BSD-3-Clause"
] | null | null | null |
/*ckwg +5
* Copyright 2013 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "vtkVgQtUtil.h"
#include <QApplication>
#include <QThreadStorage>
#include <vtkEventQtSlotConnect.h>
#include <vtkVgInstance.h>
namespace // anonymous
{
//-----------------------------------------------------------------------------
class vtkVgQtConnectionManager : public QObject
{
public:
vtkVgQtConnectionManager() {}
virtual ~vtkVgQtConnectionManager() {}
vtkEventQtSlotConnect* manager();
protected:
typedef vtkVgInstance<vtkEventQtSlotConnect> Manager;
QThreadStorage<Manager*> tls;
};
Q_GLOBAL_STATIC(vtkVgQtConnectionManager, globalConnectionManager)
//-----------------------------------------------------------------------------
vtkEventQtSlotConnect* vtkVgQtConnectionManager::manager()
{
if (!this->tls.hasLocalData())
{
this->tls.setLocalData(new Manager);
}
return *this->tls.localData();
}
} // namespace <anonymous>
//-----------------------------------------------------------------------------
void vtkConnect(
vtkObject* sender, unsigned long event, QObject* receiver, const char* slot,
Qt::ConnectionType type)
{
vtkConnect(sender, event, receiver, slot, 0, 0.0f, type);
}
//-----------------------------------------------------------------------------
void vtkConnect(
vtkObject* sender, unsigned long event, QObject* receiver, const char* slot,
void* data, float priority, Qt::ConnectionType type)
{
vtkEventQtSlotConnect* m = globalConnectionManager()->manager();
m->Connect(sender, static_cast<vtkCommand::EventIds>(event),
receiver, slot, data, priority, type);
}
//-----------------------------------------------------------------------------
void vtkDisconnect(
vtkObject* sender, unsigned long event,
QObject* receiver, const char* slot,
void* data)
{
vtkEventQtSlotConnect* m = globalConnectionManager()->manager();
m->Disconnect(sender, event, receiver, slot, data);
}
| 28.527027 | 79 | 0.598768 |
judajake
|
df86b706c9105a2eef30148fc0e759ff03fd9138
| 8,130 |
hpp
|
C++
|
include/cellarium/paged_storage.hpp
|
ortfero/cellarium
|
32b6d19edb5f4110a22eb74c7f9bead8982be665
|
[
"MIT"
] | null | null | null |
include/cellarium/paged_storage.hpp
|
ortfero/cellarium
|
32b6d19edb5f4110a22eb74c7f9bead8982be665
|
[
"MIT"
] | null | null | null |
include/cellarium/paged_storage.hpp
|
ortfero/cellarium
|
32b6d19edb5f4110a22eb74c7f9bead8982be665
|
[
"MIT"
] | null | null | null |
/* This file is part of cellarium library
* Copyright 2020 Andrei Ilin <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include <cmath>
#include <filesystem>
#include <system_error>
#include <memory>
#include <type_traits>
#include "storage.hpp"
#include "file_manager.hpp"
namespace cellarium {
template<typename T>
class paged_storage {
public:
static_assert(std::is_trivial_v<T>, "Only trivial types can be stored");
using path_type = std::filesystem::path;
using storage_type = storage<T>;
using storage_ptr = std::unique_ptr<storage_type>;
using value_type = T;
using size_type = typename storage_type::size_type;
using index_type = typename storage_type::index_type;
static constexpr index_type no_index = storage_type::no_index;
paged_storage() noexcept = default;
~paged_storage() { close(); }
paged_storage(paged_storage const&) = delete;
paged_storage& operator = (paged_storage const&) = delete;
explicit operator bool () const noexcept { return pages_count_ != 0; }
bool initialize(path_type const& path, size_type max_pages,
header const& specified, std::error_code& ec) noexcept {
bool const exists = std::filesystem::exists(path, ec);
if(!!ec)
return false;
if(exists)
return open(path, max_pages, specified, ec);
else
return create(path, max_pages, specified, ec);
}
bool create(path_type const& path, size_type max_pages,
header const& specified, std::error_code& ec) {
file_manager_ = file_manager{path};
max_pages_ = max_pages;
page_capacity_ = specified.capacity();
if(!file_manager_::remove_all(ec))
return false;
pages_ = std::make_unique<storage_ptr[]>(max_pages_);
auto storage = std::make_unique<cellarium::storage>();
path_type const path = file_manager_.name_for_page(0);
if(!storage->create(path, specified, ec))
return false;
pages_[0] = std::move(storage);
last_page_ = std::to_address(pages_[0]);
last_page_base_ = 0;
pages_count_ = 1;
return true;
}
bool open(path_type const& path, size_type max_pages,
header const& specified, std::error_code& ec) {
file_manager_ = file_manager{path};
max_pages_ = max_pages;
auto files = file_manager_.list(ec);
if(!!ec)
return false;
if(files.empty())
return (ec = std::error_code{error::storage_not_found_to_open}), false;
pages_ = std::make_unique<storage_ptr[]>(max_pages_);
if(files.size() == 1) {
auto storage = std::make_unique<storage_type>();
if(!storage->open(path, specified, ec))
return false;
page_capacity_ = storage->header()->capacity();
pages_[0] = std::move(storage);
} else {
size_type total_size = 0; size_type last_storage_capacity = 0;
header each_header; size_type each_size;
for(auto& each_file: files) {
if(!storage_type::read_info(each_file, each_header, each_size, ec))
return false;
if(last_storage_capacity != 0 && last_storage_capacity != each_header.capacity())
return (ec = std::error_code{error::merging_incompatible_storages})
total_size += each_size;
}
files[0] = file_manager_.generate_zero_page_name();
std::filesystem::rename(path, files[0], ec);
if(!!ec)
return false;
size_type const needed_capacity = specified.needed_capacity(total_size);
header const merged_header = header::with_capacity(specified, needed_capacity);
page_capacity_ = merged_header.capacity();
auto merged_storage = std::make_unique<storage_type>();
if(!merged_storage->create(path, merged_header, ec)) {
std::error_code none;
std::filesystem::rename(files[0], path, none);
return false;
}
storage_type each_storage;
for(auto& each_file: files) {
if(!each_storage.open_to_read(each_file, specified, ec)) {
std::error_code none;
std::filesystem::rename(files[0], path, none);
return false;
}
each_storage.for_each([&](value_type const& value) { merged_storage.try_insert(value); });
each_storage.close();
}
for(auto& each_file: files) {
std::filesystem::remove(each_file, ec);
if(!!ec)
return false;
}
pages_[0] = std::move(merged_storage);
}
last_page_ = std::to_address(pages_[0]);
last_page_base_ = 0;
pages_count_ = 1;
return true;
}
void close() noexcept {
pages_.reset();
last_page_ = nullptr;
last_page_base_ = 0;
file_manager_ = file_manager{};
page_capacity_ = 0;
max_pages_ = 0;
pages_count_ = 0;
}
index_type try_insert(T const& data) noexcept {
index_type const inserted = last_page_->try_insert(data);
if(inserted != no_index)
return last_page_base_ + inserted;
if(!add_page(*last_page_->header()))
return no_index;
return last_page_base_ + last_page_->try_insert(data);
}
void remove(index_type index) noexcept {
if(pages_count_ == 1)
return last_page_->remove(index);
index_type base = index / page_capacity_;
index_type offset = index % page_capacity_;
pages_[base]->remove(offset);
}
template<typename F> void for_each(F&& f) {
for(index_type i = 0; i != pages_count_; ++i)
pages_[i]->for_each(std::forward<F>(f));
}
template<typename F> void for_each(F&& f) const {
for(index_type i = 0; i != pages_count_; ++i)
pages_[i]->for_each(std::forward<F>(f));
}
private:
file_manager file_manager_;
size_type page_capacity_{0};
size_type max_pages_{0};
size_type pages_count_{0};
std::unique_ptr<storage_ptr[]> pages_;
storage* last_page_{nullptr};
size_type last_page_base_{0};
bool add_page(header const& last_header) {
if(pages_count_ == max_pages_)
return false;
auto storage = std::make_unique<cellarium::storage>();
path_type const path = file_manager_.name_for_page(pages_count_);
std::error_code ec;
header new_page_header{header::with_page_number(last_header, pages_count_)};
if(!storage->create(path, new_page_header, ec))
return false;
pages_[pages_count_] = std::move(storage);
last_page_ = std::to_address(pages_[pages_count_]);
last_page_base_ = page_capacity_ * pages_count_;
++pages_count_;
return true;
}
}; // paged_storage
} // cellarium
| 32.261905 | 100 | 0.628659 |
ortfero
|
df89d2c08fe187fe049d534e8deed96f55c32fb7
| 11,811 |
cpp
|
C++
|
hip/matrix/dense_kernels.hip.cpp
|
flipflapflop/ginkgo
|
876234e142a0f5bb2a85bb1dd2cc488c3c5d6206
|
[
"BSD-3-Clause"
] | null | null | null |
hip/matrix/dense_kernels.hip.cpp
|
flipflapflop/ginkgo
|
876234e142a0f5bb2a85bb1dd2cc488c3c5d6206
|
[
"BSD-3-Clause"
] | null | null | null |
hip/matrix/dense_kernels.hip.cpp
|
flipflapflop/ginkgo
|
876234e142a0f5bb2a85bb1dd2cc488c3c5d6206
|
[
"BSD-3-Clause"
] | null | null | null |
/*******************************<GINKGO LICENSE>******************************
Copyright (c) 2017-2019, the Ginkgo 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:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************<GINKGO LICENSE>*******************************/
#include "core/matrix/dense_kernels.hpp"
#include <hip/hip_complex.h>
#include <hip/hip_runtime.h>
#include <hip/math_functions.h>
#include <ginkgo/core/base/range_accessors.hpp>
#include <ginkgo/core/matrix/coo.hpp>
#include <ginkgo/core/matrix/csr.hpp>
#include <ginkgo/core/matrix/ell.hpp>
#include <ginkgo/core/matrix/sellp.hpp>
#include "hip/base/hipblas_bindings.hip.hpp"
#include "hip/components/uninitialized_array.hip.hpp"
namespace gko {
namespace kernels {
namespace hip {
/**
* @brief The Dense matrix format namespace.
*
* @ingroup dense
*/
namespace dense {
constexpr auto default_block_size = 512;
template <typename ValueType>
void simple_apply(std::shared_ptr<const HipExecutor> exec,
const matrix::Dense<ValueType> *a,
const matrix::Dense<ValueType> *b,
matrix::Dense<ValueType> *c) GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_DENSE_SIMPLE_APPLY_KERNEL);
template <typename ValueType>
void apply(std::shared_ptr<const HipExecutor> exec,
const matrix::Dense<ValueType> *alpha,
const matrix::Dense<ValueType> *a, const matrix::Dense<ValueType> *b,
const matrix::Dense<ValueType> *beta,
matrix::Dense<ValueType> *c) GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_DENSE_APPLY_KERNEL);
template <typename ValueType>
void scale(std::shared_ptr<const HipExecutor> exec,
const matrix::Dense<ValueType> *alpha,
matrix::Dense<ValueType> *x) GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_DENSE_SCALE_KERNEL);
template <typename ValueType>
void add_scaled(std::shared_ptr<const HipExecutor> exec,
const matrix::Dense<ValueType> *alpha,
const matrix::Dense<ValueType> *x,
matrix::Dense<ValueType> *y) GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_DENSE_ADD_SCALED_KERNEL);
template <typename ValueType>
void compute_dot(std::shared_ptr<const HipExecutor> exec,
const matrix::Dense<ValueType> *x,
const matrix::Dense<ValueType> *y,
matrix::Dense<ValueType> *result)
{
if (hipblas::is_supported<ValueType>::value) {
// TODO: write a custom kernel which does this more efficiently
for (size_type col = 0; col < x->get_size()[1]; ++col) {
hipblas::dot(exec->get_hipblas_handle(), x->get_size()[0],
x->get_const_values() + col, x->get_stride(),
y->get_const_values() + col, y->get_stride(),
result->get_values() + col);
}
} else {
// TODO: implement this
GKO_NOT_IMPLEMENTED;
}
}
GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_DENSE_COMPUTE_DOT_KERNEL);
namespace kernel {
template <typename ValueType>
__global__ __launch_bounds__(default_block_size) void compute_sqrt(
size_type num_cols, ValueType *__restrict__ work)
{
const auto tidx =
static_cast<size_type>(blockDim.x) * blockIdx.x + threadIdx.x;
if (tidx < num_cols) {
work[tidx] = sqrt(abs(work[tidx]));
}
}
} // namespace kernel
template <typename ValueType>
void compute_norm2(std::shared_ptr<const HipExecutor> exec,
const matrix::Dense<ValueType> *x,
matrix::Dense<ValueType> *result)
{
if (hipblas::is_supported<ValueType>::value) {
for (size_type col = 0; col < x->get_size()[1]; ++col) {
hipblas::norm2(exec->get_hipblas_handle(), x->get_size()[0],
x->get_const_values() + col, x->get_stride(),
result->get_values() + col);
}
} else {
compute_dot(exec, x, x, result);
const dim3 block_size(default_block_size, 1, 1);
const dim3 grid_size(ceildiv(result->get_size()[1], block_size.x), 1,
1);
hipLaunchKernelGGL(kernel::compute_sqrt, dim3(grid_size),
dim3(block_size), 0, 0, result->get_size()[1],
as_hip_type(result->get_values()));
}
}
GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_DENSE_COMPUTE_NORM2_KERNEL);
template <typename ValueType, typename IndexType>
void convert_to_coo(std::shared_ptr<const HipExecutor> exec,
matrix::Coo<ValueType, IndexType> *result,
const matrix::Dense<ValueType> *source) GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE(
GKO_DECLARE_DENSE_CONVERT_TO_COO_KERNEL);
template <typename ValueType, typename IndexType>
void convert_to_csr(std::shared_ptr<const HipExecutor> exec,
matrix::Csr<ValueType, IndexType> *result,
const matrix::Dense<ValueType> *source) GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE(
GKO_DECLARE_DENSE_CONVERT_TO_CSR_KERNEL);
template <typename ValueType, typename IndexType>
void convert_to_ell(std::shared_ptr<const HipExecutor> exec,
matrix::Ell<ValueType, IndexType> *result,
const matrix::Dense<ValueType> *source) GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE(
GKO_DECLARE_DENSE_CONVERT_TO_ELL_KERNEL);
template <typename ValueType, typename IndexType>
void convert_to_hybrid(std::shared_ptr<const HipExecutor> exec,
matrix::Hybrid<ValueType, IndexType> *result,
const matrix::Dense<ValueType> *source)
GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE(
GKO_DECLARE_DENSE_CONVERT_TO_HYBRID_KERNEL);
template <typename ValueType, typename IndexType>
void convert_to_sellp(std::shared_ptr<const HipExecutor> exec,
matrix::Sellp<ValueType, IndexType> *result,
const matrix::Dense<ValueType> *source)
GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE(
GKO_DECLARE_DENSE_CONVERT_TO_SELLP_KERNEL);
template <typename ValueType, typename IndexType>
void convert_to_sparsity_csr(std::shared_ptr<const HipExecutor> exec,
matrix::SparsityCsr<ValueType, IndexType> *result,
const matrix::Dense<ValueType> *source)
GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE(
GKO_DECLARE_DENSE_CONVERT_TO_SPARSITY_CSR_KERNEL);
template <typename ValueType>
void count_nonzeros(std::shared_ptr<const HipExecutor> exec,
const matrix::Dense<ValueType> *source,
size_type *result) GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_DENSE_COUNT_NONZEROS_KERNEL);
template <typename ValueType>
void calculate_max_nnz_per_row(std::shared_ptr<const HipExecutor> exec,
const matrix::Dense<ValueType> *source,
size_type *result) GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(
GKO_DECLARE_DENSE_CALCULATE_MAX_NNZ_PER_ROW_KERNEL);
template <typename ValueType, typename IndexType>
void row_permute(std::shared_ptr<const HipExecutor> exec,
const Array<IndexType> *permutation_indices,
matrix::Dense<ValueType> *row_permuted,
const matrix::Dense<ValueType> *orig) GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE(GKO_DECLARE_ROW_PERMUTE_KERNEL);
template <typename ValueType, typename IndexType>
void column_permute(std::shared_ptr<const HipExecutor> exec,
const Array<IndexType> *permutation_indices,
matrix::Dense<ValueType> *column_permuted,
const matrix::Dense<ValueType> *orig) GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE(
GKO_DECLARE_COLUMN_PERMUTE_KERNEL);
template <typename ValueType, typename IndexType>
void inverse_row_permute(std::shared_ptr<const HipExecutor> exec,
const Array<IndexType> *permutation_indices,
matrix::Dense<ValueType> *row_permuted,
const matrix::Dense<ValueType> *orig)
GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE(
GKO_DECLARE_INVERSE_ROW_PERMUTE_KERNEL);
template <typename ValueType, typename IndexType>
void inverse_column_permute(std::shared_ptr<const HipExecutor> exec,
const Array<IndexType> *permutation_indices,
matrix::Dense<ValueType> *column_permuted,
const matrix::Dense<ValueType> *orig)
GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_AND_INDEX_TYPE(
GKO_DECLARE_INVERSE_COLUMN_PERMUTE_KERNEL);
template <typename ValueType>
void calculate_nonzeros_per_row(std::shared_ptr<const HipExecutor> exec,
const matrix::Dense<ValueType> *source,
Array<size_type> *result) GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(
GKO_DECLARE_DENSE_CALCULATE_NONZEROS_PER_ROW_KERNEL);
template <typename ValueType>
void calculate_total_cols(std::shared_ptr<const HipExecutor> exec,
const matrix::Dense<ValueType> *source,
size_type *result, size_type stride_factor,
size_type slice_size) GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(
GKO_DECLARE_DENSE_CALCULATE_TOTAL_COLS_KERNEL);
template <typename ValueType>
void transpose(std::shared_ptr<const HipExecutor> exec,
matrix::Dense<ValueType> *trans,
const matrix::Dense<ValueType> *orig) GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_TRANSPOSE_KERNEL);
template <typename ValueType>
void conj_transpose(std::shared_ptr<const HipExecutor> exec,
matrix::Dense<ValueType> *trans,
const matrix::Dense<ValueType> *orig) GKO_NOT_IMPLEMENTED;
GKO_INSTANTIATE_FOR_EACH_VALUE_TYPE(GKO_DECLARE_CONJ_TRANSPOSE_KERNEL);
} // namespace dense
} // namespace hip
} // namespace kernels
} // namespace gko
| 36.680124 | 80 | 0.698671 |
flipflapflop
|
df8e164c1ab2a07de0eca43a3eaa9c989dd42fbf
| 1,074 |
hpp
|
C++
|
src/Namespace.hpp
|
degustaf/lisp-compiler
|
e176d5b07d68456b07fda516b722213b07f46248
|
[
"MIT"
] | null | null | null |
src/Namespace.hpp
|
degustaf/lisp-compiler
|
e176d5b07d68456b07fda516b722213b07f46248
|
[
"MIT"
] | null | null | null |
src/Namespace.hpp
|
degustaf/lisp-compiler
|
e176d5b07d68456b07fda516b722213b07f46248
|
[
"MIT"
] | null | null | null |
#ifndef NAMESPACE_HPP
#define NAMESPACE_HPP
#include "Interfaces.hpp"
#include <map>
#include "AReference.hpp"
#include "Symbol.hpp"
class Namespace : public AReference, public IReference_inherit<Namespace>, public std::enable_shared_from_this<Namespace> {
public:
const std::shared_ptr<const Symbol> name;
virtual std::string toString(void) const;
virtual std::shared_ptr<const IMap> resetMeta(std::shared_ptr<const IMap> m) {IMeta::_meta = m; return m;};
static std::shared_ptr<Namespace> findOrCreate(std::shared_ptr<const Symbol> name);
private:
std::shared_ptr<const IMap> mappings;
std::shared_ptr<const IMap> aliases;
static std::map<std::shared_ptr<const Symbol>, std::shared_ptr<Namespace> > namespaces;
Namespace(std::shared_ptr<const Symbol> name) : IReference_inherit<Namespace>(name->meta()), name(name),
mappings(NULL), aliases(NULL) /* TODO mappings.set(RT.DEFAULT_IMPORTS); aliases.set(RT.map()); */ {};
virtual std::shared_ptr<const Namespace> with_meta_impl(std::shared_ptr<const IMap>) const;
};
#endif /* NAMESPACE_HPP */
| 34.645161 | 123 | 0.748603 |
degustaf
|
df8f289b23ea2b7ae77d5a04940c2d1055c8af43
| 1,151 |
cpp
|
C++
|
src/stl_generate/main.cpp
|
MaksimPopp/STL_practice_UNN_381906-3
|
83dedf756b170b4ce89e0c74e615bbfd72c4e0a7
|
[
"Apache-2.0"
] | null | null | null |
src/stl_generate/main.cpp
|
MaksimPopp/STL_practice_UNN_381906-3
|
83dedf756b170b4ce89e0c74e615bbfd72c4e0a7
|
[
"Apache-2.0"
] | 1 |
2020-12-12T09:55:31.000Z
|
2020-12-12T11:04:55.000Z
|
src/stl_generate/main.cpp
|
MaksimPopp/STL_practice_UNN_381906-3
|
83dedf756b170b4ce89e0c74e615bbfd72c4e0a7
|
[
"Apache-2.0"
] | 12 |
2020-12-12T09:42:22.000Z
|
2020-12-19T11:44:27.000Z
|
//Лазарев Алексей
//Вместо того чтобы использовать постоянное значение для заполнения
//контейнера, иногда желательно вычислить свое значение для каждого элемента
//Это можно сделать с помощью алгоритма generate(породить).
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <list>
using namespace std;
//В качестве третьего параметра этого алгоритма выступает функция или функциональный объект.
//Следующая программа помещает значения 10, 12, 16 и 18 в массив а:
struct funobj { //можно было использовать функцию вместо функционального объкета, но есть тонкость
int i;
funobj() : i(8) {}
int operator ()() { return i += 2; }
};
int fun() {
static int i = 8;
return i += 2;
}
int main()
{
setlocale(LC_ALL, "Russian");
int a[5];
generate(a, a + 5, funobj());
copy(a, a + 5, ostream_iterator<int>(cout, " "));
cout << endl;//вывод: 10 12 14 16 18
//_________________________________________________________________________________________
list<int> b(5);
generate_n(b.begin(), 5, fun);
copy(b.begin(), b.end(), ostream_iterator<int>(cout, " "));
cout << endl;//вывод: 10 12 14 16 18
return 0;
}
| 28.775 | 98 | 0.720243 |
MaksimPopp
|
df9b20f5d86c7d0add80f831eeaaa97d55a8983b
| 1,133 |
cpp
|
C++
|
offer/problem034/Solution.cpp
|
MyYaYa/leetcode
|
d779c215516ede594267b15abdfba5a47dc879dd
|
[
"Apache-2.0"
] | 1 |
2016-09-29T14:23:59.000Z
|
2016-09-29T14:23:59.000Z
|
offer/problem034/Solution.cpp
|
MyYaYa/leetcode
|
d779c215516ede594267b15abdfba5a47dc879dd
|
[
"Apache-2.0"
] | null | null | null |
offer/problem034/Solution.cpp
|
MyYaYa/leetcode
|
d779c215516ede594267b15abdfba5a47dc879dd
|
[
"Apache-2.0"
] | null | null | null |
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> input, int k) {
if (input.empty() || k == 0 || k > input.size()) return vector<int>();
int left = 0, right = input.size() - 1;
int index = Partition(input, left, right);
while (index != (k-1)) {
if (index < k - 1) {
left = index + 1;
index = Partition(input, left, right);
} else {
right = index - 1;
index = Partition(input, left, right);
}
}
vector<int> result;
for (int i = 0; i < k; i++) {
result.push_back(input[i]);
}
return result;
}
int Partition(vector<int>& numbers, int left, int right) {
int i = left, j = right;
int pivot = numbers[left];
while (i < j) {
while (i < j && numbers[j] >= pivot) j--;
numbers[i] = numbers[j];
while (i < j && numbers[i] < pivot) i++;
numbers[j] = numbers[i];
} // assert i == j
numbers[i] = pivot;
return i;
}
};
| 32.371429 | 79 | 0.44925 |
MyYaYa
|
df9dc069bf88d219dd9444b43c1a0b4a22806ce4
| 3,363 |
hpp
|
C++
|
Engine/Utilities/UtilityAssert.hpp
|
jcolwell/ogl
|
efa8404a25fb7a23bf5951f798a3970134e15386
|
[
"Unlicense"
] | null | null | null |
Engine/Utilities/UtilityAssert.hpp
|
jcolwell/ogl
|
efa8404a25fb7a23bf5951f798a3970134e15386
|
[
"Unlicense"
] | null | null | null |
Engine/Utilities/UtilityAssert.hpp
|
jcolwell/ogl
|
efa8404a25fb7a23bf5951f798a3970134e15386
|
[
"Unlicense"
] | null | null | null |
#ifndef _ASSERT_UTILITIES_H_
#define _ASSERT_UTILITIES_H_
//==================================================================================
// File: UtilityAssert.h
// Desc:
//==================================================================================
//==================================================================================
// INCLUDES
//==================================================================================
#if defined (_WIN32)
#include <Windows.h>
#endif
#include <cassert>
#include <string>
//==================================================================================
// ASSERT
//==================================================================================
//----------------------------------------------------------------------------------
#if defined(_DEBUG) && defined (_WIN32)
//----------------------------------------------------------------------------------
//Windows Platform
#include <Windows.h>
#define LOG(format, ...)\
{\
{\
char buffer[1024];\
sprintf_s(buffer, 1024, (#format), __VA_ARGS__);\
std::string message;\
message += (buffer);\
message += "\n";\
OutputDebugStringA(message.c_str());\
}\
}
//----------------------------------------------------------------------------------
#define ASSERT(condition, format, ...)\
{\
if (!(condition))\
{\
LOG(format, __VA_ARGS__)\
DebugBreak();\
}\
}
#
//----------------------------------------------------------------------------------
#elif defined(_DEBUG) && defined (__APPLE__ && __MACH__)
//----------------------------------------------------------------------------------
// Apple Platform
#include <TargetConditionals.h>
#if TARGET_IPHONE_SIMULATOR == 1
//----------------------------------------------------------------------------------
// iOS in Xcode simulator
#define ASSERT(condition, format, ...)
#elif TARGET_OS_IPHONE == 1
//----------------------------------------------------------------------------------
// iOS on iPhone, iPad, etc.
#define ASSERT(condition, format, ...)
#elif TARGET_OS_MAC == 1
//----------------------------------------------------------------------------------
// OSX
#define ASSERT(condition, format, ...)
//----------------------------------------------------------------------------------
#endif
//----------------------------------------------------------------------------------
#elif defined(_DEBUG) && defined (__linux__)
//----------------------------------------------------------------------------------
//Linux Platform!
#define ASSERT(condition, format, ...)
//----------------------------------------------------------------------------------
#elif defined(_DEBUG) && defined (__Android__)
//----------------------------------------------------------------------------------
//Android !
#define ASSERT(condition, format, ...)
//----------------------------------------------------------------------------------
#else
//----------------------------------------------------------------------------------
#define ASSERT(condition, format, ...)
//----------------------------------------------------------------------------------
#endif
//----------------------------------------------------------------------------------
//==================================================================================
#endif //!_COMMON_UTILITIES_H_
| 33.29703 | 84 | 0.262266 |
jcolwell
|
dfb5dd43032185690be0e8dae1132064200a0368
| 792 |
hpp
|
C++
|
Merlin/Merlin/Platform/OpenGL/opengl_cubemap.hpp
|
kshatos/MerlinEngine
|
a7eb9b39b6cb8a02bef0f739db25268a7a06e215
|
[
"MIT"
] | null | null | null |
Merlin/Merlin/Platform/OpenGL/opengl_cubemap.hpp
|
kshatos/MerlinEngine
|
a7eb9b39b6cb8a02bef0f739db25268a7a06e215
|
[
"MIT"
] | null | null | null |
Merlin/Merlin/Platform/OpenGL/opengl_cubemap.hpp
|
kshatos/MerlinEngine
|
a7eb9b39b6cb8a02bef0f739db25268a7a06e215
|
[
"MIT"
] | null | null | null |
#ifndef OPENGL_CUBEMAP_HPP
#define OPENGL_CUBEMAP_HPP
#include "Merlin/Render/cubemap.hpp"
#include <stdint.h>
namespace Merlin
{
class OpenGLCubemap : public Cubemap
{
uint32_t m_channel_count;
uint32_t m_resolution;
uint32_t m_id;
public:
OpenGLCubemap(const std::vector<std::string>& face_paths);
OpenGLCubemap(uint32_t resolution, uint32_t channel_count);
~OpenGLCubemap();
inline virtual uint32_t GetResolution() override { return m_resolution; }
inline virtual uint32_t GetChannelCount() override { return m_channel_count; }
void Bind(uint32_t slot=0) override;
void UnBind(uint32_t slot = 0) override;
virtual void SetFaceData(CubeFace face, float* data) override;
};
}
#endif
| 28.285714 | 86 | 0.694444 |
kshatos
|
dfc36dea730e557de3eafa86b5b9c02b16e52d0c
| 14,211 |
cpp
|
C++
|
reflex/src/win32/defs.cpp
|
xord/reflexion
|
7d864267152dca1ffeef757d0584777b16a92ede
|
[
"MIT"
] | 3 |
2015-12-18T09:04:48.000Z
|
2022-01-04T22:21:20.000Z
|
reflex/src/win32/defs.cpp
|
xord/reflexion
|
7d864267152dca1ffeef757d0584777b16a92ede
|
[
"MIT"
] | null | null | null |
reflex/src/win32/defs.cpp
|
xord/reflexion
|
7d864267152dca1ffeef757d0584777b16a92ede
|
[
"MIT"
] | null | null | null |
#include "defs.h"
#include <windowsx.h>
#ifndef VK_BROWSER_BACK
#define VK_BROWSER_BACK 0xa6
#define VK_BROWSER_FORWARD 0xa7
#define VK_BROWSER_REFRESH 0xa8
#define VK_BROWSER_STOP 0xa9
#define VK_BROWSER_SEARCH 0xaa
#define VK_BROWSER_FAVORITES 0xab
#define VK_BROWSER_HOME 0xac
#define VK_VOLUME_MUTE 0xad
#define VK_VOLUME_DOWN 0xae
#define VK_VOLUME_UP 0xaf
#define VK_MEDIA_NEXT_TRACK 0xb0
#define VK_MEDIA_PREV_TRACK 0xb1
#define VK_MEDIA_STOP 0xb2
#define VK_MEDIA_PLAY_PAUSE 0xb3
#define VK_LAUNCH_MAIL 0xb4
#define VK_LAUNCH_MEDIA_SELECT 0xb5
#define VK_LAUNCH_APP1 0xb6
#define VK_LAUNCH_APP2 0xb7
#endif
namespace Reflex
{
static bool
get_modifiers (uint* modifiers)
{
if (!modifiers) return false;
*modifiers |=
GetKeyState(VK_SHIFT) ? MOD_SHIFT : 0 |
GetKeyState(VK_CONTROL) ? MOD_CONTROL : 0 |
GetKeyState(VK_MENU) ? MOD_ALT : 0 |
GetKeyState(VK_LWIN) ? MOD_WIN : 0 |
GetKeyState(VK_RWIN) ? MOD_WIN : 0 |
GetKeyState(VK_CAPITAL) ? MOD_CAPS : 0 |
GetKeyState(VK_NUMLOCK) ? MOD_NUMPAD : 0;
return true;
}
static bool
get_keypress (Key* key, UINT msg, WPARAM wp, LPARAM lp)
{
if (!key) return false;
String& s = key->chars;
int& c = key->code;
uint& m = key->modifiers;
switch (wp)
{
case VK_CANCEL: c = KEY_BREAK; return true;
case VK_BACK: c = KEY_BACKSPACE; return true;
case VK_TAB: c = KEY_TAB; return true;
case VK_CLEAR: c = KEY_CLEAR; return true;
case VK_RETURN: c = KEY_RETURN; return true;
case VK_SHIFT: c = KEY_SHIFT; return true;
case VK_CONTROL: c = KEY_CONTROL; return true;
case VK_MENU: c = KEY_ALT; return true;
case VK_PAUSE: c = KEY_PAUSE; return true;
case VK_CAPITAL: c = KEY_CAPSLOCK; return true;
case VK_KANA: c = KEY_IME_KANA; return true;
case VK_JUNJA: c = KEY_IME_JUNJA; return true;
case VK_FINAL: c = KEY_IME_FINAL; return true;
case VK_KANJI: c = KEY_IME_KANJI; return true;
case VK_ESCAPE: c = KEY_ESCAPE; return true;
case VK_CONVERT: c = KEY_IME_CONVERT; return true;
case VK_NONCONVERT: c = KEY_IME_NONCONVERT; return true;
case VK_ACCEPT: c = KEY_IME_ACCEPT; return true;
case VK_MODECHANGE: c = KEY_IME_MODECHANGE; return true;
case VK_SPACE: c = KEY_SPACE; return true;
case VK_PRIOR: c = KEY_PAGEUP; return true;
case VK_NEXT: c = KEY_PAGEDOWN; return true;
case VK_END: c = KEY_END; return true;
case VK_HOME: c = KEY_HOME; return true;
case VK_LEFT: c = KEY_LEFT; return true;
case VK_UP: c = KEY_UP; return true;
case VK_RIGHT: c = KEY_RIGHT; return true;
case VK_DOWN: c = KEY_DOWN; return true;
case VK_SELECT: c = KEY_SELECT; return true;
case VK_PRINT: c = KEY_PRINT; return true;
case VK_EXECUTE: c = KEY_EXECUTE; return true;
case VK_SNAPSHOT: c = KEY_PRINTSCREEN; return true;
case VK_INSERT: c = KEY_INSERT; return true;
case VK_DELETE: c = KEY_DELETE; return true;
case VK_HELP: c = KEY_HELP; return true;
case VK_LWIN: c = KEY_LWIN; return true;
case VK_RWIN: c = KEY_RWIN; return true;
case VK_APPS: c = KEY_APPS; return true;
case VK_SLEEP: c = KEY_SLEEP; return true;
case VK_NUMPAD0: s = "0"; m = MOD_NUMPAD; return true;
case VK_NUMPAD1: s = "1"; m = MOD_NUMPAD; return true;
case VK_NUMPAD2: s = "2"; m = MOD_NUMPAD; return true;
case VK_NUMPAD3: s = "3"; m = MOD_NUMPAD; return true;
case VK_NUMPAD4: s = "4"; m = MOD_NUMPAD; return true;
case VK_NUMPAD5: s = "5"; m = MOD_NUMPAD; return true;
case VK_NUMPAD6: s = "6"; m = MOD_NUMPAD; return true;
case VK_NUMPAD7: s = "7"; m = MOD_NUMPAD; return true;
case VK_NUMPAD8: s = "8"; m = MOD_NUMPAD; return true;
case VK_NUMPAD9: s = "9"; m = MOD_NUMPAD; return true;
case VK_MULTIPLY: s = "*"; m = MOD_NUMPAD; return true;
case VK_ADD: s = "+"; m = MOD_NUMPAD; return true;
case VK_SEPARATOR: s = ":"; m = MOD_NUMPAD; return true;
case VK_SUBTRACT: s = "-"; m = MOD_NUMPAD; return true;
case VK_DECIMAL: s = "."; m = MOD_NUMPAD; return true;
case VK_DIVIDE: s = "/"; m = MOD_NUMPAD; return true;
case VK_F1: c = KEY_F1; m = MOD_FUNCTION; return true;
case VK_F2: c = KEY_F2; m = MOD_FUNCTION; return true;
case VK_F3: c = KEY_F3; m = MOD_FUNCTION; return true;
case VK_F4: c = KEY_F4; m = MOD_FUNCTION; return true;
case VK_F5: c = KEY_F5; m = MOD_FUNCTION; return true;
case VK_F6: c = KEY_F6; m = MOD_FUNCTION; return true;
case VK_F7: c = KEY_F7; m = MOD_FUNCTION; return true;
case VK_F8: c = KEY_F8; m = MOD_FUNCTION; return true;
case VK_F9: c = KEY_F9; m = MOD_FUNCTION; return true;
case VK_F10: c = KEY_F10; m = MOD_FUNCTION; return true;
case VK_F11: c = KEY_F11; m = MOD_FUNCTION; return true;
case VK_F12: c = KEY_F12; m = MOD_FUNCTION; return true;
case VK_F13: c = KEY_F13; m = MOD_FUNCTION; return true;
case VK_F14: c = KEY_F14; m = MOD_FUNCTION; return true;
case VK_F15: c = KEY_F15; m = MOD_FUNCTION; return true;
case VK_F16: c = KEY_F16; m = MOD_FUNCTION; return true;
case VK_F17: c = KEY_F17; m = MOD_FUNCTION; return true;
case VK_F18: c = KEY_F18; m = MOD_FUNCTION; return true;
case VK_F19: c = KEY_F19; m = MOD_FUNCTION; return true;
case VK_F20: c = KEY_F20; m = MOD_FUNCTION; return true;
case VK_F21: c = KEY_F21; m = MOD_FUNCTION; return true;
case VK_F22: c = KEY_F22; m = MOD_FUNCTION; return true;
case VK_F23: c = KEY_F23; m = MOD_FUNCTION; return true;
case VK_F24: c = KEY_F24; m = MOD_FUNCTION; return true;
case VK_NUMLOCK: c = KEY_NUMLOCK; return true;
case VK_SCROLL: c = KEY_SCROLLLOCK; return true;
case VK_LSHIFT: c = KEY_LSHIFT; return true;
case VK_RSHIFT: c = KEY_RSHIFT; return true;
case VK_LCONTROL: c = KEY_LCONTROL; return true;
case VK_RCONTROL: c = KEY_RCONTROL; return true;
case VK_LMENU: c = KEY_LALT; return true;
case VK_RMENU: c = KEY_RALT; return true;
case VK_BROWSER_BACK: c = KEY_BROWSER_BACK; return true;
case VK_BROWSER_FORWARD: c = KEY_BROWSER_FORWARD; return true;
case VK_BROWSER_REFRESH: c = KEY_BROWSER_REFRESH; return true;
case VK_BROWSER_STOP: c = KEY_BROWSER_STOP; return true;
case VK_BROWSER_SEARCH: c = KEY_BROWSER_SEARCH; return true;
case VK_BROWSER_FAVORITES: c = KEY_BROWSER_FAVORITES; return true;
case VK_BROWSER_HOME: c = KEY_BROWSER_HOME; return true;
case VK_VOLUME_MUTE: c = KEY_VOLUME_MUTE; return true;
case VK_VOLUME_DOWN: c = KEY_VOLUME_DOWN; return true;
case VK_VOLUME_UP: c = KEY_VOLUME_UP; return true;
case VK_MEDIA_NEXT_TRACK: c = KEY_MEDIA_NEXT_TRACK; return true;
case VK_MEDIA_PREV_TRACK: c = KEY_MEDIA_PREV_TRACK; return true;
case VK_MEDIA_STOP: c = KEY_MEDIA_STOP; return true;
case VK_MEDIA_PLAY_PAUSE: c = KEY_MEDIA_PLAY_PAUSE; return true;
case VK_LAUNCH_MAIL: c = KEY_LAUNCH_MAIL; return true;
case VK_LAUNCH_MEDIA_SELECT: c = KEY_LAUNCH_MEDIA_SELECT; return true;
case VK_LAUNCH_APP1: c = KEY_LAUNCH_APP1; return true;
case VK_LAUNCH_APP2: c = KEY_LAUNCH_APP2; return true;
#if 0
case VK_OEM_1: s = ","; return true;
case VK_OEM_PLUS: s = "},"; return true;
case VK_OEM_COMMA: s = ","; return true;
case VK_OEM_MINUS: s = "-"; return true;
case VK_OEM_PERIOD: s = "."; return true;
case VK_OEM_2: s = "/"; return true;
case VK_OEM_3: s = "@"; return true;
case VK_OEM_4: s = "["; return true;
case VK_OEM_5: s = "\\"; return true;
case VK_OEM_6: s = "]"; return true;
case VK_OEM_7: s = "^"; return true;
case VK_OEM_8: c = KEY_OEM_8; return true;
case VK_OEM_AX: c = KEY_KEY_OEM_AX; return true;
case VK_OEM_102: s = "\\"; return true;
case VK_ICO_HELP: c = KEY_ICO_HELP; return true;
case VK_ICO_OO: c = KEY_ICO_OO; return true;
#endif
case VK_PROCESSKEY: c = KEY_IME_PROCESS; return true;
#if 0
case VK_ICO_CLEAR: c = KEY_ICO_CLEAR; return true;
case VK_PACKET: c = KEY_PACKET; return true;
case VK_OEM_RESET: c = KEY_OEM_RESET; return true;
case VK_OEM_JUMP: c = KEY_OEM_JUMP; return true;
case VK_OEM_PA1: c = KEY_OEM_PA1; return true;
case VK_OEM_PA2: c = KEY_OEM_PA2; return true;
case VK_OEM_PA3: c = KEY_OEM_PA3; return true;
case VK_OEM_WSCTRL: c = KEY_OEM_WSCTRL; return true;
case VK_OEM_CUSEL: c = KEY_OEM_CUSEL; return true;
case VK_OEM_ATTN: c = KEY_OEM_ATTN; return true;
case VK_OEM_FINISH: c = KEY_OEM_FINISH; return true;
case VK_OEM_COPY: c = KEY_OEM_COPY; return true;
case VK_OEM_AUTO: c = KEY_OEM_AUTO; return true;
case VK_OEM_ENLW: c = KEY_OEM_ENLW; return true;
case VK_OEM_BACKTAB: c = KEY_OEM_BACKTAB; return true;
case VK_ATTN: c = KEY_ATTN; return true;
case VK_CRSEL: c = KEY_CRSEL; return true;
case VK_EXSEL: c = KEY_EXSEL; return true;
case VK_EREOF: c = KEY_EREOF; return true;
#endif
case VK_PLAY: c = KEY_PLAY; return true;
case VK_ZOOM: c = KEY_ZOOM; return true;
#if 0
case VK_NONAME: c = KEY_NONAME; return true;
case VK_PA1: c = KEY_PA1; return true;
case VK_OEM_CLEAR: c = KEY_OEM_CLEAR; return true;
#endif
}
return false;
}
static bool
get_chars (Key* key, UINT msg, WPARAM wp, LPARAM lp)
{
if (!key) return false;
key->chars += (char) wp;
return true;
}
static bool
get_key (Key* key, UINT msg, WPARAM wp, LPARAM lp)
{
if (!key || !get_modifiers(&key->modifiers))
return false;
bool ret = true;
if (
msg == WM_KEYDOWN || msg == WM_KEYUP ||
msg == WM_SYSKEYDOWN || msg == WM_SYSKEYUP)
{
ret &= get_keypress(key, msg, wp, lp);
}
else if (
msg == WM_CHAR || msg == WM_SYSCHAR ||
msg == WM_DEADCHAR || msg == WM_SYSDEADCHAR)
{
ret &= get_chars(key, msg, wp, lp);
}
key->repeat = lp & 0xff;
ret &= get_modifiers(&key->modifiers);
return ret;
}
static int
get_points (Points* points, UINT msg, WPARAM wp, LPARAM lp)
{
if (!points) return false;
switch (msg)
{
case WM_LBUTTONDBLCLK:
points->count += 1;
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
points->type = POINT_MOUSE_LEFT;
points->count += 1;
break;
case WM_RBUTTONDBLCLK:
points->count += 1;
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
points->type = POINT_MOUSE_RIGHT;
points->count += 1;
break;
case WM_MBUTTONDBLCLK:
points->count += 1;
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
points->type = POINT_MOUSE_MIDDLE;
points->count += 1;
break;
}
return get_modifiers(&points->modifiers);
}
Win32Key::Win32Key (UINT msg, WPARAM wp, LPARAM lp)
{
get_key(this, msg, wp, lp);
}
Win32Points::Win32Points (UINT msg, WPARAM wp, LPARAM lp)
: Points(POINT_NONE, GET_X_LPARAM(lp), GET_Y_LPARAM(lp))
{
get_points(this, msg, wp, lp);
}
}// Reflex
| 46.746711 | 75 | 0.517557 |
xord
|
dfc4a1b7b904f4f29f6f2e734ed693b2bc05b654
| 6,224 |
cpp
|
C++
|
NINJA/TreeBuilderManager.cpp
|
jebrosen/NINJA
|
db4f4216fc402e73ae16be65a1fc8e5ecfeef79b
|
[
"MIT"
] | null | null | null |
NINJA/TreeBuilderManager.cpp
|
jebrosen/NINJA
|
db4f4216fc402e73ae16be65a1fc8e5ecfeef79b
|
[
"MIT"
] | null | null | null |
NINJA/TreeBuilderManager.cpp
|
jebrosen/NINJA
|
db4f4216fc402e73ae16be65a1fc8e5ecfeef79b
|
[
"MIT"
] | null | null | null |
/*
* TreeBuilderManager.cpp
*
* Created on: Feb 7, 2016
* Author: michel
*/
#include "TreeBuilderManager.hpp"
#define LINUX 1
#ifdef LINUX
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
//standard constructor
TreeBuilderManager::TreeBuilderManager(std::string method, std::string njTmpDir, std::string inFile, FILE* outFile, InputType inType, OutputType outType, AlphabetType alphType, CorrectionType corrType, int threads, bool useSSE){
this->method = method;
this->njTmpDir = njTmpDir;
this->inFile = inFile;
this->outFile = outFile;
this->inType = inType;
this->outType = outType;
this->alphType = alphType;
this->corrType = corrType;
this->names = NULL;
this->chars = "abcdefghijklmonpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
this->newDistanceMethod = false;
this->threads = threads;
this->newDistanceMethod = useSSE;
}
std::string TreeBuilderManager::doJob(){
int** distances = NULL;
float** memD = NULL;
float* R = NULL;
// all for external memory version
int pageBlockSize = 1024; //that many ints = 4096 bytes;
FILE* diskD = NULL;
int rowLength = 0;
int firstMemCol = -1;
int numCols = 0;
//Runtime runtime = Runtime.getRuntime();
long maxMemory = -1;
bool ok = true;
TreeNode** nodes = NULL;
std::string treeString = "";
//NinjaLogWriter.printVersion();
int K=0;
/*
#ifdef LINUX
maxMemory = sysconf(_SC_PAGE_SIZE)*sysconf(_SC_AVPHYS_PAGES);
#endif
*/
SequenceFileReader* seqReader = NULL;
if (!this->method.compare("extmem")){
if (maxMemory < 1900000000) {
fprintf(stderr,"Warning: using an external-memory variant of NINJA with less than 2GB allocated RAM.\n");
fprintf(stderr,"The data structures of NINJA may not work well if given less than 2GB.\n");
}
fprintf(stderr,"Using External Memory...\n");
njTmpDir += "treeBuilderManager";
mkdir(njTmpDir.c_str(), 0700);
fprintf(stderr,"created temporary directory for this run of NINJA : %s\n", njTmpDir.c_str());
this->njTmpDir += "/";
DistanceReaderExtMem* reader = NULL;
if (inType == alignment) {
seqReader = new SequenceFileReader(&(this->inFile),(SequenceFileReader::AlphabetType) this->alphType);
std::string** seqs = seqReader->getSeqs();
this->names = seqReader->getNames();
this->alphType = (TreeBuilderManager::AlphabetType) seqReader->getAlphType();
fprintf(stderr,"Calculating distances....\n");
DistanceCalculator* distCalc = new DistanceCalculator(seqs,(DistanceCalculator::AlphabetType) alphType,(DistanceCalculator::CorrectionType) corrType, seqReader->numSeqs, this->newDistanceMethod);
K = seqReader->numSeqs;
reader = new DistanceReaderExtMem(distCalc, K);
} else {
fprintf(stderr,"External memory with distances as input not allowed.\n");
Exception::critical();
//reader = new DistanceReaderExtMem(this->inFile);
K = reader->K;
this->names = new std::string*[K];
for (int i = 0;i<K;i++)
this->names[i] = new std::string();
}
R = new float[K]();
rowLength = (K + K-2); //that's a K*K table for the initial values, plus another K*(K-2) columns for new nodes
long maxSize; // max amount of D stored in memory
if (TreeBuilderExtMem::useBinPairHeaps) {
maxSize = maxMemory / 10;
} else {
maxSize = maxMemory / 3;
}
numCols = (int)(maxSize / (4 * K));
int numBlocks = numCols/pageBlockSize; // chops off fractional part
if (numBlocks == 0) numBlocks = 1; //for huge inputs, this could result in memD larger than 400MB
numCols = numBlocks * pageBlockSize;
if (numCols >= 2*K-2) {
numCols = 2*K-2;
} else {
std::string newDir = njTmpDir + "ninja_diskD_tmp";
FILE* tmpFile = fopen(newDir.c_str(),"w+");
diskD = tmpFile;
}
memD = new float*[K];
for(int i=0;i<K;i++){
memD[i] = new float[numCols];
}
firstMemCol = reader->read( names, R, diskD, memD, numCols, rowLength, pageBlockSize);
if(this->outType == dist){
fprintf(stderr,"Output distances with external memory not allowed.\n");
Exception::critical();
}
}else{
DistanceReader* reader = NULL;
if (this->inType == alignment) {
seqReader = new SequenceFileReader(&(this->inFile),(SequenceFileReader::AlphabetType) this->alphType);
std::string** seqs = seqReader->getSeqs();
this->names = seqReader->getNames();
this->alphType = (TreeBuilderManager::AlphabetType) seqReader->getAlphType();
fprintf(stderr,"Calculating distances....\n");
DistanceCalculator* distCalc = new DistanceCalculator(seqs,(DistanceCalculator::AlphabetType) alphType,(DistanceCalculator::CorrectionType) corrType, seqReader->numSeqs,newDistanceMethod);
K = seqReader->numSeqs;
reader = new DistanceReader(distCalc, K, this->threads);
}else{
reader = new DistanceReader(this->inFile);
K = reader->K;
this->names = new std::string*[K];
for (int i = 0;i<K;i++)
this->names[i] = new std::string();
}
distances = new int*[K];
for (int i=0; i<K; i++) {
distances[i] = new int[K - i - 1];
}
if(this->outType == dist){
if(this->inType != alignment){
fprintf(stderr,"Input and output distances not allowed. What are you trying to do?\n");
Exception::critical();
}
reader->readAndWrite(this->names,this->outFile);
return "";
}else{
reader->read( this->names, distances);
}
}
fprintf(stderr,"Generating tree....\n");
int nodesSize = 0;
TreeBuilderBinHeap* tb = NULL;
TreeBuilderExtMem *tb_extmem = NULL;
if (!this->method.compare("inmem") or !this->method.compare("default")) {
tb = new TreeBuilderBinHeap(this->names, distances, K);
nodes = tb->build();
nodesSize = (tb->K*2)-1;
} else if (!method.compare("extmem") ) {
tb_extmem = new TreeBuilderExtMem(names, K, R, njTmpDir, diskD, memD , numCols, firstMemCol, rowLength, maxMemory);
nodes = tb_extmem->build();
nodesSize = (tb_extmem->K*2)-1;
}
std::string *sb;
if (ok && treeString.empty()) {
if (nodes != NULL) {
sb = new std::string();
*sb = "";
nodes[nodesSize-1]->buildTreeString(sb);
treeString = *sb + ";\n";
delete sb;
}
}
if (tb != NULL)
delete tb;
if (tb_extmem != NULL)
delete tb_extmem;
if (seqReader != NULL)
delete seqReader;
delete[] distances;
return (treeString);
}
| 29.358491 | 228 | 0.677378 |
jebrosen
|
dfc6194a7973a9035028ec4014b658ac6667416f
| 9,918 |
cpp
|
C++
|
Source/VoxelArt/Private/Editor/VoxelModificationWorld.cpp
|
limness/Voxel-Art
|
78e3d71f820657568d861983c46ed130fd40f807
|
[
"MIT"
] | 32 |
2021-04-28T21:11:30.000Z
|
2022-03-27T15:28:59.000Z
|
Source/VoxelArt/Private/Editor/VoxelModificationWorld.cpp
|
limness/Voxel-Art
|
78e3d71f820657568d861983c46ed130fd40f807
|
[
"MIT"
] | null | null | null |
Source/VoxelArt/Private/Editor/VoxelModificationWorld.cpp
|
limness/Voxel-Art
|
78e3d71f820657568d861983c46ed130fd40f807
|
[
"MIT"
] | 5 |
2021-04-29T03:09:03.000Z
|
2022-01-26T03:25:47.000Z
|
// Voxel Art Plugin 2021 ~ Copyright Limit
#include "Editor/VoxelModificationWorld.h"
#include "Editor/VoxelEditorData.h"
#include "DrawDebugHelpers.h"
#include "Kismet/KismetMathLibrary.h"
//#include "Noise/SimplexNoiseBPLibrary.h"
#include "Helpers/VoxelTools.h"
#include "Helpers/VoxelSDFUtilities.h"
#include "Helpers/VoxelCollisionBox.h"
#include "VoxelWorld.h"
using namespace VoxelTools;
void UVoxelModificationWorld::SpherePainter(UVoxelEditorData* Data, AVoxelWorld* World, FIntVector Position, float Radius)
{
int VoxelsRadius = FMath::CeilToInt(Radius);
FVoxelOctreeDensity* OutOctant = nullptr;
World->OctreeMutex.Lock();
bool TerrainEdit = Data->EditorType == EEditorType::TerrainEdit;
bool ColorEdit = Data->EditorType == EEditorType::ColorEdit;
if (Data->CopyPastOn && Data->CopyingPasting == ECopyingPasting::Pasting)
{
for (auto& VoxelCopied : Data->CopiedDensity)
{
World->SetVoxelValue(OutOctant, VoxelCopied.Position, VoxelCopied.Value, VoxelCopied.Color, true, true);
}
return;
}
for (int Z = -VoxelsRadius; Z <= VoxelsRadius; Z++)
{
for (int Y = -VoxelsRadius; Y <= VoxelsRadius; Y++)
{
for (int X = -VoxelsRadius; X <= VoxelsRadius; X++)
{
float SphereSDF = FVoxelSDFUtilities::SphereSDF(X, Y, Z, Radius);// Radius - VoxelOffset - FVector(X, Y, Z).Size();
//if (SphereSDF >= -2)
if(Data->CopyPastOn)
{
if (Data->CopyingPasting == ECopyingPasting::Copying)
{
float OutValue = 0.f;
FColor OutColor = FColor(77.f, 77.f, 77.f);
World->GetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, OutValue, OutColor);
Data->CopiedDensity.Add(FVoxelInfo(FIntVector(X, Y, Z) + Position, OutValue, OutColor));
}
}
else
{
float OutValue = 0.f;
FColor OutColor = FColor(77.f, 77.f, 77.f);
World->GetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, OutValue, OutColor);
float Value = 0.f;
{
if (TerrainEdit)
{
if (Data->BrushSoftness == EBrushSoftness::Smooth)
{
}
else if (Data->BrushSoftness == EBrushSoftness::Insert)
{
Value = Data->Dig ? UKismetMathLibrary::FMax(OutValue, SphereSDF) : UKismetMathLibrary::FMin(OutValue, -SphereSDF);
}
}
}
World->SetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, Value, Data->BrushColor, TerrainEdit, ColorEdit);
}
}
}
}
UpdateOverlapOctants(World, Position, FIntVector(1, 1, 1) * VoxelsRadius * 2);
World->OctreeMutex.Unlock();
}
void UVoxelModificationWorld::CubePainter(UVoxelEditorData* Data, AVoxelWorld* World, FIntVector Position, float Radius)
{
int VoxelsRadius = FMath::CeilToInt(Radius);
FVoxelOctreeDensity* OutOctant = nullptr;
World->OctreeMutex.Lock();
for (int Z = -VoxelsRadius; Z <= VoxelsRadius; Z++)
{
for (int Y = -VoxelsRadius; Y <= VoxelsRadius; Y++)
{
for (int X = -VoxelsRadius; X <= VoxelsRadius; X++)
{
float OutValue = 0.f;
FColor OutColor = FColor(77.f, 77.f, 77.f);
World->GetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, OutValue, OutColor);
float Value = Data->Dig ? UKismetMathLibrary::FMax(OutValue, 1.f) : UKismetMathLibrary::FMin(OutValue, -1.f);
if (Data->EditorType == EEditorType::TerrainEdit)
{
World->SetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, Value, FColor(77.f, 77.f, 77.f), true, false);
}
else if (Data->EditorType == EEditorType::ColorEdit)
{
World->SetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, -1.f, Data->BrushColor, false, true);
}
}
}
}
UpdateOverlapOctants(World, Position, FIntVector(1, 1, 1) * (VoxelsRadius + 1) * 2);
World->OctreeMutex.Unlock();
}
void UVoxelModificationWorld::TorusPainter(UVoxelEditorData* Data, AVoxelWorld* World, FIntVector Position, float Radius, float InnerRadius)
{
int VoxelsRadius = FMath::CeilToInt(Radius + InnerRadius);
FVoxelOctreeDensity* OutOctant = nullptr;
World->OctreeMutex.Lock();
for (int Z = -VoxelsRadius; Z <= VoxelsRadius; Z++)
{
for (int Y = -VoxelsRadius; Y <= VoxelsRadius; Y++)
{
for (int X = -VoxelsRadius; X <= VoxelsRadius; X++)
{
float OutValue = 0.f;
FColor OutColor = FColor(77.f, 77.f, 77.f);
World->GetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, OutValue, OutColor);
float TorusSDF = FVoxelSDFUtilities::TorusSDF(X, Y, Z, Radius, InnerRadius);
float Value = Data->Dig ? UKismetMathLibrary::FMax(OutValue, TorusSDF) : UKismetMathLibrary::FMin(OutValue, -TorusSDF);
if (Data->EditorType == EEditorType::TerrainEdit)
{
World->SetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, Value, FColor(77.f, 77.f, 77.f), true, false);
}
else if (Data->EditorType == EEditorType::ColorEdit)
{
World->SetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, -1.f, Data->BrushColor, false, true);
}
}
}
}
UpdateOverlapOctants(World, Position, FIntVector(1, 1, 1) * (VoxelsRadius + 1) * 2);
World->OctreeMutex.Unlock();
}
void UVoxelModificationWorld::ConePainter(UVoxelEditorData* Data, AVoxelWorld* World, FIntVector Position, float Radius, float Height, FVector2D Angle)
{
int VoxelsRadius = FMath::CeilToInt(Radius + Height);
FVoxelOctreeDensity* OutOctant = nullptr;
World->OctreeMutex.Lock();
for (int Z = -VoxelsRadius; Z <= VoxelsRadius; Z++)
{
for (int Y = -VoxelsRadius; Y <= VoxelsRadius; Y++)
{
for (int X = -VoxelsRadius; X <= VoxelsRadius; X++)
{
float OutValue = 0.f;
FColor OutColor = FColor(77.f, 77.f, 77.f);
World->GetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, OutValue, OutColor);
float ConeSDF = FVoxelSDFUtilities::ConeSDF(Y, Z - Height / 2, X, Angle, Height);
float Value = Data->Dig ? UKismetMathLibrary::FMax(OutValue, ConeSDF) : UKismetMathLibrary::FMin(OutValue, -ConeSDF);
if (Data->EditorType == EEditorType::TerrainEdit)
{
World->SetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, Value, FColor(77.f, 77.f, 77.f), true, false);
}
else if (Data->EditorType == EEditorType::ColorEdit)
{
World->SetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, -1.f, Data->BrushColor, false, true);
}
}
}
}
UpdateOverlapOctants(World, Position, FIntVector(1, 1, 1) * (VoxelsRadius + 1) * 2);
World->OctreeMutex.Unlock();
}
void UVoxelModificationWorld::CopyPainter(UVoxelEditorData* Data, AVoxelWorld* World, FIntVector Position, float Radius)
{
int VoxelsRadius = FMath::CeilToInt(Radius);
FVoxelOctreeDensity* OutOctant = nullptr;
World->OctreeMutex.Lock();
// As soon as we start copying new data - we have to set a new center of coordinates
if (Data->CopiedDensity.Num() == 0)
{
Data->CenterCopy = Position;
}
for (int Z = -VoxelsRadius; Z <= VoxelsRadius; Z++)
{
for (int Y = -VoxelsRadius; Y <= VoxelsRadius; Y++)
{
for (int X = -VoxelsRadius; X <= VoxelsRadius; X++)
{
float OutValue = 0.f;
FColor OutColor = FColor(77.f, 77.f, 77.f);
World->GetVoxelValue(OutOctant, FIntVector(X, Y, Z) + Position, OutValue, OutColor);
Data->CopiedDensity.Add(FVoxelInfo(FIntVector(X, Y, Z) + Position - Data->CenterCopy, OutValue, OutColor));
}
}
}
World->OctreeMutex.Unlock();
}
void UVoxelModificationWorld::PastPainter(UVoxelEditorData* Data, AVoxelWorld* World, FIntVector Position)
{
FVoxelOctreeDensity* OutOctant = nullptr;
// Before pasting, we must define the boundaries of the changed data
// so that we can then update only the affected chunks
if (Data->CornerMin == FIntVector(0, 0, 0) && Data->CornerMax == FIntVector(0, 0, 0))
{
for (auto& VoxelCopied : Data->CopiedDensity)
{
if (VoxelCopied.Position.X < Data->CornerMin.X)
{
Data->CornerMin.X = VoxelCopied.Position.X;
}
if (VoxelCopied.Position.Y < Data->CornerMin.Y)
{
Data->CornerMin.Y = VoxelCopied.Position.Y;
}
if (VoxelCopied.Position.Z < Data->CornerMin.Z)
{
Data->CornerMin.Z = VoxelCopied.Position.Z;
}
///////////////////////////////////////////////
///////////////////////////////////////////////
if (VoxelCopied.Position.X > Data->CornerMax.X)
{
Data->CornerMax.X = VoxelCopied.Position.X;
}
if (VoxelCopied.Position.Y > Data->CornerMax.Y)
{
Data->CornerMax.Y = VoxelCopied.Position.Y;
}
if (VoxelCopied.Position.Z > Data->CornerMax.Z)
{
Data->CornerMax.Z = VoxelCopied.Position.Z;
}
}
}
World->OctreeMutex.Lock();
for (auto& VoxelCopied : Data->CopiedDensity)
{
World->SetVoxelValue(OutOctant, VoxelCopied.Position + Position + Data->PastOffset, VoxelCopied.Value, VoxelCopied.Color, true, true);
}
FIntVector MaxBoundBox = FIntVector(
FMath::Max(Data->CornerMax.X, Data->CornerMin.X),
FMath::Max(Data->CornerMax.Y, Data->CornerMin.Y),
FMath::Max(Data->CornerMax.Z, Data->CornerMin.Z)
);
UpdateOverlapOctants(World, Position, (MaxBoundBox + FIntVector(1, 1, 1)) * 2);
World->OctreeMutex.Unlock();
}
float UVoxelModificationWorld::BangPainter(int X, int Y, int Z, float Radius, int octaves, float amplitude, float frequency)
{
float value = 0.f;
float valuefractal = 0.f;
// TODO: Tranfer to Fast Noise
/*
value = Radius - sqrt(X * X + Y * Y + Z * Z);
for (int i = 0; i < octaves; i++)
{
valuefractal += USimplexNoiseBPLibrary::SimplexNoise3D(X * frequency, Y * frequency, Z * frequency) * amplitude;
frequency *= 2.f;
amplitude *= 0.5f;
}
*/
return value + valuefractal;
}
void UVoxelModificationWorld::UpdateOverlapOctants(AVoxelWorld* World, FIntVector Position, FIntVector Size)
{
FVoxelCollisionBox Box = FVoxelCollisionBox(World, Position, Size);
TArray<TSharedPtr<FVoxelOctreeData>> OverlapOctants;
World->GetOverlapingOctree(Box, World->MainOctree, OverlapOctants);
for (auto& Octant : OverlapOctants)
{
if (Octant->Data != nullptr)
{
if (IsValid(Octant->Data->Chunk))
{
World->PutChunkOnGeneration(Octant->Data);
}
}
}
}
| 31.993548 | 151 | 0.672817 |
limness
|
dfc66268313230649d3d4ae8246ff9a66e52be3f
| 975 |
cpp
|
C++
|
tools/flang2/flang2exe/expdf.cpp
|
kammerdienerb/flang
|
8cc4a02b94713750f09fe6b756d33daced0b4a74
|
[
"Apache-2.0"
] | 1 |
2019-12-11T17:43:58.000Z
|
2019-12-11T17:43:58.000Z
|
tools/flang2/flang2exe/expdf.cpp
|
kammerdienerb/flang
|
8cc4a02b94713750f09fe6b756d33daced0b4a74
|
[
"Apache-2.0"
] | 2 |
2019-12-29T21:15:40.000Z
|
2020-06-15T11:21:10.000Z
|
tools/flang2/flang2exe/expdf.cpp
|
kammerdienerb/flang
|
8cc4a02b94713750f09fe6b756d33daced0b4a74
|
[
"Apache-2.0"
] | 3 |
2019-12-21T06:35:35.000Z
|
2020-06-07T23:18:58.000Z
|
/*
* Copyright (c) 1993-2017, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "gbldefs.h"
#include "global.h"
#include "symtab.h"
#include "ilm.h"
/* need ilmtp.h since expand.h tests #ifdef IM_... */
#include "ilmtp.h"
#include "ili.h"
#define EXPANDER_DECLARE_INTERNAL
#include "expand.h"
#include "regutil.h"
ILIB ilib;
ILTB iltb;
BIHB bihb;
NMEB nmeb;
EXP expb = {0};
RCANDB rcandb;
RATB ratb;
| 23.214286 | 75 | 0.718974 |
kammerdienerb
|
dfc7a153e75c3cfc9a922805c0b3278821c8d641
| 5,231 |
cpp
|
C++
|
pheroes/Game/Dlg_Recruit.cpp
|
TripleMOMO/pocketheroes
|
6a6f0726c8ea590592290ac53c38e653cf7f966c
|
[
"Apache-2.0"
] | 3 |
2015-08-08T09:10:02.000Z
|
2016-03-21T08:48:19.000Z
|
pheroes/Game/Dlg_Recruit.cpp
|
TripleMOMO/pocketheroes
|
6a6f0726c8ea590592290ac53c38e653cf7f966c
|
[
"Apache-2.0"
] | null | null | null |
pheroes/Game/Dlg_Recruit.cpp
|
TripleMOMO/pocketheroes
|
6a6f0726c8ea590592290ac53c38e653cf7f966c
|
[
"Apache-2.0"
] | 1 |
2015-08-21T23:32:49.000Z
|
2015-08-21T23:32:49.000Z
|
/*
* This file is a part of Pocket Heroes Game project
* http://www.pocketheroes.net
* https://code.google.com/p/pocketheroes/
*
* Copyright 2004-2010 by Robert Tarasov and Anton Stuk (iO UPG)
*
* 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 "stdafx.h"
#include "Dlg_Recruit.h"
#include "Dlg_CreatInfo.h"
iDlg_Recruit::iDlg_Recruit(iViewMgr* pViewMgr, iCreatGroup& creats, iArmy& army, PLAYER_ID owner)
: iBaseGameDlg(pViewMgr, owner), m_creats(creats), m_army(army), m_avail(0), m_recr(0), m_max(0)
{ }
void iDlg_Recruit::OnCreateDlg()
{
m_avail = m_creats.Count();
check(m_pid != PID_NEUTRAL);
iPlayer* pOwner = gGame.Map().FindPlayer(m_pid);
check(pOwner);
m_crCost = CREAT_DESC[m_creats.Type()].cost;
m_max = iMIN<sint32>(m_avail, pOwner->Minerals().Has(m_crCost));
/*
iMineralSet ms = m_crCost;
while (m_max < m_avail && pOwner->Minerals().Has(ms)) {
ms += m_crCost;
++m_max;
}*/
iRect clrc = ClientRect();
// Creature button
AddChild(m_pIcnButton = new iIconButton(m_pMgr, this, iRect(clrc.x + (clrc.w/2-22), 34,44,56), PDGG_MINIMON + m_creats.Type(), 201));
// Slider
AddChild(m_pSlider = new iPHScrollBar(m_pMgr, this, iRect(clrc.x + (clrc.w/2-80), clrc.y2()-20-10-15,160,15), 101, iScrollBar::Horizontal));
m_pSlider->SetMetrics(m_max+1,1);
// Button size 40x15 (3*40+10)
iRect rc(clrc.x + (clrc.w/2-65), clrc.y2()-DEF_BTN_HEIGHT, 40, DEF_BTN_HEIGHT);
AddChild(new iDlgIconButton(m_pMgr,this,rc,PDGG_BTN_MAX, 100));
rc.x+=45;
AddChild(new iTextButton(m_pMgr,this,rc,TRID_OK, DRC_OK));
rc.x+=45;
AddChild(new iTextButton(m_pMgr,this,rc,TRID_CANCEL, DRC_CANCEL));
GetChildById(100)->SetEnabled(m_max>0);
GetChildById(DRC_OK)->SetEnabled(m_recr>0);
}
void iDlg_Recruit::DoCompose(const iRect& clRect)
{
iRect rc(clRect);
// title
gTextComposer.TextOut(dlgfc_hdr, gApp.Surface(), rc.point(), iFormat(_T("%s %s"), gTextMgr[TRID_RECRUIT], gTextMgr[m_creats.Type()*3+TRID_CREATURE_PEASANT_F3]), rc, AlignTop);
rc.DeflateRect(0,20,0,0);
// information
iRect orc(rc.x + (rc.w/2-100), rc.y, 78, 56);
//gApp.Surface().Darken25Rect(orc);
//ButtonFrame(gApp.Surface(), orc, 0);
iRect trc(orc);
trc.DeflateRect(3);
gTextComposer.TextOut(dlgfc_splain, gApp.Surface(), trc, iStringT(gTextMgr[TRID_AVAILABLE]) + _T(":"), trc, AlignTop);
trc.y += 11;
gTextComposer.TextOut(dlgfc_topic, gApp.Surface(), trc, FormatNumber(m_avail), trc, AlignTop);
trc.y += 14;
gTextComposer.TextOut(dlgfc_splain, gApp.Surface(), trc, iStringT(gTextMgr[TRID_COST_PER_TROOP]) + _T(":"), trc, AlignTop);
trc.y += 11;
gTextComposer.TextOut(dlgfc_topic, gApp.Surface(), rc.point(), MineralSet2Text(m_crCost), trc, AlignTop);
orc.x += 78;
orc.w = 42;
//BlitIcon(gApp.Surface(), PDGG_MINIMON +m_dwel.CrType(), orc);
orc.w = 78;
orc.x += 44;
//gApp.Surface().Darken25Rect(orc);
//ButtonFrame(gApp.Surface(), orc, 0);
trc = orc;
trc.DeflateRect(3);
gTextComposer.TextOut(dlgfc_splain, gApp.Surface(), trc, iStringT(gTextMgr[TRID_RECRUIT]) + _T(":"), trc, AlignTop);
trc.y += 11;
gTextComposer.TextOut(dlgfc_topic, gApp.Surface(), trc, FormatNumber(m_recr), trc, AlignTop);
trc.y += 14;
gTextComposer.TextOut(dlgfc_splain, gApp.Surface(), trc, iStringT(gTextMgr[TRID_TOTAL_COST]) + _T(":"), trc, AlignTop);
trc.y += 11;
iMineralSet ms; ms.Reset();
for(uint32 xx=0; xx<m_recr; ++xx) ms += m_crCost;
gTextComposer.TextOut(dlgfc_topic, gApp.Surface(), rc.point(), MineralSet2Text(ms), trc, AlignTop);
}
iSize iDlg_Recruit::ClientSize() const
{
return iSize(220,110 + DEF_BTN_HEIGHT);
}
void iDlg_Recruit::iCMDH_ControlCommand(iView* pView, CTRL_CMD_ID cmd, sint32 param)
{
if (!IsValidDialog()) return;
uint32 uid = pView->GetUID();
if (uid == 101) {
m_recr = m_pSlider->CurPos();
GetChildById(DRC_OK)->SetEnabled(m_recr>0);
} else if (cmd == CCI_BTNCLICK) {
if (uid == 100) {
m_pSlider->SetCurPos(m_max);
m_recr = m_max;
GetChildById(DRC_OK)->SetEnabled(m_recr>0);
} else if (uid == 201) {
iCreatGroup group(m_creats.Type(),m_avail);
iDlg_CreatInfo cidlg(m_pMgr, m_pid, group, iFurtSkills(), false, 0);
cidlg.DoModal();
} else if (uid == DRC_OK) {
// Check space in target army
if (m_army.CanAddGroup(m_creats.Type())) {
m_army.AddGroup(m_creats.Type(), m_recr);
m_creats.Count() -= m_recr;
gGame.Map().FindPlayer(m_pid)->Minerals() -= m_crCost * m_recr;
EndDialog(DRC_OK);
} else {
iTextDlg tdlg(m_pMgr, _T(""), gTextMgr[TRID_MSG_NO_ROOM], m_pid);
tdlg.DoModal();
}
} else if (uid == DRC_CANCEL) {
EndDialog(DRC_CANCEL);
}
}
}
| 34.873333 | 177 | 0.678455 |
TripleMOMO
|
dfd1932a30a21161f6deab54b076cc19ae0b4031
| 10,438 |
cpp
|
C++
|
source/gfx/gfx_objects.cpp
|
SaeruHikari/VulkanLittleMaster
|
204696b0eb87500bc6ed3ed7fca68f1458e698a1
|
[
"MIT"
] | 3 |
2022-03-16T03:57:49.000Z
|
2022-03-20T08:05:35.000Z
|
source/gfx/gfx_objects.cpp
|
SaeruHikari/VulkanLittleMaster
|
204696b0eb87500bc6ed3ed7fca68f1458e698a1
|
[
"MIT"
] | null | null | null |
source/gfx/gfx_objects.cpp
|
SaeruHikari/VulkanLittleMaster
|
204696b0eb87500bc6ed3ed7fca68f1458e698a1
|
[
"MIT"
] | null | null | null |
#include "gfx/gfx_objects.h"
#include <vector>
#include <string_view>
#include <iostream>
void LittleGFXAdapter::queryProperties()
{
vkPhysDeviceProps.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
vkGetPhysicalDeviceProperties2(vkPhysicalDevice, &vkPhysDeviceProps);
std::cout << vkPhysDeviceProps.properties.deviceName << std::endl;
}
void LittleGFXAdapter::selectExtensionsAndLayers()
{
uint32_t ext_count = 0;
vkEnumerateDeviceExtensionProperties(vkPhysicalDevice, NULL, &ext_count, NULL);
std::vector<VkExtensionProperties> allExtentions(ext_count);
vkEnumerateDeviceExtensionProperties(vkPhysicalDevice, NULL, &ext_count, allExtentions.data());
for (auto ext : wanted_device_exts)
{
for (auto usable_ext : allExtentions)
{
if (std::string_view(ext) == std::string_view(usable_ext.extensionName))
{
deviceExtensions.emplace_back(ext);
}
}
}
}
void LittleGFXAdapter::selectQueueIndices()
{
vkGetPhysicalDeviceQueueFamilyProperties(vkPhysicalDevice, &queueFamiliesCount, nullptr);
std::vector<VkQueueFamilyProperties> queueProps(queueFamiliesCount);
vkGetPhysicalDeviceQueueFamilyProperties(vkPhysicalDevice, &queueFamiliesCount, queueProps.data());
uint32_t queueIdx = 0;
for (auto&& queueProp : queueProps)
{
// select graphics index
if (queueProp.queueFlags & VK_QUEUE_GRAPHICS_BIT)
{
gfxQueueIndex = queueIdx;
}
queueIdx++;
}
}
bool LittleGFXInstance::Initialize(bool enableDebugLayer)
{
// volk需要初始化,这个初始化过程其实就是在LoadLibrary("vulkan-1.dll")
static VkResult volkInit = volkInitialize();
if (volkInit != VK_SUCCESS)
{
assert(0 && "Volk Initialize Failed!");
return false;
}
selectExtensionsAndLayers(enableDebugLayer);
VkApplicationInfo appInfo = {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "LittleMaster";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "No Engine";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_1;
VkInstanceCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
// 填写我们上文筛选出的可以打开的层以及扩展
createInfo.enabledLayerCount = (uint32_t)instanceLayers.size();
createInfo.ppEnabledLayerNames = instanceLayers.data();
createInfo.enabledExtensionCount = (uint32_t)instanceExtensions.size();
createInfo.ppEnabledExtensionNames = instanceExtensions.data();
// 创建VkInstance
if (vkCreateInstance(&createInfo, nullptr, &vkInstance) != VK_SUCCESS)
{
assert(0 && "Vulkan: failed to create instance!");
}
// 使用volk的动态加载方法,直接加载Instance中的Vulkan函数地址
volkLoadInstance(vkInstance);
// 直接获取所有的Adapter/PhysicalDevice供以后使用
fetchAllAdapters();
return true;
}
bool LittleGFXInstance::Destroy()
{
vkDestroyInstance(vkInstance, VK_NULL_HANDLE);
return true;
}
void LittleGFXInstance::selectExtensionsAndLayers(bool enableDebugLayer)
{
// 查询Extension支持并打开它们
{
// 这是C API中很常用的一种两段式query法
uint32_t ext_count = 0;
// 首先传入NULL Data和一个计数指针,API会返回一个数量
vkEnumerateInstanceExtensionProperties(NULL, &ext_count, NULL);
// 随后应用程序可以根据返回的数量来开辟合适的空间
std::vector<VkExtensionProperties> allExtentions(ext_count);
// 最后再把空间传回API,获得对应的返回数据
vkEnumerateInstanceExtensionProperties(NULL, &ext_count, allExtentions.data());
for (auto ext : wanted_instance_exts)
{
for (auto usable_ext : allExtentions)
{
if (std::string_view(ext) == std::string_view(usable_ext.extensionName))
{
instanceExtensions.emplace_back(ext);
}
}
}
}
// 查询Validation Layer支持并打开它
if (enableDebugLayer)
{
uint32_t layer_count = 0;
vkEnumerateInstanceLayerProperties(&layer_count, NULL);
std::vector<VkLayerProperties> allLayers(layer_count);
vkEnumerateInstanceLayerProperties(&layer_count, allLayers.data());
for (auto usable_layer : allLayers)
{
if (std::string_view(validation_layer_name) == std::string_view(usable_layer.layerName))
{
instanceLayers.emplace_back(validation_layer_name);
}
}
}
}
void LittleGFXInstance::fetchAllAdapters()
{
uint32_t adapter_count = 0;
vkEnumeratePhysicalDevices(vkInstance, &adapter_count, nullptr);
adapters.resize(adapter_count);
std::vector<VkPhysicalDevice> allVkAdapters(adapter_count);
vkEnumeratePhysicalDevices(vkInstance, &adapter_count, allVkAdapters.data());
for (uint32_t i = 0; i < allVkAdapters.size(); i++)
{
adapters[i].gfxInstance = this;
adapters[i].vkPhysicalDevice = allVkAdapters[i];
adapters[i].queryProperties();
adapters[i].selectExtensionsAndLayers();
adapters[i].selectQueueIndices();
}
}
// 队列优先级。概念上是分配不同Queue执行调度优先级的参数。
// 全部给1.f,忽略此参数。
const float queuePriorities[] = {
1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, //
1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, //
1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, //
1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, //
};
bool LittleGFXDevice::Initialize(LittleGFXAdapter* adapter)
{
gfxAdapter = adapter;
// 要申请的graphics queue
VkDeviceQueueCreateInfo queueInfo = {};
queueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueInfo.queueCount = 1;
queueInfo.queueFamilyIndex = adapter->gfxQueueIndex;
queueInfo.pQueuePriorities = queuePriorities;
VkPhysicalDeviceFeatures deviceFeatures{};
VkDeviceCreateInfo deviceInfo = {};
deviceInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
deviceInfo.queueCreateInfoCount = 1;
deviceInfo.pQueueCreateInfos = &queueInfo;
deviceInfo.pEnabledFeatures = &deviceFeatures;
// 打开需要的扩展和层
deviceInfo.enabledExtensionCount = adapter->deviceExtensions.size();
deviceInfo.ppEnabledExtensionNames = adapter->deviceExtensions.data();
deviceInfo.enabledLayerCount = adapter->deviceLayers.size();
deviceInfo.ppEnabledLayerNames = adapter->deviceLayers.data();
if (vkCreateDevice(adapter->vkPhysicalDevice, &deviceInfo, nullptr, &vkDevice) != VK_SUCCESS)
{
assert(0 && "failed to create logical device!");
return false;
}
// 使用volk从device中读出相关的API函数地址
// 这些API被放进volkTable中,因为转发层数很少所以性能有一定提升
volkLoadDeviceTable(&volkTable, vkDevice);
return true;
}
bool LittleGFXDevice::Destroy()
{
vkDestroyDevice(vkDevice, nullptr);
return true;
}
bool LittleGFXWindow::Initialize(const wchar_t* title, LittleGFXDevice* device, bool enableVsync)
{
auto succeed = LittleWindow::Initialize(title);
gfxDevice = device;
createSurface(device->gfxAdapter->gfxInstance);
createSwapchainKHR(device, enableVsync);
return succeed;
}
bool LittleGFXWindow::Destroy()
{
auto succeed = LittleWindow::Destroy();
gfxDevice->volkTable.vkDestroySwapchainKHR(gfxDevice->vkDevice, vkSwapchain, nullptr);
vkDestroySurfaceKHR(gfxDevice->gfxAdapter->gfxInstance->vkInstance, vkSurface, nullptr);
return succeed;
}
void LittleGFXWindow::createSurface(LittleGFXInstance* inst)
{
#if defined(_WIN32) || defined(_WIN64)
VkWin32SurfaceCreateInfoKHR create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
create_info.pNext = NULL;
create_info.flags = 0;
create_info.hinstance = GetModuleHandle(NULL);
create_info.hwnd = hWnd;
if (vkCreateWin32SurfaceKHR(inst->vkInstance, &create_info, nullptr, &vkSurface) != VK_SUCCESS)
{
assert(0 && "Create VKWin32 Surface Failed!");
}
return;
#endif
assert(0 && "Platform not supported!");
}
/*
VkPresentModeKHR preferredModeList[] = {
VK_PRESENT_MODE_IMMEDIATE_KHR, // normal
VK_PRESENT_MODE_MAILBOX_KHR, // low latency
VK_PRESENT_MODE_FIFO_RELAXED_KHR, // minimize stuttering
VK_PRESENT_MODE_FIFO_KHR // low power consumption
};
*/
#define clamp(x, min, max) (x) < (min) ? (min) : ((x) > (max) ? (max) : (x))
void LittleGFXWindow::createSwapchainKHR(LittleGFXDevice* device, bool enableVsync)
{
// 获取surface支持的格式信息
VkSurfaceCapabilitiesKHR caps = { 0 };
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device->gfxAdapter->vkPhysicalDevice, vkSurface, &caps);
// 创建
uint32_t presentQueueFamilyIndex = device->gfxAdapter->gfxQueueIndex;
VkExtent2D extent{
clamp(width, caps.minImageExtent.width, caps.maxImageExtent.width),
clamp(height, caps.minImageExtent.height, caps.maxImageExtent.height)
};
VkSwapchainCreateInfoKHR swapchainInfo = {};
swapchainInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swapchainInfo.pNext = NULL;
swapchainInfo.flags = 0;
swapchainInfo.surface = vkSurface;
swapchainInfo.minImageCount = enableVsync ? 3 : 2;
swapchainInfo.presentMode = enableVsync ? VK_PRESENT_MODE_FIFO_KHR : VK_PRESENT_MODE_IMMEDIATE_KHR;
// 因为OGL标准,此format和色彩空间一定是被现在的显卡支持的
swapchainInfo.imageFormat = VK_FORMAT_B8G8R8A8_UNORM;
swapchainInfo.imageColorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
swapchainInfo.imageExtent = extent;
swapchainInfo.imageArrayLayers = 1;
swapchainInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
// 反转缓冲区呈现交换链是一种GPU行为,同样是被Queue执行的。这里指定可以执行Present操作的Queue。
swapchainInfo.queueFamilyIndexCount = 1;
swapchainInfo.pQueueFamilyIndices = &presentQueueFamilyIndex;
swapchainInfo.clipped = VK_TRUE;
// 在这里指定一个老的交换链可以加速创建
swapchainInfo.oldSwapchain = VK_NULL_HANDLE;
// 可以在呈现时指定某种变换,比如把图片逆时针旋转90度
swapchainInfo.preTransform = caps.currentTransform;
// 是否使用Alpha通道和其它的窗口混合,这里可以实现很多奇特的效果,但是我们不需要。所以设定为OPAQUE(不透明)模式
swapchainInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
VkResult res = device->volkTable.vkCreateSwapchainKHR(
device->vkDevice, &swapchainInfo, nullptr, &vkSwapchain);
if (VK_SUCCESS != res)
{
assert(0 && "fatal: vkCreateSwapchainKHR failed!");
}
}
| 37.68231 | 103 | 0.705403 |
SaeruHikari
|
2547637c7fa4c3af8dc1ca379700190fbfc2dce1
| 1,878 |
cc
|
C++
|
second-project/solutions/TLM/LT/src/multiplier_LT.cc
|
elenaramon/Embedded-systems-design-projects
|
228f50e40a46a4c9fc738d38f910a22663900697
|
[
"MIT"
] | null | null | null |
second-project/solutions/TLM/LT/src/multiplier_LT.cc
|
elenaramon/Embedded-systems-design-projects
|
228f50e40a46a4c9fc738d38f910a22663900697
|
[
"MIT"
] | null | null | null |
second-project/solutions/TLM/LT/src/multiplier_LT.cc
|
elenaramon/Embedded-systems-design-projects
|
228f50e40a46a4c9fc738d38f910a22663900697
|
[
"MIT"
] | null | null | null |
#include "multiplier_LT.hh"
multiplier_LT::multiplier_LT(sc_module_name name_): sc_module(name_), target_socket("target_socket"), pending_transaction(NULL) {
target_socket(*this);
}
void multiplier_LT::b_transport(tlm::tlm_generic_payload & trans, sc_time & t) {
timing_annotation = SC_ZERO_TIME;
ioDataStruct = *((iostruct*) trans.get_data_ptr());
if (trans.is_write()) {
cout << "\t\t[MULTIPLIER:] Received invocation of the b_transport primitive - write" << endl;
cout << "\t\t[MULTIPLIER:] Invoking the multiplication_function to calculate the floating point multiplication" << endl;
multiplication_function();
ioDataStruct.result = tmp_result;
cout << "\t\t[MULTIPLIER:] Returning result: " << tmp_result << endl;
*((iostruct*) trans.get_data_ptr()) = ioDataStruct;
trans.set_response_status(tlm::TLM_OK_RESPONSE);
}
else if (trans.is_read()) {
cout << "\t\t[MULTIPLIER:] Received invocation of the b_transport primitive - read" << endl;
ioDataStruct.result = tmp_result;
cout << "\t\t[MULTIPLIER:] Returning result: " << tmp_result << endl;
*((iostruct*) trans.get_data_ptr()) = ioDataStruct;
}
t += timing_annotation;
}
bool multiplier_LT::get_direct_mem_ptr(tlm::tlm_generic_payload & trans, tlm::tlm_dmi & dmi_data) {
return false;
}
tlm::tlm_sync_enum multiplier_LT::nb_transport_fw(tlm::tlm_generic_payload & trans, tlm::tlm_phase & phase, sc_time & t) {
return tlm::TLM_COMPLETED;
}
unsigned int multiplier_LT::transport_dbg(tlm::tlm_generic_payload & trans) {
return 0;
}
void multiplier_LT:: multiplication_function() {
cout << "\t\t[MULTIPLIER:] Calculating multiplication_function ... " << endl;
tmp_result = float(ioDataStruct.op1 * ioDataStruct.op2);
timing_annotation += sc_time(100, SC_NS);
}
void multiplier_LT::end_of_elaboration() {
}
void multiplier_LT::reset() {
}
| 32.37931 | 129 | 0.71885 |
elenaramon
|
254ab8e1dd62bbb70df38566d0eedd2d9be7e406
| 1,307 |
cpp
|
C++
|
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 04(Unsorted List )/unsortedtype(23).cpp
|
diptu/Teaching
|
20655bb2c688ae29566b0a914df4a3e5936a2f61
|
[
"MIT"
] | null | null | null |
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 04(Unsorted List )/unsortedtype(23).cpp
|
diptu/Teaching
|
20655bb2c688ae29566b0a914df4a3e5936a2f61
|
[
"MIT"
] | null | null | null |
CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 04(Unsorted List )/unsortedtype(23).cpp
|
diptu/Teaching
|
20655bb2c688ae29566b0a914df4a3e5936a2f61
|
[
"MIT"
] | null | null | null |
#include "UnsortedType.h"
template<class ItemType>
UnsortedType<ItemType>::UnsortedType()
{
length=0;
currentPos=-1;
}
template<class ItemType>
void UnsortedType<ItemType>::MakeEmpty()
{
length =0;
}
template<class ItemType>
bool UnsortedType<ItemType>::IsFull()
{
return (length == MAX_ITEMS);
}
template<class ItemType>
int UnsortedType<ItemType>::LengthIs()
{
return length;
}
template<class ItemType>
void UnsortedType<ItemType>::ResetList()
{
currentPos=-1;
}
template<class ItemType>
void UnsortedType<ItemType>::GetNextItem(ItemType& item)
{
currentPos++;
item = info[currentPos];
}
template <class ItemType>
void UnsortedType<ItemType>::RetrieveItem(ItemType& item, bool &found)
{
int location;
found = false;
for (location = 0; location < length; location++)
{
if(item == info[location])
{
found = true;
item = info[location];
break;
}
}
}
template<class ItemType>
void UnsortedType<ItemType>::InsertItem(ItemType item)
{
info[length] = item;
length++;
}
template<class ItemType>
void UnsortedType<ItemType>::DeleteItem(ItemType item)
{
int location =0;
while(item !=info[location])
location++;
info[location]=info[length-1];
length--;
}
| 16.3375 | 70 | 0.653405 |
diptu
|
255023e849b9bc071d3e5a5cb2a6f0054b4fd1b8
| 5,366 |
cpp
|
C++
|
ProblemSelect/Control.cpp
|
kravitz/transims4
|
ea0848bf3dc71440d54724bb3ecba3947b982215
|
[
"NASA-1.3"
] | 2 |
2018-04-27T11:07:02.000Z
|
2020-04-24T06:53:21.000Z
|
ProblemSelect/Control.cpp
|
idkravitz/transims4
|
ea0848bf3dc71440d54724bb3ecba3947b982215
|
[
"NASA-1.3"
] | null | null | null |
ProblemSelect/Control.cpp
|
idkravitz/transims4
|
ea0848bf3dc71440d54724bb3ecba3947b982215
|
[
"NASA-1.3"
] | null | null | null |
//*********************************************************
// Control.cpp - Program Control
//*********************************************************
#include "ProblemSelect.hpp"
#include "Utility.hpp"
//---------------------------------------------------------
// Program_Control
//---------------------------------------------------------
void ProblemSelect::Program_Control (void)
{
int type;
char *str_ptr, *format_ptr, buffer [FIELD_BUFFER];
//---- open network files ----
Demand_Service::Program_Control ();
//---- open the plan file ----
str_ptr = Get_Control_String (PROBLEM_FILE);
if (str_ptr == NULL) goto control_error;
format_ptr = Get_Control_String (PROBLEM_FORMAT);
if (format_ptr != NULL) {
problem_file.File_Format (format_ptr);
}
if (Partition ()) {
problem_file.Filename (Project_Filename (str_ptr), Partition_Number ());
} else {
problem_file.Filename (Project_Filename (str_ptr));
}
Print_Filename (2, problem_file.File_Type (), problem_file.Groupname ());
if (!problem_file.Open (0)) {
File_Error (problem_file.File_Type (), problem_file.Filename ());
}
//---- get the household list ----
str_ptr = Get_Control_String (HOUSEHOLD_LIST);
if (str_ptr != NULL) {
hh_flag = true;
str_ptr = Project_Filename (str_ptr, Extension ());
hhold_file.File_Type ("Household List");
Print_Filename (2, hhold_file.File_Type (), str_ptr);
hhold_file.Filename (str_ptr);
if (!hhold_file.Open (0)) {
File_Error ("Opening Household List", hhold_file.Filename ());
}
}
//---- get the household list ----
str_ptr = Get_Control_String (NEW_HOUSEHOLD_LIST);
if (str_ptr == NULL) goto control_error;
str_ptr = Project_Filename (str_ptr, Extension ());
new_hhold_file.File_Type ("New Household List");
new_hhold_file.File_Access (Db_Code::CREATE);
Print_Filename (2, new_hhold_file.File_Type (), str_ptr);
new_hhold_file.Filename (str_ptr);
if (!new_hhold_file.Open (0)) {
File_Error ("Opening New Household List", new_hhold_file.Filename ());
}
//---- get the select links ----
str_ptr = Get_Control_String (SELECT_LINKS);
if (str_ptr != NULL) {
Print (2, "Select Links = %s", str_ptr);
if (!links.Add_Ranges (str_ptr)) {
File_Error ("Link Range", str_ptr);
}
link_flag = true;
if (!Network_File_Flag (LINK) || !Network_File_Flag (NODE)) {
Error ("Link and Node files are required for Link-Based Processing");
}
}
//---- get the select time periods ----
str_ptr = Get_Control_String (SELECT_TIME_PERIODS);
if (str_ptr != NULL) {
Print (2, "Select Time Periods = %s", str_ptr);
//---- get the time of day format ----
format_ptr = Get_Control_String (TIME_OF_DAY_FORMAT);
if (format_ptr != NULL) {
if (!times.Format (str_ptr)) {
Error ("Time of Day Format %s was Unrecognized", format_ptr);
}
Print (1, "Time of Day Format = %s", format_ptr);
}
if (!times.Add_Ranges (str_ptr)) {
File_Error ("Time Period Range", str_ptr);
}
time_flag = true;
}
//---- get the select problem types ----
str_ptr = Get_Control_String (SELECT_PROBLEM_TYPES);
if (str_ptr != NULL) {
Print (2, "Select Problem Types = %s", str_ptr);
while (str_ptr != NULL) {
str_ptr = Get_Token (str_ptr, buffer, sizeof (buffer));
if (buffer [0] != '\0') {
type = Problem_Code (buffer);
str_fmt (buffer, sizeof (buffer), "%d", type);
if (!types.Add_Ranges (buffer)) {
File_Error ("Problem Types", str_ptr);
}
type_flag = true;
}
}
}
//---- get the select subarea polygon ----
str_ptr = Get_Control_String (SELECT_SUBAREA_POLYGON);
if (str_ptr != NULL) {
Print (1);
select_subarea.File_Type ("Select Subarea Polygon");
select_subarea.Open (Project_Filename (str_ptr));
if (!select_subarea.Read_Record ()) {
Error ("Reading %s", select_subarea.File_Type ());
}
subarea_flag = true;
if (problem_file.Link_Field () > 0) {
if (!Network_File_Flag (NODE) || !Network_File_Flag (LINK)) {
Error ("Node and Link files are Required for Select Subarea Polygon");
}
}
if (!Network_File_Flag (ACTIVITY_LOCATION)) {
Error ("An Activity Location file is Required for Select Subarea Polygon");
}
}
//---- get the selection percentage ----
str_ptr = Get_Control_String (SELECTION_PERCENTAGE);
if (str_ptr != NULL) {
Get_Double (str_ptr, &percent);
if (percent < 0.1 || percent > 100.0) {
Error ("Selection Percentage %.2lf is Out of Range (0.1-100.0)", percent);
}
select_flag = (percent != 100.0);
}
Print (2, "Selection Percentage = %.1lf%%", percent);
percent /= 100.0;
//---- get the max percent selected ----
str_ptr = Get_Control_String (MAXIMUM_PERCENT_SELECTED);
if (str_ptr != NULL) {
Get_Double (str_ptr, &max_percent);
if (max_percent < 1.0 || max_percent > 100.0) {
Error ("Maximum Percent Selected %.1lf is Out of Range (1.0-100.0)", max_percent);
}
}
Print (1, "Maximum Percent Selected = %.1lf%%", max_percent);
max_percent /= 100.0;
//---- random number seed ----
str_ptr = Get_Control_String (RANDOM_NUMBER_SEED);
if (str_ptr != NULL) {
random.Seed (atoi (str_ptr));
}
if (str_ptr != NULL || percent != 1.0 || max_percent != 1.0) {
Print (1, "Random Number Seed = %d", random.Seed ());
}
return;
//---- error message ----
control_error:
Error ("Missing Control Key = %s", Current_Key ());
}
| 25.074766 | 85 | 0.631196 |
kravitz
|
25534e17aafff04a64555557f7a5161924630dc5
| 364 |
cpp
|
C++
|
925. Long Pressed Name.cpp
|
rajeev-ranjan-au6/Leetcode_Cpp
|
f64cd98ab96ec110f1c21393f418acf7d88473e8
|
[
"MIT"
] | 3 |
2020-12-30T00:29:59.000Z
|
2021-01-24T22:43:04.000Z
|
925. Long Pressed Name.cpp
|
rajeevranjancom/Leetcode_Cpp
|
f64cd98ab96ec110f1c21393f418acf7d88473e8
|
[
"MIT"
] | null | null | null |
925. Long Pressed Name.cpp
|
rajeevranjancom/Leetcode_Cpp
|
f64cd98ab96ec110f1c21393f418acf7d88473e8
|
[
"MIT"
] | null | null | null |
class Solution {
public:
bool isLongPressedName(string name, string typed) {
int a = 0, b = 0, n = name.size(), m = typed.size();
while (a < n && b < m) {
if (name[a++] != typed[b++]) return false;
while (b > 0 && name[a] != typed[b] && typed[b] == typed[b - 1]) ++b;
}
return a == n && b == m;
}
};
| 30.333333 | 81 | 0.445055 |
rajeev-ranjan-au6
|
2557b707320b1ac078aeb7a547c716231914c7a8
| 1,693 |
hpp
|
C++
|
include/PauseState.hpp
|
AgostonSzepessy/oxshans-battle
|
15d4cd5eb6375cca5e8e426fc9b8f70e74ca28b0
|
[
"MIT"
] | null | null | null |
include/PauseState.hpp
|
AgostonSzepessy/oxshans-battle
|
15d4cd5eb6375cca5e8e426fc9b8f70e74ca28b0
|
[
"MIT"
] | null | null | null |
include/PauseState.hpp
|
AgostonSzepessy/oxshans-battle
|
15d4cd5eb6375cca5e8e426fc9b8f70e74ca28b0
|
[
"MIT"
] | null | null | null |
#pragma once
#include <memory>
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include "GameState.hpp"
#include "PlayState.hpp"
#include "Background.hpp"
/**
* @brief The PauseState class This the pause menu.
* The user can decide to resume, restart or quit.
*/
class PauseState : public GameState
{
public:
/**
* @brief build Creates a new std::unique_ptr<PauseState>
* @param window The window to draw everything on
* @param gsm The GameStateManager that handles switching states
* @return an std::unique_ptr<PauseState>
*/
static std::unique_ptr<PauseState> build(sf::RenderWindow *window, GameStateManager *gsm);
~PauseState();
/**
* @brief update Calls handleInput(), and changes the text color if
* the user has an option selected.
*/
void update();
/**
* @brief draw Draws the background, text, and everything else that needs to
* be drawn on the screen.
*/
void draw();
/**
* @brief handleInput Handles all input from the user.
*/
void handleInput();
protected:
private:
PauseState(sf::RenderWindow *window, GameStateManager *gsm);
void setText();
void changeTextColor();
void select();
/**
* Used for checking whether the mouse coordinates are on the text
* when clicking.
*/
bool inBounds(int x, int y, int width, int height, int x2, int y2);
const int textSize = 20;
const int menuOptions = 3;
int currentChoice = 0;
const sf::Color textColor = sf::Color::Black;
const sf::Color selectedText = sf::Color::Blue;
sf::Font *font;
sf::Text *text; // text to store menu options
int x; // mouse coordinates
int y;
std::unique_ptr<Background> background;
};
| 25.651515 | 92 | 0.680449 |
AgostonSzepessy
|
255bea5fc8a3cb03a0e5a4d77e498ae23a4a307b
| 991 |
hpp
|
C++
|
scenes/inf585/06_skinning/src/animation.hpp
|
Lieunoir/inf585
|
41e8e52436f34d4a46425482ff953888bb8345bc
|
[
"MIT"
] | null | null | null |
scenes/inf585/06_skinning/src/animation.hpp
|
Lieunoir/inf585
|
41e8e52436f34d4a46425482ff953888bb8345bc
|
[
"MIT"
] | null | null | null |
scenes/inf585/06_skinning/src/animation.hpp
|
Lieunoir/inf585
|
41e8e52436f34d4a46425482ff953888bb8345bc
|
[
"MIT"
] | null | null | null |
#pragma once
#include "vcl/vcl.hpp"
#include "skeleton.hpp"
namespace vcl
{
enum Marine_Animations {
IDLE,
WALK,
RUN,
};
struct marine_animation_structure {
bool transition = false;
float transitionStart;
Marine_Animations current_animation = IDLE;
Marine_Animations next_animation = IDLE;
skeleton_animation_structure idle_animation;
skeleton_animation_structure walk_animation;
skeleton_animation_structure run_animation;
};
buffer<affine_rt> mix(buffer<affine_rt> const &source, skeleton_animation_structure const &target, float alpha);
buffer<affine_rt> to_global(buffer<affine_rt> const& local, buffer<int> const& parent_index);
buffer<affine_rt> transition(marine_animation_structure &marine_animation, skeleton_animation_structure &skeleton_data, timer_interval &timer);
void change_animation(marine_animation_structure &marine_animation, timer_interval &timer);
}
| 30.96875 | 147 | 0.739657 |
Lieunoir
|
255bf262ed7427659800ab1396debc802f912f41
| 1,018 |
cpp
|
C++
|
src/game_object.cpp
|
SYNTAXDZ/simpleOpenGLGame
|
14f50824e9f43b6c421676856aa33b0cce053554
|
[
"MIT"
] | null | null | null |
src/game_object.cpp
|
SYNTAXDZ/simpleOpenGLGame
|
14f50824e9f43b6c421676856aa33b0cce053554
|
[
"MIT"
] | null | null | null |
src/game_object.cpp
|
SYNTAXDZ/simpleOpenGLGame
|
14f50824e9f43b6c421676856aa33b0cce053554
|
[
"MIT"
] | null | null | null |
/*******************************************************************
** This code is part of Breakout.
**
** Breakout is free software: you can redistribute it and/or modify
** it under the terms of the CC BY 4.0 license as published by
** Creative Commons, either version 4 of the License, or (at your
** option) any later version.
******************************************************************/
#include "game_object.h"
GameObject::GameObject()
: Position( 0, 0 ), Size( 1, 1 ), Velocity( 0.0f ), Color( 1.0f ), Rotation( 0.0f ), Sprite(), IsSolid( false ), Destroyed( false ) { }
GameObject::GameObject( glm::vec2 pos, glm::vec2 size, Texture2D sprite, glm::vec3 color, glm::vec2 velocity )
: Position( pos ), Size( size ), Velocity( velocity ), Color( color ), Rotation( 0.0f ), Sprite( sprite ), IsSolid( false ), Destroyed( false ) { }
void GameObject::Draw( SpriteRenderer &renderer ) {
renderer.DrawSprite( this->Sprite, this->Position, this->Size, this->Rotation, this->Color );
}
| 44.26087 | 151 | 0.585462 |
SYNTAXDZ
|
2560385ae097cd937e78ffb7e9ff23b9d0e28a0c
| 4,638 |
cpp
|
C++
|
Source/managementD3D.cpp
|
L0mion/Makes-a-Click
|
c7f53a53ea3a58da027ea5f00176352edb914718
|
[
"MIT"
] | 1 |
2016-04-28T06:24:15.000Z
|
2016-04-28T06:24:15.000Z
|
Source/managementD3D.cpp
|
L0mion/Makes-a-Click
|
c7f53a53ea3a58da027ea5f00176352edb914718
|
[
"MIT"
] | null | null | null |
Source/managementD3D.cpp
|
L0mion/Makes-a-Click
|
c7f53a53ea3a58da027ea5f00176352edb914718
|
[
"MIT"
] | null | null | null |
#include "managementD3D.h"
#include "utility.h"
ManagementD3D::ManagementD3D()
{
swapChain_ = NULL;
device_ = NULL;
devcon_ = NULL;
uavBackBuffer_ = NULL;
rtvBackBuffer_ = NULL;
dsvDepthBuffer_ = NULL;
}
ManagementD3D::~ManagementD3D()
{
SAFE_RELEASE(swapChain_);
SAFE_RELEASE(device_);
SAFE_RELEASE(devcon_);
SAFE_RELEASE(uavBackBuffer_);
SAFE_RELEASE(rtvBackBuffer_);
SAFE_RELEASE(dsvDepthBuffer_);
}
void ManagementD3D::present()
{
if(swapChain_)
swapChain_->Present(0, 0);
}
void ManagementD3D::setFullscreen(bool fullscreen)
{
swapChain_->SetFullscreenState(fullscreen, NULL);
}
void ManagementD3D::setBackBuffer()
{
devcon_->OMSetRenderTargets(1, &rtvBackBuffer_, dsvDepthBuffer_);
}
void ManagementD3D::setBackBufferNoDepth()
{
devcon_->OMSetRenderTargets(1, &rtvBackBuffer_, NULL);
}
void ManagementD3D::clearBackBuffer()
{
FLOAT clearColor[4] = {0.0f, 0.0f, 0.0f, 0.0f};
devcon_->ClearRenderTargetView(rtvBackBuffer_, clearColor);
}
ID3D11Device* ManagementD3D::getDevice() const
{
return device_;
}
ID3D11DeviceContext* ManagementD3D::getDeviceContext() const
{
return devcon_;
}
ID3D11RenderTargetView* ManagementD3D::getRTVBackBuffer()
{
return rtvBackBuffer_;
}
ID3D11DepthStencilView* ManagementD3D::getDSVDepthBuffer()
{
return dsvDepthBuffer_;
}
HRESULT ManagementD3D::init(HWND windowHandle)
{
HRESULT hr = S_OK;
hr = initDeviceAndSwapChain(windowHandle);
if(SUCCEEDED(hr))
hr = initBackBuffer();
if(SUCCEEDED(hr))
hr = initDepthBuffer();
if(SUCCEEDED(hr))
initViewport();
return hr;
}
HRESULT ManagementD3D::initDeviceAndSwapChain(HWND windowHandle)
{
HRESULT hr = S_OK;
DXGI_SWAP_CHAIN_DESC scd;
ZeroMemory(&scd, sizeof(scd));
scd.BufferCount = 1;
scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
scd.BufferDesc.Width = SCREEN_WIDTH;
scd.BufferDesc.Height = SCREEN_HEIGHT;
scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
scd.OutputWindow = windowHandle;
scd.BufferDesc.RefreshRate.Numerator = 60;
scd.BufferDesc.RefreshRate.Denominator = 1;
scd.SampleDesc.Count = 1;
scd.SampleDesc.Quality = 0;
scd.Windowed = true;
scd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
UINT numFeatureLevels = 3;
D3D_FEATURE_LEVEL initiatedFeatureLevel;
D3D_FEATURE_LEVEL featureLevels[] = {D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0};
UINT numDriverTypes = 2;
D3D_DRIVER_TYPE driverTypes[] = {D3D_DRIVER_TYPE_HARDWARE,
D3D_DRIVER_TYPE_REFERENCE};
UINT createDeviceFlags = 0;
#if defined( DEBUG ) || defined( _DEBUG )
createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
unsigned int index = 0;
bool deviceCreated = false;
while(index < numDriverTypes && !deviceCreated)
{
hr = D3D11CreateDeviceAndSwapChain(NULL,
driverTypes[index],
NULL,
createDeviceFlags,
featureLevels,
numFeatureLevels,
D3D11_SDK_VERSION,
&scd,
&swapChain_,
&device_,
&initiatedFeatureLevel,
&devcon_);
if(SUCCEEDED(hr))
{
deviceCreated = true;
}
index++;
}
return hr;
}
HRESULT ManagementD3D::initBackBuffer()
{
HRESULT hr = S_OK;
ID3D11Texture2D* texBackBuffer;
swapChain_->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&texBackBuffer);
//hr = device_->CreateUnorderedAccessView(texBackBuffer, NULL, &uavBackBuffer_);
hr = device_->CreateRenderTargetView(texBackBuffer, NULL, &rtvBackBuffer_);
SAFE_RELEASE(texBackBuffer);
return hr;
}
HRESULT ManagementD3D::initDepthBuffer()
{
HRESULT hr = S_OK;
D3D11_TEXTURE2D_DESC texDesc;
ZeroMemory(&texDesc, sizeof(texDesc));
texDesc.Width = SCREEN_WIDTH;
texDesc.Height = SCREEN_HEIGHT;
texDesc.ArraySize = 1;
texDesc.MipLevels = 1;
texDesc.SampleDesc.Count = 1;
texDesc.Format = DXGI_FORMAT_D32_FLOAT;
texDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
ID3D11Texture2D *depthBuffer;
device_->CreateTexture2D(&texDesc, NULL, &depthBuffer);
D3D11_DEPTH_STENCIL_VIEW_DESC dsvd;
ZeroMemory(&dsvd, sizeof(dsvd));
dsvd.Format = DXGI_FORMAT_D32_FLOAT;
dsvd.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS;
hr = device_->CreateDepthStencilView(depthBuffer, &dsvd, &dsvDepthBuffer_);
SAFE_RELEASE(depthBuffer);
return hr;
}
void ManagementD3D::initViewport()
{
D3D11_VIEWPORT viewport;
ZeroMemory(&viewport, sizeof(viewport));
viewport.TopLeftX = 0;
viewport.TopLeftY = 0;
viewport.Width = SCREEN_WIDTH;
viewport.Height = SCREEN_HEIGHT;
viewport.MinDepth = 0;
viewport.MaxDepth = 1;
devcon_->RSSetViewports(1, &viewport);
}
| 24.15625 | 81 | 0.734368 |
L0mion
|
25632e571c62600c9572c258fa50ce252f18e186
| 3,034 |
cpp
|
C++
|
devmand/gateway/src/devmand/channels/cli/IoConfigurationBuilder.cpp
|
fannycchen/magma
|
b8ccc1c7437c555656988638482d3a8f458224e8
|
[
"BSD-3-Clause"
] | 1 |
2020-06-05T09:01:40.000Z
|
2020-06-05T09:01:40.000Z
|
devmand/gateway/src/devmand/channels/cli/IoConfigurationBuilder.cpp
|
phirmware/magma
|
1b3e4533235293f754d7375eb421c968cc0b1856
|
[
"BSD-3-Clause"
] | null | null | null |
devmand/gateway/src/devmand/channels/cli/IoConfigurationBuilder.cpp
|
phirmware/magma
|
1b3e4533235293f754d7375eb421c968cc0b1856
|
[
"BSD-3-Clause"
] | 1 |
2020-01-14T14:28:23.000Z
|
2020-01-14T14:28:23.000Z
|
// Copyright (c) 2019-present, Facebook, Inc.
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#define LOG_WITH_GLOG
#include <magma_logging.h>
#include <devmand/channels/cli/IoConfigurationBuilder.h>
#include <devmand/channels/cli/PromptAwareCli.h>
#include <devmand/channels/cli/QueuedCli.h>
#include <devmand/channels/cli/ReadCachingCli.h>
#include <devmand/channels/cli/SshSession.h>
#include <devmand/channels/cli/SshSessionAsync.h>
#include <devmand/channels/cli/SshSocketReader.h>
#include <folly/Singleton.h>
#include <folly/executors/IOThreadPoolExecutor.h>
namespace devmand {
namespace channels {
namespace cli {
using devmand::channels::cli::IoConfigurationBuilder;
using devmand::channels::cli::SshSocketReader;
using devmand::channels::cli::sshsession::readCallback;
using devmand::channels::cli::sshsession::SshSession;
using devmand::channels::cli::sshsession::SshSessionAsync;
using folly::EvictingCacheMap;
using folly::IOThreadPoolExecutor;
using std::make_shared;
using std::string;
// TODO executor?
shared_ptr<IOThreadPoolExecutor> executor =
std::make_shared<IOThreadPoolExecutor>(10);
IoConfigurationBuilder::IoConfigurationBuilder(
const DeviceConfig& _deviceConfig)
: deviceConfig(_deviceConfig) {}
shared_ptr<Cli> IoConfigurationBuilder::getIo(
shared_ptr<CliCache> commandCache) {
MLOG(MDEBUG) << "Creating CLI ssh device for " << deviceConfig.id
<< " (host: " << deviceConfig.ip << ")";
const auto& plaintextCliKv = deviceConfig.channelConfigs.at("cli").kvPairs;
// crate session
const std::shared_ptr<SshSessionAsync>& session =
std::make_shared<SshSessionAsync>(deviceConfig.id, executor);
// opening SSH connection
session
->openShell(
deviceConfig.ip,
std::stoi(plaintextCliKv.at("port")),
plaintextCliKv.at("username"),
plaintextCliKv.at("password"))
.get();
shared_ptr<CliFlavour> cl =
plaintextCliKv.find("flavour") != plaintextCliKv.end()
? CliFlavour::create(plaintextCliKv.at("flavour"))
: CliFlavour::create("");
// create CLI - how to create a CLI stack?
const shared_ptr<PromptAwareCli>& cli =
std::make_shared<PromptAwareCli>(session, cl);
// initialize CLI
cli->initializeCli();
// resolve prompt needs to happen
cli->resolvePrompt();
// create async data reader
event* sessionEvent = SshSocketReader::getInstance().addSshReader(
readCallback, session->getSshFd(), session.get());
session->setEvent(sessionEvent);
// create caching cli
const shared_ptr<ReadCachingCli>& ccli =
std::make_shared<ReadCachingCli>(deviceConfig.id, cli, commandCache);
// create Queued cli
return std::make_shared<QueuedCli>(deviceConfig.id, ccli, executor);
}
} // namespace cli
} // namespace channels
} // namespace devmand
| 33.711111 | 78 | 0.733355 |
fannycchen
|
2567794d604519aeeae1c19ebadc8bd1e57daf9e
| 2,842 |
hpp
|
C++
|
src/interface/stream.hpp
|
wuxun-zhang/mkl-dnn
|
00a239ad2c932b967234ffb528069800ffcc0334
|
[
"Apache-2.0"
] | null | null | null |
src/interface/stream.hpp
|
wuxun-zhang/mkl-dnn
|
00a239ad2c932b967234ffb528069800ffcc0334
|
[
"Apache-2.0"
] | null | null | null |
src/interface/stream.hpp
|
wuxun-zhang/mkl-dnn
|
00a239ad2c932b967234ffb528069800ffcc0334
|
[
"Apache-2.0"
] | null | null | null |
/*******************************************************************************
* Copyright 2020-2022 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef INTERFACE_STREAM_HPP
#define INTERFACE_STREAM_HPP
#include "c_types_map.hpp"
#ifdef DNNL_GRAPH_WITH_SYCL
#include <CL/sycl.hpp>
#endif
#if DNNL_GRAPH_CPU_RUNTIME == DNNL_GRAPH_RUNTIME_THREADPOOL
#include "oneapi/dnnl/dnnl_graph_threadpool_iface.hpp"
#endif
struct dnnl_graph_stream {
public:
dnnl_graph_stream() = delete;
dnnl_graph_stream(const dnnl::graph::impl::engine_t *engine)
: engine_ {engine} {}
#ifdef DNNL_GRAPH_WITH_SYCL
// Create an stream from SYCL queue.
dnnl_graph_stream(const dnnl::graph::impl::engine_t *engine,
const cl::sycl::queue &queue)
: engine_ {engine}, queue_ {queue} {}
#endif // DNNL_GRAPH_WITH_SYCL
#if DNNL_GRAPH_CPU_RUNTIME == DNNL_GRAPH_RUNTIME_THREADPOOL
dnnl_graph_stream(const dnnl::graph::impl::engine_t *engine,
dnnl::graph::threadpool_interop::threadpool_iface *threadpool)
: dnnl_graph_stream(engine) {
assert(engine->kind() == dnnl::graph::impl::engine_kind::cpu);
threadpool_ = threadpool;
}
dnnl::graph::impl::status_t get_threadpool(
dnnl::graph::threadpool_interop::threadpool_iface **threadpool)
const {
if (engine_->kind() != dnnl::graph::impl::engine_kind::cpu)
return dnnl::graph::impl::status::invalid_arguments;
*threadpool = threadpool_;
return dnnl::graph::impl::status::success;
}
#endif
~dnnl_graph_stream() = default;
const dnnl::graph::impl::engine_t *get_engine() const noexcept {
return engine_;
}
#ifdef DNNL_GRAPH_WITH_SYCL
const cl::sycl::queue &get_queue() const noexcept { return queue_; }
#endif
dnnl::graph::impl::status_t wait() {
#ifdef DNNL_GRAPH_WITH_SYCL
queue_.wait();
#endif
return dnnl::graph::impl::status::success;
}
private:
const dnnl::graph::impl::engine_t *engine_;
#ifdef DNNL_GRAPH_WITH_SYCL
cl::sycl::queue queue_;
#endif
#if DNNL_GRAPH_CPU_RUNTIME == DNNL_GRAPH_RUNTIME_THREADPOOL
dnnl::graph::threadpool_interop::threadpool_iface *threadpool_ = nullptr;
#endif
};
#endif
| 32.295455 | 80 | 0.671006 |
wuxun-zhang
|
256a9728d866c93330b0cb16e2912deb5aff872d
| 770 |
cpp
|
C++
|
examples/Example4/EventListener.cpp
|
hasaranga/RFC-Framework
|
9c1881d412db6f9f7670b910a0918a631208cfd1
|
[
"MIT"
] | 9 |
2017-10-02T08:15:50.000Z
|
2021-08-09T21:29:46.000Z
|
examples/Example4/EventListener.cpp
|
hasaranga/RFC-Framework
|
9c1881d412db6f9f7670b910a0918a631208cfd1
|
[
"MIT"
] | 1 |
2021-09-18T07:38:53.000Z
|
2021-09-26T12:11:48.000Z
|
examples/Example4/EventListener.cpp
|
hasaranga/RFC-Framework
|
9c1881d412db6f9f7670b910a0918a631208cfd1
|
[
"MIT"
] | 8 |
2017-10-02T13:21:29.000Z
|
2021-07-30T09:35:31.000Z
|
#include "../../amalgamated/rfc_amalgamated.h"
class MyWindow : public KFrame, public KButtonListener
{
protected:
KButton btn1;
public:
MyWindow()
{
this->SetText(L"My Window");
this->Create();
btn1.SetPosition(10, 10);
btn1.SetText(L"My Button");
btn1.SetListener(this); // set MyWindow class as button listener
this->AddComponent(&btn1);
}
void OnButtonPress(KButton *button)
{
if (button == &btn1)
{
::MessageBoxW(this->GetHWND(), L"Button pressed!", L"Info", MB_ICONINFORMATION);
}
}
};
class MyApplication : public KApplication
{
public:
int Main(KString **argv, int argc)
{
MyWindow window;
window.CenterScreen();
window.SetVisible(true);
::DoMessagePump();
return 0;
}
};
START_RFC_APPLICATION(MyApplication);
| 16.041667 | 83 | 0.685714 |
hasaranga
|
256b27c22efe1506adcc2def5f60ca936113eb87
| 3,494 |
cpp
|
C++
|
sources/core/ecs/private/system_manager.cpp
|
suVrik/hooker.galore
|
616e2692d7afab24b70bfb6aa14ad780eb7c451d
|
[
"MIT"
] | 4 |
2019-09-14T09:18:47.000Z
|
2022-01-29T02:47:00.000Z
|
sources/core/ecs/private/system_manager.cpp
|
suVrik/hooker.galore
|
616e2692d7afab24b70bfb6aa14ad780eb7c451d
|
[
"MIT"
] | null | null | null |
sources/core/ecs/private/system_manager.cpp
|
suVrik/hooker.galore
|
616e2692d7afab24b70bfb6aa14ad780eb7c451d
|
[
"MIT"
] | 1 |
2020-03-25T14:41:17.000Z
|
2020-03-25T14:41:17.000Z
|
#include "core/ecs/system_manager.h"
#include "core/ecs/tags.h"
#include <entt/core/hashed_string.hpp>
#include <entt/meta/factory.hpp>
#include <algorithm>
namespace hg {
std::vector<SystemManager::SystemDescriptor> SystemManager::m_systems[2];
void SystemManager::commit() {
size_t current_tag_index = 0;
for (std::vector<SystemDescriptor>& systems : m_systems) {
std::unordered_map<std::string, size_t> system_mapping;
std::sort(systems.begin(), systems.end(), [](const SystemDescriptor& lhs, const SystemDescriptor& rhs) {
return lhs.name < rhs.name;
});
for (size_t i = 0; i < systems.size(); i++) {
SystemDescriptor& system_descriptor = systems[i];
entt::meta_prop tags_property = system_descriptor.system_type.prop("tags"_hs);
if (tags_property) {
entt::meta_any tags_property_value = tags_property.value();
assert(tags_property_value);
assert(tags_property_value.type() == entt::resolve<std::shared_ptr<TagWrapper>>());
const auto& tags_expression = tags_property_value.fast_cast<std::shared_ptr<TagWrapper>>();
system_descriptor.tag_expression = tags_expression.get();
}
assert(!system_descriptor.name.empty());
assert(system_mapping.count(system_descriptor.name) == 0);
system_mapping.emplace(system_descriptor.name, i);
}
for (size_t i = 0; i < systems.size(); i++) {
SystemDescriptor& system_descriptor = systems[i];
entt::meta_prop before_property = system_descriptor.system_type.prop("before"_hs);
if (before_property) {
entt::meta_any before_property_value = before_property.value();
assert(before_property_value);
assert(before_property_value.type() == entt::resolve<std::vector<const char*>>());
const auto& systems_before = before_property_value.fast_cast<std::vector<const char*>>();
for (const char* system_name : systems_before) {
assert(system_mapping.count(system_name) == 1);
systems[system_mapping[system_name]].after.push_back(i);
}
}
entt::meta_prop after_property = system_descriptor.system_type.prop("after"_hs);
if (after_property) {
entt::meta_any after_property_value = after_property.value();
assert(after_property_value);
assert(after_property_value.type() == entt::resolve<std::vector<const char*>>());
const auto& systems_after = after_property_value.fast_cast<std::vector<const char*>>();
for (const char* system_name : systems_after) {
assert(system_mapping.count(system_name) == 1);
system_descriptor.after.push_back(system_mapping[system_name]);
}
}
}
for (size_t i = 0; i < systems.size(); i++) {
SystemDescriptor& system_descriptor = systems[i];
std::vector<size_t>& after = system_descriptor.after;
std::sort(after.begin(), after.end());
after.erase(std::unique(after.begin(), after.end()), after.end());
#ifndef NDEBUG
for (size_t preceding_system : after) {
assert(i != preceding_system);
}
#endif
}
}
}
} // namespace hg
| 38.395604 | 112 | 0.604179 |
suVrik
|
257000e1ece5778c65cb48266b94130794cd584c
| 4,910 |
cpp
|
C++
|
test/coco/combix/error_test.cpp
|
agatan/coco
|
e19e74cf97d788b435351379296ea3ead901c576
|
[
"BSL-1.0"
] | 1 |
2016-08-31T04:44:17.000Z
|
2016-08-31T04:44:17.000Z
|
test/coco/combix/error_test.cpp
|
agatan/coco
|
e19e74cf97d788b435351379296ea3ead901c576
|
[
"BSL-1.0"
] | null | null | null |
test/coco/combix/error_test.cpp
|
agatan/coco
|
e19e74cf97d788b435351379296ea3ead901c576
|
[
"BSL-1.0"
] | null | null | null |
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE expected
#include <coco/combix/combinators.hpp>
#include <coco/combix/iterator_stream.hpp>
#include <coco/combix/primitives.hpp>
#include <coco/combix/chars.hpp>
#include <coco/combix/parser.hpp>
#include <coco/combix/lazy_fun.hpp>
#include <boost/test/unit_test.hpp>
#include <string>
namespace cbx = coco::combix;
using stream_type = cbx::iterator_stream<std::string::const_iterator>;
cbx::parser<std::string, stream_type> reserved() {
return cbx::choice(cbx::string("val"), cbx::string("true"),
cbx::string("false"), cbx::string("def"),
cbx::string("return"));
}
cbx::parser<std::string, stream_type> varname() {
auto lead = cbx::choice(cbx::alpha(), cbx::token('_'));
auto tail = cbx::map(
cbx::many(cbx::choice(cbx::alpha(), cbx::digit(), cbx::token('_'))),
[](auto&& cs) { return std::string(cs.begin(), cs.end()); });
auto const var = cbx::map(cbx::seq(lead, tail), [](auto&& s) {
return std::get<0>(std::forward<decltype(s)>(s)) +
std::get<1>(std::forward<decltype(s)>(s));
});
return cbx::expected(
cbx::map(cbx::seq(cbx::not_followed_by(reserved()), var),
[](auto&& t) { return std::get<1>(std::move(t)); }),
"identifier");
}
BOOST_AUTO_TEST_SUITE(combix)
BOOST_AUTO_TEST_SUITE(combinators)
BOOST_AUTO_TEST_CASE(parens) {
auto const src = std::string("()");
auto s = coco::combix::range_stream(src);
auto const p = cbx::choice(
cbx::alpha(), cbx::map(cbx::digit(), [](auto) { return '!'; }));
auto res = parse(p, s);
BOOST_TEST(res.is_error());
std::stringstream ss;
ss << res.unwrap_error();
BOOST_TEST(ss.str() == "Unexpected \"(\"\nExpected alphabet, digit\n");
}
BOOST_AUTO_TEST_CASE(seq) {
auto const src = std::string{"a1c"};
auto s = cbx::range_stream(src);
auto const p = cbx::seq(cbx::alpha(), cbx::digit(), cbx::digit());
auto res = parse(p, s);
BOOST_TEST(res.is_error());
std::stringstream ss;
ss << res.unwrap_error();
BOOST_TEST(ss.str() == "Unexpected \"c\"\nExpected digit\n");
}
BOOST_AUTO_TEST_CASE(expected) {
auto const src = std::string{"1"};
auto s = cbx::range_stream(src);
auto const p = cbx::expected(cbx::alpha(), "letter");
auto res = parse(p, s);
BOOST_TEST(res.is_error());
std::stringstream ss;
ss << res.unwrap_error();
BOOST_TEST(ss.str() == "Unexpected \"1\"\nExpected letter\n");
}
BOOST_AUTO_TEST_CASE(consumed) {
auto const src = std::string{"1b2"};
auto s = cbx::range_stream(src);
auto const p = cbx::seq(cbx::digit(), cbx::digit(), cbx::digit());
auto res = cbx::parse(p, s);
BOOST_TEST(res.is_error());
BOOST_TEST(res.unwrap_error().consumed());
BOOST_TEST(std::string(s.begin(), s.end()) == "b2");
auto const manyp = cbx::many(p);
s = cbx::range_stream(src);
auto res2 = cbx::parse(manyp, s);
BOOST_TEST(res2.is_error());
BOOST_TEST(res2.unwrap_error().consumed());
BOOST_TEST(std::string(s.begin(), s.end()) == "b2");
}
BOOST_AUTO_TEST_CASE(between_consumed) {
auto const p = cbx::between(cbx::token('('), cbx::token(')'), cbx::digit());
auto const src = std::string{"(1"};
auto s = cbx::range_stream(src);
auto res = cbx::parse(p, s);
BOOST_TEST(res.is_error());
BOOST_TEST(res.unwrap_error().consumed());
BOOST_TEST(std::string(s.begin(), s.end()) == "");
}
BOOST_AUTO_TEST_CASE(not_followed_by) {
auto const inner = cbx::skip_seq(cbx::spaces())(varname(), cbx::token(':'));
auto const p = cbx::sep_by(inner, cbx::skip(cbx::token(','), cbx::spaces()));
{
auto const src = std::string{"hoge:"};
auto s = cbx::range_stream(src);
auto res = cbx::parse(p, s);
BOOST_TEST(res.is_ok());
}
{
auto const src = std::string{"hoge"};
auto s = cbx::range_stream(src);
auto res = cbx::parse(p, s);
BOOST_TEST(res.is_error());
BOOST_TEST(res.unwrap_error().consumed());
}
{
auto const src = std::string{""};
auto s = cbx::range_stream(src);
auto res = cbx::parse(p, s);
BOOST_TEST(res.is_ok());
}
}
BOOST_AUTO_TEST_CASE(sep_by) {
auto const inner = cbx::skip_seq(cbx::spaces())(
cbx::digit(), cbx::token(':'), cbx::alpha());
auto const sep = cbx::sep_by(inner, cbx::token(','));
{
auto const src = std::string{"1:a,2:b"};
auto s = cbx::range_stream(src);
BOOST_TEST(parse(sep, s).is_ok());
}
{
auto const src = std::string{"1:a"};
auto s = cbx::range_stream(src);
BOOST_TEST(parse(sep, s).is_ok());
}
{
auto const src = std::string{""};
auto s = cbx::range_stream(src);
BOOST_TEST(parse(sep, s).is_ok());
}
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
| 30.496894 | 81 | 0.599593 |
agatan
|
25777280a133b64c960a2a9dd33c507a8b372261
| 6,727 |
cc
|
C++
|
src/frameset.cc
|
alexeden/realsense-node
|
a4060c8fdcc091d933fb4c895f04e72f44328e63
|
[
"MIT"
] | null | null | null |
src/frameset.cc
|
alexeden/realsense-node
|
a4060c8fdcc091d933fb4c895f04e72f44328e63
|
[
"MIT"
] | 6 |
2021-01-28T20:31:27.000Z
|
2022-03-25T18:59:04.000Z
|
src/frameset.cc
|
alexeden/realsense-node
|
a4060c8fdcc091d933fb4c895f04e72f44328e63
|
[
"MIT"
] | null | null | null |
#ifndef FRAMESET_H
#define FRAMESET_H
#include "frame.cc"
#include "stream_profile_extractor.cc"
#include "utils.cc"
#include <iostream>
#include <librealsense2/hpp/rs_types.hpp>
#include <napi.h>
using namespace Napi;
class RSFrameSet : public ObjectWrap<RSFrameSet> {
public:
static Object Init(Napi::Env env, Object exports) {
Napi::Function func = DefineClass(
env,
"RSFrameSet",
{
InstanceMethod("destroy", &RSFrameSet::Destroy),
InstanceMethod("getFrame", &RSFrameSet::GetFrame),
InstanceMethod("getSize", &RSFrameSet::GetSize),
InstanceMethod("indexToStream", &RSFrameSet::IndexToStream),
InstanceMethod("indexToStreamIndex", &RSFrameSet::IndexToStreamIndex),
InstanceMethod("replaceFrame", &RSFrameSet::ReplaceFrame),
});
constructor = Napi::Persistent(func);
constructor.SuppressDestruct();
exports.Set("RSFrameSet", func);
return exports;
}
static Object NewInstance(Napi::Env env, rs2_frame* frame) {
EscapableHandleScope scope(env);
Object instance = constructor.New({});
auto unwrapped = ObjectWrap<RSFrameSet>::Unwrap(instance);
unwrapped->SetFrame(frame);
return scope.Escape(napi_value(instance)).ToObject();
}
rs2_frame* GetFrames() {
return frames_;
}
void Replace(rs2_frame* frame) {
DestroyMe();
SetFrame(frame);
}
RSFrameSet(const CallbackInfo& info)
: ObjectWrap<RSFrameSet>(info) {
error_ = nullptr;
frames_ = nullptr;
}
~RSFrameSet() {
DestroyMe();
}
private:
static FunctionReference constructor;
rs2_frame* frames_;
uint32_t frame_count_;
rs2_error* error_;
void SetFrame(rs2_frame* frame) {
if (
!frame
|| (!GetNativeResult<
int>(rs2_is_frame_extendable_to, &error_, frame, RS2_EXTENSION_COMPOSITE_FRAME, &error_)))
return;
frames_ = frame;
frame_count_ = GetNativeResult<int>(rs2_embedded_frames_count, &error_, frame, &error_);
}
void DestroyMe() {
if (error_) rs2_free_error(error_);
error_ = nullptr;
if (frames_) rs2_release_frame(frames_);
frames_ = nullptr;
}
Napi::Value Destroy(const CallbackInfo& info) {
// auto unwrapped = ObjectWrap<RSFrameSet>::Unwrap(info[0].As<Object>());
// if (unwrapped) { unwrapped->DestroyMe(); }
this->DestroyMe();
return info.This();
}
Napi::Value GetFrame(const CallbackInfo& info) {
if (!this->frames_) return info.Env().Undefined();
rs2_stream stream = static_cast<rs2_stream>(info[0].ToNumber().Int32Value());
auto stream_index = info[1].ToNumber().Int32Value();
// if RS2_STREAM_ANY is used, we return the first frame.
if (stream == RS2_STREAM_ANY && this->frame_count_) {
rs2_frame* frame
= GetNativeResult<rs2_frame*>(rs2_extract_frame, &this->error_, this->frames_, 0, &this->error_);
if (!frame) return info.Env().Undefined();
return RSFrame::NewInstance(info.Env(), frame);
}
for (uint32_t i = 0; i < this->frame_count_; i++) {
rs2_frame* frame
= GetNativeResult<rs2_frame*>(rs2_extract_frame, &this->error_, this->frames_, i, &this->error_);
if (!frame) continue;
const rs2_stream_profile* profile = GetNativeResult<
const rs2_stream_profile*>(rs2_get_frame_stream_profile, &this->error_, frame, &this->error_);
if (profile) {
StreamProfileExtractor extrator(profile);
if (
extrator.stream_ == stream && (!stream_index || (stream_index && stream_index == extrator.index_))) {
return RSFrame::NewInstance(info.Env(), frame);
}
}
rs2_release_frame(frame);
}
return info.Env().Undefined();
}
Napi::Value GetSize(const CallbackInfo& info) {
if (this->frames_) { return Number::New(info.Env(), this->frame_count_); }
return Number::New(info.Env(), 0);
}
Napi::Value IndexToStream(const CallbackInfo& info) {
if (!this->frames_) return info.Env().Undefined();
int32_t index = info[0].ToNumber().Int32Value();
rs2_frame* frame
= GetNativeResult<rs2_frame*>(rs2_extract_frame, &this->error_, this->frames_, index, &this->error_);
if (!frame) return info.Env().Undefined();
const rs2_stream_profile* profile = GetNativeResult<
const rs2_stream_profile*>(rs2_get_frame_stream_profile, &this->error_, frame, &this->error_);
if (!profile) {
rs2_release_frame(frame);
return info.Env().Undefined();
}
rs2_stream stream = RS2_STREAM_ANY;
rs2_format format = RS2_FORMAT_ANY;
int32_t fps = 0;
int32_t idx = 0;
int32_t unique_id = 0;
CallNativeFunc(
rs2_get_stream_profile_data, &this->error_, profile, &stream, &format, &idx, &unique_id, &fps, &this->error_);
rs2_release_frame(frame);
if (this->error_) return info.Env().Undefined();
return Number::New(info.Env(), stream);
}
Napi::Value IndexToStreamIndex(const CallbackInfo& info) {
if (!this->frames_) return info.Env().Undefined();
int32_t index = info[0].ToNumber().Int32Value();
rs2_frame* frame
= GetNativeResult<rs2_frame*>(rs2_extract_frame, &this->error_, this->frames_, index, &this->error_);
if (!frame) return info.Env().Undefined();
const rs2_stream_profile* profile = GetNativeResult<
const rs2_stream_profile*>(rs2_get_frame_stream_profile, &this->error_, frame, &this->error_);
if (!profile) {
rs2_release_frame(frame);
return info.Env().Undefined();
}
rs2_stream stream = RS2_STREAM_ANY;
rs2_format format = RS2_FORMAT_ANY;
int32_t fps = 0;
int32_t idx = 0;
int32_t unique_id = 0;
CallNativeFunc(
rs2_get_stream_profile_data, &this->error_, profile, &stream, &format, &idx, &unique_id, &fps, &this->error_);
rs2_release_frame(frame);
if (this->error_) return info.Env().Undefined();
return Number::New(info.Env(), idx);
}
Napi::Value ReplaceFrame(const CallbackInfo& info) {
rs2_stream stream = static_cast<rs2_stream>(info[0].ToNumber().Int32Value());
auto stream_index = info[1].ToNumber().Int32Value();
auto target_frame = ObjectWrap<RSFrame>::Unwrap(info[2].ToObject());
if (!this->frames_) return Boolean::New(info.Env(), false);
for (uint32_t i = 0; i < this->frame_count_; i++) {
rs2_frame* frame
= GetNativeResult<rs2_frame*>(rs2_extract_frame, &this->error_, this->frames_, i, &this->error_);
if (!frame) continue;
const rs2_stream_profile* profile = GetNativeResult<
const rs2_stream_profile*>(rs2_get_frame_stream_profile, &this->error_, frame, &this->error_);
if (profile) {
StreamProfileExtractor extrator(profile);
if (
extrator.stream_ == stream && (!stream_index || (stream_index && stream_index == extrator.index_))) {
target_frame->Replace(frame);
return Boolean::New(info.Env(), true);
}
}
rs2_release_frame(frame);
}
return Boolean::New(info.Env(), false);
}
};
Napi::FunctionReference RSFrameSet::constructor;
#endif
| 30.716895 | 114 | 0.699569 |
alexeden
|
257ab07332ad18085d7c029ff8e302892107b215
| 7,730 |
cpp
|
C++
|
liblineside/test/boparraymashdatatests.cpp
|
freesurfer-rge/linesidecabinet
|
8944c67fa7d340aa792e3a6e681113a4676bfbad
|
[
"MIT"
] | null | null | null |
liblineside/test/boparraymashdatatests.cpp
|
freesurfer-rge/linesidecabinet
|
8944c67fa7d340aa792e3a6e681113a4676bfbad
|
[
"MIT"
] | 14 |
2019-11-17T14:46:25.000Z
|
2021-03-10T02:48:40.000Z
|
liblineside/test/boparraymashdatatests.cpp
|
freesurfer-rge/linesidecabinet
|
8944c67fa7d340aa792e3a6e681113a4676bfbad
|
[
"MIT"
] | null | null | null |
#include <boost/test/unit_test.hpp>
#include "lineside/boparraymashdata.hpp"
#include "lineside/boparraymash.hpp"
#include "lineside/linesideexceptions.hpp"
#include "exceptionmessagecheck.hpp"
#include "mockmanagerfixture.hpp"
BOOST_AUTO_TEST_SUITE(BOPArrayMASHData)
// ---------------
BOOST_AUTO_TEST_SUITE(ExtractAspects)
BOOST_AUTO_TEST_CASE(TwoAspect)
{
Lineside::BOPArrayMASHData mashd;
mashd.id = 16;
mashd.settings["Green"] = "0";
mashd.settings["Red"] = "1";
mashd.settings["Feather1"] = "2";
auto result = mashd.ExtractAspects();
BOOST_REQUIRE_EQUAL( result.size(), 2 );
BOOST_CHECK_EQUAL( result.at(Lineside::SignalAspect::Red), 1 );
BOOST_CHECK_EQUAL( result.at(Lineside::SignalAspect::Green), 0 );
}
BOOST_AUTO_TEST_CASE(ThreeAspect)
{
Lineside::BOPArrayMASHData mashd;
mashd.id = 19;
mashd.settings["Green"] = "0";
mashd.settings["Yellow1"] = "3";
mashd.settings["Red"] = "1";
mashd.settings["Feather1"] = "2";
auto result = mashd.ExtractAspects();
BOOST_REQUIRE_EQUAL( result.size(), 3 );
BOOST_CHECK_EQUAL( result.at(Lineside::SignalAspect::Red), 1 );
BOOST_CHECK_EQUAL( result.at(Lineside::SignalAspect::Green), 0 );
BOOST_CHECK_EQUAL( result.at(Lineside::SignalAspect::Yellow1), 3 );
}
BOOST_AUTO_TEST_CASE(FourAspect)
{
Lineside::BOPArrayMASHData mashd;
mashd.id = 19;
mashd.settings["Green"] = "4";
mashd.settings["Yellow1"] = "3";
mashd.settings["Yellow2"] = "2";
mashd.settings["Red"] = "1";
mashd.settings["Feather1"] = "0";
auto result = mashd.ExtractAspects();
BOOST_REQUIRE_EQUAL( result.size(), 4 );
BOOST_CHECK_EQUAL( result.at(Lineside::SignalAspect::Red), 1);
BOOST_CHECK_EQUAL( result.at(Lineside::SignalAspect::Green), 4 );
BOOST_CHECK_EQUAL( result.at(Lineside::SignalAspect::Yellow1), 3 );
BOOST_CHECK_EQUAL( result.at(Lineside::SignalAspect::Yellow2), 2 );
}
BOOST_AUTO_TEST_CASE(NoRedAspect)
{
Lineside::BOPArrayMASHData mashd;
mashd.id = 16;
mashd.settings["Green"] = "0";
std::string msg = "Configuration problem for 00:00:00:10 - Red aspect missing";
BOOST_CHECK_EXCEPTION( mashd.ExtractAspects(),
Lineside::BadPWItemDataException,
GetExceptionMessageChecker<Lineside::BadPWItemDataException>(msg) );
}
BOOST_AUTO_TEST_CASE(NoGreenAspect)
{
Lineside::BOPArrayMASHData mashd;
mashd.id = 17;
mashd.settings["Red"] = "0";
std::string msg = "Configuration problem for 00:00:00:11 - Green aspect missing";
BOOST_CHECK_EXCEPTION( mashd.ExtractAspects(),
Lineside::BadPWItemDataException,
GetExceptionMessageChecker<Lineside::BadPWItemDataException>(msg) );
}
BOOST_AUTO_TEST_CASE(Yellow2AspectButNoYellow1)
{
Lineside::BOPArrayMASHData mashd;
mashd.id = 35;
mashd.settings["Red"] = "0";
mashd.settings["Green"] = "2";
mashd.settings["Yellow2"] = "1";
std::string msg = "Configuration problem for 00:00:00:23 - Have Yellow2 aspect but no Yellow1";
BOOST_CHECK_EXCEPTION( mashd.ExtractAspects(),
Lineside::BadPWItemDataException,
GetExceptionMessageChecker<Lineside::BadPWItemDataException>(msg) );
}
BOOST_AUTO_TEST_SUITE_END()
// ---------------
BOOST_AUTO_TEST_SUITE(ExtractFeathers)
BOOST_AUTO_TEST_CASE(NoFeathers)
{
Lineside::BOPArrayMASHData mashd;
mashd.id = 255;
mashd.settings["Red"] = "0";
mashd.settings["Green"] = "2";
auto result = mashd.ExtractFeathers();
BOOST_CHECK_EQUAL( result.size(), 1 );
}
BOOST_AUTO_TEST_CASE(OneFeather)
{
Lineside::BOPArrayMASHData mashd;
mashd.id = 255;
mashd.settings["Red"] = "0";
mashd.settings["Green"] = "1";
mashd.settings["Feather1"] = "2";
auto result = mashd.ExtractFeathers();
BOOST_REQUIRE_EQUAL( result.size(), 2 );
BOOST_CHECK_EQUAL( result.at(1), 2 );
}
BOOST_AUTO_TEST_CASE(TwoFeathers)
{
Lineside::BOPArrayMASHData mashd;
mashd.id = 255;
mashd.settings["Red"] = "2";
mashd.settings["Green"] = "1";
mashd.settings["Feather1"] = "0";
mashd.settings["Feather2"] = "3";
auto result = mashd.ExtractFeathers();
BOOST_REQUIRE_EQUAL( result.size(), 3 );
BOOST_CHECK_EQUAL( result.at(1), 0 );
BOOST_CHECK_EQUAL( result.at(2), 3 );
}
BOOST_AUTO_TEST_CASE(FeathersZeroDefined)
{
Lineside::BOPArrayMASHData mashd;
mashd.id = 255;
mashd.settings["Red"] = "0";
mashd.settings["Green"] = "2";
mashd.settings["Feather0"] = "1";
std::string msg = "Configuration problem for 00:00:00:ff - Feather '0' defined";
BOOST_CHECK_EXCEPTION( mashd.ExtractFeathers(),
Lineside::BadPWItemDataException,
GetExceptionMessageChecker<Lineside::BadPWItemDataException>( msg ) );
}
BOOST_AUTO_TEST_CASE(FeathersNonSequential)
{
Lineside::BOPArrayMASHData mashd;
mashd.id = 255;
mashd.settings["Red"] = "2";
mashd.settings["Green"] = "1";
mashd.settings["Feather2"] = "0";
std::string msg = "Configuration problem for 00:00:00:ff - Feathers are not sequential from one";
BOOST_CHECK_EXCEPTION( mashd.ExtractFeathers(),
Lineside::BadPWItemDataException,
GetExceptionMessageChecker<Lineside::BadPWItemDataException>( msg ) );
}
BOOST_AUTO_TEST_SUITE_END()
// ---------------
BOOST_FIXTURE_TEST_SUITE(Construct, MockManagerFixture)
BOOST_AUTO_TEST_CASE(Smoke)
{
Lineside::BOPArrayMASHData mashd;
mashd.id = 255;
mashd.settings["Red"] = "2";
mashd.settings["Green"] = "1";
mashd.settings["Feather1"] = "0";
mashd.bopArrayRequest.providerName = "MockBOPArray";
mashd.bopArrayRequest.settings["0"] = "18";
mashd.bopArrayRequest.settings["1"] = "19";
mashd.bopArrayRequest.settings["2"] = "26";
auto result = mashd.Construct(*(this->hwManager), *(this->swManager));
BOOST_REQUIRE(result);
auto bopArrayMash = std::dynamic_pointer_cast<Lineside::BOPArrayMASH>(result);
BOOST_CHECK( bopArrayMash );
}
BOOST_AUTO_TEST_CASE(AspectFeatherBOPArraySizeMismatch)
{
Lineside::BOPArrayMASHData mashd;
mashd.id = 255;
mashd.settings["Red"] = "2";
mashd.settings["Green"] = "1";
mashd.settings["Feather1"] = "0";
mashd.bopArrayRequest.settings["0"] = "18";
mashd.bopArrayRequest.settings["1"] = "19";
std::string msg = "Configuration problem for 00:00:00:ff - Number of feathers and aspects does not match BOPArray size";
BOOST_CHECK_EXCEPTION( mashd.Construct(*(this->hwManager), *(this->swManager)),
Lineside::BadPWItemDataException,
GetExceptionMessageChecker<Lineside::BadPWItemDataException>(msg) );
}
BOOST_AUTO_TEST_CASE(DuplicatePinRequest)
{
Lineside::BOPArrayMASHData mashd;
mashd.id = 255;
mashd.settings["Red"] = "2";
mashd.settings["Green"] = "1";
mashd.settings["Feather1"] = "1";
mashd.bopArrayRequest.settings["0"] = "18";
mashd.bopArrayRequest.settings["1"] = "19";
mashd.bopArrayRequest.settings["2"] = "26";
std::string msg = "Configuration problem for 00:00:00:ff - At least one pin in BOPArray requested twice";
BOOST_CHECK_EXCEPTION( mashd.Construct(*(this->hwManager), *(this->swManager)),
Lineside::BadPWItemDataException,
GetExceptionMessageChecker<Lineside::BadPWItemDataException>(msg) );
}
BOOST_AUTO_TEST_CASE(PinsNotSequential)
{
Lineside::BOPArrayMASHData mashd;
mashd.id = 255;
mashd.settings["Red"] = "2";
mashd.settings["Green"] = "3";
mashd.settings["Feather1"] = "0";
mashd.bopArrayRequest.settings["0"] = "18";
mashd.bopArrayRequest.settings["1"] = "19";
mashd.bopArrayRequest.settings["2"] = "26";
std::string msg = "Configuration problem for 00:00:00:ff - BOPArray pin requests not sequential from zero";
BOOST_CHECK_EXCEPTION( mashd.Construct(*(this->hwManager), *(this->swManager)),
Lineside::BadPWItemDataException,
GetExceptionMessageChecker<Lineside::BadPWItemDataException>(msg) );
}
BOOST_AUTO_TEST_SUITE_END()
// ---------------
BOOST_AUTO_TEST_SUITE_END()
| 28.419118 | 122 | 0.713454 |
freesurfer-rge
|
257ea34d17379a52fafdae8621743f031af0493d
| 148 |
cpp
|
C++
|
src/Window.cpp
|
HadesD/vim-power-mode
|
b3d701545fec08c329d54441d22e8f9b92ebb4cf
|
[
"MIT"
] | 8 |
2018-07-01T12:18:42.000Z
|
2022-01-30T01:59:31.000Z
|
src/Window.cpp
|
HadesD/vim-power-mode
|
b3d701545fec08c329d54441d22e8f9b92ebb4cf
|
[
"MIT"
] | 1 |
2018-07-01T16:50:47.000Z
|
2018-07-02T13:15:39.000Z
|
src/Window.cpp
|
HadesD/vim-power-mode
|
b3d701545fec08c329d54441d22e8f9b92ebb4cf
|
[
"MIT"
] | null | null | null |
#include "vpm/Window.hpp"
namespace VPM
{
bool Window::m_isClosed = false;
bool Window::getIsClosed() const
{
return m_isClosed;
}
}
| 11.384615 | 34 | 0.662162 |
HadesD
|
258579fc67f3a1ba684e9e943e1a4d05970da572
| 1,480 |
cpp
|
C++
|
dlls/ulkata.cpp
|
Laluka256/halflife-planckepoch
|
3ccfd783213c3ee88b9ed8204acdce01d40d5420
|
[
"Unlicense"
] | 1 |
2021-12-16T19:29:18.000Z
|
2021-12-16T19:29:18.000Z
|
dlls/ulkata.cpp
|
Laluka256/halflife-planckepoch
|
3ccfd783213c3ee88b9ed8204acdce01d40d5420
|
[
"Unlicense"
] | 1 |
2021-11-29T18:04:51.000Z
|
2021-11-29T18:04:51.000Z
|
dlls/ulkata.cpp
|
Laluka256/halflife-planckepoch
|
3ccfd783213c3ee88b9ed8204acdce01d40d5420
|
[
"Unlicense"
] | null | null | null |
#include "CBarney.h"
class CUlkata : public CBarney
{
void Spawn();
void Precache();
int Classify();
};
LINK_ENTITY_TO_CLASS(monster_ulkata, CUlkata);
void CUlkata::Spawn()
{
Precache();
SET_MODEL(ENT(pev), "models/ulkata.mdl");
UTIL_SetSize(pev, VEC_HUMAN_HULL_MIN, VEC_HUMAN_HULL_MAX);
pev->solid = SOLID_SLIDEBOX;
pev->movetype = MOVETYPE_STEP;
m_bloodColor = BLOOD_COLOR_RED;
pev->health = gSkillData.barneyHealth;
pev->view_ofs = Vector(0, 0, 50);// position of the eyes relative to monster's origin.
m_flFieldOfView = VIEW_FIELD_WIDE; // NOTE: we need a wide field of view so npc will notice player and say hello
m_MonsterState = MONSTERSTATE_NONE;
pev->body = 0; // gun in holster
m_fGunDrawn = FALSE;
m_afCapability = bits_CAP_HEAR | bits_CAP_TURN_HEAD | bits_CAP_DOORS_GROUP;
PainSound();
MonsterInit();
SetUse(&CUlkata::FollowerUse);
}
void CUlkata::Precache()
{
PRECACHE_MODEL("models/ulkata.mdl");
PRECACHE_SOUND("barney/ba_attack1.wav");
PRECACHE_SOUND("barney/ba_attack2.wav");
PRECACHE_SOUND("barney/ba_pain1.wav");
PRECACHE_SOUND("barney/ba_pain2.wav");
PRECACHE_SOUND("barney/ba_pain3.wav");
PRECACHE_SOUND("barney/ba_die1.wav");
PRECACHE_SOUND("barney/ba_die2.wav");
PRECACHE_SOUND("barney/ba_die3.wav");
// every new barney must call this, otherwise
// when a level is loaded, nobody will talk (time is reset to 0)
TalkInit();
CTalkMonster::Precache();
}
int CUlkata::Classify()
{
return CLASS_HUMAN_MILITARY;
}
| 23.125 | 113 | 0.741892 |
Laluka256
|
2586f4a0c4c6794bbcf64c3236ec408605e6c6a0
| 15,878 |
cxx
|
C++
|
PWMTest/PWMTest.cxx
|
RobertPHeller/RPi-RRCircuits
|
19aff23e20eebdbd028c0407d68eef77cc6ee0ec
|
[
"CC-BY-4.0"
] | 10 |
2018-09-04T02:12:39.000Z
|
2022-03-17T20:29:32.000Z
|
PWMTest/PWMTest.cxx
|
RobertPHeller/RPi-RRCircuits
|
19aff23e20eebdbd028c0407d68eef77cc6ee0ec
|
[
"CC-BY-4.0"
] | null | null | null |
PWMTest/PWMTest.cxx
|
RobertPHeller/RPi-RRCircuits
|
19aff23e20eebdbd028c0407d68eef77cc6ee0ec
|
[
"CC-BY-4.0"
] | 1 |
2018-12-26T00:32:27.000Z
|
2018-12-26T00:32:27.000Z
|
// -!- C++ -!- //////////////////////////////////////////////////////////////
//
// System :
// Module :
// Object Name : $RCSfile$
// Revision : $Revision$
// Date : $Date$
// Author : $Author$
// Created By : Robert Heller
// Created : Sun Feb 17 15:35:50 2019
// Last Modified : <190219.1354>
//
// Description
//
// Notes
//
// History
//
/////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2019 Robert Heller D/B/A Deepwoods Software
// 51 Locke Hill Road
// Wendell, MA 01379-9728
//
// 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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//
//
//////////////////////////////////////////////////////////////////////////////
static const char rcsid[] = "@(#) : $Id$";
#include "PWMTest.hxx"
#include "utils/ConfigUpdateListener.hxx"
#include "utils/ConfigUpdateService.hxx"
#include "openlcb/EventService.hxx"
ConfigUpdateListener::UpdateAction ConfiguredPWMConsumer::apply_configuration(int fd,
bool initial_load,
BarrierNotifiable *done)
{
AutoNotify n(done);
openlcb::EventId cfg_pwm_zero_event = config.event_pwm_zero().read(fd);
openlcb::EventId cfg_pwm_one_event = config.event_pwm_one().read(fd);
openlcb::EventId cfg_pwm_two_event = config.event_pwm_two().read(fd);
openlcb::EventId cfg_pwm_three_event = config.event_pwm_three().read(fd);
openlcb::EventId cfg_pwm_four_event = config.event_pwm_four().read(fd);
openlcb::EventId cfg_pwm_five_event = config.event_pwm_five().read(fd);
openlcb::EventId cfg_pwm_six_event = config.event_pwm_six().read(fd);
openlcb::EventId cfg_pwm_seven_event = config.event_pwm_seven().read(fd);
openlcb::EventId cfg_pwm_eight_event = config.event_pwm_eight().read(fd);
openlcb::EventId cfg_pwm_nine_event = config.event_pwm_nine().read(fd);
openlcb::EventId cfg_pwm_ten_event = config.event_pwm_ten().read(fd);
period = config.pwm_period().read(fd);
pwm_->set_period(period);
zero_duty = config.pwm_zero().read(fd);
one_duty = config.pwm_one().read(fd);
two_duty = config.pwm_two().read(fd);
three_duty = config.pwm_three().read(fd);
four_duty = config.pwm_four().read(fd);
five_duty = config.pwm_five().read(fd);
six_duty = config.pwm_six().read(fd);
seven_duty = config.pwm_seven().read(fd);
eight_duty = config.pwm_eight().read(fd);
nine_duty = config.pwm_nine().read(fd);
ten_duty = config.pwm_ten().read(fd);
if (cfg_pwm_zero_event != pwm_zero_event ||
cfg_pwm_one_event != pwm_one_event ||
cfg_pwm_two_event != pwm_two_event ||
cfg_pwm_three_event != pwm_three_event ||
cfg_pwm_four_event != pwm_four_event ||
cfg_pwm_five_event != pwm_five_event ||
cfg_pwm_six_event != pwm_six_event ||
cfg_pwm_seven_event != pwm_seven_event ||
cfg_pwm_eight_event != pwm_eight_event ||
cfg_pwm_nine_event != pwm_nine_event ||
cfg_pwm_ten_event != pwm_ten_event) {
if (!initial_load) unregister_handler();
pwm_zero_event = cfg_pwm_zero_event;
pwm_one_event = cfg_pwm_one_event;
pwm_two_event = cfg_pwm_two_event;
pwm_three_event = cfg_pwm_three_event;
pwm_four_event = cfg_pwm_four_event;
pwm_five_event = cfg_pwm_five_event;
pwm_six_event = cfg_pwm_six_event;
pwm_seven_event = cfg_pwm_seven_event;
pwm_eight_event = cfg_pwm_eight_event;
pwm_nine_event = cfg_pwm_nine_event;
pwm_ten_event = cfg_pwm_ten_event;
register_handler();
return REINIT_NEEDED; // Causes events identify.
}
return UPDATED;
}
void ConfiguredPWMConsumer::factory_reset(int fd)
{
config.description().write(fd,"");
CDI_FACTORY_RESET(config.pwm_period);
CDI_FACTORY_RESET(config.pwm_zero);
CDI_FACTORY_RESET(config.pwm_one);
CDI_FACTORY_RESET(config.pwm_two);
CDI_FACTORY_RESET(config.pwm_three);
CDI_FACTORY_RESET(config.pwm_four);
CDI_FACTORY_RESET(config.pwm_five);
CDI_FACTORY_RESET(config.pwm_six);
CDI_FACTORY_RESET(config.pwm_seven);
CDI_FACTORY_RESET(config.pwm_eight);
CDI_FACTORY_RESET(config.pwm_nine);
CDI_FACTORY_RESET(config.pwm_ten);
}
void ConfiguredPWMConsumer::handle_event_report(const EventRegistryEntry &entry,
EventReport *event,
BarrierNotifiable *done)
{
if (event->event == pwm_zero_event) {
pwm_->set_duty(zero_duty);
} else if (event->event == pwm_one_event) {
pwm_->set_duty(one_duty);
} else if (event->event == pwm_two_event) {
pwm_->set_duty(two_duty);
} else if (event->event == pwm_three_event) {
pwm_->set_duty(three_duty);
} else if (event->event == pwm_four_event) {
pwm_->set_duty(four_duty);
} else if (event->event == pwm_five_event) {
pwm_->set_duty(five_duty);
} else if (event->event == pwm_six_event) {
pwm_->set_duty(six_duty);
} else if (event->event == pwm_seven_event) {
pwm_->set_duty(seven_duty);
} else if (event->event == pwm_eight_event) {
pwm_->set_duty(eight_duty);
} else if (event->event == pwm_nine_event) {
pwm_->set_duty(nine_duty);
} else if (event->event == pwm_ten_event) {
pwm_->set_duty(ten_duty);
}
done->notify();
}
void ConfiguredPWMConsumer::handle_identify_global(const EventRegistryEntry
®istry_entry,
EventReport *event,
BarrierNotifiable *done)
{
if (event->dst_node && event->dst_node != node_)
{
done->notify();
}
SendAllConsumersIdentified(event,done);
done->maybe_done();
}
void ConfiguredPWMConsumer::SendAllConsumersIdentified(openlcb::EventReport* event, BarrierNotifiable* done)
{
openlcb::Defs::MTI mti_zero = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID,
mti_one = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID,
mti_two = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID,
mti_three = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID,
mti_four = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID,
mti_five = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID,
mti_six = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID,
mti_seven = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID,
mti_eight = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID,
mti_nine = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID,
mti_ten = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID;
uint32_t current_duty_cycle = /* pwm_->get_duty() */ 0;
if (current_duty_cycle == zero_duty) {
mti_zero = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (current_duty_cycle == one_duty) {
mti_one = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (current_duty_cycle == two_duty) {
mti_two = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (current_duty_cycle == three_duty) {
mti_three = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (current_duty_cycle == four_duty) {
mti_four = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (current_duty_cycle == five_duty) {
mti_five = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (current_duty_cycle == six_duty) {
mti_six = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (current_duty_cycle == seven_duty) {
mti_seven = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (current_duty_cycle == eight_duty) {
mti_eight = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (current_duty_cycle == nine_duty) {
mti_nine = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (current_duty_cycle == ten_duty) {
mti_ten = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
}
write_helpers[0].WriteAsync(node_,mti_zero,
openlcb::WriteHelper::global(),
openlcb::eventid_to_buffer(pwm_zero_event),
done->new_child());
write_helpers[1].WriteAsync(node_,mti_one,
openlcb::WriteHelper::global(),
openlcb::eventid_to_buffer(pwm_one_event),
done->new_child());
write_helpers[2].WriteAsync(node_,mti_two,
openlcb::WriteHelper::global(),
openlcb::eventid_to_buffer(pwm_two_event),
done->new_child());
write_helpers[3].WriteAsync(node_,mti_three,
openlcb::WriteHelper::global(),
openlcb::eventid_to_buffer(pwm_three_event),
done->new_child());
write_helpers[4].WriteAsync(node_,mti_four,
openlcb::WriteHelper::global(),
openlcb::eventid_to_buffer(pwm_four_event),
done->new_child());
write_helpers[5].WriteAsync(node_,mti_five,
openlcb::WriteHelper::global(),
openlcb::eventid_to_buffer(pwm_five_event),
done->new_child());
write_helpers[6].WriteAsync(node_,mti_six,
openlcb::WriteHelper::global(),
openlcb::eventid_to_buffer(pwm_six_event),
done->new_child());
write_helpers[7].WriteAsync(node_,mti_seven,
openlcb::WriteHelper::global(),
openlcb::eventid_to_buffer(pwm_seven_event),
done->new_child());
write_helpers[8].WriteAsync(node_,mti_eight,
openlcb::WriteHelper::global(),
openlcb::eventid_to_buffer(pwm_eight_event),
done->new_child());
write_helpers[9].WriteAsync(node_,mti_nine,
openlcb::WriteHelper::global(),
openlcb::eventid_to_buffer(pwm_nine_event),
done->new_child());
write_helpers[10].WriteAsync(node_,mti_ten,
openlcb::WriteHelper::global(),
openlcb::eventid_to_buffer(pwm_ten_event),
done->new_child());
}
void ConfiguredPWMConsumer::handle_identify_consumer(const EventRegistryEntry
®istry_entry,
EventReport *event,
BarrierNotifiable *done)
{
SendConsumerIdentified(event,done);
done->maybe_done();
}
void ConfiguredPWMConsumer::SendConsumerIdentified(openlcb::EventReport* event, BarrierNotifiable* done)
{
openlcb::Defs::MTI mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID;
uint32_t current_duty_cycle = /* pwm_->get_duty() */ 0;
if (event->event == pwm_zero_event &&
current_duty_cycle == zero_duty) {
mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (event->event == pwm_one_event &&
current_duty_cycle == one_duty) {
mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (event->event == pwm_two_event &&
current_duty_cycle == two_duty) {
mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (event->event == pwm_three_event &&
current_duty_cycle == three_duty) {
mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (event->event == pwm_four_event &&
current_duty_cycle == four_duty) {
mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (event->event == pwm_five_event &&
current_duty_cycle == five_duty) {
mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (event->event == pwm_six_event &&
current_duty_cycle == six_duty) {
mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (event->event == pwm_seven_event &&
current_duty_cycle == seven_duty) {
mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (event->event == pwm_eight_event &&
current_duty_cycle == eight_duty) {
mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (event->event == pwm_nine_event &&
current_duty_cycle == nine_duty) {
mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else if (event->event == pwm_ten_event &&
current_duty_cycle == ten_duty) {
mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID;
} else {
mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_UNKNOWN;
}
event->event_write_helper<1>()->WriteAsync(node_, mti,
openlcb::WriteHelper::global(),
openlcb::eventid_to_buffer(event->event),
done->new_child());
}
void ConfiguredPWMConsumer::register_handler()
{
openlcb::EventRegistry::instance()->register_handler(
openlcb::EventRegistryEntry(this,pwm_zero_event),0);
openlcb::EventRegistry::instance()->register_handler(
openlcb::EventRegistryEntry(this,pwm_one_event),0);
openlcb::EventRegistry::instance()->register_handler(
openlcb::EventRegistryEntry(this,pwm_two_event),0);
openlcb::EventRegistry::instance()->register_handler(
openlcb::EventRegistryEntry(this,pwm_three_event),0);
openlcb::EventRegistry::instance()->register_handler(
openlcb::EventRegistryEntry(this,pwm_four_event),0);
openlcb::EventRegistry::instance()->register_handler(
openlcb::EventRegistryEntry(this,pwm_five_event),0);
openlcb::EventRegistry::instance()->register_handler(
openlcb::EventRegistryEntry(this,pwm_six_event),0);
openlcb::EventRegistry::instance()->register_handler(
openlcb::EventRegistryEntry(this,pwm_seven_event),0);
openlcb::EventRegistry::instance()->register_handler(
openlcb::EventRegistryEntry(this,pwm_eight_event),0);
openlcb::EventRegistry::instance()->register_handler(
openlcb::EventRegistryEntry(this,pwm_nine_event),0);
openlcb::EventRegistry::instance()->register_handler(
openlcb::EventRegistryEntry(this,pwm_ten_event),0);
}
void ConfiguredPWMConsumer::unregister_handler()
{
openlcb::EventRegistry::instance()->unregister_handler(this);
}
| 46.7 | 108 | 0.609963 |
RobertPHeller
|
2588ecbf5ba8af9b5faadfeb107428a9334ae03a
| 4,036 |
cpp
|
C++
|
hardware/digistump/avr/libraries/LPD8806/LPD8806.cpp
|
emptyland/arduino
|
278cf1189401ba2bcb2d4125e42ac338c20ee4c8
|
[
"BSD-3-Clause"
] | 1 |
2021-04-10T10:01:06.000Z
|
2021-04-10T10:01:06.000Z
|
hardware/digistump/avr/libraries/LPD8806/LPD8806.cpp
|
emptyland/arduino
|
278cf1189401ba2bcb2d4125e42ac338c20ee4c8
|
[
"BSD-3-Clause"
] | 6 |
2020-06-04T06:04:39.000Z
|
2021-05-02T17:09:15.000Z
|
arduino/portable/packages/digistump/hardware/avr/1.6.7/libraries/LPD8806/LPD8806.cpp
|
darrintw/ardublockly-tw
|
b9c29bbe52c77a7bec14ae69a5a7365c9e4ab86e
|
[
"Apache-2.0"
] | 3 |
2021-04-10T10:01:08.000Z
|
2021-09-02T00:14:31.000Z
|
#include "LPD8806.h"
// Arduino library to control LPD8806-based RGB LED Strips
// (c) Adafruit industries
// MIT license
/*****************************************************************************/
// Constructor for use with arbitrary clock/data pins:
LPD8806::LPD8806(uint16_t n, uint8_t dpin, uint8_t cpin) {
pixels = NULL;
begun = false;
updateLength(n);
updatePins(dpin, cpin);
}
// Activate hard/soft SPI as appropriate:
void LPD8806::begin(void) {
startBitbang();
begun = true;
}
// Change pin assignments post-constructor, using arbitrary pins:
void LPD8806::updatePins(uint8_t dpin, uint8_t cpin) {
datapin = dpin;
clkpin = cpin;
clkport = portOutputRegister(digitalPinToPort(cpin));
clkpinmask = digitalPinToBitMask(cpin);
dataport = portOutputRegister(digitalPinToPort(dpin));
datapinmask = digitalPinToBitMask(dpin);
if(begun == true) { // If begin() was previously invoked...
startBitbang(); // Regardless, now enable 'soft' SPI outputs
} // Otherwise, pins are not set to outputs until begin() is called.
// Note: any prior clock/data pin directions are left as-is and are
// NOT restored as inputs!
hardwareSPI = false;
}
// Enable software SPI pins and issue initial latch:
void LPD8806::startBitbang() {
pinMode(datapin, OUTPUT);
pinMode(clkpin , OUTPUT);
*dataport &= ~datapinmask; // Data is held low throughout (latch = 0)
for(uint8_t i = 8; i>0; i--) {
*clkport |= clkpinmask;
*clkport &= ~clkpinmask;
}
}
// Change strip length (see notes with empty constructor, above):
void LPD8806::updateLength(uint16_t n) {
if(pixels != NULL) free(pixels); // Free existing data (if any)
numLEDs = n;
n *= 3; // 3 bytes per pixel
if(NULL != (pixels = (uint8_t *)malloc(n + 1))) { // Alloc new data
memset(pixels, 0x80, n); // Init to RGB 'off' state
pixels[n] = 0; // Last byte is always zero for latch
} else numLEDs = 0; // else malloc failed
// 'begun' state does not change -- pins retain prior modes
}
uint16_t LPD8806::numPixels(void) {
return numLEDs;
}
// This is how data is pushed to the strip. Unfortunately, the company
// that makes the chip didnt release the protocol document or you need
// to sign an NDA or something stupid like that, but we reverse engineered
// this from a strip controller and it seems to work very nicely!
void LPD8806::show(void) {
uint16_t i, n3 = numLEDs * 3 + 1; // 3 bytes per LED + 1 for latch
// write 24 bits per pixel
for (i=0; i<n3; i++ ) {
for (uint8_t bit=0x80; bit; bit >>= 1) {
if(pixels[i] & bit) *dataport |= datapinmask;
else *dataport &= ~datapinmask;
*clkport |= clkpinmask;
*clkport &= ~clkpinmask;
}
}
}
// Convert separate R,G,B into combined 32-bit GRB color:
uint32_t LPD8806::Color(byte r, byte g, byte b) {
return 0x808080 | ((uint32_t)g << 16) | ((uint32_t)r << 8) | (uint32_t)b;
}
// Set pixel color from separate 7-bit R, G, B components:
void LPD8806::setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b) {
if(n < numLEDs) { // Arrays are 0-indexed, thus NOT '<='
uint8_t *p = &pixels[n * 3];
*p++ = g | 0x80; // LPD8806 color order is GRB,
*p++ = r | 0x80; // not the more common RGB,
*p++ = b | 0x80; // so the order here is intentional; don't "fix"
}
}
// Set pixel color from 'packed' 32-bit RGB value:
void LPD8806::setPixelColor(uint16_t n, uint32_t c) {
if(n < numLEDs) { // Arrays are 0-indexed, thus NOT '<='
uint8_t *p = &pixels[n * 3];
*p++ = (c >> 16) | 0x80;
*p++ = (c >> 8) | 0x80;
*p++ = c | 0x80;
}
}
// Query color from previously-set pixel (returns packed 32-bit GRB value)
uint32_t LPD8806::getPixelColor(uint16_t n) {
if(n < numLEDs) {
uint16_t ofs = n * 3;
return ((uint32_t)((uint32_t)pixels[ofs ] << 16) |
(uint32_t)((uint32_t)pixels[ofs + 1] << 8) |
(uint32_t)pixels[ofs + 2]) & 0x7f7f7f;
}
return 0; // Pixel # is out of bounds
}
| 32.288 | 79 | 0.625867 |
emptyland
|
258932e9f96ae85ee617f4c40c1f163bf0a461e9
| 353 |
cpp
|
C++
|
0812_largest_triangle_area.cpp
|
fxshan/LeetCode
|
a54bbe22bc335dcb3c7efffcc34357cab7641492
|
[
"Apache-2.0"
] | 2 |
2020-06-04T13:20:20.000Z
|
2020-06-04T14:49:10.000Z
|
0812_largest_triangle_area.cpp
|
fxshan/LeetCode
|
a54bbe22bc335dcb3c7efffcc34357cab7641492
|
[
"Apache-2.0"
] | null | null | null |
0812_largest_triangle_area.cpp
|
fxshan/LeetCode
|
a54bbe22bc335dcb3c7efffcc34357cab7641492
|
[
"Apache-2.0"
] | null | null | null |
class Solution {
public:
double largestTriangleArea(vector<vector<int>>& points) {
double res = 0;
for (vector i : points)
for (vector j : points)
for (vector k : points)
res = max(res, 0.5 * (i[0] * (j[1] - k[1]) + j[0] * (k[1] - i[1]) +
k[0] * (i[1] - j[1])));
return res;
}
};
| 27.153846 | 77 | 0.456091 |
fxshan
|
2590e40fb962694ad4e013e627025acdfecb9ce0
| 5,906 |
cpp
|
C++
|
podofo-0.9.6/test/unit/FontTest.cpp
|
zia95/pdf-toolkit-console-
|
369d73f66f7d4c74a252e83d200acbb792a6b8d5
|
[
"MIT"
] | 1 |
2020-12-29T07:37:14.000Z
|
2020-12-29T07:37:14.000Z
|
podofo-0.9.6/test/unit/FontTest.cpp
|
zia95/pdf-toolkit-console-
|
369d73f66f7d4c74a252e83d200acbb792a6b8d5
|
[
"MIT"
] | null | null | null |
podofo-0.9.6/test/unit/FontTest.cpp
|
zia95/pdf-toolkit-console-
|
369d73f66f7d4c74a252e83d200acbb792a6b8d5
|
[
"MIT"
] | null | null | null |
/***************************************************************************
* Copyright (C) 2009 by Dominik Seichter *
* [email protected] *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This 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 Library 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. *
***************************************************************************/
#include "FontTest.h"
#include <cppunit/Asserter.h>
#include <ft2build.h>
#include FT_FREETYPE_H
using namespace PoDoFo;
CPPUNIT_TEST_SUITE_REGISTRATION( FontTest );
void FontTest::setUp()
{
m_pDoc = new PdfMemDocument();
m_pVecObjects = new PdfVecObjects();
m_pFontCache = new PdfFontCache( m_pVecObjects );
}
void FontTest::tearDown()
{
delete m_pDoc;
delete m_pFontCache;
delete m_pVecObjects;
}
#if defined(PODOFO_HAVE_FONTCONFIG)
void FontTest::testFonts()
{
FcObjectSet* objectSet = NULL;
FcFontSet* fontSet = NULL;
FcPattern* pattern = NULL;
FcConfig* pConfig = NULL;
// Initialize fontconfig
CPPUNIT_ASSERT_EQUAL( !FcInit(), false );
pConfig = FcInitLoadConfigAndFonts();
CPPUNIT_ASSERT_EQUAL( !pConfig, false );
// Get all installed fonts
pattern = FcPatternCreate();
objectSet = FcObjectSetBuild( FC_FAMILY, FC_STYLE, FC_FILE, FC_SLANT, FC_WEIGHT, NULL );
fontSet = FcFontList( NULL, pattern, objectSet );
FcObjectSetDestroy( objectSet );
FcPatternDestroy( pattern );
if( fontSet )
{
printf("Testing %i fonts\n", fontSet->nfont );
int j;
for (j = 0; j < fontSet->nfont; j++)
{
testSingleFont( fontSet->fonts[j], pConfig );
}
FcFontSetDestroy( fontSet );
}
// Shut fontconfig down
// Causes an assertion in fontconfig FcFini();
}
void FontTest::testSingleFont(FcPattern* pFont, FcConfig* pConfig)
{
std::string sFamily;
std::string sPath;
bool bBold;
bool bItalic;
if( GetFontInfo( pFont, sFamily, sPath, bBold, bItalic ) )
{
std::string sPodofoFontPath =
m_pFontCache->GetFontConfigFontPath( pConfig, sFamily.c_str(),
bBold, bItalic );
std::string msg = "Font failed: " + sPodofoFontPath;
EPdfFontType eFontType = PdfFontFactory::GetFontType( sPath.c_str() );
if( eFontType == ePdfFontType_TrueType )
{
// Only TTF fonts can use identity encoding
PdfFont* pFont = m_pDoc->CreateFont( sFamily.c_str(), bBold, bItalic,
new PdfIdentityEncoding() );
CPPUNIT_ASSERT_EQUAL_MESSAGE( msg, pFont != NULL, true );
}
else if( eFontType != ePdfFontType_Unknown )
{
PdfFont* pFont = m_pDoc->CreateFont( sFamily.c_str(), bBold, bItalic );
CPPUNIT_ASSERT_EQUAL_MESSAGE( msg, pFont != NULL, true );
}
else
{
printf("Ignoring font: %s\n", sPodofoFontPath.c_str());
}
}
}
void FontTest::testCreateFontFtFace()
{
FT_Face face;
FT_Error error;
// TODO: Find font file on disc!
error = FT_New_Face( m_pDoc->GetFontLibrary(), "/usr/share/fonts/truetype/msttcorefonts/Arial.ttf", 0, &face );
if( !error )
{
PdfFont* pFont = m_pDoc->CreateFont( face );
CPPUNIT_ASSERT_MESSAGE( "Cannot create font from FT_Face.", pFont != NULL );
}
}
bool FontTest::GetFontInfo( FcPattern* pFont, std::string & rsFamily, std::string & rsPath,
bool & rbBold, bool & rbItalic )
{
FcChar8* family = NULL;
FcChar8* file = NULL;
int slant;
int weight;
if( FcPatternGetString(pFont, FC_FAMILY, 0, &family) == FcResultMatch )
{
rsFamily = reinterpret_cast<char*>(family);
if( FcPatternGetString(pFont, FC_FILE, 0, &file) == FcResultMatch )
{
rsPath = reinterpret_cast<char*>(file);
if( FcPatternGetInteger(pFont, FC_SLANT, 0, &slant) == FcResultMatch )
{
if(slant == FC_SLANT_ROMAN)
rbItalic = false;
else if(slant == FC_SLANT_ITALIC)
rbItalic = true;
else
return false;
if( FcPatternGetInteger(pFont, FC_WEIGHT, 0, &weight) == FcResultMatch )
{
if(weight == FC_WEIGHT_MEDIUM)
rbBold = false;
else if(weight == FC_WEIGHT_BOLD)
rbBold = true;
else
return false;
return true;
}
}
//free( file );
}
//free( family );
}
return false;
}
#endif
| 33.179775 | 115 | 0.526752 |
zia95
|
25977b810b0f80b9cb060e17cd3ffb1a385e5c16
| 1,292 |
cpp
|
C++
|
libs/pika/execution/tests/regressions/split_continuation_clear.cpp
|
pika-org/pika
|
c80f542b2432a7f108fcfba31a5fe5073ad2b3e1
|
[
"BSL-1.0"
] | 13 |
2022-01-17T12:01:48.000Z
|
2022-03-16T10:03:14.000Z
|
libs/pika/execution/tests/regressions/split_continuation_clear.cpp
|
pika-org/pika
|
c80f542b2432a7f108fcfba31a5fe5073ad2b3e1
|
[
"BSL-1.0"
] | 163 |
2022-01-17T17:36:45.000Z
|
2022-03-31T17:42:57.000Z
|
libs/pika/execution/tests/regressions/split_continuation_clear.cpp
|
pika-org/pika
|
c80f542b2432a7f108fcfba31a5fe5073ad2b3e1
|
[
"BSL-1.0"
] | 4 |
2022-01-19T08:44:22.000Z
|
2022-01-31T23:16:21.000Z
|
// Copyright (c) 2022 ETH Zurich
//
// SPDX-License-Identifier: BSL-1.0
// 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)
// This test reproduces a segfault in the split sender adaptor which happens if
// the continuations are cleared after all continuations are called. This may
// happen because the last continuation to run may reset the shared state of the
// split adaptor. If the shared state has been reset the continuations have
// already been released. There is a corresponding comment in the set_value
// implementation of split_receiver.
#include <pika/execution.hpp>
#include <pika/init.hpp>
#include <pika/testing.hpp>
#include <cstddef>
namespace ex = pika::execution::experimental;
int pika_main()
{
ex::thread_pool_scheduler sched;
for (std::size_t i = 0; i < 100; ++i)
{
auto s = ex::schedule(sched) | ex::split();
for (std::size_t j = 0; j < 10; ++j)
{
ex::start_detached(s);
}
}
return pika::finalize();
}
int main(int argc, char* argv[])
{
PIKA_TEST_EQ_MSG(pika::init(pika_main, argc, argv), 0,
"pika main exited with non-zero status");
return pika::util::report_errors();
}
| 28.711111 | 80 | 0.682663 |
pika-org
|
259a92c669b2ad7330ff4a4a3b05585f9fe62d7a
| 421 |
cpp
|
C++
|
Engine/Samples/Core/Math/main.cpp
|
ZenEngine3D/ZenEngine
|
42bcd06f743eb1381a587c9671de67e24cf72316
|
[
"MIT"
] | 1 |
2018-10-12T19:10:59.000Z
|
2018-10-12T19:10:59.000Z
|
Engine/Samples/Core/Math/main.cpp
|
ZenEngine3D/ZenEngine
|
42bcd06f743eb1381a587c9671de67e24cf72316
|
[
"MIT"
] | null | null | null |
Engine/Samples/Core/Math/main.cpp
|
ZenEngine3D/ZenEngine
|
42bcd06f743eb1381a587c9671de67e24cf72316
|
[
"MIT"
] | 1 |
2019-03-09T02:12:31.000Z
|
2019-03-09T02:12:31.000Z
|
#include "zenEngine.h"
namespace sample
{
extern void SampleVector();
class SampleBaseMath : public zenSys::zSampleEngineInstance
{
public:
virtual const char* GetAppName()const
{
return "Sample Math";
}
virtual void Update()
{
SampleVector();
SetDone();
}
};
}
int main(int argc, char * const argv[])
{
sample::SampleBaseMath Sample;
zenSys::LaunchEngine(&Sample, argc, argv);
return 0;
}
| 15.592593 | 60 | 0.68171 |
ZenEngine3D
|
259b417714e466f713cae90869cfb8d203e85878
| 288 |
cpp
|
C++
|
CodeChef/Begginer-Problems/SMPAIR.cpp
|
annukamat/My-Competitive-Journey
|
adb13a5723483cde13e5f3859b3a7ad840b86c97
|
[
"MIT"
] | 7 |
2018-11-08T11:39:27.000Z
|
2020-09-10T17:50:57.000Z
|
CodeChef/Begginer-Problems/SMPAIR.cpp
|
annukamat/My-Competitive-Journey
|
adb13a5723483cde13e5f3859b3a7ad840b86c97
|
[
"MIT"
] | null | null | null |
CodeChef/Begginer-Problems/SMPAIR.cpp
|
annukamat/My-Competitive-Journey
|
adb13a5723483cde13e5f3859b3a7ad840b86c97
|
[
"MIT"
] | 2 |
2019-09-16T14:34:03.000Z
|
2019-10-12T19:24:00.000Z
|
#include <bits/stdc++.h>
using namespace std;
int main(){
long int t;
vector<long int> vals(100000);
long int n, x;
cin>>t;
while(t--){
cin>> n;
for(int i=0;i<n; i++)
cin>>x;
vals.push_back(x);
}
sort(vals.begin(), vals+n);
}
| 16 | 34 | 0.489583 |
annukamat
|
259de4d152a4f89a607a1d66209fb8fb75e69105
| 1,393 |
hpp
|
C++
|
src/color/hsi/get/gray.hpp
|
3l0w/color
|
e42d0933b6b88564807bcd5f49e9c7f66e24990a
|
[
"Apache-2.0"
] | 120 |
2015-12-31T22:30:14.000Z
|
2022-03-29T15:08:01.000Z
|
src/color/hsi/get/gray.hpp
|
3l0w/color
|
e42d0933b6b88564807bcd5f49e9c7f66e24990a
|
[
"Apache-2.0"
] | 6 |
2016-08-22T02:14:56.000Z
|
2021-11-06T22:39:52.000Z
|
src/color/hsi/get/gray.hpp
|
3l0w/color
|
e42d0933b6b88564807bcd5f49e9c7f66e24990a
|
[
"Apache-2.0"
] | 23 |
2016-02-03T01:56:26.000Z
|
2021-09-28T16:36:27.000Z
|
#ifndef color_hsi_get_gray
#define color_hsi_get_gray
// ::color::get::gray( c )
#include "../../gray/place/place.hpp"
#include "../../gray/akin/hsi.hpp"
#include "../../gray/trait/component.hpp"
#include "../category.hpp"
#include "../../_internal/normalize.hpp"
#include "../../_internal/diverse.hpp"
#include "../../generic/trait/scalar.hpp"
namespace color
{
namespace get
{
template< typename tag_name >
inline
typename ::color::trait::component< typename ::color::akin::gray< ::color::category::hsi<tag_name> >::akin_type >::return_type
gray( ::color::model< ::color::category::hsi<tag_name> > const& color_parameter )
{
typedef ::color::category::hsi<tag_name> category_type;
typedef typename ::color::trait::scalar<category_type>::instance_type scalar_type;
typedef typename ::color::akin::gray<category_type>::akin_type akin_type;
typedef ::color::_internal::diverse< akin_type > diverse_type;
typedef ::color::_internal::normalize<category_type> normalize_type;
enum{ intensity_p = ::color::place::_internal::intensity<category_type>::position_enum };
scalar_type g = normalize_type::template process<intensity_p >( color_parameter.template get<intensity_p >() );
return diverse_type::template process<0>( g );
}
}
}
#endif
| 30.282609 | 132 | 0.656856 |
3l0w
|
259e79dc8c56138e5a173d30655bd280e724de4f
| 3,479 |
cpp
|
C++
|
test/test_free_functions.cpp
|
jb--/luaponte
|
06bfe551bce23e411e75895797b8bb84bb662ed2
|
[
"BSL-1.0"
] | 3 |
2015-08-30T10:02:10.000Z
|
2018-08-27T06:54:44.000Z
|
test/test_free_functions.cpp
|
halmd-org/luaponte
|
165328485954a51524a0b1aec27518861c6be719
|
[
"BSL-1.0"
] | null | null | null |
test/test_free_functions.cpp
|
halmd-org/luaponte
|
165328485954a51524a0b1aec27518861c6be719
|
[
"BSL-1.0"
] | null | null | null |
// Luaponte library
// Copyright (c) 2011-2012 Peter Colberg
// Luaponte is based on Luabind, a library, inspired by and similar to
// Boost.Python, that helps you create bindings between C++ and Lua,
// Copyright (c) 2003-2010 Daniel Wallin and Arvid Norberg.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "test.hpp"
#include <luaponte/luaponte.hpp>
#include <luaponte/adopt_policy.hpp>
struct base : counted_type<base>
{
int f()
{
return 5;
}
};
COUNTER_GUARD(base);
int f(int x)
{
return x + 1;
}
int f(int x, int y)
{
return x + y;
}
base* create_base()
{
return new base();
}
void test_value_converter(const std::string str)
{
TEST_CHECK(str == "converted string");
}
void test_pointer_converter(const char* const str)
{
TEST_CHECK(std::strcmp(str, "converted string") == 0);
}
struct copy_me
{
};
void take_by_value(copy_me m)
{
}
int function_should_never_be_called(lua_State* L)
{
lua_pushnumber(L, 10);
return 1;
}
void test_main(lua_State* L)
{
using namespace luaponte;
lua_pushcclosure(L, &function_should_never_be_called, 0);
lua_setglobal(L, "f");
DOSTRING(L, "assert(f() == 10)");
module(L)
[
class_<copy_me>("copy_me")
.def(constructor<>()),
class_<base>("base")
.def("f", &base::f),
def("by_value", &take_by_value),
def("f", (int(*)(int)) &f),
def("f", (int(*)(int, int)) &f),
def("create", &create_base, adopt(return_value))
// def("set_functor", &set_functor)
#if !(BOOST_MSVC < 1300)
,
def("test_value_converter", &test_value_converter),
def("test_pointer_converter", &test_pointer_converter)
#endif
];
DOSTRING(L,
"e = create()\n"
"assert(e:f() == 5)");
DOSTRING(L, "assert(f(7) == 8)");
DOSTRING(L, "assert(f(3, 9) == 12)");
// DOSTRING(L, "set_functor(function(x) return x * 10 end)");
// TEST_CHECK(functor_test(20) == 200);
// DOSTRING(L, "set_functor(nil)");
DOSTRING(L, "function lua_create() return create() end");
base* ptr = call_function<base*>(L, "lua_create") [ adopt(result) ];
delete ptr;
#if !(BOOST_MSVC < 1300)
DOSTRING(L, "test_value_converter('converted string')");
DOSTRING(L, "test_pointer_converter('converted string')");
#endif
DOSTRING_EXPECTED(L, "f('incorrect', 'parameters')",
"No matching overload found, candidates:\n"
"int f(int,int)\n"
"int f(int)");
DOSTRING(L, "function failing_fun() error('expected error message') end");
try
{
call_function<void>(L, "failing_fun");
TEST_ERROR("function didn't fail when it was expected to");
}
catch(luaponte::error const& e)
{
// LuaJIT 2.0 and Lua >= 5.2 will return expected1
std::string expected52("[string \"function failing_fun() error('expected error ...\"]:1: expected error message");
// Lua < 5.2 will return expected2
std::string expected51("[string \"function failing_fun() error('expected erro...\"]:1: expected error message");
std::string result(lua_tostring(L, -1));
if (result != expected51 && result != expected52)
{
TEST_ERROR("function failed with unexpected error message");
}
lua_pop(L, 1);
}
}
| 23.193333 | 122 | 0.616556 |
jb--
|
259fbcf71e33fd6166fdebc6cfb7ca4a5337cb97
| 596 |
cpp
|
C++
|
GraphicsToolsModule/Objects/gtmaterialparametervector3f.cpp
|
HowCanidothis-zz/DevLib
|
d3d7f4ef7b2b3f1c9559ca6bd56743e5aeff06ee
|
[
"MIT"
] | null | null | null |
GraphicsToolsModule/Objects/gtmaterialparametervector3f.cpp
|
HowCanidothis-zz/DevLib
|
d3d7f4ef7b2b3f1c9559ca6bd56743e5aeff06ee
|
[
"MIT"
] | null | null | null |
GraphicsToolsModule/Objects/gtmaterialparametervector3f.cpp
|
HowCanidothis-zz/DevLib
|
d3d7f4ef7b2b3f1c9559ca6bd56743e5aeff06ee
|
[
"MIT"
] | 1 |
2020-07-27T02:23:38.000Z
|
2020-07-27T02:23:38.000Z
|
#include "gtmaterialparametervector3f.h"
#include <QOpenGLShaderProgram>
#include "ResourcesModule/resourcessystem.h"
#include "../internal.hpp"
GtMaterialParameterVector3F::GtMaterialParameterVector3F(const QString& name, const QString& resource)
: GtMaterialParameterBase(name, resource)
{}
GtMaterialParameterBase::FDelegate GtMaterialParameterVector3F::apply()
{
m_vector = ResourcesSystem::GetResource<Vector3F>(m_resource);
return [this](QOpenGLShaderProgram* program, gLocID loc, OpenGLFunctions*) {
program->setUniformValue(loc, m_vector->Data().Get());
};
}
| 31.368421 | 102 | 0.771812 |
HowCanidothis-zz
|
25a65c573b1d9e09046be77976bf90321d8b36d9
| 408 |
cpp
|
C++
|
10783.cpp
|
shaonsani/UVA_Solving
|
ee916a2938ea81b3676baf4c8150b1b42c9ab5a5
|
[
"MIT"
] | null | null | null |
10783.cpp
|
shaonsani/UVA_Solving
|
ee916a2938ea81b3676baf4c8150b1b42c9ab5a5
|
[
"MIT"
] | null | null | null |
10783.cpp
|
shaonsani/UVA_Solving
|
ee916a2938ea81b3676baf4c8150b1b42c9ab5a5
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
int main()
{
int t,a,b,ca=1;
cin>>t;
while(t!=0)
{
int sum=0;
cin>>a;
cin>>b;
for(int i=a; i<=b; i++)
{
if(i%2==1)
{
sum+=i;
}
}
cout<<"Case "<<ca<<": "<<sum<<endl;
ca++;
t--;
}
return 0;
}
| 12.75 | 43 | 0.335784 |
shaonsani
|
25a7341141377dfd268a9ba521547ead79c8b139
| 10,744 |
hpp
|
C++
|
geometry/include/pcl/geometry/impl/face.hpp
|
zhangxaochen/CuFusion
|
e8bab7a366b1f2c85a80b95093d195d9f0774c11
|
[
"MIT"
] | 52 |
2017-09-05T13:31:44.000Z
|
2022-03-14T08:48:29.000Z
|
geometry/include/pcl/geometry/impl/face.hpp
|
GucciPrada/CuFusion
|
522920bcf316d1ddf9732fc71fa457174168d2fb
|
[
"MIT"
] | 4 |
2018-05-17T22:45:35.000Z
|
2020-02-01T21:46:42.000Z
|
geometry/include/pcl/geometry/impl/face.hpp
|
GucciPrada/CuFusion
|
522920bcf316d1ddf9732fc71fa457174168d2fb
|
[
"MIT"
] | 21 |
2015-07-27T13:00:36.000Z
|
2022-01-17T08:18:41.000Z
|
/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2012, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id: face.hpp 6833 2012-08-15 01:44:45Z Martin $
*
*/
#ifndef PCL_GEOMETRY_FACE_HPP
#define PCL_GEOMETRY_FACE_HPP
namespace pcl
{
/** \brief A Face is defined by a closed loop of edges.
*
* \tparam FaceDataT User data that is stored in the Face: Must have operator == (Equality Comparable)
* \tparam MeshT Mesh to which the Face belongs to (classes derived from MeshBase)
*
* \note It is not necessary to declare the Face manually. Please declare the mesh first and use the provided typedefs.
* \author Martin Saelzle
* \ingroup geometry
*/
template <class FaceDataT, class MeshT>
class Face : public FaceDataT
{
//////////////////////////////////////////////////////////////////////////
// Types
//////////////////////////////////////////////////////////////////////////
public:
typedef pcl::Face <FaceDataT, MeshT> Self;
typedef FaceDataT FaceData;
typedef MeshT Mesh;
typedef typename Mesh::HalfEdge HalfEdge;
typedef typename Mesh::HalfEdgeIndex HalfEdgeIndex;
//////////////////////////////////////////////////////////////////////////
// Constructor
//////////////////////////////////////////////////////////////////////////
public:
/** \brief Constructor
* \param face_data (optional) User data that is stored in the Face; defaults to FaceData ()
* \param idx_inner_half_edge (optional) Inner HalfEdgeIndex; defaults to HalfEdgeIndex () (invalid index)
*/
Face (const FaceData& face_data = FaceData (),
const HalfEdgeIndex& idx_inner_half_edge = HalfEdgeIndex ())
: FaceData (face_data),
is_deleted_ (false),
idx_inner_half_edge_ (idx_inner_half_edge)
{
}
//////////////////////////////////////////////////////////////////////////
// InnerHalfEdge
//////////////////////////////////////////////////////////////////////////
public:
/** \brief Returns the inner HalfEdgeIndex (non-const) */
HalfEdgeIndex&
getInnerHalfEdgeIndex ()
{
return (idx_inner_half_edge_);
}
/** \brief Returns the inner HalfEdgeIndex (const) */
const HalfEdgeIndex&
getInnerHalfEdgeIndex () const
{
return (idx_inner_half_edge_);
}
/** \brief Set the inner HalfEdgeIndex */
void
setInnerHalfEdgeIndex (const HalfEdgeIndex& idx_inner_half_edge)
{
idx_inner_half_edge_ = idx_inner_half_edge;
}
/** \brief Returns the inner HalfEdge (non-const)
* \param mesh Reference to the mesh to which the Face belongs to
* \note Convenience method for Mesh::getElement
*/
HalfEdge&
getInnerHalfEdge (Mesh& mesh) const
{
return (mesh.getElement (this->getInnerHalfEdgeIndex ()));
}
/** \brief Returns the inner HalfEdge (const)
* \param mesh Reference to the mesh to which the Face belongs to
* \note Convenience method for Mesh::getElement
*/
const HalfEdge&
getInnerHalfEdge (const Mesh& mesh) const
{
return (mesh.getElement (this->getInnerHalfEdgeIndex ()));
}
//////////////////////////////////////////////////////////////////////////
// OuterHalfEdge
//////////////////////////////////////////////////////////////////////////
public:
/** \brief Returns the outer HalfEdgeIndex (non-const)
* \param mesh Reference to the mesh to which the Face belongs to
* \note Convenience method for getInnerHalfEdge -> getOppositeHalfEdgeIndex
*/
HalfEdgeIndex&
getOuterHalfEdgeIndex (Mesh& mesh) const
{
return (this->getInnerHalfEdge (mesh).getOppositeHalfEdgeIndex ());
}
/** \brief Returns the outer HalfEdgeIndex (const)
* \param mesh Reference to the mesh to which the Face belongs to
* \note Convenience method for getInnerHalfEdge -> getOppositeHalfEdgeIndex
*/
const HalfEdgeIndex&
getOuterHalfEdgeIndex (const Mesh& mesh) const
{
return (this->getInnerHalfEdge (mesh).getOppositeHalfEdgeIndex ());
}
/** \brief Set the outer HalfEdgeIndex
* \param mesh Reference to the mesh to which the Face belongs to
* \param idx_outer_half_edge Outer HalfEdgeIndex
* \note Convenience method for getInnerHalfEdge -> setOppositeHalfEdgeIndex
*/
void
setOuterHalfEdgeIndex (Mesh& mesh,
const HalfEdgeIndex& idx_outer_half_edge) const
{
this->getInnerHalfEdge (mesh).setOppositeHalfEdgeIndex (idx_outer_half_edge);
}
/** \brief Returns the outer HalfEdge (non-const)
* \param mesh Reference to the mesh to which the Face belongs to
* \note Convenience method for getInnerHalfEdge -> getOppositeHalfEdge
*/
HalfEdge&
getOuterHalfEdge (Mesh& mesh) const
{
return (this->getInnerHalfEdge (mesh).getOppositeHalfEdge (mesh));
}
/** \brief Returns the outer HalfEdge (const)
* \param mesh Reference to the mesh to which the Face belongs to
* \note Convenience method for getInnerHalfEdge -> getOppositeHalfEdge
*/
const HalfEdge&
getOuterHalfEdge (const Mesh& mesh) const
{
return (this->getInnerHalfEdge (mesh).getOppositeHalfEdge (mesh));
}
//////////////////////////////////////////////////////////////////////////
// deleted
//////////////////////////////////////////////////////////////////////////
public:
/** \brief Returns true if the Face is marked as deleted */
bool
getDeleted () const
{
return (is_deleted_);
}
/** \brief Mark the Face as deleted (or not-deleted) */
void
setDeleted (const bool is_deleted)
{
is_deleted_ = is_deleted;
}
//////////////////////////////////////////////////////////////////////////
// Isolated
//////////////////////////////////////////////////////////////////////////
public:
/** \brief Returns true if the Face is isolated (not connected to any HalfEdge) */
bool
isIsolated () const
{
return (!this->getInnerHalfEdgeIndex ().isValid ());
}
//////////////////////////////////////////////////////////////////////////
// isBoundary
//////////////////////////////////////////////////////////////////////////
public:
/** \brief Returns true if any Vertex in the Face is on the boundary
* \param mesh Reference to the mesh to which the Face belongs to
*/
bool
isBoundary (const Mesh& mesh) const
{
typename Mesh::VertexAroundFaceConstCirculator circ = mesh.getVertexAroundFaceConstCirculator (*this);
const typename Mesh::VertexAroundFaceConstCirculator circ_end = circ;
do
{
if ((*circ++).isBoundary (mesh))
{
return (true);
}
} while (circ!=circ_end);
return (false);
}
//////////////////////////////////////////////////////////////////////////
// Operators
//////////////////////////////////////////////////////////////////////////
public:
/** \brief Equality comparison operator with FaceData */
bool
operator == (const FaceData& other) const
{
return (FaceData::operator == (other));
}
/** \brief Inequality comparison operator with FaceData */
bool
operator != (const FaceData& other) const
{
return (!this->operator == (other));
}
/** \brief Equality comparison operator with another Face */
bool
operator == (const Self& other) const
{
return (this->getInnerHalfEdgeIndex () == other.getInnerHalfEdgeIndex () &&
this->operator == (FaceData (other)));
}
/** \brief Inequality comparison operator with another Face */
bool
operator != (const Self& other) const
{
return (!this->operator == (other));
}
//////////////////////////////////////////////////////////////////////////
// Members
//////////////////////////////////////////////////////////////////////////
private:
/** \brief Face is marked as deleted */
bool is_deleted_;
/** \brief Index to an inner HalfEdge */
HalfEdgeIndex idx_inner_half_edge_;
};
} // End namespace pcl
#endif // PCL_GEOMETRY_FACE_HPP
| 34.996743 | 123 | 0.53239 |
zhangxaochen
|
25ad7e1add2861ae364335aea992758eca1d85aa
| 2,542 |
hpp
|
C++
|
includes/adventofcode.hpp
|
mbitokhov/AdventOfCode2017
|
a716822b2906580b03b7c5cda8e7a696961f4c40
|
[
"Unlicense"
] | null | null | null |
includes/adventofcode.hpp
|
mbitokhov/AdventOfCode2017
|
a716822b2906580b03b7c5cda8e7a696961f4c40
|
[
"Unlicense"
] | null | null | null |
includes/adventofcode.hpp
|
mbitokhov/AdventOfCode2017
|
a716822b2906580b03b7c5cda8e7a696961f4c40
|
[
"Unlicense"
] | null | null | null |
#pragma once
#include <vector>
#include <cstring>
#include <string>
constexpr long day1p1(const char input[], const size_t &index=0);
constexpr long day1p2(const char input[], const size_t &index=0);
long day2p1(const std::vector<std::vector<int>>&);
long day2p2(const std::vector<std::vector<int>>&);
long day3p1(const long&);
long day3p2(const long&);
long day4p1(const std::vector<std::vector<std::string>>&);
long day4p2(const std::vector<std::vector<std::string>>&);
unsigned long day5p1(std::vector<int>);
unsigned long day5p2(std::vector<int>);
long day6p1(std::vector<int>);
long day6p2(std::vector<int>);
std::string day7p1(std::vector<std::vector<std::string>>);
long day7p2(std::vector<std::vector<std::string>>);
long day8p1(std::vector<std::vector<std::string>>);
long day8p2(std::vector<std::vector<std::string>>);
long day9p1(std::string);
long day9p2(const std::string&);
long day10p1(const std::vector<int> &input);
std::string day10p2(std::string input);
long day11p1(const std::vector<std::string> &input);
long day11p2(const std::vector<std::string> &input);
constexpr long day1p1(const char input[], const size_t &index)
{
/*
* Sum up integers that are the same as the the value ahead of them
*
* This code is the same as the following
* if(input[index != 0]) {
* if(input[index] == input[(index+1) % strlen(input)]) {
* return (input[index] - '0') + day1p1(input,index+1);
* } else {
* return day1p1(input,index+1);
* }
* } else {
* return 0;
* }
*/
return (input[index] != 0) ?
(
(
(input[index] == input[(index + 1) % strlen(input)]) ?
input[index] - '0':
0
) + day1p1(input, index+1)
): 0;
}
constexpr long day1p2(const char input[], const size_t &index)
{
/*
* Sum up integers that are the same as the the value half way
* around the list
*
* This code is the same as the following
* if(input[index != 0]) {
* if(input[index] == input[(index+ strlen(input)/2) % strlen(input)]) {
* return (input[index] - '0') + day1p2(input,index+1);
* } else {
* return day1p2(input,index+1);
* }
* } else {
* return 0;
* }
*/
return (input[index] != 0) ?
(
(
(input[index] == input[(index + (strlen(input) / 2)) % strlen(input)]) ?
input[index] - '0':
0
) + day1p2(input, index+1)
): 0;
}
| 30.626506 | 81 | 0.579858 |
mbitokhov
|
25af18af72584b900b02d6a5ef4ad2982c61e0d0
| 564 |
hh
|
C++
|
spl/include/ast/ext_dec_list.hh
|
Alan052918/CS323-Compilers
|
d2591dbf0e8b3eb87ab507cb8633c12d587fee99
|
[
"MIT"
] | 2 |
2020-09-09T03:33:10.000Z
|
2020-11-29T15:14:01.000Z
|
spl/include/ast/ext_dec_list.hh
|
Alan052918/CS323-Compilers
|
d2591dbf0e8b3eb87ab507cb8633c12d587fee99
|
[
"MIT"
] | null | null | null |
spl/include/ast/ext_dec_list.hh
|
Alan052918/CS323-Compilers
|
d2591dbf0e8b3eb87ab507cb8633c12d587fee99
|
[
"MIT"
] | 1 |
2020-09-09T03:35:14.000Z
|
2020-09-09T03:35:14.000Z
|
#ifndef EXT_DEC_LIST_H
#define EXT_DEC_LIST_H
#include "ast.hh"
#include "../common.hh"
#include "../enums.hh"
#include "../symtable.hh"
#include "../typedef.hh"
class VarDec;
class ExtDecList : public NonterminalNode {
public:
// nonterminal member variables
std::vector<VarDec *> node_list;
// data member variables
std::vector<std::pair<std::string, std::vector<int> > > dec_list;
VarType *var_type;
ExtDecList(int fl, int ll, int fc, int lc, int rhsf);
void visit(int indent_level, SymbolTable *st) override;
};
#endif // EXT_DEC_LIST_H
| 20.888889 | 67 | 0.703901 |
Alan052918
|
25b1d4fc8bb3fe881a34d29ce566da161761ccd9
| 351 |
cpp
|
C++
|
src/apps/S3DAnalyzer/rendering/entity/stereo/anaglyphrectangleentity.cpp
|
hugbed/OpenS3D
|
4ffad16f9b0973404b59eb1424cc45f68754fe12
|
[
"BSD-3-Clause"
] | 8 |
2017-04-16T16:38:15.000Z
|
2020-04-20T03:23:15.000Z
|
src/apps/S3DAnalyzer/rendering/entity/stereo/anaglyphrectangleentity.cpp
|
hugbed/OpenS3D
|
4ffad16f9b0973404b59eb1424cc45f68754fe12
|
[
"BSD-3-Clause"
] | 40 |
2017-04-12T17:24:44.000Z
|
2017-12-21T18:41:23.000Z
|
src/apps/S3DAnalyzer/rendering/entity/stereo/anaglyphrectangleentity.cpp
|
hugbed/OpenS3D
|
4ffad16f9b0973404b59eb1424cc45f68754fe12
|
[
"BSD-3-Clause"
] | 6 |
2017-07-13T21:51:09.000Z
|
2021-05-18T16:22:03.000Z
|
#include "anaglyphrectangleentity.h"
AnaglyphRectangleEntity::AnaglyphRectangleEntity() : RectangleEntity() {}
void AnaglyphRectangleEntity::addShaders() {
m_program->addShaderFromSourceFile(QOpenGLShader::Vertex, ":/shaders/stereo/overlap.vert");
m_program->addShaderFromSourceFile(QOpenGLShader::Fragment, ":/shaders/stereo/anaglyph.frag");
}
| 39 | 96 | 0.803419 |
hugbed
|
25bfd0677c71cf52215b34f200bf2f7c4a4f5ba5
| 796 |
cpp
|
C++
|
src/mgos_homie.cpp
|
cslauritsen/mgos-garage
|
934bc266d7486be320fec806dd265c655af76d56
|
[
"MIT"
] | null | null | null |
src/mgos_homie.cpp
|
cslauritsen/mgos-garage
|
934bc266d7486be320fec806dd265c655af76d56
|
[
"MIT"
] | null | null | null |
src/mgos_homie.cpp
|
cslauritsen/mgos-garage
|
934bc266d7486be320fec806dd265c655af76d56
|
[
"MIT"
] | null | null | null |
#include "all.h"
void homie::Device::computePsk() {
int rc = 0;
unsigned char output[64];
int is384 = 0;
rc = mbedtls_sha512_ret((const unsigned char *)this->topicBase.c_str(),
this->topicBase.length(), output, is384);
if (0 == rc) {
char *hex = (char *)calloc(1, sizeof(output) * 2 + 1);
char *p = hex;
for (size_t i = 0; i < sizeof(output); i++) {
sprintf(p, "%02x", output[i]);
p += 2;
}
this->psk = std::string(static_cast<const char *>(hex));
free(hex);
} else {
LOG(LL_ERROR, ("SHA512 failed: %d", rc));
}
}
void homie::Device::publish(Message &m) {
mgos_mqtt_pub(m.topic.c_str(), m.payload.c_str(), m.payload.length(), m.qos,
m.retained);
LOG(LL_DEBUG, ("pub t=%s", m.topic.c_str()));
}
| 28.428571 | 78 | 0.556533 |
cslauritsen
|
25c0b0af1a83afb1285a1ffdd396ff228a57fe67
| 24,253 |
cpp
|
C++
|
estl/containers/unittest/vector_s_unittest.cpp
|
mlutken/playground
|
88b0fc457ae8f028b9a1f8f959b8361a645468be
|
[
"Unlicense"
] | null | null | null |
estl/containers/unittest/vector_s_unittest.cpp
|
mlutken/playground
|
88b0fc457ae8f028b9a1f8f959b8361a645468be
|
[
"Unlicense"
] | null | null | null |
estl/containers/unittest/vector_s_unittest.cpp
|
mlutken/playground
|
88b0fc457ae8f028b9a1f8f959b8361a645468be
|
[
"Unlicense"
] | null | null | null |
#include <stdexcept>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "../vector_s.hpp"
#include <vector>
using namespace testing;
using namespace estl;
class VectorSUnitTest : public testing::Test
{
public:
VectorSUnitTest() = default;
~VectorSUnitTest() override = default;
void SetUp() override
{
}
void TearDown() override;
};
void VectorSUnitTest::TearDown()
{
}
// ----------------------------------------
// --- Simple helper test element class ---
// ----------------------------------------
struct Rect {
Rect() = default;
Rect(unsigned w, unsigned h)
: width_(w),
height_(h)
{
}
unsigned width_ = 0;
unsigned height_ = 0;
};
inline bool operator== (const Rect& lhs, const Rect& rhs) {
return lhs.width_ == rhs.width_ &&
lhs.height_ == rhs.height_;
}
// -------------------
// -- Constructors ---
// -------------------
TEST_F(VectorSUnitTest, default_constructor)
{
vector_s<int, 10> v;
EXPECT_TRUE(v.empty());
EXPECT_EQ(static_cast<size_t>(0u), v.size());
EXPECT_EQ(10u, v.capacity());
EXPECT_EQ(10u, v.max_size());
}
TEST_F(VectorSUnitTest, count_constructor)
{
vector_s<std::string, 10> vs(5);
EXPECT_FALSE(vs.empty());
EXPECT_EQ(5u, vs.size());
EXPECT_EQ(std::string(""), vs[0]);
EXPECT_EQ(std::string(""), vs[1]);
EXPECT_EQ(std::string(""), vs[2]);
EXPECT_EQ(std::string(""), vs[3]);
EXPECT_EQ(std::string(""), vs[4]);
vector_s<std::string, 10> vsv(5, "value");
EXPECT_FALSE(vsv.empty());
EXPECT_EQ(5u, vsv.size());
EXPECT_EQ(std::string("value"), vsv[0]);
EXPECT_EQ(std::string("value"), vsv[1]);
EXPECT_EQ(std::string("value"), vsv[2]);
EXPECT_EQ(std::string("value"), vsv[3]);
EXPECT_EQ(std::string("value"), vsv[4]);
}
TEST_F(VectorSUnitTest, range_constructor)
{
std::vector<std::string> vs_src{"0","1","2","3","4"};
vector_s<std::string, 10> vs(vs_src.begin(), vs_src.end());
EXPECT_FALSE(vs.empty());
EXPECT_EQ(5u, vs.size());
EXPECT_EQ(std::string("0"), vs[0]);
EXPECT_EQ(std::string("1"), vs[1]);
EXPECT_EQ(std::string("2"), vs[2]);
EXPECT_EQ(std::string("3"), vs[3]);
EXPECT_EQ(std::string("4"), vs[4]);
}
TEST_F(VectorSUnitTest, copy_constructor)
{
std::vector<std::string> v_raw_src{"0","1","2","3","4"};
vector_s<std::string, 10> v_src(v_raw_src.begin(), v_raw_src.end());
vector_s<std::string, 10> vs(v_src);
EXPECT_FALSE(vs.empty());
EXPECT_EQ(5u, vs.size());
EXPECT_EQ(std::string("0"), vs[0]);
EXPECT_EQ(std::string("1"), vs[1]);
EXPECT_EQ(std::string("2"), vs[2]);
EXPECT_EQ(std::string("3"), vs[3]);
EXPECT_EQ(std::string("4"), vs[4]);
vector_s<std::string, 10> v_src_move(v_raw_src.begin(), v_raw_src.end());
vector_s<std::string, 10> vs_move(std::move(v_src_move));
EXPECT_FALSE(vs_move.empty());
EXPECT_EQ(5u, vs_move.size());
EXPECT_EQ(std::string("0"), vs_move[0]);
EXPECT_EQ(std::string("1"), vs_move[1]);
EXPECT_EQ(std::string("2"), vs_move[2]);
EXPECT_EQ(std::string("3"), vs_move[3]);
EXPECT_EQ(std::string("4"), vs_move[4]);
vector_s<std::string, 12> vs_diff_capacity(v_src);
EXPECT_FALSE(vs_diff_capacity.empty());
EXPECT_EQ(5u, vs_diff_capacity.size());
EXPECT_EQ(std::string("0"), vs_diff_capacity[0]);
EXPECT_EQ(std::string("1"), vs_diff_capacity[1]);
EXPECT_EQ(std::string("2"), vs_diff_capacity[2]);
EXPECT_EQ(std::string("3"), vs_diff_capacity[3]);
EXPECT_EQ(std::string("4"), vs_diff_capacity[4]);
vector_s<std::string, 10> v_src_move_diff_capacity(v_raw_src.begin(), v_raw_src.end());
vector_s<std::string, 12> vs_diff_capacity_move(std::move(v_src_move_diff_capacity));
EXPECT_FALSE(vs_diff_capacity_move.empty());
EXPECT_EQ(5u, vs_diff_capacity_move.size());
EXPECT_EQ(std::string("0"), vs_diff_capacity_move[0]);
EXPECT_EQ(std::string("1"), vs_diff_capacity_move[1]);
EXPECT_EQ(std::string("2"), vs_diff_capacity_move[2]);
EXPECT_EQ(std::string("3"), vs_diff_capacity_move[3]);
EXPECT_EQ(std::string("4"), vs_diff_capacity_move[4]);
}
TEST_F(VectorSUnitTest, push_back)
{
vector_s<unsigned, 6> v{};
EXPECT_EQ(0u, v.size());
// Insert 3 elements from start
v.push_back(0u); // rvalue reference (the (T&& value) overload)
v.push_back(1u); // rvalue reference (the (T&& value) overload)
v.push_back(2u); // rvalue reference (the (T&& value) overload)
EXPECT_EQ(0u, v[0]);
EXPECT_EQ(1u, v[1]);
EXPECT_EQ(2u, v[2]);
EXPECT_EQ(3u, v.size());
const unsigned v10 = 10u;
v.push_back(v10); // Normal (const T& value) overload
EXPECT_EQ(10u, v[3]);
EXPECT_EQ(4u, v.size());
}
#if (CXX_STANDARD != 98)
TEST_F(VectorSUnitTest, assignment)
{
std::vector<int> v_raw_src{0,1,2,3,4};
vector_s<int, 10> v_src(v_raw_src.begin(), v_raw_src.end());
vector_s<int, 10> v;
v = v_src;
EXPECT_FALSE(v.empty());
EXPECT_EQ(5u, v.size());
EXPECT_EQ(static_cast<int>(0), v[0]);
EXPECT_EQ(1, v[1]);
EXPECT_EQ(2, v[2]);
EXPECT_EQ(3, v[3]);
EXPECT_EQ(4, v[4]);
vector_s<std::string, 10> vs_src{"0","1","2","3","4"};
vector_s<std::string, 10> vs;
vs = vs_src;
EXPECT_FALSE(vs.empty());
EXPECT_EQ(5u, vs.size());
EXPECT_EQ(std::string("0"), vs[0]);
EXPECT_EQ(std::string("1"), vs[1]);
EXPECT_EQ(std::string("2"), vs[2]);
EXPECT_EQ(std::string("3"), vs[3]);
EXPECT_EQ(std::string("4"), vs[4]);
vector_s<std::string, 20> vsdifferent; // Different capicy from source vector!
vsdifferent = vs_src;
EXPECT_FALSE(vsdifferent.empty());
EXPECT_EQ(5u, vsdifferent.size());
EXPECT_EQ(std::string("0"), vsdifferent[0]);
EXPECT_EQ(std::string("1"), vsdifferent[1]);
EXPECT_EQ(std::string("2"), vsdifferent[2]);
EXPECT_EQ(std::string("3"), vsdifferent[3]);
EXPECT_EQ(std::string("4"), vsdifferent[4]);
}
TEST_F(VectorSUnitTest, initializer_list_constructor)
{
vector_s<int, 10> v{0,1,2,3,4};
EXPECT_FALSE(v.empty());
EXPECT_EQ(5u, v.size());
EXPECT_EQ(static_cast<int>(0), v[0]);
EXPECT_EQ(1, v[1]);
EXPECT_EQ(2, v[2]);
EXPECT_EQ(3, v[3]);
EXPECT_EQ(4, v[4]);
vector_s<std::string, 10> vs{"0","1","2","3","4"};
EXPECT_FALSE(vs.empty());
EXPECT_EQ(5u, vs.size());
EXPECT_EQ(std::string("0"), vs[0]);
EXPECT_EQ(std::string("1"), vs[1]);
EXPECT_EQ(std::string("2"), vs[2]);
EXPECT_EQ(std::string("3"), vs[3]);
EXPECT_EQ(std::string("4"), vs[4]);
}
TEST_F(VectorSUnitTest, initializer_list_assignment)
{
vector_s<int, 10> v;
v = {0,1,2,3,4};
EXPECT_FALSE(v.empty());
EXPECT_EQ(5u, v.size());
EXPECT_EQ(static_cast<int>(0), v[0]);
EXPECT_EQ(1, v[1]);
EXPECT_EQ(2, v[2]);
EXPECT_EQ(3, v[3]);
EXPECT_EQ(4, v[4]);
vector_s<std::string, 10> vs;
vs = {"0","1","2","3","4"};
EXPECT_FALSE(vs.empty());
EXPECT_EQ(5u, vs.size());
EXPECT_EQ(std::string("0"), vs[0]);
EXPECT_EQ(std::string("1"), vs[1]);
EXPECT_EQ(std::string("2"), vs[2]);
EXPECT_EQ(std::string("3"), vs[3]);
EXPECT_EQ(std::string("4"), vs[4]);
}
TEST_F(VectorSUnitTest, assign_function)
{
vector_s<std::string, 10> vsv;
vsv.assign(5, "value");
EXPECT_FALSE(vsv.empty());
EXPECT_EQ(5u, vsv.size());
EXPECT_EQ(std::string("value"), vsv[0]);
EXPECT_EQ(std::string("value"), vsv[1]);
EXPECT_EQ(std::string("value"), vsv[2]);
EXPECT_EQ(std::string("value"), vsv[3]);
EXPECT_EQ(std::string("value"), vsv[4]);
}
TEST_F(VectorSUnitTest, initializer_list_assign_function)
{
vector_s<std::string, 10> vs;
vs.assign({"00","11","22","33","44"});
EXPECT_FALSE(vs.empty());
EXPECT_EQ(5u, vs.size());
EXPECT_EQ(std::string("00"), vs[0]);
EXPECT_EQ(std::string("11"), vs[1]);
EXPECT_EQ(std::string("22"), vs[2]);
EXPECT_EQ(std::string("33"), vs[3]);
EXPECT_EQ(std::string("44"), vs[4]);
}
TEST_F(VectorSUnitTest, range_assignment)
{
std::vector<int> v_src{0,1,2,3,4};
vector_s<int, 10> v;
v.assign(v_src.begin(), v_src.end());
EXPECT_FALSE(v.empty());
EXPECT_EQ(5u, v.size());
EXPECT_EQ(static_cast<int>(0), v[0]);
EXPECT_EQ(1, v[1]);
EXPECT_EQ(2, v[2]);
EXPECT_EQ(3, v[3]);
EXPECT_EQ(4, v[4]);
std::vector<std::string> vs_src{"0","1","2","3","4"};
vector_s<std::string, 10> vs;
vs.assign(vs_src.begin(), vs_src.end());
EXPECT_FALSE(vs.empty());
EXPECT_EQ(5u, vs.size());
EXPECT_EQ(std::string("0"), vs[0]);
EXPECT_EQ(std::string("1"), vs[1]);
EXPECT_EQ(std::string("2"), vs[2]);
EXPECT_EQ(std::string("3"), vs[3]);
EXPECT_EQ(std::string("4"), vs[4]);
}
TEST_F(VectorSUnitTest, construct_out_of_range)
{
std::vector<unsigned> v_src{0u,1u,2u,3u,4u};
std::vector<unsigned> v_src_too_big{0u,1u,2u,3u,4u,5u};
using vec_t = vector_s<unsigned, 5>;
EXPECT_THROW(vec_t(6), std::range_error);
EXPECT_THROW(vec_t(6, 12u), std::range_error);
EXPECT_THROW((vec_t{0u, 1u, 2u, 3u, 4u, 5u}), std::range_error);
EXPECT_NO_THROW((vec_t(v_src.begin(), v_src.end())));
EXPECT_THROW((vec_t(v_src.end(), v_src.begin())), std::out_of_range);
EXPECT_THROW((vec_t(v_src_too_big.begin(), v_src_too_big.end())), std::range_error);
}
TEST_F(VectorSUnitTest, assign_out_of_range)
{
std::vector<unsigned> v_src{0u,1u,2u,3u,4u};
std::vector<unsigned> v_src_too_big{0u,1u,2u,3u,4u,5u};
using vec_t = vector_s<unsigned, 5>;
vec_t v;
EXPECT_THROW( (v = {0u, 1u, 2u, 3u, 4u, 5u}), std::range_error );
EXPECT_NO_THROW( v.assign(v_src.begin(), v_src.end()) );
EXPECT_THROW(v.assign(v_src.end(), v_src.begin()), std::out_of_range);
EXPECT_THROW(v.assign(v_src_too_big.begin(), v_src_too_big.end()), std::range_error);
}
// ----------------------
// --- Element access ---
// ----------------------
TEST_F(VectorSUnitTest, element_access_at)
{
vector_s<unsigned, 5> v{0u,1u,2u,3u,4u};
EXPECT_EQ(0u, v.at(0));
EXPECT_EQ(1u, v.at(1));
EXPECT_EQ(2u, v.at(2));
EXPECT_EQ(3u, v.at(3));
EXPECT_EQ(4u, v.at(4));
EXPECT_THROW(v.at(5), std::out_of_range);
// const variant of at()
const vector_s<unsigned, 5> vc{0u,1u,2u,3u,4u};
EXPECT_EQ(0u, vc.at(0));
EXPECT_EQ(1u, vc.at(1));
EXPECT_EQ(2u, vc.at(2));
EXPECT_EQ(3u, vc.at(3));
EXPECT_EQ(4u, vc.at(4));
EXPECT_THROW(vc.at(5), std::out_of_range);
}
TEST_F(VectorSUnitTest, element_access_operator_index)
{
vector_s<unsigned, 5> v{0u,1u,2u,3u,4u};
EXPECT_EQ(0u, v[0]);
EXPECT_EQ(1u, v[1]);
EXPECT_EQ(2u, v[2]);
EXPECT_EQ(3u, v[3]);
EXPECT_EQ(4u, v[4]);
EXPECT_NO_THROW(v[5]);
// const variant of at()
vector_s<unsigned, 5> vc{0u,1u,2u,3u,4u};
EXPECT_EQ(0u, vc[0]);
EXPECT_EQ(1u, vc[1]);
EXPECT_EQ(2u, vc[2]);
EXPECT_EQ(3u, vc[3]);
EXPECT_EQ(4u, vc[4]);
EXPECT_NO_THROW(vc[5]);
}
TEST_F(VectorSUnitTest, element_access_front_back)
{
vector_s<unsigned, 4> v{1u,2u,3u,4u};
EXPECT_EQ(1u, v.front());
EXPECT_EQ(4u, v.back());
// const variant of front()/back()
const vector_s<unsigned, 4> vc{1u,2u,3u,4u};
EXPECT_EQ(1u, vc.front());
EXPECT_EQ(4u, vc.back());
}
TEST_F(VectorSUnitTest, access_raw_data)
{
vector_s<unsigned, 4> v{1u,2u,3u,4u};
EXPECT_EQ(1u, *(v.data()));
EXPECT_EQ(4u, *(v.data() + 3));
// const variant of data() function
vector_s<unsigned, 4> vc{1u,2u,3u,4u};
EXPECT_EQ(1u, *(vc.data()));
EXPECT_EQ(4u, *(vc.data() + 3));
}
// -----------------
// --- Iterators ---
// -----------------
TEST_F(VectorSUnitTest, iterator_loop)
{
using vec_t = vector_s<size_t, 4>;
{
vec_t v{1u,2u,3u,4u};
size_t count = 0;
for (auto& elem : v) {
++count;
EXPECT_EQ(count, elem);
elem = count + 1u;
}
EXPECT_EQ(4u, count);
EXPECT_EQ(2u, v[0]);
EXPECT_EQ(3u, v[1]);
EXPECT_EQ(4u, v[2]);
EXPECT_EQ(5u, v[3]);
}
// const
{
const vec_t v{1u,2u,3u,4u};
size_t count = 0;
for (const auto& elem : v) {
++count;
EXPECT_EQ(count, elem);
}
EXPECT_EQ(4u, count);
}
}
TEST_F(VectorSUnitTest, range_for_loop)
{
using vec_t = vector_s<size_t, 4>;
{
vec_t v{1u,2u,3u,4u};
size_t count = 0;
for (auto& e : v ) {
++count;
EXPECT_EQ(count, e);
e = count + 1u;
}
EXPECT_EQ(4u, count);
EXPECT_EQ(2u, v[0]);
EXPECT_EQ(3u, v[1]);
EXPECT_EQ(4u, v[2]);
EXPECT_EQ(5u, v[3]);
}
// const
{
const vec_t v{1u,2u,3u,4u};
size_t count = 0;
for (const auto& e : v ) {
++count;
EXPECT_EQ(count, e);
}
EXPECT_EQ(4u, count);
}
}
TEST_F(VectorSUnitTest, reverse_iterator_loop)
{
using vec_t = vector_s<size_t, 4>;
{
vec_t v{4u,3u,2u,1u};
size_t count = 0;
for (vec_t::reverse_iterator it = v.rbegin(); it != v.rend(); ++it) {
++count;
EXPECT_EQ(count, *it);
*it = count + 1u;
}
EXPECT_EQ(4u, count);
EXPECT_EQ(5u, v[0]);
EXPECT_EQ(4u, v[1]);
EXPECT_EQ(3u, v[2]);
EXPECT_EQ(2u, v[3]);
}
// const
{
const vec_t v{4u,3u,2u,1u};
size_t count = 0;
for (auto it = v.crbegin(); it != v.crend(); ++it) {
++count;
EXPECT_EQ(count, *it);
}
EXPECT_EQ(4u, count);
}
}
// ----------------
// --- Capacity ---
// ----------------
// NOTE: Tested in 'default_constructor_test'
// -----------------
// --- Modifiers ---
// -----------------
struct S {
S() = default;
explicit S(size_t v) : val(v) { ++count_constructor; }
S( const S& other) = default;
~S() { ++count_destructor; }
size_t val = 0;
static size_t count_constructor;
static size_t count_destructor;
};
size_t S::count_constructor = 0;
size_t S::count_destructor = 0;
TEST_F(VectorSUnitTest, clear)
{
using vec_t = vector_s<S, 10>;
vec_t v{S(1u),S(2u),S(3u),S(4u)};
EXPECT_FALSE(v.empty());
EXPECT_EQ(4u, v.size());
EXPECT_EQ(10u, v.capacity());
EXPECT_EQ(10u, v.max_size());
EXPECT_EQ(4u, S::count_constructor);
EXPECT_EQ(4u, S::count_destructor);
v.clear();
EXPECT_EQ(static_cast<size_t>(0u), v.size());
EXPECT_EQ(8u, S::count_destructor);
}
TEST_F(VectorSUnitTest, insert_single_element)
{
vector_s<std::string, 10> v{"0","1","2"};
EXPECT_EQ("0", v[0]);
EXPECT_EQ("1", v[1]);
EXPECT_EQ("2", v[2]);
EXPECT_EQ(3u, v.size());
const auto it1 = v.insert(v.begin(), "10");
EXPECT_EQ("10", *it1);
EXPECT_EQ("10", v[0]);
EXPECT_EQ("0", v[1]);
EXPECT_EQ("1", v[2]);
EXPECT_EQ("2", v[3]);
EXPECT_EQ(4u, v.size());
const auto it2 = v.insert(v.begin()+2, "20");
EXPECT_EQ("20", *it2);
EXPECT_EQ("10", v[0]);
EXPECT_EQ("0", v[1]);
EXPECT_EQ("20", v[2]);
EXPECT_EQ("1", v[3]);
EXPECT_EQ("2", v[4]);
EXPECT_EQ(5u, v.size());
const auto it3 = v.insert(v.end(), "50");
EXPECT_EQ("50", *it3);
EXPECT_EQ("10", v[0]);
EXPECT_EQ("0", v[1]);
EXPECT_EQ("20", v[2]);
EXPECT_EQ("1", v[3]);
EXPECT_EQ("2", v[4]);
EXPECT_EQ("50", v[5]);
EXPECT_EQ(6u, v.size());
}
TEST_F(VectorSUnitTest, insert_multiple_elements)
{
vector_s<unsigned, 10> v{0u,1u,2u};
EXPECT_EQ(0u, v[0]);
EXPECT_EQ(1u, v[1]);
EXPECT_EQ(2u, v[2]);
EXPECT_EQ(3u, v.size());
// Insert zero elements
v.insert(v.begin(), 0, 10u);
EXPECT_EQ(0u, v[0]);
EXPECT_EQ(1u, v[1]);
EXPECT_EQ(2u, v[2]);
EXPECT_EQ(3u, v.size());
// Insert 3 elements from start
const auto it1 = v.insert(v.begin(), 3, 10u);
EXPECT_EQ(10u, *it1);
EXPECT_EQ(10u, *(it1 + 1));
EXPECT_EQ(10u, *(it1 + 2));
EXPECT_EQ(10u, v[0]);
EXPECT_EQ(10u, v[1]);
EXPECT_EQ(10u, v[2]);
EXPECT_EQ(0u, v[3]);
EXPECT_EQ(1u, v[4]);
EXPECT_EQ(2u, v[5]);
EXPECT_EQ(6u, v.size());
// Insert 2 elements in the middle
const auto it2 = v.insert(v.begin()+3, 2, 20u);
EXPECT_EQ(20u, *it2);
EXPECT_EQ(20u, *(it2 + 1));
EXPECT_EQ(10u, v[0]);
EXPECT_EQ(10u, v[1]);
EXPECT_EQ(10u, v[2]);
EXPECT_EQ(20u, v[3]);
EXPECT_EQ(20u, v[4]);
EXPECT_EQ(0u, v[5]);
EXPECT_EQ(1u, v[6]);
EXPECT_EQ(2u, v[7]);
EXPECT_EQ(8u, v.size());
// Insert 2 elements 'in' the end
const auto it3 = v.insert(v.end(), 2, 50u);
EXPECT_EQ(50u, *it3);
EXPECT_EQ(50u, *(it3 + 1));
EXPECT_EQ(10u, v[0]);
EXPECT_EQ(10u, v[1]);
EXPECT_EQ(10u, v[2]);
EXPECT_EQ(20u, v[3]);
EXPECT_EQ(20u, v[4]);
EXPECT_EQ(0u, v[5]);
EXPECT_EQ(1u, v[6]);
EXPECT_EQ(2u, v[7]);
EXPECT_EQ(50u, v[8]);
EXPECT_EQ(50u, v[9]);
EXPECT_EQ(10u, v.size());
}
TEST_F(VectorSUnitTest, insert_iterator_range)
{
constexpr std::array<unsigned, 3> src{10u,20u,30u};
vector_s<unsigned, 12> v{0u,1u,2u};
EXPECT_EQ(0u, v[0]);
EXPECT_EQ(1u, v[1]);
EXPECT_EQ(2u, v[2]);
EXPECT_EQ(3u, v.size());
// Insert zero elements
v.insert(v.begin(), src.begin(), src.begin());
EXPECT_EQ(0u, v[0]);
EXPECT_EQ(1u, v[1]);
EXPECT_EQ(2u, v[2]);
EXPECT_EQ(3u, v.size());
// Insert 3 elements from start
const auto it1 = v.insert(v.begin(), src.begin(), src.end());
EXPECT_EQ(v.begin(), it1);
EXPECT_EQ(src[0], *it1);
EXPECT_EQ(src[1], *(it1 + 1));
EXPECT_EQ(src[2], *(it1 + 2));
EXPECT_EQ(10u, v[0]);
EXPECT_EQ(20u, v[1]);
EXPECT_EQ(30u, v[2]);
EXPECT_EQ(0u, v[3]);
EXPECT_EQ(1u, v[4]);
EXPECT_EQ(2u, v[5]);
EXPECT_EQ(6u, v.size());
// Insert 3 elements in the middle
const auto it2 = v.insert(v.begin()+3, src.begin(), src.end());
EXPECT_EQ(v.begin()+3, it2);
EXPECT_EQ(src[0], *it2);
EXPECT_EQ(src[1], *(it2 + 1));
EXPECT_EQ(src[2], *(it2 + 2));
EXPECT_EQ(10u, v[0]);
EXPECT_EQ(20u, v[1]);
EXPECT_EQ(30u, v[2]);
EXPECT_EQ(10u, v[3]);
EXPECT_EQ(20u, v[4]);
EXPECT_EQ(30u, v[5]);
EXPECT_EQ(0u, v[6]);
EXPECT_EQ(1u, v[7]);
EXPECT_EQ(2u, v[8]);
EXPECT_EQ(9u, v.size());
// Insert 3 elements 'in' the end
const auto it3 = v.insert(v.end(), src.begin(), src.end());
EXPECT_EQ(v.begin()+9, it3);
EXPECT_EQ(src[0], *it3);
EXPECT_EQ(src[1], *(it3 + 1));
EXPECT_EQ(src[2], *(it3 + 2));
EXPECT_EQ(10u, v[0]);
EXPECT_EQ(20u, v[1]);
EXPECT_EQ(30u, v[2]);
EXPECT_EQ(10u, v[3]);
EXPECT_EQ(20u, v[4]);
EXPECT_EQ(30u, v[5]);
EXPECT_EQ(0u, v[6]);
EXPECT_EQ(1u, v[7]);
EXPECT_EQ(2u, v[8]);
EXPECT_EQ(10u, v[9]);
EXPECT_EQ(20u, v[10]);
EXPECT_EQ(30u, v[11]);
EXPECT_EQ(12u, v.size());
}
TEST_F(VectorSUnitTest, insert_initializer_list)
{
vector_s<unsigned, 12> v{0u,1u,2u};
EXPECT_EQ(0u, v[0]);
EXPECT_EQ(1u, v[1]);
EXPECT_EQ(2u, v[2]);
EXPECT_EQ(3u, v.size());
// Insert 3 elements from start
v.insert(v.begin(), {10u,20u,30u});
EXPECT_EQ(10u, v[0]);
EXPECT_EQ(20u, v[1]);
EXPECT_EQ(30u, v[2]);
EXPECT_EQ(0u, v[3]);
EXPECT_EQ(1u, v[4]);
EXPECT_EQ(2u, v[5]);
EXPECT_EQ(6u, v.size());
// Insert 3 elements in the middle
v.insert(v.begin()+3, {10u,20u,30u});
EXPECT_EQ(10u, v[0]);
EXPECT_EQ(20u, v[1]);
EXPECT_EQ(30u, v[2]);
EXPECT_EQ(10u, v[3]);
EXPECT_EQ(20u, v[4]);
EXPECT_EQ(30u, v[5]);
EXPECT_EQ(0u, v[6]);
EXPECT_EQ(1u, v[7]);
EXPECT_EQ(2u, v[8]);
EXPECT_EQ(9u, v.size());
// Insert 3 elements 'in' the end
v.insert(v.end(), {10u,20u,30u});
EXPECT_EQ(10u, v[0]);
EXPECT_EQ(20u, v[1]);
EXPECT_EQ(30u, v[2]);
EXPECT_EQ(10u, v[3]);
EXPECT_EQ(20u, v[4]);
EXPECT_EQ(30u, v[5]);
EXPECT_EQ(0u, v[6]);
EXPECT_EQ(1u, v[7]);
EXPECT_EQ(2u, v[8]);
EXPECT_EQ(10u, v[9]);
EXPECT_EQ(20u, v[10]);
EXPECT_EQ(30u, v[11]);
EXPECT_EQ(12u, v.size());
}
TEST_F(VectorSUnitTest, emplace)
{
vector_s<Rect, 6> v{ {1u,1u}, {2u,2u}, {3u,3u}, {4u,4u} };
EXPECT_EQ(Rect(1u, 1u), v[0]);
EXPECT_EQ(Rect(2u, 2u), v[1]);
EXPECT_EQ(Rect(3u, 3u), v[2]);
EXPECT_EQ(Rect(4u, 4u), v[3]);
EXPECT_EQ(4u, v.size());
const auto it = v.emplace(v.begin()+1, 10u, 10u);
EXPECT_EQ(Rect(10u, 10u), *it);
EXPECT_EQ(5u, v.size());
EXPECT_EQ(Rect(1u, 1u), v[0]);
EXPECT_EQ(Rect(10u, 10u), v[1]);
EXPECT_EQ(Rect(2u, 2u), v[2]);
EXPECT_EQ(Rect(3u, 3u), v[3]);
EXPECT_EQ(Rect(4u, 4u), v[4]);
}
TEST_F(VectorSUnitTest, erase_single_element)
{
vector_s<unsigned, 12> v{0u, 1u, 2u, 3u, 4u, 5u};
EXPECT_EQ(6u, v.size());
// Erase one element from the beginning
const auto it1 = v.erase(v.begin());
EXPECT_EQ(1u, *it1);
EXPECT_EQ(v.begin(), it1);
EXPECT_EQ(5u, v.size());
EXPECT_EQ(1u, v[0]);
EXPECT_EQ(2u, v[1]);
EXPECT_EQ(3u, v[2]);
EXPECT_EQ(4u, v[3]);
EXPECT_EQ(5u, v[4]);
// Erase one element from the middle
const auto it2 = v.erase(v.begin()+2);
EXPECT_EQ(4u, *it2);
EXPECT_EQ(v.begin()+2, it2);
EXPECT_EQ(4u, v.size());
EXPECT_EQ(1u, v[0]);
EXPECT_EQ(2u, v[1]);
EXPECT_EQ(4u, v[2]);
EXPECT_EQ(5u, v[3]);
// Erase last element
const auto it3 = v.erase(v.end()-1);
EXPECT_EQ(v.end(), it3);
EXPECT_EQ(3u, v.size());
EXPECT_EQ(1u, v[0]);
EXPECT_EQ(2u, v[1]);
EXPECT_EQ(4u, v[2]);
}
TEST_F(VectorSUnitTest, erase_range_of_elements)
{
vector_s<unsigned, 12> v{0u, 1u, 2u, 3u, 4u, 5u, 6u, 7u, 8u, 9u, 10u, 11u};
EXPECT_EQ(12u, v.size());
// Erase 3 elements from the beginning
const auto it1 = v.erase(v.begin(), v.begin() +3);
EXPECT_EQ(v.begin(), it1);
EXPECT_EQ(3u, *it1);
EXPECT_EQ(9u, v.size());
EXPECT_EQ(3u, v[0]);
EXPECT_EQ(4u, v[1]);
EXPECT_EQ(5u, v[2]);
EXPECT_EQ(6u, v[3]);
EXPECT_EQ(7u, v[4]);
EXPECT_EQ(8u, v[5]);
EXPECT_EQ(9u, v[6]);
EXPECT_EQ(10u, v[7]);
EXPECT_EQ(11u, v[8]);
// Erase 3 elements from the middle
const auto it2 = v.erase(v.begin()+3, v.begin()+6);
EXPECT_EQ(v.begin()+3, it2);
EXPECT_EQ(9u, *it2);
EXPECT_EQ(6u, v.size());
EXPECT_EQ(3u, v[0]);
EXPECT_EQ(4u, v[1]);
EXPECT_EQ(5u, v[2]);
EXPECT_EQ(9u, v[3]);
EXPECT_EQ(10u, v[4]);
EXPECT_EQ(11u, v[5]);
// Erase 3 last element
const auto it3 = v.erase(v.end()-3, v.end());
EXPECT_EQ(v.end(), it3);
EXPECT_EQ(3u, v.size());
EXPECT_EQ(3u, v[0]);
EXPECT_EQ(4u, v[1]);
EXPECT_EQ(5u, v[2]);
}
TEST_F(VectorSUnitTest, emplace_back)
{
vector_s<Rect, 6> v{};
EXPECT_EQ(0u, v.size());
const auto& ret1 = v.emplace_back(1u,2u);
EXPECT_EQ(Rect(1u, 2u), ret1);
EXPECT_EQ(Rect(1u, 2u), v.back());
EXPECT_EQ(1u, v.size());
const auto& ret2 = v.emplace_back(2u,3u);
EXPECT_EQ(Rect(2u, 3u), ret2);
EXPECT_EQ(Rect(2u, 3u), v.back());
EXPECT_EQ(2u, v.size());
}
TEST_F(VectorSUnitTest, pop_back)
{
vector_s<unsigned, 12> v{0u, 1u, 2u, 3u, 4u, 5u};
EXPECT_EQ(6u, v.size());
EXPECT_EQ(5u, v.back());
v.pop_back();
EXPECT_EQ(4u, v.back());
EXPECT_EQ(5u, v.size());
v.pop_back();
EXPECT_EQ(3u, v.back());
EXPECT_EQ(4u, v.size());
}
TEST_F(VectorSUnitTest, swap)
{
// NOTE: The reason for using different capacities here
// is to exercise the mixed-capacity constructors, assigment
// and equality functions/operators.
vector_s<unsigned, 12> original_v1{0u, 1u, 2u, 3u, 4u, 5u};
vector_s<unsigned, 11> original_v2{0u, 1u, 2u};
vector_s<unsigned, 10> v1 = original_v1;
vector_s<unsigned, 9> v2 = original_v2;
EXPECT_EQ(6u, v1.size());
EXPECT_EQ(3u, v2.size());
v1.swap(v2);
EXPECT_EQ(6u, v2.size());
EXPECT_EQ(3u, v1.size());
EXPECT_EQ(v1, original_v2);
EXPECT_EQ(v2, original_v1);
}
#endif // (CXX_STANDARD != 98)
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 27.06808 | 91 | 0.57564 |
mlutken
|
25c1dcf30031bb224d23644a9edb4afa00324808
| 1,255 |
cpp
|
C++
|
noise.cpp
|
ursinus-cs174-s2022/HW2_Steganography
|
af8ad24dbb6be42b5c4cb9f46b66cd8abfc3d3fe
|
[
"Apache-2.0"
] | null | null | null |
noise.cpp
|
ursinus-cs174-s2022/HW2_Steganography
|
af8ad24dbb6be42b5c4cb9f46b66cd8abfc3d3fe
|
[
"Apache-2.0"
] | null | null | null |
noise.cpp
|
ursinus-cs174-s2022/HW2_Steganography
|
af8ad24dbb6be42b5c4cb9f46b66cd8abfc3d3fe
|
[
"Apache-2.0"
] | null | null | null |
/**
* @file grayscale.cpp
* @author Chris Tralie
*
* Purpose: To add a certain amount of noise to an image
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <sstream>
#include "simplecanvas/SimpleCanvas.h"
#include "randutils.h"
using namespace std;
/**
* @brief Add noise to every channel of every pixel
*
* @param image Image to which to add noise
* @param snr Signal to noise ratio
*/
void noise(SimpleCanvas& image, float snr) {
RandFloat r;
float amt = 255/snr;
for (int i = 0; i < image.height; i++) {
for (int j = 0; j < image.width; j++) {
for (int k = 0; k < 3; k++) {
float x = (float)image.data[i][j][k];
x += amt*(r.nextFloat()-0.5);
if (x > 255) {
x = 255;
}
if (x < 0) {
x = 0;
}
image.data[i][j][k] = (uint8_t)x;
}
}
}
}
int main(int argc, char** argv) {
if (argc < 4) {
printf("Usage: ./noise <image in> <snr> <image out>\n");
return 1;
}
SimpleCanvas image(argv[1]);
float snr = atof(argv[2]);
noise(image, snr);
image.write(argv[3]);
return 0;
}
| 22.818182 | 64 | 0.495618 |
ursinus-cs174-s2022
|
5ae569aec9055db273a7666f15859ef8ee7f7031
| 544 |
cpp
|
C++
|
Sorting Algorithms/insertionSort.cpp
|
Raghav1806/Data-Structures-CSL-201-
|
2e4e3c67e3ff28ac6a9e1f06fe12a2864b17d177
|
[
"MIT"
] | null | null | null |
Sorting Algorithms/insertionSort.cpp
|
Raghav1806/Data-Structures-CSL-201-
|
2e4e3c67e3ff28ac6a9e1f06fe12a2864b17d177
|
[
"MIT"
] | null | null | null |
Sorting Algorithms/insertionSort.cpp
|
Raghav1806/Data-Structures-CSL-201-
|
2e4e3c67e3ff28ac6a9e1f06fe12a2864b17d177
|
[
"MIT"
] | null | null | null |
// insertion sort algorithm
#include <iostream>
using namespace std;
int main(){
int size, i, j, curr;
cout << "Enter the size of array to be sorted\n";
cin >> size;
int A[size];
cout << "Enter the elements of array\n";
for(i = 0; i < size; i++)
cin >> A[i];
for(i = 0; i < size - 1; i++){
j = i + 1;
curr = A[j];
while(j > 0 && A[j - 1] > A[j]){
A[j] = A[j - 1];
A[j - 1] = curr;
j--;
}
}
cout << "The sorted array is\n";
for(i = 0; i < size; i++)
cout << A[i] << " ";
cout << "\n";
return 0;
}
| 16 | 50 | 0.483456 |
Raghav1806
|
5ae97766fa4dcf353527302a99c555db13297345
| 6,580 |
hpp
|
C++
|
include/mxx/type_traits.hpp
|
asrivast28/mxx
|
75a4a7b8b04922f070991f1d9a4351e339a0d848
|
[
"Apache-2.0"
] | 76 |
2015-09-28T22:06:07.000Z
|
2022-03-25T17:47:34.000Z
|
include/mxx/type_traits.hpp
|
asrivast28/mxx
|
75a4a7b8b04922f070991f1d9a4351e339a0d848
|
[
"Apache-2.0"
] | 23 |
2015-10-29T17:35:51.000Z
|
2021-09-07T09:56:56.000Z
|
include/mxx/type_traits.hpp
|
asrivast28/mxx
|
75a4a7b8b04922f070991f1d9a4351e339a0d848
|
[
"Apache-2.0"
] | 20 |
2015-10-29T17:18:01.000Z
|
2021-05-12T16:41:20.000Z
|
#ifndef MXX_TYPE_TRAITS
#define MXX_TYPE_TRAITS
#include <type_traits>
#include <vector>
#include <string>
namespace mxx {
// source for testing if member functions are available: http://stackoverflow.com/a/16824239/4639394
#define MXX_DEFINE_HAS_MEMBER(member) \
template<typename, typename T> \
struct has_member_ ## member {}; \
\
template<typename C, typename Ret, typename... Args> \
struct has_member_ ## member <C, Ret(Args...)> { \
private: \
template<typename T> \
static constexpr auto check(T*) \
-> typename \
std::is_same< \
decltype( std::declval<T>(). member ( std::declval<Args>()... ) ), \
Ret /* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */ \
>::type; /* attempt to call it and see if the return type is correct */ \
template <typename> \
static constexpr std::false_type check(...); \
typedef decltype(check<C>(0)) type; \
public: \
static constexpr bool value = type::value; \
};
#define MXX_DEFINE_HAS_STATIC_MEMBER(member) \
template<typename, typename T> \
struct has_static_member_ ## member {}; \
\
template<typename C, typename Ret, typename... Args> \
struct has_static_member_ ## member <C, Ret(Args...)> { \
private: \
template<typename T> \
static constexpr auto check(T*) \
-> typename \
std::is_same< \
decltype(T:: member ( std::declval<Args>()... ) ), \
Ret /* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */ \
>::type; /* attempt to call it and see if the return type is correct */ \
template<typename> \
static constexpr std::false_type check(...); \
typedef decltype(check<C>(0)) type; \
public: \
static constexpr bool value = type::value; \
};
#define MXX_DEFINE_IS_GLOBAL_FUNC(fname) \
template<typename U> \
struct is_global_func_ ## fname { \
private: \
typedef U signature; \
template <typename T, T> struct has_matching_sig; \
template <typename T> \
static std::true_type check(has_matching_sig<T*,& :: fname>*); \
template <typename T> \
static std::false_type check(...); \
typedef decltype(check<signature>(0)) type; \
public: \
static constexpr bool value = type::value; \
};
// own implementation of the HAS_MEMBER struct
template <typename, typename>
struct has_member_size : std::false_type {};
template <typename C, typename R, typename... Args>
struct has_member_size<C, R(Args...)> : std::integral_constant<bool,
std::is_same<decltype(std::declval<C>().size(std::declval<Args>()...)), R>::value> {};
// type traits returning whether the type `C` has the typedef member ::value_type
#define MXX_DEFINE_HAS_TYPEDEF(type_name) \
template <typename C, typename Enable = void> \
struct has_typedef_ ## type_name : std::false_type {}; \
template <typename C> \
struct has_typedef_ ## type_name <C, typename std::enable_if< \
!std::is_same<typename C:: type_name ,void>::value>::type> \
: std::true_type {};
MXX_DEFINE_HAS_TYPEDEF(value_type)
MXX_DEFINE_HAS_TYPEDEF(iterator)
MXX_DEFINE_HAS_TYPEDEF(const_iterator)
MXX_DEFINE_HAS_MEMBER(data)
//MXX_DEFINE_HAS_MEMBER(size)
MXX_DEFINE_HAS_MEMBER(resize)
MXX_DEFINE_HAS_MEMBER(end)
MXX_DEFINE_HAS_MEMBER(begin)
MXX_DEFINE_HAS_STATIC_MEMBER(datatype)
MXX_DEFINE_HAS_MEMBER(datatype)
// TODO: build this into the mxx/datatype structures
template <typename T, typename Enable = void>
struct has_datatype : std::false_type {};
/***********************************************************
* Compile-time reflection for members begin() and end() *
***********************************************************/
template <typename C, typename Enable = void>
struct has_nonconst_begin_end : std::false_type {};
template <typename C>
struct has_nonconst_begin_end<C, typename std::enable_if<has_typedef_iterator<C>::value>::type>
: std::integral_constant<bool,
has_member_begin<typename std::remove_const<C>::type, typename C::iterator()>::value
&& has_member_end<typename std::remove_const<C>::type, typename C::iterator()>::value> {};
template <typename C, typename Enable = void>
struct has_const_begin_end : std::false_type {};
template <typename C>
struct has_const_begin_end<C, typename std::enable_if<has_typedef_iterator<C>::value>::type>
: std::integral_constant<bool,
has_member_begin<const typename std::remove_const<C>::type, typename C::const_iterator()>::value
&& has_member_end<const typename std::remove_const<C>::type, typename C::const_iterator()>::value> {};
template <typename C>
struct has_begin_end : std::integral_constant<bool,
has_nonconst_begin_end<C>::value
&& has_const_begin_end<C>::value> {};
/**************************************************************
* Compile-time determination whether a type is a container *
**************************************************************/
/*
template <typename C, typename Enable = void>
struct is_container : std::false_type {};
*/
template <typename C, typename Enable = void>
struct is_container : std::integral_constant<bool,
has_begin_end<C>::value> {};
template <typename C, typename Enable = void>
struct is_flat_container : std::false_type {};
template <typename C>
struct is_flat_container<C, typename std::enable_if<has_typedef_value_type<C>::value>::type>
: std::integral_constant<bool,
is_container<C>::value
&& mxx::has_datatype<typename C::value_type>::value> {};
template <typename C, typename Enable = void>
struct is_contiguous_container : std::false_type {};
template <typename T, typename A>
struct is_contiguous_container<std::vector<T,A>> : std::true_type {};
template <typename C, typename CT, typename A>
struct is_contiguous_container<std::basic_string<C, CT, A>> : std::true_type {};
// anything that's templated by at least its value type T and has the member functions
// size_t size(), void resize(size_t size), and T* data()
template <template <typename, typename...> class C, typename T, typename... Targs>
struct is_contiguous_container<C<T,Targs...>> : std::integral_constant<bool,
has_member_data<C<T,Targs...>, T*()>::value &&
has_member_size<C<T,Targs...>, std::size_t()>::value &&
has_member_resize<C<T,Targs...>, void(std::size_t)>::value> {};
template <typename C>
struct is_flat_contiguous_container : std::integral_constant<bool,
is_contiguous_container<C>::value && is_flat_container<C>::value> {};
template <typename C, typename Enable = void>
struct is_flat_type : std::integral_constant<bool,
is_contiguous_container<C>::value> {};
} // namespace mxx
#endif // MXX_TYPE_TRAITS
| 35.956284 | 106 | 0.670365 |
asrivast28
|
5aea383e89d1bf70f266b1ec1b9d000edd891f76
| 6,986 |
cpp
|
C++
|
wled00/Effect/snowflake/StarBurst.cpp
|
mdraper81/WLED
|
408696ef02f7b2dd66300a6a2ddb67a74d037b88
|
[
"MIT"
] | null | null | null |
wled00/Effect/snowflake/StarBurst.cpp
|
mdraper81/WLED
|
408696ef02f7b2dd66300a6a2ddb67a74d037b88
|
[
"MIT"
] | null | null | null |
wled00/Effect/snowflake/StarBurst.cpp
|
mdraper81/WLED
|
408696ef02f7b2dd66300a6a2ddb67a74d037b88
|
[
"MIT"
] | null | null | null |
#include "StarBurst.h"
namespace Effect
{
namespace Snowflake
{
/*
** ============================================================================
** Constructor
** ============================================================================
*/
StarBurst::StarBurst(NeoPixelWrapper* pixelWrapper, Data* effectData)
: BaseSnowFlake(pixelWrapper, effectData)
, mEffectLengthInTicks(0)
, mHoldLengthInTicks(0)
, mCurrentTick(0)
{
}
/*
** ============================================================================
** Destructor
** ============================================================================
*/
StarBurst::~StarBurst()
{
}
/*
** ============================================================================
** Run the current effect
** ============================================================================
*/
bool StarBurst::runEffect(uint32_t delta)
{
incrementRunningTime(delta);
updateEffectData();
// This effect will light one LED at a time all the way up the length of the
// arm and to the ends of the large chevron. This will take a total number
// of ticks equal to the arm length and half the large chevron length (in case
// the large chevron length is odd we'll round up);
mEffectLengthInTicks = mArmLength + getNumberOfTicksForLargeChevron();
// We'll hold the effect for half the time that it took to light up all LEDs
mHoldLengthInTicks = mEffectLengthInTicks / 2;
mCurrentTick = getCurrentTick() % (mEffectLengthInTicks + mHoldLengthInTicks);
if (mCurrentTick == 0)
{
// Turn off all LEDs to reset the effect
setPixelColorForRange(mStartingAddress, mNumLEDs, 0x00000000);
}
else
{
// Process the effect to turn on the next LED (or hold the effect)
for (int armIndex = 0; armIndex < mNumberOfArms; ++armIndex)
{
processArm(armIndex);
}
}
}
/*
** ============================================================================
** Process the LEDs in the arm with the given index. This will turn on the
** correct LEDs for this arm
** ============================================================================
*/
void StarBurst::processArm(int armIndex)
{
// Turn on the correct number of LEDs in the arm for where we are in the
// effect (what tick we are on).
const uint16_t armStartingAddress = getStartingAddressForArmIndex(armIndex);
for (int armAddressIndex = 0; armAddressIndex < mArmLength; ++armAddressIndex)
{
uint16_t address = armStartingAddress + armAddressIndex;
if (mCurrentTick > armAddressIndex)
{
// This LED should be on
const int effectOffset = armAddressIndex;
setPixelColorFromPalette(address, effectOffset);
}
else
{
// The LED should be off since we haven't gotten to this address yet
setPixelColor(address, 0x00000000);
}
}
// If the current tick is greater than the small chevron position then we
// should start lighting up LEDs in the small chevron
if (mCurrentTick > mSmallChevronPosition)
{
processSmallChevron(armIndex);
}
// If the current tick is greater than the arm length then we have reached
// the end of the arm and should start lighting up LEDs in the large chevron
if (mCurrentTick > mArmLength)
{
processLargeChevron(armIndex);
}
}
/*
** ============================================================================
** Process the LEDs in the small chevron for the arm with the given index.
** This will turn on the correct LEDs.
** ============================================================================
*/
void StarBurst::processSmallChevron(int armIndex)
{
// This is a paranoia check to ensure that we only turn the LEDs on if we
// have reached the small chevron
if (mCurrentTick > mSmallChevronPosition)
{
const uint8_t numTicksToProcess = getNumberOfTicksForSmallChevron();
const uint16_t smallChevronStartingAddress_Left = getStartingAddressForSmallChevron(armIndex, true);
const uint16_t smallChevronStartingAddress_Right = getStartingAddressForSmallChevron(armIndex, false);
for (uint8_t chevronAddressIndex = 0; chevronAddressIndex < numTicksToProcess; ++chevronAddressIndex)
{
const uint16_t leftAddress = smallChevronStartingAddress_Left + chevronAddressIndex;
const uint16_t rightAddress = smallChevronStartingAddress_Right + chevronAddressIndex;
if (mCurrentTick > mSmallChevronPosition + chevronAddressIndex)
{
// This LED should be on
const int effectOffset = mSmallChevronPosition + chevronAddressIndex;
setPixelColorFromPalette(leftAddress, effectOffset);
setPixelColorFromPalette(rightAddress, effectOffset);
}
else
{
// The LED should be off since we haven't gotten to this address yet
setPixelColor(leftAddress, 0x00000000);
setPixelColor(rightAddress, 0x00000000);
}
}
}
}
/*
** ============================================================================
** Process the LEDs in the large chevron for the arm with the given index.
** This will turn on the correct LEDs.
** ============================================================================
*/
void StarBurst::processLargeChevron(int armIndex)
{
// This is a paranoia check to ensure that we only turn the LEDs on if we
// have reached the large chevron
if (mCurrentTick > mArmLength)
{
const uint8_t numTicksToProcess = getNumberOfTicksForLargeChevron();
const uint16_t largeChevronStartingAddress_Left = getStartingAddressForLargeChevron(armIndex, true);
const uint16_t largeChevronStartingAddress_Right = getStartingAddressForLargeChevron(armIndex, false);
for (uint8_t chevronAddressIndex = 0; chevronAddressIndex < numTicksToProcess; ++chevronAddressIndex)
{
const uint16_t leftAddress = largeChevronStartingAddress_Left + chevronAddressIndex;
const uint16_t rightAddress = largeChevronStartingAddress_Right + chevronAddressIndex;
if (mCurrentTick > mArmLength + chevronAddressIndex)
{
// This LED should be on
const int effectOffset = mArmLength + chevronAddressIndex;
setPixelColorFromPalette(leftAddress, effectOffset);
setPixelColorFromPalette(rightAddress, effectOffset);
}
else
{
// The LED should be off since we haven't gotten to this address yet
setPixelColor(leftAddress, 0x00000000);
setPixelColor(rightAddress, 0x00000000);
}
}
}
}
} // namespace Effect::Snowflake
} // namespace Effect
| 38.174863 | 110 | 0.577584 |
mdraper81
|
5af27f1563b3385df9acbc8fd8d973b92daedaa5
| 548 |
cpp
|
C++
|
Compiler/IntConstantExpression.cpp
|
acbarrentine/Mika
|
8d88f015360c1ab731da0fda1281a3327dcb9ec9
|
[
"Unlicense"
] | null | null | null |
Compiler/IntConstantExpression.cpp
|
acbarrentine/Mika
|
8d88f015360c1ab731da0fda1281a3327dcb9ec9
|
[
"Unlicense"
] | null | null | null |
Compiler/IntConstantExpression.cpp
|
acbarrentine/Mika
|
8d88f015360c1ab731da0fda1281a3327dcb9ec9
|
[
"Unlicense"
] | null | null | null |
#include "stdafx.h"
#include "IntConstantExpression.h"
#include "Compiler.h"
#include "ObjectFileHelper.h"
void IntConstantExpression::ResolveType(SymbolTable&)
{
mType = GCompiler.GetIntType();
Token& tok = GCompiler.GetToken(mRootToken);
mValue = tok.GetIntValue();
}
void IntConstantExpression::GenCode(ObjectFileHelper& helper)
{
mResultRegister = new IRRegisterOperand;
IRInstruction* op = helper.EmitInstruction(CopyConstantToStack, mRootToken);
op->SetOperand(0, mResultRegister);
op->SetOperand(1, new IRIntOperand(mValue));
}
| 23.826087 | 77 | 0.775547 |
acbarrentine
|
5af511673b65874c9ebf3e5e97032f7758235e5c
| 1,073 |
hh
|
C++
|
src/lisp/map.hh
|
kuriboshi/lips
|
f9f4838a95ff574fb7a627a3eb966b38b6f430f7
|
[
"Apache-2.0"
] | 1 |
2020-11-10T11:02:21.000Z
|
2020-11-10T11:02:21.000Z
|
src/lisp/map.hh
|
kuriboshi/lips
|
f9f4838a95ff574fb7a627a3eb966b38b6f430f7
|
[
"Apache-2.0"
] | null | null | null |
src/lisp/map.hh
|
kuriboshi/lips
|
f9f4838a95ff574fb7a627a3eb966b38b6f430f7
|
[
"Apache-2.0"
] | null | null | null |
//
// Lips, lisp shell.
// Copyright 2020 Krister Joas
//
#pragma once
#include "lisp.hh"
namespace lisp
{
namespace Map
{
void init();
LISPT map(lisp&, LISPT, LISPT, LISPT);
LISPT mapc(lisp&, LISPT, LISPT, LISPT);
LISPT maplist(lisp&, LISPT, LISPT, LISPT);
LISPT mapcar(lisp&, LISPT, LISPT, LISPT);
}
inline LISPT map(lisp& l, LISPT a, LISPT b, LISPT c) { return Map::map(l, a, b, c); }
inline LISPT map(LISPT a, LISPT b, LISPT c) { return Map::map(lisp::current(), a, b, c); }
inline LISPT mapc(lisp& l, LISPT a, LISPT b, LISPT c) { return Map::mapc(l, a, b, c); }
inline LISPT mapc(LISPT a, LISPT b, LISPT c) { return Map::mapc(lisp::current(), a, b, c); }
inline LISPT maplist(lisp& l, LISPT a, LISPT b, LISPT c) { return Map::maplist(l, a, b, c); }
inline LISPT maplist(LISPT a, LISPT b, LISPT c) { return Map::maplist(lisp::current(), a, b, c); }
inline LISPT mapcar(lisp& l, LISPT a, LISPT b, LISPT c) { return Map::mapcar(l, a, b, c); }
inline LISPT mapcar(LISPT a, LISPT b, LISPT c) { return Map::mapcar(lisp::current(), a, b, c); }
} // namespace lisp
| 33.53125 | 98 | 0.650513 |
kuriboshi
|
5af6f81c6da9bb1476794675832ad0e9875d9b55
| 31,030 |
cc
|
C++
|
kleption.cc
|
jdb19937/tewel
|
e2dc25c0998b2bf2763cd68ff66691e0c9f86928
|
[
"MIT"
] | null | null | null |
kleption.cc
|
jdb19937/tewel
|
e2dc25c0998b2bf2763cd68ff66691e0c9f86928
|
[
"MIT"
] | null | null | null |
kleption.cc
|
jdb19937/tewel
|
e2dc25c0998b2bf2763cd68ff66691e0c9f86928
|
[
"MIT"
] | null | null | null |
#define __MAKEMORE_KLEPTION_CC__ 1
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <dirent.h>
#include "kleption.hh"
#include "random.hh"
#include "youtil.hh"
#include "colonel.hh"
#include "camera.hh"
#include "display.hh"
#include "picpipes.hh"
#include "rando.hh"
#include <algorithm>
namespace makemore {
std::string Kleption::picreader_cmd;
std::string Kleption::picwriter_cmd;
std::string Kleption::vidreader_cmd;
std::string Kleption::vidwriter_cmd;
Kleption::Kleption(
const std::string &_fn,
unsigned int _pw, unsigned int _ph, unsigned int _pc,
Flags _flags, Trav _trav, Kind _kind,
unsigned int _sw, unsigned int _sh, unsigned int _sc,
const char *refsfn, double _evolve, double _rvgmul, double _trim
) {
fn = _fn;
flags = _flags;
trav = _trav;
pw = _pw;
ph = _ph;
pc = _pc;
sw = _sw;
sh = _sh;
sc = _sc;
loaded = false;
trim = _trim;
b = 0;
dat = NULL;
cam = NULL;
frames = 0;
dsp = NULL;
idi = 0;
vidreader = NULL;
vidwriter = NULL;
datreader = NULL;
datn = 0;
datwriter = NULL;
refwriter = NULL;
rvg = NULL;
evolve = _evolve;
rvgmul = _rvgmul;
if (refsfn) {
if (trav != TRAV_REFS)
error("refsfn requires trav refs");
refreader = fopen(refsfn, "r");
if (!refreader)
error(std::string("can't open ") + refsfn + ": " + strerror(errno));
} else
refreader = NULL;
if (_kind == KIND_SDL) {
if (!(flags & FLAG_WRITER))
error("can't input from sdl");
// assert(fn == "0");
kind = KIND_SDL;
dsp = new Display;
dsp->open();
return;
}
if (_kind == KIND_REF) {
if (!(flags & FLAG_WRITER))
error("can't input from ref");
kind = KIND_REF;
return;
}
if (_kind == KIND_CAM) {
if (fn == "")
fn = "/dev/video0";
if (flags & FLAG_WRITER)
error("can't output to camera");
}
if (_kind == KIND_RND) {
if (flags & FLAG_WRITER)
error("can't output to rnd kind");
kind = KIND_RND;
return;
}
struct stat buf;
int ret = ::stat(fn.c_str(), &buf);
if (ret != 0) {
if (!(flags & FLAG_WRITER))
error("failed to stat " + fn + ": " + strerror(errno));
if (_kind == KIND_DIR) {
if (0 == ::mkdir(fn.c_str(), 0755))
warning("created directory " + fn);
else if (errno != EEXIST)
error("failed to create directory " + fn + ": " + strerror(errno));
if (pw == 0 || ph == 0 || pc == 0)
error("outdim required for dir kind");
kind = KIND_DIR;
return;
}
if (_kind == KIND_RVG) {
kind = KIND_RVG;
return;
}
if (_kind == KIND_F64LE) {
kind = KIND_F64LE;
return;
}
if (_kind == KIND_U8) {
kind = KIND_U8;
return;
}
if (_kind == KIND_VID) {
kind = KIND_VID;
return;
}
if (_kind == KIND_PIC) {
kind = KIND_PIC;
return;
}
assert(_kind == KIND_ANY);
if (endswith(fn, ".dat") || endswith(fn, ".f64le")) {
kind = KIND_F64LE;
} else if (endswith(fn, ".rgb") || endswith(fn, ".u8")) {
kind = KIND_U8;
} else if (endswith(fn, ".rvg")) {
kind = KIND_RVG;
} else if (
endswith(fn, ".mp4") ||
endswith(fn, ".avi") ||
endswith(fn, ".mkv")
) {
kind = KIND_VID;
} else if (
endswith(fn, ".jpg") ||
endswith(fn, ".png") ||
endswith(fn, ".pbm") ||
endswith(fn, ".pgm") ||
endswith(fn, ".ppm")
) {
kind = KIND_PIC;
} else {
warning(std::string("can't identify kind from extension, assuming pic for ") + fn);
kind = KIND_PIC;
}
return;
}
if (S_ISDIR(buf.st_mode)) {
assert(_kind == KIND_DIR || _kind == KIND_ANY);
if (pw == 0 || ph == 0 || pc == 0)
error("outdim required for dir kind");
kind = KIND_DIR;
return;
} else if (S_ISCHR(buf.st_mode) && ::major(buf.st_rdev) == 81) {
if (flags & FLAG_WRITER)
error("can't output to camera");
if (trav != TRAV_SCAN)
error("reading cam kind requires scan traversal");
assert(_kind == KIND_CAM || _kind == KIND_ANY);
kind = KIND_CAM;
return;
} else {
if (_kind == KIND_F64LE) {
kind = KIND_F64LE;
return;
}
if (_kind == KIND_U8) {
kind = KIND_U8;
return;
}
if (_kind == KIND_VID) {
if (!(flags & FLAG_WRITER))
if (trav != TRAV_SCAN)
error("reading vid kind requires scan traversal");
kind = KIND_VID;
return;
}
if (_kind == KIND_PIC) {
kind = KIND_PIC;
return;
}
if (_kind == KIND_RVG) {
kind = KIND_RVG;
return;
}
if (endswith(fn, ".dat") || endswith(fn, ".f64le")) {
kind = KIND_F64LE;
} else if (endswith(fn, ".rgb") || endswith(fn, ".u8")) {
kind = KIND_U8;
} else if (endswith(fn, ".rvg")) {
kind = KIND_RVG;
} else if (
endswith(fn, ".mp4") ||
endswith(fn, ".avi") ||
endswith(fn, ".mkv")
) {
if (!(flags & FLAG_WRITER))
if (trav != TRAV_SCAN)
error("reading vid kind requires scan traversal");
kind = KIND_VID;
} else if (
endswith(fn, ".jpg") ||
endswith(fn, ".png") ||
endswith(fn, ".pbm") ||
endswith(fn, ".pgm") ||
endswith(fn, ".ppm")
) {
kind = KIND_PIC;
} else {
warning(std::string("can't identify kind from extension, assuming pic for ") + fn);
kind = KIND_PIC;
}
return;
}
}
Kleption::~Kleption() {
if (loaded)
unload();
if (dsp)
delete dsp;
if (vidwriter)
delete vidwriter;
if (datreader)
fclose(datreader);
if (datwriter)
fclose(datwriter);
if (refreader)
fclose(refreader);
if (refwriter)
fclose(refwriter);
if (rvg) {
assert(flags & FLAG_WRITER);
rvg->save(fn);
delete rvg;
}
}
void Kleption::unload() {
if (!loaded)
return;
switch (kind) {
case KIND_RND:
break;
case KIND_RVG:
assert(rvg);
delete rvg;
rvg = NULL;
break;
case KIND_CAM:
assert(cam);
delete cam;
cam = NULL;
assert(dat);
delete[] dat;
dat = NULL;
b = 0;
idi = 0;
break;
case KIND_VID:
if (vidreader) {
delete vidreader;
vidreader = NULL;
}
assert(dat);
delete[] dat;
dat = NULL;
b = 0;
idi = 0;
break;
case KIND_DIR:
for (auto psi = id_sub.begin(); psi != id_sub.end(); ++psi) {
Kleption *subkl = psi->second;
delete subkl;
}
ids.clear();
id_sub.clear();
idi = 0;
break;
case KIND_PIC:
assert(dat);
delete[] dat;
dat = NULL;
b = 0;
idi = 0;
break;
case KIND_U8:
case KIND_F64LE:
assert(dat);
unmapfp(dat, datn);
if (datreader)
fclose(datreader);
datreader = NULL;
dat = NULL;
b = 0;
idi = 0;
break;
}
loaded = false;
}
void Kleption::load() {
if (loaded)
return;
switch (kind) {
case KIND_VID:
{
assert(!vidreader);
vidreader = new Picreader(vidreader_cmd);
vidreader->open(fn);
assert(!dat);
unsigned int w, h;
assert(vidreader->read(&dat, &w, &h));
if (w != sw) {
if (sw)
error("vid width doesn't match");
sw = w;
}
if (h != sh) {
if (sh)
error("vid height doesn't match");
sh = h;
}
if (3 != sc) {
if (sc)
error("vid channels doesn't match");
sc = 3;
}
if (pw == 0)
pw = sw;
if (ph == 0)
ph = sh;
if (pc == 0)
pc = 3;
assert(pw <= w);
assert(ph <= h);
assert(pc == 3);
b = 1;
}
break;
case KIND_RND:
{
if (pw == 0)
pw = sw;
if (ph == 0)
ph = sh;
if (pc == 0)
pc = sc;
if (sw == 0)
sw = pw;
if (sh == 0)
sh = ph;
if (sc == 0)
sc = pc;
assert(pw <= sw);
assert(ph <= sh);
assert(pw > 0);
assert(ph > 0);
assert(pc == sc);
}
break;
case KIND_RVG:
{
if (pw == 0)
pw = sw;
if (ph == 0)
ph = sh;
if (pc == 0)
pc = sc;
if (sw == 0)
sw = pw;
if (sh == 0)
sh = ph;
if (sc == 0)
sc = pc;
assert(pw <= sw);
assert(ph <= sh);
assert(pw > 0);
assert(ph > 0);
assert(pc == sc);
assert(!rvg);
rvg = new Rando(sc);
rvg->load(fn);
}
break;
case KIND_CAM:
{
assert(!cam);
cam = new Camera(fn, sw, sh);
cam->open();
if (sw && cam->w != sw)
error("cam width doesn't match");
if (sh && cam->h != sh)
error("cam height doesn't match");
if (sc && 3 != sh)
error("cam channels doesn't match");
sw = cam->w;
sh = cam->h;
sc = 3;
if (pw == 0)
pw = sw;
if (ph == 0)
ph = sh;
if (pc == 0)
pc = sc;
assert(pw <= sw);
assert(ph <= sh);
assert(pw > 0);
assert(ph > 0);
assert(pc == 3);
assert(!dat);
dat = new uint8_t[sw * sh * 3];
b = 1;
}
break;
case KIND_DIR:
{
assert(ids.empty());
assert(id_sub.empty());
assert(pw > 0);
assert(ph > 0);
assert(pc > 0);
DIR *dp = ::opendir(fn.c_str());
assert(dp);
struct dirent *de;
while ((de = ::readdir(dp))) {
if (*de->d_name == '.')
continue;
std::string subfn = de->d_name;
Kleption *subkl = new Kleption(
fn + "/" + subfn, pw, ph, pc,
flags & ~FLAG_REPEAT, trav, KIND_ANY,
sw, sh, sc
);
if (subkl->kind == KIND_CAM) {
delete subkl;
error("v4l2 device found in dir, dir can contain only pics");
}
if (subkl->kind == KIND_VID) {
delete subkl;
error("vid found in dir, dir can contain only pics");
}
assert(
subkl->kind == KIND_DIR ||
subkl->kind == KIND_F64LE ||
subkl->kind == KIND_U8 ||
subkl->kind == KIND_PIC
);
id_sub.insert(std::make_pair(subfn, subkl));
ids.push_back(subfn);
}
::closedir(dp);
assert(ids.size() > 0);
std::sort(ids.begin(), ids.end());
}
break;
case KIND_PIC:
assert(!dat);
unsigned int w, h;
{
Picreader picreader(picreader_cmd);
picreader.open(fn);
picreader.read(&dat, &w, &h);
}
b = 1;
if (w != sw) {
if (sw)
error("pic width doesn't match");
sw = w;
}
if (h != sh) {
if (sh)
error("pic height doesn't match");
sh = h;
}
if (3 != sc) {
if (sc)
error("pic channels doesn't match");
sc = 3;
}
if (pw == 0)
pw = sw;
if (ph == 0)
ph = sh;
if (pc == 0)
pc = sc;
assert(pw <= sw);
assert(ph <= sh);
assert(pc == sc);
assert(pw > 0);
assert(sw > 0);
assert(ph > 0);
assert(sh > 0);
assert(pc > 0);
assert(sc == 3);
break;
case KIND_U8:
{
assert(!dat);
if (!sw) {
sw = pw;
if (!sw)
error("dat width required");
}
if (!sh) {
sh = ph;
if (!sh)
error("dat height required");
}
if (!sc) {
sc = pc;
if (!sc)
error("dat channels required");
}
if (pw == 0)
pw = sw;
if (ph == 0)
ph = sh;
if (pc == 0)
pc = sc;
datn = 0;
assert(!datreader);
if (!(datreader = ::fopen(fn.c_str(), "r")))
error("can't open " + fn);
// dat = slurp(fn, &datn);
dat = mapfp(datreader, &datn);
unsigned int swhc = sw * sh * sc;
assert(datn % swhc == 0);
b = datn / swhc;
break;
}
case KIND_F64LE:
{
assert(!dat);
if (!sw) {
sw = pw;
if (!sw)
error("dat width required");
}
if (!sh) {
sh = ph;
if (!sh)
error("dat height required");
}
if (!sc) {
sc = pc;
if (!sc)
error("dat channels required");
}
if (pw == 0)
pw = sw;
if (ph == 0)
ph = sh;
if (pc == 0)
pc = sc;
datn = 0;
assert(!datreader);
if (!(datreader = ::fopen(fn.c_str(), "r")))
error("can't open " + fn);
// dat = slurp(fn, &datn);
dat = mapfp(datreader, &datn);
unsigned int swhc = sw * sh * sc;
assert(datn % (8 * swhc) == 0);
b = datn / swhc / 8;
break;
}
default:
assert(0);
}
loaded = true;
}
static void _outcrop(
const uint8_t *tmpdat, double *kdat, Kleption::Flags flags,
int sw, int sh, int sc, int pw, int ph, int pc,
unsigned int *x0p, unsigned int *y0p, double trim
) {
assert(pw <= sw);
assert(ph <= sh);
assert(pc == sc);
unsigned int x0, y0, x1, y1;
if (flags & Kleption::FLAG_CENTER) {
x0 = (sw - pw) / 2;
y0 = (sh - ph) / 2;
} else {
int bx0 = trim * sw;
int by0 = trim * sh;
int bx1 = sw - bx0;
int by1 = sh - by0;
assert(bx1 > bx0);
assert(by1 > by0);
int bsw = bx1 - bx0;
int bsh = by1 - by0;
assert(bsw >= pw);
assert(bsh >= ph);
x0 = bx0 + (randuint() % (bsw - pw + 1));
y0 = by0 + (randuint() % (bsh - ph + 1));
}
x1 = x0 + pw - 1;
y1 = y0 + ph - 1;
unsigned int pwhc = pw * ph * pc;
double *ddat = new double[pwhc];
double *edat = ddat;
for (unsigned int y = y0; y <= y1; ++y)
for (unsigned int x = x0; x <= x1; ++x) {
for (unsigned int z = 0; z < sc; ++z)
*edat++ = (0.5 + (double)tmpdat[z + sc * (x + sw * y)]) / 256.0;
}
enk(ddat, pwhc, kdat);
delete[] ddat;
if (x0p)
*x0p = x0;
if (y0p)
*y0p = y0;
}
static void _outcrop(
const double *tmpdat, double *kdat, Kleption::Flags flags,
int sw, int sh, int sc, int pw, int ph, int pc,
unsigned int *x0p, unsigned int *y0p, double trim
) {
assert(pw <= sw);
assert(ph <= sh);
assert(pc == sc);
unsigned int x0, y0, x1, y1;
if (flags & Kleption::FLAG_CENTER) {
x0 = (sw - pw) / 2;
y0 = (sh - ph) / 2;
} else {
int bx0 = trim * sw;
int by0 = trim * sh;
int bx1 = sw - bx0;
int by1 = sh - by0;
assert(bx1 > bx0);
assert(by1 > by0);
int bsw = bx1 - bx0;
int bsh = by1 - by0;
assert(bsw >= pw);
assert(bsh >= ph);
x0 = bx0 + (randuint() % (bsw - pw + 1));
y0 = by0 + (randuint() % (bsh - ph + 1));
}
x1 = x0 + pw - 1;
y1 = y0 + ph - 1;
unsigned int pwhc = pw * ph * pc;
double *ddat = new double[pwhc];
double *edat = ddat;
for (unsigned int y = y0; y <= y1; ++y)
for (unsigned int x = x0; x <= x1; ++x) {
for (unsigned int z = 0; z < sc; ++z)
*edat++ = tmpdat[z + sc * (x + sw * y)];
}
enk(ddat, pwhc, kdat);
delete[] ddat;
if (x0p)
*x0p = x0;
if (y0p)
*y0p = y0;
}
static void cpumatvec(const double *a, const double *b, int aw, int ahbw, double *c) {
int ah = ahbw;
int bw = ahbw;
int cw = aw;
for (int cx = 0; cx < cw; ++cx) {
c[cx] = 0;
for (int i = 0; i < ahbw; ++i) {
c[cx] += a[cx + aw * i] * b[i];
}
}
}
bool Kleption::pick(double *kdat, std::string *idp) {
load();
switch (kind) {
case KIND_VID:
{
if (!vidreader) {
unload();
load();
return false;
}
unsigned int x0, y0;
_outcrop(dat, kdat, flags, sw, sh, sc, pw, ph, pc, &x0, &y0, trim);
assert(vidreader);
if (!vidreader->read(dat, sw, sh)) {
if (flags & FLAG_REPEAT) {
unload();
load();
} else {
delete(vidreader);
vidreader = NULL;
}
}
if (idp) {
char buf[256];
sprintf(buf, "%ux%ux%u+%u+%u+%u.ppm", pw, ph, sc, x0, y0, frames);
*idp = buf;
}
++frames;
return true;
}
case KIND_CAM:
{
assert(cam);
assert(pc == sc);
assert(cam->w == sw);
assert(cam->h == sh);
assert(sc == 3);
cam->read(dat);
unsigned int x0, y0;
_outcrop(dat, kdat, flags, sw, sh, sc, pw, ph, pc, &x0, &y0, trim);
if (idp) {
char buf[256];
sprintf(buf, "%ux%ux%u+%u+%u+%u.ppm", pw, ph, sc, x0, y0, frames);
*idp = buf;
}
++frames;
return true;
}
case KIND_RND:
{
unsigned int swh = sw * sh;
unsigned int swhc = swh * sc;
double *rnd = new double[swhc];
for (int j = 0; j < swhc; ++j)
rnd[j] = randgauss();
unsigned int x0, y0;
_outcrop(rnd, kdat, flags, sw, sh, sc, pw, ph, pc, &x0, &y0, trim);
delete[] rnd;
if (idp) {
char buf[256];
sprintf(buf, "%ux%ux%u+%u+%u+%u.ppm", pw, ph, sc, x0, y0, frames);
*idp = buf;
}
++frames;
return true;
}
case KIND_RVG:
{
assert(rvg);
assert(rvg->dim == sc);
unsigned int swh = sw * sh;
unsigned int swhc = swh * sc;
double *rnd = new double[swhc];
for (int xy = 0; xy < swh; ++xy)
rvg->generate(rnd + xy * sc, rvgmul, evolve);
unsigned int x0, y0;
_outcrop(rnd, kdat, flags, sw, sh, sc, pw, ph, pc, &x0, &y0, trim);
delete[] rnd;
if (idp) {
char buf[256];
sprintf(buf, "%ux%ux%u+%u+%u+%u.ppm", pw, ph, sc, x0, y0, frames);
*idp = buf;
}
++frames;
return true;
}
case KIND_DIR:
{
unsigned int idn = ids.size();
unsigned int idj;
if (trav == TRAV_SCAN) {
if (idi >= idn) {
idi = 0;
if (!(flags & FLAG_REPEAT))
return false;
}
idj = idi;
} else if (trav == TRAV_RAND) {
idj = randuint() % idn;
} else if (trav == TRAV_REFS) {
std::string ref;
if (!read_line(refreader, &ref)) {
rewind(refreader);
assert(read_line(refreader, &ref));
if (!(flags & FLAG_REPEAT)) {
rewind(refreader);
return false;
}
}
find(ref, kdat);
if (idp)
*idp = ref;
return true;
}
assert(idj < idn);
std::string id = ids[idj];
Kleption *subkl = id_sub[id];
assert(subkl != NULL);
std::string idq;
bool ret = subkl->pick(kdat, idp ? &idq : NULL);
if (!ret) {
assert(trav == TRAV_SCAN);
++idi;
if (idi >= idn) {
idi = 0;
if (!(flags & FLAG_REPEAT))
return false;
}
idj = idi;
id = ids[idj];
subkl = id_sub[id];
ret = subkl->pick(kdat, idp ? &idq : NULL);
assert(ret);
}
if (idp)
*idp = id + "/" + idq;
return true;
}
case KIND_PIC:
{
if (trav == TRAV_SCAN) {
if (!(flags & FLAG_REPEAT) && idi > 0) {
assert(idi == 1);
idi = 0;
return false;
}
} else if (trav == TRAV_REFS) {
std::string ref;
if (!read_line(refreader, &ref)) {
rewind(refreader);
assert(read_line(refreader, &ref));
if (!(flags & FLAG_REPEAT)) {
rewind(refreader);
return false;
}
}
find(ref, kdat);
if (idp)
*idp = ref;
return true;
}
assert(dat);
assert(sw >= pw);
assert(sh >= ph);
assert(sc == 3);
assert(pc == sc);
unsigned int x0, y0;
_outcrop(dat, kdat, flags, sw, sh, sc, pw, ph, pc, &x0, &y0, trim);
if ((flags & FLAG_LOWMEM) && kind == KIND_PIC)
unload();
if (idp) {
char buf[256];
sprintf(buf, "%ux%ux%u+%u+%u.ppm", pw, ph, sc, x0, y0);
*idp = buf;
}
if (trav == TRAV_SCAN) {
assert(idi == 0);
if (!(flags & FLAG_REPEAT))
++idi;
}
return true;
}
case KIND_U8:
{
assert(dat);
assert(pc == sc);
assert(b > 0);
unsigned int v;
if (trav == TRAV_SCAN) {
if (idi >= b) {
idi = 0;
if (!(flags & FLAG_REPEAT))
return false;
}
v = idi;
++idi;
} else if (trav == TRAV_REFS) {
std::string ref;
if (!read_line(refreader, &ref)) {
rewind(refreader);
assert(read_line(refreader, &ref));
if (!(flags & FLAG_REPEAT)) {
rewind(refreader);
return false;
}
}
find(ref, kdat);
if (idp)
*idp = ref;
return true;
} else if (trav == TRAV_RAND) {
v = randuint() % b;
} else {
assert(0);
}
assert(v < b);
unsigned int swhc = sw * sh * sc;
const uint8_t *tmpdat = dat + (long)v * (long)swhc;
unsigned int x0, y0;
_outcrop(tmpdat, kdat, flags, sw, sh, sc, pw, ph, pc, &x0, &y0, trim);
if (idp) {
char buf[256];
sprintf(buf, "%ux%ux%u+%u+%u+%u.ppm", pw, ph, sc, x0, y0, v);
*idp = buf;
}
return true;
}
case KIND_F64LE:
{
assert(dat);
assert(pc == sc);
assert(b > 0);
unsigned int v;
if (trav == TRAV_SCAN) {
if (idi >= b) {
idi = 0;
if (!(flags & FLAG_REPEAT))
return false;
}
v = idi;
++idi;
} else if (trav == TRAV_REFS) {
std::string ref;
if (!read_line(refreader, &ref)) {
rewind(refreader);
assert(read_line(refreader, &ref));
if (!(flags & FLAG_REPEAT)) {
rewind(refreader);
return false;
}
}
find(ref, kdat);
if (idp)
*idp = ref;
return true;
} else if (trav == TRAV_RAND) {
v = randuint() % b;
} else {
assert(0);
}
assert(v < b);
unsigned int swhc = sw * sh * sc;
const double *tmpdat = ((double *)dat) + (long)v * (long)swhc;
unsigned int x0, y0;
_outcrop(tmpdat, kdat, flags, sw, sh, sc, pw, ph, pc, &x0, &y0, trim);
if (idp) {
char buf[256];
sprintf(buf, "%ux%ux%u+%u+%u+%u.ppm", pw, ph, sc, x0, y0, v);
*idp = buf;
}
return true;
}
default:
assert(0);
}
assert(0);
}
void Kleption::find(const std::string &id, double *kdat) {
const char *cid = id.c_str();
std::string pid, qid;
if (const char *p = ::strchr(cid, '/')) {
pid = std::string(cid, p - cid);
qid = p + 1;
} else {
pid = id;
qid = "";
}
load();
switch (kind) {
case KIND_RND:
case KIND_RVG:
case KIND_CAM:
case KIND_VID:
assert(0);
case KIND_DIR:
{
assert(qid != "");
Kleption *subkl = id_sub[pid];
assert(subkl != NULL);
subkl->find(qid, kdat);
break;
}
case KIND_PIC:
{
assert(qid == "");
assert(dat);
unsigned int vpw, vph, vpc, x0, y0;
sscanf(pid.c_str(), "%ux%ux%u+%u+%u.ppm", &vpw, &vph, &vpc, &x0, &y0);
assert(sw >= pw);
assert(sh >= ph);
assert(vpw == pw);
assert(vph == ph);
assert(vpc == pc);
assert(sc == 3);
assert(pc == sc);
assert(x0 >= 0);
assert(x0 < sw);
assert(y0 >= 0);
assert(y0 < sh);
unsigned int x1 = x0 + pw - 1;
unsigned int y1 = y0 + ph - 1;
assert(x1 >= x0);
assert(x1 < sw);
assert(y1 >= y0);
assert(y1 < sh);
unsigned int pwhc = pw * ph * pc;
double *ddat = new double[pwhc];
double *edat = ddat;
for (unsigned int y = y0; y <= y1; ++y)
for (unsigned int x = x0; x <= x1; ++x) {
for (unsigned int z = 0; z < sc; ++z)
*edat++ = (double)dat[z + sc * (x + sw * y)] / 255.0;
}
enk(ddat, pwhc, kdat);
delete[] ddat;
break;
}
case KIND_U8:
{
assert(dat);
assert(qid == "");
unsigned int vpw, vph, vpc, x0, y0, v;
sscanf(pid.c_str(), "%ux%ux%u+%u+%u+%u.ppm", &vpw, &vph, &vpc, &x0, &y0, &v);
assert(v < b);
// info(fmt("matching %ux%ux%u -> %ux%ux%u", vpw, vph, vpc, pw, ph, pc));
// assert(vpw == pw);
// assert(vph == ph);
// assert(vpc == pc);
assert(sw == pw);
assert(sh == ph);
assert(pc == sc);
assert(x0 >= 0);
assert(x0 < sw);
assert(y0 >= 0);
assert(y0 < sh);
unsigned int x1 = x0 + pw - 1;
unsigned int y1 = y0 + ph - 1;
assert(x1 >= x0);
assert(x1 < sw);
assert(y1 >= y0);
assert(y1 < sh);
unsigned int pwhc = pw * ph * pc;
unsigned int swhc = sw * sh * sc;
const uint8_t *tmpdat = dat + (long)v * (long)swhc;
double *ddat = new double[pwhc];
double *edat = ddat;
for (unsigned int y = y0; y <= y1; ++y)
for (unsigned int x = x0; x <= x1; ++x) {
for (unsigned int z = 0; z < sc; ++z)
*edat++ = (double)tmpdat[z + sc * (x + sw * y)] / 255.0;
}
enk(ddat, pwhc, kdat);
delete[] ddat;
}
break;
case KIND_F64LE:
{
assert(dat);
assert(qid == "");
unsigned int vpw, vph, vpc, x0, y0, v;
sscanf(pid.c_str(), "%ux%ux%u+%u+%u+%u.ppm", &vpw, &vph, &vpc, &x0, &y0, &v);
assert(v < b);
// fprintf(stderr, "pid=%s pw=%d ph=%d pc=%d\n", pid.c_str(), pw, ph, pc);
// assert(vpw == pw);
// assert(vph == ph);
// assert(vpc == pc);
assert(sw == pw);
assert(sh == ph);
assert(pc == sc);
assert(x0 >= 0);
assert(x0 < sw);
assert(y0 >= 0);
assert(y0 < sh);
unsigned int x1 = x0 + pw - 1;
unsigned int y1 = y0 + ph - 1;
assert(x1 >= x0);
assert(x1 < sw);
assert(y1 >= y0);
assert(y1 < sh);
unsigned int pwhc = pw * ph * pc;
unsigned int swhc = sw * sh * sc;
const double *tmpdat = ((double *)dat) + (long)v * (long)swhc;
double *ddat = new double[pwhc];
double *edat = ddat;
for (unsigned int y = y0; y <= y1; ++y)
for (unsigned int x = x0; x <= x1; ++x) {
for (unsigned int z = 0; z < sc; ++z)
*edat++ = tmpdat[z + sc * (x + sw * y)];
}
enk(ddat, pwhc, kdat);
delete[] ddat;
}
break;
default:
assert(0);
}
}
bool Kleption::place(const std::string &id, const double *kdat) {
info(fmt("placing %s", id.c_str()));
assert(flags & FLAG_WRITER);
assert(pw > 0);
assert(ph > 0);
assert(pc > 0);
const char *cid = id.c_str();
std::string pid, qid;
if (const char *p = ::strchr(cid, '/')) {
pid = std::string(cid, p - cid);
qid = p + 1;
} else {
pid = id;
qid = "";
}
switch (kind) {
case KIND_RND:
error("can't place to kind rnd");
break;
case KIND_RVG:
{
if (!rvg)
rvg = new Rando(pc);
unsigned int pwh = pw * ph;
unsigned int pwhc = pwh * pc;
double *ddat = new double[pwhc];
dek(kdat, pwhc, ddat);
for (int xy = 0; xy < pwh; ++xy)
rvg->observe(ddat + xy * pc);
delete[] ddat;
}
return true;
case KIND_U8:
{
if (!datwriter) {
datwriter = fopen(fn.c_str(), (flags & FLAG_APPEND) ? "a" : "w");
if (!datwriter)
error(std::string("failed to open ") + fn + ": " + strerror(errno));
}
unsigned int pwhc = pw * ph * pc;
double *dtmp = new double[pwhc];
uint8_t *tmp = new uint8_t[pwhc];
dek(kdat, pwhc, dtmp);
dedub(dtmp, pwhc, tmp);
fwrite(tmp, 1, pw * ph * pc, datwriter);
delete[] tmp;
delete[] dtmp;
}
return true;
case KIND_F64LE:
{
if (!datwriter) {
datwriter = fopen(fn.c_str(), (flags & FLAG_APPEND) ? "a" : "w");
if (!datwriter)
error(std::string("failed to open ") + fn + ": " + strerror(errno));
}
unsigned int pwhc = pw * ph * pc;
double *dtmp = new double[pwhc];
dek(kdat, pwhc, dtmp);
fwrite(dtmp, 1, pw * ph * pc * 8, datwriter);
delete[] dtmp;
}
return true;
case KIND_VID:
{
if (!vidwriter) {
vidwriter = new Picwriter(vidwriter_cmd);
vidwriter->open(fn);
}
unsigned int pwhc = pw * ph * pc;
double *dtmp = new double[pwhc];
uint8_t *tmp = new uint8_t[pwhc];
dek(kdat, pwhc, dtmp);
dedub(dtmp, pwhc, tmp);
vidwriter->write(tmp, pw, ph);
delete[] tmp;
delete[] dtmp;
}
return true;
case KIND_CAM:
assert(0);
case KIND_DIR:
{
std::string fnp = fn;
while (const char *p = ::strchr(qid.c_str(), '/')) {
fnp += std::string("/" + pid);
if (0 == ::mkdir(fnp.c_str(), 0755))
warning("created directory " + fnp);
else if (errno != EEXIST)
error("failed to create directory " + fnp + ": " + strerror(errno));
pid = std::string(qid.c_str(), p - qid.c_str());
qid = std::string(p + 1);
}
Picwriter *picwriter = new Picwriter(picwriter_cmd);
picwriter->open(fnp + "/" + pid);
assert(pc == 3);
unsigned int pwhc = pw * ph * pc;
double *dtmp = new double[pwhc];
uint8_t *tmp = new uint8_t[pwhc];
dek(kdat, pwhc, dtmp);
dedub(dtmp, pwhc, tmp);
picwriter->write(tmp, pw, ph);
delete picwriter;
delete[] tmp;
delete[] dtmp;
}
return true;
case KIND_PIC:
{
Picwriter *picwriter = new Picwriter(picwriter_cmd);
picwriter->open(fn);
unsigned int pwhc = pw * ph * pc;
double *dtmp = new double[pwhc];
uint8_t *tmp = new uint8_t[pwhc];
dek(kdat, pwhc, dtmp);
dedub(dtmp, pwhc, tmp);
picwriter->write(tmp, pw, ph);
delete picwriter;
delete[] tmp;
delete[] dtmp;
}
return true;
case KIND_SDL:
{
assert(dsp);
assert(pc == 3);
unsigned int pwhc = pw * ph * pc;
double *dtmp = new double[pwhc];
uint8_t *tmp = new uint8_t[pwhc];
dek(kdat, pwhc, dtmp);
dedub(dtmp, pwhc, tmp);
dsp->update(tmp, pw, ph);
dsp->present();
delete[] tmp;
delete[] dtmp;
}
return !dsp->done();
case KIND_REF:
if (!refwriter) {
refwriter = fopen(fn.c_str(), (flags & FLAG_APPEND) ? "a" : "w");
if (!refwriter)
error(std::string("failed to open ") + fn + ": " + strerror(errno));
setbuf(refwriter, NULL);
}
fprintf(refwriter, "%s\n", id.c_str());
return true;
default:
assert(0);
}
assert(0);
}
// static
std::string Kleption::pick_pair(
Kleption *kl0, double *kdat0,
Kleption *kl1, double *kdat1
) {
std::string id;
bool ret = kl0->pick(kdat0, &id);
assert(ret);
kl1->find(id, kdat1);
return id;
}
}
| 21.593598 | 89 | 0.477312 |
jdb19937
|
5af8c11d00fe7ab4a4053086cf0211ba4bcc6a3b
| 3,647 |
cc
|
C++
|
attic/acpi.cc
|
Anton-Cao/sv6
|
f525c4d588d3cfe750867990902b882cd4a21fad
|
[
"MIT-0"
] | 147 |
2015-01-13T08:56:18.000Z
|
2022-03-10T06:49:25.000Z
|
attic/acpi.cc
|
Anton-Cao/sv6
|
f525c4d588d3cfe750867990902b882cd4a21fad
|
[
"MIT-0"
] | 1 |
2018-05-12T11:46:14.000Z
|
2018-05-12T11:46:14.000Z
|
attic/acpi.cc
|
Anton-Cao/sv6
|
f525c4d588d3cfe750867990902b882cd4a21fad
|
[
"MIT-0"
] | 34 |
2015-01-06T12:36:58.000Z
|
2021-09-23T17:56:22.000Z
|
// http://www.acpi.info/spec.htm
#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "cpu.hh"
#include "apic.hh"
struct rsdp {
u8 signature[8];
u8 checksum;
u8 oemid[6];
u8 revision;
u32 rsdtaddr;
u32 length;
u64 xsdtaddr;
u8 extchecksum;
u8 reserved[3];
};
struct header {
u8 signature[4];
u32 length;
u8 revision;
u8 checksum;
u8 oemid[6];
u8 oemtableid[8];
u32 oemrevision;
u32 creatorid;
u32 creatorrevision;
};
struct rsdt {
struct header hdr;
u32 entry[];
};
struct xsdt {
struct header hdr;
u64 entry[];
} __attribute__((packed));
struct madt {
struct header hdr;
u32 localaddr;
u32 flags;
u8 entry[];
};
struct madt_apic {
u8 type;
u8 length;
u8 procid;
u8 apicid;
u32 flags;
} __attribute__((packed));
struct madt_x2apic {
u8 type;
u8 length;
u8 reserved[2];
u32 apicid;
u32 flags;
u32 procuid;
} __attribute__((packed));
#define CPU_ENABLED 0x1
static u8
sum(u8 *a, u32 length)
{
u8 s = 0;
for (u32 i = 0; i < length; i++)
s += a[i];
return s;
}
static struct rsdp *
rsdp_search1(paddr pa, int len)
{
u8 *start = (u8 *)p2v(pa);
for (u8 *p = start; p < (start + len); p += 16) {
if ((memcmp(p, "RSD PTR ", 8) == 0) && (sum(p, 20) == 0))
return (struct rsdp *)p;
}
return 0;
}
static struct rsdp *
rsdp_search(void)
{
struct rsdp *ret;
u8 *bda;
paddr pa;
bda = (u8 *)p2v(0x400);
if ((pa = ((bda[0x0F] << 8) | bda[0x0E]) << 4)) {
if ((ret = rsdp_search1(pa, 1024)))
return ret;
}
return rsdp_search1(0xE0000, 0x20000);
}
static void
scan_madt(struct madt* madt)
{
struct madt_x2apic* mx2;
struct madt_apic* ma;
u8* type;
u8* end;
u32 c;
end = ((u8*)madt) + madt->hdr.length;
type = ((u8*)madt) + sizeof(*madt);
c = 0 == myid() ? 1 : 0;
while (type < end) {
s64 id = -1;
switch (type[0]) {
case 0: // Processor Local APIC
ma = (struct madt_apic*) type;
if (ma->flags & CPU_ENABLED)
id = ma->apicid;
break;
case 9: // Processor Local x2APIC
mx2 = (struct madt_x2apic*) type;
if (mx2->flags & CPU_ENABLED)
id = mx2->apicid;
break;
}
if (id != -1 && id != lapicid().num) {
assert(c < NCPU);
if (VERBOSE)
cprintf("%u from %u to %ld\n", c, cpus[c].hwid.num, id);
cpus[c].hwid.num = id;
c = c+1 == myid() ? c+2 : c+1;
}
type = type + type[1];
}
}
void
initacpi(void)
{
struct rsdp* rsdp = rsdp_search();
struct madt* madt = nullptr;
if (!rsdp)
return;
if (rsdp->xsdtaddr) {
struct xsdt* xsdt = (struct xsdt*) p2v(rsdp->xsdtaddr);
if (sum((u8 *)xsdt, xsdt->hdr.length)) {
cprintf("initacpi: bad xsdt checksum\n");
return;
}
u32 n = xsdt->hdr.length > sizeof(*xsdt) ?
(xsdt->hdr.length - sizeof(*xsdt)) / 8 : 0;
for (u32 i = 0; i < n; i++) {
struct header* h = (struct header*) p2v(xsdt->entry[i]);
if (memcmp(h->signature, "APIC", 4) == 0) {
madt = (struct madt*) h;
break;
}
}
} else {
struct rsdt* rsdt = (struct rsdt*) p2v(rsdp->rsdtaddr);
if (sum((u8 *)rsdt, rsdt->hdr.length)) {
cprintf("initacpi: bad rsdt checksum\n");
return;
}
u32 n = rsdt->hdr.length > sizeof(*rsdt) ?
(rsdt->hdr.length - sizeof(*rsdt)) / 8 : 0;
for (u32 i = 0; i < n; i++) {
struct header* h = (struct header*) p2v(rsdt->entry[i]);
if (memcmp(h->signature, "APIC", 4) == 0) {
madt = (struct madt*) h;
break;
}
}
}
if (madt != nullptr)
scan_madt(madt);
}
| 18.994792 | 64 | 0.549767 |
Anton-Cao
|
5afa0b2d60def81c35bdec955d27b68cbbf8e422
| 14,976 |
cpp
|
C++
|
Samples/Win7Samples/multimedia/mediafoundation/MFCaptureToFile/winmain.cpp
|
windows-development/Windows-classic-samples
|
96f883e4c900948e39660ec14a200a5164a3c7b7
|
[
"MIT"
] | 8 |
2017-04-30T17:38:27.000Z
|
2021-11-29T00:59:03.000Z
|
Samples/Win7Samples/multimedia/mediafoundation/MFCaptureToFile/winmain.cpp
|
TomeSq/Windows-classic-samples
|
96f883e4c900948e39660ec14a200a5164a3c7b7
|
[
"MIT"
] | null | null | null |
Samples/Win7Samples/multimedia/mediafoundation/MFCaptureToFile/winmain.cpp
|
TomeSq/Windows-classic-samples
|
96f883e4c900948e39660ec14a200a5164a3c7b7
|
[
"MIT"
] | 2 |
2020-08-11T13:21:49.000Z
|
2021-09-01T10:41:51.000Z
|
//////////////////////////////////////////////////////////////////////////
//
// winmain.cpp. Application entry-point.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//////////////////////////////////////////////////////////////////////////
#include <windows.h>
#include <windowsx.h>
#include <mfapi.h>
#include <mfidl.h>
#include <mfreadwrite.h>
#include <assert.h>
#include <strsafe.h>
#include <shlwapi.h>
#include <Dbt.h>
#include <ks.h>
#include <ksmedia.h>
template <class T> void SafeRelease(T **ppT)
{
if (*ppT)
{
(*ppT)->Release();
*ppT = NULL;
}
}
#include "capture.h"
#include "resource.h"
// Include the v6 common controls in the manifest
#pragma comment(linker, \
"\"/manifestdependency:type='Win32' "\
"name='Microsoft.Windows.Common-Controls' "\
"version='6.0.0.0' "\
"processorArchitecture='*' "\
"publicKeyToken='6595b64144ccf1df' "\
"language='*'\"")
enum FileContainer
{
FileContainer_MP4 = IDC_CAPTURE_MP4,
FileContainer_WMV = IDC_CAPTURE_WMV
};
DeviceList g_devices;
CCapture *g_pCapture = NULL;
HDEVNOTIFY g_hdevnotify = NULL;
const UINT32 TARGET_BIT_RATE = 240 * 1000;
INT_PTR CALLBACK DialogProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam);
void OnInitDialog(HWND hDlg);
void OnCloseDialog();
void UpdateUI(HWND hDlg);
void StopCapture(HWND hDlg);
void StartCapture(HWND hDlg);
void OnSelectEncodingType(HWND hDlg, FileContainer file);
HRESULT GetSelectedDevice(HWND hDlg, IMFActivate **ppActivate);
HRESULT UpdateDeviceList(HWND hDlg);
void OnDeviceChange(HWND hwnd, WPARAM reason, DEV_BROADCAST_HDR *pHdr);
void NotifyError(HWND hwnd, const WCHAR *sErrorMessage, HRESULT hrErr);
void EnableDialogControl(HWND hDlg, int nIDDlgItem, BOOL bEnable);
INT WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPWSTR /*lpCmdLine*/, INT /*nCmdShow*/)
{
(void)HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
INT_PTR ret = DialogBox(
hInstance,
MAKEINTRESOURCE(IDD_DIALOG1),
NULL,
DialogProc
);
if (ret == 0 || ret == -1)
{
MessageBox( NULL, L"Could not create dialog", L"Error", MB_OK | MB_ICONERROR );
}
return 0;
}
//-----------------------------------------------------------------------------
// Dialog procedure
//-----------------------------------------------------------------------------
INT_PTR CALLBACK DialogProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_INITDIALOG:
OnInitDialog(hDlg);
break;
case WM_DEVICECHANGE:
OnDeviceChange(hDlg, wParam, (PDEV_BROADCAST_HDR)lParam);
return TRUE;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDC_CAPTURE_MP4: // Fall through
case IDC_CAPTURE_WMV:
OnSelectEncodingType(hDlg, (FileContainer)(LOWORD(wParam)));
return TRUE;
case IDC_CAPTURE:
if (g_pCapture && g_pCapture->IsCapturing())
{
StopCapture(hDlg);
}
else
{
StartCapture(hDlg);
}
return TRUE;
case IDCANCEL:
OnCloseDialog();
::EndDialog(hDlg, IDCANCEL);
return TRUE;
}
break;
}
return FALSE;
}
//-----------------------------------------------------------------------------
// OnInitDialog
// Handler for WM_INITDIALOG message.
//-----------------------------------------------------------------------------
void OnInitDialog(HWND hDlg)
{
HRESULT hr = S_OK;
HWND hEdit = GetDlgItem(hDlg, IDC_OUTPUT_FILE);
SetWindowText(hEdit, TEXT("capture.mp4"));
CheckRadioButton(hDlg, IDC_CAPTURE_MP4, IDC_CAPTURE_WMV, IDC_CAPTURE_MP4);
// Initialize the COM library
hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
// Initialize Media Foundation
if (SUCCEEDED(hr))
{
hr = MFStartup(MF_VERSION);
}
// Register for device notifications
if (SUCCEEDED(hr))
{
DEV_BROADCAST_DEVICEINTERFACE di = { 0 };
di.dbcc_size = sizeof(di);
di.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
di.dbcc_classguid = KSCATEGORY_CAPTURE;
g_hdevnotify = RegisterDeviceNotification(
hDlg,
&di,
DEVICE_NOTIFY_WINDOW_HANDLE
);
if (g_hdevnotify == NULL)
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
}
// Enumerate the video capture devices.
if (SUCCEEDED(hr))
{
hr = UpdateDeviceList(hDlg);
}
if (SUCCEEDED(hr))
{
UpdateUI(hDlg);
if (g_devices.Count() == 0)
{
::MessageBox(
hDlg,
TEXT("Could not find any video capture devices."),
TEXT("MFCaptureToFile"),
MB_OK
);
}
}
else
{
OnCloseDialog();
::EndDialog(hDlg, 0);
}
}
//-----------------------------------------------------------------------------
// OnCloseDialog
//
// Frees resources before closing the dialog.
//-----------------------------------------------------------------------------
void OnCloseDialog()
{
if (g_pCapture)
{
g_pCapture->EndCaptureSession();
}
SafeRelease(&g_pCapture);
g_devices.Clear();
if (g_hdevnotify)
{
UnregisterDeviceNotification(g_hdevnotify);
}
MFShutdown();
CoUninitialize();
}
//-----------------------------------------------------------------------------
// StartCapture
//
// Starts video capture.
//-----------------------------------------------------------------------------
void StartCapture(HWND hDlg)
{
EncodingParameters params;
if (BST_CHECKED == IsDlgButtonChecked(hDlg, IDC_CAPTURE_WMV))
{
params.subtype = MFVideoFormat_WMV3;
}
else
{
params.subtype = MFVideoFormat_H264;
}
params.bitrate = TARGET_BIT_RATE;
HRESULT hr = S_OK;
WCHAR pszFile[MAX_PATH] = { 0 };
HWND hEdit = GetDlgItem(hDlg, IDC_OUTPUT_FILE);
IMFActivate *pActivate = NULL;
// Get the name of the target file.
if (0 == GetWindowText(hEdit, pszFile, MAX_PATH))
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
// Create the media source for the capture device.
if (SUCCEEDED(hr))
{
hr = GetSelectedDevice(hDlg, &pActivate);
}
// Start capturing.
if (SUCCEEDED(hr))
{
hr = CCapture::CreateInstance(hDlg, &g_pCapture);
}
if (SUCCEEDED(hr))
{
hr = g_pCapture->StartCapture(pActivate, pszFile, params);
}
if (SUCCEEDED(hr))
{
UpdateUI(hDlg);
}
SafeRelease(&pActivate);
if (FAILED(hr))
{
NotifyError(hDlg, L"Error starting capture.", hr);
}
}
//-----------------------------------------------------------------------------
// StopCapture
//
// Stops video capture.
//-----------------------------------------------------------------------------
void StopCapture(HWND hDlg)
{
HRESULT hr = S_OK;
hr = g_pCapture->EndCaptureSession();
SafeRelease(&g_pCapture);
UpdateDeviceList(hDlg);
// NOTE: Updating the device list releases the existing IMFActivate
// pointers. This ensures that the current instance of the video capture
// source is released.
UpdateUI(hDlg);
if (FAILED(hr))
{
NotifyError(hDlg, L"Error stopping capture. File might be corrupt.", hr);
}
}
//-----------------------------------------------------------------------------
// CreateSelectedDevice
//
// Create a media source for the video capture device selected by the user.
//-----------------------------------------------------------------------------
HRESULT GetSelectedDevice(HWND hDlg, IMFActivate **ppActivate)
{
HWND hDeviceList = GetDlgItem(hDlg, IDC_DEVICE_LIST);
// First get the index of the selected item in the combo box.
int iListIndex = ComboBox_GetCurSel(hDeviceList);
if (iListIndex == CB_ERR)
{
return HRESULT_FROM_WIN32(GetLastError());
}
// Now find the index of the device within the device list.
//
// This index is stored as item data in the combo box, so that
// the order of the combo box items does not need to match the
// order of the device list.
LRESULT iDeviceIndex = ComboBox_GetItemData(hDeviceList, iListIndex);
if (iDeviceIndex == CB_ERR)
{
return HRESULT_FROM_WIN32(GetLastError());
}
// Now create the media source.
return g_devices.GetDevice((UINT32)iDeviceIndex, ppActivate);
}
//-----------------------------------------------------------------------------
// UpdateDeviceList
//
// Enumerates the video capture devices and populates the list of device
// names in the dialog UI.
//-----------------------------------------------------------------------------
HRESULT UpdateDeviceList(HWND hDlg)
{
HRESULT hr = S_OK;
WCHAR *szFriendlyName = NULL;
HWND hCombobox = GetDlgItem(hDlg, IDC_DEVICE_LIST);
ComboBox_ResetContent( hCombobox );
g_devices.Clear();
hr = g_devices.EnumerateDevices();
if (FAILED(hr)) { goto done; }
for (UINT32 iDevice = 0; iDevice < g_devices.Count(); iDevice++)
{
// Get the friendly name of the device.
hr = g_devices.GetDeviceName(iDevice, &szFriendlyName);
if (FAILED(hr)) { goto done; }
// Add the string to the combo-box. This message returns the index in the list.
int iListIndex = ComboBox_AddString(hCombobox, szFriendlyName);
if (iListIndex == CB_ERR || iListIndex == CB_ERRSPACE)
{
hr = E_FAIL;
goto done;
}
// The list might be sorted, so the list index is not always the same as the
// array index. Therefore, set the array index as item data.
int result = ComboBox_SetItemData(hCombobox, iListIndex, iDevice);
if (result == CB_ERR)
{
hr = E_FAIL;
goto done;
}
CoTaskMemFree(szFriendlyName);
szFriendlyName = NULL;
}
if (g_devices.Count() > 0)
{
// Select the first item.
ComboBox_SetCurSel(hCombobox, 0);
}
done:
return hr;
}
//-----------------------------------------------------------------------------
// OnSelectEncodingType
//
// Called when the user toggles between file-format types.
//-----------------------------------------------------------------------------
void OnSelectEncodingType(HWND hDlg, FileContainer file)
{
WCHAR pszFile[MAX_PATH] = { 0 };
HWND hEdit = GetDlgItem(hDlg, IDC_OUTPUT_FILE);
GetWindowText(hEdit, pszFile, MAX_PATH);
switch (file)
{
case FileContainer_MP4:
PathRenameExtension(pszFile, L".mp4");
break;
case FileContainer_WMV:
PathRenameExtension(pszFile, L".wmv");
break;
default:
assert(false);
break;
}
SetWindowText(hEdit, pszFile);
}
//-----------------------------------------------------------------------------
// UpdateUI
//
// Updates the dialog UI for the current state.
//-----------------------------------------------------------------------------
void UpdateUI(HWND hDlg)
{
BOOL bEnable = (g_devices.Count() > 0); // Are there any capture devices?
BOOL bCapturing = (g_pCapture != NULL); // Is video capture in progress now?
HWND hButton = GetDlgItem(hDlg, IDC_CAPTURE);
if (bCapturing)
{
SetWindowText(hButton, L"Stop Capture");
}
else
{
SetWindowText(hButton, L"Start Capture");
}
EnableDialogControl(hDlg, IDC_CAPTURE, bCapturing || bEnable);
EnableDialogControl(hDlg, IDC_DEVICE_LIST, !bCapturing && bEnable);
// The following cannot be changed while capture is in progress,
// but are OK to change when there are no capture devices.
EnableDialogControl(hDlg, IDC_CAPTURE_MP4, !bCapturing);
EnableDialogControl(hDlg, IDC_CAPTURE_WMV, !bCapturing);
EnableDialogControl(hDlg, IDC_OUTPUT_FILE, !bCapturing);
}
//-----------------------------------------------------------------------------
// OnDeviceChange
//
// Handles WM_DEVICECHANGE messages.
//-----------------------------------------------------------------------------
void OnDeviceChange(HWND hDlg, WPARAM reason, DEV_BROADCAST_HDR *pHdr)
{
if (reason == DBT_DEVNODES_CHANGED || reason == DBT_DEVICEARRIVAL)
{
// Check for added/removed devices, regardless of whether
// the application is capturing video at this time.
UpdateDeviceList(hDlg);
UpdateUI(hDlg);
}
// Now check if the current video capture device was lost.
if (pHdr == NULL)
{
return;
}
if (pHdr->dbch_devicetype != DBT_DEVTYP_DEVICEINTERFACE)
{
return;
}
HRESULT hr = S_OK;
BOOL bDeviceLost = FALSE;
if (g_pCapture && g_pCapture->IsCapturing())
{
hr = g_pCapture->CheckDeviceLost(pHdr, &bDeviceLost);
if (FAILED(hr) || bDeviceLost)
{
StopCapture(hDlg);
MessageBox(hDlg, L"The capture device was removed or lost.", L"Lost Device", MB_OK);
}
}
}
void NotifyError(HWND hwnd, const WCHAR *sErrorMessage, HRESULT hrErr)
{
const size_t MESSAGE_LEN = 512;
WCHAR message[MESSAGE_LEN];
HRESULT hr = StringCchPrintf (message, MESSAGE_LEN, L"%s (HRESULT = 0x%X)", sErrorMessage, hrErr);
if (SUCCEEDED(hr))
{
MessageBox(hwnd, message, NULL, MB_OK | MB_ICONERROR);
}
}
void EnableDialogControl(HWND hDlg, int nIDDlgItem, BOOL bEnable)
{
HWND hwnd = GetDlgItem(hDlg, nIDDlgItem);
if (!bEnable && hwnd == GetFocus())
{
// When disabling a control that has focus, set the
// focus to the next control.
::SendMessage(GetParent(hwnd), WM_NEXTDLGCTL, 0, FALSE);
}
EnableWindow(hwnd, bEnable);
}
| 25.340102 | 110 | 0.529046 |
windows-development
|
5afcc9ce1af33e50dd599d3b2f62f2c5a9bf7c65
| 883 |
cpp
|
C++
|
Notes/File Handling/fileHandling.cpp
|
Concept-Team/e-box-UTA018
|
a6caf487c9f27a5ca30a00847ed49a163049f67e
|
[
"MIT"
] | 26 |
2021-03-17T03:15:22.000Z
|
2021-06-09T13:29:41.000Z
|
Notes/File Handling/fileHandling.cpp
|
Servatom/e-box-UTA018
|
a6caf487c9f27a5ca30a00847ed49a163049f67e
|
[
"MIT"
] | 6 |
2021-03-16T19:04:05.000Z
|
2021-06-03T13:41:04.000Z
|
Notes/File Handling/fileHandling.cpp
|
Concept-Team/e-box-UTA018
|
a6caf487c9f27a5ca30a00847ed49a163049f67e
|
[
"MIT"
] | 42 |
2021-03-17T03:16:22.000Z
|
2021-06-14T21:11:20.000Z
|
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
//For output file
//opening a file
ofstream out("myFile.txt");
if(!out.is_open()){
cout<<"Error in opening file"<<endl;
//ABORT
return 1;
}
out<<"Raghav is a human"<<endl;
out<<"Yash is a human"<<endl;
out<<"Rupanshi is human"<<endl;
//File input
ifstream in("myFile.txt");
if (!in){
//error in opening file
cout<<"Error in opening file"<<endl;
//Abort
return 1;
}
//Option 1
/*
string sentence;
in >> sentence;
cout<<sentence<<endl;
in >> sentence;
cout<<sentence<<endl;
in >> sentence;
cout<<sentence<<endl;
*/
char c;
while(!in.eof()){
in.get(c);
cout << c;
}
in.close();
out.close();
return 0;
}
| 15.767857 | 44 | 0.518686 |
Concept-Team
|
850781cb97ae66118a26a0fe738abc3e04d7885b
| 3,296 |
cpp
|
C++
|
src/core/template_deriveditem.cpp
|
mvsframework/mvs
|
4bbda9f18fab960a9bea9c4e5e2de16b77c6ff81
|
[
"Apache-2.0"
] | null | null | null |
src/core/template_deriveditem.cpp
|
mvsframework/mvs
|
4bbda9f18fab960a9bea9c4e5e2de16b77c6ff81
|
[
"Apache-2.0"
] | null | null | null |
src/core/template_deriveditem.cpp
|
mvsframework/mvs
|
4bbda9f18fab960a9bea9c4e5e2de16b77c6ff81
|
[
"Apache-2.0"
] | null | null | null |
//
// Copyright © 2015 Claus Christmann <hcc |ä| gatech.edu>.
//
// 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 "template_deriveditem.h"
#include "template_deriveditem_p.h"
//############################################################################//
// //
// DerivedItemPrivate //
// //
//############################################################################//
DerivedItemPrivate::DerivedItemPrivate ( DerivedItem* q
,DerivedItem::Settings* const settings
,SimItem* parent)
:SimItemPrivate(q,settings)
,q_ptr ( q )
,xmlSettings(settings)
{ //NOTE: Do _NOT_ use q_ptr or q in here, it _WILL_ break things!
}
DerivedItemPrivate::~DerivedItemPrivate()
{
}
void DerivedItemPrivate::unInitializeDerivedItem()
{
// undo whatever DerivedItem::initializeItem() did...
}
//############################################################################//
// //
// DerivedItem //
// //
//############################################################################//
/** \note This constructor does NOT do any work!
* All DerivedItem level construction needs to happen in
* DerivedItem(DerivedItemPrivate & dd, ...)!
*/
DerivedItem::DerivedItem( Settings* const settings
,SimItem* parent)
:DerivedItem(*new DerivedItemPrivate(this,settings,parent),parent)
{}
DerivedItem::DerivedItem( DerivedItemPrivate& dd
,SimItem* parent )
: SimItem(dd, parent) // DerivedItems have SimItems as parents
{
Q_D(DerivedItem); Q_ASSERT(d);
/** \internal
* This will only indicate the status of the DerivedItem, any derived classes
* will not be constructed at this point!
*/
d->setStatus(Status::Constructed);
}
DerivedItem::~DerivedItem()
{
Q_D(DerivedItem); Q_ASSERT(d);
d->unInitializeDerivedItem();
}
void DerivedItem::initializeItem()
{
SimItem::initializeItem();
// do local work below ...
}
void DerivedItem::startItem()
{
SimItem::startItem();
// do local work below ...
}
void DerivedItem::stopItem()
{
// do local work above...
SimItem::stopItem();
}
void DerivedItem::unInitializeItem()
{
Q_D(DerivedItem); Q_ASSERT(d);
d->unInitializeDerivedItem();
// do local work above...
SimItem::unInitializeItem();
}
#include "template_deriveditem.moc"
| 29.693694 | 80 | 0.522755 |
mvsframework
|
8508032439c9d78399714ef8e4769ca2116c455b
| 4,586 |
cpp
|
C++
|
kernel/ubsan.cpp
|
qookei/quack
|
47808580dda218cb47d0c9ca04b51eb24f1e2266
|
[
"Zlib"
] | 16 |
2019-06-25T15:18:03.000Z
|
2021-10-10T18:52:30.000Z
|
kernel/ubsan.cpp
|
qookei/quack
|
47808580dda218cb47d0c9ca04b51eb24f1e2266
|
[
"Zlib"
] | null | null | null |
kernel/ubsan.cpp
|
qookei/quack
|
47808580dda218cb47d0c9ca04b51eb24f1e2266
|
[
"Zlib"
] | null | null | null |
#include <stddef.h>
#include <stdint.h>
#include <kmesg.h>
enum type_kinds { TK_INTEGER = 0x0000, TK_FLOAT = 0x0001, TK_UNKNOWN = 0xffff };
struct type_descriptor {
uint16_t type_kind;
uint16_t type_info;
char type_name[];
};
struct source_location {
char *filename;
uint32_t line;
uint32_t column;
};
struct overflow_data {
struct source_location loc;
struct type_descriptor *type;
};
struct shift_out_of_bounds_data {
struct source_location loc;
struct type_descriptor *lhs_type;
struct type_descriptor *rhs_type;
};
struct out_of_bounds_data {
struct source_location loc;
struct type_descriptor *array_type;
struct type_descriptor *index_type;
};
struct non_null_return_data {
struct source_location attr_loc;
};
struct type_mismatch_data_v1 {
struct source_location loc;
struct type_descriptor *type;
unsigned char log_alignment;
unsigned char type_check_kind;
};
struct type_mismatch_data {
struct source_location loc;
struct type_descriptor *type;
unsigned long alignment;
unsigned char type_check_kind;
};
struct vla_bound_data {
struct source_location loc;
struct type_descriptor *type;
};
struct invalid_value_data {
struct source_location loc;
struct type_descriptor *type;
};
struct unreachable_data {
struct source_location loc;
};
struct nonnull_arg_data {
struct source_location loc;
};
static void log_location(struct source_location loc) {
kmesg("ubsan", "ubsan failure at %s:%d", loc.filename, loc.line);
}
void __ubsan_handle_add_overflow(struct overflow_data *data, uintptr_t lhs,
uintptr_t rhs) {
kmesg("ubsan", "add of %ld and %ld will overflow", lhs, rhs);
log_location(data->loc);
}
void __ubsan_handle_sub_overflow(struct overflow_data *data, uintptr_t lhs,
uintptr_t rhs) {
kmesg("ubsan", "subtract of %ld and %ld will overflow", lhs, rhs);
log_location(data->loc);
}
void __ubsan_handle_pointer_overflow(struct overflow_data *data, uintptr_t lhs,
uintptr_t rhs) {
kmesg("ubsan", "pointer %lx and %lx will overflow", lhs, rhs);
log_location(data->loc);
}
void __ubsan_handle_mul_overflow(struct overflow_data *data, uintptr_t lhs,
uintptr_t rhs) {
kmesg("ubsan", "multiply of %ld and %ld will overflow", lhs, rhs);
log_location(data->loc);
}
void __ubsan_handle_divrem_overflow(struct overflow_data *data,
uintptr_t lhs, uintptr_t rhs) {
kmesg("ubsan", "division of %ld and %ld will overflow", lhs, rhs);
log_location(data->loc);
}
void __ubsan_handle_negate_overflow(struct overflow_data *data,
uintptr_t old) {
kmesg("ubsan", "negation of %ld will overflow", old);
log_location(data->loc);
}
void __ubsan_handle_shift_out_of_bounds(
struct shift_out_of_bounds_data *data, uintptr_t lhs, uintptr_t rhs) {
kmesg("ubsan", "shift of %ld by %ld will go out of bounds", lhs, rhs);
log_location(data->loc);
}
void __ubsan_handle_out_of_bounds(struct out_of_bounds_data *data,
uintptr_t index) {
kmesg("ubsan", "out of bounds access at index %ld", index);
log_location(data->loc);
}
void __ubsan_handle_nonnull_return(struct non_null_return_data *data,
struct source_location *loc) {
kmesg("ubsan", "null return at %s:%d", data->attr_loc.filename, data->attr_loc.line);
log_location(*loc);
}
void __ubsan_handle_type_mismatch_v1(struct type_mismatch_data_v1 *data,
uintptr_t ptr) {
if(!ptr) {
kmesg("ubsan", "null pointer access");
} else if (ptr & ((1 << data->log_alignment) - 1)) {
kmesg("ubsan", "misaligned access (ptr %016lx, alignment %ld)", ptr, (1 << data->log_alignment));
} else {
kmesg("ubsan", "too large access (ptr %016lx)", ptr);
}
log_location(data->loc);
}
void __ubsan_handle_vla_bound_not_positive(struct vla_bound_data *data,
uintptr_t bound) {
kmesg("ubsan", "negative vla bound %ld", bound);
log_location(data->loc);
}
void __ubsan_handle_load_invalid_value(struct invalid_value_data *data,
uintptr_t val) {
kmesg("ubsan", "invalid value %lx", val);
log_location(data->loc);
}
void __ubsan_handle_builtin_unreachable(struct unreachable_data *data) {
kmesg("ubsan", "reached __builtin_unreachabe");
log_location(data->loc);
}
void __ubsan_handle_nonnull_arg(struct nonnull_arg_data *data) {
kmesg("ubsan", "null argument");
log_location(data->loc);
}
void __ubsan_handle_type_mismatch(struct type_mismatch_data *data, uintptr_t ptr) {
if(!ptr) {
kmesg("ubsan", "null pointer access");
} else if (ptr & (data->alignment - 1)) {
kmesg("ubsan", "misaligned access (ptr %016lx, alignment %ld)", ptr, data->alignment);
} else {
kmesg("ubsan", "too large access (ptr %016lx)", ptr);
}
log_location(data->loc);
}
| 26.056818 | 99 | 0.744876 |
qookei
|
8508e990a285b9913d791410fa0cf7b8de83fcad
| 1,325 |
cpp
|
C++
|
Periodic.cpp
|
olehzdubna/FastOutReader
|
81cd55220492a6ae042b38af03c1152ee6fc7eef
|
[
"MIT"
] | null | null | null |
Periodic.cpp
|
olehzdubna/FastOutReader
|
81cd55220492a6ae042b38af03c1152ee6fc7eef
|
[
"MIT"
] | null | null | null |
Periodic.cpp
|
olehzdubna/FastOutReader
|
81cd55220492a6ae042b38af03c1152ee6fc7eef
|
[
"MIT"
] | 1 |
2020-02-12T16:47:00.000Z
|
2020-02-12T16:47:00.000Z
|
/*
* Periodic.cpp
*
* Created on: Jul 6, 2019
* Author: oleh
*/
#include <iostream>
#include <Utils.h>
#include <Periodic.h>
Periodic::Periodic()
: AxisX()
, samples(0)
, trig(0)
, firstTime(0)
, incrementTime(0) {
}
Periodic::~Periodic() {
}
/*
// Read periodic information from a file
// See 'Vertical Header->Abscissa Data Type->Perodic' section of online
// help for HPLogic Fast Binary Data File Format under the File Out tool (8.2)
*/
std::shared_ptr<Periodic> Periodic::read(std::ifstream& inFile) {
std::string line;
//TODO: for debug std::cout << "+++ Periodic Data" << std::endl;
auto periodic = std::make_shared<Periodic>();
/* number of samples and trigger position */
std::getline(inFile, line);
::sscanf(line.data(), "%d %d\n", &periodic->samples, &periodic->trig ) ;
//TODO: for debug std::cout << "+++ samples = " << periodic->samples << " trigger = " << periodic->trig << std::endl;
/* Time of first sample sample */
/* Time between samples */
std::getline(inFile, line);
::sscanf(line.data(), "%d %d\n", &periodic->firstTime, &periodic->incrementTime ) ;
//TODO: for debug std::cout << "+++ origin = " << periodic->firstTime << " ps, increment = " << periodic->incrementTime << std::endl;
Utils::readAttributes(inFile, "Periodic");
return periodic;
}
| 25.480769 | 139 | 0.637736 |
olehzdubna
|
850b15fcb635adbf4ee8a34c4bf3a16106ae6fc0
| 4,255 |
cpp
|
C++
|
formats/lua/Scanner.cpp
|
xguerin/ace
|
ad6e1bc4cb4f10d6cf5b782f623ec0eef13e000b
|
[
"MIT"
] | 5 |
2016-06-14T17:56:47.000Z
|
2022-02-10T19:54:25.000Z
|
formats/lua/Scanner.cpp
|
xguerin/ace
|
ad6e1bc4cb4f10d6cf5b782f623ec0eef13e000b
|
[
"MIT"
] | 42 |
2016-06-21T20:48:22.000Z
|
2021-03-23T15:20:51.000Z
|
formats/lua/Scanner.cpp
|
xguerin/ace
|
ad6e1bc4cb4f10d6cf5b782f623ec0eef13e000b
|
[
"MIT"
] | 1 |
2016-10-02T02:58:49.000Z
|
2016-10-02T02:58:49.000Z
|
/**
* Copyright (c) 2016 Xavier R. Guerin
*
* 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 "Scanner.h"
#include "Common.h"
#include "Object.h"
#include <ace/common/Log.h>
#include <ace/common/String.h>
#include <ace/engine/Master.h>
#include <lua.hpp>
#include <iostream>
#include <string>
#include <vector>
namespace {
static void
report_errors(lua_State* L)
{
const char* str = lua_tostring(L, -1);
std::cerr << "-- " << str << std::endl;
lua_pop(L, 1);
}
static void
build_args(lua_State* L, int argc, char** argv)
{
lua_newtable(L);
for (int i = 0; i < argc; i += 1) {
lua_pushstring(L, argv[i]);
lua_rawseti(L, -2, i);
}
lua_setglobal(L, "arg");
}
}
namespace ace { namespace luafmt {
tree::Value::Ref
Scanner::open(std::string const& fn, int argc, char** argv)
{
if (argc == 0 or argv == nullptr) {
ACE_LOG(Error, "invalid ARGC/ARGV arguments");
return nullptr;
}
tree::Value::Ref obj;
lua_State* L = luaL_newstate();
luaL_openlibs(L);
shift(fn, argc, argv);
build_args(L, argc, argv);
if (luaL_loadfile(L, fn.c_str()) != 0) {
report_errors(L);
goto error;
}
if (lua_pcall(L, 0, LUA_MULTRET, 0) != 0) {
report_errors(L);
goto error;
}
lua_getglobal(L, "config");
if (!lua_istable(L, -1)) {
ACE_LOG(Error, "no \"config\" dictionary found in \"", fn, "\"");
goto error;
}
obj = Object::build("", L);
lua_pop(L, 1);
error:
return obj;
}
tree::Value::Ref
Scanner::parse(std::string const& s, int argc, char** argv)
{
if (argc == 0 or argv == nullptr) {
ACE_LOG(Error, "invalid ARGC/ARGV arguments");
return nullptr;
}
tree::Value::Ref obj;
lua_State* L = luaL_newstate();
luaL_openlibs(L);
shift("", argc, argv);
build_args(L, argc, argv);
if (luaL_loadstring(L, s.c_str()) != 0) {
report_errors(L);
goto error;
}
if (lua_pcall(L, 0, LUA_MULTRET, 0) != 0) {
report_errors(L);
goto error;
}
lua_getglobal(L, "config");
if (!lua_istable(L, -1)) {
ACE_LOG(Error, "no \"config\" dictionary found in inline LUA");
goto error;
}
obj = Object::build("", L);
lua_pop(L, 1);
error:
return obj;
}
void
Scanner::dump(tree::Value const& v, const Format f, std::ostream& o) const
{
o << "config = ";
dump_value(v, o, 0, true);
o << std::endl;
}
bool
Scanner::openAll(std::string const& fn, int argc, char** argv,
std::list<tree::Value::Ref>& values)
{
auto res = open(fn, argc, argv);
if (res == nullptr) {
return false;
}
values.push_back(res);
return true;
}
bool
Scanner::parseAll(std::string const& s, int argc, char** argv,
std::list<tree::Value::Ref>& values)
{
auto res = parse(s, argc, argv);
if (res == nullptr) {
return false;
}
values.push_back(res);
return true;
}
bool
Scanner::dumpAll(std::list<tree::Value::Ref>& values, const Format f,
std::ostream& o) const
{
if (values.size() != 1) {
return false;
}
dump(*values.front(), f, o);
return true;
}
std::string
Scanner::name() const
{
return "lua";
}
std::string
Scanner::extension() const
{
return "lua";
}
}}
extern "C" {
void*
loadPlugin()
{
return new ace::luafmt::Scanner();
}
}
| 22.513228 | 80 | 0.644418 |
xguerin
|
85183b4114cbd1d8ce1bd978f58c2abb97c1a5d7
| 3,095 |
cpp
|
C++
|
CREP/utility.cpp
|
martinschonger/aerdg
|
d28df9fc9e2e0780f6e492e378320ed004e516ea
|
[
"MIT"
] | null | null | null |
CREP/utility.cpp
|
martinschonger/aerdg
|
d28df9fc9e2e0780f6e492e378320ed004e516ea
|
[
"MIT"
] | null | null | null |
CREP/utility.cpp
|
martinschonger/aerdg
|
d28df9fc9e2e0780f6e492e378320ed004e516ea
|
[
"MIT"
] | null | null | null |
/*
Implementation of some functions declared in utility.h.
*/
#include "utility.h"
namespace crep
{
tstamp_ util::CUR_TIME = 0;
tstamp_ util::CUR_TIME_AGE = 0;
//Begin: legacy code
dur util::charikar_partial_time_detailed = dur(0);
dur util::charikar_partial_time_detailed2 = dur(0);
dur util::charikar_partial_time_detailed3 = dur(0);
std::vector<std::vector<std::pair<int32_t, int32_t>>> util::edge_ontime = std::vector<std::vector<std::pair<int32_t, int32_t>>>();
std::vector<log_cluster_assignment_record> util::cluster_assignment = std::vector<log_cluster_assignment_record>();
std::vector<std::pair<int32_t, int32_t>> util::cluster = std::vector<std::pair<int32_t, int32_t>>();
//End: legacy code
void append_to_file(std::string filename, std::string new_content)
{
std::ofstream ost{ filename, std::ios_base::app };
ost << new_content << std::endl;
ost.close();
}
std::string get_timestamp()
{
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::ostringstream oss;
oss << std::put_time(&tm, "%Y%m%d-%H%M%S");
auto str = oss.str();
return str;
}
std::string get_project_root()
{
#if defined(__GNUC__)
return "/mnt/c/Users/Martin Schonger/source/repos/CREP/";
#elif defined(_MSC_VER)
return "C:/Users/Martin Schonger/source/repos/CREP/";
#endif
}
std::string get_log_dir()
{
#if defined(__GNUC__)
return "/mnt/c/Users/Martin Schonger/source/repos/crep_eval/log/";
#elif defined(_MSC_VER)
return "C:/Users/Martin Schonger/source/repos/crep_eval/log/";
#endif
}
std::map<std::string, std::string> read_config(const std::string& filename)
{
std::map<std::string, std::string> res;
std::ifstream is_file(filename);
if (!is_file.is_open())
{
std::cerr << "[ERROR] Failed to open config file '" << filename << "'." << std::endl;
}
else
{
//Inspired by https://stackoverflow.com/a/6892829/2868795 (Author: sbi).
//Note that for this snippet a license different from the one specified by the LICENSE file in the root directory might apply.
//Begin: snippet
std::string line;
while (std::getline(is_file, line))
{
std::istringstream is_line(line);
std::string key;
if (std::getline(is_line, key, '='))
{
std::string value;
if (std::getline(is_line, value))
{
res.emplace(key, trim(value));
}
}
}
//End: snippet
}
return res;
}
//Begin: legacy code
namespace prob
{
double exp(const double lambda, const double& x)
{
return lambda * std::exp((-lambda) * x);
}
double exp_log(const double p, const double beta, const double& x)
{
return (1 / (-std::log(p)))
* ((beta * (1 - p) * std::exp((-beta) * x))
/ (1 - (1 - p) * std::exp((-beta) * x)));
}
double beta(const double alpha, const double beta, const double& x)
{
return (std::pow(x, alpha - 1.0) * std::pow(1.0 - x, beta - 1.0)) / std::beta(alpha, beta);
}
}
//End: legacy code
}
// Copyright (c) 2019 Martin Schonger
| 26.452991 | 132 | 0.630048 |
martinschonger
|
851efea545fc612423498046f866042e0173dee5
| 17,573 |
cpp
|
C++
|
aws-cpp-sdk-ec2/source/model/IpamPool.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1 |
2022-01-05T18:20:03.000Z
|
2022-01-05T18:20:03.000Z
|
aws-cpp-sdk-ec2/source/model/IpamPool.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1 |
2022-01-03T23:59:37.000Z
|
2022-01-03T23:59:37.000Z
|
aws-cpp-sdk-ec2/source/model/IpamPool.cpp
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1 |
2021-11-09T11:58:03.000Z
|
2021-11-09T11:58:03.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/ec2/model/IpamPool.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
namespace Aws
{
namespace EC2
{
namespace Model
{
IpamPool::IpamPool() :
m_ownerIdHasBeenSet(false),
m_ipamPoolIdHasBeenSet(false),
m_sourceIpamPoolIdHasBeenSet(false),
m_ipamPoolArnHasBeenSet(false),
m_ipamScopeArnHasBeenSet(false),
m_ipamScopeType(IpamScopeType::NOT_SET),
m_ipamScopeTypeHasBeenSet(false),
m_ipamArnHasBeenSet(false),
m_ipamRegionHasBeenSet(false),
m_localeHasBeenSet(false),
m_poolDepth(0),
m_poolDepthHasBeenSet(false),
m_state(IpamPoolState::NOT_SET),
m_stateHasBeenSet(false),
m_stateMessageHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_autoImport(false),
m_autoImportHasBeenSet(false),
m_publiclyAdvertisable(false),
m_publiclyAdvertisableHasBeenSet(false),
m_addressFamily(AddressFamily::NOT_SET),
m_addressFamilyHasBeenSet(false),
m_allocationMinNetmaskLength(0),
m_allocationMinNetmaskLengthHasBeenSet(false),
m_allocationMaxNetmaskLength(0),
m_allocationMaxNetmaskLengthHasBeenSet(false),
m_allocationDefaultNetmaskLength(0),
m_allocationDefaultNetmaskLengthHasBeenSet(false),
m_allocationResourceTagsHasBeenSet(false),
m_tagsHasBeenSet(false),
m_awsService(IpamPoolAwsService::NOT_SET),
m_awsServiceHasBeenSet(false)
{
}
IpamPool::IpamPool(const XmlNode& xmlNode) :
m_ownerIdHasBeenSet(false),
m_ipamPoolIdHasBeenSet(false),
m_sourceIpamPoolIdHasBeenSet(false),
m_ipamPoolArnHasBeenSet(false),
m_ipamScopeArnHasBeenSet(false),
m_ipamScopeType(IpamScopeType::NOT_SET),
m_ipamScopeTypeHasBeenSet(false),
m_ipamArnHasBeenSet(false),
m_ipamRegionHasBeenSet(false),
m_localeHasBeenSet(false),
m_poolDepth(0),
m_poolDepthHasBeenSet(false),
m_state(IpamPoolState::NOT_SET),
m_stateHasBeenSet(false),
m_stateMessageHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_autoImport(false),
m_autoImportHasBeenSet(false),
m_publiclyAdvertisable(false),
m_publiclyAdvertisableHasBeenSet(false),
m_addressFamily(AddressFamily::NOT_SET),
m_addressFamilyHasBeenSet(false),
m_allocationMinNetmaskLength(0),
m_allocationMinNetmaskLengthHasBeenSet(false),
m_allocationMaxNetmaskLength(0),
m_allocationMaxNetmaskLengthHasBeenSet(false),
m_allocationDefaultNetmaskLength(0),
m_allocationDefaultNetmaskLengthHasBeenSet(false),
m_allocationResourceTagsHasBeenSet(false),
m_tagsHasBeenSet(false),
m_awsService(IpamPoolAwsService::NOT_SET),
m_awsServiceHasBeenSet(false)
{
*this = xmlNode;
}
IpamPool& IpamPool::operator =(const XmlNode& xmlNode)
{
XmlNode resultNode = xmlNode;
if(!resultNode.IsNull())
{
XmlNode ownerIdNode = resultNode.FirstChild("ownerId");
if(!ownerIdNode.IsNull())
{
m_ownerId = Aws::Utils::Xml::DecodeEscapedXmlText(ownerIdNode.GetText());
m_ownerIdHasBeenSet = true;
}
XmlNode ipamPoolIdNode = resultNode.FirstChild("ipamPoolId");
if(!ipamPoolIdNode.IsNull())
{
m_ipamPoolId = Aws::Utils::Xml::DecodeEscapedXmlText(ipamPoolIdNode.GetText());
m_ipamPoolIdHasBeenSet = true;
}
XmlNode sourceIpamPoolIdNode = resultNode.FirstChild("sourceIpamPoolId");
if(!sourceIpamPoolIdNode.IsNull())
{
m_sourceIpamPoolId = Aws::Utils::Xml::DecodeEscapedXmlText(sourceIpamPoolIdNode.GetText());
m_sourceIpamPoolIdHasBeenSet = true;
}
XmlNode ipamPoolArnNode = resultNode.FirstChild("ipamPoolArn");
if(!ipamPoolArnNode.IsNull())
{
m_ipamPoolArn = Aws::Utils::Xml::DecodeEscapedXmlText(ipamPoolArnNode.GetText());
m_ipamPoolArnHasBeenSet = true;
}
XmlNode ipamScopeArnNode = resultNode.FirstChild("ipamScopeArn");
if(!ipamScopeArnNode.IsNull())
{
m_ipamScopeArn = Aws::Utils::Xml::DecodeEscapedXmlText(ipamScopeArnNode.GetText());
m_ipamScopeArnHasBeenSet = true;
}
XmlNode ipamScopeTypeNode = resultNode.FirstChild("ipamScopeType");
if(!ipamScopeTypeNode.IsNull())
{
m_ipamScopeType = IpamScopeTypeMapper::GetIpamScopeTypeForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(ipamScopeTypeNode.GetText()).c_str()).c_str());
m_ipamScopeTypeHasBeenSet = true;
}
XmlNode ipamArnNode = resultNode.FirstChild("ipamArn");
if(!ipamArnNode.IsNull())
{
m_ipamArn = Aws::Utils::Xml::DecodeEscapedXmlText(ipamArnNode.GetText());
m_ipamArnHasBeenSet = true;
}
XmlNode ipamRegionNode = resultNode.FirstChild("ipamRegion");
if(!ipamRegionNode.IsNull())
{
m_ipamRegion = Aws::Utils::Xml::DecodeEscapedXmlText(ipamRegionNode.GetText());
m_ipamRegionHasBeenSet = true;
}
XmlNode localeNode = resultNode.FirstChild("locale");
if(!localeNode.IsNull())
{
m_locale = Aws::Utils::Xml::DecodeEscapedXmlText(localeNode.GetText());
m_localeHasBeenSet = true;
}
XmlNode poolDepthNode = resultNode.FirstChild("poolDepth");
if(!poolDepthNode.IsNull())
{
m_poolDepth = StringUtils::ConvertToInt32(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(poolDepthNode.GetText()).c_str()).c_str());
m_poolDepthHasBeenSet = true;
}
XmlNode stateNode = resultNode.FirstChild("state");
if(!stateNode.IsNull())
{
m_state = IpamPoolStateMapper::GetIpamPoolStateForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(stateNode.GetText()).c_str()).c_str());
m_stateHasBeenSet = true;
}
XmlNode stateMessageNode = resultNode.FirstChild("stateMessage");
if(!stateMessageNode.IsNull())
{
m_stateMessage = Aws::Utils::Xml::DecodeEscapedXmlText(stateMessageNode.GetText());
m_stateMessageHasBeenSet = true;
}
XmlNode descriptionNode = resultNode.FirstChild("description");
if(!descriptionNode.IsNull())
{
m_description = Aws::Utils::Xml::DecodeEscapedXmlText(descriptionNode.GetText());
m_descriptionHasBeenSet = true;
}
XmlNode autoImportNode = resultNode.FirstChild("autoImport");
if(!autoImportNode.IsNull())
{
m_autoImport = StringUtils::ConvertToBool(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(autoImportNode.GetText()).c_str()).c_str());
m_autoImportHasBeenSet = true;
}
XmlNode publiclyAdvertisableNode = resultNode.FirstChild("publiclyAdvertisable");
if(!publiclyAdvertisableNode.IsNull())
{
m_publiclyAdvertisable = StringUtils::ConvertToBool(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(publiclyAdvertisableNode.GetText()).c_str()).c_str());
m_publiclyAdvertisableHasBeenSet = true;
}
XmlNode addressFamilyNode = resultNode.FirstChild("addressFamily");
if(!addressFamilyNode.IsNull())
{
m_addressFamily = AddressFamilyMapper::GetAddressFamilyForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(addressFamilyNode.GetText()).c_str()).c_str());
m_addressFamilyHasBeenSet = true;
}
XmlNode allocationMinNetmaskLengthNode = resultNode.FirstChild("allocationMinNetmaskLength");
if(!allocationMinNetmaskLengthNode.IsNull())
{
m_allocationMinNetmaskLength = StringUtils::ConvertToInt32(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(allocationMinNetmaskLengthNode.GetText()).c_str()).c_str());
m_allocationMinNetmaskLengthHasBeenSet = true;
}
XmlNode allocationMaxNetmaskLengthNode = resultNode.FirstChild("allocationMaxNetmaskLength");
if(!allocationMaxNetmaskLengthNode.IsNull())
{
m_allocationMaxNetmaskLength = StringUtils::ConvertToInt32(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(allocationMaxNetmaskLengthNode.GetText()).c_str()).c_str());
m_allocationMaxNetmaskLengthHasBeenSet = true;
}
XmlNode allocationDefaultNetmaskLengthNode = resultNode.FirstChild("allocationDefaultNetmaskLength");
if(!allocationDefaultNetmaskLengthNode.IsNull())
{
m_allocationDefaultNetmaskLength = StringUtils::ConvertToInt32(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(allocationDefaultNetmaskLengthNode.GetText()).c_str()).c_str());
m_allocationDefaultNetmaskLengthHasBeenSet = true;
}
XmlNode allocationResourceTagsNode = resultNode.FirstChild("allocationResourceTagSet");
if(!allocationResourceTagsNode.IsNull())
{
XmlNode allocationResourceTagsMember = allocationResourceTagsNode.FirstChild("item");
while(!allocationResourceTagsMember.IsNull())
{
m_allocationResourceTags.push_back(allocationResourceTagsMember);
allocationResourceTagsMember = allocationResourceTagsMember.NextNode("item");
}
m_allocationResourceTagsHasBeenSet = true;
}
XmlNode tagsNode = resultNode.FirstChild("tagSet");
if(!tagsNode.IsNull())
{
XmlNode tagsMember = tagsNode.FirstChild("item");
while(!tagsMember.IsNull())
{
m_tags.push_back(tagsMember);
tagsMember = tagsMember.NextNode("item");
}
m_tagsHasBeenSet = true;
}
XmlNode awsServiceNode = resultNode.FirstChild("awsService");
if(!awsServiceNode.IsNull())
{
m_awsService = IpamPoolAwsServiceMapper::GetIpamPoolAwsServiceForName(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(awsServiceNode.GetText()).c_str()).c_str());
m_awsServiceHasBeenSet = true;
}
}
return *this;
}
void IpamPool::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
if(m_ownerIdHasBeenSet)
{
oStream << location << index << locationValue << ".OwnerId=" << StringUtils::URLEncode(m_ownerId.c_str()) << "&";
}
if(m_ipamPoolIdHasBeenSet)
{
oStream << location << index << locationValue << ".IpamPoolId=" << StringUtils::URLEncode(m_ipamPoolId.c_str()) << "&";
}
if(m_sourceIpamPoolIdHasBeenSet)
{
oStream << location << index << locationValue << ".SourceIpamPoolId=" << StringUtils::URLEncode(m_sourceIpamPoolId.c_str()) << "&";
}
if(m_ipamPoolArnHasBeenSet)
{
oStream << location << index << locationValue << ".IpamPoolArn=" << StringUtils::URLEncode(m_ipamPoolArn.c_str()) << "&";
}
if(m_ipamScopeArnHasBeenSet)
{
oStream << location << index << locationValue << ".IpamScopeArn=" << StringUtils::URLEncode(m_ipamScopeArn.c_str()) << "&";
}
if(m_ipamScopeTypeHasBeenSet)
{
oStream << location << index << locationValue << ".IpamScopeType=" << IpamScopeTypeMapper::GetNameForIpamScopeType(m_ipamScopeType) << "&";
}
if(m_ipamArnHasBeenSet)
{
oStream << location << index << locationValue << ".IpamArn=" << StringUtils::URLEncode(m_ipamArn.c_str()) << "&";
}
if(m_ipamRegionHasBeenSet)
{
oStream << location << index << locationValue << ".IpamRegion=" << StringUtils::URLEncode(m_ipamRegion.c_str()) << "&";
}
if(m_localeHasBeenSet)
{
oStream << location << index << locationValue << ".Locale=" << StringUtils::URLEncode(m_locale.c_str()) << "&";
}
if(m_poolDepthHasBeenSet)
{
oStream << location << index << locationValue << ".PoolDepth=" << m_poolDepth << "&";
}
if(m_stateHasBeenSet)
{
oStream << location << index << locationValue << ".State=" << IpamPoolStateMapper::GetNameForIpamPoolState(m_state) << "&";
}
if(m_stateMessageHasBeenSet)
{
oStream << location << index << locationValue << ".StateMessage=" << StringUtils::URLEncode(m_stateMessage.c_str()) << "&";
}
if(m_descriptionHasBeenSet)
{
oStream << location << index << locationValue << ".Description=" << StringUtils::URLEncode(m_description.c_str()) << "&";
}
if(m_autoImportHasBeenSet)
{
oStream << location << index << locationValue << ".AutoImport=" << std::boolalpha << m_autoImport << "&";
}
if(m_publiclyAdvertisableHasBeenSet)
{
oStream << location << index << locationValue << ".PubliclyAdvertisable=" << std::boolalpha << m_publiclyAdvertisable << "&";
}
if(m_addressFamilyHasBeenSet)
{
oStream << location << index << locationValue << ".AddressFamily=" << AddressFamilyMapper::GetNameForAddressFamily(m_addressFamily) << "&";
}
if(m_allocationMinNetmaskLengthHasBeenSet)
{
oStream << location << index << locationValue << ".AllocationMinNetmaskLength=" << m_allocationMinNetmaskLength << "&";
}
if(m_allocationMaxNetmaskLengthHasBeenSet)
{
oStream << location << index << locationValue << ".AllocationMaxNetmaskLength=" << m_allocationMaxNetmaskLength << "&";
}
if(m_allocationDefaultNetmaskLengthHasBeenSet)
{
oStream << location << index << locationValue << ".AllocationDefaultNetmaskLength=" << m_allocationDefaultNetmaskLength << "&";
}
if(m_allocationResourceTagsHasBeenSet)
{
unsigned allocationResourceTagsIdx = 1;
for(auto& item : m_allocationResourceTags)
{
Aws::StringStream allocationResourceTagsSs;
allocationResourceTagsSs << location << index << locationValue << ".AllocationResourceTagSet." << allocationResourceTagsIdx++;
item.OutputToStream(oStream, allocationResourceTagsSs.str().c_str());
}
}
if(m_tagsHasBeenSet)
{
unsigned tagsIdx = 1;
for(auto& item : m_tags)
{
Aws::StringStream tagsSs;
tagsSs << location << index << locationValue << ".TagSet." << tagsIdx++;
item.OutputToStream(oStream, tagsSs.str().c_str());
}
}
if(m_awsServiceHasBeenSet)
{
oStream << location << index << locationValue << ".AwsService=" << IpamPoolAwsServiceMapper::GetNameForIpamPoolAwsService(m_awsService) << "&";
}
}
void IpamPool::OutputToStream(Aws::OStream& oStream, const char* location) const
{
if(m_ownerIdHasBeenSet)
{
oStream << location << ".OwnerId=" << StringUtils::URLEncode(m_ownerId.c_str()) << "&";
}
if(m_ipamPoolIdHasBeenSet)
{
oStream << location << ".IpamPoolId=" << StringUtils::URLEncode(m_ipamPoolId.c_str()) << "&";
}
if(m_sourceIpamPoolIdHasBeenSet)
{
oStream << location << ".SourceIpamPoolId=" << StringUtils::URLEncode(m_sourceIpamPoolId.c_str()) << "&";
}
if(m_ipamPoolArnHasBeenSet)
{
oStream << location << ".IpamPoolArn=" << StringUtils::URLEncode(m_ipamPoolArn.c_str()) << "&";
}
if(m_ipamScopeArnHasBeenSet)
{
oStream << location << ".IpamScopeArn=" << StringUtils::URLEncode(m_ipamScopeArn.c_str()) << "&";
}
if(m_ipamScopeTypeHasBeenSet)
{
oStream << location << ".IpamScopeType=" << IpamScopeTypeMapper::GetNameForIpamScopeType(m_ipamScopeType) << "&";
}
if(m_ipamArnHasBeenSet)
{
oStream << location << ".IpamArn=" << StringUtils::URLEncode(m_ipamArn.c_str()) << "&";
}
if(m_ipamRegionHasBeenSet)
{
oStream << location << ".IpamRegion=" << StringUtils::URLEncode(m_ipamRegion.c_str()) << "&";
}
if(m_localeHasBeenSet)
{
oStream << location << ".Locale=" << StringUtils::URLEncode(m_locale.c_str()) << "&";
}
if(m_poolDepthHasBeenSet)
{
oStream << location << ".PoolDepth=" << m_poolDepth << "&";
}
if(m_stateHasBeenSet)
{
oStream << location << ".State=" << IpamPoolStateMapper::GetNameForIpamPoolState(m_state) << "&";
}
if(m_stateMessageHasBeenSet)
{
oStream << location << ".StateMessage=" << StringUtils::URLEncode(m_stateMessage.c_str()) << "&";
}
if(m_descriptionHasBeenSet)
{
oStream << location << ".Description=" << StringUtils::URLEncode(m_description.c_str()) << "&";
}
if(m_autoImportHasBeenSet)
{
oStream << location << ".AutoImport=" << std::boolalpha << m_autoImport << "&";
}
if(m_publiclyAdvertisableHasBeenSet)
{
oStream << location << ".PubliclyAdvertisable=" << std::boolalpha << m_publiclyAdvertisable << "&";
}
if(m_addressFamilyHasBeenSet)
{
oStream << location << ".AddressFamily=" << AddressFamilyMapper::GetNameForAddressFamily(m_addressFamily) << "&";
}
if(m_allocationMinNetmaskLengthHasBeenSet)
{
oStream << location << ".AllocationMinNetmaskLength=" << m_allocationMinNetmaskLength << "&";
}
if(m_allocationMaxNetmaskLengthHasBeenSet)
{
oStream << location << ".AllocationMaxNetmaskLength=" << m_allocationMaxNetmaskLength << "&";
}
if(m_allocationDefaultNetmaskLengthHasBeenSet)
{
oStream << location << ".AllocationDefaultNetmaskLength=" << m_allocationDefaultNetmaskLength << "&";
}
if(m_allocationResourceTagsHasBeenSet)
{
unsigned allocationResourceTagsIdx = 1;
for(auto& item : m_allocationResourceTags)
{
Aws::StringStream allocationResourceTagsSs;
allocationResourceTagsSs << location << ".AllocationResourceTagSet." << allocationResourceTagsIdx++;
item.OutputToStream(oStream, allocationResourceTagsSs.str().c_str());
}
}
if(m_tagsHasBeenSet)
{
unsigned tagsIdx = 1;
for(auto& item : m_tags)
{
Aws::StringStream tagsSs;
tagsSs << location << ".TagSet." << tagsIdx++;
item.OutputToStream(oStream, tagsSs.str().c_str());
}
}
if(m_awsServiceHasBeenSet)
{
oStream << location << ".AwsService=" << IpamPoolAwsServiceMapper::GetNameForIpamPoolAwsService(m_awsService) << "&";
}
}
} // namespace Model
} // namespace EC2
} // namespace Aws
| 36.307851 | 189 | 0.702157 |
perfectrecall
|
8521e0922a05bd286fa561d8f883e4165bb6c0ba
| 1,224 |
cpp
|
C++
|
src/svLibrary/src/Engine.cpp
|
sevanspowell/sev
|
c678aaab3a9e6bd4e5b98774205c8775c9a3291d
|
[
"MIT"
] | null | null | null |
src/svLibrary/src/Engine.cpp
|
sevanspowell/sev
|
c678aaab3a9e6bd4e5b98774205c8775c9a3291d
|
[
"MIT"
] | 1 |
2017-06-11T06:34:50.000Z
|
2017-06-11T06:34:50.000Z
|
src/svLibrary/src/Engine.cpp
|
sevanspowell/sev
|
c678aaab3a9e6bd4e5b98774205c8775c9a3291d
|
[
"MIT"
] | null | null | null |
#include <cassert>
#include <sstream>
#include <sv/Engine.h>
#include <sv/Globals.h>
#include <sv/ProgramOptions.h>
#include <sv/platform/SDL2Platform.h>
namespace sv {
Engine::Engine() {
isInitialized = false;
platform = std::shared_ptr<Platform>(new SDL2Platform());
}
Engine::~Engine() {
if (isInitialized == true) {
platform->shutdown();
}
}
bool Engine::initialize(int argc, char *argv[]) {
isInitialized = true;
ProgramOptions options(argc, (const char **)argv);
// Find game to load
// std::string game("default");
// int32_t optionIndex = options.checkOption("--game");
// if (optionIndex >= 0) {
// const char *gameOption = options.getOption(optionIndex + 1);
// if (gameOption != nullptr) {
// game = std::string(gameOption);
// }
// }
// Get config file path
// std::stringstream configFilePath;
// configFilePath << game << "/config.cfg" << std::endl;
isInitialized &= client.initialize(options);
isInitialized &= platform->initialize();
return isInitialized;
}
uint32_t Engine::getMilliseconds() const {
assert(isInitialized == true);
return platform->getMilliseconds();
}
}
| 23.538462 | 71 | 0.625817 |
sevanspowell
|
8522913d7710c96bb191a5516028f509c2f728ca
| 715 |
cpp
|
C++
|
2021.11.11-Homework-5/Project5/Source.cpp
|
021213/programming-c-rus-2021-2022
|
58d981f5b63554594705f597aad76bbfa6777988
|
[
"Apache-2.0"
] | null | null | null |
2021.11.11-Homework-5/Project5/Source.cpp
|
021213/programming-c-rus-2021-2022
|
58d981f5b63554594705f597aad76bbfa6777988
|
[
"Apache-2.0"
] | null | null | null |
2021.11.11-Homework-5/Project5/Source.cpp
|
021213/programming-c-rus-2021-2022
|
58d981f5b63554594705f597aad76bbfa6777988
|
[
"Apache-2.0"
] | null | null | null |
#include<iostream>
using namespace std;
int main(int argc, char* argv[])
{
int choice = 0;
int count = 0;
int capacity = 3;
int* a = new int[capacity] { 0 };
int element = 0;
do
{
cin >> choice;
switch (choice)
{
case 1:
cout << "[" << count << "/" << capacity << "] : ";
for (int i = 0; i < count; ++i)
{
cout << a[i] << " ";
}
cout << endl;
break;
case 2:
cin >> element;
if (count == capacity)
{
int* temp = new int[capacity * 2]{ 0 };
for (int i = 0; i < capacity; ++i)
{
temp[i] = a[i];
}
delete[] a;
a = temp;
capacity *= 2;
}
a[count] = element;
++count;
break;
}
} while (choice != 0);
return EXIT_SUCCESS;
}
| 16.25 | 53 | 0.483916 |
021213
|
8526dab9bfc639c7b5cb90b3a340e96be8d9cd89
| 201 |
cpp
|
C++
|
Easy/172_Factorial_Trailing_Zeroes.cpp
|
ShehabMMohamed/LeetCodeCPP
|
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
|
[
"MIT"
] | 1 |
2021-03-15T10:02:10.000Z
|
2021-03-15T10:02:10.000Z
|
Easy/172_Factorial_Trailing_Zeroes.cpp
|
ShehabMMohamed/LeetCodeCPP
|
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
|
[
"MIT"
] | null | null | null |
Easy/172_Factorial_Trailing_Zeroes.cpp
|
ShehabMMohamed/LeetCodeCPP
|
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int trailingZeroes(int n) {
int trails = 0;
for(long long int i = 5; n/i > 0; i*=5) {
trails += (n/i);
}
return trails;
}
};
| 20.1 | 49 | 0.452736 |
ShehabMMohamed
|
852bae421dee27b71e48ffd59f87498c7b2defc2
| 23,028 |
hpp
|
C++
|
include/Vector/GenericLengthedVector.hpp
|
Renardjojo/RenardMath
|
74b4e65cf8f663eda830e00a1c61b563f711288c
|
[
"MIT"
] | null | null | null |
include/Vector/GenericLengthedVector.hpp
|
Renardjojo/RenardMath
|
74b4e65cf8f663eda830e00a1c61b563f711288c
|
[
"MIT"
] | null | null | null |
include/Vector/GenericLengthedVector.hpp
|
Renardjojo/RenardMath
|
74b4e65cf8f663eda830e00a1c61b563f711288c
|
[
"MIT"
] | null | null | null |
/*
* Project : FoxMath
* Editing by Six Jonathan
* Date : 2020-08-28 - 10 h 03
*
*
* MIT License
*
* Copyright (c) 2020 Six Jonathan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include "Vector/GenericVector.hpp"
#include "Macro/CrossInheritanceCompatibility.hpp"
namespace FoxMath
{
/**
* @brief Lengthed vector save vector length. This fact optimize length computation of vector but use more memory to save this variable. Use it if you want to know frequently the vector length with vector that don't move between each length check
*
* @tparam TLength
* @tparam TType
*/
template <size_t TLength, typename TType>
class GenericLengthedVector final : public GenericVector<TLength, TType>
{
private:
using Parent = GenericVector<TLength, TType>;
protected:
#pragma region attribut
TType m_length;
bool m_lengthIsDirty = true;
#pragma endregion //!attribut
public:
#pragma region constructor/destructor
constexpr inline
GenericLengthedVector () noexcept = default;
constexpr inline
GenericLengthedVector (const GenericLengthedVector& other) noexcept = default;
constexpr inline
GenericLengthedVector (GenericLengthedVector&& other) noexcept = default;
inline
~GenericLengthedVector () noexcept = default;
constexpr inline
GenericLengthedVector& operator=(GenericLengthedVector const& other) noexcept = default;
constexpr inline
GenericLengthedVector& operator=(GenericLengthedVector && other) noexcept = default;
DECLARE_CROSS_INHERITANCE_COMPATIBILTY(GenericLengthedVector, Parent, GenericVector)
#pragma endregion //!constructor/destructor
#pragma region methods
/**
* @brief Fill generic vector's member with scalar value
*
* @tparam TscalarType
* @tparam true
* @param scalar
* @return constexpr GenericLengthedVector&
*/
template<typename TscalarType, IsArithmetic<TscalarType> = true>
inline constexpr
GenericLengthedVector& fill (const TscalarType scalar) noexcept
{
m_lengthIsDirty = true;
return GenericVector<TLength, TType>::fill(scalar);
}
/**
* @brief Deprecated to avoid compare distance hack (Less optimized than check directly the length).
* If you really want the squart length ask it explicitely with length() * length()
*
*/
TType squareLength () const noexcept = delete;
/**
* @brief Homogenize vector to the lower dimension
* @note devise each component by the last
* @example to convert vector 4 to vector 3 it must be homogenize to lose it fourth dimension
*
* @return constexpr GenericLengthedVector&
*/
inline constexpr
GenericLengthedVector& homogenize () noexcept
{
m_length /= Parent::m_data[TLength - 1];
return GenericVector<TLength, TType>::homogenize();
}
/**
* @brief Normalize the generic vector. If the generic vector is null (all components are set to 0), nothing is done.
*
* @return constexpr GenericLengthedVector&
*/
inline constexpr
GenericLengthedVector& normalize () noexcept
{
if (m_length) [[likely]]
{
for (size_t i = 0; i < TLength; i++)
Parent::m_data[i] /= m_length;
}
m_length = static_cast<TType>(1);
return *this;
}
/**
* @brief Clamp the generic vector's length to max value
*
* @param maxLength
* @return constexpr GenericLengthedVector&
*/
inline constexpr
GenericLengthedVector& clampLength (TType maxLength) noexcept
{
if (m_length > maxLength) [[likely]]
{
const TType coef = maxLength / m_length;
*this *= coef;
m_length = maxLength;
}
return *this;
}
/**
* @brief perform cross product with another generic vector
*
* @param other
* @return constexpr GenericLengthedVector&
*/
inline constexpr
GenericLengthedVector& cross (const GenericVector<TLength, TType>& other) noexcept
{
m_lengthIsDirty = true;
return GenericVector<TLength, TType>::cross(other);
}
/**
* @brief Performs a linear interpolation between 2 generic vectors of the same type.
*
* @param other
* @param t
* @return constexpr GenericLengthedVector&
*/
inline constexpr
GenericLengthedVector& lerp (const GenericVector<TLength, TType>& other, TType t) noexcept
{
m_lengthIsDirty = true;
return GenericVector<TLength, TType>::lerp(other, t);
}
/**
* @brief Performs a reflection with a normal generic vector
*
* @param normalNormalized : Normal must be normalized
* @return constexpr GenericLengthedVector&
*/
inline constexpr
GenericLengthedVector& reflect (const GenericVector<TLength, TType>& normalNormalized) noexcept
{
m_lengthIsDirty = true;
return GenericVector<TLength, TType>::reflect(normalNormalized);
}
/**
* @brief Set the magnitude of the current generic vector
*
* @param newLength
* @return constexpr GenericLengthedVector&
*/
inline constexpr
GenericLengthedVector& setLength (TType newLength) noexcept
{
const TType coef = newLength / m_length;
*this *= coef;
m_length = newLength;
return *this;
}
/**
* @brief rotate generic vector around another unit generic vector. This function assert if axis is not unit
*
* @param unitAxis
* @param angleRad
*/
inline constexpr
GenericLengthedVector& rotateAroundAxis (const GenericVector<TLength, TType>& unitAxis, const Angle<EAngleType::Radian, TType>& angle) noexcept
{
m_lengthIsDirty = true;
return GenericVector<TLength, TType>::rotateAroundAxis(unitAxis, angle);
}
#pragma endregion //!methods
#pragma region accessor
/**
* @brief return magnitude of the generic vector
*
* @return constexpr cnost TType
*/
[[nodiscard]] inline constexpr
const TType length () noexcept
{
if (m_lengthIsDirty)
{
m_length = GenericVector<TLength, TType>::length();
m_lengthIsDirty = false;
}
return m_length;
}
/**
* @brief return magnitude of the generic vector
*
* @note TODO: When vector is create, constructor must compute the vector length
*
* @return constexpr cnost TType
*/
[[nodiscard]] inline constexpr
const TType length () const noexcept
{
return m_length;
}
#pragma endregion //!accessor
#pragma region mutator
/**
* @brief Set the Data a index
*
* A similar member function, GenericsetDataAt, has the same behavior as this operator function,
* except that GenericsetDataAt is bound-checked and signals if the requested position is out of range by throwing an out_of_range exception.
*
* Portable programs should never call this function with an argument index that is out of range,
* since this causes undefined behavior.
*
* @tparam TscalarType
* @tparam true
* @param index
* @param scalar
* @return constexpr GenericLengthedVector&
*/
template<typename TscalarType, IsArithmetic<TscalarType> = true>
inline constexpr
GenericLengthedVector& setData(size_t index, TscalarType scalar) noexcept
{
assert(index < TLength);
Parent::m_data[index] = static_cast<TType>(scalar);
m_lengthIsDirty = true;
return *this;
}
/**
* @brief Set the Data at index
*
* The function automatically checks whether index is within the bounds of valid elements in the GenericVector, throwing an out_of_range exception if it is not (i.e., if n is greater than, or equal to, its size).
* This is in contrast with function GenericsetData, that does not check against bounds.
*
* @tparam TscalarType
* @tparam true
* @param index
* @param scalar
* @return constexpr GenericLengthedVector&
*/
template<typename TscalarType, IsArithmetic<TscalarType> = true>
inline constexpr
GenericLengthedVector& setDataAt(size_t index, TscalarType scalar) throw ()
{
if (index < TLength) [[likely]]
{
Parent::m_data[index] = static_cast<TType>(scalar);
m_lengthIsDirty = true;
return *this;
}
std::__throw_out_of_range_fmt(__N("Genericat: index"
"(which is %zu) >= TLength "
"(which is %zu)"),
index, TLength);
}
#pragma endregion //!mutator
#pragma region operator
#pragma region member access operators
#pragma endregion //!member access operators
#pragma region assignment operators
/**
* @brief fill the vector with scalar assigned
*
* @tparam TscalarType
* @tparam true
* @param scalar
* @return implicit constexpr&
*/
template<typename TscalarType, IsArithmetic<TscalarType> = true>
implicit inline constexpr
GenericLengthedVector& operator=(TscalarType scalar) noexcept
{
m_lengthIsDirty = true;
return Parent::operator=(scalar);
}
/**
* @brief addition assignment
*
* @tparam TscalarType
* @tparam true
* @param scalar
* @return constexpr GenericLengthedVector&
*/
template<typename TscalarType, IsArithmetic<TscalarType> = true>
inline constexpr
GenericLengthedVector& operator+=(TscalarType scalar) noexcept
{
m_lengthIsDirty = true;
return Parent::operator+=(scalar);
}
/**
* @brief addition assignment
*
* @tparam TLengthOther
* @tparam TType
* @param other
* @return constexpr GenericLengthedVector&
*/
template <size_t TLengthOther, typename TTypeOther>
inline constexpr
GenericLengthedVector& operator+=(const GenericVector<TLengthOther, TTypeOther>& other) noexcept
{
m_lengthIsDirty = true;
return Parent::operator+=(other);
}
/**
* @brief subtraction assignment
*
* @tparam TscalarType
* @tparam true
* @param scalar
* @return constexpr GenericLengthedVector&
*/
template<typename TscalarType, IsArithmetic<TscalarType> = true>
inline constexpr
GenericLengthedVector& operator-=(TscalarType scalar) noexcept
{
m_lengthIsDirty = true;
return Parent::operator-=(scalar);
}
/**
* @brief subtraction assignment
*
* @tparam TLengthOther
* @tparam TType
* @param other
* @return constexpr GenericLengthedVector&
*/
template <size_t TLengthOther, typename TTypeOther>
inline constexpr
GenericLengthedVector& operator-=(const GenericVector<TLengthOther, TTypeOther>& other) noexcept
{
m_lengthIsDirty = true;
return Parent::operator-=(other);
}
/**
* @brief multiplication assignment
*
* @tparam TscalarType
* @tparam true
* @param scalar
* @return constexpr GenericLengthedVector&
*/
template<typename TscalarType, IsArithmetic<TscalarType> = true>
inline constexpr
GenericLengthedVector& operator*=(TscalarType scalar) noexcept
{
m_lengthIsDirty = true;
return Parent::operator*=(scalar);
}
/**
* @brief multiplication assignment
*
* @tparam TLengthOther
* @tparam TType
* @param other
* @return constexpr GenericLengthedVector&
*/
template <size_t TLengthOther, typename TTypeOther>
inline constexpr
GenericLengthedVector& operator*=(const GenericVector<TLengthOther, TTypeOther>& other) noexcept
{
m_lengthIsDirty = true;
return Parent::operator*=(other);
}
/**
* @brief division assignment
*
* @tparam TscalarType
* @tparam true
* @param scalar
* @return constexpr GenericLengthedVector&
*/
template<typename TscalarType, IsArithmetic<TscalarType> = true>
inline constexpr
GenericLengthedVector& operator/=(TscalarType scalar) noexcept
{
m_lengthIsDirty = true;
return Parent::operator/=(scalar);
}
/**
* @brief division assignment
*
* @tparam TLengthOther
* @tparam TType
* @param other
* @return constexpr GenericLengthedVector&
*/
template <size_t TLengthOther, typename TTypeOther>
inline constexpr
GenericLengthedVector& operator/=(const GenericVector<TLengthOther, TTypeOther>& other) noexcept
{
m_lengthIsDirty = true;
return Parent::operator/=(other);
}
/**
* @brief modulo assignment
*
* @tparam TscalarType
* @tparam true
* @param scalar
* @return constexpr GenericLengthedVector&
*/
template<typename TscalarType, IsArithmetic<TscalarType> = true>
inline constexpr
GenericLengthedVector& operator%=(TscalarType scalar) noexcept
{
m_lengthIsDirty = true;
return Parent::operator%=(scalar);
}
/**
* @brief modulo assignment
*
* @tparam TLengthOther
* @tparam TType
* @param other
* @return constexpr GenericLengthedVector&
*/
template <size_t TLengthOther, typename TTypeOther>
inline constexpr
GenericLengthedVector& operator%=(const GenericVector<TLengthOther, TTypeOther>& other) noexcept
{
m_lengthIsDirty = true;
return Parent::operator%=(other);
}
/**
* @brief bitwise AND assignment
*
* @tparam TscalarType
* @tparam true
* @param scalar
* @return constexpr GenericLengthedVector&
*/
template<typename TscalarType, IsArithmetic<TscalarType> = true>
inline constexpr
GenericLengthedVector& operator&=(TscalarType scalar) noexcept
{
m_lengthIsDirty = true;
return Parent::operator&=(scalar);
}
/**
* @brief bitwise AND assignment
*
* @tparam TLengthOther
* @tparam TType
* @param other
* @return constexpr GenericLengthedVector&
*/
template <size_t TLengthOther, typename TTypeOther>
inline constexpr
GenericLengthedVector& operator&=(const GenericVector<TLengthOther, TTypeOther>& other) noexcept
{
m_lengthIsDirty = true;
return Parent::operator&=(other);
}
/**
* @brief bitwise OR assignment
*
* @tparam TscalarType
* @tparam true
* @param scalar
* @return constexpr GenericLengthedVector&
*/
template<typename TscalarType, IsArithmetic<TscalarType> = true>
inline constexpr
GenericLengthedVector& operator|=(TscalarType scalar) noexcept
{
m_lengthIsDirty = true;
return Parent::operator|=(scalar);
}
/**
* @brief bitwise OR assignment
*
* @tparam TLengthOther
* @tparam TType
* @param other
* @return constexpr GenericLengthedVector&
*/
template <size_t TLengthOther, typename TTypeOther>
inline constexpr
GenericLengthedVector& operator|=(const GenericVector<TLengthOther, TTypeOther>& other) noexcept
{
m_lengthIsDirty = true;
return Parent::operator|=(other);
}
/**
* @brief bitwise XOR assignment
*
* @tparam TscalarType
* @tparam true
* @param scalar
* @return constexpr GenericLengthedVector&
*/
template<typename TscalarType, IsArithmetic<TscalarType> = true>
inline constexpr
GenericLengthedVector& operator^=(TscalarType scalar) noexcept
{
m_lengthIsDirty = true;
return Parent::operator^=(scalar);
}
/**
* @brief bitwise XOR assignment
*
* @tparam TLengthOther
* @tparam TType
* @param other
* @return constexpr GenericLengthedVector&
*/
template <size_t TLengthOther, typename TTypeOther>
inline constexpr
GenericLengthedVector& operator^=(const GenericVector<TLengthOther, TTypeOther>& other) noexcept
{
m_lengthIsDirty = true;
return Parent::operator^=(other);
}
/**
* @brief bitwise left shift assignment
*
* @tparam TscalarType
* @tparam true
* @param scalar
* @return constexpr GenericLengthedVector&
*/
template<typename TscalarType, IsArithmetic<TscalarType> = true>
inline constexpr
GenericLengthedVector& operator<<=(TscalarType scalar) noexcept
{
m_lengthIsDirty = true;
return Parent::operator<<=(scalar);
}
/**
* @brief bitwise left shift assignment
*
* @tparam TLengthOther
* @tparam TType
* @param other
* @return constexpr GenericLengthedVector&
*/
template <size_t TLengthOther, typename TTypeOther>
inline constexpr
GenericLengthedVector& operator<<=(const GenericVector<TLengthOther, TTypeOther>& other) noexcept
{
m_lengthIsDirty = true;
return Parent::operator<<=(other);
}
/**
* @brief bitwise right shift assignment
*
* @tparam TscalarType
* @tparam true
* @param scalar
* @return constexpr GenericLengthedVector&
*/
template<typename TscalarType, IsArithmetic<TscalarType> = true>
inline constexpr
GenericLengthedVector& operator>>=(TscalarType scalar) noexcept
{
m_lengthIsDirty = true;
return Parent::operator>>=(scalar);
}
/**
* @brief bitwise right shift assignment
*
* @tparam TLengthOther
* @tparam TType
* @param other
* @return constexpr GenericLengthedVector&
*/
template <size_t TLengthOther, typename TTypeOther>
inline constexpr
GenericLengthedVector& operator>>=(const GenericVector<TLengthOther, TTypeOther>& other) noexcept
{
m_lengthIsDirty = true;
return Parent::operator>>=(other);
}
#pragma endregion //!region assignment operators
#pragma region increment decrement operators
/**
* @brief pre-increment operator
*
* @return constexpr GenericLengthedVector&
*/
inline constexpr
GenericLengthedVector& operator++ () noexcept
{
m_lengthIsDirty = true;
return Parent::operator++();
}
/**
* @brief pre-decrement operator
*
* @return constexpr GenericLengthedVector&
*/
inline constexpr
GenericLengthedVector& operator-- () noexcept
{
m_lengthIsDirty = true;
return Parent::operator--();
}
/**
* @brief post-increment operator
*
* @return constexpr GenericLengthedVector
*/
inline constexpr
GenericLengthedVector operator++ (int) noexcept
{
m_lengthIsDirty = true;
return Parent::operator++();
}
/**
* @brief post-decrement operator
*
* @return constexpr GenericLengthedVector
*/
inline constexpr
GenericLengthedVector operator-- (int) noexcept
{
m_lengthIsDirty = true;
return Parent::operator--();
}
#pragma endregion //!increment decrement operators
#pragma endregion //!operators
#pragma region convertor
#pragma endregion //!convertor
};
} /*namespace FoxMath*/
| 31.588477 | 250 | 0.57543 |
Renardjojo
|
852cb2f518a7b520b016b9426084cc6c4714d19a
| 371 |
cpp
|
C++
|
matriz/MATRIZ.cpp
|
ejpcr/libs-c
|
e544e4338ea9f2fe8c57de83045944f38ae06a07
|
[
"MIT"
] | null | null | null |
matriz/MATRIZ.cpp
|
ejpcr/libs-c
|
e544e4338ea9f2fe8c57de83045944f38ae06a07
|
[
"MIT"
] | null | null | null |
matriz/MATRIZ.cpp
|
ejpcr/libs-c
|
e544e4338ea9f2fe8c57de83045944f38ae06a07
|
[
"MIT"
] | null | null | null |
#include <C:\TC\BIN\PRESENTA.CPP>
#include <C:\TC\BIN\CAPTURA.CPP>
#include <C:\TC\BIN\SALIDA.CPP>
#include <C:\TC\BIN\PROCESO.CPP>
#include <C:\TC\BIN\Menu.CPP>
void main()
{entrar();
matriz a,b; double x;
a=crear(a);limpiar(); b=crear(b);limpiar();
a=llenar(a);limpiar(); b=llenar(b);limpiar();
menu(a,b);
getchar();
vaciar(a);vaciar(b);
limpiar(); getchar();
}
| 24.733333 | 46 | 0.6469 |
ejpcr
|
852d241652927fe22d2f76c1f1384a421db67a87
| 1,245 |
cpp
|
C++
|
November/Homeworks/Homework 1/AlgoritmaOdev4/AlgoritmaOdev4.cpp
|
MrMirhan/Algorithm-Class-221-HomeWorks
|
3198fce11a0fd4ea10b576b418cec3a35ffcff2e
|
[
"MIT"
] | 1 |
2020-11-19T09:15:09.000Z
|
2020-11-19T09:15:09.000Z
|
November/Homeworks/Homework 1/AlgoritmaOdev4/AlgoritmaOdev4.cpp
|
MrMirhan/Algorithm-Class-221-HomeWorks
|
3198fce11a0fd4ea10b576b418cec3a35ffcff2e
|
[
"MIT"
] | null | null | null |
November/Homeworks/Homework 1/AlgoritmaOdev4/AlgoritmaOdev4.cpp
|
MrMirhan/Algorithm-Class-221-HomeWorks
|
3198fce11a0fd4ea10b576b418cec3a35ffcff2e
|
[
"MIT"
] | 2 |
2020-11-12T17:37:28.000Z
|
2020-11-21T14:48:49.000Z
|
// AlgoritmaOdev4.cpp : Bu dosya 'main' işlevi içeriyor. Program yürütme orada başlayıp biter.
//
#include <iostream>
#include <string>
using namespace std;
void minmax(int a, int b, int c, int d) {
int min_ab, min_cd, min, max_ab, max_cd, max;
min_ab = a < b ? a : b;
min_cd = c < d ? c : d;
max_ab = a > b ? a : b;
max_cd = c > d ? c : d;
min = min_ab < min_cd ? min_ab : min_cd;
max = max_ab > max_cd ? max_ab : max_cd;
cout << "Max: " << max << endl;
cout << "Min: " << min << endl;
}
int main()
{
setlocale(LC_ALL, "Turkish");
while (true) {
char i;
int a, b, c, d;
while (1) {
cout << "Karşılaştırmak adına 4 sayı giriniz. (Örn: 2, 10, 278, 5210)" << endl;
cin >> a >> b >> c >> d;
if (cin.good()) {
break;
}
else {
cout << "Lütfen sadece sayı giriniz!" << endl;
cin.clear();
cin.ignore(INT_MAX, '\n');
}
}
minmax(a, b, c, d);
cout << "\nİşlemi bitirmek için 'c' yazın. Devam etmek için bir harfe basıp ENTER tuşuna basın.";
cin >> i;
if (i == 'c') {
break;
}
}
}
| 25.408163 | 105 | 0.469076 |
MrMirhan
|
8532d44e9378acd401cf14b9f932d162525658fd
| 7,384 |
cpp
|
C++
|
Driver/Thread/Pthread/ZThreadPthread.cpp
|
paintdream/PaintsNowCore
|
4962b579ff3bc00aa55bb9294a4d722b1bef36ac
|
[
"MIT"
] | 2 |
2020-10-09T07:43:13.000Z
|
2021-09-01T02:09:09.000Z
|
Driver/Thread/Pthread/ZThreadPthread.cpp
|
paintdream/PaintsNowCore
|
4962b579ff3bc00aa55bb9294a4d722b1bef36ac
|
[
"MIT"
] | null | null | null |
Driver/Thread/Pthread/ZThreadPthread.cpp
|
paintdream/PaintsNowCore
|
4962b579ff3bc00aa55bb9294a4d722b1bef36ac
|
[
"MIT"
] | 1 |
2021-03-31T02:02:02.000Z
|
2021-03-31T02:02:02.000Z
|
#include "ZThreadPthread.h"
#if defined(_DEBUG) && defined(_MSC_VER)
#include <Windows.h>
#endif
#if !defined(_MSC_VER) || _MSC_VER > 1200
#define USE_STD_THREAD
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
#else
#include <windows.h>
#include <process.h>
#if _WIN32_WINNT >= 0x0600 // Windows Vista
#define HAS_CONDITION_VARIABLE 1
#else
#define HAS_CONDITION_VARIABLE 0
#endif
#endif
using namespace PaintsNow;
class LockImpl : public IThread::Lock {
public:
#ifdef USE_STD_THREAD
std::mutex cs;
#if defined(_DEBUG) && defined(_MSC_VER)
DWORD owner;
#endif
#else
CRITICAL_SECTION cs;
#if defined(_DEBUG)
DWORD owner;
#endif
#endif
size_t lockCount;
};
class ThreadImpl : public IThread::Thread {
public:
#ifdef USE_STD_THREAD
std::thread thread;
#else
HANDLE thread;
#endif
TWrapper<bool, IThread::Thread*, size_t> proxy;
size_t index;
bool running;
bool managed;
bool reserved[2];
};
class EventImpl : public IThread::Event {
public:
#ifdef USE_STD_THREAD
std::condition_variable cond;
#else
#if HAS_CONDITION_VARIABLE
CONDITION_VARIABLE cond;
#else
HANDLE cond;
#endif
#endif
};
#ifdef USE_STD_THREAD
static void
#else
static UINT _stdcall
#endif
_ThreadProc(void* param)
{
ThreadImpl* thread = reinterpret_cast<ThreadImpl*>(param);
thread->running = true;
bool deleteSelf = thread->proxy(thread, thread->index);
if (deleteSelf) {
thread->running = false;
delete thread;
}
#ifndef USE_STD_THREAD
::_endthreadex(0);
return 0;
#endif
}
ZThreadPthread::ZThreadPthread() {
}
ZThreadPthread::~ZThreadPthread() {
}
void ZThreadPthread::Wait(Thread* th) {
ThreadImpl* t = static_cast<ThreadImpl*>(th);
#ifdef USE_STD_THREAD
t->thread.join();
#else
::WaitForSingleObject(t->thread, INFINITE);
#endif
t->managed = false;
}
IThread::Thread* ZThreadPthread::NewThread(const TWrapper<bool, IThread::Thread*, size_t>& wrapper, size_t index) {
ThreadImpl* t = new ThreadImpl();
t->proxy = wrapper;
t->index = index;
t->managed = true;
#ifdef USE_STD_THREAD
t->thread = std::thread(_ThreadProc, t);
#else
t->thread = (HANDLE)::_beginthreadex(nullptr, 0, _ThreadProc, t, 0, nullptr);
#endif
return t;
}
bool ZThreadPthread::IsThreadRunning(Thread* th) const {
assert(th != nullptr);
ThreadImpl* thread = static_cast<ThreadImpl*>(th);
return thread->running;
}
void ZThreadPthread::DeleteThread(Thread* thread) {
assert(thread != nullptr);
ThreadImpl* t = static_cast<ThreadImpl*>(thread);
if (t->managed) {
#ifdef USE_STD_THREAD
t->thread.detach();
#else
::CloseHandle(t->thread);
#endif
}
delete t;
}
IThread::Lock* ZThreadPthread::NewLock() {
LockImpl* lock = new LockImpl();
lock->lockCount = 0;
#if defined(_DEBUG) && defined(_MSC_VER)
lock->owner = 0;
#endif
#ifndef USE_STD_THREAD
::InitializeCriticalSection(&lock->cs);
#endif
return lock;
}
void ZThreadPthread::DoLock(Lock* l) {
assert(l != nullptr);
LockImpl* lock = static_cast<LockImpl*>(l);
#ifdef USE_STD_THREAD
#if defined(_DEBUG) && defined(_MSC_VER)
assert(lock->owner != ::GetCurrentThreadId());
#endif
lock->cs.lock();
#if defined(_DEBUG) && defined(_MSC_VER)
lock->owner = ::GetCurrentThreadId();
// printf("Thread %d, takes: %p\n", lock->owner, lock);
#endif
#else
::EnterCriticalSection(&lock->cs);
#endif
assert(lock->lockCount == 0);
lock->lockCount++;
}
void ZThreadPthread::UnLock(Lock* l) {
assert(l != nullptr);
LockImpl* lock = static_cast<LockImpl*>(l);
lock->lockCount--;
#ifdef USE_STD_THREAD
#if defined(_DEBUG) && defined(_MSC_VER)
// printf("Thread %d, releases: %p\n", lock->owner, lock);
lock->owner = ::GetCurrentThreadId();
lock->owner = 0;
#endif
lock->cs.unlock();
#else
::LeaveCriticalSection(&lock->cs);
#endif
}
bool ZThreadPthread::TryLock(Lock* l) {
assert(l != nullptr);
LockImpl* lock = static_cast<LockImpl*>(l);
#ifdef USE_STD_THREAD
bool success = lock->cs.try_lock();
#else
bool success = ::TryEnterCriticalSection(&lock->cs) != 0;
#endif
if (success) {
lock->lockCount++;
}
return success;
}
void ZThreadPthread::DeleteLock(Lock* l) {
assert(l != nullptr);
LockImpl* lock = static_cast<LockImpl*>(l);
#ifndef USE_STD_THREAD
::DeleteCriticalSection(&lock->cs);
#endif
delete lock;
}
bool ZThreadPthread::IsLocked(Lock* l) {
assert(l != nullptr);
LockImpl* lock = static_cast<LockImpl*>(l);
return lock->lockCount != 0;
}
IThread::Event* ZThreadPthread::NewEvent() {
EventImpl* ev = new EventImpl();
#ifndef USE_STD_THREAD
#if HAS_CONDITION_VARIABLE
::InitializeConditionVariable(&ev->cond);
#else
ev->cond = ::CreateEvent(NULL, FALSE, FALSE, NULL);
#endif
#endif
return ev;
}
void ZThreadPthread::Signal(Event* event) {
assert(event != nullptr);
EventImpl* ev = static_cast<EventImpl*>(event);
#ifdef USE_STD_THREAD
ev->cond.notify_one();
#else
#if HAS_CONDITION_VARIABLE
::WakeConditionVariable(&ev->cond);
#else
::SetEvent(ev->cond);
#endif
#endif
}
void ZThreadPthread::Wait(Event* event, Lock* lock, size_t timeout) {
assert(event != nullptr);
assert(lock != nullptr);
EventImpl* ev = static_cast<EventImpl*>(event);
LockImpl* l = static_cast<LockImpl*>(lock);
assert(l->lockCount != 0);
l->lockCount--; // it's safe because we still hold this lock
#ifdef USE_STD_THREAD
std::unique_lock<std::mutex> u(l->cs, std::adopt_lock);
ev->cond.wait_for(u, std::chrono::microseconds(timeout));
u.release();
#else
#if HAS_CONDITION_VARIABLE
::SleepConditionVariableCS(&ev->cond, &l->cs, (DWORD)timeout);
#else
::LeaveCriticalSection(&l->cs);
::WaitForSingleObject(ev->cond, (DWORD)timeout); // Windows Event's SetEvent can be called before WaitForSingleObject
::EnterCriticalSection(&l->cs);
#endif
#endif
l->lockCount++; // it's also safe because we has already take lock before returning from pthread_cond_wait
}
void ZThreadPthread::Wait(Event* event, Lock* lock) {
assert(event != nullptr);
assert(lock != nullptr);
EventImpl* ev = static_cast<EventImpl*>(event);
LockImpl* l = static_cast<LockImpl*>(lock);
l->lockCount--; // it's safe because we still hold this lock
#ifdef USE_STD_THREAD
std::unique_lock<std::mutex> u(l->cs, std::adopt_lock);
#if defined(_DEBUG) && defined(_MSC_VER)
l->owner = 0;
#endif
ev->cond.wait(u);
#if defined(_DEBUG) && defined(_MSC_VER)
l->owner = ::GetCurrentThreadId();
#endif
u.release();
#else
#if HAS_CONDITION_VARIABLE
::SleepConditionVariableCS(&ev->cond, &l->cs, INFINITE);
#else
::LeaveCriticalSection(&l->cs);
::WaitForSingleObject(ev->cond, INFINITE);
::EnterCriticalSection(&l->cs);
#endif
#endif
l->lockCount++; // it's also safe because we has already take lock before returning from pthread_cond_wait
}
void ZThreadPthread::DeleteEvent(Event* event) {
assert(event != nullptr);
EventImpl* ev = static_cast<EventImpl*>(event);
#ifndef USE_STD_THREAD
#if !HAS_CONDITION_VARIABLE
::CloseHandle(ev->cond);
#endif
#endif
delete ev;
}
void ZThreadPthread::Sleep(size_t milliseconds) {
#ifdef USE_STD_THREAD
std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
#else
::Sleep((DWORD)milliseconds);
#endif
}
| 22.860681 | 119 | 0.687839 |
paintdream
|
8539c3db25cc2d087a1b4366f5cbb96d5a369184
| 3,585 |
cpp
|
C++
|
DataStructure/cht.cpp
|
rsk0315/codefolio
|
1de990978489f466e1fd47884d4a19de9cc30e02
|
[
"MIT"
] | 1 |
2020-03-20T13:24:30.000Z
|
2020-03-20T13:24:30.000Z
|
DataStructure/cht.cpp
|
rsk0315/codefolio
|
1de990978489f466e1fd47884d4a19de9cc30e02
|
[
"MIT"
] | null | null | null |
DataStructure/cht.cpp
|
rsk0315/codefolio
|
1de990978489f466e1fd47884d4a19de9cc30e02
|
[
"MIT"
] | null | null | null |
template <typename Tp>
class lower_envelope {
public:
using size_type = size_t;
using value_type = Tp;
private:
using interval_type = std::pair<value_type, value_type>;
using line_type = std::pair<value_type, value_type>;
std::map<interval_type, line_type> M_lines;
std::map<line_type, interval_type, std::greater<line_type>> M_intervals;
static value_type const S_min = std::numeric_limits<value_type>::min();
static value_type const S_max = std::numeric_limits<value_type>::max();
static value_type S_divfloor(value_type x, value_type y) {
value_type q = x / y;
value_type r = x % y;
if (r < 0) --q;
return q;
}
static value_type S_divceil(value_type x, value_type y) {
value_type q = x / y;
value_type r = x % y;
if (r > 0) ++q;
return q;
}
public:
bool push(value_type const& a, value_type const& b) {
// try to push y = ax+b; return true if it is actually pushed
if (M_lines.empty()) {
M_lines[interval_type(S_min, S_max)] = line_type(a, b);
M_intervals[line_type(a, b)] = interval_type(S_min, S_max);
return true;
}
auto it = M_intervals.lower_bound(line_type(a, S_min));
value_type lb = S_min;
value_type ub = S_max;
auto it1 = it; // next one
if (it != M_intervals.end() && it->first.first == a) {
if (it->first.second <= b) return false;
M_lines.erase(it->second);
it1 = M_intervals.erase(it);
}
auto it0 = M_intervals.end(); // previous one
if (it != M_intervals.begin()) it0 = std::prev(it);
if (it0 != M_intervals.end()) {
value_type a0, b0;
std::tie(a0, b0) = it0->first;
lb = S_divceil(b-b0, -(a-a0)); // XXX this may cause overflow
}
if (it1 != M_intervals.end()) {
value_type a1, b1;
std::tie(a1, b1) = it1->first;
ub = S_divfloor(b1-b, -(a1-a)); // XXX this may cause overflow
}
if (ub < lb) return false;
if (it0 != M_intervals.end()) {
while (lb <= it0->second.first) {
M_lines.erase(it0->second);
it0 = M_intervals.erase(it0);
if (it0 == M_intervals.begin()) {
it0 = M_intervals.end();
break;
}
--it0;
value_type a0, b0;
std::tie(a0, b0) = it0->first;
lb = S_divceil(b-b0, -(a-a0));
}
}
while (it1 != M_intervals.end() && it1->second.second <= ub) {
M_lines.erase(it1->second);
it1 = M_intervals.erase(it1);
value_type a1, b1;
std::tie(a1, b1) = it1->first;
ub = S_divfloor(b1-b, -(a1-a));
}
if (it0 != M_intervals.end()) {
value_type a0, b0, l0, u0;
std::tie(a0, b0) = it0->first;
std::tie(l0, u0) = it0->second;
it0->second.second = std::min(u0, lb-1);
M_lines.erase(interval_type(l0, u0));
M_lines[it0->second] = it0->first;
}
if (it1 != M_intervals.end()) {
value_type a1, b1, l1, u1;
std::tie(a1, b1) = it1->first;
std::tie(l1, u1) = it1->second;
it1->second.first = std::max(l1, ub+1);
M_lines.erase(interval_type(l1, u1));
M_lines[it1->second] = it1->first;
}
M_lines[interval_type(lb, ub)] = line_type(a, b);
M_intervals[line_type(a, b)] = interval_type(lb, ub);
return true;
}
value_type get(value_type const& x) {
// return the minimum value at x
value_type a, b;
std::tie(a, b) = (--M_lines.upper_bound(interval_type(x, S_max)))->second;
return a*x + b;
}
};
template <typename Tp> Tp const lower_envelope<Tp>::S_min;
template <typename Tp> Tp const lower_envelope<Tp>::S_max;
| 29.875 | 78 | 0.591353 |
rsk0315
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.